source: trunk/src/Scantable.cpp@ 3025

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

New Development: No

JIRA Issue: No

Ready for Test: Yes

Interface Changes: No

What Interface Changed: Please list interface changes

Test Programs: List test programs

Put in Release Notes: No

Module(s):

Description: No fix for stand alone asap. added an include file.


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