source: trunk/src/Scantable.cpp @ 2591

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

New Development: Yes

JIRA Issue: Yes CSV-1869

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs:

Put in Release Notes: No

Module(s): asap

Description: added a scantable function to get/set moleculesID columns data.


  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 121.7 KB
Line 
1//
2// C++ Implementation: Scantable
3//
4// Description:
5//
6//
7// Author: Malte Marquarding <asap@atnf.csiro.au>, (C) 2005
8//
9// Copyright: See COPYING file that comes with this distribution
10//
11//
12#include <map>
13#include <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
2306std::vector<float> Scantable::getWeather(int whichrow) const
2307{
2308  std::vector<float> out(5);
2309  //Float temperature, pressure, humidity, windspeed, windaz;
2310  weatherTable_.getEntry(out[0], out[1], out[2], out[3], out[4],
2311                         mweatheridCol_(uInt(whichrow)));
2312
2313
2314  return out;
2315}
2316
2317bool Scantable::getFlagtraFast(uInt whichrow)
2318{
2319  uChar flag;
2320  Vector<uChar> flags;
2321  flagsCol_.get(whichrow, flags);
2322  flag = flags[0];
2323  for (uInt i = 1; i < flags.size(); ++i) {
2324    flag &= flags[i];
2325  }
2326  return ((flag >> 7) == 1);
2327}
2328
2329void Scantable::polyBaseline(const std::vector<bool>& mask, int order, bool getResidual, const std::string& progressInfo, const bool outLogger, const std::string& blfile)
2330{
2331  try {
2332    ofstream ofs;
2333    String coordInfo = "";
2334    bool hasSameNchan = true;
2335    bool outTextFile = false;
2336
2337    if (blfile != "") {
2338      ofs.open(blfile.c_str(), ios::out | ios::app);
2339      if (ofs) outTextFile = true;
2340    }
2341
2342    if (outLogger || outTextFile) {
2343      coordInfo = getCoordInfo()[0];
2344      if (coordInfo == "") coordInfo = "channel";
2345      hasSameNchan = hasSameNchanOverIFs();
2346    }
2347
2348    Fitter fitter = Fitter();
2349    fitter.setExpression("poly", order);
2350    //fitter.setIterClipping(thresClip, nIterClip);
2351
2352    int nRow = nrow();
2353    std::vector<bool> chanMask;
2354    bool showProgress;
2355    int minNRow;
2356    parseProgressInfo(progressInfo, showProgress, minNRow);
2357
2358    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2359      chanMask = getCompositeChanMask(whichrow, mask);
2360      fitBaseline(chanMask, whichrow, fitter);
2361      setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
2362      outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "polyBaseline()", fitter);
2363      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
2364    }
2365
2366    if (outTextFile) ofs.close();
2367
2368  } catch (...) {
2369    throw;
2370  }
2371}
2372
2373void 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)
2374{
2375  try {
2376    ofstream ofs;
2377    String coordInfo = "";
2378    bool hasSameNchan = true;
2379    bool outTextFile = false;
2380
2381    if (blfile != "") {
2382      ofs.open(blfile.c_str(), ios::out | ios::app);
2383      if (ofs) outTextFile = true;
2384    }
2385
2386    if (outLogger || outTextFile) {
2387      coordInfo = getCoordInfo()[0];
2388      if (coordInfo == "") coordInfo = "channel";
2389      hasSameNchan = hasSameNchanOverIFs();
2390    }
2391
2392    Fitter fitter = Fitter();
2393    fitter.setExpression("poly", order);
2394    //fitter.setIterClipping(thresClip, nIterClip);
2395
2396    int nRow = nrow();
2397    std::vector<bool> chanMask;
2398    int minEdgeSize = getIFNos().size()*2;
2399    STLineFinder lineFinder = STLineFinder();
2400    lineFinder.setOptions(threshold, 3, chanAvgLimit);
2401
2402    bool showProgress;
2403    int minNRow;
2404    parseProgressInfo(progressInfo, showProgress, minNRow);
2405
2406    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2407
2408      //-------------------------------------------------------
2409      //chanMask = getCompositeChanMask(whichrow, mask, edge, minEdgeSize, lineFinder);
2410      //-------------------------------------------------------
2411      int edgeSize = edge.size();
2412      std::vector<int> currentEdge;
2413      if (edgeSize >= 2) {
2414        int idx = 0;
2415        if (edgeSize > 2) {
2416          if (edgeSize < minEdgeSize) {
2417            throw(AipsError("Length of edge element info is less than that of IFs"));
2418          }
2419          idx = 2 * getIF(whichrow);
2420        }
2421        currentEdge.push_back(edge[idx]);
2422        currentEdge.push_back(edge[idx+1]);
2423      } else {
2424        throw(AipsError("Wrong length of edge element"));
2425      }
2426      lineFinder.setData(getSpectrum(whichrow));
2427      lineFinder.findLines(getCompositeChanMask(whichrow, mask), currentEdge, whichrow);
2428      chanMask = lineFinder.getMask();
2429      //-------------------------------------------------------
2430
2431      fitBaseline(chanMask, whichrow, fitter);
2432      setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
2433
2434      outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "autoPolyBaseline()", fitter);
2435      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
2436    }
2437
2438    if (outTextFile) ofs.close();
2439
2440  } catch (...) {
2441    throw;
2442  }
2443}
2444
2445void 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)
2446{
2447  /*************/
2448  //clock_t totTimeStart, totTimeEnd, blTimeStart, blTimeEnd, ioTimeStart, ioTimeEnd;
2449  double totTimeStart, totTimeEnd, blTimeStart, blTimeEnd, ioTimeStart, ioTimeEnd, msTimeStart, msTimeEnd, seTimeStart, seTimeEnd, otTimeStart, otTimeEnd, prTimeStart, prTimeEnd;
2450  double elapseMs = 0.0;
2451  double elapseSe = 0.0;
2452  double elapseOt = 0.0;
2453  double elapsePr = 0.0;
2454  double elapseBl = 0.0;
2455  double elapseIo = 0.0;
2456  //totTimeStart = clock();
2457  totTimeStart = mathutil::gettimeofday_sec();
2458  /*************/
2459
2460  try {
2461    ofstream ofs;
2462    String coordInfo = "";
2463    bool hasSameNchan = true;
2464    bool outTextFile = false;
2465
2466    if (blfile != "") {
2467      ofs.open(blfile.c_str(), ios::out | ios::app);
2468      if (ofs) outTextFile = true;
2469    }
2470
2471    if (outLogger || outTextFile) {
2472      coordInfo = getCoordInfo()[0];
2473      if (coordInfo == "") coordInfo = "channel";
2474      hasSameNchan = hasSameNchanOverIFs();
2475    }
2476
2477    //Fitter fitter = Fitter();
2478    //fitter.setExpression("cspline", nPiece);
2479    //fitter.setIterClipping(thresClip, nIterClip);
2480
2481    bool showProgress;
2482    int minNRow;
2483    parseProgressInfo(progressInfo, showProgress, minNRow);
2484
2485    int nRow = nrow();
2486    std::vector<bool> chanMask;
2487
2488    //--------------------------------
2489    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2490      /******************/
2491      //ioTimeStart = clock();
2492      ioTimeStart = mathutil::gettimeofday_sec();
2493      /**/
2494      std::vector<float> sp = getSpectrum(whichrow);
2495      /**/
2496      //ioTimeEnd = clock();
2497      ioTimeEnd = mathutil::gettimeofday_sec();
2498      elapseIo += (double)(ioTimeEnd - ioTimeStart);
2499
2500      //blTimeStart = clock();
2501      msTimeStart = mathutil::gettimeofday_sec();
2502      /******************/
2503
2504      chanMask = getCompositeChanMask(whichrow, mask);
2505
2506      /**/
2507      msTimeEnd = mathutil::gettimeofday_sec();
2508      elapseMs += (double)(msTimeEnd - msTimeStart);
2509      blTimeStart = mathutil::gettimeofday_sec();
2510      /**/
2511
2512      //fitBaseline(chanMask, whichrow, fitter);
2513      //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
2514      std::vector<int> pieceEdges(nPiece+1);
2515      std::vector<float> params(nPiece*4);
2516      int nClipped = 0;
2517      std::vector<float> res = doCubicSplineFitting(sp, chanMask, nPiece, pieceEdges, params, nClipped, thresClip, nIterClip, getResidual);
2518
2519      /**/
2520      blTimeEnd = mathutil::gettimeofday_sec();
2521      elapseBl += (double)(blTimeEnd - blTimeStart);
2522      seTimeStart = mathutil::gettimeofday_sec();
2523      /**/
2524
2525
2526      setSpectrum(res, whichrow);
2527      //
2528
2529      /**/
2530      seTimeEnd = mathutil::gettimeofday_sec();
2531      elapseSe += (double)(seTimeEnd - seTimeStart);
2532      otTimeStart = mathutil::gettimeofday_sec();
2533      /**/
2534
2535      outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "cubicSplineBaseline()", pieceEdges, params, nClipped);
2536
2537      /**/
2538      otTimeEnd = mathutil::gettimeofday_sec();
2539      elapseOt += (double)(otTimeEnd - otTimeStart);
2540      prTimeStart = mathutil::gettimeofday_sec();
2541      /**/
2542
2543      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
2544
2545      /******************/
2546      //blTimeEnd = clock();
2547      prTimeEnd = mathutil::gettimeofday_sec();
2548      elapsePr += (double)(prTimeEnd - prTimeStart);
2549      /******************/
2550    }
2551    //--------------------------------
2552   
2553    if (outTextFile) ofs.close();
2554
2555  } catch (...) {
2556    throw;
2557  }
2558  /***************/
2559  //totTimeEnd = clock();
2560  totTimeEnd = mathutil::gettimeofday_sec();
2561  //std::cout << "io    : " << elapseIo/CLOCKS_PER_SEC << " (sec.)" << endl;
2562  //std::cout << "bl    : " << elapseBl/CLOCKS_PER_SEC << " (sec.)" << endl;
2563  //std::cout << "total : " << (double)(totTimeEnd - totTimeStart)/CLOCKS_PER_SEC << " (sec.)" << endl;
2564  std::cout << "io    : " << elapseIo << " (sec.)" << endl;
2565  std::cout << "ms    : " << elapseMs << " (sec.)" << endl;
2566  std::cout << "bl    : " << elapseBl << " (sec.)" << endl;
2567  std::cout << "se    : " << elapseSe << " (sec.)" << endl;
2568  std::cout << "ot    : " << elapseOt << " (sec.)" << endl;
2569  std::cout << "pr    : " << elapsePr << " (sec.)" << endl;
2570  std::cout << "total : " << (double)(totTimeEnd - totTimeStart) << " (sec.)" << endl;
2571  /***************/
2572}
2573
2574void 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)
2575{
2576  /*************
2577  clock_t totTimeStart, totTimeEnd, blTimeStart, blTimeEnd, ioTimeStart, ioTimeEnd;
2578  double elapseBl = 0.0;
2579  double elapseIo = 0.0;
2580  totTimeStart = clock();
2581  *************/
2582
2583  try {
2584    ofstream ofs;
2585    String coordInfo = "";
2586    bool hasSameNchan = true;
2587    bool outTextFile = false;
2588
2589    if (blfile != "") {
2590      ofs.open(blfile.c_str(), ios::out | ios::app);
2591      if (ofs) outTextFile = true;
2592    }
2593
2594    if (outLogger || outTextFile) {
2595      coordInfo = getCoordInfo()[0];
2596      if (coordInfo == "") coordInfo = "channel";
2597      hasSameNchan = hasSameNchanOverIFs();
2598    }
2599
2600    //Fitter fitter = Fitter();
2601    //fitter.setExpression("cspline", nPiece);
2602    //fitter.setIterClipping(thresClip, nIterClip);
2603
2604    int nRow = nrow();
2605    std::vector<bool> chanMask;
2606    int minEdgeSize = getIFNos().size()*2;
2607    STLineFinder lineFinder = STLineFinder();
2608    lineFinder.setOptions(threshold, 3, chanAvgLimit);
2609
2610    bool showProgress;
2611    int minNRow;
2612    parseProgressInfo(progressInfo, showProgress, minNRow);
2613
2614    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2615      /******************
2616      ioTimeStart = clock();
2617      */
2618      std::vector<float> sp = getSpectrum(whichrow);
2619      /*
2620      ioTimeEnd = clock();
2621      elapseIo += (double)(ioTimeEnd - ioTimeStart);
2622
2623      blTimeStart = clock();
2624      ******************/
2625
2626      //-------------------------------------------------------
2627      //chanMask = getCompositeChanMask(whichrow, mask, edge, minEdgeSize, lineFinder);
2628      //-------------------------------------------------------
2629      int edgeSize = edge.size();
2630      std::vector<int> currentEdge;
2631      if (edgeSize >= 2) {
2632        int idx = 0;
2633        if (edgeSize > 2) {
2634          if (edgeSize < minEdgeSize) {
2635            throw(AipsError("Length of edge element info is less than that of IFs"));
2636          }
2637          idx = 2 * getIF(whichrow);
2638        }
2639        currentEdge.push_back(edge[idx]);
2640        currentEdge.push_back(edge[idx+1]);
2641      } else {
2642        throw(AipsError("Wrong length of edge element"));
2643      }
2644      lineFinder.setData(getSpectrum(whichrow));
2645      lineFinder.findLines(getCompositeChanMask(whichrow, mask), currentEdge, whichrow);
2646      chanMask = lineFinder.getMask();
2647      //-------------------------------------------------------
2648
2649
2650      //fitBaseline(chanMask, whichrow, fitter);
2651      //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
2652      std::vector<int> pieceEdges(nPiece+1);
2653      std::vector<float> params(nPiece*4);
2654      int nClipped = 0;
2655      std::vector<float> res = doCubicSplineFitting(sp, chanMask, nPiece, pieceEdges, params, nClipped, thresClip, nIterClip, getResidual);
2656      setSpectrum(res, whichrow);
2657      //
2658
2659      outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "autoCubicSplineBaseline()", pieceEdges, params, nClipped);
2660      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
2661
2662      /******************
2663      blTimeEnd = clock();
2664      elapseBl += (double)(blTimeEnd - blTimeStart);
2665      ******************/
2666
2667    }
2668
2669    if (outTextFile) ofs.close();
2670
2671  } catch (...) {
2672    throw;
2673  }
2674
2675  /***************
2676  totTimeEnd = clock();
2677  std::cout << "io    : " << elapseIo/CLOCKS_PER_SEC << " (sec.)" << endl;
2678  std::cout << "bl    : " << elapseBl/CLOCKS_PER_SEC << " (sec.)" << endl;
2679  std::cout << "total : " << (double)(totTimeEnd - totTimeStart)/CLOCKS_PER_SEC << " (sec.)" << endl;
2680  ***************/
2681}
2682
2683std::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)
2684{
2685  if (data.size() != mask.size()) {
2686    throw(AipsError("data and mask sizes are not identical"));
2687  }
2688  if (nPiece < 1) {
2689    throw(AipsError("number of the sections must be one or more"));
2690  }
2691
2692  int nChan = data.size();
2693  std::vector<int> maskArray(nChan);
2694  std::vector<int> x(nChan);
2695  int j = 0;
2696  for (int i = 0; i < nChan; ++i) {
2697    maskArray[i] = mask[i] ? 1 : 0;
2698    if (mask[i]) {
2699      x[j] = i;
2700      j++;
2701    }
2702  }
2703  int initNData = j;
2704
2705  if (initNData < nPiece) {
2706    throw(AipsError("too few non-flagged channels"));
2707  }
2708
2709  int nElement = (int)(floor(floor((double)(initNData/nPiece))+0.5));
2710  std::vector<double> invEdge(nPiece-1);
2711  idxEdge[0] = x[0];
2712  for (int i = 1; i < nPiece; ++i) {
2713    int valX = x[nElement*i];
2714    idxEdge[i] = valX;
2715    invEdge[i-1] = 1.0/(double)valX;
2716  }
2717  idxEdge[nPiece] = x[initNData-1]+1;
2718
2719  int nData = initNData;
2720  int nDOF = nPiece + 3;  //number of parameters to solve, namely, 4+(nPiece-1).
2721
2722  std::vector<double> x1(nChan), x2(nChan), x3(nChan);
2723  std::vector<double> z1(nChan), x1z1(nChan), x2z1(nChan), x3z1(nChan);
2724  std::vector<double> r1(nChan), residual(nChan);
2725  for (int i = 0; i < nChan; ++i) {
2726    double di = (double)i;
2727    double dD = (double)data[i];
2728    x1[i]   = di;
2729    x2[i]   = di*di;
2730    x3[i]   = di*di*di;
2731    z1[i]   = dD;
2732    x1z1[i] = dD*di;
2733    x2z1[i] = dD*di*di;
2734    x3z1[i] = dD*di*di*di;
2735    r1[i]   = 0.0;
2736    residual[i] = 0.0;
2737  }
2738
2739  for (int nClip = 0; nClip < nIterClip+1; ++nClip) {
2740    // xMatrix : horizontal concatenation of
2741    //           the least-sq. matrix (left) and an
2742    //           identity matrix (right).
2743    // the right part is used to calculate the inverse matrix of the left part.
2744    double xMatrix[nDOF][2*nDOF];
2745    double zMatrix[nDOF];
2746    for (int i = 0; i < nDOF; ++i) {
2747      for (int j = 0; j < 2*nDOF; ++j) {
2748        xMatrix[i][j] = 0.0;
2749      }
2750      xMatrix[i][nDOF+i] = 1.0;
2751      zMatrix[i] = 0.0;
2752    }
2753
2754    for (int n = 0; n < nPiece; ++n) {
2755      int nUseDataInPiece = 0;
2756      for (int i = idxEdge[n]; i < idxEdge[n+1]; ++i) {
2757
2758        if (maskArray[i] == 0) continue;
2759
2760        xMatrix[0][0] += 1.0;
2761        xMatrix[0][1] += x1[i];
2762        xMatrix[0][2] += x2[i];
2763        xMatrix[0][3] += x3[i];
2764        xMatrix[1][1] += x2[i];
2765        xMatrix[1][2] += x3[i];
2766        xMatrix[1][3] += x2[i]*x2[i];
2767        xMatrix[2][2] += x2[i]*x2[i];
2768        xMatrix[2][3] += x3[i]*x2[i];
2769        xMatrix[3][3] += x3[i]*x3[i];
2770        zMatrix[0] += z1[i];
2771        zMatrix[1] += x1z1[i];
2772        zMatrix[2] += x2z1[i];
2773        zMatrix[3] += x3z1[i];
2774
2775        for (int j = 0; j < n; ++j) {
2776          double q = 1.0 - x1[i]*invEdge[j];
2777          q = q*q*q;
2778          xMatrix[0][j+4] += q;
2779          xMatrix[1][j+4] += q*x1[i];
2780          xMatrix[2][j+4] += q*x2[i];
2781          xMatrix[3][j+4] += q*x3[i];
2782          for (int k = 0; k < j; ++k) {
2783            double r = 1.0 - x1[i]*invEdge[k];
2784            r = r*r*r;
2785            xMatrix[k+4][j+4] += r*q;
2786          }
2787          xMatrix[j+4][j+4] += q*q;
2788          zMatrix[j+4] += q*z1[i];
2789        }
2790
2791        nUseDataInPiece++;
2792      }
2793
2794      if (nUseDataInPiece < 1) {
2795        std::vector<string> suffixOfPieceNumber(4);
2796        suffixOfPieceNumber[0] = "th";
2797        suffixOfPieceNumber[1] = "st";
2798        suffixOfPieceNumber[2] = "nd";
2799        suffixOfPieceNumber[3] = "rd";
2800        int idxNoDataPiece = (n % 10 <= 3) ? n : 0;
2801        ostringstream oss;
2802        oss << "all channels clipped or masked in " << n << suffixOfPieceNumber[idxNoDataPiece];
2803        oss << " piece of the spectrum. can't execute fitting anymore.";
2804        throw(AipsError(String(oss)));
2805      }
2806    }
2807
2808    for (int i = 0; i < nDOF; ++i) {
2809      for (int j = 0; j < i; ++j) {
2810        xMatrix[i][j] = xMatrix[j][i];
2811      }
2812    }
2813
2814    std::vector<double> invDiag(nDOF);
2815    for (int i = 0; i < nDOF; ++i) {
2816      invDiag[i] = 1.0/xMatrix[i][i];
2817      for (int j = 0; j < nDOF; ++j) {
2818        xMatrix[i][j] *= invDiag[i];
2819      }
2820    }
2821
2822    for (int k = 0; k < nDOF; ++k) {
2823      for (int i = 0; i < nDOF; ++i) {
2824        if (i != k) {
2825          double factor1 = xMatrix[k][k];
2826          double factor2 = xMatrix[i][k];
2827          for (int j = k; j < 2*nDOF; ++j) {
2828            xMatrix[i][j] *= factor1;
2829            xMatrix[i][j] -= xMatrix[k][j]*factor2;
2830            xMatrix[i][j] /= factor1;
2831          }
2832        }
2833      }
2834      double xDiag = xMatrix[k][k];
2835      for (int j = k; j < 2*nDOF; ++j) {
2836        xMatrix[k][j] /= xDiag;
2837      }
2838    }
2839   
2840    for (int i = 0; i < nDOF; ++i) {
2841      for (int j = 0; j < nDOF; ++j) {
2842        xMatrix[i][nDOF+j] *= invDiag[j];
2843      }
2844    }
2845    //compute a vector y which consists of the coefficients of the best-fit spline curves
2846    //(a0,a1,a2,a3(,b3,c3,...)), namely, the ones for the leftmost piece and the ones of
2847    //cubic terms for the other pieces (in case nPiece>1).
2848    std::vector<double> y(nDOF);
2849    for (int i = 0; i < nDOF; ++i) {
2850      y[i] = 0.0;
2851      for (int j = 0; j < nDOF; ++j) {
2852        y[i] += xMatrix[i][nDOF+j]*zMatrix[j];
2853      }
2854    }
2855
2856    double a0 = y[0];
2857    double a1 = y[1];
2858    double a2 = y[2];
2859    double a3 = y[3];
2860
2861    int j = 0;
2862    for (int n = 0; n < nPiece; ++n) {
2863      for (int i = idxEdge[n]; i < idxEdge[n+1]; ++i) {
2864        r1[i] = a0 + a1*x1[i] + a2*x2[i] + a3*x3[i];
2865      }
2866      params[j]   = a0;
2867      params[j+1] = a1;
2868      params[j+2] = a2;
2869      params[j+3] = a3;
2870      j += 4;
2871
2872      if (n == nPiece-1) break;
2873
2874      double d = y[4+n];
2875      double iE = invEdge[n];
2876      a0 +=     d;
2877      a1 -= 3.0*d*iE;
2878      a2 += 3.0*d*iE*iE;
2879      a3 -=     d*iE*iE*iE;
2880    }
2881
2882    //subtract constant value for masked regions at the edge of spectrum
2883    if (idxEdge[0] > 0) {
2884      int n = idxEdge[0];
2885      for (int i = 0; i < idxEdge[0]; ++i) {
2886        //--cubic extrapolate--
2887        //r1[i] = params[0] + params[1]*x1[i] + params[2]*x2[i] + params[3]*x3[i];
2888        //--linear extrapolate--
2889        //r1[i] = (r1[n+1] - r1[n])/(x1[n+1] - x1[n])*(x1[i] - x1[n]) + r1[n];
2890        //--constant--
2891        r1[i] = r1[n];
2892      }
2893    }
2894    if (idxEdge[nPiece] < nChan) {
2895      int n = idxEdge[nPiece]-1;
2896      for (int i = idxEdge[nPiece]; i < nChan; ++i) {
2897        //--cubic extrapolate--
2898        //int m = 4*(nPiece-1);
2899        //r1[i] = params[m] + params[m+1]*x1[i] + params[m+2]*x2[i] + params[m+3]*x3[i];
2900        //--linear extrapolate--
2901        //r1[i] = (r1[n-1] - r1[n])/(x1[n-1] - x1[n])*(x1[i] - x1[n]) + r1[n];
2902        //--constant--
2903        r1[i] = r1[n];
2904      }
2905    }
2906
2907    for (int i = 0; i < nChan; ++i) {
2908      residual[i] = z1[i] - r1[i];
2909    }
2910
2911    if ((nClip == nIterClip) || (thresClip <= 0.0)) {
2912      break;
2913    } else {
2914      double stdDev = 0.0;
2915      for (int i = 0; i < nChan; ++i) {
2916        stdDev += residual[i]*residual[i]*(double)maskArray[i];
2917      }
2918      stdDev = sqrt(stdDev/(double)nData);
2919     
2920      double thres = stdDev * thresClip;
2921      int newNData = 0;
2922      for (int i = 0; i < nChan; ++i) {
2923        if (abs(residual[i]) >= thres) {
2924          maskArray[i] = 0;
2925        }
2926        if (maskArray[i] > 0) {
2927          newNData++;
2928        }
2929      }
2930      if (newNData == nData) {
2931        break; //no more flag to add. iteration stops.
2932      } else {
2933        nData = newNData;
2934      }
2935    }
2936  }
2937
2938  nClipped = initNData - nData;
2939
2940  std::vector<float> result(nChan);
2941  if (getResidual) {
2942    for (int i = 0; i < nChan; ++i) {
2943      result[i] = (float)residual[i];
2944    }
2945  } else {
2946    for (int i = 0; i < nChan; ++i) {
2947      result[i] = (float)r1[i];
2948    }
2949  }
2950
2951  return result;
2952}
2953
2954void 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)
2955{
2956  nWaves.clear();
2957
2958  if (applyFFT) {
2959    string fftThAttr;
2960    float fftThSigma;
2961    int fftThTop;
2962    parseThresholdExpression(fftThresh, fftThAttr, fftThSigma, fftThTop);
2963    doSelectWaveNumbers(whichrow, chanMask, fftMethod, fftThSigma, fftThTop, fftThAttr, nWaves);
2964  }
2965
2966  addAuxWaveNumbers(whichrow, addNWaves, rejectNWaves, nWaves);
2967}
2968
2969void Scantable::parseThresholdExpression(const std::string& fftThresh, std::string& fftThAttr, float& fftThSigma, int& fftThTop)
2970{
2971  uInt idxSigma = fftThresh.find("sigma");
2972  uInt idxTop   = fftThresh.find("top");
2973
2974  if (idxSigma == fftThresh.size() - 5) {
2975    std::istringstream is(fftThresh.substr(0, fftThresh.size() - 5));
2976    is >> fftThSigma;
2977    fftThAttr = "sigma";
2978  } else if (idxTop == 0) {
2979    std::istringstream is(fftThresh.substr(3));
2980    is >> fftThTop;
2981    fftThAttr = "top";
2982  } else {
2983    bool isNumber = true;
2984    for (uInt i = 0; i < fftThresh.size()-1; ++i) {
2985      char ch = (fftThresh.substr(i, 1).c_str())[0];
2986      if (!(isdigit(ch) || (fftThresh.substr(i, 1) == "."))) {
2987        isNumber = false;
2988        break;
2989      }
2990    }
2991    if (isNumber) {
2992      std::istringstream is(fftThresh);
2993      is >> fftThSigma;
2994      fftThAttr = "sigma";
2995    } else {
2996      throw(AipsError("fftthresh has a wrong value"));
2997    }
2998  }
2999}
3000
3001void 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)
3002{
3003  std::vector<float> fspec;
3004  if (fftMethod == "fft") {
3005    fspec = execFFT(whichrow, chanMask, false, true);
3006  //} else if (fftMethod == "lsp") {
3007  //  fspec = lombScarglePeriodogram(whichrow);
3008  }
3009
3010  if (fftThAttr == "sigma") {
3011    float mean  = 0.0;
3012    float mean2 = 0.0;
3013    for (uInt i = 0; i < fspec.size(); ++i) {
3014      mean  += fspec[i];
3015      mean2 += fspec[i]*fspec[i];
3016    }
3017    mean  /= float(fspec.size());
3018    mean2 /= float(fspec.size());
3019    float thres = mean + fftThSigma * float(sqrt(mean2 - mean*mean));
3020
3021    for (uInt i = 0; i < fspec.size(); ++i) {
3022      if (fspec[i] >= thres) {
3023        nWaves.push_back(i);
3024      }
3025    }
3026
3027  } else if (fftThAttr == "top") {
3028    for (int i = 0; i < fftThTop; ++i) {
3029      float max = 0.0;
3030      int maxIdx = 0;
3031      for (uInt j = 0; j < fspec.size(); ++j) {
3032        if (fspec[j] > max) {
3033          max = fspec[j];
3034          maxIdx = j;
3035        }
3036      }
3037      nWaves.push_back(maxIdx);
3038      fspec[maxIdx] = 0.0;
3039    }
3040
3041  }
3042
3043  if (nWaves.size() > 1) {
3044    sort(nWaves.begin(), nWaves.end());
3045  }
3046}
3047
3048void Scantable::addAuxWaveNumbers(const int whichrow, const std::vector<int>& addNWaves, const std::vector<int>& rejectNWaves, std::vector<int>& nWaves)
3049{
3050  std::vector<int> tempAddNWaves, tempRejectNWaves;
3051  for (uInt i = 0; i < addNWaves.size(); ++i) {
3052    tempAddNWaves.push_back(addNWaves[i]);
3053  }
3054  if ((tempAddNWaves.size() == 2) && (tempAddNWaves[1] == -999)) {
3055    setWaveNumberListUptoNyquistFreq(whichrow, tempAddNWaves);
3056  }
3057
3058  for (uInt i = 0; i < rejectNWaves.size(); ++i) {
3059    tempRejectNWaves.push_back(rejectNWaves[i]);
3060  }
3061  if ((tempRejectNWaves.size() == 2) && (tempRejectNWaves[1] == -999)) {
3062    setWaveNumberListUptoNyquistFreq(whichrow, tempRejectNWaves);
3063  }
3064
3065  for (uInt i = 0; i < tempAddNWaves.size(); ++i) {
3066    bool found = false;
3067    for (uInt j = 0; j < nWaves.size(); ++j) {
3068      if (nWaves[j] == tempAddNWaves[i]) {
3069        found = true;
3070        break;
3071      }
3072    }
3073    if (!found) nWaves.push_back(tempAddNWaves[i]);
3074  }
3075
3076  for (uInt i = 0; i < tempRejectNWaves.size(); ++i) {
3077    for (std::vector<int>::iterator j = nWaves.begin(); j != nWaves.end(); ) {
3078      if (*j == tempRejectNWaves[i]) {
3079        j = nWaves.erase(j);
3080      } else {
3081        ++j;
3082      }
3083    }
3084  }
3085
3086  if (nWaves.size() > 1) {
3087    sort(nWaves.begin(), nWaves.end());
3088    unique(nWaves.begin(), nWaves.end());
3089  }
3090}
3091
3092void Scantable::setWaveNumberListUptoNyquistFreq(const int whichrow, std::vector<int>& nWaves)
3093{
3094  if ((nWaves.size() == 2)&&(nWaves[1] == -999)) {
3095    int val = nWaves[0];
3096    int nyquistFreq = nchan(getIF(whichrow))/2+1;
3097    nWaves.clear();
3098    if (val > nyquistFreq) {  // for safety, at least nWaves contains a constant; CAS-3759
3099      nWaves.push_back(0);
3100    }
3101    while (val <= nyquistFreq) {
3102      nWaves.push_back(val);
3103      val++;
3104    }
3105  }
3106}
3107
3108void 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)
3109{
3110  try {
3111    ofstream ofs;
3112    String coordInfo = "";
3113    bool hasSameNchan = true;
3114    bool outTextFile = false;
3115
3116    if (blfile != "") {
3117      ofs.open(blfile.c_str(), ios::out | ios::app);
3118      if (ofs) outTextFile = true;
3119    }
3120
3121    if (outLogger || outTextFile) {
3122      coordInfo = getCoordInfo()[0];
3123      if (coordInfo == "") coordInfo = "channel";
3124      hasSameNchan = hasSameNchanOverIFs();
3125    }
3126
3127    //Fitter fitter = Fitter();
3128    //fitter.setExpression("sinusoid", nWaves);
3129    //fitter.setIterClipping(thresClip, nIterClip);
3130
3131    int nRow = nrow();
3132    std::vector<bool> chanMask;
3133    std::vector<int> nWaves;
3134
3135    bool showProgress;
3136    int minNRow;
3137    parseProgressInfo(progressInfo, showProgress, minNRow);
3138
3139    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
3140      chanMask = getCompositeChanMask(whichrow, mask);
3141      selectWaveNumbers(whichrow, chanMask, applyFFT, fftMethod, fftThresh, addNWaves, rejectNWaves, nWaves);
3142
3143      //FOR DEBUGGING------------
3144      /*
3145      if (whichrow < 0) {// == nRow -1) {
3146        cout << "+++ i=" << setw(3) << whichrow << ", IF=" << setw(2) << getIF(whichrow);
3147        if (applyFFT) {
3148          cout << "[ ";
3149          for (uInt j = 0; j < nWaves.size(); ++j) {
3150            cout << nWaves[j] << ", ";
3151          }
3152          cout << " ]    " << endl;
3153        }
3154        cout << flush;
3155      }
3156      */
3157      //-------------------------
3158
3159      //fitBaseline(chanMask, whichrow, fitter);
3160      //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
3161      std::vector<float> params;
3162      int nClipped = 0;
3163      std::vector<float> res = doSinusoidFitting(getSpectrum(whichrow), chanMask, nWaves, params, nClipped, thresClip, nIterClip, getResidual);
3164      setSpectrum(res, whichrow);
3165      //
3166
3167      outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "sinusoidBaseline()", params, nClipped);
3168      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
3169    }
3170
3171    if (outTextFile) ofs.close();
3172
3173  } catch (...) {
3174    throw;
3175  }
3176}
3177
3178void 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)
3179{
3180  try {
3181    ofstream ofs;
3182    String coordInfo = "";
3183    bool hasSameNchan = true;
3184    bool outTextFile = false;
3185
3186    if (blfile != "") {
3187      ofs.open(blfile.c_str(), ios::out | ios::app);
3188      if (ofs) outTextFile = true;
3189    }
3190
3191    if (outLogger || outTextFile) {
3192      coordInfo = getCoordInfo()[0];
3193      if (coordInfo == "") coordInfo = "channel";
3194      hasSameNchan = hasSameNchanOverIFs();
3195    }
3196
3197    //Fitter fitter = Fitter();
3198    //fitter.setExpression("sinusoid", nWaves);
3199    //fitter.setIterClipping(thresClip, nIterClip);
3200
3201    int nRow = nrow();
3202    std::vector<bool> chanMask;
3203    std::vector<int> nWaves;
3204
3205    int minEdgeSize = getIFNos().size()*2;
3206    STLineFinder lineFinder = STLineFinder();
3207    lineFinder.setOptions(threshold, 3, chanAvgLimit);
3208
3209    bool showProgress;
3210    int minNRow;
3211    parseProgressInfo(progressInfo, showProgress, minNRow);
3212
3213    for (int whichrow = 0; whichrow < nRow; ++whichrow) {
3214
3215      //-------------------------------------------------------
3216      //chanMask = getCompositeChanMask(whichrow, mask, edge, minEdgeSize, lineFinder);
3217      //-------------------------------------------------------
3218      int edgeSize = edge.size();
3219      std::vector<int> currentEdge;
3220      if (edgeSize >= 2) {
3221        int idx = 0;
3222        if (edgeSize > 2) {
3223          if (edgeSize < minEdgeSize) {
3224            throw(AipsError("Length of edge element info is less than that of IFs"));
3225          }
3226          idx = 2 * getIF(whichrow);
3227        }
3228        currentEdge.push_back(edge[idx]);
3229        currentEdge.push_back(edge[idx+1]);
3230      } else {
3231        throw(AipsError("Wrong length of edge element"));
3232      }
3233      lineFinder.setData(getSpectrum(whichrow));
3234      lineFinder.findLines(getCompositeChanMask(whichrow, mask), currentEdge, whichrow);
3235      chanMask = lineFinder.getMask();
3236      //-------------------------------------------------------
3237
3238      selectWaveNumbers(whichrow, chanMask, applyFFT, fftMethod, fftThresh, addNWaves, rejectNWaves, nWaves);
3239
3240      //fitBaseline(chanMask, whichrow, fitter);
3241      //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
3242      std::vector<float> params;
3243      int nClipped = 0;
3244      std::vector<float> res = doSinusoidFitting(getSpectrum(whichrow), chanMask, nWaves, params, nClipped, thresClip, nIterClip, getResidual);
3245      setSpectrum(res, whichrow);
3246      //
3247
3248      outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "autoSinusoidBaseline()", params, nClipped);
3249      showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
3250    }
3251
3252    if (outTextFile) ofs.close();
3253
3254  } catch (...) {
3255    throw;
3256  }
3257}
3258
3259std::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)
3260{
3261  if (data.size() != mask.size()) {
3262    throw(AipsError("data and mask sizes are not identical"));
3263  }
3264  if (data.size() < 2) {
3265    throw(AipsError("data size is too short"));
3266  }
3267  if (waveNumbers.size() == 0) {
3268    throw(AipsError("no wave numbers given"));
3269  }
3270  std::vector<int> nWaves;  // sorted and uniqued array of wave numbers
3271  nWaves.reserve(waveNumbers.size());
3272  copy(waveNumbers.begin(), waveNumbers.end(), back_inserter(nWaves));
3273  sort(nWaves.begin(), nWaves.end());
3274  std::vector<int>::iterator end_it = unique(nWaves.begin(), nWaves.end());
3275  nWaves.erase(end_it, nWaves.end());
3276
3277  int minNWaves = nWaves[0];
3278  if (minNWaves < 0) {
3279    throw(AipsError("wave number must be positive or zero (i.e. constant)"));
3280  }
3281  bool hasConstantTerm = (minNWaves == 0);
3282
3283  int nChan = data.size();
3284  std::vector<int> maskArray;
3285  std::vector<int> x;
3286  for (int i = 0; i < nChan; ++i) {
3287    maskArray.push_back(mask[i] ? 1 : 0);
3288    if (mask[i]) {
3289      x.push_back(i);
3290    }
3291  }
3292
3293  int initNData = x.size();
3294
3295  int nData = initNData;
3296  int nDOF = nWaves.size() * 2 - (hasConstantTerm ? 1 : 0);  //number of parameters to solve.
3297
3298  const double PI = 6.0 * asin(0.5); // PI (= 3.141592653...)
3299  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)
3300
3301  // xArray : contains elemental values for computing the least-square matrix.
3302  //          xArray.size() is nDOF and xArray[*].size() is nChan.
3303  //          Each xArray element are as follows:
3304  //          xArray[0]    = {1.0, 1.0, 1.0, ..., 1.0},
3305  //          xArray[2n-1] = {sin(nPI/L*x[0]), sin(nPI/L*x[1]), ..., sin(nPI/L*x[nChan])},
3306  //          xArray[2n]   = {cos(nPI/L*x[0]), cos(nPI/L*x[1]), ..., cos(nPI/L*x[nChan])},
3307  //          where (1 <= n <= nMaxWavesInSW),
3308  //          or,
3309  //          xArray[2n-1] = {sin(wn[n]PI/L*x[0]), sin(wn[n]PI/L*x[1]), ..., sin(wn[n]PI/L*x[nChan])},
3310  //          xArray[2n]   = {cos(wn[n]PI/L*x[0]), cos(wn[n]PI/L*x[1]), ..., cos(wn[n]PI/L*x[nChan])},
3311  //          where wn[n] denotes waveNumbers[n] (1 <= n <= waveNumbers.size()).
3312  std::vector<std::vector<double> > xArray;
3313  if (hasConstantTerm) {
3314    std::vector<double> xu;
3315    for (int j = 0; j < nChan; ++j) {
3316      xu.push_back(1.0);
3317    }
3318    xArray.push_back(xu);
3319  }
3320  for (uInt i = (hasConstantTerm ? 1 : 0); i < nWaves.size(); ++i) {
3321    double xFactor = baseXFactor*(double)nWaves[i];
3322    std::vector<double> xs, xc;
3323    xs.clear();
3324    xc.clear();
3325    for (int j = 0; j < nChan; ++j) {
3326      xs.push_back(sin(xFactor*(double)j));
3327      xc.push_back(cos(xFactor*(double)j));
3328    }
3329    xArray.push_back(xs);
3330    xArray.push_back(xc);
3331  }
3332
3333  std::vector<double> z1, r1, residual;
3334  for (int i = 0; i < nChan; ++i) {
3335    z1.push_back((double)data[i]);
3336    r1.push_back(0.0);
3337    residual.push_back(0.0);
3338  }
3339
3340  for (int nClip = 0; nClip < nIterClip+1; ++nClip) {
3341    // xMatrix : horizontal concatenation of
3342    //           the least-sq. matrix (left) and an
3343    //           identity matrix (right).
3344    // the right part is used to calculate the inverse matrix of the left part.
3345    double xMatrix[nDOF][2*nDOF];
3346    double zMatrix[nDOF];
3347    for (int i = 0; i < nDOF; ++i) {
3348      for (int j = 0; j < 2*nDOF; ++j) {
3349        xMatrix[i][j] = 0.0;
3350      }
3351      xMatrix[i][nDOF+i] = 1.0;
3352      zMatrix[i] = 0.0;
3353    }
3354
3355    int nUseData = 0;
3356    for (int k = 0; k < nChan; ++k) {
3357      if (maskArray[k] == 0) continue;
3358
3359      for (int i = 0; i < nDOF; ++i) {
3360        for (int j = i; j < nDOF; ++j) {
3361          xMatrix[i][j] += xArray[i][k] * xArray[j][k];
3362        }
3363        zMatrix[i] += z1[k] * xArray[i][k];
3364      }
3365
3366      nUseData++;
3367    }
3368
3369    if (nUseData < 1) {
3370        throw(AipsError("all channels clipped or masked. can't execute fitting anymore."));     
3371    }
3372
3373    for (int i = 0; i < nDOF; ++i) {
3374      for (int j = 0; j < i; ++j) {
3375        xMatrix[i][j] = xMatrix[j][i];
3376      }
3377    }
3378
3379    std::vector<double> invDiag;
3380    for (int i = 0; i < nDOF; ++i) {
3381      invDiag.push_back(1.0/xMatrix[i][i]);
3382      for (int j = 0; j < nDOF; ++j) {
3383        xMatrix[i][j] *= invDiag[i];
3384      }
3385    }
3386
3387    for (int k = 0; k < nDOF; ++k) {
3388      for (int i = 0; i < nDOF; ++i) {
3389        if (i != k) {
3390          double factor1 = xMatrix[k][k];
3391          double factor2 = xMatrix[i][k];
3392          for (int j = k; j < 2*nDOF; ++j) {
3393            xMatrix[i][j] *= factor1;
3394            xMatrix[i][j] -= xMatrix[k][j]*factor2;
3395            xMatrix[i][j] /= factor1;
3396          }
3397        }
3398      }
3399      double xDiag = xMatrix[k][k];
3400      for (int j = k; j < 2*nDOF; ++j) {
3401        xMatrix[k][j] /= xDiag;
3402      }
3403    }
3404   
3405    for (int i = 0; i < nDOF; ++i) {
3406      for (int j = 0; j < nDOF; ++j) {
3407        xMatrix[i][nDOF+j] *= invDiag[j];
3408      }
3409    }
3410    //compute a vector y which consists of the coefficients of the sinusoids forming the
3411    //best-fit curves (a0,s1,c1,s2,c2,...), where a0 is constant and s* and c* are of sine
3412    //and cosine functions, respectively.
3413    std::vector<double> y;
3414    params.clear();
3415    for (int i = 0; i < nDOF; ++i) {
3416      y.push_back(0.0);
3417      for (int j = 0; j < nDOF; ++j) {
3418        y[i] += xMatrix[i][nDOF+j]*zMatrix[j];
3419      }
3420      params.push_back(y[i]);
3421    }
3422
3423    for (int i = 0; i < nChan; ++i) {
3424      r1[i] = y[0];
3425      for (int j = 1; j < nDOF; ++j) {
3426        r1[i] += y[j]*xArray[j][i];
3427      }
3428      residual[i] = z1[i] - r1[i];
3429    }
3430
3431    if ((nClip == nIterClip) || (thresClip <= 0.0)) {
3432      break;
3433    } else {
3434      double stdDev = 0.0;
3435      for (int i = 0; i < nChan; ++i) {
3436        stdDev += residual[i]*residual[i]*(double)maskArray[i];
3437      }
3438      stdDev = sqrt(stdDev/(double)nData);
3439     
3440      double thres = stdDev * thresClip;
3441      int newNData = 0;
3442      for (int i = 0; i < nChan; ++i) {
3443        if (abs(residual[i]) >= thres) {
3444          maskArray[i] = 0;
3445        }
3446        if (maskArray[i] > 0) {
3447          newNData++;
3448        }
3449      }
3450      if (newNData == nData) {
3451        break; //no more flag to add. iteration stops.
3452      } else {
3453        nData = newNData;
3454      }
3455    }
3456  }
3457
3458  nClipped = initNData - nData;
3459
3460  std::vector<float> result;
3461  if (getResidual) {
3462    for (int i = 0; i < nChan; ++i) {
3463      result.push_back((float)residual[i]);
3464    }
3465  } else {
3466    for (int i = 0; i < nChan; ++i) {
3467      result.push_back((float)r1[i]);
3468    }
3469  }
3470
3471  return result;
3472}
3473
3474void Scantable::fitBaseline(const std::vector<bool>& mask, int whichrow, Fitter& fitter)
3475{
3476  std::vector<double> dAbcissa = getAbcissa(whichrow);
3477  std::vector<float> abcissa;
3478  for (uInt i = 0; i < dAbcissa.size(); ++i) {
3479    abcissa.push_back((float)dAbcissa[i]);
3480  }
3481  std::vector<float> spec = getSpectrum(whichrow);
3482
3483  fitter.setData(abcissa, spec, mask);
3484  fitter.lfit();
3485}
3486
3487std::vector<bool> Scantable::getCompositeChanMask(int whichrow, const std::vector<bool>& inMask)
3488{
3489  /****
3490  double ms1TimeStart, ms1TimeEnd, ms2TimeStart, ms2TimeEnd;
3491  double elapse1 = 0.0;
3492  double elapse2 = 0.0;
3493
3494  ms1TimeStart = mathutil::gettimeofday_sec();
3495  ****/
3496
3497  std::vector<bool> mask = getMask(whichrow);
3498
3499  /****
3500  ms1TimeEnd = mathutil::gettimeofday_sec();
3501  elapse1 = ms1TimeEnd - ms1TimeStart;
3502  std::cout << "ms1   : " << elapse1 << " (sec.)" << endl;
3503  ms2TimeStart = mathutil::gettimeofday_sec();
3504  ****/
3505
3506  uInt maskSize = mask.size();
3507  if (inMask.size() != 0) {
3508    if (maskSize != inMask.size()) {
3509      throw(AipsError("mask sizes are not the same."));
3510    }
3511    for (uInt i = 0; i < maskSize; ++i) {
3512      mask[i] = mask[i] && inMask[i];
3513    }
3514  }
3515
3516  /****
3517  ms2TimeEnd = mathutil::gettimeofday_sec();
3518  elapse2 = ms2TimeEnd - ms2TimeStart;
3519  std::cout << "ms2   : " << elapse2 << " (sec.)" << endl;
3520  ****/
3521
3522  return mask;
3523}
3524
3525/*
3526std::vector<bool> Scantable::getCompositeChanMask(int whichrow, const std::vector<bool>& inMask, const std::vector<int>& edge, const int minEdgeSize, STLineFinder& lineFinder)
3527{
3528  int edgeSize = edge.size();
3529  std::vector<int> currentEdge;
3530  if (edgeSize >= 2) {
3531      int idx = 0;
3532      if (edgeSize > 2) {
3533        if (edgeSize < minEdgeSize) {
3534          throw(AipsError("Length of edge element info is less than that of IFs"));
3535        }
3536        idx = 2 * getIF(whichrow);
3537      }
3538      currentEdge.push_back(edge[idx]);
3539      currentEdge.push_back(edge[idx+1]);
3540  } else {
3541    throw(AipsError("Wrong length of edge element"));
3542  }
3543
3544  lineFinder.setData(getSpectrum(whichrow));
3545  lineFinder.findLines(getCompositeChanMask(whichrow, inMask), currentEdge, whichrow);
3546
3547  return lineFinder.getMask();
3548}
3549*/
3550
3551/* for poly. the variations of outputFittingResult() should be merged into one eventually (2011/3/10 WK)  */
3552void Scantable::outputFittingResult(bool outLogger, bool outTextFile, const std::vector<bool>& chanMask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, ofstream& ofs, const casa::String& funcName, Fitter& fitter)
3553{
3554  if (outLogger || outTextFile) {
3555    std::vector<float> params = fitter.getParameters();
3556    std::vector<bool>  fixed  = fitter.getFixedParameters();
3557    float rms = getRms(chanMask, whichrow);
3558    String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
3559
3560    if (outLogger) {
3561      LogIO ols(LogOrigin("Scantable", funcName, WHERE));
3562      ols << formatBaselineParams(params, fixed, rms, -1, masklist, whichrow, false) << LogIO::POST ;
3563    }
3564    if (outTextFile) {
3565      ofs << formatBaselineParams(params, fixed, rms, -1, masklist, whichrow, true) << flush;
3566    }
3567  }
3568}
3569
3570/* for cspline. will be merged once cspline is available in fitter (2011/3/10 WK) */
3571void Scantable::outputFittingResult(bool outLogger, bool outTextFile, const std::vector<bool>& chanMask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, ofstream& ofs, const casa::String& funcName, const std::vector<int>& edge, const std::vector<float>& params, const int nClipped)
3572{
3573  if (outLogger || outTextFile) {
3574  /****
3575  double ms1TimeStart, ms1TimeEnd, ms2TimeStart, ms2TimeEnd;
3576  double elapse1 = 0.0;
3577  double elapse2 = 0.0;
3578
3579  ms1TimeStart = mathutil::gettimeofday_sec();
3580  ****/
3581
3582    float rms = getRms(chanMask, whichrow);
3583
3584  /****
3585  ms1TimeEnd = mathutil::gettimeofday_sec();
3586  elapse1 = ms1TimeEnd - ms1TimeStart;
3587  std::cout << "ot1   : " << elapse1 << " (sec.)" << endl;
3588  ms2TimeStart = mathutil::gettimeofday_sec();
3589  ****/
3590
3591    String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
3592    std::vector<bool> fixed;
3593    fixed.clear();
3594
3595    if (outLogger) {
3596      LogIO ols(LogOrigin("Scantable", funcName, WHERE));
3597      ols << formatPiecewiseBaselineParams(edge, params, fixed, rms, nClipped, masklist, whichrow, false) << LogIO::POST ;
3598    }
3599    if (outTextFile) {
3600      ofs << formatPiecewiseBaselineParams(edge, params, fixed, rms, nClipped, masklist, whichrow, true);// << flush;
3601    }
3602
3603  /****
3604  ms2TimeEnd = mathutil::gettimeofday_sec();
3605  elapse2 = ms2TimeEnd - ms2TimeStart;
3606  std::cout << "ot2   : " << elapse2 << " (sec.)" << endl;
3607  ****/
3608
3609  }
3610}
3611
3612/* for sinusoid. will be merged once sinusoid is available in fitter (2011/3/10 WK) */
3613void Scantable::outputFittingResult(bool outLogger, bool outTextFile, const std::vector<bool>& chanMask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, ofstream& ofs, const casa::String& funcName, const std::vector<float>& params, const int nClipped)
3614{
3615  if (outLogger || outTextFile) {
3616    float rms = getRms(chanMask, whichrow);
3617    String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
3618    std::vector<bool> fixed;
3619    fixed.clear();
3620
3621    if (outLogger) {
3622      LogIO ols(LogOrigin("Scantable", funcName, WHERE));
3623      ols << formatBaselineParams(params, fixed, rms, nClipped, masklist, whichrow, false) << LogIO::POST ;
3624    }
3625    if (outTextFile) {
3626      ofs << formatBaselineParams(params, fixed, rms, nClipped, masklist, whichrow, true) << flush;
3627    }
3628  }
3629}
3630
3631void Scantable::parseProgressInfo(const std::string& progressInfo, bool& showProgress, int& minNRow)
3632{
3633  int idxDelimiter = progressInfo.find(",");
3634  if (idxDelimiter < 0) {
3635    throw(AipsError("wrong value in 'showprogress' parameter")) ;
3636  }
3637  showProgress = (progressInfo.substr(0, idxDelimiter) == "true");
3638  std::istringstream is(progressInfo.substr(idxDelimiter+1));
3639  is >> minNRow;
3640}
3641
3642void Scantable::showProgressOnTerminal(const int nProcessed, const int nTotal, const bool showProgress, const int nTotalThreshold)
3643{
3644  if (showProgress && (nTotal >= nTotalThreshold)) {
3645    int nInterval = int(floor(double(nTotal)/100.0));
3646    if (nInterval == 0) nInterval++;
3647
3648    if (nProcessed % nInterval == 0) {
3649      printf("\r");                          //go to the head of line
3650      printf("\x1b[31m\x1b[1m");             //set red color, highlighted
3651      printf("[%3d%%]", (int)(100.0*(double(nProcessed+1))/(double(nTotal))) );
3652      printf("\x1b[39m\x1b[0m");             //set default attributes
3653      fflush(NULL);
3654    }
3655
3656    if (nProcessed == nTotal - 1) {
3657      printf("\r\x1b[K");                    //clear
3658      fflush(NULL);
3659    }
3660
3661  }
3662}
3663
3664std::vector<float> Scantable::execFFT(const int whichrow, const std::vector<bool>& inMask, bool getRealImag, bool getAmplitudeOnly)
3665{
3666  std::vector<bool>  mask = getMask(whichrow);
3667
3668  if (inMask.size() > 0) {
3669    uInt maskSize = mask.size();
3670    if (maskSize != inMask.size()) {
3671      throw(AipsError("mask sizes are not the same."));
3672    }
3673    for (uInt i = 0; i < maskSize; ++i) {
3674      mask[i] = mask[i] && inMask[i];
3675    }
3676  }
3677
3678  Vector<Float> spec = getSpectrum(whichrow);
3679  mathutil::doZeroOrderInterpolation(spec, mask);
3680
3681  FFTServer<Float,Complex> ffts;
3682  Vector<Complex> fftres;
3683  ffts.fft0(fftres, spec);
3684
3685  std::vector<float> res;
3686  float norm = float(2.0/double(spec.size()));
3687
3688  if (getRealImag) {
3689    for (uInt i = 0; i < fftres.size(); ++i) {
3690      res.push_back(real(fftres[i])*norm);
3691      res.push_back(imag(fftres[i])*norm);
3692    }
3693  } else {
3694    for (uInt i = 0; i < fftres.size(); ++i) {
3695      res.push_back(abs(fftres[i])*norm);
3696      if (!getAmplitudeOnly) res.push_back(arg(fftres[i]));
3697    }
3698  }
3699
3700  return res;
3701}
3702
3703
3704float Scantable::getRms(const std::vector<bool>& mask, int whichrow)
3705{
3706  /****
3707  double ms1TimeStart, ms1TimeEnd, ms2TimeStart, ms2TimeEnd;
3708  double elapse1 = 0.0;
3709  double elapse2 = 0.0;
3710
3711  ms1TimeStart = mathutil::gettimeofday_sec();
3712  ****/
3713
3714  Vector<Float> spec;
3715
3716  specCol_.get(whichrow, spec);
3717
3718  /****
3719  ms1TimeEnd = mathutil::gettimeofday_sec();
3720  elapse1 = ms1TimeEnd - ms1TimeStart;
3721  std::cout << "rm1   : " << elapse1 << " (sec.)" << endl;
3722  ms2TimeStart = mathutil::gettimeofday_sec();
3723  ****/
3724
3725  float mean = 0.0;
3726  float smean = 0.0;
3727  int n = 0;
3728  for (uInt i = 0; i < spec.nelements(); ++i) {
3729    if (mask[i]) {
3730      mean += spec[i];
3731      smean += spec[i]*spec[i];
3732      n++;
3733    }
3734  }
3735
3736  mean /= (float)n;
3737  smean /= (float)n;
3738
3739  /****
3740  ms2TimeEnd = mathutil::gettimeofday_sec();
3741  elapse2 = ms2TimeEnd - ms2TimeStart;
3742  std::cout << "rm2   : " << elapse2 << " (sec.)" << endl;
3743  ****/
3744
3745  return sqrt(smean - mean*mean);
3746}
3747
3748
3749std::string Scantable::formatBaselineParamsHeader(int whichrow, const std::string& masklist, bool verbose) const
3750{
3751  ostringstream oss;
3752
3753  if (verbose) {
3754    oss <<  " Scan[" << getScan(whichrow)  << "]";
3755    oss <<  " Beam[" << getBeam(whichrow)  << "]";
3756    oss <<    " IF[" << getIF(whichrow)    << "]";
3757    oss <<   " Pol[" << getPol(whichrow)   << "]";
3758    oss << " Cycle[" << getCycle(whichrow) << "]: " << endl;
3759    oss << "Fitter range = " << masklist << endl;
3760    oss << "Baseline parameters" << endl;
3761    oss << flush;
3762  }
3763
3764  return String(oss);
3765}
3766
3767std::string Scantable::formatBaselineParamsFooter(float rms, int nClipped, bool verbose) const
3768{
3769  ostringstream oss;
3770
3771  if (verbose) {
3772    oss << "Results of baseline fit" << endl;
3773    oss << "  rms = " << setprecision(6) << rms << endl;
3774    if (nClipped >= 0) {
3775      oss << "  Number of clipped channels = " << nClipped << endl;
3776    }
3777    for (int i = 0; i < 60; ++i) {
3778      oss << "-";
3779    }
3780    oss << endl;
3781    oss << flush;
3782  }
3783
3784  return String(oss);
3785}
3786
3787std::string Scantable::formatBaselineParams(const std::vector<float>& params,
3788                                            const std::vector<bool>& fixed,
3789                                            float rms,
3790                                            int nClipped,
3791                                            const std::string& masklist,
3792                                            int whichrow,
3793                                            bool verbose,
3794                                            int start, int count,
3795                                            bool resetparamid) const
3796{
3797  int nParam = (int)(params.size());
3798
3799  if (nParam < 1) {
3800    return("  Not fitted");
3801  } else {
3802
3803    ostringstream oss;
3804    oss << formatBaselineParamsHeader(whichrow, masklist, verbose);
3805
3806    if (start < 0) start = 0;
3807    if (count < 0) count = nParam;
3808    int end = start + count;
3809    if (end > nParam) end = nParam;
3810    int paramidoffset = (resetparamid) ? (-start) : 0;
3811
3812    for (int i = start; i < end; ++i) {
3813      if (i > start) {
3814        oss << ",";
3815      }
3816      std::string sFix = ((fixed.size() > 0) && (fixed[i]) && verbose) ? "(fixed)" : "";
3817      oss << "  p" << (i+paramidoffset) << sFix << "= " << right << setw(13) << setprecision(6) << params[i];
3818    }
3819
3820    oss << endl;
3821    oss << formatBaselineParamsFooter(rms, nClipped, verbose);
3822
3823    return String(oss);
3824  }
3825
3826}
3827
3828  std::string Scantable::formatPiecewiseBaselineParams(const std::vector<int>& ranges, const std::vector<float>& params, const std::vector<bool>& fixed, float rms, int nClipped, const std::string& masklist, int whichrow, bool verbose) const
3829{
3830  int nOutParam = (int)(params.size());
3831  int nPiece = (int)(ranges.size()) - 1;
3832
3833  if (nOutParam < 1) {
3834    return("  Not fitted");
3835  } else if (nPiece < 0) {
3836    return formatBaselineParams(params, fixed, rms, nClipped, masklist, whichrow, verbose);
3837  } else if (nPiece < 1) {
3838    return("  Bad count of the piece edge info");
3839  } else if (nOutParam % nPiece != 0) {
3840    return("  Bad count of the output baseline parameters");
3841  } else {
3842
3843    int nParam = nOutParam / nPiece;
3844
3845    ostringstream oss;
3846    oss << formatBaselineParamsHeader(whichrow, masklist, verbose);
3847
3848    stringstream ss;
3849    ss << ranges[nPiece] << flush;
3850    int wRange = ss.str().size() * 2 + 5;
3851
3852    for (int i = 0; i < nPiece; ++i) {
3853      ss.str("");
3854      ss << "  [" << ranges[i] << "," << (ranges[i+1]-1) << "]";
3855      oss << left << setw(wRange) << ss.str();
3856      oss << formatBaselineParams(params, fixed, rms, 0, masklist, whichrow, false, i*nParam, nParam, true);
3857    }
3858
3859    oss << formatBaselineParamsFooter(rms, nClipped, verbose);
3860
3861    return String(oss);
3862  }
3863
3864}
3865
3866bool Scantable::hasSameNchanOverIFs()
3867{
3868  int nIF = nif(-1);
3869  int nCh;
3870  int totalPositiveNChan = 0;
3871  int nPositiveNChan = 0;
3872
3873  for (int i = 0; i < nIF; ++i) {
3874    nCh = nchan(i);
3875    if (nCh > 0) {
3876      totalPositiveNChan += nCh;
3877      nPositiveNChan++;
3878    }
3879  }
3880
3881  return (totalPositiveNChan == (nPositiveNChan * nchan(0)));
3882}
3883
3884std::string Scantable::getMaskRangeList(const std::vector<bool>& mask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, bool verbose)
3885{
3886  if (mask.size() <= 0) {
3887    throw(AipsError("The mask elements should be > 0"));
3888  }
3889  int IF = getIF(whichrow);
3890  if (mask.size() != (uInt)nchan(IF)) {
3891    throw(AipsError("Number of channels in scantable != number of mask elements"));
3892  }
3893
3894  if (verbose) {
3895    LogIO logOs(LogOrigin("Scantable", "getMaskRangeList()", WHERE));
3896    logOs << LogIO::WARN << "The current mask window unit is " << coordInfo;
3897    if (!hasSameNchan) {
3898      logOs << endl << "This mask is only valid for IF=" << IF;
3899    }
3900    logOs << LogIO::POST;
3901  }
3902
3903  std::vector<double> abcissa = getAbcissa(whichrow);
3904  std::vector<int> edge = getMaskEdgeIndices(mask);
3905
3906  ostringstream oss;
3907  oss.setf(ios::fixed);
3908  oss << setprecision(1) << "[";
3909  for (uInt i = 0; i < edge.size(); i+=2) {
3910    if (i > 0) oss << ",";
3911    oss << "[" << (float)abcissa[edge[i]] << "," << (float)abcissa[edge[i+1]] << "]";
3912  }
3913  oss << "]" << flush;
3914
3915  return String(oss);
3916}
3917
3918std::vector<int> Scantable::getMaskEdgeIndices(const std::vector<bool>& mask)
3919{
3920  if (mask.size() <= 0) {
3921    throw(AipsError("The mask elements should be > 0"));
3922  }
3923
3924  std::vector<int> out, startIndices, endIndices;
3925  int maskSize = mask.size();
3926
3927  startIndices.clear();
3928  endIndices.clear();
3929
3930  if (mask[0]) {
3931    startIndices.push_back(0);
3932  }
3933  for (int i = 1; i < maskSize; ++i) {
3934    if ((!mask[i-1]) && mask[i]) {
3935      startIndices.push_back(i);
3936    } else if (mask[i-1] && (!mask[i])) {
3937      endIndices.push_back(i-1);
3938    }
3939  }
3940  if (mask[maskSize-1]) {
3941    endIndices.push_back(maskSize-1);
3942  }
3943
3944  if (startIndices.size() != endIndices.size()) {
3945    throw(AipsError("Inconsistent Mask Size: bad data?"));
3946  }
3947  for (uInt i = 0; i < startIndices.size(); ++i) {
3948    if (startIndices[i] > endIndices[i]) {
3949      throw(AipsError("Mask start index > mask end index"));
3950    }
3951  }
3952
3953  out.clear();
3954  for (uInt i = 0; i < startIndices.size(); ++i) {
3955    out.push_back(startIndices[i]);
3956    out.push_back(endIndices[i]);
3957  }
3958
3959  return out;
3960}
3961
3962vector<float> Scantable::getTsysSpectrum( int whichrow ) const
3963{
3964  Vector<Float> tsys( tsysCol_(whichrow) ) ;
3965  vector<float> stlTsys ;
3966  tsys.tovector( stlTsys ) ;
3967  return stlTsys ;
3968}
3969
3970vector<uint> Scantable::getMoleculeIdColumnData() const
3971{
3972  Vector<uInt> molIds(mmolidCol_.getColumn());
3973  vector<uint> res;
3974  molIds.tovector(res);
3975  return res;
3976}
3977
3978void Scantable::setMoleculeIdColumnData(const std::vector<uint>& molids)
3979{
3980  Vector<uInt> molIds(molids);
3981  Vector<uInt> arr(mmolidCol_.getColumn());
3982  if ( molIds.nelements() != arr.nelements() )
3983    throw AipsError("The input data size must be the number of rows.");
3984  mmolidCol_.putColumn(molIds);
3985}
3986
3987
3988}
3989//namespace asap
Note: See TracBrowser for help on using the repository browser.