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

Last change on this file since 2543 was 2543, 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...

Defiend STMath::copyRows that is able to skip to copy SPECTRA/FLAGTRA/TSYS
if they are not necessary to copy.


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