source: trunk/src/SDMath.cc @ 264

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

add functiom VelocityAlignment?

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