source: trunk/src/SDMath.cc@ 535

Last change on this file since 535 was 532, checked in by kil064, 20 years ago

add Tsys weighting to average_pol

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