source: branches/pixel-map-branch/src/Cubes/cubes.hh @ 1339

Last change on this file since 1339 was 252, checked in by Matthew Whiting, 17 years ago
  • Have put all classes in the files in src/PixelMap/ into a PixelInfo? namespace.
  • Added "using namespace PixelInfo?" to all necessary files.
  • Removed "friend class Detection" from Voxel and Object3D classes -- not necessary and complicated now by them being in the namespace
  • Various minor changes, including fixing up commentary.
File size: 20.4 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
207  /** Read in reconstructed & smoothed arrays from FITS files on disk. */
208  void        readSavedArrays();
209
210  /** Save an external array to the Cube's pixel array */
211  void        saveArray(float *input, long size);
212
213  /** Save an external array to the Cube's reconstructed array. */
214  void        saveRecon(float *input, long size);
215
216  /** Save reconstructed array to an external array. */
217  void        getRecon(float *output);
218
219  /** Set Milky Way channels to zero. */
220  void        removeMW();
221
222  //------------------------
223  // Statistics for cube
224  //
225
226  /** Calculate the statistics for the Cube (older version). */
227  void        setCubeStatsOld();
228
229  /** Calculate the statistics for the Cube. */
230  void        setCubeStats();
231
232  /** Set up thresholds for the False Discovery Rate routine. */
233  int         setupFDR();
234
235  /** A detection test for a given voxel. */
236  bool        isDetection(long x, long y, long z);
237
238  //-----------------------------
239  // Dealing with the detections
240  //
241
242  /** Calculate the WCS parameters for each Cube Detection. */
243  void        calcObjectWCSparams();
244
245  /** Sort the list of detections. */
246  void        sortDetections();
247
248  /** Update the map of detected pixels. */
249  void        updateDetectMap();
250
251  /** Update the map of detected pixels for a given Detection. */
252  void        updateDetectMap(Detection obj);
253
254  /** Find the flux enclosed by a Detection. */
255  float       enclosedFlux(Detection obj);
256
257  /** Set up the output column definitions for the Cube and its
258      Detection list. */
259  void        setupColumns();
260
261  /** Is the object at the edge of the image? */
262  bool        objAtSpatialEdge(Detection obj);
263
264  /** Is the object at an end of the spectrum? */
265  bool        objAtSpectralEdge(Detection obj);
266
267  /** Set warning flags for the detections. */
268  void        setObjectFlags();
269
270  // ----------------------------
271  // Dealing with the WCS
272  //
273  FitsHeader  getHead(){ return head; };
274  void        setHead(FitsHeader F){head = F;};
275  FitsHeader& header(){ FitsHeader &h = head; return h; };
276
277  /** Convert a point from WCS to Pixel coords. */
278  int         wcsToPix(const double *world, double *pix);
279
280  /** Convert a set of points from WCS to Pixel coords. */
281  int         wcsToPix(const double *world, double *pix, const int npts);
282
283  /** Convert a point from Pixel to WCS coords. */
284  int         pixToWCS(const double *pix, double *world);
285
286  /** Convert a set of points from Pixel to WCS coords. */
287  int         pixToWCS(const double *pix, double *world, const int npts);
288
289  //-------------------------------------------
290  // FITS-I/O related functions -- not in cubes.cc
291  //
292  /** Function to read in FITS file.*/
293  int         getCube(std::string fname);  // in Cubes/getImage.cc
294
295  /** Function to retrieve FITS data array */
296  int         getFITSdata(std::string fname);   // in FitsIO/dataIO.cc
297
298  /** Save Hanning-smoothed array to disk.*/
299  void        saveSmoothedCube();       // in Cubes/saveImage.cc
300
301  /** Save Reconstructed array to disk. */
302  void        saveReconstructedCube();  // in Cubes/saveImage.cc
303
304  /** Read in reconstructed array from FITS file. */
305  int         readReconCube();  // in Cubes/readRecon.cc
306 
307  /** Read in Hanning-smoothed array from FITS file. */
308  int         readSmoothCube();     // in Cubes/readSmooth.cc 
309
310  //-------------------------------------
311  // Functions that act on the cube
312  //
313
314  /** Remove excess BLANK pixels from spatial edge of cube. */
315  void        trimCube();         // in Cubes/trimImage.cc
316
317  /** Replace BLANK pixels to spatial edge of cube. */
318  void        unTrimCube();       // in Cubes/trimImage.cc
319
320  /** Removes the baselines from the spectra, and stores in Cube::baseline */
321  void        removeBaseline();   // in Cubes/baseline.cc
322
323  /** Replace the baselines stored in Cube::baseline */
324  void        replaceBaseline();  // in Cubes/baseline.cc
325
326  /** Multiply all pixel values by -1. */
327  void        invert();           // in Cubes/invertCube.cc
328
329  /** Undo the inversion, and invert fluxes of all detected objects. */
330  void        reInvert();         // in Cubes/invertCube.cc
331
332  //-------------------------------------
333  // Reconstruction, Searching and Merging functions
334  //
335  // in ATrous/ReconSearch.cc
336  /** Front-end to reconstruction & searching functions.*/
337  void        ReconSearch();
338  /** Switcher to reconstruction functions */
339  void        ReconCube();
340  /** Performs 1-dimensional a trous reconstruction on the Cube. */
341  void        ReconCube1D();
342  /** Performs 2-dimensional a trous reconstruction on the Cube. */
343  void        ReconCube2D();
344  /** Performs 3-dimensional a trous reconstruction on the Cube. */
345  void        ReconCube3D();
346
347  // in Cubes/CubicSearch.cc
348  /** Front-end to the cubic searching routine. */
349  void        CubicSearch();
350
351  // in Cubes/smoothCube.cc
352  /** Front-end to the smoothing and searching functions. */
353  void        SmoothSearch();
354  /** A function to Hanning-smooth the cube. */
355  void        SmoothCube();
356
357  // in Cubes/Merger.cc
358  /** Merge all objects in the detection list so that only distinct
359      ones are left. */
360  void        ObjectMerger();
361 
362  //-------------------------------------
363  // Text outputting of detected objects.
364  //   in Cubes/detectionIO.cc
365  //
366  /** Output detections to a Karma annotation file. */
367  void        outputDetectionsKarma(std::ostream &stream);
368
369  /** Output detections to a VOTable. */
370  void        outputDetectionsVOTable(std::ostream &stream);
371
372  /** Output detections to the output file and standard output. */
373  void        outputDetectionList();
374
375  /** Output detections to the log file. */
376  void        logDetectionList();
377
378  /** Output a single detection to the log file. */
379  void        logDetection(Detection obj, int counter);
380
381
382  // ----------------------------------
383  // Graphical plotting of the cube and the detections.
384  //
385  /** Draw blank edges of cube. */
386  void        plotBlankEdges();  // in cubes.cc
387
388  //  in Cubes/plotting.cc
389  /** Plot a spatial map of detections based on number of detected
390      channels. */
391  void        plotDetectionMap(std::string pgDestination);
392
393  /** Plot a spatial map of detections based on 0th moment map of each
394      object. */
395  void        plotMomentMap(std::string pgDestination);
396
397  /** Plot a spatial map of detections based on 0th moment map of each
398      object to a number of PGPLOT devices. */
399  void        plotMomentMap(std::vector<std::string> pgDestination);
400
401  /** Draw WCS axes over a PGPLOT map. */
402  void        plotWCSaxes();
403
404  //  in Cubes/outputSpectra.cc
405  /** Print spectra of each detected object. */
406  void        outputSpectra();
407
408  /** Print spectrum of a single object */
409  void        plotSpectrum(Detection obj,Plot::SpectralPlot &plot);
410
411  //  in Cubes/drawMomentCutout.cc
412  /** Draw the 0th moment map for a single object. */
413  void        drawMomentCutout(Detection &object);
414
415  /** Draw a scale bar indicating angular size of the cutout. */
416  void        drawScale(float xstart,float ystart,float channel);
417
418  /** Draw a yellow line around the edge of the spatial extent of
419      pixels. */
420  void        drawFieldEdge();
421
422private:
423  float      *recon;            ///< reconstructed array - used when
424                                ///   doing a trous reconstruction.
425  bool        reconExists;      ///< flag saying whether there is a
426                                ///   reconstruction
427  short      *detectMap;        ///< "moment map" - x,y locations of
428                                ///   detected pixels
429  float      *baseline;         ///< array of spectral baseline
430                                ///   values.
431                             
432  bool        reconAllocated;   ///< have we allocated memory for the
433                                ///   recon array?
434  bool        baselineAllocated;///< have we allocated memory for the
435                                ///   baseline array?
436  FitsHeader  head;             ///< the WCS and other header
437                                ///   information.
438  std::vector<Col> fullCols;    ///< the list of all columns as
439                                ///   printed in the results file
440  std::vector<Col> logCols;     ///< the list of columns as printed in
441                                ///   the log file
442
443};
444
445////////////
446//// Cube inline function definitions
447////////////
448
449inline int Cube::wcsToPix(const double *world, double *pix)
450{
451  /**
452   *  Use the WCS in the FitsHeader to convert from WCS to pixel coords for
453   *   a single point.
454   *  \param world The world coordinates.
455   *  \param pix The returned pixel coordinates.
456   */
457  return this->head.wcsToPix(world,pix);
458}
459inline int Cube::wcsToPix(const double *world, double *pix, const int npts)
460{
461  /**
462   *  Use the WCS in the FitsHeader to convert from WCS to pixel coords for
463   *   a set of points.
464   *  \param world The world coordinates.
465   *  \param pix The returned pixel coordinates.
466   *  \param npts The number of points being converted.
467   */
468  return this->head.wcsToPix(world,pix,npts);
469}
470inline int Cube::pixToWCS(const double *pix, double *world)
471{
472  /**
473   *  Use the WCS in the FitsHeader to convert from pixel to WCS coords for
474   *   a single point.
475   *  \param pix The pixel coordinates.
476   *  \param world The returned world coordinates.
477   */
478  return this->head.pixToWCS(pix,world);
479}
480inline int Cube::pixToWCS(const double *pix, double *world, const int npts)
481{
482  /**
483   *  Use the WCS in the FitsHeader to convert from pixel to WCS coords for
484   *   a set of points.
485   *  \param pix The pixel coordinates.
486   *  \param world The returned world coordinates.
487   *  \param npts The number of points being converted.
488   */
489  return this->head.pixToWCS(pix,world,npts);
490}
491
492
493//===============================================================================
494
495/**
496 *  A DataArray object limited to two dimensions, and with some additional
497 *   special functions.
498 *
499 *  It is used primarily for searching a 1- or 2-D array with
500 *   lutz_detect() and spectrumDetect().
501 */
502
503class Image : public DataArray
504{
505public:
506  Image(){numPixels=0; numDim=2;};
507  Image(long nPix);
508  Image(long *dimensions);
509  virtual ~Image(){};
510
511  //--------------------
512  // Defining the array
513  //
514  /** Save an external array to the Cube's pixel array */
515  void      saveArray(float *input, long size);
516
517  /** Extract a spectrum from an array and save to the local pixel array. */
518  void      extractSpectrum(float *Array, long *dim, long pixel);
519
520  /** Extract an image from an array and save to the local pixel array. */
521  void      extractImage(float *Array, long *dim, long channel);
522
523  /** Extract a spectrum from a cube and save to the local pixel array. */
524  void      extractSpectrum(Cube &cube, long pixel);
525
526  /** Extract an image from a cube and save to the local pixel array. */
527  void      extractImage(Cube &cube, long channel);
528
529  //--------------------
530  // Accessing the data.
531  //
532  float     getPixValue(long pos){ return array[pos]; };
533  float     getPixValue(long x, long y){return array[y*axisDim[0] + x];};
534  // the next few should have checks against array overflow...
535  void      setPixValue(long pos, float f){array[pos] = f;};;
536  void      setPixValue(long x, long y, float f){array[y*axisDim[0] + x] = f;};
537  bool      isBlank(int vox){return par.isBlank(array[vox]);};
538  bool      isBlank(long x,long y){return par.isBlank(array[y*axisDim[0]+x]);};
539
540  //-----------------------
541  // Detection-related
542  //
543  /** Detect objects in a 2-D image */
544  std::vector<Object2D> lutz_detect();    // in Detection/lutz_detect.cc
545
546  /** Detect objects in a 1-D spectrum */
547  std::vector<Scan> spectrumDetect();     // in Detection/spectrumDetect.cc
548
549  int       getMinSize(){return minSize;};
550  void      setMinSize(int i){minSize=i;};
551
552  /**  A detection test for a pixel location.  */
553  bool      isDetection(long x, long y){
554    /**
555     * Test whether a pixel (x,y) is a statistically significant detection,
556     * according to the set of statistics in the local StatsContainer object.
557     */
558    long voxel = y*axisDim[0] + x;
559    if(isBlank(x,y)) return false;
560    else return Stats.isDetection(array[voxel]);
561  }; 
562
563  /** Blank out a set of channels marked as being Milky Way channels */
564  void      removeMW();
565
566private:
567  int       minSize;    ///< the minimum number of pixels for a
568                        ///   detection to be accepted.
569};
570
571
572/****************************************************************/
573//////////////////////////////////////////////////////
574// Prototypes for functions that use above classes
575//////////////////////////////////////////////////////
576
577/** Search a reconstructed array for significant detections. */
578std::vector <Detection> searchReconArray(long *dim, float *originalArray,
579                                         float *reconArray, Param &par,
580                                         StatsContainer<float> &stats);
581
582/** Search a 3-dimensional array for significant detections. */
583std::vector <Detection> search3DArray(long *dim, float *Array, Param &par,
584                                      StatsContainer<float> &stats);
585
586/** Grow an object to a lower threshold */
587void growObject(Detection &object, Cube &cube);
588
589/** Draw the edge of the BLANK region on a map.*/
590void drawBlankEdges(float *dataArray, int xdim, int ydim, Param &par);
591
592#endif
Note: See TracBrowser for help on using the repository browser.