source: branches/Release-2-fixes/src/SDMath.cc@ 2897

Last change on this file since 2897 was 699, checked in by mar637, 19 years ago

whitespace tidy

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