source: trunk/src/Scantable.cpp @ 972

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

Completed Ticket #7 - storing of fits.

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