source: trunk/src/Scantable.cpp @ 996

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

more fixes after compiling with -Wall.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 28.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#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  uInt 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  // a uder set table type e.g. GALCTIC, B1950 ...
222  td.rwKeywordSet().define("DIRECTIONREF", String("J2000"));
223  // writing create the measure column
224  mdirCol.write(td);
225  td.addColumn(ScalarColumnDesc<Float>("AZIMUTH"));
226  td.addColumn(ScalarColumnDesc<Float>("ELEVATION"));
227  td.addColumn(ScalarColumnDesc<Float>("PARANGLE"));
228
229  td.addColumn(ScalarColumnDesc<uInt>("TCAL_ID"));
230  ScalarColumnDesc<Int> fitColumn("FIT_ID");
231  fitColumn.setDefault(Int(-1));
232  td.addColumn(fitColumn);
233
234  td.addColumn(ScalarColumnDesc<uInt>("FOCUS_ID"));
235  td.addColumn(ScalarColumnDesc<uInt>("WEATHER_ID"));
236
237  td.rwKeywordSet().define("OBSMODE", String(""));
238
239  // Now create Table SetUp from the description.
240  SetupNewTable aNewTab(generateName(), td, Table::Scratch);
241  table_ = Table(aNewTab, type_, 0);
242  originalTable_ = table_;
243}
244
245
246void Scantable::attach()
247{
248  timeCol_.attach(table_, "TIME");
249  srcnCol_.attach(table_, "SRCNAME");
250  specCol_.attach(table_, "SPECTRA");
251  flagsCol_.attach(table_, "FLAGTRA");
252  tsysCol_.attach(table_, "TSYS");
253  cycleCol_.attach(table_,"CYCLENO");
254  scanCol_.attach(table_, "SCANNO");
255  beamCol_.attach(table_, "BEAMNO");
256  ifCol_.attach(table_, "IFNO");
257  polCol_.attach(table_, "POLNO");
258  integrCol_.attach(table_, "INTERVAL");
259  azCol_.attach(table_, "AZIMUTH");
260  elCol_.attach(table_, "ELEVATION");
261  dirCol_.attach(table_, "DIRECTION");
262  paraCol_.attach(table_, "PARANGLE");
263  fldnCol_.attach(table_, "FIELDNAME");
264  rbeamCol_.attach(table_, "REFBEAMNO");
265
266  mfitidCol_.attach(table_,"FIT_ID");
267  mfreqidCol_.attach(table_, "FREQ_ID");
268  mtcalidCol_.attach(table_, "TCAL_ID");
269  mfocusidCol_.attach(table_, "FOCUS_ID");
270  mmolidCol_.attach(table_, "MOLECULE_ID");
271}
272
273void Scantable::setHeader(const STHeader& sdh)
274{
275  table_.rwKeywordSet().define("nIF", sdh.nif);
276  table_.rwKeywordSet().define("nBeam", sdh.nbeam);
277  table_.rwKeywordSet().define("nPol", sdh.npol);
278  table_.rwKeywordSet().define("nChan", sdh.nchan);
279  table_.rwKeywordSet().define("Observer", sdh.observer);
280  table_.rwKeywordSet().define("Project", sdh.project);
281  table_.rwKeywordSet().define("Obstype", sdh.obstype);
282  table_.rwKeywordSet().define("AntennaName", sdh.antennaname);
283  table_.rwKeywordSet().define("AntennaPosition", sdh.antennaposition);
284  table_.rwKeywordSet().define("Equinox", sdh.equinox);
285  table_.rwKeywordSet().define("FreqRefFrame", sdh.freqref);
286  table_.rwKeywordSet().define("FreqRefVal", sdh.reffreq);
287  table_.rwKeywordSet().define("Bandwidth", sdh.bandwidth);
288  table_.rwKeywordSet().define("UTC", sdh.utc);
289  table_.rwKeywordSet().define("FluxUnit", sdh.fluxunit);
290  table_.rwKeywordSet().define("Epoch", sdh.epoch);
291  table_.rwKeywordSet().define("POLTYPE", sdh.poltype);
292}
293
294STHeader Scantable::getHeader() const
295{
296  STHeader sdh;
297  table_.keywordSet().get("nBeam",sdh.nbeam);
298  table_.keywordSet().get("nIF",sdh.nif);
299  table_.keywordSet().get("nPol",sdh.npol);
300  table_.keywordSet().get("nChan",sdh.nchan);
301  table_.keywordSet().get("Observer", sdh.observer);
302  table_.keywordSet().get("Project", sdh.project);
303  table_.keywordSet().get("Obstype", sdh.obstype);
304  table_.keywordSet().get("AntennaName", sdh.antennaname);
305  table_.keywordSet().get("AntennaPosition", sdh.antennaposition);
306  table_.keywordSet().get("Equinox", sdh.equinox);
307  table_.keywordSet().get("FreqRefFrame", sdh.freqref);
308  table_.keywordSet().get("FreqRefVal", sdh.reffreq);
309  table_.keywordSet().get("Bandwidth", sdh.bandwidth);
310  table_.keywordSet().get("UTC", sdh.utc);
311  table_.keywordSet().get("FluxUnit", sdh.fluxunit);
312  table_.keywordSet().get("Epoch", sdh.epoch);
313  table_.keywordSet().get("POLTYPE", sdh.poltype);
314  return sdh;
315}
316
317bool Scantable::conformant( const Scantable& other )
318{
319  return this->getHeader().conformant(other.getHeader());
320}
321
322
323int Scantable::nscan() const {
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  uInt tp = md.getRef().getType();
355  if (tp == MDirection::GALACTIC ||
356      tp == MDirection::SUPERGAL ) {
357    sLon = mvLon(0.0).string(MVAngle::ANGLE_CLEAN,prec);
358  }
359  MVAngle mvLat(t[1]);
360  String sLat = mvLat.string(MVAngle::ANGLE+MVAngle::DIG2,prec);
361  return sLon + String(" ") + sLat;
362}
363
364
365std::string Scantable::getFluxUnit() const
366{
367  return table_.keywordSet().asString("FluxUnit");
368}
369
370void Scantable::setFluxUnit(const std::string& unit)
371{
372  String tmp(unit);
373  Unit tU(tmp);
374  if (tU==Unit("K") || tU==Unit("Jy")) {
375     table_.rwKeywordSet().define(String("FluxUnit"), tmp);
376  } else {
377     throw AipsError("Illegal unit - must be compatible with Jy or K");
378  }
379}
380
381void Scantable::setInstrument(const std::string& name)
382{
383  bool throwIt = true;
384  // create an Instrument to see if this is valid
385  STAttr::convertInstrument(name, throwIt);
386  String nameU(name);
387  nameU.upcase();
388  table_.rwKeywordSet().define(String("AntennaName"), nameU);
389}
390
391MPosition Scantable::getAntennaPosition () const
392{
393  Vector<Double> antpos;
394  table_.keywordSet().get("AntennaPosition", antpos);
395  MVPosition mvpos(antpos(0),antpos(1),antpos(2));
396  return MPosition(mvpos);
397}
398
399void Scantable::makePersistent(const std::string& filename)
400{
401  String inname(filename);
402  Path path(inname);
403  inname = path.expandedName();
404  table_.deepCopy(inname, Table::New);
405}
406
407int Scantable::nbeam( int scanno ) const
408{
409  if ( scanno < 0 ) {
410    Int n;
411    table_.keywordSet().get("nBeam",n);
412    return int(n);
413  } else {
414    // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
415    Table t = table_(table_.col("SCANNO") == scanno);
416    ROTableRow row(t);
417    const TableRecord& rec = row.get(0);
418    Table subt = t( t.col("IFNO") == Int(rec.asuInt("IFNO"))
419                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
420                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
421    ROTableVector<uInt> v(subt, "BEAMNO");
422    return int(v.nelements());
423  }
424  return 0;
425}
426
427int Scantable::nif( int scanno ) const
428{
429  if ( scanno < 0 ) {
430    Int n;
431    table_.keywordSet().get("nIF",n);
432    return int(n);
433  } else {
434    // take the first POLNO,BEAMNO,CYCLENO as nbeam shouldn't vary with these
435    Table t = table_(table_.col("SCANNO") == scanno);
436    ROTableRow row(t);
437    const TableRecord& rec = row.get(0);
438    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
439                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
440                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
441    if ( subt.nrow() == 0 ) return 0;
442    ROTableVector<uInt> v(subt, "IFNO");
443    return int(v.nelements());
444  }
445  return 0;
446}
447
448int Scantable::npol( int scanno ) const
449{
450  if ( scanno < 0 ) {
451    Int n;
452    table_.keywordSet().get("nPol",n);
453    return n;
454  } else {
455    // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
456    Table t = table_(table_.col("SCANNO") == scanno);
457    ROTableRow row(t);
458    const TableRecord& rec = row.get(0);
459    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
460                    && t.col("IFNO") == Int(rec.asuInt("IFNO"))
461                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
462    if ( subt.nrow() == 0 ) return 0;
463    ROTableVector<uInt> v(subt, "POLNO");
464    return int(v.nelements());
465  }
466  return 0;
467}
468
469int Scantable::ncycle( int scanno ) const
470{
471  if ( scanno < 0 ) {
472    Block<String> cols(2);
473    cols[0] = "SCANNO";
474    cols[1] = "CYCLENO";
475    TableIterator it(table_, cols);
476    int n = 0;
477    while ( !it.pastEnd() ) {
478      ++n;
479      ++it;
480    }
481    return n;
482  } else {
483    Table t = table_(table_.col("SCANNO") == scanno);
484    ROTableRow row(t);
485    const TableRecord& rec = row.get(0);
486    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
487                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
488                    && t.col("IFNO") == Int(rec.asuInt("IFNO")) );
489    if ( subt.nrow() == 0 ) return 0;
490    return int(subt.nrow());
491  }
492  return 0;
493}
494
495
496int Scantable::nrow( int scanno ) const
497{
498  return int(table_.nrow());
499}
500
501int Scantable::nchan( int ifno ) const
502{
503  if ( ifno < 0 ) {
504    Int n;
505    table_.keywordSet().get("nChan",n);
506    return int(n);
507  } else {
508    // take the first SCANNO,POLNO,BEAMNO,CYCLENO as nbeam shouldn't vary with these
509    Table t = table_(table_.col("IFNO") == ifno);
510    if ( t.nrow() == 0 ) return 0;
511    ROArrayColumn<Float> v(t, "SPECTRA");
512    return v.shape(0)(0);
513  }
514  return 0;
515}
516
517int Scantable::getChannels(int whichrow) const
518{
519  return specCol_.shape(whichrow)(0);
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 (Int i=0; i<nrow(); ++i) {
557    MEpoch me = timeCol(i);
558    MDirection md = getDirection(i);
559    oss  << " Time: " << formatTime(me,False) << " Direction: " << formatDirection(md)
560         << endl << "     => ";
561    MeasFrame frame(mp, me);
562    Vector<Double> azel =
563        MDirection::Convert(md, MDirection::Ref(MDirection::AZEL,
564                                                frame)
565                            )().getAngle("rad").getValue();
566    azCol_.put(i,Float(azel[0]));
567    elCol_.put(i,Float(azel[1]));
568    oss << "azel: " << azel[0]/C::pi*180.0 << " "
569        << azel[1]/C::pi*180.0 << " (deg)" << endl;
570  }
571  pushLog(String(oss));
572}
573
574void Scantable::flag()
575{
576  if ( selector_.empty() )
577    throw(AipsError("Trying to flag whole scantable. Aborted."));
578  TableVector<uChar> tvec(table_, "FLAGTRA");
579  uChar userflag = 1 << 7;
580  tvec = userflag;
581}
582
583std::vector<bool> Scantable::getMask(int whichrow) const
584{
585  Vector<uChar> flags;
586  flagsCol_.get(uInt(whichrow), flags);
587  Vector<Bool> bflag(flags.shape());
588  convertArray(bflag, flags);
589  bflag = !bflag;
590  std::vector<bool> mask;
591  bflag.tovector(mask);
592  return mask;
593}
594
595std::vector<float> Scantable::getSpectrum( int whichrow,
596                                           const std::string& poltype ) const
597{
598  String ptype = poltype;
599  if (poltype == "" ) ptype = getPolType();
600  if ( whichrow  < 0 || whichrow >= nrow() )
601    throw(AipsError("Illegal row number."));
602  std::vector<float> out;
603  Vector<Float> arr;
604  uInt requestedpol = polCol_(whichrow);
605  String basetype = getPolType();
606  if ( ptype == basetype ) {
607    specCol_.get(whichrow, arr);
608  } else {
609    STPol* stpol = 0;
610    stpol =STPol::getPolClass(Scantable::factories_, basetype);
611    try {
612      uInt row = uInt(whichrow);
613      stpol->setSpectra(getPolMatrix(row));
614      Float fang,fhand,parang;
615      fang = focusTable_.getTotalFeedAngle(mfocusidCol_(row));
616      fhand = focusTable_.getFeedHand(mfocusidCol_(row));
617      parang = paraCol_(row);
618      /// @todo re-enable this
619      // disable total feed angle to support paralactifying Caswell style
620      stpol->setPhaseCorrections(parang, -parang, fhand);
621      arr = stpol->getSpectrum(requestedpol, ptype);
622      delete stpol;
623    } catch (AipsError& e) {
624      delete stpol;
625      throw(e);
626    }
627  }
628  if ( arr.nelements() == 0 )
629    pushLog("Not enough polarisations present to do the conversion.");
630  arr.tovector(out);
631  return out;
632}
633
634void asap::Scantable::setSpectrum( const std::vector<float>& spec,
635                                   int whichrow )
636{
637  Vector<Float> spectrum(spec);
638  Vector<Float> arr;
639  specCol_.get(whichrow, arr);
640  if ( spectrum.nelements() != arr.nelements() )
641    throw AipsError("The spectrum has incorrect number of channels.");
642  specCol_.put(whichrow, spectrum);
643}
644
645
646String Scantable::generateName()
647{
648  return (File::newUniqueName("./","temp")).baseName();
649}
650
651const casa::Table& Scantable::table( ) const
652{
653  return table_;
654}
655
656casa::Table& Scantable::table( )
657{
658  return table_;
659}
660
661std::string Scantable::getPolType() const
662{
663  return table_.keywordSet().asString("POLTYPE");
664}
665
666void Scantable::unsetSelection()
667{
668  table_ = originalTable_;
669  attach();
670  selector_.reset();
671}
672
673void Scantable::setSelection( const STSelector& selection )
674{
675  Table tab = const_cast<STSelector&>(selection).apply(originalTable_);
676  if ( tab.nrow() == 0 ) {
677    throw(AipsError("Selection contains no data. Not applying it."));
678  }
679  table_ = tab;
680  attach();
681  selector_ = selection;
682}
683
684std::string Scantable::summary( bool verbose )
685{
686  // Format header info
687  ostringstream oss;
688  oss << endl;
689  oss << asap::SEPERATOR << endl;
690  oss << " Scan Table Summary" << endl;
691  oss << asap::SEPERATOR << endl;
692  oss.flags(std::ios_base::left);
693  oss << setw(15) << "Beams:" << setw(4) << nbeam() << endl
694      << setw(15) << "IFs:" << setw(4) << nif() << endl
695      << setw(15) << "Polarisations:" << setw(4) << npol()
696      << "(" << getPolType() << ")" << endl
697      << setw(15) << "Channels:"  << setw(4) << nchan() << endl;
698  oss << endl;
699  String tmp;
700  oss << setw(15) << "Observer:"
701      << table_.keywordSet().asString("Observer") << endl;
702  oss << setw(15) << "Obs Date:" << getTime(-1,true) << endl;
703  table_.keywordSet().get("Project", tmp);
704  oss << setw(15) << "Project:" << tmp << endl;
705  table_.keywordSet().get("Obstype", tmp);
706  oss << setw(15) << "Obs. Type:" << tmp << endl;
707  table_.keywordSet().get("AntennaName", tmp);
708  oss << setw(15) << "Antenna Name:" << tmp << endl;
709  table_.keywordSet().get("FluxUnit", tmp);
710  oss << setw(15) << "Flux Unit:" << tmp << endl;
711  Vector<Double> vec(moleculeTable_.getRestFrequencies());
712  oss << setw(15) << "Rest Freqs:";
713  if (vec.nelements() > 0) {
714      oss << setprecision(10) << vec << " [Hz]" << endl;
715  } else {
716      oss << "none" << endl;
717  }
718
719  oss << setw(15) << "Abcissa:" << getAbcissaLabel(0) << endl;
720  oss << selector_.print() << endl;
721  oss << endl;
722  // main table
723  String dirtype = "Position ("
724                  + getDirectionRefString()
725                  + ")";
726  oss << setw(5) << "Scan" << setw(15) << "Source"
727      << setw(10) << "Time" << setw(18) << "Integration" << endl;
728  oss << setw(5) << "" << setw(5) << "Beam" << setw(3) << "" << dirtype << endl;
729  oss << setw(10) << "" << setw(3) << "IF" << setw(6) << ""
730      << setw(8) << "Frame" << setw(16)
731      << "RefVal" << setw(10) << "RefPix" << setw(12) << "Increment" <<endl;
732  oss << asap::SEPERATOR << endl;
733  TableIterator iter(table_, "SCANNO");
734  while (!iter.pastEnd()) {
735    Table subt = iter.table();
736    ROTableRow row(subt);
737    MEpoch::ROScalarColumn timeCol(subt,"TIME");
738    const TableRecord& rec = row.get(0);
739    oss << setw(4) << std::right << rec.asuInt("SCANNO")
740        << std::left << setw(1) << ""
741        << setw(15) << rec.asString("SRCNAME")
742        << setw(10) << formatTime(timeCol(0), false);
743    // count the cycles in the scan
744    TableIterator cyciter(subt, "CYCLENO");
745    int nint = 0;
746    while (!cyciter.pastEnd()) {
747      ++nint;
748      ++cyciter;
749    }
750    oss << setw(3) << std::right << nint  << setw(3) << " x " << std::left
751        << setw(6) <<  formatSec(rec.asFloat("INTERVAL")) << endl;
752
753    TableIterator biter(subt, "BEAMNO");
754    while (!biter.pastEnd()) {
755      Table bsubt = biter.table();
756      ROTableRow brow(bsubt);
757      const TableRecord& brec = brow.get(0);
758      uInt row0 = bsubt.rowNumbers()[0];
759      oss << setw(5) << "" <<  setw(4) << std::right << brec.asuInt("BEAMNO")<< std::left;
760      oss  << setw(4) << ""  << formatDirection(getDirection(row0)) << endl;
761      TableIterator iiter(bsubt, "IFNO");
762      while (!iiter.pastEnd()) {
763        Table isubt = iiter.table();
764        ROTableRow irow(isubt);
765        const TableRecord& irec = irow.get(0);
766        oss << setw(10) << "";
767        oss << setw(3) << std::right << irec.asuInt("IFNO") << std::left
768            << setw(2) << "" << frequencies().print(irec.asuInt("FREQ_ID"));
769
770        ++iiter;
771      }
772      ++biter;
773    }
774    ++iter;
775  }
776  /// @todo implement verbose mode
777  return String(oss);
778}
779
780std::string Scantable::getTime(int whichrow, bool showdate) const
781{
782  MEpoch::ROScalarColumn timeCol(table_, "TIME");
783  MEpoch me;
784  if (whichrow > -1) {
785    me = timeCol(uInt(whichrow));
786  } else {
787    Double tm;
788    table_.keywordSet().get("UTC",tm);
789    me = MEpoch(MVEpoch(tm));
790  }
791  return formatTime(me, showdate);
792}
793
794std::vector< double > asap::Scantable::getAbcissa( int whichrow ) const
795{
796  if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal ro number"));
797  std::vector<double> stlout;
798  int nchan = specCol_(whichrow).nelements();
799  String us = freqTable_.getUnitString();
800  if ( us == "" || us == "pixel" || us == "channel" ) {
801    for (int i=0; i<nchan; ++i) {
802      stlout.push_back(double(i));
803    }
804    return stlout;
805  }
806
807  const MPosition& mp = getAntennaPosition();
808  const MDirection& md = getDirection(whichrow);
809  const MEpoch& me = timeCol_(whichrow);
810  Double rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
811  SpectralCoordinate spc =
812    freqTable_.getSpectralCoordinate(md, mp, me, rf, mfreqidCol_(whichrow));
813  Vector<Double> pixel(nchan);
814  Vector<Double> world;
815  indgen(pixel);
816  if ( Unit(us) == Unit("Hz") ) {
817    for ( int i=0; i < nchan; ++i) {
818      Double world;
819      spc.toWorld(world, pixel[i]);
820      stlout.push_back(double(world));
821    }
822  } else if ( Unit(us) == Unit("km/s") ) {
823    Vector<Double> world;
824    spc.pixelToVelocity(world, pixel);
825    world.tovector(stlout);
826  }
827  return stlout;
828}
829void asap::Scantable::setDirectionRefString( const std::string & refstr )
830{
831  MDirection::Types mdt;
832  if (refstr != "" && !MDirection::getType(mdt, refstr)) {
833    throw(AipsError("Illegal Direction frame."));
834  }
835  if ( refstr == "" ) {
836    String defaultstr = MDirection::showType(dirCol_.getMeasRef().getType());
837    table_.rwKeywordSet().define("DIRECTIONREF", defaultstr);
838  } else {
839    table_.rwKeywordSet().define("DIRECTIONREF", String(refstr));
840  }
841}
842
843std::string asap::Scantable::getDirectionRefString( ) const
844{
845  return table_.keywordSet().asString("DIRECTIONREF");
846}
847
848MDirection Scantable::getDirection(int whichrow ) const
849{
850  String usertype = table_.keywordSet().asString("DIRECTIONREF");
851  String type = MDirection::showType(dirCol_.getMeasRef().getType());
852  if ( usertype != type ) {
853    MDirection::Types mdt;
854    if (!MDirection::getType(mdt, usertype)) {
855      throw(AipsError("Illegal Direction frame."));
856    }
857    return dirCol_.convert(uInt(whichrow), mdt);
858  } else {
859    return dirCol_(uInt(whichrow));
860  }
861}
862
863std::string Scantable::getAbcissaLabel( int whichrow ) const
864{
865  if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal ro number"));
866  const MPosition& mp = getAntennaPosition();
867  const MDirection& md = getDirection(whichrow);
868  const MEpoch& me = timeCol_(whichrow);
869  const Double& rf = mmolidCol_(whichrow);
870  SpectralCoordinate spc =
871    freqTable_.getSpectralCoordinate(md, mp, me, rf, mfreqidCol_(whichrow));
872
873  String s = "Channel";
874  Unit u = Unit(freqTable_.getUnitString());
875  if (u == Unit("km/s")) {
876    s = CoordinateUtil::axisLabel(spc,0,True,True,True);
877  } else if (u == Unit("Hz")) {
878    Vector<String> wau(1);wau = u.getName();
879    spc.setWorldAxisUnits(wau);
880    s = CoordinateUtil::axisLabel(spc,0,True,True,False);
881  }
882  return s;
883
884}
885
886void asap::Scantable::setRestFrequencies( double rf, const std::string& unit )
887{
888  ///@todo lookup in line table to fill in name and formattedname
889  Unit u(unit);
890  Quantum<Double> urf(rf, u);
891  uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), "", "");
892  TableVector<uInt> tabvec(table_, "MOLECULE_ID");
893  tabvec = id;
894}
895
896void asap::Scantable::setRestFrequencies( const std::string& name )
897{
898  throw(AipsError("setRestFrequencies( const std::string& name ) NYI"));
899  ///@todo implement
900}
901
902std::vector< unsigned int > asap::Scantable::rownumbers( ) const
903{
904  std::vector<unsigned int> stlout;
905  Vector<uInt> vec = table_.rowNumbers();
906  vec.tovector(stlout);
907  return stlout;
908}
909
910
911Matrix<Float> asap::Scantable::getPolMatrix( uInt whichrow ) const
912{
913  ROTableRow row(table_);
914  const TableRecord& rec = row.get(whichrow);
915  Table t =
916    originalTable_( originalTable_.col("SCANNO") == Int(rec.asuInt("SCANNO"))
917                    && originalTable_.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
918                    && originalTable_.col("IFNO") == Int(rec.asuInt("IFNO"))
919                    && originalTable_.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
920  ROArrayColumn<Float> speccol(t, "SPECTRA");
921  return speccol.getColumn();
922}
923
924std::vector< std::string > asap::Scantable::columnNames( ) const
925{
926  Vector<String> vec = table_.tableDesc().columnNames();
927  return mathutil::tovectorstring(vec);
928}
929
930casa::MEpoch::Types asap::Scantable::getTimeReference( ) const
931{
932  return MEpoch::castType(timeCol_.getMeasRef().getType());
933}
934
935void asap::Scantable::addFit( const STFitEntry & fit, int row )
936{
937  cout << mfitidCol_(uInt(row)) << endl;
938  uInt id = fitTable_.addEntry(fit, mfitidCol_(uInt(row)));
939  mfitidCol_.put(uInt(row), id);
940}
941
942
943}
944 //namespace asap
Note: See TracBrowser for help on using the repository browser.