source: trunk/src/SDMath.cc @ 518

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

add Tsys and Tint weightring

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