source: trunk/src/Scantable.cpp@ 2057

Last change on this file since 2057 was 2047, checked in by WataruKawasaki, 14 years ago

New Development: Yes

JIRA Issue: Yes CAS-2847

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs:

Put in Release Notes: Yes

Module(s): scantable

Description: added {auto_}sinusoid_baseline() for sinusoidal baseline fitting. also minor bug fixes for asapfitter.


  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 85.9 KB
Line 
1//
2// C++ Implementation: Scantable
3//
4// Description:
5//
6//
7// Author: Malte Marquarding <asap@atnf.csiro.au>, (C) 2005
8//
9// Copyright: See COPYING file that comes with this distribution
10//
11//
12#include <map>
13#include <fstream>
14
15#include <casa/aips.h>
16#include <casa/iostream.h>
17#include <casa/iomanip.h>
18#include <casa/OS/Path.h>
19#include <casa/OS/File.h>
20#include <casa/Arrays/Array.h>
21#include <casa/Arrays/ArrayMath.h>
22#include <casa/Arrays/MaskArrMath.h>
23#include <casa/Arrays/ArrayLogical.h>
24#include <casa/Arrays/ArrayAccessor.h>
25#include <casa/Arrays/Vector.h>
26#include <casa/Arrays/VectorSTLIterator.h>
27#include <casa/Arrays/Slice.h>
28#include <casa/BasicMath/Math.h>
29#include <casa/BasicSL/Constants.h>
30#include <casa/Quanta/MVAngle.h>
31#include <casa/Containers/RecordField.h>
32#include <casa/Utilities/GenSort.h>
33#include <casa/Logging/LogIO.h>
34
35#include <tables/Tables/TableParse.h>
36#include <tables/Tables/TableDesc.h>
37#include <tables/Tables/TableCopy.h>
38#include <tables/Tables/SetupNewTab.h>
39#include <tables/Tables/ScaColDesc.h>
40#include <tables/Tables/ArrColDesc.h>
41#include <tables/Tables/TableRow.h>
42#include <tables/Tables/TableVector.h>
43#include <tables/Tables/TableIter.h>
44
45#include <tables/Tables/ExprNode.h>
46#include <tables/Tables/TableRecord.h>
47#include <casa/Quanta/MVTime.h>
48#include <casa/Quanta/MVAngle.h>
49#include <measures/Measures/MeasRef.h>
50#include <measures/Measures/MeasTable.h>
51// needed to avoid error in .tcc
52#include <measures/Measures/MCDirection.h>
53//
54#include <measures/Measures/MDirection.h>
55#include <measures/Measures/MFrequency.h>
56#include <measures/Measures/MEpoch.h>
57#include <measures/TableMeasures/TableMeasRefDesc.h>
58#include <measures/TableMeasures/TableMeasValueDesc.h>
59#include <measures/TableMeasures/TableMeasDesc.h>
60#include <measures/TableMeasures/ScalarMeasColumn.h>
61#include <coordinates/Coordinates/CoordinateUtil.h>
62
63#include <atnf/PKSIO/SrcType.h>
64#include "Scantable.h"
65#include "STPolLinear.h"
66#include "STPolCircular.h"
67#include "STPolStokes.h"
68#include "STAttr.h"
69#include "STLineFinder.h"
70#include "MathUtils.h"
71
72using namespace casa;
73
74namespace asap {
75
76std::map<std::string, STPol::STPolFactory *> Scantable::factories_;
77
78void Scantable::initFactories() {
79 if ( factories_.empty() ) {
80 Scantable::factories_["linear"] = &STPolLinear::myFactory;
81 Scantable::factories_["circular"] = &STPolCircular::myFactory;
82 Scantable::factories_["stokes"] = &STPolStokes::myFactory;
83 }
84}
85
86Scantable::Scantable(Table::TableType ttype) :
87 type_(ttype)
88{
89 initFactories();
90 setupMainTable();
91 freqTable_ = STFrequencies(*this);
92 table_.rwKeywordSet().defineTable("FREQUENCIES", freqTable_.table());
93 weatherTable_ = STWeather(*this);
94 table_.rwKeywordSet().defineTable("WEATHER", weatherTable_.table());
95 focusTable_ = STFocus(*this);
96 table_.rwKeywordSet().defineTable("FOCUS", focusTable_.table());
97 tcalTable_ = STTcal(*this);
98 table_.rwKeywordSet().defineTable("TCAL", tcalTable_.table());
99 moleculeTable_ = STMolecules(*this);
100 table_.rwKeywordSet().defineTable("MOLECULES", moleculeTable_.table());
101 historyTable_ = STHistory(*this);
102 table_.rwKeywordSet().defineTable("HISTORY", historyTable_.table());
103 fitTable_ = STFit(*this);
104 table_.rwKeywordSet().defineTable("FIT", fitTable_.table());
105 table_.tableInfo().setType( "Scantable" ) ;
106 originalTable_ = table_;
107 attach();
108}
109
110Scantable::Scantable(const std::string& name, Table::TableType ttype) :
111 type_(ttype)
112{
113 initFactories();
114
115 Table tab(name, Table::Update);
116 uInt version = tab.keywordSet().asuInt("VERSION");
117 if (version != version_) {
118 throw(AipsError("Unsupported version of ASAP file."));
119 }
120 if ( type_ == Table::Memory ) {
121 table_ = tab.copyToMemoryTable(generateName());
122 } else {
123 table_ = tab;
124 }
125 table_.tableInfo().setType( "Scantable" ) ;
126
127 attachSubtables();
128 originalTable_ = table_;
129 attach();
130}
131/*
132Scantable::Scantable(const std::string& name, Table::TableType ttype) :
133 type_(ttype)
134{
135 initFactories();
136 Table tab(name, Table::Update);
137 uInt version = tab.keywordSet().asuInt("VERSION");
138 if (version != version_) {
139 throw(AipsError("Unsupported version of ASAP file."));
140 }
141 if ( type_ == Table::Memory ) {
142 table_ = tab.copyToMemoryTable(generateName());
143 } else {
144 table_ = tab;
145 }
146
147 attachSubtables();
148 originalTable_ = table_;
149 attach();
150}
151*/
152
153Scantable::Scantable( const Scantable& other, bool clear )
154{
155 // with or without data
156 String newname = String(generateName());
157 type_ = other.table_.tableType();
158 if ( other.table_.tableType() == Table::Memory ) {
159 if ( clear ) {
160 table_ = TableCopy::makeEmptyMemoryTable(newname,
161 other.table_, True);
162 } else
163 table_ = other.table_.copyToMemoryTable(newname);
164 } else {
165 other.table_.deepCopy(newname, Table::New, False,
166 other.table_.endianFormat(),
167 Bool(clear));
168 table_ = Table(newname, Table::Update);
169 table_.markForDelete();
170 }
171 table_.tableInfo().setType( "Scantable" ) ;
172 /// @todo reindex SCANNO, recompute nbeam, nif, npol
173 if ( clear ) copySubtables(other);
174 attachSubtables();
175 originalTable_ = table_;
176 attach();
177}
178
179void Scantable::copySubtables(const Scantable& other) {
180 Table t = table_.rwKeywordSet().asTable("FREQUENCIES");
181 TableCopy::copyRows(t, other.freqTable_.table());
182 t = table_.rwKeywordSet().asTable("FOCUS");
183 TableCopy::copyRows(t, other.focusTable_.table());
184 t = table_.rwKeywordSet().asTable("WEATHER");
185 TableCopy::copyRows(t, other.weatherTable_.table());
186 t = table_.rwKeywordSet().asTable("TCAL");
187 TableCopy::copyRows(t, other.tcalTable_.table());
188 t = table_.rwKeywordSet().asTable("MOLECULES");
189 TableCopy::copyRows(t, other.moleculeTable_.table());
190 t = table_.rwKeywordSet().asTable("HISTORY");
191 TableCopy::copyRows(t, other.historyTable_.table());
192 t = table_.rwKeywordSet().asTable("FIT");
193 TableCopy::copyRows(t, other.fitTable_.table());
194}
195
196void Scantable::attachSubtables()
197{
198 freqTable_ = STFrequencies(table_);
199 focusTable_ = STFocus(table_);
200 weatherTable_ = STWeather(table_);
201 tcalTable_ = STTcal(table_);
202 moleculeTable_ = STMolecules(table_);
203 historyTable_ = STHistory(table_);
204 fitTable_ = STFit(table_);
205}
206
207Scantable::~Scantable()
208{
209 //cout << "~Scantable() " << this << endl;
210}
211
212void Scantable::setupMainTable()
213{
214 TableDesc td("", "1", TableDesc::Scratch);
215 td.comment() = "An ASAP Scantable";
216 td.rwKeywordSet().define("VERSION", uInt(version_));
217
218 // n Cycles
219 td.addColumn(ScalarColumnDesc<uInt>("SCANNO"));
220 // new index every nBeam x nIF x nPol
221 td.addColumn(ScalarColumnDesc<uInt>("CYCLENO"));
222
223 td.addColumn(ScalarColumnDesc<uInt>("BEAMNO"));
224 td.addColumn(ScalarColumnDesc<uInt>("IFNO"));
225 // linear, circular, stokes
226 td.rwKeywordSet().define("POLTYPE", String("linear"));
227 td.addColumn(ScalarColumnDesc<uInt>("POLNO"));
228
229 td.addColumn(ScalarColumnDesc<uInt>("FREQ_ID"));
230 td.addColumn(ScalarColumnDesc<uInt>("MOLECULE_ID"));
231
232 ScalarColumnDesc<Int> refbeamnoColumn("REFBEAMNO");
233 refbeamnoColumn.setDefault(Int(-1));
234 td.addColumn(refbeamnoColumn);
235
236 ScalarColumnDesc<uInt> flagrowColumn("FLAGROW");
237 flagrowColumn.setDefault(uInt(0));
238 td.addColumn(flagrowColumn);
239
240 td.addColumn(ScalarColumnDesc<Double>("TIME"));
241 TableMeasRefDesc measRef(MEpoch::UTC); // UTC as default
242 TableMeasValueDesc measVal(td, "TIME");
243 TableMeasDesc<MEpoch> mepochCol(measVal, measRef);
244 mepochCol.write(td);
245
246 td.addColumn(ScalarColumnDesc<Double>("INTERVAL"));
247
248 td.addColumn(ScalarColumnDesc<String>("SRCNAME"));
249 // Type of source (on=0, off=1, other=-1)
250 ScalarColumnDesc<Int> stypeColumn("SRCTYPE");
251 stypeColumn.setDefault(Int(-1));
252 td.addColumn(stypeColumn);
253 td.addColumn(ScalarColumnDesc<String>("FIELDNAME"));
254
255 //The actual Data Vectors
256 td.addColumn(ArrayColumnDesc<Float>("SPECTRA"));
257 td.addColumn(ArrayColumnDesc<uChar>("FLAGTRA"));
258 td.addColumn(ArrayColumnDesc<Float>("TSYS"));
259
260 td.addColumn(ArrayColumnDesc<Double>("DIRECTION",
261 IPosition(1,2),
262 ColumnDesc::Direct));
263 TableMeasRefDesc mdirRef(MDirection::J2000); // default
264 TableMeasValueDesc tmvdMDir(td, "DIRECTION");
265 // the TableMeasDesc gives the column a type
266 TableMeasDesc<MDirection> mdirCol(tmvdMDir, mdirRef);
267 // a uder set table type e.g. GALCTIC, B1950 ...
268 td.rwKeywordSet().define("DIRECTIONREF", String("J2000"));
269 // writing create the measure column
270 mdirCol.write(td);
271 td.addColumn(ScalarColumnDesc<Float>("AZIMUTH"));
272 td.addColumn(ScalarColumnDesc<Float>("ELEVATION"));
273 td.addColumn(ScalarColumnDesc<Float>("OPACITY"));
274
275 td.addColumn(ScalarColumnDesc<uInt>("TCAL_ID"));
276 ScalarColumnDesc<Int> fitColumn("FIT_ID");
277 fitColumn.setDefault(Int(-1));
278 td.addColumn(fitColumn);
279
280 td.addColumn(ScalarColumnDesc<uInt>("FOCUS_ID"));
281 td.addColumn(ScalarColumnDesc<uInt>("WEATHER_ID"));
282
283 // columns which just get dragged along, as they aren't used in asap
284 td.addColumn(ScalarColumnDesc<Double>("SRCVELOCITY"));
285 td.addColumn(ArrayColumnDesc<Double>("SRCPROPERMOTION"));
286 td.addColumn(ArrayColumnDesc<Double>("SRCDIRECTION"));
287 td.addColumn(ArrayColumnDesc<Double>("SCANRATE"));
288
289 td.rwKeywordSet().define("OBSMODE", String(""));
290
291 // Now create Table SetUp from the description.
292 SetupNewTable aNewTab(generateName(), td, Table::Scratch);
293 table_ = Table(aNewTab, type_, 0);
294 originalTable_ = table_;
295}
296
297void Scantable::attach()
298{
299 timeCol_.attach(table_, "TIME");
300 srcnCol_.attach(table_, "SRCNAME");
301 srctCol_.attach(table_, "SRCTYPE");
302 specCol_.attach(table_, "SPECTRA");
303 flagsCol_.attach(table_, "FLAGTRA");
304 tsysCol_.attach(table_, "TSYS");
305 cycleCol_.attach(table_,"CYCLENO");
306 scanCol_.attach(table_, "SCANNO");
307 beamCol_.attach(table_, "BEAMNO");
308 ifCol_.attach(table_, "IFNO");
309 polCol_.attach(table_, "POLNO");
310 integrCol_.attach(table_, "INTERVAL");
311 azCol_.attach(table_, "AZIMUTH");
312 elCol_.attach(table_, "ELEVATION");
313 dirCol_.attach(table_, "DIRECTION");
314 fldnCol_.attach(table_, "FIELDNAME");
315 rbeamCol_.attach(table_, "REFBEAMNO");
316
317 mweatheridCol_.attach(table_,"WEATHER_ID");
318 mfitidCol_.attach(table_,"FIT_ID");
319 mfreqidCol_.attach(table_, "FREQ_ID");
320 mtcalidCol_.attach(table_, "TCAL_ID");
321 mfocusidCol_.attach(table_, "FOCUS_ID");
322 mmolidCol_.attach(table_, "MOLECULE_ID");
323
324 //Add auxiliary column for row-based flagging (CAS-1433 Wataru Kawasaki)
325 attachAuxColumnDef(flagrowCol_, "FLAGROW", 0);
326
327}
328
329template<class T, class T2>
330void Scantable::attachAuxColumnDef(ScalarColumn<T>& col,
331 const String& colName,
332 const T2& defValue)
333{
334 try {
335 col.attach(table_, colName);
336 } catch (TableError& err) {
337 String errMesg = err.getMesg();
338 if (errMesg == "Table column " + colName + " is unknown") {
339 table_.addColumn(ScalarColumnDesc<T>(colName));
340 col.attach(table_, colName);
341 col.fillColumn(static_cast<T>(defValue));
342 } else {
343 throw;
344 }
345 } catch (...) {
346 throw;
347 }
348}
349
350template<class T, class T2>
351void Scantable::attachAuxColumnDef(ArrayColumn<T>& col,
352 const String& colName,
353 const Array<T2>& defValue)
354{
355 try {
356 col.attach(table_, colName);
357 } catch (TableError& err) {
358 String errMesg = err.getMesg();
359 if (errMesg == "Table column " + colName + " is unknown") {
360 table_.addColumn(ArrayColumnDesc<T>(colName));
361 col.attach(table_, colName);
362
363 int size = 0;
364 ArrayIterator<T2>& it = defValue.begin();
365 while (it != defValue.end()) {
366 ++size;
367 ++it;
368 }
369 IPosition ip(1, size);
370 Array<T>& arr(ip);
371 for (int i = 0; i < size; ++i)
372 arr[i] = static_cast<T>(defValue[i]);
373
374 col.fillColumn(arr);
375 } else {
376 throw;
377 }
378 } catch (...) {
379 throw;
380 }
381}
382
383void Scantable::setHeader(const STHeader& sdh)
384{
385 table_.rwKeywordSet().define("nIF", sdh.nif);
386 table_.rwKeywordSet().define("nBeam", sdh.nbeam);
387 table_.rwKeywordSet().define("nPol", sdh.npol);
388 table_.rwKeywordSet().define("nChan", sdh.nchan);
389 table_.rwKeywordSet().define("Observer", sdh.observer);
390 table_.rwKeywordSet().define("Project", sdh.project);
391 table_.rwKeywordSet().define("Obstype", sdh.obstype);
392 table_.rwKeywordSet().define("AntennaName", sdh.antennaname);
393 table_.rwKeywordSet().define("AntennaPosition", sdh.antennaposition);
394 table_.rwKeywordSet().define("Equinox", sdh.equinox);
395 table_.rwKeywordSet().define("FreqRefFrame", sdh.freqref);
396 table_.rwKeywordSet().define("FreqRefVal", sdh.reffreq);
397 table_.rwKeywordSet().define("Bandwidth", sdh.bandwidth);
398 table_.rwKeywordSet().define("UTC", sdh.utc);
399 table_.rwKeywordSet().define("FluxUnit", sdh.fluxunit);
400 table_.rwKeywordSet().define("Epoch", sdh.epoch);
401 table_.rwKeywordSet().define("POLTYPE", sdh.poltype);
402}
403
404STHeader Scantable::getHeader() const
405{
406 STHeader sdh;
407 table_.keywordSet().get("nBeam",sdh.nbeam);
408 table_.keywordSet().get("nIF",sdh.nif);
409 table_.keywordSet().get("nPol",sdh.npol);
410 table_.keywordSet().get("nChan",sdh.nchan);
411 table_.keywordSet().get("Observer", sdh.observer);
412 table_.keywordSet().get("Project", sdh.project);
413 table_.keywordSet().get("Obstype", sdh.obstype);
414 table_.keywordSet().get("AntennaName", sdh.antennaname);
415 table_.keywordSet().get("AntennaPosition", sdh.antennaposition);
416 table_.keywordSet().get("Equinox", sdh.equinox);
417 table_.keywordSet().get("FreqRefFrame", sdh.freqref);
418 table_.keywordSet().get("FreqRefVal", sdh.reffreq);
419 table_.keywordSet().get("Bandwidth", sdh.bandwidth);
420 table_.keywordSet().get("UTC", sdh.utc);
421 table_.keywordSet().get("FluxUnit", sdh.fluxunit);
422 table_.keywordSet().get("Epoch", sdh.epoch);
423 table_.keywordSet().get("POLTYPE", sdh.poltype);
424 return sdh;
425}
426
427void Scantable::setSourceType( int stype )
428{
429 if ( stype < 0 || stype > 1 )
430 throw(AipsError("Illegal sourcetype."));
431 TableVector<Int> tabvec(table_, "SRCTYPE");
432 tabvec = Int(stype);
433}
434
435bool Scantable::conformant( const Scantable& other )
436{
437 return this->getHeader().conformant(other.getHeader());
438}
439
440
441
442std::string Scantable::formatSec(Double x) const
443{
444 Double xcop = x;
445 MVTime mvt(xcop/24./3600.); // make days
446
447 if (x < 59.95)
448 return String(" ") + mvt.string(MVTime::TIME_CLEAN_NO_HM, 7)+"s";
449 else if (x < 3599.95)
450 return String(" ") + mvt.string(MVTime::TIME_CLEAN_NO_H,7)+" ";
451 else {
452 ostringstream oss;
453 oss << setw(2) << std::right << setprecision(1) << mvt.hour();
454 oss << ":" << mvt.string(MVTime::TIME_CLEAN_NO_H,7) << " ";
455 return String(oss);
456 }
457};
458
459std::string Scantable::formatDirection(const MDirection& md) const
460{
461 Vector<Double> t = md.getAngle(Unit(String("rad"))).getValue();
462 Int prec = 7;
463
464 MVAngle mvLon(t[0]);
465 String sLon = mvLon.string(MVAngle::TIME,prec);
466 uInt tp = md.getRef().getType();
467 if (tp == MDirection::GALACTIC ||
468 tp == MDirection::SUPERGAL ) {
469 sLon = mvLon(0.0).string(MVAngle::ANGLE_CLEAN,prec);
470 }
471 MVAngle mvLat(t[1]);
472 String sLat = mvLat.string(MVAngle::ANGLE+MVAngle::DIG2,prec);
473 return sLon + String(" ") + sLat;
474}
475
476
477std::string Scantable::getFluxUnit() const
478{
479 return table_.keywordSet().asString("FluxUnit");
480}
481
482void Scantable::setFluxUnit(const std::string& unit)
483{
484 String tmp(unit);
485 Unit tU(tmp);
486 if (tU==Unit("K") || tU==Unit("Jy")) {
487 table_.rwKeywordSet().define(String("FluxUnit"), tmp);
488 } else {
489 throw AipsError("Illegal unit - must be compatible with Jy or K");
490 }
491}
492
493void Scantable::setInstrument(const std::string& name)
494{
495 bool throwIt = true;
496 // create an Instrument to see if this is valid
497 STAttr::convertInstrument(name, throwIt);
498 String nameU(name);
499 nameU.upcase();
500 table_.rwKeywordSet().define(String("AntennaName"), nameU);
501}
502
503void Scantable::setFeedType(const std::string& feedtype)
504{
505 if ( Scantable::factories_.find(feedtype) == Scantable::factories_.end() ) {
506 std::string msg = "Illegal feed type "+ feedtype;
507 throw(casa::AipsError(msg));
508 }
509 table_.rwKeywordSet().define(String("POLTYPE"), feedtype);
510}
511
512MPosition Scantable::getAntennaPosition() const
513{
514 Vector<Double> antpos;
515 table_.keywordSet().get("AntennaPosition", antpos);
516 MVPosition mvpos(antpos(0),antpos(1),antpos(2));
517 return MPosition(mvpos);
518}
519
520void Scantable::makePersistent(const std::string& filename)
521{
522 String inname(filename);
523 Path path(inname);
524 /// @todo reindex SCANNO, recompute nbeam, nif, npol
525 inname = path.expandedName();
526 // 2011/03/04 TN
527 // We can comment out this workaround since the essential bug is
528 // fixed in casacore (r20889 in google code).
529 table_.deepCopy(inname, Table::New);
530// // WORKAROUND !!! for Table bug
531// // Remove when fixed in casacore
532// if ( table_.tableType() == Table::Memory && !selector_.empty() ) {
533// Table tab = table_.copyToMemoryTable(generateName());
534// tab.deepCopy(inname, Table::New);
535// tab.markForDelete();
536//
537// } else {
538// table_.deepCopy(inname, Table::New);
539// }
540}
541
542int Scantable::nbeam( int scanno ) const
543{
544 if ( scanno < 0 ) {
545 Int n;
546 table_.keywordSet().get("nBeam",n);
547 return int(n);
548 } else {
549 // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
550 Table t = table_(table_.col("SCANNO") == scanno);
551 ROTableRow row(t);
552 const TableRecord& rec = row.get(0);
553 Table subt = t( t.col("IFNO") == Int(rec.asuInt("IFNO"))
554 && t.col("POLNO") == Int(rec.asuInt("POLNO"))
555 && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
556 ROTableVector<uInt> v(subt, "BEAMNO");
557 return int(v.nelements());
558 }
559 return 0;
560}
561
562int Scantable::nif( int scanno ) const
563{
564 if ( scanno < 0 ) {
565 Int n;
566 table_.keywordSet().get("nIF",n);
567 return int(n);
568 } else {
569 // take the first POLNO,BEAMNO,CYCLENO as nbeam shouldn't vary with these
570 Table t = table_(table_.col("SCANNO") == scanno);
571 ROTableRow row(t);
572 const TableRecord& rec = row.get(0);
573 Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
574 && t.col("POLNO") == Int(rec.asuInt("POLNO"))
575 && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
576 if ( subt.nrow() == 0 ) return 0;
577 ROTableVector<uInt> v(subt, "IFNO");
578 return int(v.nelements());
579 }
580 return 0;
581}
582
583int Scantable::npol( int scanno ) const
584{
585 if ( scanno < 0 ) {
586 Int n;
587 table_.keywordSet().get("nPol",n);
588 return n;
589 } else {
590 // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
591 Table t = table_(table_.col("SCANNO") == scanno);
592 ROTableRow row(t);
593 const TableRecord& rec = row.get(0);
594 Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
595 && t.col("IFNO") == Int(rec.asuInt("IFNO"))
596 && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
597 if ( subt.nrow() == 0 ) return 0;
598 ROTableVector<uInt> v(subt, "POLNO");
599 return int(v.nelements());
600 }
601 return 0;
602}
603
604int Scantable::ncycle( int scanno ) const
605{
606 if ( scanno < 0 ) {
607 Block<String> cols(2);
608 cols[0] = "SCANNO";
609 cols[1] = "CYCLENO";
610 TableIterator it(table_, cols);
611 int n = 0;
612 while ( !it.pastEnd() ) {
613 ++n;
614 ++it;
615 }
616 return n;
617 } else {
618 Table t = table_(table_.col("SCANNO") == scanno);
619 ROTableRow row(t);
620 const TableRecord& rec = row.get(0);
621 Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
622 && t.col("POLNO") == Int(rec.asuInt("POLNO"))
623 && t.col("IFNO") == Int(rec.asuInt("IFNO")) );
624 if ( subt.nrow() == 0 ) return 0;
625 return int(subt.nrow());
626 }
627 return 0;
628}
629
630
631int Scantable::nrow( int scanno ) const
632{
633 return int(table_.nrow());
634}
635
636int Scantable::nchan( int ifno ) const
637{
638 if ( ifno < 0 ) {
639 Int n;
640 table_.keywordSet().get("nChan",n);
641 return int(n);
642 } else {
643 // take the first SCANNO,POLNO,BEAMNO,CYCLENO as nbeam shouldn't
644 // vary with these
645 Table t = table_(table_.col("IFNO") == ifno);
646 if ( t.nrow() == 0 ) return 0;
647 ROArrayColumn<Float> v(t, "SPECTRA");
648 return v.shape(0)(0);
649 }
650 return 0;
651}
652
653int Scantable::nscan() const {
654 Vector<uInt> scannos(scanCol_.getColumn());
655 uInt nout = genSort( scannos, Sort::Ascending,
656 Sort::QuickSort|Sort::NoDuplicates );
657 return int(nout);
658}
659
660int Scantable::getChannels(int whichrow) const
661{
662 return specCol_.shape(whichrow)(0);
663}
664
665int Scantable::getBeam(int whichrow) const
666{
667 return beamCol_(whichrow);
668}
669
670std::vector<uint> Scantable::getNumbers(const ScalarColumn<uInt>& col) const
671{
672 Vector<uInt> nos(col.getColumn());
673 uInt n = genSort( nos, Sort::Ascending, Sort::QuickSort|Sort::NoDuplicates );
674 nos.resize(n, True);
675 std::vector<uint> stlout;
676 nos.tovector(stlout);
677 return stlout;
678}
679
680int Scantable::getIF(int whichrow) const
681{
682 return ifCol_(whichrow);
683}
684
685int Scantable::getPol(int whichrow) const
686{
687 return polCol_(whichrow);
688}
689
690std::string Scantable::formatTime(const MEpoch& me, bool showdate) const
691{
692 return formatTime(me, showdate, 0);
693}
694
695std::string Scantable::formatTime(const MEpoch& me, bool showdate, uInt prec) const
696{
697 MVTime mvt(me.getValue());
698 if (showdate)
699 //mvt.setFormat(MVTime::YMD);
700 mvt.setFormat(MVTime::YMD, prec);
701 else
702 //mvt.setFormat(MVTime::TIME);
703 mvt.setFormat(MVTime::TIME, prec);
704 ostringstream oss;
705 oss << mvt;
706 return String(oss);
707}
708
709void Scantable::calculateAZEL()
710{
711 MPosition mp = getAntennaPosition();
712 MEpoch::ROScalarColumn timeCol(table_, "TIME");
713 ostringstream oss;
714 oss << "Computed azimuth/elevation using " << endl
715 << mp << endl;
716 for (Int i=0; i<nrow(); ++i) {
717 MEpoch me = timeCol(i);
718 MDirection md = getDirection(i);
719 oss << " Time: " << formatTime(me,False) << " Direction: " << formatDirection(md)
720 << endl << " => ";
721 MeasFrame frame(mp, me);
722 Vector<Double> azel =
723 MDirection::Convert(md, MDirection::Ref(MDirection::AZEL,
724 frame)
725 )().getAngle("rad").getValue();
726 azCol_.put(i,Float(azel[0]));
727 elCol_.put(i,Float(azel[1]));
728 oss << "azel: " << azel[0]/C::pi*180.0 << " "
729 << azel[1]/C::pi*180.0 << " (deg)" << endl;
730 }
731 pushLog(String(oss));
732}
733
734void Scantable::clip(const Float uthres, const Float dthres, bool clipoutside, bool unflag)
735{
736 for (uInt i=0; i<table_.nrow(); ++i) {
737 Vector<uChar> flgs = flagsCol_(i);
738 srchChannelsToClip(i, uthres, dthres, clipoutside, unflag, flgs);
739 flagsCol_.put(i, flgs);
740 }
741}
742
743std::vector<bool> Scantable::getClipMask(int whichrow, const Float uthres, const Float dthres, bool clipoutside, bool unflag)
744{
745 Vector<uChar> flags;
746 flagsCol_.get(uInt(whichrow), flags);
747 srchChannelsToClip(uInt(whichrow), uthres, dthres, clipoutside, unflag, flags);
748 Vector<Bool> bflag(flags.shape());
749 convertArray(bflag, flags);
750 //bflag = !bflag;
751
752 std::vector<bool> mask;
753 bflag.tovector(mask);
754 return mask;
755}
756
757void Scantable::srchChannelsToClip(uInt whichrow, const Float uthres, const Float dthres, bool clipoutside, bool unflag,
758 Vector<uChar> flgs)
759{
760 Vector<Float> spcs = specCol_(whichrow);
761 uInt nchannel = nchan();
762 if (spcs.nelements() != nchannel) {
763 throw(AipsError("Data has incorrect number of channels"));
764 }
765 uChar userflag = 1 << 7;
766 if (unflag) {
767 userflag = 0 << 7;
768 }
769 if (clipoutside) {
770 for (uInt j = 0; j < nchannel; ++j) {
771 Float spc = spcs(j);
772 if ((spc >= uthres) || (spc <= dthres)) {
773 flgs(j) = userflag;
774 }
775 }
776 } else {
777 for (uInt j = 0; j < nchannel; ++j) {
778 Float spc = spcs(j);
779 if ((spc < uthres) && (spc > dthres)) {
780 flgs(j) = userflag;
781 }
782 }
783 }
784}
785
786
787void Scantable::flag( int whichrow, const std::vector<bool>& msk, bool unflag ) {
788 std::vector<bool>::const_iterator it;
789 uInt ntrue = 0;
790 if (whichrow >= int(table_.nrow()) ) {
791 throw(AipsError("Invalid row number"));
792 }
793 for (it = msk.begin(); it != msk.end(); ++it) {
794 if ( *it ) {
795 ntrue++;
796 }
797 }
798 //if ( selector_.empty() && (msk.size() == 0 || msk.size() == ntrue) )
799 if ( whichrow == -1 && !unflag && selector_.empty() && (msk.size() == 0 || msk.size() == ntrue) )
800 throw(AipsError("Trying to flag whole scantable."));
801 uChar userflag = 1 << 7;
802 if ( unflag ) {
803 userflag = 0 << 7;
804 }
805 if (whichrow > -1 ) {
806 applyChanFlag(uInt(whichrow), msk, userflag);
807 } else {
808 for ( uInt i=0; i<table_.nrow(); ++i) {
809 applyChanFlag(i, msk, userflag);
810 }
811 }
812}
813
814void Scantable::applyChanFlag( uInt whichrow, const std::vector<bool>& msk, uChar flagval )
815{
816 if (whichrow >= table_.nrow() ) {
817 throw( casa::indexError<int>( whichrow, "asap::Scantable::applyChanFlag: Invalid row number" ) );
818 }
819 Vector<uChar> flgs = flagsCol_(whichrow);
820 if ( msk.size() == 0 ) {
821 flgs = flagval;
822 flagsCol_.put(whichrow, flgs);
823 return;
824 }
825 if ( int(msk.size()) != nchan() ) {
826 throw(AipsError("Mask has incorrect number of channels."));
827 }
828 if ( flgs.nelements() != msk.size() ) {
829 throw(AipsError("Mask has incorrect number of channels."
830 " Probably varying with IF. Please flag per IF"));
831 }
832 std::vector<bool>::const_iterator it;
833 uInt j = 0;
834 for (it = msk.begin(); it != msk.end(); ++it) {
835 if ( *it ) {
836 flgs(j) = flagval;
837 }
838 ++j;
839 }
840 flagsCol_.put(whichrow, flgs);
841}
842
843void Scantable::flagRow(const std::vector<uInt>& rows, bool unflag)
844{
845 if ( selector_.empty() && (rows.size() == table_.nrow()) )
846 throw(AipsError("Trying to flag whole scantable."));
847
848 uInt rowflag = (unflag ? 0 : 1);
849 std::vector<uInt>::const_iterator it;
850 for (it = rows.begin(); it != rows.end(); ++it)
851 flagrowCol_.put(*it, rowflag);
852}
853
854std::vector<bool> Scantable::getMask(int whichrow) const
855{
856 Vector<uChar> flags;
857 flagsCol_.get(uInt(whichrow), flags);
858 Vector<Bool> bflag(flags.shape());
859 convertArray(bflag, flags);
860 bflag = !bflag;
861 std::vector<bool> mask;
862 bflag.tovector(mask);
863 return mask;
864}
865
866std::vector<float> Scantable::getSpectrum( int whichrow,
867 const std::string& poltype ) const
868{
869 String ptype = poltype;
870 if (poltype == "" ) ptype = getPolType();
871 if ( whichrow < 0 || whichrow >= nrow() )
872 throw(AipsError("Illegal row number."));
873 std::vector<float> out;
874 Vector<Float> arr;
875 uInt requestedpol = polCol_(whichrow);
876 String basetype = getPolType();
877 if ( ptype == basetype ) {
878 specCol_.get(whichrow, arr);
879 } else {
880 CountedPtr<STPol> stpol(STPol::getPolClass(Scantable::factories_,
881 basetype));
882 uInt row = uInt(whichrow);
883 stpol->setSpectra(getPolMatrix(row));
884 Float fang,fhand;
885 fang = focusTable_.getTotalAngle(mfocusidCol_(row));
886 fhand = focusTable_.getFeedHand(mfocusidCol_(row));
887 stpol->setPhaseCorrections(fang, fhand);
888 arr = stpol->getSpectrum(requestedpol, ptype);
889 }
890 if ( arr.nelements() == 0 )
891 pushLog("Not enough polarisations present to do the conversion.");
892 arr.tovector(out);
893 return out;
894}
895
896void Scantable::setSpectrum( const std::vector<float>& spec,
897 int whichrow )
898{
899 Vector<Float> spectrum(spec);
900 Vector<Float> arr;
901 specCol_.get(whichrow, arr);
902 if ( spectrum.nelements() != arr.nelements() )
903 throw AipsError("The spectrum has incorrect number of channels.");
904 specCol_.put(whichrow, spectrum);
905}
906
907
908String Scantable::generateName()
909{
910 return (File::newUniqueName("./","temp")).baseName();
911}
912
913const casa::Table& Scantable::table( ) const
914{
915 return table_;
916}
917
918casa::Table& Scantable::table( )
919{
920 return table_;
921}
922
923std::string Scantable::getPolType() const
924{
925 return table_.keywordSet().asString("POLTYPE");
926}
927
928void Scantable::unsetSelection()
929{
930 table_ = originalTable_;
931 attach();
932 selector_.reset();
933}
934
935void Scantable::setSelection( const STSelector& selection )
936{
937 Table tab = const_cast<STSelector&>(selection).apply(originalTable_);
938 if ( tab.nrow() == 0 ) {
939 throw(AipsError("Selection contains no data. Not applying it."));
940 }
941 table_ = tab;
942 attach();
943 selector_ = selection;
944}
945
946std::string Scantable::summary( bool verbose )
947{
948 // Format header info
949 ostringstream oss;
950 oss << endl;
951 oss << asap::SEPERATOR << endl;
952 oss << " Scan Table Summary" << endl;
953 oss << asap::SEPERATOR << endl;
954 oss.flags(std::ios_base::left);
955 oss << setw(15) << "Beams:" << setw(4) << nbeam() << endl
956 << setw(15) << "IFs:" << setw(4) << nif() << endl
957 << setw(15) << "Polarisations:" << setw(4) << npol()
958 << "(" << getPolType() << ")" << endl
959 << setw(15) << "Channels:" << nchan() << endl;
960 String tmp;
961 oss << setw(15) << "Observer:"
962 << table_.keywordSet().asString("Observer") << endl;
963 oss << setw(15) << "Obs Date:" << getTime(-1,true) << endl;
964 table_.keywordSet().get("Project", tmp);
965 oss << setw(15) << "Project:" << tmp << endl;
966 table_.keywordSet().get("Obstype", tmp);
967 oss << setw(15) << "Obs. Type:" << tmp << endl;
968 table_.keywordSet().get("AntennaName", tmp);
969 oss << setw(15) << "Antenna Name:" << tmp << endl;
970 table_.keywordSet().get("FluxUnit", tmp);
971 oss << setw(15) << "Flux Unit:" << tmp << endl;
972 //Vector<Double> vec(moleculeTable_.getRestFrequencies());
973 int nid = moleculeTable_.nrow();
974 Bool firstline = True;
975 oss << setw(15) << "Rest Freqs:";
976 for (int i=0; i<nid; i++) {
977 Table t = table_(table_.col("MOLECULE_ID") == i);
978 if (t.nrow() > 0) {
979 Vector<Double> vec(moleculeTable_.getRestFrequency(i));
980 if (vec.nelements() > 0) {
981 if (firstline) {
982 oss << setprecision(10) << vec << " [Hz]" << endl;
983 firstline=False;
984 }
985 else{
986 oss << setw(15)<<" " << setprecision(10) << vec << " [Hz]" << endl;
987 }
988 } else {
989 oss << "none" << endl;
990 }
991 }
992 }
993
994 oss << setw(15) << "Abcissa:" << getAbcissaLabel(0) << endl;
995 oss << selector_.print() << endl;
996 oss << endl;
997 // main table
998 String dirtype = "Position ("
999 + getDirectionRefString()
1000 + ")";
1001 oss << setw(5) << "Scan" << setw(15) << "Source"
1002 << setw(10) << "Time" << setw(18) << "Integration"
1003 << setw(15) << "Source Type" << endl;
1004 oss << setw(5) << "" << setw(5) << "Beam" << setw(3) << "" << dirtype << endl;
1005 oss << setw(10) << "" << setw(3) << "IF" << setw(3) << ""
1006 << setw(8) << "Frame" << setw(16)
1007 << "RefVal" << setw(10) << "RefPix" << setw(12) << "Increment"
1008 << setw(7) << "Channels"
1009 << endl;
1010 oss << asap::SEPERATOR << endl;
1011 TableIterator iter(table_, "SCANNO");
1012 while (!iter.pastEnd()) {
1013 Table subt = iter.table();
1014 ROTableRow row(subt);
1015 MEpoch::ROScalarColumn timeCol(subt,"TIME");
1016 const TableRecord& rec = row.get(0);
1017 oss << setw(4) << std::right << rec.asuInt("SCANNO")
1018 << std::left << setw(1) << ""
1019 << setw(15) << rec.asString("SRCNAME")
1020 << setw(10) << formatTime(timeCol(0), false);
1021 // count the cycles in the scan
1022 TableIterator cyciter(subt, "CYCLENO");
1023 int nint = 0;
1024 while (!cyciter.pastEnd()) {
1025 ++nint;
1026 ++cyciter;
1027 }
1028 oss << setw(3) << std::right << nint << setw(3) << " x " << std::left
1029 << setw(11) << formatSec(rec.asFloat("INTERVAL")) << setw(1) << ""
1030 << setw(15) << SrcType::getName(rec.asInt("SRCTYPE")) << endl;
1031
1032 TableIterator biter(subt, "BEAMNO");
1033 while (!biter.pastEnd()) {
1034 Table bsubt = biter.table();
1035 ROTableRow brow(bsubt);
1036 const TableRecord& brec = brow.get(0);
1037 uInt row0 = bsubt.rowNumbers(table_)[0];
1038 oss << setw(5) << "" << setw(4) << std::right << brec.asuInt("BEAMNO")<< std::left;
1039 oss << setw(4) << "" << formatDirection(getDirection(row0)) << endl;
1040 TableIterator iiter(bsubt, "IFNO");
1041 while (!iiter.pastEnd()) {
1042 Table isubt = iiter.table();
1043 ROTableRow irow(isubt);
1044 const TableRecord& irec = irow.get(0);
1045 oss << setw(9) << "";
1046 oss << setw(3) << std::right << irec.asuInt("IFNO") << std::left
1047 << setw(1) << "" << frequencies().print(irec.asuInt("FREQ_ID"))
1048 << setw(3) << "" << nchan(irec.asuInt("IFNO"))
1049 << endl;
1050
1051 ++iiter;
1052 }
1053 ++biter;
1054 }
1055 ++iter;
1056 }
1057 /// @todo implement verbose mode
1058 return String(oss);
1059}
1060
1061// std::string Scantable::getTime(int whichrow, bool showdate) const
1062// {
1063// MEpoch::ROScalarColumn timeCol(table_, "TIME");
1064// MEpoch me;
1065// if (whichrow > -1) {
1066// me = timeCol(uInt(whichrow));
1067// } else {
1068// Double tm;
1069// table_.keywordSet().get("UTC",tm);
1070// me = MEpoch(MVEpoch(tm));
1071// }
1072// return formatTime(me, showdate);
1073// }
1074
1075std::string Scantable::getTime(int whichrow, bool showdate, uInt prec) const
1076{
1077 MEpoch me;
1078 me = getEpoch(whichrow);
1079 return formatTime(me, showdate, prec);
1080}
1081
1082MEpoch Scantable::getEpoch(int whichrow) const
1083{
1084 if (whichrow > -1) {
1085 return timeCol_(uInt(whichrow));
1086 } else {
1087 Double tm;
1088 table_.keywordSet().get("UTC",tm);
1089 return MEpoch(MVEpoch(tm));
1090 }
1091}
1092
1093std::string Scantable::getDirectionString(int whichrow) const
1094{
1095 return formatDirection(getDirection(uInt(whichrow)));
1096}
1097
1098
1099SpectralCoordinate Scantable::getSpectralCoordinate(int whichrow) const {
1100 const MPosition& mp = getAntennaPosition();
1101 const MDirection& md = getDirection(whichrow);
1102 const MEpoch& me = timeCol_(whichrow);
1103 //Double rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
1104 Vector<Double> rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
1105 return freqTable_.getSpectralCoordinate(md, mp, me, rf,
1106 mfreqidCol_(whichrow));
1107}
1108
1109std::vector< double > Scantable::getAbcissa( int whichrow ) const
1110{
1111 if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal row number"));
1112 std::vector<double> stlout;
1113 int nchan = specCol_(whichrow).nelements();
1114 String us = freqTable_.getUnitString();
1115 if ( us == "" || us == "pixel" || us == "channel" ) {
1116 for (int i=0; i<nchan; ++i) {
1117 stlout.push_back(double(i));
1118 }
1119 return stlout;
1120 }
1121 SpectralCoordinate spc = getSpectralCoordinate(whichrow);
1122 Vector<Double> pixel(nchan);
1123 Vector<Double> world;
1124 indgen(pixel);
1125 if ( Unit(us) == Unit("Hz") ) {
1126 for ( int i=0; i < nchan; ++i) {
1127 Double world;
1128 spc.toWorld(world, pixel[i]);
1129 stlout.push_back(double(world));
1130 }
1131 } else if ( Unit(us) == Unit("km/s") ) {
1132 Vector<Double> world;
1133 spc.pixelToVelocity(world, pixel);
1134 world.tovector(stlout);
1135 }
1136 return stlout;
1137}
1138void Scantable::setDirectionRefString( const std::string & refstr )
1139{
1140 MDirection::Types mdt;
1141 if (refstr != "" && !MDirection::getType(mdt, refstr)) {
1142 throw(AipsError("Illegal Direction frame."));
1143 }
1144 if ( refstr == "" ) {
1145 String defaultstr = MDirection::showType(dirCol_.getMeasRef().getType());
1146 table_.rwKeywordSet().define("DIRECTIONREF", defaultstr);
1147 } else {
1148 table_.rwKeywordSet().define("DIRECTIONREF", String(refstr));
1149 }
1150}
1151
1152std::string Scantable::getDirectionRefString( ) const
1153{
1154 return table_.keywordSet().asString("DIRECTIONREF");
1155}
1156
1157MDirection Scantable::getDirection(int whichrow ) const
1158{
1159 String usertype = table_.keywordSet().asString("DIRECTIONREF");
1160 String type = MDirection::showType(dirCol_.getMeasRef().getType());
1161 if ( usertype != type ) {
1162 MDirection::Types mdt;
1163 if (!MDirection::getType(mdt, usertype)) {
1164 throw(AipsError("Illegal Direction frame."));
1165 }
1166 return dirCol_.convert(uInt(whichrow), mdt);
1167 } else {
1168 return dirCol_(uInt(whichrow));
1169 }
1170}
1171
1172std::string Scantable::getAbcissaLabel( int whichrow ) const
1173{
1174 if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal ro number"));
1175 const MPosition& mp = getAntennaPosition();
1176 const MDirection& md = getDirection(whichrow);
1177 const MEpoch& me = timeCol_(whichrow);
1178 //const Double& rf = mmolidCol_(whichrow);
1179 const Vector<Double> rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
1180 SpectralCoordinate spc =
1181 freqTable_.getSpectralCoordinate(md, mp, me, rf, mfreqidCol_(whichrow));
1182
1183 String s = "Channel";
1184 Unit u = Unit(freqTable_.getUnitString());
1185 if (u == Unit("km/s")) {
1186 s = CoordinateUtil::axisLabel(spc, 0, True,True, True);
1187 } else if (u == Unit("Hz")) {
1188 Vector<String> wau(1);wau = u.getName();
1189 spc.setWorldAxisUnits(wau);
1190 s = CoordinateUtil::axisLabel(spc, 0, True, True, False);
1191 }
1192 return s;
1193
1194}
1195
1196/**
1197void asap::Scantable::setRestFrequencies( double rf, const std::string& name,
1198 const std::string& unit )
1199**/
1200void Scantable::setRestFrequencies( vector<double> rf, const vector<std::string>& name,
1201 const std::string& unit )
1202
1203{
1204 ///@todo lookup in line table to fill in name and formattedname
1205 Unit u(unit);
1206 //Quantum<Double> urf(rf, u);
1207 Quantum<Vector<Double> >urf(rf, u);
1208 Vector<String> formattedname(0);
1209 //cerr<<"Scantable::setRestFrequnecies="<<urf<<endl;
1210
1211 //uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), name, "");
1212 uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), mathutil::toVectorString(name), formattedname);
1213 TableVector<uInt> tabvec(table_, "MOLECULE_ID");
1214 tabvec = id;
1215}
1216
1217/**
1218void asap::Scantable::setRestFrequencies( const std::string& name )
1219{
1220 throw(AipsError("setRestFrequencies( const std::string& name ) NYI"));
1221 ///@todo implement
1222}
1223**/
1224
1225void Scantable::setRestFrequencies( const vector<std::string>& name )
1226{
1227 throw(AipsError("setRestFrequencies( const vector<std::string>& name ) NYI"));
1228 ///@todo implement
1229}
1230
1231std::vector< unsigned int > Scantable::rownumbers( ) const
1232{
1233 std::vector<unsigned int> stlout;
1234 Vector<uInt> vec = table_.rowNumbers();
1235 vec.tovector(stlout);
1236 return stlout;
1237}
1238
1239
1240Matrix<Float> Scantable::getPolMatrix( uInt whichrow ) const
1241{
1242 ROTableRow row(table_);
1243 const TableRecord& rec = row.get(whichrow);
1244 Table t =
1245 originalTable_( originalTable_.col("SCANNO") == Int(rec.asuInt("SCANNO"))
1246 && originalTable_.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
1247 && originalTable_.col("IFNO") == Int(rec.asuInt("IFNO"))
1248 && originalTable_.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
1249 ROArrayColumn<Float> speccol(t, "SPECTRA");
1250 return speccol.getColumn();
1251}
1252
1253std::vector< std::string > Scantable::columnNames( ) const
1254{
1255 Vector<String> vec = table_.tableDesc().columnNames();
1256 return mathutil::tovectorstring(vec);
1257}
1258
1259MEpoch::Types Scantable::getTimeReference( ) const
1260{
1261 return MEpoch::castType(timeCol_.getMeasRef().getType());
1262}
1263
1264void Scantable::addFit( const STFitEntry& fit, int row )
1265{
1266 //cout << mfitidCol_(uInt(row)) << endl;
1267 LogIO os( LogOrigin( "Scantable", "addFit()", WHERE ) ) ;
1268 os << mfitidCol_(uInt(row)) << LogIO::POST ;
1269 uInt id = fitTable_.addEntry(fit, mfitidCol_(uInt(row)));
1270 mfitidCol_.put(uInt(row), id);
1271}
1272
1273void Scantable::shift(int npix)
1274{
1275 Vector<uInt> fids(mfreqidCol_.getColumn());
1276 genSort( fids, Sort::Ascending,
1277 Sort::QuickSort|Sort::NoDuplicates );
1278 for (uInt i=0; i<fids.nelements(); ++i) {
1279 frequencies().shiftRefPix(npix, fids[i]);
1280 }
1281}
1282
1283String Scantable::getAntennaName() const
1284{
1285 String out;
1286 table_.keywordSet().get("AntennaName", out);
1287 String::size_type pos1 = out.find("@") ;
1288 String::size_type pos2 = out.find("//") ;
1289 if ( pos2 != String::npos )
1290 out = out.substr(pos2+2,pos1-pos2-2) ;
1291 else if ( pos1 != String::npos )
1292 out = out.substr(0,pos1) ;
1293 return out;
1294}
1295
1296int Scantable::checkScanInfo(const std::vector<int>& scanlist) const
1297{
1298 String tbpath;
1299 int ret = 0;
1300 if ( table_.keywordSet().isDefined("GBT_GO") ) {
1301 table_.keywordSet().get("GBT_GO", tbpath);
1302 Table t(tbpath,Table::Old);
1303 // check each scan if other scan of the pair exist
1304 int nscan = scanlist.size();
1305 for (int i = 0; i < nscan; i++) {
1306 Table subt = t( t.col("SCAN") == scanlist[i]+1 );
1307 if (subt.nrow()==0) {
1308 //cerr <<"Scan "<<scanlist[i]<<" cannot be found in the scantable."<<endl;
1309 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1310 os <<LogIO::WARN<<"Scan "<<scanlist[i]<<" cannot be found in the scantable."<<LogIO::POST;
1311 ret = 1;
1312 break;
1313 }
1314 ROTableRow row(subt);
1315 const TableRecord& rec = row.get(0);
1316 int scan1seqn = rec.asuInt("PROCSEQN");
1317 int laston1 = rec.asuInt("LASTON");
1318 if ( rec.asuInt("PROCSIZE")==2 ) {
1319 if ( i < nscan-1 ) {
1320 Table subt2 = t( t.col("SCAN") == scanlist[i+1]+1 );
1321 if ( subt2.nrow() == 0) {
1322 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1323
1324 //cerr<<"Scan "<<scanlist[i+1]<<" cannot be found in the scantable."<<endl;
1325 os<<LogIO::WARN<<"Scan "<<scanlist[i+1]<<" cannot be found in the scantable."<<LogIO::POST;
1326 ret = 1;
1327 break;
1328 }
1329 ROTableRow row2(subt2);
1330 const TableRecord& rec2 = row2.get(0);
1331 int scan2seqn = rec2.asuInt("PROCSEQN");
1332 int laston2 = rec2.asuInt("LASTON");
1333 if (scan1seqn == 1 && scan2seqn == 2) {
1334 if (laston1 == laston2) {
1335 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1336 //cerr<<"A valid scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl;
1337 os<<"A valid scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<LogIO::POST;
1338 i +=1;
1339 }
1340 else {
1341 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1342 //cerr<<"Incorrect scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl;
1343 os<<LogIO::WARN<<"Incorrect scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<LogIO::POST;
1344 }
1345 }
1346 else if (scan1seqn==2 && scan2seqn == 1) {
1347 if (laston1 == laston2) {
1348 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1349 //cerr<<"["<<scanlist[i]<<","<<scanlist[i+1]<<"] is a valid scan pair but in incorrect order."<<endl;
1350 os<<LogIO::WARN<<"["<<scanlist[i]<<","<<scanlist[i+1]<<"] is a valid scan pair but in incorrect order."<<LogIO::POST;
1351 ret = 1;
1352 break;
1353 }
1354 }
1355 else {
1356 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1357 //cerr<<"The other scan for "<<scanlist[i]<<" appears to be missing. Check the input scan numbers."<<endl;
1358 os<<LogIO::WARN<<"The other scan for "<<scanlist[i]<<" appears to be missing. Check the input scan numbers."<<LogIO::POST;
1359 ret = 1;
1360 break;
1361 }
1362 }
1363 }
1364 else {
1365 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1366 //cerr<<"The scan does not appear to be standard obsevation."<<endl;
1367 os<<LogIO::WARN<<"The scan does not appear to be standard obsevation."<<LogIO::POST;
1368 }
1369 //if ( i >= nscan ) break;
1370 }
1371 }
1372 else {
1373 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1374 //cerr<<"No reference to GBT_GO table."<<endl;
1375 os<<LogIO::WARN<<"No reference to GBT_GO table."<<LogIO::POST;
1376 ret = 1;
1377 }
1378 return ret;
1379}
1380
1381std::vector<double> Scantable::getDirectionVector(int whichrow) const
1382{
1383 Vector<Double> Dir = dirCol_(whichrow).getAngle("rad").getValue();
1384 std::vector<double> dir;
1385 Dir.tovector(dir);
1386 return dir;
1387}
1388
1389void asap::Scantable::reshapeSpectrum( int nmin, int nmax )
1390 throw( casa::AipsError )
1391{
1392 // assumed that all rows have same nChan
1393 Vector<Float> arr = specCol_( 0 ) ;
1394 int nChan = arr.nelements() ;
1395
1396 // if nmin < 0 or nmax < 0, nothing to do
1397 if ( nmin < 0 ) {
1398 throw( casa::indexError<int>( nmin, "asap::Scantable::reshapeSpectrum: Invalid range. Negative index is specified." ) ) ;
1399 }
1400 if ( nmax < 0 ) {
1401 throw( casa::indexError<int>( nmax, "asap::Scantable::reshapeSpectrum: Invalid range. Negative index is specified." ) ) ;
1402 }
1403
1404 // if nmin > nmax, exchange values
1405 if ( nmin > nmax ) {
1406 int tmp = nmax ;
1407 nmax = nmin ;
1408 nmin = tmp ;
1409 LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1410 os << "Swap values. Applied range is ["
1411 << nmin << ", " << nmax << "]" << LogIO::POST ;
1412 }
1413
1414 // if nmin exceeds nChan, nothing to do
1415 if ( nmin >= nChan ) {
1416 throw( casa::indexError<int>( nmin, "asap::Scantable::reshapeSpectrum: Invalid range. Specified minimum exceeds nChan." ) ) ;
1417 }
1418
1419 // if nmax exceeds nChan, reset nmax to nChan
1420 if ( nmax >= nChan ) {
1421 if ( nmin == 0 ) {
1422 // nothing to do
1423 LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1424 os << "Whole range is selected. Nothing to do." << LogIO::POST ;
1425 return ;
1426 }
1427 else {
1428 LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1429 os << "Specified maximum exceeds nChan. Applied range is ["
1430 << nmin << ", " << nChan-1 << "]." << LogIO::POST ;
1431 nmax = nChan - 1 ;
1432 }
1433 }
1434
1435 // reshape specCol_ and flagCol_
1436 for ( int irow = 0 ; irow < nrow() ; irow++ ) {
1437 reshapeSpectrum( nmin, nmax, irow ) ;
1438 }
1439
1440 // update FREQUENCIES subtable
1441 Double refpix ;
1442 Double refval ;
1443 Double increment ;
1444 int freqnrow = freqTable_.table().nrow() ;
1445 Vector<uInt> oldId( freqnrow ) ;
1446 Vector<uInt> newId( freqnrow ) ;
1447 for ( int irow = 0 ; irow < freqnrow ; irow++ ) {
1448 freqTable_.getEntry( refpix, refval, increment, irow ) ;
1449 /***
1450 * need to shift refpix to nmin
1451 * note that channel nmin in old index will be channel 0 in new one
1452 ***/
1453 refval = refval - ( refpix - nmin ) * increment ;
1454 refpix = 0 ;
1455 freqTable_.setEntry( refpix, refval, increment, irow ) ;
1456 }
1457
1458 // update nchan
1459 int newsize = nmax - nmin + 1 ;
1460 table_.rwKeywordSet().define( "nChan", newsize ) ;
1461
1462 // update bandwidth
1463 // assumed all spectra in the scantable have same bandwidth
1464 table_.rwKeywordSet().define( "Bandwidth", increment * newsize ) ;
1465
1466 return ;
1467}
1468
1469void asap::Scantable::reshapeSpectrum( int nmin, int nmax, int irow )
1470{
1471 // reshape specCol_ and flagCol_
1472 Vector<Float> oldspec = specCol_( irow ) ;
1473 Vector<uChar> oldflag = flagsCol_( irow ) ;
1474 uInt newsize = nmax - nmin + 1 ;
1475 specCol_.put( irow, oldspec( Slice( nmin, newsize, 1 ) ) ) ;
1476 flagsCol_.put( irow, oldflag( Slice( nmin, newsize, 1 ) ) ) ;
1477
1478 return ;
1479}
1480
1481void asap::Scantable::regridChannel( int nChan, double dnu )
1482{
1483 LogIO os( LogOrigin( "Scantable", "regridChannel()", WHERE ) ) ;
1484 os << "Regrid abcissa with channel number " << nChan << " and spectral resoultion " << dnu << "Hz." << LogIO::POST ;
1485 // assumed that all rows have same nChan
1486 Vector<Float> arr = specCol_( 0 ) ;
1487 int oldsize = arr.nelements() ;
1488
1489 // if oldsize == nChan, nothing to do
1490 if ( oldsize == nChan ) {
1491 os << "Specified channel number is same as current one. Nothing to do." << LogIO::POST ;
1492 return ;
1493 }
1494
1495 // if oldChan < nChan, unphysical operation
1496 if ( oldsize < nChan ) {
1497 os << "Unphysical operation. Nothing to do." << LogIO::POST ;
1498 return ;
1499 }
1500
1501 // change channel number for specCol_ and flagCol_
1502 Vector<Float> newspec( nChan, 0 ) ;
1503 Vector<uChar> newflag( nChan, false ) ;
1504 vector<string> coordinfo = getCoordInfo() ;
1505 string oldinfo = coordinfo[0] ;
1506 coordinfo[0] = "Hz" ;
1507 setCoordInfo( coordinfo ) ;
1508 for ( int irow = 0 ; irow < nrow() ; irow++ ) {
1509 regridChannel( nChan, dnu, irow ) ;
1510 }
1511 coordinfo[0] = oldinfo ;
1512 setCoordInfo( coordinfo ) ;
1513
1514
1515 // NOTE: this method does not update metadata such as
1516 // FREQUENCIES subtable, nChan, Bandwidth, etc.
1517
1518 return ;
1519}
1520
1521void asap::Scantable::regridChannel( int nChan, double dnu, int irow )
1522{
1523 // logging
1524 //ofstream ofs( "average.log", std::ios::out | std::ios::app ) ;
1525 //ofs << "IFNO = " << getIF( irow ) << " irow = " << irow << endl ;
1526
1527 Vector<Float> oldspec = specCol_( irow ) ;
1528 Vector<uChar> oldflag = flagsCol_( irow ) ;
1529 Vector<Float> newspec( nChan, 0 ) ;
1530 Vector<uChar> newflag( nChan, false ) ;
1531
1532 // regrid
1533 vector<double> abcissa = getAbcissa( irow ) ;
1534 int oldsize = abcissa.size() ;
1535 double olddnu = abcissa[1] - abcissa[0] ;
1536 //int refChan = 0 ;
1537 //double frac = 0.0 ;
1538 //double wedge = 0.0 ;
1539 //double pile = 0.0 ;
1540 int ichan = 0 ;
1541 double wsum = 0.0 ;
1542 Vector<Float> z( nChan ) ;
1543 z[0] = abcissa[0] - 0.5 * olddnu + 0.5 * dnu ;
1544 for ( int ii = 1 ; ii < nChan ; ii++ )
1545 z[ii] = z[ii-1] + dnu ;
1546 Vector<Float> zi( nChan+1 ) ;
1547 Vector<Float> yi( oldsize + 1 ) ;
1548 zi[0] = z[0] - 0.5 * dnu ;
1549 zi[1] = z[0] + 0.5 * dnu ;
1550 for ( int ii = 2 ; ii < nChan ; ii++ )
1551 zi[ii] = zi[ii-1] + dnu ;
1552 zi[nChan] = z[nChan-1] + 0.5 * dnu ;
1553 yi[0] = abcissa[0] - 0.5 * olddnu ;
1554 yi[1] = abcissa[1] + 0.5 * olddnu ;
1555 for ( int ii = 2 ; ii < oldsize ; ii++ )
1556 yi[ii] = abcissa[ii-1] + olddnu ;
1557 yi[oldsize] = abcissa[oldsize-1] + 0.5 * olddnu ;
1558 if ( dnu > 0.0 ) {
1559 for ( int ii = 0 ; ii < nChan ; ii++ ) {
1560 double zl = zi[ii] ;
1561 double zr = zi[ii+1] ;
1562 for ( int j = ichan ; j < oldsize ; j++ ) {
1563 double yl = yi[j] ;
1564 double yr = yi[j+1] ;
1565 if ( yl <= zl ) {
1566 if ( yr <= zl ) {
1567 continue ;
1568 }
1569 else if ( yr <= zr ) {
1570 newspec[ii] += oldspec[j] * ( yr - zl ) ;
1571 newflag[ii] = newflag[ii] || oldflag[j] ;
1572 wsum += ( yr - zl ) ;
1573 }
1574 else {
1575 newspec[ii] += oldspec[j] * dnu ;
1576 newflag[ii] = newflag[ii] || oldflag[j] ;
1577 wsum += dnu ;
1578 ichan = j ;
1579 break ;
1580 }
1581 }
1582 else if ( yl < zr ) {
1583 if ( yr <= zr ) {
1584 newspec[ii] += oldspec[j] * ( yr - yl ) ;
1585 newflag[ii] = newflag[ii] || oldflag[j] ;
1586 wsum += ( yr - yl ) ;
1587 }
1588 else {
1589 newspec[ii] += oldspec[j] * ( zr - yl ) ;
1590 newflag[ii] = newflag[ii] || oldflag[j] ;
1591 wsum += ( zr - yl ) ;
1592 ichan = j ;
1593 break ;
1594 }
1595 }
1596 else {
1597 ichan = j - 1 ;
1598 break ;
1599 }
1600 }
1601 newspec[ii] /= wsum ;
1602 wsum = 0.0 ;
1603 }
1604 }
1605 else if ( dnu < 0.0 ) {
1606 for ( int ii = 0 ; ii < nChan ; ii++ ) {
1607 double zl = zi[ii] ;
1608 double zr = zi[ii+1] ;
1609 for ( int j = ichan ; j < oldsize ; j++ ) {
1610 double yl = yi[j] ;
1611 double yr = yi[j+1] ;
1612 if ( yl >= zl ) {
1613 if ( yr >= zl ) {
1614 continue ;
1615 }
1616 else if ( yr >= zr ) {
1617 newspec[ii] += oldspec[j] * abs( yr - zl ) ;
1618 newflag[ii] = newflag[ii] || oldflag[j] ;
1619 wsum += abs( yr - zl ) ;
1620 }
1621 else {
1622 newspec[ii] += oldspec[j] * abs( dnu ) ;
1623 newflag[ii] = newflag[ii] || oldflag[j] ;
1624 wsum += abs( dnu ) ;
1625 ichan = j ;
1626 break ;
1627 }
1628 }
1629 else if ( yl > zr ) {
1630 if ( yr >= zr ) {
1631 newspec[ii] += oldspec[j] * abs( yr - yl ) ;
1632 newflag[ii] = newflag[ii] || oldflag[j] ;
1633 wsum += abs( yr - yl ) ;
1634 }
1635 else {
1636 newspec[ii] += oldspec[j] * abs( zr - yl ) ;
1637 newflag[ii] = newflag[ii] || oldflag[j] ;
1638 wsum += abs( zr - yl ) ;
1639 ichan = j ;
1640 break ;
1641 }
1642 }
1643 else {
1644 ichan = j - 1 ;
1645 break ;
1646 }
1647 }
1648 newspec[ii] /= wsum ;
1649 wsum = 0.0 ;
1650 }
1651 }
1652// * ichan = 0
1653// ***/
1654// //ofs << "olddnu = " << olddnu << ", dnu = " << dnu << endl ;
1655// pile += dnu ;
1656// wedge = olddnu * ( refChan + 1 ) ;
1657// while ( wedge < pile ) {
1658// newspec[0] += olddnu * oldspec[refChan] ;
1659// newflag[0] = newflag[0] || oldflag[refChan] ;
1660// //ofs << "channel " << refChan << " is included in new channel 0" << endl ;
1661// refChan++ ;
1662// wedge += olddnu ;
1663// wsum += olddnu ;
1664// //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
1665// }
1666// frac = ( wedge - pile ) / olddnu ;
1667// wsum += ( 1.0 - frac ) * olddnu ;
1668// newspec[0] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
1669// newflag[0] = newflag[0] || oldflag[refChan] ;
1670// //ofs << "channel " << refChan << " is partly included in new channel 0" << " with fraction of " << ( 1.0 - frac ) << endl ;
1671// //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
1672// newspec[0] /= wsum ;
1673// //ofs << "newspec[0] = " << newspec[0] << endl ;
1674// //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
1675
1676// /***
1677// * ichan = 1 - nChan-2
1678// ***/
1679// for ( int ichan = 1 ; ichan < nChan - 1 ; ichan++ ) {
1680// pile += dnu ;
1681// newspec[ichan] += frac * olddnu * oldspec[refChan] ;
1682// newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
1683// //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << frac << endl ;
1684// refChan++ ;
1685// wedge += olddnu ;
1686// wsum = frac * olddnu ;
1687// //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
1688// while ( wedge < pile ) {
1689// newspec[ichan] += olddnu * oldspec[refChan] ;
1690// newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
1691// //ofs << "channel " << refChan << " is included in new channel " << ichan << endl ;
1692// refChan++ ;
1693// wedge += olddnu ;
1694// wsum += olddnu ;
1695// //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
1696// }
1697// frac = ( wedge - pile ) / olddnu ;
1698// wsum += ( 1.0 - frac ) * olddnu ;
1699// newspec[ichan] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
1700// newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
1701// //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << ( 1.0 - frac ) << endl ;
1702// //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
1703// //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
1704// newspec[ichan] /= wsum ;
1705// //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << endl ;
1706// }
1707
1708// /***
1709// * ichan = nChan-1
1710// ***/
1711// // NOTE: Assumed that all spectra have the same bandwidth
1712// pile += dnu ;
1713// newspec[nChan-1] += frac * olddnu * oldspec[refChan] ;
1714// newflag[nChan-1] = newflag[nChan-1] || oldflag[refChan] ;
1715// //ofs << "channel " << refChan << " is partly included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
1716// refChan++ ;
1717// wedge += olddnu ;
1718// wsum = frac * olddnu ;
1719// //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
1720// for ( int jchan = refChan ; jchan < oldsize ; jchan++ ) {
1721// newspec[nChan-1] += olddnu * oldspec[jchan] ;
1722// newflag[nChan-1] = newflag[nChan-1] || oldflag[jchan] ;
1723// wsum += olddnu ;
1724// //ofs << "channel " << jchan << " is included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
1725// //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
1726// }
1727// //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
1728// //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
1729// newspec[nChan-1] /= wsum ;
1730// //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << endl ;
1731
1732// // ofs.close() ;
1733
1734 specCol_.put( irow, newspec ) ;
1735 flagsCol_.put( irow, newflag ) ;
1736
1737 return ;
1738}
1739
1740std::vector<float> Scantable::getWeather(int whichrow) const
1741{
1742 std::vector<float> out(5);
1743 //Float temperature, pressure, humidity, windspeed, windaz;
1744 weatherTable_.getEntry(out[0], out[1], out[2], out[3], out[4],
1745 mweatheridCol_(uInt(whichrow)));
1746
1747
1748 return out;
1749}
1750
1751bool Scantable::getFlagtraFast(uInt whichrow)
1752{
1753 uChar flag;
1754 Vector<uChar> flags;
1755 flagsCol_.get(whichrow, flags);
1756 flag = flags[0];
1757 for (uInt i = 1; i < flags.size(); ++i) {
1758 flag &= flags[i];
1759 }
1760 return ((flag >> 7) == 1);
1761}
1762
1763void Scantable::polyBaseline(const std::vector<bool>& mask, int order, bool outLogger, const std::string& blfile)
1764{
1765 ofstream ofs;
1766 String coordInfo;
1767 bool hasSameNchan = true;
1768 bool outTextFile = false;
1769
1770 if (blfile != "") {
1771 ofs.open(blfile.c_str(), ios::out | ios::app);
1772 if (ofs) outTextFile = true;
1773 }
1774
1775 if (outLogger || outTextFile) {
1776 coordInfo = getCoordInfo()[0];
1777 if (coordInfo == "") coordInfo = "channel";
1778 hasSameNchan = hasSameNchanOverIFs();
1779 }
1780
1781 Fitter fitter = Fitter();
1782 fitter.setExpression("poly", order);
1783
1784 int nRow = nrow();
1785 std::vector<bool> chanMask;
1786
1787 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
1788 chanMask = getCompositeChanMask(whichrow, mask);
1789 fitBaseline(chanMask, whichrow, fitter);
1790 setSpectrum(fitter.getResidual(), whichrow);
1791 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "polyBaseline()", fitter);
1792 }
1793
1794 if (outTextFile) ofs.close();
1795}
1796
1797void Scantable::autoPolyBaseline(const std::vector<bool>& mask, int order, const std::vector<int>& edge, float threshold, int chanAvgLimit, bool outLogger, const std::string& blfile)
1798{
1799 ofstream ofs;
1800 String coordInfo;
1801 bool hasSameNchan = true;
1802 bool outTextFile = false;
1803
1804 if (blfile != "") {
1805 ofs.open(blfile.c_str(), ios::out | ios::app);
1806 if (ofs) outTextFile = true;
1807 }
1808
1809 if (outLogger || outTextFile) {
1810 coordInfo = getCoordInfo()[0];
1811 if (coordInfo == "") coordInfo = "channel";
1812 hasSameNchan = hasSameNchanOverIFs();
1813 }
1814
1815 Fitter fitter = Fitter();
1816 fitter.setExpression("poly", order);
1817
1818 int nRow = nrow();
1819 std::vector<bool> chanMask;
1820 int minEdgeSize = getIFNos().size()*2;
1821 STLineFinder lineFinder = STLineFinder();
1822 lineFinder.setOptions(threshold, 3, chanAvgLimit);
1823
1824 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
1825
1826 //-------------------------------------------------------
1827 //chanMask = getCompositeChanMask(whichrow, mask, edge, minEdgeSize, lineFinder);
1828 //-------------------------------------------------------
1829 int edgeSize = edge.size();
1830 std::vector<int> currentEdge;
1831 if (edgeSize >= 2) {
1832 int idx = 0;
1833 if (edgeSize > 2) {
1834 if (edgeSize < minEdgeSize) {
1835 throw(AipsError("Length of edge element info is less than that of IFs"));
1836 }
1837 idx = 2 * getIF(whichrow);
1838 }
1839 currentEdge.push_back(edge[idx]);
1840 currentEdge.push_back(edge[idx+1]);
1841 } else {
1842 throw(AipsError("Wrong length of edge element"));
1843 }
1844 lineFinder.setData(getSpectrum(whichrow));
1845 lineFinder.findLines(getCompositeChanMask(whichrow, mask), currentEdge, whichrow);
1846 chanMask = lineFinder.getMask();
1847 //-------------------------------------------------------
1848
1849 fitBaseline(chanMask, whichrow, fitter);
1850 setSpectrum(fitter.getResidual(), whichrow);
1851
1852 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "autoPolyBaseline()", fitter);
1853 }
1854
1855 if (outTextFile) ofs.close();
1856}
1857
1858void Scantable::cubicSplineBaseline(const std::vector<bool>& mask, int nPiece, float thresClip, int nIterClip, bool outLogger, const std::string& blfile) {
1859 ofstream ofs;
1860 String coordInfo;
1861 bool hasSameNchan = true;
1862 bool outTextFile = false;
1863
1864 if (blfile != "") {
1865 ofs.open(blfile.c_str(), ios::out | ios::app);
1866 if (ofs) outTextFile = true;
1867 }
1868
1869 if (outLogger || outTextFile) {
1870 coordInfo = getCoordInfo()[0];
1871 if (coordInfo == "") coordInfo = "channel";
1872 hasSameNchan = hasSameNchanOverIFs();
1873 }
1874
1875 //Fitter fitter = Fitter();
1876 //fitter.setExpression("cspline", nPiece);
1877
1878 int nRow = nrow();
1879 std::vector<bool> chanMask;
1880
1881 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
1882 chanMask = getCompositeChanMask(whichrow, mask);
1883 //fitBaseline(chanMask, whichrow, fitter, thresClip, nIterClip);
1884 //setSpectrum(fitter.getResidual(), whichrow);
1885 std::vector<int> pieceRanges;
1886 std::vector<float> params;
1887 std::vector<float> res = doCubicSplineFitting(getSpectrum(whichrow), chanMask, pieceRanges, params, nPiece, thresClip, nIterClip);
1888 setSpectrum(res, whichrow);
1889 //
1890
1891 std::vector<bool> fixed;
1892 fixed.clear();
1893 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "cubicSplineBaseline()", pieceRanges, params, fixed);
1894 }
1895
1896 if (outTextFile) ofs.close();
1897}
1898
1899void Scantable::autoCubicSplineBaseline(const std::vector<bool>& mask, int nPiece, float thresClip, int nIterClip, const std::vector<int>& edge, float threshold, int chanAvgLimit, bool outLogger, const std::string& blfile)
1900{
1901 ofstream ofs;
1902 String coordInfo;
1903 bool hasSameNchan = true;
1904 bool outTextFile = false;
1905
1906 if (blfile != "") {
1907 ofs.open(blfile.c_str(), ios::out | ios::app);
1908 if (ofs) outTextFile = true;
1909 }
1910
1911 if (outLogger || outTextFile) {
1912 coordInfo = getCoordInfo()[0];
1913 if (coordInfo == "") coordInfo = "channel";
1914 hasSameNchan = hasSameNchanOverIFs();
1915 }
1916
1917 //Fitter fitter = Fitter();
1918 //fitter.setExpression("cspline", nPiece);
1919
1920 int nRow = nrow();
1921 std::vector<bool> chanMask;
1922 int minEdgeSize = getIFNos().size()*2;
1923 STLineFinder lineFinder = STLineFinder();
1924 lineFinder.setOptions(threshold, 3, chanAvgLimit);
1925
1926 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
1927
1928 //-------------------------------------------------------
1929 //chanMask = getCompositeChanMask(whichrow, mask, edge, minEdgeSize, lineFinder);
1930 //-------------------------------------------------------
1931 int edgeSize = edge.size();
1932 std::vector<int> currentEdge;
1933 if (edgeSize >= 2) {
1934 int idx = 0;
1935 if (edgeSize > 2) {
1936 if (edgeSize < minEdgeSize) {
1937 throw(AipsError("Length of edge element info is less than that of IFs"));
1938 }
1939 idx = 2 * getIF(whichrow);
1940 }
1941 currentEdge.push_back(edge[idx]);
1942 currentEdge.push_back(edge[idx+1]);
1943 } else {
1944 throw(AipsError("Wrong length of edge element"));
1945 }
1946 lineFinder.setData(getSpectrum(whichrow));
1947 lineFinder.findLines(getCompositeChanMask(whichrow, mask), currentEdge, whichrow);
1948 chanMask = lineFinder.getMask();
1949 //-------------------------------------------------------
1950
1951
1952 //fitBaseline(chanMask, whichrow, fitter, thresClip, nIterClip);
1953 //setSpectrum(fitter.getResidual(), whichrow);
1954 std::vector<int> pieceRanges;
1955 std::vector<float> params;
1956 std::vector<float> res = doCubicSplineFitting(getSpectrum(whichrow), chanMask, pieceRanges, params, nPiece, thresClip, nIterClip);
1957 setSpectrum(res, whichrow);
1958 //
1959
1960 std::vector<bool> fixed;
1961 fixed.clear();
1962 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "autoCubicSplineBaseline()", pieceRanges, params, fixed);
1963 }
1964
1965 if (outTextFile) ofs.close();
1966}
1967
1968std::vector<float> Scantable::doCubicSplineFitting(const std::vector<float>& data, const std::vector<bool>& mask, std::vector<int>& sectionRanges, std::vector<float>& params, int nPiece, float thresClip, int nIterClip) {
1969 if (nPiece < 1) {
1970 throw(AipsError("wrong number of the sections for fitting"));
1971 }
1972 if (data.size() != mask.size()) {
1973 throw(AipsError("data and mask have different size"));
1974 }
1975
1976 int nChan = data.size();
1977 std::vector<int> maskArray;
1978 std::vector<int> x;
1979 for (int i = 0; i < nChan; ++i) {
1980 maskArray.push_back(mask[i] ? 1 : 0);
1981 if (mask[i]) {
1982 x.push_back(i);
1983 }
1984 }
1985
1986 int nData = x.size();
1987 int nElement = (int)(floor(floor((double)(nData/nPiece))+0.5));
1988
1989 std::vector<int> sectionList0, sectionList1;
1990 std::vector<double> sectionListR;
1991 sectionList0.push_back(x[0]);
1992 sectionRanges.clear();
1993 sectionRanges.push_back(x[0]);
1994 for (int i = 1; i < nPiece; ++i) {
1995 int valX = x[nElement*i];
1996 sectionList0.push_back(valX);
1997 sectionList1.push_back(valX);
1998 sectionListR.push_back(1.0/(double)valX);
1999
2000 sectionRanges.push_back(valX-1);
2001 sectionRanges.push_back(valX);
2002 }
2003 sectionList1.push_back(x[x.size()-1]+1);
2004 sectionRanges.push_back(x[x.size()-1]);
2005
2006 std::vector<double> x1, x2, x3, z1, x1z1, x2z1, x3z1, r1;
2007 for (int i = 0; i < nChan; ++i) {
2008 x1.push_back((double)i);
2009 x2.push_back((double)(i*i));
2010 x3.push_back((double)(i*i*i));
2011 z1.push_back((double)data[i]);
2012 x1z1.push_back(((double)i)*(double)data[i]);
2013 x2z1.push_back(((double)(i*i))*(double)data[i]);
2014 x3z1.push_back(((double)(i*i*i))*(double)data[i]);
2015 r1.push_back(0.0);
2016 }
2017
2018 int currentNData = nData;
2019 int nDOF = nPiece + 3; //number of parameters to solve, namely, 4+(nPiece-1).
2020
2021 for (int nClip = 0; nClip < nIterClip+1; ++nClip) {
2022 //xMatrix : horizontal concatenation of the least-sq. matrix (left) and an
2023 //identity matrix (right).
2024 //the right part is used to calculate the inverse matrix of the left part.
2025 double xMatrix[nDOF][2*nDOF];
2026 double zMatrix[nDOF];
2027 for (int i = 0; i < nDOF; ++i) {
2028 for (int j = 0; j < 2*nDOF; ++j) {
2029 xMatrix[i][j] = 0.0;
2030 }
2031 xMatrix[i][nDOF+i] = 1.0;
2032 zMatrix[i] = 0.0;
2033 }
2034
2035 for (int n = 0; n < nPiece; ++n) {
2036 for (int i = sectionList0[n]; i < sectionList1[n]; ++i) {
2037 if (maskArray[i] == 0) continue;
2038 xMatrix[0][0] += 1.0;
2039 xMatrix[0][1] += x1[i];
2040 xMatrix[0][2] += x2[i];
2041 xMatrix[0][3] += x3[i];
2042 xMatrix[1][1] += x2[i];
2043 xMatrix[1][2] += x3[i];
2044 xMatrix[1][3] += x2[i]*x2[i];
2045 xMatrix[2][2] += x2[i]*x2[i];
2046 xMatrix[2][3] += x3[i]*x2[i];
2047 xMatrix[3][3] += x3[i]*x3[i];
2048 zMatrix[0] += z1[i];
2049 zMatrix[1] += x1z1[i];
2050 zMatrix[2] += x2z1[i];
2051 zMatrix[3] += x3z1[i];
2052 for (int j = 0; j < n; ++j) {
2053 double q = 1.0 - x1[i]*sectionListR[j];
2054 q = q*q*q;
2055 xMatrix[0][j+4] += q;
2056 xMatrix[1][j+4] += q*x1[i];
2057 xMatrix[2][j+4] += q*x2[i];
2058 xMatrix[3][j+4] += q*x3[i];
2059 for (int k = 0; k < j; ++k) {
2060 double r = 1.0 - x1[i]*sectionListR[k];
2061 r = r*r*r;
2062 xMatrix[k+4][j+4] += r*q;
2063 }
2064 xMatrix[j+4][j+4] += q*q;
2065 zMatrix[j+4] += q*z1[i];
2066 }
2067 }
2068 }
2069
2070 for (int i = 0; i < nDOF; ++i) {
2071 for (int j = 0; j < i; ++j) {
2072 xMatrix[i][j] = xMatrix[j][i];
2073 }
2074 }
2075
2076 std::vector<double> invDiag;
2077 for (int i = 0; i < nDOF; ++i) {
2078 invDiag.push_back(1.0/xMatrix[i][i]);
2079 for (int j = 0; j < nDOF; ++j) {
2080 xMatrix[i][j] *= invDiag[i];
2081 }
2082 }
2083
2084 for (int k = 0; k < nDOF; ++k) {
2085 for (int i = 0; i < nDOF; ++i) {
2086 if (i != k) {
2087 double factor1 = xMatrix[k][k];
2088 double factor2 = xMatrix[i][k];
2089 for (int j = k; j < 2*nDOF; ++j) {
2090 xMatrix[i][j] *= factor1;
2091 xMatrix[i][j] -= xMatrix[k][j]*factor2;
2092 xMatrix[i][j] /= factor1;
2093 }
2094 }
2095 }
2096 double xDiag = xMatrix[k][k];
2097 for (int j = k; j < 2*nDOF; ++j) {
2098 xMatrix[k][j] /= xDiag;
2099 }
2100 }
2101
2102 for (int i = 0; i < nDOF; ++i) {
2103 for (int j = 0; j < nDOF; ++j) {
2104 xMatrix[i][nDOF+j] *= invDiag[j];
2105 }
2106 }
2107 //compute a vector y which consists of the coefficients of the best-fit spline curves
2108 //(a0,a1,a2,a3(,b3,c3,...)), namely, the ones for the leftmost piece and the ones of
2109 //cubic terms for the other pieces (in case nPiece>1).
2110 std::vector<double> y;
2111 for (int i = 0; i < nDOF; ++i) {
2112 y.push_back(0.0);
2113 for (int j = 0; j < nDOF; ++j) {
2114 y[i] += xMatrix[i][nDOF+j]*zMatrix[j];
2115 }
2116 }
2117
2118 double a0 = y[0];
2119 double a1 = y[1];
2120 double a2 = y[2];
2121 double a3 = y[3];
2122 params.clear();
2123
2124 for (int n = 0; n < nPiece; ++n) {
2125 for (int i = sectionList0[n]; i < sectionList1[n]; ++i) {
2126 r1[i] = a0 + a1*x1[i] + a2*x2[i] + a3*x3[i];
2127 }
2128 params.push_back(a0);
2129 params.push_back(a1);
2130 params.push_back(a2);
2131 params.push_back(a3);
2132
2133 if (n == nPiece-1) break;
2134
2135 double d = y[4+n];
2136 a0 += d;
2137 a1 -= 3.0*d*sectionListR[n];
2138 a2 += 3.0*d*sectionListR[n]*sectionListR[n];
2139 a3 -= d*sectionListR[n]*sectionListR[n]*sectionListR[n];
2140 }
2141
2142 if ((nClip == nIterClip) || (thresClip <= 0.0)) {
2143 break;
2144 } else {
2145 std::vector<double> rz;
2146 double stdDev = 0.0;
2147 for (int i = 0; i < nChan; ++i) {
2148 double val = abs(r1[i] - z1[i]);
2149 rz.push_back(val);
2150 stdDev += val*val*(double)maskArray[i];
2151 }
2152 stdDev = sqrt(stdDev/(double)nData);
2153
2154 double thres = stdDev * thresClip;
2155 int newNData = 0;
2156 for (int i = 0; i < nChan; ++i) {
2157 if (rz[i] >= thres) {
2158 maskArray[i] = 0;
2159 }
2160 if (maskArray[i] > 0) {
2161 newNData++;
2162 }
2163 }
2164 if (newNData == currentNData) {
2165 break; //no additional flag. finish iteration.
2166 } else {
2167 currentNData = newNData;
2168 }
2169 }
2170 }
2171
2172 std::vector<float> residual;
2173 for (int i = 0; i < nChan; ++i) {
2174 residual.push_back((float)(z1[i] - r1[i]));
2175 }
2176 return residual;
2177
2178}
2179
2180 void Scantable::sinusoidBaseline(const std::vector<bool>& mask, int nMinWavesInSW, int nMaxWavesInSW, float thresClip, int nIterClip, bool outLogger, const std::string& blfile) {
2181 ofstream ofs;
2182 String coordInfo;
2183 bool hasSameNchan = true;
2184 bool outTextFile = false;
2185
2186 if (blfile != "") {
2187 ofs.open(blfile.c_str(), ios::out | ios::app);
2188 if (ofs) outTextFile = true;
2189 }
2190
2191 if (outLogger || outTextFile) {
2192 coordInfo = getCoordInfo()[0];
2193 if (coordInfo == "") coordInfo = "channel";
2194 hasSameNchan = hasSameNchanOverIFs();
2195 }
2196
2197 //Fitter fitter = Fitter();
2198 //fitter.setExpression("sinusoid", nMaxWavesInSW);
2199
2200 int nRow = nrow();
2201 std::vector<bool> chanMask;
2202
2203 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2204 chanMask = getCompositeChanMask(whichrow, mask);
2205 //fitBaseline(chanMask, whichrow, fitter, thresClip, nIterClip);
2206 //setSpectrum(fitter.getResidual(), whichrow);
2207 std::vector<int> pieceRanges;
2208 std::vector<float> params;
2209 std::vector<float> res = doSinusoidFitting(getSpectrum(whichrow), chanMask, nMinWavesInSW, nMaxWavesInSW, params, thresClip, nIterClip);
2210 setSpectrum(res, whichrow);
2211 //
2212
2213 std::vector<bool> fixed;
2214 fixed.clear();
2215 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "sinusoidBaseline()", pieceRanges, params, fixed);
2216 }
2217
2218 if (outTextFile) ofs.close();
2219}
2220
2221void Scantable::autoSinusoidBaseline(const std::vector<bool>& mask, int nMinWavesInSW, int nMaxWavesInSW, float thresClip, int nIterClip, const std::vector<int>& edge, float threshold, int chanAvgLimit, bool outLogger, const std::string& blfile)
2222{
2223 ofstream ofs;
2224 String coordInfo;
2225 bool hasSameNchan = true;
2226 bool outTextFile = false;
2227
2228 if (blfile != "") {
2229 ofs.open(blfile.c_str(), ios::out | ios::app);
2230 if (ofs) outTextFile = true;
2231 }
2232
2233 if (outLogger || outTextFile) {
2234 coordInfo = getCoordInfo()[0];
2235 if (coordInfo == "") coordInfo = "channel";
2236 hasSameNchan = hasSameNchanOverIFs();
2237 }
2238
2239 //Fitter fitter = Fitter();
2240 //fitter.setExpression("sinusoid", nMaxWavesInSW);
2241
2242 int nRow = nrow();
2243 std::vector<bool> chanMask;
2244 int minEdgeSize = getIFNos().size()*2;
2245 STLineFinder lineFinder = STLineFinder();
2246 lineFinder.setOptions(threshold, 3, chanAvgLimit);
2247
2248 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2249
2250 //-------------------------------------------------------
2251 //chanMask = getCompositeChanMask(whichrow, mask, edge, minEdgeSize, lineFinder);
2252 //-------------------------------------------------------
2253 int edgeSize = edge.size();
2254 std::vector<int> currentEdge;
2255 if (edgeSize >= 2) {
2256 int idx = 0;
2257 if (edgeSize > 2) {
2258 if (edgeSize < minEdgeSize) {
2259 throw(AipsError("Length of edge element info is less than that of IFs"));
2260 }
2261 idx = 2 * getIF(whichrow);
2262 }
2263 currentEdge.push_back(edge[idx]);
2264 currentEdge.push_back(edge[idx+1]);
2265 } else {
2266 throw(AipsError("Wrong length of edge element"));
2267 }
2268 lineFinder.setData(getSpectrum(whichrow));
2269 lineFinder.findLines(getCompositeChanMask(whichrow, mask), currentEdge, whichrow);
2270 chanMask = lineFinder.getMask();
2271 //-------------------------------------------------------
2272
2273
2274 //fitBaseline(chanMask, whichrow, fitter, thresClip, nIterClip);
2275 //setSpectrum(fitter.getResidual(), whichrow);
2276 std::vector<int> pieceRanges;
2277 std::vector<float> params;
2278 std::vector<float> res = doSinusoidFitting(getSpectrum(whichrow), chanMask, nMinWavesInSW, nMaxWavesInSW, params, thresClip, nIterClip);
2279 setSpectrum(res, whichrow);
2280 //
2281
2282 std::vector<bool> fixed;
2283 fixed.clear();
2284 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "autoSinusoidBaseline()", pieceRanges, params, fixed);
2285 }
2286
2287 if (outTextFile) ofs.close();
2288}
2289
2290std::vector<float> Scantable::doSinusoidFitting(const std::vector<float>& data, const std::vector<bool>& mask, int nMinWavesInSW, int nMaxWavesInSW, std::vector<float>& params, float thresClip, int nIterClip) {
2291 if (nMaxWavesInSW < 1) {
2292 throw(AipsError("maximum wave number must be a positive value"));
2293 }
2294 if (data.size() != mask.size()) {
2295 throw(AipsError("data and mask have different size"));
2296 }
2297
2298 int nChan = data.size();
2299 std::vector<int> maskArray;
2300 std::vector<int> x;
2301 for (int i = 0; i < nChan; ++i) {
2302 maskArray.push_back(mask[i] ? 1 : 0);
2303 if (mask[i]) {
2304 x.push_back(i);
2305 }
2306 }
2307
2308 int nData = x.size();
2309
2310 std::vector<double> x1, x2, x3, z1, x1z1, x2z1, x3z1, r1;
2311 for (int i = 0; i < nChan; ++i) {
2312 x1.push_back((double)i);
2313 x2.push_back((double)(i*i));
2314 x3.push_back((double)(i*i*i));
2315 z1.push_back((double)data[i]);
2316 x1z1.push_back(((double)i)*(double)data[i]);
2317 x2z1.push_back(((double)(i*i))*(double)data[i]);
2318 x3z1.push_back(((double)(i*i*i))*(double)data[i]);
2319 r1.push_back(0.0);
2320 }
2321
2322 int currentNData = nData;
2323 int nDOF = nMaxWavesInSW + 1; //number of parameters to solve.
2324
2325 for (int nClip = 0; nClip < nIterClip+1; ++nClip) {
2326 //xMatrix : horizontal concatenation of the least-sq. matrix (left) and an
2327 //identity matrix (right).
2328 //the right part is used to calculate the inverse matrix of the left part.
2329 double xMatrix[nDOF][2*nDOF];
2330 double zMatrix[nDOF];
2331 for (int i = 0; i < nDOF; ++i) {
2332 for (int j = 0; j < 2*nDOF; ++j) {
2333 xMatrix[i][j] = 0.0;
2334 }
2335 xMatrix[i][nDOF+i] = 1.0;
2336 zMatrix[i] = 0.0;
2337 }
2338
2339 for (int i = 0; i < currentNData; ++i) {
2340 if (maskArray[i] == 0) continue;
2341 xMatrix[0][0] += 1.0;
2342 xMatrix[0][1] += x1[i];
2343 xMatrix[0][2] += x2[i];
2344 xMatrix[0][3] += x3[i];
2345 xMatrix[1][1] += x2[i];
2346 xMatrix[1][2] += x3[i];
2347 xMatrix[1][3] += x2[i]*x2[i];
2348 xMatrix[2][2] += x2[i]*x2[i];
2349 xMatrix[2][3] += x3[i]*x2[i];
2350 xMatrix[3][3] += x3[i]*x3[i];
2351 zMatrix[0] += z1[i];
2352 zMatrix[1] += x1z1[i];
2353 zMatrix[2] += x2z1[i];
2354 zMatrix[3] += x3z1[i];
2355 }
2356
2357 for (int i = 0; i < nDOF; ++i) {
2358 for (int j = 0; j < i; ++j) {
2359 xMatrix[i][j] = xMatrix[j][i];
2360 }
2361 }
2362
2363 std::vector<double> invDiag;
2364 for (int i = 0; i < nDOF; ++i) {
2365 invDiag.push_back(1.0/xMatrix[i][i]);
2366 for (int j = 0; j < nDOF; ++j) {
2367 xMatrix[i][j] *= invDiag[i];
2368 }
2369 }
2370
2371 for (int k = 0; k < nDOF; ++k) {
2372 for (int i = 0; i < nDOF; ++i) {
2373 if (i != k) {
2374 double factor1 = xMatrix[k][k];
2375 double factor2 = xMatrix[i][k];
2376 for (int j = k; j < 2*nDOF; ++j) {
2377 xMatrix[i][j] *= factor1;
2378 xMatrix[i][j] -= xMatrix[k][j]*factor2;
2379 xMatrix[i][j] /= factor1;
2380 }
2381 }
2382 }
2383 double xDiag = xMatrix[k][k];
2384 for (int j = k; j < 2*nDOF; ++j) {
2385 xMatrix[k][j] /= xDiag;
2386 }
2387 }
2388
2389 for (int i = 0; i < nDOF; ++i) {
2390 for (int j = 0; j < nDOF; ++j) {
2391 xMatrix[i][nDOF+j] *= invDiag[j];
2392 }
2393 }
2394 //compute a vector y which consists of the coefficients of the sinusoids forming the
2395 //best-fit curves (a0,b0,a1,b1,...), namely, a* and b* are of sine and cosine functions,
2396 //respectively.
2397 std::vector<double> y;
2398 for (int i = 0; i < nDOF; ++i) {
2399 y.push_back(0.0);
2400 for (int j = 0; j < nDOF; ++j) {
2401 y[i] += xMatrix[i][nDOF+j]*zMatrix[j];
2402 }
2403 }
2404
2405 double a0 = y[0];
2406 double a1 = y[1];
2407 double a2 = y[2];
2408 double a3 = y[3];
2409 params.clear();
2410
2411 for (int i = 0; i < nChan; ++i) {
2412 r1[i] = a0 + a1*x1[i] + a2*x2[i] + a3*x3[i];
2413 }
2414 params.push_back(a0);
2415 params.push_back(a1);
2416 params.push_back(a2);
2417 params.push_back(a3);
2418
2419
2420 if ((nClip == nIterClip) || (thresClip <= 0.0)) {
2421 break;
2422 } else {
2423 std::vector<double> rz;
2424 double stdDev = 0.0;
2425 for (int i = 0; i < nChan; ++i) {
2426 double val = abs(r1[i] - z1[i]);
2427 rz.push_back(val);
2428 stdDev += val*val*(double)maskArray[i];
2429 }
2430 stdDev = sqrt(stdDev/(double)nData);
2431
2432 double thres = stdDev * thresClip;
2433 int newNData = 0;
2434 for (int i = 0; i < nChan; ++i) {
2435 if (rz[i] >= thres) {
2436 maskArray[i] = 0;
2437 }
2438 if (maskArray[i] > 0) {
2439 newNData++;
2440 }
2441 }
2442 if (newNData == currentNData) {
2443 break; //no additional flag. finish iteration.
2444 } else {
2445 currentNData = newNData;
2446 }
2447 }
2448 }
2449
2450 std::vector<float> residual;
2451 for (int i = 0; i < nChan; ++i) {
2452 residual.push_back((float)(z1[i] - r1[i]));
2453 }
2454 return residual;
2455
2456}
2457
2458void Scantable::fitBaseline(const std::vector<bool>& mask, int whichrow, Fitter& fitter)
2459{
2460 std::vector<double> abcsd = getAbcissa(whichrow);
2461 std::vector<float> abcs;
2462 for (uInt i = 0; i < abcsd.size(); ++i) {
2463 abcs.push_back((float)abcsd[i]);
2464 }
2465 std::vector<float> spec = getSpectrum(whichrow);
2466
2467 fitter.setData(abcs, spec, mask);
2468 fitter.lfit();
2469}
2470
2471std::vector<bool> Scantable::getCompositeChanMask(int whichrow, const std::vector<bool>& inMask)
2472{
2473 std::vector<bool> chanMask = getMask(whichrow);
2474 uInt chanMaskSize = chanMask.size();
2475 if (chanMaskSize != inMask.size()) {
2476 throw(AipsError("different mask sizes"));
2477 }
2478 for (uInt i = 0; i < chanMaskSize; ++i) {
2479 chanMask[i] = chanMask[i] && inMask[i];
2480 }
2481
2482 return chanMask;
2483}
2484
2485/*
2486std::vector<bool> Scantable::getCompositeChanMask(int whichrow, const std::vector<bool>& inMask, const std::vector<int>& edge, const int minEdgeSize, STLineFinder& lineFinder)
2487{
2488 int edgeSize = edge.size();
2489 std::vector<int> currentEdge;
2490 if (edgeSize >= 2) {
2491 int idx = 0;
2492 if (edgeSize > 2) {
2493 if (edgeSize < minEdgeSize) {
2494 throw(AipsError("Length of edge element info is less than that of IFs"));
2495 }
2496 idx = 2 * getIF(whichrow);
2497 }
2498 currentEdge.push_back(edge[idx]);
2499 currentEdge.push_back(edge[idx+1]);
2500 } else {
2501 throw(AipsError("Wrong length of edge element"));
2502 }
2503
2504 lineFinder.setData(getSpectrum(whichrow));
2505 lineFinder.findLines(getCompositeChanMask(whichrow, inMask), currentEdge, whichrow);
2506
2507 return lineFinder.getMask();
2508}
2509*/
2510
2511/* for poly. the variations of outputFittingResult() should be merged into one eventually (2011/3/10 WK) */
2512void Scantable::outputFittingResult(bool outLogger, bool outTextFile, const std::vector<bool>& chanMask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, ofstream& ofs, const casa::String& funcName, Fitter& fitter) {
2513 if (outLogger || outTextFile) {
2514 std::vector<float> params = fitter.getParameters();
2515 std::vector<bool> fixed = fitter.getFixedParameters();
2516 float rms = getRms(chanMask, whichrow);
2517 String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
2518
2519 if (outLogger) {
2520 LogIO ols(LogOrigin("Scantable", funcName, WHERE));
2521 ols << formatBaselineParams(params, fixed, rms, masklist, whichrow, false) << LogIO::POST ;
2522 }
2523 if (outTextFile) {
2524 ofs << formatBaselineParams(params, fixed, rms, masklist, whichrow, true) << flush;
2525 }
2526 }
2527}
2528
2529/* for cspline. will be merged once cspline is available in fitter (2011/3/10 WK) */
2530void Scantable::outputFittingResult(bool outLogger, bool outTextFile, const std::vector<bool>& chanMask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, ofstream& ofs, const casa::String& funcName, const std::vector<int>& pieceEdges, const std::vector<float>& params, const std::vector<bool>& fixed) {
2531 if (outLogger || outTextFile) {
2532 float rms = getRms(chanMask, whichrow);
2533 String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
2534
2535 if (outLogger) {
2536 LogIO ols(LogOrigin("Scantable", funcName, WHERE));
2537 ols << formatPiecewiseBaselineParams(pieceEdges, params, fixed, rms, masklist, whichrow, false) << LogIO::POST ;
2538 }
2539 if (outTextFile) {
2540 ofs << formatPiecewiseBaselineParams(pieceEdges, params, fixed, rms, masklist, whichrow, true) << flush;
2541 }
2542 }
2543}
2544
2545/* for sinusoid. will be merged once sinusoid is available in fitter (2011/3/10 WK) */
2546void Scantable::outputFittingResult(bool outLogger, bool outTextFile, const std::vector<bool>& chanMask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, ofstream& ofs, const casa::String& funcName, const std::vector<float>& params, const std::vector<bool>& fixed) {
2547 if (outLogger || outTextFile) {
2548 float rms = getRms(chanMask, whichrow);
2549 String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
2550
2551 if (outLogger) {
2552 LogIO ols(LogOrigin("Scantable", funcName, WHERE));
2553 ols << formatBaselineParams(params, fixed, rms, masklist, whichrow, false) << LogIO::POST ;
2554 }
2555 if (outTextFile) {
2556 ofs << formatBaselineParams(params, fixed, rms, masklist, whichrow, true) << flush;
2557 }
2558 }
2559}
2560
2561float Scantable::getRms(const std::vector<bool>& mask, int whichrow) {
2562 Vector<Float> spec;
2563 specCol_.get(whichrow, spec);
2564
2565 float mean = 0.0;
2566 float smean = 0.0;
2567 int n = 0;
2568 for (uInt i = 0; i < spec.nelements(); ++i) {
2569 if (mask[i]) {
2570 mean += spec[i];
2571 smean += spec[i]*spec[i];
2572 n++;
2573 }
2574 }
2575
2576 mean /= (float)n;
2577 smean /= (float)n;
2578
2579 return sqrt(smean - mean*mean);
2580}
2581
2582
2583std::string Scantable::formatBaselineParamsHeader(int whichrow, const std::string& masklist, bool verbose) const
2584{
2585 ostringstream oss;
2586
2587 if (verbose) {
2588 for (int i = 0; i < 60; ++i) {
2589 oss << "-";
2590 }
2591 oss << endl;
2592 oss << " Scan[" << getScan(whichrow) << "]";
2593 oss << " Beam[" << getBeam(whichrow) << "]";
2594 oss << " IF[" << getIF(whichrow) << "]";
2595 oss << " Pol[" << getPol(whichrow) << "]";
2596 oss << " Cycle[" << getCycle(whichrow) << "]: " << endl;
2597 oss << "Fitter range = " << masklist << endl;
2598 oss << "Baseline parameters" << endl;
2599 oss << flush;
2600 }
2601
2602 return String(oss);
2603}
2604
2605std::string Scantable::formatBaselineParamsFooter(float rms, bool verbose) const
2606{
2607 ostringstream oss;
2608
2609 if (verbose) {
2610 oss << "Results of baseline fit" << endl;
2611 oss << " rms = " << setprecision(6) << rms << endl;
2612 }
2613
2614 return String(oss);
2615}
2616
2617std::string Scantable::formatBaselineParams(const std::vector<float>& params, const std::vector<bool>& fixed, float rms, const std::string& masklist, int whichrow, bool verbose) const
2618{
2619 ostringstream oss;
2620 oss << formatBaselineParamsHeader(whichrow, masklist, verbose);
2621
2622 if (params.size() > 0) {
2623 for (uInt i = 0; i < params.size(); ++i) {
2624 if (i > 0) {
2625 oss << ",";
2626 }
2627 std::string fix = ((fixed.size() > 0) && (fixed[i]) && verbose) ? "(fixed)" : "";
2628 float vParam = params[i];
2629 std::string equals = "= " + (String)((vParam < 0.0) ? "" : " ");
2630 oss << " p" << i << fix << equals << setprecision(6) << vParam;
2631 }
2632 } else {
2633 oss << " Not fitted";
2634 }
2635 oss << endl;
2636
2637 oss << formatBaselineParamsFooter(rms, verbose);
2638 oss << flush;
2639
2640 return String(oss);
2641}
2642
2643std::string Scantable::formatPiecewiseBaselineParams(const std::vector<int>& ranges, const std::vector<float>& params, const std::vector<bool>& fixed, float rms, const std::string& masklist, int whichrow, bool verbose) const
2644{
2645 ostringstream oss;
2646 oss << formatBaselineParamsHeader(whichrow, masklist, verbose);
2647
2648 if ((params.size() > 0) && (ranges.size() > 0)) {
2649 if (((ranges.size() % 2) == 0) && ((params.size() % (ranges.size() / 2)) == 0)) {
2650 uInt nParam = params.size() / (ranges.size() / 2);
2651 stringstream ss;
2652 ss << ranges[ranges.size()-1] << flush;
2653 int wRange = ss.str().size()*2+5;
2654 ss.str("");
2655 for (uInt j = 0; j < ranges.size(); j+=2) {
2656 ss << " [" << ranges[j] << "," << ranges[j+1] << "]" << flush;
2657 oss << setw(wRange) << left << ss.str();
2658 ss.str("");
2659 for (uInt i = 0; i < nParam; ++i) {
2660 if (i > 0) {
2661 oss << ",";
2662 }
2663 std::string fix = ((fixed.size() > 0) && (fixed[i]) && verbose) ? "(fixed)" : "";
2664 float vParam = params[j/2*nParam+i];
2665 std::string equals = "= " + (String)((vParam < 0.0) ? "" : " ");
2666 oss << " p" << i << fix << equals << setprecision(6) << vParam;
2667 }
2668 oss << endl;
2669 }
2670 } else {
2671 oss << " " << endl;
2672 }
2673 } else {
2674 oss << " Not fitted" << endl;
2675 }
2676
2677 oss << formatBaselineParamsFooter(rms, verbose);
2678 oss << flush;
2679
2680 return String(oss);
2681}
2682
2683bool Scantable::hasSameNchanOverIFs()
2684{
2685 int nIF = nif(-1);
2686 int nCh;
2687 int totalPositiveNChan = 0;
2688 int nPositiveNChan = 0;
2689
2690 for (int i = 0; i < nIF; ++i) {
2691 nCh = nchan(i);
2692 if (nCh > 0) {
2693 totalPositiveNChan += nCh;
2694 nPositiveNChan++;
2695 }
2696 }
2697
2698 return (totalPositiveNChan == (nPositiveNChan * nchan(0)));
2699}
2700
2701std::string Scantable::getMaskRangeList(const std::vector<bool>& mask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, bool verbose)
2702{
2703 if (mask.size() < 2) {
2704 throw(AipsError("The mask elements should be > 1"));
2705 }
2706 int IF = getIF(whichrow);
2707 if (mask.size() != (uInt)nchan(IF)) {
2708 throw(AipsError("Number of channels in scantable != number of mask elements"));
2709 }
2710
2711 if (verbose) {
2712 LogIO logOs(LogOrigin("Scantable", "getMaskRangeList()", WHERE));
2713 logOs << LogIO::WARN << "The current mask window unit is " << coordInfo;
2714 if (!hasSameNchan) {
2715 logOs << endl << "This mask is only valid for IF=" << IF;
2716 }
2717 logOs << LogIO::POST;
2718 }
2719
2720 std::vector<double> abcissa = getAbcissa(whichrow);
2721 std::vector<int> edge = getMaskEdgeIndices(mask);
2722
2723 ostringstream oss;
2724 oss.setf(ios::fixed);
2725 oss << setprecision(1) << "[";
2726 for (uInt i = 0; i < edge.size(); i+=2) {
2727 if (i > 0) oss << ",";
2728 oss << "[" << (float)abcissa[edge[i]] << "," << (float)abcissa[edge[i+1]] << "]";
2729 }
2730 oss << "]" << flush;
2731
2732 return String(oss);
2733}
2734
2735std::vector<int> Scantable::getMaskEdgeIndices(const std::vector<bool>& mask)
2736{
2737 if (mask.size() < 2) {
2738 throw(AipsError("The mask elements should be > 1"));
2739 }
2740
2741 std::vector<int> out, startIndices, endIndices;
2742 int maskSize = mask.size();
2743
2744 startIndices.clear();
2745 endIndices.clear();
2746
2747 if (mask[0]) {
2748 startIndices.push_back(0);
2749 }
2750 for (int i = 1; i < maskSize; ++i) {
2751 if ((!mask[i-1]) && mask[i]) {
2752 startIndices.push_back(i);
2753 } else if (mask[i-1] && (!mask[i])) {
2754 endIndices.push_back(i-1);
2755 }
2756 }
2757 if (mask[maskSize-1]) {
2758 endIndices.push_back(maskSize-1);
2759 }
2760
2761 if (startIndices.size() != endIndices.size()) {
2762 throw(AipsError("Inconsistent Mask Size: bad data?"));
2763 }
2764 for (uInt i = 0; i < startIndices.size(); ++i) {
2765 if (startIndices[i] > endIndices[i]) {
2766 throw(AipsError("Mask start index > mask end index"));
2767 }
2768 }
2769
2770 out.clear();
2771 for (uInt i = 0; i < startIndices.size(); ++i) {
2772 out.push_back(startIndices[i]);
2773 out.push_back(endIndices[i]);
2774 }
2775
2776 return out;
2777}
2778
2779
2780/*
2781STFitEntry Scantable::polyBaseline(const std::vector<bool>& mask, int order, int rowno)
2782{
2783 Fitter fitter = Fitter();
2784 fitter.setExpression("poly", order);
2785
2786 std::vector<bool> fmask = getMask(rowno);
2787 if (fmask.size() != mask.size()) {
2788 throw(AipsError("different mask sizes"));
2789 }
2790 for (int i = 0; i < fmask.size(); ++i) {
2791 fmask[i] = fmask[i] && mask[i];
2792 }
2793
2794 fitBaseline(fmask, rowno, fitter);
2795 setSpectrum(fitter.getResidual(), rowno);
2796 return fitter.getFitEntry();
2797}
2798*/
2799
2800}
2801//namespace asap
Note: See TracBrowser for help on using the repository browser.