source: trunk/src/SDMath.cc @ 245

Last change on this file since 245 was 244, checked in by kil064, 19 years ago

Add arg 'preserve' to quotient method to preserve continuum (or not)

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