source: branches/hpc33/src/STMath.cpp @ 2539

Last change on this file since 2539 was 2539, checked in by Takeshi Nakazato, 12 years ago

New Development: No

JIRA Issue: No

Ready for Test: Yes

Interface Changes: No

What Interface Changed: Please list interface changes

Test Programs: List test programs

Put in Release Notes: Yes/No?

Module(s): Module Names change impacts.

Description: Describe your changes here...

Speedup STMath::average(). Duplicated data selection for first input table
is removed by merging TableIterator? loop with for loop over the rows for
output table.


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