source: trunk/src/SDMath.cc@ 498

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