source: trunk/src/Scantable.cpp @ 901

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

SDContainer -> STHeader

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