source: trunk/src/STApplyCal.cpp @ 2925

Last change on this file since 2925 was 2925, checked in by Takeshi Nakazato, 10 years ago

New Development: No

JIRA Issue: No

Ready for Test: Yes

Interface Changes: Yes/No?

What Interface Changed: Please list interface changes

Test Programs: test_tsdcal2

Put in Release Notes: Yes/No?

Module(s): Module Names change impacts.

Description: Describe your changes here...

Improve performance by reconsidering array element order.


File size: 16.6 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  sel_ = target_->getSelection();
185  if (caltype_ == STCalEnum::CalPSAlma ||
186      caltype_ == STCalEnum::CalPS) {
187    sel_.setTypes(vector<int>(1,(int)SrcType::PSON));
188  }
189  target_->setSelection(sel_);
190
191  //os_ << "sel_.print()=" << sel_.print() << LogIO::POST;
192
193  // working data
194  if (insitu) {
195    os_.origin(LogOrigin("STApplyCal","apply",WHERE));
196    os_ << "Overwrite input scantable" << LogIO::POST;
197    work_ = target_;
198  }
199  else {
200    os_.origin(LogOrigin("STApplyCal","apply",WHERE));
201    os_ << "Create output scantable from input" << LogIO::POST;
202    work_ = new Scantable(*target_, false);
203  }
204
205  //os_ << "work_->nrow()=" << work_->nrow() << LogIO::POST;
206
207  // list of apply tables for sky calibration
208  Vector<uInt> skycalList;
209  uInt numSkyCal = 0;
210  uInt nrowSky = 0;
211
212  // list of apply tables for Tsys calibration
213  for (uInt i = 0 ; i < skytable_.size(); i++) {
214    STCalEnum::CalType caltype = STApplyTable::getCalType(skytable_[i]);
215    if (caltype == caltype_) {
216      skycalList.resize(numSkyCal+1, True);
217      skycalList[numSkyCal] = i;
218      numSkyCal++;
219      nrowSky += skytable_[i]->nrow();
220    }
221  }
222
223
224  vector<string> cols( 3 ) ;
225  cols[0] = "BEAMNO" ;
226  cols[1] = "POLNO" ;
227  cols[2] = "IFNO" ;
228  CountedPtr<STIdxIter2> iter = new STIdxIter2(work_, cols) ;
229  double start = mathutil::gettimeofday_sec();
230  os_ << LogIO::DEBUGGING << "start iterative doapply: " << start << LogIO::POST;
231  while (!iter->pastEnd()) {
232    Record ids = iter->currentValue();
233    Vector<uInt> rows = iter->getRows(SHARE);
234    if (rows.nelements() > 0)
235      doapply(ids.asuInt("BEAMNO"), ids.asuInt("IFNO"), ids.asuInt("POLNO"), rows, skycalList, filltsys);
236    iter->next();
237  }
238  double end = mathutil::gettimeofday_sec();
239  os_ << LogIO::DEBUGGING << "end iterative doapply: " << end << LogIO::POST;
240  os_ << LogIO::DEBUGGING << "elapsed time for doapply: " << end - start << " sec" << LogIO::POST;
241
242  target_->unsetSelection();
243}
244
245void STApplyCal::doapply(uInt beamno, uInt ifno, uInt polno,
246                         Vector<uInt> &rows,
247                         Vector<uInt> &skylist,
248                         Bool filltsys)
249{
250  os_.origin(LogOrigin("STApplyCal","doapply",WHERE));
251  Bool doTsys = doTsys_;
252
253  STSelector sel;
254  vector<int> id(1);
255  id[0] = beamno;
256  sel.setBeams(id);
257  id[0] = ifno;
258  sel.setIFs(id);
259  id[0] = polno;
260  sel.setPolarizations(id); 
261
262  // apply selection to apply tables
263  uInt nrowSky = 0;
264  uInt nrowTsys = 0;
265  for (uInt i = 0; i < skylist.nelements(); i++) {
266    skytable_[skylist[i]]->setSelection(sel);
267    nrowSky += skytable_[skylist[i]]->nrow();
268    os_ << "nrowSky=" << nrowSky << LogIO::POST;
269  }
270
271  // Skip IFNO without sky data
272  if (nrowSky == 0)
273    return;
274
275  uInt nchanTsys = 0;
276  Vector<Double> ftsys;
277  uInt tsysifno = getIFForTsys(ifno);
278  os_ << "tsysifno=" << (Int)tsysifno << LogIO::POST;
279  if (tsystable_.size() == 0) {
280    os_.origin(LogOrigin("STApplyTable", "doapply", WHERE));
281    os_ << "No Tsys tables are given. Skip Tsys calibratoin." << LogIO::POST;
282    doTsys = False;
283  }
284  else if (tsysifno == (uInt)-1) {
285    os_.origin(LogOrigin("STApplyTable", "doapply", WHERE));
286    os_ << "No corresponding Tsys for IFNO " << ifno << ". Skip Tsys calibration" << LogIO::POST;
287    doTsys = False;
288  }
289  else {
290    id[0] = (int)tsysifno;
291    sel.setIFs(id);
292    for (uInt i = 0; i < tsystable_.size() ; i++) {
293      tsystable_[i]->setSelection(sel);
294      uInt nrowThisTsys = tsystable_[i]->nrow();
295      nrowTsys += nrowThisTsys;
296      if (nrowThisTsys > 0 and nchanTsys == 0) {
297        nchanTsys = tsystable_[i]->nchan(tsysifno);
298        ftsys = tsystable_[i]->getBaseFrequency(0);
299      }
300    }
301    interpolatorF_->setX(ftsys.data(), nchanTsys);
302  }
303
304  uInt nchanSp = skytable_[skylist[0]]->nchan(ifno);
305  Vector<Double> timeSky(nrowSky);
306  Matrix<Float> spoff(nrowSky, nchanSp);
307  Vector<Float> iOff(nchanSp);
308  nrowSky = 0;
309  for (uInt i = 0 ; i < skylist.nelements(); i++) {
310    STCalSkyTable *p = skytable_[skylist[i]];
311    Vector<Double> t = p->getTime();
312    Matrix<Float> sp = p->getSpectra();
313    for (uInt j = 0; j < t.nelements(); j++) {
314      timeSky[nrowSky] = t[j];
315      spoff.row(nrowSky) = sp.column(j);
316      nrowSky++;
317    }
318  }
319
320  Vector<uInt> skyIdx = timeSort(timeSky);
321
322  Double *xa = new Double[skyIdx.nelements()];
323  Float *ya = new Float[skyIdx.nelements()];
324  IPosition ipos(1, skyIdx.nelements());
325  Vector<Double> timeSkySorted(ipos, xa, TAKE_OVER);
326  Vector<Float> tmpOff(ipos, ya, TAKE_OVER);
327  for (uInt i = 0 ; i < skyIdx.nelements(); i++) {
328    timeSkySorted[i] = timeSky[skyIdx[i]];
329  }
330
331  interpolatorS_->setX(xa, skyIdx.nelements());
332
333  Vector<uInt> tsysIdx;
334  Vector<Double> timeTsys(nrowTsys);
335  Matrix<Float> tsys;
336  Vector<Double> timeTsysSorted;
337  Vector<Float> tmpTsys;
338  if (doTsys) {
339    //os_ << "doTsys" << LogIO::POST;
340    timeTsys.resize(nrowTsys);
341    tsys.resize(nrowTsys, nchanTsys);
342    nrowTsys = 0;
343    for (uInt i = 0 ; i < tsystable_.size(); i++) {
344      STCalTsysTable *p = tsystable_[i];
345      Vector<Double> t = p->getTime();
346      Matrix<Float> ts = p->getTsys();
347      for (uInt j = 0; j < t.nelements(); j++) {
348        timeTsys[nrowTsys] = t[j];
349        tsys.row(nrowTsys) = ts.column(j);
350        nrowTsys++;
351      }
352    }
353    tsysIdx = timeSort(timeTsys);
354
355    Double *xb = new Double[tsysIdx.nelements()];
356    Float *yb = new Float[tsysIdx.nelements()];
357    IPosition ipos(1, tsysIdx.nelements());
358    timeTsysSorted.takeStorage(ipos, xb, TAKE_OVER);
359    tmpTsys.takeStorage(ipos, yb, TAKE_OVER);
360    for (uInt i = 0 ; i < tsysIdx.nelements(); i++) {
361      timeTsysSorted[i] = timeTsys[tsysIdx[i]];
362    }
363    interpolatorT_->setX(xb, tsysIdx.nelements());
364  }
365
366  Table tab = work_->table();
367  ArrayColumn<Float> spCol(tab, "SPECTRA");
368  ArrayColumn<Float> tsysCol(tab, "TSYS");
369  ScalarColumn<Double> timeCol(tab, "TIME");
370  Vector<Float> on;
371
372  // Array for scaling factor (aka Tsys)
373  Vector<Float> iTsys(IPosition(1,nchanSp), new Float[nchanSp], TAKE_OVER);
374 
375  for (uInt i = 0; i < rows.nelements(); i++) {
376    //os_ << "start i = " << i << " (row = " << rows[i] << ")" << LogIO::POST;
377    uInt irow = rows[i];
378
379    // target spectral data
380    on = spCol(irow);
381    //os_ << "on=" << on[0] << LogIO::POST;
382    calibrator_->setSource(on);
383
384    // interpolation
385    Double t0 = timeCol(irow);
386    for (uInt ichan = 0; ichan < nchanSp; ichan++) {
387      for (uInt j = 0; j < skyIdx.nelements(); j++) {
388        tmpOff[j] = spoff(skyIdx[j], ichan);
389      }
390      interpolatorS_->setY(ya, skyIdx.nelements());
391      iOff[ichan] = interpolatorS_->interpolate(t0);
392    }
393    //os_ << "iOff=" << iOff[0] << LogIO::POST;
394    calibrator_->setReference(iOff);
395   
396    if (doTsys) {
397      // Tsys correction
398      Float *yt = new Float[nchanTsys];
399      Vector<Float> iTsysT(IPosition(1,nchanTsys), yt, TAKE_OVER);
400      Float *yb = tmpTsys.data();
401      for (uInt ichan = 0; ichan < nchanTsys; ichan++) {
402        for (uInt j = 0; j < tsysIdx.nelements(); j++) {
403          tmpTsys[j] = tsys(tsysIdx[j], ichan);
404        }
405        interpolatorT_->setY(yb, tsysIdx.nelements());
406        iTsysT[ichan] = interpolatorT_->interpolate(t0);
407      }
408      if (nchanSp == 1) {
409        // take average
410        iTsys[0] = mean(iTsysT);
411      }
412      else {
413        // interpolation on frequency axis
414        Vector<Double> fsp = getBaseFrequency(rows[i]);
415        interpolatorF_->setY(yt, nchanTsys);
416        for (uInt ichan = 0; ichan < nchanSp; ichan++) {
417          iTsys[ichan] = interpolatorF_->interpolate(fsp[ichan]);
418        }
419      }
420    }
421    else {
422      Vector<Float> tsysInRow = tsysCol(irow);
423      if (tsysInRow.nelements() == 1) {
424        iTsys = tsysInRow[0];
425      }
426      else {
427        for (uInt ichan = 0; ichan < tsysInRow.nelements(); ++ichan)
428          iTsys[ichan] = tsysInRow[ichan];
429      }
430    }
431    //os_ << "iTsys=" << iTsys[0] << LogIO::POST;
432    calibrator_->setScaler(iTsys);
433 
434    // do calibration
435    calibrator_->calibrate();
436
437    // update table
438    //os_ << "calibrated=" << calibrator_->getCalibrated()[0] << LogIO::POST;
439    spCol.put(irow, calibrator_->getCalibrated());
440    if (filltsys)
441      tsysCol.put(irow, iTsys);
442  }
443 
444
445  // reset selection on apply tables
446  for (uInt i = 0; i < skylist.nelements(); i++)
447    skytable_[i]->unsetSelection();
448  for (uInt i = 0; i < tsystable_.size(); i++)
449    tsystable_[i]->unsetSelection();
450
451
452  // reset interpolator
453  interpolatorS_->reset();
454  interpolatorF_->reset();
455  interpolatorT_->reset();
456}
457
458Vector<uInt> STApplyCal::timeSort(Vector<Double> &t)
459{
460  Sort sort;
461  sort.sortKey(&t[0], TpDouble, 0, Sort::Ascending);
462  Vector<uInt> idx;
463  sort.sort(idx, t.nelements(), Sort::QuickSort|Sort::NoDuplicates);
464  return idx;
465}
466
467uInt STApplyCal::getIFForTsys(uInt to)
468{
469  for (map<casa::uInt, Vector<uInt> >::iterator i = spwmap_.begin();
470       i != spwmap_.end(); i++) {
471    Vector<uInt> tolist = i->second;
472    os_ << "from=" << i->first << ": tolist=" << tolist << LogIO::POST;
473    for (uInt j = 0; j < tolist.nelements(); j++) {
474      if (tolist[j] == to)
475        return i->first;
476    }
477  }
478  return (uInt)-1;
479}
480
481void STApplyCal::save(const String &name)
482{
483  //assert(!work_.null());
484  assert_<AipsError>(!work_.null(),"You have to execute apply method first.");
485
486  work_->setSelection(sel_);
487  work_->makePersistent(name);
488  work_->unsetSelection();
489}
490
491Vector<Double> STApplyCal::getBaseFrequency(uInt whichrow)
492{
493  //assert(whichrow <= (uInt)work_->nrow());
494  assert_<AipsError>(whichrow <= (uInt)work_->nrow(),"row index out of range.");
495  ROTableColumn col(work_->table(), "IFNO");
496  uInt ifno = col.asuInt(whichrow);
497  col.attach(work_->table(), "FREQ_ID");
498  uInt freqid = col.asuInt(whichrow);
499  uInt nc = work_->nchan(ifno);
500  STFrequencies ftab = work_->frequencies();
501  Double rp, rf, inc;
502  ftab.getEntry(rp, rf, inc, freqid);
503  Vector<Double> r(nc);
504  indgen(r, rf-rp*inc, inc);
505  return r;
506}
507
508void STApplyCal::initInterpolator()
509{
510  os_.origin(LogOrigin("STApplyCal","initInterpolator",WHERE));
511  int order = (order_ > 0) ? order_ : 1;
512  switch (iTime_) {
513  case STCalEnum::NearestInterpolation:
514    {
515      os_ << "use NearestInterpolator in time axis" << LogIO::POST;
516      interpolatorS_ = new NearestInterpolator1D<Double, Float>();
517      interpolatorT_ = new NearestInterpolator1D<Double, Float>();
518      break;
519    }
520  case STCalEnum::LinearInterpolation:
521    {
522      os_ << "use BufferedLinearInterpolator in time axis" << LogIO::POST;
523      interpolatorS_ = new BufferedLinearInterpolator1D<Double, Float>();
524      interpolatorT_ = new BufferedLinearInterpolator1D<Double, Float>();
525      break;     
526    }
527  case STCalEnum::CubicSplineInterpolation:
528    {
529      os_ << "use CubicSplineInterpolator in time axis" << LogIO::POST;
530      interpolatorS_ = new CubicSplineInterpolator1D<Double, Float>();
531      interpolatorT_ = new CubicSplineInterpolator1D<Double, Float>();
532      break;
533    }
534  case STCalEnum::PolynomialInterpolation:
535    {
536      os_ << "use PolynomialInterpolator in time axis" << LogIO::POST;
537      if (order == 0) {
538        interpolatorS_ = new NearestInterpolator1D<Double, Float>();
539        interpolatorT_ = new NearestInterpolator1D<Double, Float>();
540      }
541      else {
542        interpolatorS_ = new PolynomialInterpolator1D<Double, Float>();
543        interpolatorT_ = new PolynomialInterpolator1D<Double, Float>();
544        interpolatorS_->setOrder(order);
545        interpolatorT_->setOrder(order);
546      }
547      break;
548    }
549  default:
550    {
551      os_ << "use BufferedLinearInterpolator in time axis" << LogIO::POST;
552      interpolatorS_ = new BufferedLinearInterpolator1D<Double, Float>();
553      interpolatorT_ = new BufferedLinearInterpolator1D<Double, Float>();
554      break;     
555    }
556  }
557   
558  switch (iFreq_) {
559  case STCalEnum::NearestInterpolation:
560    {
561      os_ << "use NearestInterpolator in frequency axis" << LogIO::POST;
562      interpolatorF_ = new NearestInterpolator1D<Double, Float>();
563      break;
564    }
565  case STCalEnum::LinearInterpolation:
566    {
567      os_ << "use BufferedLinearInterpolator in frequency axis" << LogIO::POST;
568      interpolatorF_ = new BufferedLinearInterpolator1D<Double, Float>();
569      break;     
570    }
571  case STCalEnum::CubicSplineInterpolation:
572    {
573      os_ << "use CubicSplineInterpolator in frequency axis" << LogIO::POST;
574      interpolatorF_ = new CubicSplineInterpolator1D<Double, Float>();
575      break;
576    }
577  case STCalEnum::PolynomialInterpolation:
578    {
579      os_ << "use PolynomialInterpolator in frequency axis" << LogIO::POST;
580      if (order == 0) {
581        interpolatorF_ = new NearestInterpolator1D<Double, Float>();
582      }
583      else {
584        interpolatorF_ = new PolynomialInterpolator1D<Double, Float>();
585        interpolatorF_->setOrder(order);
586      }
587      break;
588    }
589  default:
590    {
591      os_ << "use LinearInterpolator in frequency axis" << LogIO::POST;
592      interpolatorF_ = new BufferedLinearInterpolator1D<Double, Float>();
593      break;     
594    }
595  }
596}
597}
Note: See TracBrowser for help on using the repository browser.