source: trunk/src/MSWriter.cpp@ 2741

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

New Development: No

JIRA Issue: No

Ready for Test: Yes

Interface Changes: No

What Interface Changed: Please list interface changes

Test Programs:

Put in Release Notes: No

Module(s): Module Names change impacts.

Description: Describe your changes here...

Bug fix on handling IFNO and FREQ_ID when exporting scantable to MS.


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