casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines
LatticeHistograms.h
Go to the documentation of this file.
00001 //# LatticeHistograms.h: generate histograms from a lattice
00002 //# Copyright (C) 1996,1997,1999,2000,2001
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: LatticeHistograms.h 20299 2008-04-03 05:56:44Z gervandiepen $
00027 
00028 #ifndef LATTICES_LATTICEHISTOGRAMS_H
00029 #define LATTICES_LATTICEHISTOGRAMS_H
00030 
00031 
00032 //# Includes
00033 #include <casa/aips.h>
00034 #include <lattices/Lattices/TiledCollapser.h>
00035 #include <lattices/Lattices/LatticeStatistics.h>
00036 #include <lattices/Lattices/LatticeProgress.h>
00037 #include <casa/Logging/LogIO.h>
00038 #include <scimath/Mathematics/NumericTraits.h>
00039 #include <casa/iosfwd.h>
00040 
00041 namespace casa { //# NAMESPACE CASA - BEGIN
00042 
00043 //# Forward Declarations
00044 template <class T> class MaskedLattice;
00045 template <class T> class TempLattice;
00046 template <class T> class Vector;
00047 class IPosition;
00048 class PGPlotter;
00049 
00050 // <summary>
00051 // Displays histograms of regions from a lattice.
00052 // </summary>
00053 
00054 // <use visibility=export>
00055 
00056 // <reviewed reviewer="" date="yyyy/mm/dd" tests="" demos="">
00057 // </reviewed>
00058 
00059 // <prerequisite>
00060 //   <li> <linkto class=MaskedLattice>MaskedLattice</linkto>
00061 // </prerequisite>
00062 
00063 // <etymology>
00064 // This is a class designed to display histograms from MaskedLattices
00065 // </etymology>
00066 
00067 // <synopsis>
00068 // This class enable you to display and/or retrieve histograms evaluated over 
00069 // specified regions from a MaskedLattice.  The dimension of the region is arbitrary, but 
00070 // the size of each dimension is always the size of the corresponding lattice axis.
00071 // The histograms are displayed as a function of location of the axes not
00072 // used to evaluate the histograms over.  The axes which you evaluate the histograms 
00073 // over are called the cursor axes, the others are called the display axes.
00074 //
00075 // For example, consider a lattice cube (call the axes xyz or [0,1,2]).  You could 
00076 // display histograms from xy planes (cursor axes [0,1]) as a function of z (display
00077 // axes [2]).   Or  you could retrieve histograms from the z axis (cursor axes [2])
00078 // for each [x,y] location (display axes [0,1]).
00079 //
00080 // This class generates a "storage lattice" into which it writes the histograms.
00081 // It is from this storage lattice that the plotting and retrieval
00082 // arrays are drawn.  The storage lattice is either in core or on disk
00083 // depending upon its size (if > 10% of memory given by .aipsrc system.resources.memory
00084 // then it goes into a disk-based PagedArray).  If on disk,  the
00085 // storage lattice is deleted when the <src>LatticeHistograms</src> 
00086 // object destructs.    
00087 //
00088 //
00089 // <note role=tip>
00090 // Note that for complex lattices, real and imaginary are treated independently.
00091 // They are binned and plotted separately.
00092 // </note>
00093 //
00094 // <note role=tip>
00095 // If you ignore return error statuses from the functions that set the
00096 // state of the class, the internal status of the class is set to bad.
00097 // This means it will just  keep on returning error conditions until you
00098 // explicitly recover the situation.   A message describing the last   
00099 // error condition can be recovered with function errorMessage.
00100 
00101 // </note>
00102 // </synopsis>
00103 
00104 // <example>
00105 // <srcBlock>
00107 //
00108 //      PagedImage<Float> inImage(inName);
00109 //   
00111 //      
00112 //      LogOrigin or("myClass", "myFunction(...)", WHERE);
00113 //      LogIO os(or);
00114 //      ImageHistograms<Float> histo(inImage, os);
00115 //      
00117 //
00118 //      Vector<Int> cursorAxes(2)
00119 //      cursorAxes(0) = 1;
00120 //      cursorAxes(1) = 2;
00121 //      if (!histo.setAxes(cursorAxes)) return 1;
00122 //
00124 //
00125 //      if (!histo.setList(True)) return 1;
00126 //      String device = "/xs";
00127 //      Vector<Int> nxy(2);
00128 //      nxy(0) = 3;
00129 //      nxy(1) = 3;
00130 //      if (!histo.setPlotting(device, nxy)) return 1;
00131 // 
00133 // 
00134 //      if (!histo.display ()) return 1;
00135 //
00137 //
00138 //      Array<Float> values, counts;
00139 //      if (!histo.getHistograms(values, counts)) return 1;
00140 //
00141 // </srcBlock>
00142 // In this example, a <src>PagedImage</src> is constructed.  We set the cursor axes 
00143 // to be the y and z axes so we make a histogram of each yz plane as a function 
00144 // of x location on the PGPLOT device "/xs" with 9 subplots per page.
00145 // After the plotting we also retrieve the histograms into an array.
00146 // </example>
00147 
00148 // <motivation>
00149 // The generation of histograms from an image is a basic and necessary capability.
00150 // </motivation>
00151 //
00152 // <todo asof="2000/04/04">
00153 //   <li> Make ascii listing of histograms as well as plots if desired
00154 // </todo>
00155 //
00156 
00157 
00158 template <class T> class LatticeHistograms 
00159 {
00160 public:
00161 
00162 // Constructor takes the MaskedLattice and a <src>LogIO</src> object for logging.
00163 // You can also specify whether you want to see progress meters or not.
00164 // You can force the storage lattice to be disk based, otherwise
00165 // the decision for core or disk is taken for you.
00166    LatticeHistograms(const MaskedLattice<T>& lattice, 
00167                      LogIO& os,
00168                      Bool showProgress=True,
00169                      Bool forceDisk=False);
00170 
00171 // Constructor takes the MaskedLattice only. In the absence of a logger you get no messages.
00172 // This includes error messages and potential listing of statistics.
00173 // You can specify whether you want to see progress meters or not.
00174 // You can force the storage lattice to be disk based, otherwise
00175 // the decision for core or disk is taken for you.
00176    LatticeHistograms(const MaskedLattice<T>& lattice, 
00177                    Bool showProgress=True,
00178                    Bool forceDisk=False);
00179 
00180 // Copy constructor (copy semantics)
00181    LatticeHistograms(const LatticeHistograms<T> &other);
00182 
00183 // Destructor
00184    virtual ~LatticeHistograms ();
00185 
00186 // Assignment operator (copy semantics)
00187    LatticeHistograms<T> &operator=(const LatticeHistograms<T> &other);
00188 
00189 // Set the cursor axes (0 relative).  A return value of <src>False</src>
00190 // indicates you have asked for an invalid axis or that the internal
00191 // status of the class is bad.  The default state of the class is to set 
00192 // the cursor axes to all axes in the lattice.
00193    Bool setAxes (const Vector<Int>& cursorAxes);
00194 
00195 // Set the number of bins for the histogram.  Note that the bin width is
00196 // worked out for each histogram separately from the data minimum and maximum.
00197 // The default state of the class is to set 25 bins.  A return value of <src>False</src>
00198 // indicates you gave a non-positive bin width or  that the internal status of the 
00199 // class is bad. 
00200    Bool setNBins (const uInt& nBins);
00201 
00202 // Specify a pixel intensity range for which all pixels in that range are 
00203 // included.  A vector of length 1 for <src>include</src> means that the 
00204 // range will be set to <src>-abs(include(0))</src> to <src>abs(include(0))</src>.
00205 // A return value of <src>False</src> indicates that the internal
00206 // status of the class is bad. If you don't call this function, the default 
00207 // state of the class is to include all pixels.
00208    Bool setIncludeRange (const Vector<T>& include);
00209 
00210 // Specify that a Gaussian overlay should be plotted on the histogram. This
00211 // Gaussian has the same mean and standard deviation as the data that were
00212 // binned, and the same integral as the histogram.   A return value of <src>False</src>
00213 // indicates that the internal status of the class is bad. The default state of
00214 // the class is to not draw a Gaussian overlay.  
00215    Bool setGaussian (const Bool& doGauss);
00216 
00217 // Specify the form of the histogram.   It can be plotted linearly or
00218 // logarithmically, and cumulatively or non-cumulatively.   A return value 
00219 // of <src>False</src> indicates that the internal status of the class is bad.
00220 // The default state of the class is to draw the histograms linearly and
00221 // non-cumulatively.
00222    Bool setForm (const Bool& doLog, const Bool& doCumu);
00223 
00224 // This function allows you to control whether some statistics of the
00225 // data that contributed to the histogram are written to  the output 
00226 // stream.   A return value of <src>False</src> indicates that the internal
00227 // status of the class is bad. The default state of the class is to not 
00228 // list statistics.
00229    Bool setStatsList(const Bool& doList);
00230 
00231 // This function sets the name of the PGPLOT plotting device and the number of
00232 // subplots in x and y per page.   If you set <src>plotter</src> but offer
00233 // a zero length array for <src>nxy</src> then <src>nxy</src> is set
00234 // to [1,1].  A return value of <src>False</src> indicates invalid
00235 // plotting arguments or that the internal status of the class is bad. If you
00236 // don't call this function, the default state of the class is to not set
00237 // a plotting device.
00238    Bool setPlotting(PGPlotter& plotter,
00239                     const Vector<Int>& nxy);
00240 
00241 // Display the histograms by plotting them.  A return value of <src>False</src> 
00242 // indicates an invalid plotting device, or that the internal status of the class is bad.
00243 // If you don't call this function you won't see any histograms.
00244    Bool display ();
00245 
00246 // CLose the plotter
00247    void closePlotting();
00248 
00249 // Return the display axes
00250    Vector<Int> displayAxes() const {return displayAxes_p;}
00251 
00252 // This function retrieves the histograms into <src>Array</src>.  The shape of the first
00253 // dimension of this array is the number of bins.  The rest of the shape of the
00254 // array is the shape of the display axes (e.g. if the shape of the lattice is
00255 // [nx,ny,nz] and you ask for histograms of the y axis the shape of the returned
00256 // array would be [nbins,nx,nz].    The histograms are retrieved in the form 
00257 // specified by the <src>setForm</src> function. The arrays are resized internally.
00258 // A return value of <src>False</src> indicates  that the internal status of the class is bad. 
00259    Bool getHistograms (Array<T>& values, Array<T>& counts);
00260 
00261 // This function retrieves the histogram at the specified location 
00262 // into <src>Vectors</src>.  The histogram is retrieved in the form 
00263 // specified by the <src>setForm</src> function. The vectors are resized 
00264 // internally. If <src>posInLattice=True</src> then the location is a 
00265 // location in the input lattice.  Any positions on the display axes 
00266 // are ignored.  Otherwise, you should just give locations for 
00267 // the display axes only. A return  value of <src>False</src> indicates  that 
00268 // the internal status  of the class is bad. 
00269    Bool getHistogram (Vector<T>& values, 
00270                       Vector<T>& counts, 
00271                       const IPosition& pos,
00272                       const Bool posInLattice=False);
00273 
00274 // Reset argument error condition.  If you specify invalid arguments to
00275 // one of the above <src>set</src> functions, an internal flag will be set which will
00276 // prevent the work functions from doing anything (should you have chosen 
00277 // to ignore the Boolean return values of the <src>set</src> functions).
00278 // This function allows you to reset that internal state to good.
00279    void resetError () {goodParameterStatus_p = True;};
00280 
00281 // Recover last error message
00282    String errorMessage() const {return error_p;};
00283 
00284 // Set a MaskedLattice.  A return value of <src>False</src> indicates the 
00285 // lattice had an invalid type or that the internal status of the class is bad.
00286    Bool setNewLattice (const MaskedLattice<T>& lattice);
00287 
00288 // These things are protected only so that they are available to ImageHistograms
00289 // which inherits from LatticeHistograms
00290 
00291 protected:
00292    LogIO os_p;
00293    Bool goodParameterStatus_p; 
00294    Vector<Int> cursorAxes_p, displayAxes_p;
00295    String error_p;
00296 
00297 // Given a location in the histogram storage lattice, convert those locations on the
00298 // non-histogram axis (the first one) relative to the parent or current lattice
00299    IPosition locHistInLattice (const IPosition& histPosition, 
00300                                Bool relativeToParent=True) const;  
00301 
00302 private:
00303 
00304 // A useful typedef
00305    typedef typename NumericTraits<T>::PrecisionType AccumType;
00306 
00307    const MaskedLattice<T>* pInLattice_p;
00308    TempLattice<T>* pStoreLattice_p;
00309    LatticeStatistics<T>* pStats_p;
00310    Bool binAll_p, needStorageLattice_p;
00311    Bool doCumu_p, doGauss_p, doList_p, doLog_p;
00312    Bool haveLogger_p, showProgress_p, forceDisk_p;
00313    uInt nBins_p;
00314    PGPlotter plotter_p;
00315    Vector<Int> nxy_p;
00316    Vector<T> range_p;
00317    IPosition blcParent_p;
00318 
00319 
00320 // Convert a <tt>T</tt> to a <tt>Float</tt> for plotting
00321    static Float convertT (const T value) {return Float(std::real(value));};   
00322  
00323 // Convert a <tt>Float</tt> (from plotting) to a <tt>T</tt>
00324    static T convertF (const Float value) {return T(value);};
00325 
00326 // Display histograms as a function of display axis
00327    Bool displayHistograms ();
00328 
00329 // Display one histogram
00330    Bool displayOneHistogram (const T&linearSum,
00331                              const T&linearYMax,
00332                              const IPosition& histPos,
00333                              const Vector<T> &stats,
00334                              const Vector<T>& values,
00335                              const Vector<T>& counts,
00336                              PGPlotter& plotter);
00337 
00338 
00339 // Fish out and convert to the appropriate form one histogram from the
00340 // storage lattice
00341    void extractOneHistogram (T& linearSum,
00342                              T& linearYMax,
00343                              Vector<T>& values,
00344                              Vector<T>& counts,
00345                              const Vector<T>& stats,
00346                              const Vector<T>& intCounts);
00347 
00348 // Iterate through the lattice and generate the histogram accumulation lattice
00349    Bool generateStorageLattice();
00350 
00351 // Get the statistics from the statistics object for the current
00352 // location of either the input lattice, or the histogram storage lattice
00353    void getStatistics (Vector<T> &stats,
00354                        const IPosition &pos) const;
00355 
00356 // List statistics
00357    void listStatistics(LogIO& os, const Vector<T>& stats, T binWidth);
00358 
00359 
00360 // Fill histograms storage lattice
00361    void makeHistograms();
00362 
00363 // Create and fill statistics object
00364    Bool makeStatistics();
00365 
00366 // Check/set include pixel range
00367    Bool setInclude (Vector<T>& range,
00368                     Bool& noInclude,  
00369                     const Vector<T>& include,
00370                     ostream& os);
00371 
00372 // Set stream attributes
00373    void setStream (ostream& os, Int oPrec);
00374 
00375 // Make a string with pixel coordinates of display axes.  This function
00376 // is over-ridden by ImageHistograms which inherits from LatticeHistograms.
00377    virtual String writeCoordinates(const IPosition& histPos) const;
00378 
00379 // Write values of display axes on plots
00380    Bool writeDispAxesValues (const String& coords,
00381                              PGPlotter& plotter,
00382                              Float nchar) const;
00383 };
00384 
00385 
00386 
00387 // <summary> Generate histograms, tile by tile, from a masked lattice </summary>
00388 //
00389 // <use visibility=export>
00390 //
00391 // <reviewed reviewer="" date="yyyy/mm/dd" tests="" demos="">
00392 // </reviewed>
00393 //
00394 // <prerequisite>
00395 //   <li> <linkto class=LatticeApply>LatticeApply</linkto>
00396 //   <li> <linkto class=TiledCollapser>TiledCollapser</linkto>
00397 // </prerequisite>
00398 //
00399 // <etymology>
00400 // This class is used by <src>LatticeHistograms</src> to generate
00401 // histograms from an input <src>MaskedLattice</src>.
00402 // The input lattice is iterated through in tile-sized chunks
00403 // and fed to an object of this class.
00404 // </etymology>
00405 //
00406 // <synopsis>
00407 // <src>HistTiledCollapser</src> is derived from <src>TiledCollapser</src> which
00408 // is a base class used to define methods.  Objects of this base class are
00409 // used by <src>LatticeApply</src> functions.  In this particular case,
00410 // we are interested in <src>LatticeApply::tiledApply</src>.  This  function iterates
00411 // through a <src>MaskedLattice</src> and allows you to collapse one or more
00412 // axes, computing some values from it, and placing those values into
00413 // an output <src>MaskedLattice</src>.  It iterates through the input
00414 // lattice in optimal tile-sized chunks.    <src>LatticeHistograms</src> 
00415 // uses a <src>HistTiledCollapser</src> object which it gives to 
00416 // <src>LatticeApply::tiledApply</src> for digestion.  After it has
00417 // done its work, <src>LatticeHistograms</src> then accesses the output
00418 // <src>Lattice</src> that it made.
00419 // </synopsis>
00420 //
00421 // <example>
00422 // <srcblock>
00424 //
00425 //   HistTiledCollapser<T> collapser(pStats, nBins_p);
00426 // 
00429 // 
00430 //   Int newOutAxis = 0;
00431 //
00434 //
00435 //   LatticeApply<T>::tiledApply(outLattice, inLattice,
00436 //                               collapser, collapseAxes,
00437 //                               newOutAxis);
00438 //
00439 // </srcblock>
00440 // In this example, a collapser is made and passed to LatticeApply.
00441 // Afterwards, the output Lattice is available for use.
00442 // The Lattices must all be the correct shapes on input to tiledApply
00443 // </example>
00444 //
00445 // <motivation>
00446 // The LatticeApply classes enable the ugly details of optimal
00447 // Lattice iteration to be hidden from the user.
00448 // </motivation>
00449 //
00450 // <todo asof="1998/05/10">   
00451 //   <li> 
00452 // </todo>
00453 
00454 template <class T>
00455 class HistTiledCollapser : public TiledCollapser<T,T>
00456 {
00457  
00458 public:
00459 // Constructor
00460     HistTiledCollapser(LatticeStatistics<T>* pStats, uInt nBins);
00461 
00462     virtual ~HistTiledCollapser();
00463 
00464 // Initialize process, making some checks
00465     virtual void init (uInt nOutPixelsPerCollapse);
00466 
00467 // Initialize the accumulator
00468     virtual void initAccumulator (uInt n1, uInt n3);
00469 
00470 // Process the data in the current chunk.
00471     virtual void process (
00472         uInt accumIndex1,
00473         uInt accumIndex3,
00474         const T* inData,
00475         const Bool* inMask,
00476         uInt inDataIncr,
00477         uInt inMaskIncr,
00478         uInt nrval,
00479         const IPosition& startPos,
00480         const IPosition& shape
00481     );
00482  
00483 // End the accumulation process and return the result arrays 
00484     virtual void endAccumulator(Array<T>& result,  
00485                                 Array<Bool>& resultMask,
00486                                 const IPosition& shape); 
00487 
00488 // Can handle null mask
00489    virtual Bool canHandleNullMask() const {return True;};
00490 
00491 private:
00492     LatticeStatistics<T>* pStats_p;
00493     Block<T>* pHist_p;
00494     uInt nBins_p;
00495     uInt n1_p;
00496     uInt n3_p;
00497 };
00498  
00499 
00500 
00501 } //# NAMESPACE CASA - END
00502 
00503 #ifndef CASACORE_NO_AUTO_TEMPLATES
00504 #include <lattices/Lattices/LatticeHistograms.tcc>
00505 #endif //# CASACORE_NO_AUTO_TEMPLATES
00506 #endif