source: trunk/src/SDMath.cc @ 291

Last change on this file since 291 was 288, checked in by kil064, 19 years ago

track changes to SDMemTable interfgace

  • 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==PKSMULTIBEAM) {
1019        } else if (inst==PKSSINGLEBEAM) {
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==MOPRA) {
1027        }
1028        msg = String("built in");
1029     }
1030//
1031     if (coeff.nelements()>0) {
1032        pPoly->setCoefficients(coeff);
1033     } else {
1034        throw(AipsError("There is no known gain-el polynomial known for this instrument"));
1035     }
1036//
1037     cerr << "Making polynomial correction with " << msg << " coefficients" << endl;
1038     const uInt nRow = in.nRow();
1039     Vector<Float> factor(nRow);
1040     for (uInt i=0; i<nRow; i++) {
1041        factor[i] = (*pPoly)(x[i]);
1042     }
1043     delete pPoly;
1044//
1045     correctFromVector (pTabOut, in, doAll, factor);
1046  } else {
1047
1048// Indicate which columns to read from ascii file
1049
1050     String col0("ELEVATION");
1051     String col1("FACTOR");
1052
1053// Read and correct
1054
1055     cerr << "Making correction from ascii Table" << endl;
1056     correctFromAsciiTable (pTabOut, in, fileName, col0, col1,
1057                            methodStr, doAll, x);
1058   }
1059//
1060   return pTabOut;
1061}
1062
1063 
1064
1065SDMemTable* SDMath::opacity (const SDMemTable& in, Float tau, Bool doAll) const
1066{
1067
1068// Get header and clone output table
1069
1070  SDHeader sh = in.getSDHeader();
1071  SDMemTable* pTabOut = new SDMemTable(in, True);
1072
1073// Get elevation data from SDMemTable and convert to degrees
1074
1075  const Table& tab = in.table();
1076  ROScalarColumn<Float> elev(tab, "ELEVATION");
1077  Vector<Float> zDist = elev.getColumn();
1078  zDist = Float(C::pi_2) - zDist;
1079
1080// Generate correction factor
1081
1082  const uInt nRow = in.nRow();
1083  Vector<Float> factor(nRow);
1084  Vector<Float> factor2(nRow);
1085  for (uInt i=0; i<nRow; i++) {
1086     factor[i] = exp(tau)/cos(zDist[i]);
1087  }
1088
1089// Correct
1090
1091  correctFromVector (pTabOut, in, doAll, factor);
1092//
1093  return pTabOut;
1094}
1095
1096
1097
1098
1099// 'private' functions
1100
1101SDMemTable* SDMath::velocityAlign (const SDMemTable& in,
1102                                   MFrequency::Types velSystem,
1103                                   const String& velUnit,
1104                                   MDoppler::Types doppler,
1105                                   const String& refTime) const
1106{
1107// Get Header
1108
1109   SDHeader sh = in.getSDHeader();
1110   const uInt nChan = sh.nchan;
1111   const uInt nRows = in.nRow();
1112
1113// Get Table reference
1114
1115   const Table& tabIn = in.table();
1116
1117// Get Columns from Table
1118
1119  ROScalarColumn<Double> mjdCol(tabIn, "TIME");
1120  ROScalarColumn<String> srcCol(tabIn, "SRCNAME");
1121  ROArrayColumn<uInt> fqIDCol(tabIn, "FREQID");
1122//
1123  Vector<Double> times = mjdCol.getColumn();
1124  Vector<String> srcNames = srcCol.getColumn();
1125  Vector<uInt> freqID;
1126
1127// Generate Source table
1128
1129   Vector<String> srcTab;
1130   Vector<uInt> srcIdx, firstRow;
1131   generateSourceTable (srcTab, srcIdx, firstRow, srcNames);
1132   const uInt nSrcTab = srcTab.nelements();
1133   cerr << "Found " << srcTab.nelements() << " sources to align " << endl;
1134
1135// Set reference Epoch to time of first row or given String
1136
1137   Unit DAY(String("d"));
1138   MEpoch::Ref epochRef(in.getTimeReference());
1139   MEpoch refEpoch;
1140   if (refTime.length()>0) {
1141      refEpoch = epochFromString(refTime, in.getTimeReference());
1142   } else {
1143      refEpoch = in.getEpoch(0);
1144   }
1145   cerr << "Aligning at reference Epoch " << formatEpoch(refEpoch) << endl;
1146
1147// Set Reference Position
1148
1149   MPosition refPos = in.getAntennaPosition();
1150
1151// Get Frequency Table
1152
1153   SDFrequencyTable fTab = in.getSDFreqTable();
1154   const uInt nFreqIDs = fTab.length();
1155
1156// Create VelocityAligner Block. One VA for each possible
1157// source/freqID combination
1158
1159   PtrBlock<VelocityAligner<Float>* > vA(nFreqIDs*nSrcTab);
1160   for (uInt fqID=0; fqID<nFreqIDs; fqID++) {
1161      SpectralCoordinate sC = in.getSpectralCoordinate(fqID);
1162      for (uInt iSrc=0; iSrc<nSrcTab; iSrc++) {
1163         MDirection refDir = in.getDirection(firstRow[iSrc]);
1164         uInt idx = (iSrc*nFreqIDs) + fqID;
1165         vA[idx] = new VelocityAligner<Float>(sC, nChan, refEpoch, refDir, refPos,
1166                                              velUnit, doppler, velSystem);
1167      }
1168   }
1169
1170// New output Table
1171
1172   SDMemTable* pTabOut = new SDMemTable(in,True);
1173
1174// Loop over rows in Table
1175
1176  const IPosition polChanAxes(2, asap::PolAxis, asap::ChanAxis);
1177  VelocityAligner<Float>::Method method = VelocityAligner<Float>::LINEAR;
1178  Bool extrapolate=False;
1179  Bool useCachedAbcissa = False;
1180  Bool first = True;
1181  Bool ok;
1182  Vector<Float> yOut;
1183  Vector<Bool> maskOut;
1184  uInt ifIdx, vaIdx;
1185//
1186  for (uInt iRow=0; iRow<nRows; ++iRow) {
1187     if (iRow%10==0) {
1188        cerr << "Processing row " << iRow << endl;
1189     }
1190
1191// Get EPoch
1192
1193    Quantum<Double> tQ2(times[iRow],DAY);
1194    MVEpoch mv2(tQ2);
1195    MEpoch epoch(mv2, epochRef);
1196
1197// Get FreqID vector.  One freqID per IF
1198
1199    fqIDCol.get(iRow, freqID);
1200
1201// Get copy of data
1202   
1203    const MaskedArray<Float>& mArrIn(in.rowAsMaskedArray(iRow));
1204    Array<Float> values = mArrIn.getArray();
1205    Array<Bool> mask = mArrIn.getMask();
1206
1207// cerr << "values in = " << values(IPosition(4,0,0,0,0),IPosition(4,0,0,0,9)) << endl;
1208
1209// For each row, the Velocity abcissa will be the same regardless
1210// of polarization.  For all other axes (IF and BEAM) the abcissa
1211// will change.  So we iterate through the data by pol-chan planes
1212// to mimimize the work.  At this point, I think the Direction
1213// is stored as the same for each beam. DOn't know where the
1214// offsets are or what to do about them right now.  For now
1215// all beams get same position and velocoity abcissa.
1216
1217    ArrayIterator<Float> itValuesPlane(values, polChanAxes);
1218    ArrayIterator<Bool> itMaskPlane(mask, polChanAxes);
1219    while (!itValuesPlane.pastEnd()) {
1220
1221// Find the IF index and then the VA PtrBlock index
1222
1223       const IPosition& pos = itValuesPlane.pos();
1224       ifIdx = pos(asap::IFAxis);
1225       vaIdx = (srcIdx[iRow]*nFreqIDs) + freqID[ifIdx];
1226//
1227       VectorIterator<Float> itValuesVec(itValuesPlane.array(), 1);
1228       VectorIterator<Bool> itMaskVec(itMaskPlane.array(), 1);
1229//
1230       first = True;
1231       useCachedAbcissa=False;
1232       while (!itValuesVec.pastEnd()) {     
1233          ok = vA[vaIdx]->align (yOut, maskOut, itValuesVec.vector(),
1234                                 itMaskVec.vector(), epoch, useCachedAbcissa,
1235                                 method, extrapolate);
1236          itValuesVec.vector() = yOut;
1237          itMaskVec.vector() = maskOut;
1238//
1239          itValuesVec.next();
1240          itMaskVec.next();
1241//
1242          if (first) {
1243             useCachedAbcissa = True;
1244             first = False;
1245          }
1246       }
1247//
1248       itValuesPlane.next();
1249       itMaskPlane.next();
1250    }
1251
1252// cerr << "values out = " << values(IPosition(4,0,0,0,0),IPosition(4,0,0,0,9)) << endl;
1253
1254// Create and put back
1255
1256    SDContainer sc = in.getSDContainer(iRow);
1257    putDataInSDC(sc, values, mask);
1258//
1259    pTabOut->putSDContainer(sc);
1260  }
1261
1262// Clean up PointerBlock
1263
1264  for (uInt i=0; i<vA.nelements(); i++) delete vA[i];
1265//
1266  return pTabOut;
1267}
1268
1269
1270void SDMath::fillSDC(SDContainer& sc,
1271                     const Array<Bool>& mask,
1272                     const Array<Float>& data,
1273                     const Array<Float>& tSys,
1274                     Int scanID, Double timeStamp,
1275                     Double interval, const String& sourceName,
1276                     const Vector<uInt>& freqID) const
1277{
1278// Data and mask
1279
1280  putDataInSDC(sc, data, mask);
1281
1282// TSys
1283
1284  sc.putTsys(tSys);
1285
1286// Time things
1287
1288  sc.timestamp = timeStamp;
1289  sc.interval = interval;
1290  sc.scanid = scanID;
1291//
1292  sc.sourcename = sourceName;
1293  sc.putFreqMap(freqID);
1294}
1295
1296void SDMath::normalize(MaskedArray<Float>& sum,
1297                        const Array<Float>& sumSq,
1298                        const Array<Float>& nPts,
1299                        WeightType wtType, Int axis,
1300                        Int nAxesSub) const
1301{
1302   IPosition pos2(nAxesSub,0);
1303//
1304   if (wtType==NONE) {
1305
1306// We just average by the number of points accumulated.
1307// We need to make a MA out of nPts so that no divide by
1308// zeros occur
1309
1310      MaskedArray<Float> t(nPts, (nPts>Float(0.0)));
1311      sum /= t;
1312   } else if (wtType==VAR) {
1313
1314// Normalize each spectrum by sum(1/var) where the variance
1315// is worked out for each spectrum
1316
1317      Array<Float>& data = sum.getRWArray();
1318      VectorIterator<Float> itData(data, axis);
1319      while (!itData.pastEnd()) {
1320         pos2 = itData.pos().getFirst(nAxesSub);
1321         itData.vector() /= sumSq(pos2);
1322         itData.next();
1323      }
1324   } else if (wtType==TSYS) {
1325   }
1326}
1327
1328
1329void SDMath::accumulate(Double& timeSum, Double& intSum, Int& nAccum,
1330                        MaskedArray<Float>& sum, Array<Float>& sumSq,
1331                        Array<Float>& nPts, Array<Float>& tSysSum,
1332                        const Array<Float>& tSys, const Array<Float>& nInc,
1333                        const Vector<Bool>& mask, Double time, Double interval,
1334                        const Block<CountedPtr<SDMemTable> >& in,
1335                        uInt iTab, uInt iRow, uInt axis,
1336                        uInt nAxesSub, Bool useMask,
1337                        WeightType wtType) const
1338{
1339
1340// Get data
1341
1342   MaskedArray<Float> dataIn(in[iTab]->rowAsMaskedArray(iRow));
1343   Array<Float>& valuesIn = dataIn.getRWArray();           // writable reference
1344   const Array<Bool>& maskIn = dataIn.getMask();          // RO reference
1345//
1346   if (wtType==NONE) {
1347      const MaskedArray<Float> n(nInc,dataIn.getMask());
1348      nPts += n;                               // Only accumulates where mask==T
1349   } else if (wtType==VAR) {
1350
1351// We are going to average the data, weighted by the noise for each pol, beam and IF.
1352// So therefore we need to iterate through by spectrum (axis 3)
1353
1354      VectorIterator<Float> itData(valuesIn, axis);
1355      ReadOnlyVectorIterator<Bool> itMask(maskIn, axis);
1356      Float fac = 1.0;
1357      IPosition pos(nAxesSub,0); 
1358//
1359      while (!itData.pastEnd()) {
1360
1361// Make MaskedArray of Vector, optionally apply OTF mask, and find scaling factor
1362
1363        if (useMask) {
1364           MaskedArray<Float> tmp(itData.vector(),mask&&itMask.vector());
1365           fac = 1.0/variance(tmp);
1366        } else {
1367           MaskedArray<Float> tmp(itData.vector(),itMask.vector());
1368           fac = 1.0/variance(tmp);
1369        }
1370
1371// Scale data
1372
1373        itData.vector() *= fac;     // Writes back into 'dataIn'
1374//
1375// Accumulate variance per if/pol/beam averaged over spectrum
1376// This method to get pos2 from itData.pos() is only valid
1377// because the spectral axis is the last one (so we can just
1378// copy the first nAXesSub positions out)
1379
1380        pos = itData.pos().getFirst(nAxesSub);
1381        sumSq(pos) += fac;
1382//
1383        itData.next();
1384        itMask.next();
1385      }
1386   } else if (wtType==TSYS) {
1387   }
1388
1389// Accumulate sum of (possibly scaled) data
1390
1391   sum += dataIn;
1392
1393// Accumulate Tsys, time, and interval
1394
1395   tSysSum += tSys;
1396   timeSum += time;
1397   intSum += interval;
1398   nAccum += 1;
1399}
1400
1401
1402
1403
1404void SDMath::getCursorLocation(IPosition& start, IPosition& end,
1405                               const SDMemTable& in) const
1406{
1407  const uInt nDim = 4;
1408  const uInt i = in.getBeam();
1409  const uInt j = in.getIF();
1410  const uInt k = in.getPol();
1411  const uInt n = in.nChan();
1412//
1413  start.resize(nDim);
1414  start(0) = i;
1415  start(1) = j;
1416  start(2) = k;
1417  start(3) = 0;
1418//
1419  end.resize(nDim);
1420  end(0) = i;
1421  end(1) = j;
1422  end(2) = k;
1423  end(3) = n-1;
1424}
1425
1426
1427void SDMath::convertWeightString(WeightType& wtType, const String& weightStr) const
1428{
1429  String tStr(weightStr);
1430  tStr.upcase();
1431  if (tStr.contains(String("NONE"))) {
1432     wtType = NONE;
1433  } else if (tStr.contains(String("VAR"))) {
1434     wtType = VAR;
1435  } else if (tStr.contains(String("TSYS"))) {
1436     wtType = TSYS;
1437     throw(AipsError("T_sys weighting not yet implemented"));
1438  } else {
1439    throw(AipsError("Unrecognized weighting type"));
1440  }
1441}
1442
1443void SDMath::convertInterpString(Int& type, const String& interp) const
1444{
1445  String tStr(interp);
1446  tStr.upcase();
1447  if (tStr.contains(String("NEAR"))) {
1448     type = InterpolateArray1D<Float,Float>::nearestNeighbour;
1449  } else if (tStr.contains(String("LIN"))) {
1450     type = InterpolateArray1D<Float,Float>::linear;
1451  } else if (tStr.contains(String("CUB"))) {
1452     type = InterpolateArray1D<Float,Float>::cubic;
1453  } else if (tStr.contains(String("SPL"))) {
1454     type = InterpolateArray1D<Float,Float>::spline;
1455  } else {
1456    throw(AipsError("Unrecognized interpolation type"));
1457  }
1458}
1459
1460void SDMath::putDataInSDC(SDContainer& sc, const Array<Float>& data,
1461                          const Array<Bool>& mask) const
1462{
1463    sc.putSpectrum(data);
1464//
1465    Array<uChar> outflags(data.shape());
1466    convertArray(outflags,!mask);
1467    sc.putFlags(outflags);
1468}
1469
1470Table SDMath::readAsciiFile (const String& fileName) const
1471{
1472   String formatString;
1473   Table tbl = readAsciiTable (formatString, Table::Memory, fileName, "", "", False);
1474   return tbl;
1475}
1476
1477
1478
1479void SDMath::correctFromAsciiTable(SDMemTable* pTabOut,
1480                                   const SDMemTable& in, const String& fileName,
1481                                   const String& col0, const String& col1,
1482                                   const String& methodStr, Bool doAll,
1483                                   const Vector<Float>& xOut) const
1484{
1485
1486// Read gain-elevation ascii file data into a Table.
1487
1488  Table geTable = readAsciiFile (fileName);
1489//
1490  correctFromTable (pTabOut, in, geTable, col0, col1, methodStr, doAll, xOut);
1491}
1492
1493void SDMath::correctFromTable(SDMemTable* pTabOut, const SDMemTable& in,
1494                              const Table& tTable, const String& col0,
1495                              const String& col1,
1496                              const String& methodStr, Bool doAll,
1497                              const Vector<Float>& xOut) const
1498{
1499
1500// Get data from Table
1501
1502  ROScalarColumn<Float> geElCol(tTable, col0);
1503  ROScalarColumn<Float> geFacCol(tTable, col1);
1504  Vector<Float> xIn = geElCol.getColumn();
1505  Vector<Float> yIn = geFacCol.getColumn();
1506  Vector<Bool> maskIn(xIn.nelements(),True);
1507
1508// Interpolate (and extrapolate) with desired method
1509
1510   Int method = 0;
1511   convertInterpString(method, methodStr);
1512//
1513   Vector<Float> yOut;
1514   Vector<Bool> maskOut;
1515   InterpolateArray1D<Float,Float>::interpolate(yOut, maskOut, xOut,
1516                                                xIn, yIn, maskIn, method,
1517                                                True, True);
1518// Apply
1519
1520   correctFromVector (pTabOut, in, doAll, yOut);
1521}
1522
1523
1524void SDMath::correctFromVector (SDMemTable* pTabOut, const SDMemTable& in,
1525                                Bool doAll, const Vector<Float>& factor) const
1526{
1527
1528// For operations only on specified cursor location
1529
1530  IPosition start, end;
1531  getCursorLocation(start, end, in);
1532
1533// Loop over rows and apply correction factor
1534 
1535  const uInt axis = asap::ChanAxis;
1536  for (uInt i=0; i < in.nRow(); ++i) {
1537
1538// Get data
1539
1540    MaskedArray<Float> dataIn(in.rowAsMaskedArray(i));
1541
1542// Apply factor
1543
1544    if (doAll) {
1545       dataIn *= factor[i];
1546    } else {
1547       MaskedArray<Float> dataIn2 = dataIn(start,end);  // reference
1548       dataIn2 *= factor[i];
1549    }
1550
1551// Write out
1552
1553    SDContainer sc = in.getSDContainer(i);
1554    putDataInSDC(sc, dataIn.getArray(), dataIn.getMask());
1555//
1556    pTabOut->putSDContainer(sc);
1557  }
1558}
1559
1560
1561void SDMath::generateSourceTable (Vector<String>& srcTab,
1562                                  Vector<uInt>& srcIdx,
1563                                  Vector<uInt>& firstRow,
1564                                  const Vector<String>& srcNames) const
1565//
1566// This algorithm assumes that if there are multiple beams
1567// that the source names are diffent.  Oterwise we would need
1568// to look atthe direction for each beam...
1569//
1570{
1571   const uInt nRow = srcNames.nelements();
1572   srcTab.resize(0);
1573   srcIdx.resize(nRow);
1574   firstRow.resize(0);
1575//
1576   uInt nSrc = 0;
1577   for (uInt i=0; i<nRow; i++) {
1578      String srcName = srcNames[i];
1579     
1580// Do we have this source already ?
1581
1582      Int idx = -1;
1583      if (nSrc>0) {
1584         for (uInt j=0; j<nSrc; j++) {
1585           if (srcName==srcTab[j]) {
1586              idx = j;
1587              break;
1588           }
1589         }
1590      }
1591
1592// Add new entry if not found
1593
1594      if (idx==-1) {
1595         nSrc++;
1596         srcTab.resize(nSrc,True);
1597         srcTab(nSrc-1) = srcName;
1598         idx = nSrc-1;
1599//
1600         firstRow.resize(nSrc,True);
1601         firstRow(nSrc-1) = i;       // First row for which this source occurs
1602      }
1603
1604// Set index for this row
1605
1606      srcIdx[i] = idx;
1607   }
1608}
1609
1610MEpoch SDMath::epochFromString (const String& str, MEpoch::Types timeRef) const
1611{
1612   Quantum<Double> qt;
1613   if (MVTime::read(qt,str)) {
1614      MVEpoch mv(qt);
1615      MEpoch me(mv, timeRef);
1616      return me;
1617   } else {
1618      throw(AipsError("Invalid format for Epoch string"));
1619   }
1620}
1621
1622
1623String SDMath::formatEpoch(const MEpoch& epoch)  const
1624{
1625   MVTime mvt(epoch.getValue());
1626   return mvt.string(MVTime::YMD) + String(" (") + epoch.getRefString() + String(")");
1627}
1628
Note: See TracBrowser for help on using the repository browser.