source: trunk/src/Scantable.cpp@ 2946

Last change on this file since 2946 was 2946, checked in by WataruKawasaki, 11 years ago

New Development: No

JIRA Issue: No

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs:

Put in Release Notes: No

Module(s): sd

Description: flagtra was not used in subBaseline() with uself=false mode. fixed so that flagtra is properly used in both cases uself=T/F.


  • 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 } else {
2733 mask = getCompositeChanMask(irow, mask);
2734 }
2735
2736 std::vector<float> res;
2737 if (ftype == STBaselineFunc::Polynomial) {
2738 res = doPolynomialFitting(spec, mask, fpar[0], params, rms, finalmask, clipth, clipn);
2739 } else if (ftype == STBaselineFunc::Chebyshev) {
2740 res = doChebyshevFitting(spec, mask, fpar[0], params, rms, finalmask, clipth, clipn);
2741 } else if (ftype == STBaselineFunc::CSpline) {
2742 if (fpar.size() > 1) { // reading from baseline table in which pieceEdges are already calculated and stored.
2743 res = doCubicSplineFitting(spec, mask, fpar, params, rms, finalmask, clipth, clipn);
2744 } else { // usual cspline fitting by giving nPiece only. fpar will be replaced with pieceEdges.
2745 res = doCubicSplineFitting(spec, mask, fpar[0], fpar, params, rms, finalmask, clipth, clipn);
2746 }
2747 } else if (ftype == STBaselineFunc::Sinusoid) {
2748 res = doSinusoidFitting(spec, mask, fpar, params, rms, finalmask, clipth, clipn);
2749 }
2750
2751 return res;
2752}
2753
2754std::string Scantable::packFittingResults(const int irow, const std::vector<float>& params, const float rms)
2755{
2756 // returned value: "irow:params[0],params[1],..,params[n-1]:rms"
2757 ostringstream os;
2758 os << irow << ':';
2759 for (uInt i = 0; i < params.size(); ++i) {
2760 if (i > 0) {
2761 os << ',';
2762 }
2763 os << params[i];
2764 }
2765 os << ':' << rms;
2766
2767 return os.str();
2768}
2769
2770void 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)
2771{
2772 // The baseline info to be parsed must be column-delimited string like
2773 // "0:chebyshev:5:3,5,169,174,485,487" where the elements are
2774 // row number, funcType, funcOrder, maskList, clipThreshold, clipNIter,
2775 // useLineFinder, lfThreshold, lfEdge and lfChanAvgLimit.
2776
2777 std::vector<string> res = splitToStringList(blInfo, ':');
2778 if (res.size() < 4) {
2779 throw(AipsError("baseline info has bad format")) ;
2780 }
2781
2782 string ftype0, fpar0, masklist0, uself0, edge0;
2783 std::vector<int> masklist;
2784
2785 stringstream ss;
2786 ss << res[0];
2787 ss >> irow;
2788 ss.clear(); ss.str("");
2789
2790 ss << res[1];
2791 ss >> ftype0;
2792 if (ftype0 == "poly") {
2793 ftype = STBaselineFunc::Polynomial;
2794 } else if (ftype0 == "cspline") {
2795 ftype = STBaselineFunc::CSpline;
2796 } else if (ftype0 == "sinusoid") {
2797 ftype = STBaselineFunc::Sinusoid;
2798 } else if (ftype0 == "chebyshev") {
2799 ftype = STBaselineFunc::Chebyshev;
2800 } else {
2801 throw(AipsError("invalid function type."));
2802 }
2803 ss.clear(); ss.str("");
2804
2805 ss << res[2];
2806 ss >> fpar0;
2807 fpar = splitToIntList(fpar0, ',');
2808 ss.clear(); ss.str("");
2809
2810 ss << res[3];
2811 ss >> masklist0;
2812 mask = getMaskFromMaskList(nchan(getIF(irow)), splitToIntList(masklist0, ','));
2813 ss.clear(); ss.str("");
2814
2815 ss << res[4];
2816 ss >> thresClip;
2817 ss.clear(); ss.str("");
2818
2819 ss << res[5];
2820 ss >> nIterClip;
2821 ss.clear(); ss.str("");
2822
2823 ss << res[6];
2824 ss >> uself0;
2825 if (uself0 == "true") {
2826 useLineFinder = true;
2827 } else {
2828 useLineFinder = false;
2829 }
2830 ss.clear(); ss.str("");
2831
2832 if (useLineFinder) {
2833 ss << res[7];
2834 ss >> thresLF;
2835 ss.clear(); ss.str("");
2836
2837 ss << res[8];
2838 ss >> edge0;
2839 edgeLF = splitToIntList(edge0, ',');
2840 ss.clear(); ss.str("");
2841
2842 ss << res[9];
2843 ss >> avgLF;
2844 ss.clear(); ss.str("");
2845 }
2846
2847}
2848
2849std::vector<int> Scantable::splitToIntList(const std::string& s, const char delim)
2850{
2851 istringstream iss(s);
2852 string tmp;
2853 int tmpi;
2854 std::vector<int> res;
2855 stringstream ss;
2856 while (getline(iss, tmp, delim)) {
2857 ss << tmp;
2858 ss >> tmpi;
2859 res.push_back(tmpi);
2860 ss.clear(); ss.str("");
2861 }
2862
2863 return res;
2864}
2865
2866std::vector<string> Scantable::splitToStringList(const std::string& s, const char delim)
2867{
2868 istringstream iss(s);
2869 std::string tmp;
2870 std::vector<string> res;
2871 while (getline(iss, tmp, delim)) {
2872 res.push_back(tmp);
2873 }
2874
2875 return res;
2876}
2877
2878std::vector<bool> Scantable::getMaskFromMaskList(const int nchan, const std::vector<int>& masklist)
2879{
2880 if (masklist.size() % 2 != 0) {
2881 throw(AipsError("masklist must have even number of elements."));
2882 }
2883
2884 std::vector<bool> res(nchan);
2885
2886 for (int i = 0; i < nchan; ++i) {
2887 res[i] = false;
2888 }
2889 for (uInt j = 0; j < masklist.size(); j += 2) {
2890 for (int i = masklist[j]; i <= masklist[j+1]; ++i) {
2891 res[i] = true;
2892 }
2893 }
2894
2895 return res;
2896}
2897
2898Vector<uInt> Scantable::getMaskListFromMask(const std::vector<bool>& mask)
2899{
2900 std::vector<int> masklist;
2901 masklist.clear();
2902
2903 for (uInt i = 0; i < mask.size(); ++i) {
2904 if (mask[i]) {
2905 if ((i == 0)||(i == mask.size()-1)) {
2906 masklist.push_back(i);
2907 } else {
2908 if ((mask[i])&&(!mask[i-1])) {
2909 masklist.push_back(i);
2910 }
2911 if ((mask[i])&&(!mask[i+1])) {
2912 masklist.push_back(i);
2913 }
2914 }
2915 }
2916 }
2917
2918 Vector<uInt> res(masklist.size());
2919 for (uInt i = 0; i < masklist.size(); ++i) {
2920 res[i] = (uInt)masklist[i];
2921 }
2922
2923 return res;
2924}
2925
2926void Scantable::initialiseBaselining(const std::string& blfile,
2927 ofstream& ofs,
2928 const bool outLogger,
2929 bool& outTextFile,
2930 bool& csvFormat,
2931 String& coordInfo,
2932 bool& hasSameNchan,
2933 const std::string& progressInfo,
2934 bool& showProgress,
2935 int& minNRow,
2936 Vector<Double>& timeSecCol)
2937{
2938 csvFormat = false;
2939 outTextFile = false;
2940
2941 if (blfile != "") {
2942 csvFormat = (blfile.substr(0, 1) == "T");
2943 ofs.open(blfile.substr(1).c_str(), ios::out | ios::app);
2944 if (ofs) outTextFile = true;
2945 }
2946
2947 coordInfo = "";
2948 hasSameNchan = true;
2949
2950 if (outLogger || outTextFile) {
2951 coordInfo = getCoordInfo()[0];
2952 if (coordInfo == "") coordInfo = "channel";
2953 hasSameNchan = hasSameNchanOverIFs();
2954 }
2955
2956 parseProgressInfo(progressInfo, showProgress, minNRow);
2957
2958 ROScalarColumn<Double> tcol = ROScalarColumn<Double>(table_, "TIME");
2959 timeSecCol = tcol.getColumn();
2960}
2961
2962void Scantable::finaliseBaselining(const bool outBaselineTable,
2963 STBaselineTable* pbt,
2964 const string& bltable,
2965 const bool outTextFile,
2966 ofstream& ofs)
2967{
2968 if (outBaselineTable) {
2969 pbt->save(bltable);
2970 }
2971
2972 if (outTextFile) ofs.close();
2973}
2974
2975void Scantable::initLineFinder(const std::vector<int>& edge,
2976 const float threshold,
2977 const int chanAvgLimit,
2978 STLineFinder& lineFinder)
2979{
2980 if ((edge.size() > 2) && (edge.size() < getIFNos().size()*2)) {
2981 throw(AipsError("Length of edge element info is less than that of IFs"));
2982 }
2983
2984 lineFinder.setOptions(threshold, 3, chanAvgLimit);
2985}
2986
2987void Scantable::polyBaseline(const std::vector<bool>& mask, int order,
2988 float thresClip, int nIterClip,
2989 bool getResidual,
2990 const std::string& progressInfo,
2991 const bool outLogger, const std::string& blfile,
2992 const std::string& bltable)
2993{
2994 /****
2995 double TimeStart = mathutil::gettimeofday_sec();
2996 ****/
2997
2998 try {
2999 ofstream ofs;
3000 String coordInfo;
3001 bool hasSameNchan, outTextFile, csvFormat, showProgress;
3002 int minNRow;
3003 int nRow = nrow();
3004 std::vector<bool> chanMask, finalChanMask;
3005 float rms;
3006 bool outBaselineTable = (bltable != "");
3007 STBaselineTable bt = STBaselineTable(*this);
3008 Vector<Double> timeSecCol;
3009
3010 initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
3011 coordInfo, hasSameNchan,
3012 progressInfo, showProgress, minNRow,
3013 timeSecCol);
3014
3015 std::vector<int> nChanNos;
3016 std::vector<std::vector<std::vector<double> > > modelReservoir;
3017 modelReservoir = getPolynomialModelReservoir(order,
3018 &Scantable::getNormalPolynomial,
3019 nChanNos);
3020
3021 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
3022 std::vector<float> sp = getSpectrum(whichrow);
3023 chanMask = getCompositeChanMask(whichrow, mask);
3024
3025 std::vector<float> params;
3026 int nClipped = 0;
3027 std::vector<float> res = doLeastSquareFitting(sp, chanMask,
3028 modelReservoir[getIdxOfNchan(sp.size(), nChanNos)],
3029 params, rms, finalChanMask,
3030 nClipped, thresClip, nIterClip, getResidual);
3031
3032 if (outBaselineTable) {
3033 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3034 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3035 true, STBaselineFunc::Polynomial, order, std::vector<float>(),
3036 getMaskListFromMask(finalChanMask), params, rms, sp.size(),
3037 thresClip, nIterClip, 0.0, 0, std::vector<int>());
3038 } else {
3039 setSpectrum(res, whichrow);
3040 }
3041
3042 outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
3043 coordInfo, hasSameNchan, ofs, "polyBaseline()",
3044 params, nClipped);
3045 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
3046 }
3047
3048 finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
3049
3050 } catch (...) {
3051 throw;
3052 }
3053
3054 /****
3055 double TimeEnd = mathutil::gettimeofday_sec();
3056 double elapse1 = TimeEnd - TimeStart;
3057 std::cout << "poly-new : " << elapse1 << " (sec.)" << endl;
3058 ****/
3059}
3060
3061void Scantable::autoPolyBaseline(const std::vector<bool>& mask, int order,
3062 float thresClip, int nIterClip,
3063 const std::vector<int>& edge,
3064 float threshold, int chanAvgLimit,
3065 bool getResidual,
3066 const std::string& progressInfo,
3067 const bool outLogger, const std::string& blfile,
3068 const std::string& bltable)
3069{
3070 try {
3071 ofstream ofs;
3072 String coordInfo;
3073 bool hasSameNchan, outTextFile, csvFormat, showProgress;
3074 int minNRow;
3075 int nRow = nrow();
3076 std::vector<bool> chanMask, finalChanMask;
3077 float rms;
3078 bool outBaselineTable = (bltable != "");
3079 STBaselineTable bt = STBaselineTable(*this);
3080 Vector<Double> timeSecCol;
3081 STLineFinder lineFinder = STLineFinder();
3082
3083 initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
3084 coordInfo, hasSameNchan,
3085 progressInfo, showProgress, minNRow,
3086 timeSecCol);
3087
3088 initLineFinder(edge, threshold, chanAvgLimit, lineFinder);
3089
3090 std::vector<int> nChanNos;
3091 std::vector<std::vector<std::vector<double> > > modelReservoir;
3092 modelReservoir = getPolynomialModelReservoir(order,
3093 &Scantable::getNormalPolynomial,
3094 nChanNos);
3095
3096 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
3097 std::vector<float> sp = getSpectrum(whichrow);
3098 std::vector<int> currentEdge;
3099 chanMask = getCompositeChanMask(whichrow, mask, edge, currentEdge, lineFinder);
3100
3101 std::vector<float> params;
3102 int nClipped = 0;
3103 std::vector<float> res = doLeastSquareFitting(sp, chanMask,
3104 modelReservoir[getIdxOfNchan(sp.size(), nChanNos)],
3105 params, rms, finalChanMask,
3106 nClipped, thresClip, nIterClip, getResidual);
3107
3108 if (outBaselineTable) {
3109 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3110 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3111 true, STBaselineFunc::Polynomial, order, std::vector<float>(),
3112 getMaskListFromMask(finalChanMask), params, rms, sp.size(),
3113 thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
3114 } else {
3115 setSpectrum(res, whichrow);
3116 }
3117
3118 outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
3119 coordInfo, hasSameNchan, ofs, "autoPolyBaseline()",
3120 params, nClipped);
3121 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
3122 }
3123
3124 finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
3125
3126 } catch (...) {
3127 throw;
3128 }
3129}
3130
3131void Scantable::chebyshevBaseline(const std::vector<bool>& mask, int order,
3132 float thresClip, int nIterClip,
3133 bool getResidual,
3134 const std::string& progressInfo,
3135 const bool outLogger, const std::string& blfile,
3136 const std::string& bltable)
3137{
3138 /*
3139 double TimeStart = mathutil::gettimeofday_sec();
3140 */
3141
3142 try {
3143 ofstream ofs;
3144 String coordInfo;
3145 bool hasSameNchan, outTextFile, csvFormat, showProgress;
3146 int minNRow;
3147 int nRow = nrow();
3148 std::vector<bool> chanMask, finalChanMask;
3149 float rms;
3150 bool outBaselineTable = (bltable != "");
3151 STBaselineTable bt = STBaselineTable(*this);
3152 Vector<Double> timeSecCol;
3153
3154 initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
3155 coordInfo, hasSameNchan,
3156 progressInfo, showProgress, minNRow,
3157 timeSecCol);
3158
3159 std::vector<int> nChanNos;
3160 std::vector<std::vector<std::vector<double> > > modelReservoir;
3161 modelReservoir = getPolynomialModelReservoir(order,
3162 &Scantable::getChebyshevPolynomial,
3163 nChanNos);
3164
3165 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
3166 std::vector<float> sp = getSpectrum(whichrow);
3167 chanMask = getCompositeChanMask(whichrow, mask);
3168
3169 std::vector<float> params;
3170 int nClipped = 0;
3171 std::vector<float> res = doLeastSquareFitting(sp, chanMask,
3172 modelReservoir[getIdxOfNchan(sp.size(), nChanNos)],
3173 params, rms, finalChanMask,
3174 nClipped, thresClip, nIterClip, getResidual);
3175
3176 if (outBaselineTable) {
3177 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3178 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3179 true, STBaselineFunc::Chebyshev, order, std::vector<float>(),
3180 getMaskListFromMask(finalChanMask), params, rms, sp.size(),
3181 thresClip, nIterClip, 0.0, 0, std::vector<int>());
3182 } else {
3183 setSpectrum(res, whichrow);
3184 }
3185
3186 outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
3187 coordInfo, hasSameNchan, ofs, "chebyshevBaseline()",
3188 params, nClipped);
3189 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
3190 }
3191
3192 finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
3193
3194 } catch (...) {
3195 throw;
3196 }
3197
3198 /*
3199 double TimeEnd = mathutil::gettimeofday_sec();
3200 double elapse1 = TimeEnd - TimeStart;
3201 std::cout << "cheby : " << elapse1 << " (sec.)" << endl;
3202 */
3203}
3204
3205void Scantable::autoChebyshevBaseline(const std::vector<bool>& mask, int order,
3206 float thresClip, int nIterClip,
3207 const std::vector<int>& edge,
3208 float threshold, int chanAvgLimit,
3209 bool getResidual,
3210 const std::string& progressInfo,
3211 const bool outLogger, const std::string& blfile,
3212 const std::string& bltable)
3213{
3214 try {
3215 ofstream ofs;
3216 String coordInfo;
3217 bool hasSameNchan, outTextFile, csvFormat, showProgress;
3218 int minNRow;
3219 int nRow = nrow();
3220 std::vector<bool> chanMask, finalChanMask;
3221 float rms;
3222 bool outBaselineTable = (bltable != "");
3223 STBaselineTable bt = STBaselineTable(*this);
3224 Vector<Double> timeSecCol;
3225 STLineFinder lineFinder = STLineFinder();
3226
3227 initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
3228 coordInfo, hasSameNchan,
3229 progressInfo, showProgress, minNRow,
3230 timeSecCol);
3231
3232 initLineFinder(edge, threshold, chanAvgLimit, lineFinder);
3233
3234 std::vector<int> nChanNos;
3235 std::vector<std::vector<std::vector<double> > > modelReservoir;
3236 modelReservoir = getPolynomialModelReservoir(order,
3237 &Scantable::getChebyshevPolynomial,
3238 nChanNos);
3239
3240 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
3241 std::vector<float> sp = getSpectrum(whichrow);
3242 std::vector<int> currentEdge;
3243 chanMask = getCompositeChanMask(whichrow, mask, edge, currentEdge, lineFinder);
3244
3245 std::vector<float> params;
3246 int nClipped = 0;
3247 std::vector<float> res = doLeastSquareFitting(sp, chanMask,
3248 modelReservoir[getIdxOfNchan(sp.size(), nChanNos)],
3249 params, rms, finalChanMask,
3250 nClipped, thresClip, nIterClip, getResidual);
3251
3252 if (outBaselineTable) {
3253 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3254 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3255 true, STBaselineFunc::Chebyshev, order, std::vector<float>(),
3256 getMaskListFromMask(finalChanMask), params, rms, sp.size(),
3257 thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
3258 } else {
3259 setSpectrum(res, whichrow);
3260 }
3261
3262 outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
3263 coordInfo, hasSameNchan, ofs, "autoChebyshevBaseline()",
3264 params, nClipped);
3265 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
3266 }
3267
3268 finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
3269
3270 } catch (...) {
3271 throw;
3272 }
3273}
3274
3275double Scantable::calculateModelSelectionCriteria(const std::string& valname,
3276 const std::string& blfunc,
3277 int order,
3278 const std::vector<bool>& inMask,
3279 int whichrow,
3280 bool useLineFinder,
3281 const std::vector<int>& edge,
3282 float threshold,
3283 int chanAvgLimit)
3284{
3285 std::vector<float> sp = getSpectrum(whichrow);
3286 std::vector<bool> chanMask;
3287 chanMask.clear();
3288
3289 if (useLineFinder) {
3290 STLineFinder lineFinder = STLineFinder();
3291 initLineFinder(edge, threshold, chanAvgLimit, lineFinder);
3292 std::vector<int> currentEdge;
3293 chanMask = getCompositeChanMask(whichrow, inMask, edge, currentEdge, lineFinder);
3294 } else {
3295 chanMask = getCompositeChanMask(whichrow, inMask);
3296 }
3297
3298 return doCalculateModelSelectionCriteria(valname, sp, chanMask, blfunc, order);
3299}
3300
3301double Scantable::doCalculateModelSelectionCriteria(const std::string& valname, const std::vector<float>& spec, const std::vector<bool>& mask, const std::string& blfunc, int order)
3302{
3303 int nparam;
3304 std::vector<float> params;
3305 std::vector<bool> finalChanMask;
3306 float rms;
3307 int nClipped = 0;
3308 std::vector<float> res;
3309 if (blfunc == "poly") {
3310 nparam = order + 1;
3311 res = doPolynomialFitting(spec, mask, order, params, rms, finalChanMask, nClipped);
3312 } else if (blfunc == "chebyshev") {
3313 nparam = order + 1;
3314 res = doChebyshevFitting(spec, mask, order, params, rms, finalChanMask, nClipped);
3315 } else if (blfunc == "cspline") {
3316 std::vector<int> pieceEdges;//(order+1); //order = npiece
3317 nparam = order + 3;
3318 res = doCubicSplineFitting(spec, mask, order, false, pieceEdges, params, rms, finalChanMask, nClipped);
3319 } else if (blfunc == "sinusoid") {
3320 std::vector<int> nWaves;
3321 nWaves.clear();
3322 for (int i = 0; i <= order; ++i) {
3323 nWaves.push_back(i);
3324 }
3325 nparam = 2*order + 1; // order = nwave
3326 res = doSinusoidFitting(spec, mask, nWaves, params, rms, finalChanMask, nClipped);
3327 } else {
3328 throw(AipsError("blfunc must be poly, chebyshev, cspline or sinusoid."));
3329 }
3330
3331 double msq = 0.0;
3332 int nusedchan = 0;
3333 int nChan = res.size();
3334 for (int i = 0; i < nChan; ++i) {
3335 if (mask[i]) {
3336 msq += (double)res[i]*(double)res[i];
3337 nusedchan++;
3338 }
3339 }
3340 if (nusedchan == 0) {
3341 throw(AipsError("all channels masked."));
3342 }
3343 msq /= (double)nusedchan;
3344
3345 nparam++; //add 1 for sigma of Gaussian distribution
3346 const double PI = 6.0 * asin(0.5); // PI (= 3.141592653...)
3347
3348 if (valname.find("aic") == 0) {
3349 // Original Akaike Information Criterion (AIC)
3350 double aic = nusedchan * (log(2.0 * PI * msq) + 1.0) + 2.0 * nparam;
3351
3352 // Corrected AIC by Sugiura(1978) (AICc)
3353 if (valname == "aicc") {
3354 if (nusedchan - nparam - 1 <= 0) {
3355 throw(AipsError("channel size is too small to calculate AICc."));
3356 }
3357 aic += 2.0*nparam*(nparam + 1)/(double)(nusedchan - nparam - 1);
3358 }
3359
3360 return aic;
3361
3362 } else if (valname == "bic") {
3363 // Bayesian Information Criterion (BIC)
3364 double bic = nusedchan * log(msq) + nparam * log((double)nusedchan);
3365 return bic;
3366
3367 } else if (valname == "gcv") {
3368 // Generalised Cross Validation
3369 double x = 1.0 - (double)nparam / (double)nusedchan;
3370 double gcv = msq / (x * x);
3371 return gcv;
3372
3373 } else {
3374 throw(AipsError("valname must be aic, aicc, bic or gcv."));
3375 }
3376}
3377
3378double Scantable::getNormalPolynomial(int n, double x) {
3379 if (n == 0) {
3380 return 1.0;
3381 } else if (n > 0) {
3382 double res = 1.0;
3383 for (int i = 0; i < n; ++i) {
3384 res *= x;
3385 }
3386 return res;
3387 } else {
3388 if (x == 0.0) {
3389 throw(AipsError("infinity result: x=0 given for negative power."));
3390 } else {
3391 return pow(x, (double)n);
3392 }
3393 }
3394}
3395
3396double Scantable::getChebyshevPolynomial(int n, double x) {
3397 if ((x < -1.0)||(x > 1.0)) {
3398 throw(AipsError("out of definition range (-1 <= x <= 1)."));
3399 } else if (x == 1.0) {
3400 return 1.0;
3401 } else if (x == 0.0) {
3402 double res;
3403 if (n%2 == 0) {
3404 if (n%4 == 0) {
3405 res = 1.0;
3406 } else {
3407 res = -1.0;
3408 }
3409 } else {
3410 res = 0.0;
3411 }
3412 return res;
3413 } else if (x == -1.0) {
3414 double res = (n%2 == 0 ? 1.0 : -1.0);
3415 return res;
3416 } else if (n < 0) {
3417 throw(AipsError("the order must be zero or positive."));
3418 } else if (n == 0) {
3419 return 1.0;
3420 } else if (n == 1) {
3421 return x;
3422 } else {
3423 double res[n+1];
3424 for (int i = 0; i < n+1; ++i) {
3425 double res0 = 0.0;
3426 if (i == 0) {
3427 res0 = 1.0;
3428 } else if (i == 1) {
3429 res0 = x;
3430 } else {
3431 res0 = 2.0 * x * res[i-1] - res[i-2];
3432 }
3433 res[i] = res0;
3434 }
3435 return res[n];
3436 }
3437}
3438
3439std::vector<float> Scantable::doPolynomialFitting(const std::vector<float>& data,
3440 const std::vector<bool>& mask,
3441 int order,
3442 std::vector<float>& params,
3443 float& rms,
3444 std::vector<bool>& finalmask,
3445 float clipth,
3446 int clipn)
3447{
3448 int nClipped = 0;
3449 return doPolynomialFitting(data, mask, order, params, rms, finalmask, nClipped, clipth, clipn);
3450}
3451
3452std::vector<float> Scantable::doPolynomialFitting(const std::vector<float>& data,
3453 const std::vector<bool>& mask,
3454 int order,
3455 std::vector<float>& params,
3456 float& rms,
3457 std::vector<bool>& finalMask,
3458 int& nClipped,
3459 float thresClip,
3460 int nIterClip,
3461 bool getResidual)
3462{
3463 return doLeastSquareFitting(data, mask,
3464 getPolynomialModel(order, data.size(), &Scantable::getNormalPolynomial),
3465 params, rms, finalMask,
3466 nClipped, thresClip, nIterClip,
3467 getResidual);
3468}
3469
3470std::vector<float> Scantable::doChebyshevFitting(const std::vector<float>& data,
3471 const std::vector<bool>& mask,
3472 int order,
3473 std::vector<float>& params,
3474 float& rms,
3475 std::vector<bool>& finalmask,
3476 float clipth,
3477 int clipn)
3478{
3479 int nClipped = 0;
3480 return doChebyshevFitting(data, mask, order, params, rms, finalmask, nClipped, clipth, clipn);
3481}
3482
3483std::vector<float> Scantable::doChebyshevFitting(const std::vector<float>& data,
3484 const std::vector<bool>& mask,
3485 int order,
3486 std::vector<float>& params,
3487 float& rms,
3488 std::vector<bool>& finalMask,
3489 int& nClipped,
3490 float thresClip,
3491 int nIterClip,
3492 bool getResidual)
3493{
3494 return doLeastSquareFitting(data, mask,
3495 getPolynomialModel(order, data.size(), &Scantable::getChebyshevPolynomial),
3496 params, rms, finalMask,
3497 nClipped, thresClip, nIterClip,
3498 getResidual);
3499}
3500
3501std::vector<std::vector<double> > Scantable::getPolynomialModel(int order, int nchan, double (Scantable::*pfunc)(int, double))
3502{
3503 // model : contains model values for computing the least-square matrix.
3504 // model.size() is nmodel and model[*].size() is nchan.
3505 // Each model element are as follows:
3506 //
3507 // (for normal polynomials)
3508 // model[0] = {1.0, 1.0, 1.0, ..., 1.0},
3509 // model[1] = {0.0, 1.0, 2.0, ..., (nchan-1)}
3510 // model[n-1] = ...,
3511 // model[n] = {0.0^n, 1.0^n, 2.0^n, ..., (nchan-1)^n}
3512 // where (0 <= n <= order)
3513 //
3514 // (for Chebyshev polynomials)
3515 // model[0] = {T0(-1), T0(2/(nchan-1)-1), T0(4/(nchan-1)-1), ..., T0(1)},
3516 // model[n-1] = ...,
3517 // model[n] = {Tn(-1), Tn(2/(nchan-1)-1), Tn(4/(nchan-1)-1), ..., Tn(1)}
3518 // where (0 <= n <= order),
3519
3520 int nmodel = order + 1;
3521 std::vector<std::vector<double> > model(nmodel, std::vector<double>(nchan));
3522
3523 double stretch, shift;
3524 if (pfunc == &Scantable::getChebyshevPolynomial) {
3525 stretch = 2.0/(double)(nchan - 1);
3526 shift = -1.0;
3527 } else {
3528 stretch = 1.0;
3529 shift = 0.0;
3530 }
3531
3532 for (int i = 0; i < nmodel; ++i) {
3533 for (int j = 0; j < nchan; ++j) {
3534 model[i][j] = (this->*pfunc)(i, stretch*(double)j + shift);
3535 }
3536 }
3537
3538 return model;
3539}
3540
3541std::vector<std::vector<std::vector<double> > > Scantable::getPolynomialModelReservoir(int order,
3542 double (Scantable::*pfunc)(int, double),
3543 std::vector<int>& nChanNos)
3544{
3545 std::vector<std::vector<std::vector<double> > > res;
3546 res.clear();
3547 nChanNos.clear();
3548
3549 std::vector<uint> ifNos = getIFNos();
3550 for (uint i = 0; i < ifNos.size(); ++i) {
3551 int currNchan = nchan(ifNos[i]);
3552 bool hasDifferentNchan = (i == 0);
3553 for (uint j = 0; j < i; ++j) {
3554 if (currNchan != nchan(ifNos[j])) {
3555 hasDifferentNchan = true;
3556 break;
3557 }
3558 }
3559 if (hasDifferentNchan) {
3560 res.push_back(getPolynomialModel(order, currNchan, pfunc));
3561 nChanNos.push_back(currNchan);
3562 }
3563 }
3564
3565 return res;
3566}
3567
3568std::vector<float> Scantable::doLeastSquareFitting(const std::vector<float>& data,
3569 const std::vector<bool>& mask,
3570 const std::vector<std::vector<double> >& model,
3571 std::vector<float>& params,
3572 float& rms,
3573 std::vector<bool>& finalMask,
3574 int& nClipped,
3575 float thresClip,
3576 int nIterClip,
3577 bool getResidual)
3578{
3579 int nDOF = model.size();
3580 int nChan = data.size();
3581
3582 if (nDOF == 0) {
3583 throw(AipsError("no model data given"));
3584 }
3585 if (nChan < 2) {
3586 throw(AipsError("data size is too few"));
3587 }
3588 if (nChan != (int)mask.size()) {
3589 throw(AipsError("data and mask sizes are not identical"));
3590 }
3591 for (int i = 0; i < nDOF; ++i) {
3592 if (nChan != (int)model[i].size()) {
3593 throw(AipsError("data and model sizes are not identical"));
3594 }
3595 }
3596
3597 params.clear();
3598 params.resize(nDOF);
3599
3600 finalMask.clear();
3601 finalMask.resize(nChan);
3602
3603 std::vector<int> maskArray(nChan);
3604 int j = 0;
3605 for (int i = 0; i < nChan; ++i) {
3606 maskArray[i] = mask[i] ? 1 : 0;
3607 if (isnan(data[i])) maskArray[i] = 0;
3608 if (isinf(data[i])) maskArray[i] = 0;
3609
3610 finalMask[i] = (maskArray[i] == 1);
3611 if (finalMask[i]) {
3612 j++;
3613 }
3614
3615 /*
3616 maskArray[i] = mask[i] ? 1 : 0;
3617 if (mask[i]) {
3618 j++;
3619 }
3620 finalMask[i] = mask[i];
3621 */
3622 }
3623
3624 int initNData = j;
3625 int nData = initNData;
3626
3627 std::vector<double> z1(nChan), r1(nChan), residual(nChan);
3628 for (int i = 0; i < nChan; ++i) {
3629 z1[i] = (double)data[i];
3630 r1[i] = 0.0;
3631 residual[i] = 0.0;
3632 }
3633
3634 for (int nClip = 0; nClip < nIterClip+1; ++nClip) {
3635 // xMatrix : horizontal concatenation of
3636 // the least-sq. matrix (left) and an
3637 // identity matrix (right).
3638 // the right part is used to calculate the inverse matrix of the left part.
3639 double xMatrix[nDOF][2*nDOF];
3640 double zMatrix[nDOF];
3641 for (int i = 0; i < nDOF; ++i) {
3642 for (int j = 0; j < 2*nDOF; ++j) {
3643 xMatrix[i][j] = 0.0;
3644 }
3645 xMatrix[i][nDOF+i] = 1.0;
3646 zMatrix[i] = 0.0;
3647 }
3648
3649 int nUseData = 0;
3650 for (int k = 0; k < nChan; ++k) {
3651 if (maskArray[k] == 0) continue;
3652
3653 for (int i = 0; i < nDOF; ++i) {
3654 for (int j = i; j < nDOF; ++j) {
3655 xMatrix[i][j] += model[i][k] * model[j][k];
3656 }
3657 zMatrix[i] += z1[k] * model[i][k];
3658 }
3659
3660 nUseData++;
3661 }
3662
3663 if (nUseData < 1) {
3664 throw(AipsError("all channels clipped or masked. can't execute fitting anymore."));
3665 }
3666
3667 for (int i = 0; i < nDOF; ++i) {
3668 for (int j = 0; j < i; ++j) {
3669 xMatrix[i][j] = xMatrix[j][i];
3670 }
3671 }
3672
3673 //compute inverse matrix of the left half of xMatrix
3674 std::vector<double> invDiag(nDOF);
3675 for (int i = 0; i < nDOF; ++i) {
3676 invDiag[i] = 1.0 / xMatrix[i][i];
3677 for (int j = 0; j < nDOF; ++j) {
3678 xMatrix[i][j] *= invDiag[i];
3679 }
3680 }
3681
3682 for (int k = 0; k < nDOF; ++k) {
3683 for (int i = 0; i < nDOF; ++i) {
3684 if (i != k) {
3685 double factor1 = xMatrix[k][k];
3686 double invfactor1 = 1.0 / factor1;
3687 double factor2 = xMatrix[i][k];
3688 for (int j = k; j < 2*nDOF; ++j) {
3689 xMatrix[i][j] *= factor1;
3690 xMatrix[i][j] -= xMatrix[k][j]*factor2;
3691 xMatrix[i][j] *= invfactor1;
3692 }
3693 }
3694 }
3695 double invXDiag = 1.0 / xMatrix[k][k];
3696 for (int j = k; j < 2*nDOF; ++j) {
3697 xMatrix[k][j] *= invXDiag;
3698 }
3699 }
3700
3701 for (int i = 0; i < nDOF; ++i) {
3702 for (int j = 0; j < nDOF; ++j) {
3703 xMatrix[i][nDOF+j] *= invDiag[j];
3704 }
3705 }
3706 //compute a vector y in which coefficients of the best-fit
3707 //model functions are stored.
3708 //in case of polynomials, y consists of (a0,a1,a2,...)
3709 //where ai is the coefficient of the term x^i.
3710 //in case of sinusoids, y consists of (a0,s1,c1,s2,c2,...)
3711 //where a0 is constant term and s* and c* are of sine
3712 //and cosine functions, respectively.
3713 std::vector<double> y(nDOF);
3714 for (int i = 0; i < nDOF; ++i) {
3715 y[i] = 0.0;
3716 for (int j = 0; j < nDOF; ++j) {
3717 y[i] += xMatrix[i][nDOF+j]*zMatrix[j];
3718 }
3719 params[i] = (float)y[i];
3720 }
3721
3722 for (int i = 0; i < nChan; ++i) {
3723 r1[i] = y[0];
3724 for (int j = 1; j < nDOF; ++j) {
3725 r1[i] += y[j]*model[j][i];
3726 }
3727 residual[i] = z1[i] - r1[i];
3728 }
3729
3730 double stdDev = 0.0;
3731 for (int i = 0; i < nChan; ++i) {
3732 if (maskArray[i] == 0) continue;
3733 stdDev += residual[i]*residual[i];
3734 }
3735 stdDev = sqrt(stdDev/(double)nData);
3736 rms = (float)stdDev;
3737
3738 if ((nClip == nIterClip) || (thresClip <= 0.0)) {
3739 break;
3740 } else {
3741
3742 double thres = stdDev * thresClip;
3743 int newNData = 0;
3744 for (int i = 0; i < nChan; ++i) {
3745 if (abs(residual[i]) >= thres) {
3746 maskArray[i] = 0;
3747 finalMask[i] = false;
3748 }
3749 if (maskArray[i] > 0) {
3750 newNData++;
3751 }
3752 }
3753 if (newNData == nData) {
3754 break; //no more flag to add. stop iteration.
3755 } else {
3756 nData = newNData;
3757 }
3758
3759 }
3760 }
3761
3762 nClipped = initNData - nData;
3763
3764 std::vector<float> result(nChan);
3765 if (getResidual) {
3766 for (int i = 0; i < nChan; ++i) {
3767 result[i] = (float)residual[i];
3768 }
3769 } else {
3770 for (int i = 0; i < nChan; ++i) {
3771 result[i] = (float)r1[i];
3772 }
3773 }
3774
3775 return result;
3776} //xMatrix
3777
3778void Scantable::cubicSplineBaseline(const std::vector<bool>& mask, int nPiece,
3779 float thresClip, int nIterClip,
3780 bool getResidual,
3781 const std::string& progressInfo,
3782 const bool outLogger, const std::string& blfile,
3783 const std::string& bltable)
3784{
3785 /****
3786 double TimeStart = mathutil::gettimeofday_sec();
3787 ****/
3788
3789 try {
3790 ofstream ofs;
3791 String coordInfo;
3792 bool hasSameNchan, outTextFile, csvFormat, showProgress;
3793 int minNRow;
3794 int nRow = nrow();
3795 std::vector<bool> chanMask, finalChanMask;
3796 float rms;
3797 bool outBaselineTable = (bltable != "");
3798 STBaselineTable bt = STBaselineTable(*this);
3799 Vector<Double> timeSecCol;
3800
3801 initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
3802 coordInfo, hasSameNchan,
3803 progressInfo, showProgress, minNRow,
3804 timeSecCol);
3805
3806 std::vector<int> nChanNos;
3807 std::vector<std::vector<std::vector<double> > > modelReservoir;
3808 modelReservoir = getPolynomialModelReservoir(3,
3809 &Scantable::getNormalPolynomial,
3810 nChanNos);
3811
3812 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
3813 std::vector<float> sp = getSpectrum(whichrow);
3814 chanMask = getCompositeChanMask(whichrow, mask);
3815
3816 std::vector<int> pieceEdges;
3817 std::vector<float> params;
3818 int nClipped = 0;
3819 std::vector<float> res = doCubicSplineLeastSquareFitting(sp, chanMask,
3820 modelReservoir[getIdxOfNchan(sp.size(), nChanNos)],
3821 nPiece, false, pieceEdges, params, rms, finalChanMask,
3822 nClipped, thresClip, nIterClip, getResidual);
3823
3824 if (outBaselineTable) {
3825 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3826 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3827 true, STBaselineFunc::CSpline, pieceEdges, std::vector<float>(),
3828 getMaskListFromMask(finalChanMask), params, rms, sp.size(),
3829 thresClip, nIterClip, 0.0, 0, std::vector<int>());
3830 } else {
3831 setSpectrum(res, whichrow);
3832 }
3833
3834 outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
3835 coordInfo, hasSameNchan, ofs, "cubicSplineBaseline()",
3836 pieceEdges, params, nClipped);
3837 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
3838 }
3839
3840 finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
3841
3842 } catch (...) {
3843 throw;
3844 }
3845
3846 /****
3847 double TimeEnd = mathutil::gettimeofday_sec();
3848 double elapse1 = TimeEnd - TimeStart;
3849 std::cout << "cspline-new : " << elapse1 << " (sec.)" << endl;
3850 ****/
3851}
3852
3853void Scantable::autoCubicSplineBaseline(const std::vector<bool>& mask, int nPiece,
3854 float thresClip, int nIterClip,
3855 const std::vector<int>& edge,
3856 float threshold, int chanAvgLimit,
3857 bool getResidual,
3858 const std::string& progressInfo,
3859 const bool outLogger, const std::string& blfile,
3860 const std::string& bltable)
3861{
3862 try {
3863 ofstream ofs;
3864 String coordInfo;
3865 bool hasSameNchan, outTextFile, csvFormat, showProgress;
3866 int minNRow;
3867 int nRow = nrow();
3868 std::vector<bool> chanMask, finalChanMask;
3869 float rms;
3870 bool outBaselineTable = (bltable != "");
3871 STBaselineTable bt = STBaselineTable(*this);
3872 Vector<Double> timeSecCol;
3873 STLineFinder lineFinder = STLineFinder();
3874
3875 initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
3876 coordInfo, hasSameNchan,
3877 progressInfo, showProgress, minNRow,
3878 timeSecCol);
3879
3880 initLineFinder(edge, threshold, chanAvgLimit, lineFinder);
3881
3882 std::vector<int> nChanNos;
3883 std::vector<std::vector<std::vector<double> > > modelReservoir;
3884 modelReservoir = getPolynomialModelReservoir(3,
3885 &Scantable::getNormalPolynomial,
3886 nChanNos);
3887
3888 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
3889 std::vector<float> sp = getSpectrum(whichrow);
3890 std::vector<int> currentEdge;
3891 chanMask = getCompositeChanMask(whichrow, mask, edge, currentEdge, lineFinder);
3892
3893 std::vector<int> pieceEdges;
3894 std::vector<float> params;
3895 int nClipped = 0;
3896 std::vector<float> res = doCubicSplineLeastSquareFitting(sp, chanMask,
3897 modelReservoir[getIdxOfNchan(sp.size(), nChanNos)],
3898 nPiece, false, pieceEdges, params, rms, finalChanMask,
3899 nClipped, thresClip, nIterClip, getResidual);
3900
3901 if (outBaselineTable) {
3902 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
3903 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
3904 true, STBaselineFunc::CSpline, pieceEdges, std::vector<float>(),
3905 getMaskListFromMask(finalChanMask), params, rms, sp.size(),
3906 thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
3907 } else {
3908 setSpectrum(res, whichrow);
3909 }
3910
3911 outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
3912 coordInfo, hasSameNchan, ofs, "autoCubicSplineBaseline()",
3913 pieceEdges, params, nClipped);
3914 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
3915 }
3916
3917 finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
3918
3919 } catch (...) {
3920 throw;
3921 }
3922}
3923
3924std::vector<float> Scantable::doCubicSplineFitting(const std::vector<float>& data,
3925 const std::vector<bool>& mask,
3926 std::vector<int>& idxEdge,
3927 std::vector<float>& params,
3928 float& rms,
3929 std::vector<bool>& finalmask,
3930 float clipth,
3931 int clipn)
3932{
3933 int nClipped = 0;
3934 return doCubicSplineFitting(data, mask, idxEdge.size()-1, true, idxEdge, params, rms, finalmask, nClipped, clipth, clipn);
3935}
3936
3937std::vector<float> Scantable::doCubicSplineFitting(const std::vector<float>& data,
3938 const std::vector<bool>& mask,
3939 int nPiece,
3940 std::vector<int>& idxEdge,
3941 std::vector<float>& params,
3942 float& rms,
3943 std::vector<bool>& finalmask,
3944 float clipth,
3945 int clipn)
3946{
3947 int nClipped = 0;
3948 return doCubicSplineFitting(data, mask, nPiece, false, idxEdge, params, rms, finalmask, nClipped, clipth, clipn);
3949}
3950
3951std::vector<float> Scantable::doCubicSplineFitting(const std::vector<float>& data,
3952 const std::vector<bool>& mask,
3953 int nPiece,
3954 bool useGivenPieceBoundary,
3955 std::vector<int>& idxEdge,
3956 std::vector<float>& params,
3957 float& rms,
3958 std::vector<bool>& finalMask,
3959 int& nClipped,
3960 float thresClip,
3961 int nIterClip,
3962 bool getResidual)
3963{
3964 return doCubicSplineLeastSquareFitting(data, mask,
3965 getPolynomialModel(3, data.size(), &Scantable::getNormalPolynomial),
3966 nPiece, useGivenPieceBoundary, idxEdge,
3967 params, rms, finalMask,
3968 nClipped, thresClip, nIterClip,
3969 getResidual);
3970}
3971
3972std::vector<float> Scantable::doCubicSplineLeastSquareFitting(const std::vector<float>& data,
3973 const std::vector<bool>& mask,
3974 const std::vector<std::vector<double> >& model,
3975 int nPiece,
3976 bool useGivenPieceBoundary,
3977 std::vector<int>& idxEdge,
3978 std::vector<float>& params,
3979 float& rms,
3980 std::vector<bool>& finalMask,
3981 int& nClipped,
3982 float thresClip,
3983 int nIterClip,
3984 bool getResidual)
3985{
3986 int nDOF = nPiece + 3; //number of independent parameters to solve, namely, 4+(nPiece-1).
3987 int nModel = model.size();
3988 int nChan = data.size();
3989
3990 if (nModel != 4) {
3991 throw(AipsError("model size must be 4."));
3992 }
3993 if (nPiece < 1) {
3994 throw(AipsError("number of the sections must be one or more"));
3995 }
3996 if (nChan < 2*nPiece) {
3997 throw(AipsError("data size is too few"));
3998 }
3999 if (nChan != (int)mask.size()) {
4000 throw(AipsError("data and mask sizes are not identical"));
4001 }
4002 for (int i = 0; i < nModel; ++i) {
4003 if (nChan != (int)model[i].size()) {
4004 throw(AipsError("data and model sizes are not identical"));
4005 }
4006 }
4007
4008 params.clear();
4009 params.resize(nPiece*nModel);
4010
4011 finalMask.clear();
4012 finalMask.resize(nChan);
4013
4014 std::vector<int> maskArray(nChan);
4015 std::vector<int> x(nChan);
4016 int j = 0;
4017 for (int i = 0; i < nChan; ++i) {
4018 maskArray[i] = mask[i] ? 1 : 0;
4019 if (isnan(data[i])) maskArray[i] = 0;
4020 if (isinf(data[i])) maskArray[i] = 0;
4021
4022 finalMask[i] = (maskArray[i] == 1);
4023 if (finalMask[i]) {
4024 x[j] = i;
4025 j++;
4026 }
4027
4028 /*
4029 maskArray[i] = mask[i] ? 1 : 0;
4030 if (mask[i]) {
4031 x[j] = i;
4032 j++;
4033 }
4034 finalMask[i] = mask[i];
4035 */
4036 }
4037
4038 int initNData = j;
4039 int nData = initNData;
4040
4041 if (initNData < nPiece) {
4042 throw(AipsError("too few non-flagged channels"));
4043 }
4044
4045 int nElement = (int)(floor(floor((double)(initNData/nPiece))+0.5));
4046 std::vector<double> invEdge(nPiece-1);
4047
4048 if (useGivenPieceBoundary) {
4049 if ((int)idxEdge.size() != nPiece+1) {
4050 throw(AipsError("pieceEdge.size() must be equal to nPiece+1."));
4051 }
4052 } else {
4053 idxEdge.clear();
4054 idxEdge.resize(nPiece+1);
4055 idxEdge[0] = x[0];
4056 }
4057 for (int i = 1; i < nPiece; ++i) {
4058 int valX = x[nElement*i];
4059 if (!useGivenPieceBoundary) {
4060 idxEdge[i] = valX;
4061 }
4062 invEdge[i-1] = 1.0/(double)valX;
4063 }
4064 if (!useGivenPieceBoundary) {
4065 idxEdge[nPiece] = x[initNData-1]+1;
4066 }
4067
4068 std::vector<double> z1(nChan), r1(nChan), residual(nChan);
4069 for (int i = 0; i < nChan; ++i) {
4070 z1[i] = (double)data[i];
4071 r1[i] = 0.0;
4072 residual[i] = 0.0;
4073 }
4074
4075 for (int nClip = 0; nClip < nIterClip+1; ++nClip) {
4076 // xMatrix : horizontal concatenation of
4077 // the least-sq. matrix (left) and an
4078 // identity matrix (right).
4079 // the right part is used to calculate the inverse matrix of the left part.
4080
4081 double xMatrix[nDOF][2*nDOF];
4082 double zMatrix[nDOF];
4083 for (int i = 0; i < nDOF; ++i) {
4084 for (int j = 0; j < 2*nDOF; ++j) {
4085 xMatrix[i][j] = 0.0;
4086 }
4087 xMatrix[i][nDOF+i] = 1.0;
4088 zMatrix[i] = 0.0;
4089 }
4090
4091 for (int n = 0; n < nPiece; ++n) {
4092 int nUseDataInPiece = 0;
4093 for (int k = idxEdge[n]; k < idxEdge[n+1]; ++k) {
4094
4095 if (maskArray[k] == 0) continue;
4096
4097 for (int i = 0; i < nModel; ++i) {
4098 for (int j = i; j < nModel; ++j) {
4099 xMatrix[i][j] += model[i][k] * model[j][k];
4100 }
4101 zMatrix[i] += z1[k] * model[i][k];
4102 }
4103
4104 for (int i = 0; i < n; ++i) {
4105 double q = 1.0 - model[1][k]*invEdge[i];
4106 q = q*q*q;
4107 for (int j = 0; j < nModel; ++j) {
4108 xMatrix[j][i+nModel] += q * model[j][k];
4109 }
4110 for (int j = 0; j < i; ++j) {
4111 double r = 1.0 - model[1][k]*invEdge[j];
4112 r = r*r*r;
4113 xMatrix[j+nModel][i+nModel] += r*q;
4114 }
4115 xMatrix[i+nModel][i+nModel] += q*q;
4116 zMatrix[i+nModel] += q*z1[k];
4117 }
4118
4119 nUseDataInPiece++;
4120 }
4121
4122 if (nUseDataInPiece < 1) {
4123 std::vector<string> suffixOfPieceNumber(4);
4124 suffixOfPieceNumber[0] = "th";
4125 suffixOfPieceNumber[1] = "st";
4126 suffixOfPieceNumber[2] = "nd";
4127 suffixOfPieceNumber[3] = "rd";
4128 int idxNoDataPiece = (n % 10 <= 3) ? n : 0;
4129 ostringstream oss;
4130 oss << "all channels clipped or masked in " << n << suffixOfPieceNumber[idxNoDataPiece];
4131 oss << " piece of the spectrum. can't execute fitting anymore.";
4132 throw(AipsError(String(oss)));
4133 }
4134 }
4135
4136 for (int i = 0; i < nDOF; ++i) {
4137 for (int j = 0; j < i; ++j) {
4138 xMatrix[i][j] = xMatrix[j][i];
4139 }
4140 }
4141
4142 std::vector<double> invDiag(nDOF);
4143 for (int i = 0; i < nDOF; ++i) {
4144 invDiag[i] = 1.0 / xMatrix[i][i];
4145 for (int j = 0; j < nDOF; ++j) {
4146 xMatrix[i][j] *= invDiag[i];
4147 }
4148 }
4149
4150 for (int k = 0; k < nDOF; ++k) {
4151 for (int i = 0; i < nDOF; ++i) {
4152 if (i != k) {
4153 double factor1 = xMatrix[k][k];
4154 double invfactor1 = 1.0 / factor1;
4155 double factor2 = xMatrix[i][k];
4156 for (int j = k; j < 2*nDOF; ++j) {
4157 xMatrix[i][j] *= factor1;
4158 xMatrix[i][j] -= xMatrix[k][j]*factor2;
4159 xMatrix[i][j] *= invfactor1;
4160 }
4161 }
4162 }
4163 double invXDiag = 1.0 / xMatrix[k][k];
4164 for (int j = k; j < 2*nDOF; ++j) {
4165 xMatrix[k][j] *= invXDiag;
4166 }
4167 }
4168
4169 for (int i = 0; i < nDOF; ++i) {
4170 for (int j = 0; j < nDOF; ++j) {
4171 xMatrix[i][nDOF+j] *= invDiag[j];
4172 }
4173 }
4174
4175 //compute a vector y which consists of the coefficients of the best-fit spline curves
4176 //(a0,a1,a2,a3(,b3,c3,...)), namely, the ones for the leftmost piece and the ones of
4177 //cubic terms for the other pieces (in case nPiece>1).
4178 std::vector<double> y(nDOF);
4179 for (int i = 0; i < nDOF; ++i) {
4180 y[i] = 0.0;
4181 for (int j = 0; j < nDOF; ++j) {
4182 y[i] += xMatrix[i][nDOF+j]*zMatrix[j];
4183 }
4184 }
4185
4186 std::vector<double> a(nModel);
4187 for (int i = 0; i < nModel; ++i) {
4188 a[i] = y[i];
4189 }
4190
4191 int j = 0;
4192 for (int n = 0; n < nPiece; ++n) {
4193 for (int i = idxEdge[n]; i < idxEdge[n+1]; ++i) {
4194 r1[i] = 0.0;
4195 for (int j = 0; j < nModel; ++j) {
4196 r1[i] += a[j] * model[j][i];
4197 }
4198 }
4199 for (int i = 0; i < nModel; ++i) {
4200 params[j+i] = a[i];
4201 }
4202 j += nModel;
4203
4204 if (n == nPiece-1) break;
4205
4206 double d = y[n+nModel];
4207 double iE = invEdge[n];
4208 a[0] += d;
4209 a[1] -= 3.0 * d * iE;
4210 a[2] += 3.0 * d * iE * iE;
4211 a[3] -= d * iE * iE * iE;
4212 }
4213
4214 //subtract constant value for masked regions at the edge of spectrum
4215 if (idxEdge[0] > 0) {
4216 int n = idxEdge[0];
4217 for (int i = 0; i < idxEdge[0]; ++i) {
4218 //--cubic extrapolate--
4219 //r1[i] = params[0] + params[1]*x1[i] + params[2]*x2[i] + params[3]*x3[i];
4220 //--linear extrapolate--
4221 //r1[i] = (r1[n+1] - r1[n])/(x1[n+1] - x1[n])*(x1[i] - x1[n]) + r1[n];
4222 //--constant--
4223 r1[i] = r1[n];
4224 }
4225 }
4226
4227 if (idxEdge[nPiece] < nChan) {
4228 int n = idxEdge[nPiece]-1;
4229 for (int i = idxEdge[nPiece]; i < nChan; ++i) {
4230 //--cubic extrapolate--
4231 //int m = 4*(nPiece-1);
4232 //r1[i] = params[m] + params[m+1]*x1[i] + params[m+2]*x2[i] + params[m+3]*x3[i];
4233 //--linear extrapolate--
4234 //r1[i] = (r1[n-1] - r1[n])/(x1[n-1] - x1[n])*(x1[i] - x1[n]) + r1[n];
4235 //--constant--
4236 r1[i] = r1[n];
4237 }
4238 }
4239
4240 for (int i = 0; i < nChan; ++i) {
4241 residual[i] = z1[i] - r1[i];
4242 }
4243
4244 double stdDev = 0.0;
4245 for (int i = 0; i < nChan; ++i) {
4246 if (maskArray[i] == 0) continue;
4247 stdDev += residual[i]*residual[i];
4248 }
4249 stdDev = sqrt(stdDev/(double)nData);
4250 rms = (float)stdDev;
4251
4252 if ((nClip == nIterClip) || (thresClip <= 0.0)) {
4253 break;
4254 } else {
4255
4256 double thres = stdDev * thresClip;
4257 int newNData = 0;
4258 for (int i = 0; i < nChan; ++i) {
4259 if (abs(residual[i]) >= thres) {
4260 maskArray[i] = 0;
4261 finalMask[i] = false;
4262 }
4263 if (maskArray[i] > 0) {
4264 newNData++;
4265 }
4266 }
4267 if (newNData == nData) {
4268 break; //no more flag to add. iteration stops.
4269 } else {
4270 nData = newNData;
4271 }
4272
4273 }
4274 }
4275
4276 nClipped = initNData - nData;
4277
4278 std::vector<float> result(nChan);
4279 if (getResidual) {
4280 for (int i = 0; i < nChan; ++i) {
4281 result[i] = (float)residual[i];
4282 }
4283 } else {
4284 for (int i = 0; i < nChan; ++i) {
4285 result[i] = (float)r1[i];
4286 }
4287 }
4288
4289 return result;
4290}
4291
4292std::vector<int> Scantable::selectWaveNumbers(const std::vector<int>& addNWaves,
4293 const std::vector<int>& rejectNWaves)
4294{
4295 std::vector<bool> chanMask;
4296 std::string fftMethod;
4297 std::string fftThresh;
4298
4299 return selectWaveNumbers(0, chanMask, false, fftMethod, fftThresh, addNWaves, rejectNWaves);
4300}
4301
4302std::vector<int> Scantable::selectWaveNumbers(const int whichrow,
4303 const std::vector<bool>& chanMask,
4304 const bool applyFFT,
4305 const std::string& fftMethod,
4306 const std::string& fftThresh,
4307 const std::vector<int>& addNWaves,
4308 const std::vector<int>& rejectNWaves)
4309{
4310 std::vector<int> nWaves;
4311 nWaves.clear();
4312
4313 if (applyFFT) {
4314 string fftThAttr;
4315 float fftThSigma;
4316 int fftThTop;
4317 parseFFTThresholdInfo(fftThresh, fftThAttr, fftThSigma, fftThTop);
4318 doSelectWaveNumbers(whichrow, chanMask, fftMethod, fftThSigma, fftThTop, fftThAttr, nWaves);
4319 }
4320
4321 addAuxWaveNumbers(whichrow, addNWaves, rejectNWaves, nWaves);
4322
4323 return nWaves;
4324}
4325
4326int Scantable::getIdxOfNchan(const int nChan, const std::vector<int>& nChanNos)
4327{
4328 int idx = -1;
4329 for (uint i = 0; i < nChanNos.size(); ++i) {
4330 if (nChan == nChanNos[i]) {
4331 idx = i;
4332 break;
4333 }
4334 }
4335
4336 if (idx < 0) {
4337 throw(AipsError("nChan not found in nChhanNos."));
4338 }
4339
4340 return idx;
4341}
4342
4343void Scantable::parseFFTInfo(const std::string& fftInfo, bool& applyFFT, std::string& fftMethod, std::string& fftThresh)
4344{
4345 istringstream iss(fftInfo);
4346 std::string tmp;
4347 std::vector<string> res;
4348 while (getline(iss, tmp, ',')) {
4349 res.push_back(tmp);
4350 }
4351 if (res.size() < 3) {
4352 throw(AipsError("wrong value in 'fftinfo' parameter")) ;
4353 }
4354 applyFFT = (res[0] == "true");
4355 fftMethod = res[1];
4356 fftThresh = res[2];
4357}
4358
4359void Scantable::parseFFTThresholdInfo(const std::string& fftThresh, std::string& fftThAttr, float& fftThSigma, int& fftThTop)
4360{
4361 uInt idxSigma = fftThresh.find("sigma");
4362 uInt idxTop = fftThresh.find("top");
4363
4364 if (idxSigma == fftThresh.size() - 5) {
4365 std::istringstream is(fftThresh.substr(0, fftThresh.size() - 5));
4366 is >> fftThSigma;
4367 fftThAttr = "sigma";
4368 } else if (idxTop == 0) {
4369 std::istringstream is(fftThresh.substr(3));
4370 is >> fftThTop;
4371 fftThAttr = "top";
4372 } else {
4373 bool isNumber = true;
4374 for (uInt i = 0; i < fftThresh.size()-1; ++i) {
4375 char ch = (fftThresh.substr(i, 1).c_str())[0];
4376 if (!(isdigit(ch) || (fftThresh.substr(i, 1) == "."))) {
4377 isNumber = false;
4378 break;
4379 }
4380 }
4381 if (isNumber) {
4382 std::istringstream is(fftThresh);
4383 is >> fftThSigma;
4384 fftThAttr = "sigma";
4385 } else {
4386 throw(AipsError("fftthresh has a wrong value"));
4387 }
4388 }
4389}
4390
4391void 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)
4392{
4393 std::vector<float> fspec;
4394 if (fftMethod == "fft") {
4395 fspec = execFFT(whichrow, chanMask, false, true);
4396 //} else if (fftMethod == "lsp") {
4397 // fspec = lombScarglePeriodogram(whichrow);
4398 }
4399
4400 if (fftThAttr == "sigma") {
4401 float mean = 0.0;
4402 float mean2 = 0.0;
4403 for (uInt i = 0; i < fspec.size(); ++i) {
4404 mean += fspec[i];
4405 mean2 += fspec[i]*fspec[i];
4406 }
4407 mean /= float(fspec.size());
4408 mean2 /= float(fspec.size());
4409 float thres = mean + fftThSigma * float(sqrt(mean2 - mean*mean));
4410
4411 for (uInt i = 0; i < fspec.size(); ++i) {
4412 if (fspec[i] >= thres) {
4413 nWaves.push_back(i);
4414 }
4415 }
4416
4417 } else if (fftThAttr == "top") {
4418 for (int i = 0; i < fftThTop; ++i) {
4419 float max = 0.0;
4420 int maxIdx = 0;
4421 for (uInt j = 0; j < fspec.size(); ++j) {
4422 if (fspec[j] > max) {
4423 max = fspec[j];
4424 maxIdx = j;
4425 }
4426 }
4427 nWaves.push_back(maxIdx);
4428 fspec[maxIdx] = 0.0;
4429 }
4430
4431 }
4432
4433 if (nWaves.size() > 1) {
4434 sort(nWaves.begin(), nWaves.end());
4435 }
4436}
4437
4438void Scantable::addAuxWaveNumbers(const int whichrow, const std::vector<int>& addNWaves, const std::vector<int>& rejectNWaves, std::vector<int>& nWaves)
4439{
4440 std::vector<int> tempAddNWaves, tempRejectNWaves;
4441 tempAddNWaves.clear();
4442 tempRejectNWaves.clear();
4443
4444 for (uInt i = 0; i < addNWaves.size(); ++i) {
4445 tempAddNWaves.push_back(addNWaves[i]);
4446 }
4447 if ((tempAddNWaves.size() == 2) && (tempAddNWaves[1] == -999)) {
4448 setWaveNumberListUptoNyquistFreq(whichrow, tempAddNWaves);
4449 }
4450
4451 for (uInt i = 0; i < rejectNWaves.size(); ++i) {
4452 tempRejectNWaves.push_back(rejectNWaves[i]);
4453 }
4454 if ((tempRejectNWaves.size() == 2) && (tempRejectNWaves[1] == -999)) {
4455 setWaveNumberListUptoNyquistFreq(whichrow, tempRejectNWaves);
4456 }
4457
4458 for (uInt i = 0; i < tempAddNWaves.size(); ++i) {
4459 bool found = false;
4460 for (uInt j = 0; j < nWaves.size(); ++j) {
4461 if (nWaves[j] == tempAddNWaves[i]) {
4462 found = true;
4463 break;
4464 }
4465 }
4466 if (!found) nWaves.push_back(tempAddNWaves[i]);
4467 }
4468
4469 for (uInt i = 0; i < tempRejectNWaves.size(); ++i) {
4470 for (std::vector<int>::iterator j = nWaves.begin(); j != nWaves.end(); ) {
4471 if (*j == tempRejectNWaves[i]) {
4472 j = nWaves.erase(j);
4473 } else {
4474 ++j;
4475 }
4476 }
4477 }
4478
4479 if (nWaves.size() > 1) {
4480 sort(nWaves.begin(), nWaves.end());
4481 unique(nWaves.begin(), nWaves.end());
4482 }
4483}
4484
4485void Scantable::setWaveNumberListUptoNyquistFreq(const int whichrow, std::vector<int>& nWaves)
4486{
4487 int val = nWaves[0];
4488 int nyquistFreq = nchan(getIF(whichrow))/2+1;
4489 nWaves.clear();
4490 if (val > nyquistFreq) { // for safety, at least nWaves contains a constant; CAS-3759
4491 nWaves.push_back(0);
4492 }
4493 while (val <= nyquistFreq) {
4494 nWaves.push_back(val);
4495 val++;
4496 }
4497}
4498
4499void Scantable::sinusoidBaseline(const std::vector<bool>& mask, const std::string& fftInfo,
4500 const std::vector<int>& addNWaves,
4501 const std::vector<int>& rejectNWaves,
4502 float thresClip, int nIterClip,
4503 bool getResidual,
4504 const std::string& progressInfo,
4505 const bool outLogger, const std::string& blfile,
4506 const std::string& bltable)
4507{
4508 /****
4509 double TimeStart = mathutil::gettimeofday_sec();
4510 ****/
4511
4512 try {
4513 ofstream ofs;
4514 String coordInfo;
4515 bool hasSameNchan, outTextFile, csvFormat, showProgress;
4516 int minNRow;
4517 int nRow = nrow();
4518 std::vector<bool> chanMask, finalChanMask;
4519 float rms;
4520 bool outBaselineTable = (bltable != "");
4521 STBaselineTable bt = STBaselineTable(*this);
4522 Vector<Double> timeSecCol;
4523
4524 initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
4525 coordInfo, hasSameNchan,
4526 progressInfo, showProgress, minNRow,
4527 timeSecCol);
4528
4529 bool applyFFT;
4530 std::string fftMethod, fftThresh;
4531 parseFFTInfo(fftInfo, applyFFT, fftMethod, fftThresh);
4532
4533 std::vector<int> nWaves;
4534 std::vector<int> nChanNos;
4535 std::vector<std::vector<std::vector<double> > > modelReservoir;
4536 if (!applyFFT) {
4537 nWaves = selectWaveNumbers(addNWaves, rejectNWaves);
4538 modelReservoir = getSinusoidModelReservoir(nWaves, nChanNos);
4539 }
4540
4541 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
4542 std::vector<float> sp = getSpectrum(whichrow);
4543 chanMask = getCompositeChanMask(whichrow, mask);
4544 std::vector<std::vector<double> > model;
4545 if (applyFFT) {
4546 nWaves = selectWaveNumbers(whichrow, chanMask, true, fftMethod, fftThresh,
4547 addNWaves, rejectNWaves);
4548 model = getSinusoidModel(nWaves, sp.size());
4549 } else {
4550 model = modelReservoir[getIdxOfNchan(sp.size(), nChanNos)];
4551 }
4552
4553 std::vector<float> params;
4554 int nClipped = 0;
4555 std::vector<float> res = doLeastSquareFitting(sp, chanMask, model,
4556 params, rms, finalChanMask,
4557 nClipped, thresClip, nIterClip, getResidual);
4558
4559 if (outBaselineTable) {
4560 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
4561 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
4562 true, STBaselineFunc::Sinusoid, nWaves, std::vector<float>(),
4563 getMaskListFromMask(finalChanMask), params, rms, sp.size(),
4564 thresClip, nIterClip, 0.0, 0, std::vector<int>());
4565 } else {
4566 setSpectrum(res, whichrow);
4567 }
4568
4569 outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
4570 coordInfo, hasSameNchan, ofs, "sinusoidBaseline()",
4571 params, nClipped);
4572 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
4573 }
4574
4575 finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
4576
4577 } catch (...) {
4578 throw;
4579 }
4580
4581 /****
4582 double TimeEnd = mathutil::gettimeofday_sec();
4583 double elapse1 = TimeEnd - TimeStart;
4584 std::cout << "sinusoid-old : " << elapse1 << " (sec.)" << endl;
4585 ****/
4586}
4587
4588void Scantable::autoSinusoidBaseline(const std::vector<bool>& mask, const std::string& fftInfo,
4589 const std::vector<int>& addNWaves,
4590 const std::vector<int>& rejectNWaves,
4591 float thresClip, int nIterClip,
4592 const std::vector<int>& edge,
4593 float threshold, int chanAvgLimit,
4594 bool getResidual,
4595 const std::string& progressInfo,
4596 const bool outLogger, const std::string& blfile,
4597 const std::string& bltable)
4598{
4599 try {
4600 ofstream ofs;
4601 String coordInfo;
4602 bool hasSameNchan, outTextFile, csvFormat, showProgress;
4603 int minNRow;
4604 int nRow = nrow();
4605 std::vector<bool> chanMask, finalChanMask;
4606 float rms;
4607 bool outBaselineTable = (bltable != "");
4608 STBaselineTable bt = STBaselineTable(*this);
4609 Vector<Double> timeSecCol;
4610 STLineFinder lineFinder = STLineFinder();
4611
4612 initialiseBaselining(blfile, ofs, outLogger, outTextFile, csvFormat,
4613 coordInfo, hasSameNchan,
4614 progressInfo, showProgress, minNRow,
4615 timeSecCol);
4616
4617 initLineFinder(edge, threshold, chanAvgLimit, lineFinder);
4618
4619 bool applyFFT;
4620 string fftMethod, fftThresh;
4621 parseFFTInfo(fftInfo, applyFFT, fftMethod, fftThresh);
4622
4623 std::vector<int> nWaves;
4624 std::vector<int> nChanNos;
4625 std::vector<std::vector<std::vector<double> > > modelReservoir;
4626 if (!applyFFT) {
4627 nWaves = selectWaveNumbers(addNWaves, rejectNWaves);
4628 modelReservoir = getSinusoidModelReservoir(nWaves, nChanNos);
4629 }
4630
4631 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
4632 std::vector<float> sp = getSpectrum(whichrow);
4633 std::vector<int> currentEdge;
4634 chanMask = getCompositeChanMask(whichrow, mask, edge, currentEdge, lineFinder);
4635 std::vector<std::vector<double> > model;
4636 if (applyFFT) {
4637 nWaves = selectWaveNumbers(whichrow, chanMask, true, fftMethod, fftThresh,
4638 addNWaves, rejectNWaves);
4639 model = getSinusoidModel(nWaves, sp.size());
4640 } else {
4641 model = modelReservoir[getIdxOfNchan(sp.size(), nChanNos)];
4642 }
4643
4644 std::vector<float> params;
4645 int nClipped = 0;
4646 std::vector<float> res = doLeastSquareFitting(sp, chanMask, model,
4647 params, rms, finalChanMask,
4648 nClipped, thresClip, nIterClip, getResidual);
4649
4650 if (outBaselineTable) {
4651 bt.appenddata(getScan(whichrow), getCycle(whichrow), getBeam(whichrow),
4652 getIF(whichrow), getPol(whichrow), 0, timeSecCol[whichrow],
4653 true, STBaselineFunc::Sinusoid, nWaves, std::vector<float>(),
4654 getMaskListFromMask(finalChanMask), params, rms, sp.size(),
4655 thresClip, nIterClip, threshold, chanAvgLimit, currentEdge);
4656 } else {
4657 setSpectrum(res, whichrow);
4658 }
4659
4660 outputFittingResult(outLogger, outTextFile, csvFormat, chanMask, whichrow,
4661 coordInfo, hasSameNchan, ofs, "autoSinusoidBaseline()",
4662 params, nClipped);
4663 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
4664 }
4665
4666 finaliseBaselining(outBaselineTable, &bt, bltable, outTextFile, ofs);
4667
4668 } catch (...) {
4669 throw;
4670 }
4671}
4672
4673std::vector<float> Scantable::doSinusoidFitting(const std::vector<float>& data,
4674 const std::vector<bool>& mask,
4675 const std::vector<int>& waveNumbers,
4676 std::vector<float>& params,
4677 float& rms,
4678 std::vector<bool>& finalmask,
4679 float clipth,
4680 int clipn)
4681{
4682 int nClipped = 0;
4683 return doSinusoidFitting(data, mask, waveNumbers, params, rms, finalmask, nClipped, clipth, clipn);
4684}
4685
4686std::vector<float> Scantable::doSinusoidFitting(const std::vector<float>& data,
4687 const std::vector<bool>& mask,
4688 const std::vector<int>& waveNumbers,
4689 std::vector<float>& params,
4690 float& rms,
4691 std::vector<bool>& finalMask,
4692 int& nClipped,
4693 float thresClip,
4694 int nIterClip,
4695 bool getResidual)
4696{
4697 return doLeastSquareFitting(data, mask,
4698 getSinusoidModel(waveNumbers, data.size()),
4699 params, rms, finalMask,
4700 nClipped, thresClip, nIterClip,
4701 getResidual);
4702}
4703
4704std::vector<std::vector<std::vector<double> > > Scantable::getSinusoidModelReservoir(const std::vector<int>& waveNumbers,
4705 std::vector<int>& nChanNos)
4706{
4707 std::vector<std::vector<std::vector<double> > > res;
4708 res.clear();
4709 nChanNos.clear();
4710
4711 std::vector<uint> ifNos = getIFNos();
4712 for (uint i = 0; i < ifNos.size(); ++i) {
4713 int currNchan = nchan(ifNos[i]);
4714 bool hasDifferentNchan = (i == 0);
4715 for (uint j = 0; j < i; ++j) {
4716 if (currNchan != nchan(ifNos[j])) {
4717 hasDifferentNchan = true;
4718 break;
4719 }
4720 }
4721 if (hasDifferentNchan) {
4722 res.push_back(getSinusoidModel(waveNumbers, currNchan));
4723 nChanNos.push_back(currNchan);
4724 }
4725 }
4726
4727 return res;
4728}
4729
4730std::vector<std::vector<double> > Scantable::getSinusoidModel(const std::vector<int>& waveNumbers, int nchan)
4731{
4732 // model : contains elemental values for computing the least-square matrix.
4733 // model.size() is nmodel and model[*].size() is nchan.
4734 // Each model element are as follows:
4735 // model[0] = {1.0, 1.0, 1.0, ..., 1.0},
4736 // model[2n-1] = {sin(nPI/L*x[0]), sin(nPI/L*x[1]), ..., sin(nPI/L*x[nchan])},
4737 // model[2n] = {cos(nPI/L*x[0]), cos(nPI/L*x[1]), ..., cos(nPI/L*x[nchan])},
4738 // where (1 <= n <= nMaxWavesInSW),
4739 // or,
4740 // model[2n-1] = {sin(wn[n]PI/L*x[0]), sin(wn[n]PI/L*x[1]), ..., sin(wn[n]PI/L*x[nchan])},
4741 // model[2n] = {cos(wn[n]PI/L*x[0]), cos(wn[n]PI/L*x[1]), ..., cos(wn[n]PI/L*x[nchan])},
4742 // where wn[n] denotes waveNumbers[n] (1 <= n <= waveNumbers.size()).
4743
4744 std::vector<int> nWaves; // sorted and uniqued array of wave numbers
4745 nWaves.reserve(waveNumbers.size());
4746 copy(waveNumbers.begin(), waveNumbers.end(), back_inserter(nWaves));
4747 sort(nWaves.begin(), nWaves.end());
4748 std::vector<int>::iterator end_it = unique(nWaves.begin(), nWaves.end());
4749 nWaves.erase(end_it, nWaves.end());
4750
4751 int minNWaves = nWaves[0];
4752 if (minNWaves < 0) {
4753 throw(AipsError("wave number must be positive or zero (i.e. constant)"));
4754 }
4755 bool hasConstantTerm = (minNWaves == 0);
4756 int nmodel = nWaves.size() * 2 - (hasConstantTerm ? 1 : 0); //number of parameters to solve.
4757
4758 std::vector<std::vector<double> > model(nmodel, std::vector<double>(nchan));
4759
4760 if (hasConstantTerm) {
4761 for (int j = 0; j < nchan; ++j) {
4762 model[0][j] = 1.0;
4763 }
4764 }
4765
4766 const double PI = 6.0 * asin(0.5); // PI (= 3.141592653...)
4767 double stretch0 = 2.0*PI/(double)(nchan-1);
4768
4769 for (uInt i = (hasConstantTerm ? 1 : 0); i < nWaves.size(); ++i) {
4770 int sidx = hasConstantTerm ? 2*i-1 : 2*i;
4771 int cidx = sidx + 1;
4772 double stretch = stretch0*(double)nWaves[i];
4773
4774 for (int j = 0; j < nchan; ++j) {
4775 model[sidx][j] = sin(stretch*(double)j);
4776 model[cidx][j] = cos(stretch*(double)j);
4777 }
4778 }
4779
4780 return model;
4781}
4782
4783std::vector<bool> Scantable::getCompositeChanMask(int whichrow,
4784 const std::vector<bool>& inMask)
4785{
4786 std::vector<bool> mask = getMask(whichrow);
4787 uInt maskSize = mask.size();
4788 if (inMask.size() != 0) {
4789 if (maskSize != inMask.size()) {
4790 throw(AipsError("mask sizes are not the same."));
4791 }
4792 for (uInt i = 0; i < maskSize; ++i) {
4793 mask[i] = mask[i] && inMask[i];
4794 }
4795 }
4796
4797 return mask;
4798}
4799
4800std::vector<bool> Scantable::getCompositeChanMask(int whichrow,
4801 const std::vector<bool>& inMask,
4802 const std::vector<int>& edge,
4803 std::vector<int>& currEdge,
4804 STLineFinder& lineFinder)
4805{
4806 std::vector<uint> ifNos = getIFNos();
4807 if ((edge.size() > 2) && (edge.size() < ifNos.size()*2)) {
4808 throw(AipsError("Length of edge element info is less than that of IFs"));
4809 }
4810
4811 uint idx = 0;
4812 if (edge.size() > 2) {
4813 int ifVal = getIF(whichrow);
4814 bool foundIF = false;
4815 for (uint i = 0; i < ifNos.size(); ++i) {
4816 if (ifVal == (int)ifNos[i]) {
4817 idx = 2*i;
4818 foundIF = true;
4819 break;
4820 }
4821 }
4822 if (!foundIF) {
4823 throw(AipsError("bad IF number"));
4824 }
4825 }
4826
4827 currEdge.clear();
4828 currEdge.resize(2);
4829 currEdge[0] = edge[idx];
4830 currEdge[1] = edge[idx+1];
4831
4832 lineFinder.setData(getSpectrum(whichrow));
4833 lineFinder.findLines(getCompositeChanMask(whichrow, inMask), currEdge, whichrow);
4834
4835 return lineFinder.getMask();
4836}
4837
4838/* for cspline. will be merged once cspline is available in fitter (2011/3/10 WK) */
4839void Scantable::outputFittingResult(bool outLogger,
4840 bool outTextFile,
4841 bool csvFormat,
4842 const std::vector<bool>& chanMask,
4843 int whichrow,
4844 const casa::String& coordInfo,
4845 bool hasSameNchan,
4846 ofstream& ofs,
4847 const casa::String& funcName,
4848 const std::vector<int>& edge,
4849 const std::vector<float>& params,
4850 const int nClipped)
4851{
4852 if (outLogger || outTextFile) {
4853 float rms = getRms(chanMask, whichrow);
4854 String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
4855 std::vector<bool> fixed;
4856 fixed.clear();
4857
4858 if (outLogger) {
4859 LogIO ols(LogOrigin("Scantable", funcName, WHERE));
4860 ols << formatPiecewiseBaselineParams(edge, params, fixed, rms, nClipped,
4861 masklist, whichrow, false, csvFormat) << LogIO::POST ;
4862 }
4863 if (outTextFile) {
4864 ofs << formatPiecewiseBaselineParams(edge, params, fixed, rms, nClipped,
4865 masklist, whichrow, true, csvFormat) << flush;
4866 }
4867 }
4868}
4869
4870/* for poly/chebyshev/sinusoid. */
4871void Scantable::outputFittingResult(bool outLogger,
4872 bool outTextFile,
4873 bool csvFormat,
4874 const std::vector<bool>& chanMask,
4875 int whichrow,
4876 const casa::String& coordInfo,
4877 bool hasSameNchan,
4878 ofstream& ofs,
4879 const casa::String& funcName,
4880 const std::vector<float>& params,
4881 const int nClipped)
4882{
4883 if (outLogger || outTextFile) {
4884 float rms = getRms(chanMask, whichrow);
4885 String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
4886 std::vector<bool> fixed;
4887 fixed.clear();
4888
4889 if (outLogger) {
4890 LogIO ols(LogOrigin("Scantable", funcName, WHERE));
4891 ols << formatBaselineParams(params, fixed, rms, nClipped,
4892 masklist, whichrow, false, csvFormat) << LogIO::POST ;
4893 }
4894 if (outTextFile) {
4895 ofs << formatBaselineParams(params, fixed, rms, nClipped,
4896 masklist, whichrow, true, csvFormat) << flush;
4897 }
4898 }
4899}
4900
4901void Scantable::parseProgressInfo(const std::string& progressInfo, bool& showProgress, int& minNRow)
4902{
4903 int idxDelimiter = progressInfo.find(",");
4904 if (idxDelimiter < 0) {
4905 throw(AipsError("wrong value in 'showprogress' parameter")) ;
4906 }
4907 showProgress = (progressInfo.substr(0, idxDelimiter) == "true");
4908 std::istringstream is(progressInfo.substr(idxDelimiter+1));
4909 is >> minNRow;
4910}
4911
4912void Scantable::showProgressOnTerminal(const int nProcessed, const int nTotal, const bool showProgress, const int nTotalThreshold)
4913{
4914 if (showProgress && (nTotal >= nTotalThreshold)) {
4915 int nInterval = int(floor(double(nTotal)/100.0));
4916 if (nInterval == 0) nInterval++;
4917
4918 if (nProcessed % nInterval == 0) {
4919 printf("\r"); //go to the head of line
4920 printf("\x1b[31m\x1b[1m"); //set red color, highlighted
4921 printf("[%3d%%]", (int)(100.0*(double(nProcessed+1))/(double(nTotal))) );
4922 printf("\x1b[39m\x1b[0m"); //set default attributes
4923 fflush(NULL);
4924 }
4925
4926 if (nProcessed == nTotal - 1) {
4927 printf("\r\x1b[K"); //clear
4928 fflush(NULL);
4929 }
4930
4931 }
4932}
4933
4934std::vector<float> Scantable::execFFT(const int whichrow, const std::vector<bool>& inMask, bool getRealImag, bool getAmplitudeOnly)
4935{
4936 std::vector<bool> mask = getMask(whichrow);
4937
4938 if (inMask.size() > 0) {
4939 uInt maskSize = mask.size();
4940 if (maskSize != inMask.size()) {
4941 throw(AipsError("mask sizes are not the same."));
4942 }
4943 for (uInt i = 0; i < maskSize; ++i) {
4944 mask[i] = mask[i] && inMask[i];
4945 }
4946 }
4947
4948 Vector<Float> spec = getSpectrum(whichrow);
4949 mathutil::doZeroOrderInterpolation(spec, mask);
4950
4951 FFTServer<Float,Complex> ffts;
4952 Vector<Complex> fftres;
4953 ffts.fft0(fftres, spec);
4954
4955 std::vector<float> res;
4956 float norm = float(2.0/double(spec.size()));
4957
4958 if (getRealImag) {
4959 for (uInt i = 0; i < fftres.size(); ++i) {
4960 res.push_back(real(fftres[i])*norm);
4961 res.push_back(imag(fftres[i])*norm);
4962 }
4963 } else {
4964 for (uInt i = 0; i < fftres.size(); ++i) {
4965 res.push_back(abs(fftres[i])*norm);
4966 if (!getAmplitudeOnly) res.push_back(arg(fftres[i]));
4967 }
4968 }
4969
4970 return res;
4971}
4972
4973
4974float Scantable::getRms(const std::vector<bool>& mask, int whichrow)
4975{
4976 /****
4977 double ms1TimeStart, ms1TimeEnd;
4978 double elapse1 = 0.0;
4979 ms1TimeStart = mathutil::gettimeofday_sec();
4980 ****/
4981
4982 Vector<Float> spec;
4983 specCol_.get(whichrow, spec);
4984
4985 /****
4986 ms1TimeEnd = mathutil::gettimeofday_sec();
4987 elapse1 = ms1TimeEnd - ms1TimeStart;
4988 std::cout << "rm1 : " << elapse1 << " (sec.)" << endl;
4989 ****/
4990
4991 return (float)doGetRms(mask, spec);
4992}
4993
4994double Scantable::doGetRms(const std::vector<bool>& mask, const Vector<Float>& spec)
4995{
4996 double mean = 0.0;
4997 double smean = 0.0;
4998 int n = 0;
4999 for (uInt i = 0; i < spec.nelements(); ++i) {
5000 if (mask[i]) {
5001 double val = (double)spec[i];
5002 mean += val;
5003 smean += val*val;
5004 n++;
5005 }
5006 }
5007
5008 mean /= (double)n;
5009 smean /= (double)n;
5010
5011 return sqrt(smean - mean*mean);
5012}
5013
5014std::string Scantable::formatBaselineParamsHeader(int whichrow, const std::string& masklist, bool verbose, bool csvformat) const
5015{
5016 if (verbose) {
5017 ostringstream oss;
5018
5019 if (csvformat) {
5020 oss << getScan(whichrow) << ",";
5021 oss << getBeam(whichrow) << ",";
5022 oss << getIF(whichrow) << ",";
5023 oss << getPol(whichrow) << ",";
5024 oss << getCycle(whichrow) << ",";
5025 String commaReplacedMasklist = masklist;
5026 string::size_type pos = 0;
5027 while (pos = commaReplacedMasklist.find(","), pos != string::npos) {
5028 commaReplacedMasklist.replace(pos, 1, ";");
5029 pos++;
5030 }
5031 oss << commaReplacedMasklist << ",";
5032 } else {
5033 oss << " Scan[" << getScan(whichrow) << "]";
5034 oss << " Beam[" << getBeam(whichrow) << "]";
5035 oss << " IF[" << getIF(whichrow) << "]";
5036 oss << " Pol[" << getPol(whichrow) << "]";
5037 oss << " Cycle[" << getCycle(whichrow) << "]: " << endl;
5038 oss << "Fitter range = " << masklist << endl;
5039 oss << "Baseline parameters" << endl;
5040 }
5041 oss << flush;
5042
5043 return String(oss);
5044 }
5045
5046 return "";
5047}
5048
5049std::string Scantable::formatBaselineParamsFooter(float rms, int nClipped, bool verbose, bool csvformat) const
5050{
5051 if (verbose) {
5052 ostringstream oss;
5053
5054 if (csvformat) {
5055 oss << rms << ",";
5056 if (nClipped >= 0) {
5057 oss << nClipped;
5058 }
5059 } else {
5060 oss << "Results of baseline fit" << endl;
5061 oss << " rms = " << setprecision(6) << rms << endl;
5062 if (nClipped >= 0) {
5063 oss << " Number of clipped channels = " << nClipped << endl;
5064 }
5065 for (int i = 0; i < 60; ++i) {
5066 oss << "-";
5067 }
5068 }
5069 oss << endl;
5070 oss << flush;
5071
5072 return String(oss);
5073 }
5074
5075 return "";
5076}
5077
5078std::string Scantable::formatBaselineParams(const std::vector<float>& params,
5079 const std::vector<bool>& fixed,
5080 float rms,
5081 int nClipped,
5082 const std::string& masklist,
5083 int whichrow,
5084 bool verbose,
5085 bool csvformat,
5086 int start, int count,
5087 bool resetparamid) const
5088{
5089 int nParam = (int)(params.size());
5090
5091 if (nParam < 1) {
5092 return(" Not fitted");
5093 } else {
5094
5095 ostringstream oss;
5096 oss << formatBaselineParamsHeader(whichrow, masklist, verbose, csvformat);
5097
5098 if (start < 0) start = 0;
5099 if (count < 0) count = nParam;
5100 int end = start + count;
5101 if (end > nParam) end = nParam;
5102 int paramidoffset = (resetparamid) ? (-start) : 0;
5103
5104 for (int i = start; i < end; ++i) {
5105 if (i > start) {
5106 oss << ",";
5107 }
5108 std::string sFix = ((fixed.size() > 0) && (fixed[i]) && verbose) ? "(fixed)" : "";
5109 if (csvformat) {
5110 oss << params[i] << sFix;
5111 } else {
5112 oss << " p" << (i+paramidoffset) << sFix << "= " << right << setw(13) << setprecision(6) << params[i];
5113 }
5114 }
5115
5116 if (csvformat) {
5117 oss << ",";
5118 } else {
5119 oss << endl;
5120 }
5121 oss << formatBaselineParamsFooter(rms, nClipped, verbose, csvformat);
5122
5123 return String(oss);
5124 }
5125
5126}
5127
5128std::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
5129{
5130 int nOutParam = (int)(params.size());
5131 int nPiece = (int)(ranges.size()) - 1;
5132
5133 if (nOutParam < 1) {
5134 return(" Not fitted");
5135 } else if (nPiece < 0) {
5136 return formatBaselineParams(params, fixed, rms, nClipped, masklist, whichrow, verbose, csvformat);
5137 } else if (nPiece < 1) {
5138 return(" Bad count of the piece edge info");
5139 } else if (nOutParam % nPiece != 0) {
5140 return(" Bad count of the output baseline parameters");
5141 } else {
5142
5143 int nParam = nOutParam / nPiece;
5144
5145 ostringstream oss;
5146 oss << formatBaselineParamsHeader(whichrow, masklist, verbose, csvformat);
5147
5148 if (csvformat) {
5149 for (int i = 0; i < nPiece; ++i) {
5150 oss << ranges[i] << "," << (ranges[i+1]-1) << ",";
5151 oss << formatBaselineParams(params, fixed, rms, 0, masklist, whichrow, false, csvformat, i*nParam, nParam, true);
5152 }
5153 } else {
5154 stringstream ss;
5155 ss << ranges[nPiece] << flush;
5156 int wRange = ss.str().size() * 2 + 5;
5157
5158 for (int i = 0; i < nPiece; ++i) {
5159 ss.str("");
5160 ss << " [" << ranges[i] << "," << (ranges[i+1]-1) << "]";
5161 oss << left << setw(wRange) << ss.str();
5162 oss << formatBaselineParams(params, fixed, rms, 0, masklist, whichrow, false, csvformat, i*nParam, nParam, true);
5163 //oss << endl;
5164 }
5165 }
5166
5167 oss << formatBaselineParamsFooter(rms, nClipped, verbose, csvformat);
5168
5169 return String(oss);
5170 }
5171
5172}
5173
5174bool Scantable::hasSameNchanOverIFs()
5175{
5176 int nIF = nif(-1);
5177 int nCh;
5178 int totalPositiveNChan = 0;
5179 int nPositiveNChan = 0;
5180
5181 for (int i = 0; i < nIF; ++i) {
5182 nCh = nchan(i);
5183 if (nCh > 0) {
5184 totalPositiveNChan += nCh;
5185 nPositiveNChan++;
5186 }
5187 }
5188
5189 return (totalPositiveNChan == (nPositiveNChan * nchan(0)));
5190}
5191
5192std::string Scantable::getMaskRangeList(const std::vector<bool>& mask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, bool verbose)
5193{
5194 if (mask.size() <= 0) {
5195 throw(AipsError("The mask elements should be > 0"));
5196 }
5197 int IF = getIF(whichrow);
5198 if (mask.size() != (uInt)nchan(IF)) {
5199 throw(AipsError("Number of channels in scantable != number of mask elements"));
5200 }
5201
5202 if (verbose) {
5203 LogIO logOs(LogOrigin("Scantable", "getMaskRangeList()", WHERE));
5204 logOs << LogIO::WARN << "The current mask window unit is " << coordInfo;
5205 if (!hasSameNchan) {
5206 logOs << endl << "This mask is only valid for IF=" << IF;
5207 }
5208 logOs << LogIO::POST;
5209 }
5210
5211 std::vector<double> abcissa = getAbcissa(whichrow);
5212 std::vector<int> edge = getMaskEdgeIndices(mask);
5213
5214 ostringstream oss;
5215 oss.setf(ios::fixed);
5216 oss << setprecision(1) << "[";
5217 for (uInt i = 0; i < edge.size(); i+=2) {
5218 if (i > 0) oss << ",";
5219 oss << "[" << (float)abcissa[edge[i]] << "," << (float)abcissa[edge[i+1]] << "]";
5220 }
5221 oss << "]" << flush;
5222
5223 return String(oss);
5224}
5225
5226std::vector<int> Scantable::getMaskEdgeIndices(const std::vector<bool>& mask)
5227{
5228 if (mask.size() <= 0) {
5229 throw(AipsError("The mask elements should be > 0"));
5230 }
5231
5232 std::vector<int> out, startIndices, endIndices;
5233 int maskSize = mask.size();
5234
5235 startIndices.clear();
5236 endIndices.clear();
5237
5238 if (mask[0]) {
5239 startIndices.push_back(0);
5240 }
5241 for (int i = 1; i < maskSize; ++i) {
5242 if ((!mask[i-1]) && mask[i]) {
5243 startIndices.push_back(i);
5244 } else if (mask[i-1] && (!mask[i])) {
5245 endIndices.push_back(i-1);
5246 }
5247 }
5248 if (mask[maskSize-1]) {
5249 endIndices.push_back(maskSize-1);
5250 }
5251
5252 if (startIndices.size() != endIndices.size()) {
5253 throw(AipsError("Inconsistent Mask Size: bad data?"));
5254 }
5255 for (uInt i = 0; i < startIndices.size(); ++i) {
5256 if (startIndices[i] > endIndices[i]) {
5257 throw(AipsError("Mask start index > mask end index"));
5258 }
5259 }
5260
5261 out.clear();
5262 for (uInt i = 0; i < startIndices.size(); ++i) {
5263 out.push_back(startIndices[i]);
5264 out.push_back(endIndices[i]);
5265 }
5266
5267 return out;
5268}
5269
5270void Scantable::setTsys(const std::vector<float>& newvals, int whichrow) {
5271 Vector<Float> tsys(newvals);
5272 if (whichrow > -1) {
5273 if (tsysCol_.shape(whichrow) != tsys.shape())
5274 throw(AipsError("Given Tsys values are not of the same shape"));
5275 tsysCol_.put(whichrow, tsys);
5276 } else {
5277 tsysCol_.fillColumn(tsys);
5278 }
5279}
5280
5281vector<float> Scantable::getTsysSpectrum( int whichrow ) const
5282{
5283 Vector<Float> tsys( tsysCol_(whichrow) ) ;
5284 vector<float> stlTsys ;
5285 tsys.tovector( stlTsys ) ;
5286 return stlTsys ;
5287}
5288
5289vector<uint> Scantable::getMoleculeIdColumnData() const
5290{
5291 Vector<uInt> molIds(mmolidCol_.getColumn());
5292 vector<uint> res;
5293 molIds.tovector(res);
5294 return res;
5295}
5296
5297void Scantable::setMoleculeIdColumnData(const std::vector<uint>& molids)
5298{
5299 Vector<uInt> molIds(molids);
5300 Vector<uInt> arr(mmolidCol_.getColumn());
5301 if ( molIds.nelements() != arr.nelements() )
5302 throw AipsError("The input data size must be the number of rows.");
5303 mmolidCol_.putColumn(molIds);
5304}
5305
5306
5307std::vector<uint> Scantable::getRootTableRowNumbers() const
5308{
5309 Vector<uInt> rowIds(table_.rowNumbers());
5310 vector<uint> res;
5311 rowIds.tovector(res);
5312 return res;
5313}
5314
5315
5316void Scantable::dropXPol()
5317{
5318 if (npol() <= 2) {
5319 return;
5320 }
5321 if (!selector_.empty()) {
5322 throw AipsError("Can only operate with empty selection");
5323 }
5324 std::string taql = "SELECT FROM $1 WHERE POLNO IN [0,1]";
5325 Table tab = tableCommand(taql, table_);
5326 table_ = tab;
5327 table_.rwKeywordSet().define("nPol", Int(2));
5328 originalTable_ = table_;
5329 attach();
5330}
5331
5332}
5333//namespace asap
Note: See TracBrowser for help on using the repository browser.