source: trunk/src/Scantable.cpp @ 973

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

removed debug info

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 27.3 KB
Line 
1//
2// C++ Implementation: Scantable
3//
4// Description:
5//
6//
7// Author: Malte Marquarding <asap@atnf.csiro.au>, (C) 2005
8//
9// Copyright: See COPYING file that comes with this distribution
10//
11//
12#include <map>
13
14#include <casa/aips.h>
15#include <casa/iostream.h>
16#include <casa/iomanip.h>
17#include <casa/OS/Path.h>
18#include <casa/OS/File.h>
19#include <casa/Arrays/Array.h>
20#include <casa/Arrays/ArrayMath.h>
21#include <casa/Arrays/MaskArrMath.h>
22#include <casa/Arrays/ArrayLogical.h>
23#include <casa/Arrays/ArrayAccessor.h>
24#include <casa/Arrays/VectorSTLIterator.h>
25#include <casa/Arrays/Vector.h>
26#include <casa/BasicMath/Math.h>
27#include <casa/BasicSL/Constants.h>
28#include <casa/Quanta/MVAngle.h>
29#include <casa/Containers/RecordField.h>
30#include <casa/Utilities/GenSort.h>
31
32#include <tables/Tables/TableParse.h>
33#include <tables/Tables/TableDesc.h>
34#include <tables/Tables/TableCopy.h>
35#include <tables/Tables/SetupNewTab.h>
36#include <tables/Tables/ScaColDesc.h>
37#include <tables/Tables/ArrColDesc.h>
38#include <tables/Tables/TableRow.h>
39#include <tables/Tables/TableVector.h>
40#include <tables/Tables/TableIter.h>
41
42#include <tables/Tables/ExprNode.h>
43#include <tables/Tables/TableRecord.h>
44#include <measures/Measures/MFrequency.h>
45#include <measures/Measures/MEpoch.h>
46#include <measures/Measures/MeasTable.h>
47#include <measures/Measures/MeasRef.h>
48#include <measures/TableMeasures/TableMeasRefDesc.h>
49#include <measures/TableMeasures/TableMeasValueDesc.h>
50#include <measures/TableMeasures/TableMeasDesc.h>
51#include <measures/TableMeasures/ScalarMeasColumn.h>
52#include <coordinates/Coordinates/CoordinateUtil.h>
53#include <casa/Quanta/MVTime.h>
54#include <casa/Quanta/MVAngle.h>
55
56#include "Scantable.h"
57#include "STPolLinear.h"
58#include "STPolStokes.h"
59#include "STAttr.h"
60#include "MathUtils.h"
61
62using namespace casa;
63
64namespace asap {
65
66std::map<std::string, STPol::STPolFactory *> Scantable::factories_;
67
68void Scantable::initFactories() {
69  if ( factories_.empty() ) {
70    Scantable::factories_["linear"] = &STPolLinear::myFactory;
71    Scantable::factories_["stokes"] = &STPolStokes::myFactory;
72  }
73}
74
75Scantable::Scantable(Table::TableType ttype) :
76  type_(ttype)
77{
78  initFactories();
79  setupMainTable();
80  freqTable_ = STFrequencies(*this);
81  table_.rwKeywordSet().defineTable("FREQUENCIES", freqTable_.table());
82  weatherTable_ = STWeather(*this);
83  table_.rwKeywordSet().defineTable("WEATHER", weatherTable_.table());
84  focusTable_ = STFocus(*this);
85  table_.rwKeywordSet().defineTable("FOCUS", focusTable_.table());
86  tcalTable_ = STTcal(*this);
87  table_.rwKeywordSet().defineTable("TCAL", tcalTable_.table());
88  moleculeTable_ = STMolecules(*this);
89  table_.rwKeywordSet().defineTable("MOLECULES", moleculeTable_.table());
90  historyTable_ = STHistory(*this);
91  table_.rwKeywordSet().defineTable("HISTORY", historyTable_.table());
92  fitTable_ = STFit(*this);
93  table_.rwKeywordSet().defineTable("FIT", fitTable_.table());
94  originalTable_ = table_;
95  attach();
96}
97
98Scantable::Scantable(const std::string& name, Table::TableType ttype) :
99  type_(ttype)
100{
101  initFactories();
102  Table tab(name, Table::Update);
103  Int version;
104  tab.keywordSet().get("VERSION", version);
105  if (version != version_) {
106    throw(AipsError("Unsupported version of ASAP file."));
107  }
108  if ( type_ == Table::Memory )
109    table_ = tab.copyToMemoryTable(generateName());
110  else
111    table_ = tab;
112  attachSubtables();
113  originalTable_ = table_;
114  attach();
115}
116
117Scantable::Scantable( const Scantable& other, bool clear )
118{
119  // with or without data
120  String newname = String(generateName());
121  type_ = other.table_.tableType();
122  if ( other.table_.tableType() == Table::Memory ) {
123      if ( clear ) {
124        table_ = TableCopy::makeEmptyMemoryTable(newname,
125                                                 other.table_, True);
126      } else
127        table_ = other.table_.copyToMemoryTable(newname);
128  } else {
129      other.table_.deepCopy(newname, Table::New, False,
130                            other.table_.endianFormat(),
131                            Bool(clear));
132      table_ = Table(newname, Table::Update);
133      table_.markForDelete();
134  }
135
136  if ( clear ) copySubtables(other);
137  attachSubtables();
138  originalTable_ = table_;
139  attach();
140}
141
142void Scantable::copySubtables(const Scantable& other) {
143  Table t = table_.rwKeywordSet().asTable("FREQUENCIES");
144  TableCopy::copyRows(t, other.freqTable_.table());
145  t = table_.rwKeywordSet().asTable("FOCUS");
146  TableCopy::copyRows(t, other.focusTable_.table());
147  t = table_.rwKeywordSet().asTable("WEATHER");
148  TableCopy::copyRows(t, other.weatherTable_.table());
149  t = table_.rwKeywordSet().asTable("TCAL");
150  TableCopy::copyRows(t, other.tcalTable_.table());
151  t = table_.rwKeywordSet().asTable("MOLECULES");
152  TableCopy::copyRows(t, other.moleculeTable_.table());
153  t = table_.rwKeywordSet().asTable("HISTORY");
154  TableCopy::copyRows(t, other.historyTable_.table());
155  t = table_.rwKeywordSet().asTable("FIT");
156  TableCopy::copyRows(t, other.fitTable_.table());
157}
158
159void Scantable::attachSubtables()
160{
161  freqTable_ = STFrequencies(table_);
162  focusTable_ = STFocus(table_);
163  weatherTable_ = STWeather(table_);
164  tcalTable_ = STTcal(table_);
165  moleculeTable_ = STMolecules(table_);
166  historyTable_ = STHistory(table_);
167  fitTable_ = STFit(table_);
168}
169
170Scantable::~Scantable()
171{
172  //cout << "~Scantable() " << this << endl;
173}
174
175void Scantable::setupMainTable()
176{
177  TableDesc td("", "1", TableDesc::Scratch);
178  td.comment() = "An ASAP Scantable";
179  td.rwKeywordSet().define("VERSION", Int(version_));
180
181  // n Cycles
182  td.addColumn(ScalarColumnDesc<uInt>("SCANNO"));
183  // new index every nBeam x nIF x nPol
184  td.addColumn(ScalarColumnDesc<uInt>("CYCLENO"));
185
186  td.addColumn(ScalarColumnDesc<uInt>("BEAMNO"));
187  td.addColumn(ScalarColumnDesc<uInt>("IFNO"));
188  // linear, circular, stokes
189  td.rwKeywordSet().define("POLTYPE", String("linear"));
190  td.addColumn(ScalarColumnDesc<uInt>("POLNO"));
191
192  td.addColumn(ScalarColumnDesc<uInt>("FREQ_ID"));
193  td.addColumn(ScalarColumnDesc<uInt>("MOLECULE_ID"));
194  td.addColumn(ScalarColumnDesc<Int>("REFBEAMNO"));
195
196  td.addColumn(ScalarColumnDesc<Double>("TIME"));
197  TableMeasRefDesc measRef(MEpoch::UTC); // UTC as default
198  TableMeasValueDesc measVal(td, "TIME");
199  TableMeasDesc<MEpoch> mepochCol(measVal, measRef);
200  mepochCol.write(td);
201
202  td.addColumn(ScalarColumnDesc<Double>("INTERVAL"));
203
204  td.addColumn(ScalarColumnDesc<String>("SRCNAME"));
205  // Type of source (on=0, off=1, other=-1)
206  td.addColumn(ScalarColumnDesc<Int>("SRCTYPE", Int(-1)));
207  td.addColumn(ScalarColumnDesc<String>("FIELDNAME"));
208
209  //The actual Data Vectors
210  td.addColumn(ArrayColumnDesc<Float>("SPECTRA"));
211  td.addColumn(ArrayColumnDesc<uChar>("FLAGTRA"));
212  td.addColumn(ArrayColumnDesc<Float>("TSYS"));
213
214  td.addColumn(ArrayColumnDesc<Double>("DIRECTION",
215                                       IPosition(1,2),
216                                       ColumnDesc::Direct));
217  TableMeasRefDesc mdirRef(MDirection::J2000); // default
218  TableMeasValueDesc tmvdMDir(td, "DIRECTION");
219  // the TableMeasDesc gives the column a type
220  TableMeasDesc<MDirection> mdirCol(tmvdMDir, mdirRef);
221  // writing create the measure column
222  mdirCol.write(td);
223  td.addColumn(ScalarColumnDesc<Float>("AZIMUTH"));
224  td.addColumn(ScalarColumnDesc<Float>("ELEVATION"));
225  td.addColumn(ScalarColumnDesc<Float>("PARANGLE"));
226
227  td.addColumn(ScalarColumnDesc<uInt>("TCAL_ID"));
228  ScalarColumnDesc<Int> fitColumn("FIT_ID");
229  fitColumn.setDefault(Int(-1));
230  td.addColumn(fitColumn);
231
232  td.addColumn(ScalarColumnDesc<uInt>("FOCUS_ID"));
233  td.addColumn(ScalarColumnDesc<uInt>("WEATHER_ID"));
234
235  td.rwKeywordSet().define("OBSMODE", String(""));
236
237  // Now create Table SetUp from the description.
238  SetupNewTable aNewTab(generateName(), td, Table::Scratch);
239  table_ = Table(aNewTab, type_, 0);
240  originalTable_ = table_;
241}
242
243
244void Scantable::attach()
245{
246  timeCol_.attach(table_, "TIME");
247  srcnCol_.attach(table_, "SRCNAME");
248  specCol_.attach(table_, "SPECTRA");
249  flagsCol_.attach(table_, "FLAGTRA");
250  tsysCol_.attach(table_, "TSYS");
251  cycleCol_.attach(table_,"CYCLENO");
252  scanCol_.attach(table_, "SCANNO");
253  beamCol_.attach(table_, "BEAMNO");
254  ifCol_.attach(table_, "IFNO");
255  polCol_.attach(table_, "POLNO");
256  integrCol_.attach(table_, "INTERVAL");
257  azCol_.attach(table_, "AZIMUTH");
258  elCol_.attach(table_, "ELEVATION");
259  dirCol_.attach(table_, "DIRECTION");
260  paraCol_.attach(table_, "PARANGLE");
261  fldnCol_.attach(table_, "FIELDNAME");
262  rbeamCol_.attach(table_, "REFBEAMNO");
263
264  mfitidCol_.attach(table_,"FIT_ID");
265  mfreqidCol_.attach(table_, "FREQ_ID");
266  mtcalidCol_.attach(table_, "TCAL_ID");
267  mfocusidCol_.attach(table_, "FOCUS_ID");
268  mmolidCol_.attach(table_, "MOLECULE_ID");
269}
270
271void Scantable::setHeader(const STHeader& sdh)
272{
273  table_.rwKeywordSet().define("nIF", sdh.nif);
274  table_.rwKeywordSet().define("nBeam", sdh.nbeam);
275  table_.rwKeywordSet().define("nPol", sdh.npol);
276  table_.rwKeywordSet().define("nChan", sdh.nchan);
277  table_.rwKeywordSet().define("Observer", sdh.observer);
278  table_.rwKeywordSet().define("Project", sdh.project);
279  table_.rwKeywordSet().define("Obstype", sdh.obstype);
280  table_.rwKeywordSet().define("AntennaName", sdh.antennaname);
281  table_.rwKeywordSet().define("AntennaPosition", sdh.antennaposition);
282  table_.rwKeywordSet().define("Equinox", sdh.equinox);
283  table_.rwKeywordSet().define("FreqRefFrame", sdh.freqref);
284  table_.rwKeywordSet().define("FreqRefVal", sdh.reffreq);
285  table_.rwKeywordSet().define("Bandwidth", sdh.bandwidth);
286  table_.rwKeywordSet().define("UTC", sdh.utc);
287  table_.rwKeywordSet().define("FluxUnit", sdh.fluxunit);
288  table_.rwKeywordSet().define("Epoch", sdh.epoch);
289  table_.rwKeywordSet().define("POLTYPE", sdh.poltype);
290}
291
292STHeader Scantable::getHeader() const
293{
294  STHeader sdh;
295  table_.keywordSet().get("nBeam",sdh.nbeam);
296  table_.keywordSet().get("nIF",sdh.nif);
297  table_.keywordSet().get("nPol",sdh.npol);
298  table_.keywordSet().get("nChan",sdh.nchan);
299  table_.keywordSet().get("Observer", sdh.observer);
300  table_.keywordSet().get("Project", sdh.project);
301  table_.keywordSet().get("Obstype", sdh.obstype);
302  table_.keywordSet().get("AntennaName", sdh.antennaname);
303  table_.keywordSet().get("AntennaPosition", sdh.antennaposition);
304  table_.keywordSet().get("Equinox", sdh.equinox);
305  table_.keywordSet().get("FreqRefFrame", sdh.freqref);
306  table_.keywordSet().get("FreqRefVal", sdh.reffreq);
307  table_.keywordSet().get("Bandwidth", sdh.bandwidth);
308  table_.keywordSet().get("UTC", sdh.utc);
309  table_.keywordSet().get("FluxUnit", sdh.fluxunit);
310  table_.keywordSet().get("Epoch", sdh.epoch);
311  table_.keywordSet().get("POLTYPE", sdh.poltype);
312  return sdh;
313}
314
315bool Scantable::conformant( const Scantable& other )
316{
317  return this->getHeader().conformant(other.getHeader());
318}
319
320
321int Scantable::nscan() const {
322  int n = 0;
323  Int previous = -1; Int current = 0;
324  Vector<uInt> scannos(scanCol_.getColumn());
325  uInt nout = GenSort<uInt>::sort( scannos, Sort::Ascending,
326                       Sort::QuickSort|Sort::NoDuplicates );
327  return int(nout);
328}
329
330std::string Scantable::formatSec(Double x) const
331{
332  Double xcop = x;
333  MVTime mvt(xcop/24./3600.);  // make days
334
335  if (x < 59.95)
336    return  String("      ") + mvt.string(MVTime::TIME_CLEAN_NO_HM, 7)+"s";
337  else if (x < 3599.95)
338    return String("   ") + mvt.string(MVTime::TIME_CLEAN_NO_H,7)+" ";
339  else {
340    ostringstream oss;
341    oss << setw(2) << std::right << setprecision(1) << mvt.hour();
342    oss << ":" << mvt.string(MVTime::TIME_CLEAN_NO_H,7) << " ";
343    return String(oss);
344  }
345};
346
347std::string Scantable::formatDirection(const MDirection& md) const
348{
349  Vector<Double> t = md.getAngle(Unit(String("rad"))).getValue();
350  Int prec = 7;
351
352  MVAngle mvLon(t[0]);
353  String sLon = mvLon.string(MVAngle::TIME,prec);
354  MVAngle mvLat(t[1]);
355  String sLat = mvLat.string(MVAngle::ANGLE+MVAngle::DIG2,prec);
356  return sLon + String(" ") + sLat;
357}
358
359
360std::string Scantable::getFluxUnit() const
361{
362  return table_.keywordSet().asString("FluxUnit");
363}
364
365void Scantable::setFluxUnit(const std::string& unit)
366{
367  String tmp(unit);
368  Unit tU(tmp);
369  if (tU==Unit("K") || tU==Unit("Jy")) {
370     table_.rwKeywordSet().define(String("FluxUnit"), tmp);
371  } else {
372     throw AipsError("Illegal unit - must be compatible with Jy or K");
373  }
374}
375
376void Scantable::setInstrument(const std::string& name)
377{
378  bool throwIt = true;
379  Instrument ins = STAttr::convertInstrument(name, throwIt);
380  String nameU(name);
381  nameU.upcase();
382  table_.rwKeywordSet().define(String("AntennaName"), nameU);
383}
384
385MPosition Scantable::getAntennaPosition () const
386{
387  Vector<Double> antpos;
388  table_.keywordSet().get("AntennaPosition", antpos);
389  MVPosition mvpos(antpos(0),antpos(1),antpos(2));
390  return MPosition(mvpos);
391}
392
393void Scantable::makePersistent(const std::string& filename)
394{
395  String inname(filename);
396  Path path(inname);
397  inname = path.expandedName();
398  table_.deepCopy(inname, Table::New);
399}
400
401int Scantable::nbeam( int scanno ) const
402{
403  if ( scanno < 0 ) {
404    Int n;
405    table_.keywordSet().get("nBeam",n);
406    return int(n);
407  } else {
408    // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
409    Table t = table_(table_.col("SCANNO") == scanno);
410    ROTableRow row(t);
411    const TableRecord& rec = row.get(0);
412    Table subt = t( t.col("IFNO") == Int(rec.asuInt("IFNO"))
413                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
414                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
415    ROTableVector<uInt> v(subt, "BEAMNO");
416    return int(v.nelements());
417  }
418  return 0;
419}
420
421int Scantable::nif( int scanno ) const
422{
423  if ( scanno < 0 ) {
424    Int n;
425    table_.keywordSet().get("nIF",n);
426    return int(n);
427  } else {
428    // take the first POLNO,BEAMNO,CYCLENO as nbeam shouldn't vary with these
429    Table t = table_(table_.col("SCANNO") == scanno);
430    ROTableRow row(t);
431    const TableRecord& rec = row.get(0);
432    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
433                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
434                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
435    if ( subt.nrow() == 0 ) return 0;
436    ROTableVector<uInt> v(subt, "IFNO");
437    return int(v.nelements());
438  }
439  return 0;
440}
441
442int Scantable::npol( int scanno ) const
443{
444  if ( scanno < 0 ) {
445    Int n;
446    table_.keywordSet().get("nPol",n);
447    return n;
448  } else {
449    // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
450    Table t = table_(table_.col("SCANNO") == scanno);
451    ROTableRow row(t);
452    const TableRecord& rec = row.get(0);
453    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
454                    && t.col("IFNO") == Int(rec.asuInt("IFNO"))
455                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
456    if ( subt.nrow() == 0 ) return 0;
457    ROTableVector<uInt> v(subt, "POLNO");
458    return int(v.nelements());
459  }
460  return 0;
461}
462
463int Scantable::ncycle( int scanno ) const
464{
465  if ( scanno < 0 ) {
466    Block<String> cols(2);
467    cols[0] = "SCANNO";
468    cols[1] = "CYCLENO";
469    TableIterator it(table_, cols);
470    int n = 0;
471    while ( !it.pastEnd() ) {
472      ++n;
473      ++it;
474    }
475    return n;
476  } else {
477    Table t = table_(table_.col("SCANNO") == scanno);
478    ROTableRow row(t);
479    const TableRecord& rec = row.get(0);
480    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
481                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
482                    && t.col("IFNO") == Int(rec.asuInt("IFNO")) );
483    if ( subt.nrow() == 0 ) return 0;
484    return int(subt.nrow());
485  }
486  return 0;
487}
488
489
490int Scantable::nrow( int scanno ) const
491{
492  return int(table_.nrow());
493}
494
495int Scantable::nchan( int ifno ) const
496{
497  if ( ifno < 0 ) {
498    Int n;
499    table_.keywordSet().get("nChan",n);
500    return int(n);
501  } else {
502    // take the first SCANNO,POLNO,BEAMNO,CYCLENO as nbeam shouldn't vary with these
503    Table t = table_(table_.col("IFNO") == ifno);
504    if ( t.nrow() == 0 ) return 0;
505    ROArrayColumn<Float> v(t, "SPECTRA");
506    return v.shape(0)(0);
507  }
508  return 0;
509}
510
511int Scantable::getChannels(int whichrow) const
512{
513  return specCol_.shape(whichrow)(0);
514}
515
516int Scantable::getBeam(int whichrow) const
517{
518  return beamCol_(whichrow);
519}
520
521int Scantable::getIF(int whichrow) const
522{
523  return ifCol_(whichrow);
524}
525
526int Scantable::getPol(int whichrow) const
527{
528  return polCol_(whichrow);
529}
530
531std::string Scantable::formatTime(const MEpoch& me, bool showdate) const
532{
533  MVTime mvt(me.getValue());
534  if (showdate)
535    mvt.setFormat(MVTime::YMD);
536  else
537    mvt.setFormat(MVTime::TIME);
538  ostringstream oss;
539  oss << mvt;
540  return String(oss);
541}
542
543void Scantable::calculateAZEL()
544{
545  MPosition mp = getAntennaPosition();
546  MEpoch::ROScalarColumn timeCol(table_, "TIME");
547  ostringstream oss;
548  oss << "Computed azimuth/elevation using " << endl
549      << mp << endl;
550  for (uInt i=0; i<nrow(); ++i) {
551    MEpoch me = timeCol(i);
552    MDirection md = dirCol_(i);
553    dirCol_.get(i,md);
554    oss  << " Time: " << formatTime(me,False) << " Direction: " << formatDirection(md)
555         << endl << "     => ";
556    MeasFrame frame(mp, me);
557    Vector<Double> azel =
558        MDirection::Convert(md, MDirection::Ref(MDirection::AZEL,
559                                                frame)
560                            )().getAngle("rad").getValue();
561    azCol_.put(i,Float(azel[0]));
562    elCol_.put(i,Float(azel[1]));
563    oss << "azel: " << azel[0]/C::pi*180.0 << " "
564        << azel[1]/C::pi*180.0 << " (deg)" << endl;
565  }
566  pushLog(String(oss));
567}
568
569void Scantable::flag()
570{
571  if ( selector_.empty() )
572    throw(AipsError("Trying to flag whole scantable. Aborted."));
573  TableVector<uChar> tvec(table_, "FLAGTRA");
574  uChar userflag = 1 << 7;
575  tvec = userflag;
576}
577
578std::vector<bool> Scantable::getMask(int whichrow) const
579{
580  Vector<uChar> flags;
581  flagsCol_.get(uInt(whichrow), flags);
582  Vector<Bool> bflag(flags.shape());
583  convertArray(bflag, flags);
584  bflag = !bflag;
585  std::vector<bool> mask;
586  bflag.tovector(mask);
587  return mask;
588}
589
590std::vector<float> Scantable::getSpectrum( int whichrow,
591                                           const std::string& poltype ) const
592{
593  String ptype = poltype;
594  if (poltype == "" ) ptype = getPolType();
595  if ( whichrow  < 0 || whichrow >= nrow() )
596    throw(AipsError("Illegal row number."));
597  std::vector<float> out;
598  Vector<Float> arr;
599  uInt requestedpol = polCol_(whichrow);
600  String basetype = getPolType();
601  if ( ptype == basetype ) {
602    specCol_.get(whichrow, arr);
603  } else {
604    STPol* stpol = 0;
605    stpol =STPol::getPolClass(Scantable::factories_, basetype);
606    try {
607      uInt row = uInt(whichrow);
608      stpol->setSpectra(getPolMatrix(row));
609      Float fang,fhand,parang;
610      fang = focusTable_.getTotalFeedAngle(mfocusidCol_(row));
611      fhand = focusTable_.getFeedHand(mfocusidCol_(row));
612      parang = paraCol_(row);
613      /// @todo re-enable this
614      // disable total feed angle to support paralactifying Caswell style
615      stpol->setPhaseCorrections(parang, -parang, fhand);
616      arr = stpol->getSpectrum(requestedpol, ptype);
617      delete stpol;
618    } catch (AipsError& e) {
619      delete stpol;
620      throw(e);
621    }
622  }
623  if ( arr.nelements() == 0 )
624    pushLog("Not enough polarisations present to do the conversion.");
625  arr.tovector(out);
626  return out;
627}
628
629void asap::Scantable::setSpectrum( const std::vector<float>& spec,
630                                   int whichrow )
631{
632  Vector<Float> spectrum(spec);
633  Vector<Float> arr;
634  specCol_.get(whichrow, arr);
635  if ( spectrum.nelements() != arr.nelements() )
636    throw AipsError("The spectrum has incorrect number of channels.");
637  specCol_.put(whichrow, spectrum);
638}
639
640
641String Scantable::generateName()
642{
643  return (File::newUniqueName("./","temp")).baseName();
644}
645
646const casa::Table& Scantable::table( ) const
647{
648  return table_;
649}
650
651casa::Table& Scantable::table( )
652{
653  return table_;
654}
655
656std::string Scantable::getPolType() const
657{
658  return table_.keywordSet().asString("POLTYPE");
659}
660
661void Scantable::unsetSelection()
662{
663  table_ = originalTable_;
664  attach();
665  selector_.reset();
666}
667
668void Scantable::setSelection( const STSelector& selection )
669{
670  Table tab = const_cast<STSelector&>(selection).apply(originalTable_);
671  if ( tab.nrow() == 0 ) {
672    throw(AipsError("Selection contains no data. Not applying it."));
673  }
674  table_ = tab;
675  attach();
676  selector_ = selection;
677}
678
679std::string Scantable::summary( bool verbose )
680{
681  // Format header info
682  ostringstream oss;
683  oss << endl;
684  oss << asap::SEPERATOR << endl;
685  oss << " Scan Table Summary" << endl;
686  oss << asap::SEPERATOR << endl;
687  oss.flags(std::ios_base::left);
688  oss << setw(15) << "Beams:" << setw(4) << nbeam() << endl
689      << setw(15) << "IFs:" << setw(4) << nif() << endl
690      << setw(15) << "Polarisations:" << setw(4) << npol()
691      << "(" << getPolType() << ")" << endl
692      << setw(15) << "Channels:"  << setw(4) << nchan() << endl;
693  oss << endl;
694  String tmp;
695  oss << setw(15) << "Observer:"
696      << table_.keywordSet().asString("Observer") << endl;
697  oss << setw(15) << "Obs Date:" << getTime(-1,true) << endl;
698  table_.keywordSet().get("Project", tmp);
699  oss << setw(15) << "Project:" << tmp << endl;
700  table_.keywordSet().get("Obstype", tmp);
701  oss << setw(15) << "Obs. Type:" << tmp << endl;
702  table_.keywordSet().get("AntennaName", tmp);
703  oss << setw(15) << "Antenna Name:" << tmp << endl;
704  table_.keywordSet().get("FluxUnit", tmp);
705  oss << setw(15) << "Flux Unit:" << tmp << endl;
706  Vector<Double> vec(moleculeTable_.getRestFrequencies());
707  oss << setw(15) << "Rest Freqs:";
708  if (vec.nelements() > 0) {
709      oss << setprecision(10) << vec << " [Hz]" << endl;
710  } else {
711      oss << "none" << endl;
712  }
713
714  oss << setw(15) << "Abcissa:" << getAbcissaLabel(0) << endl;
715  oss << selector_.print() << endl;
716  oss << endl;
717  // main table
718  String dirtype = "Position ("
719                  + MDirection::showType(dirCol_.getMeasRef().getType())
720                  + ")";
721  oss << setw(5) << "Scan" << setw(15) << "Source"
722      << setw(10) << "Time" << setw(18) << "Integration" << endl;
723  oss << setw(5) << "" << setw(5) << "Beam" << setw(3) << "" << dirtype << endl;
724  oss << setw(10) << "" << setw(3) << "IF" << setw(6) << ""
725      << setw(8) << "Frame" << setw(16)
726      << "RefVal" << setw(10) << "RefPix" << setw(12) << "Increment" <<endl;
727  oss << asap::SEPERATOR << endl;
728  TableIterator iter(table_, "SCANNO");
729  while (!iter.pastEnd()) {
730    Table subt = iter.table();
731    ROTableRow row(subt);
732    MEpoch::ROScalarColumn timeCol(subt,"TIME");
733    const TableRecord& rec = row.get(0);
734    oss << setw(4) << std::right << rec.asuInt("SCANNO")
735        << std::left << setw(1) << ""
736        << setw(15) << rec.asString("SRCNAME")
737        << setw(10) << formatTime(timeCol(0), false);
738    // count the cycles in the scan
739    TableIterator cyciter(subt, "CYCLENO");
740    int nint = 0;
741    while (!cyciter.pastEnd()) {
742      ++nint;
743      ++cyciter;
744    }
745    oss << setw(3) << std::right << nint  << setw(3) << " x " << std::left
746        << setw(6) <<  formatSec(rec.asFloat("INTERVAL")) << endl;
747
748    TableIterator biter(subt, "BEAMNO");
749    while (!biter.pastEnd()) {
750      Table bsubt = biter.table();
751      ROTableRow brow(bsubt);
752      MDirection::ROScalarColumn bdirCol(bsubt,"DIRECTION");
753      const TableRecord& brec = brow.get(0);
754      oss << setw(5) << "" <<  setw(4) << std::right << brec.asuInt("BEAMNO")<< std::left;
755      oss  << setw(4) << ""  << formatDirection(bdirCol(0)) << endl;
756      TableIterator iiter(bsubt, "IFNO");
757      while (!iiter.pastEnd()) {
758        Table isubt = iiter.table();
759        ROTableRow irow(isubt);
760        const TableRecord& irec = irow.get(0);
761        oss << setw(10) << "";
762        oss << setw(3) << std::right << irec.asuInt("IFNO") << std::left
763            << setw(2) << "" << frequencies().print(irec.asuInt("FREQ_ID"));
764
765        ++iiter;
766      }
767      ++biter;
768    }
769    ++iter;
770  }
771  /// @todo implement verbose mode
772  return String(oss);
773}
774
775std::string Scantable::getTime(int whichrow, bool showdate) const
776{
777  MEpoch::ROScalarColumn timeCol(table_, "TIME");
778  MEpoch me;
779  if (whichrow > -1) {
780    me = timeCol(uInt(whichrow));
781  } else {
782    Double tm;
783    table_.keywordSet().get("UTC",tm);
784    me = MEpoch(MVEpoch(tm));
785  }
786  return formatTime(me, showdate);
787}
788
789std::vector< double > asap::Scantable::getAbcissa( int whichrow ) const
790{
791  if ( whichrow > table_.nrow() ) throw(AipsError("Illegal ro number"));
792  std::vector<double> stlout;
793  int nchan = specCol_(whichrow).nelements();
794  String us = freqTable_.getUnitString();
795  if ( us == "" || us == "pixel" || us == "channel" ) {
796    for (int i=0; i<nchan; ++i) {
797      stlout.push_back(double(i));
798    }
799    return stlout;
800  }
801
802  const MPosition& mp = getAntennaPosition();
803  const MDirection& md = dirCol_(whichrow);
804  const MEpoch& me = timeCol_(whichrow);
805  Double rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
806  SpectralCoordinate spc =
807    freqTable_.getSpectralCoordinate(md, mp, me, rf, mfreqidCol_(whichrow));
808  Vector<Double> pixel(nchan);
809  Vector<Double> world;
810  indgen(pixel);
811  if ( Unit(us) == Unit("Hz") ) {
812    for ( int i=0; i < nchan; ++i) {
813      Double world;
814      spc.toWorld(world, pixel[i]);
815      stlout.push_back(double(world));
816    }
817  } else if ( Unit(us) == Unit("km/s") ) {
818    Vector<Double> world;
819    spc.pixelToVelocity(world, pixel);
820    world.tovector(stlout);
821  }
822  return stlout;
823}
824
825std::string Scantable::getAbcissaLabel( int whichrow ) const
826{
827  if ( whichrow > table_.nrow() ) throw(AipsError("Illegal ro number"));
828  const MPosition& mp = getAntennaPosition();
829  const MDirection& md = dirCol_(whichrow);
830  const MEpoch& me = timeCol_(whichrow);
831  const Double& rf = mmolidCol_(whichrow);
832  SpectralCoordinate spc =
833    freqTable_.getSpectralCoordinate(md, mp, me, rf, mfreqidCol_(whichrow));
834
835  String s = "Channel";
836  Unit u = Unit(freqTable_.getUnitString());
837  if (u == Unit("km/s")) {
838    s = CoordinateUtil::axisLabel(spc,0,True,True,True);
839  } else if (u == Unit("Hz")) {
840    Vector<String> wau(1);wau = u.getName();
841    spc.setWorldAxisUnits(wau);
842    s = CoordinateUtil::axisLabel(spc,0,True,True,False);
843  }
844  return s;
845
846}
847
848void asap::Scantable::setRestFrequencies( double rf, const std::string& unit )
849{
850  ///@todo lookup in line table to fill in name and formattedname
851  Unit u(unit);
852  Quantum<Double> urf(rf, u);
853  uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), "", "");
854  TableVector<uInt> tabvec(table_, "MOLECULE_ID");
855  tabvec = id;
856}
857
858void asap::Scantable::setRestFrequencies( const std::string& name )
859{
860  throw(AipsError("setRestFrequencies( const std::string& name ) NYI"));
861  ///@todo implement
862}
863
864std::vector< unsigned int > asap::Scantable::rownumbers( ) const
865{
866  std::vector<unsigned int> stlout;
867  Vector<uInt> vec = table_.rowNumbers();
868  vec.tovector(stlout);
869  return stlout;
870}
871
872
873Matrix<Float> asap::Scantable::getPolMatrix( uInt whichrow ) const
874{
875  ROTableRow row(table_);
876  const TableRecord& rec = row.get(whichrow);
877  Table t =
878    originalTable_( originalTable_.col("SCANNO") == Int(rec.asuInt("SCANNO"))
879                    && originalTable_.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
880                    && originalTable_.col("IFNO") == Int(rec.asuInt("IFNO"))
881                    && originalTable_.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
882  ROArrayColumn<Float> speccol(t, "SPECTRA");
883  return speccol.getColumn();
884}
885
886std::vector< std::string > asap::Scantable::columnNames( ) const
887{
888  Vector<String> vec = table_.tableDesc().columnNames();
889  return mathutil::tovectorstring(vec);
890}
891
892casa::MEpoch::Types asap::Scantable::getTimeReference( ) const
893{
894  return MEpoch::castType(timeCol_.getMeasRef().getType());
895}
896
897void asap::Scantable::addFit( const STFitEntry & fit, int row )
898{
899  cout << mfitidCol_(uInt(row)) << endl;
900  uInt id = fitTable_.addEntry(fit, mfitidCol_(uInt(row)));
901  mfitidCol_.put(uInt(row), id);
902}
903
904} //namespace asap
Note: See TracBrowser for help on using the repository browser.