source: trunk/src/STApplyCal.cpp@ 2951

Last change on this file since 2951 was 2928, checked in by Takeshi Nakazato, 11 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_sdcal2, test_tsdcal2

Put in Release Notes: No

Module(s): Module Names change impacts.

Description: Describe your changes here...

Improved performance of apply mode by revisiting array structure.


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