source: trunk/src/Scantable.cpp@ 2364

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

New Development: No

JIRA Issue: No (a bug fix related to CAS-3606)

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs: all SD unit and regression tests passed

Put in Release Notes: No

Module(s): asap.scantable and asap.asapmath

Description: spceified ifno parameter in some of the calls to scantable.nchan.


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