source: trunk/src/Scantable.cpp @ 2290

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

New Development: Yes

JIRA Issue: Yes (CAS-3219/ASAP-247)

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs: sdlist unit test (reference data to be updated)

Put in Release Notes: Yes

Module(s): scantable.summary, sdlist

Description:

Output format of scantable summary changed.
Less use of TableIterator? for speed up scantable.summary/sdlist now lists a scantable
with 348,000 records (NRO 45m w/ 25beams x 13,920scans) in ~30sec (was ~7 min previously).


  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 109.3 KB
Line 
1//
2// C++ Implementation: Scantable
3//
4// Description:
5//
6//
7// Author: Malte Marquarding <asap@atnf.csiro.au>, (C) 2005
8//
9// Copyright: See COPYING file that comes with this distribution
10//
11//
12#include <map>
13
14#include <atnf/PKSIO/SrcType.h>
15
16#include <casa/aips.h>
17#include <casa/iomanip.h>
18#include <casa/iostream.h>
19#include <casa/OS/File.h>
20#include <casa/OS/Path.h>
21#include <casa/Arrays/Array.h>
22#include <casa/Arrays/ArrayAccessor.h>
23#include <casa/Arrays/ArrayLogical.h>
24#include <casa/Arrays/ArrayMath.h>
25#include <casa/Arrays/MaskArrMath.h>
26#include <casa/Arrays/Slice.h>
27#include <casa/Arrays/Vector.h>
28#include <casa/Arrays/VectorSTLIterator.h>
29#include <casa/BasicMath/Math.h>
30#include <casa/BasicSL/Constants.h>
31#include <casa/Containers/RecordField.h>
32#include <casa/Logging/LogIO.h>
33#include <casa/Quanta/MVAngle.h>
34#include <casa/Quanta/MVTime.h>
35#include <casa/Utilities/GenSort.h>
36
37#include <coordinates/Coordinates/CoordinateUtil.h>
38
39// needed to avoid error in .tcc
40#include <measures/Measures/MCDirection.h>
41//
42#include <measures/Measures/MDirection.h>
43#include <measures/Measures/MEpoch.h>
44#include <measures/Measures/MFrequency.h>
45#include <measures/Measures/MeasRef.h>
46#include <measures/Measures/MeasTable.h>
47#include <measures/TableMeasures/ScalarMeasColumn.h>
48#include <measures/TableMeasures/TableMeasDesc.h>
49#include <measures/TableMeasures/TableMeasRefDesc.h>
50#include <measures/TableMeasures/TableMeasValueDesc.h>
51
52#include <tables/Tables/ArrColDesc.h>
53#include <tables/Tables/ExprNode.h>
54#include <tables/Tables/ScaColDesc.h>
55#include <tables/Tables/SetupNewTab.h>
56#include <tables/Tables/TableCopy.h>
57#include <tables/Tables/TableDesc.h>
58#include <tables/Tables/TableIter.h>
59#include <tables/Tables/TableParse.h>
60#include <tables/Tables/TableRecord.h>
61#include <tables/Tables/TableRow.h>
62#include <tables/Tables/TableVector.h>
63
64#include "MathUtils.h"
65#include "STAttr.h"
66#include "STLineFinder.h"
67#include "STPolCircular.h"
68#include "STPolLinear.h"
69#include "STPolStokes.h"
70#include "Scantable.h"
71
72using namespace casa;
73
74namespace asap {
75
76std::map<std::string, STPol::STPolFactory *> Scantable::factories_;
77
78void Scantable::initFactories() {
79  if ( factories_.empty() ) {
80    Scantable::factories_["linear"] = &STPolLinear::myFactory;
81    Scantable::factories_["circular"] = &STPolCircular::myFactory;
82    Scantable::factories_["stokes"] = &STPolStokes::myFactory;
83  }
84}
85
86Scantable::Scantable(Table::TableType ttype) :
87  type_(ttype)
88{
89  initFactories();
90  setupMainTable();
91  freqTable_ = STFrequencies(*this);
92  table_.rwKeywordSet().defineTable("FREQUENCIES", freqTable_.table());
93  weatherTable_ = STWeather(*this);
94  table_.rwKeywordSet().defineTable("WEATHER", weatherTable_.table());
95  focusTable_ = STFocus(*this);
96  table_.rwKeywordSet().defineTable("FOCUS", focusTable_.table());
97  tcalTable_ = STTcal(*this);
98  table_.rwKeywordSet().defineTable("TCAL", tcalTable_.table());
99  moleculeTable_ = STMolecules(*this);
100  table_.rwKeywordSet().defineTable("MOLECULES", moleculeTable_.table());
101  historyTable_ = STHistory(*this);
102  table_.rwKeywordSet().defineTable("HISTORY", historyTable_.table());
103  fitTable_ = STFit(*this);
104  table_.rwKeywordSet().defineTable("FIT", fitTable_.table());
105  table_.tableInfo().setType( "Scantable" ) ;
106  originalTable_ = table_;
107  attach();
108}
109
110Scantable::Scantable(const std::string& name, Table::TableType ttype) :
111  type_(ttype)
112{
113  initFactories();
114
115  Table tab(name, Table::Update);
116  uInt version = tab.keywordSet().asuInt("VERSION");
117  if (version != version_) {
118    if ( version == 2 && version_ == 3 ) {
119      // run asap2to3 command
120      LogIO os( LogOrigin( "Scantable" ) ) ;
121      string command="asap2to3" ;
122      string exec=command+" in="+name ;
123      string outname=name ;
124      if ( name.at(name.length()-1) == '/' )
125        outname = outname.substr( 0, name.length()-1 ) ;
126      outname += ".asap3" ;
127      os << LogIO::WARN
128         << name << " is incompatible data format (Scantable v2)." << endl
129         << "Running " << command << " to create " << outname << ", " << endl 
130         << "which is identical to " << name << " but compatible " << endl
131         << "data format with current software version (Scantable v3)."
132         << LogIO::POST ; 
133      int ret = system( string("which "+command+" > /dev/null 2>&1").c_str() ) ;
134      if ( ret != 0 )
135        throw(AipsError(command+" is not installed")) ;
136      os << LogIO::WARN
137         << "Data will be loaded from " << outname << " instead of "
138         << name << LogIO::POST ;
139      int tmp = system( exec.c_str() ) ;
140      (void) tmp;
141      tab = Table(outname, Table::Update ) ;
142      //os << "tab.tableName()=" << tab.tableName() << LogIO::POST ;
143    }
144    else {
145      throw(AipsError("Unsupported version of ASAP file."));
146    }
147  }
148  if ( type_ == Table::Memory ) {
149    table_ = tab.copyToMemoryTable(generateName());
150  } else {
151    table_ = tab;
152  }
153  table_.tableInfo().setType( "Scantable" ) ;
154
155  attachSubtables();
156  originalTable_ = table_;
157  attach();
158}
159/*
160Scantable::Scantable(const std::string& name, Table::TableType ttype) :
161  type_(ttype)
162{
163  initFactories();
164  Table tab(name, Table::Update);
165  uInt version = tab.keywordSet().asuInt("VERSION");
166  if (version != version_) {
167    throw(AipsError("Unsupported version of ASAP file."));
168  }
169  if ( type_ == Table::Memory ) {
170    table_ = tab.copyToMemoryTable(generateName());
171  } else {
172    table_ = tab;
173  }
174
175  attachSubtables();
176  originalTable_ = table_;
177  attach();
178}
179*/
180
181Scantable::Scantable( const Scantable& other, bool clear ):
182  Logger()
183{
184  // with or without data
185  String newname = String(generateName());
186  type_ = other.table_.tableType();
187  if ( other.table_.tableType() == Table::Memory ) {
188      if ( clear ) {
189        table_ = TableCopy::makeEmptyMemoryTable(newname,
190                                                 other.table_, True);
191      } else
192        table_ = other.table_.copyToMemoryTable(newname);
193  } else {
194      other.table_.deepCopy(newname, Table::New, False,
195                            other.table_.endianFormat(),
196                            Bool(clear));
197      table_ = Table(newname, Table::Update);
198      table_.markForDelete();
199  }
200  table_.tableInfo().setType( "Scantable" ) ;
201  /// @todo reindex SCANNO, recompute nbeam, nif, npol
202  if ( clear ) copySubtables(other);
203  attachSubtables();
204  originalTable_ = table_;
205  attach();
206}
207
208void Scantable::copySubtables(const Scantable& other) {
209  Table t = table_.rwKeywordSet().asTable("FREQUENCIES");
210  TableCopy::copyRows(t, other.freqTable_.table());
211  t = table_.rwKeywordSet().asTable("FOCUS");
212  TableCopy::copyRows(t, other.focusTable_.table());
213  t = table_.rwKeywordSet().asTable("WEATHER");
214  TableCopy::copyRows(t, other.weatherTable_.table());
215  t = table_.rwKeywordSet().asTable("TCAL");
216  TableCopy::copyRows(t, other.tcalTable_.table());
217  t = table_.rwKeywordSet().asTable("MOLECULES");
218  TableCopy::copyRows(t, other.moleculeTable_.table());
219  t = table_.rwKeywordSet().asTable("HISTORY");
220  TableCopy::copyRows(t, other.historyTable_.table());
221  t = table_.rwKeywordSet().asTable("FIT");
222  TableCopy::copyRows(t, other.fitTable_.table());
223}
224
225void Scantable::attachSubtables()
226{
227  freqTable_ = STFrequencies(table_);
228  focusTable_ = STFocus(table_);
229  weatherTable_ = STWeather(table_);
230  tcalTable_ = STTcal(table_);
231  moleculeTable_ = STMolecules(table_);
232  historyTable_ = STHistory(table_);
233  fitTable_ = STFit(table_);
234}
235
236Scantable::~Scantable()
237{
238  //cout << "~Scantable() " << this << endl;
239}
240
241void Scantable::setupMainTable()
242{
243  TableDesc td("", "1", TableDesc::Scratch);
244  td.comment() = "An ASAP Scantable";
245  td.rwKeywordSet().define("VERSION", uInt(version_));
246
247  // n Cycles
248  td.addColumn(ScalarColumnDesc<uInt>("SCANNO"));
249  // new index every nBeam x nIF x nPol
250  td.addColumn(ScalarColumnDesc<uInt>("CYCLENO"));
251
252  td.addColumn(ScalarColumnDesc<uInt>("BEAMNO"));
253  td.addColumn(ScalarColumnDesc<uInt>("IFNO"));
254  // linear, circular, stokes
255  td.rwKeywordSet().define("POLTYPE", String("linear"));
256  td.addColumn(ScalarColumnDesc<uInt>("POLNO"));
257
258  td.addColumn(ScalarColumnDesc<uInt>("FREQ_ID"));
259  td.addColumn(ScalarColumnDesc<uInt>("MOLECULE_ID"));
260
261  ScalarColumnDesc<Int> refbeamnoColumn("REFBEAMNO");
262  refbeamnoColumn.setDefault(Int(-1));
263  td.addColumn(refbeamnoColumn);
264
265  ScalarColumnDesc<uInt> flagrowColumn("FLAGROW");
266  flagrowColumn.setDefault(uInt(0));
267  td.addColumn(flagrowColumn);
268
269  td.addColumn(ScalarColumnDesc<Double>("TIME"));
270  TableMeasRefDesc measRef(MEpoch::UTC); // UTC as default
271  TableMeasValueDesc measVal(td, "TIME");
272  TableMeasDesc<MEpoch> mepochCol(measVal, measRef);
273  mepochCol.write(td);
274
275  td.addColumn(ScalarColumnDesc<Double>("INTERVAL"));
276
277  td.addColumn(ScalarColumnDesc<String>("SRCNAME"));
278  // Type of source (on=0, off=1, other=-1)
279  ScalarColumnDesc<Int> stypeColumn("SRCTYPE");
280  stypeColumn.setDefault(Int(-1));
281  td.addColumn(stypeColumn);
282  td.addColumn(ScalarColumnDesc<String>("FIELDNAME"));
283
284  //The actual Data Vectors
285  td.addColumn(ArrayColumnDesc<Float>("SPECTRA"));
286  td.addColumn(ArrayColumnDesc<uChar>("FLAGTRA"));
287  td.addColumn(ArrayColumnDesc<Float>("TSYS"));
288
289  td.addColumn(ArrayColumnDesc<Double>("DIRECTION",
290                                       IPosition(1,2),
291                                       ColumnDesc::Direct));
292  TableMeasRefDesc mdirRef(MDirection::J2000); // default
293  TableMeasValueDesc tmvdMDir(td, "DIRECTION");
294  // the TableMeasDesc gives the column a type
295  TableMeasDesc<MDirection> mdirCol(tmvdMDir, mdirRef);
296  // a uder set table type e.g. GALCTIC, B1950 ...
297  td.rwKeywordSet().define("DIRECTIONREF", String("J2000"));
298  // writing create the measure column
299  mdirCol.write(td);
300  td.addColumn(ScalarColumnDesc<Float>("AZIMUTH"));
301  td.addColumn(ScalarColumnDesc<Float>("ELEVATION"));
302  td.addColumn(ScalarColumnDesc<Float>("OPACITY"));
303
304  td.addColumn(ScalarColumnDesc<uInt>("TCAL_ID"));
305  ScalarColumnDesc<Int> fitColumn("FIT_ID");
306  fitColumn.setDefault(Int(-1));
307  td.addColumn(fitColumn);
308
309  td.addColumn(ScalarColumnDesc<uInt>("FOCUS_ID"));
310  td.addColumn(ScalarColumnDesc<uInt>("WEATHER_ID"));
311
312  // columns which just get dragged along, as they aren't used in asap
313  td.addColumn(ScalarColumnDesc<Double>("SRCVELOCITY"));
314  td.addColumn(ArrayColumnDesc<Double>("SRCPROPERMOTION"));
315  td.addColumn(ArrayColumnDesc<Double>("SRCDIRECTION"));
316  td.addColumn(ArrayColumnDesc<Double>("SCANRATE"));
317
318  td.rwKeywordSet().define("OBSMODE", String(""));
319
320  // Now create Table SetUp from the description.
321  SetupNewTable aNewTab(generateName(), td, Table::Scratch);
322  table_ = Table(aNewTab, type_, 0);
323  originalTable_ = table_;
324}
325
326void Scantable::attach()
327{
328  timeCol_.attach(table_, "TIME");
329  srcnCol_.attach(table_, "SRCNAME");
330  srctCol_.attach(table_, "SRCTYPE");
331  specCol_.attach(table_, "SPECTRA");
332  flagsCol_.attach(table_, "FLAGTRA");
333  tsysCol_.attach(table_, "TSYS");
334  cycleCol_.attach(table_,"CYCLENO");
335  scanCol_.attach(table_, "SCANNO");
336  beamCol_.attach(table_, "BEAMNO");
337  ifCol_.attach(table_, "IFNO");
338  polCol_.attach(table_, "POLNO");
339  integrCol_.attach(table_, "INTERVAL");
340  azCol_.attach(table_, "AZIMUTH");
341  elCol_.attach(table_, "ELEVATION");
342  dirCol_.attach(table_, "DIRECTION");
343  fldnCol_.attach(table_, "FIELDNAME");
344  rbeamCol_.attach(table_, "REFBEAMNO");
345
346  mweatheridCol_.attach(table_,"WEATHER_ID");
347  mfitidCol_.attach(table_,"FIT_ID");
348  mfreqidCol_.attach(table_, "FREQ_ID");
349  mtcalidCol_.attach(table_, "TCAL_ID");
350  mfocusidCol_.attach(table_, "FOCUS_ID");
351  mmolidCol_.attach(table_, "MOLECULE_ID");
352
353  //Add auxiliary column for row-based flagging (CAS-1433 Wataru Kawasaki)
354  attachAuxColumnDef(flagrowCol_, "FLAGROW", 0);
355
356}
357
358template<class T, class T2>
359void Scantable::attachAuxColumnDef(ScalarColumn<T>& col,
360                                   const String& colName,
361                                   const T2& defValue)
362{
363  try {
364    col.attach(table_, colName);
365  } catch (TableError& err) {
366    String errMesg = err.getMesg();
367    if (errMesg == "Table column " + colName + " is unknown") {
368      table_.addColumn(ScalarColumnDesc<T>(colName));
369      col.attach(table_, colName);
370      col.fillColumn(static_cast<T>(defValue));
371    } else {
372      throw;
373    }
374  } catch (...) {
375    throw;
376  }
377}
378
379template<class T, class T2>
380void Scantable::attachAuxColumnDef(ArrayColumn<T>& col,
381                                   const String& colName,
382                                   const Array<T2>& defValue)
383{
384  try {
385    col.attach(table_, colName);
386  } catch (TableError& err) {
387    String errMesg = err.getMesg();
388    if (errMesg == "Table column " + colName + " is unknown") {
389      table_.addColumn(ArrayColumnDesc<T>(colName));
390      col.attach(table_, colName);
391
392      int size = 0;
393      ArrayIterator<T2>& it = defValue.begin();
394      while (it != defValue.end()) {
395        ++size;
396        ++it;
397      }
398      IPosition ip(1, size);
399      Array<T>& arr(ip);
400      for (int i = 0; i < size; ++i)
401        arr[i] = static_cast<T>(defValue[i]);
402
403      col.fillColumn(arr);
404    } else {
405      throw;
406    }
407  } catch (...) {
408    throw;
409  }
410}
411
412void Scantable::setHeader(const STHeader& sdh)
413{
414  table_.rwKeywordSet().define("nIF", sdh.nif);
415  table_.rwKeywordSet().define("nBeam", sdh.nbeam);
416  table_.rwKeywordSet().define("nPol", sdh.npol);
417  table_.rwKeywordSet().define("nChan", sdh.nchan);
418  table_.rwKeywordSet().define("Observer", sdh.observer);
419  table_.rwKeywordSet().define("Project", sdh.project);
420  table_.rwKeywordSet().define("Obstype", sdh.obstype);
421  table_.rwKeywordSet().define("AntennaName", sdh.antennaname);
422  table_.rwKeywordSet().define("AntennaPosition", sdh.antennaposition);
423  table_.rwKeywordSet().define("Equinox", sdh.equinox);
424  table_.rwKeywordSet().define("FreqRefFrame", sdh.freqref);
425  table_.rwKeywordSet().define("FreqRefVal", sdh.reffreq);
426  table_.rwKeywordSet().define("Bandwidth", sdh.bandwidth);
427  table_.rwKeywordSet().define("UTC", sdh.utc);
428  table_.rwKeywordSet().define("FluxUnit", sdh.fluxunit);
429  table_.rwKeywordSet().define("Epoch", sdh.epoch);
430  table_.rwKeywordSet().define("POLTYPE", sdh.poltype);
431}
432
433STHeader Scantable::getHeader() const
434{
435  STHeader sdh;
436  table_.keywordSet().get("nBeam",sdh.nbeam);
437  table_.keywordSet().get("nIF",sdh.nif);
438  table_.keywordSet().get("nPol",sdh.npol);
439  table_.keywordSet().get("nChan",sdh.nchan);
440  table_.keywordSet().get("Observer", sdh.observer);
441  table_.keywordSet().get("Project", sdh.project);
442  table_.keywordSet().get("Obstype", sdh.obstype);
443  table_.keywordSet().get("AntennaName", sdh.antennaname);
444  table_.keywordSet().get("AntennaPosition", sdh.antennaposition);
445  table_.keywordSet().get("Equinox", sdh.equinox);
446  table_.keywordSet().get("FreqRefFrame", sdh.freqref);
447  table_.keywordSet().get("FreqRefVal", sdh.reffreq);
448  table_.keywordSet().get("Bandwidth", sdh.bandwidth);
449  table_.keywordSet().get("UTC", sdh.utc);
450  table_.keywordSet().get("FluxUnit", sdh.fluxunit);
451  table_.keywordSet().get("Epoch", sdh.epoch);
452  table_.keywordSet().get("POLTYPE", sdh.poltype);
453  return sdh;
454}
455
456void Scantable::setSourceType( int stype )
457{
458  if ( stype < 0 || stype > 1 )
459    throw(AipsError("Illegal sourcetype."));
460  TableVector<Int> tabvec(table_, "SRCTYPE");
461  tabvec = Int(stype);
462}
463
464bool Scantable::conformant( const Scantable& other )
465{
466  return this->getHeader().conformant(other.getHeader());
467}
468
469
470
471std::string Scantable::formatSec(Double x) const
472{
473  Double xcop = x;
474  MVTime mvt(xcop/24./3600.);  // make days
475
476  if (x < 59.95)
477    return  String("      ") + mvt.string(MVTime::TIME_CLEAN_NO_HM, 7)+"s";
478  else if (x < 3599.95)
479    return String("   ") + mvt.string(MVTime::TIME_CLEAN_NO_H,7)+" ";
480  else {
481    ostringstream oss;
482    oss << setw(2) << std::right << setprecision(1) << mvt.hour();
483    oss << ":" << mvt.string(MVTime::TIME_CLEAN_NO_H,7) << " ";
484    return String(oss);
485  }
486};
487
488std::string Scantable::formatDirection(const MDirection& md) const
489{
490  Vector<Double> t = md.getAngle(Unit(String("rad"))).getValue();
491  Int prec = 7;
492
493  MVAngle mvLon(t[0]);
494  String sLon = mvLon.string(MVAngle::TIME,prec);
495  uInt tp = md.getRef().getType();
496  if (tp == MDirection::GALACTIC ||
497      tp == MDirection::SUPERGAL ) {
498    sLon = mvLon(0.0).string(MVAngle::ANGLE_CLEAN,prec);
499  }
500  MVAngle mvLat(t[1]);
501  String sLat = mvLat.string(MVAngle::ANGLE+MVAngle::DIG2,prec);
502  return sLon + String(" ") + sLat;
503}
504
505
506std::string Scantable::getFluxUnit() const
507{
508  return table_.keywordSet().asString("FluxUnit");
509}
510
511void Scantable::setFluxUnit(const std::string& unit)
512{
513  String tmp(unit);
514  Unit tU(tmp);
515  if (tU==Unit("K") || tU==Unit("Jy")) {
516     table_.rwKeywordSet().define(String("FluxUnit"), tmp);
517  } else {
518     throw AipsError("Illegal unit - must be compatible with Jy or K");
519  }
520}
521
522void Scantable::setInstrument(const std::string& name)
523{
524  bool throwIt = true;
525  // create an Instrument to see if this is valid
526  STAttr::convertInstrument(name, throwIt);
527  String nameU(name);
528  nameU.upcase();
529  table_.rwKeywordSet().define(String("AntennaName"), nameU);
530}
531
532void Scantable::setFeedType(const std::string& feedtype)
533{
534  if ( Scantable::factories_.find(feedtype) ==  Scantable::factories_.end() ) {
535    std::string msg = "Illegal feed type "+ feedtype;
536    throw(casa::AipsError(msg));
537  }
538  table_.rwKeywordSet().define(String("POLTYPE"), feedtype);
539}
540
541MPosition Scantable::getAntennaPosition() const
542{
543  Vector<Double> antpos;
544  table_.keywordSet().get("AntennaPosition", antpos);
545  MVPosition mvpos(antpos(0),antpos(1),antpos(2));
546  return MPosition(mvpos);
547}
548
549void Scantable::makePersistent(const std::string& filename)
550{
551  String inname(filename);
552  Path path(inname);
553  /// @todo reindex SCANNO, recompute nbeam, nif, npol
554  inname = path.expandedName();
555  // 2011/03/04 TN
556  // We can comment out this workaround since the essential bug is
557  // fixed in casacore (r20889 in google code).
558  table_.deepCopy(inname, Table::New);
559//   // WORKAROUND !!! for Table bug
560//   // Remove when fixed in casacore
561//   if ( table_.tableType() == Table::Memory  && !selector_.empty() ) {
562//     Table tab = table_.copyToMemoryTable(generateName());
563//     tab.deepCopy(inname, Table::New);
564//     tab.markForDelete();
565//
566//   } else {
567//     table_.deepCopy(inname, Table::New);
568//   }
569}
570
571int Scantable::nbeam( int scanno ) const
572{
573  if ( scanno < 0 ) {
574    Int n;
575    table_.keywordSet().get("nBeam",n);
576    return int(n);
577  } else {
578    // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
579    Table t = table_(table_.col("SCANNO") == scanno);
580    ROTableRow row(t);
581    const TableRecord& rec = row.get(0);
582    Table subt = t( t.col("IFNO") == Int(rec.asuInt("IFNO"))
583                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
584                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
585    ROTableVector<uInt> v(subt, "BEAMNO");
586    return int(v.nelements());
587  }
588  return 0;
589}
590
591int Scantable::nif( int scanno ) const
592{
593  if ( scanno < 0 ) {
594    Int n;
595    table_.keywordSet().get("nIF",n);
596    return int(n);
597  } else {
598    // take the first POLNO,BEAMNO,CYCLENO as nbeam shouldn't vary with these
599    Table t = table_(table_.col("SCANNO") == scanno);
600    ROTableRow row(t);
601    const TableRecord& rec = row.get(0);
602    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
603                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
604                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
605    if ( subt.nrow() == 0 ) return 0;
606    ROTableVector<uInt> v(subt, "IFNO");
607    return int(v.nelements());
608  }
609  return 0;
610}
611
612int Scantable::npol( int scanno ) const
613{
614  if ( scanno < 0 ) {
615    Int n;
616    table_.keywordSet().get("nPol",n);
617    return n;
618  } else {
619    // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
620    Table t = table_(table_.col("SCANNO") == scanno);
621    ROTableRow row(t);
622    const TableRecord& rec = row.get(0);
623    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
624                    && t.col("IFNO") == Int(rec.asuInt("IFNO"))
625                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
626    if ( subt.nrow() == 0 ) return 0;
627    ROTableVector<uInt> v(subt, "POLNO");
628    return int(v.nelements());
629  }
630  return 0;
631}
632
633int Scantable::ncycle( int scanno ) const
634{
635  if ( scanno < 0 ) {
636    Block<String> cols(2);
637    cols[0] = "SCANNO";
638    cols[1] = "CYCLENO";
639    TableIterator it(table_, cols);
640    int n = 0;
641    while ( !it.pastEnd() ) {
642      ++n;
643      ++it;
644    }
645    return n;
646  } else {
647    Table t = table_(table_.col("SCANNO") == scanno);
648    ROTableRow row(t);
649    const TableRecord& rec = row.get(0);
650    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
651                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
652                    && t.col("IFNO") == Int(rec.asuInt("IFNO")) );
653    if ( subt.nrow() == 0 ) return 0;
654    return int(subt.nrow());
655  }
656  return 0;
657}
658
659
660int Scantable::nrow( int scanno ) const
661{
662  return int(table_.nrow());
663}
664
665int Scantable::nchan( int ifno ) const
666{
667  if ( ifno < 0 ) {
668    Int n;
669    table_.keywordSet().get("nChan",n);
670    return int(n);
671  } else {
672    // take the first SCANNO,POLNO,BEAMNO,CYCLENO as nbeam shouldn't
673    // vary with these
674    Table t = table_(table_.col("IFNO") == ifno, 1);
675    if ( t.nrow() == 0 ) return 0;
676    ROArrayColumn<Float> v(t, "SPECTRA");
677    return v.shape(0)(0);
678  }
679  return 0;
680}
681
682int Scantable::nscan() const {
683  Vector<uInt> scannos(scanCol_.getColumn());
684  uInt nout = genSort( scannos, Sort::Ascending,
685                       Sort::QuickSort|Sort::NoDuplicates );
686  return int(nout);
687}
688
689int Scantable::getChannels(int whichrow) const
690{
691  return specCol_.shape(whichrow)(0);
692}
693
694int Scantable::getBeam(int whichrow) const
695{
696  return beamCol_(whichrow);
697}
698
699std::vector<uint> Scantable::getNumbers(const ScalarColumn<uInt>& col) const
700{
701  Vector<uInt> nos(col.getColumn());
702  uInt n = genSort( nos, Sort::Ascending, Sort::QuickSort|Sort::NoDuplicates );
703  nos.resize(n, True);
704  std::vector<uint> stlout;
705  nos.tovector(stlout);
706  return stlout;
707}
708
709int Scantable::getIF(int whichrow) const
710{
711  return ifCol_(whichrow);
712}
713
714int Scantable::getPol(int whichrow) const
715{
716  return polCol_(whichrow);
717}
718
719std::string Scantable::formatTime(const MEpoch& me, bool showdate) const
720{
721  return formatTime(me, showdate, 0);
722}
723
724std::string Scantable::formatTime(const MEpoch& me, bool showdate, uInt prec) const
725{
726  MVTime mvt(me.getValue());
727  if (showdate)
728    //mvt.setFormat(MVTime::YMD);
729    mvt.setFormat(MVTime::YMD, prec);
730  else
731    //mvt.setFormat(MVTime::TIME);
732    mvt.setFormat(MVTime::TIME, prec);
733  ostringstream oss;
734  oss << mvt;
735  return String(oss);
736}
737
738void Scantable::calculateAZEL()
739{
740  MPosition mp = getAntennaPosition();
741  MEpoch::ROScalarColumn timeCol(table_, "TIME");
742  ostringstream oss;
743  oss << "Computed azimuth/elevation using " << endl
744      << mp << endl;
745  for (Int i=0; i<nrow(); ++i) {
746    MEpoch me = timeCol(i);
747    MDirection md = getDirection(i);
748    oss  << " Time: " << formatTime(me,False) << " Direction: " << formatDirection(md)
749         << endl << "     => ";
750    MeasFrame frame(mp, me);
751    Vector<Double> azel =
752        MDirection::Convert(md, MDirection::Ref(MDirection::AZEL,
753                                                frame)
754                            )().getAngle("rad").getValue();
755    azCol_.put(i,Float(azel[0]));
756    elCol_.put(i,Float(azel[1]));
757    oss << "azel: " << azel[0]/C::pi*180.0 << " "
758        << azel[1]/C::pi*180.0 << " (deg)" << endl;
759  }
760  pushLog(String(oss));
761}
762
763void Scantable::clip(const Float uthres, const Float dthres, bool clipoutside, bool unflag)
764{
765  for (uInt i=0; i<table_.nrow(); ++i) {
766    Vector<uChar> flgs = flagsCol_(i);
767    srchChannelsToClip(i, uthres, dthres, clipoutside, unflag, flgs);
768    flagsCol_.put(i, flgs);
769  }
770}
771
772std::vector<bool> Scantable::getClipMask(int whichrow, const Float uthres, const Float dthres, bool clipoutside, bool unflag)
773{
774  Vector<uChar> flags;
775  flagsCol_.get(uInt(whichrow), flags);
776  srchChannelsToClip(uInt(whichrow), uthres, dthres, clipoutside, unflag, flags);
777  Vector<Bool> bflag(flags.shape());
778  convertArray(bflag, flags);
779  //bflag = !bflag;
780
781  std::vector<bool> mask;
782  bflag.tovector(mask);
783  return mask;
784}
785
786void Scantable::srchChannelsToClip(uInt whichrow, const Float uthres, const Float dthres, bool clipoutside, bool unflag,
787                                   Vector<uChar> flgs)
788{
789    Vector<Float> spcs = specCol_(whichrow);
790    uInt nchannel = nchan();
791    if (spcs.nelements() != nchannel) {
792      throw(AipsError("Data has incorrect number of channels"));
793    }
794    uChar userflag = 1 << 7;
795    if (unflag) {
796      userflag = 0 << 7;
797    }
798    if (clipoutside) {
799      for (uInt j = 0; j < nchannel; ++j) {
800        Float spc = spcs(j);
801        if ((spc >= uthres) || (spc <= dthres)) {
802          flgs(j) = userflag;
803        }
804      }
805    } else {
806      for (uInt j = 0; j < nchannel; ++j) {
807        Float spc = spcs(j);
808        if ((spc < uthres) && (spc > dthres)) {
809          flgs(j) = userflag;
810        }
811      }
812    }
813}
814
815
816void Scantable::flag( int whichrow, const std::vector<bool>& msk, bool unflag ) {
817  std::vector<bool>::const_iterator it;
818  uInt ntrue = 0;
819  if (whichrow >= int(table_.nrow()) ) {
820    throw(AipsError("Invalid row number"));
821  }
822  for (it = msk.begin(); it != msk.end(); ++it) {
823    if ( *it ) {
824      ntrue++;
825    }
826  }
827  //if ( selector_.empty()  && (msk.size() == 0 || msk.size() == ntrue) )
828  if ( whichrow == -1 && !unflag && selector_.empty() && (msk.size() == 0 || msk.size() == ntrue) )
829    throw(AipsError("Trying to flag whole scantable."));
830  uChar userflag = 1 << 7;
831  if ( unflag ) {
832    userflag = 0 << 7;
833  }
834  if (whichrow > -1 ) {
835    applyChanFlag(uInt(whichrow), msk, userflag);
836  } else {
837    for ( uInt i=0; i<table_.nrow(); ++i) {
838      applyChanFlag(i, msk, userflag);
839    }
840  }
841}
842
843void Scantable::applyChanFlag( uInt whichrow, const std::vector<bool>& msk, uChar flagval )
844{
845  if (whichrow >= table_.nrow() ) {
846    throw( casa::indexError<int>( whichrow, "asap::Scantable::applyChanFlag: Invalid row number" ) );
847  }
848  Vector<uChar> flgs = flagsCol_(whichrow);
849  if ( msk.size() == 0 ) {
850    flgs = flagval;
851    flagsCol_.put(whichrow, flgs);
852    return;
853  }
854  if ( int(msk.size()) != nchan() ) {
855    throw(AipsError("Mask has incorrect number of channels."));
856  }
857  if ( flgs.nelements() != msk.size() ) {
858    throw(AipsError("Mask has incorrect number of channels."
859                    " Probably varying with IF. Please flag per IF"));
860  }
861  std::vector<bool>::const_iterator it;
862  uInt j = 0;
863  for (it = msk.begin(); it != msk.end(); ++it) {
864    if ( *it ) {
865      flgs(j) = flagval;
866    }
867    ++j;
868  }
869  flagsCol_.put(whichrow, flgs);
870}
871
872void Scantable::flagRow(const std::vector<uInt>& rows, bool unflag)
873{
874  if ( selector_.empty() && (rows.size() == table_.nrow()) )
875    throw(AipsError("Trying to flag whole scantable."));
876
877  uInt rowflag = (unflag ? 0 : 1);
878  std::vector<uInt>::const_iterator it;
879  for (it = rows.begin(); it != rows.end(); ++it)
880    flagrowCol_.put(*it, rowflag);
881}
882
883std::vector<bool> Scantable::getMask(int whichrow) const
884{
885  Vector<uChar> flags;
886  flagsCol_.get(uInt(whichrow), flags);
887  Vector<Bool> bflag(flags.shape());
888  convertArray(bflag, flags);
889  bflag = !bflag;
890  std::vector<bool> mask;
891  bflag.tovector(mask);
892  return mask;
893}
894
895std::vector<float> Scantable::getSpectrum( int whichrow,
896                                           const std::string& poltype ) const
897{
898  String ptype = poltype;
899  if (poltype == "" ) ptype = getPolType();
900  if ( whichrow  < 0 || whichrow >= nrow() )
901    throw(AipsError("Illegal row number."));
902  std::vector<float> out;
903  Vector<Float> arr;
904  uInt requestedpol = polCol_(whichrow);
905  String basetype = getPolType();
906  if ( ptype == basetype ) {
907    specCol_.get(whichrow, arr);
908  } else {
909    CountedPtr<STPol> stpol(STPol::getPolClass(Scantable::factories_,
910                                               basetype));
911    uInt row = uInt(whichrow);
912    stpol->setSpectra(getPolMatrix(row));
913    Float fang,fhand;
914    fang = focusTable_.getTotalAngle(mfocusidCol_(row));
915    fhand = focusTable_.getFeedHand(mfocusidCol_(row));
916    stpol->setPhaseCorrections(fang, fhand);
917    arr = stpol->getSpectrum(requestedpol, ptype);
918  }
919  if ( arr.nelements() == 0 )
920    pushLog("Not enough polarisations present to do the conversion.");
921  arr.tovector(out);
922  return out;
923}
924
925void Scantable::setSpectrum( const std::vector<float>& spec,
926                                   int whichrow )
927{
928  Vector<Float> spectrum(spec);
929  Vector<Float> arr;
930  specCol_.get(whichrow, arr);
931  if ( spectrum.nelements() != arr.nelements() )
932    throw AipsError("The spectrum has incorrect number of channels.");
933  specCol_.put(whichrow, spectrum);
934}
935
936
937String Scantable::generateName()
938{
939  return (File::newUniqueName("./","temp")).baseName();
940}
941
942const casa::Table& Scantable::table( ) const
943{
944  return table_;
945}
946
947casa::Table& Scantable::table( )
948{
949  return table_;
950}
951
952std::string Scantable::getPolType() const
953{
954  return table_.keywordSet().asString("POLTYPE");
955}
956
957void Scantable::unsetSelection()
958{
959  table_ = originalTable_;
960  attach();
961  selector_.reset();
962}
963
964void Scantable::setSelection( const STSelector& selection )
965{
966  Table tab = const_cast<STSelector&>(selection).apply(originalTable_);
967  if ( tab.nrow() == 0 ) {
968    throw(AipsError("Selection contains no data. Not applying it."));
969  }
970  table_ = tab;
971  attach();
972//   tab.rwKeywordSet().define("nBeam",(Int)(getBeamNos().size())) ;
973//   vector<uint> selectedIFs = getIFNos() ;
974//   Int newnIF = selectedIFs.size() ;
975//   tab.rwKeywordSet().define("nIF",newnIF) ;
976//   if ( newnIF != 0 ) {
977//     Int newnChan = 0 ;
978//     for ( Int i = 0 ; i < newnIF ; i++ ) {
979//       Int nChan = nchan( selectedIFs[i] ) ;
980//       if ( newnChan > nChan )
981//         newnChan = nChan ;
982//     }
983//     tab.rwKeywordSet().define("nChan",newnChan) ;
984//   }
985//   tab.rwKeywordSet().define("nPol",(Int)(getPolNos().size())) ;
986  selector_ = selection;
987}
988
989
990std::string Scantable::headerSummary()
991{
992  // Format header info
993//   STHeader sdh;
994//   sdh = getHeader();
995//   sdh.print();
996  ostringstream oss;
997  oss.flags(std::ios_base::left);
998  String tmp;
999  // Project
1000  table_.keywordSet().get("Project", tmp);
1001  oss << setw(15) << "Project:" << tmp << endl;
1002  // Observation date
1003  oss << setw(15) << "Obs Date:" << getTime(-1,true) << endl;
1004  // Observer
1005  oss << setw(15) << "Observer:"
1006      << table_.keywordSet().asString("Observer") << endl;
1007  // Antenna Name
1008  table_.keywordSet().get("AntennaName", tmp);
1009  oss << setw(15) << "Antenna Name:" << tmp << endl;
1010  // Obs type
1011  table_.keywordSet().get("Obstype", tmp);
1012  // Records (nrow)
1013  oss << setw(15) << "Data Records:" << table_.nrow() << " rows" << endl;
1014  oss << setw(15) << "Obs. Type:" << tmp << endl;
1015  // Beams, IFs, Polarizations, and Channels
1016  oss << setw(15) << "Beams:" << setw(4) << nbeam() << endl
1017      << setw(15) << "IFs:" << setw(4) << nif() << endl
1018      << setw(15) << "Polarisations:" << setw(4) << npol()
1019      << "(" << getPolType() << ")" << endl
1020      << setw(15) << "Channels:" << nchan() << endl;
1021  // Flux unit
1022  table_.keywordSet().get("FluxUnit", tmp);
1023  oss << setw(15) << "Flux Unit:" << tmp << endl;
1024  // Abscissa Unit
1025  oss << setw(15) << "Abscissa:" << getAbcissaLabel(0) << endl;
1026  // Selection
1027  oss << selector_.print() << endl;
1028
1029  return String(oss);
1030}
1031
1032void Scantable::summary( const std::string& filename )
1033{
1034  ostringstream oss;
1035  ofstream ofs;
1036  LogIO ols(LogOrigin("Scantable", "summary", WHERE));
1037
1038  if (filename != "")
1039    ofs.open( filename.c_str(),  ios::out );
1040
1041  oss << endl;
1042  oss << asap::SEPERATOR << endl;
1043  oss << " Scan Table Summary" << endl;
1044  oss << asap::SEPERATOR << endl;
1045
1046  // Format header info
1047  oss << headerSummary();
1048  oss << endl;
1049
1050  if (table_.nrow() <= 0){
1051    oss << asap::SEPERATOR << endl;
1052    oss << "The MAIN table is empty: there are no data!!!" << endl;
1053    oss << asap::SEPERATOR << endl;
1054
1055    ols << String(oss) << LogIO::POST;
1056    if (ofs) {
1057      ofs << String(oss) << flush;
1058      ofs.close();
1059    }
1060    return;
1061  }
1062
1063
1064
1065  // main table
1066  String dirtype = "Position ("
1067                  + getDirectionRefString()
1068                  + ")";
1069  oss.flags(std::ios_base::left);
1070  oss << setw(5) << "Scan"
1071      << setw(15) << "Source"
1072      << setw(35) << "Time range"
1073      << setw(2) << "" << setw(7) << "Int[s]"
1074      << setw(7) << "Record"
1075      << setw(8) << "SrcType"
1076      << setw(8) << "FreqIDs"
1077      << setw(7) << "MolIDs" << endl;
1078  oss << setw(7)<< "" << setw(6) << "Beam"
1079      << setw(23) << dirtype << endl;
1080
1081  oss << asap::SEPERATOR << endl;
1082
1083  // Flush summary and clear up the string
1084  ols << String(oss) << LogIO::POST;
1085  if (ofs) ofs << String(oss) << flush;
1086  oss.str("");
1087  oss.clear();
1088
1089
1090  // Get Freq_ID map
1091  ROScalarColumn<uInt> ftabIds(frequencies().table(), "ID");
1092  Int nfid = ftabIds.nrow();
1093  if (nfid <= 0){
1094    oss << "FREQUENCIES subtable is empty: there are no data!!!" << endl;
1095    oss << asap::SEPERATOR << endl;
1096
1097    ols << String(oss) << LogIO::POST;
1098    if (ofs) {
1099      ofs << String(oss) << flush;
1100      ofs.close();
1101    }
1102    return;
1103  }
1104  // Storages of overall IFNO, POLNO, and nchan per FREQ_ID
1105  // the orders are identical to ID in FREQ subtable
1106  Block< Vector<uInt> > ifNos(nfid), polNos(nfid);
1107  Vector<Int> fIdchans(nfid,-1);
1108  map<uInt, Int> fidMap;  // (FREQ_ID, row # in FREQ subtable) pair
1109  for (Int i=0; i < nfid; i++){
1110   // fidMap[freqId] returns row number in FREQ subtable
1111   fidMap.insert(pair<uInt, Int>(ftabIds(i),i));
1112   ifNos[i] = Vector<uInt>();
1113   polNos[i] = Vector<uInt>();
1114  }
1115
1116  TableIterator iter(table_, "SCANNO");
1117
1118  // Vars for keeping track of time, freqids, molIds in a SCANNO
1119  Vector<uInt> freqids;
1120  Vector<uInt> molids;
1121  Vector<uInt> beamids(1,0);
1122  Vector<MDirection> beamDirs;
1123  Vector<Int> stypeids(1,0);
1124  Vector<String> stypestrs;
1125  Int nfreq(1);
1126  Int nmol(1);
1127  uInt nbeam(1);
1128  uInt nstype(1);
1129
1130  Double btime(0.0), etime(0.0);
1131  Double meanIntTim(0.0);
1132
1133  uInt currFreqId(0), ftabRow(0);
1134  Int iflen(0), pollen(0);
1135
1136  while (!iter.pastEnd()) {
1137    Table subt = iter.table();
1138    uInt snrow = subt.nrow();
1139    ROTableRow row(subt);
1140    const TableRecord& rec = row.get(0);
1141
1142    // relevant columns
1143    ROScalarColumn<Double> mjdCol(subt,"TIME");
1144    ROScalarColumn<Double> intervalCol(subt,"INTERVAL");
1145    MDirection::ROScalarColumn dirCol(subt,"DIRECTION");
1146
1147    ScalarColumn<uInt> freqIdCol(subt,"FREQ_ID");
1148    ScalarColumn<uInt> molIdCol(subt,"MOLECULE_ID");
1149    ROScalarColumn<uInt> beamCol(subt,"BEAMNO");
1150    ROScalarColumn<Int> stypeCol(subt,"SRCTYPE");
1151
1152    ROScalarColumn<uInt> ifNoCol(subt,"IFNO");
1153    ROScalarColumn<uInt> polNoCol(subt,"POLNO");
1154
1155
1156    // Times
1157    meanIntTim = sum(intervalCol.getColumn()) / (double) snrow;
1158    minMax(btime, etime, mjdCol.getColumn());
1159    etime += meanIntTim/C::day;
1160
1161    // MOLECULE_ID and FREQ_ID
1162    molids = getNumbers(molIdCol);
1163    molids.shape(nmol);
1164
1165    freqids = getNumbers(freqIdCol);
1166    freqids.shape(nfreq);
1167
1168    // Add first beamid, and srcNames
1169    beamids.resize(1,False);
1170    beamDirs.resize(1,False);
1171    beamids(0)=beamCol(0);
1172    beamDirs(0)=dirCol(0);
1173    nbeam = 1;
1174
1175    stypeids.resize(1,False);
1176    stypeids(0)=stypeCol(0);
1177    nstype = 1;
1178
1179    // Global listings of nchan/IFNO/POLNO per FREQ_ID
1180    currFreqId=freqIdCol(0);
1181    ftabRow = fidMap[currFreqId];
1182    // Assumes an identical number of channels per FREQ_ID
1183    if (fIdchans(ftabRow) < 0 ) {
1184      RORecordFieldPtr< Array<Float> > spec(rec, "SPECTRA");
1185      fIdchans(ftabRow)=(*spec).shape()(0);
1186    }
1187    // Should keep ifNos and polNos form the previous SCANNO
1188    if ( !anyEQ(ifNos[ftabRow],ifNoCol(0)) ) {
1189      ifNos[ftabRow].shape(iflen);
1190      iflen++;
1191      ifNos[ftabRow].resize(iflen,True);
1192      ifNos[ftabRow](iflen-1) = ifNoCol(0);
1193    }
1194    if ( !anyEQ(polNos[ftabRow],polNoCol(0)) ) {
1195      polNos[ftabRow].shape(pollen);
1196      pollen++;
1197      polNos[ftabRow].resize(pollen,True);
1198      polNos[ftabRow](pollen-1) = polNoCol(0);
1199    }
1200
1201    for (uInt i=1; i < snrow; i++){
1202      // Need to list BEAMNO and DIRECTION in the same order
1203      if ( !anyEQ(beamids,beamCol(i)) ) {
1204        nbeam++;
1205        beamids.resize(nbeam,True);
1206        beamids(nbeam-1)=beamCol(i);
1207        beamDirs.resize(nbeam,True);
1208        beamDirs(nbeam-1)=dirCol(i);
1209      }
1210
1211      // SRCTYPE is Int (getNumber takes only uInt)
1212      if ( !anyEQ(stypeids,stypeCol(i)) ) {
1213        nstype++;
1214        stypeids.resize(nstype,True);
1215        stypeids(nstype-1)=stypeCol(i);
1216      }
1217
1218      // Global listings of nchan/IFNO/POLNO per FREQ_ID
1219      currFreqId=freqIdCol(i);
1220      ftabRow = fidMap[currFreqId];
1221      if (fIdchans(ftabRow) < 0 ) {
1222        const TableRecord& rec = row.get(i);
1223        RORecordFieldPtr< Array<Float> > spec(rec, "SPECTRA");
1224        fIdchans(ftabRow) = (*spec).shape()(0);
1225      }
1226      if ( !anyEQ(ifNos[ftabRow],ifNoCol(i)) ) {
1227        ifNos[ftabRow].shape(iflen);
1228        iflen++;
1229        ifNos[ftabRow].resize(iflen,True);
1230        ifNos[ftabRow](iflen-1) = ifNoCol(i);
1231      }
1232      if ( !anyEQ(polNos[ftabRow],polNoCol(i)) ) {
1233        polNos[ftabRow].shape(pollen);
1234        pollen++;
1235        polNos[ftabRow].resize(pollen,True);
1236        polNos[ftabRow](pollen-1) = polNoCol(i);
1237      }
1238    } // end of row iteration
1239
1240    stypestrs.resize(nstype,False);
1241    for (uInt j=0; j < nstype; j++)
1242      stypestrs(j) = SrcType::getName(stypeids(j));
1243
1244    // Format Scan summary
1245    oss << setw(4) << std::right << rec.asuInt("SCANNO")
1246        << std::left << setw(1) << ""
1247        << setw(15) << rec.asString("SRCNAME")
1248        << setw(21) << MVTime(btime).string(MVTime::YMD,7)
1249        << setw(3) << " - " << MVTime(etime).string(MVTime::TIME,7)
1250        << setw(3) << "" << setw(6) << meanIntTim << setw(1) << ""
1251        << std::right << setw(5) << snrow << setw(2) << ""
1252        << std::left << stypestrs << setw(1) << ""
1253        << freqids << setw(1) << ""
1254        << molids  << endl;
1255    // Format Beam summary
1256    for (uInt j=0; j < nbeam; j++) {
1257      oss << setw(7) << "" << setw(6) << beamids(j) << setw(1) << ""
1258          << formatDirection(beamDirs(j)) << endl;
1259    }
1260    // Flush summary every scan and clear up the string
1261    ols << String(oss) << LogIO::POST;
1262    if (ofs) ofs << String(oss) << flush;
1263    oss.str("");
1264    oss.clear();
1265
1266    ++iter;
1267  } // end of scan iteration
1268  oss << asap::SEPERATOR << endl;
1269 
1270  // List FRECUENCIES Table (using STFrequencies.print may be slow)
1271  oss << "FREQUENCIES: " << nfreq << endl;
1272  oss << std::right << setw(5) << "ID" << setw(2) << ""
1273      << std::left  << setw(5) << "IFNO" << setw(2) << ""
1274      << setw(8) << "Frame"
1275      << setw(16) << "RefVal"
1276      << setw(7) << "RefPix"
1277      << setw(15) << "Increment"
1278      << setw(9) << "Channels"
1279      << setw(6) << "POLNOs" << endl;
1280  Int tmplen;
1281  for (Int i=0; i < nfid; i++){
1282    // List row=i of FREQUENCIES subtable
1283    ifNos[i].shape(tmplen);
1284    if (tmplen == 1) {
1285      oss << std::right << setw(5) << ftabIds(i) << setw(2) << ""
1286          << setw(3) << ifNos[i](0) << setw(1) << ""
1287          << std::left << setw(46) << frequencies().print(ftabIds(i))
1288          << setw(2) << ""
1289          << std::right << setw(8) << fIdchans[i] << setw(2) << ""
1290          << std::left << polNos[i] << endl;
1291    } else if (tmplen > 0 ) {
1292      // You shouldn't come here
1293      oss << std::left
1294          << "Multiple IFNOs in FREQ_ID = " << ftabIds(i)
1295          << " !!!" << endl;
1296    }
1297  }
1298  oss << asap::SEPERATOR << endl;
1299
1300  // List MOLECULES Table (currently lists all rows)
1301  oss << "MOLECULES: " << endl;
1302  if (molecules().nrow() <= 0) {
1303    oss << "   MOLECULES subtable is empty: there are no data" << endl;
1304  } else {
1305    ROTableRow row(molecules().table());
1306    oss << std::right << setw(5) << "ID"
1307        << std::left << setw(3) << ""
1308        << setw(18) << "RestFreq"
1309        << setw(15) << "Name" << endl;
1310    for (Int i=0; i < molecules().nrow(); i++){
1311      const TableRecord& rec=row.get(i);
1312      oss << std::right << setw(5) << rec.asuInt("ID")
1313          << std::left << setw(3) << ""
1314          << rec.asArrayDouble("RESTFREQUENCY") << setw(1) << ""
1315          << rec.asArrayString("NAME") << endl;
1316    }
1317  }
1318  oss << asap::SEPERATOR << endl;
1319  ols << String(oss) << LogIO::POST;
1320  if (ofs) {
1321    ofs << String(oss) << flush;
1322    ofs.close();
1323  }
1324  //  return String(oss);
1325}
1326
1327
1328std::string Scantable::oldheaderSummary()
1329{
1330  // Format header info
1331//   STHeader sdh;
1332//   sdh = getHeader();
1333//   sdh.print();
1334  ostringstream oss;
1335  oss.flags(std::ios_base::left);
1336  oss << setw(15) << "Beams:" << setw(4) << nbeam() << endl
1337      << setw(15) << "IFs:" << setw(4) << nif() << endl
1338      << setw(15) << "Polarisations:" << setw(4) << npol()
1339      << "(" << getPolType() << ")" << endl
1340      << setw(15) << "Channels:" << nchan() << endl;
1341  String tmp;
1342  oss << setw(15) << "Observer:"
1343      << table_.keywordSet().asString("Observer") << endl;
1344  oss << setw(15) << "Obs Date:" << getTime(-1,true) << endl;
1345  table_.keywordSet().get("Project", tmp);
1346  oss << setw(15) << "Project:" << tmp << endl;
1347  table_.keywordSet().get("Obstype", tmp);
1348  oss << setw(15) << "Obs. Type:" << tmp << endl;
1349  table_.keywordSet().get("AntennaName", tmp);
1350  oss << setw(15) << "Antenna Name:" << tmp << endl;
1351  table_.keywordSet().get("FluxUnit", tmp);
1352  oss << setw(15) << "Flux Unit:" << tmp << endl;
1353  int nid = moleculeTable_.nrow();
1354  Bool firstline = True;
1355  oss << setw(15) << "Rest Freqs:";
1356  for (int i=0; i<nid; i++) {
1357    Table t = table_(table_.col("MOLECULE_ID") == i, 1);
1358      if (t.nrow() >  0) {
1359          Vector<Double> vec(moleculeTable_.getRestFrequency(i));
1360          if (vec.nelements() > 0) {
1361               if (firstline) {
1362                   oss << setprecision(10) << vec << " [Hz]" << endl;
1363                   firstline=False;
1364               }
1365               else{
1366                   oss << setw(15)<<" " << setprecision(10) << vec << " [Hz]" << endl;
1367               }
1368          } else {
1369              oss << "none" << endl;
1370          }
1371      }
1372  }
1373
1374  oss << setw(15) << "Abcissa:" << getAbcissaLabel(0) << endl;
1375  oss << selector_.print() << endl;
1376  return String(oss);
1377}
1378
1379  //std::string Scantable::summary( const std::string& filename )
1380void Scantable::oldsummary( const std::string& filename )
1381{
1382  ostringstream oss;
1383  ofstream ofs;
1384  LogIO ols(LogOrigin("Scantable", "summary", WHERE));
1385
1386  if (filename != "")
1387    ofs.open( filename.c_str(),  ios::out );
1388
1389  oss << endl;
1390  oss << asap::SEPERATOR << endl;
1391  oss << " Scan Table Summary" << endl;
1392  oss << asap::SEPERATOR << endl;
1393
1394  // Format header info
1395  oss << oldheaderSummary();
1396  oss << endl;
1397
1398  // main table
1399  String dirtype = "Position ("
1400                  + getDirectionRefString()
1401                  + ")";
1402  oss.flags(std::ios_base::left);
1403  oss << setw(5) << "Scan" << setw(15) << "Source"
1404      << setw(10) << "Time" << setw(18) << "Integration"
1405      << setw(15) << "Source Type" << endl;
1406  oss << setw(5) << "" << setw(5) << "Beam" << setw(3) << "" << dirtype << endl;
1407  oss << setw(10) << "" << setw(3) << "IF" << setw(3) << ""
1408      << setw(8) << "Frame" << setw(16)
1409      << "RefVal" << setw(10) << "RefPix" << setw(12) << "Increment"
1410      << setw(7) << "Channels"
1411      << endl;
1412  oss << asap::SEPERATOR << endl;
1413
1414  // Flush summary and clear up the string
1415  ols << String(oss) << LogIO::POST;
1416  if (ofs) ofs << String(oss) << flush;
1417  oss.str("");
1418  oss.clear();
1419
1420  TableIterator iter(table_, "SCANNO");
1421  while (!iter.pastEnd()) {
1422    Table subt = iter.table();
1423    ROTableRow row(subt);
1424    MEpoch::ROScalarColumn timeCol(subt,"TIME");
1425    const TableRecord& rec = row.get(0);
1426    oss << setw(4) << std::right << rec.asuInt("SCANNO")
1427        << std::left << setw(1) << ""
1428        << setw(15) << rec.asString("SRCNAME")
1429        << setw(10) << formatTime(timeCol(0), false);
1430    // count the cycles in the scan
1431    TableIterator cyciter(subt, "CYCLENO");
1432    int nint = 0;
1433    while (!cyciter.pastEnd()) {
1434      ++nint;
1435      ++cyciter;
1436    }
1437    oss << setw(3) << std::right << nint  << setw(3) << " x " << std::left
1438        << setw(11) <<  formatSec(rec.asFloat("INTERVAL")) << setw(1) << ""
1439        << setw(15) << SrcType::getName(rec.asInt("SRCTYPE")) << endl;
1440
1441    TableIterator biter(subt, "BEAMNO");
1442    while (!biter.pastEnd()) {
1443      Table bsubt = biter.table();
1444      ROTableRow brow(bsubt);
1445      const TableRecord& brec = brow.get(0);
1446      uInt row0 = bsubt.rowNumbers(table_)[0];
1447      oss << setw(5) << "" <<  setw(4) << std::right << brec.asuInt("BEAMNO")<< std::left;
1448      oss  << setw(4) << ""  << formatDirection(getDirection(row0)) << endl;
1449      TableIterator iiter(bsubt, "IFNO");
1450      while (!iiter.pastEnd()) {
1451        Table isubt = iiter.table();
1452        ROTableRow irow(isubt);
1453        const TableRecord& irec = irow.get(0);
1454        oss << setw(9) << "";
1455        oss << setw(3) << std::right << irec.asuInt("IFNO") << std::left
1456            << setw(1) << "" << frequencies().print(irec.asuInt("FREQ_ID"))
1457            << setw(3) << "" << nchan(irec.asuInt("IFNO"))
1458            << endl;
1459
1460        ++iiter;
1461      }
1462      ++biter;
1463    }
1464    // Flush summary every scan and clear up the string
1465    ols << String(oss) << LogIO::POST;
1466    if (ofs) ofs << String(oss) << flush;
1467    oss.str("");
1468    oss.clear();
1469
1470    ++iter;
1471  }
1472  oss << asap::SEPERATOR << endl;
1473  ols << String(oss) << LogIO::POST;
1474  if (ofs) {
1475    ofs << String(oss) << flush;
1476    ofs.close();
1477  }
1478  //  return String(oss);
1479}
1480
1481// std::string Scantable::getTime(int whichrow, bool showdate) const
1482// {
1483//   MEpoch::ROScalarColumn timeCol(table_, "TIME");
1484//   MEpoch me;
1485//   if (whichrow > -1) {
1486//     me = timeCol(uInt(whichrow));
1487//   } else {
1488//     Double tm;
1489//     table_.keywordSet().get("UTC",tm);
1490//     me = MEpoch(MVEpoch(tm));
1491//   }
1492//   return formatTime(me, showdate);
1493// }
1494
1495std::string Scantable::getTime(int whichrow, bool showdate, uInt prec) const
1496{
1497  MEpoch me;
1498  me = getEpoch(whichrow);
1499  return formatTime(me, showdate, prec);
1500}
1501
1502MEpoch Scantable::getEpoch(int whichrow) const
1503{
1504  if (whichrow > -1) {
1505    return timeCol_(uInt(whichrow));
1506  } else {
1507    Double tm;
1508    table_.keywordSet().get("UTC",tm);
1509    return MEpoch(MVEpoch(tm));
1510  }
1511}
1512
1513std::string Scantable::getDirectionString(int whichrow) const
1514{
1515  return formatDirection(getDirection(uInt(whichrow)));
1516}
1517
1518
1519SpectralCoordinate Scantable::getSpectralCoordinate(int whichrow) const {
1520  const MPosition& mp = getAntennaPosition();
1521  const MDirection& md = getDirection(whichrow);
1522  const MEpoch& me = timeCol_(whichrow);
1523  //Double rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
1524  Vector<Double> rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
1525  return freqTable_.getSpectralCoordinate(md, mp, me, rf,
1526                                          mfreqidCol_(whichrow));
1527}
1528
1529std::vector< double > Scantable::getAbcissa( int whichrow ) const
1530{
1531  if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal row number"));
1532  std::vector<double> stlout;
1533  int nchan = specCol_(whichrow).nelements();
1534  String us = freqTable_.getUnitString();
1535  if ( us == "" || us == "pixel" || us == "channel" ) {
1536    for (int i=0; i<nchan; ++i) {
1537      stlout.push_back(double(i));
1538    }
1539    return stlout;
1540  }
1541  SpectralCoordinate spc = getSpectralCoordinate(whichrow);
1542  Vector<Double> pixel(nchan);
1543  Vector<Double> world;
1544  indgen(pixel);
1545  if ( Unit(us) == Unit("Hz") ) {
1546    for ( int i=0; i < nchan; ++i) {
1547      Double world;
1548      spc.toWorld(world, pixel[i]);
1549      stlout.push_back(double(world));
1550    }
1551  } else if ( Unit(us) == Unit("km/s") ) {
1552    Vector<Double> world;
1553    spc.pixelToVelocity(world, pixel);
1554    world.tovector(stlout);
1555  }
1556  return stlout;
1557}
1558void Scantable::setDirectionRefString( const std::string & refstr )
1559{
1560  MDirection::Types mdt;
1561  if (refstr != "" && !MDirection::getType(mdt, refstr)) {
1562    throw(AipsError("Illegal Direction frame."));
1563  }
1564  if ( refstr == "" ) {
1565    String defaultstr = MDirection::showType(dirCol_.getMeasRef().getType());
1566    table_.rwKeywordSet().define("DIRECTIONREF", defaultstr);
1567  } else {
1568    table_.rwKeywordSet().define("DIRECTIONREF", String(refstr));
1569  }
1570}
1571
1572std::string Scantable::getDirectionRefString( ) const
1573{
1574  return table_.keywordSet().asString("DIRECTIONREF");
1575}
1576
1577MDirection Scantable::getDirection(int whichrow ) const
1578{
1579  String usertype = table_.keywordSet().asString("DIRECTIONREF");
1580  String type = MDirection::showType(dirCol_.getMeasRef().getType());
1581  if ( usertype != type ) {
1582    MDirection::Types mdt;
1583    if (!MDirection::getType(mdt, usertype)) {
1584      throw(AipsError("Illegal Direction frame."));
1585    }
1586    return dirCol_.convert(uInt(whichrow), mdt);
1587  } else {
1588    return dirCol_(uInt(whichrow));
1589  }
1590}
1591
1592std::string Scantable::getAbcissaLabel( int whichrow ) const
1593{
1594  if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal ro number"));
1595  const MPosition& mp = getAntennaPosition();
1596  const MDirection& md = getDirection(whichrow);
1597  const MEpoch& me = timeCol_(whichrow);
1598  //const Double& rf = mmolidCol_(whichrow);
1599  const Vector<Double> rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
1600  SpectralCoordinate spc =
1601    freqTable_.getSpectralCoordinate(md, mp, me, rf, mfreqidCol_(whichrow));
1602
1603  String s = "Channel";
1604  Unit u = Unit(freqTable_.getUnitString());
1605  if (u == Unit("km/s")) {
1606    s = CoordinateUtil::axisLabel(spc, 0, True,True,  True);
1607  } else if (u == Unit("Hz")) {
1608    Vector<String> wau(1);wau = u.getName();
1609    spc.setWorldAxisUnits(wau);
1610    s = CoordinateUtil::axisLabel(spc, 0, True, True, False);
1611  }
1612  return s;
1613
1614}
1615
1616/**
1617void asap::Scantable::setRestFrequencies( double rf, const std::string& name,
1618                                          const std::string& unit )
1619**/
1620void Scantable::setRestFrequencies( vector<double> rf, const vector<std::string>& name,
1621                                          const std::string& unit )
1622
1623{
1624  ///@todo lookup in line table to fill in name and formattedname
1625  Unit u(unit);
1626  //Quantum<Double> urf(rf, u);
1627  Quantum<Vector<Double> >urf(rf, u);
1628  Vector<String> formattedname(0);
1629  //cerr<<"Scantable::setRestFrequnecies="<<urf<<endl;
1630
1631  //uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), name, "");
1632  uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), mathutil::toVectorString(name), formattedname);
1633  TableVector<uInt> tabvec(table_, "MOLECULE_ID");
1634  tabvec = id;
1635}
1636
1637/**
1638void asap::Scantable::setRestFrequencies( const std::string& name )
1639{
1640  throw(AipsError("setRestFrequencies( const std::string& name ) NYI"));
1641  ///@todo implement
1642}
1643**/
1644
1645void Scantable::setRestFrequencies( const vector<std::string>& name )
1646{
1647  (void) name; // suppress unused warning
1648  throw(AipsError("setRestFrequencies( const vector<std::string>& name ) NYI"));
1649  ///@todo implement
1650}
1651
1652std::vector< unsigned int > Scantable::rownumbers( ) const
1653{
1654  std::vector<unsigned int> stlout;
1655  Vector<uInt> vec = table_.rowNumbers();
1656  vec.tovector(stlout);
1657  return stlout;
1658}
1659
1660
1661Matrix<Float> Scantable::getPolMatrix( uInt whichrow ) const
1662{
1663  ROTableRow row(table_);
1664  const TableRecord& rec = row.get(whichrow);
1665  Table t =
1666    originalTable_( originalTable_.col("SCANNO") == Int(rec.asuInt("SCANNO"))
1667                    && originalTable_.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
1668                    && originalTable_.col("IFNO") == Int(rec.asuInt("IFNO"))
1669                    && originalTable_.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
1670  ROArrayColumn<Float> speccol(t, "SPECTRA");
1671  return speccol.getColumn();
1672}
1673
1674std::vector< std::string > Scantable::columnNames( ) const
1675{
1676  Vector<String> vec = table_.tableDesc().columnNames();
1677  return mathutil::tovectorstring(vec);
1678}
1679
1680MEpoch::Types Scantable::getTimeReference( ) const
1681{
1682  return MEpoch::castType(timeCol_.getMeasRef().getType());
1683}
1684
1685void Scantable::addFit( const STFitEntry& fit, int row )
1686{
1687  //cout << mfitidCol_(uInt(row)) << endl;
1688  LogIO os( LogOrigin( "Scantable", "addFit()", WHERE ) ) ;
1689  os << mfitidCol_(uInt(row)) << LogIO::POST ;
1690  uInt id = fitTable_.addEntry(fit, mfitidCol_(uInt(row)));
1691  mfitidCol_.put(uInt(row), id);
1692}
1693
1694void Scantable::shift(int npix)
1695{
1696  Vector<uInt> fids(mfreqidCol_.getColumn());
1697  genSort( fids, Sort::Ascending,
1698           Sort::QuickSort|Sort::NoDuplicates );
1699  for (uInt i=0; i<fids.nelements(); ++i) {
1700    frequencies().shiftRefPix(npix, fids[i]);
1701  }
1702}
1703
1704String Scantable::getAntennaName() const
1705{
1706  String out;
1707  table_.keywordSet().get("AntennaName", out);
1708  String::size_type pos1 = out.find("@") ;
1709  String::size_type pos2 = out.find("//") ;
1710  if ( pos2 != String::npos )
1711    out = out.substr(pos2+2,pos1-pos2-2) ;
1712  else if ( pos1 != String::npos )
1713    out = out.substr(0,pos1) ;
1714  return out;
1715}
1716
1717int Scantable::checkScanInfo(const std::vector<int>& scanlist) const
1718{
1719  String tbpath;
1720  int ret = 0;
1721  if ( table_.keywordSet().isDefined("GBT_GO") ) {
1722    table_.keywordSet().get("GBT_GO", tbpath);
1723    Table t(tbpath,Table::Old);
1724    // check each scan if other scan of the pair exist
1725    int nscan = scanlist.size();
1726    for (int i = 0; i < nscan; i++) {
1727      Table subt = t( t.col("SCAN") == scanlist[i]+1 );
1728      if (subt.nrow()==0) {
1729        //cerr <<"Scan "<<scanlist[i]<<" cannot be found in the scantable."<<endl;
1730        LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1731        os <<LogIO::WARN<<"Scan "<<scanlist[i]<<" cannot be found in the scantable."<<LogIO::POST;
1732        ret = 1;
1733        break;
1734      }
1735      ROTableRow row(subt);
1736      const TableRecord& rec = row.get(0);
1737      int scan1seqn = rec.asuInt("PROCSEQN");
1738      int laston1 = rec.asuInt("LASTON");
1739      if ( rec.asuInt("PROCSIZE")==2 ) {
1740        if ( i < nscan-1 ) {
1741          Table subt2 = t( t.col("SCAN") == scanlist[i+1]+1 );
1742          if ( subt2.nrow() == 0) {
1743            LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1744
1745            //cerr<<"Scan "<<scanlist[i+1]<<" cannot be found in the scantable."<<endl;
1746            os<<LogIO::WARN<<"Scan "<<scanlist[i+1]<<" cannot be found in the scantable."<<LogIO::POST;
1747            ret = 1;
1748            break;
1749          }
1750          ROTableRow row2(subt2);
1751          const TableRecord& rec2 = row2.get(0);
1752          int scan2seqn = rec2.asuInt("PROCSEQN");
1753          int laston2 = rec2.asuInt("LASTON");
1754          if (scan1seqn == 1 && scan2seqn == 2) {
1755            if (laston1 == laston2) {
1756              LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1757              //cerr<<"A valid scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl;
1758              os<<"A valid scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<LogIO::POST;
1759              i +=1;
1760            }
1761            else {
1762              LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1763              //cerr<<"Incorrect scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl;
1764              os<<LogIO::WARN<<"Incorrect scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<LogIO::POST;
1765            }
1766          }
1767          else if (scan1seqn==2 && scan2seqn == 1) {
1768            if (laston1 == laston2) {
1769              LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1770              //cerr<<"["<<scanlist[i]<<","<<scanlist[i+1]<<"] is a valid scan pair but in incorrect order."<<endl;
1771              os<<LogIO::WARN<<"["<<scanlist[i]<<","<<scanlist[i+1]<<"] is a valid scan pair but in incorrect order."<<LogIO::POST;
1772              ret = 1;
1773              break;
1774            }
1775          }
1776          else {
1777            LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1778            //cerr<<"The other scan for  "<<scanlist[i]<<" appears to be missing. Check the input scan numbers."<<endl;
1779            os<<LogIO::WARN<<"The other scan for  "<<scanlist[i]<<" appears to be missing. Check the input scan numbers."<<LogIO::POST;
1780            ret = 1;
1781            break;
1782          }
1783        }
1784      }
1785      else {
1786        LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1787        //cerr<<"The scan does not appear to be standard obsevation."<<endl;
1788        os<<LogIO::WARN<<"The scan does not appear to be standard obsevation."<<LogIO::POST;
1789      }
1790    //if ( i >= nscan ) break;
1791    }
1792  }
1793  else {
1794    LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1795    //cerr<<"No reference to GBT_GO table."<<endl;
1796    os<<LogIO::WARN<<"No reference to GBT_GO table."<<LogIO::POST;
1797    ret = 1;
1798  }
1799  return ret;
1800}
1801
1802std::vector<double> Scantable::getDirectionVector(int whichrow) const
1803{
1804  Vector<Double> Dir = dirCol_(whichrow).getAngle("rad").getValue();
1805  std::vector<double> dir;
1806  Dir.tovector(dir);
1807  return dir;
1808}
1809
1810void asap::Scantable::reshapeSpectrum( int nmin, int nmax )
1811  throw( casa::AipsError )
1812{
1813  // assumed that all rows have same nChan
1814  Vector<Float> arr = specCol_( 0 ) ;
1815  int nChan = arr.nelements() ;
1816
1817  // if nmin < 0 or nmax < 0, nothing to do
1818  if (  nmin < 0 ) {
1819    throw( casa::indexError<int>( nmin, "asap::Scantable::reshapeSpectrum: Invalid range. Negative index is specified." ) ) ;
1820    }
1821  if (  nmax < 0  ) {
1822    throw( casa::indexError<int>( nmax, "asap::Scantable::reshapeSpectrum: Invalid range. Negative index is specified." ) ) ;
1823  }
1824
1825  // if nmin > nmax, exchange values
1826  if ( nmin > nmax ) {
1827    int tmp = nmax ;
1828    nmax = nmin ;
1829    nmin = tmp ;
1830    LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1831    os << "Swap values. Applied range is ["
1832       << nmin << ", " << nmax << "]" << LogIO::POST ;
1833  }
1834
1835  // if nmin exceeds nChan, nothing to do
1836  if ( nmin >= nChan ) {
1837    throw( casa::indexError<int>( nmin, "asap::Scantable::reshapeSpectrum: Invalid range. Specified minimum exceeds nChan." ) ) ;
1838  }
1839
1840  // if nmax exceeds nChan, reset nmax to nChan
1841  if ( nmax >= nChan ) {
1842    if ( nmin == 0 ) {
1843      // nothing to do
1844      LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1845      os << "Whole range is selected. Nothing to do." << LogIO::POST ;
1846      return ;
1847    }
1848    else {
1849      LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1850      os << "Specified maximum exceeds nChan. Applied range is ["
1851         << nmin << ", " << nChan-1 << "]." << LogIO::POST ;
1852      nmax = nChan - 1 ;
1853    }
1854  }
1855
1856  // reshape specCol_ and flagCol_
1857  for ( int irow = 0 ; irow < nrow() ; irow++ ) {
1858    reshapeSpectrum( nmin, nmax, irow ) ;
1859  }
1860
1861  // update FREQUENCIES subtable
1862  Double refpix ;
1863  Double refval ;
1864  Double increment ;
1865  int freqnrow = freqTable_.table().nrow() ;
1866  Vector<uInt> oldId( freqnrow ) ;
1867  Vector<uInt> newId( freqnrow ) ;
1868  for ( int irow = 0 ; irow < freqnrow ; irow++ ) {
1869    freqTable_.getEntry( refpix, refval, increment, irow ) ;
1870    /***
1871     * need to shift refpix to nmin
1872     * note that channel nmin in old index will be channel 0 in new one
1873     ***/
1874    refval = refval - ( refpix - nmin ) * increment ;
1875    refpix = 0 ;
1876    freqTable_.setEntry( refpix, refval, increment, irow ) ;
1877  }
1878
1879  // update nchan
1880  int newsize = nmax - nmin + 1 ;
1881  table_.rwKeywordSet().define( "nChan", newsize ) ;
1882
1883  // update bandwidth
1884  // assumed all spectra in the scantable have same bandwidth
1885  table_.rwKeywordSet().define( "Bandwidth", increment * newsize ) ;
1886
1887  return ;
1888}
1889
1890void asap::Scantable::reshapeSpectrum( int nmin, int nmax, int irow )
1891{
1892  // reshape specCol_ and flagCol_
1893  Vector<Float> oldspec = specCol_( irow ) ;
1894  Vector<uChar> oldflag = flagsCol_( irow ) ;
1895  uInt newsize = nmax - nmin + 1 ;
1896  specCol_.put( irow, oldspec( Slice( nmin, newsize, 1 ) ) ) ;
1897  flagsCol_.put( irow, oldflag( Slice( nmin, newsize, 1 ) ) ) ;
1898
1899  return ;
1900}
1901
1902void asap::Scantable::regridChannel( int nChan, double dnu )
1903{
1904  LogIO os( LogOrigin( "Scantable", "regridChannel()", WHERE ) ) ;
1905  os << "Regrid abcissa with channel number " << nChan << " and spectral resoultion " << dnu << "Hz." << LogIO::POST ;
1906  // assumed that all rows have same nChan
1907  Vector<Float> arr = specCol_( 0 ) ;
1908  int oldsize = arr.nelements() ;
1909
1910  // if oldsize == nChan, nothing to do
1911  if ( oldsize == nChan ) {
1912    os << "Specified channel number is same as current one. Nothing to do." << LogIO::POST ;
1913    return ;
1914  }
1915
1916  // if oldChan < nChan, unphysical operation
1917  if ( oldsize < nChan ) {
1918    os << "Unphysical operation. Nothing to do." << LogIO::POST ;
1919    return ;
1920  }
1921
1922  // change channel number for specCol_ and flagCol_
1923  Vector<Float> newspec( nChan, 0 ) ;
1924  Vector<uChar> newflag( nChan, false ) ;
1925  vector<string> coordinfo = getCoordInfo() ;
1926  string oldinfo = coordinfo[0] ;
1927  coordinfo[0] = "Hz" ;
1928  setCoordInfo( coordinfo ) ;
1929  for ( int irow = 0 ; irow < nrow() ; irow++ ) {
1930    regridChannel( nChan, dnu, irow ) ;
1931  }
1932  coordinfo[0] = oldinfo ;
1933  setCoordInfo( coordinfo ) ;
1934
1935
1936  // NOTE: this method does not update metadata such as
1937  //       FREQUENCIES subtable, nChan, Bandwidth, etc.
1938
1939  return ;
1940}
1941
1942void asap::Scantable::regridChannel( int nChan, double dnu, int irow )
1943{
1944  // logging
1945  //ofstream ofs( "average.log", std::ios::out | std::ios::app ) ;
1946  //ofs << "IFNO = " << getIF( irow ) << " irow = " << irow << endl ;
1947
1948  Vector<Float> oldspec = specCol_( irow ) ;
1949  Vector<uChar> oldflag = flagsCol_( irow ) ;
1950  Vector<Float> newspec( nChan, 0 ) ;
1951  Vector<uChar> newflag( nChan, false ) ;
1952
1953  // regrid
1954  vector<double> abcissa = getAbcissa( irow ) ;
1955  int oldsize = abcissa.size() ;
1956  double olddnu = abcissa[1] - abcissa[0] ;
1957  //int refChan = 0 ;
1958  //double frac = 0.0 ;
1959  //double wedge = 0.0 ;
1960  //double pile = 0.0 ;
1961  int ichan = 0 ;
1962  double wsum = 0.0 ;
1963  Vector<Float> zi( nChan+1 ) ;
1964  Vector<Float> yi( oldsize + 1 ) ;
1965  zi[0] = abcissa[0] - 0.5 * olddnu ;
1966  zi[1] = zi[1] + dnu ;
1967  for ( int ii = 2 ; ii < nChan ; ii++ )
1968    zi[ii] = zi[0] + dnu * ii ;
1969  zi[nChan] = zi[nChan-1] + dnu ;
1970  yi[0] = abcissa[0] - 0.5 * olddnu ;
1971  yi[1] = abcissa[1] + 0.5 * olddnu ;
1972  for ( int ii = 2 ; ii < oldsize ; ii++ )
1973    yi[ii] = abcissa[ii-1] + olddnu ;
1974  yi[oldsize] = abcissa[oldsize-1] + 0.5 * olddnu ;
1975  if ( dnu > 0.0 ) {
1976    for ( int ii = 0 ; ii < nChan ; ii++ ) {
1977      double zl = zi[ii] ;
1978      double zr = zi[ii+1] ;
1979      for ( int j = ichan ; j < oldsize ; j++ ) {
1980        double yl = yi[j] ;
1981        double yr = yi[j+1] ;
1982        if ( yl <= zl ) {
1983          if ( yr <= zl ) {
1984            continue ;
1985          }
1986          else if ( yr <= zr ) {
1987            newspec[ii] += oldspec[j] * ( yr - zl ) ;
1988            newflag[ii] = newflag[ii] || oldflag[j] ;
1989            wsum += ( yr - zl ) ;
1990          }
1991          else {
1992            newspec[ii] += oldspec[j] * dnu ;
1993            newflag[ii] = newflag[ii] || oldflag[j] ;
1994            wsum += dnu ;
1995            ichan = j ;
1996            break ;
1997          }
1998        }
1999        else if ( yl < zr ) {
2000          if ( yr <= zr ) {
2001              newspec[ii] += oldspec[j] * ( yr - yl ) ;
2002              newflag[ii] = newflag[ii] || oldflag[j] ;
2003              wsum += ( yr - yl ) ;
2004          }
2005          else {
2006            newspec[ii] += oldspec[j] * ( zr - yl ) ;
2007            newflag[ii] = newflag[ii] || oldflag[j] ;
2008            wsum += ( zr - yl ) ;
2009            ichan = j ;
2010            break ;
2011          }
2012        }
2013        else {
2014          ichan = j - 1 ;
2015          break ;
2016        }
2017      }
2018      if ( wsum != 0.0 )
2019        newspec[ii] /= wsum ;
2020      wsum = 0.0 ;
2021    }
2022  }
2023  else if ( dnu < 0.0 ) {
2024    for ( int ii = 0 ; ii < nChan ; ii++ ) {
2025      double zl = zi[ii] ;
2026      double zr = zi[ii+1] ;
2027      for ( int j = ichan ; j < oldsize ; j++ ) {
2028        double yl = yi[j] ;
2029        double yr = yi[j+1] ;
2030        if ( yl >= zl ) {
2031          if ( yr >= zl ) {
2032            continue ;
2033          }
2034          else if ( yr >= zr ) {
2035            newspec[ii] += oldspec[j] * abs( yr - zl ) ;
2036            newflag[ii] = newflag[ii] || oldflag[j] ;
2037            wsum += abs( yr - zl ) ;
2038          }
2039          else {
2040            newspec[ii] += oldspec[j] * abs( dnu ) ;
2041            newflag[ii] = newflag[ii] || oldflag[j] ;
2042            wsum += abs( dnu ) ;
2043            ichan = j ;
2044            break ;
2045          }
2046        }
2047        else if ( yl > zr ) {
2048          if ( yr >= zr ) {
2049            newspec[ii] += oldspec[j] * abs( yr - yl ) ;
2050            newflag[ii] = newflag[ii] || oldflag[j] ;
2051            wsum += abs( yr - yl ) ;
2052          }
2053          else {
2054            newspec[ii] += oldspec[j] * abs( zr - yl ) ;
2055            newflag[ii] = newflag[ii] || oldflag[j] ;
2056            wsum += abs( zr - yl ) ;
2057            ichan = j ;
2058            break ;
2059          }
2060        }
2061        else {
2062          ichan = j - 1 ;
2063          break ;
2064        }
2065      }
2066      if ( wsum != 0.0 )
2067        newspec[ii] /= wsum ;
2068      wsum = 0.0 ;
2069    }
2070  }
2071//    * ichan = 0
2072//    ***/
2073//   //ofs << "olddnu = " << olddnu << ", dnu = " << dnu << endl ;
2074//   pile += dnu ;
2075//   wedge = olddnu * ( refChan + 1 ) ;
2076//   while ( wedge < pile ) {
2077//     newspec[0] += olddnu * oldspec[refChan] ;
2078//     newflag[0] = newflag[0] || oldflag[refChan] ;
2079//     //ofs << "channel " << refChan << " is included in new channel 0" << endl ;
2080//     refChan++ ;
2081//     wedge += olddnu ;
2082//     wsum += olddnu ;
2083//     //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
2084//   }
2085//   frac = ( wedge - pile ) / olddnu ;
2086//   wsum += ( 1.0 - frac ) * olddnu ;
2087//   newspec[0] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
2088//   newflag[0] = newflag[0] || oldflag[refChan] ;
2089//   //ofs << "channel " << refChan << " is partly included in new channel 0" << " with fraction of " << ( 1.0 - frac ) << endl ;
2090//   //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
2091//   newspec[0] /= wsum ;
2092//   //ofs << "newspec[0] = " << newspec[0] << endl ;
2093//   //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
2094
2095//   /***
2096//    * ichan = 1 - nChan-2
2097//    ***/
2098//   for ( int ichan = 1 ; ichan < nChan - 1 ; ichan++ ) {
2099//     pile += dnu ;
2100//     newspec[ichan] += frac * olddnu * oldspec[refChan] ;
2101//     newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
2102//     //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << frac << endl ;
2103//     refChan++ ;
2104//     wedge += olddnu ;
2105//     wsum = frac * olddnu ;
2106//     //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
2107//     while ( wedge < pile ) {
2108//       newspec[ichan] += olddnu * oldspec[refChan] ;
2109//       newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
2110//       //ofs << "channel " << refChan << " is included in new channel " << ichan << endl ;
2111//       refChan++ ;
2112//       wedge += olddnu ;
2113//       wsum += olddnu ;
2114//       //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
2115//     }
2116//     frac = ( wedge - pile ) / olddnu ;
2117//     wsum += ( 1.0 - frac ) * olddnu ;
2118//     newspec[ichan] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
2119//     newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
2120//     //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << ( 1.0 - frac ) << endl ;
2121//     //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
2122//     //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
2123//     newspec[ichan] /= wsum ;
2124//     //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << endl ;
2125//   }
2126
2127//   /***
2128//    * ichan = nChan-1
2129//    ***/
2130//   // NOTE: Assumed that all spectra have the same bandwidth
2131//   pile += dnu ;
2132//   newspec[nChan-1] += frac * olddnu * oldspec[refChan] ;
2133//   newflag[nChan-1] = newflag[nChan-1] || oldflag[refChan] ;
2134//   //ofs << "channel " << refChan << " is partly included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
2135//   refChan++ ;
2136//   wedge += olddnu ;
2137//   wsum = frac * olddnu ;
2138//   //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
2139//   for ( int jchan = refChan ; jchan < oldsize ; jchan++ ) {
2140//     newspec[nChan-1] += olddnu * oldspec[jchan] ;
2141//     newflag[nChan-1] = newflag[nChan-1] || oldflag[jchan] ;
2142//     wsum += olddnu ;
2143//     //ofs << "channel " << jchan << " is included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
2144//     //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
2145//   }
2146//   //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
2147//   //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
2148//   newspec[nChan-1] /= wsum ;
2149//   //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << endl ;
2150
2151//   // ofs.close() ;
2152
2153  specCol_.put( irow, newspec ) ;
2154  flagsCol_.put( irow, newflag ) ;
2155
2156  return ;
2157}
2158
2159std::vector<float> Scantable::getWeather(int whichrow) const
2160{
2161  std::vector<float> out(5);
2162  //Float temperature, pressure, humidity, windspeed, windaz;
2163  weatherTable_.getEntry(out[0], out[1], out[2], out[3], out[4],
2164                         mweatheridCol_(uInt(whichrow)));
2165
2166
2167  return out;
2168}
2169
2170bool Scantable::getFlagtraFast(uInt whichrow)
2171{
2172  uChar flag;
2173  Vector<uChar> flags;
2174  flagsCol_.get(whichrow, flags);
2175  flag = flags[0];
2176  for (uInt i = 1; i < flags.size(); ++i) {
2177    flag &= flags[i];
2178  }
2179  return ((flag >> 7) == 1);
2180}
2181
2182void Scantable::polyBaseline(const std::vector<bool>& mask, int order, bool getResidual, const std::string& progressInfo, const bool outLogger, const std::string& blfile)
2183{
2184  try {
2185    ofstream ofs;
2186    String coordInfo = "";
2187    bool hasSameNchan = true;
2188    bool outTextFile = false;
2189
2190    if (blfile != "") {
2191      ofs.open(blfile.c_str(), ios::out | ios::app);
2192      if (ofs) outTextFile = true;
2193    }
2194
2195    if (outLogger || outTextFile) {
2196      coordInfo = getCoordInfo()[0];
2197      if (coordInfo == "") coordInfo = "channel";
2198      hasSameNchan = hasSameNchanOverIFs();
2199    }
2200
2201    Fitter fitter = Fitter();
2202    fitter.setExpression("poly", order);
2203    //fitter.setIterClipping(thresClip, nIterClip);
2204
2205    int nRow = nrow();
2206    std::vector<bool> chanMask;
2207    bool showProgress;
2208    int minNRow;
2209    parseProgressInfo(progressInfo, showProgress, minNRow);
2210
2211    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2212      chanMask = getCompositeChanMask(whichrow, mask);
2213      fitBaseline(chanMask, whichrow, fitter);
2214      setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
2215      outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "polyBaseline()", fitter);
2216      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
2217    }
2218
2219    if (outTextFile) ofs.close();
2220
2221  } catch (...) {
2222    throw;
2223  }
2224}
2225
2226void Scantable::autoPolyBaseline(const std::vector<bool>& mask, int order, const std::vector<int>& edge, float threshold, int chanAvgLimit, bool getResidual, const std::string& progressInfo, const bool outLogger, const std::string& blfile)
2227{
2228  try {
2229    ofstream ofs;
2230    String coordInfo = "";
2231    bool hasSameNchan = true;
2232    bool outTextFile = false;
2233
2234    if (blfile != "") {
2235      ofs.open(blfile.c_str(), ios::out | ios::app);
2236      if (ofs) outTextFile = true;
2237    }
2238
2239    if (outLogger || outTextFile) {
2240      coordInfo = getCoordInfo()[0];
2241      if (coordInfo == "") coordInfo = "channel";
2242      hasSameNchan = hasSameNchanOverIFs();
2243    }
2244
2245    Fitter fitter = Fitter();
2246    fitter.setExpression("poly", order);
2247    //fitter.setIterClipping(thresClip, nIterClip);
2248
2249    int nRow = nrow();
2250    std::vector<bool> chanMask;
2251    int minEdgeSize = getIFNos().size()*2;
2252    STLineFinder lineFinder = STLineFinder();
2253    lineFinder.setOptions(threshold, 3, chanAvgLimit);
2254
2255    bool showProgress;
2256    int minNRow;
2257    parseProgressInfo(progressInfo, showProgress, minNRow);
2258
2259    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2260
2261      //-------------------------------------------------------
2262      //chanMask = getCompositeChanMask(whichrow, mask, edge, minEdgeSize, lineFinder);
2263      //-------------------------------------------------------
2264      int edgeSize = edge.size();
2265      std::vector<int> currentEdge;
2266      if (edgeSize >= 2) {
2267        int idx = 0;
2268        if (edgeSize > 2) {
2269          if (edgeSize < minEdgeSize) {
2270            throw(AipsError("Length of edge element info is less than that of IFs"));
2271          }
2272          idx = 2 * getIF(whichrow);
2273        }
2274        currentEdge.push_back(edge[idx]);
2275        currentEdge.push_back(edge[idx+1]);
2276      } else {
2277        throw(AipsError("Wrong length of edge element"));
2278      }
2279      lineFinder.setData(getSpectrum(whichrow));
2280      lineFinder.findLines(getCompositeChanMask(whichrow, mask), currentEdge, whichrow);
2281      chanMask = lineFinder.getMask();
2282      //-------------------------------------------------------
2283
2284      fitBaseline(chanMask, whichrow, fitter);
2285      setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
2286
2287      outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "autoPolyBaseline()", fitter);
2288      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
2289    }
2290
2291    if (outTextFile) ofs.close();
2292
2293  } catch (...) {
2294    throw;
2295  }
2296}
2297
2298void Scantable::cubicSplineBaseline(const std::vector<bool>& mask, int nPiece, float thresClip, int nIterClip, bool getResidual, const std::string& progressInfo, const bool outLogger, const std::string& blfile)
2299{
2300  try {
2301    ofstream ofs;
2302    String coordInfo = "";
2303    bool hasSameNchan = true;
2304    bool outTextFile = false;
2305
2306    if (blfile != "") {
2307      ofs.open(blfile.c_str(), ios::out | ios::app);
2308      if (ofs) outTextFile = true;
2309    }
2310
2311    if (outLogger || outTextFile) {
2312      coordInfo = getCoordInfo()[0];
2313      if (coordInfo == "") coordInfo = "channel";
2314      hasSameNchan = hasSameNchanOverIFs();
2315    }
2316
2317    //Fitter fitter = Fitter();
2318    //fitter.setExpression("cspline", nPiece);
2319    //fitter.setIterClipping(thresClip, nIterClip);
2320
2321    int nRow = nrow();
2322    std::vector<bool> chanMask;
2323    bool showProgress;
2324    int minNRow;
2325    parseProgressInfo(progressInfo, showProgress, minNRow);
2326
2327    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2328      chanMask = getCompositeChanMask(whichrow, mask);
2329      //fitBaseline(chanMask, whichrow, fitter);
2330      //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
2331      std::vector<int> pieceEdges;
2332      std::vector<float> params;
2333      int nClipped = 0;
2334      std::vector<float> res = doCubicSplineFitting(getSpectrum(whichrow), chanMask, nPiece, pieceEdges, params, nClipped, thresClip, nIterClip, getResidual);
2335      setSpectrum(res, whichrow);
2336      //
2337
2338      outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "cubicSplineBaseline()", pieceEdges, params, nClipped);
2339      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
2340    }
2341
2342    if (outTextFile) ofs.close();
2343
2344  } catch (...) {
2345    throw;
2346  }
2347}
2348
2349void Scantable::autoCubicSplineBaseline(const std::vector<bool>& mask, int nPiece, float thresClip, int nIterClip, const std::vector<int>& edge, float threshold, int chanAvgLimit, bool getResidual, const std::string& progressInfo, const bool outLogger, const std::string& blfile)
2350{
2351  try {
2352    ofstream ofs;
2353    String coordInfo = "";
2354    bool hasSameNchan = true;
2355    bool outTextFile = false;
2356
2357    if (blfile != "") {
2358      ofs.open(blfile.c_str(), ios::out | ios::app);
2359      if (ofs) outTextFile = true;
2360    }
2361
2362    if (outLogger || outTextFile) {
2363      coordInfo = getCoordInfo()[0];
2364      if (coordInfo == "") coordInfo = "channel";
2365      hasSameNchan = hasSameNchanOverIFs();
2366    }
2367
2368    //Fitter fitter = Fitter();
2369    //fitter.setExpression("cspline", nPiece);
2370    //fitter.setIterClipping(thresClip, nIterClip);
2371
2372    int nRow = nrow();
2373    std::vector<bool> chanMask;
2374    int minEdgeSize = getIFNos().size()*2;
2375    STLineFinder lineFinder = STLineFinder();
2376    lineFinder.setOptions(threshold, 3, chanAvgLimit);
2377
2378    bool showProgress;
2379    int minNRow;
2380    parseProgressInfo(progressInfo, showProgress, minNRow);
2381
2382    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2383
2384      //-------------------------------------------------------
2385      //chanMask = getCompositeChanMask(whichrow, mask, edge, minEdgeSize, lineFinder);
2386      //-------------------------------------------------------
2387      int edgeSize = edge.size();
2388      std::vector<int> currentEdge;
2389      if (edgeSize >= 2) {
2390        int idx = 0;
2391        if (edgeSize > 2) {
2392          if (edgeSize < minEdgeSize) {
2393            throw(AipsError("Length of edge element info is less than that of IFs"));
2394          }
2395          idx = 2 * getIF(whichrow);
2396        }
2397        currentEdge.push_back(edge[idx]);
2398        currentEdge.push_back(edge[idx+1]);
2399      } else {
2400        throw(AipsError("Wrong length of edge element"));
2401      }
2402      lineFinder.setData(getSpectrum(whichrow));
2403      lineFinder.findLines(getCompositeChanMask(whichrow, mask), currentEdge, whichrow);
2404      chanMask = lineFinder.getMask();
2405      //-------------------------------------------------------
2406
2407
2408      //fitBaseline(chanMask, whichrow, fitter);
2409      //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
2410      std::vector<int> pieceEdges;
2411      std::vector<float> params;
2412      int nClipped = 0;
2413      std::vector<float> res = doCubicSplineFitting(getSpectrum(whichrow), chanMask, nPiece, pieceEdges, params, nClipped, thresClip, nIterClip, getResidual);
2414      setSpectrum(res, whichrow);
2415      //
2416
2417      outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "autoCubicSplineBaseline()", pieceEdges, params, nClipped);
2418      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
2419    }
2420
2421    if (outTextFile) ofs.close();
2422
2423  } catch (...) {
2424    throw;
2425  }
2426}
2427
2428std::vector<float> Scantable::doCubicSplineFitting(const std::vector<float>& data, const std::vector<bool>& mask, int nPiece, std::vector<int>& idxEdge, std::vector<float>& params, int& nClipped, float thresClip, int nIterClip, bool getResidual)
2429{
2430  if (data.size() != mask.size()) {
2431    throw(AipsError("data and mask sizes are not identical"));
2432  }
2433  if (nPiece < 1) {
2434    throw(AipsError("number of the sections must be one or more"));
2435  }
2436
2437  int nChan = data.size();
2438  std::vector<int> maskArray;
2439  std::vector<int> x;
2440  for (int i = 0; i < nChan; ++i) {
2441    maskArray.push_back(mask[i] ? 1 : 0);
2442    if (mask[i]) {
2443      x.push_back(i);
2444    }
2445  }
2446
2447  int initNData = x.size();
2448  if (initNData < nPiece) {
2449    throw(AipsError("too few non-flagged channels"));
2450  }
2451
2452  int nElement = (int)(floor(floor((double)(initNData/nPiece))+0.5));
2453  std::vector<double> invEdge;
2454  idxEdge.clear();
2455  idxEdge.push_back(x[0]);
2456  for (int i = 1; i < nPiece; ++i) {
2457    int valX = x[nElement*i];
2458    idxEdge.push_back(valX);
2459    invEdge.push_back(1.0/(double)valX);
2460  }
2461  idxEdge.push_back(x[x.size()-1]+1);
2462
2463  int nData = initNData;
2464  int nDOF = nPiece + 3;  //number of parameters to solve, namely, 4+(nPiece-1).
2465
2466  std::vector<double> x1, x2, x3, z1, x1z1, x2z1, x3z1, r1, residual;
2467  for (int i = 0; i < nChan; ++i) {
2468    double di = (double)i;
2469    double dD = (double)data[i];
2470    x1.push_back(di);
2471    x2.push_back(di*di);
2472    x3.push_back(di*di*di);
2473    z1.push_back(dD);
2474    x1z1.push_back(dD*di);
2475    x2z1.push_back(dD*di*di);
2476    x3z1.push_back(dD*di*di*di);
2477    r1.push_back(0.0);
2478    residual.push_back(0.0);
2479  }
2480
2481  for (int nClip = 0; nClip < nIterClip+1; ++nClip) {
2482    // xMatrix : horizontal concatenation of
2483    //           the least-sq. matrix (left) and an
2484    //           identity matrix (right).
2485    // the right part is used to calculate the inverse matrix of the left part.
2486    double xMatrix[nDOF][2*nDOF];
2487    double zMatrix[nDOF];
2488    for (int i = 0; i < nDOF; ++i) {
2489      for (int j = 0; j < 2*nDOF; ++j) {
2490        xMatrix[i][j] = 0.0;
2491      }
2492      xMatrix[i][nDOF+i] = 1.0;
2493      zMatrix[i] = 0.0;
2494    }
2495
2496    for (int n = 0; n < nPiece; ++n) {
2497      int nUseDataInPiece = 0;
2498      for (int i = idxEdge[n]; i < idxEdge[n+1]; ++i) {
2499
2500        if (maskArray[i] == 0) continue;
2501
2502        xMatrix[0][0] += 1.0;
2503        xMatrix[0][1] += x1[i];
2504        xMatrix[0][2] += x2[i];
2505        xMatrix[0][3] += x3[i];
2506        xMatrix[1][1] += x2[i];
2507        xMatrix[1][2] += x3[i];
2508        xMatrix[1][3] += x2[i]*x2[i];
2509        xMatrix[2][2] += x2[i]*x2[i];
2510        xMatrix[2][3] += x3[i]*x2[i];
2511        xMatrix[3][3] += x3[i]*x3[i];
2512        zMatrix[0] += z1[i];
2513        zMatrix[1] += x1z1[i];
2514        zMatrix[2] += x2z1[i];
2515        zMatrix[3] += x3z1[i];
2516
2517        for (int j = 0; j < n; ++j) {
2518          double q = 1.0 - x1[i]*invEdge[j];
2519          q = q*q*q;
2520          xMatrix[0][j+4] += q;
2521          xMatrix[1][j+4] += q*x1[i];
2522          xMatrix[2][j+4] += q*x2[i];
2523          xMatrix[3][j+4] += q*x3[i];
2524          for (int k = 0; k < j; ++k) {
2525            double r = 1.0 - x1[i]*invEdge[k];
2526            r = r*r*r;
2527            xMatrix[k+4][j+4] += r*q;
2528          }
2529          xMatrix[j+4][j+4] += q*q;
2530          zMatrix[j+4] += q*z1[i];
2531        }
2532
2533        nUseDataInPiece++;
2534      }
2535
2536      if (nUseDataInPiece < 1) {
2537        std::vector<string> suffixOfPieceNumber(4);
2538        suffixOfPieceNumber[0] = "th";
2539        suffixOfPieceNumber[1] = "st";
2540        suffixOfPieceNumber[2] = "nd";
2541        suffixOfPieceNumber[3] = "rd";
2542        int idxNoDataPiece = (n % 10 <= 3) ? n : 0;
2543        ostringstream oss;
2544        oss << "all channels clipped or masked in " << n << suffixOfPieceNumber[idxNoDataPiece];
2545        oss << " piece of the spectrum. can't execute fitting anymore.";
2546        throw(AipsError(String(oss)));
2547      }
2548    }
2549
2550    for (int i = 0; i < nDOF; ++i) {
2551      for (int j = 0; j < i; ++j) {
2552        xMatrix[i][j] = xMatrix[j][i];
2553      }
2554    }
2555
2556    std::vector<double> invDiag;
2557    for (int i = 0; i < nDOF; ++i) {
2558      invDiag.push_back(1.0/xMatrix[i][i]);
2559      for (int j = 0; j < nDOF; ++j) {
2560        xMatrix[i][j] *= invDiag[i];
2561      }
2562    }
2563
2564    for (int k = 0; k < nDOF; ++k) {
2565      for (int i = 0; i < nDOF; ++i) {
2566        if (i != k) {
2567          double factor1 = xMatrix[k][k];
2568          double factor2 = xMatrix[i][k];
2569          for (int j = k; j < 2*nDOF; ++j) {
2570            xMatrix[i][j] *= factor1;
2571            xMatrix[i][j] -= xMatrix[k][j]*factor2;
2572            xMatrix[i][j] /= factor1;
2573          }
2574        }
2575      }
2576      double xDiag = xMatrix[k][k];
2577      for (int j = k; j < 2*nDOF; ++j) {
2578        xMatrix[k][j] /= xDiag;
2579      }
2580    }
2581   
2582    for (int i = 0; i < nDOF; ++i) {
2583      for (int j = 0; j < nDOF; ++j) {
2584        xMatrix[i][nDOF+j] *= invDiag[j];
2585      }
2586    }
2587    //compute a vector y which consists of the coefficients of the best-fit spline curves
2588    //(a0,a1,a2,a3(,b3,c3,...)), namely, the ones for the leftmost piece and the ones of
2589    //cubic terms for the other pieces (in case nPiece>1).
2590    std::vector<double> y;
2591    y.clear();
2592    for (int i = 0; i < nDOF; ++i) {
2593      y.push_back(0.0);
2594      for (int j = 0; j < nDOF; ++j) {
2595        y[i] += xMatrix[i][nDOF+j]*zMatrix[j];
2596      }
2597    }
2598
2599    double a0 = y[0];
2600    double a1 = y[1];
2601    double a2 = y[2];
2602    double a3 = y[3];
2603    params.clear();
2604
2605    for (int n = 0; n < nPiece; ++n) {
2606      for (int i = idxEdge[n]; i < idxEdge[n+1]; ++i) {
2607        r1[i] = a0 + a1*x1[i] + a2*x2[i] + a3*x3[i];
2608        residual[i] = z1[i] - r1[i];
2609      }
2610      params.push_back(a0);
2611      params.push_back(a1);
2612      params.push_back(a2);
2613      params.push_back(a3);
2614
2615      if (n == nPiece-1) break;
2616
2617      double d = y[4+n];
2618      double iE = invEdge[n];
2619      a0 +=     d;
2620      a1 -= 3.0*d*iE;
2621      a2 += 3.0*d*iE*iE;
2622      a3 -=     d*iE*iE*iE;
2623    }
2624
2625    if ((nClip == nIterClip) || (thresClip <= 0.0)) {
2626      break;
2627    } else {
2628      double stdDev = 0.0;
2629      for (int i = 0; i < nChan; ++i) {
2630        stdDev += residual[i]*residual[i]*(double)maskArray[i];
2631      }
2632      stdDev = sqrt(stdDev/(double)nData);
2633     
2634      double thres = stdDev * thresClip;
2635      int newNData = 0;
2636      for (int i = 0; i < nChan; ++i) {
2637        if (abs(residual[i]) >= thres) {
2638          maskArray[i] = 0;
2639        }
2640        if (maskArray[i] > 0) {
2641          newNData++;
2642        }
2643      }
2644      if (newNData == nData) {
2645        break; //no more flag to add. iteration stops.
2646      } else {
2647        nData = newNData;
2648      }
2649    }
2650  }
2651
2652  nClipped = initNData - nData;
2653
2654  std::vector<float> result;
2655  if (getResidual) {
2656    for (int i = 0; i < nChan; ++i) {
2657      result.push_back((float)residual[i]);
2658    }
2659  } else {
2660    for (int i = 0; i < nChan; ++i) {
2661      result.push_back((float)r1[i]);
2662    }
2663  }
2664
2665  return result;
2666}
2667
2668  void Scantable::selectWaveNumbers(const int whichrow, const std::vector<bool>& chanMask, const bool applyFFT, const std::string& fftMethod, const std::string& fftThresh, const std::vector<int>& addNWaves, const std::vector<int>& rejectNWaves, std::vector<int>& nWaves)
2669{
2670  nWaves.clear();
2671
2672  if (applyFFT) {
2673    string fftThAttr;
2674    float fftThSigma;
2675    int fftThTop;
2676    parseThresholdExpression(fftThresh, fftThAttr, fftThSigma, fftThTop);
2677    doSelectWaveNumbers(whichrow, chanMask, fftMethod, fftThSigma, fftThTop, fftThAttr, nWaves);
2678  }
2679
2680  addAuxWaveNumbers(addNWaves, rejectNWaves, nWaves);
2681}
2682
2683void Scantable::parseThresholdExpression(const std::string& fftThresh, std::string& fftThAttr, float& fftThSigma, int& fftThTop)
2684{
2685  uInt idxSigma = fftThresh.find("sigma");
2686  uInt idxTop   = fftThresh.find("top");
2687
2688  if (idxSigma == fftThresh.size() - 5) {
2689    std::istringstream is(fftThresh.substr(0, fftThresh.size() - 5));
2690    is >> fftThSigma;
2691    fftThAttr = "sigma";
2692  } else if (idxTop == 0) {
2693    std::istringstream is(fftThresh.substr(3));
2694    is >> fftThTop;
2695    fftThAttr = "top";
2696  } else {
2697    bool isNumber = true;
2698    for (uInt i = 0; i < fftThresh.size()-1; ++i) {
2699      char ch = (fftThresh.substr(i, 1).c_str())[0];
2700      if (!(isdigit(ch) || (fftThresh.substr(i, 1) == "."))) {
2701        isNumber = false;
2702        break;
2703      }
2704    }
2705    if (isNumber) {
2706      std::istringstream is(fftThresh);
2707      is >> fftThSigma;
2708      fftThAttr = "sigma";
2709    } else {
2710      throw(AipsError("fftthresh has a wrong value"));
2711    }
2712  }
2713}
2714
2715void Scantable::doSelectWaveNumbers(const int whichrow, const std::vector<bool>& chanMask, const std::string& fftMethod, const float fftThSigma, const int fftThTop, const std::string& fftThAttr, std::vector<int>& nWaves)
2716{
2717  std::vector<float> fspec;
2718  if (fftMethod == "fft") {
2719    fspec = execFFT(whichrow, chanMask, false, true);
2720  //} else if (fftMethod == "lsp") {
2721  //  fspec = lombScarglePeriodogram(whichrow);
2722  }
2723
2724  if (fftThAttr == "sigma") {
2725    float mean  = 0.0;
2726    float mean2 = 0.0;
2727    for (uInt i = 0; i < fspec.size(); ++i) {
2728      mean  += fspec[i];
2729      mean2 += fspec[i]*fspec[i];
2730    }
2731    mean  /= float(fspec.size());
2732    mean2 /= float(fspec.size());
2733    float thres = mean + fftThSigma * float(sqrt(mean2 - mean*mean));
2734
2735    for (uInt i = 0; i < fspec.size(); ++i) {
2736      if (fspec[i] >= thres) {
2737        nWaves.push_back(i);
2738      }
2739    }
2740
2741  } else if (fftThAttr == "top") {
2742    for (int i = 0; i < fftThTop; ++i) {
2743      float max = 0.0;
2744      int maxIdx = 0;
2745      for (uInt j = 0; j < fspec.size(); ++j) {
2746        if (fspec[j] > max) {
2747          max = fspec[j];
2748          maxIdx = j;
2749        }
2750      }
2751      nWaves.push_back(maxIdx);
2752      fspec[maxIdx] = 0.0;
2753    }
2754
2755  }
2756
2757  if (nWaves.size() > 1) {
2758    sort(nWaves.begin(), nWaves.end());
2759  }
2760}
2761
2762void Scantable::addAuxWaveNumbers(const std::vector<int>& addNWaves, const std::vector<int>& rejectNWaves, std::vector<int>& nWaves)
2763{
2764  for (uInt i = 0; i < addNWaves.size(); ++i) {
2765    bool found = false;
2766    for (uInt j = 0; j < nWaves.size(); ++j) {
2767      if (nWaves[j] == addNWaves[i]) {
2768        found = true;
2769        break;
2770      }
2771    }
2772    if (!found) nWaves.push_back(addNWaves[i]);
2773  }
2774
2775  for (uInt i = 0; i < rejectNWaves.size(); ++i) {
2776    for (std::vector<int>::iterator j = nWaves.begin(); j != nWaves.end(); ) {
2777      if (*j == rejectNWaves[i]) {
2778        j = nWaves.erase(j);
2779      } else {
2780        ++j;
2781      }
2782    }
2783  }
2784
2785  if (nWaves.size() > 1) {
2786    sort(nWaves.begin(), nWaves.end());
2787    unique(nWaves.begin(), nWaves.end());
2788  }
2789}
2790
2791void Scantable::sinusoidBaseline(const std::vector<bool>& mask, const bool applyFFT, const std::string& fftMethod, const std::string& fftThresh, const std::vector<int>& addNWaves, const std::vector<int>& rejectNWaves, float thresClip, int nIterClip, bool getResidual, const std::string& progressInfo, const bool outLogger, const std::string& blfile)
2792{
2793  try {
2794    ofstream ofs;
2795    String coordInfo = "";
2796    bool hasSameNchan = true;
2797    bool outTextFile = false;
2798
2799    if (blfile != "") {
2800      ofs.open(blfile.c_str(), ios::out | ios::app);
2801      if (ofs) outTextFile = true;
2802    }
2803
2804    if (outLogger || outTextFile) {
2805      coordInfo = getCoordInfo()[0];
2806      if (coordInfo == "") coordInfo = "channel";
2807      hasSameNchan = hasSameNchanOverIFs();
2808    }
2809
2810    //Fitter fitter = Fitter();
2811    //fitter.setExpression("sinusoid", nWaves);
2812    //fitter.setIterClipping(thresClip, nIterClip);
2813
2814    int nRow = nrow();
2815    std::vector<bool> chanMask;
2816    std::vector<int> nWaves;
2817
2818    bool showProgress;
2819    int minNRow;
2820    parseProgressInfo(progressInfo, showProgress, minNRow);
2821
2822    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2823      chanMask = getCompositeChanMask(whichrow, mask);
2824      selectWaveNumbers(whichrow, chanMask, applyFFT, fftMethod, fftThresh, addNWaves, rejectNWaves, nWaves);
2825
2826      //FOR DEBUGGING------------
2827      if (whichrow < 0) {// == nRow -1) {
2828        cout << "+++ i=" << setw(3) << whichrow << ", IF=" << setw(2) << getIF(whichrow);
2829        if (applyFFT) {
2830          cout << "[ ";
2831          for (uInt j = 0; j < nWaves.size(); ++j) {
2832            cout << nWaves[j] << ", ";
2833          }
2834          cout << " ]    " << endl;
2835        }
2836        cout << flush;
2837      }
2838      //-------------------------
2839
2840      //fitBaseline(chanMask, whichrow, fitter);
2841      //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
2842      std::vector<float> params;
2843      int nClipped = 0;
2844      std::vector<float> res = doSinusoidFitting(getSpectrum(whichrow), chanMask, nWaves, params, nClipped, thresClip, nIterClip, getResidual);
2845      setSpectrum(res, whichrow);
2846      //
2847
2848      outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "sinusoidBaseline()", params, nClipped);
2849      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
2850    }
2851
2852    if (outTextFile) ofs.close();
2853
2854  } catch (...) {
2855    throw;
2856  }
2857}
2858
2859void Scantable::autoSinusoidBaseline(const std::vector<bool>& mask, const bool applyFFT, const std::string& fftMethod, const std::string& fftThresh, const std::vector<int>& addNWaves, const std::vector<int>& rejectNWaves, float thresClip, int nIterClip, const std::vector<int>& edge, float threshold, int chanAvgLimit, bool getResidual, const std::string& progressInfo, const bool outLogger, const std::string& blfile)
2860{
2861  try {
2862    ofstream ofs;
2863    String coordInfo = "";
2864    bool hasSameNchan = true;
2865    bool outTextFile = false;
2866
2867    if (blfile != "") {
2868      ofs.open(blfile.c_str(), ios::out | ios::app);
2869      if (ofs) outTextFile = true;
2870    }
2871
2872    if (outLogger || outTextFile) {
2873      coordInfo = getCoordInfo()[0];
2874      if (coordInfo == "") coordInfo = "channel";
2875      hasSameNchan = hasSameNchanOverIFs();
2876    }
2877
2878    //Fitter fitter = Fitter();
2879    //fitter.setExpression("sinusoid", nWaves);
2880    //fitter.setIterClipping(thresClip, nIterClip);
2881
2882    int nRow = nrow();
2883    std::vector<bool> chanMask;
2884    std::vector<int> nWaves;
2885
2886    int minEdgeSize = getIFNos().size()*2;
2887    STLineFinder lineFinder = STLineFinder();
2888    lineFinder.setOptions(threshold, 3, chanAvgLimit);
2889
2890    bool showProgress;
2891    int minNRow;
2892    parseProgressInfo(progressInfo, showProgress, minNRow);
2893
2894    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2895
2896      //-------------------------------------------------------
2897      //chanMask = getCompositeChanMask(whichrow, mask, edge, minEdgeSize, lineFinder);
2898      //-------------------------------------------------------
2899      int edgeSize = edge.size();
2900      std::vector<int> currentEdge;
2901      if (edgeSize >= 2) {
2902        int idx = 0;
2903        if (edgeSize > 2) {
2904          if (edgeSize < minEdgeSize) {
2905            throw(AipsError("Length of edge element info is less than that of IFs"));
2906          }
2907          idx = 2 * getIF(whichrow);
2908        }
2909        currentEdge.push_back(edge[idx]);
2910        currentEdge.push_back(edge[idx+1]);
2911      } else {
2912        throw(AipsError("Wrong length of edge element"));
2913      }
2914      lineFinder.setData(getSpectrum(whichrow));
2915      lineFinder.findLines(getCompositeChanMask(whichrow, mask), currentEdge, whichrow);
2916      chanMask = lineFinder.getMask();
2917      //-------------------------------------------------------
2918
2919      selectWaveNumbers(whichrow, chanMask, applyFFT, fftMethod, fftThresh, addNWaves, rejectNWaves, nWaves);
2920
2921      //fitBaseline(chanMask, whichrow, fitter);
2922      //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
2923      std::vector<float> params;
2924      int nClipped = 0;
2925      std::vector<float> res = doSinusoidFitting(getSpectrum(whichrow), chanMask, nWaves, params, nClipped, thresClip, nIterClip, getResidual);
2926      setSpectrum(res, whichrow);
2927      //
2928
2929      outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "autoSinusoidBaseline()", params, nClipped);
2930      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
2931    }
2932
2933    if (outTextFile) ofs.close();
2934
2935  } catch (...) {
2936    throw;
2937  }
2938}
2939
2940std::vector<float> Scantable::doSinusoidFitting(const std::vector<float>& data, const std::vector<bool>& mask, const std::vector<int>& waveNumbers, std::vector<float>& params, int& nClipped, float thresClip, int nIterClip, bool getResidual)
2941{
2942  if (data.size() != mask.size()) {
2943    throw(AipsError("data and mask sizes are not identical"));
2944  }
2945  if (data.size() < 2) {
2946    throw(AipsError("data size is too short"));
2947  }
2948  if (waveNumbers.size() == 0) {
2949    throw(AipsError("no wave numbers given"));
2950  }
2951  std::vector<int> nWaves;  // sorted and uniqued array of wave numbers
2952  nWaves.reserve(waveNumbers.size());
2953  copy(waveNumbers.begin(), waveNumbers.end(), back_inserter(nWaves));
2954  sort(nWaves.begin(), nWaves.end());
2955  std::vector<int>::iterator end_it = unique(nWaves.begin(), nWaves.end());
2956  nWaves.erase(end_it, nWaves.end());
2957
2958  int minNWaves = nWaves[0];
2959  if (minNWaves < 0) {
2960    throw(AipsError("wave number must be positive or zero (i.e. constant)"));
2961  }
2962  bool hasConstantTerm = (minNWaves == 0);
2963
2964  int nChan = data.size();
2965  std::vector<int> maskArray;
2966  std::vector<int> x;
2967  for (int i = 0; i < nChan; ++i) {
2968    maskArray.push_back(mask[i] ? 1 : 0);
2969    if (mask[i]) {
2970      x.push_back(i);
2971    }
2972  }
2973
2974  int initNData = x.size();
2975
2976  int nData = initNData;
2977  int nDOF = nWaves.size() * 2 - (hasConstantTerm ? 1 : 0);  //number of parameters to solve.
2978
2979  const double PI = 6.0 * asin(0.5); // PI (= 3.141592653...)
2980  double baseXFactor = 2.0*PI/(double)(nChan-1);  //the denominator (nChan-1) should be changed to (xdata[nChan-1]-xdata[0]) for accepting x-values given in velocity or frequency when this function is moved to fitter. (2011/03/30 WK)
2981
2982  // xArray : contains elemental values for computing the least-square matrix.
2983  //          xArray.size() is nDOF and xArray[*].size() is nChan.
2984  //          Each xArray element are as follows:
2985  //          xArray[0]    = {1.0, 1.0, 1.0, ..., 1.0},
2986  //          xArray[2n-1] = {sin(nPI/L*x[0]), sin(nPI/L*x[1]), ..., sin(nPI/L*x[nChan])},
2987  //          xArray[2n]   = {cos(nPI/L*x[0]), cos(nPI/L*x[1]), ..., cos(nPI/L*x[nChan])},
2988  //          where (1 <= n <= nMaxWavesInSW),
2989  //          or,
2990  //          xArray[2n-1] = {sin(wn[n]PI/L*x[0]), sin(wn[n]PI/L*x[1]), ..., sin(wn[n]PI/L*x[nChan])},
2991  //          xArray[2n]   = {cos(wn[n]PI/L*x[0]), cos(wn[n]PI/L*x[1]), ..., cos(wn[n]PI/L*x[nChan])},
2992  //          where wn[n] denotes waveNumbers[n] (1 <= n <= waveNumbers.size()).
2993  std::vector<std::vector<double> > xArray;
2994  if (hasConstantTerm) {
2995    std::vector<double> xu;
2996    for (int j = 0; j < nChan; ++j) {
2997      xu.push_back(1.0);
2998    }
2999    xArray.push_back(xu);
3000  }
3001  for (uInt i = (hasConstantTerm ? 1 : 0); i < nWaves.size(); ++i) {
3002    double xFactor = baseXFactor*(double)nWaves[i];
3003    std::vector<double> xs, xc;
3004    xs.clear();
3005    xc.clear();
3006    for (int j = 0; j < nChan; ++j) {
3007      xs.push_back(sin(xFactor*(double)j));
3008      xc.push_back(cos(xFactor*(double)j));
3009    }
3010    xArray.push_back(xs);
3011    xArray.push_back(xc);
3012  }
3013
3014  std::vector<double> z1, r1, residual;
3015  for (int i = 0; i < nChan; ++i) {
3016    z1.push_back((double)data[i]);
3017    r1.push_back(0.0);
3018    residual.push_back(0.0);
3019  }
3020
3021  for (int nClip = 0; nClip < nIterClip+1; ++nClip) {
3022    // xMatrix : horizontal concatenation of
3023    //           the least-sq. matrix (left) and an
3024    //           identity matrix (right).
3025    // the right part is used to calculate the inverse matrix of the left part.
3026    double xMatrix[nDOF][2*nDOF];
3027    double zMatrix[nDOF];
3028    for (int i = 0; i < nDOF; ++i) {
3029      for (int j = 0; j < 2*nDOF; ++j) {
3030        xMatrix[i][j] = 0.0;
3031      }
3032      xMatrix[i][nDOF+i] = 1.0;
3033      zMatrix[i] = 0.0;
3034    }
3035
3036    int nUseData = 0;
3037    for (int k = 0; k < nChan; ++k) {
3038      if (maskArray[k] == 0) continue;
3039
3040      for (int i = 0; i < nDOF; ++i) {
3041        for (int j = i; j < nDOF; ++j) {
3042          xMatrix[i][j] += xArray[i][k] * xArray[j][k];
3043        }
3044        zMatrix[i] += z1[k] * xArray[i][k];
3045      }
3046
3047      nUseData++;
3048    }
3049
3050    if (nUseData < 1) {
3051        throw(AipsError("all channels clipped or masked. can't execute fitting anymore."));     
3052    }
3053
3054    for (int i = 0; i < nDOF; ++i) {
3055      for (int j = 0; j < i; ++j) {
3056        xMatrix[i][j] = xMatrix[j][i];
3057      }
3058    }
3059
3060    std::vector<double> invDiag;
3061    for (int i = 0; i < nDOF; ++i) {
3062      invDiag.push_back(1.0/xMatrix[i][i]);
3063      for (int j = 0; j < nDOF; ++j) {
3064        xMatrix[i][j] *= invDiag[i];
3065      }
3066    }
3067
3068    for (int k = 0; k < nDOF; ++k) {
3069      for (int i = 0; i < nDOF; ++i) {
3070        if (i != k) {
3071          double factor1 = xMatrix[k][k];
3072          double factor2 = xMatrix[i][k];
3073          for (int j = k; j < 2*nDOF; ++j) {
3074            xMatrix[i][j] *= factor1;
3075            xMatrix[i][j] -= xMatrix[k][j]*factor2;
3076            xMatrix[i][j] /= factor1;
3077          }
3078        }
3079      }
3080      double xDiag = xMatrix[k][k];
3081      for (int j = k; j < 2*nDOF; ++j) {
3082        xMatrix[k][j] /= xDiag;
3083      }
3084    }
3085   
3086    for (int i = 0; i < nDOF; ++i) {
3087      for (int j = 0; j < nDOF; ++j) {
3088        xMatrix[i][nDOF+j] *= invDiag[j];
3089      }
3090    }
3091    //compute a vector y which consists of the coefficients of the sinusoids forming the
3092    //best-fit curves (a0,s1,c1,s2,c2,...), where a0 is constant and s* and c* are of sine
3093    //and cosine functions, respectively.
3094    std::vector<double> y;
3095    params.clear();
3096    for (int i = 0; i < nDOF; ++i) {
3097      y.push_back(0.0);
3098      for (int j = 0; j < nDOF; ++j) {
3099        y[i] += xMatrix[i][nDOF+j]*zMatrix[j];
3100      }
3101      params.push_back(y[i]);
3102    }
3103
3104    for (int i = 0; i < nChan; ++i) {
3105      r1[i] = y[0];
3106      for (int j = 1; j < nDOF; ++j) {
3107        r1[i] += y[j]*xArray[j][i];
3108      }
3109      residual[i] = z1[i] - r1[i];
3110    }
3111
3112    if ((nClip == nIterClip) || (thresClip <= 0.0)) {
3113      break;
3114    } else {
3115      double stdDev = 0.0;
3116      for (int i = 0; i < nChan; ++i) {
3117        stdDev += residual[i]*residual[i]*(double)maskArray[i];
3118      }
3119      stdDev = sqrt(stdDev/(double)nData);
3120     
3121      double thres = stdDev * thresClip;
3122      int newNData = 0;
3123      for (int i = 0; i < nChan; ++i) {
3124        if (abs(residual[i]) >= thres) {
3125          maskArray[i] = 0;
3126        }
3127        if (maskArray[i] > 0) {
3128          newNData++;
3129        }
3130      }
3131      if (newNData == nData) {
3132        break; //no more flag to add. iteration stops.
3133      } else {
3134        nData = newNData;
3135      }
3136    }
3137  }
3138
3139  nClipped = initNData - nData;
3140
3141  std::vector<float> result;
3142  if (getResidual) {
3143    for (int i = 0; i < nChan; ++i) {
3144      result.push_back((float)residual[i]);
3145    }
3146  } else {
3147    for (int i = 0; i < nChan; ++i) {
3148      result.push_back((float)r1[i]);
3149    }
3150  }
3151
3152  return result;
3153}
3154
3155void Scantable::fitBaseline(const std::vector<bool>& mask, int whichrow, Fitter& fitter)
3156{
3157  std::vector<double> dAbcissa = getAbcissa(whichrow);
3158  std::vector<float> abcissa;
3159  for (uInt i = 0; i < dAbcissa.size(); ++i) {
3160    abcissa.push_back((float)dAbcissa[i]);
3161  }
3162  std::vector<float> spec = getSpectrum(whichrow);
3163
3164  fitter.setData(abcissa, spec, mask);
3165  fitter.lfit();
3166}
3167
3168std::vector<bool> Scantable::getCompositeChanMask(int whichrow, const std::vector<bool>& inMask)
3169{
3170  std::vector<bool> mask = getMask(whichrow);
3171  uInt maskSize = mask.size();
3172  if (maskSize != inMask.size()) {
3173    throw(AipsError("mask sizes are not the same."));
3174  }
3175  for (uInt i = 0; i < maskSize; ++i) {
3176    mask[i] = mask[i] && inMask[i];
3177  }
3178
3179  return mask;
3180}
3181
3182/*
3183std::vector<bool> Scantable::getCompositeChanMask(int whichrow, const std::vector<bool>& inMask, const std::vector<int>& edge, const int minEdgeSize, STLineFinder& lineFinder)
3184{
3185  int edgeSize = edge.size();
3186  std::vector<int> currentEdge;
3187  if (edgeSize >= 2) {
3188      int idx = 0;
3189      if (edgeSize > 2) {
3190        if (edgeSize < minEdgeSize) {
3191          throw(AipsError("Length of edge element info is less than that of IFs"));
3192        }
3193        idx = 2 * getIF(whichrow);
3194      }
3195      currentEdge.push_back(edge[idx]);
3196      currentEdge.push_back(edge[idx+1]);
3197  } else {
3198    throw(AipsError("Wrong length of edge element"));
3199  }
3200
3201  lineFinder.setData(getSpectrum(whichrow));
3202  lineFinder.findLines(getCompositeChanMask(whichrow, inMask), currentEdge, whichrow);
3203
3204  return lineFinder.getMask();
3205}
3206*/
3207
3208/* for poly. the variations of outputFittingResult() should be merged into one eventually (2011/3/10 WK)  */
3209void Scantable::outputFittingResult(bool outLogger, bool outTextFile, const std::vector<bool>& chanMask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, ofstream& ofs, const casa::String& funcName, Fitter& fitter)
3210{
3211  if (outLogger || outTextFile) {
3212    std::vector<float> params = fitter.getParameters();
3213    std::vector<bool>  fixed  = fitter.getFixedParameters();
3214    float rms = getRms(chanMask, whichrow);
3215    String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
3216
3217    if (outLogger) {
3218      LogIO ols(LogOrigin("Scantable", funcName, WHERE));
3219      ols << formatBaselineParams(params, fixed, rms, -1, masklist, whichrow, false) << LogIO::POST ;
3220    }
3221    if (outTextFile) {
3222      ofs << formatBaselineParams(params, fixed, rms, -1, masklist, whichrow, true) << flush;
3223    }
3224  }
3225}
3226
3227/* for cspline. will be merged once cspline is available in fitter (2011/3/10 WK) */
3228void Scantable::outputFittingResult(bool outLogger, bool outTextFile, const std::vector<bool>& chanMask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, ofstream& ofs, const casa::String& funcName, const std::vector<int>& edge, const std::vector<float>& params, const int nClipped)
3229{
3230  if (outLogger || outTextFile) {
3231    float rms = getRms(chanMask, whichrow);
3232    String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
3233    std::vector<bool> fixed;
3234    fixed.clear();
3235
3236    if (outLogger) {
3237      LogIO ols(LogOrigin("Scantable", funcName, WHERE));
3238      ols << formatPiecewiseBaselineParams(edge, params, fixed, rms, nClipped, masklist, whichrow, false) << LogIO::POST ;
3239    }
3240    if (outTextFile) {
3241      ofs << formatPiecewiseBaselineParams(edge, params, fixed, rms, nClipped, masklist, whichrow, true) << flush;
3242    }
3243  }
3244}
3245
3246/* for sinusoid. will be merged once sinusoid is available in fitter (2011/3/10 WK) */
3247void Scantable::outputFittingResult(bool outLogger, bool outTextFile, const std::vector<bool>& chanMask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, ofstream& ofs, const casa::String& funcName, const std::vector<float>& params, const int nClipped)
3248{
3249  if (outLogger || outTextFile) {
3250    float rms = getRms(chanMask, whichrow);
3251    String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
3252    std::vector<bool> fixed;
3253    fixed.clear();
3254
3255    if (outLogger) {
3256      LogIO ols(LogOrigin("Scantable", funcName, WHERE));
3257      ols << formatBaselineParams(params, fixed, rms, nClipped, masklist, whichrow, false) << LogIO::POST ;
3258    }
3259    if (outTextFile) {
3260      ofs << formatBaselineParams(params, fixed, rms, nClipped, masklist, whichrow, true) << flush;
3261    }
3262  }
3263}
3264
3265void Scantable::parseProgressInfo(const std::string& progressInfo, bool& showProgress, int& minNRow)
3266{
3267  int idxDelimiter = progressInfo.find(",");
3268  if (idxDelimiter < 0) {
3269    throw(AipsError("wrong value in 'showprogress' parameter")) ;
3270  }
3271  showProgress = (progressInfo.substr(0, idxDelimiter) == "true");
3272  std::istringstream is(progressInfo.substr(idxDelimiter+1));
3273  is >> minNRow;
3274}
3275
3276void Scantable::showProgressOnTerminal(const int nProcessed, const int nTotal, const bool showProgress, const int nTotalThreshold)
3277{
3278  if (showProgress && (nTotal >= nTotalThreshold)) {
3279    int nInterval = int(floor(double(nTotal)/100.0));
3280    if (nInterval == 0) nInterval++;
3281
3282    if (nProcessed % nInterval == 0) {
3283      printf("\r");                          //go to the head of line
3284      printf("\x1b[31m\x1b[1m");             //set red color, highlighted
3285      printf("[%3d%%]", (int)(100.0*(double(nProcessed+1))/(double(nTotal))) );
3286      printf("\x1b[39m\x1b[0m");             //set default attributes
3287      fflush(NULL);
3288    }
3289
3290    if (nProcessed == nTotal - 1) {
3291      printf("\r\x1b[K");                    //clear
3292      fflush(NULL);
3293    }
3294
3295  }
3296}
3297
3298std::vector<float> Scantable::execFFT(const int whichrow, const std::vector<bool>& inMask, bool getRealImag, bool getAmplitudeOnly)
3299{
3300  std::vector<bool>  mask = getMask(whichrow);
3301
3302  if (inMask.size() > 0) {
3303    uInt maskSize = mask.size();
3304    if (maskSize != inMask.size()) {
3305      throw(AipsError("mask sizes are not the same."));
3306    }
3307    for (uInt i = 0; i < maskSize; ++i) {
3308      mask[i] = mask[i] && inMask[i];
3309    }
3310  }
3311
3312  Vector<Float> spec = getSpectrum(whichrow);
3313  mathutil::doZeroOrderInterpolation(spec, mask);
3314
3315  FFTServer<Float,Complex> ffts;
3316  Vector<Complex> fftres;
3317  ffts.fft0(fftres, spec);
3318
3319  std::vector<float> res;
3320  float norm = float(2.0/double(spec.size()));
3321
3322  if (getRealImag) {
3323    for (uInt i = 0; i < fftres.size(); ++i) {
3324      res.push_back(real(fftres[i])*norm);
3325      res.push_back(imag(fftres[i])*norm);
3326    }
3327  } else {
3328    for (uInt i = 0; i < fftres.size(); ++i) {
3329      res.push_back(abs(fftres[i])*norm);
3330      if (!getAmplitudeOnly) res.push_back(arg(fftres[i]));
3331    }
3332  }
3333
3334  return res;
3335}
3336
3337
3338float Scantable::getRms(const std::vector<bool>& mask, int whichrow)
3339{
3340  Vector<Float> spec;
3341  specCol_.get(whichrow, spec);
3342
3343  float mean = 0.0;
3344  float smean = 0.0;
3345  int n = 0;
3346  for (uInt i = 0; i < spec.nelements(); ++i) {
3347    if (mask[i]) {
3348      mean += spec[i];
3349      smean += spec[i]*spec[i];
3350      n++;
3351    }
3352  }
3353
3354  mean /= (float)n;
3355  smean /= (float)n;
3356
3357  return sqrt(smean - mean*mean);
3358}
3359
3360
3361std::string Scantable::formatBaselineParamsHeader(int whichrow, const std::string& masklist, bool verbose) const
3362{
3363  ostringstream oss;
3364
3365  if (verbose) {
3366    oss <<  " Scan[" << getScan(whichrow)  << "]";
3367    oss <<  " Beam[" << getBeam(whichrow)  << "]";
3368    oss <<    " IF[" << getIF(whichrow)    << "]";
3369    oss <<   " Pol[" << getPol(whichrow)   << "]";
3370    oss << " Cycle[" << getCycle(whichrow) << "]: " << endl;
3371    oss << "Fitter range = " << masklist << endl;
3372    oss << "Baseline parameters" << endl;
3373    oss << flush;
3374  }
3375
3376  return String(oss);
3377}
3378
3379std::string Scantable::formatBaselineParamsFooter(float rms, int nClipped, bool verbose) const
3380{
3381  ostringstream oss;
3382
3383  if (verbose) {
3384    oss << "Results of baseline fit" << endl;
3385    oss << "  rms = " << setprecision(6) << rms << endl;
3386    if (nClipped >= 0) {
3387      oss << "  Number of clipped channels = " << nClipped << endl;
3388    }
3389    for (int i = 0; i < 60; ++i) {
3390      oss << "-";
3391    }
3392    oss << endl;
3393    oss << flush;
3394  }
3395
3396  return String(oss);
3397}
3398
3399std::string Scantable::formatBaselineParams(const std::vector<float>& params,
3400                                            const std::vector<bool>& fixed,
3401                                            float rms,
3402                                            int nClipped,
3403                                            const std::string& masklist,
3404                                            int whichrow,
3405                                            bool verbose,
3406                                            int start, int count,
3407                                            bool resetparamid) const
3408{
3409  int nParam = (int)(params.size());
3410
3411  if (nParam < 1) {
3412    return("  Not fitted");
3413  } else {
3414
3415    ostringstream oss;
3416    oss << formatBaselineParamsHeader(whichrow, masklist, verbose);
3417
3418    if (start < 0) start = 0;
3419    if (count < 0) count = nParam;
3420    int end = start + count;
3421    if (end > nParam) end = nParam;
3422    int paramidoffset = (resetparamid) ? (-start) : 0;
3423
3424    for (int i = start; i < end; ++i) {
3425      if (i > start) {
3426        oss << ",";
3427      }
3428      std::string sFix = ((fixed.size() > 0) && (fixed[i]) && verbose) ? "(fixed)" : "";
3429      oss << "  p" << (i+paramidoffset) << sFix << "= " << right << setw(13) << setprecision(6) << params[i];
3430    }
3431
3432    oss << endl;
3433    oss << formatBaselineParamsFooter(rms, nClipped, verbose);
3434
3435    return String(oss);
3436  }
3437
3438}
3439
3440  std::string Scantable::formatPiecewiseBaselineParams(const std::vector<int>& ranges, const std::vector<float>& params, const std::vector<bool>& fixed, float rms, int nClipped, const std::string& masklist, int whichrow, bool verbose) const
3441{
3442  int nOutParam = (int)(params.size());
3443  int nPiece = (int)(ranges.size()) - 1;
3444
3445  if (nOutParam < 1) {
3446    return("  Not fitted");
3447  } else if (nPiece < 0) {
3448    return formatBaselineParams(params, fixed, rms, nClipped, masklist, whichrow, verbose);
3449  } else if (nPiece < 1) {
3450    return("  Bad count of the piece edge info");
3451  } else if (nOutParam % nPiece != 0) {
3452    return("  Bad count of the output baseline parameters");
3453  } else {
3454
3455    int nParam = nOutParam / nPiece;
3456
3457    ostringstream oss;
3458    oss << formatBaselineParamsHeader(whichrow, masklist, verbose);
3459
3460    stringstream ss;
3461    ss << ranges[nPiece] << flush;
3462    int wRange = ss.str().size() * 2 + 5;
3463
3464    for (int i = 0; i < nPiece; ++i) {
3465      ss.str("");
3466      ss << "  [" << ranges[i] << "," << (ranges[i+1]-1) << "]";
3467      oss << left << setw(wRange) << ss.str();
3468      oss << formatBaselineParams(params, fixed, rms, 0, masklist, whichrow, false, i*nParam, nParam, true);
3469    }
3470
3471    oss << formatBaselineParamsFooter(rms, nClipped, verbose);
3472
3473    return String(oss);
3474  }
3475
3476}
3477
3478bool Scantable::hasSameNchanOverIFs()
3479{
3480  int nIF = nif(-1);
3481  int nCh;
3482  int totalPositiveNChan = 0;
3483  int nPositiveNChan = 0;
3484
3485  for (int i = 0; i < nIF; ++i) {
3486    nCh = nchan(i);
3487    if (nCh > 0) {
3488      totalPositiveNChan += nCh;
3489      nPositiveNChan++;
3490    }
3491  }
3492
3493  return (totalPositiveNChan == (nPositiveNChan * nchan(0)));
3494}
3495
3496std::string Scantable::getMaskRangeList(const std::vector<bool>& mask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, bool verbose)
3497{
3498  if (mask.size() < 2) {
3499    throw(AipsError("The mask elements should be > 1"));
3500  }
3501  int IF = getIF(whichrow);
3502  if (mask.size() != (uInt)nchan(IF)) {
3503    throw(AipsError("Number of channels in scantable != number of mask elements"));
3504  }
3505
3506  if (verbose) {
3507    LogIO logOs(LogOrigin("Scantable", "getMaskRangeList()", WHERE));
3508    logOs << LogIO::WARN << "The current mask window unit is " << coordInfo;
3509    if (!hasSameNchan) {
3510      logOs << endl << "This mask is only valid for IF=" << IF;
3511    }
3512    logOs << LogIO::POST;
3513  }
3514
3515  std::vector<double> abcissa = getAbcissa(whichrow);
3516  std::vector<int> edge = getMaskEdgeIndices(mask);
3517
3518  ostringstream oss;
3519  oss.setf(ios::fixed);
3520  oss << setprecision(1) << "[";
3521  for (uInt i = 0; i < edge.size(); i+=2) {
3522    if (i > 0) oss << ",";
3523    oss << "[" << (float)abcissa[edge[i]] << "," << (float)abcissa[edge[i+1]] << "]";
3524  }
3525  oss << "]" << flush;
3526
3527  return String(oss);
3528}
3529
3530std::vector<int> Scantable::getMaskEdgeIndices(const std::vector<bool>& mask)
3531{
3532  if (mask.size() < 2) {
3533    throw(AipsError("The mask elements should be > 1"));
3534  }
3535
3536  std::vector<int> out, startIndices, endIndices;
3537  int maskSize = mask.size();
3538
3539  startIndices.clear();
3540  endIndices.clear();
3541
3542  if (mask[0]) {
3543    startIndices.push_back(0);
3544  }
3545  for (int i = 1; i < maskSize; ++i) {
3546    if ((!mask[i-1]) && mask[i]) {
3547      startIndices.push_back(i);
3548    } else if (mask[i-1] && (!mask[i])) {
3549      endIndices.push_back(i-1);
3550    }
3551  }
3552  if (mask[maskSize-1]) {
3553    endIndices.push_back(maskSize-1);
3554  }
3555
3556  if (startIndices.size() != endIndices.size()) {
3557    throw(AipsError("Inconsistent Mask Size: bad data?"));
3558  }
3559  for (uInt i = 0; i < startIndices.size(); ++i) {
3560    if (startIndices[i] > endIndices[i]) {
3561      throw(AipsError("Mask start index > mask end index"));
3562    }
3563  }
3564
3565  out.clear();
3566  for (uInt i = 0; i < startIndices.size(); ++i) {
3567    out.push_back(startIndices[i]);
3568    out.push_back(endIndices[i]);
3569  }
3570
3571  return out;
3572}
3573
3574vector<float> Scantable::getTsysSpectrum( int whichrow ) const
3575{
3576  Vector<Float> tsys( tsysCol_(whichrow) ) ;
3577  vector<float> stlTsys ;
3578  tsys.tovector( stlTsys ) ;
3579  return stlTsys ;
3580}
3581
3582
3583}
3584//namespace asap
Note: See TracBrowser for help on using the repository browser.