source: trunk/src/Scantable.cpp@ 2886

Last change on this file since 2886 was 2883, 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: fixed two bugs in Scantable::subBaseline() reported by Kana: (1) RuntimeError "too many channels masked..." occurs when clipniter>0 and (2) RuntimeError "row index is out of range" occurs when outbltable exists.


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