source: tags/asap2.3.0/src/Scantable.cpp @ 1525

Last change on this file since 1525 was 1525, checked in by Malte Marquarding, 15 years ago

Tagged 2.3.0 release

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 35.6 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/Vector.h>
25#include <casa/Arrays/VectorSTLIterator.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 <casa/Quanta/MVTime.h>
45#include <casa/Quanta/MVAngle.h>
46#include <measures/Measures/MeasRef.h>
47#include <measures/Measures/MeasTable.h>
48// needed to avoid error in .tcc
49#include <measures/Measures/MCDirection.h>
50//
51#include <measures/Measures/MCRadialVelocity.h>
52#include <measures/Measures/MCDoppler.h>
53#include <measures/Measures/MDirection.h>
54#include <measures/Measures/MFrequency.h>
55#include <measures/Measures/MEpoch.h>
56#include <measures/TableMeasures/TableMeasRefDesc.h>
57#include <measures/TableMeasures/TableMeasValueDesc.h>
58#include <measures/TableMeasures/TableMeasDesc.h>
59#include <measures/TableMeasures/ScalarMeasColumn.h>
60#include <coordinates/Coordinates/CoordinateUtil.h>
61
62#include "Scantable.h"
63#include "STPolLinear.h"
64#include "STPolCircular.h"
65#include "STPolStokes.h"
66#include "STAttr.h"
67#include "MathUtils.h"
68
69using namespace casa;
70
71namespace asap {
72
73std::map<std::string, STPol::STPolFactory *> Scantable::factories_;
74
75void Scantable::initFactories() {
76  if ( factories_.empty() ) {
77    Scantable::factories_["linear"] = &STPolLinear::myFactory;
78    Scantable::factories_["circular"] = &STPolCircular::myFactory;
79    Scantable::factories_["stokes"] = &STPolStokes::myFactory;
80  }
81}
82
83Scantable::Scantable(Table::TableType ttype) :
84  type_(ttype)
85{
86  initFactories();
87  setupMainTable();
88  freqTable_ = STFrequencies(*this);
89  table_.rwKeywordSet().defineTable("FREQUENCIES", freqTable_.table());
90  weatherTable_ = STWeather(*this);
91  table_.rwKeywordSet().defineTable("WEATHER", weatherTable_.table());
92  focusTable_ = STFocus(*this);
93  table_.rwKeywordSet().defineTable("FOCUS", focusTable_.table());
94  tcalTable_ = STTcal(*this);
95  table_.rwKeywordSet().defineTable("TCAL", tcalTable_.table());
96  moleculeTable_ = STMolecules(*this);
97  table_.rwKeywordSet().defineTable("MOLECULES", moleculeTable_.table());
98  historyTable_ = STHistory(*this);
99  table_.rwKeywordSet().defineTable("HISTORY", historyTable_.table());
100  fitTable_ = STFit(*this);
101  table_.rwKeywordSet().defineTable("FIT", fitTable_.table());
102  originalTable_ = table_;
103  attach();
104}
105
106Scantable::Scantable(const std::string& name, Table::TableType ttype) :
107  type_(ttype)
108{
109  initFactories();
110  Table tab(name, Table::Update);
111  uInt version = tab.keywordSet().asuInt("VERSION");
112  if (version != version_) {
113    throw(AipsError("Unsupported version of ASAP file."));
114  }
115  if ( type_ == Table::Memory ) {
116    table_ = tab.copyToMemoryTable(generateName());
117  } else {
118    table_ = tab;
119  }
120
121  attachSubtables();
122  originalTable_ = table_;
123  attach();
124}
125
126Scantable::Scantable( const Scantable& other, bool clear )
127{
128  // with or without data
129  String newname = String(generateName());
130  type_ = other.table_.tableType();
131  if ( other.table_.tableType() == Table::Memory ) {
132      if ( clear ) {
133        table_ = TableCopy::makeEmptyMemoryTable(newname,
134                                                 other.table_, True);
135      } else
136        table_ = other.table_.copyToMemoryTable(newname);
137  } else {
138      other.table_.deepCopy(newname, Table::New, False,
139                            other.table_.endianFormat(),
140                            Bool(clear));
141      table_ = Table(newname, Table::Update);
142      table_.markForDelete();
143  }
144  /// @todo reindex SCANNO, recompute nbeam, nif, npol
145  if ( clear ) copySubtables(other);
146  attachSubtables();
147  originalTable_ = table_;
148  attach();
149}
150
151void Scantable::copySubtables(const Scantable& other) {
152  Table t = table_.rwKeywordSet().asTable("FREQUENCIES");
153  TableCopy::copyRows(t, other.freqTable_.table());
154  t = table_.rwKeywordSet().asTable("FOCUS");
155  TableCopy::copyRows(t, other.focusTable_.table());
156  t = table_.rwKeywordSet().asTable("WEATHER");
157  TableCopy::copyRows(t, other.weatherTable_.table());
158  t = table_.rwKeywordSet().asTable("TCAL");
159  TableCopy::copyRows(t, other.tcalTable_.table());
160  t = table_.rwKeywordSet().asTable("MOLECULES");
161  TableCopy::copyRows(t, other.moleculeTable_.table());
162  t = table_.rwKeywordSet().asTable("HISTORY");
163  TableCopy::copyRows(t, other.historyTable_.table());
164  t = table_.rwKeywordSet().asTable("FIT");
165  TableCopy::copyRows(t, other.fitTable_.table());
166}
167
168void Scantable::attachSubtables()
169{
170  freqTable_ = STFrequencies(table_);
171  focusTable_ = STFocus(table_);
172  weatherTable_ = STWeather(table_);
173  tcalTable_ = STTcal(table_);
174  moleculeTable_ = STMolecules(table_);
175  historyTable_ = STHistory(table_);
176  fitTable_ = STFit(table_);
177}
178
179Scantable::~Scantable()
180{
181  //cout << "~Scantable() " << this << endl;
182}
183
184void Scantable::setupMainTable()
185{
186  TableDesc td("", "1", TableDesc::Scratch);
187  td.comment() = "An ASAP Scantable";
188  td.rwKeywordSet().define("VERSION", uInt(version_));
189
190  // n Cycles
191  td.addColumn(ScalarColumnDesc<uInt>("SCANNO"));
192  // new index every nBeam x nIF x nPol
193  td.addColumn(ScalarColumnDesc<uInt>("CYCLENO"));
194
195  td.addColumn(ScalarColumnDesc<uInt>("BEAMNO"));
196  td.addColumn(ScalarColumnDesc<uInt>("IFNO"));
197  // linear, circular, stokes
198  td.rwKeywordSet().define("POLTYPE", String("linear"));
199  td.addColumn(ScalarColumnDesc<uInt>("POLNO"));
200
201  td.addColumn(ScalarColumnDesc<uInt>("FREQ_ID"));
202  td.addColumn(ScalarColumnDesc<uInt>("MOLECULE_ID"));
203  td.addColumn(ScalarColumnDesc<Int>("REFBEAMNO"));
204
205  td.addColumn(ScalarColumnDesc<Double>("TIME"));
206  TableMeasRefDesc measRef(MEpoch::UTC); // UTC as default
207  TableMeasValueDesc measVal(td, "TIME");
208  TableMeasDesc<MEpoch> mepochCol(measVal, measRef);
209  mepochCol.write(td);
210
211  td.addColumn(ScalarColumnDesc<Double>("INTERVAL"));
212
213  td.addColumn(ScalarColumnDesc<String>("SRCNAME"));
214  // Type of source (on=0, off=1, other=-1)
215  ScalarColumnDesc<Int> stypeColumn("SRCTYPE");
216  stypeColumn.setDefault(Int(-1));
217  td.addColumn(stypeColumn);
218  td.addColumn(ScalarColumnDesc<String>("FIELDNAME"));
219
220  //The actual Data Vectors
221  td.addColumn(ArrayColumnDesc<Float>("SPECTRA"));
222  td.addColumn(ArrayColumnDesc<uChar>("FLAGTRA"));
223  td.addColumn(ArrayColumnDesc<Float>("TSYS"));
224
225  td.addColumn(ArrayColumnDesc<Double>("DIRECTION",
226                                       IPosition(1,2),
227                                       ColumnDesc::Direct));
228  TableMeasRefDesc mdirRef(MDirection::J2000); // default
229  TableMeasValueDesc tmvdMDir(td, "DIRECTION");
230  // the TableMeasDesc gives the column a type
231  TableMeasDesc<MDirection> mdirCol(tmvdMDir, mdirRef);
232  // a uder set table type e.g. GALCTIC, B1950 ...
233  td.rwKeywordSet().define("DIRECTIONREF", String("J2000"));
234  // writing create the measure column
235  mdirCol.write(td);
236  td.addColumn(ScalarColumnDesc<Float>("AZIMUTH"));
237  td.addColumn(ScalarColumnDesc<Float>("ELEVATION"));
238  td.addColumn(ScalarColumnDesc<Float>("PARANGLE"));
239  td.addColumn(ScalarColumnDesc<Float>("OPACITY"));
240
241  td.addColumn(ScalarColumnDesc<uInt>("TCAL_ID"));
242  ScalarColumnDesc<Int> fitColumn("FIT_ID");
243  fitColumn.setDefault(Int(-1));
244  td.addColumn(fitColumn);
245
246  td.addColumn(ScalarColumnDesc<uInt>("FOCUS_ID"));
247  td.addColumn(ScalarColumnDesc<uInt>("WEATHER_ID"));
248
249  // columns which just get dragged along, as they aren't used in asap
250  td.addColumn(ScalarColumnDesc<Double>("SRCVELOCITY"));
251  td.addColumn(ArrayColumnDesc<Double>("SRCPROPERMOTION"));
252  td.addColumn(ArrayColumnDesc<Double>("SRCDIRECTION"));
253  td.addColumn(ArrayColumnDesc<Double>("SCANRATE"));
254
255  td.rwKeywordSet().define("OBSMODE", String(""));
256
257  // Now create Table SetUp from the description.
258  SetupNewTable aNewTab(generateName(), td, Table::Scratch);
259  table_ = Table(aNewTab, type_, 0);
260  originalTable_ = table_;
261}
262
263
264void Scantable::attach()
265{
266  timeCol_.attach(table_, "TIME");
267  srcnCol_.attach(table_, "SRCNAME");
268  srctCol_.attach(table_, "SRCTYPE");
269  specCol_.attach(table_, "SPECTRA");
270  flagsCol_.attach(table_, "FLAGTRA");
271  tsysCol_.attach(table_, "TSYS");
272  cycleCol_.attach(table_,"CYCLENO");
273  scanCol_.attach(table_, "SCANNO");
274  beamCol_.attach(table_, "BEAMNO");
275  ifCol_.attach(table_, "IFNO");
276  polCol_.attach(table_, "POLNO");
277  integrCol_.attach(table_, "INTERVAL");
278  azCol_.attach(table_, "AZIMUTH");
279  elCol_.attach(table_, "ELEVATION");
280  dirCol_.attach(table_, "DIRECTION");
281  paraCol_.attach(table_, "PARANGLE");
282  fldnCol_.attach(table_, "FIELDNAME");
283  rbeamCol_.attach(table_, "REFBEAMNO");
284
285  mfitidCol_.attach(table_,"FIT_ID");
286  mfreqidCol_.attach(table_, "FREQ_ID");
287  mtcalidCol_.attach(table_, "TCAL_ID");
288  mfocusidCol_.attach(table_, "FOCUS_ID");
289  mmolidCol_.attach(table_, "MOLECULE_ID");
290}
291
292void Scantable::setHeader(const STHeader& sdh)
293{
294  table_.rwKeywordSet().define("nIF", sdh.nif);
295  table_.rwKeywordSet().define("nBeam", sdh.nbeam);
296  table_.rwKeywordSet().define("nPol", sdh.npol);
297  table_.rwKeywordSet().define("nChan", sdh.nchan);
298  table_.rwKeywordSet().define("Observer", sdh.observer);
299  table_.rwKeywordSet().define("Project", sdh.project);
300  table_.rwKeywordSet().define("Obstype", sdh.obstype);
301  table_.rwKeywordSet().define("AntennaName", sdh.antennaname);
302  table_.rwKeywordSet().define("AntennaPosition", sdh.antennaposition);
303  table_.rwKeywordSet().define("Equinox", sdh.equinox);
304  table_.rwKeywordSet().define("FreqRefFrame", sdh.freqref);
305  table_.rwKeywordSet().define("FreqRefVal", sdh.reffreq);
306  table_.rwKeywordSet().define("Bandwidth", sdh.bandwidth);
307  table_.rwKeywordSet().define("UTC", sdh.utc);
308  table_.rwKeywordSet().define("FluxUnit", sdh.fluxunit);
309  table_.rwKeywordSet().define("Epoch", sdh.epoch);
310  table_.rwKeywordSet().define("POLTYPE", sdh.poltype);
311}
312
313STHeader Scantable::getHeader() const
314{
315  STHeader sdh;
316  table_.keywordSet().get("nBeam",sdh.nbeam);
317  table_.keywordSet().get("nIF",sdh.nif);
318  table_.keywordSet().get("nPol",sdh.npol);
319  table_.keywordSet().get("nChan",sdh.nchan);
320  table_.keywordSet().get("Observer", sdh.observer);
321  table_.keywordSet().get("Project", sdh.project);
322  table_.keywordSet().get("Obstype", sdh.obstype);
323  table_.keywordSet().get("AntennaName", sdh.antennaname);
324  table_.keywordSet().get("AntennaPosition", sdh.antennaposition);
325  table_.keywordSet().get("Equinox", sdh.equinox);
326  table_.keywordSet().get("FreqRefFrame", sdh.freqref);
327  table_.keywordSet().get("FreqRefVal", sdh.reffreq);
328  table_.keywordSet().get("Bandwidth", sdh.bandwidth);
329  table_.keywordSet().get("UTC", sdh.utc);
330  table_.keywordSet().get("FluxUnit", sdh.fluxunit);
331  table_.keywordSet().get("Epoch", sdh.epoch);
332  table_.keywordSet().get("POLTYPE", sdh.poltype);
333  return sdh;
334}
335
336void Scantable::setSourceType( int stype )
337{
338  if ( stype < 0 || stype > 1 )
339    throw(AipsError("Illegal sourcetype."));
340  TableVector<Int> tabvec(table_, "SRCTYPE");
341  tabvec = Int(stype);
342}
343
344bool Scantable::conformant( const Scantable& other )
345{
346  return this->getHeader().conformant(other.getHeader());
347}
348
349
350
351std::string Scantable::formatSec(Double x) const
352{
353  Double xcop = x;
354  MVTime mvt(xcop/24./3600.);  // make days
355
356  if (x < 59.95)
357    return  String("      ") + mvt.string(MVTime::TIME_CLEAN_NO_HM, 7)+"s";
358  else if (x < 3599.95)
359    return String("   ") + mvt.string(MVTime::TIME_CLEAN_NO_H,7)+" ";
360  else {
361    ostringstream oss;
362    oss << setw(2) << std::right << setprecision(1) << mvt.hour();
363    oss << ":" << mvt.string(MVTime::TIME_CLEAN_NO_H,7) << " ";
364    return String(oss);
365  }
366};
367
368std::string Scantable::formatDirection(const MDirection& md) const
369{
370  Vector<Double> t = md.getAngle(Unit(String("rad"))).getValue();
371  Int prec = 7;
372
373  MVAngle mvLon(t[0]);
374  String sLon = mvLon.string(MVAngle::TIME,prec);
375  uInt tp = md.getRef().getType();
376  if (tp == MDirection::GALACTIC ||
377      tp == MDirection::SUPERGAL ) {
378    sLon = mvLon(0.0).string(MVAngle::ANGLE_CLEAN,prec);
379  }
380  MVAngle mvLat(t[1]);
381  String sLat = mvLat.string(MVAngle::ANGLE+MVAngle::DIG2,prec);
382  return sLon + String(" ") + sLat;
383}
384
385
386std::string Scantable::getFluxUnit() const
387{
388  return table_.keywordSet().asString("FluxUnit");
389}
390
391void Scantable::setFluxUnit(const std::string& unit)
392{
393  String tmp(unit);
394  Unit tU(tmp);
395  if (tU==Unit("K") || tU==Unit("Jy")) {
396     table_.rwKeywordSet().define(String("FluxUnit"), tmp);
397  } else {
398     throw AipsError("Illegal unit - must be compatible with Jy or K");
399  }
400}
401
402void Scantable::setInstrument(const std::string& name)
403{
404  bool throwIt = true;
405  // create an Instrument to see if this is valid
406  STAttr::convertInstrument(name, throwIt);
407  String nameU(name);
408  nameU.upcase();
409  table_.rwKeywordSet().define(String("AntennaName"), nameU);
410}
411
412void Scantable::setFeedType(const std::string& feedtype)
413{
414  if ( Scantable::factories_.find(feedtype) ==  Scantable::factories_.end() ) {
415    std::string msg = "Illegal feed type "+ feedtype;
416    throw(casa::AipsError(msg));
417  }
418  table_.rwKeywordSet().define(String("POLTYPE"), feedtype);
419}
420
421MPosition Scantable::getAntennaPosition () const
422{
423  Vector<Double> antpos;
424  table_.keywordSet().get("AntennaPosition", antpos);
425  MVPosition mvpos(antpos(0),antpos(1),antpos(2));
426  return MPosition(mvpos);
427}
428
429void Scantable::makePersistent(const std::string& filename)
430{
431  String inname(filename);
432  Path path(inname);
433  /// @todo reindex SCANNO, recompute nbeam, nif, npol
434  inname = path.expandedName();
435  table_.deepCopy(inname, Table::New);
436}
437
438int Scantable::nbeam( int scanno ) const
439{
440  if ( scanno < 0 ) {
441    Int n;
442    table_.keywordSet().get("nBeam",n);
443    return int(n);
444  } else {
445    // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
446    Table t = table_(table_.col("SCANNO") == scanno);
447    ROTableRow row(t);
448    const TableRecord& rec = row.get(0);
449    Table subt = t( t.col("IFNO") == Int(rec.asuInt("IFNO"))
450                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
451                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
452    ROTableVector<uInt> v(subt, "BEAMNO");
453    return int(v.nelements());
454  }
455  return 0;
456}
457
458int Scantable::nif( int scanno ) const
459{
460  if ( scanno < 0 ) {
461    Int n;
462    table_.keywordSet().get("nIF",n);
463    return int(n);
464  } else {
465    // take the first POLNO,BEAMNO,CYCLENO as nbeam shouldn't vary with these
466    Table t = table_(table_.col("SCANNO") == scanno);
467    ROTableRow row(t);
468    const TableRecord& rec = row.get(0);
469    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
470                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
471                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
472    if ( subt.nrow() == 0 ) return 0;
473    ROTableVector<uInt> v(subt, "IFNO");
474    return int(v.nelements());
475  }
476  return 0;
477}
478
479int Scantable::npol( int scanno ) const
480{
481  if ( scanno < 0 ) {
482    Int n;
483    table_.keywordSet().get("nPol",n);
484    return n;
485  } else {
486    // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
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("IFNO") == Int(rec.asuInt("IFNO"))
492                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
493    if ( subt.nrow() == 0 ) return 0;
494    ROTableVector<uInt> v(subt, "POLNO");
495    return int(v.nelements());
496  }
497  return 0;
498}
499
500int Scantable::ncycle( int scanno ) const
501{
502  if ( scanno < 0 ) {
503    Block<String> cols(2);
504    cols[0] = "SCANNO";
505    cols[1] = "CYCLENO";
506    TableIterator it(table_, cols);
507    int n = 0;
508    while ( !it.pastEnd() ) {
509      ++n;
510      ++it;
511    }
512    return n;
513  } else {
514    Table t = table_(table_.col("SCANNO") == scanno);
515    ROTableRow row(t);
516    const TableRecord& rec = row.get(0);
517    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
518                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
519                    && t.col("IFNO") == Int(rec.asuInt("IFNO")) );
520    if ( subt.nrow() == 0 ) return 0;
521    return int(subt.nrow());
522  }
523  return 0;
524}
525
526
527int Scantable::nrow( int scanno ) const
528{
529  return int(table_.nrow());
530}
531
532int Scantable::nchan( int ifno ) const
533{
534  if ( ifno < 0 ) {
535    Int n;
536    table_.keywordSet().get("nChan",n);
537    return int(n);
538  } else {
539    // take the first SCANNO,POLNO,BEAMNO,CYCLENO as nbeam shouldn't
540    // vary with these
541    Table t = table_(table_.col("IFNO") == ifno);
542    if ( t.nrow() == 0 ) return 0;
543    ROArrayColumn<Float> v(t, "SPECTRA");
544    return v.shape(0)(0);
545  }
546  return 0;
547}
548
549int Scantable::nscan() const {
550  Vector<uInt> scannos(scanCol_.getColumn());
551  uInt nout = genSort( scannos, Sort::Ascending,
552                       Sort::QuickSort|Sort::NoDuplicates );
553  return int(nout);
554}
555
556int Scantable::getChannels(int whichrow) const
557{
558  return specCol_.shape(whichrow)(0);
559}
560
561int Scantable::getBeam(int whichrow) const
562{
563  return beamCol_(whichrow);
564}
565
566std::vector<uint> Scantable::getNumbers(ScalarColumn<uInt>& col)
567{
568  Vector<uInt> nos(col.getColumn());
569  uInt n = genSort( nos, Sort::Ascending, Sort::QuickSort|Sort::NoDuplicates );
570  nos.resize(n, True);
571  std::vector<uint> stlout;
572  nos.tovector(stlout);
573  return stlout;
574}
575
576int Scantable::getIF(int whichrow) const
577{
578  return ifCol_(whichrow);
579}
580
581int Scantable::getPol(int whichrow) const
582{
583  return polCol_(whichrow);
584}
585
586std::string Scantable::formatTime(const MEpoch& me, bool showdate) const
587{
588  MVTime mvt(me.getValue());
589  if (showdate)
590    mvt.setFormat(MVTime::YMD);
591  else
592    mvt.setFormat(MVTime::TIME);
593  ostringstream oss;
594  oss << mvt;
595  return String(oss);
596}
597
598void Scantable::calculateAZEL()
599{
600  MPosition mp = getAntennaPosition();
601  MEpoch::ROScalarColumn timeCol(table_, "TIME");
602  ostringstream oss;
603  oss << "Computed azimuth/elevation using " << endl
604      << mp << endl;
605  for (Int i=0; i<nrow(); ++i) {
606    MEpoch me = timeCol(i);
607    MDirection md = getDirection(i);
608    oss  << " Time: " << formatTime(me,False) << " Direction: " << formatDirection(md)
609         << endl << "     => ";
610    MeasFrame frame(mp, me);
611    Vector<Double> azel =
612        MDirection::Convert(md, MDirection::Ref(MDirection::AZEL,
613                                                frame)
614                            )().getAngle("rad").getValue();
615    azCol_.put(i,Float(azel[0]));
616    elCol_.put(i,Float(azel[1]));
617    oss << "azel: " << azel[0]/C::pi*180.0 << " "
618        << azel[1]/C::pi*180.0 << " (deg)" << endl;
619  }
620  pushLog(String(oss));
621}
622
623void Scantable::flag(const std::vector<bool>& msk, bool unflag)
624{
625  std::vector<bool>::const_iterator it;
626  uInt ntrue = 0;
627  for (it = msk.begin(); it != msk.end(); ++it) {
628    if ( *it ) {
629      ntrue++;
630    }
631  }
632  if ( selector_.empty()  && (msk.size() == 0 || msk.size() == ntrue) )
633    throw(AipsError("Trying to flag whole scantable."));
634  if ( msk.size() == 0 ) {
635    uChar userflag = 1 << 7;
636    if ( unflag ) {
637      userflag = 0 << 7;
638    }
639    for ( uInt i=0; i<table_.nrow(); ++i) {
640      Vector<uChar> flgs = flagsCol_(i);
641      flgs = userflag;
642      flagsCol_.put(i, flgs);
643    }
644    return;
645  }
646  if ( int(msk.size()) != nchan() ) {
647    throw(AipsError("Mask has incorrect number of channels."));
648  }
649  for ( uInt i=0; i<table_.nrow(); ++i) {
650    Vector<uChar> flgs = flagsCol_(i);
651    if ( flgs.nelements() != msk.size() ) {
652      throw(AipsError("Mask has incorrect number of channels."
653                      " Probably varying with IF. Please flag per IF"));
654    }
655    std::vector<bool>::const_iterator it;
656    uInt j = 0;
657    uChar userflag = 1 << 7;
658    if ( unflag ) {
659      userflag = 0 << 7;
660    }
661    for (it = msk.begin(); it != msk.end(); ++it) {
662      if ( *it ) {
663        flgs(j) = userflag;
664      }
665      ++j;
666    }
667    flagsCol_.put(i, flgs);
668  }
669}
670
671std::vector<bool> Scantable::getMask(int whichrow) const
672{
673  Vector<uChar> flags;
674  flagsCol_.get(uInt(whichrow), flags);
675  Vector<Bool> bflag(flags.shape());
676  convertArray(bflag, flags);
677  bflag = !bflag;
678  std::vector<bool> mask;
679  bflag.tovector(mask);
680  return mask;
681}
682
683std::vector<float> Scantable::getSpectrum( int whichrow,
684                                           const std::string& poltype ) const
685{
686  String ptype = poltype;
687  if (poltype == "" ) ptype = getPolType();
688  if ( whichrow  < 0 || whichrow >= nrow() )
689    throw(AipsError("Illegal row number."));
690  std::vector<float> out;
691  Vector<Float> arr;
692  uInt requestedpol = polCol_(whichrow);
693  String basetype = getPolType();
694  if ( ptype == basetype ) {
695    specCol_.get(whichrow, arr);
696  } else {
697    CountedPtr<STPol> stpol(STPol::getPolClass(Scantable::factories_, basetype));
698    uInt row = uInt(whichrow);
699    stpol->setSpectra(getPolMatrix(row));
700    Float fang,fhand,parang;
701    fang = focusTable_.getTotalFeedAngle(mfocusidCol_(row));
702    fhand = focusTable_.getFeedHand(mfocusidCol_(row));
703    parang = paraCol_(row);
704    /// @todo re-enable this
705    // disable total feed angle to support paralactifying Caswell style
706    stpol->setPhaseCorrections(parang, -parang, fhand);
707    arr = stpol->getSpectrum(requestedpol, ptype);
708  }
709  if ( arr.nelements() == 0 )
710    pushLog("Not enough polarisations present to do the conversion.");
711  arr.tovector(out);
712  return out;
713}
714
715void Scantable::setSpectrum( const std::vector<float>& spec,
716                                   int whichrow )
717{
718  Vector<Float> spectrum(spec);
719  Vector<Float> arr;
720  specCol_.get(whichrow, arr);
721  if ( spectrum.nelements() != arr.nelements() )
722    throw AipsError("The spectrum has incorrect number of channels.");
723  specCol_.put(whichrow, spectrum);
724}
725
726
727String Scantable::generateName()
728{
729  return (File::newUniqueName("./","temp")).baseName();
730}
731
732const casa::Table& Scantable::table( ) const
733{
734  return table_;
735}
736
737casa::Table& Scantable::table( )
738{
739  return table_;
740}
741
742std::string Scantable::getPolType() const
743{
744  return table_.keywordSet().asString("POLTYPE");
745}
746
747void Scantable::unsetSelection()
748{
749  table_ = originalTable_;
750  attach();
751  selector_.reset();
752}
753
754void Scantable::setSelection( const STSelector& selection )
755{
756  Table tab = const_cast<STSelector&>(selection).apply(originalTable_);
757  if ( tab.nrow() == 0 ) {
758    throw(AipsError("Selection contains no data. Not applying it."));
759  }
760  table_ = tab;
761  attach();
762  selector_ = selection;
763}
764
765std::string Scantable::summary( bool verbose )
766{
767  // Format header info
768  ostringstream oss;
769  oss << endl;
770  oss << asap::SEPERATOR << endl;
771  oss << " Scan Table Summary" << endl;
772  oss << asap::SEPERATOR << endl;
773  oss.flags(std::ios_base::left);
774  oss << setw(15) << "Beams:" << setw(4) << nbeam() << endl
775      << setw(15) << "IFs:" << setw(4) << nif() << endl
776      << setw(15) << "Polarisations:" << setw(4) << npol()
777      << "(" << getPolType() << ")" << endl
778      << setw(15) << "Channels:"  << setw(4) << nchan() << endl;
779  oss << endl;
780  String tmp;
781  oss << setw(15) << "Observer:"
782      << table_.keywordSet().asString("Observer") << endl;
783  oss << setw(15) << "Obs Date:" << getTime(-1,true) << endl;
784  table_.keywordSet().get("Project", tmp);
785  oss << setw(15) << "Project:" << tmp << endl;
786  table_.keywordSet().get("Obstype", tmp);
787  oss << setw(15) << "Obs. Type:" << tmp << endl;
788  table_.keywordSet().get("AntennaName", tmp);
789  oss << setw(15) << "Antenna Name:" << tmp << endl;
790  table_.keywordSet().get("FluxUnit", tmp);
791  oss << setw(15) << "Flux Unit:" << tmp << endl;
792  Vector<Double> vec(moleculeTable_.getRestFrequencies());
793  oss << setw(15) << "Rest Freqs:";
794  if (vec.nelements() > 0) {
795      oss << setprecision(10) << vec << " [Hz]" << endl;
796  } else {
797      oss << "none" << endl;
798  }
799
800  oss << setw(15) << "Abcissa:" << getAbcissaLabel(0) << endl;
801  oss << selector_.print() << endl;
802  oss << endl;
803  // main table
804  String dirtype = "Position ("
805                  + getDirectionRefString()
806                  + ")";
807  oss << setw(5) << "Scan" << setw(15) << "Source"
808      << setw(10) << "Time" << setw(18) << "Integration" << endl;
809  oss << setw(5) << "" << setw(5) << "Beam" << setw(3) << "" << dirtype << endl;
810  oss << setw(10) << "" << setw(3) << "IF" << setw(6) << ""
811      << setw(8) << "Frame" << setw(16)
812      << "RefVal" << setw(10) << "RefPix" << setw(12) << "Increment" <<endl;
813  oss << asap::SEPERATOR << endl;
814  TableIterator iter(table_, "SCANNO");
815  while (!iter.pastEnd()) {
816    Table subt = iter.table();
817    ROTableRow row(subt);
818    MEpoch::ROScalarColumn timeCol(subt,"TIME");
819    const TableRecord& rec = row.get(0);
820    oss << setw(4) << std::right << rec.asuInt("SCANNO")
821        << std::left << setw(1) << ""
822        << setw(15) << rec.asString("SRCNAME")
823        << setw(10) << formatTime(timeCol(0), false);
824    // count the cycles in the scan
825    TableIterator cyciter(subt, "CYCLENO");
826    int nint = 0;
827    while (!cyciter.pastEnd()) {
828      ++nint;
829      ++cyciter;
830    }
831    oss << setw(3) << std::right << nint  << setw(3) << " x " << std::left
832        << setw(6) <<  formatSec(rec.asFloat("INTERVAL")) << endl;
833
834    TableIterator biter(subt, "BEAMNO");
835    while (!biter.pastEnd()) {
836      Table bsubt = biter.table();
837      ROTableRow brow(bsubt);
838      const TableRecord& brec = brow.get(0);
839      uInt row0 = bsubt.rowNumbers(table_)[0];
840      oss << setw(5) << "" <<  setw(4) << std::right << brec.asuInt("BEAMNO")<< std::left;
841      oss  << setw(4) << ""  << formatDirection(getDirection(row0)) << endl;
842      TableIterator iiter(bsubt, "IFNO");
843      while (!iiter.pastEnd()) {
844        Table isubt = iiter.table();
845        ROTableRow irow(isubt);
846        const TableRecord& irec = irow.get(0);
847        oss << setw(10) << "";
848        oss << setw(3) << std::right << irec.asuInt("IFNO") << std::left
849            << setw(2) << "" << frequencies().print(irec.asuInt("FREQ_ID"))
850            << endl;
851
852        ++iiter;
853      }
854      ++biter;
855    }
856    ++iter;
857  }
858  /// @todo implement verbose mode
859  return String(oss);
860}
861
862std::string Scantable::getTime(int whichrow, bool showdate) const
863{
864  MEpoch::ROScalarColumn timeCol(table_, "TIME");
865  MEpoch me;
866  if (whichrow > -1) {
867    me = timeCol(uInt(whichrow));
868  } else {
869    Double tm;
870    table_.keywordSet().get("UTC",tm);
871    me = MEpoch(MVEpoch(tm));
872  }
873  return formatTime(me, showdate);
874}
875
876MEpoch Scantable::getEpoch(int whichrow) const
877{
878  if (whichrow > -1) {
879    return timeCol_(uInt(whichrow));
880  } else {
881    Double tm;
882    table_.keywordSet().get("UTC",tm);
883    return MEpoch(MVEpoch(tm)); 
884  }
885}
886
887std::string Scantable::getDirectionString(int whichrow) const
888{
889  return formatDirection(getDirection(uInt(whichrow)));
890}
891
892std::vector< double > Scantable::getAbcissa( int whichrow ) const
893{
894  if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal row number"));
895  std::vector<double> stlout;
896  int nchan = specCol_(whichrow).nelements();
897  String us = freqTable_.getUnitString();
898  if ( us == "" || us == "pixel" || us == "channel" ) {
899    for (int i=0; i<nchan; ++i) {
900      stlout.push_back(double(i));
901    }
902    return stlout;
903  }
904
905  const MPosition& mp = getAntennaPosition();
906  const MDirection& md = getDirection(whichrow);
907  const MEpoch& me = timeCol_(whichrow);
908  Double rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
909  SpectralCoordinate spc =
910    freqTable_.getSpectralCoordinate(md, mp, me, rf, mfreqidCol_(whichrow));
911  Vector<Double> pixel(nchan);
912  Vector<Double> world;
913  indgen(pixel);
914  if ( Unit(us) == Unit("Hz") ) {
915    for ( int i=0; i < nchan; ++i) {
916      Double worldi;
917      spc.toWorld(worldi, pixel[i]);
918      stlout.push_back(double(worldi));
919    }
920  } else if ( Unit(us) == Unit("km/s") ) {
921   
922    MeasFrame frame(mp,md,me);
923    MRadialVelocity::Types refin, refout;
924    MFrequency::Types refinfreq = freqTable_.getFrame(true);
925    MRadialVelocity::getType(refin, freqTable_.getFrameString(true));
926    MRadialVelocity::getType(refout, freqTable_.getFrameString(false));
927    SpectralCoordinate spc1 =
928      freqTable_.getSpectralCoordinate(mfreqidCol_(whichrow));
929   
930    MRadialVelocity::Ref rin(refin, frame);
931    MRadialVelocity::Ref rout(refout, frame);
932    MRadialVelocity::Convert cnv(rin, rout);
933    Vector<Double> worlds(2); 
934    Double deltav;
935    for ( int i=0; i < nchan; ++i) {     
936     
937      Double worldi;
938      if (i == 0) {
939        for (uInt k = 0; k<2;++k) {
940          spc1.toWorld(worlds[i+k], pixel[i+k]);
941          MDoppler mdop =                               \
942            MFrequency(Quantity(worlds[i+k], "Hz"),
943                       refinfreq).toDoppler(Quantity(rf, "Hz"));
944          MRadialVelocity mrv = MRadialVelocity::fromDoppler(mdop, refin);
945          MRadialVelocity mrvo =  cnv(mrv);
946          //worlds[i+k] = cnv(mrv).get(us).getValue();
947         
948            MDoppler mdopo = MDoppler::Convert(mrvo.toDoppler(),
949            MDoppler::RADIO)();
950            MFrequency mf = MFrequency::fromDoppler(mdopo,
951            MVFrequency(Quantity(rf, "Hz")));
952            worlds[i+k] = mf.get("GHz").getValue();
953       
954        }
955      }     
956      deltav = worlds[1]-worlds[0];
957      worldi = worlds[0] + Double(i)*deltav;
958      stlout.push_back(double(worldi));
959    }
960    cout << worlds[0] << " + " << deltav <<  "+" << spc1.increment() << endl;
961  }
962  return stlout;
963}
964void Scantable::setDirectionRefString( const std::string & refstr )
965{
966  MDirection::Types mdt;
967  if (refstr != "" && !MDirection::getType(mdt, refstr)) {
968    throw(AipsError("Illegal Direction frame."));
969  }
970  if ( refstr == "" ) {
971    String defaultstr = MDirection::showType(dirCol_.getMeasRef().getType());
972    table_.rwKeywordSet().define("DIRECTIONREF", defaultstr);
973  } else {
974    table_.rwKeywordSet().define("DIRECTIONREF", String(refstr));
975  }
976}
977
978std::string Scantable::getDirectionRefString( ) const
979{
980  return table_.keywordSet().asString("DIRECTIONREF");
981}
982
983MDirection Scantable::getDirection(int whichrow ) const
984{
985  String usertype = table_.keywordSet().asString("DIRECTIONREF");
986  String type = MDirection::showType(dirCol_.getMeasRef().getType());
987  if ( usertype != type ) {
988    MDirection::Types mdt;
989    if (!MDirection::getType(mdt, usertype)) {
990      throw(AipsError("Illegal Direction frame."));
991    }
992    return dirCol_.convert(uInt(whichrow), mdt);
993  } else {
994    return dirCol_(uInt(whichrow));
995  }
996}
997
998std::string Scantable::getAbcissaLabel( int whichrow ) const
999{
1000  if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal ro number"));
1001  const MPosition& mp = getAntennaPosition();
1002  const MDirection& md = getDirection(whichrow);
1003  const MEpoch& me = timeCol_(whichrow);
1004  const Double& rf = mmolidCol_(whichrow);
1005  SpectralCoordinate spc =
1006    freqTable_.getSpectralCoordinate(md, mp, me, rf, mfreqidCol_(whichrow));
1007
1008  String s = "Channel";
1009  Unit u = Unit(freqTable_.getUnitString());
1010  if (u == Unit("km/s")) {
1011    s = CoordinateUtil::axisLabel(spc, 0, True,True,  True);
1012  } else if (u == Unit("Hz")) {
1013    Vector<String> wau(1);wau = u.getName();
1014    spc.setWorldAxisUnits(wau);
1015    s = CoordinateUtil::axisLabel(spc, 0, True, True, False);
1016  }
1017  return s;
1018
1019}
1020
1021void Scantable::setRestFrequencies( double rf, const std::string& name,
1022                                          const std::string& unit )
1023{
1024  ///@todo lookup in line table to fill in name and formattedname
1025  Unit u(unit);
1026  Quantum<Double> urf(rf, u);
1027  uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), name, "");
1028  TableVector<uInt> tabvec(table_, "MOLECULE_ID");
1029  tabvec = id;
1030}
1031
1032void Scantable::setRestFrequencies( const std::string& name )
1033{
1034  throw(AipsError("setRestFrequencies( const std::string& name ) NYI"));
1035  ///@todo implement
1036}
1037
1038std::vector< unsigned int > Scantable::rownumbers( ) const
1039{
1040  std::vector<unsigned int> stlout;
1041  Vector<uInt> vec = table_.rowNumbers();
1042  vec.tovector(stlout);
1043  return stlout;
1044}
1045
1046
1047Matrix<Float> Scantable::getPolMatrix( uInt whichrow ) const
1048{
1049  ROTableRow row(table_);
1050  const TableRecord& rec = row.get(whichrow);
1051  Table t =
1052    originalTable_( originalTable_.col("SCANNO") == Int(rec.asuInt("SCANNO"))
1053                    && originalTable_.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
1054                    && originalTable_.col("IFNO") == Int(rec.asuInt("IFNO"))
1055                    && originalTable_.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
1056  ROArrayColumn<Float> speccol(t, "SPECTRA");
1057  return speccol.getColumn();
1058}
1059
1060std::vector< std::string > Scantable::columnNames( ) const
1061{
1062  Vector<String> vec = table_.tableDesc().columnNames();
1063  return mathutil::tovectorstring(vec);
1064}
1065
1066MEpoch::Types Scantable::getTimeReference( ) const
1067{
1068  return MEpoch::castType(timeCol_.getMeasRef().getType());
1069}
1070
1071void Scantable::addFit( const STFitEntry& fit, int row )
1072{
1073  cout << mfitidCol_(uInt(row)) << endl;
1074  uInt id = fitTable_.addEntry(fit, mfitidCol_(uInt(row)));
1075  mfitidCol_.put(uInt(row), id);
1076}
1077
1078void Scantable::shift(int npix)
1079{
1080  Vector<uInt> fids(mfreqidCol_.getColumn());
1081  genSort( fids, Sort::Ascending,
1082           Sort::QuickSort|Sort::NoDuplicates );
1083  for (uInt i=0; i<fids.nelements(); ++i) {
1084    frequencies().shiftRefPix(npix, i);
1085  }
1086}
1087
1088std::string asap::Scantable::getAntennaName() const
1089{
1090  String out;
1091  table_.keywordSet().get("AntennaName", out);
1092  return out;
1093}
1094
1095int asap::Scantable::checkScanInfo(const std::vector<int>& scanlist) const
1096{
1097  String tbpath;
1098  int ret = 0;
1099  if ( table_.keywordSet().isDefined("GBT_GO") ) {
1100    table_.keywordSet().get("GBT_GO", tbpath);
1101    Table t(tbpath,Table::Old);
1102    // check each scan if other scan of the pair exist
1103    int nscan = scanlist.size();
1104    for (int i = 0; i < nscan; i++) {
1105      Table subt = t( t.col("SCAN") == scanlist[i]+1 );
1106      if (subt.nrow()==0) {
1107        cerr <<"Scan "<<scanlist[i]<<" cannot be found in the scantable."<<endl;
1108        ret = 1;
1109        break;
1110      }
1111      ROTableRow row(subt);
1112      const TableRecord& rec = row.get(0);
1113      int scan1seqn = rec.asuInt("PROCSEQN");
1114      int laston1 = rec.asuInt("LASTON");
1115      if ( rec.asuInt("PROCSIZE")==2 ) {
1116        if ( i < nscan-1 ) {
1117          Table subt2 = t( t.col("SCAN") == scanlist[i+1]+1 );
1118          if ( subt2.nrow() == 0) {
1119            cerr<<"Scan "<<scanlist[i+1]<<" cannot be found in the scantable."<<endl;
1120            ret = 1;
1121            break;
1122          }
1123          ROTableRow row2(subt2);
1124          const TableRecord& rec2 = row2.get(0);
1125          int scan2seqn = rec2.asuInt("PROCSEQN");
1126          int laston2 = rec2.asuInt("LASTON");
1127          if (scan1seqn == 1 && scan2seqn == 2) {
1128            if (laston1 == laston2) {
1129              cerr<<"A valid scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl;
1130              i +=1;
1131            }
1132            else {
1133              cerr<<"Incorrect scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl;
1134            }
1135          }
1136          else if (scan1seqn==2 && scan2seqn == 1) {
1137            if (laston1 == laston2) {
1138              cerr<<"["<<scanlist[i]<<","<<scanlist[i+1]<<"] is a valid scan pair but in incorrect order."<<endl;
1139              ret = 1;
1140              break;
1141            }
1142          }
1143          else {
1144            cerr<<"The other scan for  "<<scanlist[i]<<" appears to be missing. Check the input scan numbers."<<endl;
1145            ret = 1;
1146            break;
1147          }
1148        }
1149      }
1150      else {
1151        cerr<<"The scan does not appear to be standard obsevation."<<endl;
1152      }
1153    //if ( i >= nscan ) break;
1154    }
1155  }
1156  else {
1157    cerr<<"No reference to GBT_GO table."<<endl;
1158    ret = 1;
1159  }
1160  return ret;
1161}
1162
1163std::vector<double>  asap::Scantable::getDirectionVector(int whichrow) const
1164{
1165  Vector<Double> Dir = dirCol_(whichrow).getAngle("rad").getValue();
1166  std::vector<double> dir;
1167  Dir.tovector(dir);
1168  return dir;
1169}
1170
1171}
1172 //namespace asap
Note: See TracBrowser for help on using the repository browser.