source: trunk/src/SDMath.cc@ 300

Last change on this file since 300 was 299, checked in by kil064, 20 years ago

add resample function

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