source: trunk/src/MSWriter.cpp@ 3083

Last change on this file since 3083 was 3074, checked in by Takeshi Nakazato, 9 years ago

New Development: No

JIRA Issue: No

Ready for Test: Yes

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


Make MSWriter warning free. The parameter nCols is not commented out but casted to void since it is used in debug build.

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/Tables/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 casa ;
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 Bool useFloat;
1581 String poltype;
1582 Bool addScanrate_;
1583
1584 // MS subtables
1585 Table spwtab;
1586 Table statetab;
1587 Table ddtab;
1588 Table poltab;
1589 Table fieldtab;
1590 Table feedtab;
1591 Table potab;
1592
1593 // Scantable MAIN columns
1594 ROArrayColumn<Float> spectraCol;
1595 ROArrayColumn<Double> directionCol,scanRateCol,sourceDirectionCol;
1596 ROArrayColumn<uChar> flagtraCol;
1597 ROTableColumn tcalIdCol,intervalCol,flagRowCol,timeCol,freqIdCol,
1598 sourceNameCol,fieldNameCol;
1599
1600 // MS MAIN columns
1601 RecordFieldPtr<Int> dataDescIdRF,fieldIdRF,feed1RF,feed2RF,
1602 scanNumberRF,stateIdRF;
1603 RecordFieldPtr<Double> timeRF,timeCentroidRF,intervalRF,exposureRF;
1604
1605 // MS POINTING columns
1606 TableRow porow;
1607 RecordFieldPtr<Int> poNumPolyRF ;
1608 RecordFieldPtr<Double> poTimeRF,
1609 poTimeOriginRF,
1610 poIntervalRF ;
1611 RecordFieldPtr<String> poNameRF ;
1612 RecordFieldPtr< Matrix<Double> > poDirectionRF,
1613 poTargetRF ;
1614
1615 Vector<String> stateEntry;
1616 Block<Int> ddEntry;
1617 Block<Int> feedEntry;
1618 vector< Vector<Int> > polEntry;
1619 set<uInt> processedFreqId;
1620 set<uInt> processedIFNO;
1621 map<uInt,Double> refpix;
1622 map<uInt,Double> refval;
1623 map<uInt,Double> increment;
1624 MFrequency::Types freqframe;
1625 Record srcRec;
1626 map< Int, Matrix<Int> > corrProductTemplate;
1627 Vector<Double> pointingTimeList_;
1628 Int referenceBeam_;
1629};
1630
1631class BaseMSSysCalVisitor: public TableVisitor {
1632 uInt lastRecordNo;
1633 uInt lastBeamNo, lastIfNo, lastPolNo;
1634 Double lastTime;
1635protected:
1636 const Table &table;
1637 uInt count;
1638public:
1639 BaseMSSysCalVisitor(const Table &table)
1640 : table(table)
1641 {
1642 count = 0;
1643 }
1644
1645 virtual void enterBeamNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
1646 virtual void leaveBeamNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
1647 virtual void enterIfNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
1648 virtual void leaveIfNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
1649 virtual void enterPolNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
1650 virtual void leavePolNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
1651 virtual void enterTime(const uInt /*recordNo*/, Double /*columnValue*/) { }
1652 virtual void leaveTime(const uInt /*recordNo*/, Double /*columnValue*/) { }
1653
1654 virtual Bool visitRecord(const uInt /*recordNo*/,
1655 const uInt /*beamNo*/,
1656 const uInt /*ifNo*/,
1657 const uInt /*polNo*/,
1658 const Double /*time*/) { return True ;}
1659
1660 virtual Bool visit(Bool isFirst, const uInt recordNo,
1661 const uInt nCols, void const *const colValues[]) {
1662 (void)nCols;
1663 uInt beamNo, ifNo, polNo;
1664 Double time;
1665 { // prologue
1666 uInt i = 0;
1667 {
1668 const uInt *col = (const uInt *)colValues[i++];
1669 beamNo = col[recordNo];
1670 }
1671 {
1672 const uInt *col = (const uInt *)colValues[i++];
1673 ifNo = col[recordNo];
1674 }
1675 {
1676 const Double *col = (const Double *)colValues[i++];
1677 time = col[recordNo];
1678 }
1679 {
1680 const uInt *col = (const uInt *)colValues[i++];
1681 polNo = col[recordNo];
1682 }
1683 assert(nCols == i);
1684 }
1685
1686 if (isFirst) {
1687 enterBeamNo(recordNo, beamNo);
1688 enterIfNo(recordNo, ifNo);
1689 enterTime(recordNo, time);
1690 enterPolNo(recordNo, polNo);
1691 } else {
1692 if (lastBeamNo != beamNo) {
1693 leavePolNo(lastRecordNo, lastPolNo);
1694 leaveTime(lastRecordNo, lastTime);
1695 leaveIfNo(lastRecordNo, lastIfNo);
1696 leaveBeamNo(lastRecordNo, lastBeamNo);
1697
1698 enterBeamNo(recordNo, beamNo);
1699 enterIfNo(recordNo, ifNo);
1700 enterTime(recordNo, time);
1701 enterPolNo(recordNo, polNo);
1702 } else if (lastIfNo != ifNo) {
1703 leavePolNo(lastRecordNo, lastPolNo);
1704 leaveTime(lastRecordNo, lastTime);
1705 leaveIfNo(lastRecordNo, lastIfNo);
1706
1707 enterIfNo(recordNo, ifNo);
1708 enterTime(recordNo, time);
1709 enterPolNo(recordNo, polNo);
1710 } else if (lastTime != time) {
1711 leavePolNo(lastRecordNo, lastPolNo);
1712 leaveTime(lastRecordNo, lastTime);
1713
1714 enterTime(recordNo, time);
1715 enterPolNo(recordNo, polNo);
1716 } else if (lastPolNo != polNo) {
1717 leavePolNo(lastRecordNo, lastPolNo);
1718 enterPolNo(recordNo, polNo);
1719 }
1720 }
1721 count++;
1722 Bool result = visitRecord(recordNo, beamNo, ifNo, polNo, time);
1723
1724 { // epilogue
1725 lastRecordNo = recordNo;
1726
1727 lastBeamNo = beamNo;
1728 lastIfNo = ifNo;
1729 lastPolNo = polNo;
1730 lastTime = time;
1731 }
1732 return result ;
1733 }
1734
1735 virtual void finish() {
1736 if (count > 0) {
1737 leavePolNo(lastRecordNo, lastPolNo);
1738 leaveTime(lastRecordNo, lastTime);
1739 leaveIfNo(lastRecordNo, lastIfNo);
1740 leaveBeamNo(lastRecordNo, lastBeamNo);
1741 }
1742 }
1743};
1744
1745class BaseTsysHolder
1746{
1747public:
1748 BaseTsysHolder( ROArrayColumn<Float> &tsysCol )
1749 : col( tsysCol ),
1750 nchan(0)
1751 {
1752 reset() ;
1753 }
1754 virtual ~BaseTsysHolder() {}
1755 virtual Array<Float> getTsys() = 0 ;
1756 void setNchan( uInt n ) { nchan = n ; }
1757 void appendTsys( uInt row )
1758 {
1759 Vector<Float> v = col( row ) ;
1760 uInt len = tsys.nrow() ;
1761 tsys.resize( len+1, nchan, True ) ;
1762 if ( v.nelements() == nchan )
1763 tsys.row( len ) = v ;
1764 else
1765 tsys.row( len ) = v[0] ;
1766 }
1767 void setTsys( uInt row, uInt idx )
1768 {
1769 if ( idx >= nrow() )
1770 appendTsys( row ) ;
1771 else {
1772 Vector<Float> v = col( row ) ;
1773 if ( v.nelements() == nchan )
1774 tsys.row( idx ) = v ;
1775 else
1776 tsys.row( idx ) = v[0] ;
1777 }
1778 }
1779 void reset()
1780 {
1781 tsys.resize() ;
1782 }
1783 uInt nrow() { return tsys.nrow() ; }
1784 Bool isEffective()
1785 {
1786 return ( !(tsys.empty()) && anyNE( tsys, (Float)1.0 ) ) ;
1787 }
1788 BaseTsysHolder &operator= ( const BaseTsysHolder &v )
1789 {
1790 if ( this != &v )
1791 tsys.assign( v.tsys ) ;
1792 return *this ;
1793 }
1794protected:
1795 ROArrayColumn<Float> col ;
1796 Matrix<Float> tsys ;
1797 uInt nchan ;
1798};
1799
1800class TsysHolder : public BaseTsysHolder
1801{
1802public:
1803 TsysHolder( ROArrayColumn<Float> &tsysCol )
1804 : BaseTsysHolder( tsysCol )
1805 {}
1806 virtual ~TsysHolder() {}
1807 virtual Array<Float> getTsys()
1808 {
1809 return tsys.column( 0 ) ;
1810 }
1811};
1812
1813class TsysSpectrumHolder : public BaseTsysHolder
1814{
1815public:
1816 TsysSpectrumHolder( ROArrayColumn<Float> &tsysCol )
1817 : BaseTsysHolder( tsysCol )
1818 {}
1819 virtual ~TsysSpectrumHolder() {}
1820 virtual Array<Float> getTsys()
1821 {
1822 return tsys ;
1823 }
1824};
1825
1826class BaseTcalProcessor
1827{
1828public:
1829 BaseTcalProcessor( ROArrayColumn<Float> &tcalCol )
1830 : col_( tcalCol )
1831 {}
1832 virtual ~BaseTcalProcessor() {}
1833 void setTcalId( Vector<uInt> &tcalId ) { id_.assign( tcalId ) ; }
1834 virtual Array<Float> getTcal() = 0 ;
1835protected:
1836 ROArrayColumn<Float> col_ ;
1837 Vector<uInt> id_ ;
1838};
1839
1840class TcalProcessor : public BaseTcalProcessor
1841{
1842public:
1843 TcalProcessor( ROArrayColumn<Float> &tcalCol )
1844 : BaseTcalProcessor( tcalCol )
1845 {}
1846 virtual ~TcalProcessor() {}
1847 virtual Array<Float> getTcal()
1848 {
1849 uInt npol = id_.nelements() ;
1850 Vector<Float> tcal( npol ) ;
1851 for ( uInt ipol = 0 ; ipol < npol ; ipol++ )
1852 tcal[ipol] = col_( id_[ipol] ).data()[0] ;
1853 //cout << "TcalProcessor: tcal = " << tcal << endl ;
1854 return tcal ;
1855 }
1856};
1857
1858class TcalSpectrumProcessor : public BaseTcalProcessor
1859{
1860public:
1861 TcalSpectrumProcessor( ROArrayColumn<Float> &tcalCol )
1862 : BaseTcalProcessor( tcalCol )
1863 {}
1864 virtual ~TcalSpectrumProcessor() {}
1865 virtual Array<Float> getTcal()
1866 {
1867 uInt npol = id_.nelements() ;
1868 //Vector<Float> tcal0 = col_( 0 ) ;
1869 Vector<Float> tcal0 = col_( id_[0] ) ;
1870 uInt nchan = tcal0.nelements() ;
1871 Matrix<Float> tcal( npol, nchan ) ;
1872 tcal.row( 0 ) = tcal0 ;
1873 for ( uInt ipol = 1 ; ipol < npol ; ipol++ )
1874 tcal.row( ipol ) = col_( id_[ipol] ) ;
1875 return tcal ;
1876 }
1877};
1878
1879class MSSysCalVisitor : public BaseMSSysCalVisitor
1880{
1881public:
1882 MSSysCalVisitor( const Table &from, Table &to )
1883 : BaseMSSysCalVisitor( from ),
1884 sctab( to ),
1885 rowidx( 0 ),
1886 polno_()
1887 {
1888 scrow = TableRow( sctab ) ;
1889
1890 lastTcalId.resize() ;
1891 theTcalId.resize() ;
1892 startTime = 0.0 ;
1893 endTime = 0.0 ;
1894
1895 const TableRecord &keys = table.keywordSet() ;
1896 Table tcalTable = keys.asTable( "TCAL" ) ;
1897 tcalCol.attach( tcalTable, "TCAL" ) ;
1898 tsysCol.attach( table, "TSYS" ) ;
1899 tcalIdCol.attach( table, "TCAL_ID" ) ;
1900 intervalCol.attach( table, "INTERVAL" ) ;
1901 effectiveTcal.resize( tcalTable.nrow() ) ;
1902 for ( uInt irow = 0 ; irow < tcalTable.nrow() ; irow++ ) {
1903 if ( allEQ( tcalCol( irow ), (Float)1.0 ) )
1904 effectiveTcal[irow] = False ;
1905 else
1906 effectiveTcal[irow] = True ;
1907 }
1908
1909 TableRecord &r = scrow.record() ;
1910 RecordFieldPtr<Int> antennaIdRF( r, "ANTENNA_ID" ) ;
1911 *antennaIdRF = 0 ;
1912 feedIdRF.attachToRecord( r, "FEED_ID" ) ;
1913 specWinIdRF.attachToRecord( r, "SPECTRAL_WINDOW_ID" ) ;
1914 timeRF.attachToRecord( r, "TIME" ) ;
1915 intervalRF.attachToRecord( r, "INTERVAL" ) ;
1916 if ( r.isDefined( "TCAL" ) ) {
1917 tcalRF.attachToRecord( r, "TCAL" ) ;
1918 tcalProcessor = new TcalProcessor( tcalCol ) ;
1919 }
1920 else if ( r.isDefined( "TCAL_SPECTRUM" ) ) {
1921 tcalRF.attachToRecord( r, "TCAL_SPECTRUM" ) ;
1922 tcalProcessor = new TcalSpectrumProcessor( tcalCol ) ;
1923 }
1924 if ( r.isDefined( "TSYS" ) ) {
1925 tsysRF.attachToRecord( r, "TSYS" ) ;
1926 theTsys = new TsysHolder( tsysCol ) ;
1927 lastTsys = new TsysHolder( tsysCol ) ;
1928 }
1929 else {
1930 tsysRF.attachToRecord( r, "TSYS_SPECTRUM" ) ;
1931 theTsys = new TsysSpectrumHolder( tsysCol ) ;
1932 lastTsys = new TsysSpectrumHolder( tsysCol ) ;
1933 }
1934
1935 }
1936
1937 virtual void enterBeamNo(const uInt /*recordNo*/, uInt columnValue)
1938 {
1939 *feedIdRF = (Int)columnValue ;
1940 }
1941 virtual void leaveBeamNo(const uInt /*recordNo*/, uInt /*columnValue*/)
1942 {
1943 }
1944 virtual void enterIfNo(const uInt recordNo, uInt columnValue)
1945 {
1946 //cout << "enterIfNo" << endl ;
1947 ROArrayColumn<Float> sp( table, "SPECTRA" ) ;
1948 uInt nchan = sp( recordNo ).nelements() ;
1949 theTsys->setNchan( nchan ) ;
1950 lastTsys->setNchan( nchan ) ;
1951
1952 *specWinIdRF = (Int)columnValue ;
1953 }
1954 virtual void leaveIfNo(const uInt /*recordNo*/, uInt /*columnValue*/)
1955 {
1956 //cout << "leaveIfNo" << endl ;
1957 post() ;
1958 reset(true);
1959 startTime = 0.0 ;
1960 endTime = 0.0 ;
1961 }
1962 virtual void enterTime(const uInt recordNo, Double columnValue)
1963 {
1964 //cout << "enterTime" << endl ;
1965 interval = intervalCol.asdouble( recordNo ) ;
1966 // start time and end time
1967 if ( startTime == 0.0 ) {
1968 startTime = columnValue * 86400.0 - 0.5 * interval ;
1969 endTime = columnValue * 86400.0 + 0.5 * interval ;
1970 }
1971 }
1972 virtual void leaveTime(const uInt /*recordNo*/, Double columnValue)
1973 {
1974 //cout << "leaveTime" << endl ;
1975 if ( isUpdated() ) {
1976 post() ;
1977 *lastTsys = *theTsys ;
1978 lastTcalId = theTcalId ;
1979 reset(false);
1980 startTime = columnValue * 86400.0 - 0.5 * interval ;
1981 endTime = columnValue * 86400.0 + 0.5 * interval ;
1982 }
1983 else {
1984 endTime = columnValue * 86400.0 + 0.5 * interval ;
1985 }
1986 }
1987 virtual void enterPolNo(const uInt recordNo, uInt columnValue)
1988 {
1989 //cout << "enterPolNo" << endl ;
1990 Vector<Float> tsys = tsysCol( recordNo ) ;
1991 uInt tcalId = tcalIdCol.asuInt( recordNo ) ;
1992 polno_.insert( columnValue ) ;
1993 uInt numPol = polno_.size() ;
1994 if ( lastTsys->nrow() < numPol )
1995 lastTsys->appendTsys( recordNo ) ;
1996 if ( lastTcalId.nelements() <= numPol )
1997 appendTcalId( lastTcalId, tcalId, numPol-1 ) ;
1998 if ( theTsys->nrow() < numPol )
1999 theTsys->appendTsys( recordNo ) ;
2000 else {
2001 theTsys->setTsys( recordNo, numPol-1 ) ;
2002 }
2003 if ( theTcalId.nelements() < numPol )
2004 appendTcalId( theTcalId, tcalId, numPol-1 ) ;
2005 else
2006 setTcalId( theTcalId, tcalId, numPol-1 ) ;
2007 }
2008 virtual void leavePolNo( const uInt /*recordNo*/, uInt /*columnValue*/ )
2009 {
2010 }
2011
2012private:
2013 void reset(bool completely)
2014 {
2015 if (completely) {
2016 lastTsys->reset() ;
2017 lastTcalId.resize() ;
2018 }
2019 theTsys->reset() ;
2020 theTcalId.resize() ;
2021 polno_.clear();
2022 }
2023 void appendTcalId( Vector<uInt> &v, uInt &elem, uInt polId )
2024 {
2025 v.resize( polId+1, True ) ;
2026 v[polId] = elem ;
2027 }
2028 void setTcalId( Vector<uInt> &v, uInt &elem, uInt polId )
2029 {
2030 v[polId] = elem ;
2031 }
2032 void post()
2033 {
2034 // check if given Tcal and Tsys is effective
2035 Bool isEffective = False ;
2036 for ( uInt ipol = 0 ; ipol < lastTcalId.nelements() ; ipol++ ) {
2037 if ( effectiveTcal[lastTcalId[ipol]] ) {
2038 isEffective = True ;
2039 break ;
2040 }
2041 }
2042 if ( !isEffective ) {
2043 if ( !(lastTsys->isEffective()) )
2044 return ;
2045 }
2046
2047 //cout << " interval: " << (endTime-startTime) << " lastTcalId = " << lastTcalId << endl ;
2048 Double midTime = 0.5 * ( startTime + endTime ) ;
2049 Double interval = endTime - startTime ;
2050 *timeRF = midTime ;
2051 *intervalRF = interval ;
2052 tcalProcessor->setTcalId( lastTcalId ) ;
2053 Array<Float> tcal = tcalProcessor->getTcal() ;
2054 Array<Float> tsys = lastTsys->getTsys() ;
2055 tcalRF.define( tcal ) ;
2056 tsysRF.define( tsys ) ;
2057 sctab.addRow( 1, True ) ;
2058 scrow.put( rowidx ) ;
2059 rowidx++ ;
2060 }
2061
2062 Bool isUpdated()
2063 {
2064 Bool ret = (anyNE( theTcalId, lastTcalId ) || anyNE( theTsys->getTsys(), lastTsys->getTsys() )) ;
2065 return ret ;
2066 }
2067
2068 Table &sctab;
2069 TableRow scrow;
2070 uInt rowidx;
2071
2072 Double startTime,endTime,interval;
2073
2074 CountedPtr<BaseTsysHolder> lastTsys,theTsys;
2075 Vector<uInt> lastTcalId,theTcalId;
2076 set<uInt> polno_;
2077 CountedPtr<BaseTcalProcessor> tcalProcessor ;
2078 Vector<Bool> effectiveTcal;
2079
2080 RecordFieldPtr<Int> feedIdRF,specWinIdRF;
2081 RecordFieldPtr<Double> timeRF,intervalRF;
2082 RecordFieldPtr< Array<Float> > tcalRF,tsysRF;
2083
2084 ROArrayColumn<Float> tsysCol,tcalCol;
2085 ROTableColumn tcalIdCol,intervalCol;
2086};
2087
2088MSWriter::MSWriter(CountedPtr<Scantable> stable)
2089 : table_(stable),
2090 mstable_(NULL),
2091 isWeather_(False),
2092 tcalSpec_(False),
2093 tsysSpec_(False),
2094 ptTabName_("")
2095{
2096 os_ = LogIO() ;
2097 os_.origin( LogOrigin( "MSWriter", "MSWriter()", WHERE ) ) ;
2098// os_ << "MSWriter::MSWriter()" << LogIO::POST ;
2099
2100 // initialize writer
2101 init() ;
2102}
2103
2104MSWriter::~MSWriter()
2105{
2106 os_.origin( LogOrigin( "MSWriter", "~MSWriter()", WHERE ) ) ;
2107// os_ << "MSWriter::~MSWriter()" << LogIO::POST ;
2108
2109 if ( mstable_ != 0 )
2110 delete mstable_ ;
2111}
2112
2113bool MSWriter::write(const string& filename, const Record& rec)
2114{
2115 os_.origin( LogOrigin( "MSWriter", "write()", WHERE ) ) ;
2116 //double startSec = mathutil::gettimeofday_sec() ;
2117 //os_ << "start MSWriter::write() startSec=" << startSec << LogIO::POST ;
2118
2119 filename_ = filename ;
2120
2121 // parsing MS options
2122 Bool overwrite = False ;
2123 if ( rec.isDefined( "ms" ) ) {
2124 Record msrec = rec.asRecord( "ms" ) ;
2125 if ( msrec.isDefined( "overwrite" ) ) {
2126 overwrite = msrec.asBool( "overwrite" ) ;
2127 }
2128 }
2129
2130 os_ << "Parsing MS options" << endl ;
2131 os_ << " overwrite = " << overwrite << LogIO::POST ;
2132
2133 File file( filename_ ) ;
2134 if ( file.exists() ) {
2135 if ( overwrite ) {
2136 os_ << filename_ << " exists. Overwrite existing data... " << LogIO::POST ;
2137 if ( file.isRegular() ) RegularFile(file).remove() ;
2138 else if ( file.isDirectory() ) Directory(file).removeRecursive() ;
2139 else SymLink(file).remove() ;
2140 }
2141 else {
2142 os_ << LogIO::SEVERE << "ERROR: " << filename_ << " exists..." << LogIO::POST ;
2143 return False ;
2144 }
2145 }
2146
2147 // set up MS
2148 setupMS() ;
2149
2150 // subtables
2151 // OBSERVATION
2152 fillObservation() ;
2153
2154 // ANTENNA
2155 fillAntenna() ;
2156
2157 // PROCESSOR
2158 fillProcessor() ;
2159
2160 // SOURCE
2161 fillSource() ;
2162
2163 // WEATHER
2164 if ( isWeather_ )
2165 fillWeather() ;
2166
2167 // SYSCAL
2168 fillSysCal() ;
2169
2170 /***
2171 * Start iteration using TableVisitor
2172 ***/
2173 {
2174 static const char *cols[] = {
2175 "FIELDNAME", "BEAMNO", "SCANNO", "IFNO", "SRCTYPE", "CYCLENO", "TIME",
2176 "POLNO",
2177 NULL
2178 };
2179 static const TypeManagerImpl<uInt> tmUInt;
2180 static const TypeManagerImpl<Int> tmInt;
2181 static const TypeManagerImpl<Double> tmDouble;
2182 static const TypeManagerImpl<String> tmString;
2183 static const TypeManager *const tms[] = {
2184 &tmString, &tmUInt, &tmUInt, &tmUInt, &tmInt, &tmUInt, &tmDouble, &tmUInt, NULL
2185 };
2186 //double t0 = mathutil::gettimeofday_sec() ;
2187 MSWriterVisitor myVisitor(table_->table(),*mstable_);
2188 //double t1 = mathutil::gettimeofday_sec() ;
2189 //cout << "MSWriterVisitor(): elapsed time " << t1-t0 << " sec" << endl ;
2190 String dataColName = "FLOAT_DATA" ;
2191 if ( useData_ )
2192 dataColName = "DATA" ;
2193 myVisitor.dataColumnName( dataColName ) ;
2194 myVisitor.pointingTableName( ptTabName_ ) ;
2195 myVisitor.setSourceRecord( srcRec_ ) ;
2196 //double t2 = mathutil::gettimeofday_sec() ;
2197 traverseTable(table_->table(), cols, tms, &myVisitor);
2198 //double t3 = mathutil::gettimeofday_sec() ;
2199 //cout << "traverseTable(): elapsed time " << t3-t2 << " sec" << endl ;
2200 }
2201 /***
2202 * End iteration using TableVisitor
2203 ***/
2204
2205 // ASDM tables
2206 const TableRecord &stKeys = table_->table().keywordSet() ;
2207 TableRecord &msKeys = mstable_->rwKeywordSet() ;
2208 uInt nfields = stKeys.nfields() ;
2209 for ( uInt ifield = 0 ; ifield < nfields ; ifield++ ) {
2210 String kname = stKeys.name( ifield ) ;
2211 if ( kname.find( "ASDM" ) != String::npos ) {
2212 String asdmpath = stKeys.asString( ifield ) ;
2213 os_ << "found ASDM table: " << asdmpath << LogIO::POST ;
2214 if ( Table::isReadable( asdmpath ) ) {
2215 Table newAsdmTab( asdmpath, Table::Old ) ;
2216 newAsdmTab.copy( filename_+"/"+kname, Table::New ) ;
2217 os_ << "add subtable: " << kname << LogIO::POST ;
2218 msKeys.defineTable( kname, Table( filename_+"/"+kname, Table::Old ) ) ;
2219 }
2220 }
2221 }
2222
2223 // replace POINTING table with original one if exists
2224 if ( ptTabName_ != "" ) {
2225 delete mstable_ ;
2226 mstable_ = 0 ;
2227 Table newPtTab( ptTabName_, Table::Old ) ;
2228 newPtTab.copy( filename_+"/POINTING", Table::New ) ;
2229 }
2230
2231 //double endSec = mathutil::gettimeofday_sec() ;
2232 //os_ << "end MSWriter::write() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2233
2234 os_ << "Exported data as MS" << LogIO::POST ;
2235
2236 return True ;
2237}
2238
2239void MSWriter::init()
2240{
2241// os_.origin( LogOrigin( "MSWriter", "init()", WHERE ) ) ;
2242// double startSec = mathutil::gettimeofday_sec() ;
2243// os_ << "start MSWriter::init() startSec=" << startSec << LogIO::POST ;
2244
2245 // access to scantable
2246 header_ = table_->getHeader() ;
2247
2248 // FLOAT_DATA? or DATA?
2249 if ( header_.npol > 2 ) {
2250 useFloatData_ = False ;
2251 useData_ = True ;
2252 }
2253 else {
2254 useFloatData_ = True ;
2255 useData_ = False ;
2256 }
2257
2258 // polarization type
2259 polType_ = header_.poltype ;
2260 if ( polType_ == "" )
2261 polType_ = "stokes" ;
2262 else if ( polType_.find( "linear" ) != String::npos )
2263 polType_ = "linear" ;
2264 else if ( polType_.find( "circular" ) != String::npos )
2265 polType_ = "circular" ;
2266 else if ( polType_.find( "stokes" ) != String::npos )
2267 polType_ = "stokes" ;
2268 else if ( polType_.find( "linpol" ) != String::npos )
2269 polType_ = "linpol" ;
2270 else
2271 polType_ = "notype" ;
2272
2273 // Check if some subtables are exists
2274 Bool isTcal = False ;
2275 if ( table_->tcal().table().nrow() != 0 ) {
2276 ROTableColumn col( table_->tcal().table(), "TCAL" ) ;
2277 if ( col.isDefined( 0 ) ) {
2278 os_ << "TCAL table exists: nrow=" << table_->tcal().table().nrow() << LogIO::POST ;
2279 isTcal = True ;
2280 }
2281 else {
2282 os_ << "No TCAL rows" << LogIO::POST ;
2283 }
2284 }
2285 else {
2286 os_ << "No TCAL rows" << LogIO::POST ;
2287 }
2288 if ( table_->weather().table().nrow() != 0 ) {
2289 ROTableColumn col( table_->weather().table(), "TEMPERATURE" ) ;
2290 if ( col.isDefined( 0 ) ) {
2291 os_ << "WEATHER table exists: nrow=" << table_->weather().table().nrow() << LogIO::POST ;
2292 isWeather_ =True ;
2293 }
2294 else {
2295 os_ << "No WEATHER rows" << LogIO::POST ;
2296 }
2297 }
2298 else {
2299 os_ << "No WEATHER rows" << LogIO::POST ;
2300 }
2301
2302 // Are TCAL_SPECTRUM and TSYS_SPECTRUM necessary?
2303 if ( header_.nchan != 1 ) {
2304 if ( isTcal ) {
2305 // examine TCAL subtable
2306 Table tcaltab = table_->tcal().table() ;
2307 ROArrayColumn<Float> tcalCol( tcaltab, "TCAL" ) ;
2308 for ( uInt irow = 0 ; irow < tcaltab.nrow() ; irow++ ) {
2309 if ( tcalCol( irow ).size() != 1 )
2310 tcalSpec_ = True ;
2311 }
2312 }
2313 // examine spectral data
2314 TableIterator iter0( table_->table(), "IFNO" ) ;
2315 while( !iter0.pastEnd() ) {
2316 Table t0( iter0.table() ) ;
2317 ROArrayColumn<Float> sharedFloatArrCol( t0, "SPECTRA" ) ;
2318 uInt len = sharedFloatArrCol( 0 ).size() ;
2319 if ( len != 1 ) {
2320 sharedFloatArrCol.attach( t0, "TSYS" ) ;
2321 if ( sharedFloatArrCol( 0 ).size() != 1 )
2322 tsysSpec_ = True ;
2323 }
2324 iter0.next() ;
2325 }
2326 }
2327
2328 // check if reference for POINTING table exists
2329 const TableRecord &rec = table_->table().keywordSet() ;
2330 if ( rec.isDefined( "POINTING" ) ) {
2331 ptTabName_ = rec.asString( "POINTING" ) ;
2332 if ( !Table::isReadable( ptTabName_ ) ) {
2333 ptTabName_ = "" ;
2334 }
2335 }
2336
2337// double endSec = mathutil::gettimeofday_sec() ;
2338// os_ << "end MSWriter::init() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2339}
2340
2341void MSWriter::setupMS()
2342{
2343// os_.origin( LogOrigin( "MSWriter", "setupMS()", WHERE ) ) ;
2344// double startSec = mathutil::gettimeofday_sec() ;
2345// os_ << "start MSWriter::setupMS() startSec=" << startSec << LogIO::POST ;
2346
2347 String dunit = table_->getHeader().fluxunit ;
2348
2349 TableDesc msDesc = MeasurementSet::requiredTableDesc() ;
2350 if ( useFloatData_ )
2351 MeasurementSet::addColumnToDesc( msDesc, MSMainEnums::FLOAT_DATA, 2 ) ;
2352 else if ( useData_ )
2353 MeasurementSet::addColumnToDesc( msDesc, MSMainEnums::DATA, 2 ) ;
2354
2355 SetupNewTable newtab( filename_, msDesc, Table::New ) ;
2356
2357 mstable_ = new MeasurementSet( newtab ) ;
2358
2359 TableColumn col ;
2360 if ( useFloatData_ )
2361 col.attach( *mstable_, "FLOAT_DATA" ) ;
2362 else if ( useData_ )
2363 col.attach( *mstable_, "DATA" ) ;
2364 col.rwKeywordSet().define( "UNIT", dunit ) ;
2365
2366 // create subtables
2367 TableDesc antennaDesc = MSAntenna::requiredTableDesc() ;
2368 SetupNewTable antennaTab( mstable_->antennaTableName(), antennaDesc, Table::New ) ;
2369 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::ANTENNA ), Table( antennaTab ) ) ;
2370
2371 TableDesc dataDescDesc = MSDataDescription::requiredTableDesc() ;
2372 SetupNewTable dataDescTab( mstable_->dataDescriptionTableName(), dataDescDesc, Table::New ) ;
2373 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::DATA_DESCRIPTION ), Table( dataDescTab ) ) ;
2374
2375 TableDesc dopplerDesc = MSDoppler::requiredTableDesc() ;
2376 SetupNewTable dopplerTab( mstable_->dopplerTableName(), dopplerDesc, Table::New ) ;
2377 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::DOPPLER ), Table( dopplerTab ) ) ;
2378
2379 TableDesc feedDesc = MSFeed::requiredTableDesc() ;
2380 SetupNewTable feedTab( mstable_->feedTableName(), feedDesc, Table::New ) ;
2381 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FEED ), Table( feedTab ) ) ;
2382
2383 TableDesc fieldDesc = MSField::requiredTableDesc() ;
2384 SetupNewTable fieldTab( mstable_->fieldTableName(), fieldDesc, Table::New ) ;
2385 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FIELD ), Table( fieldTab ) ) ;
2386
2387 TableDesc flagCmdDesc = MSFlagCmd::requiredTableDesc() ;
2388 SetupNewTable flagCmdTab( mstable_->flagCmdTableName(), flagCmdDesc, Table::New ) ;
2389 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FLAG_CMD ), Table( flagCmdTab ) ) ;
2390
2391 TableDesc freqOffsetDesc = MSFreqOffset::requiredTableDesc() ;
2392 SetupNewTable freqOffsetTab( mstable_->freqOffsetTableName(), freqOffsetDesc, Table::New ) ;
2393 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FREQ_OFFSET ), Table( freqOffsetTab ) ) ;
2394
2395 TableDesc historyDesc = MSHistory::requiredTableDesc() ;
2396 SetupNewTable historyTab( mstable_->historyTableName(), historyDesc, Table::New ) ;
2397 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::HISTORY ), Table( historyTab ) ) ;
2398
2399 TableDesc observationDesc = MSObservation::requiredTableDesc() ;
2400 SetupNewTable observationTab( mstable_->observationTableName(), observationDesc, Table::New ) ;
2401 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::OBSERVATION ), Table( observationTab ) ) ;
2402
2403 TableDesc pointingDesc = MSPointing::requiredTableDesc() ;
2404 SetupNewTable pointingTab( mstable_->pointingTableName(), pointingDesc, Table::New ) ;
2405 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::POINTING ), Table( pointingTab ) ) ;
2406
2407 TableDesc polarizationDesc = MSPolarization::requiredTableDesc() ;
2408 SetupNewTable polarizationTab( mstable_->polarizationTableName(), polarizationDesc, Table::New ) ;
2409 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::POLARIZATION ), Table( polarizationTab ) ) ;
2410
2411 TableDesc processorDesc = MSProcessor::requiredTableDesc() ;
2412 SetupNewTable processorTab( mstable_->processorTableName(), processorDesc, Table::New ) ;
2413 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::PROCESSOR ), Table( processorTab ) ) ;
2414
2415 TableDesc sourceDesc = MSSource::requiredTableDesc() ;
2416 MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::TRANSITION, 1 ) ;
2417 MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::REST_FREQUENCY, 1 ) ;
2418 MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::SYSVEL, 1 ) ;
2419 SetupNewTable sourceTab( mstable_->sourceTableName(), sourceDesc, Table::New ) ;
2420 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SOURCE ), Table( sourceTab ) ) ;
2421
2422 TableDesc spwDesc = MSSpectralWindow::requiredTableDesc() ;
2423 SetupNewTable spwTab( mstable_->spectralWindowTableName(), spwDesc, Table::New ) ;
2424 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SPECTRAL_WINDOW ), Table( spwTab ) ) ;
2425
2426 TableDesc stateDesc = MSState::requiredTableDesc() ;
2427 SetupNewTable stateTab( mstable_->stateTableName(), stateDesc, Table::New ) ;
2428 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::STATE ), Table( stateTab ) ) ;
2429
2430 TableDesc sysCalDesc = MSSysCal::requiredTableDesc() ;
2431 if ( tcalSpec_ )
2432 MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TCAL_SPECTRUM, 2 ) ;
2433 else
2434 MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TCAL, 1 ) ;
2435 if ( tsysSpec_ )
2436 MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TSYS_SPECTRUM, 2 ) ;
2437 else
2438 MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TSYS, 1 ) ;
2439 SetupNewTable sysCalTab( mstable_->sysCalTableName(), sysCalDesc, Table::New ) ;
2440 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SYSCAL ), Table( sysCalTab ) ) ;
2441
2442 TableDesc weatherDesc = MSWeather::requiredTableDesc() ;
2443 MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::TEMPERATURE ) ;
2444 MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::PRESSURE ) ;
2445 MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::REL_HUMIDITY ) ;
2446 MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::WIND_SPEED ) ;
2447 MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::WIND_DIRECTION ) ;
2448 SetupNewTable weatherTab( mstable_->weatherTableName(), weatherDesc, Table::New ) ;
2449 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::WEATHER ), Table( weatherTab ) ) ;
2450
2451 mstable_->initRefs() ;
2452
2453// double endSec = mathutil::gettimeofday_sec() ;
2454// os_ << "end MSWriter::setupMS() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2455}
2456
2457void MSWriter::fillObservation()
2458{
2459 //double startSec = mathutil::gettimeofday_sec() ;
2460 //os_ << "start MSWriter::fillObservation() startSec=" << startSec << LogIO::POST ;
2461
2462 // only 1 row
2463 mstable_->observation().addRow( 1, True ) ;
2464 MSObservationColumns msObsCols( mstable_->observation() ) ;
2465 msObsCols.observer().put( 0, header_.observer ) ;
2466 // tentatively put antennaname (from ANTENNA subtable)
2467 String hAntennaName = header_.antennaname ;
2468 String::size_type pos = hAntennaName.find( "//" ) ;
2469 String telescopeName ;
2470 if ( pos != String::npos ) {
2471 telescopeName = hAntennaName.substr( 0, pos ) ;
2472 }
2473 else {
2474 pos = hAntennaName.find( "@" ) ;
2475 telescopeName = hAntennaName.substr( 0, pos ) ;
2476 }
2477// os_ << "telescopeName = " << telescopeName << LogIO::POST ;
2478 msObsCols.telescopeName().put( 0, telescopeName ) ;
2479 msObsCols.project().put( 0, header_.project ) ;
2480 //ScalarMeasColumn<MEpoch> timeCol( table_->table().sort("TIME"), "TIME" ) ;
2481 Table sortedtable = table_->table().sort("TIME") ;
2482 ScalarMeasColumn<MEpoch> timeCol( sortedtable, "TIME" ) ;
2483 Vector<MEpoch> trange( 2 ) ;
2484 trange[0] = timeCol( 0 ) ;
2485 trange[1] = timeCol( table_->nrow()-1 ) ;
2486 msObsCols.timeRangeMeas().put( 0, trange ) ;
2487
2488 //double endSec = mathutil::gettimeofday_sec() ;
2489 //os_ << "end MSWriter::fillObservation() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2490}
2491
2492void MSWriter::antennaProperty( String &name, String &m, String &t, Double &d )
2493{
2494 name.upcase() ;
2495
2496 m = "ALT-AZ" ;
2497 t = "GROUND-BASED" ;
2498 if ( name.matches( Regex( "DV[0-9]+$" ) )
2499 || name.matches( Regex( "DA[0-9]+$" ) )
2500 || name.matches( Regex( "PM[0-9]+$" ) ) )
2501 d = 12.0 ;
2502 else if ( name.matches( Regex( "CM[0-9]+$" ) ) )
2503 d = 7.0 ;
2504 else if ( name.contains( "GBT" ) )
2505 d = 104.9 ;
2506 else if ( name.contains( "MOPRA" ) )
2507 d = 22.0 ;
2508 else if ( name.contains( "PKS" ) || name.contains( "PARKS" ) )
2509 d = 64.0 ;
2510 else if ( name.contains( "TIDBINBILLA" ) )
2511 d = 70.0 ;
2512 else if ( name.contains( "CEDUNA" ) )
2513 d = 30.0 ;
2514 else if ( name.contains( "HOBART" ) )
2515 d = 26.0 ;
2516 else if ( name.contains( "APEX" ) )
2517 d = 12.0 ;
2518 else if ( name.contains( "ASTE" ) )
2519 d = 10.0 ;
2520 else if ( name.contains( "NRO" ) )
2521 d = 45.0 ;
2522 else
2523 d = 1.0 ;
2524}
2525
2526void MSWriter::fillAntenna()
2527{
2528 //double startSec = mathutil::gettimeofday_sec() ;
2529 //os_ << "start MSWriter::fillAntenna() startSec=" << startSec << LogIO::POST ;
2530
2531 // only 1 row
2532 Table anttab = mstable_->antenna() ;
2533 anttab.addRow( 1, True ) ;
2534
2535 Table &table = table_->table() ;
2536 const TableRecord &keys = table.keywordSet() ;
2537 String hAntName = keys.asString( "AntennaName" ) ;
2538 String::size_type pos = hAntName.find( "//" ) ;
2539 String antennaName ;
2540 String stationName ;
2541 if ( pos != String::npos ) {
2542 stationName = hAntName.substr( 0, pos ) ;
2543 hAntName = hAntName.substr( pos+2 ) ;
2544 }
2545 pos = hAntName.find( "@" ) ;
2546 if ( pos != String::npos ) {
2547 antennaName = hAntName.substr( 0, pos ) ;
2548 stationName = hAntName.substr( pos+1 ) ;
2549 }
2550 else {
2551 antennaName = hAntName ;
2552 }
2553 Vector<Double> antpos = keys.asArrayDouble( "AntennaPosition" ) ;
2554
2555 String mount, atype ;
2556 Double diameter ;
2557 antennaProperty( antennaName, mount, atype, diameter ) ;
2558
2559 TableRow tr( anttab ) ;
2560 TableRecord &r = tr.record() ;
2561 RecordFieldPtr<String> nameRF( r, "NAME" ) ;
2562 RecordFieldPtr<String> stationRF( r, "STATION" ) ;
2563 RecordFieldPtr<String> mountRF( r, "MOUNT" ) ;
2564 RecordFieldPtr<String> typeRF( r, "TYPE" ) ;
2565 RecordFieldPtr<Double> dishDiameterRF( r, "DISH_DIAMETER" ) ;
2566 RecordFieldPtr< Vector<Double> > positionRF( r, "POSITION" ) ;
2567 *nameRF = antennaName ;
2568 *mountRF = mount ;
2569 *typeRF = atype ;
2570 *dishDiameterRF = diameter ;
2571 *positionRF = antpos ;
2572 *stationRF = stationName ;
2573
2574 tr.put( 0 ) ;
2575
2576 //double endSec = mathutil::gettimeofday_sec() ;
2577 //os_ << "end MSWriter::fillAntenna() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2578}
2579
2580void MSWriter::fillProcessor()
2581{
2582// double startSec = mathutil::gettimeofday_sec() ;
2583// os_ << "start MSWriter::fillProcessor() startSec=" << startSec << LogIO::POST ;
2584
2585 // only add empty 1 row
2586 MSProcessor msProc = mstable_->processor() ;
2587 msProc.addRow( 1, True ) ;
2588
2589// double endSec = mathutil::gettimeofday_sec() ;
2590// os_ << "end MSWriter::fillProcessor() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2591}
2592
2593void MSWriter::fillSource()
2594{
2595// double startSec = mathutil::gettimeofday_sec() ;
2596// os_ << "start MSWriter::fillSource() startSec=" << startSec << LogIO::POST ;
2597
2598 // access to MS SOURCE subtable
2599 MSSource msSrc = mstable_->source() ;
2600
2601 // access to MOLECULE subtable
2602 STMolecules stm = table_->molecules() ;
2603
2604 Int srcId = 0 ;
2605
2606 // row based
2607 TableRow row( msSrc ) ;
2608 TableRecord &rec = row.record() ;
2609 RecordFieldPtr<Int> srcidRF( rec, "SOURCE_ID" ) ;
2610 RecordFieldPtr<String> nameRF( rec, "NAME" ) ;
2611 RecordFieldPtr< Array<Double> > srcpmRF( rec, "PROPER_MOTION" ) ;
2612 RecordFieldPtr< Array<Double> > srcdirRF( rec, "DIRECTION" ) ;
2613 RecordFieldPtr<Int> numlineRF( rec, "NUM_LINES" ) ;
2614 RecordFieldPtr< Array<Double> > restfreqRF( rec, "REST_FREQUENCY" ) ;
2615 RecordFieldPtr< Array<Double> > sysvelRF( rec, "SYSVEL" ) ;
2616 RecordFieldPtr< Array<String> > transitionRF( rec, "TRANSITION" ) ;
2617 RecordFieldPtr<Double> timeRF( rec, "TIME" ) ;
2618 RecordFieldPtr<Double> intervalRF( rec, "INTERVAL" ) ;
2619 RecordFieldPtr<Int> spwidRF( rec, "SPECTRAL_WINDOW_ID" ) ;
2620
2621 //
2622 // ITERATION: SRCNAME
2623 //
2624 TableIterator iter0( table_->table(), "SRCNAME" ) ;
2625 while( !iter0.pastEnd() ) {
2626 //Table t0( iter0.table() ) ;
2627 Table t0 = iter0.table() ;
2628
2629 // get necessary information
2630 ROScalarColumn<String> srcNameCol( t0, "SRCNAME" ) ;
2631 String srcName = srcNameCol( 0 ) ;
2632 ROArrayColumn<Double> sharedDArrRCol( t0, "SRCPROPERMOTION" ) ;
2633 Vector<Double> srcPM = sharedDArrRCol( 0 ) ;
2634 sharedDArrRCol.attach( t0, "SRCDIRECTION" ) ;
2635 Vector<Double> srcDir = sharedDArrRCol( 0 ) ;
2636 ROScalarColumn<Double> srcVelCol( t0, "SRCVELOCITY" ) ;
2637 Double srcVel = srcVelCol( 0 ) ;
2638 srcRec_.define( srcName, srcId ) ;
2639
2640 // NAME
2641 *nameRF = srcName ;
2642
2643 // SOURCE_ID
2644 *srcidRF = srcId ;
2645
2646 // PROPER_MOTION
2647 *srcpmRF = srcPM ;
2648
2649 // DIRECTION
2650 *srcdirRF = srcDir ;
2651
2652 //
2653 // ITERATION: MOLECULE_ID
2654 //
2655 TableIterator iter1( t0, "MOLECULE_ID" ) ;
2656 while( !iter1.pastEnd() ) {
2657 //Table t1( iter1.table() ) ;
2658 Table t1 = iter1.table() ;
2659
2660 // get necessary information
2661 Vector<Double> restFreq ;
2662 Vector<String> molName ;
2663 Vector<String> fMolName ;
2664 ROScalarColumn<uInt> molIdCol( t1, "MOLECULE_ID" ) ;
2665 uInt molId = molIdCol( 0 ) ;
2666 stm.getEntry( restFreq, molName, fMolName, molId ) ;
2667
2668 uInt numFreq = restFreq.size() ;
2669
2670 // NUM_LINES
2671 *numlineRF = numFreq ;
2672
2673 // REST_FREQUENCY
2674 restfreqRF.define(restFreq);
2675
2676 // TRANSITION
2677 Vector<String> transition ;
2678 if ( fMolName.size() != 0 ) {
2679 transition = fMolName ;
2680 }
2681 else if ( molName.size() != 0 ) {
2682 transition = molName ;
2683 }
2684 else {
2685 transition.resize( numFreq ) ;
2686 transition = "" ;
2687 }
2688 transitionRF.define(transition);
2689
2690 // SYSVEL
2691 Vector<Double> sysvelArr( numFreq, srcVel ) ;
2692 sysvelRF.define(sysvelArr);
2693
2694 //
2695 // ITERATION: IFNO
2696 //
2697 TableIterator iter2( t1, "IFNO" ) ;
2698 while( !iter2.pastEnd() ) {
2699 //Table t2( iter2.table() ) ;
2700 Table t2 = iter2.table() ;
2701 uInt nrow = msSrc.nrow() ;
2702
2703 // get necessary information
2704 ROScalarColumn<uInt> ifNoCol( t2, "IFNO" ) ;
2705 uInt ifno = ifNoCol( 0 ) ; // IFNO = SPECTRAL_WINDOW_ID
2706 Double midTime ;
2707 Double interval ;
2708 getValidTimeRange( midTime, interval, t2 ) ;
2709
2710 // fill SPECTRAL_WINDOW_ID
2711 *spwidRF = ifno ;
2712
2713 // fill TIME, INTERVAL
2714 *timeRF = midTime ;
2715 *intervalRF = interval ;
2716
2717 // add row
2718 msSrc.addRow( 1, True ) ;
2719 row.put( nrow ) ;
2720
2721 iter2.next() ;
2722 }
2723
2724 iter1.next() ;
2725 }
2726
2727 // increment srcId if SRCNAME changed
2728 srcId++ ;
2729
2730 iter0.next() ;
2731 }
2732
2733// double endSec = mathutil::gettimeofday_sec() ;
2734// os_ << "end MSWriter::fillSource() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2735}
2736
2737void MSWriter::fillWeather()
2738{
2739// double startSec = mathutil::gettimeofday_sec() ;
2740// os_ << "start MSWriter::fillWeather() startSec=" << startSec << LogIO::POST ;
2741
2742 // access to MS WEATHER subtable
2743 MSWeather msw = mstable_->weather() ;
2744
2745 // access to WEATHER subtable
2746 Table stw = table_->weather().table() ;
2747 uInt nrow = stw.nrow() ;
2748
2749 if ( nrow == 0 )
2750 return ;
2751
2752 msw.addRow( nrow, True ) ;
2753 MSWeatherColumns mswCols( msw ) ;
2754
2755 // ANTENNA_ID is always 0
2756 Vector<Int> antIdArr( nrow, 0 ) ;
2757 mswCols.antennaId().putColumn( antIdArr ) ;
2758
2759 // fill weather status
2760 ROScalarColumn<Float> sharedFloatCol( stw, "TEMPERATURE" ) ;
2761 mswCols.temperature().putColumn( sharedFloatCol ) ;
2762 sharedFloatCol.attach( stw, "PRESSURE" ) ;
2763 mswCols.pressure().putColumn( sharedFloatCol ) ;
2764 sharedFloatCol.attach( stw, "HUMIDITY" ) ;
2765 mswCols.relHumidity().putColumn( sharedFloatCol ) ;
2766 sharedFloatCol.attach( stw, "WINDSPEED" ) ;
2767 mswCols.windSpeed().putColumn( sharedFloatCol ) ;
2768 sharedFloatCol.attach( stw, "WINDAZ" ) ;
2769 mswCols.windDirection().putColumn( sharedFloatCol ) ;
2770
2771 // fill TIME and INTERVAL
2772 Double midTime ;
2773 Double interval ;
2774 Vector<Double> intervalArr( nrow, 0.0 ) ;
2775 TableIterator iter( table_->table(), "WEATHER_ID" ) ;
2776 while( !iter.pastEnd() ) {
2777 //Table tab( iter.table() ) ;
2778 Table tab = iter.table() ;
2779
2780 ROScalarColumn<uInt> widCol( tab, "WEATHER_ID" ) ;
2781 uInt wid = widCol( 0 ) ;
2782
2783 getValidTimeRange( midTime, interval, tab ) ;
2784 mswCols.time().put( wid, midTime ) ;
2785 intervalArr[wid] = interval ;
2786
2787 iter.next() ;
2788 }
2789 mswCols.interval().putColumn( intervalArr ) ;
2790
2791// double endSec = mathutil::gettimeofday_sec() ;
2792// os_ << "end MSWriter::fillWeather() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2793}
2794
2795void MSWriter::fillSysCal()
2796{
2797 Table mssc = mstable_->sysCal() ;
2798
2799 if (table_->tcal().table().nrow() > 0) {
2800 static const char *cols[] = {
2801 "BEAMNO", "IFNO", "TIME", "POLNO",
2802 NULL
2803 };
2804 static const TypeManagerImpl<uInt> tmUInt;
2805 static const TypeManagerImpl<Double> tmDouble;
2806 static const TypeManager *const tms[] = {
2807 &tmUInt, &tmUInt, &tmDouble, &tmUInt, NULL
2808 };
2809 //double t0 = mathutil::gettimeofday_sec() ;
2810 MSSysCalVisitor myVisitor(table_->table(),mssc);
2811 //double t1 = mathutil::gettimeofday_sec() ;
2812 //cout << "MSWriterVisitor(): elapsed time " << t1-t0 << " sec" << endl ;
2813 traverseTable(table_->table(), cols, tms, &myVisitor);
2814 //double t3 = mathutil::gettimeofday_sec() ;
2815 //cout << "traverseTable(): elapsed time " << t3-t2 << " sec" << endl ;
2816 }
2817
2818}
2819
2820void MSWriter::getValidTimeRange( Double &me, Double &interval, Table &tab )
2821{
2822// double startSec = mathutil::gettimeofday_sec() ;
2823// os_ << "start MSWriter::getVaridTimeRange() startSec=" << startSec << LogIO::POST ;
2824
2825 // sort table
2826 //Table stab = tab.sort( "TIME" ) ;
2827
2828 ROScalarColumn<Double> timeCol( tab, "TIME" ) ;
2829 Vector<Double> timeArr = timeCol.getColumn() ;
2830 Double minTime ;
2831 Double maxTime ;
2832 minMax( minTime, maxTime, timeArr ) ;
2833 Double midTime = 0.5 * ( minTime + maxTime ) * 86400.0 ;
2834 // unit for TIME
2835 // Scantable: "d"
2836 // MS: "s"
2837 me = midTime ;
2838 interval = ( maxTime - minTime ) * 86400.0 ;
2839
2840// double endSec = mathutil::gettimeofday_sec() ;
2841// os_ << "end MSWriter::getValidTimeRange() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2842}
2843
2844void MSWriter::getValidTimeRange( Double &me, Double &interval, Vector<Double> &atime, Vector<Double> &ainterval )
2845{
2846// double startSec = mathutil::gettimeofday_sec() ;
2847// os_ << "start MSWriter::getVaridTimeRange() startSec=" << startSec << LogIO::POST ;
2848
2849 // sort table
2850 //Table stab = tab.sort( "TIME" ) ;
2851
2852 Double minTime ;
2853 Double maxTime ;
2854 minMax( minTime, maxTime, atime ) ;
2855 Double midTime = 0.5 * ( minTime + maxTime ) * 86400.0 ;
2856 // unit for TIME
2857 // Scantable: "d"
2858 // MS: "s"
2859 me = midTime ;
2860 interval = ( maxTime - minTime ) * 86400.0 + mean( ainterval ) ;
2861
2862// double endSec = mathutil::gettimeofday_sec() ;
2863// os_ << "end MSWriter::getValidTimeRange() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2864}
2865
2866}
Note: See TracBrowser for help on using the repository browser.