source: branches/casa-prerelease/pre-asap/src/MSWriter.cpp @ 2188

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

New Development: No

JIRA Issue: Yes CSV-929 etc.

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

Merge several bug fixes for MSFiller/Writer in trunk
(r2167,r2176,r2184,r2185,r2187).


File size: 63.4 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  // fill empty SPECTRAL_WINDOW rows
447  infillSpectralWindow() ;
448
449  // ASDM tables
450  const TableRecord &stKeys = table_->table().keywordSet() ;
451  TableRecord &msKeys = mstable_->rwKeywordSet() ;
452  uInt nfields = stKeys.nfields() ;
453  for ( uInt ifield = 0 ; ifield < nfields ; ifield++ ) {
454    String kname = stKeys.name( ifield ) ;
455    if ( kname.find( "ASDM" ) != String::npos ) {
456      String asdmpath = stKeys.asString( ifield ) ;
457      os_ << "found ASDM table: " << asdmpath << LogIO::POST ;
458      if ( Table::isReadable( asdmpath ) ) {
459        Table newAsdmTab( asdmpath, Table::Old ) ;
460        newAsdmTab.copy( filename_+"/"+kname, Table::New ) ;
461        os_ << "add subtable: " << kname << LogIO::POST ;
462        msKeys.defineTable( kname, Table( filename_+"/"+kname, Table::Old ) ) ;
463      }
464    }
465  }
466
467  // replace POINTING table with original one if exists
468  if ( ptTabName_ != "" ) {
469    delete mstable_ ;
470    mstable_ = 0 ;
471    Table newPtTab( ptTabName_, Table::Old ) ;
472    newPtTab.copy( filename_+"/POINTING", Table::New ) ;
473  }
474
475//   double endSec = gettimeofday_sec() ;
476//   os_ << "end MSWriter::write() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
477
478  return True ;
479}
480 
481void MSWriter::init()
482{
483//   os_.origin( LogOrigin( "MSWriter", "init()", WHERE ) ) ;
484//   double startSec = gettimeofday_sec() ;
485//   os_ << "start MSWriter::init() startSec=" << startSec << LogIO::POST ;
486 
487  // access to scantable
488  header_ = table_->getHeader() ;
489
490  // FLOAT_DATA? or DATA?
491  if ( header_.npol > 2 ) {
492    useFloatData_ = False ;
493    useData_ = True ;
494  }
495  else {
496    useFloatData_ = True ;
497    useData_ = False ;
498  }
499
500  // polarization type
501  polType_ = header_.poltype ;
502  if ( polType_ == "" )
503    polType_ = "stokes" ;
504  else if ( polType_.find( "linear" ) != String::npos )
505    polType_ = "linear" ;
506  else if ( polType_.find( "circular" ) != String::npos )
507    polType_ = "circular" ;
508  else if ( polType_.find( "stokes" ) != String::npos )
509    polType_ = "stokes" ;
510  else if ( polType_.find( "linpol" ) != String::npos )
511    polType_ = "linpol" ;
512  else
513    polType_ = "notype" ;
514
515  // Check if some subtables are exists
516  if ( table_->tcal().table().nrow() != 0 ) {
517    ROTableColumn col( table_->tcal().table(), "TCAL" ) ;
518    if ( col.isDefined( 0 ) ) {
519      os_ << "TCAL table exists: nrow=" << table_->tcal().table().nrow() << LogIO::POST ;
520      isTcal_ = True ;
521    }
522    else {
523      os_ << "No TCAL rows" << LogIO::POST ;
524    }
525  }
526  else {
527    os_ << "No TCAL rows" << LogIO::POST ;
528  }
529  if ( table_->weather().table().nrow() != 0 ) {
530    ROTableColumn col( table_->weather().table(), "TEMPERATURE" ) ;
531    if ( col.isDefined( 0 ) ) {
532      os_ << "WEATHER table exists: nrow=" << table_->weather().table().nrow() << LogIO::POST ;
533      isWeather_ =True ;
534    }
535    else {
536      os_ << "No WEATHER rows" << LogIO::POST ;
537    }
538  }
539  else {
540    os_ << "No WEATHER rows" << LogIO::POST ;
541  }
542
543  // Are TCAL_SPECTRUM and TSYS_SPECTRUM necessary?
544  if ( isTcal_ && header_.nchan != 1 ) {
545    // examine TCAL subtable
546    Table tcaltab = table_->tcal().table() ;
547    ROArrayColumn<Float> tcalCol( tcaltab, "TCAL" ) ;
548    for ( uInt irow = 0 ; irow < tcaltab.nrow() ; irow++ ) {
549      if ( tcalCol( irow ).size() != 1 )
550        tcalSpec_ = True ;
551    }
552    // examine spectral data
553    TableIterator iter0( table_->table(), "IFNO" ) ;
554    while( !iter0.pastEnd() ) {
555      Table t0( iter0.table() ) ;
556      ROArrayColumn<Float> sharedFloatArrCol( t0, "SPECTRA" ) ;
557      uInt len = sharedFloatArrCol( 0 ).size() ;
558      if ( len != 1 ) {
559        sharedFloatArrCol.attach( t0, "TSYS" ) ;
560        if ( sharedFloatArrCol( 0 ).size() != 1 )
561          tsysSpec_ = True ;
562      }
563      iter0.next() ;
564    }
565  }
566
567  // check if reference for POINTING table exists
568  const TableRecord &rec = table_->table().keywordSet() ;
569  if ( rec.isDefined( "POINTING" ) ) {
570    ptTabName_ = rec.asString( "POINTING" ) ;
571    if ( !Table::isReadable( ptTabName_ ) ) {
572      ptTabName_ = "" ;
573    }
574  }
575
576//   double endSec = gettimeofday_sec() ;
577//   os_ << "end MSWriter::init() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
578}
579
580void MSWriter::setupMS()
581{
582//   os_.origin( LogOrigin( "MSWriter", "setupMS()", WHERE ) ) ;
583//   double startSec = gettimeofday_sec() ;
584//   os_ << "start MSWriter::setupMS() startSec=" << startSec << LogIO::POST ;
585 
586  String dunit = table_->getHeader().fluxunit ;
587
588  TableDesc msDesc = MeasurementSet::requiredTableDesc() ;
589  if ( useFloatData_ )
590    MeasurementSet::addColumnToDesc( msDesc, MSMainEnums::FLOAT_DATA, 2 ) ;
591  else if ( useData_ )
592    MeasurementSet::addColumnToDesc( msDesc, MSMainEnums::DATA, 2 ) ;
593
594  SetupNewTable newtab( filename_, msDesc, Table::New ) ;
595
596  mstable_ = new MeasurementSet( newtab ) ;
597
598  TableColumn col ;
599  if ( useFloatData_ )
600    col.attach( *mstable_, "FLOAT_DATA" ) ;
601  else if ( useData_ )
602    col.attach( *mstable_, "DATA" ) ;
603  col.rwKeywordSet().define( "UNIT", dunit ) ;
604
605  // create subtables
606  TableDesc antennaDesc = MSAntenna::requiredTableDesc() ;
607  SetupNewTable antennaTab( mstable_->antennaTableName(), antennaDesc, Table::New ) ;
608  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::ANTENNA ), Table( antennaTab ) ) ;
609
610  TableDesc dataDescDesc = MSDataDescription::requiredTableDesc() ;
611  SetupNewTable dataDescTab( mstable_->dataDescriptionTableName(), dataDescDesc, Table::New ) ;
612  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::DATA_DESCRIPTION ), Table( dataDescTab ) ) ;
613
614  TableDesc dopplerDesc = MSDoppler::requiredTableDesc() ;
615  SetupNewTable dopplerTab( mstable_->dopplerTableName(), dopplerDesc, Table::New ) ;
616  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::DOPPLER ), Table( dopplerTab ) ) ;
617
618  TableDesc feedDesc = MSFeed::requiredTableDesc() ;
619  SetupNewTable feedTab( mstable_->feedTableName(), feedDesc, Table::New ) ;
620  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FEED ), Table( feedTab ) ) ;
621
622  TableDesc fieldDesc = MSField::requiredTableDesc() ;
623  SetupNewTable fieldTab( mstable_->fieldTableName(), fieldDesc, Table::New ) ;
624  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FIELD ), Table( fieldTab ) ) ;
625
626  TableDesc flagCmdDesc = MSFlagCmd::requiredTableDesc() ;
627  SetupNewTable flagCmdTab( mstable_->flagCmdTableName(), flagCmdDesc, Table::New ) ;
628  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FLAG_CMD ), Table( flagCmdTab ) ) ;
629
630  TableDesc freqOffsetDesc = MSFreqOffset::requiredTableDesc() ;
631  SetupNewTable freqOffsetTab( mstable_->freqOffsetTableName(), freqOffsetDesc, Table::New ) ;
632  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FREQ_OFFSET ), Table( freqOffsetTab ) ) ;
633
634  TableDesc historyDesc = MSHistory::requiredTableDesc() ;
635  SetupNewTable historyTab( mstable_->historyTableName(), historyDesc, Table::New ) ;
636  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::HISTORY ), Table( historyTab ) ) ;
637
638  TableDesc observationDesc = MSObservation::requiredTableDesc() ;
639  SetupNewTable observationTab( mstable_->observationTableName(), observationDesc, Table::New ) ;
640  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::OBSERVATION ), Table( observationTab ) ) ;
641
642  TableDesc pointingDesc = MSPointing::requiredTableDesc() ;
643  SetupNewTable pointingTab( mstable_->pointingTableName(), pointingDesc, Table::New ) ;
644  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::POINTING ), Table( pointingTab ) ) ;
645
646  TableDesc polarizationDesc = MSPolarization::requiredTableDesc() ;
647  SetupNewTable polarizationTab( mstable_->polarizationTableName(), polarizationDesc, Table::New ) ;
648  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::POLARIZATION ), Table( polarizationTab ) ) ;
649
650  TableDesc processorDesc = MSProcessor::requiredTableDesc() ;
651  SetupNewTable processorTab( mstable_->processorTableName(), processorDesc, Table::New ) ;
652  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::PROCESSOR ), Table( processorTab ) ) ;
653
654  TableDesc sourceDesc = MSSource::requiredTableDesc() ;
655  MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::TRANSITION, 1 ) ;
656  MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::REST_FREQUENCY, 1 ) ;
657  MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::SYSVEL, 1 ) ;
658  SetupNewTable sourceTab( mstable_->sourceTableName(), sourceDesc, Table::New ) ;
659  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SOURCE ), Table( sourceTab ) ) ;
660
661  TableDesc spwDesc = MSSpectralWindow::requiredTableDesc() ;
662  SetupNewTable spwTab( mstable_->spectralWindowTableName(), spwDesc, Table::New ) ;
663  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SPECTRAL_WINDOW ), Table( spwTab ) ) ;
664
665  TableDesc stateDesc = MSState::requiredTableDesc() ;
666  SetupNewTable stateTab( mstable_->stateTableName(), stateDesc, Table::New ) ;
667  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::STATE ), Table( stateTab ) ) ;
668
669  // TODO: add TCAL_SPECTRUM and TSYS_SPECTRUM if necessary
670  TableDesc sysCalDesc = MSSysCal::requiredTableDesc() ;
671  MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TCAL, 2 ) ;
672  MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TSYS, 2 ) ;
673  if ( tcalSpec_ )
674    MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TCAL_SPECTRUM, 2 ) ;
675  if ( tsysSpec_ )
676    MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TSYS_SPECTRUM, 2 ) ;
677  SetupNewTable sysCalTab( mstable_->sysCalTableName(), sysCalDesc, Table::New ) ;
678  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SYSCAL ), Table( sysCalTab ) ) ;
679
680  TableDesc weatherDesc = MSWeather::requiredTableDesc() ;
681  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::TEMPERATURE ) ;
682  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::PRESSURE ) ;
683  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::REL_HUMIDITY ) ;
684  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::WIND_SPEED ) ;
685  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::WIND_DIRECTION ) ;
686  SetupNewTable weatherTab( mstable_->weatherTableName(), weatherDesc, Table::New ) ;
687  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::WEATHER ), Table( weatherTab ) ) ;
688
689  mstable_->initRefs() ;
690
691//   double endSec = gettimeofday_sec() ;
692//   os_ << "end MSWriter::setupMS() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
693}
694
695void MSWriter::fillObservation()
696{
697//   double startSec = gettimeofday_sec() ;
698//   os_ << "start MSWriter::fillObservation() startSec=" << startSec << LogIO::POST ;
699
700  // only 1 row
701  mstable_->observation().addRow( 1, True ) ;
702  MSObservationColumns msObsCols( mstable_->observation() ) ;
703  msObsCols.observer().put( 0, header_.observer ) ;
704  // tentatively put antennaname (from ANTENNA subtable)
705  String hAntennaName = header_.antennaname ;
706  String::size_type pos = hAntennaName.find( "//" ) ;
707  String telescopeName ;
708  if ( pos != String::npos ) {
709    telescopeName = hAntennaName.substr( 0, pos ) ;
710  }
711  else {
712    pos = hAntennaName.find( "@" ) ;
713    telescopeName = hAntennaName.substr( 0, pos ) ;
714  }
715//   os_ << "telescopeName = " << telescopeName << LogIO::POST ;
716  msObsCols.telescopeName().put( 0, telescopeName ) ;
717  msObsCols.project().put( 0, header_.project ) ;
718  //ScalarMeasColumn<MEpoch> timeCol( table_->table().sort("TIME"), "TIME" ) ;
719  Table sortedtable = table_->table().sort("TIME") ;
720  ScalarMeasColumn<MEpoch> timeCol( sortedtable, "TIME" ) ;
721  Vector<MEpoch> trange( 2 ) ;
722  trange[0] = timeCol( 0 ) ;
723  trange[1] = timeCol( table_->nrow()-1 ) ;
724  msObsCols.timeRangeMeas().put( 0, trange ) ;
725
726//   double endSec = gettimeofday_sec() ;
727//   os_ << "end MSWriter::fillObservation() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
728}
729
730void MSWriter::fillAntenna()
731{
732//   double startSec = gettimeofday_sec() ;
733//   os_ << "start MSWriter::fillAntenna() startSec=" << startSec << LogIO::POST ;
734
735  // only 1 row
736  mstable_->antenna().addRow( 1, True ) ;
737  MSAntennaColumns msAntCols( mstable_->antenna() ) ;
738
739  String hAntennaName = header_.antennaname ;
740  String::size_type pos = hAntennaName.find( "//" ) ;
741  String antennaName ;
742  String stationName ;
743  if ( pos != String::npos ) {
744    hAntennaName = hAntennaName.substr( pos+2 ) ;
745  }
746  pos = hAntennaName.find( "@" ) ;
747  if ( pos != String::npos ) {
748    antennaName = hAntennaName.substr( 0, pos ) ;
749    stationName = hAntennaName.substr( pos+1 ) ;
750  }
751  else {
752    antennaName = hAntennaName ;
753    stationName = hAntennaName ;
754  }
755//   os_ << "antennaName = " << antennaName << LogIO::POST ;
756//   os_ << "stationName = " << stationName << LogIO::POST ;
757 
758  msAntCols.name().put( 0, antennaName ) ;
759  msAntCols.station().put( 0, stationName ) ;
760
761//   os_ << "antennaPosition = " << header_.antennaposition << LogIO::POST ;
762 
763  msAntCols.position().put( 0, header_.antennaposition ) ;
764
765  // MOUNT is set to "ALT-AZ"
766  msAntCols.mount().put( 0, "ALT-AZ" ) ;
767
768  Double diameter = getDishDiameter( antennaName ) ;
769  msAntCols.dishDiameterQuant().put( 0, Quantity( diameter, "m" ) ) ;
770
771//   double endSec = gettimeofday_sec() ;
772//   os_ << "end MSWriter::fillAntenna() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
773}
774
775void MSWriter::fillProcessor()
776{
777//   double startSec = gettimeofday_sec() ;
778//   os_ << "start MSWriter::fillProcessor() startSec=" << startSec << LogIO::POST ;
779 
780  // only add empty 1 row
781  MSProcessor msProc = mstable_->processor() ;
782  msProc.addRow( 1, True ) ;
783
784//   double endSec = gettimeofday_sec() ;
785//   os_ << "end MSWriter::fillProcessor() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
786}
787
788void MSWriter::fillSource()
789{
790//   double startSec = gettimeofday_sec() ;
791//   os_ << "start MSWriter::fillSource() startSec=" << startSec << LogIO::POST ;
792 
793  // access to MS SOURCE subtable
794  MSSource msSrc = mstable_->source() ;
795
796  // access to MOLECULE subtable
797  STMolecules stm = table_->molecules() ;
798
799  Int srcId = 0 ;
800  Vector<Double> restFreq ;
801  Vector<String> molName ;
802  Vector<String> fMolName ;
803
804  // row based
805  TableRow row( msSrc ) ;
806  TableRecord &rec = row.record() ;
807  RecordFieldPtr<Int> srcidRF( rec, "SOURCE_ID" ) ;
808  RecordFieldPtr<String> nameRF( rec, "NAME" ) ;
809  RecordFieldPtr< Array<Double> > srcpmRF( rec, "PROPER_MOTION" ) ;
810  RecordFieldPtr< Array<Double> > srcdirRF( rec, "DIRECTION" ) ;
811  RecordFieldPtr<Int> numlineRF( rec, "NUM_LINES" ) ;
812  RecordFieldPtr< Array<Double> > restfreqRF( rec, "REST_FREQUENCY" ) ;
813  RecordFieldPtr< Array<Double> > sysvelRF( rec, "SYSVEL" ) ;
814  RecordFieldPtr< Array<String> > transitionRF( rec, "TRANSITION" ) ;
815  RecordFieldPtr<Double> timeRF( rec, "TIME" ) ;
816  RecordFieldPtr<Double> intervalRF( rec, "INTERVAL" ) ;
817  RecordFieldPtr<Int> spwidRF( rec, "SPECTRAL_WINDOW_ID" ) ;
818
819  //
820  // ITERATION: SRCNAME
821  //
822  TableIterator iter0( table_->table(), "SRCNAME" ) ;
823  while( !iter0.pastEnd() ) {
824    //Table t0( iter0.table() ) ;
825    Table t0 =  iter0.table()  ;
826
827    // get necessary information
828    ROScalarColumn<String> srcNameCol( t0, "SRCNAME" ) ;
829    String srcName = srcNameCol( 0 ) ;
830    ROArrayColumn<Double> sharedDArrRCol( t0, "SRCPROPERMOTION" ) ;
831    Vector<Double> srcPM = sharedDArrRCol( 0 ) ;
832    sharedDArrRCol.attach( t0, "SRCDIRECTION" ) ;
833    Vector<Double> srcDir = sharedDArrRCol( 0 ) ;
834    ROScalarColumn<Double> srcVelCol( t0, "SRCVELOCITY" ) ;
835    Double srcVel = srcVelCol( 0 ) ;
836
837    // NAME
838    *nameRF = srcName ;
839
840    // SOURCE_ID
841    *srcidRF = srcId ;
842
843    // PROPER_MOTION
844    *srcpmRF = srcPM ;
845   
846    // DIRECTION
847    *srcdirRF = srcDir ;
848
849    //
850    // ITERATION: MOLECULE_ID
851    //
852    TableIterator iter1( t0, "MOLECULE_ID" ) ;
853    while( !iter1.pastEnd() ) {
854      //Table t1( iter1.table() ) ;
855      Table t1 = iter1.table() ;
856
857      // get necessary information
858      ROScalarColumn<uInt> molIdCol( t1, "MOLECULE_ID" ) ;
859      uInt molId = molIdCol( 0 ) ;
860      stm.getEntry( restFreq, molName, fMolName, molId ) ;
861
862      uInt numFreq = restFreq.size() ;
863     
864      // NUM_LINES
865      *numlineRF = numFreq ;
866
867      // REST_FREQUENCY
868      *restfreqRF = restFreq ;
869
870      // TRANSITION
871      //*transitionRF = fMolName ;
872      Vector<String> transition ;
873      if ( fMolName.size() != 0 ) {
874        transition = fMolName ;
875      }
876      else if ( molName.size() != 0 ) {
877        transition = molName ;
878      }
879      else {
880        transition.resize( numFreq ) ;
881        transition = "" ;
882      }
883      *transitionRF = transition ;
884
885      // SYSVEL
886      Vector<Double> sysvelArr( numFreq, srcVel ) ;
887      *sysvelRF = sysvelArr ;
888
889      //
890      // ITERATION: IFNO
891      //
892      TableIterator iter2( t1, "IFNO" ) ;
893      while( !iter2.pastEnd() ) {
894        //Table t2( iter2.table() ) ;
895        Table t2 = iter2.table() ;
896        uInt nrow = msSrc.nrow() ;
897
898        // get necessary information
899        ROScalarColumn<uInt> ifNoCol( t2, "IFNO" ) ;
900        uInt ifno = ifNoCol( 0 ) ; // IFNO = SPECTRAL_WINDOW_ID
901        Double midTime ;
902        Double interval ;
903        getValidTimeRange( midTime, interval, t2 ) ;
904
905        // fill SPECTRAL_WINDOW_ID
906        *spwidRF = ifno ;
907
908        // fill TIME, INTERVAL
909        *timeRF = midTime ;
910        *intervalRF = interval ;
911
912        // add row
913        msSrc.addRow( 1, True ) ;
914        row.put( nrow ) ;
915
916        iter2.next() ;
917      }
918
919      iter1.next() ;
920    }
921
922    // increment srcId if SRCNAME changed
923    srcId++ ;
924
925    iter0.next() ;
926  }
927
928//   double endSec = gettimeofday_sec() ;
929//   os_ << "end MSWriter::fillSource() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
930}
931
932void MSWriter::fillWeather()
933{
934//   double startSec = gettimeofday_sec() ;
935//   os_ << "start MSWriter::fillWeather() startSec=" << startSec << LogIO::POST ;
936
937  // access to MS WEATHER subtable
938  MSWeather msw = mstable_->weather() ;
939
940  // access to WEATHER subtable
941  Table stw = table_->weather().table() ;
942  uInt nrow = stw.nrow() ;
943
944  if ( nrow == 0 )
945    return ;
946
947  msw.addRow( nrow, True ) ;
948  MSWeatherColumns mswCols( msw ) ;
949
950  // ANTENNA_ID is always 0
951  Vector<Int> antIdArr( nrow, 0 ) ;
952  mswCols.antennaId().putColumn( antIdArr ) ;
953
954  // fill weather status
955  ROScalarColumn<Float> sharedFloatCol( stw, "TEMPERATURE" ) ;
956  mswCols.temperature().putColumn( sharedFloatCol ) ;
957  sharedFloatCol.attach( stw, "PRESSURE" ) ;
958  mswCols.pressure().putColumn( sharedFloatCol ) ;
959  sharedFloatCol.attach( stw, "HUMIDITY" ) ;
960  mswCols.relHumidity().putColumn( sharedFloatCol ) ;
961  sharedFloatCol.attach( stw, "WINDSPEED" ) ;
962  mswCols.windSpeed().putColumn( sharedFloatCol ) ;
963  sharedFloatCol.attach( stw, "WINDAZ" ) ;
964  mswCols.windDirection().putColumn( sharedFloatCol ) ;
965
966  // fill TIME and INTERVAL
967  Double midTime ;
968  Double interval ;
969  Vector<Double> intervalArr( nrow, 0.0 ) ;
970  TableIterator iter( table_->table(), "WEATHER_ID" ) ;
971  while( !iter.pastEnd() ) {
972    //Table tab( iter.table() ) ;
973    Table tab = iter.table() ;
974
975    ROScalarColumn<uInt> widCol( tab, "WEATHER_ID" ) ;
976    uInt wid = widCol( 0 ) ;
977
978    getValidTimeRange( midTime, interval, tab ) ;
979    mswCols.time().put( wid, midTime ) ;
980    intervalArr[wid] = interval ;
981
982    iter.next() ;
983  }
984  mswCols.interval().putColumn( intervalArr ) ;
985
986//   double endSec = gettimeofday_sec() ;
987//   os_ << "end MSWriter::fillWeather() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
988}
989
990void MSWriter::fillSysCal()
991{
992//   double startSec = gettimeofday_sec() ;
993//   os_ << "start MSWriter::fillSysCal() startSec=" << startSec << LogIO::POST ;
994
995  //tcalIdRec_.print( cout ) ;
996
997  // access to MS SYSCAL subtable
998  MSSysCal mssc = mstable_->sysCal() ;
999
1000  // access to TCAL subtable
1001  Table stt = table_->tcal().table() ;
1002  uInt nrow = stt.nrow() ;
1003
1004  // access to MAIN table
1005  Block<String> cols( 6 ) ;
1006  cols[0] = "TIME" ;
1007  cols[1] = "TCAL_ID" ;
1008  cols[2] = "TSYS" ;
1009  cols[3] = "BEAMNO" ;
1010  cols[4] = "IFNO" ;
1011  cols[5] = "INTERVAL" ;
1012  Table tab = table_->table().project( cols ) ;
1013
1014  if ( nrow == 0 )
1015    return ;
1016
1017  nrow = tcalIdRec_.nfields() ;
1018
1019  Double midTime ;
1020  Double interval ;
1021  String timeStr ;
1022
1023  // row base
1024  TableRow row( mssc ) ;
1025  TableRecord &trec = row.record() ;
1026  RecordFieldPtr<Int> antennaRF( trec, "ANTENNA_ID" ) ;
1027  RecordFieldPtr<Int> feedRF( trec, "FEED_ID" ) ;
1028  RecordFieldPtr<Int> spwRF( trec, "SPECTRAL_WINDOW_ID" ) ;
1029  RecordFieldPtr<Double> timeRF( trec, "TIME" ) ;
1030  RecordFieldPtr<Double> intervalRF( trec, "INTERVAL" ) ;
1031  RecordFieldPtr< Array<Float> > tsysRF( trec, "TSYS" ) ;
1032  RecordFieldPtr< Array<Float> > tcalRF( trec, "TCAL" ) ;
1033  RecordFieldPtr< Array<Float> > tsysspRF ;
1034  RecordFieldPtr< Array<Float> > tcalspRF ;
1035  if ( tsysSpec_ )
1036    tsysspRF.attachToRecord( trec, "TSYS_SPECTRUM" ) ;
1037  if ( tcalSpec_ )
1038    tcalspRF.attachToRecord( trec, "TCAL_SPECTRUM" ) ;
1039
1040  // ANTENNA_ID is always 0
1041  *antennaRF = 0 ;
1042
1043  Table sortedstt = stt.sort( "ID" ) ;
1044  ROArrayColumn<Float> tcalCol( sortedstt, "TCAL" ) ;
1045  ROTableColumn idCol( sortedstt, "ID" ) ;
1046  ROArrayColumn<Float> tsysCol( tab, "TSYS" ) ;
1047  ROTableColumn tcalidCol( tab, "TCAL_ID" ) ;
1048  ROTableColumn timeCol( tab, "TIME" ) ;
1049  ROTableColumn intervalCol( tab, "INTERVAL" ) ;
1050  ROTableColumn beamnoCol( tab, "BEAMNO" ) ;
1051  ROTableColumn ifnoCol( tab, "IFNO" ) ;
1052  for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
1053//     double t1 = gettimeofday_sec() ;
1054    Vector<uInt> ids = tcalIdRec_.asArrayuInt( irow ) ;
1055//     os_ << "ids = " << ids << LogIO::POST ;
1056    uInt npol = ids.size() ;
1057    Vector<uInt> rows = tcalRowRec_.asArrayuInt( irow ) ;
1058//     os_ << "rows = " << rows << LogIO::POST ;
1059    Vector<Double> atime( rows.nelements() ) ;
1060    Vector<Double> ainterval( rows.nelements() ) ;
1061    Vector<uInt> atcalid( rows.nelements() ) ;
1062    for( uInt jrow = 0 ; jrow < rows.nelements() ; jrow++ ) {
1063      atime[jrow] = (Double)timeCol.asdouble( rows[jrow] ) ;
1064      ainterval[jrow] = (Double)intervalCol.asdouble( rows[jrow] ) ;
1065      atcalid[jrow] = tcalidCol.asuInt( rows[jrow] ) ;
1066    }
1067    Vector<Float> dummy = tsysCol( rows[0] ) ;
1068    Matrix<Float> tsys( npol,dummy.nelements() ) ;
1069    tsys.row( 0 ) = dummy ;
1070    for ( uInt jrow = 1 ; jrow < npol ; jrow++ )
1071      tsys.row( jrow ) = tsysCol( rows[jrow] ) ;
1072
1073    // FEED_ID
1074    *feedRF = beamnoCol.asuInt( rows[0] ) ;
1075
1076    // SPECTRAL_WINDOW_ID
1077    *spwRF = ifnoCol.asuInt( rows[0] ) ;
1078
1079    // TIME and INTERVAL
1080    getValidTimeRange( midTime, interval, atime, ainterval ) ;
1081    *timeRF = midTime ;
1082    *intervalRF = interval ;
1083
1084    // TCAL and TSYS
1085    Matrix<Float> tcal ;
1086    Table t ;
1087    if ( idCol.asuInt( ids[0] ) == ids[0] ) {
1088//       os_ << "sorted at irow=" << irow << " ids[0]=" << ids[0] << LogIO::POST ;
1089      Vector<Float> dummyC = tcalCol( ids[0] ) ;
1090      tcal.resize( npol, dummyC.size() ) ;
1091      tcal.row( 0 ) = dummyC ;
1092    }
1093    else {
1094//       os_ << "NOT sorted at irow=" << irow << " ids[0]=" << ids[0] << LogIO::POST ;
1095      t = stt( stt.col("ID") == ids[0] ) ;
1096      Vector<Float> dummyC = tcalCol( 0 ) ;
1097      tcal.resize( npol, dummyC.size() ) ;
1098      tcal.row( 0 ) = dummyC ;
1099    }
1100    if ( npol == 2 ) {
1101      if ( idCol.asuInt( ids[1] ) == ids[1] ) {
1102//         os_ << "sorted at irow=" << irow << " ids[1]=" << ids[1] << LogIO::POST ;
1103        tcal.row( 1 ) = tcalCol( ids[1] ) ;
1104      }
1105      else {
1106//         os_ << "NOT sorted at irow=" << irow << " ids[1]=" << ids[1] << LogIO::POST ;
1107        t = stt( stt.col("ID") == ids[1] ) ;
1108        tcalCol.attach( t, "TCAL" ) ;
1109        tcal.row( 1 ) = tcalCol( 1 ) ;
1110      }
1111    }
1112    else if ( npol == 3 ) {
1113      if ( idCol.asuInt( ids[2] ) == ids[2] )
1114        tcal.row( 1 ) = tcalCol( ids[2] ) ;
1115      else {
1116        t = stt( stt.col("ID") == ids[2] ) ;
1117        tcalCol.attach( t, "TCAL" ) ;
1118        tcal.row( 1 ) = tcalCol( 0 ) ;
1119      }
1120      if ( idCol.asuInt( ids[1] ) == ids[1] )
1121        tcal.row( 2 ) = tcalCol( ids[1] ) ;
1122      else {
1123        t = stt( stt.col("ID") == ids[1] ) ;
1124        tcalCol.attach( t, "TCAL" ) ;
1125        tcal.row( 2 ) = tcalCol( 0 ) ;
1126      }
1127    }
1128    else if ( npol == 4 ) {
1129      if ( idCol.asuInt( ids[2] ) == ids[2] )
1130        tcal.row( 1 ) = tcalCol( ids[2] ) ;
1131      else {
1132        t = stt( stt.col("ID") == ids[2] ) ;
1133        tcalCol.attach( t, "TCAL" ) ;
1134        tcal.row( 1 ) = tcalCol( 0 ) ;
1135      }
1136      if ( idCol.asuInt( ids[3] ) == ids[3] )
1137        tcal.row( 2 ) = tcalCol( ids[3] ) ;
1138      else {
1139        t = stt( stt.col("ID") == ids[3] ) ;
1140        tcalCol.attach( t, "TCAL" ) ;
1141        tcal.row( 2 ) = tcalCol( 0 ) ;
1142      }
1143      if ( idCol.asuInt( ids[1] ) == ids[1] )
1144        tcal.row( 2 ) = tcalCol( ids[1] ) ;
1145      else {
1146        t = stt( stt.col("ID") == ids[1] ) ;
1147        tcalCol.attach( t, "TCAL" ) ;
1148        tcal.row( 3 ) = tcalCol( 0 ) ;
1149      }
1150    }
1151    if ( tcalSpec_ ) {
1152      // put TCAL_SPECTRUM
1153      //*tcalspRF = tcal ;
1154      tcalspRF.define( tcal ) ;
1155      // set TCAL (mean of TCAL_SPECTRUM)
1156      Matrix<Float> tcalMean( npol, 1 ) ;
1157      for ( uInt iid = 0 ; iid < npol ; iid++ ) {
1158        tcalMean( iid, 0 ) = mean( tcal.row(iid) ) ;
1159      }
1160      // put TCAL
1161      *tcalRF = tcalMean ;
1162    }
1163    else {
1164      // put TCAL
1165      *tcalRF = tcal ;
1166    }
1167   
1168    if ( tsysSpec_ ) {
1169      // put TSYS_SPECTRUM
1170      //*tsysspRF = tsys ;
1171      tsysspRF.define( tsys ) ;
1172      // set TSYS (mean of TSYS_SPECTRUM)
1173      Matrix<Float> tsysMean( npol, 1 ) ;
1174      for ( uInt iid = 0 ; iid < npol ; iid++ ) {
1175        tsysMean( iid, 0 ) = mean( tsys.row(iid) ) ;
1176      }
1177      // put TSYS
1178      *tsysRF = tsysMean ;
1179    }
1180    else {
1181      // put TSYS
1182      *tsysRF = tsys ;
1183    }
1184
1185    // add row
1186    mssc.addRow( 1, True ) ;
1187    row.put( mssc.nrow()-1 ) ;
1188
1189//     double t2 = gettimeofday_sec() ;
1190//     os_ << irow << "th loop elapsed time = " << t2-t1 << "sec" << LogIO::POST ;
1191  }
1192 
1193//   double endSec = gettimeofday_sec() ;
1194//   os_ << "end MSWriter::fillSysCal() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1195}
1196
1197void MSWriter::addFeed( Int id )
1198{
1199//   double startSec = gettimeofday_sec() ;
1200//   os_ << "start MSWriter::addFeed() startSec=" << startSec << LogIO::POST ;
1201
1202  // add row
1203  MSFeed msFeed = mstable_->feed() ;
1204  msFeed.addRow( 1, True ) ;
1205  Int nrow = msFeed.nrow() ;
1206  Int numReceptors = 2 ;
1207  Vector<String> polType( numReceptors ) ;
1208  Matrix<Double> beamOffset( 2, numReceptors ) ;
1209  beamOffset = 0.0 ;
1210  Vector<Double> receptorAngle( numReceptors, 0.0 ) ;
1211  if ( polType_ == "linear" ) {
1212    polType[0] = "X" ;
1213    polType[1] = "Y" ;
1214  }
1215  else if ( polType_ == "circular" ) {
1216    polType[0] = "R" ;
1217    polType[1] = "L" ;
1218  }
1219  else {
1220    polType[0] = "X" ;
1221    polType[1] = "Y" ;
1222  }
1223  Matrix<Complex> polResponse( numReceptors, numReceptors, 0.0 ) ;
1224  for ( Int i = 0 ; i < numReceptors ; i++ )
1225    polResponse( i, i ) = 0.0 ;
1226
1227  MSFeedColumns msFeedCols( mstable_->feed() ) ;
1228
1229  msFeedCols.feedId().put( nrow-1, id ) ;
1230  msFeedCols.antennaId().put( nrow-1, 0 ) ;
1231  msFeedCols.numReceptors().put( nrow-1, numReceptors ) ;
1232  msFeedCols.polarizationType().put( nrow-1, polType ) ;
1233  msFeedCols.beamOffset().put( nrow-1, beamOffset ) ;
1234  msFeedCols.receptorAngle().put( nrow-1, receptorAngle ) ;
1235  msFeedCols.polResponse().put( nrow-1, polResponse ) ;
1236
1237//   double endSec = gettimeofday_sec() ;
1238//   os_ << "end MSWriter::addFeed() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1239}
1240
1241void MSWriter::addSpectralWindow( Int spwid, Int freqid )
1242{
1243//   double startSec = gettimeofday_sec() ;
1244//   os_ << "start MSWriter::addSpectralWindow() startSec=" << startSec << LogIO::POST ;
1245 
1246  // add row
1247  MSSpectralWindow msSpw = mstable_->spectralWindow() ;
1248  while( (Int)msSpw.nrow() <= spwid ) {
1249    msSpw.addRow( 1, True ) ;
1250  }
1251 
1252  MSSpWindowColumns msSpwCols( msSpw ) ;
1253
1254  STFrequencies stf = table_->frequencies() ;
1255
1256  // MEAS_FREQ_REF
1257  msSpwCols.measFreqRef().put( spwid, stf.getFrame( True ) ) ;
1258
1259  Double refpix ;
1260  Double refval ;
1261  Double inc ;
1262  stf.getEntry( refpix, refval, inc, (uInt)freqid ) ;
1263
1264  // NUM_CHAN
1265  Int nchan = (Int)(refpix * 2) + 1 ;
1266  if ( nchan == 0 )
1267    nchan = 1 ;
1268  msSpwCols.numChan().put( spwid, nchan ) ;
1269
1270  // TOTAL_BANDWIDTH
1271  Double bw = nchan * inc ;
1272  msSpwCols.totalBandwidth().put( spwid, bw ) ;
1273
1274  // REF_FREQUENCY
1275  Double refFreq = refval - refpix * inc ;
1276  msSpwCols.refFrequency().put( spwid, refFreq ) ;
1277
1278  // NET_SIDEBAND
1279  // tentative: USB->0, LSB->1
1280  Int netSideband = 0 ;
1281  if ( inc < 0 )
1282    netSideband = 1 ;
1283  msSpwCols.netSideband().put( spwid, netSideband ) ;
1284
1285  // RESOLUTION, CHAN_WIDTH, EFFECTIVE_BW
1286  Vector<Double> sharedDoubleArr( nchan, abs(inc) ) ;
1287  msSpwCols.resolution().put( spwid, sharedDoubleArr ) ;
1288  msSpwCols.chanWidth().put( spwid, sharedDoubleArr ) ;
1289  msSpwCols.effectiveBW().put( spwid, sharedDoubleArr ) ;
1290
1291  // CHAN_FREQ
1292  indgen( sharedDoubleArr, refFreq, inc ) ;
1293  msSpwCols.chanFreq().put( spwid, sharedDoubleArr ) ;
1294
1295//   double endSec = gettimeofday_sec() ;
1296//   os_ << "end MSWriter::addSpectralWindow() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1297}
1298
1299void MSWriter::addField( Int fid, String fieldname, String srcname, Double t, Vector<Double> rate )
1300{
1301//   double startSec = gettimeofday_sec() ;
1302//   os_ << "start MSWriter::addField() startSec=" << startSec << LogIO::POST ;
1303 
1304  MSField msField = mstable_->field() ;
1305  while( (Int)msField.nrow() <= fid ) {
1306    msField.addRow( 1, True ) ;
1307  }
1308  MSFieldColumns msFieldCols( msField ) ;
1309
1310  // Access to SOURCE table
1311  MSSource msSrc = mstable_->source() ;
1312
1313  // fill target row
1314  msFieldCols.name().put( fid, fieldname ) ;
1315  msFieldCols.time().put( fid, t ) ;
1316  Int numPoly = 0 ;
1317  if ( anyNE( rate, 0.0 ) )
1318    numPoly = 1 ;
1319  msFieldCols.numPoly().put( fid, numPoly ) ;
1320  MSSourceIndex msSrcIdx( msSrc ) ;
1321  Int srcId = -1 ;
1322  Vector<Int> srcIdArr = msSrcIdx.matchSourceName( srcname ) ;
1323  if ( srcIdArr.size() != 0 ) {
1324    srcId = srcIdArr[0] ;
1325    MSSource msSrcSel = msSrc( msSrc.col("SOURCE_ID") == srcId ) ;
1326    ROMSSourceColumns msSrcCols( msSrcSel ) ;
1327    Vector<Double> srcDir = msSrcCols.direction()( 0 ) ;
1328    Matrix<Double> srcDirA( IPosition( 2, 2, 1+numPoly ) ) ;
1329//     os_ << "srcDirA = " << srcDirA << LogIO::POST ;
1330//     os_ << "sliced srcDirA = " << srcDirA.column( 0 ) << LogIO::POST ;
1331    srcDirA.column( 0 ) = srcDir ;
1332//     os_ << "srcDirA = " << srcDirA << LogIO::POST ;
1333    if ( numPoly != 0 )
1334      srcDirA.column( 1 ) = rate ;
1335    msFieldCols.phaseDir().put( fid, srcDirA ) ;
1336    msFieldCols.referenceDir().put( fid, srcDirA ) ;
1337    msFieldCols.delayDir().put( fid, srcDirA ) ;
1338  }
1339  msFieldCols.sourceId().put( fid, srcId ) ;
1340
1341//   double endSec = gettimeofday_sec() ;
1342//   os_ << "end MSWriter::addField() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1343}
1344
1345void MSWriter::addPointing( String &name, Double &me, Double &interval, Matrix<Double> &dir )
1346{
1347//   double startSec = gettimeofday_sec() ;
1348//   os_ << "start MSWriter::addPointing() startSec=" << startSec << LogIO::POST ;
1349 
1350  // access to POINTING subtable
1351  MSPointing msp = mstable_->pointing() ;
1352  uInt nrow = msp.nrow() ;
1353
1354  // add row
1355  msp.addRow( 1, True ) ;
1356
1357  // fill row
1358  TableRow row( msp ) ;
1359  TableRecord &rec = row.record() ;
1360  RecordFieldPtr<Int> antennaRF( rec, "ANTENNA_ID" ) ;
1361  *antennaRF = 0 ;
1362  RecordFieldPtr<Int> numpolyRF( rec, "NUM_POLY" ) ;
1363  *numpolyRF = dir.ncolumn() ;
1364  RecordFieldPtr<Double> timeRF( rec, "TIME" ) ;
1365  *timeRF = me ;
1366  RecordFieldPtr<Double> toriginRF( rec, "TIME_ORIGIN" ) ;
1367  *toriginRF = me ;
1368  RecordFieldPtr<Double> intervalRF( rec, "INTERVAL" ) ;
1369  *intervalRF = interval ;
1370  RecordFieldPtr<String> nameRF( rec, "NAME" ) ;
1371  *nameRF = name ;
1372  RecordFieldPtr<Bool> trackRF( rec, "TRACKING" ) ;
1373  *trackRF = True ;
1374  RecordFieldPtr< Array<Double> > dirRF( rec, "DIRECTION" ) ;
1375  *dirRF = dir ;
1376  RecordFieldPtr< Array<Double> > targetRF( rec, "TARGET" ) ;
1377  *dirRF = dir ;
1378  row.put( nrow ) ;
1379
1380//   double endSec = gettimeofday_sec() ;
1381//   os_ << "end MSWriter::addPointing() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1382}
1383
1384Int MSWriter::addPolarization( Vector<Int> polnos )
1385{
1386//   double startSec = gettimeofday_sec() ;
1387//   os_ << "start MSWriter::addPolarization() startSec=" << startSec << LogIO::POST ;
1388
1389//   os_ << "polnos = " << polnos << LogIO::POST ;
1390  MSPolarization msPol = mstable_->polarization() ;
1391  uInt nrow = msPol.nrow() ;
1392
1393//   // only 1 POLARIZATION row for 1 scantable
1394//   if ( nrow > 0 )
1395//     return 0 ;
1396 
1397  Vector<Int> corrType = toCorrType( polnos ) ;
1398 
1399  ROArrayColumn<Int> corrtCol( msPol, "CORR_TYPE" ) ;
1400  //Matrix<Int> corrTypeArr = corrtCol.getColumn() ;
1401  Int polid = -1 ;
1402  for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
1403    Vector<Int> corrTypeArr = corrtCol( irow ) ;
1404    if ( corrType.nelements() == corrTypeArr.nelements()
1405         && allEQ( corrType, corrTypeArr ) ) {
1406      polid = irow ;
1407      break ;
1408    }
1409  }
1410
1411  if ( polid == -1 ) {
1412    MSPolarizationColumns msPolCols( msPol ) ;
1413
1414    // add row
1415    msPol.addRow( 1, True ) ;
1416    polid = (Int)nrow ;
1417
1418    // CORR_TYPE
1419    msPolCols.corrType().put( nrow, corrType ) ;
1420
1421    // NUM_CORR
1422    uInt npol = corrType.size() ;
1423    msPolCols.numCorr().put( nrow, npol ) ;
1424
1425    // CORR_PRODUCT
1426    Matrix<Int> corrProd( 2, npol, -1 ) ;
1427    if ( npol == 1 ) {
1428      corrProd = 0 ;
1429    }
1430    else if ( npol == 2 ) {
1431      corrProd.column( 0 ) = 0 ;
1432      corrProd.column( 1 ) = 1 ;
1433    }
1434    else {
1435      corrProd.column( 0 ) = 0 ;
1436      corrProd.column( 3 ) = 1 ;
1437      corrProd( 0,1 ) = 0 ;
1438      corrProd( 1,1 ) = 1 ;
1439      corrProd( 0,2 ) = 1 ;
1440      corrProd( 1,2 ) = 0 ;
1441    }
1442    msPolCols.corrProduct().put( nrow, corrProd ) ;   
1443  }
1444
1445//   double endSec = gettimeofday_sec() ;
1446//   os_ << "end MSWriter::addPolarization() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1447
1448  return polid ;
1449}
1450
1451Int MSWriter::addDataDescription( Int polid, Int spwid )
1452{
1453//   double startSec = gettimeofday_sec() ;
1454//   os_ << "start MSWriter::addDataDescription() startSec=" << startSec << LogIO::POST ;
1455
1456  MSDataDescription msDataDesc = mstable_->dataDescription() ;
1457  uInt nrow = msDataDesc.nrow() ;
1458
1459  // only 1 POLARIZATION_ID for 1 scantable
1460  Int ddid = -1 ;
1461  ROScalarColumn<Int> spwCol( msDataDesc, "SPECTRAL_WINDOW_ID" ) ;
1462  Vector<Int> spwIds = spwCol.getColumn() ;
1463  //ROScalarColumn<Int> polCol( msDataDesc, "POLARIZATION_ID" ) ;
1464  //Vector<Int> polIds = polCol.getColumn() ;
1465  for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
1466    //if ( spwid == spwIds[irow] && polid == polIds[irow] ) {
1467    if ( spwid == spwIds[irow] ) {
1468      ddid = irow ;
1469      break ;
1470    }
1471  }
1472//   os_ << "ddid = " << ddid << LogIO::POST ;
1473 
1474
1475  if ( ddid == -1 ) {
1476    msDataDesc.addRow( 1, True ) ;
1477    MSDataDescColumns msDataDescCols( msDataDesc ) ;
1478    msDataDescCols.polarizationId().put( nrow, polid ) ;
1479    msDataDescCols.spectralWindowId().put( nrow, spwid ) ;
1480    ddid = (Int)nrow ;
1481  }
1482
1483//   double endSec = gettimeofday_sec() ;
1484//   os_ << "end MSWriter::addDataDescription() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1485
1486  return ddid ;
1487}
1488
1489Int MSWriter::addState( Int st, Int &subscan )
1490{
1491//   double startSec = gettimeofday_sec() ;
1492//   os_ << "start MSWriter::addState() startSec=" << startSec << LogIO::POST ;
1493
1494  // access to STATE subtable
1495  MSState msState = mstable_->state() ;
1496  uInt nrow = msState.nrow() ;
1497
1498  String obsMode ;
1499  Bool isSignal ;
1500  Double tnoise ;
1501  Double tload ;
1502  queryType( st, obsMode, isSignal, tnoise, tload ) ;
1503//   os_ << "obsMode = " << obsMode << " isSignal = " << isSignal << LogIO::POST ;
1504
1505  Int idx = -1 ;
1506  ROScalarColumn<String> obsModeCol( msState, "OBS_MODE" ) ;
1507  ROScalarColumn<Int> subscanCol( msState, "SUB_SCAN" ) ;
1508  for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
1509    if ( obsModeCol(irow) == obsMode
1510         //&& sigCol(irow) == isSignal
1511         //&& refCol(irow) != isSignal
1512         && subscanCol(irow) == subscan ) {
1513      idx = irow ;
1514      break ;
1515    }
1516  }
1517  if ( idx == -1 ) {
1518    msState.addRow( 1, True ) ;
1519    TableRow row( msState ) ;
1520    TableRecord &rec = row.record() ;
1521    RecordFieldPtr<String> obsmodeRF( rec, "OBS_MODE" ) ;
1522    *obsmodeRF = obsMode ;
1523    RecordFieldPtr<Bool> sigRF( rec, "SIG" ) ;
1524    *sigRF = isSignal ;
1525    RecordFieldPtr<Bool> refRF( rec, "REF" ) ;
1526    *refRF = !isSignal ;
1527    RecordFieldPtr<Int> subscanRF( rec, "SUB_SCAN" ) ;
1528    *subscanRF = subscan ;
1529    RecordFieldPtr<Double> noiseRF( rec, "CAL" ) ;
1530    *noiseRF = tnoise ;
1531    RecordFieldPtr<Double> loadRF( rec, "LOAD" ) ;
1532    *loadRF = tload ;
1533    row.put( nrow ) ;
1534    idx = nrow ;
1535  }
1536  subscan++ ;
1537
1538//   double endSec = gettimeofday_sec() ;
1539//   os_ << "end MSWriter::addState() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1540
1541  return idx ;
1542}
1543
1544Vector<Int> MSWriter::toCorrType( Vector<Int> polnos )
1545{
1546//   double startSec = gettimeofday_sec() ;
1547//   os_ << "start MSWriter::toCorrType() startSec=" << startSec << LogIO::POST ;
1548
1549  uInt npol = polnos.size() ;
1550  Vector<Int> corrType( npol, Stokes::Undefined ) ;
1551 
1552  if ( npol == 4 ) {
1553    if ( polType_ == "linear" ) {
1554      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1555        if ( polnos[ipol] == 0 )
1556          corrType[ipol] = Stokes::XX ;
1557        else if ( polnos[ipol] == 1 )
1558          corrType[ipol] = Stokes::XY ;
1559        else if ( polnos[ipol] == 2 )
1560          corrType[ipol] = Stokes::YX ;
1561        else if ( polnos[ipol] == 3 )
1562          corrType[ipol] = Stokes::YY ;
1563      }
1564    }
1565    else if ( polType_ == "circular" ) {
1566      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1567        if ( polnos[ipol] == 0 )
1568          corrType[ipol] = Stokes::RR ;
1569        else if ( polnos[ipol] == 1 )
1570          corrType[ipol] = Stokes::RL ;
1571        else if ( polnos[ipol] == 2 )
1572          corrType[ipol] = Stokes::LR ;
1573        else if ( polnos[ipol] == 3 )
1574          corrType[ipol] = Stokes::LL ;
1575      }
1576    }
1577    else if ( polType_ == "stokes" ) {
1578      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1579        if ( polnos[ipol] == 0 )
1580          corrType[ipol] = Stokes::I ;
1581        else if ( polnos[ipol] == 1 )
1582          corrType[ipol] = Stokes::Q ;
1583        else if ( polnos[ipol] == 2 )
1584          corrType[ipol] = Stokes::U ;
1585        else if ( polnos[ipol] == 3 )
1586          corrType[ipol] = Stokes::V ;
1587      }
1588    }
1589  }
1590  else if ( npol == 2 ) {
1591    if ( polType_ == "linear" ) {
1592      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1593        if ( polnos[ipol] == 0 )
1594          corrType[ipol] = Stokes::XX ;
1595        else if ( polnos[ipol] == 1 )
1596          corrType[ipol] = Stokes::YY ;
1597      }
1598    }
1599    else if ( polType_ == "circular" ) {
1600      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1601        if ( polnos[ipol] == 0 )
1602          corrType[ipol] = Stokes::RR ;
1603        else if ( polnos[ipol] == 1 )
1604          corrType[ipol] = Stokes::LL ;
1605      }
1606    }
1607    else if ( polType_ == "stokes" ) {
1608      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1609        if ( polnos[ipol] == 0 )
1610          corrType[ipol] = Stokes::I ;
1611        else if ( polnos[ipol] == 1 )
1612          corrType[ipol] = Stokes::V ;
1613      }
1614    }
1615    else if ( polType_ == "linpol" ) {
1616      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1617        if ( polnos[ipol] == 1 )
1618          corrType[ipol] = Stokes::Plinear ;
1619        else if ( polnos[ipol] == 2 )
1620          corrType[ipol] = Stokes::Pangle ;
1621      }
1622    }
1623  }     
1624  else if ( npol == 1 ) {
1625    if ( polType_ == "linear" )
1626      corrType[0] = Stokes::XX ;
1627    else if ( polType_ == "circular" )
1628      corrType[0] = Stokes::RR ;
1629    else if ( polType_ == "stokes" )
1630      corrType[0] = Stokes::I ;
1631  }
1632
1633//   double endSec = gettimeofday_sec() ;
1634//   os_ << "end MSWriter::toCorrType() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1635
1636  return corrType ;
1637}
1638
1639void MSWriter::getValidTimeRange( Double &me, Double &interval, Table &tab )
1640{
1641//   double startSec = gettimeofday_sec() ;
1642//   os_ << "start MSWriter::getVaridTimeRange() startSec=" << startSec << LogIO::POST ;
1643
1644  // sort table
1645  //Table stab = tab.sort( "TIME" ) ;
1646
1647  ROScalarColumn<Double> timeCol( tab, "TIME" ) ;
1648  Vector<Double> timeArr = timeCol.getColumn() ;
1649  Double minTime ;
1650  Double maxTime ;
1651  minMax( minTime, maxTime, timeArr ) ;
1652  Double midTime = 0.5 * ( minTime + maxTime ) * 86400.0 ;
1653  // unit for TIME
1654  // Scantable: "d"
1655  // MS: "s"
1656  me = midTime ;
1657  interval = ( maxTime - minTime ) * 86400.0 ;
1658
1659//   double endSec = gettimeofday_sec() ;
1660//   os_ << "end MSWriter::getValidTimeRange() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1661}
1662
1663void MSWriter::getValidTimeRange( Double &me, Double &interval, Vector<Double> &atime, Vector<Double> &ainterval )
1664{
1665//   double startSec = gettimeofday_sec() ;
1666//   os_ << "start MSWriter::getVaridTimeRange() startSec=" << startSec << LogIO::POST ;
1667
1668  // sort table
1669  //Table stab = tab.sort( "TIME" ) ;
1670
1671  Double minTime ;
1672  Double maxTime ;
1673  minMax( minTime, maxTime, atime ) ;
1674  Double midTime = 0.5 * ( minTime + maxTime ) * 86400.0 ;
1675  // unit for TIME
1676  // Scantable: "d"
1677  // MS: "s"
1678  me = midTime ;
1679  interval = ( maxTime - minTime ) * 86400.0 + mean( ainterval ) ;
1680
1681//   double endSec = gettimeofday_sec() ;
1682//   os_ << "end MSWriter::getValidTimeRange() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1683}
1684
1685//void MSWriter::queryType( Int type, String &stype, Bool &b )
1686void MSWriter::queryType( Int type, String &stype, Bool &b, Double &t, Double &l )
1687{
1688//   double startSec = gettimeofday_sec() ;
1689//   os_ << "start MSWriter::queryType() startSec=" << startSec << LogIO::POST ;
1690
1691  // 2011/03/14 TN
1692  // OBS_MODE string of MS created by importasdm task is slightly
1693  // (but critically) changed.
1694  // 2011/05/20 TN
1695  // OBS_MODE string of MS created by importasdm task is changed
1696  // again (separator is now "#" instead of "_"
1697  String sep1="#" ;
1698  String sep2="," ;
1699  String target="OBSERVE_TARGET" ;
1700  String atmcal="CALIBRATE_TEMPERATURE" ;
1701  String onstr="ON_SOURCE" ;
1702  String offstr="OFF_SOURCE" ;
1703  String pswitch="POSITION_SWITCH" ;
1704  String nod="NOD" ;
1705  String fswitch="FREQUENCY_SWITCH" ;
1706  String sigstr="SIG" ;
1707  String refstr="REF" ;
1708  String unspecified="UNSPECIFIED" ;
1709  String ftlow="LOWER" ;
1710  String fthigh="HIGHER" ;
1711  switch ( type ) {
1712  case SrcType::PSON:
1713    //stype = "OBSERVE_TARGET_ON_SOURCE,POSITION_SWITCH" ;
1714    stype = target+sep1+onstr+sep2+pswitch ;
1715    b = True ;
1716    t = 0.0 ;
1717    l = 0.0 ;
1718    break ;
1719  case SrcType::PSOFF:
1720    //stype = "OBSERVE_TARGET_OFF_SOURCE,POSITION_SWITCH" ;
1721    stype = target+sep1+offstr+sep2+pswitch ;
1722    b = False ;
1723    t = 0.0 ;
1724    l = 0.0 ;
1725    break ;
1726  case SrcType::NOD:
1727    //stype = "OBSERVE_TARGET_ON_SOURCE,NOD" ;
1728    stype = target+sep1+onstr+sep2+nod ;
1729    b = True ;
1730    t = 0.0 ;
1731    l = 0.0 ;
1732    break ;
1733  case SrcType::FSON:
1734    //stype = "OBSERVE_TARGET_ON_SOURCE,FREQUENCY_SWITCH_SIG" ;
1735    stype = target+sep1+onstr+sep2+fswitch+sep1+sigstr ;
1736    b = True ;
1737    t = 0.0 ;
1738    l = 0.0 ;
1739    break ;
1740  case SrcType::FSOFF:
1741    //stype = "OBSERVE_TARGET_ON_SOURCE,FREQUENCY_SWITCH_REF" ;
1742    stype = target+sep1+onstr+sep2+fswitch+sep1+refstr ;
1743    b = False ;
1744    t = 0.0 ;
1745    l = 0.0 ;
1746    break ;
1747  case SrcType::SKY:
1748    //stype = "CALIBRATE_TEMPERATURE_OFF_SOURCE,UNSPECIFIED" ;
1749    stype = atmcal+sep1+offstr+sep2+unspecified ;
1750    b = False ;
1751    t = 0.0 ;
1752    l = 1.0 ;
1753    break ;
1754  case SrcType::HOT:
1755    //stype = "CALIBRATE_TEMPERATURE_OFF_SOURCE,UNSPECIFIED" ;
1756    stype = atmcal+sep1+offstr+sep2+unspecified ;
1757    b = False ;
1758    t = 0.0 ;
1759    l = 1.0 ;
1760    break ;
1761  case SrcType::WARM:
1762    //stype = "CALIBRATE_TEMPERATURE_OFF_SOURCE,UNSPECIFIED" ;
1763    stype = atmcal+sep1+offstr+sep2+unspecified ;
1764    t = 0.0 ;
1765    b = False ;
1766    l = 1.0 ;
1767    break ;
1768  case SrcType::COLD:
1769    //stype = "CALIBRATE_TEMPERATURE_OFF_SOURCE,UNSPECIFIED" ;
1770    stype = atmcal+sep1+offstr+sep2+unspecified ;
1771    b = False ;
1772    t = 0.0 ;
1773    l = 1.0 ;
1774    break ;
1775  case SrcType::PONCAL:
1776    //stype = "CALIBRATE_TEMPERATURE_ON_SOURCE,POSITION_SWITCH" ;
1777    stype = atmcal+sep1+onstr+sep2+pswitch ;
1778    b = True ;
1779    t = 1.0 ;
1780    l = 0.0 ;
1781    break ;
1782  case SrcType::POFFCAL:
1783    //stype = "CALIBRATE_TEMPERATURE_OFF_SOURCE,POSITION_SWITCH" ;
1784    stype = atmcal+sep1+offstr+sep2+pswitch ;
1785    b = False ;
1786    t = 1.0 ;
1787    l = 0.0 ;
1788    break ;
1789  case SrcType::NODCAL:
1790    //stype = "CALIBRATE_TEMPERATURE_ON_SOURCE,NOD" ;
1791    stype = atmcal+sep1+onstr+sep2+nod ;
1792    b = True ;
1793    t = 1.0 ;
1794    l = 0.0 ;
1795    break ;
1796  case SrcType::FONCAL:
1797    //stype = "CALIBRATE_TEMPERATURE_ON_SOURCE,FREQUENCY_SWITCH_SIG" ;
1798    stype = atmcal+sep1+onstr+sep2+fswitch+sep1+sigstr ;
1799    b = True ;
1800    t = 1.0 ;
1801    l = 0.0 ;
1802    break ;
1803  case SrcType::FOFFCAL:
1804    //stype = "CALIBRATE_TEMPERATURE_OFF_SOURCE,FREQUENCY_SWITCH_REF" ;
1805    stype = atmcal+sep1+offstr+sep2+fswitch+sep1+refstr ;
1806    b = False ;
1807    t = 1.0 ;
1808    l = 0.0 ;
1809    break ;
1810  case SrcType::FSLO:
1811    //stype = "OBSERVE_TARGET_ON_SOURCE,FREQUENCY_SWITCH_LOWER" ;
1812    stype = target+sep1+onstr+sep2+fswitch+sep1+ftlow ;
1813    b = True ;
1814    t = 0.0 ;
1815    l = 0.0 ;
1816    break ;
1817  case SrcType::FLOOFF:
1818    //stype = "OBSERVE_TARGET_OFF_SOURCE,FREQUENCY_SWITCH_LOWER" ;
1819    stype = target+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1820    b = False ;
1821    t = 0.0 ;
1822    l = 0.0 ;
1823    break ;
1824  case SrcType::FLOSKY:
1825    //stype = "CALIBRATE_TEMPERATURE_OFF_SOURCE,FREQUENCY_SWITCH_LOWER" ;
1826    stype = atmcal+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1827    b = False ;
1828    t = 0.0 ;
1829    l = 1.0 ;
1830    break ;
1831  case SrcType::FLOHOT:
1832    //stype = "CALIBRATE_TEMPERATURE_OFF_SOURCE,FREQUENCY_SWITCH_LOWER" ;
1833    stype = atmcal+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1834    b = False ;
1835    t = 0.0 ;
1836    l = 1.0 ;
1837    break ;
1838  case SrcType::FLOWARM:
1839    //stype = "CALIBRATE_TEMPERATURE_OFF_SOURCE,FREQUENCY_SWITCH_LOWER" ;
1840    stype = atmcal+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1841    b = False ;
1842    t = 0.0 ;
1843    l = 1.0 ;
1844    break ;
1845  case SrcType::FLOCOLD:
1846    //stype = "CALIBRATE_TEMPERATURE_OFF_SOURCE,FREQUENCY_SWITCH_LOWER" ;
1847    stype = atmcal+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1848    b = False ;
1849    t = 0.0 ;
1850    l = 1.0 ;
1851    break ;
1852  case SrcType::FSHI:
1853    //stype = "OBSERVE_TARGET_ON_SOURCE,FREQUENCY_SWITCH_HIGHER" ;
1854    stype = target+sep1+onstr+sep2+fswitch+sep1+fthigh ;
1855    b = True ;
1856    t = 0.0 ;
1857    l = 0.0 ;
1858    break ;
1859  case SrcType::FHIOFF:
1860    //stype = "CALIBRATE_TEMPERATURE_OFF_SOURCE,FREQUENCY_SWITCH_HIGHER" ;
1861    stype = target+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1862    b = False ;
1863    t = 0.0 ;
1864    l = 0.0 ;
1865    break ;
1866  case SrcType::FHISKY:
1867    //stype = "CALIBRATE_TEMPERATURE_OFF_SOURCE,FREQUENCY_SWITCH_HIGHER" ;
1868    stype = atmcal+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1869    b = False ;
1870    t = 0.0 ;
1871    l = 1.0 ;
1872    break ;
1873  case SrcType::FHIHOT:
1874    //stype = "CALIBRATE_TEMPERATURE_OFF_SOURCE,FREQUENCY_SWITCH_HIGHER" ;
1875    stype = atmcal+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1876    b = False ;
1877    t = 0.0 ;
1878    l = 1.0 ;
1879    break ;
1880  case SrcType::FHIWARM:
1881    //stype = "CALIBRATE_TEMPERATURE_OFF_SOURCE,FREQUENCY_SWITCH_HIGHER" ;
1882    stype = atmcal+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1883    b = False ;
1884    t = 0.0 ;
1885    l = 1.0 ;
1886    break ;
1887  case SrcType::FHICOLD:
1888    //stype = "CALIBRATE_TEMPERATURE_OFF_SOURCE,FREQUENCY_SWITCH_HIGHER" ;
1889    stype = atmcal+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1890    b = False ;
1891    t = 0.0 ;
1892    l = 1.0 ;
1893    break ;
1894  case SrcType::SIG:
1895    //stype = "OBSERVE_TARGET_ON_SOURCE,UNSPECIFIED" ;
1896    stype = target+sep1+onstr+sep2+unspecified ;
1897    b = True ;
1898    t = 0.0 ;
1899    l = 0.0 ;
1900    break ;
1901  case SrcType::REF:
1902    //stype = "OBSERVE_TARGET_ON_SOURCE,UNSPECIFIED" ;
1903    stype = target+sep1+offstr+sep2+unspecified ;
1904    b = False ;
1905    t = 0.0 ;
1906    l = 0.0 ;
1907    break ;
1908  default:
1909    //stype = "UNSPECIFIED" ;
1910    stype = unspecified ;
1911    b = True ;
1912    t = 0.0 ;
1913    l = 0.0 ;
1914    break ;
1915  }
1916
1917//   double endSec = gettimeofday_sec() ;
1918//   os_ << "end MSWriter::queryType() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1919}
1920
1921Double MSWriter::getDishDiameter( String antname )
1922{
1923  Double diameter = 0.0 ;
1924 
1925  antname.upcase() ;
1926
1927  if ( antname.matches( Regex( "DV[0-9]+$" ) )
1928       || antname.matches( Regex( "DA[0-9]+$" ) )
1929       || antname.matches( Regex( "PM[0-9]+$" ) ) )
1930    diameter = 12.0 ;
1931  else if ( antname.matches( Regex( "CM[0-9]+$" ) ) )
1932    diameter = 7.0 ;
1933  else if ( antname.contains( "GBT" ) )
1934    diameter = 104.9 ;
1935  else if ( antname.contains( "MOPRA" ) )
1936    diameter = 22.0 ;
1937  else if ( antname.contains( "PKS" ) || antname.contains( "PARKS" ) )
1938    diameter = 64.0 ;
1939  else if ( antname.contains( "TIDBINBILLA" ) )
1940    diameter = 70.0 ;
1941  else if ( antname.contains( "CEDUNA" ) )
1942    diameter = 30.0 ;
1943  else if ( antname.contains( "HOBART" ) )
1944    diameter = 26.0 ;
1945  else if ( antname.contains( "APEX" ) )
1946    diameter = 12.0 ;
1947  else if ( antname.contains( "ASTE" ) )
1948    diameter = 10.0 ;
1949  else if ( antname.contains( "NRO" ) )
1950    diameter = 45.0 ;
1951  else
1952    diameter = 1.0 ;
1953
1954  return diameter ;
1955}
1956
1957void MSWriter::infillSpectralWindow()
1958{
1959  MSSpectralWindow msSpw = mstable_->spectralWindow() ;
1960  MSSpWindowColumns msSpwCols( msSpw ) ;
1961  uInt nrow = msSpw.nrow() ;
1962
1963  ScalarColumn<Int> measFreqRefCol = msSpwCols.measFreqRef() ;
1964  ArrayColumn<Double> chanFreqCol = msSpwCols.chanFreq() ;
1965  ArrayColumn<Double> chanWidthCol = msSpwCols.chanWidth() ;
1966  ArrayColumn<Double> effectiveBWCol = msSpwCols.effectiveBW() ;
1967  ArrayColumn<Double> resolutionCol = msSpwCols.resolution() ;
1968  Vector<Double> dummy( 1, 0.0 ) ;
1969  for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
1970    if ( !(chanFreqCol.isDefined( irow )) ) {
1971      measFreqRefCol.put( irow, 1 ) ;
1972      chanFreqCol.put( irow, dummy ) ;
1973      chanWidthCol.put( irow, dummy ) ;
1974      effectiveBWCol.put( irow, dummy ) ;
1975      resolutionCol.put( irow, dummy ) ;
1976    }
1977  }
1978
1979}
1980
1981}
Note: See TracBrowser for help on using the repository browser.