source: trunk/src/STMath.cpp@ 1333

Last change on this file since 1333 was 1333, checked in by mar637, 17 years ago

Fix for Ticket #104; protect the user from flagging the whole scantable. This has performance penalties.

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