source: trunk/src/STMath.cpp@ 2184

Last change on this file since 2184 was 2177, checked in by WataruKawasaki, 14 years ago

New Development: Yes

JIRA Issue: Yes CAS-2828

Ready for Test: Yes

Interface Changes:

What Interface Changed:

Test Programs:

Put in Release Notes:

Module(s): SD

Description: created a tool function sd.scantable.fft() to apply FFT for scantable data.


  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 169.1 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 "MathUtils.h"
52#include "RowAccumulator.h"
53#include "STAttr.h"
54#include "STMath.h"
55#include "STSelector.h"
56
57using namespace casa;
58using namespace asap;
59
60// tolerance for direction comparison (rad)
61#define TOL_OTF 1.0e-15
62#define TOL_POINT 2.9088821e-4 // 1 arcmin
63
64STMath::STMath(bool insitu) :
65 insitu_(insitu)
66{
67}
68
69
70STMath::~STMath()
71{
72}
73
74CountedPtr<Scantable>
75STMath::average( const std::vector<CountedPtr<Scantable> >& in,
76 const std::vector<bool>& mask,
77 const std::string& weight,
78 const std::string& avmode)
79{
80 LogIO os( LogOrigin( "STMath", "average()", WHERE ) ) ;
81 if ( avmode == "SCAN" && in.size() != 1 )
82 throw(AipsError("Can't perform 'SCAN' averaging on multiple tables.\n"
83 "Use merge first."));
84 WeightType wtype = stringToWeight(weight);
85
86 // check if OTF observation
87 String obstype = in[0]->getHeader().obstype ;
88 Double tol = 0.0 ;
89 if ( (obstype.find( "OTF" ) != String::npos) || (obstype.find( "OBSERVE_TARGET" ) != String::npos) ) {
90 tol = TOL_OTF ;
91 }
92 else {
93 tol = TOL_POINT ;
94 }
95
96 // output
97 // clone as this is non insitu
98 bool insitu = insitu_;
99 setInsitu(false);
100 CountedPtr< Scantable > out = getScantable(in[0], true);
101 setInsitu(insitu);
102 std::vector<CountedPtr<Scantable> >::const_iterator stit = in.begin();
103 ++stit;
104 while ( stit != in.end() ) {
105 out->appendToHistoryTable((*stit)->history());
106 ++stit;
107 }
108
109 Table& tout = out->table();
110
111 /// @todo check if all scantables are conformant
112
113 ArrayColumn<Float> specColOut(tout,"SPECTRA");
114 ArrayColumn<uChar> flagColOut(tout,"FLAGTRA");
115 ArrayColumn<Float> tsysColOut(tout,"TSYS");
116 ScalarColumn<Double> mjdColOut(tout,"TIME");
117 ScalarColumn<Double> intColOut(tout,"INTERVAL");
118 ScalarColumn<uInt> cycColOut(tout,"CYCLENO");
119 ScalarColumn<uInt> scanColOut(tout,"SCANNO");
120
121 // set up the output table rows. These are based on the structure of the
122 // FIRST scantable in the vector
123 const Table& baset = in[0]->table();
124
125 Block<String> cols(3);
126 cols[0] = String("BEAMNO");
127 cols[1] = String("IFNO");
128 cols[2] = String("POLNO");
129 if ( avmode == "SOURCE" ) {
130 cols.resize(4);
131 cols[3] = String("SRCNAME");
132 }
133 if ( avmode == "SCAN" && in.size() == 1) {
134 //cols.resize(4);
135 //cols[3] = String("SCANNO");
136 cols.resize(5);
137 cols[3] = String("SRCNAME");
138 cols[4] = String("SCANNO");
139 }
140 uInt outrowCount = 0;
141 TableIterator iter(baset, cols);
142// int count = 0 ;
143 while (!iter.pastEnd()) {
144 Table subt = iter.table();
145// // copy the first row of this selection into the new table
146// tout.addRow();
147// TableCopy::copyRows(tout, subt, outrowCount, 0, 1);
148// // re-index to 0
149// if ( avmode != "SCAN" && avmode != "SOURCE" ) {
150// scanColOut.put(outrowCount, uInt(0));
151// }
152// ++outrowCount;
153 MDirection::ScalarColumn dircol ;
154 dircol.attach( subt, "DIRECTION" ) ;
155 Int length = subt.nrow() ;
156 vector< Vector<Double> > dirs ;
157 vector<int> indexes ;
158 for ( Int i = 0 ; i < length ; i++ ) {
159 Vector<Double> t = dircol(i).getAngle(Unit(String("rad"))).getValue() ;
160 //os << << count++ << ": " ;
161 //os << "[" << t[0] << "," << t[1] << "]" << LogIO::POST ;
162 bool adddir = true ;
163 for ( uInt j = 0 ; j < dirs.size() ; j++ ) {
164 //if ( allTrue( t == dirs[j] ) ) {
165 Double dx = t[0] - dirs[j][0] ;
166 Double dy = t[1] - dirs[j][1] ;
167 Double dd = sqrt( dx * dx + dy * dy ) ;
168 //if ( allNearAbs( t, dirs[j], tol ) ) {
169 if ( dd <= tol ) {
170 adddir = false ;
171 break ;
172 }
173 }
174 if ( adddir ) {
175 dirs.push_back( t ) ;
176 indexes.push_back( i ) ;
177 }
178 }
179 uInt rowNum = dirs.size() ;
180 tout.addRow( rowNum ) ;
181 for ( uInt i = 0 ; i < rowNum ; i++ ) {
182 TableCopy::copyRows( tout, subt, outrowCount+i, indexes[i], 1 ) ;
183 // re-index to 0
184 if ( avmode != "SCAN" && avmode != "SOURCE" ) {
185 scanColOut.put(outrowCount+i, uInt(0));
186 }
187 }
188 outrowCount += rowNum ;
189 ++iter;
190 }
191 RowAccumulator acc(wtype);
192 Vector<Bool> cmask(mask);
193 acc.setUserMask(cmask);
194 ROTableRow row(tout);
195 ROArrayColumn<Float> specCol, tsysCol;
196 ROArrayColumn<uChar> flagCol;
197 ROScalarColumn<Double> mjdCol, intCol;
198 ROScalarColumn<Int> scanIDCol;
199
200 Vector<uInt> rowstodelete;
201
202 for (uInt i=0; i < tout.nrow(); ++i) {
203 for ( int j=0; j < int(in.size()); ++j ) {
204 const Table& tin = in[j]->table();
205 const TableRecord& rec = row.get(i);
206 ROScalarColumn<Double> tmp(tin, "TIME");
207 Double td;tmp.get(0,td);
208 Table basesubt = tin( tin.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
209 && tin.col("IFNO") == Int(rec.asuInt("IFNO"))
210 && tin.col("POLNO") == Int(rec.asuInt("POLNO")) );
211 Table subt;
212 if ( avmode == "SOURCE") {
213 subt = basesubt( basesubt.col("SRCNAME") == rec.asString("SRCNAME"));
214 } else if (avmode == "SCAN") {
215 subt = basesubt( basesubt.col("SRCNAME") == rec.asString("SRCNAME")
216 && basesubt.col("SCANNO") == Int(rec.asuInt("SCANNO")) );
217 } else {
218 subt = basesubt;
219 }
220
221 vector<uInt> removeRows ;
222 uInt nrsubt = subt.nrow() ;
223 for ( uInt irow = 0 ; irow < nrsubt ; irow++ ) {
224 //if ( !allTrue((subt.col("DIRECTION").getArrayDouble(TableExprId(irow)))==rec.asArrayDouble("DIRECTION")) ) {
225 Vector<Double> x0 = (subt.col("DIRECTION").getArrayDouble(TableExprId(irow))) ;
226 Vector<Double> x1 = rec.asArrayDouble("DIRECTION") ;
227 double dx = x0[0] - x1[0] ;
228 double dy = x0[0] - x1[0] ;
229 Double dd = sqrt( dx * dx + dy * dy ) ;
230 //if ( !allNearAbs((subt.col("DIRECTION").getArrayDouble(TableExprId(irow))), rec.asArrayDouble("DIRECTION"), tol ) ) {
231 if ( dd > tol ) {
232 removeRows.push_back( irow ) ;
233 }
234 }
235 if ( removeRows.size() != 0 ) {
236 subt.removeRow( removeRows ) ;
237 }
238
239 if ( nrsubt == removeRows.size() )
240 throw(AipsError("Averaging data is empty.")) ;
241
242 specCol.attach(subt,"SPECTRA");
243 flagCol.attach(subt,"FLAGTRA");
244 tsysCol.attach(subt,"TSYS");
245 intCol.attach(subt,"INTERVAL");
246 mjdCol.attach(subt,"TIME");
247 Vector<Float> spec,tsys;
248 Vector<uChar> flag;
249 Double inter,time;
250 for (uInt k = 0; k < subt.nrow(); ++k ) {
251 flagCol.get(k, flag);
252 Vector<Bool> bflag(flag.shape());
253 convertArray(bflag, flag);
254 /*
255 if ( allEQ(bflag, True) ) {
256 continue;//don't accumulate
257 }
258 */
259 specCol.get(k, spec);
260 tsysCol.get(k, tsys);
261 intCol.get(k, inter);
262 mjdCol.get(k, time);
263 // spectrum has to be added last to enable weighting by the other values
264 acc.add(spec, !bflag, tsys, inter, time);
265 }
266
267 // If there exists a channel at which all the input spectra are masked,
268 // spec has 'nan' values for that channel and it may affect the following
269 // processes. To avoid this, replacing 'nan' values in spec with
270 // weighted-mean of all spectra in the following line.
271 // (done for CAS-2776, 2011/04/07 by Wataru Kawasaki)
272 acc.replaceNaN();
273 }
274 const Vector<Bool>& msk = acc.getMask();
275 if ( allEQ(msk, False) ) {
276 uint n = rowstodelete.nelements();
277 rowstodelete.resize(n+1, True);
278 rowstodelete[n] = i;
279 continue;
280 }
281 //write out
282 if (acc.state()) {
283 Vector<uChar> flg(msk.shape());
284 convertArray(flg, !msk);
285 for (uInt k = 0; k < flg.nelements(); ++k) {
286 uChar userFlag = 1 << 7;
287 if (msk[k]==True) userFlag = 0 << 7;
288 flg(k) = userFlag;
289 }
290
291 flagColOut.put(i, flg);
292 specColOut.put(i, acc.getSpectrum());
293 tsysColOut.put(i, acc.getTsys());
294 intColOut.put(i, acc.getInterval());
295 mjdColOut.put(i, acc.getTime());
296 // we should only have one cycle now -> reset it to be 0
297 // frequency switched data has different CYCLENO for different IFNO
298 // which requires resetting this value
299 cycColOut.put(i, uInt(0));
300 } else {
301 ostringstream oss;
302 oss << "For output row="<<i<<", all input rows of data are flagged. no averaging" << endl;
303 pushLog(String(oss));
304 }
305 acc.reset();
306 }
307
308 if (rowstodelete.nelements() > 0) {
309 os << rowstodelete << LogIO::POST ;
310 tout.removeRow(rowstodelete);
311 if (tout.nrow() == 0) {
312 throw(AipsError("Can't average fully flagged data."));
313 }
314 }
315 return out;
316}
317
318CountedPtr< Scantable >
319STMath::averageChannel( const CountedPtr < Scantable > & in,
320 const std::string & mode,
321 const std::string& avmode )
322{
323 (void) mode; // currently unused
324 // check if OTF observation
325 String obstype = in->getHeader().obstype ;
326 Double tol = 0.0 ;
327 if ( obstype.find( "OTF" ) != String::npos ) {
328 tol = TOL_OTF ;
329 }
330 else {
331 tol = TOL_POINT ;
332 }
333
334 // clone as this is non insitu
335 bool insitu = insitu_;
336 setInsitu(false);
337 CountedPtr< Scantable > out = getScantable(in, true);
338 setInsitu(insitu);
339 Table& tout = out->table();
340 ArrayColumn<Float> specColOut(tout,"SPECTRA");
341 ArrayColumn<uChar> flagColOut(tout,"FLAGTRA");
342 ArrayColumn<Float> tsysColOut(tout,"TSYS");
343 ScalarColumn<uInt> scanColOut(tout,"SCANNO");
344 ScalarColumn<Double> intColOut(tout, "INTERVAL");
345 Table tmp = in->table().sort("BEAMNO");
346 Block<String> cols(3);
347 cols[0] = String("BEAMNO");
348 cols[1] = String("IFNO");
349 cols[2] = String("POLNO");
350 if ( avmode == "SCAN") {
351 cols.resize(4);
352 cols[3] = String("SCANNO");
353 }
354 uInt outrowCount = 0;
355 uChar userflag = 1 << 7;
356 TableIterator iter(tmp, cols);
357 while (!iter.pastEnd()) {
358 Table subt = iter.table();
359 ROArrayColumn<Float> specCol, tsysCol;
360 ROArrayColumn<uChar> flagCol;
361 ROScalarColumn<Double> intCol(subt, "INTERVAL");
362 specCol.attach(subt,"SPECTRA");
363 flagCol.attach(subt,"FLAGTRA");
364 tsysCol.attach(subt,"TSYS");
365// tout.addRow();
366// TableCopy::copyRows(tout, subt, outrowCount, 0, 1);
367// if ( avmode != "SCAN") {
368// scanColOut.put(outrowCount, uInt(0));
369// }
370// Vector<Float> tmp;
371// specCol.get(0, tmp);
372// uInt nchan = tmp.nelements();
373// // have to do channel by channel here as MaskedArrMath
374// // doesn't have partialMedians
375// Vector<uChar> flags = flagCol.getColumn(Slicer(Slice(0)));
376// Vector<Float> outspec(nchan);
377// Vector<uChar> outflag(nchan,0);
378// Vector<Float> outtsys(1);/// @fixme when tsys is channel based
379// for (uInt i=0; i<nchan; ++i) {
380// Vector<Float> specs = specCol.getColumn(Slicer(Slice(i)));
381// MaskedArray<Float> ma = maskedArray(specs,flags);
382// outspec[i] = median(ma);
383// if ( allEQ(ma.getMask(), False) )
384// outflag[i] = userflag;// flag data
385// }
386// outtsys[0] = median(tsysCol.getColumn());
387// specColOut.put(outrowCount, outspec);
388// flagColOut.put(outrowCount, outflag);
389// tsysColOut.put(outrowCount, outtsys);
390// Double intsum = sum(intCol.getColumn());
391// intColOut.put(outrowCount, intsum);
392// ++outrowCount;
393// ++iter;
394 MDirection::ScalarColumn dircol ;
395 dircol.attach( subt, "DIRECTION" ) ;
396 Int length = subt.nrow() ;
397 vector< Vector<Double> > dirs ;
398 vector<int> indexes ;
399 for ( Int i = 0 ; i < length ; i++ ) {
400 Vector<Double> t = dircol(i).getAngle(Unit(String("rad"))).getValue() ;
401 bool adddir = true ;
402 for ( uInt j = 0 ; j < dirs.size() ; j++ ) {
403 //if ( allTrue( t == dirs[j] ) ) {
404 Double dx = t[0] - dirs[j][0] ;
405 Double dy = t[1] - dirs[j][1] ;
406 Double dd = sqrt( dx * dx + dy * dy ) ;
407 //if ( allNearAbs( t, dirs[j], tol ) ) {
408 if ( dd <= tol ) {
409 adddir = false ;
410 break ;
411 }
412 }
413 if ( adddir ) {
414 dirs.push_back( t ) ;
415 indexes.push_back( i ) ;
416 }
417 }
418 uInt rowNum = dirs.size() ;
419 tout.addRow( rowNum );
420 for ( uInt i = 0 ; i < rowNum ; i++ ) {
421 TableCopy::copyRows(tout, subt, outrowCount+i, indexes[i], 1) ;
422 if ( avmode != "SCAN") {
423 //scanColOut.put(outrowCount+i, uInt(0));
424 }
425 }
426 MDirection::ScalarColumn dircolOut ;
427 dircolOut.attach( tout, "DIRECTION" ) ;
428 for ( uInt irow = 0 ; irow < rowNum ; irow++ ) {
429 Vector<Double> t = dircolOut(outrowCount+irow).getAngle(Unit(String("rad"))).getValue() ;
430 Vector<Float> tmp;
431 specCol.get(0, tmp);
432 uInt nchan = tmp.nelements();
433 // have to do channel by channel here as MaskedArrMath
434 // doesn't have partialMedians
435 Vector<uChar> flags = flagCol.getColumn(Slicer(Slice(0)));
436 // mask spectra for different DIRECTION
437 for ( uInt jrow = 0 ; jrow < subt.nrow() ; jrow++ ) {
438 Vector<Double> direction = dircol(jrow).getAngle(Unit(String("rad"))).getValue() ;
439 //if ( t[0] != direction[0] || t[1] != direction[1] ) {
440 Double dx = t[0] - direction[0] ;
441 Double dy = t[1] - direction[1] ;
442 Double dd = sqrt( dx * dx + dy * dy ) ;
443 //if ( !allNearAbs( t, direction, tol ) ) {
444 if ( dd > tol ) {
445 flags[jrow] = userflag ;
446 }
447 }
448 Vector<Float> outspec(nchan);
449 Vector<uChar> outflag(nchan,0);
450 Vector<Float> outtsys(1);/// @fixme when tsys is channel based
451 for (uInt i=0; i<nchan; ++i) {
452 Vector<Float> specs = specCol.getColumn(Slicer(Slice(i)));
453 MaskedArray<Float> ma = maskedArray(specs,flags);
454 outspec[i] = median(ma);
455 if ( allEQ(ma.getMask(), False) )
456 outflag[i] = userflag;// flag data
457 }
458 outtsys[0] = median(tsysCol.getColumn());
459 specColOut.put(outrowCount+irow, outspec);
460 flagColOut.put(outrowCount+irow, outflag);
461 tsysColOut.put(outrowCount+irow, outtsys);
462 Vector<Double> integ = intCol.getColumn() ;
463 MaskedArray<Double> mi = maskedArray( integ, flags ) ;
464 Double intsum = sum(mi);
465 intColOut.put(outrowCount+irow, intsum);
466 }
467 outrowCount += rowNum ;
468 ++iter;
469 }
470 return out;
471}
472
473CountedPtr< Scantable > STMath::getScantable(const CountedPtr< Scantable >& in,
474 bool droprows)
475{
476 if (insitu_) {
477 return in;
478 }
479 else {
480 // clone
481 return CountedPtr<Scantable>(new Scantable(*in, Bool(droprows)));
482 }
483}
484
485CountedPtr< Scantable > STMath::unaryOperate( const CountedPtr< Scantable >& in,
486 float val,
487 const std::string& mode,
488 bool tsys )
489{
490 CountedPtr< Scantable > out = getScantable(in, false);
491 Table& tab = out->table();
492 ArrayColumn<Float> specCol(tab,"SPECTRA");
493 ArrayColumn<Float> tsysCol(tab,"TSYS");
494 if (mode=="DIV") val = 1.0/val ;
495 else if (mode=="SUB") val *= -1.0 ;
496 for (uInt i=0; i<tab.nrow(); ++i) {
497 Vector<Float> spec;
498 Vector<Float> ts;
499 specCol.get(i, spec);
500 tsysCol.get(i, ts);
501 if (mode == "MUL" || mode == "DIV") {
502 //if (mode == "DIV") val = 1.0/val;
503 spec *= val;
504 specCol.put(i, spec);
505 if ( tsys ) {
506 ts *= val;
507 tsysCol.put(i, ts);
508 }
509 } else if ( mode == "ADD" || mode == "SUB") {
510 //if (mode == "SUB") val *= -1.0;
511 spec += val;
512 specCol.put(i, spec);
513 if ( tsys ) {
514 ts += val;
515 tsysCol.put(i, ts);
516 }
517 }
518 }
519 return out;
520}
521
522CountedPtr< Scantable > STMath::arrayOperate( const CountedPtr< Scantable >& in,
523 const std::vector<float> val,
524 const std::string& mode,
525 const std::string& opmode,
526 bool tsys )
527{
528 CountedPtr< Scantable > out ;
529 if ( opmode == "channel" ) {
530 out = arrayOperateChannel( in, val, mode, tsys ) ;
531 }
532 else if ( opmode == "row" ) {
533 out = arrayOperateRow( in, val, mode, tsys ) ;
534 }
535 else {
536 throw( AipsError( "Unknown array operation mode." ) ) ;
537 }
538 return out ;
539}
540
541CountedPtr< Scantable > STMath::arrayOperateChannel( const CountedPtr< Scantable >& in,
542 const std::vector<float> val,
543 const std::string& mode,
544 bool tsys )
545{
546 if ( val.size() == 1 ){
547 return unaryOperate( in, val[0], mode, tsys ) ;
548 }
549
550 // conformity of SPECTRA and TSYS
551 if ( tsys ) {
552 TableIterator titer(in->table(), "IFNO");
553 while ( !titer.pastEnd() ) {
554 ArrayColumn<Float> specCol( in->table(), "SPECTRA" ) ;
555 ArrayColumn<Float> tsysCol( in->table(), "TSYS" ) ;
556 Array<Float> spec = specCol.getColumn() ;
557 Array<Float> ts = tsysCol.getColumn() ;
558 if ( !spec.conform( ts ) ) {
559 throw( AipsError( "SPECTRA and TSYS must conform in shape if you want to apply operation on Tsys." ) ) ;
560 }
561 titer.next() ;
562 }
563 }
564
565 // check if all spectra in the scantable have the same number of channel
566 vector<uInt> nchans;
567 vector<uInt> ifnos = in->getIFNos() ;
568 for ( uInt i = 0 ; i < ifnos.size() ; i++ ) {
569 nchans.push_back( in->nchan( ifnos[i] ) ) ;
570 }
571 Vector<uInt> mchans( nchans ) ;
572 if ( anyNE( mchans, mchans[0] ) ) {
573 throw( AipsError("All spectra in the input scantable must have the same number of channel for vector operation." ) ) ;
574 }
575
576 // check if vector size is equal to nchan
577 Vector<Float> fact( val ) ;
578 if ( fact.nelements() != mchans[0] ) {
579 throw( AipsError("Vector size must be 1 or be same as number of channel.") ) ;
580 }
581
582 // check divided by zero
583 if ( ( mode == "DIV" ) && anyEQ( fact, (float)0.0 ) ) {
584 throw( AipsError("Divided by zero is not recommended." ) ) ;
585 }
586
587 CountedPtr< Scantable > out = getScantable(in, false);
588 Table& tab = out->table();
589 ArrayColumn<Float> specCol(tab,"SPECTRA");
590 ArrayColumn<Float> tsysCol(tab,"TSYS");
591 if (mode == "DIV") fact = (float)1.0 / fact;
592 else if (mode == "SUB") fact *= (float)-1.0 ;
593 for (uInt i=0; i<tab.nrow(); ++i) {
594 Vector<Float> spec;
595 Vector<Float> ts;
596 specCol.get(i, spec);
597 tsysCol.get(i, ts);
598 if (mode == "MUL" || mode == "DIV") {
599 //if (mode == "DIV") fact = (float)1.0 / fact;
600 spec *= fact;
601 specCol.put(i, spec);
602 if ( tsys ) {
603 ts *= fact;
604 tsysCol.put(i, ts);
605 }
606 } else if ( mode == "ADD" || mode == "SUB") {
607 //if (mode == "SUB") fact *= (float)-1.0 ;
608 spec += fact;
609 specCol.put(i, spec);
610 if ( tsys ) {
611 ts += fact;
612 tsysCol.put(i, ts);
613 }
614 }
615 }
616 return out;
617}
618
619CountedPtr< Scantable > STMath::arrayOperateRow( const CountedPtr< Scantable >& in,
620 const std::vector<float> val,
621 const std::string& mode,
622 bool tsys )
623{
624 if ( val.size() == 1 ) {
625 return unaryOperate( in, val[0], mode, tsys ) ;
626 }
627
628 // conformity of SPECTRA and TSYS
629 if ( tsys ) {
630 TableIterator titer(in->table(), "IFNO");
631 while ( !titer.pastEnd() ) {
632 ArrayColumn<Float> specCol( in->table(), "SPECTRA" ) ;
633 ArrayColumn<Float> tsysCol( in->table(), "TSYS" ) ;
634 Array<Float> spec = specCol.getColumn() ;
635 Array<Float> ts = tsysCol.getColumn() ;
636 if ( !spec.conform( ts ) ) {
637 throw( AipsError( "SPECTRA and TSYS must conform in shape if you want to apply operation on Tsys." ) ) ;
638 }
639 titer.next() ;
640 }
641 }
642
643 // check if vector size is equal to nrow
644 Vector<Float> fact( val ) ;
645 if (fact.nelements() != uInt(in->nrow())) {
646 throw( AipsError("Vector size must be 1 or be same as number of row.") ) ;
647 }
648
649 // check divided by zero
650 if ( ( mode == "DIV" ) && anyEQ( fact, (float)0.0 ) ) {
651 throw( AipsError("Divided by zero is not recommended." ) ) ;
652 }
653
654 CountedPtr< Scantable > out = getScantable(in, false);
655 Table& tab = out->table();
656 ArrayColumn<Float> specCol(tab,"SPECTRA");
657 ArrayColumn<Float> tsysCol(tab,"TSYS");
658 if (mode == "DIV") fact = (float)1.0 / fact;
659 if (mode == "SUB") fact *= (float)-1.0 ;
660 for (uInt i=0; i<tab.nrow(); ++i) {
661 Vector<Float> spec;
662 Vector<Float> ts;
663 specCol.get(i, spec);
664 tsysCol.get(i, ts);
665 if (mode == "MUL" || mode == "DIV") {
666 spec *= fact[i];
667 specCol.put(i, spec);
668 if ( tsys ) {
669 ts *= fact[i];
670 tsysCol.put(i, ts);
671 }
672 } else if ( mode == "ADD" || mode == "SUB") {
673 spec += fact[i];
674 specCol.put(i, spec);
675 if ( tsys ) {
676 ts += fact[i];
677 tsysCol.put(i, ts);
678 }
679 }
680 }
681 return out;
682}
683
684CountedPtr< Scantable > STMath::array2dOperate( const CountedPtr< Scantable >& in,
685 const std::vector< std::vector<float> > val,
686 const std::string& mode,
687 bool tsys )
688{
689 // conformity of SPECTRA and TSYS
690 if ( tsys ) {
691 TableIterator titer(in->table(), "IFNO");
692 while ( !titer.pastEnd() ) {
693 ArrayColumn<Float> specCol( in->table(), "SPECTRA" ) ;
694 ArrayColumn<Float> tsysCol( in->table(), "TSYS" ) ;
695 Array<Float> spec = specCol.getColumn() ;
696 Array<Float> ts = tsysCol.getColumn() ;
697 if ( !spec.conform( ts ) ) {
698 throw( AipsError( "SPECTRA and TSYS must conform in shape if you want to apply operation on Tsys." ) ) ;
699 }
700 titer.next() ;
701 }
702 }
703
704 // some checks
705 vector<uInt> nchans;
706 for (Int i = 0 ; i < in->nrow() ; i++) {
707 nchans.push_back((in->getSpectrum(i)).size());
708 }
709 //Vector<uInt> mchans( nchans ) ;
710 vector< Vector<Float> > facts ;
711 for ( uInt i = 0 ; i < nchans.size() ; i++ ) {
712 Vector<Float> tmp( val[i] ) ;
713 // check divided by zero
714 if ( ( mode == "DIV" ) && anyEQ( tmp, (float)0.0 ) ) {
715 throw( AipsError("Divided by zero is not recommended." ) ) ;
716 }
717 // conformity check
718 if ( tmp.nelements() != nchans[i] ) {
719 stringstream ss ;
720 ss << "Row " << i << ": Vector size must be same as number of channel." ;
721 throw( AipsError( ss.str() ) ) ;
722 }
723 facts.push_back( tmp ) ;
724 }
725
726
727 CountedPtr< Scantable > out = getScantable(in, false);
728 Table& tab = out->table();
729 ArrayColumn<Float> specCol(tab,"SPECTRA");
730 ArrayColumn<Float> tsysCol(tab,"TSYS");
731 for (uInt i=0; i<tab.nrow(); ++i) {
732 Vector<Float> fact = facts[i] ;
733 Vector<Float> spec;
734 Vector<Float> ts;
735 specCol.get(i, spec);
736 tsysCol.get(i, ts);
737 if (mode == "MUL" || mode == "DIV") {
738 if (mode == "DIV") fact = (float)1.0 / fact;
739 spec *= fact;
740 specCol.put(i, spec);
741 if ( tsys ) {
742 ts *= fact;
743 tsysCol.put(i, ts);
744 }
745 } else if ( mode == "ADD" || mode == "SUB") {
746 if (mode == "SUB") fact *= (float)-1.0 ;
747 spec += fact;
748 specCol.put(i, spec);
749 if ( tsys ) {
750 ts += fact;
751 tsysCol.put(i, ts);
752 }
753 }
754 }
755 return out;
756}
757
758CountedPtr<Scantable> STMath::binaryOperate(const CountedPtr<Scantable>& left,
759 const CountedPtr<Scantable>& right,
760 const std::string& mode)
761{
762 bool insitu = insitu_;
763 if ( ! left->conformant(*right) ) {
764 throw(AipsError("'left' and 'right' scantables are not conformant."));
765 }
766 setInsitu(false);
767 CountedPtr< Scantable > out = getScantable(left, false);
768 setInsitu(insitu);
769 Table& tout = out->table();
770 Block<String> coln(5);
771 coln[0] = "SCANNO"; coln[1] = "CYCLENO"; coln[2] = "BEAMNO";
772 coln[3] = "IFNO"; coln[4] = "POLNO";
773 Table tmpl = tout.sort(coln);
774 Table tmpr = right->table().sort(coln);
775 ArrayColumn<Float> lspecCol(tmpl,"SPECTRA");
776 ROArrayColumn<Float> rspecCol(tmpr,"SPECTRA");
777 ArrayColumn<uChar> lflagCol(tmpl,"FLAGTRA");
778 ROArrayColumn<uChar> rflagCol(tmpr,"FLAGTRA");
779
780 for (uInt i=0; i<tout.nrow(); ++i) {
781 Vector<Float> lspecvec, rspecvec;
782 Vector<uChar> lflagvec, rflagvec;
783 lspecvec = lspecCol(i); rspecvec = rspecCol(i);
784 lflagvec = lflagCol(i); rflagvec = rflagCol(i);
785 MaskedArray<Float> mleft = maskedArray(lspecvec, lflagvec);
786 MaskedArray<Float> mright = maskedArray(rspecvec, rflagvec);
787 if (mode == "ADD") {
788 mleft += mright;
789 } else if ( mode == "SUB") {
790 mleft -= mright;
791 } else if ( mode == "MUL") {
792 mleft *= mright;
793 } else if ( mode == "DIV") {
794 mleft /= mright;
795 } else {
796 throw(AipsError("Illegal binary operator"));
797 }
798 lspecCol.put(i, mleft.getArray());
799 }
800 return out;
801}
802
803
804
805MaskedArray<Float> STMath::maskedArray( const Vector<Float>& s,
806 const Vector<uChar>& f)
807{
808 Vector<Bool> mask;
809 mask.resize(f.shape());
810 convertArray(mask, f);
811 return MaskedArray<Float>(s,!mask);
812}
813
814MaskedArray<Double> STMath::maskedArray( const Vector<Double>& s,
815 const Vector<uChar>& f)
816{
817 Vector<Bool> mask;
818 mask.resize(f.shape());
819 convertArray(mask, f);
820 return MaskedArray<Double>(s,!mask);
821}
822
823Vector<uChar> STMath::flagsFromMA(const MaskedArray<Float>& ma)
824{
825 const Vector<Bool>& m = ma.getMask();
826 Vector<uChar> flags(m.shape());
827 convertArray(flags, !m);
828 return flags;
829}
830
831CountedPtr< Scantable > STMath::autoQuotient( const CountedPtr< Scantable >& in,
832 const std::string & mode,
833 bool preserve )
834{
835 /// @todo make other modes available
836 /// modes should be "nearest", "pair"
837 // make this operation non insitu
838 (void) mode; //currently unused
839 const Table& tin = in->table();
840 Table ons = tin(tin.col("SRCTYPE") == Int(SrcType::PSON));
841 Table offs = tin(tin.col("SRCTYPE") == Int(SrcType::PSOFF));
842 if ( offs.nrow() == 0 )
843 throw(AipsError("No 'off' scans present."));
844 // put all "on" scans into output table
845
846 bool insitu = insitu_;
847 setInsitu(false);
848 CountedPtr< Scantable > out = getScantable(in, true);
849 setInsitu(insitu);
850 Table& tout = out->table();
851
852 TableCopy::copyRows(tout, ons);
853 TableRow row(tout);
854 ROScalarColumn<Double> offtimeCol(offs, "TIME");
855 ArrayColumn<Float> outspecCol(tout, "SPECTRA");
856 ROArrayColumn<Float> outtsysCol(tout, "TSYS");
857 ArrayColumn<uChar> outflagCol(tout, "FLAGTRA");
858 for (uInt i=0; i < tout.nrow(); ++i) {
859 const TableRecord& rec = row.get(i);
860 Double ontime = rec.asDouble("TIME");
861 Table presel = offs(offs.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
862 && offs.col("IFNO") == Int(rec.asuInt("IFNO"))
863 && offs.col("POLNO") == Int(rec.asuInt("POLNO")) );
864 ROScalarColumn<Double> offtimeCol(presel, "TIME");
865
866 Double mindeltat = min(abs(offtimeCol.getColumn() - ontime));
867 // Timestamp may vary within a cycle ???!!!
868 // increase this by 0.01 sec in case of rounding errors...
869 // There might be a better way to do this.
870 // fix to this fix. TIME is MJD, so 1.0d not 1.0s
871 mindeltat += 0.01/24./60./60.;
872 Table sel = presel( abs(presel.col("TIME")-ontime) <= mindeltat);
873
874 if ( sel.nrow() < 1 ) {
875 throw(AipsError("No closest in time found... This could be a rounding "
876 "issue. Try quotient instead."));
877 }
878 TableRow offrow(sel);
879 const TableRecord& offrec = offrow.get(0);//should only be one row
880 RORecordFieldPtr< Array<Float> > specoff(offrec, "SPECTRA");
881 RORecordFieldPtr< Array<Float> > tsysoff(offrec, "TSYS");
882 RORecordFieldPtr< Array<uChar> > flagoff(offrec, "FLAGTRA");
883 /// @fixme this assumes tsys is a scalar not vector
884 Float tsysoffscalar = (*tsysoff)(IPosition(1,0));
885 Vector<Float> specon, tsyson;
886 outtsysCol.get(i, tsyson);
887 outspecCol.get(i, specon);
888 Vector<uChar> flagon;
889 outflagCol.get(i, flagon);
890 MaskedArray<Float> mon = maskedArray(specon, flagon);
891 MaskedArray<Float> moff = maskedArray(*specoff, *flagoff);
892 MaskedArray<Float> quot = (tsysoffscalar * mon / moff);
893 if (preserve) {
894 quot -= tsysoffscalar;
895 } else {
896 quot -= tsyson[0];
897 }
898 outspecCol.put(i, quot.getArray());
899 outflagCol.put(i, flagsFromMA(quot));
900 }
901 // renumber scanno
902 TableIterator it(tout, "SCANNO");
903 uInt i = 0;
904 while ( !it.pastEnd() ) {
905 Table t = it.table();
906 TableVector<uInt> vec(t, "SCANNO");
907 vec = i;
908 ++i;
909 ++it;
910 }
911 return out;
912}
913
914
915CountedPtr< Scantable > STMath::quotient( const CountedPtr< Scantable > & on,
916 const CountedPtr< Scantable > & off,
917 bool preserve )
918{
919 bool insitu = insitu_;
920 if ( ! on->conformant(*off) ) {
921 throw(AipsError("'on' and 'off' scantables are not conformant."));
922 }
923 setInsitu(false);
924 CountedPtr< Scantable > out = getScantable(on, false);
925 setInsitu(insitu);
926 Table& tout = out->table();
927 const Table& toff = off->table();
928 TableIterator sit(tout, "SCANNO");
929 TableIterator s2it(toff, "SCANNO");
930 while ( !sit.pastEnd() ) {
931 Table ton = sit.table();
932 TableRow row(ton);
933 Table t = s2it.table();
934 ArrayColumn<Float> outspecCol(ton, "SPECTRA");
935 ROArrayColumn<Float> outtsysCol(ton, "TSYS");
936 ArrayColumn<uChar> outflagCol(ton, "FLAGTRA");
937 for (uInt i=0; i < ton.nrow(); ++i) {
938 const TableRecord& rec = row.get(i);
939 Table offsel = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
940 && t.col("IFNO") == Int(rec.asuInt("IFNO"))
941 && t.col("POLNO") == Int(rec.asuInt("POLNO")) );
942 if ( offsel.nrow() == 0 )
943 throw AipsError("STMath::quotient: no matching off");
944 TableRow offrow(offsel);
945 const TableRecord& offrec = offrow.get(0);//should be ncycles - take first
946 RORecordFieldPtr< Array<Float> > specoff(offrec, "SPECTRA");
947 RORecordFieldPtr< Array<Float> > tsysoff(offrec, "TSYS");
948 RORecordFieldPtr< Array<uChar> > flagoff(offrec, "FLAGTRA");
949 Float tsysoffscalar = (*tsysoff)(IPosition(1,0));
950 Vector<Float> specon, tsyson;
951 outtsysCol.get(i, tsyson);
952 outspecCol.get(i, specon);
953 Vector<uChar> flagon;
954 outflagCol.get(i, flagon);
955 MaskedArray<Float> mon = maskedArray(specon, flagon);
956 MaskedArray<Float> moff = maskedArray(*specoff, *flagoff);
957 MaskedArray<Float> quot = (tsysoffscalar * mon / moff);
958 if (preserve) {
959 quot -= tsysoffscalar;
960 } else {
961 quot -= tsyson[0];
962 }
963 outspecCol.put(i, quot.getArray());
964 outflagCol.put(i, flagsFromMA(quot));
965 }
966 ++sit;
967 ++s2it;
968 // take the first off for each on scan which doesn't have a
969 // matching off scan
970 // non <= noff: matching pairs, non > noff matching pairs then first off
971 if ( s2it.pastEnd() ) s2it.reset();
972 }
973 return out;
974}
975
976// dototalpower (migration of GBTIDL procedure dototalpower.pro)
977// calibrate the CAL on-off pair. It calculate Tsys and average CAL on-off subintegrations
978// do it for each cycles in a specific scan.
979CountedPtr< Scantable > STMath::dototalpower( const CountedPtr< Scantable >& calon,
980 const CountedPtr< Scantable >& caloff, Float tcal )
981{
982if ( ! calon->conformant(*caloff) ) {
983 throw(AipsError("'CAL on' and 'CAL off' scantables are not conformant."));
984 }
985 setInsitu(false);
986 CountedPtr< Scantable > out = getScantable(caloff, false);
987 Table& tout = out->table();
988 const Table& tcon = calon->table();
989 Vector<Float> tcalout;
990 Vector<Float> tcalout2; //debug
991
992 if ( tout.nrow() != tcon.nrow() ) {
993 throw(AipsError("Mismatch in number of rows to form cal on - off pair."));
994 }
995 // iteration by scanno or cycle no.
996 TableIterator sit(tout, "SCANNO");
997 TableIterator s2it(tcon, "SCANNO");
998 while ( !sit.pastEnd() ) {
999 Table toff = sit.table();
1000 TableRow row(toff);
1001 Table t = s2it.table();
1002 ScalarColumn<Double> outintCol(toff, "INTERVAL");
1003 ArrayColumn<Float> outspecCol(toff, "SPECTRA");
1004 ArrayColumn<Float> outtsysCol(toff, "TSYS");
1005 ArrayColumn<uChar> outflagCol(toff, "FLAGTRA");
1006 ROScalarColumn<uInt> outtcalIdCol(toff, "TCAL_ID");
1007 ROScalarColumn<uInt> outpolCol(toff, "POLNO");
1008 ROScalarColumn<Double> onintCol(t, "INTERVAL");
1009 ROArrayColumn<Float> onspecCol(t, "SPECTRA");
1010 ROArrayColumn<Float> ontsysCol(t, "TSYS");
1011 ROArrayColumn<uChar> onflagCol(t, "FLAGTRA");
1012 //ROScalarColumn<uInt> ontcalIdCol(t, "TCAL_ID");
1013
1014 for (uInt i=0; i < toff.nrow(); ++i) {
1015 //skip these checks -> assumes the data order are the same between the cal on off pairs
1016 //
1017 Vector<Float> specCalon, specCaloff;
1018 // to store scalar (mean) tsys
1019 Vector<Float> tsysout(1);
1020 uInt tcalId, polno;
1021 Double offint, onint;
1022 outpolCol.get(i, polno);
1023 outspecCol.get(i, specCaloff);
1024 onspecCol.get(i, specCalon);
1025 Vector<uChar> flagCaloff, flagCalon;
1026 outflagCol.get(i, flagCaloff);
1027 onflagCol.get(i, flagCalon);
1028 outtcalIdCol.get(i, tcalId);
1029 outintCol.get(i, offint);
1030 onintCol.get(i, onint);
1031 // caluculate mean Tsys
1032 uInt nchan = specCaloff.nelements();
1033 // percentage of edge cut off
1034 uInt pc = 10;
1035 uInt bchan = nchan/pc;
1036 uInt echan = nchan-bchan;
1037
1038 Slicer chansl(IPosition(1,bchan-1), IPosition(1,echan-1), IPosition(1,1),Slicer::endIsLast);
1039 Vector<Float> testsubsp = specCaloff(chansl);
1040 MaskedArray<Float> spoff = maskedArray( specCaloff(chansl),flagCaloff(chansl) );
1041 MaskedArray<Float> spon = maskedArray( specCalon(chansl),flagCalon(chansl) );
1042 MaskedArray<Float> spdiff = spon-spoff;
1043 uInt noff = spoff.nelementsValid();
1044 //uInt non = spon.nelementsValid();
1045 uInt ndiff = spdiff.nelementsValid();
1046 Float meantsys;
1047
1048/**
1049 Double subspec, subdiff;
1050 uInt usednchan;
1051 subspec = 0;
1052 subdiff = 0;
1053 usednchan = 0;
1054 for(uInt k=(bchan-1); k<echan; k++) {
1055 subspec += specCaloff[k];
1056 subdiff += static_cast<Double>(specCalon[k]-specCaloff[k]);
1057 ++usednchan;
1058 }
1059**/
1060 // get tcal if input tcal <= 0
1061 String tcalt;
1062 Float tcalUsed;
1063 tcalUsed = tcal;
1064 if ( tcal <= 0.0 ) {
1065 caloff->tcal().getEntry(tcalt, tcalout, tcalId);
1066// if (polno<=3) {
1067// tcalUsed = tcalout[polno];
1068// }
1069// else {
1070// tcalUsed = tcalout[0];
1071// }
1072 if ( tcalout.size() == 1 )
1073 tcalUsed = tcalout[0] ;
1074 else if ( tcalout.size() == nchan )
1075 tcalUsed = mean(tcalout) ;
1076 else {
1077 uInt ipol = polno ;
1078 if ( ipol > 3 ) ipol = 0 ;
1079 tcalUsed = tcalout[ipol] ;
1080 }
1081 }
1082
1083 Float meanoff;
1084 Float meandiff;
1085 if (noff && ndiff) {
1086 //Debug
1087 //if(noff!=ndiff) cerr<<"noff and ndiff is not equal"<<endl;
1088 //LogIO os( LogOrigin( "STMath", "dototalpower()", WHERE ) ) ;
1089 //if(noff!=ndiff) os<<"noff and ndiff is not equal"<<LogIO::POST;
1090 meanoff = sum(spoff)/noff;
1091 meandiff = sum(spdiff)/ndiff;
1092 meantsys= (meanoff/meandiff )*tcalUsed + tcalUsed/2;
1093 }
1094 else {
1095 meantsys=1;
1096 }
1097
1098 tsysout[0] = Float(meantsys);
1099 MaskedArray<Float> mcaloff = maskedArray(specCaloff, flagCaloff);
1100 MaskedArray<Float> mcalon = maskedArray(specCalon, flagCalon);
1101 MaskedArray<Float> sig = Float(0.5) * (mcaloff + mcalon);
1102 //uInt ncaloff = mcaloff.nelementsValid();
1103 //uInt ncalon = mcalon.nelementsValid();
1104
1105 outintCol.put(i, offint+onint);
1106 outspecCol.put(i, sig.getArray());
1107 outflagCol.put(i, flagsFromMA(sig));
1108 outtsysCol.put(i, tsysout);
1109 }
1110 ++sit;
1111 ++s2it;
1112 }
1113 return out;
1114}
1115
1116//dosigref - migrated from GBT IDL's dosigref.pro, do calibration of position switch
1117// observatiions.
1118// input: sig and ref scantables, and an optional boxcar smoothing width(default width=0,
1119// no smoothing).
1120// output: resultant scantable [= (sig-ref/ref)*tsys]
1121CountedPtr< Scantable > STMath::dosigref( const CountedPtr < Scantable >& sig,
1122 const CountedPtr < Scantable >& ref,
1123 int smoothref,
1124 casa::Float tsysv,
1125 casa::Float tau )
1126{
1127if ( ! ref->conformant(*sig) ) {
1128 throw(AipsError("'sig' and 'ref' scantables are not conformant."));
1129 }
1130 setInsitu(false);
1131 CountedPtr< Scantable > out = getScantable(sig, false);
1132 CountedPtr< Scantable > smref;
1133 if ( smoothref > 1 ) {
1134 float fsmoothref = static_cast<float>(smoothref);
1135 std::string inkernel = "boxcar";
1136 smref = smooth(ref, inkernel, fsmoothref );
1137 ostringstream oss;
1138 oss<<"Applied smoothing of "<<fsmoothref<<" on the reference."<<endl;
1139 pushLog(String(oss));
1140 }
1141 else {
1142 smref = ref;
1143 }
1144 Table& tout = out->table();
1145 const Table& tref = smref->table();
1146 if ( tout.nrow() != tref.nrow() ) {
1147 throw(AipsError("Mismatch in number of rows to form on-source and reference pair."));
1148 }
1149 // iteration by scanno? or cycle no.
1150 TableIterator sit(tout, "SCANNO");
1151 TableIterator s2it(tref, "SCANNO");
1152 while ( !sit.pastEnd() ) {
1153 Table ton = sit.table();
1154 Table t = s2it.table();
1155 ScalarColumn<Double> outintCol(ton, "INTERVAL");
1156 ArrayColumn<Float> outspecCol(ton, "SPECTRA");
1157 ArrayColumn<Float> outtsysCol(ton, "TSYS");
1158 ArrayColumn<uChar> outflagCol(ton, "FLAGTRA");
1159 ArrayColumn<Float> refspecCol(t, "SPECTRA");
1160 ROScalarColumn<Double> refintCol(t, "INTERVAL");
1161 ROArrayColumn<Float> reftsysCol(t, "TSYS");
1162 ArrayColumn<uChar> refflagCol(t, "FLAGTRA");
1163 ROScalarColumn<Float> refelevCol(t, "ELEVATION");
1164 for (uInt i=0; i < ton.nrow(); ++i) {
1165
1166 Double onint, refint;
1167 Vector<Float> specon, specref;
1168 // to store scalar (mean) tsys
1169 Vector<Float> tsysref;
1170 outintCol.get(i, onint);
1171 refintCol.get(i, refint);
1172 outspecCol.get(i, specon);
1173 refspecCol.get(i, specref);
1174 Vector<uChar> flagref, flagon;
1175 outflagCol.get(i, flagon);
1176 refflagCol.get(i, flagref);
1177 reftsysCol.get(i, tsysref);
1178
1179 Float tsysrefscalar;
1180 if ( tsysv > 0.0 ) {
1181 ostringstream oss;
1182 Float elev;
1183 refelevCol.get(i, elev);
1184 oss << "user specified Tsys = " << tsysv;
1185 // do recalc elevation if EL = 0
1186 if ( elev == 0 ) {
1187 throw(AipsError("EL=0, elevation data is missing."));
1188 } else {
1189 if ( tau <= 0.0 ) {
1190 throw(AipsError("Valid tau is not supplied."));
1191 } else {
1192 tsysrefscalar = tsysv * exp(tau/elev);
1193 }
1194 }
1195 oss << ", corrected (for El) tsys= "<<tsysrefscalar;
1196 pushLog(String(oss));
1197 }
1198 else {
1199 tsysrefscalar = tsysref[0];
1200 }
1201 //get quotient spectrum
1202 MaskedArray<Float> mref = maskedArray(specref, flagref);
1203 MaskedArray<Float> mon = maskedArray(specon, flagon);
1204 MaskedArray<Float> specres = tsysrefscalar*((mon - mref)/mref);
1205 Double resint = onint*refint*smoothref/(onint+refint*smoothref);
1206
1207 //Debug
1208 //cerr<<"Tsys used="<<tsysrefscalar<<endl;
1209 //LogIO os( LogOrigin( "STMath", "dosigref", WHERE ) ) ;
1210 //os<<"Tsys used="<<tsysrefscalar<<LogIO::POST;
1211 // fill the result, replay signal tsys by reference tsys
1212 outintCol.put(i, resint);
1213 outspecCol.put(i, specres.getArray());
1214 outflagCol.put(i, flagsFromMA(specres));
1215 outtsysCol.put(i, tsysref);
1216 }
1217 ++sit;
1218 ++s2it;
1219 }
1220 return out;
1221}
1222
1223CountedPtr< Scantable > STMath::donod(const casa::CountedPtr<Scantable>& s,
1224 const std::vector<int>& scans,
1225 int smoothref,
1226 casa::Float tsysv,
1227 casa::Float tau,
1228 casa::Float tcal )
1229
1230{
1231 setInsitu(false);
1232 STSelector sel;
1233 std::vector<int> scan1, scan2, beams, types;
1234 std::vector< vector<int> > scanpair;
1235 //std::vector<string> calstate;
1236 std::vector<int> calstate;
1237 String msg;
1238
1239 CountedPtr< Scantable > s1b1on, s1b1off, s1b2on, s1b2off;
1240 CountedPtr< Scantable > s2b1on, s2b1off, s2b2on, s2b2off;
1241
1242 std::vector< CountedPtr< Scantable > > sctables;
1243 sctables.push_back(s1b1on);
1244 sctables.push_back(s1b1off);
1245 sctables.push_back(s1b2on);
1246 sctables.push_back(s1b2off);
1247 sctables.push_back(s2b1on);
1248 sctables.push_back(s2b1off);
1249 sctables.push_back(s2b2on);
1250 sctables.push_back(s2b2off);
1251
1252 //check scanlist
1253 int n=s->checkScanInfo(scans);
1254 if (n==1) {
1255 throw(AipsError("Incorrect scan pairs. "));
1256 }
1257
1258 // Assume scans contain only a pair of consecutive scan numbers.
1259 // It is assumed that first beam, b1, is on target.
1260 // There is no check if the first beam is on or not.
1261 if ( scans.size()==1 ) {
1262 scan1.push_back(scans[0]);
1263 scan2.push_back(scans[0]+1);
1264 } else if ( scans.size()==2 ) {
1265 scan1.push_back(scans[0]);
1266 scan2.push_back(scans[1]);
1267 } else {
1268 if ( scans.size()%2 == 0 ) {
1269 for (uInt i=0; i<scans.size(); i++) {
1270 if (i%2 == 0) {
1271 scan1.push_back(scans[i]);
1272 }
1273 else {
1274 scan2.push_back(scans[i]);
1275 }
1276 }
1277 } else {
1278 throw(AipsError("Odd numbers of scans, cannot form pairs."));
1279 }
1280 }
1281 scanpair.push_back(scan1);
1282 scanpair.push_back(scan2);
1283 //calstate.push_back("*calon");
1284 //calstate.push_back("*[^calon]");
1285 calstate.push_back(SrcType::NODCAL);
1286 calstate.push_back(SrcType::NOD);
1287 CountedPtr< Scantable > ws = getScantable(s, false);
1288 uInt l=0;
1289 while ( l < sctables.size() ) {
1290 for (uInt i=0; i < 2; i++) {
1291 for (uInt j=0; j < 2; j++) {
1292 for (uInt k=0; k < 2; k++) {
1293 sel.reset();
1294 sel.setScans(scanpair[i]);
1295 //sel.setName(calstate[k]);
1296 types.clear();
1297 types.push_back(calstate[k]);
1298 sel.setTypes(types);
1299 beams.clear();
1300 beams.push_back(j);
1301 sel.setBeams(beams);
1302 ws->setSelection(sel);
1303 sctables[l]= getScantable(ws, false);
1304 l++;
1305 }
1306 }
1307 }
1308 }
1309
1310 // replace here by splitData or getData functionality
1311 CountedPtr< Scantable > sig1;
1312 CountedPtr< Scantable > ref1;
1313 CountedPtr< Scantable > sig2;
1314 CountedPtr< Scantable > ref2;
1315 CountedPtr< Scantable > calb1;
1316 CountedPtr< Scantable > calb2;
1317
1318 msg=String("Processing dototalpower for subset of the data");
1319 ostringstream oss1;
1320 oss1 << msg << endl;
1321 pushLog(String(oss1));
1322 // Debug for IRC CS data
1323 //float tcal1=7.0;
1324 //float tcal2=4.0;
1325 sig1 = dototalpower(sctables[0], sctables[1], tcal=tcal);
1326 ref1 = dototalpower(sctables[2], sctables[3], tcal=tcal);
1327 ref2 = dototalpower(sctables[4], sctables[5], tcal=tcal);
1328 sig2 = dototalpower(sctables[6], sctables[7], tcal=tcal);
1329
1330 // correction of user-specified tsys for elevation here
1331
1332 // dosigref calibration
1333 msg=String("Processing dosigref for subset of the data");
1334 ostringstream oss2;
1335 oss2 << msg << endl;
1336 pushLog(String(oss2));
1337 calb1=dosigref(sig1,ref2,smoothref,tsysv,tau);
1338 calb2=dosigref(sig2,ref1,smoothref,tsysv,tau);
1339
1340 // iteration by scanno or cycle no.
1341 Table& tcalb1 = calb1->table();
1342 Table& tcalb2 = calb2->table();
1343 TableIterator sit(tcalb1, "SCANNO");
1344 TableIterator s2it(tcalb2, "SCANNO");
1345 while ( !sit.pastEnd() ) {
1346 Table t1 = sit.table();
1347 Table t2= s2it.table();
1348 ArrayColumn<Float> outspecCol(t1, "SPECTRA");
1349 ArrayColumn<Float> outtsysCol(t1, "TSYS");
1350 ArrayColumn<uChar> outflagCol(t1, "FLAGTRA");
1351 ScalarColumn<Double> outintCol(t1, "INTERVAL");
1352 ArrayColumn<Float> t2specCol(t2, "SPECTRA");
1353 ROArrayColumn<Float> t2tsysCol(t2, "TSYS");
1354 ArrayColumn<uChar> t2flagCol(t2, "FLAGTRA");
1355 ROScalarColumn<Double> t2intCol(t2, "INTERVAL");
1356 for (uInt i=0; i < t1.nrow(); ++i) {
1357 Vector<Float> spec1, spec2;
1358 // to store scalar (mean) tsys
1359 Vector<Float> tsys1, tsys2;
1360 Vector<uChar> flag1, flag2;
1361 Double tint1, tint2;
1362 outspecCol.get(i, spec1);
1363 t2specCol.get(i, spec2);
1364 outflagCol.get(i, flag1);
1365 t2flagCol.get(i, flag2);
1366 outtsysCol.get(i, tsys1);
1367 t2tsysCol.get(i, tsys2);
1368 outintCol.get(i, tint1);
1369 t2intCol.get(i, tint2);
1370 // average
1371 // assume scalar tsys for weights
1372 Float wt1, wt2, tsyssq1, tsyssq2;
1373 tsyssq1 = tsys1[0]*tsys1[0];
1374 tsyssq2 = tsys2[0]*tsys2[0];
1375 wt1 = Float(tint1)/tsyssq1;
1376 wt2 = Float(tint2)/tsyssq2;
1377 Float invsumwt=1/(wt1+wt2);
1378 MaskedArray<Float> mspec1 = maskedArray(spec1, flag1);
1379 MaskedArray<Float> mspec2 = maskedArray(spec2, flag2);
1380 MaskedArray<Float> avspec = invsumwt * (wt1*mspec1 + wt2*mspec2);
1381 //Array<Float> avtsys = Float(0.5) * (tsys1 + tsys2);
1382 // cerr<< "Tsys1="<<tsys1<<" Tsys2="<<tsys2<<endl;
1383 // LogIO os( LogOrigin( "STMath", "donod", WHERE ) ) ;
1384 // os<< "Tsys1="<<tsys1<<" Tsys2="<<tsys2<<LogIO::POST;
1385 tsys1[0] = sqrt(tsyssq1 + tsyssq2);
1386 Array<Float> avtsys = tsys1;
1387
1388 outspecCol.put(i, avspec.getArray());
1389 outflagCol.put(i, flagsFromMA(avspec));
1390 outtsysCol.put(i, avtsys);
1391 }
1392 ++sit;
1393 ++s2it;
1394 }
1395 return calb1;
1396}
1397
1398//GBTIDL version of frequency switched data calibration
1399CountedPtr< Scantable > STMath::dofs( const CountedPtr< Scantable >& s,
1400 const std::vector<int>& scans,
1401 int smoothref,
1402 casa::Float tsysv,
1403 casa::Float tau,
1404 casa::Float tcal )
1405{
1406
1407
1408 (void) scans; //currently unused
1409 STSelector sel;
1410 CountedPtr< Scantable > ws = getScantable(s, false);
1411 CountedPtr< Scantable > sig, sigwcal, ref, refwcal;
1412 CountedPtr< Scantable > calsig, calref, out, out1, out2;
1413 Bool nofold=False;
1414 vector<int> types ;
1415
1416 //split the data
1417 //sel.setName("*_fs");
1418 types.push_back( SrcType::FSON ) ;
1419 sel.setTypes( types ) ;
1420 ws->setSelection(sel);
1421 sig = getScantable(ws,false);
1422 sel.reset();
1423 types.clear() ;
1424 //sel.setName("*_fs_calon");
1425 types.push_back( SrcType::FONCAL ) ;
1426 sel.setTypes( types ) ;
1427 ws->setSelection(sel);
1428 sigwcal = getScantable(ws,false);
1429 sel.reset();
1430 types.clear() ;
1431 //sel.setName("*_fsr");
1432 types.push_back( SrcType::FSOFF ) ;
1433 sel.setTypes( types ) ;
1434 ws->setSelection(sel);
1435 ref = getScantable(ws,false);
1436 sel.reset();
1437 types.clear() ;
1438 //sel.setName("*_fsr_calon");
1439 types.push_back( SrcType::FOFFCAL ) ;
1440 sel.setTypes( types ) ;
1441 ws->setSelection(sel);
1442 refwcal = getScantable(ws,false);
1443 sel.reset() ;
1444 types.clear() ;
1445
1446 calsig = dototalpower(sigwcal, sig, tcal=tcal);
1447 calref = dototalpower(refwcal, ref, tcal=tcal);
1448
1449 out1=dosigref(calsig,calref,smoothref,tsysv,tau);
1450 out2=dosigref(calref,calsig,smoothref,tsysv,tau);
1451
1452 Table& tabout1=out1->table();
1453 Table& tabout2=out2->table();
1454 ROScalarColumn<uInt> freqidCol1(tabout1, "FREQ_ID");
1455 ScalarColumn<uInt> freqidCol2(tabout2, "FREQ_ID");
1456 ROArrayColumn<Float> specCol(tabout2, "SPECTRA");
1457 Vector<Float> spec; specCol.get(0, spec);
1458 uInt nchan = spec.nelements();
1459 uInt freqid1; freqidCol1.get(0,freqid1);
1460 uInt freqid2; freqidCol2.get(0,freqid2);
1461 Double rp1, rp2, rv1, rv2, inc1, inc2;
1462 out1->frequencies().getEntry(rp1, rv1, inc1, freqid1);
1463 out2->frequencies().getEntry(rp2, rv2, inc2, freqid2);
1464 //cerr << out1->frequencies().table().nrow() << " " << out2->frequencies().table().nrow() << endl ;
1465 //LogIO os( LogOrigin( "STMath", "dofs()", WHERE ) ) ;
1466 //os << out1->frequencies().table().nrow() << " " << out2->frequencies().table().nrow() << LogIO::POST ;
1467 if (rp1==rp2) {
1468 Double foffset = rv1 - rv2;
1469 uInt choffset = static_cast<uInt>(foffset/abs(inc2));
1470 if (choffset >= nchan) {
1471 //cerr<<"out-band frequency switching, no folding"<<endl;
1472 LogIO os( LogOrigin( "STMath", "dofs()", WHERE ) ) ;
1473 os<<"out-band frequency switching, no folding"<<LogIO::POST;
1474 nofold = True;
1475 }
1476 }
1477
1478 if (nofold) {
1479 std::vector< CountedPtr< Scantable > > tabs;
1480 tabs.push_back(out1);
1481 tabs.push_back(out2);
1482 out = merge(tabs);
1483 }
1484 else {
1485 //out = out1;
1486 Double choffset = ( rv1 - rv2 ) / inc2 ;
1487 out = dofold( out1, out2, choffset ) ;
1488 }
1489
1490 return out;
1491}
1492
1493CountedPtr<Scantable> STMath::dofold( const CountedPtr<Scantable> &sig,
1494 const CountedPtr<Scantable> &ref,
1495 Double choffset,
1496 Double choffset2 )
1497{
1498 LogIO os( LogOrigin( "STMath", "dofold", WHERE ) ) ;
1499 os << "choffset=" << choffset << " choffset2=" << choffset2 << LogIO::POST ;
1500
1501 // output scantable
1502 CountedPtr<Scantable> out = getScantable( sig, false ) ;
1503
1504 // separate choffset to integer part and decimal part
1505 Int ioffset = (Int)choffset ;
1506 Double doffset = choffset - ioffset ;
1507 Int ioffset2 = (Int)choffset2 ;
1508 Double doffset2 = choffset2 - ioffset2 ;
1509 os << "ioffset=" << ioffset << " doffset=" << doffset << LogIO::POST ;
1510 os << "ioffset2=" << ioffset2 << " doffset2=" << doffset2 << LogIO::POST ;
1511
1512 // get column
1513 ROArrayColumn<Float> specCol1( sig->table(), "SPECTRA" ) ;
1514 ROArrayColumn<Float> specCol2( ref->table(), "SPECTRA" ) ;
1515 ROArrayColumn<Float> tsysCol1( sig->table(), "TSYS" ) ;
1516 ROArrayColumn<Float> tsysCol2( ref->table(), "TSYS" ) ;
1517 ROArrayColumn<uChar> flagCol1( sig->table(), "FLAGTRA" ) ;
1518 ROArrayColumn<uChar> flagCol2( ref->table(), "FLAGTRA" ) ;
1519 ROScalarColumn<Double> mjdCol1( sig->table(), "TIME" ) ;
1520 ROScalarColumn<Double> mjdCol2( ref->table(), "TIME" ) ;
1521 ROScalarColumn<Double> intervalCol1( sig->table(), "INTERVAL" ) ;
1522 ROScalarColumn<Double> intervalCol2( ref->table(), "INTERVAL" ) ;
1523
1524 // check
1525 if ( ioffset == 0 ) {
1526 LogIO os( LogOrigin( "STMath", "dofold()", WHERE ) ) ;
1527 os << "channel offset is zero, no folding" << LogIO::POST ;
1528 return out ;
1529 }
1530 int nchan = ref->nchan() ;
1531 if ( abs(ioffset) >= nchan ) {
1532 LogIO os( LogOrigin( "STMath", "dofold()", WHERE ) ) ;
1533 os << "out-band frequency switching, no folding" << LogIO::POST ;
1534 return out ;
1535 }
1536
1537 // attach column for output scantable
1538 ArrayColumn<Float> specColOut( out->table(), "SPECTRA" ) ;
1539 ArrayColumn<uChar> flagColOut( out->table(), "FLAGTRA" ) ;
1540 ArrayColumn<Float> tsysColOut( out->table(), "TSYS" ) ;
1541 ScalarColumn<Double> mjdColOut( out->table(), "TIME" ) ;
1542 ScalarColumn<Double> intervalColOut( out->table(), "INTERVAL" ) ;
1543 ScalarColumn<uInt> fidColOut( out->table(), "FREQ_ID" ) ;
1544
1545 // for each row
1546 // assume that the data order are same between sig and ref
1547 RowAccumulator acc( asap::W_TINTSYS ) ;
1548 for ( int i = 0 ; i < sig->nrow() ; i++ ) {
1549 // get values
1550 Vector<Float> spsig ;
1551 specCol1.get( i, spsig ) ;
1552 Vector<Float> spref ;
1553 specCol2.get( i, spref ) ;
1554 Vector<Float> tsyssig ;
1555 tsysCol1.get( i, tsyssig ) ;
1556 Vector<Float> tsysref ;
1557 tsysCol2.get( i, tsysref ) ;
1558 Vector<uChar> flagsig ;
1559 flagCol1.get( i, flagsig ) ;
1560 Vector<uChar> flagref ;
1561 flagCol2.get( i, flagref ) ;
1562 Double timesig ;
1563 mjdCol1.get( i, timesig ) ;
1564 Double timeref ;
1565 mjdCol2.get( i, timeref ) ;
1566 Double intsig ;
1567 intervalCol1.get( i, intsig ) ;
1568 Double intref ;
1569 intervalCol2.get( i, intref ) ;
1570
1571 // shift reference spectra
1572 int refchan = spref.nelements() ;
1573 Vector<Float> sspref( spref.nelements() ) ;
1574 Vector<Float> stsysref( tsysref.nelements() ) ;
1575 Vector<uChar> sflagref( flagref.nelements() ) ;
1576 if ( ioffset > 0 ) {
1577 // SPECTRA and FLAGTRA
1578 for ( int j = 0 ; j < refchan-ioffset ; j++ ) {
1579 sspref[j] = spref[j+ioffset] ;
1580 sflagref[j] = flagref[j+ioffset] ;
1581 }
1582 for ( int j = refchan-ioffset ; j < refchan ; j++ ) {
1583 sspref[j] = spref[j-refchan+ioffset] ;
1584 sflagref[j] = flagref[j-refchan+ioffset] ;
1585 }
1586 spref = sspref.copy() ;
1587 flagref = sflagref.copy() ;
1588 for ( int j = 0 ; j < refchan - 1 ; j++ ) {
1589 sspref[j] = doffset * spref[j+1] + ( 1.0 - doffset ) * spref[j] ;
1590 sflagref[j] = flagref[j+1] + flagref[j] ;
1591 }
1592 sspref[refchan-1] = doffset * spref[0] + ( 1.0 - doffset ) * spref[refchan-1] ;
1593 sflagref[refchan-1] = flagref[0] + flagref[refchan-1] ;
1594
1595 // TSYS
1596 if ( spref.nelements() == tsysref.nelements() ) {
1597 for ( int j = 0 ; j < refchan-ioffset ; j++ ) {
1598 stsysref[j] = tsysref[j+ioffset] ;
1599 }
1600 for ( int j = refchan-ioffset ; j < refchan ; j++ ) {
1601 stsysref[j] = tsysref[j-refchan+ioffset] ;
1602 }
1603 tsysref = stsysref.copy() ;
1604 for ( int j = 0 ; j < refchan - 1 ; j++ ) {
1605 stsysref[j] = doffset * tsysref[j+1] + ( 1.0 - doffset ) * tsysref[j] ;
1606 }
1607 stsysref[refchan-1] = doffset * tsysref[0] + ( 1.0 - doffset ) * tsysref[refchan-1] ;
1608 }
1609 }
1610 else {
1611 // SPECTRA and FLAGTRA
1612 for ( int j = 0 ; j < abs(ioffset) ; j++ ) {
1613 sspref[j] = spref[refchan+ioffset+j] ;
1614 sflagref[j] = flagref[refchan+ioffset+j] ;
1615 }
1616 for ( int j = abs(ioffset) ; j < refchan ; j++ ) {
1617 sspref[j] = spref[j+ioffset] ;
1618 sflagref[j] = flagref[j+ioffset] ;
1619 }
1620 spref = sspref.copy() ;
1621 flagref = sflagref.copy() ;
1622 sspref[0] = doffset * spref[refchan-1] + ( 1.0 - doffset ) * spref[0] ;
1623 sflagref[0] = flagref[0] + flagref[refchan-1] ;
1624 for ( int j = 1 ; j < refchan ; j++ ) {
1625 sspref[j] = doffset * spref[j-1] + ( 1.0 - doffset ) * spref[j] ;
1626 sflagref[j] = flagref[j-1] + flagref[j] ;
1627 }
1628 // TSYS
1629 if ( spref.nelements() == tsysref.nelements() ) {
1630 for ( int j = 0 ; j < abs(ioffset) ; j++ ) {
1631 stsysref[j] = tsysref[refchan+ioffset+j] ;
1632 }
1633 for ( int j = abs(ioffset) ; j < refchan ; j++ ) {
1634 stsysref[j] = tsysref[j+ioffset] ;
1635 }
1636 tsysref = stsysref.copy() ;
1637 stsysref[0] = doffset * tsysref[refchan-1] + ( 1.0 - doffset ) * tsysref[0] ;
1638 for ( int j = 1 ; j < refchan ; j++ ) {
1639 stsysref[j] = doffset * tsysref[j-1] + ( 1.0 - doffset ) * tsysref[j] ;
1640 }
1641 }
1642 }
1643
1644 // shift signal spectra if necessary (only for APEX?)
1645 if ( choffset2 != 0.0 ) {
1646 int sigchan = spsig.nelements() ;
1647 Vector<Float> sspsig( spsig.nelements() ) ;
1648 Vector<Float> stsyssig( tsyssig.nelements() ) ;
1649 Vector<uChar> sflagsig( flagsig.nelements() ) ;
1650 if ( ioffset2 > 0 ) {
1651 // SPECTRA and FLAGTRA
1652 for ( int j = 0 ; j < sigchan-ioffset2 ; j++ ) {
1653 sspsig[j] = spsig[j+ioffset2] ;
1654 sflagsig[j] = flagsig[j+ioffset2] ;
1655 }
1656 for ( int j = sigchan-ioffset2 ; j < sigchan ; j++ ) {
1657 sspsig[j] = spsig[j-sigchan+ioffset2] ;
1658 sflagsig[j] = flagsig[j-sigchan+ioffset2] ;
1659 }
1660 spsig = sspsig.copy() ;
1661 flagsig = sflagsig.copy() ;
1662 for ( int j = 0 ; j < sigchan - 1 ; j++ ) {
1663 sspsig[j] = doffset2 * spsig[j+1] + ( 1.0 - doffset2 ) * spsig[j] ;
1664 sflagsig[j] = flagsig[j+1] || flagsig[j] ;
1665 }
1666 sspsig[sigchan-1] = doffset2 * spsig[0] + ( 1.0 - doffset2 ) * spsig[sigchan-1] ;
1667 sflagsig[sigchan-1] = flagsig[0] || flagsig[sigchan-1] ;
1668 // TSTS
1669 if ( spsig.nelements() == tsyssig.nelements() ) {
1670 for ( int j = 0 ; j < sigchan-ioffset2 ; j++ ) {
1671 stsyssig[j] = tsyssig[j+ioffset2] ;
1672 }
1673 for ( int j = sigchan-ioffset2 ; j < sigchan ; j++ ) {
1674 stsyssig[j] = tsyssig[j-sigchan+ioffset2] ;
1675 }
1676 tsyssig = stsyssig.copy() ;
1677 for ( int j = 0 ; j < sigchan - 1 ; j++ ) {
1678 stsyssig[j] = doffset2 * tsyssig[j+1] + ( 1.0 - doffset2 ) * tsyssig[j] ;
1679 }
1680 stsyssig[sigchan-1] = doffset2 * tsyssig[0] + ( 1.0 - doffset2 ) * tsyssig[sigchan-1] ;
1681 }
1682 }
1683 else {
1684 // SPECTRA and FLAGTRA
1685 for ( int j = 0 ; j < abs(ioffset2) ; j++ ) {
1686 sspsig[j] = spsig[sigchan+ioffset2+j] ;
1687 sflagsig[j] = flagsig[sigchan+ioffset2+j] ;
1688 }
1689 for ( int j = abs(ioffset2) ; j < sigchan ; j++ ) {
1690 sspsig[j] = spsig[j+ioffset2] ;
1691 sflagsig[j] = flagsig[j+ioffset2] ;
1692 }
1693 spsig = sspsig.copy() ;
1694 flagsig = sflagsig.copy() ;
1695 sspsig[0] = doffset2 * spsig[sigchan-1] + ( 1.0 - doffset2 ) * spsig[0] ;
1696 sflagsig[0] = flagsig[0] + flagsig[sigchan-1] ;
1697 for ( int j = 1 ; j < sigchan ; j++ ) {
1698 sspsig[j] = doffset2 * spsig[j-1] + ( 1.0 - doffset2 ) * spsig[j] ;
1699 sflagsig[j] = flagsig[j-1] + flagsig[j] ;
1700 }
1701 // TSYS
1702 if ( spsig.nelements() == tsyssig.nelements() ) {
1703 for ( int j = 0 ; j < abs(ioffset2) ; j++ ) {
1704 stsyssig[j] = tsyssig[sigchan+ioffset2+j] ;
1705 }
1706 for ( int j = abs(ioffset2) ; j < sigchan ; j++ ) {
1707 stsyssig[j] = tsyssig[j+ioffset2] ;
1708 }
1709 tsyssig = stsyssig.copy() ;
1710 stsyssig[0] = doffset2 * tsyssig[sigchan-1] + ( 1.0 - doffset2 ) * tsyssig[0] ;
1711 for ( int j = 1 ; j < sigchan ; j++ ) {
1712 stsyssig[j] = doffset2 * tsyssig[j-1] + ( 1.0 - doffset2 ) * tsyssig[j] ;
1713 }
1714 }
1715 }
1716 }
1717
1718 // folding
1719 acc.add( spsig, !flagsig, tsyssig, intsig, timesig ) ;
1720 acc.add( sspref, !sflagref, stsysref, intref, timeref ) ;
1721
1722 // put result
1723 specColOut.put( i, acc.getSpectrum() ) ;
1724 const Vector<Bool> &msk = acc.getMask() ;
1725 Vector<uChar> flg( msk.shape() ) ;
1726 convertArray( flg, !msk ) ;
1727 flagColOut.put( i, flg ) ;
1728 tsysColOut.put( i, acc.getTsys() ) ;
1729 intervalColOut.put( i, acc.getInterval() ) ;
1730 mjdColOut.put( i, acc.getTime() ) ;
1731 // change FREQ_ID to unshifted IF setting (only for APEX?)
1732 if ( choffset2 != 0.0 ) {
1733 uInt freqid = fidColOut( 0 ) ; // assume single-IF data
1734 double refpix, refval, increment ;
1735 out->frequencies().getEntry( refpix, refval, increment, freqid ) ;
1736 refval -= choffset * increment ;
1737 uInt newfreqid = out->frequencies().addEntry( refpix, refval, increment ) ;
1738 Vector<uInt> freqids = fidColOut.getColumn() ;
1739 for ( uInt j = 0 ; j < freqids.nelements() ; j++ ) {
1740 if ( freqids[j] == freqid )
1741 freqids[j] = newfreqid ;
1742 }
1743 fidColOut.putColumn( freqids ) ;
1744 }
1745
1746 acc.reset() ;
1747 }
1748
1749 return out ;
1750}
1751
1752
1753CountedPtr< Scantable > STMath::freqSwitch( const CountedPtr< Scantable >& in )
1754{
1755 // make copy or reference
1756 CountedPtr< Scantable > out = getScantable(in, false);
1757 Table& tout = out->table();
1758 Block<String> cols(4);
1759 cols[0] = String("SCANNO");
1760 cols[1] = String("CYCLENO");
1761 cols[2] = String("BEAMNO");
1762 cols[3] = String("POLNO");
1763 TableIterator iter(tout, cols);
1764 while (!iter.pastEnd()) {
1765 Table subt = iter.table();
1766 // this should leave us with two rows for the two IFs....if not ignore
1767 if (subt.nrow() != 2 ) {
1768 continue;
1769 }
1770 ArrayColumn<Float> specCol(subt, "SPECTRA");
1771 ArrayColumn<Float> tsysCol(subt, "TSYS");
1772 ArrayColumn<uChar> flagCol(subt, "FLAGTRA");
1773 Vector<Float> onspec,offspec, ontsys, offtsys;
1774 Vector<uChar> onflag, offflag;
1775 tsysCol.get(0, ontsys); tsysCol.get(1, offtsys);
1776 specCol.get(0, onspec); specCol.get(1, offspec);
1777 flagCol.get(0, onflag); flagCol.get(1, offflag);
1778 MaskedArray<Float> on = maskedArray(onspec, onflag);
1779 MaskedArray<Float> off = maskedArray(offspec, offflag);
1780 MaskedArray<Float> oncopy = on.copy();
1781
1782 on /= off; on -= 1.0f;
1783 on *= ontsys[0];
1784 off /= oncopy; off -= 1.0f;
1785 off *= offtsys[0];
1786 specCol.put(0, on.getArray());
1787 const Vector<Bool>& m0 = on.getMask();
1788 Vector<uChar> flags0(m0.shape());
1789 convertArray(flags0, !m0);
1790 flagCol.put(0, flags0);
1791
1792 specCol.put(1, off.getArray());
1793 const Vector<Bool>& m1 = off.getMask();
1794 Vector<uChar> flags1(m1.shape());
1795 convertArray(flags1, !m1);
1796 flagCol.put(1, flags1);
1797 ++iter;
1798 }
1799
1800 return out;
1801}
1802
1803std::vector< float > STMath::statistic( const CountedPtr< Scantable > & in,
1804 const std::vector< bool > & mask,
1805 const std::string& which )
1806{
1807
1808 Vector<Bool> m(mask);
1809 const Table& tab = in->table();
1810 ROArrayColumn<Float> specCol(tab, "SPECTRA");
1811 ROArrayColumn<uChar> flagCol(tab, "FLAGTRA");
1812 std::vector<float> out;
1813 for (uInt i=0; i < tab.nrow(); ++i ) {
1814 Vector<Float> spec; specCol.get(i, spec);
1815 Vector<uChar> flag; flagCol.get(i, flag);
1816 MaskedArray<Float> ma = maskedArray(spec, flag);
1817 float outstat = 0.0;
1818 if ( spec.nelements() == m.nelements() ) {
1819 outstat = mathutil::statistics(which, ma(m));
1820 } else {
1821 outstat = mathutil::statistics(which, ma);
1822 }
1823 out.push_back(outstat);
1824 }
1825 return out;
1826}
1827
1828std::vector< float > STMath::statisticRow( const CountedPtr< Scantable > & in,
1829 const std::vector< bool > & mask,
1830 const std::string& which,
1831 int row )
1832{
1833
1834 Vector<Bool> m(mask);
1835 const Table& tab = in->table();
1836 ROArrayColumn<Float> specCol(tab, "SPECTRA");
1837 ROArrayColumn<uChar> flagCol(tab, "FLAGTRA");
1838 std::vector<float> out;
1839
1840 Vector<Float> spec; specCol.get(row, spec);
1841 Vector<uChar> flag; flagCol.get(row, flag);
1842 MaskedArray<Float> ma = maskedArray(spec, flag);
1843 float outstat = 0.0;
1844 if ( spec.nelements() == m.nelements() ) {
1845 outstat = mathutil::statistics(which, ma(m));
1846 } else {
1847 outstat = mathutil::statistics(which, ma);
1848 }
1849 out.push_back(outstat);
1850
1851 return out;
1852}
1853
1854std::vector< int > STMath::minMaxChan( const CountedPtr< Scantable > & in,
1855 const std::vector< bool > & mask,
1856 const std::string& which )
1857{
1858
1859 Vector<Bool> m(mask);
1860 const Table& tab = in->table();
1861 ROArrayColumn<Float> specCol(tab, "SPECTRA");
1862 ROArrayColumn<uChar> flagCol(tab, "FLAGTRA");
1863 std::vector<int> out;
1864 for (uInt i=0; i < tab.nrow(); ++i ) {
1865 Vector<Float> spec; specCol.get(i, spec);
1866 Vector<uChar> flag; flagCol.get(i, flag);
1867 MaskedArray<Float> ma = maskedArray(spec, flag);
1868 if (ma.ndim() != 1) {
1869 throw (ArrayError(
1870 "std::vector<int> STMath::minMaxChan("
1871 "ContedPtr<Scantable> &in, std::vector<bool> &mask, "
1872 " std::string &which)"
1873 " - MaskedArray is not 1D"));
1874 }
1875 IPosition outpos(1,0);
1876 if ( spec.nelements() == m.nelements() ) {
1877 outpos = mathutil::minMaxPos(which, ma(m));
1878 } else {
1879 outpos = mathutil::minMaxPos(which, ma);
1880 }
1881 out.push_back(outpos[0]);
1882 }
1883 return out;
1884}
1885
1886CountedPtr< Scantable > STMath::bin( const CountedPtr< Scantable > & in,
1887 int width )
1888{
1889 if ( !in->getSelection().empty() ) throw(AipsError("Can't bin subset of the data."));
1890 CountedPtr< Scantable > out = getScantable(in, false);
1891 Table& tout = out->table();
1892 out->frequencies().rescale(width, "BIN");
1893 ArrayColumn<Float> specCol(tout, "SPECTRA");
1894 ArrayColumn<uChar> flagCol(tout, "FLAGTRA");
1895 for (uInt i=0; i < tout.nrow(); ++i ) {
1896 MaskedArray<Float> main = maskedArray(specCol(i), flagCol(i));
1897 MaskedArray<Float> maout;
1898 LatticeUtilities::bin(maout, main, 0, Int(width));
1899 /// @todo implement channel based tsys binning
1900 specCol.put(i, maout.getArray());
1901 flagCol.put(i, flagsFromMA(maout));
1902 // take only the first binned spectrum's length for the deprecated
1903 // global header item nChan
1904 if (i==0) tout.rwKeywordSet().define(String("nChan"),
1905 Int(maout.getArray().nelements()));
1906 }
1907 return out;
1908}
1909
1910CountedPtr< Scantable > STMath::resample( const CountedPtr< Scantable >& in,
1911 const std::string& method,
1912 float width )
1913//
1914// Should add the possibility of width being specified in km/s. This means
1915// that for each freqID (SpectralCoordinate) we will need to convert to an
1916// average channel width (say at the reference pixel). Then we would need
1917// to be careful to make sure each spectrum (of different freqID)
1918// is the same length.
1919//
1920{
1921 //InterpolateArray1D<Double,Float>::InterpolationMethod interp;
1922 Int interpMethod(stringToIMethod(method));
1923
1924 CountedPtr< Scantable > out = getScantable(in, false);
1925 Table& tout = out->table();
1926
1927// Resample SpectralCoordinates (one per freqID)
1928 out->frequencies().rescale(width, "RESAMPLE");
1929 TableIterator iter(tout, "IFNO");
1930 TableRow row(tout);
1931 while ( !iter.pastEnd() ) {
1932 Table tab = iter.table();
1933 ArrayColumn<Float> specCol(tab, "SPECTRA");
1934 //ArrayColumn<Float> tsysCol(tout, "TSYS");
1935 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
1936 Vector<Float> spec;
1937 Vector<uChar> flag;
1938 specCol.get(0,spec); // the number of channels should be constant per IF
1939 uInt nChanIn = spec.nelements();
1940 Vector<Float> xIn(nChanIn); indgen(xIn);
1941 Int fac = Int(nChanIn/width);
1942 Vector<Float> xOut(fac+10); // 10 to be safe - resize later
1943 uInt k = 0;
1944 Float x = 0.0;
1945 while (x < Float(nChanIn) ) {
1946 xOut(k) = x;
1947 k++;
1948 x += width;
1949 }
1950 uInt nChanOut = k;
1951 xOut.resize(nChanOut, True);
1952 // process all rows for this IFNO
1953 Vector<Float> specOut;
1954 Vector<Bool> maskOut;
1955 Vector<uChar> flagOut;
1956 for (uInt i=0; i < tab.nrow(); ++i) {
1957 specCol.get(i, spec);
1958 flagCol.get(i, flag);
1959 Vector<Bool> mask(flag.nelements());
1960 convertArray(mask, flag);
1961
1962 IPosition shapeIn(spec.shape());
1963 //sh.nchan = nChanOut;
1964 InterpolateArray1D<Float,Float>::interpolate(specOut, maskOut, xOut,
1965 xIn, spec, mask,
1966 interpMethod, True, True);
1967 /// @todo do the same for channel based Tsys
1968 flagOut.resize(maskOut.nelements());
1969 convertArray(flagOut, maskOut);
1970 specCol.put(i, specOut);
1971 flagCol.put(i, flagOut);
1972 }
1973 ++iter;
1974 }
1975
1976 return out;
1977}
1978
1979STMath::imethod STMath::stringToIMethod(const std::string& in)
1980{
1981 static STMath::imap lookup;
1982
1983 // initialize the lookup table if necessary
1984 if ( lookup.empty() ) {
1985 lookup["nearest"] = InterpolateArray1D<Double,Float>::nearestNeighbour;
1986 lookup["linear"] = InterpolateArray1D<Double,Float>::linear;
1987 lookup["cubic"] = InterpolateArray1D<Double,Float>::cubic;
1988 lookup["spline"] = InterpolateArray1D<Double,Float>::spline;
1989 }
1990
1991 STMath::imap::const_iterator iter = lookup.find(in);
1992
1993 if ( lookup.end() == iter ) {
1994 std::string message = in;
1995 message += " is not a valid interpolation mode";
1996 throw(AipsError(message));
1997 }
1998 return iter->second;
1999}
2000
2001WeightType STMath::stringToWeight(const std::string& in)
2002{
2003 static std::map<std::string, WeightType> lookup;
2004
2005 // initialize the lookup table if necessary
2006 if ( lookup.empty() ) {
2007 lookup["NONE"] = asap::W_NONE;
2008 lookup["TINT"] = asap::W_TINT;
2009 lookup["TINTSYS"] = asap::W_TINTSYS;
2010 lookup["TSYS"] = asap::W_TSYS;
2011 lookup["VAR"] = asap::W_VAR;
2012 }
2013
2014 std::map<std::string, WeightType>::const_iterator iter = lookup.find(in);
2015
2016 if ( lookup.end() == iter ) {
2017 std::string message = in;
2018 message += " is not a valid weighting mode";
2019 throw(AipsError(message));
2020 }
2021 return iter->second;
2022}
2023
2024CountedPtr< Scantable > STMath::gainElevation( const CountedPtr< Scantable >& in,
2025 const vector< float > & coeff,
2026 const std::string & filename,
2027 const std::string& method)
2028{
2029 // Get elevation data from Scantable and convert to degrees
2030 CountedPtr< Scantable > out = getScantable(in, false);
2031 Table& tab = out->table();
2032 ROScalarColumn<Float> elev(tab, "ELEVATION");
2033 Vector<Float> x = elev.getColumn();
2034 x *= Float(180 / C::pi); // Degrees
2035
2036 Vector<Float> coeffs(coeff);
2037 const uInt nc = coeffs.nelements();
2038 if ( filename.length() > 0 && nc > 0 ) {
2039 throw(AipsError("You must choose either polynomial coefficients or an ascii file, not both"));
2040 }
2041
2042 // Correct
2043 if ( nc > 0 || filename.length() == 0 ) {
2044 // Find instrument
2045 Bool throwit = True;
2046 Instrument inst =
2047 STAttr::convertInstrument(tab.keywordSet().asString("AntennaName"),
2048 throwit);
2049
2050 // Set polynomial
2051 Polynomial<Float>* ppoly = 0;
2052 Vector<Float> coeff;
2053 String msg;
2054 if ( nc > 0 ) {
2055 ppoly = new Polynomial<Float>(nc-1);
2056 coeff = coeffs;
2057 msg = String("user");
2058 } else {
2059 STAttr sdAttr;
2060 coeff = sdAttr.gainElevationPoly(inst);
2061 ppoly = new Polynomial<Float>(coeff.nelements()-1);
2062 msg = String("built in");
2063 }
2064
2065 if ( coeff.nelements() > 0 ) {
2066 ppoly->setCoefficients(coeff);
2067 } else {
2068 delete ppoly;
2069 throw(AipsError("There is no known gain-elevation polynomial known for this instrument"));
2070 }
2071 ostringstream oss;
2072 oss << "Making polynomial correction with " << msg << " coefficients:" << endl;
2073 oss << " " << coeff;
2074 pushLog(String(oss));
2075 const uInt nrow = tab.nrow();
2076 Vector<Float> factor(nrow);
2077 for ( uInt i=0; i < nrow; ++i ) {
2078 factor[i] = 1.0 / (*ppoly)(x[i]);
2079 }
2080 delete ppoly;
2081 scaleByVector(tab, factor, true);
2082
2083 } else {
2084 // Read and correct
2085 pushLog("Making correction from ascii Table");
2086 scaleFromAsciiTable(tab, filename, method, x, true);
2087 }
2088 return out;
2089}
2090
2091void STMath::scaleFromAsciiTable(Table& in, const std::string& filename,
2092 const std::string& method,
2093 const Vector<Float>& xout, bool dotsys)
2094{
2095
2096// Read gain-elevation ascii file data into a Table.
2097
2098 String formatString;
2099 Table tbl = readAsciiTable(formatString, Table::Memory, filename, "", "", False);
2100 scaleFromTable(in, tbl, method, xout, dotsys);
2101}
2102
2103void STMath::scaleFromTable(Table& in,
2104 const Table& table,
2105 const std::string& method,
2106 const Vector<Float>& xout, bool dotsys)
2107{
2108
2109 ROScalarColumn<Float> geElCol(table, "ELEVATION");
2110 ROScalarColumn<Float> geFacCol(table, "FACTOR");
2111 Vector<Float> xin = geElCol.getColumn();
2112 Vector<Float> yin = geFacCol.getColumn();
2113 Vector<Bool> maskin(xin.nelements(),True);
2114
2115 // Interpolate (and extrapolate) with desired method
2116
2117 InterpolateArray1D<Double,Float>::InterpolationMethod interp = stringToIMethod(method);
2118
2119 Vector<Float> yout;
2120 Vector<Bool> maskout;
2121 InterpolateArray1D<Float,Float>::interpolate(yout, maskout, xout,
2122 xin, yin, maskin, interp,
2123 True, True);
2124
2125 scaleByVector(in, Float(1.0)/yout, dotsys);
2126}
2127
2128void STMath::scaleByVector( Table& in,
2129 const Vector< Float >& factor,
2130 bool dotsys )
2131{
2132 uInt nrow = in.nrow();
2133 if ( factor.nelements() != nrow ) {
2134 throw(AipsError("factors.nelements() != table.nelements()"));
2135 }
2136 ArrayColumn<Float> specCol(in, "SPECTRA");
2137 ArrayColumn<uChar> flagCol(in, "FLAGTRA");
2138 ArrayColumn<Float> tsysCol(in, "TSYS");
2139 for (uInt i=0; i < nrow; ++i) {
2140 MaskedArray<Float> ma = maskedArray(specCol(i), flagCol(i));
2141 ma *= factor[i];
2142 specCol.put(i, ma.getArray());
2143 flagCol.put(i, flagsFromMA(ma));
2144 if ( dotsys ) {
2145 Vector<Float> tsys = tsysCol(i);
2146 tsys *= factor[i];
2147 tsysCol.put(i,tsys);
2148 }
2149 }
2150}
2151
2152CountedPtr< Scantable > STMath::convertFlux( const CountedPtr< Scantable >& in,
2153 float d, float etaap,
2154 float jyperk )
2155{
2156 CountedPtr< Scantable > out = getScantable(in, false);
2157 Table& tab = in->table();
2158 Unit fluxUnit(tab.keywordSet().asString("FluxUnit"));
2159 Unit K(String("K"));
2160 Unit JY(String("Jy"));
2161
2162 bool tokelvin = true;
2163 Double cfac = 1.0;
2164
2165 if ( fluxUnit == JY ) {
2166 pushLog("Converting to K");
2167 Quantum<Double> t(1.0,fluxUnit);
2168 Quantum<Double> t2 = t.get(JY);
2169 cfac = (t2 / t).getValue(); // value to Jy
2170
2171 tokelvin = true;
2172 out->setFluxUnit("K");
2173 } else if ( fluxUnit == K ) {
2174 pushLog("Converting to Jy");
2175 Quantum<Double> t(1.0,fluxUnit);
2176 Quantum<Double> t2 = t.get(K);
2177 cfac = (t2 / t).getValue(); // value to K
2178
2179 tokelvin = false;
2180 out->setFluxUnit("Jy");
2181 } else {
2182 throw(AipsError("Unrecognized brightness units in Table - must be consistent with Jy or K"));
2183 }
2184 // Make sure input values are converted to either Jy or K first...
2185 Float factor = cfac;
2186
2187 // Select method
2188 if (jyperk > 0.0) {
2189 factor *= jyperk;
2190 if ( tokelvin ) factor = 1.0 / jyperk;
2191 ostringstream oss;
2192 oss << "Jy/K = " << jyperk;
2193 pushLog(String(oss));
2194 Vector<Float> factors(tab.nrow(), factor);
2195 scaleByVector(tab,factors, false);
2196 } else if ( etaap > 0.0) {
2197 if (d < 0) {
2198 Instrument inst =
2199 STAttr::convertInstrument(tab.keywordSet().asString("AntennaName"),
2200 True);
2201 STAttr sda;
2202 d = sda.diameter(inst);
2203 }
2204 jyperk = STAttr::findJyPerK(etaap, d);
2205 ostringstream oss;
2206 oss << "Jy/K = " << jyperk;
2207 pushLog(String(oss));
2208 factor *= jyperk;
2209 if ( tokelvin ) {
2210 factor = 1.0 / factor;
2211 }
2212 Vector<Float> factors(tab.nrow(), factor);
2213 scaleByVector(tab, factors, False);
2214 } else {
2215
2216 // OK now we must deal with automatic look up of values.
2217 // We must also deal with the fact that the factors need
2218 // to be computed per IF and may be different and may
2219 // change per integration.
2220
2221 pushLog("Looking up conversion factors");
2222 convertBrightnessUnits(out, tokelvin, cfac);
2223 }
2224
2225 return out;
2226}
2227
2228void STMath::convertBrightnessUnits( CountedPtr<Scantable>& in,
2229 bool tokelvin, float cfac )
2230{
2231 Table& table = in->table();
2232 Instrument inst =
2233 STAttr::convertInstrument(table.keywordSet().asString("AntennaName"), True);
2234 TableIterator iter(table, "FREQ_ID");
2235 STFrequencies stfreqs = in->frequencies();
2236 STAttr sdAtt;
2237 while (!iter.pastEnd()) {
2238 Table tab = iter.table();
2239 ArrayColumn<Float> specCol(tab, "SPECTRA");
2240 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2241 ROScalarColumn<uInt> freqidCol(tab, "FREQ_ID");
2242 MEpoch::ROScalarColumn timeCol(tab, "TIME");
2243
2244 uInt freqid; freqidCol.get(0, freqid);
2245 Vector<Float> tmpspec; specCol.get(0, tmpspec);
2246 // STAttr.JyPerK has a Vector interface... change sometime.
2247 Vector<Float> freqs(1,stfreqs.getRefFreq(freqid, tmpspec.nelements()));
2248 for ( uInt i=0; i<tab.nrow(); ++i) {
2249 Float jyperk = (sdAtt.JyPerK(inst, timeCol(i), freqs))[0];
2250 Float factor = cfac * jyperk;
2251 if ( tokelvin ) factor = Float(1.0) / factor;
2252 MaskedArray<Float> ma = maskedArray(specCol(i), flagCol(i));
2253 ma *= factor;
2254 specCol.put(i, ma.getArray());
2255 flagCol.put(i, flagsFromMA(ma));
2256 }
2257 ++iter;
2258 }
2259}
2260
2261CountedPtr< Scantable > STMath::opacity( const CountedPtr< Scantable > & in,
2262 const std::vector<float>& tau )
2263{
2264 CountedPtr< Scantable > out = getScantable(in, false);
2265
2266 Table outtab = out->table();
2267
2268 const Int ntau = uInt(tau.size());
2269 std::vector<float>::const_iterator tauit = tau.begin();
2270 AlwaysAssert((ntau == 1 || ntau == in->nif() || ntau == in->nif() * in->npol()),
2271 AipsError);
2272 TableIterator iiter(outtab, "IFNO");
2273 while ( !iiter.pastEnd() ) {
2274 Table itab = iiter.table();
2275 TableIterator piter(outtab, "POLNO");
2276 while ( !piter.pastEnd() ) {
2277 Table tab = piter.table();
2278 ROScalarColumn<Float> elev(tab, "ELEVATION");
2279 ArrayColumn<Float> specCol(tab, "SPECTRA");
2280 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2281 ArrayColumn<Float> tsysCol(tab, "TSYS");
2282 for ( uInt i=0; i<tab.nrow(); ++i) {
2283 Float zdist = Float(C::pi_2) - elev(i);
2284 Float factor = exp(*tauit/cos(zdist));
2285 MaskedArray<Float> ma = maskedArray(specCol(i), flagCol(i));
2286 ma *= factor;
2287 specCol.put(i, ma.getArray());
2288 flagCol.put(i, flagsFromMA(ma));
2289 Vector<Float> tsys;
2290 tsysCol.get(i, tsys);
2291 tsys *= factor;
2292 tsysCol.put(i, tsys);
2293 }
2294 if (ntau == in->nif()*in->npol() ) {
2295 tauit++;
2296 }
2297 piter++;
2298 }
2299 if (ntau >= in->nif() ) {
2300 tauit++;
2301 }
2302 iiter++;
2303 }
2304 return out;
2305}
2306
2307CountedPtr< Scantable > STMath::smoothOther( const CountedPtr< Scantable >& in,
2308 const std::string& kernel,
2309 float width, int order)
2310{
2311 CountedPtr< Scantable > out = getScantable(in, false);
2312 Table table = out->table();
2313
2314 TableIterator iter(table, "IFNO");
2315 while (!iter.pastEnd()) {
2316 Table tab = iter.table();
2317 ArrayColumn<Float> specCol(tab, "SPECTRA");
2318 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2319 Vector<Float> spec;
2320 Vector<uChar> flag;
2321 for (uInt i = 0; i < tab.nrow(); ++i) {
2322 specCol.get(i, spec);
2323 flagCol.get(i, flag);
2324 Vector<Bool> mask(flag.nelements());
2325 convertArray(mask, flag);
2326 Vector<Float> specout;
2327 Vector<Bool> maskout;
2328 if (kernel == "hanning") {
2329 mathutil::hanning(specout, maskout, spec, !mask);
2330 convertArray(flag, !maskout);
2331 } else if (kernel == "rmedian") {
2332 mathutil::runningMedian(specout, maskout, spec , mask, width);
2333 convertArray(flag, maskout);
2334 } else if (kernel == "poly") {
2335 mathutil::polyfit(specout, maskout, spec, !mask, width, order);
2336 convertArray(flag, !maskout);
2337 }
2338
2339 for (uInt j = 0; j < flag.nelements(); ++j) {
2340 uChar userFlag = 1 << 7;
2341 if (maskout[j]==True) userFlag = 0 << 7;
2342 flag(j) = userFlag;
2343 }
2344
2345 flagCol.put(i, flag);
2346 specCol.put(i, specout);
2347 }
2348 ++iter;
2349 }
2350 return out;
2351}
2352
2353CountedPtr< Scantable > STMath::smooth( const CountedPtr< Scantable >& in,
2354 const std::string& kernel, float width,
2355 int order)
2356{
2357 if (kernel == "rmedian" || kernel == "hanning" || kernel == "poly") {
2358 return smoothOther(in, kernel, width, order);
2359 }
2360 CountedPtr< Scantable > out = getScantable(in, false);
2361 Table& table = out->table();
2362 VectorKernel::KernelTypes type = VectorKernel::toKernelType(kernel);
2363 // same IFNO should have same no of channels
2364 // this saves overhead
2365 TableIterator iter(table, "IFNO");
2366 while (!iter.pastEnd()) {
2367 Table tab = iter.table();
2368 ArrayColumn<Float> specCol(tab, "SPECTRA");
2369 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2370 Vector<Float> tmpspec; specCol.get(0, tmpspec);
2371 uInt nchan = tmpspec.nelements();
2372 Vector<Float> kvec = VectorKernel::make(type, width, nchan, True, False);
2373 Convolver<Float> conv(kvec, IPosition(1,nchan));
2374 Vector<Float> spec;
2375 Vector<uChar> flag;
2376 for ( uInt i=0; i<tab.nrow(); ++i) {
2377 specCol.get(i, spec);
2378 flagCol.get(i, flag);
2379 Vector<Bool> mask(flag.nelements());
2380 convertArray(mask, flag);
2381 Vector<Float> specout;
2382 mathutil::replaceMaskByZero(specout, mask);
2383 conv.linearConv(specout, spec);
2384 specCol.put(i, specout);
2385 }
2386 ++iter;
2387 }
2388 return out;
2389}
2390
2391CountedPtr< Scantable >
2392 STMath::merge( const std::vector< CountedPtr < Scantable > >& in )
2393{
2394 if ( in.size() < 2 ) {
2395 throw(AipsError("Need at least two scantables to perform a merge."));
2396 }
2397 std::vector<CountedPtr < Scantable > >::const_iterator it = in.begin();
2398 bool insitu = insitu_;
2399 setInsitu(false);
2400 CountedPtr< Scantable > out = getScantable(*it, false);
2401 setInsitu(insitu);
2402 Table& tout = out->table();
2403 ScalarColumn<uInt> freqidcol(tout,"FREQ_ID"), molidcol(tout, "MOLECULE_ID");
2404 ScalarColumn<uInt> scannocol(tout,"SCANNO"), focusidcol(tout,"FOCUS_ID");
2405 // Renumber SCANNO to be 0-based
2406 Vector<uInt> scannos = scannocol.getColumn();
2407 uInt offset = min(scannos);
2408 scannos -= offset;
2409 scannocol.putColumn(scannos);
2410 uInt newscanno = max(scannos)+1;
2411 ++it;
2412 while ( it != in.end() ){
2413 if ( ! (*it)->conformant(*out) ) {
2414 // non conformant.
2415 //pushLog(String("Warning: Can't merge scantables as header info differs."));
2416 LogIO os( LogOrigin( "STMath", "merge()", WHERE ) ) ;
2417 os << LogIO::SEVERE << "Can't merge scantables as header informations (any one of AntennaName, Equinox, and FluxUnit) differ." << LogIO::EXCEPTION ;
2418 }
2419 out->appendToHistoryTable((*it)->history());
2420 const Table& tab = (*it)->table();
2421 TableIterator scanit(tab, "SCANNO");
2422 while (!scanit.pastEnd()) {
2423 TableIterator freqit(scanit.table(), "FREQ_ID");
2424 while ( !freqit.pastEnd() ) {
2425 Table thetab = freqit.table();
2426 uInt nrow = tout.nrow();
2427 tout.addRow(thetab.nrow());
2428 TableCopy::copyRows(tout, thetab, nrow, 0, thetab.nrow());
2429 ROTableRow row(thetab);
2430 for ( uInt i=0; i<thetab.nrow(); ++i) {
2431 uInt k = nrow+i;
2432 scannocol.put(k, newscanno);
2433 const TableRecord& rec = row.get(i);
2434 Double rv,rp,inc;
2435 (*it)->frequencies().getEntry(rp, rv, inc, rec.asuInt("FREQ_ID"));
2436 uInt id;
2437 id = out->frequencies().addEntry(rp, rv, inc);
2438 freqidcol.put(k,id);
2439 //String name,fname;Double rf;
2440 Vector<String> name,fname;Vector<Double> rf;
2441 (*it)->molecules().getEntry(rf, name, fname, rec.asuInt("MOLECULE_ID"));
2442 id = out->molecules().addEntry(rf, name, fname);
2443 molidcol.put(k, id);
2444 Float fpa,frot,fax,ftan,fhand,fmount,fuser, fxy, fxyp;
2445 (*it)->focus().getEntry(fpa, fax, ftan, frot, fhand,
2446 fmount,fuser, fxy, fxyp,
2447 rec.asuInt("FOCUS_ID"));
2448 id = out->focus().addEntry(fpa, fax, ftan, frot, fhand,
2449 fmount,fuser, fxy, fxyp);
2450 focusidcol.put(k, id);
2451 }
2452 ++freqit;
2453 }
2454 ++newscanno;
2455 ++scanit;
2456 }
2457 ++it;
2458 }
2459 return out;
2460}
2461
2462CountedPtr< Scantable >
2463 STMath::invertPhase( const CountedPtr < Scantable >& in )
2464{
2465 return applyToPol(in, &STPol::invertPhase, Float(0.0));
2466}
2467
2468CountedPtr< Scantable >
2469 STMath::rotateXYPhase( const CountedPtr < Scantable >& in, float phase )
2470{
2471 return applyToPol(in, &STPol::rotatePhase, Float(phase));
2472}
2473
2474CountedPtr< Scantable >
2475 STMath::rotateLinPolPhase( const CountedPtr < Scantable >& in, float phase )
2476{
2477 return applyToPol(in, &STPol::rotateLinPolPhase, Float(phase));
2478}
2479
2480CountedPtr< Scantable > STMath::applyToPol( const CountedPtr<Scantable>& in,
2481 STPol::polOperation fptr,
2482 Float phase )
2483{
2484 CountedPtr< Scantable > out = getScantable(in, false);
2485 Table& tout = out->table();
2486 Block<String> cols(4);
2487 cols[0] = String("SCANNO");
2488 cols[1] = String("BEAMNO");
2489 cols[2] = String("IFNO");
2490 cols[3] = String("CYCLENO");
2491 TableIterator iter(tout, cols);
2492 CountedPtr<STPol> stpol = STPol::getPolClass(out->factories_,
2493 out->getPolType() );
2494 while (!iter.pastEnd()) {
2495 Table t = iter.table();
2496 ArrayColumn<Float> speccol(t, "SPECTRA");
2497 ScalarColumn<uInt> focidcol(t, "FOCUS_ID");
2498 Matrix<Float> pols(speccol.getColumn());
2499 try {
2500 stpol->setSpectra(pols);
2501 Float fang,fhand;
2502 fang = in->focusTable_.getTotalAngle(focidcol(0));
2503 fhand = in->focusTable_.getFeedHand(focidcol(0));
2504 stpol->setPhaseCorrections(fang, fhand);
2505 // use a member function pointer in STPol. This only works on
2506 // the STPol pointer itself, not the Counted Pointer so
2507 // derefernce it.
2508 (&(*(stpol))->*fptr)(phase);
2509 speccol.putColumn(stpol->getSpectra());
2510 } catch (AipsError& e) {
2511 //delete stpol;stpol=0;
2512 throw(e);
2513 }
2514 ++iter;
2515 }
2516 //delete stpol;stpol=0;
2517 return out;
2518}
2519
2520CountedPtr< Scantable >
2521 STMath::swapPolarisations( const CountedPtr< Scantable > & in )
2522{
2523 CountedPtr< Scantable > out = getScantable(in, false);
2524 Table& tout = out->table();
2525 Table t0 = tout(tout.col("POLNO") == 0);
2526 Table t1 = tout(tout.col("POLNO") == 1);
2527 if ( t0.nrow() != t1.nrow() )
2528 throw(AipsError("Inconsistent number of polarisations"));
2529 ArrayColumn<Float> speccol0(t0, "SPECTRA");
2530 ArrayColumn<uChar> flagcol0(t0, "FLAGTRA");
2531 ArrayColumn<Float> speccol1(t1, "SPECTRA");
2532 ArrayColumn<uChar> flagcol1(t1, "FLAGTRA");
2533 Matrix<Float> s0 = speccol0.getColumn();
2534 Matrix<uChar> f0 = flagcol0.getColumn();
2535 speccol0.putColumn(speccol1.getColumn());
2536 flagcol0.putColumn(flagcol1.getColumn());
2537 speccol1.putColumn(s0);
2538 flagcol1.putColumn(f0);
2539 return out;
2540}
2541
2542CountedPtr< Scantable >
2543 STMath::averagePolarisations( const CountedPtr< Scantable > & in,
2544 const std::vector<bool>& mask,
2545 const std::string& weight )
2546{
2547 if (in->npol() < 2 )
2548 throw(AipsError("averagePolarisations can only be applied to two or more"
2549 "polarisations"));
2550 bool insitu = insitu_;
2551 setInsitu(false);
2552 CountedPtr< Scantable > pols = getScantable(in, true);
2553 setInsitu(insitu);
2554 Table& tout = pols->table();
2555 std::string taql = "SELECT FROM $1 WHERE POLNO IN [0,1]";
2556 Table tab = tableCommand(taql, in->table());
2557 if (tab.nrow() == 0 )
2558 throw(AipsError("Could not find any rows with POLNO==0 and POLNO==1"));
2559 TableCopy::copyRows(tout, tab);
2560 TableVector<uInt> vec(tout, "POLNO");
2561 vec = 0;
2562 pols->table_.rwKeywordSet().define("nPol", Int(1));
2563 pols->table_.rwKeywordSet().define("POLTYPE", String("stokes"));
2564 //pols->table_.rwKeywordSet().define("POLTYPE", in->getPolType());
2565 std::vector<CountedPtr<Scantable> > vpols;
2566 vpols.push_back(pols);
2567 CountedPtr< Scantable > out = average(vpols, mask, weight, "SCAN");
2568 return out;
2569}
2570
2571CountedPtr< Scantable >
2572 STMath::averageBeams( const CountedPtr< Scantable > & in,
2573 const std::vector<bool>& mask,
2574 const std::string& weight )
2575{
2576 bool insitu = insitu_;
2577 setInsitu(false);
2578 CountedPtr< Scantable > beams = getScantable(in, false);
2579 setInsitu(insitu);
2580 Table& tout = beams->table();
2581 // give all rows the same BEAMNO
2582 TableVector<uInt> vec(tout, "BEAMNO");
2583 vec = 0;
2584 beams->table_.rwKeywordSet().define("nBeam", Int(1));
2585 std::vector<CountedPtr<Scantable> > vbeams;
2586 vbeams.push_back(beams);
2587 CountedPtr< Scantable > out = average(vbeams, mask, weight, "SCAN");
2588 return out;
2589}
2590
2591
2592CountedPtr< Scantable >
2593 asap::STMath::frequencyAlign( const CountedPtr< Scantable > & in,
2594 const std::string & refTime,
2595 const std::string & method)
2596{
2597 // clone as this is not working insitu
2598 bool insitu = insitu_;
2599 setInsitu(false);
2600 CountedPtr< Scantable > out = getScantable(in, false);
2601 setInsitu(insitu);
2602 Table& tout = out->table();
2603 // Get reference Epoch to time of first row or given String
2604 Unit DAY(String("d"));
2605 MEpoch::Ref epochRef(in->getTimeReference());
2606 MEpoch refEpoch;
2607 if (refTime.length()>0) {
2608 Quantum<Double> qt;
2609 if (MVTime::read(qt,refTime)) {
2610 MVEpoch mv(qt);
2611 refEpoch = MEpoch(mv, epochRef);
2612 } else {
2613 throw(AipsError("Invalid format for Epoch string"));
2614 }
2615 } else {
2616 refEpoch = in->timeCol_(0);
2617 }
2618 MPosition refPos = in->getAntennaPosition();
2619
2620 InterpolateArray1D<Double,Float>::InterpolationMethod interp = stringToIMethod(method);
2621 /*
2622 // Comment from MV.
2623 // the following code has been commented out because different FREQ_IDs have to be aligned together even
2624 // if the frame doesn't change. So far, lack of this check didn't cause any problems.
2625 // test if user frame is different to base frame
2626 if ( in->frequencies().getFrameString(true)
2627 == in->frequencies().getFrameString(false) ) {
2628 throw(AipsError("Can't convert as no output frame has been set"
2629 " (use set_freqframe) or it is aligned already."));
2630 }
2631 */
2632 MFrequency::Types system = in->frequencies().getFrame();
2633 MVTime mvt(refEpoch.getValue());
2634 String epochout = mvt.string(MVTime::YMD) + String(" (") + refEpoch.getRefString() + String(")");
2635 ostringstream oss;
2636 oss << "Aligned at reference Epoch " << epochout
2637 << " in frame " << MFrequency::showType(system);
2638 pushLog(String(oss));
2639 // set up the iterator
2640 Block<String> cols(4);
2641 // select by constant direction
2642 cols[0] = String("SRCNAME");
2643 cols[1] = String("BEAMNO");
2644 // select by IF ( no of channels varies over this )
2645 cols[2] = String("IFNO");
2646 // select by restfrequency
2647 cols[3] = String("MOLECULE_ID");
2648 TableIterator iter(tout, cols);
2649 while ( !iter.pastEnd() ) {
2650 Table t = iter.table();
2651 MDirection::ROScalarColumn dirCol(t, "DIRECTION");
2652 TableIterator fiter(t, "FREQ_ID");
2653 // determine nchan from the first row. This should work as
2654 // we are iterating over BEAMNO and IFNO // we should have constant direction
2655
2656 ROArrayColumn<Float> sCol(t, "SPECTRA");
2657 const MDirection direction = dirCol(0);
2658 const uInt nchan = sCol(0).nelements();
2659
2660 // skip operations if there is nothing to align
2661 if (fiter.pastEnd()) {
2662 continue;
2663 }
2664
2665 Table ftab = fiter.table();
2666 // align all frequency ids with respect to the first encountered id
2667 ScalarColumn<uInt> freqidCol(ftab, "FREQ_ID");
2668 // get the SpectralCoordinate for the freqid, which we are iterating over
2669 SpectralCoordinate sC = in->frequencies().getSpectralCoordinate(freqidCol(0));
2670 FrequencyAligner<Float> fa( sC, nchan, refEpoch,
2671 direction, refPos, system );
2672 // realign the SpectralCoordinate and put into the output Scantable
2673 Vector<String> units(1);
2674 units = String("Hz");
2675 Bool linear=True;
2676 SpectralCoordinate sc2 = fa.alignedSpectralCoordinate(linear);
2677 sc2.setWorldAxisUnits(units);
2678 const uInt id = out->frequencies().addEntry(sc2.referencePixel()[0],
2679 sc2.referenceValue()[0],
2680 sc2.increment()[0]);
2681 while ( !fiter.pastEnd() ) {
2682 ftab = fiter.table();
2683 // spectral coordinate for the current FREQ_ID
2684 ScalarColumn<uInt> freqidCol2(ftab, "FREQ_ID");
2685 sC = in->frequencies().getSpectralCoordinate(freqidCol2(0));
2686 // create the "global" abcissa for alignment with same FREQ_ID
2687 Vector<Double> abc(nchan);
2688 for (uInt i=0; i<nchan; i++) {
2689 Double w;
2690 sC.toWorld(w,Double(i));
2691 abc[i] = w;
2692 }
2693 TableVector<uInt> tvec(ftab, "FREQ_ID");
2694 // assign new frequency id to all rows
2695 tvec = id;
2696 // cache abcissa for same time stamps, so iterate over those
2697 TableIterator timeiter(ftab, "TIME");
2698 while ( !timeiter.pastEnd() ) {
2699 Table tab = timeiter.table();
2700 ArrayColumn<Float> specCol(tab, "SPECTRA");
2701 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2702 MEpoch::ROScalarColumn timeCol(tab, "TIME");
2703 // use align abcissa cache after the first row
2704 // these rows should be just be POLNO
2705 bool first = true;
2706 for (int i=0; i<int(tab.nrow()); ++i) {
2707 // input values
2708 Vector<uChar> flag = flagCol(i);
2709 Vector<Bool> mask(flag.shape());
2710 Vector<Float> specOut, spec;
2711 spec = specCol(i);
2712 Vector<Bool> maskOut;Vector<uChar> flagOut;
2713 convertArray(mask, flag);
2714 // alignment
2715 Bool ok = fa.align(specOut, maskOut, abc, spec,
2716 mask, timeCol(i), !first,
2717 interp, False);
2718 (void) ok; // unused stop compiler nagging
2719 // back into scantable
2720 flagOut.resize(maskOut.nelements());
2721 convertArray(flagOut, maskOut);
2722 flagCol.put(i, flagOut);
2723 specCol.put(i, specOut);
2724 // start abcissa caching
2725 first = false;
2726 }
2727 // next timestamp
2728 ++timeiter;
2729 }
2730 // next FREQ_ID
2731 ++fiter;
2732 }
2733 // next aligner
2734 ++iter;
2735 }
2736 // set this afterwards to ensure we are doing insitu correctly.
2737 out->frequencies().setFrame(system, true);
2738 return out;
2739}
2740
2741CountedPtr<Scantable>
2742 asap::STMath::convertPolarisation( const CountedPtr<Scantable>& in,
2743 const std::string & newtype )
2744{
2745 if (in->npol() != 2 && in->npol() != 4)
2746 throw(AipsError("Can only convert two or four polarisations."));
2747 if ( in->getPolType() == newtype )
2748 throw(AipsError("No need to convert."));
2749 if ( ! in->selector_.empty() )
2750 throw(AipsError("Can only convert whole scantable. Unset the selection."));
2751 bool insitu = insitu_;
2752 setInsitu(false);
2753 CountedPtr< Scantable > out = getScantable(in, true);
2754 setInsitu(insitu);
2755 Table& tout = out->table();
2756 tout.rwKeywordSet().define("POLTYPE", String(newtype));
2757
2758 Block<String> cols(4);
2759 cols[0] = "SCANNO";
2760 cols[1] = "CYCLENO";
2761 cols[2] = "BEAMNO";
2762 cols[3] = "IFNO";
2763 TableIterator it(in->originalTable_, cols);
2764 String basetype = in->getPolType();
2765 STPol* stpol = STPol::getPolClass(in->factories_, basetype);
2766 try {
2767 while ( !it.pastEnd() ) {
2768 Table tab = it.table();
2769 uInt row = tab.rowNumbers()[0];
2770 stpol->setSpectra(in->getPolMatrix(row));
2771 Float fang,fhand;
2772 fang = in->focusTable_.getTotalAngle(in->mfocusidCol_(row));
2773 fhand = in->focusTable_.getFeedHand(in->mfocusidCol_(row));
2774 stpol->setPhaseCorrections(fang, fhand);
2775 Int npolout = 0;
2776 for (uInt i=0; i<tab.nrow(); ++i) {
2777 Vector<Float> outvec = stpol->getSpectrum(i, newtype);
2778 if ( outvec.nelements() > 0 ) {
2779 tout.addRow();
2780 TableCopy::copyRows(tout, tab, tout.nrow()-1, 0, 1);
2781 ArrayColumn<Float> sCol(tout,"SPECTRA");
2782 ScalarColumn<uInt> pCol(tout,"POLNO");
2783 sCol.put(tout.nrow()-1 ,outvec);
2784 pCol.put(tout.nrow()-1 ,uInt(npolout));
2785 npolout++;
2786 }
2787 }
2788 tout.rwKeywordSet().define("nPol", npolout);
2789 ++it;
2790 }
2791 } catch (AipsError& e) {
2792 delete stpol;
2793 throw(e);
2794 }
2795 delete stpol;
2796 return out;
2797}
2798
2799CountedPtr< Scantable >
2800 asap::STMath::mxExtract( const CountedPtr< Scantable > & in,
2801 const std::string & scantype )
2802{
2803 bool insitu = insitu_;
2804 setInsitu(false);
2805 CountedPtr< Scantable > out = getScantable(in, true);
2806 setInsitu(insitu);
2807 Table& tout = out->table();
2808 std::string taql = "SELECT FROM $1 WHERE BEAMNO != REFBEAMNO";
2809 if (scantype == "on") {
2810 taql = "SELECT FROM $1 WHERE BEAMNO == REFBEAMNO";
2811 }
2812 Table tab = tableCommand(taql, in->table());
2813 TableCopy::copyRows(tout, tab);
2814 if (scantype == "on") {
2815 // re-index SCANNO to 0
2816 TableVector<uInt> vec(tout, "SCANNO");
2817 vec = 0;
2818 }
2819 return out;
2820}
2821
2822std::vector<float>
2823 asap::STMath::fft( const casa::CountedPtr< Scantable > & in,
2824 const std::vector<int>& whichrow,
2825 bool getRealImag )
2826{
2827 std::vector<float> res;
2828 Table tab = in->table();
2829 ArrayColumn<Float> specCol(tab, "SPECTRA");
2830 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2831 FFTServer<Float,Complex> ffts;
2832
2833 if (whichrow.size() < 1) { // for all rows (by default)
2834 int nrow = int(tab.nrow());
2835 for (int i = 0; i < nrow; ++i) {
2836 Vector<Float> spec = specCol(i);
2837 Vector<uChar> flag = flagCol(i);
2838 doFFT(res, ffts, getRealImag, spec, flag);
2839 }
2840 } else { // for specified rows
2841 for (uInt i = 0; i < whichrow.size(); ++i) {
2842 Vector<Float> spec = specCol(whichrow[i]);
2843 Vector<uChar> flag = flagCol(whichrow[i]);
2844 doFFT(res, ffts, getRealImag, spec, flag);
2845 }
2846 }
2847
2848 return res;
2849}
2850
2851void asap::STMath::doFFT( std::vector<float>& out,
2852 FFTServer<Float,Complex>& ffts,
2853 bool getRealImag,
2854 Vector<Float>& spec,
2855 Vector<uChar>& flag )
2856{
2857 doZeroOrderInterpolation(spec, flag);
2858
2859 Vector<Complex> fftout;
2860 ffts.fft0(fftout, spec);
2861
2862 float norm = float(2.0/double(spec.size()));
2863 if (getRealImag) {
2864 for (uInt j = 0; j < fftout.size(); ++j) {
2865 out.push_back(real(fftout[j])*norm);
2866 out.push_back(imag(fftout[j])*norm);
2867 }
2868 } else {
2869 for (uInt j = 0; j < fftout.size(); ++j) {
2870 out.push_back(abs(fftout[j])*norm);
2871 out.push_back(arg(fftout[j]));
2872 }
2873 }
2874
2875}
2876
2877void asap::STMath::doZeroOrderInterpolation( Vector<Float>& spec,
2878 Vector<uChar>& flag )
2879{
2880 int fstart = -1;
2881 int fend = -1;
2882 for (uInt i = 0; i < flag.nelements(); ++i) {
2883 if (flag[i] > 0) {
2884 fstart = i;
2885 while (flag[i] > 0 && i < flag.nelements()) {
2886 fend = i;
2887 i++;
2888 }
2889 }
2890
2891 // execute interpolation as the following criteria:
2892 // (1) for a masked region inside the spectrum, replace the spectral
2893 // values with the mean of those at the two channels just outside
2894 // the both edges of the masked region.
2895 // (2) for a masked region at the spectral edge, replace the values
2896 // with the one at the nearest non-masked channel.
2897 // (ZOH, but bilateral)
2898 Float interp = 0.0;
2899 if (fstart-1 > 0) {
2900 interp = spec[fstart-1];
2901 if (fend+1 < Int(spec.nelements())) {
2902 interp = (interp + spec[fend+1]) / 2.0;
2903 }
2904 } else {
2905 interp = spec[fend+1];
2906 }
2907 if (fstart > -1 && fend > -1) {
2908 for (int j = fstart; j <= fend; ++j) {
2909 spec[j] = interp;
2910 }
2911 }
2912
2913 fstart = -1;
2914 fend = -1;
2915 }
2916}
2917
2918CountedPtr<Scantable>
2919 asap::STMath::lagFlag( const CountedPtr<Scantable>& in,
2920 double start, double end,
2921 const std::string& mode )
2922{
2923 CountedPtr<Scantable> out = getScantable(in, false);
2924 Table& tout = out->table();
2925 TableIterator iter(tout, "FREQ_ID");
2926 FFTServer<Float,Complex> ffts;
2927
2928 while ( !iter.pastEnd() ) {
2929 Table tab = iter.table();
2930 Double rp,rv,inc;
2931 ROTableRow row(tab);
2932 const TableRecord& rec = row.get(0);
2933 uInt freqid = rec.asuInt("FREQ_ID");
2934 out->frequencies().getEntry(rp, rv, inc, freqid);
2935 ArrayColumn<Float> specCol(tab, "SPECTRA");
2936 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2937
2938 for (int i=0; i<int(tab.nrow()); ++i) {
2939 Vector<Float> spec = specCol(i);
2940 Vector<uChar> flag = flagCol(i);
2941 doZeroOrderInterpolation(spec, flag);
2942
2943 Vector<Complex> lags;
2944 ffts.fft0(lags, spec);
2945
2946 Int lag0(start+0.5);
2947 Int lag1(end+0.5);
2948 if (mode == "frequency") {
2949 lag0 = Int(spec.nelements()*abs(inc)/(start)+0.5);
2950 lag1 = Int(spec.nelements()*abs(inc)/(end)+0.5);
2951 }
2952 Int lstart = max(0, lag0);
2953 Int lend = min(Int(lags.nelements()-1), lag1);
2954 if (lstart == lend) {
2955 lags[lstart] = Complex(0.0);
2956 } else {
2957 if (lstart > lend) {
2958 Int tmp = lend;
2959 lend = lstart;
2960 lstart = tmp;
2961 }
2962 for (int j=lstart; j <=lend ;++j) {
2963 lags[j] = Complex(0.0);
2964 }
2965 }
2966
2967 ffts.fft0(spec, lags);
2968
2969 specCol.put(i, spec);
2970 }
2971 ++iter;
2972 }
2973 return out;
2974}
2975
2976// Averaging spectra with different channel/resolution
2977CountedPtr<Scantable>
2978STMath::new_average( const std::vector<CountedPtr<Scantable> >& in,
2979 const bool& compel,
2980 const std::vector<bool>& mask,
2981 const std::string& weight,
2982 const std::string& avmode )
2983 throw ( casa::AipsError )
2984{
2985 LogIO os( LogOrigin( "STMath", "new_average()", WHERE ) ) ;
2986 if ( avmode == "SCAN" && in.size() != 1 )
2987 throw(AipsError("Can't perform 'SCAN' averaging on multiple tables.\n"
2988 "Use merge first."));
2989
2990 // check if OTF observation
2991 String obstype = in[0]->getHeader().obstype ;
2992 Double tol = 0.0 ;
2993 if ( obstype.find( "OTF" ) != String::npos ) {
2994 tol = TOL_OTF ;
2995 }
2996 else {
2997 tol = TOL_POINT ;
2998 }
2999
3000 CountedPtr<Scantable> out ; // processed result
3001 if ( compel ) {
3002 std::vector< CountedPtr<Scantable> > newin ; // input for average process
3003 uInt insize = in.size() ; // number of input scantables
3004
3005 // TEST: do normal average in each table before IF grouping
3006 os << "Do preliminary averaging" << LogIO::POST ;
3007 vector< CountedPtr<Scantable> > tmpin( insize ) ;
3008 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3009 vector< CountedPtr<Scantable> > v( 1, in[itable] ) ;
3010 tmpin[itable] = average( v, mask, weight, avmode ) ;
3011 }
3012
3013 // warning
3014 os << "Average spectra with different spectral resolution" << LogIO::POST ;
3015
3016 // temporarily set coordinfo
3017 vector<string> oldinfo( insize ) ;
3018 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3019 vector<string> coordinfo = in[itable]->getCoordInfo() ;
3020 oldinfo[itable] = coordinfo[0] ;
3021 coordinfo[0] = "Hz" ;
3022 tmpin[itable]->setCoordInfo( coordinfo ) ;
3023 }
3024
3025 // columns
3026 ScalarColumn<uInt> freqIDCol ;
3027 ScalarColumn<uInt> ifnoCol ;
3028 ScalarColumn<uInt> scannoCol ;
3029
3030
3031 // check IF frequency coverage
3032 // freqid: list of FREQ_ID, which is used, in each table
3033 // iffreq: list of minimum and maximum frequency for each FREQ_ID in
3034 // each table
3035 // freqid[insize][numIF]
3036 // freqid: [[id00, id01, ...],
3037 // [id10, id11, ...],
3038 // ...
3039 // [idn0, idn1, ...]]
3040 // iffreq[insize][numIF*2]
3041 // iffreq: [[min_id00, max_id00, min_id01, max_id01, ...],
3042 // [min_id10, max_id10, min_id11, max_id11, ...],
3043 // ...
3044 // [min_idn0, max_idn0, min_idn1, max_idn1, ...]]
3045 //os << "Check IF settings in each table" << LogIO::POST ;
3046 vector< vector<uInt> > freqid( insize );
3047 vector< vector<double> > iffreq( insize ) ;
3048 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3049 uInt rows = tmpin[itable]->nrow() ;
3050 uInt freqnrows = tmpin[itable]->frequencies().table().nrow() ;
3051 for ( uInt irow = 0 ; irow < rows ; irow++ ) {
3052 if ( freqid[itable].size() == freqnrows ) {
3053 break ;
3054 }
3055 else {
3056 freqIDCol.attach( tmpin[itable]->table(), "FREQ_ID" ) ;
3057 ifnoCol.attach( tmpin[itable]->table(), "IFNO" ) ;
3058 uInt id = freqIDCol( irow ) ;
3059 if ( freqid[itable].size() == 0 || count( freqid[itable].begin(), freqid[itable].end(), id ) == 0 ) {
3060 //os << "itable = " << itable << ": IF " << id << " is included in the list" << LogIO::POST ;
3061 vector<double> abcissa = tmpin[itable]->getAbcissa( irow ) ;
3062 freqid[itable].push_back( id ) ;
3063 iffreq[itable].push_back( abcissa[0] - 0.5 * ( abcissa[1] - abcissa[0] ) ) ;
3064 iffreq[itable].push_back( abcissa[abcissa.size()-1] + 0.5 * ( abcissa[1] - abcissa[0] ) ) ;
3065 }
3066 }
3067 }
3068 }
3069
3070 // debug
3071 //os << "IF settings summary:" << endl ;
3072 //for ( uInt i = 0 ; i < freqid.size() ; i++ ) {
3073 //os << " Table" << i << endl ;
3074 //for ( uInt j = 0 ; j < freqid[i].size() ; j++ ) {
3075 //os << " id = " << freqid[i][j] << " (min,max) = (" << iffreq[i][2*j] << "," << iffreq[i][2*j+1] << ")" << endl ;
3076 //}
3077 //}
3078 //os << endl ;
3079 //os.post() ;
3080
3081 // IF grouping based on their frequency coverage
3082 // ifgrp: list of table index and FREQ_ID for all members in each IF group
3083 // ifgfreq: list of minimum and maximum frequency in each IF group
3084 // ifgrp[numgrp][nummember*2]
3085 // ifgrp: [[table00, freqrow00, table01, freqrow01, ...],
3086 // [table10, freqrow10, table11, freqrow11, ...],
3087 // ...
3088 // [tablen0, freqrown0, tablen1, freqrown1, ...]]
3089 // ifgfreq[numgrp*2]
3090 // ifgfreq: [min0_grp0, max0_grp0, min1_grp1, max1_grp1, ...]
3091 //os << "IF grouping based on their frequency coverage" << LogIO::POST ;
3092 vector< vector<uInt> > ifgrp ;
3093 vector<double> ifgfreq ;
3094
3095 // parameter for IF grouping
3096 // groupmode = OR retrieve all region
3097 // AND only retrieve overlaped region
3098 //string groupmode = "AND" ;
3099 string groupmode = "OR" ;
3100 uInt sizecr = 0 ;
3101 if ( groupmode == "AND" )
3102 sizecr = 2 ;
3103 else if ( groupmode == "OR" )
3104 sizecr = 0 ;
3105
3106 vector<double> sortedfreq ;
3107 for ( uInt i = 0 ; i < iffreq.size() ; i++ ) {
3108 for ( uInt j = 0 ; j < iffreq[i].size() ; j++ ) {
3109 if ( count( sortedfreq.begin(), sortedfreq.end(), iffreq[i][j] ) == 0 )
3110 sortedfreq.push_back( iffreq[i][j] ) ;
3111 }
3112 }
3113 sort( sortedfreq.begin(), sortedfreq.end() ) ;
3114 for ( vector<double>::iterator i = sortedfreq.begin() ; i != sortedfreq.end()-1 ; i++ ) {
3115 ifgfreq.push_back( *i ) ;
3116 ifgfreq.push_back( *(i+1) ) ;
3117 }
3118 ifgrp.resize( ifgfreq.size()/2 ) ;
3119 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3120 for ( uInt iif = 0 ; iif < freqid[itable].size() ; iif++ ) {
3121 double range0 = iffreq[itable][2*iif] ;
3122 double range1 = iffreq[itable][2*iif+1] ;
3123 for ( uInt j = 0 ; j < ifgrp.size() ; j++ ) {
3124 double fmin = max( range0, ifgfreq[2*j] ) ;
3125 double fmax = min( range1, ifgfreq[2*j+1] ) ;
3126 if ( fmin < fmax ) {
3127 ifgrp[j].push_back( itable ) ;
3128 ifgrp[j].push_back( freqid[itable][iif] ) ;
3129 }
3130 }
3131 }
3132 }
3133 vector< vector<uInt> >::iterator fiter = ifgrp.begin() ;
3134 vector<double>::iterator giter = ifgfreq.begin() ;
3135 while( fiter != ifgrp.end() ) {
3136 if ( fiter->size() <= sizecr ) {
3137 fiter = ifgrp.erase( fiter ) ;
3138 giter = ifgfreq.erase( giter ) ;
3139 giter = ifgfreq.erase( giter ) ;
3140 }
3141 else {
3142 fiter++ ;
3143 advance( giter, 2 ) ;
3144 }
3145 }
3146
3147 // Grouping continuous IF groups (without frequency gap)
3148 // freqgrp: list of IF group indexes in each frequency group
3149 // freqrange: list of minimum and maximum frequency in each frequency group
3150 // freqgrp[numgrp][nummember]
3151 // freqgrp: [[ifgrp00, ifgrp01, ifgrp02, ...],
3152 // [ifgrp10, ifgrp11, ifgrp12, ...],
3153 // ...
3154 // [ifgrpn0, ifgrpn1, ifgrpn2, ...]]
3155 // freqrange[numgrp*2]
3156 // freqrange: [min_grp0, max_grp0, min_grp1, max_grp1, ...]
3157 vector< vector<uInt> > freqgrp ;
3158 double freqrange = 0.0 ;
3159 uInt grpnum = 0 ;
3160 for ( uInt i = 0 ; i < ifgrp.size() ; i++ ) {
3161 // Assumed that ifgfreq was sorted
3162 if ( grpnum != 0 && freqrange == ifgfreq[2*i] ) {
3163 freqgrp[grpnum-1].push_back( i ) ;
3164 }
3165 else {
3166 vector<uInt> grp0( 1, i ) ;
3167 freqgrp.push_back( grp0 ) ;
3168 grpnum++ ;
3169 }
3170 freqrange = ifgfreq[2*i+1] ;
3171 }
3172
3173
3174 // print IF groups
3175 ostringstream oss ;
3176 oss << "IF Group summary: " << endl ;
3177 oss << " GROUP_ID [FREQ_MIN, FREQ_MAX]: (TABLE_ID, FREQ_ID)" << endl ;
3178 for ( uInt i = 0 ; i < ifgrp.size() ; i++ ) {
3179 oss << " GROUP " << setw( 2 ) << i << " [" << ifgfreq[2*i] << "," << ifgfreq[2*i+1] << "]: " ;
3180 for ( uInt j = 0 ; j < ifgrp[i].size()/2 ; j++ ) {
3181 oss << "(" << ifgrp[i][2*j] << "," << ifgrp[i][2*j+1] << ") " ;
3182 }
3183 oss << endl ;
3184 }
3185 oss << endl ;
3186 os << oss.str() << LogIO::POST ;
3187
3188 // print frequency group
3189 oss.str("") ;
3190 oss << "Frequency Group summary: " << endl ;
3191 oss << " GROUP_ID [FREQ_MIN, FREQ_MAX]: IF_GROUP_ID" << endl ;
3192 for ( uInt i = 0 ; i < freqgrp.size() ; i++ ) {
3193 oss << " GROUP " << setw( 2 ) << i << " [" << ifgfreq[2*freqgrp[i][0]] << "," << ifgfreq[2*freqgrp[i][freqgrp[i].size()-1]+1] << "]: " ;
3194 for ( uInt j = 0 ; j < freqgrp[i].size() ; j++ ) {
3195 oss << freqgrp[i][j] << " " ;
3196 }
3197 oss << endl ;
3198 }
3199 oss << endl ;
3200 os << oss.str() << LogIO::POST ;
3201
3202 // membership check
3203 // groups: list of IF group indexes whose frequency range overlaps with
3204 // that of each table and IF
3205 // groups[numtable][numIF][nummembership]
3206 // groups: [[[grp, grp,...], [grp, grp,...],...],
3207 // [[grp, grp,...], [grp, grp,...],...],
3208 // ...
3209 // [[grp, grp,...], [grp, grp,...],...]]
3210 vector< vector< vector<uInt> > > groups( insize ) ;
3211 for ( uInt i = 0 ; i < insize ; i++ ) {
3212 groups[i].resize( freqid[i].size() ) ;
3213 }
3214 for ( uInt igrp = 0 ; igrp < ifgrp.size() ; igrp++ ) {
3215 for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) {
3216 uInt tableid = ifgrp[igrp][2*imem] ;
3217 vector<uInt>::iterator iter = find( freqid[tableid].begin(), freqid[tableid].end(), ifgrp[igrp][2*imem+1] ) ;
3218 if ( iter != freqid[tableid].end() ) {
3219 uInt rowid = distance( freqid[tableid].begin(), iter ) ;
3220 groups[tableid][rowid].push_back( igrp ) ;
3221 }
3222 }
3223 }
3224
3225 // print membership
3226 //oss.str("") ;
3227 //for ( uInt i = 0 ; i < insize ; i++ ) {
3228 //oss << "Table " << i << endl ;
3229 //for ( uInt j = 0 ; j < groups[i].size() ; j++ ) {
3230 //oss << " FREQ_ID " << setw( 2 ) << freqid[i][j] << ": " ;
3231 //for ( uInt k = 0 ; k < groups[i][j].size() ; k++ ) {
3232 //oss << setw( 2 ) << groups[i][j][k] << " " ;
3233 //}
3234 //oss << endl ;
3235 //}
3236 //}
3237 //os << oss.str() << LogIO::POST ;
3238
3239 // set back coordinfo
3240 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3241 vector<string> coordinfo = tmpin[itable]->getCoordInfo() ;
3242 coordinfo[0] = oldinfo[itable] ;
3243 tmpin[itable]->setCoordInfo( coordinfo ) ;
3244 }
3245
3246 // Create additional table if needed
3247 bool oldInsitu = insitu_ ;
3248 setInsitu( false ) ;
3249 vector< vector<uInt> > addrow( insize ) ;
3250 vector<uInt> addtable( insize, 0 ) ;
3251 vector<uInt> newtableids( insize ) ;
3252 vector<uInt> newifids( insize, 0 ) ;
3253 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3254 //os << "Table " << itable << ": " ;
3255 for ( uInt ifrow = 0 ; ifrow < groups[itable].size() ; ifrow++ ) {
3256 addrow[itable].push_back( groups[itable][ifrow].size()-1 ) ;
3257 //os << addrow[itable][ifrow] << " " ;
3258 }
3259 addtable[itable] = *max_element( addrow[itable].begin(), addrow[itable].end() ) ;
3260 //os << "(" << addtable[itable] << ")" << LogIO::POST ;
3261 }
3262 newin.resize( insize ) ;
3263 copy( tmpin.begin(), tmpin.end(), newin.begin() ) ;
3264 for ( uInt i = 0 ; i < insize ; i++ ) {
3265 newtableids[i] = i ;
3266 }
3267 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3268 for ( uInt iadd = 0 ; iadd < addtable[itable] ; iadd++ ) {
3269 CountedPtr<Scantable> add = getScantable( newin[itable], false ) ;
3270 vector<int> freqidlist ;
3271 for ( uInt i = 0 ; i < groups[itable].size() ; i++ ) {
3272 if ( groups[itable][i].size() > iadd + 1 ) {
3273 freqidlist.push_back( freqid[itable][i] ) ;
3274 }
3275 }
3276 stringstream taqlstream ;
3277 taqlstream << "SELECT FROM $1 WHERE FREQ_ID IN [" ;
3278 for ( uInt i = 0 ; i < freqidlist.size() ; i++ ) {
3279 taqlstream << freqidlist[i] ;
3280 if ( i < freqidlist.size() - 1 )
3281 taqlstream << "," ;
3282 else
3283 taqlstream << "]" ;
3284 }
3285 string taql = taqlstream.str() ;
3286 //os << "taql = " << taql << LogIO::POST ;
3287 STSelector selector = STSelector() ;
3288 selector.setTaQL( taql ) ;
3289 add->setSelection( selector ) ;
3290 newin.push_back( add ) ;
3291 newtableids.push_back( itable ) ;
3292 newifids.push_back( iadd + 1 ) ;
3293 }
3294 }
3295
3296 // udpate ifgrp
3297 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3298 for ( uInt iadd = 0 ; iadd < addtable[itable] ; iadd++ ) {
3299 for ( uInt ifrow = 0 ; ifrow < groups[itable].size() ; ifrow++ ) {
3300 if ( groups[itable][ifrow].size() > iadd + 1 ) {
3301 uInt igrp = groups[itable][ifrow][iadd+1] ;
3302 for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) {
3303 if ( ifgrp[igrp][2*imem] == newtableids[iadd+insize] && ifgrp[igrp][2*imem+1] == freqid[newtableids[iadd+insize]][ifrow] ) {
3304 ifgrp[igrp][2*imem] = insize + iadd ;
3305 }
3306 }
3307 }
3308 }
3309 }
3310 }
3311
3312 // print IF groups again for debug
3313 //oss.str( "" ) ;
3314 //oss << "IF Group summary: " << endl ;
3315 //oss << " GROUP_ID [FREQ_MIN, FREQ_MAX]: (TABLE_ID, FREQ_ID)" << endl ;
3316 //for ( uInt i = 0 ; i < ifgrp.size() ; i++ ) {
3317 //oss << " GROUP " << setw( 2 ) << i << " [" << ifgfreq[2*i] << "," << ifgfreq[2*i+1] << "]: " ;
3318 //for ( uInt j = 0 ; j < ifgrp[i].size()/2 ; j++ ) {
3319 //oss << "(" << ifgrp[i][2*j] << "," << ifgrp[i][2*j+1] << ") " ;
3320 //}
3321 //oss << endl ;
3322 //}
3323 //oss << endl ;
3324 //os << oss.str() << LogIO::POST ;
3325
3326 // reset SCANNO and IFNO/FREQ_ID: IF is reset by the result of sortation
3327 os << "All scan number is set to 0" << LogIO::POST ;
3328 //os << "All IF number is set to IF group index" << LogIO::POST ;
3329 insize = newin.size() ;
3330 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3331 uInt rows = newin[itable]->nrow() ;
3332 Table &tmpt = newin[itable]->table() ;
3333 freqIDCol.attach( tmpt, "FREQ_ID" ) ;
3334 scannoCol.attach( tmpt, "SCANNO" ) ;
3335 ifnoCol.attach( tmpt, "IFNO" ) ;
3336 for ( uInt irow=0 ; irow < rows ; irow++ ) {
3337 scannoCol.put( irow, 0 ) ;
3338 uInt freqID = freqIDCol( irow ) ;
3339 vector<uInt>::iterator iter = find( freqid[newtableids[itable]].begin(), freqid[newtableids[itable]].end(), freqID ) ;
3340 if ( iter != freqid[newtableids[itable]].end() ) {
3341 uInt index = distance( freqid[newtableids[itable]].begin(), iter ) ;
3342 ifnoCol.put( irow, groups[newtableids[itable]][index][newifids[itable]] ) ;
3343 }
3344 else {
3345 throw(AipsError("IF grouping was wrong in additional tables.")) ;
3346 }
3347 }
3348 }
3349 oldinfo.resize( insize ) ;
3350 setInsitu( oldInsitu ) ;
3351
3352 // temporarily set coordinfo
3353 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3354 vector<string> coordinfo = newin[itable]->getCoordInfo() ;
3355 oldinfo[itable] = coordinfo[0] ;
3356 coordinfo[0] = "Hz" ;
3357 newin[itable]->setCoordInfo( coordinfo ) ;
3358 }
3359
3360 // save column values in the vector
3361 vector< vector<uInt> > freqTableIdVec( insize ) ;
3362 vector< vector<uInt> > freqIdVec( insize ) ;
3363 vector< vector<uInt> > ifNoVec( insize ) ;
3364 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3365 ScalarColumn<uInt> freqIDs ;
3366 freqIDs.attach( newin[itable]->frequencies().table(), "ID" ) ;
3367 ifnoCol.attach( newin[itable]->table(), "IFNO" ) ;
3368 freqIDCol.attach( newin[itable]->table(), "FREQ_ID" ) ;
3369 for ( uInt irow = 0 ; irow < newin[itable]->frequencies().table().nrow() ; irow++ ) {
3370 freqTableIdVec[itable].push_back( freqIDs( irow ) ) ;
3371 }
3372 for ( uInt irow = 0 ; irow < newin[itable]->table().nrow() ; irow++ ) {
3373 freqIdVec[itable].push_back( freqIDCol( irow ) ) ;
3374 ifNoVec[itable].push_back( ifnoCol( irow ) ) ;
3375 }
3376 }
3377
3378 // reset spectra and flagtra: pick up common part of frequency coverage
3379 //os << "Pick common frequency range and align resolution" << LogIO::POST ;
3380 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3381 uInt rows = newin[itable]->nrow() ;
3382 int nminchan = -1 ;
3383 int nmaxchan = -1 ;
3384 vector<uInt> freqIdUpdate ;
3385 for ( uInt irow = 0 ; irow < rows ; irow++ ) {
3386 uInt ifno = ifNoVec[itable][irow] ; // IFNO is reset by group index
3387 double minfreq = ifgfreq[2*ifno] ;
3388 double maxfreq = ifgfreq[2*ifno+1] ;
3389 //os << "frequency range: [" << minfreq << "," << maxfreq << "]" << LogIO::POST ;
3390 vector<double> abcissa = newin[itable]->getAbcissa( irow ) ;
3391 int nchan = abcissa.size() ;
3392 double resol = abcissa[1] - abcissa[0] ;
3393 //os << "abcissa range : [" << abcissa[0] << "," << abcissa[nchan-1] << "]" << LogIO::POST ;
3394 if ( minfreq <= abcissa[0] )
3395 nminchan = 0 ;
3396 else {
3397 //double cfreq = ( minfreq - abcissa[0] ) / resol ;
3398 double cfreq = ( minfreq - abcissa[0] + 0.5 * resol ) / resol ;
3399 nminchan = int(cfreq) + ( ( cfreq - int(cfreq) <= 0.5 ) ? 0 : 1 ) ;
3400 }
3401 if ( maxfreq >= abcissa[abcissa.size()-1] )
3402 nmaxchan = abcissa.size() - 1 ;
3403 else {
3404 //double cfreq = ( abcissa[abcissa.size()-1] - maxfreq ) / resol ;
3405 double cfreq = ( abcissa[abcissa.size()-1] - maxfreq + 0.5 * resol ) / resol ;
3406 nmaxchan = abcissa.size() - 1 - int(cfreq) - ( ( cfreq - int(cfreq) >= 0.5 ) ? 1 : 0 ) ;
3407 }
3408 //os << "channel range (" << irow << "): [" << nminchan << "," << nmaxchan << "]" << LogIO::POST ;
3409 if ( nmaxchan > nminchan ) {
3410 newin[itable]->reshapeSpectrum( nminchan, nmaxchan, irow ) ;
3411 int newchan = nmaxchan - nminchan + 1 ;
3412 if ( count( freqIdUpdate.begin(), freqIdUpdate.end(), freqIdVec[itable][irow] ) == 0 && newchan < nchan )
3413 freqIdUpdate.push_back( freqIdVec[itable][irow] ) ;
3414 }
3415 else {
3416 throw(AipsError("Failed to pick up common part of frequency range.")) ;
3417 }
3418 }
3419 for ( uInt i = 0 ; i < freqIdUpdate.size() ; i++ ) {
3420 uInt freqId = freqIdUpdate[i] ;
3421 Double refpix ;
3422 Double refval ;
3423 Double increment ;
3424
3425 // update row
3426 newin[itable]->frequencies().getEntry( refpix, refval, increment, freqId ) ;
3427 refval = refval - ( refpix - nminchan ) * increment ;
3428 refpix = 0 ;
3429 newin[itable]->frequencies().setEntry( refpix, refval, increment, freqId ) ;
3430 }
3431 }
3432
3433
3434 // reset spectra and flagtra: align spectral resolution
3435 //os << "Align spectral resolution" << LogIO::POST ;
3436 // gmaxdnu: the coarsest frequency resolution in the frequency group
3437 // gmemid: member index that have a resolution equal to gmaxdnu
3438 // gmaxdnu[numfreqgrp]
3439 // gmaxdnu: [dnu0, dnu1, ...]
3440 // gmemid[numfreqgrp]
3441 // gmemid: [id0, id1, ...]
3442 vector<double> gmaxdnu( freqgrp.size(), 0.0 ) ;
3443 vector<uInt> gmemid( freqgrp.size(), 0 ) ;
3444 for ( uInt igrp = 0 ; igrp < ifgrp.size() ; igrp++ ) {
3445 double maxdnu = 0.0 ; // maximum (coarsest) frequency resolution
3446 int minchan = INT_MAX ; // minimum channel number
3447 Double refpixref = -1 ; // reference of 'reference pixel'
3448 Double refvalref = -1 ; // reference of 'reference frequency'
3449 Double refinc = -1 ; // reference frequency resolution
3450 uInt refreqid ;
3451 uInt reftable = INT_MAX;
3452 // process only if group member > 1
3453 if ( ifgrp[igrp].size() > 2 ) {
3454 // find minchan and maxdnu in each group
3455 for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) {
3456 uInt tableid = ifgrp[igrp][2*imem] ;
3457 uInt rowid = ifgrp[igrp][2*imem+1] ;
3458 vector<uInt>::iterator iter = find( freqIdVec[tableid].begin(), freqIdVec[tableid].end(), rowid ) ;
3459 if ( iter != freqIdVec[tableid].end() ) {
3460 uInt index = distance( freqIdVec[tableid].begin(), iter ) ;
3461 vector<double> abcissa = newin[tableid]->getAbcissa( index ) ;
3462 int nchan = abcissa.size() ;
3463 double dnu = abcissa[1] - abcissa[0] ;
3464 //os << "GROUP " << igrp << " (" << tableid << "," << rowid << "): nchan = " << nchan << " (minchan = " << minchan << ")" << LogIO::POST ;
3465 if ( nchan < minchan ) {
3466 minchan = nchan ;
3467 maxdnu = dnu ;
3468 newin[tableid]->frequencies().getEntry( refpixref, refvalref, refinc, rowid ) ;
3469 refreqid = rowid ;
3470 reftable = tableid ;
3471 }
3472 }
3473 }
3474 // regrid spectra in each group
3475 os << "GROUP " << igrp << endl ;
3476 os << " Channel number is adjusted to " << minchan << endl ;
3477 os << " Corresponding frequency resolution is " << maxdnu << "Hz" << LogIO::POST ;
3478 for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) {
3479 uInt tableid = ifgrp[igrp][2*imem] ;
3480 uInt rowid = ifgrp[igrp][2*imem+1] ;
3481 freqIDCol.attach( newin[tableid]->table(), "FREQ_ID" ) ;
3482 //os << "tableid = " << tableid << " rowid = " << rowid << ": " << LogIO::POST ;
3483 //os << " regridChannel applied to " ;
3484 //if ( tableid != reftable )
3485 refreqid = newin[tableid]->frequencies().addEntry( refpixref, refvalref, refinc ) ;
3486 for ( uInt irow = 0 ; irow < newin[tableid]->table().nrow() ; irow++ ) {
3487 uInt tfreqid = freqIdVec[tableid][irow] ;
3488 if ( tfreqid == rowid ) {
3489 //os << irow << " " ;
3490 newin[tableid]->regridChannel( minchan, maxdnu, irow ) ;
3491 freqIDCol.put( irow, refreqid ) ;
3492 freqIdVec[tableid][irow] = refreqid ;
3493 }
3494 }
3495 //os << LogIO::POST ;
3496 }
3497 }
3498 else {
3499 uInt tableid = ifgrp[igrp][0] ;
3500 uInt rowid = ifgrp[igrp][1] ;
3501 vector<uInt>::iterator iter = find( freqIdVec[tableid].begin(), freqIdVec[tableid].end(), rowid ) ;
3502 if ( iter != freqIdVec[tableid].end() ) {
3503 uInt index = distance( freqIdVec[tableid].begin(), iter ) ;
3504 vector<double> abcissa = newin[tableid]->getAbcissa( index ) ;
3505 minchan = abcissa.size() ;
3506 maxdnu = abcissa[1] - abcissa[0] ;
3507 }
3508 }
3509 for ( uInt i = 0 ; i < freqgrp.size() ; i++ ) {
3510 if ( count( freqgrp[i].begin(), freqgrp[i].end(), igrp ) > 0 ) {
3511 if ( maxdnu > gmaxdnu[i] ) {
3512 gmaxdnu[i] = maxdnu ;
3513 gmemid[i] = igrp ;
3514 }
3515 break ;
3516 }
3517 }
3518 }
3519
3520 // set back coordinfo
3521 for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3522 vector<string> coordinfo = newin[itable]->getCoordInfo() ;
3523 coordinfo[0] = oldinfo[itable] ;
3524 newin[itable]->setCoordInfo( coordinfo ) ;
3525 }
3526
3527 // accumulate all rows into the first table
3528 // NOTE: assumed in.size() = 1
3529 vector< CountedPtr<Scantable> > tmp( 1 ) ;
3530 if ( newin.size() == 1 )
3531 tmp[0] = newin[0] ;
3532 else
3533 tmp[0] = merge( newin ) ;
3534
3535 //return tmp[0] ;
3536
3537 // average
3538 CountedPtr<Scantable> tmpout = average( tmp, mask, weight, avmode ) ;
3539
3540 //return tmpout ;
3541
3542 // combine frequency group
3543 os << "Combine spectra based on frequency grouping" << LogIO::POST ;
3544 os << "IFNO is renumbered as frequency group ID (see above)" << LogIO::POST ;
3545 vector<string> coordinfo = tmpout->getCoordInfo() ;
3546 oldinfo[0] = coordinfo[0] ;
3547 coordinfo[0] = "Hz" ;
3548 tmpout->setCoordInfo( coordinfo ) ;
3549 // create proformas of output table
3550 stringstream taqlstream ;
3551 taqlstream << "SELECT FROM $1 WHERE IFNO IN [" ;
3552 for ( uInt i = 0 ; i < gmemid.size() ; i++ ) {
3553 taqlstream << gmemid[i] ;
3554 if ( i < gmemid.size() - 1 )
3555 taqlstream << "," ;
3556 else
3557 taqlstream << "]" ;
3558 }
3559 string taql = taqlstream.str() ;
3560 //os << "taql = " << taql << LogIO::POST ;
3561 STSelector selector = STSelector() ;
3562 selector.setTaQL( taql ) ;
3563 oldInsitu = insitu_ ;
3564 setInsitu( false ) ;
3565 out = getScantable( tmpout, false ) ;
3566 setInsitu( oldInsitu ) ;
3567 out->setSelection( selector ) ;
3568 // regrid rows
3569 ifnoCol.attach( tmpout->table(), "IFNO" ) ;
3570 for ( uInt irow = 0 ; irow < tmpout->table().nrow() ; irow++ ) {
3571 uInt ifno = ifnoCol( irow ) ;
3572 for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) {
3573 if ( count( freqgrp[igrp].begin(), freqgrp[igrp].end(), ifno ) > 0 ) {
3574 vector<double> abcissa = tmpout->getAbcissa( irow ) ;
3575 double bw = ( abcissa[1] - abcissa[0] ) * abcissa.size() ;
3576 int nchan = (int)( bw / gmaxdnu[igrp] ) ;
3577 tmpout->regridChannel( nchan, gmaxdnu[igrp], irow ) ;
3578 break ;
3579 }
3580 }
3581 }
3582 // combine spectra
3583 ArrayColumn<Float> specColOut ;
3584 specColOut.attach( out->table(), "SPECTRA" ) ;
3585 ArrayColumn<uChar> flagColOut ;
3586 flagColOut.attach( out->table(), "FLAGTRA" ) ;
3587 ScalarColumn<uInt> ifnoColOut ;
3588 ifnoColOut.attach( out->table(), "IFNO" ) ;
3589 ScalarColumn<uInt> polnoColOut ;
3590 polnoColOut.attach( out->table(), "POLNO" ) ;
3591 ScalarColumn<uInt> freqidColOut ;
3592 freqidColOut.attach( out->table(), "FREQ_ID" ) ;
3593 MDirection::ScalarColumn dirColOut ;
3594 dirColOut.attach( out->table(), "DIRECTION" ) ;
3595 Table &tab = tmpout->table() ;
3596 Block<String> cols(1);
3597 cols[0] = String("POLNO") ;
3598 TableIterator iter( tab, cols ) ;
3599 bool done = false ;
3600 vector< vector<uInt> > sizes( freqgrp.size() ) ;
3601 while( !iter.pastEnd() ) {
3602 vector< vector<Float> > specout( freqgrp.size() ) ;
3603 vector< vector<uChar> > flagout( freqgrp.size() ) ;
3604 ArrayColumn<Float> specCols ;
3605 specCols.attach( iter.table(), "SPECTRA" ) ;
3606 ArrayColumn<uChar> flagCols ;
3607 flagCols.attach( iter.table(), "FLAGTRA" ) ;
3608 ifnoCol.attach( iter.table(), "IFNO" ) ;
3609 ScalarColumn<uInt> polnos ;
3610 polnos.attach( iter.table(), "POLNO" ) ;
3611 MDirection::ScalarColumn dircol ;
3612 dircol.attach( iter.table(), "DIRECTION" ) ;
3613 uInt polno = polnos( 0 ) ;
3614 //os << "POLNO iteration: " << polno << LogIO::POST ;
3615// for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) {
3616// sizes[igrp].resize( freqgrp[igrp].size() ) ;
3617// for ( uInt imem = 0 ; imem < freqgrp[igrp].size() ; imem++ ) {
3618// for ( uInt irow = 0 ; irow < iter.table().nrow() ; irow++ ) {
3619// uInt ifno = ifnoCol( irow ) ;
3620// if ( ifno == freqgrp[igrp][imem] ) {
3621// Vector<Float> spec = specCols( irow ) ;
3622// Vector<uChar> flag = flagCols( irow ) ;
3623// vector<Float> svec ;
3624// spec.tovector( svec ) ;
3625// vector<uChar> fvec ;
3626// flag.tovector( fvec ) ;
3627// //os << "spec.size() = " << svec.size() << " fvec.size() = " << fvec.size() << LogIO::POST ;
3628// specout[igrp].insert( specout[igrp].end(), svec.begin(), svec.end() ) ;
3629// flagout[igrp].insert( flagout[igrp].end(), fvec.begin(), fvec.end() ) ;
3630// //os << "specout[" << igrp << "].size() = " << specout[igrp].size() << LogIO::POST ;
3631// sizes[igrp][imem] = spec.nelements() ;
3632// }
3633// }
3634// }
3635// for ( uInt irow = 0 ; irow < out->table().nrow() ; irow++ ) {
3636// uInt ifout = ifnoColOut( irow ) ;
3637// uInt polout = polnoColOut( irow ) ;
3638// if ( ifout == gmemid[igrp] && polout == polno ) {
3639// // set SPECTRA and FRAGTRA
3640// Vector<Float> newspec( specout[igrp] ) ;
3641// Vector<uChar> newflag( flagout[igrp] ) ;
3642// specColOut.put( irow, newspec ) ;
3643// flagColOut.put( irow, newflag ) ;
3644// // IFNO renumbering
3645// ifnoColOut.put( irow, igrp ) ;
3646// }
3647// }
3648// }
3649 // get a list of number of channels for each frequency group member
3650 if ( !done ) {
3651 for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) {
3652 sizes[igrp].resize( freqgrp[igrp].size() ) ;
3653 for ( uInt imem = 0 ; imem < freqgrp[igrp].size() ; imem++ ) {
3654 for ( uInt irow = 0 ; irow < iter.table().nrow() ; irow++ ) {
3655 uInt ifno = ifnoCol( irow ) ;
3656 if ( ifno == freqgrp[igrp][imem] ) {
3657 Vector<Float> spec = specCols( irow ) ;
3658 sizes[igrp][imem] = spec.nelements() ;
3659 break ;
3660 }
3661 }
3662 }
3663 }
3664 done = true ;
3665 }
3666 // combine spectra
3667 for ( uInt irow = 0 ; irow < out->table().nrow() ; irow++ ) {
3668 uInt polout = polnoColOut( irow ) ;
3669 if ( polout == polno ) {
3670 uInt ifout = ifnoColOut( irow ) ;
3671 Vector<Double> direction = dirColOut(irow).getAngle(Unit(String("rad"))).getValue() ;
3672 uInt igrp ;
3673 for ( uInt jgrp = 0 ; jgrp < freqgrp.size() ; jgrp++ ) {
3674 if ( ifout == gmemid[jgrp] ) {
3675 igrp = jgrp ;
3676 break ;
3677 }
3678 }
3679 for ( uInt imem = 0 ; imem < freqgrp[igrp].size() ; imem++ ) {
3680 for ( uInt jrow = 0 ; jrow < iter.table().nrow() ; jrow++ ) {
3681 uInt ifno = ifnoCol( jrow ) ;
3682 Vector<Double> tdir = dircol(jrow).getAngle(Unit(String("rad"))).getValue() ;
3683 //if ( ifno == freqgrp[igrp][imem] && allTrue( tdir == direction ) ) {
3684 Double dx = tdir[0] - direction[0] ;
3685 Double dy = tdir[1] - direction[1] ;
3686 Double dd = sqrt( dx * dx + dy * dy ) ;
3687 //if ( ifno == freqgrp[igrp][imem] && allNearAbs( tdir, direction, tol ) ) {
3688 if ( ifno == freqgrp[igrp][imem] && dd <= tol ) {
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.