source: trunk/src/Scantable.cpp @ 1994

Last change on this file since 1994 was 1994, checked in by Kana Sugimoto, 13 years ago

New Development: Yes

JIRA Issue: Yes (CAS-1306)

Ready for Test: Yes

Interface Changes: Yes

What Interface Changed: added row selection parameters to scantable.flag,

ScantableWrapper::flag and Scantable::flag.

Test Programs:

Put in Release Notes: No

Module(s): scantable class

Description:

Enabled a row selection in scantable.flag.

  • A parameter 'row' is added to scantable.flag. The default value -1 applies

specified channel flags to the all rows in the scantable (same as previous code).

  • A parameter 'whichrow' is also added to ScantableWrapper::flag and

Scantable::flag accordingly.

  • The actual flagg application part in the code Scantable::flag is moved to a new

private function Scantable::applyChanFlag(uInt whichrow, vector<bool> msk, uChar flagval).
The function applies flag with a value, 'flagval', to masked channels, 'msk',
in a selected row, 'whichrow'.


  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 55.7 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#include <fstream>
14
15#include <casa/aips.h>
16#include <casa/iostream.h>
17#include <casa/iomanip.h>
18#include <casa/OS/Path.h>
19#include <casa/OS/File.h>
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>
25#include <casa/Arrays/Vector.h>
26#include <casa/Arrays/VectorSTLIterator.h>
27#include <casa/Arrays/Slice.h>
28#include <casa/BasicMath/Math.h>
29#include <casa/BasicSL/Constants.h>
30#include <casa/Quanta/MVAngle.h>
31#include <casa/Containers/RecordField.h>
32#include <casa/Utilities/GenSort.h>
33#include <casa/Logging/LogIO.h>
34
35#include <tables/Tables/TableParse.h>
36#include <tables/Tables/TableDesc.h>
37#include <tables/Tables/TableCopy.h>
38#include <tables/Tables/SetupNewTab.h>
39#include <tables/Tables/ScaColDesc.h>
40#include <tables/Tables/ArrColDesc.h>
41#include <tables/Tables/TableRow.h>
42#include <tables/Tables/TableVector.h>
43#include <tables/Tables/TableIter.h>
44
45#include <tables/Tables/ExprNode.h>
46#include <tables/Tables/TableRecord.h>
47#include <casa/Quanta/MVTime.h>
48#include <casa/Quanta/MVAngle.h>
49#include <measures/Measures/MeasRef.h>
50#include <measures/Measures/MeasTable.h>
51// needed to avoid error in .tcc
52#include <measures/Measures/MCDirection.h>
53//
54#include <measures/Measures/MDirection.h>
55#include <measures/Measures/MFrequency.h>
56#include <measures/Measures/MEpoch.h>
57#include <measures/TableMeasures/TableMeasRefDesc.h>
58#include <measures/TableMeasures/TableMeasValueDesc.h>
59#include <measures/TableMeasures/TableMeasDesc.h>
60#include <measures/TableMeasures/ScalarMeasColumn.h>
61#include <coordinates/Coordinates/CoordinateUtil.h>
62
63#include "Scantable.h"
64#include "STPolLinear.h"
65#include "STPolCircular.h"
66#include "STPolStokes.h"
67#include "STAttr.h"
68#include "MathUtils.h"
69
70using namespace casa;
71
72namespace asap {
73
74std::map<std::string, STPol::STPolFactory *> Scantable::factories_;
75
76void Scantable::initFactories() {
77  if ( factories_.empty() ) {
78    Scantable::factories_["linear"] = &STPolLinear::myFactory;
79    Scantable::factories_["circular"] = &STPolCircular::myFactory;
80    Scantable::factories_["stokes"] = &STPolStokes::myFactory;
81  }
82}
83
84Scantable::Scantable(Table::TableType ttype) :
85  type_(ttype)
86{
87  initFactories();
88  setupMainTable();
89  freqTable_ = STFrequencies(*this);
90  table_.rwKeywordSet().defineTable("FREQUENCIES", freqTable_.table());
91  weatherTable_ = STWeather(*this);
92  table_.rwKeywordSet().defineTable("WEATHER", weatherTable_.table());
93  focusTable_ = STFocus(*this);
94  table_.rwKeywordSet().defineTable("FOCUS", focusTable_.table());
95  tcalTable_ = STTcal(*this);
96  table_.rwKeywordSet().defineTable("TCAL", tcalTable_.table());
97  moleculeTable_ = STMolecules(*this);
98  table_.rwKeywordSet().defineTable("MOLECULES", moleculeTable_.table());
99  historyTable_ = STHistory(*this);
100  table_.rwKeywordSet().defineTable("HISTORY", historyTable_.table());
101  fitTable_ = STFit(*this);
102  table_.rwKeywordSet().defineTable("FIT", fitTable_.table());
103  table_.tableInfo().setType( "Scantable" ) ;
104  originalTable_ = table_;
105  attach();
106}
107
108Scantable::Scantable(const std::string& name, Table::TableType ttype) :
109  type_(ttype)
110{
111  initFactories();
112
113  Table tab(name, Table::Update);
114  uInt version = tab.keywordSet().asuInt("VERSION");
115  if (version != version_) {
116    throw(AipsError("Unsupported version of ASAP file."));
117  }
118  if ( type_ == Table::Memory ) {
119    table_ = tab.copyToMemoryTable(generateName());
120  } else {
121    table_ = tab;
122  }
123  table_.tableInfo().setType( "Scantable" ) ;
124
125  attachSubtables();
126  originalTable_ = table_;
127  attach();
128}
129/*
130Scantable::Scantable(const std::string& name, Table::TableType ttype) :
131  type_(ttype)
132{
133  initFactories();
134  Table tab(name, Table::Update);
135  uInt version = tab.keywordSet().asuInt("VERSION");
136  if (version != version_) {
137    throw(AipsError("Unsupported version of ASAP file."));
138  }
139  if ( type_ == Table::Memory ) {
140    table_ = tab.copyToMemoryTable(generateName());
141  } else {
142    table_ = tab;
143  }
144
145  attachSubtables();
146  originalTable_ = table_;
147  attach();
148}
149*/
150
151Scantable::Scantable( const Scantable& other, bool clear )
152{
153  // with or without data
154  String newname = String(generateName());
155  type_ = other.table_.tableType();
156  if ( other.table_.tableType() == Table::Memory ) {
157      if ( clear ) {
158        table_ = TableCopy::makeEmptyMemoryTable(newname,
159                                                 other.table_, True);
160      } else
161        table_ = other.table_.copyToMemoryTable(newname);
162  } else {
163      other.table_.deepCopy(newname, Table::New, False,
164                            other.table_.endianFormat(),
165                            Bool(clear));
166      table_ = Table(newname, Table::Update);
167      table_.markForDelete();
168  }
169  table_.tableInfo().setType( "Scantable" ) ;
170  /// @todo reindex SCANNO, recompute nbeam, nif, npol
171  if ( clear ) copySubtables(other);
172  attachSubtables();
173  originalTable_ = table_;
174  attach();
175}
176
177void Scantable::copySubtables(const Scantable& other) {
178  Table t = table_.rwKeywordSet().asTable("FREQUENCIES");
179  TableCopy::copyRows(t, other.freqTable_.table());
180  t = table_.rwKeywordSet().asTable("FOCUS");
181  TableCopy::copyRows(t, other.focusTable_.table());
182  t = table_.rwKeywordSet().asTable("WEATHER");
183  TableCopy::copyRows(t, other.weatherTable_.table());
184  t = table_.rwKeywordSet().asTable("TCAL");
185  TableCopy::copyRows(t, other.tcalTable_.table());
186  t = table_.rwKeywordSet().asTable("MOLECULES");
187  TableCopy::copyRows(t, other.moleculeTable_.table());
188  t = table_.rwKeywordSet().asTable("HISTORY");
189  TableCopy::copyRows(t, other.historyTable_.table());
190  t = table_.rwKeywordSet().asTable("FIT");
191  TableCopy::copyRows(t, other.fitTable_.table());
192}
193
194void Scantable::attachSubtables()
195{
196  freqTable_ = STFrequencies(table_);
197  focusTable_ = STFocus(table_);
198  weatherTable_ = STWeather(table_);
199  tcalTable_ = STTcal(table_);
200  moleculeTable_ = STMolecules(table_);
201  historyTable_ = STHistory(table_);
202  fitTable_ = STFit(table_);
203}
204
205Scantable::~Scantable()
206{
207  //cout << "~Scantable() " << this << endl;
208}
209
210void Scantable::setupMainTable()
211{
212  TableDesc td("", "1", TableDesc::Scratch);
213  td.comment() = "An ASAP Scantable";
214  td.rwKeywordSet().define("VERSION", uInt(version_));
215
216  // n Cycles
217  td.addColumn(ScalarColumnDesc<uInt>("SCANNO"));
218  // new index every nBeam x nIF x nPol
219  td.addColumn(ScalarColumnDesc<uInt>("CYCLENO"));
220
221  td.addColumn(ScalarColumnDesc<uInt>("BEAMNO"));
222  td.addColumn(ScalarColumnDesc<uInt>("IFNO"));
223  // linear, circular, stokes
224  td.rwKeywordSet().define("POLTYPE", String("linear"));
225  td.addColumn(ScalarColumnDesc<uInt>("POLNO"));
226
227  td.addColumn(ScalarColumnDesc<uInt>("FREQ_ID"));
228  td.addColumn(ScalarColumnDesc<uInt>("MOLECULE_ID"));
229
230  ScalarColumnDesc<Int> refbeamnoColumn("REFBEAMNO");
231  refbeamnoColumn.setDefault(Int(-1));
232  td.addColumn(refbeamnoColumn);
233
234  ScalarColumnDesc<uInt> flagrowColumn("FLAGROW");
235  flagrowColumn.setDefault(uInt(0));
236  td.addColumn(flagrowColumn);
237
238  td.addColumn(ScalarColumnDesc<Double>("TIME"));
239  TableMeasRefDesc measRef(MEpoch::UTC); // UTC as default
240  TableMeasValueDesc measVal(td, "TIME");
241  TableMeasDesc<MEpoch> mepochCol(measVal, measRef);
242  mepochCol.write(td);
243
244  td.addColumn(ScalarColumnDesc<Double>("INTERVAL"));
245
246  td.addColumn(ScalarColumnDesc<String>("SRCNAME"));
247  // Type of source (on=0, off=1, other=-1)
248  ScalarColumnDesc<Int> stypeColumn("SRCTYPE");
249  stypeColumn.setDefault(Int(-1));
250  td.addColumn(stypeColumn);
251  td.addColumn(ScalarColumnDesc<String>("FIELDNAME"));
252
253  //The actual Data Vectors
254  td.addColumn(ArrayColumnDesc<Float>("SPECTRA"));
255  td.addColumn(ArrayColumnDesc<uChar>("FLAGTRA"));
256  td.addColumn(ArrayColumnDesc<Float>("TSYS"));
257
258  td.addColumn(ArrayColumnDesc<Double>("DIRECTION",
259                                       IPosition(1,2),
260                                       ColumnDesc::Direct));
261  TableMeasRefDesc mdirRef(MDirection::J2000); // default
262  TableMeasValueDesc tmvdMDir(td, "DIRECTION");
263  // the TableMeasDesc gives the column a type
264  TableMeasDesc<MDirection> mdirCol(tmvdMDir, mdirRef);
265  // a uder set table type e.g. GALCTIC, B1950 ...
266  td.rwKeywordSet().define("DIRECTIONREF", String("J2000"));
267  // writing create the measure column
268  mdirCol.write(td);
269  td.addColumn(ScalarColumnDesc<Float>("AZIMUTH"));
270  td.addColumn(ScalarColumnDesc<Float>("ELEVATION"));
271  td.addColumn(ScalarColumnDesc<Float>("OPACITY"));
272
273  td.addColumn(ScalarColumnDesc<uInt>("TCAL_ID"));
274  ScalarColumnDesc<Int> fitColumn("FIT_ID");
275  fitColumn.setDefault(Int(-1));
276  td.addColumn(fitColumn);
277
278  td.addColumn(ScalarColumnDesc<uInt>("FOCUS_ID"));
279  td.addColumn(ScalarColumnDesc<uInt>("WEATHER_ID"));
280
281  // columns which just get dragged along, as they aren't used in asap
282  td.addColumn(ScalarColumnDesc<Double>("SRCVELOCITY"));
283  td.addColumn(ArrayColumnDesc<Double>("SRCPROPERMOTION"));
284  td.addColumn(ArrayColumnDesc<Double>("SRCDIRECTION"));
285  td.addColumn(ArrayColumnDesc<Double>("SCANRATE"));
286
287  td.rwKeywordSet().define("OBSMODE", String(""));
288
289  // Now create Table SetUp from the description.
290  SetupNewTable aNewTab(generateName(), td, Table::Scratch);
291  table_ = Table(aNewTab, type_, 0);
292  originalTable_ = table_;
293}
294
295void Scantable::attach()
296{
297  timeCol_.attach(table_, "TIME");
298  srcnCol_.attach(table_, "SRCNAME");
299  srctCol_.attach(table_, "SRCTYPE");
300  specCol_.attach(table_, "SPECTRA");
301  flagsCol_.attach(table_, "FLAGTRA");
302  tsysCol_.attach(table_, "TSYS");
303  cycleCol_.attach(table_,"CYCLENO");
304  scanCol_.attach(table_, "SCANNO");
305  beamCol_.attach(table_, "BEAMNO");
306  ifCol_.attach(table_, "IFNO");
307  polCol_.attach(table_, "POLNO");
308  integrCol_.attach(table_, "INTERVAL");
309  azCol_.attach(table_, "AZIMUTH");
310  elCol_.attach(table_, "ELEVATION");
311  dirCol_.attach(table_, "DIRECTION");
312  fldnCol_.attach(table_, "FIELDNAME");
313  rbeamCol_.attach(table_, "REFBEAMNO");
314
315  mweatheridCol_.attach(table_,"WEATHER_ID");
316  mfitidCol_.attach(table_,"FIT_ID");
317  mfreqidCol_.attach(table_, "FREQ_ID");
318  mtcalidCol_.attach(table_, "TCAL_ID");
319  mfocusidCol_.attach(table_, "FOCUS_ID");
320  mmolidCol_.attach(table_, "MOLECULE_ID");
321
322  //Add auxiliary column for row-based flagging (CAS-1433 Wataru Kawasaki)
323  attachAuxColumnDef(flagrowCol_, "FLAGROW", 0);
324
325}
326
327template<class T, class T2>
328void Scantable::attachAuxColumnDef(ScalarColumn<T>& col,
329                                   const String& colName,
330                                   const T2& defValue)
331{
332  try {
333    col.attach(table_, colName);
334  } catch (TableError& err) {
335    String errMesg = err.getMesg();
336    if (errMesg == "Table column " + colName + " is unknown") {
337      table_.addColumn(ScalarColumnDesc<T>(colName));
338      col.attach(table_, colName);
339      col.fillColumn(static_cast<T>(defValue));
340    } else {
341      throw;
342    }
343  } catch (...) {
344    throw;
345  }
346}
347
348template<class T, class T2>
349void Scantable::attachAuxColumnDef(ArrayColumn<T>& col,
350                                   const String& colName,
351                                   const Array<T2>& defValue)
352{
353  try {
354    col.attach(table_, colName);
355  } catch (TableError& err) {
356    String errMesg = err.getMesg();
357    if (errMesg == "Table column " + colName + " is unknown") {
358      table_.addColumn(ArrayColumnDesc<T>(colName));
359      col.attach(table_, colName);
360
361      int size = 0;
362      ArrayIterator<T2>& it = defValue.begin();
363      while (it != defValue.end()) {
364        ++size;
365        ++it;
366      }
367      IPosition ip(1, size);
368      Array<T>& arr(ip);
369      for (int i = 0; i < size; ++i)
370        arr[i] = static_cast<T>(defValue[i]);
371
372      col.fillColumn(arr);
373    } else {
374      throw;
375    }
376  } catch (...) {
377    throw;
378  }
379}
380
381void Scantable::setHeader(const STHeader& sdh)
382{
383  table_.rwKeywordSet().define("nIF", sdh.nif);
384  table_.rwKeywordSet().define("nBeam", sdh.nbeam);
385  table_.rwKeywordSet().define("nPol", sdh.npol);
386  table_.rwKeywordSet().define("nChan", sdh.nchan);
387  table_.rwKeywordSet().define("Observer", sdh.observer);
388  table_.rwKeywordSet().define("Project", sdh.project);
389  table_.rwKeywordSet().define("Obstype", sdh.obstype);
390  table_.rwKeywordSet().define("AntennaName", sdh.antennaname);
391  table_.rwKeywordSet().define("AntennaPosition", sdh.antennaposition);
392  table_.rwKeywordSet().define("Equinox", sdh.equinox);
393  table_.rwKeywordSet().define("FreqRefFrame", sdh.freqref);
394  table_.rwKeywordSet().define("FreqRefVal", sdh.reffreq);
395  table_.rwKeywordSet().define("Bandwidth", sdh.bandwidth);
396  table_.rwKeywordSet().define("UTC", sdh.utc);
397  table_.rwKeywordSet().define("FluxUnit", sdh.fluxunit);
398  table_.rwKeywordSet().define("Epoch", sdh.epoch);
399  table_.rwKeywordSet().define("POLTYPE", sdh.poltype);
400}
401
402STHeader Scantable::getHeader() const
403{
404  STHeader sdh;
405  table_.keywordSet().get("nBeam",sdh.nbeam);
406  table_.keywordSet().get("nIF",sdh.nif);
407  table_.keywordSet().get("nPol",sdh.npol);
408  table_.keywordSet().get("nChan",sdh.nchan);
409  table_.keywordSet().get("Observer", sdh.observer);
410  table_.keywordSet().get("Project", sdh.project);
411  table_.keywordSet().get("Obstype", sdh.obstype);
412  table_.keywordSet().get("AntennaName", sdh.antennaname);
413  table_.keywordSet().get("AntennaPosition", sdh.antennaposition);
414  table_.keywordSet().get("Equinox", sdh.equinox);
415  table_.keywordSet().get("FreqRefFrame", sdh.freqref);
416  table_.keywordSet().get("FreqRefVal", sdh.reffreq);
417  table_.keywordSet().get("Bandwidth", sdh.bandwidth);
418  table_.keywordSet().get("UTC", sdh.utc);
419  table_.keywordSet().get("FluxUnit", sdh.fluxunit);
420  table_.keywordSet().get("Epoch", sdh.epoch);
421  table_.keywordSet().get("POLTYPE", sdh.poltype);
422  return sdh;
423}
424
425void Scantable::setSourceType( int stype )
426{
427  if ( stype < 0 || stype > 1 )
428    throw(AipsError("Illegal sourcetype."));
429  TableVector<Int> tabvec(table_, "SRCTYPE");
430  tabvec = Int(stype);
431}
432
433bool Scantable::conformant( const Scantable& other )
434{
435  return this->getHeader().conformant(other.getHeader());
436}
437
438
439
440std::string Scantable::formatSec(Double x) const
441{
442  Double xcop = x;
443  MVTime mvt(xcop/24./3600.);  // make days
444
445  if (x < 59.95)
446    return  String("      ") + mvt.string(MVTime::TIME_CLEAN_NO_HM, 7)+"s";
447  else if (x < 3599.95)
448    return String("   ") + mvt.string(MVTime::TIME_CLEAN_NO_H,7)+" ";
449  else {
450    ostringstream oss;
451    oss << setw(2) << std::right << setprecision(1) << mvt.hour();
452    oss << ":" << mvt.string(MVTime::TIME_CLEAN_NO_H,7) << " ";
453    return String(oss);
454  }
455};
456
457std::string Scantable::formatDirection(const MDirection& md) const
458{
459  Vector<Double> t = md.getAngle(Unit(String("rad"))).getValue();
460  Int prec = 7;
461
462  MVAngle mvLon(t[0]);
463  String sLon = mvLon.string(MVAngle::TIME,prec);
464  uInt tp = md.getRef().getType();
465  if (tp == MDirection::GALACTIC ||
466      tp == MDirection::SUPERGAL ) {
467    sLon = mvLon(0.0).string(MVAngle::ANGLE_CLEAN,prec);
468  }
469  MVAngle mvLat(t[1]);
470  String sLat = mvLat.string(MVAngle::ANGLE+MVAngle::DIG2,prec);
471  return sLon + String(" ") + sLat;
472}
473
474
475std::string Scantable::getFluxUnit() const
476{
477  return table_.keywordSet().asString("FluxUnit");
478}
479
480void Scantable::setFluxUnit(const std::string& unit)
481{
482  String tmp(unit);
483  Unit tU(tmp);
484  if (tU==Unit("K") || tU==Unit("Jy")) {
485     table_.rwKeywordSet().define(String("FluxUnit"), tmp);
486  } else {
487     throw AipsError("Illegal unit - must be compatible with Jy or K");
488  }
489}
490
491void Scantable::setInstrument(const std::string& name)
492{
493  bool throwIt = true;
494  // create an Instrument to see if this is valid
495  STAttr::convertInstrument(name, throwIt);
496  String nameU(name);
497  nameU.upcase();
498  table_.rwKeywordSet().define(String("AntennaName"), nameU);
499}
500
501void Scantable::setFeedType(const std::string& feedtype)
502{
503  if ( Scantable::factories_.find(feedtype) ==  Scantable::factories_.end() ) {
504    std::string msg = "Illegal feed type "+ feedtype;
505    throw(casa::AipsError(msg));
506  }
507  table_.rwKeywordSet().define(String("POLTYPE"), feedtype);
508}
509
510MPosition Scantable::getAntennaPosition() const
511{
512  Vector<Double> antpos;
513  table_.keywordSet().get("AntennaPosition", antpos);
514  MVPosition mvpos(antpos(0),antpos(1),antpos(2));
515  return MPosition(mvpos);
516}
517
518void Scantable::makePersistent(const std::string& filename)
519{
520  String inname(filename);
521  Path path(inname);
522  /// @todo reindex SCANNO, recompute nbeam, nif, npol
523  inname = path.expandedName();
524  // WORKAROUND !!! for Table bug
525  // Remove when fixed in casacore
526  if ( table_.tableType() == Table::Memory  && !selector_.empty() ) {
527    Table tab = table_.copyToMemoryTable(generateName());
528    tab.deepCopy(inname, Table::New);
529    tab.markForDelete();
530
531  } else {
532    table_.deepCopy(inname, Table::New);
533  }
534}
535
536int Scantable::nbeam( int scanno ) const
537{
538  if ( scanno < 0 ) {
539    Int n;
540    table_.keywordSet().get("nBeam",n);
541    return int(n);
542  } else {
543    // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
544    Table t = table_(table_.col("SCANNO") == scanno);
545    ROTableRow row(t);
546    const TableRecord& rec = row.get(0);
547    Table subt = t( t.col("IFNO") == Int(rec.asuInt("IFNO"))
548                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
549                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
550    ROTableVector<uInt> v(subt, "BEAMNO");
551    return int(v.nelements());
552  }
553  return 0;
554}
555
556int Scantable::nif( int scanno ) const
557{
558  if ( scanno < 0 ) {
559    Int n;
560    table_.keywordSet().get("nIF",n);
561    return int(n);
562  } else {
563    // take the first POLNO,BEAMNO,CYCLENO as nbeam shouldn't vary with these
564    Table t = table_(table_.col("SCANNO") == scanno);
565    ROTableRow row(t);
566    const TableRecord& rec = row.get(0);
567    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
568                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
569                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
570    if ( subt.nrow() == 0 ) return 0;
571    ROTableVector<uInt> v(subt, "IFNO");
572    return int(v.nelements());
573  }
574  return 0;
575}
576
577int Scantable::npol( int scanno ) const
578{
579  if ( scanno < 0 ) {
580    Int n;
581    table_.keywordSet().get("nPol",n);
582    return n;
583  } else {
584    // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
585    Table t = table_(table_.col("SCANNO") == scanno);
586    ROTableRow row(t);
587    const TableRecord& rec = row.get(0);
588    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
589                    && t.col("IFNO") == Int(rec.asuInt("IFNO"))
590                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
591    if ( subt.nrow() == 0 ) return 0;
592    ROTableVector<uInt> v(subt, "POLNO");
593    return int(v.nelements());
594  }
595  return 0;
596}
597
598int Scantable::ncycle( int scanno ) const
599{
600  if ( scanno < 0 ) {
601    Block<String> cols(2);
602    cols[0] = "SCANNO";
603    cols[1] = "CYCLENO";
604    TableIterator it(table_, cols);
605    int n = 0;
606    while ( !it.pastEnd() ) {
607      ++n;
608      ++it;
609    }
610    return n;
611  } else {
612    Table t = table_(table_.col("SCANNO") == scanno);
613    ROTableRow row(t);
614    const TableRecord& rec = row.get(0);
615    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
616                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
617                    && t.col("IFNO") == Int(rec.asuInt("IFNO")) );
618    if ( subt.nrow() == 0 ) return 0;
619    return int(subt.nrow());
620  }
621  return 0;
622}
623
624
625int Scantable::nrow( int scanno ) const
626{
627  return int(table_.nrow());
628}
629
630int Scantable::nchan( int ifno ) const
631{
632  if ( ifno < 0 ) {
633    Int n;
634    table_.keywordSet().get("nChan",n);
635    return int(n);
636  } else {
637    // take the first SCANNO,POLNO,BEAMNO,CYCLENO as nbeam shouldn't
638    // vary with these
639    Table t = table_(table_.col("IFNO") == ifno);
640    if ( t.nrow() == 0 ) return 0;
641    ROArrayColumn<Float> v(t, "SPECTRA");
642    return v.shape(0)(0);
643  }
644  return 0;
645}
646
647int Scantable::nscan() const {
648  Vector<uInt> scannos(scanCol_.getColumn());
649  uInt nout = genSort( scannos, Sort::Ascending,
650                       Sort::QuickSort|Sort::NoDuplicates );
651  return int(nout);
652}
653
654int Scantable::getChannels(int whichrow) const
655{
656  return specCol_.shape(whichrow)(0);
657}
658
659int Scantable::getBeam(int whichrow) const
660{
661  return beamCol_(whichrow);
662}
663
664std::vector<uint> Scantable::getNumbers(const ScalarColumn<uInt>& col) const
665{
666  Vector<uInt> nos(col.getColumn());
667  uInt n = genSort( nos, Sort::Ascending, Sort::QuickSort|Sort::NoDuplicates );
668  nos.resize(n, True);
669  std::vector<uint> stlout;
670  nos.tovector(stlout);
671  return stlout;
672}
673
674int Scantable::getIF(int whichrow) const
675{
676  return ifCol_(whichrow);
677}
678
679int Scantable::getPol(int whichrow) const
680{
681  return polCol_(whichrow);
682}
683
684std::string Scantable::formatTime(const MEpoch& me, bool showdate) const
685{
686  return formatTime(me, showdate, 0);
687}
688
689std::string Scantable::formatTime(const MEpoch& me, bool showdate, uInt prec) const
690{
691  MVTime mvt(me.getValue());
692  if (showdate)
693    //mvt.setFormat(MVTime::YMD);
694    mvt.setFormat(MVTime::YMD, prec);
695  else
696    //mvt.setFormat(MVTime::TIME);
697    mvt.setFormat(MVTime::TIME, prec);
698  ostringstream oss;
699  oss << mvt;
700  return String(oss);
701}
702
703void Scantable::calculateAZEL()
704{
705  MPosition mp = getAntennaPosition();
706  MEpoch::ROScalarColumn timeCol(table_, "TIME");
707  ostringstream oss;
708  oss << "Computed azimuth/elevation using " << endl
709      << mp << endl;
710  for (Int i=0; i<nrow(); ++i) {
711    MEpoch me = timeCol(i);
712    MDirection md = getDirection(i);
713    oss  << " Time: " << formatTime(me,False) << " Direction: " << formatDirection(md)
714         << endl << "     => ";
715    MeasFrame frame(mp, me);
716    Vector<Double> azel =
717        MDirection::Convert(md, MDirection::Ref(MDirection::AZEL,
718                                                frame)
719                            )().getAngle("rad").getValue();
720    azCol_.put(i,Float(azel[0]));
721    elCol_.put(i,Float(azel[1]));
722    oss << "azel: " << azel[0]/C::pi*180.0 << " "
723        << azel[1]/C::pi*180.0 << " (deg)" << endl;
724  }
725  pushLog(String(oss));
726}
727
728void Scantable::clip(const Float uthres, const Float dthres, bool clipoutside, bool unflag)
729{
730  for (uInt i=0; i<table_.nrow(); ++i) {
731    Vector<uChar> flgs = flagsCol_(i);
732    srchChannelsToClip(i, uthres, dthres, clipoutside, unflag, flgs);
733    flagsCol_.put(i, flgs);
734  }
735}
736
737std::vector<bool> Scantable::getClipMask(int whichrow, const Float uthres, const Float dthres, bool clipoutside, bool unflag)
738{
739  Vector<uChar> flags;
740  flagsCol_.get(uInt(whichrow), flags);
741  srchChannelsToClip(uInt(whichrow), uthres, dthres, clipoutside, unflag, flags);
742  Vector<Bool> bflag(flags.shape());
743  convertArray(bflag, flags);
744  //bflag = !bflag;
745
746  std::vector<bool> mask;
747  bflag.tovector(mask);
748  return mask;
749}
750
751void Scantable::srchChannelsToClip(uInt whichrow, const Float uthres, const Float dthres, bool clipoutside, bool unflag,
752                                   Vector<uChar> flgs)
753{
754    Vector<Float> spcs = specCol_(whichrow);
755    uInt nchannel = nchan();
756    if (spcs.nelements() != nchannel) {
757      throw(AipsError("Data has incorrect number of channels"));
758    }
759    uChar userflag = 1 << 7;
760    if (unflag) {
761      userflag = 0 << 7;
762    }
763    if (clipoutside) {
764      for (uInt j = 0; j < nchannel; ++j) {
765        Float spc = spcs(j);
766        if ((spc >= uthres) || (spc <= dthres)) {
767          flgs(j) = userflag;
768        }
769      }
770    } else {
771      for (uInt j = 0; j < nchannel; ++j) {
772        Float spc = spcs(j);
773        if ((spc < uthres) && (spc > dthres)) {
774          flgs(j) = userflag;
775        }
776      }
777    }
778}
779
780
781void Scantable::flag( int whichrow, const std::vector<bool>& msk, bool unflag ) {
782  std::vector<bool>::const_iterator it;
783  uInt ntrue = 0;
784  if (whichrow >= int(table_.nrow()) ) {
785    throw(AipsError("Invalid row number"));
786  }
787  for (it = msk.begin(); it != msk.end(); ++it) {
788    if ( *it ) {
789      ntrue++;
790    }
791  }
792  //if ( selector_.empty()  && (msk.size() == 0 || msk.size() == ntrue) )
793  if ( whichrow == -1 && !unflag && selector_.empty() && (msk.size() == 0 || msk.size() == ntrue) )
794    throw(AipsError("Trying to flag whole scantable."));
795  uChar userflag = 1 << 7;
796  if ( unflag ) {
797    userflag = 0 << 7;
798  }
799  if (whichrow > -1 ) {
800    applyChanFlag(uInt(whichrow), msk, userflag);
801  } else {
802    for ( uInt i=0; i<table_.nrow(); ++i) {
803      applyChanFlag(i, msk, userflag);
804    }
805  }
806}
807
808void Scantable::applyChanFlag( uInt whichrow, const std::vector<bool>& msk, uChar flagval )
809{
810  if (whichrow >= table_.nrow() ) {
811    throw( casa::indexError<int>( whichrow, "asap::Scantable::applyChanFlag: Invalid row number" ) );
812  }
813  Vector<uChar> flgs = flagsCol_(whichrow);
814  if ( msk.size() == 0 ) {
815    flgs = flagval;
816    flagsCol_.put(whichrow, flgs);
817    return;
818  }
819  if ( int(msk.size()) != nchan() ) {
820    throw(AipsError("Mask has incorrect number of channels."));
821  }
822  if ( flgs.nelements() != msk.size() ) {
823    throw(AipsError("Mask has incorrect number of channels."
824                    " Probably varying with IF. Please flag per IF"));
825  }
826  std::vector<bool>::const_iterator it;
827  uInt j = 0;
828  for (it = msk.begin(); it != msk.end(); ++it) {
829    if ( *it ) {
830      flgs(j) = flagval;
831    }
832    ++j;
833  }
834  flagsCol_.put(whichrow, flgs);
835}
836
837void Scantable::flagRow(const std::vector<uInt>& rows, bool unflag)
838{
839  if ( selector_.empty() && (rows.size() == table_.nrow()) )
840    throw(AipsError("Trying to flag whole scantable."));
841
842  uInt rowflag = (unflag ? 0 : 1);
843  std::vector<uInt>::const_iterator it;
844  for (it = rows.begin(); it != rows.end(); ++it)
845    flagrowCol_.put(*it, rowflag);
846}
847
848std::vector<bool> Scantable::getMask(int whichrow) const
849{
850  Vector<uChar> flags;
851  flagsCol_.get(uInt(whichrow), flags);
852  Vector<Bool> bflag(flags.shape());
853  convertArray(bflag, flags);
854  bflag = !bflag;
855  std::vector<bool> mask;
856  bflag.tovector(mask);
857  return mask;
858}
859
860std::vector<float> Scantable::getSpectrum( int whichrow,
861                                           const std::string& poltype ) const
862{
863  String ptype = poltype;
864  if (poltype == "" ) ptype = getPolType();
865  if ( whichrow  < 0 || whichrow >= nrow() )
866    throw(AipsError("Illegal row number."));
867  std::vector<float> out;
868  Vector<Float> arr;
869  uInt requestedpol = polCol_(whichrow);
870  String basetype = getPolType();
871  if ( ptype == basetype ) {
872    specCol_.get(whichrow, arr);
873  } else {
874    CountedPtr<STPol> stpol(STPol::getPolClass(Scantable::factories_,
875                                               basetype));
876    uInt row = uInt(whichrow);
877    stpol->setSpectra(getPolMatrix(row));
878    Float fang,fhand,parang;
879    fang = focusTable_.getTotalAngle(mfocusidCol_(row));
880    fhand = focusTable_.getFeedHand(mfocusidCol_(row));
881    stpol->setPhaseCorrections(fang, fhand);
882    arr = stpol->getSpectrum(requestedpol, ptype);
883  }
884  if ( arr.nelements() == 0 )
885    pushLog("Not enough polarisations present to do the conversion.");
886  arr.tovector(out);
887  return out;
888}
889
890void Scantable::setSpectrum( const std::vector<float>& spec,
891                                   int whichrow )
892{
893  Vector<Float> spectrum(spec);
894  Vector<Float> arr;
895  specCol_.get(whichrow, arr);
896  if ( spectrum.nelements() != arr.nelements() )
897    throw AipsError("The spectrum has incorrect number of channels.");
898  specCol_.put(whichrow, spectrum);
899}
900
901
902String Scantable::generateName()
903{
904  return (File::newUniqueName("./","temp")).baseName();
905}
906
907const casa::Table& Scantable::table( ) const
908{
909  return table_;
910}
911
912casa::Table& Scantable::table( )
913{
914  return table_;
915}
916
917std::string Scantable::getPolType() const
918{
919  return table_.keywordSet().asString("POLTYPE");
920}
921
922void Scantable::unsetSelection()
923{
924  table_ = originalTable_;
925  attach();
926  selector_.reset();
927}
928
929void Scantable::setSelection( const STSelector& selection )
930{
931  Table tab = const_cast<STSelector&>(selection).apply(originalTable_);
932  if ( tab.nrow() == 0 ) {
933    throw(AipsError("Selection contains no data. Not applying it."));
934  }
935  table_ = tab;
936  attach();
937  selector_ = selection;
938}
939
940std::string Scantable::summary( bool verbose )
941{
942  // Format header info
943  ostringstream oss;
944  oss << endl;
945  oss << asap::SEPERATOR << endl;
946  oss << " Scan Table Summary" << endl;
947  oss << asap::SEPERATOR << endl;
948  oss.flags(std::ios_base::left);
949  oss << setw(15) << "Beams:" << setw(4) << nbeam() << endl
950      << setw(15) << "IFs:" << setw(4) << nif() << endl
951      << setw(15) << "Polarisations:" << setw(4) << npol()
952      << "(" << getPolType() << ")" << endl
953      << setw(15) << "Channels:" << nchan() << endl;
954  String tmp;
955  oss << setw(15) << "Observer:"
956      << table_.keywordSet().asString("Observer") << endl;
957  oss << setw(15) << "Obs Date:" << getTime(-1,true) << endl;
958  table_.keywordSet().get("Project", tmp);
959  oss << setw(15) << "Project:" << tmp << endl;
960  table_.keywordSet().get("Obstype", tmp);
961  oss << setw(15) << "Obs. Type:" << tmp << endl;
962  table_.keywordSet().get("AntennaName", tmp);
963  oss << setw(15) << "Antenna Name:" << tmp << endl;
964  table_.keywordSet().get("FluxUnit", tmp);
965  oss << setw(15) << "Flux Unit:" << tmp << endl;
966  //Vector<Double> vec(moleculeTable_.getRestFrequencies());
967  int nid = moleculeTable_.nrow();
968  Bool firstline = True;
969  oss << setw(15) << "Rest Freqs:";
970  for (int i=0; i<nid; i++) {
971      Table t = table_(table_.col("MOLECULE_ID") == i);
972      if (t.nrow() >  0) {
973          Vector<Double> vec(moleculeTable_.getRestFrequency(i));
974          if (vec.nelements() > 0) {
975               if (firstline) {
976                   oss << setprecision(10) << vec << " [Hz]" << endl;
977                   firstline=False;
978               }
979               else{
980                   oss << setw(15)<<" " << setprecision(10) << vec << " [Hz]" << endl;
981               }
982          } else {
983              oss << "none" << endl;
984          }
985      }
986  }
987
988  oss << setw(15) << "Abcissa:" << getAbcissaLabel(0) << endl;
989  oss << selector_.print() << endl;
990  oss << endl;
991  // main table
992  String dirtype = "Position ("
993                  + getDirectionRefString()
994                  + ")";
995  oss << setw(5) << "Scan" << setw(15) << "Source"
996      << setw(10) << "Time" << setw(18) << "Integration" << endl;
997  oss << setw(5) << "" << setw(5) << "Beam" << setw(3) << "" << dirtype << endl;
998  oss << setw(10) << "" << setw(3) << "IF" << setw(3) << ""
999      << setw(8) << "Frame" << setw(16)
1000      << "RefVal" << setw(10) << "RefPix" << setw(12) << "Increment"
1001      << setw(7) << "Channels"
1002      << endl;
1003  oss << asap::SEPERATOR << endl;
1004  TableIterator iter(table_, "SCANNO");
1005  while (!iter.pastEnd()) {
1006    Table subt = iter.table();
1007    ROTableRow row(subt);
1008    MEpoch::ROScalarColumn timeCol(subt,"TIME");
1009    const TableRecord& rec = row.get(0);
1010    oss << setw(4) << std::right << rec.asuInt("SCANNO")
1011        << std::left << setw(1) << ""
1012        << setw(15) << rec.asString("SRCNAME")
1013        << setw(10) << formatTime(timeCol(0), false);
1014    // count the cycles in the scan
1015    TableIterator cyciter(subt, "CYCLENO");
1016    int nint = 0;
1017    while (!cyciter.pastEnd()) {
1018      ++nint;
1019      ++cyciter;
1020    }
1021    oss << setw(3) << std::right << nint  << setw(3) << " x " << std::left
1022        << setw(6) <<  formatSec(rec.asFloat("INTERVAL")) << endl;
1023
1024    TableIterator biter(subt, "BEAMNO");
1025    while (!biter.pastEnd()) {
1026      Table bsubt = biter.table();
1027      ROTableRow brow(bsubt);
1028      const TableRecord& brec = brow.get(0);
1029      uInt row0 = bsubt.rowNumbers(table_)[0];
1030      oss << setw(5) << "" <<  setw(4) << std::right << brec.asuInt("BEAMNO")<< std::left;
1031      oss  << setw(4) << ""  << formatDirection(getDirection(row0)) << endl;
1032      TableIterator iiter(bsubt, "IFNO");
1033      while (!iiter.pastEnd()) {
1034        Table isubt = iiter.table();
1035        ROTableRow irow(isubt);
1036        const TableRecord& irec = irow.get(0);
1037        oss << setw(9) << "";
1038        oss << setw(3) << std::right << irec.asuInt("IFNO") << std::left
1039            << setw(1) << "" << frequencies().print(irec.asuInt("FREQ_ID"))
1040            << setw(3) << "" << nchan(irec.asuInt("IFNO"))
1041            << endl;
1042
1043        ++iiter;
1044      }
1045      ++biter;
1046    }
1047    ++iter;
1048  }
1049  /// @todo implement verbose mode
1050  return String(oss);
1051}
1052
1053// std::string Scantable::getTime(int whichrow, bool showdate) const
1054// {
1055//   MEpoch::ROScalarColumn timeCol(table_, "TIME");
1056//   MEpoch me;
1057//   if (whichrow > -1) {
1058//     me = timeCol(uInt(whichrow));
1059//   } else {
1060//     Double tm;
1061//     table_.keywordSet().get("UTC",tm);
1062//     me = MEpoch(MVEpoch(tm));
1063//   }
1064//   return formatTime(me, showdate);
1065// }
1066
1067std::string Scantable::getTime(int whichrow, bool showdate, uInt prec) const
1068{
1069  MEpoch me;
1070  me = getEpoch(whichrow);
1071  return formatTime(me, showdate, prec);
1072}
1073
1074MEpoch Scantable::getEpoch(int whichrow) const
1075{
1076  if (whichrow > -1) {
1077    return timeCol_(uInt(whichrow));
1078  } else {
1079    Double tm;
1080    table_.keywordSet().get("UTC",tm);
1081    return MEpoch(MVEpoch(tm));
1082  }
1083}
1084
1085std::string Scantable::getDirectionString(int whichrow) const
1086{
1087  return formatDirection(getDirection(uInt(whichrow)));
1088}
1089
1090
1091SpectralCoordinate Scantable::getSpectralCoordinate(int whichrow) const {
1092  const MPosition& mp = getAntennaPosition();
1093  const MDirection& md = getDirection(whichrow);
1094  const MEpoch& me = timeCol_(whichrow);
1095  //Double rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
1096  Vector<Double> rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
1097  return freqTable_.getSpectralCoordinate(md, mp, me, rf,
1098                                          mfreqidCol_(whichrow));
1099}
1100
1101std::vector< double > Scantable::getAbcissa( int whichrow ) const
1102{
1103  if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal row number"));
1104  std::vector<double> stlout;
1105  int nchan = specCol_(whichrow).nelements();
1106  String us = freqTable_.getUnitString();
1107  if ( us == "" || us == "pixel" || us == "channel" ) {
1108    for (int i=0; i<nchan; ++i) {
1109      stlout.push_back(double(i));
1110    }
1111    return stlout;
1112  }
1113  SpectralCoordinate spc = getSpectralCoordinate(whichrow);
1114  Vector<Double> pixel(nchan);
1115  Vector<Double> world;
1116  indgen(pixel);
1117  if ( Unit(us) == Unit("Hz") ) {
1118    for ( int i=0; i < nchan; ++i) {
1119      Double world;
1120      spc.toWorld(world, pixel[i]);
1121      stlout.push_back(double(world));
1122    }
1123  } else if ( Unit(us) == Unit("km/s") ) {
1124    Vector<Double> world;
1125    spc.pixelToVelocity(world, pixel);
1126    world.tovector(stlout);
1127  }
1128  return stlout;
1129}
1130void Scantable::setDirectionRefString( const std::string & refstr )
1131{
1132  MDirection::Types mdt;
1133  if (refstr != "" && !MDirection::getType(mdt, refstr)) {
1134    throw(AipsError("Illegal Direction frame."));
1135  }
1136  if ( refstr == "" ) {
1137    String defaultstr = MDirection::showType(dirCol_.getMeasRef().getType());
1138    table_.rwKeywordSet().define("DIRECTIONREF", defaultstr);
1139  } else {
1140    table_.rwKeywordSet().define("DIRECTIONREF", String(refstr));
1141  }
1142}
1143
1144std::string Scantable::getDirectionRefString( ) const
1145{
1146  return table_.keywordSet().asString("DIRECTIONREF");
1147}
1148
1149MDirection Scantable::getDirection(int whichrow ) const
1150{
1151  String usertype = table_.keywordSet().asString("DIRECTIONREF");
1152  String type = MDirection::showType(dirCol_.getMeasRef().getType());
1153  if ( usertype != type ) {
1154    MDirection::Types mdt;
1155    if (!MDirection::getType(mdt, usertype)) {
1156      throw(AipsError("Illegal Direction frame."));
1157    }
1158    return dirCol_.convert(uInt(whichrow), mdt);
1159  } else {
1160    return dirCol_(uInt(whichrow));
1161  }
1162}
1163
1164std::string Scantable::getAbcissaLabel( int whichrow ) const
1165{
1166  if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal ro number"));
1167  const MPosition& mp = getAntennaPosition();
1168  const MDirection& md = getDirection(whichrow);
1169  const MEpoch& me = timeCol_(whichrow);
1170  //const Double& rf = mmolidCol_(whichrow);
1171  const Vector<Double> rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
1172  SpectralCoordinate spc =
1173    freqTable_.getSpectralCoordinate(md, mp, me, rf, mfreqidCol_(whichrow));
1174
1175  String s = "Channel";
1176  Unit u = Unit(freqTable_.getUnitString());
1177  if (u == Unit("km/s")) {
1178    s = CoordinateUtil::axisLabel(spc, 0, True,True,  True);
1179  } else if (u == Unit("Hz")) {
1180    Vector<String> wau(1);wau = u.getName();
1181    spc.setWorldAxisUnits(wau);
1182    s = CoordinateUtil::axisLabel(spc, 0, True, True, False);
1183  }
1184  return s;
1185
1186}
1187
1188/**
1189void asap::Scantable::setRestFrequencies( double rf, const std::string& name,
1190                                          const std::string& unit )
1191**/
1192void Scantable::setRestFrequencies( vector<double> rf, const vector<std::string>& name,
1193                                          const std::string& unit )
1194
1195{
1196  ///@todo lookup in line table to fill in name and formattedname
1197  Unit u(unit);
1198  //Quantum<Double> urf(rf, u);
1199  Quantum<Vector<Double> >urf(rf, u);
1200  Vector<String> formattedname(0);
1201  //cerr<<"Scantable::setRestFrequnecies="<<urf<<endl;
1202
1203  //uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), name, "");
1204  uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), mathutil::toVectorString(name), formattedname);
1205  TableVector<uInt> tabvec(table_, "MOLECULE_ID");
1206  tabvec = id;
1207}
1208
1209/**
1210void asap::Scantable::setRestFrequencies( const std::string& name )
1211{
1212  throw(AipsError("setRestFrequencies( const std::string& name ) NYI"));
1213  ///@todo implement
1214}
1215**/
1216void Scantable::setRestFrequencies( const vector<std::string>& name )
1217{
1218  throw(AipsError("setRestFrequencies( const vector<std::string>& name ) NYI"));
1219  ///@todo implement
1220}
1221
1222std::vector< unsigned int > Scantable::rownumbers( ) const
1223{
1224  std::vector<unsigned int> stlout;
1225  Vector<uInt> vec = table_.rowNumbers();
1226  vec.tovector(stlout);
1227  return stlout;
1228}
1229
1230
1231Matrix<Float> Scantable::getPolMatrix( uInt whichrow ) const
1232{
1233  ROTableRow row(table_);
1234  const TableRecord& rec = row.get(whichrow);
1235  Table t =
1236    originalTable_( originalTable_.col("SCANNO") == Int(rec.asuInt("SCANNO"))
1237                    && originalTable_.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
1238                    && originalTable_.col("IFNO") == Int(rec.asuInt("IFNO"))
1239                    && originalTable_.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
1240  ROArrayColumn<Float> speccol(t, "SPECTRA");
1241  return speccol.getColumn();
1242}
1243
1244std::vector< std::string > Scantable::columnNames( ) const
1245{
1246  Vector<String> vec = table_.tableDesc().columnNames();
1247  return mathutil::tovectorstring(vec);
1248}
1249
1250MEpoch::Types Scantable::getTimeReference( ) const
1251{
1252  return MEpoch::castType(timeCol_.getMeasRef().getType());
1253}
1254
1255void Scantable::addFit( const STFitEntry& fit, int row )
1256{
1257  //cout << mfitidCol_(uInt(row)) << endl;
1258  LogIO os( LogOrigin( "Scantable", "addFit()", WHERE ) ) ;
1259  os << mfitidCol_(uInt(row)) << LogIO::POST ;
1260  uInt id = fitTable_.addEntry(fit, mfitidCol_(uInt(row)));
1261  mfitidCol_.put(uInt(row), id);
1262}
1263
1264void Scantable::shift(int npix)
1265{
1266  Vector<uInt> fids(mfreqidCol_.getColumn());
1267  genSort( fids, Sort::Ascending,
1268           Sort::QuickSort|Sort::NoDuplicates );
1269  for (uInt i=0; i<fids.nelements(); ++i) {
1270    frequencies().shiftRefPix(npix, fids[i]);
1271  }
1272}
1273
1274String Scantable::getAntennaName() const
1275{
1276  String out;
1277  table_.keywordSet().get("AntennaName", out);
1278  String::size_type pos1 = out.find("@") ;
1279  String::size_type pos2 = out.find("//") ;
1280  if ( pos2 != String::npos )
1281    out = out.substr(pos2+2,pos1) ;
1282  else if ( pos1 != String::npos )
1283    out = out.substr(0,pos1) ;
1284  return out;
1285}
1286
1287int Scantable::checkScanInfo(const std::vector<int>& scanlist) const
1288{
1289  String tbpath;
1290  int ret = 0;
1291  if ( table_.keywordSet().isDefined("GBT_GO") ) {
1292    table_.keywordSet().get("GBT_GO", tbpath);
1293    Table t(tbpath,Table::Old);
1294    // check each scan if other scan of the pair exist
1295    int nscan = scanlist.size();
1296    for (int i = 0; i < nscan; i++) {
1297      Table subt = t( t.col("SCAN") == scanlist[i]+1 );
1298      if (subt.nrow()==0) {
1299        //cerr <<"Scan "<<scanlist[i]<<" cannot be found in the scantable."<<endl;
1300        LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1301        os <<LogIO::WARN<<"Scan "<<scanlist[i]<<" cannot be found in the scantable."<<LogIO::POST;
1302        ret = 1;
1303        break;
1304      }
1305      ROTableRow row(subt);
1306      const TableRecord& rec = row.get(0);
1307      int scan1seqn = rec.asuInt("PROCSEQN");
1308      int laston1 = rec.asuInt("LASTON");
1309      if ( rec.asuInt("PROCSIZE")==2 ) {
1310        if ( i < nscan-1 ) {
1311          Table subt2 = t( t.col("SCAN") == scanlist[i+1]+1 );
1312          if ( subt2.nrow() == 0) {
1313            LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1314
1315            //cerr<<"Scan "<<scanlist[i+1]<<" cannot be found in the scantable."<<endl;
1316            os<<LogIO::WARN<<"Scan "<<scanlist[i+1]<<" cannot be found in the scantable."<<LogIO::POST;
1317            ret = 1;
1318            break;
1319          }
1320          ROTableRow row2(subt2);
1321          const TableRecord& rec2 = row2.get(0);
1322          int scan2seqn = rec2.asuInt("PROCSEQN");
1323          int laston2 = rec2.asuInt("LASTON");
1324          if (scan1seqn == 1 && scan2seqn == 2) {
1325            if (laston1 == laston2) {
1326              LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1327              //cerr<<"A valid scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl;
1328              os<<"A valid scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<LogIO::POST;
1329              i +=1;
1330            }
1331            else {
1332              LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1333              //cerr<<"Incorrect scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl;
1334              os<<LogIO::WARN<<"Incorrect scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<LogIO::POST;
1335            }
1336          }
1337          else if (scan1seqn==2 && scan2seqn == 1) {
1338            if (laston1 == laston2) {
1339              LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1340              //cerr<<"["<<scanlist[i]<<","<<scanlist[i+1]<<"] is a valid scan pair but in incorrect order."<<endl;
1341              os<<LogIO::WARN<<"["<<scanlist[i]<<","<<scanlist[i+1]<<"] is a valid scan pair but in incorrect order."<<LogIO::POST;
1342              ret = 1;
1343              break;
1344            }
1345          }
1346          else {
1347            LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1348            //cerr<<"The other scan for  "<<scanlist[i]<<" appears to be missing. Check the input scan numbers."<<endl;
1349            os<<LogIO::WARN<<"The other scan for  "<<scanlist[i]<<" appears to be missing. Check the input scan numbers."<<LogIO::POST;
1350            ret = 1;
1351            break;
1352          }
1353        }
1354      }
1355      else {
1356        LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1357        //cerr<<"The scan does not appear to be standard obsevation."<<endl;
1358        os<<LogIO::WARN<<"The scan does not appear to be standard obsevation."<<LogIO::POST;
1359      }
1360    //if ( i >= nscan ) break;
1361    }
1362  }
1363  else {
1364    LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1365    //cerr<<"No reference to GBT_GO table."<<endl;
1366    os<<LogIO::WARN<<"No reference to GBT_GO table."<<LogIO::POST;
1367    ret = 1;
1368  }
1369  return ret;
1370}
1371
1372std::vector<double> Scantable::getDirectionVector(int whichrow) const
1373{
1374  Vector<Double> Dir = dirCol_(whichrow).getAngle("rad").getValue();
1375  std::vector<double> dir;
1376  Dir.tovector(dir);
1377  return dir;
1378}
1379
1380void asap::Scantable::reshapeSpectrum( int nmin, int nmax )
1381  throw( casa::AipsError )
1382{
1383  // assumed that all rows have same nChan
1384  Vector<Float> arr = specCol_( 0 ) ;
1385  int nChan = arr.nelements() ;
1386
1387  // if nmin < 0 or nmax < 0, nothing to do
1388  if (  nmin < 0 ) {
1389    throw( casa::indexError<int>( nmin, "asap::Scantable::reshapeSpectrum: Invalid range. Negative index is specified." ) ) ;
1390    }
1391  if (  nmax < 0  ) {
1392    throw( casa::indexError<int>( nmax, "asap::Scantable::reshapeSpectrum: Invalid range. Negative index is specified." ) ) ;
1393  }
1394
1395  // if nmin > nmax, exchange values
1396  if ( nmin > nmax ) {
1397    int tmp = nmax ;
1398    nmax = nmin ;
1399    nmin = tmp ;
1400    LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1401    os << "Swap values. Applied range is ["
1402       << nmin << ", " << nmax << "]" << LogIO::POST ;
1403  }
1404
1405  // if nmin exceeds nChan, nothing to do
1406  if ( nmin >= nChan ) {
1407    throw( casa::indexError<int>( nmin, "asap::Scantable::reshapeSpectrum: Invalid range. Specified minimum exceeds nChan." ) ) ;
1408  }
1409
1410  // if nmax exceeds nChan, reset nmax to nChan
1411  if ( nmax >= nChan ) {
1412    if ( nmin == 0 ) {
1413      // nothing to do
1414      LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1415      os << "Whole range is selected. Nothing to do." << LogIO::POST ;
1416      return ;
1417    }
1418    else {
1419      LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1420      os << "Specified maximum exceeds nChan. Applied range is ["
1421         << nmin << ", " << nChan-1 << "]." << LogIO::POST ;
1422      nmax = nChan - 1 ;
1423    }
1424  }
1425
1426  // reshape specCol_ and flagCol_
1427  for ( int irow = 0 ; irow < nrow() ; irow++ ) {
1428    reshapeSpectrum( nmin, nmax, irow ) ;
1429  }
1430
1431  // update FREQUENCIES subtable
1432  Double refpix ;
1433  Double refval ;
1434  Double increment ;
1435  int freqnrow = freqTable_.table().nrow() ;
1436  Vector<uInt> oldId( freqnrow ) ;
1437  Vector<uInt> newId( freqnrow ) ;
1438  for ( int irow = 0 ; irow < freqnrow ; irow++ ) {
1439    freqTable_.getEntry( refpix, refval, increment, irow ) ;
1440    /***
1441     * need to shift refpix to nmin
1442     * note that channel nmin in old index will be channel 0 in new one
1443     ***/
1444    refval = refval - ( refpix - nmin ) * increment ;
1445    refpix = 0 ;
1446    freqTable_.setEntry( refpix, refval, increment, irow ) ;
1447  }
1448
1449  // update nchan
1450  int newsize = nmax - nmin + 1 ;
1451  table_.rwKeywordSet().define( "nChan", newsize ) ;
1452
1453  // update bandwidth
1454  // assumed all spectra in the scantable have same bandwidth
1455  table_.rwKeywordSet().define( "Bandwidth", increment * newsize ) ;
1456
1457  return ;
1458}
1459
1460void asap::Scantable::reshapeSpectrum( int nmin, int nmax, int irow )
1461{
1462  // reshape specCol_ and flagCol_
1463  Vector<Float> oldspec = specCol_( irow ) ;
1464  Vector<uChar> oldflag = flagsCol_( irow ) ;
1465  uInt newsize = nmax - nmin + 1 ;
1466  specCol_.put( irow, oldspec( Slice( nmin, newsize, 1 ) ) ) ;
1467  flagsCol_.put( irow, oldflag( Slice( nmin, newsize, 1 ) ) ) ;
1468
1469  return ;
1470}
1471
1472void asap::Scantable::regridChannel( int nChan, double dnu )
1473{
1474  LogIO os( LogOrigin( "Scantable", "regridChannel()", WHERE ) ) ;
1475  os << "Regrid abcissa with channel number " << nChan << " and spectral resoultion " << dnu << "Hz." << LogIO::POST ;
1476  // assumed that all rows have same nChan
1477  Vector<Float> arr = specCol_( 0 ) ;
1478  int oldsize = arr.nelements() ;
1479
1480  // if oldsize == nChan, nothing to do
1481  if ( oldsize == nChan ) {
1482    os << "Specified channel number is same as current one. Nothing to do." << LogIO::POST ;
1483    return ;
1484  }
1485
1486  // if oldChan < nChan, unphysical operation
1487  if ( oldsize < nChan ) {
1488    os << "Unphysical operation. Nothing to do." << LogIO::POST ;
1489    return ;
1490  }
1491
1492  // change channel number for specCol_ and flagCol_
1493  Vector<Float> newspec( nChan, 0 ) ;
1494  Vector<uChar> newflag( nChan, false ) ;
1495  vector<string> coordinfo = getCoordInfo() ;
1496  string oldinfo = coordinfo[0] ;
1497  coordinfo[0] = "Hz" ;
1498  setCoordInfo( coordinfo ) ;
1499  for ( int irow = 0 ; irow < nrow() ; irow++ ) {
1500    regridChannel( nChan, dnu, irow ) ;
1501  }
1502  coordinfo[0] = oldinfo ;
1503  setCoordInfo( coordinfo ) ;
1504
1505
1506  // NOTE: this method does not update metadata such as
1507  //       FREQUENCIES subtable, nChan, Bandwidth, etc.
1508
1509  return ;
1510}
1511
1512void asap::Scantable::regridChannel( int nChan, double dnu, int irow )
1513{
1514  // logging
1515  //ofstream ofs( "average.log", std::ios::out | std::ios::app ) ;
1516  //ofs << "IFNO = " << getIF( irow ) << " irow = " << irow << endl ;
1517
1518  Vector<Float> oldspec = specCol_( irow ) ;
1519  Vector<uChar> oldflag = flagsCol_( irow ) ;
1520  Vector<Float> newspec( nChan, 0 ) ;
1521  Vector<uChar> newflag( nChan, false ) ;
1522
1523  // regrid
1524  vector<double> abcissa = getAbcissa( irow ) ;
1525  int oldsize = abcissa.size() ;
1526  double olddnu = abcissa[1] - abcissa[0] ;
1527  //int refChan = 0 ;
1528  //double frac = 0.0 ;
1529  //double wedge = 0.0 ;
1530  //double pile = 0.0 ;
1531  int ichan = 0 ;
1532  double wsum = 0.0 ;
1533  Vector<Float> z( nChan ) ;
1534  z[0] = abcissa[0] - 0.5 * olddnu + 0.5 * dnu ;
1535  for ( int ii = 1 ; ii < nChan ; ii++ )
1536    z[ii] = z[ii-1] + dnu ;
1537  Vector<Float> zi( nChan+1 ) ;
1538  Vector<Float> yi( oldsize + 1 ) ;
1539  zi[0] = z[0] - 0.5 * dnu ;
1540  zi[1] = z[0] + 0.5 * dnu ;
1541  for ( int ii = 2 ; ii < nChan ; ii++ )
1542    zi[ii] = zi[ii-1] + dnu ;
1543  zi[nChan] = z[nChan-1] + 0.5 * dnu ;
1544  yi[0] = abcissa[0] - 0.5 * olddnu ;
1545  yi[1] = abcissa[1] + 0.5 * olddnu ;
1546  for ( int ii = 2 ; ii < oldsize ; ii++ )
1547    yi[ii] = abcissa[ii-1] + olddnu ;
1548  yi[oldsize] = abcissa[oldsize-1] + 0.5 * olddnu ;
1549  if ( dnu > 0.0 ) {
1550    for ( int ii = 0 ; ii < nChan ; ii++ ) {
1551      double zl = zi[ii] ;
1552      double zr = zi[ii+1] ;
1553      for ( int j = ichan ; j < oldsize ; j++ ) {
1554        double yl = yi[j] ;
1555        double yr = yi[j+1] ;
1556        if ( yl <= zl ) {
1557          if ( yr <= zl ) {
1558            continue ;
1559          }
1560          else if ( yr <= zr ) {
1561            newspec[ii] += oldspec[j] * ( yr - zl ) ;
1562            newflag[ii] = newflag[ii] || oldflag[j] ;
1563            wsum += ( yr - zl ) ;
1564          }
1565          else {
1566            newspec[ii] += oldspec[j] * dnu ;
1567            newflag[ii] = newflag[ii] || oldflag[j] ;
1568            wsum += dnu ;
1569            ichan = j ;
1570            break ;
1571          }
1572        }
1573        else if ( yl < zr ) {
1574          if ( yr <= zr ) {
1575              newspec[ii] += oldspec[j] * ( yr - yl ) ;
1576              newflag[ii] = newflag[ii] || oldflag[j] ;
1577              wsum += ( yr - yl ) ;
1578          }
1579          else {
1580            newspec[ii] += oldspec[j] * ( zr - yl ) ;
1581            newflag[ii] = newflag[ii] || oldflag[j] ;
1582            wsum += ( zr - yl ) ;
1583            ichan = j ;
1584            break ;
1585          }
1586        }
1587        else {
1588          ichan = j - 1 ;
1589          break ;
1590        }
1591      }
1592      newspec[ii] /= wsum ;
1593      wsum = 0.0 ;
1594    }
1595  }
1596  else if ( dnu < 0.0 ) {
1597    for ( int ii = 0 ; ii < nChan ; ii++ ) {
1598      double zl = zi[ii] ;
1599      double zr = zi[ii+1] ;
1600      for ( int j = ichan ; j < oldsize ; j++ ) {
1601        double yl = yi[j] ;
1602        double yr = yi[j+1] ;
1603        if ( yl >= zl ) {
1604          if ( yr >= zl ) {
1605            continue ;
1606          }
1607          else if ( yr >= zr ) {
1608            newspec[ii] += oldspec[j] * abs( yr - zl ) ;
1609            newflag[ii] = newflag[ii] || oldflag[j] ;
1610            wsum += abs( yr - zl ) ;
1611          }
1612          else {
1613            newspec[ii] += oldspec[j] * abs( dnu ) ;
1614            newflag[ii] = newflag[ii] || oldflag[j] ;
1615            wsum += abs( dnu ) ;
1616            ichan = j ;
1617            break ;
1618          }
1619        }
1620        else if ( yl > zr ) {
1621          if ( yr >= zr ) {
1622            newspec[ii] += oldspec[j] * abs( yr - yl ) ;
1623            newflag[ii] = newflag[ii] || oldflag[j] ;
1624            wsum += abs( yr - yl ) ;
1625          }
1626          else {
1627            newspec[ii] += oldspec[j] * abs( zr - yl ) ;
1628            newflag[ii] = newflag[ii] || oldflag[j] ;
1629            wsum += abs( zr - yl ) ;
1630            ichan = j ;
1631            break ;
1632          }
1633        }
1634        else {
1635          ichan = j - 1 ;
1636          break ;
1637        }
1638      }
1639      newspec[ii] /= wsum ;
1640      wsum = 0.0 ;
1641    }
1642  }
1643//    * ichan = 0
1644//    ***/
1645//   //ofs << "olddnu = " << olddnu << ", dnu = " << dnu << endl ;
1646//   pile += dnu ;
1647//   wedge = olddnu * ( refChan + 1 ) ;
1648//   while ( wedge < pile ) {
1649//     newspec[0] += olddnu * oldspec[refChan] ;
1650//     newflag[0] = newflag[0] || oldflag[refChan] ;
1651//     //ofs << "channel " << refChan << " is included in new channel 0" << endl ;
1652//     refChan++ ;
1653//     wedge += olddnu ;
1654//     wsum += olddnu ;
1655//     //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
1656//   }
1657//   frac = ( wedge - pile ) / olddnu ;
1658//   wsum += ( 1.0 - frac ) * olddnu ;
1659//   newspec[0] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
1660//   newflag[0] = newflag[0] || oldflag[refChan] ;
1661//   //ofs << "channel " << refChan << " is partly included in new channel 0" << " with fraction of " << ( 1.0 - frac ) << endl ;
1662//   //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
1663//   newspec[0] /= wsum ;
1664//   //ofs << "newspec[0] = " << newspec[0] << endl ;
1665//   //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
1666
1667//   /***
1668//    * ichan = 1 - nChan-2
1669//    ***/
1670//   for ( int ichan = 1 ; ichan < nChan - 1 ; ichan++ ) {
1671//     pile += dnu ;
1672//     newspec[ichan] += frac * olddnu * oldspec[refChan] ;
1673//     newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
1674//     //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << frac << endl ;
1675//     refChan++ ;
1676//     wedge += olddnu ;
1677//     wsum = frac * olddnu ;
1678//     //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
1679//     while ( wedge < pile ) {
1680//       newspec[ichan] += olddnu * oldspec[refChan] ;
1681//       newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
1682//       //ofs << "channel " << refChan << " is included in new channel " << ichan << endl ;
1683//       refChan++ ;
1684//       wedge += olddnu ;
1685//       wsum += olddnu ;
1686//       //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
1687//     }
1688//     frac = ( wedge - pile ) / olddnu ;
1689//     wsum += ( 1.0 - frac ) * olddnu ;
1690//     newspec[ichan] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
1691//     newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
1692//     //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << ( 1.0 - frac ) << endl ;
1693//     //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
1694//     //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
1695//     newspec[ichan] /= wsum ;
1696//     //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << endl ;
1697//   }
1698
1699//   /***
1700//    * ichan = nChan-1
1701//    ***/
1702//   // NOTE: Assumed that all spectra have the same bandwidth
1703//   pile += dnu ;
1704//   newspec[nChan-1] += frac * olddnu * oldspec[refChan] ;
1705//   newflag[nChan-1] = newflag[nChan-1] || oldflag[refChan] ;
1706//   //ofs << "channel " << refChan << " is partly included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
1707//   refChan++ ;
1708//   wedge += olddnu ;
1709//   wsum = frac * olddnu ;
1710//   //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
1711//   for ( int jchan = refChan ; jchan < oldsize ; jchan++ ) {
1712//     newspec[nChan-1] += olddnu * oldspec[jchan] ;
1713//     newflag[nChan-1] = newflag[nChan-1] || oldflag[jchan] ;
1714//     wsum += olddnu ;
1715//     //ofs << "channel " << jchan << " is included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
1716//     //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
1717//   }
1718//   //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
1719//   //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
1720//   newspec[nChan-1] /= wsum ;
1721//   //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << endl ;
1722
1723//   specCol_.put( irow, newspec ) ;
1724//   flagsCol_.put( irow, newflag ) ;
1725
1726//   // ofs.close() ;
1727
1728
1729  return ;
1730}
1731
1732std::vector<float> Scantable::getWeather(int whichrow) const
1733{
1734  std::vector<float> out(5);
1735  //Float temperature, pressure, humidity, windspeed, windaz;
1736  weatherTable_.getEntry(out[0], out[1], out[2], out[3], out[4],
1737                         mweatheridCol_(uInt(whichrow)));
1738
1739
1740  return out;
1741}
1742
1743bool Scantable::getFlagtraFast(int whichrow)
1744{
1745  uChar flag;
1746  Vector<uChar> flags;
1747  flagsCol_.get(uInt(whichrow), flags);
1748  for (int i = 0; i < flags.size(); i++) {
1749    if (i==0) {
1750      flag = flags[i];
1751    }
1752    else {
1753      flag &= flags[i];
1754    }
1755    return ((flag >> 7) == 1);
1756   }
1757}
1758
1759void Scantable::doPolyBaseline(const std::vector<bool>& mask, int order, int rowno, Fitter& fitter)
1760{
1761  fitter.setExpression("poly", order);
1762
1763  std::vector<double> abcsd = getAbcissa(rowno);
1764  std::vector<float> abcs;
1765  for (int i = 0; i < abcsd.size(); i++) {
1766    abcs.push_back((float)abcsd[i]);
1767  }
1768  std::vector<float> spec = getSpectrum(rowno);
1769  std::vector<bool> fmask = getMask(rowno);
1770  if (fmask.size() != mask.size()) {
1771    throw(AipsError("different mask sizes"));
1772  }
1773  for (int i = 0; i < fmask.size(); i++) {
1774    fmask[i] = fmask[i] && mask[i];
1775  }
1776  fitter.setData(abcs, spec, fmask);
1777
1778  fitter.lfit();
1779}
1780
1781void Scantable::polyBaselineBatch(const std::vector<bool>& mask, int order)
1782{
1783  Fitter fitter = Fitter();
1784  for (uInt rowno=0; rowno < nrow(); ++rowno) {
1785    doPolyBaseline(mask, order, rowno, fitter);
1786    setSpectrum(fitter.getResidual(), rowno);
1787  }
1788}
1789
1790STFitEntry Scantable::polyBaseline(const std::vector<bool>& mask, int order, int rowno)
1791{
1792  Fitter fitter = Fitter();
1793  doPolyBaseline(mask, order, rowno, fitter);
1794  setSpectrum(fitter.getResidual(), rowno);
1795  return fitter.getFitEntry();
1796}
1797
1798}
1799//namespace asap
Note: See TracBrowser for help on using the repository browser.