source: trunk/src/Scantable.cpp @ 1728

Last change on this file since 1728 was 1728, checked in by Malte Marquarding, 14 years ago

Ticket #181: got my logic reversed (again)

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