FlagDataHandler.h

Go to the documentation of this file.
00001 //# FlagDataHandler.h: This file contains the interface definition of the FlagDataHandler class.
00002 //#
00003 //#  CASA - Common Astronomy Software Applications (http://casa.nrao.edu/)
00004 //#  Copyright (C) Associated Universities, Inc. Washington DC, USA 2011, All rights reserved.
00005 //#  Copyright (C) European Southern Observatory, 2011, All rights reserved.
00006 //#
00007 //#  This library is free software; you can redistribute it and/or
00008 //#  modify it under the terms of the GNU Lesser General Public
00009 //#  License as published by the Free software Foundation; either
00010 //#  version 2.1 of the License, or (at your option) any later version.
00011 //#
00012 //#  This library is distributed in the hope that it will be useful,
00013 //#  but WITHOUT ANY WARRANTY, without even the implied warranty of
00014 //#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015 //#  Lesser General Public License for more details.
00016 //#
00017 //#  You should have received a copy of the GNU Lesser General Public
00018 //#  License along with this library; if not, write to the Free Software
00019 //#  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
00020 //#  MA 02111-1307  USA
00021 //# $Id: $
00022 
00023 #ifndef FLAGDATAHANDLER_H_
00024 #define FLAGDATAHANDLER_H_
00025 
00026 // Measurement Set selection
00027 #include <ms/MeasurementSets/MeasurementSet.h>
00028 #include <ms/MSSel/MSSelection.h>
00029 #include <ms/MeasurementSets/MSAntennaColumns.h>
00030 #include <ms/MeasurementSets/MSFieldColumns.h>
00031 #include <ms/MeasurementSets/MSPolColumns.h>
00032 #include <ms/MeasurementSets/MSSpWindowColumns.h>
00033 #include <ms/MeasurementSets/MSProcessorColumns.h>
00034 
00035 // VI/VB infrastructure
00036 #include <msvis/MSVis/StokesVector.h>
00037 #include <msvis/MSVis/VisBuffer2.h>
00038 #include <msvis/MSVis/VisibilityIterator2.h>
00039 
00040 // TVI framework
00041 #include <msvis/MSVis/AveragingVi2Factory.h>
00042 #include <msvis/MSVis/AveragingTvi2.h>
00043 
00044 // .casarc interface
00045 #include <casa/System/AipsrcValue.h>
00046 
00047 // Records interface
00048 #include <casa/Containers/Record.h>
00049 
00050 // System utilities (for profiling macros)
00051 #include <casa/OS/HostInfo.h>
00052 #include <sys/time.h>
00053 
00054 // Data mapping
00055 #include <algorithm>
00056 #include <map>
00057 
00058 #define STARTCLOCK timeval start,stop; double elapsedTime; if (profiling_p) gettimeofday(&start,0);
00059 #define STOPCLOCK if (profiling_p) \
00060         {\
00061                 gettimeofday(&stop,0);\
00062                 elapsedTime = (stop.tv_sec-start.tv_sec)*1000.0+(stop.tv_usec-start.tv_usec)/1000.0;\
00063                 *logger_p << LogIO::DEBUG2 << "FlagDataHandler::" << __FUNCTION__ << " Executed in: " << elapsedTime << " ms, Memory free: " << HostInfo::memoryFree( )/1024.0 << " MB" << LogIO::POST;\
00064         }
00065 
00066 namespace casa { //# NAMESPACE CASA - BEGIN
00067 
00068 // Type definitions
00069 typedef std::map< std::pair<Int,Int>,std::vector<uInt> >::iterator antennaPairMapIterator;
00070 typedef std::map< Double,std::vector<uInt> >::iterator subIntegrationMapIterator;
00071 typedef std::map< uShort,uShort >::iterator polartizationMapIterator;
00072 typedef std::map< std::pair<Int,Int>,std::vector<uInt> > antennaPairMap;
00073 typedef std::map< Double,std::vector<uInt> > subIntegrationMap;
00074 typedef std::map< uShort,uShort > polarizationMap;
00075 typedef std::map< uInt,String > polarizationIndexMap;
00076 typedef std::vector< vector<Double> > antennaPointingMap;
00077 typedef std::map< Int,vector<Double> > scanStartStopMap;
00078 typedef std::map< Int,Double > lambdaMap;
00079 
00080 const Complex ImaginaryUnit = Complex(0,1);
00081 
00082 // We need to have the CubeView definition here because its type is used by FlagDataHandler class
00083 template<class T> class CubeView
00084 {
00085 
00086 public:
00087 
00088         CubeView(Cube<T> *parentCube, std::vector<uInt> *rows = NULL, std::vector<uInt> *channels = NULL, std::vector<uInt> *polarizations = NULL)
00089         {
00090                 parentCube_p = parentCube;
00091                 IPosition baseCubeShape = parentCube_p->shape();
00092                 reducedLength_p = IPosition(3);
00093 
00094                 if (((polarizations != NULL) and (polarizations->size() > 0)) and
00095                         ((channels != NULL) and (channels->size() > 0)) and
00096                         ((rows != NULL) and (rows->size() > 0)))
00097                 {
00098                         access_p = &CubeView::accessMapped;
00099                 }
00100                 else if (((polarizations != NULL) and (polarizations->size() > 0)) and
00101                                 ((channels != NULL) and (channels->size() > 0)))
00102                 {
00103                         access_p = &CubeView::accessIndex12Mapped;
00104                 }
00105                 else if (((polarizations != NULL) and (polarizations->size() > 0)) and
00106                                 ((rows != NULL) and (rows->size() > 0)))
00107                 {
00108                         access_p = &CubeView::accessIndex13Mapped;
00109                 }
00110                 else if (((channels != NULL) and (channels->size() > 0)) and
00111                                 ((rows != NULL) and (rows->size() > 0)))
00112                 {
00113                         access_p = &CubeView::accessIndex23Mapped;
00114                 }
00115                 else if ((polarizations != NULL) and (polarizations->size() > 0))
00116                 {
00117                         access_p = &CubeView::accessIndex1Mapped;
00118                 }
00119                 else if ((channels != NULL) and (channels->size() > 0))
00120                 {
00121                         access_p = &CubeView::accessIndex2Mapped;
00122                 }
00123                 else if ((rows != NULL) and (rows->size() > 0))
00124                 {
00125                         access_p = &CubeView::accessIndex3Mapped;
00126                 }
00127                 else
00128                 {
00129                         access_p = &CubeView::accessUnmapped;
00130                 }
00131 
00132                 if ((polarizations != NULL) and (polarizations->size() > 0))
00133                 {
00134                         polarizations_p = polarizations;
00135                         reducedLength_p(0) = polarizations_p->size();
00136                 }
00137                 else
00138                 {
00139                         polarizations_p = NULL;
00140                         reducedLength_p(0) = baseCubeShape(0);
00141                 }
00142 
00143                 if ((channels != NULL) and (channels->size() > 0))
00144                 {
00145                         channels_p = channels;
00146                         reducedLength_p(1) = channels_p->size();
00147                 }
00148                 else
00149                 {
00150                         channels_p = NULL;
00151                         reducedLength_p(1) = baseCubeShape(1);
00152                 }
00153 
00154                 if ((rows != NULL) and (rows->size() > 0))
00155                 {
00156                         rows_p = rows;
00157                         reducedLength_p(2) = rows_p->size();
00158                 }
00159                 else
00160                 {
00161                         rows_p = NULL;
00162                         reducedLength_p(2) = baseCubeShape(2);
00163                 }
00164         }
00165 
00166     T &operator()(uInt i1, uInt i2, uInt i3)
00167     {
00168         return (*this.*access_p)(i1,i2,i3);
00169     }
00170 
00171     const IPosition &shape() const
00172     {
00173         return reducedLength_p;
00174     }
00175 
00176     void shape(Int &s1, Int &s2, Int &s3) const
00177     {
00178         s1 = reducedLength_p(0);
00179         s2 = reducedLength_p(1);
00180         s3 = reducedLength_p(2);
00181         return;
00182     }
00183 
00184 protected:
00185 
00186     vector<uInt> *createIndex(uInt size)
00187     {
00188         vector<uInt> *index = new vector<uInt>(size);
00189         index->clear();
00190         for (uInt i=0; i<size; i++ )
00191         {
00192                 index->push_back(i);
00193         }
00194         return index;
00195     }
00196 
00197     T &accessUnmapped(uInt i1, uInt i2, uInt i3)
00198     {
00199         return parentCube_p->at(i1,i2,i3);
00200     }
00201 
00202     T &accessMapped(uInt i1, uInt i2, uInt i3)
00203     {
00204         uInt i1_index = polarizations_p->at(i1);
00205         uInt i2_index = channels_p->at(i2);
00206         uInt i3_index = rows_p->at(i3);
00207         return parentCube_p->at(i1_index,i2_index,i3_index);
00208     }
00209 
00210     T &accessIndex1Mapped(uInt i1, uInt i2, uInt i3)
00211     {
00212         uInt i1_index = polarizations_p->at(i1);
00213         return parentCube_p->at(i1_index,i2,i3);
00214     }
00215 
00216     T &accessIndex2Mapped(uInt i1, uInt i2, uInt i3)
00217     {
00218         uInt i2_index = channels_p->at(i2);
00219         return parentCube_p->at(i1,i2_index,i3);
00220     }
00221 
00222     T &accessIndex3Mapped(uInt i1, uInt i2, uInt i3)
00223     {
00224         uInt i3_index = rows_p->at(i3);
00225         return parentCube_p->at(i1,i2,i3_index);
00226     }
00227 
00228     T &accessIndex12Mapped(uInt i1, uInt i2, uInt i3)
00229     {
00230         uInt i1_index = polarizations_p->at(i1);
00231         uInt i2_index = channels_p->at(i2);
00232         return parentCube_p->at(i1_index,i2_index,i3);
00233     }
00234 
00235     T &accessIndex13Mapped(uInt i1, uInt i2, uInt i3)
00236     {
00237         uInt i1_index = polarizations_p->at(i1);
00238         uInt i3_index = rows_p->at(i3);
00239         return parentCube_p->at(i1_index,i2,i3_index);
00240     }
00241 
00242     T &accessIndex23Mapped(uInt i1, uInt i2, uInt i3)
00243     {
00244         uInt i2_index = channels_p->at(i2);
00245         uInt i3_index = rows_p->at(i3);
00246         return parentCube_p->at(i1,i2_index,i3_index);
00247     }
00248 
00249 private:
00250     Cube<T> *parentCube_p;
00251         std::vector<uInt> *rows_p;
00252         std::vector<uInt> *channels_p;
00253         std::vector<uInt> *polarizations_p;
00254         IPosition reducedLength_p;
00255         T &(casa::CubeView<T>::*access_p)(uInt,uInt,uInt);
00256 };
00257 
00258 template<class T> class VectorView
00259 {
00260 
00261 public:
00262         VectorView(Vector<T> *parentVector, std::vector<uInt> *rows = NULL)
00263         {
00264                 IPosition parentVectorShape = parentVector->shape();
00265                 parentVector_p = parentVector;
00266                 reducedLength_p = IPosition(1);
00267 
00268                 if ((rows != NULL) and (rows->size() > 0))
00269                 {
00270                         access_p = &VectorView::accessMapped;
00271                 }
00272                 else
00273                 {
00274                         access_p = &VectorView::accessUnmapped;
00275                 }
00276 
00277                 if ((rows != NULL) and (rows->size() > 0))
00278                 {
00279                         rows_p = rows;
00280                         reducedLength_p(0) = rows_p->size();
00281                 }
00282                 else
00283                 {
00284                         rows_p = NULL;
00285                         reducedLength_p(0) = parentVectorShape(0);
00286                 }
00287         }
00288 
00289     T &operator()(uInt i1)
00290     {
00291         return (*this.*access_p)(i1);
00292     }
00293 
00294     const IPosition &shape() const
00295     {
00296         return reducedLength_p;
00297     }
00298 
00299     void shape(Int &s1) const
00300     {
00301         s1 = reducedLength_p(0);
00302         return;
00303     }
00304 
00305 protected:
00306 
00307     vector<uInt> *createIndex(uInt size)
00308     {
00309         vector<uInt> *index = new vector<uInt>(size);
00310         index->clear();
00311         for (uInt i=0; i<size; i++ )
00312         {
00313                 index->push_back(i);
00314         }
00315         return index;
00316     }
00317 
00318     T &accessUnmapped(uInt i1)
00319     {
00320         return parentVector_p->operator()(i1);
00321     }
00322 
00323     T &accessMapped(uInt i1)
00324     {
00325         uInt i1_index = rows_p->at(i1);
00326         return parentVector_p->operator()(i1_index);
00327     }
00328 
00329 private:
00330     Vector<T> *parentVector_p;
00331         std::vector<uInt> *rows_p;
00332         IPosition reducedLength_p;
00333         T &(casa::VectorView<T>::*access_p)(uInt);
00334 };
00335 
00336 class VisMapper
00337 {
00338         typedef Complex (casa::VisMapper::*corrProduct)(uInt,uInt);
00339 
00340 public:
00341 
00342         enum calsolutions {
00343 
00344                 CALSOL1=Stokes::NumberOfTypes,
00345                 CALSOL2,
00346                 CALSOL3,
00347                 CALSOL4
00348         };
00349 
00350         VisMapper(String expression,polarizationMap *polMap,CubeView<Complex> *leftVis,CubeView<Complex> *rightVis=NULL);
00351         VisMapper(String expression,polarizationMap *polMap);
00352         ~VisMapper();
00353 
00354     void setParentCubes(CubeView<Complex> *leftVis,CubeView<Complex> *rightVis=NULL);
00355 
00356     vector< vector<uInt> > getSelectedCorrelations() { return selectedCorrelations_p;}
00357     vector< string > getSelectedCorrelationStrings() { return selectedCorrelationStrings_p;}
00358 
00359         Float operator()(uInt chan, uInt row);
00360         Float operator()(uInt pol, uInt chan, uInt row);
00361 
00362         // Direct access to the complex correlation product
00363         Complex correlationProduct(uInt pol, uInt chan, uInt row);
00364 
00365     // NOTE: reducedLength_p is defined as [chan,row,pol]
00366     const IPosition &shape() const
00367     {
00368         return reducedLength_p;
00369     }
00370 
00371     void shape(Int &chan, Int &row) const
00372     {
00373         chan = reducedLength_p(0);
00374         row = reducedLength_p(1);
00375         return;
00376     }
00377 
00378     void shape(Int &pol, Int &chan, Int &row) const
00379     {
00380         chan = reducedLength_p(0);
00381         row = reducedLength_p(1);
00382         pol = reducedLength_p(2);
00383         return;
00384     }
00385 
00386 
00387 protected:
00388     void setExpressionMapping(String expression,polarizationMap *polMap);
00389         Float real(Complex val) {return val.real();}
00390         Float imag(Complex val) {return val.imag();}
00391         Float abs(Complex val) {return std::abs(val);}
00392         Float arg(Complex val) {return std::arg(val);}
00393         Float norm(Complex val) {return std::norm(val);}
00394         Complex leftVis(uInt pol, uInt chan, uInt row);
00395         Complex diffVis(uInt pol, uInt chan, uInt row);
00396         Complex stokes_i(uInt pol, uInt chan);
00397         Complex stokes_q(uInt pol, uInt chan);
00398         Complex stokes_u(uInt pol, uInt chan);
00399         Complex stokes_v(uInt pol, uInt chan);
00400         Complex linear_xx(uInt pol, uInt chan);
00401         Complex linear_yy(uInt pol, uInt chan);
00402         Complex linear_xy(uInt pol, uInt chan);
00403         Complex linear_yx(uInt pol, uInt chan);
00404         Complex circular_rr(uInt pol, uInt chan);
00405         Complex circular_ll(uInt pol, uInt chan);
00406         Complex circular_rl(uInt pol, uInt chan);
00407         Complex circular_lr(uInt pol, uInt chan);
00408         Complex stokes_i_from_linear(uInt chan, uInt row);
00409         Complex stokes_q_from_linear(uInt chan, uInt row);
00410         Complex stokes_u_from_linear(uInt chan, uInt row);
00411         Complex stokes_v_from_linear(uInt chan, uInt row);
00412         Complex stokes_i_from_circular(uInt chan, uInt row);
00413         Complex stokes_q_from_circular(uInt chan, uInt row);
00414         Complex stokes_u_from_circular(uInt chan, uInt row);
00415         Complex stokes_v_from_circular(uInt chan, uInt row);
00416         Complex calsol1(uInt chan, uInt row);
00417         Complex calsol2(uInt chan, uInt row);
00418         Complex calsol3(uInt chan, uInt row);
00419         Complex calsol4(uInt chan, uInt row);
00420 
00421 
00422 private:
00423         Float (casa::VisMapper::*applyVisExpr_p)(Complex);
00424         Complex (casa::VisMapper::*getVis_p)(uInt,uInt,uInt);
00425         Complex (casa::VisMapper::*getCorr_p)(uInt,uInt);
00426         vector<corrProduct> selectedCorrelationProducts_p;
00427         vector< vector<uInt> > selectedCorrelations_p;
00428         vector<string> selectedCorrelationStrings_p;
00429         CubeView<Complex> *leftVis_p;
00430         CubeView<Complex> *rightVis_p;
00431         IPosition reducedLength_p;
00432         polarizationMap *polMap_p;
00433         String expression_p;
00434 };
00435 
00436 class FlagMapper
00437 {
00438 
00439 public:
00440 
00441         FlagMapper(Bool flag,   vector < vector<uInt> > selectedCorrelations,
00442                                                         CubeView<Bool> *commonFlagsView,
00443                                                         CubeView<Bool> *originalFlagsView,
00444                                                         CubeView<Bool> *privateFlagsView=NULL,
00445                                                         VectorView<Bool> *commonFlagRowView=NULL,
00446                                                         VectorView<Bool> *originalFlagRowView=NULL,
00447                                                         VectorView<Bool> *privateFlagRowView=NULL);
00448         FlagMapper(Bool flag,vector< vector<uInt> > selectedCorrelations);
00449         ~FlagMapper();
00450 
00451         void setParentCubes(CubeView<Bool> *commonFlagsView,CubeView<Bool> *originalFlagsView,CubeView<Bool> *privateFlagsView=NULL);
00452         void setParentFlagRow(VectorView<Bool> *commonFlagRowView,VectorView<Bool> *originalFlagRowView,VectorView<Bool> *privateFlagRowView=NULL);
00453 
00454         void applyFlag(uInt chan, uInt row);
00455         void applyFlag(uInt pol, uInt channel, uInt row);
00456         void applyFlagRow(uInt row);
00457         void applyFlagInRow(uInt row);
00458 
00459         Bool getOriginalFlags(uInt chan, uInt row);
00460         Bool getModifiedFlags(uInt chan, uInt row);
00461         Bool getPrivateFlags(uInt chan, uInt row);
00462 
00463         Bool getOriginalFlags(uInt pol, uInt channel, uInt row);
00464         Bool getModifiedFlags(uInt pol, uInt channel, uInt row);
00465         Bool getPrivateFlags(uInt pol, uInt channel, uInt row);
00466 
00467         // These methods are needed for flag extension
00468         void setModifiedFlags(uInt pol, uInt channel, uInt row);
00469         void setPrivateFlags(uInt pol, uInt channel, uInt row);
00470 
00471         Bool getOriginalFlagRow(uInt row);
00472         Bool getModifiedFlagRow(uInt row);
00473         Bool getPrivateFlagRow(uInt row);
00474 
00475     const IPosition &shape() const
00476     {
00477         return reducedLength_p;
00478     }
00479 
00480     void shape(Int &chan, Int &row) const
00481     {
00482         chan = reducedLength_p(0);
00483         row = reducedLength_p(1);
00484         return;
00485     }
00486 
00487     void shape(Int &pol, Int &chan, Int &row) const
00488     {
00489         chan = reducedLength_p(0);
00490         row = reducedLength_p(1);
00491         pol = reducedLength_p(2);
00492         return;
00493     }
00494 
00495         vector< vector<uInt> > getSelectedCorrelations() {return selectedCorrelations_p;}
00496 
00497     void activateCheckMode() {applyFlag_p = &FlagMapper::checkCommonFlags;}
00498 
00499     uInt nSelectedCorrelations() {return nSelectedCorrelations_p;}
00500     uInt flagsPerRow() {return flagsPerRow_p;}
00501 
00502 protected:
00503 
00504         void setExpressionMapping(vector< vector<uInt> > selectedCorrelations);
00505 
00506         // Apply flags to common flag cube
00507         void applyCommonFlags(uInt pol, uInt channel, uInt row);
00508         // Apply flags to common and private flag cubes
00509         void applyPrivateFlags(uInt pol, uInt channel, uInt row);
00510         // Apply flags to common and private flag cubes
00511         void checkCommonFlags(uInt pol, uInt channel, uInt row);
00512 
00513         // Apply flags to common flag rows
00514         void applyCommonFlagRow(uInt row);
00515         // Apply flags to common and private flag rows
00516         void applyPrivateFlagRow(uInt row);
00517 
00518 private:
00519 
00520         Bool flag_p;
00521     IPosition reducedLength_p;
00522         CubeView<Bool> *commonFlagsView_p;
00523         CubeView<Bool> *originalFlagsView_p;
00524         CubeView<Bool> *privateFlagsView_p;
00525         VectorView<Bool> *commonFlagRowView_p;
00526         VectorView<Bool> *originalFlagRowView_p;
00527         VectorView<Bool> *privateFlagRowView_p;
00528         vector< vector<uInt> > selectedCorrelations_p;
00529         uInt nSelectedCorrelations_p;
00530         uInt flagsPerRow_p;
00531         void (casa::FlagMapper::*applyFlag_p)(uInt,uInt,uInt);
00532         void (casa::FlagMapper::*applyFlagRow_p)(uInt);
00533 };
00534 
00535 // <summary>
00536 // A top level class defining the data handling interface for the flagging module
00537 // </summary>
00538 //
00539 // <use visibility=export>
00540 //
00541 // <prerequisite>
00542 //   <li> <linkto class="VisBuffer:description">VisBuffer</linkto>
00543 //   <li> <linkto class="FlagMapper:description">FlagMapper</linkto>
00544 //   <li> <linkto class="VisMapper:description">VisMapper</linkto>
00545 // </prerequisite>
00546 //
00547 // <etymology>
00548 // FlagDataHandler stands for generic data handling (i.e. MSs, CalTables, ...) specific to the flagging module
00549 // </etymology>
00550 //
00551 // <synopsis>
00552 //
00553 // This is a top-level class defining the data handling interface for the flagging module.
00554 // There are various methods (virtual) that must be re-implemented by the specific derived
00555 // classes (e.g. FlagMSHandler, FlagCalTableHandler). These methods essentially cover:
00556 //
00557 // - Table access (i.e. open/close/iteration/rw)
00558 //
00559 // - Table selection (i.e. expression parsing, sub-table selection)
00560 //
00561 // Additionally there are public non-virtual methods to:
00562 //
00563 // - Set configuration parameters (pre-sort columns, data selection, time interval, async I/O)
00564 //
00565 // - Enable and access different kinds of mapping (baselines, correlation products, antenna pointing)
00566 //
00567 // Also at this top level there are public members which are used by the FlagAgent classes,
00568 // so that there is no dependency with the specific implementation classes (e.g. FlagMsHandler,
00569 // FlagCalTableHandler), and thus no re-implementation is required at the FlagAgent level.
00570 //
00571 // - VisBuffer (for accessing the data and meta data columns)
00572 //
00573 // - Chunk and Table flag counters (for statistics)
00574 //
00575 // </synopsis>
00576 //
00577 // <motivation>
00578 // The motivation for the FlagDataHandler class is having all the data operations encapsulated
00579 // in one single class, with a common interface for all types of tables (MSs, CalTables, SingleDish),
00580 // so that no specific specific table type implementation has to be done at the FlagAgent level.
00581 // </motivation>
00582 //
00583 // <example>
00584 // <srcblock>
00585 //
00586 // // The following code sets up a FlagDataHandler with either CalTable or MS implementation and
00587 // // iterates through the table applying a clip agent, flushing the flags, and extracting summaries.
00588 //
00589 // // IMPORTANT NOTE:
00590 // // The order of FlagDataHandler and FlagAgent initialization is critical to have everything right,
00591 // // in particular data selection must happen before initializing FlagAgents, and iterator generation
00592 // // must be done after initializing FlagAgents, so that each agent can communicate to the FlagDataHandler
00593 // // which columns have to be pre-fetched (async i/o or parallel mode), and what mapping options are necessary.
00594 //
00595 // // NOTE ON ASYNC I/O:
00596 // // Asyncnronous I/O is only enabled for MS-type tables, but not for CalTables, and it is necessary to switch
00597 // // it on before generating the iterators. Something else to take into account, is that there are 2 global
00598 // // switches at .casarc level which invalidate the application code selection:
00599 // //
00600 // // VisibilityIterator.async.enabled rules over
00601 // // |-> FlagDataHandler.asyncio, and in turns rules over
00602 // //     |-> FlagDataHandler.enableAsyncIO(True)
00603 //
00604 // // Identify table type
00605 // Table table(msname_p,TableLock(TableLock::AutoNoReadLocking));
00606 // TableInfo& info = table.tableInfo();
00607 // String type=info.type();
00608 //
00609 // // Create derived FlagDataHandler object with corresponding implementation
00610 // FlagDataHandler *fdh_p = NULL;
00611 // if (type == "Measurement Set")
00612 // {
00613 //    fdh_p = new FlagMSHandler(msname_p, FlagDataHandler::COMPLETE_SCAN_UNMAPPED, timeInterval_p);
00614 // }
00615 // else
00616 // {
00617 //    fdh_p = new FlagCalTableHandler(msname_p, FlagDataHandler::COMPLETE_SCAN_UNMAPPED, timeInterval_p);
00618 // }
00619 //
00620 // // NOTE: It is also possible to independently set the iteration approach via the setIterationApproach
00621 // //       method which accepts the following modes, defined in the FlagDataHandler iteration enumeration
00622 // //
00623 // //       COMPLETE_SCAN_MAPPED:
00624 // //       - Sort by OBSERVATION_ID, ARRAY_ID, SCAN_NUMBER, FIELD_ID, DATA_DESC_ID and TIME
00625 // //       - Group all time steps together, so that there is no sub-chunk iteration
00626 // //       - Generate baseline maps (to iterate trough rows with the same antenna1, antenna2)
00627 // //       - Generate sub-integration maps (to iterate trough rows with the same timestamp)
00628 // //       COMPLETE_SCAN_MAP_SUB_INTEGRATIONS_ONLY:
00629 // //       - Sort by OBSERVATION_ID, ARRAY_ID, SCAN_NUMBER, FIELD_ID, DATA_DESC_ID and TIME
00630 // //       - Group all time steps together, so that there is no sub-chunk iteration
00631 // //       * Don't generate baseline maps
00632 // //       - Generate sub-integration maps (to iterate trough rows with the same timestamp)
00633 // //       COMPLETE_SCAN_MAP_ANTENNA_PAIRS_ONLY:
00634 // //       - Sort by OBSERVATION_ID, ARRAY_ID, SCAN_NUMBER, FIELD_ID, DATA_DESC_ID and TIME
00635 // //       - Group all time steps together, so that there is no sub-chunk iteration
00636 // //       - Generate baseline maps (to iterate trough rows with the same antenna1, antenna2)
00637 // //       * Don't generate sub-integration maps
00638 // //       COMPLETE_SCAN_UNMAPPED:
00639 // //       - Sort by OBSERVATION_ID, ARRAY_ID, SCAN_NUMBER, FIELD_ID, DATA_DESC_ID and TIME
00640 // //       - Group all time steps together, so that there is no sub-chunk iteration
00641 // //       * Don't generate baseline maps
00642 // //       * Don't generate sub-integration maps
00643 // //       COMBINE_SCANS_MAPPED:
00644 // //       - Sort by OBSERVATION_ID, ARRAY_ID, FIELD_ID, DATA_DESC_ID and TIME
00645 // //       - Group all time steps together, so that there is no sub-chunk iteration
00646 // //       - Generate baseline maps (to iterate trough rows with the same antenna1, antenna2)
00647 // //       - Generate sub-integration maps (to iterate trough rows with the same timestamp)
00648 // //       COMBINE_SCANS_MAP_SUB_INTEGRATIONS_ONLY:
00649 // //       - Sort by OBSERVATION_ID, ARRAY_ID, FIELD_ID, DATA_DESC_ID and TIME
00650 // //       - Group all time steps together, so that there is no sub-chunk iteration
00651 // //       * Don't generate baseline maps
00652 // //       - Generate sub-integration maps (to iterate trough rows with the same timestamp)
00653 // //       COMBINE_SCANS_MAP_ANTENNA_PAIRS_ONLY:
00654 // //       - Sort by OBSERVATION_ID, ARRAY_ID, FIELD_ID, DATA_DESC_ID and TIME
00655 // //       - Group all time steps together, so that there is no sub-chunk iteration
00656 // //       - Generate baseline maps (to iterate trough rows with the same antenna1, antenna2)
00657 // //       * Don't generate sub-integration maps
00658 // //       COMBINE_SCANS_UNMAPPED:
00659 // //       - Sort by OBSERVATION_ID, ARRAY_ID, FIELD_ID, DATA_DESC_ID and TIME
00660 // //       - Group all time steps together, so that there is no sub-chunk iteration
00661 // //       * Don't generate baseline maps
00662 // //       * Don't generate sub-integration maps
00663 // //       ANTENNA_PAIR:
00664 // //       - Sort by OBSERVATION_ID, ARRAY_ID, FIELD_ID, ANTENNA1, ANTENNA2, DATA_DESC_ID and TIME
00665 // //       - Group all time steps together, so that there is no sub-chunk iteration
00666 // //       * Don't generate baseline maps (they are not necessary because the chunks have constant ANTENNA1,ANTENNA2)
00667 // //       * Don't generate sub-integration maps
00668 // //       SUB_INTEGRATION:
00669 // //       - Sort by OBSERVATION_ID, ARRAY_ID, SCAN_NUMBER, FIELD_ID, DATA_DESC_ID and TIME
00670 // //       - Don't group all time steps together, so it is necessary to add an inner sub-chunk iteration loop
00671 // //       * Don't generate baseline maps (it is not possible because not all the rows corresponding to a given baseline are available)
00672 // //       * Don't generate sub-integration maps (they are not necessary because the sub-chunks have constant TIME)
00673 // //       ARRAY_FIELD:
00674 // //       - Sort by OBSERVATION_ID, ARRAY_ID, FIELD_ID, DATA_DESC_ID and TIME
00675 // //       - Don't group all time steps together, so it is necessary to add an inner sub-chunk iteration loop
00676 // //       * Don't generate baseline maps (it is not possible because not all the rows corresponding to a given baseline are available)
00677 // //       * Don't generate sub-integration maps (they are not necessary because the sub-chunks have constant TIME)
00678 // //       * NOTE: This is the iteration approach used by the old flagger framework
00679 //
00680 // // Open table
00681 // fdh_p->open();
00682 //
00683 // // Parse data selection to Flag Data Handler
00684 // fdh_p->setDataSelection(dataSelection);
00685 //
00686 // // Select data (thus creating selected table)
00687 // fdh_p->selectData();
00688 //
00689 // // Create flagging agent and list
00690 // Record agentConfig;
00691 // agentConfig.define("mode","clip")
00692 // FlagAgentBase *agent = FlagAgentBase::create(fdh_p,agentConfig);
00693 // FlagAgentList agentList;
00694 // agentList.push_back(agent);
00695 //
00696 // // Switch on/off async i/p
00697 // fdh_p->enableAsyncIO(true);
00698 //
00699 // // Generate table iterator
00700 // fdh_p->generateIterator();
00701 //
00702 // // Start Flag Agent
00703 // agentList.start();
00704 //
00705 // // Iterates over chunks (constant column values)
00706 // while (fdh_p->nextChunk())
00707 // {
00708 //    // Iterates over buffers (time steps)
00709 //    while (fdh_p->nextBuffer())
00710 //    {
00711 //       // Apply flags
00712 //       agentList.apply();
00713 //       // Flush flag cube
00714 //       fdh_p->flushFlags();
00715 //    }
00716 //
00717 //    // Print end-of-chunk statistics
00718 //    agentList.chunkSummary();
00719 // }
00720 //
00721 // // Print total stats from each agent
00722 // agentList.msSummary();
00723 //
00724 // // Stop Flag Agent
00725 // agentList.terminate();
00726 // agentList.join();
00727 //
00728 // // Close MS
00729 // fdh_p->close();
00730 //
00731 // // Clear Flag Agent List
00732 // agentList.clear();
00733 //
00734 // </srcblock>
00735 // </example>
00736 //
00737 // <example>
00738 // <srcblock>
00739 //
00740 // // The following code shows the FlagAgent-FlagDataHandler interaction works internally:
00741 //
00742 // // First of all, at construction time, each agent has to communicate to the FlagDataHandler
00743 // // which columns have to be pre-fetched (for async i/o or parallel mode) and what mapping
00744 // // options are necessary
00745 
00746 // // ...for instance in the case of FlagAgentShadow we need Ant1,Ant2,UVW,TimeCentroid and PhaseCenter:
00747 // flagDataHandler_p->preLoadColumn(vi::Antenna1);
00748 // flagDataHandler_p->preLoadColumn(vi::Antenna2);
00749 // flagDataHandler_p->preLoadColumn(vi::uvw);
00750 // flagDataHandler_p->preLoadColumn(vi::TimeCentroid);
00751 // flagDataHandler_p->preLoadColumn(vi::PhaseCenter);
00752 //
00753 // // ...and FlagAgentElevation needs to have the antenna pointing information globally available for each chunk:
00754 // flagDataHandler_p->setMapAntennaPointing(true);
00755 //
00756 // // Then, at iteration time, the FlagAgentBase class has access to the VisBuffer held
00757 // // in the FlagDataHandler, in order to retrieve the meta-data columns needed for the
00758 // // data selection engine (agent-level row filtering).
00759 // // NOTE: The VisBuffer is actually held within an auto-pointer wrapper,
00760 // //       thus there is an additional get() involved when accessing it.
00761 //
00762 // if (spwList_p.size())
00763 // {
00764 //    if (!find(spwList_p,visibilityBuffer_p->get()->spectralWindow())) return false;
00765 // }
00766 //
00767 // // The sorting columns used for the iteration are also accessible to optimize the selection engine:
00768 // // (e.g.: If scan is constant check only 1st row)
00769 // if ( (scanList_p.size()>0) and (find(flagDataHandler_p->sortOrder_p,MS::SCAN_NUMBER)==true) )
00770 // {
00771 //    if (!find(scanList_p,visibilityBuffer_p->get()->scan()[0])) return false;
00772 // }
00773 //
00774 // // Once that chunk/rows are evaluated as eligible for the flagging process
00775 // // by the data selection engine, the previously booked maps at construction
00776 // // time can be access in order to iterate trough the data as desired:
00777 // // e.g.: Baseline (antenna pairs) iteration
00778 // for (myAntennaPairMapIterator=flagDataHandler_p->getAntennaPairMap()->begin();
00779 //      myAntennaPairMapIterator != flagDataHandler_p->getAntennaPairMap()->end();
00780 //      ++myAntennaPairMapIterator)
00781 // {
00782 //    // NOTE: The following code is also encapsulated in the FlagAgentBase::processAntennaPair(Int antenna1,Int antenna2) code
00783 //
00784 //    // From the antenna map we can retrieve the rows corresponding to the baseline defined by the antenna pair
00785 //    vector<uInt> baselineRows = (*flagDataHandler_p->getAntennaPairMap())[std::make_pair(antennaPair.first,antennaPair.second)];
00786 //
00787 //    // This rows can be now inserted in the mapper classes (VisMapper and FlagMapper using the CubeView<T> template class)
00788 //    VisMapper visibilitiesMap = VisMapper(expression_p,flagDataHandler_p->getPolarizationMap());
00789 //    FlagMapper flagsMap = FlagMapper(flag_p,visibilitiesMap.getSelectedCorrelations());
00790 //    setVisibilitiesMap(antennaRows,&visibilitiesMap);
00791 //    setFlagsMap(antennaRows,&flagsMap);
00792 // }
00793 //
00794 // // Finally, after flagging time, the FlagAgent can communicate to the FlagDataHandler
00795 // // that the modified FlagCube has to be flushed to disk, this is a small but very important
00796 // // step in order to avoid unnecessary I/O activity when a chunk is not eligible for flagging
00797 // // or the auto-flagging algorithms don't produce any flags.
00798 //
00799 // // If any row was flag, then we have to flush the flagRow
00800 // if (flagRow_p) flagDataHandler_p->flushFlagRow_p = true;
00801 // // If any flag was raised, then we have to flush the flagCube
00802 // if (visBufferFlags_p>0) flagDataHandler_p->flushFlags_p = true;
00803 //
00804 // </srcblock>
00805 // </example>
00806 
00807 class FlagDataHandler
00808 {
00809 
00810 public:
00811 
00812         enum iteration {
00813 
00814                 COMPLETE_SCAN_MAPPED=0,
00815                 COMPLETE_SCAN_MAP_SUB_INTEGRATIONS_ONLY,
00816                 COMPLETE_SCAN_MAP_ANTENNA_PAIRS_ONLY,
00817                 COMPLETE_SCAN_UNMAPPED,
00818                 COMBINE_SCANS_MAPPED,
00819                 COMBINE_SCANS_MAP_SUB_INTEGRATIONS_ONLY,
00820                 COMBINE_SCANS_MAP_ANTENNA_PAIRS_ONLY,
00821                 COMBINE_SCANS_UNMAPPED,
00822                 ANTENNA_PAIR,
00823                 SUB_INTEGRATION,
00824                 ARRAY_FIELD
00825         };
00826 
00827         enum tableType {
00828 
00829                 MEASUREMENT_SET=0,
00830                 CALIBRATION_TABLE
00831         };
00832 
00833         // Default constructor
00834         // NOTE: Time interval 0 groups all time steps together in one chunk.
00835         FlagDataHandler(string msname, uShort iterationApproach = SUB_INTEGRATION, Double timeInterval = 0);
00836 
00837         // Default destructor
00838         virtual ~FlagDataHandler();
00839 
00840         // Common MS/CalTables public interface
00841         virtual bool open() {return false;}
00842         virtual bool close() {return false;}
00843         virtual bool selectData() {return false;}
00844         virtual bool generateIterator() {return false;}
00845         virtual bool nextChunk() {return false;}
00846         virtual bool nextBuffer() {return false;}
00847         virtual bool flushFlags() {return false;}
00848         virtual String getTableName() {return String("none");}
00849         virtual bool parseExpression(MSSelection &/*parser*/) {return true;}
00850         virtual bool checkIfColumnExists(String /*column*/) {return true;}
00851         virtual bool summarySignal() {return true;}
00852 
00853         // Set the iteration approach
00854         void setIterationApproach(uShort iterationApproach);
00855 
00856         // Set Data Selection parameters
00857         bool setDataSelection(Record record);
00858 
00859         // Set time interval (also known as ntime)
00860         void setTimeInterval(Double timeInterval);
00861 
00862         // Methods to switch on/off async i/o
00863         void enableAsyncIO(Bool enable);
00864 
00865         // Pre-Load columns (in order to avoid parallelism problems when not using
00866         // async i/o, and also to know what columns to pre-fetch in async i/o mode)
00867         void preLoadColumn(VisBufferComponent2 column);
00868         void preFetchColumns();
00869 
00870         // Stop iterating
00871         void stopIteration() {stopIteration_p = true;};
00872 
00873         // As requested by Urvashi R.V. provide access to the original and modified flag cubes
00874         Cube<Bool> * getModifiedFlagCube() {return &modifiedFlagCube_p;}
00875         Cube<Bool> * getOriginalFlagCube() {return &originalFlagCube_p;}
00876         Vector<Bool> * getModifiedFlagRow() {return &modifiedFlagRow_p;}
00877         Vector<Bool> * getOriginalFlagRow() {return &originalFlagRow_p;}
00878 
00879         // Functions to switch on/off mapping functions
00880         void setMapAntennaPairs(bool activated);
00881         void setMapSubIntegrations(bool activated);
00882         void setMapPolarizations(bool activated);
00883         void setMapAntennaPointing(bool activated);
00884         void setScanStartStopMap(bool activated);
00885         void setScanStartStopFlaggedMap(bool activated);
00886     void setTimeAverageIter(bool activated);
00887     void setChanAverageIter(Vector<Int> chanbin);
00888 
00889         // Accessors for the mapping functions
00890         antennaPairMap * getAntennaPairMap() {return antennaPairMap_p;}
00891         subIntegrationMap * getSubIntegrationMap() {return subIntegrationMap_p;}
00892         polarizationMap * getPolarizationMap() {return polarizationMap_p;}
00893         polarizationIndexMap * getPolarizationIndexMap() {return polarizationIndexMap_p;}
00894         antennaPointingMap * getMapAntennaPointing() {return antennaPointingMap_p;}
00895         scanStartStopMap * getMapScanStartStop() {return scanStartStopMap_p;}
00896         lambdaMap * getLambdaMap() {return lambdaMap_p;}
00897 
00898         void setProfiling(Bool value) {profiling_p=value;}
00899 
00900         // Get a Float visCube and return a Complex one
00901         Cube<Complex>& weightVisCube();
00902         Cube<Complex> weight_spectrum_p;
00903 
00904         // Make the logger public to that we can use it from FlagAgentBase::create
00905         casa::LogIO *logger_p;
00906 
00907         // Measurement set section
00908         String tablename_p;
00909         MSSelection *measurementSetSelection_p;
00910         Vector<String> *antennaNames_p;
00911         std::map< string, std::pair<Int,Int> > baselineToAnt1Ant2_p;
00912         std::map< std::pair<Int,Int>, string > Ant1Ant2ToBaseline_p;
00913         ROScalarMeasColumn<MPosition> *antennaPositions_p;
00914         Vector<Double> *antennaDiameters_p;
00915         Vector<String> *fieldNames_p;
00916         std::vector<String> *corrProducts_p;
00917 
00918         // RO Visibility Iterator
00919         VisBufferComponents2 *prefetchColumns_p;
00920         // Iteration counters
00921         uLong processedRows;
00922         uShort chunkNo;
00923         uShort bufferNo;
00924 
00925         // FlagDataHanler-FlagAgents interaction
00926         bool flushFlags_p;
00927         bool flushFlagRow_p;
00928         uInt64 chunkCounts_p;
00929         uInt64 progressCounts_p;
00930         uInt64 msCounts_p;
00931         uShort summaryThreshold_p;
00932         bool printChunkSummary_p;
00933         uShort tableTye_p;
00934         Bool loadProcessorTable_p;
00935 
00936         // PROCESSOR sub-table section
00937         Vector<Bool> isCorrelatorType_p;
00938         bool processorTableExist_p;
00939 
00940 
00941         // Visibility Buffer
00942         // WARNING: The attach mechanism only works with pointers or
00943         // referenced variables. Otherwise the VisBuffer is created
00944         // and attached, but when it is assigned to the member it is
00945         // detached because of the dynamically called destructor
00946         vi::VisBuffer2 *visibilityBuffer_p;
00947 
00948         // Vis buffer characteristics (constant values)
00949         bool groupTimeSteps_p;
00950         Block<int> sortOrder_p;
00951 
00952     // Time average iterator parameters
00953     Bool enableTimeAvg_p;
00954     Bool enableChanAvg_p;
00955     Double timeAverageBin_p;
00956     Vector <Int> chanAverageBin_p;
00957     String dataColumnType_p;
00958     vi::AveragingOptions timeAvgOptions_p;
00959     Record chanAvgOptions_p;
00960 
00961 protected:
00962 
00963         // Common MS/CalTables private interface
00964         virtual void generateAntennaPairMap();
00965         virtual void generateSubIntegrationMap();
00966         virtual void generatePolarizationsMap();
00967         virtual void generateAntennaPointingMap();
00968         virtual void generateScanStartStopMap();
00969 
00970         // Data Selection ranges
00971         bool anySelection_p;
00972         bool inrowSelection_p;
00973         casa::String arraySelection_p;
00974         casa::String fieldSelection_p;
00975         casa::String scanSelection_p;
00976         casa::String timeSelection_p;
00977         casa::String spwSelection_p;
00978         casa::String baselineSelection_p;
00979         casa::String uvwSelection_p;
00980         casa::String polarizationSelection_p;
00981         casa::String scanIntentSelection_p;
00982         casa::String observationSelection_p;
00983 
00984         // Async I/O stuff
00985         bool asyncio_enabled_p;
00986         // Pre-Load columns (in order to avoid parallelism problems when not using
00987         // async i/o, and also to know what columns to pre-fetch in async i/o mode)
00988         vector<VisBufferComponent2> preLoadColumns_p;
00989 
00990         // Iteration parameters
00991         uShort iterationApproach_p;
00992         Double timeInterval_p;
00993         // Slurp flag
00994         bool slurp_p;
00995         // Iteration initialization parameters
00996         bool chunksInitialized_p;
00997         bool buffersInitialized_p;
00998         bool iteratorGenerated_p;
00999         bool stopIteration_p;
01000 
01001         // Flag Cubes
01002         Cube<Bool> originalFlagCube_p;
01003         Cube<Bool> modifiedFlagCube_p;
01004 
01005         // FlagRows
01006         Vector<Bool> originalFlagRow_p;
01007         Vector<Bool> modifiedFlagRow_p;
01008 
01009         // Mapping members
01010         antennaPairMap *antennaPairMap_p;
01011         subIntegrationMap *subIntegrationMap_p;
01012         polarizationMap *polarizationMap_p;
01013         polarizationIndexMap *polarizationIndexMap_p;
01014         antennaPointingMap *antennaPointingMap_p;
01015         scanStartStopMap *scanStartStopMap_p;
01016         lambdaMap *lambdaMap_p;
01017         bool mapAntennaPairs_p;
01018         bool mapSubIntegrations_p;
01019         bool mapPolarizations_p;
01020         bool mapAntennaPointing_p;
01021         bool mapScanStartStop_p;
01022         bool mapScanStartStopFlagged_p;
01023 
01024         // Stats members
01025         bool stats_p;
01026         uLong cubeAccessCounter_p;
01027         double cubeAccessTime_p;
01028         uLong cubeAccessCounterTotal_p;
01029         double cubeAccessTimeTotal_p;
01030 
01031         // Profiling
01032         bool profiling_p;
01033 
01034 
01035 
01036 };
01037 
01038 } //# NAMESPACE CASA - END
01039 
01040 #endif /* FLAGDATAHANDLER_H_ */
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines

Generated on 31 Aug 2016 for casa by  doxygen 1.6.1