source: trunk/src/STMath.cpp @ 2466

Last change on this file since 2466 was 2466, checked in by Kana Sugimoto, 12 years ago

New Development: No

JIRA Issue: No (a bug fix)

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs: unit test of sdcal, using averageall=True

Put in Release Notes: No

Module(s):

Description:

Fixed a bug recently found by Malte in asapmath.new_average, with compel=True, or
sdcal with averageall=True.
The bug caused the method/task crash, when the spectra to be averaged over have
IFs with negative and positive frequency increments mixed.


  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 170.7 KB
Line 
1//
2// C++ Implementation: STMath
3//
4// Description:
5//
6//
7// Author: Malte Marquarding <asap@atnf.csiro.au>, (C) 2006
8//
9// Copyright: See COPYING file that comes with this distribution
10//
11//
12
13#include <sstream>
14
15#include <casa/iomanip.h>
16#include <casa/Arrays/MaskArrLogi.h>
17#include <casa/Arrays/MaskArrMath.h>
18#include <casa/Arrays/ArrayLogical.h>
19#include <casa/Arrays/ArrayMath.h>
20#include <casa/Arrays/Slice.h>
21#include <casa/Arrays/Slicer.h>
22#include <casa/BasicSL/String.h>
23#include <casa/Containers/Block.h>
24#include <casa/Containers/RecordField.h>
25#include <casa/Exceptions/Error.h>
26#include <casa/Logging/LogIO.h>
27
28#include <coordinates/Coordinates/CoordinateSystem.h>
29#include <coordinates/Coordinates/CoordinateUtil.h>
30#include <coordinates/Coordinates/FrequencyAligner.h>
31#include <coordinates/Coordinates/SpectralCoordinate.h>
32
33#include <lattices/Lattices/LatticeUtilities.h>
34
35#include <scimath/Functionals/Polynomial.h>
36#include <scimath/Mathematics/Convolver.h>
37#include <scimath/Mathematics/VectorKernel.h>
38
39#include <tables/Tables/ExprNode.h>
40#include <tables/Tables/ReadAsciiTable.h>
41#include <tables/Tables/TableCopy.h>
42#include <tables/Tables/TableIter.h>
43#include <tables/Tables/TableParse.h>
44#include <tables/Tables/TableRecord.h>
45#include <tables/Tables/TableRow.h>
46#include <tables/Tables/TableVector.h>
47#include <tables/Tables/TabVecMath.h>
48
49#include <atnf/PKSIO/SrcType.h>
50
51#include "RowAccumulator.h"
52#include "STAttr.h"
53#include "STMath.h"
54#include "STSelector.h"
55
56using namespace casa;
57using namespace asap;
58
59// 2012/02/17 TN
60// Since STGrid is implemented, average doesn't consider direction
61// when accumulating
62// tolerance for direction comparison (rad)
63// #define TOL_OTF    1.0e-15
64// #define TOL_POINT  2.9088821e-4  // 1 arcmin
65
66STMath::STMath(bool insitu) :
67  insitu_(insitu)
68{
69}
70
71
72STMath::~STMath()
73{
74}
75
76CountedPtr<Scantable>
77STMath::average( const std::vector<CountedPtr<Scantable> >& in,
78                 const std::vector<bool>& mask,
79                 const std::string& weight,
80                 const std::string& avmode)
81{
82  LogIO os( LogOrigin( "STMath", "average()", WHERE ) ) ;
83  if ( avmode == "SCAN" && in.size() != 1 )
84    throw(AipsError("Can't perform 'SCAN' averaging on multiple tables.\n"
85                    "Use merge first."));
86  WeightType wtype = stringToWeight(weight);
87
88  // 2012/02/17 TN
89  // Since STGrid is implemented, average doesn't consider direction
90  // when accumulating
91  // check if OTF observation
92//   String obstype = in[0]->getHeader().obstype ;
93//   Double tol = 0.0 ;
94//   if ( (obstype.find( "OTF" ) != String::npos) || (obstype.find( "OBSERVE_TARGET" ) != String::npos) ) {
95//     tol = TOL_OTF ;
96//   }
97//   else {
98//     tol = TOL_POINT ;
99//   }
100
101  // output
102  // clone as this is non insitu
103  bool insitu = insitu_;
104  setInsitu(false);
105  CountedPtr< Scantable > out = getScantable(in[0], true);
106  setInsitu(insitu);
107  std::vector<CountedPtr<Scantable> >::const_iterator stit = in.begin();
108  ++stit;
109  while ( stit != in.end() ) {
110    out->appendToHistoryTable((*stit)->history());
111    ++stit;
112  }
113
114  Table& tout = out->table();
115
116  /// @todo check if all scantables are conformant
117
118  ArrayColumn<Float> specColOut(tout,"SPECTRA");
119  ArrayColumn<uChar> flagColOut(tout,"FLAGTRA");
120  ArrayColumn<Float> tsysColOut(tout,"TSYS");
121  ScalarColumn<Double> mjdColOut(tout,"TIME");
122  ScalarColumn<Double> intColOut(tout,"INTERVAL");
123  ScalarColumn<uInt> cycColOut(tout,"CYCLENO");
124  ScalarColumn<uInt> scanColOut(tout,"SCANNO");
125
126  // set up the output table rows. These are based on the structure of the
127  // FIRST scantable in the vector
128  const Table& baset = in[0]->table();
129
130  Block<String> cols(3);
131  cols[0] = String("BEAMNO");
132  cols[1] = String("IFNO");
133  cols[2] = String("POLNO");
134  if ( avmode == "SOURCE" ) {
135    cols.resize(4);
136    cols[3] = String("SRCNAME");
137  }
138  if ( avmode == "SCAN"  && in.size() == 1) {
139    //cols.resize(4);
140    //cols[3] = String("SCANNO");
141    cols.resize(5);
142    cols[3] = String("SRCNAME");
143    cols[4] = String("SCANNO");
144  }
145  uInt outrowCount = 0;
146  TableIterator iter(baset, cols);
147//   int count = 0 ;
148  while (!iter.pastEnd()) {
149    Table subt = iter.table();
150    // copy the first row of this selection into the new table
151    tout.addRow();
152    TableCopy::copyRows(tout, subt, outrowCount, 0, 1);
153    // re-index to 0
154    if ( avmode != "SCAN" && avmode != "SOURCE" ) {
155      scanColOut.put(outrowCount, uInt(0));
156    }
157    ++outrowCount;
158    // 2012/02/17 TN
159    // Since STGrid is implemented, average doesn't consider direction
160    // when accumulating
161//     MDirection::ScalarColumn dircol ;
162//     dircol.attach( subt, "DIRECTION" ) ;
163//     Int length = subt.nrow() ;
164//     vector< Vector<Double> > dirs ;
165//     vector<int> indexes ;
166//     for ( Int i = 0 ; i < length ; i++ ) {
167//       Vector<Double> t = dircol(i).getAngle(Unit(String("rad"))).getValue() ;
168//       //os << << count++ << ": " ;
169//       //os << "[" << t[0] << "," << t[1] << "]" << LogIO::POST ;
170//       bool adddir = true ;
171//       for ( uInt j = 0 ; j < dirs.size() ; j++ ) {
172//         //if ( allTrue( t == dirs[j] ) ) {
173//         Double dx = t[0] - dirs[j][0] ;
174//         Double dy = t[1] - dirs[j][1] ;
175//         Double dd = sqrt( dx * dx + dy * dy ) ;
176//         //if ( allNearAbs( t, dirs[j], tol ) ) {
177//         if ( dd <= tol ) {
178//           adddir = false ;
179//           break ;
180//         }
181//       }
182//       if ( adddir ) {
183//         dirs.push_back( t ) ;
184//         indexes.push_back( i ) ;
185//       }
186//     }
187//     uInt rowNum = dirs.size() ;
188//     tout.addRow( rowNum ) ;
189//     for ( uInt i = 0 ; i < rowNum ; i++ ) {
190//       TableCopy::copyRows( tout, subt, outrowCount+i, indexes[i], 1 ) ;
191//       // re-index to 0
192//       if ( avmode != "SCAN" && avmode != "SOURCE" ) {
193//         scanColOut.put(outrowCount+i, uInt(0));
194//       }       
195//     }
196//     outrowCount += rowNum ;
197    ++iter;
198  }
199  RowAccumulator acc(wtype);
200  Vector<Bool> cmask(mask);
201  acc.setUserMask(cmask);
202  ROTableRow row(tout);
203  ROArrayColumn<Float> specCol, tsysCol;
204  ROArrayColumn<uChar> flagCol;
205  ROScalarColumn<Double> mjdCol, intCol;
206  ROScalarColumn<Int> scanIDCol;
207
208  Vector<uInt> rowstodelete;
209
210  for (uInt i=0; i < tout.nrow(); ++i) {
211    for ( int j=0; j < int(in.size()); ++j ) {
212      const Table& tin = in[j]->table();
213      const TableRecord& rec = row.get(i);
214      ROScalarColumn<Double> tmp(tin, "TIME");
215      Double td;tmp.get(0,td);
216      Table basesubt = tin( tin.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
217                         && tin.col("IFNO") == Int(rec.asuInt("IFNO"))
218                         && tin.col("POLNO") == Int(rec.asuInt("POLNO")) );
219      Table subt;
220      if ( avmode == "SOURCE") {
221        subt = basesubt( basesubt.col("SRCNAME") == rec.asString("SRCNAME"));
222      } else if (avmode == "SCAN") {
223        subt = basesubt( basesubt.col("SRCNAME") == rec.asString("SRCNAME")
224                      && basesubt.col("SCANNO") == Int(rec.asuInt("SCANNO")) );
225      } else {
226        subt = basesubt;
227      }
228
229      // 2012/02/17 TN
230      // Since STGrid is implemented, average doesn't consider direction
231      // when accumulating
232//       vector<uInt> removeRows ;
233//       uInt nrsubt = subt.nrow() ;
234//       for ( uInt irow = 0 ; irow < nrsubt ; irow++ ) {
235//         //if ( !allTrue((subt.col("DIRECTION").getArrayDouble(TableExprId(irow)))==rec.asArrayDouble("DIRECTION")) ) {
236//         Vector<Double> x0 = (subt.col("DIRECTION").getArrayDouble(TableExprId(irow))) ;
237//         Vector<Double> x1 = rec.asArrayDouble("DIRECTION") ;
238//         double dx = x0[0] - x1[0];
239//         double dy = x0[1] - x1[1];
240//         Double dd = sqrt( dx * dx + dy * dy ) ;
241//         //if ( !allNearAbs((subt.col("DIRECTION").getArrayDouble(TableExprId(irow))), rec.asArrayDouble("DIRECTION"), tol ) ) {
242//         if ( dd > tol ) {
243//           removeRows.push_back( irow ) ;
244//         }
245//       }
246//       if ( removeRows.size() != 0 ) {
247//         subt.removeRow( removeRows ) ;
248//       }
249     
250//       if ( nrsubt == removeRows.size() )
251//         throw(AipsError("Averaging data is empty.")) ;
252
253      specCol.attach(subt,"SPECTRA");
254      flagCol.attach(subt,"FLAGTRA");
255      tsysCol.attach(subt,"TSYS");
256      intCol.attach(subt,"INTERVAL");
257      mjdCol.attach(subt,"TIME");
258      Vector<Float> spec,tsys;
259      Vector<uChar> flag;
260      Double inter,time;
261      for (uInt k = 0; k < subt.nrow(); ++k ) {
262        flagCol.get(k, flag);
263        Vector<Bool> bflag(flag.shape());
264        convertArray(bflag, flag);
265        /*
266        if ( allEQ(bflag, True) ) {
267        continue;//don't accumulate
268        }
269        */
270        specCol.get(k, spec);
271        tsysCol.get(k, tsys);
272        intCol.get(k, inter);
273        mjdCol.get(k, time);
274        // spectrum has to be added last to enable weighting by the other values
275        acc.add(spec, !bflag, tsys, inter, time);
276      }
277
278      // If there exists a channel at which all the input spectra are masked,
279      // spec has 'nan' values for that channel and it may affect the following
280      // processes. To avoid this, replacing 'nan' values in spec with
281      // weighted-mean of all spectra in the following line.
282      // (done for CAS-2776, 2011/04/07 by Wataru Kawasaki)
283      acc.replaceNaN();
284    }
285    const Vector<Bool>& msk = acc.getMask();
286    if ( allEQ(msk, False) ) {
287      uint n = rowstodelete.nelements();
288      rowstodelete.resize(n+1, True);
289      rowstodelete[n] = i;
290      continue;
291    }
292    //write out
293    if (acc.state()) {
294      Vector<uChar> flg(msk.shape());
295      convertArray(flg, !msk);
296      for (uInt k = 0; k < flg.nelements(); ++k) {
297        uChar userFlag = 1 << 7;
298        if (msk[k]==True) userFlag = 0 << 7;
299        flg(k) = userFlag;
300      }
301
302      flagColOut.put(i, flg);
303      specColOut.put(i, acc.getSpectrum());
304      tsysColOut.put(i, acc.getTsys());
305      intColOut.put(i, acc.getInterval());
306      mjdColOut.put(i, acc.getTime());
307      // we should only have one cycle now -> reset it to be 0
308      // frequency switched data has different CYCLENO for different IFNO
309      // which requires resetting this value
310      cycColOut.put(i, uInt(0));
311    } else {
312      ostringstream oss;
313      oss << "For output row="<<i<<", all input rows of data are flagged. no averaging" << endl;
314      pushLog(String(oss));
315    }
316    acc.reset();
317  }
318
319  if (rowstodelete.nelements() > 0) {
320    os << rowstodelete << LogIO::POST ;
321    tout.removeRow(rowstodelete);
322    if (tout.nrow() == 0) {
323      throw(AipsError("Can't average fully flagged data."));
324    }
325  }
326  return out;
327}
328
329CountedPtr< Scantable >
330STMath::averageChannel( const CountedPtr < Scantable > & in,
331                          const std::string & mode,
332                          const std::string& avmode )
333{
334  (void) mode; // currently unused
335  // 2012/02/17 TN
336  // Since STGrid is implemented, average doesn't consider direction
337  // when accumulating
338  // check if OTF observation
339//   String obstype = in->getHeader().obstype ;
340//   Double tol = 0.0 ;
341//   if ( obstype.find( "OTF" ) != String::npos ) {
342//     tol = TOL_OTF ;
343//   }
344//   else {
345//     tol = TOL_POINT ;
346//   }
347
348  // clone as this is non insitu
349  bool insitu = insitu_;
350  setInsitu(false);
351  CountedPtr< Scantable > out = getScantable(in, true);
352  setInsitu(insitu);
353  Table& tout = out->table();
354  ArrayColumn<Float> specColOut(tout,"SPECTRA");
355  ArrayColumn<uChar> flagColOut(tout,"FLAGTRA");
356  ArrayColumn<Float> tsysColOut(tout,"TSYS");
357  ScalarColumn<uInt> scanColOut(tout,"SCANNO");
358  ScalarColumn<Double> intColOut(tout, "INTERVAL");
359  Table tmp = in->table().sort("BEAMNO");
360  Block<String> cols(3);
361  cols[0] = String("BEAMNO");
362  cols[1] = String("IFNO");
363  cols[2] = String("POLNO");
364  if ( avmode == "SCAN") {
365    cols.resize(4);
366    cols[3] = String("SCANNO");
367  }
368  uInt outrowCount = 0;
369  uChar userflag = 1 << 7;
370  TableIterator iter(tmp, cols);
371  while (!iter.pastEnd()) {
372    Table subt = iter.table();
373    ROArrayColumn<Float> specCol, tsysCol;
374    ROArrayColumn<uChar> flagCol;
375    ROScalarColumn<Double> intCol(subt, "INTERVAL");
376    specCol.attach(subt,"SPECTRA");
377    flagCol.attach(subt,"FLAGTRA");
378    tsysCol.attach(subt,"TSYS");
379
380    tout.addRow();
381    TableCopy::copyRows(tout, subt, outrowCount, 0, 1);
382    if ( avmode != "SCAN") {
383      scanColOut.put(outrowCount, uInt(0));
384    }
385    Vector<Float> tmp;
386    specCol.get(0, tmp);
387    uInt nchan = tmp.nelements();
388    // have to do channel by channel here as MaskedArrMath
389    // doesn't have partialMedians
390    Vector<uChar> flags = flagCol.getColumn(Slicer(Slice(0)));
391    Vector<Float> outspec(nchan);
392    Vector<uChar> outflag(nchan,0);
393    Vector<Float> outtsys(1);/// @fixme when tsys is channel based
394    for (uInt i=0; i<nchan; ++i) {
395      Vector<Float> specs = specCol.getColumn(Slicer(Slice(i)));
396      MaskedArray<Float> ma = maskedArray(specs,flags);
397      outspec[i] = median(ma);
398      if ( allEQ(ma.getMask(), False) )
399        outflag[i] = userflag;// flag data
400    }
401    outtsys[0] = median(tsysCol.getColumn());
402    specColOut.put(outrowCount, outspec);
403    flagColOut.put(outrowCount, outflag);
404    tsysColOut.put(outrowCount, outtsys);
405    Double intsum = sum(intCol.getColumn());
406    intColOut.put(outrowCount, intsum);
407    ++outrowCount;
408    ++iter;
409
410    // 2012/02/17 TN
411    // Since STGrid is implemented, average doesn't consider direction
412    // when accumulating
413//     MDirection::ScalarColumn dircol ;
414//     dircol.attach( subt, "DIRECTION" ) ;
415//     Int length = subt.nrow() ;
416//     vector< Vector<Double> > dirs ;
417//     vector<int> indexes ;
418//     // Handle MX mode averaging
419//     if (in->nbeam() > 1 ) {     
420//       length = 1;
421//     }
422//     for ( Int i = 0 ; i < length ; i++ ) {
423//       Vector<Double> t = dircol(i).getAngle(Unit(String("rad"))).getValue() ;
424//       bool adddir = true ;
425//       for ( uInt j = 0 ; j < dirs.size() ; j++ ) {
426//         //if ( allTrue( t == dirs[j] ) ) {
427//         Double dx = t[0] - dirs[j][0] ;
428//         Double dy = t[1] - dirs[j][1] ;
429//         Double dd = sqrt( dx * dx + dy * dy ) ;
430//         //if ( allNearAbs( t, dirs[j], tol ) ) {
431//         if ( dd <= tol ) {
432//           adddir = false ;
433//           break ;
434//         }
435//       }
436//       if ( adddir ) {
437//         dirs.push_back( t ) ;
438//         indexes.push_back( i ) ;
439//       }
440//     }
441//     uInt rowNum = dirs.size() ;
442//     tout.addRow( rowNum );
443//     for ( uInt i = 0 ; i < rowNum ; i++ ) {
444//       TableCopy::copyRows(tout, subt, outrowCount+i, indexes[i], 1) ;
445//       // Handle MX mode averaging
446//       if ( avmode != "SCAN") {
447//         scanColOut.put(outrowCount+i, uInt(0));
448//       }
449//     }
450//     MDirection::ScalarColumn dircolOut ;
451//     dircolOut.attach( tout, "DIRECTION" ) ;
452//     for ( uInt irow = 0 ; irow < rowNum ; irow++ ) {
453//       Vector<Double> t = \
454//      dircolOut(outrowCount+irow).getAngle(Unit(String("rad"))).getValue() ;
455//       Vector<Float> tmp;
456//       specCol.get(0, tmp);
457//       uInt nchan = tmp.nelements();
458//       // have to do channel by channel here as MaskedArrMath
459//       // doesn't have partialMedians
460//       Vector<uChar> flags = flagCol.getColumn(Slicer(Slice(0)));
461//       // mask spectra for different DIRECTION
462//       for ( uInt jrow = 0 ; jrow < subt.nrow() ; jrow++ ) {
463//         Vector<Double> direction = \
464//        dircol(jrow).getAngle(Unit(String("rad"))).getValue() ;
465//         //if ( t[0] != direction[0] || t[1] != direction[1] ) {
466//         Double dx = t[0] - direction[0];
467//         Double dy = t[1] - direction[1];
468//         Double dd = sqrt(dx*dx + dy*dy);
469//         //if ( !allNearAbs( t, direction, tol ) ) {
470//         if ( dd > tol &&  in->nbeam() < 2 ) {
471//           flags[jrow] = userflag ;
472//         }
473//       }
474//       Vector<Float> outspec(nchan);
475//       Vector<uChar> outflag(nchan,0);
476//       Vector<Float> outtsys(1);/// @fixme when tsys is channel based
477//       for (uInt i=0; i<nchan; ++i) {
478//         Vector<Float> specs = specCol.getColumn(Slicer(Slice(i)));
479//         MaskedArray<Float> ma = maskedArray(specs,flags);
480//         outspec[i] = median(ma);
481//         if ( allEQ(ma.getMask(), False) )
482//           outflag[i] = userflag;// flag data
483//       }
484//       outtsys[0] = median(tsysCol.getColumn());
485//       specColOut.put(outrowCount+irow, outspec);
486//       flagColOut.put(outrowCount+irow, outflag);
487//       tsysColOut.put(outrowCount+irow, outtsys);
488//       Vector<Double> integ = intCol.getColumn() ;
489//       MaskedArray<Double> mi = maskedArray( integ, flags ) ;
490//       Double intsum = sum(mi);
491//       intColOut.put(outrowCount+irow, intsum);
492//     }
493//     outrowCount += rowNum ;
494//     ++iter;
495  }
496  return out;
497}
498
499CountedPtr< Scantable > STMath::getScantable(const CountedPtr< Scantable >& in,
500                                             bool droprows)
501{
502  if (insitu_) {
503    return in;
504  }
505  else {
506    // clone
507    return CountedPtr<Scantable>(new Scantable(*in, Bool(droprows)));
508  }
509}
510
511CountedPtr< Scantable > STMath::unaryOperate( const CountedPtr< Scantable >& in,
512                                              float val,
513                                              const std::string& mode,
514                                              bool tsys )
515{
516  CountedPtr< Scantable > out = getScantable(in, false);
517  Table& tab = out->table();
518  ArrayColumn<Float> specCol(tab,"SPECTRA");
519  ArrayColumn<Float> tsysCol(tab,"TSYS");
520  if (mode=="DIV") val = 1.0/val ;
521  else if (mode=="SUB") val *= -1.0 ;
522  for (uInt i=0; i<tab.nrow(); ++i) {
523    Vector<Float> spec;
524    Vector<Float> ts;
525    specCol.get(i, spec);
526    tsysCol.get(i, ts);
527    if (mode == "MUL" || mode == "DIV") {
528      //if (mode == "DIV") val = 1.0/val;
529      spec *= val;
530      specCol.put(i, spec);
531      if ( tsys ) {
532        ts *= val;
533        tsysCol.put(i, ts);
534      }
535    } else if ( mode == "ADD"  || mode == "SUB") {
536      //if (mode == "SUB") val *= -1.0;
537      spec += val;
538      specCol.put(i, spec);
539      if ( tsys ) {
540        ts += val;
541        tsysCol.put(i, ts);
542      }
543    }
544  }
545  return out;
546}
547
548CountedPtr< Scantable > STMath::arrayOperate( const CountedPtr< Scantable >& in,
549                                              const std::vector<float> val,
550                                              const std::string& mode,
551                                              const std::string& opmode,
552                                              bool tsys )
553{
554  CountedPtr< Scantable > out ;
555  if ( opmode == "channel" ) {
556    out = arrayOperateChannel( in, val, mode, tsys ) ;
557  }
558  else if ( opmode == "row" ) {
559    out = arrayOperateRow( in, val, mode, tsys ) ;
560  }
561  else {
562    throw( AipsError( "Unknown array operation mode." ) ) ;
563  }
564  return out ;
565}
566
567CountedPtr< Scantable > STMath::arrayOperateChannel( const CountedPtr< Scantable >& in,
568                                                     const std::vector<float> val,
569                                                     const std::string& mode,
570                                                     bool tsys )
571{
572  if ( val.size() == 1 ){
573    return unaryOperate( in, val[0], mode, tsys ) ;
574  }
575
576  // conformity of SPECTRA and TSYS
577  if ( tsys ) {
578    TableIterator titer(in->table(), "IFNO");
579    while ( !titer.pastEnd() ) {
580      ArrayColumn<Float> specCol( in->table(), "SPECTRA" ) ;
581      ArrayColumn<Float> tsysCol( in->table(), "TSYS" ) ;
582      Array<Float> spec = specCol.getColumn() ;
583      Array<Float> ts = tsysCol.getColumn() ;
584      if ( !spec.conform( ts ) ) {
585        throw( AipsError( "SPECTRA and TSYS must conform in shape if you want to apply operation on Tsys." ) ) ;
586      }
587      titer.next() ;
588    }
589  }
590
591  // check if all spectra in the scantable have the same number of channel
592  vector<uInt> nchans;
593  vector<uInt> ifnos = in->getIFNos() ;
594  for ( uInt i = 0 ; i < ifnos.size() ; i++ ) {
595    nchans.push_back( in->nchan( ifnos[i] ) ) ;
596  }
597  Vector<uInt> mchans( nchans ) ;
598  if ( anyNE( mchans, mchans[0] ) ) {
599    throw( AipsError("All spectra in the input scantable must have the same number of channel for vector operation." ) ) ;
600  }
601
602  // check if vector size is equal to nchan
603  Vector<Float> fact( val ) ;
604  if ( fact.nelements() != mchans[0] ) {
605    throw( AipsError("Vector size must be 1 or be same as number of channel.") ) ;
606  }
607
608  // check divided by zero
609  if ( ( mode == "DIV" ) && anyEQ( fact, (float)0.0 ) ) {
610    throw( AipsError("Divided by zero is not recommended." ) ) ;
611  }
612
613  CountedPtr< Scantable > out = getScantable(in, false);
614  Table& tab = out->table();
615  ArrayColumn<Float> specCol(tab,"SPECTRA");
616  ArrayColumn<Float> tsysCol(tab,"TSYS");
617  if (mode == "DIV") fact = (float)1.0 / fact;
618  else if (mode == "SUB") fact *= (float)-1.0 ;
619  for (uInt i=0; i<tab.nrow(); ++i) {
620    Vector<Float> spec;
621    Vector<Float> ts;
622    specCol.get(i, spec);
623    tsysCol.get(i, ts);
624    if (mode == "MUL" || mode == "DIV") {
625      //if (mode == "DIV") fact = (float)1.0 / fact;
626      spec *= fact;
627      specCol.put(i, spec);
628      if ( tsys ) {
629        ts *= fact;
630        tsysCol.put(i, ts);
631      }
632    } else if ( mode == "ADD"  || mode == "SUB") {
633      //if (mode == "SUB") fact *= (float)-1.0 ;
634      spec += fact;
635      specCol.put(i, spec);
636      if ( tsys ) {
637        ts += fact;
638        tsysCol.put(i, ts);
639      }
640    }
641  }
642  return out;
643}
644
645CountedPtr< Scantable > STMath::arrayOperateRow( const CountedPtr< Scantable >& in,
646                                                 const std::vector<float> val,
647                                                 const std::string& mode,
648                                                 bool tsys )
649{
650  if ( val.size() == 1 ) {
651    return unaryOperate( in, val[0], mode, tsys ) ;
652  }
653
654  // conformity of SPECTRA and TSYS
655  if ( tsys ) {
656    TableIterator titer(in->table(), "IFNO");
657    while ( !titer.pastEnd() ) {
658      ArrayColumn<Float> specCol( in->table(), "SPECTRA" ) ;
659      ArrayColumn<Float> tsysCol( in->table(), "TSYS" ) ;
660      Array<Float> spec = specCol.getColumn() ;
661      Array<Float> ts = tsysCol.getColumn() ;
662      if ( !spec.conform( ts ) ) {
663        throw( AipsError( "SPECTRA and TSYS must conform in shape if you want to apply operation on Tsys." ) ) ;
664      }
665      titer.next() ;
666    }
667  }
668
669  // check if vector size is equal to nrow
670  Vector<Float> fact( val ) ;
671  if (fact.nelements() != uInt(in->nrow())) {
672    throw( AipsError("Vector size must be 1 or be same as number of row.") ) ;
673  }
674
675  // check divided by zero
676  if ( ( mode == "DIV" ) && anyEQ( fact, (float)0.0 ) ) {
677    throw( AipsError("Divided by zero is not recommended." ) ) ;
678  }
679
680  CountedPtr< Scantable > out = getScantable(in, false);
681  Table& tab = out->table();
682  ArrayColumn<Float> specCol(tab,"SPECTRA");
683  ArrayColumn<Float> tsysCol(tab,"TSYS");
684  if (mode == "DIV") fact = (float)1.0 / fact;
685  if (mode == "SUB") fact *= (float)-1.0 ;
686  for (uInt i=0; i<tab.nrow(); ++i) {
687    Vector<Float> spec;
688    Vector<Float> ts;
689    specCol.get(i, spec);
690    tsysCol.get(i, ts);
691    if (mode == "MUL" || mode == "DIV") {
692      spec *= fact[i];
693      specCol.put(i, spec);
694      if ( tsys ) {
695        ts *= fact[i];
696        tsysCol.put(i, ts);
697      }
698    } else if ( mode == "ADD"  || mode == "SUB") {
699      spec += fact[i];
700      specCol.put(i, spec);
701      if ( tsys ) {
702        ts += fact[i];
703        tsysCol.put(i, ts);
704      }
705    }
706  }
707  return out;
708}
709
710CountedPtr< Scantable > STMath::array2dOperate( const CountedPtr< Scantable >& in,
711                                                const std::vector< std::vector<float> > val,
712                                                const std::string& mode,
713                                                bool tsys )
714{
715  // conformity of SPECTRA and TSYS
716  if ( tsys ) {
717    TableIterator titer(in->table(), "IFNO");
718    while ( !titer.pastEnd() ) {
719      ArrayColumn<Float> specCol( in->table(), "SPECTRA" ) ;
720      ArrayColumn<Float> tsysCol( in->table(), "TSYS" ) ;
721      Array<Float> spec = specCol.getColumn() ;
722      Array<Float> ts = tsysCol.getColumn() ;
723      if ( !spec.conform( ts ) ) {
724        throw( AipsError( "SPECTRA and TSYS must conform in shape if you want to apply operation on Tsys." ) ) ;
725      }
726      titer.next() ;
727    }
728  }
729
730  // some checks
731  vector<uInt> nchans;
732  for (Int i = 0 ; i < in->nrow() ; i++) {
733    nchans.push_back((in->getSpectrum(i)).size());
734  }
735  //Vector<uInt> mchans( nchans ) ;
736  vector< Vector<Float> > facts ;
737  for ( uInt i = 0 ; i < nchans.size() ; i++ ) {
738    Vector<Float> tmp( val[i] ) ;
739    // check divided by zero
740    if ( ( mode == "DIV" ) && anyEQ( tmp, (float)0.0 ) ) {
741      throw( AipsError("Divided by zero is not recommended." ) ) ;
742    }
743    // conformity check
744    if ( tmp.nelements() != nchans[i] ) {
745      stringstream ss ;
746      ss << "Row " << i << ": Vector size must be same as number of channel." ;
747      throw( AipsError( ss.str() ) ) ;
748    }
749    facts.push_back( tmp ) ;
750  }
751
752
753  CountedPtr< Scantable > out = getScantable(in, false);
754  Table& tab = out->table();
755  ArrayColumn<Float> specCol(tab,"SPECTRA");
756  ArrayColumn<Float> tsysCol(tab,"TSYS");
757  for (uInt i=0; i<tab.nrow(); ++i) {
758    Vector<Float> fact = facts[i] ;
759    Vector<Float> spec;
760    Vector<Float> ts;
761    specCol.get(i, spec);
762    tsysCol.get(i, ts);
763    if (mode == "MUL" || mode == "DIV") {
764      if (mode == "DIV") fact = (float)1.0 / fact;
765      spec *= fact;
766      specCol.put(i, spec);
767      if ( tsys ) {
768        ts *= fact;
769        tsysCol.put(i, ts);
770      }
771    } else if ( mode == "ADD"  || mode == "SUB") {
772      if (mode == "SUB") fact *= (float)-1.0 ;
773      spec += fact;
774      specCol.put(i, spec);
775      if ( tsys ) {
776        ts += fact;
777        tsysCol.put(i, ts);
778      }
779    }
780  }
781  return out;
782}
783
784CountedPtr<Scantable> STMath::binaryOperate(const CountedPtr<Scantable>& left,
785                                            const CountedPtr<Scantable>& right,
786                                            const std::string& mode)
787{
788  bool insitu = insitu_;
789  if ( ! left->conformant(*right) ) {
790    throw(AipsError("'left' and 'right' scantables are not conformant."));
791  }
792  setInsitu(false);
793  CountedPtr< Scantable > out = getScantable(left, false);
794  setInsitu(insitu);
795  Table& tout = out->table();
796  Block<String> coln(5);
797  coln[0] = "SCANNO";  coln[1] = "CYCLENO";  coln[2] = "BEAMNO";
798  coln[3] = "IFNO";  coln[4] = "POLNO";
799  Table tmpl = tout.sort(coln);
800  Table tmpr = right->table().sort(coln);
801  ArrayColumn<Float> lspecCol(tmpl,"SPECTRA");
802  ROArrayColumn<Float> rspecCol(tmpr,"SPECTRA");
803  ArrayColumn<uChar> lflagCol(tmpl,"FLAGTRA");
804  ROArrayColumn<uChar> rflagCol(tmpr,"FLAGTRA");
805
806  for (uInt i=0; i<tout.nrow(); ++i) {
807    Vector<Float> lspecvec, rspecvec;
808    Vector<uChar> lflagvec, rflagvec;
809    lspecvec = lspecCol(i);    rspecvec = rspecCol(i);
810    lflagvec = lflagCol(i);    rflagvec = rflagCol(i);
811    MaskedArray<Float> mleft = maskedArray(lspecvec, lflagvec);
812    MaskedArray<Float> mright = maskedArray(rspecvec, rflagvec);
813    if (mode == "ADD") {
814      mleft += mright;
815    } else if ( mode == "SUB") {
816      mleft -= mright;
817    } else if ( mode == "MUL") {
818      mleft *= mright;
819    } else if ( mode == "DIV") {
820      mleft /= mright;
821    } else {
822      throw(AipsError("Illegal binary operator"));
823    }
824    lspecCol.put(i, mleft.getArray());
825  }
826  return out;
827}
828
829
830
831MaskedArray<Float> STMath::maskedArray( const Vector<Float>& s,
832                                        const Vector<uChar>& f)
833{
834  Vector<Bool> mask;
835  mask.resize(f.shape());
836  convertArray(mask, f);
837  return MaskedArray<Float>(s,!mask);
838}
839
840MaskedArray<Double> STMath::maskedArray( const Vector<Double>& s,
841                                         const Vector<uChar>& f)
842{
843  Vector<Bool> mask;
844  mask.resize(f.shape());
845  convertArray(mask, f);
846  return MaskedArray<Double>(s,!mask);
847}
848
849Vector<uChar> STMath::flagsFromMA(const MaskedArray<Float>& ma)
850{
851  const Vector<Bool>& m = ma.getMask();
852  Vector<uChar> flags(m.shape());
853  convertArray(flags, !m);
854  return flags;
855}
856
857CountedPtr< Scantable > STMath::autoQuotient( const CountedPtr< Scantable >& in,
858                                              const std::string & mode,
859                                              bool preserve )
860{
861  /// @todo make other modes available
862  /// modes should be "nearest", "pair"
863  // make this operation non insitu
864  (void) mode; //currently unused
865  const Table& tin = in->table();
866  Table ons = tin(tin.col("SRCTYPE") == Int(SrcType::PSON));
867  Table offs = tin(tin.col("SRCTYPE") == Int(SrcType::PSOFF));
868  if ( offs.nrow() == 0 )
869    throw(AipsError("No 'off' scans present."));
870  // put all "on" scans into output table
871
872  bool insitu = insitu_;
873  setInsitu(false);
874  CountedPtr< Scantable > out = getScantable(in, true);
875  setInsitu(insitu);
876  Table& tout = out->table();
877
878  TableCopy::copyRows(tout, ons);
879  TableRow row(tout);
880  ROScalarColumn<Double> offtimeCol(offs, "TIME");
881  ArrayColumn<Float> outspecCol(tout, "SPECTRA");
882  ROArrayColumn<Float> outtsysCol(tout, "TSYS");
883  ArrayColumn<uChar> outflagCol(tout, "FLAGTRA");
884  for (uInt i=0; i < tout.nrow(); ++i) {
885    const TableRecord& rec = row.get(i);
886    Double ontime = rec.asDouble("TIME");
887    Table presel = offs(offs.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
888                        && offs.col("IFNO") == Int(rec.asuInt("IFNO"))
889                        && offs.col("POLNO") == Int(rec.asuInt("POLNO")) );
890    ROScalarColumn<Double> offtimeCol(presel, "TIME");
891
892    Double mindeltat = min(abs(offtimeCol.getColumn() - ontime));
893    // Timestamp may vary within a cycle ???!!!
894    // increase this by 0.01 sec in case of rounding errors...
895    // There might be a better way to do this.
896    // fix to this fix. TIME is MJD, so 1.0d not 1.0s
897    mindeltat += 0.01/24./60./60.;
898    Table sel = presel( abs(presel.col("TIME")-ontime) <= mindeltat);
899
900    if ( sel.nrow() < 1 )  {
901      throw(AipsError("No closest in time found... This could be a rounding "
902                      "issue. Try quotient instead."));
903    }
904    TableRow offrow(sel);
905    const TableRecord& offrec = offrow.get(0);//should only be one row
906    RORecordFieldPtr< Array<Float> > specoff(offrec, "SPECTRA");
907    RORecordFieldPtr< Array<Float> > tsysoff(offrec, "TSYS");
908    RORecordFieldPtr< Array<uChar> > flagoff(offrec, "FLAGTRA");
909    /// @fixme this assumes tsys is a scalar not vector
910    Float tsysoffscalar = (*tsysoff)(IPosition(1,0));
911    Vector<Float> specon, tsyson;
912    outtsysCol.get(i, tsyson);
913    outspecCol.get(i, specon);
914    Vector<uChar> flagon;
915    outflagCol.get(i, flagon);
916    MaskedArray<Float> mon = maskedArray(specon, flagon);
917    MaskedArray<Float> moff = maskedArray(*specoff, *flagoff);
918    MaskedArray<Float> quot = (tsysoffscalar * mon / moff);
919    if (preserve) {
920      quot -= tsysoffscalar;
921    } else {
922      quot -= tsyson[0];
923    }
924    outspecCol.put(i, quot.getArray());
925    outflagCol.put(i, flagsFromMA(quot));
926  }
927  // renumber scanno
928  TableIterator it(tout, "SCANNO");
929  uInt i = 0;
930  while ( !it.pastEnd() ) {
931    Table t = it.table();
932    TableVector<uInt> vec(t, "SCANNO");
933    vec = i;
934    ++i;
935    ++it;
936  }
937  return out;
938}
939
940
941CountedPtr< Scantable > STMath::quotient( const CountedPtr< Scantable > & on,
942                                          const CountedPtr< Scantable > & off,
943                                          bool preserve )
944{
945  bool insitu = insitu_;
946  if ( ! on->conformant(*off) ) {
947    throw(AipsError("'on' and 'off' scantables are not conformant."));
948  }
949  setInsitu(false);
950  CountedPtr< Scantable > out = getScantable(on, false);
951  setInsitu(insitu);
952  Table& tout = out->table();
953  const Table& toff = off->table();
954  TableIterator sit(tout, "SCANNO");
955  TableIterator s2it(toff, "SCANNO");
956  while ( !sit.pastEnd() ) {
957    Table ton = sit.table();
958    TableRow row(ton);
959    Table t = s2it.table();
960    ArrayColumn<Float> outspecCol(ton, "SPECTRA");
961    ROArrayColumn<Float> outtsysCol(ton, "TSYS");
962    ArrayColumn<uChar> outflagCol(ton, "FLAGTRA");
963    for (uInt i=0; i < ton.nrow(); ++i) {
964      const TableRecord& rec = row.get(i);
965      Table offsel = t( t.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
966                          && t.col("IFNO") == Int(rec.asuInt("IFNO"))
967                          && t.col("POLNO") == Int(rec.asuInt("POLNO")) );
968      if ( offsel.nrow() == 0 )
969        throw AipsError("STMath::quotient: no matching off");
970      TableRow offrow(offsel);
971      const TableRecord& offrec = offrow.get(0);//should be ncycles - take first
972      RORecordFieldPtr< Array<Float> > specoff(offrec, "SPECTRA");
973      RORecordFieldPtr< Array<Float> > tsysoff(offrec, "TSYS");
974      RORecordFieldPtr< Array<uChar> > flagoff(offrec, "FLAGTRA");
975      Float tsysoffscalar = (*tsysoff)(IPosition(1,0));
976      Vector<Float> specon, tsyson;
977      outtsysCol.get(i, tsyson);
978      outspecCol.get(i, specon);
979      Vector<uChar> flagon;
980      outflagCol.get(i, flagon);
981      MaskedArray<Float> mon = maskedArray(specon, flagon);
982      MaskedArray<Float> moff = maskedArray(*specoff, *flagoff);
983      MaskedArray<Float> quot = (tsysoffscalar * mon / moff);
984      if (preserve) {
985        quot -= tsysoffscalar;
986      } else {
987        quot -= tsyson[0];
988      }
989      outspecCol.put(i, quot.getArray());
990      outflagCol.put(i, flagsFromMA(quot));
991    }
992    ++sit;
993    ++s2it;
994    // take the first off for each on scan which doesn't have a
995    // matching off scan
996    // non <= noff:  matching pairs, non > noff matching pairs then first off
997    if ( s2it.pastEnd() ) s2it.reset();
998  }
999  return out;
1000}
1001
1002// dototalpower (migration of GBTIDL procedure dototalpower.pro)
1003// calibrate the CAL on-off pair. It calculate Tsys and average CAL on-off subintegrations
1004// do it for each cycles in a specific scan.
1005CountedPtr< Scantable > STMath::dototalpower( const CountedPtr< Scantable >& calon,
1006                                              const CountedPtr< Scantable >& caloff, Float tcal )
1007{
1008  if ( ! calon->conformant(*caloff) ) {
1009    throw(AipsError("'CAL on' and 'CAL off' scantables are not conformant."));
1010  }
1011  setInsitu(false);
1012  CountedPtr< Scantable > out = getScantable(caloff, false);
1013  Table& tout = out->table();
1014  const Table& tcon = calon->table();
1015  Vector<Float> tcalout;
1016
1017  std::map<uInt,uInt> tcalIdToRecNoMap;
1018  const Table& calOffTcalTable = caloff->tcal().table();
1019  {
1020    ROScalarColumn<uInt> calOffTcalTable_IDcol(calOffTcalTable, "ID");
1021    const Vector<uInt> tcalIds(calOffTcalTable_IDcol.getColumn());
1022    size_t tcalIdsEnd = tcalIds.nelements();
1023    for (uInt i = 0; i < tcalIdsEnd; i++) {
1024      tcalIdToRecNoMap[tcalIds[i]] = i;
1025    }
1026  }
1027  ROArrayColumn<Float> calOffTcalTable_TCALcol(calOffTcalTable, "TCAL");
1028
1029  if ( tout.nrow() != tcon.nrow() ) {
1030    throw(AipsError("Mismatch in number of rows to form cal on - off pair."));
1031  }
1032  // iteration by scanno or cycle no.
1033  TableIterator sit(tout, "SCANNO");
1034  TableIterator s2it(tcon, "SCANNO");
1035  while ( !sit.pastEnd() ) {
1036    Table toff = sit.table();
1037    TableRow row(toff);
1038    Table t = s2it.table();
1039    ScalarColumn<Double> outintCol(toff, "INTERVAL");
1040    ArrayColumn<Float> outspecCol(toff, "SPECTRA");
1041    ArrayColumn<Float> outtsysCol(toff, "TSYS");
1042    ArrayColumn<uChar> outflagCol(toff, "FLAGTRA");
1043    ROScalarColumn<uInt> outtcalIdCol(toff, "TCAL_ID");
1044    ROScalarColumn<uInt> outpolCol(toff, "POLNO");
1045    ROScalarColumn<Double> onintCol(t, "INTERVAL");
1046    ROArrayColumn<Float> onspecCol(t, "SPECTRA");
1047    ROArrayColumn<Float> ontsysCol(t, "TSYS");
1048    ROArrayColumn<uChar> onflagCol(t, "FLAGTRA");
1049    //ROScalarColumn<uInt> ontcalIdCol(t, "TCAL_ID");
1050
1051    for (uInt i=0; i < toff.nrow(); ++i) {
1052      //skip these checks -> assumes the data order are the same between the cal on off pairs
1053      //
1054      Vector<Float> specCalon, specCaloff;
1055      // to store scalar (mean) tsys
1056      Vector<Float> tsysout(1);
1057      uInt tcalId, polno;
1058      Double offint, onint;
1059      outpolCol.get(i, polno);
1060      outspecCol.get(i, specCaloff);
1061      onspecCol.get(i, specCalon);
1062      Vector<uChar> flagCaloff, flagCalon;
1063      outflagCol.get(i, flagCaloff);
1064      onflagCol.get(i, flagCalon);
1065      outtcalIdCol.get(i, tcalId);
1066      outintCol.get(i, offint);
1067      onintCol.get(i, onint);
1068      // caluculate mean Tsys
1069      uInt nchan = specCaloff.nelements();
1070      // percentage of edge cut off
1071      uInt pc = 10;
1072      uInt bchan = nchan/pc;
1073      uInt echan = nchan-bchan;
1074
1075      Slicer chansl(IPosition(1,bchan-1), IPosition(1,echan-1), IPosition(1,1),Slicer::endIsLast);
1076      Vector<Float> testsubsp = specCaloff(chansl);
1077      MaskedArray<Float> spoff = maskedArray( specCaloff(chansl),flagCaloff(chansl) );
1078      MaskedArray<Float> spon = maskedArray( specCalon(chansl),flagCalon(chansl) );
1079      MaskedArray<Float> spdiff = spon-spoff;
1080      uInt noff = spoff.nelementsValid();
1081      //uInt non = spon.nelementsValid();
1082      uInt ndiff = spdiff.nelementsValid();
1083      Float meantsys;
1084
1085/**
1086      Double subspec, subdiff;
1087      uInt usednchan;
1088      subspec = 0;
1089      subdiff = 0;
1090      usednchan = 0;
1091      for(uInt k=(bchan-1); k<echan; k++) {
1092        subspec += specCaloff[k];
1093        subdiff += static_cast<Double>(specCalon[k]-specCaloff[k]);
1094        ++usednchan;
1095      }
1096**/
1097      // get tcal if input tcal <= 0
1098      Float tcalUsed;
1099      tcalUsed = tcal;
1100      if ( tcal <= 0.0 ) {
1101        uInt tcalRecNo = tcalIdToRecNoMap[tcalId];
1102        calOffTcalTable_TCALcol.get(tcalRecNo, tcalout);
1103//         if (polno<=3) {
1104//           tcalUsed = tcalout[polno];
1105//         }
1106//         else {
1107//           tcalUsed = tcalout[0];
1108//         }
1109        if ( tcalout.size() == 1 )
1110          tcalUsed = tcalout[0] ;
1111        else if ( tcalout.size() == nchan )
1112          tcalUsed = mean(tcalout) ;
1113        else {
1114          uInt ipol = polno ;
1115          if ( ipol > 3 ) ipol = 0 ;
1116          tcalUsed = tcalout[ipol] ;
1117        }
1118      }
1119
1120      Float meanoff;
1121      Float meandiff;
1122      if (noff && ndiff) {
1123         //Debug
1124         //if(noff!=ndiff) cerr<<"noff and ndiff is not equal"<<endl;
1125         //LogIO os( LogOrigin( "STMath", "dototalpower()", WHERE ) ) ;
1126         //if(noff!=ndiff) os<<"noff and ndiff is not equal"<<LogIO::POST;
1127         meanoff = sum(spoff)/noff;
1128         meandiff = sum(spdiff)/ndiff;
1129         meantsys= (meanoff/meandiff )*tcalUsed + tcalUsed/2;
1130      }
1131      else {
1132         meantsys=1;
1133      }
1134
1135      tsysout[0] = Float(meantsys);
1136      MaskedArray<Float> mcaloff = maskedArray(specCaloff, flagCaloff);
1137      MaskedArray<Float> mcalon = maskedArray(specCalon, flagCalon);
1138      MaskedArray<Float> sig =   Float(0.5) * (mcaloff + mcalon);
1139      //uInt ncaloff = mcaloff.nelementsValid();
1140      //uInt ncalon = mcalon.nelementsValid();
1141
1142      outintCol.put(i, offint+onint);
1143      outspecCol.put(i, sig.getArray());
1144      outflagCol.put(i, flagsFromMA(sig));
1145      outtsysCol.put(i, tsysout);
1146    }
1147    ++sit;
1148    ++s2it;
1149  }
1150  return out;
1151}
1152
1153//dosigref - migrated from GBT IDL's dosigref.pro, do calibration of position switch
1154// observatiions.
1155// input: sig and ref scantables, and an optional boxcar smoothing width(default width=0,
1156//        no smoothing).
1157// output: resultant scantable [= (sig-ref/ref)*tsys]
1158CountedPtr< Scantable > STMath::dosigref( const CountedPtr < Scantable >& sig,
1159                                          const CountedPtr < Scantable >& ref,
1160                                          int smoothref,
1161                                          casa::Float tsysv,
1162                                          casa::Float tau )
1163{
1164if ( ! ref->conformant(*sig) ) {
1165    throw(AipsError("'sig' and 'ref' scantables are not conformant."));
1166  }
1167  setInsitu(false);
1168  CountedPtr< Scantable > out = getScantable(sig, false);
1169  CountedPtr< Scantable > smref;
1170  if ( smoothref > 1 ) {
1171    float fsmoothref = static_cast<float>(smoothref);
1172    std::string inkernel = "boxcar";
1173    smref = smooth(ref, inkernel, fsmoothref );
1174    ostringstream oss;
1175    oss<<"Applied smoothing of "<<fsmoothref<<" on the reference."<<endl;
1176    pushLog(String(oss));
1177  }
1178  else {
1179    smref = ref;
1180  }
1181  Table& tout = out->table();
1182  const Table& tref = smref->table();
1183  if ( tout.nrow() != tref.nrow() ) {
1184    throw(AipsError("Mismatch in number of rows to form on-source and reference pair."));
1185  }
1186  // iteration by scanno? or cycle no.
1187  TableIterator sit(tout, "SCANNO");
1188  TableIterator s2it(tref, "SCANNO");
1189  while ( !sit.pastEnd() ) {
1190    Table ton = sit.table();
1191    Table t = s2it.table();
1192    ScalarColumn<Double> outintCol(ton, "INTERVAL");
1193    ArrayColumn<Float> outspecCol(ton, "SPECTRA");
1194    ArrayColumn<Float> outtsysCol(ton, "TSYS");
1195    ArrayColumn<uChar> outflagCol(ton, "FLAGTRA");
1196    ArrayColumn<Float> refspecCol(t, "SPECTRA");
1197    ROScalarColumn<Double> refintCol(t, "INTERVAL");
1198    ROArrayColumn<Float> reftsysCol(t, "TSYS");
1199    ArrayColumn<uChar> refflagCol(t, "FLAGTRA");
1200    ROScalarColumn<Float> refelevCol(t, "ELEVATION");
1201    for (uInt i=0; i < ton.nrow(); ++i) {
1202
1203      Double onint, refint;
1204      Vector<Float> specon, specref;
1205      // to store scalar (mean) tsys
1206      Vector<Float> tsysref;
1207      outintCol.get(i, onint);
1208      refintCol.get(i, refint);
1209      outspecCol.get(i, specon);
1210      refspecCol.get(i, specref);
1211      Vector<uChar> flagref, flagon;
1212      outflagCol.get(i, flagon);
1213      refflagCol.get(i, flagref);
1214      reftsysCol.get(i, tsysref);
1215
1216      Float tsysrefscalar;
1217      if ( tsysv > 0.0 ) {
1218        ostringstream oss;
1219        Float elev;
1220        refelevCol.get(i, elev);
1221        oss << "user specified Tsys = " << tsysv;
1222        // do recalc elevation if EL = 0
1223        if ( elev == 0 ) {
1224          throw(AipsError("EL=0, elevation data is missing."));
1225        } else {
1226          if ( tau <= 0.0 ) {
1227            throw(AipsError("Valid tau is not supplied."));
1228          } else {
1229            tsysrefscalar = tsysv * exp(tau/elev);
1230          }
1231        }
1232        oss << ", corrected (for El) tsys= "<<tsysrefscalar;
1233        pushLog(String(oss));
1234      }
1235      else {
1236        tsysrefscalar = tsysref[0];
1237      }
1238      //get quotient spectrum
1239      MaskedArray<Float> mref = maskedArray(specref, flagref);
1240      MaskedArray<Float> mon = maskedArray(specon, flagon);
1241      MaskedArray<Float> specres =   tsysrefscalar*((mon - mref)/mref);
1242      Double resint = onint*refint*smoothref/(onint+refint*smoothref);
1243
1244      //Debug
1245      //cerr<<"Tsys used="<<tsysrefscalar<<endl;
1246      //LogIO os( LogOrigin( "STMath", "dosigref", WHERE ) ) ;
1247      //os<<"Tsys used="<<tsysrefscalar<<LogIO::POST;
1248      // fill the result, replay signal tsys by reference tsys
1249      outintCol.put(i, resint);
1250      outspecCol.put(i, specres.getArray());
1251      outflagCol.put(i, flagsFromMA(specres));
1252      outtsysCol.put(i, tsysref);
1253    }
1254    ++sit;
1255    ++s2it;
1256  }
1257  return out;
1258}
1259
1260CountedPtr< Scantable > STMath::donod(const casa::CountedPtr<Scantable>& s,
1261                                     const std::vector<int>& scans,
1262                                     int smoothref,
1263                                     casa::Float tsysv,
1264                                     casa::Float tau,
1265                                     casa::Float tcal )
1266
1267{
1268  setInsitu(false);
1269  STSelector sel;
1270  std::vector<int> scan1, scan2, beams, types;
1271  std::vector< vector<int> > scanpair;
1272  //std::vector<string> calstate;
1273  std::vector<int> calstate;
1274  String msg;
1275
1276  CountedPtr< Scantable > s1b1on, s1b1off, s1b2on, s1b2off;
1277  CountedPtr< Scantable > s2b1on, s2b1off, s2b2on, s2b2off;
1278
1279  std::vector< CountedPtr< Scantable > > sctables;
1280  sctables.push_back(s1b1on);
1281  sctables.push_back(s1b1off);
1282  sctables.push_back(s1b2on);
1283  sctables.push_back(s1b2off);
1284  sctables.push_back(s2b1on);
1285  sctables.push_back(s2b1off);
1286  sctables.push_back(s2b2on);
1287  sctables.push_back(s2b2off);
1288
1289  //check scanlist
1290  int n=s->checkScanInfo(scans);
1291  if (n==1) {
1292     throw(AipsError("Incorrect scan pairs. "));
1293  }
1294
1295  // Assume scans contain only a pair of consecutive scan numbers.
1296  // It is assumed that first beam, b1,  is on target.
1297  // There is no check if the first beam is on or not.
1298  if ( scans.size()==1 ) {
1299    scan1.push_back(scans[0]);
1300    scan2.push_back(scans[0]+1);
1301  } else if ( scans.size()==2 ) {
1302   scan1.push_back(scans[0]);
1303   scan2.push_back(scans[1]);
1304  } else {
1305    if ( scans.size()%2 == 0 ) {
1306      for (uInt i=0; i<scans.size(); i++) {
1307        if (i%2 == 0) {
1308          scan1.push_back(scans[i]);
1309        }
1310        else {
1311          scan2.push_back(scans[i]);
1312        }
1313      }
1314    } else {
1315      throw(AipsError("Odd numbers of scans, cannot form pairs."));
1316    }
1317  }
1318  scanpair.push_back(scan1);
1319  scanpair.push_back(scan2);
1320  //calstate.push_back("*calon");
1321  //calstate.push_back("*[^calon]");
1322  calstate.push_back(SrcType::NODCAL);
1323  calstate.push_back(SrcType::NOD);
1324  CountedPtr< Scantable > ws = getScantable(s, false);
1325  uInt l=0;
1326  while ( l < sctables.size() ) {
1327    for (uInt i=0; i < 2; i++) {
1328      for (uInt j=0; j < 2; j++) {
1329        for (uInt k=0; k < 2; k++) {
1330          sel.reset();
1331          sel.setScans(scanpair[i]);
1332          //sel.setName(calstate[k]);
1333          types.clear();
1334          types.push_back(calstate[k]);
1335          sel.setTypes(types);
1336          beams.clear();
1337          beams.push_back(j);
1338          sel.setBeams(beams);
1339          ws->setSelection(sel);
1340          sctables[l]= getScantable(ws, false);
1341          l++;
1342        }
1343      }
1344    }
1345  }
1346
1347  // replace here by splitData or getData functionality
1348  CountedPtr< Scantable > sig1;
1349  CountedPtr< Scantable > ref1;
1350  CountedPtr< Scantable > sig2;
1351  CountedPtr< Scantable > ref2;
1352  CountedPtr< Scantable > calb1;
1353  CountedPtr< Scantable > calb2;
1354
1355  msg=String("Processing dototalpower for subset of the data");
1356  ostringstream oss1;
1357  oss1 << msg  << endl;
1358  pushLog(String(oss1));
1359  // Debug for IRC CS data
1360  //float tcal1=7.0;
1361  //float tcal2=4.0;
1362  sig1 = dototalpower(sctables[0], sctables[1], tcal=tcal);
1363  ref1 = dototalpower(sctables[2], sctables[3], tcal=tcal);
1364  ref2 = dototalpower(sctables[4], sctables[5], tcal=tcal);
1365  sig2 = dototalpower(sctables[6], sctables[7], tcal=tcal);
1366
1367  // correction of user-specified tsys for elevation here
1368
1369  // dosigref calibration
1370  msg=String("Processing dosigref for subset of the data");
1371  ostringstream oss2;
1372  oss2 << msg  << endl;
1373  pushLog(String(oss2));
1374  calb1=dosigref(sig1,ref2,smoothref,tsysv,tau);
1375  calb2=dosigref(sig2,ref1,smoothref,tsysv,tau);
1376
1377  // iteration by scanno or cycle no.
1378  Table& tcalb1 = calb1->table();
1379  Table& tcalb2 = calb2->table();
1380  TableIterator sit(tcalb1, "SCANNO");
1381  TableIterator s2it(tcalb2, "SCANNO");
1382  while ( !sit.pastEnd() ) {
1383    Table t1 = sit.table();
1384    Table t2= s2it.table();
1385    ArrayColumn<Float> outspecCol(t1, "SPECTRA");
1386    ArrayColumn<Float> outtsysCol(t1, "TSYS");
1387    ArrayColumn<uChar> outflagCol(t1, "FLAGTRA");
1388    ScalarColumn<Double> outintCol(t1, "INTERVAL");
1389    ArrayColumn<Float> t2specCol(t2, "SPECTRA");
1390    ROArrayColumn<Float> t2tsysCol(t2, "TSYS");
1391    ArrayColumn<uChar> t2flagCol(t2, "FLAGTRA");
1392    ROScalarColumn<Double> t2intCol(t2, "INTERVAL");
1393    for (uInt i=0; i < t1.nrow(); ++i) {
1394      Vector<Float> spec1, spec2;
1395      // to store scalar (mean) tsys
1396      Vector<Float> tsys1, tsys2;
1397      Vector<uChar> flag1, flag2;
1398      Double tint1, tint2;
1399      outspecCol.get(i, spec1);
1400      t2specCol.get(i, spec2);
1401      outflagCol.get(i, flag1);
1402      t2flagCol.get(i, flag2);
1403      outtsysCol.get(i, tsys1);
1404      t2tsysCol.get(i, tsys2);
1405      outintCol.get(i, tint1);
1406      t2intCol.get(i, tint2);
1407      // average
1408      // assume scalar tsys for weights
1409      Float wt1, wt2, tsyssq1, tsyssq2;
1410      tsyssq1 = tsys1[0]*tsys1[0];
1411      tsyssq2 = tsys2[0]*tsys2[0];
1412      wt1 = Float(tint1)/tsyssq1;
1413      wt2 = Float(tint2)/tsyssq2;
1414      Float invsumwt=1/(wt1+wt2);
1415      MaskedArray<Float> mspec1 = maskedArray(spec1, flag1);
1416      MaskedArray<Float> mspec2 = maskedArray(spec2, flag2);
1417      MaskedArray<Float> avspec =  invsumwt * (wt1*mspec1 + wt2*mspec2);
1418      //Array<Float> avtsys =  Float(0.5) * (tsys1 + tsys2);
1419      // cerr<< "Tsys1="<<tsys1<<" Tsys2="<<tsys2<<endl;
1420      // LogIO os( LogOrigin( "STMath", "donod", WHERE ) ) ;
1421      // os<< "Tsys1="<<tsys1<<" Tsys2="<<tsys2<<LogIO::POST;
1422      tsys1[0] = sqrt(tsyssq1 + tsyssq2);
1423      Array<Float> avtsys =  tsys1;
1424
1425      outspecCol.put(i, avspec.getArray());
1426      outflagCol.put(i, flagsFromMA(avspec));
1427      outtsysCol.put(i, avtsys);
1428    }
1429    ++sit;
1430    ++s2it;
1431  }
1432  return calb1;
1433}
1434
1435//GBTIDL version of frequency switched data calibration
1436CountedPtr< Scantable > STMath::dofs( const CountedPtr< Scantable >& s,
1437                                      const std::vector<int>& scans,
1438                                      int smoothref,
1439                                      casa::Float tsysv,
1440                                      casa::Float tau,
1441                                      casa::Float tcal )
1442{
1443
1444
1445  (void) scans; //currently unused
1446  STSelector sel;
1447  CountedPtr< Scantable > ws = getScantable(s, false);
1448  CountedPtr< Scantable > sig, sigwcal, ref, refwcal;
1449  CountedPtr< Scantable > calsig, calref, out, out1, out2;
1450  Bool nofold=False;
1451  vector<int> types ;
1452
1453  //split the data
1454  //sel.setName("*_fs");
1455  types.push_back( SrcType::FSON ) ;
1456  sel.setTypes( types ) ;
1457  ws->setSelection(sel);
1458  sig = getScantable(ws,false);
1459  sel.reset();
1460  types.clear() ;
1461  //sel.setName("*_fs_calon");
1462  types.push_back( SrcType::FONCAL ) ;
1463  sel.setTypes( types ) ;
1464  ws->setSelection(sel);
1465  sigwcal = getScantable(ws,false);
1466  sel.reset();
1467  types.clear() ;
1468  //sel.setName("*_fsr");
1469  types.push_back( SrcType::FSOFF ) ;
1470  sel.setTypes( types ) ;
1471  ws->setSelection(sel);
1472  ref = getScantable(ws,false);
1473  sel.reset();
1474  types.clear() ;
1475  //sel.setName("*_fsr_calon");
1476  types.push_back( SrcType::FOFFCAL ) ;
1477  sel.setTypes( types ) ;
1478  ws->setSelection(sel);
1479  refwcal = getScantable(ws,false);
1480  sel.reset() ;
1481  types.clear() ;
1482
1483  calsig = dototalpower(sigwcal, sig, tcal=tcal);
1484  calref = dototalpower(refwcal, ref, tcal=tcal);
1485
1486  out1=dosigref(calsig,calref,smoothref,tsysv,tau);
1487  out2=dosigref(calref,calsig,smoothref,tsysv,tau);
1488
1489  Table& tabout1=out1->table();
1490  Table& tabout2=out2->table();
1491  ROScalarColumn<uInt> freqidCol1(tabout1, "FREQ_ID");
1492  ScalarColumn<uInt> freqidCol2(tabout2, "FREQ_ID");
1493  ROArrayColumn<Float> specCol(tabout2, "SPECTRA");
1494  Vector<Float> spec; specCol.get(0, spec);
1495  uInt nchan = spec.nelements();
1496  uInt freqid1; freqidCol1.get(0,freqid1);
1497  uInt freqid2; freqidCol2.get(0,freqid2);
1498  Double rp1, rp2, rv1, rv2, inc1, inc2;
1499  out1->frequencies().getEntry(rp1, rv1, inc1, freqid1);
1500  out2->frequencies().getEntry(rp2, rv2, inc2, freqid2);
1501  //cerr << out1->frequencies().table().nrow() << " " << out2->frequencies().table().nrow() << endl ;
1502  //LogIO os( LogOrigin( "STMath", "dofs()", WHERE ) ) ;
1503  //os << out1->frequencies().table().nrow() << " " << out2->frequencies().table().nrow() << LogIO::POST ;
1504  if (rp1==rp2) {
1505    Double foffset = rv1 - rv2;
1506    uInt choffset = static_cast<uInt>(foffset/abs(inc2));
1507    if (choffset >= nchan) {
1508      //cerr<<"out-band frequency switching, no folding"<<endl;
1509      LogIO os( LogOrigin( "STMath", "dofs()", WHERE ) ) ;
1510      os<<"out-band frequency switching, no folding"<<LogIO::POST;
1511      nofold = True;
1512    }
1513  }
1514
1515  if (nofold) {
1516    std::vector< CountedPtr< Scantable > > tabs;
1517    tabs.push_back(out1);
1518    tabs.push_back(out2);
1519    out = merge(tabs);
1520  }
1521  else {
1522    //out = out1;
1523    Double choffset = ( rv1 - rv2 ) / inc2 ;
1524    out = dofold( out1, out2, choffset ) ;
1525  }
1526   
1527  return out;
1528}
1529
1530CountedPtr<Scantable> STMath::dofold( const CountedPtr<Scantable> &sig,
1531                                      const CountedPtr<Scantable> &ref,
1532                                      Double choffset,
1533                                      Double choffset2 )
1534{
1535  LogIO os( LogOrigin( "STMath", "dofold", WHERE ) ) ;
1536  os << "choffset=" << choffset << " choffset2=" << choffset2 << LogIO::POST ;
1537
1538  // output scantable
1539  CountedPtr<Scantable> out = getScantable( sig, false ) ;
1540
1541  // separate choffset to integer part and decimal part
1542  Int ioffset = (Int)choffset ;
1543  Double doffset = choffset - ioffset ;
1544  Int ioffset2 = (Int)choffset2 ;
1545  Double doffset2 = choffset2 - ioffset2 ;
1546  os << "ioffset=" << ioffset << " doffset=" << doffset << LogIO::POST ;
1547  os << "ioffset2=" << ioffset2 << " doffset2=" << doffset2 << LogIO::POST ; 
1548
1549  // get column
1550  ROArrayColumn<Float> specCol1( sig->table(), "SPECTRA" ) ;
1551  ROArrayColumn<Float> specCol2( ref->table(), "SPECTRA" ) ;
1552  ROArrayColumn<Float> tsysCol1( sig->table(), "TSYS" ) ;
1553  ROArrayColumn<Float> tsysCol2( ref->table(), "TSYS" ) ;
1554  ROArrayColumn<uChar> flagCol1( sig->table(), "FLAGTRA" ) ;
1555  ROArrayColumn<uChar> flagCol2( ref->table(), "FLAGTRA" ) ;
1556  ROScalarColumn<Double> mjdCol1( sig->table(), "TIME" ) ;
1557  ROScalarColumn<Double> mjdCol2( ref->table(), "TIME" ) ;
1558  ROScalarColumn<Double> intervalCol1( sig->table(), "INTERVAL" ) ;
1559  ROScalarColumn<Double> intervalCol2( ref->table(), "INTERVAL" ) ;
1560
1561  // check
1562  if ( ioffset == 0 ) {
1563    LogIO os( LogOrigin( "STMath", "dofold()", WHERE ) ) ;
1564    os << "channel offset is zero, no folding" << LogIO::POST ;
1565    return out ;
1566  }
1567  int nchan = ref->nchan() ;
1568  if ( abs(ioffset) >= nchan ) {
1569    LogIO os( LogOrigin( "STMath", "dofold()", WHERE ) ) ;
1570    os << "out-band frequency switching, no folding" << LogIO::POST ;
1571    return out ;
1572  }
1573
1574  // attach column for output scantable
1575  ArrayColumn<Float> specColOut( out->table(), "SPECTRA" ) ;
1576  ArrayColumn<uChar> flagColOut( out->table(), "FLAGTRA" ) ;
1577  ArrayColumn<Float> tsysColOut( out->table(), "TSYS" ) ;
1578  ScalarColumn<Double> mjdColOut( out->table(), "TIME" ) ;
1579  ScalarColumn<Double> intervalColOut( out->table(), "INTERVAL" ) ;
1580  ScalarColumn<uInt> fidColOut( out->table(), "FREQ_ID" ) ;
1581
1582  // for each row
1583  // assume that the data order are same between sig and ref
1584  RowAccumulator acc( asap::W_TINTSYS ) ;
1585  for ( int i = 0 ; i < sig->nrow() ; i++ ) {
1586    // get values
1587    Vector<Float> spsig ;
1588    specCol1.get( i, spsig ) ;
1589    Vector<Float> spref ;
1590    specCol2.get( i, spref ) ;
1591    Vector<Float> tsyssig ;
1592    tsysCol1.get( i, tsyssig ) ;
1593    Vector<Float> tsysref ;
1594    tsysCol2.get( i, tsysref ) ;
1595    Vector<uChar> flagsig ;
1596    flagCol1.get( i, flagsig ) ;
1597    Vector<uChar> flagref ;
1598    flagCol2.get( i, flagref ) ;
1599    Double timesig ;
1600    mjdCol1.get( i, timesig ) ;
1601    Double timeref ;
1602    mjdCol2.get( i, timeref ) ;
1603    Double intsig ;
1604    intervalCol1.get( i, intsig ) ;
1605    Double intref ;
1606    intervalCol2.get( i, intref ) ;
1607
1608    // shift reference spectra
1609    int refchan = spref.nelements() ;
1610    Vector<Float> sspref( spref.nelements() ) ;
1611    Vector<Float> stsysref( tsysref.nelements() ) ;
1612    Vector<uChar> sflagref( flagref.nelements() ) ;
1613    if ( ioffset > 0 ) {
1614      // SPECTRA and FLAGTRA
1615      for ( int j = 0 ; j < refchan-ioffset ; j++ ) {
1616        sspref[j] = spref[j+ioffset] ;
1617        sflagref[j] = flagref[j+ioffset] ;
1618      }
1619      for ( int j = refchan-ioffset ; j < refchan ; j++ ) {
1620        sspref[j] = spref[j-refchan+ioffset] ;
1621        sflagref[j] = flagref[j-refchan+ioffset] ;
1622      }
1623      spref = sspref.copy() ;
1624      flagref = sflagref.copy() ;
1625      for ( int j = 0 ; j < refchan - 1 ; j++ ) {
1626        sspref[j] = doffset * spref[j+1] + ( 1.0 - doffset ) * spref[j] ;
1627        sflagref[j] = flagref[j+1] + flagref[j] ;
1628      }
1629      sspref[refchan-1] = doffset * spref[0] + ( 1.0 - doffset ) * spref[refchan-1] ;
1630      sflagref[refchan-1] = flagref[0] + flagref[refchan-1] ;
1631
1632      // TSYS
1633      if ( spref.nelements() == tsysref.nelements() ) {
1634        for ( int j = 0 ; j < refchan-ioffset ; j++ ) {
1635          stsysref[j] = tsysref[j+ioffset] ;
1636        }
1637        for ( int j = refchan-ioffset ; j < refchan ; j++ ) {
1638          stsysref[j] = tsysref[j-refchan+ioffset] ;
1639        }
1640        tsysref = stsysref.copy() ;
1641        for ( int j = 0 ; j < refchan - 1 ; j++ ) {
1642          stsysref[j] = doffset * tsysref[j+1] + ( 1.0 - doffset ) * tsysref[j] ;
1643        }
1644        stsysref[refchan-1] = doffset * tsysref[0] + ( 1.0 - doffset ) * tsysref[refchan-1] ;
1645      }
1646    }
1647    else {
1648      // SPECTRA and FLAGTRA
1649      for ( int j = 0 ; j < abs(ioffset) ; j++ ) {
1650        sspref[j] = spref[refchan+ioffset+j] ;
1651        sflagref[j] = flagref[refchan+ioffset+j] ;
1652      }
1653      for ( int j = abs(ioffset) ; j < refchan ; j++ ) {
1654        sspref[j] = spref[j+ioffset] ;
1655        sflagref[j] = flagref[j+ioffset] ;
1656      }
1657      spref = sspref.copy() ;
1658      flagref = sflagref.copy() ;
1659      sspref[0] = doffset * spref[refchan-1] + ( 1.0 - doffset ) * spref[0] ;
1660      sflagref[0] = flagref[0] + flagref[refchan-1] ;
1661      for ( int j = 1 ; j < refchan ; j++ ) {
1662        sspref[j] = doffset * spref[j-1] + ( 1.0 - doffset ) * spref[j] ;
1663        sflagref[j] = flagref[j-1] + flagref[j] ;
1664      }
1665      // TSYS
1666      if ( spref.nelements() == tsysref.nelements() ) {
1667        for ( int j = 0 ; j < abs(ioffset) ; j++ ) {
1668          stsysref[j] = tsysref[refchan+ioffset+j] ;
1669        }
1670        for ( int j = abs(ioffset) ; j < refchan ; j++ ) {
1671          stsysref[j] = tsysref[j+ioffset] ;
1672        }
1673        tsysref = stsysref.copy() ;
1674        stsysref[0] = doffset * tsysref[refchan-1] + ( 1.0 - doffset ) * tsysref[0] ;
1675        for ( int j = 1 ; j < refchan ; j++ ) {
1676          stsysref[j] = doffset * tsysref[j-1] + ( 1.0 - doffset ) * tsysref[j] ;
1677        }
1678      }
1679    }
1680
1681    // shift signal spectra if necessary (only for APEX?)
1682    if ( choffset2 != 0.0 ) {
1683      int sigchan = spsig.nelements() ;
1684      Vector<Float> sspsig( spsig.nelements() ) ;
1685      Vector<Float> stsyssig( tsyssig.nelements() ) ;
1686      Vector<uChar> sflagsig( flagsig.nelements() ) ;
1687      if ( ioffset2 > 0 ) {
1688        // SPECTRA and FLAGTRA
1689        for ( int j = 0 ; j < sigchan-ioffset2 ; j++ ) {
1690          sspsig[j] = spsig[j+ioffset2] ;
1691          sflagsig[j] = flagsig[j+ioffset2] ;
1692        }
1693        for ( int j = sigchan-ioffset2 ; j < sigchan ; j++ ) {
1694          sspsig[j] = spsig[j-sigchan+ioffset2] ;
1695          sflagsig[j] = flagsig[j-sigchan+ioffset2] ;
1696        }
1697        spsig = sspsig.copy() ;
1698        flagsig = sflagsig.copy() ;
1699        for ( int j = 0 ; j < sigchan - 1 ; j++ ) {
1700          sspsig[j] = doffset2 * spsig[j+1] + ( 1.0 - doffset2 ) * spsig[j] ;
1701          sflagsig[j] = flagsig[j+1] || flagsig[j] ;
1702        }
1703        sspsig[sigchan-1] = doffset2 * spsig[0] + ( 1.0 - doffset2 ) * spsig[sigchan-1] ;
1704        sflagsig[sigchan-1] = flagsig[0] || flagsig[sigchan-1] ;
1705        // TSTS
1706        if ( spsig.nelements() == tsyssig.nelements() ) {
1707          for ( int j = 0 ; j < sigchan-ioffset2 ; j++ ) {
1708            stsyssig[j] = tsyssig[j+ioffset2] ;
1709          }
1710          for ( int j = sigchan-ioffset2 ; j < sigchan ; j++ ) {
1711            stsyssig[j] = tsyssig[j-sigchan+ioffset2] ;
1712          }
1713          tsyssig = stsyssig.copy() ;
1714          for ( int j = 0 ; j < sigchan - 1 ; j++ ) {
1715            stsyssig[j] = doffset2 * tsyssig[j+1] + ( 1.0 - doffset2 ) * tsyssig[j] ;
1716          }
1717          stsyssig[sigchan-1] = doffset2 * tsyssig[0] + ( 1.0 - doffset2 ) * tsyssig[sigchan-1] ;
1718        }
1719      }
1720      else {
1721        // SPECTRA and FLAGTRA
1722        for ( int j = 0 ; j < abs(ioffset2) ; j++ ) {
1723          sspsig[j] = spsig[sigchan+ioffset2+j] ;
1724          sflagsig[j] = flagsig[sigchan+ioffset2+j] ;
1725        }
1726        for ( int j = abs(ioffset2) ; j < sigchan ; j++ ) {
1727          sspsig[j] = spsig[j+ioffset2] ;
1728          sflagsig[j] = flagsig[j+ioffset2] ;
1729        }
1730        spsig = sspsig.copy() ;
1731        flagsig = sflagsig.copy() ;
1732        sspsig[0] = doffset2 * spsig[sigchan-1] + ( 1.0 - doffset2 ) * spsig[0] ;
1733        sflagsig[0] = flagsig[0] + flagsig[sigchan-1] ;
1734        for ( int j = 1 ; j < sigchan ; j++ ) {
1735          sspsig[j] = doffset2 * spsig[j-1] + ( 1.0 - doffset2 ) * spsig[j] ;
1736          sflagsig[j] = flagsig[j-1] + flagsig[j] ;
1737        }
1738        // TSYS
1739        if ( spsig.nelements() == tsyssig.nelements() ) {
1740          for ( int j = 0 ; j < abs(ioffset2) ; j++ ) {
1741            stsyssig[j] = tsyssig[sigchan+ioffset2+j] ;
1742          }
1743          for ( int j = abs(ioffset2) ; j < sigchan ; j++ ) {
1744            stsyssig[j] = tsyssig[j+ioffset2] ;
1745          }
1746          tsyssig = stsyssig.copy() ;
1747          stsyssig[0] = doffset2 * tsyssig[sigchan-1] + ( 1.0 - doffset2 ) * tsyssig[0] ;
1748          for ( int j = 1 ; j < sigchan ; j++ ) {
1749            stsyssig[j] = doffset2 * tsyssig[j-1] + ( 1.0 - doffset2 ) * tsyssig[j] ;
1750          }
1751        }
1752      }
1753    }
1754
1755    // folding
1756    acc.add( spsig, !flagsig, tsyssig, intsig, timesig ) ;
1757    acc.add( sspref, !sflagref, stsysref, intref, timeref ) ;
1758   
1759    // put result
1760    specColOut.put( i, acc.getSpectrum() ) ;
1761    const Vector<Bool> &msk = acc.getMask() ;
1762    Vector<uChar> flg( msk.shape() ) ;
1763    convertArray( flg, !msk ) ;
1764    flagColOut.put( i, flg ) ;
1765    tsysColOut.put( i, acc.getTsys() ) ;
1766    intervalColOut.put( i, acc.getInterval() ) ;
1767    mjdColOut.put( i, acc.getTime() ) ;
1768    // change FREQ_ID to unshifted IF setting (only for APEX?)
1769    if ( choffset2 != 0.0 ) {
1770      uInt freqid = fidColOut( 0 ) ; // assume single-IF data
1771      double refpix, refval, increment ;
1772      out->frequencies().getEntry( refpix, refval, increment, freqid ) ;
1773      refval -= choffset * increment ;
1774      uInt newfreqid = out->frequencies().addEntry( refpix, refval, increment ) ;
1775      Vector<uInt> freqids = fidColOut.getColumn() ;
1776      for ( uInt j = 0 ; j < freqids.nelements() ; j++ ) {
1777        if ( freqids[j] == freqid )
1778          freqids[j] = newfreqid ;
1779      }
1780      fidColOut.putColumn( freqids ) ;
1781    }
1782
1783    acc.reset() ;
1784  }
1785
1786  return out ;
1787}
1788
1789
1790CountedPtr< Scantable > STMath::freqSwitch( const CountedPtr< Scantable >& in )
1791{
1792  // make copy or reference
1793  CountedPtr< Scantable > out = getScantable(in, false);
1794  Table& tout = out->table();
1795  Block<String> cols(4);
1796  cols[0] = String("SCANNO");
1797  cols[1] = String("CYCLENO");
1798  cols[2] = String("BEAMNO");
1799  cols[3] = String("POLNO");
1800  TableIterator iter(tout, cols);
1801  while (!iter.pastEnd()) {
1802    Table subt = iter.table();
1803    // this should leave us with two rows for the two IFs....if not ignore
1804    if (subt.nrow() != 2 ) {
1805      continue;
1806    }
1807    ArrayColumn<Float> specCol(subt, "SPECTRA");
1808    ArrayColumn<Float> tsysCol(subt, "TSYS");
1809    ArrayColumn<uChar> flagCol(subt, "FLAGTRA");
1810    Vector<Float> onspec,offspec, ontsys, offtsys;
1811    Vector<uChar> onflag, offflag;
1812    tsysCol.get(0, ontsys);   tsysCol.get(1, offtsys);
1813    specCol.get(0, onspec);   specCol.get(1, offspec);
1814    flagCol.get(0, onflag);   flagCol.get(1, offflag);
1815    MaskedArray<Float> on  = maskedArray(onspec, onflag);
1816    MaskedArray<Float> off = maskedArray(offspec, offflag);
1817    MaskedArray<Float> oncopy = on.copy();
1818
1819    on /= off; on -= 1.0f;
1820    on *= ontsys[0];
1821    off /= oncopy; off -= 1.0f;
1822    off *= offtsys[0];
1823    specCol.put(0, on.getArray());
1824    const Vector<Bool>& m0 = on.getMask();
1825    Vector<uChar> flags0(m0.shape());
1826    convertArray(flags0, !m0);
1827    flagCol.put(0, flags0);
1828
1829    specCol.put(1, off.getArray());
1830    const Vector<Bool>& m1 = off.getMask();
1831    Vector<uChar> flags1(m1.shape());
1832    convertArray(flags1, !m1);
1833    flagCol.put(1, flags1);
1834    ++iter;
1835  }
1836
1837  return out;
1838}
1839
1840std::vector< float > STMath::statistic( const CountedPtr< Scantable > & in,
1841                                        const std::vector< bool > & mask,
1842                                        const std::string& which )
1843{
1844
1845  Vector<Bool> m(mask);
1846  const Table& tab = in->table();
1847  ROArrayColumn<Float> specCol(tab, "SPECTRA");
1848  ROArrayColumn<uChar> flagCol(tab, "FLAGTRA");
1849  std::vector<float> out;
1850  for (uInt i=0; i < tab.nrow(); ++i ) {
1851    Vector<Float> spec; specCol.get(i, spec);
1852    Vector<uChar> flag; flagCol.get(i, flag);
1853    MaskedArray<Float> ma  = maskedArray(spec, flag);
1854    float outstat = 0.0;
1855    if ( spec.nelements() == m.nelements() ) {
1856      outstat = mathutil::statistics(which, ma(m));
1857    } else {
1858      outstat = mathutil::statistics(which, ma);
1859    }
1860    out.push_back(outstat);
1861  }
1862  return out;
1863}
1864
1865std::vector< float > STMath::statisticRow( const CountedPtr< Scantable > & in,
1866                                        const std::vector< bool > & mask,
1867                                        const std::string& which,
1868                                        int row )
1869{
1870
1871  Vector<Bool> m(mask);
1872  const Table& tab = in->table();
1873  ROArrayColumn<Float> specCol(tab, "SPECTRA");
1874  ROArrayColumn<uChar> flagCol(tab, "FLAGTRA");
1875  std::vector<float> out;
1876
1877  Vector<Float> spec; specCol.get(row, spec);
1878  Vector<uChar> flag; flagCol.get(row, flag);
1879  MaskedArray<Float> ma  = maskedArray(spec, flag);
1880  float outstat = 0.0;
1881  if ( spec.nelements() == m.nelements() ) {
1882    outstat = mathutil::statistics(which, ma(m));
1883  } else {
1884    outstat = mathutil::statistics(which, ma);
1885  }
1886  out.push_back(outstat);
1887
1888  return out;
1889}
1890
1891std::vector< int > STMath::minMaxChan( const CountedPtr< Scantable > & in,
1892                                        const std::vector< bool > & mask,
1893                                        const std::string& which )
1894{
1895
1896  Vector<Bool> m(mask);
1897  const Table& tab = in->table();
1898  ROArrayColumn<Float> specCol(tab, "SPECTRA");
1899  ROArrayColumn<uChar> flagCol(tab, "FLAGTRA");
1900  std::vector<int> out;
1901  for (uInt i=0; i < tab.nrow(); ++i ) {
1902    Vector<Float> spec; specCol.get(i, spec);
1903    Vector<uChar> flag; flagCol.get(i, flag);
1904    MaskedArray<Float> ma  = maskedArray(spec, flag);
1905    if (ma.ndim() != 1) {
1906      throw (ArrayError(
1907          "std::vector<int> STMath::minMaxChan("
1908          "ContedPtr<Scantable> &in, std::vector<bool> &mask, "
1909          " std::string &which)"
1910          " - MaskedArray is not 1D"));
1911    }
1912    IPosition outpos(1,0);
1913    if ( spec.nelements() == m.nelements() ) {
1914      outpos = mathutil::minMaxPos(which, ma(m));
1915    } else {
1916      outpos = mathutil::minMaxPos(which, ma);
1917    }
1918    out.push_back(outpos[0]);
1919  }
1920  return out;
1921}
1922
1923CountedPtr< Scantable > STMath::bin( const CountedPtr< Scantable > & in,
1924                                     int width )
1925{
1926  if ( !in->getSelection().empty() ) throw(AipsError("Can't bin subset of the data."));
1927  CountedPtr< Scantable > out = getScantable(in, false);
1928  Table& tout = out->table();
1929  out->frequencies().rescale(width, "BIN");
1930  ArrayColumn<Float> specCol(tout, "SPECTRA");
1931  ArrayColumn<uChar> flagCol(tout, "FLAGTRA");
1932  ArrayColumn<Float> tsysCol(tout, "TSYS");
1933
1934  for (uInt i=0; i < tout.nrow(); ++i ) {
1935    MaskedArray<Float> main  = maskedArray(specCol(i), flagCol(i));
1936    MaskedArray<Float> maout;
1937    LatticeUtilities::bin(maout, main, 0, Int(width));
1938    specCol.put(i, maout.getArray());
1939    flagCol.put(i, flagsFromMA(maout));
1940    if (tsysCol(i).nelements() == specCol(i).nelements()) {
1941      MaskedArray<Float> matsysin = maskedArray(tsysCol(i), flagCol(i));
1942      MaskedArray<Float> matsysout;
1943      LatticeUtilities::bin(matsysout, matsysin, 0, Int(width));
1944      tsysCol.put(i, matsysout.getArray());
1945    }
1946    // take only the first binned spectrum's length for the deprecated
1947    // global header item nChan
1948    if (i==0) tout.rwKeywordSet().define(String("nChan"),
1949                                       Int(maout.getArray().nelements()));
1950  }
1951  return out;
1952}
1953
1954CountedPtr< Scantable > STMath::resample( const CountedPtr< Scantable >& in,
1955                                          const std::string& method,
1956                                          float width )
1957//
1958// Should add the possibility of width being specified in km/s. This means
1959// that for each freqID (SpectralCoordinate) we will need to convert to an
1960// average channel width (say at the reference pixel).  Then we would need
1961// to be careful to make sure each spectrum (of different freqID)
1962// is the same length.
1963//
1964{
1965  //InterpolateArray1D<Double,Float>::InterpolationMethod interp;
1966  Int interpMethod(stringToIMethod(method));
1967
1968  CountedPtr< Scantable > out = getScantable(in, false);
1969  Table& tout = out->table();
1970
1971// Resample SpectralCoordinates (one per freqID)
1972  out->frequencies().rescale(width, "RESAMPLE");
1973  TableIterator iter(tout, "IFNO");
1974  TableRow row(tout);
1975  while ( !iter.pastEnd() ) {
1976    Table tab = iter.table();
1977    ArrayColumn<Float> specCol(tab, "SPECTRA");
1978    //ArrayColumn<Float> tsysCol(tout, "TSYS");
1979    ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
1980    Vector<Float> spec;
1981    Vector<uChar> flag;
1982    specCol.get(0,spec); // the number of channels should be constant per IF
1983    uInt nChanIn = spec.nelements();
1984    Vector<Float> xIn(nChanIn); indgen(xIn);
1985    Int fac =  Int(nChanIn/width);
1986    Vector<Float> xOut(fac+10); // 10 to be safe - resize later
1987    uInt k = 0;
1988    Float x = 0.0;
1989    while (x < Float(nChanIn) ) {
1990      xOut(k) = x;
1991      k++;
1992      x += width;
1993    }
1994    uInt nChanOut = k;
1995    xOut.resize(nChanOut, True);
1996    // process all rows for this IFNO
1997    Vector<Float> specOut;
1998    Vector<Bool> maskOut;
1999    Vector<uChar> flagOut;
2000    for (uInt i=0; i < tab.nrow(); ++i) {
2001      specCol.get(i, spec);
2002      flagCol.get(i, flag);
2003      Vector<Bool> mask(flag.nelements());
2004      convertArray(mask, flag);
2005
2006      IPosition shapeIn(spec.shape());
2007      //sh.nchan = nChanOut;
2008      InterpolateArray1D<Float,Float>::interpolate(specOut, maskOut, xOut,
2009                                                   xIn, spec, mask,
2010                                                   interpMethod, True, True);
2011      /// @todo do the same for channel based Tsys
2012      flagOut.resize(maskOut.nelements());
2013      convertArray(flagOut, maskOut);
2014      specCol.put(i, specOut);
2015      flagCol.put(i, flagOut);
2016    }
2017    ++iter;
2018  }
2019
2020  return out;
2021}
2022
2023STMath::imethod STMath::stringToIMethod(const std::string& in)
2024{
2025  static STMath::imap lookup;
2026
2027  // initialize the lookup table if necessary
2028  if ( lookup.empty() ) {
2029    lookup["nearest"]   = InterpolateArray1D<Double,Float>::nearestNeighbour;
2030    lookup["linear"] = InterpolateArray1D<Double,Float>::linear;
2031    lookup["cubic"]  = InterpolateArray1D<Double,Float>::cubic;
2032    lookup["spline"]  = InterpolateArray1D<Double,Float>::spline;
2033  }
2034
2035  STMath::imap::const_iterator iter = lookup.find(in);
2036
2037  if ( lookup.end() == iter ) {
2038    std::string message = in;
2039    message += " is not a valid interpolation mode";
2040    throw(AipsError(message));
2041  }
2042  return iter->second;
2043}
2044
2045WeightType STMath::stringToWeight(const std::string& in)
2046{
2047  static std::map<std::string, WeightType> lookup;
2048
2049  // initialize the lookup table if necessary
2050  if ( lookup.empty() ) {
2051    lookup["NONE"]   = asap::W_NONE;
2052    lookup["TINT"] = asap::W_TINT;
2053    lookup["TINTSYS"]  = asap::W_TINTSYS;
2054    lookup["TSYS"]  = asap::W_TSYS;
2055    lookup["VAR"]  = asap::W_VAR;
2056  }
2057
2058  std::map<std::string, WeightType>::const_iterator iter = lookup.find(in);
2059
2060  if ( lookup.end() == iter ) {
2061    std::string message = in;
2062    message += " is not a valid weighting mode";
2063    throw(AipsError(message));
2064  }
2065  return iter->second;
2066}
2067
2068CountedPtr< Scantable > STMath::gainElevation( const CountedPtr< Scantable >& in,
2069                                               const vector< float > & coeff,
2070                                               const std::string & filename,
2071                                               const std::string& method)
2072{
2073  // Get elevation data from Scantable and convert to degrees
2074  CountedPtr< Scantable > out = getScantable(in, false);
2075  Table& tab = out->table();
2076  ROScalarColumn<Float> elev(tab, "ELEVATION");
2077  Vector<Float> x = elev.getColumn();
2078  x *= Float(180 / C::pi);                        // Degrees
2079
2080  Vector<Float> coeffs(coeff);
2081  const uInt nc = coeffs.nelements();
2082  if ( filename.length() > 0 && nc > 0 ) {
2083    throw(AipsError("You must choose either polynomial coefficients or an ascii file, not both"));
2084  }
2085
2086  // Correct
2087  if ( nc > 0 || filename.length() == 0 ) {
2088    // Find instrument
2089    Bool throwit = True;
2090    Instrument inst =
2091      STAttr::convertInstrument(tab.keywordSet().asString("AntennaName"),
2092                                throwit);
2093
2094    // Set polynomial
2095    Polynomial<Float>* ppoly = 0;
2096    Vector<Float> coeff;
2097    String msg;
2098    if ( nc > 0 ) {
2099      ppoly = new Polynomial<Float>(nc-1);
2100      coeff = coeffs;
2101      msg = String("user");
2102    } else {
2103      STAttr sdAttr;
2104      coeff = sdAttr.gainElevationPoly(inst);
2105      ppoly = new Polynomial<Float>(coeff.nelements()-1);
2106      msg = String("built in");
2107    }
2108
2109    if ( coeff.nelements() > 0 ) {
2110      ppoly->setCoefficients(coeff);
2111    } else {
2112      delete ppoly;
2113      throw(AipsError("There is no known gain-elevation polynomial known for this instrument"));
2114    }
2115    ostringstream oss;
2116    oss << "Making polynomial correction with " << msg << " coefficients:" << endl;
2117    oss << "   " <<  coeff;
2118    pushLog(String(oss));
2119    const uInt nrow = tab.nrow();
2120    Vector<Float> factor(nrow);
2121    for ( uInt i=0; i < nrow; ++i ) {
2122      factor[i] = 1.0 / (*ppoly)(x[i]);
2123    }
2124    delete ppoly;
2125    scaleByVector(tab, factor, true);
2126
2127  } else {
2128    // Read and correct
2129    pushLog("Making correction from ascii Table");
2130    scaleFromAsciiTable(tab, filename, method, x, true);
2131  }
2132  return out;
2133}
2134
2135void STMath::scaleFromAsciiTable(Table& in, const std::string& filename,
2136                                 const std::string& method,
2137                                 const Vector<Float>& xout, bool dotsys)
2138{
2139
2140// Read gain-elevation ascii file data into a Table.
2141
2142  String formatString;
2143  Table tbl = readAsciiTable(formatString, Table::Memory, filename, "", "", False);
2144  scaleFromTable(in, tbl, method, xout, dotsys);
2145}
2146
2147void STMath::scaleFromTable(Table& in,
2148                            const Table& table,
2149                            const std::string& method,
2150                            const Vector<Float>& xout, bool dotsys)
2151{
2152
2153  ROScalarColumn<Float> geElCol(table, "ELEVATION");
2154  ROScalarColumn<Float> geFacCol(table, "FACTOR");
2155  Vector<Float> xin = geElCol.getColumn();
2156  Vector<Float> yin = geFacCol.getColumn();
2157  Vector<Bool> maskin(xin.nelements(),True);
2158
2159  // Interpolate (and extrapolate) with desired method
2160
2161  InterpolateArray1D<Double,Float>::InterpolationMethod interp = stringToIMethod(method);
2162
2163   Vector<Float> yout;
2164   Vector<Bool> maskout;
2165   InterpolateArray1D<Float,Float>::interpolate(yout, maskout, xout,
2166                                                xin, yin, maskin, interp,
2167                                                True, True);
2168
2169   scaleByVector(in, Float(1.0)/yout, dotsys);
2170}
2171
2172void STMath::scaleByVector( Table& in,
2173                            const Vector< Float >& factor,
2174                            bool dotsys )
2175{
2176  uInt nrow = in.nrow();
2177  if ( factor.nelements() != nrow ) {
2178    throw(AipsError("factors.nelements() != table.nelements()"));
2179  }
2180  ArrayColumn<Float> specCol(in, "SPECTRA");
2181  ArrayColumn<uChar> flagCol(in, "FLAGTRA");
2182  ArrayColumn<Float> tsysCol(in, "TSYS");
2183  for (uInt i=0; i < nrow; ++i) {
2184    MaskedArray<Float> ma  = maskedArray(specCol(i), flagCol(i));
2185    ma *= factor[i];
2186    specCol.put(i, ma.getArray());
2187    flagCol.put(i, flagsFromMA(ma));
2188    if ( dotsys ) {
2189      Vector<Float> tsys = tsysCol(i);
2190      tsys *= factor[i];
2191      tsysCol.put(i,tsys);
2192    }
2193  }
2194}
2195
2196CountedPtr< Scantable > STMath::convertFlux( const CountedPtr< Scantable >& in,
2197                                             float d, float etaap,
2198                                             float jyperk )
2199{
2200  CountedPtr< Scantable > out = getScantable(in, false);
2201  Table& tab = in->table();
2202  Unit fluxUnit(tab.keywordSet().asString("FluxUnit"));
2203  Unit K(String("K"));
2204  Unit JY(String("Jy"));
2205
2206  bool tokelvin = true;
2207  Double cfac = 1.0;
2208
2209  if ( fluxUnit == JY ) {
2210    pushLog("Converting to K");
2211    Quantum<Double> t(1.0,fluxUnit);
2212    Quantum<Double> t2 = t.get(JY);
2213    cfac = (t2 / t).getValue();               // value to Jy
2214
2215    tokelvin = true;
2216    out->setFluxUnit("K");
2217  } else if ( fluxUnit == K ) {
2218    pushLog("Converting to Jy");
2219    Quantum<Double> t(1.0,fluxUnit);
2220    Quantum<Double> t2 = t.get(K);
2221    cfac = (t2 / t).getValue();              // value to K
2222
2223    tokelvin = false;
2224    out->setFluxUnit("Jy");
2225  } else {
2226    throw(AipsError("Unrecognized brightness units in Table - must be consistent with Jy or K"));
2227  }
2228  // Make sure input values are converted to either Jy or K first...
2229  Float factor = cfac;
2230
2231  // Select method
2232  if (jyperk > 0.0) {
2233    factor *= jyperk;
2234    if ( tokelvin ) factor = 1.0 / jyperk;
2235    ostringstream oss;
2236    oss << "Jy/K = " << jyperk;
2237    pushLog(String(oss));
2238    Vector<Float> factors(tab.nrow(), factor);
2239    scaleByVector(tab,factors, false);
2240  } else if ( etaap > 0.0) {
2241    if (d < 0) {
2242      Instrument inst =
2243        STAttr::convertInstrument(tab.keywordSet().asString("AntennaName"),
2244                                  True);
2245      STAttr sda;
2246      d = sda.diameter(inst);
2247    }
2248    jyperk = STAttr::findJyPerK(etaap, d);
2249    ostringstream oss;
2250    oss << "Jy/K = " << jyperk;
2251    pushLog(String(oss));
2252    factor *= jyperk;
2253    if ( tokelvin ) {
2254      factor = 1.0 / factor;
2255    }
2256    Vector<Float> factors(tab.nrow(), factor);
2257    scaleByVector(tab, factors, False);
2258  } else {
2259
2260    // OK now we must deal with automatic look up of values.
2261    // We must also deal with the fact that the factors need
2262    // to be computed per IF and may be different and may
2263    // change per integration.
2264
2265    pushLog("Looking up conversion factors");
2266    convertBrightnessUnits(out, tokelvin, cfac);
2267  }
2268
2269  return out;
2270}
2271
2272void STMath::convertBrightnessUnits( CountedPtr<Scantable>& in,
2273                                     bool tokelvin, float cfac )
2274{
2275  Table& table = in->table();
2276  Instrument inst =
2277    STAttr::convertInstrument(table.keywordSet().asString("AntennaName"), True);
2278  TableIterator iter(table, "FREQ_ID");
2279  STFrequencies stfreqs = in->frequencies();
2280  STAttr sdAtt;
2281  while (!iter.pastEnd()) {
2282    Table tab = iter.table();
2283    ArrayColumn<Float> specCol(tab, "SPECTRA");
2284    ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2285    ROScalarColumn<uInt> freqidCol(tab, "FREQ_ID");
2286    MEpoch::ROScalarColumn timeCol(tab, "TIME");
2287
2288    uInt freqid; freqidCol.get(0, freqid);
2289    Vector<Float> tmpspec; specCol.get(0, tmpspec);
2290    // STAttr.JyPerK has a Vector interface... change sometime.
2291    Vector<Float> freqs(1,stfreqs.getRefFreq(freqid, tmpspec.nelements()));
2292    for ( uInt i=0; i<tab.nrow(); ++i) {
2293      Float jyperk = (sdAtt.JyPerK(inst, timeCol(i), freqs))[0];
2294      Float factor = cfac * jyperk;
2295      if ( tokelvin ) factor = Float(1.0) / factor;
2296      MaskedArray<Float> ma  = maskedArray(specCol(i), flagCol(i));
2297      ma *= factor;
2298      specCol.put(i, ma.getArray());
2299      flagCol.put(i, flagsFromMA(ma));
2300    }
2301  ++iter;
2302  }
2303}
2304
2305CountedPtr< Scantable > STMath::opacity( const CountedPtr< Scantable > & in,
2306                                         const std::vector<float>& tau )
2307{
2308  CountedPtr< Scantable > out = getScantable(in, false);
2309
2310  Table outtab = out->table();
2311
2312  const Int ntau = uInt(tau.size());
2313  std::vector<float>::const_iterator tauit = tau.begin();
2314  AlwaysAssert((ntau == 1 || ntau == in->nif() || ntau == in->nif() * in->npol()),
2315               AipsError);
2316  TableIterator iiter(outtab, "IFNO");
2317  while ( !iiter.pastEnd() ) {
2318    Table itab = iiter.table();
2319    TableIterator piter(itab, "POLNO");
2320    while ( !piter.pastEnd() ) {
2321      Table tab = piter.table();
2322      ROScalarColumn<Float> elev(tab, "ELEVATION");
2323      ArrayColumn<Float> specCol(tab, "SPECTRA");
2324      ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2325      ArrayColumn<Float> tsysCol(tab, "TSYS");
2326      for ( uInt i=0; i<tab.nrow(); ++i) {
2327        Float zdist = Float(C::pi_2) - elev(i);
2328        Float factor = exp(*tauit/cos(zdist));
2329        MaskedArray<Float> ma = maskedArray(specCol(i), flagCol(i));
2330        ma *= factor;
2331        specCol.put(i, ma.getArray());
2332        flagCol.put(i, flagsFromMA(ma));
2333        Vector<Float> tsys;
2334        tsysCol.get(i, tsys);
2335        tsys *= factor;
2336        tsysCol.put(i, tsys);
2337      }
2338      if (ntau == in->nif()*in->npol() ) {
2339        tauit++;
2340      }
2341      piter++;
2342    }
2343    if (ntau >= in->nif() ) {
2344      tauit++;
2345    }
2346    iiter++;
2347  }
2348  return out;
2349}
2350
2351CountedPtr< Scantable > STMath::smoothOther( const CountedPtr< Scantable >& in,
2352                                             const std::string& kernel,
2353                                             float width, int order)
2354{
2355  CountedPtr< Scantable > out = getScantable(in, false);
2356  Table table = out->table();
2357
2358  TableIterator iter(table, "IFNO");
2359  while (!iter.pastEnd()) {
2360    Table tab = iter.table();
2361    ArrayColumn<Float> specCol(tab, "SPECTRA");
2362    ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2363    Vector<Float> spec;
2364    Vector<uChar> flag;
2365    for (uInt i = 0; i < tab.nrow(); ++i) {
2366      specCol.get(i, spec);
2367      flagCol.get(i, flag);
2368      Vector<Bool> mask(flag.nelements());
2369      convertArray(mask, flag);
2370      Vector<Float> specout;
2371      Vector<Bool> maskout;
2372      if (kernel == "hanning") {
2373        mathutil::hanning(specout, maskout, spec, !mask);
2374        convertArray(flag, !maskout);
2375      } else if (kernel == "rmedian") {
2376        mathutil::runningMedian(specout, maskout, spec , mask, width);
2377        convertArray(flag, maskout);
2378      } else if (kernel == "poly") {
2379        mathutil::polyfit(specout, maskout, spec, !mask, width, order);
2380        convertArray(flag, !maskout);
2381      }
2382
2383      for (uInt j = 0; j < flag.nelements(); ++j) {
2384        uChar userFlag = 1 << 7;
2385        if (maskout[j]==True) userFlag = 0 << 7;
2386        flag(j) = userFlag;
2387      }
2388
2389      flagCol.put(i, flag);
2390      specCol.put(i, specout);
2391    }
2392  ++iter;
2393  }
2394  return out;
2395}
2396
2397CountedPtr< Scantable > STMath::smooth( const CountedPtr< Scantable >& in,
2398                                        const std::string& kernel, float width,
2399                                        int order)
2400{
2401  if (kernel == "rmedian"  || kernel == "hanning" || kernel == "poly") {
2402    return smoothOther(in, kernel, width, order);
2403  }
2404  CountedPtr< Scantable > out = getScantable(in, false);
2405  Table& table = out->table();
2406  VectorKernel::KernelTypes type = VectorKernel::toKernelType(kernel);
2407  // same IFNO should have same no of channels
2408  // this saves overhead
2409  TableIterator iter(table, "IFNO");
2410  while (!iter.pastEnd()) {
2411    Table tab = iter.table();
2412    ArrayColumn<Float> specCol(tab, "SPECTRA");
2413    ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2414    Vector<Float> tmpspec; specCol.get(0, tmpspec);
2415    uInt nchan = tmpspec.nelements();
2416    Vector<Float> kvec = VectorKernel::make(type, width, nchan, True, False);
2417    Convolver<Float> conv(kvec, IPosition(1,nchan));
2418    Vector<Float> spec;
2419    Vector<uChar> flag;
2420    for ( uInt i=0; i<tab.nrow(); ++i) {
2421      specCol.get(i, spec);
2422      flagCol.get(i, flag);
2423      Vector<Bool> mask(flag.nelements());
2424      convertArray(mask, flag);
2425      Vector<Float> specout;
2426      mathutil::replaceMaskByZero(specout, mask);
2427      conv.linearConv(specout, spec);
2428      specCol.put(i, specout);
2429    }
2430    ++iter;
2431  }
2432  return out;
2433}
2434
2435CountedPtr< Scantable >
2436  STMath::merge( const std::vector< CountedPtr < Scantable > >& in )
2437{
2438  if ( in.size() < 2 ) {
2439    throw(AipsError("Need at least two scantables to perform a merge."));
2440  }
2441  std::vector<CountedPtr < Scantable > >::const_iterator it = in.begin();
2442  bool insitu = insitu_;
2443  setInsitu(false);
2444  CountedPtr< Scantable > out = getScantable(*it, false);
2445  setInsitu(insitu);
2446  Table& tout = out->table();
2447  ScalarColumn<uInt> freqidcol(tout,"FREQ_ID"), molidcol(tout, "MOLECULE_ID");
2448  ScalarColumn<uInt> scannocol(tout,"SCANNO"), focusidcol(tout,"FOCUS_ID");
2449  // Renumber SCANNO to be 0-based
2450  Vector<uInt> scannos = scannocol.getColumn();
2451  uInt offset = min(scannos);
2452  scannos -= offset;
2453  scannocol.putColumn(scannos);
2454  uInt newscanno = max(scannos)+1;
2455  ++it;
2456  while ( it != in.end() ){
2457    if ( ! (*it)->conformant(*out) ) {
2458      // non conformant.
2459      //pushLog(String("Warning: Can't merge scantables as header info differs."));
2460      LogIO os( LogOrigin( "STMath", "merge()", WHERE ) ) ;
2461      os << LogIO::SEVERE << "Can't merge scantables as header informations (any one of AntennaName, Equinox, and FluxUnit) differ." << LogIO::EXCEPTION ;
2462    }
2463    out->appendToHistoryTable((*it)->history());
2464    const Table& tab = (*it)->table();
2465
2466    Block<String> cols(3);
2467    cols[0] = String("FREQ_ID");
2468    cols[1] = String("MOLECULE_ID");
2469    cols[2] = String("FOCUS_ID");
2470
2471    TableIterator scanit(tab, "SCANNO");
2472    while (!scanit.pastEnd()) {
2473      ScalarColumn<uInt> thescannocol(scanit.table(),"SCANNO");
2474      Vector<uInt> thescannos(thescannocol.nrow(),newscanno);
2475      thescannocol.putColumn(thescannos);
2476      TableIterator subit(scanit.table(), cols);
2477      while ( !subit.pastEnd() ) {
2478        uInt nrow = tout.nrow();
2479        Table thetab = subit.table();
2480        ROTableRow row(thetab);
2481        Vector<uInt> thecolvals(thetab.nrow());
2482        ScalarColumn<uInt> thefreqidcol(thetab,"FREQ_ID");
2483        ScalarColumn<uInt> themolidcol(thetab, "MOLECULE_ID");
2484        ScalarColumn<uInt> thefocusidcol(thetab,"FOCUS_ID");
2485        // The selected subset of table should have
2486        // the equal FREQ_ID, MOLECULE_ID, and FOCUS_ID values.
2487        const TableRecord& rec = row.get(0);
2488        // Set the proper FREQ_ID
2489        Double rv,rp,inc;
2490        (*it)->frequencies().getEntry(rp, rv, inc, rec.asuInt("FREQ_ID"));
2491        uInt id;
2492        id = out->frequencies().addEntry(rp, rv, inc);
2493        thecolvals = id;
2494        thefreqidcol.putColumn(thecolvals);
2495        // Set the proper MOLECULE_ID
2496        Vector<String> name,fname;Vector<Double> rf;
2497        (*it)->molecules().getEntry(rf, name, fname, rec.asuInt("MOLECULE_ID"));
2498        id = out->molecules().addEntry(rf, name, fname);
2499        thecolvals = id;
2500        themolidcol.putColumn(thecolvals);
2501        // Set the proper FOCUS_ID
2502        Float fpa,frot,fax,ftan,fhand,fmount,fuser, fxy, fxyp;
2503        (*it)->focus().getEntry(fpa, fax, ftan, frot, fhand, fmount,fuser,
2504                                fxy, fxyp, rec.asuInt("FOCUS_ID"));
2505        id = out->focus().addEntry(fpa, fax, ftan, frot, fhand, fmount,fuser,
2506                                   fxy, fxyp);
2507        thecolvals = id;
2508        thefocusidcol.putColumn(thecolvals);
2509
2510        tout.addRow(thetab.nrow());
2511        TableCopy::copyRows(tout, thetab, nrow, 0, thetab.nrow());
2512
2513        ++subit;
2514      }
2515      ++newscanno;
2516      ++scanit;
2517    }
2518    ++it;
2519  }
2520  return out;
2521}
2522
2523CountedPtr< Scantable >
2524  STMath::invertPhase( const CountedPtr < Scantable >& in )
2525{
2526  return applyToPol(in, &STPol::invertPhase, Float(0.0));
2527}
2528
2529CountedPtr< Scantable >
2530  STMath::rotateXYPhase( const CountedPtr < Scantable >& in, float phase )
2531{
2532   return applyToPol(in, &STPol::rotatePhase, Float(phase));
2533}
2534
2535CountedPtr< Scantable >
2536  STMath::rotateLinPolPhase( const CountedPtr < Scantable >& in, float phase )
2537{
2538  return applyToPol(in, &STPol::rotateLinPolPhase, Float(phase));
2539}
2540
2541CountedPtr< Scantable > STMath::applyToPol( const CountedPtr<Scantable>& in,
2542                                             STPol::polOperation fptr,
2543                                             Float phase )
2544{
2545  CountedPtr< Scantable > out = getScantable(in, false);
2546  Table& tout = out->table();
2547  Block<String> cols(4);
2548  cols[0] = String("SCANNO");
2549  cols[1] = String("BEAMNO");
2550  cols[2] = String("IFNO");
2551  cols[3] = String("CYCLENO");
2552  TableIterator iter(tout, cols);
2553  CountedPtr<STPol> stpol = STPol::getPolClass(out->factories_,
2554                                               out->getPolType() );
2555  while (!iter.pastEnd()) {
2556    Table t = iter.table();
2557    ArrayColumn<Float> speccol(t, "SPECTRA");
2558    ScalarColumn<uInt> focidcol(t, "FOCUS_ID");
2559    Matrix<Float> pols(speccol.getColumn());
2560    try {
2561      stpol->setSpectra(pols);
2562      Float fang,fhand;
2563      fang = in->focusTable_.getTotalAngle(focidcol(0));
2564      fhand = in->focusTable_.getFeedHand(focidcol(0));
2565      stpol->setPhaseCorrections(fang, fhand);
2566      // use a member function pointer in STPol.  This only works on
2567      // the STPol pointer itself, not the Counted Pointer so
2568      // derefernce it.
2569      (&(*(stpol))->*fptr)(phase);
2570      speccol.putColumn(stpol->getSpectra());
2571    } catch (AipsError& e) {
2572      //delete stpol;stpol=0;
2573      throw(e);
2574    }
2575    ++iter;
2576  }
2577  //delete stpol;stpol=0;
2578  return out;
2579}
2580
2581CountedPtr< Scantable >
2582  STMath::swapPolarisations( const CountedPtr< Scantable > & in )
2583{
2584  CountedPtr< Scantable > out = getScantable(in, false);
2585  Table& tout = out->table();
2586  Table t0 = tout(tout.col("POLNO") == 0);
2587  Table t1 = tout(tout.col("POLNO") == 1);
2588  if ( t0.nrow() != t1.nrow() )
2589    throw(AipsError("Inconsistent number of polarisations"));
2590  ArrayColumn<Float> speccol0(t0, "SPECTRA");
2591  ArrayColumn<uChar> flagcol0(t0, "FLAGTRA");
2592  ArrayColumn<Float> speccol1(t1, "SPECTRA");
2593  ArrayColumn<uChar> flagcol1(t1, "FLAGTRA");
2594  Matrix<Float> s0 = speccol0.getColumn();
2595  Matrix<uChar> f0 = flagcol0.getColumn();
2596  speccol0.putColumn(speccol1.getColumn());
2597  flagcol0.putColumn(flagcol1.getColumn());
2598  speccol1.putColumn(s0);
2599  flagcol1.putColumn(f0);
2600  return out;
2601}
2602
2603CountedPtr< Scantable >
2604  STMath::averagePolarisations( const CountedPtr< Scantable > & in,
2605                                const std::vector<bool>& mask,
2606                                const std::string& weight )
2607{
2608  if (in->npol() < 2 )
2609    throw(AipsError("averagePolarisations can only be applied to two or more"
2610                    "polarisations"));
2611  bool insitu = insitu_;
2612  setInsitu(false);
2613  CountedPtr< Scantable > pols = getScantable(in, true);
2614  setInsitu(insitu);
2615  Table& tout = pols->table();
2616  std::string taql = "SELECT FROM $1 WHERE POLNO IN [0,1]";
2617  Table tab = tableCommand(taql, in->table());
2618  if (tab.nrow() == 0 )
2619    throw(AipsError("Could not find  any rows with POLNO==0 and POLNO==1"));
2620  TableCopy::copyRows(tout, tab);
2621  TableVector<uInt> vec(tout, "POLNO");
2622  vec = 0;
2623  pols->table_.rwKeywordSet().define("nPol", Int(1));
2624  pols->table_.rwKeywordSet().define("POLTYPE", String("stokes"));
2625  //pols->table_.rwKeywordSet().define("POLTYPE", in->getPolType());
2626  std::vector<CountedPtr<Scantable> > vpols;
2627  vpols.push_back(pols);
2628  CountedPtr< Scantable > out = average(vpols, mask, weight, "SCAN");
2629  return out;
2630}
2631
2632CountedPtr< Scantable >
2633  STMath::averageBeams( const CountedPtr< Scantable > & in,
2634                        const std::vector<bool>& mask,
2635                        const std::string& weight )
2636{
2637  bool insitu = insitu_;
2638  setInsitu(false);
2639  CountedPtr< Scantable > beams = getScantable(in, false);
2640  setInsitu(insitu);
2641  Table& tout = beams->table();
2642  // give all rows the same BEAMNO
2643  TableVector<uInt> vec(tout, "BEAMNO");
2644  vec = 0;
2645  beams->table_.rwKeywordSet().define("nBeam", Int(1));
2646  std::vector<CountedPtr<Scantable> > vbeams;
2647  vbeams.push_back(beams);
2648  CountedPtr< Scantable > out = average(vbeams, mask, weight, "SCAN");
2649  return out;
2650}
2651
2652
2653CountedPtr< Scantable >
2654  asap::STMath::frequencyAlign( const CountedPtr< Scantable > & in,
2655                                const std::string & refTime,
2656                                const std::string & method)
2657{
2658  // clone as this is not working insitu
2659  bool insitu = insitu_;
2660  setInsitu(false);
2661  CountedPtr< Scantable > out = getScantable(in, false);
2662  setInsitu(insitu);
2663  Table& tout = out->table();
2664  // Get reference Epoch to time of first row or given String
2665  Unit DAY(String("d"));
2666  MEpoch::Ref epochRef(in->getTimeReference());
2667  MEpoch refEpoch;
2668  if (refTime.length()>0) {
2669    Quantum<Double> qt;
2670    if (MVTime::read(qt,refTime)) {
2671      MVEpoch mv(qt);
2672      refEpoch = MEpoch(mv, epochRef);
2673   } else {
2674      throw(AipsError("Invalid format for Epoch string"));
2675   }
2676  } else {
2677    refEpoch = in->timeCol_(0);
2678  }
2679  MPosition refPos = in->getAntennaPosition();
2680
2681  InterpolateArray1D<Double,Float>::InterpolationMethod interp = stringToIMethod(method);
2682  /*
2683  // Comment from MV.
2684  // the following code has been commented out because different FREQ_IDs have to be aligned together even
2685  // if the frame doesn't change. So far, lack of this check didn't cause any problems.
2686  // test if user frame is different to base frame
2687  if ( in->frequencies().getFrameString(true)
2688       == in->frequencies().getFrameString(false) ) {
2689    throw(AipsError("Can't convert as no output frame has been set"
2690                    " (use set_freqframe) or it is aligned already."));
2691  }
2692  */
2693  MFrequency::Types system = in->frequencies().getFrame();
2694  MVTime mvt(refEpoch.getValue());
2695  String epochout = mvt.string(MVTime::YMD) + String(" (") + refEpoch.getRefString() + String(")");
2696  ostringstream oss;
2697  oss << "Aligned at reference Epoch " << epochout
2698      << " in frame " << MFrequency::showType(system);
2699  pushLog(String(oss));
2700  // set up the iterator
2701  Block<String> cols(4);
2702  // select by constant direction
2703  cols[0] = String("SRCNAME");
2704  cols[1] = String("BEAMNO");
2705  // select by IF ( no of channels varies over this )
2706  cols[2] = String("IFNO");
2707  // select by restfrequency
2708  cols[3] = String("MOLECULE_ID");
2709  TableIterator iter(tout, cols);
2710  while ( !iter.pastEnd() ) {
2711    Table t = iter.table();
2712    MDirection::ROScalarColumn dirCol(t, "DIRECTION");
2713    TableIterator fiter(t, "FREQ_ID");
2714    // determine nchan from the first row. This should work as
2715    // we are iterating over BEAMNO and IFNO    // we should have constant direction
2716
2717    ROArrayColumn<Float> sCol(t, "SPECTRA");
2718    const MDirection direction = dirCol(0);
2719    const uInt nchan = sCol(0).nelements();
2720
2721    // skip operations if there is nothing to align
2722    if (fiter.pastEnd()) {
2723        continue;
2724    }
2725
2726    Table ftab = fiter.table();
2727    // align all frequency ids with respect to the first encountered id
2728    ScalarColumn<uInt> freqidCol(ftab, "FREQ_ID");
2729    // get the SpectralCoordinate for the freqid, which we are iterating over
2730    SpectralCoordinate sC = in->frequencies().getSpectralCoordinate(freqidCol(0));
2731    FrequencyAligner<Float> fa( sC, nchan, refEpoch,
2732                                direction, refPos, system );
2733    // realign the SpectralCoordinate and put into the output Scantable
2734    Vector<String> units(1);
2735    units = String("Hz");
2736    Bool linear=True;
2737    SpectralCoordinate sc2 = fa.alignedSpectralCoordinate(linear);
2738    sc2.setWorldAxisUnits(units);
2739    const uInt id = out->frequencies().addEntry(sc2.referencePixel()[0],
2740                                                sc2.referenceValue()[0],
2741                                                sc2.increment()[0]);
2742    while ( !fiter.pastEnd() ) {
2743      ftab = fiter.table();
2744      // spectral coordinate for the current FREQ_ID
2745      ScalarColumn<uInt> freqidCol2(ftab, "FREQ_ID");
2746      sC = in->frequencies().getSpectralCoordinate(freqidCol2(0));
2747      // create the "global" abcissa for alignment with same FREQ_ID
2748      Vector<Double> abc(nchan);
2749      for (uInt i=0; i<nchan; i++) {
2750           Double w;
2751           sC.toWorld(w,Double(i));
2752           abc[i] = w;
2753      }
2754      TableVector<uInt> tvec(ftab, "FREQ_ID");
2755      // assign new frequency id to all rows
2756      tvec = id;
2757      // cache abcissa for same time stamps, so iterate over those
2758      TableIterator timeiter(ftab, "TIME");
2759      while ( !timeiter.pastEnd() ) {
2760        Table tab = timeiter.table();
2761        ArrayColumn<Float> specCol(tab, "SPECTRA");
2762        ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2763        MEpoch::ROScalarColumn timeCol(tab, "TIME");
2764        // use align abcissa cache after the first row
2765        // these rows should be just be POLNO
2766        bool first = true;
2767        for (int i=0; i<int(tab.nrow()); ++i) {
2768          // input values
2769          Vector<uChar> flag = flagCol(i);
2770          Vector<Bool> mask(flag.shape());
2771          Vector<Float> specOut, spec;
2772          spec  = specCol(i);
2773          Vector<Bool> maskOut;Vector<uChar> flagOut;
2774          convertArray(mask, flag);
2775          // alignment
2776          Bool ok = fa.align(specOut, maskOut, abc, spec,
2777                             mask, timeCol(i), !first,
2778                             interp, False);
2779          (void) ok; // unused stop compiler nagging
2780          // back into scantable
2781          flagOut.resize(maskOut.nelements());
2782          convertArray(flagOut, maskOut);
2783          flagCol.put(i, flagOut);
2784          specCol.put(i, specOut);
2785          // start abcissa caching
2786          first = false;
2787        }
2788        // next timestamp
2789        ++timeiter;
2790      }
2791      // next FREQ_ID
2792      ++fiter;
2793    }
2794    // next aligner
2795    ++iter;
2796  }
2797  // set this afterwards to ensure we are doing insitu correctly.
2798  out->frequencies().setFrame(system, true);
2799  return out;
2800}
2801
2802CountedPtr<Scantable>
2803  asap::STMath::convertPolarisation( const CountedPtr<Scantable>& in,
2804                                     const std::string & newtype )
2805{
2806  if (in->npol() != 2 && in->npol() != 4)
2807    throw(AipsError("Can only convert two or four polarisations."));
2808  if ( in->getPolType() == newtype )
2809    throw(AipsError("No need to convert."));
2810  if ( ! in->selector_.empty() )
2811    throw(AipsError("Can only convert whole scantable. Unset the selection."));
2812  bool insitu = insitu_;
2813  setInsitu(false);
2814  CountedPtr< Scantable > out = getScantable(in, true);
2815  setInsitu(insitu);
2816  Table& tout = out->table();
2817  tout.rwKeywordSet().define("POLTYPE", String(newtype));
2818
2819  Block<String> cols(4);
2820  cols[0] = "SCANNO";
2821  cols[1] = "CYCLENO";
2822  cols[2] = "BEAMNO";
2823  cols[3] = "IFNO";
2824  TableIterator it(in->originalTable_, cols);
2825  String basetype = in->getPolType();
2826  STPol* stpol = STPol::getPolClass(in->factories_, basetype);
2827  try {
2828    while ( !it.pastEnd() ) {
2829      Table tab = it.table();
2830      uInt row = tab.rowNumbers()[0];
2831      stpol->setSpectra(in->getPolMatrix(row));
2832      Float fang,fhand;
2833      fang = in->focusTable_.getTotalAngle(in->mfocusidCol_(row));
2834      fhand = in->focusTable_.getFeedHand(in->mfocusidCol_(row));
2835      stpol->setPhaseCorrections(fang, fhand);
2836      Int npolout = 0;
2837      for (uInt i=0; i<tab.nrow(); ++i) {
2838        Vector<Float> outvec = stpol->getSpectrum(i, newtype);
2839        if ( outvec.nelements() > 0 ) {
2840          tout.addRow();
2841          TableCopy::copyRows(tout, tab, tout.nrow()-1, 0, 1);
2842          ArrayColumn<Float> sCol(tout,"SPECTRA");
2843          ScalarColumn<uInt> pCol(tout,"POLNO");
2844          sCol.put(tout.nrow()-1 ,outvec);
2845          pCol.put(tout.nrow()-1 ,uInt(npolout));
2846          npolout++;
2847       }
2848      }
2849      tout.rwKeywordSet().define("nPol", npolout);
2850      ++it;
2851    }
2852  } catch (AipsError& e) {
2853    delete stpol;
2854    throw(e);
2855  }
2856  delete stpol;
2857  return out;
2858}
2859
2860CountedPtr< Scantable >
2861  asap::STMath::mxExtract( const CountedPtr< Scantable > & in,
2862                           const std::string & scantype )
2863{
2864  bool insitu = insitu_;
2865  setInsitu(false);
2866  CountedPtr< Scantable > out = getScantable(in, true);
2867  setInsitu(insitu);
2868  Table& tout = out->table();
2869  std::string taql = "SELECT FROM $1 WHERE BEAMNO != REFBEAMNO";
2870  if (scantype == "on") {
2871    taql = "SELECT FROM $1 WHERE BEAMNO == REFBEAMNO";
2872  }
2873  Table tab = tableCommand(taql, in->table());
2874  TableCopy::copyRows(tout, tab);
2875  if (scantype == "on") {
2876    // re-index SCANNO to 0
2877    TableVector<uInt> vec(tout, "SCANNO");
2878    vec = 0;
2879  }
2880  return out;
2881}
2882
2883std::vector<float>
2884  asap::STMath::fft( const casa::CountedPtr< Scantable > & in,
2885                     const std::vector<int>& whichrow,
2886                     bool getRealImag )
2887{
2888  std::vector<float> res;
2889  Table tab = in->table();
2890  std::vector<bool> mask;
2891
2892  if (whichrow.size() < 1) {          // for all rows (by default)
2893    int nrow = int(tab.nrow());
2894    for (int i = 0; i < nrow; ++i) {
2895      res = in->execFFT(i, mask, getRealImag);
2896    }
2897  } else {                           // for specified rows
2898    for (uInt i = 0; i < whichrow.size(); ++i) {
2899      res = in->execFFT(i, mask, getRealImag);
2900    }
2901  }
2902
2903  return res;
2904}
2905
2906
2907CountedPtr<Scantable>
2908  asap::STMath::lagFlag( const CountedPtr<Scantable>& in,
2909                         double start, double end,
2910                         const std::string& mode )
2911{
2912  CountedPtr<Scantable> out = getScantable(in, false);
2913  Table& tout = out->table();
2914  TableIterator iter(tout, "FREQ_ID");
2915  FFTServer<Float,Complex> ffts;
2916
2917  while ( !iter.pastEnd() ) {
2918    Table tab = iter.table();
2919    Double rp,rv,inc;
2920    ROTableRow row(tab);
2921    const TableRecord& rec = row.get(0);
2922    uInt freqid = rec.asuInt("FREQ_ID");
2923    out->frequencies().getEntry(rp, rv, inc, freqid);
2924    ArrayColumn<Float> specCol(tab, "SPECTRA");
2925    ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2926
2927    for (int i=0; i<int(tab.nrow()); ++i) {
2928      Vector<Float> spec = specCol(i);
2929      Vector<uChar> flag = flagCol(i);
2930      std::vector<bool> mask;
2931      for (uInt j = 0; j < flag.nelements(); ++j) {
2932        mask.push_back(!(flag[j]>0));
2933      }
2934      mathutil::doZeroOrderInterpolation(spec, mask);
2935
2936      Vector<Complex> lags;
2937      ffts.fft0(lags, spec);
2938
2939      Int lag0(start+0.5);
2940      Int lag1(end+0.5);
2941      if (mode == "frequency") {
2942        lag0 = Int(spec.nelements()*abs(inc)/(start)+0.5);
2943        lag1 = Int(spec.nelements()*abs(inc)/(end)+0.5);
2944      }
2945      Int lstart =  max(0, lag0);
2946      Int lend   =  min(Int(lags.nelements()-1), lag1);
2947      if (lstart == lend) {
2948        lags[lstart] = Complex(0.0);
2949      } else {
2950        if (lstart > lend) {
2951          Int tmp = lend;
2952          lend = lstart;
2953          lstart = tmp;
2954        }
2955        for (int j=lstart; j <=lend ;++j) {
2956          lags[j] = Complex(0.0);
2957        }
2958      }
2959
2960      ffts.fft0(spec, lags);
2961
2962      specCol.put(i, spec);
2963    }
2964    ++iter;
2965  }
2966  return out;
2967}
2968
2969// Averaging spectra with different channel/resolution
2970CountedPtr<Scantable>
2971STMath::new_average( const std::vector<CountedPtr<Scantable> >& in,
2972                     const bool& compel,
2973                     const std::vector<bool>& mask,
2974                     const std::string& weight,
2975                     const std::string& avmode )
2976  throw ( casa::AipsError )
2977{
2978  LogIO os( LogOrigin( "STMath", "new_average()", WHERE ) ) ;
2979  if ( avmode == "SCAN" && in.size() != 1 )
2980    throw(AipsError("Can't perform 'SCAN' averaging on multiple tables.\n"
2981                    "Use merge first."));
2982 
2983  // 2012/02/17 TN
2984  // Since STGrid is implemented, average doesn't consider direction
2985  // when accumulating
2986  // check if OTF observation
2987//   String obstype = in[0]->getHeader().obstype ;
2988//   Double tol = 0.0 ;
2989//   if ( obstype.find( "OTF" ) != String::npos ) {
2990//     tol = TOL_OTF ;
2991//   }
2992//   else {
2993//     tol = TOL_POINT ;
2994//   }
2995
2996  CountedPtr<Scantable> out ;     // processed result
2997  if ( compel ) {
2998    std::vector< CountedPtr<Scantable> > newin ; // input for average process
2999    uInt insize = in.size() ;    // number of input scantables
3000
3001    // TEST: do normal average in each table before IF grouping
3002    os << "Do preliminary averaging" << LogIO::POST ;
3003    vector< CountedPtr<Scantable> > tmpin( insize ) ;
3004    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3005      vector< CountedPtr<Scantable> > v( 1, in[itable] ) ;
3006      tmpin[itable] = average( v, mask, weight, avmode ) ;
3007    }
3008
3009    // warning
3010    os << "Average spectra with different spectral resolution" << LogIO::POST ;
3011
3012    // temporarily set coordinfo
3013    vector<string> oldinfo( insize ) ;
3014    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3015      vector<string> coordinfo = in[itable]->getCoordInfo() ;
3016      oldinfo[itable] = coordinfo[0] ;
3017      coordinfo[0] = "Hz" ;
3018      tmpin[itable]->setCoordInfo( coordinfo ) ;
3019    }
3020
3021    // columns
3022    ScalarColumn<uInt> freqIDCol ;
3023    ScalarColumn<uInt> ifnoCol ;
3024    ScalarColumn<uInt> scannoCol ;
3025
3026
3027    // check IF frequency coverage
3028    // freqid: list of FREQ_ID, which is used, in each table 
3029    // iffreq: list of minimum and maximum frequency for each FREQ_ID in
3030    //         each table
3031    // freqid[insize][numIF]
3032    // freqid: [[id00, id01, ...],
3033    //          [id10, id11, ...],
3034    //          ...
3035    //          [idn0, idn1, ...]]
3036    // iffreq[insize][numIF*2]
3037    // iffreq: [[min_id00, max_id00, min_id01, max_id01, ...],
3038    //          [min_id10, max_id10, min_id11, max_id11, ...],
3039    //          ...
3040    //          [min_idn0, max_idn0, min_idn1, max_idn1, ...]]
3041    //os << "Check IF settings in each table" << LogIO::POST ;
3042    vector< vector<uInt> > freqid( insize );
3043    vector< vector<double> > iffreq( insize ) ;
3044    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3045      uInt rows = tmpin[itable]->nrow() ;
3046      uInt freqnrows = tmpin[itable]->frequencies().table().nrow() ;
3047      freqIDCol.attach( tmpin[itable]->table(), "FREQ_ID" ) ;
3048      //ifnoCol.attach( tmpin[itable]->table(), "IFNO" ) ;
3049      for ( uInt irow = 0 ; irow < rows ; irow++ ) {
3050        if ( freqid[itable].size() == freqnrows ) {
3051          break ;
3052        }
3053        else {
3054          uInt id = freqIDCol( irow ) ;
3055          if ( freqid[itable].size() == 0 || count( freqid[itable].begin(), freqid[itable].end(), id ) == 0 ) {
3056            //os << "itable = " << itable << ": IF " << id << " is included in the list" << LogIO::POST ;
3057            vector<double> abcissa = tmpin[itable]->getAbcissa( irow ) ;
3058            double lbedge, rbedge;
3059            freqid[itable].push_back( id ) ;
3060            lbedge = abcissa[0] - 0.5 * ( abcissa[1] - abcissa[0] );
3061            rbedge = abcissa[abcissa.size()-1] + 0.5 * ( abcissa[1] - abcissa[0] );
3062            iffreq[itable].push_back( min(lbedge, rbedge) ) ;
3063            iffreq[itable].push_back( max(lbedge, rbedge) ) ;
3064          }
3065        }
3066      }
3067    }
3068
3069    // debug
3070    //os << "IF settings summary:" << endl ;
3071    //for ( uInt i = 0 ; i < freqid.size() ; i++ ) {
3072    //os << "   Table" << i << endl ;
3073    //for ( uInt j = 0 ; j < freqid[i].size() ; j++ ) {
3074    //os << "      id = " << freqid[i][j] << " (min,max) = (" << iffreq[i][2*j] << "," << iffreq[i][2*j+1] << ")" << endl ;
3075    //}
3076    //}
3077    //os << endl ;
3078    //os.post() ;
3079
3080    // IF grouping based on their frequency coverage
3081    // ifgrp: list of table index and FREQ_ID for all members in each IF group
3082    // ifgfreq: list of minimum and maximum frequency in each IF group
3083    // ifgrp[numgrp][nummember*2]
3084    // ifgrp: [[table00, freqrow00, table01, freqrow01, ...],
3085    //         [table10, freqrow10, table11, freqrow11, ...],
3086    //         ...
3087    //         [tablen0, freqrown0, tablen1, freqrown1, ...]]
3088    // ifgfreq[numgrp*2]
3089    // ifgfreq: [min0_grp0, max0_grp0, min1_grp1, max1_grp1, ...]
3090    //os << "IF grouping based on their frequency coverage" << LogIO::POST ;
3091    vector< vector<uInt> > ifgrp ;
3092    vector<double> ifgfreq ;
3093
3094    // parameter for IF grouping
3095    // groupmode = OR    retrieve all region
3096    //             AND   only retrieve overlaped region
3097    //string groupmode = "AND" ;
3098    string groupmode = "OR" ;
3099    uInt sizecr = 0 ;
3100    if ( groupmode == "AND" )
3101      sizecr = 2 ;
3102    else if ( groupmode == "OR" )
3103      sizecr = 0 ;
3104
3105    vector<double> sortedfreq ;
3106    for ( uInt i = 0 ; i < iffreq.size() ; i++ ) {
3107      for ( uInt j = 0 ; j < iffreq[i].size() ; j++ ) {
3108        if ( count( sortedfreq.begin(), sortedfreq.end(), iffreq[i][j] ) == 0 )
3109          sortedfreq.push_back( iffreq[i][j] ) ;
3110      }
3111    }
3112    sort( sortedfreq.begin(), sortedfreq.end() ) ;
3113    for ( vector<double>::iterator i = sortedfreq.begin() ; i != sortedfreq.end()-1 ; i++ ) {
3114      ifgfreq.push_back( *i ) ;
3115      ifgfreq.push_back( *(i+1) ) ;
3116    }
3117    ifgrp.resize( ifgfreq.size()/2 ) ;
3118    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3119      for ( uInt iif = 0 ; iif < freqid[itable].size() ; iif++ ) {
3120        double range0 = iffreq[itable][2*iif] ;
3121        double range1 = iffreq[itable][2*iif+1] ;
3122        for ( uInt j = 0 ; j < ifgrp.size() ; j++ ) {
3123          double fmin = max( range0, ifgfreq[2*j] ) ;
3124          double fmax = min( range1, ifgfreq[2*j+1] ) ;
3125          if ( fmin < fmax ) {
3126            ifgrp[j].push_back( itable ) ;
3127            ifgrp[j].push_back( freqid[itable][iif] ) ;
3128          }
3129        }
3130      }
3131    }
3132    vector< vector<uInt> >::iterator fiter = ifgrp.begin() ;
3133    vector<double>::iterator giter = ifgfreq.begin() ;
3134    while( fiter != ifgrp.end() ) {
3135      if ( fiter->size() <= sizecr ) {
3136        fiter = ifgrp.erase( fiter ) ;
3137        giter = ifgfreq.erase( giter ) ;
3138        giter = ifgfreq.erase( giter ) ;
3139      }
3140      else {
3141        fiter++ ;
3142        advance( giter, 2 ) ;
3143      }
3144    }
3145
3146    // Grouping continuous IF groups (without frequency gap)
3147    // freqgrp: list of IF group indexes in each frequency group
3148    // freqgrp[numgrp][nummember]
3149    // freqgrp: [[ifgrp00, ifgrp01, ifgrp02, ...],
3150    //           [ifgrp10, ifgrp11, ifgrp12, ...],
3151    //           ...
3152    //           [ifgrpn0, ifgrpn1, ifgrpn2, ...]]
3153    vector< vector<uInt> > freqgrp ;
3154    double freqrange = 0.0 ;
3155    uInt grpnum = 0 ;
3156    for ( uInt i = 0 ; i < ifgrp.size() ; i++ ) {
3157      // Assumed that ifgfreq was sorted
3158      if ( grpnum != 0 && freqrange == ifgfreq[2*i] ) {
3159        freqgrp[grpnum-1].push_back( i ) ;
3160      }
3161      else {
3162        vector<uInt> grp0( 1, i ) ;
3163        freqgrp.push_back( grp0 ) ;
3164        grpnum++ ;
3165      }
3166      freqrange = ifgfreq[2*i+1] ;
3167    }
3168       
3169
3170    // print IF groups
3171    ostringstream oss ;
3172    oss << "IF Group summary: " << endl ;
3173    oss << "   GROUP_ID [FREQ_MIN, FREQ_MAX]: (TABLE_ID, FREQ_ID)" << endl ;
3174    for ( uInt i = 0 ; i < ifgrp.size() ; i++ ) {
3175      oss << "   GROUP " << setw( 2 ) << i << " [" << ifgfreq[2*i] << "," << ifgfreq[2*i+1] << "]: " ;
3176      for ( uInt j = 0 ; j < ifgrp[i].size()/2 ; j++ ) {
3177        oss << "(" << ifgrp[i][2*j] << "," << ifgrp[i][2*j+1] << ") " ;
3178      }
3179      oss << endl ;
3180    }
3181    oss << endl ;
3182    os << oss.str() << LogIO::POST ;
3183   
3184    // print frequency group
3185    oss.str("") ;
3186    oss << "Frequency Group summary: " << endl ;
3187    oss << "   GROUP_ID [FREQ_MIN, FREQ_MAX]: IF_GROUP_ID" << endl ;
3188    for ( uInt i = 0 ; i < freqgrp.size() ; i++ ) {
3189      oss << "   GROUP " << setw( 2 ) << i << " [" << ifgfreq[2*freqgrp[i][0]] << "," << ifgfreq[2*freqgrp[i][freqgrp[i].size()-1]+1] << "]: " ;
3190      for ( uInt j = 0 ; j < freqgrp[i].size() ; j++ ) {
3191        oss << freqgrp[i][j] << " " ;
3192      }
3193      oss << endl ;
3194    }
3195    oss << endl ;
3196    os << oss.str() << LogIO::POST ;
3197
3198    // membership check
3199    // groups: list of IF group indexes whose frequency range overlaps with
3200    //         that of each table and IF
3201    // groups[numtable][numIF][nummembership]
3202    // groups: [[[grp, grp,...], [grp, grp,...],...],
3203    //          [[grp, grp,...], [grp, grp,...],...],
3204    //          ...
3205    //          [[grp, grp,...], [grp, grp,...],...]]
3206    vector< vector< vector<uInt> > > groups( insize ) ;
3207    for ( uInt i = 0 ; i < insize ; i++ ) {
3208      groups[i].resize( freqid[i].size() ) ;
3209    }
3210    for ( uInt igrp = 0 ; igrp < ifgrp.size() ; igrp++ ) {
3211      for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) {
3212        uInt tableid = ifgrp[igrp][2*imem] ;
3213        vector<uInt>::iterator iter = find( freqid[tableid].begin(), freqid[tableid].end(), ifgrp[igrp][2*imem+1] ) ;
3214        if ( iter != freqid[tableid].end() ) {
3215          uInt rowid = distance( freqid[tableid].begin(), iter ) ;
3216          groups[tableid][rowid].push_back( igrp ) ;
3217        }
3218      }
3219    }
3220
3221    // print membership
3222    //oss.str("") ;
3223    //for ( uInt i = 0 ; i < insize ; i++ ) {
3224    //oss << "Table " << i << endl ;
3225    //for ( uInt j = 0 ; j < groups[i].size() ; j++ ) {
3226    //oss << "   FREQ_ID " <<  setw( 2 ) << freqid[i][j] << ": " ;
3227    //for ( uInt k = 0 ; k < groups[i][j].size() ; k++ ) {
3228    //oss << setw( 2 ) << groups[i][j][k] << " " ;
3229    //}
3230    //oss << endl ;
3231    //}
3232    //}
3233    //os << oss.str() << LogIO::POST ;
3234
3235    // set back coordinfo
3236    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3237      vector<string> coordinfo = tmpin[itable]->getCoordInfo() ;
3238      coordinfo[0] = oldinfo[itable] ;
3239      tmpin[itable]->setCoordInfo( coordinfo ) ;
3240    }
3241
3242    // Create additional table if needed
3243    bool oldInsitu = insitu_ ;
3244    setInsitu( false ) ;
3245    vector< vector<uInt> > addrow( insize ) ;
3246    vector<uInt> addtable( insize, 0 ) ;
3247    vector<uInt> newtableids( insize ) ;
3248    vector<uInt> newifids( insize, 0 ) ;
3249    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3250      //os << "Table " << itable << ": " ;
3251      for ( uInt ifrow = 0 ; ifrow < groups[itable].size() ; ifrow++ ) {
3252        addrow[itable].push_back( groups[itable][ifrow].size()-1 ) ;
3253        //os << addrow[itable][ifrow] << " " ;
3254      }
3255      addtable[itable] = *max_element( addrow[itable].begin(), addrow[itable].end() ) ;
3256      //os << "(" << addtable[itable] << ")" << LogIO::POST ;
3257    }
3258    newin.resize( insize ) ;
3259    copy( tmpin.begin(), tmpin.end(), newin.begin() ) ;
3260    for ( uInt i = 0 ; i < insize ; i++ ) {
3261      newtableids[i] = i ;
3262    }
3263    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3264      for ( uInt iadd = 0 ; iadd < addtable[itable] ; iadd++ ) {
3265        CountedPtr<Scantable> add = getScantable( newin[itable], false ) ;
3266        vector<int> freqidlist ;
3267        for ( uInt i = 0 ; i < groups[itable].size() ; i++ ) {
3268          if ( groups[itable][i].size() > iadd + 1 ) {
3269            freqidlist.push_back( freqid[itable][i] ) ;
3270          }
3271        }
3272        stringstream taqlstream ;
3273        taqlstream << "SELECT FROM $1 WHERE FREQ_ID IN [" ;
3274        for ( uInt i = 0 ; i < freqidlist.size() ; i++ ) {
3275          taqlstream << freqidlist[i] ;
3276          if ( i < freqidlist.size() - 1 )
3277            taqlstream << "," ;
3278          else
3279            taqlstream << "]" ;
3280        }
3281        string taql = taqlstream.str() ;
3282        //os << "taql = " << taql << LogIO::POST ;
3283        STSelector selector = STSelector() ;
3284        selector.setTaQL( taql ) ;
3285        add->setSelection( selector ) ;
3286        newin.push_back( add ) ;
3287        newtableids.push_back( itable ) ;
3288        newifids.push_back( iadd + 1 ) ;
3289      }
3290    }
3291
3292    // udpate ifgrp
3293    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3294      for ( uInt iadd = 0 ; iadd < addtable[itable] ; iadd++ ) {
3295        for ( uInt ifrow = 0 ; ifrow < groups[itable].size() ; ifrow++ ) {
3296          if ( groups[itable][ifrow].size() > iadd + 1 ) {
3297            uInt igrp = groups[itable][ifrow][iadd+1] ;
3298            for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) {
3299              if ( ifgrp[igrp][2*imem] == newtableids[iadd+insize] && ifgrp[igrp][2*imem+1] == freqid[newtableids[iadd+insize]][ifrow] ) {
3300                ifgrp[igrp][2*imem] = insize + iadd ;
3301              }
3302            }
3303          }
3304        }
3305      }
3306    }
3307
3308    // print IF groups again for debug
3309    //oss.str( "" ) ;
3310    //oss << "IF Group summary: " << endl ;
3311    //oss << "   GROUP_ID [FREQ_MIN, FREQ_MAX]: (TABLE_ID, FREQ_ID)" << endl ;
3312    //for ( uInt i = 0 ; i < ifgrp.size() ; i++ ) {
3313    //oss << "   GROUP " << setw( 2 ) << i << " [" << ifgfreq[2*i] << "," << ifgfreq[2*i+1] << "]: " ;
3314    //for ( uInt j = 0 ; j < ifgrp[i].size()/2 ; j++ ) {
3315    //oss << "(" << ifgrp[i][2*j] << "," << ifgrp[i][2*j+1] << ") " ;
3316    //}
3317    //oss << endl ;
3318    //}
3319    //oss << endl ;
3320    //os << oss.str() << LogIO::POST ;
3321
3322    // reset SCANNO and IFNO/FREQ_ID: IF is reset by the result of sortation
3323    os << "All scan number is set to 0" << LogIO::POST ;
3324    //os << "All IF number is set to IF group index" << LogIO::POST ;
3325    insize = newin.size() ;
3326    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3327      uInt rows = newin[itable]->nrow() ;
3328      Table &tmpt = newin[itable]->table() ;
3329      freqIDCol.attach( tmpt, "FREQ_ID" ) ;
3330      scannoCol.attach( tmpt, "SCANNO" ) ;
3331      ifnoCol.attach( tmpt, "IFNO" ) ;
3332      for ( uInt irow=0 ; irow < rows ; irow++ ) {
3333        scannoCol.put( irow, 0 ) ;
3334        uInt freqID = freqIDCol( irow ) ;
3335        vector<uInt>::iterator iter = find( freqid[newtableids[itable]].begin(), freqid[newtableids[itable]].end(), freqID ) ;
3336        if ( iter != freqid[newtableids[itable]].end() ) {
3337          uInt index = distance( freqid[newtableids[itable]].begin(), iter ) ;
3338          ifnoCol.put( irow, groups[newtableids[itable]][index][newifids[itable]] ) ;
3339        }
3340        else {
3341          throw(AipsError("IF grouping was wrong in additional tables.")) ;
3342        }
3343      }
3344    }
3345    oldinfo.resize( insize ) ;
3346    setInsitu( oldInsitu ) ;
3347
3348    // temporarily set coordinfo
3349    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3350      vector<string> coordinfo = newin[itable]->getCoordInfo() ;
3351      oldinfo[itable] = coordinfo[0] ;
3352      coordinfo[0] = "Hz" ;
3353      newin[itable]->setCoordInfo( coordinfo ) ;
3354    }
3355
3356    // save column values in the vector
3357    vector< vector<uInt> > freqTableIdVec( insize ) ;
3358    vector< vector<uInt> > freqIdVec( insize ) ;
3359    vector< vector<uInt> > ifNoVec( insize ) ;
3360    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3361      ScalarColumn<uInt> freqIDs ;
3362      freqIDs.attach( newin[itable]->frequencies().table(), "ID" ) ;
3363      ifnoCol.attach( newin[itable]->table(), "IFNO" ) ;
3364      freqIDCol.attach( newin[itable]->table(), "FREQ_ID" ) ;
3365      for ( uInt irow = 0 ; irow < newin[itable]->frequencies().table().nrow() ; irow++ ) {
3366        freqTableIdVec[itable].push_back( freqIDs( irow ) ) ;
3367      }
3368      for ( uInt irow = 0 ; irow < newin[itable]->table().nrow() ; irow++ ) {
3369        freqIdVec[itable].push_back( freqIDCol( irow ) ) ;
3370        ifNoVec[itable].push_back( ifnoCol( irow ) ) ;
3371      }
3372    }
3373
3374    // reset spectra and flagtra: pick up common part of frequency coverage
3375    //os << "Pick common frequency range and align resolution" << LogIO::POST ;
3376    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3377      uInt rows = newin[itable]->nrow() ;
3378      int nminchan = -1 ;
3379      int nmaxchan = -1 ;
3380      vector<uInt> freqIdUpdate ;
3381      for ( uInt irow = 0 ; irow < rows ; irow++ ) {
3382        uInt ifno = ifNoVec[itable][irow] ;  // IFNO is reset by group index
3383        double minfreq = ifgfreq[2*ifno] ;
3384        double maxfreq = ifgfreq[2*ifno+1] ;
3385        //os << "frequency range: [" << minfreq << "," << maxfreq << "]" << LogIO::POST ;
3386        vector<double> abcissa = newin[itable]->getAbcissa( irow ) ;
3387        int nchan = abcissa.size() ;
3388        double resol = abcissa[1] - abcissa[0] ;
3389        //os << "abcissa range  : [" << abcissa[0] << "," << abcissa[nchan-1] << "]" << LogIO::POST ;
3390        uInt imin, imax;
3391        int sigres;
3392        if ( resol >= 0. ) {
3393          imin = 0;
3394          imax = nchan - 1 ;
3395          sigres = 1 ;
3396        } else {
3397          imin = nchan - 1 ;
3398          imax = 0 ;
3399          sigres = -1 ;
3400          resol = abs(resol) ;
3401        }
3402        if ( minfreq <= abcissa[imin] )
3403          nminchan = imin ;
3404        else {
3405          //double cfreq = ( minfreq - abcissa[0] ) / resol ;
3406          double cfreq = ( minfreq - abcissa[imin] + 0.5 * resol ) / resol ;
3407          nminchan = imin + sigres * (int(cfreq) + ( ( cfreq - int(cfreq) <= 0.5 ) ? 0 : 1 )) ;
3408        }
3409        if ( maxfreq >= abcissa[imax] )
3410          nmaxchan = imax;
3411        else {
3412          //double cfreq = ( abcissa[abcissa.size()-1] - maxfreq ) / resol ;
3413          double cfreq = ( abcissa[imax] - maxfreq + 0.5 * resol ) / resol ;
3414          nmaxchan = imax - sigres * (int(cfreq) +( ( cfreq - int(cfreq) >= 0.5 ) ? 1 : 0 )) ;
3415        }
3416        //os << "freqrange = [" << abcissa[nminchan] << ", " << abcissa[nmaxchan] << "]"<< LogIO::POST;
3417        if ( nmaxchan < nminchan ) {
3418          int tmp = nmaxchan ;
3419          nmaxchan = nminchan ;
3420          nminchan = tmp ;
3421        }
3422        if ( nmaxchan > nminchan ) {
3423          newin[itable]->reshapeSpectrum( nminchan, nmaxchan, irow ) ;
3424          int newchan = nmaxchan - nminchan + 1 ;
3425          if ( count( freqIdUpdate.begin(), freqIdUpdate.end(), freqIdVec[itable][irow] ) == 0 && newchan < nchan ) {
3426            freqIdUpdate.push_back( freqIdVec[itable][irow] ) ;
3427
3428            // Update before nminchan is lost
3429            uInt freqId = freqIdVec[itable][irow] ;
3430            Double refpix ;
3431            Double refval ;
3432            Double increment ;
3433            newin[itable]->frequencies().getEntry( refpix, refval, increment, freqId ) ;
3434            //refval = refval - ( refpix - nminchan ) * increment ;
3435            refval = abcissa[nminchan] ;
3436            refpix = 0 ;
3437            newin[itable]->frequencies().setEntry( refpix, refval, increment, freqId ) ;
3438          }
3439        }
3440        else {
3441          throw(AipsError("Failed to pick up common part of frequency range.")) ;
3442        }
3443      }
3444//       for ( uInt i = 0 ; i < freqIdUpdate.size() ; i++ ) {
3445//      uInt freqId = freqIdUpdate[i] ;
3446//      Double refpix ;
3447//      Double refval ;
3448//      Double increment ;
3449       
3450//      // update row
3451//      newin[itable]->frequencies().getEntry( refpix, refval, increment, freqId ) ;
3452//      refval = refval - ( refpix - nminchan ) * increment ;
3453//      refpix = 0 ;
3454//      newin[itable]->frequencies().setEntry( refpix, refval, increment, freqId ) ;
3455//       }   
3456    }
3457
3458   
3459    // reset spectra and flagtra: align spectral resolution
3460    //os << "Align spectral resolution" << LogIO::POST ;
3461    // gmaxdnu: the coarsest frequency resolution in the frequency group
3462    // gmemid: member index that have a resolution equal to gmaxdnu
3463    // gmaxdnu[numfreqgrp]
3464    // gmaxdnu: [dnu0, dnu1, ...]
3465    // gmemid[numfreqgrp]
3466    // gmemid: [id0, id1, ...]
3467    vector<double> gmaxdnu( freqgrp.size(), 0.0 ) ;
3468    vector<uInt> gmemid( freqgrp.size(), 0 ) ;
3469    for ( uInt igrp = 0 ; igrp < ifgrp.size() ; igrp++ ) {
3470      double maxdnu = 0.0 ;       // maximum (coarsest) frequency resolution
3471      int minchan = INT_MAX ;     // minimum channel number
3472      Double refpixref = -1 ;     // reference of 'reference pixel'
3473      Double refvalref = -1 ;     // reference of 'reference frequency'
3474      Double refinc = -1 ;        // reference frequency resolution
3475      uInt refreqid ;
3476      uInt reftable = INT_MAX;
3477      // process only if group member > 1
3478      if ( ifgrp[igrp].size() > 2 ) {
3479        // find minchan and maxdnu in each group
3480        for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) {
3481          uInt tableid = ifgrp[igrp][2*imem] ;
3482          uInt rowid = ifgrp[igrp][2*imem+1] ;
3483          vector<uInt>::iterator iter = find( freqIdVec[tableid].begin(), freqIdVec[tableid].end(), rowid ) ;
3484          if ( iter != freqIdVec[tableid].end() ) {
3485            uInt index = distance( freqIdVec[tableid].begin(), iter ) ;
3486            vector<double> abcissa = newin[tableid]->getAbcissa( index ) ;
3487            int nchan = abcissa.size() ;
3488            double dnu = abcissa[1] - abcissa[0] ;
3489            //os << "GROUP " << igrp << " (" << tableid << "," << rowid << "): nchan = " << nchan << " (minchan = " << minchan << ")" << LogIO::POST ;
3490            if ( nchan < minchan ) {
3491              minchan = nchan ;
3492              maxdnu = abs(dnu) ;
3493              newin[tableid]->frequencies().getEntry( refpixref, refvalref, refinc, rowid ) ;
3494              refreqid = rowid ;
3495              reftable = tableid ;
3496              // Spectra are reversed when dnu < 0
3497              if (dnu < 0)
3498                refpixref = minchan - 1 -refpixref ;
3499            }
3500          }
3501        }
3502        // regrid spectra in each group
3503        os << "GROUP " << igrp << endl ;
3504        os << "   Channel number is adjusted to " << minchan << endl ;
3505        os << "   Corresponding frequency resolution is " << maxdnu << "Hz" << LogIO::POST ;
3506        for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) {
3507          uInt tableid = ifgrp[igrp][2*imem] ;
3508          uInt rowid = ifgrp[igrp][2*imem+1] ;
3509          freqIDCol.attach( newin[tableid]->table(), "FREQ_ID" ) ;
3510          //os << "tableid = " << tableid << " rowid = " << rowid << ": " << LogIO::POST ;
3511          //os << "   regridChannel applied to " ;
3512          //if ( tableid != reftable )
3513          refreqid = newin[tableid]->frequencies().addEntry( refpixref, refvalref, maxdnu ) ;
3514          for ( uInt irow = 0 ; irow < newin[tableid]->table().nrow() ; irow++ ) {
3515            uInt tfreqid = freqIdVec[tableid][irow] ;
3516            if ( tfreqid == rowid ) {     
3517              //os << irow << " " ;
3518              newin[tableid]->regridChannel( minchan, maxdnu, irow ) ;
3519              freqIDCol.put( irow, refreqid ) ;
3520              freqIdVec[tableid][irow] = refreqid ;
3521            }
3522          }
3523          //os << LogIO::POST ;
3524        }
3525      }
3526      else {
3527        uInt tableid = ifgrp[igrp][0] ;
3528        uInt rowid = ifgrp[igrp][1] ;
3529        vector<uInt>::iterator iter = find( freqIdVec[tableid].begin(), freqIdVec[tableid].end(), rowid ) ;
3530        if ( iter != freqIdVec[tableid].end() ) {
3531          uInt index = distance( freqIdVec[tableid].begin(), iter ) ;
3532          vector<double> abcissa = newin[tableid]->getAbcissa( index ) ;
3533          minchan = abcissa.size() ;
3534          maxdnu = abs( abcissa[1] - abcissa[0]) ;
3535        }
3536      }
3537      for ( uInt i = 0 ; i < freqgrp.size() ; i++ ) {
3538        if ( count( freqgrp[i].begin(), freqgrp[i].end(), igrp ) > 0 ) {
3539          if ( maxdnu > gmaxdnu[i] ) {
3540            gmaxdnu[i] = maxdnu ;
3541            gmemid[i] = igrp ;
3542          }
3543          break ;
3544        }
3545      }
3546    }
3547
3548    // set back coordinfo
3549    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3550      vector<string> coordinfo = newin[itable]->getCoordInfo() ;
3551      coordinfo[0] = oldinfo[itable] ;
3552      newin[itable]->setCoordInfo( coordinfo ) ;
3553    }     
3554
3555    // accumulate all rows into the first table
3556    // NOTE: assumed in.size() = 1
3557    vector< CountedPtr<Scantable> > tmp( 1 ) ;
3558    if ( newin.size() == 1 )
3559      tmp[0] = newin[0] ;
3560    else
3561      tmp[0] = merge( newin ) ;
3562
3563    //return tmp[0] ;
3564
3565    // average
3566    CountedPtr<Scantable> tmpout = average( tmp, mask, weight, avmode ) ;
3567
3568    //return tmpout ;
3569
3570    // combine frequency group
3571    os << "Combine spectra based on frequency grouping" << LogIO::POST ;
3572    //os << "IFNO is renumbered as frequency group ID (see above)" << LogIO::POST ;
3573    os << "IFNO is renumbered as IF group ID (see above)" << LogIO::POST ;
3574    vector<string> coordinfo = tmpout->getCoordInfo() ;
3575    oldinfo[0] = coordinfo[0] ;
3576    coordinfo[0] = "Hz" ;
3577    tmpout->setCoordInfo( coordinfo ) ;
3578    // create proformas of output table
3579    stringstream taqlstream ;
3580    taqlstream << "SELECT FROM $1 WHERE IFNO IN [" ;
3581    for ( uInt i = 0 ; i < gmemid.size() ; i++ ) {
3582      taqlstream << gmemid[i] ;
3583      if ( i < gmemid.size() - 1 )
3584        taqlstream << "," ;
3585      else
3586        taqlstream << "]" ;
3587    }
3588    string taql = taqlstream.str() ;
3589    //os << "taql = " << taql << LogIO::POST ;
3590    STSelector selector = STSelector() ;
3591    selector.setTaQL( taql ) ;
3592    oldInsitu = insitu_ ;
3593    setInsitu( false ) ;
3594    out = getScantable( tmpout, false ) ;
3595    setInsitu( oldInsitu ) ;
3596    out->setSelection( selector ) ;
3597    // regrid rows
3598    ifnoCol.attach( tmpout->table(), "IFNO" ) ;
3599    for ( uInt irow = 0 ; irow < tmpout->table().nrow() ; irow++ ) {
3600      uInt ifno = ifnoCol( irow ) ;
3601      for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) {
3602        if ( count( freqgrp[igrp].begin(), freqgrp[igrp].end(), ifno ) > 0 ) {
3603          vector<double> abcissa = tmpout->getAbcissa( irow ) ;
3604          double bw = ( abcissa[1] - abcissa[0] ) * abcissa.size() ;
3605          int nchan = (int) abs( bw / gmaxdnu[igrp] ) ;
3606          // All spectra will have positive frequency increments
3607          tmpout->regridChannel( nchan, gmaxdnu[igrp], irow ) ;
3608          break ;
3609        }
3610      }
3611    }
3612    // combine spectra
3613    ArrayColumn<Float> specColOut ;
3614    specColOut.attach( out->table(), "SPECTRA" ) ;
3615    ArrayColumn<uChar> flagColOut ;
3616    flagColOut.attach( out->table(), "FLAGTRA" ) ;
3617    ScalarColumn<uInt> ifnoColOut ;
3618    ifnoColOut.attach( out->table(), "IFNO" ) ;
3619    ScalarColumn<uInt> polnoColOut ;
3620    polnoColOut.attach( out->table(), "POLNO" ) ;
3621    ScalarColumn<uInt> freqidColOut ;
3622    freqidColOut.attach( out->table(), "FREQ_ID" ) ;
3623//     MDirection::ScalarColumn dirColOut ;
3624//     dirColOut.attach( out->table(), "DIRECTION" ) ;
3625    Table &tab = tmpout->table() ;
3626    Block<String> cols(1);
3627    cols[0] = String("POLNO") ;
3628    TableIterator iter( tab, cols ) ;
3629    vector< vector<uInt> > sizes( freqgrp.size() ) ;
3630    while( !iter.pastEnd() ) {
3631      vector< vector<Float> > specout( freqgrp.size() ) ;
3632      vector< vector<uChar> > flagout( freqgrp.size() ) ;
3633      ArrayColumn<Float> specCols ;
3634      specCols.attach( iter.table(), "SPECTRA" ) ;
3635      ArrayColumn<uChar> flagCols ;
3636      flagCols.attach( iter.table(), "FLAGTRA" ) ;
3637      ifnoCol.attach( iter.table(), "IFNO" ) ;
3638      ScalarColumn<uInt> polnos ;
3639      polnos.attach( iter.table(), "POLNO" ) ;
3640//       MDirection::ScalarColumn dircol ;
3641//       dircol.attach( iter.table(), "DIRECTION" ) ;
3642      uInt polno = polnos( 0 ) ;
3643      //os << "POLNO iteration: " << polno << LogIO::POST ;
3644//       for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) {
3645//      sizes[igrp].resize( freqgrp[igrp].size() ) ;
3646//      for ( uInt imem = 0 ; imem < freqgrp[igrp].size() ; imem++ ) {
3647//        for ( uInt irow = 0 ; irow < iter.table().nrow() ; irow++ ) {
3648//          uInt ifno = ifnoCol( irow ) ;
3649//          if ( ifno == freqgrp[igrp][imem] ) {
3650//            Vector<Float> spec = specCols( irow ) ;
3651//            Vector<uChar> flag = flagCols( irow ) ;
3652//            vector<Float> svec ;
3653//            spec.tovector( svec ) ;
3654//            vector<uChar> fvec ;
3655//            flag.tovector( fvec ) ;
3656//            //os << "spec.size() = " << svec.size() << " fvec.size() = " << fvec.size() << LogIO::POST ;
3657//            specout[igrp].insert( specout[igrp].end(), svec.begin(), svec.end() ) ;
3658//            flagout[igrp].insert( flagout[igrp].end(), fvec.begin(), fvec.end() ) ;
3659//            //os << "specout[" << igrp << "].size() = " << specout[igrp].size() << LogIO::POST ;
3660//            sizes[igrp][imem] = spec.nelements() ;
3661//          }
3662//        }
3663//      }
3664//      for ( uInt irow = 0 ; irow < out->table().nrow() ; irow++ ) {
3665//        uInt ifout = ifnoColOut( irow ) ;
3666//        uInt polout = polnoColOut( irow ) ;
3667//        if ( ifout == gmemid[igrp] && polout == polno ) {
3668//          // set SPECTRA and FRAGTRA
3669//          Vector<Float> newspec( specout[igrp] ) ;
3670//          Vector<uChar> newflag( flagout[igrp] ) ;
3671//          specColOut.put( irow, newspec ) ;
3672//          flagColOut.put( irow, newflag ) ;
3673//          // IFNO renumbering
3674//          ifnoColOut.put( irow, igrp ) ;
3675//        }
3676//      }
3677//       }
3678      // get a list of number of channels for each frequency group member
3679      for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) {
3680        sizes[igrp].resize( freqgrp[igrp].size() ) ;
3681        for ( uInt imem = 0 ; imem < freqgrp[igrp].size() ; imem++ ) {
3682          for ( uInt irow = 0 ; irow < iter.table().nrow() ; irow++ ) {
3683            uInt ifno = ifnoCol( irow ) ;
3684            if ( ifno == freqgrp[igrp][imem] ) {
3685              Vector<Float> spec = specCols( irow ) ;
3686              sizes[igrp][imem] = spec.nelements() ;
3687              break ;
3688            }
3689          }
3690        }
3691      }
3692      // combine spectra
3693      for ( uInt irow = 0 ; irow < out->table().nrow() ; irow++ ) {
3694        uInt polout = polnoColOut( irow ) ;
3695        if ( polout == polno ) {
3696          uInt ifout = ifnoColOut( irow ) ;
3697//           Vector<Double> direction = dirColOut(irow).getAngle(Unit(String("rad"))).getValue() ;
3698          uInt igrp ;
3699          for ( uInt jgrp = 0 ; jgrp < freqgrp.size() ; jgrp++ ) {
3700            if ( ifout == gmemid[jgrp] ) {
3701              igrp = jgrp ;
3702              break ;
3703            }
3704          }
3705          for ( uInt imem = 0 ; imem < freqgrp[igrp].size() ; imem++ ) {
3706            for ( uInt jrow = 0 ; jrow < iter.table().nrow() ; jrow++ ) {
3707              uInt ifno = ifnoCol( jrow ) ;
3708              // 2012/02/17 TN
3709              // Since STGrid is implemented, average doesn't consider direction
3710              // when accumulating
3711//               Vector<Double> tdir = dircol(jrow).getAngle(Unit(String("rad"))).getValue() ;
3712//               //if ( ifno == freqgrp[igrp][imem] && allTrue( tdir == direction  ) ) {
3713//               Double dx = tdir[0] - direction[0] ;
3714//               Double dy = tdir[1] - direction[1] ;
3715//               Double dd = sqrt( dx * dx + dy * dy ) ;
3716              //if ( ifno == freqgrp[igrp][imem] && allNearAbs( tdir, direction, tol ) ) {
3717//               if ( ifno == freqgrp[igrp][imem] && dd <= tol ) {
3718              if ( ifno == freqgrp[igrp][imem] ) {
3719                Vector<Float> spec = specCols( jrow ) ;
3720                Vector<uChar> flag = flagCols( jrow ) ;
3721                vector<Float> svec ;
3722                spec.tovector( svec ) ;
3723                vector<uChar> fvec ;
3724                flag.tovector( fvec ) ;
3725                //os << "spec.size() = " << svec.size() << " fvec.size() = " << fvec.size() << LogIO::POST ;
3726                specout[igrp].insert( specout[igrp].end(), svec.begin(), svec.end() ) ;
3727                flagout[igrp].insert( flagout[igrp].end(), fvec.begin(), fvec.end() ) ;
3728                //os << "specout[" << igrp << "].size() = " << specout[igrp].size() << LogIO::POST ;
3729              }
3730            }
3731          }
3732          // set SPECTRA and FRAGTRA
3733          Vector<Float> newspec( specout[igrp] ) ;
3734          Vector<uChar> newflag( flagout[igrp] ) ;
3735          specColOut.put( irow, newspec ) ;
3736          flagColOut.put( irow, newflag ) ;
3737          // IFNO renumbering (renumbered as frequency group ID)
3738          ifnoColOut.put( irow, igrp ) ;
3739        }
3740      }
3741      iter++ ;
3742    }
3743    // update FREQUENCIES subtable
3744    vector<bool> updated( freqgrp.size(), false ) ;
3745    for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) {
3746      uInt index = 0 ;
3747      uInt pixShift = 0 ;
3748
3749      while ( freqgrp[igrp][index] != gmemid[igrp] ) {
3750        pixShift += sizes[igrp][index++] ;
3751      }
3752      for ( uInt irow = 0 ; irow < out->table().nrow() ; irow++ ) {
3753        //if ( ifnoColOut( irow ) == gmemid[igrp] && !updated[igrp] ) {
3754        if ( ifnoColOut( irow ) == igrp && !updated[igrp] ) {
3755          uInt freqidOut = freqidColOut( irow ) ;
3756          //os << "freqgrp " << igrp << " freqidOut = " << freqidOut << LogIO::POST ;
3757          double refpix ;
3758          double refval ;
3759          double increm ;
3760          out->frequencies().getEntry( refpix, refval, increm, freqidOut ) ;
3761          if (increm < 0)
3762            refpix = sizes[igrp][index] - 1 - refpix ; // reversed
3763          refpix += pixShift ;
3764          out->frequencies().setEntry( refpix, refval, gmaxdnu[igrp], freqidOut ) ;
3765          updated[igrp] = true ;
3766        }
3767      }
3768    }
3769
3770    //out = tmpout ;
3771
3772    coordinfo = tmpout->getCoordInfo() ;
3773    coordinfo[0] = oldinfo[0] ;
3774    tmpout->setCoordInfo( coordinfo ) ;
3775  }
3776  else {
3777    // simple average
3778    out =  average( in, mask, weight, avmode ) ;
3779  }
3780 
3781  return out;
3782}
3783
3784CountedPtr<Scantable> STMath::cwcal( const CountedPtr<Scantable>& s,
3785                                     const String calmode,
3786                                     const String antname )
3787{
3788  // frequency switch
3789  if ( calmode == "fs" ) {
3790    return cwcalfs( s, antname ) ;
3791  }
3792  else {
3793    vector<bool> masks = s->getMask( 0 ) ;
3794    vector<int> types ;
3795
3796    // sky scan
3797    STSelector sel = STSelector() ;
3798    types.push_back( SrcType::SKY ) ;
3799    sel.setTypes( types ) ;
3800    s->setSelection( sel ) ;
3801    vector< CountedPtr<Scantable> > tmp( 1, getScantable( s, false ) ) ;
3802    CountedPtr<Scantable> asky = average( tmp, masks, "TINT", "SCAN" ) ;
3803    s->unsetSelection() ;
3804    sel.reset() ;
3805    types.clear() ;
3806
3807    // hot scan
3808    types.push_back( SrcType::HOT ) ;
3809    sel.setTypes( types ) ;
3810    s->setSelection( sel ) ;
3811    tmp.clear() ;
3812    tmp.push_back( getScantable( s, false ) ) ;
3813    CountedPtr<Scantable> ahot = average( tmp, masks, "TINT", "SCAN" ) ;
3814    s->unsetSelection() ;
3815    sel.reset() ;
3816    types.clear() ;
3817   
3818    // cold scan
3819    CountedPtr<Scantable> acold ;
3820//     types.push_back( SrcType::COLD ) ;
3821//     sel.setTypes( types ) ;
3822//     s->setSelection( sel ) ;
3823//     tmp.clear() ;
3824//     tmp.push_back( getScantable( s, false ) ) ;
3825//     CountedPtr<Scantable> acold = average( tmp, masks, "TINT", "SCNAN" ) ;
3826//     s->unsetSelection() ;
3827//     sel.reset() ;
3828//     types.clear() ;
3829
3830    // off scan
3831    types.push_back( SrcType::PSOFF ) ;
3832    sel.setTypes( types ) ;
3833    s->setSelection( sel ) ;
3834    tmp.clear() ;
3835    tmp.push_back( getScantable( s, false ) ) ;
3836    CountedPtr<Scantable> aoff = average( tmp, masks, "TINT", "SCAN" ) ;
3837    s->unsetSelection() ;
3838    sel.reset() ;
3839    types.clear() ;
3840   
3841    // on scan
3842    bool insitu = insitu_ ;
3843    insitu_ = false ;
3844    CountedPtr<Scantable> out = getScantable( s, true ) ;
3845    insitu_ = insitu ;
3846    types.push_back( SrcType::PSON ) ;
3847    sel.setTypes( types ) ;
3848    s->setSelection( sel ) ;
3849    TableCopy::copyRows( out->table(), s->table() ) ;
3850    s->unsetSelection() ;
3851    sel.reset() ;
3852    types.clear() ;
3853   
3854    // process each on scan
3855    ArrayColumn<Float> tsysCol ;
3856    tsysCol.attach( out->table(), "TSYS" ) ;
3857    for ( int i = 0 ; i < out->nrow() ; i++ ) {
3858      vector<float> sp = getCalibratedSpectra( out, aoff, asky, ahot, acold, i, antname ) ;
3859      out->setSpectrum( sp, i ) ;
3860      string reftime = out->getTime( i ) ;
3861      vector<int> ii( 1, out->getIF( i ) ) ;
3862      vector<int> ib( 1, out->getBeam( i ) ) ;
3863      vector<int> ip( 1, out->getPol( i ) ) ;
3864      sel.setIFs( ii ) ;
3865      sel.setBeams( ib ) ;
3866      sel.setPolarizations( ip ) ;
3867      asky->setSelection( sel ) ;   
3868      vector<float> sptsys = getTsysFromTime( reftime, asky, "linear" ) ;
3869      const Vector<Float> Vtsys( sptsys ) ;
3870      tsysCol.put( i, Vtsys ) ;
3871      asky->unsetSelection() ;
3872      sel.reset() ;
3873    }
3874
3875    // flux unit
3876    out->setFluxUnit( "K" ) ;
3877
3878    return out ;
3879  }
3880}
3881 
3882CountedPtr<Scantable> STMath::almacal( const CountedPtr<Scantable>& s,
3883                                       const String calmode )
3884{
3885  // frequency switch
3886  if ( calmode == "fs" ) {
3887    return almacalfs( s ) ;
3888  }
3889  else {
3890    vector<bool> masks = s->getMask( 0 ) ;
3891   
3892    // off scan
3893    STSelector sel = STSelector() ;
3894    vector<int> types ;
3895    types.push_back( SrcType::PSOFF ) ;
3896    sel.setTypes( types ) ;
3897    s->setSelection( sel ) ;
3898    // TODO 2010/01/08 TN
3899    // Grouping by time should be needed before averaging.
3900    // Each group must have own unique SCANNO (should be renumbered).
3901    // See PIPELINE/SDCalibration.py
3902    CountedPtr<Scantable> soff = getScantable( s, false ) ;
3903    Table ttab = soff->table() ;
3904    ROScalarColumn<Double> timeCol( ttab, "TIME" ) ;
3905    uInt nrow = timeCol.nrow() ;
3906    Vector<Double> timeSep( nrow - 1 ) ;
3907    for ( uInt i = 0 ; i < nrow - 1 ; i++ ) {
3908      timeSep[i] = timeCol(i+1) - timeCol(i) ;
3909    }
3910    ScalarColumn<Double> intervalCol( ttab, "INTERVAL" ) ;
3911    Vector<Double> interval = intervalCol.getColumn() ;
3912    interval /= 86400.0 ;
3913    ScalarColumn<uInt> scanCol( ttab, "SCANNO" ) ;
3914    vector<uInt> glist ;
3915    for ( uInt i = 0 ; i < nrow - 1 ; i++ ) {
3916      double gap = 2.0 * timeSep[i] / ( interval[i] + interval[i+1] ) ;
3917      //cout << "gap[" << i << "]=" << setw(5) << gap << endl ;
3918      if ( gap > 1.1 ) {
3919        glist.push_back( i ) ;
3920      }
3921    }
3922    Vector<uInt> gaplist( glist ) ;
3923    //cout << "gaplist = " << gaplist << endl ;
3924    uInt newid = 0 ;
3925    for ( uInt i = 0 ; i < nrow ; i++ ) {
3926      scanCol.put( i, newid ) ;
3927      if ( i == gaplist[newid] ) {
3928        newid++ ;
3929      }
3930    }
3931    //cout << "new scancol = " << scanCol.getColumn() << endl ;
3932    vector< CountedPtr<Scantable> > tmp( 1, soff ) ;
3933    CountedPtr<Scantable> aoff = average( tmp, masks, "TINT", "SCAN" ) ;
3934    //cout << "aoff.nrow = " << aoff->nrow() << endl ;
3935    s->unsetSelection() ;
3936    sel.reset() ;
3937    types.clear() ;
3938   
3939    // on scan
3940    bool insitu = insitu_ ;
3941    insitu_ = false ;
3942    CountedPtr<Scantable> out = getScantable( s, true ) ;
3943    insitu_ = insitu ;
3944    types.push_back( SrcType::PSON ) ;
3945    sel.setTypes( types ) ;
3946    s->setSelection( sel ) ;
3947    TableCopy::copyRows( out->table(), s->table() ) ;
3948    s->unsetSelection() ;
3949    sel.reset() ;
3950    types.clear() ;
3951   
3952    // process each on scan
3953    ArrayColumn<Float> tsysCol ;
3954    tsysCol.attach( out->table(), "TSYS" ) ;
3955    for ( int i = 0 ; i < out->nrow() ; i++ ) {
3956      vector<float> sp = getCalibratedSpectra( out, aoff, i ) ;
3957      out->setSpectrum( sp, i ) ;
3958    }
3959
3960    // flux unit
3961    out->setFluxUnit( "K" ) ;
3962
3963    return out ;
3964  }
3965}
3966
3967CountedPtr<Scantable> STMath::cwcalfs( const CountedPtr<Scantable>& s,
3968                                       const String antname )
3969{
3970  vector<int> types ;
3971
3972  // APEX calibration mode
3973  int apexcalmode = 1 ;
3974 
3975  if ( antname.find( "APEX" ) != string::npos ) {
3976    // check if off scan exists or not
3977    STSelector sel = STSelector() ;
3978    //sel.setName( offstr1 ) ;
3979    types.push_back( SrcType::FLOOFF ) ;
3980    sel.setTypes( types ) ;
3981    try {
3982      s->setSelection( sel ) ;
3983    }
3984    catch ( AipsError &e ) {
3985      apexcalmode = 0 ;
3986    }
3987    sel.reset() ;
3988  }
3989  s->unsetSelection() ;
3990  types.clear() ;
3991
3992  vector<bool> masks = s->getMask( 0 ) ;
3993  CountedPtr<Scantable> ssig, sref ;
3994  CountedPtr<Scantable> out ;
3995
3996  if ( antname.find( "APEX" ) != string::npos ) {
3997    // APEX calibration
3998    // sky scan
3999    STSelector sel = STSelector() ;
4000    types.push_back( SrcType::FLOSKY ) ;
4001    sel.setTypes( types ) ;
4002    s->setSelection( sel ) ;
4003    vector< CountedPtr<Scantable> > tmp( 1, getScantable( s, false ) ) ;
4004    CountedPtr<Scantable> askylo = average( tmp, masks, "TINT", "SCAN" ) ;
4005    s->unsetSelection() ;
4006    sel.reset() ;
4007    types.clear() ;
4008    types.push_back( SrcType::FHISKY ) ;
4009    sel.setTypes( types ) ;
4010    s->setSelection( sel ) ;
4011    tmp.clear() ;
4012    tmp.push_back( getScantable( s, false ) ) ;
4013    CountedPtr<Scantable> askyhi = average( tmp, masks, "TINT", "SCAN" ) ;
4014    s->unsetSelection() ;
4015    sel.reset() ;
4016    types.clear() ;
4017   
4018    // hot scan
4019    types.push_back( SrcType::FLOHOT ) ;
4020    sel.setTypes( types ) ;
4021    s->setSelection( sel ) ;
4022    tmp.clear() ;
4023    tmp.push_back( getScantable( s, false ) ) ;
4024    CountedPtr<Scantable> ahotlo = average( tmp, masks, "TINT", "SCAN" ) ;
4025    s->unsetSelection() ;
4026    sel.reset() ;
4027    types.clear() ;
4028    types.push_back( SrcType::FHIHOT ) ;
4029    sel.setTypes( types ) ;
4030    s->setSelection( sel ) ;
4031    tmp.clear() ;
4032    tmp.push_back( getScantable( s, false ) ) ;
4033    CountedPtr<Scantable> ahothi = average( tmp, masks, "TINT", "SCAN" ) ;
4034    s->unsetSelection() ;
4035    sel.reset() ;
4036    types.clear() ;
4037   
4038    // cold scan
4039    CountedPtr<Scantable> acoldlo, acoldhi ;
4040//     types.push_back( SrcType::FLOCOLD ) ;
4041//     sel.setTypes( types ) ;
4042//     s->setSelection( sel ) ;
4043//     tmp.clear() ;
4044//     tmp.push_back( getScantable( s, false ) ) ;
4045//     CountedPtr<Scantable> acoldlo = average( tmp, masks, "TINT", "SCAN" ) ;
4046//     s->unsetSelection() ;
4047//     sel.reset() ;
4048//     types.clear() ;
4049//     types.push_back( SrcType::FHICOLD ) ;
4050//     sel.setTypes( types ) ;
4051//     s->setSelection( sel ) ;
4052//     tmp.clear() ;
4053//     tmp.push_back( getScantable( s, false ) ) ;
4054//     CountedPtr<Scantable> acoldhi = average( tmp, masks, "TINT", "SCAN" ) ;
4055//     s->unsetSelection() ;
4056//     sel.reset() ;
4057//     types.clear() ;
4058
4059    // ref scan
4060    bool insitu = insitu_ ;
4061    insitu_ = false ;
4062    sref = getScantable( s, true ) ;
4063    insitu_ = insitu ;
4064    types.push_back( SrcType::FSLO ) ;
4065    sel.setTypes( types ) ;
4066    s->setSelection( sel ) ;
4067    TableCopy::copyRows( sref->table(), s->table() ) ;
4068    s->unsetSelection() ;
4069    sel.reset() ;
4070    types.clear() ;
4071   
4072    // sig scan
4073    insitu_ = false ;
4074    ssig = getScantable( s, true ) ;
4075    insitu_ = insitu ;
4076    types.push_back( SrcType::FSHI ) ;
4077    sel.setTypes( types ) ;
4078    s->setSelection( sel ) ;
4079    TableCopy::copyRows( ssig->table(), s->table() ) ;
4080    s->unsetSelection() ;
4081    sel.reset() ; 
4082    types.clear() ;
4083         
4084    if ( apexcalmode == 0 ) {
4085      // APEX fs data without off scan
4086      // process each sig and ref scan
4087      ArrayColumn<Float> tsysCollo ;
4088      tsysCollo.attach( ssig->table(), "TSYS" ) ;
4089      ArrayColumn<Float> tsysColhi ;
4090      tsysColhi.attach( sref->table(), "TSYS" ) ;
4091      for ( int i = 0 ; i < ssig->nrow() ; i++ ) {
4092        vector< CountedPtr<Scantable> > sky( 2 ) ;
4093        sky[0] = askylo ;
4094        sky[1] = askyhi ;
4095        vector< CountedPtr<Scantable> > hot( 2 ) ;
4096        hot[0] = ahotlo ;
4097        hot[1] = ahothi ;
4098        vector< CountedPtr<Scantable> > cold( 2 ) ;
4099        //cold[0] = acoldlo ;
4100        //cold[1] = acoldhi ;
4101        vector<float> sp = getFSCalibratedSpectra( ssig, sref, sky, hot, cold, i ) ;
4102        ssig->setSpectrum( sp, i ) ;
4103        string reftime = ssig->getTime( i ) ;
4104        vector<int> ii( 1, ssig->getIF( i ) ) ;
4105        vector<int> ib( 1, ssig->getBeam( i ) ) ;
4106        vector<int> ip( 1, ssig->getPol( i ) ) ;
4107        sel.setIFs( ii ) ;
4108        sel.setBeams( ib ) ;
4109        sel.setPolarizations( ip ) ;
4110        askylo->setSelection( sel ) ;
4111        vector<float> sptsys = getTsysFromTime( reftime, askylo, "linear" ) ;
4112        const Vector<Float> Vtsyslo( sptsys ) ;
4113        tsysCollo.put( i, Vtsyslo ) ;
4114        askylo->unsetSelection() ;
4115        sel.reset() ;
4116        sky[0] = askyhi ;
4117        sky[1] = askylo ;
4118        hot[0] = ahothi ;
4119        hot[1] = ahotlo ;
4120        cold[0] = acoldhi ;
4121        cold[1] = acoldlo ;
4122        sp = getFSCalibratedSpectra( sref, ssig, sky, hot, cold, i ) ;
4123        sref->setSpectrum( sp, i ) ;
4124        reftime = sref->getTime( i ) ;
4125        ii[0] = sref->getIF( i )  ;
4126        ib[0] = sref->getBeam( i ) ;
4127        ip[0] = sref->getPol( i ) ;
4128        sel.setIFs( ii ) ;
4129        sel.setBeams( ib ) ;
4130        sel.setPolarizations( ip ) ;
4131        askyhi->setSelection( sel ) ;   
4132        sptsys = getTsysFromTime( reftime, askyhi, "linear" ) ;
4133        const Vector<Float> Vtsyshi( sptsys ) ;
4134        tsysColhi.put( i, Vtsyshi ) ;
4135        askyhi->unsetSelection() ;
4136        sel.reset() ;
4137      }
4138    }
4139    else if ( apexcalmode == 1 ) {
4140      // APEX fs data with off scan
4141      // off scan
4142      types.push_back( SrcType::FLOOFF ) ;
4143      sel.setTypes( types ) ;
4144      s->setSelection( sel ) ;
4145      tmp.clear() ;
4146      tmp.push_back( getScantable( s, false ) ) ;
4147      CountedPtr<Scantable> aofflo = average( tmp, masks, "TINT", "SCAN" ) ;
4148      s->unsetSelection() ;
4149      sel.reset() ;
4150      types.clear() ;
4151      types.push_back( SrcType::FHIOFF ) ;
4152      sel.setTypes( types ) ;
4153      s->setSelection( sel ) ;
4154      tmp.clear() ;
4155      tmp.push_back( getScantable( s, false ) ) ;
4156      CountedPtr<Scantable> aoffhi = average( tmp, masks, "TINT", "SCAN" ) ;
4157      s->unsetSelection() ;
4158      sel.reset() ;
4159      types.clear() ;
4160     
4161      // process each sig and ref scan
4162      ArrayColumn<Float> tsysCollo ;
4163      tsysCollo.attach( ssig->table(), "TSYS" ) ;
4164      ArrayColumn<Float> tsysColhi ;
4165      tsysColhi.attach( sref->table(), "TSYS" ) ;
4166      for ( int i = 0 ; i < ssig->nrow() ; i++ ) {
4167        vector<float> sp = getCalibratedSpectra( ssig, aofflo, askylo, ahotlo, acoldlo, i, antname ) ;
4168        ssig->setSpectrum( sp, i ) ;
4169        sp = getCalibratedSpectra( sref, aoffhi, askyhi, ahothi, acoldhi, i, antname ) ;
4170        string reftime = ssig->getTime( i ) ;
4171        vector<int> ii( 1, ssig->getIF( i ) ) ;
4172        vector<int> ib( 1, ssig->getBeam( i ) ) ;
4173        vector<int> ip( 1, ssig->getPol( i ) ) ;
4174        sel.setIFs( ii ) ;
4175        sel.setBeams( ib ) ;
4176        sel.setPolarizations( ip ) ;
4177        askylo->setSelection( sel ) ;
4178        vector<float> sptsys = getTsysFromTime( reftime, askylo, "linear" ) ;
4179        const Vector<Float> Vtsyslo( sptsys ) ;
4180        tsysCollo.put( i, Vtsyslo ) ;
4181        askylo->unsetSelection() ;
4182        sel.reset() ;
4183        sref->setSpectrum( sp, i ) ;
4184        reftime = sref->getTime( i ) ;
4185        ii[0] = sref->getIF( i )  ;
4186        ib[0] = sref->getBeam( i ) ;
4187        ip[0] = sref->getPol( i ) ;
4188        sel.setIFs( ii ) ;
4189        sel.setBeams( ib ) ;
4190        sel.setPolarizations( ip ) ;
4191        askyhi->setSelection( sel ) ;   
4192        sptsys = getTsysFromTime( reftime, askyhi, "linear" ) ;
4193        const Vector<Float> Vtsyshi( sptsys ) ;
4194        tsysColhi.put( i, Vtsyshi ) ;
4195        askyhi->unsetSelection() ;
4196        sel.reset() ;
4197      }
4198    }
4199  }
4200  else {
4201    // non-APEX fs data
4202    // sky scan
4203    STSelector sel = STSelector() ;
4204    types.push_back( SrcType::SKY ) ;
4205    sel.setTypes( types ) ;
4206    s->setSelection( sel ) ;
4207    vector< CountedPtr<Scantable> > tmp( 1, getScantable( s, false ) ) ;
4208    CountedPtr<Scantable> asky = average( tmp, masks, "TINT", "SCAN" ) ;
4209    s->unsetSelection() ;
4210    sel.reset() ;
4211    types.clear() ;
4212   
4213    // hot scan
4214    types.push_back( SrcType::HOT ) ;
4215    sel.setTypes( types ) ;
4216    s->setSelection( sel ) ;
4217    tmp.clear() ;
4218    tmp.push_back( getScantable( s, false ) ) ;
4219    CountedPtr<Scantable> ahot = average( tmp, masks, "TINT", "SCAN" ) ;
4220    s->unsetSelection() ;
4221    sel.reset() ;
4222    types.clear() ;
4223
4224    // cold scan
4225    CountedPtr<Scantable> acold ;
4226//     types.push_back( SrcType::COLD ) ;
4227//     sel.setTypes( types ) ;
4228//     s->setSelection( sel ) ;
4229//     tmp.clear() ;
4230//     tmp.push_back( getScantable( s, false ) ) ;
4231//     CountedPtr<Scantable> acold = average( tmp, masks, "TINT", "SCAN" ) ;
4232//     s->unsetSelection() ;
4233//     sel.reset() ;
4234//     types.clear() ;
4235   
4236    // ref scan
4237    bool insitu = insitu_ ;
4238    insitu_ = false ;
4239    sref = getScantable( s, true ) ;
4240    insitu_ = insitu ;
4241    types.push_back( SrcType::FSOFF ) ;
4242    sel.setTypes( types ) ;
4243    s->setSelection( sel ) ;
4244    TableCopy::copyRows( sref->table(), s->table() ) ;
4245    s->unsetSelection() ;
4246    sel.reset() ;
4247    types.clear() ;
4248   
4249    // sig scan
4250    insitu_ = false ;
4251    ssig = getScantable( s, true ) ;
4252    insitu_ = insitu ;
4253    types.push_back( SrcType::FSON ) ;
4254    sel.setTypes( types ) ;
4255    s->setSelection( sel ) ;
4256    TableCopy::copyRows( ssig->table(), s->table() ) ;
4257    s->unsetSelection() ;
4258    sel.reset() ;
4259    types.clear() ;
4260
4261    // process each sig and ref scan
4262    ArrayColumn<Float> tsysColsig ;
4263    tsysColsig.attach( ssig->table(), "TSYS" ) ;
4264    ArrayColumn<Float> tsysColref ;
4265    tsysColref.attach( ssig->table(), "TSYS" ) ;
4266    for ( int i = 0 ; i < ssig->nrow() ; i++ ) {
4267      vector<float> sp = getFSCalibratedSpectra( ssig, sref, asky, ahot, acold, i ) ;
4268      ssig->setSpectrum( sp, i ) ;
4269      string reftime = ssig->getTime( i ) ;
4270      vector<int> ii( 1, ssig->getIF( i ) ) ;
4271      vector<int> ib( 1, ssig->getBeam( i ) ) ;
4272      vector<int> ip( 1, ssig->getPol( i ) ) ;
4273      sel.setIFs( ii ) ;
4274      sel.setBeams( ib ) ;
4275      sel.setPolarizations( ip ) ;
4276      asky->setSelection( sel ) ;
4277      vector<float> sptsys = getTsysFromTime( reftime, asky, "linear" ) ;
4278      const Vector<Float> Vtsys( sptsys ) ;
4279      tsysColsig.put( i, Vtsys ) ;
4280      asky->unsetSelection() ;
4281      sel.reset() ;
4282      sp = getFSCalibratedSpectra( sref, ssig, asky, ahot, acold, i ) ;
4283      sref->setSpectrum( sp, i ) ;
4284      tsysColref.put( i, Vtsys ) ;
4285    }
4286  }
4287
4288  // do folding if necessary
4289  Table sigtab = ssig->table() ;
4290  Table reftab = sref->table() ;
4291  ScalarColumn<uInt> sigifnoCol ;
4292  ScalarColumn<uInt> refifnoCol ;
4293  ScalarColumn<uInt> sigfidCol ;
4294  ScalarColumn<uInt> reffidCol ;
4295  Int nchan = (Int)ssig->nchan() ;
4296  sigifnoCol.attach( sigtab, "IFNO" ) ;
4297  refifnoCol.attach( reftab, "IFNO" ) ;
4298  sigfidCol.attach( sigtab, "FREQ_ID" ) ;
4299  reffidCol.attach( reftab, "FREQ_ID" ) ;
4300  Vector<uInt> sfids( sigfidCol.getColumn() ) ;
4301  Vector<uInt> rfids( reffidCol.getColumn() ) ;
4302  vector<uInt> sfids_unique ;
4303  vector<uInt> rfids_unique ;
4304  vector<uInt> sifno_unique ;
4305  vector<uInt> rifno_unique ;
4306  for ( uInt i = 0 ; i < sfids.nelements() ; i++ ) {
4307    if ( count( sfids_unique.begin(), sfids_unique.end(), sfids[i] ) == 0 ) {
4308      sfids_unique.push_back( sfids[i] ) ;
4309      sifno_unique.push_back( ssig->getIF( i ) ) ;
4310    }
4311    if ( count( rfids_unique.begin(), rfids_unique.end(),  rfids[i] ) == 0 ) {
4312      rfids_unique.push_back( rfids[i] ) ;
4313      rifno_unique.push_back( sref->getIF( i ) ) ;
4314    }
4315  }
4316  double refpix_sig, refval_sig, increment_sig ;
4317  double refpix_ref, refval_ref, increment_ref ;
4318  vector< CountedPtr<Scantable> > tmp( sfids_unique.size() ) ;
4319  for ( uInt i = 0 ; i < sfids_unique.size() ; i++ ) {
4320    ssig->frequencies().getEntry( refpix_sig, refval_sig, increment_sig, sfids_unique[i] ) ;
4321    sref->frequencies().getEntry( refpix_ref, refval_ref, increment_ref, rfids_unique[i] ) ;
4322    if ( refpix_sig == refpix_ref ) {
4323      double foffset = refval_ref - refval_sig ;
4324      int choffset = static_cast<int>(foffset/increment_sig) ;
4325      double doffset = foffset / increment_sig ;
4326      if ( abs(choffset) >= nchan ) {
4327        LogIO os( LogOrigin( "STMath", "cwcalfs", WHERE ) ) ;
4328        os << "FREQ_ID=[" << sfids_unique[i] << "," << rfids_unique[i] << "]: out-band frequency switching, no folding" << LogIO::POST ;
4329        os << "Just return signal data" << LogIO::POST ;
4330        //std::vector< CountedPtr<Scantable> > tabs ;
4331        //tabs.push_back( ssig ) ;
4332        //tabs.push_back( sref ) ;
4333        //out = merge( tabs ) ;
4334        tmp[i] = ssig ;
4335      }
4336      else {
4337        STSelector sel = STSelector() ;
4338        vector<int> v( 1, sifno_unique[i] ) ;
4339        sel.setIFs( v ) ;
4340        ssig->setSelection( sel ) ;
4341        sel.reset() ;
4342        v[0] = rifno_unique[i] ;
4343        sel.setIFs( v ) ;
4344        sref->setSelection( sel ) ;
4345        sel.reset() ;
4346        if ( antname.find( "APEX" ) != string::npos ) {
4347          tmp[i] = dofold( ssig, sref, 0.5*doffset, -0.5*doffset ) ;
4348          //tmp[i] = dofold( ssig, sref, doffset ) ;
4349        }
4350        else {
4351          tmp[i] = dofold( ssig, sref, doffset ) ;
4352        }
4353        ssig->unsetSelection() ;
4354        sref->unsetSelection() ;
4355      }
4356    }
4357  }
4358
4359  if ( tmp.size() > 1 ) {
4360    out = merge( tmp ) ;
4361  }
4362  else {
4363    out = tmp[0] ;
4364  }
4365
4366  // flux unit
4367  out->setFluxUnit( "K" ) ;
4368
4369  return out ;
4370}
4371
4372CountedPtr<Scantable> STMath::almacalfs( const CountedPtr<Scantable>& s )
4373{
4374  (void) s; //currently unused
4375  CountedPtr<Scantable> out ;
4376
4377  return out ;
4378}
4379
4380vector<float> STMath::getSpectrumFromTime( string reftime,
4381                                           CountedPtr<Scantable>& s,
4382                                           string mode )
4383{
4384  LogIO os( LogOrigin( "STMath", "getSpectrumFromTime", WHERE ) ) ;
4385  vector<float> sp ;
4386
4387  if ( s->nrow() == 0 ) {
4388    os << LogIO::SEVERE << "No spectra in the input scantable. Return empty spectrum." << LogIO::POST ;
4389    return sp ;
4390  }
4391  else if ( s->nrow() == 1 ) {
4392    //os << "use row " << 0 << " (scanno = " << s->getScan( 0 ) << ")" << LogIO::POST ;
4393    return s->getSpectrum( 0 ) ;
4394  }
4395  else {
4396    vector<int> idx = getRowIdFromTime( reftime, s ) ;
4397    if ( mode == "before" ) {
4398      int id = -1 ;
4399      if ( idx[0] != -1 ) {
4400        id = idx[0] ;
4401      }
4402      else if ( idx[1] != -1 ) {
4403        os << LogIO::WARN << "Failed to find a scan before reftime. return a spectrum just after the reftime." << LogIO::POST ;
4404        id = idx[1] ;
4405      }
4406      //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
4407      sp = s->getSpectrum( id ) ;
4408    }
4409    else if ( mode == "after" ) {
4410      int id = -1 ;
4411      if ( idx[1] != -1 ) {
4412        id = idx[1] ;
4413      }
4414      else if ( idx[0] != -1 ) {
4415        os << LogIO::WARN << "Failed to find a scan after reftime. return a spectrum just before the reftime." << LogIO::POST ;
4416        id = idx[1] ;
4417      }
4418      //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
4419      sp = s->getSpectrum( id ) ;
4420    }
4421    else if ( mode == "nearest" ) {
4422      int id = -1 ;
4423      if ( idx[0] == -1 ) {
4424        id = idx[1] ;
4425      }
4426      else if ( idx[1] == -1 ) {
4427        id = idx[0] ;
4428      }
4429      else if ( idx[0] == idx[1] ) {
4430        id = idx[0] ;
4431      }
4432      else {
4433        //double t0 = getMJD( s->getTime( idx[0] ) ) ;
4434        //double t1 = getMJD( s->getTime( idx[1] ) ) ;
4435        double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
4436        double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
4437        double tref = getMJD( reftime ) ;
4438        if ( abs( t0 - tref ) > abs( t1 - tref ) ) {
4439          id = idx[1] ;
4440        }
4441        else {
4442          id = idx[0] ;
4443        }
4444      }
4445      //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
4446      sp = s->getSpectrum( id ) ;     
4447    }
4448    else if ( mode == "linear" ) {
4449      if ( idx[0] == -1 ) {
4450        // use after
4451        os << LogIO::WARN << "Failed to interpolate. return a spectrum just after the reftime." << LogIO::POST ;
4452        int id = idx[1] ;
4453        //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
4454        sp = s->getSpectrum( id ) ;
4455      }
4456      else if ( idx[1] == -1 ) {
4457        // use before
4458        os << LogIO::WARN << "Failed to interpolate. return a spectrum just before the reftime." << LogIO::POST ;
4459        int id = idx[0] ;
4460        //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
4461        sp = s->getSpectrum( id ) ;
4462      }
4463      else if ( idx[0] == idx[1] ) {
4464        // use before
4465        //os << "No need to interporate." << LogIO::POST ;
4466        int id = idx[0] ;
4467        //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
4468        sp = s->getSpectrum( id ) ;
4469      }
4470      else {
4471        // do interpolation
4472        //os << "interpolate between " << idx[0] << " and " << idx[1] << " (scanno: " << s->getScan( idx[0] ) << ", " << s->getScan( idx[1] ) << ")" << LogIO::POST ;
4473        //double t0 = getMJD( s->getTime( idx[0] ) ) ;
4474        //double t1 = getMJD( s->getTime( idx[1] ) ) ;
4475        double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
4476        double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
4477        double tref = getMJD( reftime ) ;
4478        vector<float> sp0 = s->getSpectrum( idx[0] ) ;
4479        vector<float> sp1 = s->getSpectrum( idx[1] ) ;
4480        for ( unsigned int i = 0 ; i < sp0.size() ; i++ ) {
4481          float v = ( sp1[i] - sp0[i] ) / ( t1 - t0 ) * ( tref - t0 ) + sp0[i] ;
4482          sp.push_back( v ) ;
4483        }
4484      }
4485    }
4486    else {
4487      os << LogIO::SEVERE << "Unknown mode" << LogIO::POST ;
4488    }
4489    return sp ;
4490  }
4491}
4492
4493double STMath::getMJD( string strtime )
4494{
4495  if ( strtime.find("/") == string::npos ) {
4496    // MJD time string
4497    return atof( strtime.c_str() ) ;
4498  }
4499  else {
4500    // string in YYYY/MM/DD/HH:MM:SS format
4501    uInt year = atoi( strtime.substr( 0, 4 ).c_str() ) ;
4502    uInt month = atoi( strtime.substr( 5, 2 ).c_str() ) ;
4503    uInt day = atoi( strtime.substr( 8, 2 ).c_str() ) ;
4504    uInt hour = atoi( strtime.substr( 11, 2 ).c_str() ) ;
4505    uInt minute = atoi( strtime.substr( 14, 2 ).c_str() ) ;
4506    uInt sec = atoi( strtime.substr( 17, 2 ).c_str() ) ;
4507    Time t( year, month, day, hour, minute, sec ) ;
4508    return t.modifiedJulianDay() ;
4509  }
4510}
4511
4512vector<int> STMath::getRowIdFromTime( string reftime, CountedPtr<Scantable> &s )
4513{
4514  double reft = getMJD( reftime ) ;
4515  double dtmin = 1.0e100 ;
4516  double dtmax = -1.0e100 ;
4517  vector<double> dt ;
4518  int just_before = -1 ;
4519  int just_after = -1 ;
4520  for ( int i = 0 ; i < s->nrow() ; i++ ) {
4521    dt.push_back( getMJD( s->getTime( i ) ) - reft ) ;
4522  }
4523  for ( unsigned int i = 0 ; i < dt.size() ; i++ ) {
4524    if ( dt[i] > 0.0 ) {
4525      // after reftime
4526      if ( dt[i] < dtmin ) {
4527        just_after = i ;
4528        dtmin = dt[i] ;
4529      }
4530    }
4531    else if ( dt[i] < 0.0 ) {
4532      // before reftime
4533      if ( dt[i] > dtmax ) {
4534        just_before = i ;
4535        dtmax = dt[i] ;
4536      }
4537    }
4538    else {
4539      // just a reftime
4540      just_before = i ;
4541      just_after = i ;
4542      dtmax = 0 ;
4543      dtmin = 0 ;
4544      break ;
4545    }
4546  }
4547
4548  vector<int> v ;
4549  v.push_back( just_before ) ;
4550  v.push_back( just_after ) ;
4551
4552  return v ;
4553}
4554
4555vector<float> STMath::getTcalFromTime( string reftime,
4556                                       CountedPtr<Scantable>& s,
4557                                       string mode )
4558{
4559  LogIO os( LogOrigin( "STMath", "getTcalFromTime", WHERE ) ) ;
4560  vector<float> tcal ;
4561  STTcal tcalTable = s->tcal() ;
4562  String time ;
4563  Vector<Float> tcalval ;
4564  if ( s->nrow() == 0 ) {
4565    os << LogIO::SEVERE << "No row in the input scantable. Return empty tcal." << LogIO::POST ;
4566    return tcal ;
4567  }
4568  else if ( s->nrow() == 1 ) {
4569    uInt tcalid = s->getTcalId( 0 ) ;
4570    //os << "use row " << 0 << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4571    tcalTable.getEntry( time, tcalval, tcalid ) ;
4572    tcalval.tovector( tcal ) ;
4573    return tcal ;
4574  }
4575  else {
4576    vector<int> idx = getRowIdFromTime( reftime, s ) ;
4577    if ( mode == "before" ) {
4578      int id = -1 ;
4579      if ( idx[0] != -1 ) {
4580        id = idx[0] ;
4581      }
4582      else if ( idx[1] != -1 ) {
4583        os << LogIO::WARN << "Failed to find a scan before reftime. return a spectrum just after the reftime." << LogIO::POST ;
4584        id = idx[1] ;
4585      }
4586      uInt tcalid = s->getTcalId( id ) ;
4587      //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4588      tcalTable.getEntry( time, tcalval, tcalid ) ;
4589      tcalval.tovector( tcal ) ;
4590    }
4591    else if ( mode == "after" ) {
4592      int id = -1 ;
4593      if ( idx[1] != -1 ) {
4594        id = idx[1] ;
4595      }
4596      else if ( idx[0] != -1 ) {
4597        os << LogIO::WARN << "Failed to find a scan after reftime. return a spectrum just before the reftime." << LogIO::POST ;
4598        id = idx[1] ;
4599      }
4600      uInt tcalid = s->getTcalId( id ) ;
4601      //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4602      tcalTable.getEntry( time, tcalval, tcalid ) ;
4603      tcalval.tovector( tcal ) ;
4604    }
4605    else if ( mode == "nearest" ) {
4606      int id = -1 ;
4607      if ( idx[0] == -1 ) {
4608        id = idx[1] ;
4609      }
4610      else if ( idx[1] == -1 ) {
4611        id = idx[0] ;
4612      }
4613      else if ( idx[0] == idx[1] ) {
4614        id = idx[0] ;
4615      }
4616      else {
4617        //double t0 = getMJD( s->getTime( idx[0] ) ) ;
4618        //double t1 = getMJD( s->getTime( idx[1] ) ) ;
4619        double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
4620        double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
4621        double tref = getMJD( reftime ) ;
4622        if ( abs( t0 - tref ) > abs( t1 - tref ) ) {
4623          id = idx[1] ;
4624        }
4625        else {
4626          id = idx[0] ;
4627        }
4628      }
4629      uInt tcalid = s->getTcalId( id ) ;
4630      //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4631      tcalTable.getEntry( time, tcalval, tcalid ) ;
4632      tcalval.tovector( tcal ) ;
4633    }
4634    else if ( mode == "linear" ) {
4635      if ( idx[0] == -1 ) {
4636        // use after
4637        os << LogIO::WARN << "Failed to interpolate. return a spectrum just after the reftime." << LogIO::POST ;
4638        int id = idx[1] ;
4639        uInt tcalid = s->getTcalId( id ) ;
4640        //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4641        tcalTable.getEntry( time, tcalval, tcalid ) ;
4642        tcalval.tovector( tcal ) ;
4643      }
4644      else if ( idx[1] == -1 ) {
4645        // use before
4646        os << LogIO::WARN << "Failed to interpolate. return a spectrum just before the reftime." << LogIO::POST ;
4647        int id = idx[0] ;
4648        uInt tcalid = s->getTcalId( id ) ;
4649        //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4650        tcalTable.getEntry( time, tcalval, tcalid ) ;
4651        tcalval.tovector( tcal ) ;
4652      }
4653      else if ( idx[0] == idx[1] ) {
4654        // use before
4655        //os << "No need to interporate." << LogIO::POST ;
4656        int id = idx[0] ;
4657        uInt tcalid = s->getTcalId( id ) ;
4658        //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4659        tcalTable.getEntry( time, tcalval, tcalid ) ;
4660        tcalval.tovector( tcal ) ;
4661      }
4662      else {
4663        // do interpolation
4664        //os << "interpolate between " << idx[0] << " and " << idx[1] << " (scanno: " << s->getScan( idx[0] ) << ", " << s->getScan( idx[1] ) << ")" << LogIO::POST ;
4665        //double t0 = getMJD( s->getTime( idx[0] ) ) ;
4666        //double t1 = getMJD( s->getTime( idx[1] ) ) ;
4667        double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
4668        double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
4669        double tref = getMJD( reftime ) ;
4670        vector<float> tcal0 ;
4671        vector<float> tcal1 ;
4672        uInt tcalid0 = s->getTcalId( idx[0] ) ;
4673        uInt tcalid1 = s->getTcalId( idx[1] ) ;
4674        tcalTable.getEntry( time, tcalval, tcalid0 ) ;
4675        tcalval.tovector( tcal0 ) ;
4676        tcalTable.getEntry( time, tcalval, tcalid1 ) ;
4677        tcalval.tovector( tcal1 ) ;       
4678        for ( unsigned int i = 0 ; i < tcal0.size() ; i++ ) {
4679          float v = ( tcal1[i] - tcal0[i] ) / ( t1 - t0 ) * ( tref - t0 ) + tcal0[i] ;
4680          tcal.push_back( v ) ;
4681        }
4682      }
4683    }
4684    else {
4685      os << LogIO::SEVERE << "Unknown mode" << LogIO::POST ;
4686    }
4687    return tcal ;
4688  }
4689}
4690
4691vector<float> STMath::getTsysFromTime( string reftime,
4692                                       CountedPtr<Scantable>& s,
4693                                       string mode )
4694{
4695  LogIO os( LogOrigin( "STMath", "getTsysFromTime", WHERE ) ) ;
4696  ArrayColumn<Float> tsysCol ;
4697  tsysCol.attach( s->table(), "TSYS" ) ;
4698  vector<float> tsys ;
4699  String time ;
4700  Vector<Float> tsysval ;
4701  if ( s->nrow() == 0 ) {
4702    os << LogIO::SEVERE << "No row in the input scantable. Return empty tsys." << LogIO::POST ;
4703    return tsys ;
4704  }
4705  else if ( s->nrow() == 1 ) {
4706    //os << "use row " << 0 << LogIO::POST ;
4707    tsysval = tsysCol( 0 ) ;
4708    tsysval.tovector( tsys ) ;
4709    return tsys ;
4710  }
4711  else {
4712    vector<int> idx = getRowIdFromTime( reftime, s ) ;
4713    if ( mode == "before" ) {
4714      int id = -1 ;
4715      if ( idx[0] != -1 ) {
4716        id = idx[0] ;
4717      }
4718      else if ( idx[1] != -1 ) {
4719        os << LogIO::WARN << "Failed to find a scan before reftime. return a spectrum just after the reftime." << LogIO::POST ;
4720        id = idx[1] ;
4721      }
4722      //os << "use row " << id << LogIO::POST ;
4723      tsysval = tsysCol( id ) ;
4724      tsysval.tovector( tsys ) ;
4725    }
4726    else if ( mode == "after" ) {
4727      int id = -1 ;
4728      if ( idx[1] != -1 ) {
4729        id = idx[1] ;
4730      }
4731      else if ( idx[0] != -1 ) {
4732        os << LogIO::WARN << "Failed to find a scan after reftime. return a spectrum just before the reftime." << LogIO::POST ;
4733        id = idx[1] ;
4734      }
4735      //os << "use row " << id << LogIO::POST ;
4736      tsysval = tsysCol( id ) ;
4737      tsysval.tovector( tsys ) ;
4738    }
4739    else if ( mode == "nearest" ) {
4740      int id = -1 ;
4741      if ( idx[0] == -1 ) {
4742        id = idx[1] ;
4743      }
4744      else if ( idx[1] == -1 ) {
4745        id = idx[0] ;
4746      }
4747      else if ( idx[0] == idx[1] ) {
4748        id = idx[0] ;
4749      }
4750      else {
4751        //double t0 = getMJD( s->getTime( idx[0] ) ) ;
4752        //double t1 = getMJD( s->getTime( idx[1] ) ) ;
4753        double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
4754        double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
4755        double tref = getMJD( reftime ) ;
4756        if ( abs( t0 - tref ) > abs( t1 - tref ) ) {
4757          id = idx[1] ;
4758        }
4759        else {
4760          id = idx[0] ;
4761        }
4762      }
4763      //os << "use row " << id << LogIO::POST ;
4764      tsysval = tsysCol( id ) ;
4765      tsysval.tovector( tsys ) ;
4766    }
4767    else if ( mode == "linear" ) {
4768      if ( idx[0] == -1 ) {
4769        // use after
4770        os << LogIO::WARN << "Failed to interpolate. return a spectrum just after the reftime." << LogIO::POST ;
4771        int id = idx[1] ;
4772        //os << "use row " << id << LogIO::POST ;
4773        tsysval = tsysCol( id ) ;
4774        tsysval.tovector( tsys ) ;
4775      }
4776      else if ( idx[1] == -1 ) {
4777        // use before
4778        os << LogIO::WARN << "Failed to interpolate. return a spectrum just before the reftime." << LogIO::POST ;
4779        int id = idx[0] ;
4780        //os << "use row " << id << LogIO::POST ;
4781        tsysval = tsysCol( id ) ;
4782        tsysval.tovector( tsys ) ;
4783      }
4784      else if ( idx[0] == idx[1] ) {
4785        // use before
4786        //os << "No need to interporate." << LogIO::POST ;
4787        int id = idx[0] ;
4788        //os << "use row " << id << LogIO::POST ;
4789        tsysval = tsysCol( id ) ;
4790        tsysval.tovector( tsys ) ;
4791      }
4792      else {
4793        // do interpolation
4794        //os << "interpolate between " << idx[0] << " and " << idx[1] << " (scanno: " << s->getScan( idx[0] ) << ", " << s->getScan( idx[1] ) << ")" << LogIO::POST ;
4795        //double t0 = getMJD( s->getTime( idx[0] ) ) ;
4796        //double t1 = getMJD( s->getTime( idx[1] ) ) ;
4797        double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
4798        double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
4799        double tref = getMJD( reftime ) ;
4800        vector<float> tsys0 ;
4801        vector<float> tsys1 ;
4802        tsysval = tsysCol( idx[0] ) ;
4803        tsysval.tovector( tsys0 ) ;
4804        tsysval = tsysCol( idx[1] ) ;
4805        tsysval.tovector( tsys1 ) ;       
4806        for ( unsigned int i = 0 ; i < tsys0.size() ; i++ ) {
4807          float v = ( tsys1[i] - tsys0[i] ) / ( t1 - t0 ) * ( tref - t0 ) + tsys0[i] ;
4808          tsys.push_back( v ) ;
4809        }
4810      }
4811    }
4812    else {
4813      os << LogIO::SEVERE << "Unknown mode" << LogIO::POST ;
4814    }
4815    return tsys ;
4816  }
4817}
4818
4819vector<float> STMath::getCalibratedSpectra( CountedPtr<Scantable>& on,
4820                                            CountedPtr<Scantable>& off,
4821                                            CountedPtr<Scantable>& sky,
4822                                            CountedPtr<Scantable>& hot,
4823                                            CountedPtr<Scantable>& cold,
4824                                            int index,
4825                                            string antname )
4826{
4827  (void) cold; //currently unused
4828  string reftime = on->getTime( index ) ;
4829  vector<int> ii( 1, on->getIF( index ) ) ;
4830  vector<int> ib( 1, on->getBeam( index ) ) ;
4831  vector<int> ip( 1, on->getPol( index ) ) ;
4832  vector<int> ic( 1, on->getScan( index ) ) ;
4833  STSelector sel = STSelector() ;
4834  sel.setIFs( ii ) ;
4835  sel.setBeams( ib ) ;
4836  sel.setPolarizations( ip ) ;
4837  sky->setSelection( sel ) ;
4838  hot->setSelection( sel ) ;
4839  //cold->setSelection( sel ) ;
4840  off->setSelection( sel ) ;
4841  vector<float> spsky = getSpectrumFromTime( reftime, sky, "linear" ) ;
4842  vector<float> sphot = getSpectrumFromTime( reftime, hot, "linear" ) ;
4843  //vector<float> spcold = getSpectrumFromTime( reftime, cold, "linear" ) ;
4844  vector<float> spoff = getSpectrumFromTime( reftime, off, "linear" ) ;
4845  vector<float> spec = on->getSpectrum( index ) ;
4846  vector<float> tcal = getTcalFromTime( reftime, sky, "linear" ) ;
4847  vector<float> sp( tcal.size() ) ;
4848  if ( antname.find( "APEX" ) != string::npos ) {
4849    // using gain array
4850    for ( unsigned int j = 0 ; j < tcal.size() ; j++ ) {
4851      float v = ( ( spec[j] - spoff[j] ) / spoff[j] )
4852        * ( spsky[j] / ( sphot[j] - spsky[j] ) ) * tcal[j] ;
4853      sp[j] = v ;
4854    }
4855  }
4856  else {
4857    // Chopper-Wheel calibration (Ulich & Haas 1976)
4858    for ( unsigned int j = 0 ; j < tcal.size() ; j++ ) {
4859      float v = ( spec[j] - spoff[j] ) / ( sphot[j] - spsky[j] ) * tcal[j] ;
4860      sp[j] = v ;
4861    }
4862  }
4863  sel.reset() ;
4864  sky->unsetSelection() ;
4865  hot->unsetSelection() ;
4866  //cold->unsetSelection() ;
4867  off->unsetSelection() ;
4868
4869  return sp ;
4870}
4871
4872vector<float> STMath::getCalibratedSpectra( CountedPtr<Scantable>& on,
4873                                            CountedPtr<Scantable>& off,
4874                                            int index )
4875{
4876  string reftime = on->getTime( index ) ;
4877  vector<int> ii( 1, on->getIF( index ) ) ;
4878  vector<int> ib( 1, on->getBeam( index ) ) ;
4879  vector<int> ip( 1, on->getPol( index ) ) ;
4880  vector<int> ic( 1, on->getScan( index ) ) ;
4881  STSelector sel = STSelector() ;
4882  sel.setIFs( ii ) ;
4883  sel.setBeams( ib ) ;
4884  sel.setPolarizations( ip ) ;
4885  off->setSelection( sel ) ;
4886  vector<float> spoff = getSpectrumFromTime( reftime, off, "linear" ) ;
4887  vector<float> spec = on->getSpectrum( index ) ;
4888  //vector<float> tcal = getTcalFromTime( reftime, sky, "linear" ) ;
4889  //vector<float> tsys = on->getTsysVec( index ) ;
4890  ArrayColumn<Float> tsysCol( on->table(), "TSYS" ) ;
4891  Vector<Float> tsys = tsysCol( index ) ;
4892  vector<float> sp( spec.size() ) ;
4893  // ALMA Calibration
4894  //
4895  // Ta* = Tsys * ( ON - OFF ) / OFF
4896  //
4897  // 2010/01/07 Takeshi Nakazato
4898  unsigned int tsyssize = tsys.nelements() ;
4899  unsigned int spsize = sp.size() ;
4900  for ( unsigned int j = 0 ; j < sp.size() ; j++ ) {
4901    float tscale = 0.0 ;
4902    if ( tsyssize == spsize )
4903      tscale = tsys[j] ;
4904    else
4905      tscale = tsys[0] ;
4906    float v = tscale * ( spec[j] - spoff[j] ) / spoff[j] ;
4907    sp[j] = v ;
4908  }
4909  sel.reset() ;
4910  off->unsetSelection() ;
4911
4912  return sp ;
4913}
4914
4915vector<float> STMath::getFSCalibratedSpectra( CountedPtr<Scantable>& sig,
4916                                              CountedPtr<Scantable>& ref,
4917                                              CountedPtr<Scantable>& sky,
4918                                              CountedPtr<Scantable>& hot,
4919                                              CountedPtr<Scantable>& cold,
4920                                              int index )
4921{
4922  (void) cold; //currently unused
4923  string reftime = sig->getTime( index ) ;
4924  vector<int> ii( 1, sig->getIF( index ) ) ;
4925  vector<int> ib( 1, sig->getBeam( index ) ) ;
4926  vector<int> ip( 1, sig->getPol( index ) ) ;
4927  vector<int> ic( 1, sig->getScan( index ) ) ;
4928  STSelector sel = STSelector() ;
4929  sel.setIFs( ii ) ;
4930  sel.setBeams( ib ) ;
4931  sel.setPolarizations( ip ) ;
4932  sky->setSelection( sel ) ;
4933  hot->setSelection( sel ) ;
4934  //cold->setSelection( sel ) ;
4935  vector<float> spsky = getSpectrumFromTime( reftime, sky, "linear" ) ;
4936  vector<float> sphot = getSpectrumFromTime( reftime, hot, "linear" ) ;
4937  //vector<float> spcold = getSpectrumFromTime( reftime, cold, "linear" ) ;
4938  vector<float> spref = ref->getSpectrum( index ) ;
4939  vector<float> spsig = sig->getSpectrum( index ) ;
4940  vector<float> tcal = getTcalFromTime( reftime, sky, "linear" ) ;
4941  vector<float> sp( tcal.size() ) ;
4942  for ( unsigned int j = 0 ; j < tcal.size() ; j++ ) {
4943    float v = tcal[j] * spsky[j] / ( sphot[j] - spsky[j] ) * ( spsig[j] - spref[j] ) / spref[j] ;
4944    sp[j] = v ;
4945  }
4946  sel.reset() ;
4947  sky->unsetSelection() ;
4948  hot->unsetSelection() ;
4949  //cold->unsetSelection() ;
4950
4951  return sp ;
4952}
4953
4954vector<float> STMath::getFSCalibratedSpectra( CountedPtr<Scantable>& sig,
4955                                              CountedPtr<Scantable>& ref,
4956                                              vector< CountedPtr<Scantable> >& sky,
4957                                              vector< CountedPtr<Scantable> >& hot,
4958                                              vector< CountedPtr<Scantable> >& cold,
4959                                              int index )
4960{
4961  (void) cold; //currently unused
4962  string reftime = sig->getTime( index ) ;
4963  vector<int> ii( 1, sig->getIF( index ) ) ;
4964  vector<int> ib( 1, sig->getBeam( index ) ) ;
4965  vector<int> ip( 1, sig->getPol( index ) ) ;
4966  vector<int> ic( 1, sig->getScan( index ) ) ;
4967  STSelector sel = STSelector() ;
4968  sel.setIFs( ii ) ;
4969  sel.setBeams( ib ) ;
4970  sel.setPolarizations( ip ) ;
4971  sky[0]->setSelection( sel ) ;
4972  hot[0]->setSelection( sel ) ;
4973  //cold[0]->setSelection( sel ) ;
4974  vector<float> spskys = getSpectrumFromTime( reftime, sky[0], "linear" ) ;
4975  vector<float> sphots = getSpectrumFromTime( reftime, hot[0], "linear" ) ;
4976  //vector<float> spcolds = getSpectrumFromTime( reftime, cold[0], "linear" ) ;
4977  vector<float> tcals = getTcalFromTime( reftime, sky[0], "linear" ) ;
4978  sel.reset() ;
4979  ii[0] = ref->getIF( index ) ;
4980  sel.setIFs( ii ) ;
4981  sel.setBeams( ib ) ;
4982  sel.setPolarizations( ip ) ;
4983  sky[1]->setSelection( sel ) ;
4984  hot[1]->setSelection( sel ) ;
4985  //cold[1]->setSelection( sel ) ;
4986  vector<float> spskyr = getSpectrumFromTime( reftime, sky[1], "linear" ) ;
4987  vector<float> sphotr = getSpectrumFromTime( reftime, hot[1], "linear" ) ;
4988  //vector<float> spcoldr = getSpectrumFromTime( reftime, cold[1], "linear" ) ;
4989  vector<float> tcalr = getTcalFromTime( reftime, sky[1], "linear" ) ; 
4990  vector<float> spref = ref->getSpectrum( index ) ;
4991  vector<float> spsig = sig->getSpectrum( index ) ;
4992  vector<float> sp( tcals.size() ) ;
4993  for ( unsigned int j = 0 ; j < tcals.size() ; j++ ) {
4994    float v = tcals[j] * spsig[j] / ( sphots[j] - spskys[j] ) - tcalr[j] * spref[j] / ( sphotr[j] - spskyr[j] ) ;
4995    sp[j] = v ;
4996  }
4997  sel.reset() ;
4998  sky[0]->unsetSelection() ;
4999  hot[0]->unsetSelection() ;
5000  //cold[0]->unsetSelection() ;
5001  sky[1]->unsetSelection() ;
5002  hot[1]->unsetSelection() ;
5003  //cold[1]->unsetSelection() ;
5004
5005  return sp ;
5006}
Note: See TracBrowser for help on using the repository browser.