source: trunk/src/SDMath.cc@ 609

Last change on this file since 609 was 536, checked in by kil064, 20 years ago

add 'TINTSYS' weighting to averageTime

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 60.5 KB
RevLine 
[2]1//#---------------------------------------------------------------------------
2//# SDMath.cc: A collection of single dish mathematical operations
3//#---------------------------------------------------------------------------
4//# Copyright (C) 2004
[125]5//# ATNF
[2]6//#
7//# This program is free software; you can redistribute it and/or modify it
8//# under the terms of the GNU General Public License as published by the Free
9//# Software Foundation; either version 2 of the License, or (at your option)
10//# any later version.
11//#
12//# This program is distributed in the hope that it will be useful, but
13//# WITHOUT ANY WARRANTY; without even the implied warranty of
14//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
15//# Public License for more details.
16//#
17//# You should have received a copy of the GNU General Public License along
18//# with this program; if not, write to the Free Software Foundation, Inc.,
19//# 675 Massachusetts Ave, Cambridge, MA 02139, USA.
20//#
21//# Correspondence concerning this software should be addressed as follows:
22//# Internet email: Malte.Marquarding@csiro.au
23//# Postal address: Malte Marquarding,
24//# Australia Telescope National Facility,
25//# P.O. Box 76,
26//# Epping, NSW, 2121,
27//# AUSTRALIA
28//#
29//# $Id:
30//#---------------------------------------------------------------------------
[38]31#include <vector>
32
[81]33#include <casa/aips.h>
[330]34#include <casa/iostream.h>
35#include <casa/iomanip.h>
[81]36#include <casa/BasicSL/String.h>
37#include <casa/Arrays/IPosition.h>
38#include <casa/Arrays/Array.h>
[130]39#include <casa/Arrays/ArrayIter.h>
40#include <casa/Arrays/VectorIter.h>
[81]41#include <casa/Arrays/ArrayMath.h>
42#include <casa/Arrays/ArrayLogical.h>
43#include <casa/Arrays/MaskedArray.h>
44#include <casa/Arrays/MaskArrMath.h>
45#include <casa/Arrays/MaskArrLogi.h>
[330]46#include <casa/Arrays/Matrix.h>
[234]47#include <casa/BasicMath/Math.h>
[221]48#include <casa/Containers/Block.h>
[262]49#include <casa/Exceptions.h>
50#include <casa/Quanta/Quantum.h>
51#include <casa/Quanta/Unit.h>
52#include <casa/Quanta/MVEpoch.h>
[272]53#include <casa/Quanta/MVTime.h>
[177]54#include <casa/Utilities/Assert.h>
[2]55
[262]56#include <coordinates/Coordinates/SpectralCoordinate.h>
57#include <coordinates/Coordinates/CoordinateSystem.h>
58#include <coordinates/Coordinates/CoordinateUtil.h>
[309]59#include <coordinates/Coordinates/FrequencyAligner.h>
[262]60
61#include <lattices/Lattices/LatticeUtilities.h>
62#include <lattices/Lattices/RebinLattice.h>
63
64#include <measures/Measures/MEpoch.h>
65#include <measures/Measures/MDirection.h>
66#include <measures/Measures/MPosition.h>
67
[177]68#include <scimath/Mathematics/VectorKernel.h>
69#include <scimath/Mathematics/Convolver.h>
[227]70#include <scimath/Mathematics/InterpolateArray1D.h>
[234]71#include <scimath/Functionals/Polynomial.h>
[177]72
[81]73#include <tables/Tables/Table.h>
74#include <tables/Tables/ScalarColumn.h>
75#include <tables/Tables/ArrayColumn.h>
[227]76#include <tables/Tables/ReadAsciiTable.h>
[2]77
[38]78#include "MathUtils.h"
[232]79#include "SDDefs.h"
[354]80#include "SDAttr.h"
[2]81#include "SDContainer.h"
82#include "SDMemTable.h"
83
84#include "SDMath.h"
[457]85#include "SDPol.h"
[2]86
[125]87using namespace casa;
[83]88using namespace asap;
[2]89
[170]90
91SDMath::SDMath()
92{;}
93
[185]94SDMath::SDMath(const SDMath& other)
[170]95{
96
97// No state
98
99}
100
101SDMath& SDMath::operator=(const SDMath& other)
102{
103 if (this != &other) {
104// No state
105 }
106 return *this;
107}
108
[183]109SDMath::~SDMath()
110{;}
[170]111
[183]112
[262]113
[488]114SDMemTable* SDMath::frequencyAlignment(const SDMemTable& in,
115 const String& refTime,
116 const String& method,
117 Bool perFreqID) const
[262]118{
[309]119// Get frame info from Table
[262]120
121 std::vector<std::string> info = in.getCoordInfo();
[294]122
[309]123// Parse frequency system
[294]124
[309]125 String systemStr(info[1]);
126 String baseSystemStr(info[3]);
127 if (baseSystemStr==systemStr) {
128 throw(AipsError("You have not set a frequency frame different from the initial - use function set_freqframe"));
[262]129 }
[309]130//
131 MFrequency::Types freqSystem;
132 MFrequency::getType(freqSystem, systemStr);
[294]133
[267]134// Do it
[262]135
[488]136 return frequencyAlign(in, freqSystem, refTime, method, perFreqID);
[267]137}
[262]138
139
140
[185]141CountedPtr<SDMemTable> SDMath::average(const Block<CountedPtr<SDMemTable> >& in,
142 const Vector<Bool>& mask, Bool scanAv,
[309]143 const String& weightStr, Bool alignFreq) const
[130]144//
[144]145// Weighted averaging of spectra from one or more Tables.
[130]146//
147{
[2]148
[163]149// Convert weight type
150
151 WeightType wtType = NONE;
[518]152 convertWeightString(wtType, weightStr, True);
[163]153
[144]154// Create output Table by cloning from the first table
[2]155
[144]156 SDMemTable* pTabOut = new SDMemTable(*in[0],True);
[488]157 if (in.nelements() > 1) {
158 for (uInt i=1; i < in.nelements(); ++i) {
159 pTabOut->appendToHistoryTable(in[i]->getHistoryTable());
160 }
161 }
[144]162// Setup
[130]163
[144]164 IPosition shp = in[0]->rowAsMaskedArray(0).shape(); // Must not change
165 Array<Float> arr(shp);
166 Array<Bool> barr(shp);
[221]167 const Bool useMask = (mask.nelements() == shp(asap::ChanAxis));
[130]168
[144]169// Columns from Tables
[130]170
[144]171 ROArrayColumn<Float> tSysCol;
172 ROScalarColumn<Double> mjdCol;
173 ROScalarColumn<String> srcNameCol;
174 ROScalarColumn<Double> intCol;
175 ROArrayColumn<uInt> fqIDCol;
[410]176 ROScalarColumn<Int> scanIDCol;
[130]177
[144]178// Create accumulation MaskedArray. We accumulate for each channel,if,pol,beam
179// Note that the mask of the accumulation array will ALWAYS remain ALL True.
180// The MA is only used so that when data which is masked Bad is added to it,
181// that data does not contribute.
182
183 Array<Float> zero(shp);
184 zero=0.0;
185 Array<Bool> good(shp);
186 good = True;
187 MaskedArray<Float> sum(zero,good);
188
189// Counter arrays
190
191 Array<Float> nPts(shp); // Number of points
192 nPts = 0.0;
193 Array<Float> nInc(shp); // Increment
194 nInc = 1.0;
195
196// Create accumulation Array for variance. We accumulate for
197// each if,pol,beam, but average over channel. So we need
198// a shape with one less axis dropping channels.
199
200 const uInt nAxesSub = shp.nelements() - 1;
201 IPosition shp2(nAxesSub);
202 for (uInt i=0,j=0; i<(nAxesSub+1); i++) {
[221]203 if (i!=asap::ChanAxis) {
[144]204 shp2(j) = shp(i);
205 j++;
206 }
[2]207 }
[144]208 Array<Float> sumSq(shp2);
209 sumSq = 0.0;
210 IPosition pos2(nAxesSub,0); // For indexing
[130]211
[144]212// Time-related accumulators
[130]213
[144]214 Double time;
215 Double timeSum = 0.0;
216 Double intSum = 0.0;
217 Double interval = 0.0;
[130]218
[144]219// To get the right shape for the Tsys accumulator we need to
220// access a column from the first table. The shape of this
[518]221// array must not change. Note however that since the TSysSqSum
222// array is used in a normalization process, and that I ignore the
223// channel axis replication of values for now, it loses a dimension
[130]224
[518]225 Array<Float> tSysSum, tSysSqSum;
[144]226 {
227 const Table& tabIn = in[0]->table();
228 tSysCol.attach(tabIn,"TSYS");
229 tSysSum.resize(tSysCol.shape(0));
[518]230//
231 tSysSqSum.resize(shp2);
[144]232 }
233 tSysSum =0.0;
[518]234 tSysSqSum = 0.0;
[144]235 Array<Float> tSys;
236
237// Scan and row tracking
238
239 Int oldScanID = 0;
240 Int outScanID = 0;
241 Int scanID = 0;
242 Int rowStart = 0;
243 Int nAccum = 0;
244 Int tableStart = 0;
245
246// Source and FreqID
247
248 String sourceName, oldSourceName, sourceNameStart;
249 Vector<uInt> freqID, freqIDStart, oldFreqID;
250
251// Loop over tables
252
253 Float fac = 1.0;
254 const uInt nTables = in.nelements();
255 for (uInt iTab=0; iTab<nTables; iTab++) {
256
[309]257// Should check that the frequency tables don't change if doing FreqAlignment
[221]258
[144]259// Attach columns to Table
260
261 const Table& tabIn = in[iTab]->table();
262 tSysCol.attach(tabIn, "TSYS");
263 mjdCol.attach(tabIn, "TIME");
264 srcNameCol.attach(tabIn, "SRCNAME");
265 intCol.attach(tabIn, "INTERVAL");
266 fqIDCol.attach(tabIn, "FREQID");
[410]267 scanIDCol.attach(tabIn, "SCANID");
[144]268
269// Loop over rows in Table
270
271 const uInt nRows = in[iTab]->nRow();
272 for (uInt iRow=0; iRow<nRows; iRow++) {
273
274// Check conformance
275
276 IPosition shp2 = in[iTab]->rowAsMaskedArray(iRow).shape();
277 if (!shp.isEqual(shp2)) {
278 throw (AipsError("Shapes for all rows must be the same"));
279 }
280
281// If we are not doing scan averages, make checks for source and
282// frequency setup and warn if averaging across them
283
[410]284 scanIDCol.getScalar(iRow, scanID);
[144]285
286// Get quantities from columns
287
288 srcNameCol.getScalar(iRow, sourceName);
289 mjdCol.get(iRow, time);
290 tSysCol.get(iRow, tSys);
291 intCol.get(iRow, interval);
292 fqIDCol.get(iRow, freqID);
293
294// Initialize first source and freqID
295
296 if (iRow==0 && iTab==0) {
297 sourceNameStart = sourceName;
298 freqIDStart = freqID;
299 }
300
301// If we are doing scan averages, see if we are at the end of an
302// accumulation period (scan). We must check soutce names too,
303// since we might have two tables with one scan each but different
304// source names; we shouldn't average different sources together
305
306 if (scanAv && ( (scanID != oldScanID) ||
307 (iRow==0 && iTab>0 && sourceName!=oldSourceName))) {
308
309// Normalize data in 'sum' accumulation array according to weighting scheme
310
[518]311 normalize(sum, sumSq, tSysSqSum, nPts, intSum, wtType, asap::ChanAxis, nAxesSub);
[144]312
[410]313// Get ScanContainer for the first row of this averaged Scan
314
315 SDContainer scOut = in[iTab]->getSDContainer(rowStart);
316
[144]317// Fill scan container. The source and freqID come from the
318// first row of the first table that went into this average (
319// should be the same for all rows in the scan average)
320
321 Float nR(nAccum);
[410]322 fillSDC(scOut, sum.getMask(), sum.getArray(), tSysSum/nR, outScanID,
[144]323 timeSum/nR, intSum, sourceNameStart, freqIDStart);
324
325// Write container out to Table
326
[410]327 pTabOut->putSDContainer(scOut);
[144]328
329// Reset accumulators
330
331 sum = 0.0;
332 sumSq = 0.0;
333 nAccum = 0;
334//
335 tSysSum =0.0;
[518]336 tSysSqSum =0.0;
[144]337 timeSum = 0.0;
338 intSum = 0.0;
[221]339 nPts = 0.0;
[144]340
341// Increment
342
343 rowStart = iRow; // First row for next accumulation
344 tableStart = iTab; // First table for next accumulation
345 sourceNameStart = sourceName; // First source name for next accumulation
346 freqIDStart = freqID; // First FreqID for next accumulation
347//
348 oldScanID = scanID;
349 outScanID += 1; // Scan ID for next accumulation period
[227]350 }
[144]351
[146]352// Accumulate
[144]353
[518]354 accumulate(timeSum, intSum, nAccum, sum, sumSq, nPts, tSysSum, tSysSqSum,
355 tSys, nInc, mask, time, interval, in, iTab, iRow, asap::ChanAxis,
356 nAxesSub, useMask, wtType);
[144]357//
358 oldSourceName = sourceName;
359 oldFreqID = freqID;
[184]360 }
[144]361 }
362
363// OK at this point we have accumulation data which is either
364// - accumulated from all tables into one row
365// or
366// - accumulated from the last scan average
367//
368// Normalize data in 'sum' accumulation array according to weighting scheme
[410]369
[518]370 normalize(sum, sumSq, tSysSqSum, nPts, intSum, wtType, asap::ChanAxis, nAxesSub);
[144]371
372// Create and fill container. The container we clone will be from
373// the last Table and the first row that went into the current
374// accumulation. It probably doesn't matter that much really...
375
376 Float nR(nAccum);
[410]377 SDContainer scOut = in[tableStart]->getSDContainer(rowStart);
378 fillSDC(scOut, sum.getMask(), sum.getArray(), tSysSum/nR, outScanID,
[144]379 timeSum/nR, intSum, sourceNameStart, freqIDStart);
[410]380 pTabOut->putSDContainer(scOut);
[304]381 pTabOut->resetCursor();
[144]382//
383 return CountedPtr<SDMemTable>(pTabOut);
[2]384}
[9]385
[144]386
387
[488]388CountedPtr<SDMemTable> SDMath::binaryOperate(const CountedPtr<SDMemTable>&
389 left,
390 const CountedPtr<SDMemTable>&
391 right,
392 const String& op, Bool preserve,
393 Bool doTSys) const
[185]394{
[85]395
[248]396// Check operator
[130]397
[234]398 String op2(op);
399 op2.upcase();
400 uInt what = 0;
401 if (op2=="ADD") {
402 what = 0;
403 } else if (op2=="SUB") {
404 what = 1;
405 } else if (op2=="MUL") {
406 what = 2;
407 } else if (op2=="DIV") {
408 what = 3;
[248]409 } else if (op2=="QUOTIENT") {
410 what = 4;
[294]411 doTSys = True;
[234]412 } else {
[248]413 throw( AipsError("Unrecognized operation"));
[234]414 }
415
416// Check rows
417
[248]418 const uInt nRowLeft = left->nRow();
419 const uInt nRowRight = right->nRow();
420 Bool ok = (nRowRight==1&&nRowLeft>0) ||
421 (nRowRight>=1&&nRowLeft==nRowRight);
422 if (!ok) {
423 throw (AipsError("The right Scan Table can have one row or the same number of rows as the left Scan Table"));
[234]424 }
425
[248]426// Input Tables
[234]427
428 const Table& tLeft = left->table();
429 const Table& tRight = right->table();
[248]430
431// TSys columns
432
[294]433 ROArrayColumn<Float> tSysLeftCol, tSysRightCol;
434 if (doTSys) {
435 tSysLeftCol.attach(tLeft, "TSYS");
436 tSysRightCol.attach(tRight, "TSYS");
437 }
[234]438
[248]439// First row for right
[234]440
[248]441 Array<Float> tSysLeftArr, tSysRightArr;
[294]442 if (doTSys) tSysRightCol.get(0, tSysRightArr);
[248]443 MaskedArray<Float>* pMRight = new MaskedArray<Float>(right->rowAsMaskedArray(0));
444 IPosition shpRight = pMRight->shape();
445
446// Output Table cloned from left
447
[234]448 SDMemTable* pTabOut = new SDMemTable(*left, True);
[488]449 pTabOut->appendToHistoryTable(right->getHistoryTable());
[234]450// Loop over rows
451
[248]452 for (uInt i=0; i<nRowLeft; i++) {
[234]453
454// Get data
[248]455
[234]456 MaskedArray<Float> mLeft(left->rowAsMaskedArray(i));
[248]457 IPosition shpLeft = mLeft.shape();
[294]458 if (doTSys) tSysLeftCol.get(i, tSysLeftArr);
[234]459//
[248]460 if (nRowRight>1) {
461 delete pMRight;
462 pMRight = new MaskedArray<Float>(right->rowAsMaskedArray(i));
463 shpRight = pMRight->shape();
[294]464 if (doTSys) tSysRightCol.get(i, tSysRightArr);
[234]465 }
[248]466//
467 if (!shpRight.isEqual(shpLeft)) {
468 throw(AipsError("left and right scan tables are not conformant"));
469 }
[294]470 if (doTSys) {
471 if (!tSysRightArr.shape().isEqual(tSysRightArr.shape())) {
472 throw(AipsError("left and right Tsys data are not conformant"));
473 }
474 if (!shpRight.isEqual(tSysRightArr.shape())) {
475 throw(AipsError("left and right scan tables are not conformant"));
476 }
[248]477 }
[234]478
479// Make container
480
481 SDContainer sc = left->getSDContainer(i);
482
483// Operate on data and TSys
484
485 if (what==0) {
[248]486 MaskedArray<Float> tmp = mLeft + *pMRight;
[234]487 putDataInSDC(sc, tmp.getArray(), tmp.getMask());
[294]488 if (doTSys) sc.putTsys(tSysLeftArr+tSysRightArr);
[234]489 } else if (what==1) {
[248]490 MaskedArray<Float> tmp = mLeft - *pMRight;
[234]491 putDataInSDC(sc, tmp.getArray(), tmp.getMask());
[294]492 if (doTSys) sc.putTsys(tSysLeftArr-tSysRightArr);
[234]493 } else if (what==2) {
[248]494 MaskedArray<Float> tmp = mLeft * *pMRight;
[234]495 putDataInSDC(sc, tmp.getArray(), tmp.getMask());
[294]496 if (doTSys) sc.putTsys(tSysLeftArr*tSysRightArr);
[234]497 } else if (what==3) {
[248]498 MaskedArray<Float> tmp = mLeft / *pMRight;
[234]499 putDataInSDC(sc, tmp.getArray(), tmp.getMask());
[294]500 if (doTSys) sc.putTsys(tSysLeftArr/tSysRightArr);
[248]501 } else if (what==4) {
[488]502 if (preserve) {
503 MaskedArray<Float> tmp = (tSysRightArr * mLeft / *pMRight) -
504 tSysRightArr;
505 putDataInSDC(sc, tmp.getArray(), tmp.getMask());
506 } else {
507 MaskedArray<Float> tmp = (tSysRightArr * mLeft / *pMRight) -
508 tSysLeftArr;
509 putDataInSDC(sc, tmp.getArray(), tmp.getMask());
510 }
511 sc.putTsys(tSysRightArr);
[234]512 }
513
514// Put new row in output Table
515
[171]516 pTabOut->putSDContainer(sc);
[130]517 }
[248]518 if (pMRight) delete pMRight;
[304]519 pTabOut->resetCursor();
[488]520
[171]521 return CountedPtr<SDMemTable>(pTabOut);
[9]522}
[48]523
[146]524
525
[185]526std::vector<float> SDMath::statistic(const CountedPtr<SDMemTable>& in,
[234]527 const Vector<Bool>& mask,
528 const String& which, Int row) const
[130]529//
530// Perhaps iteration over pol/beam/if should be in here
531// and inside the nrow iteration ?
532//
533{
534 const uInt nRow = in->nRow();
535
536// Specify cursor location
537
[152]538 IPosition start, end;
[434]539 Bool doAll = False;
540 setCursorSlice (start, end, doAll, *in);
[130]541
542// Loop over rows
543
[234]544 const uInt nEl = mask.nelements();
545 uInt iStart = 0;
546 uInt iEnd = in->nRow()-1;
547//
548 if (row>=0) {
549 iStart = row;
550 iEnd = row;
551 }
552//
553 std::vector<float> result(iEnd-iStart+1);
554 for (uInt ii=iStart; ii <= iEnd; ++ii) {
[130]555
556// Get row and deconstruct
557
[434]558 MaskedArray<Float> dataIn = (in->rowAsMaskedArray(ii))(start,end);
559 Array<Float> v = dataIn.getArray().nonDegenerate();
560 Array<Bool> m = dataIn.getMask().nonDegenerate();
[130]561
562// Access desired piece of data
563
[434]564// Array<Float> v((arr(start,end)).nonDegenerate());
565// Array<Bool> m((barr(start,end)).nonDegenerate());
[130]566
567// Apply OTF mask
568
569 MaskedArray<Float> tmp;
570 if (m.nelements()==nEl) {
[234]571 tmp.setData(v,m&&mask);
[130]572 } else {
573 tmp.setData(v,m);
574 }
575
576// Get statistic
577
[234]578 result[ii-iStart] = mathutil::statistics(which, tmp);
[130]579 }
580//
581 return result;
582}
583
[146]584
[234]585SDMemTable* SDMath::bin(const SDMemTable& in, Int width) const
[144]586{
[169]587 SDHeader sh = in.getSDHeader();
588 SDMemTable* pTabOut = new SDMemTable(in, True);
[163]589
[169]590// Bin up SpectralCoordinates
[163]591
[169]592 IPosition factors(1);
593 factors(0) = width;
594 for (uInt j=0; j<in.nCoordinates(); ++j) {
595 CoordinateSystem cSys;
[288]596 cSys.addCoordinate(in.getSpectralCoordinate(j));
[169]597 CoordinateSystem cSysBin =
[185]598 CoordinateUtil::makeBinnedCoordinateSystem(factors, cSys, False);
[169]599//
600 SpectralCoordinate sCBin = cSysBin.spectralCoordinate(0);
601 pTabOut->setCoordinate(sCBin, j);
602 }
[163]603
[169]604// Use RebinLattice to find shape
[130]605
[169]606 IPosition shapeIn(1,sh.nchan);
[185]607 IPosition shapeOut = RebinLattice<Float>::rebinShape(shapeIn, factors);
[169]608 sh.nchan = shapeOut(0);
609 pTabOut->putSDHeader(sh);
[144]610
[169]611// Loop over rows and bin along channel axis
612
613 for (uInt i=0; i < in.nRow(); ++i) {
614 SDContainer sc = in.getSDContainer(i);
[144]615//
[169]616 Array<Float> tSys(sc.getTsys()); // Get it out before sc changes shape
[144]617
[169]618// Bin up spectrum
[144]619
[169]620 MaskedArray<Float> marr(in.rowAsMaskedArray(i));
621 MaskedArray<Float> marrout;
[221]622 LatticeUtilities::bin(marrout, marr, asap::ChanAxis, width);
[144]623
[169]624// Put back the binned data and flags
[144]625
[169]626 IPosition ip2 = marrout.shape();
627 sc.resize(ip2);
[146]628//
[185]629 putDataInSDC(sc, marrout.getArray(), marrout.getMask());
[146]630
[169]631// Bin up Tsys.
[146]632
[169]633 Array<Bool> allGood(tSys.shape(),True);
634 MaskedArray<Float> tSysIn(tSys, allGood, True);
[146]635//
[169]636 MaskedArray<Float> tSysOut;
[221]637 LatticeUtilities::bin(tSysOut, tSysIn, asap::ChanAxis, width);
[169]638 sc.putTsys(tSysOut.getArray());
[146]639//
[169]640 pTabOut->putSDContainer(sc);
641 }
642 return pTabOut;
[146]643}
644
[488]645SDMemTable* SDMath::resample(const SDMemTable& in, const String& methodStr,
646 Float width) const
[299]647//
648// Should add the possibility of width being specified in km/s. This means
649// that for each freqID (SpectralCoordinate) we will need to convert to an
650// average channel width (say at the reference pixel). Then we would need
651// to be careful to make sure each spectrum (of different freqID)
652// is the same length.
653//
654{
655 Bool doVel = False;
[309]656 if (doVel) {
657 for (uInt j=0; j<in.nCoordinates(); ++j) {
658 SpectralCoordinate sC = in.getSpectralCoordinate(j);
659 }
660 }
[299]661
662// Interpolation method
663
[317]664 InterpolateArray1D<Double,Float>::InterpolationMethod interp;
665 convertInterpString(interp, methodStr);
666 Int interpMethod(interp);
[299]667
668// Make output table
669
670 SDMemTable* pTabOut = new SDMemTable(in, True);
671
672// Resample SpectralCoordinates (one per freqID)
673
674 const uInt nCoord = in.nCoordinates();
675 Vector<Float> offset(1,0.0);
676 Vector<Float> factors(1,1.0/width);
677 Vector<Int> newShape;
678 for (uInt j=0; j<in.nCoordinates(); ++j) {
679 CoordinateSystem cSys;
680 cSys.addCoordinate(in.getSpectralCoordinate(j));
681 CoordinateSystem cSys2 = cSys.subImage(offset, factors, newShape);
682 SpectralCoordinate sC = cSys2.spectralCoordinate(0);
683//
684 pTabOut->setCoordinate(sC, j);
685 }
686
687// Get header
688
689 SDHeader sh = in.getSDHeader();
690
691// Generate resampling vectors
692
693 const uInt nChanIn = sh.nchan;
694 Vector<Float> xIn(nChanIn);
695 indgen(xIn);
696//
697 Int fac = Int(nChanIn/width);
698 Vector<Float> xOut(fac+10); // 10 to be safe - resize later
699 uInt i = 0;
700 Float x = 0.0;
701 Bool more = True;
702 while (more) {
703 xOut(i) = x;
704//
705 i++;
706 x += width;
707 if (x>nChanIn-1) more = False;
708 }
709 const uInt nChanOut = i;
710 xOut.resize(nChanOut,True);
711//
712 IPosition shapeIn(in.rowAsMaskedArray(0).shape());
713 sh.nchan = nChanOut;
714 pTabOut->putSDHeader(sh);
715
716// Loop over rows and resample along channel axis
717
718 Array<Float> valuesOut;
719 Array<Bool> maskOut;
720 Array<Float> tSysOut;
721 Array<Bool> tSysMaskIn(shapeIn,True);
722 Array<Bool> tSysMaskOut;
723 for (uInt i=0; i < in.nRow(); ++i) {
724
725// Get container
726
727 SDContainer sc = in.getSDContainer(i);
728
729// Get data and Tsys
730
731 const Array<Float>& tSysIn = sc.getTsys();
732 const MaskedArray<Float>& dataIn(in.rowAsMaskedArray(i));
733 Array<Float> valuesIn = dataIn.getArray();
734 Array<Bool> maskIn = dataIn.getMask();
735
736// Interpolate data
737
738 InterpolateArray1D<Float,Float>::interpolate(valuesOut, maskOut, xOut,
739 xIn, valuesIn, maskIn,
740 interpMethod, True, True);
741 sc.resize(valuesOut.shape());
742 putDataInSDC(sc, valuesOut, maskOut);
743
744// Interpolate TSys
745
746 InterpolateArray1D<Float,Float>::interpolate(tSysOut, tSysMaskOut, xOut,
747 xIn, tSysIn, tSysMaskIn,
748 interpMethod, True, True);
749 sc.putTsys(tSysOut);
750
751// Put container in output
752
753 pTabOut->putSDContainer(sc);
754 }
755//
756 return pTabOut;
757}
758
[248]759SDMemTable* SDMath::unaryOperate(const SDMemTable& in, Float val, Bool doAll,
[294]760 uInt what, Bool doTSys) const
[152]761//
762// what = 0 Multiply
763// 1 Add
[146]764{
[152]765 SDMemTable* pOut = new SDMemTable(in,False);
766 const Table& tOut = pOut->table();
[294]767 ArrayColumn<Float> specCol(tOut,"SPECTRA");
768 ArrayColumn<Float> tSysCol(tOut,"TSYS");
769 Array<Float> tSysArr;
[434]770
771// Get data slice bounds
772
773 IPosition start, end;
774 setCursorSlice (start, end, doAll, in);
[146]775//
[434]776 for (uInt i=0; i<tOut.nrow(); i++) {
[294]777
778// Modify data
779
[434]780 MaskedArray<Float> dataIn(pOut->rowAsMaskedArray(i));
781 MaskedArray<Float> dataIn2 = dataIn(start,end); // Reference
782 if (what==0) {
783 dataIn2 *= val;
784 } else if (what==1) {
785 dataIn2 += val;
786 }
787 specCol.put(i, dataIn.getArray());
[294]788
789// Modify Tsys
790
[434]791 if (doTSys) {
792 tSysCol.get(i, tSysArr);
793 Array<Float> tSysArr2 = tSysArr(start,end); // Reference
[152]794 if (what==0) {
[434]795 tSysArr2 *= val;
[152]796 } else if (what==1) {
[434]797 tSysArr2 += val;
[152]798 }
[434]799 tSysCol.put(i, tSysArr);
[152]800 }
801 }
802//
[146]803 return pOut;
804}
805
[315]806SDMemTable* SDMath::averagePol(const SDMemTable& in, const Vector<Bool>& mask,
807 const String& weightStr) const
[152]808//
[165]809// Average all polarizations together, weighted by variance
810//
811{
[315]812 WeightType wtType = NONE;
[532]813 convertWeightString(wtType, weightStr, True);
[165]814
815// Create output Table and reshape number of polarizations
816
817 Bool clear=True;
818 SDMemTable* pTabOut = new SDMemTable(in, clear);
819 SDHeader header = pTabOut->getSDHeader();
820 header.npol = 1;
821 pTabOut->putSDHeader(header);
[532]822//
823 const Table& tabIn = in.table();
[165]824
825// Shape of input and output data
826
[448]827 const IPosition& shapeIn = in.rowAsMaskedArray(0).shape();
[165]828 IPosition shapeOut(shapeIn);
[262]829 shapeOut(asap::PolAxis) = 1; // Average all polarizations
[315]830 if (shapeIn(asap::PolAxis)==1) {
831 throw(AipsError("The input has only one polarisation"));
832 }
[165]833//
[532]834 const uInt nRows = in.nRow();
[262]835 const uInt nChan = shapeIn(asap::ChanAxis);
[532]836 AlwaysAssert(asap::nAxes==4,AipsError);
[165]837 const IPosition vecShapeOut(4,1,1,1,nChan); // A multi-dim form of a Vector shape
838 IPosition start(4), end(4);
839
840// Output arrays
841
842 Array<Float> outData(shapeOut, 0.0);
843 Array<Bool> outMask(shapeOut, True);
[262]844 const IPosition axes(2, asap::PolAxis, asap::ChanAxis); // pol-channel plane
[532]845
846// Attach Tsys column if needed
847
848 ROArrayColumn<Float> tSysCol;
849 Array<Float> tSys;
850 if (wtType==TSYS) {
851 tSysCol.attach(tabIn,"TSYS");
852 }
[165]853//
[262]854 const Bool useMask = (mask.nelements() == shapeIn(asap::ChanAxis));
[165]855
856// Loop over rows
857
858 for (uInt iRow=0; iRow<nRows; iRow++) {
859
860// Get data for this row
861
862 MaskedArray<Float> marr(in.rowAsMaskedArray(iRow));
863 Array<Float>& arr = marr.getRWArray();
864 const Array<Bool>& barr = marr.getMask();
[532]865
866// Get Tsys
[165]867
[532]868 if (wtType==TSYS) {
869 tSysCol.get(iRow,tSys);
870 }
871
[165]872// Make iterators to iterate by pol-channel planes
[532]873// The tSys array is empty unless wtType=TSYS so only
874// access the iterator is that is the case
[165]875
876 ReadOnlyArrayIterator<Float> itDataPlane(arr, axes);
877 ReadOnlyArrayIterator<Bool> itMaskPlane(barr, axes);
[532]878 ReadOnlyArrayIterator<Float>* pItTsysPlane = 0;
879 if (wtType==TSYS) pItTsysPlane = new ReadOnlyArrayIterator<Float>(tSys, axes);
[165]880
881// Accumulations
882
883 Float fac = 1.0;
884 Vector<Float> vecSum(nChan,0.0);
885
886// Iterate through data by pol-channel planes
887
888 while (!itDataPlane.pastEnd()) {
889
890// Iterate through plane by polarization and accumulate Vectors
891
892 Vector<Float> t1(nChan); t1 = 0.0;
893 Vector<Bool> t2(nChan); t2 = True;
[532]894 Float tSys = 0.0;
[165]895 MaskedArray<Float> vecSum(t1,t2);
[315]896 Float norm = 0.0;
[165]897 {
898 ReadOnlyVectorIterator<Float> itDataVec(itDataPlane.array(), 1);
899 ReadOnlyVectorIterator<Bool> itMaskVec(itMaskPlane.array(), 1);
[532]900//
901 ReadOnlyVectorIterator<Float>* pItTsysVec = 0;
902 if (wtType==TSYS) {
903 pItTsysVec = new ReadOnlyVectorIterator<Float>(pItTsysPlane->array(), 1);
904 }
905//
[165]906 while (!itDataVec.pastEnd()) {
907
[315]908// Create MA of data & mask (optionally including OTF mask) and get variance for this spectrum
[165]909
910 if (useMask) {
911 const MaskedArray<Float> spec(itDataVec.vector(),mask&&itMaskVec.vector());
[532]912 if (wtType==VAR) {
913 fac = 1.0 / variance(spec);
914 } else if (wtType==TSYS) {
915 tSys = pItTsysVec->vector()[0]; // Drop pseudo channel dependency
916 fac = 1.0 / tSys / tSys;
917 }
[165]918 } else {
919 const MaskedArray<Float> spec(itDataVec.vector(),itMaskVec.vector());
[532]920 if (wtType==VAR) {
921 fac = 1.0 / variance(spec);
922 } else if (wtType==TSYS) {
923 tSys = pItTsysVec->vector()[0]; // Drop pseudo channel dependency
924 fac = 1.0 / tSys / tSys;
925 }
[165]926 }
927
928// Normalize spectrum (without OTF mask) and accumulate
929
930 const MaskedArray<Float> spec(fac*itDataVec.vector(), itMaskVec.vector());
931 vecSum += spec;
[315]932 norm += fac;
[165]933
934// Next
935
936 itDataVec.next();
937 itMaskVec.next();
[532]938 if (wtType==TSYS) pItTsysVec->next();
[165]939 }
[532]940
941// Clean up
942
943 if (pItTsysVec) {
944 delete pItTsysVec;
945 pItTsysVec = 0;
946 }
[165]947 }
948
949// Normalize summed spectrum
950
[315]951 vecSum /= norm;
[165]952
953// FInd position in input data array. We are iterating by pol-channel
954// plane so all that will change is beam and IF and that's what we want.
955
956 IPosition pos = itDataPlane.pos();
957
958// Write out data. This is a bit messy. We have to reform the Vector
959// accumulator into an Array of shape (1,1,1,nChan)
960
961 start = pos;
962 end = pos;
[262]963 end(asap::ChanAxis) = nChan-1;
[165]964 outData(start,end) = vecSum.getArray().reform(vecShapeOut);
965 outMask(start,end) = vecSum.getMask().reform(vecShapeOut);
966
967// Step to next beam/IF combination
968
969 itDataPlane.next();
970 itMaskPlane.next();
[532]971 if (wtType==TSYS) pItTsysPlane->next();
[165]972 }
973
974// Generate output container and write it to output table
975
976 SDContainer sc = in.getSDContainer();
977 sc.resize(shapeOut);
978//
[185]979 putDataInSDC(sc, outData, outMask);
[165]980 pTabOut->putSDContainer(sc);
[532]981//
982 if (wtType==TSYS) {
983 delete pItTsysPlane;
984 pItTsysPlane = 0;
985 }
[165]986 }
[304]987
988// Set polarization cursor to 0
989
990 pTabOut->setPol(0);
[165]991//
992 return pTabOut;
993}
[167]994
[169]995
[185]996SDMemTable* SDMath::smooth(const SDMemTable& in,
997 const casa::String& kernelType,
[234]998 casa::Float width, Bool doAll) const
[299]999//
1000// Should smooth TSys as well
1001//
[177]1002{
[169]1003
[177]1004// Number of channels
[169]1005
[434]1006 const uInt nChan = in.nChan();
[177]1007
1008// Generate Kernel
1009
[185]1010 VectorKernel::KernelTypes type = VectorKernel::toKernelType(kernelType);
[177]1011 Vector<Float> kernel = VectorKernel::make(type, width, nChan, True, False);
1012
1013// Generate Convolver
1014
1015 IPosition shape(1,nChan);
1016 Convolver<Float> conv(kernel, shape);
1017
1018// New Table
1019
1020 SDMemTable* pTabOut = new SDMemTable(in,True);
1021
1022// Output Vectors
1023
[434]1024 Vector<Float> valuesOut(nChan);
1025 Vector<Bool> maskOut(nChan);
[177]1026
[434]1027// Get data slice bounds
1028
1029 IPosition start, end;
1030 setCursorSlice (start, end, doAll, in);
1031
[177]1032// Loop over rows in Table
1033
[434]1034 for (uInt ri=0; ri < in.nRow(); ++ri) {
[177]1035
[434]1036// Get slice of data
[177]1037
[434]1038 MaskedArray<Float> dataIn = in.rowAsMaskedArray(ri);
[177]1039
[434]1040// Deconstruct and get slices which reference these arrays
[177]1041
[434]1042 Array<Float> valuesIn = dataIn.getArray();
1043 Array<Bool> maskIn = dataIn.getMask();
[177]1044//
[434]1045 Array<Float> valuesIn2 = valuesIn(start,end); // ref to valuesIn
1046 Array<Bool> maskIn2 = maskIn(start,end);
[177]1047
[434]1048// Iterate through by spectra
[177]1049
[434]1050 VectorIterator<Float> itValues(valuesIn2, asap::ChanAxis);
1051 VectorIterator<Bool> itMask(maskIn2, asap::ChanAxis);
1052 while (!itValues.pastEnd()) {
1053
[177]1054// Smooth
1055
[434]1056 if (kernelType==VectorKernel::HANNING) {
1057 mathutil::hanning(valuesOut, maskOut, itValues.vector(), itMask.vector());
1058 itMask.vector() = maskOut;
1059 } else {
1060 mathutil::replaceMaskByZero(itValues.vector(), itMask.vector());
1061 conv.linearConv(valuesOut, itValues.vector());
1062 }
1063//
1064 itValues.vector() = valuesOut;
1065//
1066 itValues.next();
1067 itMask.next();
1068 }
[177]1069
1070// Create and put back
1071
[434]1072 SDContainer sc = in.getSDContainer(ri);
1073 putDataInSDC(sc, valuesIn, maskIn);
[177]1074//
[434]1075 pTabOut->putSDContainer(sc);
1076 }
[177]1077//
1078 return pTabOut;
1079}
1080
1081
[262]1082
[488]1083SDMemTable* SDMath::convertFlux(const SDMemTable& in, Float D, Float etaAp,
1084 Float JyPerK, Bool doAll) const
[221]1085//
[478]1086// etaAp = aperture efficiency (-1 means find)
1087// D = geometric diameter (m) (-1 means find)
[354]1088// JyPerK
[221]1089//
1090{
1091 SDHeader sh = in.getSDHeader();
1092 SDMemTable* pTabOut = new SDMemTable(in, True);
[177]1093
[354]1094// Find out how to convert values into Jy and K (e.g. units might be mJy or mK)
[221]1095// Also automatically find out what we are converting to according to the
1096// flux unit
[177]1097
[221]1098 Unit fluxUnit(sh.fluxunit);
1099 Unit K(String("K"));
1100 Unit JY(String("Jy"));
1101//
1102 Bool toKelvin = True;
[354]1103 Double cFac = 1.0;
[221]1104 if (fluxUnit==JY) {
[414]1105 cout << "Converting to K" << endl;
[221]1106//
1107 Quantum<Double> t(1.0,fluxUnit);
1108 Quantum<Double> t2 = t.get(JY);
[354]1109 cFac = (t2 / t).getValue(); // value to Jy
[221]1110//
1111 toKelvin = True;
1112 sh.fluxunit = "K";
1113 } else if (fluxUnit==K) {
[414]1114 cout << "Converting to Jy" << endl;
[221]1115//
1116 Quantum<Double> t(1.0,fluxUnit);
1117 Quantum<Double> t2 = t.get(K);
[354]1118 cFac = (t2 / t).getValue(); // value to K
[221]1119//
1120 toKelvin = False;
1121 sh.fluxunit = "Jy";
1122 } else {
[248]1123 throw(AipsError("Unrecognized brightness units in Table - must be consistent with Jy or K"));
[221]1124 }
1125 pTabOut->putSDHeader(sh);
[177]1126
[354]1127// Make sure input values are converted to either Jy or K first...
[221]1128
[354]1129 Float factor = cFac;
[221]1130
[354]1131// Select method
[221]1132
[354]1133 if (JyPerK>0.0) {
1134 factor *= JyPerK;
1135 if (toKelvin) factor = 1.0 / JyPerK;
1136//
[478]1137 cout << "Jy/K = " << JyPerK << endl;
[354]1138 Vector<Float> factors(in.nRow(), factor);
[480]1139 scaleByVector(pTabOut, in, doAll, factors, False);
[354]1140 } else if (etaAp>0.0) {
[478]1141 Bool throwIt = True;
1142 Instrument inst = SDAttr::convertInstrument (sh.antennaname, throwIt);
1143 SDAttr sda;
1144 if (D < 0) D = sda.diameter(inst);
1145 Float JyPerK = SDAttr::findJyPerK (etaAp,D);
1146 cout << "Jy/K = " << JyPerK << endl;
1147 factor *= JyPerK;
[354]1148 if (toKelvin) {
1149 factor = 1.0 / factor;
1150 }
1151//
1152 Vector<Float> factors(in.nRow(), factor);
[480]1153 scaleByVector(pTabOut, in, doAll, factors, False);
[354]1154 } else {
[221]1155
[354]1156// OK now we must deal with automatic look up of values.
1157// We must also deal with the fact that the factors need
1158// to be computed per IF and may be different and may
1159// change per integration.
[221]1160
[414]1161 cout << "Looking up conversion factors" << endl;
[354]1162 convertBrightnessUnits (pTabOut, in, toKelvin, cFac, doAll);
1163 }
[221]1164//
1165 return pTabOut;
1166}
1167
1168
[354]1169
1170
1171
[488]1172SDMemTable* SDMath::gainElevation(const SDMemTable& in,
1173 const Vector<Float>& coeffs,
1174 const String& fileName,
1175 const String& methodStr, Bool doAll) const
[227]1176{
[234]1177
1178// Get header and clone output table
1179
[227]1180 SDHeader sh = in.getSDHeader();
1181 SDMemTable* pTabOut = new SDMemTable(in, True);
1182
[234]1183// Get elevation data from SDMemTable and convert to degrees
[227]1184
1185 const Table& tab = in.table();
1186 ROScalarColumn<Float> elev(tab, "ELEVATION");
[234]1187 Vector<Float> x = elev.getColumn();
[363]1188 x *= Float(180 / C::pi); // Degrees
[227]1189//
[234]1190 const uInt nC = coeffs.nelements();
1191 if (fileName.length()>0 && nC>0) {
[248]1192 throw(AipsError("You must choose either polynomial coefficients or an ascii file, not both"));
[234]1193 }
1194
1195// Correct
1196
1197 if (nC>0 || fileName.length()==0) {
1198
1199// Find instrument
1200
1201 Bool throwIt = True;
[478]1202 Instrument inst = SDAttr::convertInstrument (sh.antennaname, throwIt);
[234]1203
1204// Set polynomial
1205
1206 Polynomial<Float>* pPoly = 0;
1207 Vector<Float> coeff;
1208 String msg;
1209 if (nC>0) {
1210 pPoly = new Polynomial<Float>(nC);
1211 coeff = coeffs;
1212 msg = String("user");
1213 } else {
[363]1214 SDAttr sdAttr;
1215 coeff = sdAttr.gainElevationPoly(inst);
1216 pPoly = new Polynomial<Float>(3);
[234]1217 msg = String("built in");
1218 }
[227]1219//
[234]1220 if (coeff.nelements()>0) {
1221 pPoly->setCoefficients(coeff);
1222 } else {
[363]1223 throw(AipsError("There is no known gain-elevation polynomial known for this instrument"));
[234]1224 }
1225//
[414]1226 cout << "Making polynomial correction with " << msg << " coefficients" << endl;
[234]1227 const uInt nRow = in.nRow();
1228 Vector<Float> factor(nRow);
1229 for (uInt i=0; i<nRow; i++) {
[480]1230 factor[i] = 1.0 / (*pPoly)(x[i]);
[234]1231 }
1232 delete pPoly;
1233//
[480]1234 scaleByVector (pTabOut, in, doAll, factor, True);
[234]1235 } else {
1236
1237// Indicate which columns to read from ascii file
1238
1239 String col0("ELEVATION");
1240 String col1("FACTOR");
1241
1242// Read and correct
1243
[414]1244 cout << "Making correction from ascii Table" << endl;
[480]1245 scaleFromAsciiTable (pTabOut, in, fileName, col0, col1,
1246 methodStr, doAll, x, True);
[234]1247 }
1248//
1249 return pTabOut;
[230]1250}
[227]1251
[230]1252
[227]1253
[488]1254SDMemTable* SDMath::opacity(const SDMemTable& in, Float tau, Bool doAll) const
[234]1255{
[227]1256
[234]1257// Get header and clone output table
[227]1258
[234]1259 SDHeader sh = in.getSDHeader();
1260 SDMemTable* pTabOut = new SDMemTable(in, True);
1261
1262// Get elevation data from SDMemTable and convert to degrees
1263
1264 const Table& tab = in.table();
1265 ROScalarColumn<Float> elev(tab, "ELEVATION");
1266 Vector<Float> zDist = elev.getColumn();
1267 zDist = Float(C::pi_2) - zDist;
1268
1269// Generate correction factor
1270
1271 const uInt nRow = in.nRow();
1272 Vector<Float> factor(nRow);
1273 Vector<Float> factor2(nRow);
1274 for (uInt i=0; i<nRow; i++) {
1275 factor[i] = exp(tau)/cos(zDist[i]);
1276 }
1277
1278// Correct
1279
[480]1280 scaleByVector (pTabOut, in, doAll, factor, True);
[234]1281//
1282 return pTabOut;
1283}
1284
1285
[488]1286void SDMath::rotateXYPhase(SDMemTable& in, Float value, Bool doAll)
[457]1287//
1288// phase in degrees
[518]1289// assumes linear correlations
[457]1290//
1291{
1292 if (in.nPol() != 4) {
1293 throw(AipsError("You must have 4 polarizations to run this function"));
1294 }
[518]1295//
1296 SDHeader sh = in.getSDHeader();
1297 Instrument inst = SDAttr::convertInstrument (sh.antennaname, False);
1298 SDAttr sdAtt;
1299 if (sdAtt.feedPolType(inst) != LINEAR) {
1300 throw(AipsError("Only linear polarizations are supported"));
1301 }
[457]1302//
1303 const Table& tabIn = in.table();
1304 ArrayColumn<Float> specCol(tabIn,"SPECTRA");
1305 IPosition start(asap::nAxes,0);
1306 IPosition end(asap::nAxes);
[234]1307
[457]1308// Set cursor slice. Assumes shape the same for all rows
1309
1310 setCursorSlice (start, end, doAll, in);
1311 IPosition start3(start);
1312 start3(asap::PolAxis) = 2; // Real(XY)
1313 IPosition end3(end);
1314 end3(asap::PolAxis) = 2;
1315//
1316 IPosition start4(start);
1317 start4(asap::PolAxis) = 3; // Imag (XY)
1318 IPosition end4(end);
1319 end4(asap::PolAxis) = 3;
1320//
1321 uInt nRow = in.nRow();
1322 Array<Float> data;
1323 for (uInt i=0; i<nRow;++i) {
1324 specCol.get(i,data);
1325 IPosition shape = data.shape();
1326
1327// Get polarization slice references
1328
1329 Array<Float> C3 = data(start3,end3);
1330 Array<Float> C4 = data(start4,end4);
1331
1332// Rotate
1333
[502]1334 SDPolUtil::rotatePhase(C3, C4, value);
[457]1335
1336// Put
1337
1338 specCol.put(i,data);
1339 }
1340}
[234]1341
[502]1342
1343
1344void SDMath::rotateLinPolPhase(SDMemTable& in, Float value, Bool doAll)
1345//
1346// phase in degrees
[518]1347// assumes linear correlations
[502]1348//
1349{
1350 if (in.nPol() != 4) {
1351 throw(AipsError("You must have 4 polarizations to run this function"));
1352 }
[518]1353//
1354 SDHeader sh = in.getSDHeader();
1355 Instrument inst = SDAttr::convertInstrument (sh.antennaname, False);
1356 SDAttr sdAtt;
1357 if (sdAtt.feedPolType(inst) != LINEAR) {
1358 throw(AipsError("Only linear polarizations are supported"));
1359 }
[502]1360//
1361 const Table& tabIn = in.table();
1362 ArrayColumn<Float> specCol(tabIn,"SPECTRA");
1363 ROArrayColumn<Float> stokesCol(tabIn,"STOKES");
1364 IPosition start(asap::nAxes,0);
1365 IPosition end(asap::nAxes);
1366
1367// Set cursor slice. Assumes shape the same for all rows
1368
1369 setCursorSlice (start, end, doAll, in);
1370//
1371 IPosition start1(start);
1372 start1(asap::PolAxis) = 0; // C1 (XX)
1373 IPosition end1(end);
1374 end1(asap::PolAxis) = 0;
1375//
1376 IPosition start2(start);
1377 start2(asap::PolAxis) = 1; // C2 (YY)
1378 IPosition end2(end);
1379 end2(asap::PolAxis) = 1;
1380//
1381 IPosition start3(start);
1382 start3(asap::PolAxis) = 2; // C3 ( Real(XY) )
1383 IPosition end3(end);
1384 end3(asap::PolAxis) = 2;
1385//
1386 IPosition startI(start);
1387 startI(asap::PolAxis) = 0; // I
1388 IPosition endI(end);
1389 endI(asap::PolAxis) = 0;
1390//
1391 IPosition startQ(start);
1392 startQ(asap::PolAxis) = 1; // Q
1393 IPosition endQ(end);
1394 endQ(asap::PolAxis) = 1;
1395//
1396 IPosition startU(start);
1397 startU(asap::PolAxis) = 2; // U
1398 IPosition endU(end);
1399 endU(asap::PolAxis) = 2;
1400
1401//
1402 uInt nRow = in.nRow();
1403 Array<Float> data, stokes;
1404 for (uInt i=0; i<nRow;++i) {
1405 specCol.get(i,data);
1406 stokesCol.get(i,stokes);
1407 IPosition shape = data.shape();
1408
1409// Get linear polarization slice references
1410
1411 Array<Float> C1 = data(start1,end1);
1412 Array<Float> C2 = data(start2,end2);
1413 Array<Float> C3 = data(start3,end3);
1414
1415// Get STokes slice references
1416
1417 Array<Float> I = stokes(startI,endI);
1418 Array<Float> Q = stokes(startQ,endQ);
1419 Array<Float> U = stokes(startU,endU);
1420
1421// Rotate
1422
1423 SDPolUtil::rotateLinPolPhase(C1, C2, C3, I, Q, U, value);
1424
1425// Put
1426
1427 specCol.put(i,data);
1428 }
1429}
1430
[169]1431// 'private' functions
1432
[354]1433void SDMath::convertBrightnessUnits (SDMemTable* pTabOut, const SDMemTable& in,
1434 Bool toKelvin, Float cFac, Bool doAll) const
1435{
[309]1436
[354]1437// Get header
1438
1439 SDHeader sh = in.getSDHeader();
1440 const uInt nChan = sh.nchan;
1441
1442// Get instrument
1443
1444 Bool throwIt = True;
[478]1445 Instrument inst = SDAttr::convertInstrument (sh.antennaname, throwIt);
[354]1446
1447// Get Diameter (m)
1448
1449 SDAttr sdAtt;
1450
1451// Get epoch of first row
1452
1453 MEpoch dateObs = in.getEpoch(0);
1454
1455// Generate a Vector of correction factors. One per FreqID
1456
1457 SDFrequencyTable sdft = in.getSDFreqTable();
1458 Vector<uInt> freqIDs;
1459//
1460 Vector<Float> freqs(sdft.length());
1461 for (uInt i=0; i<sdft.length(); i++) {
1462 freqs(i) = (nChan/2 - sdft.referencePixel(i))*sdft.increment(i) + sdft.referenceValue(i);
1463 }
1464//
1465 Vector<Float> JyPerK = sdAtt.JyPerK(inst, dateObs, freqs);
[414]1466 cout << "Jy/K = " << JyPerK << endl;
[354]1467 Vector<Float> factors = cFac * JyPerK;
1468 if (toKelvin) factors = Float(1.0) / factors;
1469
[434]1470// Get data slice bounds
[354]1471
1472 IPosition start, end;
[434]1473 setCursorSlice (start, end, doAll, in);
[354]1474 const uInt ifAxis = in.getIF();
1475
1476// Iteration axes
1477
1478 IPosition axes(asap::nAxes-1,0);
1479 for (uInt i=0,j=0; i<asap::nAxes; i++) {
1480 if (i!=asap::IFAxis) {
1481 axes(j++) = i;
1482 }
1483 }
1484
1485// Loop over rows and apply correction factor
1486
1487 Float factor = 1.0;
1488 const uInt axis = asap::ChanAxis;
1489 for (uInt i=0; i < in.nRow(); ++i) {
1490
1491// Get data
1492
[434]1493 MaskedArray<Float> dataIn = in.rowAsMaskedArray(i);
1494 Array<Float>& values = dataIn.getRWArray(); // Ref to dataIn
1495 Array<Float> values2 = values(start,end); // Ref to values to dataIn
[354]1496
1497// Get SDCOntainer
1498
1499 SDContainer sc = in.getSDContainer(i);
1500
1501// Get FreqIDs
1502
1503 freqIDs = sc.getFreqMap();
1504
1505// Now the conversion factor depends only upon frequency
1506// So we need to iterate through by IF only giving
1507// us BEAM/POL/CHAN cubes
1508
[434]1509 ArrayIterator<Float> itIn(values2, axes);
1510 uInt ax = 0;
1511 while (!itIn.pastEnd()) {
1512 itIn.array() *= factors(freqIDs(ax)); // Writes back to dataIn
1513 itIn.next();
[354]1514 }
1515
1516// Write out
1517
1518 putDataInSDC(sc, dataIn.getArray(), dataIn.getMask());
1519//
1520 pTabOut->putSDContainer(sc);
1521 }
1522}
1523
1524
1525
[309]1526SDMemTable* SDMath::frequencyAlign (const SDMemTable& in,
1527 MFrequency::Types freqSystem,
[397]1528 const String& refTime,
1529 const String& methodStr,
1530 Bool perFreqID) const
[267]1531{
1532// Get Header
1533
1534 SDHeader sh = in.getSDHeader();
1535 const uInt nChan = sh.nchan;
1536 const uInt nRows = in.nRow();
[330]1537 const uInt nIF = sh.nif;
[267]1538
1539// Get Table reference
1540
1541 const Table& tabIn = in.table();
1542
1543// Get Columns from Table
1544
[294]1545 ROScalarColumn<Double> mjdCol(tabIn, "TIME");
1546 ROScalarColumn<String> srcCol(tabIn, "SRCNAME");
1547 ROArrayColumn<uInt> fqIDCol(tabIn, "FREQID");
1548 Vector<Double> times = mjdCol.getColumn();
[267]1549
[397]1550// Generate DataDesc table
[330]1551
1552 Matrix<uInt> ddIdx;
1553 SDDataDesc dDesc;
[397]1554 generateDataDescTable (ddIdx, dDesc, nIF, in, tabIn, srcCol, fqIDCol, perFreqID);
[267]1555
[294]1556// Get reference Epoch to time of first row or given String
[267]1557
1558 Unit DAY(String("d"));
[272]1559 MEpoch::Ref epochRef(in.getTimeReference());
1560 MEpoch refEpoch;
1561 if (refTime.length()>0) {
1562 refEpoch = epochFromString(refTime, in.getTimeReference());
1563 } else {
[288]1564 refEpoch = in.getEpoch(0);
[272]1565 }
[414]1566 cout << "Aligning at reference Epoch " << formatEpoch(refEpoch)
1567 << " in frame " << MFrequency::showType(freqSystem) << endl;
1568
[294]1569// Get Reference Position
[267]1570
[288]1571 MPosition refPos = in.getAntennaPosition();
[267]1572
[397]1573// Create FrequencyAligner Block. One FA for each possible
1574// source/freqID (perFreqID=True) or source/IF (perFreqID=False) combination
[267]1575
[330]1576 PtrBlock<FrequencyAligner<Float>* > a(dDesc.length());
[397]1577 generateFrequencyAligners (a, dDesc, in, nChan, freqSystem, refPos,
1578 refEpoch, perFreqID);
[267]1579
[397]1580// Generate and fill output Frequency Table. WHen perFreqID=True, there is one output FreqID
1581// for each entry in the SDDataDesc table. However, in perFreqID=False mode, there may be
1582// some degeneracy, so we need a little translation map
[330]1583
1584 SDFrequencyTable freqTabOut = in.getSDFreqTable();
1585 freqTabOut.setLength(0);
1586 Vector<String> units(1);
1587 units = String("Hz");
1588 Bool linear=True;
1589//
[397]1590 Vector<uInt> ddFQTrans(dDesc.length(),0);
[330]1591 for (uInt i=0; i<dDesc.length(); i++) {
1592
1593// Get Aligned SC in Hz
1594
1595 SpectralCoordinate sC = a[i]->alignedSpectralCoordinate(linear);
1596 sC.setWorldAxisUnits(units);
1597
1598// Add FreqID
1599
[397]1600 uInt idx = freqTabOut.addFrequency(sC.referencePixel()[0],
1601 sC.referenceValue()[0],
1602 sC.increment()[0]);
1603 ddFQTrans(i) = idx; // output FreqID = ddFQTrans(ddIdx)
[330]1604 }
1605
[317]1606// Interpolation method
1607
1608 InterpolateArray1D<Double,Float>::InterpolationMethod interp;
1609 convertInterpString(interp, methodStr);
1610
[267]1611// New output Table
1612
[414]1613 cout << "Create output table" << endl;
[267]1614 SDMemTable* pTabOut = new SDMemTable(in,True);
[330]1615 pTabOut->putSDFreqTable(freqTabOut);
[267]1616
1617// Loop over rows in Table
1618
[330]1619 Bool extrapolate=False;
[294]1620 const IPosition polChanAxes(2, asap::PolAxis, asap::ChanAxis);
1621 Bool useCachedAbcissa = False;
1622 Bool first = True;
1623 Bool ok;
1624 Vector<Float> yOut;
1625 Vector<Bool> maskOut;
[330]1626 Vector<uInt> freqID(nIF);
[309]1627 uInt ifIdx, faIdx;
[397]1628 Vector<Double> xIn;
[267]1629//
[294]1630 for (uInt iRow=0; iRow<nRows; ++iRow) {
1631 if (iRow%10==0) {
[414]1632 cout << "Processing row " << iRow << endl;
[294]1633 }
[267]1634
1635// Get EPoch
1636
[294]1637 Quantum<Double> tQ2(times[iRow],DAY);
1638 MVEpoch mv2(tQ2);
1639 MEpoch epoch(mv2, epochRef);
[267]1640
1641// Get copy of data
1642
[294]1643 const MaskedArray<Float>& mArrIn(in.rowAsMaskedArray(iRow));
1644 Array<Float> values = mArrIn.getArray();
1645 Array<Bool> mask = mArrIn.getMask();
[267]1646
[309]1647// For each row, the Frequency abcissa will be the same regardless
[267]1648// of polarization. For all other axes (IF and BEAM) the abcissa
1649// will change. So we iterate through the data by pol-chan planes
[330]1650// to mimimize the work. Probably won't work for multiple beams
1651// at this point.
[267]1652
[294]1653 ArrayIterator<Float> itValuesPlane(values, polChanAxes);
1654 ArrayIterator<Bool> itMaskPlane(mask, polChanAxes);
1655 while (!itValuesPlane.pastEnd()) {
[267]1656
[309]1657// Find the IF index and then the FA PtrBlock index
[267]1658
[294]1659 const IPosition& pos = itValuesPlane.pos();
1660 ifIdx = pos(asap::IFAxis);
[330]1661 faIdx = ddIdx(iRow,ifIdx);
[397]1662
1663// Generate abcissa for perIF. Could cache this in a Matrix
1664// on a per scan basis. Pretty expensive doing it for every row.
1665
1666 if (!perFreqID) {
1667 xIn.resize(nChan);
1668 uInt fqID = dDesc.secID(ddIdx(iRow,ifIdx));
1669 SpectralCoordinate sC = in.getSpectralCoordinate(fqID);
1670 Double w;
1671 for (uInt i=0; i<nChan; i++) {
1672 sC.toWorld(w,Double(i));
1673 xIn[i] = w;
1674 }
1675 }
[267]1676//
[294]1677 VectorIterator<Float> itValuesVec(itValuesPlane.array(), 1);
1678 VectorIterator<Bool> itMaskVec(itMaskPlane.array(), 1);
[330]1679
1680// Iterate through the plane by vector and align
1681
[294]1682 first = True;
1683 useCachedAbcissa=False;
1684 while (!itValuesVec.pastEnd()) {
[397]1685 if (perFreqID) {
1686 ok = a[faIdx]->align (yOut, maskOut, itValuesVec.vector(),
1687 itMaskVec.vector(), epoch, useCachedAbcissa,
1688 interp, extrapolate);
1689 } else {
1690 ok = a[faIdx]->align (yOut, maskOut, xIn, itValuesVec.vector(),
1691 itMaskVec.vector(), epoch, useCachedAbcissa,
1692 interp, extrapolate);
1693 }
[330]1694//
[294]1695 itValuesVec.vector() = yOut;
1696 itMaskVec.vector() = maskOut;
[267]1697//
[294]1698 itValuesVec.next();
1699 itMaskVec.next();
[267]1700//
[294]1701 if (first) {
1702 useCachedAbcissa = True;
1703 first = False;
1704 }
1705 }
[267]1706//
1707 itValuesPlane.next();
1708 itMaskPlane.next();
[294]1709 }
[267]1710
[330]1711// Create SDContainer and put back
[267]1712
1713 SDContainer sc = in.getSDContainer(iRow);
1714 putDataInSDC(sc, values, mask);
[397]1715
1716// Set output FreqIDs
1717
[330]1718 for (uInt i=0; i<nIF; i++) {
[397]1719 uInt idx = ddIdx(iRow,i); // Index into SDDataDesc table
1720 freqID(i) = ddFQTrans(idx); // FreqID in output FQ table
[330]1721 }
1722 sc.putFreqMap(freqID);
[267]1723//
1724 pTabOut->putSDContainer(sc);
[294]1725 }
[267]1726
[309]1727// Now we must set the base and extra frames to the
1728// input frame
1729
1730 std::vector<string> info = pTabOut->getCoordInfo();
1731 info[1] = MFrequency::showType(freqSystem); // Conversion frame
1732 info[3] = info[1]; // Base frame
1733 pTabOut->setCoordInfo(info);
1734
[267]1735// Clean up PointerBlock
1736
[309]1737 for (uInt i=0; i<a.nelements(); i++) delete a[i];
[267]1738//
[309]1739 return pTabOut;
[267]1740}
1741
1742
[185]1743void SDMath::fillSDC(SDContainer& sc,
1744 const Array<Bool>& mask,
1745 const Array<Float>& data,
1746 const Array<Float>& tSys,
1747 Int scanID, Double timeStamp,
1748 Double interval, const String& sourceName,
[227]1749 const Vector<uInt>& freqID) const
[167]1750{
[169]1751// Data and mask
[167]1752
[185]1753 putDataInSDC(sc, data, mask);
[167]1754
[169]1755// TSys
1756
1757 sc.putTsys(tSys);
1758
1759// Time things
1760
1761 sc.timestamp = timeStamp;
1762 sc.interval = interval;
1763 sc.scanid = scanID;
[167]1764//
[169]1765 sc.sourcename = sourceName;
1766 sc.putFreqMap(freqID);
1767}
[167]1768
[185]1769void SDMath::accumulate(Double& timeSum, Double& intSum, Int& nAccum,
1770 MaskedArray<Float>& sum, Array<Float>& sumSq,
1771 Array<Float>& nPts, Array<Float>& tSysSum,
[518]1772 Array<Float>& tSysSqSum,
[185]1773 const Array<Float>& tSys, const Array<Float>& nInc,
1774 const Vector<Bool>& mask, Double time, Double interval,
1775 const Block<CountedPtr<SDMemTable> >& in,
1776 uInt iTab, uInt iRow, uInt axis,
1777 uInt nAxesSub, Bool useMask,
[227]1778 WeightType wtType) const
[169]1779{
1780
1781// Get data
1782
1783 MaskedArray<Float> dataIn(in[iTab]->rowAsMaskedArray(iRow));
1784 Array<Float>& valuesIn = dataIn.getRWArray(); // writable reference
1785 const Array<Bool>& maskIn = dataIn.getMask(); // RO reference
[167]1786//
[169]1787 if (wtType==NONE) {
1788 const MaskedArray<Float> n(nInc,dataIn.getMask());
1789 nPts += n; // Only accumulates where mask==T
[518]1790 } else if (wtType==TINT) {
1791
1792// We are weighting the data by integration time.
1793
1794 valuesIn *= Float(interval);
1795
[169]1796 } else if (wtType==VAR) {
[167]1797
[169]1798// We are going to average the data, weighted by the noise for each pol, beam and IF.
1799// So therefore we need to iterate through by spectrum (axis 3)
[167]1800
[169]1801 VectorIterator<Float> itData(valuesIn, axis);
1802 ReadOnlyVectorIterator<Bool> itMask(maskIn, axis);
1803 Float fac = 1.0;
1804 IPosition pos(nAxesSub,0);
1805//
1806 while (!itData.pastEnd()) {
[167]1807
[169]1808// Make MaskedArray of Vector, optionally apply OTF mask, and find scaling factor
[167]1809
[518]1810 if (useMask) {
1811 MaskedArray<Float> tmp(itData.vector(),mask&&itMask.vector());
1812 fac = 1.0/variance(tmp);
1813 } else {
1814 MaskedArray<Float> tmp(itData.vector(),itMask.vector());
1815 fac = 1.0/variance(tmp);
1816 }
[169]1817
1818// Scale data
1819
[518]1820 itData.vector() *= fac; // Writes back into 'dataIn'
[167]1821//
[169]1822// Accumulate variance per if/pol/beam averaged over spectrum
1823// This method to get pos2 from itData.pos() is only valid
1824// because the spectral axis is the last one (so we can just
1825// copy the first nAXesSub positions out)
[167]1826
[518]1827 pos = itData.pos().getFirst(nAxesSub);
1828 sumSq(pos) += fac;
[169]1829//
[518]1830 itData.next();
1831 itMask.next();
[169]1832 }
[536]1833 } else if (wtType==TSYS || wtType==TINTSYS) {
[518]1834
1835// We are going to average the data, weighted by 1/Tsys**2 for each pol, beam and IF.
1836// So therefore we need to iterate through by spectrum (axis 3). Although
1837// Tsys is stored as a vector of length nChan, the values are replicated.
1838// We will take a short cut and just use the value from the first channel
1839// for now.
1840//
1841 VectorIterator<Float> itData(valuesIn, axis);
1842 ReadOnlyVectorIterator<Float> itTSys(tSys, axis);
1843 IPosition pos(nAxesSub,0);
1844//
[536]1845 Float fac = 1.0;
1846 if (wtType==TINTSYS) fac *= interval;
[518]1847 while (!itData.pastEnd()) {
1848 Float t = itTSys.vector()[0];
[536]1849 fac *= 1.0/t/t;
[518]1850
1851// Scale data
1852
1853 itData.vector() *= fac; // Writes back into 'dataIn'
1854//
1855// Accumulate Tsys per if/pol/beam averaged over spectrum
1856// This method to get pos2 from itData.pos() is only valid
1857// because the spectral axis is the last one (so we can just
1858// copy the first nAXesSub positions out)
1859
1860 pos = itData.pos().getFirst(nAxesSub);
1861 tSysSqSum(pos) += fac;
1862//
1863 itData.next();
1864 itTSys.next();
1865 }
[169]1866 }
[167]1867
[169]1868// Accumulate sum of (possibly scaled) data
1869
1870 sum += dataIn;
1871
1872// Accumulate Tsys, time, and interval
1873
1874 tSysSum += tSys;
1875 timeSum += time;
1876 intSum += interval;
1877 nAccum += 1;
1878}
1879
1880
[518]1881void SDMath::normalize(MaskedArray<Float>& sum,
1882 const Array<Float>& sumSq,
1883 const Array<Float>& tSysSqSum,
1884 const Array<Float>& nPts,
1885 Double intSum,
1886 WeightType wtType, Int axis,
1887 Int nAxesSub) const
1888{
1889 IPosition pos2(nAxesSub,0);
1890//
1891 if (wtType==NONE) {
1892
1893// We just average by the number of points accumulated.
1894// We need to make a MA out of nPts so that no divide by
1895// zeros occur
1896
1897 MaskedArray<Float> t(nPts, (nPts>Float(0.0)));
1898 sum /= t;
1899 } else if (wtType==TINT) {
1900
1901// Average by sum of Tint
1902
1903 sum /= Float(intSum);
1904 } else if (wtType==VAR) {
1905
1906// Normalize each spectrum by sum(1/var) where the variance
1907// is worked out for each spectrum
1908
1909 Array<Float>& data = sum.getRWArray();
1910 VectorIterator<Float> itData(data, axis);
1911 while (!itData.pastEnd()) {
1912 pos2 = itData.pos().getFirst(nAxesSub);
1913 itData.vector() /= sumSq(pos2);
1914 itData.next();
1915 }
[536]1916 } else if (wtType==TSYS || wtType==TINTSYS) {
[518]1917
[536]1918// Normalize each spectrum by sum(1/Tsys**2) (TSYS) or
1919// sum(Tint/Tsys**2) (TINTSYS) where the pseudo
[518]1920// replication over channel for Tsys has been dropped.
1921
1922 Array<Float>& data = sum.getRWArray();
1923 VectorIterator<Float> itData(data, axis);
1924 while (!itData.pastEnd()) {
1925 pos2 = itData.pos().getFirst(nAxesSub);
1926 itData.vector() /= tSysSqSum(pos2);
1927 itData.next();
1928 }
1929 }
1930}
1931
1932
1933
1934
[434]1935void SDMath::setCursorSlice (IPosition& start, IPosition& end, Bool doAll, const SDMemTable& in) const
[169]1936{
[434]1937 const uInt nDim = asap::nAxes;
1938 DebugAssert(nDim==4,AipsError);
[167]1939//
[169]1940 start.resize(nDim);
[434]1941 end.resize(nDim);
1942 if (doAll) {
1943 start = 0;
1944 end(0) = in.nBeam()-1;
1945 end(1) = in.nIF()-1;
1946 end(2) = in.nPol()-1;
1947 end(3) = in.nChan()-1;
1948 } else {
1949 start(0) = in.getBeam();
1950 end(0) = start(0);
[167]1951//
[434]1952 start(1) = in.getIF();
1953 end(1) = start(1);
1954//
1955 start(2) = in.getPol();
1956 end(2) = start(2);
1957//
1958 start(3) = 0;
1959 end(3) = in.nChan()-1;
1960 }
[169]1961}
1962
1963
[518]1964void SDMath::convertWeightString(WeightType& wtType, const String& weightStr,
1965 Bool listType) const
[169]1966{
1967 String tStr(weightStr);
1968 tStr.upcase();
[518]1969 String msg;
[169]1970 if (tStr.contains(String("NONE"))) {
1971 wtType = NONE;
[518]1972 msg = String("Weighting type selected : None");
[169]1973 } else if (tStr.contains(String("VAR"))) {
1974 wtType = VAR;
[518]1975 msg = String("Weighting type selected : Variance");
[536]1976 } else if (tStr.contains(String("TINTSYS"))) {
1977 wtType = TINTSYS;
1978 msg = String("Weighting type selected : Tint&Tsys");
[518]1979 } else if (tStr.contains(String("TINT"))) {
1980 wtType = TINT;
[519]1981 msg = String("Weighting type selected : Tint");
[169]1982 } else if (tStr.contains(String("TSYS"))) {
1983 wtType = TSYS;
[518]1984 msg = String("Weighting type selected : Tsys");
[169]1985 } else {
[518]1986 msg = String("Weighting type selected : None");
1987 throw(AipsError("Unrecognized weighting type"));
[167]1988 }
[518]1989//
1990 if (listType) cout << msg << endl;
[167]1991}
1992
[317]1993
1994void SDMath::convertInterpString(casa::InterpolateArray1D<Double,Float>::InterpolationMethod& type,
1995 const casa::String& interp) const
[227]1996{
1997 String tStr(interp);
1998 tStr.upcase();
1999 if (tStr.contains(String("NEAR"))) {
[317]2000 type = InterpolateArray1D<Double,Float>::nearestNeighbour;
[227]2001 } else if (tStr.contains(String("LIN"))) {
[317]2002 type = InterpolateArray1D<Double,Float>::linear;
[227]2003 } else if (tStr.contains(String("CUB"))) {
[317]2004 type = InterpolateArray1D<Double,Float>::cubic;
[227]2005 } else if (tStr.contains(String("SPL"))) {
[317]2006 type = InterpolateArray1D<Double,Float>::spline;
[227]2007 } else {
2008 throw(AipsError("Unrecognized interpolation type"));
2009 }
2010}
2011
[185]2012void SDMath::putDataInSDC(SDContainer& sc, const Array<Float>& data,
[227]2013 const Array<Bool>& mask) const
[169]2014{
2015 sc.putSpectrum(data);
2016//
2017 Array<uChar> outflags(data.shape());
2018 convertArray(outflags,!mask);
2019 sc.putFlags(outflags);
2020}
[227]2021
2022Table SDMath::readAsciiFile (const String& fileName) const
2023{
[230]2024 String formatString;
2025 Table tbl = readAsciiTable (formatString, Table::Memory, fileName, "", "", False);
[227]2026 return tbl;
2027}
[230]2028
2029
[234]2030
[480]2031void SDMath::scaleFromAsciiTable(SDMemTable* pTabOut,
2032 const SDMemTable& in, const String& fileName,
2033 const String& col0, const String& col1,
2034 const String& methodStr, Bool doAll,
2035 const Vector<Float>& xOut, Bool doTSys) const
[230]2036{
2037
2038// Read gain-elevation ascii file data into a Table.
2039
[234]2040 Table geTable = readAsciiFile (fileName);
[230]2041//
[480]2042 scaleFromTable (pTabOut, in, geTable, col0, col1, methodStr, doAll, xOut, doTSys);
[230]2043}
2044
[480]2045void SDMath::scaleFromTable(SDMemTable* pTabOut, const SDMemTable& in,
2046 const Table& tTable, const String& col0,
2047 const String& col1,
2048 const String& methodStr, Bool doAll,
2049 const Vector<Float>& xOut, Bool doTsys) const
[230]2050{
2051
2052// Get data from Table
2053
2054 ROScalarColumn<Float> geElCol(tTable, col0);
2055 ROScalarColumn<Float> geFacCol(tTable, col1);
2056 Vector<Float> xIn = geElCol.getColumn();
2057 Vector<Float> yIn = geFacCol.getColumn();
2058 Vector<Bool> maskIn(xIn.nelements(),True);
2059
2060// Interpolate (and extrapolate) with desired method
2061
[317]2062 InterpolateArray1D<Double,Float>::InterpolationMethod method;
[230]2063 convertInterpString(method, methodStr);
[317]2064 Int intMethod(method);
[230]2065//
2066 Vector<Float> yOut;
2067 Vector<Bool> maskOut;
2068 InterpolateArray1D<Float,Float>::interpolate(yOut, maskOut, xOut,
[317]2069 xIn, yIn, maskIn, intMethod,
[230]2070 True, True);
[234]2071// Apply
[230]2072
[480]2073 scaleByVector(pTabOut, in, doAll, Float(1.0)/yOut, doTsys);
[234]2074}
2075
2076
[480]2077void SDMath::scaleByVector(SDMemTable* pTabOut, const SDMemTable& in,
2078 Bool doAll, const Vector<Float>& factor,
2079 Bool doTSys) const
[234]2080{
[270]2081
[434]2082// Set up data slice
[230]2083
2084 IPosition start, end;
[434]2085 setCursorSlice (start, end, doAll, in);
[230]2086
[480]2087// Get Tsys column
2088
2089 const Table& tIn = in.table();
2090 ArrayColumn<Float> tSysCol(tIn, "TSYS");
2091 Array<Float> tSys;
2092
[270]2093// Loop over rows and apply correction factor
[230]2094
2095 const uInt axis = asap::ChanAxis;
2096 for (uInt i=0; i < in.nRow(); ++i) {
2097
2098// Get data
2099
[434]2100 MaskedArray<Float> dataIn(in.rowAsMaskedArray(i));
2101 MaskedArray<Float> dataIn2 = dataIn(start,end); // reference to dataIn
[480]2102//
2103 if (doTSys) {
2104 tSysCol.get(i, tSys);
2105 Array<Float> tSys2 = tSys(start,end) * factor[i];
2106 tSysCol.put(i, tSys);
2107 }
[230]2108
2109// Apply factor
2110
[434]2111 dataIn2 *= factor[i];
[230]2112
2113// Write out
2114
[434]2115 SDContainer sc = in.getSDContainer(i);
2116 putDataInSDC(sc, dataIn.getArray(), dataIn.getMask());
[230]2117//
[434]2118 pTabOut->putSDContainer(sc);
[230]2119 }
2120}
2121
[234]2122
[262]2123
2124
[330]2125void SDMath::generateDataDescTable (Matrix<uInt>& ddIdx,
2126 SDDataDesc& dDesc,
2127 uInt nIF,
2128 const SDMemTable& in,
2129 const Table& tabIn,
2130 const ROScalarColumn<String>& srcCol,
[397]2131 const ROArrayColumn<uInt>& fqIDCol,
2132 Bool perFreqID) const
[330]2133{
2134 const uInt nRows = tabIn.nrow();
2135 ddIdx.resize(nRows,nIF);
[262]2136//
[330]2137 String srcName;
2138 Vector<uInt> freqIDs;
2139 for (uInt iRow=0; iRow<nRows; iRow++) {
2140 srcCol.get(iRow, srcName);
2141 fqIDCol.get(iRow, freqIDs);
2142 const MDirection& dir = in.getDirection(iRow);
2143//
[397]2144 if (perFreqID) {
2145
2146// One entry per source/freqID pair
2147
2148 for (uInt iIF=0; iIF<nIF; iIF++) {
2149 ddIdx(iRow,iIF) = dDesc.addEntry(srcName, freqIDs[iIF], dir, 0);
2150 }
2151 } else {
2152
2153// One entry per source/IF pair. Hang onto the FreqID as well
2154
2155 for (uInt iIF=0; iIF<nIF; iIF++) {
2156 ddIdx(iRow,iIF) = dDesc.addEntry(srcName, iIF, dir, freqIDs[iIF]);
2157 }
[262]2158 }
2159 }
2160}
[272]2161
[397]2162
2163
2164
2165
[272]2166MEpoch SDMath::epochFromString (const String& str, MEpoch::Types timeRef) const
2167{
2168 Quantum<Double> qt;
2169 if (MVTime::read(qt,str)) {
2170 MVEpoch mv(qt);
2171 MEpoch me(mv, timeRef);
2172 return me;
2173 } else {
2174 throw(AipsError("Invalid format for Epoch string"));
2175 }
2176}
2177
2178
2179String SDMath::formatEpoch(const MEpoch& epoch) const
2180{
2181 MVTime mvt(epoch.getValue());
2182 return mvt.string(MVTime::YMD) + String(" (") + epoch.getRefString() + String(")");
2183}
2184
[294]2185
[309]2186
2187void SDMath::generateFrequencyAligners (PtrBlock<FrequencyAligner<Float>* >& a,
[330]2188 const SDDataDesc& dDesc,
2189 const SDMemTable& in, uInt nChan,
2190 MFrequency::Types system,
2191 const MPosition& refPos,
[397]2192 const MEpoch& refEpoch,
2193 Bool perFreqID) const
[294]2194{
[330]2195 for (uInt i=0; i<dDesc.length(); i++) {
[397]2196 uInt ID = dDesc.ID(i);
2197 uInt secID = dDesc.secID(i);
2198 const MDirection& refDir = dDesc.secDir(i);
[330]2199//
[397]2200 if (perFreqID) {
2201
2202// One aligner per source/FreqID pair.
2203
2204 SpectralCoordinate sC = in.getSpectralCoordinate(ID);
2205 a[i] = new FrequencyAligner<Float>(sC, nChan, refEpoch, refDir, refPos, system);
2206 } else {
2207
2208// One aligner per source/IF pair. But we still need the FreqID to
2209// get the right SC. Hence the messing about with the secondary ID
2210
2211 SpectralCoordinate sC = in.getSpectralCoordinate(secID);
2212 a[i] = new FrequencyAligner<Float>(sC, nChan, refEpoch, refDir, refPos, system);
2213 }
[294]2214 }
2215}
[480]2216
2217Vector<uInt> SDMath::getRowRange (const SDMemTable& in) const
2218{
2219 Vector<uInt> range(2);
2220 range[0] = 0;
2221 range[1] = in.nRow()-1;
2222 return range;
2223}
2224
2225
2226Bool SDMath::rowInRange (uInt i, const Vector<uInt>& range) const
2227{
2228 return (i>=range[0] && i<=range[1]);
2229}
Note: See TracBrowser for help on using the repository browser.