source: trunk/src/Scantable.cpp @ 2644

Last change on this file since 2644 was 2644, checked in by WataruKawasaki, 12 years ago

New Development: No

JIRA Issue: No

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs:

Put in Release Notes: No

Module(s): sd.scantable

Description: modified to not output an empty line in formatPiecewiseBaselineParams().


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