source: trunk/src/Scantable.cpp@ 2943

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

New Development: Yes

JIRA Issue: Yes (CAS-6486)

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs: unit tests of sdlist

Put in Release Notes: Yes

Module(s): sdlist, scantable.summary()

Description: Modified Frequency listing of Scantable::summary. It now lists channel 0 frequency and IF center frequency, instead of refval and refpix.


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