source: trunk/src/Scantable.cpp@ 2617

Last change on this file since 2617 was 2595, checked in by Takeshi Nakazato, 12 years ago

New Development: No

JIRA Issue: Yes CAS-4010

Ready for Test: Yes

Interface Changes: No

What Interface Changed: Please list interface changes

Test Programs: sdcal unit test

Put in Release Notes: Yes/No

Module(s): Module Names change impacts.

Description: Describe your changes here...

Rewrote STMath::new_average based on new algorithm. To do that,
Scantable::regridChannel is re-defined.


  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 126.3 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 <sys/time.h>
14
15#include <atnf/PKSIO/SrcType.h>
16
17#include <casa/aips.h>
18#include <casa/iomanip.h>
19#include <casa/iostream.h>
20#include <casa/OS/File.h>
21#include <casa/OS/Path.h>
22#include <casa/Arrays/Array.h>
23#include <casa/Arrays/ArrayAccessor.h>
24#include <casa/Arrays/ArrayLogical.h>
25#include <casa/Arrays/ArrayMath.h>
26#include <casa/Arrays/MaskArrMath.h>
27#include <casa/Arrays/Slice.h>
28#include <casa/Arrays/Vector.h>
29#include <casa/Arrays/VectorSTLIterator.h>
30#include <casa/BasicMath/Math.h>
31#include <casa/BasicSL/Constants.h>
32#include <casa/Containers/RecordField.h>
33#include <casa/Logging/LogIO.h>
34#include <casa/Quanta/MVAngle.h>
35#include <casa/Quanta/MVTime.h>
36#include <casa/Utilities/GenSort.h>
37
38#include <coordinates/Coordinates/CoordinateUtil.h>
39
40// needed to avoid error in .tcc
41#include <measures/Measures/MCDirection.h>
42//
43#include <measures/Measures/MDirection.h>
44#include <measures/Measures/MEpoch.h>
45#include <measures/Measures/MFrequency.h>
46#include <measures/Measures/MeasRef.h>
47#include <measures/Measures/MeasTable.h>
48#include <measures/TableMeasures/ScalarMeasColumn.h>
49#include <measures/TableMeasures/TableMeasDesc.h>
50#include <measures/TableMeasures/TableMeasRefDesc.h>
51#include <measures/TableMeasures/TableMeasValueDesc.h>
52
53#include <tables/Tables/ArrColDesc.h>
54#include <tables/Tables/ExprNode.h>
55#include <tables/Tables/ScaColDesc.h>
56#include <tables/Tables/SetupNewTab.h>
57#include <tables/Tables/TableCopy.h>
58#include <tables/Tables/TableDesc.h>
59#include <tables/Tables/TableIter.h>
60#include <tables/Tables/TableParse.h>
61#include <tables/Tables/TableRecord.h>
62#include <tables/Tables/TableRow.h>
63#include <tables/Tables/TableVector.h>
64
65#include "MathUtils.h"
66#include "STAttr.h"
67#include "STLineFinder.h"
68#include "STPolCircular.h"
69#include "STPolLinear.h"
70#include "STPolStokes.h"
71#include "STUpgrade.h"
72#include "Scantable.h"
73
74#define debug 1
75
76using namespace casa;
77
78namespace asap {
79
80std::map<std::string, STPol::STPolFactory *> Scantable::factories_;
81
82void Scantable::initFactories() {
83 if ( factories_.empty() ) {
84 Scantable::factories_["linear"] = &STPolLinear::myFactory;
85 Scantable::factories_["circular"] = &STPolCircular::myFactory;
86 Scantable::factories_["stokes"] = &STPolStokes::myFactory;
87 }
88}
89
90Scantable::Scantable(Table::TableType ttype) :
91 type_(ttype)
92{
93 initFactories();
94 setupMainTable();
95 freqTable_ = STFrequencies(*this);
96 table_.rwKeywordSet().defineTable("FREQUENCIES", freqTable_.table());
97 weatherTable_ = STWeather(*this);
98 table_.rwKeywordSet().defineTable("WEATHER", weatherTable_.table());
99 focusTable_ = STFocus(*this);
100 table_.rwKeywordSet().defineTable("FOCUS", focusTable_.table());
101 tcalTable_ = STTcal(*this);
102 table_.rwKeywordSet().defineTable("TCAL", tcalTable_.table());
103 moleculeTable_ = STMolecules(*this);
104 table_.rwKeywordSet().defineTable("MOLECULES", moleculeTable_.table());
105 historyTable_ = STHistory(*this);
106 table_.rwKeywordSet().defineTable("HISTORY", historyTable_.table());
107 fitTable_ = STFit(*this);
108 table_.rwKeywordSet().defineTable("FIT", fitTable_.table());
109 table_.tableInfo().setType( "Scantable" ) ;
110 originalTable_ = table_;
111 attach();
112}
113
114Scantable::Scantable(const std::string& name, Table::TableType ttype) :
115 type_(ttype)
116{
117 initFactories();
118
119 Table tab(name, Table::Update);
120 uInt version = tab.keywordSet().asuInt("VERSION");
121 if (version != version_) {
122 STUpgrade upgrader(version_);
123 LogIO os( LogOrigin( "Scantable" ) ) ;
124 os << LogIO::WARN
125 << name << " data format version " << version
126 << " is deprecated" << endl
127 << "Running upgrade."<< endl
128 << LogIO::POST ;
129 std::string outname = upgrader.upgrade(name);
130 if ( outname != name ) {
131 os << LogIO::WARN
132 << "Data will be loaded from " << outname << " instead of "
133 << name << LogIO::POST ;
134 tab = Table(outname, Table::Update ) ;
135 }
136 }
137 if ( type_ == Table::Memory ) {
138 table_ = tab.copyToMemoryTable(generateName());
139 } else {
140 table_ = tab;
141 }
142 table_.tableInfo().setType( "Scantable" ) ;
143
144 attachSubtables();
145 originalTable_ = table_;
146 attach();
147}
148/*
149Scantable::Scantable(const std::string& name, Table::TableType ttype) :
150 type_(ttype)
151{
152 initFactories();
153 Table tab(name, Table::Update);
154 uInt version = tab.keywordSet().asuInt("VERSION");
155 if (version != version_) {
156 throw(AipsError("Unsupported version of ASAP file."));
157 }
158 if ( type_ == Table::Memory ) {
159 table_ = tab.copyToMemoryTable(generateName());
160 } else {
161 table_ = tab;
162 }
163
164 attachSubtables();
165 originalTable_ = table_;
166 attach();
167}
168*/
169
170Scantable::Scantable( const Scantable& other, bool clear ):
171 Logger()
172{
173 // with or without data
174 String newname = String(generateName());
175 type_ = other.table_.tableType();
176 if ( other.table_.tableType() == Table::Memory ) {
177 if ( clear ) {
178 table_ = TableCopy::makeEmptyMemoryTable(newname,
179 other.table_, True);
180 } else
181 table_ = other.table_.copyToMemoryTable(newname);
182 } else {
183 other.table_.deepCopy(newname, Table::New, False,
184 other.table_.endianFormat(),
185 Bool(clear));
186 table_ = Table(newname, Table::Update);
187 table_.markForDelete();
188 }
189 table_.tableInfo().setType( "Scantable" ) ;
190 /// @todo reindex SCANNO, recompute nbeam, nif, npol
191 if ( clear ) copySubtables(other);
192 attachSubtables();
193 originalTable_ = table_;
194 attach();
195}
196
197void Scantable::copySubtables(const Scantable& other) {
198 Table t = table_.rwKeywordSet().asTable("FREQUENCIES");
199 TableCopy::copyRows(t, other.freqTable_.table());
200 t = table_.rwKeywordSet().asTable("FOCUS");
201 TableCopy::copyRows(t, other.focusTable_.table());
202 t = table_.rwKeywordSet().asTable("WEATHER");
203 TableCopy::copyRows(t, other.weatherTable_.table());
204 t = table_.rwKeywordSet().asTable("TCAL");
205 TableCopy::copyRows(t, other.tcalTable_.table());
206 t = table_.rwKeywordSet().asTable("MOLECULES");
207 TableCopy::copyRows(t, other.moleculeTable_.table());
208 t = table_.rwKeywordSet().asTable("HISTORY");
209 TableCopy::copyRows(t, other.historyTable_.table());
210 t = table_.rwKeywordSet().asTable("FIT");
211 TableCopy::copyRows(t, other.fitTable_.table());
212}
213
214void Scantable::attachSubtables()
215{
216 freqTable_ = STFrequencies(table_);
217 focusTable_ = STFocus(table_);
218 weatherTable_ = STWeather(table_);
219 tcalTable_ = STTcal(table_);
220 moleculeTable_ = STMolecules(table_);
221 historyTable_ = STHistory(table_);
222 fitTable_ = STFit(table_);
223}
224
225Scantable::~Scantable()
226{
227}
228
229void Scantable::setupMainTable()
230{
231 TableDesc td("", "1", TableDesc::Scratch);
232 td.comment() = "An ASAP Scantable";
233 td.rwKeywordSet().define("VERSION", uInt(version_));
234
235 // n Cycles
236 td.addColumn(ScalarColumnDesc<uInt>("SCANNO"));
237 // new index every nBeam x nIF x nPol
238 td.addColumn(ScalarColumnDesc<uInt>("CYCLENO"));
239
240 td.addColumn(ScalarColumnDesc<uInt>("BEAMNO"));
241 td.addColumn(ScalarColumnDesc<uInt>("IFNO"));
242 // linear, circular, stokes
243 td.rwKeywordSet().define("POLTYPE", String("linear"));
244 td.addColumn(ScalarColumnDesc<uInt>("POLNO"));
245
246 td.addColumn(ScalarColumnDesc<uInt>("FREQ_ID"));
247 td.addColumn(ScalarColumnDesc<uInt>("MOLECULE_ID"));
248
249 ScalarColumnDesc<Int> refbeamnoColumn("REFBEAMNO");
250 refbeamnoColumn.setDefault(Int(-1));
251 td.addColumn(refbeamnoColumn);
252
253 ScalarColumnDesc<uInt> flagrowColumn("FLAGROW");
254 flagrowColumn.setDefault(uInt(0));
255 td.addColumn(flagrowColumn);
256
257 td.addColumn(ScalarColumnDesc<Double>("TIME"));
258 TableMeasRefDesc measRef(MEpoch::UTC); // UTC as default
259 TableMeasValueDesc measVal(td, "TIME");
260 TableMeasDesc<MEpoch> mepochCol(measVal, measRef);
261 mepochCol.write(td);
262
263 td.addColumn(ScalarColumnDesc<Double>("INTERVAL"));
264
265 td.addColumn(ScalarColumnDesc<String>("SRCNAME"));
266 // Type of source (on=0, off=1, other=-1)
267 ScalarColumnDesc<Int> stypeColumn("SRCTYPE");
268 stypeColumn.setDefault(Int(-1));
269 td.addColumn(stypeColumn);
270 td.addColumn(ScalarColumnDesc<String>("FIELDNAME"));
271
272 //The actual Data Vectors
273 td.addColumn(ArrayColumnDesc<Float>("SPECTRA"));
274 td.addColumn(ArrayColumnDesc<uChar>("FLAGTRA"));
275 td.addColumn(ArrayColumnDesc<Float>("TSYS"));
276
277 td.addColumn(ArrayColumnDesc<Double>("DIRECTION",
278 IPosition(1,2),
279 ColumnDesc::Direct));
280 TableMeasRefDesc mdirRef(MDirection::J2000); // default
281 TableMeasValueDesc tmvdMDir(td, "DIRECTION");
282 // the TableMeasDesc gives the column a type
283 TableMeasDesc<MDirection> mdirCol(tmvdMDir, mdirRef);
284 // a uder set table type e.g. GALCTIC, B1950 ...
285 td.rwKeywordSet().define("DIRECTIONREF", String("J2000"));
286 // writing create the measure column
287 mdirCol.write(td);
288 td.addColumn(ScalarColumnDesc<Float>("AZIMUTH"));
289 td.addColumn(ScalarColumnDesc<Float>("ELEVATION"));
290 td.addColumn(ScalarColumnDesc<Float>("OPACITY"));
291
292 td.addColumn(ScalarColumnDesc<uInt>("TCAL_ID"));
293 ScalarColumnDesc<Int> fitColumn("FIT_ID");
294 fitColumn.setDefault(Int(-1));
295 td.addColumn(fitColumn);
296
297 td.addColumn(ScalarColumnDesc<uInt>("FOCUS_ID"));
298 td.addColumn(ScalarColumnDesc<uInt>("WEATHER_ID"));
299
300 // columns which just get dragged along, as they aren't used in asap
301 td.addColumn(ScalarColumnDesc<Double>("SRCVELOCITY"));
302 td.addColumn(ArrayColumnDesc<Double>("SRCPROPERMOTION"));
303 td.addColumn(ArrayColumnDesc<Double>("SRCDIRECTION"));
304 td.addColumn(ArrayColumnDesc<Double>("SCANRATE"));
305
306 td.rwKeywordSet().define("OBSMODE", String(""));
307
308 // Now create Table SetUp from the description.
309 SetupNewTable aNewTab(generateName(), td, Table::Scratch);
310 table_ = Table(aNewTab, type_, 0);
311 originalTable_ = table_;
312}
313
314void Scantable::attach()
315{
316 timeCol_.attach(table_, "TIME");
317 srcnCol_.attach(table_, "SRCNAME");
318 srctCol_.attach(table_, "SRCTYPE");
319 specCol_.attach(table_, "SPECTRA");
320 flagsCol_.attach(table_, "FLAGTRA");
321 tsysCol_.attach(table_, "TSYS");
322 cycleCol_.attach(table_,"CYCLENO");
323 scanCol_.attach(table_, "SCANNO");
324 beamCol_.attach(table_, "BEAMNO");
325 ifCol_.attach(table_, "IFNO");
326 polCol_.attach(table_, "POLNO");
327 integrCol_.attach(table_, "INTERVAL");
328 azCol_.attach(table_, "AZIMUTH");
329 elCol_.attach(table_, "ELEVATION");
330 dirCol_.attach(table_, "DIRECTION");
331 fldnCol_.attach(table_, "FIELDNAME");
332 rbeamCol_.attach(table_, "REFBEAMNO");
333
334 mweatheridCol_.attach(table_,"WEATHER_ID");
335 mfitidCol_.attach(table_,"FIT_ID");
336 mfreqidCol_.attach(table_, "FREQ_ID");
337 mtcalidCol_.attach(table_, "TCAL_ID");
338 mfocusidCol_.attach(table_, "FOCUS_ID");
339 mmolidCol_.attach(table_, "MOLECULE_ID");
340
341 //Add auxiliary column for row-based flagging (CAS-1433 Wataru Kawasaki)
342 attachAuxColumnDef(flagrowCol_, "FLAGROW", 0);
343
344}
345
346template<class T, class T2>
347void Scantable::attachAuxColumnDef(ScalarColumn<T>& col,
348 const String& colName,
349 const T2& defValue)
350{
351 try {
352 col.attach(table_, colName);
353 } catch (TableError& err) {
354 String errMesg = err.getMesg();
355 if (errMesg == "Table column " + colName + " is unknown") {
356 table_.addColumn(ScalarColumnDesc<T>(colName));
357 col.attach(table_, colName);
358 col.fillColumn(static_cast<T>(defValue));
359 } else {
360 throw;
361 }
362 } catch (...) {
363 throw;
364 }
365}
366
367template<class T, class T2>
368void Scantable::attachAuxColumnDef(ArrayColumn<T>& col,
369 const String& colName,
370 const Array<T2>& defValue)
371{
372 try {
373 col.attach(table_, colName);
374 } catch (TableError& err) {
375 String errMesg = err.getMesg();
376 if (errMesg == "Table column " + colName + " is unknown") {
377 table_.addColumn(ArrayColumnDesc<T>(colName));
378 col.attach(table_, colName);
379
380 int size = 0;
381 ArrayIterator<T2>& it = defValue.begin();
382 while (it != defValue.end()) {
383 ++size;
384 ++it;
385 }
386 IPosition ip(1, size);
387 Array<T>& arr(ip);
388 for (int i = 0; i < size; ++i)
389 arr[i] = static_cast<T>(defValue[i]);
390
391 col.fillColumn(arr);
392 } else {
393 throw;
394 }
395 } catch (...) {
396 throw;
397 }
398}
399
400void Scantable::setHeader(const STHeader& sdh)
401{
402 table_.rwKeywordSet().define("nIF", sdh.nif);
403 table_.rwKeywordSet().define("nBeam", sdh.nbeam);
404 table_.rwKeywordSet().define("nPol", sdh.npol);
405 table_.rwKeywordSet().define("nChan", sdh.nchan);
406 table_.rwKeywordSet().define("Observer", sdh.observer);
407 table_.rwKeywordSet().define("Project", sdh.project);
408 table_.rwKeywordSet().define("Obstype", sdh.obstype);
409 table_.rwKeywordSet().define("AntennaName", sdh.antennaname);
410 table_.rwKeywordSet().define("AntennaPosition", sdh.antennaposition);
411 table_.rwKeywordSet().define("Equinox", sdh.equinox);
412 table_.rwKeywordSet().define("FreqRefFrame", sdh.freqref);
413 table_.rwKeywordSet().define("FreqRefVal", sdh.reffreq);
414 table_.rwKeywordSet().define("Bandwidth", sdh.bandwidth);
415 table_.rwKeywordSet().define("UTC", sdh.utc);
416 table_.rwKeywordSet().define("FluxUnit", sdh.fluxunit);
417 table_.rwKeywordSet().define("Epoch", sdh.epoch);
418 table_.rwKeywordSet().define("POLTYPE", sdh.poltype);
419}
420
421STHeader Scantable::getHeader() const
422{
423 STHeader sdh;
424 table_.keywordSet().get("nBeam",sdh.nbeam);
425 table_.keywordSet().get("nIF",sdh.nif);
426 table_.keywordSet().get("nPol",sdh.npol);
427 table_.keywordSet().get("nChan",sdh.nchan);
428 table_.keywordSet().get("Observer", sdh.observer);
429 table_.keywordSet().get("Project", sdh.project);
430 table_.keywordSet().get("Obstype", sdh.obstype);
431 table_.keywordSet().get("AntennaName", sdh.antennaname);
432 table_.keywordSet().get("AntennaPosition", sdh.antennaposition);
433 table_.keywordSet().get("Equinox", sdh.equinox);
434 table_.keywordSet().get("FreqRefFrame", sdh.freqref);
435 table_.keywordSet().get("FreqRefVal", sdh.reffreq);
436 table_.keywordSet().get("Bandwidth", sdh.bandwidth);
437 table_.keywordSet().get("UTC", sdh.utc);
438 table_.keywordSet().get("FluxUnit", sdh.fluxunit);
439 table_.keywordSet().get("Epoch", sdh.epoch);
440 table_.keywordSet().get("POLTYPE", sdh.poltype);
441 return sdh;
442}
443
444void Scantable::setSourceType( int stype )
445{
446 if ( stype < 0 || stype > 1 )
447 throw(AipsError("Illegal sourcetype."));
448 TableVector<Int> tabvec(table_, "SRCTYPE");
449 tabvec = Int(stype);
450}
451
452bool Scantable::conformant( const Scantable& other )
453{
454 return this->getHeader().conformant(other.getHeader());
455}
456
457
458
459std::string Scantable::formatSec(Double x) const
460{
461 Double xcop = x;
462 MVTime mvt(xcop/24./3600.); // make days
463
464 if (x < 59.95)
465 return String(" ") + mvt.string(MVTime::TIME_CLEAN_NO_HM, 7)+"s";
466 else if (x < 3599.95)
467 return String(" ") + mvt.string(MVTime::TIME_CLEAN_NO_H,7)+" ";
468 else {
469 ostringstream oss;
470 oss << setw(2) << std::right << setprecision(1) << mvt.hour();
471 oss << ":" << mvt.string(MVTime::TIME_CLEAN_NO_H,7) << " ";
472 return String(oss);
473 }
474};
475
476std::string Scantable::formatDirection(const MDirection& md) const
477{
478 Vector<Double> t = md.getAngle(Unit(String("rad"))).getValue();
479 Int prec = 7;
480
481 String ref = md.getRefString();
482 MVAngle mvLon(t[0]);
483 String sLon = mvLon.string(MVAngle::TIME,prec);
484 uInt tp = md.getRef().getType();
485 if (tp == MDirection::GALACTIC ||
486 tp == MDirection::SUPERGAL ) {
487 sLon = mvLon(0.0).string(MVAngle::ANGLE_CLEAN,prec);
488 }
489 MVAngle mvLat(t[1]);
490 String sLat = mvLat.string(MVAngle::ANGLE+MVAngle::DIG2,prec);
491 return ref + String(" ") + sLon + String(" ") + sLat;
492}
493
494
495std::string Scantable::getFluxUnit() const
496{
497 return table_.keywordSet().asString("FluxUnit");
498}
499
500void Scantable::setFluxUnit(const std::string& unit)
501{
502 String tmp(unit);
503 Unit tU(tmp);
504 if (tU==Unit("K") || tU==Unit("Jy")) {
505 table_.rwKeywordSet().define(String("FluxUnit"), tmp);
506 } else {
507 throw AipsError("Illegal unit - must be compatible with Jy or K");
508 }
509}
510
511void Scantable::setInstrument(const std::string& name)
512{
513 bool throwIt = true;
514 // create an Instrument to see if this is valid
515 STAttr::convertInstrument(name, throwIt);
516 String nameU(name);
517 nameU.upcase();
518 table_.rwKeywordSet().define(String("AntennaName"), nameU);
519}
520
521void Scantable::setFeedType(const std::string& feedtype)
522{
523 if ( Scantable::factories_.find(feedtype) == Scantable::factories_.end() ) {
524 std::string msg = "Illegal feed type "+ feedtype;
525 throw(casa::AipsError(msg));
526 }
527 table_.rwKeywordSet().define(String("POLTYPE"), feedtype);
528}
529
530MPosition Scantable::getAntennaPosition() const
531{
532 Vector<Double> antpos;
533 table_.keywordSet().get("AntennaPosition", antpos);
534 MVPosition mvpos(antpos(0),antpos(1),antpos(2));
535 return MPosition(mvpos);
536}
537
538void Scantable::makePersistent(const std::string& filename)
539{
540 String inname(filename);
541 Path path(inname);
542 /// @todo reindex SCANNO, recompute nbeam, nif, npol
543 inname = path.expandedName();
544 // 2011/03/04 TN
545 // We can comment out this workaround since the essential bug is
546 // fixed in casacore (r20889 in google code).
547 table_.deepCopy(inname, Table::New);
548// // WORKAROUND !!! for Table bug
549// // Remove when fixed in casacore
550// if ( table_.tableType() == Table::Memory && !selector_.empty() ) {
551// Table tab = table_.copyToMemoryTable(generateName());
552// tab.deepCopy(inname, Table::New);
553// tab.markForDelete();
554//
555// } else {
556// table_.deepCopy(inname, Table::New);
557// }
558}
559
560int Scantable::nbeam( int scanno ) const
561{
562 if ( scanno < 0 ) {
563 Int n;
564 table_.keywordSet().get("nBeam",n);
565 return int(n);
566 } else {
567 // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
568 Table t = table_(table_.col("SCANNO") == scanno);
569 ROTableRow row(t);
570 const TableRecord& rec = row.get(0);
571 Table subt = t( t.col("IFNO") == Int(rec.asuInt("IFNO"))
572 && t.col("POLNO") == Int(rec.asuInt("POLNO"))
573 && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
574 ROTableVector<uInt> v(subt, "BEAMNO");
575 return int(v.nelements());
576 }
577 return 0;
578}
579
580int Scantable::nif( int scanno ) const
581{
582 if ( scanno < 0 ) {
583 Int n;
584 table_.keywordSet().get("nIF",n);
585 return int(n);
586 } else {
587 // take the first POLNO,BEAMNO,CYCLENO as nbeam shouldn't vary with these
588 Table t = table_(table_.col("SCANNO") == scanno);
589 ROTableRow row(t);
590 const TableRecord& rec = row.get(0);
591 Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
592 && t.col("POLNO") == Int(rec.asuInt("POLNO"))
593 && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
594 if ( subt.nrow() == 0 ) return 0;
595 ROTableVector<uInt> v(subt, "IFNO");
596 return int(v.nelements());
597 }
598 return 0;
599}
600
601int Scantable::npol( int scanno ) const
602{
603 if ( scanno < 0 ) {
604 Int n;
605 table_.keywordSet().get("nPol",n);
606 return n;
607 } else {
608 // take the first POLNO,IFNO,CYCLENO as nbeam shouldn't vary with these
609 Table t = table_(table_.col("SCANNO") == scanno);
610 ROTableRow row(t);
611 const TableRecord& rec = row.get(0);
612 Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
613 && t.col("IFNO") == Int(rec.asuInt("IFNO"))
614 && t.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
615 if ( subt.nrow() == 0 ) return 0;
616 ROTableVector<uInt> v(subt, "POLNO");
617 return int(v.nelements());
618 }
619 return 0;
620}
621
622int Scantable::ncycle( int scanno ) const
623{
624 if ( scanno < 0 ) {
625 Block<String> cols(2);
626 cols[0] = "SCANNO";
627 cols[1] = "CYCLENO";
628 TableIterator it(table_, cols);
629 int n = 0;
630 while ( !it.pastEnd() ) {
631 ++n;
632 ++it;
633 }
634 return n;
635 } else {
636 Table t = table_(table_.col("SCANNO") == scanno);
637 ROTableRow row(t);
638 const TableRecord& rec = row.get(0);
639 Table subt = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
640 && t.col("POLNO") == Int(rec.asuInt("POLNO"))
641 && t.col("IFNO") == Int(rec.asuInt("IFNO")) );
642 if ( subt.nrow() == 0 ) return 0;
643 return int(subt.nrow());
644 }
645 return 0;
646}
647
648
649int Scantable::nrow( int scanno ) const
650{
651 return int(table_.nrow());
652}
653
654int Scantable::nchan( int ifno ) const
655{
656 if ( ifno < 0 ) {
657 Int n;
658 table_.keywordSet().get("nChan",n);
659 return int(n);
660 } else {
661 // take the first SCANNO,POLNO,BEAMNO,CYCLENO as nbeam shouldn't
662 // vary with these
663 Table t = table_(table_.col("IFNO") == ifno, 1);
664 if ( t.nrow() == 0 ) return 0;
665 ROArrayColumn<Float> v(t, "SPECTRA");
666 return v.shape(0)(0);
667 }
668 return 0;
669}
670
671int Scantable::nscan() const {
672 Vector<uInt> scannos(scanCol_.getColumn());
673 uInt nout = genSort( scannos, Sort::Ascending,
674 Sort::QuickSort|Sort::NoDuplicates );
675 return int(nout);
676}
677
678int Scantable::getChannels(int whichrow) const
679{
680 return specCol_.shape(whichrow)(0);
681}
682
683int Scantable::getBeam(int whichrow) const
684{
685 return beamCol_(whichrow);
686}
687
688std::vector<uint> Scantable::getNumbers(const ScalarColumn<uInt>& col) const
689{
690 Vector<uInt> nos(col.getColumn());
691 uInt n = genSort( nos, Sort::Ascending, Sort::QuickSort|Sort::NoDuplicates );
692 nos.resize(n, True);
693 std::vector<uint> stlout;
694 nos.tovector(stlout);
695 return stlout;
696}
697
698int Scantable::getIF(int whichrow) const
699{
700 return ifCol_(whichrow);
701}
702
703int Scantable::getPol(int whichrow) const
704{
705 return polCol_(whichrow);
706}
707
708std::string Scantable::formatTime(const MEpoch& me, bool showdate) const
709{
710 return formatTime(me, showdate, 0);
711}
712
713std::string Scantable::formatTime(const MEpoch& me, bool showdate, uInt prec) const
714{
715 MVTime mvt(me.getValue());
716 if (showdate)
717 //mvt.setFormat(MVTime::YMD);
718 mvt.setFormat(MVTime::YMD, prec);
719 else
720 //mvt.setFormat(MVTime::TIME);
721 mvt.setFormat(MVTime::TIME, prec);
722 ostringstream oss;
723 oss << mvt;
724 return String(oss);
725}
726
727void Scantable::calculateAZEL()
728{
729 MPosition mp = getAntennaPosition();
730 MEpoch::ROScalarColumn timeCol(table_, "TIME");
731 ostringstream oss;
732 oss << "Computed azimuth/elevation using " << endl
733 << mp << endl;
734 for (Int i=0; i<nrow(); ++i) {
735 MEpoch me = timeCol(i);
736 MDirection md = getDirection(i);
737 oss << " Time: " << formatTime(me,False) << " Direction: " << formatDirection(md)
738 << endl << " => ";
739 MeasFrame frame(mp, me);
740 Vector<Double> azel =
741 MDirection::Convert(md, MDirection::Ref(MDirection::AZEL,
742 frame)
743 )().getAngle("rad").getValue();
744 azCol_.put(i,Float(azel[0]));
745 elCol_.put(i,Float(azel[1]));
746 oss << "azel: " << azel[0]/C::pi*180.0 << " "
747 << azel[1]/C::pi*180.0 << " (deg)" << endl;
748 }
749 pushLog(String(oss));
750}
751
752void Scantable::clip(const Float uthres, const Float dthres, bool clipoutside, bool unflag)
753{
754 for (uInt i=0; i<table_.nrow(); ++i) {
755 Vector<uChar> flgs = flagsCol_(i);
756 srchChannelsToClip(i, uthres, dthres, clipoutside, unflag, flgs);
757 flagsCol_.put(i, flgs);
758 }
759}
760
761std::vector<bool> Scantable::getClipMask(int whichrow, const Float uthres, const Float dthres, bool clipoutside, bool unflag)
762{
763 Vector<uChar> flags;
764 flagsCol_.get(uInt(whichrow), flags);
765 srchChannelsToClip(uInt(whichrow), uthres, dthres, clipoutside, unflag, flags);
766 Vector<Bool> bflag(flags.shape());
767 convertArray(bflag, flags);
768 //bflag = !bflag;
769
770 std::vector<bool> mask;
771 bflag.tovector(mask);
772 return mask;
773}
774
775void Scantable::srchChannelsToClip(uInt whichrow, const Float uthres, const Float dthres, bool clipoutside, bool unflag,
776 Vector<uChar> flgs)
777{
778 Vector<Float> spcs = specCol_(whichrow);
779 uInt nchannel = spcs.nelements();
780 if (spcs.nelements() != nchannel) {
781 throw(AipsError("Data has incorrect number of channels"));
782 }
783 uChar userflag = 1 << 7;
784 if (unflag) {
785 userflag = 0 << 7;
786 }
787 if (clipoutside) {
788 for (uInt j = 0; j < nchannel; ++j) {
789 Float spc = spcs(j);
790 if ((spc >= uthres) || (spc <= dthres)) {
791 flgs(j) = userflag;
792 }
793 }
794 } else {
795 for (uInt j = 0; j < nchannel; ++j) {
796 Float spc = spcs(j);
797 if ((spc < uthres) && (spc > dthres)) {
798 flgs(j) = userflag;
799 }
800 }
801 }
802}
803
804
805void Scantable::flag( int whichrow, const std::vector<bool>& msk, bool unflag ) {
806 std::vector<bool>::const_iterator it;
807 uInt ntrue = 0;
808 if (whichrow >= int(table_.nrow()) ) {
809 throw(AipsError("Invalid row number"));
810 }
811 for (it = msk.begin(); it != msk.end(); ++it) {
812 if ( *it ) {
813 ntrue++;
814 }
815 }
816 //if ( selector_.empty() && (msk.size() == 0 || msk.size() == ntrue) )
817 if ( whichrow == -1 && !unflag && selector_.empty() && (msk.size() == 0 || msk.size() == ntrue) )
818 throw(AipsError("Trying to flag whole scantable."));
819 uChar userflag = 1 << 7;
820 if ( unflag ) {
821 userflag = 0 << 7;
822 }
823 if (whichrow > -1 ) {
824 applyChanFlag(uInt(whichrow), msk, userflag);
825 } else {
826 for ( uInt i=0; i<table_.nrow(); ++i) {
827 applyChanFlag(i, msk, userflag);
828 }
829 }
830}
831
832void Scantable::applyChanFlag( uInt whichrow, const std::vector<bool>& msk, uChar flagval )
833{
834 if (whichrow >= table_.nrow() ) {
835 throw( casa::indexError<int>( whichrow, "asap::Scantable::applyChanFlag: Invalid row number" ) );
836 }
837 Vector<uChar> flgs = flagsCol_(whichrow);
838 if ( msk.size() == 0 ) {
839 flgs = flagval;
840 flagsCol_.put(whichrow, flgs);
841 return;
842 }
843 if ( int(msk.size()) != nchan( getIF(whichrow) ) ) {
844 throw(AipsError("Mask has incorrect number of channels."));
845 }
846 if ( flgs.nelements() != msk.size() ) {
847 throw(AipsError("Mask has incorrect number of channels."
848 " Probably varying with IF. Please flag per IF"));
849 }
850 std::vector<bool>::const_iterator it;
851 uInt j = 0;
852 for (it = msk.begin(); it != msk.end(); ++it) {
853 if ( *it ) {
854 flgs(j) = flagval;
855 }
856 ++j;
857 }
858 flagsCol_.put(whichrow, flgs);
859}
860
861void Scantable::flagRow(const std::vector<uInt>& rows, bool unflag)
862{
863 if ( selector_.empty() && (rows.size() == table_.nrow()) )
864 throw(AipsError("Trying to flag whole scantable."));
865
866 uInt rowflag = (unflag ? 0 : 1);
867 std::vector<uInt>::const_iterator it;
868 for (it = rows.begin(); it != rows.end(); ++it)
869 flagrowCol_.put(*it, rowflag);
870}
871
872std::vector<bool> Scantable::getMask(int whichrow) const
873{
874 Vector<uChar> flags;
875 flagsCol_.get(uInt(whichrow), flags);
876 Vector<Bool> bflag(flags.shape());
877 convertArray(bflag, flags);
878 bflag = !bflag;
879 std::vector<bool> mask;
880 bflag.tovector(mask);
881 return mask;
882}
883
884std::vector<float> Scantable::getSpectrum( int whichrow,
885 const std::string& poltype ) const
886{
887 String ptype = poltype;
888 if (poltype == "" ) ptype = getPolType();
889 if ( whichrow < 0 || whichrow >= nrow() )
890 throw(AipsError("Illegal row number."));
891 std::vector<float> out;
892 Vector<Float> arr;
893 uInt requestedpol = polCol_(whichrow);
894 String basetype = getPolType();
895 if ( ptype == basetype ) {
896 specCol_.get(whichrow, arr);
897 } else {
898 CountedPtr<STPol> stpol(STPol::getPolClass(Scantable::factories_,
899 basetype));
900 uInt row = uInt(whichrow);
901 stpol->setSpectra(getPolMatrix(row));
902 Float fang,fhand;
903 fang = focusTable_.getTotalAngle(mfocusidCol_(row));
904 fhand = focusTable_.getFeedHand(mfocusidCol_(row));
905 stpol->setPhaseCorrections(fang, fhand);
906 arr = stpol->getSpectrum(requestedpol, ptype);
907 }
908 if ( arr.nelements() == 0 )
909 pushLog("Not enough polarisations present to do the conversion.");
910 arr.tovector(out);
911 return out;
912}
913
914void Scantable::setSpectrum( const std::vector<float>& spec,
915 int whichrow )
916{
917 Vector<Float> spectrum(spec);
918 Vector<Float> arr;
919 specCol_.get(whichrow, arr);
920 if ( spectrum.nelements() != arr.nelements() )
921 throw AipsError("The spectrum has incorrect number of channels.");
922 specCol_.put(whichrow, spectrum);
923}
924
925
926String Scantable::generateName()
927{
928 return (File::newUniqueName("./","temp")).baseName();
929}
930
931const casa::Table& Scantable::table( ) const
932{
933 return table_;
934}
935
936casa::Table& Scantable::table( )
937{
938 return table_;
939}
940
941std::string Scantable::getPolType() const
942{
943 return table_.keywordSet().asString("POLTYPE");
944}
945
946void Scantable::unsetSelection()
947{
948 table_ = originalTable_;
949 attach();
950 selector_.reset();
951}
952
953void Scantable::setSelection( const STSelector& selection )
954{
955 Table tab = const_cast<STSelector&>(selection).apply(originalTable_);
956 if ( tab.nrow() == 0 ) {
957 throw(AipsError("Selection contains no data. Not applying it."));
958 }
959 table_ = tab;
960 attach();
961// tab.rwKeywordSet().define("nBeam",(Int)(getBeamNos().size())) ;
962// vector<uint> selectedIFs = getIFNos() ;
963// Int newnIF = selectedIFs.size() ;
964// tab.rwKeywordSet().define("nIF",newnIF) ;
965// if ( newnIF != 0 ) {
966// Int newnChan = 0 ;
967// for ( Int i = 0 ; i < newnIF ; i++ ) {
968// Int nChan = nchan( selectedIFs[i] ) ;
969// if ( newnChan > nChan )
970// newnChan = nChan ;
971// }
972// tab.rwKeywordSet().define("nChan",newnChan) ;
973// }
974// tab.rwKeywordSet().define("nPol",(Int)(getPolNos().size())) ;
975 selector_ = selection;
976}
977
978
979std::string Scantable::headerSummary()
980{
981 // Format header info
982// STHeader sdh;
983// sdh = getHeader();
984// sdh.print();
985 ostringstream oss;
986 oss.flags(std::ios_base::left);
987 String tmp;
988 // Project
989 table_.keywordSet().get("Project", tmp);
990 oss << setw(15) << "Project:" << tmp << endl;
991 // Observation date
992 oss << setw(15) << "Obs Date:" << getTime(-1,true) << endl;
993 // Observer
994 oss << setw(15) << "Observer:"
995 << table_.keywordSet().asString("Observer") << endl;
996 // Antenna Name
997 table_.keywordSet().get("AntennaName", tmp);
998 oss << setw(15) << "Antenna Name:" << tmp << endl;
999 // Obs type
1000 table_.keywordSet().get("Obstype", tmp);
1001 // Records (nrow)
1002 oss << setw(15) << "Data Records:" << table_.nrow() << " rows" << endl;
1003 oss << setw(15) << "Obs. Type:" << tmp << endl;
1004 // Beams, IFs, Polarizations, and Channels
1005 oss << setw(15) << "Beams:" << setw(4) << nbeam() << endl
1006 << setw(15) << "IFs:" << setw(4) << nif() << endl
1007 << setw(15) << "Polarisations:" << setw(4) << npol()
1008 << "(" << getPolType() << ")" << endl
1009 << setw(15) << "Channels:" << nchan() << endl;
1010 // Flux unit
1011 table_.keywordSet().get("FluxUnit", tmp);
1012 oss << setw(15) << "Flux Unit:" << tmp << endl;
1013 // Abscissa Unit
1014 oss << setw(15) << "Abscissa:" << getAbcissaLabel(0) << endl;
1015 // Selection
1016 oss << selector_.print() << endl;
1017
1018 return String(oss);
1019}
1020
1021void Scantable::summary( const std::string& filename )
1022{
1023 ostringstream oss;
1024 ofstream ofs;
1025 LogIO ols(LogOrigin("Scantable", "summary", WHERE));
1026
1027 if (filename != "")
1028 ofs.open( filename.c_str(), ios::out );
1029
1030 oss << endl;
1031 oss << asap::SEPERATOR << endl;
1032 oss << " Scan Table Summary" << endl;
1033 oss << asap::SEPERATOR << endl;
1034
1035 // Format header info
1036 oss << headerSummary();
1037 oss << endl;
1038
1039 if (table_.nrow() <= 0){
1040 oss << asap::SEPERATOR << endl;
1041 oss << "The MAIN table is empty: there are no data!!!" << endl;
1042 oss << asap::SEPERATOR << endl;
1043
1044 ols << String(oss) << LogIO::POST;
1045 if (ofs) {
1046 ofs << String(oss) << flush;
1047 ofs.close();
1048 }
1049 return;
1050 }
1051
1052
1053
1054 // main table
1055 String dirtype = "Position ("
1056 + getDirectionRefString()
1057 + ")";
1058 oss.flags(std::ios_base::left);
1059 oss << setw(5) << "Scan"
1060 << setw(15) << "Source"
1061 << setw(35) << "Time range"
1062 << setw(2) << "" << setw(7) << "Int[s]"
1063 << setw(7) << "Record"
1064 << setw(8) << "SrcType"
1065 << setw(8) << "FreqIDs"
1066 << setw(7) << "MolIDs" << endl;
1067 oss << setw(7)<< "" << setw(6) << "Beam"
1068 << setw(23) << dirtype << endl;
1069
1070 oss << asap::SEPERATOR << endl;
1071
1072 // Flush summary and clear up the string
1073 ols << String(oss) << LogIO::POST;
1074 if (ofs) ofs << String(oss) << flush;
1075 oss.str("");
1076 oss.clear();
1077
1078
1079 // Get Freq_ID map
1080 ROScalarColumn<uInt> ftabIds(frequencies().table(), "ID");
1081 Int nfid = ftabIds.nrow();
1082 if (nfid <= 0){
1083 oss << "FREQUENCIES subtable is empty: there are no data!!!" << endl;
1084 oss << asap::SEPERATOR << endl;
1085
1086 ols << String(oss) << LogIO::POST;
1087 if (ofs) {
1088 ofs << String(oss) << flush;
1089 ofs.close();
1090 }
1091 return;
1092 }
1093 // Storages of overall IFNO, POLNO, and nchan per FREQ_ID
1094 // the orders are identical to ID in FREQ subtable
1095 Block< Vector<uInt> > ifNos(nfid), polNos(nfid);
1096 Vector<Int> fIdchans(nfid,-1);
1097 map<uInt, Int> fidMap; // (FREQ_ID, row # in FREQ subtable) pair
1098 for (Int i=0; i < nfid; i++){
1099 // fidMap[freqId] returns row number in FREQ subtable
1100 fidMap.insert(pair<uInt, Int>(ftabIds(i),i));
1101 ifNos[i] = Vector<uInt>();
1102 polNos[i] = Vector<uInt>();
1103 }
1104
1105 TableIterator iter(table_, "SCANNO");
1106
1107 // Vars for keeping track of time, freqids, molIds in a SCANNO
1108 Vector<uInt> freqids;
1109 Vector<uInt> molids;
1110 Vector<uInt> beamids(1,0);
1111 Vector<MDirection> beamDirs;
1112 Vector<Int> stypeids(1,0);
1113 Vector<String> stypestrs;
1114 Int nfreq(1);
1115 Int nmol(1);
1116 uInt nbeam(1);
1117 uInt nstype(1);
1118
1119 Double btime(0.0), etime(0.0);
1120 Double meanIntTim(0.0);
1121
1122 uInt currFreqId(0), ftabRow(0);
1123 Int iflen(0), pollen(0);
1124
1125 while (!iter.pastEnd()) {
1126 Table subt = iter.table();
1127 uInt snrow = subt.nrow();
1128 ROTableRow row(subt);
1129 const TableRecord& rec = row.get(0);
1130
1131 // relevant columns
1132 ROScalarColumn<Double> mjdCol(subt,"TIME");
1133 ROScalarColumn<Double> intervalCol(subt,"INTERVAL");
1134 MDirection::ROScalarColumn dirCol(subt,"DIRECTION");
1135
1136 ScalarColumn<uInt> freqIdCol(subt,"FREQ_ID");
1137 ScalarColumn<uInt> molIdCol(subt,"MOLECULE_ID");
1138 ROScalarColumn<uInt> beamCol(subt,"BEAMNO");
1139 ROScalarColumn<Int> stypeCol(subt,"SRCTYPE");
1140
1141 ROScalarColumn<uInt> ifNoCol(subt,"IFNO");
1142 ROScalarColumn<uInt> polNoCol(subt,"POLNO");
1143
1144
1145 // Times
1146 meanIntTim = sum(intervalCol.getColumn()) / (double) snrow;
1147 minMax(btime, etime, mjdCol.getColumn());
1148 etime += meanIntTim/C::day;
1149
1150 // MOLECULE_ID and FREQ_ID
1151 molids = getNumbers(molIdCol);
1152 molids.shape(nmol);
1153
1154 freqids = getNumbers(freqIdCol);
1155 freqids.shape(nfreq);
1156
1157 // Add first beamid, and srcNames
1158 beamids.resize(1,False);
1159 beamDirs.resize(1,False);
1160 beamids(0)=beamCol(0);
1161 beamDirs(0)=dirCol(0);
1162 nbeam = 1;
1163
1164 stypeids.resize(1,False);
1165 stypeids(0)=stypeCol(0);
1166 nstype = 1;
1167
1168 // Global listings of nchan/IFNO/POLNO per FREQ_ID
1169 currFreqId=freqIdCol(0);
1170 ftabRow = fidMap[currFreqId];
1171 // Assumes an identical number of channels per FREQ_ID
1172 if (fIdchans(ftabRow) < 0 ) {
1173 RORecordFieldPtr< Array<Float> > spec(rec, "SPECTRA");
1174 fIdchans(ftabRow)=(*spec).shape()(0);
1175 }
1176 // Should keep ifNos and polNos form the previous SCANNO
1177 if ( !anyEQ(ifNos[ftabRow],ifNoCol(0)) ) {
1178 ifNos[ftabRow].shape(iflen);
1179 iflen++;
1180 ifNos[ftabRow].resize(iflen,True);
1181 ifNos[ftabRow](iflen-1) = ifNoCol(0);
1182 }
1183 if ( !anyEQ(polNos[ftabRow],polNoCol(0)) ) {
1184 polNos[ftabRow].shape(pollen);
1185 pollen++;
1186 polNos[ftabRow].resize(pollen,True);
1187 polNos[ftabRow](pollen-1) = polNoCol(0);
1188 }
1189
1190 for (uInt i=1; i < snrow; i++){
1191 // Need to list BEAMNO and DIRECTION in the same order
1192 if ( !anyEQ(beamids,beamCol(i)) ) {
1193 nbeam++;
1194 beamids.resize(nbeam,True);
1195 beamids(nbeam-1)=beamCol(i);
1196 beamDirs.resize(nbeam,True);
1197 beamDirs(nbeam-1)=dirCol(i);
1198 }
1199
1200 // SRCTYPE is Int (getNumber takes only uInt)
1201 if ( !anyEQ(stypeids,stypeCol(i)) ) {
1202 nstype++;
1203 stypeids.resize(nstype,True);
1204 stypeids(nstype-1)=stypeCol(i);
1205 }
1206
1207 // Global listings of nchan/IFNO/POLNO per FREQ_ID
1208 currFreqId=freqIdCol(i);
1209 ftabRow = fidMap[currFreqId];
1210 if (fIdchans(ftabRow) < 0 ) {
1211 const TableRecord& rec = row.get(i);
1212 RORecordFieldPtr< Array<Float> > spec(rec, "SPECTRA");
1213 fIdchans(ftabRow) = (*spec).shape()(0);
1214 }
1215 if ( !anyEQ(ifNos[ftabRow],ifNoCol(i)) ) {
1216 ifNos[ftabRow].shape(iflen);
1217 iflen++;
1218 ifNos[ftabRow].resize(iflen,True);
1219 ifNos[ftabRow](iflen-1) = ifNoCol(i);
1220 }
1221 if ( !anyEQ(polNos[ftabRow],polNoCol(i)) ) {
1222 polNos[ftabRow].shape(pollen);
1223 pollen++;
1224 polNos[ftabRow].resize(pollen,True);
1225 polNos[ftabRow](pollen-1) = polNoCol(i);
1226 }
1227 } // end of row iteration
1228
1229 stypestrs.resize(nstype,False);
1230 for (uInt j=0; j < nstype; j++)
1231 stypestrs(j) = SrcType::getName(stypeids(j));
1232
1233 // Format Scan summary
1234 oss << setw(4) << std::right << rec.asuInt("SCANNO")
1235 << std::left << setw(1) << ""
1236 << setw(15) << rec.asString("SRCNAME")
1237 << setw(21) << MVTime(btime).string(MVTime::YMD,7)
1238 << setw(3) << " - " << MVTime(etime).string(MVTime::TIME,7)
1239 << setw(3) << "" << setw(6) << meanIntTim << setw(1) << ""
1240 << std::right << setw(5) << snrow << setw(2) << ""
1241 << std::left << stypestrs << setw(1) << ""
1242 << freqids << setw(1) << ""
1243 << molids << endl;
1244 // Format Beam summary
1245 for (uInt j=0; j < nbeam; j++) {
1246 oss << setw(7) << "" << setw(6) << beamids(j) << setw(1) << ""
1247 << formatDirection(beamDirs(j)) << endl;
1248 }
1249 // Flush summary every scan and clear up the string
1250 ols << String(oss) << LogIO::POST;
1251 if (ofs) ofs << String(oss) << flush;
1252 oss.str("");
1253 oss.clear();
1254
1255 ++iter;
1256 } // end of scan iteration
1257 oss << asap::SEPERATOR << endl;
1258
1259 // List FRECUENCIES Table (using STFrequencies.print may be slow)
1260 oss << "FREQUENCIES: " << nfreq << endl;
1261 oss << std::right << setw(5) << "ID" << setw(2) << ""
1262 << std::left << setw(5) << "IFNO" << setw(2) << ""
1263 << setw(8) << "Frame"
1264 << setw(16) << "RefVal"
1265 << setw(7) << "RefPix"
1266 << setw(15) << "Increment"
1267 << setw(9) << "Channels"
1268 << setw(6) << "POLNOs" << endl;
1269 Int tmplen;
1270 for (Int i=0; i < nfid; i++){
1271 // List row=i of FREQUENCIES subtable
1272 ifNos[i].shape(tmplen);
1273 if (tmplen >= 1) {
1274 oss << std::right << setw(5) << ftabIds(i) << setw(2) << ""
1275 << setw(3) << ifNos[i](0) << setw(1) << ""
1276 << std::left << setw(46) << frequencies().print(ftabIds(i))
1277 << setw(2) << ""
1278 << std::right << setw(8) << fIdchans[i] << setw(2) << ""
1279 << std::left << polNos[i];
1280 if (tmplen > 1) {
1281 oss << " (" << tmplen << " chains)";
1282 }
1283 oss << endl;
1284 }
1285
1286 }
1287 oss << asap::SEPERATOR << endl;
1288
1289 // List MOLECULES Table (currently lists all rows)
1290 oss << "MOLECULES: " << endl;
1291 if (molecules().nrow() <= 0) {
1292 oss << " MOLECULES subtable is empty: there are no data" << endl;
1293 } else {
1294 ROTableRow row(molecules().table());
1295 oss << std::right << setw(5) << "ID"
1296 << std::left << setw(3) << ""
1297 << setw(18) << "RestFreq"
1298 << setw(15) << "Name" << endl;
1299 for (Int i=0; i < molecules().nrow(); i++){
1300 const TableRecord& rec=row.get(i);
1301 oss << std::right << setw(5) << rec.asuInt("ID")
1302 << std::left << setw(3) << ""
1303 << rec.asArrayDouble("RESTFREQUENCY") << setw(1) << ""
1304 << rec.asArrayString("NAME") << endl;
1305 }
1306 }
1307 oss << asap::SEPERATOR << endl;
1308 ols << String(oss) << LogIO::POST;
1309 if (ofs) {
1310 ofs << String(oss) << flush;
1311 ofs.close();
1312 }
1313 // return String(oss);
1314}
1315
1316
1317std::string Scantable::oldheaderSummary()
1318{
1319 // Format header info
1320// STHeader sdh;
1321// sdh = getHeader();
1322// sdh.print();
1323 ostringstream oss;
1324 oss.flags(std::ios_base::left);
1325 oss << setw(15) << "Beams:" << setw(4) << nbeam() << endl
1326 << setw(15) << "IFs:" << setw(4) << nif() << endl
1327 << setw(15) << "Polarisations:" << setw(4) << npol()
1328 << "(" << getPolType() << ")" << endl
1329 << setw(15) << "Channels:" << nchan() << endl;
1330 String tmp;
1331 oss << setw(15) << "Observer:"
1332 << table_.keywordSet().asString("Observer") << endl;
1333 oss << setw(15) << "Obs Date:" << getTime(-1,true) << endl;
1334 table_.keywordSet().get("Project", tmp);
1335 oss << setw(15) << "Project:" << tmp << endl;
1336 table_.keywordSet().get("Obstype", tmp);
1337 oss << setw(15) << "Obs. Type:" << tmp << endl;
1338 table_.keywordSet().get("AntennaName", tmp);
1339 oss << setw(15) << "Antenna Name:" << tmp << endl;
1340 table_.keywordSet().get("FluxUnit", tmp);
1341 oss << setw(15) << "Flux Unit:" << tmp << endl;
1342 int nid = moleculeTable_.nrow();
1343 Bool firstline = True;
1344 oss << setw(15) << "Rest Freqs:";
1345 for (int i=0; i<nid; i++) {
1346 Table t = table_(table_.col("MOLECULE_ID") == i, 1);
1347 if (t.nrow() > 0) {
1348 Vector<Double> vec(moleculeTable_.getRestFrequency(i));
1349 if (vec.nelements() > 0) {
1350 if (firstline) {
1351 oss << setprecision(10) << vec << " [Hz]" << endl;
1352 firstline=False;
1353 }
1354 else{
1355 oss << setw(15)<<" " << setprecision(10) << vec << " [Hz]" << endl;
1356 }
1357 } else {
1358 oss << "none" << endl;
1359 }
1360 }
1361 }
1362
1363 oss << setw(15) << "Abcissa:" << getAbcissaLabel(0) << endl;
1364 oss << selector_.print() << endl;
1365 return String(oss);
1366}
1367
1368 //std::string Scantable::summary( const std::string& filename )
1369void Scantable::oldsummary( const std::string& filename )
1370{
1371 ostringstream oss;
1372 ofstream ofs;
1373 LogIO ols(LogOrigin("Scantable", "summary", WHERE));
1374
1375 if (filename != "")
1376 ofs.open( filename.c_str(), ios::out );
1377
1378 oss << endl;
1379 oss << asap::SEPERATOR << endl;
1380 oss << " Scan Table Summary" << endl;
1381 oss << asap::SEPERATOR << endl;
1382
1383 // Format header info
1384 oss << oldheaderSummary();
1385 oss << endl;
1386
1387 // main table
1388 String dirtype = "Position ("
1389 + getDirectionRefString()
1390 + ")";
1391 oss.flags(std::ios_base::left);
1392 oss << setw(5) << "Scan" << setw(15) << "Source"
1393 << setw(10) << "Time" << setw(18) << "Integration"
1394 << setw(15) << "Source Type" << endl;
1395 oss << setw(5) << "" << setw(5) << "Beam" << setw(3) << "" << dirtype << endl;
1396 oss << setw(10) << "" << setw(3) << "IF" << setw(3) << ""
1397 << setw(8) << "Frame" << setw(16)
1398 << "RefVal" << setw(10) << "RefPix" << setw(12) << "Increment"
1399 << setw(7) << "Channels"
1400 << endl;
1401 oss << asap::SEPERATOR << endl;
1402
1403 // Flush summary and clear up the string
1404 ols << String(oss) << LogIO::POST;
1405 if (ofs) ofs << String(oss) << flush;
1406 oss.str("");
1407 oss.clear();
1408
1409 TableIterator iter(table_, "SCANNO");
1410 while (!iter.pastEnd()) {
1411 Table subt = iter.table();
1412 ROTableRow row(subt);
1413 MEpoch::ROScalarColumn timeCol(subt,"TIME");
1414 const TableRecord& rec = row.get(0);
1415 oss << setw(4) << std::right << rec.asuInt("SCANNO")
1416 << std::left << setw(1) << ""
1417 << setw(15) << rec.asString("SRCNAME")
1418 << setw(10) << formatTime(timeCol(0), false);
1419 // count the cycles in the scan
1420 TableIterator cyciter(subt, "CYCLENO");
1421 int nint = 0;
1422 while (!cyciter.pastEnd()) {
1423 ++nint;
1424 ++cyciter;
1425 }
1426 oss << setw(3) << std::right << nint << setw(3) << " x " << std::left
1427 << setw(11) << formatSec(rec.asFloat("INTERVAL")) << setw(1) << ""
1428 << setw(15) << SrcType::getName(rec.asInt("SRCTYPE")) << endl;
1429
1430 TableIterator biter(subt, "BEAMNO");
1431 while (!biter.pastEnd()) {
1432 Table bsubt = biter.table();
1433 ROTableRow brow(bsubt);
1434 const TableRecord& brec = brow.get(0);
1435 uInt row0 = bsubt.rowNumbers(table_)[0];
1436 oss << setw(5) << "" << setw(4) << std::right << brec.asuInt("BEAMNO")<< std::left;
1437 oss << setw(4) << "" << formatDirection(getDirection(row0)) << endl;
1438 TableIterator iiter(bsubt, "IFNO");
1439 while (!iiter.pastEnd()) {
1440 Table isubt = iiter.table();
1441 ROTableRow irow(isubt);
1442 const TableRecord& irec = irow.get(0);
1443 oss << setw(9) << "";
1444 oss << setw(3) << std::right << irec.asuInt("IFNO") << std::left
1445 << setw(1) << "" << frequencies().print(irec.asuInt("FREQ_ID"))
1446 << setw(3) << "" << nchan(irec.asuInt("IFNO"))
1447 << endl;
1448
1449 ++iiter;
1450 }
1451 ++biter;
1452 }
1453 // Flush summary every scan and clear up the string
1454 ols << String(oss) << LogIO::POST;
1455 if (ofs) ofs << String(oss) << flush;
1456 oss.str("");
1457 oss.clear();
1458
1459 ++iter;
1460 }
1461 oss << asap::SEPERATOR << endl;
1462 ols << String(oss) << LogIO::POST;
1463 if (ofs) {
1464 ofs << String(oss) << flush;
1465 ofs.close();
1466 }
1467 // return String(oss);
1468}
1469
1470// std::string Scantable::getTime(int whichrow, bool showdate) const
1471// {
1472// MEpoch::ROScalarColumn timeCol(table_, "TIME");
1473// MEpoch me;
1474// if (whichrow > -1) {
1475// me = timeCol(uInt(whichrow));
1476// } else {
1477// Double tm;
1478// table_.keywordSet().get("UTC",tm);
1479// me = MEpoch(MVEpoch(tm));
1480// }
1481// return formatTime(me, showdate);
1482// }
1483
1484std::string Scantable::getTime(int whichrow, bool showdate, uInt prec) const
1485{
1486 MEpoch me;
1487 me = getEpoch(whichrow);
1488 return formatTime(me, showdate, prec);
1489}
1490
1491MEpoch Scantable::getEpoch(int whichrow) const
1492{
1493 if (whichrow > -1) {
1494 return timeCol_(uInt(whichrow));
1495 } else {
1496 Double tm;
1497 table_.keywordSet().get("UTC",tm);
1498 return MEpoch(MVEpoch(tm));
1499 }
1500}
1501
1502std::string Scantable::getDirectionString(int whichrow) const
1503{
1504 return formatDirection(getDirection(uInt(whichrow)));
1505}
1506
1507
1508SpectralCoordinate Scantable::getSpectralCoordinate(int whichrow) const {
1509 const MPosition& mp = getAntennaPosition();
1510 const MDirection& md = getDirection(whichrow);
1511 const MEpoch& me = timeCol_(whichrow);
1512 //Double rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
1513 Vector<Double> rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
1514 return freqTable_.getSpectralCoordinate(md, mp, me, rf,
1515 mfreqidCol_(whichrow));
1516}
1517
1518std::vector< double > Scantable::getAbcissa( int whichrow ) const
1519{
1520 if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal row number"));
1521 std::vector<double> stlout;
1522 int nchan = specCol_(whichrow).nelements();
1523 String us = freqTable_.getUnitString();
1524 if ( us == "" || us == "pixel" || us == "channel" ) {
1525 for (int i=0; i<nchan; ++i) {
1526 stlout.push_back(double(i));
1527 }
1528 return stlout;
1529 }
1530 SpectralCoordinate spc = getSpectralCoordinate(whichrow);
1531 Vector<Double> pixel(nchan);
1532 Vector<Double> world;
1533 indgen(pixel);
1534 if ( Unit(us) == Unit("Hz") ) {
1535 for ( int i=0; i < nchan; ++i) {
1536 Double world;
1537 spc.toWorld(world, pixel[i]);
1538 stlout.push_back(double(world));
1539 }
1540 } else if ( Unit(us) == Unit("km/s") ) {
1541 Vector<Double> world;
1542 spc.pixelToVelocity(world, pixel);
1543 world.tovector(stlout);
1544 }
1545 return stlout;
1546}
1547void Scantable::setDirectionRefString( const std::string & refstr )
1548{
1549 MDirection::Types mdt;
1550 if (refstr != "" && !MDirection::getType(mdt, refstr)) {
1551 throw(AipsError("Illegal Direction frame."));
1552 }
1553 if ( refstr == "" ) {
1554 String defaultstr = MDirection::showType(dirCol_.getMeasRef().getType());
1555 table_.rwKeywordSet().define("DIRECTIONREF", defaultstr);
1556 } else {
1557 table_.rwKeywordSet().define("DIRECTIONREF", String(refstr));
1558 }
1559}
1560
1561std::string Scantable::getDirectionRefString( ) const
1562{
1563 return table_.keywordSet().asString("DIRECTIONREF");
1564}
1565
1566MDirection Scantable::getDirection(int whichrow ) const
1567{
1568 String usertype = table_.keywordSet().asString("DIRECTIONREF");
1569 String type = MDirection::showType(dirCol_.getMeasRef().getType());
1570 if ( usertype != type ) {
1571 MDirection::Types mdt;
1572 if (!MDirection::getType(mdt, usertype)) {
1573 throw(AipsError("Illegal Direction frame."));
1574 }
1575 return dirCol_.convert(uInt(whichrow), mdt);
1576 } else {
1577 return dirCol_(uInt(whichrow));
1578 }
1579}
1580
1581std::string Scantable::getAbcissaLabel( int whichrow ) const
1582{
1583 if ( whichrow > int(table_.nrow()) ) throw(AipsError("Illegal ro number"));
1584 const MPosition& mp = getAntennaPosition();
1585 const MDirection& md = getDirection(whichrow);
1586 const MEpoch& me = timeCol_(whichrow);
1587 //const Double& rf = mmolidCol_(whichrow);
1588 const Vector<Double> rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow));
1589 SpectralCoordinate spc =
1590 freqTable_.getSpectralCoordinate(md, mp, me, rf, mfreqidCol_(whichrow));
1591
1592 String s = "Channel";
1593 Unit u = Unit(freqTable_.getUnitString());
1594 if (u == Unit("km/s")) {
1595 s = CoordinateUtil::axisLabel(spc, 0, True,True, True);
1596 } else if (u == Unit("Hz")) {
1597 Vector<String> wau(1);wau = u.getName();
1598 spc.setWorldAxisUnits(wau);
1599 s = CoordinateUtil::axisLabel(spc, 0, True, True, False);
1600 }
1601 return s;
1602
1603}
1604
1605/**
1606void asap::Scantable::setRestFrequencies( double rf, const std::string& name,
1607 const std::string& unit )
1608**/
1609void Scantable::setRestFrequencies( vector<double> rf, const vector<std::string>& name,
1610 const std::string& unit )
1611
1612{
1613 ///@todo lookup in line table to fill in name and formattedname
1614 Unit u(unit);
1615 //Quantum<Double> urf(rf, u);
1616 Quantum<Vector<Double> >urf(rf, u);
1617 Vector<String> formattedname(0);
1618 //cerr<<"Scantable::setRestFrequnecies="<<urf<<endl;
1619
1620 //uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), name, "");
1621 uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), mathutil::toVectorString(name), formattedname);
1622 TableVector<uInt> tabvec(table_, "MOLECULE_ID");
1623 tabvec = id;
1624}
1625
1626/**
1627void asap::Scantable::setRestFrequencies( const std::string& name )
1628{
1629 throw(AipsError("setRestFrequencies( const std::string& name ) NYI"));
1630 ///@todo implement
1631}
1632**/
1633
1634void Scantable::setRestFrequencies( const vector<std::string>& name )
1635{
1636 (void) name; // suppress unused warning
1637 throw(AipsError("setRestFrequencies( const vector<std::string>& name ) NYI"));
1638 ///@todo implement
1639}
1640
1641std::vector< unsigned int > Scantable::rownumbers( ) const
1642{
1643 std::vector<unsigned int> stlout;
1644 Vector<uInt> vec = table_.rowNumbers();
1645 vec.tovector(stlout);
1646 return stlout;
1647}
1648
1649
1650Matrix<Float> Scantable::getPolMatrix( uInt whichrow ) const
1651{
1652 ROTableRow row(table_);
1653 const TableRecord& rec = row.get(whichrow);
1654 Table t =
1655 originalTable_( originalTable_.col("SCANNO") == Int(rec.asuInt("SCANNO"))
1656 && originalTable_.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
1657 && originalTable_.col("IFNO") == Int(rec.asuInt("IFNO"))
1658 && originalTable_.col("CYCLENO") == Int(rec.asuInt("CYCLENO")) );
1659 ROArrayColumn<Float> speccol(t, "SPECTRA");
1660 return speccol.getColumn();
1661}
1662
1663std::vector< std::string > Scantable::columnNames( ) const
1664{
1665 Vector<String> vec = table_.tableDesc().columnNames();
1666 return mathutil::tovectorstring(vec);
1667}
1668
1669MEpoch::Types Scantable::getTimeReference( ) const
1670{
1671 return MEpoch::castType(timeCol_.getMeasRef().getType());
1672}
1673
1674void Scantable::addFit( const STFitEntry& fit, int row )
1675{
1676 //cout << mfitidCol_(uInt(row)) << endl;
1677 LogIO os( LogOrigin( "Scantable", "addFit()", WHERE ) ) ;
1678 os << mfitidCol_(uInt(row)) << LogIO::POST ;
1679 uInt id = fitTable_.addEntry(fit, mfitidCol_(uInt(row)));
1680 mfitidCol_.put(uInt(row), id);
1681}
1682
1683void Scantable::shift(int npix)
1684{
1685 Vector<uInt> fids(mfreqidCol_.getColumn());
1686 genSort( fids, Sort::Ascending,
1687 Sort::QuickSort|Sort::NoDuplicates );
1688 for (uInt i=0; i<fids.nelements(); ++i) {
1689 frequencies().shiftRefPix(npix, fids[i]);
1690 }
1691}
1692
1693String Scantable::getAntennaName() const
1694{
1695 String out;
1696 table_.keywordSet().get("AntennaName", out);
1697 String::size_type pos1 = out.find("@") ;
1698 String::size_type pos2 = out.find("//") ;
1699 if ( pos2 != String::npos )
1700 out = out.substr(pos2+2,pos1-pos2-2) ;
1701 else if ( pos1 != String::npos )
1702 out = out.substr(0,pos1) ;
1703 return out;
1704}
1705
1706int Scantable::checkScanInfo(const std::vector<int>& scanlist) const
1707{
1708 String tbpath;
1709 int ret = 0;
1710 if ( table_.keywordSet().isDefined("GBT_GO") ) {
1711 table_.keywordSet().get("GBT_GO", tbpath);
1712 Table t(tbpath,Table::Old);
1713 // check each scan if other scan of the pair exist
1714 int nscan = scanlist.size();
1715 for (int i = 0; i < nscan; i++) {
1716 Table subt = t( t.col("SCAN") == scanlist[i]+1 );
1717 if (subt.nrow()==0) {
1718 //cerr <<"Scan "<<scanlist[i]<<" cannot be found in the scantable."<<endl;
1719 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1720 os <<LogIO::WARN<<"Scan "<<scanlist[i]<<" cannot be found in the scantable."<<LogIO::POST;
1721 ret = 1;
1722 break;
1723 }
1724 ROTableRow row(subt);
1725 const TableRecord& rec = row.get(0);
1726 int scan1seqn = rec.asuInt("PROCSEQN");
1727 int laston1 = rec.asuInt("LASTON");
1728 if ( rec.asuInt("PROCSIZE")==2 ) {
1729 if ( i < nscan-1 ) {
1730 Table subt2 = t( t.col("SCAN") == scanlist[i+1]+1 );
1731 if ( subt2.nrow() == 0) {
1732 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1733
1734 //cerr<<"Scan "<<scanlist[i+1]<<" cannot be found in the scantable."<<endl;
1735 os<<LogIO::WARN<<"Scan "<<scanlist[i+1]<<" cannot be found in the scantable."<<LogIO::POST;
1736 ret = 1;
1737 break;
1738 }
1739 ROTableRow row2(subt2);
1740 const TableRecord& rec2 = row2.get(0);
1741 int scan2seqn = rec2.asuInt("PROCSEQN");
1742 int laston2 = rec2.asuInt("LASTON");
1743 if (scan1seqn == 1 && scan2seqn == 2) {
1744 if (laston1 == laston2) {
1745 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1746 //cerr<<"A valid scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl;
1747 os<<"A valid scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<LogIO::POST;
1748 i +=1;
1749 }
1750 else {
1751 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1752 //cerr<<"Incorrect scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl;
1753 os<<LogIO::WARN<<"Incorrect scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<LogIO::POST;
1754 }
1755 }
1756 else if (scan1seqn==2 && scan2seqn == 1) {
1757 if (laston1 == laston2) {
1758 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1759 //cerr<<"["<<scanlist[i]<<","<<scanlist[i+1]<<"] is a valid scan pair but in incorrect order."<<endl;
1760 os<<LogIO::WARN<<"["<<scanlist[i]<<","<<scanlist[i+1]<<"] is a valid scan pair but in incorrect order."<<LogIO::POST;
1761 ret = 1;
1762 break;
1763 }
1764 }
1765 else {
1766 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1767 //cerr<<"The other scan for "<<scanlist[i]<<" appears to be missing. Check the input scan numbers."<<endl;
1768 os<<LogIO::WARN<<"The other scan for "<<scanlist[i]<<" appears to be missing. Check the input scan numbers."<<LogIO::POST;
1769 ret = 1;
1770 break;
1771 }
1772 }
1773 }
1774 else {
1775 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1776 //cerr<<"The scan does not appear to be standard obsevation."<<endl;
1777 os<<LogIO::WARN<<"The scan does not appear to be standard obsevation."<<LogIO::POST;
1778 }
1779 //if ( i >= nscan ) break;
1780 }
1781 }
1782 else {
1783 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ;
1784 //cerr<<"No reference to GBT_GO table."<<endl;
1785 os<<LogIO::WARN<<"No reference to GBT_GO table."<<LogIO::POST;
1786 ret = 1;
1787 }
1788 return ret;
1789}
1790
1791std::vector<double> Scantable::getDirectionVector(int whichrow) const
1792{
1793 Vector<Double> Dir = dirCol_(whichrow).getAngle("rad").getValue();
1794 std::vector<double> dir;
1795 Dir.tovector(dir);
1796 return dir;
1797}
1798
1799void asap::Scantable::reshapeSpectrum( int nmin, int nmax )
1800 throw( casa::AipsError )
1801{
1802 // assumed that all rows have same nChan
1803 Vector<Float> arr = specCol_( 0 ) ;
1804 int nChan = arr.nelements() ;
1805
1806 // if nmin < 0 or nmax < 0, nothing to do
1807 if ( nmin < 0 ) {
1808 throw( casa::indexError<int>( nmin, "asap::Scantable::reshapeSpectrum: Invalid range. Negative index is specified." ) ) ;
1809 }
1810 if ( nmax < 0 ) {
1811 throw( casa::indexError<int>( nmax, "asap::Scantable::reshapeSpectrum: Invalid range. Negative index is specified." ) ) ;
1812 }
1813
1814 // if nmin > nmax, exchange values
1815 if ( nmin > nmax ) {
1816 int tmp = nmax ;
1817 nmax = nmin ;
1818 nmin = tmp ;
1819 LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1820 os << "Swap values. Applied range is ["
1821 << nmin << ", " << nmax << "]" << LogIO::POST ;
1822 }
1823
1824 // if nmin exceeds nChan, nothing to do
1825 if ( nmin >= nChan ) {
1826 throw( casa::indexError<int>( nmin, "asap::Scantable::reshapeSpectrum: Invalid range. Specified minimum exceeds nChan." ) ) ;
1827 }
1828
1829 // if nmax exceeds nChan, reset nmax to nChan
1830 if ( nmax >= nChan ) {
1831 if ( nmin == 0 ) {
1832 // nothing to do
1833 LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1834 os << "Whole range is selected. Nothing to do." << LogIO::POST ;
1835 return ;
1836 }
1837 else {
1838 LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ;
1839 os << "Specified maximum exceeds nChan. Applied range is ["
1840 << nmin << ", " << nChan-1 << "]." << LogIO::POST ;
1841 nmax = nChan - 1 ;
1842 }
1843 }
1844
1845 // reshape specCol_ and flagCol_
1846 for ( int irow = 0 ; irow < nrow() ; irow++ ) {
1847 reshapeSpectrum( nmin, nmax, irow ) ;
1848 }
1849
1850 // update FREQUENCIES subtable
1851 Double refpix ;
1852 Double refval ;
1853 Double increment ;
1854 int freqnrow = freqTable_.table().nrow() ;
1855 Vector<uInt> oldId( freqnrow ) ;
1856 Vector<uInt> newId( freqnrow ) ;
1857 for ( int irow = 0 ; irow < freqnrow ; irow++ ) {
1858 freqTable_.getEntry( refpix, refval, increment, irow ) ;
1859 /***
1860 * need to shift refpix to nmin
1861 * note that channel nmin in old index will be channel 0 in new one
1862 ***/
1863 refval = refval - ( refpix - nmin ) * increment ;
1864 refpix = 0 ;
1865 freqTable_.setEntry( refpix, refval, increment, irow ) ;
1866 }
1867
1868 // update nchan
1869 int newsize = nmax - nmin + 1 ;
1870 table_.rwKeywordSet().define( "nChan", newsize ) ;
1871
1872 // update bandwidth
1873 // assumed all spectra in the scantable have same bandwidth
1874 table_.rwKeywordSet().define( "Bandwidth", increment * newsize ) ;
1875
1876 return ;
1877}
1878
1879void asap::Scantable::reshapeSpectrum( int nmin, int nmax, int irow )
1880{
1881 // reshape specCol_ and flagCol_
1882 Vector<Float> oldspec = specCol_( irow ) ;
1883 Vector<uChar> oldflag = flagsCol_( irow ) ;
1884 Vector<Float> oldtsys = tsysCol_( irow ) ;
1885 uInt newsize = nmax - nmin + 1 ;
1886 Slice slice( nmin, newsize, 1 ) ;
1887 specCol_.put( irow, oldspec( slice ) ) ;
1888 flagsCol_.put( irow, oldflag( slice ) ) ;
1889 if ( oldspec.size() == oldtsys.size() )
1890 tsysCol_.put( irow, oldtsys( slice ) ) ;
1891
1892 return ;
1893}
1894
1895void asap::Scantable::regridSpecChannel( double dnu, int nChan )
1896{
1897 LogIO os( LogOrigin( "Scantable", "regridChannel()", WHERE ) ) ;
1898 os << "Regrid abcissa with spectral resoultion " << dnu << " " << freqTable_.getUnitString() << " with channel number " << ((nChan>0)? String(nChan) : "covering band width")<< LogIO::POST ;
1899 int freqnrow = freqTable_.table().nrow() ;
1900 Vector<bool> firstTime( freqnrow, true ) ;
1901 double oldincr, factor;
1902 uInt currId;
1903 Double refpix ;
1904 Double refval ;
1905 Double increment ;
1906 for ( int irow = 0 ; irow < nrow() ; irow++ ) {
1907 currId = mfreqidCol_(irow);
1908 vector<double> abcissa = getAbcissa( irow ) ;
1909 if (nChan < 0) {
1910 int oldsize = abcissa.size() ;
1911 double bw = (abcissa[oldsize-1]-abcissa[0]) + \
1912 0.5 * (abcissa[1]-abcissa[0] + abcissa[oldsize-1]-abcissa[oldsize-2]) ;
1913 nChan = int( ceil( abs(bw/dnu) ) ) ;
1914 }
1915 // actual regridding
1916 regridChannel( nChan, dnu, irow ) ;
1917
1918 // update FREQUENCIES subtable
1919 if (firstTime[currId]) {
1920 oldincr = abcissa[1]-abcissa[0] ;
1921 factor = dnu/oldincr ;
1922 firstTime[currId] = false ;
1923 freqTable_.getEntry( refpix, refval, increment, currId ) ;
1924
1925 //refval = refval - ( refpix + 0.5 * (1 - factor) ) * increment ;
1926 if (factor > 0 ) {
1927 refpix = (refpix + 0.5)/factor - 0.5;
1928 } else {
1929 refpix = (abcissa.size() - 0.5 - refpix)/abs(factor) - 0.5;
1930 }
1931 freqTable_.setEntry( refpix, refval, increment*factor, currId ) ;
1932 //os << "ID" << currId << ": channel width (Orig) = " << oldincr << " [" << freqTable_.getUnitString() << "], scale factor = " << factor << LogIO::POST ;
1933 //os << " frequency increment (Orig) = " << increment << "-> (New) " << increment*factor << LogIO::POST ;
1934 }
1935 }
1936}
1937
1938void asap::Scantable::regridChannel( int nChan, double dnu )
1939{
1940 LogIO os( LogOrigin( "Scantable", "regridChannel()", WHERE ) ) ;
1941 os << "Regrid abcissa with channel number " << nChan << " and spectral resoultion " << dnu << "Hz." << LogIO::POST ;
1942 // assumed that all rows have same nChan
1943 Vector<Float> arr = specCol_( 0 ) ;
1944 int oldsize = arr.nelements() ;
1945
1946 // if oldsize == nChan, nothing to do
1947 if ( oldsize == nChan ) {
1948 os << "Specified channel number is same as current one. Nothing to do." << LogIO::POST ;
1949 return ;
1950 }
1951
1952 // if oldChan < nChan, unphysical operation
1953 if ( oldsize < nChan ) {
1954 os << "Unphysical operation. Nothing to do." << LogIO::POST ;
1955 return ;
1956 }
1957
1958 // change channel number for specCol_, flagCol_, and tsysCol_ (if necessary)
1959 vector<string> coordinfo = getCoordInfo() ;
1960 string oldinfo = coordinfo[0] ;
1961 coordinfo[0] = "Hz" ;
1962 setCoordInfo( coordinfo ) ;
1963 for ( int irow = 0 ; irow < nrow() ; irow++ ) {
1964 regridChannel( nChan, dnu, irow ) ;
1965 }
1966 coordinfo[0] = oldinfo ;
1967 setCoordInfo( coordinfo ) ;
1968
1969
1970 // NOTE: this method does not update metadata such as
1971 // FREQUENCIES subtable, nChan, Bandwidth, etc.
1972
1973 return ;
1974}
1975
1976void asap::Scantable::regridChannel( int nChan, double dnu, int irow )
1977{
1978 // logging
1979 //ofstream ofs( "average.log", std::ios::out | std::ios::app ) ;
1980 //ofs << "IFNO = " << getIF( irow ) << " irow = " << irow << endl ;
1981
1982 Vector<Float> oldspec = specCol_( irow ) ;
1983 Vector<uChar> oldflag = flagsCol_( irow ) ;
1984 Vector<Float> oldtsys = tsysCol_( irow ) ;
1985 Vector<Float> newspec( nChan, 0 ) ;
1986 Vector<uChar> newflag( nChan, true ) ;
1987 Vector<Float> newtsys ;
1988 bool regridTsys = false ;
1989 if (oldtsys.size() == oldspec.size()) {
1990 regridTsys = true ;
1991 newtsys.resize(nChan,false) ;
1992 newtsys = 0 ;
1993 }
1994
1995 // regrid
1996 vector<double> abcissa = getAbcissa( irow ) ;
1997 int oldsize = abcissa.size() ;
1998 double olddnu = abcissa[1] - abcissa[0] ;
1999 //int ichan = 0 ;
2000 double wsum = 0.0 ;
2001 Vector<double> zi( nChan+1 ) ;
2002 Vector<double> yi( oldsize + 1 ) ;
2003 yi[0] = abcissa[0] - 0.5 * olddnu ;
2004 for ( int ii = 1 ; ii < oldsize ; ii++ )
2005 yi[ii] = 0.5* (abcissa[ii-1] + abcissa[ii]) ;
2006 yi[oldsize] = abcissa[oldsize-1] \
2007 + 0.5 * (abcissa[oldsize-1] - abcissa[oldsize-2]) ;
2008 //zi[0] = abcissa[0] - 0.5 * olddnu ;
2009 zi[0] = ((olddnu*dnu > 0) ? yi[0] : yi[oldsize]) ;
2010 for ( int ii = 1 ; ii < nChan ; ii++ )
2011 zi[ii] = zi[0] + dnu * ii ;
2012 zi[nChan] = zi[nChan-1] + dnu ;
2013 // Access zi and yi in ascending order
2014 int izs = ((dnu > 0) ? 0 : nChan ) ;
2015 int ize = ((dnu > 0) ? nChan : 0 ) ;
2016 int izincr = ((dnu > 0) ? 1 : -1 ) ;
2017 int ichan = ((olddnu > 0) ? 0 : oldsize ) ;
2018 int iye = ((olddnu > 0) ? oldsize : 0 ) ;
2019 int iyincr = ((olddnu > 0) ? 1 : -1 ) ;
2020 //for ( int ii = izs ; ii != ize ; ii+=izincr ){
2021 int ii = izs ;
2022 while (ii != ize) {
2023 // always zl < zr
2024 double zl = zi[ii] ;
2025 double zr = zi[ii+izincr] ;
2026 // Need to access smaller index for the new spec, flag, and tsys.
2027 // Values between zi[k] and zi[k+1] should be stored in newspec[k], etc.
2028 int i = min(ii, ii+izincr) ;
2029 //for ( int jj = ichan ; jj != iye ; jj+=iyincr ) {
2030 int jj = ichan ;
2031 while (jj != iye) {
2032 // always yl < yr
2033 double yl = yi[jj] ;
2034 double yr = yi[jj+iyincr] ;
2035 // Need to access smaller index for the original spec, flag, and tsys.
2036 // Values between yi[k] and yi[k+1] are stored in oldspec[k], etc.
2037 int j = min(jj, jj+iyincr) ;
2038 if ( yr <= zl ) {
2039 jj += iyincr ;
2040 continue ;
2041 }
2042 else if ( yl <= zl ) {
2043 if ( yr < zr ) {
2044 if (!oldflag[j]) {
2045 newspec[i] += oldspec[j] * ( yr - zl ) ;
2046 if (regridTsys) newtsys[i] += oldtsys[j] * ( yr - zl ) ;
2047 wsum += ( yr - zl ) ;
2048 }
2049 newflag[i] = newflag[i] && oldflag[j] ;
2050 }
2051 else {
2052 if (!oldflag[j]) {
2053 newspec[i] += oldspec[j] * abs(dnu) ;
2054 if (regridTsys) newtsys[i] += oldtsys[j] * abs(dnu) ;
2055 wsum += abs(dnu) ;
2056 }
2057 newflag[i] = newflag[i] && oldflag[j] ;
2058 ichan = jj ;
2059 break ;
2060 }
2061 }
2062 else if ( yl < zr ) {
2063 if ( yr <= zr ) {
2064 if (!oldflag[j]) {
2065 newspec[i] += oldspec[j] * ( yr - yl ) ;
2066 if (regridTsys) newtsys[i] += oldtsys[j] * ( yr - yl ) ;
2067 wsum += ( yr - yl ) ;
2068 }
2069 newflag[i] = newflag[i] && oldflag[j] ;
2070 }
2071 else {
2072 if (!oldflag[j]) {
2073 newspec[i] += oldspec[j] * ( zr - yl ) ;
2074 if (regridTsys) newtsys[i] += oldtsys[j] * ( zr - yl ) ;
2075 wsum += ( zr - yl ) ;
2076 }
2077 newflag[i] = newflag[i] && oldflag[j] ;
2078 ichan = jj ;
2079 break ;
2080 }
2081 }
2082 else {
2083 ichan = jj - iyincr ;
2084 break ;
2085 }
2086 jj += iyincr ;
2087 }
2088 if ( wsum != 0.0 ) {
2089 newspec[i] /= wsum ;
2090 if (regridTsys) newtsys[i] /= wsum ;
2091 }
2092 wsum = 0.0 ;
2093 ii += izincr ;
2094 }
2095// if ( dnu > 0.0 ) {
2096// for ( int ii = 0 ; ii < nChan ; ii++ ) {
2097// double zl = zi[ii] ;
2098// double zr = zi[ii+1] ;
2099// for ( int j = ichan ; j < oldsize ; j++ ) {
2100// double yl = yi[j] ;
2101// double yr = yi[j+1] ;
2102// if ( yl <= zl ) {
2103// if ( yr <= zl ) {
2104// continue ;
2105// }
2106// else if ( yr <= zr ) {
2107// if (!oldflag[j]) {
2108// newspec[ii] += oldspec[j] * ( yr - zl ) ;
2109// if (regridTsys) newtsys[ii] += oldtsys[j] * ( yr - zl ) ;
2110// wsum += ( yr - zl ) ;
2111// }
2112// newflag[ii] = newflag[ii] && oldflag[j] ;
2113// }
2114// else {
2115// if (!oldflag[j]) {
2116// newspec[ii] += oldspec[j] * dnu ;
2117// if (regridTsys) newtsys[ii] += oldtsys[j] * dnu ;
2118// wsum += dnu ;
2119// }
2120// newflag[ii] = newflag[ii] && oldflag[j] ;
2121// ichan = j ;
2122// break ;
2123// }
2124// }
2125// else if ( yl < zr ) {
2126// if ( yr <= zr ) {
2127// if (!oldflag[j]) {
2128// newspec[ii] += oldspec[j] * ( yr - yl ) ;
2129// if (regridTsys) newtsys[ii] += oldtsys[j] * ( yr - yl ) ;
2130// wsum += ( yr - yl ) ;
2131// }
2132// newflag[ii] = newflag[ii] && oldflag[j] ;
2133// }
2134// else {
2135// if (!oldflag[j]) {
2136// newspec[ii] += oldspec[j] * ( zr - yl ) ;
2137// if (regridTsys) newtsys[ii] += oldtsys[j] * ( zr - yl ) ;
2138// wsum += ( zr - yl ) ;
2139// }
2140// newflag[ii] = newflag[ii] && oldflag[j] ;
2141// ichan = j ;
2142// break ;
2143// }
2144// }
2145// else {
2146// ichan = j - 1 ;
2147// break ;
2148// }
2149// }
2150// if ( wsum != 0.0 ) {
2151// newspec[ii] /= wsum ;
2152// if (regridTsys) newtsys[ii] /= wsum ;
2153// }
2154// wsum = 0.0 ;
2155// }
2156// }
2157// else if ( dnu < 0.0 ) {
2158// for ( int ii = 0 ; ii < nChan ; ii++ ) {
2159// double zl = zi[ii] ;
2160// double zr = zi[ii+1] ;
2161// for ( int j = ichan ; j < oldsize ; j++ ) {
2162// double yl = yi[j] ;
2163// double yr = yi[j+1] ;
2164// if ( yl >= zl ) {
2165// if ( yr >= zl ) {
2166// continue ;
2167// }
2168// else if ( yr >= zr ) {
2169// if (!oldflag[j]) {
2170// newspec[ii] += oldspec[j] * abs( yr - zl ) ;
2171// if (regridTsys) newtsys[ii] += oldtsys[j] * abs( yr - zl ) ;
2172// wsum += abs( yr - zl ) ;
2173// }
2174// newflag[ii] = newflag[ii] && oldflag[j] ;
2175// }
2176// else {
2177// if (!oldflag[j]) {
2178// newspec[ii] += oldspec[j] * abs( dnu ) ;
2179// if (regridTsys) newtsys[ii] += oldtsys[j] * abs( dnu ) ;
2180// wsum += abs( dnu ) ;
2181// }
2182// newflag[ii] = newflag[ii] && oldflag[j] ;
2183// ichan = j ;
2184// break ;
2185// }
2186// }
2187// else if ( yl > zr ) {
2188// if ( yr >= zr ) {
2189// if (!oldflag[j]) {
2190// newspec[ii] += oldspec[j] * abs( yr - yl ) ;
2191// if (regridTsys) newtsys[ii] += oldtsys[j] * abs( yr - yl ) ;
2192// wsum += abs( yr - yl ) ;
2193// }
2194// newflag[ii] = newflag[ii] && oldflag[j] ;
2195// }
2196// else {
2197// if (!oldflag[j]) {
2198// newspec[ii] += oldspec[j] * abs( zr - yl ) ;
2199// if (regridTsys) newtsys[ii] += oldtsys[j] * abs( zr - yl ) ;
2200// wsum += abs( zr - yl ) ;
2201// }
2202// newflag[ii] = newflag[ii] && oldflag[j] ;
2203// ichan = j ;
2204// break ;
2205// }
2206// }
2207// else {
2208// ichan = j - 1 ;
2209// break ;
2210// }
2211// }
2212// if ( wsum != 0.0 ) {
2213// newspec[ii] /= wsum ;
2214// if (regridTsys) newtsys[ii] /= wsum ;
2215// }
2216// wsum = 0.0 ;
2217// }
2218// }
2219// // //ofs << "olddnu = " << olddnu << ", dnu = " << dnu << endl ;
2220// // pile += dnu ;
2221// // wedge = olddnu * ( refChan + 1 ) ;
2222// // while ( wedge < pile ) {
2223// // newspec[0] += olddnu * oldspec[refChan] ;
2224// // newflag[0] = newflag[0] || oldflag[refChan] ;
2225// // //ofs << "channel " << refChan << " is included in new channel 0" << endl ;
2226// // refChan++ ;
2227// // wedge += olddnu ;
2228// // wsum += olddnu ;
2229// // //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
2230// // }
2231// // frac = ( wedge - pile ) / olddnu ;
2232// // wsum += ( 1.0 - frac ) * olddnu ;
2233// // newspec[0] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
2234// // newflag[0] = newflag[0] || oldflag[refChan] ;
2235// // //ofs << "channel " << refChan << " is partly included in new channel 0" << " with fraction of " << ( 1.0 - frac ) << endl ;
2236// // //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
2237// // newspec[0] /= wsum ;
2238// // //ofs << "newspec[0] = " << newspec[0] << endl ;
2239// // //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
2240
2241// // /***
2242// // * ichan = 1 - nChan-2
2243// // ***/
2244// // for ( int ichan = 1 ; ichan < nChan - 1 ; ichan++ ) {
2245// // pile += dnu ;
2246// // newspec[ichan] += frac * olddnu * oldspec[refChan] ;
2247// // newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
2248// // //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << frac << endl ;
2249// // refChan++ ;
2250// // wedge += olddnu ;
2251// // wsum = frac * olddnu ;
2252// // //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
2253// // while ( wedge < pile ) {
2254// // newspec[ichan] += olddnu * oldspec[refChan] ;
2255// // newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
2256// // //ofs << "channel " << refChan << " is included in new channel " << ichan << endl ;
2257// // refChan++ ;
2258// // wedge += olddnu ;
2259// // wsum += olddnu ;
2260// // //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
2261// // }
2262// // frac = ( wedge - pile ) / olddnu ;
2263// // wsum += ( 1.0 - frac ) * olddnu ;
2264// // newspec[ichan] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
2265// // newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
2266// // //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << ( 1.0 - frac ) << endl ;
2267// // //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
2268// // //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
2269// // newspec[ichan] /= wsum ;
2270// // //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << endl ;
2271// // }
2272
2273// // /***
2274// // * ichan = nChan-1
2275// // ***/
2276// // // NOTE: Assumed that all spectra have the same bandwidth
2277// // pile += dnu ;
2278// // newspec[nChan-1] += frac * olddnu * oldspec[refChan] ;
2279// // newflag[nChan-1] = newflag[nChan-1] || oldflag[refChan] ;
2280// // //ofs << "channel " << refChan << " is partly included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
2281// // refChan++ ;
2282// // wedge += olddnu ;
2283// // wsum = frac * olddnu ;
2284// // //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
2285// // for ( int jchan = refChan ; jchan < oldsize ; jchan++ ) {
2286// // newspec[nChan-1] += olddnu * oldspec[jchan] ;
2287// // newflag[nChan-1] = newflag[nChan-1] || oldflag[jchan] ;
2288// // wsum += olddnu ;
2289// // //ofs << "channel " << jchan << " is included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
2290// // //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
2291// // }
2292// // //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
2293// // //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
2294// // newspec[nChan-1] /= wsum ;
2295// // //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << endl ;
2296
2297// // // ofs.close() ;
2298
2299 specCol_.put( irow, newspec ) ;
2300 flagsCol_.put( irow, newflag ) ;
2301 if (regridTsys) tsysCol_.put( irow, newtsys );
2302
2303 return ;
2304}
2305
2306void Scantable::regridChannel( int nChan, double dnu, double fmin, int irow )
2307{
2308 Vector<Float> oldspec = specCol_( irow ) ;
2309 Vector<uChar> oldflag = flagsCol_( irow ) ;
2310 Vector<Float> oldtsys = tsysCol_( irow ) ;
2311 Vector<Float> newspec( nChan, 0 ) ;
2312 Vector<uChar> newflag( nChan, true ) ;
2313 Vector<Float> newtsys ;
2314 bool regridTsys = false ;
2315 if (oldtsys.size() == oldspec.size()) {
2316 regridTsys = true ;
2317 newtsys.resize(nChan,false) ;
2318 newtsys = 0 ;
2319 }
2320
2321 // regrid
2322 vector<double> abcissa = getAbcissa( irow ) ;
2323 int oldsize = abcissa.size() ;
2324 double olddnu = abcissa[1] - abcissa[0] ;
2325 //int ichan = 0 ;
2326 double wsum = 0.0 ;
2327 Vector<double> zi( nChan+1 ) ;
2328 Vector<double> yi( oldsize + 1 ) ;
2329 Block<uInt> count( nChan, 0 ) ;
2330 yi[0] = abcissa[0] - 0.5 * olddnu ;
2331 for ( int ii = 1 ; ii < oldsize ; ii++ )
2332 yi[ii] = 0.5* (abcissa[ii-1] + abcissa[ii]) ;
2333 yi[oldsize] = abcissa[oldsize-1] \
2334 + 0.5 * (abcissa[oldsize-1] - abcissa[oldsize-2]) ;
2335// cout << "olddnu=" << olddnu << ", dnu=" << dnu << " (diff=" << olddnu-dnu << ")" << endl ;
2336// cout << "yi[0]=" << yi[0] << ", fmin=" << fmin << " (diff=" << yi[0]-fmin << ")" << endl ;
2337// cout << "oldsize=" << oldsize << ", nChan=" << nChan << endl ;
2338
2339 // do not regrid if input parameters are almost same as current
2340 // spectral setup
2341 double dnuDiff = abs( ( dnu - olddnu ) / olddnu ) ;
2342 double oldfmin = min( yi[0], yi[oldsize] ) ;
2343 double fminDiff = abs( ( fmin - oldfmin ) / oldfmin ) ;
2344 double nChanDiff = nChan - oldsize ;
2345 double eps = 1.0e-8 ;
2346 if ( nChanDiff == 0 && dnuDiff < eps && fminDiff < eps )
2347 return ;
2348
2349 //zi[0] = abcissa[0] - 0.5 * olddnu ;
2350 //zi[0] = ((olddnu*dnu > 0) ? yi[0] : yi[oldsize]) ;
2351 if ( dnu > 0 )
2352 zi[0] = fmin - 0.5 * dnu ;
2353 else
2354 zi[0] = fmin + nChan * abs(dnu) ;
2355 for ( int ii = 1 ; ii < nChan ; ii++ )
2356 zi[ii] = zi[0] + dnu * ii ;
2357 zi[nChan] = zi[nChan-1] + dnu ;
2358 // Access zi and yi in ascending order
2359 int izs = ((dnu > 0) ? 0 : nChan ) ;
2360 int ize = ((dnu > 0) ? nChan : 0 ) ;
2361 int izincr = ((dnu > 0) ? 1 : -1 ) ;
2362 int ichan = ((olddnu > 0) ? 0 : oldsize ) ;
2363 int iye = ((olddnu > 0) ? oldsize : 0 ) ;
2364 int iyincr = ((olddnu > 0) ? 1 : -1 ) ;
2365 //for ( int ii = izs ; ii != ize ; ii+=izincr ){
2366 int ii = izs ;
2367 while (ii != ize) {
2368 // always zl < zr
2369 double zl = zi[ii] ;
2370 double zr = zi[ii+izincr] ;
2371 // Need to access smaller index for the new spec, flag, and tsys.
2372 // Values between zi[k] and zi[k+1] should be stored in newspec[k], etc.
2373 int i = min(ii, ii+izincr) ;
2374 //for ( int jj = ichan ; jj != iye ; jj+=iyincr ) {
2375 int jj = ichan ;
2376 while (jj != iye) {
2377 // always yl < yr
2378 double yl = yi[jj] ;
2379 double yr = yi[jj+iyincr] ;
2380 // Need to access smaller index for the original spec, flag, and tsys.
2381 // Values between yi[k] and yi[k+1] are stored in oldspec[k], etc.
2382 int j = min(jj, jj+iyincr) ;
2383 if ( yr <= zl ) {
2384 jj += iyincr ;
2385 continue ;
2386 }
2387 else if ( yl <= zl ) {
2388 if ( yr < zr ) {
2389 if (!oldflag[j]) {
2390 newspec[i] += oldspec[j] * ( yr - zl ) ;
2391 if (regridTsys) newtsys[i] += oldtsys[j] * ( yr - zl ) ;
2392 wsum += ( yr - zl ) ;
2393 count[i]++ ;
2394 }
2395 newflag[i] = newflag[i] && oldflag[j] ;
2396 }
2397 else {
2398 if (!oldflag[j]) {
2399 newspec[i] += oldspec[j] * abs(dnu) ;
2400 if (regridTsys) newtsys[i] += oldtsys[j] * abs(dnu) ;
2401 wsum += abs(dnu) ;
2402 count[i]++ ;
2403 }
2404 newflag[i] = newflag[i] && oldflag[j] ;
2405 ichan = jj ;
2406 break ;
2407 }
2408 }
2409 else if ( yl < zr ) {
2410 if ( yr <= zr ) {
2411 if (!oldflag[j]) {
2412 newspec[i] += oldspec[j] * ( yr - yl ) ;
2413 if (regridTsys) newtsys[i] += oldtsys[j] * ( yr - yl ) ;
2414 wsum += ( yr - yl ) ;
2415 count[i]++ ;
2416 }
2417 newflag[i] = newflag[i] && oldflag[j] ;
2418 }
2419 else {
2420 if (!oldflag[j]) {
2421 newspec[i] += oldspec[j] * ( zr - yl ) ;
2422 if (regridTsys) newtsys[i] += oldtsys[j] * ( zr - yl ) ;
2423 wsum += ( zr - yl ) ;
2424 count[i]++ ;
2425 }
2426 newflag[i] = newflag[i] && oldflag[j] ;
2427 ichan = jj ;
2428 break ;
2429 }
2430 }
2431 else {
2432 //ichan = jj - iyincr ;
2433 break ;
2434 }
2435 jj += iyincr ;
2436 }
2437 if ( wsum != 0.0 ) {
2438 newspec[i] /= wsum ;
2439 if (regridTsys) newtsys[i] /= wsum ;
2440 }
2441 wsum = 0.0 ;
2442 ii += izincr ;
2443 }
2444
2445 // flag out channels without data
2446 // this is tentative since there is no specific definition
2447 // on bit flag...
2448 uChar noData = 1 << 7 ;
2449 for ( Int i = 0 ; i < nChan ; i++ ) {
2450 if ( count[i] == 0 )
2451 newflag[i] = noData ;
2452 }
2453
2454 specCol_.put( irow, newspec ) ;
2455 flagsCol_.put( irow, newflag ) ;
2456 if (regridTsys) tsysCol_.put( irow, newtsys );
2457
2458 return ;
2459}
2460
2461std::vector<float> Scantable::getWeather(int whichrow) const
2462{
2463 std::vector<float> out(5);
2464 //Float temperature, pressure, humidity, windspeed, windaz;
2465 weatherTable_.getEntry(out[0], out[1], out[2], out[3], out[4],
2466 mweatheridCol_(uInt(whichrow)));
2467
2468
2469 return out;
2470}
2471
2472bool Scantable::getFlagtraFast(uInt whichrow)
2473{
2474 uChar flag;
2475 Vector<uChar> flags;
2476 flagsCol_.get(whichrow, flags);
2477 flag = flags[0];
2478 for (uInt i = 1; i < flags.size(); ++i) {
2479 flag &= flags[i];
2480 }
2481 return ((flag >> 7) == 1);
2482}
2483
2484void Scantable::polyBaseline(const std::vector<bool>& mask, int order, bool getResidual, const std::string& progressInfo, const bool outLogger, const std::string& blfile)
2485{
2486 try {
2487 ofstream ofs;
2488 String coordInfo = "";
2489 bool hasSameNchan = true;
2490 bool outTextFile = false;
2491
2492 if (blfile != "") {
2493 ofs.open(blfile.c_str(), ios::out | ios::app);
2494 if (ofs) outTextFile = true;
2495 }
2496
2497 if (outLogger || outTextFile) {
2498 coordInfo = getCoordInfo()[0];
2499 if (coordInfo == "") coordInfo = "channel";
2500 hasSameNchan = hasSameNchanOverIFs();
2501 }
2502
2503 Fitter fitter = Fitter();
2504 fitter.setExpression("poly", order);
2505 //fitter.setIterClipping(thresClip, nIterClip);
2506
2507 int nRow = nrow();
2508 std::vector<bool> chanMask;
2509 bool showProgress;
2510 int minNRow;
2511 parseProgressInfo(progressInfo, showProgress, minNRow);
2512
2513 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2514 chanMask = getCompositeChanMask(whichrow, mask);
2515 fitBaseline(chanMask, whichrow, fitter);
2516 setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
2517 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "polyBaseline()", fitter);
2518 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
2519 }
2520
2521 if (outTextFile) ofs.close();
2522
2523 } catch (...) {
2524 throw;
2525 }
2526}
2527
2528void Scantable::autoPolyBaseline(const std::vector<bool>& mask, int order, const std::vector<int>& edge, float threshold, int chanAvgLimit, bool getResidual, const std::string& progressInfo, const bool outLogger, const std::string& blfile)
2529{
2530 try {
2531 ofstream ofs;
2532 String coordInfo = "";
2533 bool hasSameNchan = true;
2534 bool outTextFile = false;
2535
2536 if (blfile != "") {
2537 ofs.open(blfile.c_str(), ios::out | ios::app);
2538 if (ofs) outTextFile = true;
2539 }
2540
2541 if (outLogger || outTextFile) {
2542 coordInfo = getCoordInfo()[0];
2543 if (coordInfo == "") coordInfo = "channel";
2544 hasSameNchan = hasSameNchanOverIFs();
2545 }
2546
2547 Fitter fitter = Fitter();
2548 fitter.setExpression("poly", order);
2549 //fitter.setIterClipping(thresClip, nIterClip);
2550
2551 int nRow = nrow();
2552 std::vector<bool> chanMask;
2553 int minEdgeSize = getIFNos().size()*2;
2554 STLineFinder lineFinder = STLineFinder();
2555 lineFinder.setOptions(threshold, 3, chanAvgLimit);
2556
2557 bool showProgress;
2558 int minNRow;
2559 parseProgressInfo(progressInfo, showProgress, minNRow);
2560
2561 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2562
2563 //-------------------------------------------------------
2564 //chanMask = getCompositeChanMask(whichrow, mask, edge, minEdgeSize, lineFinder);
2565 //-------------------------------------------------------
2566 int edgeSize = edge.size();
2567 std::vector<int> currentEdge;
2568 if (edgeSize >= 2) {
2569 int idx = 0;
2570 if (edgeSize > 2) {
2571 if (edgeSize < minEdgeSize) {
2572 throw(AipsError("Length of edge element info is less than that of IFs"));
2573 }
2574 idx = 2 * getIF(whichrow);
2575 }
2576 currentEdge.push_back(edge[idx]);
2577 currentEdge.push_back(edge[idx+1]);
2578 } else {
2579 throw(AipsError("Wrong length of edge element"));
2580 }
2581 lineFinder.setData(getSpectrum(whichrow));
2582 lineFinder.findLines(getCompositeChanMask(whichrow, mask), currentEdge, whichrow);
2583 chanMask = lineFinder.getMask();
2584 //-------------------------------------------------------
2585
2586 fitBaseline(chanMask, whichrow, fitter);
2587 setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
2588
2589 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "autoPolyBaseline()", fitter);
2590 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
2591 }
2592
2593 if (outTextFile) ofs.close();
2594
2595 } catch (...) {
2596 throw;
2597 }
2598}
2599
2600void Scantable::cubicSplineBaseline(const std::vector<bool>& mask, int nPiece, float thresClip, int nIterClip, bool getResidual, const std::string& progressInfo, const bool outLogger, const std::string& blfile)
2601{
2602 /*************/
2603 //clock_t totTimeStart, totTimeEnd, blTimeStart, blTimeEnd, ioTimeStart, ioTimeEnd;
2604 double totTimeStart, totTimeEnd, blTimeStart, blTimeEnd, ioTimeStart, ioTimeEnd, msTimeStart, msTimeEnd, seTimeStart, seTimeEnd, otTimeStart, otTimeEnd, prTimeStart, prTimeEnd;
2605 double elapseMs = 0.0;
2606 double elapseSe = 0.0;
2607 double elapseOt = 0.0;
2608 double elapsePr = 0.0;
2609 double elapseBl = 0.0;
2610 double elapseIo = 0.0;
2611 //totTimeStart = clock();
2612 totTimeStart = mathutil::gettimeofday_sec();
2613 /*************/
2614
2615 try {
2616 ofstream ofs;
2617 String coordInfo = "";
2618 bool hasSameNchan = true;
2619 bool outTextFile = false;
2620
2621 if (blfile != "") {
2622 ofs.open(blfile.c_str(), ios::out | ios::app);
2623 if (ofs) outTextFile = true;
2624 }
2625
2626 if (outLogger || outTextFile) {
2627 coordInfo = getCoordInfo()[0];
2628 if (coordInfo == "") coordInfo = "channel";
2629 hasSameNchan = hasSameNchanOverIFs();
2630 }
2631
2632 //Fitter fitter = Fitter();
2633 //fitter.setExpression("cspline", nPiece);
2634 //fitter.setIterClipping(thresClip, nIterClip);
2635
2636 bool showProgress;
2637 int minNRow;
2638 parseProgressInfo(progressInfo, showProgress, minNRow);
2639
2640 int nRow = nrow();
2641 std::vector<bool> chanMask;
2642
2643 //--------------------------------
2644 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2645 /******************/
2646 //ioTimeStart = clock();
2647 ioTimeStart = mathutil::gettimeofday_sec();
2648 /**/
2649 std::vector<float> sp = getSpectrum(whichrow);
2650 /**/
2651 //ioTimeEnd = clock();
2652 ioTimeEnd = mathutil::gettimeofday_sec();
2653 elapseIo += (double)(ioTimeEnd - ioTimeStart);
2654
2655 //blTimeStart = clock();
2656 msTimeStart = mathutil::gettimeofday_sec();
2657 /******************/
2658
2659 chanMask = getCompositeChanMask(whichrow, mask);
2660
2661 /**/
2662 msTimeEnd = mathutil::gettimeofday_sec();
2663 elapseMs += (double)(msTimeEnd - msTimeStart);
2664 blTimeStart = mathutil::gettimeofday_sec();
2665 /**/
2666
2667 //fitBaseline(chanMask, whichrow, fitter);
2668 //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
2669 std::vector<int> pieceEdges(nPiece+1);
2670 std::vector<float> params(nPiece*4);
2671 int nClipped = 0;
2672 std::vector<float> res = doCubicSplineFitting(sp, chanMask, nPiece, pieceEdges, params, nClipped, thresClip, nIterClip, getResidual);
2673
2674 /**/
2675 blTimeEnd = mathutil::gettimeofday_sec();
2676 elapseBl += (double)(blTimeEnd - blTimeStart);
2677 seTimeStart = mathutil::gettimeofday_sec();
2678 /**/
2679
2680
2681 setSpectrum(res, whichrow);
2682 //
2683
2684 /**/
2685 seTimeEnd = mathutil::gettimeofday_sec();
2686 elapseSe += (double)(seTimeEnd - seTimeStart);
2687 otTimeStart = mathutil::gettimeofday_sec();
2688 /**/
2689
2690 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "cubicSplineBaseline()", pieceEdges, params, nClipped);
2691
2692 /**/
2693 otTimeEnd = mathutil::gettimeofday_sec();
2694 elapseOt += (double)(otTimeEnd - otTimeStart);
2695 prTimeStart = mathutil::gettimeofday_sec();
2696 /**/
2697
2698 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
2699
2700 /******************/
2701 //blTimeEnd = clock();
2702 prTimeEnd = mathutil::gettimeofday_sec();
2703 elapsePr += (double)(prTimeEnd - prTimeStart);
2704 /******************/
2705 }
2706 //--------------------------------
2707
2708 if (outTextFile) ofs.close();
2709
2710 } catch (...) {
2711 throw;
2712 }
2713 /***************/
2714 //totTimeEnd = clock();
2715 totTimeEnd = mathutil::gettimeofday_sec();
2716 //std::cout << "io : " << elapseIo/CLOCKS_PER_SEC << " (sec.)" << endl;
2717 //std::cout << "bl : " << elapseBl/CLOCKS_PER_SEC << " (sec.)" << endl;
2718 //std::cout << "total : " << (double)(totTimeEnd - totTimeStart)/CLOCKS_PER_SEC << " (sec.)" << endl;
2719 std::cout << "io : " << elapseIo << " (sec.)" << endl;
2720 std::cout << "ms : " << elapseMs << " (sec.)" << endl;
2721 std::cout << "bl : " << elapseBl << " (sec.)" << endl;
2722 std::cout << "se : " << elapseSe << " (sec.)" << endl;
2723 std::cout << "ot : " << elapseOt << " (sec.)" << endl;
2724 std::cout << "pr : " << elapsePr << " (sec.)" << endl;
2725 std::cout << "total : " << (double)(totTimeEnd - totTimeStart) << " (sec.)" << endl;
2726 /***************/
2727}
2728
2729void Scantable::autoCubicSplineBaseline(const std::vector<bool>& mask, int nPiece, float thresClip, int nIterClip, const std::vector<int>& edge, float threshold, int chanAvgLimit, bool getResidual, const std::string& progressInfo, const bool outLogger, const std::string& blfile)
2730{
2731 /*************
2732 clock_t totTimeStart, totTimeEnd, blTimeStart, blTimeEnd, ioTimeStart, ioTimeEnd;
2733 double elapseBl = 0.0;
2734 double elapseIo = 0.0;
2735 totTimeStart = clock();
2736 *************/
2737
2738 try {
2739 ofstream ofs;
2740 String coordInfo = "";
2741 bool hasSameNchan = true;
2742 bool outTextFile = false;
2743
2744 if (blfile != "") {
2745 ofs.open(blfile.c_str(), ios::out | ios::app);
2746 if (ofs) outTextFile = true;
2747 }
2748
2749 if (outLogger || outTextFile) {
2750 coordInfo = getCoordInfo()[0];
2751 if (coordInfo == "") coordInfo = "channel";
2752 hasSameNchan = hasSameNchanOverIFs();
2753 }
2754
2755 //Fitter fitter = Fitter();
2756 //fitter.setExpression("cspline", nPiece);
2757 //fitter.setIterClipping(thresClip, nIterClip);
2758
2759 int nRow = nrow();
2760 std::vector<bool> chanMask;
2761 int minEdgeSize = getIFNos().size()*2;
2762 STLineFinder lineFinder = STLineFinder();
2763 lineFinder.setOptions(threshold, 3, chanAvgLimit);
2764
2765 bool showProgress;
2766 int minNRow;
2767 parseProgressInfo(progressInfo, showProgress, minNRow);
2768
2769 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
2770 /******************
2771 ioTimeStart = clock();
2772 */
2773 std::vector<float> sp = getSpectrum(whichrow);
2774 /*
2775 ioTimeEnd = clock();
2776 elapseIo += (double)(ioTimeEnd - ioTimeStart);
2777
2778 blTimeStart = clock();
2779 ******************/
2780
2781 //-------------------------------------------------------
2782 //chanMask = getCompositeChanMask(whichrow, mask, edge, minEdgeSize, lineFinder);
2783 //-------------------------------------------------------
2784 int edgeSize = edge.size();
2785 std::vector<int> currentEdge;
2786 if (edgeSize >= 2) {
2787 int idx = 0;
2788 if (edgeSize > 2) {
2789 if (edgeSize < minEdgeSize) {
2790 throw(AipsError("Length of edge element info is less than that of IFs"));
2791 }
2792 idx = 2 * getIF(whichrow);
2793 }
2794 currentEdge.push_back(edge[idx]);
2795 currentEdge.push_back(edge[idx+1]);
2796 } else {
2797 throw(AipsError("Wrong length of edge element"));
2798 }
2799 lineFinder.setData(getSpectrum(whichrow));
2800 lineFinder.findLines(getCompositeChanMask(whichrow, mask), currentEdge, whichrow);
2801 chanMask = lineFinder.getMask();
2802 //-------------------------------------------------------
2803
2804
2805 //fitBaseline(chanMask, whichrow, fitter);
2806 //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
2807 std::vector<int> pieceEdges(nPiece+1);
2808 std::vector<float> params(nPiece*4);
2809 int nClipped = 0;
2810 std::vector<float> res = doCubicSplineFitting(sp, chanMask, nPiece, pieceEdges, params, nClipped, thresClip, nIterClip, getResidual);
2811 setSpectrum(res, whichrow);
2812 //
2813
2814 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "autoCubicSplineBaseline()", pieceEdges, params, nClipped);
2815 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
2816
2817 /******************
2818 blTimeEnd = clock();
2819 elapseBl += (double)(blTimeEnd - blTimeStart);
2820 ******************/
2821
2822 }
2823
2824 if (outTextFile) ofs.close();
2825
2826 } catch (...) {
2827 throw;
2828 }
2829
2830 /***************
2831 totTimeEnd = clock();
2832 std::cout << "io : " << elapseIo/CLOCKS_PER_SEC << " (sec.)" << endl;
2833 std::cout << "bl : " << elapseBl/CLOCKS_PER_SEC << " (sec.)" << endl;
2834 std::cout << "total : " << (double)(totTimeEnd - totTimeStart)/CLOCKS_PER_SEC << " (sec.)" << endl;
2835 ***************/
2836}
2837
2838std::vector<float> Scantable::doCubicSplineFitting(const std::vector<float>& data, const std::vector<bool>& mask, int nPiece, std::vector<int>& idxEdge, std::vector<float>& params, int& nClipped, float thresClip, int nIterClip, bool getResidual)
2839{
2840 if (data.size() != mask.size()) {
2841 throw(AipsError("data and mask sizes are not identical"));
2842 }
2843 if (nPiece < 1) {
2844 throw(AipsError("number of the sections must be one or more"));
2845 }
2846
2847 int nChan = data.size();
2848 std::vector<int> maskArray(nChan);
2849 std::vector<int> x(nChan);
2850 int j = 0;
2851 for (int i = 0; i < nChan; ++i) {
2852 maskArray[i] = mask[i] ? 1 : 0;
2853 if (mask[i]) {
2854 x[j] = i;
2855 j++;
2856 }
2857 }
2858 int initNData = j;
2859
2860 if (initNData < nPiece) {
2861 throw(AipsError("too few non-flagged channels"));
2862 }
2863
2864 int nElement = (int)(floor(floor((double)(initNData/nPiece))+0.5));
2865 std::vector<double> invEdge(nPiece-1);
2866 idxEdge[0] = x[0];
2867 for (int i = 1; i < nPiece; ++i) {
2868 int valX = x[nElement*i];
2869 idxEdge[i] = valX;
2870 invEdge[i-1] = 1.0/(double)valX;
2871 }
2872 idxEdge[nPiece] = x[initNData-1]+1;
2873
2874 int nData = initNData;
2875 int nDOF = nPiece + 3; //number of parameters to solve, namely, 4+(nPiece-1).
2876
2877 std::vector<double> x1(nChan), x2(nChan), x3(nChan);
2878 std::vector<double> z1(nChan), x1z1(nChan), x2z1(nChan), x3z1(nChan);
2879 std::vector<double> r1(nChan), residual(nChan);
2880 for (int i = 0; i < nChan; ++i) {
2881 double di = (double)i;
2882 double dD = (double)data[i];
2883 x1[i] = di;
2884 x2[i] = di*di;
2885 x3[i] = di*di*di;
2886 z1[i] = dD;
2887 x1z1[i] = dD*di;
2888 x2z1[i] = dD*di*di;
2889 x3z1[i] = dD*di*di*di;
2890 r1[i] = 0.0;
2891 residual[i] = 0.0;
2892 }
2893
2894 for (int nClip = 0; nClip < nIterClip+1; ++nClip) {
2895 // xMatrix : horizontal concatenation of
2896 // the least-sq. matrix (left) and an
2897 // identity matrix (right).
2898 // the right part is used to calculate the inverse matrix of the left part.
2899 double xMatrix[nDOF][2*nDOF];
2900 double zMatrix[nDOF];
2901 for (int i = 0; i < nDOF; ++i) {
2902 for (int j = 0; j < 2*nDOF; ++j) {
2903 xMatrix[i][j] = 0.0;
2904 }
2905 xMatrix[i][nDOF+i] = 1.0;
2906 zMatrix[i] = 0.0;
2907 }
2908
2909 for (int n = 0; n < nPiece; ++n) {
2910 int nUseDataInPiece = 0;
2911 for (int i = idxEdge[n]; i < idxEdge[n+1]; ++i) {
2912
2913 if (maskArray[i] == 0) continue;
2914
2915 xMatrix[0][0] += 1.0;
2916 xMatrix[0][1] += x1[i];
2917 xMatrix[0][2] += x2[i];
2918 xMatrix[0][3] += x3[i];
2919 xMatrix[1][1] += x2[i];
2920 xMatrix[1][2] += x3[i];
2921 xMatrix[1][3] += x2[i]*x2[i];
2922 xMatrix[2][2] += x2[i]*x2[i];
2923 xMatrix[2][3] += x3[i]*x2[i];
2924 xMatrix[3][3] += x3[i]*x3[i];
2925 zMatrix[0] += z1[i];
2926 zMatrix[1] += x1z1[i];
2927 zMatrix[2] += x2z1[i];
2928 zMatrix[3] += x3z1[i];
2929
2930 for (int j = 0; j < n; ++j) {
2931 double q = 1.0 - x1[i]*invEdge[j];
2932 q = q*q*q;
2933 xMatrix[0][j+4] += q;
2934 xMatrix[1][j+4] += q*x1[i];
2935 xMatrix[2][j+4] += q*x2[i];
2936 xMatrix[3][j+4] += q*x3[i];
2937 for (int k = 0; k < j; ++k) {
2938 double r = 1.0 - x1[i]*invEdge[k];
2939 r = r*r*r;
2940 xMatrix[k+4][j+4] += r*q;
2941 }
2942 xMatrix[j+4][j+4] += q*q;
2943 zMatrix[j+4] += q*z1[i];
2944 }
2945
2946 nUseDataInPiece++;
2947 }
2948
2949 if (nUseDataInPiece < 1) {
2950 std::vector<string> suffixOfPieceNumber(4);
2951 suffixOfPieceNumber[0] = "th";
2952 suffixOfPieceNumber[1] = "st";
2953 suffixOfPieceNumber[2] = "nd";
2954 suffixOfPieceNumber[3] = "rd";
2955 int idxNoDataPiece = (n % 10 <= 3) ? n : 0;
2956 ostringstream oss;
2957 oss << "all channels clipped or masked in " << n << suffixOfPieceNumber[idxNoDataPiece];
2958 oss << " piece of the spectrum. can't execute fitting anymore.";
2959 throw(AipsError(String(oss)));
2960 }
2961 }
2962
2963 for (int i = 0; i < nDOF; ++i) {
2964 for (int j = 0; j < i; ++j) {
2965 xMatrix[i][j] = xMatrix[j][i];
2966 }
2967 }
2968
2969 std::vector<double> invDiag(nDOF);
2970 for (int i = 0; i < nDOF; ++i) {
2971 invDiag[i] = 1.0/xMatrix[i][i];
2972 for (int j = 0; j < nDOF; ++j) {
2973 xMatrix[i][j] *= invDiag[i];
2974 }
2975 }
2976
2977 for (int k = 0; k < nDOF; ++k) {
2978 for (int i = 0; i < nDOF; ++i) {
2979 if (i != k) {
2980 double factor1 = xMatrix[k][k];
2981 double factor2 = xMatrix[i][k];
2982 for (int j = k; j < 2*nDOF; ++j) {
2983 xMatrix[i][j] *= factor1;
2984 xMatrix[i][j] -= xMatrix[k][j]*factor2;
2985 xMatrix[i][j] /= factor1;
2986 }
2987 }
2988 }
2989 double xDiag = xMatrix[k][k];
2990 for (int j = k; j < 2*nDOF; ++j) {
2991 xMatrix[k][j] /= xDiag;
2992 }
2993 }
2994
2995 for (int i = 0; i < nDOF; ++i) {
2996 for (int j = 0; j < nDOF; ++j) {
2997 xMatrix[i][nDOF+j] *= invDiag[j];
2998 }
2999 }
3000 //compute a vector y which consists of the coefficients of the best-fit spline curves
3001 //(a0,a1,a2,a3(,b3,c3,...)), namely, the ones for the leftmost piece and the ones of
3002 //cubic terms for the other pieces (in case nPiece>1).
3003 std::vector<double> y(nDOF);
3004 for (int i = 0; i < nDOF; ++i) {
3005 y[i] = 0.0;
3006 for (int j = 0; j < nDOF; ++j) {
3007 y[i] += xMatrix[i][nDOF+j]*zMatrix[j];
3008 }
3009 }
3010
3011 double a0 = y[0];
3012 double a1 = y[1];
3013 double a2 = y[2];
3014 double a3 = y[3];
3015
3016 int j = 0;
3017 for (int n = 0; n < nPiece; ++n) {
3018 for (int i = idxEdge[n]; i < idxEdge[n+1]; ++i) {
3019 r1[i] = a0 + a1*x1[i] + a2*x2[i] + a3*x3[i];
3020 }
3021 params[j] = a0;
3022 params[j+1] = a1;
3023 params[j+2] = a2;
3024 params[j+3] = a3;
3025 j += 4;
3026
3027 if (n == nPiece-1) break;
3028
3029 double d = y[4+n];
3030 double iE = invEdge[n];
3031 a0 += d;
3032 a1 -= 3.0*d*iE;
3033 a2 += 3.0*d*iE*iE;
3034 a3 -= d*iE*iE*iE;
3035 }
3036
3037 //subtract constant value for masked regions at the edge of spectrum
3038 if (idxEdge[0] > 0) {
3039 int n = idxEdge[0];
3040 for (int i = 0; i < idxEdge[0]; ++i) {
3041 //--cubic extrapolate--
3042 //r1[i] = params[0] + params[1]*x1[i] + params[2]*x2[i] + params[3]*x3[i];
3043 //--linear extrapolate--
3044 //r1[i] = (r1[n+1] - r1[n])/(x1[n+1] - x1[n])*(x1[i] - x1[n]) + r1[n];
3045 //--constant--
3046 r1[i] = r1[n];
3047 }
3048 }
3049 if (idxEdge[nPiece] < nChan) {
3050 int n = idxEdge[nPiece]-1;
3051 for (int i = idxEdge[nPiece]; i < nChan; ++i) {
3052 //--cubic extrapolate--
3053 //int m = 4*(nPiece-1);
3054 //r1[i] = params[m] + params[m+1]*x1[i] + params[m+2]*x2[i] + params[m+3]*x3[i];
3055 //--linear extrapolate--
3056 //r1[i] = (r1[n-1] - r1[n])/(x1[n-1] - x1[n])*(x1[i] - x1[n]) + r1[n];
3057 //--constant--
3058 r1[i] = r1[n];
3059 }
3060 }
3061
3062 for (int i = 0; i < nChan; ++i) {
3063 residual[i] = z1[i] - r1[i];
3064 }
3065
3066 if ((nClip == nIterClip) || (thresClip <= 0.0)) {
3067 break;
3068 } else {
3069 double stdDev = 0.0;
3070 for (int i = 0; i < nChan; ++i) {
3071 stdDev += residual[i]*residual[i]*(double)maskArray[i];
3072 }
3073 stdDev = sqrt(stdDev/(double)nData);
3074
3075 double thres = stdDev * thresClip;
3076 int newNData = 0;
3077 for (int i = 0; i < nChan; ++i) {
3078 if (abs(residual[i]) >= thres) {
3079 maskArray[i] = 0;
3080 }
3081 if (maskArray[i] > 0) {
3082 newNData++;
3083 }
3084 }
3085 if (newNData == nData) {
3086 break; //no more flag to add. iteration stops.
3087 } else {
3088 nData = newNData;
3089 }
3090 }
3091 }
3092
3093 nClipped = initNData - nData;
3094
3095 std::vector<float> result(nChan);
3096 if (getResidual) {
3097 for (int i = 0; i < nChan; ++i) {
3098 result[i] = (float)residual[i];
3099 }
3100 } else {
3101 for (int i = 0; i < nChan; ++i) {
3102 result[i] = (float)r1[i];
3103 }
3104 }
3105
3106 return result;
3107}
3108
3109void Scantable::selectWaveNumbers(const int whichrow, const std::vector<bool>& chanMask, const bool applyFFT, const std::string& fftMethod, const std::string& fftThresh, const std::vector<int>& addNWaves, const std::vector<int>& rejectNWaves, std::vector<int>& nWaves)
3110{
3111 nWaves.clear();
3112
3113 if (applyFFT) {
3114 string fftThAttr;
3115 float fftThSigma;
3116 int fftThTop;
3117 parseThresholdExpression(fftThresh, fftThAttr, fftThSigma, fftThTop);
3118 doSelectWaveNumbers(whichrow, chanMask, fftMethod, fftThSigma, fftThTop, fftThAttr, nWaves);
3119 }
3120
3121 addAuxWaveNumbers(whichrow, addNWaves, rejectNWaves, nWaves);
3122}
3123
3124void Scantable::parseThresholdExpression(const std::string& fftThresh, std::string& fftThAttr, float& fftThSigma, int& fftThTop)
3125{
3126 uInt idxSigma = fftThresh.find("sigma");
3127 uInt idxTop = fftThresh.find("top");
3128
3129 if (idxSigma == fftThresh.size() - 5) {
3130 std::istringstream is(fftThresh.substr(0, fftThresh.size() - 5));
3131 is >> fftThSigma;
3132 fftThAttr = "sigma";
3133 } else if (idxTop == 0) {
3134 std::istringstream is(fftThresh.substr(3));
3135 is >> fftThTop;
3136 fftThAttr = "top";
3137 } else {
3138 bool isNumber = true;
3139 for (uInt i = 0; i < fftThresh.size()-1; ++i) {
3140 char ch = (fftThresh.substr(i, 1).c_str())[0];
3141 if (!(isdigit(ch) || (fftThresh.substr(i, 1) == "."))) {
3142 isNumber = false;
3143 break;
3144 }
3145 }
3146 if (isNumber) {
3147 std::istringstream is(fftThresh);
3148 is >> fftThSigma;
3149 fftThAttr = "sigma";
3150 } else {
3151 throw(AipsError("fftthresh has a wrong value"));
3152 }
3153 }
3154}
3155
3156void Scantable::doSelectWaveNumbers(const int whichrow, const std::vector<bool>& chanMask, const std::string& fftMethod, const float fftThSigma, const int fftThTop, const std::string& fftThAttr, std::vector<int>& nWaves)
3157{
3158 std::vector<float> fspec;
3159 if (fftMethod == "fft") {
3160 fspec = execFFT(whichrow, chanMask, false, true);
3161 //} else if (fftMethod == "lsp") {
3162 // fspec = lombScarglePeriodogram(whichrow);
3163 }
3164
3165 if (fftThAttr == "sigma") {
3166 float mean = 0.0;
3167 float mean2 = 0.0;
3168 for (uInt i = 0; i < fspec.size(); ++i) {
3169 mean += fspec[i];
3170 mean2 += fspec[i]*fspec[i];
3171 }
3172 mean /= float(fspec.size());
3173 mean2 /= float(fspec.size());
3174 float thres = mean + fftThSigma * float(sqrt(mean2 - mean*mean));
3175
3176 for (uInt i = 0; i < fspec.size(); ++i) {
3177 if (fspec[i] >= thres) {
3178 nWaves.push_back(i);
3179 }
3180 }
3181
3182 } else if (fftThAttr == "top") {
3183 for (int i = 0; i < fftThTop; ++i) {
3184 float max = 0.0;
3185 int maxIdx = 0;
3186 for (uInt j = 0; j < fspec.size(); ++j) {
3187 if (fspec[j] > max) {
3188 max = fspec[j];
3189 maxIdx = j;
3190 }
3191 }
3192 nWaves.push_back(maxIdx);
3193 fspec[maxIdx] = 0.0;
3194 }
3195
3196 }
3197
3198 if (nWaves.size() > 1) {
3199 sort(nWaves.begin(), nWaves.end());
3200 }
3201}
3202
3203void Scantable::addAuxWaveNumbers(const int whichrow, const std::vector<int>& addNWaves, const std::vector<int>& rejectNWaves, std::vector<int>& nWaves)
3204{
3205 std::vector<int> tempAddNWaves, tempRejectNWaves;
3206 for (uInt i = 0; i < addNWaves.size(); ++i) {
3207 tempAddNWaves.push_back(addNWaves[i]);
3208 }
3209 if ((tempAddNWaves.size() == 2) && (tempAddNWaves[1] == -999)) {
3210 setWaveNumberListUptoNyquistFreq(whichrow, tempAddNWaves);
3211 }
3212
3213 for (uInt i = 0; i < rejectNWaves.size(); ++i) {
3214 tempRejectNWaves.push_back(rejectNWaves[i]);
3215 }
3216 if ((tempRejectNWaves.size() == 2) && (tempRejectNWaves[1] == -999)) {
3217 setWaveNumberListUptoNyquistFreq(whichrow, tempRejectNWaves);
3218 }
3219
3220 for (uInt i = 0; i < tempAddNWaves.size(); ++i) {
3221 bool found = false;
3222 for (uInt j = 0; j < nWaves.size(); ++j) {
3223 if (nWaves[j] == tempAddNWaves[i]) {
3224 found = true;
3225 break;
3226 }
3227 }
3228 if (!found) nWaves.push_back(tempAddNWaves[i]);
3229 }
3230
3231 for (uInt i = 0; i < tempRejectNWaves.size(); ++i) {
3232 for (std::vector<int>::iterator j = nWaves.begin(); j != nWaves.end(); ) {
3233 if (*j == tempRejectNWaves[i]) {
3234 j = nWaves.erase(j);
3235 } else {
3236 ++j;
3237 }
3238 }
3239 }
3240
3241 if (nWaves.size() > 1) {
3242 sort(nWaves.begin(), nWaves.end());
3243 unique(nWaves.begin(), nWaves.end());
3244 }
3245}
3246
3247void Scantable::setWaveNumberListUptoNyquistFreq(const int whichrow, std::vector<int>& nWaves)
3248{
3249 if ((nWaves.size() == 2)&&(nWaves[1] == -999)) {
3250 int val = nWaves[0];
3251 int nyquistFreq = nchan(getIF(whichrow))/2+1;
3252 nWaves.clear();
3253 if (val > nyquistFreq) { // for safety, at least nWaves contains a constant; CAS-3759
3254 nWaves.push_back(0);
3255 }
3256 while (val <= nyquistFreq) {
3257 nWaves.push_back(val);
3258 val++;
3259 }
3260 }
3261}
3262
3263void Scantable::sinusoidBaseline(const std::vector<bool>& mask, const bool applyFFT, const std::string& fftMethod, const std::string& fftThresh, const std::vector<int>& addNWaves, const std::vector<int>& rejectNWaves, float thresClip, int nIterClip, bool getResidual, const std::string& progressInfo, const bool outLogger, const std::string& blfile)
3264{
3265 try {
3266 ofstream ofs;
3267 String coordInfo = "";
3268 bool hasSameNchan = true;
3269 bool outTextFile = false;
3270
3271 if (blfile != "") {
3272 ofs.open(blfile.c_str(), ios::out | ios::app);
3273 if (ofs) outTextFile = true;
3274 }
3275
3276 if (outLogger || outTextFile) {
3277 coordInfo = getCoordInfo()[0];
3278 if (coordInfo == "") coordInfo = "channel";
3279 hasSameNchan = hasSameNchanOverIFs();
3280 }
3281
3282 //Fitter fitter = Fitter();
3283 //fitter.setExpression("sinusoid", nWaves);
3284 //fitter.setIterClipping(thresClip, nIterClip);
3285
3286 int nRow = nrow();
3287 std::vector<bool> chanMask;
3288 std::vector<int> nWaves;
3289
3290 bool showProgress;
3291 int minNRow;
3292 parseProgressInfo(progressInfo, showProgress, minNRow);
3293
3294 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
3295 chanMask = getCompositeChanMask(whichrow, mask);
3296 selectWaveNumbers(whichrow, chanMask, applyFFT, fftMethod, fftThresh, addNWaves, rejectNWaves, nWaves);
3297
3298 //FOR DEBUGGING------------
3299 /*
3300 if (whichrow < 0) {// == nRow -1) {
3301 cout << "+++ i=" << setw(3) << whichrow << ", IF=" << setw(2) << getIF(whichrow);
3302 if (applyFFT) {
3303 cout << "[ ";
3304 for (uInt j = 0; j < nWaves.size(); ++j) {
3305 cout << nWaves[j] << ", ";
3306 }
3307 cout << " ] " << endl;
3308 }
3309 cout << flush;
3310 }
3311 */
3312 //-------------------------
3313
3314 //fitBaseline(chanMask, whichrow, fitter);
3315 //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
3316 std::vector<float> params;
3317 int nClipped = 0;
3318 std::vector<float> res = doSinusoidFitting(getSpectrum(whichrow), chanMask, nWaves, params, nClipped, thresClip, nIterClip, getResidual);
3319 setSpectrum(res, whichrow);
3320 //
3321
3322 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "sinusoidBaseline()", params, nClipped);
3323 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
3324 }
3325
3326 if (outTextFile) ofs.close();
3327
3328 } catch (...) {
3329 throw;
3330 }
3331}
3332
3333void Scantable::autoSinusoidBaseline(const std::vector<bool>& mask, const bool applyFFT, const std::string& fftMethod, const std::string& fftThresh, const std::vector<int>& addNWaves, const std::vector<int>& rejectNWaves, float thresClip, int nIterClip, const std::vector<int>& edge, float threshold, int chanAvgLimit, bool getResidual, const std::string& progressInfo, const bool outLogger, const std::string& blfile)
3334{
3335 try {
3336 ofstream ofs;
3337 String coordInfo = "";
3338 bool hasSameNchan = true;
3339 bool outTextFile = false;
3340
3341 if (blfile != "") {
3342 ofs.open(blfile.c_str(), ios::out | ios::app);
3343 if (ofs) outTextFile = true;
3344 }
3345
3346 if (outLogger || outTextFile) {
3347 coordInfo = getCoordInfo()[0];
3348 if (coordInfo == "") coordInfo = "channel";
3349 hasSameNchan = hasSameNchanOverIFs();
3350 }
3351
3352 //Fitter fitter = Fitter();
3353 //fitter.setExpression("sinusoid", nWaves);
3354 //fitter.setIterClipping(thresClip, nIterClip);
3355
3356 int nRow = nrow();
3357 std::vector<bool> chanMask;
3358 std::vector<int> nWaves;
3359
3360 int minEdgeSize = getIFNos().size()*2;
3361 STLineFinder lineFinder = STLineFinder();
3362 lineFinder.setOptions(threshold, 3, chanAvgLimit);
3363
3364 bool showProgress;
3365 int minNRow;
3366 parseProgressInfo(progressInfo, showProgress, minNRow);
3367
3368 for (int whichrow = 0; whichrow < nRow; ++whichrow) {
3369
3370 //-------------------------------------------------------
3371 //chanMask = getCompositeChanMask(whichrow, mask, edge, minEdgeSize, lineFinder);
3372 //-------------------------------------------------------
3373 int edgeSize = edge.size();
3374 std::vector<int> currentEdge;
3375 if (edgeSize >= 2) {
3376 int idx = 0;
3377 if (edgeSize > 2) {
3378 if (edgeSize < minEdgeSize) {
3379 throw(AipsError("Length of edge element info is less than that of IFs"));
3380 }
3381 idx = 2 * getIF(whichrow);
3382 }
3383 currentEdge.push_back(edge[idx]);
3384 currentEdge.push_back(edge[idx+1]);
3385 } else {
3386 throw(AipsError("Wrong length of edge element"));
3387 }
3388 lineFinder.setData(getSpectrum(whichrow));
3389 lineFinder.findLines(getCompositeChanMask(whichrow, mask), currentEdge, whichrow);
3390 chanMask = lineFinder.getMask();
3391 //-------------------------------------------------------
3392
3393 selectWaveNumbers(whichrow, chanMask, applyFFT, fftMethod, fftThresh, addNWaves, rejectNWaves, nWaves);
3394
3395 //fitBaseline(chanMask, whichrow, fitter);
3396 //setSpectrum((getResidual ? fitter.getResidual() : fitter.getFit()), whichrow);
3397 std::vector<float> params;
3398 int nClipped = 0;
3399 std::vector<float> res = doSinusoidFitting(getSpectrum(whichrow), chanMask, nWaves, params, nClipped, thresClip, nIterClip, getResidual);
3400 setSpectrum(res, whichrow);
3401 //
3402
3403 outputFittingResult(outLogger, outTextFile, chanMask, whichrow, coordInfo, hasSameNchan, ofs, "autoSinusoidBaseline()", params, nClipped);
3404 showProgressOnTerminal(whichrow, nRow, showProgress, minNRow);
3405 }
3406
3407 if (outTextFile) ofs.close();
3408
3409 } catch (...) {
3410 throw;
3411 }
3412}
3413
3414std::vector<float> Scantable::doSinusoidFitting(const std::vector<float>& data, const std::vector<bool>& mask, const std::vector<int>& waveNumbers, std::vector<float>& params, int& nClipped, float thresClip, int nIterClip, bool getResidual)
3415{
3416 if (data.size() != mask.size()) {
3417 throw(AipsError("data and mask sizes are not identical"));
3418 }
3419 if (data.size() < 2) {
3420 throw(AipsError("data size is too short"));
3421 }
3422 if (waveNumbers.size() == 0) {
3423 throw(AipsError("no wave numbers given"));
3424 }
3425 std::vector<int> nWaves; // sorted and uniqued array of wave numbers
3426 nWaves.reserve(waveNumbers.size());
3427 copy(waveNumbers.begin(), waveNumbers.end(), back_inserter(nWaves));
3428 sort(nWaves.begin(), nWaves.end());
3429 std::vector<int>::iterator end_it = unique(nWaves.begin(), nWaves.end());
3430 nWaves.erase(end_it, nWaves.end());
3431
3432 int minNWaves = nWaves[0];
3433 if (minNWaves < 0) {
3434 throw(AipsError("wave number must be positive or zero (i.e. constant)"));
3435 }
3436 bool hasConstantTerm = (minNWaves == 0);
3437
3438 int nChan = data.size();
3439 std::vector<int> maskArray;
3440 std::vector<int> x;
3441 for (int i = 0; i < nChan; ++i) {
3442 maskArray.push_back(mask[i] ? 1 : 0);
3443 if (mask[i]) {
3444 x.push_back(i);
3445 }
3446 }
3447
3448 int initNData = x.size();
3449
3450 int nData = initNData;
3451 int nDOF = nWaves.size() * 2 - (hasConstantTerm ? 1 : 0); //number of parameters to solve.
3452
3453 const double PI = 6.0 * asin(0.5); // PI (= 3.141592653...)
3454 double baseXFactor = 2.0*PI/(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)
3455
3456 // xArray : contains elemental values for computing the least-square matrix.
3457 // xArray.size() is nDOF and xArray[*].size() is nChan.
3458 // Each xArray element are as follows:
3459 // xArray[0] = {1.0, 1.0, 1.0, ..., 1.0},
3460 // xArray[2n-1] = {sin(nPI/L*x[0]), sin(nPI/L*x[1]), ..., sin(nPI/L*x[nChan])},
3461 // xArray[2n] = {cos(nPI/L*x[0]), cos(nPI/L*x[1]), ..., cos(nPI/L*x[nChan])},
3462 // where (1 <= n <= nMaxWavesInSW),
3463 // or,
3464 // xArray[2n-1] = {sin(wn[n]PI/L*x[0]), sin(wn[n]PI/L*x[1]), ..., sin(wn[n]PI/L*x[nChan])},
3465 // xArray[2n] = {cos(wn[n]PI/L*x[0]), cos(wn[n]PI/L*x[1]), ..., cos(wn[n]PI/L*x[nChan])},
3466 // where wn[n] denotes waveNumbers[n] (1 <= n <= waveNumbers.size()).
3467 std::vector<std::vector<double> > xArray;
3468 if (hasConstantTerm) {
3469 std::vector<double> xu;
3470 for (int j = 0; j < nChan; ++j) {
3471 xu.push_back(1.0);
3472 }
3473 xArray.push_back(xu);
3474 }
3475 for (uInt i = (hasConstantTerm ? 1 : 0); i < nWaves.size(); ++i) {
3476 double xFactor = baseXFactor*(double)nWaves[i];
3477 std::vector<double> xs, xc;
3478 xs.clear();
3479 xc.clear();
3480 for (int j = 0; j < nChan; ++j) {
3481 xs.push_back(sin(xFactor*(double)j));
3482 xc.push_back(cos(xFactor*(double)j));
3483 }
3484 xArray.push_back(xs);
3485 xArray.push_back(xc);
3486 }
3487
3488 std::vector<double> z1, r1, residual;
3489 for (int i = 0; i < nChan; ++i) {
3490 z1.push_back((double)data[i]);
3491 r1.push_back(0.0);
3492 residual.push_back(0.0);
3493 }
3494
3495 for (int nClip = 0; nClip < nIterClip+1; ++nClip) {
3496 // xMatrix : horizontal concatenation of
3497 // the least-sq. matrix (left) and an
3498 // identity matrix (right).
3499 // the right part is used to calculate the inverse matrix of the left part.
3500 double xMatrix[nDOF][2*nDOF];
3501 double zMatrix[nDOF];
3502 for (int i = 0; i < nDOF; ++i) {
3503 for (int j = 0; j < 2*nDOF; ++j) {
3504 xMatrix[i][j] = 0.0;
3505 }
3506 xMatrix[i][nDOF+i] = 1.0;
3507 zMatrix[i] = 0.0;
3508 }
3509
3510 int nUseData = 0;
3511 for (int k = 0; k < nChan; ++k) {
3512 if (maskArray[k] == 0) continue;
3513
3514 for (int i = 0; i < nDOF; ++i) {
3515 for (int j = i; j < nDOF; ++j) {
3516 xMatrix[i][j] += xArray[i][k] * xArray[j][k];
3517 }
3518 zMatrix[i] += z1[k] * xArray[i][k];
3519 }
3520
3521 nUseData++;
3522 }
3523
3524 if (nUseData < 1) {
3525 throw(AipsError("all channels clipped or masked. can't execute fitting anymore."));
3526 }
3527
3528 for (int i = 0; i < nDOF; ++i) {
3529 for (int j = 0; j < i; ++j) {
3530 xMatrix[i][j] = xMatrix[j][i];
3531 }
3532 }
3533
3534 std::vector<double> invDiag;
3535 for (int i = 0; i < nDOF; ++i) {
3536 invDiag.push_back(1.0/xMatrix[i][i]);
3537 for (int j = 0; j < nDOF; ++j) {
3538 xMatrix[i][j] *= invDiag[i];
3539 }
3540 }
3541
3542 for (int k = 0; k < nDOF; ++k) {
3543 for (int i = 0; i < nDOF; ++i) {
3544 if (i != k) {
3545 double factor1 = xMatrix[k][k];
3546 double factor2 = xMatrix[i][k];
3547 for (int j = k; j < 2*nDOF; ++j) {
3548 xMatrix[i][j] *= factor1;
3549 xMatrix[i][j] -= xMatrix[k][j]*factor2;
3550 xMatrix[i][j] /= factor1;
3551 }
3552 }
3553 }
3554 double xDiag = xMatrix[k][k];
3555 for (int j = k; j < 2*nDOF; ++j) {
3556 xMatrix[k][j] /= xDiag;
3557 }
3558 }
3559
3560 for (int i = 0; i < nDOF; ++i) {
3561 for (int j = 0; j < nDOF; ++j) {
3562 xMatrix[i][nDOF+j] *= invDiag[j];
3563 }
3564 }
3565 //compute a vector y which consists of the coefficients of the sinusoids forming the
3566 //best-fit curves (a0,s1,c1,s2,c2,...), where a0 is constant and s* and c* are of sine
3567 //and cosine functions, respectively.
3568 std::vector<double> y;
3569 params.clear();
3570 for (int i = 0; i < nDOF; ++i) {
3571 y.push_back(0.0);
3572 for (int j = 0; j < nDOF; ++j) {
3573 y[i] += xMatrix[i][nDOF+j]*zMatrix[j];
3574 }
3575 params.push_back(y[i]);
3576 }
3577
3578 for (int i = 0; i < nChan; ++i) {
3579 r1[i] = y[0];
3580 for (int j = 1; j < nDOF; ++j) {
3581 r1[i] += y[j]*xArray[j][i];
3582 }
3583 residual[i] = z1[i] - r1[i];
3584 }
3585
3586 if ((nClip == nIterClip) || (thresClip <= 0.0)) {
3587 break;
3588 } else {
3589 double stdDev = 0.0;
3590 for (int i = 0; i < nChan; ++i) {
3591 stdDev += residual[i]*residual[i]*(double)maskArray[i];
3592 }
3593 stdDev = sqrt(stdDev/(double)nData);
3594
3595 double thres = stdDev * thresClip;
3596 int newNData = 0;
3597 for (int i = 0; i < nChan; ++i) {
3598 if (abs(residual[i]) >= thres) {
3599 maskArray[i] = 0;
3600 }
3601 if (maskArray[i] > 0) {
3602 newNData++;
3603 }
3604 }
3605 if (newNData == nData) {
3606 break; //no more flag to add. iteration stops.
3607 } else {
3608 nData = newNData;
3609 }
3610 }
3611 }
3612
3613 nClipped = initNData - nData;
3614
3615 std::vector<float> result;
3616 if (getResidual) {
3617 for (int i = 0; i < nChan; ++i) {
3618 result.push_back((float)residual[i]);
3619 }
3620 } else {
3621 for (int i = 0; i < nChan; ++i) {
3622 result.push_back((float)r1[i]);
3623 }
3624 }
3625
3626 return result;
3627}
3628
3629void Scantable::fitBaseline(const std::vector<bool>& mask, int whichrow, Fitter& fitter)
3630{
3631 std::vector<double> dAbcissa = getAbcissa(whichrow);
3632 std::vector<float> abcissa;
3633 for (uInt i = 0; i < dAbcissa.size(); ++i) {
3634 abcissa.push_back((float)dAbcissa[i]);
3635 }
3636 std::vector<float> spec = getSpectrum(whichrow);
3637
3638 fitter.setData(abcissa, spec, mask);
3639 fitter.lfit();
3640}
3641
3642std::vector<bool> Scantable::getCompositeChanMask(int whichrow, const std::vector<bool>& inMask)
3643{
3644 /****
3645 double ms1TimeStart, ms1TimeEnd, ms2TimeStart, ms2TimeEnd;
3646 double elapse1 = 0.0;
3647 double elapse2 = 0.0;
3648
3649 ms1TimeStart = mathutil::gettimeofday_sec();
3650 ****/
3651
3652 std::vector<bool> mask = getMask(whichrow);
3653
3654 /****
3655 ms1TimeEnd = mathutil::gettimeofday_sec();
3656 elapse1 = ms1TimeEnd - ms1TimeStart;
3657 std::cout << "ms1 : " << elapse1 << " (sec.)" << endl;
3658 ms2TimeStart = mathutil::gettimeofday_sec();
3659 ****/
3660
3661 uInt maskSize = mask.size();
3662 if (inMask.size() != 0) {
3663 if (maskSize != inMask.size()) {
3664 throw(AipsError("mask sizes are not the same."));
3665 }
3666 for (uInt i = 0; i < maskSize; ++i) {
3667 mask[i] = mask[i] && inMask[i];
3668 }
3669 }
3670
3671 /****
3672 ms2TimeEnd = mathutil::gettimeofday_sec();
3673 elapse2 = ms2TimeEnd - ms2TimeStart;
3674 std::cout << "ms2 : " << elapse2 << " (sec.)" << endl;
3675 ****/
3676
3677 return mask;
3678}
3679
3680/*
3681std::vector<bool> Scantable::getCompositeChanMask(int whichrow, const std::vector<bool>& inMask, const std::vector<int>& edge, const int minEdgeSize, STLineFinder& lineFinder)
3682{
3683 int edgeSize = edge.size();
3684 std::vector<int> currentEdge;
3685 if (edgeSize >= 2) {
3686 int idx = 0;
3687 if (edgeSize > 2) {
3688 if (edgeSize < minEdgeSize) {
3689 throw(AipsError("Length of edge element info is less than that of IFs"));
3690 }
3691 idx = 2 * getIF(whichrow);
3692 }
3693 currentEdge.push_back(edge[idx]);
3694 currentEdge.push_back(edge[idx+1]);
3695 } else {
3696 throw(AipsError("Wrong length of edge element"));
3697 }
3698
3699 lineFinder.setData(getSpectrum(whichrow));
3700 lineFinder.findLines(getCompositeChanMask(whichrow, inMask), currentEdge, whichrow);
3701
3702 return lineFinder.getMask();
3703}
3704*/
3705
3706/* for poly. the variations of outputFittingResult() should be merged into one eventually (2011/3/10 WK) */
3707void 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)
3708{
3709 if (outLogger || outTextFile) {
3710 std::vector<float> params = fitter.getParameters();
3711 std::vector<bool> fixed = fitter.getFixedParameters();
3712 float rms = getRms(chanMask, whichrow);
3713 String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
3714
3715 if (outLogger) {
3716 LogIO ols(LogOrigin("Scantable", funcName, WHERE));
3717 ols << formatBaselineParams(params, fixed, rms, -1, masklist, whichrow, false) << LogIO::POST ;
3718 }
3719 if (outTextFile) {
3720 ofs << formatBaselineParams(params, fixed, rms, -1, masklist, whichrow, true) << flush;
3721 }
3722 }
3723}
3724
3725/* for cspline. will be merged once cspline is available in fitter (2011/3/10 WK) */
3726void 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, const int nClipped)
3727{
3728 if (outLogger || outTextFile) {
3729 /****
3730 double ms1TimeStart, ms1TimeEnd, ms2TimeStart, ms2TimeEnd;
3731 double elapse1 = 0.0;
3732 double elapse2 = 0.0;
3733
3734 ms1TimeStart = mathutil::gettimeofday_sec();
3735 ****/
3736
3737 float rms = getRms(chanMask, whichrow);
3738
3739 /****
3740 ms1TimeEnd = mathutil::gettimeofday_sec();
3741 elapse1 = ms1TimeEnd - ms1TimeStart;
3742 std::cout << "ot1 : " << elapse1 << " (sec.)" << endl;
3743 ms2TimeStart = mathutil::gettimeofday_sec();
3744 ****/
3745
3746 String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
3747 std::vector<bool> fixed;
3748 fixed.clear();
3749
3750 if (outLogger) {
3751 LogIO ols(LogOrigin("Scantable", funcName, WHERE));
3752 ols << formatPiecewiseBaselineParams(edge, params, fixed, rms, nClipped, masklist, whichrow, false) << LogIO::POST ;
3753 }
3754 if (outTextFile) {
3755 ofs << formatPiecewiseBaselineParams(edge, params, fixed, rms, nClipped, masklist, whichrow, true);// << flush;
3756 }
3757
3758 /****
3759 ms2TimeEnd = mathutil::gettimeofday_sec();
3760 elapse2 = ms2TimeEnd - ms2TimeStart;
3761 std::cout << "ot2 : " << elapse2 << " (sec.)" << endl;
3762 ****/
3763
3764 }
3765}
3766
3767/* for sinusoid. will be merged once sinusoid is available in fitter (2011/3/10 WK) */
3768void Scantable::outputFittingResult(bool outLogger, bool outTextFile, const std::vector<bool>& chanMask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, ofstream& ofs, const casa::String& funcName, const std::vector<float>& params, const int nClipped)
3769{
3770 if (outLogger || outTextFile) {
3771 float rms = getRms(chanMask, whichrow);
3772 String masklist = getMaskRangeList(chanMask, whichrow, coordInfo, hasSameNchan);
3773 std::vector<bool> fixed;
3774 fixed.clear();
3775
3776 if (outLogger) {
3777 LogIO ols(LogOrigin("Scantable", funcName, WHERE));
3778 ols << formatBaselineParams(params, fixed, rms, nClipped, masklist, whichrow, false) << LogIO::POST ;
3779 }
3780 if (outTextFile) {
3781 ofs << formatBaselineParams(params, fixed, rms, nClipped, masklist, whichrow, true) << flush;
3782 }
3783 }
3784}
3785
3786void Scantable::parseProgressInfo(const std::string& progressInfo, bool& showProgress, int& minNRow)
3787{
3788 int idxDelimiter = progressInfo.find(",");
3789 if (idxDelimiter < 0) {
3790 throw(AipsError("wrong value in 'showprogress' parameter")) ;
3791 }
3792 showProgress = (progressInfo.substr(0, idxDelimiter) == "true");
3793 std::istringstream is(progressInfo.substr(idxDelimiter+1));
3794 is >> minNRow;
3795}
3796
3797void Scantable::showProgressOnTerminal(const int nProcessed, const int nTotal, const bool showProgress, const int nTotalThreshold)
3798{
3799 if (showProgress && (nTotal >= nTotalThreshold)) {
3800 int nInterval = int(floor(double(nTotal)/100.0));
3801 if (nInterval == 0) nInterval++;
3802
3803 if (nProcessed % nInterval == 0) {
3804 printf("\r"); //go to the head of line
3805 printf("\x1b[31m\x1b[1m"); //set red color, highlighted
3806 printf("[%3d%%]", (int)(100.0*(double(nProcessed+1))/(double(nTotal))) );
3807 printf("\x1b[39m\x1b[0m"); //set default attributes
3808 fflush(NULL);
3809 }
3810
3811 if (nProcessed == nTotal - 1) {
3812 printf("\r\x1b[K"); //clear
3813 fflush(NULL);
3814 }
3815
3816 }
3817}
3818
3819std::vector<float> Scantable::execFFT(const int whichrow, const std::vector<bool>& inMask, bool getRealImag, bool getAmplitudeOnly)
3820{
3821 std::vector<bool> mask = getMask(whichrow);
3822
3823 if (inMask.size() > 0) {
3824 uInt maskSize = mask.size();
3825 if (maskSize != inMask.size()) {
3826 throw(AipsError("mask sizes are not the same."));
3827 }
3828 for (uInt i = 0; i < maskSize; ++i) {
3829 mask[i] = mask[i] && inMask[i];
3830 }
3831 }
3832
3833 Vector<Float> spec = getSpectrum(whichrow);
3834 mathutil::doZeroOrderInterpolation(spec, mask);
3835
3836 FFTServer<Float,Complex> ffts;
3837 Vector<Complex> fftres;
3838 ffts.fft0(fftres, spec);
3839
3840 std::vector<float> res;
3841 float norm = float(2.0/double(spec.size()));
3842
3843 if (getRealImag) {
3844 for (uInt i = 0; i < fftres.size(); ++i) {
3845 res.push_back(real(fftres[i])*norm);
3846 res.push_back(imag(fftres[i])*norm);
3847 }
3848 } else {
3849 for (uInt i = 0; i < fftres.size(); ++i) {
3850 res.push_back(abs(fftres[i])*norm);
3851 if (!getAmplitudeOnly) res.push_back(arg(fftres[i]));
3852 }
3853 }
3854
3855 return res;
3856}
3857
3858
3859float Scantable::getRms(const std::vector<bool>& mask, int whichrow)
3860{
3861 /****
3862 double ms1TimeStart, ms1TimeEnd, ms2TimeStart, ms2TimeEnd;
3863 double elapse1 = 0.0;
3864 double elapse2 = 0.0;
3865
3866 ms1TimeStart = mathutil::gettimeofday_sec();
3867 ****/
3868
3869 Vector<Float> spec;
3870
3871 specCol_.get(whichrow, spec);
3872
3873 /****
3874 ms1TimeEnd = mathutil::gettimeofday_sec();
3875 elapse1 = ms1TimeEnd - ms1TimeStart;
3876 std::cout << "rm1 : " << elapse1 << " (sec.)" << endl;
3877 ms2TimeStart = mathutil::gettimeofday_sec();
3878 ****/
3879
3880 float mean = 0.0;
3881 float smean = 0.0;
3882 int n = 0;
3883 for (uInt i = 0; i < spec.nelements(); ++i) {
3884 if (mask[i]) {
3885 mean += spec[i];
3886 smean += spec[i]*spec[i];
3887 n++;
3888 }
3889 }
3890
3891 mean /= (float)n;
3892 smean /= (float)n;
3893
3894 /****
3895 ms2TimeEnd = mathutil::gettimeofday_sec();
3896 elapse2 = ms2TimeEnd - ms2TimeStart;
3897 std::cout << "rm2 : " << elapse2 << " (sec.)" << endl;
3898 ****/
3899
3900 return sqrt(smean - mean*mean);
3901}
3902
3903
3904std::string Scantable::formatBaselineParamsHeader(int whichrow, const std::string& masklist, bool verbose) const
3905{
3906 ostringstream oss;
3907
3908 if (verbose) {
3909 oss << " Scan[" << getScan(whichrow) << "]";
3910 oss << " Beam[" << getBeam(whichrow) << "]";
3911 oss << " IF[" << getIF(whichrow) << "]";
3912 oss << " Pol[" << getPol(whichrow) << "]";
3913 oss << " Cycle[" << getCycle(whichrow) << "]: " << endl;
3914 oss << "Fitter range = " << masklist << endl;
3915 oss << "Baseline parameters" << endl;
3916 oss << flush;
3917 }
3918
3919 return String(oss);
3920}
3921
3922std::string Scantable::formatBaselineParamsFooter(float rms, int nClipped, bool verbose) const
3923{
3924 ostringstream oss;
3925
3926 if (verbose) {
3927 oss << "Results of baseline fit" << endl;
3928 oss << " rms = " << setprecision(6) << rms << endl;
3929 if (nClipped >= 0) {
3930 oss << " Number of clipped channels = " << nClipped << endl;
3931 }
3932 for (int i = 0; i < 60; ++i) {
3933 oss << "-";
3934 }
3935 oss << endl;
3936 oss << flush;
3937 }
3938
3939 return String(oss);
3940}
3941
3942std::string Scantable::formatBaselineParams(const std::vector<float>& params,
3943 const std::vector<bool>& fixed,
3944 float rms,
3945 int nClipped,
3946 const std::string& masklist,
3947 int whichrow,
3948 bool verbose,
3949 int start, int count,
3950 bool resetparamid) const
3951{
3952 int nParam = (int)(params.size());
3953
3954 if (nParam < 1) {
3955 return(" Not fitted");
3956 } else {
3957
3958 ostringstream oss;
3959 oss << formatBaselineParamsHeader(whichrow, masklist, verbose);
3960
3961 if (start < 0) start = 0;
3962 if (count < 0) count = nParam;
3963 int end = start + count;
3964 if (end > nParam) end = nParam;
3965 int paramidoffset = (resetparamid) ? (-start) : 0;
3966
3967 for (int i = start; i < end; ++i) {
3968 if (i > start) {
3969 oss << ",";
3970 }
3971 std::string sFix = ((fixed.size() > 0) && (fixed[i]) && verbose) ? "(fixed)" : "";
3972 oss << " p" << (i+paramidoffset) << sFix << "= " << right << setw(13) << setprecision(6) << params[i];
3973 }
3974
3975 oss << endl;
3976 oss << formatBaselineParamsFooter(rms, nClipped, verbose);
3977
3978 return String(oss);
3979 }
3980
3981}
3982
3983 std::string Scantable::formatPiecewiseBaselineParams(const std::vector<int>& ranges, const std::vector<float>& params, const std::vector<bool>& fixed, float rms, int nClipped, const std::string& masklist, int whichrow, bool verbose) const
3984{
3985 int nOutParam = (int)(params.size());
3986 int nPiece = (int)(ranges.size()) - 1;
3987
3988 if (nOutParam < 1) {
3989 return(" Not fitted");
3990 } else if (nPiece < 0) {
3991 return formatBaselineParams(params, fixed, rms, nClipped, masklist, whichrow, verbose);
3992 } else if (nPiece < 1) {
3993 return(" Bad count of the piece edge info");
3994 } else if (nOutParam % nPiece != 0) {
3995 return(" Bad count of the output baseline parameters");
3996 } else {
3997
3998 int nParam = nOutParam / nPiece;
3999
4000 ostringstream oss;
4001 oss << formatBaselineParamsHeader(whichrow, masklist, verbose);
4002
4003 stringstream ss;
4004 ss << ranges[nPiece] << flush;
4005 int wRange = ss.str().size() * 2 + 5;
4006
4007 for (int i = 0; i < nPiece; ++i) {
4008 ss.str("");
4009 ss << " [" << ranges[i] << "," << (ranges[i+1]-1) << "]";
4010 oss << left << setw(wRange) << ss.str();
4011 oss << formatBaselineParams(params, fixed, rms, 0, masklist, whichrow, false, i*nParam, nParam, true);
4012 }
4013
4014 oss << formatBaselineParamsFooter(rms, nClipped, verbose);
4015
4016 return String(oss);
4017 }
4018
4019}
4020
4021bool Scantable::hasSameNchanOverIFs()
4022{
4023 int nIF = nif(-1);
4024 int nCh;
4025 int totalPositiveNChan = 0;
4026 int nPositiveNChan = 0;
4027
4028 for (int i = 0; i < nIF; ++i) {
4029 nCh = nchan(i);
4030 if (nCh > 0) {
4031 totalPositiveNChan += nCh;
4032 nPositiveNChan++;
4033 }
4034 }
4035
4036 return (totalPositiveNChan == (nPositiveNChan * nchan(0)));
4037}
4038
4039std::string Scantable::getMaskRangeList(const std::vector<bool>& mask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, bool verbose)
4040{
4041 if (mask.size() <= 0) {
4042 throw(AipsError("The mask elements should be > 0"));
4043 }
4044 int IF = getIF(whichrow);
4045 if (mask.size() != (uInt)nchan(IF)) {
4046 throw(AipsError("Number of channels in scantable != number of mask elements"));
4047 }
4048
4049 if (verbose) {
4050 LogIO logOs(LogOrigin("Scantable", "getMaskRangeList()", WHERE));
4051 logOs << LogIO::WARN << "The current mask window unit is " << coordInfo;
4052 if (!hasSameNchan) {
4053 logOs << endl << "This mask is only valid for IF=" << IF;
4054 }
4055 logOs << LogIO::POST;
4056 }
4057
4058 std::vector<double> abcissa = getAbcissa(whichrow);
4059 std::vector<int> edge = getMaskEdgeIndices(mask);
4060
4061 ostringstream oss;
4062 oss.setf(ios::fixed);
4063 oss << setprecision(1) << "[";
4064 for (uInt i = 0; i < edge.size(); i+=2) {
4065 if (i > 0) oss << ",";
4066 oss << "[" << (float)abcissa[edge[i]] << "," << (float)abcissa[edge[i+1]] << "]";
4067 }
4068 oss << "]" << flush;
4069
4070 return String(oss);
4071}
4072
4073std::vector<int> Scantable::getMaskEdgeIndices(const std::vector<bool>& mask)
4074{
4075 if (mask.size() <= 0) {
4076 throw(AipsError("The mask elements should be > 0"));
4077 }
4078
4079 std::vector<int> out, startIndices, endIndices;
4080 int maskSize = mask.size();
4081
4082 startIndices.clear();
4083 endIndices.clear();
4084
4085 if (mask[0]) {
4086 startIndices.push_back(0);
4087 }
4088 for (int i = 1; i < maskSize; ++i) {
4089 if ((!mask[i-1]) && mask[i]) {
4090 startIndices.push_back(i);
4091 } else if (mask[i-1] && (!mask[i])) {
4092 endIndices.push_back(i-1);
4093 }
4094 }
4095 if (mask[maskSize-1]) {
4096 endIndices.push_back(maskSize-1);
4097 }
4098
4099 if (startIndices.size() != endIndices.size()) {
4100 throw(AipsError("Inconsistent Mask Size: bad data?"));
4101 }
4102 for (uInt i = 0; i < startIndices.size(); ++i) {
4103 if (startIndices[i] > endIndices[i]) {
4104 throw(AipsError("Mask start index > mask end index"));
4105 }
4106 }
4107
4108 out.clear();
4109 for (uInt i = 0; i < startIndices.size(); ++i) {
4110 out.push_back(startIndices[i]);
4111 out.push_back(endIndices[i]);
4112 }
4113
4114 return out;
4115}
4116
4117vector<float> Scantable::getTsysSpectrum( int whichrow ) const
4118{
4119 Vector<Float> tsys( tsysCol_(whichrow) ) ;
4120 vector<float> stlTsys ;
4121 tsys.tovector( stlTsys ) ;
4122 return stlTsys ;
4123}
4124
4125vector<uint> Scantable::getMoleculeIdColumnData() const
4126{
4127 Vector<uInt> molIds(mmolidCol_.getColumn());
4128 vector<uint> res;
4129 molIds.tovector(res);
4130 return res;
4131}
4132
4133void Scantable::setMoleculeIdColumnData(const std::vector<uint>& molids)
4134{
4135 Vector<uInt> molIds(molids);
4136 Vector<uInt> arr(mmolidCol_.getColumn());
4137 if ( molIds.nelements() != arr.nelements() )
4138 throw AipsError("The input data size must be the number of rows.");
4139 mmolidCol_.putColumn(molIds);
4140}
4141
4142
4143}
4144//namespace asap
Note: See TracBrowser for help on using the repository browser.