source: branches/parallel/src/STMath.cpp@ 2136

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