source: trunk/src/STMath.cpp @ 2467

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

New Development: No

JIRA Issue: No (bug fixes)

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs: unit test of sdcal

Put in Release Notes: No

Module(s):

Description: fixed minor bug in a log message. also removed unused variables.


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