source: trunk/src/Scantable.cpp@ 2814

Last change on this file since 2814 was 2813, checked in by Takeshi Nakazato, 11 years ago

New Development: No

JIRA Issue: Yes CSV-2709

Ready for Test: Yes

Interface Changes: No

What Interface Changed: Please list interface changes

Test Programs: List test programs

Put in Release Notes: Yes/No

Module(s): Module Names change impacts.

Description: Describe your changes here...

Bug fix on sdlist (Scantable::summary).
List of MOLECULE_IDs can change for each SCANNO.
The fix properly handles variable list of MOLECULE_IDs.

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