source: trunk/src/STMath.cpp@ 2173

Last change on this file since 2173 was 2163, checked in by Malte Marquarding, 13 years ago

Remove various compiler warnings

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 167.2 KB
RevLine 
[805]1//
2// C++ Implementation: STMath
3//
4// Description:
5//
6//
7// Author: Malte Marquarding <asap@atnf.csiro.au>, (C) 2006
8//
9// Copyright: See COPYING file that comes with this distribution
10//
11//
[38]12
[330]13#include <casa/iomanip.h>
[805]14#include <casa/Exceptions/Error.h>
15#include <casa/Containers/Block.h>
[81]16#include <casa/BasicSL/String.h>
[805]17#include <casa/Arrays/MaskArrLogi.h>
18#include <casa/Arrays/MaskArrMath.h>
19#include <casa/Arrays/ArrayLogical.h>
[81]20#include <casa/Arrays/ArrayMath.h>
[1066]21#include <casa/Arrays/Slice.h>
22#include <casa/Arrays/Slicer.h>
[805]23#include <casa/Containers/RecordField.h>
24#include <tables/Tables/TableRow.h>
25#include <tables/Tables/TableVector.h>
[917]26#include <tables/Tables/TabVecMath.h>
[805]27#include <tables/Tables/ExprNode.h>
28#include <tables/Tables/TableRecord.h>
[1140]29#include <tables/Tables/TableParse.h>
[805]30#include <tables/Tables/ReadAsciiTable.h>
[1140]31#include <tables/Tables/TableIter.h>
32#include <tables/Tables/TableCopy.h>
[1192]33#include <scimath/Mathematics/FFTServer.h>
[2]34
[262]35#include <lattices/Lattices/LatticeUtilities.h>
36
[917]37#include <coordinates/Coordinates/SpectralCoordinate.h>
38#include <coordinates/Coordinates/CoordinateSystem.h>
39#include <coordinates/Coordinates/CoordinateUtil.h>
40#include <coordinates/Coordinates/FrequencyAligner.h>
41
[177]42#include <scimath/Mathematics/VectorKernel.h>
43#include <scimath/Mathematics/Convolver.h>
[234]44#include <scimath/Functionals/Polynomial.h>
[177]45
[1819]46#include <atnf/PKSIO/SrcType.h>
47
48#include <casa/Logging/LogIO.h>
49#include <sstream>
50
[38]51#include "MathUtils.h"
[805]52#include "RowAccumulator.h"
[878]53#include "STAttr.h"
[1391]54#include "STSelector.h"
[2]55
[1569]56#include "STMath.h"
[805]57using namespace casa;
[2]58
[83]59using namespace asap;
[2]60
[1819]61// tolerance for direction comparison (rad)
62#define TOL_OTF 1.0e-15
63#define TOL_POINT 2.9088821e-4 // 1 arcmin
64
[805]65STMath::STMath(bool insitu) :
66 insitu_(insitu)
[716]67{
68}
[170]69
70
[805]71STMath::~STMath()
[170]72{
73}
74
[805]75CountedPtr<Scantable>
[977]76STMath::average( const std::vector<CountedPtr<Scantable> >& in,
[858]77 const std::vector<bool>& mask,
[805]78 const std::string& weight,
[977]79 const std::string& avmode)
[262]80{
[1819]81 LogIO os( LogOrigin( "STMath", "average()", WHERE ) ) ;
[977]82 if ( avmode == "SCAN" && in.size() != 1 )
[1066]83 throw(AipsError("Can't perform 'SCAN' averaging on multiple tables.\n"
84 "Use merge first."));
[805]85 WeightType wtype = stringToWeight(weight);
[926]86
[1819]87 // check if OTF observation
88 String obstype = in[0]->getHeader().obstype ;
89 Double tol = 0.0 ;
90 if ( (obstype.find( "OTF" ) != String::npos) || (obstype.find( "OBSERVE_TARGET" ) != String::npos) ) {
91 tol = TOL_OTF ;
92 }
93 else {
94 tol = TOL_POINT ;
95 }
96
[805]97 // output
98 // clone as this is non insitu
99 bool insitu = insitu_;
100 setInsitu(false);
[977]101 CountedPtr< Scantable > out = getScantable(in[0], true);
[805]102 setInsitu(insitu);
[977]103 std::vector<CountedPtr<Scantable> >::const_iterator stit = in.begin();
[862]104 ++stit;
[977]105 while ( stit != in.end() ) {
[862]106 out->appendToHistoryTable((*stit)->history());
107 ++stit;
108 }
[294]109
[805]110 Table& tout = out->table();
[701]111
[805]112 /// @todo check if all scantables are conformant
[294]113
[805]114 ArrayColumn<Float> specColOut(tout,"SPECTRA");
115 ArrayColumn<uChar> flagColOut(tout,"FLAGTRA");
116 ArrayColumn<Float> tsysColOut(tout,"TSYS");
117 ScalarColumn<Double> mjdColOut(tout,"TIME");
118 ScalarColumn<Double> intColOut(tout,"INTERVAL");
[1008]119 ScalarColumn<uInt> cycColOut(tout,"CYCLENO");
[1145]120 ScalarColumn<uInt> scanColOut(tout,"SCANNO");
[262]121
[805]122 // set up the output table rows. These are based on the structure of the
[862]123 // FIRST scantable in the vector
[977]124 const Table& baset = in[0]->table();
[262]125
[805]126 Block<String> cols(3);
127 cols[0] = String("BEAMNO");
128 cols[1] = String("IFNO");
129 cols[2] = String("POLNO");
130 if ( avmode == "SOURCE" ) {
131 cols.resize(4);
132 cols[3] = String("SRCNAME");
[488]133 }
[977]134 if ( avmode == "SCAN" && in.size() == 1) {
[1819]135 //cols.resize(4);
136 //cols[3] = String("SCANNO");
137 cols.resize(5);
138 cols[3] = String("SRCNAME");
139 cols[4] = String("SCANNO");
[2]140 }
[805]141 uInt outrowCount = 0;
142 TableIterator iter(baset, cols);
[1819]143// int count = 0 ;
[805]144 while (!iter.pastEnd()) {
145 Table subt = iter.table();
[1819]146// // copy the first row of this selection into the new table
147// tout.addRow();
148// TableCopy::copyRows(tout, subt, outrowCount, 0, 1);
149// // re-index to 0
150// if ( avmode != "SCAN" && avmode != "SOURCE" ) {
151// scanColOut.put(outrowCount, uInt(0));
152// }
153// ++outrowCount;
154 MDirection::ScalarColumn dircol ;
155 dircol.attach( subt, "DIRECTION" ) ;
156 Int length = subt.nrow() ;
157 vector< Vector<Double> > dirs ;
158 vector<int> indexes ;
159 for ( Int i = 0 ; i < length ; i++ ) {
160 Vector<Double> t = dircol(i).getAngle(Unit(String("rad"))).getValue() ;
161 //os << << count++ << ": " ;
162 //os << "[" << t[0] << "," << t[1] << "]" << LogIO::POST ;
163 bool adddir = true ;
164 for ( uInt j = 0 ; j < dirs.size() ; j++ ) {
165 //if ( allTrue( t == dirs[j] ) ) {
166 Double dx = t[0] - dirs[j][0] ;
167 Double dy = t[1] - dirs[j][1] ;
168 Double dd = sqrt( dx * dx + dy * dy ) ;
169 //if ( allNearAbs( t, dirs[j], tol ) ) {
170 if ( dd <= tol ) {
171 adddir = false ;
172 break ;
173 }
174 }
175 if ( adddir ) {
176 dirs.push_back( t ) ;
177 indexes.push_back( i ) ;
178 }
[1145]179 }
[1819]180 uInt rowNum = dirs.size() ;
181 tout.addRow( rowNum ) ;
182 for ( uInt i = 0 ; i < rowNum ; i++ ) {
183 TableCopy::copyRows( tout, subt, outrowCount+i, indexes[i], 1 ) ;
184 // re-index to 0
185 if ( avmode != "SCAN" && avmode != "SOURCE" ) {
186 scanColOut.put(outrowCount+i, uInt(0));
187 }
188 }
189 outrowCount += rowNum ;
[805]190 ++iter;
[144]191 }
[805]192 RowAccumulator acc(wtype);
[858]193 Vector<Bool> cmask(mask);
194 acc.setUserMask(cmask);
[805]195 ROTableRow row(tout);
196 ROArrayColumn<Float> specCol, tsysCol;
197 ROArrayColumn<uChar> flagCol;
198 ROScalarColumn<Double> mjdCol, intCol;
199 ROScalarColumn<Int> scanIDCol;
[144]200
[1333]201 Vector<uInt> rowstodelete;
202
[805]203 for (uInt i=0; i < tout.nrow(); ++i) {
[996]204 for ( int j=0; j < int(in.size()); ++j ) {
[977]205 const Table& tin = in[j]->table();
[805]206 const TableRecord& rec = row.get(i);
207 ROScalarColumn<Double> tmp(tin, "TIME");
208 Double td;tmp.get(0,td);
[2125]209 Table basesubt = tin( tin.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
210 && tin.col("IFNO") == Int(rec.asuInt("IFNO"))
211 && tin.col("POLNO") == Int(rec.asuInt("POLNO")) );
[805]212 Table subt;
213 if ( avmode == "SOURCE") {
[2125]214 subt = basesubt( basesubt.col("SRCNAME") == rec.asString("SRCNAME"));
[805]215 } else if (avmode == "SCAN") {
[2125]216 subt = basesubt( basesubt.col("SRCNAME") == rec.asString("SRCNAME")
217 && basesubt.col("SCANNO") == Int(rec.asuInt("SCANNO")) );
[805]218 } else {
219 subt = basesubt;
220 }
[1819]221
222 vector<uInt> removeRows ;
223 uInt nrsubt = subt.nrow() ;
224 for ( uInt irow = 0 ; irow < nrsubt ; irow++ ) {
225 //if ( !allTrue((subt.col("DIRECTION").getArrayDouble(TableExprId(irow)))==rec.asArrayDouble("DIRECTION")) ) {
226 Vector<Double> x0 = (subt.col("DIRECTION").getArrayDouble(TableExprId(irow))) ;
227 Vector<Double> x1 = rec.asArrayDouble("DIRECTION") ;
228 double dx = x0[0] - x1[0] ;
229 double dy = x0[0] - x1[0] ;
230 Double dd = sqrt( dx * dx + dy * dy ) ;
231 //if ( !allNearAbs((subt.col("DIRECTION").getArrayDouble(TableExprId(irow))), rec.asArrayDouble("DIRECTION"), tol ) ) {
232 if ( dd > tol ) {
233 removeRows.push_back( irow ) ;
234 }
235 }
236 if ( removeRows.size() != 0 ) {
237 subt.removeRow( removeRows ) ;
238 }
239
240 if ( nrsubt == removeRows.size() )
241 throw(AipsError("Averaging data is empty.")) ;
242
[805]243 specCol.attach(subt,"SPECTRA");
244 flagCol.attach(subt,"FLAGTRA");
245 tsysCol.attach(subt,"TSYS");
246 intCol.attach(subt,"INTERVAL");
247 mjdCol.attach(subt,"TIME");
248 Vector<Float> spec,tsys;
249 Vector<uChar> flag;
250 Double inter,time;
251 for (uInt k = 0; k < subt.nrow(); ++k ) {
252 flagCol.get(k, flag);
253 Vector<Bool> bflag(flag.shape());
254 convertArray(bflag, flag);
[1314]255 /*
[805]256 if ( allEQ(bflag, True) ) {
[1314]257 continue;//don't accumulate
[144]258 }
[1314]259 */
[805]260 specCol.get(k, spec);
261 tsysCol.get(k, tsys);
262 intCol.get(k, inter);
263 mjdCol.get(k, time);
264 // spectrum has to be added last to enable weighting by the other values
265 acc.add(spec, !bflag, tsys, inter, time);
266 }
[2125]267
268 // If there exists a channel at which all the input spectra are masked,
269 // spec has 'nan' values for that channel and it may affect the following
270 // processes. To avoid this, replacing 'nan' values in spec with
271 // weighted-mean of all spectra in the following line.
272 // (done for CAS-2776, 2011/04/07 by Wataru Kawasaki)
273 acc.replaceNaN();
[805]274 }
[1333]275 const Vector<Bool>& msk = acc.getMask();
276 if ( allEQ(msk, False) ) {
277 uint n = rowstodelete.nelements();
278 rowstodelete.resize(n+1, True);
279 rowstodelete[n] = i;
280 continue;
281 }
[805]282 //write out
[1819]283 if (acc.state()) {
284 Vector<uChar> flg(msk.shape());
285 convertArray(flg, !msk);
[2125]286 for (uInt k = 0; k < flg.nelements(); ++k) {
287 uChar userFlag = 1 << 7;
288 if (msk[k]==True) userFlag = 0 << 7;
289 flg(k) = userFlag;
290 }
291
[1819]292 flagColOut.put(i, flg);
293 specColOut.put(i, acc.getSpectrum());
294 tsysColOut.put(i, acc.getTsys());
295 intColOut.put(i, acc.getInterval());
296 mjdColOut.put(i, acc.getTime());
297 // we should only have one cycle now -> reset it to be 0
298 // frequency switched data has different CYCLENO for different IFNO
299 // which requires resetting this value
300 cycColOut.put(i, uInt(0));
301 } else {
302 ostringstream oss;
303 oss << "For output row="<<i<<", all input rows of data are flagged. no averaging" << endl;
304 pushLog(String(oss));
305 }
[805]306 acc.reset();
[144]307 }
[2135]308
[1333]309 if (rowstodelete.nelements() > 0) {
[1819]310 os << rowstodelete << LogIO::POST ;
[1333]311 tout.removeRow(rowstodelete);
312 if (tout.nrow() == 0) {
313 throw(AipsError("Can't average fully flagged data."));
314 }
315 }
[805]316 return out;
[2]317}
[9]318
[1069]319CountedPtr< Scantable >
[2163]320STMath::averageChannel( const CountedPtr < Scantable > & in,
[1078]321 const std::string & mode,
322 const std::string& avmode )
[1069]323{
[2163]324 (void) mode; // currently unused
[1819]325 // check if OTF observation
326 String obstype = in->getHeader().obstype ;
327 Double tol = 0.0 ;
328 if ( obstype.find( "OTF" ) != String::npos ) {
329 tol = TOL_OTF ;
330 }
331 else {
332 tol = TOL_POINT ;
333 }
334
[1069]335 // clone as this is non insitu
336 bool insitu = insitu_;
337 setInsitu(false);
338 CountedPtr< Scantable > out = getScantable(in, true);
339 setInsitu(insitu);
340 Table& tout = out->table();
341 ArrayColumn<Float> specColOut(tout,"SPECTRA");
342 ArrayColumn<uChar> flagColOut(tout,"FLAGTRA");
343 ArrayColumn<Float> tsysColOut(tout,"TSYS");
[1140]344 ScalarColumn<uInt> scanColOut(tout,"SCANNO");
[1232]345 ScalarColumn<Double> intColOut(tout, "INTERVAL");
[1140]346 Table tmp = in->table().sort("BEAMNO");
[1069]347 Block<String> cols(3);
348 cols[0] = String("BEAMNO");
349 cols[1] = String("IFNO");
350 cols[2] = String("POLNO");
[1078]351 if ( avmode == "SCAN") {
352 cols.resize(4);
353 cols[3] = String("SCANNO");
354 }
[1069]355 uInt outrowCount = 0;
356 uChar userflag = 1 << 7;
[1140]357 TableIterator iter(tmp, cols);
[1069]358 while (!iter.pastEnd()) {
359 Table subt = iter.table();
360 ROArrayColumn<Float> specCol, tsysCol;
361 ROArrayColumn<uChar> flagCol;
[1232]362 ROScalarColumn<Double> intCol(subt, "INTERVAL");
[1069]363 specCol.attach(subt,"SPECTRA");
364 flagCol.attach(subt,"FLAGTRA");
365 tsysCol.attach(subt,"TSYS");
[1819]366// tout.addRow();
367// TableCopy::copyRows(tout, subt, outrowCount, 0, 1);
368// if ( avmode != "SCAN") {
369// scanColOut.put(outrowCount, uInt(0));
370// }
371// Vector<Float> tmp;
372// specCol.get(0, tmp);
373// uInt nchan = tmp.nelements();
374// // have to do channel by channel here as MaskedArrMath
375// // doesn't have partialMedians
376// Vector<uChar> flags = flagCol.getColumn(Slicer(Slice(0)));
377// Vector<Float> outspec(nchan);
378// Vector<uChar> outflag(nchan,0);
379// Vector<Float> outtsys(1);/// @fixme when tsys is channel based
380// for (uInt i=0; i<nchan; ++i) {
381// Vector<Float> specs = specCol.getColumn(Slicer(Slice(i)));
382// MaskedArray<Float> ma = maskedArray(specs,flags);
383// outspec[i] = median(ma);
384// if ( allEQ(ma.getMask(), False) )
385// outflag[i] = userflag;// flag data
386// }
387// outtsys[0] = median(tsysCol.getColumn());
388// specColOut.put(outrowCount, outspec);
389// flagColOut.put(outrowCount, outflag);
390// tsysColOut.put(outrowCount, outtsys);
391// Double intsum = sum(intCol.getColumn());
392// intColOut.put(outrowCount, intsum);
393// ++outrowCount;
394// ++iter;
395 MDirection::ScalarColumn dircol ;
396 dircol.attach( subt, "DIRECTION" ) ;
397 Int length = subt.nrow() ;
398 vector< Vector<Double> > dirs ;
399 vector<int> indexes ;
400 for ( Int i = 0 ; i < length ; i++ ) {
401 Vector<Double> t = dircol(i).getAngle(Unit(String("rad"))).getValue() ;
402 bool adddir = true ;
403 for ( uInt j = 0 ; j < dirs.size() ; j++ ) {
404 //if ( allTrue( t == dirs[j] ) ) {
405 Double dx = t[0] - dirs[j][0] ;
406 Double dy = t[1] - dirs[j][1] ;
407 Double dd = sqrt( dx * dx + dy * dy ) ;
408 //if ( allNearAbs( t, dirs[j], tol ) ) {
409 if ( dd <= tol ) {
410 adddir = false ;
411 break ;
412 }
413 }
414 if ( adddir ) {
415 dirs.push_back( t ) ;
416 indexes.push_back( i ) ;
417 }
[1140]418 }
[1819]419 uInt rowNum = dirs.size() ;
420 tout.addRow( rowNum );
421 for ( uInt i = 0 ; i < rowNum ; i++ ) {
422 TableCopy::copyRows(tout, subt, outrowCount+i, indexes[i], 1) ;
423 if ( avmode != "SCAN") {
424 //scanColOut.put(outrowCount+i, uInt(0));
425 }
[1069]426 }
[1819]427 MDirection::ScalarColumn dircolOut ;
428 dircolOut.attach( tout, "DIRECTION" ) ;
429 for ( uInt irow = 0 ; irow < rowNum ; irow++ ) {
430 Vector<Double> t = dircolOut(outrowCount+irow).getAngle(Unit(String("rad"))).getValue() ;
431 Vector<Float> tmp;
432 specCol.get(0, tmp);
433 uInt nchan = tmp.nelements();
434 // have to do channel by channel here as MaskedArrMath
435 // doesn't have partialMedians
436 Vector<uChar> flags = flagCol.getColumn(Slicer(Slice(0)));
437 // mask spectra for different DIRECTION
438 for ( uInt jrow = 0 ; jrow < subt.nrow() ; jrow++ ) {
439 Vector<Double> direction = dircol(jrow).getAngle(Unit(String("rad"))).getValue() ;
440 //if ( t[0] != direction[0] || t[1] != direction[1] ) {
441 Double dx = t[0] - direction[0] ;
442 Double dy = t[1] - direction[1] ;
443 Double dd = sqrt( dx * dx + dy * dy ) ;
444 //if ( !allNearAbs( t, direction, tol ) ) {
445 if ( dd > tol ) {
446 flags[jrow] = userflag ;
447 }
448 }
449 Vector<Float> outspec(nchan);
450 Vector<uChar> outflag(nchan,0);
451 Vector<Float> outtsys(1);/// @fixme when tsys is channel based
452 for (uInt i=0; i<nchan; ++i) {
453 Vector<Float> specs = specCol.getColumn(Slicer(Slice(i)));
454 MaskedArray<Float> ma = maskedArray(specs,flags);
455 outspec[i] = median(ma);
456 if ( allEQ(ma.getMask(), False) )
457 outflag[i] = userflag;// flag data
458 }
459 outtsys[0] = median(tsysCol.getColumn());
460 specColOut.put(outrowCount+irow, outspec);
461 flagColOut.put(outrowCount+irow, outflag);
462 tsysColOut.put(outrowCount+irow, outtsys);
463 Vector<Double> integ = intCol.getColumn() ;
464 MaskedArray<Double> mi = maskedArray( integ, flags ) ;
465 Double intsum = sum(mi);
466 intColOut.put(outrowCount+irow, intsum);
467 }
468 outrowCount += rowNum ;
[1069]469 ++iter;
470 }
471 return out;
472}
473
[805]474CountedPtr< Scantable > STMath::getScantable(const CountedPtr< Scantable >& in,
475 bool droprows)
[185]476{
[1505]477 if (insitu_) {
478 return in;
479 }
[805]480 else {
481 // clone
[1505]482 return CountedPtr<Scantable>(new Scantable(*in, Bool(droprows)));
[234]483 }
[805]484}
[234]485
[805]486CountedPtr< Scantable > STMath::unaryOperate( const CountedPtr< Scantable >& in,
487 float val,
488 const std::string& mode,
489 bool tsys )
490{
491 CountedPtr< Scantable > out = getScantable(in, false);
492 Table& tab = out->table();
493 ArrayColumn<Float> specCol(tab,"SPECTRA");
494 ArrayColumn<Float> tsysCol(tab,"TSYS");
[2143]495 if (mode=="DIV") val = 1.0/val ;
496 else if (mode=="SUB") val *= -1.0 ;
[805]497 for (uInt i=0; i<tab.nrow(); ++i) {
498 Vector<Float> spec;
499 Vector<Float> ts;
500 specCol.get(i, spec);
501 tsysCol.get(i, ts);
[1308]502 if (mode == "MUL" || mode == "DIV") {
[2143]503 //if (mode == "DIV") val = 1.0/val;
[805]504 spec *= val;
505 specCol.put(i, spec);
506 if ( tsys ) {
507 ts *= val;
508 tsysCol.put(i, ts);
509 }
[1308]510 } else if ( mode == "ADD" || mode == "SUB") {
[2143]511 //if (mode == "SUB") val *= -1.0;
[805]512 spec += val;
513 specCol.put(i, spec);
514 if ( tsys ) {
515 ts += val;
516 tsysCol.put(i, ts);
517 }
518 }
[234]519 }
[805]520 return out;
521}
[234]522
[1819]523CountedPtr< Scantable > STMath::arrayOperate( const CountedPtr< Scantable >& in,
524 const std::vector<float> val,
525 const std::string& mode,
526 const std::string& opmode,
527 bool tsys )
528{
529 CountedPtr< Scantable > out ;
530 if ( opmode == "channel" ) {
531 out = arrayOperateChannel( in, val, mode, tsys ) ;
532 }
533 else if ( opmode == "row" ) {
534 out = arrayOperateRow( in, val, mode, tsys ) ;
535 }
536 else {
537 throw( AipsError( "Unknown array operation mode." ) ) ;
538 }
539 return out ;
540}
541
542CountedPtr< Scantable > STMath::arrayOperateChannel( const CountedPtr< Scantable >& in,
543 const std::vector<float> val,
544 const std::string& mode,
545 bool tsys )
546{
547 if ( val.size() == 1 ){
548 return unaryOperate( in, val[0], mode, tsys ) ;
549 }
550
551 // conformity of SPECTRA and TSYS
552 if ( tsys ) {
553 TableIterator titer(in->table(), "IFNO");
554 while ( !titer.pastEnd() ) {
555 ArrayColumn<Float> specCol( in->table(), "SPECTRA" ) ;
556 ArrayColumn<Float> tsysCol( in->table(), "TSYS" ) ;
557 Array<Float> spec = specCol.getColumn() ;
558 Array<Float> ts = tsysCol.getColumn() ;
559 if ( !spec.conform( ts ) ) {
560 throw( AipsError( "SPECTRA and TSYS must conform in shape if you want to apply operation on Tsys." ) ) ;
561 }
562 titer.next() ;
563 }
564 }
565
566 // check if all spectra in the scantable have the same number of channel
567 vector<uInt> nchans;
568 vector<uInt> ifnos = in->getIFNos() ;
569 for ( uInt i = 0 ; i < ifnos.size() ; i++ ) {
570 nchans.push_back( in->nchan( ifnos[i] ) ) ;
571 }
572 Vector<uInt> mchans( nchans ) ;
573 if ( anyNE( mchans, mchans[0] ) ) {
574 throw( AipsError("All spectra in the input scantable must have the same number of channel for vector operation." ) ) ;
575 }
576
577 // check if vector size is equal to nchan
578 Vector<Float> fact( val ) ;
579 if ( fact.nelements() != mchans[0] ) {
580 throw( AipsError("Vector size must be 1 or be same as number of channel.") ) ;
581 }
582
583 // check divided by zero
584 if ( ( mode == "DIV" ) && anyEQ( fact, (float)0.0 ) ) {
585 throw( AipsError("Divided by zero is not recommended." ) ) ;
586 }
587
588 CountedPtr< Scantable > out = getScantable(in, false);
589 Table& tab = out->table();
590 ArrayColumn<Float> specCol(tab,"SPECTRA");
591 ArrayColumn<Float> tsysCol(tab,"TSYS");
[2143]592 if (mode == "DIV") fact = (float)1.0 / fact;
593 else if (mode == "SUB") fact *= (float)-1.0 ;
[1819]594 for (uInt i=0; i<tab.nrow(); ++i) {
595 Vector<Float> spec;
596 Vector<Float> ts;
597 specCol.get(i, spec);
598 tsysCol.get(i, ts);
599 if (mode == "MUL" || mode == "DIV") {
[2143]600 //if (mode == "DIV") fact = (float)1.0 / fact;
[1819]601 spec *= fact;
602 specCol.put(i, spec);
603 if ( tsys ) {
604 ts *= fact;
605 tsysCol.put(i, ts);
606 }
607 } else if ( mode == "ADD" || mode == "SUB") {
[2143]608 //if (mode == "SUB") fact *= (float)-1.0 ;
[1819]609 spec += fact;
610 specCol.put(i, spec);
611 if ( tsys ) {
612 ts += fact;
613 tsysCol.put(i, ts);
614 }
615 }
616 }
617 return out;
618}
619
620CountedPtr< Scantable > STMath::arrayOperateRow( const CountedPtr< Scantable >& in,
621 const std::vector<float> val,
622 const std::string& mode,
623 bool tsys )
624{
625 if ( val.size() == 1 ) {
626 return unaryOperate( in, val[0], mode, tsys ) ;
627 }
628
629 // conformity of SPECTRA and TSYS
630 if ( tsys ) {
631 TableIterator titer(in->table(), "IFNO");
632 while ( !titer.pastEnd() ) {
633 ArrayColumn<Float> specCol( in->table(), "SPECTRA" ) ;
634 ArrayColumn<Float> tsysCol( in->table(), "TSYS" ) ;
635 Array<Float> spec = specCol.getColumn() ;
636 Array<Float> ts = tsysCol.getColumn() ;
637 if ( !spec.conform( ts ) ) {
638 throw( AipsError( "SPECTRA and TSYS must conform in shape if you want to apply operation on Tsys." ) ) ;
639 }
640 titer.next() ;
641 }
642 }
643
644 // check if vector size is equal to nrow
645 Vector<Float> fact( val ) ;
[2125]646 if (fact.nelements() != uInt(in->nrow())) {
[1819]647 throw( AipsError("Vector size must be 1 or be same as number of row.") ) ;
648 }
649
650 // check divided by zero
651 if ( ( mode == "DIV" ) && anyEQ( fact, (float)0.0 ) ) {
652 throw( AipsError("Divided by zero is not recommended." ) ) ;
653 }
654
655 CountedPtr< Scantable > out = getScantable(in, false);
656 Table& tab = out->table();
657 ArrayColumn<Float> specCol(tab,"SPECTRA");
658 ArrayColumn<Float> tsysCol(tab,"TSYS");
659 if (mode == "DIV") fact = (float)1.0 / fact;
660 if (mode == "SUB") fact *= (float)-1.0 ;
661 for (uInt i=0; i<tab.nrow(); ++i) {
662 Vector<Float> spec;
663 Vector<Float> ts;
664 specCol.get(i, spec);
665 tsysCol.get(i, ts);
666 if (mode == "MUL" || mode == "DIV") {
667 spec *= fact[i];
668 specCol.put(i, spec);
669 if ( tsys ) {
670 ts *= fact[i];
671 tsysCol.put(i, ts);
672 }
673 } else if ( mode == "ADD" || mode == "SUB") {
674 spec += fact[i];
675 specCol.put(i, spec);
676 if ( tsys ) {
677 ts += fact[i];
678 tsysCol.put(i, ts);
679 }
680 }
681 }
682 return out;
683}
684
685CountedPtr< Scantable > STMath::array2dOperate( const CountedPtr< Scantable >& in,
686 const std::vector< std::vector<float> > val,
687 const std::string& mode,
688 bool tsys )
689{
690 // conformity of SPECTRA and TSYS
691 if ( tsys ) {
692 TableIterator titer(in->table(), "IFNO");
693 while ( !titer.pastEnd() ) {
694 ArrayColumn<Float> specCol( in->table(), "SPECTRA" ) ;
695 ArrayColumn<Float> tsysCol( in->table(), "TSYS" ) ;
696 Array<Float> spec = specCol.getColumn() ;
697 Array<Float> ts = tsysCol.getColumn() ;
698 if ( !spec.conform( ts ) ) {
699 throw( AipsError( "SPECTRA and TSYS must conform in shape if you want to apply operation on Tsys." ) ) ;
700 }
701 titer.next() ;
702 }
703 }
704
705 // some checks
706 vector<uInt> nchans;
[2125]707 for (Int i = 0 ; i < in->nrow() ; i++) {
708 nchans.push_back((in->getSpectrum(i)).size());
[1819]709 }
710 //Vector<uInt> mchans( nchans ) ;
711 vector< Vector<Float> > facts ;
712 for ( uInt i = 0 ; i < nchans.size() ; i++ ) {
713 Vector<Float> tmp( val[i] ) ;
714 // check divided by zero
715 if ( ( mode == "DIV" ) && anyEQ( tmp, (float)0.0 ) ) {
716 throw( AipsError("Divided by zero is not recommended." ) ) ;
717 }
718 // conformity check
719 if ( tmp.nelements() != nchans[i] ) {
720 stringstream ss ;
721 ss << "Row " << i << ": Vector size must be same as number of channel." ;
722 throw( AipsError( ss.str() ) ) ;
723 }
724 facts.push_back( tmp ) ;
725 }
726
727
728 CountedPtr< Scantable > out = getScantable(in, false);
729 Table& tab = out->table();
730 ArrayColumn<Float> specCol(tab,"SPECTRA");
731 ArrayColumn<Float> tsysCol(tab,"TSYS");
732 for (uInt i=0; i<tab.nrow(); ++i) {
733 Vector<Float> fact = facts[i] ;
734 Vector<Float> spec;
735 Vector<Float> ts;
736 specCol.get(i, spec);
737 tsysCol.get(i, ts);
738 if (mode == "MUL" || mode == "DIV") {
739 if (mode == "DIV") fact = (float)1.0 / fact;
740 spec *= fact;
741 specCol.put(i, spec);
742 if ( tsys ) {
743 ts *= fact;
744 tsysCol.put(i, ts);
745 }
746 } else if ( mode == "ADD" || mode == "SUB") {
747 if (mode == "SUB") fact *= (float)-1.0 ;
748 spec += fact;
749 specCol.put(i, spec);
750 if ( tsys ) {
751 ts += fact;
752 tsysCol.put(i, ts);
753 }
754 }
755 }
756 return out;
757}
758
[1569]759CountedPtr<Scantable> STMath::binaryOperate(const CountedPtr<Scantable>& left,
760 const CountedPtr<Scantable>& right,
[1308]761 const std::string& mode)
762{
763 bool insitu = insitu_;
764 if ( ! left->conformant(*right) ) {
765 throw(AipsError("'left' and 'right' scantables are not conformant."));
766 }
767 setInsitu(false);
768 CountedPtr< Scantable > out = getScantable(left, false);
769 setInsitu(insitu);
770 Table& tout = out->table();
771 Block<String> coln(5);
772 coln[0] = "SCANNO"; coln[1] = "CYCLENO"; coln[2] = "BEAMNO";
773 coln[3] = "IFNO"; coln[4] = "POLNO";
774 Table tmpl = tout.sort(coln);
775 Table tmpr = right->table().sort(coln);
776 ArrayColumn<Float> lspecCol(tmpl,"SPECTRA");
777 ROArrayColumn<Float> rspecCol(tmpr,"SPECTRA");
778 ArrayColumn<uChar> lflagCol(tmpl,"FLAGTRA");
779 ROArrayColumn<uChar> rflagCol(tmpr,"FLAGTRA");
780
781 for (uInt i=0; i<tout.nrow(); ++i) {
782 Vector<Float> lspecvec, rspecvec;
783 Vector<uChar> lflagvec, rflagvec;
784 lspecvec = lspecCol(i); rspecvec = rspecCol(i);
785 lflagvec = lflagCol(i); rflagvec = rflagCol(i);
786 MaskedArray<Float> mleft = maskedArray(lspecvec, lflagvec);
787 MaskedArray<Float> mright = maskedArray(rspecvec, rflagvec);
788 if (mode == "ADD") {
789 mleft += mright;
790 } else if ( mode == "SUB") {
791 mleft -= mright;
792 } else if ( mode == "MUL") {
793 mleft *= mright;
794 } else if ( mode == "DIV") {
795 mleft /= mright;
796 } else {
797 throw(AipsError("Illegal binary operator"));
798 }
799 lspecCol.put(i, mleft.getArray());
800 }
801 return out;
802}
803
804
805
[805]806MaskedArray<Float> STMath::maskedArray( const Vector<Float>& s,
807 const Vector<uChar>& f)
808{
809 Vector<Bool> mask;
810 mask.resize(f.shape());
811 convertArray(mask, f);
812 return MaskedArray<Float>(s,!mask);
813}
[248]814
[1819]815MaskedArray<Double> STMath::maskedArray( const Vector<Double>& s,
816 const Vector<uChar>& f)
817{
818 Vector<Bool> mask;
819 mask.resize(f.shape());
820 convertArray(mask, f);
821 return MaskedArray<Double>(s,!mask);
822}
823
[805]824Vector<uChar> STMath::flagsFromMA(const MaskedArray<Float>& ma)
825{
826 const Vector<Bool>& m = ma.getMask();
827 Vector<uChar> flags(m.shape());
828 convertArray(flags, !m);
829 return flags;
830}
[234]831
[1066]832CountedPtr< Scantable > STMath::autoQuotient( const CountedPtr< Scantable >& in,
833 const std::string & mode,
834 bool preserve )
[805]835{
836 /// @todo make other modes available
837 /// modes should be "nearest", "pair"
838 // make this operation non insitu
[2163]839 (void) mode; //currently unused
[805]840 const Table& tin = in->table();
[1819]841 Table ons = tin(tin.col("SRCTYPE") == Int(SrcType::PSON));
842 Table offs = tin(tin.col("SRCTYPE") == Int(SrcType::PSOFF));
[805]843 if ( offs.nrow() == 0 )
844 throw(AipsError("No 'off' scans present."));
845 // put all "on" scans into output table
[701]846
[805]847 bool insitu = insitu_;
848 setInsitu(false);
849 CountedPtr< Scantable > out = getScantable(in, true);
850 setInsitu(insitu);
851 Table& tout = out->table();
[248]852
[805]853 TableCopy::copyRows(tout, ons);
854 TableRow row(tout);
855 ROScalarColumn<Double> offtimeCol(offs, "TIME");
856 ArrayColumn<Float> outspecCol(tout, "SPECTRA");
857 ROArrayColumn<Float> outtsysCol(tout, "TSYS");
858 ArrayColumn<uChar> outflagCol(tout, "FLAGTRA");
859 for (uInt i=0; i < tout.nrow(); ++i) {
860 const TableRecord& rec = row.get(i);
861 Double ontime = rec.asDouble("TIME");
[1321]862 Table presel = offs(offs.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
863 && offs.col("IFNO") == Int(rec.asuInt("IFNO"))
864 && offs.col("POLNO") == Int(rec.asuInt("POLNO")) );
865 ROScalarColumn<Double> offtimeCol(presel, "TIME");
866
[805]867 Double mindeltat = min(abs(offtimeCol.getColumn() - ontime));
[1259]868 // Timestamp may vary within a cycle ???!!!
[1321]869 // increase this by 0.01 sec in case of rounding errors...
[1259]870 // There might be a better way to do this.
[1321]871 // fix to this fix. TIME is MJD, so 1.0d not 1.0s
872 mindeltat += 0.01/24./60./60.;
873 Table sel = presel( abs(presel.col("TIME")-ontime) <= mindeltat);
[780]874
[1259]875 if ( sel.nrow() < 1 ) {
876 throw(AipsError("No closest in time found... This could be a rounding "
877 "issue. Try quotient instead."));
878 }
[805]879 TableRow offrow(sel);
880 const TableRecord& offrec = offrow.get(0);//should only be one row
881 RORecordFieldPtr< Array<Float> > specoff(offrec, "SPECTRA");
882 RORecordFieldPtr< Array<Float> > tsysoff(offrec, "TSYS");
883 RORecordFieldPtr< Array<uChar> > flagoff(offrec, "FLAGTRA");
884 /// @fixme this assumes tsys is a scalar not vector
885 Float tsysoffscalar = (*tsysoff)(IPosition(1,0));
886 Vector<Float> specon, tsyson;
887 outtsysCol.get(i, tsyson);
888 outspecCol.get(i, specon);
889 Vector<uChar> flagon;
890 outflagCol.get(i, flagon);
891 MaskedArray<Float> mon = maskedArray(specon, flagon);
892 MaskedArray<Float> moff = maskedArray(*specoff, *flagoff);
893 MaskedArray<Float> quot = (tsysoffscalar * mon / moff);
894 if (preserve) {
895 quot -= tsysoffscalar;
896 } else {
897 quot -= tsyson[0];
[701]898 }
[805]899 outspecCol.put(i, quot.getArray());
900 outflagCol.put(i, flagsFromMA(quot));
901 }
[926]902 // renumber scanno
903 TableIterator it(tout, "SCANNO");
904 uInt i = 0;
905 while ( !it.pastEnd() ) {
906 Table t = it.table();
907 TableVector<uInt> vec(t, "SCANNO");
908 vec = i;
909 ++i;
910 ++it;
911 }
[805]912 return out;
913}
[234]914
[1066]915
916CountedPtr< Scantable > STMath::quotient( const CountedPtr< Scantable > & on,
917 const CountedPtr< Scantable > & off,
918 bool preserve )
919{
920 bool insitu = insitu_;
[1069]921 if ( ! on->conformant(*off) ) {
922 throw(AipsError("'on' and 'off' scantables are not conformant."));
923 }
[1066]924 setInsitu(false);
925 CountedPtr< Scantable > out = getScantable(on, false);
926 setInsitu(insitu);
927 Table& tout = out->table();
928 const Table& toff = off->table();
929 TableIterator sit(tout, "SCANNO");
930 TableIterator s2it(toff, "SCANNO");
931 while ( !sit.pastEnd() ) {
932 Table ton = sit.table();
933 TableRow row(ton);
934 Table t = s2it.table();
935 ArrayColumn<Float> outspecCol(ton, "SPECTRA");
936 ROArrayColumn<Float> outtsysCol(ton, "TSYS");
937 ArrayColumn<uChar> outflagCol(ton, "FLAGTRA");
938 for (uInt i=0; i < ton.nrow(); ++i) {
939 const TableRecord& rec = row.get(i);
940 Table offsel = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
941 && t.col("IFNO") == Int(rec.asuInt("IFNO"))
942 && t.col("POLNO") == Int(rec.asuInt("POLNO")) );
[1145]943 if ( offsel.nrow() == 0 )
944 throw AipsError("STMath::quotient: no matching off");
[1066]945 TableRow offrow(offsel);
946 const TableRecord& offrec = offrow.get(0);//should be ncycles - take first
947 RORecordFieldPtr< Array<Float> > specoff(offrec, "SPECTRA");
948 RORecordFieldPtr< Array<Float> > tsysoff(offrec, "TSYS");
949 RORecordFieldPtr< Array<uChar> > flagoff(offrec, "FLAGTRA");
950 Float tsysoffscalar = (*tsysoff)(IPosition(1,0));
951 Vector<Float> specon, tsyson;
952 outtsysCol.get(i, tsyson);
953 outspecCol.get(i, specon);
954 Vector<uChar> flagon;
955 outflagCol.get(i, flagon);
956 MaskedArray<Float> mon = maskedArray(specon, flagon);
957 MaskedArray<Float> moff = maskedArray(*specoff, *flagoff);
958 MaskedArray<Float> quot = (tsysoffscalar * mon / moff);
959 if (preserve) {
960 quot -= tsysoffscalar;
961 } else {
962 quot -= tsyson[0];
963 }
964 outspecCol.put(i, quot.getArray());
965 outflagCol.put(i, flagsFromMA(quot));
966 }
967 ++sit;
968 ++s2it;
969 // take the first off for each on scan which doesn't have a
970 // matching off scan
971 // non <= noff: matching pairs, non > noff matching pairs then first off
972 if ( s2it.pastEnd() ) s2it.reset();
973 }
974 return out;
975}
976
[1391]977// dototalpower (migration of GBTIDL procedure dototalpower.pro)
978// calibrate the CAL on-off pair. It calculate Tsys and average CAL on-off subintegrations
979// do it for each cycles in a specific scan.
980CountedPtr< Scantable > STMath::dototalpower( const CountedPtr< Scantable >& calon,
981 const CountedPtr< Scantable >& caloff, Float tcal )
982{
983if ( ! calon->conformant(*caloff) ) {
984 throw(AipsError("'CAL on' and 'CAL off' scantables are not conformant."));
985 }
986 setInsitu(false);
987 CountedPtr< Scantable > out = getScantable(caloff, false);
988 Table& tout = out->table();
989 const Table& tcon = calon->table();
990 Vector<Float> tcalout;
991 Vector<Float> tcalout2; //debug
[1066]992
[1391]993 if ( tout.nrow() != tcon.nrow() ) {
994 throw(AipsError("Mismatch in number of rows to form cal on - off pair."));
995 }
996 // iteration by scanno or cycle no.
997 TableIterator sit(tout, "SCANNO");
998 TableIterator s2it(tcon, "SCANNO");
999 while ( !sit.pastEnd() ) {
1000 Table toff = sit.table();
1001 TableRow row(toff);
1002 Table t = s2it.table();
1003 ScalarColumn<Double> outintCol(toff, "INTERVAL");
1004 ArrayColumn<Float> outspecCol(toff, "SPECTRA");
1005 ArrayColumn<Float> outtsysCol(toff, "TSYS");
1006 ArrayColumn<uChar> outflagCol(toff, "FLAGTRA");
1007 ROScalarColumn<uInt> outtcalIdCol(toff, "TCAL_ID");
1008 ROScalarColumn<uInt> outpolCol(toff, "POLNO");
1009 ROScalarColumn<Double> onintCol(t, "INTERVAL");
1010 ROArrayColumn<Float> onspecCol(t, "SPECTRA");
1011 ROArrayColumn<Float> ontsysCol(t, "TSYS");
1012 ROArrayColumn<uChar> onflagCol(t, "FLAGTRA");
1013 //ROScalarColumn<uInt> ontcalIdCol(t, "TCAL_ID");
1014
1015 for (uInt i=0; i < toff.nrow(); ++i) {
1016 //skip these checks -> assumes the data order are the same between the cal on off pairs
1017 //
1018 Vector<Float> specCalon, specCaloff;
1019 // to store scalar (mean) tsys
1020 Vector<Float> tsysout(1);
1021 uInt tcalId, polno;
1022 Double offint, onint;
1023 outpolCol.get(i, polno);
1024 outspecCol.get(i, specCaloff);
1025 onspecCol.get(i, specCalon);
1026 Vector<uChar> flagCaloff, flagCalon;
1027 outflagCol.get(i, flagCaloff);
1028 onflagCol.get(i, flagCalon);
1029 outtcalIdCol.get(i, tcalId);
1030 outintCol.get(i, offint);
1031 onintCol.get(i, onint);
1032 // caluculate mean Tsys
1033 uInt nchan = specCaloff.nelements();
1034 // percentage of edge cut off
1035 uInt pc = 10;
1036 uInt bchan = nchan/pc;
1037 uInt echan = nchan-bchan;
1038
1039 Slicer chansl(IPosition(1,bchan-1), IPosition(1,echan-1), IPosition(1,1),Slicer::endIsLast);
1040 Vector<Float> testsubsp = specCaloff(chansl);
1041 MaskedArray<Float> spoff = maskedArray( specCaloff(chansl),flagCaloff(chansl) );
1042 MaskedArray<Float> spon = maskedArray( specCalon(chansl),flagCalon(chansl) );
1043 MaskedArray<Float> spdiff = spon-spoff;
1044 uInt noff = spoff.nelementsValid();
1045 //uInt non = spon.nelementsValid();
1046 uInt ndiff = spdiff.nelementsValid();
1047 Float meantsys;
1048
1049/**
1050 Double subspec, subdiff;
1051 uInt usednchan;
1052 subspec = 0;
1053 subdiff = 0;
1054 usednchan = 0;
1055 for(uInt k=(bchan-1); k<echan; k++) {
1056 subspec += specCaloff[k];
1057 subdiff += static_cast<Double>(specCalon[k]-specCaloff[k]);
1058 ++usednchan;
1059 }
1060**/
1061 // get tcal if input tcal <= 0
1062 String tcalt;
1063 Float tcalUsed;
1064 tcalUsed = tcal;
1065 if ( tcal <= 0.0 ) {
1066 caloff->tcal().getEntry(tcalt, tcalout, tcalId);
[2004]1067// if (polno<=3) {
1068// tcalUsed = tcalout[polno];
1069// }
1070// else {
1071// tcalUsed = tcalout[0];
1072// }
1073 if ( tcalout.size() == 1 )
1074 tcalUsed = tcalout[0] ;
1075 else if ( tcalout.size() == nchan )
1076 tcalUsed = mean(tcalout) ;
[1391]1077 else {
[2004]1078 uInt ipol = polno ;
1079 if ( ipol > 3 ) ipol = 0 ;
1080 tcalUsed = tcalout[ipol] ;
[1391]1081 }
1082 }
1083
1084 Float meanoff;
1085 Float meandiff;
1086 if (noff && ndiff) {
1087 //Debug
1088 //if(noff!=ndiff) cerr<<"noff and ndiff is not equal"<<endl;
[1819]1089 //LogIO os( LogOrigin( "STMath", "dototalpower()", WHERE ) ) ;
1090 //if(noff!=ndiff) os<<"noff and ndiff is not equal"<<LogIO::POST;
[1391]1091 meanoff = sum(spoff)/noff;
1092 meandiff = sum(spdiff)/ndiff;
1093 meantsys= (meanoff/meandiff )*tcalUsed + tcalUsed/2;
1094 }
1095 else {
1096 meantsys=1;
1097 }
1098
1099 tsysout[0] = Float(meantsys);
1100 MaskedArray<Float> mcaloff = maskedArray(specCaloff, flagCaloff);
1101 MaskedArray<Float> mcalon = maskedArray(specCalon, flagCalon);
1102 MaskedArray<Float> sig = Float(0.5) * (mcaloff + mcalon);
1103 //uInt ncaloff = mcaloff.nelementsValid();
1104 //uInt ncalon = mcalon.nelementsValid();
1105
1106 outintCol.put(i, offint+onint);
1107 outspecCol.put(i, sig.getArray());
1108 outflagCol.put(i, flagsFromMA(sig));
1109 outtsysCol.put(i, tsysout);
1110 }
1111 ++sit;
1112 ++s2it;
1113 }
1114 return out;
1115}
1116
1117//dosigref - migrated from GBT IDL's dosigref.pro, do calibration of position switch
1118// observatiions.
1119// input: sig and ref scantables, and an optional boxcar smoothing width(default width=0,
1120// no smoothing).
1121// output: resultant scantable [= (sig-ref/ref)*tsys]
1122CountedPtr< Scantable > STMath::dosigref( const CountedPtr < Scantable >& sig,
1123 const CountedPtr < Scantable >& ref,
1124 int smoothref,
1125 casa::Float tsysv,
1126 casa::Float tau )
1127{
1128if ( ! ref->conformant(*sig) ) {
1129 throw(AipsError("'sig' and 'ref' scantables are not conformant."));
1130 }
1131 setInsitu(false);
1132 CountedPtr< Scantable > out = getScantable(sig, false);
1133 CountedPtr< Scantable > smref;
1134 if ( smoothref > 1 ) {
1135 float fsmoothref = static_cast<float>(smoothref);
1136 std::string inkernel = "boxcar";
1137 smref = smooth(ref, inkernel, fsmoothref );
1138 ostringstream oss;
1139 oss<<"Applied smoothing of "<<fsmoothref<<" on the reference."<<endl;
1140 pushLog(String(oss));
1141 }
1142 else {
1143 smref = ref;
1144 }
1145 Table& tout = out->table();
1146 const Table& tref = smref->table();
1147 if ( tout.nrow() != tref.nrow() ) {
1148 throw(AipsError("Mismatch in number of rows to form on-source and reference pair."));
1149 }
1150 // iteration by scanno? or cycle no.
1151 TableIterator sit(tout, "SCANNO");
1152 TableIterator s2it(tref, "SCANNO");
1153 while ( !sit.pastEnd() ) {
1154 Table ton = sit.table();
1155 Table t = s2it.table();
1156 ScalarColumn<Double> outintCol(ton, "INTERVAL");
1157 ArrayColumn<Float> outspecCol(ton, "SPECTRA");
1158 ArrayColumn<Float> outtsysCol(ton, "TSYS");
1159 ArrayColumn<uChar> outflagCol(ton, "FLAGTRA");
1160 ArrayColumn<Float> refspecCol(t, "SPECTRA");
1161 ROScalarColumn<Double> refintCol(t, "INTERVAL");
1162 ROArrayColumn<Float> reftsysCol(t, "TSYS");
1163 ArrayColumn<uChar> refflagCol(t, "FLAGTRA");
1164 ROScalarColumn<Float> refelevCol(t, "ELEVATION");
1165 for (uInt i=0; i < ton.nrow(); ++i) {
1166
1167 Double onint, refint;
1168 Vector<Float> specon, specref;
1169 // to store scalar (mean) tsys
1170 Vector<Float> tsysref;
1171 outintCol.get(i, onint);
1172 refintCol.get(i, refint);
1173 outspecCol.get(i, specon);
1174 refspecCol.get(i, specref);
1175 Vector<uChar> flagref, flagon;
1176 outflagCol.get(i, flagon);
1177 refflagCol.get(i, flagref);
1178 reftsysCol.get(i, tsysref);
1179
1180 Float tsysrefscalar;
1181 if ( tsysv > 0.0 ) {
1182 ostringstream oss;
1183 Float elev;
1184 refelevCol.get(i, elev);
1185 oss << "user specified Tsys = " << tsysv;
1186 // do recalc elevation if EL = 0
1187 if ( elev == 0 ) {
1188 throw(AipsError("EL=0, elevation data is missing."));
1189 } else {
1190 if ( tau <= 0.0 ) {
1191 throw(AipsError("Valid tau is not supplied."));
1192 } else {
1193 tsysrefscalar = tsysv * exp(tau/elev);
1194 }
1195 }
1196 oss << ", corrected (for El) tsys= "<<tsysrefscalar;
1197 pushLog(String(oss));
1198 }
1199 else {
1200 tsysrefscalar = tsysref[0];
1201 }
1202 //get quotient spectrum
1203 MaskedArray<Float> mref = maskedArray(specref, flagref);
1204 MaskedArray<Float> mon = maskedArray(specon, flagon);
1205 MaskedArray<Float> specres = tsysrefscalar*((mon - mref)/mref);
1206 Double resint = onint*refint*smoothref/(onint+refint*smoothref);
1207
1208 //Debug
1209 //cerr<<"Tsys used="<<tsysrefscalar<<endl;
[1819]1210 //LogIO os( LogOrigin( "STMath", "dosigref", WHERE ) ) ;
1211 //os<<"Tsys used="<<tsysrefscalar<<LogIO::POST;
[1391]1212 // fill the result, replay signal tsys by reference tsys
1213 outintCol.put(i, resint);
1214 outspecCol.put(i, specres.getArray());
1215 outflagCol.put(i, flagsFromMA(specres));
1216 outtsysCol.put(i, tsysref);
1217 }
1218 ++sit;
1219 ++s2it;
1220 }
1221 return out;
1222}
1223
1224CountedPtr< Scantable > STMath::donod(const casa::CountedPtr<Scantable>& s,
1225 const std::vector<int>& scans,
1226 int smoothref,
1227 casa::Float tsysv,
1228 casa::Float tau,
1229 casa::Float tcal )
1230
1231{
1232 setInsitu(false);
1233 STSelector sel;
[1819]1234 std::vector<int> scan1, scan2, beams, types;
[1391]1235 std::vector< vector<int> > scanpair;
[1819]1236 //std::vector<string> calstate;
1237 std::vector<int> calstate;
[1391]1238 String msg;
1239
1240 CountedPtr< Scantable > s1b1on, s1b1off, s1b2on, s1b2off;
1241 CountedPtr< Scantable > s2b1on, s2b1off, s2b2on, s2b2off;
1242
1243 std::vector< CountedPtr< Scantable > > sctables;
1244 sctables.push_back(s1b1on);
1245 sctables.push_back(s1b1off);
1246 sctables.push_back(s1b2on);
1247 sctables.push_back(s1b2off);
1248 sctables.push_back(s2b1on);
1249 sctables.push_back(s2b1off);
1250 sctables.push_back(s2b2on);
1251 sctables.push_back(s2b2off);
1252
1253 //check scanlist
1254 int n=s->checkScanInfo(scans);
1255 if (n==1) {
1256 throw(AipsError("Incorrect scan pairs. "));
1257 }
1258
1259 // Assume scans contain only a pair of consecutive scan numbers.
1260 // It is assumed that first beam, b1, is on target.
1261 // There is no check if the first beam is on or not.
1262 if ( scans.size()==1 ) {
1263 scan1.push_back(scans[0]);
1264 scan2.push_back(scans[0]+1);
1265 } else if ( scans.size()==2 ) {
1266 scan1.push_back(scans[0]);
1267 scan2.push_back(scans[1]);
1268 } else {
1269 if ( scans.size()%2 == 0 ) {
1270 for (uInt i=0; i<scans.size(); i++) {
1271 if (i%2 == 0) {
1272 scan1.push_back(scans[i]);
1273 }
1274 else {
1275 scan2.push_back(scans[i]);
1276 }
1277 }
1278 } else {
1279 throw(AipsError("Odd numbers of scans, cannot form pairs."));
1280 }
1281 }
1282 scanpair.push_back(scan1);
1283 scanpair.push_back(scan2);
[1819]1284 //calstate.push_back("*calon");
1285 //calstate.push_back("*[^calon]");
1286 calstate.push_back(SrcType::NODCAL);
1287 calstate.push_back(SrcType::NOD);
[1391]1288 CountedPtr< Scantable > ws = getScantable(s, false);
1289 uInt l=0;
1290 while ( l < sctables.size() ) {
1291 for (uInt i=0; i < 2; i++) {
1292 for (uInt j=0; j < 2; j++) {
1293 for (uInt k=0; k < 2; k++) {
1294 sel.reset();
1295 sel.setScans(scanpair[i]);
[1819]1296 //sel.setName(calstate[k]);
1297 types.clear();
1298 types.push_back(calstate[k]);
1299 sel.setTypes(types);
[1391]1300 beams.clear();
1301 beams.push_back(j);
1302 sel.setBeams(beams);
1303 ws->setSelection(sel);
1304 sctables[l]= getScantable(ws, false);
1305 l++;
1306 }
1307 }
1308 }
1309 }
1310
1311 // replace here by splitData or getData functionality
1312 CountedPtr< Scantable > sig1;
1313 CountedPtr< Scantable > ref1;
1314 CountedPtr< Scantable > sig2;
1315 CountedPtr< Scantable > ref2;
1316 CountedPtr< Scantable > calb1;
1317 CountedPtr< Scantable > calb2;
1318
1319 msg=String("Processing dototalpower for subset of the data");
1320 ostringstream oss1;
1321 oss1 << msg << endl;
1322 pushLog(String(oss1));
1323 // Debug for IRC CS data
1324 //float tcal1=7.0;
1325 //float tcal2=4.0;
1326 sig1 = dototalpower(sctables[0], sctables[1], tcal=tcal);
1327 ref1 = dototalpower(sctables[2], sctables[3], tcal=tcal);
1328 ref2 = dototalpower(sctables[4], sctables[5], tcal=tcal);
1329 sig2 = dototalpower(sctables[6], sctables[7], tcal=tcal);
1330
1331 // correction of user-specified tsys for elevation here
1332
1333 // dosigref calibration
1334 msg=String("Processing dosigref for subset of the data");
1335 ostringstream oss2;
1336 oss2 << msg << endl;
1337 pushLog(String(oss2));
1338 calb1=dosigref(sig1,ref2,smoothref,tsysv,tau);
1339 calb2=dosigref(sig2,ref1,smoothref,tsysv,tau);
1340
1341 // iteration by scanno or cycle no.
1342 Table& tcalb1 = calb1->table();
1343 Table& tcalb2 = calb2->table();
1344 TableIterator sit(tcalb1, "SCANNO");
1345 TableIterator s2it(tcalb2, "SCANNO");
1346 while ( !sit.pastEnd() ) {
1347 Table t1 = sit.table();
1348 Table t2= s2it.table();
1349 ArrayColumn<Float> outspecCol(t1, "SPECTRA");
1350 ArrayColumn<Float> outtsysCol(t1, "TSYS");
1351 ArrayColumn<uChar> outflagCol(t1, "FLAGTRA");
1352 ScalarColumn<Double> outintCol(t1, "INTERVAL");
1353 ArrayColumn<Float> t2specCol(t2, "SPECTRA");
1354 ROArrayColumn<Float> t2tsysCol(t2, "TSYS");
1355 ArrayColumn<uChar> t2flagCol(t2, "FLAGTRA");
1356 ROScalarColumn<Double> t2intCol(t2, "INTERVAL");
1357 for (uInt i=0; i < t1.nrow(); ++i) {
1358 Vector<Float> spec1, spec2;
1359 // to store scalar (mean) tsys
1360 Vector<Float> tsys1, tsys2;
1361 Vector<uChar> flag1, flag2;
1362 Double tint1, tint2;
1363 outspecCol.get(i, spec1);
1364 t2specCol.get(i, spec2);
1365 outflagCol.get(i, flag1);
1366 t2flagCol.get(i, flag2);
1367 outtsysCol.get(i, tsys1);
1368 t2tsysCol.get(i, tsys2);
1369 outintCol.get(i, tint1);
1370 t2intCol.get(i, tint2);
1371 // average
1372 // assume scalar tsys for weights
1373 Float wt1, wt2, tsyssq1, tsyssq2;
1374 tsyssq1 = tsys1[0]*tsys1[0];
1375 tsyssq2 = tsys2[0]*tsys2[0];
1376 wt1 = Float(tint1)/tsyssq1;
1377 wt2 = Float(tint2)/tsyssq2;
1378 Float invsumwt=1/(wt1+wt2);
1379 MaskedArray<Float> mspec1 = maskedArray(spec1, flag1);
1380 MaskedArray<Float> mspec2 = maskedArray(spec2, flag2);
1381 MaskedArray<Float> avspec = invsumwt * (wt1*mspec1 + wt2*mspec2);
1382 //Array<Float> avtsys = Float(0.5) * (tsys1 + tsys2);
1383 // cerr<< "Tsys1="<<tsys1<<" Tsys2="<<tsys2<<endl;
[1819]1384 // LogIO os( LogOrigin( "STMath", "donod", WHERE ) ) ;
1385 // os<< "Tsys1="<<tsys1<<" Tsys2="<<tsys2<<LogIO::POST;
[1391]1386 tsys1[0] = sqrt(tsyssq1 + tsyssq2);
1387 Array<Float> avtsys = tsys1;
1388
1389 outspecCol.put(i, avspec.getArray());
1390 outflagCol.put(i, flagsFromMA(avspec));
1391 outtsysCol.put(i, avtsys);
1392 }
1393 ++sit;
1394 ++s2it;
1395 }
1396 return calb1;
1397}
1398
1399//GBTIDL version of frequency switched data calibration
1400CountedPtr< Scantable > STMath::dofs( const CountedPtr< Scantable >& s,
1401 const std::vector<int>& scans,
1402 int smoothref,
1403 casa::Float tsysv,
1404 casa::Float tau,
1405 casa::Float tcal )
1406{
1407
1408
[2163]1409 (void) scans; //currently unused
[1391]1410 STSelector sel;
1411 CountedPtr< Scantable > ws = getScantable(s, false);
1412 CountedPtr< Scantable > sig, sigwcal, ref, refwcal;
[1819]1413 CountedPtr< Scantable > calsig, calref, out, out1, out2;
1414 Bool nofold=False;
1415 vector<int> types ;
[1391]1416
1417 //split the data
[1819]1418 //sel.setName("*_fs");
1419 types.push_back( SrcType::FSON ) ;
1420 sel.setTypes( types ) ;
[1391]1421 ws->setSelection(sel);
1422 sig = getScantable(ws,false);
1423 sel.reset();
[1819]1424 types.clear() ;
1425 //sel.setName("*_fs_calon");
1426 types.push_back( SrcType::FONCAL ) ;
1427 sel.setTypes( types ) ;
[1391]1428 ws->setSelection(sel);
1429 sigwcal = getScantable(ws,false);
1430 sel.reset();
[1819]1431 types.clear() ;
1432 //sel.setName("*_fsr");
1433 types.push_back( SrcType::FSOFF ) ;
1434 sel.setTypes( types ) ;
[1391]1435 ws->setSelection(sel);
1436 ref = getScantable(ws,false);
1437 sel.reset();
[1819]1438 types.clear() ;
1439 //sel.setName("*_fsr_calon");
1440 types.push_back( SrcType::FOFFCAL ) ;
1441 sel.setTypes( types ) ;
[1391]1442 ws->setSelection(sel);
1443 refwcal = getScantable(ws,false);
[1819]1444 sel.reset() ;
1445 types.clear() ;
[1391]1446
1447 calsig = dototalpower(sigwcal, sig, tcal=tcal);
1448 calref = dototalpower(refwcal, ref, tcal=tcal);
1449
[1819]1450 out1=dosigref(calsig,calref,smoothref,tsysv,tau);
1451 out2=dosigref(calref,calsig,smoothref,tsysv,tau);
[1391]1452
[1819]1453 Table& tabout1=out1->table();
1454 Table& tabout2=out2->table();
1455 ROScalarColumn<uInt> freqidCol1(tabout1, "FREQ_ID");
1456 ScalarColumn<uInt> freqidCol2(tabout2, "FREQ_ID");
1457 ROArrayColumn<Float> specCol(tabout2, "SPECTRA");
1458 Vector<Float> spec; specCol.get(0, spec);
1459 uInt nchan = spec.nelements();
1460 uInt freqid1; freqidCol1.get(0,freqid1);
1461 uInt freqid2; freqidCol2.get(0,freqid2);
1462 Double rp1, rp2, rv1, rv2, inc1, inc2;
1463 out1->frequencies().getEntry(rp1, rv1, inc1, freqid1);
1464 out2->frequencies().getEntry(rp2, rv2, inc2, freqid2);
1465 //cerr << out1->frequencies().table().nrow() << " " << out2->frequencies().table().nrow() << endl ;
1466 //LogIO os( LogOrigin( "STMath", "dofs()", WHERE ) ) ;
1467 //os << out1->frequencies().table().nrow() << " " << out2->frequencies().table().nrow() << LogIO::POST ;
1468 if (rp1==rp2) {
1469 Double foffset = rv1 - rv2;
1470 uInt choffset = static_cast<uInt>(foffset/abs(inc2));
1471 if (choffset >= nchan) {
1472 //cerr<<"out-band frequency switching, no folding"<<endl;
1473 LogIO os( LogOrigin( "STMath", "dofs()", WHERE ) ) ;
1474 os<<"out-band frequency switching, no folding"<<LogIO::POST;
1475 nofold = True;
1476 }
1477 }
1478
1479 if (nofold) {
1480 std::vector< CountedPtr< Scantable > > tabs;
1481 tabs.push_back(out1);
1482 tabs.push_back(out2);
1483 out = merge(tabs);
1484 }
1485 else {
1486 //out = out1;
1487 Double choffset = ( rv1 - rv2 ) / inc2 ;
1488 out = dofold( out1, out2, choffset ) ;
1489 }
1490
[1391]1491 return out;
1492}
1493
[1819]1494CountedPtr<Scantable> STMath::dofold( const CountedPtr<Scantable> &sig,
1495 const CountedPtr<Scantable> &ref,
1496 Double choffset,
1497 Double choffset2 )
1498{
1499 LogIO os( LogOrigin( "STMath", "dofold", WHERE ) ) ;
1500 os << "choffset=" << choffset << " choffset2=" << choffset2 << LogIO::POST ;
[1391]1501
[1819]1502 // output scantable
1503 CountedPtr<Scantable> out = getScantable( sig, false ) ;
1504
1505 // separate choffset to integer part and decimal part
1506 Int ioffset = (Int)choffset ;
1507 Double doffset = choffset - ioffset ;
1508 Int ioffset2 = (Int)choffset2 ;
1509 Double doffset2 = choffset2 - ioffset2 ;
1510 os << "ioffset=" << ioffset << " doffset=" << doffset << LogIO::POST ;
1511 os << "ioffset2=" << ioffset2 << " doffset2=" << doffset2 << LogIO::POST ;
1512
1513 // get column
1514 ROArrayColumn<Float> specCol1( sig->table(), "SPECTRA" ) ;
1515 ROArrayColumn<Float> specCol2( ref->table(), "SPECTRA" ) ;
1516 ROArrayColumn<Float> tsysCol1( sig->table(), "TSYS" ) ;
1517 ROArrayColumn<Float> tsysCol2( ref->table(), "TSYS" ) ;
1518 ROArrayColumn<uChar> flagCol1( sig->table(), "FLAGTRA" ) ;
1519 ROArrayColumn<uChar> flagCol2( ref->table(), "FLAGTRA" ) ;
1520 ROScalarColumn<Double> mjdCol1( sig->table(), "TIME" ) ;
1521 ROScalarColumn<Double> mjdCol2( ref->table(), "TIME" ) ;
1522 ROScalarColumn<Double> intervalCol1( sig->table(), "INTERVAL" ) ;
1523 ROScalarColumn<Double> intervalCol2( ref->table(), "INTERVAL" ) ;
1524
1525 // check
1526 if ( ioffset == 0 ) {
1527 LogIO os( LogOrigin( "STMath", "dofold()", WHERE ) ) ;
1528 os << "channel offset is zero, no folding" << LogIO::POST ;
1529 return out ;
1530 }
1531 int nchan = ref->nchan() ;
1532 if ( abs(ioffset) >= nchan ) {
1533 LogIO os( LogOrigin( "STMath", "dofold()", WHERE ) ) ;
1534 os << "out-band frequency switching, no folding" << LogIO::POST ;
1535 return out ;
1536 }
1537
1538 // attach column for output scantable
1539 ArrayColumn<Float> specColOut( out->table(), "SPECTRA" ) ;
1540 ArrayColumn<uChar> flagColOut( out->table(), "FLAGTRA" ) ;
1541 ArrayColumn<Float> tsysColOut( out->table(), "TSYS" ) ;
1542 ScalarColumn<Double> mjdColOut( out->table(), "TIME" ) ;
1543 ScalarColumn<Double> intervalColOut( out->table(), "INTERVAL" ) ;
1544 ScalarColumn<uInt> fidColOut( out->table(), "FREQ_ID" ) ;
1545
1546 // for each row
1547 // assume that the data order are same between sig and ref
1548 RowAccumulator acc( asap::W_TINTSYS ) ;
1549 for ( int i = 0 ; i < sig->nrow() ; i++ ) {
1550 // get values
1551 Vector<Float> spsig ;
1552 specCol1.get( i, spsig ) ;
1553 Vector<Float> spref ;
1554 specCol2.get( i, spref ) ;
1555 Vector<Float> tsyssig ;
1556 tsysCol1.get( i, tsyssig ) ;
1557 Vector<Float> tsysref ;
1558 tsysCol2.get( i, tsysref ) ;
1559 Vector<uChar> flagsig ;
1560 flagCol1.get( i, flagsig ) ;
1561 Vector<uChar> flagref ;
1562 flagCol2.get( i, flagref ) ;
1563 Double timesig ;
1564 mjdCol1.get( i, timesig ) ;
1565 Double timeref ;
1566 mjdCol2.get( i, timeref ) ;
1567 Double intsig ;
1568 intervalCol1.get( i, intsig ) ;
1569 Double intref ;
1570 intervalCol2.get( i, intref ) ;
1571
1572 // shift reference spectra
1573 int refchan = spref.nelements() ;
1574 Vector<Float> sspref( spref.nelements() ) ;
1575 Vector<Float> stsysref( tsysref.nelements() ) ;
1576 Vector<uChar> sflagref( flagref.nelements() ) ;
1577 if ( ioffset > 0 ) {
1578 // SPECTRA and FLAGTRA
1579 for ( int j = 0 ; j < refchan-ioffset ; j++ ) {
1580 sspref[j] = spref[j+ioffset] ;
1581 sflagref[j] = flagref[j+ioffset] ;
1582 }
1583 for ( int j = refchan-ioffset ; j < refchan ; j++ ) {
1584 sspref[j] = spref[j-refchan+ioffset] ;
1585 sflagref[j] = flagref[j-refchan+ioffset] ;
1586 }
1587 spref = sspref.copy() ;
1588 flagref = sflagref.copy() ;
1589 for ( int j = 0 ; j < refchan - 1 ; j++ ) {
1590 sspref[j] = doffset * spref[j+1] + ( 1.0 - doffset ) * spref[j] ;
1591 sflagref[j] = flagref[j+1] + flagref[j] ;
1592 }
1593 sspref[refchan-1] = doffset * spref[0] + ( 1.0 - doffset ) * spref[refchan-1] ;
1594 sflagref[refchan-1] = flagref[0] + flagref[refchan-1] ;
1595
1596 // TSYS
1597 if ( spref.nelements() == tsysref.nelements() ) {
1598 for ( int j = 0 ; j < refchan-ioffset ; j++ ) {
1599 stsysref[j] = tsysref[j+ioffset] ;
1600 }
1601 for ( int j = refchan-ioffset ; j < refchan ; j++ ) {
1602 stsysref[j] = tsysref[j-refchan+ioffset] ;
1603 }
1604 tsysref = stsysref.copy() ;
1605 for ( int j = 0 ; j < refchan - 1 ; j++ ) {
1606 stsysref[j] = doffset * tsysref[j+1] + ( 1.0 - doffset ) * tsysref[j] ;
1607 }
1608 stsysref[refchan-1] = doffset * tsysref[0] + ( 1.0 - doffset ) * tsysref[refchan-1] ;
1609 }
1610 }
1611 else {
1612 // SPECTRA and FLAGTRA
1613 for ( int j = 0 ; j < abs(ioffset) ; j++ ) {
1614 sspref[j] = spref[refchan+ioffset+j] ;
1615 sflagref[j] = flagref[refchan+ioffset+j] ;
1616 }
1617 for ( int j = abs(ioffset) ; j < refchan ; j++ ) {
1618 sspref[j] = spref[j+ioffset] ;
1619 sflagref[j] = flagref[j+ioffset] ;
1620 }
1621 spref = sspref.copy() ;
1622 flagref = sflagref.copy() ;
1623 sspref[0] = doffset * spref[refchan-1] + ( 1.0 - doffset ) * spref[0] ;
1624 sflagref[0] = flagref[0] + flagref[refchan-1] ;
1625 for ( int j = 1 ; j < refchan ; j++ ) {
1626 sspref[j] = doffset * spref[j-1] + ( 1.0 - doffset ) * spref[j] ;
1627 sflagref[j] = flagref[j-1] + flagref[j] ;
1628 }
1629 // TSYS
1630 if ( spref.nelements() == tsysref.nelements() ) {
1631 for ( int j = 0 ; j < abs(ioffset) ; j++ ) {
1632 stsysref[j] = tsysref[refchan+ioffset+j] ;
1633 }
1634 for ( int j = abs(ioffset) ; j < refchan ; j++ ) {
1635 stsysref[j] = tsysref[j+ioffset] ;
1636 }
1637 tsysref = stsysref.copy() ;
1638 stsysref[0] = doffset * tsysref[refchan-1] + ( 1.0 - doffset ) * tsysref[0] ;
1639 for ( int j = 1 ; j < refchan ; j++ ) {
1640 stsysref[j] = doffset * tsysref[j-1] + ( 1.0 - doffset ) * tsysref[j] ;
1641 }
1642 }
1643 }
1644
1645 // shift signal spectra if necessary (only for APEX?)
1646 if ( choffset2 != 0.0 ) {
1647 int sigchan = spsig.nelements() ;
1648 Vector<Float> sspsig( spsig.nelements() ) ;
1649 Vector<Float> stsyssig( tsyssig.nelements() ) ;
1650 Vector<uChar> sflagsig( flagsig.nelements() ) ;
1651 if ( ioffset2 > 0 ) {
1652 // SPECTRA and FLAGTRA
1653 for ( int j = 0 ; j < sigchan-ioffset2 ; j++ ) {
1654 sspsig[j] = spsig[j+ioffset2] ;
1655 sflagsig[j] = flagsig[j+ioffset2] ;
1656 }
1657 for ( int j = sigchan-ioffset2 ; j < sigchan ; j++ ) {
1658 sspsig[j] = spsig[j-sigchan+ioffset2] ;
1659 sflagsig[j] = flagsig[j-sigchan+ioffset2] ;
1660 }
1661 spsig = sspsig.copy() ;
1662 flagsig = sflagsig.copy() ;
1663 for ( int j = 0 ; j < sigchan - 1 ; j++ ) {
1664 sspsig[j] = doffset2 * spsig[j+1] + ( 1.0 - doffset2 ) * spsig[j] ;
1665 sflagsig[j] = flagsig[j+1] || flagsig[j] ;
1666 }
1667 sspsig[sigchan-1] = doffset2 * spsig[0] + ( 1.0 - doffset2 ) * spsig[sigchan-1] ;
1668 sflagsig[sigchan-1] = flagsig[0] || flagsig[sigchan-1] ;
1669 // TSTS
1670 if ( spsig.nelements() == tsyssig.nelements() ) {
1671 for ( int j = 0 ; j < sigchan-ioffset2 ; j++ ) {
1672 stsyssig[j] = tsyssig[j+ioffset2] ;
1673 }
1674 for ( int j = sigchan-ioffset2 ; j < sigchan ; j++ ) {
1675 stsyssig[j] = tsyssig[j-sigchan+ioffset2] ;
1676 }
1677 tsyssig = stsyssig.copy() ;
1678 for ( int j = 0 ; j < sigchan - 1 ; j++ ) {
1679 stsyssig[j] = doffset2 * tsyssig[j+1] + ( 1.0 - doffset2 ) * tsyssig[j] ;
1680 }
1681 stsyssig[sigchan-1] = doffset2 * tsyssig[0] + ( 1.0 - doffset2 ) * tsyssig[sigchan-1] ;
1682 }
1683 }
1684 else {
1685 // SPECTRA and FLAGTRA
1686 for ( int j = 0 ; j < abs(ioffset2) ; j++ ) {
1687 sspsig[j] = spsig[sigchan+ioffset2+j] ;
1688 sflagsig[j] = flagsig[sigchan+ioffset2+j] ;
1689 }
1690 for ( int j = abs(ioffset2) ; j < sigchan ; j++ ) {
1691 sspsig[j] = spsig[j+ioffset2] ;
1692 sflagsig[j] = flagsig[j+ioffset2] ;
1693 }
1694 spsig = sspsig.copy() ;
1695 flagsig = sflagsig.copy() ;
1696 sspsig[0] = doffset2 * spsig[sigchan-1] + ( 1.0 - doffset2 ) * spsig[0] ;
1697 sflagsig[0] = flagsig[0] + flagsig[sigchan-1] ;
1698 for ( int j = 1 ; j < sigchan ; j++ ) {
1699 sspsig[j] = doffset2 * spsig[j-1] + ( 1.0 - doffset2 ) * spsig[j] ;
1700 sflagsig[j] = flagsig[j-1] + flagsig[j] ;
1701 }
1702 // TSYS
1703 if ( spsig.nelements() == tsyssig.nelements() ) {
1704 for ( int j = 0 ; j < abs(ioffset2) ; j++ ) {
1705 stsyssig[j] = tsyssig[sigchan+ioffset2+j] ;
1706 }
1707 for ( int j = abs(ioffset2) ; j < sigchan ; j++ ) {
1708 stsyssig[j] = tsyssig[j+ioffset2] ;
1709 }
1710 tsyssig = stsyssig.copy() ;
1711 stsyssig[0] = doffset2 * tsyssig[sigchan-1] + ( 1.0 - doffset2 ) * tsyssig[0] ;
1712 for ( int j = 1 ; j < sigchan ; j++ ) {
1713 stsyssig[j] = doffset2 * tsyssig[j-1] + ( 1.0 - doffset2 ) * tsyssig[j] ;
1714 }
1715 }
1716 }
1717 }
1718
1719 // folding
1720 acc.add( spsig, !flagsig, tsyssig, intsig, timesig ) ;
1721 acc.add( sspref, !sflagref, stsysref, intref, timeref ) ;
1722
1723 // put result
1724 specColOut.put( i, acc.getSpectrum() ) ;
1725 const Vector<Bool> &msk = acc.getMask() ;
1726 Vector<uChar> flg( msk.shape() ) ;
1727 convertArray( flg, !msk ) ;
1728 flagColOut.put( i, flg ) ;
1729 tsysColOut.put( i, acc.getTsys() ) ;
1730 intervalColOut.put( i, acc.getInterval() ) ;
1731 mjdColOut.put( i, acc.getTime() ) ;
1732 // change FREQ_ID to unshifted IF setting (only for APEX?)
1733 if ( choffset2 != 0.0 ) {
1734 uInt freqid = fidColOut( 0 ) ; // assume single-IF data
1735 double refpix, refval, increment ;
1736 out->frequencies().getEntry( refpix, refval, increment, freqid ) ;
1737 refval -= choffset * increment ;
1738 uInt newfreqid = out->frequencies().addEntry( refpix, refval, increment ) ;
1739 Vector<uInt> freqids = fidColOut.getColumn() ;
1740 for ( uInt j = 0 ; j < freqids.nelements() ; j++ ) {
1741 if ( freqids[j] == freqid )
1742 freqids[j] = newfreqid ;
1743 }
1744 fidColOut.putColumn( freqids ) ;
1745 }
1746
1747 acc.reset() ;
1748 }
1749
1750 return out ;
1751}
1752
1753
[805]1754CountedPtr< Scantable > STMath::freqSwitch( const CountedPtr< Scantable >& in )
1755{
1756 // make copy or reference
1757 CountedPtr< Scantable > out = getScantable(in, false);
1758 Table& tout = out->table();
[1008]1759 Block<String> cols(4);
[805]1760 cols[0] = String("SCANNO");
[1008]1761 cols[1] = String("CYCLENO");
1762 cols[2] = String("BEAMNO");
1763 cols[3] = String("POLNO");
[805]1764 TableIterator iter(tout, cols);
1765 while (!iter.pastEnd()) {
1766 Table subt = iter.table();
1767 // this should leave us with two rows for the two IFs....if not ignore
1768 if (subt.nrow() != 2 ) {
1769 continue;
[701]1770 }
[1008]1771 ArrayColumn<Float> specCol(subt, "SPECTRA");
1772 ArrayColumn<Float> tsysCol(subt, "TSYS");
1773 ArrayColumn<uChar> flagCol(subt, "FLAGTRA");
[805]1774 Vector<Float> onspec,offspec, ontsys, offtsys;
1775 Vector<uChar> onflag, offflag;
1776 tsysCol.get(0, ontsys); tsysCol.get(1, offtsys);
1777 specCol.get(0, onspec); specCol.get(1, offspec);
1778 flagCol.get(0, onflag); flagCol.get(1, offflag);
1779 MaskedArray<Float> on = maskedArray(onspec, onflag);
1780 MaskedArray<Float> off = maskedArray(offspec, offflag);
1781 MaskedArray<Float> oncopy = on.copy();
[248]1782
[805]1783 on /= off; on -= 1.0f;
1784 on *= ontsys[0];
1785 off /= oncopy; off -= 1.0f;
1786 off *= offtsys[0];
1787 specCol.put(0, on.getArray());
1788 const Vector<Bool>& m0 = on.getMask();
1789 Vector<uChar> flags0(m0.shape());
1790 convertArray(flags0, !m0);
1791 flagCol.put(0, flags0);
[234]1792
[805]1793 specCol.put(1, off.getArray());
1794 const Vector<Bool>& m1 = off.getMask();
1795 Vector<uChar> flags1(m1.shape());
1796 convertArray(flags1, !m1);
1797 flagCol.put(1, flags1);
[867]1798 ++iter;
[130]1799 }
[780]1800
[805]1801 return out;
[9]1802}
[48]1803
[805]1804std::vector< float > STMath::statistic( const CountedPtr< Scantable > & in,
1805 const std::vector< bool > & mask,
1806 const std::string& which )
[130]1807{
1808
[805]1809 Vector<Bool> m(mask);
1810 const Table& tab = in->table();
1811 ROArrayColumn<Float> specCol(tab, "SPECTRA");
1812 ROArrayColumn<uChar> flagCol(tab, "FLAGTRA");
1813 std::vector<float> out;
1814 for (uInt i=0; i < tab.nrow(); ++i ) {
1815 Vector<Float> spec; specCol.get(i, spec);
[867]1816 Vector<uChar> flag; flagCol.get(i, flag);
1817 MaskedArray<Float> ma = maskedArray(spec, flag);
1818 float outstat = 0.0;
[805]1819 if ( spec.nelements() == m.nelements() ) {
1820 outstat = mathutil::statistics(which, ma(m));
1821 } else {
1822 outstat = mathutil::statistics(which, ma);
1823 }
1824 out.push_back(outstat);
[234]1825 }
[805]1826 return out;
[130]1827}
1828
[1907]1829std::vector< float > STMath::statisticRow( const CountedPtr< Scantable > & in,
1830 const std::vector< bool > & mask,
1831 const std::string& which,
1832 int row )
1833{
1834
1835 Vector<Bool> m(mask);
1836 const Table& tab = in->table();
1837 ROArrayColumn<Float> specCol(tab, "SPECTRA");
1838 ROArrayColumn<uChar> flagCol(tab, "FLAGTRA");
1839 std::vector<float> out;
1840
1841 Vector<Float> spec; specCol.get(row, spec);
1842 Vector<uChar> flag; flagCol.get(row, flag);
1843 MaskedArray<Float> ma = maskedArray(spec, flag);
1844 float outstat = 0.0;
1845 if ( spec.nelements() == m.nelements() ) {
1846 outstat = mathutil::statistics(which, ma(m));
1847 } else {
1848 outstat = mathutil::statistics(which, ma);
1849 }
1850 out.push_back(outstat);
1851
1852 return out;
1853}
1854
[1819]1855std::vector< int > STMath::minMaxChan( const CountedPtr< Scantable > & in,
1856 const std::vector< bool > & mask,
1857 const std::string& which )
1858{
1859
1860 Vector<Bool> m(mask);
1861 const Table& tab = in->table();
1862 ROArrayColumn<Float> specCol(tab, "SPECTRA");
1863 ROArrayColumn<uChar> flagCol(tab, "FLAGTRA");
1864 std::vector<int> out;
1865 for (uInt i=0; i < tab.nrow(); ++i ) {
1866 Vector<Float> spec; specCol.get(i, spec);
1867 Vector<uChar> flag; flagCol.get(i, flag);
1868 MaskedArray<Float> ma = maskedArray(spec, flag);
1869 if (ma.ndim() != 1) {
1870 throw (ArrayError(
1871 "std::vector<int> STMath::minMaxChan("
1872 "ContedPtr<Scantable> &in, std::vector<bool> &mask, "
1873 " std::string &which)"
1874 " - MaskedArray is not 1D"));
1875 }
1876 IPosition outpos(1,0);
1877 if ( spec.nelements() == m.nelements() ) {
1878 outpos = mathutil::minMaxPos(which, ma(m));
1879 } else {
1880 outpos = mathutil::minMaxPos(which, ma);
1881 }
1882 out.push_back(outpos[0]);
1883 }
1884 return out;
1885}
1886
[805]1887CountedPtr< Scantable > STMath::bin( const CountedPtr< Scantable > & in,
1888 int width )
[144]1889{
[841]1890 if ( !in->getSelection().empty() ) throw(AipsError("Can't bin subset of the data."));
[805]1891 CountedPtr< Scantable > out = getScantable(in, false);
1892 Table& tout = out->table();
1893 out->frequencies().rescale(width, "BIN");
1894 ArrayColumn<Float> specCol(tout, "SPECTRA");
1895 ArrayColumn<uChar> flagCol(tout, "FLAGTRA");
1896 for (uInt i=0; i < tout.nrow(); ++i ) {
1897 MaskedArray<Float> main = maskedArray(specCol(i), flagCol(i));
1898 MaskedArray<Float> maout;
1899 LatticeUtilities::bin(maout, main, 0, Int(width));
1900 /// @todo implement channel based tsys binning
1901 specCol.put(i, maout.getArray());
1902 flagCol.put(i, flagsFromMA(maout));
1903 // take only the first binned spectrum's length for the deprecated
1904 // global header item nChan
1905 if (i==0) tout.rwKeywordSet().define(String("nChan"),
1906 Int(maout.getArray().nelements()));
[169]1907 }
[805]1908 return out;
[146]1909}
1910
[805]1911CountedPtr< Scantable > STMath::resample( const CountedPtr< Scantable >& in,
1912 const std::string& method,
1913 float width )
[299]1914//
1915// Should add the possibility of width being specified in km/s. This means
[780]1916// that for each freqID (SpectralCoordinate) we will need to convert to an
1917// average channel width (say at the reference pixel). Then we would need
1918// to be careful to make sure each spectrum (of different freqID)
[299]1919// is the same length.
1920//
1921{
[996]1922 //InterpolateArray1D<Double,Float>::InterpolationMethod interp;
[805]1923 Int interpMethod(stringToIMethod(method));
[299]1924
[805]1925 CountedPtr< Scantable > out = getScantable(in, false);
1926 Table& tout = out->table();
[299]1927
1928// Resample SpectralCoordinates (one per freqID)
[805]1929 out->frequencies().rescale(width, "RESAMPLE");
1930 TableIterator iter(tout, "IFNO");
1931 TableRow row(tout);
1932 while ( !iter.pastEnd() ) {
1933 Table tab = iter.table();
1934 ArrayColumn<Float> specCol(tab, "SPECTRA");
1935 //ArrayColumn<Float> tsysCol(tout, "TSYS");
1936 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
1937 Vector<Float> spec;
1938 Vector<uChar> flag;
1939 specCol.get(0,spec); // the number of channels should be constant per IF
1940 uInt nChanIn = spec.nelements();
1941 Vector<Float> xIn(nChanIn); indgen(xIn);
1942 Int fac = Int(nChanIn/width);
1943 Vector<Float> xOut(fac+10); // 10 to be safe - resize later
1944 uInt k = 0;
1945 Float x = 0.0;
1946 while (x < Float(nChanIn) ) {
1947 xOut(k) = x;
1948 k++;
1949 x += width;
1950 }
1951 uInt nChanOut = k;
1952 xOut.resize(nChanOut, True);
1953 // process all rows for this IFNO
1954 Vector<Float> specOut;
1955 Vector<Bool> maskOut;
1956 Vector<uChar> flagOut;
1957 for (uInt i=0; i < tab.nrow(); ++i) {
1958 specCol.get(i, spec);
1959 flagCol.get(i, flag);
1960 Vector<Bool> mask(flag.nelements());
1961 convertArray(mask, flag);
[299]1962
[805]1963 IPosition shapeIn(spec.shape());
1964 //sh.nchan = nChanOut;
1965 InterpolateArray1D<Float,Float>::interpolate(specOut, maskOut, xOut,
1966 xIn, spec, mask,
1967 interpMethod, True, True);
1968 /// @todo do the same for channel based Tsys
1969 flagOut.resize(maskOut.nelements());
1970 convertArray(flagOut, maskOut);
1971 specCol.put(i, specOut);
1972 flagCol.put(i, flagOut);
1973 }
1974 ++iter;
[299]1975 }
1976
[805]1977 return out;
1978}
[299]1979
[805]1980STMath::imethod STMath::stringToIMethod(const std::string& in)
1981{
1982 static STMath::imap lookup;
[299]1983
[805]1984 // initialize the lookup table if necessary
1985 if ( lookup.empty() ) {
[926]1986 lookup["nearest"] = InterpolateArray1D<Double,Float>::nearestNeighbour;
1987 lookup["linear"] = InterpolateArray1D<Double,Float>::linear;
1988 lookup["cubic"] = InterpolateArray1D<Double,Float>::cubic;
1989 lookup["spline"] = InterpolateArray1D<Double,Float>::spline;
[299]1990 }
1991
[805]1992 STMath::imap::const_iterator iter = lookup.find(in);
[299]1993
[805]1994 if ( lookup.end() == iter ) {
1995 std::string message = in;
1996 message += " is not a valid interpolation mode";
1997 throw(AipsError(message));
[299]1998 }
[805]1999 return iter->second;
[299]2000}
2001
[805]2002WeightType STMath::stringToWeight(const std::string& in)
[146]2003{
[805]2004 static std::map<std::string, WeightType> lookup;
[434]2005
[805]2006 // initialize the lookup table if necessary
2007 if ( lookup.empty() ) {
[1569]2008 lookup["NONE"] = asap::W_NONE;
2009 lookup["TINT"] = asap::W_TINT;
2010 lookup["TINTSYS"] = asap::W_TINTSYS;
2011 lookup["TSYS"] = asap::W_TSYS;
2012 lookup["VAR"] = asap::W_VAR;
[805]2013 }
[434]2014
[805]2015 std::map<std::string, WeightType>::const_iterator iter = lookup.find(in);
[294]2016
[805]2017 if ( lookup.end() == iter ) {
2018 std::string message = in;
2019 message += " is not a valid weighting mode";
2020 throw(AipsError(message));
2021 }
2022 return iter->second;
[146]2023}
2024
[805]2025CountedPtr< Scantable > STMath::gainElevation( const CountedPtr< Scantable >& in,
[867]2026 const vector< float > & coeff,
[805]2027 const std::string & filename,
2028 const std::string& method)
[165]2029{
[805]2030 // Get elevation data from Scantable and convert to degrees
2031 CountedPtr< Scantable > out = getScantable(in, false);
[926]2032 Table& tab = out->table();
[805]2033 ROScalarColumn<Float> elev(tab, "ELEVATION");
2034 Vector<Float> x = elev.getColumn();
2035 x *= Float(180 / C::pi); // Degrees
[165]2036
[867]2037 Vector<Float> coeffs(coeff);
[805]2038 const uInt nc = coeffs.nelements();
2039 if ( filename.length() > 0 && nc > 0 ) {
2040 throw(AipsError("You must choose either polynomial coefficients or an ascii file, not both"));
[315]2041 }
[165]2042
[805]2043 // Correct
2044 if ( nc > 0 || filename.length() == 0 ) {
2045 // Find instrument
2046 Bool throwit = True;
2047 Instrument inst =
[878]2048 STAttr::convertInstrument(tab.keywordSet().asString("AntennaName"),
[805]2049 throwit);
[165]2050
[805]2051 // Set polynomial
2052 Polynomial<Float>* ppoly = 0;
2053 Vector<Float> coeff;
2054 String msg;
2055 if ( nc > 0 ) {
[1618]2056 ppoly = new Polynomial<Float>(nc-1);
[805]2057 coeff = coeffs;
2058 msg = String("user");
2059 } else {
[878]2060 STAttr sdAttr;
[805]2061 coeff = sdAttr.gainElevationPoly(inst);
[1618]2062 ppoly = new Polynomial<Float>(coeff.nelements()-1);
[805]2063 msg = String("built in");
2064 }
[532]2065
[805]2066 if ( coeff.nelements() > 0 ) {
2067 ppoly->setCoefficients(coeff);
2068 } else {
2069 delete ppoly;
2070 throw(AipsError("There is no known gain-elevation polynomial known for this instrument"));
2071 }
2072 ostringstream oss;
2073 oss << "Making polynomial correction with " << msg << " coefficients:" << endl;
2074 oss << " " << coeff;
2075 pushLog(String(oss));
2076 const uInt nrow = tab.nrow();
2077 Vector<Float> factor(nrow);
2078 for ( uInt i=0; i < nrow; ++i ) {
2079 factor[i] = 1.0 / (*ppoly)(x[i]);
2080 }
2081 delete ppoly;
2082 scaleByVector(tab, factor, true);
[532]2083
[805]2084 } else {
2085 // Read and correct
2086 pushLog("Making correction from ascii Table");
2087 scaleFromAsciiTable(tab, filename, method, x, true);
[532]2088 }
[805]2089 return out;
2090}
[165]2091
[805]2092void STMath::scaleFromAsciiTable(Table& in, const std::string& filename,
2093 const std::string& method,
2094 const Vector<Float>& xout, bool dotsys)
2095{
[165]2096
[805]2097// Read gain-elevation ascii file data into a Table.
[165]2098
[805]2099 String formatString;
2100 Table tbl = readAsciiTable(formatString, Table::Memory, filename, "", "", False);
2101 scaleFromTable(in, tbl, method, xout, dotsys);
2102}
[165]2103
[805]2104void STMath::scaleFromTable(Table& in,
2105 const Table& table,
2106 const std::string& method,
2107 const Vector<Float>& xout, bool dotsys)
2108{
[780]2109
[805]2110 ROScalarColumn<Float> geElCol(table, "ELEVATION");
2111 ROScalarColumn<Float> geFacCol(table, "FACTOR");
2112 Vector<Float> xin = geElCol.getColumn();
2113 Vector<Float> yin = geFacCol.getColumn();
2114 Vector<Bool> maskin(xin.nelements(),True);
[165]2115
[805]2116 // Interpolate (and extrapolate) with desired method
[532]2117
[996]2118 InterpolateArray1D<Double,Float>::InterpolationMethod interp = stringToIMethod(method);
[165]2119
[805]2120 Vector<Float> yout;
2121 Vector<Bool> maskout;
2122 InterpolateArray1D<Float,Float>::interpolate(yout, maskout, xout,
[996]2123 xin, yin, maskin, interp,
[805]2124 True, True);
[165]2125
[805]2126 scaleByVector(in, Float(1.0)/yout, dotsys);
[165]2127}
[167]2128
[805]2129void STMath::scaleByVector( Table& in,
2130 const Vector< Float >& factor,
2131 bool dotsys )
[177]2132{
[805]2133 uInt nrow = in.nrow();
2134 if ( factor.nelements() != nrow ) {
2135 throw(AipsError("factors.nelements() != table.nelements()"));
2136 }
2137 ArrayColumn<Float> specCol(in, "SPECTRA");
2138 ArrayColumn<uChar> flagCol(in, "FLAGTRA");
2139 ArrayColumn<Float> tsysCol(in, "TSYS");
2140 for (uInt i=0; i < nrow; ++i) {
2141 MaskedArray<Float> ma = maskedArray(specCol(i), flagCol(i));
2142 ma *= factor[i];
2143 specCol.put(i, ma.getArray());
2144 flagCol.put(i, flagsFromMA(ma));
2145 if ( dotsys ) {
[926]2146 Vector<Float> tsys = tsysCol(i);
[805]2147 tsys *= factor[i];
[926]2148 tsysCol.put(i,tsys);
[805]2149 }
2150 }
[177]2151}
2152
[805]2153CountedPtr< Scantable > STMath::convertFlux( const CountedPtr< Scantable >& in,
2154 float d, float etaap,
2155 float jyperk )
[221]2156{
[805]2157 CountedPtr< Scantable > out = getScantable(in, false);
2158 Table& tab = in->table();
2159 Unit fluxUnit(tab.keywordSet().asString("FluxUnit"));
[221]2160 Unit K(String("K"));
2161 Unit JY(String("Jy"));
[701]2162
[805]2163 bool tokelvin = true;
2164 Double cfac = 1.0;
[716]2165
[805]2166 if ( fluxUnit == JY ) {
[716]2167 pushLog("Converting to K");
[701]2168 Quantum<Double> t(1.0,fluxUnit);
2169 Quantum<Double> t2 = t.get(JY);
[805]2170 cfac = (t2 / t).getValue(); // value to Jy
[780]2171
[805]2172 tokelvin = true;
2173 out->setFluxUnit("K");
2174 } else if ( fluxUnit == K ) {
[716]2175 pushLog("Converting to Jy");
[701]2176 Quantum<Double> t(1.0,fluxUnit);
2177 Quantum<Double> t2 = t.get(K);
[805]2178 cfac = (t2 / t).getValue(); // value to K
[780]2179
[805]2180 tokelvin = false;
2181 out->setFluxUnit("Jy");
[221]2182 } else {
[701]2183 throw(AipsError("Unrecognized brightness units in Table - must be consistent with Jy or K"));
[221]2184 }
[701]2185 // Make sure input values are converted to either Jy or K first...
[805]2186 Float factor = cfac;
[221]2187
[701]2188 // Select method
[805]2189 if (jyperk > 0.0) {
2190 factor *= jyperk;
2191 if ( tokelvin ) factor = 1.0 / jyperk;
[716]2192 ostringstream oss;
[805]2193 oss << "Jy/K = " << jyperk;
[716]2194 pushLog(String(oss));
[805]2195 Vector<Float> factors(tab.nrow(), factor);
2196 scaleByVector(tab,factors, false);
2197 } else if ( etaap > 0.0) {
[1319]2198 if (d < 0) {
2199 Instrument inst =
[1570]2200 STAttr::convertInstrument(tab.keywordSet().asString("AntennaName"),
[1319]2201 True);
2202 STAttr sda;
2203 d = sda.diameter(inst);
2204 }
[996]2205 jyperk = STAttr::findJyPerK(etaap, d);
[716]2206 ostringstream oss;
[805]2207 oss << "Jy/K = " << jyperk;
[716]2208 pushLog(String(oss));
[805]2209 factor *= jyperk;
2210 if ( tokelvin ) {
[701]2211 factor = 1.0 / factor;
2212 }
[805]2213 Vector<Float> factors(tab.nrow(), factor);
2214 scaleByVector(tab, factors, False);
[354]2215 } else {
[780]2216
[701]2217 // OK now we must deal with automatic look up of values.
2218 // We must also deal with the fact that the factors need
2219 // to be computed per IF and may be different and may
2220 // change per integration.
[780]2221
[716]2222 pushLog("Looking up conversion factors");
[805]2223 convertBrightnessUnits(out, tokelvin, cfac);
[701]2224 }
[805]2225
2226 return out;
[221]2227}
2228
[805]2229void STMath::convertBrightnessUnits( CountedPtr<Scantable>& in,
2230 bool tokelvin, float cfac )
[227]2231{
[805]2232 Table& table = in->table();
2233 Instrument inst =
[878]2234 STAttr::convertInstrument(table.keywordSet().asString("AntennaName"), True);
[805]2235 TableIterator iter(table, "FREQ_ID");
2236 STFrequencies stfreqs = in->frequencies();
[878]2237 STAttr sdAtt;
[805]2238 while (!iter.pastEnd()) {
2239 Table tab = iter.table();
2240 ArrayColumn<Float> specCol(tab, "SPECTRA");
2241 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2242 ROScalarColumn<uInt> freqidCol(tab, "FREQ_ID");
2243 MEpoch::ROScalarColumn timeCol(tab, "TIME");
[234]2244
[805]2245 uInt freqid; freqidCol.get(0, freqid);
2246 Vector<Float> tmpspec; specCol.get(0, tmpspec);
[878]2247 // STAttr.JyPerK has a Vector interface... change sometime.
[805]2248 Vector<Float> freqs(1,stfreqs.getRefFreq(freqid, tmpspec.nelements()));
2249 for ( uInt i=0; i<tab.nrow(); ++i) {
2250 Float jyperk = (sdAtt.JyPerK(inst, timeCol(i), freqs))[0];
2251 Float factor = cfac * jyperk;
2252 if ( tokelvin ) factor = Float(1.0) / factor;
2253 MaskedArray<Float> ma = maskedArray(specCol(i), flagCol(i));
2254 ma *= factor;
2255 specCol.put(i, ma.getArray());
2256 flagCol.put(i, flagsFromMA(ma));
2257 }
[867]2258 ++iter;
[234]2259 }
[230]2260}
[227]2261
[805]2262CountedPtr< Scantable > STMath::opacity( const CountedPtr< Scantable > & in,
[1689]2263 const std::vector<float>& tau )
[234]2264{
[805]2265 CountedPtr< Scantable > out = getScantable(in, false);
[926]2266
[1689]2267 Table outtab = out->table();
2268
[2125]2269 const Int ntau = uInt(tau.size());
[1689]2270 std::vector<float>::const_iterator tauit = tau.begin();
2271 AlwaysAssert((ntau == 1 || ntau == in->nif() || ntau == in->nif() * in->npol()),
2272 AipsError);
2273 TableIterator iiter(outtab, "IFNO");
2274 while ( !iiter.pastEnd() ) {
2275 Table itab = iiter.table();
2276 TableIterator piter(outtab, "POLNO");
2277 while ( !piter.pastEnd() ) {
2278 Table tab = piter.table();
2279 ROScalarColumn<Float> elev(tab, "ELEVATION");
2280 ArrayColumn<Float> specCol(tab, "SPECTRA");
2281 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2282 ArrayColumn<Float> tsysCol(tab, "TSYS");
2283 for ( uInt i=0; i<tab.nrow(); ++i) {
2284 Float zdist = Float(C::pi_2) - elev(i);
2285 Float factor = exp(*tauit/cos(zdist));
2286 MaskedArray<Float> ma = maskedArray(specCol(i), flagCol(i));
2287 ma *= factor;
2288 specCol.put(i, ma.getArray());
2289 flagCol.put(i, flagsFromMA(ma));
2290 Vector<Float> tsys;
2291 tsysCol.get(i, tsys);
2292 tsys *= factor;
2293 tsysCol.put(i, tsys);
2294 }
2295 if (ntau == in->nif()*in->npol() ) {
2296 tauit++;
2297 }
2298 piter++;
2299 }
2300 if (ntau >= in->nif() ) {
2301 tauit++;
2302 }
2303 iiter++;
[234]2304 }
[805]2305 return out;
[234]2306}
2307
[1373]2308CountedPtr< Scantable > STMath::smoothOther( const CountedPtr< Scantable >& in,
2309 const std::string& kernel,
[1570]2310 float width, int order)
[1373]2311{
2312 CountedPtr< Scantable > out = getScantable(in, false);
[2125]2313 Table table = out->table();
2314
2315 TableIterator iter(table, "IFNO");
2316 while (!iter.pastEnd()) {
2317 Table tab = iter.table();
2318 ArrayColumn<Float> specCol(tab, "SPECTRA");
2319 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2320 Vector<Float> spec;
2321 Vector<uChar> flag;
2322 for (uInt i = 0; i < tab.nrow(); ++i) {
2323 specCol.get(i, spec);
2324 flagCol.get(i, flag);
2325 Vector<Bool> mask(flag.nelements());
2326 convertArray(mask, flag);
2327 Vector<Float> specout;
2328 Vector<Bool> maskout;
2329 if (kernel == "hanning") {
2330 mathutil::hanning(specout, maskout, spec, !mask);
2331 convertArray(flag, !maskout);
2332 } else if (kernel == "rmedian") {
2333 mathutil::runningMedian(specout, maskout, spec , mask, width);
2334 convertArray(flag, maskout);
2335 } else if (kernel == "poly") {
2336 mathutil::polyfit(specout, maskout, spec, !mask, width, order);
2337 convertArray(flag, !maskout);
2338 }
2339
2340 for (uInt j = 0; j < flag.nelements(); ++j) {
2341 uChar userFlag = 1 << 7;
2342 if (maskout[j]==True) userFlag = 0 << 7;
2343 flag(j) = userFlag;
2344 }
2345
2346 flagCol.put(i, flag);
2347 specCol.put(i, specout);
[1373]2348 }
[2125]2349 ++iter;
[1373]2350 }
2351 return out;
2352}
2353
[805]2354CountedPtr< Scantable > STMath::smooth( const CountedPtr< Scantable >& in,
[1571]2355 const std::string& kernel, float width,
2356 int order)
[457]2357{
[1571]2358 if (kernel == "rmedian" || kernel == "hanning" || kernel == "poly") {
2359 return smoothOther(in, kernel, width, order);
[1373]2360 }
[805]2361 CountedPtr< Scantable > out = getScantable(in, false);
[1033]2362 Table& table = out->table();
[805]2363 VectorKernel::KernelTypes type = VectorKernel::toKernelType(kernel);
2364 // same IFNO should have same no of channels
2365 // this saves overhead
2366 TableIterator iter(table, "IFNO");
2367 while (!iter.pastEnd()) {
2368 Table tab = iter.table();
2369 ArrayColumn<Float> specCol(tab, "SPECTRA");
2370 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2371 Vector<Float> tmpspec; specCol.get(0, tmpspec);
2372 uInt nchan = tmpspec.nelements();
2373 Vector<Float> kvec = VectorKernel::make(type, width, nchan, True, False);
2374 Convolver<Float> conv(kvec, IPosition(1,nchan));
2375 Vector<Float> spec;
2376 Vector<uChar> flag;
2377 for ( uInt i=0; i<tab.nrow(); ++i) {
2378 specCol.get(i, spec);
2379 flagCol.get(i, flag);
2380 Vector<Bool> mask(flag.nelements());
2381 convertArray(mask, flag);
2382 Vector<Float> specout;
[1373]2383 mathutil::replaceMaskByZero(specout, mask);
2384 conv.linearConv(specout, spec);
2385 specCol.put(i, specout);
[805]2386 }
[867]2387 ++iter;
[701]2388 }
[805]2389 return out;
[701]2390}
[841]2391
2392CountedPtr< Scantable >
2393 STMath::merge( const std::vector< CountedPtr < Scantable > >& in )
2394{
2395 if ( in.size() < 2 ) {
[862]2396 throw(AipsError("Need at least two scantables to perform a merge."));
[841]2397 }
2398 std::vector<CountedPtr < Scantable > >::const_iterator it = in.begin();
2399 bool insitu = insitu_;
2400 setInsitu(false);
[862]2401 CountedPtr< Scantable > out = getScantable(*it, false);
[841]2402 setInsitu(insitu);
2403 Table& tout = out->table();
2404 ScalarColumn<uInt> freqidcol(tout,"FREQ_ID"), molidcol(tout, "MOLECULE_ID");
[917]2405 ScalarColumn<uInt> scannocol(tout,"SCANNO"), focusidcol(tout,"FOCUS_ID");
2406 // Renumber SCANNO to be 0-based
[926]2407 Vector<uInt> scannos = scannocol.getColumn();
2408 uInt offset = min(scannos);
[917]2409 scannos -= offset;
[926]2410 scannocol.putColumn(scannos);
2411 uInt newscanno = max(scannos)+1;
[862]2412 ++it;
[841]2413 while ( it != in.end() ){
2414 if ( ! (*it)->conformant(*out) ) {
[1439]2415 // non conformant.
[1819]2416 //pushLog(String("Warning: Can't merge scantables as header info differs."));
2417 LogIO os( LogOrigin( "STMath", "merge()", WHERE ) ) ;
2418 os << LogIO::SEVERE << "Can't merge scantables as header informations (any one of AntennaName, Equinox, and FluxUnit) differ." << LogIO::EXCEPTION ;
[841]2419 }
[862]2420 out->appendToHistoryTable((*it)->history());
[841]2421 const Table& tab = (*it)->table();
2422 TableIterator scanit(tab, "SCANNO");
2423 while (!scanit.pastEnd()) {
2424 TableIterator freqit(scanit.table(), "FREQ_ID");
2425 while ( !freqit.pastEnd() ) {
2426 Table thetab = freqit.table();
2427 uInt nrow = tout.nrow();
[1505]2428 tout.addRow(thetab.nrow());
[841]2429 TableCopy::copyRows(tout, thetab, nrow, 0, thetab.nrow());
2430 ROTableRow row(thetab);
2431 for ( uInt i=0; i<thetab.nrow(); ++i) {
2432 uInt k = nrow+i;
2433 scannocol.put(k, newscanno);
2434 const TableRecord& rec = row.get(i);
2435 Double rv,rp,inc;
2436 (*it)->frequencies().getEntry(rp, rv, inc, rec.asuInt("FREQ_ID"));
2437 uInt id;
2438 id = out->frequencies().addEntry(rp, rv, inc);
2439 freqidcol.put(k,id);
[1819]2440 //String name,fname;Double rf;
2441 Vector<String> name,fname;Vector<Double> rf;
[841]2442 (*it)->molecules().getEntry(rf, name, fname, rec.asuInt("MOLECULE_ID"));
2443 id = out->molecules().addEntry(rf, name, fname);
2444 molidcol.put(k, id);
[1586]2445 Float fpa,frot,fax,ftan,fhand,fmount,fuser, fxy, fxyp;
2446 (*it)->focus().getEntry(fpa, fax, ftan, frot, fhand,
[961]2447 fmount,fuser, fxy, fxyp,
2448 rec.asuInt("FOCUS_ID"));
[1586]2449 id = out->focus().addEntry(fpa, fax, ftan, frot, fhand,
[961]2450 fmount,fuser, fxy, fxyp);
[841]2451 focusidcol.put(k, id);
2452 }
2453 ++freqit;
2454 }
2455 ++newscanno;
2456 ++scanit;
2457 }
2458 ++it;
2459 }
2460 return out;
2461}
[896]2462
2463CountedPtr< Scantable >
2464 STMath::invertPhase( const CountedPtr < Scantable >& in )
2465{
[996]2466 return applyToPol(in, &STPol::invertPhase, Float(0.0));
[896]2467}
2468
2469CountedPtr< Scantable >
2470 STMath::rotateXYPhase( const CountedPtr < Scantable >& in, float phase )
2471{
2472 return applyToPol(in, &STPol::rotatePhase, Float(phase));
2473}
2474
2475CountedPtr< Scantable >
2476 STMath::rotateLinPolPhase( const CountedPtr < Scantable >& in, float phase )
2477{
2478 return applyToPol(in, &STPol::rotateLinPolPhase, Float(phase));
2479}
2480
2481CountedPtr< Scantable > STMath::applyToPol( const CountedPtr<Scantable>& in,
2482 STPol::polOperation fptr,
2483 Float phase )
2484{
2485 CountedPtr< Scantable > out = getScantable(in, false);
2486 Table& tout = out->table();
2487 Block<String> cols(4);
2488 cols[0] = String("SCANNO");
2489 cols[1] = String("BEAMNO");
2490 cols[2] = String("IFNO");
2491 cols[3] = String("CYCLENO");
2492 TableIterator iter(tout, cols);
[1569]2493 CountedPtr<STPol> stpol = STPol::getPolClass(out->factories_,
[1384]2494 out->getPolType() );
[896]2495 while (!iter.pastEnd()) {
2496 Table t = iter.table();
2497 ArrayColumn<Float> speccol(t, "SPECTRA");
[1015]2498 ScalarColumn<uInt> focidcol(t, "FOCUS_ID");
[1384]2499 Matrix<Float> pols(speccol.getColumn());
[896]2500 try {
2501 stpol->setSpectra(pols);
[1586]2502 Float fang,fhand;
2503 fang = in->focusTable_.getTotalAngle(focidcol(0));
[1015]2504 fhand = in->focusTable_.getFeedHand(focidcol(0));
[1586]2505 stpol->setPhaseCorrections(fang, fhand);
[1384]2506 // use a member function pointer in STPol. This only works on
2507 // the STPol pointer itself, not the Counted Pointer so
2508 // derefernce it.
2509 (&(*(stpol))->*fptr)(phase);
[896]2510 speccol.putColumn(stpol->getSpectra());
2511 } catch (AipsError& e) {
[1384]2512 //delete stpol;stpol=0;
[896]2513 throw(e);
2514 }
2515 ++iter;
2516 }
[1384]2517 //delete stpol;stpol=0;
[896]2518 return out;
2519}
2520
2521CountedPtr< Scantable >
2522 STMath::swapPolarisations( const CountedPtr< Scantable > & in )
2523{
2524 CountedPtr< Scantable > out = getScantable(in, false);
2525 Table& tout = out->table();
2526 Table t0 = tout(tout.col("POLNO") == 0);
2527 Table t1 = tout(tout.col("POLNO") == 1);
2528 if ( t0.nrow() != t1.nrow() )
2529 throw(AipsError("Inconsistent number of polarisations"));
2530 ArrayColumn<Float> speccol0(t0, "SPECTRA");
2531 ArrayColumn<uChar> flagcol0(t0, "FLAGTRA");
2532 ArrayColumn<Float> speccol1(t1, "SPECTRA");
2533 ArrayColumn<uChar> flagcol1(t1, "FLAGTRA");
2534 Matrix<Float> s0 = speccol0.getColumn();
2535 Matrix<uChar> f0 = flagcol0.getColumn();
2536 speccol0.putColumn(speccol1.getColumn());
2537 flagcol0.putColumn(flagcol1.getColumn());
2538 speccol1.putColumn(s0);
2539 flagcol1.putColumn(f0);
2540 return out;
2541}
[917]2542
2543CountedPtr< Scantable >
[940]2544 STMath::averagePolarisations( const CountedPtr< Scantable > & in,
2545 const std::vector<bool>& mask,
2546 const std::string& weight )
2547{
[1232]2548 if (in->npol() < 2 )
2549 throw(AipsError("averagePolarisations can only be applied to two or more"
2550 "polarisations"));
[1010]2551 bool insitu = insitu_;
2552 setInsitu(false);
[1232]2553 CountedPtr< Scantable > pols = getScantable(in, true);
[1010]2554 setInsitu(insitu);
2555 Table& tout = pols->table();
[1232]2556 std::string taql = "SELECT FROM $1 WHERE POLNO IN [0,1]";
2557 Table tab = tableCommand(taql, in->table());
2558 if (tab.nrow() == 0 )
2559 throw(AipsError("Could not find any rows with POLNO==0 and POLNO==1"));
2560 TableCopy::copyRows(tout, tab);
[1145]2561 TableVector<uInt> vec(tout, "POLNO");
[940]2562 vec = 0;
[1145]2563 pols->table_.rwKeywordSet().define("nPol", Int(1));
[2102]2564 pols->table_.rwKeywordSet().define("POLTYPE", String("stokes"));
2565 //pols->table_.rwKeywordSet().define("POLTYPE", in->getPolType());
[1010]2566 std::vector<CountedPtr<Scantable> > vpols;
2567 vpols.push_back(pols);
[1232]2568 CountedPtr< Scantable > out = average(vpols, mask, weight, "SCAN");
[940]2569 return out;
2570}
2571
[1145]2572CountedPtr< Scantable >
2573 STMath::averageBeams( const CountedPtr< Scantable > & in,
2574 const std::vector<bool>& mask,
2575 const std::string& weight )
2576{
2577 bool insitu = insitu_;
2578 setInsitu(false);
2579 CountedPtr< Scantable > beams = getScantable(in, false);
2580 setInsitu(insitu);
2581 Table& tout = beams->table();
2582 // give all rows the same BEAMNO
2583 TableVector<uInt> vec(tout, "BEAMNO");
2584 vec = 0;
2585 beams->table_.rwKeywordSet().define("nBeam", Int(1));
2586 std::vector<CountedPtr<Scantable> > vbeams;
2587 vbeams.push_back(beams);
[1232]2588 CountedPtr< Scantable > out = average(vbeams, mask, weight, "SCAN");
[1145]2589 return out;
2590}
[940]2591
[1145]2592
[940]2593CountedPtr< Scantable >
[917]2594 asap::STMath::frequencyAlign( const CountedPtr< Scantable > & in,
2595 const std::string & refTime,
[926]2596 const std::string & method)
[917]2597{
[940]2598 // clone as this is not working insitu
2599 bool insitu = insitu_;
2600 setInsitu(false);
[917]2601 CountedPtr< Scantable > out = getScantable(in, false);
[940]2602 setInsitu(insitu);
[917]2603 Table& tout = out->table();
2604 // Get reference Epoch to time of first row or given String
2605 Unit DAY(String("d"));
2606 MEpoch::Ref epochRef(in->getTimeReference());
2607 MEpoch refEpoch;
2608 if (refTime.length()>0) {
2609 Quantum<Double> qt;
2610 if (MVTime::read(qt,refTime)) {
2611 MVEpoch mv(qt);
2612 refEpoch = MEpoch(mv, epochRef);
2613 } else {
2614 throw(AipsError("Invalid format for Epoch string"));
2615 }
2616 } else {
2617 refEpoch = in->timeCol_(0);
2618 }
2619 MPosition refPos = in->getAntennaPosition();
[940]2620
[996]2621 InterpolateArray1D<Double,Float>::InterpolationMethod interp = stringToIMethod(method);
[1475]2622 /*
2623 // Comment from MV.
2624 // the following code has been commented out because different FREQ_IDs have to be aligned together even
2625 // if the frame doesn't change. So far, lack of this check didn't cause any problems.
[917]2626 // test if user frame is different to base frame
2627 if ( in->frequencies().getFrameString(true)
2628 == in->frequencies().getFrameString(false) ) {
[985]2629 throw(AipsError("Can't convert as no output frame has been set"
2630 " (use set_freqframe) or it is aligned already."));
[917]2631 }
[1475]2632 */
[917]2633 MFrequency::Types system = in->frequencies().getFrame();
[940]2634 MVTime mvt(refEpoch.getValue());
2635 String epochout = mvt.string(MVTime::YMD) + String(" (") + refEpoch.getRefString() + String(")");
2636 ostringstream oss;
2637 oss << "Aligned at reference Epoch " << epochout
2638 << " in frame " << MFrequency::showType(system);
2639 pushLog(String(oss));
[917]2640 // set up the iterator
[926]2641 Block<String> cols(4);
2642 // select by constant direction
[917]2643 cols[0] = String("SRCNAME");
2644 cols[1] = String("BEAMNO");
2645 // select by IF ( no of channels varies over this )
2646 cols[2] = String("IFNO");
[926]2647 // select by restfrequency
2648 cols[3] = String("MOLECULE_ID");
[917]2649 TableIterator iter(tout, cols);
[926]2650 while ( !iter.pastEnd() ) {
[917]2651 Table t = iter.table();
2652 MDirection::ROScalarColumn dirCol(t, "DIRECTION");
[926]2653 TableIterator fiter(t, "FREQ_ID");
[917]2654 // determine nchan from the first row. This should work as
[926]2655 // we are iterating over BEAMNO and IFNO // we should have constant direction
2656
[917]2657 ROArrayColumn<Float> sCol(t, "SPECTRA");
[1475]2658 const MDirection direction = dirCol(0);
2659 const uInt nchan = sCol(0).nelements();
2660
2661 // skip operations if there is nothing to align
2662 if (fiter.pastEnd()) {
2663 continue;
2664 }
2665
2666 Table ftab = fiter.table();
2667 // align all frequency ids with respect to the first encountered id
2668 ScalarColumn<uInt> freqidCol(ftab, "FREQ_ID");
2669 // get the SpectralCoordinate for the freqid, which we are iterating over
2670 SpectralCoordinate sC = in->frequencies().getSpectralCoordinate(freqidCol(0));
2671 FrequencyAligner<Float> fa( sC, nchan, refEpoch,
2672 direction, refPos, system );
2673 // realign the SpectralCoordinate and put into the output Scantable
2674 Vector<String> units(1);
2675 units = String("Hz");
2676 Bool linear=True;
2677 SpectralCoordinate sc2 = fa.alignedSpectralCoordinate(linear);
2678 sc2.setWorldAxisUnits(units);
2679 const uInt id = out->frequencies().addEntry(sc2.referencePixel()[0],
2680 sc2.referenceValue()[0],
2681 sc2.increment()[0]);
[926]2682 while ( !fiter.pastEnd() ) {
[1475]2683 ftab = fiter.table();
2684 // spectral coordinate for the current FREQ_ID
2685 ScalarColumn<uInt> freqidCol2(ftab, "FREQ_ID");
2686 sC = in->frequencies().getSpectralCoordinate(freqidCol2(0));
[926]2687 // create the "global" abcissa for alignment with same FREQ_ID
2688 Vector<Double> abc(nchan);
[917]2689 for (uInt i=0; i<nchan; i++) {
[1475]2690 Double w;
2691 sC.toWorld(w,Double(i));
2692 abc[i] = w;
[917]2693 }
[1475]2694 TableVector<uInt> tvec(ftab, "FREQ_ID");
2695 // assign new frequency id to all rows
2696 tvec = id;
[926]2697 // cache abcissa for same time stamps, so iterate over those
2698 TableIterator timeiter(ftab, "TIME");
2699 while ( !timeiter.pastEnd() ) {
2700 Table tab = timeiter.table();
2701 ArrayColumn<Float> specCol(tab, "SPECTRA");
2702 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2703 MEpoch::ROScalarColumn timeCol(tab, "TIME");
2704 // use align abcissa cache after the first row
[1475]2705 // these rows should be just be POLNO
[926]2706 bool first = true;
[996]2707 for (int i=0; i<int(tab.nrow()); ++i) {
[926]2708 // input values
2709 Vector<uChar> flag = flagCol(i);
2710 Vector<Bool> mask(flag.shape());
2711 Vector<Float> specOut, spec;
2712 spec = specCol(i);
2713 Vector<Bool> maskOut;Vector<uChar> flagOut;
2714 convertArray(mask, flag);
2715 // alignment
2716 Bool ok = fa.align(specOut, maskOut, abc, spec,
2717 mask, timeCol(i), !first,
2718 interp, False);
[2163]2719 (void) ok; // unused stop compiler nagging
[926]2720 // back into scantable
2721 flagOut.resize(maskOut.nelements());
2722 convertArray(flagOut, maskOut);
2723 flagCol.put(i, flagOut);
2724 specCol.put(i, specOut);
2725 // start abcissa caching
2726 first = false;
[917]2727 }
[926]2728 // next timestamp
2729 ++timeiter;
[917]2730 }
[940]2731 // next FREQ_ID
[926]2732 ++fiter;
[917]2733 }
2734 // next aligner
2735 ++iter;
2736 }
[940]2737 // set this afterwards to ensure we are doing insitu correctly.
2738 out->frequencies().setFrame(system, true);
[917]2739 return out;
2740}
[992]2741
2742CountedPtr<Scantable>
2743 asap::STMath::convertPolarisation( const CountedPtr<Scantable>& in,
2744 const std::string & newtype )
2745{
2746 if (in->npol() != 2 && in->npol() != 4)
2747 throw(AipsError("Can only convert two or four polarisations."));
2748 if ( in->getPolType() == newtype )
2749 throw(AipsError("No need to convert."));
[1000]2750 if ( ! in->selector_.empty() )
2751 throw(AipsError("Can only convert whole scantable. Unset the selection."));
[992]2752 bool insitu = insitu_;
2753 setInsitu(false);
2754 CountedPtr< Scantable > out = getScantable(in, true);
2755 setInsitu(insitu);
2756 Table& tout = out->table();
2757 tout.rwKeywordSet().define("POLTYPE", String(newtype));
2758
2759 Block<String> cols(4);
2760 cols[0] = "SCANNO";
2761 cols[1] = "CYCLENO";
2762 cols[2] = "BEAMNO";
2763 cols[3] = "IFNO";
2764 TableIterator it(in->originalTable_, cols);
2765 String basetype = in->getPolType();
2766 STPol* stpol = STPol::getPolClass(in->factories_, basetype);
2767 try {
2768 while ( !it.pastEnd() ) {
2769 Table tab = it.table();
2770 uInt row = tab.rowNumbers()[0];
2771 stpol->setSpectra(in->getPolMatrix(row));
[1586]2772 Float fang,fhand;
2773 fang = in->focusTable_.getTotalAngle(in->mfocusidCol_(row));
[992]2774 fhand = in->focusTable_.getFeedHand(in->mfocusidCol_(row));
[1586]2775 stpol->setPhaseCorrections(fang, fhand);
[992]2776 Int npolout = 0;
2777 for (uInt i=0; i<tab.nrow(); ++i) {
2778 Vector<Float> outvec = stpol->getSpectrum(i, newtype);
2779 if ( outvec.nelements() > 0 ) {
2780 tout.addRow();
2781 TableCopy::copyRows(tout, tab, tout.nrow()-1, 0, 1);
2782 ArrayColumn<Float> sCol(tout,"SPECTRA");
2783 ScalarColumn<uInt> pCol(tout,"POLNO");
2784 sCol.put(tout.nrow()-1 ,outvec);
2785 pCol.put(tout.nrow()-1 ,uInt(npolout));
2786 npolout++;
2787 }
2788 }
2789 tout.rwKeywordSet().define("nPol", npolout);
2790 ++it;
2791 }
2792 } catch (AipsError& e) {
2793 delete stpol;
2794 throw(e);
2795 }
2796 delete stpol;
2797 return out;
2798}
[1066]2799
[1143]2800CountedPtr< Scantable >
[1140]2801 asap::STMath::mxExtract( const CountedPtr< Scantable > & in,
2802 const std::string & scantype )
2803{
2804 bool insitu = insitu_;
2805 setInsitu(false);
2806 CountedPtr< Scantable > out = getScantable(in, true);
2807 setInsitu(insitu);
2808 Table& tout = out->table();
2809 std::string taql = "SELECT FROM $1 WHERE BEAMNO != REFBEAMNO";
2810 if (scantype == "on") {
2811 taql = "SELECT FROM $1 WHERE BEAMNO == REFBEAMNO";
2812 }
2813 Table tab = tableCommand(taql, in->table());
2814 TableCopy::copyRows(tout, tab);
2815 if (scantype == "on") {
[1143]2816 // re-index SCANNO to 0
[1140]2817 TableVector<uInt> vec(tout, "SCANNO");
2818 vec = 0;
2819 }
2820 return out;
2821}
[1192]2822
2823CountedPtr< Scantable >
2824 asap::STMath::lagFlag( const CountedPtr< Scantable > & in,
[1579]2825 double start, double end,
2826 const std::string& mode)
[1192]2827{
2828 CountedPtr< Scantable > out = getScantable(in, false);
2829 Table& tout = out->table();
2830 TableIterator iter(tout, "FREQ_ID");
2831 FFTServer<Float,Complex> ffts;
2832 while ( !iter.pastEnd() ) {
2833 Table tab = iter.table();
2834 Double rp,rv,inc;
2835 ROTableRow row(tab);
2836 const TableRecord& rec = row.get(0);
2837 uInt freqid = rec.asuInt("FREQ_ID");
2838 out->frequencies().getEntry(rp, rv, inc, freqid);
2839 ArrayColumn<Float> specCol(tab, "SPECTRA");
2840 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2841 for (int i=0; i<int(tab.nrow()); ++i) {
2842 Vector<Float> spec = specCol(i);
2843 Vector<uChar> flag = flagCol(i);
[1579]2844 int fstart = -1;
2845 int fend = -1;
[1819]2846 for (unsigned int k=0; k < flag.nelements(); ++k ) {
[1192]2847 if (flag[k] > 0) {
[1579]2848 fstart = k;
2849 while (flag[k] > 0 && k < flag.nelements()) {
2850 fend = k;
2851 k++;
2852 }
[1192]2853 }
[1579]2854 Float interp = 0.0;
2855 if (fstart-1 > 0 ) {
2856 interp = spec[fstart-1];
[2125]2857 if (fend+1 < Int(spec.nelements())) {
[1579]2858 interp = (interp+spec[fend+1])/2.0;
2859 }
2860 } else {
2861 interp = spec[fend+1];
2862 }
2863 if (fstart > -1 && fend > -1) {
2864 for (int j=fstart;j<=fend;++j) {
2865 spec[j] = interp;
2866 }
2867 }
2868 fstart =-1;
2869 fend = -1;
[1192]2870 }
2871 Vector<Complex> lags;
[1203]2872 ffts.fft0(lags, spec);
[1579]2873 Int lag0(start+0.5);
2874 Int lag1(end+0.5);
2875 if (mode == "frequency") {
2876 lag0 = Int(spec.nelements()*abs(inc)/(start)+0.5);
2877 lag1 = Int(spec.nelements()*abs(inc)/(end)+0.5);
2878 }
2879 Int lstart = max(0, lag0);
2880 Int lend = min(Int(lags.nelements()-1), lag1);
2881 if (lstart == lend) {
2882 lags[lstart] = Complex(0.0);
[1192]2883 } else {
[1579]2884 if (lstart > lend) {
2885 Int tmp = lend;
2886 lend = lstart;
2887 lstart = tmp;
2888 }
2889 for (int j=lstart; j <=lend ;++j) {
[1192]2890 lags[j] = Complex(0.0);
2891 }
2892 }
[1203]2893 ffts.fft0(spec, lags);
[1192]2894 specCol.put(i, spec);
2895 }
2896 ++iter;
2897 }
2898 return out;
2899}
[1819]2900
2901// Averaging spectra with different channel/resolution
2902CountedPtr<Scantable>
2903STMath::new_average( const std::vector<CountedPtr<Scantable> >& in,
2904 const bool& compel,
2905 const std::vector<bool>& mask,
2906 const std::string& weight,
2907 const std::string& avmode )
2908 throw ( casa::AipsError )
2909{
2910 LogIO os( LogOrigin( "STMath", "new_average()", WHERE ) ) ;
2911 if ( avmode == "SCAN" && in.size() != 1 )
2912 throw(AipsError("Can't perform 'SCAN' averaging on multiple tables.\n"
2913 "Use merge first."));
2914
2915 // check if OTF observation
2916 String obstype = in[0]->getHeader().obstype ;
2917 Double tol = 0.0 ;
2918 if ( obstype.find( "OTF" ) != String::npos ) {
2919 tol = TOL_OTF ;
2920 }
2921 else {
2922 tol = TOL_POINT ;
2923 }
2924
2925 CountedPtr<Scantable> out ; // processed result
2926 if ( compel ) {
2927 std::vector< CountedPtr<Scantable> > newin ; // input for average process
2928 uInt insize = in.size() ; // number of input scantables
2929
2930 // TEST: do normal average in each table before IF grouping
2931 os << "Do preliminary averaging" << LogIO::POST ;
2932 vector< CountedPtr<Scantable> > tmpin( insize ) ;
2933 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
2934 vector< CountedPtr<Scantable> > v( 1, in[itable] ) ;
2935 tmpin[itable] = average( v, mask, weight, avmode ) ;
2936 }
2937
2938 // warning
2939 os << "Average spectra with different spectral resolution" << LogIO::POST ;
2940
2941 // temporarily set coordinfo
2942 vector<string> oldinfo( insize ) ;
2943 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
2944 vector<string> coordinfo = in[itable]->getCoordInfo() ;
2945 oldinfo[itable] = coordinfo[0] ;
2946 coordinfo[0] = "Hz" ;
2947 tmpin[itable]->setCoordInfo( coordinfo ) ;
2948 }
2949
2950 // columns
2951 ScalarColumn<uInt> freqIDCol ;
2952 ScalarColumn<uInt> ifnoCol ;
2953 ScalarColumn<uInt> scannoCol ;
2954
2955
2956 // check IF frequency coverage
2957 // freqid: list of FREQ_ID, which is used, in each table
2958 // iffreq: list of minimum and maximum frequency for each FREQ_ID in
2959 // each table
2960 // freqid[insize][numIF]
2961 // freqid: [[id00, id01, ...],
2962 // [id10, id11, ...],
2963 // ...
2964 // [idn0, idn1, ...]]
2965 // iffreq[insize][numIF*2]
2966 // iffreq: [[min_id00, max_id00, min_id01, max_id01, ...],
2967 // [min_id10, max_id10, min_id11, max_id11, ...],
2968 // ...
2969 // [min_idn0, max_idn0, min_idn1, max_idn1, ...]]
2970 //os << "Check IF settings in each table" << LogIO::POST ;
2971 vector< vector<uInt> > freqid( insize );
2972 vector< vector<double> > iffreq( insize ) ;
2973 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
2974 uInt rows = tmpin[itable]->nrow() ;
2975 uInt freqnrows = tmpin[itable]->frequencies().table().nrow() ;
2976 for ( uInt irow = 0 ; irow < rows ; irow++ ) {
2977 if ( freqid[itable].size() == freqnrows ) {
2978 break ;
2979 }
2980 else {
2981 freqIDCol.attach( tmpin[itable]->table(), "FREQ_ID" ) ;
2982 ifnoCol.attach( tmpin[itable]->table(), "IFNO" ) ;
2983 uInt id = freqIDCol( irow ) ;
2984 if ( freqid[itable].size() == 0 || count( freqid[itable].begin(), freqid[itable].end(), id ) == 0 ) {
2985 //os << "itable = " << itable << ": IF " << id << " is included in the list" << LogIO::POST ;
2986 vector<double> abcissa = tmpin[itable]->getAbcissa( irow ) ;
2987 freqid[itable].push_back( id ) ;
2988 iffreq[itable].push_back( abcissa[0] - 0.5 * ( abcissa[1] - abcissa[0] ) ) ;
2989 iffreq[itable].push_back( abcissa[abcissa.size()-1] + 0.5 * ( abcissa[1] - abcissa[0] ) ) ;
2990 }
2991 }
2992 }
2993 }
2994
2995 // debug
2996 //os << "IF settings summary:" << endl ;
2997 //for ( uInt i = 0 ; i < freqid.size() ; i++ ) {
2998 //os << " Table" << i << endl ;
2999 //for ( uInt j = 0 ; j < freqid[i].size() ; j++ ) {
3000 //os << " id = " << freqid[i][j] << " (min,max) = (" << iffreq[i][2*j] << "," << iffreq[i][2*j+1] << ")" << endl ;
3001 //}
3002 //}
3003 //os << endl ;
3004 //os.post() ;
3005
3006 // IF grouping based on their frequency coverage
3007 // ifgrp: list of table index and FREQ_ID for all members in each IF group
3008 // ifgfreq: list of minimum and maximum frequency in each IF group
3009 // ifgrp[numgrp][nummember*2]
3010 // ifgrp: [[table00, freqrow00, table01, freqrow01, ...],
3011 // [table10, freqrow10, table11, freqrow11, ...],
3012 // ...
3013 // [tablen0, freqrown0, tablen1, freqrown1, ...]]
3014 // ifgfreq[numgrp*2]
3015 // ifgfreq: [min0_grp0, max0_grp0, min1_grp1, max1_grp1, ...]
3016 //os << "IF grouping based on their frequency coverage" << LogIO::POST ;
3017 vector< vector<uInt> > ifgrp ;
3018 vector<double> ifgfreq ;
3019
3020 // parameter for IF grouping
3021 // groupmode = OR retrieve all region
3022 // AND only retrieve overlaped region
3023 //string groupmode = "AND" ;
3024 string groupmode = "OR" ;
3025 uInt sizecr = 0 ;
3026 if ( groupmode == "AND" )
3027 sizecr = 2 ;
3028 else if ( groupmode == "OR" )
3029 sizecr = 0 ;
3030
3031 vector<double> sortedfreq ;
3032 for ( uInt i = 0 ; i < iffreq.size() ; i++ ) {
3033 for ( uInt j = 0 ; j < iffreq[i].size() ; j++ ) {
3034 if ( count( sortedfreq.begin(), sortedfreq.end(), iffreq[i][j] ) == 0 )
3035 sortedfreq.push_back( iffreq[i][j] ) ;
3036 }
3037 }
3038 sort( sortedfreq.begin(), sortedfreq.end() ) ;
3039 for ( vector<double>::iterator i = sortedfreq.begin() ; i != sortedfreq.end()-1 ; i++ ) {
3040 ifgfreq.push_back( *i ) ;
3041 ifgfreq.push_back( *(i+1) ) ;
3042 }
3043 ifgrp.resize( ifgfreq.size()/2 ) ;
3044 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3045 for ( uInt iif = 0 ; iif < freqid[itable].size() ; iif++ ) {
3046 double range0 = iffreq[itable][2*iif] ;
3047 double range1 = iffreq[itable][2*iif+1] ;
3048 for ( uInt j = 0 ; j < ifgrp.size() ; j++ ) {
3049 double fmin = max( range0, ifgfreq[2*j] ) ;
3050 double fmax = min( range1, ifgfreq[2*j+1] ) ;
3051 if ( fmin < fmax ) {
3052 ifgrp[j].push_back( itable ) ;
3053 ifgrp[j].push_back( freqid[itable][iif] ) ;
3054 }
3055 }
3056 }
3057 }
3058 vector< vector<uInt> >::iterator fiter = ifgrp.begin() ;
3059 vector<double>::iterator giter = ifgfreq.begin() ;
3060 while( fiter != ifgrp.end() ) {
3061 if ( fiter->size() <= sizecr ) {
3062 fiter = ifgrp.erase( fiter ) ;
3063 giter = ifgfreq.erase( giter ) ;
3064 giter = ifgfreq.erase( giter ) ;
3065 }
3066 else {
3067 fiter++ ;
3068 advance( giter, 2 ) ;
3069 }
3070 }
3071
3072 // Grouping continuous IF groups (without frequency gap)
3073 // freqgrp: list of IF group indexes in each frequency group
3074 // freqrange: list of minimum and maximum frequency in each frequency group
3075 // freqgrp[numgrp][nummember]
3076 // freqgrp: [[ifgrp00, ifgrp01, ifgrp02, ...],
3077 // [ifgrp10, ifgrp11, ifgrp12, ...],
3078 // ...
3079 // [ifgrpn0, ifgrpn1, ifgrpn2, ...]]
3080 // freqrange[numgrp*2]
3081 // freqrange: [min_grp0, max_grp0, min_grp1, max_grp1, ...]
3082 vector< vector<uInt> > freqgrp ;
3083 double freqrange = 0.0 ;
3084 uInt grpnum = 0 ;
3085 for ( uInt i = 0 ; i < ifgrp.size() ; i++ ) {
3086 // Assumed that ifgfreq was sorted
3087 if ( grpnum != 0 && freqrange == ifgfreq[2*i] ) {
3088 freqgrp[grpnum-1].push_back( i ) ;
3089 }
3090 else {
3091 vector<uInt> grp0( 1, i ) ;
3092 freqgrp.push_back( grp0 ) ;
3093 grpnum++ ;
3094 }
3095 freqrange = ifgfreq[2*i+1] ;
3096 }
3097
3098
3099 // print IF groups
3100 ostringstream oss ;
3101 oss << "IF Group summary: " << endl ;
3102 oss << " GROUP_ID [FREQ_MIN, FREQ_MAX]: (TABLE_ID, FREQ_ID)" << endl ;
3103 for ( uInt i = 0 ; i < ifgrp.size() ; i++ ) {
3104 oss << " GROUP " << setw( 2 ) << i << " [" << ifgfreq[2*i] << "," << ifgfreq[2*i+1] << "]: " ;
3105 for ( uInt j = 0 ; j < ifgrp[i].size()/2 ; j++ ) {
3106 oss << "(" << ifgrp[i][2*j] << "," << ifgrp[i][2*j+1] << ") " ;
3107 }
3108 oss << endl ;
3109 }
3110 oss << endl ;
3111 os << oss.str() << LogIO::POST ;
3112
3113 // print frequency group
3114 oss.str("") ;
3115 oss << "Frequency Group summary: " << endl ;
3116 oss << " GROUP_ID [FREQ_MIN, FREQ_MAX]: IF_GROUP_ID" << endl ;
3117 for ( uInt i = 0 ; i < freqgrp.size() ; i++ ) {
3118 oss << " GROUP " << setw( 2 ) << i << " [" << ifgfreq[2*freqgrp[i][0]] << "," << ifgfreq[2*freqgrp[i][freqgrp[i].size()-1]+1] << "]: " ;
3119 for ( uInt j = 0 ; j < freqgrp[i].size() ; j++ ) {
3120 oss << freqgrp[i][j] << " " ;
3121 }
3122 oss << endl ;
3123 }
3124 oss << endl ;
3125 os << oss.str() << LogIO::POST ;
3126
3127 // membership check
3128 // groups: list of IF group indexes whose frequency range overlaps with
3129 // that of each table and IF
3130 // groups[numtable][numIF][nummembership]
3131 // groups: [[[grp, grp,...], [grp, grp,...],...],
3132 // [[grp, grp,...], [grp, grp,...],...],
3133 // ...
3134 // [[grp, grp,...], [grp, grp,...],...]]
3135 vector< vector< vector<uInt> > > groups( insize ) ;
3136 for ( uInt i = 0 ; i < insize ; i++ ) {
3137 groups[i].resize( freqid[i].size() ) ;
3138 }
3139 for ( uInt igrp = 0 ; igrp < ifgrp.size() ; igrp++ ) {
3140 for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) {
3141 uInt tableid = ifgrp[igrp][2*imem] ;
3142 vector<uInt>::iterator iter = find( freqid[tableid].begin(), freqid[tableid].end(), ifgrp[igrp][2*imem+1] ) ;
3143 if ( iter != freqid[tableid].end() ) {
3144 uInt rowid = distance( freqid[tableid].begin(), iter ) ;
3145 groups[tableid][rowid].push_back( igrp ) ;
3146 }
3147 }
3148 }
3149
3150 // print membership
3151 //oss.str("") ;
3152 //for ( uInt i = 0 ; i < insize ; i++ ) {
3153 //oss << "Table " << i << endl ;
3154 //for ( uInt j = 0 ; j < groups[i].size() ; j++ ) {
3155 //oss << " FREQ_ID " << setw( 2 ) << freqid[i][j] << ": " ;
3156 //for ( uInt k = 0 ; k < groups[i][j].size() ; k++ ) {
3157 //oss << setw( 2 ) << groups[i][j][k] << " " ;
3158 //}
3159 //oss << endl ;
3160 //}
3161 //}
3162 //os << oss.str() << LogIO::POST ;
3163
3164 // set back coordinfo
3165 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3166 vector<string> coordinfo = tmpin[itable]->getCoordInfo() ;
3167 coordinfo[0] = oldinfo[itable] ;
3168 tmpin[itable]->setCoordInfo( coordinfo ) ;
3169 }
3170
3171 // Create additional table if needed
3172 bool oldInsitu = insitu_ ;
3173 setInsitu( false ) ;
3174 vector< vector<uInt> > addrow( insize ) ;
3175 vector<uInt> addtable( insize, 0 ) ;
3176 vector<uInt> newtableids( insize ) ;
3177 vector<uInt> newifids( insize, 0 ) ;
3178 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3179 //os << "Table " << itable << ": " ;
3180 for ( uInt ifrow = 0 ; ifrow < groups[itable].size() ; ifrow++ ) {
3181 addrow[itable].push_back( groups[itable][ifrow].size()-1 ) ;
3182 //os << addrow[itable][ifrow] << " " ;
3183 }
3184 addtable[itable] = *max_element( addrow[itable].begin(), addrow[itable].end() ) ;
3185 //os << "(" << addtable[itable] << ")" << LogIO::POST ;
3186 }
3187 newin.resize( insize ) ;
3188 copy( tmpin.begin(), tmpin.end(), newin.begin() ) ;
3189 for ( uInt i = 0 ; i < insize ; i++ ) {
3190 newtableids[i] = i ;
3191 }
3192 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3193 for ( uInt iadd = 0 ; iadd < addtable[itable] ; iadd++ ) {
3194 CountedPtr<Scantable> add = getScantable( newin[itable], false ) ;
3195 vector<int> freqidlist ;
3196 for ( uInt i = 0 ; i < groups[itable].size() ; i++ ) {
3197 if ( groups[itable][i].size() > iadd + 1 ) {
3198 freqidlist.push_back( freqid[itable][i] ) ;
3199 }
3200 }
3201 stringstream taqlstream ;
3202 taqlstream << "SELECT FROM $1 WHERE FREQ_ID IN [" ;
3203 for ( uInt i = 0 ; i < freqidlist.size() ; i++ ) {
[2133]3204 taqlstream << freqidlist[i] ;
[1819]3205 if ( i < freqidlist.size() - 1 )
3206 taqlstream << "," ;
3207 else
3208 taqlstream << "]" ;
3209 }
3210 string taql = taqlstream.str() ;
3211 //os << "taql = " << taql << LogIO::POST ;
3212 STSelector selector = STSelector() ;
3213 selector.setTaQL( taql ) ;
3214 add->setSelection( selector ) ;
3215 newin.push_back( add ) ;
3216 newtableids.push_back( itable ) ;
3217 newifids.push_back( iadd + 1 ) ;
3218 }
3219 }
3220
3221 // udpate ifgrp
3222 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3223 for ( uInt iadd = 0 ; iadd < addtable[itable] ; iadd++ ) {
3224 for ( uInt ifrow = 0 ; ifrow < groups[itable].size() ; ifrow++ ) {
3225 if ( groups[itable][ifrow].size() > iadd + 1 ) {
3226 uInt igrp = groups[itable][ifrow][iadd+1] ;
3227 for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) {
3228 if ( ifgrp[igrp][2*imem] == newtableids[iadd+insize] && ifgrp[igrp][2*imem+1] == freqid[newtableids[iadd+insize]][ifrow] ) {
3229 ifgrp[igrp][2*imem] = insize + iadd ;
3230 }
3231 }
3232 }
3233 }
3234 }
3235 }
3236
3237 // print IF groups again for debug
3238 //oss.str( "" ) ;
3239 //oss << "IF Group summary: " << endl ;
3240 //oss << " GROUP_ID [FREQ_MIN, FREQ_MAX]: (TABLE_ID, FREQ_ID)" << endl ;
3241 //for ( uInt i = 0 ; i < ifgrp.size() ; i++ ) {
3242 //oss << " GROUP " << setw( 2 ) << i << " [" << ifgfreq[2*i] << "," << ifgfreq[2*i+1] << "]: " ;
3243 //for ( uInt j = 0 ; j < ifgrp[i].size()/2 ; j++ ) {
3244 //oss << "(" << ifgrp[i][2*j] << "," << ifgrp[i][2*j+1] << ") " ;
3245 //}
3246 //oss << endl ;
3247 //}
3248 //oss << endl ;
3249 //os << oss.str() << LogIO::POST ;
3250
3251 // reset SCANNO and IFNO/FREQ_ID: IF is reset by the result of sortation
3252 os << "All scan number is set to 0" << LogIO::POST ;
3253 //os << "All IF number is set to IF group index" << LogIO::POST ;
3254 insize = newin.size() ;
3255 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3256 uInt rows = newin[itable]->nrow() ;
3257 Table &tmpt = newin[itable]->table() ;
3258 freqIDCol.attach( tmpt, "FREQ_ID" ) ;
3259 scannoCol.attach( tmpt, "SCANNO" ) ;
3260 ifnoCol.attach( tmpt, "IFNO" ) ;
3261 for ( uInt irow=0 ; irow < rows ; irow++ ) {
3262 scannoCol.put( irow, 0 ) ;
3263 uInt freqID = freqIDCol( irow ) ;
3264 vector<uInt>::iterator iter = find( freqid[newtableids[itable]].begin(), freqid[newtableids[itable]].end(), freqID ) ;
3265 if ( iter != freqid[newtableids[itable]].end() ) {
3266 uInt index = distance( freqid[newtableids[itable]].begin(), iter ) ;
3267 ifnoCol.put( irow, groups[newtableids[itable]][index][newifids[itable]] ) ;
3268 }
3269 else {
3270 throw(AipsError("IF grouping was wrong in additional tables.")) ;
3271 }
3272 }
3273 }
3274 oldinfo.resize( insize ) ;
3275 setInsitu( oldInsitu ) ;
3276
3277 // temporarily set coordinfo
3278 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3279 vector<string> coordinfo = newin[itable]->getCoordInfo() ;
3280 oldinfo[itable] = coordinfo[0] ;
3281 coordinfo[0] = "Hz" ;
3282 newin[itable]->setCoordInfo( coordinfo ) ;
3283 }
3284
3285 // save column values in the vector
3286 vector< vector<uInt> > freqTableIdVec( insize ) ;
3287 vector< vector<uInt> > freqIdVec( insize ) ;
3288 vector< vector<uInt> > ifNoVec( insize ) ;
3289 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3290 ScalarColumn<uInt> freqIDs ;
3291 freqIDs.attach( newin[itable]->frequencies().table(), "ID" ) ;
3292 ifnoCol.attach( newin[itable]->table(), "IFNO" ) ;
3293 freqIDCol.attach( newin[itable]->table(), "FREQ_ID" ) ;
3294 for ( uInt irow = 0 ; irow < newin[itable]->frequencies().table().nrow() ; irow++ ) {
3295 freqTableIdVec[itable].push_back( freqIDs( irow ) ) ;
3296 }
3297 for ( uInt irow = 0 ; irow < newin[itable]->table().nrow() ; irow++ ) {
3298 freqIdVec[itable].push_back( freqIDCol( irow ) ) ;
3299 ifNoVec[itable].push_back( ifnoCol( irow ) ) ;
3300 }
3301 }
3302
3303 // reset spectra and flagtra: pick up common part of frequency coverage
3304 //os << "Pick common frequency range and align resolution" << LogIO::POST ;
3305 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3306 uInt rows = newin[itable]->nrow() ;
3307 int nminchan = -1 ;
3308 int nmaxchan = -1 ;
3309 vector<uInt> freqIdUpdate ;
3310 for ( uInt irow = 0 ; irow < rows ; irow++ ) {
3311 uInt ifno = ifNoVec[itable][irow] ; // IFNO is reset by group index
3312 double minfreq = ifgfreq[2*ifno] ;
3313 double maxfreq = ifgfreq[2*ifno+1] ;
3314 //os << "frequency range: [" << minfreq << "," << maxfreq << "]" << LogIO::POST ;
3315 vector<double> abcissa = newin[itable]->getAbcissa( irow ) ;
3316 int nchan = abcissa.size() ;
3317 double resol = abcissa[1] - abcissa[0] ;
3318 //os << "abcissa range : [" << abcissa[0] << "," << abcissa[nchan-1] << "]" << LogIO::POST ;
3319 if ( minfreq <= abcissa[0] )
3320 nminchan = 0 ;
3321 else {
3322 //double cfreq = ( minfreq - abcissa[0] ) / resol ;
3323 double cfreq = ( minfreq - abcissa[0] + 0.5 * resol ) / resol ;
3324 nminchan = int(cfreq) + ( ( cfreq - int(cfreq) <= 0.5 ) ? 0 : 1 ) ;
3325 }
3326 if ( maxfreq >= abcissa[abcissa.size()-1] )
3327 nmaxchan = abcissa.size() - 1 ;
3328 else {
3329 //double cfreq = ( abcissa[abcissa.size()-1] - maxfreq ) / resol ;
3330 double cfreq = ( abcissa[abcissa.size()-1] - maxfreq + 0.5 * resol ) / resol ;
3331 nmaxchan = abcissa.size() - 1 - int(cfreq) - ( ( cfreq - int(cfreq) >= 0.5 ) ? 1 : 0 ) ;
3332 }
3333 //os << "channel range (" << irow << "): [" << nminchan << "," << nmaxchan << "]" << LogIO::POST ;
3334 if ( nmaxchan > nminchan ) {
3335 newin[itable]->reshapeSpectrum( nminchan, nmaxchan, irow ) ;
3336 int newchan = nmaxchan - nminchan + 1 ;
3337 if ( count( freqIdUpdate.begin(), freqIdUpdate.end(), freqIdVec[itable][irow] ) == 0 && newchan < nchan )
3338 freqIdUpdate.push_back( freqIdVec[itable][irow] ) ;
3339 }
3340 else {
3341 throw(AipsError("Failed to pick up common part of frequency range.")) ;
3342 }
3343 }
3344 for ( uInt i = 0 ; i < freqIdUpdate.size() ; i++ ) {
3345 uInt freqId = freqIdUpdate[i] ;
3346 Double refpix ;
3347 Double refval ;
3348 Double increment ;
3349
3350 // update row
3351 newin[itable]->frequencies().getEntry( refpix, refval, increment, freqId ) ;
3352 refval = refval - ( refpix - nminchan ) * increment ;
3353 refpix = 0 ;
3354 newin[itable]->frequencies().setEntry( refpix, refval, increment, freqId ) ;
3355 }
3356 }
3357
3358
3359 // reset spectra and flagtra: align spectral resolution
3360 //os << "Align spectral resolution" << LogIO::POST ;
3361 // gmaxdnu: the coarsest frequency resolution in the frequency group
3362 // gmemid: member index that have a resolution equal to gmaxdnu
3363 // gmaxdnu[numfreqgrp]
3364 // gmaxdnu: [dnu0, dnu1, ...]
3365 // gmemid[numfreqgrp]
3366 // gmemid: [id0, id1, ...]
3367 vector<double> gmaxdnu( freqgrp.size(), 0.0 ) ;
3368 vector<uInt> gmemid( freqgrp.size(), 0 ) ;
3369 for ( uInt igrp = 0 ; igrp < ifgrp.size() ; igrp++ ) {
3370 double maxdnu = 0.0 ; // maximum (coarsest) frequency resolution
3371 int minchan = INT_MAX ; // minimum channel number
3372 Double refpixref = -1 ; // reference of 'reference pixel'
3373 Double refvalref = -1 ; // reference of 'reference frequency'
3374 Double refinc = -1 ; // reference frequency resolution
3375 uInt refreqid ;
3376 uInt reftable = INT_MAX;
3377 // process only if group member > 1
3378 if ( ifgrp[igrp].size() > 2 ) {
3379 // find minchan and maxdnu in each group
3380 for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) {
3381 uInt tableid = ifgrp[igrp][2*imem] ;
3382 uInt rowid = ifgrp[igrp][2*imem+1] ;
3383 vector<uInt>::iterator iter = find( freqIdVec[tableid].begin(), freqIdVec[tableid].end(), rowid ) ;
3384 if ( iter != freqIdVec[tableid].end() ) {
3385 uInt index = distance( freqIdVec[tableid].begin(), iter ) ;
3386 vector<double> abcissa = newin[tableid]->getAbcissa( index ) ;
3387 int nchan = abcissa.size() ;
3388 double dnu = abcissa[1] - abcissa[0] ;
3389 //os << "GROUP " << igrp << " (" << tableid << "," << rowid << "): nchan = " << nchan << " (minchan = " << minchan << ")" << LogIO::POST ;
3390 if ( nchan < minchan ) {
3391 minchan = nchan ;
3392 maxdnu = dnu ;
3393 newin[tableid]->frequencies().getEntry( refpixref, refvalref, refinc, rowid ) ;
3394 refreqid = rowid ;
3395 reftable = tableid ;
3396 }
3397 }
3398 }
3399 // regrid spectra in each group
3400 os << "GROUP " << igrp << endl ;
3401 os << " Channel number is adjusted to " << minchan << endl ;
3402 os << " Corresponding frequency resolution is " << maxdnu << "Hz" << LogIO::POST ;
3403 for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) {
3404 uInt tableid = ifgrp[igrp][2*imem] ;
3405 uInt rowid = ifgrp[igrp][2*imem+1] ;
3406 freqIDCol.attach( newin[tableid]->table(), "FREQ_ID" ) ;
3407 //os << "tableid = " << tableid << " rowid = " << rowid << ": " << LogIO::POST ;
3408 //os << " regridChannel applied to " ;
[2133]3409 //if ( tableid != reftable )
3410 refreqid = newin[tableid]->frequencies().addEntry( refpixref, refvalref, refinc ) ;
[1819]3411 for ( uInt irow = 0 ; irow < newin[tableid]->table().nrow() ; irow++ ) {
3412 uInt tfreqid = freqIdVec[tableid][irow] ;
3413 if ( tfreqid == rowid ) {
3414 //os << irow << " " ;
3415 newin[tableid]->regridChannel( minchan, maxdnu, irow ) ;
3416 freqIDCol.put( irow, refreqid ) ;
3417 freqIdVec[tableid][irow] = refreqid ;
3418 }
3419 }
3420 //os << LogIO::POST ;
3421 }
3422 }
3423 else {
3424 uInt tableid = ifgrp[igrp][0] ;
3425 uInt rowid = ifgrp[igrp][1] ;
3426 vector<uInt>::iterator iter = find( freqIdVec[tableid].begin(), freqIdVec[tableid].end(), rowid ) ;
3427 if ( iter != freqIdVec[tableid].end() ) {
3428 uInt index = distance( freqIdVec[tableid].begin(), iter ) ;
3429 vector<double> abcissa = newin[tableid]->getAbcissa( index ) ;
3430 minchan = abcissa.size() ;
3431 maxdnu = abcissa[1] - abcissa[0] ;
3432 }
3433 }
3434 for ( uInt i = 0 ; i < freqgrp.size() ; i++ ) {
3435 if ( count( freqgrp[i].begin(), freqgrp[i].end(), igrp ) > 0 ) {
3436 if ( maxdnu > gmaxdnu[i] ) {
3437 gmaxdnu[i] = maxdnu ;
3438 gmemid[i] = igrp ;
3439 }
3440 break ;
3441 }
3442 }
3443 }
3444
3445 // set back coordinfo
3446 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3447 vector<string> coordinfo = newin[itable]->getCoordInfo() ;
3448 coordinfo[0] = oldinfo[itable] ;
3449 newin[itable]->setCoordInfo( coordinfo ) ;
3450 }
3451
3452 // accumulate all rows into the first table
3453 // NOTE: assumed in.size() = 1
3454 vector< CountedPtr<Scantable> > tmp( 1 ) ;
3455 if ( newin.size() == 1 )
3456 tmp[0] = newin[0] ;
3457 else
3458 tmp[0] = merge( newin ) ;
3459
3460 //return tmp[0] ;
3461
3462 // average
3463 CountedPtr<Scantable> tmpout = average( tmp, mask, weight, avmode ) ;
3464
3465 //return tmpout ;
3466
3467 // combine frequency group
3468 os << "Combine spectra based on frequency grouping" << LogIO::POST ;
3469 os << "IFNO is renumbered as frequency group ID (see above)" << LogIO::POST ;
3470 vector<string> coordinfo = tmpout->getCoordInfo() ;
3471 oldinfo[0] = coordinfo[0] ;
3472 coordinfo[0] = "Hz" ;
3473 tmpout->setCoordInfo( coordinfo ) ;
3474 // create proformas of output table
3475 stringstream taqlstream ;
3476 taqlstream << "SELECT FROM $1 WHERE IFNO IN [" ;
3477 for ( uInt i = 0 ; i < gmemid.size() ; i++ ) {
3478 taqlstream << gmemid[i] ;
3479 if ( i < gmemid.size() - 1 )
3480 taqlstream << "," ;
3481 else
3482 taqlstream << "]" ;
3483 }
3484 string taql = taqlstream.str() ;
3485 //os << "taql = " << taql << LogIO::POST ;
3486 STSelector selector = STSelector() ;
3487 selector.setTaQL( taql ) ;
3488 oldInsitu = insitu_ ;
3489 setInsitu( false ) ;
3490 out = getScantable( tmpout, false ) ;
3491 setInsitu( oldInsitu ) ;
3492 out->setSelection( selector ) ;
3493 // regrid rows
3494 ifnoCol.attach( tmpout->table(), "IFNO" ) ;
3495 for ( uInt irow = 0 ; irow < tmpout->table().nrow() ; irow++ ) {
3496 uInt ifno = ifnoCol( irow ) ;
3497 for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) {
3498 if ( count( freqgrp[igrp].begin(), freqgrp[igrp].end(), ifno ) > 0 ) {
3499 vector<double> abcissa = tmpout->getAbcissa( irow ) ;
3500 double bw = ( abcissa[1] - abcissa[0] ) * abcissa.size() ;
3501 int nchan = (int)( bw / gmaxdnu[igrp] ) ;
3502 tmpout->regridChannel( nchan, gmaxdnu[igrp], irow ) ;
3503 break ;
3504 }
3505 }
3506 }
3507 // combine spectra
3508 ArrayColumn<Float> specColOut ;
3509 specColOut.attach( out->table(), "SPECTRA" ) ;
3510 ArrayColumn<uChar> flagColOut ;
3511 flagColOut.attach( out->table(), "FLAGTRA" ) ;
3512 ScalarColumn<uInt> ifnoColOut ;
3513 ifnoColOut.attach( out->table(), "IFNO" ) ;
3514 ScalarColumn<uInt> polnoColOut ;
3515 polnoColOut.attach( out->table(), "POLNO" ) ;
3516 ScalarColumn<uInt> freqidColOut ;
3517 freqidColOut.attach( out->table(), "FREQ_ID" ) ;
3518 MDirection::ScalarColumn dirColOut ;
3519 dirColOut.attach( out->table(), "DIRECTION" ) ;
3520 Table &tab = tmpout->table() ;
3521 Block<String> cols(1);
3522 cols[0] = String("POLNO") ;
3523 TableIterator iter( tab, cols ) ;
3524 bool done = false ;
3525 vector< vector<uInt> > sizes( freqgrp.size() ) ;
3526 while( !iter.pastEnd() ) {
3527 vector< vector<Float> > specout( freqgrp.size() ) ;
3528 vector< vector<uChar> > flagout( freqgrp.size() ) ;
3529 ArrayColumn<Float> specCols ;
3530 specCols.attach( iter.table(), "SPECTRA" ) ;
3531 ArrayColumn<uChar> flagCols ;
3532 flagCols.attach( iter.table(), "FLAGTRA" ) ;
3533 ifnoCol.attach( iter.table(), "IFNO" ) ;
3534 ScalarColumn<uInt> polnos ;
3535 polnos.attach( iter.table(), "POLNO" ) ;
3536 MDirection::ScalarColumn dircol ;
3537 dircol.attach( iter.table(), "DIRECTION" ) ;
3538 uInt polno = polnos( 0 ) ;
3539 //os << "POLNO iteration: " << polno << LogIO::POST ;
3540// for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) {
3541// sizes[igrp].resize( freqgrp[igrp].size() ) ;
3542// for ( uInt imem = 0 ; imem < freqgrp[igrp].size() ; imem++ ) {
3543// for ( uInt irow = 0 ; irow < iter.table().nrow() ; irow++ ) {
3544// uInt ifno = ifnoCol( irow ) ;
3545// if ( ifno == freqgrp[igrp][imem] ) {
3546// Vector<Float> spec = specCols( irow ) ;
3547// Vector<uChar> flag = flagCols( irow ) ;
3548// vector<Float> svec ;
3549// spec.tovector( svec ) ;
3550// vector<uChar> fvec ;
3551// flag.tovector( fvec ) ;
3552// //os << "spec.size() = " << svec.size() << " fvec.size() = " << fvec.size() << LogIO::POST ;
3553// specout[igrp].insert( specout[igrp].end(), svec.begin(), svec.end() ) ;
3554// flagout[igrp].insert( flagout[igrp].end(), fvec.begin(), fvec.end() ) ;
3555// //os << "specout[" << igrp << "].size() = " << specout[igrp].size() << LogIO::POST ;
3556// sizes[igrp][imem] = spec.nelements() ;
3557// }
3558// }
3559// }
3560// for ( uInt irow = 0 ; irow < out->table().nrow() ; irow++ ) {
3561// uInt ifout = ifnoColOut( irow ) ;
3562// uInt polout = polnoColOut( irow ) ;
3563// if ( ifout == gmemid[igrp] && polout == polno ) {
3564// // set SPECTRA and FRAGTRA
3565// Vector<Float> newspec( specout[igrp] ) ;
3566// Vector<uChar> newflag( flagout[igrp] ) ;
3567// specColOut.put( irow, newspec ) ;
3568// flagColOut.put( irow, newflag ) ;
3569// // IFNO renumbering
3570// ifnoColOut.put( irow, igrp ) ;
3571// }
3572// }
3573// }
3574 // get a list of number of channels for each frequency group member
3575 if ( !done ) {
3576 for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) {
3577 sizes[igrp].resize( freqgrp[igrp].size() ) ;
3578 for ( uInt imem = 0 ; imem < freqgrp[igrp].size() ; imem++ ) {
3579 for ( uInt irow = 0 ; irow < iter.table().nrow() ; irow++ ) {
3580 uInt ifno = ifnoCol( irow ) ;
3581 if ( ifno == freqgrp[igrp][imem] ) {
3582 Vector<Float> spec = specCols( irow ) ;
3583 sizes[igrp][imem] = spec.nelements() ;
3584 break ;
3585 }
3586 }
3587 }
3588 }
3589 done = true ;
3590 }
3591 // combine spectra
3592 for ( uInt irow = 0 ; irow < out->table().nrow() ; irow++ ) {
3593 uInt polout = polnoColOut( irow ) ;
3594 if ( polout == polno ) {
3595 uInt ifout = ifnoColOut( irow ) ;
3596 Vector<Double> direction = dirColOut(irow).getAngle(Unit(String("rad"))).getValue() ;
3597 uInt igrp ;
3598 for ( uInt jgrp = 0 ; jgrp < freqgrp.size() ; jgrp++ ) {
3599 if ( ifout == gmemid[jgrp] ) {
3600 igrp = jgrp ;
3601 break ;
3602 }
3603 }
3604 for ( uInt imem = 0 ; imem < freqgrp[igrp].size() ; imem++ ) {
3605 for ( uInt jrow = 0 ; jrow < iter.table().nrow() ; jrow++ ) {
3606 uInt ifno = ifnoCol( jrow ) ;
3607 Vector<Double> tdir = dircol(jrow).getAngle(Unit(String("rad"))).getValue() ;
3608 //if ( ifno == freqgrp[igrp][imem] && allTrue( tdir == direction ) ) {
3609 Double dx = tdir[0] - direction[0] ;
3610 Double dy = tdir[1] - direction[1] ;
3611 Double dd = sqrt( dx * dx + dy * dy ) ;
3612 //if ( ifno == freqgrp[igrp][imem] && allNearAbs( tdir, direction, tol ) ) {
3613 if ( ifno == freqgrp[igrp][imem] && dd <= tol ) {
3614 Vector<Float> spec = specCols( jrow ) ;
3615 Vector<uChar> flag = flagCols( jrow ) ;
3616 vector<Float> svec ;
3617 spec.tovector( svec ) ;
3618 vector<uChar> fvec ;
3619 flag.tovector( fvec ) ;
3620 //os << "spec.size() = " << svec.size() << " fvec.size() = " << fvec.size() << LogIO::POST ;
3621 specout[igrp].insert( specout[igrp].end(), svec.begin(), svec.end() ) ;
3622 flagout[igrp].insert( flagout[igrp].end(), fvec.begin(), fvec.end() ) ;
3623 //os << "specout[" << igrp << "].size() = " << specout[igrp].size() << LogIO::POST ;
3624 }
3625 }
3626 }
3627 // set SPECTRA and FRAGTRA
3628 Vector<Float> newspec( specout[igrp] ) ;
3629 Vector<uChar> newflag( flagout[igrp] ) ;
3630 specColOut.put( irow, newspec ) ;
3631 flagColOut.put( irow, newflag ) ;
3632 // IFNO renumbering
3633 ifnoColOut.put( irow, igrp ) ;
3634 }
3635 }
3636 iter++ ;
3637 }
3638 // update FREQUENCIES subtable
3639 vector<bool> updated( freqgrp.size(), false ) ;
3640 for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) {
3641 uInt index = 0 ;
3642 uInt pixShift = 0 ;
3643 while ( freqgrp[igrp][index] != gmemid[igrp] ) {
3644 pixShift += sizes[igrp][index++] ;
3645 }
3646 for ( uInt irow = 0 ; irow < out->table().nrow() ; irow++ ) {
3647 if ( ifnoColOut( irow ) == gmemid[igrp] && !updated[igrp] ) {
3648 uInt freqidOut = freqidColOut( irow ) ;
3649 //os << "freqgrp " << igrp << " freqidOut = " << freqidOut << LogIO::POST ;
3650 double refpix ;
3651 double refval ;
3652 double increm ;
3653 out->frequencies().getEntry( refpix, refval, increm, freqidOut ) ;
3654 refpix += pixShift ;
3655 out->frequencies().setEntry( refpix, refval, increm, freqidOut ) ;
3656 updated[igrp] = true ;
3657 }
3658 }
3659 }
3660
3661 //out = tmpout ;
3662
3663 coordinfo = tmpout->getCoordInfo() ;
3664 coordinfo[0] = oldinfo[0] ;
3665 tmpout->setCoordInfo( coordinfo ) ;
3666 }
3667 else {
3668 // simple average
3669 out = average( in, mask, weight, avmode ) ;
3670 }
3671
3672 return out ;
3673}
3674
3675CountedPtr<Scantable> STMath::cwcal( const CountedPtr<Scantable>& s,
3676 const String calmode,
3677 const String antname )
3678{
3679 // frequency switch
3680 if ( calmode == "fs" ) {
3681 return cwcalfs( s, antname ) ;
3682 }
3683 else {
3684 vector<bool> masks = s->getMask( 0 ) ;
3685 vector<int> types ;
3686
3687 // sky scan
3688 STSelector sel = STSelector() ;
3689 types.push_back( SrcType::SKY ) ;
3690 sel.setTypes( types ) ;
3691 s->setSelection( sel ) ;
3692 vector< CountedPtr<Scantable> > tmp( 1, getScantable( s, false ) ) ;
3693 CountedPtr<Scantable> asky = average( tmp, masks, "TINT", "SCAN" ) ;
3694 s->unsetSelection() ;
3695 sel.reset() ;
3696 types.clear() ;
3697
3698 // hot scan
3699 types.push_back( SrcType::HOT ) ;
3700 sel.setTypes( types ) ;
3701 s->setSelection( sel ) ;
3702 tmp.clear() ;
3703 tmp.push_back( getScantable( s, false ) ) ;
3704 CountedPtr<Scantable> ahot = average( tmp, masks, "TINT", "SCAN" ) ;
3705 s->unsetSelection() ;
3706 sel.reset() ;
3707 types.clear() ;
3708
3709 // cold scan
3710 CountedPtr<Scantable> acold ;
3711// types.push_back( SrcType::COLD ) ;
3712// sel.setTypes( types ) ;
3713// s->setSelection( sel ) ;
3714// tmp.clear() ;
3715// tmp.push_back( getScantable( s, false ) ) ;
3716// CountedPtr<Scantable> acold = average( tmp, masks, "TINT", "SCNAN" ) ;
3717// s->unsetSelection() ;
3718// sel.reset() ;
3719// types.clear() ;
3720
3721 // off scan
3722 types.push_back( SrcType::PSOFF ) ;
3723 sel.setTypes( types ) ;
3724 s->setSelection( sel ) ;
3725 tmp.clear() ;
3726 tmp.push_back( getScantable( s, false ) ) ;
3727 CountedPtr<Scantable> aoff = average( tmp, masks, "TINT", "SCAN" ) ;
3728 s->unsetSelection() ;
3729 sel.reset() ;
3730 types.clear() ;
3731
3732 // on scan
3733 bool insitu = insitu_ ;
3734 insitu_ = false ;
3735 CountedPtr<Scantable> out = getScantable( s, true ) ;
3736 insitu_ = insitu ;
3737 types.push_back( SrcType::PSON ) ;
3738 sel.setTypes( types ) ;
3739 s->setSelection( sel ) ;
3740 TableCopy::copyRows( out->table(), s->table() ) ;
3741 s->unsetSelection() ;
3742 sel.reset() ;
3743 types.clear() ;
3744
3745 // process each on scan
3746 ArrayColumn<Float> tsysCol ;
3747 tsysCol.attach( out->table(), "TSYS" ) ;
3748 for ( int i = 0 ; i < out->nrow() ; i++ ) {
3749 vector<float> sp = getCalibratedSpectra( out, aoff, asky, ahot, acold, i, antname ) ;
3750 out->setSpectrum( sp, i ) ;
3751 string reftime = out->getTime( i ) ;
3752 vector<int> ii( 1, out->getIF( i ) ) ;
3753 vector<int> ib( 1, out->getBeam( i ) ) ;
3754 vector<int> ip( 1, out->getPol( i ) ) ;
3755 sel.setIFs( ii ) ;
3756 sel.setBeams( ib ) ;
3757 sel.setPolarizations( ip ) ;
3758 asky->setSelection( sel ) ;
3759 vector<float> sptsys = getTsysFromTime( reftime, asky, "linear" ) ;
3760 const Vector<Float> Vtsys( sptsys ) ;
3761 tsysCol.put( i, Vtsys ) ;
3762 asky->unsetSelection() ;
3763 sel.reset() ;
3764 }
3765
3766 // flux unit
3767 out->setFluxUnit( "K" ) ;
3768
3769 return out ;
3770 }
3771}
3772
3773CountedPtr<Scantable> STMath::almacal( const CountedPtr<Scantable>& s,
3774 const String calmode )
3775{
3776 // frequency switch
3777 if ( calmode == "fs" ) {
3778 return almacalfs( s ) ;
3779 }
3780 else {
3781 vector<bool> masks = s->getMask( 0 ) ;
3782
3783 // off scan
3784 STSelector sel = STSelector() ;
3785 vector<int> types ;
3786 types.push_back( SrcType::PSOFF ) ;
3787 sel.setTypes( types ) ;
3788 s->setSelection( sel ) ;
3789 // TODO 2010/01/08 TN
3790 // Grouping by time should be needed before averaging.
3791 // Each group must have own unique SCANNO (should be renumbered).
3792 // See PIPELINE/SDCalibration.py
3793 CountedPtr<Scantable> soff = getScantable( s, false ) ;
3794 Table ttab = soff->table() ;
3795 ROScalarColumn<Double> timeCol( ttab, "TIME" ) ;
3796 uInt nrow = timeCol.nrow() ;
3797 Vector<Double> timeSep( nrow - 1 ) ;
3798 for ( uInt i = 0 ; i < nrow - 1 ; i++ ) {
3799 timeSep[i] = timeCol(i+1) - timeCol(i) ;
3800 }
3801 ScalarColumn<Double> intervalCol( ttab, "INTERVAL" ) ;
3802 Vector<Double> interval = intervalCol.getColumn() ;
3803 interval /= 86400.0 ;
3804 ScalarColumn<uInt> scanCol( ttab, "SCANNO" ) ;
3805 vector<uInt> glist ;
3806 for ( uInt i = 0 ; i < nrow - 1 ; i++ ) {
3807 double gap = 2.0 * timeSep[i] / ( interval[i] + interval[i+1] ) ;
3808 //cout << "gap[" << i << "]=" << setw(5) << gap << endl ;
3809 if ( gap > 1.1 ) {
3810 glist.push_back( i ) ;
3811 }
3812 }
3813 Vector<uInt> gaplist( glist ) ;
3814 //cout << "gaplist = " << gaplist << endl ;
3815 uInt newid = 0 ;
3816 for ( uInt i = 0 ; i < nrow ; i++ ) {
3817 scanCol.put( i, newid ) ;
3818 if ( i == gaplist[newid] ) {
3819 newid++ ;
3820 }
3821 }
3822 //cout << "new scancol = " << scanCol.getColumn() << endl ;
3823 vector< CountedPtr<Scantable> > tmp( 1, soff ) ;
3824 CountedPtr<Scantable> aoff = average( tmp, masks, "TINT", "SCAN" ) ;
3825 //cout << "aoff.nrow = " << aoff->nrow() << endl ;
3826 s->unsetSelection() ;
3827 sel.reset() ;
3828 types.clear() ;
3829
3830 // on scan
3831 bool insitu = insitu_ ;
3832 insitu_ = false ;
3833 CountedPtr<Scantable> out = getScantable( s, true ) ;
3834 insitu_ = insitu ;
3835 types.push_back( SrcType::PSON ) ;
3836 sel.setTypes( types ) ;
3837 s->setSelection( sel ) ;
3838 TableCopy::copyRows( out->table(), s->table() ) ;
3839 s->unsetSelection() ;
3840 sel.reset() ;
3841 types.clear() ;
3842
3843 // process each on scan
3844 ArrayColumn<Float> tsysCol ;
3845 tsysCol.attach( out->table(), "TSYS" ) ;
3846 for ( int i = 0 ; i < out->nrow() ; i++ ) {
3847 vector<float> sp = getCalibratedSpectra( out, aoff, i ) ;
3848 out->setSpectrum( sp, i ) ;
3849 }
3850
3851 // flux unit
3852 out->setFluxUnit( "K" ) ;
3853
3854 return out ;
3855 }
3856}
3857
3858CountedPtr<Scantable> STMath::cwcalfs( const CountedPtr<Scantable>& s,
3859 const String antname )
3860{
3861 vector<int> types ;
3862
3863 // APEX calibration mode
3864 int apexcalmode = 1 ;
3865
3866 if ( antname.find( "APEX" ) != string::npos ) {
3867 // check if off scan exists or not
3868 STSelector sel = STSelector() ;
3869 //sel.setName( offstr1 ) ;
3870 types.push_back( SrcType::FLOOFF ) ;
3871 sel.setTypes( types ) ;
3872 try {
3873 s->setSelection( sel ) ;
3874 }
3875 catch ( AipsError &e ) {
3876 apexcalmode = 0 ;
3877 }
3878 sel.reset() ;
3879 }
3880 s->unsetSelection() ;
3881 types.clear() ;
3882
3883 vector<bool> masks = s->getMask( 0 ) ;
3884 CountedPtr<Scantable> ssig, sref ;
3885 CountedPtr<Scantable> out ;
3886
3887 if ( antname.find( "APEX" ) != string::npos ) {
3888 // APEX calibration
3889 // sky scan
3890 STSelector sel = STSelector() ;
3891 types.push_back( SrcType::FLOSKY ) ;
3892 sel.setTypes( types ) ;
3893 s->setSelection( sel ) ;
3894 vector< CountedPtr<Scantable> > tmp( 1, getScantable( s, false ) ) ;
3895 CountedPtr<Scantable> askylo = average( tmp, masks, "TINT", "SCAN" ) ;
3896 s->unsetSelection() ;
3897 sel.reset() ;
3898 types.clear() ;
3899 types.push_back( SrcType::FHISKY ) ;
3900 sel.setTypes( types ) ;
3901 s->setSelection( sel ) ;
3902 tmp.clear() ;
3903 tmp.push_back( getScantable( s, false ) ) ;
3904 CountedPtr<Scantable> askyhi = average( tmp, masks, "TINT", "SCAN" ) ;
3905 s->unsetSelection() ;
3906 sel.reset() ;
3907 types.clear() ;
3908
3909 // hot scan
3910 types.push_back( SrcType::FLOHOT ) ;
3911 sel.setTypes( types ) ;
3912 s->setSelection( sel ) ;
3913 tmp.clear() ;
3914 tmp.push_back( getScantable( s, false ) ) ;
3915 CountedPtr<Scantable> ahotlo = average( tmp, masks, "TINT", "SCAN" ) ;
3916 s->unsetSelection() ;
3917 sel.reset() ;
3918 types.clear() ;
3919 types.push_back( SrcType::FHIHOT ) ;
3920 sel.setTypes( types ) ;
3921 s->setSelection( sel ) ;
3922 tmp.clear() ;
3923 tmp.push_back( getScantable( s, false ) ) ;
3924 CountedPtr<Scantable> ahothi = average( tmp, masks, "TINT", "SCAN" ) ;
3925 s->unsetSelection() ;
3926 sel.reset() ;
3927 types.clear() ;
3928
3929 // cold scan
3930 CountedPtr<Scantable> acoldlo, acoldhi ;
3931// types.push_back( SrcType::FLOCOLD ) ;
3932// sel.setTypes( types ) ;
3933// s->setSelection( sel ) ;
3934// tmp.clear() ;
3935// tmp.push_back( getScantable( s, false ) ) ;
3936// CountedPtr<Scantable> acoldlo = average( tmp, masks, "TINT", "SCAN" ) ;
3937// s->unsetSelection() ;
3938// sel.reset() ;
3939// types.clear() ;
3940// types.push_back( SrcType::FHICOLD ) ;
3941// sel.setTypes( types ) ;
3942// s->setSelection( sel ) ;
3943// tmp.clear() ;
3944// tmp.push_back( getScantable( s, false ) ) ;
3945// CountedPtr<Scantable> acoldhi = average( tmp, masks, "TINT", "SCAN" ) ;
3946// s->unsetSelection() ;
3947// sel.reset() ;
3948// types.clear() ;
3949
3950 // ref scan
3951 bool insitu = insitu_ ;
3952 insitu_ = false ;
3953 sref = getScantable( s, true ) ;
3954 insitu_ = insitu ;
3955 types.push_back( SrcType::FSLO ) ;
3956 sel.setTypes( types ) ;
3957 s->setSelection( sel ) ;
3958 TableCopy::copyRows( sref->table(), s->table() ) ;
3959 s->unsetSelection() ;
3960 sel.reset() ;
3961 types.clear() ;
3962
3963 // sig scan
3964 insitu_ = false ;
3965 ssig = getScantable( s, true ) ;
3966 insitu_ = insitu ;
3967 types.push_back( SrcType::FSHI ) ;
3968 sel.setTypes( types ) ;
3969 s->setSelection( sel ) ;
3970 TableCopy::copyRows( ssig->table(), s->table() ) ;
3971 s->unsetSelection() ;
3972 sel.reset() ;
3973 types.clear() ;
3974
3975 if ( apexcalmode == 0 ) {
3976 // APEX fs data without off scan
3977 // process each sig and ref scan
3978 ArrayColumn<Float> tsysCollo ;
3979 tsysCollo.attach( ssig->table(), "TSYS" ) ;
3980 ArrayColumn<Float> tsysColhi ;
3981 tsysColhi.attach( sref->table(), "TSYS" ) ;
3982 for ( int i = 0 ; i < ssig->nrow() ; i++ ) {
3983 vector< CountedPtr<Scantable> > sky( 2 ) ;
3984 sky[0] = askylo ;
3985 sky[1] = askyhi ;
3986 vector< CountedPtr<Scantable> > hot( 2 ) ;
3987 hot[0] = ahotlo ;
3988 hot[1] = ahothi ;
3989 vector< CountedPtr<Scantable> > cold( 2 ) ;
3990 //cold[0] = acoldlo ;
3991 //cold[1] = acoldhi ;
3992 vector<float> sp = getFSCalibratedSpectra( ssig, sref, sky, hot, cold, i ) ;
3993 ssig->setSpectrum( sp, i ) ;
3994 string reftime = ssig->getTime( i ) ;
3995 vector<int> ii( 1, ssig->getIF( i ) ) ;
3996 vector<int> ib( 1, ssig->getBeam( i ) ) ;
3997 vector<int> ip( 1, ssig->getPol( i ) ) ;
3998 sel.setIFs( ii ) ;
3999 sel.setBeams( ib ) ;
4000 sel.setPolarizations( ip ) ;
4001 askylo->setSelection( sel ) ;
4002 vector<float> sptsys = getTsysFromTime( reftime, askylo, "linear" ) ;
4003 const Vector<Float> Vtsyslo( sptsys ) ;
4004 tsysCollo.put( i, Vtsyslo ) ;
4005 askylo->unsetSelection() ;
4006 sel.reset() ;
4007 sky[0] = askyhi ;
4008 sky[1] = askylo ;
4009 hot[0] = ahothi ;
4010 hot[1] = ahotlo ;
4011 cold[0] = acoldhi ;
4012 cold[1] = acoldlo ;
4013 sp = getFSCalibratedSpectra( sref, ssig, sky, hot, cold, i ) ;
4014 sref->setSpectrum( sp, i ) ;
4015 reftime = sref->getTime( i ) ;
4016 ii[0] = sref->getIF( i ) ;
4017 ib[0] = sref->getBeam( i ) ;
4018 ip[0] = sref->getPol( i ) ;
4019 sel.setIFs( ii ) ;
4020 sel.setBeams( ib ) ;
4021 sel.setPolarizations( ip ) ;
4022 askyhi->setSelection( sel ) ;
4023 sptsys = getTsysFromTime( reftime, askyhi, "linear" ) ;
4024 const Vector<Float> Vtsyshi( sptsys ) ;
4025 tsysColhi.put( i, Vtsyshi ) ;
4026 askyhi->unsetSelection() ;
4027 sel.reset() ;
4028 }
4029 }
4030 else if ( apexcalmode == 1 ) {
4031 // APEX fs data with off scan
4032 // off scan
4033 types.push_back( SrcType::FLOOFF ) ;
4034 sel.setTypes( types ) ;
4035 s->setSelection( sel ) ;
4036 tmp.clear() ;
4037 tmp.push_back( getScantable( s, false ) ) ;
4038 CountedPtr<Scantable> aofflo = average( tmp, masks, "TINT", "SCAN" ) ;
4039 s->unsetSelection() ;
4040 sel.reset() ;
4041 types.clear() ;
4042 types.push_back( SrcType::FHIOFF ) ;
4043 sel.setTypes( types ) ;
4044 s->setSelection( sel ) ;
4045 tmp.clear() ;
4046 tmp.push_back( getScantable( s, false ) ) ;
4047 CountedPtr<Scantable> aoffhi = average( tmp, masks, "TINT", "SCAN" ) ;
4048 s->unsetSelection() ;
4049 sel.reset() ;
4050 types.clear() ;
4051
4052 // process each sig and ref scan
4053 ArrayColumn<Float> tsysCollo ;
4054 tsysCollo.attach( ssig->table(), "TSYS" ) ;
4055 ArrayColumn<Float> tsysColhi ;
4056 tsysColhi.attach( sref->table(), "TSYS" ) ;
4057 for ( int i = 0 ; i < ssig->nrow() ; i++ ) {
4058 vector<float> sp = getCalibratedSpectra( ssig, aofflo, askylo, ahotlo, acoldlo, i, antname ) ;
4059 ssig->setSpectrum( sp, i ) ;
4060 sp = getCalibratedSpectra( sref, aoffhi, askyhi, ahothi, acoldhi, i, antname ) ;
4061 string reftime = ssig->getTime( i ) ;
4062 vector<int> ii( 1, ssig->getIF( i ) ) ;
4063 vector<int> ib( 1, ssig->getBeam( i ) ) ;
4064 vector<int> ip( 1, ssig->getPol( i ) ) ;
4065 sel.setIFs( ii ) ;
4066 sel.setBeams( ib ) ;
4067 sel.setPolarizations( ip ) ;
4068 askylo->setSelection( sel ) ;
4069 vector<float> sptsys = getTsysFromTime( reftime, askylo, "linear" ) ;
4070 const Vector<Float> Vtsyslo( sptsys ) ;
4071 tsysCollo.put( i, Vtsyslo ) ;
4072 askylo->unsetSelection() ;
4073 sel.reset() ;
4074 sref->setSpectrum( sp, i ) ;
4075 reftime = sref->getTime( i ) ;
4076 ii[0] = sref->getIF( i ) ;
4077 ib[0] = sref->getBeam( i ) ;
4078 ip[0] = sref->getPol( i ) ;
4079 sel.setIFs( ii ) ;
4080 sel.setBeams( ib ) ;
4081 sel.setPolarizations( ip ) ;
4082 askyhi->setSelection( sel ) ;
4083 sptsys = getTsysFromTime( reftime, askyhi, "linear" ) ;
4084 const Vector<Float> Vtsyshi( sptsys ) ;
4085 tsysColhi.put( i, Vtsyshi ) ;
4086 askyhi->unsetSelection() ;
4087 sel.reset() ;
4088 }
4089 }
4090 }
4091 else {
4092 // non-APEX fs data
4093 // sky scan
4094 STSelector sel = STSelector() ;
4095 types.push_back( SrcType::SKY ) ;
4096 sel.setTypes( types ) ;
4097 s->setSelection( sel ) ;
4098 vector< CountedPtr<Scantable> > tmp( 1, getScantable( s, false ) ) ;
4099 CountedPtr<Scantable> asky = average( tmp, masks, "TINT", "SCAN" ) ;
4100 s->unsetSelection() ;
4101 sel.reset() ;
4102 types.clear() ;
4103
4104 // hot scan
4105 types.push_back( SrcType::HOT ) ;
4106 sel.setTypes( types ) ;
4107 s->setSelection( sel ) ;
4108 tmp.clear() ;
4109 tmp.push_back( getScantable( s, false ) ) ;
4110 CountedPtr<Scantable> ahot = average( tmp, masks, "TINT", "SCAN" ) ;
4111 s->unsetSelection() ;
4112 sel.reset() ;
4113 types.clear() ;
4114
4115 // cold scan
4116 CountedPtr<Scantable> acold ;
4117// types.push_back( SrcType::COLD ) ;
4118// sel.setTypes( types ) ;
4119// s->setSelection( sel ) ;
4120// tmp.clear() ;
4121// tmp.push_back( getScantable( s, false ) ) ;
4122// CountedPtr<Scantable> acold = average( tmp, masks, "TINT", "SCAN" ) ;
4123// s->unsetSelection() ;
4124// sel.reset() ;
4125// types.clear() ;
4126
4127 // ref scan
4128 bool insitu = insitu_ ;
4129 insitu_ = false ;
4130 sref = getScantable( s, true ) ;
4131 insitu_ = insitu ;
4132 types.push_back( SrcType::FSOFF ) ;
4133 sel.setTypes( types ) ;
4134 s->setSelection( sel ) ;
4135 TableCopy::copyRows( sref->table(), s->table() ) ;
4136 s->unsetSelection() ;
4137 sel.reset() ;
4138 types.clear() ;
4139
4140 // sig scan
4141 insitu_ = false ;
4142 ssig = getScantable( s, true ) ;
4143 insitu_ = insitu ;
4144 types.push_back( SrcType::FSON ) ;
4145 sel.setTypes( types ) ;
4146 s->setSelection( sel ) ;
4147 TableCopy::copyRows( ssig->table(), s->table() ) ;
4148 s->unsetSelection() ;
4149 sel.reset() ;
4150 types.clear() ;
4151
4152 // process each sig and ref scan
4153 ArrayColumn<Float> tsysColsig ;
4154 tsysColsig.attach( ssig->table(), "TSYS" ) ;
4155 ArrayColumn<Float> tsysColref ;
4156 tsysColref.attach( ssig->table(), "TSYS" ) ;
4157 for ( int i = 0 ; i < ssig->nrow() ; i++ ) {
4158 vector<float> sp = getFSCalibratedSpectra( ssig, sref, asky, ahot, acold, i ) ;
4159 ssig->setSpectrum( sp, i ) ;
4160 string reftime = ssig->getTime( i ) ;
4161 vector<int> ii( 1, ssig->getIF( i ) ) ;
4162 vector<int> ib( 1, ssig->getBeam( i ) ) ;
4163 vector<int> ip( 1, ssig->getPol( i ) ) ;
4164 sel.setIFs( ii ) ;
4165 sel.setBeams( ib ) ;
4166 sel.setPolarizations( ip ) ;
4167 asky->setSelection( sel ) ;
4168 vector<float> sptsys = getTsysFromTime( reftime, asky, "linear" ) ;
4169 const Vector<Float> Vtsys( sptsys ) ;
4170 tsysColsig.put( i, Vtsys ) ;
4171 asky->unsetSelection() ;
4172 sel.reset() ;
4173 sp = getFSCalibratedSpectra( sref, ssig, asky, ahot, acold, i ) ;
4174 sref->setSpectrum( sp, i ) ;
4175 tsysColref.put( i, Vtsys ) ;
4176 }
4177 }
4178
4179 // do folding if necessary
4180 Table sigtab = ssig->table() ;
4181 Table reftab = sref->table() ;
4182 ScalarColumn<uInt> sigifnoCol ;
4183 ScalarColumn<uInt> refifnoCol ;
4184 ScalarColumn<uInt> sigfidCol ;
4185 ScalarColumn<uInt> reffidCol ;
4186 Int nchan = (Int)ssig->nchan() ;
4187 sigifnoCol.attach( sigtab, "IFNO" ) ;
4188 refifnoCol.attach( reftab, "IFNO" ) ;
4189 sigfidCol.attach( sigtab, "FREQ_ID" ) ;
4190 reffidCol.attach( reftab, "FREQ_ID" ) ;
4191 Vector<uInt> sfids( sigfidCol.getColumn() ) ;
4192 Vector<uInt> rfids( reffidCol.getColumn() ) ;
4193 vector<uInt> sfids_unique ;
4194 vector<uInt> rfids_unique ;
4195 vector<uInt> sifno_unique ;
4196 vector<uInt> rifno_unique ;
4197 for ( uInt i = 0 ; i < sfids.nelements() ; i++ ) {
4198 if ( count( sfids_unique.begin(), sfids_unique.end(), sfids[i] ) == 0 ) {
4199 sfids_unique.push_back( sfids[i] ) ;
4200 sifno_unique.push_back( ssig->getIF( i ) ) ;
4201 }
4202 if ( count( rfids_unique.begin(), rfids_unique.end(), rfids[i] ) == 0 ) {
4203 rfids_unique.push_back( rfids[i] ) ;
4204 rifno_unique.push_back( sref->getIF( i ) ) ;
4205 }
4206 }
4207 double refpix_sig, refval_sig, increment_sig ;
4208 double refpix_ref, refval_ref, increment_ref ;
4209 vector< CountedPtr<Scantable> > tmp( sfids_unique.size() ) ;
4210 for ( uInt i = 0 ; i < sfids_unique.size() ; i++ ) {
4211 ssig->frequencies().getEntry( refpix_sig, refval_sig, increment_sig, sfids_unique[i] ) ;
4212 sref->frequencies().getEntry( refpix_ref, refval_ref, increment_ref, rfids_unique[i] ) ;
4213 if ( refpix_sig == refpix_ref ) {
4214 double foffset = refval_ref - refval_sig ;
4215 int choffset = static_cast<int>(foffset/increment_sig) ;
4216 double doffset = foffset / increment_sig ;
4217 if ( abs(choffset) >= nchan ) {
4218 LogIO os( LogOrigin( "STMath", "cwcalfs", WHERE ) ) ;
4219 os << "FREQ_ID=[" << sfids_unique[i] << "," << rfids_unique[i] << "]: out-band frequency switching, no folding" << LogIO::POST ;
4220 os << "Just return signal data" << LogIO::POST ;
4221 //std::vector< CountedPtr<Scantable> > tabs ;
4222 //tabs.push_back( ssig ) ;
4223 //tabs.push_back( sref ) ;
4224 //out = merge( tabs ) ;
4225 tmp[i] = ssig ;
4226 }
4227 else {
4228 STSelector sel = STSelector() ;
4229 vector<int> v( 1, sifno_unique[i] ) ;
4230 sel.setIFs( v ) ;
4231 ssig->setSelection( sel ) ;
4232 sel.reset() ;
4233 v[0] = rifno_unique[i] ;
4234 sel.setIFs( v ) ;
4235 sref->setSelection( sel ) ;
4236 sel.reset() ;
4237 if ( antname.find( "APEX" ) != string::npos ) {
4238 tmp[i] = dofold( ssig, sref, 0.5*doffset, -0.5*doffset ) ;
4239 //tmp[i] = dofold( ssig, sref, doffset ) ;
4240 }
4241 else {
4242 tmp[i] = dofold( ssig, sref, doffset ) ;
4243 }
4244 ssig->unsetSelection() ;
4245 sref->unsetSelection() ;
4246 }
4247 }
4248 }
4249
4250 if ( tmp.size() > 1 ) {
4251 out = merge( tmp ) ;
4252 }
4253 else {
4254 out = tmp[0] ;
4255 }
4256
4257 // flux unit
4258 out->setFluxUnit( "K" ) ;
4259
4260 return out ;
4261}
4262
4263CountedPtr<Scantable> STMath::almacalfs( const CountedPtr<Scantable>& s )
4264{
[2163]4265 (void) s; //currently unused
[1819]4266 CountedPtr<Scantable> out ;
4267
4268 return out ;
4269}
4270
4271vector<float> STMath::getSpectrumFromTime( string reftime,
4272 CountedPtr<Scantable>& s,
4273 string mode )
4274{
4275 LogIO os( LogOrigin( "STMath", "getSpectrumFromTime", WHERE ) ) ;
4276 vector<float> sp ;
4277
4278 if ( s->nrow() == 0 ) {
4279 os << LogIO::SEVERE << "No spectra in the input scantable. Return empty spectrum." << LogIO::POST ;
4280 return sp ;
4281 }
4282 else if ( s->nrow() == 1 ) {
4283 //os << "use row " << 0 << " (scanno = " << s->getScan( 0 ) << ")" << LogIO::POST ;
4284 return s->getSpectrum( 0 ) ;
4285 }
4286 else {
4287 vector<int> idx = getRowIdFromTime( reftime, s ) ;
4288 if ( mode == "before" ) {
4289 int id = -1 ;
4290 if ( idx[0] != -1 ) {
4291 id = idx[0] ;
4292 }
4293 else if ( idx[1] != -1 ) {
4294 os << LogIO::WARN << "Failed to find a scan before reftime. return a spectrum just after the reftime." << LogIO::POST ;
4295 id = idx[1] ;
4296 }
4297 //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
4298 sp = s->getSpectrum( id ) ;
4299 }
4300 else if ( mode == "after" ) {
4301 int id = -1 ;
4302 if ( idx[1] != -1 ) {
4303 id = idx[1] ;
4304 }
4305 else if ( idx[0] != -1 ) {
4306 os << LogIO::WARN << "Failed to find a scan after reftime. return a spectrum just before the reftime." << LogIO::POST ;
4307 id = idx[1] ;
4308 }
4309 //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
4310 sp = s->getSpectrum( id ) ;
4311 }
4312 else if ( mode == "nearest" ) {
4313 int id = -1 ;
4314 if ( idx[0] == -1 ) {
4315 id = idx[1] ;
4316 }
4317 else if ( idx[1] == -1 ) {
4318 id = idx[0] ;
4319 }
4320 else if ( idx[0] == idx[1] ) {
4321 id = idx[0] ;
4322 }
4323 else {
[1967]4324 //double t0 = getMJD( s->getTime( idx[0] ) ) ;
4325 //double t1 = getMJD( s->getTime( idx[1] ) ) ;
4326 double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
4327 double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
[1819]4328 double tref = getMJD( reftime ) ;
4329 if ( abs( t0 - tref ) > abs( t1 - tref ) ) {
4330 id = idx[1] ;
4331 }
4332 else {
4333 id = idx[0] ;
4334 }
4335 }
4336 //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
4337 sp = s->getSpectrum( id ) ;
4338 }
4339 else if ( mode == "linear" ) {
4340 if ( idx[0] == -1 ) {
4341 // use after
4342 os << LogIO::WARN << "Failed to interpolate. return a spectrum just after the reftime." << LogIO::POST ;
4343 int id = idx[1] ;
4344 //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
4345 sp = s->getSpectrum( id ) ;
4346 }
4347 else if ( idx[1] == -1 ) {
4348 // use before
4349 os << LogIO::WARN << "Failed to interpolate. return a spectrum just before the reftime." << LogIO::POST ;
4350 int id = idx[0] ;
4351 //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
4352 sp = s->getSpectrum( id ) ;
4353 }
4354 else if ( idx[0] == idx[1] ) {
4355 // use before
4356 //os << "No need to interporate." << LogIO::POST ;
4357 int id = idx[0] ;
4358 //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
4359 sp = s->getSpectrum( id ) ;
4360 }
4361 else {
4362 // do interpolation
4363 //os << "interpolate between " << idx[0] << " and " << idx[1] << " (scanno: " << s->getScan( idx[0] ) << ", " << s->getScan( idx[1] ) << ")" << LogIO::POST ;
[1967]4364 //double t0 = getMJD( s->getTime( idx[0] ) ) ;
4365 //double t1 = getMJD( s->getTime( idx[1] ) ) ;
4366 double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
4367 double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
[1819]4368 double tref = getMJD( reftime ) ;
4369 vector<float> sp0 = s->getSpectrum( idx[0] ) ;
4370 vector<float> sp1 = s->getSpectrum( idx[1] ) ;
4371 for ( unsigned int i = 0 ; i < sp0.size() ; i++ ) {
4372 float v = ( sp1[i] - sp0[i] ) / ( t1 - t0 ) * ( tref - t0 ) + sp0[i] ;
4373 sp.push_back( v ) ;
4374 }
4375 }
4376 }
4377 else {
4378 os << LogIO::SEVERE << "Unknown mode" << LogIO::POST ;
4379 }
4380 return sp ;
4381 }
4382}
4383
4384double STMath::getMJD( string strtime )
4385{
4386 if ( strtime.find("/") == string::npos ) {
4387 // MJD time string
4388 return atof( strtime.c_str() ) ;
4389 }
4390 else {
4391 // string in YYYY/MM/DD/HH:MM:SS format
4392 uInt year = atoi( strtime.substr( 0, 4 ).c_str() ) ;
4393 uInt month = atoi( strtime.substr( 5, 2 ).c_str() ) ;
4394 uInt day = atoi( strtime.substr( 8, 2 ).c_str() ) ;
4395 uInt hour = atoi( strtime.substr( 11, 2 ).c_str() ) ;
4396 uInt minute = atoi( strtime.substr( 14, 2 ).c_str() ) ;
4397 uInt sec = atoi( strtime.substr( 17, 2 ).c_str() ) ;
4398 Time t( year, month, day, hour, minute, sec ) ;
4399 return t.modifiedJulianDay() ;
4400 }
4401}
4402
4403vector<int> STMath::getRowIdFromTime( string reftime, CountedPtr<Scantable> &s )
4404{
4405 double reft = getMJD( reftime ) ;
4406 double dtmin = 1.0e100 ;
4407 double dtmax = -1.0e100 ;
4408 vector<double> dt ;
4409 int just_before = -1 ;
4410 int just_after = -1 ;
4411 for ( int i = 0 ; i < s->nrow() ; i++ ) {
4412 dt.push_back( getMJD( s->getTime( i ) ) - reft ) ;
4413 }
4414 for ( unsigned int i = 0 ; i < dt.size() ; i++ ) {
4415 if ( dt[i] > 0.0 ) {
4416 // after reftime
4417 if ( dt[i] < dtmin ) {
4418 just_after = i ;
4419 dtmin = dt[i] ;
4420 }
4421 }
4422 else if ( dt[i] < 0.0 ) {
4423 // before reftime
4424 if ( dt[i] > dtmax ) {
4425 just_before = i ;
4426 dtmax = dt[i] ;
4427 }
4428 }
4429 else {
4430 // just a reftime
4431 just_before = i ;
4432 just_after = i ;
4433 dtmax = 0 ;
4434 dtmin = 0 ;
4435 break ;
4436 }
4437 }
4438
4439 vector<int> v ;
4440 v.push_back( just_before ) ;
4441 v.push_back( just_after ) ;
4442
4443 return v ;
4444}
4445
4446vector<float> STMath::getTcalFromTime( string reftime,
4447 CountedPtr<Scantable>& s,
4448 string mode )
4449{
4450 LogIO os( LogOrigin( "STMath", "getTcalFromTime", WHERE ) ) ;
4451 vector<float> tcal ;
4452 STTcal tcalTable = s->tcal() ;
4453 String time ;
4454 Vector<Float> tcalval ;
4455 if ( s->nrow() == 0 ) {
4456 os << LogIO::SEVERE << "No row in the input scantable. Return empty tcal." << LogIO::POST ;
4457 return tcal ;
4458 }
4459 else if ( s->nrow() == 1 ) {
4460 uInt tcalid = s->getTcalId( 0 ) ;
4461 //os << "use row " << 0 << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4462 tcalTable.getEntry( time, tcalval, tcalid ) ;
4463 tcalval.tovector( tcal ) ;
4464 return tcal ;
4465 }
4466 else {
4467 vector<int> idx = getRowIdFromTime( reftime, s ) ;
4468 if ( mode == "before" ) {
4469 int id = -1 ;
4470 if ( idx[0] != -1 ) {
4471 id = idx[0] ;
4472 }
4473 else if ( idx[1] != -1 ) {
4474 os << LogIO::WARN << "Failed to find a scan before reftime. return a spectrum just after the reftime." << LogIO::POST ;
4475 id = idx[1] ;
4476 }
4477 uInt tcalid = s->getTcalId( id ) ;
4478 //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4479 tcalTable.getEntry( time, tcalval, tcalid ) ;
4480 tcalval.tovector( tcal ) ;
4481 }
4482 else if ( mode == "after" ) {
4483 int id = -1 ;
4484 if ( idx[1] != -1 ) {
4485 id = idx[1] ;
4486 }
4487 else if ( idx[0] != -1 ) {
4488 os << LogIO::WARN << "Failed to find a scan after reftime. return a spectrum just before the reftime." << LogIO::POST ;
4489 id = idx[1] ;
4490 }
4491 uInt tcalid = s->getTcalId( id ) ;
4492 //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4493 tcalTable.getEntry( time, tcalval, tcalid ) ;
4494 tcalval.tovector( tcal ) ;
4495 }
4496 else if ( mode == "nearest" ) {
4497 int id = -1 ;
4498 if ( idx[0] == -1 ) {
4499 id = idx[1] ;
4500 }
4501 else if ( idx[1] == -1 ) {
4502 id = idx[0] ;
4503 }
4504 else if ( idx[0] == idx[1] ) {
4505 id = idx[0] ;
4506 }
4507 else {
[1967]4508 //double t0 = getMJD( s->getTime( idx[0] ) ) ;
4509 //double t1 = getMJD( s->getTime( idx[1] ) ) ;
4510 double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
4511 double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
[1819]4512 double tref = getMJD( reftime ) ;
4513 if ( abs( t0 - tref ) > abs( t1 - tref ) ) {
4514 id = idx[1] ;
4515 }
4516 else {
4517 id = idx[0] ;
4518 }
4519 }
4520 uInt tcalid = s->getTcalId( id ) ;
4521 //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4522 tcalTable.getEntry( time, tcalval, tcalid ) ;
4523 tcalval.tovector( tcal ) ;
4524 }
4525 else if ( mode == "linear" ) {
4526 if ( idx[0] == -1 ) {
4527 // use after
4528 os << LogIO::WARN << "Failed to interpolate. return a spectrum just after the reftime." << LogIO::POST ;
4529 int id = idx[1] ;
4530 uInt tcalid = s->getTcalId( id ) ;
4531 //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4532 tcalTable.getEntry( time, tcalval, tcalid ) ;
4533 tcalval.tovector( tcal ) ;
4534 }
4535 else if ( idx[1] == -1 ) {
4536 // use before
4537 os << LogIO::WARN << "Failed to interpolate. return a spectrum just before the reftime." << LogIO::POST ;
4538 int id = idx[0] ;
4539 uInt tcalid = s->getTcalId( id ) ;
4540 //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4541 tcalTable.getEntry( time, tcalval, tcalid ) ;
4542 tcalval.tovector( tcal ) ;
4543 }
4544 else if ( idx[0] == idx[1] ) {
4545 // use before
4546 //os << "No need to interporate." << LogIO::POST ;
4547 int id = idx[0] ;
4548 uInt tcalid = s->getTcalId( id ) ;
4549 //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4550 tcalTable.getEntry( time, tcalval, tcalid ) ;
4551 tcalval.tovector( tcal ) ;
4552 }
4553 else {
4554 // do interpolation
4555 //os << "interpolate between " << idx[0] << " and " << idx[1] << " (scanno: " << s->getScan( idx[0] ) << ", " << s->getScan( idx[1] ) << ")" << LogIO::POST ;
[1967]4556 //double t0 = getMJD( s->getTime( idx[0] ) ) ;
4557 //double t1 = getMJD( s->getTime( idx[1] ) ) ;
4558 double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
4559 double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
[1819]4560 double tref = getMJD( reftime ) ;
4561 vector<float> tcal0 ;
4562 vector<float> tcal1 ;
4563 uInt tcalid0 = s->getTcalId( idx[0] ) ;
4564 uInt tcalid1 = s->getTcalId( idx[1] ) ;
4565 tcalTable.getEntry( time, tcalval, tcalid0 ) ;
4566 tcalval.tovector( tcal0 ) ;
4567 tcalTable.getEntry( time, tcalval, tcalid1 ) ;
4568 tcalval.tovector( tcal1 ) ;
4569 for ( unsigned int i = 0 ; i < tcal0.size() ; i++ ) {
4570 float v = ( tcal1[i] - tcal0[i] ) / ( t1 - t0 ) * ( tref - t0 ) + tcal0[i] ;
4571 tcal.push_back( v ) ;
4572 }
4573 }
4574 }
4575 else {
4576 os << LogIO::SEVERE << "Unknown mode" << LogIO::POST ;
4577 }
4578 return tcal ;
4579 }
4580}
4581
4582vector<float> STMath::getTsysFromTime( string reftime,
4583 CountedPtr<Scantable>& s,
4584 string mode )
4585{
4586 LogIO os( LogOrigin( "STMath", "getTsysFromTime", WHERE ) ) ;
4587 ArrayColumn<Float> tsysCol ;
4588 tsysCol.attach( s->table(), "TSYS" ) ;
4589 vector<float> tsys ;
4590 String time ;
4591 Vector<Float> tsysval ;
4592 if ( s->nrow() == 0 ) {
4593 os << LogIO::SEVERE << "No row in the input scantable. Return empty tsys." << LogIO::POST ;
4594 return tsys ;
4595 }
4596 else if ( s->nrow() == 1 ) {
4597 //os << "use row " << 0 << LogIO::POST ;
4598 tsysval = tsysCol( 0 ) ;
4599 tsysval.tovector( tsys ) ;
4600 return tsys ;
4601 }
4602 else {
4603 vector<int> idx = getRowIdFromTime( reftime, s ) ;
4604 if ( mode == "before" ) {
4605 int id = -1 ;
4606 if ( idx[0] != -1 ) {
4607 id = idx[0] ;
4608 }
4609 else if ( idx[1] != -1 ) {
4610 os << LogIO::WARN << "Failed to find a scan before reftime. return a spectrum just after the reftime." << LogIO::POST ;
4611 id = idx[1] ;
4612 }
4613 //os << "use row " << id << LogIO::POST ;
4614 tsysval = tsysCol( id ) ;
4615 tsysval.tovector( tsys ) ;
4616 }
4617 else if ( mode == "after" ) {
4618 int id = -1 ;
4619 if ( idx[1] != -1 ) {
4620 id = idx[1] ;
4621 }
4622 else if ( idx[0] != -1 ) {
4623 os << LogIO::WARN << "Failed to find a scan after reftime. return a spectrum just before the reftime." << LogIO::POST ;
4624 id = idx[1] ;
4625 }
4626 //os << "use row " << id << LogIO::POST ;
4627 tsysval = tsysCol( id ) ;
4628 tsysval.tovector( tsys ) ;
4629 }
4630 else if ( mode == "nearest" ) {
4631 int id = -1 ;
4632 if ( idx[0] == -1 ) {
4633 id = idx[1] ;
4634 }
4635 else if ( idx[1] == -1 ) {
4636 id = idx[0] ;
4637 }
4638 else if ( idx[0] == idx[1] ) {
4639 id = idx[0] ;
4640 }
4641 else {
[1967]4642 //double t0 = getMJD( s->getTime( idx[0] ) ) ;
4643 //double t1 = getMJD( s->getTime( idx[1] ) ) ;
4644 double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
4645 double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
[1819]4646 double tref = getMJD( reftime ) ;
4647 if ( abs( t0 - tref ) > abs( t1 - tref ) ) {
4648 id = idx[1] ;
4649 }
4650 else {
4651 id = idx[0] ;
4652 }
4653 }
4654 //os << "use row " << id << LogIO::POST ;
4655 tsysval = tsysCol( id ) ;
4656 tsysval.tovector( tsys ) ;
4657 }
4658 else if ( mode == "linear" ) {
4659 if ( idx[0] == -1 ) {
4660 // use after
4661 os << LogIO::WARN << "Failed to interpolate. return a spectrum just after the reftime." << LogIO::POST ;
4662 int id = idx[1] ;
4663 //os << "use row " << id << LogIO::POST ;
4664 tsysval = tsysCol( id ) ;
4665 tsysval.tovector( tsys ) ;
4666 }
4667 else if ( idx[1] == -1 ) {
4668 // use before
4669 os << LogIO::WARN << "Failed to interpolate. return a spectrum just before the reftime." << LogIO::POST ;
4670 int id = idx[0] ;
4671 //os << "use row " << id << LogIO::POST ;
4672 tsysval = tsysCol( id ) ;
4673 tsysval.tovector( tsys ) ;
4674 }
4675 else if ( idx[0] == idx[1] ) {
4676 // use before
4677 //os << "No need to interporate." << LogIO::POST ;
4678 int id = idx[0] ;
4679 //os << "use row " << id << LogIO::POST ;
4680 tsysval = tsysCol( id ) ;
4681 tsysval.tovector( tsys ) ;
4682 }
4683 else {
4684 // do interpolation
4685 //os << "interpolate between " << idx[0] << " and " << idx[1] << " (scanno: " << s->getScan( idx[0] ) << ", " << s->getScan( idx[1] ) << ")" << LogIO::POST ;
[1967]4686 //double t0 = getMJD( s->getTime( idx[0] ) ) ;
4687 //double t1 = getMJD( s->getTime( idx[1] ) ) ;
4688 double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
4689 double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
[1819]4690 double tref = getMJD( reftime ) ;
4691 vector<float> tsys0 ;
4692 vector<float> tsys1 ;
4693 tsysval = tsysCol( idx[0] ) ;
4694 tsysval.tovector( tsys0 ) ;
4695 tsysval = tsysCol( idx[1] ) ;
4696 tsysval.tovector( tsys1 ) ;
4697 for ( unsigned int i = 0 ; i < tsys0.size() ; i++ ) {
4698 float v = ( tsys1[i] - tsys0[i] ) / ( t1 - t0 ) * ( tref - t0 ) + tsys0[i] ;
4699 tsys.push_back( v ) ;
4700 }
4701 }
4702 }
4703 else {
4704 os << LogIO::SEVERE << "Unknown mode" << LogIO::POST ;
4705 }
4706 return tsys ;
4707 }
4708}
4709
4710vector<float> STMath::getCalibratedSpectra( CountedPtr<Scantable>& on,
4711 CountedPtr<Scantable>& off,
4712 CountedPtr<Scantable>& sky,
4713 CountedPtr<Scantable>& hot,
4714 CountedPtr<Scantable>& cold,
4715 int index,
4716 string antname )
4717{
[2163]4718 (void) cold; //currently unused
[1819]4719 string reftime = on->getTime( index ) ;
4720 vector<int> ii( 1, on->getIF( index ) ) ;
4721 vector<int> ib( 1, on->getBeam( index ) ) ;
4722 vector<int> ip( 1, on->getPol( index ) ) ;
4723 vector<int> ic( 1, on->getScan( index ) ) ;
4724 STSelector sel = STSelector() ;
4725 sel.setIFs( ii ) ;
4726 sel.setBeams( ib ) ;
4727 sel.setPolarizations( ip ) ;
4728 sky->setSelection( sel ) ;
4729 hot->setSelection( sel ) ;
4730 //cold->setSelection( sel ) ;
4731 off->setSelection( sel ) ;
4732 vector<float> spsky = getSpectrumFromTime( reftime, sky, "linear" ) ;
4733 vector<float> sphot = getSpectrumFromTime( reftime, hot, "linear" ) ;
4734 //vector<float> spcold = getSpectrumFromTime( reftime, cold, "linear" ) ;
4735 vector<float> spoff = getSpectrumFromTime( reftime, off, "linear" ) ;
4736 vector<float> spec = on->getSpectrum( index ) ;
4737 vector<float> tcal = getTcalFromTime( reftime, sky, "linear" ) ;
4738 vector<float> sp( tcal.size() ) ;
4739 if ( antname.find( "APEX" ) != string::npos ) {
4740 // using gain array
4741 for ( unsigned int j = 0 ; j < tcal.size() ; j++ ) {
4742 float v = ( ( spec[j] - spoff[j] ) / spoff[j] )
4743 * ( spsky[j] / ( sphot[j] - spsky[j] ) ) * tcal[j] ;
4744 sp[j] = v ;
4745 }
4746 }
4747 else {
4748 // Chopper-Wheel calibration (Ulich & Haas 1976)
4749 for ( unsigned int j = 0 ; j < tcal.size() ; j++ ) {
4750 float v = ( spec[j] - spoff[j] ) / ( sphot[j] - spsky[j] ) * tcal[j] ;
4751 sp[j] = v ;
4752 }
4753 }
4754 sel.reset() ;
4755 sky->unsetSelection() ;
4756 hot->unsetSelection() ;
4757 //cold->unsetSelection() ;
4758 off->unsetSelection() ;
4759
4760 return sp ;
4761}
4762
4763vector<float> STMath::getCalibratedSpectra( CountedPtr<Scantable>& on,
4764 CountedPtr<Scantable>& off,
4765 int index )
4766{
4767 string reftime = on->getTime( index ) ;
4768 vector<int> ii( 1, on->getIF( index ) ) ;
4769 vector<int> ib( 1, on->getBeam( index ) ) ;
4770 vector<int> ip( 1, on->getPol( index ) ) ;
4771 vector<int> ic( 1, on->getScan( index ) ) ;
4772 STSelector sel = STSelector() ;
4773 sel.setIFs( ii ) ;
4774 sel.setBeams( ib ) ;
4775 sel.setPolarizations( ip ) ;
4776 off->setSelection( sel ) ;
4777 vector<float> spoff = getSpectrumFromTime( reftime, off, "linear" ) ;
4778 vector<float> spec = on->getSpectrum( index ) ;
4779 //vector<float> tcal = getTcalFromTime( reftime, sky, "linear" ) ;
4780 //vector<float> tsys = on->getTsysVec( index ) ;
4781 ArrayColumn<Float> tsysCol( on->table(), "TSYS" ) ;
4782 Vector<Float> tsys = tsysCol( index ) ;
4783 vector<float> sp( spec.size() ) ;
4784 // ALMA Calibration
4785 //
4786 // Ta* = Tsys * ( ON - OFF ) / OFF
4787 //
4788 // 2010/01/07 Takeshi Nakazato
4789 unsigned int tsyssize = tsys.nelements() ;
4790 unsigned int spsize = sp.size() ;
4791 for ( unsigned int j = 0 ; j < sp.size() ; j++ ) {
4792 float tscale = 0.0 ;
4793 if ( tsyssize == spsize )
4794 tscale = tsys[j] ;
4795 else
4796 tscale = tsys[0] ;
4797 float v = tscale * ( spec[j] - spoff[j] ) / spoff[j] ;
4798 sp[j] = v ;
4799 }
4800 sel.reset() ;
4801 off->unsetSelection() ;
4802
4803 return sp ;
4804}
4805
4806vector<float> STMath::getFSCalibratedSpectra( CountedPtr<Scantable>& sig,
4807 CountedPtr<Scantable>& ref,
4808 CountedPtr<Scantable>& sky,
4809 CountedPtr<Scantable>& hot,
4810 CountedPtr<Scantable>& cold,
4811 int index )
4812{
[2163]4813 (void) cold; //currently unused
[1819]4814 string reftime = sig->getTime( index ) ;
4815 vector<int> ii( 1, sig->getIF( index ) ) ;
4816 vector<int> ib( 1, sig->getBeam( index ) ) ;
4817 vector<int> ip( 1, sig->getPol( index ) ) ;
4818 vector<int> ic( 1, sig->getScan( index ) ) ;
4819 STSelector sel = STSelector() ;
4820 sel.setIFs( ii ) ;
4821 sel.setBeams( ib ) ;
4822 sel.setPolarizations( ip ) ;
4823 sky->setSelection( sel ) ;
4824 hot->setSelection( sel ) ;
4825 //cold->setSelection( sel ) ;
4826 vector<float> spsky = getSpectrumFromTime( reftime, sky, "linear" ) ;
4827 vector<float> sphot = getSpectrumFromTime( reftime, hot, "linear" ) ;
4828 //vector<float> spcold = getSpectrumFromTime( reftime, cold, "linear" ) ;
4829 vector<float> spref = ref->getSpectrum( index ) ;
4830 vector<float> spsig = sig->getSpectrum( index ) ;
4831 vector<float> tcal = getTcalFromTime( reftime, sky, "linear" ) ;
4832 vector<float> sp( tcal.size() ) ;
4833 for ( unsigned int j = 0 ; j < tcal.size() ; j++ ) {
4834 float v = tcal[j] * spsky[j] / ( sphot[j] - spsky[j] ) * ( spsig[j] - spref[j] ) / spref[j] ;
4835 sp[j] = v ;
4836 }
4837 sel.reset() ;
4838 sky->unsetSelection() ;
4839 hot->unsetSelection() ;
4840 //cold->unsetSelection() ;
4841
4842 return sp ;
4843}
4844
4845vector<float> STMath::getFSCalibratedSpectra( CountedPtr<Scantable>& sig,
4846 CountedPtr<Scantable>& ref,
4847 vector< CountedPtr<Scantable> >& sky,
4848 vector< CountedPtr<Scantable> >& hot,
4849 vector< CountedPtr<Scantable> >& cold,
4850 int index )
4851{
[2163]4852 (void) cold; //currently unused
[1819]4853 string reftime = sig->getTime( index ) ;
4854 vector<int> ii( 1, sig->getIF( index ) ) ;
4855 vector<int> ib( 1, sig->getBeam( index ) ) ;
4856 vector<int> ip( 1, sig->getPol( index ) ) ;
4857 vector<int> ic( 1, sig->getScan( index ) ) ;
4858 STSelector sel = STSelector() ;
4859 sel.setIFs( ii ) ;
4860 sel.setBeams( ib ) ;
4861 sel.setPolarizations( ip ) ;
4862 sky[0]->setSelection( sel ) ;
4863 hot[0]->setSelection( sel ) ;
4864 //cold[0]->setSelection( sel ) ;
4865 vector<float> spskys = getSpectrumFromTime( reftime, sky[0], "linear" ) ;
4866 vector<float> sphots = getSpectrumFromTime( reftime, hot[0], "linear" ) ;
4867 //vector<float> spcolds = getSpectrumFromTime( reftime, cold[0], "linear" ) ;
4868 vector<float> tcals = getTcalFromTime( reftime, sky[0], "linear" ) ;
4869 sel.reset() ;
4870 ii[0] = ref->getIF( index ) ;
4871 sel.setIFs( ii ) ;
4872 sel.setBeams( ib ) ;
4873 sel.setPolarizations( ip ) ;
4874 sky[1]->setSelection( sel ) ;
4875 hot[1]->setSelection( sel ) ;
4876 //cold[1]->setSelection( sel ) ;
4877 vector<float> spskyr = getSpectrumFromTime( reftime, sky[1], "linear" ) ;
4878 vector<float> sphotr = getSpectrumFromTime( reftime, hot[1], "linear" ) ;
4879 //vector<float> spcoldr = getSpectrumFromTime( reftime, cold[1], "linear" ) ;
4880 vector<float> tcalr = getTcalFromTime( reftime, sky[1], "linear" ) ;
4881 vector<float> spref = ref->getSpectrum( index ) ;
4882 vector<float> spsig = sig->getSpectrum( index ) ;
4883 vector<float> sp( tcals.size() ) ;
4884 for ( unsigned int j = 0 ; j < tcals.size() ; j++ ) {
4885 float v = tcals[j] * spsig[j] / ( sphots[j] - spskys[j] ) - tcalr[j] * spref[j] / ( sphotr[j] - spskyr[j] ) ;
4886 sp[j] = v ;
4887 }
4888 sel.reset() ;
4889 sky[0]->unsetSelection() ;
4890 hot[0]->unsetSelection() ;
4891 //cold[0]->unsetSelection() ;
4892 sky[1]->unsetSelection() ;
4893 hot[1]->unsetSelection() ;
4894 //cold[1]->unsetSelection() ;
4895
4896 return sp ;
4897}
Note: See TracBrowser for help on using the repository browser.