source: trunk/src/STSideBandSep.cpp@ 2721

Last change on this file since 2721 was 2716, 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): sbseparator

Description: a bug fix in STSideBandSep::solveImageFreqency()


File size: 14.7 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 "STSideBandSep.h"
29
30using namespace std ;
31using namespace casa ;
32using namespace asap ;
33
34//#ifndef KS_DEBUG
35//#define KS_DEBUG
36//#endif
37
38namespace asap {
39
40// constructors
41STSideBandSep::STSideBandSep()
42 : sigIfno_(0), ftol_(-1),
43 loTime_(-1), lo1Freq_(-1), loDir_("")
44{
45#ifdef KS_DEBUG
46 cout << "Default constructor STSideBandSep()" << endl;
47#endif
48 // Default LO frame is TOPO
49 loFrame_ = MFrequency::TOPO;
50};
51
52STSideBandSep::~STSideBandSep()
53{
54#ifdef KS_DEBUG
55 cout << "Destructor ~STSideBandSep()" << endl;
56#endif
57};
58
59
60void STSideBandSep::setFrequency(const unsigned int ifno, const double freqtol, string frame)
61{
62#ifdef KS_DEBUG
63 cout << "STSideBandSep::setFrequency" << endl;
64 cout << "IFNO = " << ifno << endl;
65 cout << "freq tol = " << freqtol << " [Hz]" << endl;
66 cout << "frame = " << frame << endl;
67#endif
68};
69
70// Temporal function to set scantable of image sideband
71void STSideBandSep::setImageTable(const ScantableWrapper &s)
72{
73#ifdef KS_DEBUG
74 cout << "STSideBandSep::setImageTable" << endl;
75 cout << "got image table nrow = " << s.nrow() << endl;
76#endif
77 imgTab_p = s.getCP();
78 AlwaysAssert(!imgTab_p.null(),AipsError);
79
80};
81
82//
83void STSideBandSep::setLO1(const double lo1, string frame, double reftime, string refdir)
84{
85 lo1Freq_ = lo1;
86 MFrequency::getType(loFrame_, frame);
87 loTime_ = reftime;
88 loDir_ = refdir;
89
90#ifdef KS_DEBUG
91 cout << "STSideBandSep::setLO1" << endl;
92 if (lo1Freq_ > 0.)
93 cout << "lo1 = " << lo1Freq_ << " [Hz] (" << frame << ")" << endl;
94 if (loTime_ > 0.)
95 cout << "ref time = " << loTime_ << " [day]" << endl;
96 if (!loDir_.empty())
97 cout << "ref direction = " << loDir_ << " [day]" << endl;
98#endif
99};
100
101void STSideBandSep::setLO1Root(string name)
102{
103 LogIO os(LogOrigin("STSideBandSep","setLO1Root()", WHERE));
104 os << "Searching for '" << name << "'..." << LogIO::POST;
105 // Check for existance of the file
106 if (!checkFile(name)) {
107 throw(AipsError("File does not exist"));
108 }
109 if (name[(name.size()-1)] == '/')
110 name = name.substr(0,(name.size()-2));
111
112 if (checkFile(name+"/Receiver.xml", "file") &&
113 checkFile(name+"/SpectralWindow.xml", "file")){
114 os << "Found '" << name << "/Receiver.xml' ... got an ASDM name." << LogIO::POST;
115 asdmName_ = name;
116 } else if (checkFile(name+"/ASDM_RECEIVER") &&
117 checkFile(name+"/ASDM_SPECTRALWINDOW")){
118 os << "Found '" << name << "/ASDM_RECEIVER' ... got a Table name." << LogIO::POST;
119 asisName_ = name;
120 } else {
121 throw(AipsError("Invalid file name. Set an MS or ASDM name."));
122 }
123
124#ifdef KS_DEBUG
125 cout << "STSideBandSep::setLO1Root" << endl;
126 if (!asdmName_.empty())
127 cout << "asdm name = " << asdmName_ << endl;
128 if (!asisName_.empty())
129 cout << "MS name = " << asisName_ << endl;
130#endif
131};
132
133///// TEMPORAL FUNCTION!!! /////
134void STSideBandSep::setScanTb0(const ScantableWrapper &s){
135 st0_ = s.getCP();
136};
137////////////////////////////////
138
139void STSideBandSep::solveImageFreqency()
140{
141#ifdef KS_DEBUG
142 cout << "STSideBandSep::solveImageFrequency" << endl;
143#endif
144 LogIO os(LogOrigin("STSideBandSep","solveImageFreqency()", WHERE));
145 os << "Start calculating frequencies of image side band" << LogIO::POST;
146
147 if (imgTab_p.null())
148 throw AipsError("STSideBandSep::solveImageFreqency - an image side band scantable should be set first");
149
150 // Convert frequency REFVAL to the value in frame of LO.
151 // The code assumes that imgTab_p has only an IF and only a FREQ_ID
152 // is associated to an IFNO
153 // TODO: More complete Procedure would be
154 // 1. Get freq IDs associated to sigIfno_
155 // 2. Get freq information of the freq IDs
156 // 3. For each freqIDs, get freq infromation in TOPO and an LO1
157 // frequency and calculate image band frequencies.
158 STFrequencies freqTab_ = imgTab_p->frequencies();
159 // get the base frame of table
160 const MFrequency::Types tabframe = freqTab_.getFrame(true);
161 TableVector<uInt> freqIdVec( imgTab_p->table(), "FREQ_ID" );
162 // assuming single freqID per IFNO
163 uInt freqid = freqIdVec(0);
164 int nChan = imgTab_p->nchan(imgTab_p->getIF(0));
165 double refpix, refval, increment ;
166 freqTab_.getEntry(refpix, refval, increment, freqid);
167 //MFrequency sigrefval = MFrequency(MVFrequency(refval),tabframe);
168 // get freq infromation of sigIfno_ in loFrame_
169 const MPosition mp = imgTab_p->getAntennaPosition();
170 MEpoch me;
171 MDirection md;
172 if (loTime_ < 0.)
173 me = imgTab_p->getEpoch(-1);
174 else
175 me = MEpoch(MVEpoch(loTime_));
176 if (loDir_.empty()) {
177 ArrayColumn<Double> srcdirCol_;
178 srcdirCol_.attach(imgTab_p->table(), "SRCDIRECTION");
179 // Assuming J2000 and SRCDIRECTION in unit of rad
180 Quantum<Double> srcra = Quantum<Double>(srcdirCol_(0)(IPosition(1,0)), "rad");
181 Quantum<Double> srcdec = Quantum<Double>(srcdirCol_(0)(IPosition(1,1)), "rad");
182 md = MDirection(srcra, srcdec, MDirection::J2000);
183 //imgTab_p->getDirection(0);
184 } else {
185 // parse direction string
186 string::size_type pos0 = loDir_.find(" ");
187
188 if (pos0 == string::npos) {
189 throw AipsError("bad string format in LO1 direction");
190 }
191 string::size_type pos1 = loDir_.find(" ", pos0+1);
192 String sepoch, sra, sdec;
193 if (pos1 != string::npos) {
194 sepoch = loDir_.substr(0, pos0);
195 sra = loDir_.substr(pos0+1, pos1-pos0);
196 sdec = loDir_.substr(pos1+1);
197 }
198 MDirection::Types epoch;
199 MDirection::getType(epoch, sepoch);
200 QuantumHolder qh ;
201 String err ;
202 qh.fromString( err, sra);
203 Quantum<Double> ra = qh.asQuantumDouble() ;
204 qh.fromString( err, sdec ) ;
205 Quantum<Double> dec = qh.asQuantumDouble() ;
206 //md = MDirection(ra.getValue("rad"), dec.getValue("rad"),epoch);
207 md = MDirection(ra, dec, epoch);
208 }
209 MeasFrame mframe( me, mp, md );
210 MFrequency::Convert tobframe(loFrame_, MFrequency::Ref(tabframe, mframe));
211 MFrequency::Convert toloframe(tabframe, MFrequency::Ref(loFrame_, mframe));
212 // Convert refval to loFrame_
213 double sigrefval;
214 if (tabframe == loFrame_)
215 sigrefval = refval;
216 else
217 sigrefval = toloframe(Quantum<Double>(refval, "Hz")).get("Hz").getValue();
218
219
220 // Check for the availability of LO1
221 if (lo1Freq_ > 0.) {
222 os << "Using user defined LO1 frequency." << LogIO::POST;
223 } else if (!asisName_.empty()) {
224 // MS name is set.
225 os << "Using user defined MS (asis): " << asisName_ << LogIO::POST;
226 if (!getLo1FromAsisTab(asisName_, sigrefval, refpix, increment, nChan)) {
227 throw AipsError("Failed to get LO1 frequency from MS");
228 }
229 } else if (!asdmName_.empty()) {
230 // ASDM name is set.
231 os << "Using user defined ASDM: " << asdmName_ << LogIO::POST;
232 if (!getLo1FromAsdm(asdmName_, sigrefval, refpix, increment, nChan)) {
233 throw AipsError("Failed to get LO1 frequency from ASDM");
234 }
235 } else {
236 // Try getting ASDM name from scantable header
237 os << "Try getting information from scantable header" << LogIO::POST;
238 if (!getLo1FromScanTab(st0_, sigrefval, refpix, increment, nChan)) {
239 //throw AipsError("Failed to get LO1 frequency from asis table");
240 os << LogIO::WARN << "Failed to get LO1 frequency using information in scantable." << LogIO::POST;
241 os << LogIO::WARN << "Could not fill frequency information of IMAGE sideband properly." << LogIO::POST;
242 os << LogIO::WARN << "Storing values of SIGNAL sideband in FREQUENCIES table" << LogIO::POST;
243 return;
244 }
245 }
246 // LO1 should now be ready.
247 if (lo1Freq_ < 0.)
248 throw(AipsError("Got negative LO1 Frequency"));
249
250 // Print summary (LO1)
251 Vector<Double> dirvec = md.getAngle(Unit(String("rad"))).getValue();
252 os << "[LO1 settings]" << LogIO::POST;
253 os << "- Frequency: " << lo1Freq_ << " [Hz] ("
254 << MFrequency::showType(loFrame_) << ")" << LogIO::POST;
255 os << "- Reference time: " << me.get(Unit(String("d"))).getValue()
256 << " [day]" << LogIO::POST;
257 os << "- Reference direction: [" << dirvec[0] << ", " << dirvec[1]
258 << "] (" << md.getRefString() << ") " << LogIO::POST;
259
260 //Print summary (signal)
261 os << "[Signal side band]" << LogIO::POST;
262 os << "- IFNO: " << imgTab_p->getIF(0) << " (FREQ_ID = " << freqid << ")"
263 << LogIO::POST;
264 os << "- Reference value: " << refval << " [Hz] ("
265 << MFrequency::showType(tabframe) << ") = "
266 << sigrefval << " [Hz] (" << MFrequency::showType(loFrame_)
267 << ")" << LogIO::POST;
268 os << "- Reference pixel: " << refpix << LogIO::POST;
269 os << "- Increment: " << increment << " [Hz]" << LogIO::POST;
270
271 // Calculate image band incr and refval in loFrame_
272 Double imgincr = -increment;
273 Double imgrefval = 2 * lo1Freq_ - sigrefval;
274 Double imgrefval_tab = imgrefval;
275 // Convert imgrefval back to table base frame
276 if (tabframe != loFrame_)
277 imgrefval = tobframe(Quantum<Double>(imgrefval, "Hz")).get("Hz").getValue();
278 // Set new frequencies table
279 uInt fIDnew = freqTab_.addEntry(refpix, imgrefval, imgincr);
280 // Update FREQ_ID in table.
281 freqIdVec = fIDnew;
282
283 // Print summary (Image side band)
284 os << "[Image side band]" << LogIO::POST;
285 os << "- IFNO: " << imgTab_p->getIF(0) << " (FREQ_ID = " << freqIdVec(0)
286 << ")" << LogIO::POST;
287 os << "- Reference value: " << imgrefval << " [Hz] ("
288 << MFrequency::showType(tabframe) << ") = "
289 << imgrefval_tab << " [Hz] (" << MFrequency::showType(loFrame_)
290 << ")" << LogIO::POST;
291 os << "- Reference pixel: " << refpix << LogIO::POST;
292 os << "- Increment: " << imgincr << " [Hz]" << LogIO::POST;
293};
294
295Bool STSideBandSep::checkFile(const string name, string type)
296{
297 File file(name);
298 if (!file.exists()){
299 return false;
300 } else if (type.empty()) {
301 return true;
302 } else {
303 // Check for file type
304 switch (tolower(type[0])) {
305 case 'f':
306 return file.isRegular(True);
307 case 'd':
308 return file.isDirectory(True);
309 case 's':
310 return file.isSymLink();
311 default:
312 throw AipsError("Invalid file type. Available types are 'file', 'directory', and 'symlink'.");
313 }
314 }
315};
316
317bool STSideBandSep::getLo1FromAsdm(const string asdmname,
318 const double refval,
319 const double refpix,
320 const double increment,
321 const int nChan)
322{
323 // Check for relevant tables.
324 string spwname = asdmname + "/SpectralWindow.xml";
325 string recname = asdmname + "/Receiver.xml";
326 if (!checkFile(spwname) || !checkFile(recname)) {
327 throw(AipsError("Could not find subtables in ASDM"));
328 }
329
330 return false;
331
332};
333
334
335bool STSideBandSep::getLo1FromScanTab(CountedPtr< Scantable > &scantab,
336 const double refval,
337 const double refpix,
338 const double increment,
339 const int nChan)
340{
341 LogIO os(LogOrigin("STSideBandSep","getLo1FromScanTab()", WHERE));
342 // Check for relevant tables.
343 const TableRecord &rec = scantab->table().keywordSet() ;
344 String spwname, recname;
345 if (rec.isDefined("ASDM_SPECTRALWINDOW") && rec.isDefined("ASDM_RECEIVER")){
346 spwname = rec.asString("ASDM_SPECTRALWINDOW");
347 recname = rec.asString("ASDM_RECEIVER");
348 }
349 else {
350 // keywords are not there
351 os << LogIO::WARN
352 << "Could not find necessary table names in scantable header."
353 << LogIO::POST;
354 return false;
355 }
356 if (!checkFile(spwname,"directory") || !checkFile(recname,"directory")) {
357 throw(AipsError("Could not find relevant subtables in MS"));
358 }
359 // Get root MS name
360 string msname;
361 const String recsuff = "/ASDM_RECEIVER";
362 String::size_type pos;
363 pos = recname.size()-recsuff.size();
364 if (recname.substr(pos) == recsuff)
365 msname = recname.substr(0, pos);
366 else
367 throw(AipsError("Internal error in parsing table name from a scantable keyword."));
368
369 if (!checkFile(msname))
370 throw(AipsError("Internal error in parsing MS name from a scantable keyword."));
371
372 return getLo1FromAsisTab(msname, refval, refpix, increment, nChan);
373
374};
375
376bool STSideBandSep::getLo1FromAsisTab(const string msname,
377 const double refval,
378 const double refpix,
379 const double increment,
380 const int nChan)
381{
382 LogIO os(LogOrigin("STSideBandSep","getLo1FromAsisTab()", WHERE));
383 os << "Searching an LO1 frequency in '" << msname << "'" << LogIO::POST;
384 // Check for relevant tables.
385 const string spwname = msname + "/ASDM_SPECTRALWINDOW";
386 const string recname = msname + "/ASDM_RECEIVER";
387 if (!checkFile(spwname,"directory") || !checkFile(recname,"directory")) {
388 throw(AipsError("Could not find relevant tables in MS"));
389 }
390
391 Table spwtab_ = Table(spwname);
392 String asdmSpw;
393 ROTableRow spwrow(spwtab_);
394 const Double rtol = 0.01;
395 for (uInt idx = 0; idx < spwtab_.nrow(); idx++){
396 const TableRecord& rec = spwrow.get(idx);
397 // Compare nchan
398 if (rec.asInt("numChan") != (Int) nChan)
399 continue;
400 // Compare increment
401 Double asdminc;
402 Array<Double> incarr = rec.asArrayDouble("chanWidthArray");
403 if (incarr.size() > 0)
404 asdminc = incarr(IPosition(1, (uInt) refpix));
405 else
406 asdminc = rec.asDouble("chanWidth");
407 if (abs(asdminc - abs(increment)) > rtol * abs(increment))
408 continue;
409 // Compare refval
410 Double asdmrefv;
411 Array<Double> refvarr = rec.asArrayDouble("chanFreqArray");
412 if (refvarr.size() > 0){
413 const uInt iref = (uInt) refpix;
414 const Double ratio = refpix - (Double) iref;
415 asdmrefv = refvarr(IPosition(1, iref))*(1.-ratio)
416 + refvarr(IPosition(1,iref+1))*ratio;
417 }
418 else {
419 const Double ch0 = rec.asDouble("chanFreqStart");
420 const Double chstep = rec.asDouble("chanFreqStep");
421 asdmrefv = ch0 + chstep * refpix;
422 }
423 if (abs(asdmrefv - refval) < 0.5*abs(asdminc)){
424 asdmSpw = rec.asString("spectralWindowId");
425 break;
426 }
427 }
428
429 if (asdmSpw.empty()){
430 os << LogIO::WARN << "Could not find relevant SPW ID in " << spwname << LogIO::POST;
431 return false;
432 }
433 else {
434 os << asdmSpw << " in " << spwname
435 << " matches the freqeuncies of signal side band." << LogIO::POST;
436 }
437
438 Table rectab_ = Table(recname);
439 ROTableRow recrow(rectab_);
440 for (uInt idx = 0; idx < rectab_.nrow(); idx++){
441 const TableRecord& rec = recrow.get(idx);
442 if (rec.asString("spectralWindowId") == asdmSpw){
443 const Array<Double> loarr = rec.asArrayDouble("freqLO");
444 lo1Freq_ = loarr(IPosition(1,0));
445 os << "Found LO1 Frequency in " << recname << ": "
446 << lo1Freq_ << " [Hz]" << LogIO::POST;
447 return true;
448 }
449 }
450 os << LogIO::WARN << "Could not find " << asdmSpw << " in " << recname
451 << LogIO::POST;
452 return false;
453};
454
455// String STSideBandSep::()
456// {
457
458// };
459
460} //namespace asap
Note: See TracBrowser for help on using the repository browser.