source: trunk/src/STSideBandSep.cpp @ 2711

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

New Development: No

JIRA Issue: Yes (CAS-4141/CSV-1526)

Ready for Test: Yes

Interface Changes: Yes

What Interface Changed: Added asap.sbseparator.set_lo1root() = SBSeparator::set_lo1root(),

and STSideBandSep::setLO1Root()

Test Programs:

Put in Release Notes: No

Module(s): sbseparator and STSideBandSep

Description:

Added a new python method asap.sbseparator.set_lo1root() to set MS
name to search for LO1 frequency.
Underlying c++ functions are SBSeparator::set_lo1root (interface) and STSideBandSep::setLO1Root().
Also developed a capability to get relevant table names from scantable header and
fill frequencies of image side band.


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