source: trunk/src/SDMath.cc@ 292

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

track changes to enum SDDefs::Instrument

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