source: trunk/src/MSWriter.cpp @ 1977

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

Almost finished a writer. Ready to test.


File size: 50.6 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
20#include <tables/Tables/ExprNode.h>
21#include <tables/Tables/TableDesc.h>
22#include <tables/Tables/SetupNewTab.h>
23#include <tables/Tables/TableIter.h>
24#include <tables/Tables/RefRows.h>
25
26#include <ms/MeasurementSets/MeasurementSet.h>
27#include <ms/MeasurementSets/MSColumns.h>
28#include <ms/MeasurementSets/MSPolIndex.h>
29#include <ms/MeasurementSets/MSDataDescIndex.h>
30#include <ms/MeasurementSets/MSSourceIndex.h>
31
32#include "MSWriter.h"
33#include "STHeader.h"
34#include "STFrequencies.h"
35#include "STMolecules.h"
36#include "STTcal.h"
37
38using namespace casa ;
39
40namespace asap
41{
42
43MSWriter::MSWriter(CountedPtr<Scantable> stable)
44  : table_(stable)
45{
46  os_ = LogIO() ;
47  os_.origin( LogOrigin( "MSWriter", "MSWriter()", WHERE ) ) ;
48  os_ << "MSWriter::MSWriter()" << LogIO::POST ;
49
50  // initialize writer
51  init() ;
52}
53
54MSWriter::~MSWriter()
55{
56  os_.origin( LogOrigin( "MSWriter", "~MSWriter()", WHERE ) ) ;
57  os_ << "MSWriter::~MSWriter()" << LogIO::POST ;
58}
59 
60bool MSWriter::write(const string& filename, const Record& rec)
61{
62  os_.origin( LogOrigin( "MSWriter", "write()", WHERE ) ) ;
63  os_ << "MSWriter::write()" << LogIO::POST ;
64
65  filename_ = filename ;
66
67  // parsing MS options
68  Bool overwrite = False ;
69  if ( rec.isDefined( "ms" ) ) {
70    Record msrec = rec.asRecord( "ms" ) ;
71    if ( msrec.isDefined( "overwrite" ) ) {
72      overwrite = msrec.asBool( "overwrite" ) ;
73    }
74  }
75
76  os_ << "Parsing MS options" << endl ;
77  os_ << "   overwrite = " << overwrite << LogIO::POST ;
78
79  File file( filename_ ) ;
80  if ( file.exists() ) {
81    if ( overwrite ) {
82      os_ << filename_ << " exists. Overwrite existing data... " << LogIO::POST ;
83      if ( file.isRegular() ) RegularFile(file).remove() ;
84      else if ( file.isDirectory() ) Directory(file).removeRecursive() ;
85      else SymLink(file).remove() ;
86    }
87    else {
88      os_ << LogIO::SEVERE << "ERROR: " << filename_ << " exists..." << LogIO::POST ;
89      return False ;
90    }
91  }
92
93  // set up MS
94  setupMS() ;
95 
96  // subtables
97  // OBSERVATION
98  fillObservation() ;
99
100  // ANTENNA
101  fillAntenna() ;
102
103  // PROCESSOR
104  fillProcessor() ;
105
106  // SOURCE
107  fillSource() ;
108
109  // WEATHER
110  fillWeather() ;
111
112  // MAIN
113  // Iterate over several ids
114  Vector<uInt> processedFreqId( 0 ) ;
115  Int defaultFieldId = 0 ;
116  //
117  // ITERATION: FIELDNAME
118  //
119  Int added0 = 0 ;
120  Int current0 = mstable_->nrow() ;
121  TableIterator iter0( table_->table(), "FIELDNAME" ) ;
122  while( !iter0.pastEnd() ) {
123    Table t0( iter0.table() ) ;
124    ROScalarColumn<String> sharedStrCol( t0, "FIELDNAME" ) ;
125    String fieldName = sharedStrCol( 0 ) ;
126    sharedStrCol.attach( t0, "SRCNAME" ) ;
127    String srcName = sharedStrCol( 0 ) ;
128    ROScalarColumn<Double> timeCol( t0, "TIME" ) ;
129    Double minTime = min( timeCol.getColumn() ) ;
130    ROArrayColumn<Double> scanRateCol( t0, "SCANRATE" ) ;
131    Vector<Double> scanRate = scanRateCol.getColumn()[0] ;
132    String::size_type pos = fieldName.find( "__" ) ;
133    Int fieldId = -1 ;
134    if ( pos != String::npos ) {
135      os_ << "fieldName.substr( pos+2 )=" << fieldName.substr( pos+2 ) << LogIO::POST ;
136      fieldId = String::toInt( fieldName.substr( pos+2 ) ) ;
137      fieldName = fieldName.substr( 0, pos ) ;
138    }
139    else {
140      os_ << "use default field id" << LogIO::POST ;
141      fieldId = defaultFieldId ;
142      defaultFieldId++ ;
143    }
144    os_ << "fieldId" << fieldId << ": " << fieldName << LogIO::POST ;
145    //
146    // ITERATION: BEAMNO
147    //
148    Int added1 = 0 ;
149    Int current1 = mstable_->nrow() ;
150    TableIterator iter1( t0, "BEAMNO" ) ;
151    while( !iter1.pastEnd() ) {
152      Table t1( iter1.table() ) ;
153      ROScalarColumn<uInt> beamNoCol( t1, "BEAMNO" ) ;
154      uInt beamNo = beamNoCol( 0 ) ;
155      os_ << "beamNo = " << beamNo << LogIO::POST ;
156      //
157      // ITERATION: SCANNO
158      //
159      Int added2 = 0 ;
160      Int current2 = mstable_->nrow() ;
161      TableIterator iter2( t1, "SCANNO" ) ;
162      while( !iter2.pastEnd() ) {
163        Table t2( iter2.table() ) ;
164        ROScalarColumn<uInt> scanNoCol( t2, "SCANNO" ) ;
165        uInt scanNo = scanNoCol( 0 ) ;
166        os_ << "scanNo = " << scanNo << LogIO::POST ;
167        //
168        // ITERATION: IFNO
169        //
170        Int added3 = 0 ;
171        Int current3 = mstable_->nrow() ;
172        TableIterator iter3( t2, "IFNO" ) ;
173        while( !iter3.pastEnd() ) {
174          Table t3( iter3.table() ) ;
175          ROScalarColumn<uInt> ifNoCol( t3, "IFNO" ) ;
176          uInt ifNo = ifNoCol( 0 ) ;
177          os_ << "ifNo = " << ifNo << LogIO::POST ;
178          ROScalarColumn<uInt> freqIdCol( t3, "FREQ_ID" ) ;
179          uInt freqId = freqIdCol( 0 ) ;
180          os_ << "freqId = " << freqId << LogIO::POST ;
181          Int subscan = 0 ;
182          //
183          // ITERATION: CYCLENO
184          //
185          Int added4 = 0 ;
186          Int current4 = mstable_->nrow() ;
187          TableIterator iter4( t3, "CYCLENO" ) ;
188          while( !iter4.pastEnd() ) {
189            Table t4( iter4.table() ) ;
190            //
191            // ITERATION: TIME
192            //
193            Int added5 = 0 ;
194            Int current5 = mstable_->nrow() ;
195            TableIterator iter5( t4, "TIME" ) ;
196            while( !iter5.pastEnd() ) {
197              Table t5( iter5.table().sort("POLNO") ) ;
198              Int prevnr = mstable_->nrow() ;
199              Int nrow = t5.nrow() ;
200              os_ << "nrow = " << nrow << LogIO::POST ;
201             
202              // add row
203              mstable_->addRow( 1, True ) ;
204             
205              Vector<Int> polnos( nrow ) ;
206              indgen( polnos, 0 ) ;
207              Int polid = addPolarization( polnos ) ;
208              os_ << "polid = " << polid << LogIO::POST ;
209              //
210              // LOOP: POLNO
211              //
212              ROArrayColumn<Float> specCol( t5, "SPECTRA" ) ;
213              ROArrayColumn<uChar> flagCol( t5, "FLAGTRA" ) ;
214              ROScalarColumn<uInt> flagRowCol( t5, "FLAGROW" ) ;
215              uInt nchan = specCol( 0 ).size() ;
216              IPosition newshape( 2,1,nchan ) ;
217              IPosition cellshape( 2, nrow, nchan ) ;
218              if ( useFloatData_ ) {
219                // FLOAT_DATA
220                Array<Float> dataArr( cellshape ) ;
221                Array<Bool> flagArr( cellshape ) ;
222                for ( Int ipol = 0 ; ipol < nrow ; ipol++ ) {
223                  Slicer slicer( Slice(ipol), Slice(0,nchan,1) ) ;
224                  dataArr( slicer ) = specCol( ipol ).reform( newshape ) ;
225                  Array<uChar> tmpUC = flagCol( ipol ).reform( newshape ) ;
226                  Array<Bool> tmpB( tmpUC.shape() ) ;
227                  //convertArray( flagArr( slicer ), flagCol( ipol ).reform( newshape ) ) ;
228                  convertArray( tmpB, tmpUC ) ;
229                  flagArr( slicer ) = tmpB ;
230                }
231                ArrayColumn<Float> msDataCol( *mstable_, "FLOAT_DATA" ) ;
232                msDataCol.put( prevnr, dataArr ) ;
233               
234                // FLAG
235                ArrayColumn<Bool> msFlagCol( *mstable_, "FLAG" ) ;
236                msFlagCol.put( prevnr, flagArr ) ;
237              }
238              else if ( useData_ ) {
239                // DATA
240                // assume nrow = 4
241                Array<Complex> dataArr( cellshape ) ;
242                Vector<Float> zeroIm( nchan, 0 ) ;
243                Array<Float> dummy( IPosition( 2, 2, nchan ) ) ;
244                Slicer slicer0( Slice(0), Slice(0,nchan,1) ) ;
245                Slicer slicer1( Slice(1), Slice(0,nchan,1) ) ;
246                Slicer slicer2( Slice(2), Slice(0,nchan,1) ) ;
247                Slicer slicer3( Slice(3), Slice(0,nchan,1) ) ;
248                dummy( slicer0 ) = specCol( 0 ).reform( newshape ) ;
249                dummy( slicer1 ) = zeroIm.reform( newshape ) ;
250                dataArr( slicer0 ) = RealToComplex( dummy ) ;
251                dummy( slicer0 ) = specCol( 1 ).reform( newshape ) ;
252                dataArr( slicer3 ) = RealToComplex( dummy ) ;
253                dummy( slicer0 ) = specCol( 2 ).reform( newshape ) ;
254                dummy( slicer1 ) = specCol( 3 ).reform( newshape ) ;
255                dataArr( slicer1 ) = RealToComplex( dummy ) ;
256                dataArr( slicer2 ) = conj( RealToComplex( dummy ) ) ;
257                ArrayColumn<Complex> msDataCol( *mstable_, "DATA" ) ;
258                msDataCol.put( prevnr, dataArr ) ;
259
260                // FLAG
261                Array<Bool> flagArr( cellshape ) ;
262                Array<uChar> tmpUC = flagCol( 0 ).reform( newshape ) ;
263                Array<Bool> tmpB( tmpUC.shape() ) ;
264                convertArray( tmpB, tmpUC ) ;
265                flagArr( slicer0 ) = tmpB ;
266                tmpUC = flagCol( 3 ).reform( newshape ) ;
267                convertArray( tmpB, tmpUC ) ;
268                flagArr( slicer3 ) = tmpB ;
269                Vector<uChar> bitOr = flagCol( 2 ) | flagCol( 3 ) ;
270                tmpUC = bitOr.reform( newshape ) ;
271                convertArray( tmpB, tmpUC ) ;
272                flagArr( slicer1 ) = tmpB ;
273                flagArr( slicer2 ) = tmpB ;
274                ArrayColumn<Bool> msFlagCol( *mstable_, "FLAG" ) ;
275                msFlagCol.put( prevnr, flagArr ) ;
276              }
277
278              // FLAG_ROW
279              ScalarColumn<Bool> msFlagRowCol( *mstable_, "FLAG_ROW" ) ;
280              msFlagRowCol.put( prevnr, anyNE( flagRowCol.getColumn(), (uInt)0 ) ) ;
281             
282              // TIME and TIME_CENTROID
283              ROScalarMeasColumn<MEpoch> timeCol( t5, "TIME" ) ;
284              MEpoch mTime = timeCol( 0 ) ;
285              ScalarMeasColumn<MEpoch> msTimeCol( *mstable_, "TIME" ) ;
286              msTimeCol.put( prevnr, mTime ) ;
287              msTimeCol.attach( *mstable_, "TIME_CENTROID" ) ;
288              msTimeCol.put( prevnr, mTime ) ;
289             
290              // INTERVAL and EXPOSURE
291              ROScalarColumn<Double> intervalCol( t5, "INTERVAL" ) ;
292              Double interval = intervalCol( 0 ) ;
293              ScalarColumn<Double> msIntervalCol( *mstable_, "INTERVAL" ) ;
294              msIntervalCol.put( prevnr, interval ) ;
295              msIntervalCol.attach( *mstable_, "EXPOSURE" ) ;
296              msIntervalCol.put( prevnr, interval ) ;
297
298              // WEIGHT and SIGMA
299              // always 1 at the moment
300              Vector<Float> wArr( nrow, 1.0 ) ;
301              ArrayColumn<Float> wArrCol( *mstable_, "WEIGHT" ) ;
302              wArrCol.put( prevnr, wArr ) ;
303              wArrCol.attach( *mstable_, "SIGMA" ) ;
304              wArrCol.put( prevnr, wArr ) ;
305             
306              // add DATA_DESCRIPTION row
307              Int ddid = addDataDescription( polid, ifNo ) ;
308              os_ << "ddid = " << ddid << LogIO::POST ;
309              ScalarColumn<Int> ddIdCol( *mstable_, "DATA_DESC_ID" ) ;
310              ddIdCol.put( prevnr, ddid ) ;
311             
312              // for SYSCAL table
313              ROScalarColumn<uInt> tcalIdCol( t5, "TCAL_ID" ) ;
314              Vector<uInt> tcalIdArr = tcalIdCol.getColumn() ;
315              os_ << "tcalIdArr = " << tcalIdArr << LogIO::POST ;
316              String key = String::toString( tcalIdArr[0] ) ;
317              if ( !tcalIdRec_.isDefined( key ) ) {
318                tcalIdRec_.define( key, tcalIdArr ) ;
319              }
320             
321              // fill STATE_ID
322              ROScalarColumn<Int> srcTypeCol( t5, "SRCTYPE" ) ;
323              Int srcType = srcTypeCol( 0 ) ;
324              Int stateId = addState( srcType, subscan ) ;
325              ScalarColumn<Int> msStateIdCol( *mstable_, "STATE_ID" ) ;
326              msStateIdCol.put( prevnr, stateId ) ;
327
328              // for POINTING table
329              Matrix<Double> msDir( 2, 2 ) ;
330              ROArrayColumn<Double> dirCol( t5, "DIRECTION" ) ;
331              msDir.column( 0 ) = dirCol( 0 ) ;
332              dirCol.attach( t5, "SCANRATE" ) ;
333              msDir.column( 1 ) = dirCol( 0 ) ;
334              addPointing( fieldName, mTime, interval, msDir ) ;
335
336              added5 += 1 ;
337              os_ << "added5 = " << added5 << " current5 = " << current5 << LogIO::POST ;
338              iter5.next() ;
339            }
340           
341            added4 += added5 ;
342            os_ << "added4 = " << added4 << " current4 = " << current4 << LogIO::POST ;
343            iter4.next() ;
344          }
345
346          // add SPECTRAL_WINDOW row
347          if ( allNE( processedFreqId, freqId ) ) {
348            uInt vsize = processedFreqId.size() ;
349            processedFreqId.resize( vsize+1, True ) ;
350            processedFreqId[vsize] = freqId ;
351            addSpectralWindow( ifNo, freqId ) ;
352          }
353         
354          added3 += added4 ;
355          os_ << "added3 = " << added3 << " current3 = " << current3 << LogIO::POST ;
356          iter3.next() ;
357        }
358       
359        // SCAN_NUMBER
360        RefRows rows3( current3, current3+added3-1 ) ;
361        Vector<Int> scanNum( added3, scanNo ) ;
362        ScalarColumn<Int> scanNumCol( *mstable_, "SCAN_NUMBER" ) ;
363        scanNumCol.putColumnCells( rows3, scanNum ) ;
364       
365        added2 += added3 ;
366        os_ << "added2 = " << added2 << " current2 = " << current2 << LogIO::POST ;
367        iter2.next() ;
368      }
369     
370      // FEED1 and FEED2
371      RefRows rows2( current2, current2+added2-1 ) ;
372      Vector<Int> feedId( added2, beamNo ) ;
373      ScalarColumn<Int> feedCol( *mstable_, "FEED1" ) ;
374      feedCol.putColumnCells( rows2, feedId ) ;
375      feedCol.attach( *mstable_, "FEED2" ) ;
376      feedCol.putColumnCells( rows2, feedId ) ;
377     
378      // add FEED row
379      addFeed( beamNo ) ;
380     
381      added1 += added2 ;
382      os_ << "added1 = " << added1 << " current1 = " << current1 << LogIO::POST ;
383      iter1.next() ;
384    }
385   
386    // FIELD_ID
387    RefRows rows1( current1, current1+added1-1 ) ;
388    Vector<Int> fieldIds( added1, fieldId ) ;
389    ScalarColumn<Int> fieldIdCol( *mstable_, "FIELD_ID" ) ;
390    fieldIdCol.putColumnCells( rows1, fieldIds ) ;
391
392    // add FIELD row
393    addField( fieldId, fieldName, srcName, minTime, scanRate ) ;
394
395    added0 += added1 ;
396    os_ << "added0 = " << added0 << " current0 = " << current0 << LogIO::POST ;
397    iter0.next() ;
398  }
399
400  // OBSERVATION_ID is always 0
401  ScalarColumn<Int> sharedIntCol( *mstable_, "OBSERVATION_ID" ) ;
402  Vector<Int> sharedIntArr( added0, 0 ) ;
403  sharedIntCol.putColumn( sharedIntArr ) ;
404
405  // ANTENNA1 and ANTENNA2 are always 0
406  sharedIntArr = 0 ;
407  sharedIntCol.attach( *mstable_, "ANTENNA1" ) ;
408  sharedIntCol.putColumn( sharedIntArr ) ;
409  sharedIntCol.attach( *mstable_, "ANTENNA2" ) ;
410  sharedIntCol.putColumn( sharedIntArr ) ;
411
412  // ARRAY_ID is tentatively set to 0
413  sharedIntArr = 0 ;
414  sharedIntCol.attach( *mstable_, "ARRAY_ID" ) ;
415  sharedIntCol.putColumn( sharedIntArr ) ;
416
417  // PROCESSOR_ID is tentatively set to 0
418  sharedIntArr = 0 ;
419  sharedIntCol.attach( *mstable_, "PROCESSOR_ID" ) ;
420  sharedIntCol.putColumn( sharedIntArr ) ;
421
422
423  // SYSCAL
424  fillSysCal() ;
425
426  return True ;
427}
428 
429void MSWriter::init()
430{
431//   os_.origin( LogOrigin( "MSWriter", "init()", WHERE ) ) ;
432  os_ << "MSWriter::init()" << LogIO::POST ;
433 
434  // access to scantable
435  header_ = table_->getHeader() ;
436
437  // FLOAT_DATA? or DATA?
438  if ( header_.npol > 2 ) {
439    useFloatData_ = False ;
440    useData_ = True ;
441  }
442  else {
443    useFloatData_ = True ;
444    useData_ = False ;
445  }
446
447  // polarization type
448  polType_ = header_.poltype ;
449  if ( polType_ == "" )
450    polType_ = "stokes" ;
451  else if ( polType_.find( "linear" ) != String::npos )
452    polType_ = "linear" ;
453  else if ( polType_.find( "circular" ) != String::npos )
454    polType_ = "circular" ;
455  else if ( polType_.find( "stokes" ) != String::npos )
456    polType_ = "stokes" ;
457  else if ( polType_.find( "linpol" ) != String::npos )
458    polType_ = "linpol" ;
459  else
460    polType_ = "notype" ;
461
462  // Are TCAL_SPECTRUM and TSYS_SPECTRUM necessary?
463  tcalSpec_ = False ;
464  tsysSpec_ = False ;
465  if ( header_.nchan != 1 ) {
466    // examine TCAL subtable
467    Table tcaltab = table_->tcal().table() ;
468    ROArrayColumn<Float> tcalCol( tcaltab, "TCAL" ) ;
469    for ( uInt irow = 0 ; irow < tcaltab.nrow() ; irow++ ) {
470      if ( tcalCol( irow ).size() != 1 )
471        tcalSpec_ = True ;
472    }
473    // examine spectral data
474    TableIterator iter0( table_->table(), "IFNO" ) ;
475    while( !iter0.pastEnd() ) {
476      Table t0( iter0.table() ) ;
477      ROArrayColumn<Float> sharedFloatArrCol( t0, "SPECTRA" ) ;
478      uInt len = sharedFloatArrCol( 0 ).size() ;
479      if ( len != 1 ) {
480        sharedFloatArrCol.attach( t0, "TSYS" ) ;
481        if ( sharedFloatArrCol( 0 ).size() != 1 )
482          tsysSpec_ = True ;
483      }
484      iter0.next() ;
485    }
486  }
487}
488
489void MSWriter::setupMS()
490{
491//   os_.origin( LogOrigin( "MSWriter", "setupMS()", WHERE ) ) ;
492  os_ << "MSWriter::setupMS()" << LogIO::POST ;
493
494  TableDesc msDesc = MeasurementSet::requiredTableDesc() ;
495  if ( useFloatData_ )
496    MeasurementSet::addColumnToDesc( msDesc, MSMainEnums::FLOAT_DATA, 2 ) ;
497  else if ( useData_ )
498    MeasurementSet::addColumnToDesc( msDesc, MSMainEnums::DATA, 2 ) ;
499
500  SetupNewTable newtab( filename_, msDesc, Table::New ) ;
501
502  mstable_ = new MeasurementSet( newtab ) ;
503
504  // create subtables
505  TableDesc antennaDesc = MSAntenna::requiredTableDesc() ;
506  SetupNewTable antennaTab( mstable_->antennaTableName(), antennaDesc, Table::New ) ;
507  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::ANTENNA ), Table( antennaTab ) ) ;
508
509  TableDesc dataDescDesc = MSDataDescription::requiredTableDesc() ;
510  SetupNewTable dataDescTab( mstable_->dataDescriptionTableName(), dataDescDesc, Table::New ) ;
511  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::DATA_DESCRIPTION ), Table( dataDescTab ) ) ;
512
513  TableDesc dopplerDesc = MSDoppler::requiredTableDesc() ;
514  SetupNewTable dopplerTab( mstable_->dopplerTableName(), dopplerDesc, Table::New ) ;
515  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::DOPPLER ), Table( dopplerTab ) ) ;
516
517  TableDesc feedDesc = MSFeed::requiredTableDesc() ;
518  SetupNewTable feedTab( mstable_->feedTableName(), feedDesc, Table::New ) ;
519  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FEED ), Table( feedTab ) ) ;
520
521  TableDesc fieldDesc = MSField::requiredTableDesc() ;
522  SetupNewTable fieldTab( mstable_->fieldTableName(), fieldDesc, Table::New ) ;
523  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FIELD ), Table( fieldTab ) ) ;
524
525  TableDesc flagCmdDesc = MSFlagCmd::requiredTableDesc() ;
526  SetupNewTable flagCmdTab( mstable_->flagCmdTableName(), flagCmdDesc, Table::New ) ;
527  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FLAG_CMD ), Table( flagCmdTab ) ) ;
528
529  TableDesc freqOffsetDesc = MSFreqOffset::requiredTableDesc() ;
530  SetupNewTable freqOffsetTab( mstable_->freqOffsetTableName(), freqOffsetDesc, Table::New ) ;
531  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FREQ_OFFSET ), Table( freqOffsetTab ) ) ;
532
533  TableDesc historyDesc = MSHistory::requiredTableDesc() ;
534  SetupNewTable historyTab( mstable_->historyTableName(), historyDesc, Table::New ) ;
535  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::HISTORY ), Table( historyTab ) ) ;
536
537  TableDesc observationDesc = MSObservation::requiredTableDesc() ;
538  SetupNewTable observationTab( mstable_->observationTableName(), observationDesc, Table::New ) ;
539  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::OBSERVATION ), Table( observationTab ) ) ;
540
541  TableDesc pointingDesc = MSPointing::requiredTableDesc() ;
542  SetupNewTable pointingTab( mstable_->pointingTableName(), pointingDesc, Table::New ) ;
543  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::POINTING ), Table( pointingTab ) ) ;
544
545  TableDesc polarizationDesc = MSPolarization::requiredTableDesc() ;
546  SetupNewTable polarizationTab( mstable_->polarizationTableName(), polarizationDesc, Table::New ) ;
547  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::POLARIZATION ), Table( polarizationTab ) ) ;
548
549  TableDesc processorDesc = MSProcessor::requiredTableDesc() ;
550  SetupNewTable processorTab( mstable_->processorTableName(), processorDesc, Table::New ) ;
551  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::PROCESSOR ), Table( processorTab ) ) ;
552
553  TableDesc sourceDesc = MSSource::requiredTableDesc() ;
554  MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::TRANSITION, 1 ) ;
555  MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::REST_FREQUENCY, 1 ) ;
556  MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::SYSVEL, 1 ) ;
557  SetupNewTable sourceTab( mstable_->sourceTableName(), sourceDesc, Table::New ) ;
558  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SOURCE ), Table( sourceTab ) ) ;
559
560  TableDesc spwDesc = MSSpectralWindow::requiredTableDesc() ;
561  SetupNewTable spwTab( mstable_->spectralWindowTableName(), spwDesc, Table::New ) ;
562  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SPECTRAL_WINDOW ), Table( spwTab ) ) ;
563
564  TableDesc stateDesc = MSState::requiredTableDesc() ;
565  SetupNewTable stateTab( mstable_->stateTableName(), stateDesc, Table::New ) ;
566  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::STATE ), Table( stateTab ) ) ;
567
568  // TODO: add TCAL_SPECTRUM and TSYS_SPECTRUM if necessary
569  TableDesc sysCalDesc = MSSysCal::requiredTableDesc() ;
570  MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TCAL, 2 ) ;
571  MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TSYS, 2 ) ;
572  if ( tcalSpec_ )
573    MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TCAL_SPECTRUM, 2 ) ;
574  if ( tsysSpec_ )
575    MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TSYS_SPECTRUM, 2 ) ;
576  SetupNewTable sysCalTab( mstable_->sysCalTableName(), sysCalDesc, Table::New ) ;
577  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SYSCAL ), Table( sysCalTab ) ) ;
578
579  TableDesc weatherDesc = MSWeather::requiredTableDesc() ;
580  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::TEMPERATURE ) ;
581  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::PRESSURE ) ;
582  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::REL_HUMIDITY ) ;
583  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::WIND_SPEED ) ;
584  MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::WIND_DIRECTION ) ;
585  SetupNewTable weatherTab( mstable_->weatherTableName(), weatherDesc, Table::New ) ;
586  mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::WEATHER ), Table( weatherTab ) ) ;
587
588  mstable_->initRefs() ;
589
590}
591
592void MSWriter::fillObservation()
593{
594  os_ << "set up OBSERVATION subtable" << LogIO::POST ;
595  // only 1 row
596  mstable_->observation().addRow( 1, True ) ;
597  MSObservationColumns msObsCols( mstable_->observation() ) ;
598  msObsCols.observer().put( 0, header_.observer ) ;
599  // tentatively put antennaname (from ANTENNA subtable)
600  String hAntennaName = header_.antennaname ;
601  String::size_type pos = hAntennaName.find( "//" ) ;
602  String telescopeName ;
603  if ( pos != String::npos ) {
604    telescopeName = hAntennaName.substr( 0, pos ) ;
605  }
606  else {
607    pos = hAntennaName.find( "@" ) ;
608    telescopeName = hAntennaName.substr( 0, pos ) ;
609  }
610  os_ << "telescopeName = " << telescopeName << LogIO::POST ;
611  msObsCols.telescopeName().put( 0, telescopeName ) ;
612  msObsCols.project().put( 0, header_.project ) ;
613  //ScalarMeasColumn<MEpoch> timeCol( table_->table().sort("TIME"), "TIME" ) ;
614  Table sortedtable = table_->table().sort("TIME") ;
615  ScalarMeasColumn<MEpoch> timeCol( sortedtable, "TIME" ) ;
616  Vector<MEpoch> trange( 2 ) ;
617  trange[0] = timeCol( 0 ) ;
618  trange[1] = timeCol( table_->nrow()-1 ) ;
619  msObsCols.timeRangeMeas().put( 0, trange ) ;
620}
621
622void MSWriter::fillAntenna()
623{
624  os_ << "set up ANTENNA subtable" << LogIO::POST ;
625  // only 1 row
626  mstable_->antenna().addRow( 1, True ) ;
627  MSAntennaColumns msAntCols( mstable_->antenna() ) ;
628
629  String hAntennaName = header_.antennaname ;
630  String::size_type pos = hAntennaName.find( "//" ) ;
631  String antennaName ;
632  String stationName ;
633  if ( pos != String::npos ) {
634    hAntennaName = hAntennaName.substr( pos+2 ) ;
635  }
636  pos = hAntennaName.find( "@" ) ;
637  if ( pos != String::npos ) {
638    antennaName = hAntennaName.substr( 0, pos ) ;
639    stationName = hAntennaName.substr( pos+1 ) ;
640  }
641  else {
642    antennaName = hAntennaName ;
643    stationName = hAntennaName ;
644  }
645  os_ << "antennaName = " << antennaName << LogIO::POST ;
646  os_ << "stationName = " << stationName << LogIO::POST ;
647 
648  msAntCols.name().put( 0, antennaName ) ;
649  msAntCols.station().put( 0, stationName ) ;
650
651  os_ << "antennaPosition = " << header_.antennaposition << LogIO::POST ;
652 
653  msAntCols.position().put( 0, header_.antennaposition ) ;
654}
655
656void MSWriter::fillProcessor()
657{
658  os_ << "set up PROCESSOR subtable" << LogIO::POST ;
659 
660  // only add empty 1 row
661  MSProcessor msProc = mstable_->processor() ;
662  msProc.addRow( 1, True ) ;
663}
664
665void MSWriter::fillSource()
666{
667  os_ << "set up SOURCE subtable" << LogIO::POST ;
668 
669
670  // access to MS SOURCE subtable
671  MSSource msSrc = mstable_->source() ;
672
673  // access to MOLECULE subtable
674  STMolecules stm = table_->molecules() ;
675
676  Int srcId = 0 ;
677  Vector<Double> restFreq ;
678  Vector<String> molName ;
679  Vector<String> fMolName ;
680  //
681  // ITERATION: SRCNAME
682  //
683  Int added0 = 0 ;
684  Int current0 = msSrc.nrow() ;
685  TableIterator iter0( table_->table(), "SRCNAME" ) ;
686  while( !iter0.pastEnd() ) {
687    Table t0( iter0.table() ) ;
688
689    // get necessary information
690    ROScalarColumn<String> srcNameCol( t0, "SRCNAME" ) ;
691    String srcName = srcNameCol( 0 ) ;
692    ROArrayColumn<Double> sharedDArrRCol( t0, "SRCPROPERMOTION" ) ;
693    Vector<Double> srcPM = sharedDArrRCol( 0 ) ;
694    sharedDArrRCol.attach( t0, "SRCDIRECTION" ) ;
695    Vector<Double> srcDir = sharedDArrRCol( 0 ) ;
696    ROScalarColumn<Double> srcVelCol( t0, "SRCVELOCITY" ) ;
697    Double srcVel = srcVelCol( 0 ) ;
698
699    //
700    // ITERATION: MOLECULE_ID
701    //
702    Int added1 = 0 ;
703    Int current1 = msSrc.nrow() ;
704    TableIterator iter1( t0, "MOLECULE_ID" ) ;
705    while( !iter1.pastEnd() ) {
706      Table t1( iter1.table() ) ;
707
708      // get necessary information
709      ROScalarColumn<uInt> molIdCol( t1, "MOLECULE_ID" ) ;
710      uInt molId = molIdCol( 0 ) ;
711      stm.getEntry( restFreq, molName, fMolName, molId ) ;
712
713      //
714      // ITERATION: IFNO
715      //
716      Int added2 = 0 ;
717      Int current2 = msSrc.nrow() ;
718      TableIterator iter2( t1, "IFNO" ) ;
719      while( !iter2.pastEnd() ) {
720        Table t2( iter2.table() ) ;
721        uInt prevnr = msSrc.nrow() ;
722
723        // get necessary information
724        ROScalarColumn<uInt> ifNoCol( t2, "IFNO" ) ;
725        uInt ifno = ifNoCol( 0 ) ; // IFNO = SPECTRAL_WINDOW_ID
726        MEpoch midTimeMeas ;
727        Double interval ;
728        getValidTimeRange( midTimeMeas, interval, t2 ) ;
729
730        // add row
731        msSrc.addRow( 1, True ) ;
732
733        // fill SPECTRAL_WINDOW_ID
734        ScalarColumn<Int> sSpwIdCol( msSrc, "SPECTRAL_WINDOW_ID" ) ;
735        sSpwIdCol.put( prevnr, ifno ) ;
736
737        // fill TIME, INTERVAL
738        ScalarMeasColumn<MEpoch> sTimeMeasCol( msSrc, "TIME" ) ;
739        sTimeMeasCol.put( prevnr, midTimeMeas ) ;
740        ScalarColumn<Double> sIntervalCol( msSrc, "INTERVAL" ) ;
741        sIntervalCol.put( prevnr, interval ) ;
742
743        added2++ ;
744        iter2.next() ;
745      }
746
747      // fill NUM_LINES, REST_FREQUENCY, TRANSITION, SYSVEL
748      RefRows rows2( current2, current2+added2-1 ) ;
749      uInt numFreq = restFreq.size() ;
750      Vector<Int> numLines( added2, numFreq ) ;
751      ScalarColumn<Int> numLinesCol( msSrc, "NUM_LINES" ) ;
752      numLinesCol.putColumnCells( rows2, numLines ) ;
753      if ( numFreq != 0 ) {
754        Array<Double> rf( IPosition( 2, numFreq, added2 ) ) ;
755        Array<String> trans( IPosition( 2, numFreq, added2 ) ) ;
756        Array<Double> srcVelArr( IPosition( 2, numFreq, added2 ), srcVel ) ;
757        for ( uInt ifreq = 0 ; ifreq < numFreq ; ifreq++ ) {
758          Slicer slice( Slice(ifreq),Slice(0,added2,1) ) ;
759          rf( slice ) = restFreq[ifreq] ;
760          String transStr = fMolName[ifreq] ;
761          if ( transStr.size() == 0 ) {
762            transStr = molName[ifreq] ;
763          }
764          trans( slice ) = transStr ;
765        }
766        ArrayColumn<Double> sharedDArrCol( msSrc, "REST_FREQUENCY" ) ;
767        sharedDArrCol.putColumnCells( rows2, rf ) ;
768        sharedDArrCol.attach( msSrc, "SYSVEL" ) ;
769        sharedDArrCol.putColumnCells( rows2, srcVelArr ) ;
770        ArrayColumn<String> transCol( msSrc, "TRANSITION" ) ;
771        transCol.putColumnCells( rows2, trans ) ;
772      }
773
774      added1 += added2 ;
775      iter1.next() ;
776    }
777
778    // fill NAME, SOURCE_ID
779    RefRows rows1( current1, current1+added1-1 ) ;
780    Vector<String> nameArr( added1, srcName ) ;
781    Vector<Int> srcIdArr( added1, srcId ) ;
782    ScalarColumn<String> sNameCol( msSrc, "NAME" ) ;
783    ScalarColumn<Int> srcIdCol( msSrc, "SOURCE_ID" ) ;
784    sNameCol.putColumnCells( rows1, nameArr ) ;
785    srcIdCol.putColumnCells( rows1, srcIdArr ) ;
786
787    // fill DIRECTION, PROPER_MOTION
788    Array<Double> srcPMArr( IPosition( 2, 2, added1 ) ) ;
789    Array<Double> srcDirArr( IPosition( 2, 2, added1 ) ) ;
790    for ( uInt i = 0 ; i < 2 ; i++ ) {
791      Slicer slice( Slice(i),Slice(0,added1,1) ) ;
792      srcPMArr( slice ) = srcPM[i] ;
793      srcDirArr( slice ) = srcDir[i] ;
794    }
795    ArrayColumn<Double> sharedDArrCol( msSrc, "DIRECTION" ) ;
796    sharedDArrCol.putColumnCells( rows1, srcDirArr ) ;
797    sharedDArrCol.attach( msSrc, "PROPER_MOTION" ) ;
798    sharedDArrCol.putColumnCells( rows1, srcPMArr ) ;
799
800    // fill TIME, INTERVAL
801
802    // increment srcId if SRCNAME changed
803    srcId++ ;
804
805    added0 += added1 ;
806    iter0.next() ;
807  }
808}
809
810void MSWriter::fillWeather()
811{
812  os_ << "set up WEATHER subtable" << LogIO::POST ;
813
814  // access to MS WEATHER subtable
815  MSWeather msw = mstable_->weather() ;
816
817  // access to WEATHER subtable
818  Table stw = table_->weather().table() ;
819  uInt nrow = stw.nrow() ;
820
821  if ( nrow == 0 )
822    return ;
823
824  msw.addRow( nrow, True ) ;
825  MSWeatherColumns mswCols( msw ) ;
826
827  // ANTENNA_ID is always 0
828  Vector<Int> antIdArr( nrow, 0 ) ;
829  mswCols.antennaId().putColumn( antIdArr ) ;
830
831  // fill weather status
832  ROScalarColumn<Float> sharedFloatCol( stw, "TEMPERATURE" ) ;
833  mswCols.temperature().putColumn( sharedFloatCol ) ;
834  sharedFloatCol.attach( stw, "PRESSURE" ) ;
835  mswCols.pressure().putColumn( sharedFloatCol ) ;
836  sharedFloatCol.attach( stw, "HUMIDITY" ) ;
837  mswCols.relHumidity().putColumn( sharedFloatCol ) ;
838  sharedFloatCol.attach( stw, "WINDSPEED" ) ;
839  mswCols.windSpeed().putColumn( sharedFloatCol ) ;
840  sharedFloatCol.attach( stw, "WINDAZ" ) ;
841  mswCols.windDirection().putColumn( sharedFloatCol ) ;
842
843  // fill TIME and INTERVAL
844  MEpoch me ;
845  Double interval ;
846  Vector<Double> intervalArr( nrow, 0.0 ) ;
847  TableIterator iter( table_->table(), "WEATHER_ID" ) ;
848  while( !iter.pastEnd() ) {
849    Table tab( iter.table() ) ;
850
851    ROScalarColumn<uInt> widCol( tab, "WEATHER_ID" ) ;
852    uInt wid = widCol( 0 ) ;
853
854    getValidTimeRange( me, interval, tab ) ;
855    mswCols.timeMeas().put( wid, me ) ;
856    intervalArr[wid] = interval ;
857
858    iter.next() ;
859  }
860  mswCols.interval().putColumn( intervalArr ) ;
861}
862
863void MSWriter::fillSysCal()
864{
865  os_ << "set up SYSCAL subtable" << LogIO::POST ;
866
867  tcalIdRec_.print( cout ) ;
868
869  // access to MS SYSCAL subtable
870  MSSysCal mssc = mstable_->sysCal() ;
871
872  // access to TCAL subtable
873  STTcal stt = table_->tcal() ;
874  uInt nrow = stt.table().nrow() ;
875
876  if ( nrow == 0 )
877    return ;
878
879  nrow = tcalIdRec_.nfields() ;
880
881  MEpoch me ;
882  Double interval ;
883  String timeStr ;
884  //
885  // ITERATION: BEAMNO
886  //
887  Int added0 = 0 ;
888  Int current0 = mssc.nrow() ;
889  TableIterator iter0( table_->table(), "BEAMNO" ) ;
890  while( !iter0.pastEnd() ) {
891    Table t0( iter0.table() ) ;
892    ROScalarColumn<uInt> beamNoCol( t0, "BEAMNO" ) ;
893    uInt beamNo = beamNoCol( 0 ) ;
894    //
895    // ITERATION: IFNO
896    //
897    Int added1 = 0 ;
898    Int current1 = mssc.nrow() ;
899    TableIterator iter1( t0, "IFNO" ) ;
900    while( !iter1.pastEnd() ) {
901      Table t1( iter1.table() ) ;
902      ROScalarColumn<uInt> ifNoCol( t1, "IFNO" ) ;
903      uInt ifNo = ifNoCol( 0 ) ;
904      uInt prevnr = mssc.nrow() ;
905
906      //
907      // LOOP: TCAL_ID
908      //
909      Int added2 = 0 ;
910      Int current2 = mssc.nrow() ;
911      for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
912        Vector<uInt> ids = tcalIdRec_.asArrayuInt( irow ) ;
913        uInt npol = ids.size() ;
914        Table tsel = t1( t1.col("TCAL_ID").in(ids) ) ;
915        os_ << "nrow = " << tsel.nrow() << "@TCAL_ID " << tcalIdRec_.asArrayuInt(irow) << " beamno " << beamNo << "ifno " << ifNo << LogIO::POST ;
916        if ( tsel.nrow() != 0 ) {
917          uInt idx = current2 + added2 ;
918
919          // TIME and INTERVAL
920          mssc.addRow( 1, True ) ;
921          getValidTimeRange( me, interval, t1 ) ;
922          os_ << "me = " << me.get("s").getValue() << " interval = " << interval << LogIO::POST ;
923          ScalarMeasColumn<MEpoch> timeMeasCol( mssc, "TIME" ) ;
924          timeMeasCol.put( idx, me ) ;
925          ScalarColumn<Double> intervalCol( mssc, "INTERVAL" ) ;
926          intervalCol.put( idx, interval ) ;
927
928          // TCAL and TSYS
929          Array<Float> tcal ;
930          Array<Float> tsys ;
931          Vector<Float> dummyC ;
932          stt.getEntry( timeStr, dummyC, ids[0] ) ;
933          os_ << "dummyC[0] = " << dummyC[0] << LogIO::POST ;
934          uInt nchanC = dummyC.size() ;
935          os_ << "nchanC = " << nchanC << LogIO::POST ;
936          tcal.resize( IPosition(2,npol,nchanC) ) ;
937          IPosition shapeC( 2, 1, nchanC ) ;
938          tcal( Slicer(Slice(0),Slice(0,nchanC,1)) ) = dummyC.reform( shapeC ) ;
939          Table tsel1 = tsel( tsel.col("TCAL_ID") == ids[0] ) ;
940          ROArrayColumn<Float> tsysCol( tsel1, "TSYS" ) ;
941          Vector<Float> dummyS = tsysCol( 0 ) ;
942          os_ << "dummyS[0] = " << dummyS[0] << LogIO::POST ;
943          uInt nchanS = dummyS.size() ;
944          os_ << "nchanS = " << nchanS << LogIO::POST ;
945          IPosition shapeS( 2, 1, nchanS ) ;
946          tsys.resize( IPosition(2,npol,nchanS) ) ;
947          tsys( Slicer(Slice(0),Slice(0,nchanS,1)) ) = dummyS.reform( shapeS ) ;
948          os_ << "tsys = " << tsys << LogIO::POST ;
949          for ( uInt iid = 1 ; iid < npol ; iid++ ) {
950            // get TCAL and TSYS
951            stt.getEntry( timeStr, dummyC, ids[iid] ) ;
952            tcal( Slicer(Slice(iid),Slice(0,nchanC,1)) ) = dummyC.reform( shapeC ) ;
953            tsel1 = tsel( tsel.col("TCAL_ID") == ids[iid] ) ;
954            tsysCol.attach( tsel1, "TSYS" ) ;
955            tsys( Slicer(Slice(iid),Slice(0,nchanS,1)) ) = tsysCol( 0 ).reform( shapeS ) ;
956          }
957          os_ << "tsys = " << tsys << LogIO::POST ;
958          ArrayColumn<Float> sharedFloatArrCol ;
959          if ( tcalSpec_ ) {
960            // put TCAL_SPECTRUM
961            sharedFloatArrCol.attach( mssc, "TCAL_SPECTRUM" ) ;
962            sharedFloatArrCol.put( idx, tcal ) ;
963            // set TCAL (mean of TCAL_SPECTRUM)
964            Vector<Float> tcalMean( npol ) ;
965            for ( uInt iid = 0 ; iid < npol ; iid++ ) {
966              tcalMean[iid] = mean( tcal(Slicer(Slice(iid),Slice(0,nchanC,1))) ) ;
967            }
968            tcal.assign( tcalMean.reform(IPosition(2,npol,1)) ) ;
969          }
970          os_ << "tcal = " << tcal << LogIO::POST ;
971          // put TCAL
972          sharedFloatArrCol.attach( mssc, "TCAL" ) ;
973          sharedFloatArrCol.put( idx, tcal ) ;
974         
975          if ( tsysSpec_ ) {
976            // put TSYS_SPECTRUM
977            sharedFloatArrCol.attach( mssc, "TSYS_SPECTRUM" ) ;
978            sharedFloatArrCol.put( idx, tsys ) ;
979            // set TSYS (mean of TSYS_SPECTRUM)
980            Vector<Float> tsysMean( npol ) ;
981            for ( uInt iid = 0 ; iid < npol ; iid++ ) {
982              tsysMean[iid] = mean( tsys(Slicer(Slice(iid),Slice(0,nchanS,1))) ) ;
983            }
984            tsys.assign( tsysMean.reform(IPosition(2,npol,1)) ) ;
985          }
986          os_ << "tsys = " << tsys << LogIO::POST ;
987          // put TSYS
988          sharedFloatArrCol.attach( mssc, "TSYS" ) ;
989          sharedFloatArrCol.put( idx, tsys ) ;
990
991          added2++ ;
992        }
993      }
994
995      // SPECTRAL_WINDOW_ID
996      RefRows rows2( current2, current2+added2-1 ) ;
997      ScalarColumn<Int> spwIdCol( mssc, "SPECTRAL_WINDOW_ID" ) ;
998      Vector<Int> ifNoArr( added2, ifNo ) ;
999      spwIdCol.putColumnCells( rows2, ifNoArr ) ;
1000
1001      added1 += added2 ;
1002      iter1.next() ;
1003    }
1004   
1005    // FEED_ID
1006    RefRows rows1( current1, current1+added1-1 ) ;
1007    Vector<Int> beamNoArr( added1, beamNo ) ;
1008    ScalarColumn<Int> feedIdCol( mssc, "FEED_ID" ) ;
1009    feedIdCol.putColumnCells( rows1, beamNoArr ) ;
1010
1011    added0 += added1 ;
1012    iter0.next() ;
1013  }
1014
1015  // ANTENNA_ID
1016  Vector<Int> id( added0, 0 ) ;
1017  ScalarColumn<Int> antennaIdCol( mssc, "ANTENNA_ID" ) ;
1018  antennaIdCol.putColumn( id ) ;
1019 
1020}
1021
1022void MSWriter::addFeed( Int id )
1023{
1024  os_ << "set up FEED subtable" << LogIO::POST ;
1025
1026  // add row
1027  MSFeed msFeed = mstable_->feed() ;
1028  msFeed.addRow( 1, True ) ;
1029  Int nrow = msFeed.nrow() ;
1030
1031  MSFeedColumns msFeedCols( mstable_->feed() ) ;
1032
1033  msFeedCols.feedId().put( nrow-1, id ) ;
1034  msFeedCols.antennaId().put( nrow-1, 0 ) ;
1035}
1036
1037void MSWriter::addSpectralWindow( Int spwid, Int freqid )
1038{
1039  os_ << "set up SPECTRAL_WINDOW subtable" << LogIO::POST ;
1040 
1041  // add row
1042  MSSpectralWindow msSpw = mstable_->spectralWindow() ;
1043  while( (Int)msSpw.nrow() <= spwid ) {
1044    msSpw.addRow( 1, True ) ;
1045  }
1046 
1047  MSSpWindowColumns msSpwCols( msSpw ) ;
1048
1049  STFrequencies stf = table_->frequencies() ;
1050
1051  // MEAS_FREQ_REF
1052  msSpwCols.measFreqRef().put( spwid, stf.getFrame( True ) ) ;
1053
1054  Double refpix ;
1055  Double refval ;
1056  Double inc ;
1057  stf.getEntry( refpix, refval, inc, (uInt)freqid ) ;
1058
1059  // NUM_CHAN
1060  Int nchan = refpix * 2 ;
1061  msSpwCols.numChan().put( spwid, nchan ) ;
1062
1063  // TOTAL_BANDWIDTH
1064  Double bw = nchan * inc ;
1065  msSpwCols.totalBandwidth().put( spwid, bw ) ;
1066
1067  // REF_FREQUENCY
1068  Double refFreq = refval - refpix * inc ;
1069  msSpwCols.refFrequency().put( spwid, refFreq ) ;
1070
1071  // NET_SIDEBAND
1072  // tentative: USB->0, LSB->1
1073  Int netSideband = 0 ;
1074  if ( inc < 0 )
1075    netSideband = 1 ;
1076  msSpwCols.netSideband().put( spwid, netSideband ) ;
1077
1078  // RESOLUTION, CHAN_WIDTH, EFFECTIVE_BW
1079  Vector<Double> sharedDoubleArr( nchan, inc ) ;
1080  msSpwCols.resolution().put( spwid, sharedDoubleArr ) ;
1081  msSpwCols.chanWidth().put( spwid, sharedDoubleArr ) ;
1082  msSpwCols.effectiveBW().put( spwid, sharedDoubleArr ) ;
1083
1084  // CHAN_FREQ
1085  indgen( sharedDoubleArr, refFreq, inc ) ;
1086  msSpwCols.chanFreq().put( spwid, sharedDoubleArr ) ;
1087}
1088
1089void MSWriter::addField( Int fid, String fieldname, String srcname, Double t, Vector<Double> rate )
1090{
1091  os_ << "set up FIELD subtable" << LogIO::POST ;
1092 
1093  MSField msField = mstable_->field() ;
1094  while( (Int)msField.nrow() <= fid ) {
1095    msField.addRow( 1, True ) ;
1096  }
1097  MSFieldColumns msFieldCols( msField ) ;
1098
1099  // Access to SOURCE table
1100  MSSource msSrc = mstable_->source() ;
1101
1102  // fill target row
1103  msFieldCols.name().put( fid, fieldname ) ;
1104  msFieldCols.time().put( fid, t ) ;
1105  Int numPoly = 0 ;
1106  if ( anyNE( rate, 0.0 ) )
1107    numPoly = 1 ;
1108  msFieldCols.numPoly().put( fid, numPoly ) ;
1109  MSSourceIndex msSrcIdx( msSrc ) ;
1110  Int srcId = -1 ;
1111  Vector<Int> srcIdArr = msSrcIdx.matchSourceName( srcname ) ;
1112  if ( srcIdArr.size() != 0 ) {
1113    srcId = srcIdArr[0] ;
1114    MSSource msSrcSel = msSrc( msSrc.col("SOURCE_ID") == srcId ) ;
1115    ROMSSourceColumns msSrcCols( msSrcSel ) ;
1116    Vector<Double> srcDir = msSrcCols.direction()( 0 ) ;
1117    Array<Double> srcDirA( IPosition( 2, 2, 1+numPoly ) ) ;
1118    os_ << "srcDirA = " << srcDirA << LogIO::POST ;
1119    os_ << "sliced srcDirA = " << srcDirA( Slicer( Slice(0,2,1), Slice(0) ) ) << LogIO::POST ;
1120    srcDirA( Slicer( Slice(0,2,1), Slice(0) ) ) = srcDir.reform( IPosition(2,2,1) ) ;
1121    os_ << "srcDirA = " << srcDirA << LogIO::POST ;
1122    if ( numPoly != 0 )
1123      srcDirA( Slicer( Slice(0,2,1), Slice(1) ) ) = rate ;
1124    msFieldCols.phaseDir().put( fid, srcDirA ) ;
1125    msFieldCols.referenceDir().put( fid, srcDirA ) ;
1126    msFieldCols.delayDir().put( fid, srcDirA ) ;
1127  }
1128  msFieldCols.sourceId().put( fid, srcId ) ;
1129}
1130
1131void MSWriter::addPointing( String &name, MEpoch &me, Double &interval, Matrix<Double> &dir )
1132{
1133  os_ << "set up POINTING subtable" << LogIO::POST ;
1134 
1135  // access to POINTING subtable
1136  MSPointing msp = mstable_->pointing() ;
1137  uInt nrow = msp.nrow() ;
1138
1139  // add row
1140  msp.addRow( 1, True ) ;
1141
1142  // fill row
1143  MSPointingColumns mspCols( msp ) ;
1144  mspCols.antennaId().put( nrow, 0 ) ;
1145  mspCols.timeMeas().put( nrow, me ) ;
1146  mspCols.interval().put( nrow, interval ) ;
1147  mspCols.name().put( nrow, name ) ;
1148  mspCols.numPoly().put( nrow, 1 ) ;
1149  mspCols.timeOriginMeas().put( nrow, me ) ;
1150  mspCols.direction().put( nrow, dir ) ;
1151  mspCols.target().put( nrow, dir ) ;
1152  mspCols.tracking().put( nrow, True ) ;
1153}
1154
1155Int MSWriter::addPolarization( Vector<Int> polnos )
1156{
1157  os_ << "set up POLARIZATION subtable" << LogIO::POST ;
1158
1159  os_ << "polnos = " << polnos << LogIO::POST ;
1160  MSPolarization msPol = mstable_->polarization() ;
1161  uInt nrow = msPol.nrow() ;
1162 
1163  Vector<Int> corrType = toCorrType( polnos ) ;
1164  os_ << "corrType = " << corrType << LogIO::POST ;
1165 
1166  MSPolarizationIndex msPolIdx( msPol ) ;
1167  Vector<Int> polids = msPolIdx.matchCorrType( corrType ) ;
1168  os_ << "polids = " << polids << LogIO::POST ;
1169
1170  Int polid = -1 ;
1171
1172  if ( polids.size() == 0 ) {
1173    // add row
1174    msPol.addRow( 1, True ) ;
1175    polid = (Int)nrow ;
1176
1177    MSPolarizationColumns msPolCols( msPol ) ;
1178   
1179    // CORR_TYPE
1180    msPolCols.corrType().put( nrow, corrType ) ;
1181
1182    // NUM_CORR
1183    uInt npol = corrType.size() ;
1184    msPolCols.numCorr().put( nrow, npol ) ;
1185
1186    // CORR_PRODUCT
1187    Matrix<Int> corrProd( 2, npol, -1 ) ;
1188    if ( npol == 1 ) {
1189      corrProd = 0 ;
1190    }
1191    else if ( npol == 2 ) {
1192      corrProd.column( 0 ) = 0 ;
1193      corrProd.column( 1 ) = 1 ;
1194    }
1195    else {
1196      corrProd.column( 0 ) = 0 ;
1197      corrProd.column( 3 ) = 1 ;
1198      corrProd( 0,1 ) = 0 ;
1199      corrProd( 1,1 ) = 1 ;
1200      corrProd( 0,2 ) = 1 ;
1201      corrProd( 1,2 ) = 0 ;
1202    }
1203    msPolCols.corrProduct().put( nrow, corrProd ) ;
1204   
1205  }
1206  else {
1207    polid = polids[0] ;
1208  }
1209
1210  return polid ;
1211}
1212
1213Int MSWriter::addDataDescription( Int polid, Int spwid )
1214{
1215  os_ << "set up DATA_DESCRIPTION subtable" << LogIO::POST ;
1216
1217  MSDataDescription msDataDesc = mstable_->dataDescription() ;
1218  uInt nrow = msDataDesc.nrow() ;
1219
1220  MSDataDescIndex msDataDescIdx( msDataDesc ) ;
1221 
1222  Vector<Int> ddids = msDataDescIdx.matchSpwIdAndPolznId( spwid, polid ) ;
1223  os_ << "ddids = " << ddids << LogIO::POST ;
1224
1225  Int ddid = -1 ;
1226  if ( ddids.size() == 0 ) {
1227    msDataDesc.addRow( 1, True ) ;
1228    MSDataDescColumns msDataDescCols( msDataDesc ) ;
1229    msDataDescCols.polarizationId().put( nrow, polid ) ;
1230    msDataDescCols.spectralWindowId().put( nrow, spwid ) ;
1231    ddid = (Int)nrow ;
1232  }
1233  else {
1234    ddid = ddids[0] ;
1235  }
1236
1237  return ddid ;
1238}
1239
1240Int MSWriter::addState( Int st, Int &subscan )
1241{
1242  os_ << "set up STATE subtable" << LogIO::POST ;
1243
1244  // access to STATE subtable
1245  MSState msState = mstable_->state() ;
1246  uInt nrow = msState.nrow() ;
1247
1248  String obsMode ;
1249  Bool isSignal ;
1250  queryType( st, obsMode, isSignal ) ;
1251  os_ << "obsMode = " << obsMode << " isSignal = " << isSignal << LogIO::POST ;
1252
1253  MSState msStatSel = msState( msState.col("OBS_MODE")==obsMode
1254                               && msState.col("SIG")==isSignal
1255                               && msState.col("REF")!=isSignal
1256                               && msState.col("SUB_SCAN") == subscan ) ;
1257  uInt nrowSel = msStatSel.nrow() ;
1258
1259  Int idx = -1 ;
1260  if ( nrowSel == 0 ) {
1261    msState.addRow( 1, True ) ;
1262    ScalarColumn<String> obsModeCol( msState, "OBS_MODE" ) ;
1263    obsModeCol.put( nrow, obsMode ) ;
1264    ScalarColumn<Bool> sharedBCol( msState, "SIG" ) ;
1265    sharedBCol.put( nrow, isSignal ) ;
1266    sharedBCol.attach( msState, "REF" ) ;
1267    sharedBCol.put( nrow, !isSignal ) ;
1268    ScalarColumn<Int> subscanCol( msState, "SUB_SCAN" ) ;
1269    subscanCol.put( nrow, subscan ) ;
1270    idx = nrow ;
1271  }
1272  else {
1273    ScalarColumn<String> obsModeCol( msState, "OBS_MODE" ) ;
1274    ScalarColumn<Bool> sigCol( msState, "SIG" ) ;
1275    ScalarColumn<Bool> refCol( msState, "REF" ) ;
1276    ScalarColumn<Int> subscanCol( msState, "SUB_SCAN" ) ;
1277    for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
1278      if ( obsModeCol(irow) == obsMode
1279           && sigCol(irow) == isSignal
1280           && refCol(irow) != isSignal
1281           && subscanCol(irow) == subscan ) {
1282        idx = irow ;
1283        break ;
1284      }
1285    }
1286  }
1287  subscan++ ;
1288  return idx ;
1289}
1290
1291Vector<Int> MSWriter::toCorrType( Vector<Int> polnos )
1292{
1293  uInt npol = polnos.size() ;
1294  Vector<Int> corrType( npol, Stokes::Undefined ) ;
1295 
1296  if ( npol == 4 ) {
1297    if ( polType_ == "linear" ) {
1298      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1299        if ( polnos[ipol] == 0 )
1300          corrType[ipol] = Stokes::XX ;
1301        else if ( polnos[ipol] == 1 )
1302          corrType[ipol] = Stokes::XY ;
1303        else if ( polnos[ipol] == 2 )
1304          corrType[ipol] = Stokes::YX ;
1305        else if ( polnos[ipol] == 3 )
1306          corrType[ipol] = Stokes::YY ;
1307      }
1308    }
1309    else if ( polType_ == "circular" ) {
1310      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1311        if ( polnos[ipol] == 0 )
1312          corrType[ipol] = Stokes::RR ;
1313        else if ( polnos[ipol] == 1 )
1314          corrType[ipol] = Stokes::RL ;
1315        else if ( polnos[ipol] == 2 )
1316          corrType[ipol] = Stokes::LR ;
1317        else if ( polnos[ipol] == 3 )
1318          corrType[ipol] = Stokes::LL ;
1319      }
1320    }
1321    else if ( polType_ == "stokes" ) {
1322      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1323        if ( polnos[ipol] == 0 )
1324          corrType[ipol] = Stokes::I ;
1325        else if ( polnos[ipol] == 1 )
1326          corrType[ipol] = Stokes::Q ;
1327        else if ( polnos[ipol] == 2 )
1328          corrType[ipol] = Stokes::U ;
1329        else if ( polnos[ipol] == 3 )
1330          corrType[ipol] = Stokes::V ;
1331      }
1332    }
1333  }
1334  else if ( npol == 2 ) {
1335    if ( polType_ == "linear" ) {
1336      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1337        if ( polnos[ipol] == 0 )
1338          corrType[ipol] = Stokes::XX ;
1339        else if ( polnos[ipol] == 1 )
1340          corrType[ipol] = Stokes::YY ;
1341      }
1342    }
1343    else if ( polType_ == "circular" ) {
1344      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1345        if ( polnos[ipol] == 0 )
1346          corrType[ipol] = Stokes::RR ;
1347        else if ( polnos[ipol] == 1 )
1348          corrType[ipol] = Stokes::LL ;
1349      }
1350    }
1351    else if ( polType_ == "stokes" ) {
1352      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1353        if ( polnos[ipol] == 0 )
1354          corrType[ipol] = Stokes::I ;
1355        else if ( polnos[ipol] == 1 )
1356          corrType[ipol] = Stokes::V ;
1357      }
1358    }
1359    else if ( polType_ == "linpol" ) {
1360      for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1361        if ( polnos[ipol] == 1 )
1362          corrType[ipol] = Stokes::Plinear ;
1363        else if ( polnos[ipol] == 2 )
1364          corrType[ipol] = Stokes::Pangle ;
1365      }
1366    }
1367  }     
1368  else if ( npol == 1 ) {
1369    if ( polType_ == "linear" )
1370      corrType[0] = Stokes::XX ;
1371    else if ( polType_ == "circular" )
1372      corrType[0] = Stokes::RR ;
1373    else if ( polType_ == "stokes" )
1374      corrType[0] = Stokes::I ;
1375  }
1376
1377  return corrType ;
1378}
1379
1380void MSWriter::getValidTimeRange( MEpoch &me, Double &interval, Table &tab )
1381{
1382  ROScalarMeasColumn<MEpoch> timeMeasCol( tab, "TIME" ) ;
1383  ROScalarColumn<Double> timeCol( tab, "TIME" ) ;
1384  String refStr = timeMeasCol( 0 ).getRefString() ;
1385  Vector<Double> timeArr = timeCol.getColumn() ;
1386  MEpoch::Types meType ;
1387  MEpoch::getType( meType, refStr ) ;
1388  Unit tUnit = timeMeasCol.measDesc().getUnits()( 0 ) ;
1389  Double minTime ;
1390  Double maxTime ;
1391  minMax( minTime, maxTime, timeArr ) ;
1392  Double midTime = 0.5 * ( minTime + maxTime ) ;
1393  me = MEpoch( Quantity( midTime, tUnit ), meType ) ;
1394  interval = Quantity( maxTime-minTime, tUnit ).getValue( "s" ) ;
1395}
1396
1397void MSWriter::queryType( Int type, String &stype, Bool &b )
1398{
1399  switch ( type ) {
1400  case SrcType::PSON:
1401    stype = "POSITION_SWITCH.OBSERVE_TARGET.ON_SOURCE" ;
1402    b = True ;
1403    break ;
1404  case SrcType::PSOFF:
1405    stype = "POSITION_SWITCH.OBSERVE_TARGET.OFF_SOURCE" ;
1406    b = False ;
1407    break ;
1408  case SrcType::NOD:
1409    stype = "NOD.OBSERVE_TARGET.ON_SOURCE" ;
1410    b = True ;
1411    break ;
1412  case SrcType::FSON:
1413    stype = "FREQUENCY_SWITCH.OBSERVE_TARGET.ON_SOURCE" ;
1414    b = True ;
1415    break ;
1416  case SrcType::FSOFF:
1417    stype = "FREQUENCY_SWITCH.OBSERVE_TARGET.ON_SOURCE" ;
1418    b = False ;
1419    break ;
1420  case SrcType::SKY:
1421    stype = "UNSPECIFIED.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1422    b = False ;
1423    break ;
1424  case SrcType::HOT:
1425    stype = "UNSPECIFIED.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1426    b = False ;
1427    break ;
1428  case SrcType::WARM:
1429    stype = "UNSPECIFIED.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1430    b = False ;
1431   break ;
1432  case SrcType::COLD:
1433    stype = "UNSPECIFIED.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1434    b = False ;
1435    break ;
1436  case SrcType::PONCAL:
1437    stype = "POSITION_SWITCH.CALIBRATE_TEMPERATURE.ON_SOURCE" ;
1438    b = True ;
1439    break ;
1440  case SrcType::POFFCAL:
1441    stype = "POSITION_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1442    b = False ;
1443    break ;
1444  case SrcType::NODCAL:
1445    stype = "NOD.CALIBRATE_TEMPERATURE.ON_SOURCE" ;
1446    b = True ;
1447    break ;
1448  case SrcType::FONCAL:
1449    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.ON_SOURCE" ;
1450    b = True ;
1451    break ;
1452  case SrcType::FOFFCAL:
1453    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1454    b = False ;
1455    break ;
1456  case SrcType::FSLO:
1457    stype = "FREQUENCY_SWITCH.OBSERVE_TARGET.ON_SOURCE" ;
1458    b = True ;
1459    break ;
1460  case SrcType::FLOOFF:
1461    stype = "FREQUENCY_SWITCH.OBSERVE_TARGET.OFF_SOURCE" ;
1462    b = False ;
1463    break ;
1464  case SrcType::FLOSKY:
1465    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1466    b = False ;
1467    break ;
1468  case SrcType::FLOHOT:
1469    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1470    b = False ;
1471    break ;
1472  case SrcType::FLOWARM:
1473    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1474    b = False ;
1475    break ;
1476  case SrcType::FLOCOLD:
1477    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1478    b = False ;
1479    break ;
1480  case SrcType::FSHI:
1481    stype = "FREQUENCY_SWITCH.OBSERVE_TARGET.ON_SOURCE" ;
1482    b = True ;
1483    break ;
1484  case SrcType::FHIOFF:
1485    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1486    b = False ;
1487    break ;
1488  case SrcType::FHISKY:
1489    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1490    b = False ;
1491    break ;
1492  case SrcType::FHIHOT:
1493    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1494    b = False ;
1495    break ;
1496  case SrcType::FHIWARM:
1497    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1498    b = False ;
1499    break ;
1500  case SrcType::FHICOLD:
1501    stype = "FREQUENCY_SWITCH.CALIBRATE_TEMPERATURE.OFF_SOURCE" ;
1502    b = False ;
1503    break ;
1504  case SrcType::SIG:
1505    stype = "UNSPECIFIED.OBSERVE_TARGET.ON_SOURCE" ;
1506    b = True ;
1507    break ;
1508  case SrcType::REF:
1509    stype = "UNSPECIFIED.OBSERVE_TARGET.ON_SOURCE" ;
1510    b = False ;
1511    break ;
1512  default:
1513    stype = "UNSPECIFIED" ;
1514    b = True ;
1515    break ;
1516  }
1517}
1518}
Note: See TracBrowser for help on using the repository browser.