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

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

New Development: No

JIRA Issue: No (speedup)

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs: CASA: a unit tests of task, sdcoadd

Put in Release Notes: No

Module(s): asapmath.merge and sdcoadd (in CASA)

Description:

Reduced redundant call to addEntry and getEntry functions which are slow.


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