casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines
VBContinuumSubtractor.h
Go to the documentation of this file.
00001 //# VBContinuumSubtractor.h: Fit a continuum model to a VisBuffer and provide
00002 //# the continuum and/or line estimates as VisBuffers.
00003 //# Copyright (C) 2011
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 //# $Id$
00028 //#
00029 #ifndef MSVIS_VBCONTINUUMSUBTRACTOR_H
00030 #define MSVIS_VBCONTINUUMSUBTRACTOR_H
00031 
00032 #include <casa/aips.h>
00033 #include <casa/Arrays/Cube.h>
00034 #include <ms/MeasurementSets/MeasurementSet.h>
00035 //#include <synthesis/MSVis/VisBuffer.h>
00036 
00037 namespace casa { //# NAMESPACE CASA - BEGIN
00038 
00039 class VisBuffer;
00040 class VisBuffGroupAcc;
00041 class LogIO;
00042 
00043 // <summary>Fits and optionally subtracts the continuum in visibility spectra</summary>
00044 // <use visibility=export>
00045 // 
00046 // <reviewed reviewer="" date="yyyy/mm/dd" tests="" demos="">
00047 // </reviewed>
00048 // 
00049 // <prerequisite>
00050 //   <li> <linkto class=MeasurementSet>MeasurementSet</linkto>
00051 // </prerequisite>
00052 //
00053 // <etymology>
00054 // This class's main aim is to subtract the continuum from VisBuffers.
00055 // </etymology>
00056 //
00057 // <synopsis>
00058 // Spectral line observations often contain continuum emission which is
00059 // present in all channels (often with a small slope and curvature across the band). This
00060 // class fits a polynomial to this continuum, and can return the continuum
00061 // and/or line (continuum-subtracted) estimates as VisBuffers.
00062 // </synopsis>
00063 //
00064 // <example>
00065 // <srcBlock>
00066 //   const Int fitorder = 4;                 // Careful!  High orders might
00067 //                                           // absorb power from the lines.
00068 //   MS inMS(fileName);
00069 //   Block<Int> sortcolumns;
00070 //   ROVisIter vi(inMS, sortcolumns, 0.0);
00071 //   VisBuffer cvb(vi);                         // Continuum estimate
00072 //   VisBuffer lvb(vi);                         // Line estimate
00073 //   VisBuffer vb(vi);
00074 //   for(vi.originChunks(); vi.moreChunks(); vi.nextChunk()){
00075 //     for(vi.origin(); vi.more(); ++vi){
00076 //       VBContinuumSubtractor contestor(vb, fitorder); // Continuum Estimator
00077 //
00078 //       contestor.cont_est(cvb);             // Put continuum estimate into cvb.
00079 //       contestor.cont_subtracted(lvb);      // Put line estimate into lvb.
00080 //
00081 //       // Do something with cvb and lvb...
00082 //     }
00083 //   }
00084 // </srcBlock>
00085 // </example>
00086 //
00087 // <motivation>
00088 // This class provides continuum fitting by polynomials with order >= 0, with
00089 // a convenient interface for use by other classes in synthesis and msvis
00090 // (i.e. calibration, imaging, and split).
00091 // </motivation>
00092 //
00093 // <todo asof="">
00094 // </todo>
00095 class VBContinuumSubtractor
00096 {
00097 public:
00098   VBContinuumSubtractor();
00099 
00100   // Construct it with the low and high frequencies used for scaling the
00101   // frequencies in the polynomial.
00102   VBContinuumSubtractor(const Double lofreq, const Double hifreq);
00103 
00104   ~VBContinuumSubtractor();
00105 
00106   // Set the # of correlations and fitorder from shp, the total number of input
00107   // channels to look at (including masked ones!), and the low and high scaling
00108   // frequencies.
00109   void init(const IPosition& shp, const uInt maxAnt, const uInt totnumchan,
00110             const Double lof, const Double hif);
00111 
00112   // Set the low and high frequencies, and #s of correlations, antennas, and
00113   // channels from vbga.  Returns False if vbga is empty.
00114   Bool initFromVBGA(VisBuffGroupAcc& vbga);
00115 
00116   // Makes the continuum estimate by fitting a frequency polynomial of order
00117   // fitorder to the data in vbga.  It sets the low and high frequencies used
00118   // for scaling the frequencies in the polynomial to the min and max
00119   // frequencies in vbga.
00120   // Input: vbga,         The data
00121   //        fitorder,     e.g. 2 for a + bf + cf**2
00122   //        doInit,       if true call initFromVBGA(vbga)
00123   //        doResize      if true set coeffs and coeffsOK to the right shape.
00124   // Output (these will be resized):
00125   //   coeffs:   Polynomial coefficients for the continuum, indexed by (corr,
00126   //             order, hash(ant1, ant2).
00127   //   coeffsOK: and whether or not they're usable.
00128   void fit(VisBuffGroupAcc& vbga, const Int fitorder,
00129            MS::PredefinedColumns whichcol,
00130            Cube<Complex>& coeffs, Cube<Bool>& coeffsOK,
00131            const Bool doInit=False, const Bool doResize=False,
00132            const Bool squawk=True);
00133 
00134   // Apply the continuum estimate in coeffs (from fit) to vb.  The affected
00135   // column of vb is chosen by whichcol, which must be exactly one of MS::DATA,
00136   // MS::MODEL_DATA, or MS::CORRECTED_DATA lest an exception will be thrown.
00137   // If doSubtraction is True, vb becomes the line estimate.  Otherwise it is
00138   // replaced with the continuum estimate.  Returns False if it detects an
00139   // error, True otherwise.  squawk=True increases the potential number of
00140   // warnings sent to the logger.
00141   Bool apply(VisBuffer& vb,
00142              const MS::PredefinedColumns whichcol,
00143              const Cube<Complex>& coeffs,
00144              const Cube<Bool>& coeffsOK, const Bool doSubtraction=True,
00145              const Bool squawk=True);
00146 
00147   // Returns whether or not vb's frequencies are within the bounds used for the
00148   // continuum fit.  If not, and squawk is True, a warning will be sent to the
00149   // logger.  (Extrapolation is allowed, just not recommended.)
00150   Bool areFreqsInBounds(VisBuffer& vb, const Bool squawk) const;
00151 
00152   // Fills minfreq and maxfreq with the minimum and maximum frequencies (in Hz,
00153   // acc. to the MS def'n v.2) of vb (not the continuum fit!).  If you want to
00154   // get the extreme frequencies over a set of VisBuffers, set initialize to
00155   // False and initialize minfreq and maxfreq yourself to DBL_MAX and -1.0,
00156   // respectively.
00157   static void getMinMaxFreq(VisBuffer& vb, Double& minfreq, Double& maxfreq,
00158                             const Bool initialize=True);
00159 
00160   // These are provided for the calibration framework so that a
00161   // VBContinuumSubtractor can be c'ted from a VisBuffGroupAcc, make a
00162   // continuum fit, write its results to a caltable, destroyed, and then later
00163   // another one can be c'ted from the caltable and apply the fit to a
00164   // VisBuffer.  Obviously it'd be safer and faster to use the same
00165   // VBContinuumSubtractor for fitting and application, but the rest of CASA
00166   // isn't ready for that yet (3/7/2011).
00167   Int getOrder() const {return fitorder_p;}
00168 
00169   Double getLowFreq() const {return lofreq_p;}  // Lowest frequency used in the fit,
00170   Double getHighFreq() const {return hifreq_p;} // and highest, in Hz, acc. to
00171                                                 // the MS def'n v.2.
00172   Int getMaxAntNum() const {return maxAnt_p;}   // -1 if unready.
00173 
00174   // The total number of input channels that will be looked at (including
00175   // masked ones!)
00176   uInt getTotNumChan() const {return totnumchan_p;}
00177 
00178   // Low (lof) and high (hif) frequencies, in Hz, used for renormalizing
00179   // frequencies in the polynomials.
00180   void setScalingFreqs(Double lof, Double hif){
00181     lofreq_p = lof;
00182     hifreq_p = hif;
00183     midfreq_p = 0.5 * (lof + hif);
00184     freqscale_p = calcFreqScale();
00185   }
00186 
00187   // Set the maximum number of antennas (actually, 1 + the maximum antenna
00188   // number).
00189   void setNAnt(const uInt nAnt){
00190     maxAnt_p = nAnt - 1;
00191     nHashes_p = (nAnt * (nAnt + 1)) / 2;  // Allows for autocorrs.  
00192   }
00193 
00194   // Set the total number of input channels that will be looked at (including
00195   // masked ones!)
00196   void setTotNumChan(const uInt tnc) {totnumchan_p = tnc;}
00197 
00198   // A convenience function for prepping coeffs and coeffsOK to hold the
00199   // polynomial coefficients and their validities.
00200   void resize(Cube<Complex>& coeffs, Cube<Bool>& coeffsOK) const;
00201 
00202   Bool checkSize(Cube<Complex>& coeffs, Cube<Bool>& coeffsOK) const
00203   {
00204     return coeffs.shape()[0] == static_cast<Int>(ncorr_p) &&
00205       coeffs.shape()[1] == fitorder_p + 1 &&
00206       coeffs.shape()[2] == static_cast<Int>(nHashes_p) &&
00207       coeffsOK.shape()[0] == static_cast<Int>(ncorr_p) &&
00208       coeffsOK.shape()[1] == fitorder_p + 1 &&
00209       coeffsOK.shape()[2] == static_cast<Int>(nHashes_p);
00210   }
00211 
00212   Double calcFreqScale() const {
00213     return hifreq_p > midfreq_p ? 1.0 / (hifreq_p - midfreq_p) : 1.0;
00214   }
00215 
00216 private:
00217   // Disable default copying, and assignment.
00218   VBContinuumSubtractor& operator=(VBContinuumSubtractor& other);
00219 
00220   // Can the fit be _applied_ to vb?
00221   // If not and squawk is true, send a severe message to os.
00222   Bool doShapesMatch(VisBuffer& vb, LogIO& os, const Bool squawk=true) const;
00223 
00224   // Compute baseline (row) index in coeffs_p for (ant1, ant2).
00225   // It ASSUMES that ant1 and ant2 are both <= maxAnt_p.
00226   uInt hashFunction(const Int ant1, const Int ant2)
00227   {
00228     return (maxAnt_p + 1) * ant1 - (ant1 * (ant1 - 1)) / 2 + ant2 - ant1;
00229   }
00230 
00231   //VisBuffGroupAcc& vbga_p;      // Holds the VisBuffers
00232   Int       fitorder_p;  // Order of the fitting polynomial.
00233 
00234   Double    lofreq_p;    // Lowest frequency used in the continuum fit,
00235   Double    hifreq_p;    // and highest, in Hz, acc. to the MS def'n v.2.
00236   Double    midfreq_p;   // 0.5 * (lofreq_p + hifreq_p)
00237   Double    freqscale_p;
00238   Int       maxAnt_p;         // Highest 0 based antenna number that can be
00239                               // used with the fits.  -1 if not ready.
00240   uInt      nHashes_p;        // Calculated and cached from maxAnt_p.
00241   uInt      ncorr_p;
00242   uInt      totnumchan_p;
00243 
00244   PtrBlock<Vector<Bool> * > chanmask_p;
00245 };
00246 
00247 } //# NAMESPACE CASA - END
00248 
00249 #endif