casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines
MatrixCleaner.h
Go to the documentation of this file.
00001 //# Cleaner.h: this defines Cleaner a class for doing convolution
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 //#
00027 //# $Id: LatticeCleaner.h 20739 2009-09-29 01:15:15Z Malte.Marquarding $
00028 
00029 #ifndef SYNTHESIS_MATRIXCLEANER_H
00030 #define SYNTHESIS_MATRIXCLEANER_H
00031 
00032 //# Includes
00033 #include <casa/aips.h>
00034 #include <casa/Quanta/Quantum.h>
00035 #include <lattices/Lattices/TempLattice.h>
00036 #include <casa/Arrays/IPosition.h>
00037 #include <casa/Arrays/Vector.h>
00038 #include <casa/Containers/Block.h>
00039 #include <lattices/Lattices/LatticeCleaner.h>
00040 
00041 namespace casa { //# NAMESPACE CASA - BEGIN
00042 
00043 //# Forward Declarations
00044 template <class T> class Matrix;
00045 
00046 // <summary>A copy of LatticeCleaner but just using 2-D matrices</summary>
00047 // <synopsis> It is a mimic of the LatticeCleaner class but avoid a lot of 
00048 // of the lattice to array and back copies and uses openmp in the obvious places
00049 // </synopsis>
00050 
00051 // <summary>A class for doing multi-dimensional cleaning</summary>
00052 
00053 // <use visibility=export>
00054 
00055 // <reviewed reviewer="" date="yyyy/mm/dd" tests="tLatticeCleaner">
00056 // </reviewed>
00057 
00058 // <prerequisite>
00059 //  <li> The mathematical concept of deconvolution
00060 // </prerequisite>
00061 //
00062 // <etymology>
00063 
00064 // The MatrixCleaner class will deconvolve 2-D arrays of floats.
00065 
00066 // </etymology>
00067 //
00068 // <synopsis>
00069 // This class will perform various types of Clean deconvolution
00070 // on Lattices.
00071 //
00072 // </synopsis>
00073 //
00074 // <example>
00075 // <srcblock>
00076 // </srcblock> 
00077 // </example>
00078 //
00079 // <motivation>
00080 // </motivation>
00081 //
00082 // <thrown>
00083 // <li> AipsError: if psf has more dimensions than the model. 
00084 // </thrown>
00085 //
00086 // <todo asof="yyyy/mm/dd">
00087 // </todo>
00088 
00089 class MatrixCleaner
00090 {
00091 public:
00092 
00093   // Create a cleaner : default constructor
00094   MatrixCleaner();
00095 
00096   // Create a cleaner for a specific dirty image and PSF
00097   MatrixCleaner(const Matrix<Float> & psf, const Matrix<Float> & dirty);
00098 
00099   // The copy constructor uses reference semantics
00100   MatrixCleaner(const MatrixCleaner& other);
00101 
00102   // The assignment operator also uses reference semantics
00103   MatrixCleaner & operator=(const MatrixCleaner & other); 
00104 
00105   // The destructor does nothing special.
00106   ~MatrixCleaner();
00107  
00108   //just define the scales...nothing else is done
00109   //the user will need to call setPsf+makePsfScales+setDirty+makeDirtyScales
00110   //to be in a good state to clean.
00111   void defineScales(const Vector<Float>& scales);
00112   
00113   //Set the dirty image without calculating convolutions..
00114   //can be done by calling  makeDirtyScales or setscales if one want to redo the 
00115   //psfscales too.
00116   void setDirty(const Matrix<Float>& dirty);
00117   //Calculate the convolutions for the dirt
00118   //Obviously the 
00119   void makeDirtyScales();
00120   // Update the dirty image only (equiv of setDirty + makeDirtyScales)
00121   void update(const Matrix<Float> & dirty);
00122 
00123   //change the psf
00124   //don't forget to redo the setscales or run makePsfScales, 
00125   //followed by makeDirtyScales 
00126   void setPsf(const Matrix<Float>& psf);
00127   //calculate the convolutions of the psf 
00128   void makePsfScales();
00129   
00130   // Set a number of scale sizes. The units of the scale are pixels.
00131   // The 2 functions below assume you have the dirty image and the psf set
00132   // the convolutions are calculated automatically and the masks ones too 
00133   // if it is set ....kept so as to be compatible function wise with LatticeCleaner
00134   Bool setscales(const Int nscales, const Float scaleInc=1.0);
00135 
00136   // Set a specific set of scales
00137   Bool setscales(const Vector<Float> & scales);
00138 
00139   
00140  
00141   // Set up control parameters
00142   // cleanType - type of the cleaning algorithm to use (HOGBOM, MULTISCALE)
00143   // niter - number of iterations
00144   // gain - loop gain used in cleaning (a fraction of the maximum 
00145   //        subtracted at every iteration)
00146   // aThreshold - absolute threshold to stop iterations
00147   // fThreshold - fractional threshold (i.e. given w.r.t. maximum residual)
00148   //              to stop iterations. This parameter is specified as
00149   //              Quantity so it can be given in per cents. 
00150   // choose - unused at the moment, specify False. Original meaning is
00151   // to allow interactive decision on whether to continue iterations.
00152   // This method always returns True.
00153   Bool setcontrol(CleanEnums::CleanType cleanType, const Int niter,
00154                   const Float gain, const Quantity& aThreshold,
00155                   const Quantity& fThreshold);
00156 
00157   // This version of the method disables stopping on fractional threshold
00158   Bool setcontrol(CleanEnums::CleanType cleanType, const Int niter,
00159                   const Float gain, const Quantity& threshold);
00160 
00161   // return how many iterations we did do
00162   Int iteration() const { return itsIteration; }
00163   Int numberIterations() const { return itsIteration; }
00164 
00165   // what iteration number to start on
00166   void startingIteration(const Int starting = 0) {itsStartingIter = starting; }
00167   
00168  //Total flux accumulated so far
00169   Float totalFlux() const {return itsTotalFlux;}
00170 
00171 
00172   // Clean an image. 
00173   //return value gives you a hint of what's happening
00174   //  1 = converged
00175   //  0 = not converged but behaving normally
00176   // -1 = not converged and stopped on cleaning consecutive smallest scale
00177   // -2 = not converged and either large scale hit negative or diverging 
00178   // -3 = clean is diverging rather than converging 
00179   Int clean(Matrix<Float> & model, Bool doPlotProgress=False);
00180 
00181   // Set the mask
00182   // mask - input mask lattice
00183   // maskThreshold - if positive, the value is treated as a threshold value to determine
00184   // whether a pixel is good (mask value is greater than the threshold) or has to be 
00185   // masked (mask value is below the threshold). Negative threshold switches mask clipping
00186   // off. The mask value is used to weight the flux during cleaning. This mode is used
00187   // to implement cleaning based on the signal-to-noise as opposed to the standard cleaning
00188   // based on the flux. The default threshold value is 0.9, which ensures the behavior of the
00189   // code is exactly the same as before this parameter has been introduced.
00190   void setMask(Matrix<Float> & mask, const Float& maskThreshold = 0.9);
00191   // Call the function below if the psf is changed ..no need to setMask again
00192   Bool makeScaleMasks();
00193 
00194   // remove the mask;
00195   // useful when keeping object and sending a new dirty image to clean 
00196   // one can set another mask then 
00197   void unsetMask();
00198 
00199   // Tell the algorithm to NOT clean just the inner quarter
00200   // (This is useful when multiscale clean is being used
00201   // inside a major cycle for MF or WF algorithms)
00202   // if True, the full image deconvolution will be attempted
00203   void ignoreCenterBox(Bool huh) { itsIgnoreCenterBox = huh; }
00204 
00205   // Consider the case of a point source: 
00206   // the flux on all scales is the same, and the first scale will be chosen.
00207   // Now, consider the case of a point source with a *little* bit of extended structure:
00208   // thats right, the largest scale will be chosen.  In this case, we should provide some
00209   // bias towards the small scales, or against the large scales.  We do this in
00210   // an ad hoc manner, multiplying the maxima found at each scale by
00211   // 1.0 - itsSmallScaleBias * itsScaleSizes(scale)/itsScaleSizes(nScalesToClean-1);
00212   // Typical bias values range from 0.2 to 1.0.
00213   void setSmallScaleBias(const Float x=0.5) { itsSmallScaleBias = x; }
00214 
00215   // During early iterations of a cycled MS Clean in mosaicing, it common
00216   // to come across an ocsilatory pattern going between positive and
00217   // negative in the large scale.  If this is set, we stop at the first
00218   // negative in the largest scale.
00219   void stopAtLargeScaleNegative() {itsStopAtLargeScaleNegative = True; }
00220 
00221   // Some algorithms require that the cycles be terminated when the image
00222   // is dominated by point sources; if we get nStopPointMode of the
00223   // smallest scale components in a row, we terminate the cycles
00224   void stopPointMode(Int nStopPointMode) {itsStopPointMode = nStopPointMode; }
00225 
00226   // After completion of cycle, querry this to find out if we stopped because
00227   // of stopPointMode
00228   Bool queryStopPointMode() const {return itsDidStopPointMode; }
00229 
00230   // speedup() will speed the clean iteration by raising the
00231   // threshold.  This may be required if the threshold is
00232   // accidentally set too low (ie, lower than can be achieved
00233   // given errors in the approximate PSF).
00234   //
00235   // threshold(iteration) = threshold(0) 
00236   //                        * ( exp( (iteration - startingiteration)/Ndouble )/ 2.718 )
00237   // If speedup() is NOT invoked, no effect on threshold
00238   void speedup(const Float Ndouble);
00239 
00240   // Look at what WE think the residuals look like
00241   // Assumes the first scale is zero-sized
00242   Matrix<Float>  residual() { return itsDirtyConvScales[0]; }
00243 
00244   // Method to return threshold, including any speedup factors
00245   Float threshold() const;
00246 
00247   // Method to return the strength optimum achieved at the last clean iteration
00248   // The output of this method makes sense only if it is called after clean
00249   Float strengthOptimum() const { return itsStrengthOptimum; }
00250 
00251   // Helper function to optimize adding
00252   //static void addTo(Matrix<Float>& to, const Matrix<Float> & add);
00253 
00254 protected:
00255   // Make sure that the peak of the Psf is within the image
00256   Bool validatePsf(const Matrix<Float> & psf);
00257 
00258   // Make an array of the specified scale
00259   void makeScale(Matrix<Float>& scale, const Float& scaleSize);
00260   
00261   // Make Spheroidal function for scale images
00262   Float spheroidal(Float nu);
00263   
00264   // Find the Peak of the matrix
00265   static Bool findMaxAbs(const Matrix<Float>& lattice,
00266                          Float& maxAbs, IPosition& posMax);
00267 
00268   // Find the Peak of the lattice, applying a mask
00269   Bool findMaxAbsMask(const Matrix<Float>& lattice, const Matrix<Float>& mask,
00270                              Float& maxAbs, IPosition& posMax);
00271 
00272   // Helper function to reduce the box sizes until the have the same   
00273   // size keeping the centers intact  
00274   static void makeBoxesSameSize(IPosition& blc1, IPosition& trc1,                               
00275      IPosition &blc2, IPosition& trc2);
00276 
00277 
00278   CleanEnums::CleanType itsCleanType;
00279   Float itsGain;
00280   Int itsMaxNiter;      // maximum possible number of iterations
00281   Quantum<Double> itsThreshold;
00282   CountedPtr<Matrix<Float> > itsMask;
00283   IPosition itsPositionPeakPsf;
00284   Float itsSmallScaleBias;
00285   Block<Matrix<Float> > itsScaleMasks;
00286   Block<Matrix<Complex> > itsScaleXfrs;
00287   Bool itsScalesValid;
00288   Int itsNscales;
00289   Float itsMaskThreshold;
00290 private:
00291 
00292   //# The following functions are used in various places in the code and are
00293   //# documented in the .cc file. Static functions are used when the functions
00294   //# do not modify the object state. They ensure that implicit assumptions
00295   //# about the current state and implicit side-effects are not possible
00296   //# because all information must be supplied in the input arguments
00297 
00298 
00299   CountedPtr<Matrix<Float> > itsDirty;
00300   CountedPtr<Matrix<Complex> >itsXfr;
00301 
00302   Vector<Float> itsScaleSizes;
00303 
00304   Block<Matrix<Float> > itsScales;
00305   Block<Matrix<Float> > itsPsfConvScales;
00306   Block<Matrix<Float> > itsDirtyConvScales;
00307 
00308 
00309   Int itsIteration;     // what iteration did we get to?
00310   Int itsStartingIter;  // what iteration did we get to?
00311   Quantum<Double> itsFracThreshold;
00312 
00313   Float itsMaximumResidual;
00314   Float itsStrengthOptimum;
00315 
00316 
00317   Vector<Float> itsTotalFluxScale;
00318   Float itsTotalFlux;
00319 
00320   // Memory to be allocated per TempLattice
00321   Double itsMemoryMB;
00322 
00323   // Let the user choose whether to stop
00324   Bool itsChoose;
00325 
00326   // Threshold speedup factors:
00327   Bool  itsDoSpeedup;  // if false, threshold does not change with iteration
00328   Float itsNDouble;
00329 
00330   //# Stop now?
00331   //#//  Bool stopnow();   Removed on 8-Apr-2004 by GvD
00332 
00333   // Calculate index into PsfConvScales
00334   Int index(const Int scale, const Int otherscale);
00335   
00336   Bool destroyScales();
00337   Bool destroyMasks();
00338 
00339 
00340   
00341   Bool itsIgnoreCenterBox;
00342   Bool itsStopAtLargeScaleNegative;
00343   Int itsStopPointMode;
00344   Bool itsDidStopPointMode;
00345   Bool itsJustStarting;
00346 
00347   // threshold for masks. If negative, mask values are used as weights and no pixels are
00348   // discarded (although effectively they would be discarded if the mask value is 0.)
00349 
00350   IPosition psfShape_p;
00351   Bool noClean_p;
00352 
00353 };
00354 
00355 } //# NAMESPACE CASA - END
00356 
00357 #endif