source: trunk/src/Scantable.cpp @ 2462

Last change on this file since 2462 was 2462, checked in by Kana Sugimoto, 12 years ago

New Development: No (a bug fix)

JIRA Issue: No

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs: sdsmooth unit tests (test07-09)

Put in Release Notes: No

Module(s):

Description: fixed a bug in Scantable::regridChannel.

The function now works properly for spectra with negative frequency increments.


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