source: trunk/src/MSWriter.cpp@ 3110

Last change on this file since 3110 was 3106, checked in by Takeshi Nakazato, 8 years ago

New Development: No

JIRA Issue: No

Ready for Test: Yes/No

Interface Changes: Yes/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...


Check-in asap modifications from Jim regarding casacore namespace conversion.

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