source: trunk/src/MSWriter.cpp @ 2018

Last change on this file since 2018 was 2018, checked in by Takeshi Nakazato, 13 years ago

New Development: No

JIRA Issue: Yes CAS-2718

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...

Performance of fillSysCal() greatly improved.


File size: 58.8 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
14#include <casa/OS/File.h>
15#include <casa/OS/RegularFile.h>
16#include <casa/OS/Directory.h>
17#include <casa/OS/SymLink.h>
18#include <casa/BasicSL/String.h>
19#include <casa/Containers/RecordField.h>
20#include <casa/Arrays/Cube.h>
21
22#include <tables/Tables/ExprNode.h>
23#include <tables/Tables/TableDesc.h>
24#include <tables/Tables/SetupNewTab.h>
25#include <tables/Tables/TableIter.h>
26#include <tables/Tables/RefRows.h>
27#include <tables/Tables/TableRow.h>
28
29#include <ms/MeasurementSets/MeasurementSet.h>
30#include <ms/MeasurementSets/MSColumns.h>
31#include <ms/MeasurementSets/MSPolIndex.h>
32#include <ms/MeasurementSets/MSDataDescIndex.h>
33#include <ms/MeasurementSets/MSSourceIndex.h>
34
35#include "MSWriter.h"
36#include "STHeader.h"
37#include "STFrequencies.h"
38#include "STMolecules.h"
39#include "STTcal.h"
40
41#include <ctime>
42#include <sys/time.h>
43
44// Boost
45#include <boost/pool/object_pool.hpp>
46
47using namespace casa ;
48using namespace std ;
49
50namespace asap {
51double MSWriter::gettimeofday_sec()
52{
53  struct timeval tv ;
54  gettimeofday( &tv, NULL ) ;
55  return tv.tv_sec + (double)tv.tv_usec*1.0e-6 ;
56}
57
58MSWriter::MSWriter(CountedPtr<Scantable> stable)
59  : table_(stable),
60    ptTabName_("")
61{
62  os_ = LogIO() ;
63  os_.origin( LogOrigin( "MSWriter", "MSWriter()", WHERE ) ) ;
64  os_ << "MSWriter::MSWriter()" << LogIO::POST ;
65
66  // initialize writer
67  init() ;
68}
69
70MSWriter::~MSWriter()
71{
72  os_.origin( LogOrigin( "MSWriter", "~MSWriter()", WHERE ) ) ;
73  os_ << "MSWriter::~MSWriter()" << LogIO::POST ;
74
75  if ( mstable_ != 0 )
76    delete mstable_ ;
77}
78 
79bool MSWriter::write(const string& filename, const Record& rec)
80{
81  os_.origin( LogOrigin( "MSWriter", "write()", WHERE ) ) ;
82  double startSec = gettimeofday_sec() ;
83  os_ << "start MSWriter::write() startSec=" << startSec << LogIO::POST ;
84
85  filename_ = filename ;
86
87  // parsing MS options
88  Bool overwrite = False ;
89  if ( rec.isDefined( "ms" ) ) {
90    Record msrec = rec.asRecord( "ms" ) ;
91    if ( msrec.isDefined( "overwrite" ) ) {
92      overwrite = msrec.asBool( "overwrite" ) ;
93    }
94  }
95
96  os_ << "Parsing MS options" << endl ;
97  os_ << "   overwrite = " << overwrite << LogIO::POST ;
98
99  File file( filename_ ) ;
100  if ( file.exists() ) {
101    if ( overwrite ) {
102      os_ << filename_ << " exists. Overwrite existing data... " << LogIO::POST ;
103      if ( file.isRegular() ) RegularFile(file).remove() ;
104      else if ( file.isDirectory() ) Directory(file).removeRecursive() ;
105      else SymLink(file).remove() ;
106    }
107    else {
108      os_ << LogIO::SEVERE << "ERROR: " << filename_ << " exists..." << LogIO::POST ;
109      return False ;
110    }
111  }
112
113  // TEST
114  // memory allocation by boost::object_pool
115//   boost::object_pool<ROTableColumn> *tpoolr = new boost::object_pool<ROTableColumn> ;
116//   ROTableColumn *tcol = 0 ;
117  //
118
119  // set up MS
120  setupMS() ;
121 
122  // subtables
123  // OBSERVATION
124  fillObservation() ;
125
126  // ANTENNA
127  fillAntenna() ;
128
129  // PROCESSOR
130  fillProcessor() ;
131
132  // SOURCE
133  fillSource() ;
134
135  // WEATHER
136  fillWeather() ;
137
138  // MAIN
139  // Iterate over several ids
140  Vector<uInt> processedFreqId( 0 ) ;
141  Int defaultFieldId = 0 ;
142
143  // row based
144  TableRow row( *mstable_ ) ;
145  TableRecord &trec = row.record() ;
146  NoticeTarget *dataRF = 0 ;
147  if ( useFloatData_ )
148    dataRF = new RecordFieldPtr< Array<Float> >( trec, "FLOAT_DATA" ) ;
149  else if ( useData_ )
150    dataRF = new RecordFieldPtr< Array<Complex> >( trec, "DATA" ) ;
151  RecordFieldPtr< Array<Bool> > flagRF( trec, "FLAG" ) ;
152  RecordFieldPtr<Bool> flagrowRF( trec, "FLAG_ROW" ) ;
153  RecordFieldPtr<Double> timeRF( trec, "TIME" ) ;
154  RecordFieldPtr<Double> timecRF( trec, "TIME_CENTROID" ) ;
155  RecordFieldPtr<Double> intervalRF( trec, "INTERVAL" ) ;
156  RecordFieldPtr<Double> exposureRF( trec, "EXPOSURE" ) ;
157  RecordFieldPtr< Array<Float> > weightRF( trec, "WEIGHT" ) ;
158  RecordFieldPtr< Array<Float> > sigmaRF( trec, "SIGMA" ) ;
159  RecordFieldPtr<Int> ddidRF( trec, "DATA_DESC_ID" ) ;
160  RecordFieldPtr<Int> stateidRF( trec, "STATE_ID" ) ;
161
162
163  // OBSERVATION_ID is always 0
164  RecordFieldPtr<Int> intRF( trec, "OBSERVATION_ID" ) ;
165  *intRF = 0 ;
166 
167  // ANTENNA1 and ANTENNA2 are always 0
168  intRF.attachToRecord( trec, "ANTENNA1" ) ;
169  *intRF = 0 ;
170  intRF.attachToRecord( trec, "ANTENNA2" ) ;
171  *intRF = 0 ;
172 
173  // ARRAY_ID is tentatively set to 0
174  intRF.attachToRecord( trec, "ARRAY_ID" ) ;
175  *intRF = 0 ;
176
177  // PROCESSOR_ID is tentatively set to 0
178  intRF.attachToRecord( trec, "PROCESSOR_ID" ) ;
179  *intRF = 0 ;
180
181  // UVW is always [0,0,0]
182  RecordFieldPtr< Array<Double> > uvwRF( trec, "UVW" ) ;
183  *uvwRF = Vector<Double>( 3, 0.0 ) ;
184
185  //
186  // ITERATION: FIELDNAME
187  //
188  TableIterator iter0( table_->table(), "FIELDNAME" ) ;
189  while( !iter0.pastEnd() ) {
190    //Table t0( iter0.table() ) ;
191    Table t0 = iter0.table() ;
192    ROTableColumn sharedCol( t0, "FIELDNAME" ) ;
193    String fieldName = sharedCol.asString( 0 ) ;
194//     tcol = tpoolr->construct( t0, "FIELDNAME" ) ;
195//     String fieldName = tcol->asString( 0 ) ;
196//     tpoolr->destroy( tcol ) ;
197    sharedCol.attach( t0, "SRCNAME" ) ;
198    String srcName = sharedCol.asString( 0 ) ;
199//     tcol = tpoolr->construct( t0, "SRCNAME" ) ;
200//     String srcName = tcol->asString( 0 ) ;
201//     tpoolr->destroy( tcol ) ;
202    sharedCol.attach( t0, "TIME" ) ;
203    Double minTime = (Double)sharedCol.asdouble( 0 ) * 86400.0 ; // day->sec
204//     tcol = tpoolr->construct( t0, "TIME" ) ;
205//     Double minTime = (Double)(tcol->asdouble( 0 )) * 86400.0 ; // day -> sec
206//     tpoolr->destroy( tcol ) ;
207    ROArrayColumn<Double> scanRateCol( t0, "SCANRATE" ) ;
208    //Vector<Double> scanRate = scanRateCol.getColumn()[0] ;
209    Vector<Double> scanRate = scanRateCol( 0 ) ;
210    String::size_type pos = fieldName.find( "__" ) ;
211    Int fieldId = -1 ;
212    if ( pos != String::npos ) {
213      os_ << "fieldName.substr( pos+2 )=" << fieldName.substr( pos+2 ) << LogIO::POST ;
214      fieldId = String::toInt( fieldName.substr( pos+2 ) ) ;
215      fieldName = fieldName.substr( 0, pos ) ;
216    }
217    else {
218      os_ << "use default field id" << LogIO::POST ;
219      fieldId = defaultFieldId ;
220      defaultFieldId++ ;
221    }
222    os_ << "fieldId" << fieldId << ": " << fieldName << LogIO::POST ;
223
224    // FIELD_ID
225    intRF.attachToRecord( trec, "FIELD_ID" ) ;
226    *intRF = fieldId ;
227
228    //
229    // ITERATION: BEAMNO
230    //
231    TableIterator iter1( t0, "BEAMNO" ) ;
232    while( !iter1.pastEnd() ) {
233      Table t1 = iter1.table() ;
234//       tcol = tpoolr->construct( t1, "BEAMNO" ) ;
235//       uInt beamNo = tcol->asuInt( 0 ) ;
236//       tpoolr->destroy( tcol ) ;
237      sharedCol.attach( t1, "BEAMNO" ) ;
238      uInt beamNo = sharedCol.asuInt( 0 ) ;
239      os_ << "beamNo = " << beamNo << LogIO::POST ;
240
241      // FEED1 and FEED2
242      intRF.attachToRecord( trec, "FEED1" ) ;
243      *intRF = beamNo ;
244      intRF.attachToRecord( trec, "FEED2" ) ;
245      *intRF = beamNo ;
246
247      //
248      // ITERATION: SCANNO
249      //
250      TableIterator iter2( t1, "SCANNO" ) ;
251      while( !iter2.pastEnd() ) {
252        Table t2 = iter2.table() ;
253//         tcol = tpoolr->construct( t2, "SCANNO" ) ;
254//         uInt scanNo = tcol->asuInt( 0 ) ;
255//         tpoolr->destroy( tcol ) ;
256        sharedCol.attach( t2, "SCANNO" ) ;
257        uInt scanNo = sharedCol.asuInt( 0 ) ;
258        os_ << "scanNo = " << scanNo << LogIO::POST ;
259
260        // SCAN_NUMBER
261        // MS: 1-based
262        // Scantable: 0-based
263        intRF.attachToRecord( trec, "SCAN_NUMBER" ) ;
264        *intRF = scanNo + 1 ;
265
266        //
267        // ITERATION: IFNO
268        //
269        TableIterator iter3( t2, "IFNO" ) ;
270        while( !iter3.pastEnd() ) {
271          Table t3 = iter3.table() ;
272//           tcol = tpoolr->construct( t3, "IFNO" ) ;
273//           uInt ifNo = tcol->asuInt( 0 ) ;
274//           tpoolr->destroy( tcol ) ;
275          sharedCol.attach( t3, "IFNO" ) ;
276          uInt ifNo = sharedCol.asuInt( 0 ) ;
277          os_ << "ifNo = " << ifNo << LogIO::POST ;
278//           tcol = tpoolr->construct( t3, "FREQ_ID" ) ;
279//           uInt freqId = tcol->asuInt( 0 ) ;
280//           tpoolr->destroy( tcol ) ;
281          sharedCol.attach( t3, "FREQ_ID" ) ;
282          uInt freqId = sharedCol.asuInt( 0 ) ;
283          os_ << "freqId = " << freqId << LogIO::POST ;
284          Int subscan = 1 ; // 1-base
285          //
286          // ITERATION: SRCTYPE
287          //
288          TableIterator iter4( t3, "SRCTYPE" ) ;
289          while( !iter4.pastEnd() ) {
290            Table t4 = iter4.table() ;
291//             tcol = tpoolr->construct( t4, "SRCTYPE" ) ;
292//             uInt srcType = tcol->asInt( 0 ) ;
293//             tpoolr->destroy( tcol ) ;
294            sharedCol.attach( t4, "SRCTYPE" ) ;
295            Int srcType = sharedCol.asInt( 0 ) ;
296            Int stateId = addState( srcType, subscan ) ;
297            *stateidRF = stateId ;
298            //
299            // ITERATION: CYCLENO and TIME
300            //
301            Block<String> cols( 2 ) ;
302            cols[0] = "CYCLENO" ;
303            cols[1] = "TIME" ;
304            TableIterator iter5( t4, cols ) ;
305            while( !iter5.pastEnd() ) {
306              Table t5 =  iter5.table()  ;
307              //sharedCol.attach( t5, "CYCLENO" ) ;
308              //uInt cycleNo = sharedCol.asuInt( 0 ) ;
309              Int nrow = t5.nrow() ;
310              os_ << "nrow = " << nrow << LogIO::POST ;
311             
312              Vector<Int> polnos( nrow ) ;
313              indgen( polnos, 0 ) ;
314              Int polid = addPolarization( polnos ) ;
315              os_ << "polid = " << polid << LogIO::POST ;
316             
317              // DATA/FLOAT_DATA
318              ROArrayColumn<Float> specCol( t5, "SPECTRA" ) ;
319              ROArrayColumn<uChar> flagCol( t5, "FLAGTRA" ) ;
320              uInt nchan = specCol( 0 ).size() ;
321              IPosition cellshape( 2, nrow, nchan ) ;
322              if ( useFloatData_ ) {
323                // FLOAT_DATA
324                Matrix<Float> dataArr( cellshape ) ;
325                Matrix<Bool> flagArr( cellshape ) ;
326                Vector<uChar> tmpUC ;
327                Vector<Bool> tmpB ;
328                for ( Int ipol = 0 ; ipol < nrow ; ipol++ ) {
329                  dataArr.row( ipol ) = specCol( ipol ) ;
330                  tmpUC = flagCol( ipol ) ;
331                  tmpB = flagArr.row( ipol ) ;
332                  convertArray( tmpB, tmpUC ) ;
333                }
334                *(*((RecordFieldPtr< Array<Float> > *)dataRF)) = dataArr ;
335               
336                // FLAG
337                *flagRF = flagArr ;
338              }
339              else if ( useData_ ) {
340                // DATA
341                // assume nrow = 4
342                Matrix<Complex> dataArr( cellshape ) ;
343                Vector<Float> zeroIm( nchan, 0 ) ;
344                Matrix<Float> dummy( IPosition( 2, 2, nchan ) ) ;
345                dummy.row( 0 ) = specCol( 0 ) ;
346                dummy.row( 1 ) = zeroIm ;
347                dataArr.row( 0 ) = RealToComplex( dummy ) ;
348                dummy.row( 0 ) = specCol( 1 ) ;
349                dataArr.row( 3 ) = RealToComplex( dummy ) ;
350                dummy.row( 0 ) = specCol( 2 ) ;
351                dummy.row( 1 ) = specCol( 3 ) ;
352                dataArr.row( 1 ) = RealToComplex( dummy ) ;
353                dataArr.row( 2 ) = conj( dataArr.row( 1 ) ) ;
354                *(*((RecordFieldPtr< Array<Complex> > *)dataRF)) = dataArr ;
355               
356               
357                // FLAG
358                Matrix<Bool> flagArr( cellshape ) ;
359                Matrix<uChar> tmpUC = flagCol( 0 ) ;
360                Matrix<Bool> tmpB = flagArr.row( 0 ) ;
361                convertArray( tmpB, tmpUC ) ;
362                tmpUC = flagCol( 3 ) ;
363                tmpB = flagArr.row( 3 ) ;
364                convertArray( tmpB, tmpUC ) ;
365                tmpUC = flagCol( 2 ) | flagCol( 3 ) ;
366                tmpB = flagArr.row( 1 ) ;
367                convertArray( tmpB, tmpUC ) ;
368                tmpB = flagArr.row( 2 ) ;
369                convertArray( tmpB, tmpUC ) ;
370                *flagRF = flagArr ;
371              }
372             
373              // FLAG_ROW
374//               tcol = tpoolr->construct( t5, "FLAGROW" ) ;
375              sharedCol.attach( t5, "FLAGROW" ) ;
376              Vector<uInt> flagRowArr( nrow ) ;
377              for ( Int irow = 0 ; irow < nrow ; irow++ )
378                flagRowArr[irow] = sharedCol.asuInt( irow ) ;
379//                 flagRowArr[irow] = tcol->asuInt( irow ) ;
380//               tpoolr->destroy( tcol ) ;
381              *flagrowRF = anyNE( flagRowArr, (uInt)0 ) ;
382             
383              // TIME and TIME_CENTROID
384//               tcol = tpoolr->construct( t5, "TIME" ) ;
385//               Double mTimeV = (Double)(tcol->asdouble(0)) * 86400.0 ; // day->sec
386//               tpoolr->destroy( tcol ) ;
387              sharedCol.attach( t5, "TIME" ) ;
388              Double mTimeV = (Double)sharedCol.asdouble( 0 ) * 86400.0 ; // day -> sec
389              *timeRF = mTimeV ;
390              *timecRF = mTimeV ;
391             
392              // INTERVAL and EXPOSURE
393//               tcol = tpoolr->construct( t5, "INTERVAL" ) ;
394//               Double interval = (Double)(tcol->asdouble( 0 )) ;
395//               tpoolr->destroy( tcol ) ;
396              sharedCol.attach( t5, "INTERVAL" ) ;
397              Double interval = (Double)sharedCol.asdouble( 0 ) ;
398              *intervalRF = interval ;
399              *exposureRF = interval ;
400             
401              // WEIGHT and SIGMA
402              // always 1 at the moment
403              Vector<Float> wArr( nrow, 1.0 ) ;
404              *weightRF = wArr ;
405              *sigmaRF = wArr ;
406             
407              // add DATA_DESCRIPTION row
408              Int ddid = addDataDescription( polid, ifNo ) ;
409              os_ << "ddid = " << ddid << LogIO::POST ;
410              *ddidRF = ddid ;
411             
412              // for SYSCAL table
413//               tcol = tpoolr->construct( t5, "TCAL_ID" ) ;
414              sharedCol.attach( t5, "TCAL_ID" ) ;
415              Vector<uInt> tcalIdArr( nrow ) ;
416              for ( Int irow = 0 ; irow < nrow ; irow++ )
417                tcalIdArr[irow] = sharedCol.asuInt( irow ) ;
418//                 tcalIdArr[irow] = tcol->asuInt( irow ) ;
419//               tpoolr->destroy( tcol ) ;
420              os_ << "tcalIdArr = " << tcalIdArr << LogIO::POST ;
421              String key = String::toString( tcalIdArr[0] ) ;
422              if ( !tcalIdRec_.isDefined( key ) ) {
423                tcalIdRec_.define( key, tcalIdArr ) ;
424                tcalRowRec_.define( key, t5.rowNumbers() ) ;
425              }
426              else {
427                Vector<uInt> pastrows = tcalRowRec_.asArrayuInt( key ) ;
428                tcalRowRec_.define( key, concatenateArray( pastrows, t5.rowNumbers() ) ) ;
429              }
430             
431              // fill STATE_ID
432              //ROScalarColumn<Int> srcTypeCol( t5, "SRCTYPE" ) ;
433              //Int srcType = srcTypeCol( 0 ) ;
434              //Int stateId = addState( srcType, subscan ) ;
435              //*stateidRF = stateId ;
436             
437              // for POINTING table
438              if ( ptTabName_ == "" ) {
439                ROArrayColumn<Double> dirCol( t5, "DIRECTION" ) ;
440                Vector<Double> dir = dirCol( 0 ) ;
441                dirCol.attach( t5, "SCANRATE" ) ;
442                Vector<Double> rate = dirCol( 0 ) ;
443                Matrix<Double> msDir( 2, 1 ) ;
444                msDir.column( 0 ) = dir ;
445                if ( anyNE( rate, 0.0 ) ) {
446                  msDir.resize( 2, 2 ) ;
447                  msDir.column( 1 ) = rate ;
448                }
449                addPointing( fieldName, mTimeV, interval, msDir ) ;
450              }
451             
452              // FLAG_CATEGORY is tentatively set
453              RecordFieldPtr< Array<Bool> > flagcatRF( trec, "FLAG_CATEGORY" ) ;
454              *flagcatRF = Cube<Bool>( nrow, nchan, 1, False ) ;
455             
456              // add row
457              mstable_->addRow( 1, True ) ;
458              row.put( mstable_->nrow()-1 ) ;
459             
460              iter5.next() ;
461            }
462           
463            iter4.next() ;
464          }
465
466          // add SPECTRAL_WINDOW row
467          if ( allNE( processedFreqId, freqId ) ) {
468            uInt vsize = processedFreqId.size() ;
469            processedFreqId.resize( vsize+1, True ) ;
470            processedFreqId[vsize] = freqId ;
471            addSpectralWindow( ifNo, freqId ) ;
472          }
473         
474          iter3.next() ;
475        }
476       
477        iter2.next() ;
478      }
479     
480      // add FEED row
481      addFeed( beamNo ) ;
482     
483      iter1.next() ;
484    }
485   
486    // add FIELD row
487    addField( fieldId, fieldName, srcName, minTime, scanRate ) ;
488
489    iter0.next() ;
490  }
491
492//   delete tpoolr ;
493  delete dataRF ;
494
495  // SYSCAL
496  fillSysCal() ;
497
498  // replace POINTING table with original one if exists
499  if ( ptTabName_ != "" ) {
500    delete mstable_ ;
501    mstable_ = 0 ;
502    Table newPtTab( ptTabName_, Table::Old ) ;
503    newPtTab.copy( filename_+"/POINTING", Table::New ) ;
504  }
505
506  double endSec = gettimeofday_sec() ;
507  os_ << "end MSWriter::write() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
508
509  return True ;
510}
511 
512void MSWriter::init()
513{
514//   os_.origin( LogOrigin( "MSWriter", "init()", WHERE ) ) ;
515  double startSec = gettimeofday_sec() ;
516  os_ << "start MSWriter::init() startSec=" << startSec << LogIO::POST ;
517 
518  // access to scantable
519  header_ = table_->getHeader() ;
520
521  // FLOAT_DATA? or DATA?
522  if ( header_.npol > 2 ) {
523    useFloatData_ = False ;
524    useData_ = True ;
525  }
526  else {
527    useFloatData_ = True ;
528    useData_ = False ;
529  }
530
531  // polarization type
532  polType_ = header_.poltype ;
533  if ( polType_ == "" )
534    polType_ = "stokes" ;
535  else if ( polType_.find( "linear" ) != String::npos )
536    polType_ = "linear" ;
537  else if ( polType_.find( "circular" ) != String::npos )
538    polType_ = "circular" ;
539  else if ( polType_.find( "stokes" ) != String::npos )
540    polType_ = "stokes" ;
541  else if ( polType_.find( "linpol" ) != String::npos )
542    polType_ = "linpol" ;
543  else
544    polType_ = "notype" ;
545
546  // Are TCAL_SPECTRUM and TSYS_SPECTRUM necessary?
547  tcalSpec_ = False ;
548  tsysSpec_ = False ;
549  if ( header_.nchan != 1 ) {
550    // examine TCAL subtable
551    Table tcaltab = table_->tcal().table() ;
552    ROArrayColumn<Float> tcalCol( tcaltab, "TCAL" ) ;
553    for ( uInt irow = 0 ; irow < tcaltab.nrow() ; irow++ ) {
554      if ( tcalCol( irow ).size() != 1 )
555        tcalSpec_ = True ;
556    }
557    // examine spectral data
558    TableIterator iter0( table_->table(), "IFNO" ) ;
559    while( !iter0.pastEnd() ) {
560      Table t0( iter0.table() ) ;
561      ROArrayColumn<Float> sharedFloatArrCol( t0, "SPECTRA" ) ;
562      uInt len = sharedFloatArrCol( 0 ).size() ;
563      if ( len != 1 ) {
564        sharedFloatArrCol.attach( t0, "TSYS" ) ;
565        if ( sharedFloatArrCol( 0 ).size() != 1 )
566          tsysSpec_ = True ;
567      }
568      iter0.next() ;
569    }
570  }
571
572  // check if reference for POINTING table exists
573  const TableRecord &rec = table_->table().keywordSet() ;
574  if ( rec.isDefined( "POINTING" ) ) {
575    ptTabName_ = rec.asString( "POINTING" ) ;
576    if ( !Table::isReadable( ptTabName_ ) ) {
577      ptTabName_ = "" ;
578    }
579  }
580
581  double endSec = gettimeofday_sec() ;
582  os_ << "end MSWriter::init() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
583}
584
585void MSWriter::setupMS()
586{
587//   os_.origin( LogOrigin( "MSWriter", "setupMS()", WHERE ) ) ;
588  double startSec = gettimeofday_sec() ;
589  os_ << "start MSWriter::setupMS() startSec=" << startSec << LogIO::POST ;
590
591  TableDesc msDesc = MeasurementSet::requiredTableDesc() ;
592  if ( useFloatData_ )
593    MeasurementSet::addColumnToDesc( msDesc, MSMainEnums::FLOAT_DATA, 2 ) ;
594  else if ( useData_ )
595    MeasurementSet::addColumnToDesc( msDesc, MSMainEnums::DATA, 2 ) ;
596
597  SetupNewTable newtab( filename_, msDesc, Table::New ) ;
598
599  mstable_ = new MeasurementSet( newtab ) ;
600
601  // create subtables
602  TableDesc antennaDesc = MSAntenna::requiredTableDesc() ;
603  SetupNewTable antennaTab( mstable_->antennaTableName(), antennaDesc, Table::New ) ;
604  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::ANTENNA ), Table( antennaTab ) ) ;
605
606  TableDesc dataDescDesc = MSDataDescription::requiredTableDesc() ;
607  SetupNewTable dataDescTab( mstable_->dataDescriptionTableName(), dataDescDesc, Table::New ) ;
608  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::DATA_DESCRIPTION ), Table( dataDescTab ) ) ;
609
610  TableDesc dopplerDesc = MSDoppler::requiredTableDesc() ;
611  SetupNewTable dopplerTab( mstable_->dopplerTableName(), dopplerDesc, Table::New ) ;
612  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::DOPPLER ), Table( dopplerTab ) ) ;
613
614  TableDesc feedDesc = MSFeed::requiredTableDesc() ;
615  SetupNewTable feedTab( mstable_->feedTableName(), feedDesc, Table::New ) ;
616  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FEED ), Table( feedTab ) ) ;
617
618  TableDesc fieldDesc = MSField::requiredTableDesc() ;
619  SetupNewTable fieldTab( mstable_->fieldTableName(), fieldDesc, Table::New ) ;
620  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FIELD ), Table( fieldTab ) ) ;
621
622  TableDesc flagCmdDesc = MSFlagCmd::requiredTableDesc() ;
623  SetupNewTable flagCmdTab( mstable_->flagCmdTableName(), flagCmdDesc, Table::New ) ;
624  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FLAG_CMD ), Table( flagCmdTab ) ) ;
625
626  TableDesc freqOffsetDesc = MSFreqOffset::requiredTableDesc() ;
627  SetupNewTable freqOffsetTab( mstable_->freqOffsetTableName(), freqOffsetDesc, Table::New ) ;
628  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FREQ_OFFSET ), Table( freqOffsetTab ) ) ;
629
630  TableDesc historyDesc = MSHistory::requiredTableDesc() ;
631  SetupNewTable historyTab( mstable_->historyTableName(), historyDesc, Table::New ) ;
632  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::HISTORY ), Table( historyTab ) ) ;
633
634  TableDesc observationDesc = MSObservation::requiredTableDesc() ;
635  SetupNewTable observationTab( mstable_->observationTableName(), observationDesc, Table::New ) ;
636  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::OBSERVATION ), Table( observationTab ) ) ;
637
638  TableDesc pointingDesc = MSPointing::requiredTableDesc() ;
639  SetupNewTable pointingTab( mstable_->pointingTableName(), pointingDesc, Table::New ) ;
640  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::POINTING ), Table( pointingTab ) ) ;
641
642  TableDesc polarizationDesc = MSPolarization::requiredTableDesc() ;
643  SetupNewTable polarizationTab( mstable_->polarizationTableName(), polarizationDesc, Table::New ) ;
644  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::POLARIZATION ), Table( polarizationTab ) ) ;
645
646  TableDesc processorDesc = MSProcessor::requiredTableDesc() ;
647  SetupNewTable processorTab( mstable_->processorTableName(), processorDesc, Table::New ) ;
648  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::PROCESSOR ), Table( processorTab ) ) ;
649
650  TableDesc sourceDesc = MSSource::requiredTableDesc() ;
651  MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::TRANSITION, 1 ) ;
652  MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::REST_FREQUENCY, 1 ) ;
653  MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::SYSVEL, 1 ) ;
654  SetupNewTable sourceTab( mstable_->sourceTableName(), sourceDesc, Table::New ) ;
655  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SOURCE ), Table( sourceTab ) ) ;
656
657  TableDesc spwDesc = MSSpectralWindow::requiredTableDesc() ;
658  SetupNewTable spwTab( mstable_->spectralWindowTableName(), spwDesc, Table::New ) ;
659  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SPECTRAL_WINDOW ), Table( spwTab ) ) ;
660
661  TableDesc stateDesc = MSState::requiredTableDesc() ;
662  SetupNewTable stateTab( mstable_->stateTableName(), stateDesc, Table::New ) ;
663  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::STATE ), Table( stateTab ) ) ;
664
665  // TODO: add TCAL_SPECTRUM and TSYS_SPECTRUM if necessary
666  TableDesc sysCalDesc = MSSysCal::requiredTableDesc() ;
667  MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TCAL, 2 ) ;
668  MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TSYS, 2 ) ;
669  if ( tcalSpec_ )
670    MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TCAL_SPECTRUM, 2 ) ;
671  if ( tsysSpec_ )
672    MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TSYS_SPECTRUM, 2 ) ;
673  SetupNewTable sysCalTab( mstable_->sysCalTableName(), sysCalDesc, Table::New ) ;
674  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SYSCAL ), Table( sysCalTab ) ) ;
675
676  TableDesc weatherDesc = MSWeather::requiredTableDesc() ;
677  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::TEMPERATURE ) ;
678  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::PRESSURE ) ;
679  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::REL_HUMIDITY ) ;
680  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::WIND_SPEED ) ;
681  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::WIND_DIRECTION ) ;
682  SetupNewTable weatherTab( mstable_->weatherTableName(), weatherDesc, Table::New ) ;
683  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::WEATHER ), Table( weatherTab ) ) ;
684
685  mstable_->initRefs() ;
686
687  double endSec = gettimeofday_sec() ;
688  os_ << "end MSWriter::setupMS() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
689}
690
691void MSWriter::fillObservation()
692{
693  double startSec = gettimeofday_sec() ;
694  os_ << "start MSWriter::fillObservation() startSec=" << startSec << LogIO::POST ;
695
696  // only 1 row
697  mstable_->observation().addRow( 1, True ) ;
698  MSObservationColumns msObsCols( mstable_->observation() ) ;
699  msObsCols.observer().put( 0, header_.observer ) ;
700  // tentatively put antennaname (from ANTENNA subtable)
701  String hAntennaName = header_.antennaname ;
702  String::size_type pos = hAntennaName.find( "//" ) ;
703  String telescopeName ;
704  if ( pos != String::npos ) {
705    telescopeName = hAntennaName.substr( 0, pos ) ;
706  }
707  else {
708    pos = hAntennaName.find( "@" ) ;
709    telescopeName = hAntennaName.substr( 0, pos ) ;
710  }
711  os_ << "telescopeName = " << telescopeName << LogIO::POST ;
712  msObsCols.telescopeName().put( 0, telescopeName ) ;
713  msObsCols.project().put( 0, header_.project ) ;
714  //ScalarMeasColumn<MEpoch> timeCol( table_->table().sort("TIME"), "TIME" ) ;
715  Table sortedtable = table_->table().sort("TIME") ;
716  ScalarMeasColumn<MEpoch> timeCol( sortedtable, "TIME" ) ;
717  Vector<MEpoch> trange( 2 ) ;
718  trange[0] = timeCol( 0 ) ;
719  trange[1] = timeCol( table_->nrow()-1 ) ;
720  msObsCols.timeRangeMeas().put( 0, trange ) ;
721
722  double endSec = gettimeofday_sec() ;
723  os_ << "end MSWriter::fillObservation() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
724}
725
726void MSWriter::fillAntenna()
727{
728  double startSec = gettimeofday_sec() ;
729  os_ << "start MSWriter::fillAntenna() startSec=" << startSec << LogIO::POST ;
730
731  // only 1 row
732  mstable_->antenna().addRow( 1, True ) ;
733  MSAntennaColumns msAntCols( mstable_->antenna() ) ;
734
735  String hAntennaName = header_.antennaname ;
736  String::size_type pos = hAntennaName.find( "//" ) ;
737  String antennaName ;
738  String stationName ;
739  if ( pos != String::npos ) {
740    hAntennaName = hAntennaName.substr( pos+2 ) ;
741  }
742  pos = hAntennaName.find( "@" ) ;
743  if ( pos != String::npos ) {
744    antennaName = hAntennaName.substr( 0, pos ) ;
745    stationName = hAntennaName.substr( pos+1 ) ;
746  }
747  else {
748    antennaName = hAntennaName ;
749    stationName = hAntennaName ;
750  }
751  os_ << "antennaName = " << antennaName << LogIO::POST ;
752  os_ << "stationName = " << stationName << LogIO::POST ;
753 
754  msAntCols.name().put( 0, antennaName ) ;
755  msAntCols.station().put( 0, stationName ) ;
756
757  os_ << "antennaPosition = " << header_.antennaposition << LogIO::POST ;
758 
759  msAntCols.position().put( 0, header_.antennaposition ) ;
760
761  double endSec = gettimeofday_sec() ;
762  os_ << "end MSWriter::fillAntenna() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
763}
764
765void MSWriter::fillProcessor()
766{
767  double startSec = gettimeofday_sec() ;
768  os_ << "start MSWriter::fillProcessor() startSec=" << startSec << LogIO::POST ;
769 
770  // only add empty 1 row
771  MSProcessor msProc = mstable_->processor() ;
772  msProc.addRow( 1, True ) ;
773
774  double endSec = gettimeofday_sec() ;
775  os_ << "end MSWriter::fillProcessor() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
776}
777
778void MSWriter::fillSource()
779{
780  double startSec = gettimeofday_sec() ;
781  os_ << "start MSWriter::fillSource() startSec=" << startSec << LogIO::POST ;
782 
783  // access to MS SOURCE subtable
784  MSSource msSrc = mstable_->source() ;
785
786  // access to MOLECULE subtable
787  STMolecules stm = table_->molecules() ;
788
789  Int srcId = 0 ;
790  Vector<Double> restFreq ;
791  Vector<String> molName ;
792  Vector<String> fMolName ;
793
794  // row based
795  TableRow row( msSrc ) ;
796  TableRecord &rec = row.record() ;
797  RecordFieldPtr<Int> srcidRF( rec, "SOURCE_ID" ) ;
798  RecordFieldPtr<String> nameRF( rec, "NAME" ) ;
799  RecordFieldPtr< Array<Double> > srcpmRF( rec, "PROPER_MOTION" ) ;
800  RecordFieldPtr< Array<Double> > srcdirRF( rec, "DIRECTION" ) ;
801  RecordFieldPtr<Int> numlineRF( rec, "NUM_LINES" ) ;
802  RecordFieldPtr< Array<Double> > restfreqRF( rec, "REST_FREQUENCY" ) ;
803  RecordFieldPtr< Array<Double> > sysvelRF( rec, "SYSVEL" ) ;
804  RecordFieldPtr< Array<String> > transitionRF( rec, "TRANSITION" ) ;
805  RecordFieldPtr<Double> timeRF( rec, "TIME" ) ;
806  RecordFieldPtr<Double> intervalRF( rec, "INTERVAL" ) ;
807  RecordFieldPtr<Int> spwidRF( rec, "SPECTRAL_WINDOW_ID" ) ;
808
809  //
810  // ITERATION: SRCNAME
811  //
812  TableIterator iter0( table_->table(), "SRCNAME" ) ;
813  while( !iter0.pastEnd() ) {
814    //Table t0( iter0.table() ) ;
815    Table t0 =  iter0.table()  ;
816
817    // get necessary information
818    ROScalarColumn<String> srcNameCol( t0, "SRCNAME" ) ;
819    String srcName = srcNameCol( 0 ) ;
820    ROArrayColumn<Double> sharedDArrRCol( t0, "SRCPROPERMOTION" ) ;
821    Vector<Double> srcPM = sharedDArrRCol( 0 ) ;
822    sharedDArrRCol.attach( t0, "SRCDIRECTION" ) ;
823    Vector<Double> srcDir = sharedDArrRCol( 0 ) ;
824    ROScalarColumn<Double> srcVelCol( t0, "SRCVELOCITY" ) ;
825    Double srcVel = srcVelCol( 0 ) ;
826
827    // NAME
828    *nameRF = srcName ;
829
830    // SOURCE_ID
831    *srcidRF = srcId ;
832
833    // PROPER_MOTION
834    *srcpmRF = srcPM ;
835   
836    // DIRECTION
837    *srcdirRF = srcDir ;
838
839    //
840    // ITERATION: MOLECULE_ID
841    //
842    TableIterator iter1( t0, "MOLECULE_ID" ) ;
843    while( !iter1.pastEnd() ) {
844      //Table t1( iter1.table() ) ;
845      Table t1 = iter1.table() ;
846
847      // get necessary information
848      ROScalarColumn<uInt> molIdCol( t1, "MOLECULE_ID" ) ;
849      uInt molId = molIdCol( 0 ) ;
850      stm.getEntry( restFreq, molName, fMolName, molId ) ;
851
852      uInt numFreq = restFreq.size() ;
853     
854      // NUM_LINES
855      *numlineRF = numFreq ;
856
857      // REST_FREQUENCY
858      *restfreqRF = restFreq ;
859
860      // TRANSITION
861      *transitionRF = fMolName ;
862
863      // SYSVEL
864      Vector<Double> sysvelArr( numFreq, srcVel ) ;
865      *sysvelRF = sysvelArr ;
866
867      //
868      // ITERATION: IFNO
869      //
870      TableIterator iter2( t1, "IFNO" ) ;
871      while( !iter2.pastEnd() ) {
872        //Table t2( iter2.table() ) ;
873        Table t2 = iter2.table() ;
874        uInt nrow = msSrc.nrow() ;
875
876        // get necessary information
877        ROScalarColumn<uInt> ifNoCol( t2, "IFNO" ) ;
878        uInt ifno = ifNoCol( 0 ) ; // IFNO = SPECTRAL_WINDOW_ID
879        Double midTime ;
880        Double interval ;
881        getValidTimeRange( midTime, interval, t2 ) ;
882
883        // fill SPECTRAL_WINDOW_ID
884        *spwidRF = ifno ;
885
886        // fill TIME, INTERVAL
887        *timeRF = midTime ;
888        *intervalRF = interval ;
889
890        // add row
891        msSrc.addRow( 1, True ) ;
892        row.put( nrow ) ;
893
894        iter2.next() ;
895      }
896
897      iter1.next() ;
898    }
899
900    // increment srcId if SRCNAME changed
901    srcId++ ;
902
903    iter0.next() ;
904  }
905
906  double endSec = gettimeofday_sec() ;
907  os_ << "end MSWriter::fillSource() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
908}
909
910void MSWriter::fillWeather()
911{
912  double startSec = gettimeofday_sec() ;
913  os_ << "start MSWriter::fillWeather() startSec=" << startSec << LogIO::POST ;
914
915  // access to MS WEATHER subtable
916  MSWeather msw = mstable_->weather() ;
917
918  // access to WEATHER subtable
919  Table stw = table_->weather().table() ;
920  uInt nrow = stw.nrow() ;
921
922  if ( nrow == 0 )
923    return ;
924
925  msw.addRow( nrow, True ) ;
926  MSWeatherColumns mswCols( msw ) ;
927
928  // ANTENNA_ID is always 0
929  Vector<Int> antIdArr( nrow, 0 ) ;
930  mswCols.antennaId().putColumn( antIdArr ) ;
931
932  // fill weather status
933  ROScalarColumn<Float> sharedFloatCol( stw, "TEMPERATURE" ) ;
934  mswCols.temperature().putColumn( sharedFloatCol ) ;
935  sharedFloatCol.attach( stw, "PRESSURE" ) ;
936  mswCols.pressure().putColumn( sharedFloatCol ) ;
937  sharedFloatCol.attach( stw, "HUMIDITY" ) ;
938  mswCols.relHumidity().putColumn( sharedFloatCol ) ;
939  sharedFloatCol.attach( stw, "WINDSPEED" ) ;
940  mswCols.windSpeed().putColumn( sharedFloatCol ) ;
941  sharedFloatCol.attach( stw, "WINDAZ" ) ;
942  mswCols.windDirection().putColumn( sharedFloatCol ) ;
943
944  // fill TIME and INTERVAL
945  Double midTime ;
946  Double interval ;
947  Vector<Double> intervalArr( nrow, 0.0 ) ;
948  TableIterator iter( table_->table(), "WEATHER_ID" ) ;
949  while( !iter.pastEnd() ) {
950    //Table tab( iter.table() ) ;
951    Table tab = iter.table() ;
952
953    ROScalarColumn<uInt> widCol( tab, "WEATHER_ID" ) ;
954    uInt wid = widCol( 0 ) ;
955
956    getValidTimeRange( midTime, interval, tab ) ;
957    mswCols.time().put( wid, midTime ) ;
958    intervalArr[wid] = interval ;
959
960    iter.next() ;
961  }
962  mswCols.interval().putColumn( intervalArr ) ;
963
964  double endSec = gettimeofday_sec() ;
965  os_ << "end MSWriter::fillWeather() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
966}
967
968void MSWriter::fillSysCal()
969{
970  double startSec = gettimeofday_sec() ;
971  os_ << "start MSWriter::fillSysCal() startSec=" << startSec << LogIO::POST ;
972
973  //tcalIdRec_.print( cout ) ;
974
975  // access to MS SYSCAL subtable
976  MSSysCal mssc = mstable_->sysCal() ;
977
978  // access to TCAL subtable
979  Table stt = table_->tcal().table() ;
980  uInt nrow = stt.nrow() ;
981
982  // access to MAIN table
983  Block<String> cols( 6 ) ;
984  cols[0] = "TIME" ;
985  cols[1] = "TCAL_ID" ;
986  cols[2] = "TSYS" ;
987  cols[3] = "BEAMNO" ;
988  cols[4] = "IFNO" ;
989  cols[5] = "INTERVAL" ;
990  Table tab = table_->table().project( cols ) ;
991
992  if ( nrow == 0 )
993    return ;
994
995  nrow = tcalIdRec_.nfields() ;
996
997  Double midTime ;
998  Double interval ;
999  String timeStr ;
1000
1001  // row base
1002  TableRow row( mssc ) ;
1003  TableRecord &trec = row.record() ;
1004  RecordFieldPtr<Int> antennaRF( trec, "ANTENNA_ID" ) ;
1005  RecordFieldPtr<Int> feedRF( trec, "FEED_ID" ) ;
1006  RecordFieldPtr<Int> spwRF( trec, "SPECTRAL_WINDOW_ID" ) ;
1007  RecordFieldPtr<Double> timeRF( trec, "TIME" ) ;
1008  RecordFieldPtr<Double> intervalRF( trec, "INTERVAL" ) ;
1009  RecordFieldPtr< Array<Float> > tsysRF( trec, "TSYS" ) ;
1010  RecordFieldPtr< Array<Float> > tcalRF( trec, "TCAL" ) ;
1011  RecordFieldPtr< Array<Float> > tsysspRF ;
1012  RecordFieldPtr< Array<Float> > tcalspRF ;
1013  if ( tsysSpec_ )
1014    tsysspRF.attachToRecord( trec, "TSYS_SPECTRUM" ) ;
1015  if ( tcalSpec_ )
1016    tcalspRF.attachToRecord( trec, "TCAL_SPECTRUM" ) ;
1017
1018  // ANTENNA_ID is always 0
1019  *antennaRF = 0 ;
1020
1021  Table sortedstt = stt.sort( "ID" ) ;
1022  ROArrayColumn<Float> tcalCol( sortedstt, "TCAL" ) ;
1023  ROTableColumn idCol( sortedstt, "ID" ) ;
1024  ROArrayColumn<Float> tsysCol( tab, "TSYS" ) ;
1025  ROTableColumn tcalidCol( tab, "TCAL_ID" ) ;
1026  ROTableColumn timeCol( tab, "TIME" ) ;
1027  ROTableColumn intervalCol( tab, "INTERVAL" ) ;
1028  ROTableColumn beamnoCol( tab, "BEAMNO" ) ;
1029  ROTableColumn ifnoCol( tab, "IFNO" ) ;
1030  for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
1031    double t1 = gettimeofday_sec() ;
1032    Vector<uInt> ids = tcalIdRec_.asArrayuInt( irow ) ;
1033    os_ << "ids = " << ids << LogIO::POST ;
1034    uInt npol = ids.size() ;
1035    Vector<uInt> rows = tcalRowRec_.asArrayuInt( irow ) ;
1036    os_ << "rows = " << rows << LogIO::POST ;
1037    Vector<Double> atime( rows.nelements() ) ;
1038    Vector<Double> ainterval( rows.nelements() ) ;
1039    Vector<uInt> atcalid( rows.nelements() ) ;
1040    for( uInt jrow = 0 ; jrow < rows.nelements() ; jrow++ ) {
1041      atime[jrow] = (Double)timeCol.asdouble( rows[jrow] ) ;
1042      ainterval[jrow] = (Double)intervalCol.asdouble( rows[jrow] ) ;
1043      atcalid[jrow] = tcalidCol.asuInt( rows[jrow] ) ;
1044    }
1045    Vector<Float> dummy = tsysCol( rows[0] ) ;
1046    Matrix<Float> tsys( npol,dummy.nelements() ) ;
1047    tsys.row( 0 ) = dummy ;
1048    for ( uInt jrow = 1 ; jrow < npol ; jrow++ )
1049      tsys.row( jrow ) = tsysCol( rows[jrow] ) ;
1050
1051    // FEED_ID
1052    *feedRF = beamnoCol.asuInt( rows[0] ) ;
1053
1054    // SPECTRAL_WINDOW_ID
1055    *spwRF = ifnoCol.asuInt( rows[0] ) ;
1056
1057    // TIME and INTERVAL
1058    getValidTimeRange( midTime, interval, atime, ainterval ) ;
1059    *timeRF = midTime ;
1060    *intervalRF = interval ;
1061
1062    // TCAL and TSYS
1063    Matrix<Float> tcal ;
1064    Table t ;
1065    if ( idCol.asuInt( ids[0] ) == ids[0] ) {
1066      os_ << "sorted at irow=" << irow << " ids[0]=" << ids[0] << LogIO::POST ;
1067      Vector<Float> dummyC = tcalCol( ids[0] ) ;
1068      tcal.resize( npol, dummyC.size() ) ;
1069      tcal.row( 0 ) = dummyC ;
1070    }
1071    else {
1072      os_ << "NOT sorted at irow=" << irow << " ids[0]=" << ids[0] << LogIO::POST ;
1073      t = stt( stt.col("ID") == ids[0] ) ;
1074      Vector<Float> dummyC = tcalCol( 0 ) ;
1075      tcal.resize( npol, dummyC.size() ) ;
1076      tcal.row( 0 ) = dummyC ;
1077    }
1078    if ( npol == 2 ) {
1079      if ( idCol.asuInt( ids[1] ) == ids[1] ) {
1080        os_ << "sorted at irow=" << irow << " ids[1]=" << ids[1] << LogIO::POST ;
1081        tcal.row( 1 ) = tcalCol( ids[1] ) ;
1082      }
1083      else {
1084        os_ << "NOT sorted at irow=" << irow << " ids[1]=" << ids[1] << LogIO::POST ;
1085        t = stt( stt.col("ID") == ids[1] ) ;
1086        tcalCol.attach( t, "TCAL" ) ;
1087        tcal.row( 1 ) = tcalCol( 1 ) ;
1088      }
1089    }
1090    else if ( npol == 3 ) {
1091      if ( idCol.asuInt( ids[2] ) == ids[2] )
1092        tcal.row( 1 ) = tcalCol( ids[2] ) ;
1093      else {
1094        t = stt( stt.col("ID") == ids[2] ) ;
1095        tcalCol.attach( t, "TCAL" ) ;
1096        tcal.row( 1 ) = tcalCol( 0 ) ;
1097      }
1098      if ( idCol.asuInt( ids[1] ) == ids[1] )
1099        tcal.row( 2 ) = tcalCol( ids[1] ) ;
1100      else {
1101        t = stt( stt.col("ID") == ids[1] ) ;
1102        tcalCol.attach( t, "TCAL" ) ;
1103        tcal.row( 2 ) = tcalCol( 0 ) ;
1104      }
1105    }
1106    else if ( npol == 4 ) {
1107      if ( idCol.asuInt( ids[2] ) == ids[2] )
1108        tcal.row( 1 ) = tcalCol( ids[2] ) ;
1109      else {
1110        t = stt( stt.col("ID") == ids[2] ) ;
1111        tcalCol.attach( t, "TCAL" ) ;
1112        tcal.row( 1 ) = tcalCol( 0 ) ;
1113      }
1114      if ( idCol.asuInt( ids[3] ) == ids[3] )
1115        tcal.row( 2 ) = tcalCol( ids[3] ) ;
1116      else {
1117        t = stt( stt.col("ID") == ids[3] ) ;
1118        tcalCol.attach( t, "TCAL" ) ;
1119        tcal.row( 2 ) = tcalCol( 0 ) ;
1120      }
1121      if ( idCol.asuInt( ids[1] ) == ids[1] )
1122        tcal.row( 2 ) = tcalCol( ids[1] ) ;
1123      else {
1124        t = stt( stt.col("ID") == ids[1] ) ;
1125        tcalCol.attach( t, "TCAL" ) ;
1126        tcal.row( 3 ) = tcalCol( 0 ) ;
1127      }
1128    }
1129    if ( tcalSpec_ ) {
1130      // put TCAL_SPECTRUM
1131      *tcalspRF = tcal ;
1132      // set TCAL (mean of TCAL_SPECTRUM)
1133      Matrix<Float> tcalMean( npol, 1 ) ;
1134      for ( uInt iid = 0 ; iid < npol ; iid++ ) {
1135        tcalMean( iid, 0 ) = mean( tcal.row(iid) ) ;
1136      }
1137      // put TCAL
1138      *tcalRF = tcalMean ;
1139    }
1140    else {
1141      // put TCAL
1142      *tcalRF = tcal ;
1143    }
1144   
1145    if ( tsysSpec_ ) {
1146      // put TSYS_SPECTRUM
1147      *tsysspRF = tsys ;
1148      // set TSYS (mean of TSYS_SPECTRUM)
1149      Matrix<Float> tsysMean( npol, 1 ) ;
1150      for ( uInt iid = 0 ; iid < npol ; iid++ ) {
1151        tsysMean( iid, 0 ) = mean( tsys.row(iid) ) ;
1152      }
1153      // put TSYS
1154      *tsysRF = tsysMean ;
1155    }
1156    else {
1157      // put TSYS
1158      *tsysRF = tsys ;
1159    }
1160
1161    // add row
1162    mssc.addRow( 1, True ) ;
1163    row.put( mssc.nrow()-1 ) ;
1164
1165    double t2 = gettimeofday_sec() ;
1166    os_ << irow << "th loop elapsed time = " << t2-t1 << "sec" << LogIO::POST ;
1167  }
1168 
1169  double endSec = gettimeofday_sec() ;
1170  os_ << "end MSWriter::fillSysCal() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1171}
1172
1173void MSWriter::addFeed( Int id )
1174{
1175  double startSec = gettimeofday_sec() ;
1176  os_ << "start MSWriter::addFeed() startSec=" << startSec << LogIO::POST ;
1177
1178  // add row
1179  MSFeed msFeed = mstable_->feed() ;
1180  msFeed.addRow( 1, True ) ;
1181  Int nrow = msFeed.nrow() ;
1182
1183  MSFeedColumns msFeedCols( mstable_->feed() ) ;
1184
1185  msFeedCols.feedId().put( nrow-1, id ) ;
1186  msFeedCols.antennaId().put( nrow-1, 0 ) ;
1187
1188  double endSec = gettimeofday_sec() ;
1189  os_ << "end MSWriter::addFeed() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1190}
1191
1192void MSWriter::addSpectralWindow( Int spwid, Int freqid )
1193{
1194  double startSec = gettimeofday_sec() ;
1195  os_ << "start MSWriter::addSpectralWindow() startSec=" << startSec << LogIO::POST ;
1196 
1197  // add row
1198  MSSpectralWindow msSpw = mstable_->spectralWindow() ;
1199  while( (Int)msSpw.nrow() <= spwid ) {
1200    msSpw.addRow( 1, True ) ;
1201  }
1202 
1203  MSSpWindowColumns msSpwCols( msSpw ) ;
1204
1205  STFrequencies stf = table_->frequencies() ;
1206
1207  // MEAS_FREQ_REF
1208  msSpwCols.measFreqRef().put( spwid, stf.getFrame( True ) ) ;
1209
1210  Double refpix ;
1211  Double refval ;
1212  Double inc ;
1213  stf.getEntry( refpix, refval, inc, (uInt)freqid ) ;
1214
1215  // NUM_CHAN
1216  Int nchan = (Int)(refpix * 2) ;
1217  msSpwCols.numChan().put( spwid, nchan ) ;
1218
1219  // TOTAL_BANDWIDTH
1220  Double bw = nchan * inc ;
1221  msSpwCols.totalBandwidth().put( spwid, bw ) ;
1222
1223  // REF_FREQUENCY
1224  Double refFreq = refval - refpix * inc ;
1225  msSpwCols.refFrequency().put( spwid, refFreq ) ;
1226
1227  // NET_SIDEBAND
1228  // tentative: USB->0, LSB->1
1229  Int netSideband = 0 ;
1230  if ( inc < 0 )
1231    netSideband = 1 ;
1232  msSpwCols.netSideband().put( spwid, netSideband ) ;
1233
1234  // RESOLUTION, CHAN_WIDTH, EFFECTIVE_BW
1235  Vector<Double> sharedDoubleArr( nchan, inc ) ;
1236  msSpwCols.resolution().put( spwid, sharedDoubleArr ) ;
1237  msSpwCols.chanWidth().put( spwid, sharedDoubleArr ) ;
1238  msSpwCols.effectiveBW().put( spwid, sharedDoubleArr ) ;
1239
1240  // CHAN_FREQ
1241  indgen( sharedDoubleArr, refFreq, inc ) ;
1242  msSpwCols.chanFreq().put( spwid, sharedDoubleArr ) ;
1243
1244  double endSec = gettimeofday_sec() ;
1245  os_ << "end MSWriter::addSpectralWindow() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1246}
1247
1248void MSWriter::addField( Int fid, String fieldname, String srcname, Double t, Vector<Double> rate )
1249{
1250  double startSec = gettimeofday_sec() ;
1251  os_ << "start MSWriter::addField() startSec=" << startSec << LogIO::POST ;
1252 
1253  MSField msField = mstable_->field() ;
1254  while( (Int)msField.nrow() <= fid ) {
1255    msField.addRow( 1, True ) ;
1256  }
1257  MSFieldColumns msFieldCols( msField ) ;
1258
1259  // Access to SOURCE table
1260  MSSource msSrc = mstable_->source() ;
1261
1262  // fill target row
1263  msFieldCols.name().put( fid, fieldname ) ;
1264  msFieldCols.time().put( fid, t ) ;
1265  Int numPoly = 0 ;
1266  if ( anyNE( rate, 0.0 ) )
1267    numPoly = 1 ;
1268  msFieldCols.numPoly().put( fid, numPoly ) ;
1269  MSSourceIndex msSrcIdx( msSrc ) ;
1270  Int srcId = -1 ;
1271  Vector<Int> srcIdArr = msSrcIdx.matchSourceName( srcname ) ;
1272  if ( srcIdArr.size() != 0 ) {
1273    srcId = srcIdArr[0] ;
1274    MSSource msSrcSel = msSrc( msSrc.col("SOURCE_ID") == srcId ) ;
1275    ROMSSourceColumns msSrcCols( msSrcSel ) ;
1276    Vector<Double> srcDir = msSrcCols.direction()( 0 ) ;
1277    Matrix<Double> srcDirA( IPosition( 2, 2, 1+numPoly ) ) ;
1278    os_ << "srcDirA = " << srcDirA << LogIO::POST ;
1279    os_ << "sliced srcDirA = " << srcDirA.column( 0 ) << LogIO::POST ;
1280    srcDirA.column( 0 ) = srcDir ;
1281    os_ << "srcDirA = " << srcDirA << LogIO::POST ;
1282    if ( numPoly != 0 )
1283      srcDirA.column( 1 ) = rate ;
1284    msFieldCols.phaseDir().put( fid, srcDirA ) ;
1285    msFieldCols.referenceDir().put( fid, srcDirA ) ;
1286    msFieldCols.delayDir().put( fid, srcDirA ) ;
1287  }
1288  msFieldCols.sourceId().put( fid, srcId ) ;
1289
1290  double endSec = gettimeofday_sec() ;
1291  os_ << "end MSWriter::addField() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1292}
1293
1294void MSWriter::addPointing( String &name, Double &me, Double &interval, Matrix<Double> &dir )
1295{
1296  double startSec = gettimeofday_sec() ;
1297  os_ << "start MSWriter::addPointing() startSec=" << startSec << LogIO::POST ;
1298 
1299  // access to POINTING subtable
1300  MSPointing msp = mstable_->pointing() ;
1301  uInt nrow = msp.nrow() ;
1302
1303  // add row
1304  msp.addRow( 1, True ) ;
1305
1306  // fill row
1307  TableRow row( msp ) ;
1308  TableRecord &rec = row.record() ;
1309  RecordFieldPtr<Int> antennaRF( rec, "ANTENNA_ID" ) ;
1310  *antennaRF = 0 ;
1311  RecordFieldPtr<Int> numpolyRF( rec, "NUM_POLY" ) ;
1312  *numpolyRF = dir.ncolumn() ;
1313  RecordFieldPtr<Double> timeRF( rec, "TIME" ) ;
1314  *timeRF = me ;
1315  RecordFieldPtr<Double> toriginRF( rec, "TIME_ORIGIN" ) ;
1316  *toriginRF = me ;
1317  RecordFieldPtr<Double> intervalRF( rec, "INTERVAL" ) ;
1318  *intervalRF = interval ;
1319  RecordFieldPtr<String> nameRF( rec, "NAME" ) ;
1320  *nameRF = name ;
1321  RecordFieldPtr<Bool> trackRF( rec, "TRACKING" ) ;
1322  *trackRF = True ;
1323  RecordFieldPtr< Array<Double> > dirRF( rec, "DIRECTION" ) ;
1324  *dirRF = dir ;
1325  RecordFieldPtr< Array<Double> > targetRF( rec, "TARGET" ) ;
1326  *dirRF = dir ;
1327  row.put( nrow ) ;
1328
1329  double endSec = gettimeofday_sec() ;
1330  os_ << "end MSWriter::addPointing() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1331}
1332
1333Int MSWriter::addPolarization( Vector<Int> polnos )
1334{
1335  double startSec = gettimeofday_sec() ;
1336  os_ << "start MSWriter::addPolarization() startSec=" << startSec << LogIO::POST ;
1337
1338  os_ << "polnos = " << polnos << LogIO::POST ;
1339  MSPolarization msPol = mstable_->polarization() ;
1340  uInt nrow = msPol.nrow() ;
1341
1342  // only 1 POLARIZATION row for 1 scantable
1343  if ( nrow > 0 )
1344    return 1 ;
1345 
1346  Vector<Int> corrType = toCorrType( polnos ) ;
1347 
1348  ROArrayColumn<Int> corrtCol( msPol, "CORR_TYPE" ) ;
1349  Matrix<Int> corrTypeArr = corrtCol.getColumn() ;
1350  Int polid = -1 ;
1351  for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
1352    if ( allEQ( corrType, corrTypeArr.column( irow ) ) ) {
1353      polid = irow ;
1354      break ;
1355    }
1356  }
1357
1358  if ( polid == -1 ) {
1359    MSPolarizationColumns msPolCols( msPol ) ;
1360
1361    // add row
1362    msPol.addRow( 1, True ) ;
1363    polid = (Int)nrow ;
1364
1365    // CORR_TYPE
1366    msPolCols.corrType().put( nrow, corrType ) ;
1367
1368    // NUM_CORR
1369    uInt npol = corrType.size() ;
1370    msPolCols.numCorr().put( nrow, npol ) ;
1371
1372    // CORR_PRODUCT
1373    Matrix<Int> corrProd( 2, npol, -1 ) ;
1374    if ( npol == 1 ) {
1375      corrProd = 0 ;
1376    }
1377    else if ( npol == 2 ) {
1378      corrProd.column( 0 ) = 0 ;
1379      corrProd.column( 1 ) = 1 ;
1380    }
1381    else {
1382      corrProd.column( 0 ) = 0 ;
1383      corrProd.column( 3 ) = 1 ;
1384      corrProd( 0,1 ) = 0 ;
1385      corrProd( 1,1 ) = 1 ;
1386      corrProd( 0,2 ) = 1 ;
1387      corrProd( 1,2 ) = 0 ;
1388    }
1389    msPolCols.corrProduct().put( nrow, corrProd ) ;   
1390  }
1391
1392  double endSec = gettimeofday_sec() ;
1393  os_ << "end MSWriter::addPolarization() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1394
1395  return polid ;
1396}
1397
1398Int MSWriter::addDataDescription( Int polid, Int spwid )
1399{
1400  double startSec = gettimeofday_sec() ;
1401  os_ << "start MSWriter::addDataDescription() startSec=" << startSec << LogIO::POST ;
1402
1403  MSDataDescription msDataDesc = mstable_->dataDescription() ;
1404  uInt nrow = msDataDesc.nrow() ;
1405
1406  // only 1 POLARIZATION_ID for 1 scantable
1407  Int ddid = -1 ;
1408  ROScalarColumn<Int> spwCol( msDataDesc, "SPECTRAL_WINDOW_ID" ) ;
1409  Vector<Int> spwIds = spwCol.getColumn() ;
1410  //ROScalarColumn<Int> polCol( msDataDesc, "POLARIZATION_ID" ) ;
1411  //Vector<Int> polIds = polCol.getColumn() ;
1412  for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
1413    //if ( spwid == spwIds[irow] && polid == polIds[irow] ) {
1414    if ( spwid == spwIds[irow] ) {
1415      ddid = irow ;
1416      break ;
1417    }
1418  }
1419  os_ << "ddid = " << ddid << LogIO::POST ;
1420 
1421
1422  if ( ddid == -1 ) {
1423    msDataDesc.addRow( 1, True ) ;
1424    MSDataDescColumns msDataDescCols( msDataDesc ) ;
1425    msDataDescCols.polarizationId().put( nrow, polid ) ;
1426    msDataDescCols.spectralWindowId().put( nrow, spwid ) ;
1427    ddid = (Int)nrow ;
1428  }
1429
1430  double endSec = gettimeofday_sec() ;
1431  os_ << "end MSWriter::addDataDescription() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1432
1433  return ddid ;
1434}
1435
1436Int MSWriter::addState( Int st, Int &subscan )
1437{
1438  double startSec = gettimeofday_sec() ;
1439  os_ << "start MSWriter::addState() startSec=" << startSec << LogIO::POST ;
1440
1441  // access to STATE subtable
1442  MSState msState = mstable_->state() ;
1443  uInt nrow = msState.nrow() ;
1444
1445  String obsMode ;
1446  Bool isSignal ;
1447  Double tnoise ;
1448  Double tload ;
1449  queryType( st, obsMode, isSignal, tnoise, tload ) ;
1450  os_ << "obsMode = " << obsMode << " isSignal = " << isSignal << LogIO::POST ;
1451
1452  Int idx = -1 ;
1453  ROScalarColumn<String> obsModeCol( msState, "OBS_MODE" ) ;
1454  //ROScalarColumn<Bool> sigCol( msState, "SIG" ) ;
1455  //ROScalarColumn<Bool> refCol( msState, "REF" ) ;
1456  ROScalarColumn<Int> subscanCol( msState, "SUB_SCAN" ) ;
1457//   Vector<String> obsModeArr = obsModeCol.getColumn() ;
1458//   Vector<Bool> sigArr = sigCol.getColumn() ;
1459//   Vector<Bool> refArr = refCol.getColumn() ;
1460//   Vector<Int> subscanArr = subscanCol.getColumn() ;
1461  for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
1462    if ( obsModeCol(irow) == obsMode
1463         //&& sigCol(irow) == isSignal
1464         //&& refCol(irow) != isSignal
1465         && subscanCol(irow) == subscan ) {
1466//     if ( obsModeArr[irow] == obsMode
1467//          && sigArr[irow] == isSignal
1468//          && refArr[irow] != isSignal
1469//          && subscanArr[irow] == subscan ) {
1470      idx = irow ;
1471      break ;
1472    }
1473  }
1474  if ( idx == -1 ) {
1475    msState.addRow( 1, True ) ;
1476    TableRow row( msState ) ;
1477    TableRecord &rec = row.record() ;
1478    RecordFieldPtr<String> obsmodeRF( rec, "OBS_MODE" ) ;
1479    *obsmodeRF = obsMode ;
1480    RecordFieldPtr<Bool> sigRF( rec, "SIG" ) ;
1481    *sigRF = isSignal ;
1482    RecordFieldPtr<Bool> refRF( rec, "REF" ) ;
1483    *refRF = !isSignal ;
1484    RecordFieldPtr<Int> subscanRF( rec, "SUB_SCAN" ) ;
1485    *subscanRF = subscan ;
1486    RecordFieldPtr<Double> noiseRF( rec, "CAL" ) ;
1487    *noiseRF = tnoise ;
1488    RecordFieldPtr<Double> loadRF( rec, "LOAD" ) ;
1489    *loadRF = tload ;
1490    row.put( nrow ) ;
1491//     ScalarColumn<String> obsModeCol( msState, "OBS_MODE" ) ;
1492//     obsModeCol.put( nrow, obsMode ) ;
1493//     ScalarColumn<Bool> sharedBCol( msState, "SIG" ) ;
1494//     sharedBCol.put( nrow, isSignal ) ;
1495//     sharedBCol.attach( msState, "REF" ) ;
1496//     sharedBCol.put( nrow, !isSignal ) ;
1497//     ScalarColumn<Int> subscanCol( msState, "SUB_SCAN" ) ;
1498//     subscanCol.put( nrow, subscan ) ;
1499    idx = nrow ;
1500  }
1501  subscan++ ;
1502
1503  double endSec = gettimeofday_sec() ;
1504  os_ << "end MSWriter::addState() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1505
1506  return idx ;
1507}
1508
1509Vector<Int> MSWriter::toCorrType( Vector<Int> polnos )
1510{
1511  double startSec = gettimeofday_sec() ;
1512  os_ << "start MSWriter::toCorrType() startSec=" << startSec << LogIO::POST ;
1513
1514  uInt npol = polnos.size() ;
1515  Vector<Int> corrType( npol, Stokes::Undefined ) ;
1516 
1517  if ( npol == 4 ) {
1518    if ( polType_ == "linear" ) {
1519      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1520        if ( polnos[ipol] == 0 )
1521          corrType[ipol] = Stokes::XX ;
1522        else if ( polnos[ipol] == 1 )
1523          corrType[ipol] = Stokes::XY ;
1524        else if ( polnos[ipol] == 2 )
1525          corrType[ipol] = Stokes::YX ;
1526        else if ( polnos[ipol] == 3 )
1527          corrType[ipol] = Stokes::YY ;
1528      }
1529    }
1530    else if ( polType_ == "circular" ) {
1531      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1532        if ( polnos[ipol] == 0 )
1533          corrType[ipol] = Stokes::RR ;
1534        else if ( polnos[ipol] == 1 )
1535          corrType[ipol] = Stokes::RL ;
1536        else if ( polnos[ipol] == 2 )
1537          corrType[ipol] = Stokes::LR ;
1538        else if ( polnos[ipol] == 3 )
1539          corrType[ipol] = Stokes::LL ;
1540      }
1541    }
1542    else if ( polType_ == "stokes" ) {
1543      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1544        if ( polnos[ipol] == 0 )
1545          corrType[ipol] = Stokes::I ;
1546        else if ( polnos[ipol] == 1 )
1547          corrType[ipol] = Stokes::Q ;
1548        else if ( polnos[ipol] == 2 )
1549          corrType[ipol] = Stokes::U ;
1550        else if ( polnos[ipol] == 3 )
1551          corrType[ipol] = Stokes::V ;
1552      }
1553    }
1554  }
1555  else if ( npol == 2 ) {
1556    if ( polType_ == "linear" ) {
1557      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1558        if ( polnos[ipol] == 0 )
1559          corrType[ipol] = Stokes::XX ;
1560        else if ( polnos[ipol] == 1 )
1561          corrType[ipol] = Stokes::YY ;
1562      }
1563    }
1564    else if ( polType_ == "circular" ) {
1565      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1566        if ( polnos[ipol] == 0 )
1567          corrType[ipol] = Stokes::RR ;
1568        else if ( polnos[ipol] == 1 )
1569          corrType[ipol] = Stokes::LL ;
1570      }
1571    }
1572    else if ( polType_ == "stokes" ) {
1573      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1574        if ( polnos[ipol] == 0 )
1575          corrType[ipol] = Stokes::I ;
1576        else if ( polnos[ipol] == 1 )
1577          corrType[ipol] = Stokes::V ;
1578      }
1579    }
1580    else if ( polType_ == "linpol" ) {
1581      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1582        if ( polnos[ipol] == 1 )
1583          corrType[ipol] = Stokes::Plinear ;
1584        else if ( polnos[ipol] == 2 )
1585          corrType[ipol] = Stokes::Pangle ;
1586      }
1587    }
1588  }     
1589  else if ( npol == 1 ) {
1590    if ( polType_ == "linear" )
1591      corrType[0] = Stokes::XX ;
1592    else if ( polType_ == "circular" )
1593      corrType[0] = Stokes::RR ;
1594    else if ( polType_ == "stokes" )
1595      corrType[0] = Stokes::I ;
1596  }
1597
1598  double endSec = gettimeofday_sec() ;
1599  os_ << "end MSWriter::toCorrType() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1600
1601  return corrType ;
1602}
1603
1604void MSWriter::getValidTimeRange( Double &me, Double &interval, Table &tab )
1605{
1606  double startSec = gettimeofday_sec() ;
1607  os_ << "start MSWriter::getVaridTimeRange() startSec=" << startSec << LogIO::POST ;
1608
1609  // sort table
1610  //Table stab = tab.sort( "TIME" ) ;
1611
1612  ROScalarColumn<Double> timeCol( tab, "TIME" ) ;
1613  Vector<Double> timeArr = timeCol.getColumn() ;
1614  Double minTime ;
1615  Double maxTime ;
1616  minMax( minTime, maxTime, timeArr ) ;
1617  Double midTime = 0.5 * ( minTime + maxTime ) * 86400.0 ;
1618  // unit for TIME
1619  // Scantable: "d"
1620  // MS: "s"
1621  me = midTime ;
1622  interval = ( maxTime - minTime ) * 86400.0 ;
1623
1624  double endSec = gettimeofday_sec() ;
1625  os_ << "end MSWriter::getValidTimeRange() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1626}
1627
1628void MSWriter::getValidTimeRange( Double &me, Double &interval, Vector<Double> &atime, Vector<Double> &ainterval )
1629{
1630  double startSec = gettimeofday_sec() ;
1631  os_ << "start MSWriter::getVaridTimeRange() startSec=" << startSec << LogIO::POST ;
1632
1633  // sort table
1634  //Table stab = tab.sort( "TIME" ) ;
1635
1636  Double minTime ;
1637  Double maxTime ;
1638  minMax( minTime, maxTime, atime ) ;
1639  Double midTime = 0.5 * ( minTime + maxTime ) * 86400.0 ;
1640  // unit for TIME
1641  // Scantable: "d"
1642  // MS: "s"
1643  me = midTime ;
1644  interval = ( maxTime - minTime ) * 86400.0 ;
1645
1646  double endSec = gettimeofday_sec() ;
1647  os_ << "end MSWriter::getValidTimeRange() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1648}
1649
1650//void MSWriter::queryType( Int type, String &stype, Bool &b )
1651void MSWriter::queryType( Int type, String &stype, Bool &b, Double &t, Double &l )
1652{
1653  double startSec = gettimeofday_sec() ;
1654  os_ << "start MSWriter::queryType() startSec=" << startSec << LogIO::POST ;
1655
1656  switch ( type ) {
1657  case SrcType::PSON:
1658    stype = "POSITION_SWITCH.OBSERVE_TARGET.ON_SOURCE" ;
1659    b = True ;
1660    t = 0.0 ;
1661    l = 0.0 ;
1662    break ;
1663  case SrcType::PSOFF:
1664    stype = "POSITION_SWITCH.OBSERVE_TARGET.OFF_SOURCE" ;
1665    b = False ;
1666    t = 0.0 ;
1667    l = 0.0 ;
1668    break ;
1669  case SrcType::NOD:
1670    stype = "NOD.OBSERVE_TARGET.ON_SOURCE" ;
1671    b = True ;
1672    t = 0.0 ;
1673    l = 0.0 ;
1674    break ;
1675  case SrcType::FSON:
1676    stype = "FREQUENCY_SWITCH.OBSERVE_TARGET.ON_SOURCE" ;
1677    b = True ;
1678    t = 0.0 ;
1679    l = 0.0 ;
1680    break ;
1681  case SrcType::FSOFF:
1682    stype = "FREQUENCY_SWITCH.OBSERVE_TARGET.ON_SOURCE" ;
1683    b = False ;
1684    t = 0.0 ;
1685    l = 0.0 ;
1686    break ;
1687  case SrcType::SKY:
1688    stype = "UNSPECIFIED.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1689    b = False ;
1690    t = 0.0 ;
1691    l = 1.0 ;
1692    break ;
1693  case SrcType::HOT:
1694    stype = "UNSPECIFIED.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1695    b = False ;
1696    t = 0.0 ;
1697    l = 1.0 ;
1698    break ;
1699  case SrcType::WARM:
1700    stype = "UNSPECIFIED.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1701    t = 0.0 ;
1702    b = False ;
1703    l = 1.0 ;
1704    break ;
1705  case SrcType::COLD:
1706    stype = "UNSPECIFIED.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1707    b = False ;
1708    t = 0.0 ;
1709    l = 1.0 ;
1710    break ;
1711  case SrcType::PONCAL:
1712    stype = "POSITION_SWITCH.CALIBRATE_TEMPERATURE.ON_SOURCE" ;
1713    b = True ;
1714    t = 1.0 ;
1715    l = 0.0 ;
1716    break ;
1717  case SrcType::POFFCAL:
1718    stype = "POSITION_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1719    b = False ;
1720    t = 1.0 ;
1721    l = 0.0 ;
1722    break ;
1723  case SrcType::NODCAL:
1724    stype = "NOD.CALIBRATE_TEMPERATURE.ON_SOURCE" ;
1725    b = True ;
1726    t = 1.0 ;
1727    l = 0.0 ;
1728    break ;
1729  case SrcType::FONCAL:
1730    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.ON_SOURCE" ;
1731    b = True ;
1732    t = 1.0 ;
1733    l = 0.0 ;
1734    break ;
1735  case SrcType::FOFFCAL:
1736    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1737    b = False ;
1738    t = 1.0 ;
1739    l = 0.0 ;
1740    break ;
1741  case SrcType::FSLO:
1742    stype = "FREQUENCY_SWITCH.OBSERVE_TARGET.ON_SOURCE" ;
1743    b = True ;
1744    t = 0.0 ;
1745    l = 0.0 ;
1746    break ;
1747  case SrcType::FLOOFF:
1748    stype = "FREQUENCY_SWITCH.OBSERVE_TARGET.OFF_SOURCE" ;
1749    b = False ;
1750    t = 0.0 ;
1751    l = 0.0 ;
1752    break ;
1753  case SrcType::FLOSKY:
1754    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1755    b = False ;
1756    t = 0.0 ;
1757    l = 1.0 ;
1758    break ;
1759  case SrcType::FLOHOT:
1760    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1761    b = False ;
1762    t = 0.0 ;
1763    l = 1.0 ;
1764    break ;
1765  case SrcType::FLOWARM:
1766    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1767    b = False ;
1768    t = 0.0 ;
1769    l = 1.0 ;
1770    break ;
1771  case SrcType::FLOCOLD:
1772    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1773    b = False ;
1774    t = 0.0 ;
1775    l = 1.0 ;
1776    break ;
1777  case SrcType::FSHI:
1778    stype = "FREQUENCY_SWITCH.OBSERVE_TARGET.ON_SOURCE" ;
1779    b = True ;
1780    t = 0.0 ;
1781    l = 0.0 ;
1782    break ;
1783  case SrcType::FHIOFF:
1784    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1785    b = False ;
1786    t = 0.0 ;
1787    l = 0.0 ;
1788    break ;
1789  case SrcType::FHISKY:
1790    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1791    b = False ;
1792    t = 0.0 ;
1793    l = 1.0 ;
1794    break ;
1795  case SrcType::FHIHOT:
1796    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1797    b = False ;
1798    t = 0.0 ;
1799    l = 1.0 ;
1800    break ;
1801  case SrcType::FHIWARM:
1802    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1803    b = False ;
1804    t = 0.0 ;
1805    l = 1.0 ;
1806    break ;
1807  case SrcType::FHICOLD:
1808    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1809    b = False ;
1810    t = 0.0 ;
1811    l = 1.0 ;
1812    break ;
1813  case SrcType::SIG:
1814    stype = "UNSPECIFIED.OBSERVE_TARGET.ON_SOURCE" ;
1815    b = True ;
1816    t = 0.0 ;
1817    l = 0.0 ;
1818    break ;
1819  case SrcType::REF:
1820    stype = "UNSPECIFIED.OBSERVE_TARGET.ON_SOURCE" ;
1821    b = False ;
1822    t = 0.0 ;
1823    l = 0.0 ;
1824    break ;
1825  default:
1826    stype = "UNSPECIFIED" ;
1827    b = True ;
1828    t = 0.0 ;
1829    l = 0.0 ;
1830    break ;
1831  }
1832
1833  double endSec = gettimeofday_sec() ;
1834  os_ << "end MSWriter::queryType() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1835}
1836}
Note: See TracBrowser for help on using the repository browser.