source: trunk/src/MSWriter.cpp @ 3058

Last change on this file since 3058 was 3058, checked in by Takeshi Nakazato, 8 years ago

New Development: No

JIRA Issue: Yes CAS-8062

Ready for Test: Yes

Interface Changes: No

What Interface Changed: Please list interface changes

Test Programs: List test programs

Put in Release Notes: Yes/No?

Module(s): Module Names change impacts.

Description: Describe your changes here...

Do not add redundant row to POINTING table.

File size: 80.3 KB
Line 
1//
2// C++ Interface: MSWriter
3//
4// Description:
5//
6// This class is specific writer for MS format
7//
8// Takeshi Nakazato <takeshi.nakazato@nao.ac.jp>, (C) 2010
9//
10// Copyright: See COPYING file that comes with this distribution
11//
12//
13#include <assert.h>
14
15#include <set>
16
17#include <casa/OS/File.h>
18#include <casa/OS/RegularFile.h>
19#include <casa/OS/Directory.h>
20#include <casa/OS/SymLink.h>
21#include <casa/BasicSL/String.h>
22#include <casa/Arrays/Cube.h>
23#include <casa/Containers/RecordField.h>
24
25#include <tables/Tables/ExprNode.h>
26#include <tables/Tables/TableDesc.h>
27#include <tables/Tables/SetupNewTab.h>
28#include <tables/Tables/TableIter.h>
29#include <tables/Tables/RefRows.h>
30#include <tables/Tables/TableRow.h>
31
32#include <ms/MeasurementSets/MeasurementSet.h>
33#include <ms/MeasurementSets/MSColumns.h>
34#include <ms/MSSel/MSPolIndex.h>
35#include <ms/MSSel/MSDataDescIndex.h>
36#include <ms/MSSel/MSSourceIndex.h>
37
38#include "MSWriter.h"
39#include "STHeader.h"
40#include "STFrequencies.h"
41#include "STMolecules.h"
42#include "STTcal.h"
43#include "MathUtils.h"
44#include "TableTraverse.h"
45
46using namespace casa ;
47using namespace std ;
48
49namespace asap {
50
51class CorrTypeHandler {
52public:
53  CorrTypeHandler()
54  {}
55  virtual ~CorrTypeHandler() {}
56  virtual Vector<Stokes::StokesTypes> corrType() = 0 ;
57  virtual void reset()
58  {
59    npol = 0 ;
60  }
61  void append( uInt polno )
62  {
63    polnos[npol] = polno ;
64    npol++ ;
65  }
66  uInt nPol() { return npol ; }
67protected:
68  Vector<Stokes::StokesTypes> polmap ;
69  uInt polnos[4] ;
70  uInt npol ;
71};
72
73class LinearHandler : public CorrTypeHandler {
74public:
75  LinearHandler()
76    : CorrTypeHandler()
77  {
78    initMap() ;
79  }
80  virtual ~LinearHandler() {}
81  virtual Vector<Stokes::StokesTypes> corrType()
82  {
83    Vector<Stokes::StokesTypes> ret( npol, Stokes::Undefined ) ;
84    if ( npol < 4 ) {
85      for ( uInt ipol = 0 ; ipol < npol ; ipol++ )
86        ret[ipol] = polmap[polnos[ipol]] ;
87    }
88    else if ( npol == 4 ) {
89      ret[0] = polmap[0] ;
90      ret[1] = polmap[2] ;
91      ret[2] = polmap[3] ;
92      ret[3] = polmap[1] ;
93    }
94    else {
95      throw( AipsError("npol > 4") ) ;
96    }
97    return ret ;
98  }
99protected:
100  void initMap()
101  {
102    polmap.resize( 4 ) ;
103    polmap[0] = Stokes::XX ;
104    polmap[1] = Stokes::YY ;
105    polmap[2] = Stokes::XY ;
106    polmap[3] = Stokes::YX ;
107  }
108};
109class CircularHandler : public CorrTypeHandler {
110public:
111  CircularHandler()
112    : CorrTypeHandler()
113  {
114    initMap() ;
115  }
116  virtual ~CircularHandler() {}
117  virtual Vector<Stokes::StokesTypes> corrType()
118  {
119    Vector<Stokes::StokesTypes> ret( npol, Stokes::Undefined ) ;
120    if ( npol < 4 ) {
121      for ( uInt ipol = 0 ; ipol < npol ; ipol++ )
122        ret[ipol] = polmap[polnos[ipol]] ;
123    }
124    else if ( npol == 4 ) {
125      ret[0] = polmap[0] ;
126      ret[1] = polmap[2] ;
127      ret[2] = polmap[3] ;
128      ret[3] = polmap[1] ;
129    }
130    else {
131      throw( AipsError("npol > 4") ) ;
132    }
133    return ret ;
134  }
135private:
136  void initMap()
137  {
138    polmap.resize( 4 ) ;
139    polmap[0] = Stokes::RR ;
140    polmap[1] = Stokes::LL ;
141    polmap[2] = Stokes::RL ;
142    polmap[3] = Stokes::LR ;
143  }
144};
145class StokesHandler : public CorrTypeHandler {
146public:
147  StokesHandler()
148    : CorrTypeHandler()
149  {
150    initMap() ;
151  }
152  virtual ~StokesHandler() {}
153  virtual Vector<Stokes::StokesTypes> corrType()
154  {
155    Vector<Stokes::StokesTypes> ret( npol, Stokes::Undefined ) ;
156    if ( npol <= 4 ) {
157      for ( uInt ipol = 0 ; ipol < npol ; ipol++ )
158        ret[ipol] = polmap[polnos[ipol]] ;
159    }
160    else {
161      throw( AipsError("npol > 4") ) ;
162    }
163    return ret ;
164  }
165private:
166  void initMap()
167  {
168    polmap.resize( 4 ) ;
169    polmap[0] = Stokes::I ;
170    polmap[1] = Stokes::Q ;
171    polmap[2] = Stokes::U ;
172    polmap[3] = Stokes::V ;
173  }
174};
175class LinPolHandler : public CorrTypeHandler {
176public:
177  LinPolHandler()
178    : CorrTypeHandler()
179  {
180    initMap() ;
181  }
182  virtual ~LinPolHandler() {}
183  virtual Vector<Stokes::StokesTypes> corrType()
184  {
185    Vector<Stokes::StokesTypes> ret( npol, Stokes::Undefined ) ;
186    if ( npol <= 2 ) {
187      for ( uInt ipol = 0 ; ipol < npol ; ipol++ )
188        ret[ipol] = polmap[polnos[ipol]] ;
189    }
190    else {
191      throw( AipsError("npol > 4") ) ;
192    }
193    return ret ;
194  }
195private:
196  void initMap()
197  {
198    polmap.resize( 2 ) ;
199    polmap[0] = Stokes::Plinear ;
200    polmap[1] = Stokes::Pangle ;
201  }
202};
203
204class DataHolder {
205public:
206  DataHolder( TableRow &tableRow, String polType )
207    : row( tableRow )
208  {
209    nchan = 0 ;
210    npol = 0 ;
211    makeCorrTypeHandler( polType ) ;
212    attach() ;
213    flagRow.resize( 4 ) ;
214    reset() ;
215    sigmaTemplate.resize( 4 ) ;
216    sigmaTemplate = 1.0 ;
217  }
218  virtual ~DataHolder() {}
219  void post()
220  {
221    postData() ;
222    postFlag() ;
223    postFlagRow() ;
224    postAuxiliary() ;
225  }
226  virtual void reset()
227  {
228    corr->reset() ;
229    flagRow = False ;
230    npol = 0 ;
231    for ( uInt i = 0 ; i < 4 ; i++ )
232      isFilled[i] = False ;   
233  }
234  virtual void accumulate( uInt id, Vector<Float> &sp, Vector<Bool> &fl, Bool &flr )
235  {
236    accumulateCorrType( id ) ;
237    accumulateData( id, sp ) ;
238    accumulateFlag( id, fl ) ;
239    accumulateFlagRow( id, flr ) ;
240    isFilled[id] = True;
241  }
242  uInt nPol() { return npol ; }
243  uInt nChan() { return nchan ; }
244  Vector<Int> corrTypeInt()
245  {
246    Vector<Int> v( npol ) ;
247    convertArray( v, corr->corrType() ) ;
248    return v ;
249  }
250  Vector<Stokes::StokesTypes> corrType() { return corr->corrType() ; }
251  void setNchan( uInt num )
252  {
253    nchan = num ;
254    resize() ;
255  }
256protected:
257  void postAuxiliary()
258  {
259    Vector<Float> w = sigmaTemplate( IPosition(1,0), IPosition(1,npol-1) ) ;
260    sigmaRF.define( w ) ;
261    weightRF.define( w ) ;
262    Cube<Bool> c( npol, nchan, 1, False ) ;
263    flagCategoryRF.define( c ) ;
264  }
265  inline void accumulateCorrType( uInt &id )
266  {
267    corr->append( id ) ;
268    npol = corr->nPol() ;
269  }
270  inline void accumulateFlagRow( uInt &id, Bool &flr )
271  {
272    flagRow[id] = flr ;
273  }
274  void postFlagRow()
275  {
276    // CAS-5545 FLAG_ROW must always be set False
277    //*flagRowRF = anyEQ( flagRow, True ) ;
278    *flagRowRF = False;
279  }
280  inline void accumulateFlag( uInt &id, Vector<Bool> &fl )
281  {
282    flag.row( id ) = fl ;
283  }
284  virtual void postFlag() = 0 ;
285  inline void accumulateData( uInt &id, Vector<Float> &sp )
286  {
287    data.row( id ) = sp ;
288  }
289  uInt filledIndex()
290  {
291    uInt idx = 0;
292    while( idx < 4 && !isFilled[idx] ) ++idx;
293    return idx;
294  }
295  virtual void postData() = 0 ;
296  TableRow &row ;
297  uInt nchan ;
298  uInt npol ;
299  CountedPtr<CorrTypeHandler> corr;
300  RecordFieldPtr< Vector<Float> > sigmaRF ;
301  RecordFieldPtr< Vector<Float> > weightRF ;
302  RecordFieldPtr< Array<Bool> > flagRF ;
303  RecordFieldPtr<Bool> flagRowRF ;
304  RecordFieldPtr< Cube<Bool> > flagCategoryRF ;
305  Vector<Bool> flagRow ;
306  Matrix<Bool> flag ;
307  Matrix<Float> data ;
308  Vector<Float> sigmaTemplate ;
309  Bool isFilled[4] ;
310private:
311  void makeCorrTypeHandler( String &polType )
312  {
313    if ( polType == "linear" )
314      corr = new LinearHandler() ;
315    else if ( polType == "circular" )
316      corr = new CircularHandler() ;
317    else if ( polType == "stokes" )
318      corr = new StokesHandler() ;
319    else if ( polType == "linpol" )
320      corr = new LinPolHandler() ;
321    else
322      throw( AipsError("Invalid polarization type") ) ;
323  }
324  void attach()
325  {
326    TableRecord &rec = row.record() ;
327    sigmaRF.attachToRecord( rec, "SIGMA" ) ;
328    weightRF.attachToRecord( rec, "WEIGHT" ) ;
329    flagRF.attachToRecord( rec, "FLAG" ) ;
330    flagRowRF.attachToRecord( rec, "FLAG_ROW" ) ;
331    flagCategoryRF.attachToRecord( rec, "FLAG_CATEGORY" ) ;
332  }
333  void resize()
334  {
335    flag.resize( 4, nchan ) ;
336    data.resize( 4, nchan ) ;
337  }
338};
339
340class FloatDataHolder : public DataHolder {
341public:
342  FloatDataHolder( TableRow &tableRow, String polType )
343    : DataHolder( tableRow, polType )
344  {
345    attachData() ;
346  }
347  virtual ~FloatDataHolder() {}
348protected:
349  virtual void postFlag()
350  {
351    // CAS-5545 FLAG must all be set True if FLAG_ROW is True
352    for (uInt ipol = 0; ipol < 4; ++ipol) {
353      if (isFilled[ipol] and flagRow[ipol]) {
354        flag(IPosition(2, ipol, 0), IPosition(2, ipol, nchan-1)) = True;
355      }
356    }
357   
358    if ( npol == 2 ) {
359      flagRF.define( flag( IPosition( 2, 0, 0 ), IPosition( 2, npol-1, nchan-1 ) ) ) ;
360    }
361    else {
362      // should be npol == 1
363      uInt idx = filledIndex() ;
364      flagRF.define( flag( IPosition( 2, idx, 0 ), IPosition( 2, idx, nchan-1 ) ) ) ;
365    }
366  }
367  virtual void postData()
368  {
369    if ( npol == 2 ) {
370      dataRF.define( data( IPosition( 2, 0, 0 ), IPosition( 2, npol-1, nchan-1 ) ) ) ;
371    }
372    else {
373      // should be npol == 1
374      uInt idx = filledIndex() ;
375      dataRF.define( data( IPosition( 2, idx, 0 ), IPosition( 2, idx, nchan-1 ) ) ) ;
376    }
377  }
378private:
379  void attachData()
380  {
381    dataRF.attachToRecord( row.record(), "FLOAT_DATA" ) ;
382  }
383  RecordFieldPtr< Matrix<Float> > dataRF;
384};
385
386class ComplexDataHolder : public DataHolder {
387public:
388  ComplexDataHolder( TableRow &tableRow, String polType )
389    : DataHolder( tableRow, polType )
390  {
391    attachData() ;
392  }
393  virtual ~ComplexDataHolder() {}
394protected:
395  virtual void postFlag()
396  {
397    // CAS-5545 FLAG must all be set True if FLAG_ROW is True
398    for (uInt ipol = 0; ipol < 4; ++ipol) {
399      if (isFilled[ipol] and flagRow[ipol]) {
400        flag(IPosition(2, ipol, 0), IPosition(2, ipol, nchan-1)) = True;
401      }
402    }
403   
404    if ( npol == 4 ) {
405      Vector<Bool> tmp = flag.row( 3 ) ;
406      flag.row( 3 ) = flag.row( 1 ) ;
407      flag.row( 2 ) = flag.row( 2 ) || tmp ;
408      flag.row( 1 ) = flag.row( 2 ) ;
409      flagRF.define( flag ) ;
410    }
411    else if ( npol == 2 ) {
412      flagRF.define( flag( IPosition( 2, 0, 0 ), IPosition( 2, npol-1, nchan-1 ) ) ) ;
413    }
414    else {
415      // should be npol == 1
416      uInt idx = filledIndex() ;
417      flagRF.define( flag( IPosition( 2, idx, 0 ), IPosition( 2, idx, nchan-1 ) ) ) ;
418    }
419  }
420  virtual void postData()
421  {
422    Matrix<Float> tmp( 2, nchan, 0.0 ) ;
423    Matrix<Complex> v( npol, nchan ) ;
424    if ( isFilled[0] ) {
425      tmp.row( 0 ) = data.row( 0 ) ;
426      v.row( 0 ) = RealToComplex( tmp ) ;
427    }
428    if ( isFilled[1] ) {
429      tmp.row( 0 ) = data.row( 1 ) ;
430      v.row( npol-1 ) = RealToComplex( tmp ) ;
431    }
432    if ( isFilled[2] && isFilled[3] ) {
433      tmp.row( 0 ) = data.row( 2 ) ;
434      tmp.row( 1 ) = data.row( 3 ) ;
435      v.row( 1 ) = RealToComplex( tmp ) ;
436      v.row( 2 ) = conj( v.row( 1 ) ) ;
437    }
438    dataRF.define( v ) ;
439  }
440private:
441  void attachData()
442  {
443    dataRF.attachToRecord( row.record(), "DATA" ) ;
444  }
445  RecordFieldPtr< Matrix<Complex> > dataRF;
446};
447
448class BaseMSWriterVisitor: public TableVisitor {
449  const String *lastFieldName;
450  uInt lastRecordNo;
451  uInt lastBeamNo, lastScanNo, lastIfNo, lastPolNo;
452  Int lastSrcType;
453  uInt lastCycleNo;
454  Double lastTime;
455protected:
456  const Table &table;
457  uInt count;
458public:
459  BaseMSWriterVisitor(const Table &table)
460    : table(table)
461  {
462    static const String dummy;
463    lastFieldName = &dummy;
464    count = 0;
465  }
466 
467  virtual void enterFieldName(const uInt /*recordNo*/, const String &/*columnValue*/) {
468  }
469  virtual void leaveFieldName(const uInt /*recordNo*/, const String &/*columnValue*/) {
470  }
471  virtual void enterBeamNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
472  virtual void leaveBeamNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
473  virtual void enterScanNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
474  virtual void leaveScanNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
475  virtual void enterIfNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
476  virtual void leaveIfNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
477  virtual void enterSrcType(const uInt /*recordNo*/, Int /*columnValue*/) { }
478  virtual void leaveSrcType(const uInt /*recordNo*/, Int /*columnValue*/) { }
479  virtual void enterCycleNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
480  virtual void leaveCycleNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
481  virtual void enterTime(const uInt /*recordNo*/, Double /*columnValue*/) { }
482  virtual void leaveTime(const uInt /*recordNo*/, Double /*columnValue*/) { }
483  virtual void enterPolNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
484  virtual void leavePolNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
485
486  virtual Bool visitRecord(const uInt /*recordNo*/,
487                           const String &/*fieldName*/,
488                           const uInt /*beamNo*/,
489                           const uInt /*scanNo*/,
490                           const uInt /*ifNo*/,
491                           const Int /*srcType*/,
492                           const uInt /*cycleNo*/,
493                           const Double /*time*/,
494                           const uInt /*polNo*/) { return True ;}
495
496  virtual Bool visit(Bool isFirst, const uInt recordNo,
497                     const uInt nCols, void const *const colValues[]) {
498    const String *fieldName = NULL;
499    uInt beamNo, scanNo, ifNo;
500    Int srcType;
501    uInt cycleNo;
502    Double time;
503    uInt polNo;
504    { // prologue
505      uInt i = 0;
506      {
507        const String *col = (const String*)colValues[i++];
508        fieldName = &col[recordNo];
509      }
510      {
511        const uInt *col = (const uInt *)colValues[i++];
512        beamNo = col[recordNo];
513      }
514      {
515        const uInt *col = (const uInt *)colValues[i++];
516        scanNo = col[recordNo];
517      }
518      {
519        const uInt *col = (const uInt *)colValues[i++];
520        ifNo = col[recordNo];
521      }
522      {
523        const Int *col = (const Int *)colValues[i++];
524        srcType = col[recordNo];
525      }
526      {
527        const uInt *col = (const uInt *)colValues[i++];
528        cycleNo = col[recordNo];
529      }
530      {
531        const Double *col = (const Double *)colValues[i++];
532        time = col[recordNo];
533      }
534      {
535        const Int *col = (const Int *)colValues[i++];
536        polNo = col[recordNo];
537      }
538      assert(nCols == i);
539    }
540
541    if (isFirst) {
542      enterFieldName(recordNo, *fieldName);
543      enterBeamNo(recordNo, beamNo);
544      enterScanNo(recordNo, scanNo);
545      enterIfNo(recordNo, ifNo);
546      enterSrcType(recordNo, srcType);
547      enterCycleNo(recordNo, cycleNo);
548      enterTime(recordNo, time);
549      enterPolNo(recordNo, polNo);
550    } else {
551      if (lastFieldName->compare(*fieldName) != 0) {
552        leavePolNo(lastRecordNo, lastPolNo);
553        leaveTime(lastRecordNo, lastTime);
554        leaveCycleNo(lastRecordNo, lastCycleNo);
555        leaveSrcType(lastRecordNo, lastSrcType);
556        leaveIfNo(lastRecordNo, lastIfNo);
557        leaveScanNo(lastRecordNo, lastScanNo);
558        leaveBeamNo(lastRecordNo, lastBeamNo);
559        leaveFieldName(lastRecordNo, *lastFieldName);
560
561        enterFieldName(recordNo, *fieldName);
562        enterBeamNo(recordNo, beamNo);
563        enterScanNo(recordNo, scanNo);
564        enterIfNo(recordNo, ifNo);
565        enterSrcType(recordNo, srcType);
566        enterCycleNo(recordNo, cycleNo);
567        enterTime(recordNo, time);
568        enterPolNo(recordNo, polNo);
569      } else if (lastBeamNo != beamNo) {
570        leavePolNo(lastRecordNo, lastPolNo);
571        leaveTime(lastRecordNo, lastTime);
572        leaveCycleNo(lastRecordNo, lastCycleNo);
573        leaveSrcType(lastRecordNo, lastSrcType);
574        leaveIfNo(lastRecordNo, lastIfNo);
575        leaveScanNo(lastRecordNo, lastScanNo);
576        leaveBeamNo(lastRecordNo, lastBeamNo);
577
578        enterBeamNo(recordNo, beamNo);
579        enterScanNo(recordNo, scanNo);
580        enterIfNo(recordNo, ifNo);
581        enterSrcType(recordNo, srcType);
582        enterCycleNo(recordNo, cycleNo);
583        enterTime(recordNo, time);
584        enterPolNo(recordNo, polNo);
585      } else if (lastScanNo != scanNo) {
586        leavePolNo(lastRecordNo, lastPolNo);
587        leaveTime(lastRecordNo, lastTime);
588        leaveCycleNo(lastRecordNo, lastCycleNo);
589        leaveSrcType(lastRecordNo, lastSrcType);
590        leaveIfNo(lastRecordNo, lastIfNo);
591        leaveScanNo(lastRecordNo, lastScanNo);
592
593        enterScanNo(recordNo, scanNo);
594        enterIfNo(recordNo, ifNo);
595        enterSrcType(recordNo, srcType);
596        enterCycleNo(recordNo, cycleNo);
597        enterTime(recordNo, time);
598        enterPolNo(recordNo, polNo);
599      } else if (lastIfNo != ifNo) {
600        leavePolNo(lastRecordNo, lastPolNo);
601        leaveTime(lastRecordNo, lastTime);
602        leaveCycleNo(lastRecordNo, lastCycleNo);
603        leaveSrcType(lastRecordNo, lastSrcType);
604        leaveIfNo(lastRecordNo, lastIfNo);
605
606        enterIfNo(recordNo, ifNo);
607        enterSrcType(recordNo, srcType);
608        enterCycleNo(recordNo, cycleNo);
609        enterTime(recordNo, time);
610        enterPolNo(recordNo, polNo);
611      } else if (lastSrcType != srcType) {
612        leavePolNo(lastRecordNo, lastPolNo);
613        leaveTime(lastRecordNo, lastTime);
614        leaveCycleNo(lastRecordNo, lastCycleNo);
615        leaveSrcType(lastRecordNo, lastSrcType);
616
617        enterSrcType(recordNo, srcType);
618        enterCycleNo(recordNo, cycleNo);
619        enterTime(recordNo, time);
620        enterPolNo(recordNo, polNo);
621      } else if (lastCycleNo != cycleNo) {
622        leavePolNo(lastRecordNo, lastPolNo);
623        leaveTime(lastRecordNo, lastTime);
624        leaveCycleNo(lastRecordNo, lastCycleNo);
625
626        enterCycleNo(recordNo, cycleNo);
627        enterTime(recordNo, time);
628        enterPolNo(recordNo, polNo);
629      } else if (lastTime != time) {
630        leavePolNo(lastRecordNo, lastPolNo);
631        leaveTime(lastRecordNo, lastTime);
632
633        enterTime(recordNo, time);
634        enterPolNo(recordNo, polNo);
635      } else if (lastPolNo != polNo) {
636        leavePolNo(lastRecordNo, lastPolNo);
637        enterPolNo(recordNo, polNo);
638      }
639    }
640    count++;
641    Bool result = visitRecord(recordNo, *fieldName, beamNo, scanNo, ifNo, srcType,
642                              cycleNo, time, polNo);
643
644    { // epilogue
645      lastRecordNo = recordNo;
646
647      lastFieldName = fieldName;
648      lastBeamNo = beamNo;
649      lastScanNo = scanNo;
650      lastIfNo = ifNo;
651      lastSrcType = srcType;
652      lastCycleNo = cycleNo;
653      lastTime = time;
654      lastPolNo = polNo;
655    }
656    return result ;
657  }
658
659  virtual void finish() {
660    if (count > 0) {
661      leavePolNo(lastRecordNo, lastPolNo);
662      leaveTime(lastRecordNo, lastTime);
663      leaveCycleNo(lastRecordNo, lastCycleNo);
664      leaveSrcType(lastRecordNo, lastSrcType);
665      leaveIfNo(lastRecordNo, lastIfNo);
666      leaveScanNo(lastRecordNo, lastScanNo);
667      leaveBeamNo(lastRecordNo, lastBeamNo);
668      leaveFieldName(lastRecordNo, *lastFieldName);
669    }
670  }
671};
672
673class MSWriterVisitor: public BaseMSWriterVisitor, public MSWriterUtils {
674public:
675  MSWriterVisitor(const Table &table, Table &mstable)
676    : BaseMSWriterVisitor(table),
677      ms(mstable),
678      addScanrate_(False),
679      pointingTimeList_(table.nrow(), -1.0),
680      referenceBeam_(-1)
681  {
682    rowidx = 0 ;
683    fieldName = "" ;
684    defaultFieldId = 0 ;
685    spwId = -1 ;
686    subscan = 1 ;
687    ptName = "" ;
688    srcId = 0 ;
689   
690    row = TableRow( ms ) ;
691
692    initPolarization() ;
693    initFrequencies() ;
694
695    //
696    // add rows to MS
697    //
698    uInt addrow = table.nrow() ;
699    ms.addRow( addrow ) ;
700
701    // attach to Scantable columns
702    spectraCol.attach( table, "SPECTRA" ) ;
703    flagtraCol.attach( table, "FLAGTRA" ) ;
704    flagRowCol.attach( table, "FLAGROW" ) ;
705    tcalIdCol.attach( table, "TCAL_ID" ) ;
706    intervalCol.attach( table, "INTERVAL" ) ;
707    directionCol.attach( table, "DIRECTION" ) ;
708    scanRateCol.attach( table, "SCANRATE" ) ;
709    timeCol.attach( table, "TIME" ) ;
710    freqIdCol.attach( table, "FREQ_ID" ) ;
711    sourceNameCol.attach( table, "SRCNAME" ) ;
712    sourceDirectionCol.attach( table, "SRCDIRECTION" ) ;
713    fieldNameCol.attach( table, "FIELDNAME" ) ;
714
715    // MS subtables
716    attachSubtables() ;
717
718    // attach to MS columns
719    attachMain() ;
720    attachPointing() ;
721
722    // decide whether put SCANRATE to MS POINTING column
723    if (anyNE(scanRateCol.getColumn(), (Double)0.0)) {
724      addScanrate_ = True;
725    }
726  }
727 
728  virtual void enterFieldName(const uInt recordNo, const String &/*columnValue*/) {
729    //printf("%u: FieldName: %s\n", recordNo, columnValue.c_str());
730    fieldName = fieldNameCol.asString( recordNo ) ;
731    String::size_type pos = fieldName.find( "__" ) ;
732    if ( pos != String::npos ) {
733      fieldId = String::toInt( fieldName.substr( pos+2 ) ) ;
734      fieldName = fieldName.substr( 0, pos ) ;
735    }
736    else {
737      fieldId = defaultFieldId ;
738      defaultFieldId++ ;
739    }
740    Double tSec = timeCol.asdouble( recordNo ) * 86400.0 ;
741    Vector<Double> srcDir = sourceDirectionCol( recordNo ) ;
742    Vector<Double> srate = scanRateCol( recordNo ) ;
743    String srcName = sourceNameCol.asString( recordNo ) ;
744
745    addField( fieldId, fieldName, srcName, srcDir, srate, tSec ) ;
746
747    // put value
748    *fieldIdRF = fieldId ;
749  }
750  virtual void leaveFieldName(const uInt /*recordNo*/, const String &/*columnValue*/) {
751  }
752  virtual void enterBeamNo(const uInt /*recordNo*/, uInt columnValue) {
753    //printf("%u: BeamNo: %u\n", recordNo, columnValue);
754   
755    feedId = (Int)columnValue ;
756    if (referenceBeam_ < 0) {
757      referenceBeam_ = feedId;
758      LogIO os;
759      os << "Reference beam is " << referenceBeam_ << LogIO::POST;
760    }
761
762    // put value
763    *feed1RF = feedId ;
764    *feed2RF = feedId ;
765  }
766  virtual void leaveBeamNo(const uInt /*recordNo*/, uInt /*columnValue*/) {
767  }
768  virtual void enterScanNo(const uInt /*recordNo*/, uInt columnValue) {
769    //printf("%u: ScanNo: %u\n", recordNo, columnValue);
770
771    // put value
772    // CAS-5841: SCANNO should be consistent with MS SCAN_NUMBER
773    *scanNumberRF = (Int)columnValue ;
774  }
775  virtual void leaveScanNo(const uInt /*recordNo*/, uInt /*columnValue*/) {
776    subscan = 1 ;
777  }
778  virtual void enterIfNo(const uInt recordNo, uInt columnValue) {
779    //printf("%u: IfNo: %u\n", recordNo, columnValue);
780
781    spwId = (Int)columnValue ;
782    uInt freqId = freqIdCol.asuInt( recordNo ) ;
783
784    Vector<Float> sp = spectraCol( recordNo ) ;
785    uInt nchan = sp.nelements() ;
786    holder->setNchan( nchan ) ;
787
788    addSpectralWindow( spwId, freqId ) ;
789
790    addFeed( feedId, spwId ) ;
791  }
792  virtual void leaveIfNo(const uInt /*recordNo*/, uInt /*columnValue*/) {
793  }
794  virtual void enterSrcType(const uInt /*recordNo*/, Int columnValue) {
795    //printf("%u: SrcType: %d\n", recordNo, columnValue);
796
797    Int stateId = addState( columnValue ) ;
798
799    // put value
800    *stateIdRF = stateId ;
801  }
802  virtual void leaveSrcType(const uInt /*recordNo*/, Int /*columnValue*/) {
803  }
804  virtual void enterCycleNo(const uInt /*recordNo*/, uInt /*columnValue*/) {
805    //printf("%u: CycleNo: %u\n", recordNo, columnValue);
806  }
807  virtual void leaveCycleNo(const uInt /*recordNo*/, uInt /*columnValue*/) {
808  }
809  virtual void enterTime(const uInt recordNo, Double columnValue) {
810    //printf("%u: Time: %f\n", recordNo, columnValue);
811
812    Double timeSec = columnValue * 86400.0 ;
813    Double interval = intervalCol.asdouble( recordNo ) ;
814
815    // add POINTING row only when 1) BEAMNO is 0 and
816    // 2) there is no row corresponding to the current timestamp
817    //LogIO os;
818    //os << "feedId = " << feedId << LogIO::POST;
819    if ( ptName.empty() && //feedId == referenceBeam_ &&
820        (potab.nrow() == 0 || allNE(pointingTimeList_(Slice(0, potab.nrow())), timeSec))) {
821      LogIO os;
822      os << LogIO::DEBUGGING << "ROW " << recordNo << " Beam " << feedId
823          << ": adding pointing row, potab.nrow() = " << potab.nrow() << LogIO::POST;
824      pointingTimeList_[potab.nrow()] = timeSec;
825      Vector<Double> dir = directionCol( recordNo ) ;
826      Vector<Double> rate = scanRateCol( recordNo ) ;
827      if (feedId != referenceBeam_) {
828        os << LogIO::DEBUGGING << "TODO: Need to store pointing direction of reference beam"
829            << " if only non-reference beam row is available for certain timestamp" << LogIO::POST;
830      }
831      //if ( anyNE( rate, 0.0 ) ) {
832      if (addScanrate_) {
833        Matrix<Double> msdir( 2, 2 ) ;
834        msdir.column( 0 ) = dir ;
835        msdir.column( 1 ) = rate ;
836        addPointing( timeSec, interval, msdir ) ;
837      }
838      else {
839        Matrix<Double> msdir( 2, 1 ) ;
840        msdir.column( 0 ) = dir ;
841        addPointing( timeSec, interval, msdir ) ;
842      }
843    }
844
845    // put value
846    *timeRF = timeSec ;
847    *timeCentroidRF = timeSec ;
848    *intervalRF = interval ;
849    *exposureRF = interval ;
850  }
851  virtual void leaveTime(const uInt /*recordNo*/, Double /*columnValue*/) {
852    if ( holder->nPol() > 0 ) {
853      Int polId = addPolarization() ;
854      Int ddId = addDataDescription( polId, spwId ) ;
855       
856      // put field
857      *dataDescIdRF = ddId ;
858      holder->post() ;
859     
860      // commit row
861      row.put( rowidx ) ;
862      rowidx++ ;
863
864      // reset holder
865      holder->reset() ;
866    }
867  }
868  virtual void enterPolNo(const uInt /*recordNo*/, uInt /*columnValue*/) {
869    //printf("%u: PolNo: %d\n", recordNo, columnValue);
870  }
871  virtual void leavePolNo(const uInt /*recordNo*/, uInt /*columnValue*/) {
872  }
873
874  virtual Bool visitRecord(const uInt recordNo,
875                           const String &/*fieldName*/,
876                           const uInt /*beamNo*/,
877                           const uInt /*scanNo*/,
878                           const uInt /*ifNo*/,
879                           const Int /*srcType*/,
880                           const uInt /*cycleNo*/,
881                           const Double /*time*/,
882                           const uInt polNo) {
883    //printf("%u: %s, %u, %u, %u, %d, %u, %f, %d\n", recordNo,
884    //       fieldName.c_str(), beamNo, scanNo, ifNo, srcType, cycleNo, time, polNo);
885
886    Vector<Float> sp = spectraCol( recordNo ) ;
887    Vector<uChar> tmp = flagtraCol( recordNo ) ;
888    Vector<Bool> fl( tmp.shape() ) ;
889    convertArray( fl, tmp ) ;
890    Bool flr = (Bool)flagRowCol.asuInt( recordNo ) ;
891    holder->accumulate( polNo, sp, fl, flr ) ;
892
893    return True ;
894  }
895
896  virtual void finish() {
897    BaseMSWriterVisitor::finish();
898    //printf("Total: %u\n", count);
899
900    // remove rows
901    if ( ms.nrow() > rowidx ) {
902      uInt numRemove = ms.nrow() - rowidx ;
903      //cout << "numRemove = " << numRemove << endl ;
904      Vector<uInt> rows( numRemove ) ;
905      indgen( rows, rowidx ) ;
906      ms.removeRow( rows ) ;
907    }
908
909    // fill empty SPECTRAL_WINDOW rows
910    infillSpectralWindow() ;
911
912    // fill empty FIELD rows
913    infillField() ;
914  }
915
916  void dataColumnName( String name )
917  {
918    if ( name == "DATA" )
919      holder = new ComplexDataHolder( row, poltype ) ;
920    else if ( name == "FLOAT_DATA" )
921      holder = new FloatDataHolder( row, poltype ) ;
922  }
923  void pointingTableName( String name ) {
924    ptName = name ;
925  }
926  void setSourceRecord( Record &r ) {
927    srcRec = r ;
928  }
929private:
930  void addField( Int &fid, String &fname, String &srcName,
931                 Vector<Double> &sdir, Vector<Double> &srate,
932                 Double &tSec )
933  {
934    uInt nrow = fieldtab.nrow() ;
935    while( (Int)nrow <= fid ) {
936      fieldtab.addRow( 1, True ) ;
937      nrow++ ;
938    }
939
940    Matrix<Double> dir ;
941    Int numPoly = 0 ;
942    if ( anyNE( srate, 0.0 ) ) {
943      dir.resize( 2, 2 ) ;
944      dir.column( 0 ) = sdir ;
945      dir.column( 1 ) = srate ;
946      numPoly = 1 ;
947    }
948    else {
949      dir.resize( 2, 1 ) ;
950      dir.column( 0 ) = sdir ;
951    }
952    srcId = srcRec.asInt( srcName ) ;
953
954    TableRow tr( fieldtab ) ;
955    TableRecord &r = tr.record() ;
956    putField( "NAME", r, fname ) ;
957    putField( "NUM_POLY", r, numPoly ) ;
958    putField( "TIME", r, tSec ) ;
959    putField( "SOURCE_ID", r, srcId ) ;
960    defineField( "DELAY_DIR", r, dir ) ;
961    defineField( "REFERENCE_DIR", r, dir ) ;
962    defineField( "PHASE_DIR", r, dir ) ;
963    tr.put( fid ) ;
964
965    // for POINTING table
966    *poNameRF = fname ;
967  }
968  Int addState( Int &id )
969  {
970    String obsMode ;
971    Bool isSignal ;
972    Double tnoise ;
973    Double tload ;
974    queryType( id, obsMode, isSignal, tnoise, tload ) ;
975
976    String key = obsMode+"_"+String::toString( subscan ) ;
977    Int idx = -1 ;
978    uInt nEntry = stateEntry.nelements() ;
979    for ( uInt i = 0 ; i < nEntry ; i++ ) {
980      if ( stateEntry[i] == key ) {
981        idx = i ;
982        break ;
983      }
984    }
985    if ( idx == -1 ) {
986      uInt nrow = statetab.nrow() ;
987      statetab.addRow( 1, True ) ;
988      TableRow tr( statetab ) ;
989      TableRecord &r = tr.record() ;
990      putField( "OBS_MODE", r, obsMode ) ;
991      putField( "SIG", r, isSignal ) ;
992      isSignal = !isSignal ;
993      putField( "REF", r, isSignal ) ;
994      putField( "CAL", r, tnoise ) ;
995      putField( "LOAD", r, tload ) ;
996      tr.put( nrow ) ;
997      idx = nrow ;
998
999      stateEntry.resize( nEntry+1, True ) ;
1000      stateEntry[nEntry] = key ;
1001    }
1002    subscan++ ;
1003
1004    return idx ;
1005  }
1006  void addPointing( Double &tSec, Double &interval, Matrix<Double> &dir )
1007  {
1008    uInt nrow = potab.nrow() ;
1009    potab.addRow() ;
1010
1011    *poNumPolyRF = dir.ncolumn() - 1 ;
1012    *poTimeRF = tSec ;
1013    *poTimeOriginRF = tSec ;
1014    *poIntervalRF = interval ;
1015    poDirectionRF.define( dir ) ;
1016    poTargetRF.define( dir ) ;
1017    porow.put( nrow ) ;
1018  }
1019  Int addPolarization()
1020  {
1021    Int idx = -1 ;
1022    Vector<Int> corrType = holder->corrTypeInt() ;
1023    uInt nEntry = polEntry.size() ;
1024    for ( uInt i = 0 ; i < nEntry ; i++ ) {
1025      if ( polEntry[i].conform( corrType ) && allEQ( polEntry[i], corrType ) ) {
1026        idx = i ;
1027        break ;
1028      }
1029    }
1030   
1031    Int numCorr = holder->nPol() ;
1032    Matrix<Int> corrProduct = corrProductTemplate[numCorr].copy() ;
1033    if ( numCorr == 1 && (corrType[0] == Stokes::YY || corrType[0] == Stokes::LL ) ) {
1034      corrProduct = 1;
1035    }
1036
1037    if ( idx == -1 ) {
1038      uInt nrow = poltab.nrow() ;
1039      poltab.addRow( 1, True ) ;
1040      TableRow tr( poltab ) ;
1041      TableRecord &r = tr.record() ;
1042      putField( "NUM_CORR", r, numCorr ) ;
1043      defineField( "CORR_TYPE", r, corrType ) ;
1044      defineField( "CORR_PRODUCT", r, corrProduct ) ;
1045      tr.put( nrow ) ;
1046      idx = nrow ;
1047
1048      polEntry.resize( nEntry+1 ) ;
1049      polEntry[nEntry] = corrType ;
1050    }
1051
1052    return idx ;
1053  }
1054  Int addDataDescription( Int pid, Int sid )
1055  {
1056    Int idx = -1 ;
1057    uInt nItem = 2 ;
1058    uInt len = ddEntry.nelements() ;
1059    uInt nEntry = len / nItem ;
1060    const Int *dd_p = ddEntry.storage() ;
1061    for ( uInt i = 0 ; i < nEntry ; i++ ) {
1062      Int pol = *dd_p ;
1063      dd_p++ ;
1064      Int spw = *dd_p ;
1065      dd_p++ ;
1066      if ( pid == pol && sid == spw ) {
1067        idx = i ;
1068        break ;
1069      }
1070    }
1071
1072    if ( idx == -1 ) {
1073      uInt nrow = ddtab.nrow() ;
1074      ddtab.addRow( 1, True ) ;
1075      TableRow tr( ddtab ) ;
1076      TableRecord &r = tr.record() ;
1077      putField( "POLARIZATION_ID", r, pid ) ;
1078      putField( "SPECTRAL_WINDOW_ID", r, sid ) ;
1079      tr.put( nrow ) ;
1080      idx = nrow ;
1081
1082      ddEntry.resize( len+nItem ) ;
1083      ddEntry[len] = pid ;
1084      ddEntry[len+1] = sid ;
1085    }
1086
1087    return idx ;
1088  }
1089  void infillSpectralWindow()
1090  {
1091    ROScalarColumn<Int> nchanCol( spwtab, "NUM_CHAN" ) ;
1092    Vector<Int> nchan = nchanCol.getColumn() ;
1093    TableRow tr( spwtab ) ;
1094    TableRecord &r = tr.record() ;
1095    Int mfr = freqframe ;
1096    Int oneChan = 1 ;
1097    Vector<Double> dummy( 1, 0.0 ) ;
1098    putField( "MEAS_FREQ_REF", r, mfr ) ;
1099    defineField( "CHAN_FREQ", r, dummy ) ;
1100    defineField( "CHAN_WIDTH", r, dummy ) ;
1101    defineField( "EFFECTIVE_BW", r, dummy ) ;
1102    defineField( "RESOLUTION", r, dummy ) ;
1103    putField( "NUM_CHAN", r, oneChan ) ;
1104
1105    for ( uInt i = 0 ; i < spwtab.nrow() ; i++ ) {
1106      if ( nchan[i] == 0 )
1107        tr.put( i ) ;
1108    }
1109  }
1110  void infillField()
1111  {
1112    ScalarColumn<Int> sourceIdCol(fieldtab, "SOURCE_ID");
1113    ArrayColumn<Double> delayDirCol(fieldtab, "DELAY_DIR");
1114    ArrayColumn<Double> phaseDirCol(fieldtab, "PHASE_DIR");
1115    ArrayColumn<Double> referenceDirCol(fieldtab, "REFERENCE_DIR");
1116    uInt nrow = fieldtab.nrow();
1117    Matrix<Double> dummy(IPosition(2, 2, 1), 0.0);
1118    for (uInt irow = 0; irow < nrow; ++irow) {
1119      if (!phaseDirCol.isDefined(irow)) {
1120        delayDirCol.put(irow, dummy);
1121        phaseDirCol.put(irow, dummy);
1122        referenceDirCol.put(irow, dummy);
1123        sourceIdCol.put(irow, -1);
1124      }
1125    }
1126  }
1127  void addSpectralWindow( Int sid, uInt fid )
1128  {
1129    if (processedFreqId.find((uInt)fid) == processedFreqId.end()
1130        || processedIFNO.find((uInt)sid) == processedIFNO.end() ) {
1131      uInt nrow = spwtab.nrow() ;
1132      while( (Int)nrow <= sid ) {
1133        spwtab.addRow( 1, True ) ;
1134        nrow++ ;
1135      }
1136      processedFreqId.insert((uInt)fid);
1137      processedIFNO.insert((uInt)sid);
1138    }
1139    else {
1140      return ;
1141    }
1142     
1143
1144    Double rp = refpix[fid] ;
1145    Double rv = refval[fid] ;
1146    Double ic = increment[fid] ;
1147
1148    Int mfrInt = (Int)freqframe ;
1149    Int nchan = holder->nChan() ;
1150    Double bw = nchan * abs( ic ) ;
1151    Double reffreq = rv - rp * ic ;
1152    Int netsb = 0 ; // USB->0, LSB->1
1153    if ( ic < 0 )
1154      netsb = 1 ;
1155    Vector<Double> res( nchan, abs(ic) ) ;
1156    Vector<Double> cw( nchan, ic ) ;
1157    Vector<Double> chanf( nchan ) ;
1158    indgen( chanf, reffreq, ic ) ;
1159
1160    TableRow tr( spwtab ) ;
1161    TableRecord &r = tr.record() ;
1162    putField( "MEAS_FREQ_REF", r, mfrInt ) ;
1163    putField( "NUM_CHAN", r, nchan ) ;
1164    putField( "TOTAL_BANDWIDTH", r, bw ) ;
1165    putField( "REF_FREQUENCY", r, reffreq ) ;
1166    putField( "NET_SIDEBAND", r, netsb ) ;
1167    defineField( "RESOLUTION", r, res ) ;
1168//     defineField( "CHAN_WIDTH", r, res ) ;
1169    defineField( "CHAN_WIDTH", r, cw ) ;
1170    defineField( "EFFECTIVE_BW", r, res ) ;
1171    defineField( "CHAN_FREQ", r, chanf ) ;
1172    tr.put( sid ) ;
1173  }
1174  void addFeed( Int fid, Int sid )
1175  {
1176    Int idx = -1 ;
1177    uInt nItem = 2 ;
1178    uInt len = feedEntry.nelements() ;
1179    uInt nEntry = len / nItem ;
1180    const Int *fe_p = feedEntry.storage() ;
1181    for ( uInt i = 0 ; i < nEntry ; i++ ) {
1182      Int feed = *fe_p ;
1183      fe_p++ ;
1184      Int spw = *fe_p ;
1185      fe_p++ ;
1186      if ( fid == feed && sid == spw ) {
1187        idx = i ;
1188        break ;
1189      }
1190    }
1191
1192
1193    if ( idx == -1 ) {
1194      uInt nrow = feedtab.nrow() ;
1195      feedtab.addRow( 1, True ) ;
1196      Int numReceptors = 2 ;
1197      Vector<String> polType( numReceptors ) ;
1198      Matrix<Double> beamOffset( 2, numReceptors, 0.0 ) ;
1199      Vector<Double> receptorAngle( numReceptors, 0.0 ) ;
1200      if ( poltype == "linear" ) {
1201        polType[0] = "X" ;
1202        polType[1] = "Y" ;
1203      }
1204      else if ( poltype == "circular" ) {
1205        polType[0] = "R" ;
1206        polType[1] = "L" ;
1207      }
1208      else {
1209        polType[0] = "X" ;
1210        polType[1] = "Y" ;
1211      }
1212      Matrix<Complex> polResponse( numReceptors, numReceptors, 0.0 ) ;
1213     
1214      TableRow tr( feedtab ) ;
1215      TableRecord &r = tr.record() ;
1216      putField( "FEED_ID", r, fid ) ;
1217      putField( "BEAM_ID", r, fid ) ;
1218      Int tmp = 0 ;
1219      putField( "ANTENNA_ID", r, tmp ) ;
1220      putField( "SPECTRAL_WINDOW_ID", r, sid ) ;
1221      putField( "NUM_RECEPTORS", r, numReceptors ) ;
1222      defineField( "POLARIZATION_TYPE", r, polType ) ;
1223      defineField( "BEAM_OFFSET", r, beamOffset ) ;
1224      defineField( "RECEPTOR_ANGLE", r, receptorAngle ) ;
1225      defineField( "POL_RESPONSE", r, polResponse ) ;
1226      tr.put( nrow ) ;
1227
1228      feedEntry.resize( len+nItem ) ;
1229      feedEntry[len] = fid ;
1230      feedEntry[len+1] = sid ;
1231    }
1232  }
1233  void initPolarization()
1234  {
1235    const TableRecord &keys = table.keywordSet() ;
1236    poltype = keys.asString( "POLTYPE" ) ;
1237
1238    initCorrProductTemplate() ;
1239  }
1240  void initFrequencies()
1241  {
1242    const TableRecord &keys = table.keywordSet() ;
1243    Table tab = keys.asTable( "FREQUENCIES" ) ;
1244    ROScalarColumn<uInt> idcol( tab, "ID" ) ;
1245    ROScalarColumn<Double> rpcol( tab, "REFPIX" ) ;
1246    ROScalarColumn<Double> rvcol( tab, "REFVAL" ) ;
1247    ROScalarColumn<Double> iccol( tab, "INCREMENT" ) ;
1248    Vector<uInt> id = idcol.getColumn() ;
1249    Vector<Double> rp = rpcol.getColumn() ;
1250    Vector<Double> rv = rvcol.getColumn() ;
1251    Vector<Double> ic = iccol.getColumn() ;
1252    for ( uInt i = 0 ; i < id.nelements() ; i++ ) {
1253      refpix.insert( pair<uInt,Double>( id[i], rp[i] ) ) ;
1254      refval.insert( pair<uInt,Double>( id[i], rv[i] ) ) ;
1255      increment.insert( pair<uInt,Double>( id[i], ic[i] ) ) ;
1256    }
1257    String frameStr = tab.keywordSet().asString( "BASEFRAME" ) ;
1258    MFrequency::getType( freqframe, frameStr ) ;
1259  }
1260  void attachSubtables()
1261  {
1262    //const TableRecord &keys = table.keywordSet() ;
1263    TableRecord &mskeys = ms.rwKeywordSet() ;
1264
1265    // FIELD table
1266    fieldtab = mskeys.asTable( "FIELD" ) ;
1267
1268    // SPECTRAL_WINDOW table
1269    spwtab = mskeys.asTable( "SPECTRAL_WINDOW" ) ;
1270
1271    // POINTING table
1272    potab = mskeys.asTable( "POINTING" ) ;
1273
1274    // POLARIZATION table
1275    poltab = mskeys.asTable( "POLARIZATION" ) ;
1276
1277    // DATA_DESCRIPTION table
1278    ddtab = mskeys.asTable( "DATA_DESCRIPTION" ) ;
1279
1280    // STATE table
1281    statetab = mskeys.asTable( "STATE" ) ;
1282
1283    // FEED table
1284    feedtab = mskeys.asTable( "FEED" ) ;
1285  }
1286  void attachMain()
1287  {
1288    TableRecord &r = row.record() ;
1289    dataDescIdRF.attachToRecord( r, "DATA_DESC_ID" ) ;
1290    timeRF.attachToRecord( r, "TIME" ) ;
1291    timeCentroidRF.attachToRecord( r, "TIME_CENTROID" ) ;
1292    intervalRF.attachToRecord( r, "INTERVAL" ) ;
1293    exposureRF.attachToRecord( r, "EXPOSURE" ) ;
1294    fieldIdRF.attachToRecord( r, "FIELD_ID" ) ;
1295    feed1RF.attachToRecord( r, "FEED1" ) ;
1296    feed2RF.attachToRecord( r, "FEED2" ) ;
1297    scanNumberRF.attachToRecord( r, "SCAN_NUMBER" ) ;
1298    stateIdRF.attachToRecord( r, "STATE_ID" ) ;
1299
1300    // constant values
1301    //Int id = 0 ;
1302    RecordFieldPtr<Int> intRF( r, "OBSERVATION_ID" ) ;
1303    *intRF = 0 ;
1304    intRF.attachToRecord( r, "ANTENNA1" ) ;
1305    *intRF = 0 ;
1306    intRF.attachToRecord( r, "ANTENNA2" ) ;
1307    *intRF = 0 ;
1308    intRF.attachToRecord( r, "ARRAY_ID" ) ;
1309    *intRF = 0 ;
1310    intRF.attachToRecord( r, "PROCESSOR_ID" ) ;
1311    *intRF = 0 ;
1312    RecordFieldPtr< Vector<Double> > arrayRF( r, "UVW" ) ;
1313    arrayRF.define( Vector<Double>( 3, 0.0 ) ) ;
1314  }
1315  void attachPointing()
1316  {
1317    porow = TableRow( potab ) ;
1318    TableRecord &r = porow.record() ;
1319    poNumPolyRF.attachToRecord( r, "NUM_POLY" ) ;
1320    poTimeRF.attachToRecord( r, "TIME" ) ;
1321    poTimeOriginRF.attachToRecord( r, "TIME_ORIGIN" ) ;
1322    poIntervalRF.attachToRecord( r, "INTERVAL" ) ;
1323    poNameRF.attachToRecord( r, "NAME" ) ;
1324    poDirectionRF.attachToRecord( r, "DIRECTION" ) ;
1325    poTargetRF.attachToRecord( r, "TARGET" ) ;
1326   
1327    // constant values
1328    RecordFieldPtr<Int> antIdRF( r, "ANTENNA_ID" ) ;
1329    *antIdRF = 0 ;
1330    RecordFieldPtr<Bool> trackingRF( r, "TRACKING" ) ;
1331    *trackingRF = True ;
1332  }
1333  void queryType( Int type, String &stype, Bool &b, Double &t, Double &l )
1334  {
1335    t = 0.0 ;
1336    l = 0.0 ;
1337
1338    String sep1="#" ;
1339    String sep2="," ;
1340    String target="OBSERVE_TARGET" ;
1341    String atmcal="CALIBRATE_TEMPERATURE" ;
1342    String onstr="ON_SOURCE" ;
1343    String offstr="OFF_SOURCE" ;
1344    String pswitch="POSITION_SWITCH" ;
1345    String nod="NOD" ;
1346    String fswitch="FREQUENCY_SWITCH" ;
1347    String sigstr="SIG" ;
1348    String refstr="REF" ;
1349    String unspecified="UNSPECIFIED" ;
1350    String ftlow="LOWER" ;
1351    String fthigh="HIGHER" ;
1352    switch ( type ) {
1353    case SrcType::PSON:
1354      stype = target+sep1+onstr+sep2+pswitch ;
1355      b = True ;
1356      break ;
1357    case SrcType::PSOFF:
1358      stype = target+sep1+offstr+sep2+pswitch ;
1359      b = False ;
1360      break ;
1361    case SrcType::NOD:
1362      stype = target+sep1+onstr+sep2+nod ;
1363      b = True ;
1364      break ;
1365    case SrcType::FSON:
1366      stype = target+sep1+onstr+sep2+fswitch+sep1+sigstr ;
1367      b = True ;
1368      break ;
1369    case SrcType::FSOFF:
1370      stype = target+sep1+onstr+sep2+fswitch+sep1+refstr ;
1371      b = False ;
1372      break ;
1373    case SrcType::SKY:
1374      stype = atmcal+sep1+offstr+sep2+unspecified ;
1375      b = False ;
1376      break ;
1377    case SrcType::HOT:
1378      stype = atmcal+sep1+offstr+sep2+unspecified ;
1379      b = False ;
1380      break ;
1381    case SrcType::WARM:
1382      stype = atmcal+sep1+offstr+sep2+unspecified ;
1383      b = False ;
1384      break ;
1385    case SrcType::COLD:
1386      stype = atmcal+sep1+offstr+sep2+unspecified ;
1387      b = False ;
1388      break ;
1389    case SrcType::PONCAL:
1390      stype = atmcal+sep1+onstr+sep2+pswitch ;
1391      b = True ;
1392      break ;
1393    case SrcType::POFFCAL:
1394      stype = atmcal+sep1+offstr+sep2+pswitch ;
1395      b = False ;
1396      break ;
1397    case SrcType::NODCAL:
1398      stype = atmcal+sep1+onstr+sep2+nod ;
1399      b = True ;
1400      break ;
1401    case SrcType::FONCAL:
1402      stype = atmcal+sep1+onstr+sep2+fswitch+sep1+sigstr ;
1403      b = True ;
1404      break ;
1405    case SrcType::FOFFCAL:
1406      stype = atmcal+sep1+offstr+sep2+fswitch+sep1+refstr ;
1407      b = False ;
1408      break ;
1409    case SrcType::FSLO:
1410      stype = target+sep1+onstr+sep2+fswitch+sep1+ftlow ;
1411      b = True ;
1412      break ;
1413    case SrcType::FLOOFF:
1414      stype = target+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1415      b = False ;
1416      break ;
1417    case SrcType::FLOSKY:
1418      stype = atmcal+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1419      b = False ;
1420      break ;
1421    case SrcType::FLOHOT:
1422      stype = atmcal+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1423      b = False ;
1424      break ;
1425    case SrcType::FLOWARM:
1426      stype = atmcal+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1427      b = False ;
1428      break ;
1429    case SrcType::FLOCOLD:
1430      stype = atmcal+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1431      b = False ;
1432      break ;
1433    case SrcType::FSHI:
1434      stype = target+sep1+onstr+sep2+fswitch+sep1+fthigh ;
1435      b = True ;
1436      break ;
1437    case SrcType::FHIOFF:
1438      stype = target+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1439      b = False ;
1440      break ;
1441    case SrcType::FHISKY:
1442      stype = atmcal+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1443      b = False ;
1444      break ;
1445    case SrcType::FHIHOT:
1446      stype = atmcal+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1447      b = False ;
1448      break ;
1449    case SrcType::FHIWARM:
1450      stype = atmcal+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1451      b = False ;
1452      break ;
1453    case SrcType::FHICOLD:
1454      stype = atmcal+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1455      b = False ;
1456      break ;
1457    case SrcType::SIG:
1458      stype = target+sep1+onstr+sep2+unspecified ;
1459      b = True ;
1460      break ;
1461    case SrcType::REF:
1462      stype = target+sep1+offstr+sep2+unspecified ;
1463      b = False ;
1464      break ;
1465    default:
1466      stype = unspecified ;
1467      b = True ;
1468      break ;
1469    }
1470  }
1471  void initCorrProductTemplate()
1472  {
1473    Int n = 1 ;
1474    {
1475      Matrix<Int> c( 2, n, 0 ) ;
1476      corrProductTemplate[n] = c ;
1477    }
1478    n = 2 ;
1479    {
1480      Matrix<Int> c( 2, n, 0 ) ;
1481      c.column( 1 ) = 1 ;
1482      corrProductTemplate[n] = c ;
1483    }
1484    n = 4 ;
1485    {
1486      Matrix<Int> c( 2, n, 0 ) ;
1487      c( 0, 2 ) = 1 ;
1488      c( 0, 3 ) = 1 ;
1489      c( 1, 1 ) = 1 ;
1490      c( 1, 3 ) = 1 ;
1491      corrProductTemplate[n] = c ;
1492    }
1493  }
1494
1495  Table &ms;
1496  TableRow row;
1497  uInt rowidx;
1498  String fieldName;
1499  Int fieldId;
1500  Int srcId;
1501  Int defaultFieldId;
1502  Int spwId;
1503  Int feedId;
1504  Int subscan;
1505  CountedPtr<DataHolder> holder;
1506  String ptName;
1507  Bool useFloat;
1508  String poltype;
1509  Bool addScanrate_;
1510
1511  // MS subtables
1512  Table spwtab;
1513  Table statetab;
1514  Table ddtab;
1515  Table poltab;
1516  Table fieldtab;
1517  Table feedtab;
1518  Table potab;
1519
1520  // Scantable MAIN columns
1521  ROArrayColumn<Float> spectraCol;
1522  ROArrayColumn<Double> directionCol,scanRateCol,sourceDirectionCol;
1523  ROArrayColumn<uChar> flagtraCol;
1524  ROTableColumn tcalIdCol,intervalCol,flagRowCol,timeCol,freqIdCol,
1525    sourceNameCol,fieldNameCol;
1526
1527  // MS MAIN columns
1528  RecordFieldPtr<Int> dataDescIdRF,fieldIdRF,feed1RF,feed2RF,
1529    scanNumberRF,stateIdRF;
1530  RecordFieldPtr<Double> timeRF,timeCentroidRF,intervalRF,exposureRF;
1531
1532  // MS POINTING columns
1533  TableRow porow;
1534  RecordFieldPtr<Int> poNumPolyRF ;
1535  RecordFieldPtr<Double> poTimeRF,
1536    poTimeOriginRF,
1537    poIntervalRF ;
1538  RecordFieldPtr<String> poNameRF ;
1539  RecordFieldPtr< Matrix<Double> > poDirectionRF,
1540    poTargetRF ;
1541
1542  Vector<String> stateEntry;
1543  Block<Int> ddEntry;
1544  Block<Int> feedEntry;
1545  vector< Vector<Int> > polEntry;
1546  set<uInt> processedFreqId;
1547  set<uInt> processedIFNO;
1548  map<uInt,Double> refpix;
1549  map<uInt,Double> refval;
1550  map<uInt,Double> increment;
1551  MFrequency::Types freqframe;
1552  Record srcRec;
1553  map< Int, Matrix<Int> > corrProductTemplate;
1554  Vector<Double> pointingTimeList_;
1555  Int referenceBeam_;
1556};
1557
1558class BaseMSSysCalVisitor: public TableVisitor {
1559  uInt lastRecordNo;
1560  uInt lastBeamNo, lastIfNo, lastPolNo;
1561  Double lastTime;
1562protected:
1563  const Table &table;
1564  uInt count;
1565public:
1566  BaseMSSysCalVisitor(const Table &table)
1567    : table(table)
1568  {
1569    count = 0;
1570  }
1571 
1572  virtual void enterBeamNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
1573  virtual void leaveBeamNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
1574  virtual void enterIfNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
1575  virtual void leaveIfNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
1576  virtual void enterPolNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
1577  virtual void leavePolNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
1578  virtual void enterTime(const uInt /*recordNo*/, Double /*columnValue*/) { }
1579  virtual void leaveTime(const uInt /*recordNo*/, Double /*columnValue*/) { }
1580
1581  virtual Bool visitRecord(const uInt /*recordNo*/,
1582                           const uInt /*beamNo*/,
1583                           const uInt /*ifNo*/,
1584                           const uInt /*polNo*/,
1585                           const Double /*time*/) { return True ;}
1586
1587  virtual Bool visit(Bool isFirst, const uInt recordNo,
1588                     const uInt nCols, void const *const colValues[]) {
1589    uInt beamNo, ifNo, polNo;
1590    Double time;
1591    { // prologue
1592      uInt i = 0;
1593      {
1594        const uInt *col = (const uInt *)colValues[i++];
1595        beamNo = col[recordNo];
1596      }
1597      {
1598        const uInt *col = (const uInt *)colValues[i++];
1599        ifNo = col[recordNo];
1600      }
1601      {
1602        const Double *col = (const Double *)colValues[i++];
1603        time = col[recordNo];
1604      }
1605      {
1606        const uInt *col = (const uInt *)colValues[i++];
1607        polNo = col[recordNo];
1608      }
1609      assert(nCols == i);
1610    }
1611
1612    if (isFirst) {
1613      enterBeamNo(recordNo, beamNo);
1614      enterIfNo(recordNo, ifNo);
1615      enterTime(recordNo, time);
1616      enterPolNo(recordNo, polNo);
1617    } else {
1618      if (lastBeamNo != beamNo) {
1619        leavePolNo(lastRecordNo, lastPolNo);
1620        leaveTime(lastRecordNo, lastTime);
1621        leaveIfNo(lastRecordNo, lastIfNo);
1622        leaveBeamNo(lastRecordNo, lastBeamNo);
1623
1624        enterBeamNo(recordNo, beamNo);
1625        enterIfNo(recordNo, ifNo);
1626        enterTime(recordNo, time);
1627        enterPolNo(recordNo, polNo);
1628      } else if (lastIfNo != ifNo) {
1629        leavePolNo(lastRecordNo, lastPolNo);
1630        leaveTime(lastRecordNo, lastTime);
1631        leaveIfNo(lastRecordNo, lastIfNo);
1632       
1633        enterIfNo(recordNo, ifNo);
1634        enterTime(recordNo, time);
1635        enterPolNo(recordNo, polNo);
1636      } else if (lastTime != time) {
1637        leavePolNo(lastRecordNo, lastPolNo);
1638        leaveTime(lastRecordNo, lastTime);
1639
1640        enterTime(recordNo, time);
1641        enterPolNo(recordNo, polNo);
1642      } else if (lastPolNo != polNo) {
1643        leavePolNo(lastRecordNo, lastPolNo);
1644        enterPolNo(recordNo, polNo);
1645      }
1646    }
1647    count++;
1648    Bool result = visitRecord(recordNo, beamNo, ifNo, polNo, time);
1649
1650    { // epilogue
1651      lastRecordNo = recordNo;
1652
1653      lastBeamNo = beamNo;
1654      lastIfNo = ifNo;
1655      lastPolNo = polNo;
1656      lastTime = time;
1657    }
1658    return result ;
1659  }
1660
1661  virtual void finish() {
1662    if (count > 0) {
1663      leavePolNo(lastRecordNo, lastPolNo);
1664      leaveTime(lastRecordNo, lastTime);
1665      leaveIfNo(lastRecordNo, lastIfNo);
1666      leaveBeamNo(lastRecordNo, lastBeamNo);
1667    }
1668  }
1669};
1670
1671class BaseTsysHolder
1672{
1673public:
1674  BaseTsysHolder( ROArrayColumn<Float> &tsysCol )
1675    : col( tsysCol ),
1676      nchan(0)
1677  {
1678    reset() ;
1679  }
1680  virtual ~BaseTsysHolder() {}
1681  virtual Array<Float> getTsys() = 0 ;
1682  void setNchan( uInt n ) { nchan = n ; }
1683  void appendTsys( uInt row )
1684  {
1685    Vector<Float> v = col( row ) ;
1686    uInt len = tsys.nrow() ;
1687    tsys.resize( len+1, nchan, True ) ;
1688    if ( v.nelements() == nchan )
1689      tsys.row( len ) = v ;
1690    else
1691      tsys.row( len ) = v[0] ;
1692  }
1693  void setTsys( uInt row, uInt idx )
1694  {
1695    if ( idx >= nrow() )
1696      appendTsys( row ) ;
1697    else {
1698      Vector<Float> v = col( row ) ;
1699      if ( v.nelements() == nchan )
1700        tsys.row( idx ) = v ;
1701      else
1702        tsys.row( idx ) = v[0] ;
1703    }
1704  }
1705  void reset()
1706  {
1707    tsys.resize() ;
1708  }
1709  uInt nrow() { return tsys.nrow() ; }
1710  Bool isEffective()
1711  {
1712    return ( !(tsys.empty()) && anyNE( tsys, (Float)1.0 ) ) ;
1713  }
1714  BaseTsysHolder &operator= ( const BaseTsysHolder &v )
1715  {
1716    if ( this != &v )
1717      tsys.assign( v.tsys ) ;
1718    return *this ;
1719  }
1720protected:
1721  ROArrayColumn<Float> col ;
1722  Matrix<Float> tsys ;
1723  uInt nchan ;
1724};
1725
1726class TsysHolder : public BaseTsysHolder
1727{
1728public:
1729  TsysHolder( ROArrayColumn<Float> &tsysCol )
1730    : BaseTsysHolder( tsysCol )
1731  {}
1732  virtual ~TsysHolder() {}
1733  virtual Array<Float> getTsys()
1734  {
1735    return tsys.column( 0 ) ;
1736  }
1737};
1738
1739class TsysSpectrumHolder : public BaseTsysHolder
1740{
1741public:
1742  TsysSpectrumHolder( ROArrayColumn<Float> &tsysCol )
1743    : BaseTsysHolder( tsysCol )
1744  {}
1745  virtual ~TsysSpectrumHolder() {}
1746  virtual Array<Float> getTsys()
1747  {
1748    return tsys ;
1749  }
1750};
1751
1752class BaseTcalProcessor
1753{
1754public:
1755  BaseTcalProcessor( ROArrayColumn<Float> &tcalCol )
1756    : col_( tcalCol )
1757  {}
1758  virtual ~BaseTcalProcessor() {}
1759  void setTcalId( Vector<uInt> &tcalId ) { id_.assign( tcalId ) ; }
1760  virtual Array<Float> getTcal() = 0 ;
1761protected:
1762  ROArrayColumn<Float> col_ ;
1763  Vector<uInt> id_ ;
1764};
1765
1766class TcalProcessor : public BaseTcalProcessor
1767{
1768public:
1769  TcalProcessor( ROArrayColumn<Float> &tcalCol )
1770    : BaseTcalProcessor( tcalCol )
1771  {}
1772  virtual ~TcalProcessor() {}
1773  virtual Array<Float> getTcal()
1774  {
1775    uInt npol = id_.nelements() ;
1776    Vector<Float> tcal( npol ) ;
1777    for ( uInt ipol = 0 ; ipol < npol ; ipol++ )
1778      tcal[ipol] = col_( id_[ipol] ).data()[0] ;
1779    //cout << "TcalProcessor: tcal = " << tcal << endl ;
1780    return tcal ;
1781  }
1782};
1783
1784class TcalSpectrumProcessor : public BaseTcalProcessor
1785{
1786public:
1787  TcalSpectrumProcessor( ROArrayColumn<Float> &tcalCol )
1788    : BaseTcalProcessor( tcalCol )
1789  {}
1790  virtual ~TcalSpectrumProcessor() {}
1791  virtual Array<Float> getTcal()
1792  {
1793    uInt npol = id_.nelements() ;
1794    //Vector<Float> tcal0 = col_( 0 ) ;
1795    Vector<Float> tcal0 = col_( id_[0] ) ;
1796    uInt nchan = tcal0.nelements() ;
1797    Matrix<Float> tcal( npol, nchan ) ;
1798    tcal.row( 0 ) = tcal0 ;
1799    for ( uInt ipol = 1 ; ipol < npol ; ipol++ )
1800      tcal.row( ipol ) = col_( id_[ipol] ) ;
1801    return tcal ;
1802  }
1803};
1804
1805class MSSysCalVisitor : public BaseMSSysCalVisitor
1806{
1807public:
1808  MSSysCalVisitor( const Table &from, Table &to )
1809    : BaseMSSysCalVisitor( from ),
1810      sctab( to ),
1811      rowidx( 0 ),
1812      polno_()
1813  {
1814    scrow = TableRow( sctab ) ;
1815
1816    lastTcalId.resize() ;
1817    theTcalId.resize() ;
1818    startTime = 0.0 ;
1819    endTime = 0.0 ;
1820
1821    const TableRecord &keys = table.keywordSet() ;
1822    Table tcalTable = keys.asTable( "TCAL" ) ;
1823    tcalCol.attach( tcalTable, "TCAL" ) ;
1824    tsysCol.attach( table, "TSYS" ) ;
1825    tcalIdCol.attach( table, "TCAL_ID" ) ;
1826    intervalCol.attach( table, "INTERVAL" ) ;
1827    effectiveTcal.resize( tcalTable.nrow() ) ;
1828    for ( uInt irow = 0 ; irow < tcalTable.nrow() ; irow++ ) {
1829      if ( allEQ( tcalCol( irow ), (Float)1.0 ) )
1830        effectiveTcal[irow] = False ;
1831      else
1832        effectiveTcal[irow] = True ;
1833    }
1834   
1835    TableRecord &r = scrow.record() ;
1836    RecordFieldPtr<Int> antennaIdRF( r, "ANTENNA_ID" ) ;
1837    *antennaIdRF = 0 ;
1838    feedIdRF.attachToRecord( r, "FEED_ID" ) ;
1839    specWinIdRF.attachToRecord( r, "SPECTRAL_WINDOW_ID" ) ;
1840    timeRF.attachToRecord( r, "TIME" ) ;
1841    intervalRF.attachToRecord( r, "INTERVAL" ) ;
1842    if ( r.isDefined( "TCAL" ) ) {
1843      tcalRF.attachToRecord( r, "TCAL" ) ;
1844      tcalProcessor = new TcalProcessor( tcalCol ) ;
1845    }
1846    else if ( r.isDefined( "TCAL_SPECTRUM" ) ) {
1847      tcalRF.attachToRecord( r, "TCAL_SPECTRUM" ) ;
1848      tcalProcessor = new TcalSpectrumProcessor( tcalCol ) ;
1849    }
1850    if ( r.isDefined( "TSYS" ) ) {
1851      tsysRF.attachToRecord( r, "TSYS" ) ;
1852      theTsys = new TsysHolder( tsysCol ) ;
1853      lastTsys = new TsysHolder( tsysCol ) ;
1854    }
1855    else {
1856      tsysRF.attachToRecord( r, "TSYS_SPECTRUM" ) ;
1857      theTsys = new TsysSpectrumHolder( tsysCol ) ;
1858      lastTsys = new TsysSpectrumHolder( tsysCol ) ;
1859    }
1860
1861  }
1862
1863  virtual void enterBeamNo(const uInt /*recordNo*/, uInt columnValue)
1864  {
1865    *feedIdRF = (Int)columnValue ;
1866  }
1867  virtual void leaveBeamNo(const uInt /*recordNo*/, uInt /*columnValue*/)
1868  {
1869  }
1870  virtual void enterIfNo(const uInt recordNo, uInt columnValue)
1871  {
1872    //cout << "enterIfNo" << endl ;
1873    ROArrayColumn<Float> sp( table, "SPECTRA" ) ;
1874    uInt nchan = sp( recordNo ).nelements() ;
1875    theTsys->setNchan( nchan ) ;
1876    lastTsys->setNchan( nchan ) ;
1877
1878    *specWinIdRF = (Int)columnValue ;
1879  }
1880  virtual void leaveIfNo(const uInt /*recordNo*/, uInt /*columnValue*/)
1881  {
1882    //cout << "leaveIfNo" << endl ;
1883    post() ;
1884    reset(true);
1885    startTime = 0.0 ;
1886    endTime = 0.0 ;
1887  }
1888  virtual void enterTime(const uInt recordNo, Double columnValue)
1889  {
1890    //cout << "enterTime" << endl ;
1891    interval = intervalCol.asdouble( recordNo ) ;
1892    // start time and end time
1893    if ( startTime == 0.0 ) {
1894      startTime = columnValue * 86400.0 - 0.5 * interval ;
1895      endTime = columnValue * 86400.0 + 0.5 * interval ;
1896    }
1897  }
1898  virtual void leaveTime(const uInt /*recordNo*/, Double columnValue)
1899  {
1900    //cout << "leaveTime" << endl ;
1901    if ( isUpdated() ) {
1902      post() ;
1903      *lastTsys = *theTsys ;
1904      lastTcalId = theTcalId ;
1905      reset(false);
1906      startTime = columnValue * 86400.0 - 0.5 * interval ;
1907      endTime = columnValue * 86400.0 + 0.5 * interval ;
1908    }
1909    else {
1910      endTime = columnValue * 86400.0 + 0.5 * interval ;
1911    }
1912  }
1913  virtual void enterPolNo(const uInt recordNo, uInt columnValue)
1914  {
1915    //cout << "enterPolNo" << endl ;
1916    Vector<Float> tsys = tsysCol( recordNo ) ;
1917    uInt tcalId = tcalIdCol.asuInt( recordNo ) ;
1918    polno_.insert( columnValue ) ;
1919    uInt numPol = polno_.size() ;
1920    if ( lastTsys->nrow() < numPol )
1921      lastTsys->appendTsys( recordNo ) ;
1922    if ( lastTcalId.nelements() <= numPol )
1923      appendTcalId( lastTcalId, tcalId, numPol-1 ) ;
1924    if ( theTsys->nrow() < numPol )
1925      theTsys->appendTsys( recordNo ) ;
1926    else {
1927      theTsys->setTsys( recordNo, numPol-1 ) ;
1928    }
1929    if ( theTcalId.nelements() < numPol )
1930      appendTcalId( theTcalId, tcalId, numPol-1 ) ;
1931    else
1932      setTcalId( theTcalId, tcalId, numPol-1 ) ;
1933  }
1934  virtual void leavePolNo( const uInt /*recordNo*/, uInt /*columnValue*/ )
1935  {
1936  }
1937   
1938private:
1939  void reset(bool completely)
1940  {
1941    if (completely) {
1942      lastTsys->reset() ;
1943      lastTcalId.resize() ;
1944    }
1945    theTsys->reset() ;
1946    theTcalId.resize() ;
1947    polno_.clear();
1948  }
1949  void appendTcalId( Vector<uInt> &v, uInt &elem, uInt polId )
1950  {
1951    v.resize( polId+1, True ) ;
1952    v[polId] = elem ;
1953  }
1954  void setTcalId( Vector<uInt> &v, uInt &elem, uInt polId )
1955  {
1956    v[polId] = elem ;
1957  }
1958  void post()
1959  {
1960    // check if given Tcal and Tsys is effective
1961    Bool isEffective = False ;
1962    for ( uInt ipol = 0 ; ipol < lastTcalId.nelements() ; ipol++ ) {
1963      if ( effectiveTcal[lastTcalId[ipol]] ) {
1964        isEffective = True ;
1965        break ;
1966      }
1967    }
1968    if ( !isEffective ) {
1969      if ( !(lastTsys->isEffective()) )
1970        return ;
1971    }
1972
1973    //cout << " interval: " << (endTime-startTime) << " lastTcalId = " << lastTcalId << endl ;
1974    Double midTime = 0.5 * ( startTime + endTime ) ;
1975    Double interval = endTime - startTime ;
1976    *timeRF = midTime ;
1977    *intervalRF = interval ;
1978    tcalProcessor->setTcalId( lastTcalId ) ;
1979    Array<Float> tcal = tcalProcessor->getTcal() ;
1980    Array<Float> tsys = lastTsys->getTsys() ;
1981    tcalRF.define( tcal ) ;
1982    tsysRF.define( tsys ) ;
1983    sctab.addRow( 1, True ) ;
1984    scrow.put( rowidx ) ;
1985    rowidx++ ;
1986  }
1987 
1988  Bool isUpdated()
1989  {
1990    Bool ret = (anyNE( theTcalId, lastTcalId ) || anyNE( theTsys->getTsys(), lastTsys->getTsys() )) ;
1991    return ret ;
1992  }
1993
1994  Table &sctab;
1995  TableRow scrow;
1996  uInt rowidx;
1997
1998  Double startTime,endTime,interval;
1999 
2000  CountedPtr<BaseTsysHolder> lastTsys,theTsys;
2001  Vector<uInt> lastTcalId,theTcalId;
2002  set<uInt> polno_;
2003  CountedPtr<BaseTcalProcessor> tcalProcessor ;
2004  Vector<Bool> effectiveTcal;
2005
2006  RecordFieldPtr<Int> feedIdRF,specWinIdRF;
2007  RecordFieldPtr<Double> timeRF,intervalRF;
2008  RecordFieldPtr< Array<Float> > tcalRF,tsysRF;
2009
2010  ROArrayColumn<Float> tsysCol,tcalCol;
2011  ROTableColumn tcalIdCol,intervalCol;
2012};
2013
2014MSWriter::MSWriter(CountedPtr<Scantable> stable)
2015  : table_(stable),
2016    mstable_(NULL),
2017    isWeather_(False),
2018    tcalSpec_(False),
2019    tsysSpec_(False),
2020    ptTabName_("")
2021{
2022  os_ = LogIO() ;
2023  os_.origin( LogOrigin( "MSWriter", "MSWriter()", WHERE ) ) ;
2024//   os_ << "MSWriter::MSWriter()" << LogIO::POST ;
2025
2026  // initialize writer
2027  init() ;
2028}
2029
2030MSWriter::~MSWriter()
2031{
2032  os_.origin( LogOrigin( "MSWriter", "~MSWriter()", WHERE ) ) ;
2033//   os_ << "MSWriter::~MSWriter()" << LogIO::POST ;
2034
2035  if ( mstable_ != 0 )
2036    delete mstable_ ;
2037}
2038
2039bool MSWriter::write(const string& filename, const Record& rec)
2040{
2041  os_.origin( LogOrigin( "MSWriter", "write()", WHERE ) ) ;
2042  //double startSec = mathutil::gettimeofday_sec() ;
2043  //os_ << "start MSWriter::write() startSec=" << startSec << LogIO::POST ;
2044
2045  filename_ = filename ;
2046
2047  // parsing MS options
2048  Bool overwrite = False ;
2049  if ( rec.isDefined( "ms" ) ) {
2050    Record msrec = rec.asRecord( "ms" ) ;
2051    if ( msrec.isDefined( "overwrite" ) ) {
2052      overwrite = msrec.asBool( "overwrite" ) ;
2053    }
2054  }
2055
2056  os_ << "Parsing MS options" << endl ;
2057  os_ << "   overwrite = " << overwrite << LogIO::POST ;
2058
2059  File file( filename_ ) ;
2060  if ( file.exists() ) {
2061    if ( overwrite ) {
2062      os_ << filename_ << " exists. Overwrite existing data... " << LogIO::POST ;
2063      if ( file.isRegular() ) RegularFile(file).remove() ;
2064      else if ( file.isDirectory() ) Directory(file).removeRecursive() ;
2065      else SymLink(file).remove() ;
2066    }
2067    else {
2068      os_ << LogIO::SEVERE << "ERROR: " << filename_ << " exists..." << LogIO::POST ;
2069      return False ;
2070    }
2071  }
2072
2073  // set up MS
2074  setupMS() ;
2075 
2076  // subtables
2077  // OBSERVATION
2078  fillObservation() ;
2079
2080  // ANTENNA
2081  fillAntenna() ;
2082
2083  // PROCESSOR
2084  fillProcessor() ;
2085
2086  // SOURCE
2087  fillSource() ;
2088
2089  // WEATHER
2090  if ( isWeather_ )
2091    fillWeather() ;
2092
2093  // SYSCAL
2094  fillSysCal() ;
2095
2096  /***
2097   * Start iteration using TableVisitor
2098   ***/
2099  {
2100    static const char *cols[] = {
2101      "FIELDNAME", "BEAMNO", "SCANNO", "IFNO", "SRCTYPE", "CYCLENO", "TIME",
2102      "POLNO",
2103      NULL
2104    };
2105    static const TypeManagerImpl<uInt> tmUInt;
2106    static const TypeManagerImpl<Int> tmInt;
2107    static const TypeManagerImpl<Double> tmDouble;
2108    static const TypeManagerImpl<String> tmString;
2109    static const TypeManager *const tms[] = {
2110      &tmString, &tmUInt, &tmUInt, &tmUInt, &tmInt, &tmUInt, &tmDouble, &tmUInt, NULL
2111    };
2112    //double t0 = mathutil::gettimeofday_sec() ;
2113    MSWriterVisitor myVisitor(table_->table(),*mstable_);
2114    //double t1 = mathutil::gettimeofday_sec() ;
2115    //cout << "MSWriterVisitor(): elapsed time " << t1-t0 << " sec" << endl ;
2116    String dataColName = "FLOAT_DATA" ;
2117    if ( useData_ )
2118      dataColName = "DATA" ;
2119    myVisitor.dataColumnName( dataColName ) ;
2120    myVisitor.pointingTableName( ptTabName_ ) ;
2121    myVisitor.setSourceRecord( srcRec_ ) ;
2122    //double t2 = mathutil::gettimeofday_sec() ;
2123    traverseTable(table_->table(), cols, tms, &myVisitor);
2124    //double t3 = mathutil::gettimeofday_sec() ;
2125    //cout << "traverseTable(): elapsed time " << t3-t2 << " sec" << endl ;
2126  }
2127  /***
2128   * End iteration using TableVisitor
2129   ***/
2130
2131  // ASDM tables
2132  const TableRecord &stKeys = table_->table().keywordSet() ;
2133  TableRecord &msKeys = mstable_->rwKeywordSet() ;
2134  uInt nfields = stKeys.nfields() ;
2135  for ( uInt ifield = 0 ; ifield < nfields ; ifield++ ) {
2136    String kname = stKeys.name( ifield ) ;
2137    if ( kname.find( "ASDM" ) != String::npos ) {
2138      String asdmpath = stKeys.asString( ifield ) ;
2139      os_ << "found ASDM table: " << asdmpath << LogIO::POST ;
2140      if ( Table::isReadable( asdmpath ) ) {
2141        Table newAsdmTab( asdmpath, Table::Old ) ;
2142        newAsdmTab.copy( filename_+"/"+kname, Table::New ) ;
2143        os_ << "add subtable: " << kname << LogIO::POST ;
2144        msKeys.defineTable( kname, Table( filename_+"/"+kname, Table::Old ) ) ;
2145      }
2146    }
2147  }
2148
2149  // replace POINTING table with original one if exists
2150  if ( ptTabName_ != "" ) {
2151    delete mstable_ ;
2152    mstable_ = 0 ;
2153    Table newPtTab( ptTabName_, Table::Old ) ;
2154    newPtTab.copy( filename_+"/POINTING", Table::New ) ;
2155  }
2156
2157  //double endSec = mathutil::gettimeofday_sec() ;
2158  //os_ << "end MSWriter::write() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2159
2160  os_ << "Exported data as MS" << LogIO::POST ;
2161
2162  return True ;
2163}
2164
2165void MSWriter::init()
2166{
2167//   os_.origin( LogOrigin( "MSWriter", "init()", WHERE ) ) ;
2168//   double startSec = mathutil::gettimeofday_sec() ;
2169//   os_ << "start MSWriter::init() startSec=" << startSec << LogIO::POST ;
2170 
2171  // access to scantable
2172  header_ = table_->getHeader() ;
2173
2174  // FLOAT_DATA? or DATA?
2175  if ( header_.npol > 2 ) {
2176    useFloatData_ = False ;
2177    useData_ = True ;
2178  }
2179  else {
2180    useFloatData_ = True ;
2181    useData_ = False ;
2182  }
2183
2184  // polarization type
2185  polType_ = header_.poltype ;
2186  if ( polType_ == "" )
2187    polType_ = "stokes" ;
2188  else if ( polType_.find( "linear" ) != String::npos )
2189    polType_ = "linear" ;
2190  else if ( polType_.find( "circular" ) != String::npos )
2191    polType_ = "circular" ;
2192  else if ( polType_.find( "stokes" ) != String::npos )
2193    polType_ = "stokes" ;
2194  else if ( polType_.find( "linpol" ) != String::npos )
2195    polType_ = "linpol" ;
2196  else
2197    polType_ = "notype" ;
2198
2199  // Check if some subtables are exists
2200  Bool isTcal = False ;
2201  if ( table_->tcal().table().nrow() != 0 ) {
2202    ROTableColumn col( table_->tcal().table(), "TCAL" ) ;
2203    if ( col.isDefined( 0 ) ) {
2204      os_ << "TCAL table exists: nrow=" << table_->tcal().table().nrow() << LogIO::POST ;
2205      isTcal = True ;
2206    }
2207    else {
2208      os_ << "No TCAL rows" << LogIO::POST ;
2209    }
2210  }
2211  else {
2212    os_ << "No TCAL rows" << LogIO::POST ;
2213  }
2214  if ( table_->weather().table().nrow() != 0 ) {
2215    ROTableColumn col( table_->weather().table(), "TEMPERATURE" ) ;
2216    if ( col.isDefined( 0 ) ) {
2217      os_ << "WEATHER table exists: nrow=" << table_->weather().table().nrow() << LogIO::POST ;
2218      isWeather_ =True ;
2219    }
2220    else {
2221      os_ << "No WEATHER rows" << LogIO::POST ;
2222    }
2223  }
2224  else {
2225    os_ << "No WEATHER rows" << LogIO::POST ;
2226  }
2227
2228  // Are TCAL_SPECTRUM and TSYS_SPECTRUM necessary?
2229  if ( header_.nchan != 1 ) {
2230    if ( isTcal ) {
2231      // examine TCAL subtable
2232      Table tcaltab = table_->tcal().table() ;
2233      ROArrayColumn<Float> tcalCol( tcaltab, "TCAL" ) ;
2234      for ( uInt irow = 0 ; irow < tcaltab.nrow() ; irow++ ) {
2235        if ( tcalCol( irow ).size() != 1 )
2236          tcalSpec_ = True ;
2237      }
2238    }
2239    // examine spectral data
2240    TableIterator iter0( table_->table(), "IFNO" ) ;
2241    while( !iter0.pastEnd() ) {
2242      Table t0( iter0.table() ) ;
2243      ROArrayColumn<Float> sharedFloatArrCol( t0, "SPECTRA" ) ;
2244      uInt len = sharedFloatArrCol( 0 ).size() ;
2245      if ( len != 1 ) {
2246        sharedFloatArrCol.attach( t0, "TSYS" ) ;
2247        if ( sharedFloatArrCol( 0 ).size() != 1 )
2248          tsysSpec_ = True ;
2249      }
2250      iter0.next() ;
2251    }
2252  }
2253
2254  // check if reference for POINTING table exists
2255  const TableRecord &rec = table_->table().keywordSet() ;
2256  if ( rec.isDefined( "POINTING" ) ) {
2257    ptTabName_ = rec.asString( "POINTING" ) ;
2258    if ( !Table::isReadable( ptTabName_ ) ) {
2259      ptTabName_ = "" ;
2260    }
2261  }
2262
2263//   double endSec = mathutil::gettimeofday_sec() ;
2264//   os_ << "end MSWriter::init() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2265}
2266
2267void MSWriter::setupMS()
2268{
2269//   os_.origin( LogOrigin( "MSWriter", "setupMS()", WHERE ) ) ;
2270//   double startSec = mathutil::gettimeofday_sec() ;
2271//   os_ << "start MSWriter::setupMS() startSec=" << startSec << LogIO::POST ;
2272 
2273  String dunit = table_->getHeader().fluxunit ;
2274
2275  TableDesc msDesc = MeasurementSet::requiredTableDesc() ;
2276  if ( useFloatData_ )
2277    MeasurementSet::addColumnToDesc( msDesc, MSMainEnums::FLOAT_DATA, 2 ) ;
2278  else if ( useData_ )
2279    MeasurementSet::addColumnToDesc( msDesc, MSMainEnums::DATA, 2 ) ;
2280
2281  SetupNewTable newtab( filename_, msDesc, Table::New ) ;
2282
2283  mstable_ = new MeasurementSet( newtab ) ;
2284
2285  TableColumn col ;
2286  if ( useFloatData_ )
2287    col.attach( *mstable_, "FLOAT_DATA" ) ;
2288  else if ( useData_ )
2289    col.attach( *mstable_, "DATA" ) ;
2290  col.rwKeywordSet().define( "UNIT", dunit ) ;
2291
2292  // create subtables
2293  TableDesc antennaDesc = MSAntenna::requiredTableDesc() ;
2294  SetupNewTable antennaTab( mstable_->antennaTableName(), antennaDesc, Table::New ) ;
2295  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::ANTENNA ), Table( antennaTab ) ) ;
2296
2297  TableDesc dataDescDesc = MSDataDescription::requiredTableDesc() ;
2298  SetupNewTable dataDescTab( mstable_->dataDescriptionTableName(), dataDescDesc, Table::New ) ;
2299  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::DATA_DESCRIPTION ), Table( dataDescTab ) ) ;
2300
2301  TableDesc dopplerDesc = MSDoppler::requiredTableDesc() ;
2302  SetupNewTable dopplerTab( mstable_->dopplerTableName(), dopplerDesc, Table::New ) ;
2303  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::DOPPLER ), Table( dopplerTab ) ) ;
2304
2305  TableDesc feedDesc = MSFeed::requiredTableDesc() ;
2306  SetupNewTable feedTab( mstable_->feedTableName(), feedDesc, Table::New ) ;
2307  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FEED ), Table( feedTab ) ) ;
2308
2309  TableDesc fieldDesc = MSField::requiredTableDesc() ;
2310  SetupNewTable fieldTab( mstable_->fieldTableName(), fieldDesc, Table::New ) ;
2311  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FIELD ), Table( fieldTab ) ) ;
2312
2313  TableDesc flagCmdDesc = MSFlagCmd::requiredTableDesc() ;
2314  SetupNewTable flagCmdTab( mstable_->flagCmdTableName(), flagCmdDesc, Table::New ) ;
2315  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FLAG_CMD ), Table( flagCmdTab ) ) ;
2316
2317  TableDesc freqOffsetDesc = MSFreqOffset::requiredTableDesc() ;
2318  SetupNewTable freqOffsetTab( mstable_->freqOffsetTableName(), freqOffsetDesc, Table::New ) ;
2319  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FREQ_OFFSET ), Table( freqOffsetTab ) ) ;
2320
2321  TableDesc historyDesc = MSHistory::requiredTableDesc() ;
2322  SetupNewTable historyTab( mstable_->historyTableName(), historyDesc, Table::New ) ;
2323  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::HISTORY ), Table( historyTab ) ) ;
2324
2325  TableDesc observationDesc = MSObservation::requiredTableDesc() ;
2326  SetupNewTable observationTab( mstable_->observationTableName(), observationDesc, Table::New ) ;
2327  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::OBSERVATION ), Table( observationTab ) ) ;
2328
2329  TableDesc pointingDesc = MSPointing::requiredTableDesc() ;
2330  SetupNewTable pointingTab( mstable_->pointingTableName(), pointingDesc, Table::New ) ;
2331  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::POINTING ), Table( pointingTab ) ) ;
2332
2333  TableDesc polarizationDesc = MSPolarization::requiredTableDesc() ;
2334  SetupNewTable polarizationTab( mstable_->polarizationTableName(), polarizationDesc, Table::New ) ;
2335  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::POLARIZATION ), Table( polarizationTab ) ) ;
2336
2337  TableDesc processorDesc = MSProcessor::requiredTableDesc() ;
2338  SetupNewTable processorTab( mstable_->processorTableName(), processorDesc, Table::New ) ;
2339  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::PROCESSOR ), Table( processorTab ) ) ;
2340
2341  TableDesc sourceDesc = MSSource::requiredTableDesc() ;
2342  MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::TRANSITION, 1 ) ;
2343  MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::REST_FREQUENCY, 1 ) ;
2344  MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::SYSVEL, 1 ) ;
2345  SetupNewTable sourceTab( mstable_->sourceTableName(), sourceDesc, Table::New ) ;
2346  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SOURCE ), Table( sourceTab ) ) ;
2347
2348  TableDesc spwDesc = MSSpectralWindow::requiredTableDesc() ;
2349  SetupNewTable spwTab( mstable_->spectralWindowTableName(), spwDesc, Table::New ) ;
2350  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SPECTRAL_WINDOW ), Table( spwTab ) ) ;
2351
2352  TableDesc stateDesc = MSState::requiredTableDesc() ;
2353  SetupNewTable stateTab( mstable_->stateTableName(), stateDesc, Table::New ) ;
2354  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::STATE ), Table( stateTab ) ) ;
2355
2356  TableDesc sysCalDesc = MSSysCal::requiredTableDesc() ;
2357  if ( tcalSpec_ )
2358    MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TCAL_SPECTRUM, 2 ) ;
2359  else
2360    MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TCAL, 1 ) ;
2361  if ( tsysSpec_ )
2362    MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TSYS_SPECTRUM, 2 ) ;
2363  else
2364    MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TSYS, 1 ) ;
2365  SetupNewTable sysCalTab( mstable_->sysCalTableName(), sysCalDesc, Table::New ) ;
2366  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SYSCAL ), Table( sysCalTab ) ) ;
2367
2368  TableDesc weatherDesc = MSWeather::requiredTableDesc() ;
2369  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::TEMPERATURE ) ;
2370  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::PRESSURE ) ;
2371  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::REL_HUMIDITY ) ;
2372  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::WIND_SPEED ) ;
2373  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::WIND_DIRECTION ) ;
2374  SetupNewTable weatherTab( mstable_->weatherTableName(), weatherDesc, Table::New ) ;
2375  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::WEATHER ), Table( weatherTab ) ) ;
2376
2377  mstable_->initRefs() ;
2378
2379//   double endSec = mathutil::gettimeofday_sec() ;
2380//   os_ << "end MSWriter::setupMS() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2381}
2382
2383void MSWriter::fillObservation()
2384{
2385  //double startSec = mathutil::gettimeofday_sec() ;
2386  //os_ << "start MSWriter::fillObservation() startSec=" << startSec << LogIO::POST ;
2387
2388  // only 1 row
2389  mstable_->observation().addRow( 1, True ) ;
2390  MSObservationColumns msObsCols( mstable_->observation() ) ;
2391  msObsCols.observer().put( 0, header_.observer ) ;
2392  // tentatively put antennaname (from ANTENNA subtable)
2393  String hAntennaName = header_.antennaname ;
2394  String::size_type pos = hAntennaName.find( "//" ) ;
2395  String telescopeName ;
2396  if ( pos != String::npos ) {
2397    telescopeName = hAntennaName.substr( 0, pos ) ;
2398  }
2399  else {
2400    pos = hAntennaName.find( "@" ) ;
2401    telescopeName = hAntennaName.substr( 0, pos ) ;
2402  }
2403//   os_ << "telescopeName = " << telescopeName << LogIO::POST ;
2404  msObsCols.telescopeName().put( 0, telescopeName ) ;
2405  msObsCols.project().put( 0, header_.project ) ;
2406  //ScalarMeasColumn<MEpoch> timeCol( table_->table().sort("TIME"), "TIME" ) ;
2407  Table sortedtable = table_->table().sort("TIME") ;
2408  ScalarMeasColumn<MEpoch> timeCol( sortedtable, "TIME" ) ;
2409  Vector<MEpoch> trange( 2 ) ;
2410  trange[0] = timeCol( 0 ) ;
2411  trange[1] = timeCol( table_->nrow()-1 ) ;
2412  msObsCols.timeRangeMeas().put( 0, trange ) ;
2413
2414  //double endSec = mathutil::gettimeofday_sec() ;
2415  //os_ << "end MSWriter::fillObservation() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2416}
2417
2418void MSWriter::antennaProperty( String &name, String &m, String &t, Double &d )
2419{
2420  name.upcase() ;
2421 
2422  m = "ALT-AZ" ;
2423  t = "GROUND-BASED" ;
2424  if ( name.matches( Regex( "DV[0-9]+$" ) )
2425       || name.matches( Regex( "DA[0-9]+$" ) )
2426       || name.matches( Regex( "PM[0-9]+$" ) ) )
2427    d = 12.0 ;
2428  else if ( name.matches( Regex( "CM[0-9]+$" ) ) )
2429    d = 7.0 ;
2430  else if ( name.contains( "GBT" ) )
2431    d = 104.9 ;
2432  else if ( name.contains( "MOPRA" ) )
2433    d = 22.0 ;
2434  else if ( name.contains( "PKS" ) || name.contains( "PARKS" ) )
2435    d = 64.0 ;
2436  else if ( name.contains( "TIDBINBILLA" ) )
2437    d = 70.0 ;
2438  else if ( name.contains( "CEDUNA" ) )
2439    d = 30.0 ;
2440  else if ( name.contains( "HOBART" ) )
2441    d = 26.0 ;
2442  else if ( name.contains( "APEX" ) )
2443    d = 12.0 ;
2444  else if ( name.contains( "ASTE" ) )
2445    d = 10.0 ;
2446  else if ( name.contains( "NRO" ) )
2447    d = 45.0 ;
2448  else
2449    d = 1.0 ;
2450}
2451
2452void MSWriter::fillAntenna()
2453{
2454  //double startSec = mathutil::gettimeofday_sec() ;
2455  //os_ << "start MSWriter::fillAntenna() startSec=" << startSec << LogIO::POST ;
2456
2457  // only 1 row
2458  Table anttab = mstable_->antenna() ;
2459  anttab.addRow( 1, True ) ;
2460 
2461  Table &table = table_->table() ;
2462  const TableRecord &keys = table.keywordSet() ;
2463  String hAntName = keys.asString( "AntennaName" ) ;
2464  String::size_type pos = hAntName.find( "//" ) ;
2465  String antennaName ;
2466  String stationName ;
2467  if ( pos != String::npos ) {
2468    stationName = hAntName.substr( 0, pos ) ;
2469    hAntName = hAntName.substr( pos+2 ) ;
2470  }
2471  pos = hAntName.find( "@" ) ;
2472  if ( pos != String::npos ) {
2473    antennaName = hAntName.substr( 0, pos ) ;
2474    stationName = hAntName.substr( pos+1 ) ;
2475  }
2476  else {
2477    antennaName = hAntName ;
2478  }
2479  Vector<Double> antpos = keys.asArrayDouble( "AntennaPosition" ) ;
2480 
2481  String mount, atype ;
2482  Double diameter ;
2483  antennaProperty( antennaName, mount, atype, diameter ) ;
2484 
2485  TableRow tr( anttab ) ;
2486  TableRecord &r = tr.record() ;
2487  RecordFieldPtr<String> nameRF( r, "NAME" ) ;
2488  RecordFieldPtr<String> stationRF( r, "STATION" ) ;
2489  RecordFieldPtr<String> mountRF( r, "MOUNT" ) ;
2490  RecordFieldPtr<String> typeRF( r, "TYPE" ) ;
2491  RecordFieldPtr<Double> dishDiameterRF( r, "DISH_DIAMETER" ) ;
2492  RecordFieldPtr< Vector<Double> > positionRF( r, "POSITION" ) ;
2493  *nameRF = antennaName ;
2494  *mountRF = mount ;
2495  *typeRF = atype ;
2496  *dishDiameterRF = diameter ;
2497  *positionRF = antpos ;
2498  *stationRF = stationName ;
2499 
2500  tr.put( 0 ) ;
2501
2502  //double endSec = mathutil::gettimeofday_sec() ;
2503  //os_ << "end MSWriter::fillAntenna() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2504}
2505 
2506void MSWriter::fillProcessor()
2507{
2508//   double startSec = mathutil::gettimeofday_sec() ;
2509//   os_ << "start MSWriter::fillProcessor() startSec=" << startSec << LogIO::POST ;
2510 
2511  // only add empty 1 row
2512  MSProcessor msProc = mstable_->processor() ;
2513  msProc.addRow( 1, True ) ;
2514
2515//   double endSec = mathutil::gettimeofday_sec() ;
2516//   os_ << "end MSWriter::fillProcessor() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2517}
2518
2519void MSWriter::fillSource()
2520{
2521//   double startSec = mathutil::gettimeofday_sec() ;
2522//   os_ << "start MSWriter::fillSource() startSec=" << startSec << LogIO::POST ;
2523 
2524  // access to MS SOURCE subtable
2525  MSSource msSrc = mstable_->source() ;
2526
2527  // access to MOLECULE subtable
2528  STMolecules stm = table_->molecules() ;
2529
2530  Int srcId = 0 ;
2531
2532  // row based
2533  TableRow row( msSrc ) ;
2534  TableRecord &rec = row.record() ;
2535  RecordFieldPtr<Int> srcidRF( rec, "SOURCE_ID" ) ;
2536  RecordFieldPtr<String> nameRF( rec, "NAME" ) ;
2537  RecordFieldPtr< Array<Double> > srcpmRF( rec, "PROPER_MOTION" ) ;
2538  RecordFieldPtr< Array<Double> > srcdirRF( rec, "DIRECTION" ) ;
2539  RecordFieldPtr<Int> numlineRF( rec, "NUM_LINES" ) ;
2540  RecordFieldPtr< Array<Double> > restfreqRF( rec, "REST_FREQUENCY" ) ;
2541  RecordFieldPtr< Array<Double> > sysvelRF( rec, "SYSVEL" ) ;
2542  RecordFieldPtr< Array<String> > transitionRF( rec, "TRANSITION" ) ;
2543  RecordFieldPtr<Double> timeRF( rec, "TIME" ) ;
2544  RecordFieldPtr<Double> intervalRF( rec, "INTERVAL" ) ;
2545  RecordFieldPtr<Int> spwidRF( rec, "SPECTRAL_WINDOW_ID" ) ;
2546
2547  //
2548  // ITERATION: SRCNAME
2549  //
2550  TableIterator iter0( table_->table(), "SRCNAME" ) ;
2551  while( !iter0.pastEnd() ) {
2552    //Table t0( iter0.table() ) ;
2553    Table t0 =  iter0.table()  ;
2554
2555    // get necessary information
2556    ROScalarColumn<String> srcNameCol( t0, "SRCNAME" ) ;
2557    String srcName = srcNameCol( 0 ) ;
2558    ROArrayColumn<Double> sharedDArrRCol( t0, "SRCPROPERMOTION" ) ;
2559    Vector<Double> srcPM = sharedDArrRCol( 0 ) ;
2560    sharedDArrRCol.attach( t0, "SRCDIRECTION" ) ;
2561    Vector<Double> srcDir = sharedDArrRCol( 0 ) ;
2562    ROScalarColumn<Double> srcVelCol( t0, "SRCVELOCITY" ) ;
2563    Double srcVel = srcVelCol( 0 ) ;
2564    srcRec_.define( srcName, srcId ) ;
2565
2566    // NAME
2567    *nameRF = srcName ;
2568
2569    // SOURCE_ID
2570    *srcidRF = srcId ;
2571
2572    // PROPER_MOTION
2573    *srcpmRF = srcPM ;
2574   
2575    // DIRECTION
2576    *srcdirRF = srcDir ;
2577
2578    //
2579    // ITERATION: MOLECULE_ID
2580    //
2581    TableIterator iter1( t0, "MOLECULE_ID" ) ;
2582    while( !iter1.pastEnd() ) {
2583      //Table t1( iter1.table() ) ;
2584      Table t1 = iter1.table() ;
2585
2586      // get necessary information
2587      Vector<Double> restFreq ;
2588      Vector<String> molName ;
2589      Vector<String> fMolName ;
2590      ROScalarColumn<uInt> molIdCol( t1, "MOLECULE_ID" ) ;
2591      uInt molId = molIdCol( 0 ) ;
2592      stm.getEntry( restFreq, molName, fMolName, molId ) ;
2593
2594      uInt numFreq = restFreq.size() ;
2595     
2596      // NUM_LINES
2597      *numlineRF = numFreq ;
2598
2599      // REST_FREQUENCY
2600      restfreqRF.define(restFreq);
2601
2602      // TRANSITION
2603      Vector<String> transition ;
2604      if ( fMolName.size() != 0 ) {
2605        transition = fMolName ;
2606      }
2607      else if ( molName.size() != 0 ) {
2608        transition = molName ;
2609      }
2610      else {
2611        transition.resize( numFreq ) ;
2612        transition = "" ;
2613      }
2614      transitionRF.define(transition);
2615
2616      // SYSVEL
2617      Vector<Double> sysvelArr( numFreq, srcVel ) ;
2618      sysvelRF.define(sysvelArr);
2619
2620      //
2621      // ITERATION: IFNO
2622      //
2623      TableIterator iter2( t1, "IFNO" ) ;
2624      while( !iter2.pastEnd() ) {
2625        //Table t2( iter2.table() ) ;
2626        Table t2 = iter2.table() ;
2627        uInt nrow = msSrc.nrow() ;
2628
2629        // get necessary information
2630        ROScalarColumn<uInt> ifNoCol( t2, "IFNO" ) ;
2631        uInt ifno = ifNoCol( 0 ) ; // IFNO = SPECTRAL_WINDOW_ID
2632        Double midTime ;
2633        Double interval ;
2634        getValidTimeRange( midTime, interval, t2 ) ;
2635
2636        // fill SPECTRAL_WINDOW_ID
2637        *spwidRF = ifno ;
2638
2639        // fill TIME, INTERVAL
2640        *timeRF = midTime ;
2641        *intervalRF = interval ;
2642
2643        // add row
2644        msSrc.addRow( 1, True ) ;
2645        row.put( nrow ) ;
2646
2647        iter2.next() ;
2648      }
2649
2650      iter1.next() ;
2651    }
2652
2653    // increment srcId if SRCNAME changed
2654    srcId++ ;
2655
2656    iter0.next() ;
2657  }
2658
2659//   double endSec = mathutil::gettimeofday_sec() ;
2660//   os_ << "end MSWriter::fillSource() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2661}
2662
2663void MSWriter::fillWeather()
2664{
2665//   double startSec = mathutil::gettimeofday_sec() ;
2666//   os_ << "start MSWriter::fillWeather() startSec=" << startSec << LogIO::POST ;
2667
2668  // access to MS WEATHER subtable
2669  MSWeather msw = mstable_->weather() ;
2670
2671  // access to WEATHER subtable
2672  Table stw = table_->weather().table() ;
2673  uInt nrow = stw.nrow() ;
2674
2675  if ( nrow == 0 )
2676    return ;
2677
2678  msw.addRow( nrow, True ) ;
2679  MSWeatherColumns mswCols( msw ) ;
2680
2681  // ANTENNA_ID is always 0
2682  Vector<Int> antIdArr( nrow, 0 ) ;
2683  mswCols.antennaId().putColumn( antIdArr ) ;
2684
2685  // fill weather status
2686  ROScalarColumn<Float> sharedFloatCol( stw, "TEMPERATURE" ) ;
2687  mswCols.temperature().putColumn( sharedFloatCol ) ;
2688  sharedFloatCol.attach( stw, "PRESSURE" ) ;
2689  mswCols.pressure().putColumn( sharedFloatCol ) ;
2690  sharedFloatCol.attach( stw, "HUMIDITY" ) ;
2691  mswCols.relHumidity().putColumn( sharedFloatCol ) ;
2692  sharedFloatCol.attach( stw, "WINDSPEED" ) ;
2693  mswCols.windSpeed().putColumn( sharedFloatCol ) ;
2694  sharedFloatCol.attach( stw, "WINDAZ" ) ;
2695  mswCols.windDirection().putColumn( sharedFloatCol ) ;
2696
2697  // fill TIME and INTERVAL
2698  Double midTime ;
2699  Double interval ;
2700  Vector<Double> intervalArr( nrow, 0.0 ) ;
2701  TableIterator iter( table_->table(), "WEATHER_ID" ) ;
2702  while( !iter.pastEnd() ) {
2703    //Table tab( iter.table() ) ;
2704    Table tab = iter.table() ;
2705
2706    ROScalarColumn<uInt> widCol( tab, "WEATHER_ID" ) ;
2707    uInt wid = widCol( 0 ) ;
2708
2709    getValidTimeRange( midTime, interval, tab ) ;
2710    mswCols.time().put( wid, midTime ) ;
2711    intervalArr[wid] = interval ;
2712
2713    iter.next() ;
2714  }
2715  mswCols.interval().putColumn( intervalArr ) ;
2716
2717//   double endSec = mathutil::gettimeofday_sec() ;
2718//   os_ << "end MSWriter::fillWeather() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2719}
2720
2721void MSWriter::fillSysCal()
2722{
2723  Table mssc = mstable_->sysCal() ;
2724
2725  if (table_->tcal().table().nrow() > 0) {
2726    static const char *cols[] = {
2727      "BEAMNO", "IFNO", "TIME", "POLNO",
2728      NULL
2729    };
2730    static const TypeManagerImpl<uInt> tmUInt;
2731    static const TypeManagerImpl<Double> tmDouble;
2732    static const TypeManager *const tms[] = {
2733      &tmUInt, &tmUInt, &tmDouble, &tmUInt, NULL
2734    };
2735    //double t0 = mathutil::gettimeofday_sec() ;
2736    MSSysCalVisitor myVisitor(table_->table(),mssc);
2737    //double t1 = mathutil::gettimeofday_sec() ;
2738    //cout << "MSWriterVisitor(): elapsed time " << t1-t0 << " sec" << endl ;
2739    traverseTable(table_->table(), cols, tms, &myVisitor);
2740    //double t3 = mathutil::gettimeofday_sec() ;
2741    //cout << "traverseTable(): elapsed time " << t3-t2 << " sec" << endl ;
2742  }
2743 
2744}
2745
2746void MSWriter::getValidTimeRange( Double &me, Double &interval, Table &tab )
2747{
2748//   double startSec = mathutil::gettimeofday_sec() ;
2749//   os_ << "start MSWriter::getVaridTimeRange() startSec=" << startSec << LogIO::POST ;
2750
2751  // sort table
2752  //Table stab = tab.sort( "TIME" ) ;
2753
2754  ROScalarColumn<Double> timeCol( tab, "TIME" ) ;
2755  Vector<Double> timeArr = timeCol.getColumn() ;
2756  Double minTime ;
2757  Double maxTime ;
2758  minMax( minTime, maxTime, timeArr ) ;
2759  Double midTime = 0.5 * ( minTime + maxTime ) * 86400.0 ;
2760  // unit for TIME
2761  // Scantable: "d"
2762  // MS: "s"
2763  me = midTime ;
2764  interval = ( maxTime - minTime ) * 86400.0 ;
2765
2766//   double endSec = mathutil::gettimeofday_sec() ;
2767//   os_ << "end MSWriter::getValidTimeRange() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2768}
2769
2770void MSWriter::getValidTimeRange( Double &me, Double &interval, Vector<Double> &atime, Vector<Double> &ainterval )
2771{
2772//   double startSec = mathutil::gettimeofday_sec() ;
2773//   os_ << "start MSWriter::getVaridTimeRange() startSec=" << startSec << LogIO::POST ;
2774
2775  // sort table
2776  //Table stab = tab.sort( "TIME" ) ;
2777
2778  Double minTime ;
2779  Double maxTime ;
2780  minMax( minTime, maxTime, atime ) ;
2781  Double midTime = 0.5 * ( minTime + maxTime ) * 86400.0 ;
2782  // unit for TIME
2783  // Scantable: "d"
2784  // MS: "s"
2785  me = midTime ;
2786  interval = ( maxTime - minTime ) * 86400.0 + mean( ainterval ) ;
2787
2788//   double endSec = mathutil::gettimeofday_sec() ;
2789//   os_ << "end MSWriter::getValidTimeRange() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2790}
2791
2792}
Note: See TracBrowser for help on using the repository browser.