source: trunk/src/Scantable.cpp @ 3047

Last change on this file since 3047 was 3047, checked in by Kana Sugimoto, 9 years ago

New Development: No

JIRA Issue: No

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs: unit tests of sdbaseline and sdreduce

Put in Release Notes: No

Module(s): sinusoid baseline fitting

Description: One more fix to an internal member function for sinusoidal fitting.


  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 171.9 KB
Line 
1//
2// C++ Implementation: Scantable
3//
4// Description:
5//
6//
7// Author: Malte Marquarding <asap@atnf.csiro.au>, (C) 2005-2013
8//
9// Copyright: See COPYING file that comes with this distribution
10//
11//
12#include <map>
13#include <sys/time.h>
14
15#include <atnf/PKSIO/SrcType.h>
16
17#include <casa/aips.h>
18#include <casa/iomanip.h>
19#include <casa/iostream.h>
20#include <casa/OS/File.h>
21#include <casa/OS/Path.h>
22#include <casa/Logging/LogIO.h>
23#include <casa/Arrays/Array.h>
24#include <casa/Arrays/ArrayAccessor.h>
25#include <casa/Arrays/ArrayLogical.h>
26#include <casa/Arrays/ArrayMath.h>
27#include <casa/Arrays/MaskArrMath.h>
28#include <casa/Arrays/Slice.h>
29#include <casa/Arrays/Vector.h>
30#include <casa/Arrays/VectorSTLIterator.h>
31#include <casa/BasicMath/Math.h>
32#include <casa/BasicSL/Constants.h>
33#include <casa/Containers/RecordField.h>
34#include <casa/Logging/LogIO.h>
35#include <casa/Quanta/MVAngle.h>
36#include <casa/Quanta/MVTime.h>
37#include <casa/Utilities/GenSort.h>
38#include <casa/Utilities/Assert.h>
39
40#include <coordinates/Coordinates/CoordinateUtil.h>
41
42// needed to avoid error in .tcc
43#include <measures/Measures/MCDirection.h>
44//
45#include <measures/Measures/MDirection.h>
46#include <measures/Measures/MEpoch.h>
47#include <measures/Measures/MFrequency.h>
48#include <measures/Measures/MeasRef.h>
49#include <measures/Measures/MeasTable.h>
50#include <measures/TableMeasures/ScalarMeasColumn.h>
51#include <measures/TableMeasures/TableMeasDesc.h>
52#include <measures/TableMeasures/TableMeasRefDesc.h>
53#include <measures/TableMeasures/TableMeasValueDesc.h>
54
55#include <tables/Tables/ArrColDesc.h>
56#include <tables/Tables/ExprNode.h>
57#include <tables/Tables/ScaColDesc.h>
58#include <tables/Tables/SetupNewTab.h>
59#include <tables/Tables/TableCopy.h>
60#include <tables/Tables/TableDesc.h>
61#include <tables/Tables/TableIter.h>
62#include <tables/Tables/TableParse.h>
63#include <tables/Tables/TableRecord.h>
64#include <tables/Tables/TableRow.h>
65#include <tables/Tables/TableVector.h>
66
67#include "MathUtils.h"
68#include "STAttr.h"
69#include "STBaselineTable.h"
70#include "STLineFinder.h"
71#include "STPolCircular.h"
72#include "STPolLinear.h"
73#include "STPolStokes.h"
74#include "STUpgrade.h"
75#include "STFitter.h"
76#include "Scantable.h"
77
78#define debug 1
79
80using namespace casa;
81
82namespace asap {
83
84std::map<std::string, STPol::STPolFactory *> Scantable::factories_;
85
86void Scantable::initFactories() {
87  if ( factories_.empty() ) {
88    Scantable::factories_["linear"] = &STPolLinear::myFactory;
89    Scantable::factories_["circular"] = &STPolCircular::myFactory;
90    Scantable::factories_["stokes"] = &STPolStokes::myFactory;
91  }
92}
93
94Scantable::Scantable(Table::TableType ttype) :
95  type_(ttype),
96  cubicSplineModelPool_()
97{
98  initFactories();
99  setupMainTable();
100  freqTable_ = STFrequencies(*this);
101  table_.rwKeywordSet().defineTable("FREQUENCIES", freqTable_.table());
102  weatherTable_ = STWeather(*this);
103  table_.rwKeywordSet().defineTable("WEATHER", weatherTable_.table());
104  focusTable_ = STFocus(*this);
105  table_.rwKeywordSet().defineTable("FOCUS", focusTable_.table());
106  tcalTable_ = STTcal(*this);
107  table_.rwKeywordSet().defineTable("TCAL", tcalTable_.table());
108  moleculeTable_ = STMolecules(*this);
109  table_.rwKeywordSet().defineTable("MOLECULES", moleculeTable_.table());
110  historyTable_ = STHistory(*this);
111  table_.rwKeywordSet().defineTable("HISTORY", historyTable_.table());
112  fitTable_ = STFit(*this);
113  table_.rwKeywordSet().defineTable("FIT", fitTable_.table());
114  table_.tableInfo().setType( "Scantable" ) ;
115  originalTable_ = table_;
116  attach();
117}
118
119Scantable::Scantable(const std::string& name, Table::TableType ttype) :
120  type_(ttype),
121  cubicSplineModelPool_()
122{
123  initFactories();
124
125  Table tab(name, Table::Update);
126  uInt version = tab.keywordSet().asuInt("VERSION");
127  if (version != version_) {
128      STUpgrade upgrader(version_);
129      LogIO os( LogOrigin( "Scantable" ) ) ;
130      os << LogIO::WARN
131         << name << " data format version " << version
132         << " is deprecated" << endl
133         << "Running upgrade."<< endl 
134         << LogIO::POST ; 
135      std::string outname = upgrader.upgrade(name);
136      if ( outname != name ) {
137        os << LogIO::WARN
138           << "Data will be loaded from " << outname << " instead of "
139           << name << LogIO::POST ;
140        tab = Table(outname, Table::Update ) ;
141      }
142  }
143  if ( type_ == Table::Memory ) {
144    table_ = tab.copyToMemoryTable(generateName());
145  } else {
146    table_ = tab;
147  }
148  table_.tableInfo().setType( "Scantable" ) ;
149
150  attachSubtables();
151  originalTable_ = table_;
152  attach();
153}
154/*
155Scantable::Scantable(const std::string& name, Table::TableType ttype) :
156  type_(ttype)
157{
158  initFactories();
159  Table tab(name, Table::Update);
160  uInt version = tab.keywordSet().asuInt("VERSION");
161  if (version != version_) {
162    throw(AipsError("Unsupported version of ASAP file."));
163  }
164  if ( type_ == Table::Memory ) {
165    table_ = tab.copyToMemoryTable(generateName());
166  } else {
167    table_ = tab;
168  }
169
170  attachSubtables();
171  originalTable_ = table_;
172  attach();
173}
174*/
175
176Scantable::Scantable( const Scantable& other, bool clear )
177{
178  // with or without data
179  String newname = String(generateName());
180  type_ = other.table_.tableType();
181  if ( other.table_.tableType() == Table::Memory ) {
182      if ( clear ) {
183        table_ = TableCopy::makeEmptyMemoryTable(newname,
184                                                 other.table_, True);
185      } else {
186        table_ = other.table_.copyToMemoryTable(newname);
187      }
188  } else {
189      other.table_.deepCopy(newname, Table::New, False,
190                            other.table_.endianFormat(),
191                            Bool(clear));
192      table_ = Table(newname, Table::Update);
193      table_.markForDelete();
194  }
195  table_.tableInfo().setType( "Scantable" ) ;
196  /// @todo reindex SCANNO, recompute nbeam, nif, npol
197  if ( clear ) copySubtables(other);
198  attachSubtables();
199  originalTable_ = table_;
200  attach();
201}
202
203void Scantable::copySubtables(const Scantable& other) {
204  Table t = table_.rwKeywordSet().asTable("FREQUENCIES");
205  TableCopy::copyRows(t, other.freqTable_.table());
206  t = table_.rwKeywordSet().asTable("FOCUS");
207  TableCopy::copyRows(t, other.focusTable_.table());
208  t = table_.rwKeywordSet().asTable("WEATHER");
209  TableCopy::copyRows(t, other.weatherTable_.table());
210  t = table_.rwKeywordSet().asTable("TCAL");
211  TableCopy::copyRows(t, other.tcalTable_.table());
212  t = table_.rwKeywordSet().asTable("MOLECULES");
213  TableCopy::copyRows(t, other.moleculeTable_.table());
214  t = table_.rwKeywordSet().asTable("HISTORY");
215  TableCopy::copyRows(t, other.historyTable_.table());
216  t = table_.rwKeywordSet().asTable("FIT");
217  TableCopy::copyRows(t, other.fitTable_.table());
218}
219
220void Scantable::attachSubtables()
221{
222  freqTable_ = STFrequencies(table_);
223  focusTable_ = STFocus(table_);
224  weatherTable_ = STWeather(table_);
225  tcalTable_ = STTcal(table_);
226  moleculeTable_ = STMolecules(table_);
227  historyTable_ = STHistory(table_);
228  fitTable_ = STFit(table_);
229}
230
231Scantable::~Scantable()
232{
233}
234
235void Scantable::setupMainTable()
236{
237  TableDesc td("", "1", TableDesc::Scratch);
238  td.comment() = "An ASAP Scantable";
239  td.rwKeywordSet().define("VERSION", uInt(version_));
240
241  // n Cycles
242  td.addColumn(ScalarColumnDesc<uInt>("SCANNO"));
243  // new index every nBeam x nIF x nPol
244  td.addColumn(ScalarColumnDesc<uInt>("CYCLENO"));
245
246  td.addColumn(ScalarColumnDesc<uInt>("BEAMNO"));
247  td.addColumn(ScalarColumnDesc<uInt>("IFNO"));
248  // linear, circular, stokes
249  td.rwKeywordSet().define("POLTYPE", String("linear"));
250  td.addColumn(ScalarColumnDesc<uInt>("POLNO"));
251
252  td.addColumn(ScalarColumnDesc<uInt>("FREQ_ID"));
253  td.addColumn(ScalarColumnDesc<uInt>("MOLECULE_ID"));
254
255  ScalarColumnDesc<Int> refbeamnoColumn("REFBEAMNO");
256  refbeamnoColumn.setDefault(Int(-1));
257  td.addColumn(refbeamnoColumn);
258
259  ScalarColumnDesc<uInt> flagrowColumn("FLAGROW");
260  flagrowColumn.setDefault(uInt(0));
261  td.addColumn(flagrowColumn);
262
263  td.addColumn(ScalarColumnDesc<Double>("TIME"));
264  TableMeasRefDesc measRef(MEpoch::UTC); // UTC as default
265  TableMeasValueDesc measVal(td, "TIME");
266  TableMeasDesc<MEpoch> mepochCol(measVal, measRef);
267  mepochCol.write(td);
268
269  td.addColumn(ScalarColumnDesc<Double>("INTERVAL"));
270
271  td.addColumn(ScalarColumnDesc<String>("SRCNAME"));
272  // Type of source (on=0, off=1, other=-1)
273  ScalarColumnDesc<Int> stypeColumn("SRCTYPE");
274  stypeColumn.setDefault(Int(-1));
275  td.addColumn(stypeColumn);
276  td.addColumn(ScalarColumnDesc<String>("FIELDNAME"));
277
278  //The actual Data Vectors
279  td.addColumn(ArrayColumnDesc<Float>("SPECTRA"));
280  td.addColumn(ArrayColumnDesc<uChar>("FLAGTRA"));
281  td.addColumn(ArrayColumnDesc<Float>("TSYS"));
282
283  td.addColumn(ArrayColumnDesc<Double>("DIRECTION",
284                                       IPosition(1,2),
285                                       ColumnDesc::Direct));
286  TableMeasRefDesc mdirRef(MDirection::J2000); // default
287  TableMeasValueDesc tmvdMDir(td, "DIRECTION");
288  // the TableMeasDesc gives the column a type
289  TableMeasDesc<MDirection> mdirCol(tmvdMDir, mdirRef);
290  // a uder set table type e.g. GALCTIC, B1950 ...
291  td.rwKeywordSet().define("DIRECTIONREF", String("J2000"));
292  // writing create the measure column
293  mdirCol.write(td);
294  td.addColumn(ScalarColumnDesc<Float>("AZIMUTH"));
295  td.addColumn(ScalarColumnDesc<Float>("ELEVATION"));
296  td.addColumn(ScalarColumnDesc<Float>("OPACITY"));
297
298  td.addColumn(ScalarColumnDesc<uInt>("TCAL_ID"));
299  ScalarColumnDesc<Int> fitColumn("FIT_ID");
300  fitColumn.setDefault(Int(-1));
301  td.addColumn(fitColumn);
302
303  td.addColumn(ScalarColumnDesc<uInt>("FOCUS_ID"));
304  td.addColumn(ScalarColumnDesc<uInt>("WEATHER_ID"));
305
306  // columns which just get dragged along, as they aren't used in asap
307  td.addColumn(ScalarColumnDesc<Double>("SRCVELOCITY"));
308  td.addColumn(ArrayColumnDesc<Double>("SRCPROPERMOTION"));
309  td.addColumn(ArrayColumnDesc<Double>("SRCDIRECTION"));
310  td.addColumn(ArrayColumnDesc<Double>("SCANRATE"));
311
312  td.rwKeywordSet().define("OBSMODE", String(""));
313
314  // Now create Table SetUp from the description.
315  SetupNewTable aNewTab(generateName(), td, Table::Scratch);
316  table_ = Table(aNewTab, type_, 0);
317  originalTable_ = table_;
318}
319
320void Scantable::attach()
321{
322  timeCol_.attach(table_, "TIME");
323  srcnCol_.attach(table_, "SRCNAME");
324  srctCol_.attach(table_, "SRCTYPE");
325  specCol_.attach(table_, "SPECTRA");
326  flagsCol_.attach(table_, "FLAGTRA");
327  tsysCol_.attach(table_, "TSYS");
328  cycleCol_.attach(table_,"CYCLENO");
329  scanCol_.attach(table_, "SCANNO");
330  beamCol_.attach(table_, "BEAMNO");
331  ifCol_.attach(table_, "IFNO");
332  polCol_.attach(table_, "POLNO");
333  integrCol_.attach(table_, "INTERVAL");
334  azCol_.attach(table_, "AZIMUTH");
335  elCol_.attach(table_, "ELEVATION");
336  dirCol_.attach(table_, "DIRECTION");
337  fldnCol_.attach(table_, "FIELDNAME");
338  rbeamCol_.attach(table_, "REFBEAMNO");
339
340  mweatheridCol_.attach(table_,"WEATHER_ID");
341  mfitidCol_.attach(table_,"FIT_ID");
342  mfreqidCol_.attach(table_, "FREQ_ID");
343  mtcalidCol_.attach(table_, "TCAL_ID");
344  mfocusidCol_.attach(table_, "FOCUS_ID");
345  mmolidCol_.attach(table_, "MOLECULE_ID");
346
347  //Add auxiliary column for row-based flagging (CAS-1433 Wataru Kawasaki)
348  attachAuxColumnDef(flagrowCol_, "FLAGROW", 0);
349
350}
351
352template<class T, class T2>
353void Scantable::attachAuxColumnDef(ScalarColumn<T>& col,
354                                   const String& colName,
355                                   const T2& defValue)
356{
357  try {
358    col.attach(table_, colName);
359  } catch (TableError& err) {
360    String errMesg = err.getMesg();
361    if (errMesg == "Table column " + colName + " is unknown") {
362      table_.addColumn(ScalarColumnDesc<T>(colName));
363      col.attach(table_, colName);
364      col.fillColumn(static_cast<T>(defValue));
365    } else {
366      throw;
367    }
368  } catch (...) {
369    throw;
370  }
371}
372
373template<class T, class T2>
374void Scantable::attachAuxColumnDef(ArrayColumn<T>& col,
375                                   const String& colName,
376                                   const Array<T2>& defValue)
377{
378  try {
379    col.attach(table_, colName);
380  } catch (TableError& err) {
381    String errMesg = err.getMesg();
382    if (errMesg == "Table column " + colName + " is unknown") {
383      table_.addColumn(ArrayColumnDesc<T>(colName));
384      col.attach(table_, colName);
385
386      int size = 0;
387      ArrayIterator<T2>& it = defValue.begin();
388      while (it != defValue.end()) {
389        ++size;
390        ++it;
391      }
392      IPosition ip(1, size);
393      Array<T>& arr(ip);
394      for (int i = 0; i < size; ++i)
395        arr[i] = static_cast<T>(defValue[i]);
396
397      col.fillColumn(arr);
398    } else {
399      throw;
400    }
401  } catch (...) {
402    throw;
403  }
404}
405
406void Scantable::setHeader(const STHeader& sdh)
407{
408  table_.rwKeywordSet().define("nIF", sdh.nif);
409  table_.rwKeywordSet().define("nBeam", sdh.nbeam);
410  table_.rwKeywordSet().define("nPol", sdh.npol);
411  table_.rwKeywordSet().define("nChan", sdh.nchan);
412  table_.rwKeywordSet().define("Observer", sdh.observer);
413  table_.rwKeywordSet().define("Project", sdh.project);
414  table_.rwKeywordSet().define("Obstype", sdh.obstype);
415  table_.rwKeywordSet().define("AntennaName", sdh.antennaname);
416  table_.rwKeywordSet().define("AntennaPosition", sdh.antennaposition);
417  table_.rwKeywordSet().define("Equinox", sdh.equinox);
418  table_.rwKeywordSet().define("FreqRefFrame", sdh.freqref);
419  table_.rwKeywordSet().define("FreqRefVal", sdh.reffreq);
420  table_.rwKeywordSet().define("Bandwidth", sdh.bandwidth);
421  table_.rwKeywordSet().define("UTC", sdh.utc);
422  table_.rwKeywordSet().define("FluxUnit", sdh.fluxunit);
423  table_.rwKeywordSet().define("Epoch", sdh.epoch);
424  table_.rwKeywordSet().define("POLTYPE", sdh.poltype);
425}
426
427STHeader Scantable::getHeader() const
428{
429  STHeader sdh;
430  table_.keywordSet().get("nBeam",sdh.nbeam);
431  table_.keywordSet().get("nIF",sdh.nif);
432  table_.keywordSet().get("nPol",sdh.npol);
433  table_.keywordSet().get("nChan",sdh.nchan);
434  table_.keywordSet().get("Observer", sdh.observer);
435  table_.keywordSet().get("Project", sdh.project);
436  table_.keywordSet().get("Obstype", sdh.obstype);
437  table_.keywordSet().get("AntennaName", sdh.antennaname);
438  table_.keywordSet().get("AntennaPosition", sdh.antennaposition);
439  table_.keywordSet().get("Equinox", sdh.equinox);
440  table_.keywordSet().get("FreqRefFrame", sdh.freqref);
441  table_.keywordSet().get("FreqRefVal", sdh.reffreq);
442  table_.keywordSet().get("Bandwidth", sdh.bandwidth);
443  table_.keywordSet().get("UTC", sdh.utc);
444  table_.keywordSet().get("FluxUnit", sdh.fluxunit);
445  table_.keywordSet().get("Epoch", sdh.epoch);
446  table_.keywordSet().get("POLTYPE", sdh.poltype);
447  return sdh;
448}
449
450void Scantable::setSourceType( int stype )
451{
452  if ( stype < 0 || stype > 1 )
453    throw(AipsError("Illegal sourcetype."));
454  TableVector<Int> tabvec(table_, "SRCTYPE");
455  tabvec = Int(stype);
456}
457
458void Scantable::setSourceName( const std::string& name )
459{
460  TableVector<String> tabvec(table_, "SRCNAME");
461  tabvec = name;
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
488  std::string Scantable::formatDirection(const MDirection& md, Int prec) const
489{
490  Vector<Double> t = md.getAngle(Unit(String("rad"))).getValue();
491  if (prec<0)
492    prec = 7;
493
494  String ref = md.getRefString();
495  MVAngle mvLon(t[0]);
496  String sLon = mvLon.string(MVAngle::TIME,prec);
497  uInt tp = md.getRef().getType();
498  if (tp == MDirection::GALACTIC ||
499      tp == MDirection::SUPERGAL ) {
500    sLon = mvLon(0.0).string(MVAngle::ANGLE_CLEAN,prec);
501  }
502  MVAngle mvLat(t[1]);
503  String sLat = mvLat.string(MVAngle::ANGLE+MVAngle::DIG2,prec);
504  return  ref + String(" ") + sLon + String(" ") + sLat;
505}
506
507
508std::string Scantable::getFluxUnit() const
509{
510  return table_.keywordSet().asString("FluxUnit");
511}
512
513void Scantable::setFluxUnit(const std::string& unit)
514{
515  String tmp(unit);
516  Unit tU(tmp);
517  if (tU==Unit("K") || tU==Unit("Jy")) {
518     table_.rwKeywordSet().define(String("FluxUnit"), tmp);
519  } else {
520     throw AipsError("Illegal unit - must be compatible with Jy or K");
521  }
522}
523
524void Scantable::setInstrument(const std::string& name)
525{
526  bool throwIt = true;
527  // create an Instrument to see if this is valid
528  STAttr::convertInstrument(name, throwIt);
529  String nameU(name);
530  nameU.upcase();
531  table_.rwKeywordSet().define(String("AntennaName"), nameU);
532}
533
534void Scantable::setFeedType(const std::string& feedtype)
535{
536  if ( Scantable::factories_.find(feedtype) ==  Scantable::factories_.end() ) {
537    std::string msg = "Illegal feed type "+ feedtype;
538    throw(casa::AipsError(msg));
539  }
540  table_.rwKeywordSet().define(String("POLTYPE"), feedtype);
541}
542
543MPosition Scantable::getAntennaPosition() const
544{
545  Vector<Double> antpos;
546  table_.keywordSet().get("AntennaPosition", antpos);
547  MVPosition mvpos(antpos(0),antpos(1),antpos(2));
548  return MPosition(mvpos);
549}
550
551void Scantable::makePersistent(const std::string& filename)
552{
553  String inname(filename);
554  Path path(inname);
555  /// @todo reindex SCANNO, recompute nbeam, nif, npol
556  inname = path.expandedName();
557  // 2011/03/04 TN
558  // We can comment out this workaround since the essential bug is
559  // fixed in casacore (r20889 in google code).
560  table_.deepCopy(inname, Table::New);
561//   // WORKAROUND !!! for Table bug
562//   // Remove when fixed in casacore
563//   if ( table_.tableType() == Table::Memory  && !selector_.empty() ) {
564//     Table tab = table_.copyToMemoryTable(generateName());
565//     tab.deepCopy(inname, Table::New);
566//     tab.markForDelete();
567//
568//   } else {
569//     table_.deepCopy(inname, Table::New);
570//   }
571}
572
573int Scantable::nbeam( int scanno ) const
574{
575  if ( scanno < 0 ) {
576    Int n;
577    table_.keywordSet().get("nBeam",n);
578    return int(n);
579  } else {
580    // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
581    Table t = table_(table_.col("SCANNO") == scanno);
582    ROTableRow row(t);
583    const TableRecord& rec = row.get(0);
584    Table subt = t( t.col("IFNO") == Int(rec.asuInt("IFNO"))
585                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
586                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
587    ROTableVector<uInt> v(subt, "BEAMNO");
588    return int(v.nelements());
589  }
590  return 0;
591}
592
593int Scantable::nif( int scanno ) const
594{
595  if ( scanno < 0 ) {
596    Int n;
597    table_.keywordSet().get("nIF",n);
598    return int(n);
599  } else {
600    // take the first POLNO,BEAMNO,CYCLENO as nbeam shouldn't vary with these
601    Table t = table_(table_.col("SCANNO") == scanno);
602    ROTableRow row(t);
603    const TableRecord& rec = row.get(0);
604    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
605                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
606                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
607    if ( subt.nrow() == 0 ) return 0;
608    ROTableVector<uInt> v(subt, "IFNO");
609    return int(v.nelements());
610  }
611  return 0;
612}
613
614int Scantable::npol( int scanno ) const
615{
616  if ( scanno < 0 ) {
617    Int n;
618    table_.keywordSet().get("nPol",n);
619    return n;
620  } else {
621    // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
622    Table t = table_(table_.col("SCANNO") == scanno);
623    ROTableRow row(t);
624    const TableRecord& rec = row.get(0);
625    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
626                    && t.col("IFNO") == Int(rec.asuInt("IFNO"))
627                    && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
628    if ( subt.nrow() == 0 ) return 0;
629    ROTableVector<uInt> v(subt, "POLNO");
630    return int(v.nelements());
631  }
632  return 0;
633}
634
635int Scantable::ncycle( int scanno ) const
636{
637  if ( scanno < 0 ) {
638    Block<String> cols(2);
639    cols[0] = "SCANNO";
640    cols[1] = "CYCLENO";
641    TableIterator it(table_, cols);
642    int n = 0;
643    while ( !it.pastEnd() ) {
644      ++n;
645      ++it;
646    }
647    return n;
648  } else {
649    Table t = table_(table_.col("SCANNO") == scanno);
650    ROTableRow row(t);
651    const TableRecord& rec = row.get(0);
652    Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
653                    && t.col("POLNO") == Int(rec.asuInt("POLNO"))
654                    && t.col("IFNO") == Int(rec.asuInt("IFNO")) );
655    if ( subt.nrow() == 0 ) return 0;
656    return int(subt.nrow());
657  }
658  return 0;
659}
660
661
662int Scantable::nrow( int scanno ) const
663{
664  return int(table_.nrow());
665}
666
667int Scantable::nchan( int ifno ) const
668{
669  if ( ifno < 0 ) {
670    Int n;
671    table_.keywordSet().get("nChan",n);
672    return int(n);
673  } else {
674    // take the first SCANNO,POLNO,BEAMNO,CYCLENO as nbeam shouldn't
675    // vary with these
676    Table t = table_(table_.col("IFNO") == ifno, 1);
677    if ( t.nrow() == 0 ) return 0;
678    ROArrayColumn<Float> v(t, "SPECTRA");
679    return v.shape(0)(0);
680  }
681  return 0;
682}
683
684int Scantable::nscan() const {
685  Vector<uInt> scannos(scanCol_.getColumn());
686  uInt nout = genSort( scannos, Sort::Ascending,
687                       Sort::QuickSort|Sort::NoDuplicates );
688  return int(nout);
689}
690
691int Scantable::getChannels(int whichrow) const
692{
693  return specCol_.shape(whichrow)(0);
694}
695
696int Scantable::getBeam(int whichrow) const
697{
698  return beamCol_(whichrow);
699}
700
701std::vector<uint> Scantable::getNumbers(const ScalarColumn<uInt>& col) const
702{
703  Vector<uInt> nos(col.getColumn());
704  uInt n = genSort( nos, Sort::Ascending, Sort::QuickSort|Sort::NoDuplicates );
705  nos.resize(n, True);
706  std::vector<uint> stlout;
707  nos.tovector(stlout);
708  return stlout;
709}
710
711int Scantable::getIF(int whichrow) const
712{
713  return ifCol_(whichrow);
714}
715
716int Scantable::getPol(int whichrow) const
717{
718  return polCol_(whichrow);
719}
720
721std::string Scantable::formatTime(const MEpoch& me, bool showdate) const
722{
723  return formatTime(me, showdate, 0);
724}
725
726std::string Scantable::formatTime(const MEpoch& me, bool showdate, uInt prec) const
727{
728  MVTime mvt(me.getValue());
729  if (showdate)
730    //mvt.setFormat(MVTime::YMD);
731    mvt.setFormat(MVTime::YMD, prec);
732  else
733    //mvt.setFormat(MVTime::TIME);
734    mvt.setFormat(MVTime::TIME, prec);
735  ostringstream oss;
736  oss << mvt;
737  return String(oss);
738}
739
740void Scantable::calculateAZEL()
741
742  LogIO os( LogOrigin( "Scantable", "calculateAZEL()", WHERE ) ) ;
743  MPosition mp = getAntennaPosition();
744  MEpoch::ROScalarColumn timeCol(table_, "TIME");
745  ostringstream oss;
746  oss << mp;
747  os << "Computed azimuth/elevation using " << endl
748     << String(oss) << endl;
749  for (Int i=0; i<nrow(); ++i) {
750    MEpoch me = timeCol(i);
751    MDirection md = getDirection(i);
752    os  << " Time: " << formatTime(me,False)
753        << " Direction: " << formatDirection(md)
754         << endl << "     => ";
755    MeasFrame frame(mp, me);
756    Vector<Double> azel =
757        MDirection::Convert(md, MDirection::Ref(MDirection::AZEL,
758                                                frame)
759                            )().getAngle("rad").getValue();
760    azCol_.put(i,Float(azel[0]));
761    elCol_.put(i,Float(azel[1]));
762    os << "azel: " << azel[0]/C::pi*180.0 << " "
763       << azel[1]/C::pi*180.0 << " (deg)" << LogIO::POST;
764  }
765}
766
767void Scantable::clip(const Float uthres, const Float dthres, bool clipoutside, bool unflag)
768{
769  Vector<uInt> flagrow = flagrowCol_.getColumn();
770  for (uInt i=0; i<table_.nrow(); ++i) {
771    // apply flag only when specified row is vaild
772    if (flagrow[i] == 0) {
773      Vector<uChar> flgs = flagsCol_(i);
774      srchChannelsToClip(i, uthres, dthres, clipoutside, unflag, flgs);
775      flagsCol_.put(i, flgs);
776    }
777  }
778}
779
780std::vector<bool> Scantable::getClipMask(int whichrow, const Float uthres, const Float dthres, bool clipoutside, bool unflag)
781{
782  Vector<uChar> flags;
783  flagsCol_.get(uInt(whichrow), flags);
784  srchChannelsToClip(uInt(whichrow), uthres, dthres, clipoutside, unflag, flags);
785  Vector<Bool> bflag(flags.shape());
786  convertArray(bflag, flags);
787  //bflag = !bflag;
788
789  std::vector<bool> mask;
790  bflag.tovector(mask);
791  return mask;
792}
793
794void Scantable::srchChannelsToClip(uInt whichrow, const Float uthres, const Float dthres, bool clipoutside, bool unflag,
795                                   Vector<uChar> flgs)
796{
797    Vector<Float> spcs = specCol_(whichrow);
798    uInt nchannel = spcs.nelements();
799    if (spcs.nelements() != nchannel) {
800      throw(AipsError("Data has incorrect number of channels"));
801    }
802    uChar userflag = 1 << 7;
803    if (unflag) {
804      userflag = 0 << 7;
805    }
806    if (clipoutside) {
807      for (uInt j = 0; j < nchannel; ++j) {
808        Float spc = spcs(j);
809        if ((spc >= uthres) || (spc <= dthres)) {
810          flgs(j) = userflag;
811        }
812      }
813    } else {
814      for (uInt j = 0; j < nchannel; ++j) {
815        Float spc = spcs(j);
816        if ((spc < uthres) && (spc > dthres)) {
817          flgs(j) = userflag;
818        }
819      }
820    }
821}
822
823
824void Scantable::flag( int whichrow, const std::vector<bool>& msk, bool unflag ) {
825  std::vector<bool>::const_iterator it;
826  uInt ntrue = 0;
827  if (whichrow >= int(table_.nrow()) ) {
828    throw(AipsError("Invalid row number"));
829  }
830  for (it = msk.begin(); it != msk.end(); ++it) {
831    if ( *it ) {
832      ntrue++;
833    }
834  }
835  //if ( selector_.empty()  && (msk.size() == 0 || msk.size() == ntrue) )
836  if ( whichrow == -1 && !unflag && selector_.empty() && (msk.size() == 0 || msk.size() == ntrue) )
837    throw(AipsError("Trying to flag whole scantable."));
838  uChar userflag = 1 << 7;
839  if ( unflag ) {
840    userflag = 0 << 7;
841  }
842  if (whichrow > -1 ) {
843    // apply flag only when specified row is vaild
844    if (flagrowCol_(whichrow) == 0) {
845      applyChanFlag(uInt(whichrow), msk, userflag);
846    }
847  } else {
848    Vector<uInt> flagrow = flagrowCol_.getColumn();
849    for ( uInt i=0; i<table_.nrow(); ++i) {
850      // apply flag only when specified row is vaild
851      if (flagrow[i] == 0) {
852        applyChanFlag(i, msk, userflag);
853      }
854    }
855  }
856}
857
858void Scantable::applyChanFlag( uInt whichrow, const std::vector<bool>& msk, uChar flagval )
859{
860  if (whichrow >= table_.nrow() ) {
861    throw( casa::indexError<int>( whichrow, "asap::Scantable::applyChanFlag: Invalid row number" ) );
862  }
863  Vector<uChar> flgs = flagsCol_(whichrow);
864  if ( msk.size() == 0 ) {
865    flgs = flagval;
866    flagsCol_.put(whichrow, flgs);
867    return;
868  }
869  if ( int(msk.size()) != nchan( getIF(whichrow) ) ) {
870    throw(AipsError("Mask has incorrect number of channels."));
871  }
872  if ( flgs.nelements() != msk.size() ) {
873    throw(AipsError("Mask has incorrect number of channels."
874                    " Probably varying with IF. Please flag per IF"));
875  }
876  std::vector<bool>::const_iterator it;
877  uInt j = 0;
878  for (it = msk.begin(); it != msk.end(); ++it) {
879    if ( *it ) {
880      flgs(j) = flagval;
881    }
882    ++j;
883  }
884  flagsCol_.put(whichrow, flgs);
885}
886
887void Scantable::flagRow(const std::vector<uInt>& rows, bool unflag)
888{
889  if (selector_.empty() && (rows.size() == table_.nrow()) && !unflag)
890    throw(AipsError("Trying to flag whole scantable."));
891
892  uInt rowflag = (unflag ? 0 : 1);
893  std::vector<uInt>::const_iterator it;
894  for (it = rows.begin(); it != rows.end(); ++it)
895    flagrowCol_.put(*it, rowflag);
896}
897
898std::vector<bool> Scantable::getMask(int whichrow) const
899{
900  Vector<uChar> flags;
901  flagsCol_.get(uInt(whichrow), flags);
902  Vector<Bool> bflag(flags.shape());
903  convertArray(bflag, flags);
904  bflag = !bflag;
905  std::vector<bool> mask;
906  bflag.tovector(mask);
907  return mask;
908}
909
910std::vector<float> Scantable::getSpectrum( int whichrow,
911                                           const std::string& poltype ) const
912{
913  LogIO os( LogOrigin( "Scantable", "getSpectrum()", WHERE ) ) ;
914
915  String ptype = poltype;
916  if (poltype == "" ) ptype = getPolType();
917  if ( whichrow  < 0 || whichrow >= nrow() )
918    throw(AipsError("Illegal row number."));
919  std::vector<float> out;
920  Vector<Float> arr;
921  uInt requestedpol = polCol_(whichrow);
922  String basetype = getPolType();
923  if ( ptype == basetype ) {
924    specCol_.get(whichrow, arr);
925  } else {
926    CountedPtr<STPol> stpol(STPol::getPolClass(Scantable::factories_,
927                                               basetype));
928    uInt row = uInt(whichrow);
929    stpol->setSpectra(getPolMatrix(row));
930    Float fang,fhand;
931    fang = focusTable_.getTotalAngle(mfocusidCol_(row));
932    fhand = focusTable_.getFeedHand(mfocusidCol_(row));
933    stpol->setPhaseCorrections(fang, fhand);
934    arr = stpol->getSpectrum(requestedpol, ptype);
935  }
936  if ( arr.nelements() == 0 )
937   
938    os << "Not enough polarisations present to do the conversion."
939       << LogIO::POST;
940  arr.tovector(out);
941  return out;
942}
943
944void Scantable::setSpectrum( const std::vector<float>& spec,
945                                   int whichrow )
946{
947  Vector<Float> spectrum(spec);
948  Vector<Float> arr;
949  specCol_.get(whichrow, arr);
950  if ( spectrum.nelements() != arr.nelements() )
951    throw AipsError("The spectrum has incorrect number of channels.");
952  specCol_.put(whichrow, spectrum);
953}
954
955
956String Scantable::generateName()
957{
958  return (File::newUniqueName("./","temp")).baseName();
959}
960
961const casa::Table& Scantable::table( ) const
962{
963  return table_;
964}
965
966casa::Table& Scantable::table( )
967{
968  return table_;
969}
970
971std::string Scantable::getPolType() const
972{
973  return table_.keywordSet().asString("POLTYPE");
974}
975
976void Scantable::unsetSelection()
977{
978  table_ = originalTable_;
979  attach();
980  selector_.reset();
981}
982
983void Scantable::setSelection( const STSelector& selection )
984{
985  Table tab = const_cast<STSelector&>(selection).apply(originalTable_);
986  if ( tab.nrow() == 0 ) {
987    throw(AipsError("Selection contains no data. Not applying it."));
988  }
989  table_ = tab;
990  attach();
991//   tab.rwKeywordSet().define("nBeam",(Int)(getBeamNos().size())) ;
992//   vector<uint> selectedIFs = getIFNos() ;
993//   Int newnIF = selectedIFs.size() ;
994//   tab.rwKeywordSet().define("nIF",newnIF) ;
995//   if ( newnIF != 0 ) {
996//     Int newnChan = 0 ;
997//     for ( Int i = 0 ; i < newnIF ; i++ ) {
998//       Int nChan = nchan( selectedIFs[i] ) ;
999//       if ( newnChan > nChan )
1000//         newnChan = nChan ;
1001//     }
1002//     tab.rwKeywordSet().define("nChan",newnChan) ;
1003//   }
1004//   tab.rwKeywordSet().define("nPol",(Int)(getPolNos().size())) ;
1005  selector_ = selection;
1006}
1007
1008
1009std::string Scantable::headerSummary()
1010{
1011  // Format header info
1012//   STHeader sdh;
1013//   sdh = getHeader();
1014//   sdh.print();
1015  ostringstream oss;
1016  oss.flags(std::ios_base::left);
1017  String tmp;
1018  // Project
1019  table_.keywordSet().get("Project", tmp);
1020  oss << setw(15) << "Project:" << tmp << endl;
1021  // Observation date
1022  oss << setw(15) << "Obs Date:" << getTime(-1,true) << endl;
1023  // Observer
1024  oss << setw(15) << "Observer:"
1025      << table_.keywordSet().asString("Observer") << endl;
1026  // Antenna Name
1027  table_.keywordSet().get("AntennaName", tmp);
1028  oss << setw(15) << "Antenna Name:" << tmp << endl;
1029  // Obs type
1030  table_.keywordSet().get("Obstype", tmp);
1031  // Records (nrow)
1032  oss << setw(15) << "Data Records:" << table_.nrow() << " rows" << endl;
1033  oss << setw(15) << "Obs. Type:" << tmp << endl;
1034  // Beams, IFs, Polarizations, and Channels
1035  oss << setw(15) << "Beams:" << setw(4) << nbeam() << endl
1036      << setw(15) << "IFs:" << setw(4) << nif() << endl
1037      << setw(15) << "Polarisations:" << setw(4) << npol()
1038      << "(" << getPolType() << ")" << endl
1039      << setw(15) << "Channels:" << nchan() << endl;
1040  // Flux unit
1041  table_.keywordSet().get("FluxUnit", tmp);
1042  oss << setw(15) << "Flux Unit:" << tmp << endl;
1043  // Abscissa Unit
1044  oss << setw(15) << "Abscissa:" << getAbcissaLabel(0) << endl;
1045  // Selection
1046  oss << selector_.print() << endl;
1047
1048  return String(oss);
1049}
1050
1051void Scantable::summary( const std::string& filename )
1052{
1053  ostringstream oss;
1054  ofstream ofs;
1055  LogIO ols(LogOrigin("Scantable", "summary", WHERE));
1056
1057  if (filename != "")
1058    ofs.open( filename.c_str(),  ios::out );
1059
1060  oss << endl;
1061  oss << asap::SEPERATOR << endl;
1062  oss << " Scan Table Summary" << endl;
1063  oss << asap::SEPERATOR << endl;
1064
1065  // Format header info
1066  oss << headerSummary();
1067  oss << endl;
1068
1069  if (table_.nrow() <= 0){
1070    oss << asap::SEPERATOR << endl;
1071    oss << "The MAIN table is empty: there are no data!!!" << endl;
1072    oss << asap::SEPERATOR << endl;
1073
1074    ols << String(oss) << LogIO::POST;
1075    if (ofs) {
1076      ofs << String(oss) << flush;
1077      ofs.close();
1078    }
1079    return;
1080  }
1081
1082
1083
1084  // main table
1085  String dirtype = "Position ("
1086                  + getDirectionRefString()
1087                  + ")";
1088  oss.flags(std::ios_base::left);
1089  oss << setw(5) << "Scan"
1090      << setw(15) << "Source"
1091      << setw(35) << "Time range"
1092      << setw(2) << "" << setw(7) << "Int[s]"
1093      << setw(7) << "Record"
1094      << setw(8) << "SrcType"
1095      << setw(8) << "FreqIDs"
1096      << setw(7) << "MolIDs" << endl;
1097  oss << setw(7)<< "" << setw(6) << "Beam"
1098      << setw(23) << dirtype << endl;
1099
1100  oss << asap::SEPERATOR << endl;
1101
1102  // Flush summary and clear up the string
1103  ols << String(oss) << LogIO::POST;
1104  if (ofs) ofs << String(oss) << flush;
1105  oss.str("");
1106  oss.clear();
1107
1108
1109  // Get Freq_ID map
1110  ROScalarColumn<uInt> ftabIds(frequencies().table(), "ID");
1111  Int nfid = ftabIds.nrow();
1112  if (nfid <= 0){
1113    oss << "FREQUENCIES subtable is empty: there are no data!!!" << endl;
1114    oss << asap::SEPERATOR << endl;
1115
1116    ols << String(oss) << LogIO::POST;
1117    if (ofs) {
1118      ofs << String(oss) << flush;
1119      ofs.close();
1120    }
1121    return;
1122  }
1123  // Storages of overall IFNO, POLNO, and nchan per FREQ_ID
1124  // the orders are identical to ID in FREQ subtable
1125  Block< Vector<uInt> > ifNos(nfid), polNos(nfid);
1126  Vector<Int> fIdchans(nfid,-1);
1127  Vector<Double> fIdfreq0(nfid,-1);
1128  Vector<Double> fIdfcent(nfid,-1);
1129  map<uInt, Int> fidMap;  // (FREQ_ID, row # in FREQ subtable) pair
1130  for (Int i=0; i < nfid; i++){
1131   // fidMap[freqId] returns row number in FREQ subtable
1132   fidMap.insert(pair<uInt, Int>(ftabIds(i),i));
1133   ifNos[i] = Vector<uInt>();
1134   polNos[i] = Vector<uInt>();
1135  }
1136
1137  TableIterator iter(table_, "SCANNO");
1138
1139  // Vars for keeping track of time, freqids, molIds in a SCANNO
1140  //Vector<uInt> freqids;
1141  //Vector<uInt> molids;
1142  Vector<uInt> beamids(1,0);
1143  Vector<MDirection> beamDirs;
1144  Vector<Int> stypeids(1,0);
1145  Vector<String> stypestrs;
1146  Int nfreq(1);
1147  Int nmol(1);
1148  uInt nbeam(1);
1149  uInt nstype(1);
1150
1151  Double btime(0.0), etime(0.0);
1152  Double meanIntTim(0.0);
1153
1154  uInt currFreqId(0), ftabRow(0);
1155  Int iflen(0), pollen(0);
1156
1157  while (!iter.pastEnd()) {
1158    Table subt = iter.table();
1159    uInt snrow = subt.nrow();
1160    ROTableRow row(subt);
1161    const TableRecord& rec = row.get(0);
1162
1163    // relevant columns
1164    ROScalarColumn<Double> mjdCol(subt,"TIME");
1165    ROScalarColumn<Double> intervalCol(subt,"INTERVAL");
1166    MDirection::ROScalarColumn dirCol(subt,"DIRECTION");
1167
1168    ScalarColumn<uInt> freqIdCol(subt,"FREQ_ID");
1169    ScalarColumn<uInt> molIdCol(subt,"MOLECULE_ID");
1170    ROScalarColumn<uInt> beamCol(subt,"BEAMNO");
1171    ROScalarColumn<Int> stypeCol(subt,"SRCTYPE");
1172
1173    ROScalarColumn<uInt> ifNoCol(subt,"IFNO");
1174    ROScalarColumn<uInt> polNoCol(subt,"POLNO");
1175
1176
1177    // Times
1178    meanIntTim = sum(intervalCol.getColumn()) / (double) snrow;
1179    minMax(btime, etime, mjdCol.getColumn());
1180    double shiftInDay(0.5*meanIntTim/C::day);
1181    btime -= shiftInDay;
1182    etime += shiftInDay;
1183
1184    // MOLECULE_ID and FREQ_ID
1185    Vector<uInt> molids(getNumbers(molIdCol));
1186    molids.shape(nmol);
1187
1188    Vector<uInt> freqids(getNumbers(freqIdCol));
1189    freqids.shape(nfreq);
1190
1191    // Add first beamid, and srcNames
1192    beamids.resize(1,False);
1193    beamDirs.resize(1,False);
1194    beamids(0)=beamCol(0);
1195    beamDirs(0)=dirCol(0);
1196    nbeam = 1;
1197
1198    stypeids.resize(1,False);
1199    stypeids(0)=stypeCol(0);
1200    nstype = 1;
1201
1202    // Global listings of nchan/IFNO/POLNO per FREQ_ID
1203    currFreqId=freqIdCol(0);
1204    ftabRow = fidMap[currFreqId];
1205    // Assumes an identical number of channels per FREQ_ID
1206    if (fIdchans(ftabRow) < 0 ) {
1207      RORecordFieldPtr< Array<Float> > spec(rec, "SPECTRA");
1208      fIdchans(ftabRow)=(*spec).shape()(0);
1209    }
1210    if (fIdfreq0(ftabRow) < 0 ) {
1211      SpectralCoordinate spc = frequencies().getSpectralCoordinate(ftabRow);
1212      Double fs, fe;
1213      spc.toWorld(fs, 0);
1214      spc.toWorld(fe, fIdchans(ftabRow)-1);
1215      fIdfreq0(ftabRow) = fs;
1216      fIdfcent(ftabRow) = 0.5 * ( fs + fe );
1217    }
1218    // Should keep ifNos and polNos form the previous SCANNO
1219    if ( !anyEQ(ifNos[ftabRow],ifNoCol(0)) ) {
1220      ifNos[ftabRow].shape(iflen);
1221      iflen++;
1222      ifNos[ftabRow].resize(iflen,True);
1223      ifNos[ftabRow](iflen-1) = ifNoCol(0);
1224    }
1225    if ( !anyEQ(polNos[ftabRow],polNoCol(0)) ) {
1226      polNos[ftabRow].shape(pollen);
1227      pollen++;
1228      polNos[ftabRow].resize(pollen,True);
1229      polNos[ftabRow](pollen-1) = polNoCol(0);
1230    }
1231
1232    for (uInt i=1; i < snrow; i++){
1233      // Need to list BEAMNO and DIRECTION in the same order
1234      if ( !anyEQ(beamids,beamCol(i)) ) {
1235        nbeam++;
1236        beamids.resize(nbeam,True);
1237        beamids(nbeam-1)=beamCol(i);
1238        beamDirs.resize(nbeam,True);
1239        beamDirs(nbeam-1)=dirCol(i);
1240      }
1241
1242      // SRCTYPE is Int (getNumber takes only uInt)
1243      if ( !anyEQ(stypeids,stypeCol(i)) ) {
1244        nstype++;
1245        stypeids.resize(nstype,True);
1246        stypeids(nstype-1)=stypeCol(i);
1247      }
1248
1249      // Global listings of nchan/IFNO/POLNO per FREQ_ID
1250      currFreqId=freqIdCol(i);
1251      ftabRow = fidMap[currFreqId];
1252      if (fIdchans(ftabRow) < 0 ) {
1253        const TableRecord& rec = row.get(i);
1254        RORecordFieldPtr< Array<Float> > spec(rec, "SPECTRA");
1255        fIdchans(ftabRow) = (*spec).shape()(0);
1256      }
1257      if (fIdfreq0(ftabRow) < 0 ) {
1258        SpectralCoordinate spc = frequencies().getSpectralCoordinate(ftabRow);
1259        Double fs, fe;
1260        spc.toWorld(fs, 0);
1261        spc.toWorld(fe, fIdchans(ftabRow)-1);
1262        fIdfreq0(ftabRow) = fs;
1263        fIdfcent(ftabRow) = 5.e-1 * ( fs + fe );
1264      }
1265      if ( !anyEQ(ifNos[ftabRow],ifNoCol(i)) ) {
1266        ifNos[ftabRow].shape(iflen);
1267        iflen++;
1268        ifNos[ftabRow].resize(iflen,True);
1269        ifNos[ftabRow](iflen-1) = ifNoCol(i);
1270      }
1271      if ( !anyEQ(polNos[ftabRow],polNoCol(i)) ) {
1272        polNos[ftabRow].shape(pollen);
1273        pollen++;
1274        polNos[ftabRow].resize(pollen,True);
1275        polNos[ftabRow](pollen-1) = polNoCol(i);
1276      }
1277    } // end of row iteration
1278
1279    stypestrs.resize(nstype,False);
1280    for (uInt j=0; j < nstype; j++)
1281      stypestrs(j) = SrcType::getName(stypeids(j));
1282
1283    // Format Scan summary
1284    oss << setw(4) << std::right << rec.asuInt("SCANNO")
1285        << std::left << setw(1) << ""
1286        << setw(15) << rec.asString("SRCNAME")
1287        << setw(21) << MVTime(btime).string(MVTime::YMD,8)
1288        << setw(3) << " - " << MVTime(etime).string(MVTime::TIME,8)
1289        << setw(3) << "" << setw(6) << meanIntTim << setw(1) << ""
1290        << std::right << setw(5) << snrow << setw(2) << ""
1291        << std::left << stypestrs << setw(1) << ""
1292        << freqids << setw(1) << ""
1293        << molids  << endl;
1294    // Format Beam summary
1295    for (uInt j=0; j < nbeam; j++) {
1296      oss << setw(7) << "" << setw(6) << beamids(j) << setw(1) << ""
1297          << formatDirection(beamDirs(j),9) << endl;
1298    }
1299    // Flush summary every scan and clear up the string
1300    ols << String(oss) << LogIO::POST;
1301    if (ofs) ofs << String(oss) << flush;
1302    oss.str("");
1303    oss.clear();
1304
1305    ++iter;
1306  } // end of scan iteration
1307  oss << asap::SEPERATOR << endl;
1308 
1309  // List FRECUENCIES Table (using STFrequencies.print may be slow)
1310  oss << "FREQUENCIES: " << nfreq << endl;
1311//   oss << std::right << setw(5) << "ID" << setw(2) << ""
1312//       << std::left  << setw(5) << "IFNO" << setw(2) << ""
1313//       << setw(8) << "Frame"
1314//       << setw(16) << "RefVal"
1315//       << setw(7) << "RefPix"
1316//       << setw(15) << "Increment"
1317//       << setw(9) << "Channels"
1318//       << setw(6) << "POLNOs" << endl;
1319//   Int tmplen;
1320//   for (Int i=0; i < nfid; i++){
1321//     // List row=i of FREQUENCIES subtable
1322//     ifNos[i].shape(tmplen);
1323//     if (tmplen >= 1) {
1324//       oss << std::right << setw(5) << ftabIds(i) << setw(2) << ""
1325//        << setw(3) << ifNos[i](0) << setw(1) << ""
1326//        << std::left << setw(46) << frequencies().print(ftabIds(i))
1327//        << setw(2) << ""
1328//        << std::right << setw(8) << fIdchans[i] << setw(2) << ""
1329//        << std::left << polNos[i];
1330//       if (tmplen > 1) {
1331//      oss  << " (" << tmplen << " chains)";
1332//       }
1333//       oss << endl;
1334//     }
1335  oss << std::right << setw(4) << "ID" << setw(2) << ""
1336      << std::left  << setw(9) << "IFNO(SPW)" << setw(2) << ""
1337      << setw(8) << "#Chans"
1338      << setw(8) << "Frame"
1339      << setw(12) << "Ch0[MHz]"
1340      << setw(14) << "ChanWid[kHz]"
1341      << setw(14) << "Center[MHz]"
1342      << setw(6) << "POLNOs" << endl;
1343  Int tmplen;
1344  for (Int i=0; i < nfid; i++){
1345    // List row=i of FREQUENCIES subtable
1346    ifNos[i].shape(tmplen);
1347    Double refpix, refval, increment ;
1348    if (tmplen >= 1) {
1349      freqTable_.getEntry( refpix, refval, increment, ftabIds(i) ) ;
1350      oss << std::right << setw(4) << ftabIds(i) << setw(2) << ""
1351          << std::left << setw(9) << ifNos[i](0) << setw(2) << ""
1352          << std::right << setw(6) << fIdchans[i] << setw(2) << ""
1353          << setw(6) << frequencies().getFrameString(true)
1354          << setw(2) << ""
1355          << setw(10) << std::setprecision(9) << (fIdfreq0[i]*1.e-6) << setw(2) << ""
1356          << setw(12) << (increment*1.e-3) << setw(2) << ""
1357          << setw(12) << (fIdfcent[i]*1.e-6) << setw(2) << ""
1358          << std::left << polNos[i];
1359      if (tmplen > 1) {
1360        oss  << " (" << tmplen << " chains)";
1361      }
1362      oss << endl;
1363    }
1364   
1365  }
1366  oss << asap::SEPERATOR << endl;
1367
1368  // List MOLECULES Table (currently lists all rows)
1369  oss << "MOLECULES: " << endl;
1370  if (molecules().nrow() <= 0) {
1371    oss << "   MOLECULES subtable is empty: there are no data" << endl;
1372  } else {
1373    ROTableRow row(molecules().table());
1374    oss << std::right << setw(5) << "ID"
1375        << std::left << setw(3) << ""
1376        << setw(18) << "RestFreq"
1377        << setw(15) << "Name" << endl;
1378    for (Int i=0; i < molecules().nrow(); i++){
1379      const TableRecord& rec=row.get(i);
1380      oss << std::right << setw(5) << rec.asuInt("ID")
1381          << std::left << setw(3) << ""
1382          << rec.asArrayDouble("RESTFREQUENCY") << setw(1) << ""
1383          << rec.asArrayString("NAME") << endl;
1384    }
1385  }
1386  oss << asap::SEPERATOR << endl;
1387  ols << String(oss) << LogIO::POST;
1388  if (ofs) {
1389    ofs << String(oss) << flush;
1390    ofs.close();
1391  }
1392  //  return String(oss);
1393}
1394
1395
1396std::string Scantable::oldheaderSummary()
1397{
1398  // Format header info
1399//   STHeader sdh;
1400//   sdh = getHeader();
1401//   sdh.print();
1402  ostringstream oss;
1403  oss.flags(std::ios_base::left);
1404  oss << setw(15) << "Beams:" << setw(4) << nbeam() << endl
1405      << setw(15) << "IFs:" << setw(4) << nif() << endl
1406      << setw(15) << "Polarisations:" << setw(4) << npol()
1407      << "(" << getPolType() << ")" << endl
1408      << setw(15) << "Channels:" << nchan() << endl;
1409  String tmp;
1410  oss << setw(15) << "Observer:"
1411      << table_.keywordSet().asString("Observer") << endl;
1412  oss << setw(15) << "Obs Date:" << getTime(-1,true) << endl;
1413  table_.keywordSet().get("Project", tmp);
1414  oss << setw(15) << "Project:" << tmp << endl;
1415  table_.keywordSet().get("Obstype", tmp);
1416  oss << setw(15) << "Obs. Type:" << tmp << endl;
1417  table_.keywordSet().get("AntennaName", tmp);
1418  oss << setw(15) << "Antenna Name:" << tmp << endl;
1419  table_.keywordSet().get("FluxUnit", tmp);
1420  oss << setw(15) << "Flux Unit:" << tmp << endl;
1421  int nid = moleculeTable_.nrow();
1422  Bool firstline = True;
1423  oss << setw(15) << "Rest Freqs:";
1424  for (int i=0; i<nid; i++) {
1425    Table t = table_(table_.col("MOLECULE_ID") == i, 1);
1426      if (t.nrow() >  0) {
1427          Vector<Double> vec(moleculeTable_.getRestFrequency(i));
1428          if (vec.nelements() > 0) {
1429               if (firstline) {
1430                   oss << setprecision(10) << vec << " [Hz]" << endl;
1431                   firstline=False;
1432               }
1433               else{
1434                   oss << setw(15)<<" " << setprecision(10) << vec << " [Hz]" << endl;
1435               }
1436          } else {
1437              oss << "none" << endl;
1438          }
1439      }
1440  }
1441
1442  oss << setw(15) << "Abcissa:" << getAbcissaLabel(0) << endl;
1443  oss << selector_.print() << endl;
1444  return String(oss);
1445}
1446
1447  //std::string Scantable::summary( const std::string& filename )
1448void Scantable::oldsummary( const std::string& filename )
1449{
1450  ostringstream oss;
1451  ofstream ofs;
1452  LogIO ols(LogOrigin("Scantable", "summary", WHERE));
1453
1454  if (filename != "")
1455    ofs.open( filename.c_str(),  ios::out );
1456
1457  oss << endl;
1458  oss << asap::SEPERATOR << endl;
1459  oss << " Scan Table Summary" << endl;
1460  oss << asap::SEPERATOR << endl;
1461
1462  // Format header info
1463  oss << oldheaderSummary();
1464  oss << endl;
1465
1466  // main table
1467  String dirtype = "Position ("
1468                  + getDirectionRefString()
1469                  + ")";
1470  oss.flags(std::ios_base::left);
1471  oss << setw(5) << "Scan" << setw(15) << "Source"
1472      << setw(10) << "Time" << setw(18) << "Integration"
1473      << setw(15) << "Source Type" << endl;
1474  oss << setw(5) << "" << setw(5) << "Beam" << setw(3) << "" << dirtype << endl;
1475  oss << setw(10) << "" << setw(3) << "IF" << setw(3) << ""
1476      << setw(8) << "Frame" << setw(16)
1477      << "RefVal" << setw(10) << "RefPix" << setw(12) << "Increment"
1478      << setw(7) << "Channels"
1479      << endl;
1480  oss << asap::SEPERATOR << endl;
1481
1482  // Flush summary and clear up the string
1483  ols << String(oss) << LogIO::POST;
1484  if (ofs) ofs << String(oss) << flush;
1485  oss.str("");
1486  oss.clear();
1487
1488  TableIterator iter(table_, "SCANNO");
1489  while (!iter.pastEnd()) {
1490    Table subt = iter.table();
1491    ROTableRow row(subt);
1492    MEpoch::ROScalarColumn timeCol(subt,"TIME");
1493    const TableRecord& rec = row.get(0);
1494    oss << setw(4) << std::right << rec.asuInt("SCANNO")
1495        << std::left << setw(1) << ""
1496        << setw(15) << rec.asString("SRCNAME")
1497        << setw(10) << formatTime(timeCol(0), false);
1498    // count the cycles in the scan
1499    TableIterator cyciter(subt, "CYCLENO");
1500    int nint = 0;
1501    while (!cyciter.pastEnd()) {
1502      ++nint;
1503      ++cyciter;
1504    }
1505    oss << setw(3) << std::right << nint  << setw(3) << " x " << std::left
1506        << setw(11) <<  formatSec(rec.asFloat("INTERVAL")) << setw(1) << ""
1507        << setw(15) << SrcType::getName(rec.asInt("SRCTYPE")) << endl;
1508
1509    TableIterator biter(subt, "BEAMNO");
1510    while (!biter.pastEnd()) {
1511      Table bsubt = biter.table();
1512      ROTableRow brow(bsubt);
1513      const TableRecord& brec = brow.get(0);
1514      uInt row0 = bsubt.rowNumbers(table_)[0];
1515      oss << setw(5) << "" <<  setw(4) << std::right << brec.asuInt("BEAMNO")<< std::left;
1516      oss  << setw(4) << ""  << formatDirection(getDirection(row0)) << endl;
1517      TableIterator iiter(bsubt, "IFNO");
1518      while (!iiter.pastEnd()) {
1519        Table isubt = iiter.table();
1520        ROTableRow irow(isubt);
1521        const TableRecord& irec = irow.get(0);
1522        oss << setw(9) << "";
1523        oss << setw(3) << std::right << irec.asuInt("IFNO") << std::left
1524            << setw(1) << "" << frequencies().print(irec.asuInt("FREQ_ID"))
1525            << setw(3) << "" << nchan(irec.asuInt("IFNO"))
1526            << endl;
1527
1528        ++iiter;
1529      }
1530      ++biter;
1531    }
1532    // Flush summary every scan and clear up the string
1533    ols << String(oss) << LogIO::POST;
1534    if (ofs) ofs << String(oss) << flush;
1535    oss.str("");
1536    oss.clear();
1537
1538    ++iter;
1539  }
1540  oss << asap::SEPERATOR << endl;
1541  ols << String(oss) << LogIO::POST;
1542  if (ofs) {
1543    ofs << String(oss) << flush;
1544    ofs.close();
1545  }
1546  //  return String(oss);
1547}
1548
1549// std::string Scantable::getTime(int whichrow, bool showdate) const
1550// {
1551//   MEpoch::ROScalarColumn timeCol(table_, "TIME");
1552//   MEpoch me;
1553//   if (whichrow > -1) {
1554//     me = timeCol(uInt(whichrow));
1555//   } else {
1556//     Double tm;
1557//     table_.keywordSet().get("UTC",tm);
1558//     me = MEpoch(MVEpoch(tm));
1559//   }
1560//   return formatTime(me, showdate);
1561// }
1562
1563std::string Scantable::getTime(int whichrow, bool showdate, uInt prec) const
1564{
1565  MEpoch me;
1566  me = getEpoch(whichrow);
1567  return formatTime(me, showdate, prec);
1568}
1569
1570MEpoch Scantable::getEpoch(int whichrow) const
1571{
1572  if (whichrow > -1) {
1573    return timeCol_(uInt(whichrow));
1574  } else {
1575    Double tm;
1576    table_.keywordSet().get("UTC",tm);
1577    return MEpoch(MVEpoch(tm));
1578  }
1579}
1580
1581std::string Scantable::getDirectionString(int whichrow) const
1582{
1583  return formatDirection(getDirection(uInt(whichrow)));
1584}
1585
1586
1587SpectralCoordinate Scantable::getSpectralCoordinate(int whichrow) const {
1588  const MPosition& mp = getAntennaPosition();
1589  const MDirection& md = getDirection(whichrow);
1590  const MEpoch& me = timeCol_(whichrow);
1591  //Double rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
1592  Vector<Double> rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
1593  return freqTable_.getSpectralCoordinate(md, mp, me, rf,
1594                                          mfreqidCol_(whichrow));
1595}
1596
1597std::vector< double > Scantable::getAbcissa( int whichrow ) const
1598{
1599  if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal row number"));
1600  std::vector<double> stlout;
1601  int nchan = specCol_(whichrow).nelements();
1602  String us = freqTable_.getUnitString();
1603  if ( us == "" || us == "pixel" || us == "channel" ) {
1604    for (int i=0; i<nchan; ++i) {
1605      stlout.push_back(double(i));
1606    }
1607    return stlout;
1608  }
1609  SpectralCoordinate spc = getSpectralCoordinate(whichrow);
1610  Vector<Double> pixel(nchan);
1611  Vector<Double> world;
1612  indgen(pixel);
1613  if ( Unit(us) == Unit("Hz") ) {
1614    for ( int i=0; i < nchan; ++i) {
1615      Double world;
1616      spc.toWorld(world, pixel[i]);
1617      stlout.push_back(double(world));
1618    }
1619  } else if ( Unit(us) == Unit("km/s") ) {
1620    Vector<Double> world;
1621    spc.pixelToVelocity(world, pixel);
1622    world.tovector(stlout);
1623  }
1624  return stlout;
1625}
1626void Scantable::setDirectionRefString( const std::string & refstr )
1627{
1628  MDirection::Types mdt;
1629  if (refstr != "" && !MDirection::getType(mdt, refstr)) {
1630    throw(AipsError("Illegal Direction frame."));
1631  }
1632  if ( refstr == "" ) {
1633    String defaultstr = MDirection::showType(dirCol_.getMeasRef().getType());
1634    table_.rwKeywordSet().define("DIRECTIONREF", defaultstr);
1635  } else {
1636    table_.rwKeywordSet().define("DIRECTIONREF", String(refstr));
1637  }
1638}
1639
1640std::string Scantable::getDirectionRefString( ) const
1641{
1642  return table_.keywordSet().asString("DIRECTIONREF");
1643}
1644
1645MDirection Scantable::getDirection(int whichrow ) const
1646{
1647  String usertype = table_.keywordSet().asString("DIRECTIONREF");
1648  String type = MDirection::showType(dirCol_.getMeasRef().getType());
1649  if ( usertype != type ) {
1650    MDirection::Types mdt;
1651    if (!MDirection::getType(mdt, usertype)) {
1652      throw(AipsError("Illegal Direction frame."));
1653    }
1654    return dirCol_.convert(uInt(whichrow), mdt);
1655  } else {
1656    return dirCol_(uInt(whichrow));
1657  }
1658}
1659
1660std::string Scantable::getAbcissaLabel( int whichrow ) const
1661{
1662  if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal ro number"));
1663  const MPosition& mp = getAntennaPosition();
1664  const MDirection& md = getDirection(whichrow);
1665  const MEpoch& me = timeCol_(whichrow);
1666  //const Double& rf = mmolidCol_(whichrow);
1667  const Vector<Double> rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
1668  SpectralCoordinate spc =
1669    freqTable_.getSpectralCoordinate(md, mp, me, rf, mfreqidCol_(whichrow));
1670
1671  String s = "Channel";
1672  Unit u = Unit(freqTable_.getUnitString());
1673  if (u == Unit("km/s")) {
1674    s = CoordinateUtil::axisLabel(spc, 0, True,True,  True);
1675  } else if (u == Unit("Hz")) {
1676    Vector<String> wau(1);wau = u.getName();
1677    spc.setWorldAxisUnits(wau);
1678    s = CoordinateUtil::axisLabel(spc, 0, True, True, False);
1679  }
1680  return s;
1681
1682}
1683
1684/**
1685void asap::Scantable::setRestFrequencies( double rf, const std::string& name,
1686                                          const std::string& unit )
1687**/
1688void Scantable::setRestFrequencies( vector<double> rf, const vector<std::string>& name,
1689                                          const std::string& unit )
1690
1691{
1692  ///@todo lookup in line table to fill in name and formattedname
1693  Unit u(unit);
1694  //Quantum<Double> urf(rf, u);
1695  Quantum<Vector<Double> >urf(rf, u);
1696  Vector<String> formattedname(0);
1697  //cerr<<"Scantable::setRestFrequnecies="<<urf<<endl;
1698
1699  //uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), name, "");
1700  uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), mathutil::toVectorString(name), formattedname);
1701  TableVector<uInt> tabvec(table_, "MOLECULE_ID");
1702  tabvec = id;
1703}
1704
1705/**
1706void asap::Scantable::setRestFrequencies( const std::string& name )
1707{
1708  throw(AipsError("setRestFrequencies( const std::string& name ) NYI"));
1709  ///@todo implement
1710}
1711**/
1712
1713void Scantable::setRestFrequencies( const vector<std::string>& name )
1714{
1715  (void) name; // suppress unused warning
1716  throw(AipsError("setRestFrequencies( const vector<std::string>& name ) NYI"));
1717  ///@todo implement
1718}
1719
1720std::vector< unsigned int > Scantable::rownumbers( ) const
1721{
1722  std::vector<unsigned int> stlout;
1723  Vector<uInt> vec = table_.rowNumbers();
1724  vec.tovector(stlout);
1725  return stlout;
1726}
1727
1728
1729Matrix<Float> Scantable::getPolMatrix( uInt whichrow ) const
1730{
1731  ROTableRow row(table_);
1732  const TableRecord& rec = row.get(whichrow);
1733  Table t =
1734    originalTable_( originalTable_.col("SCANNO") == Int(rec.asuInt("SCANNO"))
1735                    && originalTable_.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
1736                    && originalTable_.col("IFNO") == Int(rec.asuInt("IFNO"))
1737                    && originalTable_.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
1738  ROArrayColumn<Float> speccol(t, "SPECTRA");
1739  return speccol.getColumn();
1740}
1741
1742std::vector< std::string > Scantable::columnNames( ) const
1743{
1744  Vector<String> vec = table_.tableDesc().columnNames();
1745  return mathutil::tovectorstring(vec);
1746}
1747
1748MEpoch::Types Scantable::getTimeReference( ) const
1749{
1750  return MEpoch::castType(timeCol_.getMeasRef().getType());
1751}
1752
1753void Scantable::addFit( const STFitEntry& fit, int row )
1754{
1755  //cout << mfitidCol_(uInt(row)) << endl;
1756  LogIO os( LogOrigin( "Scantable", "addFit()", WHERE ) ) ;
1757  os << mfitidCol_(uInt(row)) << LogIO::POST ;
1758  uInt id = fitTable_.addEntry(fit, mfitidCol_(uInt(row)));
1759  mfitidCol_.put(uInt(row), id);
1760}
1761
1762void Scantable::shift(int npix)
1763{
1764  Vector<uInt> fids(mfreqidCol_.getColumn());
1765  genSort( fids, Sort::Ascending,
1766           Sort::QuickSort|Sort::NoDuplicates );
1767  for (uInt i=0; i<fids.nelements(); ++i) {
1768    frequencies().shiftRefPix(npix, fids[i]);
1769  }
1770}
1771
1772String Scantable::getAntennaName() const
1773{
1774  String out;
1775  table_.keywordSet().get("AntennaName", out);
1776  String::size_type pos1 = out.find("@") ;
1777  String::size_type pos2 = out.find("//") ;
1778  if ( pos2 != String::npos )
1779    out = out.substr(pos2+2,pos1-pos2-2) ;
1780  else if ( pos1 != String::npos )
1781    out = out.substr(0,pos1) ;
1782  return out;
1783}
1784
1785int Scantable::checkScanInfo(const std::vector<int>& scanlist) const
1786{
1787  String tbpath;
1788  int ret = 0;
1789  if ( table_.keywordSet().isDefined("GBT_GO") ) {
1790    table_.keywordSet().get("GBT_GO", tbpath);
1791    Table t(tbpath,Table::Old);
1792    // check each scan if other scan of the pair exist
1793    int nscan = scanlist.size();
1794    for (int i = 0; i < nscan; i++) {
1795      Table subt = t( t.col("SCAN") == scanlist[i] );
1796      if (subt.nrow()==0) {
1797        //cerr <<"Scan "<<scanlist[i]<<" cannot be found in the scantable."<<endl;
1798        LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1799        os <<LogIO::WARN<<"Scan "<<scanlist[i]<<" cannot be found in the scantable."<<LogIO::POST;
1800        ret = 1;
1801        break;
1802      }
1803      ROTableRow row(subt);
1804      const TableRecord& rec = row.get(0);
1805      int scan1seqn = rec.asuInt("PROCSEQN");
1806      int laston1 = rec.asuInt("LASTON");
1807      if ( rec.asuInt("PROCSIZE")==2 ) {
1808        if ( i < nscan-1 ) {
1809          Table subt2 = t( t.col("SCAN") == scanlist[i+1] );
1810          if ( subt2.nrow() == 0) {
1811            LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1812
1813            //cerr<<"Scan "<<scanlist[i+1]<<" cannot be found in the scantable."<<endl;
1814            os<<LogIO::WARN<<"Scan "<<scanlist[i+1]<<" cannot be found in the scantable."<<LogIO::POST;
1815            ret = 1;
1816            break;
1817          }
1818          ROTableRow row2(subt2);
1819          const TableRecord& rec2 = row2.get(0);
1820          int scan2seqn = rec2.asuInt("PROCSEQN");
1821          int laston2 = rec2.asuInt("LASTON");
1822          if (scan1seqn == 1 && scan2seqn == 2) {
1823            if (laston1 == laston2) {
1824              LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1825              //cerr<<"A valid scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl;
1826              os<<"A valid scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<LogIO::POST;
1827              i +=1;
1828            }
1829            else {
1830              LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1831              //cerr<<"Incorrect scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl;
1832              os<<LogIO::WARN<<"Incorrect scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<LogIO::POST;
1833            }
1834          }
1835          else if (scan1seqn==2 && scan2seqn == 1) {
1836            if (laston1 == laston2) {
1837              LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1838              //cerr<<"["<<scanlist[i]<<","<<scanlist[i+1]<<"] is a valid scan pair but in incorrect order."<<endl;
1839              os<<LogIO::WARN<<"["<<scanlist[i]<<","<<scanlist[i+1]<<"] is a valid scan pair but in incorrect order."<<LogIO::POST;
1840              ret = 1;
1841              break;
1842            }
1843          }
1844          else {
1845            LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1846            //cerr<<"The other scan for  "<<scanlist[i]<<" appears to be missing. Check the input scan numbers."<<endl;
1847            os<<LogIO::WARN<<"The other scan for  "<<scanlist[i]<<" appears to be missing. Check the input scan numbers."<<LogIO::POST;
1848            ret = 1;
1849            break;
1850          }
1851        }
1852      }
1853      else {
1854        LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1855        //cerr<<"The scan does not appear to be standard obsevation."<<endl;
1856        os<<LogIO::WARN<<"The scan does not appear to be standard obsevation."<<LogIO::POST;
1857      }
1858    //if ( i >= nscan ) break;
1859    }
1860  }
1861  else {
1862    LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1863    //cerr<<"No reference to GBT_GO table."<<endl;
1864    os<<LogIO::WARN<<"No reference to GBT_GO table."<<LogIO::POST;
1865    ret = 1;
1866  }
1867  return ret;
1868}
1869
1870std::vector<double> Scantable::getDirectionVector(int whichrow) const
1871{
1872  Vector<Double> Dir = dirCol_(whichrow).getAngle("rad").getValue();
1873  std::vector<double> dir;
1874  Dir.tovector(dir);
1875  return dir;
1876}
1877
1878void asap::Scantable::reshapeSpectrum( int nmin, int nmax )
1879  throw( casa::AipsError )
1880{
1881  // assumed that all rows have same nChan
1882  Vector<Float> arr = specCol_( 0 ) ;
1883  int nChan = arr.nelements() ;
1884
1885  // if nmin < 0 or nmax < 0, nothing to do
1886  if (  nmin < 0 ) {
1887    throw( casa::indexError<int>( nmin, "asap::Scantable::reshapeSpectrum: Invalid range. Negative index is specified." ) ) ;
1888    }
1889  if (  nmax < 0  ) {
1890    throw( casa::indexError<int>( nmax, "asap::Scantable::reshapeSpectrum: Invalid range. Negative index is specified." ) ) ;
1891  }
1892
1893  // if nmin > nmax, exchange values
1894  if ( nmin > nmax ) {
1895    int tmp = nmax ;
1896    nmax = nmin ;
1897    nmin = tmp ;
1898    LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1899    os << "Swap values. Applied range is ["
1900       << nmin << ", " << nmax << "]" << LogIO::POST ;
1901  }
1902
1903  // if nmin exceeds nChan, nothing to do
1904  if ( nmin >= nChan ) {
1905    throw( casa::indexError<int>( nmin, "asap::Scantable::reshapeSpectrum: Invalid range. Specified minimum exceeds nChan." ) ) ;
1906  }
1907
1908  // if nmax exceeds nChan, reset nmax to nChan
1909  if ( nmax >= nChan-1 ) {
1910    if ( nmin == 0 ) {
1911      // nothing to do
1912      LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1913      os << "Whole range is selected. Nothing to do." << LogIO::POST ;
1914      return ;
1915    }
1916    else {
1917      LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1918      os << "Specified maximum exceeds nChan. Applied range is ["
1919         << nmin << ", " << nChan-1 << "]." << LogIO::POST ;
1920      nmax = nChan - 1 ;
1921    }
1922  }
1923
1924  // reshape specCol_ and flagCol_
1925  for ( int irow = 0 ; irow < nrow() ; irow++ ) {
1926    reshapeSpectrum( nmin, nmax, irow ) ;
1927  }
1928
1929  // update FREQUENCIES subtable
1930  Vector<uInt> freqIdArray = mfreqidCol_.getColumn();
1931  uInt numFreqId = GenSort<uInt>::sort(freqIdArray, Sort::Ascending,
1932                                       Sort::HeapSort | Sort::NoDuplicates);
1933  Double refpix ;
1934  Double refval ;
1935  Double increment ;
1936  for (uInt irow  = 0; irow < numFreqId; irow++) {
1937    freqTable_.getEntry( refpix, refval, increment, freqIdArray[irow] ) ;
1938    /***
1939     * need to shift refpix to nmin
1940     * note that channel nmin in old index will be channel 0 in new one
1941     ***/
1942    refval = refval - ( refpix - nmin ) * increment ;
1943    refpix = 0 ;
1944    freqTable_.setEntry( refpix, refval, increment, freqIdArray[irow] ) ;
1945  }
1946
1947  // update nchan
1948  int newsize = nmax - nmin + 1 ;
1949  table_.rwKeywordSet().define( "nChan", newsize ) ;
1950
1951  // update bandwidth
1952  // assumed all spectra in the scantable have same bandwidth
1953  table_.rwKeywordSet().define( "Bandwidth", increment * newsize ) ;
1954
1955  return ;
1956}
1957
1958void asap::Scantable::reshapeSpectrum( int nmin, int nmax, int irow )
1959{
1960  // reshape specCol_ and flagCol_
1961  Vector<Float> oldspec = specCol_( irow ) ;
1962  Vector<uChar> oldflag = flagsCol_( irow ) ;
1963  Vector<Float> oldtsys = tsysCol_( irow ) ;
1964  uInt newsize = nmax - nmin + 1 ;
1965  Slice slice( nmin, newsize, 1 ) ;
1966  specCol_.put( irow, oldspec( slice ) ) ;
1967  flagsCol_.put( irow, oldflag( slice ) ) ;
1968  if ( oldspec.size() == oldtsys.size() )
1969    tsysCol_.put( irow, oldtsys( slice ) ) ;
1970
1971  return ;
1972}
1973
1974void asap::Scantable::regridSpecChannel( double dnu, int nChan )
1975{
1976  LogIO os( LogOrigin( "Scantable", "regridChannel()", WHERE ) ) ;
1977  os << "Regrid abcissa with spectral resoultion " << dnu << " " << freqTable_.getUnitString() << " with channel number " << ((nChan>0)? String(nChan) : "covering band width")<< LogIO::POST ;
1978  int freqnrow = freqTable_.table().nrow() ;
1979  Vector<bool> firstTime( freqnrow, true ) ;
1980  double oldincr, factor;
1981  uInt currId;
1982  Double refpix ;
1983  Double refval ;
1984  Double increment ;
1985  for ( int irow = 0 ; irow < nrow() ; irow++ ) {
1986    currId = mfreqidCol_(irow);
1987    vector<double> abcissa = getAbcissa( irow ) ;
1988    if (nChan < 0) {
1989      int oldsize = abcissa.size() ;
1990      double bw = (abcissa[oldsize-1]-abcissa[0]) +                     \
1991        0.5 * (abcissa[1]-abcissa[0] + abcissa[oldsize-1]-abcissa[oldsize-2]) ;
1992      nChan = int( ceil( abs(bw/dnu) ) ) ;
1993    }
1994    // actual regridding
1995    regridChannel( nChan, dnu, irow ) ;
1996
1997    // update FREQUENCIES subtable
1998    if (firstTime[currId]) {
1999      oldincr = abcissa[1]-abcissa[0] ;
2000      factor = dnu/oldincr ;
2001      firstTime[currId] = false ;
2002      freqTable_.getEntry( refpix, refval, increment, currId ) ;
2003
2004      //refval = refval - ( refpix + 0.5 * (1 - factor) ) * increment ;
2005      if (factor > 0 ) {
2006        refpix = (refpix + 0.5)/factor - 0.5;
2007      } else {
2008        refpix = (abcissa.size() - 0.5 - refpix)/abs(factor) - 0.5;
2009      }
2010      freqTable_.setEntry( refpix, refval, increment*factor, currId ) ;
2011      //os << "ID" << currId << ": channel width (Orig) = " << oldincr << " [" << freqTable_.getUnitString() << "], scale factor = " << factor << LogIO::POST ;
2012      //os << "     frequency increment (Orig) = " << increment << "-> (New) " << increment*factor << LogIO::POST ;
2013    }
2014  }
2015}
2016
2017void asap::Scantable::regridChannel( int nChan, double dnu )
2018{
2019  LogIO os( LogOrigin( "Scantable", "regridChannel()", WHERE ) ) ;
2020  os << "Regrid abcissa with channel number " << nChan << " and spectral resoultion " << dnu << "Hz." << LogIO::POST ;
2021  // assumed that all rows have same nChan
2022  Vector<Float> arr = specCol_( 0 ) ;
2023  int oldsize = arr.nelements() ;
2024
2025  // if oldsize == nChan, nothing to do
2026  if ( oldsize == nChan ) {
2027    os << "Specified channel number is same as current one. Nothing to do." << LogIO::POST ;
2028    return ;
2029  }
2030
2031  // if oldChan < nChan, unphysical operation
2032  if ( oldsize < nChan ) {
2033    os << "Unphysical operation. Nothing to do." << LogIO::POST ;
2034    return ;
2035  }
2036
2037  // change channel number for specCol_, flagCol_, and tsysCol_ (if necessary)
2038  vector<string> coordinfo = getCoordInfo() ;
2039  string oldinfo = coordinfo[0] ;
2040  coordinfo[0] = "Hz" ;
2041  setCoordInfo( coordinfo ) ;
2042  for ( int irow = 0 ; irow < nrow() ; irow++ ) {
2043    regridChannel( nChan, dnu, irow ) ;
2044  }
2045  coordinfo[0] = oldinfo ;
2046  setCoordInfo( coordinfo ) ;
2047
2048
2049  // NOTE: this method does not update metadata such as
2050  //       FREQUENCIES subtable, nChan, Bandwidth, etc.
2051
2052  return ;
2053}
2054
2055void asap::Scantable::regridChannel( int nChan, double dnu, int irow )
2056{
2057  // logging
2058  //ofstream ofs( "average.log", std::ios::out | std::ios::app ) ;
2059  //ofs << "IFNO = " << getIF( irow ) << " irow = " << irow << endl ;
2060
2061  Vector<Float> oldspec = specCol_( irow ) ;
2062  Vector<uChar> oldflag = flagsCol_( irow ) ;
2063  Vector<Float> oldtsys = tsysCol_( irow ) ;
2064  Vector<Float> newspec( nChan, 0 ) ;
2065  Vector<uChar> newflag( nChan, true ) ;
2066  Vector<Float> newtsys ;
2067  bool regridTsys = false ;
2068  if (oldtsys.size() == oldspec.size()) {
2069    regridTsys = true ;
2070    newtsys.resize(nChan,false) ;
2071    newtsys = 0 ;
2072  }
2073
2074  // regrid
2075  vector<double> abcissa = getAbcissa( irow ) ;
2076  int oldsize = abcissa.size() ;
2077  double olddnu = abcissa[1] - abcissa[0] ;
2078  //int ichan = 0 ;
2079  double wsum = 0.0 ;
2080  Vector<double> zi( nChan+1 ) ;
2081  Vector<double> yi( oldsize + 1 ) ;
2082  yi[0] = abcissa[0] - 0.5 * olddnu ;
2083  for ( int ii = 1 ; ii < oldsize ; ii++ )
2084    yi[ii] = 0.5* (abcissa[ii-1] + abcissa[ii]) ;
2085  yi[oldsize] = abcissa[oldsize-1] \
2086    + 0.5 * (abcissa[oldsize-1] - abcissa[oldsize-2]) ;
2087  //zi[0] = abcissa[0] - 0.5 * olddnu ;
2088  zi[0] = ((olddnu*dnu > 0) ? yi[0] : yi[oldsize]) ;
2089  for ( int ii = 1 ; ii < nChan ; ii++ )
2090    zi[ii] = zi[0] + dnu * ii ;
2091  zi[nChan] = zi[nChan-1] + dnu ;
2092  // Access zi and yi in ascending order
2093  int izs = ((dnu > 0) ? 0 : nChan ) ;
2094  int ize = ((dnu > 0) ? nChan : 0 ) ;
2095  int izincr = ((dnu > 0) ? 1 : -1 ) ;
2096  int ichan =  ((olddnu > 0) ? 0 : oldsize ) ;
2097  int iye = ((olddnu > 0) ? oldsize : 0 ) ;
2098  int iyincr = ((olddnu > 0) ? 1 : -1 ) ;
2099  //for ( int ii = izs ; ii != ize ; ii+=izincr ){
2100  int ii = izs ;
2101  while (ii != ize) {
2102    // always zl < zr
2103    double zl = zi[ii] ;
2104    double zr = zi[ii+izincr] ;
2105    // Need to access smaller index for the new spec, flag, and tsys.
2106    // Values between zi[k] and zi[k+1] should be stored in newspec[k], etc.
2107    int i = min(ii, ii+izincr) ;
2108    //for ( int jj = ichan ; jj != iye ; jj+=iyincr ) {
2109    int jj = ichan ;
2110    while (jj != iye) {
2111      // always yl < yr
2112      double yl = yi[jj] ;
2113      double yr = yi[jj+iyincr] ;
2114      // Need to access smaller index for the original spec, flag, and tsys.
2115      // Values between yi[k] and yi[k+1] are stored in oldspec[k], etc.
2116      int j = min(jj, jj+iyincr) ;
2117      if ( yr <= zl ) {
2118        jj += iyincr ;
2119        continue ;
2120      }
2121      else if ( yl <= zl ) {
2122        if ( yr < zr ) {
2123          if (!oldflag[j]) {
2124            newspec[i] += oldspec[j] * ( yr - zl ) ;
2125            if (regridTsys) newtsys[i] += oldtsys[j] * ( yr - zl ) ;
2126            wsum += ( yr - zl ) ;
2127          }
2128          newflag[i] = (newflag[i] && oldflag[j]) ? 1 << 7 : 0 ;
2129        }
2130        else {
2131          if (!oldflag[j]) {
2132            newspec[i] += oldspec[j] * abs(dnu) ;
2133            if (regridTsys) newtsys[i] += oldtsys[j] * abs(dnu) ;
2134            wsum += abs(dnu) ;
2135          }
2136          newflag[i] = (newflag[i] && oldflag[j]) ? 1 << 7 : 0 ;
2137          ichan = jj ;
2138          break ;
2139        }
2140      }
2141      else if ( yl < zr ) {
2142        if ( yr <= zr ) {
2143          if (!oldflag[j]) {
2144            newspec[i] += oldspec[j] * ( yr - yl ) ;
2145            if (regridTsys) newtsys[i] += oldtsys[j] * ( yr - yl ) ;
2146            wsum += ( yr - yl ) ;
2147          }
2148          newflag[i] = (newflag[i] && oldflag[j]) ? 1 << 7 : 0 ;
2149        }
2150        else {
2151          if (!oldflag[j]) {
2152            newspec[i] += oldspec[j] * ( zr - yl ) ;
2153            if (regridTsys) newtsys[i] += oldtsys[j] * ( zr - yl ) ;
2154            wsum += ( zr - yl ) ;
2155          }
2156          newflag[i] = (newflag[i] && oldflag[j]) ? 1 << 7 : 0 ;
2157          ichan = jj ;
2158          break ;
2159        }
2160      }
2161      else {
2162        ichan = jj - iyincr ;
2163        break ;
2164      }
2165      jj += iyincr ;
2166    }
2167    if ( wsum != 0.0 ) {
2168      newspec[i] /= wsum ;
2169      if (regridTsys) newtsys[i] /= wsum ;
2170    }
2171    wsum = 0.0 ;
2172    ii += izincr ;
2173  }
2174//   if ( dnu > 0.0 ) {
2175//     for ( int ii = 0 ; ii < nChan ; ii++ ) {
2176//       double zl = zi[ii] ;
2177//       double zr = zi[ii+1] ;
2178//       for ( int j = ichan ; j < oldsize ; j++ ) {
2179//         double yl = yi[j] ;
2180//         double yr = yi[j+1] ;
2181//         if ( yl <= zl ) {
2182//           if ( yr <= zl ) {
2183//             continue ;
2184//           }
2185//           else if ( yr <= zr ) {
2186//          if (!oldflag[j]) {
2187//            newspec[ii] += oldspec[j] * ( yr - zl ) ;
2188//            if (regridTsys) newtsys[ii] += oldtsys[j] * ( yr - zl ) ;
2189//            wsum += ( yr - zl ) ;
2190//          }
2191//          newflag[ii] = newflag[ii] && oldflag[j] ;
2192//           }
2193//           else {
2194//          if (!oldflag[j]) {
2195//            newspec[ii] += oldspec[j] * dnu ;
2196//            if (regridTsys) newtsys[ii] += oldtsys[j] * dnu ;
2197//            wsum += dnu ;
2198//          }
2199//          newflag[ii] = newflag[ii] && oldflag[j] ;
2200//             ichan = j ;
2201//             break ;
2202//           }
2203//         }
2204//         else if ( yl < zr ) {
2205//           if ( yr <= zr ) {
2206//          if (!oldflag[j]) {
2207//            newspec[ii] += oldspec[j] * ( yr - yl ) ;
2208//            if (regridTsys) newtsys[ii] += oldtsys[j] * ( yr - yl ) ;
2209//               wsum += ( yr - yl ) ;
2210//          }
2211//          newflag[ii] = newflag[ii] && oldflag[j] ;
2212//           }
2213//           else {
2214//          if (!oldflag[j]) {
2215//            newspec[ii] += oldspec[j] * ( zr - yl ) ;
2216//            if (regridTsys) newtsys[ii] += oldtsys[j] * ( zr - yl ) ;
2217//            wsum += ( zr - yl ) ;
2218//          }
2219//          newflag[ii] = newflag[ii] && oldflag[j] ;
2220//             ichan = j ;
2221//             break ;
2222//           }
2223//         }
2224//         else {
2225//           ichan = j - 1 ;
2226//           break ;
2227//         }
2228//       }
2229//       if ( wsum != 0.0 ) {
2230//         newspec[ii] /= wsum ;
2231//      if (regridTsys) newtsys[ii] /= wsum ;
2232//       }
2233//       wsum = 0.0 ;
2234//     }
2235//   }
2236//   else if ( dnu < 0.0 ) {
2237//     for ( int ii = 0 ; ii < nChan ; ii++ ) {
2238//       double zl = zi[ii] ;
2239//       double zr = zi[ii+1] ;
2240//       for ( int j = ichan ; j < oldsize ; j++ ) {
2241//         double yl = yi[j] ;
2242//         double yr = yi[j+1] ;
2243//         if ( yl >= zl ) {
2244//           if ( yr >= zl ) {
2245//             continue ;
2246//           }
2247//           else if ( yr >= zr ) {
2248//          if (!oldflag[j]) {
2249//            newspec[ii] += oldspec[j] * abs( yr - zl ) ;
2250//            if (regridTsys) newtsys[ii] += oldtsys[j] * abs( yr - zl ) ;
2251//            wsum += abs( yr - zl ) ;
2252//          }
2253//          newflag[ii] = newflag[ii] && oldflag[j] ;
2254//           }
2255//           else {
2256//          if (!oldflag[j]) {
2257//            newspec[ii] += oldspec[j] * abs( dnu ) ;
2258//            if (regridTsys) newtsys[ii] += oldtsys[j] * abs( dnu ) ;
2259//            wsum += abs( dnu ) ;
2260//          }
2261//          newflag[ii] = newflag[ii] && oldflag[j] ;
2262//             ichan = j ;
2263//             break ;
2264//           }
2265//         }
2266//         else if ( yl > zr ) {
2267//           if ( yr >= zr ) {
2268//          if (!oldflag[j]) {
2269//            newspec[ii] += oldspec[j] * abs( yr - yl ) ;
2270//            if (regridTsys) newtsys[ii] += oldtsys[j] * abs( yr - yl ) ;
2271//            wsum += abs( yr - yl ) ;
2272//          }
2273//          newflag[ii] = newflag[ii] && oldflag[j] ;
2274//           }
2275//           else {
2276//          if (!oldflag[j]) {
2277//            newspec[ii] += oldspec[j] * abs( zr - yl ) ;
2278//            if (regridTsys) newtsys[ii] += oldtsys[j] * abs( zr - yl ) ;
2279//            wsum += abs( zr - yl ) ;
2280//          }
2281//          newflag[ii] = newflag[ii] && oldflag[j] ;
2282//             ichan = j ;
2283//             break ;
2284//           }
2285//         }
2286//         else {
2287//           ichan = j - 1 ;
2288//           break ;
2289//         }
2290//       }
2291//       if ( wsum != 0.0 ) {
2292//         newspec[ii] /= wsum ;
2293//      if (regridTsys) newtsys[ii] /= wsum ;
2294//       }
2295//       wsum = 0.0 ;
2296//     }
2297//   }
2298// //   //ofs << "olddnu = " << olddnu << ", dnu = " << dnu << endl ;
2299// //   pile += dnu ;
2300// //   wedge = olddnu * ( refChan + 1 ) ;
2301// //   while ( wedge < pile ) {
2302// //     newspec[0] += olddnu * oldspec[refChan] ;
2303// //     newflag[0] = newflag[0] || oldflag[refChan] ;
2304// //     //ofs << "channel " << refChan << " is included in new channel 0" << endl ;
2305// //     refChan++ ;
2306// //     wedge += olddnu ;
2307// //     wsum += olddnu ;
2308// //     //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
2309// //   }
2310// //   frac = ( wedge - pile ) / olddnu ;
2311// //   wsum += ( 1.0 - frac ) * olddnu ;
2312// //   newspec[0] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
2313// //   newflag[0] = newflag[0] || oldflag[refChan] ;
2314// //   //ofs << "channel " << refChan << " is partly included in new channel 0" << " with fraction of " << ( 1.0 - frac ) << endl ;
2315// //   //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
2316// //   newspec[0] /= wsum ;
2317// //   //ofs << "newspec[0] = " << newspec[0] << endl ;
2318// //   //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
2319
2320// //   /***
2321// //    * ichan = 1 - nChan-2
2322// //    ***/
2323// //   for ( int ichan = 1 ; ichan < nChan - 1 ; ichan++ ) {
2324// //     pile += dnu ;
2325// //     newspec[ichan] += frac * olddnu * oldspec[refChan] ;
2326// //     newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
2327// //     //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << frac << endl ;
2328// //     refChan++ ;
2329// //     wedge += olddnu ;
2330// //     wsum = frac * olddnu ;
2331// //     //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
2332// //     while ( wedge < pile ) {
2333// //       newspec[ichan] += olddnu * oldspec[refChan] ;
2334// //       newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
2335// //       //ofs << "channel " << refChan << " is included in new channel " << ichan << endl ;
2336// //       refChan++ ;
2337// //       wedge += olddnu ;
2338// //       wsum += olddnu ;
2339// //       //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
2340// //     }
2341// //     frac = ( wedge - pile ) / olddnu ;
2342// //     wsum += ( 1.0 - frac ) * olddnu ;
2343// //     newspec[ichan] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
2344// //     newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
2345// //     //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << ( 1.0 - frac ) << endl ;
2346// //     //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
2347// //     //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
2348// //     newspec[ichan] /= wsum ;
2349// //     //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << endl ;
2350// //   }
2351
2352// //   /***
2353// //    * ichan = nChan-1
2354// //    ***/
2355// //   // NOTE: Assumed that all spectra have the same bandwidth
2356// //   pile += dnu ;
2357// //   newspec[nChan-1] += frac * olddnu * oldspec[refChan] ;
2358// //   newflag[nChan-1] = newflag[nChan-1] || oldflag[refChan] ;
2359// //   //ofs << "channel " << refChan << " is partly included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
2360// //   refChan++ ;
2361// //   wedge += olddnu ;
2362// //   wsum = frac * olddnu ;
2363// //   //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
2364// //   for ( int jchan = refChan ; jchan < oldsize ; jchan++ ) {
2365// //     newspec[nChan-1] += olddnu * oldspec[jchan] ;
2366// //     newflag[nChan-1] = newflag[nChan-1] || oldflag[jchan] ;
2367// //     wsum += olddnu ;
2368// //     //ofs << "channel " << jchan << " is included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
2369// //     //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
2370// //   }
2371// //   //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
2372// //   //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
2373// //   newspec[nChan-1] /= wsum ;
2374// //   //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << endl ;
2375
2376// //   // ofs.close() ;
2377
2378  specCol_.put( irow, newspec ) ;
2379  flagsCol_.put( irow, newflag ) ;
2380  if (regridTsys) tsysCol_.put( irow, newtsys );
2381
2382  return ;
2383}
2384
2385void Scantable::regridChannel( int nChan, double dnu, double fmin, int irow )
2386{
2387  Vector<Float> oldspec = specCol_( irow ) ;
2388  Vector<uChar> oldflag = flagsCol_( irow ) ;
2389  Vector<Float> oldtsys = tsysCol_( irow ) ;
2390  Vector<Float> newspec( nChan, 0 ) ;
2391  Vector<uChar> newflag( nChan, true ) ;
2392  Vector<Float> newtsys ;
2393  bool regridTsys = false ;
2394  if (oldtsys.size() == oldspec.size()) {
2395    regridTsys = true ;
2396    newtsys.resize(nChan,false) ;
2397    newtsys = 0 ;
2398  }
2399 
2400  // regrid
2401  vector<double> abcissa = getAbcissa( irow ) ;
2402  int oldsize = abcissa.size() ;
2403  double olddnu = abcissa[1] - abcissa[0] ;
2404  //int ichan = 0 ;
2405  double wsum = 0.0 ;
2406  Vector<double> zi( nChan+1 ) ;
2407  Vector<double> yi( oldsize + 1 ) ;
2408  Block<uInt> count( nChan, 0 ) ;
2409  yi[0] = abcissa[0] - 0.5 * olddnu ;
2410  for ( int ii = 1 ; ii < oldsize ; ii++ )
2411    yi[ii] = 0.5* (abcissa[ii-1] + abcissa[ii]) ;
2412  yi[oldsize] = abcissa[oldsize-1] \
2413    + 0.5 * (abcissa[oldsize-1] - abcissa[oldsize-2]) ;
2414//   cout << "olddnu=" << olddnu << ", dnu=" << dnu << " (diff=" << olddnu-dnu << ")" << endl ;
2415//   cout << "yi[0]=" << yi[0] << ", fmin=" << fmin << " (diff=" << yi[0]-fmin << ")" << endl ;
2416//   cout << "oldsize=" << oldsize << ", nChan=" << nChan << endl ;
2417
2418  // do not regrid if input parameters are almost same as current
2419  // spectral setup
2420  double dnuDiff = abs( ( dnu - olddnu ) / olddnu ) ;
2421  double oldfmin = min( yi[0], yi[oldsize] ) ;
2422  double fminDiff = abs( ( fmin - oldfmin ) / oldfmin ) ;
2423  double nChanDiff = nChan - oldsize ;
2424  double eps = 1.0e-8 ;
2425  if ( nChanDiff == 0 && dnuDiff < eps && fminDiff < eps )
2426    return ;
2427
2428  //zi[0] = abcissa[0] - 0.5 * olddnu ;
2429  //zi[0] = ((olddnu*dnu > 0) ? yi[0] : yi[oldsize]) ;
2430  if ( dnu > 0 )
2431    zi[0] = fmin - 0.5 * dnu ;
2432  else
2433    zi[0] = fmin + nChan * abs(dnu) ;
2434  for ( int ii = 1 ; ii < nChan ; ii++ )
2435    zi[ii] = zi[0] + dnu * ii ;
2436  zi[nChan] = zi[nChan-1] + dnu ;
2437  // Access zi and yi in ascending order
2438  int izs = ((dnu > 0) ? 0 : nChan ) ;
2439  int ize = ((dnu > 0) ? nChan : 0 ) ;
2440  int izincr = ((dnu > 0) ? 1 : -1 ) ;
2441  int ichan =  ((olddnu > 0) ? 0 : oldsize ) ;
2442  int iye = ((olddnu > 0) ? oldsize : 0 ) ;
2443  int iyincr = ((olddnu > 0) ? 1 : -1 ) ;
2444  //for ( int ii = izs ; ii != ize ; ii+=izincr ){
2445  int ii = izs ;
2446  while (ii != ize) {
2447    // always zl < zr
2448    double zl = zi[ii] ;
2449    double zr = zi[ii+izincr] ;
2450    // Need to access smaller index for the new spec, flag, and tsys.
2451    // Values between zi[k] and zi[k+1] should be stored in newspec[k], etc.
2452    int i = min(ii, ii+izincr) ;
2453    //for ( int jj = ichan ; jj != iye ; jj+=iyincr ) {
2454    int jj = ichan ;
2455    while (jj != iye) {
2456      // always yl < yr
2457      double yl = yi[jj] ;
2458      double yr = yi[jj+iyincr] ;
2459      // Need to access smaller index for the original spec, flag, and tsys.
2460      // Values between yi[k] and yi[k+1] are stored in oldspec[k], etc.
2461      int j = min(jj, jj+iyincr) ;
2462      if ( yr <= zl ) {
2463        jj += iyincr ;
2464        continue ;
2465      }
2466      else if ( yl <= zl ) {
2467        if ( yr < zr ) {
2468          if (!oldflag[j]) {
2469            newspec[i] += oldspec[j] * ( yr - zl ) ;
2470            if (regridTsys) newtsys[i] += oldtsys[j] * ( yr - zl ) ;
2471            wsum += ( yr - zl ) ;
2472            count[i]++ ;
2473          }
2474          newflag[i] = newflag[i] && oldflag[j] ;
2475        }
2476        else {
2477          if (!oldflag[j]) {
2478            newspec[i] += oldspec[j] * abs(dnu) ;
2479            if (regridTsys) newtsys[i] += oldtsys[j] * abs(dnu) ;
2480            wsum += abs(dnu) ;
2481            count[i]++ ;
2482          }
2483          newflag[i] = newflag[i] && oldflag[j] ;
2484          ichan = jj ;
2485          break ;
2486        }
2487      }
2488      else if ( yl < zr ) {
2489        if ( yr <= zr ) {
2490          if (!oldflag[j]) {
2491            newspec[i] += oldspec[j] * ( yr - yl ) ;
2492            if (regridTsys) newtsys[i] += oldtsys[j] * ( yr - yl ) ;
2493            wsum += ( yr - yl ) ;
2494            count[i]++ ;
2495          }
2496          newflag[i] = newflag[i] && oldflag[j] ;
2497        }
2498        else {
2499          if (!oldflag[j]) {
2500            newspec[i] += oldspec[j] * ( zr - yl ) ;
2501            if (regridTsys) newtsys[i] += oldtsys[j] * ( zr - yl ) ;
2502            wsum += ( zr - yl ) ;
2503            count[i]++ ;
2504          }
2505          newflag[i] = newflag[i] && oldflag[j] ;
2506          ichan = jj ;
2507          break ;
2508        }
2509      }
2510      else {
2511        //ichan = jj - iyincr ;
2512        break ;
2513      }
2514      jj += iyincr ;
2515    }
2516    if ( wsum != 0.0 ) {
2517      newspec[i] /= wsum ;
2518      if (regridTsys) newtsys[i] /= wsum ;
2519    }
2520    wsum = 0.0 ;
2521    ii += izincr ;
2522  }
2523
2524  // flag out channels without data
2525  // this is tentative since there is no specific definition
2526  // on bit flag...
2527  uChar noData = 1 << 7 ;
2528  for ( Int i = 0 ; i < nChan ; i++ ) {
2529    if ( count[i] == 0 )
2530      newflag[i] = noData ;
2531  }
2532
2533  specCol_.put( irow, newspec ) ;
2534  flagsCol_.put( irow, newflag ) ;
2535  if (regridTsys) tsysCol_.put( irow, newtsys );
2536
2537  return ;
2538}
2539
2540std::vector<float> Scantable::getWeather(int whichrow) const
2541{
2542  std::vector<float> out(5);
2543  //Float temperature, pressure, humidity, windspeed, windaz;
2544  weatherTable_.getEntry(out[0], out[1], out[2], out[3], out[4],
2545                         mweatheridCol_(uInt(whichrow)));
2546
2547
2548  return out;
2549}
2550
2551bool Scantable::isAllChannelsFlagged(uInt whichrow)
2552{
2553  uInt rflag;
2554  flagrowCol_.get(whichrow, rflag);
2555  if (rflag > 0)
2556    return true;
2557  bool flag;
2558  Vector<uChar> flags;
2559  flagsCol_.get(whichrow, flags);
2560  flag = (flags[0]>0);
2561  for (uInt i = 1; i < flags.size(); ++i) {
2562    flag &= (flags[i]>0);
2563  }
2564  //  return ((flag >> 7) == 1);
2565  return (flag > 0);
2566}
2567
2568std::size_t Scantable::nValidMask(const std::vector<bool>& mask)
2569{
2570  std::size_t nvalid=0;
2571  // the assertion lines had better be replaced with static_assert when c++11 is supported
2572  AlwaysAssert(static_cast<std::size_t>(true)==1, AipsError);
2573  AlwaysAssert(static_cast<std::size_t>(false)==0, AipsError);
2574  for (uInt i = 1; i < mask.size(); ++i) {
2575    nvalid += static_cast<std::size_t>(mask[i]);
2576  }
2577  return nvalid;
2578}
2579
2580
2581std::vector<std::string> Scantable::applyBaselineTable(const std::string& bltable, const bool returnfitresult, const std::string& outbltable, const bool outbltableexists, const bool overwrite)
2582{
2583  STBaselineTable btin = STBaselineTable(bltable);
2584
2585  Vector<Bool> applyCol = btin.getApply();
2586  int nRowBl = applyCol.size();
2587  if (nRowBl != nrow()) {
2588    throw(AipsError("Scantable and bltable have different number of rows."));
2589  }
2590
2591  std::vector<std::string> res;
2592  res.clear();
2593
2594  bool outBaselineTable = ((outbltable != "") && (!outbltableexists || overwrite));
2595  bool bltableidentical = (bltable == outbltable);
2596  STBaselineTable btout = STBaselineTable(*this);
2597  ROScalarColumn<Double> tcol = ROScalarColumn<Double>(table_, "TIME");
2598  Vector<Double> timeSecCol = tcol.getColumn();
2599
2600  for (int whichrow = 0; whichrow < nRowBl; ++whichrow) {
2601    if (applyCol[whichrow]) {
2602      std::vector<float> spec = getSpectrum(whichrow);
2603
2604      std::vector<bool> mask = btin.getMask(whichrow);  //use mask_bltable only
2605
2606      STBaselineFunc::FuncName ftype = btin.getFunctionName(whichrow);
2607      std::vector<int> fpar = btin.getFuncParam(whichrow);
2608      std::vector<float> params;
2609      float rms;
2610      std::vector<float> resfit = doApplyBaselineTable(spec, mask, ftype, fpar, params, rms);
2611      setSpectrum(resfit, whichrow);
2612
2613      if (returnfitresult) {
2614        res.push_back(packFittingResults(whichrow, params, rms));
2615      }
2616
2617      if (outBaselineTable) {
2618        if (outbltableexists) {
2619          if (overwrite) {
2620            if (bltableidentical) {
2621              btin.setresult(uInt(whichrow), Vector<Float>(params), Float(rms));
2622            } else {
2623              btout.setresult(uInt(whichrow), Vector<Float>(params), Float(rms));
2624            }
2625          }
2626        } else {
2627          btout.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
2628                           getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
2629                           true, ftype, fpar, std::vector<float>(),
2630                           getMaskListFromMask(mask), params, rms, spec.size(),
2631                           3.0, 0, 0.0, 0, std::vector<int>());
2632        }
2633      }
2634    }
2635  }
2636
2637  if (outBaselineTable) {
2638    if (bltableidentical) {
2639      btin.save(outbltable);
2640    } else {
2641      btout.save(outbltable);
2642    }
2643  }
2644
2645  return res;
2646}
2647
2648std::vector<std::string> Scantable::subBaseline(const std::vector<std::string>& blInfoList, const bool returnfitresult, const std::string& outbltable, const bool outbltableexists, const bool overwrite)
2649{
2650  int nRowBl = blInfoList.size();
2651  int nRowSt = nrow();
2652
2653  std::vector<std::string> res;
2654  res.clear();
2655
2656  bool outBaselineTable = ((outbltable != "") && (!outbltableexists || overwrite));
2657  if ((outbltable != "") && outbltableexists && !overwrite) {
2658    throw(AipsError("Cannot overwrite bltable. Set overwrite=True."));
2659  }
2660
2661  STBaselineTable* btp = NULL;
2662  ROScalarColumn<Double> tcol = ROScalarColumn<Double>(table_, "TIME");
2663  Vector<Double> timeSecCol = tcol.getColumn();
2664
2665  if (outBaselineTable) {
2666    if (outbltableexists) {
2667      btp = new STBaselineTable((String)outbltable);
2668    } else {
2669      btp = new STBaselineTable(*this);
2670      // for (int i = 0; i < nRowSt; ++i) {
2671      //   btp->appendbasedata(getScan(i), getCycle(i), getBeam(i), getIF(i), getPol(i),
2672      //                   0, timeSecCol[i]);
2673      //   btp->setApply(i, false);
2674      // }
2675    }
2676    int nrow = btp->nrow();
2677    for (int i = nrow; i < nRowSt; ++i) {
2678      btp->appendbasedata(getScan(i), getCycle(i), getBeam(i), getIF(i), getPol(i),
2679                          0, timeSecCol[i]);
2680      btp->setApply(i, false);
2681    }
2682  }
2683
2684  for (int i = 0; i < nRowBl; ++i) {
2685    int irow;
2686    STBaselineFunc::FuncName ftype;
2687    std::vector<bool> mask;
2688    std::vector<int> fpar;
2689    float clipth;
2690    int clipn;
2691    bool uself;
2692    float lfth;
2693    std::vector<int> lfedge;
2694    int lfavg;
2695    parseBlInfo(blInfoList[i], irow, ftype, fpar, mask, clipth, clipn, uself, lfth, lfedge, lfavg);
2696
2697    if (irow < nRowSt) {
2698      std::vector<float> spec = getSpectrum(irow);
2699      std::vector<float> params;
2700      float rms;
2701      std::vector<bool> finalmask;
2702      Bool doApply = True;
2703     
2704      if (!isAllChannelsFlagged(irow)) {
2705        std::vector<float> resfit = doSubtractBaseline(spec, mask, ftype, fpar, params, rms, finalmask, clipth, clipn, uself, irow, lfth, lfedge, lfavg);
2706        setSpectrum(resfit, irow);
2707      }
2708      else {
2709        doApply = False;
2710      }
2711
2712      if (returnfitresult) {
2713        res.push_back(packFittingResults(irow, params, rms));
2714      }
2715
2716      if (outBaselineTable) {
2717        Vector<Int> fparam(fpar.size());
2718        for (uInt j = 0; j < fparam.size(); ++j) {
2719          fparam[j] = (Int)fpar[j];
2720        }
2721
2722        btp->setdata(uInt(irow),
2723                    uInt(getScan(irow)), uInt(getCycle(irow)),
2724                    uInt(getBeam(irow)), uInt(getIF(irow)), uInt(getPol(irow)),
2725                    uInt(0), timeSecCol[irow], doApply, ftype, fparam,
2726                    Vector<Float>(), getMaskListFromMask(finalmask), Vector<Float>(params),
2727                    Float(rms), uInt(spec.size()), Float(clipth), uInt(clipn),
2728                    Float(0.0), uInt(0), Vector<uInt>());
2729      }
2730
2731    }
2732  }
2733
2734  if (outBaselineTable) {
2735    btp->save(outbltable);
2736  }
2737
2738  if (btp != NULL) {
2739        delete btp;
2740  }
2741
2742  return res;
2743}
2744
2745std::vector<float> Scantable::doApplyBaselineTable(std::vector<float>& spec,
2746                                                   std::vector<bool>& mask,
2747                                                   const STBaselineFunc::FuncName ftype,
2748                                                   std::vector<int>& fpar,
2749                                                   std::vector<float>& params,
2750                                                   float&rms)
2751{
2752  std::vector<bool> finalmask;
2753  std::vector<int> lfedge;
2754  return doSubtractBaseline(spec, mask, ftype, fpar, params, rms, finalmask, 0.0, 0, false, 0, 0.0, lfedge, 0);
2755}
2756
2757std::vector<float> Scantable::doSubtractBaseline(std::vector<float>& spec,
2758                                                 std::vector<bool>& mask,
2759                                                 const STBaselineFunc::FuncName ftype,
2760                                                 std::vector<int>& fpar,
2761                                                 std::vector<float>& params,
2762                                                 float&rms,
2763                                                 std::vector<bool>& finalmask,
2764                                                 float clipth,
2765                                                 int clipn,
2766                                                 bool uself,
2767                                                 int irow,
2768                                                 float lfth,
2769                                                 std::vector<int>& lfedge,
2770                                                 int lfavg)
2771{
2772  if (uself) {
2773    STLineFinder lineFinder = STLineFinder();
2774    initLineFinder(lfedge, lfth, lfavg, lineFinder);
2775    std::vector<int> currentEdge;
2776    mask = getCompositeChanMask(irow, mask, lfedge, currentEdge, lineFinder);
2777  } else {
2778    mask = getCompositeChanMask(irow, mask);
2779  }
2780
2781  std::vector<float> res;
2782  if (ftype == STBaselineFunc::Polynomial) {
2783    res = doPolynomialFitting(spec, mask, fpar[0], params, rms, finalmask, clipth, clipn);
2784  } else if (ftype == STBaselineFunc::Chebyshev) {
2785    res = doChebyshevFitting(spec, mask, fpar[0], params, rms, finalmask, clipth, clipn);
2786  } else if (ftype == STBaselineFunc::CSpline) {
2787    int nclip = 0;
2788    size_t numChan = spec.size();
2789    if (cubicSplineModelPool_.find(numChan) == cubicSplineModelPool_.end()) {
2790      cubicSplineModelPool_[numChan] = getPolynomialModel(3, numChan, &Scantable::getNormalPolynomial);
2791    }
2792    if (fpar.size() > 1) { // reading from baseline table in which pieceEdges are already calculated and stored.
2793      //res = doCubicSplineFitting(spec, mask, fpar, params, rms, finalmask, clipth, clipn);
2794      res = doCubicSplineLeastSquareFitting(spec, mask,
2795                                            cubicSplineModelPool_[numChan],
2796                                            fpar.size()-1, true, fpar, params,
2797                                            rms, finalmask, nclip, clipth,
2798                                            clipn);
2799    } else {               // usual cspline fitting by giving nPiece only. fpar will be replaced with pieceEdges.
2800      //res = doCubicSplineFitting(spec, mask, fpar[0], fpar, params, rms, finalmask, clipth, clipn);
2801      res = doCubicSplineLeastSquareFitting(spec, mask,
2802                                            cubicSplineModelPool_[numChan],
2803                                            fpar[0], false, fpar, params,
2804                                            rms, finalmask, nclip, clipth,
2805                                            clipn);
2806    }
2807  } else if (ftype == STBaselineFunc::Sinusoid) {
2808    res = doSinusoidFitting(spec, mask, fpar, params, rms, finalmask, clipth, clipn);
2809  }
2810
2811  return res;
2812}
2813
2814std::string Scantable::packFittingResults(const int irow, const std::vector<float>& params, const float rms)
2815{
2816  // returned value: "irow:params[0],params[1],..,params[n-1]:rms"
2817  ostringstream os;
2818  os << irow << ':';
2819  for (uInt i = 0; i < params.size(); ++i) {
2820    if (i > 0) {
2821      os << ',';
2822    }
2823    os << params[i];
2824  }
2825  os << ':' << rms;
2826
2827  return os.str();
2828}
2829
2830void Scantable::parseBlInfo(const std::string& blInfo, int& irow, STBaselineFunc::FuncName& ftype, std::vector<int>& fpar, std::vector<bool>& mask, float& thresClip, int& nIterClip, bool& useLineFinder, float& thresLF, std::vector<int>& edgeLF, int& avgLF)
2831{
2832  // The baseline info to be parsed must be column-delimited string like
2833  // "0:chebyshev:5:3,5,169,174,485,487" where the elements are
2834  // row number, funcType, funcOrder, maskList, clipThreshold, clipNIter,
2835  // useLineFinder, lfThreshold, lfEdge and lfChanAvgLimit.
2836
2837  std::vector<string> res = splitToStringList(blInfo, ':');
2838  if (res.size() < 4) {
2839    throw(AipsError("baseline info has bad format")) ;
2840  }
2841
2842  string ftype0, fpar0, masklist0, uself0, edge0;
2843  std::vector<int> masklist;
2844
2845  stringstream ss;
2846  ss << res[0];
2847  ss >> irow;
2848  ss.clear(); ss.str("");
2849
2850  ss << res[1];
2851  ss >> ftype0;
2852  if (ftype0 == "poly") {
2853    ftype = STBaselineFunc::Polynomial;
2854  } else if (ftype0 == "cspline") {
2855    ftype = STBaselineFunc::CSpline;
2856  } else if (ftype0 == "sinusoid") {
2857    ftype = STBaselineFunc::Sinusoid;
2858  } else if (ftype0 == "chebyshev") {
2859    ftype = STBaselineFunc::Chebyshev;
2860  } else {
2861    throw(AipsError("invalid function type."));
2862  }
2863  ss.clear(); ss.str("");
2864
2865  ss << res[2];
2866  ss >> fpar0;
2867  fpar = splitToIntList(fpar0, ',');
2868  ss.clear(); ss.str("");
2869
2870  ss << res[3];
2871  ss >> masklist0;
2872  mask = getMaskFromMaskList(nchan(getIF(irow)), splitToIntList(masklist0, ','));
2873  ss.clear(); ss.str("");
2874
2875  ss << res[4];
2876  ss >> thresClip;
2877  ss.clear(); ss.str("");
2878
2879  ss << res[5];
2880  ss >> nIterClip;
2881  ss.clear(); ss.str("");
2882
2883  ss << res[6];
2884  ss >> uself0;
2885  if (uself0 == "true") {
2886    useLineFinder = true;
2887  } else {
2888    useLineFinder = false;
2889  }
2890  ss.clear(); ss.str("");
2891
2892  if (useLineFinder) {
2893    ss << res[7];
2894    ss >> thresLF;
2895    ss.clear(); ss.str("");
2896
2897    ss << res[8];
2898    ss >> edge0;
2899    edgeLF = splitToIntList(edge0, ',');
2900    ss.clear(); ss.str("");
2901
2902    ss << res[9];
2903    ss >> avgLF;
2904    ss.clear(); ss.str("");
2905  }
2906
2907}
2908
2909std::vector<int> Scantable::splitToIntList(const std::string& s, const char delim)
2910{
2911  istringstream iss(s);
2912  string tmp;
2913  int tmpi;
2914  std::vector<int> res;
2915  stringstream ss;
2916  while (getline(iss, tmp, delim)) {
2917    ss << tmp;
2918    ss >> tmpi;
2919    res.push_back(tmpi);
2920    ss.clear(); ss.str("");
2921  }
2922
2923  return res;
2924}
2925
2926std::vector<string> Scantable::splitToStringList(const std::string& s, const char delim)
2927{
2928  istringstream iss(s);
2929  std::string tmp;
2930  std::vector<string> res;
2931  while (getline(iss, tmp, delim)) {
2932    res.push_back(tmp);
2933  }
2934
2935  return res;
2936}
2937
2938std::vector<bool> Scantable::getMaskFromMaskList(const int nchan, const std::vector<int>& masklist)
2939{
2940  if (masklist.size() % 2 != 0) {
2941    throw(AipsError("masklist must have even number of elements."));
2942  }
2943
2944  std::vector<bool> res(nchan);
2945
2946  for (int i = 0; i < nchan; ++i) {
2947    res[i] = false;
2948  }
2949  for (uInt j = 0; j < masklist.size(); j += 2) {
2950    for (int i = masklist[j]; i <= min(nchan-1, masklist[j+1]); ++i) {
2951      res[i] = true;
2952    }
2953  }
2954
2955  return res;
2956}
2957
2958Vector<uInt> Scantable::getMaskListFromMask(const std::vector<bool>& mask)
2959{
2960  std::vector<int> masklist;
2961  masklist.clear();
2962
2963  for (uInt i = 0; i < mask.size(); ++i) {
2964    if (mask[i]) {
2965      if ((i == 0)||(i == mask.size()-1)) {
2966        masklist.push_back(i);
2967      } else {
2968        if ((mask[i])&&(!mask[i-1])) {
2969          masklist.push_back(i);
2970        }
2971        if ((mask[i])&&(!mask[i+1])) {
2972          masklist.push_back(i);
2973        }
2974      }
2975    }
2976  }
2977
2978  Vector<uInt> res(masklist.size());
2979  for (uInt i = 0; i < masklist.size(); ++i) {
2980    res[i] = (uInt)masklist[i];
2981  }
2982
2983  return res;
2984}
2985
2986void Scantable::initialiseBaselining(const std::string& blfile,
2987                                     ofstream& ofs,
2988                                     const bool outLogger,
2989                                     bool& outTextFile,
2990                                     bool& csvFormat,
2991                                     String& coordInfo,
2992                                     bool& hasSameNchan,
2993                                     const std::string& progressInfo,
2994                                     bool& showProgress,
2995                                     int& minNRow,
2996                                     Vector<Double>& timeSecCol)
2997{
2998  csvFormat = false;
2999  outTextFile = false;
3000
3001  if (blfile != "") {
3002    csvFormat = (blfile.substr(0, 1) == "T");
3003    ofs.open(blfile.substr(1).c_str(), ios::out | ios::app);
3004    if (ofs) outTextFile = true;
3005  }
3006
3007  coordInfo = "";
3008  hasSameNchan = true;
3009
3010  if (outLogger || outTextFile) {
3011    coordInfo = getCoordInfo()[0];
3012    if (coordInfo == "") coordInfo = "channel";
3013    hasSameNchan = hasSameNchanOverIFs();
3014  }
3015
3016  parseProgressInfo(progressInfo, showProgress, minNRow);
3017
3018  ROScalarColumn<Double> tcol = ROScalarColumn<Double>(table_, "TIME");
3019  timeSecCol = tcol.getColumn();
3020}
3021
3022void Scantable::finaliseBaselining(const bool outBaselineTable,
3023                                   STBaselineTable* pbt,
3024                                   const string& bltable,
3025                                   const bool outTextFile,
3026                                   ofstream& ofs)
3027{
3028  if (outBaselineTable) {
3029    pbt->save(bltable);
3030  }
3031
3032  if (outTextFile) ofs.close();
3033}
3034
3035void Scantable::initLineFinder(const std::vector<int>& edge,
3036                               const float threshold,
3037                               const int chanAvgLimit,
3038                               STLineFinder& lineFinder)
3039{
3040  if ((edge.size() > 2) && (edge.size() < getIFNos().size()*2)) {
3041    throw(AipsError("Length of edge element info is less than that of IFs"));
3042  }
3043
3044  lineFinder.setOptions(threshold, 3, chanAvgLimit);
3045}
3046
3047void Scantable::polyBaseline(const std::vector<bool>& mask, int order,
3048                             float thresClip, int nIterClip,
3049                             bool getResidual,
3050                             const std::string& progressInfo,
3051                             const bool outLogger, const std::string& blfile,
3052                             const std::string& bltable)
3053{
3054  /****
3055  double TimeStart = mathutil::gettimeofday_sec();
3056  ****/
3057
3058  try {
3059    ofstream ofs;
3060    String coordInfo;
3061    bool hasSameNchan, outTextFile, csvFormat, showProgress;
3062    int minNRow;
3063    int nRow = nrow();
3064    std::vector<bool> chanMask, finalChanMask;
3065    float rms;
3066    bool outBaselineTable = (bltable != "");
3067    STBaselineTable bt = STBaselineTable(*this);
3068    Vector<Double> timeSecCol;
3069    size_t flagged=0;
3070
3071    initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
3072                         coordInfo, hasSameNchan,
3073                         progressInfo, showProgress, minNRow,
3074                         timeSecCol);
3075
3076    std::vector<int> nChanNos;
3077    std::vector<std::vector<std::vector<double> > > modelReservoir;
3078    modelReservoir = getPolynomialModelReservoir(order,
3079                                                 &Scantable::getNormalPolynomial,
3080                                                 nChanNos);
3081    int nModel = modelReservoir.size();
3082
3083    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
3084      std::vector<float> sp = getSpectrum(whichrow);
3085      chanMask = getCompositeChanMask(whichrow, mask);
3086      std::vector<float> params;
3087
3088      //if (flagrowCol_(whichrow) == 0) {
3089      if (flagrowCol_(whichrow)==0 && nValidMask(chanMask)>0) {
3090        int nClipped = 0;
3091        std::vector<float> res;
3092        res = doLeastSquareFitting(sp, chanMask,
3093                                   modelReservoir[getIdxOfNchan(sp.size(), nChanNos)],
3094                                   params, rms, finalChanMask,
3095                                   nClipped, thresClip, nIterClip, getResidual);
3096
3097        if (outBaselineTable) {
3098          bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3099                        getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3100                        true, STBaselineFunc::Polynomial, order, std::vector<float>(),
3101                        getMaskListFromMask(finalChanMask), params, rms, sp.size(),
3102                        thresClip, nIterClip, 0.0, 0, std::vector<int>());
3103        } else {
3104          setSpectrum(res, whichrow);
3105        }
3106
3107        outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
3108                            coordInfo, hasSameNchan, ofs, "polyBaseline()",
3109                            params, nClipped);
3110      } else {
3111        // no valid channels to fit (flag the row)
3112        flagrowCol_.put(whichrow, 1);
3113        ++flagged;
3114        if (outBaselineTable) {
3115          params.resize(nModel);
3116          for (uInt i = 0; i < params.size(); ++i) {
3117            params[i] = 0.0;
3118          }
3119          bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3120                        getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3121                        true, STBaselineFunc::Polynomial, order, std::vector<float>(),
3122                        getMaskListFromMask(chanMask), params, 0.0, sp.size(),
3123                        thresClip, nIterClip, 0.0, 0, std::vector<int>());
3124        }
3125      }
3126
3127      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
3128    }
3129
3130    finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
3131    if (flagged > 0) {
3132      LogIO os( LogOrigin( "Scantable", "polyBaseline()") ) ;
3133      os << LogIO::WARN << "Baseline subtraction is skipped for " << flagged << " spectra due to too few valid channels to operate fit. The spectra will be flagged in output data." << LogIO::POST;
3134    }
3135  } catch (...) {
3136    throw;
3137  }
3138
3139  /****
3140  double TimeEnd = mathutil::gettimeofday_sec();
3141  double elapse1 = TimeEnd - TimeStart;
3142  std::cout << "poly-new   : " << elapse1 << " (sec.)" << endl;
3143  ****/
3144}
3145
3146void Scantable::autoPolyBaseline(const std::vector<bool>& mask, int order,
3147                                 float thresClip, int nIterClip,
3148                                 const std::vector<int>& edge,
3149                                 float threshold, int chanAvgLimit,
3150                                 bool getResidual,
3151                                 const std::string& progressInfo,
3152                                 const bool outLogger, const std::string& blfile,
3153                                 const std::string& bltable)
3154{
3155  try {
3156    ofstream ofs;
3157    String coordInfo;
3158    bool hasSameNchan, outTextFile, csvFormat, showProgress;
3159    int minNRow;
3160    int nRow = nrow();
3161    std::vector<bool> chanMask, finalChanMask;
3162    float rms;
3163    bool outBaselineTable = (bltable != "");
3164    STBaselineTable bt = STBaselineTable(*this);
3165    Vector<Double> timeSecCol;
3166    STLineFinder lineFinder = STLineFinder();
3167    size_t flagged=0;
3168
3169    initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
3170                         coordInfo, hasSameNchan,
3171                         progressInfo, showProgress, minNRow,
3172                         timeSecCol);
3173
3174    initLineFinder(edge, threshold, chanAvgLimit, lineFinder);
3175
3176    std::vector<int> nChanNos;
3177    std::vector<std::vector<std::vector<double> > > modelReservoir;
3178    modelReservoir = getPolynomialModelReservoir(order,
3179                                                 &Scantable::getNormalPolynomial,
3180                                                 nChanNos);
3181    int nModel = modelReservoir.size();
3182
3183    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
3184      std::vector<float> sp = getSpectrum(whichrow);
3185      std::vector<int> currentEdge;
3186      chanMask = getCompositeChanMask(whichrow, mask, edge, currentEdge, lineFinder);
3187      std::vector<float> params;
3188
3189      //if (flagrowCol_(whichrow) == 0) {
3190      if (flagrowCol_(whichrow)==0 && nValidMask(chanMask)>0) {
3191        int nClipped = 0;
3192        std::vector<float> res;
3193        res = doLeastSquareFitting(sp, chanMask,
3194                                   modelReservoir[getIdxOfNchan(sp.size(), nChanNos)],
3195                                   params, rms, finalChanMask,
3196                                   nClipped, thresClip, nIterClip, getResidual);
3197
3198        if (outBaselineTable) {
3199          bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3200                        getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3201                        true, STBaselineFunc::Polynomial, order, std::vector<float>(),
3202                        getMaskListFromMask(finalChanMask), params, rms, sp.size(),
3203                        thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
3204        } else {
3205          setSpectrum(res, whichrow);
3206        }
3207
3208        outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
3209                            coordInfo, hasSameNchan, ofs, "autoPolyBaseline()",
3210                            params, nClipped);
3211      } else {
3212        // no valid channels to fit (flag the row)
3213        flagrowCol_.put(whichrow, 1);
3214        ++flagged;
3215        if (outBaselineTable) {
3216          params.resize(nModel);
3217          for (uInt i = 0; i < params.size(); ++i) {
3218            params[i] = 0.0;
3219          }
3220          bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3221                        getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3222                        true, STBaselineFunc::Polynomial, order, std::vector<float>(),
3223                        getMaskListFromMask(chanMask), params, 0.0, sp.size(),
3224                        thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
3225        }
3226      }
3227
3228      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
3229    }
3230
3231    finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
3232    if (flagged > 0) {
3233      LogIO os( LogOrigin( "Scantable", "autoPolyBaseline()") ) ;
3234      os << LogIO::WARN << "Baseline subtraction is skipped for " << flagged << " spectra due to too few valid channels to operate fit. The spectra will be flagged in output data." << LogIO::POST;
3235    }
3236  } catch (...) {
3237    throw;
3238  }
3239}
3240
3241void Scantable::chebyshevBaseline(const std::vector<bool>& mask, int order,
3242                                  float thresClip, int nIterClip,
3243                                  bool getResidual,
3244                                  const std::string& progressInfo,
3245                                  const bool outLogger, const std::string& blfile,
3246                                  const std::string& bltable)
3247{
3248  /*
3249  double TimeStart = mathutil::gettimeofday_sec();
3250  */
3251
3252  try {
3253    ofstream ofs;
3254    String coordInfo;
3255    bool hasSameNchan, outTextFile, csvFormat, showProgress;
3256    int minNRow;
3257    int nRow = nrow();
3258    std::vector<bool> chanMask, finalChanMask;
3259    float rms;
3260    bool outBaselineTable = (bltable != "");
3261    STBaselineTable bt = STBaselineTable(*this);
3262    Vector<Double> timeSecCol;
3263    size_t flagged=0;
3264
3265    initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
3266                         coordInfo, hasSameNchan,
3267                         progressInfo, showProgress, minNRow,
3268                         timeSecCol);
3269
3270    std::vector<int> nChanNos;
3271    std::vector<std::vector<std::vector<double> > > modelReservoir;
3272    modelReservoir = getPolynomialModelReservoir(order,
3273                                                 &Scantable::getChebyshevPolynomial,
3274                                                 nChanNos);
3275    int nModel = modelReservoir.size();
3276
3277    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
3278      std::vector<float> sp = getSpectrum(whichrow);
3279      chanMask = getCompositeChanMask(whichrow, mask);
3280      std::vector<float> params;
3281
3282      //      if (flagrowCol_(whichrow) == 0) {
3283      if (flagrowCol_(whichrow)==0 && nValidMask(chanMask)>0) {
3284        int nClipped = 0;
3285        std::vector<float> res;
3286        res = doLeastSquareFitting(sp, chanMask,
3287                                   modelReservoir[getIdxOfNchan(sp.size(), nChanNos)],
3288                                   params, rms, finalChanMask,
3289                                   nClipped, thresClip, nIterClip, getResidual);
3290
3291        if (outBaselineTable) {
3292          bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3293                        getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3294                        true, STBaselineFunc::Chebyshev, order, std::vector<float>(),
3295                        getMaskListFromMask(finalChanMask), params, rms, sp.size(),
3296                        thresClip, nIterClip, 0.0, 0, std::vector<int>());
3297        } else {
3298          setSpectrum(res, whichrow);
3299        }
3300
3301        outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
3302                            coordInfo, hasSameNchan, ofs, "chebyshevBaseline()",
3303                            params, nClipped);
3304      } else {
3305        // no valid channels to fit (flag the row)
3306        flagrowCol_.put(whichrow, 1);
3307        ++flagged;
3308        if (outBaselineTable) {
3309          params.resize(nModel);
3310          for (uInt i = 0; i < params.size(); ++i) {
3311            params[i] = 0.0;
3312          }
3313          bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3314                        getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3315                        true, STBaselineFunc::Chebyshev, order, std::vector<float>(),
3316                        getMaskListFromMask(chanMask), params, 0.0, sp.size(),
3317                        thresClip, nIterClip, 0.0, 0, std::vector<int>());
3318        }
3319      }
3320
3321      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
3322    }
3323   
3324    finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
3325
3326    if (flagged > 0) {
3327      LogIO os( LogOrigin( "Scantable", "chebyshevBaseline()") ) ;
3328      os << LogIO::WARN << "Baseline subtraction is skipped for " << flagged << " spectra due to too few valid channels to operate fit. The spectra will be flagged in output data." << LogIO::POST;
3329    }
3330  } catch (...) {
3331    throw;
3332  }
3333
3334  /*
3335  double TimeEnd = mathutil::gettimeofday_sec();
3336  double elapse1 = TimeEnd - TimeStart;
3337  std::cout << "cheby   : " << elapse1 << " (sec.)" << endl;
3338  */
3339}
3340
3341void Scantable::autoChebyshevBaseline(const std::vector<bool>& mask, int order,
3342                                      float thresClip, int nIterClip,
3343                                      const std::vector<int>& edge,
3344                                      float threshold, int chanAvgLimit,
3345                                      bool getResidual,
3346                                      const std::string& progressInfo,
3347                                      const bool outLogger, const std::string& blfile,
3348                                      const std::string& bltable)
3349{
3350  try {
3351    ofstream ofs;
3352    String coordInfo;
3353    bool hasSameNchan, outTextFile, csvFormat, showProgress;
3354    int minNRow;
3355    int nRow = nrow();
3356    std::vector<bool> chanMask, finalChanMask;
3357    float rms;
3358    bool outBaselineTable = (bltable != "");
3359    STBaselineTable bt = STBaselineTable(*this);
3360    Vector<Double> timeSecCol;
3361    STLineFinder lineFinder = STLineFinder();
3362    size_t flagged=0;
3363
3364    initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
3365                         coordInfo, hasSameNchan,
3366                         progressInfo, showProgress, minNRow,
3367                         timeSecCol);
3368
3369    initLineFinder(edge, threshold, chanAvgLimit, lineFinder);
3370
3371    std::vector<int> nChanNos;
3372    std::vector<std::vector<std::vector<double> > > modelReservoir;
3373    modelReservoir = getPolynomialModelReservoir(order,
3374                                                 &Scantable::getChebyshevPolynomial,
3375                                                 nChanNos);
3376    int nModel = modelReservoir.size();
3377
3378    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
3379      std::vector<float> sp = getSpectrum(whichrow);
3380      std::vector<int> currentEdge;
3381      chanMask = getCompositeChanMask(whichrow, mask, edge, currentEdge, lineFinder);
3382      std::vector<float> params;
3383
3384      //      if (flagrowCol_(whichrow) == 0) {
3385      if (flagrowCol_(whichrow)==0 && nValidMask(chanMask)>0) {
3386        int nClipped = 0;
3387        std::vector<float> res;
3388        res = doLeastSquareFitting(sp, chanMask,
3389                                   modelReservoir[getIdxOfNchan(sp.size(), nChanNos)],
3390                                   params, rms, finalChanMask,
3391                                   nClipped, thresClip, nIterClip, getResidual);
3392
3393        if (outBaselineTable) {
3394          bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3395                        getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3396                        true, STBaselineFunc::Chebyshev, order, std::vector<float>(),
3397                        getMaskListFromMask(finalChanMask), params, rms, sp.size(),
3398                        thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
3399        } else {
3400          setSpectrum(res, whichrow);
3401        }
3402
3403        outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
3404                            coordInfo, hasSameNchan, ofs, "autoChebyshevBaseline()",
3405                            params, nClipped);
3406      } else {
3407        // no valid channels to fit (flag the row)
3408        flagrowCol_.put(whichrow, 1);
3409        ++flagged;
3410        if (outBaselineTable) {
3411          params.resize(nModel);
3412          for (uInt i = 0; i < params.size(); ++i) {
3413            params[i] = 0.0;
3414          }
3415          bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3416                        getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3417                        true, STBaselineFunc::Chebyshev, order, std::vector<float>(),
3418                        getMaskListFromMask(chanMask), params, 0.0, sp.size(),
3419                        thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
3420        }
3421      }
3422
3423      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
3424    }
3425
3426    finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
3427
3428    if (flagged > 0) {
3429      LogIO os( LogOrigin( "Scantable", "autoChebyshevBaseline()") ) ;
3430      os << LogIO::WARN << "Baseline subtraction is skipped for " << flagged << " spectra due to too few valid channels to operate fit. The spectra will be flagged in output data." << LogIO::POST;
3431    }
3432  } catch (...) {
3433    throw;
3434  }
3435}
3436
3437double Scantable::calculateModelSelectionCriteria(const std::string& valname,
3438                                                  const std::string& blfunc,
3439                                                  int order,
3440                                                  const std::vector<bool>& inMask,
3441                                                  int whichrow,
3442                                                  bool useLineFinder,
3443                                                  const std::vector<int>& edge,
3444                                                  float threshold,
3445                                                  int chanAvgLimit)
3446{
3447  std::vector<float> sp = getSpectrum(whichrow);
3448  std::vector<bool> chanMask;
3449  chanMask.clear();
3450
3451  if (useLineFinder) {
3452    STLineFinder lineFinder = STLineFinder();
3453    initLineFinder(edge, threshold, chanAvgLimit, lineFinder);
3454    std::vector<int> currentEdge;
3455    chanMask = getCompositeChanMask(whichrow, inMask, edge, currentEdge, lineFinder);
3456  } else {
3457    chanMask = getCompositeChanMask(whichrow, inMask);
3458  }
3459
3460  return doCalculateModelSelectionCriteria(valname, sp, chanMask, blfunc, order);
3461}
3462
3463double Scantable::doCalculateModelSelectionCriteria(const std::string& valname, const std::vector<float>& spec, const std::vector<bool>& mask, const std::string& blfunc, int order)
3464{
3465  int nparam;
3466  std::vector<float> params;
3467  std::vector<bool> finalChanMask;
3468  float rms;
3469  int nClipped = 0;
3470  std::vector<float> res;
3471  if (blfunc == "poly") {
3472    nparam = order + 1;
3473    res = doPolynomialFitting(spec, mask, order, params, rms, finalChanMask, nClipped);
3474  } else if (blfunc == "chebyshev") {
3475    nparam = order + 1;
3476    res = doChebyshevFitting(spec, mask, order, params, rms, finalChanMask, nClipped);
3477  } else if (blfunc == "cspline") {
3478    std::vector<int> pieceEdges;//(order+1);  //order = npiece
3479    nparam = order + 3;
3480    res = doCubicSplineFitting(spec, mask, order, false, pieceEdges, params, rms, finalChanMask, nClipped);
3481  } else if (blfunc == "sinusoid") {
3482    std::vector<int> nWaves;
3483    nWaves.clear();
3484    for (int i = 0; i <= order; ++i) {
3485      nWaves.push_back(i);
3486    }
3487    nparam = 2*order + 1;  // order = nwave
3488    res = doSinusoidFitting(spec, mask, nWaves, params, rms, finalChanMask, nClipped);
3489  } else {
3490    throw(AipsError("blfunc must be poly, chebyshev, cspline or sinusoid."));
3491  }
3492
3493  double msq = 0.0;
3494  int nusedchan = 0;
3495  int nChan = res.size();
3496  for (int i = 0; i < nChan; ++i) {
3497    if (mask[i]) {
3498      msq += (double)res[i]*(double)res[i];
3499      nusedchan++;
3500    }
3501  }
3502  if (nusedchan == 0) {
3503    throw(AipsError("all channels masked."));
3504  }
3505  msq /= (double)nusedchan;
3506
3507  nparam++;  //add 1 for sigma of Gaussian distribution
3508  const double PI = 6.0 * asin(0.5); // PI (= 3.141592653...)
3509
3510  if (valname.find("aic") == 0) {
3511    // Original Akaike Information Criterion (AIC)
3512    double aic = nusedchan * (log(2.0 * PI * msq) + 1.0) + 2.0 * nparam;
3513
3514    // Corrected AIC by Sugiura(1978) (AICc)
3515    if (valname == "aicc") {
3516      if (nusedchan - nparam - 1 <= 0) {
3517        throw(AipsError("channel size is too small to calculate AICc."));
3518      }
3519      aic += 2.0*nparam*(nparam + 1)/(double)(nusedchan - nparam - 1);
3520    }
3521
3522    return aic;
3523
3524  } else if (valname == "bic") {
3525    // Bayesian Information Criterion (BIC)
3526    double bic = nusedchan * log(msq) + nparam * log((double)nusedchan);
3527    return bic;
3528
3529  } else if (valname == "gcv") {
3530    // Generalised Cross Validation
3531    double x = 1.0 - (double)nparam / (double)nusedchan;
3532    double gcv = msq / (x * x);
3533    return gcv;
3534
3535  } else {
3536    throw(AipsError("valname must be aic, aicc, bic or gcv."));
3537  }
3538}
3539
3540double Scantable::getNormalPolynomial(int n, double x) {
3541  if (n == 0) {
3542    return 1.0;
3543  } else if (n > 0) {
3544    double res = 1.0;
3545    for (int i = 0; i < n; ++i) {
3546      res *= x;
3547    }
3548    return res;
3549  } else {
3550    if (x == 0.0) {
3551      throw(AipsError("infinity result: x=0 given for negative power."));
3552    } else {
3553      return pow(x, (double)n);
3554    }
3555  }
3556}
3557
3558double Scantable::getChebyshevPolynomial(int n, double x) {
3559  if ((x < -1.0)||(x > 1.0)) {
3560    throw(AipsError("out of definition range (-1 <= x <= 1)."));
3561  } else if (x == 1.0) {
3562    return 1.0;
3563  } else if (x == 0.0) {
3564    double res;
3565    if (n%2 == 0) {
3566      if (n%4 == 0) {
3567        res = 1.0;
3568      } else {
3569        res = -1.0;
3570      }
3571    } else {
3572      res = 0.0;
3573    }
3574    return res;
3575  } else if (x == -1.0) {
3576    double res = (n%2 == 0 ? 1.0 : -1.0);
3577    return res;
3578  } else if (n < 0) {
3579    throw(AipsError("the order must be zero or positive."));
3580  } else if (n == 0) {
3581    return 1.0;
3582  } else if (n == 1) {
3583    return x;
3584  } else {
3585    double res[n+1];
3586    for (int i = 0; i < n+1; ++i) {
3587      double res0 = 0.0;
3588      if (i == 0) {
3589        res0 = 1.0;
3590      } else if (i == 1) {
3591        res0 = x;
3592      } else {
3593        res0 = 2.0 * x * res[i-1] - res[i-2];
3594      }
3595      res[i] = res0;
3596    }
3597    return res[n];
3598  }
3599}
3600
3601std::vector<float> Scantable::doPolynomialFitting(const std::vector<float>& data,
3602                                                  const std::vector<bool>& mask,
3603                                                  int order,
3604                                                  std::vector<float>& params,
3605                                                  float& rms,
3606                                                  std::vector<bool>& finalmask,
3607                                                  float clipth,
3608                                                  int clipn)
3609{
3610  int nClipped = 0;
3611  return doPolynomialFitting(data, mask, order, params, rms, finalmask, nClipped, clipth, clipn);
3612}
3613
3614std::vector<float> Scantable::doPolynomialFitting(const std::vector<float>& data,
3615                                                  const std::vector<bool>& mask,
3616                                                  int order,
3617                                                  std::vector<float>& params,
3618                                                  float& rms,
3619                                                  std::vector<bool>& finalMask,
3620                                                  int& nClipped,
3621                                                  float thresClip,
3622                                                  int nIterClip,
3623                                                  bool getResidual)
3624{
3625  return doLeastSquareFitting(data, mask,
3626                              getPolynomialModel(order, data.size(), &Scantable::getNormalPolynomial),
3627                              params, rms, finalMask,
3628                              nClipped, thresClip, nIterClip,
3629                              getResidual);
3630}
3631
3632std::vector<float> Scantable::doChebyshevFitting(const std::vector<float>& data,
3633                                                 const std::vector<bool>& mask,
3634                                                 int order,
3635                                                 std::vector<float>& params,
3636                                                 float& rms,
3637                                                 std::vector<bool>& finalmask,
3638                                                 float clipth,
3639                                                 int clipn)
3640{
3641  int nClipped = 0;
3642  return doChebyshevFitting(data, mask, order, params, rms, finalmask, nClipped, clipth, clipn);
3643}
3644
3645std::vector<float> Scantable::doChebyshevFitting(const std::vector<float>& data,
3646                                                 const std::vector<bool>& mask,
3647                                                 int order,
3648                                                 std::vector<float>& params,
3649                                                 float& rms,
3650                                                 std::vector<bool>& finalMask,
3651                                                 int& nClipped,
3652                                                 float thresClip,
3653                                                 int nIterClip,
3654                                                 bool getResidual)
3655{
3656  return doLeastSquareFitting(data, mask,
3657                              getPolynomialModel(order, data.size(), &Scantable::getChebyshevPolynomial),
3658                              params, rms, finalMask,
3659                              nClipped, thresClip, nIterClip,
3660                              getResidual);
3661}
3662
3663std::vector<std::vector<double> > Scantable::getPolynomialModel(int order, int nchan, double (Scantable::*pfunc)(int, double))
3664{
3665  // model  : contains model values for computing the least-square matrix.
3666  //          model.size() is nmodel and model[*].size() is nchan.
3667  //          Each model element are as follows:
3668  //
3669  //          (for normal polynomials)
3670  //          model[0]   = {1.0,   1.0,   1.0,   ..., 1.0},
3671  //          model[1]   = {0.0,   1.0,   2.0,   ..., (nchan-1)}
3672  //          model[n-1] = ...,
3673  //          model[n]   = {0.0^n, 1.0^n, 2.0^n, ..., (nchan-1)^n}
3674  //          where (0 <= n <= order)
3675  //
3676  //          (for Chebyshev polynomials)
3677  //          model[0]   = {T0(-1), T0(2/(nchan-1)-1), T0(4/(nchan-1)-1), ..., T0(1)},
3678  //          model[n-1] = ...,
3679  //          model[n]   = {Tn(-1), Tn(2/(nchan-1)-1), Tn(4/(nchan-1)-1), ..., Tn(1)}
3680  //          where (0 <= n <= order),
3681
3682  int nmodel = order + 1;
3683  std::vector<std::vector<double> > model(nmodel, std::vector<double>(nchan));
3684
3685  double stretch, shift;
3686  if (pfunc == &Scantable::getChebyshevPolynomial) {
3687    stretch = 2.0/(double)(nchan - 1);
3688    shift   = -1.0;
3689  } else {
3690    stretch = 1.0;
3691    shift   = 0.0;
3692  }
3693
3694  for (int i = 0; i < nmodel; ++i) {
3695    for (int j = 0; j < nchan; ++j) {
3696      model[i][j] = (this->*pfunc)(i, stretch*(double)j + shift);
3697    }
3698  }
3699
3700  return model;
3701}
3702
3703std::vector<std::vector<std::vector<double> > > Scantable::getPolynomialModelReservoir(int order,
3704                                                                                       double (Scantable::*pfunc)(int, double),
3705                                                                                       std::vector<int>& nChanNos)
3706{
3707  std::vector<std::vector<std::vector<double> > > res;
3708  res.clear();
3709  nChanNos.clear();
3710
3711  std::vector<uint> ifNos = getIFNos();
3712  for (uint i = 0; i < ifNos.size(); ++i) {
3713    int currNchan = nchan(ifNos[i]);
3714    bool hasDifferentNchan = (i == 0);
3715    for (uint j = 0; j < i; ++j) {
3716      if (currNchan != nchan(ifNos[j])) {
3717        hasDifferentNchan = true;
3718        break;
3719      }
3720    }
3721    if (hasDifferentNchan) {
3722      res.push_back(getPolynomialModel(order, currNchan, pfunc));
3723      nChanNos.push_back(currNchan);
3724    }
3725  }
3726
3727  return res;
3728}
3729
3730std::vector<float> Scantable::doLeastSquareFitting(const std::vector<float>& data,
3731                                                   const std::vector<bool>& mask,
3732                                                   const std::vector<std::vector<double> >& model,
3733                                                   std::vector<float>& params,
3734                                                   float& rms,
3735                                                   std::vector<bool>& finalMask,
3736                                                   int& nClipped,
3737                                                   float thresClip,
3738                                                   int nIterClip,
3739                                                   bool getResidual)
3740{
3741  int nDOF = model.size();
3742  int nChan = data.size();
3743
3744  if (nDOF == 0) {
3745    throw(AipsError("no model data given"));
3746  }
3747  if (nChan < 2) {
3748    throw(AipsError("data size is too few"));
3749  }
3750  if (nChan != (int)mask.size()) {
3751    throw(AipsError("data and mask sizes are not identical"));
3752  }
3753  for (int i = 0; i < nDOF; ++i) {
3754    if (nChan != (int)model[i].size()) {
3755      throw(AipsError("data and model sizes are not identical"));
3756    }
3757  }
3758
3759  params.clear();
3760  params.resize(nDOF);
3761
3762  finalMask.clear();
3763  finalMask.resize(nChan);
3764
3765  std::vector<int> maskArray(nChan);
3766  int j = 0;
3767  for (int i = 0; i < nChan; ++i) {
3768    maskArray[i] = mask[i] ? 1 : 0;
3769    if (isnan(data[i])) maskArray[i] = 0;
3770    if (isinf(data[i])) maskArray[i] = 0;
3771
3772    finalMask[i] = (maskArray[i] == 1);
3773    if (finalMask[i]) {
3774      j++;
3775    }
3776
3777    /*
3778    maskArray[i] = mask[i] ? 1 : 0;
3779    if (mask[i]) {
3780      j++;
3781    }
3782    finalMask[i] = mask[i];
3783    */
3784  }
3785
3786  int initNData = j;
3787  int nData = initNData;
3788
3789  std::vector<double> z1(nChan), r1(nChan), residual(nChan);
3790  for (int i = 0; i < nChan; ++i) {
3791    z1[i] = (double)data[i];
3792    r1[i] = 0.0;
3793    residual[i] = 0.0;
3794  }
3795
3796  for (int nClip = 0; nClip < nIterClip+1; ++nClip) {
3797    // xMatrix : horizontal concatenation of
3798    //           the least-sq. matrix (left) and an
3799    //           identity matrix (right).
3800    // the right part is used to calculate the inverse matrix of the left part.
3801    double xMatrix[nDOF][2*nDOF];
3802    double zMatrix[nDOF];
3803    for (int i = 0; i < nDOF; ++i) {
3804      for (int j = 0; j < 2*nDOF; ++j) {
3805        xMatrix[i][j] = 0.0;
3806      }
3807      xMatrix[i][nDOF+i] = 1.0;
3808      zMatrix[i] = 0.0;
3809    }
3810
3811    int nUseData = 0;
3812    for (int k = 0; k < nChan; ++k) {
3813      if (maskArray[k] == 0) continue;
3814
3815      for (int i = 0; i < nDOF; ++i) {
3816        for (int j = i; j < nDOF; ++j) {
3817          xMatrix[i][j] += model[i][k] * model[j][k];
3818        }
3819        zMatrix[i] += z1[k] * model[i][k];
3820      }
3821
3822      nUseData++;
3823    }
3824
3825    if (nUseData < 1) {
3826        throw(AipsError("all channels clipped or masked. can't execute fitting anymore."));     
3827    }
3828
3829    for (int i = 0; i < nDOF; ++i) {
3830      for (int j = 0; j < i; ++j) {
3831        xMatrix[i][j] = xMatrix[j][i];
3832      }
3833    }
3834
3835    //compute inverse matrix of the left half of xMatrix
3836    std::vector<double> invDiag(nDOF);
3837    for (int i = 0; i < nDOF; ++i) {
3838      invDiag[i] = 1.0 / xMatrix[i][i];
3839      for (int j = 0; j < nDOF; ++j) {
3840        xMatrix[i][j] *= invDiag[i];
3841      }
3842    }
3843
3844    for (int k = 0; k < nDOF; ++k) {
3845      for (int i = 0; i < nDOF; ++i) {
3846        if (i != k) {
3847          double factor1 = xMatrix[k][k];
3848          double invfactor1 = 1.0 / factor1;
3849          double factor2 = xMatrix[i][k];
3850          for (int j = k; j < 2*nDOF; ++j) {
3851            xMatrix[i][j] *= factor1;
3852            xMatrix[i][j] -= xMatrix[k][j]*factor2;
3853            xMatrix[i][j] *= invfactor1;
3854          }
3855        }
3856      }
3857      double invXDiag = 1.0 / xMatrix[k][k];
3858      for (int j = k; j < 2*nDOF; ++j) {
3859        xMatrix[k][j] *= invXDiag;
3860      }
3861    }
3862   
3863    for (int i = 0; i < nDOF; ++i) {
3864      for (int j = 0; j < nDOF; ++j) {
3865        xMatrix[i][nDOF+j] *= invDiag[j];
3866      }
3867    }
3868    //compute a vector y in which coefficients of the best-fit
3869    //model functions are stored.
3870    //in case of polynomials, y consists of (a0,a1,a2,...)
3871    //where ai is the coefficient of the term x^i.
3872    //in case of sinusoids, y consists of (a0,s1,c1,s2,c2,...)
3873    //where a0 is constant term and s* and c* are of sine
3874    //and cosine functions, respectively.
3875    std::vector<double> y(nDOF);
3876    for (int i = 0; i < nDOF; ++i) {
3877      y[i] = 0.0;
3878      for (int j = 0; j < nDOF; ++j) {
3879        y[i] += xMatrix[i][nDOF+j]*zMatrix[j];
3880      }
3881      params[i] = (float)y[i];
3882    }
3883
3884    for (int i = 0; i < nChan; ++i) {
3885      r1[i] = y[0];
3886      for (int j = 1; j < nDOF; ++j) {
3887        r1[i] += y[j]*model[j][i];
3888      }
3889      residual[i] = z1[i] - r1[i];
3890    }
3891
3892    double mean  = 0.0;
3893    double mean2 = 0.0;
3894    for (int i = 0; i < nChan; ++i) {
3895      if (maskArray[i] == 0) continue;
3896      mean  += residual[i];
3897      mean2 += residual[i]*residual[i];
3898    }
3899    mean  /= (double)nData;
3900    mean2 /= (double)nData;
3901    double rmsd = sqrt(mean2 - mean*mean);
3902    rms = (float)rmsd;
3903
3904    if ((nClip == nIterClip) || (thresClip <= 0.0)) {
3905      break;
3906    } else {
3907
3908      double thres = rmsd * thresClip;
3909      int newNData = 0;
3910      for (int i = 0; i < nChan; ++i) {
3911        if (abs(residual[i]) >= thres) {
3912          maskArray[i] = 0;
3913          finalMask[i] = false;
3914        }
3915        if (maskArray[i] > 0) {
3916          newNData++;
3917        }
3918      }
3919      if (newNData == nData) {
3920        break; //no more flag to add. stop iteration.
3921      } else {
3922        nData = newNData;
3923      }
3924
3925    }
3926  }
3927
3928  nClipped = initNData - nData;
3929
3930  std::vector<float> result(nChan);
3931  if (getResidual) {
3932    for (int i = 0; i < nChan; ++i) {
3933      result[i] = (float)residual[i];
3934    }
3935  } else {
3936    for (int i = 0; i < nChan; ++i) {
3937      result[i] = (float)r1[i];
3938    }
3939  }
3940
3941  return result;
3942} //xMatrix
3943
3944void Scantable::cubicSplineBaseline(const std::vector<bool>& mask, int nPiece,
3945                                    float thresClip, int nIterClip,
3946                                    bool getResidual,
3947                                    const std::string& progressInfo,
3948                                    const bool outLogger, const std::string& blfile,
3949                                    const std::string& bltable)
3950{
3951  /****
3952  double TimeStart = mathutil::gettimeofday_sec();
3953  ****/
3954
3955  try {
3956    ofstream ofs;
3957    String coordInfo;
3958    bool hasSameNchan, outTextFile, csvFormat, showProgress;
3959    int minNRow;
3960    int nRow = nrow();
3961    std::vector<bool> chanMask, finalChanMask;
3962    float rms;
3963    bool outBaselineTable = (bltable != "");
3964    STBaselineTable bt = STBaselineTable(*this);
3965    Vector<Double> timeSecCol;
3966    size_t flagged=0;
3967
3968    initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
3969                         coordInfo, hasSameNchan,
3970                         progressInfo, showProgress, minNRow,
3971                         timeSecCol);
3972
3973    std::vector<int> nChanNos;
3974    std::vector<std::vector<std::vector<double> > > modelReservoir;
3975    modelReservoir = getPolynomialModelReservoir(3,
3976                                                 &Scantable::getNormalPolynomial,
3977                                                 nChanNos);
3978    int nDOF = nPiece + 3;
3979
3980    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
3981      std::vector<float> sp = getSpectrum(whichrow);
3982      chanMask = getCompositeChanMask(whichrow, mask);
3983      std::vector<int> pieceEdges;
3984      std::vector<float> params;
3985
3986      //if (flagrowCol_(whichrow) == 0) {
3987      if (flagrowCol_(whichrow)==0 && nValidMask(chanMask)>0) {
3988        int nClipped = 0;
3989        std::vector<float> res;
3990        res = doCubicSplineLeastSquareFitting(sp, chanMask,
3991                modelReservoir[getIdxOfNchan(sp.size(), nChanNos)],
3992                nPiece, false, pieceEdges, params, rms, finalChanMask,
3993                nClipped, thresClip, nIterClip, getResidual);
3994
3995        if (outBaselineTable) {
3996          bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3997                        getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3998                        true, STBaselineFunc::CSpline, pieceEdges, std::vector<float>(),
3999                        getMaskListFromMask(finalChanMask), params, rms, sp.size(),
4000                        thresClip, nIterClip, 0.0, 0, std::vector<int>());
4001        } else {
4002          setSpectrum(res, whichrow);
4003        }
4004
4005        outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
4006                            coordInfo, hasSameNchan, ofs, "cubicSplineBaseline()",
4007                            pieceEdges, params, nClipped);
4008      } else {
4009        // no valid channels to fit (flag the row)
4010        flagrowCol_.put(whichrow, 1);
4011        ++flagged;
4012        if (outBaselineTable) {
4013          pieceEdges.resize(nPiece+1);
4014          for (uInt i = 0; i < pieceEdges.size(); ++i) {
4015            pieceEdges[i] = 0;
4016          }
4017          params.resize(nDOF);
4018          for (uInt i = 0; i < params.size(); ++i) {
4019            params[i] = 0.0;
4020          }
4021          bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
4022                        getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
4023                        true, STBaselineFunc::CSpline, pieceEdges, std::vector<float>(),
4024                        getMaskListFromMask(chanMask), params, 0.0, sp.size(),
4025                        thresClip, nIterClip, 0.0, 0, std::vector<int>());
4026        }
4027      }
4028
4029      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
4030    }
4031   
4032    finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
4033
4034    if (flagged > 0) {
4035      LogIO os( LogOrigin( "Scantable", "cubicSplineBaseline()") ) ;
4036      os << LogIO::WARN << "Baseline subtraction is skipped for " << flagged << " spectra due to too few valid channels to operate fit. The spectra will be flagged in output data." << LogIO::POST;
4037    }
4038  } catch (...) {
4039    throw;
4040  }
4041
4042  /****
4043  double TimeEnd = mathutil::gettimeofday_sec();
4044  double elapse1 = TimeEnd - TimeStart;
4045  std::cout << "cspline-new   : " << elapse1 << " (sec.)" << endl;
4046  ****/
4047}
4048
4049void Scantable::autoCubicSplineBaseline(const std::vector<bool>& mask, int nPiece,
4050                                        float thresClip, int nIterClip,
4051                                        const std::vector<int>& edge,
4052                                        float threshold, int chanAvgLimit,
4053                                        bool getResidual,
4054                                        const std::string& progressInfo,
4055                                        const bool outLogger, const std::string& blfile,
4056                                        const std::string& bltable)
4057{
4058  try {
4059    ofstream ofs;
4060    String coordInfo;
4061    bool hasSameNchan, outTextFile, csvFormat, showProgress;
4062    int minNRow;
4063    int nRow = nrow();
4064    std::vector<bool> chanMask, finalChanMask;
4065    float rms;
4066    bool outBaselineTable = (bltable != "");
4067    STBaselineTable bt = STBaselineTable(*this);
4068    Vector<Double> timeSecCol;
4069    STLineFinder lineFinder = STLineFinder();
4070    size_t flagged=0;
4071
4072    initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
4073                         coordInfo, hasSameNchan,
4074                         progressInfo, showProgress, minNRow,
4075                         timeSecCol);
4076
4077    initLineFinder(edge, threshold, chanAvgLimit, lineFinder);
4078
4079    std::vector<int> nChanNos;
4080    std::vector<std::vector<std::vector<double> > > modelReservoir;
4081    modelReservoir = getPolynomialModelReservoir(3,
4082                                                 &Scantable::getNormalPolynomial,
4083                                                 nChanNos);
4084    int nDOF = nPiece + 3;
4085
4086    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
4087      std::vector<float> sp = getSpectrum(whichrow);
4088      std::vector<int> currentEdge;
4089      chanMask = getCompositeChanMask(whichrow, mask, edge, currentEdge, lineFinder);
4090      std::vector<int> pieceEdges;
4091      std::vector<float> params;
4092
4093      //if (flagrowCol_(whichrow) == 0) {
4094      if (flagrowCol_(whichrow)==0 && nValidMask(chanMask)>0) {
4095        int nClipped = 0;
4096        std::vector<float> res;
4097        res = doCubicSplineLeastSquareFitting(sp, chanMask,
4098                modelReservoir[getIdxOfNchan(sp.size(), nChanNos)],
4099                nPiece, false, pieceEdges, params, rms, finalChanMask,
4100                nClipped, thresClip, nIterClip, getResidual);
4101
4102        if (outBaselineTable) {
4103          bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
4104                        getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
4105                        true, STBaselineFunc::CSpline, pieceEdges, std::vector<float>(),
4106                        getMaskListFromMask(finalChanMask), params, rms, sp.size(),
4107                        thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
4108        } else {
4109          setSpectrum(res, whichrow);
4110        }
4111
4112        outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
4113                            coordInfo, hasSameNchan, ofs, "autoCubicSplineBaseline()",
4114                            pieceEdges, params, nClipped);
4115      } else {
4116        // no valid channels to fit (flag the row)
4117        flagrowCol_.put(whichrow, 1);
4118        ++flagged;
4119        if (outBaselineTable) {
4120          pieceEdges.resize(nPiece+1);
4121          for (uInt i = 0; i < pieceEdges.size(); ++i) {
4122            pieceEdges[i] = 0;
4123          }
4124          params.resize(nDOF);
4125          for (uInt i = 0; i < params.size(); ++i) {
4126            params[i] = 0.0;
4127          }
4128          bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
4129                        getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
4130                        true, STBaselineFunc::CSpline, pieceEdges, std::vector<float>(),
4131                        getMaskListFromMask(chanMask), params, 0.0, sp.size(),
4132                        thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
4133        }
4134      }
4135
4136      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
4137    }
4138
4139    finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
4140
4141    if (flagged > 0) {
4142      LogIO os( LogOrigin( "Scantable", "autoCubicSplineBaseline()") ) ;
4143      os << LogIO::WARN << "Baseline subtraction is skipped for " << flagged << " spectra due to too few valid channels to operate fit. The spectra will be flagged in output data." << LogIO::POST;
4144    }
4145  } catch (...) {
4146    throw;
4147  }
4148}
4149
4150std::vector<float> Scantable::doCubicSplineFitting(const std::vector<float>& data,
4151                                                   const std::vector<bool>& mask,
4152                                                   std::vector<int>& idxEdge,
4153                                                   std::vector<float>& params,
4154                                                   float& rms,
4155                                                   std::vector<bool>& finalmask,
4156                                                   float clipth,
4157                                                   int clipn)
4158{
4159  int nClipped = 0;
4160  return doCubicSplineFitting(data, mask, idxEdge.size()-1, true, idxEdge, params, rms, finalmask, nClipped, clipth, clipn);
4161}
4162
4163std::vector<float> Scantable::doCubicSplineFitting(const std::vector<float>& data,
4164                                                   const std::vector<bool>& mask,
4165                                                   int nPiece,
4166                                                   std::vector<int>& idxEdge,
4167                                                   std::vector<float>& params,
4168                                                   float& rms,
4169                                                   std::vector<bool>& finalmask,
4170                                                   float clipth,
4171                                                   int clipn)
4172{
4173  int nClipped = 0;
4174  return doCubicSplineFitting(data, mask, nPiece, false, idxEdge, params, rms, finalmask, nClipped, clipth, clipn);
4175}
4176
4177std::vector<float> Scantable::doCubicSplineFitting(const std::vector<float>& data,
4178                                                   const std::vector<bool>& mask,
4179                                                   int nPiece,
4180                                                   bool useGivenPieceBoundary,
4181                                                   std::vector<int>& idxEdge,
4182                                                   std::vector<float>& params,
4183                                                   float& rms,
4184                                                   std::vector<bool>& finalMask,
4185                                                   int& nClipped,
4186                                                   float thresClip,
4187                                                   int nIterClip,
4188                                                   bool getResidual)
4189{
4190  return doCubicSplineLeastSquareFitting(data, mask,
4191                                         getPolynomialModel(3, data.size(), &Scantable::getNormalPolynomial),
4192                                         nPiece, useGivenPieceBoundary, idxEdge,
4193                                         params, rms, finalMask,
4194                                         nClipped, thresClip, nIterClip,
4195                                         getResidual);
4196}
4197
4198std::vector<float> Scantable::doCubicSplineLeastSquareFitting(const std::vector<float>& data,
4199                                                              const std::vector<bool>& mask,
4200                                                              const std::vector<std::vector<double> >& model,
4201                                                              int nPiece,
4202                                                              bool useGivenPieceBoundary,
4203                                                              std::vector<int>& idxEdge,
4204                                                              std::vector<float>& params,
4205                                                              float& rms,
4206                                                              std::vector<bool>& finalMask,
4207                                                              int& nClipped,
4208                                                              float thresClip,
4209                                                              int nIterClip,
4210                                                              bool getResidual)
4211{
4212  int nDOF = nPiece + 3;  //number of independent parameters to solve, namely, 4+(nPiece-1).
4213  int nModel = model.size();
4214  int nChan = data.size();
4215
4216  if (nModel != 4) {
4217    throw(AipsError("model size must be 4."));
4218  }
4219  if (nPiece < 1) {
4220    throw(AipsError("number of the sections must be one or more"));
4221  }
4222  if (nChan < 2*nPiece) {
4223    throw(AipsError("data size is too few"));
4224  }
4225  if (nChan != (int)mask.size()) {
4226    throw(AipsError("data and mask sizes are not identical"));
4227  }
4228  for (int i = 0; i < nModel; ++i) {
4229    if (nChan != (int)model[i].size()) {
4230      throw(AipsError("data and model sizes are not identical"));
4231    }
4232  }
4233
4234  params.clear();
4235  params.resize(nPiece*nModel);
4236
4237  finalMask.clear();
4238  finalMask.resize(nChan);
4239
4240  std::vector<int> maskArray(nChan);
4241  std::vector<int> x(nChan);
4242  int j = 0;
4243  for (int i = 0; i < nChan; ++i) {
4244    maskArray[i] = mask[i] ? 1 : 0;
4245    if (isnan(data[i])) maskArray[i] = 0;
4246    if (isinf(data[i])) maskArray[i] = 0;
4247
4248    finalMask[i] = (maskArray[i] == 1);
4249    if (finalMask[i]) {
4250      x[j] = i;
4251      j++;
4252    }
4253
4254    /*
4255    maskArray[i] = mask[i] ? 1 : 0;
4256    if (mask[i]) {
4257      x[j] = i;
4258      j++;
4259    }
4260    finalMask[i] = mask[i];
4261    */
4262  }
4263
4264  int initNData = j;
4265  int nData = initNData;
4266
4267  if (initNData < nPiece) {
4268    throw(AipsError("too few non-flagged channels"));
4269  }
4270
4271  int nElement = (int)(floor(floor((double)(initNData/nPiece))+0.5));
4272  std::vector<double> invEdge(nPiece-1);
4273
4274  if (useGivenPieceBoundary) {
4275    if ((int)idxEdge.size() != nPiece+1) {
4276      throw(AipsError("pieceEdge.size() must be equal to nPiece+1."));
4277    }
4278  } else {
4279    idxEdge.clear();
4280    idxEdge.resize(nPiece+1);
4281    idxEdge[0] = x[0];
4282  }
4283  for (int i = 1; i < nPiece; ++i) {
4284    int valX = x[nElement*i];
4285    if (!useGivenPieceBoundary) {
4286      idxEdge[i] = valX;
4287    }
4288    invEdge[i-1] = 1.0/(double)valX;
4289  }
4290  if (!useGivenPieceBoundary) {
4291    idxEdge[nPiece] = x[initNData-1]+1;
4292  }
4293
4294  std::vector<double> z1(nChan), r1(nChan), residual(nChan);
4295  for (int i = 0; i < nChan; ++i) {
4296    z1[i] = (double)data[i];
4297    r1[i] = 0.0;
4298    residual[i] = 0.0;
4299  }
4300
4301  for (int nClip = 0; nClip < nIterClip+1; ++nClip) {
4302    // xMatrix : horizontal concatenation of
4303    //           the least-sq. matrix (left) and an
4304    //           identity matrix (right).
4305    // the right part is used to calculate the inverse matrix of the left part.
4306
4307    double xMatrix[nDOF][2*nDOF];
4308    double zMatrix[nDOF];
4309    for (int i = 0; i < nDOF; ++i) {
4310      for (int j = 0; j < 2*nDOF; ++j) {
4311        xMatrix[i][j] = 0.0;
4312      }
4313      xMatrix[i][nDOF+i] = 1.0;
4314      zMatrix[i] = 0.0;
4315    }
4316
4317    for (int n = 0; n < nPiece; ++n) {
4318      int nUseDataInPiece = 0;
4319      for (int k = idxEdge[n]; k < idxEdge[n+1]; ++k) {
4320
4321        if (maskArray[k] == 0) continue;
4322
4323        for (int i = 0; i < nModel; ++i) {
4324          for (int j = i; j < nModel; ++j) {
4325            xMatrix[i][j] += model[i][k] * model[j][k];
4326          }
4327          zMatrix[i] += z1[k] * model[i][k];
4328        }
4329
4330        for (int i = 0; i < n; ++i) {
4331          double q = 1.0 - model[1][k]*invEdge[i];
4332          q = q*q*q;
4333          for (int j = 0; j < nModel; ++j) {
4334            xMatrix[j][i+nModel] += q * model[j][k];
4335          }
4336          for (int j = 0; j < i; ++j) {
4337            double r = 1.0 - model[1][k]*invEdge[j];
4338            r = r*r*r;
4339            xMatrix[j+nModel][i+nModel] += r*q;
4340          }
4341          xMatrix[i+nModel][i+nModel] += q*q;
4342          zMatrix[i+nModel] += q*z1[k];
4343        }
4344
4345        nUseDataInPiece++;
4346      }
4347
4348      if (nUseDataInPiece < 1) {
4349        std::vector<string> suffixOfPieceNumber(4);
4350        suffixOfPieceNumber[0] = "th";
4351        suffixOfPieceNumber[1] = "st";
4352        suffixOfPieceNumber[2] = "nd";
4353        suffixOfPieceNumber[3] = "rd";
4354        int idxNoDataPiece = (n % 10 <= 3) ? n : 0;
4355        ostringstream oss;
4356        oss << "all channels clipped or masked in " << n << suffixOfPieceNumber[idxNoDataPiece];
4357        oss << " piece of the spectrum. can't execute fitting anymore.";
4358        throw(AipsError(String(oss)));
4359      }
4360    }
4361
4362    for (int i = 0; i < nDOF; ++i) {
4363      for (int j = 0; j < i; ++j) {
4364        xMatrix[i][j] = xMatrix[j][i];
4365      }
4366    }
4367
4368    std::vector<double> invDiag(nDOF);
4369    for (int i = 0; i < nDOF; ++i) {
4370      invDiag[i] = 1.0 / xMatrix[i][i];
4371      for (int j = 0; j < nDOF; ++j) {
4372        xMatrix[i][j] *= invDiag[i];
4373      }
4374    }
4375
4376    for (int k = 0; k < nDOF; ++k) {
4377      for (int i = 0; i < nDOF; ++i) {
4378        if (i != k) {
4379          double factor1 = xMatrix[k][k];
4380          double invfactor1 = 1.0 / factor1;
4381          double factor2 = xMatrix[i][k];
4382          for (int j = k; j < 2*nDOF; ++j) {
4383            xMatrix[i][j] *= factor1;
4384            xMatrix[i][j] -= xMatrix[k][j]*factor2;
4385            xMatrix[i][j] *= invfactor1;
4386          }
4387        }
4388      }
4389      double invXDiag = 1.0 / xMatrix[k][k];
4390      for (int j = k; j < 2*nDOF; ++j) {
4391        xMatrix[k][j] *= invXDiag;
4392      }
4393    }
4394   
4395    for (int i = 0; i < nDOF; ++i) {
4396      for (int j = 0; j < nDOF; ++j) {
4397        xMatrix[i][nDOF+j] *= invDiag[j];
4398      }
4399    }
4400
4401    //compute a vector y which consists of the coefficients of the best-fit spline curves
4402    //(a0,a1,a2,a3(,b3,c3,...)), namely, the ones for the leftmost piece and the ones of
4403    //cubic terms for the other pieces (in case nPiece>1).
4404    std::vector<double> y(nDOF);
4405    for (int i = 0; i < nDOF; ++i) {
4406      y[i] = 0.0;
4407      for (int j = 0; j < nDOF; ++j) {
4408        y[i] += xMatrix[i][nDOF+j]*zMatrix[j];
4409      }
4410    }
4411
4412    std::vector<double> a(nModel);
4413    for (int i = 0; i < nModel; ++i) {
4414      a[i] = y[i];
4415    }
4416
4417    int j = 0;
4418    for (int n = 0; n < nPiece; ++n) {
4419      for (int i = idxEdge[n]; i < idxEdge[n+1]; ++i) {
4420        r1[i] = 0.0;
4421        for (int j = 0; j < nModel; ++j) {
4422          r1[i] += a[j] * model[j][i];
4423        }
4424      }
4425      for (int i = 0; i < nModel; ++i) {
4426        params[j+i] = a[i];
4427      }
4428      j += nModel;
4429
4430      if (n == nPiece-1) break;
4431
4432      double d = y[n+nModel];
4433      double iE = invEdge[n];
4434      a[0] +=       d;
4435      a[1] -= 3.0 * d * iE;
4436      a[2] += 3.0 * d * iE * iE;
4437      a[3] -=       d * iE * iE * iE;
4438    }
4439
4440    //subtract constant value for masked regions at the edge of spectrum
4441    if (idxEdge[0] > 0) {
4442      int n = idxEdge[0];
4443      for (int i = 0; i < idxEdge[0]; ++i) {
4444        //--cubic extrapolate--
4445        //r1[i] = params[0] + params[1]*x1[i] + params[2]*x2[i] + params[3]*x3[i];
4446        //--linear extrapolate--
4447        //r1[i] = (r1[n+1] - r1[n])/(x1[n+1] - x1[n])*(x1[i] - x1[n]) + r1[n];
4448        //--constant--
4449        r1[i] = r1[n];
4450      }
4451    }
4452
4453    if (idxEdge[nPiece] < nChan) {
4454      int n = idxEdge[nPiece]-1;
4455      for (int i = idxEdge[nPiece]; i < nChan; ++i) {
4456        //--cubic extrapolate--
4457        //int m = 4*(nPiece-1);
4458        //r1[i] = params[m] + params[m+1]*x1[i] + params[m+2]*x2[i] + params[m+3]*x3[i];
4459        //--linear extrapolate--
4460        //r1[i] = (r1[n-1] - r1[n])/(x1[n-1] - x1[n])*(x1[i] - x1[n]) + r1[n];
4461        //--constant--
4462        r1[i] = r1[n];
4463      }
4464    }
4465
4466    for (int i = 0; i < nChan; ++i) {
4467      residual[i] = z1[i] - r1[i];
4468    }
4469
4470    double mean  = 0.0;
4471    double mean2 = 0.0;
4472    for (int i = 0; i < nChan; ++i) {
4473      if (maskArray[i] == 0) continue;
4474      mean  += residual[i];
4475      mean2 += residual[i]*residual[i];
4476    }
4477    mean  /= (double)nData;
4478    mean2 /= (double)nData;
4479    double rmsd = sqrt(mean2 - mean*mean);
4480    rms = (float)rmsd;
4481
4482    if ((nClip == nIterClip) || (thresClip <= 0.0)) {
4483      break;
4484    } else {
4485     
4486      double thres = rmsd * thresClip;
4487      int newNData = 0;
4488      for (int i = 0; i < nChan; ++i) {
4489        if (abs(residual[i]) >= thres) {
4490          maskArray[i] = 0;
4491          finalMask[i] = false;
4492        }
4493        if (maskArray[i] > 0) {
4494          newNData++;
4495        }
4496      }
4497      if (newNData == nData) {
4498        break; //no more flag to add. iteration stops.
4499      } else {
4500        nData = newNData;
4501      }
4502
4503    }
4504  }
4505
4506  nClipped = initNData - nData;
4507
4508  std::vector<float> result(nChan);
4509  if (getResidual) {
4510    for (int i = 0; i < nChan; ++i) {
4511      result[i] = (float)residual[i];
4512    }
4513  } else {
4514    for (int i = 0; i < nChan; ++i) {
4515      result[i] = (float)r1[i];
4516    }
4517  }
4518
4519  return result;
4520}
4521
4522std::vector<int> Scantable::selectWaveNumbers(const std::vector<int>& addNWaves,
4523                                  const std::vector<int>& rejectNWaves)
4524{
4525  std::vector<bool> chanMask;
4526  std::string fftMethod;
4527  std::string fftThresh;
4528
4529  return selectWaveNumbers(0, chanMask, false, fftMethod, fftThresh, addNWaves, rejectNWaves);
4530}
4531
4532std::vector<int> Scantable::selectWaveNumbers(const int whichrow,
4533                                  const std::vector<bool>& chanMask,
4534                                  const bool applyFFT,
4535                                  const std::string& fftMethod,
4536                                  const std::string& fftThresh,
4537                                  const std::vector<int>& addNWaves,
4538                                  const std::vector<int>& rejectNWaves)
4539{
4540  std::vector<int> nWaves;
4541  nWaves.clear();
4542
4543  if (applyFFT) {
4544    string fftThAttr;
4545    float fftThSigma;
4546    int fftThTop;
4547    parseFFTThresholdInfo(fftThresh, fftThAttr, fftThSigma, fftThTop);
4548    doSelectWaveNumbers(whichrow, chanMask, fftMethod, fftThSigma, fftThTop, fftThAttr, nWaves);
4549  }
4550
4551  addAuxWaveNumbers(whichrow, addNWaves, rejectNWaves, nWaves);
4552
4553  return nWaves;
4554}
4555
4556int Scantable::getIdxOfNchan(const int nChan, const std::vector<int>& nChanNos)
4557{
4558  int idx = -1;
4559  for (uint i = 0; i < nChanNos.size(); ++i) {
4560    if (nChan == nChanNos[i]) {
4561      idx = i;
4562      break;
4563    }
4564  }
4565
4566  if (idx < 0) {
4567    throw(AipsError("nChan not found in nChhanNos."));
4568  }
4569
4570  return idx;
4571}
4572
4573void Scantable::parseFFTInfo(const std::string& fftInfo, bool& applyFFT, std::string& fftMethod, std::string& fftThresh)
4574{
4575  istringstream iss(fftInfo);
4576  std::string tmp;
4577  std::vector<string> res;
4578  while (getline(iss, tmp, ',')) {
4579    res.push_back(tmp);
4580  }
4581  if (res.size() < 3) {
4582    throw(AipsError("wrong value in 'fftinfo' parameter")) ;
4583  }
4584  applyFFT = (res[0] == "true");
4585  fftMethod = res[1];
4586  fftThresh = res[2];
4587}
4588
4589void Scantable::parseFFTThresholdInfo(const std::string& fftThresh, std::string& fftThAttr, float& fftThSigma, int& fftThTop)
4590{
4591  uInt idxSigma = fftThresh.find("sigma");
4592  uInt idxTop   = fftThresh.find("top");
4593
4594  if (idxSigma == fftThresh.size() - 5) {
4595    std::istringstream is(fftThresh.substr(0, fftThresh.size() - 5));
4596    is >> fftThSigma;
4597    fftThAttr = "sigma";
4598  } else if (idxTop == 0) {
4599    std::istringstream is(fftThresh.substr(3));
4600    is >> fftThTop;
4601    fftThAttr = "top";
4602  } else {
4603    bool isNumber = true;
4604    for (uInt i = 0; i < fftThresh.size()-1; ++i) {
4605      char ch = (fftThresh.substr(i, 1).c_str())[0];
4606      if (!(isdigit(ch) || (fftThresh.substr(i, 1) == "."))) {
4607        isNumber = false;
4608        break;
4609      }
4610    }
4611    if (isNumber) {
4612      std::istringstream is(fftThresh);
4613      is >> fftThSigma;
4614      fftThAttr = "sigma";
4615    } else {
4616      throw(AipsError("fftthresh has a wrong value"));
4617    }
4618  }
4619}
4620
4621void 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)
4622{
4623  std::vector<float> fspec;
4624  if (fftMethod == "fft") {
4625    fspec = execFFT(whichrow, chanMask, false, true);
4626  //} else if (fftMethod == "lsp") {
4627  //  fspec = lombScarglePeriodogram(whichrow);
4628  }
4629
4630  if (fftThAttr == "sigma") {
4631    float mean  = 0.0;
4632    float mean2 = 0.0;
4633    for (uInt i = 0; i < fspec.size(); ++i) {
4634      mean  += fspec[i];
4635      mean2 += fspec[i]*fspec[i];
4636    }
4637    mean  /= float(fspec.size());
4638    mean2 /= float(fspec.size());
4639    float thres = mean + fftThSigma * float(sqrt(mean2 - mean*mean));
4640
4641    for (uInt i = 0; i < fspec.size(); ++i) {
4642      if (fspec[i] >= thres) {
4643        nWaves.push_back(i);
4644      }
4645    }
4646
4647  } else if (fftThAttr == "top") {
4648    for (int i = 0; i < fftThTop; ++i) {
4649      float max = 0.0;
4650      int maxIdx = 0;
4651      for (uInt j = 0; j < fspec.size(); ++j) {
4652        if (fspec[j] > max) {
4653          max = fspec[j];
4654          maxIdx = j;
4655        }
4656      }
4657      nWaves.push_back(maxIdx);
4658      fspec[maxIdx] = 0.0;
4659    }
4660
4661  }
4662
4663  if (nWaves.size() > 1) {
4664    sort(nWaves.begin(), nWaves.end());
4665  }
4666}
4667
4668void Scantable::addAuxWaveNumbers(const int whichrow, const std::vector<int>& addNWaves, const std::vector<int>& rejectNWaves, std::vector<int>& nWaves)
4669{
4670  std::vector<int> tempAddNWaves, tempRejectNWaves;
4671  tempAddNWaves.clear();
4672  tempRejectNWaves.clear();
4673
4674  for (uInt i = 0; i < addNWaves.size(); ++i) {
4675    tempAddNWaves.push_back(addNWaves[i]);
4676  }
4677  if ((tempAddNWaves.size() == 2) && (tempAddNWaves[1] == -999)) {
4678    setWaveNumberListUptoNyquistFreq(whichrow, tempAddNWaves);
4679  }
4680
4681  for (uInt i = 0; i < rejectNWaves.size(); ++i) {
4682    tempRejectNWaves.push_back(rejectNWaves[i]);
4683  }
4684  if ((tempRejectNWaves.size() == 2) && (tempRejectNWaves[1] == -999)) {
4685    setWaveNumberListUptoNyquistFreq(whichrow, tempRejectNWaves);
4686  }
4687
4688  for (uInt i = 0; i < tempAddNWaves.size(); ++i) {
4689    bool found = false;
4690    for (uInt j = 0; j < nWaves.size(); ++j) {
4691      if (nWaves[j] == tempAddNWaves[i]) {
4692        found = true;
4693        break;
4694      }
4695    }
4696    if (!found) nWaves.push_back(tempAddNWaves[i]);
4697  }
4698
4699  for (uInt i = 0; i < tempRejectNWaves.size(); ++i) {
4700    for (std::vector<int>::iterator j = nWaves.begin(); j != nWaves.end(); ) {
4701      if (*j == tempRejectNWaves[i]) {
4702        j = nWaves.erase(j);
4703      } else {
4704        ++j;
4705      }
4706    }
4707  }
4708
4709  if (nWaves.size() > 1) {
4710    sort(nWaves.begin(), nWaves.end());
4711    unique(nWaves.begin(), nWaves.end());
4712  }
4713}
4714
4715void Scantable::setWaveNumberListUptoNyquistFreq(const int whichrow, std::vector<int>& nWaves)
4716{
4717  int val = nWaves[0];
4718  int nyquistFreq = nchan(getIF(whichrow))/2+1;
4719  nWaves.clear();
4720  if (val > nyquistFreq) {  // for safety, at least nWaves contains a constant; CAS-3759
4721    nWaves.push_back(0);
4722  }
4723  while (val <= nyquistFreq) {
4724    nWaves.push_back(val);
4725    val++;
4726  }
4727}
4728
4729void Scantable::sinusoidBaseline(const std::vector<bool>& mask, const std::string& fftInfo,
4730                                 const std::vector<int>& addNWaves,
4731                                 const std::vector<int>& rejectNWaves,
4732                                 float thresClip, int nIterClip,
4733                                 bool getResidual,
4734                                 const std::string& progressInfo,
4735                                 const bool outLogger, const std::string& blfile,
4736                                 const std::string& bltable)
4737{
4738  /****
4739  double TimeStart = mathutil::gettimeofday_sec();
4740  ****/
4741
4742  try {
4743    ofstream ofs;
4744    String coordInfo;
4745    bool hasSameNchan, outTextFile, csvFormat, showProgress;
4746    int minNRow;
4747    int nRow = nrow();
4748    std::vector<bool> chanMask, finalChanMask;
4749    float rms;
4750    bool outBaselineTable = (bltable != "");
4751    STBaselineTable bt = STBaselineTable(*this);
4752    Vector<Double> timeSecCol;
4753    size_t flagged=0;
4754
4755    initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
4756                         coordInfo, hasSameNchan,
4757                         progressInfo, showProgress, minNRow,
4758                         timeSecCol);
4759
4760    bool applyFFT;
4761    std::string fftMethod, fftThresh;
4762    parseFFTInfo(fftInfo, applyFFT, fftMethod, fftThresh);
4763
4764    std::vector<int> nWaves;
4765    std::vector<int> nChanNos;
4766    std::vector<std::vector<std::vector<double> > > modelReservoir;
4767    if (!applyFFT) {
4768      nWaves = selectWaveNumbers(addNWaves, rejectNWaves);
4769      if (nWaves.size()==0) //no wave numbers to fit
4770        throw(AipsError("No valid wave numbers to fit"));
4771      modelReservoir = getSinusoidModelReservoir(nWaves, nChanNos);
4772    }
4773
4774    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
4775      std::vector<float> sp = getSpectrum(whichrow);
4776      chanMask = getCompositeChanMask(whichrow, mask);
4777      std::vector<std::vector<double> > model;
4778      bool canfit = true;
4779      if (applyFFT) {
4780        nWaves = selectWaveNumbers(whichrow, chanMask, true, fftMethod, fftThresh,
4781                                   addNWaves, rejectNWaves);
4782        if (nWaves.size()==0) {// no wave numbers to fit.
4783          canfit = false;
4784          break;
4785        }
4786        model = getSinusoidModel(nWaves, sp.size());
4787      } else {
4788        model = modelReservoir[getIdxOfNchan(sp.size(), nChanNos)];
4789      }
4790      int nModel = modelReservoir.size();
4791
4792      std::vector<float> params;
4793
4794      //if (flagrowCol_(whichrow) == 0) {
4795      if (canfit && flagrowCol_(whichrow)==0 && nValidMask(chanMask)>0) {
4796        int nClipped = 0;
4797        std::vector<float> res;
4798        res = doLeastSquareFitting(sp, chanMask, model,
4799                                   params, rms, finalChanMask,
4800                                   nClipped, thresClip, nIterClip, getResidual);
4801
4802        if (outBaselineTable) {
4803          bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
4804                        getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
4805                        true, STBaselineFunc::Sinusoid, nWaves, std::vector<float>(),
4806                        getMaskListFromMask(finalChanMask), params, rms, sp.size(),
4807                        thresClip, nIterClip, 0.0, 0, std::vector<int>());
4808        } else {
4809          setSpectrum(res, whichrow);
4810        }
4811
4812        outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
4813                            coordInfo, hasSameNchan, ofs, "sinusoidBaseline()",
4814                            params, nClipped);
4815      } else {
4816        // no valid channels to fit (flag the row)
4817        flagrowCol_.put(whichrow, 1);
4818        ++flagged;
4819        if (outBaselineTable) {
4820          params.resize(nModel);
4821          for (uInt i = 0; i < params.size(); ++i) {
4822            params[i] = 0.0;
4823          }
4824          bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
4825                        getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
4826                        true, STBaselineFunc::Sinusoid, nWaves, std::vector<float>(),
4827                        getMaskListFromMask(chanMask), params, 0.0, sp.size(),
4828                        thresClip, nIterClip, 0.0, 0, std::vector<int>());
4829        }
4830      }
4831
4832      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
4833    }
4834
4835    finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
4836
4837    if (flagged > 0) {
4838      LogIO os( LogOrigin( "Scantable", "sinusoidBaseline()") ) ;
4839      os << LogIO::WARN << "Baseline subtraction is skipped for " << flagged << " spectra due to too few valid channels to operate fit. The spectra will be flagged in output data." << LogIO::POST;
4840    }
4841  } catch (...) {
4842    throw;
4843  }
4844
4845  /****
4846  double TimeEnd = mathutil::gettimeofday_sec();
4847  double elapse1 = TimeEnd - TimeStart;
4848  std::cout << "sinusoid-old   : " << elapse1 << " (sec.)" << endl;
4849  ****/
4850}
4851
4852void Scantable::autoSinusoidBaseline(const std::vector<bool>& mask, const std::string& fftInfo,
4853                                     const std::vector<int>& addNWaves,
4854                                     const std::vector<int>& rejectNWaves,
4855                                     float thresClip, int nIterClip,
4856                                     const std::vector<int>& edge,
4857                                     float threshold, int chanAvgLimit,
4858                                     bool getResidual,
4859                                     const std::string& progressInfo,
4860                                     const bool outLogger, const std::string& blfile,
4861                                     const std::string& bltable)
4862{
4863  try {
4864    ofstream ofs;
4865    String coordInfo;
4866    bool hasSameNchan, outTextFile, csvFormat, showProgress;
4867    int minNRow;
4868    int nRow = nrow();
4869    std::vector<bool> chanMask, finalChanMask;
4870    float rms;
4871    bool outBaselineTable = (bltable != "");
4872    STBaselineTable bt = STBaselineTable(*this);
4873    Vector<Double> timeSecCol;
4874    STLineFinder lineFinder = STLineFinder();
4875    size_t flagged=0;
4876
4877    initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
4878                         coordInfo, hasSameNchan,
4879                         progressInfo, showProgress, minNRow,
4880                         timeSecCol);
4881
4882    initLineFinder(edge, threshold, chanAvgLimit, lineFinder);
4883
4884    bool applyFFT;
4885    string fftMethod, fftThresh;
4886    parseFFTInfo(fftInfo, applyFFT, fftMethod, fftThresh);
4887
4888    std::vector<int> nWaves;
4889    std::vector<int> nChanNos;
4890    std::vector<std::vector<std::vector<double> > > modelReservoir;
4891    if (!applyFFT) {
4892      nWaves = selectWaveNumbers(addNWaves, rejectNWaves);
4893      if (nWaves.size()==0) //no wave numbers to fit
4894        throw(AipsError("No valid wave numbers to fit"));
4895      modelReservoir = getSinusoidModelReservoir(nWaves, nChanNos);
4896    }
4897
4898    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
4899      std::vector<float> sp = getSpectrum(whichrow);
4900      std::vector<int> currentEdge;
4901      chanMask = getCompositeChanMask(whichrow, mask, edge, currentEdge, lineFinder);
4902      std::vector<std::vector<double> > model;
4903      bool canfit=true;
4904      if (applyFFT) {
4905        nWaves = selectWaveNumbers(whichrow, chanMask, true, fftMethod, fftThresh,
4906                                   addNWaves, rejectNWaves);
4907        if (nWaves.size()==0) { // no wave numbers to fit.
4908          canfit = false;
4909          break;
4910        }
4911        model = getSinusoidModel(nWaves, sp.size());
4912      } else {
4913        model = modelReservoir[getIdxOfNchan(sp.size(), nChanNos)];
4914      }
4915      int nModel = modelReservoir.size();
4916
4917      std::vector<float> params;
4918
4919      //if (flagrowCol_(whichrow) == 0) {
4920      if (canfit && flagrowCol_(whichrow)==0 && nValidMask(chanMask)>0) {
4921        int nClipped = 0;
4922        std::vector<float> res;
4923        res = doLeastSquareFitting(sp, chanMask, model,
4924                                   params, rms, finalChanMask,
4925                                   nClipped, thresClip, nIterClip, getResidual);
4926
4927        if (outBaselineTable) {
4928          bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
4929                        getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
4930                        true, STBaselineFunc::Sinusoid, nWaves, std::vector<float>(),
4931                        getMaskListFromMask(finalChanMask), params, rms, sp.size(),
4932                        thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
4933        } else {
4934          setSpectrum(res, whichrow);
4935        }
4936
4937        outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
4938                            coordInfo, hasSameNchan, ofs, "autoSinusoidBaseline()",
4939                            params, nClipped);
4940      } else {
4941        // no valid channels to fit (flag the row)
4942        flagrowCol_.put(whichrow, 1);
4943        ++flagged;
4944        if (outBaselineTable) {
4945          params.resize(nModel);
4946          for (uInt i = 0; i < params.size(); ++i) {
4947            params[i] = 0.0;
4948          }
4949          bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
4950                        getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
4951                        true, STBaselineFunc::Sinusoid, nWaves, std::vector<float>(),
4952                        getMaskListFromMask(chanMask), params, 0.0, sp.size(),
4953                        thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
4954        }
4955      }
4956
4957      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
4958    }
4959
4960    finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
4961
4962    if (flagged > 0) {
4963      LogIO os( LogOrigin( "Scantable", "autoSinusoidBaseline()") ) ;
4964      os << LogIO::WARN << "Baseline subtraction is skipped for " << flagged << " spectra due to too few valid channels to operate fit. The spectra will be flagged in output data." << LogIO::POST;
4965    }
4966  } catch (...) {
4967    throw;
4968  }
4969}
4970
4971std::vector<float> Scantable::doSinusoidFitting(const std::vector<float>& data,
4972                                                const std::vector<bool>& mask,
4973                                                const std::vector<int>& waveNumbers,
4974                                                std::vector<float>& params,
4975                                                float& rms,
4976                                                std::vector<bool>& finalmask,
4977                                                float clipth,
4978                                                int clipn)
4979{
4980  int nClipped = 0;
4981  return doSinusoidFitting(data, mask, waveNumbers, params, rms, finalmask, nClipped, clipth, clipn);
4982}
4983
4984std::vector<float> Scantable::doSinusoidFitting(const std::vector<float>& data,
4985                                                const std::vector<bool>& mask,
4986                                                const std::vector<int>& waveNumbers,
4987                                                std::vector<float>& params,
4988                                                float& rms,
4989                                                std::vector<bool>& finalMask,
4990                                                int& nClipped,
4991                                                float thresClip,
4992                                                int nIterClip,
4993                                                bool getResidual)
4994{
4995  return doLeastSquareFitting(data, mask,
4996                              getSinusoidModel(waveNumbers, data.size()),
4997                              params, rms, finalMask,
4998                              nClipped, thresClip, nIterClip,
4999                              getResidual);
5000}
5001
5002std::vector<std::vector<std::vector<double> > > Scantable::getSinusoidModelReservoir(const std::vector<int>& waveNumbers,
5003                                                                                     std::vector<int>& nChanNos)
5004{
5005  std::vector<std::vector<std::vector<double> > > res;
5006  res.clear();
5007  nChanNos.clear();
5008
5009  std::vector<uint> ifNos = getIFNos();
5010  for (uint i = 0; i < ifNos.size(); ++i) {
5011    int currNchan = nchan(ifNos[i]);
5012    bool hasDifferentNchan = (i == 0);
5013    for (uint j = 0; j < i; ++j) {
5014      if (currNchan != nchan(ifNos[j])) {
5015        hasDifferentNchan = true;
5016        break;
5017      }
5018    }
5019    if (hasDifferentNchan) {
5020      res.push_back(getSinusoidModel(waveNumbers, currNchan));
5021      nChanNos.push_back(currNchan);
5022    }
5023  }
5024
5025  return res;
5026}
5027
5028std::vector<std::vector<double> > Scantable::getSinusoidModel(const std::vector<int>& waveNumbers, int nchan)
5029{
5030  // model  : contains elemental values for computing the least-square matrix.
5031  //          model.size() is nmodel and model[*].size() is nchan.
5032  //          Each model element are as follows:
5033  //          model[0]    = {1.0, 1.0, 1.0, ..., 1.0},
5034  //          model[2n-1] = {sin(nPI/L*x[0]), sin(nPI/L*x[1]), ..., sin(nPI/L*x[nchan])},
5035  //          model[2n]   = {cos(nPI/L*x[0]), cos(nPI/L*x[1]), ..., cos(nPI/L*x[nchan])},
5036  //          where (1 <= n <= nMaxWavesInSW),
5037  //          or,
5038  //          model[2n-1] = {sin(wn[n]PI/L*x[0]), sin(wn[n]PI/L*x[1]), ..., sin(wn[n]PI/L*x[nchan])},
5039  //          model[2n]   = {cos(wn[n]PI/L*x[0]), cos(wn[n]PI/L*x[1]), ..., cos(wn[n]PI/L*x[nchan])},
5040  //          where wn[n] denotes waveNumbers[n] (1 <= n <= waveNumbers.size()).
5041
5042  std::vector<int> nWaves;  // sorted and uniqued array of wave numbers
5043  nWaves.reserve(waveNumbers.size());
5044  copy(waveNumbers.begin(), waveNumbers.end(), back_inserter(nWaves));
5045  sort(nWaves.begin(), nWaves.end());
5046  std::vector<int>::iterator end_it = unique(nWaves.begin(), nWaves.end());
5047  nWaves.erase(end_it, nWaves.end());
5048
5049  if (nWaves.size()==0)
5050    throw(AipsError("No valid wavenumbers to fit."));
5051
5052  int minNWaves = nWaves[0];
5053  if (minNWaves < 0) {
5054    throw(AipsError("wave number must be positive or zero (i.e. constant)"));
5055  }
5056  bool hasConstantTerm = (minNWaves == 0);
5057  int nmodel = nWaves.size() * 2 - (hasConstantTerm ? 1 : 0);  //number of parameters to solve.
5058
5059  std::vector<std::vector<double> > model(nmodel, std::vector<double>(nchan));
5060
5061  if (hasConstantTerm) {
5062    for (int j = 0; j < nchan; ++j) {
5063      model[0][j] = 1.0;
5064    }
5065  }
5066
5067  const double PI = 6.0 * asin(0.5); // PI (= 3.141592653...)
5068  double stretch0 = 2.0*PI/(double)(nchan-1);
5069
5070  for (uInt i = (hasConstantTerm ? 1 : 0); i < nWaves.size(); ++i) {
5071    int sidx = hasConstantTerm ? 2*i-1 : 2*i;
5072    int cidx = sidx + 1;
5073    double stretch = stretch0*(double)nWaves[i];
5074
5075    for (int j = 0; j < nchan; ++j) {
5076      model[sidx][j] = sin(stretch*(double)j);
5077      model[cidx][j] = cos(stretch*(double)j);
5078    }
5079  }
5080
5081  return model;
5082}
5083
5084std::vector<bool> Scantable::getCompositeChanMask(int whichrow,
5085                                                  const std::vector<bool>& inMask)
5086{
5087  std::vector<bool> mask = getMask(whichrow);
5088  uInt maskSize = mask.size();
5089  if (inMask.size() != 0) {
5090    if (maskSize != inMask.size()) {
5091      throw(AipsError("mask sizes are not the same."));
5092    }
5093    for (uInt i = 0; i < maskSize; ++i) {
5094      mask[i] = mask[i] && inMask[i];
5095    }
5096  }
5097
5098  return mask;
5099}
5100
5101std::vector<bool> Scantable::getCompositeChanMask(int whichrow,
5102                                                  const std::vector<bool>& inMask,
5103                                                  const std::vector<int>& edge,
5104                                                  std::vector<int>& currEdge,
5105                                                  STLineFinder& lineFinder)
5106{
5107  if (isAllChannelsFlagged(whichrow)) {//all channels flagged
5108    std::vector<bool> res_mask(nchan(getIF(whichrow)),false);
5109    return res_mask;
5110  } else if (inMask.size() != 0 && nValidMask(inMask)==0){ //no valid mask channels
5111    std::vector<bool> res_mask(inMask);
5112    return res_mask;
5113  }
5114
5115  std::vector<uint> ifNos = getIFNos();
5116  if ((edge.size() > 2) && (edge.size() < ifNos.size()*2)) {
5117    throw(AipsError("Length of edge element info is less than that of IFs"));
5118  }
5119
5120  uint idx = 0;
5121  if (edge.size() > 2) {
5122    int ifVal = getIF(whichrow);
5123    bool foundIF = false;
5124    for (uint i = 0; i < ifNos.size(); ++i) {
5125      if (ifVal == (int)ifNos[i]) {
5126        idx = 2*i;
5127        foundIF = true;
5128        break;
5129      }
5130    }
5131    if (!foundIF) {
5132      throw(AipsError("bad IF number"));
5133    }
5134  }
5135
5136  currEdge.clear();
5137  currEdge.resize(2);
5138  currEdge[0] = edge[idx];
5139  currEdge[1] = edge[idx+1];
5140
5141  lineFinder.setData(getSpectrum(whichrow));
5142  lineFinder.findLines(getCompositeChanMask(whichrow, inMask), currEdge, whichrow);
5143  return lineFinder.getMask();
5144}
5145
5146/* for cspline. will be merged once cspline is available in fitter (2011/3/10 WK) */
5147void Scantable::outputFittingResult(bool outLogger,
5148                                    bool outTextFile,
5149                                    bool csvFormat,
5150                                    const std::vector<bool>& chanMask,
5151                                    int whichrow,
5152                                    const casa::String& coordInfo,
5153                                    bool hasSameNchan,
5154                                    ofstream& ofs,
5155                                    const casa::String& funcName,
5156                                    const std::vector<int>& edge,
5157                                    const std::vector<float>& params,
5158                                    const int nClipped)
5159{
5160  if (outLogger || outTextFile) {
5161    float rms = getRms(chanMask, whichrow);
5162    String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
5163    std::vector<bool> fixed;
5164    fixed.clear();
5165
5166    if (outLogger) {
5167      LogIO ols(LogOrigin("Scantable", funcName, WHERE));
5168      ols << formatPiecewiseBaselineParams(edge, params, fixed, rms, nClipped,
5169                                           masklist, whichrow, false, csvFormat) << LogIO::POST ;
5170    }
5171    if (outTextFile) {
5172      ofs << formatPiecewiseBaselineParams(edge, params, fixed, rms, nClipped,
5173                                           masklist, whichrow, true, csvFormat) << flush;
5174    }
5175  }
5176}
5177
5178/* for poly/chebyshev/sinusoid. */
5179void Scantable::outputFittingResult(bool outLogger,
5180                                    bool outTextFile,
5181                                    bool csvFormat,
5182                                    const std::vector<bool>& chanMask,
5183                                    int whichrow,
5184                                    const casa::String& coordInfo,
5185                                    bool hasSameNchan,
5186                                    ofstream& ofs,
5187                                    const casa::String& funcName,
5188                                    const std::vector<float>& params,
5189                                    const int nClipped)
5190{
5191  if (outLogger || outTextFile) {
5192    float rms = getRms(chanMask, whichrow);
5193    String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
5194    std::vector<bool> fixed;
5195    fixed.clear();
5196
5197    if (outLogger) {
5198      LogIO ols(LogOrigin("Scantable", funcName, WHERE));
5199      ols << formatBaselineParams(params, fixed, rms, nClipped,
5200                                  masklist, whichrow, false, csvFormat) << LogIO::POST ;
5201    }
5202    if (outTextFile) {
5203      ofs << formatBaselineParams(params, fixed, rms, nClipped,
5204                                  masklist, whichrow, true, csvFormat) << flush;
5205    }
5206  }
5207}
5208
5209void Scantable::parseProgressInfo(const std::string& progressInfo, bool& showProgress, int& minNRow)
5210{
5211  int idxDelimiter = progressInfo.find(",");
5212  if (idxDelimiter < 0) {
5213    throw(AipsError("wrong value in 'showprogress' parameter")) ;
5214  }
5215  showProgress = (progressInfo.substr(0, idxDelimiter) == "true");
5216  std::istringstream is(progressInfo.substr(idxDelimiter+1));
5217  is >> minNRow;
5218}
5219
5220void Scantable::showProgressOnTerminal(const int nProcessed, const int nTotal, const bool showProgress, const int nTotalThreshold)
5221{
5222  if (showProgress && (nTotal >= nTotalThreshold)) {
5223    int nInterval = int(floor(double(nTotal)/100.0));
5224    if (nInterval == 0) nInterval++;
5225
5226    if (nProcessed % nInterval == 0) {
5227      printf("\r");                          //go to the head of line
5228      printf("\x1b[31m\x1b[1m");             //set red color, highlighted
5229      printf("[%3d%%]", (int)(100.0*(double(nProcessed+1))/(double(nTotal))) );
5230      printf("\x1b[39m\x1b[0m");             //set default attributes
5231      fflush(NULL);
5232    }
5233
5234    if (nProcessed == nTotal - 1) {
5235      printf("\r\x1b[K");                    //clear
5236      fflush(NULL);
5237    }
5238
5239  }
5240}
5241
5242std::vector<float> Scantable::execFFT(const int whichrow, const std::vector<bool>& inMask, bool getRealImag, bool getAmplitudeOnly)
5243{
5244  std::vector<bool>  mask = getMask(whichrow);
5245
5246  if (inMask.size() > 0) {
5247    uInt maskSize = mask.size();
5248    if (maskSize != inMask.size()) {
5249      throw(AipsError("mask sizes are not the same."));
5250    }
5251    for (uInt i = 0; i < maskSize; ++i) {
5252      mask[i] = mask[i] && inMask[i];
5253    }
5254  }
5255
5256  Vector<Float> spec = getSpectrum(whichrow);
5257  mathutil::doZeroOrderInterpolation(spec, mask);
5258
5259  FFTServer<Float,Complex> ffts;
5260  Vector<Complex> fftres;
5261  ffts.fft0(fftres, spec);
5262
5263  std::vector<float> res;
5264  float norm = float(2.0/double(spec.size()));
5265
5266  if (getRealImag) {
5267    for (uInt i = 0; i < fftres.size(); ++i) {
5268      res.push_back(real(fftres[i])*norm);
5269      res.push_back(imag(fftres[i])*norm);
5270    }
5271  } else {
5272    for (uInt i = 0; i < fftres.size(); ++i) {
5273      res.push_back(abs(fftres[i])*norm);
5274      if (!getAmplitudeOnly) res.push_back(arg(fftres[i]));
5275    }
5276  }
5277
5278  return res;
5279}
5280
5281
5282float Scantable::getRms(const std::vector<bool>& mask, int whichrow)
5283{
5284  /****
5285  double ms1TimeStart, ms1TimeEnd;
5286  double elapse1 = 0.0;
5287  ms1TimeStart = mathutil::gettimeofday_sec();
5288  ****/
5289
5290  Vector<Float> spec;
5291  specCol_.get(whichrow, spec);
5292
5293  /****
5294  ms1TimeEnd = mathutil::gettimeofday_sec();
5295  elapse1 = ms1TimeEnd - ms1TimeStart;
5296  std::cout << "rm1   : " << elapse1 << " (sec.)" << endl;
5297  ****/
5298
5299  return (float)doGetRms(mask, spec);
5300}
5301
5302double Scantable::doGetRms(const std::vector<bool>& mask, const Vector<Float>& spec)
5303{
5304  double mean = 0.0;
5305  double smean = 0.0;
5306  int n = 0;
5307  for (uInt i = 0; i < spec.nelements(); ++i) {
5308    if (mask[i]) {
5309      double val = (double)spec[i];
5310      mean += val;
5311      smean += val*val;
5312      n++;
5313    }
5314  }
5315
5316  mean /= (double)n;
5317  smean /= (double)n;
5318
5319  return sqrt(smean - mean*mean);
5320}
5321
5322std::string Scantable::formatBaselineParamsHeader(int whichrow, const std::string& masklist, bool verbose, bool csvformat) const
5323{
5324  if (verbose) {
5325    ostringstream oss;
5326
5327    if (csvformat) {
5328      oss << getScan(whichrow)  << ",";
5329      oss << getBeam(whichrow)  << ",";
5330      oss << getIF(whichrow)    << ",";
5331      oss << getPol(whichrow)   << ",";
5332      oss << getCycle(whichrow) << ",";
5333      String commaReplacedMasklist = masklist;
5334      string::size_type pos = 0;
5335      while (pos = commaReplacedMasklist.find(","), pos != string::npos) {
5336        commaReplacedMasklist.replace(pos, 1, ";");
5337        pos++;
5338      }
5339      oss << commaReplacedMasklist << ",";
5340    } else {
5341      oss <<  " Scan[" << getScan(whichrow)  << "]";
5342      oss <<  " Beam[" << getBeam(whichrow)  << "]";
5343      oss <<    " IF[" << getIF(whichrow)    << "]";
5344      oss <<   " Pol[" << getPol(whichrow)   << "]";
5345      oss << " Cycle[" << getCycle(whichrow) << "]: " << endl;
5346      oss << "Fitter range = " << masklist << endl;
5347      oss << "Baseline parameters" << endl;
5348    }
5349    oss << flush;
5350
5351    return String(oss);
5352  }
5353
5354  return "";
5355}
5356
5357std::string Scantable::formatBaselineParamsFooter(float rms, int nClipped, bool verbose, bool csvformat) const
5358{
5359  if (verbose) {
5360    ostringstream oss;
5361
5362    if (csvformat) {
5363      oss << rms << ",";
5364      if (nClipped >= 0) {
5365        oss << nClipped;
5366      }
5367    } else {
5368      oss << "Results of baseline fit" << endl;
5369      oss << "  rms = " << setprecision(6) << rms << endl;
5370      if (nClipped >= 0) {
5371        oss << "  Number of clipped channels = " << nClipped << endl;
5372      }
5373      for (int i = 0; i < 60; ++i) {
5374        oss << "-";
5375      }
5376    }
5377    oss << endl;
5378    oss << flush;
5379
5380    return String(oss);
5381  }
5382
5383  return "";
5384}
5385
5386std::string Scantable::formatBaselineParams(const std::vector<float>& params,
5387                                            const std::vector<bool>& fixed,
5388                                            float rms,
5389                                            int nClipped,
5390                                            const std::string& masklist,
5391                                            int whichrow,
5392                                            bool verbose,
5393                                            bool csvformat,
5394                                            int start, int count,
5395                                            bool resetparamid) const
5396{
5397  int nParam = (int)(params.size());
5398
5399  if (nParam < 1) {
5400    return("  Not fitted");
5401  } else {
5402
5403    ostringstream oss;
5404    oss << formatBaselineParamsHeader(whichrow, masklist, verbose, csvformat);
5405
5406    if (start < 0) start = 0;
5407    if (count < 0) count = nParam;
5408    int end = start + count;
5409    if (end > nParam) end = nParam;
5410    int paramidoffset = (resetparamid) ? (-start) : 0;
5411
5412    for (int i = start; i < end; ++i) {
5413      if (i > start) {
5414        oss << ",";
5415      }
5416      std::string sFix = ((fixed.size() > 0) && (fixed[i]) && verbose) ? "(fixed)" : "";
5417      if (csvformat) {
5418        oss << params[i] << sFix;
5419      } else {
5420        oss << "  p" << (i+paramidoffset) << sFix << "= " << right << setw(13) << setprecision(6) << params[i];
5421      }
5422    }
5423
5424    if (csvformat) {
5425      oss << ",";
5426    } else {
5427      oss << endl;
5428    }
5429    oss << formatBaselineParamsFooter(rms, nClipped, verbose, csvformat);
5430
5431    return String(oss);
5432  }
5433
5434}
5435
5436std::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, bool csvformat) const
5437{
5438  int nOutParam = (int)(params.size());
5439  int nPiece = (int)(ranges.size()) - 1;
5440
5441  if (nOutParam < 1) {
5442    return("  Not fitted");
5443  } else if (nPiece < 0) {
5444    return formatBaselineParams(params, fixed, rms, nClipped, masklist, whichrow, verbose, csvformat);
5445  } else if (nPiece < 1) {
5446    return("  Bad count of the piece edge info");
5447  } else if (nOutParam % nPiece != 0) {
5448    return("  Bad count of the output baseline parameters");
5449  } else {
5450
5451    int nParam = nOutParam / nPiece;
5452
5453    ostringstream oss;
5454    oss << formatBaselineParamsHeader(whichrow, masklist, verbose, csvformat);
5455
5456    if (csvformat) {
5457      for (int i = 0; i < nPiece; ++i) {
5458        oss << ranges[i] << "," << (ranges[i+1]-1) << ",";
5459        oss << formatBaselineParams(params, fixed, rms, 0, masklist, whichrow, false, csvformat, i*nParam, nParam, true);
5460      }
5461    } else {
5462      stringstream ss;
5463      ss << ranges[nPiece] << flush;
5464      int wRange = ss.str().size() * 2 + 5;
5465
5466      for (int i = 0; i < nPiece; ++i) {
5467        ss.str("");
5468        ss << "  [" << ranges[i] << "," << (ranges[i+1]-1) << "]";
5469        oss << left << setw(wRange) << ss.str();
5470        oss << formatBaselineParams(params, fixed, rms, 0, masklist, whichrow, false, csvformat, i*nParam, nParam, true);
5471        //oss << endl;
5472      }
5473    }
5474
5475    oss << formatBaselineParamsFooter(rms, nClipped, verbose, csvformat);
5476
5477    return String(oss);
5478  }
5479
5480}
5481
5482bool Scantable::hasSameNchanOverIFs()
5483{
5484  int nIF = nif(-1);
5485  int nCh;
5486  int totalPositiveNChan = 0;
5487  int nPositiveNChan = 0;
5488
5489  for (int i = 0; i < nIF; ++i) {
5490    nCh = nchan(i);
5491    if (nCh > 0) {
5492      totalPositiveNChan += nCh;
5493      nPositiveNChan++;
5494    }
5495  }
5496
5497  return (totalPositiveNChan == (nPositiveNChan * nchan(0)));
5498}
5499
5500std::string Scantable::getMaskRangeList(const std::vector<bool>& mask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, bool verbose)
5501{
5502  if (mask.size() <= 0) {
5503    throw(AipsError("The mask elements should be > 0"));
5504  }
5505  int IF = getIF(whichrow);
5506  if (mask.size() != (uInt)nchan(IF)) {
5507    throw(AipsError("Number of channels in scantable != number of mask elements"));
5508  }
5509
5510  if (verbose) {
5511    LogIO logOs(LogOrigin("Scantable", "getMaskRangeList()", WHERE));
5512    logOs << LogIO::WARN << "The current mask window unit is " << coordInfo;
5513    if (!hasSameNchan) {
5514      logOs << endl << "This mask is only valid for IF=" << IF;
5515    }
5516    logOs << LogIO::POST;
5517  }
5518
5519  std::vector<double> abcissa = getAbcissa(whichrow);
5520  std::vector<int> edge = getMaskEdgeIndices(mask);
5521
5522  ostringstream oss;
5523  oss.setf(ios::fixed);
5524  oss << setprecision(1) << "[";
5525  for (uInt i = 0; i < edge.size(); i+=2) {
5526    if (i > 0) oss << ",";
5527    oss << "[" << (float)abcissa[edge[i]] << "," << (float)abcissa[edge[i+1]] << "]";
5528  }
5529  oss << "]" << flush;
5530
5531  return String(oss);
5532}
5533
5534std::vector<int> Scantable::getMaskEdgeIndices(const std::vector<bool>& mask)
5535{
5536  if (mask.size() <= 0) {
5537    throw(AipsError("The mask elements should be > 0"));
5538  }
5539
5540  std::vector<int> out, startIndices, endIndices;
5541  int maskSize = mask.size();
5542
5543  startIndices.clear();
5544  endIndices.clear();
5545
5546  if (mask[0]) {
5547    startIndices.push_back(0);
5548  }
5549  for (int i = 1; i < maskSize; ++i) {
5550    if ((!mask[i-1]) && mask[i]) {
5551      startIndices.push_back(i);
5552    } else if (mask[i-1] && (!mask[i])) {
5553      endIndices.push_back(i-1);
5554    }
5555  }
5556  if (mask[maskSize-1]) {
5557    endIndices.push_back(maskSize-1);
5558  }
5559
5560  if (startIndices.size() != endIndices.size()) {
5561    throw(AipsError("Inconsistent Mask Size: bad data?"));
5562  }
5563  for (uInt i = 0; i < startIndices.size(); ++i) {
5564    if (startIndices[i] > endIndices[i]) {
5565      throw(AipsError("Mask start index > mask end index"));
5566    }
5567  }
5568
5569  out.clear();
5570  for (uInt i = 0; i < startIndices.size(); ++i) {
5571    out.push_back(startIndices[i]);
5572    out.push_back(endIndices[i]);
5573  }
5574
5575  return out;
5576}
5577
5578void Scantable::setTsys(const std::vector<float>& newvals, int whichrow) {
5579  Vector<Float> tsys(newvals);
5580  if (whichrow > -1) {
5581    if (tsysCol_.shape(whichrow) != tsys.shape())
5582      throw(AipsError("Given Tsys values are not of the same shape"));
5583    tsysCol_.put(whichrow, tsys);
5584  } else {
5585    tsysCol_.fillColumn(tsys);
5586  }
5587}
5588
5589vector<float> Scantable::getTsysSpectrum( int whichrow ) const
5590{
5591  Vector<Float> tsys( tsysCol_(whichrow) ) ;
5592  vector<float> stlTsys ;
5593  tsys.tovector( stlTsys ) ;
5594  return stlTsys ;
5595}
5596
5597vector<uint> Scantable::getMoleculeIdColumnData() const
5598{
5599  Vector<uInt> molIds(mmolidCol_.getColumn());
5600  vector<uint> res;
5601  molIds.tovector(res);
5602  return res;
5603}
5604
5605void Scantable::setMoleculeIdColumnData(const std::vector<uint>& molids)
5606{
5607  Vector<uInt> molIds(molids);
5608  Vector<uInt> arr(mmolidCol_.getColumn());
5609  if ( molIds.nelements() != arr.nelements() )
5610    throw AipsError("The input data size must be the number of rows.");
5611  mmolidCol_.putColumn(molIds);
5612}
5613
5614
5615std::vector<uint> Scantable::getRootTableRowNumbers() const
5616{
5617  Vector<uInt> rowIds(table_.rowNumbers());
5618  vector<uint> res;
5619  rowIds.tovector(res);
5620  return res;
5621}
5622
5623
5624void Scantable::dropXPol()
5625{
5626  if (npol() <= 2) {
5627    return;
5628  }
5629  if (!selector_.empty()) {
5630    throw AipsError("Can only operate with empty selection");
5631  }
5632  std::string taql = "SELECT FROM $1 WHERE POLNO IN [0,1]";
5633  Table tab = tableCommand(taql, table_);
5634  table_ = tab;
5635  table_.rwKeywordSet().define("nPol", Int(2));
5636  originalTable_ = table_;
5637  attach();
5638}
5639
5640}
5641//namespace asap
Note: See TracBrowser for help on using the repository browser.