source: trunk/src/SDMath.cc @ 299

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

add resample function

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