source: trunk/src/STSideBandSep.cpp@ 2853

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

New Development: Yes

JIRA Issue: Yes (CAS-5139/TRAC-290)

Ready for Test: Yes

Interface Changes: Yes

What Interface Changed: A couple of private functions are added to STSideBandSep class.

Test Programs:

Put in Release Notes: Yes

Module(s): asap.sbseparator

Description: Implemented a way to transfer channel based flag of imput tables to output tables. Channel flag is accumulated by logical SUM.


File size: 46.8 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_);
[2852]263 Matrix<bool> flagMat(nchan_, nshift_);
[2794]264 vector<float> sigSpec(nchan_), imgSpec(nchan_);
[2852]265 Vector<bool> flagVec(nchan_);
[2794]266 vector<uInt> tabIdvec;
267
268 //Generate FFTServer
269 fftsf.resize(IPosition(1, nchan_), FFTEnums::REALTOCOMPLEX);
270 fftsi.resize(IPosition(1, nchan_), FFTEnums::COMPLEXTOREAL);
271
272 /// Loop over sigTab_p and separate sideband
273 for (int irow = 0; irow < sigTab_p->nrow(); irow++){
274 tabIdvec.resize(0);
275 const int polId = sigTab_p->getPol(irow);
276 const int beamId = sigTab_p->getBeam(irow);
277 const vector<double> dir = sigTab_p->getDirectionVector(irow);
278 // Get a set of spectra to solve
279 if (!getSpectraToSolve(polId, beamId, dir[0], dir[1],
[2852]280 specMat, flagMat, tabIdvec)){
[2794]281 remRowIds.push_back(irow);
282#ifdef KS_DEBUG
283 cout << "no matching row found. skipping row = " << irow << endl;
284#endif
285 continue;
286 }
287 // Solve signal sideband
288 sigSpec = solve(specMat, tabIdvec, true);
289 sigTab_p->setSpectrum(sigSpec, irow);
[2838]290 if (sigTab_p->isAllChannelsFlagged(irow)){
291 // unflag the spectrum since there should be some valid data
292 sigTab_p->flagRow(vector<uInt>(irow), true);
[2852]293 // need to unflag whole channels anyway
[2838]294 sigTab_p->flag(irow, vector<bool>(), true);
295 }
[2852]296 // apply channel flag
297 flagVec = collapseFlag(flagMat, tabIdvec, true);
298 //boolVec = !boolVec; // flag
299 sigTab_p->flag(irow, flagVec.tovector(), false);
[2794]300
301 // Solve image sideband
302 if (doboth_) {
303 imgSpec = solve(specMat, tabIdvec, false);
304 imgTab_p->setSpectrum(imgSpec, irow);
[2838]305 if (imgTab_p->isAllChannelsFlagged(irow)){
306 // unflag the spectrum since there should be some valid data
307 imgTab_p->flagRow(vector<uInt>(irow), true);
[2852]308 // need to unflag whole channels anyway
[2838]309 imgTab_p->flag(irow, vector<bool>(), true);
310 }
[2852]311 // apply channel flag
312 flagVec = collapseFlag(flagMat, tabIdvec, false);
313 //boolVec = !boolVec; // flag
314 imgTab_p->flag(irow, flagVec.tovector(), true);
[2794]315 }
316 } // end of row loop
317
318 // Remove or flag rows without relevant data from gridded tables
319 if (remRowIds.size() > 0) {
320 const size_t nrem = remRowIds.size();
321 if ( sigTab_p->table().canRemoveRow() ) {
322 sigTab_p->table().removeRow(remRowIds);
323 os << "Removing " << nrem << " rows from the signal band table"
324 << LogIO::POST;
325 } else {
326 sigTab_p->flagRow(remRowIds, false);
327 os << "Cannot remove rows from the signal band table. Flagging "
328 << nrem << " rows" << LogIO::POST;
329 }
330
331 if (doboth_) {
332 if ( imgTab_p->table().canRemoveRow() ) {
333 imgTab_p->table().removeRow(remRowIds);
334 os << "Removing " << nrem << " rows from the image band table"
335 << LogIO::POST;
336 } else {
337 imgTab_p->flagRow(remRowIds, false);
338 os << "Cannot remove rows from the image band table. Flagging "
339 << nrem << " rows" << LogIO::POST;
340 }
341 }
342 }
343
344 // Finally, save tables on disk
345 if (outname.size() ==0)
346 outname = "sbseparated.asap";
347 const string sigName = outname + ".signalband";
348 os << "Saving SIGNAL sideband table: " << sigName << LogIO::POST;
349 sigTab_p->makePersistent(sigName);
350 if (doboth_) {
351 solveImageFrequency();
352 const string imgName = outname + ".imageband";
353 os << "Saving IMAGE sideband table: " << sigName << LogIO::POST;
354 imgTab_p->makePersistent(imgName);
355 }
356
[2707]357};
358
[2794]359unsigned int STSideBandSep::setupShift()
360{
361 LogIO os(LogOrigin("STSideBandSep","setupShift()", WHERE));
362 if (infileList_.size() == 0 && intabList_.size() == 0)
363 throw( AipsError("No scantable has been set. Set a list of scantables first.") );
364
365 const bool byname = (intabList_.size() == 0);
366 // Make sure sigIfno_ exists in the first table.
367 CountedPtr<Scantable> stab;
368 vector<string> coordsav;
369 vector<string> coordtmp(3);
370 os << "Checking IFNO in the first table." << LogIO::POST;
371 if (byname) {
372 if (!checkFile(infileList_[0], "d"))
373 os << LogIO::SEVERE << "Could not find scantable '" << infileList_[0]
374 << "'" << LogIO::EXCEPTION;
375 stab = CountedPtr<Scantable>(new Scantable(infileList_[0]));
376 } else {
377 stab = intabList_[0];
378 }
379 if (sigIfno_ < 0) {
380 sigIfno_ = (int) stab->getIF(0);
381 os << "IFNO to process has not been set. Using the first IF = "
382 << sigIfno_ << LogIO::POST;
383 }
384
385 unsigned int basench;
386 double basech0, baseinc, ftolval, inctolval;
387 coordsav = stab->getCoordInfo();
388 const string stfframe = coordsav[1];
389 coordtmp[0] = "Hz";
390 coordtmp[1] = ( (solFrame_ == MFrequency::N_Types) ?
391 stfframe :
392 MFrequency::showType(solFrame_) );
393 coordtmp[2] = coordsav[2];
394 stab->setCoordInfo(coordtmp);
395 if (!getFreqInfo(stab, (unsigned int) sigIfno_, basech0, baseinc, basench)) {
396 os << LogIO::SEVERE << "No data with IFNO=" << sigIfno_
397 << " found in the first table." << LogIO::EXCEPTION;
398 }
399 else {
400 os << "Found IFNO = " << sigIfno_
401 << " in the first table." << LogIO::POST;
402 }
403 if (ftol_.getUnit().empty()) {
404 // tolerance in unit of channels
405 ftolval = ftol_.getValue() * baseinc;
406 }
407 else {
408 ftolval = ftol_.getValue("Hz");
409 }
410 inctolval = abs(baseinc/(double) basench);
411 const string poltype0 = stab->getPolType();
412
413 // Initialize shift values
414 initshift();
415
416 const bool setImg = ( doboth_ && (imgShift_.size() == 0) );
417 // Select IFs
418 for (unsigned int itab = 0; itab < ntable_; itab++ ){
419 os << "Table " << itab << LogIO::POST;
420 if (itab > 0) {
421 if (byname) {
422 if (!checkFile(infileList_[itab], "d"))
423 os << LogIO::SEVERE << "Could not find scantable '"
424 << infileList_[itab] << "'" << LogIO::EXCEPTION;
425 stab = CountedPtr<Scantable>(new Scantable(infileList_[itab]));
426 } else {
427 stab = intabList_[itab];
428 }
429 //POLTYPE should be the same.
430 if (stab->getPolType() != poltype0 ) {
431 os << LogIO::WARN << "POLTYPE differs from the first table."
432 << " Skipping the table" << LogIO::POST;
433 continue;
434 }
435 // Multi beam data may not handled properly
436 if (stab->nbeam() > 1)
437 os << LogIO::WARN << "Table contains multiple beams. "
438 << "It may not be handled properly." << LogIO::POST;
439
440 coordsav = stab->getCoordInfo();
441 coordtmp[2] = coordsav[2];
442 stab->setCoordInfo(coordtmp);
443 }
444 bool selected = false;
445 vector<uint> ifnos = stab->getIFNos();
446 vector<uint>::iterator iter;
447 const STSelector& basesel = stab->getSelection();
448 for (iter = ifnos.begin(); iter != ifnos.end(); iter++){
449 unsigned int nch;
450 double freq0, incr;
451 if ( getFreqInfo(stab, *iter, freq0, incr, nch) ){
452 if ( (nch == basench) && (abs(freq0-basech0) < ftolval)
453 && (abs(incr-baseinc) < inctolval) ){
454 //Found
455 STSelector sel(basesel);
456 sel.setIFs(vector<int>(1,(int) *iter));
457 stab->setSelection(sel);
458 CountedPtr<Scantable> seltab = ( new Scantable(*stab, false) );
459 stab->setSelection(basesel);
460 seltab->setCoordInfo(coordsav);
461 const double chShift = (freq0 - basech0) / baseinc;
462 tableList_.push_back(seltab);
[2808]463 sigShift_.push_back(-chShift);
[2794]464 if (setImg)
[2808]465 imgShift_.push_back(chShift);
[2794]466
467 selected = true;
468 os << "- IF" << *iter << " selected: sideband shift = "
469 << chShift << " channels" << LogIO::POST;
470 }
471 }
472 } // ifno loop
473 stab->setCoordInfo(coordsav);
474 if (!selected)
475 os << LogIO::WARN << "No data selected in Table "
476 << itab << LogIO::POST;
477 } // table loop
478 nchan_ = basench;
479
480 os << "Total number of IFs selected = " << tableList_.size()
481 << LogIO::POST;
482 if ( setImg && (sigShift_.size() != imgShift_.size()) ){
483 os << LogIO::SEVERE
484 << "User defined channel shift of image sideband has "
485 << imgShift_.size()
486 << " elements, while selected IFNOs are " << sigShift_.size()
487 << "\nThe frequency tolerance (freqtol) may be too small."
488 << LogIO::EXCEPTION;
489 }
490
491 return tableList_.size();
492};
493
494bool STSideBandSep::getFreqInfo(const CountedPtr<Scantable> &stab,
495 const unsigned int &ifno,
496 double &freq0, double &incr,
497 unsigned int &nchan)
498{
499 vector<uint> ifnos = stab->getIFNos();
500 bool found = false;
501 vector<uint>::iterator iter;
502 for (iter = ifnos.begin(); iter != ifnos.end(); iter++){
503 if (*iter == ifno) {
504 found = true;
505 break;
506 }
507 }
508 if (!found)
509 return false;
510
511 const STSelector& basesel = stab->getSelection();
512 STSelector sel(basesel);
513 sel.setIFs(vector<int>(1,(int) ifno));
514 stab->setSelection(sel);
515 vector<double> freqs;
516 freqs = stab->getAbcissa(0);
517 freq0 = freqs[0];
518 incr = freqs[1] - freqs[0];
519 nchan = freqs.size();
520 stab->setSelection(basesel);
521 return true;
522};
523
524ScantableWrapper STSideBandSep::gridTable()
525{
526 LogIO os(LogOrigin("STSideBandSep","gridTable()", WHERE));
527 if (tableList_.size() == 0)
528 throw( AipsError("Internal error. No scantable has been set to grid.") );
529 Double xmin, xmax, ymin, ymax;
530 mapExtent(tableList_, xmin, xmax, ymin, ymax);
531 const Double centx = 0.5 * (xmin + xmax);
532 const Double centy = 0.5 * (ymin + ymax);
533 const int nx = max(1, (int) ceil( (xmax - xmin) * cos(centy) /xtol_ ) );
534 const int ny = max(1, (int) ceil( (ymax - ymin) / ytol_ ) );
535
536 string scellx, scelly;
537 {
538 ostringstream oss;
539 oss << xtol_ << "rad" ;
540 scellx = oss.str();
541 }
542 {
543 ostringstream oss;
544 oss << ytol_ << "rad" ;
545 scelly = oss.str();
546 }
547
548 ScantableWrapper stab0;
549 if (intabList_.size() > 0)
550 stab0 = ScantableWrapper(intabList_[0]);
551 else
552 stab0 = ScantableWrapper(infileList_[0]);
553
554 string scenter;
555 {
556 ostringstream oss;
557 oss << stab0.getCP()->getDirectionRefString() << " "
558 << centx << "rad" << " " << centy << "rad";
559 scenter = oss.str();
560 }
561
562 STGrid2 gridder = STGrid2(stab0);
563 gridder.setIF(sigIfno_);
564 gridder.defineImage(nx, ny, scellx, scelly, scenter);
[2835]565 // gridder.setFunc("box", 1); // convsupport=1 fails
566 gridder.setFunc("box");
[2794]567 gridder.setWeight("uniform");
568#ifdef KS_DEBUG
569 cout << "Grid parameter summary: " << endl;
570 cout << "- IF = " << sigIfno_ << endl;
[2836]571 cout << "- center = " << scenter << "\n"
[2794]572 << "- npix = (" << nx << ", " << ny << ")\n"
[2836]573 << "- cell = (" << scellx << ", " << scelly << ")" << endl;
[2794]574#endif
575 gridder.grid();
576 const int itp = (tp_ == Table::Memory ? 0 : 1);
577 ScantableWrapper gtab = gridder.getResultAsScantable(itp);
578 return gtab;
579};
580
581void STSideBandSep::mapExtent(vector< CountedPtr<Scantable> > &tablist,
582 Double &xmin, Double &xmax,
583 Double &ymin, Double &ymax)
584{
585 ROArrayColumn<Double> dirCol_;
586 dirCol_.attach( tablist[0]->table(), "DIRECTION" );
587 Matrix<Double> direction = dirCol_.getColumn();
588 Vector<Double> ra( direction.row(0) );
589 mathutil::rotateRA(ra);
590 minMax( xmin, xmax, ra );
591 minMax( ymin, ymax, direction.row(1) );
592 Double amin, amax, bmin, bmax;
593 const uInt ntab = tablist.size();
594 for ( uInt i = 1 ; i < ntab ; i++ ) {
595 dirCol_.attach( tablist[i]->table(), "DIRECTION" );
596 direction.assign( dirCol_.getColumn() );
597 ra.assign( direction.row(0) );
598 mathutil::rotateRA(ra);
599 minMax( amin, amax, ra );
600 minMax( bmin, bmax, direction.row(1) );
601 xmin = min(xmin, amin);
602 xmax = max(xmax, amax);
603 ymin = min(ymin, bmin);
604 ymax = max(ymax, bmax);
605 }
606};
607
[2852]608// bool STSideBandSep::getSpectraToSolve(const int polId, const int beamId,
609// const double dirX, const double dirY,
610// Matrix<float> &specMat, vector<uInt> &tabIdvec)
[2794]611bool STSideBandSep::getSpectraToSolve(const int polId, const int beamId,
612 const double dirX, const double dirY,
[2852]613 Matrix<float> &specMat,
614 Matrix<bool> &flagMat,
615 vector<uInt> &tabIdvec)
[2794]616{
617 LogIO os(LogOrigin("STSideBandSep","getSpectraToSolve()", WHERE));
618
619 tabIdvec.resize(0);
620 specMat.resize(nchan_, nshift_);
621 Vector<float> spec;
[2852]622 Vector<bool> boolVec;
[2794]623 uInt nspec = 0;
624 STMath stm(false); // insitu has no effect for average.
625 for (uInt itab = 0 ; itab < nshift_ ; itab++) {
626 CountedPtr<Scantable> currtab_p = tableList_[itab];
627 // Selection by POLNO and BEAMNO
628 const STSelector& basesel = currtab_p->getSelection();
629 STSelector sel(basesel);
630 sel.setPolarizations(vector<int>(1, polId));
631 sel.setBeams(vector<int>(1, beamId));
632 try {
633 currtab_p->setSelection(sel);
634 } catch (...) {
635#ifdef KS_DEBUG
636 cout << "Table " << itab << " - No spectrum found. skipping the table."
637 << endl;
638#endif
639 continue;
640 }
641 // Selection by direction;
642 vector<int> selrow(0);
643 vector<double> currDir(2, 0.);
644 const int nselrow = currtab_p->nrow();
645 for (int irow = 0 ; irow < nselrow ; irow++) {
646 currDir = currtab_p->getDirectionVector(irow);
647 if ( (abs(currDir[0]-dirX) > xtol_) ||
648 (abs(currDir[1]-dirY) > ytol_) )
649 continue;
650 // within direction tolerance
651 selrow.push_back(irow);
652 } // end of row loop
653
654 if (selrow.size() < 1) {
655 currtab_p->setSelection(basesel);
656
657#ifdef KS_DEBUG
658 cout << "Table " << itab << " - No spectrum found. skipping the table."
659 << endl;
660#endif
661
662 continue;
663 }
664
665 // At least a spectrum is selected in this table
666 CountedPtr<Scantable> seltab_p = ( new Scantable(*currtab_p, false) );
667 currtab_p->setSelection(basesel);
668 STSelector sel2(seltab_p->getSelection());
669 sel2.setRows(selrow);
670 seltab_p->setSelection(sel2);
671 CountedPtr<Scantable> avetab_p;
672 if (seltab_p->nrow() > 1) {
[2836]673 // STMath::average also merges FLAGTRA and FLAGROW
[2794]674 avetab_p = stm.average(vector< CountedPtr<Scantable> >(1, seltab_p),
675 vector<bool>(), "TINTSYS", "NONE");
676#ifdef KS_DEBUG
677 cout << "Table " << itab << " - more than a spectrum is selected. averaging rows..."
678 << endl;
679#endif
680 if (avetab_p->nrow() > 1)
681 throw( AipsError("Averaged table has more than a row. Somethigs went wrong.") );
682 } else {
683 avetab_p = seltab_p;
684 }
[2836]685 // Check FLAGTRA and FLAGROW if there's any valid channel in the spectrum
686 if (avetab_p->getFlagRow(0) || avetab_p->isAllChannelsFlagged(0)) {
687#ifdef KS_DEBUG
688 cout << "Table " << itab << " - All data are flagged. skipping the table."
689 << endl;
690#endif
691 continue;
692 }
693 // Interpolate flagged channels of the spectrum.
694 Vector<Float> tmpSpec = avetab_p->getSpectrum(0);
[2852]695 // Mask is true if the data is valid (!flag)
[2836]696 vector<bool> mask = avetab_p->getMask(0);
697 mathutil::doZeroOrderInterpolation(tmpSpec, mask);
[2794]698 spec.reference(specMat.column(nspec));
[2836]699 spec = tmpSpec;
[2852]700 boolVec.reference(flagMat.column(nspec));
701 boolVec = mask; // cast std::vector to casa::Vector
702 boolVec = !boolVec;
[2794]703 tabIdvec.push_back((uInt) itab);
704 nspec++;
[2852]705 //Liberate from reference
706 spec.unique();
707 boolVec.unique();
[2794]708 } // end of table loop
[2836]709 // Check the number of selected spectra and resize matrix.
[2794]710 if (nspec != nshift_){
711 //shiftSpecmat.resize(nchan_, nspec, true);
[2836]712 specMat.resize(nchan_, nspec, true);
[2852]713 flagMat.resize(nchan_, nspec, true);
[2794]714#ifdef KS_DEBUG
715 cout << "Could not find corresponding rows in some tables."
716 << endl;
717 cout << "Number of spectra selected = " << nspec << endl;
718#endif
719 }
720 if (nspec < 2) {
721#ifdef KS_DEBUG
722 cout << "At least 2 spectra are necessary for convolution"
723 << endl;
724#endif
725 return false;
726 }
727 return true;
728};
729
[2852]730
731Vector<bool> STSideBandSep::collapseFlag(const Matrix<bool> &flagMat,
732 const vector<uInt> &tabIdvec,
733 const bool signal)
734{
735 LogIO os(LogOrigin("STSideBandSep","collapseFlag()", WHERE));
736 if (tabIdvec.size() == 0)
737 throw(AipsError("Internal error. Table index is not defined."));
738 if (flagMat.ncolumn() != tabIdvec.size())
739 throw(AipsError("Internal error. The row number of input matrix is not conformant."));
740 if (flagMat.nrow() != nchan_)
741 throw(AipsError("Internal error. The channel size of input matrix is not conformant."));
742
743 const size_t nspec = tabIdvec.size();
744 vector<double> *thisShift;
745 if (signal == otherside_) {
746 // (solve signal && solveother = T) OR (solve image && solveother = F)
747 thisShift = &imgShift_;
748 } else {
749 // (solve signal && solveother = F) OR (solve image && solveother = T)
750 thisShift = &sigShift_;
751 }
752
753 Vector<bool> outflag(nchan_, false);
754 double tempshift;
755 Vector<bool> shiftvec(nchan_, false);
756 Vector<bool> accflag(nchan_, false);
757 uInt shiftId;
758 for (uInt i = 0 ; i < nspec; ++i) {
759 shiftId = tabIdvec[i];
760 tempshift = - thisShift->at(shiftId);
761 shiftFlag(flagMat.column(i), tempshift, shiftvec);
762 // Now accumulate Flag
763 for (uInt j = 0 ; j < nchan_ ; ++j)
764 accflag[j] |= shiftvec[j];
765 }
766 // Shift back Flag
767 shiftFlag(accflag, thisShift->at(0), outflag);
768
769 return outflag;
770}
771
772
[2794]773vector<float> STSideBandSep::solve(const Matrix<float> &specmat,
774 const vector<uInt> &tabIdvec,
775 const bool signal)
776{
777 LogIO os(LogOrigin("STSideBandSep","solve()", WHERE));
778 if (tabIdvec.size() == 0)
779 throw(AipsError("Internal error. Table index is not defined."));
780 if (specmat.ncolumn() != tabIdvec.size())
781 throw(AipsError("Internal error. The row number of input matrix is not conformant."));
782 if (specmat.nrow() != nchan_)
783 throw(AipsError("Internal error. The channel size of input matrix is not conformant."));
784
785
786#ifdef KS_DEBUG
787 cout << "Solving " << (signal ? "SIGNAL" : "IMAGE") << " sideband."
788 << endl;
789#endif
790
791 const size_t nspec = tabIdvec.size();
792 vector<double> *thisShift, *otherShift;
793 if (signal == otherside_) {
794 // (solve signal && solveother = T) OR (solve image && solveother = F)
795 thisShift = &imgShift_;
796 otherShift = &sigShift_;
797#ifdef KS_DEBUG
798 cout << "Image sideband will be deconvolved." << endl;
799#endif
800 } else {
801 // (solve signal && solveother = F) OR (solve image && solveother = T)
802 thisShift = &sigShift_;
[2838]803 otherShift = &imgShift_;
[2794]804#ifdef KS_DEBUG
805 cout << "Signal sideband will be deconvolved." << endl;
806#endif
807 }
808
809 vector<double> spshift(nspec);
810 Matrix<float> shiftSpecmat(nchan_, nspec, 0.);
811 double tempshift;
812 Vector<float> shiftspvec;
[2838]813 uInt shiftId;
[2794]814 for (uInt i = 0 ; i < nspec; i++) {
[2838]815 shiftId = tabIdvec[i];
816 spshift[i] = otherShift->at(shiftId) - thisShift->at(shiftId);
817 tempshift = - thisShift->at(shiftId);
[2794]818 shiftspvec.reference(shiftSpecmat.column(i));
819 shiftSpectrum(specmat.column(i), tempshift, shiftspvec);
820 }
821
822 Matrix<float> convmat(nchan_, nspec*(nspec-1)/2, 0.);
823 vector<float> thisvec(nchan_, 0.);
824
825 float minval, maxval;
826 minMax(minval, maxval, shiftSpecmat);
827#ifdef KS_DEBUG
828 cout << "Max/Min of input Matrix = (max: " << maxval << ", min: " << minval << ")" << endl;
829#endif
830
831#ifdef KS_DEBUG
832 cout << "starting deconvolution" << endl;
833#endif
834 deconvolve(shiftSpecmat, spshift, rejlimit_, convmat);
835#ifdef KS_DEBUG
836 cout << "finished deconvolution" << endl;
837#endif
838
839 minMax(minval, maxval, convmat);
840#ifdef KS_DEBUG
841 cout << "Max/Min of output Matrix = (max: " << maxval << ", min: " << minval << ")" << endl;
842#endif
843
844 aggregateMat(convmat, thisvec);
845
846 if (!otherside_) return thisvec;
847
848 // subtract from the other side band.
849 vector<float> othervec(nchan_, 0.);
850 subtractFromOther(shiftSpecmat, thisvec, spshift, othervec);
851 return othervec;
852};
853
854
855void STSideBandSep::shiftSpectrum(const Vector<float> &invec,
856 double shift,
857 Vector<float> &outvec)
858{
859 LogIO os(LogOrigin("STSideBandSep","shiftSpectrum()", WHERE));
860 if (invec.size() != nchan_)
861 throw(AipsError("Internal error. The length of input vector differs from nchan_"));
862 if (outvec.size() != nchan_)
863 throw(AipsError("Internal error. The length of output vector differs from nchan_"));
864
865#ifdef KS_DEBUG
866 cout << "Start shifting spectrum for " << shift << "channels" << endl;
867#endif
868
869 // tweak shift to be in 0 ~ nchan_-1
870 if ( fabs(shift) > nchan_ ) shift = fmod(shift, nchan_);
871 if (shift < 0.) shift += nchan_;
872 double rweight = fmod(shift, 1.);
873 if (rweight < 0.) rweight += 1.;
874 double lweight = 1. - rweight;
875 uInt lchan, rchan;
876
877 outvec = 0;
878 for (uInt i = 0 ; i < nchan_ ; i++) {
879 lchan = uInt( floor( fmod( (i + shift), nchan_ ) ) );
880 if (lchan < 0.) lchan += nchan_;
881 rchan = ( (lchan + 1) % nchan_ );
882 outvec(lchan) += invec(i) * lweight;
883 outvec(rchan) += invec(i) * rweight;
884 }
885};
886
[2852]887
888void STSideBandSep::shiftFlag(const Vector<bool> &invec,
889 double shift,
890 Vector<bool> &outvec)
891{
892 LogIO os(LogOrigin("STSideBandSep","shiftFlag()", WHERE));
893 if (invec.size() != nchan_)
894 throw(AipsError("Internal error. The length of input vector differs from nchan_"));
895 if (outvec.size() != nchan_)
896 throw(AipsError("Internal error. The length of output vector differs from nchan_"));
897
898#ifdef KS_DEBUG
899 cout << "Start shifting flag for " << shift << "channels" << endl;
900#endif
901
902 // shift is almost integer think it as int.
903 // tolerance should be in 0 - 1
904 double tolerance = 0.01;
905 // tweak shift to be in 0 ~ nchan_-1
906 if ( fabs(shift) > nchan_ ) shift = fmod(shift, nchan_);
907 if (shift < 0.) shift += nchan_;
908 double rweight = fmod(shift, 1.);
909 bool ruse(true), luse(true);
910 if (rweight < 0.) rweight += 1.;
911 if (rweight < tolerance){
912 ruse = true;
913 luse = false;
914 }
915 if (rweight > 1-tolerance){
916 ruse = false;
917 luse = true;
918 }
919 uInt lchan, rchan;
920
921 outvec = false;
922 for (uInt i = 0 ; i < nchan_ ; i++) {
923 lchan = uInt( floor( fmod( (i + shift), nchan_ ) ) );
924 if (lchan < 0.) lchan += nchan_;
925 rchan = ( (lchan + 1) % nchan_ );
926 outvec(lchan) |= (invec(i) && luse);
927 outvec(rchan) |= (invec(i) && ruse);
928 }
929};
930
931
[2794]932void STSideBandSep::deconvolve(Matrix<float> &specmat,
933 const vector<double> shiftvec,
934 const double threshold,
935 Matrix<float> &outmat)
936{
937 LogIO os(LogOrigin("STSideBandSep","deconvolve()", WHERE));
938 if (specmat.nrow() != nchan_)
939 throw(AipsError("Internal error. The length of input matrix differs from nchan_"));
940 if (specmat.ncolumn() != shiftvec.size())
941 throw(AipsError("Internal error. The number of input shifts and spectrum differs."));
942
[2836]943#ifdef KS_DEBUG
[2794]944 float minval, maxval;
[2836]945#endif
[2794]946#ifdef KS_DEBUG
947 minMax(minval, maxval, specmat);
948 cout << "Max/Min of input Matrix = (max: " << maxval << ", min: " << minval << ")" << endl;
949#endif
950
951 uInt ninsp = shiftvec.size();
952 outmat.resize(nchan_, ninsp*(ninsp-1)/2, 0.);
953 Matrix<Complex> fftspmat(nchan_/2+1, ninsp, 0.);
954 Vector<float> rvecref(nchan_, 0.);
955 Vector<Complex> cvecref(nchan_/2+1, 0.);
956 uInt icol = 0;
957 unsigned int nreject = 0;
958
959#ifdef KS_DEBUG
960 cout << "Starting initial FFT. The number of input spectra = " << ninsp << endl;
961 cout << "out matrix has ncolumn = " << outmat.ncolumn() << endl;
962#endif
963
964 for (uInt isp = 0 ; isp < ninsp ; isp++) {
965 rvecref.reference( specmat.column(isp) );
966 cvecref.reference( fftspmat.column(isp) );
967
968#ifdef KS_DEBUG
969 minMax(minval, maxval, rvecref);
970 cout << "Max/Min of inv FFTed Matrix = (max: " << maxval << ", min: " << minval << ")" << endl;
971#endif
972
973 fftsf.fft0(cvecref, rvecref, true);
974
975#ifdef KS_DEBUG
976 double maxr=cvecref[0].real(), minr=cvecref[0].real(),
977 maxi=cvecref[0].imag(), mini=cvecref[0].imag();
978 for (uInt i = 1; i<cvecref.size();i++){
979 maxr = max(maxr, cvecref[i].real());
980 maxi = max(maxi, cvecref[i].imag());
981 minr = min(minr, cvecref[i].real());
982 mini = min(mini, cvecref[i].imag());
983 }
984 cout << "Max/Min of inv FFTed Matrix (size=" << cvecref.size() << ") = (max: " << maxr << " + " << maxi << "j , min: " << minr << " + " << mini << "j)" << endl;
985#endif
986 }
987
988 //Liberate from reference
989 rvecref.unique();
990
991 Vector<Complex> cspec(nchan_/2+1, 0.);
992 const double PI = 6.0 * asin(0.5);
993 const double nchani = 1. / (float) nchan_;
994 const Complex trans(0., 1.);
995#ifdef KS_DEBUG
996 cout << "starting actual deconvolution" << endl;
997#endif
998 for (uInt j = 0 ; j < ninsp ; j++) {
999 for (uInt k = j+1 ; k < ninsp ; k++) {
1000 const double dx = (shiftvec[k] - shiftvec[j]) * 2. * PI * nchani;
1001
1002#ifdef KS_DEBUG
1003 cout << "icol = " << icol << endl;
1004#endif
1005
1006 for (uInt ichan = 0 ; ichan < cspec.size() ; ichan++){
1007 cspec[ichan] = ( fftspmat(ichan, j) + fftspmat(ichan, k) )*0.5;
1008 double phase = dx*ichan;
1009 if ( fabs( sin(phase) ) > threshold){
1010 cspec[ichan] += ( fftspmat(ichan, j) - fftspmat(ichan, k) ) * 0.5
1011 * trans * sin(phase) / ( 1. - cos(phase) );
1012 } else {
1013 nreject++;
1014 }
1015 } // end of channel loop
1016
1017#ifdef KS_DEBUG
1018 cout << "done calculation of cspec" << endl;
1019#endif
1020
1021 Vector<Float> rspec;
1022 rspec.reference( outmat.column(icol) );
1023
1024#ifdef KS_DEBUG
1025 cout << "Starting inverse FFT. icol = " << icol << endl;
1026 //cout << "- size of complex vector = " << cspec.size() << endl;
1027 double maxr=cspec[0].real(), minr=cspec[0].real(),
1028 maxi=cspec[0].imag(), mini=cspec[0].imag();
1029 for (uInt i = 1; i<cspec.size();i++){
1030 maxr = max(maxr, cspec[i].real());
1031 maxi = max(maxi, cspec[i].imag());
1032 minr = min(minr, cspec[i].real());
1033 mini = min(mini, cspec[i].imag());
1034 }
1035 cout << "Max/Min of conv vector (size=" << cspec.size() << ") = (max: " << maxr << " + " << maxi << "j , min: " << minr << " + " << mini << "j)" << endl;
1036#endif
1037
1038 fftsi.fft0(rspec, cspec, false);
1039
1040#ifdef KS_DEBUG
1041 //cout << "- size of inversed real vector = " << rspec.size() << endl;
1042 minMax(minval, maxval, rspec);
1043 cout << "Max/Min of inv FFTed Vector (size=" << rspec.size() << ") = (max: " << maxval << ", min: " << minval << ")" << endl;
1044 //cout << "Done inverse FFT. icol = " << icol << endl;
1045#endif
1046
1047 icol++;
1048 }
1049 }
1050
1051#ifdef KS_DEBUG
1052 minMax(minval, maxval, outmat);
1053 cout << "Max/Min of inv FFTed Matrix = (max: " << maxval << ", min: " << minval << ")" << endl;
1054#endif
1055
1056 os << "Threshold = " << threshold << ", Rejected channels = " << nreject << endl;
1057};
1058
1059
1060void STSideBandSep::aggregateMat(Matrix<float> &inmat,
1061 vector<float> &outvec)
1062{
1063 LogIO os(LogOrigin("STSideBandSep","aggregateMat()", WHERE));
1064 if (inmat.nrow() != nchan_)
1065 throw(AipsError("Internal error. The row numbers of input matrix differs from nchan_"));
1066// if (outvec.size() != nchan_)
1067// throw(AipsError("Internal error. The size of output vector should be equal to nchan_"));
1068
1069 os << "Averaging " << inmat.ncolumn() << " spectra in the input matrix."
1070 << LogIO::POST;
1071
1072 const uInt nspec = inmat.ncolumn();
1073 const double scale = 1./( (double) nspec );
1074 // initialize values with 0
1075 outvec.assign(nchan_, 0);
1076 for (uInt isp = 0 ; isp < nspec ; isp++) {
1077 for (uInt ich = 0 ; ich < nchan_ ; ich++) {
1078 outvec[ich] += inmat(ich, isp);
1079 }
1080 }
1081
1082 vector<float>::iterator iter;
1083 for (iter = outvec.begin(); iter != outvec.end(); iter++){
1084 *iter *= scale;
1085 }
1086};
1087
1088void STSideBandSep::subtractFromOther(const Matrix<float> &shiftmat,
1089 const vector<float> &invec,
1090 const vector<double> &shift,
1091 vector<float> &outvec)
1092{
1093 LogIO os(LogOrigin("STSideBandSep","subtractFromOther()", WHERE));
1094 if (shiftmat.nrow() != nchan_)
1095 throw(AipsError("Internal error. The row numbers of input matrix differs from nchan_"));
1096 if (invec.size() != nchan_)
1097 throw(AipsError("Internal error. The length of input vector should be nchan_"));
1098 if (shift.size() != shiftmat.ncolumn())
1099 throw(AipsError("Internal error. The column numbers of input matrix != the number of elements in shift"));
1100
1101 const uInt nspec = shiftmat.ncolumn();
1102 Vector<float> subsp(nchan_, 0.), shiftsub;
1103 Matrix<float> submat(nchan_, nspec, 0.);
1104 vector<float>::iterator iter;
1105 for (uInt isp = 0 ; isp < nspec ; isp++) {
1106 for (uInt ich = 0; ich < nchan_ ; ich++) {
1107 subsp(ich) = shiftmat(ich, isp) - invec[ich];
1108 }
1109 shiftsub.reference(submat.column(isp));
1110 shiftSpectrum(subsp, shift[isp], shiftsub);
1111 }
1112
1113 aggregateMat(submat, outvec);
1114};
1115
1116
1117void STSideBandSep::setLO1(const string lo1, const string frame,
[2726]1118 const double reftime, const string refdir)
[2707]1119{
[2794]1120 Quantum<Double> qfreq;
1121 readQuantity(qfreq, String(lo1));
1122 lo1Freq_ = qfreq.getValue("Hz");
[2707]1123 MFrequency::getType(loFrame_, frame);
1124 loTime_ = reftime;
1125 loDir_ = refdir;
1126
1127#ifdef KS_DEBUG
1128 cout << "STSideBandSep::setLO1" << endl;
1129 if (lo1Freq_ > 0.)
1130 cout << "lo1 = " << lo1Freq_ << " [Hz] (" << frame << ")" << endl;
1131 if (loTime_ > 0.)
1132 cout << "ref time = " << loTime_ << " [day]" << endl;
1133 if (!loDir_.empty())
1134 cout << "ref direction = " << loDir_ << " [day]" << endl;
1135#endif
1136};
1137
[2711]1138void STSideBandSep::setLO1Root(string name)
[2707]1139{
[2711]1140 LogIO os(LogOrigin("STSideBandSep","setLO1Root()", WHERE));
1141 os << "Searching for '" << name << "'..." << LogIO::POST;
1142 // Check for existance of the file
1143 if (!checkFile(name)) {
[2707]1144 throw(AipsError("File does not exist"));
1145 }
[2711]1146 if (name[(name.size()-1)] == '/')
1147 name = name.substr(0,(name.size()-2));
[2707]1148
[2711]1149 if (checkFile(name+"/Receiver.xml", "file") &&
1150 checkFile(name+"/SpectralWindow.xml", "file")){
1151 os << "Found '" << name << "/Receiver.xml' ... got an ASDM name." << LogIO::POST;
1152 asdmName_ = name;
1153 } else if (checkFile(name+"/ASDM_RECEIVER") &&
1154 checkFile(name+"/ASDM_SPECTRALWINDOW")){
1155 os << "Found '" << name << "/ASDM_RECEIVER' ... got a Table name." << LogIO::POST;
1156 asisName_ = name;
1157 } else {
1158 throw(AipsError("Invalid file name. Set an MS or ASDM name."));
1159 }
[2707]1160
1161#ifdef KS_DEBUG
[2711]1162 cout << "STSideBandSep::setLO1Root" << endl;
1163 if (!asdmName_.empty())
1164 cout << "asdm name = " << asdmName_ << endl;
1165 if (!asisName_.empty())
1166 cout << "MS name = " << asisName_ << endl;
[2707]1167#endif
1168};
1169
[2712]1170
[2794]1171void STSideBandSep::solveImageFrequency()
[2707]1172{
1173 LogIO os(LogOrigin("STSideBandSep","solveImageFreqency()", WHERE));
1174 os << "Start calculating frequencies of image side band" << LogIO::POST;
1175
1176 if (imgTab_p.null())
1177 throw AipsError("STSideBandSep::solveImageFreqency - an image side band scantable should be set first");
1178
[2711]1179 // Convert frequency REFVAL to the value in frame of LO.
[2707]1180 // The code assumes that imgTab_p has only an IF and only a FREQ_ID
1181 // is associated to an IFNO
1182 // TODO: More complete Procedure would be
1183 // 1. Get freq IDs associated to sigIfno_
1184 // 2. Get freq information of the freq IDs
1185 // 3. For each freqIDs, get freq infromation in TOPO and an LO1
1186 // frequency and calculate image band frequencies.
1187 STFrequencies freqTab_ = imgTab_p->frequencies();
1188 // get the base frame of table
1189 const MFrequency::Types tabframe = freqTab_.getFrame(true);
1190 TableVector<uInt> freqIdVec( imgTab_p->table(), "FREQ_ID" );
1191 // assuming single freqID per IFNO
1192 uInt freqid = freqIdVec(0);
[2711]1193 int nChan = imgTab_p->nchan(imgTab_p->getIF(0));
[2707]1194 double refpix, refval, increment ;
1195 freqTab_.getEntry(refpix, refval, increment, freqid);
1196 //MFrequency sigrefval = MFrequency(MVFrequency(refval),tabframe);
1197 // get freq infromation of sigIfno_ in loFrame_
1198 const MPosition mp = imgTab_p->getAntennaPosition();
1199 MEpoch me;
1200 MDirection md;
1201 if (loTime_ < 0.)
1202 me = imgTab_p->getEpoch(-1);
1203 else
1204 me = MEpoch(MVEpoch(loTime_));
1205 if (loDir_.empty()) {
1206 ArrayColumn<Double> srcdirCol_;
1207 srcdirCol_.attach(imgTab_p->table(), "SRCDIRECTION");
1208 // Assuming J2000 and SRCDIRECTION in unit of rad
1209 Quantum<Double> srcra = Quantum<Double>(srcdirCol_(0)(IPosition(1,0)), "rad");
1210 Quantum<Double> srcdec = Quantum<Double>(srcdirCol_(0)(IPosition(1,1)), "rad");
1211 md = MDirection(srcra, srcdec, MDirection::J2000);
1212 //imgTab_p->getDirection(0);
1213 } else {
1214 // parse direction string
1215 string::size_type pos0 = loDir_.find(" ");
1216
1217 if (pos0 == string::npos) {
1218 throw AipsError("bad string format in LO1 direction");
1219 }
1220 string::size_type pos1 = loDir_.find(" ", pos0+1);
1221 String sepoch, sra, sdec;
1222 if (pos1 != string::npos) {
1223 sepoch = loDir_.substr(0, pos0);
1224 sra = loDir_.substr(pos0+1, pos1-pos0);
1225 sdec = loDir_.substr(pos1+1);
1226 }
1227 MDirection::Types epoch;
1228 MDirection::getType(epoch, sepoch);
1229 QuantumHolder qh ;
1230 String err ;
1231 qh.fromString( err, sra);
1232 Quantum<Double> ra = qh.asQuantumDouble() ;
1233 qh.fromString( err, sdec ) ;
1234 Quantum<Double> dec = qh.asQuantumDouble() ;
[2716]1235 //md = MDirection(ra.getValue("rad"), dec.getValue("rad"),epoch);
1236 md = MDirection(ra, dec, epoch);
[2707]1237 }
1238 MeasFrame mframe( me, mp, md );
[2709]1239 MFrequency::Convert tobframe(loFrame_, MFrequency::Ref(tabframe, mframe));
1240 MFrequency::Convert toloframe(tabframe, MFrequency::Ref(loFrame_, mframe));
[2711]1241 // Convert refval to loFrame_
[2707]1242 double sigrefval;
1243 if (tabframe == loFrame_)
1244 sigrefval = refval;
1245 else
1246 sigrefval = toloframe(Quantum<Double>(refval, "Hz")).get("Hz").getValue();
1247
[2711]1248 // Check for the availability of LO1
1249 if (lo1Freq_ > 0.) {
1250 os << "Using user defined LO1 frequency." << LogIO::POST;
1251 } else if (!asisName_.empty()) {
1252 // MS name is set.
1253 os << "Using user defined MS (asis): " << asisName_ << LogIO::POST;
1254 if (!getLo1FromAsisTab(asisName_, sigrefval, refpix, increment, nChan)) {
1255 throw AipsError("Failed to get LO1 frequency from MS");
1256 }
1257 } else if (!asdmName_.empty()) {
1258 // ASDM name is set.
1259 os << "Using user defined ASDM: " << asdmName_ << LogIO::POST;
1260 if (!getLo1FromAsdm(asdmName_, sigrefval, refpix, increment, nChan)) {
1261 throw AipsError("Failed to get LO1 frequency from ASDM");
1262 }
1263 } else {
1264 // Try getting ASDM name from scantable header
1265 os << "Try getting information from scantable header" << LogIO::POST;
[2794]1266 if (!getLo1FromScanTab(tableList_[0], sigrefval, refpix, increment, nChan)) {
[2711]1267 //throw AipsError("Failed to get LO1 frequency from asis table");
1268 os << LogIO::WARN << "Failed to get LO1 frequency using information in scantable." << LogIO::POST;
1269 os << LogIO::WARN << "Could not fill frequency information of IMAGE sideband properly." << LogIO::POST;
1270 os << LogIO::WARN << "Storing values of SIGNAL sideband in FREQUENCIES table" << LogIO::POST;
1271 return;
1272 }
1273 }
[2794]1274
[2711]1275 // LO1 should now be ready.
1276 if (lo1Freq_ < 0.)
1277 throw(AipsError("Got negative LO1 Frequency"));
1278
[2794]1279 // Print summary
1280 {
1281 // LO1
1282 Vector<Double> dirvec = md.getAngle(Unit(String("rad"))).getValue();
1283 os << "[LO1 settings]" << LogIO::POST;
1284 os << "- Frequency: " << lo1Freq_ << " [Hz] ("
1285 << MFrequency::showType(loFrame_) << ")" << LogIO::POST;
1286 os << "- Reference time: " << me.get(Unit(String("d"))).getValue()
1287 << " [day]" << LogIO::POST;
1288 os << "- Reference direction: [" << dirvec[0] << ", " << dirvec[1]
1289 << "] (" << md.getRefString() << ") " << LogIO::POST;
[2711]1290
[2794]1291 // signal sideband
1292 os << "[Signal side band]" << LogIO::POST;
1293 os << "- IFNO: " << imgTab_p->getIF(0) << " (FREQ_ID = " << freqid << ")"
1294 << LogIO::POST;
1295 os << "- Reference value: " << refval << " [Hz] ("
1296 << MFrequency::showType(tabframe) << ") = "
1297 << sigrefval << " [Hz] (" << MFrequency::showType(loFrame_)
1298 << ")" << LogIO::POST;
1299 os << "- Reference pixel: " << refpix << LogIO::POST;
1300 os << "- Increment: " << increment << " [Hz]" << LogIO::POST;
1301 }
[2711]1302
1303 // Calculate image band incr and refval in loFrame_
[2707]1304 Double imgincr = -increment;
1305 Double imgrefval = 2 * lo1Freq_ - sigrefval;
1306 Double imgrefval_tab = imgrefval;
[2711]1307 // Convert imgrefval back to table base frame
[2707]1308 if (tabframe != loFrame_)
1309 imgrefval = tobframe(Quantum<Double>(imgrefval, "Hz")).get("Hz").getValue();
[2711]1310 // Set new frequencies table
[2707]1311 uInt fIDnew = freqTab_.addEntry(refpix, imgrefval, imgincr);
[2711]1312 // Update FREQ_ID in table.
[2707]1313 freqIdVec = fIDnew;
[2711]1314
[2794]1315 // Print summary (Image sideband)
1316 {
1317 os << "[Image side band]" << LogIO::POST;
1318 os << "- IFNO: " << imgTab_p->getIF(0) << " (FREQ_ID = " << freqIdVec(0)
1319 << ")" << LogIO::POST;
1320 os << "- Reference value: " << imgrefval << " [Hz] ("
1321 << MFrequency::showType(tabframe) << ") = "
1322 << imgrefval_tab << " [Hz] (" << MFrequency::showType(loFrame_)
1323 << ")" << LogIO::POST;
1324 os << "- Reference pixel: " << refpix << LogIO::POST;
1325 os << "- Increment: " << imgincr << " [Hz]" << LogIO::POST;
1326 }
[2707]1327};
1328
1329Bool STSideBandSep::checkFile(const string name, string type)
1330{
1331 File file(name);
1332 if (!file.exists()){
1333 return false;
1334 } else if (type.empty()) {
1335 return true;
1336 } else {
1337 // Check for file type
1338 switch (tolower(type[0])) {
1339 case 'f':
1340 return file.isRegular(True);
1341 case 'd':
1342 return file.isDirectory(True);
1343 case 's':
1344 return file.isSymLink();
1345 default:
1346 throw AipsError("Invalid file type. Available types are 'file', 'directory', and 'symlink'.");
1347 }
1348 }
1349};
1350
[2711]1351bool STSideBandSep::getLo1FromAsdm(const string asdmname,
[2836]1352 const double /*refval*/,
1353 const double /*refpix*/,
1354 const double /*increment*/,
1355 const int /*nChan*/)
[2707]1356{
1357 // Check for relevant tables.
1358 string spwname = asdmname + "/SpectralWindow.xml";
1359 string recname = asdmname + "/Receiver.xml";
1360 if (!checkFile(spwname) || !checkFile(recname)) {
1361 throw(AipsError("Could not find subtables in ASDM"));
1362 }
1363
1364 return false;
1365
1366};
1367
1368
[2711]1369bool STSideBandSep::getLo1FromScanTab(CountedPtr< Scantable > &scantab,
1370 const double refval,
1371 const double refpix,
1372 const double increment,
1373 const int nChan)
[2707]1374{
[2711]1375 LogIO os(LogOrigin("STSideBandSep","getLo1FromScanTab()", WHERE));
[2707]1376 // Check for relevant tables.
[2712]1377 const TableRecord &rec = scantab->table().keywordSet() ;
[2711]1378 String spwname, recname;
[2712]1379 if (rec.isDefined("ASDM_SPECTRALWINDOW") && rec.isDefined("ASDM_RECEIVER")){
1380 spwname = rec.asString("ASDM_SPECTRALWINDOW");
1381 recname = rec.asString("ASDM_RECEIVER");
1382 }
1383 else {
[2711]1384 // keywords are not there
1385 os << LogIO::WARN
1386 << "Could not find necessary table names in scantable header."
1387 << LogIO::POST;
1388 return false;
1389 }
[2707]1390 if (!checkFile(spwname,"directory") || !checkFile(recname,"directory")) {
[2711]1391 throw(AipsError("Could not find relevant subtables in MS"));
[2707]1392 }
[2711]1393 // Get root MS name
1394 string msname;
1395 const String recsuff = "/ASDM_RECEIVER";
1396 String::size_type pos;
[2712]1397 pos = recname.size()-recsuff.size();
[2711]1398 if (recname.substr(pos) == recsuff)
[2712]1399 msname = recname.substr(0, pos);
[2711]1400 else
1401 throw(AipsError("Internal error in parsing table name from a scantable keyword."));
[2707]1402
[2711]1403 if (!checkFile(msname))
1404 throw(AipsError("Internal error in parsing MS name from a scantable keyword."));
[2707]1405
[2711]1406 return getLo1FromAsisTab(msname, refval, refpix, increment, nChan);
1407
[2707]1408};
1409
[2711]1410bool STSideBandSep::getLo1FromAsisTab(const string msname,
1411 const double refval,
1412 const double refpix,
1413 const double increment,
1414 const int nChan)
1415{
1416 LogIO os(LogOrigin("STSideBandSep","getLo1FromAsisTab()", WHERE));
1417 os << "Searching an LO1 frequency in '" << msname << "'" << LogIO::POST;
1418 // Check for relevant tables.
1419 const string spwname = msname + "/ASDM_SPECTRALWINDOW";
1420 const string recname = msname + "/ASDM_RECEIVER";
1421 if (!checkFile(spwname,"directory") || !checkFile(recname,"directory")) {
1422 throw(AipsError("Could not find relevant tables in MS"));
1423 }
[2707]1424
[2711]1425 Table spwtab_ = Table(spwname);
1426 String asdmSpw;
1427 ROTableRow spwrow(spwtab_);
1428 const Double rtol = 0.01;
1429 for (uInt idx = 0; idx < spwtab_.nrow(); idx++){
1430 const TableRecord& rec = spwrow.get(idx);
1431 // Compare nchan
1432 if (rec.asInt("numChan") != (Int) nChan)
1433 continue;
1434 // Compare increment
1435 Double asdminc;
1436 Array<Double> incarr = rec.asArrayDouble("chanWidthArray");
1437 if (incarr.size() > 0)
1438 asdminc = incarr(IPosition(1, (uInt) refpix));
1439 else
1440 asdminc = rec.asDouble("chanWidth");
1441 if (abs(asdminc - abs(increment)) > rtol * abs(increment))
1442 continue;
1443 // Compare refval
1444 Double asdmrefv;
1445 Array<Double> refvarr = rec.asArrayDouble("chanFreqArray");
1446 if (refvarr.size() > 0){
1447 const uInt iref = (uInt) refpix;
1448 const Double ratio = refpix - (Double) iref;
1449 asdmrefv = refvarr(IPosition(1, iref))*(1.-ratio)
1450 + refvarr(IPosition(1,iref+1))*ratio;
1451 }
1452 else {
1453 const Double ch0 = rec.asDouble("chanFreqStart");
1454 const Double chstep = rec.asDouble("chanFreqStep");
1455 asdmrefv = ch0 + chstep * refpix;
1456 }
1457 if (abs(asdmrefv - refval) < 0.5*abs(asdminc)){
1458 asdmSpw = rec.asString("spectralWindowId");
1459 break;
1460 }
1461 }
1462
1463 if (asdmSpw.empty()){
1464 os << LogIO::WARN << "Could not find relevant SPW ID in " << spwname << LogIO::POST;
1465 return false;
1466 }
1467 else {
1468 os << asdmSpw << " in " << spwname
1469 << " matches the freqeuncies of signal side band." << LogIO::POST;
1470 }
1471
1472 Table rectab_ = Table(recname);
1473 ROTableRow recrow(rectab_);
1474 for (uInt idx = 0; idx < rectab_.nrow(); idx++){
1475 const TableRecord& rec = recrow.get(idx);
1476 if (rec.asString("spectralWindowId") == asdmSpw){
1477 const Array<Double> loarr = rec.asArrayDouble("freqLO");
1478 lo1Freq_ = loarr(IPosition(1,0));
1479 os << "Found LO1 Frequency in " << recname << ": "
1480 << lo1Freq_ << " [Hz]" << LogIO::POST;
1481 return true;
1482 }
1483 }
1484 os << LogIO::WARN << "Could not find " << asdmSpw << " in " << recname
1485 << LogIO::POST;
1486 return false;
1487};
1488
[2707]1489} //namespace asap
Note: See TracBrowser for help on using the repository browser.