source: trunk/src/Scantable.cpp @ 1333

Last change on this file since 1333 was 1333, checked in by mar637, 17 years ago

Fix for Ticket #104; protect the user from flagging the whole scantable. This has performance penalties.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 31.1 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/MDirection.h>
52#include <measures/Measures/MFrequency.h>
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>
58#include <coordinates/Coordinates/CoordinateUtil.h>
59
60#include "Scantable.h"
61#include "STPolLinear.h"
62#include "STPolCircular.h"
63#include "STPolStokes.h"
64#include "STAttr.h"
65#include "MathUtils.h"
66
67using namespace casa;
68
69namespace asap {
70
71std::map<std::string, STPol::STPolFactory *> Scantable::factories_;
72
73void Scantable::initFactories() {
74  if ( factories_.empty() ) {
75    Scantable::factories_["linear"] = &STPolLinear::myFactory;
76    Scantable::factories_["circular"] = &STPolCircular::myFactory;
77    Scantable::factories_["stokes"] = &STPolStokes::myFactory;
78  }
79}
80
81Scantable::Scantable(Table::TableType ttype) :
82  type_(ttype)
83{
84  initFactories();
85  setupMainTable();
86  freqTable_ = STFrequencies(*this);
87  table_.rwKeywordSet().defineTable("FREQUENCIES", freqTable_.table());
88  weatherTable_ = STWeather(*this);
89  table_.rwKeywordSet().defineTable("WEATHER", weatherTable_.table());
90  focusTable_ = STFocus(*this);
91  table_.rwKeywordSet().defineTable("FOCUS", focusTable_.table());
92  tcalTable_ = STTcal(*this);
93  table_.rwKeywordSet().defineTable("TCAL", tcalTable_.table());
94  moleculeTable_ = STMolecules(*this);
95  table_.rwKeywordSet().defineTable("MOLECULES", moleculeTable_.table());
96  historyTable_ = STHistory(*this);
97  table_.rwKeywordSet().defineTable("HISTORY", historyTable_.table());
98  fitTable_ = STFit(*this);
99  table_.rwKeywordSet().defineTable("FIT", fitTable_.table());
100  originalTable_ = table_;
101  attach();
102}
103
104Scantable::Scantable(const std::string& name, Table::TableType ttype) :
105  type_(ttype)
106{
107  initFactories();
108  Table tab(name, Table::Update);
109  uInt version = tab.keywordSet().asuInt("VERSION");
110  if (version != version_) {
111    throw(AipsError("Unsupported version of ASAP file."));
112  }
113  if ( type_ == Table::Memory ) {
114    table_ = tab.copyToMemoryTable(generateName());
115  } else {
116    table_ = tab;
117  }
118
119  attachSubtables();
120  originalTable_ = table_;
121  attach();
122}
123
124Scantable::Scantable( const Scantable& other, bool clear )
125{
126  // with or without data
127  String newname = String(generateName());
128  type_ = other.table_.tableType();
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);
135  } else {
136      other.table_.deepCopy(newname, Table::New, False,
137                            other.table_.endianFormat(),
138                            Bool(clear));
139      table_ = Table(newname, Table::Update);
140      table_.markForDelete();
141  }
142  /// @todo reindex SCANNO, recompute nbeam, nif, npol
143  if ( clear ) copySubtables(other);
144  attachSubtables();
145  originalTable_ = table_;
146  attach();
147}
148
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());
162  t = table_.rwKeywordSet().asTable("FIT");
163  TableCopy::copyRows(t, other.fitTable_.table());
164}
165
166void Scantable::attachSubtables()
167{
168  freqTable_ = STFrequencies(table_);
169  focusTable_ = STFocus(table_);
170  weatherTable_ = STWeather(table_);
171  tcalTable_ = STTcal(table_);
172  moleculeTable_ = STMolecules(table_);
173  historyTable_ = STHistory(table_);
174  fitTable_ = STFit(table_);
175}
176
177Scantable::~Scantable()
178{
179  //cout << "~Scantable() " << this << endl;
180}
181
182void Scantable::setupMainTable()
183{
184  TableDesc td("", "1", TableDesc::Scratch);
185  td.comment() = "An ASAP Scantable";
186  td.rwKeywordSet().define("VERSION", uInt(version_));
187
188  // n Cycles
189  td.addColumn(ScalarColumnDesc<uInt>("SCANNO"));
190  // new index every nBeam x nIF x nPol
191  td.addColumn(ScalarColumnDesc<uInt>("CYCLENO"));
192
193  td.addColumn(ScalarColumnDesc<uInt>("BEAMNO"));
194  td.addColumn(ScalarColumnDesc<uInt>("IFNO"));
195  // linear, circular, stokes
196  td.rwKeywordSet().define("POLTYPE", String("linear"));
197  td.addColumn(ScalarColumnDesc<uInt>("POLNO"));
198
199  td.addColumn(ScalarColumnDesc<uInt>("FREQ_ID"));
200  td.addColumn(ScalarColumnDesc<uInt>("MOLECULE_ID"));
201  td.addColumn(ScalarColumnDesc<Int>("REFBEAMNO"));
202
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);
208
209  td.addColumn(ScalarColumnDesc<Double>("INTERVAL"));
210
211  td.addColumn(ScalarColumnDesc<String>("SRCNAME"));
212  // Type of source (on=0, off=1, other=-1)
213  td.addColumn(ScalarColumnDesc<Int>("SRCTYPE", Int(-1)));
214  td.addColumn(ScalarColumnDesc<String>("FIELDNAME"));
215
216  //The actual Data Vectors
217  td.addColumn(ArrayColumnDesc<Float>("SPECTRA"));
218  td.addColumn(ArrayColumnDesc<uChar>("FLAGTRA"));
219  td.addColumn(ArrayColumnDesc<Float>("TSYS"));
220
221  td.addColumn(ArrayColumnDesc<Double>("DIRECTION",
222                                       IPosition(1,2),
223                                       ColumnDesc::Direct));
224  TableMeasRefDesc mdirRef(MDirection::J2000); // default
225  TableMeasValueDesc tmvdMDir(td, "DIRECTION");
226  // the TableMeasDesc gives the column a type
227  TableMeasDesc<MDirection> mdirCol(tmvdMDir, mdirRef);
228  // a uder set table type e.g. GALCTIC, B1950 ...
229  td.rwKeywordSet().define("DIRECTIONREF", String("J2000"));
230  // writing create the measure column
231  mdirCol.write(td);
232  td.addColumn(ScalarColumnDesc<Float>("AZIMUTH"));
233  td.addColumn(ScalarColumnDesc<Float>("ELEVATION"));
234  td.addColumn(ScalarColumnDesc<Float>("PARANGLE"));
235  td.addColumn(ScalarColumnDesc<Float>("OPACITY"));
236
237  td.addColumn(ScalarColumnDesc<uInt>("TCAL_ID"));
238  ScalarColumnDesc<Int> fitColumn("FIT_ID");
239  fitColumn.setDefault(Int(-1));
240  td.addColumn(fitColumn);
241
242  td.addColumn(ScalarColumnDesc<uInt>("FOCUS_ID"));
243  td.addColumn(ScalarColumnDesc<uInt>("WEATHER_ID"));
244
245  // columns which just get dragged along, as they aren't used in asap
246  td.addColumn(ScalarColumnDesc<Double>("SRCVELOCITY"));
247  td.addColumn(ArrayColumnDesc<Double>("SRCPROPERMOTION"));
248  td.addColumn(ArrayColumnDesc<Double>("SRCDIRECTION"));
249  td.addColumn(ArrayColumnDesc<Double>("SCANRATE"));
250
251  td.rwKeywordSet().define("OBSMODE", String(""));
252
253  // Now create Table SetUp from the description.
254  SetupNewTable aNewTab(generateName(), td, Table::Scratch);
255  table_ = Table(aNewTab, type_, 0);
256  originalTable_ = table_;
257}
258
259
260void Scantable::attach()
261{
262  timeCol_.attach(table_, "TIME");
263  srcnCol_.attach(table_, "SRCNAME");
264  srctCol_.attach(table_, "SRCTYPE");
265  specCol_.attach(table_, "SPECTRA");
266  flagsCol_.attach(table_, "FLAGTRA");
267  tsysCol_.attach(table_, "TSYS");
268  cycleCol_.attach(table_,"CYCLENO");
269  scanCol_.attach(table_, "SCANNO");
270  beamCol_.attach(table_, "BEAMNO");
271  ifCol_.attach(table_, "IFNO");
272  polCol_.attach(table_, "POLNO");
273  integrCol_.attach(table_, "INTERVAL");
274  azCol_.attach(table_, "AZIMUTH");
275  elCol_.attach(table_, "ELEVATION");
276  dirCol_.attach(table_, "DIRECTION");
277  paraCol_.attach(table_, "PARANGLE");
278  fldnCol_.attach(table_, "FIELDNAME");
279  rbeamCol_.attach(table_, "REFBEAMNO");
280
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");
286}
287
288void Scantable::setHeader(const STHeader& sdh)
289{
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);
304  table_.rwKeywordSet().define("FluxUnit", sdh.fluxunit);
305  table_.rwKeywordSet().define("Epoch", sdh.epoch);
306  table_.rwKeywordSet().define("POLTYPE", sdh.poltype);
307}
308
309STHeader Scantable::getHeader() const
310{
311  STHeader sdh;
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);
326  table_.keywordSet().get("FluxUnit", sdh.fluxunit);
327  table_.keywordSet().get("Epoch", sdh.epoch);
328  table_.keywordSet().get("POLTYPE", sdh.poltype);
329  return sdh;
330}
331
332void asap::Scantable::setSourceType( int stype )
333{
334  if ( stype < 0 || stype > 1 )
335    throw(AipsError("Illegal sourcetype."));
336  TableVector<Int> tabvec(table_, "SRCTYPE");
337  tabvec = Int(stype);
338}
339
340bool Scantable::conformant( const Scantable& other )
341{
342  return this->getHeader().conformant(other.getHeader());
343}
344
345
346
347std::string Scantable::formatSec(Double x) const
348{
349  Double xcop = x;
350  MVTime mvt(xcop/24./3600.);  // make days
351
352  if (x < 59.95)
353    return  String("      ") + mvt.string(MVTime::TIME_CLEAN_NO_HM, 7)+"s";
354  else if (x < 3599.95)
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);
361  }
362};
363
364std::string Scantable::formatDirection(const MDirection& md) const
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);
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  }
376  MVAngle mvLat(t[1]);
377  String sLat = mvLat.string(MVAngle::ANGLE+MVAngle::DIG2,prec);
378  return sLon + String(" ") + sLat;
379}
380
381
382std::string Scantable::getFluxUnit() const
383{
384  return table_.keywordSet().asString("FluxUnit");
385}
386
387void Scantable::setFluxUnit(const std::string& unit)
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
398void Scantable::setInstrument(const std::string& name)
399{
400  bool throwIt = true;
401  // create an Instrument to see if this is valid
402  STAttr::convertInstrument(name, throwIt);
403  String nameU(name);
404  nameU.upcase();
405  table_.rwKeywordSet().define(String("AntennaName"), nameU);
406}
407
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
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}
424
425void Scantable::makePersistent(const std::string& filename)
426{
427  String inname(filename);
428  Path path(inname);
429  /// @todo reindex SCANNO, recompute nbeam, nif, npol
430  inname = path.expandedName();
431  table_.deepCopy(inname, Table::New);
432}
433
434int Scantable::nbeam( int scanno ) const
435{
436  if ( scanno < 0 ) {
437    Int n;
438    table_.keywordSet().get("nBeam",n);
439    return int(n);
440  } else {
441    // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
442    Table t = table_(table_.col("SCANNO") == scanno);
443    ROTableRow row(t);
444    const TableRecord& rec = row.get(0);
445    Table subt = t( t.col("IFNO") == Int(rec.asuInt("IFNO"))
446                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
447                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
448    ROTableVector<uInt> v(subt, "BEAMNO");
449    return int(v.nelements());
450  }
451  return 0;
452}
453
454int Scantable::nif( int scanno ) const
455{
456  if ( scanno < 0 ) {
457    Int n;
458    table_.keywordSet().get("nIF",n);
459    return int(n);
460  } else {
461    // take the first POLNO,BEAMNO,CYCLENO as nbeam shouldn't vary with these
462    Table t = table_(table_.col("SCANNO") == scanno);
463    ROTableRow row(t);
464    const TableRecord& rec = row.get(0);
465    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
466                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
467                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
468    if ( subt.nrow() == 0 ) return 0;
469    ROTableVector<uInt> v(subt, "IFNO");
470    return int(v.nelements());
471  }
472  return 0;
473}
474
475int Scantable::npol( int scanno ) const
476{
477  if ( scanno < 0 ) {
478    Int n;
479    table_.keywordSet().get("nPol",n);
480    return n;
481  } else {
482    // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
483    Table t = table_(table_.col("SCANNO") == scanno);
484    ROTableRow row(t);
485    const TableRecord& rec = row.get(0);
486    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
487                    && t.col("IFNO") == Int(rec.asuInt("IFNO"))
488                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
489    if ( subt.nrow() == 0 ) return 0;
490    ROTableVector<uInt> v(subt, "POLNO");
491    return int(v.nelements());
492  }
493  return 0;
494}
495
496int Scantable::ncycle( int scanno ) const
497{
498  if ( scanno < 0 ) {
499    Block<String> cols(2);
500    cols[0] = "SCANNO";
501    cols[1] = "CYCLENO";
502    TableIterator it(table_, cols);
503    int n = 0;
504    while ( !it.pastEnd() ) {
505      ++n;
506      ++it;
507    }
508    return n;
509  } else {
510    Table t = table_(table_.col("SCANNO") == scanno);
511    ROTableRow row(t);
512    const TableRecord& rec = row.get(0);
513    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
514                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
515                    && t.col("IFNO") == Int(rec.asuInt("IFNO")) );
516    if ( subt.nrow() == 0 ) return 0;
517    return int(subt.nrow());
518  }
519  return 0;
520}
521
522
523int Scantable::nrow( int scanno ) const
524{
525  return int(table_.nrow());
526}
527
528int Scantable::nchan( int ifno ) const
529{
530  if ( ifno < 0 ) {
531    Int n;
532    table_.keywordSet().get("nChan",n);
533    return int(n);
534  } else {
535    // take the first SCANNO,POLNO,BEAMNO,CYCLENO as nbeam shouldn't vary with these
536    Table t = table_(table_.col("IFNO") == ifno);
537    if ( t.nrow() == 0 ) return 0;
538    ROArrayColumn<Float> v(t, "SPECTRA");
539    return v.shape(0)(0);
540  }
541  return 0;
542}
543
544int Scantable::nscan() const {
545  Vector<uInt> scannos(scanCol_.getColumn());
546  uInt nout = genSort( scannos, Sort::Ascending,
547                       Sort::QuickSort|Sort::NoDuplicates );
548  return int(nout);
549}
550
551int Scantable::getChannels(int whichrow) const
552{
553  return specCol_.shape(whichrow)(0);
554}
555
556int Scantable::getBeam(int whichrow) const
557{
558  return beamCol_(whichrow);
559}
560
561std::vector<uint> Scantable::getNumbers(ScalarColumn<uInt>& col)
562{
563  Vector<uInt> nos(col.getColumn());
564  uInt n = genSort( nos, Sort::Ascending, Sort::QuickSort|Sort::NoDuplicates );
565  nos.resize(n, True);
566  std::vector<uint> stlout;
567  nos.tovector(stlout);
568  return stlout;
569}
570
571int Scantable::getIF(int whichrow) const
572{
573  return ifCol_(whichrow);
574}
575
576int Scantable::getPol(int whichrow) const
577{
578  return polCol_(whichrow);
579}
580
581std::string Scantable::formatTime(const MEpoch& me, bool showdate) const
582{
583  MVTime mvt(me.getValue());
584  if (showdate)
585    mvt.setFormat(MVTime::YMD);
586  else
587    mvt.setFormat(MVTime::TIME);
588  ostringstream oss;
589  oss << mvt;
590  return String(oss);
591}
592
593void Scantable::calculateAZEL()
594{
595  MPosition mp = getAntennaPosition();
596  MEpoch::ROScalarColumn timeCol(table_, "TIME");
597  ostringstream oss;
598  oss << "Computed azimuth/elevation using " << endl
599      << mp << endl;
600  for (Int i=0; i<nrow(); ++i) {
601    MEpoch me = timeCol(i);
602    MDirection md = getDirection(i);
603    oss  << " Time: " << formatTime(me,False) << " Direction: " << formatDirection(md)
604         << endl << "     => ";
605    MeasFrame frame(mp, me);
606    Vector<Double> azel =
607        MDirection::Convert(md, MDirection::Ref(MDirection::AZEL,
608                                                frame)
609                            )().getAngle("rad").getValue();
610    azCol_.put(i,Float(azel[0]));
611    elCol_.put(i,Float(azel[1]));
612    oss << "azel: " << azel[0]/C::pi*180.0 << " "
613        << azel[1]/C::pi*180.0 << " (deg)" << endl;
614  }
615  pushLog(String(oss));
616}
617
618void Scantable::flag(const std::vector<bool>& msk)
619{
620  std::vector<bool>::const_iterator it;
621  uInt ntrue = 0;
622  for (it = msk.begin(); it != msk.end(); ++it) {
623    if ( *it ) {
624      ntrue++;
625    }
626  }
627  if ( selector_.empty()  && (msk.size() == 0 || msk.size() == ntrue) )
628    throw(AipsError("Trying to flag whole scantable."));
629  if ( msk.size() == 0 ) {
630    uChar userflag = 1 << 7;
631    for ( uInt i=0; i<table_.nrow(); ++i) {
632      Vector<uChar> flgs = flagsCol_(i);
633      flgs = userflag;
634      flagsCol_.put(i, flgs);
635    }
636    return;
637  }
638  if ( int(msk.size()) != nchan() ) {
639    throw(AipsError("Mask has incorrect number of channels."));
640  }
641  for ( uInt i=0; i<table_.nrow(); ++i) {
642    Vector<uChar> flgs = flagsCol_(i);
643    if ( flgs.nelements() != msk.size() ) {
644      throw(AipsError("Mask has incorrect number of channels."
645                      " Probably varying with IF. Please flag per IF"));
646    }
647    std::vector<bool>::const_iterator it;
648    uInt j = 0;
649    uChar userflag = 1 << 7;
650    for (it = msk.begin(); it != msk.end(); ++it) {
651      if ( *it ) {
652        flgs(j) = userflag;
653      }
654      ++j;
655    }
656    flagsCol_.put(i, flgs);
657  }
658}
659
660std::vector<bool> Scantable::getMask(int whichrow) const
661{
662  Vector<uChar> flags;
663  flagsCol_.get(uInt(whichrow), flags);
664  Vector<Bool> bflag(flags.shape());
665  convertArray(bflag, flags);
666  bflag = !bflag;
667  std::vector<bool> mask;
668  bflag.tovector(mask);
669  return mask;
670}
671
672std::vector<float> Scantable::getSpectrum( int whichrow,
673                                           const std::string& poltype ) const
674{
675  String ptype = poltype;
676  if (poltype == "" ) ptype = getPolType();
677  if ( whichrow  < 0 || whichrow >= nrow() )
678    throw(AipsError("Illegal row number."));
679  std::vector<float> out;
680  Vector<Float> arr;
681  uInt requestedpol = polCol_(whichrow);
682  String basetype = getPolType();
683  if ( ptype == basetype ) {
684    specCol_.get(whichrow, arr);
685  } else {
686    STPol* stpol = 0;
687    stpol =STPol::getPolClass(Scantable::factories_, basetype);
688    try {
689      uInt row = uInt(whichrow);
690      stpol->setSpectra(getPolMatrix(row));
691      Float fang,fhand,parang;
692      fang = focusTable_.getTotalFeedAngle(mfocusidCol_(row));
693      fhand = focusTable_.getFeedHand(mfocusidCol_(row));
694      parang = paraCol_(row);
695      /// @todo re-enable this
696      // disable total feed angle to support paralactifying Caswell style
697      stpol->setPhaseCorrections(parang, -parang, fhand);
698      arr = stpol->getSpectrum(requestedpol, ptype);
699      delete stpol;
700    } catch (AipsError& e) {
701      delete stpol;
702      throw(e);
703    }
704  }
705  if ( arr.nelements() == 0 )
706    pushLog("Not enough polarisations present to do the conversion.");
707  arr.tovector(out);
708  return out;
709}
710
711void asap::Scantable::setSpectrum( const std::vector<float>& spec,
712                                   int whichrow )
713{
714  Vector<Float> spectrum(spec);
715  Vector<Float> arr;
716  specCol_.get(whichrow, arr);
717  if ( spectrum.nelements() != arr.nelements() )
718    throw AipsError("The spectrum has incorrect number of channels.");
719  specCol_.put(whichrow, spectrum);
720}
721
722
723String Scantable::generateName()
724{
725  return (File::newUniqueName("./","temp")).baseName();
726}
727
728const casa::Table& Scantable::table( ) const
729{
730  return table_;
731}
732
733casa::Table& Scantable::table( )
734{
735  return table_;
736}
737
738std::string Scantable::getPolType() const
739{
740  return table_.keywordSet().asString("POLTYPE");
741}
742
743void Scantable::unsetSelection()
744{
745  table_ = originalTable_;
746  attach();
747  selector_.reset();
748}
749
750void Scantable::setSelection( const STSelector& selection )
751{
752  Table tab = const_cast<STSelector&>(selection).apply(originalTable_);
753  if ( tab.nrow() == 0 ) {
754    throw(AipsError("Selection contains no data. Not applying it."));
755  }
756  table_ = tab;
757  attach();
758  selector_ = selection;
759}
760
761std::string Scantable::summary( bool verbose )
762{
763  // Format header info
764  ostringstream oss;
765  oss << endl;
766  oss << asap::SEPERATOR << endl;
767  oss << " Scan Table Summary" << endl;
768  oss << asap::SEPERATOR << endl;
769  oss.flags(std::ios_base::left);
770  oss << setw(15) << "Beams:" << setw(4) << nbeam() << endl
771      << setw(15) << "IFs:" << setw(4) << nif() << endl
772      << setw(15) << "Polarisations:" << setw(4) << npol()
773      << "(" << getPolType() << ")" << endl
774      << setw(15) << "Channels:"  << setw(4) << nchan() << endl;
775  oss << endl;
776  String tmp;
777  oss << setw(15) << "Observer:"
778      << table_.keywordSet().asString("Observer") << endl;
779  oss << setw(15) << "Obs Date:" << getTime(-1,true) << endl;
780  table_.keywordSet().get("Project", tmp);
781  oss << setw(15) << "Project:" << tmp << endl;
782  table_.keywordSet().get("Obstype", tmp);
783  oss << setw(15) << "Obs. Type:" << tmp << endl;
784  table_.keywordSet().get("AntennaName", tmp);
785  oss << setw(15) << "Antenna Name:" << tmp << endl;
786  table_.keywordSet().get("FluxUnit", tmp);
787  oss << setw(15) << "Flux Unit:" << tmp << endl;
788  Vector<Double> vec(moleculeTable_.getRestFrequencies());
789  oss << setw(15) << "Rest Freqs:";
790  if (vec.nelements() > 0) {
791      oss << setprecision(10) << vec << " [Hz]" << endl;
792  } else {
793      oss << "none" << endl;
794  }
795
796  oss << setw(15) << "Abcissa:" << getAbcissaLabel(0) << endl;
797  oss << selector_.print() << endl;
798  oss << endl;
799  // main table
800  String dirtype = "Position ("
801                  + getDirectionRefString()
802                  + ")";
803  oss << setw(5) << "Scan" << setw(15) << "Source"
804      << setw(10) << "Time" << setw(18) << "Integration" << endl;
805  oss << setw(5) << "" << setw(5) << "Beam" << setw(3) << "" << dirtype << endl;
806  oss << setw(10) << "" << setw(3) << "IF" << setw(6) << ""
807      << setw(8) << "Frame" << setw(16)
808      << "RefVal" << setw(10) << "RefPix" << setw(12) << "Increment" <<endl;
809  oss << asap::SEPERATOR << endl;
810  TableIterator iter(table_, "SCANNO");
811  while (!iter.pastEnd()) {
812    Table subt = iter.table();
813    ROTableRow row(subt);
814    MEpoch::ROScalarColumn timeCol(subt,"TIME");
815    const TableRecord& rec = row.get(0);
816    oss << setw(4) << std::right << rec.asuInt("SCANNO")
817        << std::left << setw(1) << ""
818        << setw(15) << rec.asString("SRCNAME")
819        << setw(10) << formatTime(timeCol(0), false);
820    // count the cycles in the scan
821    TableIterator cyciter(subt, "CYCLENO");
822    int nint = 0;
823    while (!cyciter.pastEnd()) {
824      ++nint;
825      ++cyciter;
826    }
827    oss << setw(3) << std::right << nint  << setw(3) << " x " << std::left
828        << setw(6) <<  formatSec(rec.asFloat("INTERVAL")) << endl;
829
830    TableIterator biter(subt, "BEAMNO");
831    while (!biter.pastEnd()) {
832      Table bsubt = biter.table();
833      ROTableRow brow(bsubt);
834      const TableRecord& brec = brow.get(0);
835      uInt row0 = bsubt.rowNumbers(table_)[0];
836      oss << setw(5) << "" <<  setw(4) << std::right << brec.asuInt("BEAMNO")<< std::left;
837      oss  << setw(4) << ""  << formatDirection(getDirection(row0)) << endl;
838      TableIterator iiter(bsubt, "IFNO");
839      while (!iiter.pastEnd()) {
840        Table isubt = iiter.table();
841        ROTableRow irow(isubt);
842        const TableRecord& irec = irow.get(0);
843        oss << setw(10) << "";
844        oss << setw(3) << std::right << irec.asuInt("IFNO") << std::left
845            << setw(2) << "" << frequencies().print(irec.asuInt("FREQ_ID"));
846
847        ++iiter;
848      }
849      ++biter;
850    }
851    ++iter;
852  }
853  /// @todo implement verbose mode
854  return String(oss);
855}
856
857std::string Scantable::getTime(int whichrow, bool showdate) const
858{
859  MEpoch::ROScalarColumn timeCol(table_, "TIME");
860  MEpoch me;
861  if (whichrow > -1) {
862    me = timeCol(uInt(whichrow));
863  } else {
864    Double tm;
865    table_.keywordSet().get("UTC",tm);
866    me = MEpoch(MVEpoch(tm));
867  }
868  return formatTime(me, showdate);
869}
870
871std::string Scantable::getDirectionString(int whichrow) const
872{
873  return formatDirection(getDirection(uInt(whichrow)));
874}
875
876std::vector< double > asap::Scantable::getAbcissa( int whichrow ) const
877{
878  if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal ro number"));
879  std::vector<double> stlout;
880  int nchan = specCol_(whichrow).nelements();
881  String us = freqTable_.getUnitString();
882  if ( us == "" || us == "pixel" || us == "channel" ) {
883    for (int i=0; i<nchan; ++i) {
884      stlout.push_back(double(i));
885    }
886    return stlout;
887  }
888
889  const MPosition& mp = getAntennaPosition();
890  const MDirection& md = getDirection(whichrow);
891  const MEpoch& me = timeCol_(whichrow);
892  Double rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
893  SpectralCoordinate spc =
894    freqTable_.getSpectralCoordinate(md, mp, me, rf, mfreqidCol_(whichrow));
895  Vector<Double> pixel(nchan);
896  Vector<Double> world;
897  indgen(pixel);
898  if ( Unit(us) == Unit("Hz") ) {
899    for ( int i=0; i < nchan; ++i) {
900      Double world;
901      spc.toWorld(world, pixel[i]);
902      stlout.push_back(double(world));
903    }
904  } else if ( Unit(us) == Unit("km/s") ) {
905    Vector<Double> world;
906    spc.pixelToVelocity(world, pixel);
907    world.tovector(stlout);
908  }
909  return stlout;
910}
911void asap::Scantable::setDirectionRefString( const std::string & refstr )
912{
913  MDirection::Types mdt;
914  if (refstr != "" && !MDirection::getType(mdt, refstr)) {
915    throw(AipsError("Illegal Direction frame."));
916  }
917  if ( refstr == "" ) {
918    String defaultstr = MDirection::showType(dirCol_.getMeasRef().getType());
919    table_.rwKeywordSet().define("DIRECTIONREF", defaultstr);
920  } else {
921    table_.rwKeywordSet().define("DIRECTIONREF", String(refstr));
922  }
923}
924
925std::string asap::Scantable::getDirectionRefString( ) const
926{
927  return table_.keywordSet().asString("DIRECTIONREF");
928}
929
930MDirection Scantable::getDirection(int whichrow ) const
931{
932  String usertype = table_.keywordSet().asString("DIRECTIONREF");
933  String type = MDirection::showType(dirCol_.getMeasRef().getType());
934  if ( usertype != type ) {
935    MDirection::Types mdt;
936    if (!MDirection::getType(mdt, usertype)) {
937      throw(AipsError("Illegal Direction frame."));
938    }
939    return dirCol_.convert(uInt(whichrow), mdt);
940  } else {
941    return dirCol_(uInt(whichrow));
942  }
943}
944
945std::string Scantable::getAbcissaLabel( int whichrow ) const
946{
947  if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal ro number"));
948  const MPosition& mp = getAntennaPosition();
949  const MDirection& md = getDirection(whichrow);
950  const MEpoch& me = timeCol_(whichrow);
951  const Double& rf = mmolidCol_(whichrow);
952  SpectralCoordinate spc =
953    freqTable_.getSpectralCoordinate(md, mp, me, rf, mfreqidCol_(whichrow));
954
955  String s = "Channel";
956  Unit u = Unit(freqTable_.getUnitString());
957  if (u == Unit("km/s")) {
958    s = CoordinateUtil::axisLabel(spc, 0, True,True,  True);
959  } else if (u == Unit("Hz")) {
960    Vector<String> wau(1);wau = u.getName();
961    spc.setWorldAxisUnits(wau);
962    s = CoordinateUtil::axisLabel(spc, 0, True, True, False);
963  }
964  return s;
965
966}
967
968void asap::Scantable::setRestFrequencies( double rf, const std::string& name,
969                                          const std::string& unit )
970{
971  ///@todo lookup in line table to fill in name and formattedname
972  Unit u(unit);
973  Quantum<Double> urf(rf, u);
974  uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), name, "");
975  TableVector<uInt> tabvec(table_, "MOLECULE_ID");
976  tabvec = id;
977}
978
979void asap::Scantable::setRestFrequencies( const std::string& name )
980{
981  throw(AipsError("setRestFrequencies( const std::string& name ) NYI"));
982  ///@todo implement
983}
984
985std::vector< unsigned int > asap::Scantable::rownumbers( ) const
986{
987  std::vector<unsigned int> stlout;
988  Vector<uInt> vec = table_.rowNumbers();
989  vec.tovector(stlout);
990  return stlout;
991}
992
993
994Matrix<Float> asap::Scantable::getPolMatrix( uInt whichrow ) const
995{
996  ROTableRow row(table_);
997  const TableRecord& rec = row.get(whichrow);
998  Table t =
999    originalTable_( originalTable_.col("SCANNO") == Int(rec.asuInt("SCANNO"))
1000                    && originalTable_.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
1001                    && originalTable_.col("IFNO") == Int(rec.asuInt("IFNO"))
1002                    && originalTable_.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
1003  ROArrayColumn<Float> speccol(t, "SPECTRA");
1004  return speccol.getColumn();
1005}
1006
1007std::vector< std::string > asap::Scantable::columnNames( ) const
1008{
1009  Vector<String> vec = table_.tableDesc().columnNames();
1010  return mathutil::tovectorstring(vec);
1011}
1012
1013casa::MEpoch::Types asap::Scantable::getTimeReference( ) const
1014{
1015  return MEpoch::castType(timeCol_.getMeasRef().getType());
1016}
1017
1018void Scantable::addFit( const STFitEntry & fit, int row )
1019{
1020  cout << mfitidCol_(uInt(row)) << endl;
1021  uInt id = fitTable_.addEntry(fit, mfitidCol_(uInt(row)));
1022  mfitidCol_.put(uInt(row), id);
1023}
1024
1025
1026}
1027 //namespace asap
Note: See TracBrowser for help on using the repository browser.