source: trunk/src/Cubes/cubes.hh @ 269

Last change on this file since 269 was 266, checked in by Matthew Whiting, 17 years ago
  • Moved the getopts function to the Param class from the Cube class. It is more logical to have it here, as it is only the parameter set that is affected by the input options.
  • Removed the inline swap function in utils.hh -- changed all calls to it to std::swap.
  • Moved the definition of madfmToSigma to the Statistics.cc file to prevent dodgy compilations.
  • Changed configure.ac so that the order of -lwcs and -lpgsbox are correct.
File size: 20.8 KB
Line 
1#ifndef CUBES_H
2#define CUBES_H
3
4#include <iostream>
5#include <string>
6#include <vector>
7
8#include <param.hh>
9#include <Detection/detection.hh>
10#include <Detection/columns.hh>
11#include <Cubes/plots.hh>
12#include <Utils/Statistics.hh>
13#include <PixelMap/Scan.hh>
14#include <PixelMap/Object2D.hh>
15
16using namespace Column;
17using namespace Statistics;
18using namespace PixelInfo;
19
20/****************************************************************/
21/**
22 * Base class for the image container.
23 *
24 * Definition of an n-dimensional data array:
25 *     array of pixel values, size & dimensions
26 *     array of Detection objects
27 */
28
29class DataArray
30{
31public:
32  DataArray();  ///< Basic DataArray constructor
33  DataArray(short int nDim); ///< Basic nDim-dimensional DataArray constructor
34  DataArray(short int nDim, long size);///< Basic nDim-dimensional DataArray constructor, specifying size.
35  DataArray(short int nDim, long *dimensions); ///< Basic nDim-dimensional DataArray constructor, specifying size of dimensions.
36  virtual ~DataArray(); ///< Basic DataArray constructor
37
38  //-----------------------------------------
39  // Obvious inline accessor functions.
40  //
41  long               getDimX(){if(numDim>0) return this->axisDim[0];else return 0;};
42  long               getDimY(){if(numDim>1) return this->axisDim[1];else return 1;};
43  long               getDimZ(){if(numDim>2) return this->axisDim[2];else return 1;};
44  long               getSize(){ return this->numPixels; };
45  short int          getNumDim(){ return this->numDim; };
46  virtual float      getPixValue(long pos){ return array[pos]; };
47  virtual void       setPixValue(long pos, float f){array[pos] = f;};;
48  Detection          getObject(long number){ return objectList[number]; };
49  std::vector <Detection> getObjectList(){ return objectList; };
50  long               getNumObj(){ return objectList.size(); };
51
52  /** Delete all objects from the list of detections. */
53  void               clearDetectionList(){ this->objectList.clear(); };
54
55  /** Read a parameter set from file. */
56  int                readParam(std::string paramfile){
57    /**
58     *  Uses Param::readParams() to read parameters from a file.
59     *  \param paramfile The file to be read.
60     */
61    return par.readParams(paramfile);
62  };
63
64  //-----------------------------------------
65  // Related to the various arrays
66  //
67  /**  Return first three dimensional axes. */
68  void               getDim(long &x, long &y, long &z);
69  /** Return array of dimensional sizes.*/
70  void               getDimArray(long *output);
71  long *             getDimArray(){return axisDim;};
72
73  /** Return pixel value array. */
74  void               getArray(float *output);
75  float *            getArray(){return array;};
76
77  /** Save pixel value array. */
78  virtual void       saveArray(float *input, long size);
79
80  //-----------------------------------------
81  // Related to the object lists
82  //
83  /** Adds a single detection to the object list.*/
84  void               addObject(Detection object);
85
86  /** Adds all objects in a detection list to the object list. */
87  void               addObjectList(std::vector <Detection> newlist);   
88
89  /** Add pixel offsets to object coordinates. */
90  void               addObjectOffsets();
91
92  //-----------------------------------------
93  // Parameter list related.
94  //
95  /** Output the Param set.*/
96  void               showParam(std::ostream &stream){ stream << this->par; };
97  /** Return the Param set.*/
98  Param              getParam(){ return this->par; };
99  /** Save a Param set to the Cube.*/
100  void               saveParam(Param newpar){this->par = newpar;};
101  /** Provides a reference to the Param set.*/
102  Param&             pars(){ Param &rpar = this->par; return rpar; };
103  /** Is the voxel number given by vox a BLANK value?*/
104  bool               isBlank(int vox);
105
106  // --------------------------------------------
107  // Statistics
108  //
109  /**  Returns the StatsContainer. */
110  StatsContainer<float> getStats(){ return this->Stats; };
111
112  /** Provides a reference to the StatsContainer. */
113  StatsContainer<float>& stats(){
114    StatsContainer<float> &rstats = this->Stats;  return rstats;
115  };
116 
117  /** Save a StatsContainer to the Cube. */
118  void saveStats(StatsContainer<float> newStats){ this->Stats = newStats;};
119
120  /** A detection test for value. */
121  bool isDetection(float value);
122
123  /**  A detection test for pixel.  */
124  bool isDetection(long voxel);
125
126
127  /** Output operator for DataArray.*/
128  friend std::ostream& operator<< (std::ostream& theStream, DataArray &array);
129 
130
131protected:
132  short int               numDim;     ///< Number of dimensions.
133  long                   *axisDim;    ///< Array of dimensions of cube
134                                      ///   (ie. how large in each
135                                      ///        direction).
136  long                    numPixels;  ///< Total number of pixels in cube.
137  float                  *array;      ///< Array of data.
138  std::vector <Detection> objectList; ///< The list of detected objects.
139  Param                   par;        ///< A parameter list.
140  StatsContainer<float>   Stats;      ///< The statistics for the DataArray.
141};
142
143
144
145//=========================================================================
146
147/**
148 * Definition of an data-cube object (3D):
149 *     a DataArray object limited to dim=3
150 */
151
152class Cube : public DataArray
153{
154public:
155  Cube();                 ///< Basic Cube constructor.
156  Cube(long nPix);        ///< Alternative Cube constructor.
157  Cube(long *dimensions); ///< Alternative Cube constructor.
158  virtual ~Cube();        ///< Basic Cube destructor.
159
160  // INLINE functions -- definitions included after class declaration.
161  /** Is the voxel number given by vox a BLANK value? */
162  bool        isBlank(int vox){ return par.isBlank(array[vox]); };
163
164  /** Is the voxel at (x,y,z) a BLANK value? */
165  bool        isBlank(long x, long y, long z){
166    return par.isBlank(array[z*axisDim[0]*axisDim[1] + y*axisDim[0] + x]); };
167
168  /** Does the Cube::recon array exist? */
169  bool        isRecon(){ return reconExists; };
170
171  float       getPixValue(long pos){ return array[pos]; };
172  float       getPixValue(long x, long y, long z){
173    return array[z*axisDim[0]*axisDim[1] + y*axisDim[0] + x]; };
174  short       getDetectMapValue(long pos){ return detectMap[pos]; };
175  short       getDetectMapValue(long x, long y){ return detectMap[y*axisDim[0]+x]; };
176  float       getReconValue(long pos){ return recon[pos]; };
177  float       getReconValue(long x, long y, long z){
178    return recon[z*axisDim[0]*axisDim[1] + y*axisDim[0] + x];};
179  float       getBaselineValue(long pos){ return baseline[pos]; };
180  float       getBaselineValue(long x, long y, long z){
181    return baseline[z*axisDim[0]*axisDim[1] + y*axisDim[0] + x]; };
182  void        setPixValue(long pos, float f){array[pos] = f;};;
183  void        setPixValue(long x, long y, long z, float f){
184    array[z*axisDim[0]*axisDim[1] + y*axisDim[0] + x] = f;};
185  void        setDetectMapValue(long pos, short f){ detectMap[pos] = f;};
186  void        setDetectMapValue(long x, long y, short f){ detectMap[y*axisDim[0] + x] = f;};
187  void        setReconValue(long pos, float f){recon[pos] = f;};
188  void        setReconValue(long x, long y, long z, float f){
189    recon[z*axisDim[0]*axisDim[1] + y*axisDim[0] + x] = f; };
190  void        setReconFlag(bool f){reconExists = f;};
191
192  std::vector<Col> getLogCols(){return logCols;};
193  void        setLogCols(std::vector<Col> C){logCols=C;};
194  std::vector<Col> getFullCols(){return fullCols;};
195  void        setFullCols(std::vector<Col> C){fullCols=C;};
196
197  // additional functions -- in Cubes/cubes.cc
198  /** Allocate memory correctly, with WCS defining the correct axes. */
199  void        initialiseCube(long *dimensions);
200
201  /** Read in a FITS file, with subsection correction. */
202  int         getCube();
203
204  /** Read in command-line options. */
205//   int         getopts(int argc, char ** argv);
206  int         getopts(int argc, char ** argv){return par.getopts(argc,argv);};
207
208  /** Read in reconstructed & smoothed arrays from FITS files on disk. */
209  void        readSavedArrays();
210
211  /** Save an external array to the Cube's pixel array */
212  void        saveArray(float *input, long size);
213
214  /** Save an external array to the Cube's reconstructed array. */
215  void        saveRecon(float *input, long size);
216
217  /** Save reconstructed array to an external array. */
218  void        getRecon(float *output);
219
220  /** Set Milky Way channels to zero. */
221  void        removeMW();
222
223  //------------------------
224  // Statistics for cube
225  //
226
227  /** Calculate the statistics for the Cube (older version). */
228  void        setCubeStatsOld();
229
230  /** Calculate the statistics for the Cube. */
231  void        setCubeStats();
232
233  /** Set up thresholds for the False Discovery Rate routine. */
234  int         setupFDR();
235
236  /** A detection test for a given voxel. */
237  bool        isDetection(long x, long y, long z);
238
239  //-----------------------------
240  // Dealing with the detections
241  //
242
243  /** Calculate the WCS parameters for each Cube Detection. */
244  void        calcObjectWCSparams();
245
246  /** Sort the list of detections. */
247  void        sortDetections();
248
249  /** Update the map of detected pixels. */
250  void        updateDetectMap();
251
252  /** Update the map of detected pixels for a given Detection. */
253  void        updateDetectMap(Detection obj);
254
255  /** Find the flux enclosed by a Detection. */
256  float       enclosedFlux(Detection obj);
257
258  /** Set up the output column definitions for the Cube and its
259      Detection list. */
260  void        setupColumns();
261
262  /** Is the object at the edge of the image? */
263  bool        objAtSpatialEdge(Detection obj);
264
265  /** Is the object at an end of the spectrum? */
266  bool        objAtSpectralEdge(Detection obj);
267
268  /** Set warning flags for the detections. */
269  void        setObjectFlags();
270
271  // ----------------------------
272  // Dealing with the WCS
273  //
274  FitsHeader  getHead(){ return head; };
275  void        setHead(FitsHeader F){head = F;};
276  FitsHeader& header(){ FitsHeader &h = head; return h; };
277
278  /** Convert a point from WCS to Pixel coords. */
279  int         wcsToPix(const double *world, double *pix);
280
281  /** Convert a set of points from WCS to Pixel coords. */
282  int         wcsToPix(const double *world, double *pix, const int npts);
283
284  /** Convert a point from Pixel to WCS coords. */
285  int         pixToWCS(const double *pix, double *world);
286
287  /** Convert a set of points from Pixel to WCS coords. */
288  int         pixToWCS(const double *pix, double *world, const int npts);
289
290  //-------------------------------------------
291  // FITS-I/O related functions -- not in cubes.cc
292  //
293  /** Function to read in FITS file.*/
294  int         getCube(std::string fname);  // in Cubes/getImage.cc
295
296  /** Function to retrieve FITS data array */
297  int         getFITSdata(std::string fname);   // in FitsIO/dataIO.cc
298
299  /** Save Hanning-smoothed array to disk.*/
300  void        saveSmoothedCube();       // in Cubes/saveImage.cc
301
302  /** Save Reconstructed array to disk. */
303  void        saveReconstructedCube();  // in Cubes/saveImage.cc
304
305  /** Read in reconstructed array from FITS file. */
306  int         readReconCube();  // in Cubes/readRecon.cc
307 
308  /** Read in Hanning-smoothed array from FITS file. */
309  int         readSmoothCube();     // in Cubes/readSmooth.cc 
310
311  //-------------------------------------
312  // Functions that act on the cube
313  //
314
315  /** Remove excess BLANK pixels from spatial edge of cube. */
316  void        trimCube();         // in Cubes/trimImage.cc
317
318  /** Replace BLANK pixels to spatial edge of cube. */
319  void        unTrimCube();       // in Cubes/trimImage.cc
320
321  /** Removes the baselines from the spectra, and stores in Cube::baseline */
322  void        removeBaseline();   // in Cubes/baseline.cc
323
324  /** Replace the baselines stored in Cube::baseline */
325  void        replaceBaseline();  // in Cubes/baseline.cc
326
327  /** Multiply all pixel values by -1. */
328  void        invert();           // in Cubes/invertCube.cc
329
330  /** Undo the inversion, and invert fluxes of all detected objects. */
331  void        reInvert();         // in Cubes/invertCube.cc
332
333  //-------------------------------------
334  // Reconstruction, Searching and Merging functions
335  //
336  // in ATrous/ReconSearch.cc
337  /** Front-end to reconstruction & searching functions.*/
338  void        ReconSearch();
339  /** Switcher to reconstruction functions */
340  void        ReconCube();
341  /** Performs 1-dimensional a trous reconstruction on the Cube. */
342  void        ReconCube1D();
343  /** Performs 2-dimensional a trous reconstruction on the Cube. */
344  void        ReconCube2D();
345  /** Performs 3-dimensional a trous reconstruction on the Cube. */
346  void        ReconCube3D();
347
348  // in Cubes/CubicSearch.cc
349  /** Front-end to the cubic searching routine. */
350  void        CubicSearch();
351
352  // in Cubes/smoothCube.cc
353  /** Front-end to the smoothing and searching functions. */
354  void        SmoothSearch();
355  /** A function to Hanning-smooth the cube. */
356  void        SmoothCube();
357
358  // in Cubes/Merger.cc
359  /** Merge all objects in the detection list so that only distinct
360      ones are left. */
361  void        ObjectMerger();
362 
363  //-------------------------------------
364  // Text outputting of detected objects.
365  //   in Cubes/detectionIO.cc
366  //
367  /** Output detections to a Karma annotation file. */
368  void        outputDetectionsKarma(std::ostream &stream);
369
370  /** Output detections to a VOTable. */
371  void        outputDetectionsVOTable(std::ostream &stream);
372
373  /** Output detections to the output file and standard output. */
374  void        outputDetectionList();
375
376  /** Output detections to the log file. */
377  void        logDetectionList();
378
379  /** Output a single detection to the log file. */
380  void        logDetection(Detection obj, int counter);
381
382
383  // ----------------------------------
384  // Graphical plotting of the cube and the detections.
385  //
386  /** Draw blank edges of cube. */
387  void        plotBlankEdges();  // in cubes.cc
388
389  //  in Cubes/plotting.cc
390  /** Plot a spatial map of detections based on number of detected
391      channels. */
392  void        plotDetectionMap(std::string pgDestination);
393
394  /** Plot a spatial map of detections based on 0th moment map of each
395      object. */
396  void        plotMomentMap(std::string pgDestination);
397
398  /** Plot a spatial map of detections based on 0th moment map of each
399      object to a number of PGPLOT devices. */
400  void        plotMomentMap(std::vector<std::string> pgDestination);
401
402  /** Draw WCS axes over a PGPLOT map. */
403  void        plotWCSaxes();
404
405  //  in Cubes/outputSpectra.cc
406  /** Print spectra of each detected object. */
407  void        outputSpectra();
408
409  /** Print spectrum of a single object */
410  void        plotSpectrum(Detection obj,Plot::SpectralPlot &plot);
411
412  //  in Cubes/drawMomentCutout.cc
413  /** Draw the 0th moment map for a single object. */
414  void        drawMomentCutout(Detection &object);
415
416  /** Draw a scale bar indicating angular size of the cutout. */
417  void        drawScale(float xstart,float ystart,float channel);
418
419  /** Draw a yellow line around the edge of the spatial extent of
420      pixels. */
421  void        drawFieldEdge();
422
423private:
424  float      *recon;            ///< reconstructed array - used when
425                                ///   doing a trous reconstruction.
426  bool        reconExists;      ///< flag saying whether there is a
427                                ///   reconstruction
428  short      *detectMap;        ///< "moment map" - x,y locations of
429                                ///   detected pixels
430  float      *baseline;         ///< array of spectral baseline
431                                ///   values.
432                             
433  bool        reconAllocated;   ///< have we allocated memory for the
434                                ///   recon array?
435  bool        baselineAllocated;///< have we allocated memory for the
436                                ///   baseline array?
437  FitsHeader  head;             ///< the WCS and other header
438                                ///   information.
439  std::vector<Col> fullCols;    ///< the list of all columns as
440                                ///   printed in the results file
441  std::vector<Col> logCols;     ///< the list of columns as printed in
442                                ///   the log file
443
444};
445
446////////////
447//// Cube inline function definitions
448////////////
449
450inline int Cube::wcsToPix(const double *world, double *pix)
451{
452  /**
453   *  Use the WCS in the FitsHeader to convert from WCS to pixel coords for
454   *   a single point.
455   *  \param world The world coordinates.
456   *  \param pix The returned pixel coordinates.
457   */
458  return this->head.wcsToPix(world,pix);
459}
460inline int Cube::wcsToPix(const double *world, double *pix, const int npts)
461{
462  /**
463   *  Use the WCS in the FitsHeader to convert from WCS to pixel coords for
464   *   a set of points.
465   *  \param world The world coordinates.
466   *  \param pix The returned pixel coordinates.
467   *  \param npts The number of points being converted.
468   */
469  return this->head.wcsToPix(world,pix,npts);
470}
471inline int Cube::pixToWCS(const double *pix, double *world)
472{
473  /**
474   *  Use the WCS in the FitsHeader to convert from pixel to WCS coords for
475   *   a single point.
476   *  \param pix The pixel coordinates.
477   *  \param world The returned world coordinates.
478   */
479  return this->head.pixToWCS(pix,world);
480}
481inline int Cube::pixToWCS(const double *pix, double *world, const int npts)
482{
483  /**
484   *  Use the WCS in the FitsHeader to convert from pixel to WCS coords for
485   *   a set of points.
486   *  \param pix The pixel coordinates.
487   *  \param world The returned world coordinates.
488   *  \param npts The number of points being converted.
489   */
490  return this->head.pixToWCS(pix,world,npts);
491}
492
493
494//===============================================================================
495
496/**
497 *  A DataArray object limited to two dimensions, and with some additional
498 *   special functions.
499 *
500 *  It is used primarily for searching a 1- or 2-D array with
501 *   lutz_detect() and spectrumDetect().
502 */
503
504class Image : public DataArray
505{
506public:
507  Image(){numPixels=0; numDim=2;};
508  Image(long nPix);
509  Image(long *dimensions);
510  virtual ~Image(){};
511
512  //--------------------
513  // Defining the array
514  //
515  /** Save an external array to the Cube's pixel array */
516  void      saveArray(float *input, long size);
517
518  /** Extract a spectrum from an array and save to the local pixel array. */
519  void      extractSpectrum(float *Array, long *dim, long pixel);
520
521  /** Extract an image from an array and save to the local pixel array. */
522  void      extractImage(float *Array, long *dim, long channel);
523
524  /** Extract a spectrum from a cube and save to the local pixel array. */
525  void      extractSpectrum(Cube &cube, long pixel);
526
527  /** Extract an image from a cube and save to the local pixel array. */
528  void      extractImage(Cube &cube, long channel);
529
530  //--------------------
531  // Accessing the data.
532  //
533  float     getPixValue(long pos){ return array[pos]; };
534  float     getPixValue(long x, long y){return array[y*axisDim[0] + x];};
535  // the next few should have checks against array overflow...
536  void      setPixValue(long pos, float f){array[pos] = f;};;
537  void      setPixValue(long x, long y, float f){array[y*axisDim[0] + x] = f;};
538  bool      isBlank(int vox){return par.isBlank(array[vox]);};
539  bool      isBlank(long x,long y){return par.isBlank(array[y*axisDim[0]+x]);};
540
541  //-----------------------
542  // Detection-related
543  //
544  /** Detect objects in a 2-D image */
545  std::vector<Object2D> lutz_detect();    // in Detection/lutz_detect.cc
546
547  /** Detect objects in a 1-D spectrum */
548  std::vector<Scan> spectrumDetect();     // in Detection/spectrumDetect.cc
549
550  int       getMinSize(){return minSize;};
551  void      setMinSize(int i){minSize=i;};
552
553  /**  A detection test for a pixel location.  */
554  bool      isDetection(long x, long y){
555    /**
556     * Test whether a pixel (x,y) is a statistically significant detection,
557     * according to the set of statistics in the local StatsContainer object.
558     */
559    long voxel = y*axisDim[0] + x;
560    if(isBlank(x,y)) return false;
561    else return Stats.isDetection(array[voxel]);
562  }; 
563
564  /** Blank out a set of channels marked as being Milky Way channels */
565  void      removeMW();
566
567private:
568  int       minSize;    ///< the minimum number of pixels for a
569                        ///   detection to be accepted.
570};
571
572
573/****************************************************************/
574//////////////////////////////////////////////////////
575// Prototypes for functions that use above classes
576//////////////////////////////////////////////////////
577
578/** Search a reconstructed array for significant detections. */
579std::vector <Detection> searchReconArray(long *dim, float *originalArray,
580                                         float *reconArray, Param &par,
581                                         StatsContainer<float> &stats);
582std::vector <Detection> searchReconArraySimple(long *dim, float *originalArray,
583                                               float *reconArray, Param &par,
584                                               StatsContainer<float> &stats);
585
586/** Search a 3-dimensional array for significant detections. */
587std::vector <Detection> search3DArray(long *dim, float *Array, Param &par,
588                                      StatsContainer<float> &stats);
589std::vector <Detection> search3DArraySimple(long *dim, float *Array,
590                                            Param &par,
591                                            StatsContainer<float> &stats);
592
593/** Grow an object to a lower threshold */
594void growObject(Detection &object, Cube &cube);
595
596/** Draw the edge of the BLANK region on a map.*/
597void drawBlankEdges(float *dataArray, int xdim, int ydim, Param &par);
598
599#endif
Note: See TracBrowser for help on using the repository browser.