source: trunk/src/MSWriter.cpp @ 2026

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

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