source: trunk/src/STApplyCal.cpp @ 2758

Last change on this file since 2758 was 2758, checked in by Takeshi Nakazato, 11 years ago

New Development: No

JIRA Issue: Yes CAS-4770

Ready for Test: Yes

Interface Changes: No

What Interface Changed: Please list interface changes

Test Programs: test_sdcal2

Put in Release Notes: Yes/No?

Module(s): Module Names change impacts.

Description: Describe your changes here...

Implemented switch to change a behavior of EdgeMarker?.
Disabled some too verbose logs.

File size: 15.8 KB
Line 
1//
2// C++ Implementation: STApplyCal
3//
4// Description:
5//
6//
7// Author: Takeshi Nakazato <takeshi.nakazato@nao.ac.jp> (C) 2012
8//
9// Copyright: See COPYING file that comes with this distribution
10//
11//
12#include <assert.h>
13
14#include <casa/Arrays/Array.h>
15#include <casa/Arrays/Vector.h>
16#include <casa/Arrays/Matrix.h>
17#include <casa/Arrays/ArrayIO.h>
18#include <casa/Arrays/ArrayMath.h>
19#include <casa/BasicSL/String.h>
20#include <casa/Logging/LogIO.h>
21#include <casa/Exceptions/Error.h>
22#include <casa/Utilities/CountedPtr.h>
23#include <casa/Utilities/Sort.h>
24#include <casa/Utilities/Assert.h>
25#include <tables/Tables/Table.h>
26
27#include "Scantable.h"
28#include "STApplyCal.h"
29#include "STApplyTable.h"
30#include "STCalTsysTable.h"
31#include "STCalSkyTable.h"
32#include "STCalEnum.h"
33#include "STIdxIter.h"
34#include "Calibrator.h"
35#include "PSAlmaCalibrator.h"
36#include "Interpolator1D.h"
37#include "NearestInterpolator1D.h"
38#include "BufferedLinearInterpolator1D.h"
39#include "PolynomialInterpolator1D.h"
40#include "CubicSplineInterpolator1D.h"
41#include <atnf/PKSIO/SrcType.h>
42
43
44using namespace casa;
45using namespace std;
46
47namespace asap {
48
49STApplyCal::STApplyCal()
50{
51  init();
52}
53
54STApplyCal::STApplyCal(CountedPtr<Scantable> target)
55  : target_(target)
56{
57  init();
58}
59
60STApplyCal::~STApplyCal()
61{
62}
63
64void STApplyCal::init()
65{
66  caltype_ = STCalEnum::NoType;
67  doTsys_ = False;
68  iTime_ = STCalEnum::DefaultInterpolation;
69  iFreq_ = STCalEnum::DefaultInterpolation;
70}
71
72void STApplyCal::reset()
73{
74  // call init
75  init();
76
77  // clear apply tables
78  // do not delete object here
79  skytable_.resize(0);
80  tsystable_.resize(0);
81
82  // clear mapping for Tsys transfer
83  spwmap_.clear();
84
85  // reset selector
86  sel_.reset();
87 
88  // delete interpolators
89  interpolatorT_ = 0;
90  interpolatorS_ = 0;
91  interpolatorF_ = 0;
92
93  // clear working scantable
94  work_ = 0;
95 
96  // clear calibrator
97  calibrator_ = 0;
98}
99
100void STApplyCal::completeReset()
101{
102  reset();
103  target_ = 0;
104}
105
106void STApplyCal::setTarget(CountedPtr<Scantable> target)
107{
108  target_ = target;
109}
110
111void STApplyCal::setTarget(const String &name)
112{
113  // always create PlainTable
114  target_ = new Scantable(name, Table::Plain);
115}
116
117void STApplyCal::push(STCalSkyTable *table)
118{
119  os_.origin(LogOrigin("STApplyCal","push",WHERE));
120  skytable_.push_back(table);
121  STCalEnum::CalType caltype = STApplyTable::getCalType(table);
122  os_ << "caltype=" <<  caltype << LogIO::POST;
123  if (caltype_ == STCalEnum::NoType ||
124      caltype_ == STCalEnum::DefaultType ||
125      caltype_ == STCalEnum::CalTsys) {
126    caltype_ = caltype;
127  }
128  os_ << "caltype_=" << caltype_ << LogIO::POST;
129}
130
131void STApplyCal::push(STCalTsysTable *table)
132{
133  tsystable_.push_back(table);
134  doTsys_ = True;
135}
136
137void STApplyCal::setTimeInterpolation(STCalEnum::InterpolationType itype, Int order)
138{
139  iTime_ = itype;
140  order_ = order;
141}
142
143void STApplyCal::setFrequencyInterpolation(STCalEnum::InterpolationType itype, Int order)
144{
145  iFreq_ = itype;
146  order_ = order;
147}
148
149void STApplyCal::setTsysTransfer(uInt from, Vector<uInt> to)
150{
151  os_.origin(LogOrigin("STApplyCal","setTsysTransfer",WHERE));
152  os_ << "from=" << from << ", to=" << to << LogIO::POST;
153  map<uInt, Vector<uInt> >::iterator i = spwmap_.find(from);
154  if (i == spwmap_.end()) {
155    spwmap_.insert(pair<uInt, Vector<uInt> >(from, to));
156  }
157  else {
158    Vector<uInt> toNew = i->second;
159    spwmap_.erase(i);
160    uInt k = toNew.nelements();
161    toNew.resize(k+to.nelements(), True);
162    for (uInt i = 0; i < to.nelements(); i++)
163      toNew[i+k] = to[i];
164    spwmap_.insert(pair<uInt, Vector<uInt> >(from, toNew));
165  }
166}
167
168void STApplyCal::apply(Bool insitu, Bool filltsys)
169{
170  os_.origin(LogOrigin("STApplyCal","apply",WHERE));
171 
172  //assert(!target_.null());
173  assert_<AipsError>(!target_.null(),"You have to set target scantable first.");
174
175  // calibrator
176  if (caltype_ == STCalEnum::CalPSAlma)
177    calibrator_ = new PSAlmaCalibrator();
178
179  // interpolator
180  initInterpolator();
181
182  // select data
183  sel_.reset();
184  if (caltype_ == STCalEnum::CalPSAlma ||
185      caltype_ == STCalEnum::CalPS) {
186    sel_.setTypes(vector<int>(1,(int)SrcType::PSON));
187  }
188  target_->setSelection(sel_);
189
190  //os_ << "sel_.print()=" << sel_.print() << LogIO::POST;
191
192  // working data
193  if (insitu) {
194    os_.origin(LogOrigin("STApplyCal","apply",WHERE));
195    os_ << "Overwrite input scantable" << LogIO::POST;
196    work_ = target_;
197  }
198  else {
199    os_.origin(LogOrigin("STApplyCal","apply",WHERE));
200    os_ << "Create output scantable from input" << LogIO::POST;
201    work_ = new Scantable(*target_, false);
202  }
203
204  //os_ << "work_->nrow()=" << work_->nrow() << LogIO::POST;
205
206  // list of apply tables for sky calibration
207  Vector<uInt> skycalList;
208  uInt numSkyCal = 0;
209  uInt nrowSky = 0;
210
211  // list of apply tables for Tsys calibration
212  for (uInt i = 0 ; i < skytable_.size(); i++) {
213    STCalEnum::CalType caltype = STApplyTable::getCalType(skytable_[i]);
214    if (caltype == caltype_) {
215      skycalList.resize(numSkyCal+1, True);
216      skycalList[numSkyCal] = i;
217      numSkyCal++;
218      nrowSky += skytable_[i]->nrow();
219    }
220  }
221
222
223  vector<string> cols( 3 ) ;
224  cols[0] = "BEAMNO" ;
225  cols[1] = "POLNO" ;
226  cols[2] = "IFNO" ;
227  CountedPtr<STIdxIter> iter = new STIdxIterAcc(work_, cols) ;
228  while (!iter->pastEnd()) {
229    Vector<uInt> ids = iter->current();
230    Vector<uInt> rows = iter->getRows(SHARE);
231    if (rows.nelements() > 0)
232      doapply(ids[0], ids[2], ids[1], rows, skycalList, filltsys);
233    iter->next();
234  }
235
236  target_->unsetSelection();
237}
238
239void STApplyCal::doapply(uInt beamno, uInt ifno, uInt polno,
240                         Vector<uInt> &rows,
241                         Vector<uInt> &skylist,
242                         Bool filltsys)
243{
244  os_.origin(LogOrigin("STApplyCal","doapply",WHERE));
245  Bool doTsys = doTsys_;
246
247  STSelector sel;
248  vector<int> id(1);
249  id[0] = beamno;
250  sel.setBeams(id);
251  id[0] = ifno;
252  sel.setIFs(id);
253  id[0] = polno;
254  sel.setPolarizations(id); 
255
256  // apply selection to apply tables
257  uInt nrowSky = 0;
258  uInt nrowTsys = 0;
259  for (uInt i = 0; i < skylist.nelements(); i++) {
260    skytable_[skylist[i]]->setSelection(sel);
261    nrowSky += skytable_[skylist[i]]->nrow();
262    os_ << "nrowSky=" << nrowSky << LogIO::POST;
263  }
264  uInt nchanTsys = 0;
265  Vector<Double> ftsys;
266  uInt tsysifno = getIFForTsys(ifno);
267  os_ << "tsysifno=" << (Int)tsysifno << LogIO::POST;
268  if (tsystable_.size() == 0) {
269    os_.origin(LogOrigin("STApplyTable", "doapply", WHERE));
270    os_ << "No Tsys tables are given. Skip Tsys calibratoin." << LogIO::POST;
271    doTsys = False;
272  }
273  else if (tsysifno == (uInt)-1) {
274    os_.origin(LogOrigin("STApplyTable", "doapply", WHERE));
275    os_ << "No corresponding Tsys for IFNO " << ifno << ". Skip Tsys calibration" << LogIO::POST;
276    doTsys = False;
277  }
278  else {
279    nchanTsys = tsystable_[0]->nchan(tsysifno);
280    ftsys = tsystable_[0]->getBaseFrequency(0);
281    interpolatorF_->setX(ftsys.data(), nchanTsys);
282    id[0] = (int)tsysifno;
283    sel.setIFs(id);
284    for (uInt i = 0; i < tsystable_.size() ; i++) {
285      tsystable_[i]->setSelection(sel);
286      nrowTsys += tsystable_[i]->nrow();
287    }
288  }
289
290  uInt nchanSp = skytable_[skylist[0]]->nchan(ifno);
291  Vector<Double> timeSky(nrowSky);
292  Matrix<Float> spoff(nchanSp, nrowSky);
293  Vector<Float> iOff(nchanSp);
294  nrowSky = 0;
295  for (uInt i = 0 ; i < skylist.nelements(); i++) {
296    STCalSkyTable *p = skytable_[skylist[i]];
297    Vector<Double> t = p->getTime();
298    Matrix<Float> sp = p->getSpectra();
299    for (uInt j = 0; j < t.nelements(); j++) {
300      timeSky[nrowSky] = t[j];
301      spoff.column(nrowSky) = sp.column(j);
302      nrowSky++;
303    }
304  }
305
306  Vector<uInt> skyIdx = timeSort(timeSky);
307
308  Double *xa = new Double[skyIdx.nelements()];
309  Float *ya = new Float[skyIdx.nelements()];
310  IPosition ipos(1, skyIdx.nelements());
311  Vector<Double> timeSkySorted(ipos, xa, TAKE_OVER);
312  Vector<Float> tmpOff(ipos, ya, TAKE_OVER);
313  for (uInt i = 0 ; i < skyIdx.nelements(); i++) {
314    timeSkySorted[i] = timeSky[skyIdx[i]];
315  }
316
317  interpolatorS_->setX(xa, skyIdx.nelements());
318
319  Vector<uInt> tsysIdx;
320  Vector<Double> timeTsys(nrowTsys);
321  Matrix<Float> tsys;
322  Vector<Double> timeTsysSorted;
323  Vector<Float> tmpTsys;
324  if (doTsys) {
325    //os_ << "doTsys" << LogIO::POST;
326    timeTsys.resize(nrowTsys);
327    tsys.resize(nchanTsys, nrowTsys);
328    nrowTsys = 0;
329    for (uInt i = 0 ; i < tsystable_.size(); i++) {
330      STCalTsysTable *p = tsystable_[i];
331      Vector<Double> t = p->getTime();
332      Matrix<Float> ts = p->getTsys();
333      for (uInt j = 0; j < t.nelements(); j++) {
334        timeTsys[nrowTsys] = t[j];
335        tsys.column(nrowTsys) = ts.column(j);
336        nrowTsys++;
337      }
338    }
339    tsysIdx = timeSort(timeTsys);
340
341    Double *xb = new Double[tsysIdx.nelements()];
342    Float *yb = new Float[tsysIdx.nelements()];
343    IPosition ipos(1, tsysIdx.nelements());
344    timeTsysSorted.takeStorage(ipos, xb, TAKE_OVER);
345    tmpTsys.takeStorage(ipos, yb, TAKE_OVER);
346    for (uInt i = 0 ; i < tsysIdx.nelements(); i++) {
347      timeTsysSorted[i] = timeTsys[tsysIdx[i]];
348    }
349    interpolatorT_->setX(xb, tsysIdx.nelements());
350  }
351
352  Table tab = work_->table();
353  ArrayColumn<Float> spCol(tab, "SPECTRA");
354  ArrayColumn<Float> tsysCol(tab, "TSYS");
355  ScalarColumn<Double> timeCol(tab, "TIME");
356  Vector<Float> on;
357  for (uInt i = 0; i < rows.nelements(); i++) {
358    //os_ << "start i = " << i << " (row = " << rows[i] << ")" << LogIO::POST;
359    uInt irow = rows[i];
360
361    // target spectral data
362    on = spCol(irow);
363    calibrator_->setSource(on);
364
365    // interpolation
366    Double t0 = timeCol(irow);
367    for (uInt ichan = 0; ichan < nchanSp; ichan++) {
368      Vector<Float> spOffSlice = spoff.row(ichan);
369      //os_ << "spOffSlice = " << spOffSlice << LogIO::POST;
370      for (uInt j = 0; j < skyIdx.nelements(); j++) {
371        tmpOff[j] = spOffSlice[skyIdx[j]];
372      }
373      interpolatorS_->setY(ya, skyIdx.nelements());
374      iOff[ichan] = interpolatorS_->interpolate(t0);
375    }
376    //os_ << "iOff=" << iOff << LogIO::POST;
377    calibrator_->setReference(iOff);
378   
379    Float *Y = new Float[nchanSp];
380    Vector<Float> iTsys(IPosition(1,nchanSp), Y, TAKE_OVER);
381    if (doTsys) {
382      // Tsys correction
383      Float *yt = new Float[nchanTsys];
384      Vector<Float> iTsysT(IPosition(1,nchanTsys), yt, TAKE_OVER);
385      Float *yb = tmpTsys.data();
386      for (uInt ichan = 0; ichan < nchanTsys; ichan++) {
387        Vector<Float> tsysSlice = tsys.row(ichan);
388        for (uInt j = 0; j < tsysIdx.nelements(); j++) {
389          tmpTsys[j] = tsysSlice[tsysIdx[j]];
390        }
391        interpolatorT_->setY(yb, tsysIdx.nelements());
392        iTsysT[ichan] = interpolatorT_->interpolate(t0);
393      }
394      if (nchanSp == 1) {
395        // take average
396        iTsys[0] = mean(iTsysT);
397      }
398      else {
399        // interpolation on frequency axis
400        Vector<Double> fsp = getBaseFrequency(rows[i]);
401        interpolatorF_->setY(yt, nchanTsys);
402        for (uInt ichan = 0; ichan < nchanSp; ichan++) {
403          iTsys[ichan] = interpolatorF_->interpolate(fsp[ichan]);
404        }
405      }
406    }
407    else {
408      iTsys = 1.0;
409    }
410    //os_ << "iTsys=" << iTsys << LogIO::POST;
411    calibrator_->setScaler(iTsys);
412 
413    // do calibration
414    calibrator_->calibrate();
415
416    // update table
417    //os_ << "calibrated=" << calibrator_->getCalibrated() << LogIO::POST;
418    spCol.put(irow, calibrator_->getCalibrated());
419    if (filltsys)
420      tsysCol.put(irow, iTsys);
421  }
422 
423
424  // reset selection on apply tables
425  for (uInt i = 0; i < skylist.nelements(); i++)
426    skytable_[i]->unsetSelection();
427  for (uInt i = 0; i < tsystable_.size(); i++)
428    tsystable_[i]->unsetSelection();
429
430
431  // reset interpolator
432  interpolatorS_->reset();
433  interpolatorF_->reset();
434  interpolatorT_->reset();
435}
436
437Vector<uInt> STApplyCal::timeSort(Vector<Double> &t)
438{
439  Sort sort;
440  sort.sortKey(&t[0], TpDouble, 0, Sort::Ascending);
441  Vector<uInt> idx;
442  sort.sort(idx, t.nelements(), Sort::QuickSort|Sort::NoDuplicates);
443  return idx;
444}
445
446uInt STApplyCal::getIFForTsys(uInt to)
447{
448  for (map<casa::uInt, Vector<uInt> >::iterator i = spwmap_.begin();
449       i != spwmap_.end(); i++) {
450    Vector<uInt> tolist = i->second;
451    os_ << "from=" << i->first << ": tolist=" << tolist << LogIO::POST;
452    for (uInt j = 0; j < tolist.nelements(); j++) {
453      if (tolist[j] == to)
454        return i->first;
455    }
456  }
457  return (uInt)-1;
458}
459
460void STApplyCal::save(const String &name)
461{
462  //assert(!work_.null());
463  assert_<AipsError>(!work_.null(),"You have to execute apply method first.");
464
465  work_->setSelection(sel_);
466  work_->makePersistent(name);
467  work_->unsetSelection();
468}
469
470Vector<Double> STApplyCal::getBaseFrequency(uInt whichrow)
471{
472  //assert(whichrow <= (uInt)work_->nrow());
473  assert_<AipsError>(whichrow <= (uInt)work_->nrow(),"row index out of range.");
474  ROTableColumn col(work_->table(), "IFNO");
475  uInt ifno = col.asuInt(whichrow);
476  col.attach(work_->table(), "FREQ_ID");
477  uInt freqid = col.asuInt(whichrow);
478  uInt nc = work_->nchan(ifno);
479  STFrequencies ftab = work_->frequencies();
480  Double rp, rf, inc;
481  ftab.getEntry(rp, rf, inc, freqid);
482  Vector<Double> r(nc);
483  indgen(r, rf-rp*inc, inc);
484  return r;
485}
486
487void STApplyCal::initInterpolator()
488{
489  os_.origin(LogOrigin("STApplyCal","initInterpolator",WHERE));
490  int order = (order_ > 0) ? order_ : 1;
491  switch (iTime_) {
492  case STCalEnum::NearestInterpolation:
493    {
494      os_ << "use NearestInterpolator in time axis" << LogIO::POST;
495      interpolatorS_ = new NearestInterpolator1D<Double, Float>();
496      interpolatorT_ = new NearestInterpolator1D<Double, Float>();
497      break;
498    }
499  case STCalEnum::LinearInterpolation:
500    {
501      os_ << "use BufferedLinearInterpolator in time axis" << LogIO::POST;
502      interpolatorS_ = new BufferedLinearInterpolator1D<Double, Float>();
503      interpolatorT_ = new BufferedLinearInterpolator1D<Double, Float>();
504      break;     
505    }
506  case STCalEnum::CubicSplineInterpolation:
507    {
508      os_ << "use CubicSplineInterpolator in time axis" << LogIO::POST;
509      interpolatorS_ = new CubicSplineInterpolator1D<Double, Float>();
510      interpolatorT_ = new CubicSplineInterpolator1D<Double, Float>();
511      break;
512    }
513  case STCalEnum::PolynomialInterpolation:
514    {
515      os_ << "use PolynomialInterpolator in time axis" << LogIO::POST;
516      if (order == 0) {
517        interpolatorS_ = new NearestInterpolator1D<Double, Float>();
518        interpolatorT_ = new NearestInterpolator1D<Double, Float>();
519      }
520      else {
521        interpolatorS_ = new PolynomialInterpolator1D<Double, Float>();
522        interpolatorT_ = new PolynomialInterpolator1D<Double, Float>();
523        interpolatorS_->setOrder(order);
524        interpolatorT_->setOrder(order);
525      }
526      break;
527    }
528  default:
529    {
530      os_ << "use BufferedLinearInterpolator in time axis" << LogIO::POST;
531      interpolatorS_ = new BufferedLinearInterpolator1D<Double, Float>();
532      interpolatorT_ = new BufferedLinearInterpolator1D<Double, Float>();
533      break;     
534    }
535  }
536   
537  switch (iFreq_) {
538  case STCalEnum::NearestInterpolation:
539    {
540      os_ << "use NearestInterpolator in frequency axis" << LogIO::POST;
541      interpolatorF_ = new NearestInterpolator1D<Double, Float>();
542      break;
543    }
544  case STCalEnum::LinearInterpolation:
545    {
546      os_ << "use BufferedLinearInterpolator in frequency axis" << LogIO::POST;
547      interpolatorF_ = new BufferedLinearInterpolator1D<Double, Float>();
548      break;     
549    }
550  case STCalEnum::CubicSplineInterpolation:
551    {
552      os_ << "use CubicSplineInterpolator in frequency axis" << LogIO::POST;
553      interpolatorF_ = new CubicSplineInterpolator1D<Double, Float>();
554      break;
555    }
556  case STCalEnum::PolynomialInterpolation:
557    {
558      os_ << "use PolynomialInterpolator in frequency axis" << LogIO::POST;
559      if (order == 0) {
560        interpolatorF_ = new NearestInterpolator1D<Double, Float>();
561      }
562      else {
563        interpolatorF_ = new PolynomialInterpolator1D<Double, Float>();
564        interpolatorF_->setOrder(order);
565      }
566      break;
567    }
568  default:
569    {
570      os_ << "use LinearInterpolator in frequency axis" << LogIO::POST;
571      interpolatorF_ = new BufferedLinearInterpolator1D<Double, Float>();
572      break;     
573    }
574  }
575}
576}
Note: See TracBrowser for help on using the repository browser.