source: trunk/src/STSideBandSep.cpp@ 2835

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

New Development: No

JIRA Issue: Yes (CAS-4141)

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs:

Put in Release Notes: No

Module(s):

Description: Fixed a bug which caused gridded spectra totally flagged in a case. convsupport=1 with box kernel does not work for some reason in STGrid class.


File size: 42.0 KB
RevLine 
[2707]1// C++ Interface: STSideBandSep
2//
3// Description:
4// A class to invoke sideband separation of Scantable
5//
6// Author: Kana Sugimoto <kana.sugi@nao.ac.jp>, (C) 2012
7//
8// Copyright: See COPYING file that comes with this distribution
9//
10//
11
12// STL
13#include <ctype.h>
14
15// cascore
16#include <casa/OS/File.h>
17#include <casa/Logging/LogIO.h>
18#include <casa/Quanta/QuantumHolder.h>
19
20#include <measures/Measures/MFrequency.h>
21#include <measures/Measures/MCFrequency.h>
22
[2711]23#include <tables/Tables/TableRow.h>
[2707]24#include <tables/Tables/TableRecord.h>
25#include <tables/Tables/TableVector.h>
26
27// asap
[2794]28#include "STGrid.h"
29#include "STMath.h"
30#include "MathUtils.h"
[2707]31#include "STSideBandSep.h"
32
33using namespace std ;
34using namespace casa ;
35using namespace asap ;
36
[2794]37// #ifndef KS_DEBUG
38// #define KS_DEBUG
39// #endif
[2707]40
41namespace asap {
42
43// constructors
[2726]44STSideBandSep::STSideBandSep(const vector<string> &names)
[2707]45{
[2726]46 LogIO os(LogOrigin("STSideBandSep","STSideBandSep()", WHERE));
47 os << "Setting scantable names to process." << LogIO::POST ;
48 // Set file names
49 ntable_ = names.size();
50 infileList_.resize(ntable_);
51 for (unsigned int i = 0; i < ntable_; i++){
52 if (!checkFile(names[i], "d"))
53 throw( AipsError("File does not exist") );
54 infileList_[i] = names[i];
55 }
56 intabList_.resize(0);
57
58 init();
59
60 {// Summary
61 os << ntable_ << " files are set: [";
62 for (unsigned int i = 0; i < ntable_; i++) {
63 os << " '" << infileList_[i] << "' ";
64 if (i != ntable_-1) os << ",";
65 }
66 os << "] " << LogIO::POST;
67 }
[2707]68};
69
[2726]70STSideBandSep::STSideBandSep(const vector<ScantableWrapper> &tables)
71{
72 LogIO os(LogOrigin("STSideBandSep","STSideBandSep()", WHERE));
73 os << "Setting list of scantables to process." << LogIO::POST ;
74 // Set file names
75 ntable_ = tables.size();
76 intabList_.resize(ntable_);
77 for (unsigned int i = 0; i < ntable_; i++){
78 intabList_[i] = tables[i].getCP();
79 }
80 infileList_.resize(0);
81
82 init();
[2794]83 tp_ = intabList_[0]->table().tableType();
[2726]84
85 os << ntable_ << " tables are set." << LogIO::POST;
86};
87
[2707]88STSideBandSep::~STSideBandSep()
89{
90#ifdef KS_DEBUG
91 cout << "Destructor ~STSideBandSep()" << endl;
92#endif
93};
94
[2726]95void STSideBandSep::init()
96{
97 // frequency setup
[2794]98 sigIfno_= -1;
[2726]99 ftol_ = -1;
100 solFrame_ = MFrequency::N_Types;
101 // shifts
102 initshift();
103 // direction tolerance
104 xtol_ = ytol_ = 9.69627e-6; // 2arcsec
105 // solution parameters
106 otherside_ = false;
107 doboth_ = false;
108 rejlimit_ = 0.2;
109 // LO1 values
110 lo1Freq_ = -1;
111 loTime_ = -1;
112 loDir_ = "";
113 // Default LO frame is TOPO
114 loFrame_ = MFrequency::TOPO;
[2794]115 // scantable storage
116 tp_ = Table::Memory;
[2726]117};
[2707]118
[2726]119void STSideBandSep::initshift()
[2707]120{
[2726]121 // shifts
122 nshift_ = 0;
123 nchan_ = 0;
124 sigShift_.resize(0);
125 imgShift_.resize(0);
126 tableList_.resize(0);
[2707]127};
128
[2726]129void STSideBandSep::setFrequency(const unsigned int ifno,
130 const string freqtol,
131 const string frame)
132{
133 LogIO os(LogOrigin("STSideBandSep","setFrequency()", WHERE));
134
135 initshift();
136
137 // IFNO
[2794]138 sigIfno_ = (int) ifno;
[2726]139
140 // Frequency tolerance
141 Quantum<Double> qftol;
142 readQuantity(qftol, String(freqtol));
143 if (!qftol.getUnit().empty()){
144 // make sure the quantity is frequency
145 if (qftol.getFullUnit().getValue() != Unit("Hz").getValue())
146 throw( AipsError("Invalid quantity for frequency tolerance.") );
147 qftol.convert("Hz");
148 }
149 ftol_ = qftol;
150
151 // Frequency Frame
152 if (!frame.empty()){
153 MFrequency::Types mft;
154 if (!MFrequency::getType(mft, frame))
155 throw( AipsError("Invalid frame type.") );
156 solFrame_ = mft;
157 } else {
158 solFrame_ = MFrequency::N_Types;
159 }
160
161 {// Summary
162 const String sframe = ( (solFrame_ == MFrequency::N_Types) ?
163 "table frame" :
164 MFrequency::showType(solFrame_) );
165 os << "Frequency setup to search IF group: "
166 << "IFNO of table[0] = " << sigIfno_
167 << " , Freq tolerance = " << ftol_.getValue() << " [ "
168 << (ftol_.getUnit().empty() ? "channel" : ftol_.getUnit() )
169 << " ] (in " << sframe <<")" << LogIO::POST;
170 }
171};
172
173
174void STSideBandSep::setDirTolerance(const vector<string> dirtol)
175{
176 LogIO os(LogOrigin("STSideBandSep","setDirTolerance()", WHERE));
177 Quantum<Double> qcell;
178 if ( (dirtol.size() == 1) && !dirtol[0].empty() ) {
179 readQuantity(qcell, String(dirtol[0]));
180 if (qcell.getFullUnit().getValue() == Unit("rad").getValue())
181 xtol_ = ytol_ = qcell.getValue("rad");
182 else
183 throw( AipsError("Invalid unit for direction tolerance.") );
184 }
185 else if (dirtol.size() > 1) {
186 if ( dirtol[0].empty() && dirtol[1].empty() )
187 throw( AipsError("Direction tolerance is empty.") );
188 if ( !dirtol[0].empty() ) {
189 readQuantity(qcell, String(dirtol[0]));
190 if (qcell.getFullUnit().getValue() == Unit("rad").getValue())
191 xtol_ = qcell.getValue("rad");
192 else
193 throw( AipsError("Invalid unit for direction tolerance.") );
194 }
195 if ( !dirtol[1].empty() ) {
196 readQuantity(qcell, String(dirtol[1]));
197 if (qcell.getFullUnit().getValue() == Unit("rad").getValue())
198 ytol_ = qcell.getValue("rad");
199 else
200 throw( AipsError("Invalid unit for direction tolerance.") );
201 }
202 else {
203 ytol_ = xtol_;
204 }
205 }
206 else throw( AipsError("Invalid direction tolerance.") );
207
208 os << "Direction tolerance: ( "
209 << xtol_ << " , " << ytol_ << " ) [rad]" << LogIO::POST;
210};
211
212void STSideBandSep::setShift(const vector<double> &shift)
213{
214 LogIO os(LogOrigin("STSideBandSep","setShift()", WHERE));
215 imgShift_.resize(shift.size());
216 for (unsigned int i = 0; i < shift.size(); i++)
217 imgShift_[i] = shift[i];
218
219 if (imgShift_.size() == 0) {
220 os << "Channel shifts are cleared." << LogIO::POST;
221 } else {
222 os << "Channel shifts of image sideband are set: ( ";
223 for (unsigned int i = 0; i < imgShift_.size(); i++) {
224 os << imgShift_[i];
225 if (i != imgShift_.size()-1) os << " , ";
226 }
[2794]227 os << " ) [channels]" << LogIO::POST;
[2726]228 }
229};
230
231void STSideBandSep::setThreshold(const double limit)
232{
233 LogIO os(LogOrigin("STSideBandSep","setThreshold()", WHERE));
234 if (limit < 0)
[2794]235 throw( AipsError("Rejection limit should be a positive number.") );
[2726]236
237 rejlimit_ = limit;
[2794]238 os << "Rejection limit is set to " << rejlimit_ << LogIO::POST;
[2726]239};
240
[2794]241void STSideBandSep::separate(string outname)
[2707]242{
243#ifdef KS_DEBUG
[2794]244 cout << "STSideBandSep::separate" << endl;
[2707]245#endif
[2794]246 LogIO os(LogOrigin("STSideBandSep","separate()", WHERE));
247 if (outname.empty())
248 outname = "sbseparated.asap";
[2707]249
[2794]250 // Set up a goup of IFNOs in the list of scantables within
251 // the frequency tolerance and make them a list.
252 nshift_ = setupShift();
253 if (nshift_ < 2)
254 throw( AipsError("At least 2 IFs are necessary for convolution.") );
255 // Grid scantable and generate output tables
256 ScantableWrapper gridst = gridTable();
257 sigTab_p = gridst.getCP();
258 if (doboth_)
259 imgTab_p = gridst.copy().getCP();
260 vector<unsigned int> remRowIds;
261 remRowIds.resize(0);
262 Matrix<float> specMat(nchan_, nshift_);
263 vector<float> sigSpec(nchan_), imgSpec(nchan_);
264 vector<uInt> tabIdvec;
265
266 //Generate FFTServer
267 fftsf.resize(IPosition(1, nchan_), FFTEnums::REALTOCOMPLEX);
268 fftsi.resize(IPosition(1, nchan_), FFTEnums::COMPLEXTOREAL);
269
270 /// Loop over sigTab_p and separate sideband
271 for (int irow = 0; irow < sigTab_p->nrow(); irow++){
272 tabIdvec.resize(0);
273 const int polId = sigTab_p->getPol(irow);
274 const int beamId = sigTab_p->getBeam(irow);
275 const vector<double> dir = sigTab_p->getDirectionVector(irow);
276 // Get a set of spectra to solve
277 if (!getSpectraToSolve(polId, beamId, dir[0], dir[1],
278 specMat, tabIdvec)){
279 remRowIds.push_back(irow);
280#ifdef KS_DEBUG
281 cout << "no matching row found. skipping row = " << irow << endl;
282#endif
283 continue;
284 }
285 // Solve signal sideband
286 sigSpec = solve(specMat, tabIdvec, true);
287 sigTab_p->setSpectrum(sigSpec, irow);
288
289 // Solve image sideband
290 if (doboth_) {
291 imgSpec = solve(specMat, tabIdvec, false);
292 imgTab_p->setSpectrum(imgSpec, irow);
293 }
294 } // end of row loop
295
296 // Remove or flag rows without relevant data from gridded tables
297 if (remRowIds.size() > 0) {
298 const size_t nrem = remRowIds.size();
299 if ( sigTab_p->table().canRemoveRow() ) {
300 sigTab_p->table().removeRow(remRowIds);
301 os << "Removing " << nrem << " rows from the signal band table"
302 << LogIO::POST;
303 } else {
304 sigTab_p->flagRow(remRowIds, false);
305 os << "Cannot remove rows from the signal band table. Flagging "
306 << nrem << " rows" << LogIO::POST;
307 }
308
309 if (doboth_) {
310 if ( imgTab_p->table().canRemoveRow() ) {
311 imgTab_p->table().removeRow(remRowIds);
312 os << "Removing " << nrem << " rows from the image band table"
313 << LogIO::POST;
314 } else {
315 imgTab_p->flagRow(remRowIds, false);
316 os << "Cannot remove rows from the image band table. Flagging "
317 << nrem << " rows" << LogIO::POST;
318 }
319 }
320 }
321
322 // Finally, save tables on disk
323 if (outname.size() ==0)
324 outname = "sbseparated.asap";
325 const string sigName = outname + ".signalband";
326 os << "Saving SIGNAL sideband table: " << sigName << LogIO::POST;
327 sigTab_p->makePersistent(sigName);
328 if (doboth_) {
329 solveImageFrequency();
330 const string imgName = outname + ".imageband";
331 os << "Saving IMAGE sideband table: " << sigName << LogIO::POST;
332 imgTab_p->makePersistent(imgName);
333 }
334
[2707]335};
336
[2794]337unsigned int STSideBandSep::setupShift()
338{
339 LogIO os(LogOrigin("STSideBandSep","setupShift()", WHERE));
340 if (infileList_.size() == 0 && intabList_.size() == 0)
341 throw( AipsError("No scantable has been set. Set a list of scantables first.") );
342
343 const bool byname = (intabList_.size() == 0);
344 // Make sure sigIfno_ exists in the first table.
345 CountedPtr<Scantable> stab;
346 vector<string> coordsav;
347 vector<string> coordtmp(3);
348 os << "Checking IFNO in the first table." << LogIO::POST;
349 if (byname) {
350 if (!checkFile(infileList_[0], "d"))
351 os << LogIO::SEVERE << "Could not find scantable '" << infileList_[0]
352 << "'" << LogIO::EXCEPTION;
353 stab = CountedPtr<Scantable>(new Scantable(infileList_[0]));
354 } else {
355 stab = intabList_[0];
356 }
357 if (sigIfno_ < 0) {
358 sigIfno_ = (int) stab->getIF(0);
359 os << "IFNO to process has not been set. Using the first IF = "
360 << sigIfno_ << LogIO::POST;
361 }
362
363 unsigned int basench;
364 double basech0, baseinc, ftolval, inctolval;
365 coordsav = stab->getCoordInfo();
366 const string stfframe = coordsav[1];
367 coordtmp[0] = "Hz";
368 coordtmp[1] = ( (solFrame_ == MFrequency::N_Types) ?
369 stfframe :
370 MFrequency::showType(solFrame_) );
371 coordtmp[2] = coordsav[2];
372 stab->setCoordInfo(coordtmp);
373 if (!getFreqInfo(stab, (unsigned int) sigIfno_, basech0, baseinc, basench)) {
374 os << LogIO::SEVERE << "No data with IFNO=" << sigIfno_
375 << " found in the first table." << LogIO::EXCEPTION;
376 }
377 else {
378 os << "Found IFNO = " << sigIfno_
379 << " in the first table." << LogIO::POST;
380 }
381 if (ftol_.getUnit().empty()) {
382 // tolerance in unit of channels
383 ftolval = ftol_.getValue() * baseinc;
384 }
385 else {
386 ftolval = ftol_.getValue("Hz");
387 }
388 inctolval = abs(baseinc/(double) basench);
389 const string poltype0 = stab->getPolType();
390
391 // Initialize shift values
392 initshift();
393
394 const bool setImg = ( doboth_ && (imgShift_.size() == 0) );
395 // Select IFs
396 for (unsigned int itab = 0; itab < ntable_; itab++ ){
397 os << "Table " << itab << LogIO::POST;
398 if (itab > 0) {
399 if (byname) {
400 if (!checkFile(infileList_[itab], "d"))
401 os << LogIO::SEVERE << "Could not find scantable '"
402 << infileList_[itab] << "'" << LogIO::EXCEPTION;
403 stab = CountedPtr<Scantable>(new Scantable(infileList_[itab]));
404 } else {
405 stab = intabList_[itab];
406 }
407 //POLTYPE should be the same.
408 if (stab->getPolType() != poltype0 ) {
409 os << LogIO::WARN << "POLTYPE differs from the first table."
410 << " Skipping the table" << LogIO::POST;
411 continue;
412 }
413 // Multi beam data may not handled properly
414 if (stab->nbeam() > 1)
415 os << LogIO::WARN << "Table contains multiple beams. "
416 << "It may not be handled properly." << LogIO::POST;
417
418 coordsav = stab->getCoordInfo();
419 coordtmp[2] = coordsav[2];
420 stab->setCoordInfo(coordtmp);
421 }
422 bool selected = false;
423 vector<uint> ifnos = stab->getIFNos();
424 vector<uint>::iterator iter;
425 const STSelector& basesel = stab->getSelection();
426 for (iter = ifnos.begin(); iter != ifnos.end(); iter++){
427 unsigned int nch;
428 double freq0, incr;
429 if ( getFreqInfo(stab, *iter, freq0, incr, nch) ){
430 if ( (nch == basench) && (abs(freq0-basech0) < ftolval)
431 && (abs(incr-baseinc) < inctolval) ){
432 //Found
433 STSelector sel(basesel);
434 sel.setIFs(vector<int>(1,(int) *iter));
435 stab->setSelection(sel);
436 CountedPtr<Scantable> seltab = ( new Scantable(*stab, false) );
437 stab->setSelection(basesel);
438 seltab->setCoordInfo(coordsav);
439 const double chShift = (freq0 - basech0) / baseinc;
440 tableList_.push_back(seltab);
[2808]441 sigShift_.push_back(-chShift);
[2794]442 if (setImg)
[2808]443 imgShift_.push_back(chShift);
[2794]444
445 selected = true;
446 os << "- IF" << *iter << " selected: sideband shift = "
447 << chShift << " channels" << LogIO::POST;
448 }
449 }
450 } // ifno loop
451 stab->setCoordInfo(coordsav);
452 if (!selected)
453 os << LogIO::WARN << "No data selected in Table "
454 << itab << LogIO::POST;
455 } // table loop
456 nchan_ = basench;
457
458 os << "Total number of IFs selected = " << tableList_.size()
459 << LogIO::POST;
460 if ( setImg && (sigShift_.size() != imgShift_.size()) ){
461 os << LogIO::SEVERE
462 << "User defined channel shift of image sideband has "
463 << imgShift_.size()
464 << " elements, while selected IFNOs are " << sigShift_.size()
465 << "\nThe frequency tolerance (freqtol) may be too small."
466 << LogIO::EXCEPTION;
467 }
468
469 return tableList_.size();
470};
471
472bool STSideBandSep::getFreqInfo(const CountedPtr<Scantable> &stab,
473 const unsigned int &ifno,
474 double &freq0, double &incr,
475 unsigned int &nchan)
476{
477 vector<uint> ifnos = stab->getIFNos();
478 bool found = false;
479 vector<uint>::iterator iter;
480 for (iter = ifnos.begin(); iter != ifnos.end(); iter++){
481 if (*iter == ifno) {
482 found = true;
483 break;
484 }
485 }
486 if (!found)
487 return false;
488
489 const STSelector& basesel = stab->getSelection();
490 STSelector sel(basesel);
491 sel.setIFs(vector<int>(1,(int) ifno));
492 stab->setSelection(sel);
493 vector<double> freqs;
494 freqs = stab->getAbcissa(0);
495 freq0 = freqs[0];
496 incr = freqs[1] - freqs[0];
497 nchan = freqs.size();
498 stab->setSelection(basesel);
499 return true;
500};
501
502ScantableWrapper STSideBandSep::gridTable()
503{
504 LogIO os(LogOrigin("STSideBandSep","gridTable()", WHERE));
505 if (tableList_.size() == 0)
506 throw( AipsError("Internal error. No scantable has been set to grid.") );
507 Double xmin, xmax, ymin, ymax;
508 mapExtent(tableList_, xmin, xmax, ymin, ymax);
509 const Double centx = 0.5 * (xmin + xmax);
510 const Double centy = 0.5 * (ymin + ymax);
511 const int nx = max(1, (int) ceil( (xmax - xmin) * cos(centy) /xtol_ ) );
512 const int ny = max(1, (int) ceil( (ymax - ymin) / ytol_ ) );
513
514 string scellx, scelly;
515 {
516 ostringstream oss;
517 oss << xtol_ << "rad" ;
518 scellx = oss.str();
519 }
520 {
521 ostringstream oss;
522 oss << ytol_ << "rad" ;
523 scelly = oss.str();
524 }
525
526 ScantableWrapper stab0;
527 if (intabList_.size() > 0)
528 stab0 = ScantableWrapper(intabList_[0]);
529 else
530 stab0 = ScantableWrapper(infileList_[0]);
531
532 string scenter;
533 {
534 ostringstream oss;
535 oss << stab0.getCP()->getDirectionRefString() << " "
536 << centx << "rad" << " " << centy << "rad";
537 scenter = oss.str();
538 }
539
540 STGrid2 gridder = STGrid2(stab0);
541 gridder.setIF(sigIfno_);
542 gridder.defineImage(nx, ny, scellx, scelly, scenter);
[2835]543 // gridder.setFunc("box", 1); // convsupport=1 fails
544 gridder.setFunc("box");
[2794]545 gridder.setWeight("uniform");
546#ifdef KS_DEBUG
547 cout << "Grid parameter summary: " << endl;
548 cout << "- IF = " << sigIfno_ << endl;
549 cout << "- center = " << scenter << ")\n"
550 << "- npix = (" << nx << ", " << ny << ")\n"
551 << "- cell = (" << scellx << ", " << scelly << endl;
552#endif
553 gridder.grid();
554 const int itp = (tp_ == Table::Memory ? 0 : 1);
555 ScantableWrapper gtab = gridder.getResultAsScantable(itp);
556 return gtab;
557};
558
559void STSideBandSep::mapExtent(vector< CountedPtr<Scantable> > &tablist,
560 Double &xmin, Double &xmax,
561 Double &ymin, Double &ymax)
562{
563 ROArrayColumn<Double> dirCol_;
564 dirCol_.attach( tablist[0]->table(), "DIRECTION" );
565 Matrix<Double> direction = dirCol_.getColumn();
566 Vector<Double> ra( direction.row(0) );
567 mathutil::rotateRA(ra);
568 minMax( xmin, xmax, ra );
569 minMax( ymin, ymax, direction.row(1) );
570 Double amin, amax, bmin, bmax;
571 const uInt ntab = tablist.size();
572 for ( uInt i = 1 ; i < ntab ; i++ ) {
573 dirCol_.attach( tablist[i]->table(), "DIRECTION" );
574 direction.assign( dirCol_.getColumn() );
575 ra.assign( direction.row(0) );
576 mathutil::rotateRA(ra);
577 minMax( amin, amax, ra );
578 minMax( bmin, bmax, direction.row(1) );
579 xmin = min(xmin, amin);
580 xmax = max(xmax, amax);
581 ymin = min(ymin, bmin);
582 ymax = max(ymax, bmax);
583 }
584};
585
586bool STSideBandSep::getSpectraToSolve(const int polId, const int beamId,
587 const double dirX, const double dirY,
588 Matrix<float> &specMat, vector<uInt> &tabIdvec)
589{
590 LogIO os(LogOrigin("STSideBandSep","getSpectraToSolve()", WHERE));
591
592 tabIdvec.resize(0);
593 specMat.resize(nchan_, nshift_);
594 Vector<float> spec;
595 uInt nspec = 0;
596 STMath stm(false); // insitu has no effect for average.
597 for (uInt itab = 0 ; itab < nshift_ ; itab++) {
598 CountedPtr<Scantable> currtab_p = tableList_[itab];
599 // Selection by POLNO and BEAMNO
600 const STSelector& basesel = currtab_p->getSelection();
601 STSelector sel(basesel);
602 sel.setPolarizations(vector<int>(1, polId));
603 sel.setBeams(vector<int>(1, beamId));
604 try {
605 currtab_p->setSelection(sel);
606 } catch (...) {
607#ifdef KS_DEBUG
608 cout << "Table " << itab << " - No spectrum found. skipping the table."
609 << endl;
610#endif
611 continue;
612 }
613 // Selection by direction;
614 vector<int> selrow(0);
615 vector<double> currDir(2, 0.);
616 const int nselrow = currtab_p->nrow();
617 for (int irow = 0 ; irow < nselrow ; irow++) {
618 currDir = currtab_p->getDirectionVector(irow);
619 if ( (abs(currDir[0]-dirX) > xtol_) ||
620 (abs(currDir[1]-dirY) > ytol_) )
621 continue;
622 // within direction tolerance
623 selrow.push_back(irow);
624 } // end of row loop
625
626 if (selrow.size() < 1) {
627 currtab_p->setSelection(basesel);
628
629#ifdef KS_DEBUG
630 cout << "Table " << itab << " - No spectrum found. skipping the table."
631 << endl;
632#endif
633
634 continue;
635 }
636
637 // At least a spectrum is selected in this table
638 CountedPtr<Scantable> seltab_p = ( new Scantable(*currtab_p, false) );
639 currtab_p->setSelection(basesel);
640 STSelector sel2(seltab_p->getSelection());
641 sel2.setRows(selrow);
642 seltab_p->setSelection(sel2);
643 CountedPtr<Scantable> avetab_p;
644 vector<bool> mask;
645 if (seltab_p->nrow() > 1) {
646 avetab_p = stm.average(vector< CountedPtr<Scantable> >(1, seltab_p),
647 vector<bool>(), "TINTSYS", "NONE");
648#ifdef KS_DEBUG
649 cout << "Table " << itab << " - more than a spectrum is selected. averaging rows..."
650 << endl;
651#endif
652 if (avetab_p->nrow() > 1)
653 throw( AipsError("Averaged table has more than a row. Somethigs went wrong.") );
654 } else {
655 avetab_p = seltab_p;
656 }
657 spec.reference(specMat.column(nspec));
658 spec = avetab_p->getSpectrum(0);
659 tabIdvec.push_back((uInt) itab);
660 nspec++;
661 } // end of table loop
662 if (nspec != nshift_){
663 //shiftSpecmat.resize(nchan_, nspec, true);
664#ifdef KS_DEBUG
665 cout << "Could not find corresponding rows in some tables."
666 << endl;
667 cout << "Number of spectra selected = " << nspec << endl;
668#endif
669 }
670 if (nspec < 2) {
671#ifdef KS_DEBUG
672 cout << "At least 2 spectra are necessary for convolution"
673 << endl;
674#endif
675 return false;
676 }
677 return true;
678};
679
680vector<float> STSideBandSep::solve(const Matrix<float> &specmat,
681 const vector<uInt> &tabIdvec,
682 const bool signal)
683{
684 LogIO os(LogOrigin("STSideBandSep","solve()", WHERE));
685 if (tabIdvec.size() == 0)
686 throw(AipsError("Internal error. Table index is not defined."));
687 if (specmat.ncolumn() != tabIdvec.size())
688 throw(AipsError("Internal error. The row number of input matrix is not conformant."));
689 if (specmat.nrow() != nchan_)
690 throw(AipsError("Internal error. The channel size of input matrix is not conformant."));
691
692
693#ifdef KS_DEBUG
694 cout << "Solving " << (signal ? "SIGNAL" : "IMAGE") << " sideband."
695 << endl;
696#endif
697
698 const size_t nspec = tabIdvec.size();
699 vector<double> *thisShift, *otherShift;
700 if (signal == otherside_) {
701 // (solve signal && solveother = T) OR (solve image && solveother = F)
702 thisShift = &imgShift_;
703 otherShift = &sigShift_;
704#ifdef KS_DEBUG
705 cout << "Image sideband will be deconvolved." << endl;
706#endif
707 } else {
708 // (solve signal && solveother = F) OR (solve image && solveother = T)
709 thisShift = &sigShift_;
710 otherShift = &imgShift_;
711#ifdef KS_DEBUG
712 cout << "Signal sideband will be deconvolved." << endl;
713#endif
714 }
715
716 vector<double> spshift(nspec);
717 Matrix<float> shiftSpecmat(nchan_, nspec, 0.);
718 double tempshift;
719 Vector<float> shiftspvec;
720 for (uInt i = 0 ; i < nspec; i++) {
721 spshift[i] = otherShift->at(i) - thisShift->at(i);
722 tempshift = - thisShift->at(i);
723 shiftspvec.reference(shiftSpecmat.column(i));
724 shiftSpectrum(specmat.column(i), tempshift, shiftspvec);
725 }
726
727 Matrix<float> convmat(nchan_, nspec*(nspec-1)/2, 0.);
728 vector<float> thisvec(nchan_, 0.);
729
730 float minval, maxval;
731 minMax(minval, maxval, shiftSpecmat);
732#ifdef KS_DEBUG
733 cout << "Max/Min of input Matrix = (max: " << maxval << ", min: " << minval << ")" << endl;
734#endif
735
736#ifdef KS_DEBUG
737 cout << "starting deconvolution" << endl;
738#endif
739 deconvolve(shiftSpecmat, spshift, rejlimit_, convmat);
740#ifdef KS_DEBUG
741 cout << "finished deconvolution" << endl;
742#endif
743
744 minMax(minval, maxval, convmat);
745#ifdef KS_DEBUG
746 cout << "Max/Min of output Matrix = (max: " << maxval << ", min: " << minval << ")" << endl;
747#endif
748
749 aggregateMat(convmat, thisvec);
750
751 if (!otherside_) return thisvec;
752
753 // subtract from the other side band.
754 vector<float> othervec(nchan_, 0.);
755 subtractFromOther(shiftSpecmat, thisvec, spshift, othervec);
756 return othervec;
757};
758
759
760void STSideBandSep::shiftSpectrum(const Vector<float> &invec,
761 double shift,
762 Vector<float> &outvec)
763{
764 LogIO os(LogOrigin("STSideBandSep","shiftSpectrum()", WHERE));
765 if (invec.size() != nchan_)
766 throw(AipsError("Internal error. The length of input vector differs from nchan_"));
767 if (outvec.size() != nchan_)
768 throw(AipsError("Internal error. The length of output vector differs from nchan_"));
769
770#ifdef KS_DEBUG
771 cout << "Start shifting spectrum for " << shift << "channels" << endl;
772#endif
773
774 // tweak shift to be in 0 ~ nchan_-1
775 if ( fabs(shift) > nchan_ ) shift = fmod(shift, nchan_);
776 if (shift < 0.) shift += nchan_;
777 double rweight = fmod(shift, 1.);
778 if (rweight < 0.) rweight += 1.;
779 double lweight = 1. - rweight;
780 uInt lchan, rchan;
781
782 outvec = 0;
783 for (uInt i = 0 ; i < nchan_ ; i++) {
784 lchan = uInt( floor( fmod( (i + shift), nchan_ ) ) );
785 if (lchan < 0.) lchan += nchan_;
786 rchan = ( (lchan + 1) % nchan_ );
787 outvec(lchan) += invec(i) * lweight;
788 outvec(rchan) += invec(i) * rweight;
789 }
790};
791
792void STSideBandSep::deconvolve(Matrix<float> &specmat,
793 const vector<double> shiftvec,
794 const double threshold,
795 Matrix<float> &outmat)
796{
797 LogIO os(LogOrigin("STSideBandSep","deconvolve()", WHERE));
798 if (specmat.nrow() != nchan_)
799 throw(AipsError("Internal error. The length of input matrix differs from nchan_"));
800 if (specmat.ncolumn() != shiftvec.size())
801 throw(AipsError("Internal error. The number of input shifts and spectrum differs."));
802
803 float minval, maxval;
804#ifdef KS_DEBUG
805 minMax(minval, maxval, specmat);
806 cout << "Max/Min of input Matrix = (max: " << maxval << ", min: " << minval << ")" << endl;
807#endif
808
809 uInt ninsp = shiftvec.size();
810 outmat.resize(nchan_, ninsp*(ninsp-1)/2, 0.);
811 Matrix<Complex> fftspmat(nchan_/2+1, ninsp, 0.);
812 Vector<float> rvecref(nchan_, 0.);
813 Vector<Complex> cvecref(nchan_/2+1, 0.);
814 uInt icol = 0;
815 unsigned int nreject = 0;
816
817#ifdef KS_DEBUG
818 cout << "Starting initial FFT. The number of input spectra = " << ninsp << endl;
819 cout << "out matrix has ncolumn = " << outmat.ncolumn() << endl;
820#endif
821
822 for (uInt isp = 0 ; isp < ninsp ; isp++) {
823 rvecref.reference( specmat.column(isp) );
824 cvecref.reference( fftspmat.column(isp) );
825
826#ifdef KS_DEBUG
827 minMax(minval, maxval, rvecref);
828 cout << "Max/Min of inv FFTed Matrix = (max: " << maxval << ", min: " << minval << ")" << endl;
829#endif
830
831 fftsf.fft0(cvecref, rvecref, true);
832
833#ifdef KS_DEBUG
834 double maxr=cvecref[0].real(), minr=cvecref[0].real(),
835 maxi=cvecref[0].imag(), mini=cvecref[0].imag();
836 for (uInt i = 1; i<cvecref.size();i++){
837 maxr = max(maxr, cvecref[i].real());
838 maxi = max(maxi, cvecref[i].imag());
839 minr = min(minr, cvecref[i].real());
840 mini = min(mini, cvecref[i].imag());
841 }
842 cout << "Max/Min of inv FFTed Matrix (size=" << cvecref.size() << ") = (max: " << maxr << " + " << maxi << "j , min: " << minr << " + " << mini << "j)" << endl;
843#endif
844 }
845
846 //Liberate from reference
847 rvecref.unique();
848
849 Vector<Complex> cspec(nchan_/2+1, 0.);
850 const double PI = 6.0 * asin(0.5);
851 const double nchani = 1. / (float) nchan_;
852 const Complex trans(0., 1.);
853#ifdef KS_DEBUG
854 cout << "starting actual deconvolution" << endl;
855#endif
856 for (uInt j = 0 ; j < ninsp ; j++) {
857 for (uInt k = j+1 ; k < ninsp ; k++) {
858 const double dx = (shiftvec[k] - shiftvec[j]) * 2. * PI * nchani;
859
860#ifdef KS_DEBUG
861 cout << "icol = " << icol << endl;
862#endif
863
864 for (uInt ichan = 0 ; ichan < cspec.size() ; ichan++){
865 cspec[ichan] = ( fftspmat(ichan, j) + fftspmat(ichan, k) )*0.5;
866 double phase = dx*ichan;
867 if ( fabs( sin(phase) ) > threshold){
868 cspec[ichan] += ( fftspmat(ichan, j) - fftspmat(ichan, k) ) * 0.5
869 * trans * sin(phase) / ( 1. - cos(phase) );
870 } else {
871 nreject++;
872 }
873 } // end of channel loop
874
875#ifdef KS_DEBUG
876 cout << "done calculation of cspec" << endl;
877#endif
878
879 Vector<Float> rspec;
880 rspec.reference( outmat.column(icol) );
881
882#ifdef KS_DEBUG
883 cout << "Starting inverse FFT. icol = " << icol << endl;
884 //cout << "- size of complex vector = " << cspec.size() << endl;
885 double maxr=cspec[0].real(), minr=cspec[0].real(),
886 maxi=cspec[0].imag(), mini=cspec[0].imag();
887 for (uInt i = 1; i<cspec.size();i++){
888 maxr = max(maxr, cspec[i].real());
889 maxi = max(maxi, cspec[i].imag());
890 minr = min(minr, cspec[i].real());
891 mini = min(mini, cspec[i].imag());
892 }
893 cout << "Max/Min of conv vector (size=" << cspec.size() << ") = (max: " << maxr << " + " << maxi << "j , min: " << minr << " + " << mini << "j)" << endl;
894#endif
895
896 fftsi.fft0(rspec, cspec, false);
897
898#ifdef KS_DEBUG
899 //cout << "- size of inversed real vector = " << rspec.size() << endl;
900 minMax(minval, maxval, rspec);
901 cout << "Max/Min of inv FFTed Vector (size=" << rspec.size() << ") = (max: " << maxval << ", min: " << minval << ")" << endl;
902 //cout << "Done inverse FFT. icol = " << icol << endl;
903#endif
904
905 icol++;
906 }
907 }
908
909#ifdef KS_DEBUG
910 minMax(minval, maxval, outmat);
911 cout << "Max/Min of inv FFTed Matrix = (max: " << maxval << ", min: " << minval << ")" << endl;
912#endif
913
914 os << "Threshold = " << threshold << ", Rejected channels = " << nreject << endl;
915};
916
917
918void STSideBandSep::aggregateMat(Matrix<float> &inmat,
919 vector<float> &outvec)
920{
921 LogIO os(LogOrigin("STSideBandSep","aggregateMat()", WHERE));
922 if (inmat.nrow() != nchan_)
923 throw(AipsError("Internal error. The row numbers of input matrix differs from nchan_"));
924// if (outvec.size() != nchan_)
925// throw(AipsError("Internal error. The size of output vector should be equal to nchan_"));
926
927 os << "Averaging " << inmat.ncolumn() << " spectra in the input matrix."
928 << LogIO::POST;
929
930 const uInt nspec = inmat.ncolumn();
931 const double scale = 1./( (double) nspec );
932 // initialize values with 0
933 outvec.assign(nchan_, 0);
934 for (uInt isp = 0 ; isp < nspec ; isp++) {
935 for (uInt ich = 0 ; ich < nchan_ ; ich++) {
936 outvec[ich] += inmat(ich, isp);
937 }
938 }
939
940 vector<float>::iterator iter;
941 for (iter = outvec.begin(); iter != outvec.end(); iter++){
942 *iter *= scale;
943 }
944};
945
946void STSideBandSep::subtractFromOther(const Matrix<float> &shiftmat,
947 const vector<float> &invec,
948 const vector<double> &shift,
949 vector<float> &outvec)
950{
951 LogIO os(LogOrigin("STSideBandSep","subtractFromOther()", WHERE));
952 if (shiftmat.nrow() != nchan_)
953 throw(AipsError("Internal error. The row numbers of input matrix differs from nchan_"));
954 if (invec.size() != nchan_)
955 throw(AipsError("Internal error. The length of input vector should be nchan_"));
956 if (shift.size() != shiftmat.ncolumn())
957 throw(AipsError("Internal error. The column numbers of input matrix != the number of elements in shift"));
958
959 const uInt nspec = shiftmat.ncolumn();
960 Vector<float> subsp(nchan_, 0.), shiftsub;
961 Matrix<float> submat(nchan_, nspec, 0.);
962 vector<float>::iterator iter;
963 for (uInt isp = 0 ; isp < nspec ; isp++) {
964 for (uInt ich = 0; ich < nchan_ ; ich++) {
965 subsp(ich) = shiftmat(ich, isp) - invec[ich];
966 }
967 shiftsub.reference(submat.column(isp));
968 shiftSpectrum(subsp, shift[isp], shiftsub);
969 }
970
971 aggregateMat(submat, outvec);
972};
973
974
975void STSideBandSep::setLO1(const string lo1, const string frame,
[2726]976 const double reftime, const string refdir)
[2707]977{
[2794]978 Quantum<Double> qfreq;
979 readQuantity(qfreq, String(lo1));
980 lo1Freq_ = qfreq.getValue("Hz");
[2707]981 MFrequency::getType(loFrame_, frame);
982 loTime_ = reftime;
983 loDir_ = refdir;
984
985#ifdef KS_DEBUG
986 cout << "STSideBandSep::setLO1" << endl;
987 if (lo1Freq_ > 0.)
988 cout << "lo1 = " << lo1Freq_ << " [Hz] (" << frame << ")" << endl;
989 if (loTime_ > 0.)
990 cout << "ref time = " << loTime_ << " [day]" << endl;
991 if (!loDir_.empty())
992 cout << "ref direction = " << loDir_ << " [day]" << endl;
993#endif
994};
995
[2711]996void STSideBandSep::setLO1Root(string name)
[2707]997{
[2711]998 LogIO os(LogOrigin("STSideBandSep","setLO1Root()", WHERE));
999 os << "Searching for '" << name << "'..." << LogIO::POST;
1000 // Check for existance of the file
1001 if (!checkFile(name)) {
[2707]1002 throw(AipsError("File does not exist"));
1003 }
[2711]1004 if (name[(name.size()-1)] == '/')
1005 name = name.substr(0,(name.size()-2));
[2707]1006
[2711]1007 if (checkFile(name+"/Receiver.xml", "file") &&
1008 checkFile(name+"/SpectralWindow.xml", "file")){
1009 os << "Found '" << name << "/Receiver.xml' ... got an ASDM name." << LogIO::POST;
1010 asdmName_ = name;
1011 } else if (checkFile(name+"/ASDM_RECEIVER") &&
1012 checkFile(name+"/ASDM_SPECTRALWINDOW")){
1013 os << "Found '" << name << "/ASDM_RECEIVER' ... got a Table name." << LogIO::POST;
1014 asisName_ = name;
1015 } else {
1016 throw(AipsError("Invalid file name. Set an MS or ASDM name."));
1017 }
[2707]1018
1019#ifdef KS_DEBUG
[2711]1020 cout << "STSideBandSep::setLO1Root" << endl;
1021 if (!asdmName_.empty())
1022 cout << "asdm name = " << asdmName_ << endl;
1023 if (!asisName_.empty())
1024 cout << "MS name = " << asisName_ << endl;
[2707]1025#endif
1026};
1027
[2712]1028
[2794]1029void STSideBandSep::solveImageFrequency()
[2707]1030{
1031 LogIO os(LogOrigin("STSideBandSep","solveImageFreqency()", WHERE));
1032 os << "Start calculating frequencies of image side band" << LogIO::POST;
1033
1034 if (imgTab_p.null())
1035 throw AipsError("STSideBandSep::solveImageFreqency - an image side band scantable should be set first");
1036
[2711]1037 // Convert frequency REFVAL to the value in frame of LO.
[2707]1038 // The code assumes that imgTab_p has only an IF and only a FREQ_ID
1039 // is associated to an IFNO
1040 // TODO: More complete Procedure would be
1041 // 1. Get freq IDs associated to sigIfno_
1042 // 2. Get freq information of the freq IDs
1043 // 3. For each freqIDs, get freq infromation in TOPO and an LO1
1044 // frequency and calculate image band frequencies.
1045 STFrequencies freqTab_ = imgTab_p->frequencies();
1046 // get the base frame of table
1047 const MFrequency::Types tabframe = freqTab_.getFrame(true);
1048 TableVector<uInt> freqIdVec( imgTab_p->table(), "FREQ_ID" );
1049 // assuming single freqID per IFNO
1050 uInt freqid = freqIdVec(0);
[2711]1051 int nChan = imgTab_p->nchan(imgTab_p->getIF(0));
[2707]1052 double refpix, refval, increment ;
1053 freqTab_.getEntry(refpix, refval, increment, freqid);
1054 //MFrequency sigrefval = MFrequency(MVFrequency(refval),tabframe);
1055 // get freq infromation of sigIfno_ in loFrame_
1056 const MPosition mp = imgTab_p->getAntennaPosition();
1057 MEpoch me;
1058 MDirection md;
1059 if (loTime_ < 0.)
1060 me = imgTab_p->getEpoch(-1);
1061 else
1062 me = MEpoch(MVEpoch(loTime_));
1063 if (loDir_.empty()) {
1064 ArrayColumn<Double> srcdirCol_;
1065 srcdirCol_.attach(imgTab_p->table(), "SRCDIRECTION");
1066 // Assuming J2000 and SRCDIRECTION in unit of rad
1067 Quantum<Double> srcra = Quantum<Double>(srcdirCol_(0)(IPosition(1,0)), "rad");
1068 Quantum<Double> srcdec = Quantum<Double>(srcdirCol_(0)(IPosition(1,1)), "rad");
1069 md = MDirection(srcra, srcdec, MDirection::J2000);
1070 //imgTab_p->getDirection(0);
1071 } else {
1072 // parse direction string
1073 string::size_type pos0 = loDir_.find(" ");
1074
1075 if (pos0 == string::npos) {
1076 throw AipsError("bad string format in LO1 direction");
1077 }
1078 string::size_type pos1 = loDir_.find(" ", pos0+1);
1079 String sepoch, sra, sdec;
1080 if (pos1 != string::npos) {
1081 sepoch = loDir_.substr(0, pos0);
1082 sra = loDir_.substr(pos0+1, pos1-pos0);
1083 sdec = loDir_.substr(pos1+1);
1084 }
1085 MDirection::Types epoch;
1086 MDirection::getType(epoch, sepoch);
1087 QuantumHolder qh ;
1088 String err ;
1089 qh.fromString( err, sra);
1090 Quantum<Double> ra = qh.asQuantumDouble() ;
1091 qh.fromString( err, sdec ) ;
1092 Quantum<Double> dec = qh.asQuantumDouble() ;
[2716]1093 //md = MDirection(ra.getValue("rad"), dec.getValue("rad"),epoch);
1094 md = MDirection(ra, dec, epoch);
[2707]1095 }
1096 MeasFrame mframe( me, mp, md );
[2709]1097 MFrequency::Convert tobframe(loFrame_, MFrequency::Ref(tabframe, mframe));
1098 MFrequency::Convert toloframe(tabframe, MFrequency::Ref(loFrame_, mframe));
[2711]1099 // Convert refval to loFrame_
[2707]1100 double sigrefval;
1101 if (tabframe == loFrame_)
1102 sigrefval = refval;
1103 else
1104 sigrefval = toloframe(Quantum<Double>(refval, "Hz")).get("Hz").getValue();
1105
[2711]1106 // Check for the availability of LO1
1107 if (lo1Freq_ > 0.) {
1108 os << "Using user defined LO1 frequency." << LogIO::POST;
1109 } else if (!asisName_.empty()) {
1110 // MS name is set.
1111 os << "Using user defined MS (asis): " << asisName_ << LogIO::POST;
1112 if (!getLo1FromAsisTab(asisName_, sigrefval, refpix, increment, nChan)) {
1113 throw AipsError("Failed to get LO1 frequency from MS");
1114 }
1115 } else if (!asdmName_.empty()) {
1116 // ASDM name is set.
1117 os << "Using user defined ASDM: " << asdmName_ << LogIO::POST;
1118 if (!getLo1FromAsdm(asdmName_, sigrefval, refpix, increment, nChan)) {
1119 throw AipsError("Failed to get LO1 frequency from ASDM");
1120 }
1121 } else {
1122 // Try getting ASDM name from scantable header
1123 os << "Try getting information from scantable header" << LogIO::POST;
[2794]1124 if (!getLo1FromScanTab(tableList_[0], sigrefval, refpix, increment, nChan)) {
[2711]1125 //throw AipsError("Failed to get LO1 frequency from asis table");
1126 os << LogIO::WARN << "Failed to get LO1 frequency using information in scantable." << LogIO::POST;
1127 os << LogIO::WARN << "Could not fill frequency information of IMAGE sideband properly." << LogIO::POST;
1128 os << LogIO::WARN << "Storing values of SIGNAL sideband in FREQUENCIES table" << LogIO::POST;
1129 return;
1130 }
1131 }
[2794]1132
[2711]1133 // LO1 should now be ready.
1134 if (lo1Freq_ < 0.)
1135 throw(AipsError("Got negative LO1 Frequency"));
1136
[2794]1137 // Print summary
1138 {
1139 // LO1
1140 Vector<Double> dirvec = md.getAngle(Unit(String("rad"))).getValue();
1141 os << "[LO1 settings]" << LogIO::POST;
1142 os << "- Frequency: " << lo1Freq_ << " [Hz] ("
1143 << MFrequency::showType(loFrame_) << ")" << LogIO::POST;
1144 os << "- Reference time: " << me.get(Unit(String("d"))).getValue()
1145 << " [day]" << LogIO::POST;
1146 os << "- Reference direction: [" << dirvec[0] << ", " << dirvec[1]
1147 << "] (" << md.getRefString() << ") " << LogIO::POST;
[2711]1148
[2794]1149 // signal sideband
1150 os << "[Signal side band]" << LogIO::POST;
1151 os << "- IFNO: " << imgTab_p->getIF(0) << " (FREQ_ID = " << freqid << ")"
1152 << LogIO::POST;
1153 os << "- Reference value: " << refval << " [Hz] ("
1154 << MFrequency::showType(tabframe) << ") = "
1155 << sigrefval << " [Hz] (" << MFrequency::showType(loFrame_)
1156 << ")" << LogIO::POST;
1157 os << "- Reference pixel: " << refpix << LogIO::POST;
1158 os << "- Increment: " << increment << " [Hz]" << LogIO::POST;
1159 }
[2711]1160
1161 // Calculate image band incr and refval in loFrame_
[2707]1162 Double imgincr = -increment;
1163 Double imgrefval = 2 * lo1Freq_ - sigrefval;
1164 Double imgrefval_tab = imgrefval;
[2711]1165 // Convert imgrefval back to table base frame
[2707]1166 if (tabframe != loFrame_)
1167 imgrefval = tobframe(Quantum<Double>(imgrefval, "Hz")).get("Hz").getValue();
[2711]1168 // Set new frequencies table
[2707]1169 uInt fIDnew = freqTab_.addEntry(refpix, imgrefval, imgincr);
[2711]1170 // Update FREQ_ID in table.
[2707]1171 freqIdVec = fIDnew;
[2711]1172
[2794]1173 // Print summary (Image sideband)
1174 {
1175 os << "[Image side band]" << LogIO::POST;
1176 os << "- IFNO: " << imgTab_p->getIF(0) << " (FREQ_ID = " << freqIdVec(0)
1177 << ")" << LogIO::POST;
1178 os << "- Reference value: " << imgrefval << " [Hz] ("
1179 << MFrequency::showType(tabframe) << ") = "
1180 << imgrefval_tab << " [Hz] (" << MFrequency::showType(loFrame_)
1181 << ")" << LogIO::POST;
1182 os << "- Reference pixel: " << refpix << LogIO::POST;
1183 os << "- Increment: " << imgincr << " [Hz]" << LogIO::POST;
1184 }
[2707]1185};
1186
1187Bool STSideBandSep::checkFile(const string name, string type)
1188{
1189 File file(name);
1190 if (!file.exists()){
1191 return false;
1192 } else if (type.empty()) {
1193 return true;
1194 } else {
1195 // Check for file type
1196 switch (tolower(type[0])) {
1197 case 'f':
1198 return file.isRegular(True);
1199 case 'd':
1200 return file.isDirectory(True);
1201 case 's':
1202 return file.isSymLink();
1203 default:
1204 throw AipsError("Invalid file type. Available types are 'file', 'directory', and 'symlink'.");
1205 }
1206 }
1207};
1208
[2711]1209bool STSideBandSep::getLo1FromAsdm(const string asdmname,
1210 const double refval,
1211 const double refpix,
1212 const double increment,
1213 const int nChan)
[2707]1214{
1215 // Check for relevant tables.
1216 string spwname = asdmname + "/SpectralWindow.xml";
1217 string recname = asdmname + "/Receiver.xml";
1218 if (!checkFile(spwname) || !checkFile(recname)) {
1219 throw(AipsError("Could not find subtables in ASDM"));
1220 }
1221
1222 return false;
1223
1224};
1225
1226
[2711]1227bool STSideBandSep::getLo1FromScanTab(CountedPtr< Scantable > &scantab,
1228 const double refval,
1229 const double refpix,
1230 const double increment,
1231 const int nChan)
[2707]1232{
[2711]1233 LogIO os(LogOrigin("STSideBandSep","getLo1FromScanTab()", WHERE));
[2707]1234 // Check for relevant tables.
[2712]1235 const TableRecord &rec = scantab->table().keywordSet() ;
[2711]1236 String spwname, recname;
[2712]1237 if (rec.isDefined("ASDM_SPECTRALWINDOW") && rec.isDefined("ASDM_RECEIVER")){
1238 spwname = rec.asString("ASDM_SPECTRALWINDOW");
1239 recname = rec.asString("ASDM_RECEIVER");
1240 }
1241 else {
[2711]1242 // keywords are not there
1243 os << LogIO::WARN
1244 << "Could not find necessary table names in scantable header."
1245 << LogIO::POST;
1246 return false;
1247 }
[2707]1248 if (!checkFile(spwname,"directory") || !checkFile(recname,"directory")) {
[2711]1249 throw(AipsError("Could not find relevant subtables in MS"));
[2707]1250 }
[2711]1251 // Get root MS name
1252 string msname;
1253 const String recsuff = "/ASDM_RECEIVER";
1254 String::size_type pos;
[2712]1255 pos = recname.size()-recsuff.size();
[2711]1256 if (recname.substr(pos) == recsuff)
[2712]1257 msname = recname.substr(0, pos);
[2711]1258 else
1259 throw(AipsError("Internal error in parsing table name from a scantable keyword."));
[2707]1260
[2711]1261 if (!checkFile(msname))
1262 throw(AipsError("Internal error in parsing MS name from a scantable keyword."));
[2707]1263
[2711]1264 return getLo1FromAsisTab(msname, refval, refpix, increment, nChan);
1265
[2707]1266};
1267
[2711]1268bool STSideBandSep::getLo1FromAsisTab(const string msname,
1269 const double refval,
1270 const double refpix,
1271 const double increment,
1272 const int nChan)
1273{
1274 LogIO os(LogOrigin("STSideBandSep","getLo1FromAsisTab()", WHERE));
1275 os << "Searching an LO1 frequency in '" << msname << "'" << LogIO::POST;
1276 // Check for relevant tables.
1277 const string spwname = msname + "/ASDM_SPECTRALWINDOW";
1278 const string recname = msname + "/ASDM_RECEIVER";
1279 if (!checkFile(spwname,"directory") || !checkFile(recname,"directory")) {
1280 throw(AipsError("Could not find relevant tables in MS"));
1281 }
[2707]1282
[2711]1283 Table spwtab_ = Table(spwname);
1284 String asdmSpw;
1285 ROTableRow spwrow(spwtab_);
1286 const Double rtol = 0.01;
1287 for (uInt idx = 0; idx < spwtab_.nrow(); idx++){
1288 const TableRecord& rec = spwrow.get(idx);
1289 // Compare nchan
1290 if (rec.asInt("numChan") != (Int) nChan)
1291 continue;
1292 // Compare increment
1293 Double asdminc;
1294 Array<Double> incarr = rec.asArrayDouble("chanWidthArray");
1295 if (incarr.size() > 0)
1296 asdminc = incarr(IPosition(1, (uInt) refpix));
1297 else
1298 asdminc = rec.asDouble("chanWidth");
1299 if (abs(asdminc - abs(increment)) > rtol * abs(increment))
1300 continue;
1301 // Compare refval
1302 Double asdmrefv;
1303 Array<Double> refvarr = rec.asArrayDouble("chanFreqArray");
1304 if (refvarr.size() > 0){
1305 const uInt iref = (uInt) refpix;
1306 const Double ratio = refpix - (Double) iref;
1307 asdmrefv = refvarr(IPosition(1, iref))*(1.-ratio)
1308 + refvarr(IPosition(1,iref+1))*ratio;
1309 }
1310 else {
1311 const Double ch0 = rec.asDouble("chanFreqStart");
1312 const Double chstep = rec.asDouble("chanFreqStep");
1313 asdmrefv = ch0 + chstep * refpix;
1314 }
1315 if (abs(asdmrefv - refval) < 0.5*abs(asdminc)){
1316 asdmSpw = rec.asString("spectralWindowId");
1317 break;
1318 }
1319 }
1320
1321 if (asdmSpw.empty()){
1322 os << LogIO::WARN << "Could not find relevant SPW ID in " << spwname << LogIO::POST;
1323 return false;
1324 }
1325 else {
1326 os << asdmSpw << " in " << spwname
1327 << " matches the freqeuncies of signal side band." << LogIO::POST;
1328 }
1329
1330 Table rectab_ = Table(recname);
1331 ROTableRow recrow(rectab_);
1332 for (uInt idx = 0; idx < rectab_.nrow(); idx++){
1333 const TableRecord& rec = recrow.get(idx);
1334 if (rec.asString("spectralWindowId") == asdmSpw){
1335 const Array<Double> loarr = rec.asArrayDouble("freqLO");
1336 lo1Freq_ = loarr(IPosition(1,0));
1337 os << "Found LO1 Frequency in " << recname << ": "
1338 << lo1Freq_ << " [Hz]" << LogIO::POST;
1339 return true;
1340 }
1341 }
1342 os << LogIO::WARN << "Could not find " << asdmSpw << " in " << recname
1343 << LogIO::POST;
1344 return false;
1345};
1346
[2707]1347} //namespace asap
Note: See TracBrowser for help on using the repository browser.