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

Last change on this file since 2285 was 2285, checked in by ShinnosukeKawakami, 13 years ago

New Development: No

JIRA Issue: No List JIRA ticket.

Ready for Test: Yes

Interface Changes: No

What Interface Changed: Please list interface changes

Test Programs: fls3a_hi_regression.py

Put in Release Notes: No

Module(s): _asap.so

Description: (1)Replaced getEntry to map within dototalpower in STMath.cpp and STMath.h. (2) modified STFocus.h and Templates to pass build by using Intel Compiler successfully.


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