source: trunk/src/Scantable.cpp@ 2095

Last change on this file since 2095 was 2094, checked in by WataruKawasaki, 14 years ago

New Development: No

JIRA Issue: No

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs:

Put in Release Notes: No

Module(s): Scantable

Description: minor bugfix/cleanup.


  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 88.4 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>
[1819]13#include <fstream>
[206]14
[125]15#include <casa/aips.h>
[80]16#include <casa/iostream.h>
17#include <casa/iomanip.h>
[805]18#include <casa/OS/Path.h>
19#include <casa/OS/File.h>
[80]20#include <casa/Arrays/Array.h>
21#include <casa/Arrays/ArrayMath.h>
22#include <casa/Arrays/MaskArrMath.h>
23#include <casa/Arrays/ArrayLogical.h>
24#include <casa/Arrays/ArrayAccessor.h>
[1325]25#include <casa/Arrays/Vector.h>
[455]26#include <casa/Arrays/VectorSTLIterator.h>
[1819]27#include <casa/Arrays/Slice.h>
[418]28#include <casa/BasicMath/Math.h>
[504]29#include <casa/BasicSL/Constants.h>
[286]30#include <casa/Quanta/MVAngle.h>
[805]31#include <casa/Containers/RecordField.h>
[902]32#include <casa/Utilities/GenSort.h>
[1819]33#include <casa/Logging/LogIO.h>
[2]34
[80]35#include <tables/Tables/TableParse.h>
36#include <tables/Tables/TableDesc.h>
[488]37#include <tables/Tables/TableCopy.h>
[80]38#include <tables/Tables/SetupNewTab.h>
39#include <tables/Tables/ScaColDesc.h>
40#include <tables/Tables/ArrColDesc.h>
[805]41#include <tables/Tables/TableRow.h>
42#include <tables/Tables/TableVector.h>
43#include <tables/Tables/TableIter.h>
[2]44
[80]45#include <tables/Tables/ExprNode.h>
46#include <tables/Tables/TableRecord.h>
[1325]47#include <casa/Quanta/MVTime.h>
48#include <casa/Quanta/MVAngle.h>
49#include <measures/Measures/MeasRef.h>
50#include <measures/Measures/MeasTable.h>
51// needed to avoid error in .tcc
52#include <measures/Measures/MCDirection.h>
53//
54#include <measures/Measures/MDirection.h>
[80]55#include <measures/Measures/MFrequency.h>
[805]56#include <measures/Measures/MEpoch.h>
57#include <measures/TableMeasures/TableMeasRefDesc.h>
58#include <measures/TableMeasures/TableMeasValueDesc.h>
59#include <measures/TableMeasures/TableMeasDesc.h>
60#include <measures/TableMeasures/ScalarMeasColumn.h>
[105]61#include <coordinates/Coordinates/CoordinateUtil.h>
[2]62
[2005]63#include <atnf/PKSIO/SrcType.h>
[805]64#include "Scantable.h"
[896]65#include "STPolLinear.h"
[1189]66#include "STPolCircular.h"
[913]67#include "STPolStokes.h"
[878]68#include "STAttr.h"
[2012]69#include "STLineFinder.h"
[902]70#include "MathUtils.h"
[2]71
[125]72using namespace casa;
[2]73
[805]74namespace asap {
75
[896]76std::map<std::string, STPol::STPolFactory *> Scantable::factories_;
77
78void Scantable::initFactories() {
79 if ( factories_.empty() ) {
80 Scantable::factories_["linear"] = &STPolLinear::myFactory;
[1323]81 Scantable::factories_["circular"] = &STPolCircular::myFactory;
[913]82 Scantable::factories_["stokes"] = &STPolStokes::myFactory;
[896]83 }
84}
85
[805]86Scantable::Scantable(Table::TableType ttype) :
[852]87 type_(ttype)
[206]88{
[896]89 initFactories();
[805]90 setupMainTable();
[852]91 freqTable_ = STFrequencies(*this);
[805]92 table_.rwKeywordSet().defineTable("FREQUENCIES", freqTable_.table());
[852]93 weatherTable_ = STWeather(*this);
[805]94 table_.rwKeywordSet().defineTable("WEATHER", weatherTable_.table());
[852]95 focusTable_ = STFocus(*this);
[805]96 table_.rwKeywordSet().defineTable("FOCUS", focusTable_.table());
[852]97 tcalTable_ = STTcal(*this);
[805]98 table_.rwKeywordSet().defineTable("TCAL", tcalTable_.table());
[852]99 moleculeTable_ = STMolecules(*this);
[805]100 table_.rwKeywordSet().defineTable("MOLECULES", moleculeTable_.table());
[860]101 historyTable_ = STHistory(*this);
102 table_.rwKeywordSet().defineTable("HISTORY", historyTable_.table());
[959]103 fitTable_ = STFit(*this);
104 table_.rwKeywordSet().defineTable("FIT", fitTable_.table());
[1881]105 table_.tableInfo().setType( "Scantable" ) ;
[805]106 originalTable_ = table_;
[322]107 attach();
[18]108}
[206]109
[805]110Scantable::Scantable(const std::string& name, Table::TableType ttype) :
[852]111 type_(ttype)
[206]112{
[896]113 initFactories();
[1819]114
[865]115 Table tab(name, Table::Update);
[1009]116 uInt version = tab.keywordSet().asuInt("VERSION");
[483]117 if (version != version_) {
118 throw(AipsError("Unsupported version of ASAP file."));
119 }
[1009]120 if ( type_ == Table::Memory ) {
[852]121 table_ = tab.copyToMemoryTable(generateName());
[1009]122 } else {
[805]123 table_ = tab;
[1009]124 }
[1881]125 table_.tableInfo().setType( "Scantable" ) ;
[1009]126
[859]127 attachSubtables();
[805]128 originalTable_ = table_;
[329]129 attach();
[2]130}
[1819]131/*
132Scantable::Scantable(const std::string& name, Table::TableType ttype) :
133 type_(ttype)
134{
135 initFactories();
136 Table tab(name, Table::Update);
137 uInt version = tab.keywordSet().asuInt("VERSION");
138 if (version != version_) {
139 throw(AipsError("Unsupported version of ASAP file."));
140 }
141 if ( type_ == Table::Memory ) {
142 table_ = tab.copyToMemoryTable(generateName());
143 } else {
144 table_ = tab;
145 }
[2]146
[1819]147 attachSubtables();
148 originalTable_ = table_;
149 attach();
150}
151*/
152
[805]153Scantable::Scantable( const Scantable& other, bool clear )
[206]154{
[805]155 // with or without data
[859]156 String newname = String(generateName());
[865]157 type_ = other.table_.tableType();
[859]158 if ( other.table_.tableType() == Table::Memory ) {
159 if ( clear ) {
160 table_ = TableCopy::makeEmptyMemoryTable(newname,
161 other.table_, True);
162 } else
163 table_ = other.table_.copyToMemoryTable(newname);
[16]164 } else {
[915]165 other.table_.deepCopy(newname, Table::New, False,
166 other.table_.endianFormat(),
[865]167 Bool(clear));
168 table_ = Table(newname, Table::Update);
169 table_.markForDelete();
170 }
[1881]171 table_.tableInfo().setType( "Scantable" ) ;
[1111]172 /// @todo reindex SCANNO, recompute nbeam, nif, npol
[915]173 if ( clear ) copySubtables(other);
[859]174 attachSubtables();
[805]175 originalTable_ = table_;
[322]176 attach();
[2]177}
178
[865]179void Scantable::copySubtables(const Scantable& other) {
180 Table t = table_.rwKeywordSet().asTable("FREQUENCIES");
181 TableCopy::copyRows(t, other.freqTable_.table());
182 t = table_.rwKeywordSet().asTable("FOCUS");
183 TableCopy::copyRows(t, other.focusTable_.table());
184 t = table_.rwKeywordSet().asTable("WEATHER");
185 TableCopy::copyRows(t, other.weatherTable_.table());
186 t = table_.rwKeywordSet().asTable("TCAL");
187 TableCopy::copyRows(t, other.tcalTable_.table());
188 t = table_.rwKeywordSet().asTable("MOLECULES");
189 TableCopy::copyRows(t, other.moleculeTable_.table());
190 t = table_.rwKeywordSet().asTable("HISTORY");
191 TableCopy::copyRows(t, other.historyTable_.table());
[972]192 t = table_.rwKeywordSet().asTable("FIT");
193 TableCopy::copyRows(t, other.fitTable_.table());
[865]194}
195
[859]196void Scantable::attachSubtables()
197{
198 freqTable_ = STFrequencies(table_);
199 focusTable_ = STFocus(table_);
200 weatherTable_ = STWeather(table_);
201 tcalTable_ = STTcal(table_);
202 moleculeTable_ = STMolecules(table_);
[860]203 historyTable_ = STHistory(table_);
[972]204 fitTable_ = STFit(table_);
[859]205}
206
[805]207Scantable::~Scantable()
[206]208{
[941]209 //cout << "~Scantable() " << this << endl;
[2]210}
211
[805]212void Scantable::setupMainTable()
[206]213{
[805]214 TableDesc td("", "1", TableDesc::Scratch);
215 td.comment() = "An ASAP Scantable";
[1009]216 td.rwKeywordSet().define("VERSION", uInt(version_));
[2]217
[805]218 // n Cycles
219 td.addColumn(ScalarColumnDesc<uInt>("SCANNO"));
220 // new index every nBeam x nIF x nPol
221 td.addColumn(ScalarColumnDesc<uInt>("CYCLENO"));
[2]222
[805]223 td.addColumn(ScalarColumnDesc<uInt>("BEAMNO"));
224 td.addColumn(ScalarColumnDesc<uInt>("IFNO"));
[972]225 // linear, circular, stokes
[805]226 td.rwKeywordSet().define("POLTYPE", String("linear"));
227 td.addColumn(ScalarColumnDesc<uInt>("POLNO"));
[138]228
[805]229 td.addColumn(ScalarColumnDesc<uInt>("FREQ_ID"));
230 td.addColumn(ScalarColumnDesc<uInt>("MOLECULE_ID"));
[80]231
[1819]232 ScalarColumnDesc<Int> refbeamnoColumn("REFBEAMNO");
233 refbeamnoColumn.setDefault(Int(-1));
234 td.addColumn(refbeamnoColumn);
235
236 ScalarColumnDesc<uInt> flagrowColumn("FLAGROW");
237 flagrowColumn.setDefault(uInt(0));
238 td.addColumn(flagrowColumn);
239
[805]240 td.addColumn(ScalarColumnDesc<Double>("TIME"));
241 TableMeasRefDesc measRef(MEpoch::UTC); // UTC as default
242 TableMeasValueDesc measVal(td, "TIME");
243 TableMeasDesc<MEpoch> mepochCol(measVal, measRef);
244 mepochCol.write(td);
[483]245
[805]246 td.addColumn(ScalarColumnDesc<Double>("INTERVAL"));
247
[2]248 td.addColumn(ScalarColumnDesc<String>("SRCNAME"));
[805]249 // Type of source (on=0, off=1, other=-1)
[1503]250 ScalarColumnDesc<Int> stypeColumn("SRCTYPE");
251 stypeColumn.setDefault(Int(-1));
252 td.addColumn(stypeColumn);
[805]253 td.addColumn(ScalarColumnDesc<String>("FIELDNAME"));
254
255 //The actual Data Vectors
[2]256 td.addColumn(ArrayColumnDesc<Float>("SPECTRA"));
257 td.addColumn(ArrayColumnDesc<uChar>("FLAGTRA"));
[89]258 td.addColumn(ArrayColumnDesc<Float>("TSYS"));
[805]259
260 td.addColumn(ArrayColumnDesc<Double>("DIRECTION",
261 IPosition(1,2),
262 ColumnDesc::Direct));
263 TableMeasRefDesc mdirRef(MDirection::J2000); // default
264 TableMeasValueDesc tmvdMDir(td, "DIRECTION");
265 // the TableMeasDesc gives the column a type
266 TableMeasDesc<MDirection> mdirCol(tmvdMDir, mdirRef);
[987]267 // a uder set table type e.g. GALCTIC, B1950 ...
268 td.rwKeywordSet().define("DIRECTIONREF", String("J2000"));
[805]269 // writing create the measure column
270 mdirCol.write(td);
[923]271 td.addColumn(ScalarColumnDesc<Float>("AZIMUTH"));
272 td.addColumn(ScalarColumnDesc<Float>("ELEVATION"));
[1047]273 td.addColumn(ScalarColumnDesc<Float>("OPACITY"));
[105]274
[805]275 td.addColumn(ScalarColumnDesc<uInt>("TCAL_ID"));
[972]276 ScalarColumnDesc<Int> fitColumn("FIT_ID");
[973]277 fitColumn.setDefault(Int(-1));
[972]278 td.addColumn(fitColumn);
[805]279
280 td.addColumn(ScalarColumnDesc<uInt>("FOCUS_ID"));
281 td.addColumn(ScalarColumnDesc<uInt>("WEATHER_ID"));
282
[999]283 // columns which just get dragged along, as they aren't used in asap
284 td.addColumn(ScalarColumnDesc<Double>("SRCVELOCITY"));
285 td.addColumn(ArrayColumnDesc<Double>("SRCPROPERMOTION"));
286 td.addColumn(ArrayColumnDesc<Double>("SRCDIRECTION"));
287 td.addColumn(ArrayColumnDesc<Double>("SCANRATE"));
288
[805]289 td.rwKeywordSet().define("OBSMODE", String(""));
290
[418]291 // Now create Table SetUp from the description.
[859]292 SetupNewTable aNewTab(generateName(), td, Table::Scratch);
[852]293 table_ = Table(aNewTab, type_, 0);
[805]294 originalTable_ = table_;
295}
[418]296
[805]297void Scantable::attach()
[455]298{
[805]299 timeCol_.attach(table_, "TIME");
300 srcnCol_.attach(table_, "SRCNAME");
[1068]301 srctCol_.attach(table_, "SRCTYPE");
[805]302 specCol_.attach(table_, "SPECTRA");
303 flagsCol_.attach(table_, "FLAGTRA");
[865]304 tsysCol_.attach(table_, "TSYS");
[805]305 cycleCol_.attach(table_,"CYCLENO");
306 scanCol_.attach(table_, "SCANNO");
307 beamCol_.attach(table_, "BEAMNO");
[847]308 ifCol_.attach(table_, "IFNO");
309 polCol_.attach(table_, "POLNO");
[805]310 integrCol_.attach(table_, "INTERVAL");
311 azCol_.attach(table_, "AZIMUTH");
312 elCol_.attach(table_, "ELEVATION");
313 dirCol_.attach(table_, "DIRECTION");
314 fldnCol_.attach(table_, "FIELDNAME");
315 rbeamCol_.attach(table_, "REFBEAMNO");
[455]316
[1730]317 mweatheridCol_.attach(table_,"WEATHER_ID");
[805]318 mfitidCol_.attach(table_,"FIT_ID");
319 mfreqidCol_.attach(table_, "FREQ_ID");
320 mtcalidCol_.attach(table_, "TCAL_ID");
321 mfocusidCol_.attach(table_, "FOCUS_ID");
322 mmolidCol_.attach(table_, "MOLECULE_ID");
[1819]323
324 //Add auxiliary column for row-based flagging (CAS-1433 Wataru Kawasaki)
325 attachAuxColumnDef(flagrowCol_, "FLAGROW", 0);
326
[455]327}
328
[1819]329template<class T, class T2>
330void Scantable::attachAuxColumnDef(ScalarColumn<T>& col,
331 const String& colName,
332 const T2& defValue)
333{
334 try {
335 col.attach(table_, colName);
336 } catch (TableError& err) {
337 String errMesg = err.getMesg();
338 if (errMesg == "Table column " + colName + " is unknown") {
339 table_.addColumn(ScalarColumnDesc<T>(colName));
340 col.attach(table_, colName);
341 col.fillColumn(static_cast<T>(defValue));
342 } else {
343 throw;
344 }
345 } catch (...) {
346 throw;
347 }
348}
349
350template<class T, class T2>
351void Scantable::attachAuxColumnDef(ArrayColumn<T>& col,
352 const String& colName,
353 const Array<T2>& defValue)
354{
355 try {
356 col.attach(table_, colName);
357 } catch (TableError& err) {
358 String errMesg = err.getMesg();
359 if (errMesg == "Table column " + colName + " is unknown") {
360 table_.addColumn(ArrayColumnDesc<T>(colName));
361 col.attach(table_, colName);
362
363 int size = 0;
364 ArrayIterator<T2>& it = defValue.begin();
365 while (it != defValue.end()) {
366 ++size;
367 ++it;
368 }
369 IPosition ip(1, size);
370 Array<T>& arr(ip);
371 for (int i = 0; i < size; ++i)
372 arr[i] = static_cast<T>(defValue[i]);
373
374 col.fillColumn(arr);
375 } else {
376 throw;
377 }
378 } catch (...) {
379 throw;
380 }
381}
382
[901]383void Scantable::setHeader(const STHeader& sdh)
[206]384{
[18]385 table_.rwKeywordSet().define("nIF", sdh.nif);
386 table_.rwKeywordSet().define("nBeam", sdh.nbeam);
387 table_.rwKeywordSet().define("nPol", sdh.npol);
388 table_.rwKeywordSet().define("nChan", sdh.nchan);
389 table_.rwKeywordSet().define("Observer", sdh.observer);
390 table_.rwKeywordSet().define("Project", sdh.project);
391 table_.rwKeywordSet().define("Obstype", sdh.obstype);
392 table_.rwKeywordSet().define("AntennaName", sdh.antennaname);
393 table_.rwKeywordSet().define("AntennaPosition", sdh.antennaposition);
394 table_.rwKeywordSet().define("Equinox", sdh.equinox);
395 table_.rwKeywordSet().define("FreqRefFrame", sdh.freqref);
396 table_.rwKeywordSet().define("FreqRefVal", sdh.reffreq);
397 table_.rwKeywordSet().define("Bandwidth", sdh.bandwidth);
398 table_.rwKeywordSet().define("UTC", sdh.utc);
[206]399 table_.rwKeywordSet().define("FluxUnit", sdh.fluxunit);
400 table_.rwKeywordSet().define("Epoch", sdh.epoch);
[905]401 table_.rwKeywordSet().define("POLTYPE", sdh.poltype);
[50]402}
[21]403
[901]404STHeader Scantable::getHeader() const
[206]405{
[901]406 STHeader sdh;
[21]407 table_.keywordSet().get("nBeam",sdh.nbeam);
408 table_.keywordSet().get("nIF",sdh.nif);
409 table_.keywordSet().get("nPol",sdh.npol);
410 table_.keywordSet().get("nChan",sdh.nchan);
411 table_.keywordSet().get("Observer", sdh.observer);
412 table_.keywordSet().get("Project", sdh.project);
413 table_.keywordSet().get("Obstype", sdh.obstype);
414 table_.keywordSet().get("AntennaName", sdh.antennaname);
415 table_.keywordSet().get("AntennaPosition", sdh.antennaposition);
416 table_.keywordSet().get("Equinox", sdh.equinox);
417 table_.keywordSet().get("FreqRefFrame", sdh.freqref);
418 table_.keywordSet().get("FreqRefVal", sdh.reffreq);
419 table_.keywordSet().get("Bandwidth", sdh.bandwidth);
420 table_.keywordSet().get("UTC", sdh.utc);
[206]421 table_.keywordSet().get("FluxUnit", sdh.fluxunit);
422 table_.keywordSet().get("Epoch", sdh.epoch);
[905]423 table_.keywordSet().get("POLTYPE", sdh.poltype);
[21]424 return sdh;
[18]425}
[805]426
[1360]427void Scantable::setSourceType( int stype )
[1068]428{
429 if ( stype < 0 || stype > 1 )
430 throw(AipsError("Illegal sourcetype."));
431 TableVector<Int> tabvec(table_, "SRCTYPE");
432 tabvec = Int(stype);
433}
434
[845]435bool Scantable::conformant( const Scantable& other )
436{
437 return this->getHeader().conformant(other.getHeader());
438}
439
440
[50]441
[805]442std::string Scantable::formatSec(Double x) const
[206]443{
[105]444 Double xcop = x;
445 MVTime mvt(xcop/24./3600.); // make days
[365]446
[105]447 if (x < 59.95)
[281]448 return String(" ") + mvt.string(MVTime::TIME_CLEAN_NO_HM, 7)+"s";
[745]449 else if (x < 3599.95)
[281]450 return String(" ") + mvt.string(MVTime::TIME_CLEAN_NO_H,7)+" ";
451 else {
452 ostringstream oss;
453 oss << setw(2) << std::right << setprecision(1) << mvt.hour();
454 oss << ":" << mvt.string(MVTime::TIME_CLEAN_NO_H,7) << " ";
455 return String(oss);
[745]456 }
[105]457};
458
[805]459std::string Scantable::formatDirection(const MDirection& md) const
[281]460{
461 Vector<Double> t = md.getAngle(Unit(String("rad"))).getValue();
462 Int prec = 7;
463
464 MVAngle mvLon(t[0]);
465 String sLon = mvLon.string(MVAngle::TIME,prec);
[987]466 uInt tp = md.getRef().getType();
467 if (tp == MDirection::GALACTIC ||
468 tp == MDirection::SUPERGAL ) {
469 sLon = mvLon(0.0).string(MVAngle::ANGLE_CLEAN,prec);
470 }
[281]471 MVAngle mvLat(t[1]);
472 String sLat = mvLat.string(MVAngle::ANGLE+MVAngle::DIG2,prec);
[380]473 return sLon + String(" ") + sLat;
[281]474}
475
476
[805]477std::string Scantable::getFluxUnit() const
[206]478{
[847]479 return table_.keywordSet().asString("FluxUnit");
[206]480}
481
[805]482void Scantable::setFluxUnit(const std::string& unit)
[218]483{
484 String tmp(unit);
485 Unit tU(tmp);
486 if (tU==Unit("K") || tU==Unit("Jy")) {
487 table_.rwKeywordSet().define(String("FluxUnit"), tmp);
488 } else {
489 throw AipsError("Illegal unit - must be compatible with Jy or K");
490 }
491}
492
[805]493void Scantable::setInstrument(const std::string& name)
[236]494{
[805]495 bool throwIt = true;
[996]496 // create an Instrument to see if this is valid
497 STAttr::convertInstrument(name, throwIt);
[236]498 String nameU(name);
499 nameU.upcase();
500 table_.rwKeywordSet().define(String("AntennaName"), nameU);
501}
502
[1189]503void Scantable::setFeedType(const std::string& feedtype)
504{
505 if ( Scantable::factories_.find(feedtype) == Scantable::factories_.end() ) {
506 std::string msg = "Illegal feed type "+ feedtype;
507 throw(casa::AipsError(msg));
508 }
509 table_.rwKeywordSet().define(String("POLTYPE"), feedtype);
510}
511
[1743]512MPosition Scantable::getAntennaPosition() const
[805]513{
514 Vector<Double> antpos;
515 table_.keywordSet().get("AntennaPosition", antpos);
516 MVPosition mvpos(antpos(0),antpos(1),antpos(2));
517 return MPosition(mvpos);
518}
[281]519
[805]520void Scantable::makePersistent(const std::string& filename)
521{
522 String inname(filename);
523 Path path(inname);
[1111]524 /// @todo reindex SCANNO, recompute nbeam, nif, npol
[805]525 inname = path.expandedName();
[2030]526 // 2011/03/04 TN
527 // We can comment out this workaround since the essential bug is
528 // fixed in casacore (r20889 in google code).
529 table_.deepCopy(inname, Table::New);
530// // WORKAROUND !!! for Table bug
531// // Remove when fixed in casacore
532// if ( table_.tableType() == Table::Memory && !selector_.empty() ) {
533// Table tab = table_.copyToMemoryTable(generateName());
534// tab.deepCopy(inname, Table::New);
535// tab.markForDelete();
536//
537// } else {
538// table_.deepCopy(inname, Table::New);
539// }
[805]540}
541
[837]542int Scantable::nbeam( int scanno ) const
[805]543{
544 if ( scanno < 0 ) {
545 Int n;
546 table_.keywordSet().get("nBeam",n);
547 return int(n);
[105]548 } else {
[805]549 // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
[888]550 Table t = table_(table_.col("SCANNO") == scanno);
551 ROTableRow row(t);
552 const TableRecord& rec = row.get(0);
553 Table subt = t( t.col("IFNO") == Int(rec.asuInt("IFNO"))
554 && t.col("POLNO") == Int(rec.asuInt("POLNO"))
555 && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
556 ROTableVector<uInt> v(subt, "BEAMNO");
[805]557 return int(v.nelements());
[105]558 }
[805]559 return 0;
560}
[455]561
[837]562int Scantable::nif( int scanno ) const
[805]563{
564 if ( scanno < 0 ) {
565 Int n;
566 table_.keywordSet().get("nIF",n);
567 return int(n);
568 } else {
569 // take the first POLNO,BEAMNO,CYCLENO as nbeam shouldn't vary with these
[888]570 Table t = table_(table_.col("SCANNO") == scanno);
571 ROTableRow row(t);
572 const TableRecord& rec = row.get(0);
573 Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
574 && t.col("POLNO") == Int(rec.asuInt("POLNO"))
575 && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
576 if ( subt.nrow() == 0 ) return 0;
577 ROTableVector<uInt> v(subt, "IFNO");
[805]578 return int(v.nelements());
[2]579 }
[805]580 return 0;
581}
[321]582
[837]583int Scantable::npol( int scanno ) const
[805]584{
585 if ( scanno < 0 ) {
586 Int n;
587 table_.keywordSet().get("nPol",n);
588 return n;
589 } else {
590 // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
[888]591 Table t = table_(table_.col("SCANNO") == scanno);
592 ROTableRow row(t);
593 const TableRecord& rec = row.get(0);
594 Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
595 && t.col("IFNO") == Int(rec.asuInt("IFNO"))
596 && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
597 if ( subt.nrow() == 0 ) return 0;
598 ROTableVector<uInt> v(subt, "POLNO");
[805]599 return int(v.nelements());
[321]600 }
[805]601 return 0;
[2]602}
[805]603
[845]604int Scantable::ncycle( int scanno ) const
[206]605{
[805]606 if ( scanno < 0 ) {
[837]607 Block<String> cols(2);
608 cols[0] = "SCANNO";
609 cols[1] = "CYCLENO";
610 TableIterator it(table_, cols);
611 int n = 0;
612 while ( !it.pastEnd() ) {
613 ++n;
[902]614 ++it;
[837]615 }
616 return n;
[805]617 } else {
[888]618 Table t = table_(table_.col("SCANNO") == scanno);
619 ROTableRow row(t);
620 const TableRecord& rec = row.get(0);
621 Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
622 && t.col("POLNO") == Int(rec.asuInt("POLNO"))
623 && t.col("IFNO") == Int(rec.asuInt("IFNO")) );
624 if ( subt.nrow() == 0 ) return 0;
625 return int(subt.nrow());
[805]626 }
627 return 0;
[18]628}
[455]629
630
[845]631int Scantable::nrow( int scanno ) const
[805]632{
[845]633 return int(table_.nrow());
634}
635
636int Scantable::nchan( int ifno ) const
637{
638 if ( ifno < 0 ) {
[805]639 Int n;
640 table_.keywordSet().get("nChan",n);
641 return int(n);
642 } else {
[1360]643 // take the first SCANNO,POLNO,BEAMNO,CYCLENO as nbeam shouldn't
644 // vary with these
[888]645 Table t = table_(table_.col("IFNO") == ifno);
646 if ( t.nrow() == 0 ) return 0;
647 ROArrayColumn<Float> v(t, "SPECTRA");
[923]648 return v.shape(0)(0);
[805]649 }
650 return 0;
[18]651}
[455]652
[1111]653int Scantable::nscan() const {
654 Vector<uInt> scannos(scanCol_.getColumn());
[1148]655 uInt nout = genSort( scannos, Sort::Ascending,
[1111]656 Sort::QuickSort|Sort::NoDuplicates );
657 return int(nout);
658}
659
[923]660int Scantable::getChannels(int whichrow) const
661{
662 return specCol_.shape(whichrow)(0);
663}
[847]664
665int Scantable::getBeam(int whichrow) const
666{
667 return beamCol_(whichrow);
668}
669
[1694]670std::vector<uint> Scantable::getNumbers(const ScalarColumn<uInt>& col) const
[1111]671{
672 Vector<uInt> nos(col.getColumn());
[1148]673 uInt n = genSort( nos, Sort::Ascending, Sort::QuickSort|Sort::NoDuplicates );
674 nos.resize(n, True);
[1111]675 std::vector<uint> stlout;
676 nos.tovector(stlout);
677 return stlout;
678}
679
[847]680int Scantable::getIF(int whichrow) const
681{
682 return ifCol_(whichrow);
683}
684
685int Scantable::getPol(int whichrow) const
686{
687 return polCol_(whichrow);
688}
689
[805]690std::string Scantable::formatTime(const MEpoch& me, bool showdate) const
691{
[1947]692 return formatTime(me, showdate, 0);
693}
694
695std::string Scantable::formatTime(const MEpoch& me, bool showdate, uInt prec) const
696{
[805]697 MVTime mvt(me.getValue());
698 if (showdate)
[1947]699 //mvt.setFormat(MVTime::YMD);
700 mvt.setFormat(MVTime::YMD, prec);
[805]701 else
[1947]702 //mvt.setFormat(MVTime::TIME);
703 mvt.setFormat(MVTime::TIME, prec);
[805]704 ostringstream oss;
705 oss << mvt;
706 return String(oss);
707}
[488]708
[805]709void Scantable::calculateAZEL()
710{
711 MPosition mp = getAntennaPosition();
712 MEpoch::ROScalarColumn timeCol(table_, "TIME");
713 ostringstream oss;
714 oss << "Computed azimuth/elevation using " << endl
715 << mp << endl;
[996]716 for (Int i=0; i<nrow(); ++i) {
[805]717 MEpoch me = timeCol(i);
[987]718 MDirection md = getDirection(i);
[805]719 oss << " Time: " << formatTime(me,False) << " Direction: " << formatDirection(md)
720 << endl << " => ";
721 MeasFrame frame(mp, me);
722 Vector<Double> azel =
723 MDirection::Convert(md, MDirection::Ref(MDirection::AZEL,
724 frame)
725 )().getAngle("rad").getValue();
[923]726 azCol_.put(i,Float(azel[0]));
727 elCol_.put(i,Float(azel[1]));
[805]728 oss << "azel: " << azel[0]/C::pi*180.0 << " "
729 << azel[1]/C::pi*180.0 << " (deg)" << endl;
[16]730 }
[805]731 pushLog(String(oss));
732}
[89]733
[1819]734void Scantable::clip(const Float uthres, const Float dthres, bool clipoutside, bool unflag)
735{
736 for (uInt i=0; i<table_.nrow(); ++i) {
737 Vector<uChar> flgs = flagsCol_(i);
738 srchChannelsToClip(i, uthres, dthres, clipoutside, unflag, flgs);
739 flagsCol_.put(i, flgs);
740 }
741}
742
743std::vector<bool> Scantable::getClipMask(int whichrow, const Float uthres, const Float dthres, bool clipoutside, bool unflag)
744{
745 Vector<uChar> flags;
746 flagsCol_.get(uInt(whichrow), flags);
747 srchChannelsToClip(uInt(whichrow), uthres, dthres, clipoutside, unflag, flags);
748 Vector<Bool> bflag(flags.shape());
749 convertArray(bflag, flags);
750 //bflag = !bflag;
751
752 std::vector<bool> mask;
753 bflag.tovector(mask);
754 return mask;
755}
756
757void Scantable::srchChannelsToClip(uInt whichrow, const Float uthres, const Float dthres, bool clipoutside, bool unflag,
758 Vector<uChar> flgs)
759{
760 Vector<Float> spcs = specCol_(whichrow);
761 uInt nchannel = nchan();
762 if (spcs.nelements() != nchannel) {
763 throw(AipsError("Data has incorrect number of channels"));
764 }
765 uChar userflag = 1 << 7;
766 if (unflag) {
767 userflag = 0 << 7;
768 }
769 if (clipoutside) {
770 for (uInt j = 0; j < nchannel; ++j) {
771 Float spc = spcs(j);
772 if ((spc >= uthres) || (spc <= dthres)) {
773 flgs(j) = userflag;
774 }
775 }
776 } else {
777 for (uInt j = 0; j < nchannel; ++j) {
778 Float spc = spcs(j);
779 if ((spc < uthres) && (spc > dthres)) {
780 flgs(j) = userflag;
781 }
782 }
783 }
784}
785
[1994]786
787void Scantable::flag( int whichrow, const std::vector<bool>& msk, bool unflag ) {
[1333]788 std::vector<bool>::const_iterator it;
789 uInt ntrue = 0;
[1994]790 if (whichrow >= int(table_.nrow()) ) {
791 throw(AipsError("Invalid row number"));
792 }
[1333]793 for (it = msk.begin(); it != msk.end(); ++it) {
794 if ( *it ) {
795 ntrue++;
796 }
797 }
[1994]798 //if ( selector_.empty() && (msk.size() == 0 || msk.size() == ntrue) )
799 if ( whichrow == -1 && !unflag && selector_.empty() && (msk.size() == 0 || msk.size() == ntrue) )
[1000]800 throw(AipsError("Trying to flag whole scantable."));
[1994]801 uChar userflag = 1 << 7;
802 if ( unflag ) {
803 userflag = 0 << 7;
804 }
805 if (whichrow > -1 ) {
806 applyChanFlag(uInt(whichrow), msk, userflag);
807 } else {
[1000]808 for ( uInt i=0; i<table_.nrow(); ++i) {
[1994]809 applyChanFlag(i, msk, userflag);
[1000]810 }
[1994]811 }
812}
813
814void Scantable::applyChanFlag( uInt whichrow, const std::vector<bool>& msk, uChar flagval )
815{
816 if (whichrow >= table_.nrow() ) {
817 throw( casa::indexError<int>( whichrow, "asap::Scantable::applyChanFlag: Invalid row number" ) );
818 }
819 Vector<uChar> flgs = flagsCol_(whichrow);
820 if ( msk.size() == 0 ) {
821 flgs = flagval;
822 flagsCol_.put(whichrow, flgs);
[1000]823 return;
824 }
825 if ( int(msk.size()) != nchan() ) {
826 throw(AipsError("Mask has incorrect number of channels."));
827 }
[1994]828 if ( flgs.nelements() != msk.size() ) {
829 throw(AipsError("Mask has incorrect number of channels."
830 " Probably varying with IF. Please flag per IF"));
831 }
832 std::vector<bool>::const_iterator it;
833 uInt j = 0;
834 for (it = msk.begin(); it != msk.end(); ++it) {
835 if ( *it ) {
836 flgs(j) = flagval;
[1000]837 }
[1994]838 ++j;
[1000]839 }
[1994]840 flagsCol_.put(whichrow, flgs);
[865]841}
842
[1819]843void Scantable::flagRow(const std::vector<uInt>& rows, bool unflag)
844{
845 if ( selector_.empty() && (rows.size() == table_.nrow()) )
846 throw(AipsError("Trying to flag whole scantable."));
847
848 uInt rowflag = (unflag ? 0 : 1);
849 std::vector<uInt>::const_iterator it;
850 for (it = rows.begin(); it != rows.end(); ++it)
851 flagrowCol_.put(*it, rowflag);
852}
853
[805]854std::vector<bool> Scantable::getMask(int whichrow) const
855{
856 Vector<uChar> flags;
857 flagsCol_.get(uInt(whichrow), flags);
858 Vector<Bool> bflag(flags.shape());
859 convertArray(bflag, flags);
860 bflag = !bflag;
861 std::vector<bool> mask;
862 bflag.tovector(mask);
863 return mask;
864}
[89]865
[896]866std::vector<float> Scantable::getSpectrum( int whichrow,
[902]867 const std::string& poltype ) const
[805]868{
[905]869 String ptype = poltype;
870 if (poltype == "" ) ptype = getPolType();
[902]871 if ( whichrow < 0 || whichrow >= nrow() )
872 throw(AipsError("Illegal row number."));
[896]873 std::vector<float> out;
[805]874 Vector<Float> arr;
[896]875 uInt requestedpol = polCol_(whichrow);
876 String basetype = getPolType();
[905]877 if ( ptype == basetype ) {
[896]878 specCol_.get(whichrow, arr);
879 } else {
[1598]880 CountedPtr<STPol> stpol(STPol::getPolClass(Scantable::factories_,
[1586]881 basetype));
[1334]882 uInt row = uInt(whichrow);
883 stpol->setSpectra(getPolMatrix(row));
[2047]884 Float fang,fhand;
[1586]885 fang = focusTable_.getTotalAngle(mfocusidCol_(row));
[1334]886 fhand = focusTable_.getFeedHand(mfocusidCol_(row));
[1586]887 stpol->setPhaseCorrections(fang, fhand);
[1334]888 arr = stpol->getSpectrum(requestedpol, ptype);
[896]889 }
[902]890 if ( arr.nelements() == 0 )
891 pushLog("Not enough polarisations present to do the conversion.");
[805]892 arr.tovector(out);
893 return out;
[89]894}
[212]895
[1360]896void Scantable::setSpectrum( const std::vector<float>& spec,
[884]897 int whichrow )
898{
899 Vector<Float> spectrum(spec);
900 Vector<Float> arr;
901 specCol_.get(whichrow, arr);
902 if ( spectrum.nelements() != arr.nelements() )
[896]903 throw AipsError("The spectrum has incorrect number of channels.");
[884]904 specCol_.put(whichrow, spectrum);
905}
906
907
[805]908String Scantable::generateName()
[745]909{
[805]910 return (File::newUniqueName("./","temp")).baseName();
[212]911}
912
[805]913const casa::Table& Scantable::table( ) const
[212]914{
[805]915 return table_;
[212]916}
917
[805]918casa::Table& Scantable::table( )
[386]919{
[805]920 return table_;
[386]921}
922
[896]923std::string Scantable::getPolType() const
924{
925 return table_.keywordSet().asString("POLTYPE");
926}
927
[805]928void Scantable::unsetSelection()
[380]929{
[805]930 table_ = originalTable_;
[847]931 attach();
[805]932 selector_.reset();
[380]933}
[386]934
[805]935void Scantable::setSelection( const STSelector& selection )
[430]936{
[805]937 Table tab = const_cast<STSelector&>(selection).apply(originalTable_);
938 if ( tab.nrow() == 0 ) {
939 throw(AipsError("Selection contains no data. Not applying it."));
940 }
941 table_ = tab;
[847]942 attach();
[2084]943// tab.rwKeywordSet().define("nBeam",(Int)(getBeamNos().size())) ;
944// vector<uint> selectedIFs = getIFNos() ;
945// Int newnIF = selectedIFs.size() ;
946// tab.rwKeywordSet().define("nIF",newnIF) ;
947// if ( newnIF != 0 ) {
948// Int newnChan = 0 ;
949// for ( Int i = 0 ; i < newnIF ; i++ ) {
950// Int nChan = nchan( selectedIFs[i] ) ;
951// if ( newnChan > nChan )
952// newnChan = nChan ;
953// }
954// tab.rwKeywordSet().define("nChan",newnChan) ;
955// }
956// tab.rwKeywordSet().define("nPol",(Int)(getPolNos().size())) ;
[805]957 selector_ = selection;
[430]958}
959
[837]960std::string Scantable::summary( bool verbose )
[447]961{
[805]962 // Format header info
963 ostringstream oss;
964 oss << endl;
965 oss << asap::SEPERATOR << endl;
966 oss << " Scan Table Summary" << endl;
967 oss << asap::SEPERATOR << endl;
968 oss.flags(std::ios_base::left);
969 oss << setw(15) << "Beams:" << setw(4) << nbeam() << endl
970 << setw(15) << "IFs:" << setw(4) << nif() << endl
[896]971 << setw(15) << "Polarisations:" << setw(4) << npol()
972 << "(" << getPolType() << ")" << endl
[1694]973 << setw(15) << "Channels:" << nchan() << endl;
[805]974 String tmp;
[860]975 oss << setw(15) << "Observer:"
976 << table_.keywordSet().asString("Observer") << endl;
[805]977 oss << setw(15) << "Obs Date:" << getTime(-1,true) << endl;
978 table_.keywordSet().get("Project", tmp);
979 oss << setw(15) << "Project:" << tmp << endl;
980 table_.keywordSet().get("Obstype", tmp);
981 oss << setw(15) << "Obs. Type:" << tmp << endl;
982 table_.keywordSet().get("AntennaName", tmp);
983 oss << setw(15) << "Antenna Name:" << tmp << endl;
984 table_.keywordSet().get("FluxUnit", tmp);
985 oss << setw(15) << "Flux Unit:" << tmp << endl;
[1819]986 //Vector<Double> vec(moleculeTable_.getRestFrequencies());
987 int nid = moleculeTable_.nrow();
988 Bool firstline = True;
[805]989 oss << setw(15) << "Rest Freqs:";
[1819]990 for (int i=0; i<nid; i++) {
991 Table t = table_(table_.col("MOLECULE_ID") == i);
992 if (t.nrow() > 0) {
993 Vector<Double> vec(moleculeTable_.getRestFrequency(i));
994 if (vec.nelements() > 0) {
995 if (firstline) {
996 oss << setprecision(10) << vec << " [Hz]" << endl;
997 firstline=False;
998 }
999 else{
1000 oss << setw(15)<<" " << setprecision(10) << vec << " [Hz]" << endl;
1001 }
1002 } else {
1003 oss << "none" << endl;
1004 }
1005 }
[805]1006 }
[941]1007
1008 oss << setw(15) << "Abcissa:" << getAbcissaLabel(0) << endl;
[805]1009 oss << selector_.print() << endl;
1010 oss << endl;
1011 // main table
1012 String dirtype = "Position ("
[987]1013 + getDirectionRefString()
[805]1014 + ")";
[941]1015 oss << setw(5) << "Scan" << setw(15) << "Source"
[2005]1016 << setw(10) << "Time" << setw(18) << "Integration"
1017 << setw(15) << "Source Type" << endl;
[941]1018 oss << setw(5) << "" << setw(5) << "Beam" << setw(3) << "" << dirtype << endl;
[1694]1019 oss << setw(10) << "" << setw(3) << "IF" << setw(3) << ""
[805]1020 << setw(8) << "Frame" << setw(16)
[1694]1021 << "RefVal" << setw(10) << "RefPix" << setw(12) << "Increment"
1022 << setw(7) << "Channels"
1023 << endl;
[805]1024 oss << asap::SEPERATOR << endl;
1025 TableIterator iter(table_, "SCANNO");
1026 while (!iter.pastEnd()) {
1027 Table subt = iter.table();
1028 ROTableRow row(subt);
1029 MEpoch::ROScalarColumn timeCol(subt,"TIME");
1030 const TableRecord& rec = row.get(0);
1031 oss << setw(4) << std::right << rec.asuInt("SCANNO")
1032 << std::left << setw(1) << ""
1033 << setw(15) << rec.asString("SRCNAME")
1034 << setw(10) << formatTime(timeCol(0), false);
1035 // count the cycles in the scan
1036 TableIterator cyciter(subt, "CYCLENO");
1037 int nint = 0;
1038 while (!cyciter.pastEnd()) {
1039 ++nint;
1040 ++cyciter;
1041 }
1042 oss << setw(3) << std::right << nint << setw(3) << " x " << std::left
[2005]1043 << setw(11) << formatSec(rec.asFloat("INTERVAL")) << setw(1) << ""
1044 << setw(15) << SrcType::getName(rec.asInt("SRCTYPE")) << endl;
[447]1045
[805]1046 TableIterator biter(subt, "BEAMNO");
1047 while (!biter.pastEnd()) {
1048 Table bsubt = biter.table();
1049 ROTableRow brow(bsubt);
1050 const TableRecord& brec = brow.get(0);
[1000]1051 uInt row0 = bsubt.rowNumbers(table_)[0];
[941]1052 oss << setw(5) << "" << setw(4) << std::right << brec.asuInt("BEAMNO")<< std::left;
[987]1053 oss << setw(4) << "" << formatDirection(getDirection(row0)) << endl;
[805]1054 TableIterator iiter(bsubt, "IFNO");
1055 while (!iiter.pastEnd()) {
1056 Table isubt = iiter.table();
1057 ROTableRow irow(isubt);
1058 const TableRecord& irec = irow.get(0);
[1694]1059 oss << setw(9) << "";
[941]1060 oss << setw(3) << std::right << irec.asuInt("IFNO") << std::left
[1694]1061 << setw(1) << "" << frequencies().print(irec.asuInt("FREQ_ID"))
1062 << setw(3) << "" << nchan(irec.asuInt("IFNO"))
[1375]1063 << endl;
[447]1064
[805]1065 ++iiter;
1066 }
1067 ++biter;
1068 }
1069 ++iter;
[447]1070 }
[805]1071 /// @todo implement verbose mode
1072 return String(oss);
[447]1073}
1074
[1947]1075// std::string Scantable::getTime(int whichrow, bool showdate) const
1076// {
1077// MEpoch::ROScalarColumn timeCol(table_, "TIME");
1078// MEpoch me;
1079// if (whichrow > -1) {
1080// me = timeCol(uInt(whichrow));
1081// } else {
1082// Double tm;
1083// table_.keywordSet().get("UTC",tm);
1084// me = MEpoch(MVEpoch(tm));
1085// }
1086// return formatTime(me, showdate);
1087// }
1088
1089std::string Scantable::getTime(int whichrow, bool showdate, uInt prec) const
[777]1090{
[805]1091 MEpoch me;
[1947]1092 me = getEpoch(whichrow);
1093 return formatTime(me, showdate, prec);
[777]1094}
[805]1095
[1411]1096MEpoch Scantable::getEpoch(int whichrow) const
1097{
1098 if (whichrow > -1) {
1099 return timeCol_(uInt(whichrow));
1100 } else {
1101 Double tm;
1102 table_.keywordSet().get("UTC",tm);
[1598]1103 return MEpoch(MVEpoch(tm));
[1411]1104 }
1105}
1106
[1068]1107std::string Scantable::getDirectionString(int whichrow) const
1108{
1109 return formatDirection(getDirection(uInt(whichrow)));
1110}
1111
[1598]1112
1113SpectralCoordinate Scantable::getSpectralCoordinate(int whichrow) const {
1114 const MPosition& mp = getAntennaPosition();
1115 const MDirection& md = getDirection(whichrow);
1116 const MEpoch& me = timeCol_(whichrow);
[1819]1117 //Double rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
1118 Vector<Double> rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
[1598]1119 return freqTable_.getSpectralCoordinate(md, mp, me, rf,
1120 mfreqidCol_(whichrow));
1121}
1122
[1360]1123std::vector< double > Scantable::getAbcissa( int whichrow ) const
[865]1124{
[1507]1125 if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal row number"));
[865]1126 std::vector<double> stlout;
1127 int nchan = specCol_(whichrow).nelements();
1128 String us = freqTable_.getUnitString();
1129 if ( us == "" || us == "pixel" || us == "channel" ) {
1130 for (int i=0; i<nchan; ++i) {
1131 stlout.push_back(double(i));
1132 }
1133 return stlout;
1134 }
[1598]1135 SpectralCoordinate spc = getSpectralCoordinate(whichrow);
[865]1136 Vector<Double> pixel(nchan);
1137 Vector<Double> world;
1138 indgen(pixel);
1139 if ( Unit(us) == Unit("Hz") ) {
1140 for ( int i=0; i < nchan; ++i) {
1141 Double world;
1142 spc.toWorld(world, pixel[i]);
1143 stlout.push_back(double(world));
1144 }
1145 } else if ( Unit(us) == Unit("km/s") ) {
1146 Vector<Double> world;
1147 spc.pixelToVelocity(world, pixel);
1148 world.tovector(stlout);
1149 }
1150 return stlout;
1151}
[1360]1152void Scantable::setDirectionRefString( const std::string & refstr )
[987]1153{
1154 MDirection::Types mdt;
1155 if (refstr != "" && !MDirection::getType(mdt, refstr)) {
1156 throw(AipsError("Illegal Direction frame."));
1157 }
1158 if ( refstr == "" ) {
1159 String defaultstr = MDirection::showType(dirCol_.getMeasRef().getType());
1160 table_.rwKeywordSet().define("DIRECTIONREF", defaultstr);
1161 } else {
1162 table_.rwKeywordSet().define("DIRECTIONREF", String(refstr));
1163 }
1164}
[865]1165
[1360]1166std::string Scantable::getDirectionRefString( ) const
[987]1167{
1168 return table_.keywordSet().asString("DIRECTIONREF");
1169}
1170
1171MDirection Scantable::getDirection(int whichrow ) const
1172{
1173 String usertype = table_.keywordSet().asString("DIRECTIONREF");
1174 String type = MDirection::showType(dirCol_.getMeasRef().getType());
1175 if ( usertype != type ) {
1176 MDirection::Types mdt;
1177 if (!MDirection::getType(mdt, usertype)) {
1178 throw(AipsError("Illegal Direction frame."));
1179 }
1180 return dirCol_.convert(uInt(whichrow), mdt);
1181 } else {
1182 return dirCol_(uInt(whichrow));
1183 }
1184}
1185
[847]1186std::string Scantable::getAbcissaLabel( int whichrow ) const
1187{
[996]1188 if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal ro number"));
[847]1189 const MPosition& mp = getAntennaPosition();
[987]1190 const MDirection& md = getDirection(whichrow);
[847]1191 const MEpoch& me = timeCol_(whichrow);
[1819]1192 //const Double& rf = mmolidCol_(whichrow);
1193 const Vector<Double> rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
[847]1194 SpectralCoordinate spc =
1195 freqTable_.getSpectralCoordinate(md, mp, me, rf, mfreqidCol_(whichrow));
1196
1197 String s = "Channel";
1198 Unit u = Unit(freqTable_.getUnitString());
1199 if (u == Unit("km/s")) {
[1170]1200 s = CoordinateUtil::axisLabel(spc, 0, True,True, True);
[847]1201 } else if (u == Unit("Hz")) {
1202 Vector<String> wau(1);wau = u.getName();
1203 spc.setWorldAxisUnits(wau);
[1170]1204 s = CoordinateUtil::axisLabel(spc, 0, True, True, False);
[847]1205 }
1206 return s;
1207
1208}
1209
[1819]1210/**
1211void asap::Scantable::setRestFrequencies( double rf, const std::string& name,
[1170]1212 const std::string& unit )
[1819]1213**/
1214void Scantable::setRestFrequencies( vector<double> rf, const vector<std::string>& name,
1215 const std::string& unit )
1216
[847]1217{
[923]1218 ///@todo lookup in line table to fill in name and formattedname
[847]1219 Unit u(unit);
[1819]1220 //Quantum<Double> urf(rf, u);
1221 Quantum<Vector<Double> >urf(rf, u);
1222 Vector<String> formattedname(0);
1223 //cerr<<"Scantable::setRestFrequnecies="<<urf<<endl;
1224
1225 //uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), name, "");
1226 uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), mathutil::toVectorString(name), formattedname);
[847]1227 TableVector<uInt> tabvec(table_, "MOLECULE_ID");
1228 tabvec = id;
1229}
1230
[1819]1231/**
1232void asap::Scantable::setRestFrequencies( const std::string& name )
[847]1233{
1234 throw(AipsError("setRestFrequencies( const std::string& name ) NYI"));
1235 ///@todo implement
1236}
[1819]1237**/
[2012]1238
[1819]1239void Scantable::setRestFrequencies( const vector<std::string>& name )
1240{
1241 throw(AipsError("setRestFrequencies( const vector<std::string>& name ) NYI"));
1242 ///@todo implement
1243}
[847]1244
[1360]1245std::vector< unsigned int > Scantable::rownumbers( ) const
[852]1246{
1247 std::vector<unsigned int> stlout;
1248 Vector<uInt> vec = table_.rowNumbers();
1249 vec.tovector(stlout);
1250 return stlout;
1251}
1252
[865]1253
[1360]1254Matrix<Float> Scantable::getPolMatrix( uInt whichrow ) const
[896]1255{
1256 ROTableRow row(table_);
1257 const TableRecord& rec = row.get(whichrow);
1258 Table t =
1259 originalTable_( originalTable_.col("SCANNO") == Int(rec.asuInt("SCANNO"))
1260 && originalTable_.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
1261 && originalTable_.col("IFNO") == Int(rec.asuInt("IFNO"))
1262 && originalTable_.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
1263 ROArrayColumn<Float> speccol(t, "SPECTRA");
1264 return speccol.getColumn();
1265}
[865]1266
[1360]1267std::vector< std::string > Scantable::columnNames( ) const
[902]1268{
1269 Vector<String> vec = table_.tableDesc().columnNames();
1270 return mathutil::tovectorstring(vec);
1271}
[896]1272
[1360]1273MEpoch::Types Scantable::getTimeReference( ) const
[915]1274{
1275 return MEpoch::castType(timeCol_.getMeasRef().getType());
[972]1276}
[915]1277
[1360]1278void Scantable::addFit( const STFitEntry& fit, int row )
[972]1279{
[1819]1280 //cout << mfitidCol_(uInt(row)) << endl;
1281 LogIO os( LogOrigin( "Scantable", "addFit()", WHERE ) ) ;
1282 os << mfitidCol_(uInt(row)) << LogIO::POST ;
[972]1283 uInt id = fitTable_.addEntry(fit, mfitidCol_(uInt(row)));
1284 mfitidCol_.put(uInt(row), id);
1285}
[915]1286
[1360]1287void Scantable::shift(int npix)
1288{
1289 Vector<uInt> fids(mfreqidCol_.getColumn());
1290 genSort( fids, Sort::Ascending,
1291 Sort::QuickSort|Sort::NoDuplicates );
1292 for (uInt i=0; i<fids.nelements(); ++i) {
[1567]1293 frequencies().shiftRefPix(npix, fids[i]);
[1360]1294 }
1295}
[987]1296
[1819]1297String Scantable::getAntennaName() const
[1391]1298{
1299 String out;
1300 table_.keywordSet().get("AntennaName", out);
[1987]1301 String::size_type pos1 = out.find("@") ;
1302 String::size_type pos2 = out.find("//") ;
1303 if ( pos2 != String::npos )
[2036]1304 out = out.substr(pos2+2,pos1-pos2-2) ;
[1987]1305 else if ( pos1 != String::npos )
1306 out = out.substr(0,pos1) ;
[1391]1307 return out;
[987]1308}
[1391]1309
[1730]1310int Scantable::checkScanInfo(const std::vector<int>& scanlist) const
[1391]1311{
1312 String tbpath;
1313 int ret = 0;
1314 if ( table_.keywordSet().isDefined("GBT_GO") ) {
1315 table_.keywordSet().get("GBT_GO", tbpath);
1316 Table t(tbpath,Table::Old);
1317 // check each scan if other scan of the pair exist
1318 int nscan = scanlist.size();
1319 for (int i = 0; i < nscan; i++) {
1320 Table subt = t( t.col("SCAN") == scanlist[i]+1 );
1321 if (subt.nrow()==0) {
[1819]1322 //cerr <<"Scan "<<scanlist[i]<<" cannot be found in the scantable."<<endl;
1323 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1324 os <<LogIO::WARN<<"Scan "<<scanlist[i]<<" cannot be found in the scantable."<<LogIO::POST;
[1391]1325 ret = 1;
1326 break;
1327 }
1328 ROTableRow row(subt);
1329 const TableRecord& rec = row.get(0);
1330 int scan1seqn = rec.asuInt("PROCSEQN");
1331 int laston1 = rec.asuInt("LASTON");
1332 if ( rec.asuInt("PROCSIZE")==2 ) {
1333 if ( i < nscan-1 ) {
1334 Table subt2 = t( t.col("SCAN") == scanlist[i+1]+1 );
1335 if ( subt2.nrow() == 0) {
[1819]1336 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1337
1338 //cerr<<"Scan "<<scanlist[i+1]<<" cannot be found in the scantable."<<endl;
1339 os<<LogIO::WARN<<"Scan "<<scanlist[i+1]<<" cannot be found in the scantable."<<LogIO::POST;
[1391]1340 ret = 1;
1341 break;
1342 }
1343 ROTableRow row2(subt2);
1344 const TableRecord& rec2 = row2.get(0);
1345 int scan2seqn = rec2.asuInt("PROCSEQN");
1346 int laston2 = rec2.asuInt("LASTON");
1347 if (scan1seqn == 1 && scan2seqn == 2) {
1348 if (laston1 == laston2) {
[1819]1349 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1350 //cerr<<"A valid scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl;
1351 os<<"A valid scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<LogIO::POST;
[1391]1352 i +=1;
1353 }
1354 else {
[1819]1355 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1356 //cerr<<"Incorrect scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl;
1357 os<<LogIO::WARN<<"Incorrect scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<LogIO::POST;
[1391]1358 }
1359 }
1360 else if (scan1seqn==2 && scan2seqn == 1) {
1361 if (laston1 == laston2) {
[1819]1362 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1363 //cerr<<"["<<scanlist[i]<<","<<scanlist[i+1]<<"] is a valid scan pair but in incorrect order."<<endl;
1364 os<<LogIO::WARN<<"["<<scanlist[i]<<","<<scanlist[i+1]<<"] is a valid scan pair but in incorrect order."<<LogIO::POST;
[1391]1365 ret = 1;
1366 break;
1367 }
1368 }
1369 else {
[1819]1370 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1371 //cerr<<"The other scan for "<<scanlist[i]<<" appears to be missing. Check the input scan numbers."<<endl;
1372 os<<LogIO::WARN<<"The other scan for "<<scanlist[i]<<" appears to be missing. Check the input scan numbers."<<LogIO::POST;
[1391]1373 ret = 1;
1374 break;
1375 }
1376 }
1377 }
1378 else {
[1819]1379 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1380 //cerr<<"The scan does not appear to be standard obsevation."<<endl;
1381 os<<LogIO::WARN<<"The scan does not appear to be standard obsevation."<<LogIO::POST;
[1391]1382 }
1383 //if ( i >= nscan ) break;
1384 }
1385 }
1386 else {
[1819]1387 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1388 //cerr<<"No reference to GBT_GO table."<<endl;
1389 os<<LogIO::WARN<<"No reference to GBT_GO table."<<LogIO::POST;
[1391]1390 ret = 1;
1391 }
1392 return ret;
1393}
1394
[1730]1395std::vector<double> Scantable::getDirectionVector(int whichrow) const
[1391]1396{
1397 Vector<Double> Dir = dirCol_(whichrow).getAngle("rad").getValue();
1398 std::vector<double> dir;
1399 Dir.tovector(dir);
1400 return dir;
1401}
1402
[1819]1403void asap::Scantable::reshapeSpectrum( int nmin, int nmax )
1404 throw( casa::AipsError )
1405{
1406 // assumed that all rows have same nChan
1407 Vector<Float> arr = specCol_( 0 ) ;
1408 int nChan = arr.nelements() ;
1409
1410 // if nmin < 0 or nmax < 0, nothing to do
1411 if ( nmin < 0 ) {
1412 throw( casa::indexError<int>( nmin, "asap::Scantable::reshapeSpectrum: Invalid range. Negative index is specified." ) ) ;
1413 }
1414 if ( nmax < 0 ) {
1415 throw( casa::indexError<int>( nmax, "asap::Scantable::reshapeSpectrum: Invalid range. Negative index is specified." ) ) ;
1416 }
1417
1418 // if nmin > nmax, exchange values
1419 if ( nmin > nmax ) {
1420 int tmp = nmax ;
1421 nmax = nmin ;
1422 nmin = tmp ;
1423 LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1424 os << "Swap values. Applied range is ["
1425 << nmin << ", " << nmax << "]" << LogIO::POST ;
1426 }
1427
1428 // if nmin exceeds nChan, nothing to do
1429 if ( nmin >= nChan ) {
1430 throw( casa::indexError<int>( nmin, "asap::Scantable::reshapeSpectrum: Invalid range. Specified minimum exceeds nChan." ) ) ;
1431 }
1432
1433 // if nmax exceeds nChan, reset nmax to nChan
1434 if ( nmax >= nChan ) {
1435 if ( nmin == 0 ) {
1436 // nothing to do
1437 LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1438 os << "Whole range is selected. Nothing to do." << LogIO::POST ;
1439 return ;
1440 }
1441 else {
1442 LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1443 os << "Specified maximum exceeds nChan. Applied range is ["
1444 << nmin << ", " << nChan-1 << "]." << LogIO::POST ;
1445 nmax = nChan - 1 ;
1446 }
1447 }
1448
1449 // reshape specCol_ and flagCol_
1450 for ( int irow = 0 ; irow < nrow() ; irow++ ) {
1451 reshapeSpectrum( nmin, nmax, irow ) ;
1452 }
1453
1454 // update FREQUENCIES subtable
1455 Double refpix ;
1456 Double refval ;
1457 Double increment ;
1458 int freqnrow = freqTable_.table().nrow() ;
1459 Vector<uInt> oldId( freqnrow ) ;
1460 Vector<uInt> newId( freqnrow ) ;
1461 for ( int irow = 0 ; irow < freqnrow ; irow++ ) {
1462 freqTable_.getEntry( refpix, refval, increment, irow ) ;
1463 /***
1464 * need to shift refpix to nmin
1465 * note that channel nmin in old index will be channel 0 in new one
1466 ***/
1467 refval = refval - ( refpix - nmin ) * increment ;
1468 refpix = 0 ;
1469 freqTable_.setEntry( refpix, refval, increment, irow ) ;
1470 }
1471
1472 // update nchan
1473 int newsize = nmax - nmin + 1 ;
1474 table_.rwKeywordSet().define( "nChan", newsize ) ;
1475
1476 // update bandwidth
1477 // assumed all spectra in the scantable have same bandwidth
1478 table_.rwKeywordSet().define( "Bandwidth", increment * newsize ) ;
1479
1480 return ;
1481}
1482
1483void asap::Scantable::reshapeSpectrum( int nmin, int nmax, int irow )
1484{
1485 // reshape specCol_ and flagCol_
1486 Vector<Float> oldspec = specCol_( irow ) ;
1487 Vector<uChar> oldflag = flagsCol_( irow ) ;
1488 uInt newsize = nmax - nmin + 1 ;
1489 specCol_.put( irow, oldspec( Slice( nmin, newsize, 1 ) ) ) ;
1490 flagsCol_.put( irow, oldflag( Slice( nmin, newsize, 1 ) ) ) ;
1491
1492 return ;
1493}
1494
1495void asap::Scantable::regridChannel( int nChan, double dnu )
1496{
1497 LogIO os( LogOrigin( "Scantable", "regridChannel()", WHERE ) ) ;
1498 os << "Regrid abcissa with channel number " << nChan << " and spectral resoultion " << dnu << "Hz." << LogIO::POST ;
1499 // assumed that all rows have same nChan
1500 Vector<Float> arr = specCol_( 0 ) ;
1501 int oldsize = arr.nelements() ;
1502
1503 // if oldsize == nChan, nothing to do
1504 if ( oldsize == nChan ) {
1505 os << "Specified channel number is same as current one. Nothing to do." << LogIO::POST ;
1506 return ;
1507 }
1508
1509 // if oldChan < nChan, unphysical operation
1510 if ( oldsize < nChan ) {
1511 os << "Unphysical operation. Nothing to do." << LogIO::POST ;
1512 return ;
1513 }
1514
1515 // change channel number for specCol_ and flagCol_
1516 Vector<Float> newspec( nChan, 0 ) ;
1517 Vector<uChar> newflag( nChan, false ) ;
1518 vector<string> coordinfo = getCoordInfo() ;
1519 string oldinfo = coordinfo[0] ;
1520 coordinfo[0] = "Hz" ;
1521 setCoordInfo( coordinfo ) ;
1522 for ( int irow = 0 ; irow < nrow() ; irow++ ) {
1523 regridChannel( nChan, dnu, irow ) ;
1524 }
1525 coordinfo[0] = oldinfo ;
1526 setCoordInfo( coordinfo ) ;
1527
1528
1529 // NOTE: this method does not update metadata such as
1530 // FREQUENCIES subtable, nChan, Bandwidth, etc.
1531
1532 return ;
1533}
1534
1535void asap::Scantable::regridChannel( int nChan, double dnu, int irow )
1536{
1537 // logging
1538 //ofstream ofs( "average.log", std::ios::out | std::ios::app ) ;
1539 //ofs << "IFNO = " << getIF( irow ) << " irow = " << irow << endl ;
1540
1541 Vector<Float> oldspec = specCol_( irow ) ;
1542 Vector<uChar> oldflag = flagsCol_( irow ) ;
1543 Vector<Float> newspec( nChan, 0 ) ;
1544 Vector<uChar> newflag( nChan, false ) ;
1545
1546 // regrid
1547 vector<double> abcissa = getAbcissa( irow ) ;
1548 int oldsize = abcissa.size() ;
1549 double olddnu = abcissa[1] - abcissa[0] ;
1550 //int refChan = 0 ;
1551 //double frac = 0.0 ;
1552 //double wedge = 0.0 ;
1553 //double pile = 0.0 ;
1554 int ichan = 0 ;
1555 double wsum = 0.0 ;
1556 Vector<Float> z( nChan ) ;
1557 z[0] = abcissa[0] - 0.5 * olddnu + 0.5 * dnu ;
1558 for ( int ii = 1 ; ii < nChan ; ii++ )
1559 z[ii] = z[ii-1] + dnu ;
1560 Vector<Float> zi( nChan+1 ) ;
1561 Vector<Float> yi( oldsize + 1 ) ;
1562 zi[0] = z[0] - 0.5 * dnu ;
1563 zi[1] = z[0] + 0.5 * dnu ;
1564 for ( int ii = 2 ; ii < nChan ; ii++ )
1565 zi[ii] = zi[ii-1] + dnu ;
1566 zi[nChan] = z[nChan-1] + 0.5 * dnu ;
1567 yi[0] = abcissa[0] - 0.5 * olddnu ;
1568 yi[1] = abcissa[1] + 0.5 * olddnu ;
1569 for ( int ii = 2 ; ii < oldsize ; ii++ )
1570 yi[ii] = abcissa[ii-1] + olddnu ;
1571 yi[oldsize] = abcissa[oldsize-1] + 0.5 * olddnu ;
1572 if ( dnu > 0.0 ) {
1573 for ( int ii = 0 ; ii < nChan ; ii++ ) {
1574 double zl = zi[ii] ;
1575 double zr = zi[ii+1] ;
1576 for ( int j = ichan ; j < oldsize ; j++ ) {
1577 double yl = yi[j] ;
1578 double yr = yi[j+1] ;
1579 if ( yl <= zl ) {
1580 if ( yr <= zl ) {
1581 continue ;
1582 }
1583 else if ( yr <= zr ) {
1584 newspec[ii] += oldspec[j] * ( yr - zl ) ;
1585 newflag[ii] = newflag[ii] || oldflag[j] ;
1586 wsum += ( yr - zl ) ;
1587 }
1588 else {
1589 newspec[ii] += oldspec[j] * dnu ;
1590 newflag[ii] = newflag[ii] || oldflag[j] ;
1591 wsum += dnu ;
1592 ichan = j ;
1593 break ;
1594 }
1595 }
1596 else if ( yl < zr ) {
1597 if ( yr <= zr ) {
1598 newspec[ii] += oldspec[j] * ( yr - yl ) ;
1599 newflag[ii] = newflag[ii] || oldflag[j] ;
1600 wsum += ( yr - yl ) ;
1601 }
1602 else {
1603 newspec[ii] += oldspec[j] * ( zr - yl ) ;
1604 newflag[ii] = newflag[ii] || oldflag[j] ;
1605 wsum += ( zr - yl ) ;
1606 ichan = j ;
1607 break ;
1608 }
1609 }
1610 else {
1611 ichan = j - 1 ;
1612 break ;
1613 }
1614 }
1615 newspec[ii] /= wsum ;
1616 wsum = 0.0 ;
1617 }
1618 }
1619 else if ( dnu < 0.0 ) {
1620 for ( int ii = 0 ; ii < nChan ; ii++ ) {
1621 double zl = zi[ii] ;
1622 double zr = zi[ii+1] ;
1623 for ( int j = ichan ; j < oldsize ; j++ ) {
1624 double yl = yi[j] ;
1625 double yr = yi[j+1] ;
1626 if ( yl >= zl ) {
1627 if ( yr >= zl ) {
1628 continue ;
1629 }
1630 else if ( yr >= zr ) {
1631 newspec[ii] += oldspec[j] * abs( yr - zl ) ;
1632 newflag[ii] = newflag[ii] || oldflag[j] ;
1633 wsum += abs( yr - zl ) ;
1634 }
1635 else {
1636 newspec[ii] += oldspec[j] * abs( dnu ) ;
1637 newflag[ii] = newflag[ii] || oldflag[j] ;
1638 wsum += abs( dnu ) ;
1639 ichan = j ;
1640 break ;
1641 }
1642 }
1643 else if ( yl > zr ) {
1644 if ( yr >= zr ) {
1645 newspec[ii] += oldspec[j] * abs( yr - yl ) ;
1646 newflag[ii] = newflag[ii] || oldflag[j] ;
1647 wsum += abs( yr - yl ) ;
1648 }
1649 else {
1650 newspec[ii] += oldspec[j] * abs( zr - yl ) ;
1651 newflag[ii] = newflag[ii] || oldflag[j] ;
1652 wsum += abs( zr - yl ) ;
1653 ichan = j ;
1654 break ;
1655 }
1656 }
1657 else {
1658 ichan = j - 1 ;
1659 break ;
1660 }
1661 }
1662 newspec[ii] /= wsum ;
1663 wsum = 0.0 ;
1664 }
1665 }
1666// * ichan = 0
1667// ***/
1668// //ofs << "olddnu = " << olddnu << ", dnu = " << dnu << endl ;
1669// pile += dnu ;
1670// wedge = olddnu * ( refChan + 1 ) ;
1671// while ( wedge < pile ) {
1672// newspec[0] += olddnu * oldspec[refChan] ;
1673// newflag[0] = newflag[0] || oldflag[refChan] ;
1674// //ofs << "channel " << refChan << " is included in new channel 0" << endl ;
1675// refChan++ ;
1676// wedge += olddnu ;
1677// wsum += olddnu ;
1678// //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
1679// }
1680// frac = ( wedge - pile ) / olddnu ;
1681// wsum += ( 1.0 - frac ) * olddnu ;
1682// newspec[0] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
1683// newflag[0] = newflag[0] || oldflag[refChan] ;
1684// //ofs << "channel " << refChan << " is partly included in new channel 0" << " with fraction of " << ( 1.0 - frac ) << endl ;
1685// //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
1686// newspec[0] /= wsum ;
1687// //ofs << "newspec[0] = " << newspec[0] << endl ;
1688// //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
1689
1690// /***
1691// * ichan = 1 - nChan-2
1692// ***/
1693// for ( int ichan = 1 ; ichan < nChan - 1 ; ichan++ ) {
1694// pile += dnu ;
1695// newspec[ichan] += frac * olddnu * oldspec[refChan] ;
1696// newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
1697// //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << frac << endl ;
1698// refChan++ ;
1699// wedge += olddnu ;
1700// wsum = frac * olddnu ;
1701// //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
1702// while ( wedge < pile ) {
1703// newspec[ichan] += olddnu * oldspec[refChan] ;
1704// newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
1705// //ofs << "channel " << refChan << " is included in new channel " << ichan << endl ;
1706// refChan++ ;
1707// wedge += olddnu ;
1708// wsum += olddnu ;
1709// //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
1710// }
1711// frac = ( wedge - pile ) / olddnu ;
1712// wsum += ( 1.0 - frac ) * olddnu ;
1713// newspec[ichan] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
1714// newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
1715// //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << ( 1.0 - frac ) << endl ;
1716// //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
1717// //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
1718// newspec[ichan] /= wsum ;
1719// //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << endl ;
1720// }
1721
1722// /***
1723// * ichan = nChan-1
1724// ***/
1725// // NOTE: Assumed that all spectra have the same bandwidth
1726// pile += dnu ;
1727// newspec[nChan-1] += frac * olddnu * oldspec[refChan] ;
1728// newflag[nChan-1] = newflag[nChan-1] || oldflag[refChan] ;
1729// //ofs << "channel " << refChan << " is partly included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
1730// refChan++ ;
1731// wedge += olddnu ;
1732// wsum = frac * olddnu ;
1733// //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
1734// for ( int jchan = refChan ; jchan < oldsize ; jchan++ ) {
1735// newspec[nChan-1] += olddnu * oldspec[jchan] ;
1736// newflag[nChan-1] = newflag[nChan-1] || oldflag[jchan] ;
1737// wsum += olddnu ;
1738// //ofs << "channel " << jchan << " is included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
1739// //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
1740// }
1741// //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
1742// //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
1743// newspec[nChan-1] /= wsum ;
1744// //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << endl ;
1745
1746// // ofs.close() ;
1747
[2032]1748 specCol_.put( irow, newspec ) ;
1749 flagsCol_.put( irow, newflag ) ;
[1819]1750
1751 return ;
1752}
1753
[1730]1754std::vector<float> Scantable::getWeather(int whichrow) const
1755{
1756 std::vector<float> out(5);
1757 //Float temperature, pressure, humidity, windspeed, windaz;
1758 weatherTable_.getEntry(out[0], out[1], out[2], out[3], out[4],
1759 mweatheridCol_(uInt(whichrow)));
1760
1761
1762 return out;
[1391]1763}
[1730]1764
[2047]1765bool Scantable::getFlagtraFast(uInt whichrow)
[1907]1766{
1767 uChar flag;
1768 Vector<uChar> flags;
[2047]1769 flagsCol_.get(whichrow, flags);
[2012]1770 flag = flags[0];
[2047]1771 for (uInt i = 1; i < flags.size(); ++i) {
[2012]1772 flag &= flags[i];
1773 }
1774 return ((flag >> 7) == 1);
1775}
1776
[2094]1777void Scantable::polyBaseline(const std::vector<bool>& mask, int order, bool getResidual, bool outLogger, const std::string& blfile)
[2047]1778{
1779 ofstream ofs;
[2081]1780 String coordInfo = "";
[2047]1781 bool hasSameNchan = true;
1782 bool outTextFile = false;
1783
1784 if (blfile != "") {
1785 ofs.open(blfile.c_str(), ios::out | ios::app);
1786 if (ofs) outTextFile = true;
1787 }
1788
1789 if (outLogger || outTextFile) {
1790 coordInfo = getCoordInfo()[0];
1791 if (coordInfo == "") coordInfo = "channel";
1792 hasSameNchan = hasSameNchanOverIFs();
1793 }
1794
1795 Fitter fitter = Fitter();
1796 fitter.setExpression("poly", order);
[2081]1797 //fitter.setIterClipping(thresClip, nIterClip);
[2047]1798
1799 int nRow = nrow();
1800 std::vector<bool> chanMask;
1801
1802 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
1803 chanMask = getCompositeChanMask(whichrow, mask);
1804 fitBaseline(chanMask, whichrow, fitter);
[2094]1805 setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
[2047]1806 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "polyBaseline()", fitter);
1807 }
1808
1809 if (outTextFile) ofs.close();
1810}
1811
[2094]1812void Scantable::autoPolyBaseline(const std::vector<bool>& mask, int order, const std::vector<int>& edge, float threshold, int chanAvgLimit, bool getResidual, bool outLogger, const std::string& blfile)
[2047]1813{
1814 ofstream ofs;
[2081]1815 String coordInfo = "";
[2047]1816 bool hasSameNchan = true;
1817 bool outTextFile = false;
1818
1819 if (blfile != "") {
1820 ofs.open(blfile.c_str(), ios::out | ios::app);
1821 if (ofs) outTextFile = true;
1822 }
1823
1824 if (outLogger || outTextFile) {
1825 coordInfo = getCoordInfo()[0];
1826 if (coordInfo == "") coordInfo = "channel";
1827 hasSameNchan = hasSameNchanOverIFs();
1828 }
1829
1830 Fitter fitter = Fitter();
1831 fitter.setExpression("poly", order);
[2081]1832 //fitter.setIterClipping(thresClip, nIterClip);
[2047]1833
1834 int nRow = nrow();
1835 std::vector<bool> chanMask;
1836 int minEdgeSize = getIFNos().size()*2;
1837 STLineFinder lineFinder = STLineFinder();
1838 lineFinder.setOptions(threshold, 3, chanAvgLimit);
1839
1840 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
1841
1842 //-------------------------------------------------------
1843 //chanMask = getCompositeChanMask(whichrow, mask, edge, minEdgeSize, lineFinder);
1844 //-------------------------------------------------------
1845 int edgeSize = edge.size();
1846 std::vector<int> currentEdge;
1847 if (edgeSize >= 2) {
1848 int idx = 0;
1849 if (edgeSize > 2) {
1850 if (edgeSize < minEdgeSize) {
1851 throw(AipsError("Length of edge element info is less than that of IFs"));
1852 }
1853 idx = 2 * getIF(whichrow);
1854 }
1855 currentEdge.push_back(edge[idx]);
1856 currentEdge.push_back(edge[idx+1]);
1857 } else {
1858 throw(AipsError("Wrong length of edge element"));
1859 }
1860 lineFinder.setData(getSpectrum(whichrow));
1861 lineFinder.findLines(getCompositeChanMask(whichrow, mask), currentEdge, whichrow);
1862 chanMask = lineFinder.getMask();
1863 //-------------------------------------------------------
1864
1865 fitBaseline(chanMask, whichrow, fitter);
[2094]1866 setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
[2047]1867
1868 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "autoPolyBaseline()", fitter);
1869 }
1870
1871 if (outTextFile) ofs.close();
1872}
1873
[2094]1874void Scantable::cubicSplineBaseline(const std::vector<bool>& mask, int nPiece, float thresClip, int nIterClip, bool getResidual, bool outLogger, const std::string& blfile)
[2081]1875{
[2012]1876 ofstream ofs;
[2081]1877 String coordInfo = "";
[2047]1878 bool hasSameNchan = true;
[2012]1879 bool outTextFile = false;
1880
1881 if (blfile != "") {
1882 ofs.open(blfile.c_str(), ios::out | ios::app);
1883 if (ofs) outTextFile = true;
1884 }
1885
1886 if (outLogger || outTextFile) {
1887 coordInfo = getCoordInfo()[0];
1888 if (coordInfo == "") coordInfo = "channel";
1889 hasSameNchan = hasSameNchanOverIFs();
1890 }
1891
1892 //Fitter fitter = Fitter();
[2047]1893 //fitter.setExpression("cspline", nPiece);
[2081]1894 //fitter.setIterClipping(thresClip, nIterClip);
[2012]1895
1896 int nRow = nrow();
1897 std::vector<bool> chanMask;
1898
1899 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
1900 chanMask = getCompositeChanMask(whichrow, mask);
[2081]1901 //fitBaseline(chanMask, whichrow, fitter);
[2094]1902 //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
[2081]1903 std::vector<int> pieceEdges;
[2012]1904 std::vector<float> params;
[2094]1905 std::vector<float> res = doCubicSplineFitting(getSpectrum(whichrow), chanMask, nPiece, pieceEdges, params, thresClip, nIterClip, getResidual);
[2012]1906 setSpectrum(res, whichrow);
[2047]1907 //
[2012]1908
[2081]1909 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "cubicSplineBaseline()", pieceEdges, params);
[2012]1910 }
1911
1912 if (outTextFile) ofs.close();
1913}
1914
[2094]1915void Scantable::autoCubicSplineBaseline(const std::vector<bool>& mask, int nPiece, float thresClip, int nIterClip, const std::vector<int>& edge, float threshold, int chanAvgLimit, bool getResidual, bool outLogger, const std::string& blfile)
[2012]1916{
1917 ofstream ofs;
[2081]1918 String coordInfo = "";
[2047]1919 bool hasSameNchan = true;
[2012]1920 bool outTextFile = false;
1921
1922 if (blfile != "") {
1923 ofs.open(blfile.c_str(), ios::out | ios::app);
1924 if (ofs) outTextFile = true;
1925 }
1926
1927 if (outLogger || outTextFile) {
1928 coordInfo = getCoordInfo()[0];
1929 if (coordInfo == "") coordInfo = "channel";
1930 hasSameNchan = hasSameNchanOverIFs();
1931 }
1932
1933 //Fitter fitter = Fitter();
[2047]1934 //fitter.setExpression("cspline", nPiece);
[2081]1935 //fitter.setIterClipping(thresClip, nIterClip);
[2012]1936
1937 int nRow = nrow();
1938 std::vector<bool> chanMask;
1939 int minEdgeSize = getIFNos().size()*2;
1940 STLineFinder lineFinder = STLineFinder();
1941 lineFinder.setOptions(threshold, 3, chanAvgLimit);
1942
1943 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
1944
1945 //-------------------------------------------------------
1946 //chanMask = getCompositeChanMask(whichrow, mask, edge, minEdgeSize, lineFinder);
1947 //-------------------------------------------------------
1948 int edgeSize = edge.size();
1949 std::vector<int> currentEdge;
1950 if (edgeSize >= 2) {
1951 int idx = 0;
1952 if (edgeSize > 2) {
1953 if (edgeSize < minEdgeSize) {
1954 throw(AipsError("Length of edge element info is less than that of IFs"));
1955 }
1956 idx = 2 * getIF(whichrow);
1957 }
1958 currentEdge.push_back(edge[idx]);
1959 currentEdge.push_back(edge[idx+1]);
1960 } else {
1961 throw(AipsError("Wrong length of edge element"));
[1907]1962 }
[2012]1963 lineFinder.setData(getSpectrum(whichrow));
1964 lineFinder.findLines(getCompositeChanMask(whichrow, mask), currentEdge, whichrow);
1965 chanMask = lineFinder.getMask();
1966 //-------------------------------------------------------
1967
1968
[2081]1969 //fitBaseline(chanMask, whichrow, fitter);
[2094]1970 //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
[2081]1971 std::vector<int> pieceEdges;
[2012]1972 std::vector<float> params;
[2094]1973 std::vector<float> res = doCubicSplineFitting(getSpectrum(whichrow), chanMask, nPiece, pieceEdges, params, thresClip, nIterClip, getResidual);
[2012]1974 setSpectrum(res, whichrow);
[2047]1975 //
[2012]1976
[2081]1977 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "autoCubicSplineBaseline()", pieceEdges, params);
[2012]1978 }
1979
1980 if (outTextFile) ofs.close();
[1730]1981}
[1907]1982
[2081]1983std::vector<float> Scantable::doCubicSplineFitting(const std::vector<float>& data, const std::vector<bool>& mask, int nPiece, std::vector<int>& idxEdge, std::vector<float>& params, float thresClip, int nIterClip, bool getResidual)
1984{
1985 if (data.size() != mask.size()) {
1986 throw(AipsError("data and mask sizes are not identical"));
1987 }
[2012]1988 if (nPiece < 1) {
[2094]1989 throw(AipsError("number of the sections must be one or more"));
[2012]1990 }
1991
1992 int nChan = data.size();
1993 std::vector<int> maskArray;
1994 std::vector<int> x;
1995 for (int i = 0; i < nChan; ++i) {
1996 maskArray.push_back(mask[i] ? 1 : 0);
1997 if (mask[i]) {
1998 x.push_back(i);
1999 }
2000 }
2001
[2081]2002 int initNData = x.size();
2003
2004 int nElement = (int)(floor(floor((double)(initNData/nPiece))+0.5));
[2064]2005 std::vector<double> invEdge;
2006 idxEdge.clear();
2007 idxEdge.push_back(x[0]);
[2012]2008 for (int i = 1; i < nPiece; ++i) {
[2047]2009 int valX = x[nElement*i];
[2064]2010 idxEdge.push_back(valX);
2011 invEdge.push_back(1.0/(double)valX);
[2012]2012 }
[2064]2013 idxEdge.push_back(x[x.size()-1]+1);
2014
[2081]2015 int nData = initNData;
2016 int nDOF = nPiece + 3; //number of parameters to solve, namely, 4+(nPiece-1).
2017
2018 std::vector<double> x1, x2, x3, z1, x1z1, x2z1, x3z1, r1, residual;
[2012]2019 for (int i = 0; i < nChan; ++i) {
[2064]2020 double di = (double)i;
2021 double dD = (double)data[i];
2022 x1.push_back(di);
2023 x2.push_back(di*di);
2024 x3.push_back(di*di*di);
2025 z1.push_back(dD);
2026 x1z1.push_back(dD*di);
2027 x2z1.push_back(dD*di*di);
2028 x3z1.push_back(dD*di*di*di);
[2012]2029 r1.push_back(0.0);
[2081]2030 residual.push_back(0.0);
[2012]2031 }
2032
2033 for (int nClip = 0; nClip < nIterClip+1; ++nClip) {
[2064]2034 // xMatrix : horizontal concatenation of
2035 // the least-sq. matrix (left) and an
2036 // identity matrix (right).
2037 // the right part is used to calculate the inverse matrix of the left part.
[2012]2038 double xMatrix[nDOF][2*nDOF];
2039 double zMatrix[nDOF];
2040 for (int i = 0; i < nDOF; ++i) {
2041 for (int j = 0; j < 2*nDOF; ++j) {
2042 xMatrix[i][j] = 0.0;
2043 }
2044 xMatrix[i][nDOF+i] = 1.0;
2045 zMatrix[i] = 0.0;
2046 }
2047
2048 for (int n = 0; n < nPiece; ++n) {
[2064]2049 for (int i = idxEdge[n]; i < idxEdge[n+1]; ++i) {
2050
[2012]2051 if (maskArray[i] == 0) continue;
[2064]2052
[2012]2053 xMatrix[0][0] += 1.0;
[2064]2054 xMatrix[0][1] += x1[i];
2055 xMatrix[0][2] += x2[i];
2056 xMatrix[0][3] += x3[i];
2057 xMatrix[1][1] += x2[i];
2058 xMatrix[1][2] += x3[i];
2059 xMatrix[1][3] += x2[i]*x2[i];
2060 xMatrix[2][2] += x2[i]*x2[i];
2061 xMatrix[2][3] += x3[i]*x2[i];
2062 xMatrix[3][3] += x3[i]*x3[i];
[2012]2063 zMatrix[0] += z1[i];
[2064]2064 zMatrix[1] += x1z1[i];
2065 zMatrix[2] += x2z1[i];
2066 zMatrix[3] += x3z1[i];
2067
[2012]2068 for (int j = 0; j < n; ++j) {
[2064]2069 double q = 1.0 - x1[i]*invEdge[j];
[2012]2070 q = q*q*q;
2071 xMatrix[0][j+4] += q;
[2064]2072 xMatrix[1][j+4] += q*x1[i];
2073 xMatrix[2][j+4] += q*x2[i];
2074 xMatrix[3][j+4] += q*x3[i];
[2012]2075 for (int k = 0; k < j; ++k) {
[2064]2076 double r = 1.0 - x1[i]*invEdge[k];
[2012]2077 r = r*r*r;
2078 xMatrix[k+4][j+4] += r*q;
2079 }
2080 xMatrix[j+4][j+4] += q*q;
2081 zMatrix[j+4] += q*z1[i];
2082 }
[2064]2083
[2012]2084 }
2085 }
2086
2087 for (int i = 0; i < nDOF; ++i) {
2088 for (int j = 0; j < i; ++j) {
2089 xMatrix[i][j] = xMatrix[j][i];
2090 }
2091 }
2092
2093 std::vector<double> invDiag;
2094 for (int i = 0; i < nDOF; ++i) {
2095 invDiag.push_back(1.0/xMatrix[i][i]);
2096 for (int j = 0; j < nDOF; ++j) {
2097 xMatrix[i][j] *= invDiag[i];
2098 }
2099 }
2100
2101 for (int k = 0; k < nDOF; ++k) {
2102 for (int i = 0; i < nDOF; ++i) {
2103 if (i != k) {
2104 double factor1 = xMatrix[k][k];
2105 double factor2 = xMatrix[i][k];
2106 for (int j = k; j < 2*nDOF; ++j) {
2107 xMatrix[i][j] *= factor1;
2108 xMatrix[i][j] -= xMatrix[k][j]*factor2;
2109 xMatrix[i][j] /= factor1;
2110 }
2111 }
2112 }
2113 double xDiag = xMatrix[k][k];
2114 for (int j = k; j < 2*nDOF; ++j) {
2115 xMatrix[k][j] /= xDiag;
2116 }
2117 }
2118
2119 for (int i = 0; i < nDOF; ++i) {
2120 for (int j = 0; j < nDOF; ++j) {
2121 xMatrix[i][nDOF+j] *= invDiag[j];
2122 }
2123 }
2124 //compute a vector y which consists of the coefficients of the best-fit spline curves
2125 //(a0,a1,a2,a3(,b3,c3,...)), namely, the ones for the leftmost piece and the ones of
2126 //cubic terms for the other pieces (in case nPiece>1).
2127 std::vector<double> y;
[2058]2128 y.clear();
[2012]2129 for (int i = 0; i < nDOF; ++i) {
2130 y.push_back(0.0);
2131 for (int j = 0; j < nDOF; ++j) {
2132 y[i] += xMatrix[i][nDOF+j]*zMatrix[j];
2133 }
2134 }
2135
2136 double a0 = y[0];
2137 double a1 = y[1];
2138 double a2 = y[2];
2139 double a3 = y[3];
2140 params.clear();
2141
2142 for (int n = 0; n < nPiece; ++n) {
[2064]2143 for (int i = idxEdge[n]; i < idxEdge[n+1]; ++i) {
2144 r1[i] = a0 + a1*x1[i] + a2*x2[i] + a3*x3[i];
[2081]2145 residual[i] = z1[i] - r1[i];
[2012]2146 }
2147 params.push_back(a0);
2148 params.push_back(a1);
2149 params.push_back(a2);
2150 params.push_back(a3);
2151
2152 if (n == nPiece-1) break;
2153
2154 double d = y[4+n];
[2064]2155 double iE = invEdge[n];
2156 a0 += d;
2157 a1 -= 3.0*d*iE;
2158 a2 += 3.0*d*iE*iE;
2159 a3 -= d*iE*iE*iE;
[2012]2160 }
2161
2162 if ((nClip == nIterClip) || (thresClip <= 0.0)) {
2163 break;
2164 } else {
2165 double stdDev = 0.0;
2166 for (int i = 0; i < nChan; ++i) {
[2081]2167 stdDev += residual[i]*residual[i]*(double)maskArray[i];
[2012]2168 }
2169 stdDev = sqrt(stdDev/(double)nData);
2170
2171 double thres = stdDev * thresClip;
2172 int newNData = 0;
2173 for (int i = 0; i < nChan; ++i) {
[2081]2174 if (abs(residual[i]) >= thres) {
[2012]2175 maskArray[i] = 0;
2176 }
2177 if (maskArray[i] > 0) {
2178 newNData++;
2179 }
2180 }
[2081]2181 if (newNData == nData) {
[2064]2182 break; //no more flag to add. iteration stops.
[2012]2183 } else {
[2081]2184 nData = newNData;
[2012]2185 }
2186 }
2187 }
2188
[2058]2189 std::vector<float> result;
2190 if (getResidual) {
2191 for (int i = 0; i < nChan; ++i) {
[2081]2192 result.push_back((float)residual[i]);
[2058]2193 }
2194 } else {
2195 for (int i = 0; i < nChan; ++i) {
2196 result.push_back((float)r1[i]);
2197 }
[2012]2198 }
2199
[2058]2200 return result;
[2012]2201}
2202
[2081]2203void Scantable::sinusoidBaseline(const std::vector<bool>& mask, const std::vector<int>& nWaves, float maxWaveLength, float thresClip, int nIterClip, bool getResidual, bool outLogger, const std::string& blfile)
2204{
[2012]2205 ofstream ofs;
[2081]2206 String coordInfo = "";
[2047]2207 bool hasSameNchan = true;
[2012]2208 bool outTextFile = false;
2209
2210 if (blfile != "") {
2211 ofs.open(blfile.c_str(), ios::out | ios::app);
2212 if (ofs) outTextFile = true;
2213 }
2214
2215 if (outLogger || outTextFile) {
2216 coordInfo = getCoordInfo()[0];
2217 if (coordInfo == "") coordInfo = "channel";
2218 hasSameNchan = hasSameNchanOverIFs();
2219 }
2220
[2047]2221 //Fitter fitter = Fitter();
[2081]2222 //fitter.setExpression("sinusoid", nWaves);
2223 //fitter.setIterClipping(thresClip, nIterClip);
[2012]2224
2225 int nRow = nrow();
2226 std::vector<bool> chanMask;
2227
2228 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2229 chanMask = getCompositeChanMask(whichrow, mask);
[2081]2230 //fitBaseline(chanMask, whichrow, fitter);
[2094]2231 //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
[2047]2232 std::vector<float> params;
[2081]2233 std::vector<float> res = doSinusoidFitting(getSpectrum(whichrow), chanMask, nWaves, maxWaveLength, params, thresClip, nIterClip, getResidual);
[2047]2234 setSpectrum(res, whichrow);
2235 //
[2012]2236
[2081]2237 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "sinusoidBaseline()", params);
[1931]2238 }
[2012]2239
2240 if (outTextFile) ofs.close();
[1907]2241}
2242
[2081]2243void Scantable::autoSinusoidBaseline(const std::vector<bool>& mask, const std::vector<int>& nWaves, float maxWaveLength, float thresClip, int nIterClip, const std::vector<int>& edge, float threshold, int chanAvgLimit, bool getResidual, bool outLogger, const std::string& blfile)
[2012]2244{
2245 ofstream ofs;
[2081]2246 String coordInfo = "";
[2047]2247 bool hasSameNchan = true;
[2012]2248 bool outTextFile = false;
2249
2250 if (blfile != "") {
2251 ofs.open(blfile.c_str(), ios::out | ios::app);
2252 if (ofs) outTextFile = true;
2253 }
2254
2255 if (outLogger || outTextFile) {
2256 coordInfo = getCoordInfo()[0];
2257 if (coordInfo == "") coordInfo = "channel";
2258 hasSameNchan = hasSameNchanOverIFs();
2259 }
2260
[2047]2261 //Fitter fitter = Fitter();
[2081]2262 //fitter.setExpression("sinusoid", nWaves);
2263 //fitter.setIterClipping(thresClip, nIterClip);
[2012]2264
2265 int nRow = nrow();
2266 std::vector<bool> chanMask;
2267 int minEdgeSize = getIFNos().size()*2;
2268 STLineFinder lineFinder = STLineFinder();
2269 lineFinder.setOptions(threshold, 3, chanAvgLimit);
2270
2271 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2272
2273 //-------------------------------------------------------
2274 //chanMask = getCompositeChanMask(whichrow, mask, edge, minEdgeSize, lineFinder);
2275 //-------------------------------------------------------
2276 int edgeSize = edge.size();
2277 std::vector<int> currentEdge;
2278 if (edgeSize >= 2) {
2279 int idx = 0;
2280 if (edgeSize > 2) {
2281 if (edgeSize < minEdgeSize) {
2282 throw(AipsError("Length of edge element info is less than that of IFs"));
2283 }
2284 idx = 2 * getIF(whichrow);
2285 }
2286 currentEdge.push_back(edge[idx]);
2287 currentEdge.push_back(edge[idx+1]);
2288 } else {
2289 throw(AipsError("Wrong length of edge element"));
2290 }
2291 lineFinder.setData(getSpectrum(whichrow));
2292 lineFinder.findLines(getCompositeChanMask(whichrow, mask), currentEdge, whichrow);
2293 chanMask = lineFinder.getMask();
2294 //-------------------------------------------------------
2295
2296
[2081]2297 //fitBaseline(chanMask, whichrow, fitter);
[2094]2298 //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
[2047]2299 std::vector<float> params;
[2081]2300 std::vector<float> res = doSinusoidFitting(getSpectrum(whichrow), chanMask, nWaves, maxWaveLength, params, thresClip, nIterClip, getResidual);
[2047]2301 setSpectrum(res, whichrow);
2302 //
[2012]2303
[2081]2304 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "autoSinusoidBaseline()", params);
[2047]2305 }
[2012]2306
[2047]2307 if (outTextFile) ofs.close();
2308}
2309
[2081]2310std::vector<float> Scantable::doSinusoidFitting(const std::vector<float>& data, const std::vector<bool>& mask, const std::vector<int>& waveNumbers, float maxWaveLength, std::vector<float>& params, float thresClip, int nIterClip, bool getResidual)
2311{
[2047]2312 if (data.size() != mask.size()) {
[2081]2313 throw(AipsError("data and mask sizes are not identical"));
[2047]2314 }
[2081]2315 if (data.size() < 2) {
2316 throw(AipsError("data size is too short"));
2317 }
2318 if (waveNumbers.size() == 0) {
2319 throw(AipsError("missing wave number info"));
2320 }
2321 std::vector<int> nWaves; // sorted and uniqued array of wave numbers
2322 nWaves.reserve(waveNumbers.size());
2323 copy(waveNumbers.begin(), waveNumbers.end(), back_inserter(nWaves));
2324 sort(nWaves.begin(), nWaves.end());
2325 std::vector<int>::iterator end_it = unique(nWaves.begin(), nWaves.end());
2326 nWaves.erase(end_it, nWaves.end());
2327
2328 int minNWaves = nWaves[0];
2329 if (minNWaves < 0) {
[2058]2330 throw(AipsError("wave number must be positive or zero (i.e. constant)"));
2331 }
[2081]2332 bool hasConstantTerm = (minNWaves == 0);
[2047]2333
2334 int nChan = data.size();
2335 std::vector<int> maskArray;
2336 std::vector<int> x;
2337 for (int i = 0; i < nChan; ++i) {
2338 maskArray.push_back(mask[i] ? 1 : 0);
2339 if (mask[i]) {
2340 x.push_back(i);
2341 }
2342 }
2343
[2081]2344 int initNData = x.size();
[2047]2345
[2081]2346 int nData = initNData;
2347 int nDOF = nWaves.size() * 2 - (hasConstantTerm ? 1 : 0); //number of parameters to solve.
2348
2349 const double PI = 6.0 * asin(0.5); // PI (= 3.141592653...)
[2094]2350 double baseXFactor = 2.0*PI/(double)maxWaveLength/(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]2351
2352 // xArray : contains elemental values for computing the least-square matrix.
2353 // xArray.size() is nDOF and xArray[*].size() is nChan.
2354 // Each xArray element are as follows:
2355 // xArray[0] = {1.0, 1.0, 1.0, ..., 1.0},
2356 // xArray[2n-1] = {sin(nPI/L*x[0]), sin(nPI/L*x[1]), ..., sin(nPI/L*x[nChan])},
2357 // xArray[2n] = {cos(nPI/L*x[0]), cos(nPI/L*x[1]), ..., cos(nPI/L*x[nChan])},
2358 // where (1 <= n <= nMaxWavesInSW),
2359 // or,
2360 // xArray[2n-1] = {sin(wn[n]PI/L*x[0]), sin(wn[n]PI/L*x[1]), ..., sin(wn[n]PI/L*x[nChan])},
2361 // xArray[2n] = {cos(wn[n]PI/L*x[0]), cos(wn[n]PI/L*x[1]), ..., cos(wn[n]PI/L*x[nChan])},
2362 // where wn[n] denotes waveNumbers[n] (1 <= n <= waveNumbers.size()).
2363 std::vector<std::vector<double> > xArray;
2364 if (hasConstantTerm) {
2365 std::vector<double> xu;
2366 for (int j = 0; j < nChan; ++j) {
2367 xu.push_back(1.0);
2368 }
2369 xArray.push_back(xu);
2370 }
2371 for (uInt i = (hasConstantTerm ? 1 : 0); i < nWaves.size(); ++i) {
2372 double xFactor = baseXFactor*(double)nWaves[i];
2373 std::vector<double> xs, xc;
2374 xs.clear();
2375 xc.clear();
2376 for (int j = 0; j < nChan; ++j) {
2377 xs.push_back(sin(xFactor*(double)j));
2378 xc.push_back(cos(xFactor*(double)j));
2379 }
2380 xArray.push_back(xs);
2381 xArray.push_back(xc);
2382 }
2383
2384 std::vector<double> z1, r1, residual;
[2047]2385 for (int i = 0; i < nChan; ++i) {
[2081]2386 z1.push_back((double)data[i]);
[2047]2387 r1.push_back(0.0);
[2081]2388 residual.push_back(0.0);
[2047]2389 }
2390
2391 for (int nClip = 0; nClip < nIterClip+1; ++nClip) {
[2081]2392 // xMatrix : horizontal concatenation of
2393 // the least-sq. matrix (left) and an
2394 // identity matrix (right).
2395 // the right part is used to calculate the inverse matrix of the left part.
[2047]2396 double xMatrix[nDOF][2*nDOF];
2397 double zMatrix[nDOF];
2398 for (int i = 0; i < nDOF; ++i) {
2399 for (int j = 0; j < 2*nDOF; ++j) {
2400 xMatrix[i][j] = 0.0;
[2012]2401 }
[2047]2402 xMatrix[i][nDOF+i] = 1.0;
2403 zMatrix[i] = 0.0;
2404 }
2405
[2081]2406 for (int k = 0; k < nChan; ++k) {
2407 if (maskArray[k] == 0) continue;
2408
2409 for (int i = 0; i < nDOF; ++i) {
2410 for (int j = i; j < nDOF; ++j) {
2411 xMatrix[i][j] += xArray[i][k] * xArray[j][k];
2412 }
2413 zMatrix[i] += z1[k] * xArray[i][k];
2414 }
[2047]2415 }
2416
2417 for (int i = 0; i < nDOF; ++i) {
2418 for (int j = 0; j < i; ++j) {
2419 xMatrix[i][j] = xMatrix[j][i];
[2012]2420 }
2421 }
2422
[2047]2423 std::vector<double> invDiag;
2424 for (int i = 0; i < nDOF; ++i) {
2425 invDiag.push_back(1.0/xMatrix[i][i]);
2426 for (int j = 0; j < nDOF; ++j) {
2427 xMatrix[i][j] *= invDiag[i];
2428 }
2429 }
2430
2431 for (int k = 0; k < nDOF; ++k) {
2432 for (int i = 0; i < nDOF; ++i) {
2433 if (i != k) {
2434 double factor1 = xMatrix[k][k];
2435 double factor2 = xMatrix[i][k];
2436 for (int j = k; j < 2*nDOF; ++j) {
2437 xMatrix[i][j] *= factor1;
2438 xMatrix[i][j] -= xMatrix[k][j]*factor2;
2439 xMatrix[i][j] /= factor1;
2440 }
2441 }
2442 }
2443 double xDiag = xMatrix[k][k];
2444 for (int j = k; j < 2*nDOF; ++j) {
2445 xMatrix[k][j] /= xDiag;
2446 }
2447 }
2448
2449 for (int i = 0; i < nDOF; ++i) {
2450 for (int j = 0; j < nDOF; ++j) {
2451 xMatrix[i][nDOF+j] *= invDiag[j];
2452 }
2453 }
2454 //compute a vector y which consists of the coefficients of the sinusoids forming the
[2081]2455 //best-fit curves (a0,s1,c1,s2,c2,...), where a0 is constant and s* and c* are of sine
2456 //and cosine functions, respectively.
[2047]2457 std::vector<double> y;
[2081]2458 params.clear();
[2047]2459 for (int i = 0; i < nDOF; ++i) {
2460 y.push_back(0.0);
2461 for (int j = 0; j < nDOF; ++j) {
2462 y[i] += xMatrix[i][nDOF+j]*zMatrix[j];
2463 }
[2081]2464 params.push_back(y[i]);
[2047]2465 }
2466
2467 for (int i = 0; i < nChan; ++i) {
[2081]2468 r1[i] = y[0];
2469 for (int j = 1; j < nDOF; ++j) {
2470 r1[i] += y[j]*xArray[j][i];
2471 }
2472 residual[i] = z1[i] - r1[i];
[2047]2473 }
2474
2475 if ((nClip == nIterClip) || (thresClip <= 0.0)) {
2476 break;
2477 } else {
2478 double stdDev = 0.0;
2479 for (int i = 0; i < nChan; ++i) {
[2081]2480 stdDev += residual[i]*residual[i]*(double)maskArray[i];
[2047]2481 }
2482 stdDev = sqrt(stdDev/(double)nData);
2483
2484 double thres = stdDev * thresClip;
2485 int newNData = 0;
2486 for (int i = 0; i < nChan; ++i) {
[2081]2487 if (abs(residual[i]) >= thres) {
[2047]2488 maskArray[i] = 0;
2489 }
2490 if (maskArray[i] > 0) {
2491 newNData++;
2492 }
2493 }
[2081]2494 if (newNData == nData) {
2495 break; //no more flag to add. iteration stops.
[2047]2496 } else {
[2081]2497 nData = newNData;
[2047]2498 }
2499 }
[2012]2500 }
2501
[2058]2502 std::vector<float> result;
2503 if (getResidual) {
2504 for (int i = 0; i < nChan; ++i) {
[2081]2505 result.push_back((float)residual[i]);
[2058]2506 }
2507 } else {
2508 for (int i = 0; i < nChan; ++i) {
2509 result.push_back((float)r1[i]);
2510 }
[2047]2511 }
2512
[2058]2513 return result;
[2012]2514}
2515
[2047]2516void Scantable::fitBaseline(const std::vector<bool>& mask, int whichrow, Fitter& fitter)
2517{
[2081]2518 std::vector<double> dAbcissa = getAbcissa(whichrow);
2519 std::vector<float> abcissa;
2520 for (uInt i = 0; i < dAbcissa.size(); ++i) {
2521 abcissa.push_back((float)dAbcissa[i]);
[2047]2522 }
2523 std::vector<float> spec = getSpectrum(whichrow);
[2012]2524
[2081]2525 fitter.setData(abcissa, spec, mask);
[2047]2526 fitter.lfit();
2527}
2528
2529std::vector<bool> Scantable::getCompositeChanMask(int whichrow, const std::vector<bool>& inMask)
2530{
2531 std::vector<bool> chanMask = getMask(whichrow);
2532 uInt chanMaskSize = chanMask.size();
2533 if (chanMaskSize != inMask.size()) {
2534 throw(AipsError("different mask sizes"));
2535 }
2536 for (uInt i = 0; i < chanMaskSize; ++i) {
2537 chanMask[i] = chanMask[i] && inMask[i];
2538 }
2539
2540 return chanMask;
2541}
2542
2543/*
2544std::vector<bool> Scantable::getCompositeChanMask(int whichrow, const std::vector<bool>& inMask, const std::vector<int>& edge, const int minEdgeSize, STLineFinder& lineFinder)
2545{
2546 int edgeSize = edge.size();
2547 std::vector<int> currentEdge;
2548 if (edgeSize >= 2) {
2549 int idx = 0;
2550 if (edgeSize > 2) {
2551 if (edgeSize < minEdgeSize) {
2552 throw(AipsError("Length of edge element info is less than that of IFs"));
2553 }
2554 idx = 2 * getIF(whichrow);
2555 }
2556 currentEdge.push_back(edge[idx]);
2557 currentEdge.push_back(edge[idx+1]);
2558 } else {
2559 throw(AipsError("Wrong length of edge element"));
2560 }
2561
2562 lineFinder.setData(getSpectrum(whichrow));
2563 lineFinder.findLines(getCompositeChanMask(whichrow, inMask), currentEdge, whichrow);
2564
2565 return lineFinder.getMask();
2566}
2567*/
2568
2569/* for poly. the variations of outputFittingResult() should be merged into one eventually (2011/3/10 WK) */
2570void 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) {
2571 if (outLogger || outTextFile) {
2572 std::vector<float> params = fitter.getParameters();
2573 std::vector<bool> fixed = fitter.getFixedParameters();
2574 float rms = getRms(chanMask, whichrow);
2575 String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
2576
2577 if (outLogger) {
2578 LogIO ols(LogOrigin("Scantable", funcName, WHERE));
2579 ols << formatBaselineParams(params, fixed, rms, masklist, whichrow, false) << LogIO::POST ;
2580 }
2581 if (outTextFile) {
2582 ofs << formatBaselineParams(params, fixed, rms, masklist, whichrow, true) << flush;
2583 }
2584 }
2585}
2586
2587/* for cspline. will be merged once cspline is available in fitter (2011/3/10 WK) */
[2081]2588void 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) {
[2047]2589 if (outLogger || outTextFile) {
2590 float rms = getRms(chanMask, whichrow);
2591 String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
[2081]2592 std::vector<bool> fixed;
2593 fixed.clear();
[2047]2594
2595 if (outLogger) {
2596 LogIO ols(LogOrigin("Scantable", funcName, WHERE));
[2064]2597 ols << formatPiecewiseBaselineParams(edge, params, fixed, rms, masklist, whichrow, false) << LogIO::POST ;
[2047]2598 }
2599 if (outTextFile) {
[2064]2600 ofs << formatPiecewiseBaselineParams(edge, params, fixed, rms, masklist, whichrow, true) << flush;
[2047]2601 }
2602 }
2603}
2604
2605/* for sinusoid. will be merged once sinusoid is available in fitter (2011/3/10 WK) */
[2081]2606void 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) {
[2047]2607 if (outLogger || outTextFile) {
2608 float rms = getRms(chanMask, whichrow);
2609 String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
[2081]2610 std::vector<bool> fixed;
2611 fixed.clear();
[2047]2612
2613 if (outLogger) {
2614 LogIO ols(LogOrigin("Scantable", funcName, WHERE));
2615 ols << formatBaselineParams(params, fixed, rms, masklist, whichrow, false) << LogIO::POST ;
2616 }
2617 if (outTextFile) {
2618 ofs << formatBaselineParams(params, fixed, rms, masklist, whichrow, true) << flush;
2619 }
2620 }
2621}
2622
[2012]2623float Scantable::getRms(const std::vector<bool>& mask, int whichrow) {
2624 Vector<Float> spec;
2625 specCol_.get(whichrow, spec);
2626
2627 float mean = 0.0;
2628 float smean = 0.0;
2629 int n = 0;
[2047]2630 for (uInt i = 0; i < spec.nelements(); ++i) {
[2012]2631 if (mask[i]) {
2632 mean += spec[i];
2633 smean += spec[i]*spec[i];
2634 n++;
2635 }
2636 }
2637
2638 mean /= (float)n;
2639 smean /= (float)n;
2640
2641 return sqrt(smean - mean*mean);
2642}
2643
2644
2645std::string Scantable::formatBaselineParamsHeader(int whichrow, const std::string& masklist, bool verbose) const
2646{
2647 ostringstream oss;
2648
2649 if (verbose) {
2650 oss << " Scan[" << getScan(whichrow) << "]";
2651 oss << " Beam[" << getBeam(whichrow) << "]";
2652 oss << " IF[" << getIF(whichrow) << "]";
2653 oss << " Pol[" << getPol(whichrow) << "]";
2654 oss << " Cycle[" << getCycle(whichrow) << "]: " << endl;
2655 oss << "Fitter range = " << masklist << endl;
2656 oss << "Baseline parameters" << endl;
2657 oss << flush;
2658 }
2659
2660 return String(oss);
2661}
2662
2663std::string Scantable::formatBaselineParamsFooter(float rms, bool verbose) const
2664{
2665 ostringstream oss;
2666
2667 if (verbose) {
2668 oss << "Results of baseline fit" << endl;
2669 oss << " rms = " << setprecision(6) << rms << endl;
[2094]2670 for (int i = 0; i < 60; ++i) {
2671 oss << "-";
2672 }
2673 oss << flush;
[2012]2674 }
2675
2676 return String(oss);
2677}
2678
[2064]2679 std::string Scantable::formatBaselineParams(const std::vector<float>& params, const std::vector<bool>& fixed, float rms, const std::string& masklist, int whichrow, bool verbose, int start, int count, bool resetparamid) const
[2047]2680{
[2064]2681 int nParam = (int)(params.size());
[2047]2682
[2064]2683 if (nParam < 1) {
2684 return(" Not fitted");
2685 } else {
2686
2687 ostringstream oss;
2688 oss << formatBaselineParamsHeader(whichrow, masklist, verbose);
2689
2690 if (start < 0) start = 0;
2691 if (count < 0) count = nParam;
2692 int end = start + count;
2693 if (end > nParam) end = nParam;
2694 int paramidoffset = (resetparamid) ? (-start) : 0;
2695
2696 for (int i = start; i < end; ++i) {
2697 if (i > start) {
[2047]2698 oss << ",";
2699 }
[2064]2700 std::string sFix = ((fixed.size() > 0) && (fixed[i]) && verbose) ? "(fixed)" : "";
2701 oss << " p" << (i+paramidoffset) << sFix << "= " << right << setw(13) << setprecision(6) << params[i];
[2047]2702 }
[2064]2703
2704 oss << endl;
2705 oss << formatBaselineParamsFooter(rms, verbose);
2706
2707 return String(oss);
[2047]2708 }
2709
2710}
2711
[2012]2712std::string Scantable::formatPiecewiseBaselineParams(const std::vector<int>& ranges, const std::vector<float>& params, const std::vector<bool>& fixed, float rms, const std::string& masklist, int whichrow, bool verbose) const
2713{
[2064]2714 int nOutParam = (int)(params.size());
2715 int nPiece = (int)(ranges.size()) - 1;
[2012]2716
[2064]2717 if (nOutParam < 1) {
2718 return(" Not fitted");
2719 } else if (nPiece < 0) {
2720 return formatBaselineParams(params, fixed, rms, masklist, whichrow, verbose);
2721 } else if (nPiece < 1) {
2722 return(" Bad count of the piece edge info");
2723 } else if (nOutParam % nPiece != 0) {
2724 return(" Bad count of the output baseline parameters");
2725 } else {
2726
2727 int nParam = nOutParam / nPiece;
2728
2729 ostringstream oss;
2730 oss << formatBaselineParamsHeader(whichrow, masklist, verbose);
2731
2732 stringstream ss;
2733 ss << ranges[nPiece] << flush;
2734 int wRange = ss.str().size() * 2 + 5;
2735
2736 for (int i = 0; i < nPiece; ++i) {
[2047]2737 ss.str("");
[2064]2738 ss << " [" << ranges[i] << "," << (ranges[i+1]-1) << "]";
2739 oss << left << setw(wRange) << ss.str();
2740 oss << formatBaselineParams(params, fixed, rms, masklist, whichrow, false, i*nParam, nParam, true);
[2012]2741 }
[2064]2742
2743 oss << formatBaselineParamsFooter(rms, verbose);
2744
2745 return String(oss);
[2012]2746 }
2747
2748}
2749
[2047]2750bool Scantable::hasSameNchanOverIFs()
[2012]2751{
[2047]2752 int nIF = nif(-1);
2753 int nCh;
2754 int totalPositiveNChan = 0;
2755 int nPositiveNChan = 0;
[2012]2756
[2047]2757 for (int i = 0; i < nIF; ++i) {
2758 nCh = nchan(i);
2759 if (nCh > 0) {
2760 totalPositiveNChan += nCh;
2761 nPositiveNChan++;
[2012]2762 }
2763 }
2764
[2047]2765 return (totalPositiveNChan == (nPositiveNChan * nchan(0)));
[2012]2766}
2767
[2047]2768std::string Scantable::getMaskRangeList(const std::vector<bool>& mask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, bool verbose)
[2012]2769{
2770 if (mask.size() < 2) {
2771 throw(AipsError("The mask elements should be > 1"));
2772 }
[2047]2773 int IF = getIF(whichrow);
2774 if (mask.size() != (uInt)nchan(IF)) {
[2012]2775 throw(AipsError("Number of channels in scantable != number of mask elements"));
2776 }
2777
[2047]2778 if (verbose) {
[2012]2779 LogIO logOs(LogOrigin("Scantable", "getMaskRangeList()", WHERE));
2780 logOs << LogIO::WARN << "The current mask window unit is " << coordInfo;
2781 if (!hasSameNchan) {
[2047]2782 logOs << endl << "This mask is only valid for IF=" << IF;
[2012]2783 }
2784 logOs << LogIO::POST;
2785 }
2786
2787 std::vector<double> abcissa = getAbcissa(whichrow);
[2047]2788 std::vector<int> edge = getMaskEdgeIndices(mask);
2789
[2012]2790 ostringstream oss;
2791 oss.setf(ios::fixed);
2792 oss << setprecision(1) << "[";
[2047]2793 for (uInt i = 0; i < edge.size(); i+=2) {
[2012]2794 if (i > 0) oss << ",";
[2047]2795 oss << "[" << (float)abcissa[edge[i]] << "," << (float)abcissa[edge[i+1]] << "]";
[2012]2796 }
2797 oss << "]" << flush;
2798
2799 return String(oss);
2800}
2801
[2047]2802std::vector<int> Scantable::getMaskEdgeIndices(const std::vector<bool>& mask)
[2012]2803{
[2047]2804 if (mask.size() < 2) {
2805 throw(AipsError("The mask elements should be > 1"));
[2012]2806 }
2807
[2047]2808 std::vector<int> out, startIndices, endIndices;
2809 int maskSize = mask.size();
[2012]2810
[2047]2811 startIndices.clear();
2812 endIndices.clear();
2813
2814 if (mask[0]) {
2815 startIndices.push_back(0);
[2012]2816 }
[2047]2817 for (int i = 1; i < maskSize; ++i) {
2818 if ((!mask[i-1]) && mask[i]) {
2819 startIndices.push_back(i);
2820 } else if (mask[i-1] && (!mask[i])) {
2821 endIndices.push_back(i-1);
2822 }
[2012]2823 }
[2047]2824 if (mask[maskSize-1]) {
2825 endIndices.push_back(maskSize-1);
2826 }
[2012]2827
[2047]2828 if (startIndices.size() != endIndices.size()) {
2829 throw(AipsError("Inconsistent Mask Size: bad data?"));
2830 }
2831 for (uInt i = 0; i < startIndices.size(); ++i) {
2832 if (startIndices[i] > endIndices[i]) {
2833 throw(AipsError("Mask start index > mask end index"));
[2012]2834 }
2835 }
2836
[2047]2837 out.clear();
2838 for (uInt i = 0; i < startIndices.size(); ++i) {
2839 out.push_back(startIndices[i]);
2840 out.push_back(endIndices[i]);
2841 }
2842
[2012]2843 return out;
2844}
2845
2846
2847/*
[1931]2848STFitEntry Scantable::polyBaseline(const std::vector<bool>& mask, int order, int rowno)
[1907]2849{
2850 Fitter fitter = Fitter();
[2012]2851 fitter.setExpression("poly", order);
2852
2853 std::vector<bool> fmask = getMask(rowno);
2854 if (fmask.size() != mask.size()) {
2855 throw(AipsError("different mask sizes"));
2856 }
2857 for (int i = 0; i < fmask.size(); ++i) {
2858 fmask[i] = fmask[i] && mask[i];
2859 }
2860
2861 fitBaseline(fmask, rowno, fitter);
[1907]2862 setSpectrum(fitter.getResidual(), rowno);
[1931]2863 return fitter.getFitEntry();
[1907]2864}
[2012]2865*/
[1907]2866
2867}
[1819]2868//namespace asap
Note: See TracBrowser for help on using the repository browser.