source: branches/casa-prerelease/pre-asap/src/STMath.cpp@ 2133

Last change on this file since 2133 was 2126, checked in by WataruKawasaki, 14 years ago

merged bug fixes from trunk (r2124)

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