source: trunk/src/Scantable.cpp@ 2436

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

New Development: Yes

JIRA Issue: Yes (CAS-2818)

Ready for Test: Yes

Interface Changes: Yes

What Interface Changed: Added methods and functions
scantable.regrid_channel, scantable._regrid_specchan (defined in python_Scantable.cpp),
Scantable::regridSpecChannel, and ScantableWrapper::regridSpecChannel

Test Programs: comming soon with sdsmooth

Put in Release Notes: No

Module(s): scantable

Description:

Enabled regridding of spectra in a scantable.

scantable.regrid_channel(width, insitu=True/False)

will do this.
width can be either in channel, frequency, or velocity unit.
verification is not available yet.


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