casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines
SubMS.h
Go to the documentation of this file.
00001 //# SubMS.h: this defines SubMS which creates a subset of an MS with some
00002 //# transformation
00003 //# Copyright (C) 1997,1998,1999,2000,2001,2003
00004 //# Associated Universities, Inc. Washington DC, USA.
00005 //#
00006 //# This library is free software; you can redistribute it and/or modify it
00007 //# under the terms of the GNU Library General Public License as published by
00008 //# the Free Software Foundation; either version 2 of the License, or (at your
00009 //# option) any later version.
00010 //#
00011 //# This library is distributed in the hope that it will be useful, but WITHOUT
00012 //# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
00013 //# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
00014 //# License for more details.
00015 //#
00016 //# You should have received a copy of the GNU Library General Public License
00017 //# along with this library; if not, write to the Free Software Foundation,
00018 //# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
00019 //#
00020 //# Correspondence concerning AIPS++ should be addressed as follows:
00021 //#        Internet email: aips2-request@nrao.edu.
00022 //#        Postal address: AIPS++ Project Office
00023 //#                        National Radio Astronomy Observatory
00024 //#                        520 Edgemont Road
00025 //#                        Charlottesville, VA 22903-2475 USA
00026 //#
00027 //#
00028 //# $Id$
00029 #include <ms/MeasurementSets/MeasurementSet.h>
00030 #include <ms/MeasurementSets/MSColumns.h>
00031 #include <ms/MeasurementSets/MSMainEnums.h>
00032 //#include <synthesis/MSVis/VisIterator.h>
00033 #include <synthesis/MSVis/VisBufferComponents.h>
00034 #include <casa/aips.h>
00035 #include <casa/Arrays/Array.h>
00036 #include <casa/Arrays/Vector.h>
00037 //#include <casa/Utilities/CountedPtr.h>
00038 #include <map>
00039 #include <set>
00040 #include <vector>
00041 #include <scimath/Mathematics/InterpolateArray1D.h>
00042 
00043 #include <mstransform/MSTransform/MSTransformDataHandler.h>
00044 
00045 
00046 #ifndef MSVIS_SUBMS_H
00047 namespace casa { //# NAMESPACE CASA - BEGIN
00048 
00049 #define MSVIS_SUBMS_H
00050 
00051 namespace subms {
00052 // Returns wt**-0.5 or -1, depending on whether wt is positive.
00053 // NOT a member function, so it can be easily passed to other functions
00054 // (i.e. arrayTransformInPlace).
00055 Double wtToSigma(Double wt);
00056 }
00057 
00058 // <summary>
00059 // SubMS provides functionalities to make a subset of an existing MS
00060 // </summary>
00061 
00062 // <visibility=export>
00063 
00064 // <reviewed reviewer="" date="yyyy/mm/dd" tests="" demos="">
00065 // </reviewed>
00066 
00067 // <prerequisite>
00068 //   <li> MeasurementSet
00069 // </prerequisite>
00070 //
00071 // <etymology>
00072 // SubMS ...from the SUBset of an MS
00073 // </etymology>
00074 //
00075 // <synopsis>
00076 // The order of operations (as in ms::split()) is:
00077 //      ctor
00078 //      setmsselect
00079 //      selectTime
00080 //      makeSubMS
00081 // </synopsis>
00082 
00083 // These forward declarations are so the corresponding .h files don't have to
00084 // be included in this .h file, but it's only worth it if a lot of other files
00085 // include this file.
00086 class MSSelection; // #include <ms/MeasurementSets/MSSelection.h>
00087 class VBRemapper;
00088 
00089   // // These typedefs are necessary because a<b::c> doesn't work.
00090   // typedef std::vector<uInt> uivector;
00091   // struct uIntCmp 
00092   // {
00093   //   bool operator()(const uInt i1, const uInt i2) const 
00094   //   {
00095   //     return i1 < i2;
00096   //   }
00097   // };
00098   // typedef std::map<const uInt, uivector, uIntCmp> ui2vmap;
00099 
00100 template<class T> class ROArrayColumn;
00101   Bool isAllColumns(const Vector<MS::PredefinedColumns>& colNames);
00102 
00103 class SubMS
00104 {
00105 
00106  // jagonzal: Allow TransformVisDataHandler to access protected methods and members of this class
00107  friend class MSTransformDataHandler;
00108 
00109  public:
00110 
00111   enum RegriddingAlternatives {
00112     useFFTShift = -100,   // needs input and output grid to have the same number of channels and be equidistant in freq.
00113     useLinIntThenFFTShift // for the case the input grid is not equidistant in frequency but the output grid is
00114   };
00115 
00116   enum asdmStManUseAlternatives {
00117     DONT,
00118     USE_FOR_DATA,
00119     USE_FOR_DATA_WEIGHT_SIGMA_FLAG
00120   };
00121 
00122   SubMS(String& theMS, Table::TableOption option = Table::Old);
00123   
00124   // construct from an MS
00125   SubMS(MeasurementSet& ms);
00126 
00127   virtual ~SubMS();
00128   
00129   // Change or Set the MS this MSSelector refers to.
00130   void setMS(MeasurementSet& ms);
00131 
00132   // Returns the set (possibly empty) of spectral windows that are in spwv but
00133   // not listed in ms's DATA_DESCRIPTION subtable.  (This happens with certain
00134   // calibration/hardware setups.)
00135   static std::set<Int> findBadSpws(MeasurementSet& ms, Vector<Int> spwv);
00136 
00137   // Select spw and channels for each spw.
00138   // This is the version used by split.  It returns true on success and false
00139   // on failure.
00140   Bool selectSpw(const String& spwstr, const Vector<Int>& steps);
00141 
00142   // This older version is used by the older version of setmsselect().
00143   void selectSpw(Vector<Int> spw, Vector<Int> nchan, Vector<Int> start, 
00144                  Vector<Int> step);
00145   
00146   // Setup polarization selection (for now, only from available correlations -
00147   // no Stokes transformations.)
00148   Bool selectCorrelations(const String& corrstr);
00149 
00150   //select Time and time averaging or regridding
00151   //void selectTime();
00152 
00153   //select stuff using msselection syntax ...time is left out
00154   // call it separately with timebin
00155   // This version returns a success value, and does not need nchan, start, and
00156   // step.  It is used by split.
00157   Bool setmsselect(const String& spw="", const String& field="", 
00158                    const String& baseline="", const String& scan="",
00159                    const String& uvrange="", const String& taql="", 
00160                    const Vector<Int>& step=Vector<Int> (1,1),
00161                    const String& subarray="", const String& correlation="",
00162                    const String& intent="", const String& obs="");
00163 
00164   // This older version does not return a success value, and does need nchan,
00165   // start, and step.  It is used elsewhere (i.e. ImagerMultiMS).
00166   void setmsselect(const String& spw,        const String& field, 
00167                    const String& baseline,   const String& scan,
00168                    const String& obs,        const String& uvrange,
00169                    const String& taql,       const Vector<Int>& nchan,
00170                    const Vector<Int>& start, const Vector<Int>& step,
00171                    const String& subarray);
00172 
00173   // Select source or field
00174   Bool selectSource(const Vector<Int>& fieldid);
00175   
00176   // Select Antennas to split out  
00177   void selectAntenna(const Vector<Int>& antennaids,
00178                      const Vector<String>& antennaSel)
00179   {
00180     antennaSel_p = pickAntennas(antennaId_p, antennaSelStr_p,
00181                                 antennaids, antennaSel);
00182   }
00183   static Bool pickAntennas(Vector<Int>& selected_antennaids,
00184                            Vector<String>& selected_antenna_strs,
00185                            const Vector<Int>& antennaids,
00186                            const Vector<String>& antennaSel);
00187   
00188   // Select array IDs to use.
00189   void selectArray(const String& subarray) {arrayExpr_p = subarray;}
00190 
00191   //select time parameters
00192   void selectTime(Double timeBin=-1.0, String timerng="");
00193 
00194   //void selectSource(Vector<String> sourceid);
00195 
00196   //Method to set if a phase Center rotation is needed
00197   //void setPhaseCenter(Int fieldid, MDirection& newPhaseCenter);
00198 
00199   // Sets the polynomial order for continuum fitting to fitorder.
00200   // If < 0, continuum subtraction is not done.
00201   void setFitOrder(Int fitorder, Bool advise=true);
00202   // Set the selection string for line-free channels.
00203   void setFitSpw(const String& fitspw) {fitspw_p = fitspw;}
00204   // Selection string for output channels if doing continuum subtraction.
00205   void setFitOutSpw(const String& fitoutspw) {fitoutspw_p = fitoutspw;}
00206 
00207   //Method to make the subMS
00208   //
00209   //TileShape of size 1 can have 2 values [0], and [1] ...these are used in to
00210   //determine the tileshape by using MSTileLayout. Otherwise it has to be a
00211   //vector size 3 e.g [4, 15, 351] => a tile shape of 4 stokes, 15 channels 351
00212   //rows.
00213   //
00214   // combine sets combine_p.  (Columns to ignore while time averaging.)
00215   //
00216   Bool makeSubMS(String& submsname, String& whichDataCol,
00217                  const Vector<Int>& tileShape=Vector<Int>(1, 0),
00218                  const String& combine="");
00219 
00220   //Method to make a scratch subMS and even in memory if posssible
00221   //Useful if temporary subselection/averaging is necessary
00222   // It'll be in memory if the basic output ms is less than half of 
00223   // memory reported by HostInfo unless forced to by user...
00224   virtual MeasurementSet* makeScratchSubMS(const Vector<MS::PredefinedColumns>& whichDataCols, 
00225                                    const Bool forceInMemory=False);
00226   // In this form whichDataCol gets passed to parseColumnNames().
00227   virtual MeasurementSet* makeScratchSubMS(const String& whichDataCol, 
00228                                    const Bool forceInMemory=False);
00229 
00230   // This sets up a default new ms
00231   // Declared static as it can be (and is) called directly outside of SubMS.
00232   // Therefore it is not dependent on any member variable.
00233   static MeasurementSet* setupMS(const String& msname, const Int nchan,
00234                                  const Int npol, const String& telescop,
00235                                  const Vector<MS::PredefinedColumns>& colNamesTok,
00236                                  const Int obstype=0,
00237                                  const Bool compress=False,
00238                                  const asdmStManUseAlternatives asdmStManUse=DONT);
00239 
00240   // Same as above except allowing manual tileshapes
00241   static MeasurementSet* setupMS(const String& msname, const Int nchan,
00242                                  const Int npol,
00243                                  const Vector<MS::PredefinedColumns>& colNamesTok,
00244                                  const Vector<Int>& tileShape=Vector<Int>(1,0),
00245                                  const Bool compress=False,
00246                                  const asdmStManUseAlternatives asdmStManUse=DONT);
00247 
00248   
00249   // Add optional columns to outTab if present in inTab and possColNames.
00250   // beLazy should only be true if outTab is in its default state.
00251   // Returns the number of added columns.
00252   static uInt addOptionalColumns(const Table& inTab, Table& outTab,
00253                                  const Bool beLazy=false);
00254 
00255   // Like TableCopy::copyRows, but by column.
00256   static Bool copyCols(Table& out, const Table& in, const Bool flush=True);
00257 
00258   // A customized version of MS::createDefaultSubtables().
00259   static void createSubtables(MeasurementSet& ms, Table::TableOption option);
00260 
00261   // Declared static because it's used in setupMS().  Therefore it can't use
00262   // any member variables.  It is also used in MSFixvis.cc.
00263   // colNameList is internally upcased, so it is not const or passed by reference.
00264   static const Vector<MS::PredefinedColumns>& parseColumnNames(String colNameList);
00265   // This version uses the MeasurementSet to check what columns are present,
00266   // i.e. it makes col=="all" smarter, and it is not necessary to call
00267   // verifyColumns() after calling this.  Unlike the other version, it knows
00268   // about FLOAT_DATA and LAG_DATA.  It throws an exception if a
00269   // _specifically_ requested column is absent.
00270   static const Vector<MS::PredefinedColumns>& parseColumnNames(String colNameList,
00271                                                     const MeasurementSet& ms);
00272 
00273   void verifyColumns(const MeasurementSet& ms, const Vector<MS::PredefinedColumns>& colNames);
00274 
00275   // The output MS must have (at least?) 1 of DATA, FLOAT_DATA, or LAG_DATA.
00276   // MODEL_DATA or CORRECTED_DATA will be converted to DATA if necessary.
00277   static Bool mustConvertToData(const uInt nTok,
00278                                 const Vector<MS::PredefinedColumns>& datacols)
00279   {
00280     return (nTok == 1) && (datacols[0] != MS::FLOAT_DATA) &&
00281       (datacols[0] != MS::LAG_DATA);
00282   }
00283 
00284   static Bool sepFloat(const Vector<MS::PredefinedColumns>& anyDataCols,
00285                        Vector<MS::PredefinedColumns>& complexDataCols);
00286 
00287   // Fills outToIn[pol] with a map from output correlation index to input
00288   // correlation index, for each input polID pol.
00289   // It does not yet check the appropriateness of the correlation selection
00290   // string, so ignore the return value for now.  outToIn[pol] defaults to
00291   // an empty Vector if no correlations are selected for pol.
00292   // That is not the same as the default "select everything in ms".
00293   static Bool getCorrMaps(MSSelection& mssel, const MeasurementSet& ms,
00294                           Vector<Vector<Int> >& outToIn,
00295                           const Bool areSelecting=false);
00296   
00297   // Replaces col[i] with mapper[col[i]] for each element of col.
00298   // Does NOT check whether mapper[col[i]] is defined, but it does return
00299   // right away (i.e. a no-op) if mapper is empty.
00300   static void remap(Vector<Int>& col, const Vector<Int>& mapper);
00301   static void remap(Vector<Int>& col, const std::map<Int, Int>& mapper);
00302 
00303   // Transform spectral data to different reference frame,
00304   // optionally regrid the frequency channels 
00305   // return values: -1 = MS not modified, 1 = MS modified and OK, 
00306   // 0 = MS modified but not OK (i.e. MS is probably damaged) 
00307   Int regridSpw(String& message, // returns the MS history entry 
00308                 const String& outframe="", // default = "keep the same"
00309                 const String& regridQuant="chan",
00310                 const Double regridVeloRestfrq=-3E30, // default = "not set" 
00311                 const String& regridInterpMeth="LINEAR",
00312                 const Double regridCenter=-3E30, // default = "not set" 
00313                 const Double regridBandwidth=-1., // default = "not set" 
00314                 const Double regridChanWidth=-1., // default = "not set" 
00315                 const Bool doHanningSmooth=False,
00316                 const Int phaseCenterFieldId=-2, // -2 = use pahse center from field table
00317                 MDirection phaseCenter=MDirection(), // this direction is used if phaseCenterFieldId==-1
00318                 const Bool centerIsStart=False, // if true, the parameter regridCenter specifies the start
00319                 const Bool startIsEnd=False, // if true, and centerIsStart is true, regridCenter specifies the upper end in frequency
00320                 const Int nchan=0, // if >0: used instead of regridBandwidth, ==
00321                 const Int width=0, // if >0 and regridQuant=="freq": used instead of regridChanWidth
00322                 const Int start=-1 // if >=0 and regridQuant=="freq": used instead of regridCenter
00323                 );
00324 
00325   // the following inline convenience methods for regridSpw bypass the whole CASA measure system
00326   // because when they are used, they can assume that the frame stays the same and the units are OK
00327   static lDouble vrad(const lDouble freq, const lDouble rest){ return (C::c * (1. - freq/rest)); };
00328   static lDouble vopt(const lDouble freq, const lDouble rest){ return (C::c *(rest/freq - 1.)); };
00329   static lDouble lambda(const lDouble freq){ return (C::c/freq); };
00330   static lDouble freq_from_vrad(const lDouble vrad, const lDouble rest){ return (rest * (1. - vrad/C::c)); };
00331   static lDouble freq_from_vopt(const lDouble vopt, const lDouble rest){ return (rest / (1. + vopt/C::c)); };
00332   static lDouble freq_from_lambda(const lDouble lambda){ return (C::c/lambda); };
00333   
00334   // Support method for regridSpw():
00335   // results in the column oldName being renamed to newName, and a new column
00336   // which is an empty copy of oldName being created together with a
00337   // TileShapeStMan data manager and hypercolumn (name copied from the old
00338   // hypercolumn) with given dimension, the old hypercolumn of name
00339   // hypercolumnName is renamed to name+"B"
00340   Bool createPartnerColumn(TableDesc& modMSTD, const String& oldName,
00341                            const String& newName, const Int& hypercolumnDim,
00342                            const IPosition& tileShape);
00343 
00344   // Support method for regridSpw():
00345   // calculate the final new channel boundaries from the regridding parameters
00346   // and the old channel boundaries (already transformed to the desired
00347   // reference frame); returns False if input paramters were invalid and no
00348   // useful boundaries could be created
00349   static Bool regridChanBounds(Vector<Double>& newChanLoBound, 
00350                                Vector<Double>& newChanHiBound,
00351                                const Double regridCenter, 
00352                                const Double regridBandwidth,
00353                                const Double regridChanWidth,
00354                                const Double regridVeloRestfrq, 
00355                                const String regridQuant,
00356                                const Vector<Double>& transNewXin, 
00357                                const Vector<Double>& transCHAN_WIDTH,
00358                                String& message, // message to the user, epsecially in case of error 
00359                                const Bool centerIsStart=False, // if true, the parameter regridCenter specifies the start
00360                                const Bool startIsEnd=False, // if true, and centerIsStart is true, regridCenter specifies the upper end in frequency
00361                                const Int nchan=0, // if != 0 : used instead of regridBandwidth, -1 means use all channels
00362                                const Int width=0, // if >0 and regridQuant=="freq": used instead of regridChanWidth
00363                                const Int start=-1 // if >=0 and regridQuant=="freq": used instead of regridCenter
00364                                );
00365 
00366   // a helper function for handling the gridding parameter user input
00367   static Bool convertGridPars(LogIO& os,
00368                               const String& mode, 
00369                               const int nchan, 
00370                               const String& start, 
00371                               const String& width,
00372                               const String& interp, 
00373                               const String& restfreq, 
00374                               const String& outframe,
00375                               const String& veltype,
00376                               String& t_mode,
00377                               String& t_outframe,
00378                               String& t_regridQuantity,
00379                               Double& t_restfreq,
00380                               String& t_regridInterpMeth,
00381                               Double& t_cstart, 
00382                               Double& t_bandwidth,
00383                               Double& t_cwidth,
00384                               Bool& t_centerIsStart, 
00385                               Bool& t_startIsEnd,                             
00386                               Int& t_nchan,
00387                               Int& t_width,
00388                               Int& t_start);
00389 
00390   // A wrapper for SubMS::regridChanBounds() which takes the user interface type gridding parameters
00391   // The ready-made grid is returned in newCHAN_FREQ and newCHAN_WIDTH
00392   static Bool calcChanFreqs(LogIO& os,
00393                             // output
00394                             Vector<Double>& newCHAN_FREQ,
00395                             Vector<Double>& newCHAN_WIDTH,
00396                             // input
00397                             const Vector<Double>& oldCHAN_FREQ, // the original grid
00398                             const Vector<Double>& oldCHAN_WIDTH, 
00399                             // the gridding parameters
00400                             const MDirection  phaseCenter,
00401                             const MFrequency::Types theOldRefFrame,
00402                             const MEpoch theObsTime,
00403                             const MPosition mObsPos,
00404                             const String& mode, 
00405                             const int nchan, 
00406                             const String& start, 
00407                             const String& width,
00408                             const String& restfreq, 
00409                             const String& outframe,
00410                             const String& veltype,
00411                             Bool verbose=False,
00412                             MRadialVelocity mRV=MRadialVelocity() // only used when outframe=="OBJECT"
00413                             );
00414 
00415   // Support method for regridSpw():
00416   // if writeTables is False, the (const) input parameters are only verified, nothing is written;
00417   // return value is True if the parameters are OK.
00418   // if writeTables is True, the vectors are filled and the SPW, DD, and SOURCE tables are modified;
00419   // the return value in this case is True only if a successful modification (or none) took place
00420   Bool setRegridParameters(vector<Int>& oldSpwId,
00421                            vector<Int>& oldFieldId,
00422                            vector<Int>& newDataDescId,
00423                            vector<Bool>& regrid,
00424                            vector<Bool>& transform,
00425                            vector<MDirection>& theFieldDirV,
00426                            vector<MPosition>& mObsPosV,
00427                            vector<MFrequency::Types>& fromFrameTypeV,
00428                            vector<MFrequency::Ref>& outFrameV,
00429                            vector< Vector<Double> >& xold, 
00430                            vector< Vector<Double> >& xout, 
00431                            vector< Vector<Double> >& xin, 
00432                            vector< Int >& method, // interpolation method cast to Int
00433                            Bool& msMod,
00434                            const String& outframe,
00435                            const String& regridQuant,
00436                            const Double regridVeloRestfrq,
00437                            const String& regridInterpMeth,
00438                            const Double regridCenter, 
00439                            const Double regridBandwidth, 
00440                            const Double regridChanWidth,
00441                            const Int regridPhaseCenterFieldId, // -2 = take from field table, -1 = use 
00442                            const MDirection regridPhaseCenter, //    <- this value, >-1 = take from this field
00443                            const Bool writeTables,
00444                            LogIO& os,
00445                            String& regridMessage,
00446                            const Bool centerIsStart=False, // if true, the parameter regridCenter specifies the start
00447                            const Bool startIsEnd=False, // if true, and centerIsStart is true, regridCenter specifies the upper end in frequency
00448                            const Int nchan=0, // if >0: used instead of regridBandwidth
00449                            const Int width=0, // if >0 and regridQuant=="freq": used instead of regridChanWidth
00450                            const Int start=-1 // if >=0 and regridQuant=="freq": used instead of regridCenter
00451                            );
00452 
00453   // combineSpws():
00454   // make one spectral window from all spws given by the spwids vector
00455   Bool combineSpws(const Vector<Int>& spwids,  // Vector<Int>(1,-1) means: use all SPWs
00456                    const Bool noModify,   // if True, the MS will not be modified
00457                    Vector<Double>& newCHAN_FREQ, // will return the grid of the resulting SPW
00458                    Vector<Double>& newCHAN_WIDTH,
00459                    Bool verbose=False
00460                    );
00461 
00462   Bool combineSpws(const Vector<Int>& spwids = Vector<Int>(1,-1)){  // Vector<Int>(1,-1) means: use all SPWs
00463     Vector<Double> temp1; 
00464     Vector<Double> temp2;
00465     return combineSpws(spwids, False, temp1, temp2, True);
00466   }
00467 
00468   // Fills mapper[ntok] with a map from dataColumn indices to ArrayColumns in
00469   // the output.  mapper must have ntok slots!
00470   static void getDataColMap(MSColumns* msc, ArrayColumn<Complex>* mapper,
00471                             uInt ntok,
00472                             const Vector<MS::PredefinedColumns>& colEnums); 
00473 
00474  protected:
00475 
00476   //method that returns the selected ms (?! - but it's Boolean - RR)
00477   Bool makeSelection();
00478 
00479   // (Sub)table fillers.
00480   Bool fillAllTables(const Vector<MS::PredefinedColumns>& colNames);
00481   Bool fillDDTables();          // Includes spw and pol.
00482   Bool fillFieldTable();
00483   
00484   // Used to be fillMainTable(colnames), but what distinguishes it from
00485   // writeSomeMainRows(colnames) is that it is for cases where there is
00486   // a 1-1 match between rows in mssel_p and msOut_p (including order).
00487   Bool writeAllMainRows(const Vector<MS::PredefinedColumns>& colNames);
00488 
00489   // Used to be fillAverMainTable(colnames), but what distinguishes it from
00490   // writeAllMainRows(colnames) is that it is for cases where there is not
00491   // necessarily a 1-1 match between rows in mssel_p and msOut_p.
00492   Bool writeSomeMainRows(const Vector<MS::PredefinedColumns>& colNames);
00493 
00494   Bool copyAntenna();
00495   Bool copyFeed();
00496   Bool copyFlag_Cmd();
00497   Bool copyHistory();
00498   Bool copyObservation();
00499   Bool copyPointing();
00500   Bool copyProcessor();
00501   Bool copySource();
00502   Bool copyState();
00503   Bool copySyscal();
00504   Bool copyWeather();
00505   Bool copyGenericSubtables();
00506 
00507   // This falls between copyGenericSubtables() and the copiers for standard
00508   // subtables like copyFeed().  It is for optional subtables like CALDEVICE
00509   // and SYSPOWER which can be watched for by name and may need their
00510   // ANTENNA_ID and SPECTRAL_WINDOW_ID columns remapped.  (Technically FEED_ID,
00511   // too, if split ever starts remapping feeds.)
00512   //
00513   // It must be called BEFORE copyGenericSubtables()!
00514   //
00515   Bool filterOptSubtable(const String& subtabname);
00516 
00517   //  Bool writeDiffSpwShape(const Vector<MS::PredefinedColumns>& colNames);
00518   Bool fillAccessoryMainCols();
00519 
00520   // *** Private member functions ***
00521 
00522   // Adds and copies inTab to msOut_p without any filtering.
00523   // tabName is the table "type", i.e. POINTING or SYSPOWER without the
00524   // preceding path.
00525   //
00526   // If noRows is True, the structure will be setup but no rows will be
00527   // copied.  (Useful for filtering)
00528   void copySubtable(const String& tabName, const Table& inTab,
00529                     const Bool noRows=False);
00530 
00531   Bool getDataColumn(ROArrayColumn<Complex>& data,
00532                      const MS::PredefinedColumns colName);
00533   Bool getDataColumn(ROArrayColumn<Float>& data,
00534                      const MS::PredefinedColumns colName);
00535   Bool putDataColumn(MSColumns& msc, ROArrayColumn<Complex>& data,
00536                      const MS::PredefinedColumns datacol,
00537                      const Bool writeToDataCol=False);
00538   Bool putDataColumn(MSColumns& msc, ROArrayColumn<Float>& data,
00539                      const MS::PredefinedColumns datacol,
00540                      const Bool writeToDataCol=False);
00541 
00542   // This method uses VisIter for efficient copy mode data transfer
00543   Bool copyDataFlagsWtSp(const Vector<MS::PredefinedColumns>& colNames,
00544                          const Bool writeToDataCol);
00545 
00546   // Like doTimeAver(), but it subtracts the continuum instead of time
00547   // averaging.  Unlike doTimeAver(), it infers writeToDataCol from
00548   // colNames.nelements() (subtractContinuum is intentionally not as general as
00549   // copyDataFlagsWtSp), and writes according to fitoutspw_p instead of spw_p.
00550   Bool subtractContinuum(const Vector<MS::PredefinedColumns>& colNames,
00551                          const VBRemapper& remapper);
00552   
00553   // Helper function for parseColumnNames().  Converts col to a list of
00554   // MS::PredefinedColumnss, and returns the # of recognized data columns.
00555   // static because parseColumnNames() is static.
00556   static uInt dataColStrToEnums(const String& col,
00557                                 Vector<MS::PredefinedColumns>& colvec);
00558     
00559   Bool doChannelMods(const Vector<MS::PredefinedColumns>& colNames);
00560 
00561   void fill_vbmaps(std::map<VisBufferComponents::EnumType,
00562                             std::map<Int, Int> >& vbmaps);
00563 
00564   // return the number of unique antennas selected
00565   //Int numOfBaselines(Vector<Int>& ant1, Vector<Int>& ant2,
00566   //                   Bool includeAutoCorr=False);
00567 
00568   // Used in a couple of places to estimate how much memory to grab.
00569   Double n_bytes() {return mssel_p.nrow() * nchan_p[0] * ncorr_p[0] *
00570                            sizeof(Complex);}
00571 
00572   // Picks a reference to DATA, MODEL_DATA, CORRECTED_DATA, or LAG_DATA out
00573   // of ms_p.  FLOAT_DATA is not included because it is not natively complex. 
00574   const ROArrayColumn<Complex>& right_column(const ROMSColumns *ms_p,
00575                                              const MS::PredefinedColumns datacol);
00576 
00577   // The writable version of the above.
00578   ArrayColumn<Complex>& right_column(MSColumns *msclala,
00579                                      const MS::PredefinedColumns col,
00580                                      const Bool writeToDataCol);
00581 
00582   // Figures out the number, maximum, and index of the selected antennas.
00583   uInt fillAntIndexer(std::map<Int, Int>& antIndexer, const ROMSColumns *msc);
00584 
00585   // Read the input, time average it to timeBin_p, and write the output.
00586   // The first version uses VisibilityIterator (much faster), but the second
00587   // supports correlation selection using VisIterator.  VisIterator should be
00588   // sped up soon!
00589   Bool doTimeAver(const Vector<MS::PredefinedColumns>& dataColNames,
00590                   const VBRemapper& remapper);
00591   Bool doTimeAverVisIterator(const Vector<MS::PredefinedColumns>& dataColNames,
00592                   const VBRemapper& remapper);
00593 
00594   void getDataColMap(ArrayColumn<Complex>* mapper, uInt ntok,
00595                      const Vector<MS::PredefinedColumns>& colEnums)
00596   {
00597     getDataColMap(msc_p, mapper, ntok, colEnums);
00598   }
00599 
00600   // Returns whether or not the numbers of correlations and channels
00601   // are independent of DATA_DESCRIPTION_ID, for both the input and output
00602   // MSes.
00603   Bool areDataShapesConstant();
00604 
00605   // Returns whether or not the input MS has a valid FLAG_CATEGORY, and its
00606   // first row has the right number of correlations and channels.
00607   Bool existsFlagCategory() const;
00608 
00609   // Sets up sourceRelabel_p for mapping input SourceIDs (if any) to output
00610   // ones.  Must be called after fieldid_p is set and before calling
00611   // fillFieldTable() or copySource().
00612   void relabelSources();
00613 
00614   void relabelIDs();
00615 
00616   // Sets outcol to the indices of selvals that correspond to incol, i.e.
00617   // outcol(i) = j s.t. selvals[j] == incol(i).
00618   //
00619   // Ideally selvals is set up so that outcol's values will be row numbers in
00620   // the corresponding subtable of its ms.
00621   //
00622   // Throws an exception if incol and outcol do not have the same # of rows, or
00623   // incol has a value that is not in selvals.
00624   void remapColumn(ScalarColumn<Int>& outcol, const ROScalarColumn<Int>& incol,
00625                    const Vector<Int>& selvals);
00626 
00627   // Equivalent to but slightly more efficient than
00628   // remapColumn(outcol, incol, incol.getColumn()).
00629   void remapColumn(ScalarColumn<Int>& outcol, const ROScalarColumn<Int>& incol);
00630 
00631   //static void make_map(const Vector<Int>& mscol, Vector<Int>& mapper);
00632 
00633   // Sets mapper to to a map from the distinct values of inv, in increasing
00634   // order, to 0, 1, 2, ..., mapper.size() - 1.
00635   static void make_map(std::map<Int, Int>& mapper, const Vector<Int>& inv);
00636   // Sets mapper to form a map from inv whose elements are mapped values. It skips
00637   // to store in mapper if the value is -1
00638   static void make_map2(std::map<Int, Int>& mapper, const Vector<Int>& inv);
00639 
00640   uInt remapped(const Int ov, const Vector<Int>& mapper, uInt i);
00641 
00642   // Sets up the stub of a POINTING, enough to create an MSColumns.
00643   void setupNewPointing();
00644 
00645   // Sets sort to a Block of columns that a VisibilityIterator should sort by,
00646   // according to combine_p.  Columns that should never be combined in the
00647   // calling function, i.e. spw for time averaging, should be listed in
00648   // uncombinable.
00649   //
00650   // verbose: log a message on error.
00651   //
00652   // Returns whether or not there were any conflicts between combine_p and
00653   // uncombinable.
00654   Bool setSortOrder(Block<Int>& sort, const String& uncombinable="",
00655                     const Bool verbose=true) const;
00656 
00657   // Returns whether col is (not in combine_p) || in uncombinable.
00658   // Columns that should never be combined in the
00659   // calling function, i.e. spw for time averaging, should be listed in
00660   // uncombinable.
00661   //
00662   // verbose: log a message on error.
00663   //
00664   // conflict is set to true if there is a conflict between combine_p and
00665   // uncombinable.
00666   Bool shouldWatch(Bool& conflict, const String& col,
00667                    const String& uncombinable="",
00668                    const Bool verbose=true) const;
00669 
00670   // *** Member variables ***
00671 
00672   // Initialized* by ctors.  (Maintain order both here and in ctors.)
00673   //  * not necessarily to anything useful.
00674   MeasurementSet ms_p, mssel_p;
00675   MSColumns * msc_p;            // columns of msOut_p
00676   ROMSColumns * mscIn_p;
00677   Bool keepShape_p,             // Iff true, each output array has the
00678                                 // same shape as the corresponding input one.
00679        // sameShape_p,             // Iff true, the shapes of the arrays do not
00680        //                       // vary with row number.
00681        antennaSel_p;            // Selecting by antenna?
00682   Double timeBin_p;
00683   String scanString_p,          // Selects scans by #number#.  Historically named.
00684          intentString_p,        // Selects scans by string.  scanString_p was taken.
00685          obsString_p,           // String for observationID selection.
00686          uvrangeString_p,
00687          taqlString_p;
00688   String timeRange_p, arrayExpr_p, corrString_p;
00689   String combine_p;          // Should time averaging not split bins by
00690                              // scan #, observation, and/or state ID?
00691                              // Must be lowercase at all times.
00692   Int fitorder_p;               // The polynomial order for continuum fitting.
00693                                 // If < 0 (default), continuum subtraction is
00694                                 // not done.
00695   String fitspw_p;           // Selection string for line-free channels.
00696   String fitoutspw_p;        // Selection string for output channels if doing
00697                              // continuum subtraction.
00698 
00699   // jagonzal: Allow main table to be left empty, so that it can be filled by another layer.
00700   Bool fillMainTable_p;
00701 
00702   // Uninitialized by ctors.
00703   MeasurementSet msOut_p;
00704   Vector<Int> spw_p,      // The input spw corresponding to each output spw.
00705               spw_uniq_p, // Uniquified version of spw_p.
00706               spwind_to_min_spwind_p,
00707               nchan_p,    // The # of output channels for each range.
00708               totnchan_p, // The # of output channels for each output spw.
00709               chanStart_p, // 1st input channel index in a selection.
00710               chanEnd_p,   // last input channel index in a selection.
00711               chanStep_p, // Increment between input chans, i.e. if 3, only every third
00712                           // input channel will be used. 
00713               widths_p,   // # of input chans per output chan for each range.
00714               ncorr_p,    // The # of output correlations for each DDID.
00715               inNumChan_p,    // The # of input channels for each spw.
00716               inNumCorr_p;    // The # of input correlations for each DDID.
00717   Vector<Int> fieldid_p;
00718   Vector<Int> spwRelabel_p, fieldRelabel_p, sourceRelabel_p;
00719   Vector<Int> oldDDSpwMatch_p;
00720   Vector<String> antennaSelStr_p;
00721   Vector<Int> antennaId_p;
00722   Vector<Int> antIndexer_p;
00723   Vector<Int> antNewIndex_p;
00724 
00725   Vector<Int> selObsId_p;  // List of selected OBSERVATION_IDs.
00726   Vector<Int> polID_p;         // Map from input DDID to input polID, filled in fillDDTables(). 
00727   Vector<uInt> spw2ddid_p;
00728 
00729   // inCorrInd = outPolCorrToInCorrMap_p[polID_p[ddID]][outCorrInd]
00730   Vector<Vector<Int> > inPolOutCorrToInCorrMap_p;
00731 
00732   std::map<Int, Int> stateRemapper_p; 
00733 
00734   Vector<Vector<Slice> > chanSlices_p;  // Used by VisIterator::selectChannel()
00735   Vector<Slice> corrSlice_p;
00736   Vector<Vector<Slice> > corrSlices_p;  // Used by VisIterator::selectCorrelation()
00737   Matrix<Double> selTimeRanges_p;
00738 };
00739 
00740 } //# NAMESPACE CASA - END
00741 
00742 #endif
00743