source: branches/casa-release-4_3/src/Scantable.cpp@ 3037

Last change on this file since 3037 was 2969, checked in by Kana Sugimoto, 10 years ago

New Development: No

JIRA Issue: Yes (CAS-6109)

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs: runUnitTest.main(test_sdlist)

Put in Release Notes: No

Module(s): scantable, sdlist

Description: Fixed a bug in time range calculation in scantable.summary (sdlist).

Also enhanced precision of time and direction listed in the method.
Added a parameter, prec, in a private funtion, Scantable::formatDirection to allow setting precision.


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