source: trunk/src/STSideBandSep.cpp@ 2864

Last change on this file since 2864 was 2864, checked in by Kana Sugimoto, 12 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): asap.sbseparator

Description: Fixed a bug which occurs when getbothside=False.


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