source: trunk/src/STMath.cpp@ 1331

Last change on this file since 1331 was 1321, checked in by mar637, 18 years ago

Hopefully final fix to ticket #78;had to do a sub selection of BEAMNO,IFNO,POLNO fisrt, and also TIME column is MJD, which is in datys not seconds.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 49.1 KB
RevLine 
[805]1//
2// C++ Implementation: STMath
3//
4// Description:
5//
6//
7// Author: Malte Marquarding <asap@atnf.csiro.au>, (C) 2006
8//
9// Copyright: See COPYING file that comes with this distribution
10//
11//
[38]12
[330]13#include <casa/iomanip.h>
[805]14#include <casa/Exceptions/Error.h>
15#include <casa/Containers/Block.h>
[81]16#include <casa/BasicSL/String.h>
[805]17#include <casa/Arrays/MaskArrLogi.h>
18#include <casa/Arrays/MaskArrMath.h>
19#include <casa/Arrays/ArrayLogical.h>
[81]20#include <casa/Arrays/ArrayMath.h>
[1066]21#include <casa/Arrays/Slice.h>
22#include <casa/Arrays/Slicer.h>
[805]23#include <casa/Containers/RecordField.h>
24#include <tables/Tables/TableRow.h>
25#include <tables/Tables/TableVector.h>
[917]26#include <tables/Tables/TabVecMath.h>
[805]27#include <tables/Tables/ExprNode.h>
28#include <tables/Tables/TableRecord.h>
[1140]29#include <tables/Tables/TableParse.h>
[805]30#include <tables/Tables/ReadAsciiTable.h>
[1140]31#include <tables/Tables/TableIter.h>
32#include <tables/Tables/TableCopy.h>
[1192]33#include <scimath/Mathematics/FFTServer.h>
[2]34
[262]35#include <lattices/Lattices/LatticeUtilities.h>
36
[917]37#include <coordinates/Coordinates/SpectralCoordinate.h>
38#include <coordinates/Coordinates/CoordinateSystem.h>
39#include <coordinates/Coordinates/CoordinateUtil.h>
40#include <coordinates/Coordinates/FrequencyAligner.h>
41
[177]42#include <scimath/Mathematics/VectorKernel.h>
43#include <scimath/Mathematics/Convolver.h>
[234]44#include <scimath/Functionals/Polynomial.h>
[177]45
[38]46#include "MathUtils.h"
[805]47#include "RowAccumulator.h"
[878]48#include "STAttr.h"
[805]49#include "STMath.h"
[2]50
[805]51using namespace casa;
[2]52
[83]53using namespace asap;
[2]54
[805]55STMath::STMath(bool insitu) :
56 insitu_(insitu)
[716]57{
58}
[170]59
60
[805]61STMath::~STMath()
[170]62{
63}
64
[805]65CountedPtr<Scantable>
[977]66STMath::average( const std::vector<CountedPtr<Scantable> >& in,
[858]67 const std::vector<bool>& mask,
[805]68 const std::string& weight,
[977]69 const std::string& avmode)
[262]70{
[977]71 if ( avmode == "SCAN" && in.size() != 1 )
[1066]72 throw(AipsError("Can't perform 'SCAN' averaging on multiple tables.\n"
73 "Use merge first."));
[805]74 WeightType wtype = stringToWeight(weight);
[926]75
[805]76 // output
77 // clone as this is non insitu
78 bool insitu = insitu_;
79 setInsitu(false);
[977]80 CountedPtr< Scantable > out = getScantable(in[0], true);
[805]81 setInsitu(insitu);
[977]82 std::vector<CountedPtr<Scantable> >::const_iterator stit = in.begin();
[862]83 ++stit;
[977]84 while ( stit != in.end() ) {
[862]85 out->appendToHistoryTable((*stit)->history());
86 ++stit;
87 }
[294]88
[805]89 Table& tout = out->table();
[701]90
[805]91 /// @todo check if all scantables are conformant
[294]92
[805]93 ArrayColumn<Float> specColOut(tout,"SPECTRA");
94 ArrayColumn<uChar> flagColOut(tout,"FLAGTRA");
95 ArrayColumn<Float> tsysColOut(tout,"TSYS");
96 ScalarColumn<Double> mjdColOut(tout,"TIME");
97 ScalarColumn<Double> intColOut(tout,"INTERVAL");
[1008]98 ScalarColumn<uInt> cycColOut(tout,"CYCLENO");
[1145]99 ScalarColumn<uInt> scanColOut(tout,"SCANNO");
[262]100
[805]101 // set up the output table rows. These are based on the structure of the
[862]102 // FIRST scantable in the vector
[977]103 const Table& baset = in[0]->table();
[262]104
[805]105 Block<String> cols(3);
106 cols[0] = String("BEAMNO");
107 cols[1] = String("IFNO");
108 cols[2] = String("POLNO");
109 if ( avmode == "SOURCE" ) {
110 cols.resize(4);
111 cols[3] = String("SRCNAME");
[488]112 }
[977]113 if ( avmode == "SCAN" && in.size() == 1) {
[805]114 cols.resize(4);
115 cols[3] = String("SCANNO");
[2]116 }
[805]117 uInt outrowCount = 0;
118 TableIterator iter(baset, cols);
119 while (!iter.pastEnd()) {
120 Table subt = iter.table();
121 // copy the first row of this selection into the new table
122 tout.addRow();
123 TableCopy::copyRows(tout, subt, outrowCount, 0, 1);
[1145]124 // re-index to 0
125 if ( avmode != "SCAN" && avmode != "SOURCE" ) {
126 scanColOut.put(outrowCount, uInt(0));
127 }
[805]128 ++outrowCount;
129 ++iter;
[144]130 }
[805]131 RowAccumulator acc(wtype);
[858]132 Vector<Bool> cmask(mask);
133 acc.setUserMask(cmask);
[805]134 ROTableRow row(tout);
135 ROArrayColumn<Float> specCol, tsysCol;
136 ROArrayColumn<uChar> flagCol;
137 ROScalarColumn<Double> mjdCol, intCol;
138 ROScalarColumn<Int> scanIDCol;
[144]139
[805]140 for (uInt i=0; i < tout.nrow(); ++i) {
[996]141 for ( int j=0; j < int(in.size()); ++j ) {
[977]142 const Table& tin = in[j]->table();
[805]143 const TableRecord& rec = row.get(i);
144 ROScalarColumn<Double> tmp(tin, "TIME");
145 Double td;tmp.get(0,td);
146 Table basesubt = tin(tin.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
147 && tin.col("IFNO") == Int(rec.asuInt("IFNO"))
148 && tin.col("POLNO") == Int(rec.asuInt("POLNO")) );
149 Table subt;
150 if ( avmode == "SOURCE") {
151 subt = basesubt( basesubt.col("SRCNAME") == rec.asString("SRCNAME") );
152 } else if (avmode == "SCAN") {
153 subt = basesubt( basesubt.col("SCANNO") == Int(rec.asuInt("SCANNO")) );
154 } else {
155 subt = basesubt;
156 }
157 specCol.attach(subt,"SPECTRA");
158 flagCol.attach(subt,"FLAGTRA");
159 tsysCol.attach(subt,"TSYS");
160 intCol.attach(subt,"INTERVAL");
161 mjdCol.attach(subt,"TIME");
162 Vector<Float> spec,tsys;
163 Vector<uChar> flag;
164 Double inter,time;
165 for (uInt k = 0; k < subt.nrow(); ++k ) {
166 flagCol.get(k, flag);
167 Vector<Bool> bflag(flag.shape());
168 convertArray(bflag, flag);
[1314]169 /*
[805]170 if ( allEQ(bflag, True) ) {
[1314]171 continue;//don't accumulate
[144]172 }
[1314]173 */
[805]174 specCol.get(k, spec);
175 tsysCol.get(k, tsys);
176 intCol.get(k, inter);
177 mjdCol.get(k, time);
178 // spectrum has to be added last to enable weighting by the other values
179 acc.add(spec, !bflag, tsys, inter, time);
180 }
181 }
182 //write out
183 specColOut.put(i, acc.getSpectrum());
184 const Vector<Bool>& msk = acc.getMask();
185 Vector<uChar> flg(msk.shape());
186 convertArray(flg, !msk);
187 flagColOut.put(i, flg);
188 tsysColOut.put(i, acc.getTsys());
189 intColOut.put(i, acc.getInterval());
190 mjdColOut.put(i, acc.getTime());
[1008]191 // we should only have one cycle now -> reset it to be 0
192 // frequency switched data has different CYCLENO for different IFNO
193 // which requires resetting this value
194 cycColOut.put(i, uInt(0));
[805]195 acc.reset();
[144]196 }
[805]197 return out;
[2]198}
[9]199
[1069]200CountedPtr< Scantable >
201 STMath::averageChannel( const CountedPtr < Scantable > & in,
[1078]202 const std::string & mode,
203 const std::string& avmode )
[1069]204{
205 // clone as this is non insitu
206 bool insitu = insitu_;
207 setInsitu(false);
208 CountedPtr< Scantable > out = getScantable(in, true);
209 setInsitu(insitu);
210 Table& tout = out->table();
211 ArrayColumn<Float> specColOut(tout,"SPECTRA");
212 ArrayColumn<uChar> flagColOut(tout,"FLAGTRA");
213 ArrayColumn<Float> tsysColOut(tout,"TSYS");
[1140]214 ScalarColumn<uInt> scanColOut(tout,"SCANNO");
[1232]215 ScalarColumn<Double> intColOut(tout, "INTERVAL");
[1140]216 Table tmp = in->table().sort("BEAMNO");
[1069]217 Block<String> cols(3);
218 cols[0] = String("BEAMNO");
219 cols[1] = String("IFNO");
220 cols[2] = String("POLNO");
[1078]221 if ( avmode == "SCAN") {
222 cols.resize(4);
223 cols[3] = String("SCANNO");
224 }
[1069]225 uInt outrowCount = 0;
226 uChar userflag = 1 << 7;
[1140]227 TableIterator iter(tmp, cols);
[1069]228 while (!iter.pastEnd()) {
229 Table subt = iter.table();
230 ROArrayColumn<Float> specCol, tsysCol;
231 ROArrayColumn<uChar> flagCol;
[1232]232 ROScalarColumn<Double> intCol(subt, "INTERVAL");
[1069]233 specCol.attach(subt,"SPECTRA");
234 flagCol.attach(subt,"FLAGTRA");
235 tsysCol.attach(subt,"TSYS");
236 tout.addRow();
237 TableCopy::copyRows(tout, subt, outrowCount, 0, 1);
[1140]238 if ( avmode != "SCAN") {
239 scanColOut.put(outrowCount, uInt(0));
240 }
[1069]241 Vector<Float> tmp;
242 specCol.get(0, tmp);
243 uInt nchan = tmp.nelements();
[1078]244 // have to do channel by channel here as MaskedArrMath
245 // doesn't have partialMedians
[1069]246 Vector<uChar> flags = flagCol.getColumn(Slicer(Slice(0)));
247 Vector<Float> outspec(nchan);
248 Vector<uChar> outflag(nchan,0);
249 Vector<Float> outtsys(1);/// @fixme when tsys is channel based
250 for (uInt i=0; i<nchan; ++i) {
251 Vector<Float> specs = specCol.getColumn(Slicer(Slice(i)));
252 MaskedArray<Float> ma = maskedArray(specs,flags);
253 outspec[i] = median(ma);
254 if ( allEQ(ma.getMask(), False) )
255 outflag[i] = userflag;// flag data
256 }
257 outtsys[0] = median(tsysCol.getColumn());
258 specColOut.put(outrowCount, outspec);
259 flagColOut.put(outrowCount, outflag);
260 tsysColOut.put(outrowCount, outtsys);
[1232]261 Double intsum = sum(intCol.getColumn());
262 intColOut.put(outrowCount, intsum);
[1069]263 ++outrowCount;
264 ++iter;
265 }
266 return out;
267}
268
[805]269CountedPtr< Scantable > STMath::getScantable(const CountedPtr< Scantable >& in,
270 bool droprows)
[185]271{
[805]272 if (insitu_) return in;
273 else {
274 // clone
275 Scantable* tabp = new Scantable(*in, Bool(droprows));
276 return CountedPtr<Scantable>(tabp);
[234]277 }
[805]278}
[234]279
[805]280CountedPtr< Scantable > STMath::unaryOperate( const CountedPtr< Scantable >& in,
281 float val,
282 const std::string& mode,
283 bool tsys )
284{
285 CountedPtr< Scantable > out = getScantable(in, false);
286 Table& tab = out->table();
287 ArrayColumn<Float> specCol(tab,"SPECTRA");
288 ArrayColumn<Float> tsysCol(tab,"TSYS");
289 for (uInt i=0; i<tab.nrow(); ++i) {
290 Vector<Float> spec;
291 Vector<Float> ts;
292 specCol.get(i, spec);
293 tsysCol.get(i, ts);
[1308]294 if (mode == "MUL" || mode == "DIV") {
295 if (mode == "DIV") val = 1.0/val;
[805]296 spec *= val;
297 specCol.put(i, spec);
298 if ( tsys ) {
299 ts *= val;
300 tsysCol.put(i, ts);
301 }
[1308]302 } else if ( mode == "ADD" || mode == "SUB") {
303 if (mode == "SUB") val *= -1.0;
[805]304 spec += val;
305 specCol.put(i, spec);
306 if ( tsys ) {
307 ts += val;
308 tsysCol.put(i, ts);
309 }
310 }
[234]311 }
[805]312 return out;
313}
[234]314
[1308]315CountedPtr<Scantable> STMath::binaryOperate(const CountedPtr<Scantable>& left,
316 const CountedPtr<Scantable>& right,
317 const std::string& mode)
318{
319 bool insitu = insitu_;
320 if ( ! left->conformant(*right) ) {
321 throw(AipsError("'left' and 'right' scantables are not conformant."));
322 }
323 setInsitu(false);
324 CountedPtr< Scantable > out = getScantable(left, false);
325 setInsitu(insitu);
326 Table& tout = out->table();
327 Block<String> coln(5);
328 coln[0] = "SCANNO"; coln[1] = "CYCLENO"; coln[2] = "BEAMNO";
329 coln[3] = "IFNO"; coln[4] = "POLNO";
330 Table tmpl = tout.sort(coln);
331 Table tmpr = right->table().sort(coln);
332 ArrayColumn<Float> lspecCol(tmpl,"SPECTRA");
333 ROArrayColumn<Float> rspecCol(tmpr,"SPECTRA");
334 ArrayColumn<uChar> lflagCol(tmpl,"FLAGTRA");
335 ROArrayColumn<uChar> rflagCol(tmpr,"FLAGTRA");
336
337 for (uInt i=0; i<tout.nrow(); ++i) {
338 Vector<Float> lspecvec, rspecvec;
339 Vector<uChar> lflagvec, rflagvec;
340 lspecvec = lspecCol(i); rspecvec = rspecCol(i);
341 lflagvec = lflagCol(i); rflagvec = rflagCol(i);
342 MaskedArray<Float> mleft = maskedArray(lspecvec, lflagvec);
343 MaskedArray<Float> mright = maskedArray(rspecvec, rflagvec);
344 if (mode == "ADD") {
345 mleft += mright;
346 } else if ( mode == "SUB") {
347 mleft -= mright;
348 } else if ( mode == "MUL") {
349 mleft *= mright;
350 } else if ( mode == "DIV") {
351 mleft /= mright;
352 } else {
353 throw(AipsError("Illegal binary operator"));
354 }
355 lspecCol.put(i, mleft.getArray());
356 }
357 return out;
358}
359
360
361
[805]362MaskedArray<Float> STMath::maskedArray( const Vector<Float>& s,
363 const Vector<uChar>& f)
364{
365 Vector<Bool> mask;
366 mask.resize(f.shape());
367 convertArray(mask, f);
368 return MaskedArray<Float>(s,!mask);
369}
[248]370
[805]371Vector<uChar> STMath::flagsFromMA(const MaskedArray<Float>& ma)
372{
373 const Vector<Bool>& m = ma.getMask();
374 Vector<uChar> flags(m.shape());
375 convertArray(flags, !m);
376 return flags;
377}
[234]378
[1066]379CountedPtr< Scantable > STMath::autoQuotient( const CountedPtr< Scantable >& in,
380 const std::string & mode,
381 bool preserve )
[805]382{
383 /// @todo make other modes available
384 /// modes should be "nearest", "pair"
385 // make this operation non insitu
386 const Table& tin = in->table();
387 Table ons = tin(tin.col("SRCTYPE") == Int(0));
388 Table offs = tin(tin.col("SRCTYPE") == Int(1));
389 if ( offs.nrow() == 0 )
390 throw(AipsError("No 'off' scans present."));
391 // put all "on" scans into output table
[701]392
[805]393 bool insitu = insitu_;
394 setInsitu(false);
395 CountedPtr< Scantable > out = getScantable(in, true);
396 setInsitu(insitu);
397 Table& tout = out->table();
[248]398
[805]399 TableCopy::copyRows(tout, ons);
400 TableRow row(tout);
401 ROScalarColumn<Double> offtimeCol(offs, "TIME");
402 ArrayColumn<Float> outspecCol(tout, "SPECTRA");
403 ROArrayColumn<Float> outtsysCol(tout, "TSYS");
404 ArrayColumn<uChar> outflagCol(tout, "FLAGTRA");
405 for (uInt i=0; i < tout.nrow(); ++i) {
406 const TableRecord& rec = row.get(i);
407 Double ontime = rec.asDouble("TIME");
[1321]408 Table presel = offs(offs.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
409 && offs.col("IFNO") == Int(rec.asuInt("IFNO"))
410 && offs.col("POLNO") == Int(rec.asuInt("POLNO")) );
411 ROScalarColumn<Double> offtimeCol(presel, "TIME");
412
[805]413 Double mindeltat = min(abs(offtimeCol.getColumn() - ontime));
[1259]414 // Timestamp may vary within a cycle ???!!!
[1321]415 // increase this by 0.01 sec in case of rounding errors...
[1259]416 // There might be a better way to do this.
[1321]417 // fix to this fix. TIME is MJD, so 1.0d not 1.0s
418 mindeltat += 0.01/24./60./60.;
419 Table sel = presel( abs(presel.col("TIME")-ontime) <= mindeltat);
[780]420
[1259]421 if ( sel.nrow() < 1 ) {
422 throw(AipsError("No closest in time found... This could be a rounding "
423 "issue. Try quotient instead."));
424 }
[805]425 TableRow offrow(sel);
426 const TableRecord& offrec = offrow.get(0);//should only be one row
427 RORecordFieldPtr< Array<Float> > specoff(offrec, "SPECTRA");
428 RORecordFieldPtr< Array<Float> > tsysoff(offrec, "TSYS");
429 RORecordFieldPtr< Array<uChar> > flagoff(offrec, "FLAGTRA");
430 /// @fixme this assumes tsys is a scalar not vector
431 Float tsysoffscalar = (*tsysoff)(IPosition(1,0));
432 Vector<Float> specon, tsyson;
433 outtsysCol.get(i, tsyson);
434 outspecCol.get(i, specon);
435 Vector<uChar> flagon;
436 outflagCol.get(i, flagon);
437 MaskedArray<Float> mon = maskedArray(specon, flagon);
438 MaskedArray<Float> moff = maskedArray(*specoff, *flagoff);
439 MaskedArray<Float> quot = (tsysoffscalar * mon / moff);
440 if (preserve) {
441 quot -= tsysoffscalar;
442 } else {
443 quot -= tsyson[0];
[701]444 }
[805]445 outspecCol.put(i, quot.getArray());
446 outflagCol.put(i, flagsFromMA(quot));
447 }
[926]448 // renumber scanno
449 TableIterator it(tout, "SCANNO");
450 uInt i = 0;
451 while ( !it.pastEnd() ) {
452 Table t = it.table();
453 TableVector<uInt> vec(t, "SCANNO");
454 vec = i;
455 ++i;
456 ++it;
457 }
[805]458 return out;
459}
[234]460
[1066]461
462CountedPtr< Scantable > STMath::quotient( const CountedPtr< Scantable > & on,
463 const CountedPtr< Scantable > & off,
464 bool preserve )
465{
466 bool insitu = insitu_;
[1069]467 if ( ! on->conformant(*off) ) {
468 throw(AipsError("'on' and 'off' scantables are not conformant."));
469 }
[1066]470 setInsitu(false);
471 CountedPtr< Scantable > out = getScantable(on, false);
472 setInsitu(insitu);
473 Table& tout = out->table();
474 const Table& toff = off->table();
475 TableIterator sit(tout, "SCANNO");
476 TableIterator s2it(toff, "SCANNO");
477 while ( !sit.pastEnd() ) {
478 Table ton = sit.table();
479 TableRow row(ton);
480 Table t = s2it.table();
481 ArrayColumn<Float> outspecCol(ton, "SPECTRA");
482 ROArrayColumn<Float> outtsysCol(ton, "TSYS");
483 ArrayColumn<uChar> outflagCol(ton, "FLAGTRA");
484 for (uInt i=0; i < ton.nrow(); ++i) {
485 const TableRecord& rec = row.get(i);
486 Table offsel = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
487 && t.col("IFNO") == Int(rec.asuInt("IFNO"))
488 && t.col("POLNO") == Int(rec.asuInt("POLNO")) );
[1145]489 if ( offsel.nrow() == 0 )
490 throw AipsError("STMath::quotient: no matching off");
[1066]491 TableRow offrow(offsel);
492 const TableRecord& offrec = offrow.get(0);//should be ncycles - take first
493 RORecordFieldPtr< Array<Float> > specoff(offrec, "SPECTRA");
494 RORecordFieldPtr< Array<Float> > tsysoff(offrec, "TSYS");
495 RORecordFieldPtr< Array<uChar> > flagoff(offrec, "FLAGTRA");
496 Float tsysoffscalar = (*tsysoff)(IPosition(1,0));
497 Vector<Float> specon, tsyson;
498 outtsysCol.get(i, tsyson);
499 outspecCol.get(i, specon);
500 Vector<uChar> flagon;
501 outflagCol.get(i, flagon);
502 MaskedArray<Float> mon = maskedArray(specon, flagon);
503 MaskedArray<Float> moff = maskedArray(*specoff, *flagoff);
504 MaskedArray<Float> quot = (tsysoffscalar * mon / moff);
505 if (preserve) {
506 quot -= tsysoffscalar;
507 } else {
508 quot -= tsyson[0];
509 }
510 outspecCol.put(i, quot.getArray());
511 outflagCol.put(i, flagsFromMA(quot));
512 }
513 ++sit;
514 ++s2it;
515 // take the first off for each on scan which doesn't have a
516 // matching off scan
517 // non <= noff: matching pairs, non > noff matching pairs then first off
518 if ( s2it.pastEnd() ) s2it.reset();
519 }
520 return out;
521}
522
523
[805]524CountedPtr< Scantable > STMath::freqSwitch( const CountedPtr< Scantable >& in )
525{
526 // make copy or reference
527 CountedPtr< Scantable > out = getScantable(in, false);
528 Table& tout = out->table();
[1008]529 Block<String> cols(4);
[805]530 cols[0] = String("SCANNO");
[1008]531 cols[1] = String("CYCLENO");
532 cols[2] = String("BEAMNO");
533 cols[3] = String("POLNO");
[805]534 TableIterator iter(tout, cols);
535 while (!iter.pastEnd()) {
536 Table subt = iter.table();
537 // this should leave us with two rows for the two IFs....if not ignore
538 if (subt.nrow() != 2 ) {
539 continue;
[701]540 }
[1008]541 ArrayColumn<Float> specCol(subt, "SPECTRA");
542 ArrayColumn<Float> tsysCol(subt, "TSYS");
543 ArrayColumn<uChar> flagCol(subt, "FLAGTRA");
[805]544 Vector<Float> onspec,offspec, ontsys, offtsys;
545 Vector<uChar> onflag, offflag;
546 tsysCol.get(0, ontsys); tsysCol.get(1, offtsys);
547 specCol.get(0, onspec); specCol.get(1, offspec);
548 flagCol.get(0, onflag); flagCol.get(1, offflag);
549 MaskedArray<Float> on = maskedArray(onspec, onflag);
550 MaskedArray<Float> off = maskedArray(offspec, offflag);
551 MaskedArray<Float> oncopy = on.copy();
[248]552
[805]553 on /= off; on -= 1.0f;
554 on *= ontsys[0];
555 off /= oncopy; off -= 1.0f;
556 off *= offtsys[0];
557 specCol.put(0, on.getArray());
558 const Vector<Bool>& m0 = on.getMask();
559 Vector<uChar> flags0(m0.shape());
560 convertArray(flags0, !m0);
561 flagCol.put(0, flags0);
[234]562
[805]563 specCol.put(1, off.getArray());
564 const Vector<Bool>& m1 = off.getMask();
565 Vector<uChar> flags1(m1.shape());
566 convertArray(flags1, !m1);
567 flagCol.put(1, flags1);
[867]568 ++iter;
[130]569 }
[780]570
[805]571 return out;
[9]572}
[48]573
[805]574std::vector< float > STMath::statistic( const CountedPtr< Scantable > & in,
575 const std::vector< bool > & mask,
576 const std::string& which )
[130]577{
578
[805]579 Vector<Bool> m(mask);
580 const Table& tab = in->table();
581 ROArrayColumn<Float> specCol(tab, "SPECTRA");
582 ROArrayColumn<uChar> flagCol(tab, "FLAGTRA");
583 std::vector<float> out;
584 for (uInt i=0; i < tab.nrow(); ++i ) {
585 Vector<Float> spec; specCol.get(i, spec);
[867]586 Vector<uChar> flag; flagCol.get(i, flag);
587 MaskedArray<Float> ma = maskedArray(spec, flag);
588 float outstat = 0.0;
[805]589 if ( spec.nelements() == m.nelements() ) {
590 outstat = mathutil::statistics(which, ma(m));
591 } else {
592 outstat = mathutil::statistics(which, ma);
593 }
594 out.push_back(outstat);
[234]595 }
[805]596 return out;
[130]597}
598
[805]599CountedPtr< Scantable > STMath::bin( const CountedPtr< Scantable > & in,
600 int width )
[144]601{
[841]602 if ( !in->getSelection().empty() ) throw(AipsError("Can't bin subset of the data."));
[805]603 CountedPtr< Scantable > out = getScantable(in, false);
604 Table& tout = out->table();
605 out->frequencies().rescale(width, "BIN");
606 ArrayColumn<Float> specCol(tout, "SPECTRA");
607 ArrayColumn<uChar> flagCol(tout, "FLAGTRA");
608 for (uInt i=0; i < tout.nrow(); ++i ) {
609 MaskedArray<Float> main = maskedArray(specCol(i), flagCol(i));
610 MaskedArray<Float> maout;
611 LatticeUtilities::bin(maout, main, 0, Int(width));
612 /// @todo implement channel based tsys binning
613 specCol.put(i, maout.getArray());
614 flagCol.put(i, flagsFromMA(maout));
615 // take only the first binned spectrum's length for the deprecated
616 // global header item nChan
617 if (i==0) tout.rwKeywordSet().define(String("nChan"),
618 Int(maout.getArray().nelements()));
[169]619 }
[805]620 return out;
[146]621}
622
[805]623CountedPtr< Scantable > STMath::resample( const CountedPtr< Scantable >& in,
624 const std::string& method,
625 float width )
[299]626//
627// Should add the possibility of width being specified in km/s. This means
[780]628// that for each freqID (SpectralCoordinate) we will need to convert to an
629// average channel width (say at the reference pixel). Then we would need
630// to be careful to make sure each spectrum (of different freqID)
[299]631// is the same length.
632//
633{
[996]634 //InterpolateArray1D<Double,Float>::InterpolationMethod interp;
[805]635 Int interpMethod(stringToIMethod(method));
[299]636
[805]637 CountedPtr< Scantable > out = getScantable(in, false);
638 Table& tout = out->table();
[299]639
640// Resample SpectralCoordinates (one per freqID)
[805]641 out->frequencies().rescale(width, "RESAMPLE");
642 TableIterator iter(tout, "IFNO");
643 TableRow row(tout);
644 while ( !iter.pastEnd() ) {
645 Table tab = iter.table();
646 ArrayColumn<Float> specCol(tab, "SPECTRA");
647 //ArrayColumn<Float> tsysCol(tout, "TSYS");
648 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
649 Vector<Float> spec;
650 Vector<uChar> flag;
651 specCol.get(0,spec); // the number of channels should be constant per IF
652 uInt nChanIn = spec.nelements();
653 Vector<Float> xIn(nChanIn); indgen(xIn);
654 Int fac = Int(nChanIn/width);
655 Vector<Float> xOut(fac+10); // 10 to be safe - resize later
656 uInt k = 0;
657 Float x = 0.0;
658 while (x < Float(nChanIn) ) {
659 xOut(k) = x;
660 k++;
661 x += width;
662 }
663 uInt nChanOut = k;
664 xOut.resize(nChanOut, True);
665 // process all rows for this IFNO
666 Vector<Float> specOut;
667 Vector<Bool> maskOut;
668 Vector<uChar> flagOut;
669 for (uInt i=0; i < tab.nrow(); ++i) {
670 specCol.get(i, spec);
671 flagCol.get(i, flag);
672 Vector<Bool> mask(flag.nelements());
673 convertArray(mask, flag);
[299]674
[805]675 IPosition shapeIn(spec.shape());
676 //sh.nchan = nChanOut;
677 InterpolateArray1D<Float,Float>::interpolate(specOut, maskOut, xOut,
678 xIn, spec, mask,
679 interpMethod, True, True);
680 /// @todo do the same for channel based Tsys
681 flagOut.resize(maskOut.nelements());
682 convertArray(flagOut, maskOut);
683 specCol.put(i, specOut);
684 flagCol.put(i, flagOut);
685 }
686 ++iter;
[299]687 }
688
[805]689 return out;
690}
[299]691
[805]692STMath::imethod STMath::stringToIMethod(const std::string& in)
693{
694 static STMath::imap lookup;
[299]695
[805]696 // initialize the lookup table if necessary
697 if ( lookup.empty() ) {
[926]698 lookup["nearest"] = InterpolateArray1D<Double,Float>::nearestNeighbour;
699 lookup["linear"] = InterpolateArray1D<Double,Float>::linear;
700 lookup["cubic"] = InterpolateArray1D<Double,Float>::cubic;
701 lookup["spline"] = InterpolateArray1D<Double,Float>::spline;
[299]702 }
703
[805]704 STMath::imap::const_iterator iter = lookup.find(in);
[299]705
[805]706 if ( lookup.end() == iter ) {
707 std::string message = in;
708 message += " is not a valid interpolation mode";
709 throw(AipsError(message));
[299]710 }
[805]711 return iter->second;
[299]712}
713
[805]714WeightType STMath::stringToWeight(const std::string& in)
[146]715{
[805]716 static std::map<std::string, WeightType> lookup;
[434]717
[805]718 // initialize the lookup table if necessary
719 if ( lookup.empty() ) {
720 lookup["NONE"] = asap::NONE;
721 lookup["TINT"] = asap::TINT;
722 lookup["TINTSYS"] = asap::TINTSYS;
723 lookup["TSYS"] = asap::TSYS;
724 lookup["VAR"] = asap::VAR;
725 }
[434]726
[805]727 std::map<std::string, WeightType>::const_iterator iter = lookup.find(in);
[294]728
[805]729 if ( lookup.end() == iter ) {
730 std::string message = in;
731 message += " is not a valid weighting mode";
732 throw(AipsError(message));
733 }
734 return iter->second;
[146]735}
736
[805]737CountedPtr< Scantable > STMath::gainElevation( const CountedPtr< Scantable >& in,
[867]738 const vector< float > & coeff,
[805]739 const std::string & filename,
740 const std::string& method)
[165]741{
[805]742 // Get elevation data from Scantable and convert to degrees
743 CountedPtr< Scantable > out = getScantable(in, false);
[926]744 Table& tab = out->table();
[805]745 ROScalarColumn<Float> elev(tab, "ELEVATION");
746 Vector<Float> x = elev.getColumn();
747 x *= Float(180 / C::pi); // Degrees
[165]748
[867]749 Vector<Float> coeffs(coeff);
[805]750 const uInt nc = coeffs.nelements();
751 if ( filename.length() > 0 && nc > 0 ) {
752 throw(AipsError("You must choose either polynomial coefficients or an ascii file, not both"));
[315]753 }
[165]754
[805]755 // Correct
756 if ( nc > 0 || filename.length() == 0 ) {
757 // Find instrument
758 Bool throwit = True;
759 Instrument inst =
[878]760 STAttr::convertInstrument(tab.keywordSet().asString("AntennaName"),
[805]761 throwit);
[165]762
[805]763 // Set polynomial
764 Polynomial<Float>* ppoly = 0;
765 Vector<Float> coeff;
766 String msg;
767 if ( nc > 0 ) {
768 ppoly = new Polynomial<Float>(nc);
769 coeff = coeffs;
770 msg = String("user");
771 } else {
[878]772 STAttr sdAttr;
[805]773 coeff = sdAttr.gainElevationPoly(inst);
774 ppoly = new Polynomial<Float>(3);
775 msg = String("built in");
776 }
[532]777
[805]778 if ( coeff.nelements() > 0 ) {
779 ppoly->setCoefficients(coeff);
780 } else {
781 delete ppoly;
782 throw(AipsError("There is no known gain-elevation polynomial known for this instrument"));
783 }
784 ostringstream oss;
785 oss << "Making polynomial correction with " << msg << " coefficients:" << endl;
786 oss << " " << coeff;
787 pushLog(String(oss));
788 const uInt nrow = tab.nrow();
789 Vector<Float> factor(nrow);
790 for ( uInt i=0; i < nrow; ++i ) {
791 factor[i] = 1.0 / (*ppoly)(x[i]);
792 }
793 delete ppoly;
794 scaleByVector(tab, factor, true);
[532]795
[805]796 } else {
797 // Read and correct
798 pushLog("Making correction from ascii Table");
799 scaleFromAsciiTable(tab, filename, method, x, true);
[532]800 }
[805]801 return out;
802}
[165]803
[805]804void STMath::scaleFromAsciiTable(Table& in, const std::string& filename,
805 const std::string& method,
806 const Vector<Float>& xout, bool dotsys)
807{
[165]808
[805]809// Read gain-elevation ascii file data into a Table.
[165]810
[805]811 String formatString;
812 Table tbl = readAsciiTable(formatString, Table::Memory, filename, "", "", False);
813 scaleFromTable(in, tbl, method, xout, dotsys);
814}
[165]815
[805]816void STMath::scaleFromTable(Table& in,
817 const Table& table,
818 const std::string& method,
819 const Vector<Float>& xout, bool dotsys)
820{
[780]821
[805]822 ROScalarColumn<Float> geElCol(table, "ELEVATION");
823 ROScalarColumn<Float> geFacCol(table, "FACTOR");
824 Vector<Float> xin = geElCol.getColumn();
825 Vector<Float> yin = geFacCol.getColumn();
826 Vector<Bool> maskin(xin.nelements(),True);
[165]827
[805]828 // Interpolate (and extrapolate) with desired method
[532]829
[996]830 InterpolateArray1D<Double,Float>::InterpolationMethod interp = stringToIMethod(method);
[165]831
[805]832 Vector<Float> yout;
833 Vector<Bool> maskout;
834 InterpolateArray1D<Float,Float>::interpolate(yout, maskout, xout,
[996]835 xin, yin, maskin, interp,
[805]836 True, True);
[165]837
[805]838 scaleByVector(in, Float(1.0)/yout, dotsys);
[165]839}
[167]840
[805]841void STMath::scaleByVector( Table& in,
842 const Vector< Float >& factor,
843 bool dotsys )
[177]844{
[805]845 uInt nrow = in.nrow();
846 if ( factor.nelements() != nrow ) {
847 throw(AipsError("factors.nelements() != table.nelements()"));
848 }
849 ArrayColumn<Float> specCol(in, "SPECTRA");
850 ArrayColumn<uChar> flagCol(in, "FLAGTRA");
851 ArrayColumn<Float> tsysCol(in, "TSYS");
852 for (uInt i=0; i < nrow; ++i) {
853 MaskedArray<Float> ma = maskedArray(specCol(i), flagCol(i));
854 ma *= factor[i];
855 specCol.put(i, ma.getArray());
856 flagCol.put(i, flagsFromMA(ma));
857 if ( dotsys ) {
[926]858 Vector<Float> tsys = tsysCol(i);
[805]859 tsys *= factor[i];
[926]860 tsysCol.put(i,tsys);
[805]861 }
862 }
[177]863}
864
[805]865CountedPtr< Scantable > STMath::convertFlux( const CountedPtr< Scantable >& in,
866 float d, float etaap,
867 float jyperk )
[221]868{
[805]869 CountedPtr< Scantable > out = getScantable(in, false);
870 Table& tab = in->table();
871 Unit fluxUnit(tab.keywordSet().asString("FluxUnit"));
[221]872 Unit K(String("K"));
873 Unit JY(String("Jy"));
[701]874
[805]875 bool tokelvin = true;
876 Double cfac = 1.0;
[716]877
[805]878 if ( fluxUnit == JY ) {
[716]879 pushLog("Converting to K");
[701]880 Quantum<Double> t(1.0,fluxUnit);
881 Quantum<Double> t2 = t.get(JY);
[805]882 cfac = (t2 / t).getValue(); // value to Jy
[780]883
[805]884 tokelvin = true;
885 out->setFluxUnit("K");
886 } else if ( fluxUnit == K ) {
[716]887 pushLog("Converting to Jy");
[701]888 Quantum<Double> t(1.0,fluxUnit);
889 Quantum<Double> t2 = t.get(K);
[805]890 cfac = (t2 / t).getValue(); // value to K
[780]891
[805]892 tokelvin = false;
893 out->setFluxUnit("Jy");
[221]894 } else {
[701]895 throw(AipsError("Unrecognized brightness units in Table - must be consistent with Jy or K"));
[221]896 }
[701]897 // Make sure input values are converted to either Jy or K first...
[805]898 Float factor = cfac;
[221]899
[701]900 // Select method
[805]901 if (jyperk > 0.0) {
902 factor *= jyperk;
903 if ( tokelvin ) factor = 1.0 / jyperk;
[716]904 ostringstream oss;
[805]905 oss << "Jy/K = " << jyperk;
[716]906 pushLog(String(oss));
[805]907 Vector<Float> factors(tab.nrow(), factor);
908 scaleByVector(tab,factors, false);
909 } else if ( etaap > 0.0) {
[1319]910 if (d < 0) {
911 Instrument inst =
912 STAttr::convertInstrument(tab.keywordSet().asString("AntennaName"),
913 True);
914 STAttr sda;
915 d = sda.diameter(inst);
916 }
[996]917 jyperk = STAttr::findJyPerK(etaap, d);
[716]918 ostringstream oss;
[805]919 oss << "Jy/K = " << jyperk;
[716]920 pushLog(String(oss));
[805]921 factor *= jyperk;
922 if ( tokelvin ) {
[701]923 factor = 1.0 / factor;
924 }
[805]925 Vector<Float> factors(tab.nrow(), factor);
926 scaleByVector(tab, factors, False);
[354]927 } else {
[780]928
[701]929 // OK now we must deal with automatic look up of values.
930 // We must also deal with the fact that the factors need
931 // to be computed per IF and may be different and may
932 // change per integration.
[780]933
[716]934 pushLog("Looking up conversion factors");
[805]935 convertBrightnessUnits(out, tokelvin, cfac);
[701]936 }
[805]937
938 return out;
[221]939}
940
[805]941void STMath::convertBrightnessUnits( CountedPtr<Scantable>& in,
942 bool tokelvin, float cfac )
[227]943{
[805]944 Table& table = in->table();
945 Instrument inst =
[878]946 STAttr::convertInstrument(table.keywordSet().asString("AntennaName"), True);
[805]947 TableIterator iter(table, "FREQ_ID");
948 STFrequencies stfreqs = in->frequencies();
[878]949 STAttr sdAtt;
[805]950 while (!iter.pastEnd()) {
951 Table tab = iter.table();
952 ArrayColumn<Float> specCol(tab, "SPECTRA");
953 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
954 ROScalarColumn<uInt> freqidCol(tab, "FREQ_ID");
955 MEpoch::ROScalarColumn timeCol(tab, "TIME");
[234]956
[805]957 uInt freqid; freqidCol.get(0, freqid);
958 Vector<Float> tmpspec; specCol.get(0, tmpspec);
[878]959 // STAttr.JyPerK has a Vector interface... change sometime.
[805]960 Vector<Float> freqs(1,stfreqs.getRefFreq(freqid, tmpspec.nelements()));
961 for ( uInt i=0; i<tab.nrow(); ++i) {
962 Float jyperk = (sdAtt.JyPerK(inst, timeCol(i), freqs))[0];
963 Float factor = cfac * jyperk;
964 if ( tokelvin ) factor = Float(1.0) / factor;
965 MaskedArray<Float> ma = maskedArray(specCol(i), flagCol(i));
966 ma *= factor;
967 specCol.put(i, ma.getArray());
968 flagCol.put(i, flagsFromMA(ma));
969 }
[867]970 ++iter;
[234]971 }
[230]972}
[227]973
[805]974CountedPtr< Scantable > STMath::opacity( const CountedPtr< Scantable > & in,
975 float tau )
[234]976{
[805]977 CountedPtr< Scantable > out = getScantable(in, false);
[926]978
979 Table tab = out->table();
[234]980 ROScalarColumn<Float> elev(tab, "ELEVATION");
[805]981 ArrayColumn<Float> specCol(tab, "SPECTRA");
982 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
983 for ( uInt i=0; i<tab.nrow(); ++i) {
984 Float zdist = Float(C::pi_2) - elev(i);
[1318]985 Float factor = exp(tau/cos(zdist));
[926]986 MaskedArray<Float> ma = maskedArray(specCol(i), flagCol(i));
[805]987 ma *= factor;
988 specCol.put(i, ma.getArray());
989 flagCol.put(i, flagsFromMA(ma));
[234]990 }
[805]991 return out;
[234]992}
993
[805]994CountedPtr< Scantable > STMath::smooth( const CountedPtr< Scantable >& in,
995 const std::string& kernel, float width )
[457]996{
[805]997 CountedPtr< Scantable > out = getScantable(in, false);
[1033]998 Table& table = out->table();
[805]999 VectorKernel::KernelTypes type = VectorKernel::toKernelType(kernel);
1000 // same IFNO should have same no of channels
1001 // this saves overhead
1002 TableIterator iter(table, "IFNO");
1003 while (!iter.pastEnd()) {
1004 Table tab = iter.table();
1005 ArrayColumn<Float> specCol(tab, "SPECTRA");
1006 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
1007 Vector<Float> tmpspec; specCol.get(0, tmpspec);
1008 uInt nchan = tmpspec.nelements();
1009 Vector<Float> kvec = VectorKernel::make(type, width, nchan, True, False);
1010 Convolver<Float> conv(kvec, IPosition(1,nchan));
1011 Vector<Float> spec;
1012 Vector<uChar> flag;
1013 for ( uInt i=0; i<tab.nrow(); ++i) {
1014 specCol.get(i, spec);
1015 flagCol.get(i, flag);
1016 Vector<Bool> mask(flag.nelements());
1017 convertArray(mask, flag);
1018 Vector<Float> specout;
1019 if ( type == VectorKernel::HANNING ) {
1020 Vector<Bool> maskout;
[1033]1021 mathutil::hanning(specout, maskout, spec , !mask);
1022 convertArray(flag, !maskout);
[805]1023 flagCol.put(i, flag);
[1033]1024 specCol.put(i, specout);
1025 } else {
[805]1026 mathutil::replaceMaskByZero(specout, mask);
1027 conv.linearConv(specout, spec);
[1033]1028 specCol.put(i, specout);
[354]1029 }
[805]1030 }
[867]1031 ++iter;
[701]1032 }
[805]1033 return out;
[701]1034}
[841]1035
1036CountedPtr< Scantable >
1037 STMath::merge( const std::vector< CountedPtr < Scantable > >& in )
1038{
1039 if ( in.size() < 2 ) {
[862]1040 throw(AipsError("Need at least two scantables to perform a merge."));
[841]1041 }
1042 std::vector<CountedPtr < Scantable > >::const_iterator it = in.begin();
1043 bool insitu = insitu_;
1044 setInsitu(false);
[862]1045 CountedPtr< Scantable > out = getScantable(*it, false);
[841]1046 setInsitu(insitu);
1047 Table& tout = out->table();
1048 ScalarColumn<uInt> freqidcol(tout,"FREQ_ID"), molidcol(tout, "MOLECULE_ID");
[917]1049 ScalarColumn<uInt> scannocol(tout,"SCANNO"), focusidcol(tout,"FOCUS_ID");
1050 // Renumber SCANNO to be 0-based
[926]1051 Vector<uInt> scannos = scannocol.getColumn();
1052 uInt offset = min(scannos);
[917]1053 scannos -= offset;
[926]1054 scannocol.putColumn(scannos);
1055 uInt newscanno = max(scannos)+1;
[862]1056 ++it;
[841]1057 while ( it != in.end() ){
1058 if ( ! (*it)->conformant(*out) ) {
1059 // log message: "ignoring scantable i, as it isn't
1060 // conformant with the other(s)"
1061 cerr << "oh oh" << endl;
1062 ++it;
1063 continue;
1064 }
[862]1065 out->appendToHistoryTable((*it)->history());
[841]1066 const Table& tab = (*it)->table();
1067 TableIterator scanit(tab, "SCANNO");
1068 while (!scanit.pastEnd()) {
1069 TableIterator freqit(scanit.table(), "FREQ_ID");
1070 while ( !freqit.pastEnd() ) {
1071 Table thetab = freqit.table();
1072 uInt nrow = tout.nrow();
1073 //tout.addRow(thetab.nrow());
1074 TableCopy::copyRows(tout, thetab, nrow, 0, thetab.nrow());
1075 ROTableRow row(thetab);
1076 for ( uInt i=0; i<thetab.nrow(); ++i) {
1077 uInt k = nrow+i;
1078 scannocol.put(k, newscanno);
1079 const TableRecord& rec = row.get(i);
1080 Double rv,rp,inc;
1081 (*it)->frequencies().getEntry(rp, rv, inc, rec.asuInt("FREQ_ID"));
1082 uInt id;
1083 id = out->frequencies().addEntry(rp, rv, inc);
1084 freqidcol.put(k,id);
1085 String name,fname;Double rf;
1086 (*it)->molecules().getEntry(rf, name, fname, rec.asuInt("MOLECULE_ID"));
1087 id = out->molecules().addEntry(rf, name, fname);
1088 molidcol.put(k, id);
[961]1089 Float frot,fax,ftan,fhand,fmount,fuser, fxy, fxyp;
1090 (*it)->focus().getEntry(fax, ftan, frot, fhand,
1091 fmount,fuser, fxy, fxyp,
1092 rec.asuInt("FOCUS_ID"));
1093 id = out->focus().addEntry(fax, ftan, frot, fhand,
1094 fmount,fuser, fxy, fxyp);
[841]1095 focusidcol.put(k, id);
1096 }
1097 ++freqit;
1098 }
1099 ++newscanno;
1100 ++scanit;
1101 }
1102 ++it;
1103 }
1104 return out;
1105}
[896]1106
1107CountedPtr< Scantable >
1108 STMath::invertPhase( const CountedPtr < Scantable >& in )
1109{
[996]1110 return applyToPol(in, &STPol::invertPhase, Float(0.0));
[896]1111}
1112
1113CountedPtr< Scantable >
1114 STMath::rotateXYPhase( const CountedPtr < Scantable >& in, float phase )
1115{
1116 return applyToPol(in, &STPol::rotatePhase, Float(phase));
1117}
1118
1119CountedPtr< Scantable >
1120 STMath::rotateLinPolPhase( const CountedPtr < Scantable >& in, float phase )
1121{
1122 return applyToPol(in, &STPol::rotateLinPolPhase, Float(phase));
1123}
1124
1125CountedPtr< Scantable > STMath::applyToPol( const CountedPtr<Scantable>& in,
1126 STPol::polOperation fptr,
1127 Float phase )
1128{
1129 CountedPtr< Scantable > out = getScantable(in, false);
1130 Table& tout = out->table();
1131 Block<String> cols(4);
1132 cols[0] = String("SCANNO");
1133 cols[1] = String("BEAMNO");
1134 cols[2] = String("IFNO");
1135 cols[3] = String("CYCLENO");
1136 TableIterator iter(tout, cols);
[1015]1137 STPol* stpol = STPol::getPolClass(out->factories_, out->getPolType() );
[896]1138 while (!iter.pastEnd()) {
1139 Table t = iter.table();
1140 ArrayColumn<Float> speccol(t, "SPECTRA");
[1015]1141 ScalarColumn<uInt> focidcol(t, "FOCUS_ID");
1142 ScalarColumn<Float> parancol(t, "PARANGLE");
[896]1143 Matrix<Float> pols = speccol.getColumn();
1144 try {
1145 stpol->setSpectra(pols);
[1015]1146 Float fang,fhand,parang;
1147 fang = in->focusTable_.getTotalFeedAngle(focidcol(0));
1148 fhand = in->focusTable_.getFeedHand(focidcol(0));
1149 parang = parancol(0);
1150 /// @todo re-enable this
1151 // disable total feed angle to support paralactifying Caswell style
1152 stpol->setPhaseCorrections(parang, -parang, fhand);
[896]1153 (stpol->*fptr)(phase);
1154 speccol.putColumn(stpol->getSpectra());
[1015]1155 Matrix<Float> tmp = stpol->getSpectra();
[896]1156 } catch (AipsError& e) {
1157 delete stpol;stpol=0;
1158 throw(e);
1159 }
1160 ++iter;
1161 }
[934]1162 delete stpol;stpol=0;
[896]1163 return out;
1164}
1165
1166CountedPtr< Scantable >
1167 STMath::swapPolarisations( const CountedPtr< Scantable > & in )
1168{
1169 CountedPtr< Scantable > out = getScantable(in, false);
1170 Table& tout = out->table();
1171 Table t0 = tout(tout.col("POLNO") == 0);
1172 Table t1 = tout(tout.col("POLNO") == 1);
1173 if ( t0.nrow() != t1.nrow() )
1174 throw(AipsError("Inconsistent number of polarisations"));
1175 ArrayColumn<Float> speccol0(t0, "SPECTRA");
1176 ArrayColumn<uChar> flagcol0(t0, "FLAGTRA");
1177 ArrayColumn<Float> speccol1(t1, "SPECTRA");
1178 ArrayColumn<uChar> flagcol1(t1, "FLAGTRA");
1179 Matrix<Float> s0 = speccol0.getColumn();
1180 Matrix<uChar> f0 = flagcol0.getColumn();
1181 speccol0.putColumn(speccol1.getColumn());
1182 flagcol0.putColumn(flagcol1.getColumn());
1183 speccol1.putColumn(s0);
1184 flagcol1.putColumn(f0);
1185 return out;
1186}
[917]1187
1188CountedPtr< Scantable >
[940]1189 STMath::averagePolarisations( const CountedPtr< Scantable > & in,
1190 const std::vector<bool>& mask,
1191 const std::string& weight )
1192{
[1232]1193 if (in->npol() < 2 )
1194 throw(AipsError("averagePolarisations can only be applied to two or more"
1195 "polarisations"));
[1010]1196 bool insitu = insitu_;
1197 setInsitu(false);
[1232]1198 CountedPtr< Scantable > pols = getScantable(in, true);
[1010]1199 setInsitu(insitu);
1200 Table& tout = pols->table();
[1232]1201 std::string taql = "SELECT FROM $1 WHERE POLNO IN [0,1]";
1202 Table tab = tableCommand(taql, in->table());
1203 if (tab.nrow() == 0 )
1204 throw(AipsError("Could not find any rows with POLNO==0 and POLNO==1"));
1205 TableCopy::copyRows(tout, tab);
[1145]1206 TableVector<uInt> vec(tout, "POLNO");
[940]1207 vec = 0;
[1145]1208 pols->table_.rwKeywordSet().define("nPol", Int(1));
[1232]1209 pols->table_.rwKeywordSet().define("POLTYPE", String("stokes"));
[1010]1210 std::vector<CountedPtr<Scantable> > vpols;
1211 vpols.push_back(pols);
[1232]1212 CountedPtr< Scantable > out = average(vpols, mask, weight, "SCAN");
[940]1213 return out;
1214}
1215
[1145]1216CountedPtr< Scantable >
1217 STMath::averageBeams( const CountedPtr< Scantable > & in,
1218 const std::vector<bool>& mask,
1219 const std::string& weight )
1220{
1221 bool insitu = insitu_;
1222 setInsitu(false);
1223 CountedPtr< Scantable > beams = getScantable(in, false);
1224 setInsitu(insitu);
1225 Table& tout = beams->table();
1226 // give all rows the same BEAMNO
1227 TableVector<uInt> vec(tout, "BEAMNO");
1228 vec = 0;
1229 beams->table_.rwKeywordSet().define("nBeam", Int(1));
1230 std::vector<CountedPtr<Scantable> > vbeams;
1231 vbeams.push_back(beams);
[1232]1232 CountedPtr< Scantable > out = average(vbeams, mask, weight, "SCAN");
[1145]1233 return out;
1234}
[940]1235
[1145]1236
[940]1237CountedPtr< Scantable >
[917]1238 asap::STMath::frequencyAlign( const CountedPtr< Scantable > & in,
1239 const std::string & refTime,
[926]1240 const std::string & method)
[917]1241{
[940]1242 // clone as this is not working insitu
1243 bool insitu = insitu_;
1244 setInsitu(false);
[917]1245 CountedPtr< Scantable > out = getScantable(in, false);
[940]1246 setInsitu(insitu);
[917]1247 Table& tout = out->table();
1248 // Get reference Epoch to time of first row or given String
1249 Unit DAY(String("d"));
1250 MEpoch::Ref epochRef(in->getTimeReference());
1251 MEpoch refEpoch;
1252 if (refTime.length()>0) {
1253 Quantum<Double> qt;
1254 if (MVTime::read(qt,refTime)) {
1255 MVEpoch mv(qt);
1256 refEpoch = MEpoch(mv, epochRef);
1257 } else {
1258 throw(AipsError("Invalid format for Epoch string"));
1259 }
1260 } else {
1261 refEpoch = in->timeCol_(0);
1262 }
1263 MPosition refPos = in->getAntennaPosition();
[940]1264
[996]1265 InterpolateArray1D<Double,Float>::InterpolationMethod interp = stringToIMethod(method);
[917]1266 // test if user frame is different to base frame
1267 if ( in->frequencies().getFrameString(true)
1268 == in->frequencies().getFrameString(false) ) {
[985]1269 throw(AipsError("Can't convert as no output frame has been set"
1270 " (use set_freqframe) or it is aligned already."));
[917]1271 }
1272 MFrequency::Types system = in->frequencies().getFrame();
[940]1273 MVTime mvt(refEpoch.getValue());
1274 String epochout = mvt.string(MVTime::YMD) + String(" (") + refEpoch.getRefString() + String(")");
1275 ostringstream oss;
1276 oss << "Aligned at reference Epoch " << epochout
1277 << " in frame " << MFrequency::showType(system);
1278 pushLog(String(oss));
[917]1279 // set up the iterator
[926]1280 Block<String> cols(4);
1281 // select by constant direction
[917]1282 cols[0] = String("SRCNAME");
1283 cols[1] = String("BEAMNO");
1284 // select by IF ( no of channels varies over this )
1285 cols[2] = String("IFNO");
[926]1286 // select by restfrequency
1287 cols[3] = String("MOLECULE_ID");
[917]1288 TableIterator iter(tout, cols);
[926]1289 while ( !iter.pastEnd() ) {
[917]1290 Table t = iter.table();
1291 MDirection::ROScalarColumn dirCol(t, "DIRECTION");
[926]1292 TableIterator fiter(t, "FREQ_ID");
[917]1293 // determine nchan from the first row. This should work as
[926]1294 // we are iterating over BEAMNO and IFNO // we should have constant direction
1295
[917]1296 ROArrayColumn<Float> sCol(t, "SPECTRA");
[926]1297 MDirection direction = dirCol(0);
[917]1298 uInt nchan = sCol(0).nelements();
[926]1299 while ( !fiter.pastEnd() ) {
1300 Table ftab = fiter.table();
1301 ScalarColumn<uInt> freqidCol(ftab, "FREQ_ID");
1302 // get the SpectralCoordinate for the freqid, which we are iterating over
1303 SpectralCoordinate sC = in->frequencies().getSpectralCoordinate(freqidCol(0));
1304 FrequencyAligner<Float> fa( sC, nchan, refEpoch,
1305 direction, refPos, system );
1306 // realign the SpectralCoordinate and put into the output Scantable
1307 Vector<String> units(1);
1308 units = String("Hz");
1309 Bool linear=True;
1310 SpectralCoordinate sc2 = fa.alignedSpectralCoordinate(linear);
1311 sc2.setWorldAxisUnits(units);
[934]1312 uInt id = out->frequencies().addEntry(sc2.referencePixel()[0],
1313 sc2.referenceValue()[0],
1314 sc2.increment()[0]);
1315 TableVector<uInt> tvec(ftab, "FREQ_ID");
1316 tvec = id;
[926]1317 // create the "global" abcissa for alignment with same FREQ_ID
1318 Vector<Double> abc(nchan);
[917]1319 Double w;
1320 for (uInt i=0; i<nchan; i++) {
1321 sC.toWorld(w,Double(i));
1322 abc[i] = w;
1323 }
[926]1324 // cache abcissa for same time stamps, so iterate over those
1325 TableIterator timeiter(ftab, "TIME");
1326 while ( !timeiter.pastEnd() ) {
1327 Table tab = timeiter.table();
1328 ArrayColumn<Float> specCol(tab, "SPECTRA");
1329 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
1330 MEpoch::ROScalarColumn timeCol(tab, "TIME");
1331 // use align abcissa cache after the first row
1332 bool first = true;
1333 // these rows should be just be POLNO
[996]1334 for (int i=0; i<int(tab.nrow()); ++i) {
[926]1335 // input values
1336 Vector<uChar> flag = flagCol(i);
1337 Vector<Bool> mask(flag.shape());
1338 Vector<Float> specOut, spec;
1339 spec = specCol(i);
1340 Vector<Bool> maskOut;Vector<uChar> flagOut;
1341 convertArray(mask, flag);
1342 // alignment
1343 Bool ok = fa.align(specOut, maskOut, abc, spec,
1344 mask, timeCol(i), !first,
1345 interp, False);
1346 // back into scantable
1347 flagOut.resize(maskOut.nelements());
1348 convertArray(flagOut, maskOut);
1349 flagCol.put(i, flagOut);
1350 specCol.put(i, specOut);
1351 // start abcissa caching
1352 first = false;
[917]1353 }
[926]1354 // next timestamp
1355 ++timeiter;
[917]1356 }
[940]1357 // next FREQ_ID
[926]1358 ++fiter;
[917]1359 }
1360 // next aligner
1361 ++iter;
1362 }
[940]1363 // set this afterwards to ensure we are doing insitu correctly.
1364 out->frequencies().setFrame(system, true);
[917]1365 return out;
1366}
[992]1367
1368CountedPtr<Scantable>
1369 asap::STMath::convertPolarisation( const CountedPtr<Scantable>& in,
1370 const std::string & newtype )
1371{
1372 if (in->npol() != 2 && in->npol() != 4)
1373 throw(AipsError("Can only convert two or four polarisations."));
1374 if ( in->getPolType() == newtype )
1375 throw(AipsError("No need to convert."));
[1000]1376 if ( ! in->selector_.empty() )
1377 throw(AipsError("Can only convert whole scantable. Unset the selection."));
[992]1378 bool insitu = insitu_;
1379 setInsitu(false);
1380 CountedPtr< Scantable > out = getScantable(in, true);
1381 setInsitu(insitu);
1382 Table& tout = out->table();
1383 tout.rwKeywordSet().define("POLTYPE", String(newtype));
1384
1385 Block<String> cols(4);
1386 cols[0] = "SCANNO";
1387 cols[1] = "CYCLENO";
1388 cols[2] = "BEAMNO";
1389 cols[3] = "IFNO";
1390 TableIterator it(in->originalTable_, cols);
1391 String basetype = in->getPolType();
1392 STPol* stpol = STPol::getPolClass(in->factories_, basetype);
1393 try {
1394 while ( !it.pastEnd() ) {
1395 Table tab = it.table();
1396 uInt row = tab.rowNumbers()[0];
1397 stpol->setSpectra(in->getPolMatrix(row));
1398 Float fang,fhand,parang;
1399 fang = in->focusTable_.getTotalFeedAngle(in->mfocusidCol_(row));
1400 fhand = in->focusTable_.getFeedHand(in->mfocusidCol_(row));
1401 parang = in->paraCol_(row);
1402 /// @todo re-enable this
1403 // disable total feed angle to support paralactifying Caswell style
1404 stpol->setPhaseCorrections(parang, -parang, fhand);
1405 Int npolout = 0;
1406 for (uInt i=0; i<tab.nrow(); ++i) {
1407 Vector<Float> outvec = stpol->getSpectrum(i, newtype);
1408 if ( outvec.nelements() > 0 ) {
1409 tout.addRow();
1410 TableCopy::copyRows(tout, tab, tout.nrow()-1, 0, 1);
1411 ArrayColumn<Float> sCol(tout,"SPECTRA");
1412 ScalarColumn<uInt> pCol(tout,"POLNO");
1413 sCol.put(tout.nrow()-1 ,outvec);
1414 pCol.put(tout.nrow()-1 ,uInt(npolout));
1415 npolout++;
1416 }
1417 }
1418 tout.rwKeywordSet().define("nPol", npolout);
1419 ++it;
1420 }
1421 } catch (AipsError& e) {
1422 delete stpol;
1423 throw(e);
1424 }
1425 delete stpol;
1426 return out;
1427}
[1066]1428
[1143]1429CountedPtr< Scantable >
[1140]1430 asap::STMath::mxExtract( const CountedPtr< Scantable > & in,
1431 const std::string & scantype )
1432{
1433 bool insitu = insitu_;
1434 setInsitu(false);
1435 CountedPtr< Scantable > out = getScantable(in, true);
1436 setInsitu(insitu);
1437 Table& tout = out->table();
1438 std::string taql = "SELECT FROM $1 WHERE BEAMNO != REFBEAMNO";
1439 if (scantype == "on") {
1440 taql = "SELECT FROM $1 WHERE BEAMNO == REFBEAMNO";
1441 }
1442 Table tab = tableCommand(taql, in->table());
1443 TableCopy::copyRows(tout, tab);
1444 if (scantype == "on") {
[1143]1445 // re-index SCANNO to 0
[1140]1446 TableVector<uInt> vec(tout, "SCANNO");
1447 vec = 0;
1448 }
1449 return out;
1450}
[1192]1451
1452CountedPtr< Scantable >
1453 asap::STMath::lagFlag( const CountedPtr< Scantable > & in,
[1200]1454 double frequency, double width )
[1192]1455{
1456 CountedPtr< Scantable > out = getScantable(in, false);
1457 Table& tout = out->table();
1458 TableIterator iter(tout, "FREQ_ID");
1459 FFTServer<Float,Complex> ffts;
1460 while ( !iter.pastEnd() ) {
1461 Table tab = iter.table();
1462 Double rp,rv,inc;
1463 ROTableRow row(tab);
1464 const TableRecord& rec = row.get(0);
1465 uInt freqid = rec.asuInt("FREQ_ID");
1466 out->frequencies().getEntry(rp, rv, inc, freqid);
1467 ArrayColumn<Float> specCol(tab, "SPECTRA");
1468 ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
1469 for (int i=0; i<int(tab.nrow()); ++i) {
1470 Vector<Float> spec = specCol(i);
1471 Vector<uChar> flag = flagCol(i);
[1200]1472 Int lag0 = Int(spec.nelements()*abs(inc)/(frequency+width)+0.5);
1473 Int lag1 = Int(spec.nelements()*abs(inc)/(frequency-width)+0.5);
[1192]1474 for (int k=0; k < flag.nelements(); ++k ) {
1475 if (flag[k] > 0) {
1476 spec[k] = 0.0;
1477 }
1478 }
1479 Vector<Complex> lags;
[1203]1480 ffts.fft0(lags, spec);
[1200]1481 Int start = max(0, lag0);
1482 Int end = min(Int(lags.nelements()-1), lag1);
[1192]1483 if (start == end) {
1484 lags[start] = Complex(0.0);
1485 } else {
1486 for (int j=start; j <=end ;++j) {
1487 lags[j] = Complex(0.0);
1488 }
1489 }
[1203]1490 ffts.fft0(spec, lags);
[1192]1491 specCol.put(i, spec);
1492 }
1493 ++iter;
1494 }
1495 return out;
1496}
Note: See TracBrowser for help on using the repository browser.