source: branches/hpc34/src/MSWriter.cpp@ 2593

Last change on this file since 2593 was 2592, checked in by Takeshi Nakazato, 12 years ago

New Development: No

JIRA Issue: No

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

Not initialize POINTING row in addRow(). Instead all the columns are
filled by hand.


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