source: trunk/src/STMath.cpp @ 1072

Last change on this file since 1072 was 1069, checked in by mar637, 18 years ago

enhancement ticket #35. median scantable

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