source: trunk/src/SDMath.cc@ 292

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

track changes to enum SDDefs::Instrument

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