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

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

whitespace tidy

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