casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines
VisibilityIterator.h
Go to the documentation of this file.
00001 //# VisibilityIterator.h: Step through the MeasurementEquation by visibility
00002 //# Copyright (C) 1996,1997,1998,1999,2000,2001,2002,2003
00003 //# Associated Universities, Inc. Washington DC, USA.
00004 //#
00005 //# This library is free software; you can redistribute it and/or modify it
00006 //# under the terms of the GNU Library General Public License as published by
00007 //# the Free Software Foundation; either version 2 of the License, or (at your
00008 //# option) any later version.
00009 //#
00010 //# This library is distributed in the hope that it will be useful, but WITHOUT
00011 //# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
00012 //# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
00013 //# License for more details.
00014 //#
00015 //# You should have received a copy of the GNU Library General Public License
00016 //# along with this library; if not, write to the Free Software Foundation,
00017 //# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
00018 //#
00019 //# Correspondence concerning AIPS++ should be addressed as follows:
00020 //#        Internet email: aips2-request@nrao.edu.
00021 //#        Postal address: AIPS++ Project Office
00022 //#                        National Radio Astronomy Observatory
00023 //#                        520 Edgemont Road
00024 //#                        Charlottesville, VA 22903-2475 USA
00025 //#
00026 //# $Id: VisibilityIterator.h,v 19.14 2006/02/28 04:48:58 mvoronko Exp $
00027 
00028 #ifndef MSVIS_VISIBILITYITERATOR_H
00029 #define MSVIS_VISIBILITYITERATOR_H
00030 
00031 #include <casa/Arrays/Cube.h>
00032 #include <casa/Arrays/Matrix.h>
00033 #include <casa/Arrays/Slicer.h>
00034 #include <casa/BasicSL/String.h>
00035 #include <casa/Containers/Stack.h>
00036 #include <casa/Containers/RecordInterface.h>
00037 #include <casa/Quanta/MVDoppler.h>
00038 #include <casa/aips.h>
00039 #include <measures/Measures/MCDoppler.h>
00040 #include <measures/Measures/MDoppler.h>
00041 #include <measures/Measures/MeasConvert.h>
00042 #include <measures/Measures/Stokes.h>
00043 #include <ms/MeasurementSets/MSDerivedValues.h>
00044 #include <ms/MeasurementSets/MSIter.h>
00045 #include <ms/MeasurementSets/MeasurementSet.h>
00046 #include <scimath/Mathematics/RigidVector.h>
00047 #include <scimath/Mathematics/SquareMatrix.h>
00048 #include <synthesis/MSVis/StokesVector.h>
00049 #include <synthesis/MSVis/VisBufferComponents.h>
00050 #include <synthesis/MSVis/VisImagingWeight.h>
00051 #include <tables/Tables/ArrayColumn.h>
00052 #include <tables/Tables/ScalarColumn.h>
00053 
00054 #include <map>
00055 #include <set>
00056 #include <vector>
00057 
00058 namespace casa { //# NAMESPACE CASA - BEGIN
00059 
00060 //# forward decl
00061 
00062 namespace asyncio {
00063 
00064 class VLAT;
00065 
00066 // <summary>
00067 // The PrefetchColumns class is used to specify a set of columns that
00068 // can be prefetched when the (RO)VisibilityIterator is using asynchronous
00069 // I/O.
00070 // </summary>
00071 //
00072 // <synopsis>
00073 // When creating an ROVisibilityIterator or VisibilityIterator that can
00074 // potentially operate using asynchronous I/O it is necessary to specify
00075 // which columns of the main table are to be prefetched by the lookahead
00076 // thread.  This class provides the way to specify those columns.  The
00077 // class is an STL set object of enum values defined in VisBufferComponents.h.
00078 // These roughly correspond to the different components that can be access
00079 // via a VisBuffer.
00080 //
00081 // </synopsis>
00082 //
00083 // <example>
00084 // This is a simple example showing the construction of a PrefetchColumns
00085 // and its use in a VisibilityIterator constructor.  For more complex cases
00086 // (e.g., where the columns to be prefetched depend on other factors) the
00087 // class provides some additional utility methods.
00088 //
00089 // Usually the file that creates the VI will include VisBuffer which will
00090 // then include VisBufferComponents.h; if not then the user will also need
00091 // to add "#include <synthesis/MSVis/VisBufferComponents.h>" to their file.
00092 //
00093 // <code>
00094 //    asyncio::PrefetchColumns prefetchColumns =
00095 //            PrefetchColumns::prefetchColumns (VisBufferComponents::Ant1,
00096 //                                              VisBufferComponents::Ant2,
00097 //                                              VisBufferComponents::ArrayId,
00098 //                                              VisBufferComponents::Direction1,
00099 //                                              VisBufferComponents::Direction2,
00100 //                                              VisBufferComponents::Feed1,
00101 //                                              VisBufferComponents::Feed1_pa,
00102 //                                              VisBufferComponents::Feed2,
00103 //                                              VisBufferComponents::Feed2_pa,
00104 //                                              VisBufferComponents::FieldId,
00105 //                                              VisBufferComponents::FlagCube,
00106 //                                              VisBufferComponents::Flag,
00107 //                                              VisBufferComponents::FlagRow,
00108 //                                              VisBufferComponents::Freq,
00109 //                                              VisBufferComponents::NChannel,
00110 //                                              VisBufferComponents::NCorr,
00111 //                                              VisBufferComponents::NRow,
00112 //                                              VisBufferComponents::ObservedCube,
00113 //                                              VisBufferComponents::PhaseCenter,
00114 //                                              VisBufferComponents::PolFrame,
00115 //                                              VisBufferComponents::SpW,
00116 //                                              VisBufferComponents::Time,
00117 //                                              VisBufferComponents::Uvw,
00118 //                                              VisBufferComponents::UvwMat,
00119 //                                              VisBufferComponents::Weight,
00120 //                                              -1);
00121 //
00122 //     wvi_p = new VisibilityIterator (& prefetchColumns, * wvi_p);
00123 //
00124 //
00125 // </code>
00126 //
00127 // </example
00128 class PrefetchColumns : public std::set<VisBufferComponents::EnumType>{
00129 
00130 public:
00131 
00132     PrefetchColumns operator+ (const PrefetchColumns & other);
00133 
00134     static String columnName (Int id);
00135     static PrefetchColumns prefetchColumnsAll ();
00136     static PrefetchColumns prefetchAllColumnsExcept (Int firstColumn, ...);
00137     static PrefetchColumns prefetchColumns (Int firstColumn, ...);
00138 };
00139 
00140 } // end namespace asyncio
00141 
00142 class VisBuffer;
00143 class VisibilityIteratorReadImpl;
00144 class VisibilityIteratorWriteImpl;
00145 
00146 class SubChunkPair : public std::pair<Int, Int>{
00147 
00148 public:
00149 
00150     // First component is Chunk and second is subchunk
00151 
00152     SubChunkPair () { resetToOrigin ();}
00153     SubChunkPair (Int a , Int b) : pair<Int,Int> (a,b) {}
00154 
00155     Bool operator== (const SubChunkPair & other){
00156         return first == other.first && second == other.second;
00157     }
00158 
00159     Bool operator< (const SubChunkPair & other){
00160         return first < other.first ||
00161                (first == other.first && second < other.second);
00162     }
00163 
00164     Bool atOrigin () const { return * this == SubChunkPair ();}
00165     Int chunk () const { return first;}
00166     void incrementSubChunk () { second ++;}
00167     void incrementChunk () { first ++; second = 0; }
00168 
00169     void resetSubChunk () { second = 0;} // position to start of chunk
00170 
00171     void resetToOrigin () { first = 0; second = 0; }
00172        // Make a subchunk pair that is positioned to the first subchunk of the
00173        // first chunk (i.e., 0,0)
00174 
00175     Int subchunk () const { return second;}
00176     String toString () const;
00177 
00178     static SubChunkPair noMoreData ();
00179 
00180 private:
00181 
00182 
00183 };
00184 
00185 
00186 // <summary>
00187 // ROVisibilityIterator iterates through one or more readonly MeasurementSets
00188 // </summary>
00189 // <use visibility=export>
00190 // <reviewed reviewer="" date="yyyy/mm/dd" tests="" demos="">
00191 // </reviewed>
00192 // <prerequisite>
00193 //   <li> <linkto class="MSIter">MSIter</linkto>
00194 //   <li> <linkto class="MeasurementSet">MeasurementSet</linkto>
00195 //   <li> <linkto class="VisSet">VisSet</linkto>
00196 //   <li> <linkto class="PrefetchColumns">PrefetchColumns</linkto>
00197 // </prerequisite>
00198 //
00199 // <etymology>
00200 // The ROVisibilityIterator is a readonly iterator returning visibilities
00201 // </etymology>
00202 //
00203 // <synopsis>
00204 // ROVisibilityIterator provides iteration with various sort orders
00205 // for one or more MSs. It has member functions to retrieve the fields
00206 // commonly needed in synthesis calibration and imaging.
00207 //
00208 // One should use <linkto class="VisBuffer">VisBuffer</linkto>
00209 // to access chunks of data.
00210 //
00211 // ROVisibilityIterators can be either synchronous or asynchronous, depending
00212 // on the constructor used to create them as well as the current value of
00213 // a CASARC file setting.  A synchronous instance is works the same as
00214 // this class ever worked; an asynchronous instance uses a second thread
00215 // (the Visibility Lookahead Thread or VLAT) to fill the VisBuffers in
00216 // advance of their use by the original thread.
00217 //
00218 // To create an asynchronous instance of ROVI you must use one of the two
00219 // constructors which have a pointer to a PrefetchColumns object as the
00220 // first argument.  This object specifies which table columns should be
00221 // prefetched by the VLAT; accessing columns not specified in the PrefetchColumns
00222 // object will result in an exception containing an error message indicating
00223 // that a the VisBuffer does not contain the requested column.  In addition
00224 // to using the appropriate constructor, the CASARC file setting
00225 // VisibilityIterator.
00226 //
00227 // +-------------------+
00228 // |                   |
00229 // | *** Nota Bene *** |
00230 // |                   |
00231 // +-------------------+
00232 //
00233 // Because of the multithreaded nature of asynchronous I/O, the user
00234 // needs to be a bit more careful in the use of the VI and it's attached VisBuffer.
00235 // Data access operations need to be directed to the VisBuffer.  Additionally
00236 // the user must not attempt to access the data using a separate VI since
00237 // the underlying casacore objects are not threadsafe and bizarre errors
00238 // will likely occur.
00239 //
00240 // CASARC Settings
00241 // ===============
00242 //
00243 // Normal settings
00244 // ---------------
00245 //
00246 // VisibilityIterator.async.enabled - Boolean value that enables or disables
00247 //     async I/O.  The default value is currently False (i.e., disabled).
00248 // VisibilityIterator.async.nBuffers - The number of lookahead buffers.  This
00249 //     defaults to 2.
00250 //
00251 //
00252 // Debug settings
00253 // --------------
00254 //
00255 // VisibilityIterator.async.doStats: true
00256 // VisibilityIterator.async.debug.logFile: stderr
00257 // VisibilityIterator.async.debug.logLevel: 1
00258 //
00259 
00260 // </synopsis>
00261 //
00262 // <example>
00263 // <code>
00264 // //
00265 // </code>
00266 // </example>
00267 //
00268 // <motivation>
00269 // For imaging and calibration you need to access an MS in some consistent
00270 // order (by field, spectralwindow, time interval etc.). This class provides
00271 // that access.
00272 // </motivation>
00273 //
00274 // <thrown>
00275 //    <li>
00276 //    <li>
00277 // </thrown>
00278 //
00279 // <todo asof="1997/05/30">
00280 //   <li> cleanup the currently dual interface for visibilities and flags
00281 //   <li> sort out what to do with weights when interpolating
00282 // </todo>
00283 class ROVisibilityIterator
00284 {
00285     friend class AsyncEnabler;
00286     friend class VisibilityIteratorReadImpl;
00287     friend class ViReadImplAsync;
00288     friend class asyncio::VLAT; // allow VI lookahead thread class to access protected functions
00289                                 // VLAT should not access private parts, especially variables
00290 public:
00291 
00292   class Factory {
00293 
00294   public:
00295 
00296       virtual ~Factory () {}
00297 
00298       virtual VisibilityIteratorReadImpl *
00299       operator() (const asyncio::PrefetchColumns * /*prefetchColumns*/,
00300                   const Block<MeasurementSet>& /*mss*/,
00301                   const Block<Int>& /*sortColumns*/,
00302                   const Bool /*addDefaultSortCols*/,
00303                   Double /*timeInterval*/) const
00304       {
00305           return NULL;
00306       }
00307   };
00308 
00309   //# the following is a copy of the enum in MSIter
00310   //# can't think of a way to get one that known to the outside world from here
00311   enum PolFrame {
00312     // Circular polarization
00313     Circular=0,
00314     // Linear polarization
00315     Linear=1
00316   };
00317 
00318   typedef enum DataColumn {
00319       Observed=0,  // Observed data
00320       Model,       // Model data
00321       Corrected    // Corrected data
00322   } DataColumn;
00323 
00324   class AsyncEnabler {
00325   public:
00326       AsyncEnabler (ROVisibilityIterator &);
00327       AsyncEnabler (ROVisibilityIterator *);
00328       ~AsyncEnabler ();
00329       void release ();
00330   private:
00331       Bool oldEnabledState_p;
00332       ROVisibilityIterator * roVisibilityIterator_p;
00333   };
00334 
00335   // Default constructor - useful only to assign another iterator later
00336   ROVisibilityIterator();
00337   // Construct from an MS and a Block of MS column enums specifying the 
00338   // iteration order.  If no order is specified, it uses the default sort
00339   // order of MSIter, which is not necessarily the raw order of ms!
00340   // The default ordering is ARRAY_ID, FIELD_ID, DATA_DESC_ID,
00341   // and TIME, but check MSIter.h to be sure.
00342   // These columns will be added first if they are not specified.
00343   //
00344   // An optional timeInterval (in seconds) can be given to iterate through
00345   // chunks of time.  The default interval of 0 groups all times together.
00346   // Every 'chunk' of data contains all data within a certain time interval and
00347   // with identical values of the other iteration columns (e.g.  DATA_DESC_ID
00348   // and FIELD_ID).  Using selectChannel(), a number of groups of channels can
00349   // be requested.  At present the channel group iteration will always occur
00350   // before the interval iteration.
00351   ROVisibilityIterator(const MeasurementSet& ms, 
00352                        const Block<Int>& sortColumns,
00353                        Double timeInterval=0,
00354                        const Factory & factory = Factory());
00355   // Same as above, but with the option of using the raw order of ms
00356   // (addDefaultSortCols=false).
00357   ROVisibilityIterator(const MeasurementSet& ms, 
00358                        const Block<Int>& sortColumns,
00359                        const Bool addDefaultSortCols,
00360                        Double timeInterval=0);
00361  
00362   // Same as previous constructors, but with multiple MSs to iterate over.
00363   ROVisibilityIterator(const Block<MeasurementSet>& mss,
00364                        const Block<Int>& sortColumns, 
00365                        Double timeInterval=0);
00366 
00367   ROVisibilityIterator(const Block<MeasurementSet>& mss,
00368                        const Block<Int>& sortColumns,
00369                        const Bool addDefaultSortCols,
00370                        Double timeInterval=0);
00371 
00372   ROVisibilityIterator(const asyncio::PrefetchColumns * prefetchColumns,
00373                        const MeasurementSet& ms,
00374                        const Block<Int>& sortColumns,
00375                        const Bool addDefaultSortCols = True,
00376                        Double timeInterval = 0);
00377 
00378   ROVisibilityIterator (const asyncio::PrefetchColumns * prefetchColumns,
00379                         const Block<MeasurementSet>& mss,
00380                         const Block<Int>& sortColumns,
00381                         const Bool addDefaultSortCols = True,
00382                         Double timeInterval = 0);
00383 
00384   // Copy construct. This calls the assigment operator.
00385   ROVisibilityIterator(const ROVisibilityIterator & other);
00386   ROVisibilityIterator(const asyncio::PrefetchColumns * prefetchColumns, const ROVisibilityIterator & other);
00387   // Assigment. Any attached VisBuffers are lost in the assign.
00388   ROVisibilityIterator & operator=(const ROVisibilityIterator &other);
00389   // Destructor
00390   virtual ~ROVisibilityIterator();
00391   
00392 //  static ROVisibilityIterator * create (const MeasurementSet & ms,
00393 //                                        const Block<Int>& sortColumns,
00394 //                                        const asyncio::PrefetchColumns * prefetchColumns = NULL,
00395 //                                        const Bool addDefaultSortCols = True,
00396 //                                        Double timeInterval=0);
00397 //
00398 //  static ROVisibilityIterator * create (const Block<MeasurementSet>& mss,
00399 //                                        const Block<Int>& sortColumns,
00400 //                                        const asyncio::PrefetchColumns * prefetchColumns = NULL,
00401 //                                        const Bool addDefaultSortCols = True,
00402 //                                        Double timeInterval=0);
00403 //
00404 //  static ROVisibilityIterator * create (const ROVisibilityIterator & rovi,
00405 //                                        const asyncio::PrefetchColumns * prefetchColumns,
00406 //                                        Int nReadAheadBuffers = 2);
00407 
00408   // Members
00409   
00410   Bool isAsynchronous () const;
00411   static Bool isAsynchronousIoEnabled();
00412 
00413   Bool isAsyncEnabled () const;
00414   Bool isWritable () const;
00415   // Reset iterator to origin/start of data (of current chunk)
00416   void origin();
00417   // Reset iterator to true start of data (first chunk)
00418   void originChunks();
00419  
00420   // Return the time interval (in seconds) used for iteration.
00421   // This is not the same as the INTERVAL column.
00422   Double getInterval() const;
00423   // Set or reset the time interval (in seconds) to use for iteration.
00424   // You should call originChunks() to reset the iteration after 
00425   // calling this.
00426   void setInterval(Double timeInterval);
00427 
00428   // Set the 'blocking' size for returning data.
00429   // With the default (0) only a single integration is returned at a time, this
00430   // is what is currently required for the calibration software. With blocking
00431   // set, up to nRows can be returned in one go. The chunk 
00432   // size determines the actual maximum.
00433   void setRowBlocking(Int nRows=0);
00434   // Return False if no more data (in current chunk)
00435   Bool more() const;
00436   SubChunkPair getSubchunkId () const;
00437   // Advance iterator through data
00438   ROVisibilityIterator & operator++(int);
00439   ROVisibilityIterator & operator++();
00440   // Return False if no more 'Chunks' of data left
00441   Bool moreChunks() const;
00442   // Check if ms has change since last iteration
00443   Bool newMS() const;
00444   Int msId() const;
00445   VisBuffer * getVisBuffer ();
00446   //reference to actual ms in interator 
00447   const MeasurementSet& ms() const;
00448  // Advance to the next Chunk of data
00449   ROVisibilityIterator& nextChunk();
00450   // Return antenna1
00451   Vector<Int>& antenna1(Vector<Int>& ant1) const;
00452   // Return antenna2
00453   Vector<Int>& antenna2(Vector<Int>& ant2) const;
00454   // Return feed1
00455   Vector<Int>& feed1(Vector<Int>& fd1) const;
00456   // Return feed2
00457   Vector<Int>& feed2(Vector<Int>& fd2) const;
00458   // Return channel numbers in selected VisSet spectrum
00459   // (i.e. disregarding possible selection on the iterator, but
00460   //  including the selection set when creating the VisSet)
00461   virtual Vector<Int>& channel(Vector<Int>& chan) const;
00462   // Return feed configuration matrix for specified antenna
00463   Vector<SquareMatrix<Complex,2> >& 
00464   CJones(Vector<SquareMatrix<Complex,2> >& cjones) const;
00465   // Return receptor angles for all antennae and feeds
00466   // First axis of the cube is a receptor number,
00467   // 2nd is antennaId, 3rd is feedId
00468   // Note: the method is intended to provide an access to MSIter::receptorAngles
00469   // for VisBuffer in the multi-feed case. It may be worth to change the
00470   // interface of feed_pa to return the information for all feeds.
00471   const Cube<Double>& receptorAngles() const;
00472   // return a string mount identifier for each antenna
00473   const Vector<String>& antennaMounts() const;
00474   // Return a cube containing pairs of coordinate offsets for each
00475   // receptor of each feed (values are in radians, coordinate system is fixed
00476   // with antenna and is the same one as used to define the BEAM_OFFSET 
00477   // parameter in the feed table). The cube axes are receptor, antenna, feed.
00478   const Cube<RigidVector<Double, 2> >& getBeamOffsets() const;
00479   // True if all elements of the cube returned by getBeamOffsets are zero
00480   Bool allBeamOffsetsZero() const;
00481   // Return feed parallactic angles Vector(nant) (1 feed/ant)
00482   Vector<Float> feed_pa(Double time) const;
00483   static Vector<Float> feed_paCalculate(Double time, MSDerivedValues & msd,
00484                                                                             Int nAntennas, const MEpoch & mEpoch0,
00485                                                                             const Vector<Float> & receptor0Angle);
00486   // Return nominal parallactic angle at specified time
00487   // (does not include feed position angle offset--see feed_pa)
00488   // A global value for all antennas (e.g., small array)
00489   const Float& parang0(Double time) const;
00490   static Float parang0Calculate (Double time, MSDerivedValues & msd, const MEpoch & epoch0);
00491   // Per antenna:
00492   Vector<Float> parang(Double time) const;
00493   static Vector<Float> parangCalculate (Double time, MSDerivedValues & msd,
00494                                                 int nAntennas, const MEpoch mEpoch0);
00495   // Return the antenna AZ/EL Vector(nant) 
00496   MDirection azel0(Double time) const;
00497   static void azel0Calculate (Double time, MSDerivedValues & msd,
00498                                       MDirection & azel0, const MEpoch & mEpoch0);
00499   Vector<MDirection> azel(Double time) const;
00500   static void azelCalculate (Double time, MSDerivedValues & msd, Vector<MDirection> & azel,
00501                                      Int nAnt, const MEpoch & mEpoch0);
00502   // Return the hour angle for the specified time
00503   Double hourang(Double time) const;
00504   static Double hourangCalculate (Double time, MSDerivedValues & msd, const MEpoch & mEpoch0);
00505   // Return the current FieldId
00506   Int fieldId() const;
00507   // Return the current ArrayId
00508   Int arrayId() const;
00509   // Return the current Field Name
00510   String fieldName() const;
00511   // Return the current Source Name
00512   String sourceName() const;
00513   // Return flag for each polarization, channel and row
00514   virtual Cube<Bool>& flag(Cube<Bool>& flags) const;
00515   // Return flag for each channel & row
00516   Matrix<Bool>& flag(Matrix<Bool>& flags) const;
00517 
00518   // Determine whether FLAG_CATEGORY is valid.
00519   Bool existsFlagCategory() const;
00520 
00521   // Return flags for each polarization, channel, category, and row.
00522   Array<Bool>& flagCategory(Array<Bool>& flagCategories) const;
00523   // Return row flag
00524   Vector<Bool>& flagRow(Vector<Bool>& rowflags) const;
00525   // Return scan number
00526   Vector<Int>& scan(Vector<Int>& scans) const;
00527   // Return the OBSERVATION_IDs
00528   Vector<Int>& observationId(Vector<Int>& obsids) const;
00529   // Return the PROCESSOR_IDs
00530   Vector<Int>& processorId(Vector<Int>& procids) const;
00531   // Return the STATE_IDs
00532   Vector<Int>& stateId(Vector<Int>& stateids) const;
00533   // Return current frequencies (in Hz, acc. to the MS def'n v.2)
00534   virtual Vector<Double>& frequency(Vector<Double>& freq) const;
00535   // Return frequencies  (in Hz, acc. to the MS def'n v.2) in selected velocity frame,
00536   // returns the same as frequency() if there is no vel selection active.
00537   Vector<Double>& lsrFrequency(Vector<Double>& freq) const;
00538   // Return the current phase center as an MDirection
00539   const MDirection& phaseCenter() const;
00540   // Return frame for polarization (returns PolFrame enum)
00541   Int polFrame() const;
00542   // Return the correlation type (returns Stokes enums)
00543   virtual Vector<Int>& corrType(Vector<Int>& corrTypes) const;
00544   // Return sigma
00545   Vector<Float>& sigma(Vector<Float>& sig) const;
00546   // Return sigma matrix (pol-dep)
00547   virtual Matrix<Float>& sigmaMat(Matrix<Float>& sigmat) const;
00548   // Return current SpectralWindow
00549   Int spectralWindow() const;
00550   // Return current Polarization Id
00551   Int polarizationId() const;
00552   // Return current DataDescription Id
00553   Int dataDescriptionId() const;
00554   // Return MJD midpoint of interval.
00555   Vector<Double>& time(Vector<Double>& t) const;
00556   // Return MJD centroid of interval.
00557   Vector<Double>& timeCentroid(Vector<Double>& t) const;
00558   // Return nominal time interval
00559   Vector<Double>& timeInterval(Vector<Double>& ti) const;
00560   // Return actual time interval
00561   Vector<Double>& exposure(Vector<Double>& expo) const;
00562   // Return the visibilities as found in the MS, Cube(npol,nchan,nrow).
00563   virtual Cube<Complex>& visibility(Cube<Complex>& vis,
00564                                     DataColumn whichOne) const;
00565   // Return FLOAT_DATA as a Cube(npol, nchan, nrow) if found in the MS.
00566   Cube<Float>& floatData(Cube<Float>& fcube) const;
00567   // Return the visibility 4-vector of polarizations for each channel.
00568   // If the MS doesn't contain all polarizations, it is assumed it
00569   // contains one or two parallel hand polarizations.
00570   Matrix<CStokesVector>& visibility(Matrix<CStokesVector>& vis, 
00571                                     DataColumn whichOne) const;
00572   // Return the shape of the visibility Cube
00573   IPosition visibilityShape() const;
00574   // Return u,v and w (in meters)
00575   virtual Vector<RigidVector<Double,3> >& uvw(Vector<RigidVector<Double,3> >& uvwvec) const;
00576   Matrix<Double>& uvwMat(Matrix<Double>& uvwmat) const;
00577   // Return weight
00578   Vector<Float>& weight(Vector<Float>& wt) const;
00579   // Returns the nPol_p x curNumRow_p weight matrix
00580   virtual Matrix<Float>& weightMat(Matrix<Float>& wtmat) const;
00581   // Determine whether WEIGHT_SPECTRUM exists.
00582   Bool existsWeightSpectrum() const;
00583   // Return weightspectrum (a weight for each channel)
00584   Cube<Float>& weightSpectrum(Cube<Float>& wtsp) const;
00585   // Return imaging weight (a weight for each channel)
00586   //Matrix<Float>& imagingWeight(Matrix<Float>& wt) const;
00587   // Return True if FieldId/Source has changed since last iteration
00588   Bool newFieldId() const;
00589   // Return True if arrayID has changed since last iteration
00590   Bool newArrayId() const;
00591   // Return True if SpectralWindow has changed since last iteration
00592   Bool newSpectralWindow() const;
00593   // Return the index of the first channel of the current channel group 
00594   // in the total (selected) spectrum.
00595   Int channelIndex() const;
00596   // Return the width of the current group of channels, i.e.,
00597   // the number of channels returned by visibility() and frequency().
00598   Int channelGroupSize() const;
00599   
00600   // Return the number of correlations in the current iteration
00601   Int nCorr() const;;
00602   // Return the number of rows in the current iteration
00603   Int nRow() const;
00604   // Return the row ids as from the original root table. This is useful 
00605   // to find correspondance between a given row in this iteration to the 
00606   // original ms row
00607   virtual Vector<uInt>& rowIds(Vector<uInt>& rowids) const;
00608   // Return the numbers of rows in the current chunk
00609   Int nRowChunk() const;
00610   // Return the number of sub-intervals in the current chunk
00611   Int nSubInterval() const;
00612   // Call to use the slurp i/o method for all scalar columns. This
00613   // will set the BucketCache cache size to the full column length
00614   // and cause the full column to be cached in memory, if
00615   // any value of the column is used. In case of out-of-memory,
00616   // it will automatically fall-back on the smaller cache size.
00617   // Slurping the column is to be considered as a work-around for the
00618   // Table i/o code, which uses BucketCache and performs extremely bad
00619   // for random access. Slurping is useful when iterating non-sequentially
00620   // an MS or parts of an MS, it is not tested with multiple MSs.
00621   void slurp() const;
00622   // Velocity selection - specify the output channels in velocity:
00623   // nChan - number of output channels, vStart - start velocity,
00624   // vInc - velocity increment. So channel i will have velocity 
00625   // vStart + i*vInc (i=0,nChan-1).
00626   // Specify velocities as in e.g., MVRadialVelocity(Quantity(2001.,"km/s")).
00627   // The reference type and velocity definition are specified separately.
00628   // Note that no averaging is performed, the visibilities will be interpolated
00629   // and sampled at the specified velocities, it's up to you to choose a vInc
00630   // appropriate to the channel width.
00631   // The REST_FREQUENCY column in the SPECTRAL_WINDOW subtable is used to
00632   // determine the velocity-frequency conversion.
00633   // By default calculations are done for a single velocity with offsets 
00634   // applied for the others (ok for non-rel velocities with RADIO defn), 
00635   // set precise to True to do a full conversion for each output channel.(NYI)
00636   ROVisibilityIterator& 
00637   selectVelocity(Int nChan, 
00638                  const MVRadialVelocity& vStart, const MVRadialVelocity& vInc,
00639                  MRadialVelocity::Types rvType = MRadialVelocity::LSR,
00640                  MDoppler::Types dType = MDoppler::RADIO, Bool precise=False);
00641   // Select the velocity interpolation scheme.
00642   // At present the choice is limited to : nearest and linear, linear
00643   // is the default. 
00644   // TODO: add cubic, spline and possibly FFT
00645   ROVisibilityIterator& velInterpolation(const String& type);
00646   // Channel selection - only the selected channels will be returned by the
00647   // access functions. The default spectralWindow is the current one (or 0)
00648   // This allows selection of the input channels, producing
00649   // nGroup groups of width output channels. Default is to return all channels
00650   // in a single group.
00651   ROVisibilityIterator& selectChannel(Int nGroup=1, Int start=0, Int width=0, 
00652                                       Int increment=1, Int spectralWindow=-1);
00653   //Same as above except when multiple ms's are to be accessed
00654   ROVisibilityIterator& selectChannel(Block< Vector<Int> >& blockNGroup,
00655                                       Block< Vector<Int> >& blockStart,
00656                                       Block< Vector<Int> >& blockWidth,
00657                                       Block< Vector<Int> >& blockIncr,
00658                                       Block< Vector<Int> >& blockSpw);
00659   //get the channel selection ...the block over the number of ms's associated
00660   // with this iterator
00661   void getChannelSelection(Block< Vector<Int> >& blockNGroup,
00662                            Block< Vector<Int> >& blockStart,
00663                            Block< Vector<Int> >& blockWidth,
00664                            Block< Vector<Int> >& blockIncr,
00665                            Block< Vector<Int> >& blockSpw);
00666   // Translate slicesv from the form returned by MSSelection::getChanSlices()
00667   // to matv as used by setChanAveBounds().  widthsv is the channel averaging
00668   // width for each _selected_ spw.
00669   void slicesToMatrices(Vector<Matrix<Int> >& matv,
00670                         const Vector<Vector<Slice> >& slicesv,
00671                         const Vector<Int>& widthsv) const;
00672   // Get the spw, start  and nchan for all the ms's is this Visiter that 
00673   // match the frequecy "freqstart-freqStep" and "freqEnd+freqStep" range
00674   // Can help in doing channel selection above..
00675   // freqFrame is the frame the caller frequency values are in (freqStart and freqEnd)
00676   // These will be converted to the frame of the selected spw to match
00677   void getSpwInFreqRange(Block<Vector<Int> >& spw, 
00678                                  Block<Vector<Int> >& start, 
00679                                  Block<Vector<Int> >& nchan, 
00680                                  Double freqStart, Double freqEnd, 
00681                                  Double freqStep, MFrequency::Types freqFrame=MFrequency::LSRK);
00682 
00683   //Get the frequency range of the data selection
00684   void getFreqInSpwRange(Double& freqStart, Double& freqEnd, MFrequency::Types freqframe = MFrequency::LSRK);
00685 
00686   // Attach a VisBuffer object.
00687   // Note that while more than one VisBuffer may be attached, only the
00688   // last one is actively updated. A Stack is kept internally, so after 
00689   // a detach, the previous VisBuffer becomes active again.
00690   void attachVisBuffer(VisBuffer& vb);
00691   // Detach a VisBuffer object.
00692   // If the object detached is not the last one attached an exception
00693   // is thrown.
00694   void detachVisBuffer(VisBuffer& vb);
00695   // Access the current ROMSColumns object in MSIter
00696   const ROMSColumns& msColumns() const;
00697   // get back the selected spectral windows and spectral channels for
00698   // current ms 
00699   void allSelectedSpectralWindows(Vector<Int>& spws, Vector<Int>& nvischan);
00700   // Convert the frequency from the observe frame to lsr frame.
00701   // Returns True in convert if given spw was not observed 
00702   // in the LSRK frame
00703   //when ignoreconv=True...no conversion is done from data frame
00704   //frequency is served as is
00705   void lsrFrequency(const Int& spw, Vector<Double>& freq, Bool& convert, const  Bool ignoreconv=False);
00706   //assign a VisImagingWeight object to this iterator
00707   void useImagingWeight(const VisImagingWeight& imWgt);
00708   const VisImagingWeight & getImagingWeightGenerator () const;
00709 
00710   //return number  of Ant 
00711   Int numberAnt();
00712   //Return number of rows in all selected ms's
00713   Int numberCoh();
00714   // Return number of spws, polids, ddids
00715   Int numberSpw();
00716   Int numberPol();
00717   Int numberDDId();
00718 //  ROArrayColumn <Double> & getChannelFrequency () const;
00719 //  Block<Int> getChannelGroupNumber () const;
00720 //  Block<Int> getChannelIncrement () const;
00721 //  Block<Int> getChannelStart () const;
00722 //  Block<Int> getChannelWidth () const;
00723   Int getDataDescriptionId () const;
00724   const MeasurementSet & getMeasurementSet() const;;
00725   Int getMeasurementSetId() const;
00726   Int getNAntennas () const;
00727   MEpoch getEpoch () const;
00731   Vector<Float> getReceptor0Angle ();
00732   Vector<uInt> getRowIds () const;
00733 
00734   // Returns the columns that the VisibilityIterator is sorting by.
00735   const Block<Int>& getSortColumns() const;
00736 
00737   static void lsrFrequency (const Int& spw,
00738                             Vector<Double>& freq,
00739                             Bool & convert,
00740                             const Block<Int> & chanStart,
00741                             const Block<Int> & chanWidth,
00742                             const Block<Int> & chanInc,
00743                             const Block<Int> & numChanGroup,
00744                             const ROArrayColumn <Double> & chanFreqs,
00745                             const ROScalarColumn<Int> & obsMFreqTypes,
00746                             const MEpoch & ep,
00747                             const MPosition & obsPos,
00748                             const MDirection & dir);
00749 
00750   static String getAipsRcBase () { return "VisibilityIterator.async";}
00751 
00752 protected:
00753 
00754   ROVisibilityIterator (const asyncio::PrefetchColumns * prefetchColumns,
00755                         const Block<MeasurementSet>& mss,
00756                         const Block<Int>& sortColumns,
00757                         const Bool addDefaultSortCols,
00758                         Double timeInterval,
00759                         Bool writable);
00760 
00761   void construct (const asyncio::PrefetchColumns * prefetchColumns,
00762                   const Block<MeasurementSet>& mss,
00763                   const Block<Int>& sortColumns,
00764                   const Bool addDefaultSortCols,
00765                   Double timeInterval,
00766                   Bool writable,
00767                   const Factory & factory);
00768 
00769   VisibilityIteratorReadImpl * getReadImpl() const;
00770 
00771   bool existsColumn (VisBufferComponents::EnumType id) const;
00772   // advance the iteration
00773   virtual void advance();
00774   // set the currently selected table
00775   virtual void setSelTable();
00776   // set the iteration state
00777   void setState();
00778   // get the TOPO frequencies from the selected velocities and the obs. vel.
00779   void getTopoFreqs();
00780   void getTopoFreqs(Vector<Double> & lsrFreq, Vector<Double> & selFreq); // for async i/o
00781   void getLsrInfo (Block<Int> & channelGroupNumber,
00782                            Block<Int> & channelIncrement,
00783                            Block<Int> & channelStart,
00784                            Block<Int> & channelWidth,
00785                            MPosition & observatoryPositon,
00786                            MDirection & phaseCenter,
00787                            Bool & velocitySelection) const;
00788   std::vector<MeasurementSet> getMeasurementSets () const;
00789   const MSDerivedValues & getMSD () const; // for use by Async I/O *ONLY*
00790   // update the DATA slicer
00791   virtual void updateSlicer();
00792   // attach the column objects to the currently selected table
00793   virtual void attachColumns(const Table &t);
00794   // returns the table, to which columns are attached, 
00795   // can be overridden in derived classes
00796   virtual const Table attachTable() const;
00797   // get the (velocity selected) interpolated visibilities, flags and weights.
00798   // It is not really const at all (it seems to use This-> trickery so callers
00799   // like flag() can be declared const).
00800 //  void getInterpolatedVisFlagWeight(DataColumn whichOne) const;
00801   // get the (velocity selected) interpolated FLOAT_DATA (as real Floats),
00802   // flags and weights.
00803 //  void getInterpolatedFloatDataFlagWeight() const;
00804   // get the visibility data (observed, corrected or model);
00805   // deals with Float and Complex observed data (DATA or FLOAT_DATA)
00806   void getDataColumn(DataColumn whichOne, const Slicer& slicer, 
00807                              Cube<Complex>& data) const;
00808   void getDataColumn(DataColumn whichOne, Cube<Complex>& data) const;
00809   // get FLOAT_DATA as real Floats.
00810   void getFloatDataColumn(const Slicer& slicer, Cube<Float>& data) const;
00811   void getFloatDataColumn(Cube<Float>& data) const;
00812 
00813   void originChunks(Bool forceRewind);
00814   //Re-Do the channel selection in multi ms case 
00815   void doChannelSelection();
00816   //Set the tile cache size....when using slice access if tile cache size is 
00817   // not set memory usage can go wild.  Specifically, the caching scheme is
00818   // ephemeral and lives for that instance of setting the caching scheme.
00819   // 
00820   // If you don't set any then the defaults come into play and caches a few
00821   // tiles along every axis at the tile you requested...which is a waste when
00822   // say you know you want to proceed along the row axis for example...and in
00823   // fact now VisIter just reads one tile (thus the commenting in setTileCache)
00824   // and lets the OS do the caching rather than than having the table system
00825   // cache extra tiles.
00826   virtual void setTileCache();
00827   //Check if spw is in selected SPW for actual ms
00828   Bool isInSelectedSPW(const Int& spw);
00829   // Updates, if necessary, rowIds_p member for the current chunk
00830   void update_rowIds() const;
00831   void setAsyncEnabled (Bool enable);
00832   template<class T>
00833     void getColScalar(const ROScalarColumn<T> &column, Vector<T> &array, Bool resize) const;
00834   template<class T>
00835     void getColArray(const ROArrayColumn<T> &column, Array<T> &array, Bool resize) const;
00836   // column access functions, can be overridden in derived classes
00837   virtual void getCol(const ROScalarColumn<Bool> &column, Vector<Bool> &array, Bool resize = False) const;
00838   virtual void getCol(const ROScalarColumn<Int> &column, Vector<Int> &array, Bool resize = False) const;
00839   virtual void getCol(const ROScalarColumn<Double> &column, Vector<Double> &array, Bool resize = False) const;
00840   virtual void getCol(const ROArrayColumn<Bool> &column, Array<Bool> &array, Bool resize = False) const;
00841   virtual void getCol(const ROArrayColumn<Float> &column, Array<Float> &array, Bool resize = False) const;
00842   virtual void getCol(const ROArrayColumn<Double> &column, Array<Double> &array, Bool resize = False) const;
00843   virtual void getCol(const ROArrayColumn<Complex> &column, Array<Complex> &array, Bool resize = False) const;
00844   virtual void getCol(const ROArrayColumn<Bool> &column, const Slicer &slicer, Array<Bool> &array, Bool resize = False) const;
00845   virtual void getCol(const ROArrayColumn<Float> &column, const Slicer &slicer, Array<Float> &array, Bool resize = False) const;
00846   virtual void getCol(const ROArrayColumn<Complex> &column, const Slicer &slicer, Array<Complex> &array, Bool resize = False) const;
00847   //  void getCol(const String &colName, Array<Double> &array,
00848   //                      Array<Double> &all, Bool resize = False) const;
00849   //  void getCol(const String &colName, Vector<Bool> &array,
00850   //                      Vector<Bool> &all, Bool resize = False) const;
00851   //  void getCol(const String &colName, Vector<Int> &array,
00852   //                      Vector<Int> &all, Bool resize = False) const;
00853   //  void getCol(const String &colName, Vector<Double> &array,
00854   //                      Vector<Double> &all, Bool resize = False) const;
00855   template<class T>
00856   void swapyz(Cube<T>& out, const Cube<T>& in) const;
00857 
00858   VisibilityIteratorReadImpl * readImpl_p;
00859 };
00860 
00861 
00862 // <summary>
00863 // VisibilityIterator iterates through one or more writable MeasurementSets
00864 // </summary>
00865 // <use visibility=export>
00866 // <reviewed reviewer="" date="yyyy/mm/dd" tests="" demos="">
00867 // </reviewed>
00868 // <prerequisite>
00869 //   <li> <linkto class="ROVisibilityIterator">ROVisibilityIterator</linkto>
00870 // </prerequisite>
00871 //
00872 // <etymology>
00873 // The VisibilityIterator is a read/write iterator returning visibilities
00874 // </etymology>
00875 //
00876 // <synopsis>
00877 // VisibilityIterator provides iteration with various sort orders
00878 // for one or more MSs. It has member functions to retrieve the fields
00879 // commonly needed in synthesis calibration and imaging. It is 
00880 // derived from the read-only iterator
00881 // <linkto class="ROVisibilityIterator">ROVisibilityIterator</linkto>.
00882 //
00883 // One should use <linkto class="VisBuffer">VisBuffer</linkto>
00884 // to access chunks of data.
00885 //
00886 // As with an ROVI, a VI can be created to only utilize synchronous I/O
00887 // (the "normal" way) or it can potentially use asynchronous I/O.  To create
00888 // an asynchronous instance of VI requires using an appropriate constructor
00889 // (i.e., one that has PrefetchColumns * as its first argument) and setting
00890 // the CASARC setting "VisibilityIterator.async.disabled: False".
00891 //
00892 // When a write operation is performed using the various setX methods of an
00893 // asynchronous instance of this class, the data is shipped over to the VLAT
00894 // which writes out when it is not in the middle of performing a read ahead
00895 // of a VisBuffer.
00896 //
00897 // </synopsis>
00898 //
00899 // <example>
00900 // <code>
00901 // //
00902 // </code>
00903 // </example>
00904 //
00905 // <motivation>
00906 // For imaging and calibration you need to access an MS in some consistent
00907 // order (by field, spectralwindow, time interval etc.). This class provides
00908 // that access.
00909 // </motivation>
00910 //
00911 // #<thrown>
00912 //
00913 // #</thrown>
00914 //
00915 // <todo asof="1997/05/30">
00916 //   <li> cleanup the currently dual interface for visibilities and flags
00917 //   <li> sort out what to do with weights when interpolating
00918 // </todo>
00919 class VisibilityIterator : public ROVisibilityIterator
00920 {
00921 
00922     friend class VisibilityIteratorWriteImpl;
00923 
00924 public:
00925   // Constructors.
00926   // Note: The VisibilityIterator is not initialized correctly by default, you
00927   // need to call origin() before using it to iterate.
00928   VisibilityIterator();
00929   VisibilityIterator(MeasurementSet & ms, const Block<Int>& sortColumns, 
00930        Double timeInterval=0);
00931   VisibilityIterator(MeasurementSet & ms, const Block<Int>& sortColumns, 
00932                      const Bool addDefaultSortCols,
00933                      Double timeInterval=0);
00934   // Same as previous constructor, but with multiple MSs to iterate over.
00935   VisibilityIterator(const Block<MeasurementSet>& mss,
00936                        const Block<Int>& sortColumns, 
00937                        Double timeInterval=0);
00938   VisibilityIterator(const Block<MeasurementSet>& mss,
00939                      const Block<Int>& sortColumns, const Bool addDefaultSortCols, 
00940                        Double timeInterval=0);
00941   VisibilityIterator (const asyncio::PrefetchColumns * prefetchColumns,
00942                       const Block<MeasurementSet>& mss,
00943                       const Block<Int>& sortColumns,
00944                       const Bool addDefaultSortCols = True,
00945                       Double timeInterval = 0);
00946   VisibilityIterator (const asyncio::PrefetchColumns * prefetchColumns,
00947                       MeasurementSet & mss,
00948                       const Block<Int>& sortColumns,
00949                       const Bool addDefaultSortCols = True,
00950                       Double timeInterval = 0);
00951   VisibilityIterator(const VisibilityIterator & MSI);
00952   VisibilityIterator(const asyncio::PrefetchColumns * prefetchColumns, const VisibilityIterator & other);
00953 
00954   
00955   virtual ~VisibilityIterator();
00956 
00957   VisibilityIterator & operator=(const VisibilityIterator &MSI);
00958 
00959 
00960   // Members
00961   
00962   Bool isWritable () const;
00963 
00964   // Advance iterator through data
00965   VisibilityIterator & operator++(int);
00966   VisibilityIterator & operator++();
00967   // Set/modify the flags in the data.
00968   // This will flag all channels in the original data that contributed to
00969   // the output channel in the case of channel averaging.
00970   // All polarizations have the same flag value.
00971   void setFlag(const Matrix<Bool>& flag);
00972   // Set/modify the flags in the data.
00973   // This sets the flags as found in the MS, Cube(npol,nchan,nrow),
00974   // where nrow is the number of rows in the current iteration (given by
00975   // nRow()).
00976   virtual void setFlag(const Cube<Bool>& flag);
00977   // Set/modify the flag row column; dimension Vector(nrow)
00978   virtual void setFlagRow(const Vector<Bool>& rowflags);
00979 
00980   void setFlagCategory(const Array<Bool>& fc);
00981 
00982   // Set/modify the visibilities.
00983   // This is possibly only for a 'reference' MS which has a new DATA column.
00984   // The first axis of the matrix should equal the selected number of channels
00985   // in the original MS.
00986   // If the MS does not contain all polarizations, only the parallel
00987   // hand polarizations are used.
00988   void setVis(const Matrix<CStokesVector>& vis, DataColumn whichOne);
00989   // Set/modify the visibilities
00990   // This sets the data as found in the MS, Cube(npol,nchan,nrow).
00991   virtual void setVis(const Cube<Complex>& vis, DataColumn whichOne);
00992   // Set the visibility and flags, and interpolate from velocities if needed
00993   virtual void setVisAndFlag(const Cube<Complex>& vis, const Cube<Bool>& flag,
00994                              DataColumn whichOne);
00995   // Set/modify the weights
00996   void setWeight(const Vector<Float>& wt);
00997   // Set/modify the weightMat
00998   virtual void setWeightMat(const Matrix<Float>& wtmat);
00999   // Set/modify the weightSpectrum
01000   virtual void setWeightSpectrum(const Cube<Float>& wtsp);
01001   // Set/modify the Sigma
01002   void setSigma(const Vector<Float>& sig);
01003   // Set/modify the ncorr x nrow SigmaMat.
01004   void setSigmaMat(const Matrix<Float>& sigmat);
01005   
01006   //This puts a model into the descriptor of the current ms in the iterator
01007   //Set iscomponentlist to True if the record represent a componentlist
01008   //if False then it is a FTMachine Record that holds the model image 
01009   //note the spw and fields selected are going to be associated with this model
01010   //incremetal =True implies add the model to previous any existant model 
01011   //in the ms for the spw and fields 
01012   //false means any existant model will be replaces.
01013   void putModel(const RecordInterface& rec, Bool iscomponentlist=True, Bool incremental=False);
01014 
01015 
01016   void writeBack (VisBuffer *);
01017 
01018 protected:
01019 
01020   virtual void attachColumns(const Table &t);
01021 
01022   void construct ();
01023 
01024 
01025   VisibilityIteratorWriteImpl * getWriteImpl() const;
01026 
01027   void initializeBackWriters ();
01028 
01029   VisibilityIteratorWriteImpl * writeImpl_p;
01030 };
01031 
01032 } //# NAMESPACE CASA - END
01033 
01034 #ifndef AIPS_NO_TEMPLATE_SRC
01035 #include <synthesis/MSVis/VisibilityIterator.tcc>
01036 #endif //# AIPS_NO_TEMPLATE_SRC
01037 
01038 #endif