source: trunk/src/Scantable.cpp@ 3023

Last change on this file since 3023 was 3023, checked in by Kana Sugimoto, 11 years ago

New Development: No

JIRA Issue: No (Bug fixes)

Ready for Test: Yes

Interface Changes: Yes

What Interface Changed: Added a function Scantable::nValidMask(const std::vector<bool>& mask);

Test Programs:

Put in Release Notes: Yes

Module(s): scantable, sdbaseline

Description:

  • Added a new function Scantable::nValidMask(const std::vector<bool>& mask) that returns the number of elements in true in the input bool vector, mask.
  • Fixed a bug in Scantable::isAllChannelsFlagged that fails to detect completely flagged channels when BDF flag and the other flag is mixed in a spectrum.
  • Fixed a bug in *Baseline functions that caused an error of baseline subtraction in case there is a spectrum of which all channels are flagged.


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