source: trunk/src/STMath.cpp@ 2454

Last change on this file since 2454 was 2437, checked in by Kana Sugimoto, 13 years ago

New Development: No

JIRA Issue: Yes

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs: unit test of sdsmooth

Put in Release Notes: No

Module(s):

Description:

Changed the equation to calculate regridded spectral coordinate in
scantable.regrid_channel() so that it would have the same values as
the result of scantable.bin().
scantable.bin() now rebins Tsys arrays if necessary.


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