source: trunk/src/Scantable.cpp@ 2434

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

New Development: No

JIRA Issue: Yes (CAS-2818)

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs: unit test: sdaverage[test900]

Put in Release Notes: No

Module(s):

Description: Higher precision regridding of frequency axis.

*An additional comment for r2431 (forgot to mention this)*
Scantable::regridChannel now regrids Tsys column if necessary, i.e.,
the number of Tsys channels are equal to that of spectra.


  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 112.2 KB
RevLine 
[805]1//
2// C++ Implementation: Scantable
3//
4// Description:
5//
6//
7// Author: Malte Marquarding <asap@atnf.csiro.au>, (C) 2005
8//
9// Copyright: See COPYING file that comes with this distribution
10//
11//
[206]12#include <map>
13
[2186]14#include <atnf/PKSIO/SrcType.h>
15
[125]16#include <casa/aips.h>
[2186]17#include <casa/iomanip.h>
[80]18#include <casa/iostream.h>
[2186]19#include <casa/OS/File.h>
[805]20#include <casa/OS/Path.h>
[80]21#include <casa/Arrays/Array.h>
[2186]22#include <casa/Arrays/ArrayAccessor.h>
23#include <casa/Arrays/ArrayLogical.h>
[80]24#include <casa/Arrays/ArrayMath.h>
25#include <casa/Arrays/MaskArrMath.h>
[2186]26#include <casa/Arrays/Slice.h>
[1325]27#include <casa/Arrays/Vector.h>
[455]28#include <casa/Arrays/VectorSTLIterator.h>
[418]29#include <casa/BasicMath/Math.h>
[504]30#include <casa/BasicSL/Constants.h>
[2186]31#include <casa/Containers/RecordField.h>
32#include <casa/Logging/LogIO.h>
[286]33#include <casa/Quanta/MVAngle.h>
[2186]34#include <casa/Quanta/MVTime.h>
[902]35#include <casa/Utilities/GenSort.h>
[2]36
[2186]37#include <coordinates/Coordinates/CoordinateUtil.h>
[2]38
[1325]39// needed to avoid error in .tcc
40#include <measures/Measures/MCDirection.h>
41//
42#include <measures/Measures/MDirection.h>
[2186]43#include <measures/Measures/MEpoch.h>
[80]44#include <measures/Measures/MFrequency.h>
[2186]45#include <measures/Measures/MeasRef.h>
46#include <measures/Measures/MeasTable.h>
47#include <measures/TableMeasures/ScalarMeasColumn.h>
48#include <measures/TableMeasures/TableMeasDesc.h>
[805]49#include <measures/TableMeasures/TableMeasRefDesc.h>
50#include <measures/TableMeasures/TableMeasValueDesc.h>
[2]51
[2186]52#include <tables/Tables/ArrColDesc.h>
53#include <tables/Tables/ExprNode.h>
54#include <tables/Tables/ScaColDesc.h>
55#include <tables/Tables/SetupNewTab.h>
56#include <tables/Tables/TableCopy.h>
57#include <tables/Tables/TableDesc.h>
58#include <tables/Tables/TableIter.h>
59#include <tables/Tables/TableParse.h>
60#include <tables/Tables/TableRecord.h>
61#include <tables/Tables/TableRow.h>
62#include <tables/Tables/TableVector.h>
63
64#include "MathUtils.h"
65#include "STAttr.h"
66#include "STLineFinder.h"
67#include "STPolCircular.h"
[896]68#include "STPolLinear.h"
[913]69#include "STPolStokes.h"
[2321]70#include "STUpgrade.h"
[2186]71#include "Scantable.h"
[2]72
[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
[2433]1887
[1819]1888void asap::Scantable::regridChannel( int nChan, double dnu )
1889{
1890 LogIO os( LogOrigin( "Scantable", "regridChannel()", WHERE ) ) ;
1891 os << "Regrid abcissa with channel number " << nChan << " and spectral resoultion " << dnu << "Hz." << LogIO::POST ;
1892 // assumed that all rows have same nChan
1893 Vector<Float> arr = specCol_( 0 ) ;
1894 int oldsize = arr.nelements() ;
1895
1896 // if oldsize == nChan, nothing to do
1897 if ( oldsize == nChan ) {
1898 os << "Specified channel number is same as current one. Nothing to do." << LogIO::POST ;
1899 return ;
1900 }
1901
1902 // if oldChan < nChan, unphysical operation
1903 if ( oldsize < nChan ) {
1904 os << "Unphysical operation. Nothing to do." << LogIO::POST ;
1905 return ;
1906 }
1907
[2433]1908 // change channel number for specCol_, flagCol_, and tsysCol_ (if necessary)
[1819]1909 vector<string> coordinfo = getCoordInfo() ;
1910 string oldinfo = coordinfo[0] ;
1911 coordinfo[0] = "Hz" ;
1912 setCoordInfo( coordinfo ) ;
1913 for ( int irow = 0 ; irow < nrow() ; irow++ ) {
1914 regridChannel( nChan, dnu, irow ) ;
1915 }
1916 coordinfo[0] = oldinfo ;
1917 setCoordInfo( coordinfo ) ;
1918
1919
1920 // NOTE: this method does not update metadata such as
1921 // FREQUENCIES subtable, nChan, Bandwidth, etc.
1922
1923 return ;
1924}
1925
1926void asap::Scantable::regridChannel( int nChan, double dnu, int irow )
1927{
1928 // logging
1929 //ofstream ofs( "average.log", std::ios::out | std::ios::app ) ;
1930 //ofs << "IFNO = " << getIF( irow ) << " irow = " << irow << endl ;
1931
1932 Vector<Float> oldspec = specCol_( irow ) ;
1933 Vector<uChar> oldflag = flagsCol_( irow ) ;
[2431]1934 Vector<Float> oldtsys = tsysCol_( irow ) ;
[1819]1935 Vector<Float> newspec( nChan, 0 ) ;
[2431]1936 //Vector<uChar> newflag( nChan, false ) ;
1937 Vector<uChar> newflag( nChan, true ) ;
1938 Vector<Float> newtsys ;
1939 bool regridTsys = false ;
1940 if (oldtsys.size() == oldspec.size()) {
1941 regridTsys = true ;
1942 newtsys.resize(nChan,false) ;
1943 newtsys = 0 ;
1944 }
[1819]1945
1946 // regrid
1947 vector<double> abcissa = getAbcissa( irow ) ;
1948 int oldsize = abcissa.size() ;
1949 double olddnu = abcissa[1] - abcissa[0] ;
1950 //int refChan = 0 ;
1951 //double frac = 0.0 ;
1952 //double wedge = 0.0 ;
1953 //double pile = 0.0 ;
1954 int ichan = 0 ;
1955 double wsum = 0.0 ;
[2433]1956 Vector<double> zi( nChan+1 ) ;
1957 Vector<double> yi( oldsize + 1 ) ;
[2133]1958 zi[0] = abcissa[0] - 0.5 * olddnu ;
[2431]1959 //zi[1] = zi[1] + dnu ;
1960 for ( int ii = 1 ; ii < nChan ; ii++ )
[2133]1961 zi[ii] = zi[0] + dnu * ii ;
1962 zi[nChan] = zi[nChan-1] + dnu ;
[1819]1963 yi[0] = abcissa[0] - 0.5 * olddnu ;
[2431]1964 //yi[1] = abcissa[1] + 0.5 * olddnu ;
1965 for ( int ii = 1 ; ii < oldsize ; ii++ )
1966 //yi[ii] = abcissa[ii-1] + olddnu ;
[2433]1967 yi[ii] = 0.5* (abcissa[ii-1] + abcissa[ii]) ;
1968 yi[oldsize] = abcissa[oldsize-1] \
1969 + 0.5 * (abcissa[oldsize-1] - abcissa[oldsize-2]) ;
[1819]1970 if ( dnu > 0.0 ) {
1971 for ( int ii = 0 ; ii < nChan ; ii++ ) {
1972 double zl = zi[ii] ;
1973 double zr = zi[ii+1] ;
1974 for ( int j = ichan ; j < oldsize ; j++ ) {
1975 double yl = yi[j] ;
1976 double yr = yi[j+1] ;
1977 if ( yl <= zl ) {
1978 if ( yr <= zl ) {
1979 continue ;
1980 }
1981 else if ( yr <= zr ) {
[2431]1982 if (!oldflag[j]) {
1983 newspec[ii] += oldspec[j] * ( yr - zl ) ;
1984 if (regridTsys) newtsys[ii] += oldtsys[j] * ( yr - zl ) ;
1985 wsum += ( yr - zl ) ;
1986 }
1987 //newflag[ii] = newflag[ii] || oldflag[j] ;
1988 newflag[ii] = newflag[ii] && oldflag[j] ;
[1819]1989 }
1990 else {
[2431]1991 if (!oldflag[j]) {
1992 newspec[ii] += oldspec[j] * dnu ;
1993 if (regridTsys) newtsys[ii] += oldtsys[j] * dnu ;
1994 wsum += dnu ;
1995 }
1996 //newflag[ii] = newflag[ii] || oldflag[j] ;
1997 newflag[ii] = newflag[ii] && oldflag[j] ;
[1819]1998 ichan = j ;
1999 break ;
2000 }
2001 }
2002 else if ( yl < zr ) {
2003 if ( yr <= zr ) {
[2431]2004 if (!oldflag[j]) {
2005 newspec[ii] += oldspec[j] * ( yr - yl ) ;
2006 if (regridTsys) newtsys[ii] += oldtsys[j] * ( yr - yl ) ;
[1819]2007 wsum += ( yr - yl ) ;
[2431]2008 }
2009 //newflag[ii] = newflag[ii] || oldflag[j] ;
2010 newflag[ii] = newflag[ii] && oldflag[j] ;
[1819]2011 }
2012 else {
[2431]2013 if (!oldflag[j]) {
2014 newspec[ii] += oldspec[j] * ( zr - yl ) ;
2015 if (regridTsys) newtsys[ii] += oldtsys[j] * ( zr - yl ) ;
2016 wsum += ( zr - yl ) ;
2017 }
2018 //newflag[ii] = newflag[ii] || oldflag[j] ;
2019 newflag[ii] = newflag[ii] && oldflag[j] ;
[1819]2020 ichan = j ;
2021 break ;
2022 }
2023 }
2024 else {
2025 ichan = j - 1 ;
2026 break ;
2027 }
2028 }
[2431]2029 if ( wsum != 0.0 ) {
[2133]2030 newspec[ii] /= wsum ;
[2431]2031 if (regridTsys) newtsys[ii] /= wsum ;
2032 }
[1819]2033 wsum = 0.0 ;
2034 }
2035 }
2036 else if ( dnu < 0.0 ) {
2037 for ( int ii = 0 ; ii < nChan ; ii++ ) {
2038 double zl = zi[ii] ;
2039 double zr = zi[ii+1] ;
2040 for ( int j = ichan ; j < oldsize ; j++ ) {
2041 double yl = yi[j] ;
2042 double yr = yi[j+1] ;
2043 if ( yl >= zl ) {
2044 if ( yr >= zl ) {
2045 continue ;
2046 }
2047 else if ( yr >= zr ) {
[2431]2048 if (!oldflag[j]) {
2049 newspec[ii] += oldspec[j] * abs( yr - zl ) ;
2050 if (regridTsys) newtsys[ii] += oldtsys[j] * abs( yr - zl ) ;
2051 wsum += abs( yr - zl ) ;
2052 }
2053 //newflag[ii] = newflag[ii] || oldflag[j] ;
2054 newflag[ii] = newflag[ii] && oldflag[j] ;
[1819]2055 }
2056 else {
[2431]2057 if (!oldflag[j]) {
2058 newspec[ii] += oldspec[j] * abs( dnu ) ;
2059 if (regridTsys) newtsys[ii] += oldtsys[j] * abs( dnu ) ;
2060 wsum += abs( dnu ) ;
2061 }
2062 //newflag[ii] = newflag[ii] || oldflag[j] ;
2063 newflag[ii] = newflag[ii] && oldflag[j] ;
[1819]2064 ichan = j ;
2065 break ;
2066 }
2067 }
2068 else if ( yl > zr ) {
2069 if ( yr >= zr ) {
[2431]2070 if (!oldflag[j]) {
2071 newspec[ii] += oldspec[j] * abs( yr - yl ) ;
2072 if (regridTsys) newtsys[ii] += oldtsys[j] * abs( yr - yl ) ;
2073 wsum += abs( yr - yl ) ;
2074 }
2075 //newflag[ii] = newflag[ii] || oldflag[j] ;
2076 newflag[ii] = newflag[ii] && oldflag[j] ;
[1819]2077 }
2078 else {
[2431]2079 if (!oldflag[j]) {
2080 newspec[ii] += oldspec[j] * abs( zr - yl ) ;
2081 if (regridTsys) newtsys[ii] += oldtsys[j] * abs( zr - yl ) ;
2082 wsum += abs( zr - yl ) ;
2083 }
2084 //newflag[ii] = newflag[ii] || oldflag[j] ;
2085 newflag[ii] = newflag[ii] && oldflag[j] ;
[1819]2086 ichan = j ;
2087 break ;
2088 }
2089 }
2090 else {
2091 ichan = j - 1 ;
2092 break ;
2093 }
2094 }
[2431]2095 if ( wsum != 0.0 ) {
[2133]2096 newspec[ii] /= wsum ;
[2431]2097 if (regridTsys) newtsys[ii] /= wsum ;
2098 }
[1819]2099 wsum = 0.0 ;
2100 }
2101 }
2102// * ichan = 0
2103// ***/
2104// //ofs << "olddnu = " << olddnu << ", dnu = " << dnu << endl ;
2105// pile += dnu ;
2106// wedge = olddnu * ( refChan + 1 ) ;
2107// while ( wedge < pile ) {
2108// newspec[0] += olddnu * oldspec[refChan] ;
2109// newflag[0] = newflag[0] || oldflag[refChan] ;
2110// //ofs << "channel " << refChan << " is included in new channel 0" << endl ;
2111// refChan++ ;
2112// wedge += olddnu ;
2113// wsum += olddnu ;
2114// //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
2115// }
2116// frac = ( wedge - pile ) / olddnu ;
2117// wsum += ( 1.0 - frac ) * olddnu ;
2118// newspec[0] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
2119// newflag[0] = newflag[0] || oldflag[refChan] ;
2120// //ofs << "channel " << refChan << " is partly included in new channel 0" << " with fraction of " << ( 1.0 - frac ) << endl ;
2121// //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
2122// newspec[0] /= wsum ;
2123// //ofs << "newspec[0] = " << newspec[0] << endl ;
2124// //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
2125
2126// /***
2127// * ichan = 1 - nChan-2
2128// ***/
2129// for ( int ichan = 1 ; ichan < nChan - 1 ; ichan++ ) {
2130// pile += dnu ;
2131// newspec[ichan] += frac * olddnu * oldspec[refChan] ;
2132// newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
2133// //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << frac << endl ;
2134// refChan++ ;
2135// wedge += olddnu ;
2136// wsum = frac * olddnu ;
2137// //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
2138// while ( wedge < pile ) {
2139// newspec[ichan] += olddnu * oldspec[refChan] ;
2140// newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
2141// //ofs << "channel " << refChan << " is included in new channel " << ichan << endl ;
2142// refChan++ ;
2143// wedge += olddnu ;
2144// wsum += olddnu ;
2145// //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
2146// }
2147// frac = ( wedge - pile ) / olddnu ;
2148// wsum += ( 1.0 - frac ) * olddnu ;
2149// newspec[ichan] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
2150// newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
2151// //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << ( 1.0 - frac ) << endl ;
2152// //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
2153// //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
2154// newspec[ichan] /= wsum ;
2155// //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << endl ;
2156// }
2157
2158// /***
2159// * ichan = nChan-1
2160// ***/
2161// // NOTE: Assumed that all spectra have the same bandwidth
2162// pile += dnu ;
2163// newspec[nChan-1] += frac * olddnu * oldspec[refChan] ;
2164// newflag[nChan-1] = newflag[nChan-1] || oldflag[refChan] ;
2165// //ofs << "channel " << refChan << " is partly included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
2166// refChan++ ;
2167// wedge += olddnu ;
2168// wsum = frac * olddnu ;
2169// //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
2170// for ( int jchan = refChan ; jchan < oldsize ; jchan++ ) {
2171// newspec[nChan-1] += olddnu * oldspec[jchan] ;
2172// newflag[nChan-1] = newflag[nChan-1] || oldflag[jchan] ;
2173// wsum += olddnu ;
2174// //ofs << "channel " << jchan << " is included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
2175// //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
2176// }
2177// //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
2178// //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
2179// newspec[nChan-1] /= wsum ;
2180// //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << endl ;
2181
2182// // ofs.close() ;
2183
[2032]2184 specCol_.put( irow, newspec ) ;
2185 flagsCol_.put( irow, newflag ) ;
[2431]2186 if (regridTsys) tsysCol_.put( irow, newtsys );
[1819]2187
2188 return ;
2189}
2190
[1730]2191std::vector<float> Scantable::getWeather(int whichrow) const
2192{
2193 std::vector<float> out(5);
2194 //Float temperature, pressure, humidity, windspeed, windaz;
2195 weatherTable_.getEntry(out[0], out[1], out[2], out[3], out[4],
2196 mweatheridCol_(uInt(whichrow)));
2197
2198
2199 return out;
[1391]2200}
[1730]2201
[2047]2202bool Scantable::getFlagtraFast(uInt whichrow)
[1907]2203{
2204 uChar flag;
2205 Vector<uChar> flags;
[2047]2206 flagsCol_.get(whichrow, flags);
[2012]2207 flag = flags[0];
[2047]2208 for (uInt i = 1; i < flags.size(); ++i) {
[2012]2209 flag &= flags[i];
2210 }
2211 return ((flag >> 7) == 1);
2212}
2213
[2277]2214void Scantable::polyBaseline(const std::vector<bool>& mask, int order, bool getResidual, const std::string& progressInfo, const bool outLogger, const std::string& blfile)
[2047]2215{
[2193]2216 try {
2217 ofstream ofs;
2218 String coordInfo = "";
2219 bool hasSameNchan = true;
2220 bool outTextFile = false;
[2047]2221
[2193]2222 if (blfile != "") {
2223 ofs.open(blfile.c_str(), ios::out | ios::app);
2224 if (ofs) outTextFile = true;
2225 }
[2047]2226
[2193]2227 if (outLogger || outTextFile) {
2228 coordInfo = getCoordInfo()[0];
2229 if (coordInfo == "") coordInfo = "channel";
2230 hasSameNchan = hasSameNchanOverIFs();
2231 }
[2047]2232
[2193]2233 Fitter fitter = Fitter();
2234 fitter.setExpression("poly", order);
2235 //fitter.setIterClipping(thresClip, nIterClip);
[2047]2236
[2193]2237 int nRow = nrow();
2238 std::vector<bool> chanMask;
2239 bool showProgress;
2240 int minNRow;
2241 parseProgressInfo(progressInfo, showProgress, minNRow);
[2047]2242
[2193]2243 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2244 chanMask = getCompositeChanMask(whichrow, mask);
2245 fitBaseline(chanMask, whichrow, fitter);
2246 setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
[2277]2247 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "polyBaseline()", fitter);
[2193]2248 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
2249 }
2250
2251 if (outTextFile) ofs.close();
2252
2253 } catch (...) {
2254 throw;
[2047]2255 }
2256}
2257
[2189]2258void 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]2259{
[2193]2260 try {
2261 ofstream ofs;
2262 String coordInfo = "";
2263 bool hasSameNchan = true;
2264 bool outTextFile = false;
[2047]2265
[2193]2266 if (blfile != "") {
2267 ofs.open(blfile.c_str(), ios::out | ios::app);
2268 if (ofs) outTextFile = true;
2269 }
[2047]2270
[2193]2271 if (outLogger || outTextFile) {
2272 coordInfo = getCoordInfo()[0];
2273 if (coordInfo == "") coordInfo = "channel";
2274 hasSameNchan = hasSameNchanOverIFs();
2275 }
[2047]2276
[2193]2277 Fitter fitter = Fitter();
2278 fitter.setExpression("poly", order);
2279 //fitter.setIterClipping(thresClip, nIterClip);
[2047]2280
[2193]2281 int nRow = nrow();
2282 std::vector<bool> chanMask;
2283 int minEdgeSize = getIFNos().size()*2;
2284 STLineFinder lineFinder = STLineFinder();
2285 lineFinder.setOptions(threshold, 3, chanAvgLimit);
[2047]2286
[2193]2287 bool showProgress;
2288 int minNRow;
2289 parseProgressInfo(progressInfo, showProgress, minNRow);
[2189]2290
[2193]2291 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
[2047]2292
[2193]2293 //-------------------------------------------------------
2294 //chanMask = getCompositeChanMask(whichrow, mask, edge, minEdgeSize, lineFinder);
2295 //-------------------------------------------------------
2296 int edgeSize = edge.size();
2297 std::vector<int> currentEdge;
2298 if (edgeSize >= 2) {
2299 int idx = 0;
2300 if (edgeSize > 2) {
2301 if (edgeSize < minEdgeSize) {
2302 throw(AipsError("Length of edge element info is less than that of IFs"));
2303 }
2304 idx = 2 * getIF(whichrow);
[2047]2305 }
[2193]2306 currentEdge.push_back(edge[idx]);
2307 currentEdge.push_back(edge[idx+1]);
2308 } else {
2309 throw(AipsError("Wrong length of edge element"));
[2047]2310 }
[2193]2311 lineFinder.setData(getSpectrum(whichrow));
2312 lineFinder.findLines(getCompositeChanMask(whichrow, mask), currentEdge, whichrow);
2313 chanMask = lineFinder.getMask();
2314 //-------------------------------------------------------
2315
2316 fitBaseline(chanMask, whichrow, fitter);
2317 setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
2318
2319 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "autoPolyBaseline()", fitter);
2320 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
[2047]2321 }
2322
[2193]2323 if (outTextFile) ofs.close();
[2047]2324
[2193]2325 } catch (...) {
2326 throw;
[2047]2327 }
2328}
2329
[2189]2330void 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]2331{
[2193]2332 try {
2333 ofstream ofs;
2334 String coordInfo = "";
2335 bool hasSameNchan = true;
2336 bool outTextFile = false;
[2012]2337
[2193]2338 if (blfile != "") {
2339 ofs.open(blfile.c_str(), ios::out | ios::app);
2340 if (ofs) outTextFile = true;
2341 }
[2012]2342
[2193]2343 if (outLogger || outTextFile) {
2344 coordInfo = getCoordInfo()[0];
2345 if (coordInfo == "") coordInfo = "channel";
2346 hasSameNchan = hasSameNchanOverIFs();
2347 }
[2012]2348
[2193]2349 //Fitter fitter = Fitter();
2350 //fitter.setExpression("cspline", nPiece);
2351 //fitter.setIterClipping(thresClip, nIterClip);
[2012]2352
[2193]2353 bool showProgress;
2354 int minNRow;
2355 parseProgressInfo(progressInfo, showProgress, minNRow);
[2012]2356
[2344]2357 int nRow = nrow();
2358 std::vector<bool> chanMask;
2359
2360 //--------------------------------
[2193]2361 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2362 chanMask = getCompositeChanMask(whichrow, mask);
2363 //fitBaseline(chanMask, whichrow, fitter);
2364 //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
[2344]2365 std::vector<int> pieceEdges(nPiece+1);
2366 std::vector<float> params(nPiece*4);
[2193]2367 int nClipped = 0;
2368 std::vector<float> res = doCubicSplineFitting(getSpectrum(whichrow), chanMask, nPiece, pieceEdges, params, nClipped, thresClip, nIterClip, getResidual);
2369 setSpectrum(res, whichrow);
2370 //
[2012]2371
[2193]2372 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "cubicSplineBaseline()", pieceEdges, params, nClipped);
2373 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
2374 }
[2344]2375 //--------------------------------
2376
[2193]2377 if (outTextFile) ofs.close();
2378
2379 } catch (...) {
2380 throw;
[2012]2381 }
2382}
2383
[2189]2384void 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]2385{
[2193]2386 try {
2387 ofstream ofs;
2388 String coordInfo = "";
2389 bool hasSameNchan = true;
2390 bool outTextFile = false;
[2012]2391
[2193]2392 if (blfile != "") {
2393 ofs.open(blfile.c_str(), ios::out | ios::app);
2394 if (ofs) outTextFile = true;
2395 }
[2012]2396
[2193]2397 if (outLogger || outTextFile) {
2398 coordInfo = getCoordInfo()[0];
2399 if (coordInfo == "") coordInfo = "channel";
2400 hasSameNchan = hasSameNchanOverIFs();
2401 }
[2012]2402
[2193]2403 //Fitter fitter = Fitter();
2404 //fitter.setExpression("cspline", nPiece);
2405 //fitter.setIterClipping(thresClip, nIterClip);
[2012]2406
[2193]2407 int nRow = nrow();
2408 std::vector<bool> chanMask;
2409 int minEdgeSize = getIFNos().size()*2;
2410 STLineFinder lineFinder = STLineFinder();
2411 lineFinder.setOptions(threshold, 3, chanAvgLimit);
[2012]2412
[2193]2413 bool showProgress;
2414 int minNRow;
2415 parseProgressInfo(progressInfo, showProgress, minNRow);
[2189]2416
[2193]2417 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
[2012]2418
[2193]2419 //-------------------------------------------------------
2420 //chanMask = getCompositeChanMask(whichrow, mask, edge, minEdgeSize, lineFinder);
2421 //-------------------------------------------------------
2422 int edgeSize = edge.size();
2423 std::vector<int> currentEdge;
2424 if (edgeSize >= 2) {
2425 int idx = 0;
2426 if (edgeSize > 2) {
2427 if (edgeSize < minEdgeSize) {
2428 throw(AipsError("Length of edge element info is less than that of IFs"));
2429 }
2430 idx = 2 * getIF(whichrow);
[2012]2431 }
[2193]2432 currentEdge.push_back(edge[idx]);
2433 currentEdge.push_back(edge[idx+1]);
2434 } else {
2435 throw(AipsError("Wrong length of edge element"));
[2012]2436 }
[2193]2437 lineFinder.setData(getSpectrum(whichrow));
2438 lineFinder.findLines(getCompositeChanMask(whichrow, mask), currentEdge, whichrow);
2439 chanMask = lineFinder.getMask();
2440 //-------------------------------------------------------
2441
2442
2443 //fitBaseline(chanMask, whichrow, fitter);
2444 //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
[2344]2445 std::vector<int> pieceEdges(nPiece+1);
2446 std::vector<float> params(nPiece*4);
[2193]2447 int nClipped = 0;
2448 std::vector<float> res = doCubicSplineFitting(getSpectrum(whichrow), chanMask, nPiece, pieceEdges, params, nClipped, thresClip, nIterClip, getResidual);
2449 setSpectrum(res, whichrow);
2450 //
2451
2452 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "autoCubicSplineBaseline()", pieceEdges, params, nClipped);
2453 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
[1907]2454 }
[2012]2455
[2193]2456 if (outTextFile) ofs.close();
[2012]2457
[2193]2458 } catch (...) {
2459 throw;
[2012]2460 }
[1730]2461}
[1907]2462
[2193]2463std::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]2464{
2465 if (data.size() != mask.size()) {
2466 throw(AipsError("data and mask sizes are not identical"));
2467 }
[2012]2468 if (nPiece < 1) {
[2094]2469 throw(AipsError("number of the sections must be one or more"));
[2012]2470 }
2471
2472 int nChan = data.size();
[2344]2473 std::vector<int> maskArray(nChan);
2474 std::vector<int> x(nChan);
2475 int j = 0;
[2012]2476 for (int i = 0; i < nChan; ++i) {
[2344]2477 maskArray[i] = mask[i] ? 1 : 0;
[2012]2478 if (mask[i]) {
[2344]2479 x[j] = i;
2480 j++;
[2012]2481 }
2482 }
[2344]2483 int initNData = j;
[2012]2484
[2193]2485 if (initNData < nPiece) {
2486 throw(AipsError("too few non-flagged channels"));
2487 }
[2081]2488
2489 int nElement = (int)(floor(floor((double)(initNData/nPiece))+0.5));
[2344]2490 std::vector<double> invEdge(nPiece-1);
2491 idxEdge[0] = x[0];
[2012]2492 for (int i = 1; i < nPiece; ++i) {
[2047]2493 int valX = x[nElement*i];
[2344]2494 idxEdge[i] = valX;
2495 invEdge[i-1] = 1.0/(double)valX;
[2012]2496 }
[2344]2497 idxEdge[nPiece] = x[initNData-1]+1;
[2064]2498
[2081]2499 int nData = initNData;
2500 int nDOF = nPiece + 3; //number of parameters to solve, namely, 4+(nPiece-1).
2501
[2344]2502 std::vector<double> x1(nChan), x2(nChan), x3(nChan);
2503 std::vector<double> z1(nChan), x1z1(nChan), x2z1(nChan), x3z1(nChan);
2504 std::vector<double> r1(nChan), residual(nChan);
[2012]2505 for (int i = 0; i < nChan; ++i) {
[2064]2506 double di = (double)i;
2507 double dD = (double)data[i];
[2344]2508 x1[i] = di;
2509 x2[i] = di*di;
2510 x3[i] = di*di*di;
2511 z1[i] = dD;
2512 x1z1[i] = dD*di;
2513 x2z1[i] = dD*di*di;
2514 x3z1[i] = dD*di*di*di;
2515 r1[i] = 0.0;
2516 residual[i] = 0.0;
[2012]2517 }
2518
2519 for (int nClip = 0; nClip < nIterClip+1; ++nClip) {
[2064]2520 // xMatrix : horizontal concatenation of
2521 // the least-sq. matrix (left) and an
2522 // identity matrix (right).
2523 // the right part is used to calculate the inverse matrix of the left part.
[2012]2524 double xMatrix[nDOF][2*nDOF];
2525 double zMatrix[nDOF];
2526 for (int i = 0; i < nDOF; ++i) {
2527 for (int j = 0; j < 2*nDOF; ++j) {
2528 xMatrix[i][j] = 0.0;
2529 }
2530 xMatrix[i][nDOF+i] = 1.0;
2531 zMatrix[i] = 0.0;
2532 }
2533
2534 for (int n = 0; n < nPiece; ++n) {
[2193]2535 int nUseDataInPiece = 0;
[2064]2536 for (int i = idxEdge[n]; i < idxEdge[n+1]; ++i) {
2537
[2012]2538 if (maskArray[i] == 0) continue;
[2064]2539
[2012]2540 xMatrix[0][0] += 1.0;
[2064]2541 xMatrix[0][1] += x1[i];
2542 xMatrix[0][2] += x2[i];
2543 xMatrix[0][3] += x3[i];
2544 xMatrix[1][1] += x2[i];
2545 xMatrix[1][2] += x3[i];
2546 xMatrix[1][3] += x2[i]*x2[i];
2547 xMatrix[2][2] += x2[i]*x2[i];
2548 xMatrix[2][3] += x3[i]*x2[i];
2549 xMatrix[3][3] += x3[i]*x3[i];
[2012]2550 zMatrix[0] += z1[i];
[2064]2551 zMatrix[1] += x1z1[i];
2552 zMatrix[2] += x2z1[i];
2553 zMatrix[3] += x3z1[i];
2554
[2012]2555 for (int j = 0; j < n; ++j) {
[2064]2556 double q = 1.0 - x1[i]*invEdge[j];
[2012]2557 q = q*q*q;
2558 xMatrix[0][j+4] += q;
[2064]2559 xMatrix[1][j+4] += q*x1[i];
2560 xMatrix[2][j+4] += q*x2[i];
2561 xMatrix[3][j+4] += q*x3[i];
[2012]2562 for (int k = 0; k < j; ++k) {
[2064]2563 double r = 1.0 - x1[i]*invEdge[k];
[2012]2564 r = r*r*r;
2565 xMatrix[k+4][j+4] += r*q;
2566 }
2567 xMatrix[j+4][j+4] += q*q;
2568 zMatrix[j+4] += q*z1[i];
2569 }
[2064]2570
[2193]2571 nUseDataInPiece++;
[2012]2572 }
[2193]2573
2574 if (nUseDataInPiece < 1) {
2575 std::vector<string> suffixOfPieceNumber(4);
2576 suffixOfPieceNumber[0] = "th";
2577 suffixOfPieceNumber[1] = "st";
2578 suffixOfPieceNumber[2] = "nd";
2579 suffixOfPieceNumber[3] = "rd";
2580 int idxNoDataPiece = (n % 10 <= 3) ? n : 0;
2581 ostringstream oss;
2582 oss << "all channels clipped or masked in " << n << suffixOfPieceNumber[idxNoDataPiece];
2583 oss << " piece of the spectrum. can't execute fitting anymore.";
2584 throw(AipsError(String(oss)));
2585 }
[2012]2586 }
2587
2588 for (int i = 0; i < nDOF; ++i) {
2589 for (int j = 0; j < i; ++j) {
2590 xMatrix[i][j] = xMatrix[j][i];
2591 }
2592 }
2593
[2344]2594 std::vector<double> invDiag(nDOF);
[2012]2595 for (int i = 0; i < nDOF; ++i) {
[2344]2596 invDiag[i] = 1.0/xMatrix[i][i];
[2012]2597 for (int j = 0; j < nDOF; ++j) {
2598 xMatrix[i][j] *= invDiag[i];
2599 }
2600 }
2601
2602 for (int k = 0; k < nDOF; ++k) {
2603 for (int i = 0; i < nDOF; ++i) {
2604 if (i != k) {
2605 double factor1 = xMatrix[k][k];
2606 double factor2 = xMatrix[i][k];
2607 for (int j = k; j < 2*nDOF; ++j) {
2608 xMatrix[i][j] *= factor1;
2609 xMatrix[i][j] -= xMatrix[k][j]*factor2;
2610 xMatrix[i][j] /= factor1;
2611 }
2612 }
2613 }
2614 double xDiag = xMatrix[k][k];
2615 for (int j = k; j < 2*nDOF; ++j) {
2616 xMatrix[k][j] /= xDiag;
2617 }
2618 }
2619
2620 for (int i = 0; i < nDOF; ++i) {
2621 for (int j = 0; j < nDOF; ++j) {
2622 xMatrix[i][nDOF+j] *= invDiag[j];
2623 }
2624 }
2625 //compute a vector y which consists of the coefficients of the best-fit spline curves
2626 //(a0,a1,a2,a3(,b3,c3,...)), namely, the ones for the leftmost piece and the ones of
2627 //cubic terms for the other pieces (in case nPiece>1).
[2344]2628 std::vector<double> y(nDOF);
[2012]2629 for (int i = 0; i < nDOF; ++i) {
[2344]2630 y[i] = 0.0;
[2012]2631 for (int j = 0; j < nDOF; ++j) {
2632 y[i] += xMatrix[i][nDOF+j]*zMatrix[j];
2633 }
2634 }
2635
2636 double a0 = y[0];
2637 double a1 = y[1];
2638 double a2 = y[2];
2639 double a3 = y[3];
2640
[2344]2641 int j = 0;
[2012]2642 for (int n = 0; n < nPiece; ++n) {
[2064]2643 for (int i = idxEdge[n]; i < idxEdge[n+1]; ++i) {
2644 r1[i] = a0 + a1*x1[i] + a2*x2[i] + a3*x3[i];
[2012]2645 }
[2344]2646 params[j] = a0;
2647 params[j+1] = a1;
2648 params[j+2] = a2;
2649 params[j+3] = a3;
2650 j += 4;
[2012]2651
2652 if (n == nPiece-1) break;
2653
2654 double d = y[4+n];
[2064]2655 double iE = invEdge[n];
2656 a0 += d;
2657 a1 -= 3.0*d*iE;
2658 a2 += 3.0*d*iE*iE;
2659 a3 -= d*iE*iE*iE;
[2012]2660 }
2661
[2344]2662 //subtract constant value for masked regions at the edge of spectrum
2663 if (idxEdge[0] > 0) {
2664 int n = idxEdge[0];
2665 for (int i = 0; i < idxEdge[0]; ++i) {
2666 //--cubic extrapolate--
2667 //r1[i] = params[0] + params[1]*x1[i] + params[2]*x2[i] + params[3]*x3[i];
2668 //--linear extrapolate--
2669 //r1[i] = (r1[n+1] - r1[n])/(x1[n+1] - x1[n])*(x1[i] - x1[n]) + r1[n];
2670 //--constant--
2671 r1[i] = r1[n];
2672 }
2673 }
2674 if (idxEdge[nPiece] < nChan) {
2675 int n = idxEdge[nPiece]-1;
2676 for (int i = idxEdge[nPiece]; i < nChan; ++i) {
2677 //--cubic extrapolate--
2678 //int m = 4*(nPiece-1);
2679 //r1[i] = params[m] + params[m+1]*x1[i] + params[m+2]*x2[i] + params[m+3]*x3[i];
2680 //--linear extrapolate--
2681 //r1[i] = (r1[n-1] - r1[n])/(x1[n-1] - x1[n])*(x1[i] - x1[n]) + r1[n];
2682 //--constant--
2683 r1[i] = r1[n];
2684 }
2685 }
2686
2687 for (int i = 0; i < nChan; ++i) {
2688 residual[i] = z1[i] - r1[i];
2689 }
2690
[2012]2691 if ((nClip == nIterClip) || (thresClip <= 0.0)) {
2692 break;
2693 } else {
2694 double stdDev = 0.0;
2695 for (int i = 0; i < nChan; ++i) {
[2081]2696 stdDev += residual[i]*residual[i]*(double)maskArray[i];
[2012]2697 }
2698 stdDev = sqrt(stdDev/(double)nData);
2699
2700 double thres = stdDev * thresClip;
2701 int newNData = 0;
2702 for (int i = 0; i < nChan; ++i) {
[2081]2703 if (abs(residual[i]) >= thres) {
[2012]2704 maskArray[i] = 0;
2705 }
2706 if (maskArray[i] > 0) {
2707 newNData++;
2708 }
2709 }
[2081]2710 if (newNData == nData) {
[2064]2711 break; //no more flag to add. iteration stops.
[2012]2712 } else {
[2081]2713 nData = newNData;
[2012]2714 }
2715 }
2716 }
2717
[2193]2718 nClipped = initNData - nData;
2719
[2344]2720 std::vector<float> result(nChan);
[2058]2721 if (getResidual) {
2722 for (int i = 0; i < nChan; ++i) {
[2344]2723 result[i] = (float)residual[i];
[2058]2724 }
2725 } else {
2726 for (int i = 0; i < nChan; ++i) {
[2344]2727 result[i] = (float)r1[i];
[2058]2728 }
[2012]2729 }
2730
[2058]2731 return result;
[2012]2732}
2733
[2344]2734void 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]2735{
[2186]2736 nWaves.clear();
2737
2738 if (applyFFT) {
2739 string fftThAttr;
2740 float fftThSigma;
2741 int fftThTop;
2742 parseThresholdExpression(fftThresh, fftThAttr, fftThSigma, fftThTop);
2743 doSelectWaveNumbers(whichrow, chanMask, fftMethod, fftThSigma, fftThTop, fftThAttr, nWaves);
2744 }
2745
[2411]2746 addAuxWaveNumbers(whichrow, addNWaves, rejectNWaves, nWaves);
[2186]2747}
2748
2749void Scantable::parseThresholdExpression(const std::string& fftThresh, std::string& fftThAttr, float& fftThSigma, int& fftThTop)
2750{
2751 uInt idxSigma = fftThresh.find("sigma");
2752 uInt idxTop = fftThresh.find("top");
2753
2754 if (idxSigma == fftThresh.size() - 5) {
2755 std::istringstream is(fftThresh.substr(0, fftThresh.size() - 5));
2756 is >> fftThSigma;
2757 fftThAttr = "sigma";
2758 } else if (idxTop == 0) {
2759 std::istringstream is(fftThresh.substr(3));
2760 is >> fftThTop;
2761 fftThAttr = "top";
2762 } else {
2763 bool isNumber = true;
2764 for (uInt i = 0; i < fftThresh.size()-1; ++i) {
2765 char ch = (fftThresh.substr(i, 1).c_str())[0];
2766 if (!(isdigit(ch) || (fftThresh.substr(i, 1) == "."))) {
2767 isNumber = false;
2768 break;
2769 }
2770 }
2771 if (isNumber) {
2772 std::istringstream is(fftThresh);
2773 is >> fftThSigma;
2774 fftThAttr = "sigma";
2775 } else {
2776 throw(AipsError("fftthresh has a wrong value"));
2777 }
2778 }
2779}
2780
2781void 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)
2782{
2783 std::vector<float> fspec;
2784 if (fftMethod == "fft") {
2785 fspec = execFFT(whichrow, chanMask, false, true);
2786 //} else if (fftMethod == "lsp") {
2787 // fspec = lombScarglePeriodogram(whichrow);
2788 }
2789
2790 if (fftThAttr == "sigma") {
2791 float mean = 0.0;
2792 float mean2 = 0.0;
2793 for (uInt i = 0; i < fspec.size(); ++i) {
2794 mean += fspec[i];
2795 mean2 += fspec[i]*fspec[i];
2796 }
2797 mean /= float(fspec.size());
2798 mean2 /= float(fspec.size());
2799 float thres = mean + fftThSigma * float(sqrt(mean2 - mean*mean));
2800
2801 for (uInt i = 0; i < fspec.size(); ++i) {
2802 if (fspec[i] >= thres) {
2803 nWaves.push_back(i);
2804 }
2805 }
2806
2807 } else if (fftThAttr == "top") {
2808 for (int i = 0; i < fftThTop; ++i) {
2809 float max = 0.0;
2810 int maxIdx = 0;
2811 for (uInt j = 0; j < fspec.size(); ++j) {
2812 if (fspec[j] > max) {
2813 max = fspec[j];
2814 maxIdx = j;
2815 }
2816 }
2817 nWaves.push_back(maxIdx);
2818 fspec[maxIdx] = 0.0;
2819 }
2820
2821 }
2822
2823 if (nWaves.size() > 1) {
2824 sort(nWaves.begin(), nWaves.end());
2825 }
2826}
2827
[2411]2828void Scantable::addAuxWaveNumbers(const int whichrow, const std::vector<int>& addNWaves, const std::vector<int>& rejectNWaves, std::vector<int>& nWaves)
[2186]2829{
[2411]2830 std::vector<int> tempAddNWaves, tempRejectNWaves;
[2186]2831 for (uInt i = 0; i < addNWaves.size(); ++i) {
[2411]2832 tempAddNWaves.push_back(addNWaves[i]);
2833 }
2834 if ((tempAddNWaves.size() == 2) && (tempAddNWaves[1] == -999)) {
2835 setWaveNumberListUptoNyquistFreq(whichrow, tempAddNWaves);
2836 }
2837
2838 for (uInt i = 0; i < rejectNWaves.size(); ++i) {
2839 tempRejectNWaves.push_back(rejectNWaves[i]);
2840 }
2841 if ((tempRejectNWaves.size() == 2) && (tempRejectNWaves[1] == -999)) {
2842 setWaveNumberListUptoNyquistFreq(whichrow, tempRejectNWaves);
2843 }
2844
2845 for (uInt i = 0; i < tempAddNWaves.size(); ++i) {
[2186]2846 bool found = false;
2847 for (uInt j = 0; j < nWaves.size(); ++j) {
[2411]2848 if (nWaves[j] == tempAddNWaves[i]) {
[2186]2849 found = true;
2850 break;
2851 }
2852 }
[2411]2853 if (!found) nWaves.push_back(tempAddNWaves[i]);
[2186]2854 }
2855
[2411]2856 for (uInt i = 0; i < tempRejectNWaves.size(); ++i) {
[2186]2857 for (std::vector<int>::iterator j = nWaves.begin(); j != nWaves.end(); ) {
[2411]2858 if (*j == tempRejectNWaves[i]) {
[2186]2859 j = nWaves.erase(j);
2860 } else {
2861 ++j;
2862 }
2863 }
2864 }
2865
2866 if (nWaves.size() > 1) {
2867 sort(nWaves.begin(), nWaves.end());
2868 unique(nWaves.begin(), nWaves.end());
2869 }
2870}
2871
[2411]2872void Scantable::setWaveNumberListUptoNyquistFreq(const int whichrow, std::vector<int>& nWaves)
2873{
2874 if ((nWaves.size() == 2)&&(nWaves[1] == -999)) {
2875 int val = nWaves[0];
2876 int nyquistFreq = nchan(getIF(whichrow))/2+1;
2877 nWaves.clear();
2878 if (val > nyquistFreq) { // for safety, at least nWaves contains a constant; CAS-3759
2879 nWaves.push_back(0);
2880 }
2881 while (val <= nyquistFreq) {
2882 nWaves.push_back(val);
2883 val++;
2884 }
2885 }
2886}
2887
[2189]2888void 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]2889{
[2193]2890 try {
2891 ofstream ofs;
2892 String coordInfo = "";
2893 bool hasSameNchan = true;
2894 bool outTextFile = false;
[2012]2895
[2193]2896 if (blfile != "") {
2897 ofs.open(blfile.c_str(), ios::out | ios::app);
2898 if (ofs) outTextFile = true;
2899 }
[2012]2900
[2193]2901 if (outLogger || outTextFile) {
2902 coordInfo = getCoordInfo()[0];
2903 if (coordInfo == "") coordInfo = "channel";
2904 hasSameNchan = hasSameNchanOverIFs();
2905 }
[2012]2906
[2193]2907 //Fitter fitter = Fitter();
2908 //fitter.setExpression("sinusoid", nWaves);
2909 //fitter.setIterClipping(thresClip, nIterClip);
[2012]2910
[2193]2911 int nRow = nrow();
2912 std::vector<bool> chanMask;
2913 std::vector<int> nWaves;
[2012]2914
[2193]2915 bool showProgress;
2916 int minNRow;
2917 parseProgressInfo(progressInfo, showProgress, minNRow);
[2189]2918
[2193]2919 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2920 chanMask = getCompositeChanMask(whichrow, mask);
2921 selectWaveNumbers(whichrow, chanMask, applyFFT, fftMethod, fftThresh, addNWaves, rejectNWaves, nWaves);
[2186]2922
[2193]2923 //FOR DEBUGGING------------
[2411]2924 /*
[2193]2925 if (whichrow < 0) {// == nRow -1) {
2926 cout << "+++ i=" << setw(3) << whichrow << ", IF=" << setw(2) << getIF(whichrow);
2927 if (applyFFT) {
[2186]2928 cout << "[ ";
2929 for (uInt j = 0; j < nWaves.size(); ++j) {
2930 cout << nWaves[j] << ", ";
2931 }
2932 cout << " ] " << endl;
[2193]2933 }
2934 cout << flush;
[2186]2935 }
[2411]2936 */
[2193]2937 //-------------------------
2938
2939 //fitBaseline(chanMask, whichrow, fitter);
2940 //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
2941 std::vector<float> params;
2942 int nClipped = 0;
2943 std::vector<float> res = doSinusoidFitting(getSpectrum(whichrow), chanMask, nWaves, params, nClipped, thresClip, nIterClip, getResidual);
2944 setSpectrum(res, whichrow);
2945 //
2946
2947 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "sinusoidBaseline()", params, nClipped);
2948 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
[2186]2949 }
2950
[2193]2951 if (outTextFile) ofs.close();
[2012]2952
[2193]2953 } catch (...) {
2954 throw;
[1931]2955 }
[1907]2956}
2957
[2189]2958void 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]2959{
[2193]2960 try {
2961 ofstream ofs;
2962 String coordInfo = "";
2963 bool hasSameNchan = true;
2964 bool outTextFile = false;
[2012]2965
[2193]2966 if (blfile != "") {
2967 ofs.open(blfile.c_str(), ios::out | ios::app);
2968 if (ofs) outTextFile = true;
2969 }
[2012]2970
[2193]2971 if (outLogger || outTextFile) {
2972 coordInfo = getCoordInfo()[0];
2973 if (coordInfo == "") coordInfo = "channel";
2974 hasSameNchan = hasSameNchanOverIFs();
2975 }
[2012]2976
[2193]2977 //Fitter fitter = Fitter();
2978 //fitter.setExpression("sinusoid", nWaves);
2979 //fitter.setIterClipping(thresClip, nIterClip);
[2012]2980
[2193]2981 int nRow = nrow();
2982 std::vector<bool> chanMask;
2983 std::vector<int> nWaves;
[2186]2984
[2193]2985 int minEdgeSize = getIFNos().size()*2;
2986 STLineFinder lineFinder = STLineFinder();
2987 lineFinder.setOptions(threshold, 3, chanAvgLimit);
[2012]2988
[2193]2989 bool showProgress;
2990 int minNRow;
2991 parseProgressInfo(progressInfo, showProgress, minNRow);
[2189]2992
[2193]2993 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
[2012]2994
[2193]2995 //-------------------------------------------------------
2996 //chanMask = getCompositeChanMask(whichrow, mask, edge, minEdgeSize, lineFinder);
2997 //-------------------------------------------------------
2998 int edgeSize = edge.size();
2999 std::vector<int> currentEdge;
3000 if (edgeSize >= 2) {
3001 int idx = 0;
3002 if (edgeSize > 2) {
3003 if (edgeSize < minEdgeSize) {
3004 throw(AipsError("Length of edge element info is less than that of IFs"));
3005 }
3006 idx = 2 * getIF(whichrow);
[2012]3007 }
[2193]3008 currentEdge.push_back(edge[idx]);
3009 currentEdge.push_back(edge[idx+1]);
3010 } else {
3011 throw(AipsError("Wrong length of edge element"));
[2012]3012 }
[2193]3013 lineFinder.setData(getSpectrum(whichrow));
3014 lineFinder.findLines(getCompositeChanMask(whichrow, mask), currentEdge, whichrow);
3015 chanMask = lineFinder.getMask();
3016 //-------------------------------------------------------
3017
3018 selectWaveNumbers(whichrow, chanMask, applyFFT, fftMethod, fftThresh, addNWaves, rejectNWaves, nWaves);
3019
3020 //fitBaseline(chanMask, whichrow, fitter);
3021 //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
3022 std::vector<float> params;
3023 int nClipped = 0;
3024 std::vector<float> res = doSinusoidFitting(getSpectrum(whichrow), chanMask, nWaves, params, nClipped, thresClip, nIterClip, getResidual);
3025 setSpectrum(res, whichrow);
3026 //
3027
3028 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "autoSinusoidBaseline()", params, nClipped);
3029 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
[2012]3030 }
3031
[2193]3032 if (outTextFile) ofs.close();
[2012]3033
[2193]3034 } catch (...) {
3035 throw;
[2047]3036 }
3037}
3038
[2193]3039std::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]3040{
[2047]3041 if (data.size() != mask.size()) {
[2081]3042 throw(AipsError("data and mask sizes are not identical"));
[2047]3043 }
[2081]3044 if (data.size() < 2) {
3045 throw(AipsError("data size is too short"));
3046 }
3047 if (waveNumbers.size() == 0) {
[2186]3048 throw(AipsError("no wave numbers given"));
[2081]3049 }
3050 std::vector<int> nWaves; // sorted and uniqued array of wave numbers
3051 nWaves.reserve(waveNumbers.size());
3052 copy(waveNumbers.begin(), waveNumbers.end(), back_inserter(nWaves));
3053 sort(nWaves.begin(), nWaves.end());
3054 std::vector<int>::iterator end_it = unique(nWaves.begin(), nWaves.end());
3055 nWaves.erase(end_it, nWaves.end());
3056
3057 int minNWaves = nWaves[0];
3058 if (minNWaves < 0) {
[2058]3059 throw(AipsError("wave number must be positive or zero (i.e. constant)"));
3060 }
[2081]3061 bool hasConstantTerm = (minNWaves == 0);
[2047]3062
3063 int nChan = data.size();
3064 std::vector<int> maskArray;
3065 std::vector<int> x;
3066 for (int i = 0; i < nChan; ++i) {
3067 maskArray.push_back(mask[i] ? 1 : 0);
3068 if (mask[i]) {
3069 x.push_back(i);
3070 }
3071 }
3072
[2081]3073 int initNData = x.size();
[2047]3074
[2081]3075 int nData = initNData;
3076 int nDOF = nWaves.size() * 2 - (hasConstantTerm ? 1 : 0); //number of parameters to solve.
3077
3078 const double PI = 6.0 * asin(0.5); // PI (= 3.141592653...)
[2186]3079 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]3080
3081 // xArray : contains elemental values for computing the least-square matrix.
3082 // xArray.size() is nDOF and xArray[*].size() is nChan.
3083 // Each xArray element are as follows:
3084 // xArray[0] = {1.0, 1.0, 1.0, ..., 1.0},
3085 // xArray[2n-1] = {sin(nPI/L*x[0]), sin(nPI/L*x[1]), ..., sin(nPI/L*x[nChan])},
3086 // xArray[2n] = {cos(nPI/L*x[0]), cos(nPI/L*x[1]), ..., cos(nPI/L*x[nChan])},
3087 // where (1 <= n <= nMaxWavesInSW),
3088 // or,
3089 // xArray[2n-1] = {sin(wn[n]PI/L*x[0]), sin(wn[n]PI/L*x[1]), ..., sin(wn[n]PI/L*x[nChan])},
3090 // xArray[2n] = {cos(wn[n]PI/L*x[0]), cos(wn[n]PI/L*x[1]), ..., cos(wn[n]PI/L*x[nChan])},
3091 // where wn[n] denotes waveNumbers[n] (1 <= n <= waveNumbers.size()).
3092 std::vector<std::vector<double> > xArray;
3093 if (hasConstantTerm) {
3094 std::vector<double> xu;
3095 for (int j = 0; j < nChan; ++j) {
3096 xu.push_back(1.0);
3097 }
3098 xArray.push_back(xu);
3099 }
3100 for (uInt i = (hasConstantTerm ? 1 : 0); i < nWaves.size(); ++i) {
3101 double xFactor = baseXFactor*(double)nWaves[i];
3102 std::vector<double> xs, xc;
3103 xs.clear();
3104 xc.clear();
3105 for (int j = 0; j < nChan; ++j) {
3106 xs.push_back(sin(xFactor*(double)j));
3107 xc.push_back(cos(xFactor*(double)j));
3108 }
3109 xArray.push_back(xs);
3110 xArray.push_back(xc);
3111 }
3112
3113 std::vector<double> z1, r1, residual;
[2047]3114 for (int i = 0; i < nChan; ++i) {
[2081]3115 z1.push_back((double)data[i]);
[2047]3116 r1.push_back(0.0);
[2081]3117 residual.push_back(0.0);
[2047]3118 }
3119
3120 for (int nClip = 0; nClip < nIterClip+1; ++nClip) {
[2081]3121 // xMatrix : horizontal concatenation of
3122 // the least-sq. matrix (left) and an
3123 // identity matrix (right).
3124 // the right part is used to calculate the inverse matrix of the left part.
[2047]3125 double xMatrix[nDOF][2*nDOF];
3126 double zMatrix[nDOF];
3127 for (int i = 0; i < nDOF; ++i) {
3128 for (int j = 0; j < 2*nDOF; ++j) {
3129 xMatrix[i][j] = 0.0;
[2012]3130 }
[2047]3131 xMatrix[i][nDOF+i] = 1.0;
3132 zMatrix[i] = 0.0;
3133 }
3134
[2193]3135 int nUseData = 0;
[2081]3136 for (int k = 0; k < nChan; ++k) {
3137 if (maskArray[k] == 0) continue;
3138
3139 for (int i = 0; i < nDOF; ++i) {
3140 for (int j = i; j < nDOF; ++j) {
3141 xMatrix[i][j] += xArray[i][k] * xArray[j][k];
3142 }
3143 zMatrix[i] += z1[k] * xArray[i][k];
3144 }
[2193]3145
3146 nUseData++;
[2047]3147 }
3148
[2193]3149 if (nUseData < 1) {
3150 throw(AipsError("all channels clipped or masked. can't execute fitting anymore."));
3151 }
3152
[2047]3153 for (int i = 0; i < nDOF; ++i) {
3154 for (int j = 0; j < i; ++j) {
3155 xMatrix[i][j] = xMatrix[j][i];
[2012]3156 }
3157 }
3158
[2047]3159 std::vector<double> invDiag;
3160 for (int i = 0; i < nDOF; ++i) {
3161 invDiag.push_back(1.0/xMatrix[i][i]);
3162 for (int j = 0; j < nDOF; ++j) {
3163 xMatrix[i][j] *= invDiag[i];
3164 }
3165 }
3166
3167 for (int k = 0; k < nDOF; ++k) {
3168 for (int i = 0; i < nDOF; ++i) {
3169 if (i != k) {
3170 double factor1 = xMatrix[k][k];
3171 double factor2 = xMatrix[i][k];
3172 for (int j = k; j < 2*nDOF; ++j) {
3173 xMatrix[i][j] *= factor1;
3174 xMatrix[i][j] -= xMatrix[k][j]*factor2;
3175 xMatrix[i][j] /= factor1;
3176 }
3177 }
3178 }
3179 double xDiag = xMatrix[k][k];
3180 for (int j = k; j < 2*nDOF; ++j) {
3181 xMatrix[k][j] /= xDiag;
3182 }
3183 }
3184
3185 for (int i = 0; i < nDOF; ++i) {
3186 for (int j = 0; j < nDOF; ++j) {
3187 xMatrix[i][nDOF+j] *= invDiag[j];
3188 }
3189 }
3190 //compute a vector y which consists of the coefficients of the sinusoids forming the
[2081]3191 //best-fit curves (a0,s1,c1,s2,c2,...), where a0 is constant and s* and c* are of sine
3192 //and cosine functions, respectively.
[2047]3193 std::vector<double> y;
[2081]3194 params.clear();
[2047]3195 for (int i = 0; i < nDOF; ++i) {
3196 y.push_back(0.0);
3197 for (int j = 0; j < nDOF; ++j) {
3198 y[i] += xMatrix[i][nDOF+j]*zMatrix[j];
3199 }
[2081]3200 params.push_back(y[i]);
[2047]3201 }
3202
3203 for (int i = 0; i < nChan; ++i) {
[2081]3204 r1[i] = y[0];
3205 for (int j = 1; j < nDOF; ++j) {
3206 r1[i] += y[j]*xArray[j][i];
3207 }
3208 residual[i] = z1[i] - r1[i];
[2047]3209 }
3210
3211 if ((nClip == nIterClip) || (thresClip <= 0.0)) {
3212 break;
3213 } else {
3214 double stdDev = 0.0;
3215 for (int i = 0; i < nChan; ++i) {
[2081]3216 stdDev += residual[i]*residual[i]*(double)maskArray[i];
[2047]3217 }
3218 stdDev = sqrt(stdDev/(double)nData);
3219
3220 double thres = stdDev * thresClip;
3221 int newNData = 0;
3222 for (int i = 0; i < nChan; ++i) {
[2081]3223 if (abs(residual[i]) >= thres) {
[2047]3224 maskArray[i] = 0;
3225 }
3226 if (maskArray[i] > 0) {
3227 newNData++;
3228 }
3229 }
[2081]3230 if (newNData == nData) {
3231 break; //no more flag to add. iteration stops.
[2047]3232 } else {
[2081]3233 nData = newNData;
[2047]3234 }
3235 }
[2012]3236 }
3237
[2193]3238 nClipped = initNData - nData;
3239
[2058]3240 std::vector<float> result;
3241 if (getResidual) {
3242 for (int i = 0; i < nChan; ++i) {
[2081]3243 result.push_back((float)residual[i]);
[2058]3244 }
3245 } else {
3246 for (int i = 0; i < nChan; ++i) {
3247 result.push_back((float)r1[i]);
3248 }
[2047]3249 }
3250
[2058]3251 return result;
[2012]3252}
3253
[2047]3254void Scantable::fitBaseline(const std::vector<bool>& mask, int whichrow, Fitter& fitter)
3255{
[2081]3256 std::vector<double> dAbcissa = getAbcissa(whichrow);
3257 std::vector<float> abcissa;
3258 for (uInt i = 0; i < dAbcissa.size(); ++i) {
3259 abcissa.push_back((float)dAbcissa[i]);
[2047]3260 }
3261 std::vector<float> spec = getSpectrum(whichrow);
[2012]3262
[2081]3263 fitter.setData(abcissa, spec, mask);
[2047]3264 fitter.lfit();
3265}
3266
3267std::vector<bool> Scantable::getCompositeChanMask(int whichrow, const std::vector<bool>& inMask)
3268{
[2186]3269 std::vector<bool> mask = getMask(whichrow);
3270 uInt maskSize = mask.size();
[2410]3271 if (inMask.size() != 0) {
3272 if (maskSize != inMask.size()) {
3273 throw(AipsError("mask sizes are not the same."));
3274 }
3275 for (uInt i = 0; i < maskSize; ++i) {
3276 mask[i] = mask[i] && inMask[i];
3277 }
[2047]3278 }
3279
[2186]3280 return mask;
[2047]3281}
3282
3283/*
3284std::vector<bool> Scantable::getCompositeChanMask(int whichrow, const std::vector<bool>& inMask, const std::vector<int>& edge, const int minEdgeSize, STLineFinder& lineFinder)
3285{
3286 int edgeSize = edge.size();
3287 std::vector<int> currentEdge;
3288 if (edgeSize >= 2) {
3289 int idx = 0;
3290 if (edgeSize > 2) {
3291 if (edgeSize < minEdgeSize) {
3292 throw(AipsError("Length of edge element info is less than that of IFs"));
3293 }
3294 idx = 2 * getIF(whichrow);
3295 }
3296 currentEdge.push_back(edge[idx]);
3297 currentEdge.push_back(edge[idx+1]);
3298 } else {
3299 throw(AipsError("Wrong length of edge element"));
3300 }
3301
3302 lineFinder.setData(getSpectrum(whichrow));
3303 lineFinder.findLines(getCompositeChanMask(whichrow, inMask), currentEdge, whichrow);
3304
3305 return lineFinder.getMask();
3306}
3307*/
3308
3309/* for poly. the variations of outputFittingResult() should be merged into one eventually (2011/3/10 WK) */
[2186]3310void 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)
3311{
[2047]3312 if (outLogger || outTextFile) {
3313 std::vector<float> params = fitter.getParameters();
3314 std::vector<bool> fixed = fitter.getFixedParameters();
3315 float rms = getRms(chanMask, whichrow);
3316 String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
3317
3318 if (outLogger) {
3319 LogIO ols(LogOrigin("Scantable", funcName, WHERE));
[2193]3320 ols << formatBaselineParams(params, fixed, rms, -1, masklist, whichrow, false) << LogIO::POST ;
[2047]3321 }
3322 if (outTextFile) {
[2193]3323 ofs << formatBaselineParams(params, fixed, rms, -1, masklist, whichrow, true) << flush;
[2047]3324 }
3325 }
3326}
3327
3328/* for cspline. will be merged once cspline is available in fitter (2011/3/10 WK) */
[2193]3329void 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]3330{
[2047]3331 if (outLogger || outTextFile) {
3332 float rms = getRms(chanMask, whichrow);
3333 String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
[2081]3334 std::vector<bool> fixed;
3335 fixed.clear();
[2047]3336
3337 if (outLogger) {
3338 LogIO ols(LogOrigin("Scantable", funcName, WHERE));
[2193]3339 ols << formatPiecewiseBaselineParams(edge, params, fixed, rms, nClipped, masklist, whichrow, false) << LogIO::POST ;
[2047]3340 }
3341 if (outTextFile) {
[2193]3342 ofs << formatPiecewiseBaselineParams(edge, params, fixed, rms, nClipped, masklist, whichrow, true) << flush;
[2047]3343 }
3344 }
3345}
3346
3347/* for sinusoid. will be merged once sinusoid is available in fitter (2011/3/10 WK) */
[2193]3348void 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]3349{
[2047]3350 if (outLogger || outTextFile) {
3351 float rms = getRms(chanMask, whichrow);
3352 String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
[2081]3353 std::vector<bool> fixed;
3354 fixed.clear();
[2047]3355
3356 if (outLogger) {
3357 LogIO ols(LogOrigin("Scantable", funcName, WHERE));
[2193]3358 ols << formatBaselineParams(params, fixed, rms, nClipped, masklist, whichrow, false) << LogIO::POST ;
[2047]3359 }
3360 if (outTextFile) {
[2193]3361 ofs << formatBaselineParams(params, fixed, rms, nClipped, masklist, whichrow, true) << flush;
[2047]3362 }
3363 }
3364}
3365
[2189]3366void Scantable::parseProgressInfo(const std::string& progressInfo, bool& showProgress, int& minNRow)
[2186]3367{
[2189]3368 int idxDelimiter = progressInfo.find(",");
3369 if (idxDelimiter < 0) {
3370 throw(AipsError("wrong value in 'showprogress' parameter")) ;
3371 }
3372 showProgress = (progressInfo.substr(0, idxDelimiter) == "true");
3373 std::istringstream is(progressInfo.substr(idxDelimiter+1));
3374 is >> minNRow;
3375}
3376
3377void Scantable::showProgressOnTerminal(const int nProcessed, const int nTotal, const bool showProgress, const int nTotalThreshold)
3378{
3379 if (showProgress && (nTotal >= nTotalThreshold)) {
[2186]3380 int nInterval = int(floor(double(nTotal)/100.0));
3381 if (nInterval == 0) nInterval++;
3382
[2193]3383 if (nProcessed % nInterval == 0) {
[2189]3384 printf("\r"); //go to the head of line
[2186]3385 printf("\x1b[31m\x1b[1m"); //set red color, highlighted
[2189]3386 printf("[%3d%%]", (int)(100.0*(double(nProcessed+1))/(double(nTotal))) );
3387 printf("\x1b[39m\x1b[0m"); //set default attributes
[2186]3388 fflush(NULL);
3389 }
[2193]3390
[2186]3391 if (nProcessed == nTotal - 1) {
3392 printf("\r\x1b[K"); //clear
3393 fflush(NULL);
3394 }
[2193]3395
[2186]3396 }
3397}
3398
3399std::vector<float> Scantable::execFFT(const int whichrow, const std::vector<bool>& inMask, bool getRealImag, bool getAmplitudeOnly)
3400{
3401 std::vector<bool> mask = getMask(whichrow);
3402
3403 if (inMask.size() > 0) {
3404 uInt maskSize = mask.size();
3405 if (maskSize != inMask.size()) {
3406 throw(AipsError("mask sizes are not the same."));
3407 }
3408 for (uInt i = 0; i < maskSize; ++i) {
3409 mask[i] = mask[i] && inMask[i];
3410 }
3411 }
3412
3413 Vector<Float> spec = getSpectrum(whichrow);
3414 mathutil::doZeroOrderInterpolation(spec, mask);
3415
3416 FFTServer<Float,Complex> ffts;
3417 Vector<Complex> fftres;
3418 ffts.fft0(fftres, spec);
3419
3420 std::vector<float> res;
3421 float norm = float(2.0/double(spec.size()));
3422
3423 if (getRealImag) {
3424 for (uInt i = 0; i < fftres.size(); ++i) {
3425 res.push_back(real(fftres[i])*norm);
3426 res.push_back(imag(fftres[i])*norm);
3427 }
3428 } else {
3429 for (uInt i = 0; i < fftres.size(); ++i) {
3430 res.push_back(abs(fftres[i])*norm);
3431 if (!getAmplitudeOnly) res.push_back(arg(fftres[i]));
3432 }
3433 }
3434
3435 return res;
3436}
3437
3438
3439float Scantable::getRms(const std::vector<bool>& mask, int whichrow)
3440{
[2012]3441 Vector<Float> spec;
3442 specCol_.get(whichrow, spec);
3443
3444 float mean = 0.0;
3445 float smean = 0.0;
3446 int n = 0;
[2047]3447 for (uInt i = 0; i < spec.nelements(); ++i) {
[2012]3448 if (mask[i]) {
3449 mean += spec[i];
3450 smean += spec[i]*spec[i];
3451 n++;
3452 }
3453 }
3454
3455 mean /= (float)n;
3456 smean /= (float)n;
3457
3458 return sqrt(smean - mean*mean);
3459}
3460
3461
[2186]3462std::string Scantable::formatBaselineParamsHeader(int whichrow, const std::string& masklist, bool verbose) const
[2012]3463{
3464 ostringstream oss;
3465
3466 if (verbose) {
3467 oss << " Scan[" << getScan(whichrow) << "]";
3468 oss << " Beam[" << getBeam(whichrow) << "]";
3469 oss << " IF[" << getIF(whichrow) << "]";
3470 oss << " Pol[" << getPol(whichrow) << "]";
3471 oss << " Cycle[" << getCycle(whichrow) << "]: " << endl;
3472 oss << "Fitter range = " << masklist << endl;
3473 oss << "Baseline parameters" << endl;
3474 oss << flush;
3475 }
3476
3477 return String(oss);
3478}
3479
[2193]3480std::string Scantable::formatBaselineParamsFooter(float rms, int nClipped, bool verbose) const
[2012]3481{
3482 ostringstream oss;
3483
3484 if (verbose) {
3485 oss << "Results of baseline fit" << endl;
3486 oss << " rms = " << setprecision(6) << rms << endl;
[2193]3487 if (nClipped >= 0) {
3488 oss << " Number of clipped channels = " << nClipped << endl;
3489 }
[2094]3490 for (int i = 0; i < 60; ++i) {
3491 oss << "-";
3492 }
[2131]3493 oss << endl;
[2094]3494 oss << flush;
[2012]3495 }
3496
3497 return String(oss);
3498}
3499
[2186]3500std::string Scantable::formatBaselineParams(const std::vector<float>& params,
3501 const std::vector<bool>& fixed,
3502 float rms,
[2193]3503 int nClipped,
[2186]3504 const std::string& masklist,
3505 int whichrow,
3506 bool verbose,
3507 int start, int count,
3508 bool resetparamid) const
[2047]3509{
[2064]3510 int nParam = (int)(params.size());
[2047]3511
[2064]3512 if (nParam < 1) {
3513 return(" Not fitted");
3514 } else {
3515
3516 ostringstream oss;
3517 oss << formatBaselineParamsHeader(whichrow, masklist, verbose);
3518
3519 if (start < 0) start = 0;
3520 if (count < 0) count = nParam;
3521 int end = start + count;
3522 if (end > nParam) end = nParam;
3523 int paramidoffset = (resetparamid) ? (-start) : 0;
3524
3525 for (int i = start; i < end; ++i) {
3526 if (i > start) {
[2047]3527 oss << ",";
3528 }
[2064]3529 std::string sFix = ((fixed.size() > 0) && (fixed[i]) && verbose) ? "(fixed)" : "";
3530 oss << " p" << (i+paramidoffset) << sFix << "= " << right << setw(13) << setprecision(6) << params[i];
[2047]3531 }
[2064]3532
3533 oss << endl;
[2193]3534 oss << formatBaselineParamsFooter(rms, nClipped, verbose);
[2064]3535
3536 return String(oss);
[2047]3537 }
3538
3539}
3540
[2193]3541 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]3542{
[2064]3543 int nOutParam = (int)(params.size());
3544 int nPiece = (int)(ranges.size()) - 1;
[2012]3545
[2064]3546 if (nOutParam < 1) {
3547 return(" Not fitted");
3548 } else if (nPiece < 0) {
[2193]3549 return formatBaselineParams(params, fixed, rms, nClipped, masklist, whichrow, verbose);
[2064]3550 } else if (nPiece < 1) {
3551 return(" Bad count of the piece edge info");
3552 } else if (nOutParam % nPiece != 0) {
3553 return(" Bad count of the output baseline parameters");
3554 } else {
3555
3556 int nParam = nOutParam / nPiece;
3557
3558 ostringstream oss;
3559 oss << formatBaselineParamsHeader(whichrow, masklist, verbose);
3560
3561 stringstream ss;
3562 ss << ranges[nPiece] << flush;
3563 int wRange = ss.str().size() * 2 + 5;
3564
3565 for (int i = 0; i < nPiece; ++i) {
[2047]3566 ss.str("");
[2064]3567 ss << " [" << ranges[i] << "," << (ranges[i+1]-1) << "]";
3568 oss << left << setw(wRange) << ss.str();
[2193]3569 oss << formatBaselineParams(params, fixed, rms, 0, masklist, whichrow, false, i*nParam, nParam, true);
[2012]3570 }
[2064]3571
[2193]3572 oss << formatBaselineParamsFooter(rms, nClipped, verbose);
[2064]3573
3574 return String(oss);
[2012]3575 }
3576
3577}
3578
[2047]3579bool Scantable::hasSameNchanOverIFs()
[2012]3580{
[2047]3581 int nIF = nif(-1);
3582 int nCh;
3583 int totalPositiveNChan = 0;
3584 int nPositiveNChan = 0;
[2012]3585
[2047]3586 for (int i = 0; i < nIF; ++i) {
3587 nCh = nchan(i);
3588 if (nCh > 0) {
3589 totalPositiveNChan += nCh;
3590 nPositiveNChan++;
[2012]3591 }
3592 }
3593
[2047]3594 return (totalPositiveNChan == (nPositiveNChan * nchan(0)));
[2012]3595}
3596
[2047]3597std::string Scantable::getMaskRangeList(const std::vector<bool>& mask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, bool verbose)
[2012]3598{
[2427]3599 if (mask.size() <= 0) {
3600 throw(AipsError("The mask elements should be > 0"));
[2012]3601 }
[2047]3602 int IF = getIF(whichrow);
3603 if (mask.size() != (uInt)nchan(IF)) {
[2012]3604 throw(AipsError("Number of channels in scantable != number of mask elements"));
3605 }
3606
[2047]3607 if (verbose) {
[2012]3608 LogIO logOs(LogOrigin("Scantable", "getMaskRangeList()", WHERE));
3609 logOs << LogIO::WARN << "The current mask window unit is " << coordInfo;
3610 if (!hasSameNchan) {
[2047]3611 logOs << endl << "This mask is only valid for IF=" << IF;
[2012]3612 }
3613 logOs << LogIO::POST;
3614 }
3615
3616 std::vector<double> abcissa = getAbcissa(whichrow);
[2047]3617 std::vector<int> edge = getMaskEdgeIndices(mask);
3618
[2012]3619 ostringstream oss;
3620 oss.setf(ios::fixed);
3621 oss << setprecision(1) << "[";
[2047]3622 for (uInt i = 0; i < edge.size(); i+=2) {
[2012]3623 if (i > 0) oss << ",";
[2047]3624 oss << "[" << (float)abcissa[edge[i]] << "," << (float)abcissa[edge[i+1]] << "]";
[2012]3625 }
3626 oss << "]" << flush;
3627
3628 return String(oss);
3629}
3630
[2047]3631std::vector<int> Scantable::getMaskEdgeIndices(const std::vector<bool>& mask)
[2012]3632{
[2427]3633 if (mask.size() <= 0) {
3634 throw(AipsError("The mask elements should be > 0"));
[2012]3635 }
3636
[2047]3637 std::vector<int> out, startIndices, endIndices;
3638 int maskSize = mask.size();
[2012]3639
[2047]3640 startIndices.clear();
3641 endIndices.clear();
3642
3643 if (mask[0]) {
3644 startIndices.push_back(0);
[2012]3645 }
[2047]3646 for (int i = 1; i < maskSize; ++i) {
3647 if ((!mask[i-1]) && mask[i]) {
3648 startIndices.push_back(i);
3649 } else if (mask[i-1] && (!mask[i])) {
3650 endIndices.push_back(i-1);
3651 }
[2012]3652 }
[2047]3653 if (mask[maskSize-1]) {
3654 endIndices.push_back(maskSize-1);
3655 }
[2012]3656
[2047]3657 if (startIndices.size() != endIndices.size()) {
3658 throw(AipsError("Inconsistent Mask Size: bad data?"));
3659 }
3660 for (uInt i = 0; i < startIndices.size(); ++i) {
3661 if (startIndices[i] > endIndices[i]) {
3662 throw(AipsError("Mask start index > mask end index"));
[2012]3663 }
3664 }
3665
[2047]3666 out.clear();
3667 for (uInt i = 0; i < startIndices.size(); ++i) {
3668 out.push_back(startIndices[i]);
3669 out.push_back(endIndices[i]);
3670 }
3671
[2012]3672 return out;
3673}
3674
[2161]3675vector<float> Scantable::getTsysSpectrum( int whichrow ) const
3676{
3677 Vector<Float> tsys( tsysCol_(whichrow) ) ;
3678 vector<float> stlTsys ;
3679 tsys.tovector( stlTsys ) ;
3680 return stlTsys ;
3681}
[2012]3682
3683
[1907]3684}
[1819]3685//namespace asap
Note: See TracBrowser for help on using the repository browser.