source: trunk/src/Scantable.cpp@ 2162

Last change on this file since 2162 was 2162, checked in by Takeshi Nakazato, 14 years ago

New Development: No

JIRA Issue: No

Ready for Test: Yes

Interface Changes: No

What Interface Changed: Please list interface changes

Test Programs: run sd tasks by setting older data format as input

Put in Release Notes: No

Module(s): Module Names change impacts.

Description: Describe your changes here...

Automatically run asap2to3 in Scantable constructor when input Scantable is
v2 and the software requires Scantable v3.


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