source: trunk/src/Scantable.cpp@ 3024

Last change on this file since 3024 was 3024, checked in by Kana Sugimoto, 10 years ago

New Development: No

JIRA Issue: No

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs:

Put in Release Notes: Yes

Module(s): scantable, sdbaseline

Description: Fixed *Baseline functions so that FLAGROW is set for spectra in which baseline subtraction is not operated (due to flagged channels).


  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 167.5 KB
RevLine 
[805]1//
2// C++ Implementation: Scantable
3//
4// Description:
5//
6//
[2791]7// Author: Malte Marquarding <asap@atnf.csiro.au>, (C) 2005-2013
[805]8//
9// Copyright: See COPYING file that comes with this distribution
10//
11//
[206]12#include <map>
[2591]13#include <sys/time.h>
[206]14
[2186]15#include <atnf/PKSIO/SrcType.h>
16
[125]17#include <casa/aips.h>
[2186]18#include <casa/iomanip.h>
[80]19#include <casa/iostream.h>
[2186]20#include <casa/OS/File.h>
[805]21#include <casa/OS/Path.h>
[2658]22#include <casa/Logging/LogIO.h>
[80]23#include <casa/Arrays/Array.h>
[2186]24#include <casa/Arrays/ArrayAccessor.h>
25#include <casa/Arrays/ArrayLogical.h>
[80]26#include <casa/Arrays/ArrayMath.h>
27#include <casa/Arrays/MaskArrMath.h>
[2186]28#include <casa/Arrays/Slice.h>
[1325]29#include <casa/Arrays/Vector.h>
[455]30#include <casa/Arrays/VectorSTLIterator.h>
[418]31#include <casa/BasicMath/Math.h>
[504]32#include <casa/BasicSL/Constants.h>
[2186]33#include <casa/Containers/RecordField.h>
34#include <casa/Logging/LogIO.h>
[286]35#include <casa/Quanta/MVAngle.h>
[2186]36#include <casa/Quanta/MVTime.h>
[902]37#include <casa/Utilities/GenSort.h>
[2]38
[2186]39#include <coordinates/Coordinates/CoordinateUtil.h>
[2]40
[1325]41// needed to avoid error in .tcc
42#include <measures/Measures/MCDirection.h>
43//
44#include <measures/Measures/MDirection.h>
[2186]45#include <measures/Measures/MEpoch.h>
[80]46#include <measures/Measures/MFrequency.h>
[2186]47#include <measures/Measures/MeasRef.h>
48#include <measures/Measures/MeasTable.h>
49#include <measures/TableMeasures/ScalarMeasColumn.h>
50#include <measures/TableMeasures/TableMeasDesc.h>
[805]51#include <measures/TableMeasures/TableMeasRefDesc.h>
52#include <measures/TableMeasures/TableMeasValueDesc.h>
[2]53
[2186]54#include <tables/Tables/ArrColDesc.h>
55#include <tables/Tables/ExprNode.h>
56#include <tables/Tables/ScaColDesc.h>
57#include <tables/Tables/SetupNewTab.h>
58#include <tables/Tables/TableCopy.h>
59#include <tables/Tables/TableDesc.h>
60#include <tables/Tables/TableIter.h>
61#include <tables/Tables/TableParse.h>
62#include <tables/Tables/TableRecord.h>
63#include <tables/Tables/TableRow.h>
64#include <tables/Tables/TableVector.h>
65
66#include "MathUtils.h"
67#include "STAttr.h"
[2737]68#include "STBaselineTable.h"
[2186]69#include "STLineFinder.h"
70#include "STPolCircular.h"
[896]71#include "STPolLinear.h"
[913]72#include "STPolStokes.h"
[2321]73#include "STUpgrade.h"
[2666]74#include "STFitter.h"
[2186]75#include "Scantable.h"
[2]76
[2462]77#define debug 1
78
[125]79using namespace casa;
[2]80
[805]81namespace asap {
82
[896]83std::map<std::string, STPol::STPolFactory *> Scantable::factories_;
84
85void Scantable::initFactories() {
86 if ( factories_.empty() ) {
87 Scantable::factories_["linear"] = &STPolLinear::myFactory;
[1323]88 Scantable::factories_["circular"] = &STPolCircular::myFactory;
[913]89 Scantable::factories_["stokes"] = &STPolStokes::myFactory;
[896]90 }
91}
92
[805]93Scantable::Scantable(Table::TableType ttype) :
[852]94 type_(ttype)
[206]95{
[896]96 initFactories();
[805]97 setupMainTable();
[2346]98 freqTable_ = STFrequencies(*this);
99 table_.rwKeywordSet().defineTable("FREQUENCIES", freqTable_.table());
[852]100 weatherTable_ = STWeather(*this);
[805]101 table_.rwKeywordSet().defineTable("WEATHER", weatherTable_.table());
[852]102 focusTable_ = STFocus(*this);
[805]103 table_.rwKeywordSet().defineTable("FOCUS", focusTable_.table());
[852]104 tcalTable_ = STTcal(*this);
[805]105 table_.rwKeywordSet().defineTable("TCAL", tcalTable_.table());
[852]106 moleculeTable_ = STMolecules(*this);
[805]107 table_.rwKeywordSet().defineTable("MOLECULES", moleculeTable_.table());
[860]108 historyTable_ = STHistory(*this);
109 table_.rwKeywordSet().defineTable("HISTORY", historyTable_.table());
[959]110 fitTable_ = STFit(*this);
111 table_.rwKeywordSet().defineTable("FIT", fitTable_.table());
[1881]112 table_.tableInfo().setType( "Scantable" ) ;
[805]113 originalTable_ = table_;
[322]114 attach();
[18]115}
[206]116
[805]117Scantable::Scantable(const std::string& name, Table::TableType ttype) :
[852]118 type_(ttype)
[206]119{
[896]120 initFactories();
[1819]121
[865]122 Table tab(name, Table::Update);
[1009]123 uInt version = tab.keywordSet().asuInt("VERSION");
[483]124 if (version != version_) {
[2321]125 STUpgrade upgrader(version_);
[2162]126 LogIO os( LogOrigin( "Scantable" ) ) ;
127 os << LogIO::WARN
[2321]128 << name << " data format version " << version
129 << " is deprecated" << endl
130 << "Running upgrade."<< endl
[2162]131 << LogIO::POST ;
[2321]132 std::string outname = upgrader.upgrade(name);
[2332]133 if ( outname != name ) {
134 os << LogIO::WARN
135 << "Data will be loaded from " << outname << " instead of "
136 << name << LogIO::POST ;
137 tab = Table(outname, Table::Update ) ;
138 }
[483]139 }
[1009]140 if ( type_ == Table::Memory ) {
[852]141 table_ = tab.copyToMemoryTable(generateName());
[1009]142 } else {
[805]143 table_ = tab;
[1009]144 }
[1881]145 table_.tableInfo().setType( "Scantable" ) ;
[1009]146
[859]147 attachSubtables();
[805]148 originalTable_ = table_;
[329]149 attach();
[2]150}
[1819]151/*
152Scantable::Scantable(const std::string& name, Table::TableType ttype) :
153 type_(ttype)
154{
155 initFactories();
156 Table tab(name, Table::Update);
157 uInt version = tab.keywordSet().asuInt("VERSION");
158 if (version != version_) {
159 throw(AipsError("Unsupported version of ASAP file."));
160 }
161 if ( type_ == Table::Memory ) {
162 table_ = tab.copyToMemoryTable(generateName());
163 } else {
164 table_ = tab;
165 }
[2]166
[1819]167 attachSubtables();
168 originalTable_ = table_;
169 attach();
170}
171*/
172
[2658]173Scantable::Scantable( const Scantable& other, bool clear )
[206]174{
[805]175 // with or without data
[859]176 String newname = String(generateName());
[865]177 type_ = other.table_.tableType();
[859]178 if ( other.table_.tableType() == Table::Memory ) {
179 if ( clear ) {
180 table_ = TableCopy::makeEmptyMemoryTable(newname,
181 other.table_, True);
[2818]182 } else {
[859]183 table_ = other.table_.copyToMemoryTable(newname);
[2818]184 }
[16]185 } else {
[915]186 other.table_.deepCopy(newname, Table::New, False,
187 other.table_.endianFormat(),
[865]188 Bool(clear));
189 table_ = Table(newname, Table::Update);
190 table_.markForDelete();
191 }
[1881]192 table_.tableInfo().setType( "Scantable" ) ;
[1111]193 /// @todo reindex SCANNO, recompute nbeam, nif, npol
[2846]194 if ( clear ) copySubtables(other);
[859]195 attachSubtables();
[805]196 originalTable_ = table_;
[322]197 attach();
[2]198}
199
[865]200void Scantable::copySubtables(const Scantable& other) {
201 Table t = table_.rwKeywordSet().asTable("FREQUENCIES");
[2346]202 TableCopy::copyRows(t, other.freqTable_.table());
[865]203 t = table_.rwKeywordSet().asTable("FOCUS");
204 TableCopy::copyRows(t, other.focusTable_.table());
205 t = table_.rwKeywordSet().asTable("WEATHER");
206 TableCopy::copyRows(t, other.weatherTable_.table());
207 t = table_.rwKeywordSet().asTable("TCAL");
208 TableCopy::copyRows(t, other.tcalTable_.table());
209 t = table_.rwKeywordSet().asTable("MOLECULES");
210 TableCopy::copyRows(t, other.moleculeTable_.table());
211 t = table_.rwKeywordSet().asTable("HISTORY");
212 TableCopy::copyRows(t, other.historyTable_.table());
[972]213 t = table_.rwKeywordSet().asTable("FIT");
214 TableCopy::copyRows(t, other.fitTable_.table());
[865]215}
216
[859]217void Scantable::attachSubtables()
218{
[2346]219 freqTable_ = STFrequencies(table_);
[859]220 focusTable_ = STFocus(table_);
221 weatherTable_ = STWeather(table_);
222 tcalTable_ = STTcal(table_);
223 moleculeTable_ = STMolecules(table_);
[860]224 historyTable_ = STHistory(table_);
[972]225 fitTable_ = STFit(table_);
[859]226}
227
[805]228Scantable::~Scantable()
[206]229{
[2]230}
231
[805]232void Scantable::setupMainTable()
[206]233{
[805]234 TableDesc td("", "1", TableDesc::Scratch);
235 td.comment() = "An ASAP Scantable";
[1009]236 td.rwKeywordSet().define("VERSION", uInt(version_));
[2]237
[805]238 // n Cycles
239 td.addColumn(ScalarColumnDesc<uInt>("SCANNO"));
240 // new index every nBeam x nIF x nPol
241 td.addColumn(ScalarColumnDesc<uInt>("CYCLENO"));
[2]242
[805]243 td.addColumn(ScalarColumnDesc<uInt>("BEAMNO"));
244 td.addColumn(ScalarColumnDesc<uInt>("IFNO"));
[972]245 // linear, circular, stokes
[805]246 td.rwKeywordSet().define("POLTYPE", String("linear"));
247 td.addColumn(ScalarColumnDesc<uInt>("POLNO"));
[138]248
[805]249 td.addColumn(ScalarColumnDesc<uInt>("FREQ_ID"));
250 td.addColumn(ScalarColumnDesc<uInt>("MOLECULE_ID"));
[80]251
[1819]252 ScalarColumnDesc<Int> refbeamnoColumn("REFBEAMNO");
253 refbeamnoColumn.setDefault(Int(-1));
254 td.addColumn(refbeamnoColumn);
255
256 ScalarColumnDesc<uInt> flagrowColumn("FLAGROW");
257 flagrowColumn.setDefault(uInt(0));
258 td.addColumn(flagrowColumn);
259
[805]260 td.addColumn(ScalarColumnDesc<Double>("TIME"));
261 TableMeasRefDesc measRef(MEpoch::UTC); // UTC as default
262 TableMeasValueDesc measVal(td, "TIME");
263 TableMeasDesc<MEpoch> mepochCol(measVal, measRef);
264 mepochCol.write(td);
[483]265
[805]266 td.addColumn(ScalarColumnDesc<Double>("INTERVAL"));
267
[2]268 td.addColumn(ScalarColumnDesc<String>("SRCNAME"));
[805]269 // Type of source (on=0, off=1, other=-1)
[1503]270 ScalarColumnDesc<Int> stypeColumn("SRCTYPE");
271 stypeColumn.setDefault(Int(-1));
272 td.addColumn(stypeColumn);
[805]273 td.addColumn(ScalarColumnDesc<String>("FIELDNAME"));
274
275 //The actual Data Vectors
[2]276 td.addColumn(ArrayColumnDesc<Float>("SPECTRA"));
277 td.addColumn(ArrayColumnDesc<uChar>("FLAGTRA"));
[89]278 td.addColumn(ArrayColumnDesc<Float>("TSYS"));
[805]279
280 td.addColumn(ArrayColumnDesc<Double>("DIRECTION",
281 IPosition(1,2),
282 ColumnDesc::Direct));
283 TableMeasRefDesc mdirRef(MDirection::J2000); // default
284 TableMeasValueDesc tmvdMDir(td, "DIRECTION");
285 // the TableMeasDesc gives the column a type
286 TableMeasDesc<MDirection> mdirCol(tmvdMDir, mdirRef);
[987]287 // a uder set table type e.g. GALCTIC, B1950 ...
288 td.rwKeywordSet().define("DIRECTIONREF", String("J2000"));
[805]289 // writing create the measure column
290 mdirCol.write(td);
[923]291 td.addColumn(ScalarColumnDesc<Float>("AZIMUTH"));
292 td.addColumn(ScalarColumnDesc<Float>("ELEVATION"));
[1047]293 td.addColumn(ScalarColumnDesc<Float>("OPACITY"));
[105]294
[805]295 td.addColumn(ScalarColumnDesc<uInt>("TCAL_ID"));
[972]296 ScalarColumnDesc<Int> fitColumn("FIT_ID");
[973]297 fitColumn.setDefault(Int(-1));
[972]298 td.addColumn(fitColumn);
[805]299
300 td.addColumn(ScalarColumnDesc<uInt>("FOCUS_ID"));
301 td.addColumn(ScalarColumnDesc<uInt>("WEATHER_ID"));
302
[999]303 // columns which just get dragged along, as they aren't used in asap
304 td.addColumn(ScalarColumnDesc<Double>("SRCVELOCITY"));
305 td.addColumn(ArrayColumnDesc<Double>("SRCPROPERMOTION"));
306 td.addColumn(ArrayColumnDesc<Double>("SRCDIRECTION"));
307 td.addColumn(ArrayColumnDesc<Double>("SCANRATE"));
308
[805]309 td.rwKeywordSet().define("OBSMODE", String(""));
310
[418]311 // Now create Table SetUp from the description.
[859]312 SetupNewTable aNewTab(generateName(), td, Table::Scratch);
[852]313 table_ = Table(aNewTab, type_, 0);
[805]314 originalTable_ = table_;
315}
[418]316
[805]317void Scantable::attach()
[455]318{
[805]319 timeCol_.attach(table_, "TIME");
320 srcnCol_.attach(table_, "SRCNAME");
[1068]321 srctCol_.attach(table_, "SRCTYPE");
[805]322 specCol_.attach(table_, "SPECTRA");
323 flagsCol_.attach(table_, "FLAGTRA");
[865]324 tsysCol_.attach(table_, "TSYS");
[805]325 cycleCol_.attach(table_,"CYCLENO");
326 scanCol_.attach(table_, "SCANNO");
327 beamCol_.attach(table_, "BEAMNO");
[847]328 ifCol_.attach(table_, "IFNO");
329 polCol_.attach(table_, "POLNO");
[805]330 integrCol_.attach(table_, "INTERVAL");
331 azCol_.attach(table_, "AZIMUTH");
332 elCol_.attach(table_, "ELEVATION");
333 dirCol_.attach(table_, "DIRECTION");
334 fldnCol_.attach(table_, "FIELDNAME");
335 rbeamCol_.attach(table_, "REFBEAMNO");
[455]336
[1730]337 mweatheridCol_.attach(table_,"WEATHER_ID");
[805]338 mfitidCol_.attach(table_,"FIT_ID");
339 mfreqidCol_.attach(table_, "FREQ_ID");
340 mtcalidCol_.attach(table_, "TCAL_ID");
341 mfocusidCol_.attach(table_, "FOCUS_ID");
342 mmolidCol_.attach(table_, "MOLECULE_ID");
[1819]343
344 //Add auxiliary column for row-based flagging (CAS-1433 Wataru Kawasaki)
345 attachAuxColumnDef(flagrowCol_, "FLAGROW", 0);
346
[455]347}
348
[1819]349template<class T, class T2>
350void Scantable::attachAuxColumnDef(ScalarColumn<T>& col,
351 const String& colName,
352 const T2& defValue)
353{
354 try {
355 col.attach(table_, colName);
356 } catch (TableError& err) {
357 String errMesg = err.getMesg();
358 if (errMesg == "Table column " + colName + " is unknown") {
359 table_.addColumn(ScalarColumnDesc<T>(colName));
360 col.attach(table_, colName);
361 col.fillColumn(static_cast<T>(defValue));
362 } else {
363 throw;
364 }
365 } catch (...) {
366 throw;
367 }
368}
369
370template<class T, class T2>
371void Scantable::attachAuxColumnDef(ArrayColumn<T>& col,
372 const String& colName,
373 const Array<T2>& defValue)
374{
375 try {
376 col.attach(table_, colName);
377 } catch (TableError& err) {
378 String errMesg = err.getMesg();
379 if (errMesg == "Table column " + colName + " is unknown") {
380 table_.addColumn(ArrayColumnDesc<T>(colName));
381 col.attach(table_, colName);
382
383 int size = 0;
384 ArrayIterator<T2>& it = defValue.begin();
385 while (it != defValue.end()) {
386 ++size;
387 ++it;
388 }
389 IPosition ip(1, size);
390 Array<T>& arr(ip);
391 for (int i = 0; i < size; ++i)
392 arr[i] = static_cast<T>(defValue[i]);
393
394 col.fillColumn(arr);
395 } else {
396 throw;
397 }
398 } catch (...) {
399 throw;
400 }
401}
402
[901]403void Scantable::setHeader(const STHeader& sdh)
[206]404{
[18]405 table_.rwKeywordSet().define("nIF", sdh.nif);
406 table_.rwKeywordSet().define("nBeam", sdh.nbeam);
407 table_.rwKeywordSet().define("nPol", sdh.npol);
408 table_.rwKeywordSet().define("nChan", sdh.nchan);
409 table_.rwKeywordSet().define("Observer", sdh.observer);
410 table_.rwKeywordSet().define("Project", sdh.project);
411 table_.rwKeywordSet().define("Obstype", sdh.obstype);
412 table_.rwKeywordSet().define("AntennaName", sdh.antennaname);
413 table_.rwKeywordSet().define("AntennaPosition", sdh.antennaposition);
414 table_.rwKeywordSet().define("Equinox", sdh.equinox);
415 table_.rwKeywordSet().define("FreqRefFrame", sdh.freqref);
416 table_.rwKeywordSet().define("FreqRefVal", sdh.reffreq);
417 table_.rwKeywordSet().define("Bandwidth", sdh.bandwidth);
418 table_.rwKeywordSet().define("UTC", sdh.utc);
[206]419 table_.rwKeywordSet().define("FluxUnit", sdh.fluxunit);
420 table_.rwKeywordSet().define("Epoch", sdh.epoch);
[905]421 table_.rwKeywordSet().define("POLTYPE", sdh.poltype);
[50]422}
[21]423
[901]424STHeader Scantable::getHeader() const
[206]425{
[901]426 STHeader sdh;
[21]427 table_.keywordSet().get("nBeam",sdh.nbeam);
428 table_.keywordSet().get("nIF",sdh.nif);
429 table_.keywordSet().get("nPol",sdh.npol);
430 table_.keywordSet().get("nChan",sdh.nchan);
431 table_.keywordSet().get("Observer", sdh.observer);
432 table_.keywordSet().get("Project", sdh.project);
433 table_.keywordSet().get("Obstype", sdh.obstype);
434 table_.keywordSet().get("AntennaName", sdh.antennaname);
435 table_.keywordSet().get("AntennaPosition", sdh.antennaposition);
436 table_.keywordSet().get("Equinox", sdh.equinox);
437 table_.keywordSet().get("FreqRefFrame", sdh.freqref);
438 table_.keywordSet().get("FreqRefVal", sdh.reffreq);
439 table_.keywordSet().get("Bandwidth", sdh.bandwidth);
440 table_.keywordSet().get("UTC", sdh.utc);
[206]441 table_.keywordSet().get("FluxUnit", sdh.fluxunit);
442 table_.keywordSet().get("Epoch", sdh.epoch);
[905]443 table_.keywordSet().get("POLTYPE", sdh.poltype);
[21]444 return sdh;
[18]445}
[805]446
[1360]447void Scantable::setSourceType( int stype )
[1068]448{
449 if ( stype < 0 || stype > 1 )
450 throw(AipsError("Illegal sourcetype."));
451 TableVector<Int> tabvec(table_, "SRCTYPE");
452 tabvec = Int(stype);
453}
454
[2818]455void Scantable::setSourceName( const std::string& name )
456{
457 TableVector<String> tabvec(table_, "SRCNAME");
458 tabvec = name;
459}
460
[845]461bool Scantable::conformant( const Scantable& other )
462{
463 return this->getHeader().conformant(other.getHeader());
464}
465
466
[50]467
[805]468std::string Scantable::formatSec(Double x) const
[206]469{
[105]470 Double xcop = x;
471 MVTime mvt(xcop/24./3600.); // make days
[365]472
[105]473 if (x < 59.95)
[281]474 return String(" ") + mvt.string(MVTime::TIME_CLEAN_NO_HM, 7)+"s";
[745]475 else if (x < 3599.95)
[281]476 return String(" ") + mvt.string(MVTime::TIME_CLEAN_NO_H,7)+" ";
477 else {
478 ostringstream oss;
479 oss << setw(2) << std::right << setprecision(1) << mvt.hour();
480 oss << ":" << mvt.string(MVTime::TIME_CLEAN_NO_H,7) << " ";
481 return String(oss);
[745]482 }
[105]483};
484
[2969]485 std::string Scantable::formatDirection(const MDirection& md, Int prec) const
[281]486{
487 Vector<Double> t = md.getAngle(Unit(String("rad"))).getValue();
[2969]488 if (prec<0)
489 prec = 7;
[281]490
[2575]491 String ref = md.getRefString();
[281]492 MVAngle mvLon(t[0]);
493 String sLon = mvLon.string(MVAngle::TIME,prec);
[987]494 uInt tp = md.getRef().getType();
495 if (tp == MDirection::GALACTIC ||
496 tp == MDirection::SUPERGAL ) {
497 sLon = mvLon(0.0).string(MVAngle::ANGLE_CLEAN,prec);
498 }
[281]499 MVAngle mvLat(t[1]);
500 String sLat = mvLat.string(MVAngle::ANGLE+MVAngle::DIG2,prec);
[2575]501 return ref + String(" ") + sLon + String(" ") + sLat;
[281]502}
503
504
[805]505std::string Scantable::getFluxUnit() const
[206]506{
[847]507 return table_.keywordSet().asString("FluxUnit");
[206]508}
509
[805]510void Scantable::setFluxUnit(const std::string& unit)
[218]511{
512 String tmp(unit);
513 Unit tU(tmp);
514 if (tU==Unit("K") || tU==Unit("Jy")) {
515 table_.rwKeywordSet().define(String("FluxUnit"), tmp);
516 } else {
517 throw AipsError("Illegal unit - must be compatible with Jy or K");
518 }
519}
520
[805]521void Scantable::setInstrument(const std::string& name)
[236]522{
[805]523 bool throwIt = true;
[996]524 // create an Instrument to see if this is valid
525 STAttr::convertInstrument(name, throwIt);
[236]526 String nameU(name);
527 nameU.upcase();
528 table_.rwKeywordSet().define(String("AntennaName"), nameU);
529}
530
[1189]531void Scantable::setFeedType(const std::string& feedtype)
532{
533 if ( Scantable::factories_.find(feedtype) == Scantable::factories_.end() ) {
534 std::string msg = "Illegal feed type "+ feedtype;
535 throw(casa::AipsError(msg));
536 }
537 table_.rwKeywordSet().define(String("POLTYPE"), feedtype);
538}
539
[1743]540MPosition Scantable::getAntennaPosition() const
[805]541{
542 Vector<Double> antpos;
543 table_.keywordSet().get("AntennaPosition", antpos);
544 MVPosition mvpos(antpos(0),antpos(1),antpos(2));
545 return MPosition(mvpos);
546}
[281]547
[805]548void Scantable::makePersistent(const std::string& filename)
549{
550 String inname(filename);
551 Path path(inname);
[1111]552 /// @todo reindex SCANNO, recompute nbeam, nif, npol
[805]553 inname = path.expandedName();
[2030]554 // 2011/03/04 TN
555 // We can comment out this workaround since the essential bug is
556 // fixed in casacore (r20889 in google code).
557 table_.deepCopy(inname, Table::New);
558// // WORKAROUND !!! for Table bug
559// // Remove when fixed in casacore
560// if ( table_.tableType() == Table::Memory && !selector_.empty() ) {
561// Table tab = table_.copyToMemoryTable(generateName());
562// tab.deepCopy(inname, Table::New);
563// tab.markForDelete();
564//
565// } else {
566// table_.deepCopy(inname, Table::New);
567// }
[805]568}
569
[837]570int Scantable::nbeam( int scanno ) const
[805]571{
572 if ( scanno < 0 ) {
573 Int n;
574 table_.keywordSet().get("nBeam",n);
575 return int(n);
[105]576 } else {
[805]577 // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
[888]578 Table t = table_(table_.col("SCANNO") == scanno);
579 ROTableRow row(t);
580 const TableRecord& rec = row.get(0);
581 Table subt = t( t.col("IFNO") == Int(rec.asuInt("IFNO"))
582 && t.col("POLNO") == Int(rec.asuInt("POLNO"))
583 && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
584 ROTableVector<uInt> v(subt, "BEAMNO");
[805]585 return int(v.nelements());
[105]586 }
[805]587 return 0;
588}
[455]589
[837]590int Scantable::nif( int scanno ) const
[805]591{
592 if ( scanno < 0 ) {
593 Int n;
594 table_.keywordSet().get("nIF",n);
595 return int(n);
596 } else {
597 // take the first POLNO,BEAMNO,CYCLENO as nbeam shouldn't vary with these
[888]598 Table t = table_(table_.col("SCANNO") == scanno);
599 ROTableRow row(t);
600 const TableRecord& rec = row.get(0);
601 Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
602 && t.col("POLNO") == Int(rec.asuInt("POLNO"))
603 && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
604 if ( subt.nrow() == 0 ) return 0;
605 ROTableVector<uInt> v(subt, "IFNO");
[805]606 return int(v.nelements());
[2]607 }
[805]608 return 0;
609}
[321]610
[837]611int Scantable::npol( int scanno ) const
[805]612{
613 if ( scanno < 0 ) {
614 Int n;
615 table_.keywordSet().get("nPol",n);
616 return n;
617 } else {
618 // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
[888]619 Table t = table_(table_.col("SCANNO") == scanno);
620 ROTableRow row(t);
621 const TableRecord& rec = row.get(0);
622 Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
623 && t.col("IFNO") == Int(rec.asuInt("IFNO"))
624 && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
625 if ( subt.nrow() == 0 ) return 0;
626 ROTableVector<uInt> v(subt, "POLNO");
[805]627 return int(v.nelements());
[321]628 }
[805]629 return 0;
[2]630}
[805]631
[845]632int Scantable::ncycle( int scanno ) const
[206]633{
[805]634 if ( scanno < 0 ) {
[837]635 Block<String> cols(2);
636 cols[0] = "SCANNO";
637 cols[1] = "CYCLENO";
638 TableIterator it(table_, cols);
639 int n = 0;
640 while ( !it.pastEnd() ) {
641 ++n;
[902]642 ++it;
[837]643 }
644 return n;
[805]645 } else {
[888]646 Table t = table_(table_.col("SCANNO") == scanno);
647 ROTableRow row(t);
648 const TableRecord& rec = row.get(0);
649 Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
650 && t.col("POLNO") == Int(rec.asuInt("POLNO"))
651 && t.col("IFNO") == Int(rec.asuInt("IFNO")) );
652 if ( subt.nrow() == 0 ) return 0;
653 return int(subt.nrow());
[805]654 }
655 return 0;
[18]656}
[455]657
658
[845]659int Scantable::nrow( int scanno ) const
[805]660{
[845]661 return int(table_.nrow());
662}
663
664int Scantable::nchan( int ifno ) const
665{
666 if ( ifno < 0 ) {
[805]667 Int n;
668 table_.keywordSet().get("nChan",n);
669 return int(n);
670 } else {
[1360]671 // take the first SCANNO,POLNO,BEAMNO,CYCLENO as nbeam shouldn't
672 // vary with these
[2244]673 Table t = table_(table_.col("IFNO") == ifno, 1);
[888]674 if ( t.nrow() == 0 ) return 0;
675 ROArrayColumn<Float> v(t, "SPECTRA");
[923]676 return v.shape(0)(0);
[805]677 }
678 return 0;
[18]679}
[455]680
[1111]681int Scantable::nscan() const {
682 Vector<uInt> scannos(scanCol_.getColumn());
[1148]683 uInt nout = genSort( scannos, Sort::Ascending,
[1111]684 Sort::QuickSort|Sort::NoDuplicates );
685 return int(nout);
686}
687
[923]688int Scantable::getChannels(int whichrow) const
689{
690 return specCol_.shape(whichrow)(0);
691}
[847]692
693int Scantable::getBeam(int whichrow) const
694{
695 return beamCol_(whichrow);
696}
697
[1694]698std::vector<uint> Scantable::getNumbers(const ScalarColumn<uInt>& col) const
[1111]699{
700 Vector<uInt> nos(col.getColumn());
[1148]701 uInt n = genSort( nos, Sort::Ascending, Sort::QuickSort|Sort::NoDuplicates );
702 nos.resize(n, True);
[1111]703 std::vector<uint> stlout;
704 nos.tovector(stlout);
705 return stlout;
706}
707
[847]708int Scantable::getIF(int whichrow) const
709{
710 return ifCol_(whichrow);
711}
712
713int Scantable::getPol(int whichrow) const
714{
715 return polCol_(whichrow);
716}
717
[805]718std::string Scantable::formatTime(const MEpoch& me, bool showdate) const
719{
[1947]720 return formatTime(me, showdate, 0);
721}
722
723std::string Scantable::formatTime(const MEpoch& me, bool showdate, uInt prec) const
724{
[805]725 MVTime mvt(me.getValue());
726 if (showdate)
[1947]727 //mvt.setFormat(MVTime::YMD);
728 mvt.setFormat(MVTime::YMD, prec);
[805]729 else
[1947]730 //mvt.setFormat(MVTime::TIME);
731 mvt.setFormat(MVTime::TIME, prec);
[805]732 ostringstream oss;
733 oss << mvt;
734 return String(oss);
735}
[488]736
[805]737void Scantable::calculateAZEL()
[2658]738{
739 LogIO os( LogOrigin( "Scantable", "calculateAZEL()", WHERE ) ) ;
[805]740 MPosition mp = getAntennaPosition();
741 MEpoch::ROScalarColumn timeCol(table_, "TIME");
742 ostringstream oss;
[2658]743 oss << mp;
744 os << "Computed azimuth/elevation using " << endl
745 << String(oss) << endl;
[996]746 for (Int i=0; i<nrow(); ++i) {
[805]747 MEpoch me = timeCol(i);
[987]748 MDirection md = getDirection(i);
[2658]749 os << " Time: " << formatTime(me,False)
750 << " Direction: " << formatDirection(md)
[805]751 << endl << " => ";
752 MeasFrame frame(mp, me);
753 Vector<Double> azel =
754 MDirection::Convert(md, MDirection::Ref(MDirection::AZEL,
755 frame)
756 )().getAngle("rad").getValue();
[923]757 azCol_.put(i,Float(azel[0]));
758 elCol_.put(i,Float(azel[1]));
[2658]759 os << "azel: " << azel[0]/C::pi*180.0 << " "
760 << azel[1]/C::pi*180.0 << " (deg)" << LogIO::POST;
[16]761 }
[805]762}
[89]763
[1819]764void Scantable::clip(const Float uthres, const Float dthres, bool clipoutside, bool unflag)
765{
[2947]766 Vector<uInt> flagrow = flagrowCol_.getColumn();
[1819]767 for (uInt i=0; i<table_.nrow(); ++i) {
[2947]768 // apply flag only when specified row is vaild
769 if (flagrow[i] == 0) {
770 Vector<uChar> flgs = flagsCol_(i);
771 srchChannelsToClip(i, uthres, dthres, clipoutside, unflag, flgs);
772 flagsCol_.put(i, flgs);
773 }
[1819]774 }
775}
776
777std::vector<bool> Scantable::getClipMask(int whichrow, const Float uthres, const Float dthres, bool clipoutside, bool unflag)
778{
779 Vector<uChar> flags;
780 flagsCol_.get(uInt(whichrow), flags);
781 srchChannelsToClip(uInt(whichrow), uthres, dthres, clipoutside, unflag, flags);
782 Vector<Bool> bflag(flags.shape());
783 convertArray(bflag, flags);
784 //bflag = !bflag;
785
786 std::vector<bool> mask;
787 bflag.tovector(mask);
788 return mask;
789}
790
791void Scantable::srchChannelsToClip(uInt whichrow, const Float uthres, const Float dthres, bool clipoutside, bool unflag,
792 Vector<uChar> flgs)
793{
794 Vector<Float> spcs = specCol_(whichrow);
[2348]795 uInt nchannel = spcs.nelements();
[1819]796 if (spcs.nelements() != nchannel) {
797 throw(AipsError("Data has incorrect number of channels"));
798 }
799 uChar userflag = 1 << 7;
800 if (unflag) {
801 userflag = 0 << 7;
802 }
803 if (clipoutside) {
804 for (uInt j = 0; j < nchannel; ++j) {
805 Float spc = spcs(j);
806 if ((spc >= uthres) || (spc <= dthres)) {
807 flgs(j) = userflag;
808 }
809 }
810 } else {
811 for (uInt j = 0; j < nchannel; ++j) {
812 Float spc = spcs(j);
813 if ((spc < uthres) && (spc > dthres)) {
814 flgs(j) = userflag;
815 }
816 }
817 }
818}
819
[1994]820
821void Scantable::flag( int whichrow, const std::vector<bool>& msk, bool unflag ) {
[1333]822 std::vector<bool>::const_iterator it;
823 uInt ntrue = 0;
[1994]824 if (whichrow >= int(table_.nrow()) ) {
825 throw(AipsError("Invalid row number"));
826 }
[1333]827 for (it = msk.begin(); it != msk.end(); ++it) {
828 if ( *it ) {
829 ntrue++;
830 }
831 }
[1994]832 //if ( selector_.empty() && (msk.size() == 0 || msk.size() == ntrue) )
833 if ( whichrow == -1 && !unflag && selector_.empty() && (msk.size() == 0 || msk.size() == ntrue) )
[1000]834 throw(AipsError("Trying to flag whole scantable."));
[1994]835 uChar userflag = 1 << 7;
836 if ( unflag ) {
837 userflag = 0 << 7;
838 }
839 if (whichrow > -1 ) {
[2947]840 // apply flag only when specified row is vaild
841 if (flagrowCol_(whichrow) == 0) {
842 applyChanFlag(uInt(whichrow), msk, userflag);
843 }
[1994]844 } else {
[2948]845 Vector<uInt> flagrow = flagrowCol_.getColumn();
[1000]846 for ( uInt i=0; i<table_.nrow(); ++i) {
[2947]847 // apply flag only when specified row is vaild
[2948]848 if (flagrow[i] == 0) {
[2947]849 applyChanFlag(i, msk, userflag);
850 }
[1000]851 }
[1994]852 }
853}
854
855void Scantable::applyChanFlag( uInt whichrow, const std::vector<bool>& msk, uChar flagval )
856{
857 if (whichrow >= table_.nrow() ) {
858 throw( casa::indexError<int>( whichrow, "asap::Scantable::applyChanFlag: Invalid row number" ) );
859 }
860 Vector<uChar> flgs = flagsCol_(whichrow);
861 if ( msk.size() == 0 ) {
862 flgs = flagval;
863 flagsCol_.put(whichrow, flgs);
[1000]864 return;
865 }
[2348]866 if ( int(msk.size()) != nchan( getIF(whichrow) ) ) {
[1000]867 throw(AipsError("Mask has incorrect number of channels."));
868 }
[1994]869 if ( flgs.nelements() != msk.size() ) {
870 throw(AipsError("Mask has incorrect number of channels."
871 " Probably varying with IF. Please flag per IF"));
872 }
873 std::vector<bool>::const_iterator it;
874 uInt j = 0;
875 for (it = msk.begin(); it != msk.end(); ++it) {
876 if ( *it ) {
877 flgs(j) = flagval;
[1000]878 }
[1994]879 ++j;
[1000]880 }
[1994]881 flagsCol_.put(whichrow, flgs);
[865]882}
883
[1819]884void Scantable::flagRow(const std::vector<uInt>& rows, bool unflag)
885{
[2683]886 if (selector_.empty() && (rows.size() == table_.nrow()) && !unflag)
[1819]887 throw(AipsError("Trying to flag whole scantable."));
888
889 uInt rowflag = (unflag ? 0 : 1);
890 std::vector<uInt>::const_iterator it;
891 for (it = rows.begin(); it != rows.end(); ++it)
892 flagrowCol_.put(*it, rowflag);
893}
894
[805]895std::vector<bool> Scantable::getMask(int whichrow) const
896{
897 Vector<uChar> flags;
898 flagsCol_.get(uInt(whichrow), flags);
899 Vector<Bool> bflag(flags.shape());
900 convertArray(bflag, flags);
901 bflag = !bflag;
902 std::vector<bool> mask;
903 bflag.tovector(mask);
904 return mask;
905}
[89]906
[896]907std::vector<float> Scantable::getSpectrum( int whichrow,
[902]908 const std::string& poltype ) const
[805]909{
[2658]910 LogIO os( LogOrigin( "Scantable", "getSpectrum()", WHERE ) ) ;
911
[905]912 String ptype = poltype;
913 if (poltype == "" ) ptype = getPolType();
[902]914 if ( whichrow < 0 || whichrow >= nrow() )
915 throw(AipsError("Illegal row number."));
[896]916 std::vector<float> out;
[805]917 Vector<Float> arr;
[896]918 uInt requestedpol = polCol_(whichrow);
919 String basetype = getPolType();
[905]920 if ( ptype == basetype ) {
[896]921 specCol_.get(whichrow, arr);
922 } else {
[1598]923 CountedPtr<STPol> stpol(STPol::getPolClass(Scantable::factories_,
[1586]924 basetype));
[1334]925 uInt row = uInt(whichrow);
926 stpol->setSpectra(getPolMatrix(row));
[2047]927 Float fang,fhand;
[1586]928 fang = focusTable_.getTotalAngle(mfocusidCol_(row));
[1334]929 fhand = focusTable_.getFeedHand(mfocusidCol_(row));
[1586]930 stpol->setPhaseCorrections(fang, fhand);
[1334]931 arr = stpol->getSpectrum(requestedpol, ptype);
[896]932 }
[902]933 if ( arr.nelements() == 0 )
[2658]934
935 os << "Not enough polarisations present to do the conversion."
936 << LogIO::POST;
[805]937 arr.tovector(out);
938 return out;
[89]939}
[212]940
[1360]941void Scantable::setSpectrum( const std::vector<float>& spec,
[884]942 int whichrow )
943{
944 Vector<Float> spectrum(spec);
945 Vector<Float> arr;
946 specCol_.get(whichrow, arr);
947 if ( spectrum.nelements() != arr.nelements() )
[896]948 throw AipsError("The spectrum has incorrect number of channels.");
[884]949 specCol_.put(whichrow, spectrum);
950}
951
952
[805]953String Scantable::generateName()
[745]954{
[805]955 return (File::newUniqueName("./","temp")).baseName();
[212]956}
957
[805]958const casa::Table& Scantable::table( ) const
[212]959{
[805]960 return table_;
[212]961}
962
[805]963casa::Table& Scantable::table( )
[386]964{
[805]965 return table_;
[386]966}
967
[896]968std::string Scantable::getPolType() const
969{
970 return table_.keywordSet().asString("POLTYPE");
971}
972
[805]973void Scantable::unsetSelection()
[380]974{
[805]975 table_ = originalTable_;
[847]976 attach();
[805]977 selector_.reset();
[380]978}
[386]979
[805]980void Scantable::setSelection( const STSelector& selection )
[430]981{
[805]982 Table tab = const_cast<STSelector&>(selection).apply(originalTable_);
983 if ( tab.nrow() == 0 ) {
984 throw(AipsError("Selection contains no data. Not applying it."));
985 }
986 table_ = tab;
[847]987 attach();
[2084]988// tab.rwKeywordSet().define("nBeam",(Int)(getBeamNos().size())) ;
989// vector<uint> selectedIFs = getIFNos() ;
990// Int newnIF = selectedIFs.size() ;
991// tab.rwKeywordSet().define("nIF",newnIF) ;
992// if ( newnIF != 0 ) {
993// Int newnChan = 0 ;
994// for ( Int i = 0 ; i < newnIF ; i++ ) {
995// Int nChan = nchan( selectedIFs[i] ) ;
996// if ( newnChan > nChan )
997// newnChan = nChan ;
998// }
999// tab.rwKeywordSet().define("nChan",newnChan) ;
1000// }
1001// tab.rwKeywordSet().define("nPol",(Int)(getPolNos().size())) ;
[805]1002 selector_ = selection;
[430]1003}
1004
[2111]1005
[2163]1006std::string Scantable::headerSummary()
[447]1007{
[805]1008 // Format header info
[2111]1009// STHeader sdh;
1010// sdh = getHeader();
1011// sdh.print();
[805]1012 ostringstream oss;
1013 oss.flags(std::ios_base::left);
[2290]1014 String tmp;
1015 // Project
1016 table_.keywordSet().get("Project", tmp);
1017 oss << setw(15) << "Project:" << tmp << endl;
1018 // Observation date
1019 oss << setw(15) << "Obs Date:" << getTime(-1,true) << endl;
1020 // Observer
1021 oss << setw(15) << "Observer:"
1022 << table_.keywordSet().asString("Observer") << endl;
1023 // Antenna Name
1024 table_.keywordSet().get("AntennaName", tmp);
1025 oss << setw(15) << "Antenna Name:" << tmp << endl;
1026 // Obs type
1027 table_.keywordSet().get("Obstype", tmp);
1028 // Records (nrow)
1029 oss << setw(15) << "Data Records:" << table_.nrow() << " rows" << endl;
1030 oss << setw(15) << "Obs. Type:" << tmp << endl;
1031 // Beams, IFs, Polarizations, and Channels
[805]1032 oss << setw(15) << "Beams:" << setw(4) << nbeam() << endl
1033 << setw(15) << "IFs:" << setw(4) << nif() << endl
[896]1034 << setw(15) << "Polarisations:" << setw(4) << npol()
1035 << "(" << getPolType() << ")" << endl
[1694]1036 << setw(15) << "Channels:" << nchan() << endl;
[2290]1037 // Flux unit
1038 table_.keywordSet().get("FluxUnit", tmp);
1039 oss << setw(15) << "Flux Unit:" << tmp << endl;
1040 // Abscissa Unit
1041 oss << setw(15) << "Abscissa:" << getAbcissaLabel(0) << endl;
1042 // Selection
1043 oss << selector_.print() << endl;
1044
1045 return String(oss);
1046}
1047
1048void Scantable::summary( const std::string& filename )
1049{
1050 ostringstream oss;
1051 ofstream ofs;
1052 LogIO ols(LogOrigin("Scantable", "summary", WHERE));
1053
1054 if (filename != "")
1055 ofs.open( filename.c_str(), ios::out );
1056
1057 oss << endl;
1058 oss << asap::SEPERATOR << endl;
1059 oss << " Scan Table Summary" << endl;
1060 oss << asap::SEPERATOR << endl;
1061
1062 // Format header info
1063 oss << headerSummary();
1064 oss << endl;
1065
1066 if (table_.nrow() <= 0){
1067 oss << asap::SEPERATOR << endl;
1068 oss << "The MAIN table is empty: there are no data!!!" << endl;
1069 oss << asap::SEPERATOR << endl;
1070
1071 ols << String(oss) << LogIO::POST;
1072 if (ofs) {
1073 ofs << String(oss) << flush;
1074 ofs.close();
1075 }
1076 return;
1077 }
1078
1079
1080
1081 // main table
1082 String dirtype = "Position ("
1083 + getDirectionRefString()
1084 + ")";
1085 oss.flags(std::ios_base::left);
1086 oss << setw(5) << "Scan"
1087 << setw(15) << "Source"
1088 << setw(35) << "Time range"
1089 << setw(2) << "" << setw(7) << "Int[s]"
1090 << setw(7) << "Record"
1091 << setw(8) << "SrcType"
1092 << setw(8) << "FreqIDs"
1093 << setw(7) << "MolIDs" << endl;
1094 oss << setw(7)<< "" << setw(6) << "Beam"
1095 << setw(23) << dirtype << endl;
1096
1097 oss << asap::SEPERATOR << endl;
1098
1099 // Flush summary and clear up the string
1100 ols << String(oss) << LogIO::POST;
1101 if (ofs) ofs << String(oss) << flush;
1102 oss.str("");
1103 oss.clear();
1104
1105
1106 // Get Freq_ID map
1107 ROScalarColumn<uInt> ftabIds(frequencies().table(), "ID");
1108 Int nfid = ftabIds.nrow();
1109 if (nfid <= 0){
1110 oss << "FREQUENCIES subtable is empty: there are no data!!!" << endl;
1111 oss << asap::SEPERATOR << endl;
1112
1113 ols << String(oss) << LogIO::POST;
1114 if (ofs) {
1115 ofs << String(oss) << flush;
1116 ofs.close();
1117 }
1118 return;
1119 }
1120 // Storages of overall IFNO, POLNO, and nchan per FREQ_ID
1121 // the orders are identical to ID in FREQ subtable
1122 Block< Vector<uInt> > ifNos(nfid), polNos(nfid);
1123 Vector<Int> fIdchans(nfid,-1);
[2938]1124 Vector<Double> fIdfreq0(nfid,-1);
1125 Vector<Double> fIdfcent(nfid,-1);
[2290]1126 map<uInt, Int> fidMap; // (FREQ_ID, row # in FREQ subtable) pair
1127 for (Int i=0; i < nfid; i++){
1128 // fidMap[freqId] returns row number in FREQ subtable
1129 fidMap.insert(pair<uInt, Int>(ftabIds(i),i));
1130 ifNos[i] = Vector<uInt>();
1131 polNos[i] = Vector<uInt>();
1132 }
1133
1134 TableIterator iter(table_, "SCANNO");
1135
1136 // Vars for keeping track of time, freqids, molIds in a SCANNO
[2813]1137 //Vector<uInt> freqids;
1138 //Vector<uInt> molids;
[2290]1139 Vector<uInt> beamids(1,0);
1140 Vector<MDirection> beamDirs;
1141 Vector<Int> stypeids(1,0);
1142 Vector<String> stypestrs;
1143 Int nfreq(1);
1144 Int nmol(1);
1145 uInt nbeam(1);
1146 uInt nstype(1);
1147
1148 Double btime(0.0), etime(0.0);
1149 Double meanIntTim(0.0);
1150
1151 uInt currFreqId(0), ftabRow(0);
1152 Int iflen(0), pollen(0);
1153
1154 while (!iter.pastEnd()) {
1155 Table subt = iter.table();
1156 uInt snrow = subt.nrow();
1157 ROTableRow row(subt);
1158 const TableRecord& rec = row.get(0);
1159
1160 // relevant columns
1161 ROScalarColumn<Double> mjdCol(subt,"TIME");
1162 ROScalarColumn<Double> intervalCol(subt,"INTERVAL");
1163 MDirection::ROScalarColumn dirCol(subt,"DIRECTION");
1164
1165 ScalarColumn<uInt> freqIdCol(subt,"FREQ_ID");
1166 ScalarColumn<uInt> molIdCol(subt,"MOLECULE_ID");
1167 ROScalarColumn<uInt> beamCol(subt,"BEAMNO");
1168 ROScalarColumn<Int> stypeCol(subt,"SRCTYPE");
1169
1170 ROScalarColumn<uInt> ifNoCol(subt,"IFNO");
1171 ROScalarColumn<uInt> polNoCol(subt,"POLNO");
1172
1173
1174 // Times
1175 meanIntTim = sum(intervalCol.getColumn()) / (double) snrow;
1176 minMax(btime, etime, mjdCol.getColumn());
[2969]1177 double shiftInDay(0.5*meanIntTim/C::day);
1178 btime -= shiftInDay;
1179 etime += shiftInDay;
[2290]1180
1181 // MOLECULE_ID and FREQ_ID
[2813]1182 Vector<uInt> molids(getNumbers(molIdCol));
[2290]1183 molids.shape(nmol);
1184
[2813]1185 Vector<uInt> freqids(getNumbers(freqIdCol));
[2290]1186 freqids.shape(nfreq);
1187
1188 // Add first beamid, and srcNames
1189 beamids.resize(1,False);
1190 beamDirs.resize(1,False);
1191 beamids(0)=beamCol(0);
1192 beamDirs(0)=dirCol(0);
1193 nbeam = 1;
1194
1195 stypeids.resize(1,False);
1196 stypeids(0)=stypeCol(0);
1197 nstype = 1;
1198
1199 // Global listings of nchan/IFNO/POLNO per FREQ_ID
1200 currFreqId=freqIdCol(0);
1201 ftabRow = fidMap[currFreqId];
1202 // Assumes an identical number of channels per FREQ_ID
1203 if (fIdchans(ftabRow) < 0 ) {
1204 RORecordFieldPtr< Array<Float> > spec(rec, "SPECTRA");
1205 fIdchans(ftabRow)=(*spec).shape()(0);
1206 }
[2938]1207 if (fIdfreq0(ftabRow) < 0 ) {
1208 SpectralCoordinate spc = frequencies().getSpectralCoordinate(ftabRow);
1209 Double fs, fe;
1210 spc.toWorld(fs, 0);
1211 spc.toWorld(fe, fIdchans(ftabRow)-1);
1212 fIdfreq0(ftabRow) = fs;
1213 fIdfcent(ftabRow) = 0.5 * ( fs + fe );
1214 }
[2290]1215 // Should keep ifNos and polNos form the previous SCANNO
1216 if ( !anyEQ(ifNos[ftabRow],ifNoCol(0)) ) {
1217 ifNos[ftabRow].shape(iflen);
1218 iflen++;
1219 ifNos[ftabRow].resize(iflen,True);
1220 ifNos[ftabRow](iflen-1) = ifNoCol(0);
1221 }
1222 if ( !anyEQ(polNos[ftabRow],polNoCol(0)) ) {
1223 polNos[ftabRow].shape(pollen);
1224 pollen++;
1225 polNos[ftabRow].resize(pollen,True);
1226 polNos[ftabRow](pollen-1) = polNoCol(0);
1227 }
1228
1229 for (uInt i=1; i < snrow; i++){
1230 // Need to list BEAMNO and DIRECTION in the same order
1231 if ( !anyEQ(beamids,beamCol(i)) ) {
1232 nbeam++;
1233 beamids.resize(nbeam,True);
1234 beamids(nbeam-1)=beamCol(i);
1235 beamDirs.resize(nbeam,True);
1236 beamDirs(nbeam-1)=dirCol(i);
1237 }
1238
1239 // SRCTYPE is Int (getNumber takes only uInt)
1240 if ( !anyEQ(stypeids,stypeCol(i)) ) {
1241 nstype++;
1242 stypeids.resize(nstype,True);
1243 stypeids(nstype-1)=stypeCol(i);
1244 }
1245
1246 // Global listings of nchan/IFNO/POLNO per FREQ_ID
1247 currFreqId=freqIdCol(i);
1248 ftabRow = fidMap[currFreqId];
1249 if (fIdchans(ftabRow) < 0 ) {
1250 const TableRecord& rec = row.get(i);
1251 RORecordFieldPtr< Array<Float> > spec(rec, "SPECTRA");
1252 fIdchans(ftabRow) = (*spec).shape()(0);
1253 }
[2938]1254 if (fIdfreq0(ftabRow) < 0 ) {
1255 SpectralCoordinate spc = frequencies().getSpectralCoordinate(ftabRow);
1256 Double fs, fe;
1257 spc.toWorld(fs, 0);
1258 spc.toWorld(fe, fIdchans(ftabRow)-1);
1259 fIdfreq0(ftabRow) = fs;
1260 fIdfcent(ftabRow) = 5.e-1 * ( fs + fe );
1261 }
[2290]1262 if ( !anyEQ(ifNos[ftabRow],ifNoCol(i)) ) {
1263 ifNos[ftabRow].shape(iflen);
1264 iflen++;
1265 ifNos[ftabRow].resize(iflen,True);
1266 ifNos[ftabRow](iflen-1) = ifNoCol(i);
1267 }
1268 if ( !anyEQ(polNos[ftabRow],polNoCol(i)) ) {
1269 polNos[ftabRow].shape(pollen);
1270 pollen++;
1271 polNos[ftabRow].resize(pollen,True);
1272 polNos[ftabRow](pollen-1) = polNoCol(i);
1273 }
1274 } // end of row iteration
1275
1276 stypestrs.resize(nstype,False);
1277 for (uInt j=0; j < nstype; j++)
1278 stypestrs(j) = SrcType::getName(stypeids(j));
1279
1280 // Format Scan summary
1281 oss << setw(4) << std::right << rec.asuInt("SCANNO")
1282 << std::left << setw(1) << ""
1283 << setw(15) << rec.asString("SRCNAME")
[2969]1284 << setw(21) << MVTime(btime).string(MVTime::YMD,8)
1285 << setw(3) << " - " << MVTime(etime).string(MVTime::TIME,8)
[2290]1286 << setw(3) << "" << setw(6) << meanIntTim << setw(1) << ""
1287 << std::right << setw(5) << snrow << setw(2) << ""
1288 << std::left << stypestrs << setw(1) << ""
1289 << freqids << setw(1) << ""
1290 << molids << endl;
1291 // Format Beam summary
1292 for (uInt j=0; j < nbeam; j++) {
1293 oss << setw(7) << "" << setw(6) << beamids(j) << setw(1) << ""
[2969]1294 << formatDirection(beamDirs(j),9) << endl;
[2290]1295 }
1296 // Flush summary every scan and clear up the string
1297 ols << String(oss) << LogIO::POST;
1298 if (ofs) ofs << String(oss) << flush;
1299 oss.str("");
1300 oss.clear();
1301
1302 ++iter;
1303 } // end of scan iteration
1304 oss << asap::SEPERATOR << endl;
1305
1306 // List FRECUENCIES Table (using STFrequencies.print may be slow)
1307 oss << "FREQUENCIES: " << nfreq << endl;
[2938]1308// oss << std::right << setw(5) << "ID" << setw(2) << ""
1309// << std::left << setw(5) << "IFNO" << setw(2) << ""
1310// << setw(8) << "Frame"
1311// << setw(16) << "RefVal"
1312// << setw(7) << "RefPix"
1313// << setw(15) << "Increment"
1314// << setw(9) << "Channels"
1315// << setw(6) << "POLNOs" << endl;
1316// Int tmplen;
1317// for (Int i=0; i < nfid; i++){
1318// // List row=i of FREQUENCIES subtable
1319// ifNos[i].shape(tmplen);
1320// if (tmplen >= 1) {
1321// oss << std::right << setw(5) << ftabIds(i) << setw(2) << ""
1322// << setw(3) << ifNos[i](0) << setw(1) << ""
1323// << std::left << setw(46) << frequencies().print(ftabIds(i))
1324// << setw(2) << ""
1325// << std::right << setw(8) << fIdchans[i] << setw(2) << ""
1326// << std::left << polNos[i];
1327// if (tmplen > 1) {
1328// oss << " (" << tmplen << " chains)";
1329// }
1330// oss << endl;
1331// }
1332 oss << std::right << setw(4) << "ID" << setw(2) << ""
1333 << std::left << setw(9) << "IFNO(SPW)" << setw(2) << ""
1334 << setw(8) << "#Chans"
[2290]1335 << setw(8) << "Frame"
[2938]1336 << setw(12) << "Ch0[MHz]"
1337 << setw(14) << "ChanWid[kHz]"
1338 << setw(14) << "Center[MHz]"
[2290]1339 << setw(6) << "POLNOs" << endl;
1340 Int tmplen;
1341 for (Int i=0; i < nfid; i++){
1342 // List row=i of FREQUENCIES subtable
1343 ifNos[i].shape(tmplen);
[2938]1344 Double refpix, refval, increment ;
[2531]1345 if (tmplen >= 1) {
[2938]1346 freqTable_.getEntry( refpix, refval, increment, ftabIds(i) ) ;
1347 oss << std::right << setw(4) << ftabIds(i) << setw(2) << ""
1348 << std::left << setw(9) << ifNos[i](0) << setw(2) << ""
1349 << std::right << setw(6) << fIdchans[i] << setw(2) << ""
1350 << setw(6) << frequencies().getFrameString(true)
1351 << setw(2) << ""
1352 << setw(10) << std::setprecision(9) << (fIdfreq0[i]*1.e-6) << setw(2) << ""
1353 << setw(12) << (increment*1.e-3) << setw(2) << ""
1354 << setw(12) << (fIdfcent[i]*1.e-6) << setw(2) << ""
[2531]1355 << std::left << polNos[i];
1356 if (tmplen > 1) {
1357 oss << " (" << tmplen << " chains)";
1358 }
1359 oss << endl;
[2290]1360 }
[2531]1361
[2290]1362 }
1363 oss << asap::SEPERATOR << endl;
1364
1365 // List MOLECULES Table (currently lists all rows)
1366 oss << "MOLECULES: " << endl;
1367 if (molecules().nrow() <= 0) {
1368 oss << " MOLECULES subtable is empty: there are no data" << endl;
1369 } else {
1370 ROTableRow row(molecules().table());
1371 oss << std::right << setw(5) << "ID"
1372 << std::left << setw(3) << ""
1373 << setw(18) << "RestFreq"
1374 << setw(15) << "Name" << endl;
1375 for (Int i=0; i < molecules().nrow(); i++){
1376 const TableRecord& rec=row.get(i);
1377 oss << std::right << setw(5) << rec.asuInt("ID")
1378 << std::left << setw(3) << ""
1379 << rec.asArrayDouble("RESTFREQUENCY") << setw(1) << ""
1380 << rec.asArrayString("NAME") << endl;
1381 }
1382 }
1383 oss << asap::SEPERATOR << endl;
1384 ols << String(oss) << LogIO::POST;
1385 if (ofs) {
1386 ofs << String(oss) << flush;
1387 ofs.close();
1388 }
1389 // return String(oss);
1390}
1391
1392
1393std::string Scantable::oldheaderSummary()
1394{
1395 // Format header info
1396// STHeader sdh;
1397// sdh = getHeader();
1398// sdh.print();
1399 ostringstream oss;
1400 oss.flags(std::ios_base::left);
1401 oss << setw(15) << "Beams:" << setw(4) << nbeam() << endl
1402 << setw(15) << "IFs:" << setw(4) << nif() << endl
1403 << setw(15) << "Polarisations:" << setw(4) << npol()
1404 << "(" << getPolType() << ")" << endl
1405 << setw(15) << "Channels:" << nchan() << endl;
[805]1406 String tmp;
[860]1407 oss << setw(15) << "Observer:"
1408 << table_.keywordSet().asString("Observer") << endl;
[805]1409 oss << setw(15) << "Obs Date:" << getTime(-1,true) << endl;
1410 table_.keywordSet().get("Project", tmp);
1411 oss << setw(15) << "Project:" << tmp << endl;
1412 table_.keywordSet().get("Obstype", tmp);
1413 oss << setw(15) << "Obs. Type:" << tmp << endl;
1414 table_.keywordSet().get("AntennaName", tmp);
1415 oss << setw(15) << "Antenna Name:" << tmp << endl;
1416 table_.keywordSet().get("FluxUnit", tmp);
1417 oss << setw(15) << "Flux Unit:" << tmp << endl;
[1819]1418 int nid = moleculeTable_.nrow();
1419 Bool firstline = True;
[805]1420 oss << setw(15) << "Rest Freqs:";
[1819]1421 for (int i=0; i<nid; i++) {
[2244]1422 Table t = table_(table_.col("MOLECULE_ID") == i, 1);
[1819]1423 if (t.nrow() > 0) {
1424 Vector<Double> vec(moleculeTable_.getRestFrequency(i));
1425 if (vec.nelements() > 0) {
1426 if (firstline) {
1427 oss << setprecision(10) << vec << " [Hz]" << endl;
1428 firstline=False;
1429 }
1430 else{
1431 oss << setw(15)<<" " << setprecision(10) << vec << " [Hz]" << endl;
1432 }
1433 } else {
1434 oss << "none" << endl;
1435 }
1436 }
[805]1437 }
[941]1438
1439 oss << setw(15) << "Abcissa:" << getAbcissaLabel(0) << endl;
[805]1440 oss << selector_.print() << endl;
[2111]1441 return String(oss);
1442}
1443
[2286]1444 //std::string Scantable::summary( const std::string& filename )
[2290]1445void Scantable::oldsummary( const std::string& filename )
[2111]1446{
1447 ostringstream oss;
[2286]1448 ofstream ofs;
1449 LogIO ols(LogOrigin("Scantable", "summary", WHERE));
1450
1451 if (filename != "")
1452 ofs.open( filename.c_str(), ios::out );
1453
[805]1454 oss << endl;
[2111]1455 oss << asap::SEPERATOR << endl;
1456 oss << " Scan Table Summary" << endl;
1457 oss << asap::SEPERATOR << endl;
1458
1459 // Format header info
[2290]1460 oss << oldheaderSummary();
[2111]1461 oss << endl;
1462
[805]1463 // main table
1464 String dirtype = "Position ("
[987]1465 + getDirectionRefString()
[805]1466 + ")";
[2111]1467 oss.flags(std::ios_base::left);
[941]1468 oss << setw(5) << "Scan" << setw(15) << "Source"
[2005]1469 << setw(10) << "Time" << setw(18) << "Integration"
1470 << setw(15) << "Source Type" << endl;
[941]1471 oss << setw(5) << "" << setw(5) << "Beam" << setw(3) << "" << dirtype << endl;
[1694]1472 oss << setw(10) << "" << setw(3) << "IF" << setw(3) << ""
[805]1473 << setw(8) << "Frame" << setw(16)
[1694]1474 << "RefVal" << setw(10) << "RefPix" << setw(12) << "Increment"
1475 << setw(7) << "Channels"
1476 << endl;
[805]1477 oss << asap::SEPERATOR << endl;
[2286]1478
1479 // Flush summary and clear up the string
1480 ols << String(oss) << LogIO::POST;
1481 if (ofs) ofs << String(oss) << flush;
1482 oss.str("");
1483 oss.clear();
1484
[805]1485 TableIterator iter(table_, "SCANNO");
1486 while (!iter.pastEnd()) {
1487 Table subt = iter.table();
1488 ROTableRow row(subt);
1489 MEpoch::ROScalarColumn timeCol(subt,"TIME");
1490 const TableRecord& rec = row.get(0);
1491 oss << setw(4) << std::right << rec.asuInt("SCANNO")
1492 << std::left << setw(1) << ""
1493 << setw(15) << rec.asString("SRCNAME")
1494 << setw(10) << formatTime(timeCol(0), false);
1495 // count the cycles in the scan
1496 TableIterator cyciter(subt, "CYCLENO");
1497 int nint = 0;
1498 while (!cyciter.pastEnd()) {
1499 ++nint;
1500 ++cyciter;
1501 }
1502 oss << setw(3) << std::right << nint << setw(3) << " x " << std::left
[2005]1503 << setw(11) << formatSec(rec.asFloat("INTERVAL")) << setw(1) << ""
1504 << setw(15) << SrcType::getName(rec.asInt("SRCTYPE")) << endl;
[447]1505
[805]1506 TableIterator biter(subt, "BEAMNO");
1507 while (!biter.pastEnd()) {
1508 Table bsubt = biter.table();
1509 ROTableRow brow(bsubt);
1510 const TableRecord& brec = brow.get(0);
[1000]1511 uInt row0 = bsubt.rowNumbers(table_)[0];
[941]1512 oss << setw(5) << "" << setw(4) << std::right << brec.asuInt("BEAMNO")<< std::left;
[987]1513 oss << setw(4) << "" << formatDirection(getDirection(row0)) << endl;
[805]1514 TableIterator iiter(bsubt, "IFNO");
1515 while (!iiter.pastEnd()) {
1516 Table isubt = iiter.table();
1517 ROTableRow irow(isubt);
1518 const TableRecord& irec = irow.get(0);
[1694]1519 oss << setw(9) << "";
[941]1520 oss << setw(3) << std::right << irec.asuInt("IFNO") << std::left
[1694]1521 << setw(1) << "" << frequencies().print(irec.asuInt("FREQ_ID"))
1522 << setw(3) << "" << nchan(irec.asuInt("IFNO"))
[1375]1523 << endl;
[447]1524
[805]1525 ++iiter;
1526 }
1527 ++biter;
1528 }
[2286]1529 // Flush summary every scan and clear up the string
1530 ols << String(oss) << LogIO::POST;
1531 if (ofs) ofs << String(oss) << flush;
1532 oss.str("");
1533 oss.clear();
1534
[805]1535 ++iter;
[447]1536 }
[2286]1537 oss << asap::SEPERATOR << endl;
1538 ols << String(oss) << LogIO::POST;
1539 if (ofs) {
[2290]1540 ofs << String(oss) << flush;
[2286]1541 ofs.close();
1542 }
1543 // return String(oss);
[447]1544}
1545
[1947]1546// std::string Scantable::getTime(int whichrow, bool showdate) const
1547// {
1548// MEpoch::ROScalarColumn timeCol(table_, "TIME");
1549// MEpoch me;
1550// if (whichrow > -1) {
1551// me = timeCol(uInt(whichrow));
1552// } else {
1553// Double tm;
1554// table_.keywordSet().get("UTC",tm);
1555// me = MEpoch(MVEpoch(tm));
1556// }
1557// return formatTime(me, showdate);
1558// }
1559
1560std::string Scantable::getTime(int whichrow, bool showdate, uInt prec) const
[777]1561{
[805]1562 MEpoch me;
[1947]1563 me = getEpoch(whichrow);
1564 return formatTime(me, showdate, prec);
[777]1565}
[805]1566
[1411]1567MEpoch Scantable::getEpoch(int whichrow) const
1568{
1569 if (whichrow > -1) {
1570 return timeCol_(uInt(whichrow));
1571 } else {
1572 Double tm;
1573 table_.keywordSet().get("UTC",tm);
[1598]1574 return MEpoch(MVEpoch(tm));
[1411]1575 }
1576}
1577
[1068]1578std::string Scantable::getDirectionString(int whichrow) const
1579{
1580 return formatDirection(getDirection(uInt(whichrow)));
1581}
1582
[1598]1583
1584SpectralCoordinate Scantable::getSpectralCoordinate(int whichrow) const {
1585 const MPosition& mp = getAntennaPosition();
1586 const MDirection& md = getDirection(whichrow);
1587 const MEpoch& me = timeCol_(whichrow);
[1819]1588 //Double rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
1589 Vector<Double> rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
[2346]1590 return freqTable_.getSpectralCoordinate(md, mp, me, rf,
[1598]1591 mfreqidCol_(whichrow));
1592}
1593
[1360]1594std::vector< double > Scantable::getAbcissa( int whichrow ) const
[865]1595{
[1507]1596 if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal row number"));
[865]1597 std::vector<double> stlout;
1598 int nchan = specCol_(whichrow).nelements();
[2346]1599 String us = freqTable_.getUnitString();
[865]1600 if ( us == "" || us == "pixel" || us == "channel" ) {
1601 for (int i=0; i<nchan; ++i) {
1602 stlout.push_back(double(i));
1603 }
1604 return stlout;
1605 }
[1598]1606 SpectralCoordinate spc = getSpectralCoordinate(whichrow);
[865]1607 Vector<Double> pixel(nchan);
1608 Vector<Double> world;
1609 indgen(pixel);
1610 if ( Unit(us) == Unit("Hz") ) {
1611 for ( int i=0; i < nchan; ++i) {
1612 Double world;
1613 spc.toWorld(world, pixel[i]);
1614 stlout.push_back(double(world));
1615 }
1616 } else if ( Unit(us) == Unit("km/s") ) {
1617 Vector<Double> world;
1618 spc.pixelToVelocity(world, pixel);
1619 world.tovector(stlout);
1620 }
1621 return stlout;
1622}
[1360]1623void Scantable::setDirectionRefString( const std::string & refstr )
[987]1624{
1625 MDirection::Types mdt;
1626 if (refstr != "" && !MDirection::getType(mdt, refstr)) {
1627 throw(AipsError("Illegal Direction frame."));
1628 }
1629 if ( refstr == "" ) {
1630 String defaultstr = MDirection::showType(dirCol_.getMeasRef().getType());
1631 table_.rwKeywordSet().define("DIRECTIONREF", defaultstr);
1632 } else {
1633 table_.rwKeywordSet().define("DIRECTIONREF", String(refstr));
1634 }
1635}
[865]1636
[1360]1637std::string Scantable::getDirectionRefString( ) const
[987]1638{
1639 return table_.keywordSet().asString("DIRECTIONREF");
1640}
1641
1642MDirection Scantable::getDirection(int whichrow ) const
1643{
1644 String usertype = table_.keywordSet().asString("DIRECTIONREF");
1645 String type = MDirection::showType(dirCol_.getMeasRef().getType());
1646 if ( usertype != type ) {
1647 MDirection::Types mdt;
1648 if (!MDirection::getType(mdt, usertype)) {
1649 throw(AipsError("Illegal Direction frame."));
1650 }
1651 return dirCol_.convert(uInt(whichrow), mdt);
1652 } else {
1653 return dirCol_(uInt(whichrow));
1654 }
1655}
1656
[847]1657std::string Scantable::getAbcissaLabel( int whichrow ) const
1658{
[996]1659 if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal ro number"));
[847]1660 const MPosition& mp = getAntennaPosition();
[987]1661 const MDirection& md = getDirection(whichrow);
[847]1662 const MEpoch& me = timeCol_(whichrow);
[1819]1663 //const Double& rf = mmolidCol_(whichrow);
1664 const Vector<Double> rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
[847]1665 SpectralCoordinate spc =
[2346]1666 freqTable_.getSpectralCoordinate(md, mp, me, rf, mfreqidCol_(whichrow));
[847]1667
1668 String s = "Channel";
[2346]1669 Unit u = Unit(freqTable_.getUnitString());
[847]1670 if (u == Unit("km/s")) {
[1170]1671 s = CoordinateUtil::axisLabel(spc, 0, True,True, True);
[847]1672 } else if (u == Unit("Hz")) {
1673 Vector<String> wau(1);wau = u.getName();
1674 spc.setWorldAxisUnits(wau);
[1170]1675 s = CoordinateUtil::axisLabel(spc, 0, True, True, False);
[847]1676 }
1677 return s;
1678
1679}
1680
[1819]1681/**
1682void asap::Scantable::setRestFrequencies( double rf, const std::string& name,
[1170]1683 const std::string& unit )
[1819]1684**/
1685void Scantable::setRestFrequencies( vector<double> rf, const vector<std::string>& name,
1686 const std::string& unit )
1687
[847]1688{
[923]1689 ///@todo lookup in line table to fill in name and formattedname
[847]1690 Unit u(unit);
[1819]1691 //Quantum<Double> urf(rf, u);
1692 Quantum<Vector<Double> >urf(rf, u);
1693 Vector<String> formattedname(0);
1694 //cerr<<"Scantable::setRestFrequnecies="<<urf<<endl;
1695
1696 //uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), name, "");
1697 uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), mathutil::toVectorString(name), formattedname);
[847]1698 TableVector<uInt> tabvec(table_, "MOLECULE_ID");
1699 tabvec = id;
1700}
1701
[1819]1702/**
1703void asap::Scantable::setRestFrequencies( const std::string& name )
[847]1704{
1705 throw(AipsError("setRestFrequencies( const std::string& name ) NYI"));
1706 ///@todo implement
1707}
[1819]1708**/
[2012]1709
[1819]1710void Scantable::setRestFrequencies( const vector<std::string>& name )
1711{
[2163]1712 (void) name; // suppress unused warning
[1819]1713 throw(AipsError("setRestFrequencies( const vector<std::string>& name ) NYI"));
1714 ///@todo implement
1715}
[847]1716
[1360]1717std::vector< unsigned int > Scantable::rownumbers( ) const
[852]1718{
1719 std::vector<unsigned int> stlout;
1720 Vector<uInt> vec = table_.rowNumbers();
1721 vec.tovector(stlout);
1722 return stlout;
1723}
1724
[865]1725
[1360]1726Matrix<Float> Scantable::getPolMatrix( uInt whichrow ) const
[896]1727{
1728 ROTableRow row(table_);
1729 const TableRecord& rec = row.get(whichrow);
1730 Table t =
1731 originalTable_( originalTable_.col("SCANNO") == Int(rec.asuInt("SCANNO"))
1732 && originalTable_.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
1733 && originalTable_.col("IFNO") == Int(rec.asuInt("IFNO"))
1734 && originalTable_.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
1735 ROArrayColumn<Float> speccol(t, "SPECTRA");
1736 return speccol.getColumn();
1737}
[865]1738
[1360]1739std::vector< std::string > Scantable::columnNames( ) const
[902]1740{
1741 Vector<String> vec = table_.tableDesc().columnNames();
1742 return mathutil::tovectorstring(vec);
1743}
[896]1744
[1360]1745MEpoch::Types Scantable::getTimeReference( ) const
[915]1746{
1747 return MEpoch::castType(timeCol_.getMeasRef().getType());
[972]1748}
[915]1749
[1360]1750void Scantable::addFit( const STFitEntry& fit, int row )
[972]1751{
[1819]1752 //cout << mfitidCol_(uInt(row)) << endl;
1753 LogIO os( LogOrigin( "Scantable", "addFit()", WHERE ) ) ;
1754 os << mfitidCol_(uInt(row)) << LogIO::POST ;
[972]1755 uInt id = fitTable_.addEntry(fit, mfitidCol_(uInt(row)));
1756 mfitidCol_.put(uInt(row), id);
1757}
[915]1758
[1360]1759void Scantable::shift(int npix)
1760{
1761 Vector<uInt> fids(mfreqidCol_.getColumn());
1762 genSort( fids, Sort::Ascending,
1763 Sort::QuickSort|Sort::NoDuplicates );
1764 for (uInt i=0; i<fids.nelements(); ++i) {
[1567]1765 frequencies().shiftRefPix(npix, fids[i]);
[1360]1766 }
1767}
[987]1768
[1819]1769String Scantable::getAntennaName() const
[1391]1770{
1771 String out;
1772 table_.keywordSet().get("AntennaName", out);
[1987]1773 String::size_type pos1 = out.find("@") ;
1774 String::size_type pos2 = out.find("//") ;
1775 if ( pos2 != String::npos )
[2036]1776 out = out.substr(pos2+2,pos1-pos2-2) ;
[1987]1777 else if ( pos1 != String::npos )
1778 out = out.substr(0,pos1) ;
[1391]1779 return out;
[987]1780}
[1391]1781
[1730]1782int Scantable::checkScanInfo(const std::vector<int>& scanlist) const
[1391]1783{
1784 String tbpath;
1785 int ret = 0;
1786 if ( table_.keywordSet().isDefined("GBT_GO") ) {
1787 table_.keywordSet().get("GBT_GO", tbpath);
1788 Table t(tbpath,Table::Old);
1789 // check each scan if other scan of the pair exist
1790 int nscan = scanlist.size();
1791 for (int i = 0; i < nscan; i++) {
[2869]1792 Table subt = t( t.col("SCAN") == scanlist[i] );
[1391]1793 if (subt.nrow()==0) {
[1819]1794 //cerr <<"Scan "<<scanlist[i]<<" cannot be found in the scantable."<<endl;
1795 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1796 os <<LogIO::WARN<<"Scan "<<scanlist[i]<<" cannot be found in the scantable."<<LogIO::POST;
[1391]1797 ret = 1;
1798 break;
1799 }
1800 ROTableRow row(subt);
1801 const TableRecord& rec = row.get(0);
1802 int scan1seqn = rec.asuInt("PROCSEQN");
1803 int laston1 = rec.asuInt("LASTON");
1804 if ( rec.asuInt("PROCSIZE")==2 ) {
1805 if ( i < nscan-1 ) {
[2869]1806 Table subt2 = t( t.col("SCAN") == scanlist[i+1] );
[1391]1807 if ( subt2.nrow() == 0) {
[1819]1808 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1809
1810 //cerr<<"Scan "<<scanlist[i+1]<<" cannot be found in the scantable."<<endl;
1811 os<<LogIO::WARN<<"Scan "<<scanlist[i+1]<<" cannot be found in the scantable."<<LogIO::POST;
[1391]1812 ret = 1;
1813 break;
1814 }
1815 ROTableRow row2(subt2);
1816 const TableRecord& rec2 = row2.get(0);
1817 int scan2seqn = rec2.asuInt("PROCSEQN");
1818 int laston2 = rec2.asuInt("LASTON");
1819 if (scan1seqn == 1 && scan2seqn == 2) {
1820 if (laston1 == laston2) {
[1819]1821 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1822 //cerr<<"A valid scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl;
1823 os<<"A valid scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<LogIO::POST;
[1391]1824 i +=1;
1825 }
1826 else {
[1819]1827 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1828 //cerr<<"Incorrect scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl;
1829 os<<LogIO::WARN<<"Incorrect scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<LogIO::POST;
[1391]1830 }
1831 }
1832 else if (scan1seqn==2 && scan2seqn == 1) {
1833 if (laston1 == laston2) {
[1819]1834 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1835 //cerr<<"["<<scanlist[i]<<","<<scanlist[i+1]<<"] is a valid scan pair but in incorrect order."<<endl;
1836 os<<LogIO::WARN<<"["<<scanlist[i]<<","<<scanlist[i+1]<<"] is a valid scan pair but in incorrect order."<<LogIO::POST;
[1391]1837 ret = 1;
1838 break;
1839 }
1840 }
1841 else {
[1819]1842 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1843 //cerr<<"The other scan for "<<scanlist[i]<<" appears to be missing. Check the input scan numbers."<<endl;
1844 os<<LogIO::WARN<<"The other scan for "<<scanlist[i]<<" appears to be missing. Check the input scan numbers."<<LogIO::POST;
[1391]1845 ret = 1;
1846 break;
1847 }
1848 }
1849 }
1850 else {
[1819]1851 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1852 //cerr<<"The scan does not appear to be standard obsevation."<<endl;
1853 os<<LogIO::WARN<<"The scan does not appear to be standard obsevation."<<LogIO::POST;
[1391]1854 }
1855 //if ( i >= nscan ) break;
1856 }
1857 }
1858 else {
[1819]1859 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1860 //cerr<<"No reference to GBT_GO table."<<endl;
1861 os<<LogIO::WARN<<"No reference to GBT_GO table."<<LogIO::POST;
[1391]1862 ret = 1;
1863 }
1864 return ret;
1865}
1866
[1730]1867std::vector<double> Scantable::getDirectionVector(int whichrow) const
[1391]1868{
1869 Vector<Double> Dir = dirCol_(whichrow).getAngle("rad").getValue();
1870 std::vector<double> dir;
1871 Dir.tovector(dir);
1872 return dir;
1873}
1874
[1819]1875void asap::Scantable::reshapeSpectrum( int nmin, int nmax )
1876 throw( casa::AipsError )
1877{
1878 // assumed that all rows have same nChan
1879 Vector<Float> arr = specCol_( 0 ) ;
1880 int nChan = arr.nelements() ;
1881
1882 // if nmin < 0 or nmax < 0, nothing to do
1883 if ( nmin < 0 ) {
1884 throw( casa::indexError<int>( nmin, "asap::Scantable::reshapeSpectrum: Invalid range. Negative index is specified." ) ) ;
1885 }
1886 if ( nmax < 0 ) {
1887 throw( casa::indexError<int>( nmax, "asap::Scantable::reshapeSpectrum: Invalid range. Negative index is specified." ) ) ;
1888 }
1889
1890 // if nmin > nmax, exchange values
1891 if ( nmin > nmax ) {
1892 int tmp = nmax ;
1893 nmax = nmin ;
1894 nmin = tmp ;
1895 LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1896 os << "Swap values. Applied range is ["
1897 << nmin << ", " << nmax << "]" << LogIO::POST ;
1898 }
1899
1900 // if nmin exceeds nChan, nothing to do
1901 if ( nmin >= nChan ) {
1902 throw( casa::indexError<int>( nmin, "asap::Scantable::reshapeSpectrum: Invalid range. Specified minimum exceeds nChan." ) ) ;
1903 }
1904
1905 // if nmax exceeds nChan, reset nmax to nChan
[2672]1906 if ( nmax >= nChan-1 ) {
[1819]1907 if ( nmin == 0 ) {
1908 // nothing to do
1909 LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1910 os << "Whole range is selected. Nothing to do." << LogIO::POST ;
1911 return ;
1912 }
1913 else {
1914 LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1915 os << "Specified maximum exceeds nChan. Applied range is ["
1916 << nmin << ", " << nChan-1 << "]." << LogIO::POST ;
1917 nmax = nChan - 1 ;
1918 }
1919 }
1920
1921 // reshape specCol_ and flagCol_
1922 for ( int irow = 0 ; irow < nrow() ; irow++ ) {
1923 reshapeSpectrum( nmin, nmax, irow ) ;
1924 }
1925
1926 // update FREQUENCIES subtable
[2908]1927 Vector<uInt> freqIdArray = mfreqidCol_.getColumn();
1928 uInt numFreqId = GenSort<uInt>::sort(freqIdArray, Sort::Ascending,
1929 Sort::HeapSort | Sort::NoDuplicates);
[1819]1930 Double refpix ;
1931 Double refval ;
1932 Double increment ;
[2908]1933 for (uInt irow = 0; irow < numFreqId; irow++) {
1934 freqTable_.getEntry( refpix, refval, increment, freqIdArray[irow] ) ;
[1819]1935 /***
1936 * need to shift refpix to nmin
1937 * note that channel nmin in old index will be channel 0 in new one
1938 ***/
1939 refval = refval - ( refpix - nmin ) * increment ;
1940 refpix = 0 ;
[2908]1941 freqTable_.setEntry( refpix, refval, increment, freqIdArray[irow] ) ;
[1819]1942 }
1943
1944 // update nchan
1945 int newsize = nmax - nmin + 1 ;
1946 table_.rwKeywordSet().define( "nChan", newsize ) ;
1947
1948 // update bandwidth
1949 // assumed all spectra in the scantable have same bandwidth
1950 table_.rwKeywordSet().define( "Bandwidth", increment * newsize ) ;
1951
1952 return ;
1953}
1954
1955void asap::Scantable::reshapeSpectrum( int nmin, int nmax, int irow )
1956{
1957 // reshape specCol_ and flagCol_
1958 Vector<Float> oldspec = specCol_( irow ) ;
1959 Vector<uChar> oldflag = flagsCol_( irow ) ;
[2475]1960 Vector<Float> oldtsys = tsysCol_( irow ) ;
[1819]1961 uInt newsize = nmax - nmin + 1 ;
[2475]1962 Slice slice( nmin, newsize, 1 ) ;
1963 specCol_.put( irow, oldspec( slice ) ) ;
1964 flagsCol_.put( irow, oldflag( slice ) ) ;
1965 if ( oldspec.size() == oldtsys.size() )
1966 tsysCol_.put( irow, oldtsys( slice ) ) ;
[1819]1967
1968 return ;
1969}
1970
[2435]1971void asap::Scantable::regridSpecChannel( double dnu, int nChan )
1972{
1973 LogIO os( LogOrigin( "Scantable", "regridChannel()", WHERE ) ) ;
1974 os << "Regrid abcissa with spectral resoultion " << dnu << " " << freqTable_.getUnitString() << " with channel number " << ((nChan>0)? String(nChan) : "covering band width")<< LogIO::POST ;
1975 int freqnrow = freqTable_.table().nrow() ;
1976 Vector<bool> firstTime( freqnrow, true ) ;
1977 double oldincr, factor;
1978 uInt currId;
1979 Double refpix ;
1980 Double refval ;
1981 Double increment ;
1982 for ( int irow = 0 ; irow < nrow() ; irow++ ) {
1983 currId = mfreqidCol_(irow);
1984 vector<double> abcissa = getAbcissa( irow ) ;
1985 if (nChan < 0) {
1986 int oldsize = abcissa.size() ;
1987 double bw = (abcissa[oldsize-1]-abcissa[0]) + \
1988 0.5 * (abcissa[1]-abcissa[0] + abcissa[oldsize-1]-abcissa[oldsize-2]) ;
1989 nChan = int( ceil( abs(bw/dnu) ) ) ;
1990 }
1991 // actual regridding
1992 regridChannel( nChan, dnu, irow ) ;
[2433]1993
[2435]1994 // update FREQUENCIES subtable
1995 if (firstTime[currId]) {
1996 oldincr = abcissa[1]-abcissa[0] ;
1997 factor = dnu/oldincr ;
1998 firstTime[currId] = false ;
1999 freqTable_.getEntry( refpix, refval, increment, currId ) ;
[2463]2000
[2437]2001 //refval = refval - ( refpix + 0.5 * (1 - factor) ) * increment ;
[2463]2002 if (factor > 0 ) {
[2462]2003 refpix = (refpix + 0.5)/factor - 0.5;
2004 } else {
[2463]2005 refpix = (abcissa.size() - 0.5 - refpix)/abs(factor) - 0.5;
[2462]2006 }
[2435]2007 freqTable_.setEntry( refpix, refval, increment*factor, currId ) ;
[2463]2008 //os << "ID" << currId << ": channel width (Orig) = " << oldincr << " [" << freqTable_.getUnitString() << "], scale factor = " << factor << LogIO::POST ;
2009 //os << " frequency increment (Orig) = " << increment << "-> (New) " << increment*factor << LogIO::POST ;
[2435]2010 }
2011 }
2012}
2013
[1819]2014void asap::Scantable::regridChannel( int nChan, double dnu )
2015{
2016 LogIO os( LogOrigin( "Scantable", "regridChannel()", WHERE ) ) ;
2017 os << "Regrid abcissa with channel number " << nChan << " and spectral resoultion " << dnu << "Hz." << LogIO::POST ;
2018 // assumed that all rows have same nChan
2019 Vector<Float> arr = specCol_( 0 ) ;
2020 int oldsize = arr.nelements() ;
2021
2022 // if oldsize == nChan, nothing to do
2023 if ( oldsize == nChan ) {
2024 os << "Specified channel number is same as current one. Nothing to do." << LogIO::POST ;
2025 return ;
2026 }
2027
2028 // if oldChan < nChan, unphysical operation
2029 if ( oldsize < nChan ) {
2030 os << "Unphysical operation. Nothing to do." << LogIO::POST ;
2031 return ;
2032 }
2033
[2433]2034 // change channel number for specCol_, flagCol_, and tsysCol_ (if necessary)
[1819]2035 vector<string> coordinfo = getCoordInfo() ;
2036 string oldinfo = coordinfo[0] ;
2037 coordinfo[0] = "Hz" ;
2038 setCoordInfo( coordinfo ) ;
2039 for ( int irow = 0 ; irow < nrow() ; irow++ ) {
2040 regridChannel( nChan, dnu, irow ) ;
2041 }
2042 coordinfo[0] = oldinfo ;
2043 setCoordInfo( coordinfo ) ;
2044
2045
2046 // NOTE: this method does not update metadata such as
2047 // FREQUENCIES subtable, nChan, Bandwidth, etc.
2048
2049 return ;
2050}
2051
2052void asap::Scantable::regridChannel( int nChan, double dnu, int irow )
2053{
2054 // logging
2055 //ofstream ofs( "average.log", std::ios::out | std::ios::app ) ;
2056 //ofs << "IFNO = " << getIF( irow ) << " irow = " << irow << endl ;
2057
2058 Vector<Float> oldspec = specCol_( irow ) ;
2059 Vector<uChar> oldflag = flagsCol_( irow ) ;
[2431]2060 Vector<Float> oldtsys = tsysCol_( irow ) ;
[1819]2061 Vector<Float> newspec( nChan, 0 ) ;
[2431]2062 Vector<uChar> newflag( nChan, true ) ;
2063 Vector<Float> newtsys ;
2064 bool regridTsys = false ;
2065 if (oldtsys.size() == oldspec.size()) {
2066 regridTsys = true ;
2067 newtsys.resize(nChan,false) ;
2068 newtsys = 0 ;
2069 }
[1819]2070
2071 // regrid
2072 vector<double> abcissa = getAbcissa( irow ) ;
2073 int oldsize = abcissa.size() ;
2074 double olddnu = abcissa[1] - abcissa[0] ;
[2462]2075 //int ichan = 0 ;
[1819]2076 double wsum = 0.0 ;
[2433]2077 Vector<double> zi( nChan+1 ) ;
2078 Vector<double> yi( oldsize + 1 ) ;
[1819]2079 yi[0] = abcissa[0] - 0.5 * olddnu ;
[2431]2080 for ( int ii = 1 ; ii < oldsize ; ii++ )
[2433]2081 yi[ii] = 0.5* (abcissa[ii-1] + abcissa[ii]) ;
2082 yi[oldsize] = abcissa[oldsize-1] \
2083 + 0.5 * (abcissa[oldsize-1] - abcissa[oldsize-2]) ;
[2462]2084 //zi[0] = abcissa[0] - 0.5 * olddnu ;
2085 zi[0] = ((olddnu*dnu > 0) ? yi[0] : yi[oldsize]) ;
2086 for ( int ii = 1 ; ii < nChan ; ii++ )
2087 zi[ii] = zi[0] + dnu * ii ;
2088 zi[nChan] = zi[nChan-1] + dnu ;
2089 // Access zi and yi in ascending order
2090 int izs = ((dnu > 0) ? 0 : nChan ) ;
2091 int ize = ((dnu > 0) ? nChan : 0 ) ;
2092 int izincr = ((dnu > 0) ? 1 : -1 ) ;
2093 int ichan = ((olddnu > 0) ? 0 : oldsize ) ;
2094 int iye = ((olddnu > 0) ? oldsize : 0 ) ;
2095 int iyincr = ((olddnu > 0) ? 1 : -1 ) ;
2096 //for ( int ii = izs ; ii != ize ; ii+=izincr ){
2097 int ii = izs ;
2098 while (ii != ize) {
2099 // always zl < zr
2100 double zl = zi[ii] ;
2101 double zr = zi[ii+izincr] ;
2102 // Need to access smaller index for the new spec, flag, and tsys.
2103 // Values between zi[k] and zi[k+1] should be stored in newspec[k], etc.
2104 int i = min(ii, ii+izincr) ;
2105 //for ( int jj = ichan ; jj != iye ; jj+=iyincr ) {
2106 int jj = ichan ;
2107 while (jj != iye) {
2108 // always yl < yr
2109 double yl = yi[jj] ;
2110 double yr = yi[jj+iyincr] ;
2111 // Need to access smaller index for the original spec, flag, and tsys.
2112 // Values between yi[k] and yi[k+1] are stored in oldspec[k], etc.
2113 int j = min(jj, jj+iyincr) ;
2114 if ( yr <= zl ) {
2115 jj += iyincr ;
2116 continue ;
[1819]2117 }
[2462]2118 else if ( yl <= zl ) {
2119 if ( yr < zr ) {
2120 if (!oldflag[j]) {
2121 newspec[i] += oldspec[j] * ( yr - zl ) ;
2122 if (regridTsys) newtsys[i] += oldtsys[j] * ( yr - zl ) ;
2123 wsum += ( yr - zl ) ;
2124 }
[2950]2125 newflag[i] = (newflag[i] && oldflag[j]) ? 1 << 7 : 0 ;
[2462]2126 }
2127 else {
2128 if (!oldflag[j]) {
2129 newspec[i] += oldspec[j] * abs(dnu) ;
2130 if (regridTsys) newtsys[i] += oldtsys[j] * abs(dnu) ;
2131 wsum += abs(dnu) ;
2132 }
[2950]2133 newflag[i] = (newflag[i] && oldflag[j]) ? 1 << 7 : 0 ;
[2462]2134 ichan = jj ;
2135 break ;
2136 }
[2431]2137 }
[2462]2138 else if ( yl < zr ) {
2139 if ( yr <= zr ) {
2140 if (!oldflag[j]) {
2141 newspec[i] += oldspec[j] * ( yr - yl ) ;
2142 if (regridTsys) newtsys[i] += oldtsys[j] * ( yr - yl ) ;
2143 wsum += ( yr - yl ) ;
2144 }
[2950]2145 newflag[i] = (newflag[i] && oldflag[j]) ? 1 << 7 : 0 ;
[2462]2146 }
2147 else {
2148 if (!oldflag[j]) {
2149 newspec[i] += oldspec[j] * ( zr - yl ) ;
2150 if (regridTsys) newtsys[i] += oldtsys[j] * ( zr - yl ) ;
2151 wsum += ( zr - yl ) ;
2152 }
[2950]2153 newflag[i] = (newflag[i] && oldflag[j]) ? 1 << 7 : 0 ;
[2462]2154 ichan = jj ;
2155 break ;
2156 }
[1819]2157 }
[2462]2158 else {
2159 ichan = jj - iyincr ;
2160 break ;
[2431]2161 }
[2462]2162 jj += iyincr ;
[1819]2163 }
[2462]2164 if ( wsum != 0.0 ) {
2165 newspec[i] /= wsum ;
2166 if (regridTsys) newtsys[i] /= wsum ;
2167 }
2168 wsum = 0.0 ;
2169 ii += izincr ;
[1819]2170 }
[2462]2171// if ( dnu > 0.0 ) {
2172// for ( int ii = 0 ; ii < nChan ; ii++ ) {
2173// double zl = zi[ii] ;
2174// double zr = zi[ii+1] ;
2175// for ( int j = ichan ; j < oldsize ; j++ ) {
2176// double yl = yi[j] ;
2177// double yr = yi[j+1] ;
2178// if ( yl <= zl ) {
2179// if ( yr <= zl ) {
2180// continue ;
2181// }
2182// else if ( yr <= zr ) {
2183// if (!oldflag[j]) {
2184// newspec[ii] += oldspec[j] * ( yr - zl ) ;
2185// if (regridTsys) newtsys[ii] += oldtsys[j] * ( yr - zl ) ;
2186// wsum += ( yr - zl ) ;
2187// }
2188// newflag[ii] = newflag[ii] && oldflag[j] ;
2189// }
2190// else {
2191// if (!oldflag[j]) {
2192// newspec[ii] += oldspec[j] * dnu ;
2193// if (regridTsys) newtsys[ii] += oldtsys[j] * dnu ;
2194// wsum += dnu ;
2195// }
2196// newflag[ii] = newflag[ii] && oldflag[j] ;
2197// ichan = j ;
2198// break ;
2199// }
2200// }
2201// else if ( yl < zr ) {
2202// if ( yr <= zr ) {
2203// if (!oldflag[j]) {
2204// newspec[ii] += oldspec[j] * ( yr - yl ) ;
2205// if (regridTsys) newtsys[ii] += oldtsys[j] * ( yr - yl ) ;
2206// wsum += ( yr - yl ) ;
2207// }
2208// newflag[ii] = newflag[ii] && oldflag[j] ;
2209// }
2210// else {
2211// if (!oldflag[j]) {
2212// newspec[ii] += oldspec[j] * ( zr - yl ) ;
2213// if (regridTsys) newtsys[ii] += oldtsys[j] * ( zr - yl ) ;
2214// wsum += ( zr - yl ) ;
2215// }
2216// newflag[ii] = newflag[ii] && oldflag[j] ;
2217// ichan = j ;
2218// break ;
2219// }
2220// }
2221// else {
2222// ichan = j - 1 ;
2223// break ;
2224// }
2225// }
2226// if ( wsum != 0.0 ) {
2227// newspec[ii] /= wsum ;
2228// if (regridTsys) newtsys[ii] /= wsum ;
2229// }
2230// wsum = 0.0 ;
2231// }
[1819]2232// }
[2462]2233// else if ( dnu < 0.0 ) {
2234// for ( int ii = 0 ; ii < nChan ; ii++ ) {
2235// double zl = zi[ii] ;
2236// double zr = zi[ii+1] ;
2237// for ( int j = ichan ; j < oldsize ; j++ ) {
2238// double yl = yi[j] ;
2239// double yr = yi[j+1] ;
2240// if ( yl >= zl ) {
2241// if ( yr >= zl ) {
2242// continue ;
2243// }
2244// else if ( yr >= zr ) {
2245// if (!oldflag[j]) {
2246// newspec[ii] += oldspec[j] * abs( yr - zl ) ;
2247// if (regridTsys) newtsys[ii] += oldtsys[j] * abs( yr - zl ) ;
2248// wsum += abs( yr - zl ) ;
2249// }
2250// newflag[ii] = newflag[ii] && oldflag[j] ;
2251// }
2252// else {
2253// if (!oldflag[j]) {
2254// newspec[ii] += oldspec[j] * abs( dnu ) ;
2255// if (regridTsys) newtsys[ii] += oldtsys[j] * abs( dnu ) ;
2256// wsum += abs( dnu ) ;
2257// }
2258// newflag[ii] = newflag[ii] && oldflag[j] ;
2259// ichan = j ;
2260// break ;
2261// }
2262// }
2263// else if ( yl > zr ) {
2264// if ( yr >= zr ) {
2265// if (!oldflag[j]) {
2266// newspec[ii] += oldspec[j] * abs( yr - yl ) ;
2267// if (regridTsys) newtsys[ii] += oldtsys[j] * abs( yr - yl ) ;
2268// wsum += abs( yr - yl ) ;
2269// }
2270// newflag[ii] = newflag[ii] && oldflag[j] ;
2271// }
2272// else {
2273// if (!oldflag[j]) {
2274// newspec[ii] += oldspec[j] * abs( zr - yl ) ;
2275// if (regridTsys) newtsys[ii] += oldtsys[j] * abs( zr - yl ) ;
2276// wsum += abs( zr - yl ) ;
2277// }
2278// newflag[ii] = newflag[ii] && oldflag[j] ;
2279// ichan = j ;
2280// break ;
2281// }
2282// }
2283// else {
2284// ichan = j - 1 ;
2285// break ;
2286// }
2287// }
2288// if ( wsum != 0.0 ) {
2289// newspec[ii] /= wsum ;
2290// if (regridTsys) newtsys[ii] /= wsum ;
2291// }
2292// wsum = 0.0 ;
[1819]2293// }
2294// }
[2462]2295// // //ofs << "olddnu = " << olddnu << ", dnu = " << dnu << endl ;
2296// // pile += dnu ;
2297// // wedge = olddnu * ( refChan + 1 ) ;
2298// // while ( wedge < pile ) {
2299// // newspec[0] += olddnu * oldspec[refChan] ;
2300// // newflag[0] = newflag[0] || oldflag[refChan] ;
2301// // //ofs << "channel " << refChan << " is included in new channel 0" << endl ;
2302// // refChan++ ;
2303// // wedge += olddnu ;
2304// // wsum += olddnu ;
2305// // //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
2306// // }
2307// // frac = ( wedge - pile ) / olddnu ;
2308// // wsum += ( 1.0 - frac ) * olddnu ;
2309// // newspec[0] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
2310// // newflag[0] = newflag[0] || oldflag[refChan] ;
2311// // //ofs << "channel " << refChan << " is partly included in new channel 0" << " with fraction of " << ( 1.0 - frac ) << endl ;
2312// // //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
2313// // newspec[0] /= wsum ;
2314// // //ofs << "newspec[0] = " << newspec[0] << endl ;
2315// // //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
[1819]2316
[2462]2317// // /***
2318// // * ichan = 1 - nChan-2
2319// // ***/
2320// // for ( int ichan = 1 ; ichan < nChan - 1 ; ichan++ ) {
2321// // pile += dnu ;
2322// // newspec[ichan] += frac * olddnu * oldspec[refChan] ;
2323// // newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
2324// // //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << frac << endl ;
2325// // refChan++ ;
2326// // wedge += olddnu ;
2327// // wsum = frac * olddnu ;
2328// // //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
2329// // while ( wedge < pile ) {
2330// // newspec[ichan] += olddnu * oldspec[refChan] ;
2331// // newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
2332// // //ofs << "channel " << refChan << " is included in new channel " << ichan << endl ;
2333// // refChan++ ;
2334// // wedge += olddnu ;
2335// // wsum += olddnu ;
2336// // //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
2337// // }
2338// // frac = ( wedge - pile ) / olddnu ;
2339// // wsum += ( 1.0 - frac ) * olddnu ;
2340// // newspec[ichan] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
2341// // newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
2342// // //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << ( 1.0 - frac ) << endl ;
2343// // //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
2344// // //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
2345// // newspec[ichan] /= wsum ;
2346// // //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << endl ;
2347// // }
[1819]2348
[2462]2349// // /***
2350// // * ichan = nChan-1
2351// // ***/
2352// // // NOTE: Assumed that all spectra have the same bandwidth
2353// // pile += dnu ;
2354// // newspec[nChan-1] += frac * olddnu * oldspec[refChan] ;
2355// // newflag[nChan-1] = newflag[nChan-1] || oldflag[refChan] ;
2356// // //ofs << "channel " << refChan << " is partly included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
2357// // refChan++ ;
2358// // wedge += olddnu ;
2359// // wsum = frac * olddnu ;
2360// // //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
2361// // for ( int jchan = refChan ; jchan < oldsize ; jchan++ ) {
2362// // newspec[nChan-1] += olddnu * oldspec[jchan] ;
2363// // newflag[nChan-1] = newflag[nChan-1] || oldflag[jchan] ;
2364// // wsum += olddnu ;
2365// // //ofs << "channel " << jchan << " is included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
2366// // //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
2367// // }
2368// // //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
2369// // //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
2370// // newspec[nChan-1] /= wsum ;
2371// // //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << endl ;
[1819]2372
[2462]2373// // // ofs.close() ;
2374
[2032]2375 specCol_.put( irow, newspec ) ;
2376 flagsCol_.put( irow, newflag ) ;
[2431]2377 if (regridTsys) tsysCol_.put( irow, newtsys );
[1819]2378
2379 return ;
2380}
2381
[2595]2382void Scantable::regridChannel( int nChan, double dnu, double fmin, int irow )
2383{
2384 Vector<Float> oldspec = specCol_( irow ) ;
2385 Vector<uChar> oldflag = flagsCol_( irow ) ;
2386 Vector<Float> oldtsys = tsysCol_( irow ) ;
2387 Vector<Float> newspec( nChan, 0 ) ;
2388 Vector<uChar> newflag( nChan, true ) ;
2389 Vector<Float> newtsys ;
2390 bool regridTsys = false ;
2391 if (oldtsys.size() == oldspec.size()) {
2392 regridTsys = true ;
2393 newtsys.resize(nChan,false) ;
2394 newtsys = 0 ;
2395 }
2396
2397 // regrid
2398 vector<double> abcissa = getAbcissa( irow ) ;
2399 int oldsize = abcissa.size() ;
2400 double olddnu = abcissa[1] - abcissa[0] ;
2401 //int ichan = 0 ;
2402 double wsum = 0.0 ;
2403 Vector<double> zi( nChan+1 ) ;
2404 Vector<double> yi( oldsize + 1 ) ;
2405 Block<uInt> count( nChan, 0 ) ;
2406 yi[0] = abcissa[0] - 0.5 * olddnu ;
2407 for ( int ii = 1 ; ii < oldsize ; ii++ )
2408 yi[ii] = 0.5* (abcissa[ii-1] + abcissa[ii]) ;
2409 yi[oldsize] = abcissa[oldsize-1] \
2410 + 0.5 * (abcissa[oldsize-1] - abcissa[oldsize-2]) ;
2411// cout << "olddnu=" << olddnu << ", dnu=" << dnu << " (diff=" << olddnu-dnu << ")" << endl ;
2412// cout << "yi[0]=" << yi[0] << ", fmin=" << fmin << " (diff=" << yi[0]-fmin << ")" << endl ;
2413// cout << "oldsize=" << oldsize << ", nChan=" << nChan << endl ;
2414
2415 // do not regrid if input parameters are almost same as current
2416 // spectral setup
2417 double dnuDiff = abs( ( dnu - olddnu ) / olddnu ) ;
2418 double oldfmin = min( yi[0], yi[oldsize] ) ;
2419 double fminDiff = abs( ( fmin - oldfmin ) / oldfmin ) ;
2420 double nChanDiff = nChan - oldsize ;
2421 double eps = 1.0e-8 ;
2422 if ( nChanDiff == 0 && dnuDiff < eps && fminDiff < eps )
2423 return ;
2424
2425 //zi[0] = abcissa[0] - 0.5 * olddnu ;
2426 //zi[0] = ((olddnu*dnu > 0) ? yi[0] : yi[oldsize]) ;
2427 if ( dnu > 0 )
2428 zi[0] = fmin - 0.5 * dnu ;
2429 else
2430 zi[0] = fmin + nChan * abs(dnu) ;
2431 for ( int ii = 1 ; ii < nChan ; ii++ )
2432 zi[ii] = zi[0] + dnu * ii ;
2433 zi[nChan] = zi[nChan-1] + dnu ;
2434 // Access zi and yi in ascending order
2435 int izs = ((dnu > 0) ? 0 : nChan ) ;
2436 int ize = ((dnu > 0) ? nChan : 0 ) ;
2437 int izincr = ((dnu > 0) ? 1 : -1 ) ;
2438 int ichan = ((olddnu > 0) ? 0 : oldsize ) ;
2439 int iye = ((olddnu > 0) ? oldsize : 0 ) ;
2440 int iyincr = ((olddnu > 0) ? 1 : -1 ) ;
2441 //for ( int ii = izs ; ii != ize ; ii+=izincr ){
2442 int ii = izs ;
2443 while (ii != ize) {
2444 // always zl < zr
2445 double zl = zi[ii] ;
2446 double zr = zi[ii+izincr] ;
2447 // Need to access smaller index for the new spec, flag, and tsys.
2448 // Values between zi[k] and zi[k+1] should be stored in newspec[k], etc.
2449 int i = min(ii, ii+izincr) ;
2450 //for ( int jj = ichan ; jj != iye ; jj+=iyincr ) {
2451 int jj = ichan ;
2452 while (jj != iye) {
2453 // always yl < yr
2454 double yl = yi[jj] ;
2455 double yr = yi[jj+iyincr] ;
2456 // Need to access smaller index for the original spec, flag, and tsys.
2457 // Values between yi[k] and yi[k+1] are stored in oldspec[k], etc.
2458 int j = min(jj, jj+iyincr) ;
2459 if ( yr <= zl ) {
2460 jj += iyincr ;
2461 continue ;
2462 }
2463 else if ( yl <= zl ) {
2464 if ( yr < zr ) {
2465 if (!oldflag[j]) {
2466 newspec[i] += oldspec[j] * ( yr - zl ) ;
2467 if (regridTsys) newtsys[i] += oldtsys[j] * ( yr - zl ) ;
2468 wsum += ( yr - zl ) ;
2469 count[i]++ ;
2470 }
2471 newflag[i] = newflag[i] && oldflag[j] ;
2472 }
2473 else {
2474 if (!oldflag[j]) {
2475 newspec[i] += oldspec[j] * abs(dnu) ;
2476 if (regridTsys) newtsys[i] += oldtsys[j] * abs(dnu) ;
2477 wsum += abs(dnu) ;
2478 count[i]++ ;
2479 }
2480 newflag[i] = newflag[i] && oldflag[j] ;
2481 ichan = jj ;
2482 break ;
2483 }
2484 }
2485 else if ( yl < zr ) {
2486 if ( yr <= zr ) {
2487 if (!oldflag[j]) {
2488 newspec[i] += oldspec[j] * ( yr - yl ) ;
2489 if (regridTsys) newtsys[i] += oldtsys[j] * ( yr - yl ) ;
2490 wsum += ( yr - yl ) ;
2491 count[i]++ ;
2492 }
2493 newflag[i] = newflag[i] && oldflag[j] ;
2494 }
2495 else {
2496 if (!oldflag[j]) {
2497 newspec[i] += oldspec[j] * ( zr - yl ) ;
2498 if (regridTsys) newtsys[i] += oldtsys[j] * ( zr - yl ) ;
2499 wsum += ( zr - yl ) ;
2500 count[i]++ ;
2501 }
2502 newflag[i] = newflag[i] && oldflag[j] ;
2503 ichan = jj ;
2504 break ;
2505 }
2506 }
2507 else {
2508 //ichan = jj - iyincr ;
2509 break ;
2510 }
2511 jj += iyincr ;
2512 }
2513 if ( wsum != 0.0 ) {
2514 newspec[i] /= wsum ;
2515 if (regridTsys) newtsys[i] /= wsum ;
2516 }
2517 wsum = 0.0 ;
2518 ii += izincr ;
2519 }
2520
2521 // flag out channels without data
2522 // this is tentative since there is no specific definition
2523 // on bit flag...
2524 uChar noData = 1 << 7 ;
2525 for ( Int i = 0 ; i < nChan ; i++ ) {
2526 if ( count[i] == 0 )
2527 newflag[i] = noData ;
2528 }
2529
2530 specCol_.put( irow, newspec ) ;
2531 flagsCol_.put( irow, newflag ) ;
2532 if (regridTsys) tsysCol_.put( irow, newtsys );
2533
2534 return ;
2535}
2536
[1730]2537std::vector<float> Scantable::getWeather(int whichrow) const
2538{
2539 std::vector<float> out(5);
2540 //Float temperature, pressure, humidity, windspeed, windaz;
2541 weatherTable_.getEntry(out[0], out[1], out[2], out[3], out[4],
2542 mweatheridCol_(uInt(whichrow)));
2543
2544
2545 return out;
[1391]2546}
[1730]2547
[2831]2548bool Scantable::isAllChannelsFlagged(uInt whichrow)
[1907]2549{
[2831]2550 uInt rflag;
2551 flagrowCol_.get(whichrow, rflag);
2552 if (rflag > 0)
2553 return true;
[3023]2554 bool flag;
[1907]2555 Vector<uChar> flags;
[2047]2556 flagsCol_.get(whichrow, flags);
[3023]2557 flag = (flags[0]>0);
[2047]2558 for (uInt i = 1; i < flags.size(); ++i) {
[3023]2559 flag &= (flags[i]>0);
[2012]2560 }
[2837]2561 // return ((flag >> 7) == 1);
2562 return (flag > 0);
[2012]2563}
2564
[3023]2565std::size_t Scantable::nValidMask(const std::vector<bool>& mask)
2566{
2567 std::size_t nvalid=0;
2568 assert(static_cast<std::size_t>(true)==1);
2569 assert(static_cast<std::size_t>(false)==0);
2570 for (uInt i = 1; i < mask.size(); ++i) {
2571 nvalid += static_cast<std::size_t>(mask[i]);
2572 }
2573 return nvalid;
2574}
2575
2576
[2811]2577std::vector<std::string> Scantable::applyBaselineTable(const std::string& bltable, const bool returnfitresult, const std::string& outbltable, const bool outbltableexists, const bool overwrite)
[2047]2578{
[2773]2579 STBaselineTable btin = STBaselineTable(bltable);
[2767]2580
[2773]2581 Vector<Bool> applyCol = btin.getApply();
[2767]2582 int nRowBl = applyCol.size();
2583 if (nRowBl != nrow()) {
2584 throw(AipsError("Scantable and bltable have different number of rows."));
2585 }
2586
2587 std::vector<std::string> res;
2588 res.clear();
2589
2590 bool outBaselineTable = ((outbltable != "") && (!outbltableexists || overwrite));
2591 bool bltableidentical = (bltable == outbltable);
[2773]2592 STBaselineTable btout = STBaselineTable(*this);
2593 ROScalarColumn<Double> tcol = ROScalarColumn<Double>(table_, "TIME");
2594 Vector<Double> timeSecCol = tcol.getColumn();
[2767]2595
2596 for (int whichrow = 0; whichrow < nRowBl; ++whichrow) {
2597 if (applyCol[whichrow]) {
2598 std::vector<float> spec = getSpectrum(whichrow);
2599
[2773]2600 std::vector<bool> mask = btin.getMask(whichrow); //use mask_bltable only
[2767]2601
[2773]2602 STBaselineFunc::FuncName ftype = btin.getFunctionName(whichrow);
2603 std::vector<int> fpar = btin.getFuncParam(whichrow);
[2767]2604 std::vector<float> params;
2605 float rms;
2606 std::vector<float> resfit = doApplyBaselineTable(spec, mask, ftype, fpar, params, rms);
2607 setSpectrum(resfit, whichrow);
2608
[2811]2609 if (returnfitresult) {
2610 res.push_back(packFittingResults(whichrow, params, rms));
2611 }
[2767]2612
2613 if (outBaselineTable) {
2614 if (outbltableexists) {
2615 if (overwrite) {
2616 if (bltableidentical) {
[2773]2617 btin.setresult(uInt(whichrow), Vector<Float>(params), Float(rms));
[2767]2618 } else {
[2773]2619 btout.setresult(uInt(whichrow), Vector<Float>(params), Float(rms));
[2767]2620 }
2621 }
2622 } else {
[2773]2623 btout.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
2624 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
2625 true, ftype, fpar, std::vector<float>(),
2626 getMaskListFromMask(mask), params, rms, spec.size(),
2627 3.0, 0, 0.0, 0, std::vector<int>());
[2767]2628 }
2629 }
2630 }
2631 }
2632
2633 if (outBaselineTable) {
2634 if (bltableidentical) {
[2773]2635 btin.save(outbltable);
[2767]2636 } else {
[2773]2637 btout.save(outbltable);
[2767]2638 }
2639 }
2640
2641 return res;
2642}
2643
[2811]2644std::vector<std::string> Scantable::subBaseline(const std::vector<std::string>& blInfoList, const bool returnfitresult, const std::string& outbltable, const bool outbltableexists, const bool overwrite)
[2767]2645{
2646 int nRowBl = blInfoList.size();
2647 int nRowSt = nrow();
2648
2649 std::vector<std::string> res;
2650 res.clear();
2651
2652 bool outBaselineTable = ((outbltable != "") && (!outbltableexists || overwrite));
2653 if ((outbltable != "") && outbltableexists && !overwrite) {
2654 throw(AipsError("Cannot overwrite bltable. Set overwrite=True."));
2655 }
2656
[2883]2657 STBaselineTable* btp;
[2773]2658 ROScalarColumn<Double> tcol = ROScalarColumn<Double>(table_, "TIME");
2659 Vector<Double> timeSecCol = tcol.getColumn();
[2767]2660
[2883]2661 if (outBaselineTable) {
2662 if (outbltableexists) {
2663 btp = new STBaselineTable((String)outbltable);
2664 } else {
2665 btp = new STBaselineTable(*this);
[3009]2666 // for (int i = 0; i < nRowSt; ++i) {
2667 // btp->appendbasedata(getScan(i), getCycle(i), getBeam(i), getIF(i), getPol(i),
2668 // 0, timeSecCol[i]);
2669 // btp->setApply(i, false);
2670 // }
[2767]2671 }
[3009]2672 int nrow = btp->nrow();
2673 for (int i = nrow; i < nRowSt; ++i) {
2674 btp->appendbasedata(getScan(i), getCycle(i), getBeam(i), getIF(i), getPol(i),
2675 0, timeSecCol[i]);
2676 btp->setApply(i, false);
2677 }
[2767]2678 }
2679
2680 for (int i = 0; i < nRowBl; ++i) {
2681 int irow;
2682 STBaselineFunc::FuncName ftype;
2683 std::vector<bool> mask;
2684 std::vector<int> fpar;
2685 float clipth;
2686 int clipn;
2687 bool uself;
2688 float lfth;
2689 std::vector<int> lfedge;
2690 int lfavg;
2691 parseBlInfo(blInfoList[i], irow, ftype, fpar, mask, clipth, clipn, uself, lfth, lfedge, lfavg);
2692
2693 if (irow < nRowSt) {
2694 std::vector<float> spec = getSpectrum(irow);
2695 std::vector<float> params;
2696 float rms;
2697 std::vector<bool> finalmask;
[3009]2698 Bool doApply = True;
2699
[3018]2700 if (!isAllChannelsFlagged(irow)) {
[3009]2701 std::vector<float> resfit = doSubtractBaseline(spec, mask, ftype, fpar, params, rms, finalmask, clipth, clipn, uself, irow, lfth, lfedge, lfavg);
2702 setSpectrum(resfit, irow);
2703 }
2704 else {
2705 doApply = False;
2706 }
[2767]2707
[2811]2708 if (returnfitresult) {
2709 res.push_back(packFittingResults(irow, params, rms));
2710 }
2711
[2767]2712 if (outBaselineTable) {
2713 Vector<Int> fparam(fpar.size());
2714 for (uInt j = 0; j < fparam.size(); ++j) {
2715 fparam[j] = (Int)fpar[j];
2716 }
2717
[2883]2718 btp->setdata(uInt(irow),
[2767]2719 uInt(getScan(irow)), uInt(getCycle(irow)),
2720 uInt(getBeam(irow)), uInt(getIF(irow)), uInt(getPol(irow)),
[3009]2721 uInt(0), timeSecCol[irow], doApply, ftype, fparam,
[2773]2722 Vector<Float>(), getMaskListFromMask(finalmask), Vector<Float>(params),
[2767]2723 Float(rms), uInt(spec.size()), Float(clipth), uInt(clipn),
2724 Float(0.0), uInt(0), Vector<uInt>());
2725 }
2726
2727 }
2728 }
2729
2730 if (outBaselineTable) {
[2883]2731 btp->save(outbltable);
[2767]2732 }
2733
[2883]2734 delete btp;
[2767]2735 return res;
2736}
2737
[2773]2738std::vector<float> Scantable::doApplyBaselineTable(std::vector<float>& spec,
2739 std::vector<bool>& mask,
2740 const STBaselineFunc::FuncName ftype,
2741 std::vector<int>& fpar,
2742 std::vector<float>& params,
2743 float&rms)
[2767]2744{
2745 std::vector<bool> finalmask;
2746 std::vector<int> lfedge;
2747 return doSubtractBaseline(spec, mask, ftype, fpar, params, rms, finalmask, 0.0, 0, false, 0, 0.0, lfedge, 0);
2748}
2749
[2774]2750std::vector<float> Scantable::doSubtractBaseline(std::vector<float>& spec,
2751 std::vector<bool>& mask,
2752 const STBaselineFunc::FuncName ftype,
2753 std::vector<int>& fpar,
2754 std::vector<float>& params,
2755 float&rms,
2756 std::vector<bool>& finalmask,
2757 float clipth,
2758 int clipn,
2759 bool uself,
2760 int irow,
2761 float lfth,
2762 std::vector<int>& lfedge,
2763 int lfavg)
[2767]2764{
2765 if (uself) {
2766 STLineFinder lineFinder = STLineFinder();
[2774]2767 initLineFinder(lfedge, lfth, lfavg, lineFinder);
[2767]2768 std::vector<int> currentEdge;
[2774]2769 mask = getCompositeChanMask(irow, mask, lfedge, currentEdge, lineFinder);
[2946]2770 } else {
2771 mask = getCompositeChanMask(irow, mask);
[2767]2772 }
2773
2774 std::vector<float> res;
2775 if (ftype == STBaselineFunc::Polynomial) {
2776 res = doPolynomialFitting(spec, mask, fpar[0], params, rms, finalmask, clipth, clipn);
2777 } else if (ftype == STBaselineFunc::Chebyshev) {
2778 res = doChebyshevFitting(spec, mask, fpar[0], params, rms, finalmask, clipth, clipn);
2779 } else if (ftype == STBaselineFunc::CSpline) {
2780 if (fpar.size() > 1) { // reading from baseline table in which pieceEdges are already calculated and stored.
2781 res = doCubicSplineFitting(spec, mask, fpar, params, rms, finalmask, clipth, clipn);
2782 } else { // usual cspline fitting by giving nPiece only. fpar will be replaced with pieceEdges.
2783 res = doCubicSplineFitting(spec, mask, fpar[0], fpar, params, rms, finalmask, clipth, clipn);
2784 }
2785 } else if (ftype == STBaselineFunc::Sinusoid) {
2786 res = doSinusoidFitting(spec, mask, fpar, params, rms, finalmask, clipth, clipn);
2787 }
2788
2789 return res;
2790}
2791
2792std::string Scantable::packFittingResults(const int irow, const std::vector<float>& params, const float rms)
2793{
2794 // returned value: "irow:params[0],params[1],..,params[n-1]:rms"
2795 ostringstream os;
2796 os << irow << ':';
2797 for (uInt i = 0; i < params.size(); ++i) {
2798 if (i > 0) {
2799 os << ',';
2800 }
2801 os << params[i];
2802 }
2803 os << ':' << rms;
2804
2805 return os.str();
2806}
2807
2808void Scantable::parseBlInfo(const std::string& blInfo, int& irow, STBaselineFunc::FuncName& ftype, std::vector<int>& fpar, std::vector<bool>& mask, float& thresClip, int& nIterClip, bool& useLineFinder, float& thresLF, std::vector<int>& edgeLF, int& avgLF)
2809{
2810 // The baseline info to be parsed must be column-delimited string like
2811 // "0:chebyshev:5:3,5,169,174,485,487" where the elements are
2812 // row number, funcType, funcOrder, maskList, clipThreshold, clipNIter,
2813 // useLineFinder, lfThreshold, lfEdge and lfChanAvgLimit.
2814
2815 std::vector<string> res = splitToStringList(blInfo, ':');
2816 if (res.size() < 4) {
2817 throw(AipsError("baseline info has bad format")) ;
2818 }
2819
2820 string ftype0, fpar0, masklist0, uself0, edge0;
2821 std::vector<int> masklist;
2822
2823 stringstream ss;
2824 ss << res[0];
2825 ss >> irow;
2826 ss.clear(); ss.str("");
2827
2828 ss << res[1];
2829 ss >> ftype0;
2830 if (ftype0 == "poly") {
2831 ftype = STBaselineFunc::Polynomial;
2832 } else if (ftype0 == "cspline") {
2833 ftype = STBaselineFunc::CSpline;
2834 } else if (ftype0 == "sinusoid") {
2835 ftype = STBaselineFunc::Sinusoid;
2836 } else if (ftype0 == "chebyshev") {
2837 ftype = STBaselineFunc::Chebyshev;
2838 } else {
2839 throw(AipsError("invalid function type."));
2840 }
2841 ss.clear(); ss.str("");
2842
2843 ss << res[2];
2844 ss >> fpar0;
2845 fpar = splitToIntList(fpar0, ',');
2846 ss.clear(); ss.str("");
2847
2848 ss << res[3];
2849 ss >> masklist0;
2850 mask = getMaskFromMaskList(nchan(getIF(irow)), splitToIntList(masklist0, ','));
[2883]2851 ss.clear(); ss.str("");
[2767]2852
2853 ss << res[4];
2854 ss >> thresClip;
2855 ss.clear(); ss.str("");
2856
2857 ss << res[5];
2858 ss >> nIterClip;
2859 ss.clear(); ss.str("");
2860
2861 ss << res[6];
2862 ss >> uself0;
2863 if (uself0 == "true") {
2864 useLineFinder = true;
2865 } else {
2866 useLineFinder = false;
2867 }
2868 ss.clear(); ss.str("");
2869
2870 if (useLineFinder) {
2871 ss << res[7];
2872 ss >> thresLF;
2873 ss.clear(); ss.str("");
2874
2875 ss << res[8];
2876 ss >> edge0;
2877 edgeLF = splitToIntList(edge0, ',');
2878 ss.clear(); ss.str("");
2879
2880 ss << res[9];
2881 ss >> avgLF;
2882 ss.clear(); ss.str("");
2883 }
2884
2885}
2886
2887std::vector<int> Scantable::splitToIntList(const std::string& s, const char delim)
2888{
2889 istringstream iss(s);
2890 string tmp;
2891 int tmpi;
2892 std::vector<int> res;
2893 stringstream ss;
2894 while (getline(iss, tmp, delim)) {
2895 ss << tmp;
2896 ss >> tmpi;
2897 res.push_back(tmpi);
2898 ss.clear(); ss.str("");
2899 }
2900
2901 return res;
2902}
2903
2904std::vector<string> Scantable::splitToStringList(const std::string& s, const char delim)
2905{
2906 istringstream iss(s);
2907 std::string tmp;
2908 std::vector<string> res;
2909 while (getline(iss, tmp, delim)) {
2910 res.push_back(tmp);
2911 }
2912
2913 return res;
2914}
2915
2916std::vector<bool> Scantable::getMaskFromMaskList(const int nchan, const std::vector<int>& masklist)
2917{
2918 if (masklist.size() % 2 != 0) {
2919 throw(AipsError("masklist must have even number of elements."));
2920 }
2921
2922 std::vector<bool> res(nchan);
2923
2924 for (int i = 0; i < nchan; ++i) {
2925 res[i] = false;
2926 }
2927 for (uInt j = 0; j < masklist.size(); j += 2) {
[3009]2928 for (int i = masklist[j]; i <= min(nchan-1, masklist[j+1]); ++i) {
[2767]2929 res[i] = true;
2930 }
2931 }
2932
2933 return res;
2934}
2935
[2773]2936Vector<uInt> Scantable::getMaskListFromMask(const std::vector<bool>& mask)
[2767]2937{
[2773]2938 std::vector<int> masklist;
2939 masklist.clear();
2940
2941 for (uInt i = 0; i < mask.size(); ++i) {
2942 if (mask[i]) {
2943 if ((i == 0)||(i == mask.size()-1)) {
2944 masklist.push_back(i);
2945 } else {
2946 if ((mask[i])&&(!mask[i-1])) {
2947 masklist.push_back(i);
2948 }
2949 if ((mask[i])&&(!mask[i+1])) {
2950 masklist.push_back(i);
2951 }
2952 }
2953 }
2954 }
2955
2956 Vector<uInt> res(masklist.size());
2957 for (uInt i = 0; i < masklist.size(); ++i) {
2958 res[i] = (uInt)masklist[i];
2959 }
2960
2961 return res;
2962}
2963
2964void Scantable::initialiseBaselining(const std::string& blfile,
2965 ofstream& ofs,
2966 const bool outLogger,
2967 bool& outTextFile,
2968 bool& csvFormat,
2969 String& coordInfo,
2970 bool& hasSameNchan,
2971 const std::string& progressInfo,
2972 bool& showProgress,
2973 int& minNRow,
2974 Vector<Double>& timeSecCol)
2975{
2976 csvFormat = false;
2977 outTextFile = false;
2978
2979 if (blfile != "") {
2980 csvFormat = (blfile.substr(0, 1) == "T");
2981 ofs.open(blfile.substr(1).c_str(), ios::out | ios::app);
2982 if (ofs) outTextFile = true;
2983 }
2984
2985 coordInfo = "";
2986 hasSameNchan = true;
2987
2988 if (outLogger || outTextFile) {
2989 coordInfo = getCoordInfo()[0];
2990 if (coordInfo == "") coordInfo = "channel";
2991 hasSameNchan = hasSameNchanOverIFs();
2992 }
2993
2994 parseProgressInfo(progressInfo, showProgress, minNRow);
2995
2996 ROScalarColumn<Double> tcol = ROScalarColumn<Double>(table_, "TIME");
2997 timeSecCol = tcol.getColumn();
2998}
2999
3000void Scantable::finaliseBaselining(const bool outBaselineTable,
3001 STBaselineTable* pbt,
3002 const string& bltable,
3003 const bool outTextFile,
3004 ofstream& ofs)
3005{
3006 if (outBaselineTable) {
3007 pbt->save(bltable);
3008 }
3009
3010 if (outTextFile) ofs.close();
3011}
3012
3013void Scantable::initLineFinder(const std::vector<int>& edge,
3014 const float threshold,
3015 const int chanAvgLimit,
3016 STLineFinder& lineFinder)
3017{
[2774]3018 if ((edge.size() > 2) && (edge.size() < getIFNos().size()*2)) {
[2773]3019 throw(AipsError("Length of edge element info is less than that of IFs"));
3020 }
3021
3022 lineFinder.setOptions(threshold, 3, chanAvgLimit);
3023}
3024
3025void Scantable::polyBaseline(const std::vector<bool>& mask, int order,
3026 float thresClip, int nIterClip,
3027 bool getResidual,
3028 const std::string& progressInfo,
3029 const bool outLogger, const std::string& blfile,
3030 const std::string& bltable)
3031{
[2774]3032 /****
[2767]3033 double TimeStart = mathutil::gettimeofday_sec();
[2774]3034 ****/
[2767]3035
[2193]3036 try {
3037 ofstream ofs;
[2773]3038 String coordInfo;
3039 bool hasSameNchan, outTextFile, csvFormat, showProgress;
[2193]3040 int minNRow;
[2767]3041 int nRow = nrow();
[2773]3042 std::vector<bool> chanMask, finalChanMask;
[2767]3043 float rms;
[2773]3044 bool outBaselineTable = (bltable != "");
3045 STBaselineTable bt = STBaselineTable(*this);
3046 Vector<Double> timeSecCol;
[2767]3047
[2773]3048 initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
3049 coordInfo, hasSameNchan,
3050 progressInfo, showProgress, minNRow,
3051 timeSecCol);
[2767]3052
[2773]3053 std::vector<int> nChanNos;
3054 std::vector<std::vector<std::vector<double> > > modelReservoir;
3055 modelReservoir = getPolynomialModelReservoir(order,
3056 &Scantable::getNormalPolynomial,
3057 nChanNos);
[2968]3058 int nModel = modelReservoir.size();
[2773]3059
[2193]3060 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
[2767]3061 std::vector<float> sp = getSpectrum(whichrow);
[2193]3062 chanMask = getCompositeChanMask(whichrow, mask);
[2968]3063 std::vector<float> params;
[2773]3064
[3023]3065 //if (flagrowCol_(whichrow) == 0) {
3066 if (flagrowCol_(whichrow)==0 && nValidMask(chanMask)>0) {
[2968]3067 int nClipped = 0;
3068 std::vector<float> res;
3069 res = doLeastSquareFitting(sp, chanMask,
[2773]3070 modelReservoir[getIdxOfNchan(sp.size(), nChanNos)],
3071 params, rms, finalChanMask,
3072 nClipped, thresClip, nIterClip, getResidual);
[2767]3073
[2968]3074 if (outBaselineTable) {
3075 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3076 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3077 true, STBaselineFunc::Polynomial, order, std::vector<float>(),
3078 getMaskListFromMask(finalChanMask), params, rms, sp.size(),
3079 thresClip, nIterClip, 0.0, 0, std::vector<int>());
3080 } else {
3081 setSpectrum(res, whichrow);
3082 }
3083
3084 outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
3085 coordInfo, hasSameNchan, ofs, "polyBaseline()",
3086 params, nClipped);
[2767]3087 } else {
[3024]3088 // no valid channels to fit (flag the row)
3089 flagrowCol_.put(whichrow, 1);
[2968]3090 if (outBaselineTable) {
3091 params.resize(nModel);
3092 for (uInt i = 0; i < params.size(); ++i) {
3093 params[i] = 0.0;
3094 }
3095 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3096 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3097 true, STBaselineFunc::Polynomial, order, std::vector<float>(),
3098 getMaskListFromMask(chanMask), params, 0.0, sp.size(),
3099 thresClip, nIterClip, 0.0, 0, std::vector<int>());
3100 }
[2767]3101 }
3102
[2193]3103 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
3104 }
3105
[2773]3106 finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
[2193]3107
3108 } catch (...) {
3109 throw;
[2047]3110 }
[2767]3111
[2774]3112 /****
[2767]3113 double TimeEnd = mathutil::gettimeofday_sec();
3114 double elapse1 = TimeEnd - TimeStart;
3115 std::cout << "poly-new : " << elapse1 << " (sec.)" << endl;
[2774]3116 ****/
[2047]3117}
3118
[2773]3119void Scantable::autoPolyBaseline(const std::vector<bool>& mask, int order,
3120 float thresClip, int nIterClip,
3121 const std::vector<int>& edge,
3122 float threshold, int chanAvgLimit,
3123 bool getResidual,
3124 const std::string& progressInfo,
3125 const bool outLogger, const std::string& blfile,
3126 const std::string& bltable)
[2047]3127{
[2193]3128 try {
3129 ofstream ofs;
[2773]3130 String coordInfo;
3131 bool hasSameNchan, outTextFile, csvFormat, showProgress;
[2767]3132 int minNRow;
3133 int nRow = nrow();
[2773]3134 std::vector<bool> chanMask, finalChanMask;
[2767]3135 float rms;
[2773]3136 bool outBaselineTable = (bltable != "");
3137 STBaselineTable bt = STBaselineTable(*this);
3138 Vector<Double> timeSecCol;
3139 STLineFinder lineFinder = STLineFinder();
[2189]3140
[2773]3141 initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
3142 coordInfo, hasSameNchan,
3143 progressInfo, showProgress, minNRow,
3144 timeSecCol);
[2767]3145
[2773]3146 initLineFinder(edge, threshold, chanAvgLimit, lineFinder);
3147
3148 std::vector<int> nChanNos;
3149 std::vector<std::vector<std::vector<double> > > modelReservoir;
3150 modelReservoir = getPolynomialModelReservoir(order,
3151 &Scantable::getNormalPolynomial,
3152 nChanNos);
[2968]3153 int nModel = modelReservoir.size();
[2773]3154
[2193]3155 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
[2767]3156 std::vector<float> sp = getSpectrum(whichrow);
[2193]3157 std::vector<int> currentEdge;
[2773]3158 chanMask = getCompositeChanMask(whichrow, mask, edge, currentEdge, lineFinder);
[2968]3159 std::vector<float> params;
[2193]3160
[3023]3161 //if (flagrowCol_(whichrow) == 0) {
3162 if (flagrowCol_(whichrow)==0 && nValidMask(chanMask)>0) {
[2968]3163 int nClipped = 0;
3164 std::vector<float> res;
3165 res = doLeastSquareFitting(sp, chanMask,
[2773]3166 modelReservoir[getIdxOfNchan(sp.size(), nChanNos)],
3167 params, rms, finalChanMask,
3168 nClipped, thresClip, nIterClip, getResidual);
[2193]3169
[2968]3170 if (outBaselineTable) {
3171 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3172 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3173 true, STBaselineFunc::Polynomial, order, std::vector<float>(),
3174 getMaskListFromMask(finalChanMask), params, rms, sp.size(),
3175 thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
3176 } else {
3177 setSpectrum(res, whichrow);
3178 }
3179
3180 outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
3181 coordInfo, hasSameNchan, ofs, "autoPolyBaseline()",
3182 params, nClipped);
[2767]3183 } else {
[3024]3184 // no valid channels to fit (flag the row)
3185 flagrowCol_.put(whichrow, 1);
[2968]3186 if (outBaselineTable) {
3187 params.resize(nModel);
3188 for (uInt i = 0; i < params.size(); ++i) {
3189 params[i] = 0.0;
3190 }
3191 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3192 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3193 true, STBaselineFunc::Polynomial, order, std::vector<float>(),
3194 getMaskListFromMask(chanMask), params, 0.0, sp.size(),
3195 thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
3196 }
[2767]3197 }
3198
[2193]3199 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
[2047]3200 }
3201
[2773]3202 finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
[2767]3203
[2193]3204 } catch (...) {
3205 throw;
[2047]3206 }
3207}
3208
[2773]3209void Scantable::chebyshevBaseline(const std::vector<bool>& mask, int order,
3210 float thresClip, int nIterClip,
3211 bool getResidual,
3212 const std::string& progressInfo,
3213 const bool outLogger, const std::string& blfile,
3214 const std::string& bltable)
[2645]3215{
[2774]3216 /*
[2767]3217 double TimeStart = mathutil::gettimeofday_sec();
[2774]3218 */
[2767]3219
[2645]3220 try {
3221 ofstream ofs;
[2773]3222 String coordInfo;
3223 bool hasSameNchan, outTextFile, csvFormat, showProgress;
[2645]3224 int minNRow;
3225 int nRow = nrow();
[2773]3226 std::vector<bool> chanMask, finalChanMask;
[2737]3227 float rms;
[2773]3228 bool outBaselineTable = (bltable != "");
3229 STBaselineTable bt = STBaselineTable(*this);
3230 Vector<Double> timeSecCol;
[2737]3231
[2773]3232 initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
3233 coordInfo, hasSameNchan,
3234 progressInfo, showProgress, minNRow,
3235 timeSecCol);
[2737]3236
[2773]3237 std::vector<int> nChanNos;
3238 std::vector<std::vector<std::vector<double> > > modelReservoir;
3239 modelReservoir = getPolynomialModelReservoir(order,
3240 &Scantable::getChebyshevPolynomial,
3241 nChanNos);
[2968]3242 int nModel = modelReservoir.size();
[2773]3243
[2645]3244 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
3245 std::vector<float> sp = getSpectrum(whichrow);
3246 chanMask = getCompositeChanMask(whichrow, mask);
[2968]3247 std::vector<float> params;
[2773]3248
[3023]3249 // if (flagrowCol_(whichrow) == 0) {
3250 if (flagrowCol_(whichrow)==0 && nValidMask(chanMask)>0) {
[2968]3251 int nClipped = 0;
3252 std::vector<float> res;
3253 res = doLeastSquareFitting(sp, chanMask,
[2773]3254 modelReservoir[getIdxOfNchan(sp.size(), nChanNos)],
3255 params, rms, finalChanMask,
3256 nClipped, thresClip, nIterClip, getResidual);
[2645]3257
[2968]3258 if (outBaselineTable) {
3259 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3260 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3261 true, STBaselineFunc::Chebyshev, order, std::vector<float>(),
3262 getMaskListFromMask(finalChanMask), params, rms, sp.size(),
3263 thresClip, nIterClip, 0.0, 0, std::vector<int>());
3264 } else {
3265 setSpectrum(res, whichrow);
3266 }
3267
3268 outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
3269 coordInfo, hasSameNchan, ofs, "chebyshevBaseline()",
3270 params, nClipped);
[2737]3271 } else {
[3024]3272 // no valid channels to fit (flag the row)
3273 flagrowCol_.put(whichrow, 1);
[2968]3274 if (outBaselineTable) {
3275 params.resize(nModel);
3276 for (uInt i = 0; i < params.size(); ++i) {
3277 params[i] = 0.0;
3278 }
3279 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3280 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3281 true, STBaselineFunc::Chebyshev, order, std::vector<float>(),
3282 getMaskListFromMask(chanMask), params, 0.0, sp.size(),
3283 thresClip, nIterClip, 0.0, 0, std::vector<int>());
3284 }
[2737]3285 }
3286
[2645]3287 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
3288 }
3289
[2773]3290 finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
[2737]3291
[2645]3292 } catch (...) {
3293 throw;
3294 }
[2767]3295
[2774]3296 /*
[2767]3297 double TimeEnd = mathutil::gettimeofday_sec();
3298 double elapse1 = TimeEnd - TimeStart;
3299 std::cout << "cheby : " << elapse1 << " (sec.)" << endl;
[2774]3300 */
[2645]3301}
3302
[2773]3303void Scantable::autoChebyshevBaseline(const std::vector<bool>& mask, int order,
3304 float thresClip, int nIterClip,
3305 const std::vector<int>& edge,
3306 float threshold, int chanAvgLimit,
3307 bool getResidual,
3308 const std::string& progressInfo,
3309 const bool outLogger, const std::string& blfile,
3310 const std::string& bltable)
[2767]3311{
3312 try {
3313 ofstream ofs;
[2773]3314 String coordInfo;
3315 bool hasSameNchan, outTextFile, csvFormat, showProgress;
[2767]3316 int minNRow;
3317 int nRow = nrow();
[2773]3318 std::vector<bool> chanMask, finalChanMask;
[2767]3319 float rms;
[2773]3320 bool outBaselineTable = (bltable != "");
3321 STBaselineTable bt = STBaselineTable(*this);
3322 Vector<Double> timeSecCol;
3323 STLineFinder lineFinder = STLineFinder();
[2767]3324
[2773]3325 initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
3326 coordInfo, hasSameNchan,
3327 progressInfo, showProgress, minNRow,
3328 timeSecCol);
[2767]3329
[2773]3330 initLineFinder(edge, threshold, chanAvgLimit, lineFinder);
3331
3332 std::vector<int> nChanNos;
3333 std::vector<std::vector<std::vector<double> > > modelReservoir;
3334 modelReservoir = getPolynomialModelReservoir(order,
3335 &Scantable::getChebyshevPolynomial,
3336 nChanNos);
[2968]3337 int nModel = modelReservoir.size();
[2773]3338
[2767]3339 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
3340 std::vector<float> sp = getSpectrum(whichrow);
3341 std::vector<int> currentEdge;
[2773]3342 chanMask = getCompositeChanMask(whichrow, mask, edge, currentEdge, lineFinder);
[2968]3343 std::vector<float> params;
[2767]3344
[3023]3345 // if (flagrowCol_(whichrow) == 0) {
3346 if (flagrowCol_(whichrow)==0 && nValidMask(chanMask)>0) {
[2968]3347 int nClipped = 0;
3348 std::vector<float> res;
3349 res = doLeastSquareFitting(sp, chanMask,
[2773]3350 modelReservoir[getIdxOfNchan(sp.size(), nChanNos)],
3351 params, rms, finalChanMask,
3352 nClipped, thresClip, nIterClip, getResidual);
[2767]3353
[2968]3354 if (outBaselineTable) {
3355 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3356 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3357 true, STBaselineFunc::Chebyshev, order, std::vector<float>(),
3358 getMaskListFromMask(finalChanMask), params, rms, sp.size(),
3359 thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
3360 } else {
3361 setSpectrum(res, whichrow);
3362 }
3363
3364 outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
3365 coordInfo, hasSameNchan, ofs, "autoChebyshevBaseline()",
3366 params, nClipped);
[2767]3367 } else {
[3024]3368 // no valid channels to fit (flag the row)
3369 flagrowCol_.put(whichrow, 1);
[2968]3370 if (outBaselineTable) {
3371 params.resize(nModel);
3372 for (uInt i = 0; i < params.size(); ++i) {
3373 params[i] = 0.0;
3374 }
3375 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3376 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3377 true, STBaselineFunc::Chebyshev, order, std::vector<float>(),
3378 getMaskListFromMask(chanMask), params, 0.0, sp.size(),
3379 thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
3380 }
[2767]3381 }
3382
3383 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
3384 }
3385
[2773]3386 finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
[2767]3387
3388 } catch (...) {
3389 throw;
3390 }
3391}
3392
[2774]3393double Scantable::calculateModelSelectionCriteria(const std::string& valname,
3394 const std::string& blfunc,
3395 int order,
3396 const std::vector<bool>& inMask,
3397 int whichrow,
3398 bool useLineFinder,
3399 const std::vector<int>& edge,
3400 float threshold,
3401 int chanAvgLimit)
[2713]3402{
[2767]3403 std::vector<float> sp = getSpectrum(whichrow);
3404 std::vector<bool> chanMask;
3405 chanMask.clear();
3406
[2713]3407 if (useLineFinder) {
[2774]3408 STLineFinder lineFinder = STLineFinder();
3409 initLineFinder(edge, threshold, chanAvgLimit, lineFinder);
[2713]3410 std::vector<int> currentEdge;
[2774]3411 chanMask = getCompositeChanMask(whichrow, inMask, edge, currentEdge, lineFinder);
[2713]3412 } else {
[2767]3413 chanMask = getCompositeChanMask(whichrow, inMask);
[2713]3414 }
3415
[2767]3416 return doCalculateModelSelectionCriteria(valname, sp, chanMask, blfunc, order);
[2713]3417}
3418
3419double Scantable::doCalculateModelSelectionCriteria(const std::string& valname, const std::vector<float>& spec, const std::vector<bool>& mask, const std::string& blfunc, int order)
3420{
3421 int nparam;
3422 std::vector<float> params;
[2737]3423 std::vector<bool> finalChanMask;
3424 float rms;
[2713]3425 int nClipped = 0;
3426 std::vector<float> res;
[2767]3427 if (blfunc == "poly") {
[2713]3428 nparam = order + 1;
[2767]3429 res = doPolynomialFitting(spec, mask, order, params, rms, finalChanMask, nClipped);
3430 } else if (blfunc == "chebyshev") {
3431 nparam = order + 1;
3432 res = doChebyshevFitting(spec, mask, order, params, rms, finalChanMask, nClipped);
3433 } else if (blfunc == "cspline") {
3434 std::vector<int> pieceEdges;//(order+1); //order = npiece
3435 nparam = order + 3;
3436 res = doCubicSplineFitting(spec, mask, order, false, pieceEdges, params, rms, finalChanMask, nClipped);
[2713]3437 } else if (blfunc == "sinusoid") {
3438 std::vector<int> nWaves;
3439 nWaves.clear();
3440 for (int i = 0; i <= order; ++i) {
3441 nWaves.push_back(i);
3442 }
3443 nparam = 2*order + 1; // order = nwave
[2767]3444 res = doSinusoidFitting(spec, mask, nWaves, params, rms, finalChanMask, nClipped);
[2713]3445 } else {
[2767]3446 throw(AipsError("blfunc must be poly, chebyshev, cspline or sinusoid."));
[2713]3447 }
3448
3449 double msq = 0.0;
3450 int nusedchan = 0;
3451 int nChan = res.size();
3452 for (int i = 0; i < nChan; ++i) {
3453 if (mask[i]) {
3454 msq += (double)res[i]*(double)res[i];
3455 nusedchan++;
3456 }
3457 }
3458 if (nusedchan == 0) {
3459 throw(AipsError("all channels masked."));
3460 }
3461 msq /= (double)nusedchan;
3462
3463 nparam++; //add 1 for sigma of Gaussian distribution
3464 const double PI = 6.0 * asin(0.5); // PI (= 3.141592653...)
3465
3466 if (valname.find("aic") == 0) {
3467 // Original Akaike Information Criterion (AIC)
3468 double aic = nusedchan * (log(2.0 * PI * msq) + 1.0) + 2.0 * nparam;
3469
[2767]3470 // Corrected AIC by Sugiura(1978) (AICc)
[2713]3471 if (valname == "aicc") {
3472 if (nusedchan - nparam - 1 <= 0) {
3473 throw(AipsError("channel size is too small to calculate AICc."));
3474 }
3475 aic += 2.0*nparam*(nparam + 1)/(double)(nusedchan - nparam - 1);
3476 }
3477
3478 return aic;
3479
3480 } else if (valname == "bic") {
3481 // Bayesian Information Criterion (BIC)
3482 double bic = nusedchan * log(msq) + nparam * log((double)nusedchan);
3483 return bic;
3484
3485 } else if (valname == "gcv") {
3486 // Generalised Cross Validation
3487 double x = 1.0 - (double)nparam / (double)nusedchan;
3488 double gcv = msq / (x * x);
3489 return gcv;
3490
3491 } else {
3492 throw(AipsError("valname must be aic, aicc, bic or gcv."));
3493 }
3494}
3495
[2767]3496double Scantable::getNormalPolynomial(int n, double x) {
3497 if (n == 0) {
3498 return 1.0;
3499 } else if (n > 0) {
3500 double res = 1.0;
3501 for (int i = 0; i < n; ++i) {
3502 res *= x;
[2645]3503 }
[2767]3504 return res;
3505 } else {
3506 if (x == 0.0) {
3507 throw(AipsError("infinity result: x=0 given for negative power."));
3508 } else {
3509 return pow(x, (double)n);
[2645]3510 }
3511 }
3512}
3513
3514double Scantable::getChebyshevPolynomial(int n, double x) {
3515 if ((x < -1.0)||(x > 1.0)) {
3516 throw(AipsError("out of definition range (-1 <= x <= 1)."));
[2713]3517 } else if (x == 1.0) {
3518 return 1.0;
3519 } else if (x == 0.0) {
3520 double res;
3521 if (n%2 == 0) {
3522 if (n%4 == 0) {
3523 res = 1.0;
3524 } else {
3525 res = -1.0;
3526 }
3527 } else {
3528 res = 0.0;
3529 }
3530 return res;
3531 } else if (x == -1.0) {
3532 double res = (n%2 == 0 ? 1.0 : -1.0);
3533 return res;
[2645]3534 } else if (n < 0) {
3535 throw(AipsError("the order must be zero or positive."));
3536 } else if (n == 0) {
3537 return 1.0;
3538 } else if (n == 1) {
3539 return x;
3540 } else {
[2880]3541 double res[n+1];
3542 for (int i = 0; i < n+1; ++i) {
3543 double res0 = 0.0;
3544 if (i == 0) {
3545 res0 = 1.0;
3546 } else if (i == 1) {
3547 res0 = x;
3548 } else {
3549 res0 = 2.0 * x * res[i-1] - res[i-2];
[2645]3550 }
[2880]3551 res[i] = res0;
[2645]3552 }
[2880]3553 return res[n];
[2645]3554 }
3555}
3556
[2773]3557std::vector<float> Scantable::doPolynomialFitting(const std::vector<float>& data,
3558 const std::vector<bool>& mask,
3559 int order,
3560 std::vector<float>& params,
3561 float& rms,
3562 std::vector<bool>& finalmask,
3563 float clipth,
3564 int clipn)
[2645]3565{
[2767]3566 int nClipped = 0;
3567 return doPolynomialFitting(data, mask, order, params, rms, finalmask, nClipped, clipth, clipn);
3568}
3569
[2773]3570std::vector<float> Scantable::doPolynomialFitting(const std::vector<float>& data,
3571 const std::vector<bool>& mask,
3572 int order,
3573 std::vector<float>& params,
3574 float& rms,
3575 std::vector<bool>& finalMask,
3576 int& nClipped,
3577 float thresClip,
3578 int nIterClip,
3579 bool getResidual)
[2767]3580{
[2773]3581 return doLeastSquareFitting(data, mask,
3582 getPolynomialModel(order, data.size(), &Scantable::getNormalPolynomial),
3583 params, rms, finalMask,
3584 nClipped, thresClip, nIterClip,
3585 getResidual);
[2767]3586}
3587
[2773]3588std::vector<float> Scantable::doChebyshevFitting(const std::vector<float>& data,
3589 const std::vector<bool>& mask,
3590 int order,
3591 std::vector<float>& params,
3592 float& rms,
3593 std::vector<bool>& finalmask,
3594 float clipth,
3595 int clipn)
[2767]3596{
3597 int nClipped = 0;
3598 return doChebyshevFitting(data, mask, order, params, rms, finalmask, nClipped, clipth, clipn);
3599}
3600
[2773]3601std::vector<float> Scantable::doChebyshevFitting(const std::vector<float>& data,
3602 const std::vector<bool>& mask,
3603 int order,
3604 std::vector<float>& params,
3605 float& rms,
3606 std::vector<bool>& finalMask,
3607 int& nClipped,
3608 float thresClip,
3609 int nIterClip,
3610 bool getResidual)
[2767]3611{
[2773]3612 return doLeastSquareFitting(data, mask,
3613 getPolynomialModel(order, data.size(), &Scantable::getChebyshevPolynomial),
3614 params, rms, finalMask,
3615 nClipped, thresClip, nIterClip,
3616 getResidual);
[2767]3617}
3618
[2773]3619std::vector<std::vector<double> > Scantable::getPolynomialModel(int order, int nchan, double (Scantable::*pfunc)(int, double))
[2767]3620{
[2773]3621 // model : contains model values for computing the least-square matrix.
3622 // model.size() is nmodel and model[*].size() is nchan.
3623 // Each model element are as follows:
3624 //
3625 // (for normal polynomials)
3626 // model[0] = {1.0, 1.0, 1.0, ..., 1.0},
3627 // model[1] = {0.0, 1.0, 2.0, ..., (nchan-1)}
3628 // model[n-1] = ...,
3629 // model[n] = {0.0^n, 1.0^n, 2.0^n, ..., (nchan-1)^n}
3630 // where (0 <= n <= order)
3631 //
3632 // (for Chebyshev polynomials)
3633 // model[0] = {T0(-1), T0(2/(nchan-1)-1), T0(4/(nchan-1)-1), ..., T0(1)},
3634 // model[n-1] = ...,
3635 // model[n] = {Tn(-1), Tn(2/(nchan-1)-1), Tn(4/(nchan-1)-1), ..., Tn(1)}
3636 // where (0 <= n <= order),
3637
3638 int nmodel = order + 1;
3639 std::vector<std::vector<double> > model(nmodel, std::vector<double>(nchan));
3640
3641 double stretch, shift;
3642 if (pfunc == &Scantable::getChebyshevPolynomial) {
3643 stretch = 2.0/(double)(nchan - 1);
3644 shift = -1.0;
3645 } else {
3646 stretch = 1.0;
3647 shift = 0.0;
[2645]3648 }
[2773]3649
3650 for (int i = 0; i < nmodel; ++i) {
3651 for (int j = 0; j < nchan; ++j) {
3652 model[i][j] = (this->*pfunc)(i, stretch*(double)j + shift);
3653 }
[2645]3654 }
3655
[2773]3656 return model;
3657}
3658
3659std::vector<std::vector<std::vector<double> > > Scantable::getPolynomialModelReservoir(int order,
3660 double (Scantable::*pfunc)(int, double),
3661 std::vector<int>& nChanNos)
3662{
3663 std::vector<std::vector<std::vector<double> > > res;
3664 res.clear();
3665 nChanNos.clear();
3666
3667 std::vector<uint> ifNos = getIFNos();
3668 for (uint i = 0; i < ifNos.size(); ++i) {
3669 int currNchan = nchan(ifNos[i]);
3670 bool hasDifferentNchan = (i == 0);
3671 for (uint j = 0; j < i; ++j) {
3672 if (currNchan != nchan(ifNos[j])) {
3673 hasDifferentNchan = true;
3674 break;
3675 }
3676 }
3677 if (hasDifferentNchan) {
3678 res.push_back(getPolynomialModel(order, currNchan, pfunc));
3679 nChanNos.push_back(currNchan);
3680 }
3681 }
3682
3683 return res;
3684}
3685
3686std::vector<float> Scantable::doLeastSquareFitting(const std::vector<float>& data,
3687 const std::vector<bool>& mask,
3688 const std::vector<std::vector<double> >& model,
3689 std::vector<float>& params,
3690 float& rms,
3691 std::vector<bool>& finalMask,
3692 int& nClipped,
3693 float thresClip,
3694 int nIterClip,
3695 bool getResidual)
3696{
3697 int nDOF = model.size();
[2645]3698 int nChan = data.size();
[2737]3699
[2773]3700 if (nDOF == 0) {
3701 throw(AipsError("no model data given"));
3702 }
3703 if (nChan < 2) {
3704 throw(AipsError("data size is too few"));
3705 }
3706 if (nChan != (int)mask.size()) {
3707 throw(AipsError("data and mask sizes are not identical"));
3708 }
3709 for (int i = 0; i < nDOF; ++i) {
3710 if (nChan != (int)model[i].size()) {
3711 throw(AipsError("data and model sizes are not identical"));
3712 }
3713 }
3714
3715 params.clear();
3716 params.resize(nDOF);
3717
[2737]3718 finalMask.clear();
3719 finalMask.resize(nChan);
3720
[2773]3721 std::vector<int> maskArray(nChan);
3722 int j = 0;
[2645]3723 for (int i = 0; i < nChan; ++i) {
[2773]3724 maskArray[i] = mask[i] ? 1 : 0;
[2890]3725 if (isnan(data[i])) maskArray[i] = 0;
3726 if (isinf(data[i])) maskArray[i] = 0;
3727
3728 finalMask[i] = (maskArray[i] == 1);
3729 if (finalMask[i]) {
3730 j++;
3731 }
3732
3733 /*
3734 maskArray[i] = mask[i] ? 1 : 0;
[2645]3735 if (mask[i]) {
[2773]3736 j++;
[2645]3737 }
[2737]3738 finalMask[i] = mask[i];
[2890]3739 */
[2645]3740 }
3741
[2773]3742 int initNData = j;
[2645]3743 int nData = initNData;
3744
[2773]3745 std::vector<double> z1(nChan), r1(nChan), residual(nChan);
[2645]3746 for (int i = 0; i < nChan; ++i) {
[2773]3747 z1[i] = (double)data[i];
3748 r1[i] = 0.0;
3749 residual[i] = 0.0;
[2645]3750 }
3751
3752 for (int nClip = 0; nClip < nIterClip+1; ++nClip) {
3753 // xMatrix : horizontal concatenation of
3754 // the least-sq. matrix (left) and an
3755 // identity matrix (right).
3756 // the right part is used to calculate the inverse matrix of the left part.
3757 double xMatrix[nDOF][2*nDOF];
3758 double zMatrix[nDOF];
3759 for (int i = 0; i < nDOF; ++i) {
3760 for (int j = 0; j < 2*nDOF; ++j) {
3761 xMatrix[i][j] = 0.0;
3762 }
3763 xMatrix[i][nDOF+i] = 1.0;
3764 zMatrix[i] = 0.0;
3765 }
3766
3767 int nUseData = 0;
3768 for (int k = 0; k < nChan; ++k) {
3769 if (maskArray[k] == 0) continue;
3770
3771 for (int i = 0; i < nDOF; ++i) {
3772 for (int j = i; j < nDOF; ++j) {
[2773]3773 xMatrix[i][j] += model[i][k] * model[j][k];
[2645]3774 }
[2773]3775 zMatrix[i] += z1[k] * model[i][k];
[2645]3776 }
3777
3778 nUseData++;
3779 }
3780
3781 if (nUseData < 1) {
3782 throw(AipsError("all channels clipped or masked. can't execute fitting anymore."));
3783 }
3784
3785 for (int i = 0; i < nDOF; ++i) {
3786 for (int j = 0; j < i; ++j) {
3787 xMatrix[i][j] = xMatrix[j][i];
3788 }
3789 }
3790
[2890]3791 //compute inverse matrix of the left half of xMatrix
[2773]3792 std::vector<double> invDiag(nDOF);
[2645]3793 for (int i = 0; i < nDOF; ++i) {
[2773]3794 invDiag[i] = 1.0 / xMatrix[i][i];
[2645]3795 for (int j = 0; j < nDOF; ++j) {
3796 xMatrix[i][j] *= invDiag[i];
3797 }
3798 }
3799
3800 for (int k = 0; k < nDOF; ++k) {
3801 for (int i = 0; i < nDOF; ++i) {
3802 if (i != k) {
3803 double factor1 = xMatrix[k][k];
[2773]3804 double invfactor1 = 1.0 / factor1;
[2645]3805 double factor2 = xMatrix[i][k];
3806 for (int j = k; j < 2*nDOF; ++j) {
3807 xMatrix[i][j] *= factor1;
3808 xMatrix[i][j] -= xMatrix[k][j]*factor2;
[2773]3809 xMatrix[i][j] *= invfactor1;
[2645]3810 }
3811 }
3812 }
[2773]3813 double invXDiag = 1.0 / xMatrix[k][k];
[2645]3814 for (int j = k; j < 2*nDOF; ++j) {
[2773]3815 xMatrix[k][j] *= invXDiag;
[2645]3816 }
3817 }
3818
3819 for (int i = 0; i < nDOF; ++i) {
3820 for (int j = 0; j < nDOF; ++j) {
3821 xMatrix[i][nDOF+j] *= invDiag[j];
3822 }
3823 }
[2773]3824 //compute a vector y in which coefficients of the best-fit
3825 //model functions are stored.
3826 //in case of polynomials, y consists of (a0,a1,a2,...)
3827 //where ai is the coefficient of the term x^i.
3828 //in case of sinusoids, y consists of (a0,s1,c1,s2,c2,...)
3829 //where a0 is constant term and s* and c* are of sine
3830 //and cosine functions, respectively.
3831 std::vector<double> y(nDOF);
[2645]3832 for (int i = 0; i < nDOF; ++i) {
[2773]3833 y[i] = 0.0;
[2645]3834 for (int j = 0; j < nDOF; ++j) {
3835 y[i] += xMatrix[i][nDOF+j]*zMatrix[j];
3836 }
[2773]3837 params[i] = (float)y[i];
[2645]3838 }
3839
3840 for (int i = 0; i < nChan; ++i) {
3841 r1[i] = y[0];
3842 for (int j = 1; j < nDOF; ++j) {
[2773]3843 r1[i] += y[j]*model[j][i];
[2645]3844 }
3845 residual[i] = z1[i] - r1[i];
3846 }
3847
[2737]3848 double stdDev = 0.0;
3849 for (int i = 0; i < nChan; ++i) {
[2890]3850 if (maskArray[i] == 0) continue;
3851 stdDev += residual[i]*residual[i];
[2737]3852 }
3853 stdDev = sqrt(stdDev/(double)nData);
3854 rms = (float)stdDev;
3855
[2645]3856 if ((nClip == nIterClip) || (thresClip <= 0.0)) {
3857 break;
3858 } else {
[2737]3859
[2645]3860 double thres = stdDev * thresClip;
3861 int newNData = 0;
3862 for (int i = 0; i < nChan; ++i) {
3863 if (abs(residual[i]) >= thres) {
3864 maskArray[i] = 0;
[2737]3865 finalMask[i] = false;
[2645]3866 }
3867 if (maskArray[i] > 0) {
3868 newNData++;
3869 }
3870 }
3871 if (newNData == nData) {
[2890]3872 break; //no more flag to add. stop iteration.
[2645]3873 } else {
3874 nData = newNData;
3875 }
[2737]3876
[2645]3877 }
3878 }
3879
3880 nClipped = initNData - nData;
3881
[2773]3882 std::vector<float> result(nChan);
[2645]3883 if (getResidual) {
3884 for (int i = 0; i < nChan; ++i) {
[2773]3885 result[i] = (float)residual[i];
[2645]3886 }
3887 } else {
3888 for (int i = 0; i < nChan; ++i) {
[2773]3889 result[i] = (float)r1[i];
[2645]3890 }
3891 }
3892
3893 return result;
[2890]3894} //xMatrix
[2645]3895
[2773]3896void Scantable::cubicSplineBaseline(const std::vector<bool>& mask, int nPiece,
3897 float thresClip, int nIterClip,
3898 bool getResidual,
3899 const std::string& progressInfo,
3900 const bool outLogger, const std::string& blfile,
3901 const std::string& bltable)
[2081]3902{
[2774]3903 /****
[2773]3904 double TimeStart = mathutil::gettimeofday_sec();
[2774]3905 ****/
[2773]3906
[2193]3907 try {
3908 ofstream ofs;
[2773]3909 String coordInfo;
3910 bool hasSameNchan, outTextFile, csvFormat, showProgress;
[2193]3911 int minNRow;
[2344]3912 int nRow = nrow();
[2773]3913 std::vector<bool> chanMask, finalChanMask;
[2767]3914 float rms;
[2773]3915 bool outBaselineTable = (bltable != "");
3916 STBaselineTable bt = STBaselineTable(*this);
3917 Vector<Double> timeSecCol;
[2344]3918
[2773]3919 initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
3920 coordInfo, hasSameNchan,
3921 progressInfo, showProgress, minNRow,
3922 timeSecCol);
[2767]3923
[2773]3924 std::vector<int> nChanNos;
3925 std::vector<std::vector<std::vector<double> > > modelReservoir;
3926 modelReservoir = getPolynomialModelReservoir(3,
3927 &Scantable::getNormalPolynomial,
3928 nChanNos);
[2968]3929 int nDOF = nPiece + 3;
[2767]3930
[2193]3931 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
[2591]3932 std::vector<float> sp = getSpectrum(whichrow);
[2193]3933 chanMask = getCompositeChanMask(whichrow, mask);
[2773]3934 std::vector<int> pieceEdges;
3935 std::vector<float> params;
[2591]3936
[3023]3937 //if (flagrowCol_(whichrow) == 0) {
3938 if (flagrowCol_(whichrow)==0 && nValidMask(chanMask)>0) {
[2968]3939 int nClipped = 0;
3940 std::vector<float> res;
3941 res = doCubicSplineLeastSquareFitting(sp, chanMask,
3942 modelReservoir[getIdxOfNchan(sp.size(), nChanNos)],
3943 nPiece, false, pieceEdges, params, rms, finalChanMask,
3944 nClipped, thresClip, nIterClip, getResidual);
3945
3946 if (outBaselineTable) {
3947 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3948 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3949 true, STBaselineFunc::CSpline, pieceEdges, std::vector<float>(),
3950 getMaskListFromMask(finalChanMask), params, rms, sp.size(),
3951 thresClip, nIterClip, 0.0, 0, std::vector<int>());
3952 } else {
3953 setSpectrum(res, whichrow);
3954 }
3955
3956 outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
3957 coordInfo, hasSameNchan, ofs, "cubicSplineBaseline()",
3958 pieceEdges, params, nClipped);
[2767]3959 } else {
[3024]3960 // no valid channels to fit (flag the row)
3961 flagrowCol_.put(whichrow, 1);
[2968]3962 if (outBaselineTable) {
3963 pieceEdges.resize(nPiece+1);
3964 for (uInt i = 0; i < pieceEdges.size(); ++i) {
3965 pieceEdges[i] = 0;
3966 }
3967 params.resize(nDOF);
3968 for (uInt i = 0; i < params.size(); ++i) {
3969 params[i] = 0.0;
3970 }
3971 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3972 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3973 true, STBaselineFunc::CSpline, pieceEdges, std::vector<float>(),
3974 getMaskListFromMask(chanMask), params, 0.0, sp.size(),
3975 thresClip, nIterClip, 0.0, 0, std::vector<int>());
3976 }
[2767]3977 }
[2591]3978
[2193]3979 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
3980 }
[2344]3981
[2773]3982 finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
[2767]3983
[2193]3984 } catch (...) {
3985 throw;
[2012]3986 }
[2773]3987
[2774]3988 /****
[2773]3989 double TimeEnd = mathutil::gettimeofday_sec();
3990 double elapse1 = TimeEnd - TimeStart;
3991 std::cout << "cspline-new : " << elapse1 << " (sec.)" << endl;
[2774]3992 ****/
[2012]3993}
3994
[2773]3995void Scantable::autoCubicSplineBaseline(const std::vector<bool>& mask, int nPiece,
3996 float thresClip, int nIterClip,
3997 const std::vector<int>& edge,
3998 float threshold, int chanAvgLimit,
3999 bool getResidual,
4000 const std::string& progressInfo,
4001 const bool outLogger, const std::string& blfile,
4002 const std::string& bltable)
[2012]4003{
[2193]4004 try {
4005 ofstream ofs;
[2773]4006 String coordInfo;
4007 bool hasSameNchan, outTextFile, csvFormat, showProgress;
[2767]4008 int minNRow;
4009 int nRow = nrow();
[2773]4010 std::vector<bool> chanMask, finalChanMask;
[2767]4011 float rms;
[2773]4012 bool outBaselineTable = (bltable != "");
4013 STBaselineTable bt = STBaselineTable(*this);
4014 Vector<Double> timeSecCol;
4015 STLineFinder lineFinder = STLineFinder();
[2189]4016
[2773]4017 initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
4018 coordInfo, hasSameNchan,
4019 progressInfo, showProgress, minNRow,
4020 timeSecCol);
[2767]4021
[2773]4022 initLineFinder(edge, threshold, chanAvgLimit, lineFinder);
4023
4024 std::vector<int> nChanNos;
4025 std::vector<std::vector<std::vector<double> > > modelReservoir;
4026 modelReservoir = getPolynomialModelReservoir(3,
4027 &Scantable::getNormalPolynomial,
4028 nChanNos);
[2968]4029 int nDOF = nPiece + 3;
[2773]4030
[2193]4031 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
[2591]4032 std::vector<float> sp = getSpectrum(whichrow);
[2193]4033 std::vector<int> currentEdge;
[2773]4034 chanMask = getCompositeChanMask(whichrow, mask, edge, currentEdge, lineFinder);
4035 std::vector<int> pieceEdges;
4036 std::vector<float> params;
[2193]4037
[3023]4038 //if (flagrowCol_(whichrow) == 0) {
4039 if (flagrowCol_(whichrow)==0 && nValidMask(chanMask)>0) {
[2968]4040 int nClipped = 0;
4041 std::vector<float> res;
4042 res = doCubicSplineLeastSquareFitting(sp, chanMask,
4043 modelReservoir[getIdxOfNchan(sp.size(), nChanNos)],
4044 nPiece, false, pieceEdges, params, rms, finalChanMask,
4045 nClipped, thresClip, nIterClip, getResidual);
4046
4047 if (outBaselineTable) {
4048 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
4049 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
4050 true, STBaselineFunc::CSpline, pieceEdges, std::vector<float>(),
4051 getMaskListFromMask(finalChanMask), params, rms, sp.size(),
4052 thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
4053 } else {
4054 setSpectrum(res, whichrow);
4055 }
4056
4057 outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
4058 coordInfo, hasSameNchan, ofs, "autoCubicSplineBaseline()",
4059 pieceEdges, params, nClipped);
[2767]4060 } else {
[3024]4061 // no valid channels to fit (flag the row)
4062 flagrowCol_.put(whichrow, 1);
[2968]4063 if (outBaselineTable) {
4064 pieceEdges.resize(nPiece+1);
4065 for (uInt i = 0; i < pieceEdges.size(); ++i) {
4066 pieceEdges[i] = 0;
4067 }
4068 params.resize(nDOF);
4069 for (uInt i = 0; i < params.size(); ++i) {
4070 params[i] = 0.0;
4071 }
4072 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
4073 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
4074 true, STBaselineFunc::CSpline, pieceEdges, std::vector<float>(),
4075 getMaskListFromMask(chanMask), params, 0.0, sp.size(),
4076 thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
4077 }
[2767]4078 }
4079
[2193]4080 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
[1907]4081 }
[2012]4082
[2773]4083 finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
[2767]4084
[2193]4085 } catch (...) {
4086 throw;
[2012]4087 }
[1730]4088}
[1907]4089
[2773]4090std::vector<float> Scantable::doCubicSplineFitting(const std::vector<float>& data,
4091 const std::vector<bool>& mask,
4092 std::vector<int>& idxEdge,
4093 std::vector<float>& params,
4094 float& rms,
4095 std::vector<bool>& finalmask,
4096 float clipth,
4097 int clipn)
[2081]4098{
[2767]4099 int nClipped = 0;
4100 return doCubicSplineFitting(data, mask, idxEdge.size()-1, true, idxEdge, params, rms, finalmask, nClipped, clipth, clipn);
4101}
4102
[2773]4103std::vector<float> Scantable::doCubicSplineFitting(const std::vector<float>& data,
4104 const std::vector<bool>& mask,
4105 int nPiece,
4106 std::vector<int>& idxEdge,
4107 std::vector<float>& params,
4108 float& rms,
4109 std::vector<bool>& finalmask,
4110 float clipth,
4111 int clipn)
[2767]4112{
4113 int nClipped = 0;
4114 return doCubicSplineFitting(data, mask, nPiece, false, idxEdge, params, rms, finalmask, nClipped, clipth, clipn);
4115}
4116
[2773]4117std::vector<float> Scantable::doCubicSplineFitting(const std::vector<float>& data,
4118 const std::vector<bool>& mask,
4119 int nPiece,
4120 bool useGivenPieceBoundary,
4121 std::vector<int>& idxEdge,
4122 std::vector<float>& params,
4123 float& rms,
4124 std::vector<bool>& finalMask,
4125 int& nClipped,
4126 float thresClip,
4127 int nIterClip,
4128 bool getResidual)
[2767]4129{
[2773]4130 return doCubicSplineLeastSquareFitting(data, mask,
4131 getPolynomialModel(3, data.size(), &Scantable::getNormalPolynomial),
4132 nPiece, useGivenPieceBoundary, idxEdge,
4133 params, rms, finalMask,
4134 nClipped, thresClip, nIterClip,
4135 getResidual);
4136}
4137
4138std::vector<float> Scantable::doCubicSplineLeastSquareFitting(const std::vector<float>& data,
4139 const std::vector<bool>& mask,
4140 const std::vector<std::vector<double> >& model,
4141 int nPiece,
4142 bool useGivenPieceBoundary,
4143 std::vector<int>& idxEdge,
4144 std::vector<float>& params,
4145 float& rms,
4146 std::vector<bool>& finalMask,
4147 int& nClipped,
4148 float thresClip,
4149 int nIterClip,
4150 bool getResidual)
4151{
4152 int nDOF = nPiece + 3; //number of independent parameters to solve, namely, 4+(nPiece-1).
4153 int nModel = model.size();
4154 int nChan = data.size();
4155
4156 if (nModel != 4) {
4157 throw(AipsError("model size must be 4."));
[2081]4158 }
[2012]4159 if (nPiece < 1) {
[2094]4160 throw(AipsError("number of the sections must be one or more"));
[2012]4161 }
[2773]4162 if (nChan < 2*nPiece) {
4163 throw(AipsError("data size is too few"));
4164 }
4165 if (nChan != (int)mask.size()) {
4166 throw(AipsError("data and mask sizes are not identical"));
4167 }
4168 for (int i = 0; i < nModel; ++i) {
4169 if (nChan != (int)model[i].size()) {
4170 throw(AipsError("data and model sizes are not identical"));
4171 }
4172 }
[2012]4173
[2773]4174 params.clear();
4175 params.resize(nPiece*nModel);
[2767]4176
4177 finalMask.clear();
4178 finalMask.resize(nChan);
4179
[2344]4180 std::vector<int> maskArray(nChan);
4181 std::vector<int> x(nChan);
4182 int j = 0;
[2012]4183 for (int i = 0; i < nChan; ++i) {
[2344]4184 maskArray[i] = mask[i] ? 1 : 0;
[2890]4185 if (isnan(data[i])) maskArray[i] = 0;
4186 if (isinf(data[i])) maskArray[i] = 0;
4187
4188 finalMask[i] = (maskArray[i] == 1);
4189 if (finalMask[i]) {
4190 x[j] = i;
4191 j++;
4192 }
4193
4194 /*
4195 maskArray[i] = mask[i] ? 1 : 0;
[2012]4196 if (mask[i]) {
[2344]4197 x[j] = i;
4198 j++;
[2012]4199 }
[2767]4200 finalMask[i] = mask[i];
[2890]4201 */
[2012]4202 }
[2773]4203
[2344]4204 int initNData = j;
[2773]4205 int nData = initNData;
[2012]4206
[2193]4207 if (initNData < nPiece) {
4208 throw(AipsError("too few non-flagged channels"));
4209 }
[2081]4210
4211 int nElement = (int)(floor(floor((double)(initNData/nPiece))+0.5));
[2344]4212 std::vector<double> invEdge(nPiece-1);
[2767]4213
4214 if (useGivenPieceBoundary) {
4215 if ((int)idxEdge.size() != nPiece+1) {
4216 throw(AipsError("pieceEdge.size() must be equal to nPiece+1."));
4217 }
4218 } else {
4219 idxEdge.clear();
4220 idxEdge.resize(nPiece+1);
4221 idxEdge[0] = x[0];
4222 }
[2012]4223 for (int i = 1; i < nPiece; ++i) {
[2047]4224 int valX = x[nElement*i];
[2767]4225 if (!useGivenPieceBoundary) {
4226 idxEdge[i] = valX;
4227 }
[2344]4228 invEdge[i-1] = 1.0/(double)valX;
[2012]4229 }
[2767]4230 if (!useGivenPieceBoundary) {
4231 idxEdge[nPiece] = x[initNData-1]+1;
4232 }
[2064]4233
[2773]4234 std::vector<double> z1(nChan), r1(nChan), residual(nChan);
[2012]4235 for (int i = 0; i < nChan; ++i) {
[2773]4236 z1[i] = (double)data[i];
4237 r1[i] = 0.0;
[2344]4238 residual[i] = 0.0;
[2012]4239 }
4240
4241 for (int nClip = 0; nClip < nIterClip+1; ++nClip) {
[2064]4242 // xMatrix : horizontal concatenation of
4243 // the least-sq. matrix (left) and an
4244 // identity matrix (right).
4245 // the right part is used to calculate the inverse matrix of the left part.
[2767]4246
[2012]4247 double xMatrix[nDOF][2*nDOF];
4248 double zMatrix[nDOF];
4249 for (int i = 0; i < nDOF; ++i) {
4250 for (int j = 0; j < 2*nDOF; ++j) {
4251 xMatrix[i][j] = 0.0;
4252 }
4253 xMatrix[i][nDOF+i] = 1.0;
4254 zMatrix[i] = 0.0;
4255 }
4256
4257 for (int n = 0; n < nPiece; ++n) {
[2193]4258 int nUseDataInPiece = 0;
[2773]4259 for (int k = idxEdge[n]; k < idxEdge[n+1]; ++k) {
[2064]4260
[2773]4261 if (maskArray[k] == 0) continue;
[2064]4262
[2773]4263 for (int i = 0; i < nModel; ++i) {
4264 for (int j = i; j < nModel; ++j) {
4265 xMatrix[i][j] += model[i][k] * model[j][k];
4266 }
4267 zMatrix[i] += z1[k] * model[i][k];
4268 }
[2064]4269
[2773]4270 for (int i = 0; i < n; ++i) {
4271 double q = 1.0 - model[1][k]*invEdge[i];
[2012]4272 q = q*q*q;
[2773]4273 for (int j = 0; j < nModel; ++j) {
4274 xMatrix[j][i+nModel] += q * model[j][k];
4275 }
4276 for (int j = 0; j < i; ++j) {
4277 double r = 1.0 - model[1][k]*invEdge[j];
[2012]4278 r = r*r*r;
[2773]4279 xMatrix[j+nModel][i+nModel] += r*q;
[2012]4280 }
[2773]4281 xMatrix[i+nModel][i+nModel] += q*q;
4282 zMatrix[i+nModel] += q*z1[k];
[2012]4283 }
[2064]4284
[2193]4285 nUseDataInPiece++;
[2012]4286 }
[2193]4287
4288 if (nUseDataInPiece < 1) {
4289 std::vector<string> suffixOfPieceNumber(4);
4290 suffixOfPieceNumber[0] = "th";
4291 suffixOfPieceNumber[1] = "st";
4292 suffixOfPieceNumber[2] = "nd";
4293 suffixOfPieceNumber[3] = "rd";
4294 int idxNoDataPiece = (n % 10 <= 3) ? n : 0;
4295 ostringstream oss;
4296 oss << "all channels clipped or masked in " << n << suffixOfPieceNumber[idxNoDataPiece];
4297 oss << " piece of the spectrum. can't execute fitting anymore.";
4298 throw(AipsError(String(oss)));
4299 }
[2012]4300 }
4301
4302 for (int i = 0; i < nDOF; ++i) {
4303 for (int j = 0; j < i; ++j) {
4304 xMatrix[i][j] = xMatrix[j][i];
4305 }
4306 }
4307
[2344]4308 std::vector<double> invDiag(nDOF);
[2012]4309 for (int i = 0; i < nDOF; ++i) {
[2773]4310 invDiag[i] = 1.0 / xMatrix[i][i];
[2012]4311 for (int j = 0; j < nDOF; ++j) {
4312 xMatrix[i][j] *= invDiag[i];
4313 }
4314 }
4315
4316 for (int k = 0; k < nDOF; ++k) {
4317 for (int i = 0; i < nDOF; ++i) {
4318 if (i != k) {
4319 double factor1 = xMatrix[k][k];
[2773]4320 double invfactor1 = 1.0 / factor1;
[2012]4321 double factor2 = xMatrix[i][k];
4322 for (int j = k; j < 2*nDOF; ++j) {
4323 xMatrix[i][j] *= factor1;
4324 xMatrix[i][j] -= xMatrix[k][j]*factor2;
[2773]4325 xMatrix[i][j] *= invfactor1;
[2012]4326 }
4327 }
4328 }
[2773]4329 double invXDiag = 1.0 / xMatrix[k][k];
[2012]4330 for (int j = k; j < 2*nDOF; ++j) {
[2773]4331 xMatrix[k][j] *= invXDiag;
[2012]4332 }
4333 }
4334
4335 for (int i = 0; i < nDOF; ++i) {
4336 for (int j = 0; j < nDOF; ++j) {
4337 xMatrix[i][nDOF+j] *= invDiag[j];
4338 }
4339 }
[2767]4340
[2012]4341 //compute a vector y which consists of the coefficients of the best-fit spline curves
4342 //(a0,a1,a2,a3(,b3,c3,...)), namely, the ones for the leftmost piece and the ones of
4343 //cubic terms for the other pieces (in case nPiece>1).
[2344]4344 std::vector<double> y(nDOF);
[2012]4345 for (int i = 0; i < nDOF; ++i) {
[2344]4346 y[i] = 0.0;
[2012]4347 for (int j = 0; j < nDOF; ++j) {
4348 y[i] += xMatrix[i][nDOF+j]*zMatrix[j];
4349 }
4350 }
4351
[2773]4352 std::vector<double> a(nModel);
4353 for (int i = 0; i < nModel; ++i) {
4354 a[i] = y[i];
4355 }
[2012]4356
[2344]4357 int j = 0;
[2012]4358 for (int n = 0; n < nPiece; ++n) {
[2064]4359 for (int i = idxEdge[n]; i < idxEdge[n+1]; ++i) {
[2773]4360 r1[i] = 0.0;
4361 for (int j = 0; j < nModel; ++j) {
4362 r1[i] += a[j] * model[j][i];
4363 }
[2012]4364 }
[2773]4365 for (int i = 0; i < nModel; ++i) {
4366 params[j+i] = a[i];
4367 }
4368 j += nModel;
[2012]4369
4370 if (n == nPiece-1) break;
4371
[2773]4372 double d = y[n+nModel];
[2064]4373 double iE = invEdge[n];
[2773]4374 a[0] += d;
4375 a[1] -= 3.0 * d * iE;
4376 a[2] += 3.0 * d * iE * iE;
4377 a[3] -= d * iE * iE * iE;
[2012]4378 }
4379
[2344]4380 //subtract constant value for masked regions at the edge of spectrum
4381 if (idxEdge[0] > 0) {
4382 int n = idxEdge[0];
4383 for (int i = 0; i < idxEdge[0]; ++i) {
4384 //--cubic extrapolate--
4385 //r1[i] = params[0] + params[1]*x1[i] + params[2]*x2[i] + params[3]*x3[i];
4386 //--linear extrapolate--
4387 //r1[i] = (r1[n+1] - r1[n])/(x1[n+1] - x1[n])*(x1[i] - x1[n]) + r1[n];
4388 //--constant--
4389 r1[i] = r1[n];
4390 }
4391 }
[2767]4392
[2344]4393 if (idxEdge[nPiece] < nChan) {
4394 int n = idxEdge[nPiece]-1;
4395 for (int i = idxEdge[nPiece]; i < nChan; ++i) {
4396 //--cubic extrapolate--
4397 //int m = 4*(nPiece-1);
4398 //r1[i] = params[m] + params[m+1]*x1[i] + params[m+2]*x2[i] + params[m+3]*x3[i];
4399 //--linear extrapolate--
4400 //r1[i] = (r1[n-1] - r1[n])/(x1[n-1] - x1[n])*(x1[i] - x1[n]) + r1[n];
4401 //--constant--
4402 r1[i] = r1[n];
4403 }
4404 }
4405
4406 for (int i = 0; i < nChan; ++i) {
4407 residual[i] = z1[i] - r1[i];
4408 }
4409
[2767]4410 double stdDev = 0.0;
4411 for (int i = 0; i < nChan; ++i) {
[2890]4412 if (maskArray[i] == 0) continue;
4413 stdDev += residual[i]*residual[i];
[2767]4414 }
4415 stdDev = sqrt(stdDev/(double)nData);
4416 rms = (float)stdDev;
4417
[2012]4418 if ((nClip == nIterClip) || (thresClip <= 0.0)) {
4419 break;
4420 } else {
4421
4422 double thres = stdDev * thresClip;
4423 int newNData = 0;
4424 for (int i = 0; i < nChan; ++i) {
[2081]4425 if (abs(residual[i]) >= thres) {
[2012]4426 maskArray[i] = 0;
[2767]4427 finalMask[i] = false;
[2012]4428 }
4429 if (maskArray[i] > 0) {
4430 newNData++;
4431 }
4432 }
[2081]4433 if (newNData == nData) {
[2064]4434 break; //no more flag to add. iteration stops.
[2012]4435 } else {
[2081]4436 nData = newNData;
[2012]4437 }
[2767]4438
[2012]4439 }
4440 }
4441
[2193]4442 nClipped = initNData - nData;
4443
[2344]4444 std::vector<float> result(nChan);
[2058]4445 if (getResidual) {
4446 for (int i = 0; i < nChan; ++i) {
[2344]4447 result[i] = (float)residual[i];
[2058]4448 }
4449 } else {
4450 for (int i = 0; i < nChan; ++i) {
[2344]4451 result[i] = (float)r1[i];
[2058]4452 }
[2012]4453 }
4454
[2058]4455 return result;
[2012]4456}
4457
[2773]4458std::vector<int> Scantable::selectWaveNumbers(const std::vector<int>& addNWaves,
4459 const std::vector<int>& rejectNWaves)
[2081]4460{
[2773]4461 std::vector<bool> chanMask;
[2767]4462 std::string fftMethod;
4463 std::string fftThresh;
4464
[2773]4465 return selectWaveNumbers(0, chanMask, false, fftMethod, fftThresh, addNWaves, rejectNWaves);
4466}
4467
4468std::vector<int> Scantable::selectWaveNumbers(const int whichrow,
4469 const std::vector<bool>& chanMask,
4470 const bool applyFFT,
4471 const std::string& fftMethod,
4472 const std::string& fftThresh,
4473 const std::vector<int>& addNWaves,
4474 const std::vector<int>& rejectNWaves)
4475{
4476 std::vector<int> nWaves;
[2186]4477 nWaves.clear();
4478
4479 if (applyFFT) {
4480 string fftThAttr;
4481 float fftThSigma;
4482 int fftThTop;
[2773]4483 parseFFTThresholdInfo(fftThresh, fftThAttr, fftThSigma, fftThTop);
[2186]4484 doSelectWaveNumbers(whichrow, chanMask, fftMethod, fftThSigma, fftThTop, fftThAttr, nWaves);
4485 }
4486
[2411]4487 addAuxWaveNumbers(whichrow, addNWaves, rejectNWaves, nWaves);
[2773]4488
4489 return nWaves;
[2186]4490}
4491
[2773]4492int Scantable::getIdxOfNchan(const int nChan, const std::vector<int>& nChanNos)
4493{
4494 int idx = -1;
4495 for (uint i = 0; i < nChanNos.size(); ++i) {
4496 if (nChan == nChanNos[i]) {
4497 idx = i;
4498 break;
4499 }
4500 }
4501
4502 if (idx < 0) {
4503 throw(AipsError("nChan not found in nChhanNos."));
4504 }
4505
4506 return idx;
4507}
4508
[2767]4509void Scantable::parseFFTInfo(const std::string& fftInfo, bool& applyFFT, std::string& fftMethod, std::string& fftThresh)
4510{
4511 istringstream iss(fftInfo);
4512 std::string tmp;
4513 std::vector<string> res;
4514 while (getline(iss, tmp, ',')) {
4515 res.push_back(tmp);
4516 }
4517 if (res.size() < 3) {
4518 throw(AipsError("wrong value in 'fftinfo' parameter")) ;
4519 }
4520 applyFFT = (res[0] == "true");
4521 fftMethod = res[1];
4522 fftThresh = res[2];
4523}
4524
[2773]4525void Scantable::parseFFTThresholdInfo(const std::string& fftThresh, std::string& fftThAttr, float& fftThSigma, int& fftThTop)
[2186]4526{
4527 uInt idxSigma = fftThresh.find("sigma");
4528 uInt idxTop = fftThresh.find("top");
4529
4530 if (idxSigma == fftThresh.size() - 5) {
4531 std::istringstream is(fftThresh.substr(0, fftThresh.size() - 5));
4532 is >> fftThSigma;
4533 fftThAttr = "sigma";
4534 } else if (idxTop == 0) {
4535 std::istringstream is(fftThresh.substr(3));
4536 is >> fftThTop;
4537 fftThAttr = "top";
4538 } else {
4539 bool isNumber = true;
4540 for (uInt i = 0; i < fftThresh.size()-1; ++i) {
4541 char ch = (fftThresh.substr(i, 1).c_str())[0];
4542 if (!(isdigit(ch) || (fftThresh.substr(i, 1) == "."))) {
4543 isNumber = false;
4544 break;
4545 }
4546 }
4547 if (isNumber) {
4548 std::istringstream is(fftThresh);
4549 is >> fftThSigma;
4550 fftThAttr = "sigma";
4551 } else {
4552 throw(AipsError("fftthresh has a wrong value"));
4553 }
4554 }
4555}
4556
4557void 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)
4558{
4559 std::vector<float> fspec;
4560 if (fftMethod == "fft") {
4561 fspec = execFFT(whichrow, chanMask, false, true);
4562 //} else if (fftMethod == "lsp") {
4563 // fspec = lombScarglePeriodogram(whichrow);
4564 }
4565
4566 if (fftThAttr == "sigma") {
4567 float mean = 0.0;
4568 float mean2 = 0.0;
4569 for (uInt i = 0; i < fspec.size(); ++i) {
4570 mean += fspec[i];
4571 mean2 += fspec[i]*fspec[i];
4572 }
4573 mean /= float(fspec.size());
4574 mean2 /= float(fspec.size());
4575 float thres = mean + fftThSigma * float(sqrt(mean2 - mean*mean));
4576
4577 for (uInt i = 0; i < fspec.size(); ++i) {
4578 if (fspec[i] >= thres) {
4579 nWaves.push_back(i);
4580 }
4581 }
4582
4583 } else if (fftThAttr == "top") {
4584 for (int i = 0; i < fftThTop; ++i) {
4585 float max = 0.0;
4586 int maxIdx = 0;
4587 for (uInt j = 0; j < fspec.size(); ++j) {
4588 if (fspec[j] > max) {
4589 max = fspec[j];
4590 maxIdx = j;
4591 }
4592 }
4593 nWaves.push_back(maxIdx);
4594 fspec[maxIdx] = 0.0;
4595 }
4596
4597 }
4598
4599 if (nWaves.size() > 1) {
4600 sort(nWaves.begin(), nWaves.end());
4601 }
4602}
4603
[2411]4604void Scantable::addAuxWaveNumbers(const int whichrow, const std::vector<int>& addNWaves, const std::vector<int>& rejectNWaves, std::vector<int>& nWaves)
[2186]4605{
[2411]4606 std::vector<int> tempAddNWaves, tempRejectNWaves;
[2767]4607 tempAddNWaves.clear();
4608 tempRejectNWaves.clear();
4609
[2186]4610 for (uInt i = 0; i < addNWaves.size(); ++i) {
[2411]4611 tempAddNWaves.push_back(addNWaves[i]);
4612 }
4613 if ((tempAddNWaves.size() == 2) && (tempAddNWaves[1] == -999)) {
4614 setWaveNumberListUptoNyquistFreq(whichrow, tempAddNWaves);
4615 }
4616
4617 for (uInt i = 0; i < rejectNWaves.size(); ++i) {
4618 tempRejectNWaves.push_back(rejectNWaves[i]);
4619 }
4620 if ((tempRejectNWaves.size() == 2) && (tempRejectNWaves[1] == -999)) {
4621 setWaveNumberListUptoNyquistFreq(whichrow, tempRejectNWaves);
4622 }
4623
4624 for (uInt i = 0; i < tempAddNWaves.size(); ++i) {
[2186]4625 bool found = false;
4626 for (uInt j = 0; j < nWaves.size(); ++j) {
[2411]4627 if (nWaves[j] == tempAddNWaves[i]) {
[2186]4628 found = true;
4629 break;
4630 }
4631 }
[2411]4632 if (!found) nWaves.push_back(tempAddNWaves[i]);
[2186]4633 }
4634
[2411]4635 for (uInt i = 0; i < tempRejectNWaves.size(); ++i) {
[2186]4636 for (std::vector<int>::iterator j = nWaves.begin(); j != nWaves.end(); ) {
[2411]4637 if (*j == tempRejectNWaves[i]) {
[2186]4638 j = nWaves.erase(j);
4639 } else {
4640 ++j;
4641 }
4642 }
4643 }
4644
4645 if (nWaves.size() > 1) {
4646 sort(nWaves.begin(), nWaves.end());
4647 unique(nWaves.begin(), nWaves.end());
4648 }
4649}
4650
[2411]4651void Scantable::setWaveNumberListUptoNyquistFreq(const int whichrow, std::vector<int>& nWaves)
4652{
[2767]4653 int val = nWaves[0];
4654 int nyquistFreq = nchan(getIF(whichrow))/2+1;
4655 nWaves.clear();
4656 if (val > nyquistFreq) { // for safety, at least nWaves contains a constant; CAS-3759
4657 nWaves.push_back(0);
[2411]4658 }
[2767]4659 while (val <= nyquistFreq) {
4660 nWaves.push_back(val);
4661 val++;
4662 }
[2411]4663}
4664
[2773]4665void Scantable::sinusoidBaseline(const std::vector<bool>& mask, const std::string& fftInfo,
4666 const std::vector<int>& addNWaves,
4667 const std::vector<int>& rejectNWaves,
4668 float thresClip, int nIterClip,
4669 bool getResidual,
4670 const std::string& progressInfo,
4671 const bool outLogger, const std::string& blfile,
4672 const std::string& bltable)
[2186]4673{
[2774]4674 /****
[2773]4675 double TimeStart = mathutil::gettimeofday_sec();
[2774]4676 ****/
[2773]4677
[2193]4678 try {
4679 ofstream ofs;
[2773]4680 String coordInfo;
4681 bool hasSameNchan, outTextFile, csvFormat, showProgress;
4682 int minNRow;
4683 int nRow = nrow();
4684 std::vector<bool> chanMask, finalChanMask;
4685 float rms;
4686 bool outBaselineTable = (bltable != "");
4687 STBaselineTable bt = STBaselineTable(*this);
4688 Vector<Double> timeSecCol;
[2012]4689
[2773]4690 initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
4691 coordInfo, hasSameNchan,
4692 progressInfo, showProgress, minNRow,
4693 timeSecCol);
[2012]4694
[2773]4695 bool applyFFT;
4696 std::string fftMethod, fftThresh;
4697 parseFFTInfo(fftInfo, applyFFT, fftMethod, fftThresh);
[2012]4698
[2193]4699 std::vector<int> nWaves;
[2773]4700 std::vector<int> nChanNos;
4701 std::vector<std::vector<std::vector<double> > > modelReservoir;
4702 if (!applyFFT) {
4703 nWaves = selectWaveNumbers(addNWaves, rejectNWaves);
4704 modelReservoir = getSinusoidModelReservoir(nWaves, nChanNos);
4705 }
[2012]4706
[2193]4707 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
[2767]4708 std::vector<float> sp = getSpectrum(whichrow);
[2193]4709 chanMask = getCompositeChanMask(whichrow, mask);
[2773]4710 std::vector<std::vector<double> > model;
4711 if (applyFFT) {
4712 nWaves = selectWaveNumbers(whichrow, chanMask, true, fftMethod, fftThresh,
4713 addNWaves, rejectNWaves);
4714 model = getSinusoidModel(nWaves, sp.size());
4715 } else {
4716 model = modelReservoir[getIdxOfNchan(sp.size(), nChanNos)];
4717 }
[2968]4718 int nModel = modelReservoir.size();
[2186]4719
[2767]4720 std::vector<float> params;
[2968]4721
[3023]4722 //if (flagrowCol_(whichrow) == 0) {
4723 if (flagrowCol_(whichrow)==0 && nValidMask(chanMask)>0) {
[2968]4724 int nClipped = 0;
4725 std::vector<float> res;
4726 res = doLeastSquareFitting(sp, chanMask, model,
[2773]4727 params, rms, finalChanMask,
4728 nClipped, thresClip, nIterClip, getResidual);
[2767]4729
[2968]4730 if (outBaselineTable) {
4731 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
4732 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
4733 true, STBaselineFunc::Sinusoid, nWaves, std::vector<float>(),
4734 getMaskListFromMask(finalChanMask), params, rms, sp.size(),
4735 thresClip, nIterClip, 0.0, 0, std::vector<int>());
4736 } else {
4737 setSpectrum(res, whichrow);
4738 }
4739
4740 outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
4741 coordInfo, hasSameNchan, ofs, "sinusoidBaseline()",
4742 params, nClipped);
[2767]4743 } else {
[3024]4744 // no valid channels to fit (flag the row)
4745 flagrowCol_.put(whichrow, 1);
[2968]4746 if (outBaselineTable) {
4747 params.resize(nModel);
4748 for (uInt i = 0; i < params.size(); ++i) {
4749 params[i] = 0.0;
4750 }
4751 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
4752 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
4753 true, STBaselineFunc::Sinusoid, nWaves, std::vector<float>(),
4754 getMaskListFromMask(chanMask), params, 0.0, sp.size(),
4755 thresClip, nIterClip, 0.0, 0, std::vector<int>());
4756 }
[2186]4757 }
[2193]4758
4759 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
[2186]4760 }
4761
[2773]4762 finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
[2767]4763
[2193]4764 } catch (...) {
4765 throw;
[1931]4766 }
[2773]4767
[2774]4768 /****
[2773]4769 double TimeEnd = mathutil::gettimeofday_sec();
4770 double elapse1 = TimeEnd - TimeStart;
4771 std::cout << "sinusoid-old : " << elapse1 << " (sec.)" << endl;
[2774]4772 ****/
[1907]4773}
4774
[2773]4775void Scantable::autoSinusoidBaseline(const std::vector<bool>& mask, const std::string& fftInfo,
4776 const std::vector<int>& addNWaves,
4777 const std::vector<int>& rejectNWaves,
4778 float thresClip, int nIterClip,
4779 const std::vector<int>& edge,
4780 float threshold, int chanAvgLimit,
4781 bool getResidual,
4782 const std::string& progressInfo,
4783 const bool outLogger, const std::string& blfile,
4784 const std::string& bltable)
[2012]4785{
[2193]4786 try {
4787 ofstream ofs;
[2773]4788 String coordInfo;
4789 bool hasSameNchan, outTextFile, csvFormat, showProgress;
4790 int minNRow;
4791 int nRow = nrow();
4792 std::vector<bool> chanMask, finalChanMask;
4793 float rms;
4794 bool outBaselineTable = (bltable != "");
4795 STBaselineTable bt = STBaselineTable(*this);
4796 Vector<Double> timeSecCol;
4797 STLineFinder lineFinder = STLineFinder();
[2012]4798
[2773]4799 initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
4800 coordInfo, hasSameNchan,
4801 progressInfo, showProgress, minNRow,
4802 timeSecCol);
[2012]4803
[2773]4804 initLineFinder(edge, threshold, chanAvgLimit, lineFinder);
[2012]4805
[2773]4806 bool applyFFT;
4807 string fftMethod, fftThresh;
4808 parseFFTInfo(fftInfo, applyFFT, fftMethod, fftThresh);
[2012]4809
[2193]4810 std::vector<int> nWaves;
[2773]4811 std::vector<int> nChanNos;
4812 std::vector<std::vector<std::vector<double> > > modelReservoir;
4813 if (!applyFFT) {
4814 nWaves = selectWaveNumbers(addNWaves, rejectNWaves);
4815 modelReservoir = getSinusoidModelReservoir(nWaves, nChanNos);
4816 }
[2186]4817
[2193]4818 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
[2767]4819 std::vector<float> sp = getSpectrum(whichrow);
[2193]4820 std::vector<int> currentEdge;
[2773]4821 chanMask = getCompositeChanMask(whichrow, mask, edge, currentEdge, lineFinder);
4822 std::vector<std::vector<double> > model;
4823 if (applyFFT) {
4824 nWaves = selectWaveNumbers(whichrow, chanMask, true, fftMethod, fftThresh,
4825 addNWaves, rejectNWaves);
4826 model = getSinusoidModel(nWaves, sp.size());
[2193]4827 } else {
[2773]4828 model = modelReservoir[getIdxOfNchan(sp.size(), nChanNos)];
[2012]4829 }
[2968]4830 int nModel = modelReservoir.size();
[2193]4831
4832 std::vector<float> params;
[2968]4833
[3023]4834 //if (flagrowCol_(whichrow) == 0) {
4835 if (flagrowCol_(whichrow)==0 && nValidMask(chanMask)>0) {
[2968]4836 int nClipped = 0;
4837 std::vector<float> res;
4838 res = doLeastSquareFitting(sp, chanMask, model,
[2773]4839 params, rms, finalChanMask,
4840 nClipped, thresClip, nIterClip, getResidual);
[2193]4841
[2968]4842 if (outBaselineTable) {
4843 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
4844 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
4845 true, STBaselineFunc::Sinusoid, nWaves, std::vector<float>(),
4846 getMaskListFromMask(finalChanMask), params, rms, sp.size(),
4847 thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
4848 } else {
4849 setSpectrum(res, whichrow);
4850 }
4851
4852 outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
4853 coordInfo, hasSameNchan, ofs, "autoSinusoidBaseline()",
4854 params, nClipped);
[2767]4855 } else {
[3024]4856 // no valid channels to fit (flag the row)
4857 flagrowCol_.put(whichrow, 1);
[2968]4858 if (outBaselineTable) {
4859 params.resize(nModel);
4860 for (uInt i = 0; i < params.size(); ++i) {
4861 params[i] = 0.0;
4862 }
4863 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
4864 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
4865 true, STBaselineFunc::Sinusoid, nWaves, std::vector<float>(),
4866 getMaskListFromMask(chanMask), params, 0.0, sp.size(),
4867 thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
4868 }
[2767]4869 }
4870
[2193]4871 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
[2012]4872 }
4873
[2773]4874 finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
[2767]4875
[2193]4876 } catch (...) {
4877 throw;
[2047]4878 }
4879}
4880
[2773]4881std::vector<float> Scantable::doSinusoidFitting(const std::vector<float>& data,
4882 const std::vector<bool>& mask,
4883 const std::vector<int>& waveNumbers,
4884 std::vector<float>& params,
4885 float& rms,
4886 std::vector<bool>& finalmask,
4887 float clipth,
4888 int clipn)
[2081]4889{
[2767]4890 int nClipped = 0;
4891 return doSinusoidFitting(data, mask, waveNumbers, params, rms, finalmask, nClipped, clipth, clipn);
4892}
4893
[2773]4894std::vector<float> Scantable::doSinusoidFitting(const std::vector<float>& data,
4895 const std::vector<bool>& mask,
4896 const std::vector<int>& waveNumbers,
4897 std::vector<float>& params,
4898 float& rms,
4899 std::vector<bool>& finalMask,
4900 int& nClipped,
4901 float thresClip,
4902 int nIterClip,
4903 bool getResidual)
[2767]4904{
[2773]4905 return doLeastSquareFitting(data, mask,
4906 getSinusoidModel(waveNumbers, data.size()),
4907 params, rms, finalMask,
4908 nClipped, thresClip, nIterClip,
4909 getResidual);
4910}
4911
4912std::vector<std::vector<std::vector<double> > > Scantable::getSinusoidModelReservoir(const std::vector<int>& waveNumbers,
4913 std::vector<int>& nChanNos)
4914{
4915 std::vector<std::vector<std::vector<double> > > res;
4916 res.clear();
4917 nChanNos.clear();
4918
4919 std::vector<uint> ifNos = getIFNos();
4920 for (uint i = 0; i < ifNos.size(); ++i) {
4921 int currNchan = nchan(ifNos[i]);
4922 bool hasDifferentNchan = (i == 0);
4923 for (uint j = 0; j < i; ++j) {
4924 if (currNchan != nchan(ifNos[j])) {
4925 hasDifferentNchan = true;
4926 break;
4927 }
4928 }
4929 if (hasDifferentNchan) {
4930 res.push_back(getSinusoidModel(waveNumbers, currNchan));
4931 nChanNos.push_back(currNchan);
4932 }
[2047]4933 }
[2773]4934
4935 return res;
4936}
4937
4938std::vector<std::vector<double> > Scantable::getSinusoidModel(const std::vector<int>& waveNumbers, int nchan)
4939{
4940 // model : contains elemental values for computing the least-square matrix.
4941 // model.size() is nmodel and model[*].size() is nchan.
4942 // Each model element are as follows:
4943 // model[0] = {1.0, 1.0, 1.0, ..., 1.0},
4944 // model[2n-1] = {sin(nPI/L*x[0]), sin(nPI/L*x[1]), ..., sin(nPI/L*x[nchan])},
4945 // model[2n] = {cos(nPI/L*x[0]), cos(nPI/L*x[1]), ..., cos(nPI/L*x[nchan])},
4946 // where (1 <= n <= nMaxWavesInSW),
4947 // or,
4948 // model[2n-1] = {sin(wn[n]PI/L*x[0]), sin(wn[n]PI/L*x[1]), ..., sin(wn[n]PI/L*x[nchan])},
4949 // model[2n] = {cos(wn[n]PI/L*x[0]), cos(wn[n]PI/L*x[1]), ..., cos(wn[n]PI/L*x[nchan])},
4950 // where wn[n] denotes waveNumbers[n] (1 <= n <= waveNumbers.size()).
4951
[2081]4952 std::vector<int> nWaves; // sorted and uniqued array of wave numbers
4953 nWaves.reserve(waveNumbers.size());
4954 copy(waveNumbers.begin(), waveNumbers.end(), back_inserter(nWaves));
4955 sort(nWaves.begin(), nWaves.end());
4956 std::vector<int>::iterator end_it = unique(nWaves.begin(), nWaves.end());
4957 nWaves.erase(end_it, nWaves.end());
4958
4959 int minNWaves = nWaves[0];
4960 if (minNWaves < 0) {
[2058]4961 throw(AipsError("wave number must be positive or zero (i.e. constant)"));
4962 }
[2081]4963 bool hasConstantTerm = (minNWaves == 0);
[2773]4964 int nmodel = nWaves.size() * 2 - (hasConstantTerm ? 1 : 0); //number of parameters to solve.
[2047]4965
[2773]4966 std::vector<std::vector<double> > model(nmodel, std::vector<double>(nchan));
[2767]4967
[2773]4968 if (hasConstantTerm) {
4969 for (int j = 0; j < nchan; ++j) {
4970 model[0][j] = 1.0;
[2047]4971 }
4972 }
4973
[2081]4974 const double PI = 6.0 * asin(0.5); // PI (= 3.141592653...)
[2773]4975 double stretch0 = 2.0*PI/(double)(nchan-1);
[2081]4976
4977 for (uInt i = (hasConstantTerm ? 1 : 0); i < nWaves.size(); ++i) {
[2773]4978 int sidx = hasConstantTerm ? 2*i-1 : 2*i;
4979 int cidx = sidx + 1;
4980 double stretch = stretch0*(double)nWaves[i];
[2081]4981
[2773]4982 for (int j = 0; j < nchan; ++j) {
4983 model[sidx][j] = sin(stretch*(double)j);
4984 model[cidx][j] = cos(stretch*(double)j);
[2047]4985 }
[2012]4986 }
4987
[2773]4988 return model;
[2012]4989}
4990
[2773]4991std::vector<bool> Scantable::getCompositeChanMask(int whichrow,
4992 const std::vector<bool>& inMask)
[2047]4993{
[2186]4994 std::vector<bool> mask = getMask(whichrow);
4995 uInt maskSize = mask.size();
[2410]4996 if (inMask.size() != 0) {
4997 if (maskSize != inMask.size()) {
4998 throw(AipsError("mask sizes are not the same."));
4999 }
5000 for (uInt i = 0; i < maskSize; ++i) {
5001 mask[i] = mask[i] && inMask[i];
5002 }
[2047]5003 }
5004
[2186]5005 return mask;
[2047]5006}
5007
[2773]5008std::vector<bool> Scantable::getCompositeChanMask(int whichrow,
5009 const std::vector<bool>& inMask,
5010 const std::vector<int>& edge,
5011 std::vector<int>& currEdge,
5012 STLineFinder& lineFinder)
[2047]5013{
[3023]5014 if (isAllChannelsFlagged(whichrow)) {//all channels flagged
5015 std::vector<bool> res_mask(inMask.size(),false);
5016 return res_mask;
5017 } else if (nValidMask(inMask)==0){ //no valid mask channels
5018 std::vector<bool> res_mask(inMask);
5019 return res_mask;
5020 }
5021
[2773]5022 std::vector<uint> ifNos = getIFNos();
[2774]5023 if ((edge.size() > 2) && (edge.size() < ifNos.size()*2)) {
[2773]5024 throw(AipsError("Length of edge element info is less than that of IFs"));
[2047]5025 }
5026
[2774]5027 uint idx = 0;
5028 if (edge.size() > 2) {
5029 int ifVal = getIF(whichrow);
5030 bool foundIF = false;
5031 for (uint i = 0; i < ifNos.size(); ++i) {
5032 if (ifVal == (int)ifNos[i]) {
5033 idx = 2*i;
5034 foundIF = true;
5035 break;
5036 }
[2773]5037 }
[2774]5038 if (!foundIF) {
5039 throw(AipsError("bad IF number"));
5040 }
[2773]5041 }
5042
5043 currEdge.clear();
5044 currEdge.resize(2);
5045 currEdge[0] = edge[idx];
5046 currEdge[1] = edge[idx+1];
5047
[2047]5048 lineFinder.setData(getSpectrum(whichrow));
[2773]5049 lineFinder.findLines(getCompositeChanMask(whichrow, inMask), currEdge, whichrow);
[2047]5050 return lineFinder.getMask();
5051}
5052
5053/* for cspline. will be merged once cspline is available in fitter (2011/3/10 WK) */
[2773]5054void Scantable::outputFittingResult(bool outLogger,
5055 bool outTextFile,
5056 bool csvFormat,
5057 const std::vector<bool>& chanMask,
5058 int whichrow,
5059 const casa::String& coordInfo,
5060 bool hasSameNchan,
5061 ofstream& ofs,
5062 const casa::String& funcName,
5063 const std::vector<int>& edge,
5064 const std::vector<float>& params,
5065 const int nClipped)
[2186]5066{
[2047]5067 if (outLogger || outTextFile) {
5068 float rms = getRms(chanMask, whichrow);
5069 String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
[2081]5070 std::vector<bool> fixed;
5071 fixed.clear();
[2047]5072
5073 if (outLogger) {
5074 LogIO ols(LogOrigin("Scantable", funcName, WHERE));
[2773]5075 ols << formatPiecewiseBaselineParams(edge, params, fixed, rms, nClipped,
5076 masklist, whichrow, false, csvFormat) << LogIO::POST ;
[2047]5077 }
5078 if (outTextFile) {
[2773]5079 ofs << formatPiecewiseBaselineParams(edge, params, fixed, rms, nClipped,
5080 masklist, whichrow, true, csvFormat) << flush;
[2047]5081 }
5082 }
5083}
5084
[2773]5085/* for poly/chebyshev/sinusoid. */
5086void Scantable::outputFittingResult(bool outLogger,
5087 bool outTextFile,
5088 bool csvFormat,
5089 const std::vector<bool>& chanMask,
5090 int whichrow,
5091 const casa::String& coordInfo,
5092 bool hasSameNchan,
5093 ofstream& ofs,
5094 const casa::String& funcName,
5095 const std::vector<float>& params,
5096 const int nClipped)
[2186]5097{
[2047]5098 if (outLogger || outTextFile) {
5099 float rms = getRms(chanMask, whichrow);
5100 String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
[2081]5101 std::vector<bool> fixed;
5102 fixed.clear();
[2047]5103
5104 if (outLogger) {
5105 LogIO ols(LogOrigin("Scantable", funcName, WHERE));
[2773]5106 ols << formatBaselineParams(params, fixed, rms, nClipped,
5107 masklist, whichrow, false, csvFormat) << LogIO::POST ;
[2047]5108 }
5109 if (outTextFile) {
[2773]5110 ofs << formatBaselineParams(params, fixed, rms, nClipped,
5111 masklist, whichrow, true, csvFormat) << flush;
[2047]5112 }
5113 }
5114}
5115
[2189]5116void Scantable::parseProgressInfo(const std::string& progressInfo, bool& showProgress, int& minNRow)
[2186]5117{
[2189]5118 int idxDelimiter = progressInfo.find(",");
5119 if (idxDelimiter < 0) {
5120 throw(AipsError("wrong value in 'showprogress' parameter")) ;
5121 }
5122 showProgress = (progressInfo.substr(0, idxDelimiter) == "true");
5123 std::istringstream is(progressInfo.substr(idxDelimiter+1));
5124 is >> minNRow;
5125}
5126
5127void Scantable::showProgressOnTerminal(const int nProcessed, const int nTotal, const bool showProgress, const int nTotalThreshold)
5128{
5129 if (showProgress && (nTotal >= nTotalThreshold)) {
[2186]5130 int nInterval = int(floor(double(nTotal)/100.0));
5131 if (nInterval == 0) nInterval++;
5132
[2193]5133 if (nProcessed % nInterval == 0) {
[2189]5134 printf("\r"); //go to the head of line
[2186]5135 printf("\x1b[31m\x1b[1m"); //set red color, highlighted
[2189]5136 printf("[%3d%%]", (int)(100.0*(double(nProcessed+1))/(double(nTotal))) );
5137 printf("\x1b[39m\x1b[0m"); //set default attributes
[2186]5138 fflush(NULL);
5139 }
[2193]5140
[2186]5141 if (nProcessed == nTotal - 1) {
5142 printf("\r\x1b[K"); //clear
5143 fflush(NULL);
5144 }
[2193]5145
[2186]5146 }
5147}
5148
5149std::vector<float> Scantable::execFFT(const int whichrow, const std::vector<bool>& inMask, bool getRealImag, bool getAmplitudeOnly)
5150{
5151 std::vector<bool> mask = getMask(whichrow);
5152
5153 if (inMask.size() > 0) {
5154 uInt maskSize = mask.size();
5155 if (maskSize != inMask.size()) {
5156 throw(AipsError("mask sizes are not the same."));
5157 }
5158 for (uInt i = 0; i < maskSize; ++i) {
5159 mask[i] = mask[i] && inMask[i];
5160 }
5161 }
5162
5163 Vector<Float> spec = getSpectrum(whichrow);
5164 mathutil::doZeroOrderInterpolation(spec, mask);
5165
5166 FFTServer<Float,Complex> ffts;
5167 Vector<Complex> fftres;
5168 ffts.fft0(fftres, spec);
5169
5170 std::vector<float> res;
5171 float norm = float(2.0/double(spec.size()));
5172
5173 if (getRealImag) {
5174 for (uInt i = 0; i < fftres.size(); ++i) {
5175 res.push_back(real(fftres[i])*norm);
5176 res.push_back(imag(fftres[i])*norm);
5177 }
5178 } else {
5179 for (uInt i = 0; i < fftres.size(); ++i) {
5180 res.push_back(abs(fftres[i])*norm);
5181 if (!getAmplitudeOnly) res.push_back(arg(fftres[i]));
5182 }
5183 }
5184
5185 return res;
5186}
5187
5188
5189float Scantable::getRms(const std::vector<bool>& mask, int whichrow)
5190{
[2591]5191 /****
[2737]5192 double ms1TimeStart, ms1TimeEnd;
[2591]5193 double elapse1 = 0.0;
5194 ms1TimeStart = mathutil::gettimeofday_sec();
5195 ****/
5196
[2012]5197 Vector<Float> spec;
5198 specCol_.get(whichrow, spec);
5199
[2591]5200 /****
5201 ms1TimeEnd = mathutil::gettimeofday_sec();
5202 elapse1 = ms1TimeEnd - ms1TimeStart;
5203 std::cout << "rm1 : " << elapse1 << " (sec.)" << endl;
5204 ****/
5205
[2737]5206 return (float)doGetRms(mask, spec);
5207}
5208
5209double Scantable::doGetRms(const std::vector<bool>& mask, const Vector<Float>& spec)
5210{
5211 double mean = 0.0;
5212 double smean = 0.0;
[2012]5213 int n = 0;
[2047]5214 for (uInt i = 0; i < spec.nelements(); ++i) {
[2012]5215 if (mask[i]) {
[2737]5216 double val = (double)spec[i];
5217 mean += val;
5218 smean += val*val;
[2012]5219 n++;
5220 }
5221 }
5222
[2737]5223 mean /= (double)n;
5224 smean /= (double)n;
[2012]5225
5226 return sqrt(smean - mean*mean);
5227}
5228
[2641]5229std::string Scantable::formatBaselineParamsHeader(int whichrow, const std::string& masklist, bool verbose, bool csvformat) const
[2012]5230{
[2641]5231 if (verbose) {
5232 ostringstream oss;
[2012]5233
[2641]5234 if (csvformat) {
5235 oss << getScan(whichrow) << ",";
5236 oss << getBeam(whichrow) << ",";
5237 oss << getIF(whichrow) << ",";
5238 oss << getPol(whichrow) << ",";
5239 oss << getCycle(whichrow) << ",";
5240 String commaReplacedMasklist = masklist;
5241 string::size_type pos = 0;
5242 while (pos = commaReplacedMasklist.find(","), pos != string::npos) {
5243 commaReplacedMasklist.replace(pos, 1, ";");
5244 pos++;
5245 }
5246 oss << commaReplacedMasklist << ",";
5247 } else {
5248 oss << " Scan[" << getScan(whichrow) << "]";
5249 oss << " Beam[" << getBeam(whichrow) << "]";
5250 oss << " IF[" << getIF(whichrow) << "]";
5251 oss << " Pol[" << getPol(whichrow) << "]";
5252 oss << " Cycle[" << getCycle(whichrow) << "]: " << endl;
5253 oss << "Fitter range = " << masklist << endl;
5254 oss << "Baseline parameters" << endl;
5255 }
[2012]5256 oss << flush;
[2641]5257
5258 return String(oss);
[2012]5259 }
5260
[2641]5261 return "";
[2012]5262}
5263
[2641]5264std::string Scantable::formatBaselineParamsFooter(float rms, int nClipped, bool verbose, bool csvformat) const
[2012]5265{
[2641]5266 if (verbose) {
5267 ostringstream oss;
[2012]5268
[2641]5269 if (csvformat) {
5270 oss << rms << ",";
5271 if (nClipped >= 0) {
5272 oss << nClipped;
5273 }
5274 } else {
5275 oss << "Results of baseline fit" << endl;
5276 oss << " rms = " << setprecision(6) << rms << endl;
5277 if (nClipped >= 0) {
5278 oss << " Number of clipped channels = " << nClipped << endl;
5279 }
5280 for (int i = 0; i < 60; ++i) {
5281 oss << "-";
5282 }
[2193]5283 }
[2131]5284 oss << endl;
[2094]5285 oss << flush;
[2641]5286
5287 return String(oss);
[2012]5288 }
5289
[2641]5290 return "";
[2012]5291}
5292
[2186]5293std::string Scantable::formatBaselineParams(const std::vector<float>& params,
5294 const std::vector<bool>& fixed,
5295 float rms,
[2193]5296 int nClipped,
[2186]5297 const std::string& masklist,
5298 int whichrow,
5299 bool verbose,
[2641]5300 bool csvformat,
[2186]5301 int start, int count,
5302 bool resetparamid) const
[2047]5303{
[2064]5304 int nParam = (int)(params.size());
[2047]5305
[2064]5306 if (nParam < 1) {
5307 return(" Not fitted");
5308 } else {
5309
5310 ostringstream oss;
[2641]5311 oss << formatBaselineParamsHeader(whichrow, masklist, verbose, csvformat);
[2064]5312
5313 if (start < 0) start = 0;
5314 if (count < 0) count = nParam;
5315 int end = start + count;
5316 if (end > nParam) end = nParam;
5317 int paramidoffset = (resetparamid) ? (-start) : 0;
5318
5319 for (int i = start; i < end; ++i) {
5320 if (i > start) {
[2047]5321 oss << ",";
5322 }
[2064]5323 std::string sFix = ((fixed.size() > 0) && (fixed[i]) && verbose) ? "(fixed)" : "";
[2641]5324 if (csvformat) {
5325 oss << params[i] << sFix;
5326 } else {
5327 oss << " p" << (i+paramidoffset) << sFix << "= " << right << setw(13) << setprecision(6) << params[i];
5328 }
[2047]5329 }
[2064]5330
[2641]5331 if (csvformat) {
5332 oss << ",";
[2644]5333 } else {
5334 oss << endl;
[2641]5335 }
5336 oss << formatBaselineParamsFooter(rms, nClipped, verbose, csvformat);
[2064]5337
5338 return String(oss);
[2047]5339 }
5340
5341}
5342
[2641]5343std::string Scantable::formatPiecewiseBaselineParams(const std::vector<int>& ranges, const std::vector<float>& params, const std::vector<bool>& fixed, float rms, int nClipped, const std::string& masklist, int whichrow, bool verbose, bool csvformat) const
[2012]5344{
[2064]5345 int nOutParam = (int)(params.size());
5346 int nPiece = (int)(ranges.size()) - 1;
[2012]5347
[2064]5348 if (nOutParam < 1) {
5349 return(" Not fitted");
5350 } else if (nPiece < 0) {
[2641]5351 return formatBaselineParams(params, fixed, rms, nClipped, masklist, whichrow, verbose, csvformat);
[2064]5352 } else if (nPiece < 1) {
5353 return(" Bad count of the piece edge info");
5354 } else if (nOutParam % nPiece != 0) {
5355 return(" Bad count of the output baseline parameters");
5356 } else {
5357
5358 int nParam = nOutParam / nPiece;
5359
5360 ostringstream oss;
[2641]5361 oss << formatBaselineParamsHeader(whichrow, masklist, verbose, csvformat);
[2064]5362
[2641]5363 if (csvformat) {
5364 for (int i = 0; i < nPiece; ++i) {
5365 oss << ranges[i] << "," << (ranges[i+1]-1) << ",";
5366 oss << formatBaselineParams(params, fixed, rms, 0, masklist, whichrow, false, csvformat, i*nParam, nParam, true);
5367 }
5368 } else {
5369 stringstream ss;
5370 ss << ranges[nPiece] << flush;
5371 int wRange = ss.str().size() * 2 + 5;
[2064]5372
[2641]5373 for (int i = 0; i < nPiece; ++i) {
5374 ss.str("");
5375 ss << " [" << ranges[i] << "," << (ranges[i+1]-1) << "]";
5376 oss << left << setw(wRange) << ss.str();
5377 oss << formatBaselineParams(params, fixed, rms, 0, masklist, whichrow, false, csvformat, i*nParam, nParam, true);
[2644]5378 //oss << endl;
[2641]5379 }
[2012]5380 }
[2064]5381
[2641]5382 oss << formatBaselineParamsFooter(rms, nClipped, verbose, csvformat);
[2064]5383
5384 return String(oss);
[2012]5385 }
5386
5387}
5388
[2047]5389bool Scantable::hasSameNchanOverIFs()
[2012]5390{
[2047]5391 int nIF = nif(-1);
5392 int nCh;
5393 int totalPositiveNChan = 0;
5394 int nPositiveNChan = 0;
[2012]5395
[2047]5396 for (int i = 0; i < nIF; ++i) {
5397 nCh = nchan(i);
5398 if (nCh > 0) {
5399 totalPositiveNChan += nCh;
5400 nPositiveNChan++;
[2012]5401 }
5402 }
5403
[2047]5404 return (totalPositiveNChan == (nPositiveNChan * nchan(0)));
[2012]5405}
5406
[2047]5407std::string Scantable::getMaskRangeList(const std::vector<bool>& mask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, bool verbose)
[2012]5408{
[2427]5409 if (mask.size() <= 0) {
5410 throw(AipsError("The mask elements should be > 0"));
[2012]5411 }
[2047]5412 int IF = getIF(whichrow);
5413 if (mask.size() != (uInt)nchan(IF)) {
[2012]5414 throw(AipsError("Number of channels in scantable != number of mask elements"));
5415 }
5416
[2047]5417 if (verbose) {
[2012]5418 LogIO logOs(LogOrigin("Scantable", "getMaskRangeList()", WHERE));
5419 logOs << LogIO::WARN << "The current mask window unit is " << coordInfo;
5420 if (!hasSameNchan) {
[2047]5421 logOs << endl << "This mask is only valid for IF=" << IF;
[2012]5422 }
5423 logOs << LogIO::POST;
5424 }
5425
5426 std::vector<double> abcissa = getAbcissa(whichrow);
[2047]5427 std::vector<int> edge = getMaskEdgeIndices(mask);
5428
[2012]5429 ostringstream oss;
5430 oss.setf(ios::fixed);
5431 oss << setprecision(1) << "[";
[2047]5432 for (uInt i = 0; i < edge.size(); i+=2) {
[2012]5433 if (i > 0) oss << ",";
[2047]5434 oss << "[" << (float)abcissa[edge[i]] << "," << (float)abcissa[edge[i+1]] << "]";
[2012]5435 }
5436 oss << "]" << flush;
5437
5438 return String(oss);
5439}
5440
[2047]5441std::vector<int> Scantable::getMaskEdgeIndices(const std::vector<bool>& mask)
[2012]5442{
[2427]5443 if (mask.size() <= 0) {
5444 throw(AipsError("The mask elements should be > 0"));
[2012]5445 }
5446
[2047]5447 std::vector<int> out, startIndices, endIndices;
5448 int maskSize = mask.size();
[2012]5449
[2047]5450 startIndices.clear();
5451 endIndices.clear();
5452
5453 if (mask[0]) {
5454 startIndices.push_back(0);
[2012]5455 }
[2047]5456 for (int i = 1; i < maskSize; ++i) {
5457 if ((!mask[i-1]) && mask[i]) {
5458 startIndices.push_back(i);
5459 } else if (mask[i-1] && (!mask[i])) {
5460 endIndices.push_back(i-1);
5461 }
[2012]5462 }
[2047]5463 if (mask[maskSize-1]) {
5464 endIndices.push_back(maskSize-1);
5465 }
[2012]5466
[2047]5467 if (startIndices.size() != endIndices.size()) {
5468 throw(AipsError("Inconsistent Mask Size: bad data?"));
5469 }
5470 for (uInt i = 0; i < startIndices.size(); ++i) {
5471 if (startIndices[i] > endIndices[i]) {
5472 throw(AipsError("Mask start index > mask end index"));
[2012]5473 }
5474 }
5475
[2047]5476 out.clear();
5477 for (uInt i = 0; i < startIndices.size(); ++i) {
5478 out.push_back(startIndices[i]);
5479 out.push_back(endIndices[i]);
5480 }
5481
[2012]5482 return out;
5483}
5484
[2791]5485void Scantable::setTsys(const std::vector<float>& newvals, int whichrow) {
5486 Vector<Float> tsys(newvals);
5487 if (whichrow > -1) {
5488 if (tsysCol_.shape(whichrow) != tsys.shape())
5489 throw(AipsError("Given Tsys values are not of the same shape"));
5490 tsysCol_.put(whichrow, tsys);
5491 } else {
5492 tsysCol_.fillColumn(tsys);
5493 }
5494}
5495
[2161]5496vector<float> Scantable::getTsysSpectrum( int whichrow ) const
5497{
5498 Vector<Float> tsys( tsysCol_(whichrow) ) ;
5499 vector<float> stlTsys ;
5500 tsys.tovector( stlTsys ) ;
5501 return stlTsys ;
5502}
[2012]5503
[2591]5504vector<uint> Scantable::getMoleculeIdColumnData() const
5505{
5506 Vector<uInt> molIds(mmolidCol_.getColumn());
5507 vector<uint> res;
5508 molIds.tovector(res);
5509 return res;
5510}
[2012]5511
[2591]5512void Scantable::setMoleculeIdColumnData(const std::vector<uint>& molids)
5513{
5514 Vector<uInt> molIds(molids);
5515 Vector<uInt> arr(mmolidCol_.getColumn());
5516 if ( molIds.nelements() != arr.nelements() )
5517 throw AipsError("The input data size must be the number of rows.");
5518 mmolidCol_.putColumn(molIds);
[1907]5519}
[2591]5520
5521
[2888]5522std::vector<uint> Scantable::getRootTableRowNumbers() const
5523{
5524 Vector<uInt> rowIds(table_.rowNumbers());
5525 vector<uint> res;
5526 rowIds.tovector(res);
5527 return res;
5528}
5529
5530
[2789]5531void Scantable::dropXPol()
5532{
5533 if (npol() <= 2) {
5534 return;
5535 }
5536 if (!selector_.empty()) {
5537 throw AipsError("Can only operate with empty selection");
5538 }
5539 std::string taql = "SELECT FROM $1 WHERE POLNO IN [0,1]";
5540 Table tab = tableCommand(taql, table_);
5541 table_ = tab;
5542 table_.rwKeywordSet().define("nPol", Int(2));
5543 originalTable_ = table_;
5544 attach();
[2591]5545}
[2789]5546
5547}
[1819]5548//namespace asap
Note: See TracBrowser for help on using the repository browser.