source: trunk/src/STMath.cpp @ 2474

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

New Development: No

JIRA Issue: No (a bug fix)

Ready for Test: Yes

Interface Changes: No

What Interface Changed:

Test Programs: run sdsmooth unit tests with sd.rcParamsinsitu? = False

Put in Release Notes: No

Module(s):

Description:

fxied a bug which caused STMath::convertFlux modify original data but not a data to return.


  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 170.4 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  Table& outtab = out->table();
2203  Unit fluxUnit(tab.keywordSet().asString("FluxUnit"));
2204  Unit K(String("K"));
2205  Unit JY(String("Jy"));
2206
2207  bool tokelvin = true;
2208  Double cfac = 1.0;
2209
2210  if ( fluxUnit == JY ) {
2211    pushLog("Converting to K");
2212    Quantum<Double> t(1.0,fluxUnit);
2213    Quantum<Double> t2 = t.get(JY);
2214    cfac = (t2 / t).getValue();               // value to Jy
2215
2216    tokelvin = true;
2217    out->setFluxUnit("K");
2218  } else if ( fluxUnit == K ) {
2219    pushLog("Converting to Jy");
2220    Quantum<Double> t(1.0,fluxUnit);
2221    Quantum<Double> t2 = t.get(K);
2222    cfac = (t2 / t).getValue();              // value to K
2223
2224    tokelvin = false;
2225    out->setFluxUnit("Jy");
2226  } else {
2227    throw(AipsError("Unrecognized brightness units in Table - must be consistent with Jy or K"));
2228  }
2229  // Make sure input values are converted to either Jy or K first...
2230  Float factor = cfac;
2231
2232  // Select method
2233  if (jyperk > 0.0) {
2234    factor *= jyperk;
2235    if ( tokelvin ) factor = 1.0 / jyperk;
2236    ostringstream oss;
2237    oss << "Jy/K = " << jyperk;
2238    pushLog(String(oss));
2239    Vector<Float> factors(outtab.nrow(), factor);
2240    scaleByVector(outtab,factors, false);
2241  } else if ( etaap > 0.0) {
2242    if (d < 0) {
2243      Instrument inst =
2244        STAttr::convertInstrument(tab.keywordSet().asString("AntennaName"),
2245                                  True);
2246      STAttr sda;
2247      d = sda.diameter(inst);
2248    }
2249    jyperk = STAttr::findJyPerK(etaap, d);
2250    ostringstream oss;
2251    oss << "Jy/K = " << jyperk;
2252    pushLog(String(oss));
2253    factor *= jyperk;
2254    if ( tokelvin ) {
2255      factor = 1.0 / factor;
2256    }
2257    Vector<Float> factors(outtab.nrow(), factor);
2258    scaleByVector(outtab, factors, False);
2259  } else {
2260
2261    // OK now we must deal with automatic look up of values.
2262    // We must also deal with the fact that the factors need
2263    // to be computed per IF and may be different and may
2264    // change per integration.
2265
2266    pushLog("Looking up conversion factors");
2267    convertBrightnessUnits(out, tokelvin, cfac);
2268  }
2269
2270  return out;
2271}
2272
2273void STMath::convertBrightnessUnits( CountedPtr<Scantable>& in,
2274                                     bool tokelvin, float cfac )
2275{
2276  Table& table = in->table();
2277  Instrument inst =
2278    STAttr::convertInstrument(table.keywordSet().asString("AntennaName"), True);
2279  TableIterator iter(table, "FREQ_ID");
2280  STFrequencies stfreqs = in->frequencies();
2281  STAttr sdAtt;
2282  while (!iter.pastEnd()) {
2283    Table tab = iter.table();
2284    ArrayColumn<Float> specCol(tab, "SPECTRA");
2285    ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2286    ROScalarColumn<uInt> freqidCol(tab, "FREQ_ID");
2287    MEpoch::ROScalarColumn timeCol(tab, "TIME");
2288
2289    uInt freqid; freqidCol.get(0, freqid);
2290    Vector<Float> tmpspec; specCol.get(0, tmpspec);
2291    // STAttr.JyPerK has a Vector interface... change sometime.
2292    Vector<Float> freqs(1,stfreqs.getRefFreq(freqid, tmpspec.nelements()));
2293    for ( uInt i=0; i<tab.nrow(); ++i) {
2294      Float jyperk = (sdAtt.JyPerK(inst, timeCol(i), freqs))[0];
2295      Float factor = cfac * jyperk;
2296      if ( tokelvin ) factor = Float(1.0) / factor;
2297      MaskedArray<Float> ma  = maskedArray(specCol(i), flagCol(i));
2298      ma *= factor;
2299      specCol.put(i, ma.getArray());
2300      flagCol.put(i, flagsFromMA(ma));
2301    }
2302  ++iter;
2303  }
2304}
2305
2306CountedPtr< Scantable > STMath::opacity( const CountedPtr< Scantable > & in,
2307                                         const std::vector<float>& tau )
2308{
2309  CountedPtr< Scantable > out = getScantable(in, false);
2310
2311  Table outtab = out->table();
2312
2313  const Int ntau = uInt(tau.size());
2314  std::vector<float>::const_iterator tauit = tau.begin();
2315  AlwaysAssert((ntau == 1 || ntau == in->nif() || ntau == in->nif() * in->npol()),
2316               AipsError);
2317  TableIterator iiter(outtab, "IFNO");
2318  while ( !iiter.pastEnd() ) {
2319    Table itab = iiter.table();
2320    TableIterator piter(itab, "POLNO");
2321    while ( !piter.pastEnd() ) {
2322      Table tab = piter.table();
2323      ROScalarColumn<Float> elev(tab, "ELEVATION");
2324      ArrayColumn<Float> specCol(tab, "SPECTRA");
2325      ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2326      ArrayColumn<Float> tsysCol(tab, "TSYS");
2327      for ( uInt i=0; i<tab.nrow(); ++i) {
2328        Float zdist = Float(C::pi_2) - elev(i);
2329        Float factor = exp(*tauit/cos(zdist));
2330        MaskedArray<Float> ma = maskedArray(specCol(i), flagCol(i));
2331        ma *= factor;
2332        specCol.put(i, ma.getArray());
2333        flagCol.put(i, flagsFromMA(ma));
2334        Vector<Float> tsys;
2335        tsysCol.get(i, tsys);
2336        tsys *= factor;
2337        tsysCol.put(i, tsys);
2338      }
2339      if (ntau == in->nif()*in->npol() ) {
2340        tauit++;
2341      }
2342      piter++;
2343    }
2344    if (ntau >= in->nif() ) {
2345      tauit++;
2346    }
2347    iiter++;
2348  }
2349  return out;
2350}
2351
2352CountedPtr< Scantable > STMath::smoothOther( const CountedPtr< Scantable >& in,
2353                                             const std::string& kernel,
2354                                             float width, int order)
2355{
2356  CountedPtr< Scantable > out = getScantable(in, false);
2357  Table table = out->table();
2358
2359  TableIterator iter(table, "IFNO");
2360  while (!iter.pastEnd()) {
2361    Table tab = iter.table();
2362    ArrayColumn<Float> specCol(tab, "SPECTRA");
2363    ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2364    Vector<Float> spec;
2365    Vector<uChar> flag;
2366    for (uInt i = 0; i < tab.nrow(); ++i) {
2367      specCol.get(i, spec);
2368      flagCol.get(i, flag);
2369      Vector<Bool> mask(flag.nelements());
2370      convertArray(mask, flag);
2371      Vector<Float> specout;
2372      Vector<Bool> maskout;
2373      if (kernel == "hanning") {
2374        mathutil::hanning(specout, maskout, spec, !mask);
2375        convertArray(flag, !maskout);
2376      } else if (kernel == "rmedian") {
2377        mathutil::runningMedian(specout, maskout, spec , mask, width);
2378        convertArray(flag, maskout);
2379      } else if (kernel == "poly") {
2380        mathutil::polyfit(specout, maskout, spec, !mask, width, order);
2381        convertArray(flag, !maskout);
2382      }
2383
2384      for (uInt j = 0; j < flag.nelements(); ++j) {
2385        uChar userFlag = 1 << 7;
2386        if (maskout[j]==True) userFlag = 0 << 7;
2387        flag(j) = userFlag;
2388      }
2389
2390      flagCol.put(i, flag);
2391      specCol.put(i, specout);
2392    }
2393  ++iter;
2394  }
2395  return out;
2396}
2397
2398CountedPtr< Scantable > STMath::smooth( const CountedPtr< Scantable >& in,
2399                                        const std::string& kernel, float width,
2400                                        int order)
2401{
2402  if (kernel == "rmedian"  || kernel == "hanning" || kernel == "poly") {
2403    return smoothOther(in, kernel, width, order);
2404  }
2405  CountedPtr< Scantable > out = getScantable(in, false);
2406  Table& table = out->table();
2407  VectorKernel::KernelTypes type = VectorKernel::toKernelType(kernel);
2408  // same IFNO should have same no of channels
2409  // this saves overhead
2410  TableIterator iter(table, "IFNO");
2411  while (!iter.pastEnd()) {
2412    Table tab = iter.table();
2413    ArrayColumn<Float> specCol(tab, "SPECTRA");
2414    ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2415    Vector<Float> tmpspec; specCol.get(0, tmpspec);
2416    uInt nchan = tmpspec.nelements();
2417    Vector<Float> kvec = VectorKernel::make(type, width, nchan, True, False);
2418    Convolver<Float> conv(kvec, IPosition(1,nchan));
2419    Vector<Float> spec;
2420    Vector<uChar> flag;
2421    for ( uInt i=0; i<tab.nrow(); ++i) {
2422      specCol.get(i, spec);
2423      flagCol.get(i, flag);
2424      Vector<Bool> mask(flag.nelements());
2425      convertArray(mask, flag);
2426      Vector<Float> specout;
2427      mathutil::replaceMaskByZero(specout, mask);
2428      conv.linearConv(specout, spec);
2429      specCol.put(i, specout);
2430    }
2431    ++iter;
2432  }
2433  return out;
2434}
2435
2436CountedPtr< Scantable >
2437  STMath::merge( const std::vector< CountedPtr < Scantable > >& in )
2438{
2439  if ( in.size() < 2 ) {
2440    throw(AipsError("Need at least two scantables to perform a merge."));
2441  }
2442  std::vector<CountedPtr < Scantable > >::const_iterator it = in.begin();
2443  bool insitu = insitu_;
2444  setInsitu(false);
2445  CountedPtr< Scantable > out = getScantable(*it, false);
2446  setInsitu(insitu);
2447  Table& tout = out->table();
2448  ScalarColumn<uInt> freqidcol(tout,"FREQ_ID"), molidcol(tout, "MOLECULE_ID");
2449  ScalarColumn<uInt> scannocol(tout,"SCANNO"), focusidcol(tout,"FOCUS_ID");
2450  // Renumber SCANNO to be 0-based
2451  Vector<uInt> scannos = scannocol.getColumn();
2452  uInt offset = min(scannos);
2453  scannos -= offset;
2454  scannocol.putColumn(scannos);
2455  uInt newscanno = max(scannos)+1;
2456  ++it;
2457  while ( it != in.end() ){
2458    if ( ! (*it)->conformant(*out) ) {
2459      // non conformant.
2460      //pushLog(String("Warning: Can't merge scantables as header info differs."));
2461      LogIO os( LogOrigin( "STMath", "merge()", WHERE ) ) ;
2462      os << LogIO::SEVERE << "Can't merge scantables as header informations (any one of AntennaName, Equinox, and FluxUnit) differ." << LogIO::EXCEPTION ;
2463    }
2464    out->appendToHistoryTable((*it)->history());
2465    const Table& tab = (*it)->table();
2466
2467    Block<String> cols(3);
2468    cols[0] = String("FREQ_ID");
2469    cols[1] = String("MOLECULE_ID");
2470    cols[2] = String("FOCUS_ID");
2471
2472    TableIterator scanit(tab, "SCANNO");
2473    while (!scanit.pastEnd()) {
2474      ScalarColumn<uInt> thescannocol(scanit.table(),"SCANNO");
2475      Vector<uInt> thescannos(thescannocol.nrow(),newscanno);
2476      thescannocol.putColumn(thescannos);
2477      TableIterator subit(scanit.table(), cols);
2478      while ( !subit.pastEnd() ) {
2479        uInt nrow = tout.nrow();
2480        Table thetab = subit.table();
2481        ROTableRow row(thetab);
2482        Vector<uInt> thecolvals(thetab.nrow());
2483        ScalarColumn<uInt> thefreqidcol(thetab,"FREQ_ID");
2484        ScalarColumn<uInt> themolidcol(thetab, "MOLECULE_ID");
2485        ScalarColumn<uInt> thefocusidcol(thetab,"FOCUS_ID");
2486        // The selected subset of table should have
2487        // the equal FREQ_ID, MOLECULE_ID, and FOCUS_ID values.
2488        const TableRecord& rec = row.get(0);
2489        // Set the proper FREQ_ID
2490        Double rv,rp,inc;
2491        (*it)->frequencies().getEntry(rp, rv, inc, rec.asuInt("FREQ_ID"));
2492        uInt id;
2493        id = out->frequencies().addEntry(rp, rv, inc);
2494        thecolvals = id;
2495        thefreqidcol.putColumn(thecolvals);
2496        // Set the proper MOLECULE_ID
2497        Vector<String> name,fname;Vector<Double> rf;
2498        (*it)->molecules().getEntry(rf, name, fname, rec.asuInt("MOLECULE_ID"));
2499        id = out->molecules().addEntry(rf, name, fname);
2500        thecolvals = id;
2501        themolidcol.putColumn(thecolvals);
2502        // Set the proper FOCUS_ID
2503        Float fpa,frot,fax,ftan,fhand,fmount,fuser, fxy, fxyp;
2504        (*it)->focus().getEntry(fpa, fax, ftan, frot, fhand, fmount,fuser,
2505                                fxy, fxyp, rec.asuInt("FOCUS_ID"));
2506        id = out->focus().addEntry(fpa, fax, ftan, frot, fhand, fmount,fuser,
2507                                   fxy, fxyp);
2508        thecolvals = id;
2509        thefocusidcol.putColumn(thecolvals);
2510
2511        tout.addRow(thetab.nrow());
2512        TableCopy::copyRows(tout, thetab, nrow, 0, thetab.nrow());
2513
2514        ++subit;
2515      }
2516      ++newscanno;
2517      ++scanit;
2518    }
2519    ++it;
2520  }
2521  return out;
2522}
2523
2524CountedPtr< Scantable >
2525  STMath::invertPhase( const CountedPtr < Scantable >& in )
2526{
2527  return applyToPol(in, &STPol::invertPhase, Float(0.0));
2528}
2529
2530CountedPtr< Scantable >
2531  STMath::rotateXYPhase( const CountedPtr < Scantable >& in, float phase )
2532{
2533   return applyToPol(in, &STPol::rotatePhase, Float(phase));
2534}
2535
2536CountedPtr< Scantable >
2537  STMath::rotateLinPolPhase( const CountedPtr < Scantable >& in, float phase )
2538{
2539  return applyToPol(in, &STPol::rotateLinPolPhase, Float(phase));
2540}
2541
2542CountedPtr< Scantable > STMath::applyToPol( const CountedPtr<Scantable>& in,
2543                                             STPol::polOperation fptr,
2544                                             Float phase )
2545{
2546  CountedPtr< Scantable > out = getScantable(in, false);
2547  Table& tout = out->table();
2548  Block<String> cols(4);
2549  cols[0] = String("SCANNO");
2550  cols[1] = String("BEAMNO");
2551  cols[2] = String("IFNO");
2552  cols[3] = String("CYCLENO");
2553  TableIterator iter(tout, cols);
2554  CountedPtr<STPol> stpol = STPol::getPolClass(out->factories_,
2555                                               out->getPolType() );
2556  while (!iter.pastEnd()) {
2557    Table t = iter.table();
2558    ArrayColumn<Float> speccol(t, "SPECTRA");
2559    ScalarColumn<uInt> focidcol(t, "FOCUS_ID");
2560    Matrix<Float> pols(speccol.getColumn());
2561    try {
2562      stpol->setSpectra(pols);
2563      Float fang,fhand;
2564      fang = in->focusTable_.getTotalAngle(focidcol(0));
2565      fhand = in->focusTable_.getFeedHand(focidcol(0));
2566      stpol->setPhaseCorrections(fang, fhand);
2567      // use a member function pointer in STPol.  This only works on
2568      // the STPol pointer itself, not the Counted Pointer so
2569      // derefernce it.
2570      (&(*(stpol))->*fptr)(phase);
2571      speccol.putColumn(stpol->getSpectra());
2572    } catch (AipsError& e) {
2573      //delete stpol;stpol=0;
2574      throw(e);
2575    }
2576    ++iter;
2577  }
2578  //delete stpol;stpol=0;
2579  return out;
2580}
2581
2582CountedPtr< Scantable >
2583  STMath::swapPolarisations( const CountedPtr< Scantable > & in )
2584{
2585  CountedPtr< Scantable > out = getScantable(in, false);
2586  Table& tout = out->table();
2587  Table t0 = tout(tout.col("POLNO") == 0);
2588  Table t1 = tout(tout.col("POLNO") == 1);
2589  if ( t0.nrow() != t1.nrow() )
2590    throw(AipsError("Inconsistent number of polarisations"));
2591  ArrayColumn<Float> speccol0(t0, "SPECTRA");
2592  ArrayColumn<uChar> flagcol0(t0, "FLAGTRA");
2593  ArrayColumn<Float> speccol1(t1, "SPECTRA");
2594  ArrayColumn<uChar> flagcol1(t1, "FLAGTRA");
2595  Matrix<Float> s0 = speccol0.getColumn();
2596  Matrix<uChar> f0 = flagcol0.getColumn();
2597  speccol0.putColumn(speccol1.getColumn());
2598  flagcol0.putColumn(flagcol1.getColumn());
2599  speccol1.putColumn(s0);
2600  flagcol1.putColumn(f0);
2601  return out;
2602}
2603
2604CountedPtr< Scantable >
2605  STMath::averagePolarisations( const CountedPtr< Scantable > & in,
2606                                const std::vector<bool>& mask,
2607                                const std::string& weight )
2608{
2609  if (in->npol() < 2 )
2610    throw(AipsError("averagePolarisations can only be applied to two or more"
2611                    "polarisations"));
2612  bool insitu = insitu_;
2613  setInsitu(false);
2614  CountedPtr< Scantable > pols = getScantable(in, true);
2615  setInsitu(insitu);
2616  Table& tout = pols->table();
2617  std::string taql = "SELECT FROM $1 WHERE POLNO IN [0,1]";
2618  Table tab = tableCommand(taql, in->table());
2619  if (tab.nrow() == 0 )
2620    throw(AipsError("Could not find  any rows with POLNO==0 and POLNO==1"));
2621  TableCopy::copyRows(tout, tab);
2622  TableVector<uInt> vec(tout, "POLNO");
2623  vec = 0;
2624  pols->table_.rwKeywordSet().define("nPol", Int(1));
2625  pols->table_.rwKeywordSet().define("POLTYPE", String("stokes"));
2626  //pols->table_.rwKeywordSet().define("POLTYPE", in->getPolType());
2627  std::vector<CountedPtr<Scantable> > vpols;
2628  vpols.push_back(pols);
2629  CountedPtr< Scantable > out = average(vpols, mask, weight, "SCAN");
2630  return out;
2631}
2632
2633CountedPtr< Scantable >
2634  STMath::averageBeams( const CountedPtr< Scantable > & in,
2635                        const std::vector<bool>& mask,
2636                        const std::string& weight )
2637{
2638  bool insitu = insitu_;
2639  setInsitu(false);
2640  CountedPtr< Scantable > beams = getScantable(in, false);
2641  setInsitu(insitu);
2642  Table& tout = beams->table();
2643  // give all rows the same BEAMNO
2644  TableVector<uInt> vec(tout, "BEAMNO");
2645  vec = 0;
2646  beams->table_.rwKeywordSet().define("nBeam", Int(1));
2647  std::vector<CountedPtr<Scantable> > vbeams;
2648  vbeams.push_back(beams);
2649  CountedPtr< Scantable > out = average(vbeams, mask, weight, "SCAN");
2650  return out;
2651}
2652
2653
2654CountedPtr< Scantable >
2655  asap::STMath::frequencyAlign( const CountedPtr< Scantable > & in,
2656                                const std::string & refTime,
2657                                const std::string & method)
2658{
2659  // clone as this is not working insitu
2660  bool insitu = insitu_;
2661  setInsitu(false);
2662  CountedPtr< Scantable > out = getScantable(in, false);
2663  setInsitu(insitu);
2664  Table& tout = out->table();
2665  // Get reference Epoch to time of first row or given String
2666  Unit DAY(String("d"));
2667  MEpoch::Ref epochRef(in->getTimeReference());
2668  MEpoch refEpoch;
2669  if (refTime.length()>0) {
2670    Quantum<Double> qt;
2671    if (MVTime::read(qt,refTime)) {
2672      MVEpoch mv(qt);
2673      refEpoch = MEpoch(mv, epochRef);
2674   } else {
2675      throw(AipsError("Invalid format for Epoch string"));
2676   }
2677  } else {
2678    refEpoch = in->timeCol_(0);
2679  }
2680  MPosition refPos = in->getAntennaPosition();
2681
2682  InterpolateArray1D<Double,Float>::InterpolationMethod interp = stringToIMethod(method);
2683  /*
2684  // Comment from MV.
2685  // the following code has been commented out because different FREQ_IDs have to be aligned together even
2686  // if the frame doesn't change. So far, lack of this check didn't cause any problems.
2687  // test if user frame is different to base frame
2688  if ( in->frequencies().getFrameString(true)
2689       == in->frequencies().getFrameString(false) ) {
2690    throw(AipsError("Can't convert as no output frame has been set"
2691                    " (use set_freqframe) or it is aligned already."));
2692  }
2693  */
2694  MFrequency::Types system = in->frequencies().getFrame();
2695  MVTime mvt(refEpoch.getValue());
2696  String epochout = mvt.string(MVTime::YMD) + String(" (") + refEpoch.getRefString() + String(")");
2697  ostringstream oss;
2698  oss << "Aligned at reference Epoch " << epochout
2699      << " in frame " << MFrequency::showType(system);
2700  pushLog(String(oss));
2701  // set up the iterator
2702  Block<String> cols(4);
2703  // select by constant direction
2704  cols[0] = String("SRCNAME");
2705  cols[1] = String("BEAMNO");
2706  // select by IF ( no of channels varies over this )
2707  cols[2] = String("IFNO");
2708  // select by restfrequency
2709  cols[3] = String("MOLECULE_ID");
2710  TableIterator iter(tout, cols);
2711  while ( !iter.pastEnd() ) {
2712    Table t = iter.table();
2713    MDirection::ROScalarColumn dirCol(t, "DIRECTION");
2714    TableIterator fiter(t, "FREQ_ID");
2715    // determine nchan from the first row. This should work as
2716    // we are iterating over BEAMNO and IFNO    // we should have constant direction
2717
2718    ROArrayColumn<Float> sCol(t, "SPECTRA");
2719    const MDirection direction = dirCol(0);
2720    const uInt nchan = sCol(0).nelements();
2721
2722    // skip operations if there is nothing to align
2723    if (fiter.pastEnd()) {
2724        continue;
2725    }
2726
2727    Table ftab = fiter.table();
2728    // align all frequency ids with respect to the first encountered id
2729    ScalarColumn<uInt> freqidCol(ftab, "FREQ_ID");
2730    // get the SpectralCoordinate for the freqid, which we are iterating over
2731    SpectralCoordinate sC = in->frequencies().getSpectralCoordinate(freqidCol(0));
2732    FrequencyAligner<Float> fa( sC, nchan, refEpoch,
2733                                direction, refPos, system );
2734    // realign the SpectralCoordinate and put into the output Scantable
2735    Vector<String> units(1);
2736    units = String("Hz");
2737    Bool linear=True;
2738    SpectralCoordinate sc2 = fa.alignedSpectralCoordinate(linear);
2739    sc2.setWorldAxisUnits(units);
2740    const uInt id = out->frequencies().addEntry(sc2.referencePixel()[0],
2741                                                sc2.referenceValue()[0],
2742                                                sc2.increment()[0]);
2743    while ( !fiter.pastEnd() ) {
2744      ftab = fiter.table();
2745      // spectral coordinate for the current FREQ_ID
2746      ScalarColumn<uInt> freqidCol2(ftab, "FREQ_ID");
2747      sC = in->frequencies().getSpectralCoordinate(freqidCol2(0));
2748      // create the "global" abcissa for alignment with same FREQ_ID
2749      Vector<Double> abc(nchan);
2750      for (uInt i=0; i<nchan; i++) {
2751           Double w;
2752           sC.toWorld(w,Double(i));
2753           abc[i] = w;
2754      }
2755      TableVector<uInt> tvec(ftab, "FREQ_ID");
2756      // assign new frequency id to all rows
2757      tvec = id;
2758      // cache abcissa for same time stamps, so iterate over those
2759      TableIterator timeiter(ftab, "TIME");
2760      while ( !timeiter.pastEnd() ) {
2761        Table tab = timeiter.table();
2762        ArrayColumn<Float> specCol(tab, "SPECTRA");
2763        ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2764        MEpoch::ROScalarColumn timeCol(tab, "TIME");
2765        // use align abcissa cache after the first row
2766        // these rows should be just be POLNO
2767        bool first = true;
2768        for (int i=0; i<int(tab.nrow()); ++i) {
2769          // input values
2770          Vector<uChar> flag = flagCol(i);
2771          Vector<Bool> mask(flag.shape());
2772          Vector<Float> specOut, spec;
2773          spec  = specCol(i);
2774          Vector<Bool> maskOut;Vector<uChar> flagOut;
2775          convertArray(mask, flag);
2776          // alignment
2777          Bool ok = fa.align(specOut, maskOut, abc, spec,
2778                             mask, timeCol(i), !first,
2779                             interp, False);
2780          (void) ok; // unused stop compiler nagging
2781          // back into scantable
2782          flagOut.resize(maskOut.nelements());
2783          convertArray(flagOut, maskOut);
2784          flagCol.put(i, flagOut);
2785          specCol.put(i, specOut);
2786          // start abcissa caching
2787          first = false;
2788        }
2789        // next timestamp
2790        ++timeiter;
2791      }
2792      // next FREQ_ID
2793      ++fiter;
2794    }
2795    // next aligner
2796    ++iter;
2797  }
2798  // set this afterwards to ensure we are doing insitu correctly.
2799  out->frequencies().setFrame(system, true);
2800  return out;
2801}
2802
2803CountedPtr<Scantable>
2804  asap::STMath::convertPolarisation( const CountedPtr<Scantable>& in,
2805                                     const std::string & newtype )
2806{
2807  if (in->npol() != 2 && in->npol() != 4)
2808    throw(AipsError("Can only convert two or four polarisations."));
2809  if ( in->getPolType() == newtype )
2810    throw(AipsError("No need to convert."));
2811  if ( ! in->selector_.empty() )
2812    throw(AipsError("Can only convert whole scantable. Unset the selection."));
2813  bool insitu = insitu_;
2814  setInsitu(false);
2815  CountedPtr< Scantable > out = getScantable(in, true);
2816  setInsitu(insitu);
2817  Table& tout = out->table();
2818  tout.rwKeywordSet().define("POLTYPE", String(newtype));
2819
2820  Block<String> cols(4);
2821  cols[0] = "SCANNO";
2822  cols[1] = "CYCLENO";
2823  cols[2] = "BEAMNO";
2824  cols[3] = "IFNO";
2825  TableIterator it(in->originalTable_, cols);
2826  String basetype = in->getPolType();
2827  STPol* stpol = STPol::getPolClass(in->factories_, basetype);
2828  try {
2829    while ( !it.pastEnd() ) {
2830      Table tab = it.table();
2831      uInt row = tab.rowNumbers()[0];
2832      stpol->setSpectra(in->getPolMatrix(row));
2833      Float fang,fhand;
2834      fang = in->focusTable_.getTotalAngle(in->mfocusidCol_(row));
2835      fhand = in->focusTable_.getFeedHand(in->mfocusidCol_(row));
2836      stpol->setPhaseCorrections(fang, fhand);
2837      Int npolout = 0;
2838      for (uInt i=0; i<tab.nrow(); ++i) {
2839        Vector<Float> outvec = stpol->getSpectrum(i, newtype);
2840        if ( outvec.nelements() > 0 ) {
2841          tout.addRow();
2842          TableCopy::copyRows(tout, tab, tout.nrow()-1, 0, 1);
2843          ArrayColumn<Float> sCol(tout,"SPECTRA");
2844          ScalarColumn<uInt> pCol(tout,"POLNO");
2845          sCol.put(tout.nrow()-1 ,outvec);
2846          pCol.put(tout.nrow()-1 ,uInt(npolout));
2847          npolout++;
2848       }
2849      }
2850      tout.rwKeywordSet().define("nPol", npolout);
2851      ++it;
2852    }
2853  } catch (AipsError& e) {
2854    delete stpol;
2855    throw(e);
2856  }
2857  delete stpol;
2858  return out;
2859}
2860
2861CountedPtr< Scantable >
2862  asap::STMath::mxExtract( const CountedPtr< Scantable > & in,
2863                           const std::string & scantype )
2864{
2865  bool insitu = insitu_;
2866  setInsitu(false);
2867  CountedPtr< Scantable > out = getScantable(in, true);
2868  setInsitu(insitu);
2869  Table& tout = out->table();
2870  std::string taql = "SELECT FROM $1 WHERE BEAMNO != REFBEAMNO";
2871  if (scantype == "on") {
2872    taql = "SELECT FROM $1 WHERE BEAMNO == REFBEAMNO";
2873  }
2874  Table tab = tableCommand(taql, in->table());
2875  TableCopy::copyRows(tout, tab);
2876  if (scantype == "on") {
2877    // re-index SCANNO to 0
2878    TableVector<uInt> vec(tout, "SCANNO");
2879    vec = 0;
2880  }
2881  return out;
2882}
2883
2884std::vector<float>
2885  asap::STMath::fft( const casa::CountedPtr< Scantable > & in,
2886                     const std::vector<int>& whichrow,
2887                     bool getRealImag )
2888{
2889  std::vector<float> res;
2890  Table tab = in->table();
2891  std::vector<bool> mask;
2892
2893  if (whichrow.size() < 1) {          // for all rows (by default)
2894    int nrow = int(tab.nrow());
2895    for (int i = 0; i < nrow; ++i) {
2896      res = in->execFFT(i, mask, getRealImag);
2897    }
2898  } else {                           // for specified rows
2899    for (uInt i = 0; i < whichrow.size(); ++i) {
2900      res = in->execFFT(i, mask, getRealImag);
2901    }
2902  }
2903
2904  return res;
2905}
2906
2907
2908CountedPtr<Scantable>
2909  asap::STMath::lagFlag( const CountedPtr<Scantable>& in,
2910                         double start, double end,
2911                         const std::string& mode )
2912{
2913  CountedPtr<Scantable> out = getScantable(in, false);
2914  Table& tout = out->table();
2915  TableIterator iter(tout, "FREQ_ID");
2916  FFTServer<Float,Complex> ffts;
2917
2918  while ( !iter.pastEnd() ) {
2919    Table tab = iter.table();
2920    Double rp,rv,inc;
2921    ROTableRow row(tab);
2922    const TableRecord& rec = row.get(0);
2923    uInt freqid = rec.asuInt("FREQ_ID");
2924    out->frequencies().getEntry(rp, rv, inc, freqid);
2925    ArrayColumn<Float> specCol(tab, "SPECTRA");
2926    ArrayColumn<uChar> flagCol(tab, "FLAGTRA");
2927
2928    for (int i=0; i<int(tab.nrow()); ++i) {
2929      Vector<Float> spec = specCol(i);
2930      Vector<uChar> flag = flagCol(i);
2931      std::vector<bool> mask;
2932      for (uInt j = 0; j < flag.nelements(); ++j) {
2933        mask.push_back(!(flag[j]>0));
2934      }
2935      mathutil::doZeroOrderInterpolation(spec, mask);
2936
2937      Vector<Complex> lags;
2938      ffts.fft0(lags, spec);
2939
2940      Int lag0(start+0.5);
2941      Int lag1(end+0.5);
2942      if (mode == "frequency") {
2943        lag0 = Int(spec.nelements()*abs(inc)/(start)+0.5);
2944        lag1 = Int(spec.nelements()*abs(inc)/(end)+0.5);
2945      }
2946      Int lstart =  max(0, lag0);
2947      Int lend   =  min(Int(lags.nelements()-1), lag1);
2948      if (lstart == lend) {
2949        lags[lstart] = Complex(0.0);
2950      } else {
2951        if (lstart > lend) {
2952          Int tmp = lend;
2953          lend = lstart;
2954          lstart = tmp;
2955        }
2956        for (int j=lstart; j <=lend ;++j) {
2957          lags[j] = Complex(0.0);
2958        }
2959      }
2960
2961      ffts.fft0(spec, lags);
2962
2963      specCol.put(i, spec);
2964    }
2965    ++iter;
2966  }
2967  return out;
2968}
2969
2970// Averaging spectra with different channel/resolution
2971CountedPtr<Scantable>
2972STMath::new_average( const std::vector<CountedPtr<Scantable> >& in,
2973                     const bool& compel,
2974                     const std::vector<bool>& mask,
2975                     const std::string& weight,
2976                     const std::string& avmode )
2977  throw ( casa::AipsError )
2978{
2979  LogIO os( LogOrigin( "STMath", "new_average()", WHERE ) ) ;
2980  if ( avmode == "SCAN" && in.size() != 1 )
2981    throw(AipsError("Can't perform 'SCAN' averaging on multiple tables.\n"
2982                    "Use merge first."));
2983 
2984  // 2012/02/17 TN
2985  // Since STGrid is implemented, average doesn't consider direction
2986  // when accumulating
2987  // check if OTF observation
2988//   String obstype = in[0]->getHeader().obstype ;
2989//   Double tol = 0.0 ;
2990//   if ( obstype.find( "OTF" ) != String::npos ) {
2991//     tol = TOL_OTF ;
2992//   }
2993//   else {
2994//     tol = TOL_POINT ;
2995//   }
2996
2997  CountedPtr<Scantable> out ;     // processed result
2998  if ( compel ) {
2999    std::vector< CountedPtr<Scantable> > newin ; // input for average process
3000    uInt insize = in.size() ;    // number of input scantables
3001
3002    // TEST: do normal average in each table before IF grouping
3003    os << "Do preliminary averaging" << LogIO::POST ;
3004    vector< CountedPtr<Scantable> > tmpin( insize ) ;
3005    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3006      vector< CountedPtr<Scantable> > v( 1, in[itable] ) ;
3007      tmpin[itable] = average( v, mask, weight, avmode ) ;
3008    }
3009
3010    // warning
3011    os << "Average spectra with different spectral resolution" << LogIO::POST ;
3012
3013    // temporarily set coordinfo
3014    vector<string> oldinfo( insize ) ;
3015    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3016      vector<string> coordinfo = in[itable]->getCoordInfo() ;
3017      oldinfo[itable] = coordinfo[0] ;
3018      coordinfo[0] = "Hz" ;
3019      tmpin[itable]->setCoordInfo( coordinfo ) ;
3020    }
3021
3022    // columns
3023    ScalarColumn<uInt> freqIDCol ;
3024    ScalarColumn<uInt> ifnoCol ;
3025    ScalarColumn<uInt> scannoCol ;
3026
3027
3028    // check IF frequency coverage
3029    // freqid: list of FREQ_ID, which is used, in each table 
3030    // iffreq: list of minimum and maximum frequency for each FREQ_ID in
3031    //         each table
3032    // freqid[insize][numIF]
3033    // freqid: [[id00, id01, ...],
3034    //          [id10, id11, ...],
3035    //          ...
3036    //          [idn0, idn1, ...]]
3037    // iffreq[insize][numIF*2]
3038    // iffreq: [[min_id00, max_id00, min_id01, max_id01, ...],
3039    //          [min_id10, max_id10, min_id11, max_id11, ...],
3040    //          ...
3041    //          [min_idn0, max_idn0, min_idn1, max_idn1, ...]]
3042    //os << "Check IF settings in each table" << LogIO::POST ;
3043    vector< vector<uInt> > freqid( insize );
3044    vector< vector<double> > iffreq( insize ) ;
3045    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3046      uInt rows = tmpin[itable]->nrow() ;
3047      uInt freqnrows = tmpin[itable]->frequencies().table().nrow() ;
3048      freqIDCol.attach( tmpin[itable]->table(), "FREQ_ID" ) ;
3049      //ifnoCol.attach( tmpin[itable]->table(), "IFNO" ) ;
3050      for ( uInt irow = 0 ; irow < rows ; irow++ ) {
3051        if ( freqid[itable].size() == freqnrows ) {
3052          break ;
3053        }
3054        else {
3055          uInt id = freqIDCol( irow ) ;
3056          if ( freqid[itable].size() == 0 || count( freqid[itable].begin(), freqid[itable].end(), id ) == 0 ) {
3057            //os << "itable = " << itable << ": IF " << id << " is included in the list" << LogIO::POST ;
3058            vector<double> abcissa = tmpin[itable]->getAbcissa( irow ) ;
3059            double lbedge, rbedge;
3060            freqid[itable].push_back( id ) ;
3061            lbedge = abcissa[0] - 0.5 * ( abcissa[1] - abcissa[0] );
3062            rbedge = abcissa[abcissa.size()-1] + 0.5 * ( abcissa[1] - abcissa[0] );
3063            iffreq[itable].push_back( min(lbedge, rbedge) ) ;
3064            iffreq[itable].push_back( max(lbedge, rbedge) ) ;
3065          }
3066        }
3067      }
3068    }
3069
3070    // debug
3071    //os << "IF settings summary:" << endl ;
3072    //for ( uInt i = 0 ; i < freqid.size() ; i++ ) {
3073    //os << "   Table" << i << endl ;
3074    //for ( uInt j = 0 ; j < freqid[i].size() ; j++ ) {
3075    //os << "      id = " << freqid[i][j] << " (min,max) = (" << iffreq[i][2*j] << "," << iffreq[i][2*j+1] << ")" << endl ;
3076    //}
3077    //}
3078    //os << endl ;
3079    //os.post() ;
3080
3081    // IF grouping based on their frequency coverage
3082    // ifgrp: list of table index and FREQ_ID for all members in each IF group
3083    // ifgfreq: list of minimum and maximum frequency in each IF group
3084    // ifgrp[numgrp][nummember*2]
3085    // ifgrp: [[table00, freqrow00, table01, freqrow01, ...],
3086    //         [table10, freqrow10, table11, freqrow11, ...],
3087    //         ...
3088    //         [tablen0, freqrown0, tablen1, freqrown1, ...]]
3089    // ifgfreq[numgrp*2]
3090    // ifgfreq: [min0_grp0, max0_grp0, min1_grp1, max1_grp1, ...]
3091    //os << "IF grouping based on their frequency coverage" << LogIO::POST ;
3092    vector< vector<uInt> > ifgrp ;
3093    vector<double> ifgfreq ;
3094
3095    // parameter for IF grouping
3096    // groupmode = OR    retrieve all region
3097    //             AND   only retrieve overlaped region
3098    //string groupmode = "AND" ;
3099    string groupmode = "OR" ;
3100    uInt sizecr = 0 ;
3101    if ( groupmode == "AND" )
3102      sizecr = 2 ;
3103    else if ( groupmode == "OR" )
3104      sizecr = 0 ;
3105
3106    vector<double> sortedfreq ;
3107    for ( uInt i = 0 ; i < iffreq.size() ; i++ ) {
3108      for ( uInt j = 0 ; j < iffreq[i].size() ; j++ ) {
3109        if ( count( sortedfreq.begin(), sortedfreq.end(), iffreq[i][j] ) == 0 )
3110          sortedfreq.push_back( iffreq[i][j] ) ;
3111      }
3112    }
3113    sort( sortedfreq.begin(), sortedfreq.end() ) ;
3114    for ( vector<double>::iterator i = sortedfreq.begin() ; i != sortedfreq.end()-1 ; i++ ) {
3115      ifgfreq.push_back( *i ) ;
3116      ifgfreq.push_back( *(i+1) ) ;
3117    }
3118    ifgrp.resize( ifgfreq.size()/2 ) ;
3119    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3120      for ( uInt iif = 0 ; iif < freqid[itable].size() ; iif++ ) {
3121        double range0 = iffreq[itable][2*iif] ;
3122        double range1 = iffreq[itable][2*iif+1] ;
3123        for ( uInt j = 0 ; j < ifgrp.size() ; j++ ) {
3124          double fmin = max( range0, ifgfreq[2*j] ) ;
3125          double fmax = min( range1, ifgfreq[2*j+1] ) ;
3126          if ( fmin < fmax ) {
3127            ifgrp[j].push_back( itable ) ;
3128            ifgrp[j].push_back( freqid[itable][iif] ) ;
3129          }
3130        }
3131      }
3132    }
3133    vector< vector<uInt> >::iterator fiter = ifgrp.begin() ;
3134    vector<double>::iterator giter = ifgfreq.begin() ;
3135    while( fiter != ifgrp.end() ) {
3136      if ( fiter->size() <= sizecr ) {
3137        fiter = ifgrp.erase( fiter ) ;
3138        giter = ifgfreq.erase( giter ) ;
3139        giter = ifgfreq.erase( giter ) ;
3140      }
3141      else {
3142        fiter++ ;
3143        advance( giter, 2 ) ;
3144      }
3145    }
3146
3147    // Grouping continuous IF groups (without frequency gap)
3148    // freqgrp: list of IF group indexes in each frequency group
3149    // freqgrp[numgrp][nummember]
3150    // freqgrp: [[ifgrp00, ifgrp01, ifgrp02, ...],
3151    //           [ifgrp10, ifgrp11, ifgrp12, ...],
3152    //           ...
3153    //           [ifgrpn0, ifgrpn1, ifgrpn2, ...]]
3154    vector< vector<uInt> > freqgrp ;
3155    double freqrange = 0.0 ;
3156    uInt grpnum = 0 ;
3157    for ( uInt i = 0 ; i < ifgrp.size() ; i++ ) {
3158      // Assumed that ifgfreq was sorted
3159      if ( grpnum != 0 && freqrange == ifgfreq[2*i] ) {
3160        freqgrp[grpnum-1].push_back( i ) ;
3161      }
3162      else {
3163        vector<uInt> grp0( 1, i ) ;
3164        freqgrp.push_back( grp0 ) ;
3165        grpnum++ ;
3166      }
3167      freqrange = ifgfreq[2*i+1] ;
3168    }
3169
3170
3171    // print IF groups
3172    ostringstream oss ;
3173    oss << "IF Group summary: " << endl ;
3174    oss << "   GROUP_ID [FREQ_MIN, FREQ_MAX]: (TABLE_ID, FREQ_ID)" << endl ;
3175    for ( uInt i = 0 ; i < ifgrp.size() ; i++ ) {
3176      oss << "   GROUP " << setw( 2 ) << i << " [" << ifgfreq[2*i] << "," << ifgfreq[2*i+1] << "]: " ;
3177      for ( uInt j = 0 ; j < ifgrp[i].size()/2 ; j++ ) {
3178        oss << "(" << ifgrp[i][2*j] << "," << ifgrp[i][2*j+1] << ") " ;
3179      }
3180      oss << endl ;
3181    }
3182    oss << endl ;
3183    os << oss.str() << LogIO::POST ;
3184   
3185    // print frequency group
3186    oss.str("") ;
3187    oss << "Frequency Group summary: " << endl ;
3188    oss << "   GROUP_ID [FREQ_MIN, FREQ_MAX]: IF_GROUP_ID" << endl ;
3189    for ( uInt i = 0 ; i < freqgrp.size() ; i++ ) {
3190      oss << "   GROUP " << setw( 2 ) << i << " [" << ifgfreq[2*freqgrp[i][0]] << "," << ifgfreq[2*freqgrp[i][freqgrp[i].size()-1]+1] << "]: " ;
3191      for ( uInt j = 0 ; j < freqgrp[i].size() ; j++ ) {
3192        oss << freqgrp[i][j] << " " ;
3193      }
3194      oss << endl ;
3195    }
3196    oss << endl ;
3197    os << oss.str() << LogIO::POST ;
3198
3199    // membership check
3200    // groups: list of IF group indexes whose frequency range overlaps with
3201    //         that of each table and IF
3202    // groups[numtable][numIF][nummembership]
3203    // groups: [[[grp, grp,...], [grp, grp,...],...],
3204    //          [[grp, grp,...], [grp, grp,...],...],
3205    //          ...
3206    //          [[grp, grp,...], [grp, grp,...],...]]
3207    vector< vector< vector<uInt> > > groups( insize ) ;
3208    for ( uInt i = 0 ; i < insize ; i++ ) {
3209      groups[i].resize( freqid[i].size() ) ;
3210    }
3211    for ( uInt igrp = 0 ; igrp < ifgrp.size() ; igrp++ ) {
3212      for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) {
3213        uInt tableid = ifgrp[igrp][2*imem] ;
3214        vector<uInt>::iterator iter = find( freqid[tableid].begin(), freqid[tableid].end(), ifgrp[igrp][2*imem+1] ) ;
3215        if ( iter != freqid[tableid].end() ) {
3216          uInt rowid = distance( freqid[tableid].begin(), iter ) ;
3217          groups[tableid][rowid].push_back( igrp ) ;
3218        }
3219      }
3220    }
3221
3222    // print membership
3223    //oss.str("") ;
3224    //for ( uInt i = 0 ; i < insize ; i++ ) {
3225    //oss << "Table " << i << endl ;
3226    //for ( uInt j = 0 ; j < groups[i].size() ; j++ ) {
3227    //oss << "   FREQ_ID " <<  setw( 2 ) << freqid[i][j] << ": " ;
3228    //for ( uInt k = 0 ; k < groups[i][j].size() ; k++ ) {
3229    //oss << setw( 2 ) << groups[i][j][k] << " " ;
3230    //}
3231    //oss << endl ;
3232    //}
3233    //}
3234    //os << oss.str() << LogIO::POST ;
3235
3236    // set back coordinfo
3237    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3238      vector<string> coordinfo = tmpin[itable]->getCoordInfo() ;
3239      coordinfo[0] = oldinfo[itable] ;
3240      tmpin[itable]->setCoordInfo( coordinfo ) ;
3241    }
3242
3243    // Create additional table if needed
3244    bool oldInsitu = insitu_ ;
3245    setInsitu( false ) ;
3246    vector< vector<uInt> > addrow( insize ) ;
3247    vector<uInt> addtable( insize, 0 ) ;
3248    vector<uInt> newtableids( insize ) ;
3249    vector<uInt> newifids( insize, 0 ) ;
3250    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3251      //os << "Table " << itable << ": " ;
3252      for ( uInt ifrow = 0 ; ifrow < groups[itable].size() ; ifrow++ ) {
3253        addrow[itable].push_back( groups[itable][ifrow].size()-1 ) ;
3254        //os << addrow[itable][ifrow] << " " ;
3255      }
3256      addtable[itable] = *max_element( addrow[itable].begin(), addrow[itable].end() ) ;
3257      //os << "(" << addtable[itable] << ")" << LogIO::POST ;
3258    }
3259    newin.resize( insize ) ;
3260    copy( tmpin.begin(), tmpin.end(), newin.begin() ) ;
3261    for ( uInt i = 0 ; i < insize ; i++ ) {
3262      newtableids[i] = i ;
3263    }
3264    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3265      for ( uInt iadd = 0 ; iadd < addtable[itable] ; iadd++ ) {
3266        CountedPtr<Scantable> add = getScantable( newin[itable], false ) ;
3267        vector<int> freqidlist ;
3268        for ( uInt i = 0 ; i < groups[itable].size() ; i++ ) {
3269          if ( groups[itable][i].size() > iadd + 1 ) {
3270            freqidlist.push_back( freqid[itable][i] ) ;
3271          }
3272        }
3273        stringstream taqlstream ;
3274        taqlstream << "SELECT FROM $1 WHERE FREQ_ID IN [" ;
3275        for ( uInt i = 0 ; i < freqidlist.size() ; i++ ) {
3276          taqlstream << freqidlist[i] ;
3277          if ( i < freqidlist.size() - 1 )
3278            taqlstream << "," ;
3279          else
3280            taqlstream << "]" ;
3281        }
3282        string taql = taqlstream.str() ;
3283        //os << "taql = " << taql << LogIO::POST ;
3284        STSelector selector = STSelector() ;
3285        selector.setTaQL( taql ) ;
3286        add->setSelection( selector ) ;
3287        newin.push_back( add ) ;
3288        newtableids.push_back( itable ) ;
3289        newifids.push_back( iadd + 1 ) ;
3290      }
3291    }
3292
3293    // udpate ifgrp
3294    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3295      for ( uInt iadd = 0 ; iadd < addtable[itable] ; iadd++ ) {
3296        for ( uInt ifrow = 0 ; ifrow < groups[itable].size() ; ifrow++ ) {
3297          if ( groups[itable][ifrow].size() > iadd + 1 ) {
3298            uInt igrp = groups[itable][ifrow][iadd+1] ;
3299            for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) {
3300              if ( ifgrp[igrp][2*imem] == newtableids[iadd+insize] && ifgrp[igrp][2*imem+1] == freqid[newtableids[iadd+insize]][ifrow] ) {
3301                ifgrp[igrp][2*imem] = insize + iadd ;
3302              }
3303            }
3304          }
3305        }
3306      }
3307    }
3308
3309    // print IF groups again for debug
3310    //oss.str( "" ) ;
3311    //oss << "IF Group summary: " << endl ;
3312    //oss << "   GROUP_ID [FREQ_MIN, FREQ_MAX]: (TABLE_ID, FREQ_ID)" << endl ;
3313    //for ( uInt i = 0 ; i < ifgrp.size() ; i++ ) {
3314    //oss << "   GROUP " << setw( 2 ) << i << " [" << ifgfreq[2*i] << "," << ifgfreq[2*i+1] << "]: " ;
3315    //for ( uInt j = 0 ; j < ifgrp[i].size()/2 ; j++ ) {
3316    //oss << "(" << ifgrp[i][2*j] << "," << ifgrp[i][2*j+1] << ") " ;
3317    //}
3318    //oss << endl ;
3319    //}
3320    //oss << endl ;
3321    //os << oss.str() << LogIO::POST ;
3322
3323    // reset SCANNO and IFNO/FREQ_ID: IF is reset by the result of sortation
3324    os << "All scan number is set to 0" << LogIO::POST ;
3325    //os << "All IF number is set to IF group index" << LogIO::POST ;
3326    insize = newin.size() ;
3327    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3328      uInt rows = newin[itable]->nrow() ;
3329      Table &tmpt = newin[itable]->table() ;
3330      freqIDCol.attach( tmpt, "FREQ_ID" ) ;
3331      scannoCol.attach( tmpt, "SCANNO" ) ;
3332      ifnoCol.attach( tmpt, "IFNO" ) ;
3333      for ( uInt irow=0 ; irow < rows ; irow++ ) {
3334        scannoCol.put( irow, 0 ) ;
3335        uInt freqID = freqIDCol( irow ) ;
3336        vector<uInt>::iterator iter = find( freqid[newtableids[itable]].begin(), freqid[newtableids[itable]].end(), freqID ) ;
3337        if ( iter != freqid[newtableids[itable]].end() ) {
3338          uInt index = distance( freqid[newtableids[itable]].begin(), iter ) ;
3339          ifnoCol.put( irow, groups[newtableids[itable]][index][newifids[itable]] ) ;
3340        }
3341        else {
3342          throw(AipsError("IF grouping was wrong in additional tables.")) ;
3343        }
3344      }
3345    }
3346    oldinfo.resize( insize ) ;
3347    setInsitu( oldInsitu ) ;
3348
3349    // temporarily set coordinfo
3350    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3351      vector<string> coordinfo = newin[itable]->getCoordInfo() ;
3352      oldinfo[itable] = coordinfo[0] ;
3353      coordinfo[0] = "Hz" ;
3354      newin[itable]->setCoordInfo( coordinfo ) ;
3355    }
3356
3357    // save column values in the vector
3358    vector< vector<uInt> > freqIdVec( insize ) ;
3359    vector< vector<uInt> > ifNoVec( insize ) ;
3360    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3361      ifnoCol.attach( newin[itable]->table(), "IFNO" ) ;
3362      freqIDCol.attach( newin[itable]->table(), "FREQ_ID" ) ;
3363      for ( uInt irow = 0 ; irow < newin[itable]->table().nrow() ; irow++ ) {
3364        freqIdVec[itable].push_back( freqIDCol( irow ) ) ;
3365        ifNoVec[itable].push_back( ifnoCol( irow ) ) ;
3366      }
3367    }
3368
3369    // reset spectra and flagtra: pick up common part of frequency coverage
3370    //os << "Pick common frequency range and align resolution" << LogIO::POST ;
3371    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3372      uInt rows = newin[itable]->nrow() ;
3373      int nminchan = -1 ;
3374      int nmaxchan = -1 ;
3375      vector<uInt> freqIdUpdate ;
3376      for ( uInt irow = 0 ; irow < rows ; irow++ ) {
3377        uInt ifno = ifNoVec[itable][irow] ;  // IFNO is reset by group index (IF group index)
3378        double minfreq = ifgfreq[2*ifno] ;
3379        double maxfreq = ifgfreq[2*ifno+1] ;
3380        //os << "frequency range: [" << minfreq << "," << maxfreq << "]" << LogIO::POST ;
3381        vector<double> abcissa = newin[itable]->getAbcissa( irow ) ;
3382        int nchan = abcissa.size() ;
3383        double resol = abcissa[1] - abcissa[0] ;
3384        //os << "abcissa range  : [" << abcissa[0] << "," << abcissa[nchan-1] << "]" << LogIO::POST ;
3385        uInt imin, imax;
3386        int sigres;
3387        if ( resol >= 0. ) {
3388          imin = 0;
3389          imax = nchan - 1 ;
3390          sigres = 1 ;
3391        } else {
3392          imin = nchan - 1 ;
3393          imax = 0 ;
3394          sigres = -1 ;
3395          resol = abs(resol) ;
3396        }
3397        if ( minfreq <= abcissa[imin] )
3398          nminchan = imin ;
3399        else {
3400          //double cfreq = ( minfreq - abcissa[0] ) / resol ;
3401          double cfreq = ( minfreq - abcissa[imin] + 0.5 * resol ) / resol ;
3402          nminchan = imin + sigres * (int(cfreq) + ( ( cfreq - int(cfreq) <= 0.5 ) ? 0 : 1 )) ;
3403        }
3404        if ( maxfreq >= abcissa[imax] )
3405          nmaxchan = imax;
3406        else {
3407          //double cfreq = ( abcissa[abcissa.size()-1] - maxfreq ) / resol ;
3408          double cfreq = ( abcissa[imax] - maxfreq + 0.5 * resol ) / resol ;
3409          nmaxchan = imax - sigres * (int(cfreq) +( ( cfreq - int(cfreq) >= 0.5 ) ? 1 : 0 )) ;
3410        }
3411        //os << "channel range (" << irow << "): [" << nminchan << "," << nmaxchan << "]" << LogIO::POST ;
3412        if ( nmaxchan < nminchan ) {
3413          int tmp = nmaxchan ;
3414          nmaxchan = nminchan ;
3415          nminchan = tmp ;
3416        }
3417        if ( nmaxchan > nminchan ) {
3418          newin[itable]->reshapeSpectrum( nminchan, nmaxchan, irow ) ;
3419          int newchan = nmaxchan - nminchan + 1 ;
3420          if ( count( freqIdUpdate.begin(), freqIdUpdate.end(), freqIdVec[itable][irow] ) == 0 && newchan < nchan ) {
3421            freqIdUpdate.push_back( freqIdVec[itable][irow] ) ;
3422
3423            // Update before nminchan is lost
3424            uInt freqId = freqIdVec[itable][irow] ;
3425            Double refpix ;
3426            Double refval ;
3427            Double increment ;
3428            newin[itable]->frequencies().getEntry( refpix, refval, increment, freqId ) ;
3429            //refval = refval - ( refpix - nminchan ) * increment ;
3430            refval = abcissa[nminchan] ;
3431            refpix = 0 ;
3432            newin[itable]->frequencies().setEntry( refpix, refval, increment, freqId ) ;
3433          }
3434        }
3435        else {
3436          throw(AipsError("Failed to pick up common part of frequency range.")) ;
3437        }
3438      }
3439//       for ( uInt i = 0 ; i < freqIdUpdate.size() ; i++ ) {
3440//      uInt freqId = freqIdUpdate[i] ;
3441//      Double refpix ;
3442//      Double refval ;
3443//      Double increment ;
3444       
3445//      // update row
3446//      newin[itable]->frequencies().getEntry( refpix, refval, increment, freqId ) ;
3447//      refval = refval - ( refpix - nminchan ) * increment ;
3448//      refpix = 0 ;
3449//      newin[itable]->frequencies().setEntry( refpix, refval, increment, freqId ) ;
3450//       }   
3451    }
3452
3453   
3454    // reset spectra and flagtra: align spectral resolution
3455    //os << "Align spectral resolution" << LogIO::POST ;
3456    // gmaxdnu: the coarsest frequency resolution in the frequency group
3457    // gmemid: member index that have a resolution equal to gmaxdnu
3458    // gmaxdnu[numfreqgrp]
3459    // gmaxdnu: [dnu0, dnu1, ...]
3460    // gmemid[numfreqgrp]
3461    // gmemid: [id0, id1, ...]
3462    vector<double> gmaxdnu( freqgrp.size(), 0.0 ) ;
3463    vector<uInt> gmemid( freqgrp.size(), 0 ) ;
3464    for ( uInt igrp = 0 ; igrp < ifgrp.size() ; igrp++ ) {
3465      double maxdnu = 0.0 ;       // maximum (coarsest) frequency resolution
3466      int minchan = INT_MAX ;     // minimum channel number
3467      Double refpixref = -1 ;     // reference of 'reference pixel'
3468      Double refvalref = -1 ;     // reference of 'reference frequency'
3469      Double refinc = -1 ;        // reference frequency resolution
3470      uInt refreqid ;
3471      uInt reftable = INT_MAX;
3472      // process only if group member > 1
3473      if ( ifgrp[igrp].size() > 2 ) {
3474        // find minchan and maxdnu in each group
3475        for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) {
3476          uInt tableid = ifgrp[igrp][2*imem] ;
3477          uInt rowid = ifgrp[igrp][2*imem+1] ;
3478          vector<uInt>::iterator iter = find( freqIdVec[tableid].begin(), freqIdVec[tableid].end(), rowid ) ;
3479          if ( iter != freqIdVec[tableid].end() ) {
3480            uInt index = distance( freqIdVec[tableid].begin(), iter ) ;
3481            vector<double> abcissa = newin[tableid]->getAbcissa( index ) ;
3482            int nchan = abcissa.size() ;
3483            double dnu = abcissa[1] - abcissa[0] ;
3484            //os << "GROUP " << igrp << " (" << tableid << "," << rowid << "): nchan = " << nchan << " (minchan = " << minchan << ")" << LogIO::POST ;
3485            if ( nchan < minchan ) {
3486              minchan = nchan ;
3487              maxdnu = abs(dnu) ;
3488              newin[tableid]->frequencies().getEntry( refpixref, refvalref, refinc, rowid ) ;
3489              refreqid = rowid ;
3490              reftable = tableid ;
3491              // Spectra are reversed when dnu < 0
3492              if (dnu < 0)
3493                refpixref = minchan - 1 -refpixref ;
3494            }
3495          }
3496        }
3497        // regrid spectra in each group
3498        os << "GROUP " << igrp << endl ;
3499        os << "   Channel number is adjusted to " << minchan << endl ;
3500        os << "   Corresponding frequency resolution is " << maxdnu << "Hz" << LogIO::POST ;
3501        for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) {
3502          uInt tableid = ifgrp[igrp][2*imem] ;
3503          uInt rowid = ifgrp[igrp][2*imem+1] ;
3504          freqIDCol.attach( newin[tableid]->table(), "FREQ_ID" ) ;
3505          //os << "tableid = " << tableid << " rowid = " << rowid << ": " << LogIO::POST ;
3506          //os << "   regridChannel applied to " ;
3507          //if ( tableid != reftable )
3508          refreqid = newin[tableid]->frequencies().addEntry( refpixref, refvalref, maxdnu ) ;
3509          for ( uInt irow = 0 ; irow < newin[tableid]->table().nrow() ; irow++ ) {
3510            uInt tfreqid = freqIdVec[tableid][irow] ;
3511            if ( tfreqid == rowid ) {     
3512              //os << irow << " " ;
3513              newin[tableid]->regridChannel( minchan, maxdnu, irow ) ;
3514              freqIDCol.put( irow, refreqid ) ;
3515              freqIdVec[tableid][irow] = refreqid ;
3516            }
3517          }
3518          //os << LogIO::POST ;
3519        }
3520      }
3521      else {
3522        uInt tableid = ifgrp[igrp][0] ;
3523        uInt rowid = ifgrp[igrp][1] ;
3524        vector<uInt>::iterator iter = find( freqIdVec[tableid].begin(), freqIdVec[tableid].end(), rowid ) ;
3525        if ( iter != freqIdVec[tableid].end() ) {
3526          uInt index = distance( freqIdVec[tableid].begin(), iter ) ;
3527          vector<double> abcissa = newin[tableid]->getAbcissa( index ) ;
3528          minchan = abcissa.size() ;
3529          maxdnu = abs( abcissa[1] - abcissa[0]) ;
3530        }
3531      }
3532      for ( uInt i = 0 ; i < freqgrp.size() ; i++ ) {
3533        if ( count( freqgrp[i].begin(), freqgrp[i].end(), igrp ) > 0 ) {
3534          if ( maxdnu > gmaxdnu[i] ) {
3535            gmaxdnu[i] = maxdnu ;
3536            gmemid[i] = igrp ;
3537          }
3538          break ;
3539        }
3540      }
3541    }
3542
3543    // set back coordinfo
3544    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
3545      vector<string> coordinfo = newin[itable]->getCoordInfo() ;
3546      coordinfo[0] = oldinfo[itable] ;
3547      newin[itable]->setCoordInfo( coordinfo ) ;
3548    }     
3549
3550    // accumulate all rows into the first table
3551    // NOTE: assumed in.size() = 1
3552    vector< CountedPtr<Scantable> > tmp( 1 ) ;
3553    if ( newin.size() == 1 )
3554      tmp[0] = newin[0] ;
3555    else
3556      tmp[0] = merge( newin ) ;
3557
3558    //return tmp[0] ;
3559
3560    // average
3561    CountedPtr<Scantable> tmpout = average( tmp, mask, weight, avmode ) ;
3562
3563    //return tmpout ;
3564
3565    // combine frequency group
3566    os << "Combine spectra based on frequency grouping" << LogIO::POST ;
3567    os << "IFNO is renumbered as frequency group ID (see above)" << LogIO::POST ;
3568    vector<string> coordinfo = tmpout->getCoordInfo() ;
3569    oldinfo[0] = coordinfo[0] ;
3570    coordinfo[0] = "Hz" ;
3571    tmpout->setCoordInfo( coordinfo ) ;
3572    // create proformas of output table
3573    stringstream taqlstream ;
3574    taqlstream << "SELECT FROM $1 WHERE IFNO IN [" ;
3575    for ( uInt i = 0 ; i < gmemid.size() ; i++ ) {
3576      taqlstream << gmemid[i] ;
3577      if ( i < gmemid.size() - 1 )
3578        taqlstream << "," ;
3579      else
3580        taqlstream << "]" ;
3581    }
3582    string taql = taqlstream.str() ;
3583    //os << "taql = " << taql << LogIO::POST ;
3584    STSelector selector = STSelector() ;
3585    selector.setTaQL( taql ) ;
3586    oldInsitu = insitu_ ;
3587    setInsitu( false ) ;
3588    out = getScantable( tmpout, false ) ;
3589    setInsitu( oldInsitu ) ;
3590    out->setSelection( selector ) ;
3591    // regrid rows
3592    ifnoCol.attach( tmpout->table(), "IFNO" ) ;
3593    for ( uInt irow = 0 ; irow < tmpout->table().nrow() ; irow++ ) {
3594      uInt ifno = ifnoCol( irow ) ;
3595      for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) {
3596        if ( count( freqgrp[igrp].begin(), freqgrp[igrp].end(), ifno ) > 0 ) {
3597          vector<double> abcissa = tmpout->getAbcissa( irow ) ;
3598          double bw = ( abcissa[1] - abcissa[0] ) * abcissa.size() ;
3599          int nchan = (int) abs( bw / gmaxdnu[igrp] ) ;
3600          // All spectra will have positive frequency increments
3601          tmpout->regridChannel( nchan, gmaxdnu[igrp], irow ) ;
3602          break ;
3603        }
3604      }
3605    }
3606    // combine spectra
3607    ArrayColumn<Float> specColOut ;
3608    specColOut.attach( out->table(), "SPECTRA" ) ;
3609    ArrayColumn<uChar> flagColOut ;
3610    flagColOut.attach( out->table(), "FLAGTRA" ) ;
3611    ScalarColumn<uInt> ifnoColOut ;
3612    ifnoColOut.attach( out->table(), "IFNO" ) ;
3613    ScalarColumn<uInt> polnoColOut ;
3614    polnoColOut.attach( out->table(), "POLNO" ) ;
3615    ScalarColumn<uInt> freqidColOut ;
3616    freqidColOut.attach( out->table(), "FREQ_ID" ) ;
3617//     MDirection::ScalarColumn dirColOut ;
3618//     dirColOut.attach( out->table(), "DIRECTION" ) ;
3619    Table &tab = tmpout->table() ;
3620    Block<String> cols(1);
3621    cols[0] = String("POLNO") ;
3622    TableIterator iter( tab, cols ) ;
3623    vector< vector<uInt> > sizes( freqgrp.size() ) ;
3624    while( !iter.pastEnd() ) {
3625      vector< vector<Float> > specout( freqgrp.size() ) ;
3626      vector< vector<uChar> > flagout( freqgrp.size() ) ;
3627      ArrayColumn<Float> specCols ;
3628      specCols.attach( iter.table(), "SPECTRA" ) ;
3629      ArrayColumn<uChar> flagCols ;
3630      flagCols.attach( iter.table(), "FLAGTRA" ) ;
3631      ifnoCol.attach( iter.table(), "IFNO" ) ;
3632      ScalarColumn<uInt> polnos ;
3633      polnos.attach( iter.table(), "POLNO" ) ;
3634//       MDirection::ScalarColumn dircol ;
3635//       dircol.attach( iter.table(), "DIRECTION" ) ;
3636      uInt polno = polnos( 0 ) ;
3637      //os << "POLNO iteration: " << polno << LogIO::POST ;
3638//       for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) {
3639//      sizes[igrp].resize( freqgrp[igrp].size() ) ;
3640//      for ( uInt imem = 0 ; imem < freqgrp[igrp].size() ; imem++ ) {
3641//        for ( uInt irow = 0 ; irow < iter.table().nrow() ; irow++ ) {
3642//          uInt ifno = ifnoCol( irow ) ;
3643//          if ( ifno == freqgrp[igrp][imem] ) {
3644//            Vector<Float> spec = specCols( irow ) ;
3645//            Vector<uChar> flag = flagCols( irow ) ;
3646//            vector<Float> svec ;
3647//            spec.tovector( svec ) ;
3648//            vector<uChar> fvec ;
3649//            flag.tovector( fvec ) ;
3650//            //os << "spec.size() = " << svec.size() << " fvec.size() = " << fvec.size() << LogIO::POST ;
3651//            specout[igrp].insert( specout[igrp].end(), svec.begin(), svec.end() ) ;
3652//            flagout[igrp].insert( flagout[igrp].end(), fvec.begin(), fvec.end() ) ;
3653//            //os << "specout[" << igrp << "].size() = " << specout[igrp].size() << LogIO::POST ;
3654//            sizes[igrp][imem] = spec.nelements() ;
3655//          }
3656//        }
3657//      }
3658//      for ( uInt irow = 0 ; irow < out->table().nrow() ; irow++ ) {
3659//        uInt ifout = ifnoColOut( irow ) ;
3660//        uInt polout = polnoColOut( irow ) ;
3661//        if ( ifout == gmemid[igrp] && polout == polno ) {
3662//          // set SPECTRA and FRAGTRA
3663//          Vector<Float> newspec( specout[igrp] ) ;
3664//          Vector<uChar> newflag( flagout[igrp] ) ;
3665//          specColOut.put( irow, newspec ) ;
3666//          flagColOut.put( irow, newflag ) ;
3667//          // IFNO renumbering
3668//          ifnoColOut.put( irow, igrp ) ;
3669//        }
3670//      }
3671//       }
3672      // get a list of number of channels for each frequency group member
3673      for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) {
3674        sizes[igrp].resize( freqgrp[igrp].size() ) ;
3675        for ( uInt imem = 0 ; imem < freqgrp[igrp].size() ; imem++ ) {
3676          for ( uInt irow = 0 ; irow < iter.table().nrow() ; irow++ ) {
3677            uInt ifno = ifnoCol( irow ) ;
3678            if ( ifno == freqgrp[igrp][imem] ) {
3679              Vector<Float> spec = specCols( irow ) ;
3680              sizes[igrp][imem] = spec.nelements() ;
3681              break ;
3682            }
3683          }
3684        }
3685      }
3686      // combine spectra
3687      for ( uInt irow = 0 ; irow < out->table().nrow() ; irow++ ) {
3688        uInt polout = polnoColOut( irow ) ;
3689        if ( polout == polno ) {
3690          uInt ifout = ifnoColOut( irow ) ;
3691//           Vector<Double> direction = dirColOut(irow).getAngle(Unit(String("rad"))).getValue() ;
3692          uInt igrp ;
3693          for ( uInt jgrp = 0 ; jgrp < freqgrp.size() ; jgrp++ ) {
3694            if ( ifout == gmemid[jgrp] ) {
3695              igrp = jgrp ;
3696              break ;
3697            }
3698          }
3699          for ( uInt imem = 0 ; imem < freqgrp[igrp].size() ; imem++ ) {
3700            for ( uInt jrow = 0 ; jrow < iter.table().nrow() ; jrow++ ) {
3701              uInt ifno = ifnoCol( jrow ) ;
3702              // 2012/02/17 TN
3703              // Since STGrid is implemented, average doesn't consider direction
3704              // when accumulating
3705//               Vector<Double> tdir = dircol(jrow).getAngle(Unit(String("rad"))).getValue() ;
3706//               //if ( ifno == freqgrp[igrp][imem] && allTrue( tdir == direction  ) ) {
3707//               Double dx = tdir[0] - direction[0] ;
3708//               Double dy = tdir[1] - direction[1] ;
3709//               Double dd = sqrt( dx * dx + dy * dy ) ;
3710              //if ( ifno == freqgrp[igrp][imem] && allNearAbs( tdir, direction, tol ) ) {
3711//               if ( ifno == freqgrp[igrp][imem] && dd <= tol ) {
3712              if ( ifno == freqgrp[igrp][imem] ) {
3713                Vector<Float> spec = specCols( jrow ) ;
3714                Vector<uChar> flag = flagCols( jrow ) ;
3715                vector<Float> svec ;
3716                spec.tovector( svec ) ;
3717                vector<uChar> fvec ;
3718                flag.tovector( fvec ) ;
3719                //os << "spec.size() = " << svec.size() << " fvec.size() = " << fvec.size() << LogIO::POST ;
3720                specout[igrp].insert( specout[igrp].end(), svec.begin(), svec.end() ) ;
3721                flagout[igrp].insert( flagout[igrp].end(), fvec.begin(), fvec.end() ) ;
3722                //os << "specout[" << igrp << "].size() = " << specout[igrp].size() << LogIO::POST ;
3723              }
3724            }
3725          }
3726          // set SPECTRA and FRAGTRA
3727          Vector<Float> newspec( specout[igrp] ) ;
3728          Vector<uChar> newflag( flagout[igrp] ) ;
3729          specColOut.put( irow, newspec ) ;
3730          flagColOut.put( irow, newflag ) ;
3731          // IFNO renumbering (renumbered as frequency group ID)
3732          ifnoColOut.put( irow, igrp ) ;
3733        }
3734      }
3735      iter++ ;
3736    }
3737    // update FREQUENCIES subtable
3738    vector<bool> updated( freqgrp.size(), false ) ;
3739    for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) {
3740      uInt index = 0 ;
3741      uInt pixShift = 0 ;
3742
3743      while ( freqgrp[igrp][index] != gmemid[igrp] ) {
3744        pixShift += sizes[igrp][index++] ;
3745      }
3746      for ( uInt irow = 0 ; irow < out->table().nrow() ; irow++ ) {
3747        //if ( ifnoColOut( irow ) == gmemid[igrp] && !updated[igrp] ) {
3748        if ( ifnoColOut( irow ) == igrp && !updated[igrp] ) {
3749          uInt freqidOut = freqidColOut( irow ) ;
3750          //os << "freqgrp " << igrp << " freqidOut = " << freqidOut << LogIO::POST ;
3751          double refpix ;
3752          double refval ;
3753          double increm ;
3754          out->frequencies().getEntry( refpix, refval, increm, freqidOut ) ;
3755          if (increm < 0)
3756            refpix = sizes[igrp][index] - 1 - refpix ; // reversed
3757          refpix += pixShift ;
3758          out->frequencies().setEntry( refpix, refval, gmaxdnu[igrp], freqidOut ) ;
3759          updated[igrp] = true ;
3760        }
3761      }
3762    }
3763
3764    //out = tmpout ;
3765
3766    coordinfo = tmpout->getCoordInfo() ;
3767    coordinfo[0] = oldinfo[0] ;
3768    tmpout->setCoordInfo( coordinfo ) ;
3769  }
3770  else {
3771    // simple average
3772    out =  average( in, mask, weight, avmode ) ;
3773  }
3774 
3775  return out;
3776}
3777
3778CountedPtr<Scantable> STMath::cwcal( const CountedPtr<Scantable>& s,
3779                                     const String calmode,
3780                                     const String antname )
3781{
3782  // frequency switch
3783  if ( calmode == "fs" ) {
3784    return cwcalfs( s, antname ) ;
3785  }
3786  else {
3787    vector<bool> masks = s->getMask( 0 ) ;
3788    vector<int> types ;
3789
3790    // sky scan
3791    STSelector sel = STSelector() ;
3792    types.push_back( SrcType::SKY ) ;
3793    sel.setTypes( types ) ;
3794    s->setSelection( sel ) ;
3795    vector< CountedPtr<Scantable> > tmp( 1, getScantable( s, false ) ) ;
3796    CountedPtr<Scantable> asky = average( tmp, masks, "TINT", "SCAN" ) ;
3797    s->unsetSelection() ;
3798    sel.reset() ;
3799    types.clear() ;
3800
3801    // hot scan
3802    types.push_back( SrcType::HOT ) ;
3803    sel.setTypes( types ) ;
3804    s->setSelection( sel ) ;
3805    tmp.clear() ;
3806    tmp.push_back( getScantable( s, false ) ) ;
3807    CountedPtr<Scantable> ahot = average( tmp, masks, "TINT", "SCAN" ) ;
3808    s->unsetSelection() ;
3809    sel.reset() ;
3810    types.clear() ;
3811   
3812    // cold scan
3813    CountedPtr<Scantable> acold ;
3814//     types.push_back( SrcType::COLD ) ;
3815//     sel.setTypes( types ) ;
3816//     s->setSelection( sel ) ;
3817//     tmp.clear() ;
3818//     tmp.push_back( getScantable( s, false ) ) ;
3819//     CountedPtr<Scantable> acold = average( tmp, masks, "TINT", "SCNAN" ) ;
3820//     s->unsetSelection() ;
3821//     sel.reset() ;
3822//     types.clear() ;
3823
3824    // off scan
3825    types.push_back( SrcType::PSOFF ) ;
3826    sel.setTypes( types ) ;
3827    s->setSelection( sel ) ;
3828    tmp.clear() ;
3829    tmp.push_back( getScantable( s, false ) ) ;
3830    CountedPtr<Scantable> aoff = average( tmp, masks, "TINT", "SCAN" ) ;
3831    s->unsetSelection() ;
3832    sel.reset() ;
3833    types.clear() ;
3834   
3835    // on scan
3836    bool insitu = insitu_ ;
3837    insitu_ = false ;
3838    CountedPtr<Scantable> out = getScantable( s, true ) ;
3839    insitu_ = insitu ;
3840    types.push_back( SrcType::PSON ) ;
3841    sel.setTypes( types ) ;
3842    s->setSelection( sel ) ;
3843    TableCopy::copyRows( out->table(), s->table() ) ;
3844    s->unsetSelection() ;
3845    sel.reset() ;
3846    types.clear() ;
3847   
3848    // process each on scan
3849    ArrayColumn<Float> tsysCol ;
3850    tsysCol.attach( out->table(), "TSYS" ) ;
3851    for ( int i = 0 ; i < out->nrow() ; i++ ) {
3852      vector<float> sp = getCalibratedSpectra( out, aoff, asky, ahot, acold, i, antname ) ;
3853      out->setSpectrum( sp, i ) ;
3854      string reftime = out->getTime( i ) ;
3855      vector<int> ii( 1, out->getIF( i ) ) ;
3856      vector<int> ib( 1, out->getBeam( i ) ) ;
3857      vector<int> ip( 1, out->getPol( i ) ) ;
3858      sel.setIFs( ii ) ;
3859      sel.setBeams( ib ) ;
3860      sel.setPolarizations( ip ) ;
3861      asky->setSelection( sel ) ;   
3862      vector<float> sptsys = getTsysFromTime( reftime, asky, "linear" ) ;
3863      const Vector<Float> Vtsys( sptsys ) ;
3864      tsysCol.put( i, Vtsys ) ;
3865      asky->unsetSelection() ;
3866      sel.reset() ;
3867    }
3868
3869    // flux unit
3870    out->setFluxUnit( "K" ) ;
3871
3872    return out ;
3873  }
3874}
3875 
3876CountedPtr<Scantable> STMath::almacal( const CountedPtr<Scantable>& s,
3877                                       const String calmode )
3878{
3879  // frequency switch
3880  if ( calmode == "fs" ) {
3881    return almacalfs( s ) ;
3882  }
3883  else {
3884    vector<bool> masks = s->getMask( 0 ) ;
3885   
3886    // off scan
3887    STSelector sel = STSelector() ;
3888    vector<int> types ;
3889    types.push_back( SrcType::PSOFF ) ;
3890    sel.setTypes( types ) ;
3891    s->setSelection( sel ) ;
3892    // TODO 2010/01/08 TN
3893    // Grouping by time should be needed before averaging.
3894    // Each group must have own unique SCANNO (should be renumbered).
3895    // See PIPELINE/SDCalibration.py
3896    CountedPtr<Scantable> soff = getScantable( s, false ) ;
3897    Table ttab = soff->table() ;
3898    ROScalarColumn<Double> timeCol( ttab, "TIME" ) ;
3899    uInt nrow = timeCol.nrow() ;
3900    Vector<Double> timeSep( nrow - 1 ) ;
3901    for ( uInt i = 0 ; i < nrow - 1 ; i++ ) {
3902      timeSep[i] = timeCol(i+1) - timeCol(i) ;
3903    }
3904    ScalarColumn<Double> intervalCol( ttab, "INTERVAL" ) ;
3905    Vector<Double> interval = intervalCol.getColumn() ;
3906    interval /= 86400.0 ;
3907    ScalarColumn<uInt> scanCol( ttab, "SCANNO" ) ;
3908    vector<uInt> glist ;
3909    for ( uInt i = 0 ; i < nrow - 1 ; i++ ) {
3910      double gap = 2.0 * timeSep[i] / ( interval[i] + interval[i+1] ) ;
3911      //cout << "gap[" << i << "]=" << setw(5) << gap << endl ;
3912      if ( gap > 1.1 ) {
3913        glist.push_back( i ) ;
3914      }
3915    }
3916    Vector<uInt> gaplist( glist ) ;
3917    //cout << "gaplist = " << gaplist << endl ;
3918    uInt newid = 0 ;
3919    for ( uInt i = 0 ; i < nrow ; i++ ) {
3920      scanCol.put( i, newid ) ;
3921      if ( i == gaplist[newid] ) {
3922        newid++ ;
3923      }
3924    }
3925    //cout << "new scancol = " << scanCol.getColumn() << endl ;
3926    vector< CountedPtr<Scantable> > tmp( 1, soff ) ;
3927    CountedPtr<Scantable> aoff = average( tmp, masks, "TINT", "SCAN" ) ;
3928    //cout << "aoff.nrow = " << aoff->nrow() << endl ;
3929    s->unsetSelection() ;
3930    sel.reset() ;
3931    types.clear() ;
3932   
3933    // on scan
3934    bool insitu = insitu_ ;
3935    insitu_ = false ;
3936    CountedPtr<Scantable> out = getScantable( s, true ) ;
3937    insitu_ = insitu ;
3938    types.push_back( SrcType::PSON ) ;
3939    sel.setTypes( types ) ;
3940    s->setSelection( sel ) ;
3941    TableCopy::copyRows( out->table(), s->table() ) ;
3942    s->unsetSelection() ;
3943    sel.reset() ;
3944    types.clear() ;
3945   
3946    // process each on scan
3947    ArrayColumn<Float> tsysCol ;
3948    tsysCol.attach( out->table(), "TSYS" ) ;
3949    for ( int i = 0 ; i < out->nrow() ; i++ ) {
3950      vector<float> sp = getCalibratedSpectra( out, aoff, i ) ;
3951      out->setSpectrum( sp, i ) ;
3952    }
3953
3954    // flux unit
3955    out->setFluxUnit( "K" ) ;
3956
3957    return out ;
3958  }
3959}
3960
3961CountedPtr<Scantable> STMath::cwcalfs( const CountedPtr<Scantable>& s,
3962                                       const String antname )
3963{
3964  vector<int> types ;
3965
3966  // APEX calibration mode
3967  int apexcalmode = 1 ;
3968 
3969  if ( antname.find( "APEX" ) != string::npos ) {
3970    // check if off scan exists or not
3971    STSelector sel = STSelector() ;
3972    //sel.setName( offstr1 ) ;
3973    types.push_back( SrcType::FLOOFF ) ;
3974    sel.setTypes( types ) ;
3975    try {
3976      s->setSelection( sel ) ;
3977    }
3978    catch ( AipsError &e ) {
3979      apexcalmode = 0 ;
3980    }
3981    sel.reset() ;
3982  }
3983  s->unsetSelection() ;
3984  types.clear() ;
3985
3986  vector<bool> masks = s->getMask( 0 ) ;
3987  CountedPtr<Scantable> ssig, sref ;
3988  CountedPtr<Scantable> out ;
3989
3990  if ( antname.find( "APEX" ) != string::npos ) {
3991    // APEX calibration
3992    // sky scan
3993    STSelector sel = STSelector() ;
3994    types.push_back( SrcType::FLOSKY ) ;
3995    sel.setTypes( types ) ;
3996    s->setSelection( sel ) ;
3997    vector< CountedPtr<Scantable> > tmp( 1, getScantable( s, false ) ) ;
3998    CountedPtr<Scantable> askylo = average( tmp, masks, "TINT", "SCAN" ) ;
3999    s->unsetSelection() ;
4000    sel.reset() ;
4001    types.clear() ;
4002    types.push_back( SrcType::FHISKY ) ;
4003    sel.setTypes( types ) ;
4004    s->setSelection( sel ) ;
4005    tmp.clear() ;
4006    tmp.push_back( getScantable( s, false ) ) ;
4007    CountedPtr<Scantable> askyhi = average( tmp, masks, "TINT", "SCAN" ) ;
4008    s->unsetSelection() ;
4009    sel.reset() ;
4010    types.clear() ;
4011   
4012    // hot scan
4013    types.push_back( SrcType::FLOHOT ) ;
4014    sel.setTypes( types ) ;
4015    s->setSelection( sel ) ;
4016    tmp.clear() ;
4017    tmp.push_back( getScantable( s, false ) ) ;
4018    CountedPtr<Scantable> ahotlo = average( tmp, masks, "TINT", "SCAN" ) ;
4019    s->unsetSelection() ;
4020    sel.reset() ;
4021    types.clear() ;
4022    types.push_back( SrcType::FHIHOT ) ;
4023    sel.setTypes( types ) ;
4024    s->setSelection( sel ) ;
4025    tmp.clear() ;
4026    tmp.push_back( getScantable( s, false ) ) ;
4027    CountedPtr<Scantable> ahothi = average( tmp, masks, "TINT", "SCAN" ) ;
4028    s->unsetSelection() ;
4029    sel.reset() ;
4030    types.clear() ;
4031   
4032    // cold scan
4033    CountedPtr<Scantable> acoldlo, acoldhi ;
4034//     types.push_back( SrcType::FLOCOLD ) ;
4035//     sel.setTypes( types ) ;
4036//     s->setSelection( sel ) ;
4037//     tmp.clear() ;
4038//     tmp.push_back( getScantable( s, false ) ) ;
4039//     CountedPtr<Scantable> acoldlo = average( tmp, masks, "TINT", "SCAN" ) ;
4040//     s->unsetSelection() ;
4041//     sel.reset() ;
4042//     types.clear() ;
4043//     types.push_back( SrcType::FHICOLD ) ;
4044//     sel.setTypes( types ) ;
4045//     s->setSelection( sel ) ;
4046//     tmp.clear() ;
4047//     tmp.push_back( getScantable( s, false ) ) ;
4048//     CountedPtr<Scantable> acoldhi = average( tmp, masks, "TINT", "SCAN" ) ;
4049//     s->unsetSelection() ;
4050//     sel.reset() ;
4051//     types.clear() ;
4052
4053    // ref scan
4054    bool insitu = insitu_ ;
4055    insitu_ = false ;
4056    sref = getScantable( s, true ) ;
4057    insitu_ = insitu ;
4058    types.push_back( SrcType::FSLO ) ;
4059    sel.setTypes( types ) ;
4060    s->setSelection( sel ) ;
4061    TableCopy::copyRows( sref->table(), s->table() ) ;
4062    s->unsetSelection() ;
4063    sel.reset() ;
4064    types.clear() ;
4065   
4066    // sig scan
4067    insitu_ = false ;
4068    ssig = getScantable( s, true ) ;
4069    insitu_ = insitu ;
4070    types.push_back( SrcType::FSHI ) ;
4071    sel.setTypes( types ) ;
4072    s->setSelection( sel ) ;
4073    TableCopy::copyRows( ssig->table(), s->table() ) ;
4074    s->unsetSelection() ;
4075    sel.reset() ; 
4076    types.clear() ;
4077         
4078    if ( apexcalmode == 0 ) {
4079      // APEX fs data without off scan
4080      // process each sig and ref scan
4081      ArrayColumn<Float> tsysCollo ;
4082      tsysCollo.attach( ssig->table(), "TSYS" ) ;
4083      ArrayColumn<Float> tsysColhi ;
4084      tsysColhi.attach( sref->table(), "TSYS" ) ;
4085      for ( int i = 0 ; i < ssig->nrow() ; i++ ) {
4086        vector< CountedPtr<Scantable> > sky( 2 ) ;
4087        sky[0] = askylo ;
4088        sky[1] = askyhi ;
4089        vector< CountedPtr<Scantable> > hot( 2 ) ;
4090        hot[0] = ahotlo ;
4091        hot[1] = ahothi ;
4092        vector< CountedPtr<Scantable> > cold( 2 ) ;
4093        //cold[0] = acoldlo ;
4094        //cold[1] = acoldhi ;
4095        vector<float> sp = getFSCalibratedSpectra( ssig, sref, sky, hot, cold, i ) ;
4096        ssig->setSpectrum( sp, i ) ;
4097        string reftime = ssig->getTime( i ) ;
4098        vector<int> ii( 1, ssig->getIF( i ) ) ;
4099        vector<int> ib( 1, ssig->getBeam( i ) ) ;
4100        vector<int> ip( 1, ssig->getPol( i ) ) ;
4101        sel.setIFs( ii ) ;
4102        sel.setBeams( ib ) ;
4103        sel.setPolarizations( ip ) ;
4104        askylo->setSelection( sel ) ;
4105        vector<float> sptsys = getTsysFromTime( reftime, askylo, "linear" ) ;
4106        const Vector<Float> Vtsyslo( sptsys ) ;
4107        tsysCollo.put( i, Vtsyslo ) ;
4108        askylo->unsetSelection() ;
4109        sel.reset() ;
4110        sky[0] = askyhi ;
4111        sky[1] = askylo ;
4112        hot[0] = ahothi ;
4113        hot[1] = ahotlo ;
4114        cold[0] = acoldhi ;
4115        cold[1] = acoldlo ;
4116        sp = getFSCalibratedSpectra( sref, ssig, sky, hot, cold, i ) ;
4117        sref->setSpectrum( sp, i ) ;
4118        reftime = sref->getTime( i ) ;
4119        ii[0] = sref->getIF( i )  ;
4120        ib[0] = sref->getBeam( i ) ;
4121        ip[0] = sref->getPol( i ) ;
4122        sel.setIFs( ii ) ;
4123        sel.setBeams( ib ) ;
4124        sel.setPolarizations( ip ) ;
4125        askyhi->setSelection( sel ) ;   
4126        sptsys = getTsysFromTime( reftime, askyhi, "linear" ) ;
4127        const Vector<Float> Vtsyshi( sptsys ) ;
4128        tsysColhi.put( i, Vtsyshi ) ;
4129        askyhi->unsetSelection() ;
4130        sel.reset() ;
4131      }
4132    }
4133    else if ( apexcalmode == 1 ) {
4134      // APEX fs data with off scan
4135      // off scan
4136      types.push_back( SrcType::FLOOFF ) ;
4137      sel.setTypes( types ) ;
4138      s->setSelection( sel ) ;
4139      tmp.clear() ;
4140      tmp.push_back( getScantable( s, false ) ) ;
4141      CountedPtr<Scantable> aofflo = average( tmp, masks, "TINT", "SCAN" ) ;
4142      s->unsetSelection() ;
4143      sel.reset() ;
4144      types.clear() ;
4145      types.push_back( SrcType::FHIOFF ) ;
4146      sel.setTypes( types ) ;
4147      s->setSelection( sel ) ;
4148      tmp.clear() ;
4149      tmp.push_back( getScantable( s, false ) ) ;
4150      CountedPtr<Scantable> aoffhi = average( tmp, masks, "TINT", "SCAN" ) ;
4151      s->unsetSelection() ;
4152      sel.reset() ;
4153      types.clear() ;
4154     
4155      // process each sig and ref scan
4156      ArrayColumn<Float> tsysCollo ;
4157      tsysCollo.attach( ssig->table(), "TSYS" ) ;
4158      ArrayColumn<Float> tsysColhi ;
4159      tsysColhi.attach( sref->table(), "TSYS" ) ;
4160      for ( int i = 0 ; i < ssig->nrow() ; i++ ) {
4161        vector<float> sp = getCalibratedSpectra( ssig, aofflo, askylo, ahotlo, acoldlo, i, antname ) ;
4162        ssig->setSpectrum( sp, i ) ;
4163        sp = getCalibratedSpectra( sref, aoffhi, askyhi, ahothi, acoldhi, i, antname ) ;
4164        string reftime = ssig->getTime( i ) ;
4165        vector<int> ii( 1, ssig->getIF( i ) ) ;
4166        vector<int> ib( 1, ssig->getBeam( i ) ) ;
4167        vector<int> ip( 1, ssig->getPol( i ) ) ;
4168        sel.setIFs( ii ) ;
4169        sel.setBeams( ib ) ;
4170        sel.setPolarizations( ip ) ;
4171        askylo->setSelection( sel ) ;
4172        vector<float> sptsys = getTsysFromTime( reftime, askylo, "linear" ) ;
4173        const Vector<Float> Vtsyslo( sptsys ) ;
4174        tsysCollo.put( i, Vtsyslo ) ;
4175        askylo->unsetSelection() ;
4176        sel.reset() ;
4177        sref->setSpectrum( sp, i ) ;
4178        reftime = sref->getTime( i ) ;
4179        ii[0] = sref->getIF( i )  ;
4180        ib[0] = sref->getBeam( i ) ;
4181        ip[0] = sref->getPol( i ) ;
4182        sel.setIFs( ii ) ;
4183        sel.setBeams( ib ) ;
4184        sel.setPolarizations( ip ) ;
4185        askyhi->setSelection( sel ) ;   
4186        sptsys = getTsysFromTime( reftime, askyhi, "linear" ) ;
4187        const Vector<Float> Vtsyshi( sptsys ) ;
4188        tsysColhi.put( i, Vtsyshi ) ;
4189        askyhi->unsetSelection() ;
4190        sel.reset() ;
4191      }
4192    }
4193  }
4194  else {
4195    // non-APEX fs data
4196    // sky scan
4197    STSelector sel = STSelector() ;
4198    types.push_back( SrcType::SKY ) ;
4199    sel.setTypes( types ) ;
4200    s->setSelection( sel ) ;
4201    vector< CountedPtr<Scantable> > tmp( 1, getScantable( s, false ) ) ;
4202    CountedPtr<Scantable> asky = average( tmp, masks, "TINT", "SCAN" ) ;
4203    s->unsetSelection() ;
4204    sel.reset() ;
4205    types.clear() ;
4206   
4207    // hot scan
4208    types.push_back( SrcType::HOT ) ;
4209    sel.setTypes( types ) ;
4210    s->setSelection( sel ) ;
4211    tmp.clear() ;
4212    tmp.push_back( getScantable( s, false ) ) ;
4213    CountedPtr<Scantable> ahot = average( tmp, masks, "TINT", "SCAN" ) ;
4214    s->unsetSelection() ;
4215    sel.reset() ;
4216    types.clear() ;
4217
4218    // cold scan
4219    CountedPtr<Scantable> acold ;
4220//     types.push_back( SrcType::COLD ) ;
4221//     sel.setTypes( types ) ;
4222//     s->setSelection( sel ) ;
4223//     tmp.clear() ;
4224//     tmp.push_back( getScantable( s, false ) ) ;
4225//     CountedPtr<Scantable> acold = average( tmp, masks, "TINT", "SCAN" ) ;
4226//     s->unsetSelection() ;
4227//     sel.reset() ;
4228//     types.clear() ;
4229   
4230    // ref scan
4231    bool insitu = insitu_ ;
4232    insitu_ = false ;
4233    sref = getScantable( s, true ) ;
4234    insitu_ = insitu ;
4235    types.push_back( SrcType::FSOFF ) ;
4236    sel.setTypes( types ) ;
4237    s->setSelection( sel ) ;
4238    TableCopy::copyRows( sref->table(), s->table() ) ;
4239    s->unsetSelection() ;
4240    sel.reset() ;
4241    types.clear() ;
4242   
4243    // sig scan
4244    insitu_ = false ;
4245    ssig = getScantable( s, true ) ;
4246    insitu_ = insitu ;
4247    types.push_back( SrcType::FSON ) ;
4248    sel.setTypes( types ) ;
4249    s->setSelection( sel ) ;
4250    TableCopy::copyRows( ssig->table(), s->table() ) ;
4251    s->unsetSelection() ;
4252    sel.reset() ;
4253    types.clear() ;
4254
4255    // process each sig and ref scan
4256    ArrayColumn<Float> tsysColsig ;
4257    tsysColsig.attach( ssig->table(), "TSYS" ) ;
4258    ArrayColumn<Float> tsysColref ;
4259    tsysColref.attach( ssig->table(), "TSYS" ) ;
4260    for ( int i = 0 ; i < ssig->nrow() ; i++ ) {
4261      vector<float> sp = getFSCalibratedSpectra( ssig, sref, asky, ahot, acold, i ) ;
4262      ssig->setSpectrum( sp, i ) ;
4263      string reftime = ssig->getTime( i ) ;
4264      vector<int> ii( 1, ssig->getIF( i ) ) ;
4265      vector<int> ib( 1, ssig->getBeam( i ) ) ;
4266      vector<int> ip( 1, ssig->getPol( i ) ) ;
4267      sel.setIFs( ii ) ;
4268      sel.setBeams( ib ) ;
4269      sel.setPolarizations( ip ) ;
4270      asky->setSelection( sel ) ;
4271      vector<float> sptsys = getTsysFromTime( reftime, asky, "linear" ) ;
4272      const Vector<Float> Vtsys( sptsys ) ;
4273      tsysColsig.put( i, Vtsys ) ;
4274      asky->unsetSelection() ;
4275      sel.reset() ;
4276      sp = getFSCalibratedSpectra( sref, ssig, asky, ahot, acold, i ) ;
4277      sref->setSpectrum( sp, i ) ;
4278      tsysColref.put( i, Vtsys ) ;
4279    }
4280  }
4281
4282  // do folding if necessary
4283  Table sigtab = ssig->table() ;
4284  Table reftab = sref->table() ;
4285  ScalarColumn<uInt> sigifnoCol ;
4286  ScalarColumn<uInt> refifnoCol ;
4287  ScalarColumn<uInt> sigfidCol ;
4288  ScalarColumn<uInt> reffidCol ;
4289  Int nchan = (Int)ssig->nchan() ;
4290  sigifnoCol.attach( sigtab, "IFNO" ) ;
4291  refifnoCol.attach( reftab, "IFNO" ) ;
4292  sigfidCol.attach( sigtab, "FREQ_ID" ) ;
4293  reffidCol.attach( reftab, "FREQ_ID" ) ;
4294  Vector<uInt> sfids( sigfidCol.getColumn() ) ;
4295  Vector<uInt> rfids( reffidCol.getColumn() ) ;
4296  vector<uInt> sfids_unique ;
4297  vector<uInt> rfids_unique ;
4298  vector<uInt> sifno_unique ;
4299  vector<uInt> rifno_unique ;
4300  for ( uInt i = 0 ; i < sfids.nelements() ; i++ ) {
4301    if ( count( sfids_unique.begin(), sfids_unique.end(), sfids[i] ) == 0 ) {
4302      sfids_unique.push_back( sfids[i] ) ;
4303      sifno_unique.push_back( ssig->getIF( i ) ) ;
4304    }
4305    if ( count( rfids_unique.begin(), rfids_unique.end(),  rfids[i] ) == 0 ) {
4306      rfids_unique.push_back( rfids[i] ) ;
4307      rifno_unique.push_back( sref->getIF( i ) ) ;
4308    }
4309  }
4310  double refpix_sig, refval_sig, increment_sig ;
4311  double refpix_ref, refval_ref, increment_ref ;
4312  vector< CountedPtr<Scantable> > tmp( sfids_unique.size() ) ;
4313  for ( uInt i = 0 ; i < sfids_unique.size() ; i++ ) {
4314    ssig->frequencies().getEntry( refpix_sig, refval_sig, increment_sig, sfids_unique[i] ) ;
4315    sref->frequencies().getEntry( refpix_ref, refval_ref, increment_ref, rfids_unique[i] ) ;
4316    if ( refpix_sig == refpix_ref ) {
4317      double foffset = refval_ref - refval_sig ;
4318      int choffset = static_cast<int>(foffset/increment_sig) ;
4319      double doffset = foffset / increment_sig ;
4320      if ( abs(choffset) >= nchan ) {
4321        LogIO os( LogOrigin( "STMath", "cwcalfs", WHERE ) ) ;
4322        os << "FREQ_ID=[" << sfids_unique[i] << "," << rfids_unique[i] << "]: out-band frequency switching, no folding" << LogIO::POST ;
4323        os << "Just return signal data" << LogIO::POST ;
4324        //std::vector< CountedPtr<Scantable> > tabs ;
4325        //tabs.push_back( ssig ) ;
4326        //tabs.push_back( sref ) ;
4327        //out = merge( tabs ) ;
4328        tmp[i] = ssig ;
4329      }
4330      else {
4331        STSelector sel = STSelector() ;
4332        vector<int> v( 1, sifno_unique[i] ) ;
4333        sel.setIFs( v ) ;
4334        ssig->setSelection( sel ) ;
4335        sel.reset() ;
4336        v[0] = rifno_unique[i] ;
4337        sel.setIFs( v ) ;
4338        sref->setSelection( sel ) ;
4339        sel.reset() ;
4340        if ( antname.find( "APEX" ) != string::npos ) {
4341          tmp[i] = dofold( ssig, sref, 0.5*doffset, -0.5*doffset ) ;
4342          //tmp[i] = dofold( ssig, sref, doffset ) ;
4343        }
4344        else {
4345          tmp[i] = dofold( ssig, sref, doffset ) ;
4346        }
4347        ssig->unsetSelection() ;
4348        sref->unsetSelection() ;
4349      }
4350    }
4351  }
4352
4353  if ( tmp.size() > 1 ) {
4354    out = merge( tmp ) ;
4355  }
4356  else {
4357    out = tmp[0] ;
4358  }
4359
4360  // flux unit
4361  out->setFluxUnit( "K" ) ;
4362
4363  return out ;
4364}
4365
4366CountedPtr<Scantable> STMath::almacalfs( const CountedPtr<Scantable>& s )
4367{
4368  (void) s; //currently unused
4369  CountedPtr<Scantable> out ;
4370
4371  return out ;
4372}
4373
4374vector<float> STMath::getSpectrumFromTime( string reftime,
4375                                           CountedPtr<Scantable>& s,
4376                                           string mode )
4377{
4378  LogIO os( LogOrigin( "STMath", "getSpectrumFromTime", WHERE ) ) ;
4379  vector<float> sp ;
4380
4381  if ( s->nrow() == 0 ) {
4382    os << LogIO::SEVERE << "No spectra in the input scantable. Return empty spectrum." << LogIO::POST ;
4383    return sp ;
4384  }
4385  else if ( s->nrow() == 1 ) {
4386    //os << "use row " << 0 << " (scanno = " << s->getScan( 0 ) << ")" << LogIO::POST ;
4387    return s->getSpectrum( 0 ) ;
4388  }
4389  else {
4390    vector<int> idx = getRowIdFromTime( reftime, s ) ;
4391    if ( mode == "before" ) {
4392      int id = -1 ;
4393      if ( idx[0] != -1 ) {
4394        id = idx[0] ;
4395      }
4396      else if ( idx[1] != -1 ) {
4397        os << LogIO::WARN << "Failed to find a scan before reftime. return a spectrum just after the reftime." << LogIO::POST ;
4398        id = idx[1] ;
4399      }
4400      //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
4401      sp = s->getSpectrum( id ) ;
4402    }
4403    else if ( mode == "after" ) {
4404      int id = -1 ;
4405      if ( idx[1] != -1 ) {
4406        id = idx[1] ;
4407      }
4408      else if ( idx[0] != -1 ) {
4409        os << LogIO::WARN << "Failed to find a scan after reftime. return a spectrum just before the reftime." << LogIO::POST ;
4410        id = idx[1] ;
4411      }
4412      //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
4413      sp = s->getSpectrum( id ) ;
4414    }
4415    else if ( mode == "nearest" ) {
4416      int id = -1 ;
4417      if ( idx[0] == -1 ) {
4418        id = idx[1] ;
4419      }
4420      else if ( idx[1] == -1 ) {
4421        id = idx[0] ;
4422      }
4423      else if ( idx[0] == idx[1] ) {
4424        id = idx[0] ;
4425      }
4426      else {
4427        //double t0 = getMJD( s->getTime( idx[0] ) ) ;
4428        //double t1 = getMJD( s->getTime( idx[1] ) ) ;
4429        double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
4430        double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
4431        double tref = getMJD( reftime ) ;
4432        if ( abs( t0 - tref ) > abs( t1 - tref ) ) {
4433          id = idx[1] ;
4434        }
4435        else {
4436          id = idx[0] ;
4437        }
4438      }
4439      //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
4440      sp = s->getSpectrum( id ) ;     
4441    }
4442    else if ( mode == "linear" ) {
4443      if ( idx[0] == -1 ) {
4444        // use after
4445        os << LogIO::WARN << "Failed to interpolate. return a spectrum just after the reftime." << LogIO::POST ;
4446        int id = idx[1] ;
4447        //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
4448        sp = s->getSpectrum( id ) ;
4449      }
4450      else if ( idx[1] == -1 ) {
4451        // use before
4452        os << LogIO::WARN << "Failed to interpolate. return a spectrum just before the reftime." << LogIO::POST ;
4453        int id = idx[0] ;
4454        //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
4455        sp = s->getSpectrum( id ) ;
4456      }
4457      else if ( idx[0] == idx[1] ) {
4458        // use before
4459        //os << "No need to interporate." << LogIO::POST ;
4460        int id = idx[0] ;
4461        //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
4462        sp = s->getSpectrum( id ) ;
4463      }
4464      else {
4465        // do interpolation
4466        //os << "interpolate between " << idx[0] << " and " << idx[1] << " (scanno: " << s->getScan( idx[0] ) << ", " << s->getScan( idx[1] ) << ")" << LogIO::POST ;
4467        //double t0 = getMJD( s->getTime( idx[0] ) ) ;
4468        //double t1 = getMJD( s->getTime( idx[1] ) ) ;
4469        double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
4470        double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
4471        double tref = getMJD( reftime ) ;
4472        vector<float> sp0 = s->getSpectrum( idx[0] ) ;
4473        vector<float> sp1 = s->getSpectrum( idx[1] ) ;
4474        for ( unsigned int i = 0 ; i < sp0.size() ; i++ ) {
4475          float v = ( sp1[i] - sp0[i] ) / ( t1 - t0 ) * ( tref - t0 ) + sp0[i] ;
4476          sp.push_back( v ) ;
4477        }
4478      }
4479    }
4480    else {
4481      os << LogIO::SEVERE << "Unknown mode" << LogIO::POST ;
4482    }
4483    return sp ;
4484  }
4485}
4486
4487double STMath::getMJD( string strtime )
4488{
4489  if ( strtime.find("/") == string::npos ) {
4490    // MJD time string
4491    return atof( strtime.c_str() ) ;
4492  }
4493  else {
4494    // string in YYYY/MM/DD/HH:MM:SS format
4495    uInt year = atoi( strtime.substr( 0, 4 ).c_str() ) ;
4496    uInt month = atoi( strtime.substr( 5, 2 ).c_str() ) ;
4497    uInt day = atoi( strtime.substr( 8, 2 ).c_str() ) ;
4498    uInt hour = atoi( strtime.substr( 11, 2 ).c_str() ) ;
4499    uInt minute = atoi( strtime.substr( 14, 2 ).c_str() ) ;
4500    uInt sec = atoi( strtime.substr( 17, 2 ).c_str() ) ;
4501    Time t( year, month, day, hour, minute, sec ) ;
4502    return t.modifiedJulianDay() ;
4503  }
4504}
4505
4506vector<int> STMath::getRowIdFromTime( string reftime, CountedPtr<Scantable> &s )
4507{
4508  double reft = getMJD( reftime ) ;
4509  double dtmin = 1.0e100 ;
4510  double dtmax = -1.0e100 ;
4511  vector<double> dt ;
4512  int just_before = -1 ;
4513  int just_after = -1 ;
4514  for ( int i = 0 ; i < s->nrow() ; i++ ) {
4515    dt.push_back( getMJD( s->getTime( i ) ) - reft ) ;
4516  }
4517  for ( unsigned int i = 0 ; i < dt.size() ; i++ ) {
4518    if ( dt[i] > 0.0 ) {
4519      // after reftime
4520      if ( dt[i] < dtmin ) {
4521        just_after = i ;
4522        dtmin = dt[i] ;
4523      }
4524    }
4525    else if ( dt[i] < 0.0 ) {
4526      // before reftime
4527      if ( dt[i] > dtmax ) {
4528        just_before = i ;
4529        dtmax = dt[i] ;
4530      }
4531    }
4532    else {
4533      // just a reftime
4534      just_before = i ;
4535      just_after = i ;
4536      dtmax = 0 ;
4537      dtmin = 0 ;
4538      break ;
4539    }
4540  }
4541
4542  vector<int> v ;
4543  v.push_back( just_before ) ;
4544  v.push_back( just_after ) ;
4545
4546  return v ;
4547}
4548
4549vector<float> STMath::getTcalFromTime( string reftime,
4550                                       CountedPtr<Scantable>& s,
4551                                       string mode )
4552{
4553  LogIO os( LogOrigin( "STMath", "getTcalFromTime", WHERE ) ) ;
4554  vector<float> tcal ;
4555  STTcal tcalTable = s->tcal() ;
4556  String time ;
4557  Vector<Float> tcalval ;
4558  if ( s->nrow() == 0 ) {
4559    os << LogIO::SEVERE << "No row in the input scantable. Return empty tcal." << LogIO::POST ;
4560    return tcal ;
4561  }
4562  else if ( s->nrow() == 1 ) {
4563    uInt tcalid = s->getTcalId( 0 ) ;
4564    //os << "use row " << 0 << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4565    tcalTable.getEntry( time, tcalval, tcalid ) ;
4566    tcalval.tovector( tcal ) ;
4567    return tcal ;
4568  }
4569  else {
4570    vector<int> idx = getRowIdFromTime( reftime, s ) ;
4571    if ( mode == "before" ) {
4572      int id = -1 ;
4573      if ( idx[0] != -1 ) {
4574        id = idx[0] ;
4575      }
4576      else if ( idx[1] != -1 ) {
4577        os << LogIO::WARN << "Failed to find a scan before reftime. return a spectrum just after the reftime." << LogIO::POST ;
4578        id = idx[1] ;
4579      }
4580      uInt tcalid = s->getTcalId( id ) ;
4581      //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4582      tcalTable.getEntry( time, tcalval, tcalid ) ;
4583      tcalval.tovector( tcal ) ;
4584    }
4585    else if ( mode == "after" ) {
4586      int id = -1 ;
4587      if ( idx[1] != -1 ) {
4588        id = idx[1] ;
4589      }
4590      else if ( idx[0] != -1 ) {
4591        os << LogIO::WARN << "Failed to find a scan after reftime. return a spectrum just before the reftime." << LogIO::POST ;
4592        id = idx[1] ;
4593      }
4594      uInt tcalid = s->getTcalId( id ) ;
4595      //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4596      tcalTable.getEntry( time, tcalval, tcalid ) ;
4597      tcalval.tovector( tcal ) ;
4598    }
4599    else if ( mode == "nearest" ) {
4600      int id = -1 ;
4601      if ( idx[0] == -1 ) {
4602        id = idx[1] ;
4603      }
4604      else if ( idx[1] == -1 ) {
4605        id = idx[0] ;
4606      }
4607      else if ( idx[0] == idx[1] ) {
4608        id = idx[0] ;
4609      }
4610      else {
4611        //double t0 = getMJD( s->getTime( idx[0] ) ) ;
4612        //double t1 = getMJD( s->getTime( idx[1] ) ) ;
4613        double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
4614        double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
4615        double tref = getMJD( reftime ) ;
4616        if ( abs( t0 - tref ) > abs( t1 - tref ) ) {
4617          id = idx[1] ;
4618        }
4619        else {
4620          id = idx[0] ;
4621        }
4622      }
4623      uInt tcalid = s->getTcalId( id ) ;
4624      //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4625      tcalTable.getEntry( time, tcalval, tcalid ) ;
4626      tcalval.tovector( tcal ) ;
4627    }
4628    else if ( mode == "linear" ) {
4629      if ( idx[0] == -1 ) {
4630        // use after
4631        os << LogIO::WARN << "Failed to interpolate. return a spectrum just after the reftime." << LogIO::POST ;
4632        int id = idx[1] ;
4633        uInt tcalid = s->getTcalId( id ) ;
4634        //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4635        tcalTable.getEntry( time, tcalval, tcalid ) ;
4636        tcalval.tovector( tcal ) ;
4637      }
4638      else if ( idx[1] == -1 ) {
4639        // use before
4640        os << LogIO::WARN << "Failed to interpolate. return a spectrum just before the reftime." << LogIO::POST ;
4641        int id = idx[0] ;
4642        uInt tcalid = s->getTcalId( id ) ;
4643        //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4644        tcalTable.getEntry( time, tcalval, tcalid ) ;
4645        tcalval.tovector( tcal ) ;
4646      }
4647      else if ( idx[0] == idx[1] ) {
4648        // use before
4649        //os << "No need to interporate." << LogIO::POST ;
4650        int id = idx[0] ;
4651        uInt tcalid = s->getTcalId( id ) ;
4652        //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ;
4653        tcalTable.getEntry( time, tcalval, tcalid ) ;
4654        tcalval.tovector( tcal ) ;
4655      }
4656      else {
4657        // do interpolation
4658        //os << "interpolate between " << idx[0] << " and " << idx[1] << " (scanno: " << s->getScan( idx[0] ) << ", " << s->getScan( idx[1] ) << ")" << LogIO::POST ;
4659        //double t0 = getMJD( s->getTime( idx[0] ) ) ;
4660        //double t1 = getMJD( s->getTime( idx[1] ) ) ;
4661        double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
4662        double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
4663        double tref = getMJD( reftime ) ;
4664        vector<float> tcal0 ;
4665        vector<float> tcal1 ;
4666        uInt tcalid0 = s->getTcalId( idx[0] ) ;
4667        uInt tcalid1 = s->getTcalId( idx[1] ) ;
4668        tcalTable.getEntry( time, tcalval, tcalid0 ) ;
4669        tcalval.tovector( tcal0 ) ;
4670        tcalTable.getEntry( time, tcalval, tcalid1 ) ;
4671        tcalval.tovector( tcal1 ) ;       
4672        for ( unsigned int i = 0 ; i < tcal0.size() ; i++ ) {
4673          float v = ( tcal1[i] - tcal0[i] ) / ( t1 - t0 ) * ( tref - t0 ) + tcal0[i] ;
4674          tcal.push_back( v ) ;
4675        }
4676      }
4677    }
4678    else {
4679      os << LogIO::SEVERE << "Unknown mode" << LogIO::POST ;
4680    }
4681    return tcal ;
4682  }
4683}
4684
4685vector<float> STMath::getTsysFromTime( string reftime,
4686                                       CountedPtr<Scantable>& s,
4687                                       string mode )
4688{
4689  LogIO os( LogOrigin( "STMath", "getTsysFromTime", WHERE ) ) ;
4690  ArrayColumn<Float> tsysCol ;
4691  tsysCol.attach( s->table(), "TSYS" ) ;
4692  vector<float> tsys ;
4693  String time ;
4694  Vector<Float> tsysval ;
4695  if ( s->nrow() == 0 ) {
4696    os << LogIO::SEVERE << "No row in the input scantable. Return empty tsys." << LogIO::POST ;
4697    return tsys ;
4698  }
4699  else if ( s->nrow() == 1 ) {
4700    //os << "use row " << 0 << LogIO::POST ;
4701    tsysval = tsysCol( 0 ) ;
4702    tsysval.tovector( tsys ) ;
4703    return tsys ;
4704  }
4705  else {
4706    vector<int> idx = getRowIdFromTime( reftime, s ) ;
4707    if ( mode == "before" ) {
4708      int id = -1 ;
4709      if ( idx[0] != -1 ) {
4710        id = idx[0] ;
4711      }
4712      else if ( idx[1] != -1 ) {
4713        os << LogIO::WARN << "Failed to find a scan before reftime. return a spectrum just after the reftime." << LogIO::POST ;
4714        id = idx[1] ;
4715      }
4716      //os << "use row " << id << LogIO::POST ;
4717      tsysval = tsysCol( id ) ;
4718      tsysval.tovector( tsys ) ;
4719    }
4720    else if ( mode == "after" ) {
4721      int id = -1 ;
4722      if ( idx[1] != -1 ) {
4723        id = idx[1] ;
4724      }
4725      else if ( idx[0] != -1 ) {
4726        os << LogIO::WARN << "Failed to find a scan after reftime. return a spectrum just before the reftime." << LogIO::POST ;
4727        id = idx[1] ;
4728      }
4729      //os << "use row " << id << LogIO::POST ;
4730      tsysval = tsysCol( id ) ;
4731      tsysval.tovector( tsys ) ;
4732    }
4733    else if ( mode == "nearest" ) {
4734      int id = -1 ;
4735      if ( idx[0] == -1 ) {
4736        id = idx[1] ;
4737      }
4738      else if ( idx[1] == -1 ) {
4739        id = idx[0] ;
4740      }
4741      else if ( idx[0] == idx[1] ) {
4742        id = idx[0] ;
4743      }
4744      else {
4745        //double t0 = getMJD( s->getTime( idx[0] ) ) ;
4746        //double t1 = getMJD( s->getTime( idx[1] ) ) ;
4747        double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
4748        double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
4749        double tref = getMJD( reftime ) ;
4750        if ( abs( t0 - tref ) > abs( t1 - tref ) ) {
4751          id = idx[1] ;
4752        }
4753        else {
4754          id = idx[0] ;
4755        }
4756      }
4757      //os << "use row " << id << LogIO::POST ;
4758      tsysval = tsysCol( id ) ;
4759      tsysval.tovector( tsys ) ;
4760    }
4761    else if ( mode == "linear" ) {
4762      if ( idx[0] == -1 ) {
4763        // use after
4764        os << LogIO::WARN << "Failed to interpolate. return a spectrum just after the reftime." << LogIO::POST ;
4765        int id = idx[1] ;
4766        //os << "use row " << id << LogIO::POST ;
4767        tsysval = tsysCol( id ) ;
4768        tsysval.tovector( tsys ) ;
4769      }
4770      else if ( idx[1] == -1 ) {
4771        // use before
4772        os << LogIO::WARN << "Failed to interpolate. return a spectrum just before the reftime." << LogIO::POST ;
4773        int id = idx[0] ;
4774        //os << "use row " << id << LogIO::POST ;
4775        tsysval = tsysCol( id ) ;
4776        tsysval.tovector( tsys ) ;
4777      }
4778      else if ( idx[0] == idx[1] ) {
4779        // use before
4780        //os << "No need to interporate." << LogIO::POST ;
4781        int id = idx[0] ;
4782        //os << "use row " << id << LogIO::POST ;
4783        tsysval = tsysCol( id ) ;
4784        tsysval.tovector( tsys ) ;
4785      }
4786      else {
4787        // do interpolation
4788        //os << "interpolate between " << idx[0] << " and " << idx[1] << " (scanno: " << s->getScan( idx[0] ) << ", " << s->getScan( idx[1] ) << ")" << LogIO::POST ;
4789        //double t0 = getMJD( s->getTime( idx[0] ) ) ;
4790        //double t1 = getMJD( s->getTime( idx[1] ) ) ;
4791        double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
4792        double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
4793        double tref = getMJD( reftime ) ;
4794        vector<float> tsys0 ;
4795        vector<float> tsys1 ;
4796        tsysval = tsysCol( idx[0] ) ;
4797        tsysval.tovector( tsys0 ) ;
4798        tsysval = tsysCol( idx[1] ) ;
4799        tsysval.tovector( tsys1 ) ;       
4800        for ( unsigned int i = 0 ; i < tsys0.size() ; i++ ) {
4801          float v = ( tsys1[i] - tsys0[i] ) / ( t1 - t0 ) * ( tref - t0 ) + tsys0[i] ;
4802          tsys.push_back( v ) ;
4803        }
4804      }
4805    }
4806    else {
4807      os << LogIO::SEVERE << "Unknown mode" << LogIO::POST ;
4808    }
4809    return tsys ;
4810  }
4811}
4812
4813vector<float> STMath::getCalibratedSpectra( CountedPtr<Scantable>& on,
4814                                            CountedPtr<Scantable>& off,
4815                                            CountedPtr<Scantable>& sky,
4816                                            CountedPtr<Scantable>& hot,
4817                                            CountedPtr<Scantable>& cold,
4818                                            int index,
4819                                            string antname )
4820{
4821  (void) cold; //currently unused
4822  string reftime = on->getTime( index ) ;
4823  vector<int> ii( 1, on->getIF( index ) ) ;
4824  vector<int> ib( 1, on->getBeam( index ) ) ;
4825  vector<int> ip( 1, on->getPol( index ) ) ;
4826  vector<int> ic( 1, on->getScan( index ) ) ;
4827  STSelector sel = STSelector() ;
4828  sel.setIFs( ii ) ;
4829  sel.setBeams( ib ) ;
4830  sel.setPolarizations( ip ) ;
4831  sky->setSelection( sel ) ;
4832  hot->setSelection( sel ) ;
4833  //cold->setSelection( sel ) ;
4834  off->setSelection( sel ) ;
4835  vector<float> spsky = getSpectrumFromTime( reftime, sky, "linear" ) ;
4836  vector<float> sphot = getSpectrumFromTime( reftime, hot, "linear" ) ;
4837  //vector<float> spcold = getSpectrumFromTime( reftime, cold, "linear" ) ;
4838  vector<float> spoff = getSpectrumFromTime( reftime, off, "linear" ) ;
4839  vector<float> spec = on->getSpectrum( index ) ;
4840  vector<float> tcal = getTcalFromTime( reftime, sky, "linear" ) ;
4841  vector<float> sp( tcal.size() ) ;
4842  if ( antname.find( "APEX" ) != string::npos ) {
4843    // using gain array
4844    for ( unsigned int j = 0 ; j < tcal.size() ; j++ ) {
4845      float v = ( ( spec[j] - spoff[j] ) / spoff[j] )
4846        * ( spsky[j] / ( sphot[j] - spsky[j] ) ) * tcal[j] ;
4847      sp[j] = v ;
4848    }
4849  }
4850  else {
4851    // Chopper-Wheel calibration (Ulich & Haas 1976)
4852    for ( unsigned int j = 0 ; j < tcal.size() ; j++ ) {
4853      float v = ( spec[j] - spoff[j] ) / ( sphot[j] - spsky[j] ) * tcal[j] ;
4854      sp[j] = v ;
4855    }
4856  }
4857  sel.reset() ;
4858  sky->unsetSelection() ;
4859  hot->unsetSelection() ;
4860  //cold->unsetSelection() ;
4861  off->unsetSelection() ;
4862
4863  return sp ;
4864}
4865
4866vector<float> STMath::getCalibratedSpectra( CountedPtr<Scantable>& on,
4867                                            CountedPtr<Scantable>& off,
4868                                            int index )
4869{
4870  string reftime = on->getTime( index ) ;
4871  vector<int> ii( 1, on->getIF( index ) ) ;
4872  vector<int> ib( 1, on->getBeam( index ) ) ;
4873  vector<int> ip( 1, on->getPol( index ) ) ;
4874  vector<int> ic( 1, on->getScan( index ) ) ;
4875  STSelector sel = STSelector() ;
4876  sel.setIFs( ii ) ;
4877  sel.setBeams( ib ) ;
4878  sel.setPolarizations( ip ) ;
4879  off->setSelection( sel ) ;
4880  vector<float> spoff = getSpectrumFromTime( reftime, off, "linear" ) ;
4881  vector<float> spec = on->getSpectrum( index ) ;
4882  //vector<float> tcal = getTcalFromTime( reftime, sky, "linear" ) ;
4883  //vector<float> tsys = on->getTsysVec( index ) ;
4884  ArrayColumn<Float> tsysCol( on->table(), "TSYS" ) ;
4885  Vector<Float> tsys = tsysCol( index ) ;
4886  vector<float> sp( spec.size() ) ;
4887  // ALMA Calibration
4888  //
4889  // Ta* = Tsys * ( ON - OFF ) / OFF
4890  //
4891  // 2010/01/07 Takeshi Nakazato
4892  unsigned int tsyssize = tsys.nelements() ;
4893  unsigned int spsize = sp.size() ;
4894  for ( unsigned int j = 0 ; j < sp.size() ; j++ ) {
4895    float tscale = 0.0 ;
4896    if ( tsyssize == spsize )
4897      tscale = tsys[j] ;
4898    else
4899      tscale = tsys[0] ;
4900    float v = tscale * ( spec[j] - spoff[j] ) / spoff[j] ;
4901    sp[j] = v ;
4902  }
4903  sel.reset() ;
4904  off->unsetSelection() ;
4905
4906  return sp ;
4907}
4908
4909vector<float> STMath::getFSCalibratedSpectra( CountedPtr<Scantable>& sig,
4910                                              CountedPtr<Scantable>& ref,
4911                                              CountedPtr<Scantable>& sky,
4912                                              CountedPtr<Scantable>& hot,
4913                                              CountedPtr<Scantable>& cold,
4914                                              int index )
4915{
4916  (void) cold; //currently unused
4917  string reftime = sig->getTime( index ) ;
4918  vector<int> ii( 1, sig->getIF( index ) ) ;
4919  vector<int> ib( 1, sig->getBeam( index ) ) ;
4920  vector<int> ip( 1, sig->getPol( index ) ) ;
4921  vector<int> ic( 1, sig->getScan( index ) ) ;
4922  STSelector sel = STSelector() ;
4923  sel.setIFs( ii ) ;
4924  sel.setBeams( ib ) ;
4925  sel.setPolarizations( ip ) ;
4926  sky->setSelection( sel ) ;
4927  hot->setSelection( sel ) ;
4928  //cold->setSelection( sel ) ;
4929  vector<float> spsky = getSpectrumFromTime( reftime, sky, "linear" ) ;
4930  vector<float> sphot = getSpectrumFromTime( reftime, hot, "linear" ) ;
4931  //vector<float> spcold = getSpectrumFromTime( reftime, cold, "linear" ) ;
4932  vector<float> spref = ref->getSpectrum( index ) ;
4933  vector<float> spsig = sig->getSpectrum( index ) ;
4934  vector<float> tcal = getTcalFromTime( reftime, sky, "linear" ) ;
4935  vector<float> sp( tcal.size() ) ;
4936  for ( unsigned int j = 0 ; j < tcal.size() ; j++ ) {
4937    float v = tcal[j] * spsky[j] / ( sphot[j] - spsky[j] ) * ( spsig[j] - spref[j] ) / spref[j] ;
4938    sp[j] = v ;
4939  }
4940  sel.reset() ;
4941  sky->unsetSelection() ;
4942  hot->unsetSelection() ;
4943  //cold->unsetSelection() ;
4944
4945  return sp ;
4946}
4947
4948vector<float> STMath::getFSCalibratedSpectra( CountedPtr<Scantable>& sig,
4949                                              CountedPtr<Scantable>& ref,
4950                                              vector< CountedPtr<Scantable> >& sky,
4951                                              vector< CountedPtr<Scantable> >& hot,
4952                                              vector< CountedPtr<Scantable> >& cold,
4953                                              int index )
4954{
4955  (void) cold; //currently unused
4956  string reftime = sig->getTime( index ) ;
4957  vector<int> ii( 1, sig->getIF( index ) ) ;
4958  vector<int> ib( 1, sig->getBeam( index ) ) ;
4959  vector<int> ip( 1, sig->getPol( index ) ) ;
4960  vector<int> ic( 1, sig->getScan( index ) ) ;
4961  STSelector sel = STSelector() ;
4962  sel.setIFs( ii ) ;
4963  sel.setBeams( ib ) ;
4964  sel.setPolarizations( ip ) ;
4965  sky[0]->setSelection( sel ) ;
4966  hot[0]->setSelection( sel ) ;
4967  //cold[0]->setSelection( sel ) ;
4968  vector<float> spskys = getSpectrumFromTime( reftime, sky[0], "linear" ) ;
4969  vector<float> sphots = getSpectrumFromTime( reftime, hot[0], "linear" ) ;
4970  //vector<float> spcolds = getSpectrumFromTime( reftime, cold[0], "linear" ) ;
4971  vector<float> tcals = getTcalFromTime( reftime, sky[0], "linear" ) ;
4972  sel.reset() ;
4973  ii[0] = ref->getIF( index ) ;
4974  sel.setIFs( ii ) ;
4975  sel.setBeams( ib ) ;
4976  sel.setPolarizations( ip ) ;
4977  sky[1]->setSelection( sel ) ;
4978  hot[1]->setSelection( sel ) ;
4979  //cold[1]->setSelection( sel ) ;
4980  vector<float> spskyr = getSpectrumFromTime( reftime, sky[1], "linear" ) ;
4981  vector<float> sphotr = getSpectrumFromTime( reftime, hot[1], "linear" ) ;
4982  //vector<float> spcoldr = getSpectrumFromTime( reftime, cold[1], "linear" ) ;
4983  vector<float> tcalr = getTcalFromTime( reftime, sky[1], "linear" ) ; 
4984  vector<float> spref = ref->getSpectrum( index ) ;
4985  vector<float> spsig = sig->getSpectrum( index ) ;
4986  vector<float> sp( tcals.size() ) ;
4987  for ( unsigned int j = 0 ; j < tcals.size() ; j++ ) {
4988    float v = tcals[j] * spsig[j] / ( sphots[j] - spskys[j] ) - tcalr[j] * spref[j] / ( sphotr[j] - spskyr[j] ) ;
4989    sp[j] = v ;
4990  }
4991  sel.reset() ;
4992  sky[0]->unsetSelection() ;
4993  hot[0]->unsetSelection() ;
4994  //cold[0]->unsetSelection() ;
4995  sky[1]->unsetSelection() ;
4996  hot[1]->unsetSelection() ;
4997  //cold[1]->unsetSelection() ;
4998
4999  return sp ;
5000}
Note: See TracBrowser for help on using the repository browser.