casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines
LatticeStatistics.h
Go to the documentation of this file.
00001 //# LatticeStatistics.h: generate statistics from a Lattice
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: LatticeStatistics.h 20739 2009-09-29 01:15:15Z Malte.Marquarding $
00027 
00028 #ifndef LATTICES_LATTICESTATISTICS_H
00029 #define LATTICES_LATTICESTATISTICS_H
00030 
00031 
00032 //# Includes
00033 #include <casa/aips.h>
00034 #include <casa/Arrays/Array.h>
00035 #include <casa/Containers/Block.h>
00036 #include <casa/Arrays/Vector.h>
00037 #include <lattices/Lattices/LatticeStatsBase.h>
00038 #include <lattices/Lattices/TiledCollapser.h>
00039 #include <lattices/Lattices/TiledCollapser.h>
00040 #include <lattices/Lattices/LatticeExprNode.h>
00041 #include <scimath/Mathematics/NumericTraits.h>
00042 #include <casa/System/PGPlotter.h>
00043 #include <casa/Utilities/DataType.h>
00044 #include <casa/BasicSL/String.h>
00045 #include <casa/Logging/LogIO.h>
00046 #include <vector>
00047 #include <list>
00048 
00049 namespace casa { //# NAMESPACE CASA - BEGIN
00050 
00051 //# Forward Declarations
00052 template <class T> class MaskedLattice;
00053 template <class T> class TempLattice;
00054 class IPosition;
00055 #include <casa/iosstrfwd.h>
00056 
00057 
00058 // <summary>
00059 // Compute and display various statistics from a lattice
00060 // </summary>
00061 // <use visibility=export>
00062 // <reviewed reviewer="" date="yyyy/mm/dd" tests="" demos="">
00063 // </reviewed>
00064 // <prerequisite>
00065 //   <li> <linkto class=LatticeStatsBase>LatticeStatsBase</linkto>
00066 //   <li> <linkto class=MaskedLattice>MaskedLattice</linkto>
00067 // </prerequisite>
00068 
00069 // <etymology>
00070 // This is a class designed to display and retrieve statistics from lattices
00071 // </etymology>
00072 
00073 // <synopsis>
00074 // This class enable you to display and/or retrieve statistics evaluated over 
00075 // specified regions of a lattice.  The dimension of the region is arbitrary, but 
00076 // the size of each dimension is always the shape of the corresponding lattice axis.
00077 // The statistics are displayed as a function of location of the axes not
00078 // used to evaluate the statistics over.  The axes which you evaluate the statistics
00079 // over are called the cursor axes, the others are called the display axes.
00080 //
00081 // For example, consider a lattice cube (call the axes xyz or [0,1,2]).  You could 
00082 // display statistics from xy planes (cursor axes [0,1]) as a function of z (display
00083 // axes [2]).   Or  you could retrieve statistics from the z axis (cursor axes [2])
00084 // for each [x,y] location (display axes [0,1]).
00085 //
00086 // This class inherits from  <linkto class="LatticeStatsBase">LatticeStatsBase</linkto> 
00087 // This base class provides an <src>enum</src> defining allowed statistics types and a 
00088 // helper function to convert between a <src>String</src> and a 
00089 // <src>Vector<Int></src> describing  the desired statistics to plot.  
00090 // An example is shown below.
00091 //
00092 // This class can list, plot and retrieve statistics.  When it lists statistics,
00093 // it always lists all the available statistics.  When you plot statistics,
00094 // you must specify which ones you would like to see.
00095 //
00096 // This class generates a "storage lattice" into which it writes the accumulated
00097 // statistical sums.  It is from this storage lattice that the plotting and retrieval
00098 // arrays are drawn.  The storage lattice is either in core or on disk 
00099 // depending upon its size (if > 10% of memory given by .aipsrc system.resources.memory
00100 // then it goes into a disk-based PagedArray).  If on disk,  the
00101 // storage lattice is deleted when the <src>LatticeStatistics</src> class 
00102 // object destructs.    However, currently, if the process is terminated ungracefully,
00103 // the storage lattice will be left over.  
00104 // </synopsis>
00105 //
00106 // <note role=tip>
00107 // This class has a few virtual functions; they are not part of a nice general
00108 // polymorphic interface; rather they have specialized functionality.  The idea 
00109 // of these is that you can derive a class from LatticeStatistics, such as 
00110 // <linkto class="ImageStatistics">ImageStatistics</linkto> which provides
00111 // you with a little more information when displaying/logging the 
00112 // statistics (such as world coordinates)
00113 // The virtual functions are
00114 // <ul>
00115 // <li> <src>getBeamArea</src> can be used to return the synthesized beam
00116 //    area so that the FLUX statistic can be computed
00117 // <li> <src>listStats</src> is used to list the statistics to the logger
00118 // <li> <src>getLabelsM</src> find the X-axis label and the title label
00119 //     for the plotting.   
00120 // </ul>
00121 // </note>
00122 //
00123 // <note role=tip>
00124 // If you ignore return error statuses from the functions that set the
00125 // state of the class, the internal status of the class is set to bad.
00126 // This means it will just  keep on returning error conditions until you
00127 // explicitly recover the situation.  A message describing the last
00128 // error condition can be recovered with function errorMessage.
00129 // </note>
00130 
00131 
00132 // <example>
00133 // <srcBlock>
00135 //
00136 //      PagedImage<Float> inImage(inName);
00137 //   
00139 //      
00140 //      LogOrigin or("myClass", "myFunction(...)", WHERE);
00141 //      LogIO os(or);
00142 //      LatticeStatistics<Float> stats(SubImage<FLoat>(inImage), os);
00143 //      
00145 //
00146 //      Vector<Int> cursorAxes(2)
00147 //      cursorAxes(0) = 1;
00148 //      cursorAxes(1) = 2;
00149 //      if (!stats.setAxes(cursorAxes)) return 1;
00150 //
00152 //
00153 //      if (!stats.setList(True)) return 1;
00154 //      String device = "/xs";
00155 //      Vector<Int> nxy(2);
00156 //      nxy(0) = 1;
00157 //      nxy(1) = 1;
00158 //      Vector<Int> statsToPlot = LatticeStatsBase::toStatisticTypes("mean,rms,sigma");
00159 //      if (!stats.setPlotting(statsToPlot, device, nxy)) return 1;
00160 // 
00162 // 
00163 //      if (!stats.display ()) return 1;
00164 //
00166 //
00167 //      Array<Double> sum;
00168 //      if (!stats.getStatistic(sum, LatticeStatsBase::SUM)) return 1;
00169 //
00170 // </srcBlock>
00171 // In this example, a <src>PagedImage</src> is constructed (which isA
00172 // MaskedLattice) with .  We set the cursor axes 
00173 // to be the y and z axes, we specify to list the statistics if we plot them,
00174 // and we ask to plot the mean, standard deviation, and root mean square of each 
00175 // yz plane as a function of x location on the PGPLOT device "/xs" with
00176 // 1 subplot per page (there will be only one in this case).  After the
00177 // plotting and listing, we also retrieve the sum of the selected pixels
00178 // as a function of x location into an array.
00179 // </example>
00180 
00181 // <motivation>
00182 // The generation of statistical information from a lattice is a basic 
00183 // and necessary capability.
00184 // </motivation>
00185 
00186 // <todo asof="1996/11/26">
00187 //   <li> Implement plotting for complex lattices
00188 //   <li> Retrieve statistics at specified location of display axes
00189 // </todo>
00190 
00191 
00192 template <class T> class LatticeStatistics : public LatticeStatsBase
00193 {
00194 
00195 public:
00196 
00197         typedef typename NumericTraits<T>::PrecisionType AccumType;
00198 
00199 // Constructor takes the lattice and a <src>LogIO</src> object for logging.
00200 // You can specify whether you want to see progress meters or not.
00201 // You can force the storage lattice to be disk based, otherwise
00202 // the decision for core or disk is taken for you.
00203    LatticeStatistics (const MaskedLattice<T>& lattice, 
00204                       LogIO& os,
00205                       Bool showProgress=True,
00206                       Bool forceDisk=False);
00207 
00208 // Constructor takes the lattice only. In the absence of a logger you get no messages.
00209 // This includes error messages and potential listing of the statistics.
00210 // You can specify whether you want to see progress meters or not.
00211 // You can force the storage lattice to be disk based, otherwise
00212 // the decision for core or disk is taken for you.
00213    LatticeStatistics (const MaskedLattice<T>& lattice,
00214                       Bool showProgress=True,
00215                       Bool forceDisk=False);
00216 
00217 // Copy constructor.  Copy semantics are followed.  Therefore any storage lattice 
00218 // that has already been created for <src>other</src> is copied to <src>*this</src>
00219    LatticeStatistics(const LatticeStatistics<T> &other);
00220 
00221 // Destructor
00222    virtual ~LatticeStatistics ();
00223 
00224 // Assignment operator.  Deletes any storage lattice associated with
00225 // the object being assigned to and copies any storage lattice that has
00226 // already been created for "other".
00227    LatticeStatistics<T> &operator=(const LatticeStatistics<T> &other);
00228 
00229 // Set the cursor axes (0 relative).  A return value of <src>False</src>
00230 // indicates you have asked for an invalid axis.  The default state of the class
00231 // is to set the cursor axes to all axes in the lattice.
00232    Bool setAxes (const Vector<Int>& cursorAxes);
00233 
00234 // You may specify a pixel intensity range as either one for which 
00235 // all pixels in that range are included or one for which all pixels 
00236 // in that range are excluded.   One or the other of <src>include</src> 
00237 // and <src>exclude</src> must therefore be a zero length vector if you 
00238 // call this function.    If you are setting an <src>include</src>
00239 // range, then if you set <src>setMinMaxToInclude=True</src>, the
00240 // minimum and maximum values that this class returns will always be 
00241 // the minimum and maximum of the <src>include</src> range, respectively.
00242 // A return value of <src>False</src> indicates that 
00243 // you have given both an <src>include</src> and an <src>exclude</src> 
00244 // range.  A vector of length 1 for <src>include</src> and/or <src>exclude</src>
00245 // means that the range will be set to (say for <src>include</src>)
00246 // <src>-abs(include(0))</src> to <src>abs(include(0))</src>.  A return value
00247 // of <src>False</src> indicates that both an inclusion and exclusion 
00248 // range were given or that the internal state of the class is bad.   If you don't
00249 // call this function, the default state of the class  is to include all pixels.
00250    Bool setInExCludeRange(const Vector<T>& include,
00251                           const Vector<T>& exclude,
00252                           Bool setMinMaxToInclude=False);
00253 
00254 // This function allows you to control whether the statistics are written to
00255 // the output stream if you are also making a plot.  A return value of 
00256 // <src>False</src> indicates that the internal state of the class is bad.
00257 // If you have created the <src>LatticeStatistics</src> object without
00258 // a <src>LogIO</src> object, you won't see any listings, but no error
00259 // conditions will be generated.  The default state of the class is to 
00260 // not list the output when making a plot. 
00261    Bool setList(const Bool& doList);
00262 
00263 // This functions enable you to specify which statistics you would like to
00264 // plot, sets the name of the PGPLOT plotting device and the number of
00265 // subplots in x and y per page.   If you set <src>device</src> 
00266 // but offer a zero length array for <src>nxy</src> then <src>nxy</src> is 
00267 // set to [1,1].  Similarly, the default for <src>statsToPlot</src> is
00268 // to plot the mean and standard deviation. Use the helper function
00269 // <src>LatticeStatsBase::toStatisticTypes(String& stats)</src> to convert 
00270 // a <src>String</src> to the desired <src>Vector<Int> statsToPlot</src>.  
00271 // A return value of <src>False</src> indicates invalid plotting arguments
00272 // or that the internal state of the class is bad.  If you don't call this function,
00273 // the default state of the class is to not make plots.
00274    Bool setPlotting(PGPlotter& plotter,
00275                     const Vector<Int>& statsToPlot,
00276                     const Vector<Int>& nxy);
00277 
00278 // Display the statistics by listing and/or plotting them.  If you don't call
00279 // this function then you won't see anything !  A return value of <src>False</src>
00280 // indicates an invalid plotting device, or that the internal state of the class is bad.
00281 
00282    Bool display();
00283    Bool getLayerStats(String& stats, Double area, 
00284                       Int zAxis=-1, Int zLayer=-1, 
00285                       Int hAxis=-1, Int hLayer=-1); 
00286 
00287    typedef std::pair<String,String> stat_element;
00288    typedef std::list<stat_element> stat_list;
00289    Bool getLayerStats( stat_list &stats, Double area, 
00290                       Int zAxis=-1, Int zLayer=-1, 
00291                       Int hAxis=-1, Int hLayer=-1); 
00292 
00293 // CLose plotter
00294    void closePlotting();
00295 
00296 
00297 // Return the display axes.  The returned vector will be valid only if <src>setAxes</src>
00298 // has been called, or if one of the active "display" or "get*" methods has been called. 
00299    Vector<Int> displayAxes() const {return displayAxes_p;} 
00300 
00301 // Recover the desired Statistic into an array.  If you choose to use
00302 // the T version, be aware that the values in the AccumType version of the
00303 // Array may not be representable in the T version (e.g. large values for
00304 // SumSq).  The shape of the
00305 // array is the shape of the display axes (e.g. if the shape of the lattice is
00306 // [nx,ny,nz] and you ask for the mean of the y axis the shape of the returned
00307 // array would be [nx,nz].    A returned array of zero shape indicates that there 
00308 // were no good values.   A return   value of <src>False</src> 
00309 // indicates that the internal state of  the class is bad.
00310 // <group>
00311    Bool getStatistic (Array<AccumType>& stat, LatticeStatsBase::StatisticsTypes type, Bool dropDeg=True);
00312    Bool getConvertedStatistic (Array<T>& stat, LatticeStatsBase::StatisticsTypes type, Bool dropDeg=True);
00313 // </group>
00314 
00315 // Recover position of min and max. Only works if there are no
00316 // display axes (i.e. statistics found over entire image), otherwise,
00317 // the returned values are resized to 0 shape.  A return  
00318 // value of <src>False</src> indicates that the internal state of 
00319 // the class is bad.
00320    Bool getMinMaxPos(IPosition& minPos, IPosition& maxPos);
00321 
00322 // This function gets a vector containing all the statistics
00323 // for a given location.  If <src>posInLattice=True</src> then
00324 // the location is a location in the input lattice.  Any
00325 // positions on the display axes are ignored.  Otherwise, you
00326 // should just give locations for the display axes only.
00327 // Use can use the enum in class LatticeStatsBase to find out
00328 // which locations in the vector contain which statistics.
00329 // A returned vector of zero shape indicates that there 
00330 // were no good values. A return  value of <src>False</src> 
00331 // indicates that the  internal state of the class is bad.
00332    Bool getStats (Vector<AccumType>&,
00333                   const IPosition& pos,
00334                   const Bool posInLattice=False);
00335 
00336 // Reset argument error condition.  If you specify invalid arguments to
00337 // one of the above <src>set</src> functions, an internal flag will be set which will
00338 // prevent the work functions from doing anything (should you have chosen 
00339 // to ignore the Boolean return values of the <src>set</src> functions).
00340 // This function allows you to reset that internal state to good.
00341    void resetError () {goodParameterStatus_p = True;};
00342 
00343 // Get full lattice min and max only.  Returns False if no unmasked data, else returns True.
00344 // Honours any include or exclude range if set.
00345    Bool getFullMinMax (T& dataMin, T& dataMax);
00346 
00347 // Recover last error message
00348    String errorMessage() const {return error_p;};
00349 
00350 // Set a new MaskedLattice object.  A return value of <src>False</src> indicates the 
00351 // lattice had an invalid type or that the internal state of the class is bad.
00352    Bool setNewLattice(const MaskedLattice<T>& lattice);
00353 
00354 // Did we construct with a logger ?
00355    Bool hasLogger () const {return haveLogger_p;};
00356 
00357 protected:
00358 
00359    LogIO os_p;
00360    Vector<Int> cursorAxes_p, displayAxes_p;
00361    Bool goodParameterStatus_p;
00362    Bool haveLogger_p, fixedMinMax_p;
00363 
00364 // doRobust means that when the storage lattice is generated, the
00365 // robust statistics are generated as well
00366 
00367    Bool doRobust_p;
00368    Bool doList_p;
00369    IPosition minPos_p, maxPos_p, blcParent_p;
00370    String error_p;
00371 //
00372 // Virtual Functions.  See implementation to figure it all out !
00373 //
00374 // Get beam volume if possible.  Your lattice needs to be
00375 // an ImageInterface for you to be able to do this.
00376 // See for example, class ImageStatistics.  When you provide
00377 // the beam, then the Flux statistic, if requested, can be
00378 // computed.  Returns False if beam not available, else True.
00379 // The implementation here returns False. Callers are responsible
00380    // for deleting the <src>beamArea</src> pointer which is created
00381 
00382    virtual Bool _getBeamArea (Array<Double>& beamArea) const;
00383 
00384    virtual void listMinMax (ostringstream& osMin,
00385                             ostringstream& osMax,
00386                             Int oWidth, DataType type);
00387 
00388 // List the statistics to the logger.   The implementation here
00389 // is adequate for all lattices.  See ImageStatistics for an
00390 // example of where extra information is provided. hasBeam is
00391 // the return value of getBeamArea. If it is true, that means
00392 // that the FLUX statistics will be available in the storage
00393 // lattice.  dPos is the location of the start of the cursor in the
00394 // storage image for this row.  stats(j,i) is the statistics matrix.
00395 // for the jth point and the ith statistic.
00396 // The return value is False if something goes wrong !
00397 // Have a look at the implementation to see what you really
00398 // have to do.
00399    virtual Bool listStats (Bool hasBeam, const IPosition& dPos,
00400                            const Matrix<AccumType>& ord);
00401    virtual Bool listLayerStats (Double hasBeam, 
00402              const Matrix<AccumType>& ord,
00403              ostringstream& rslt, Int zLayer); 
00404 
00405 // Gets labels for higher order axes and x axis.
00406 // dPos is the location of the start of the cursor in the
00407 // storage image for this row. 
00408    virtual void getLabels(String& higherOrderLabel, String& xAxisLabel,
00409                           const IPosition& dPos) const;
00410 
00411 // Given a location in the storage lattice, convert those locations on the   
00412 // non-statistics axis (the last one) and optionally account for the 
00413 // lattice subsectioning
00414    IPosition locInLattice (const IPosition& storagePosition,
00415                            Bool relativeToParent=True) const;
00416  
00417 // Non-virtual functions
00418 //
00419 // set stream manipulators
00420    void setStream (ostream& os, Int oPrec);
00421 
00422    // get the storage lattice shape
00423    inline IPosition _storageLatticeShape() const { return pStoreLattice_p->shape(); }
00424 
00425 private:
00426    const MaskedLattice<T>* pInLattice_p;
00427    TempLattice<AccumType>* pStoreLattice_p;
00428    Vector<Int> nxy_p, statsToPlot_p;
00429    Vector<T> range_p;
00430    PGPlotter plotter_p;
00431    Bool noInclude_p, noExclude_p;
00432        
00433    Bool needStorageLattice_p, doneSomeGoodPoints_p, someGoodPointsValue_p;
00434    Bool showProgress_p, forceDisk_p;
00435 //
00436    T minFull_p, maxFull_p;
00437    Bool doneFullMinMax_p;
00438 
00439 // Summarize the statistics found over the entire lattice
00440    virtual void summStats();
00441 
00442            virtual void displayStats(
00443                    AccumType nPts, AccumType sum, AccumType median,
00444                    AccumType medAbsDevMed, AccumType quartile, AccumType sumSq, AccumType mean,
00445                    AccumType var, AccumType rms, AccumType sigma, AccumType dMin, AccumType dMax
00446            );
00447 
00448 // Calculate statistic from storage lattice and return in an array
00449    Bool calculateStatistic (Array<AccumType>& slice, 
00450                             LatticeStatsBase::StatisticsTypes type,
00451                             Bool dropDeg);
00452 
00453 // Convert a AccumType to a Float for plotting.
00454    static Float convertATtoF (AccumType value) {return Float(std::real(value));};
00455 
00456 // Find the next good or bad point in an array
00457    Bool findNextDatum     (uInt& iFound,
00458                            const uInt& n,
00459                            const Vector<AccumType>& mask,
00460                            const uInt& iStart,
00461                            const Bool& findGood) const;
00462 
00463 // Find the next label in a list of comma delimitered labels
00464    Bool findNextLabel     (String& subLabel,
00465                            Int& iLab,
00466                            String& label) const;
00467 
00468 // Find the median per cursorAxes chunk
00469    void generateRobust (); 
00470 
00471 // Create a new storage lattice
00472    Bool generateStorageLattice (); 
00473 
00474 // Examine an array and determine how many segments of good points it consists 
00475 // of.    A good point occurs if the array value is greater than zero.
00476    void lineSegments (uInt& nSeg,
00477                       Vector<uInt>& start,
00478                       Vector<uInt>& nPts,
00479                       const Vector<AccumType>& mask) const;
00480 
00481 // Given a location in the lattice and a statistic type, work
00482 // out where to put it in the storage lattice
00483    IPosition locInStorageLattice(const IPosition& latticePosition,
00484                                  LatticeStatsBase::StatisticsTypes type) const;
00485 
00486 // Draw each Y-axis sublabel in a string with a different colour
00487    void multiColourYLabel (String& label,
00488                            PGPlotter& plotter,
00489                            const String& LRLoc,
00490                            const Vector<uInt>& colours,
00491                            const Int& nLabs) const;
00492 
00493 // Plot an array which may have some blanked points.
00494 // Thus we plot it in segments         
00495    void multiPlot        (PGPlotter& plotter,
00496                           const Vector<AccumType>& x,
00497                           const Vector<AccumType>& y,
00498                           const Vector<AccumType>& n) const;
00499 
00500 // Find min and max of good data in arrays specified by pointers
00501    void minMax            (Bool& none, AccumType& dMin, AccumType& dMax,
00502                            const Vector<AccumType>& d,
00503                            const Vector<AccumType>& n) const;
00504 
00505 // Find the next nice PGPLOT colour index 
00506    Int niceColour         (Bool& initColours) const; 
00507 
00508 // Plot the statistics
00509    Bool plotStats         (Bool hasBeam, const IPosition& dPos, 
00510                            const Matrix<AccumType>& ord,
00511                            PGPlotter& plotter);
00512 
00513 // Retrieve a statistic from the storage lattice and return in an array
00514    Bool retrieveStorageStatistic (Array<AccumType>& slice, 
00515                                   const LatticeStatsBase::StatisticsTypes type,
00516                                   const Bool dropDeg);
00517 
00518 // Retrieve a statistic from the storage lattice at the specified
00519 // location and return in an array
00520    Bool retrieveStorageStatistic (Vector<AccumType>& slice, 
00521                                   const IPosition& pos,
00522                                   const Bool posInLattice);
00523 
00524 // Find the shape of slice from the statistics lattice at one
00525 // spatial pixel
00526    IPosition statsSliceShape () const; 
00527 
00528 // See if there were some valid points found in the storage lattice
00529    Bool someGoodPoints ();  
00530 
00531 
00532 // Stretch min and max by 5%
00533    void stretchMinMax (AccumType& dMin, AccumType& dMax) const;
00534 
00535    // convert a position in the input lattice to the corresponding
00536    // position in the stats storage lattice. The number of elements
00537    // in storagePos will not be changed and only the first N elements
00538    // will be modified where N = the number of elements in latticePos.
00539    // <src>storagePos</src> must therefore have at least as many elements
00540    // as <src>latticePos</src>. Returns False if
00541    //<src>latticePos</src> is inconsistent with the input lattice.
00542    void _latticePosToStoragePos(
00543                  IPosition& storagePos, const IPosition& latticePos
00544    );
00545 };
00546 
00547 
00548 
00549 
00550 // <summary> Generate statistics, tile by tile, from a masked lattice </summary>
00551 //
00552 // <use visibility=export>
00553 //
00554 // <reviewed reviewer="" date="yyyy/mm/dd" tests="" demos="">
00555 // </reviewed>
00556 //
00557 // <prerequisite>
00558 //   <li> <linkto class=LatticeApply>LatticeApply</linkto>
00559 //   <li> <linkto class=TiledCollapser>TiledCollapser</linkto>
00560 // </prerequisite>
00561 //
00562 // <etymology>
00563 // This class is used by <src>LatticeStatistics</src> to generate
00564 // statistical sum from an input <src>MaskedLattice</src>.
00565 // The input lattice is iterated through in tile-sized chunks
00566 // and fed to an object of this class.
00567 // </etymology>
00568 //
00569 // <synopsis>
00570 // <src>StatsTiledCollapser</src> is derived from <src>TiledCollapser</src> which
00571 // is a base class used to define methods.  Objects of this base class are
00572 // used by <src>LatticeApply</src> functions.  In this particular case,
00573 // we are interested in <src>LatticeApply::tiledApply</src>.  This  function iterates
00574 // through a <src>MaskedLattice</src> and allows you to collapse one or more
00575 // axes, computing some values from it, and placing those values into
00576 // an output <src>MaskedLattice</src>.  It iterates through the input
00577 // lattice in optimal tile-sized chunks.    <src>LatticeStatistics</src> 
00578 // uses a <src>StatsTiledCollapser</src> object which it gives to 
00579 // <src>LatticeApply::tiledApply</src> for digestion.  After it has
00580 // done its work, <src>LatticeStatistics</src> then accesses the output
00581 // <src>Lattice</src> that it made.
00582 // </synopsis>
00583 //
00584 // <example>
00585 // <srcblock>
00587 //
00588 //   StatsTiledCollapser<T> collapser(range_p, noInclude_p, noExclude_p,   
00589 //                                    fixedMinMax_p, blcParent_p);
00590 // 
00593 // 
00594 //   Int newOutAxis = outLattice.ndim()-1;
00595 //
00598 //
00599 //   LatticeApply<T>::tiledApply(outLattice, inLattice,
00600 //                               collapser, collapseAxes,
00601 //                               newOutAxis);
00602 //
00603 // </srcblock>
00604 // In this example, a collapser is made and passed to LatticeApply.
00605 // Afterwards, the output Lattice is available for use.
00606 // The Lattices must all be the correct shapes on input to tiledApply
00607 // </example>
00608 //
00609 // <motivation>
00610 // The LatticeApply classes enable the ugly details of optimal
00611 // Lattice iteration to be hidden from the user.
00612 // </motivation>
00613 //
00614 // <todo asof="1998/05/10">   
00615 //   <li> 
00616 // </todo>
00617 
00618 template <class T, class U=T>
00619 class StatsTiledCollapser : public TiledCollapser<T,U>
00620 {
00621 public:
00622 // Constructor provides pixel selection range and whether that
00623 // range is an inclusion or exclusion range.  If <src>fixedMinMax=True</src>
00624 // and an inclusion range is given, the min and max is set to
00625 // that inclusion range.  
00626     StatsTiledCollapser(const Vector<T>& pixelRange, Bool noInclude, 
00627                         Bool noExclude, Bool fixedMinMax);
00628 
00629 // Initialize process, making some checks
00630     virtual void init (uInt nOutPixelsPerCollapse);
00631 
00632 // Initialiaze the accumulator
00633     virtual void initAccumulator (uInt n1, uInt n3);
00634 
00635 // Process the data in the current chunk. 
00636     virtual void process (
00637         uInt accumIndex1, uInt accumIndex3,
00638         const T* inData, const Bool* inMask,
00639         uInt dataIncr, uInt maskIncr,
00640         uInt nrval,     const IPosition& startPos,
00641         const IPosition& shape
00642     );
00643 
00644 // End the accumulation process and return the result arrays
00645     virtual void endAccumulator(Array<U>& result,
00646                                 Array<Bool>& resultMask,
00647                                 const IPosition& shape);
00648 
00649 // Can handle null mask
00650    virtual Bool canHandleNullMask() const {return True;};
00651 
00652 // Find the location of the minimum and maximum data values
00653 // in the input lattice.
00654    void minMaxPos(IPosition& minPos, IPosition& maxPos);
00655 
00656 
00657 private:
00658     Vector<T> range_p;
00659     Bool noInclude_p, noExclude_p, fixedMinMax_p;
00660     IPosition minPos_p, maxPos_p;
00661 
00662 // Accumulators for sum, sum squared, number of points
00663 // minimum, and maximum
00664 
00665     Block<U> *pSum_p;
00666     Block<U> *pSumSq_p;
00667     Block<U>* pNPts_p;
00668     Block<U>* pMean_p;
00669 
00670     Block<U>* pVariance_p;
00671     Block<U>* pNVariance_p;
00672 
00673     Block<T>* pMin_p;
00674     Block<T>* pMax_p;
00675     Block<Bool>* pInitMinMax_p;
00676 //
00677     uInt n1_p;
00678     uInt n3_p;
00679 };
00680 
00681 } //# NAMESPACE CASA - END
00682 
00683 #ifndef CASACORE_NO_AUTO_TEMPLATES
00684 #include <lattices/Lattices/LatticeStatistics.tcc>
00685 #endif //# CASACORE_NO_AUTO_TEMPLATES
00686 #endif