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

Last change on this file since 2156 was 2145, checked in by Takeshi Nakazato, 14 years ago

merge bug fix in trunk (r2143,r2144).

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