source: branches/alma/src/Scantable.cpp @ 1603

Last change on this file since 1603 was 1603, checked in by TakTsutsumi, 15 years ago

New Development: No, merge with asap2.3.1

JIRA Issue: Yes CAS-1450

Ready to Release: Yes/No?

Interface Changes: Yes/No?

What Interface Changed: Please list interface changes

Test Programs: List test programs

Put in Release Notes: Yes

Module(s): single dish

Description: Upgrade of alma branch based on ASAP2.2.0

(rev.1562) to ASAP2.3.1 (rev.1561)


  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 43.5 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>
[1446]13#include <fstream>
[206]14
[125]15#include <casa/aips.h>
[80]16#include <casa/iostream.h>
17#include <casa/iomanip.h>
[805]18#include <casa/OS/Path.h>
19#include <casa/OS/File.h>
[80]20#include <casa/Arrays/Array.h>
21#include <casa/Arrays/ArrayMath.h>
22#include <casa/Arrays/MaskArrMath.h>
23#include <casa/Arrays/ArrayLogical.h>
24#include <casa/Arrays/ArrayAccessor.h>
[1325]25#include <casa/Arrays/Vector.h>
[455]26#include <casa/Arrays/VectorSTLIterator.h>
[1446]27#include <casa/Arrays/Slice.h>
[418]28#include <casa/BasicMath/Math.h>
[504]29#include <casa/BasicSL/Constants.h>
[286]30#include <casa/Quanta/MVAngle.h>
[805]31#include <casa/Containers/RecordField.h>
[902]32#include <casa/Utilities/GenSort.h>
[2]33
[80]34#include <tables/Tables/TableParse.h>
35#include <tables/Tables/TableDesc.h>
[488]36#include <tables/Tables/TableCopy.h>
[80]37#include <tables/Tables/SetupNewTab.h>
38#include <tables/Tables/ScaColDesc.h>
39#include <tables/Tables/ArrColDesc.h>
[805]40#include <tables/Tables/TableRow.h>
41#include <tables/Tables/TableVector.h>
42#include <tables/Tables/TableIter.h>
[2]43
[80]44#include <tables/Tables/ExprNode.h>
45#include <tables/Tables/TableRecord.h>
[1325]46#include <casa/Quanta/MVTime.h>
47#include <casa/Quanta/MVAngle.h>
48#include <measures/Measures/MeasRef.h>
49#include <measures/Measures/MeasTable.h>
50// needed to avoid error in .tcc
51#include <measures/Measures/MCDirection.h>
52//
53#include <measures/Measures/MDirection.h>
[80]54#include <measures/Measures/MFrequency.h>
[805]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>
[105]60#include <coordinates/Coordinates/CoordinateUtil.h>
[2]61
[805]62#include "Scantable.h"
[896]63#include "STPolLinear.h"
[1189]64#include "STPolCircular.h"
[913]65#include "STPolStokes.h"
[878]66#include "STAttr.h"
[902]67#include "MathUtils.h"
[2]68
[125]69using namespace casa;
[2]70
[805]71namespace asap {
72
[896]73std::map<std::string, STPol::STPolFactory *> Scantable::factories_;
74
75void Scantable::initFactories() {
76  if ( factories_.empty() ) {
77    Scantable::factories_["linear"] = &STPolLinear::myFactory;
[1323]78    Scantable::factories_["circular"] = &STPolCircular::myFactory;
[913]79    Scantable::factories_["stokes"] = &STPolStokes::myFactory;
[896]80  }
81}
82
[805]83Scantable::Scantable(Table::TableType ttype) :
[852]84  type_(ttype)
[206]85{
[896]86  initFactories();
[805]87  setupMainTable();
[852]88  freqTable_ = STFrequencies(*this);
[805]89  table_.rwKeywordSet().defineTable("FREQUENCIES", freqTable_.table());
[852]90  weatherTable_ = STWeather(*this);
[805]91  table_.rwKeywordSet().defineTable("WEATHER", weatherTable_.table());
[852]92  focusTable_ = STFocus(*this);
[805]93  table_.rwKeywordSet().defineTable("FOCUS", focusTable_.table());
[852]94  tcalTable_ = STTcal(*this);
[805]95  table_.rwKeywordSet().defineTable("TCAL", tcalTable_.table());
[852]96  moleculeTable_ = STMolecules(*this);
[805]97  table_.rwKeywordSet().defineTable("MOLECULES", moleculeTable_.table());
[860]98  historyTable_ = STHistory(*this);
99  table_.rwKeywordSet().defineTable("HISTORY", historyTable_.table());
[959]100  fitTable_ = STFit(*this);
101  table_.rwKeywordSet().defineTable("FIT", fitTable_.table());
[805]102  originalTable_ = table_;
[322]103  attach();
[18]104}
[206]105
[805]106Scantable::Scantable(const std::string& name, Table::TableType ttype) :
[852]107  type_(ttype)
[206]108{
[896]109  initFactories();
[865]110  Table tab(name, Table::Update);
[1009]111  uInt version = tab.keywordSet().asuInt("VERSION");
[483]112  if (version != version_) {
113    throw(AipsError("Unsupported version of ASAP file."));
114  }
[1009]115  if ( type_ == Table::Memory ) {
[852]116    table_ = tab.copyToMemoryTable(generateName());
[1009]117  } else {
[805]118    table_ = tab;
[1009]119  }
120
[859]121  attachSubtables();
[805]122  originalTable_ = table_;
[329]123  attach();
[2]124}
125
[805]126Scantable::Scantable( const Scantable& other, bool clear )
[206]127{
[805]128  // with or without data
[859]129  String newname = String(generateName());
[865]130  type_ = other.table_.tableType();
[859]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);
[16]137  } else {
[915]138      other.table_.deepCopy(newname, Table::New, False,
139                            other.table_.endianFormat(),
[865]140                            Bool(clear));
141      table_ = Table(newname, Table::Update);
142      table_.markForDelete();
143  }
[1111]144  /// @todo reindex SCANNO, recompute nbeam, nif, npol
[915]145  if ( clear ) copySubtables(other);
[859]146  attachSubtables();
[805]147  originalTable_ = table_;
[322]148  attach();
[2]149}
150
[865]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());
[972]164  t = table_.rwKeywordSet().asTable("FIT");
165  TableCopy::copyRows(t, other.fitTable_.table());
[865]166}
167
[859]168void Scantable::attachSubtables()
169{
170  freqTable_ = STFrequencies(table_);
171  focusTable_ = STFocus(table_);
172  weatherTable_ = STWeather(table_);
173  tcalTable_ = STTcal(table_);
174  moleculeTable_ = STMolecules(table_);
[860]175  historyTable_ = STHistory(table_);
[972]176  fitTable_ = STFit(table_);
[859]177}
178
[805]179Scantable::~Scantable()
[206]180{
[941]181  //cout << "~Scantable() " << this << endl;
[2]182}
183
[805]184void Scantable::setupMainTable()
[206]185{
[805]186  TableDesc td("", "1", TableDesc::Scratch);
187  td.comment() = "An ASAP Scantable";
[1009]188  td.rwKeywordSet().define("VERSION", uInt(version_));
[2]189
[805]190  // n Cycles
191  td.addColumn(ScalarColumnDesc<uInt>("SCANNO"));
192  // new index every nBeam x nIF x nPol
193  td.addColumn(ScalarColumnDesc<uInt>("CYCLENO"));
[2]194
[805]195  td.addColumn(ScalarColumnDesc<uInt>("BEAMNO"));
196  td.addColumn(ScalarColumnDesc<uInt>("IFNO"));
[972]197  // linear, circular, stokes
[805]198  td.rwKeywordSet().define("POLTYPE", String("linear"));
199  td.addColumn(ScalarColumnDesc<uInt>("POLNO"));
[138]200
[805]201  td.addColumn(ScalarColumnDesc<uInt>("FREQ_ID"));
202  td.addColumn(ScalarColumnDesc<uInt>("MOLECULE_ID"));
203  td.addColumn(ScalarColumnDesc<Int>("REFBEAMNO"));
[80]204
[805]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);
[483]210
[805]211  td.addColumn(ScalarColumnDesc<Double>("INTERVAL"));
212
[2]213  td.addColumn(ScalarColumnDesc<String>("SRCNAME"));
[805]214  // Type of source (on=0, off=1, other=-1)
[1603]215  ScalarColumnDesc<Int> stypeColumn("SRCTYPE");
216  stypeColumn.setDefault(Int(-1));
217  td.addColumn(stypeColumn);
[805]218  td.addColumn(ScalarColumnDesc<String>("FIELDNAME"));
219
220  //The actual Data Vectors
[2]221  td.addColumn(ArrayColumnDesc<Float>("SPECTRA"));
222  td.addColumn(ArrayColumnDesc<uChar>("FLAGTRA"));
[89]223  td.addColumn(ArrayColumnDesc<Float>("TSYS"));
[805]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);
[987]232  // a uder set table type e.g. GALCTIC, B1950 ...
233  td.rwKeywordSet().define("DIRECTIONREF", String("J2000"));
[805]234  // writing create the measure column
235  mdirCol.write(td);
[923]236  td.addColumn(ScalarColumnDesc<Float>("AZIMUTH"));
237  td.addColumn(ScalarColumnDesc<Float>("ELEVATION"));
[105]238  td.addColumn(ScalarColumnDesc<Float>("PARANGLE"));
[1047]239  td.addColumn(ScalarColumnDesc<Float>("OPACITY"));
[105]240
[805]241  td.addColumn(ScalarColumnDesc<uInt>("TCAL_ID"));
[972]242  ScalarColumnDesc<Int> fitColumn("FIT_ID");
[973]243  fitColumn.setDefault(Int(-1));
[972]244  td.addColumn(fitColumn);
[805]245
246  td.addColumn(ScalarColumnDesc<uInt>("FOCUS_ID"));
247  td.addColumn(ScalarColumnDesc<uInt>("WEATHER_ID"));
248
[999]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
[805]255  td.rwKeywordSet().define("OBSMODE", String(""));
256
[418]257  // Now create Table SetUp from the description.
[859]258  SetupNewTable aNewTab(generateName(), td, Table::Scratch);
[852]259  table_ = Table(aNewTab, type_, 0);
[805]260  originalTable_ = table_;
261}
[418]262
[455]263
[805]264void Scantable::attach()
[455]265{
[805]266  timeCol_.attach(table_, "TIME");
267  srcnCol_.attach(table_, "SRCNAME");
[1068]268  srctCol_.attach(table_, "SRCTYPE");
[805]269  specCol_.attach(table_, "SPECTRA");
270  flagsCol_.attach(table_, "FLAGTRA");
[865]271  tsysCol_.attach(table_, "TSYS");
[805]272  cycleCol_.attach(table_,"CYCLENO");
273  scanCol_.attach(table_, "SCANNO");
274  beamCol_.attach(table_, "BEAMNO");
[847]275  ifCol_.attach(table_, "IFNO");
276  polCol_.attach(table_, "POLNO");
[805]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");
[455]284
[805]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");
[455]290}
291
[901]292void Scantable::setHeader(const STHeader& sdh)
[206]293{
[18]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);
[206]308  table_.rwKeywordSet().define("FluxUnit", sdh.fluxunit);
309  table_.rwKeywordSet().define("Epoch", sdh.epoch);
[905]310  table_.rwKeywordSet().define("POLTYPE", sdh.poltype);
[50]311}
[21]312
[901]313STHeader Scantable::getHeader() const
[206]314{
[901]315  STHeader sdh;
[21]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);
[206]330  table_.keywordSet().get("FluxUnit", sdh.fluxunit);
331  table_.keywordSet().get("Epoch", sdh.epoch);
[905]332  table_.keywordSet().get("POLTYPE", sdh.poltype);
[21]333  return sdh;
[18]334}
[805]335
[1360]336void Scantable::setSourceType( int stype )
[1068]337{
338  if ( stype < 0 || stype > 1 )
339    throw(AipsError("Illegal sourcetype."));
340  TableVector<Int> tabvec(table_, "SRCTYPE");
341  tabvec = Int(stype);
342}
343
[845]344bool Scantable::conformant( const Scantable& other )
345{
346  return this->getHeader().conformant(other.getHeader());
347}
348
349
[50]350
[805]351std::string Scantable::formatSec(Double x) const
[206]352{
[105]353  Double xcop = x;
354  MVTime mvt(xcop/24./3600.);  // make days
[365]355
[105]356  if (x < 59.95)
[281]357    return  String("      ") + mvt.string(MVTime::TIME_CLEAN_NO_HM, 7)+"s";
[745]358  else if (x < 3599.95)
[281]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);
[745]365  }
[105]366};
367
[805]368std::string Scantable::formatDirection(const MDirection& md) const
[281]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);
[987]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  }
[281]380  MVAngle mvLat(t[1]);
381  String sLat = mvLat.string(MVAngle::ANGLE+MVAngle::DIG2,prec);
[380]382  return sLon + String(" ") + sLat;
[281]383}
384
385
[805]386std::string Scantable::getFluxUnit() const
[206]387{
[847]388  return table_.keywordSet().asString("FluxUnit");
[206]389}
390
[805]391void Scantable::setFluxUnit(const std::string& unit)
[218]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
[805]402void Scantable::setInstrument(const std::string& name)
[236]403{
[805]404  bool throwIt = true;
[996]405  // create an Instrument to see if this is valid
406  STAttr::convertInstrument(name, throwIt);
[236]407  String nameU(name);
408  nameU.upcase();
409  table_.rwKeywordSet().define(String("AntennaName"), nameU);
410}
411
[1189]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
[805]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}
[281]428
[805]429void Scantable::makePersistent(const std::string& filename)
430{
431  String inname(filename);
432  Path path(inname);
[1111]433  /// @todo reindex SCANNO, recompute nbeam, nif, npol
[805]434  inname = path.expandedName();
435  table_.deepCopy(inname, Table::New);
436}
437
[837]438int Scantable::nbeam( int scanno ) const
[805]439{
440  if ( scanno < 0 ) {
441    Int n;
442    table_.keywordSet().get("nBeam",n);
443    return int(n);
[105]444  } else {
[805]445    // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
[888]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");
[805]453    return int(v.nelements());
[105]454  }
[805]455  return 0;
456}
[455]457
[837]458int Scantable::nif( int scanno ) const
[805]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
[888]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");
[805]474    return int(v.nelements());
[2]475  }
[805]476  return 0;
477}
[321]478
[837]479int Scantable::npol( int scanno ) const
[805]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
[888]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");
[805]495    return int(v.nelements());
[321]496  }
[805]497  return 0;
[2]498}
[805]499
[845]500int Scantable::ncycle( int scanno ) const
[206]501{
[805]502  if ( scanno < 0 ) {
[837]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;
[902]510      ++it;
[837]511    }
512    return n;
[805]513  } else {
[888]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());
[805]522  }
523  return 0;
[18]524}
[455]525
526
[845]527int Scantable::nrow( int scanno ) const
[805]528{
[845]529  return int(table_.nrow());
530}
531
532int Scantable::nchan( int ifno ) const
533{
534  if ( ifno < 0 ) {
[805]535    Int n;
536    table_.keywordSet().get("nChan",n);
537    return int(n);
538  } else {
[1603]539    // take the first SCANNO,POLNO,BEAMNO,CYCLENO as nbeam shouldn't
540    // vary with these
[888]541    Table t = table_(table_.col("IFNO") == ifno);
542    if ( t.nrow() == 0 ) return 0;
543    ROArrayColumn<Float> v(t, "SPECTRA");
[923]544    return v.shape(0)(0);
[805]545  }
546  return 0;
[18]547}
[455]548
[1111]549int Scantable::nscan() const {
550  Vector<uInt> scannos(scanCol_.getColumn());
[1148]551  uInt nout = genSort( scannos, Sort::Ascending,
[1111]552                       Sort::QuickSort|Sort::NoDuplicates );
553  return int(nout);
554}
555
[923]556int Scantable::getChannels(int whichrow) const
557{
558  return specCol_.shape(whichrow)(0);
559}
[847]560
561int Scantable::getBeam(int whichrow) const
562{
563  return beamCol_(whichrow);
564}
565
[1111]566std::vector<uint> Scantable::getNumbers(ScalarColumn<uInt>& col)
567{
568  Vector<uInt> nos(col.getColumn());
[1148]569  uInt n = genSort( nos, Sort::Ascending, Sort::QuickSort|Sort::NoDuplicates );
570  nos.resize(n, True);
[1111]571  std::vector<uint> stlout;
572  nos.tovector(stlout);
573  return stlout;
574}
575
[847]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
[805]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}
[488]597
[805]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;
[996]605  for (Int i=0; i<nrow(); ++i) {
[805]606    MEpoch me = timeCol(i);
[987]607    MDirection md = getDirection(i);
[805]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();
[923]615    azCol_.put(i,Float(azel[0]));
616    elCol_.put(i,Float(azel[1]));
[805]617    oss << "azel: " << azel[0]/C::pi*180.0 << " "
618        << azel[1]/C::pi*180.0 << " (deg)" << endl;
[16]619  }
[805]620  pushLog(String(oss));
621}
[89]622
[1400]623void Scantable::flag(const std::vector<bool>& msk, bool unflag)
[865]624{
[1333]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) )
[1000]633    throw(AipsError("Trying to flag whole scantable."));
634  if ( msk.size() == 0 ) {
635    uChar userflag = 1 << 7;
[1400]636    if ( unflag ) {
637      userflag = 0 << 7;
638    }
[1000]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;
[1400]658    if ( unflag ) {
659      userflag = 0 << 7;
660    }
[1000]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  }
[865]669}
670
[805]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}
[89]682
[896]683std::vector<float> Scantable::getSpectrum( int whichrow,
[902]684                                           const std::string& poltype ) const
[805]685{
[905]686  String ptype = poltype;
687  if (poltype == "" ) ptype = getPolType();
[902]688  if ( whichrow  < 0 || whichrow >= nrow() )
689    throw(AipsError("Illegal row number."));
[896]690  std::vector<float> out;
[805]691  Vector<Float> arr;
[896]692  uInt requestedpol = polCol_(whichrow);
693  String basetype = getPolType();
[905]694  if ( ptype == basetype ) {
[896]695    specCol_.get(whichrow, arr);
696  } else {
[1334]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);
[896]708  }
[902]709  if ( arr.nelements() == 0 )
710    pushLog("Not enough polarisations present to do the conversion.");
[805]711  arr.tovector(out);
712  return out;
[89]713}
[212]714
[1360]715void Scantable::setSpectrum( const std::vector<float>& spec,
[884]716                                   int whichrow )
717{
718  Vector<Float> spectrum(spec);
719  Vector<Float> arr;
720  specCol_.get(whichrow, arr);
721  if ( spectrum.nelements() != arr.nelements() )
[896]722    throw AipsError("The spectrum has incorrect number of channels.");
[884]723  specCol_.put(whichrow, spectrum);
724}
725
726
[805]727String Scantable::generateName()
[745]728{
[805]729  return (File::newUniqueName("./","temp")).baseName();
[212]730}
731
[805]732const casa::Table& Scantable::table( ) const
[212]733{
[805]734  return table_;
[212]735}
736
[805]737casa::Table& Scantable::table( )
[386]738{
[805]739  return table_;
[386]740}
741
[896]742std::string Scantable::getPolType() const
743{
744  return table_.keywordSet().asString("POLTYPE");
745}
746
[805]747void Scantable::unsetSelection()
[380]748{
[805]749  table_ = originalTable_;
[847]750  attach();
[805]751  selector_.reset();
[380]752}
[386]753
[805]754void Scantable::setSelection( const STSelector& selection )
[430]755{
[805]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;
[847]761  attach();
[805]762  selector_ = selection;
[430]763}
764
[837]765std::string Scantable::summary( bool verbose )
[447]766{
[805]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
[896]776      << setw(15) << "Polarisations:" << setw(4) << npol()
777      << "(" << getPolType() << ")" << endl
[805]778      << setw(15) << "Channels:"  << setw(4) << nchan() << endl;
779  oss << endl;
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;
[1446]792  //Vector<Double> vec(moleculeTable_.getRestFrequencies());
793  int nid = moleculeTable_.nrow();
794  Bool firstline = True;
[805]795  oss << setw(15) << "Rest Freqs:";
[1446]796  for (int i=0; i<nid; i++) {
797      Table t = table_(table_.col("MOLECULE_ID") == i);
798      if (t.nrow() >  0) {
799          Vector<Double> vec(moleculeTable_.getRestFrequency(i));
800          if (vec.nelements() > 0) {
801               if (firstline) {
802                   oss << setprecision(10) << vec << " [Hz]" << endl;
803                   firstline=False;
804               }
805               else{
806                   oss << setw(15)<<" " << setprecision(10) << vec << " [Hz]" << endl;
807               }
808          } else {
809              oss << "none" << endl;
810          }
811      }
[805]812  }
[941]813
814  oss << setw(15) << "Abcissa:" << getAbcissaLabel(0) << endl;
[805]815  oss << selector_.print() << endl;
816  oss << endl;
817  // main table
818  String dirtype = "Position ("
[987]819                  + getDirectionRefString()
[805]820                  + ")";
[941]821  oss << setw(5) << "Scan" << setw(15) << "Source"
822      << setw(10) << "Time" << setw(18) << "Integration" << endl;
823  oss << setw(5) << "" << setw(5) << "Beam" << setw(3) << "" << dirtype << endl;
824  oss << setw(10) << "" << setw(3) << "IF" << setw(6) << ""
[805]825      << setw(8) << "Frame" << setw(16)
826      << "RefVal" << setw(10) << "RefPix" << setw(12) << "Increment" <<endl;
827  oss << asap::SEPERATOR << endl;
828  TableIterator iter(table_, "SCANNO");
829  while (!iter.pastEnd()) {
830    Table subt = iter.table();
831    ROTableRow row(subt);
832    MEpoch::ROScalarColumn timeCol(subt,"TIME");
833    const TableRecord& rec = row.get(0);
834    oss << setw(4) << std::right << rec.asuInt("SCANNO")
835        << std::left << setw(1) << ""
836        << setw(15) << rec.asString("SRCNAME")
837        << setw(10) << formatTime(timeCol(0), false);
838    // count the cycles in the scan
839    TableIterator cyciter(subt, "CYCLENO");
840    int nint = 0;
841    while (!cyciter.pastEnd()) {
842      ++nint;
843      ++cyciter;
844    }
845    oss << setw(3) << std::right << nint  << setw(3) << " x " << std::left
846        << setw(6) <<  formatSec(rec.asFloat("INTERVAL")) << endl;
[447]847
[805]848    TableIterator biter(subt, "BEAMNO");
849    while (!biter.pastEnd()) {
850      Table bsubt = biter.table();
851      ROTableRow brow(bsubt);
852      const TableRecord& brec = brow.get(0);
[1000]853      uInt row0 = bsubt.rowNumbers(table_)[0];
[941]854      oss << setw(5) << "" <<  setw(4) << std::right << brec.asuInt("BEAMNO")<< std::left;
[987]855      oss  << setw(4) << ""  << formatDirection(getDirection(row0)) << endl;
[805]856      TableIterator iiter(bsubt, "IFNO");
857      while (!iiter.pastEnd()) {
858        Table isubt = iiter.table();
859        ROTableRow irow(isubt);
860        const TableRecord& irec = irow.get(0);
[941]861        oss << setw(10) << "";
862        oss << setw(3) << std::right << irec.asuInt("IFNO") << std::left
[1451]863            << setw(2) << "" << frequencies().print(irec.asuInt("FREQ_ID"))
864            << endl;
[447]865
[805]866        ++iiter;
867      }
868      ++biter;
869    }
870    ++iter;
[447]871  }
[805]872  /// @todo implement verbose mode
873  return String(oss);
[447]874}
875
[805]876std::string Scantable::getTime(int whichrow, bool showdate) const
[777]877{
[805]878  MEpoch::ROScalarColumn timeCol(table_, "TIME");
879  MEpoch me;
880  if (whichrow > -1) {
881    me = timeCol(uInt(whichrow));
882  } else {
883    Double tm;
884    table_.keywordSet().get("UTC",tm);
885    me = MEpoch(MVEpoch(tm));
[777]886  }
[805]887  return formatTime(me, showdate);
[777]888}
[805]889
[1603]890MEpoch Scantable::getEpoch(int whichrow) const
891{
892  if (whichrow > -1) {
893    return timeCol_(uInt(whichrow));
894  } else {
895    Double tm;
896    table_.keywordSet().get("UTC",tm);
897    return MEpoch(MVEpoch(tm)); 
898  }
899}
900
[1068]901std::string Scantable::getDirectionString(int whichrow) const
902{
903  return formatDirection(getDirection(uInt(whichrow)));
904}
905
[1360]906std::vector< double > Scantable::getAbcissa( int whichrow ) const
[865]907{
[1603]908  if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal row number"));
[865]909  std::vector<double> stlout;
910  int nchan = specCol_(whichrow).nelements();
911  String us = freqTable_.getUnitString();
912  if ( us == "" || us == "pixel" || us == "channel" ) {
913    for (int i=0; i<nchan; ++i) {
914      stlout.push_back(double(i));
915    }
916    return stlout;
917  }
918
919  const MPosition& mp = getAntennaPosition();
[987]920  const MDirection& md = getDirection(whichrow);
[865]921  const MEpoch& me = timeCol_(whichrow);
[1446]922  //Double rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
923  Vector<Double> rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
[865]924  SpectralCoordinate spc =
925    freqTable_.getSpectralCoordinate(md, mp, me, rf, mfreqidCol_(whichrow));
926  Vector<Double> pixel(nchan);
927  Vector<Double> world;
928  indgen(pixel);
929  if ( Unit(us) == Unit("Hz") ) {
930    for ( int i=0; i < nchan; ++i) {
931      Double world;
932      spc.toWorld(world, pixel[i]);
933      stlout.push_back(double(world));
934    }
935  } else if ( Unit(us) == Unit("km/s") ) {
936    Vector<Double> world;
937    spc.pixelToVelocity(world, pixel);
938    world.tovector(stlout);
939  }
940  return stlout;
941}
[1360]942void Scantable::setDirectionRefString( const std::string & refstr )
[987]943{
944  MDirection::Types mdt;
945  if (refstr != "" && !MDirection::getType(mdt, refstr)) {
946    throw(AipsError("Illegal Direction frame."));
947  }
948  if ( refstr == "" ) {
949    String defaultstr = MDirection::showType(dirCol_.getMeasRef().getType());
950    table_.rwKeywordSet().define("DIRECTIONREF", defaultstr);
951  } else {
952    table_.rwKeywordSet().define("DIRECTIONREF", String(refstr));
953  }
954}
[865]955
[1360]956std::string Scantable::getDirectionRefString( ) const
[987]957{
958  return table_.keywordSet().asString("DIRECTIONREF");
959}
960
961MDirection Scantable::getDirection(int whichrow ) const
962{
963  String usertype = table_.keywordSet().asString("DIRECTIONREF");
964  String type = MDirection::showType(dirCol_.getMeasRef().getType());
965  if ( usertype != type ) {
966    MDirection::Types mdt;
967    if (!MDirection::getType(mdt, usertype)) {
968      throw(AipsError("Illegal Direction frame."));
969    }
970    return dirCol_.convert(uInt(whichrow), mdt);
971  } else {
972    return dirCol_(uInt(whichrow));
973  }
974}
975
[847]976std::string Scantable::getAbcissaLabel( int whichrow ) const
977{
[996]978  if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal ro number"));
[847]979  const MPosition& mp = getAntennaPosition();
[987]980  const MDirection& md = getDirection(whichrow);
[847]981  const MEpoch& me = timeCol_(whichrow);
[1446]982  //const Double& rf = mmolidCol_(whichrow);
983  const Vector<Double> rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
[847]984  SpectralCoordinate spc =
985    freqTable_.getSpectralCoordinate(md, mp, me, rf, mfreqidCol_(whichrow));
986
987  String s = "Channel";
988  Unit u = Unit(freqTable_.getUnitString());
989  if (u == Unit("km/s")) {
[1170]990    s = CoordinateUtil::axisLabel(spc, 0, True,True,  True);
[847]991  } else if (u == Unit("Hz")) {
992    Vector<String> wau(1);wau = u.getName();
993    spc.setWorldAxisUnits(wau);
[1170]994    s = CoordinateUtil::axisLabel(spc, 0, True, True, False);
[847]995  }
996  return s;
997
998}
999
[1446]1000/**
1001void asap::Scantable::setRestFrequencies( double rf, const std::string& name,
[1170]1002                                          const std::string& unit )
[1446]1003**/
1004void Scantable::setRestFrequencies( vector<double> rf, const vector<std::string>& name,
1005                                          const std::string& unit )
1006
[847]1007{
[923]1008  ///@todo lookup in line table to fill in name and formattedname
[847]1009  Unit u(unit);
[1446]1010  //Quantum<Double> urf(rf, u);
1011  Quantum<Vector<Double> >urf(rf, u);
1012  Vector<String> formattedname(0);
1013  //cerr<<"Scantable::setRestFrequnecies="<<urf<<endl;
1014 
1015  //uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), name, "");
1016  uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), mathutil::toVectorString(name), formattedname);
[847]1017  TableVector<uInt> tabvec(table_, "MOLECULE_ID");
1018  tabvec = id;
1019}
1020
[1446]1021/**
1022void asap::Scantable::setRestFrequencies( const std::string& name )
[847]1023{
1024  throw(AipsError("setRestFrequencies( const std::string& name ) NYI"));
1025  ///@todo implement
1026}
[1446]1027**/
1028void Scantable::setRestFrequencies( const vector<std::string>& name )
1029{
1030  throw(AipsError("setRestFrequencies( const vector<std::string>& name ) NYI"));
1031  ///@todo implement
1032}
[847]1033
[1360]1034std::vector< unsigned int > Scantable::rownumbers( ) const
[852]1035{
1036  std::vector<unsigned int> stlout;
1037  Vector<uInt> vec = table_.rowNumbers();
1038  vec.tovector(stlout);
1039  return stlout;
1040}
1041
[865]1042
[1360]1043Matrix<Float> Scantable::getPolMatrix( uInt whichrow ) const
[896]1044{
1045  ROTableRow row(table_);
1046  const TableRecord& rec = row.get(whichrow);
1047  Table t =
1048    originalTable_( originalTable_.col("SCANNO") == Int(rec.asuInt("SCANNO"))
1049                    && originalTable_.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
1050                    && originalTable_.col("IFNO") == Int(rec.asuInt("IFNO"))
1051                    && originalTable_.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
1052  ROArrayColumn<Float> speccol(t, "SPECTRA");
1053  return speccol.getColumn();
1054}
[865]1055
[1360]1056std::vector< std::string > Scantable::columnNames( ) const
[902]1057{
1058  Vector<String> vec = table_.tableDesc().columnNames();
1059  return mathutil::tovectorstring(vec);
1060}
[896]1061
[1360]1062MEpoch::Types Scantable::getTimeReference( ) const
[915]1063{
1064  return MEpoch::castType(timeCol_.getMeasRef().getType());
[972]1065}
[915]1066
[1360]1067void Scantable::addFit( const STFitEntry& fit, int row )
[972]1068{
1069  cout << mfitidCol_(uInt(row)) << endl;
1070  uInt id = fitTable_.addEntry(fit, mfitidCol_(uInt(row)));
1071  mfitidCol_.put(uInt(row), id);
1072}
[915]1073
[1360]1074void Scantable::shift(int npix)
1075{
1076  Vector<uInt> fids(mfreqidCol_.getColumn());
1077  genSort( fids, Sort::Ascending,
1078           Sort::QuickSort|Sort::NoDuplicates );
1079  for (uInt i=0; i<fids.nelements(); ++i) {
1080    frequencies().shiftRefPix(npix, i);
1081  }
1082}
[987]1083
[1387]1084std::string asap::Scantable::getAntennaName() const
1085{
1086  String out;
1087  table_.keywordSet().get("AntennaName", out);
1088  return out;
[987]1089}
[1387]1090
1091int asap::Scantable::checkScanInfo(const std::vector<int>& scanlist) const
1092{
1093  String tbpath;
1094  int ret = 0;
1095  if ( table_.keywordSet().isDefined("GBT_GO") ) {
1096    table_.keywordSet().get("GBT_GO", tbpath);
1097    Table t(tbpath,Table::Old);
1098    // check each scan if other scan of the pair exist
1099    int nscan = scanlist.size();
1100    for (int i = 0; i < nscan; i++) {
1101      Table subt = t( t.col("SCAN") == scanlist[i]+1 );
1102      if (subt.nrow()==0) {
1103        cerr <<"Scan "<<scanlist[i]<<" cannot be found in the scantable."<<endl;
1104        ret = 1;
1105        break;
1106      }
1107      ROTableRow row(subt);
1108      const TableRecord& rec = row.get(0);
1109      int scan1seqn = rec.asuInt("PROCSEQN");
1110      int laston1 = rec.asuInt("LASTON");
1111      if ( rec.asuInt("PROCSIZE")==2 ) {
1112        if ( i < nscan-1 ) {
1113          Table subt2 = t( t.col("SCAN") == scanlist[i+1]+1 );
1114          if ( subt2.nrow() == 0) {
1115            cerr<<"Scan "<<scanlist[i+1]<<" cannot be found in the scantable."<<endl;
1116            ret = 1;
1117            break;
1118          }
1119          ROTableRow row2(subt2);
1120          const TableRecord& rec2 = row2.get(0);
1121          int scan2seqn = rec2.asuInt("PROCSEQN");
1122          int laston2 = rec2.asuInt("LASTON");
1123          if (scan1seqn == 1 && scan2seqn == 2) {
1124            if (laston1 == laston2) {
1125              cerr<<"A valid scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl;
1126              i +=1;
1127            }
1128            else {
1129              cerr<<"Incorrect scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl;
1130            }
1131          }
1132          else if (scan1seqn==2 && scan2seqn == 1) {
1133            if (laston1 == laston2) {
1134              cerr<<"["<<scanlist[i]<<","<<scanlist[i+1]<<"] is a valid scan pair but in incorrect order."<<endl;
1135              ret = 1;
1136              break;
1137            }
1138          }
1139          else {
1140            cerr<<"The other scan for  "<<scanlist[i]<<" appears to be missing. Check the input scan numbers."<<endl;
1141            ret = 1;
1142            break;
1143          }
1144        }
1145      }
1146      else {
1147        cerr<<"The scan does not appear to be standard obsevation."<<endl;
1148      }
1149    //if ( i >= nscan ) break;
1150    }
1151  }
1152  else {
1153    cerr<<"No reference to GBT_GO table."<<endl;
1154    ret = 1;
1155  }
1156  return ret;
1157}
1158
1159std::vector<double>  asap::Scantable::getDirectionVector(int whichrow) const
1160{
1161  Vector<Double> Dir = dirCol_(whichrow).getAngle("rad").getValue();
1162  std::vector<double> dir;
1163  Dir.tovector(dir);
1164  return dir;
1165}
1166
[1446]1167void asap::Scantable::reshapeSpectrum( int nmin, int nmax )
1168  throw( casa::AipsError )
1169{
1170  // assumed that all rows have same nChan
1171  Vector<Float> arr = specCol_( 0 ) ;
1172  int nChan = arr.nelements() ;
1173 
1174  // if nmin < 0 or nmax < 0, nothing to do
1175  if (  nmin < 0 ) {
1176    throw( casa::indexError<int>( nmin, "asap::Scantable::reshapeSpectrum: Invalid range. Negative index is specified." ) ) ;
1177    }
1178  if (  nmax < 0  ) {
1179    throw( casa::indexError<int>( nmax, "asap::Scantable::reshapeSpectrum: Invalid range. Negative index is specified." ) ) ;
1180  }
1181 
1182  // if nmin > nmax, exchange values
1183  if ( nmin > nmax ) {
1184    int tmp = nmax ;
1185    nmax = nmin ;
1186    nmin = tmp ;
1187    cout << "Swap values. Applied range is ["
1188         << nmin << ", " << nmax << "]" << endl ;
1189  }
1190 
1191  // if nmin exceeds nChan, nothing to do
1192  if ( nmin >= nChan ) {
1193    throw( casa::indexError<int>( nmin, "asap::Scantable::reshapeSpectrum: Invalid range. Specified minimum exceeds nChan." ) ) ;
1194  }
1195 
1196  // if nmax exceeds nChan, reset nmax to nChan
1197  if ( nmax >= nChan ) {
1198    if ( nmin == 0 ) {
1199      // nothing to do
1200      cout << "Whole range is selected. Nothing to do." << endl ;
1201      return ;
1202    }
1203    else {
1204      cout << "Specified maximum exceeds nChan. Applied range is ["
1205           << nmin << ", " << nChan-1 << "]." << endl ;
1206      nmax = nChan - 1 ;
1207    }
1208  }
1209 
1210  // reshape specCol_ and flagCol_
1211  for ( int irow = 0 ; irow < nrow() ; irow++ ) {
1212    reshapeSpectrum( nmin, nmax, irow ) ;
1213  }
1214
1215  // update FREQUENCIES subtable
1216  Double refpix ;
1217  Double refval ;
1218  Double increment ;
1219  int freqnrow = freqTable_.table().nrow() ;
1220  Vector<uInt> oldId( freqnrow ) ;
1221  Vector<uInt> newId( freqnrow ) ;
1222  for ( int irow = 0 ; irow < freqnrow ; irow++ ) {
1223    freqTable_.getEntry( refpix, refval, increment, irow ) ;
1224    /***
1225     * need to shift refpix to nmin
1226     * note that channel nmin in old index will be channel 0 in new one
1227     ***/
1228    refval = refval - ( refpix - nmin ) * increment ;
1229    refpix = 0 ; 
1230    freqTable_.setEntry( refpix, refval, increment, irow ) ;
1231  }
1232 
1233  // update nchan
1234  int newsize = nmax - nmin + 1 ;
1235  table_.rwKeywordSet().define( "nChan", newsize ) ;
1236 
1237  // update bandwidth
1238  // assumed all spectra in the scantable have same bandwidth
1239  table_.rwKeywordSet().define( "Bandwidth", increment * newsize ) ;
1240 
1241  return ;
[1387]1242}
[1446]1243
1244void asap::Scantable::reshapeSpectrum( int nmin, int nmax, int irow )
1245{
1246  // reshape specCol_ and flagCol_
1247  Vector<Float> oldspec = specCol_( irow ) ;
1248  Vector<uChar> oldflag = flagsCol_( irow ) ;
1249  uInt newsize = nmax - nmin + 1 ;
1250  specCol_.put( irow, oldspec( Slice( nmin, newsize, 1 ) ) ) ;
1251  flagsCol_.put( irow, oldflag( Slice( nmin, newsize, 1 ) ) ) ;
1252
1253  return ;
1254}
1255
1256void asap::Scantable::regridChannel( int nChan, double dnu )
1257{
1258  cout << "Regrid abcissa with channel number " << nChan << " and spectral resoultion " << dnu << "Hz." << endl ;
1259  // assumed that all rows have same nChan
1260  Vector<Float> arr = specCol_( 0 ) ;
1261  int oldsize = arr.nelements() ;
1262
1263  // if oldsize == nChan, nothing to do
1264  if ( oldsize == nChan ) {
1265    cout << "Specified channel number is same as current one. Nothing to do." << endl ;
1266    return ;
1267  }
1268
1269  // if oldChan < nChan, unphysical operation
1270  if ( oldsize < nChan ) {
1271    cout << "Unphysical operation. Nothing to do." << endl ;
1272    return ;
1273  }
1274
1275  // change channel number for specCol_ and flagCol_
1276  Vector<Float> newspec( nChan, 0 ) ;
1277  Vector<uChar> newflag( nChan, false ) ;
1278  vector<string> coordinfo = getCoordInfo() ;
1279  string oldinfo = coordinfo[0] ;
1280  coordinfo[0] = "Hz" ;
1281  setCoordInfo( coordinfo ) ;
1282  for ( int irow = 0 ; irow < nrow() ; irow++ ) {
1283    regridChannel( nChan, dnu, irow ) ;
1284  }
1285  coordinfo[0] = oldinfo ;
1286  setCoordInfo( coordinfo ) ;
1287
1288
1289  // NOTE: this method does not update metadata such as
1290  //       FREQUENCIES subtable, nChan, Bandwidth, etc.
1291
1292  return ;
1293}
1294
1295void asap::Scantable::regridChannel( int nChan, double dnu, int irow )
1296{
1297  // logging
1298  //ofstream ofs( "average.log", std::ios::out | std::ios::app ) ;
1299  //ofs << "IFNO = " << getIF( irow ) << " irow = " << irow << endl ;
1300
1301  Vector<Float> oldspec = specCol_( irow ) ;
1302  Vector<uChar> oldflag = flagsCol_( irow ) ;
1303  Vector<Float> newspec( nChan, 0 ) ;
1304  Vector<uChar> newflag( nChan, false ) ;
1305 
1306  // regrid
1307  vector<double> abcissa = getAbcissa( irow ) ;
1308  int oldsize = abcissa.size() ;
1309  double olddnu = abcissa[1] - abcissa[0] ;
1310  int refChan = 0 ;
1311  double frac = 0.0 ;
1312  double wedge = 0.0 ;
1313  double pile = 0.0 ;
1314  double wsum = 0.0 ;
1315  /***
1316   * ichan = 0
1317   ***/
1318  //ofs << "olddnu = " << olddnu << ", dnu = " << dnu << endl ;
1319  pile += dnu ;
1320  wedge = olddnu * ( refChan + 1 ) ;
1321  while ( wedge < pile ) {
1322    newspec[0] += olddnu * oldspec[refChan] ;
1323    newflag[0] = newflag[0] || oldflag[refChan] ;
1324    //ofs << "channel " << refChan << " is included in new channel 0" << endl ;
1325    refChan++ ;
1326    wedge += olddnu ;
1327    wsum += olddnu ;
1328    //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
1329  }
1330  frac = ( wedge - pile ) / olddnu ;
1331  wsum += ( 1.0 - frac ) * olddnu ;
1332  newspec[0] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
1333  newflag[0] = newflag[0] || oldflag[refChan] ;
1334  //ofs << "channel " << refChan << " is partly included in new channel 0" << " with fraction of " << ( 1.0 - frac ) << endl ;
1335  //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
1336  newspec[0] /= wsum ;
1337  //ofs << "newspec[0] = " << newspec[0] << endl ;
1338  //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
1339
1340  /***
1341   * ichan = 1 - nChan-2
1342   ***/
1343  for ( int ichan = 1 ; ichan < nChan - 1 ; ichan++ ) {
1344    pile += dnu ;
1345    newspec[ichan] += frac * olddnu * oldspec[refChan] ;
1346    newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
1347    //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << frac << endl ;
1348    refChan++ ;
1349    wedge += olddnu ;
1350    wsum = frac * olddnu ;
1351    //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
1352    while ( wedge < pile ) {
1353      newspec[ichan] += olddnu * oldspec[refChan] ;
1354      newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
1355      //ofs << "channel " << refChan << " is included in new channel " << ichan << endl ;
1356      refChan++ ;
1357      wedge += olddnu ;
1358      wsum += olddnu ;
1359      //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
1360    }
1361    frac = ( wedge - pile ) / olddnu ;
1362    wsum += ( 1.0 - frac ) * olddnu ;
1363    newspec[ichan] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
1364    newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
1365    //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << ( 1.0 - frac ) << endl ;
1366    //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
1367    //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
1368    newspec[ichan] /= wsum ;
1369    //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << endl ;
1370  }
1371
1372  /***
1373   * ichan = nChan-1
1374   ***/
1375  // NOTE: Assumed that all spectra have the same bandwidth
1376  pile += dnu ;
1377  newspec[nChan-1] += frac * olddnu * oldspec[refChan] ;
1378  newflag[nChan-1] = newflag[nChan-1] || oldflag[refChan] ;
1379  //ofs << "channel " << refChan << " is partly included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
1380  refChan++ ;
1381  wedge += olddnu ;
1382  wsum = frac * olddnu ;
1383  //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
1384  for ( int jchan = refChan ; jchan < oldsize ; jchan++ ) {
1385    newspec[nChan-1] += olddnu * oldspec[jchan] ;
1386    newflag[nChan-1] = newflag[nChan-1] || oldflag[jchan] ;
1387    wsum += olddnu ;
1388    //ofs << "channel " << jchan << " is included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
1389    //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
1390  }
1391  //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
1392  //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
1393  newspec[nChan-1] /= wsum ;
1394  //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << endl ;
1395 
1396  specCol_.put( irow, newspec ) ;
1397  flagsCol_.put( irow, newflag ) ;
1398
1399  // ofs.close() ;
1400
1401  return ;
1402}
1403
1404}
1405//namespace asap
Note: See TracBrowser for help on using the repository browser.