source: branches/hpc33/src/STMath.cpp@ 2544

Last change on this file since 2544 was 2544, checked in by Takeshi Nakazato, 13 years ago

New Development: No

JIRA Issue: No

Ready for Test: Yes

Interface Changes: No

What Interface Changed: Please list interface changes

Test Programs: List test programs

Put in Release Notes: Yes/No

Module(s): Module Names change impacts.

Description: Describe your changes here...

Updated STMath::almacal to use STMath::copyRows instead of TableCopy::copyRows


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