source: trunk/src/SDMath.cc@ 460

Last change on this file since 460 was 457, checked in by kil064, 20 years ago

move SDMemTable::rotateXYPhase to SDMath

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