source: trunk/src/Cubes/cubes.cc @ 500

Last change on this file since 500 was 496, checked in by MatthewWhiting, 16 years ago

Allowing initialisation of a cube without the allocation of the pixel arrays. This comes from askapsoft development - not used by normal Duchamp work.

File size: 53.2 KB
Line 
1// -----------------------------------------------------------------------
2// cubes.cc: Member functions for the DataArray, Cube and Image classes.
3// -----------------------------------------------------------------------
4// Copyright (C) 2006, Matthew Whiting, ATNF
5//
6// This program is free software; you can redistribute it and/or modify it
7// under the terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 2 of the License, or (at your
9// option) any later version.
10//
11// Duchamp is distributed in the hope that it will be useful, but WITHOUT
12// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14// for more details.
15//
16// You should have received a copy of the GNU General Public License
17// along with Duchamp; if not, write to the Free Software Foundation,
18// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
19//
20// Correspondence concerning Duchamp may be directed to:
21//    Internet email: Matthew.Whiting [at] atnf.csiro.au
22//    Postal address: Dr. Matthew Whiting
23//                    Australia Telescope National Facility, CSIRO
24//                    PO Box 76
25//                    Epping NSW 1710
26//                    AUSTRALIA
27// -----------------------------------------------------------------------
28#include <unistd.h>
29#include <iostream>
30#include <iomanip>
31#include <vector>
32#include <algorithm>
33#include <string>
34#include <math.h>
35
36#include <wcslib/wcs.h>
37
38#include <duchamp/pgheader.hh>
39
40#include <duchamp/duchamp.hh>
41#include <duchamp/param.hh>
42#include <duchamp/fitsHeader.hh>
43#include <duchamp/Cubes/cubes.hh>
44#include <duchamp/PixelMap/Voxel.hh>
45#include <duchamp/PixelMap/Object3D.hh>
46#include <duchamp/Detection/detection.hh>
47#include <duchamp/Detection/columns.hh>
48#include <duchamp/Utils/utils.hh>
49#include <duchamp/Utils/mycpgplot.hh>
50#include <duchamp/Utils/Statistics.hh>
51
52using namespace mycpgplot;
53using namespace Statistics;
54using namespace PixelInfo;
55
56#ifdef TEST_DEBUG
57const bool TESTING=true;
58#else
59const bool TESTING=false;
60#endif
61
62namespace duchamp
63{
64
65  using namespace Column;
66
67  /****************************************************************/
68  ///////////////////////////////////////////////////
69  //// Functions for DataArray class:
70  ///////////////////////////////////////////////////
71
72  DataArray::DataArray(){
73    /**
74     * Fundamental constructor for DataArray.
75     * Number of dimensions and pixels are set to 0. Nothing else allocated.
76     */
77    this->numDim=0;
78    this->numPixels=0;
79    this->objectList = new std::vector<Detection>;
80    this->axisDimAllocated = false;
81    this->arrayAllocated = false;
82  }
83  //--------------------------------------------------------------------
84
85  DataArray::DataArray(short int nDim){
86    /**
87     * N-dimensional constructor for DataArray.
88     * Number of dimensions defined, and dimension array allocated.
89     * Number of pixels are set to 0.
90     * \param nDim Number of dimensions.
91     */
92    this->axisDimAllocated = false;
93    this->arrayAllocated = false;
94    if(nDim>0){
95      this->axisDim = new long[nDim];
96      this->axisDimAllocated = true;
97    }
98    this->numDim=nDim;
99    this->numPixels=0;
100    this->objectList = new std::vector<Detection>;
101  }
102  //--------------------------------------------------------------------
103
104  DataArray::DataArray(short int nDim, long size){
105    /**
106     * N-dimensional constructor for DataArray.
107     * Number of dimensions and number of pixels defined.
108     * Arrays allocated based on these values.
109     * \param nDim Number of dimensions.
110     * \param size Number of pixels.
111     *
112     * Note that we can assign values to the dimension array.
113     */
114
115    this->axisDimAllocated = false;
116    this->arrayAllocated = false;
117    if(size<0)
118      duchampError("DataArray(nDim,size)",
119                   "Negative size -- could not define DataArray");
120    else if(nDim<0)
121      duchampError("DataArray(nDim,size)",
122                   "Negative number of dimensions: could not define DataArray");
123    else {
124      if(size>0){
125        this->array = new float[size];
126        this->arrayAllocated = true;
127      }
128      this->numPixels = size;
129      if(nDim>0){
130        this->axisDim = new long[nDim];
131        this->axisDimAllocated = true;
132      }
133      this->numDim = nDim;
134    }
135    this->objectList = new std::vector<Detection>;
136  }
137  //--------------------------------------------------------------------
138
139  DataArray::DataArray(short int nDim, long *dimensions)
140  {
141    /**
142     * Most robust constructor for DataArray.
143     * Number and sizes of dimensions are defined, and hence the number of
144     * pixels. Arrays allocated based on these values.
145     * \param nDim Number of dimensions.
146     * \param dimensions Array giving sizes of dimensions.
147     */
148    this->axisDimAllocated = false;
149    this->arrayAllocated = false;
150    if(nDim<0)
151      duchampError("DataArray(nDim,dimArray)",
152                   "Negative number of dimensions: could not define DataArray");
153    else {
154      int size = dimensions[0];
155      for(int i=1;i<nDim;i++) size *= dimensions[i];
156      if(size<0)
157        duchampError("DataArray(nDim,dimArray)",
158                     "Negative size: could not define DataArray");
159      else{
160        this->numPixels = size;
161        if(size>0){
162          this->array = new float[size];
163          this->arrayAllocated = true;
164        }
165        this->numDim=nDim;
166        if(nDim>0){
167          this->axisDim = new long[nDim];
168          this->axisDimAllocated = true;
169        }
170        for(int i=0;i<nDim;i++) this->axisDim[i] = dimensions[i];
171      }
172    }
173  }
174  //--------------------------------------------------------------------
175
176  DataArray::~DataArray()
177  {
178    /**
179     *  Destructor -- arrays deleted if they have been allocated, and the
180     *   object list is deleted.
181     */
182    if(this->numPixels>0 && this->arrayAllocated){
183      delete [] this->array;
184      this->arrayAllocated = false;
185    }
186    if(this->numDim>0 && this->axisDimAllocated){
187      delete [] this->axisDim;
188      this->axisDimAllocated = false;
189    }
190    delete this->objectList;
191  }
192  //--------------------------------------------------------------------
193  //--------------------------------------------------------------------
194
195  void DataArray::getDim(long &x, long &y, long &z){
196    /**
197     * The sizes of the first three dimensions (if they exist) are returned.
198     * \param x The first dimension. Defaults to 0 if numDim \f$\le\f$ 0.
199     * \param y The second dimension. Defaults to 1 if numDim \f$\le\f$ 1.
200     * \param z The third dimension. Defaults to 1 if numDim \f$\le\f$ 2.
201     */
202    if(this->numDim>0) x=this->axisDim[0];
203    else x=0;
204    if(this->numDim>1) y=this->axisDim[1];
205    else y=1;
206    if(this->numDim>2) z=this->axisDim[2];
207    else z=1;
208  }
209  //--------------------------------------------------------------------
210
211  void DataArray::getDimArray(long *output){
212    /**
213     * The axisDim array is written to output. This needs to be defined
214     *  beforehand: no checking is done on the memory.
215     * \param output The array that is written to.
216     */
217    for(int i=0;i<this->numDim;i++) output[i] = this->axisDim[i];
218  }
219  //--------------------------------------------------------------------
220
221  void DataArray::getArray(float *output){
222    /**
223     * The pixel value array is written to output. This needs to be defined
224     *  beforehand: no checking is done on the memory.
225     * \param output The array that is written to.
226     */
227    for(int i=0;i<this->numPixels;i++) output[i] = this->array[i];
228  }
229  //--------------------------------------------------------------------
230
231  void DataArray::saveArray(float *input, long size){
232    /**
233     * Saves the array in input to the pixel array DataArray::array.
234     * The size of the array given must be the same as the current number of
235     * pixels, else an error message is returned and nothing is done.
236     * \param input The array of values to be saved.
237     * \param size The size of input.
238     */
239    if(size != this->numPixels)
240      duchampError("DataArray::saveArray",
241                   "Input array different size to existing array. Cannot save.");
242    else {
243      if(this->numPixels>0 && this->arrayAllocated) delete [] this->array;
244      this->numPixels = size;
245      this->array = new float[size];
246      this->arrayAllocated = true;
247      for(int i=0;i<size;i++) this->array[i] = input[i];
248    }
249  }
250  //--------------------------------------------------------------------
251
252  void DataArray::addObject(Detection object){
253    /**
254     * \param object The object to be added to the object list.
255     */
256    // objectList is a vector, so just use push_back()
257    this->objectList->push_back(object);
258  }
259  //--------------------------------------------------------------------
260
261  void DataArray::addObjectList(std::vector <Detection> newlist) {
262    /**
263     * \param newlist The list of objects to be added to the object list.
264     */
265    for(int i=0;i<newlist.size();i++) this->objectList->push_back(newlist[i]);
266  }
267  //--------------------------------------------------------------------
268
269  bool DataArray::isDetection(float value){
270    /**
271     * Is a given value a detection, based on the statistics in the
272     * DataArray's StatsContainer?
273     * \param value The pixel value to test.
274     */
275    if(par.isBlank(value)) return false;
276    else return Stats.isDetection(value);
277  }
278  //--------------------------------------------------------------------
279
280  bool DataArray::isDetection(long voxel){
281    /**
282     * Is a given pixel a detection, based on the statistics in the
283     * DataArray's StatsContainer?
284     * If the pixel lies outside the valid range for the data array, return false.
285     * \param voxel Location of the DataArray's pixel to be tested.
286     */
287    if((voxel<0)||(voxel>this->numPixels)) return false;
288    else if(par.isBlank(this->array[voxel])) return false;
289    else return Stats.isDetection(this->array[voxel]);
290  } 
291  //--------------------------------------------------------------------
292
293  std::ostream& operator<< ( std::ostream& theStream, DataArray &array)
294  {
295    /**
296     * A way to print out the pixel coordinates & flux values of the
297     * list of detected objects belonging to the DataArray.
298     * These are formatted nicely according to the << operator for Detection,
299     *  with a line indicating the number of detections at the start.
300     * \param theStream The ostream object to which the output should be sent.
301     * \param array The DataArray containing the list of objects.
302     */
303    for(int i=0;i<array.numDim;i++){
304      if(i>0) theStream<<"x";
305      theStream<<array.axisDim[i];
306    }
307    theStream<<std::endl;
308
309    theStream<<"Threshold\tmiddle\tspread\trobust\n" << array.stats().getThreshold() << "\t";
310    if(array.pars().getFlagUserThreshold())
311      theStream << "0.0000\t" << array.stats().getThreshold() << "\t";
312    else
313      theStream << array.stats().getMiddle() << " " << array.stats().getSpread() << "\t";
314    theStream << array.stats().getRobust()<<"\n";
315
316    theStream<<array.objectList->size()<<" detections:\n--------------\n";
317    for(int i=0;i<array.objectList->size();i++){
318      theStream << "Detection #" << array.objectList->at(i).getID()<<std::endl;
319      Detection *obj = new Detection;
320      *obj = array.objectList->at(i);
321      obj->addOffsets();
322      theStream<<*obj;
323      delete obj;
324    }
325    theStream<<"--------------\n";
326    return theStream;
327  }
328
329  /****************************************************************/
330  /////////////////////////////////////////////////////////////
331  //// Functions for Cube class
332  /////////////////////////////////////////////////////////////
333
334  Cube::Cube(){
335    /**
336     * Basic Constructor for Cube class.
337     * numDim set to 3, but numPixels to 0 and all bool flags to false.
338     * No allocation done.
339     */
340    numPixels=0; numDim=3;
341    reconExists = false; reconAllocated = false; baselineAllocated = false;
342  }
343  //--------------------------------------------------------------------
344
345  Cube::Cube(long size){
346    /**
347     * Alternative Cube constructor, where size is given but not individual
348     *  dimensions. Arrays are allocated as appropriate (according to the
349     *  relevant flags in Param set), but the Cube::axisDim array is not.
350     */
351    this->reconAllocated = false;
352    this->baselineAllocated = false;
353    this->axisDimAllocated = false;
354    this->arrayAllocated = false;
355    this->numPixels = this->numDim = 0;
356    if(size<0)
357      duchampError("Cube(size)","Negative size -- could not define Cube");
358    else{
359      if(size>0){
360        this->array = new float[size];
361        this->arrayAllocated = true;
362        if(this->par.getFlagATrous()||this->par.getFlagSmooth()){
363          this->recon = new float[size];
364          this->reconAllocated = true;
365        }
366        if(this->par.getFlagBaseline()){
367          this->baseline = new float[size];
368          this->baselineAllocated = true;
369        }
370      }
371      this->numPixels = size;
372      this->axisDim = new long[3];
373      this->axisDimAllocated = true;
374      this->numDim = 3;
375      this->reconExists = false;
376    }
377  }
378  //--------------------------------------------------------------------
379
380  Cube::Cube(long *dimensions){
381    /**
382     * Alternative Cube constructor, where sizes of dimensions are given.
383     * Arrays are allocated as appropriate (according to the
384     *  relevant flags in Param set), as is the Cube::axisDim array.
385     */
386    int size   = dimensions[0] * dimensions[1] * dimensions[2];
387    int imsize = dimensions[0] * dimensions[1];
388    this->reconAllocated = false;
389    this->baselineAllocated = false;
390    this->axisDimAllocated = false;
391    this->arrayAllocated = false;
392    this->numPixels = this->numDim = 0;
393    if((size<0) || (imsize<0) )
394      duchampError("Cube(dimArray)","Negative size -- could not define Cube");
395    else{
396      this->numPixels = size;
397      if(size>0){
398        this->array      = new float[size];
399        this->arrayAllocated = false;
400        this->detectMap  = new short[imsize];
401        if(this->par.getFlagATrous()||this->par.getFlagSmooth()){
402          this->recon    = new float[size];
403          this->reconAllocated = true;
404        }
405        if(this->par.getFlagBaseline()){
406          this->baseline = new float[size];
407          this->baselineAllocated = true;
408        }
409      }
410      this->numDim  = 3;
411      this->axisDim = new long[3];
412      this->axisDimAllocated = true;
413      for(int i=0;i<3     ;i++) this->axisDim[i]   = dimensions[i];
414      for(int i=0;i<imsize;i++) this->detectMap[i] = 0;
415      this->reconExists = false;
416    }
417  }
418  //--------------------------------------------------------------------
419
420  Cube::~Cube()
421  {
422    /**
423     *  The destructor deletes the memory allocated for Cube::detectMap, and,
424     *  if these have been allocated, Cube::recon and Cube::baseline.
425     */
426    delete [] this->detectMap;
427    if(this->reconAllocated)    delete [] this->recon;
428    if(this->baselineAllocated) delete [] this->baseline;
429  }
430  //--------------------------------------------------------------------
431
432  void Cube::initialiseCube(long *dimensions, bool allocateArrays)
433  {
434    /**
435     *  This function will set the sizes of all arrays that will be used by Cube.
436     *  It will also define the values of the axis dimensions: this will be done
437     *   using the WCS in the FitsHeader class, so the WCS needs to be good and
438     *   have three axes. If this is not the case, the axes are assumed to be
439     *   ordered in the sense of lng,lat,spc.
440     *
441     *  \param dimensions An array of values giving the dimensions (sizes) for
442     *  all axes. 
443     *  \param allocateArrays A flag indicating whether to allocate the memory for the data arrays: the default is true. The dimension arrays will be allocated and filled.
444     */
445
446    int lng,lat,spc,size,imsize;
447 
448    int numAxes = this->head.getNumAxes();
449
450    if(this->head.isWCS() && (numAxes>=3) && (this->head.WCS().spec>=0)){
451      // if there is a WCS and there is at least 3 axes
452      lng = this->head.WCS().lng;
453      lat = this->head.WCS().lat;
454      spc = this->head.WCS().spec;
455    }
456    else{
457      // just take dimensions[] at face value
458      lng = 0;
459      lat = 1;
460      spc = 2;
461    }
462
463    size   = dimensions[lng];
464    if(numAxes>1) size *= dimensions[lat];
465    if(this->head.canUseThirdAxis() && numAxes>spc) size *= dimensions[spc];
466
467    imsize = dimensions[lng];
468    if(numAxes>1) imsize *= dimensions[lat];
469
470    this->reconAllocated = false;
471    this->baselineAllocated = false;
472
473    if(this->axisDimAllocated){
474      delete [] this->axisDim;
475      this->axisDimAllocated = false;
476    }
477
478    if(this->arrayAllocated){
479      delete [] this->array;
480      this->arrayAllocated = false;
481    }
482
483    if((size<0) || (imsize<0) )
484      duchampError("Cube::initialiseCube(dimArray)",
485                   "Negative size -- could not define Cube.\n");
486    else{
487      this->numPixels = size;
488      this->numDim  = 3;
489      this->axisDim = new long[this->numDim];
490      this->axisDimAllocated = true;
491      this->axisDim[0] = dimensions[lng];
492      if(numAxes>1) this->axisDim[1] = dimensions[lat];
493      else this->axisDim[1] = 1;
494      if(this->head.canUseThirdAxis() && numAxes>spc) this->axisDim[2] = dimensions[spc];
495      else this->axisDim[2] = 1;
496      this->reconExists = false;
497      if(size>0 && allocateArrays){
498        this->array      = new float[size];
499        this->arrayAllocated = true;
500        this->detectMap  = new short[imsize];
501        for(int i=0;i<imsize;i++) this->detectMap[i] = 0;
502        if(this->par.getFlagATrous() || this->par.getFlagSmooth()){
503          this->recon    = new float[size];
504          this->reconAllocated = true;
505        }
506        if(this->par.getFlagBaseline()){
507          this->baseline = new float[size];
508          this->baselineAllocated = true;
509        }
510      }
511    }
512  }
513  //--------------------------------------------------------------------
514
515  int Cube::getCube(){ 
516    /**
517     * A front-end to the Cube::getCube() function, that does
518     *  subsection checks.
519     * Assumes the Param is set up properly.
520     */
521    std::string fname = par.getImageFile();
522    if(par.getFlagSubsection()) fname+=par.getSubsection();
523    return getCube(fname);
524  }
525  //--------------------------------------------------------------------
526
527  void Cube::saveArray(float *input, long size){
528    if(size != this->numPixels){
529      std::stringstream errmsg;
530      errmsg << "Input array different size to existing array ("
531             << size << " cf. " << this->numPixels << "). Cannot save.\n";
532      duchampError("Cube::saveArray",errmsg.str());
533    }
534    else {
535      if(this->numPixels>0 && this->arrayAllocated) delete [] array;
536      this->numPixels = size;
537      this->array = new float[size];
538      this->arrayAllocated = true;
539      for(int i=0;i<size;i++) this->array[i] = input[i];
540    }
541  }
542  //--------------------------------------------------------------------
543
544  void Cube::saveArray(std::vector<float> &input){
545    /**
546     * Saves the array in input to the pixel array Cube::array.
547     * The size of the array given must be the same as the current number of
548     * pixels, else an error message is returned and nothing is done.
549     * \param input The array of values to be saved.
550     */
551    if(input.size() != this->numPixels){
552      std::stringstream errmsg;
553      errmsg << "Input array different size to existing array ("
554             << input.size() << " cf. " << this->numPixels << "). Cannot save.\n";
555      duchampError("Cube::saveArray",errmsg.str());
556    }
557    else {
558      if(this->numPixels>0 && this->arrayAllocated) delete [] this->array;
559      this->numPixels = input.size();
560      this->array = new float[input.size()];
561      this->arrayAllocated = true;
562      for(int i=0;i<input.size();i++) this->array[i] = input[i];
563    }
564  }
565  //--------------------------------------------------------------------
566
567  void Cube::saveRecon(float *input, long size){
568    /**
569     * Saves the array in input to the reconstructed array Cube::recon
570     * The size of the array given must be the same as the current number of
571     * pixels, else an error message is returned and nothing is done.
572     * If the recon array has already been allocated, it is deleted first, and
573     * then the space is allocated.
574     * Afterwards, the appropriate flags are set.
575     * \param input The array of values to be saved.
576     * \param size The size of input.
577     */
578    if(size != this->numPixels){
579      std::stringstream errmsg;
580      errmsg << "Input array different size to existing array ("
581             << size << " cf. " << this->numPixels << "). Cannot save.\n";
582      duchampError("Cube::saveRecon",errmsg.str());
583    }
584    else {
585      if(this->numPixels>0){
586        if(this->reconAllocated) delete [] this->recon;
587        this->numPixels = size;
588        this->recon = new float[size];
589        this->reconAllocated = true;
590        for(int i=0;i<size;i++) this->recon[i] = input[i];
591        this->reconExists = true;
592      }
593    }
594  }
595  //--------------------------------------------------------------------
596
597  void Cube::getRecon(float *output){
598    /**
599     * The reconstructed array is written to output. The output array needs to
600     *  be defined beforehand: no checking is done on the memory.
601     * \param output The array that is written to.
602     */
603    // Need check for change in number of pixels!
604    for(int i=0;i<this->numPixels;i++){
605      if(this->reconExists) output[i] = this->recon[i];
606      else output[i] = 0.;
607    }
608  }
609  //--------------------------------------------------------------------
610
611  void Cube::removeMW()
612  {
613    /**
614     * The channels corresponding to the Milky Way range (as given by the Param
615     *  set) are all set to 0 in the pixel array.
616     * Only done if the appropriate flag is set, and the pixels are not BLANK.
617     * \deprecated
618     */
619    if(this->par.getFlagMW()){
620      for(int pix=0;pix<this->axisDim[0]*this->axisDim[1];pix++){
621        for(int z=0;z<this->axisDim[2];z++){
622          int pos = z*this->axisDim[0]*this->axisDim[1] + pix;
623          if(!this->isBlank(pos) && this->par.isInMW(z)) this->array[pos]=0.;
624        }
625      }
626    }
627  }
628  //--------------------------------------------------------------------
629
630  void Cube::setCubeStats()
631  {
632    /** 
633     *   Calculates the full statistics for the cube:
634     *     mean, rms, median, madfm
635     *   Only do this if the threshold has not been defined (ie. is still 0.,
636     *    its default).
637     *   Also work out the threshold and store it in the par set.
638     *   
639     *   Different from Cube::setCubeStatsOld() as it doesn't use the
640     *    getStats functions but has own versions of them hardcoded to
641     *    ignore BLANKs and MW channels. This saves on memory usage -- necessary
642     *    for dealing with very big files.
643     *
644     *   Three cases exist:
645     *  <ul><li>Simple case, with no reconstruction/smoothing: all stats
646     *          calculated from the original array.
647     *      <li>Wavelet reconstruction: mean & median calculated from the
648     *          original array, and stddev & madfm from the residual.
649     *      <li>Smoothing: all four stats calculated from the recon array
650     *          (which holds the smoothed data).
651     *  </ul>
652     */
653
654    if(this->par.getFlagUserThreshold() ){
655      // if the user has defined a threshold, set this in the StatsContainer
656      this->Stats.setThreshold( this->par.getThreshold() );
657    }
658    else{
659      // only work out the stats if we need to.
660      // the only reason we don't is if the user has specified a threshold.
661   
662      this->Stats.setRobust(this->par.getFlagRobustStats());
663
664      if(this->par.isVerbose())
665        std::cout << "Calculating the cube statistics... " << std::flush;
666   
667      long xysize = this->axisDim[0]*this->axisDim[1];
668
669      bool *mask = new bool[this->numPixels];
670      int vox,goodSize = 0;
671      for(int x=0;x<this->axisDim[0];x++){
672        for(int y=0;y<this->axisDim[1];y++){
673          for(int z=0;z<this->axisDim[2];z++){
674            vox = z * xysize + y*this->axisDim[0] + x;
675            mask[vox] = (!this->isBlank(vox) &&
676                         !this->par.isInMW(z) &&
677                         this->par.isStatOK(x,y,z) );
678            if(mask[vox]) goodSize++;
679          }
680        }
681      }
682
683      float mean,median,stddev,madfm;
684      if( this->par.getFlagATrous() ){
685        // Case #2 -- wavelet reconstruction
686        // just get mean & median from orig array, and rms & madfm from
687        // residual recompute array values to be residuals & then find
688        // stddev & madfm
689        if(!this->reconExists)
690          duchampError("setCubeStats",
691                       "Reconstruction not yet done!\nCannot calculate stats!\n");
692        else{
693          float *tempArray = new float[goodSize];
694
695          goodSize=0;
696          for(int x=0;x<this->axisDim[0];x++){
697            for(int y=0;y<this->axisDim[1];y++){
698              for(int z=0;z<this->axisDim[2];z++){
699                vox = z * xysize + y*this->axisDim[0] + x;
700                if(mask[vox]) tempArray[goodSize++] = this->array[vox];
701              }
702            }
703          }
704
705          // First, find the mean of the original array. Store it.
706          mean = tempArray[0];
707          for(int i=1;i<goodSize;i++) mean += tempArray[i];
708          mean /= float(goodSize);
709          mean = findMean(tempArray,goodSize);
710          this->Stats.setMean(mean);
711       
712          // Now sort it and find the median. Store it.
713          std::sort(tempArray,tempArray+goodSize);
714          if((goodSize%2)==0)
715            median = (tempArray[goodSize/2-1] + tempArray[goodSize/2])/2;
716          else median = tempArray[goodSize/2];
717          this->Stats.setMedian(median);
718
719          // Now calculate the residuals and find the mean & median of
720          // them. We don't store these, but they are necessary to find
721          // the sttdev & madfm.
722          goodSize = 0;
723          for(int p=0;p<xysize;p++){
724            for(int z=0;z<this->axisDim[2];z++){
725              vox = z * xysize + p;
726              if(mask[vox])
727                tempArray[goodSize++] = this->array[vox] - this->recon[vox];
728            }
729          }
730          mean = tempArray[0];
731          for(int i=1;i<goodSize;i++) mean += tempArray[i];
732          mean /= float(goodSize);
733          std::sort(tempArray,tempArray+goodSize);
734          if((goodSize%2)==0)
735            median = (tempArray[goodSize/2-1] + tempArray[goodSize/2])/2;
736          else median = tempArray[goodSize/2];
737
738          // Now find the standard deviation of the residuals. Store it.
739          stddev = (tempArray[0]-mean) * (tempArray[0]-mean);
740          for(int i=1;i<goodSize;i++)
741            stddev += (tempArray[i]-mean)*(tempArray[i]-mean);
742          stddev = sqrt(stddev/float(goodSize-1));
743          this->Stats.setStddev(stddev);
744
745          // Now find the madfm of the residuals. Store it.
746          for(int i=0;i<goodSize;i++){
747            if(tempArray[i]>median) tempArray[i] = tempArray[i]-median;
748            else tempArray[i] = median - tempArray[i];
749          }
750          std::sort(tempArray,tempArray+goodSize);
751          if((goodSize%2)==0)
752            madfm = (tempArray[goodSize/2-1] + tempArray[goodSize/2])/2;
753          else madfm = tempArray[goodSize/2];
754          this->Stats.setMadfm(madfm);
755
756          delete [] tempArray;
757        }
758      }
759      else if(this->par.getFlagSmooth()) {
760        // Case #3 -- smoothing
761        // get all four stats from the recon array, which holds the
762        // smoothed data. This can just be done with the
763        // StatsContainer::calculate function, using the mask generated
764        // earlier.
765        if(!this->reconExists)
766          duchampError("setCubeStats","Smoothing not yet done!\nCannot calculate stats!\n");
767        else this->Stats.calculate(this->recon,this->numPixels,mask);
768      }
769      else{
770        // Case #1 -- default case, with no smoothing or reconstruction.
771        // get all four stats from the original array. This can just be
772        // done with the StatsContainer::calculate function, using the
773        // mask generated earlier.
774        this->Stats.calculate(this->array,this->numPixels,mask);
775      }
776
777      this->Stats.setUseFDR( this->par.getFlagFDR() );
778      // If the FDR method has been requested, define the P-value
779      // threshold
780      if(this->par.getFlagFDR())  this->setupFDR();
781      else{
782        // otherwise, calculate threshold based on the requested SNR cut
783        // level, and then set the threshold parameter in the Par set.
784        this->Stats.setThresholdSNR( this->par.getCut() );
785        this->par.setThreshold( this->Stats.getThreshold() );
786      }
787   
788      delete [] mask;
789
790    }
791
792    if(this->par.isVerbose()){
793      std::cout << "Using ";
794      if(this->par.getFlagFDR()) std::cout << "effective ";
795      std::cout << "flux threshold of: ";
796      float thresh = this->Stats.getThreshold();
797      if(this->par.getFlagNegative()) thresh *= -1.;
798      std::cout << thresh << std::endl;
799    }
800
801  }
802  //--------------------------------------------------------------------
803
804  void Cube::setupFDR()
805  {
806    /**
807     *  Call the setupFDR(float *) function on the pixel array of the
808     *  cube. This is the usual way of running it.
809     *
810     *  However, if we are in smoothing mode, we calculate the FDR
811     *  parameters using the recon array, which holds the smoothed
812     *  data. Gives an error message if the reconExists flag is not set.
813     *
814     */
815    if(this->par.getFlagSmooth())
816      if(this->reconExists) this->setupFDR(this->recon);
817      else{
818        duchampError("setupFDR",
819                     "Smoothing not done properly! Using original array for defining threshold.\n");
820        this->setupFDR(this->array);
821      }
822    else if( this->par.getFlagATrous() ){
823      this->setupFDR(this->recon);
824    }
825    else{
826      this->setupFDR(this->array);
827    }
828  }
829  //--------------------------------------------------------------------
830
831  void Cube::setupFDR(float *input)
832  {
833    /** 
834     *   Determines the critical Probability value for the False
835     *   Discovery Rate detection routine. All pixels in the given arry
836     *   with Prob less than this value will be considered detections.
837     *
838     *   Note that the Stats of the cube need to be calculated first.
839     *
840     *   The Prob here is the probability, assuming a Normal
841     *   distribution, of obtaining a value as high or higher than the
842     *   pixel value (ie. only the positive tail of the PDF).
843     *
844     *   The probabilities are calculated using the
845     *   StatsContainer::getPValue(), which calculates the z-statistic,
846     *   and then the probability via
847     *   \f$0.5\operatorname{erfc}(z/\sqrt{2})\f$ -- giving the positive
848     *   tail probability.
849     */
850
851    // first calculate p-value for each pixel -- assume Gaussian for now.
852
853    float *orderedP = new float[this->numPixels];
854    int count = 0;
855    for(int x=0;x<this->axisDim[0];x++){
856      for(int y=0;y<this->axisDim[1];y++){
857        for(int z=0;z<this->axisDim[2];z++){
858          int pix = z * this->axisDim[0]*this->axisDim[1] +
859            y*this->axisDim[0] + x;
860
861          if(!(this->par.isBlank(this->array[pix])) && !this->par.isInMW(z)){
862            // only look at non-blank, valid pixels
863            //            orderedP[count++] = this->Stats.getPValue(this->array[pix]);
864            orderedP[count++] = this->Stats.getPValue(input[pix]);
865          }
866        }
867      }
868    }
869
870    // now order them
871    std::stable_sort(orderedP,orderedP+count);
872 
873    // now find the maximum P value.
874    int max = 0;
875    float cN = 0.;
876    int numVox = int(ceil(this->par.getBeamSize()));
877    //  if(this->head.isSpecOK()) numVox *= 2;
878    if(this->head.canUseThirdAxis()) numVox *= 2;
879    // why beamSize*2? we are doing this in 3D, so spectrally assume just the
880    //  neighbouring channels are correlated, but spatially all those within
881    //  the beam, so total number of voxels is 2*beamSize
882    for(int psfCtr=1;psfCtr<=numVox;psfCtr++) cN += 1./float(psfCtr);
883
884    double slope = this->par.getAlpha()/cN;
885    for(int loopCtr=0;loopCtr<count;loopCtr++) {
886      if( orderedP[loopCtr] < (slope * double(loopCtr+1)/ double(count)) ){
887        max = loopCtr;
888      }
889    }
890
891    this->Stats.setPThreshold( orderedP[max] );
892
893
894    // Find real value of the P threshold by finding the inverse of the
895    //  error function -- root finding with brute force technique
896    //  (relatively slow, but we only do it once).
897    double zStat     = 0.;
898    double deltaZ    = 0.1;
899    double tolerance = 1.e-6;
900    double initial   = 0.5 * erfc(zStat/M_SQRT2) - this->Stats.getPThreshold();
901    do{
902      zStat+=deltaZ;
903      double current = 0.5 * erfc(zStat/M_SQRT2) - this->Stats.getPThreshold();
904      if((initial*current)<0.){
905        zStat-=deltaZ;
906        deltaZ/=2.;
907      }
908    }while(deltaZ>tolerance);
909    this->Stats.setThreshold( zStat*this->Stats.getSpread() +
910                              this->Stats.getMiddle() );
911
912    ///////////////////////////
913    //   if(TESTING){
914    //     std::stringstream ss;
915    //     float *xplot = new float[2*max];
916    //     for(int i=0;i<2*max;i++) xplot[i]=float(i)/float(count);
917    //     cpgopen("latestFDR.ps/vcps");
918    //     cpgpap(8.,1.);
919    //     cpgslw(3);
920    //     cpgenv(0,float(2*max)/float(count),0,orderedP[2*max],0,0);
921    //     cpglab("i/N (index)", "p-value","");
922    //     cpgpt(2*max,xplot,orderedP,DOT);
923
924    //     ss.str("");
925    //     ss << "\\gm = " << this->Stats.getMiddle();
926    //     cpgtext(max/(4.*count),0.9*orderedP[2*max],ss.str().c_str());
927    //     ss.str("");
928    //     ss << "\\gs = " << this->Stats.getSpread();
929    //     cpgtext(max/(4.*count),0.85*orderedP[2*max],ss.str().c_str());
930    //     ss.str("");
931    //     ss << "Slope = " << slope;
932    //     cpgtext(max/(4.*count),0.8*orderedP[2*max],ss.str().c_str());
933    //     ss.str("");
934    //     ss << "Alpha = " << this->par.getAlpha();
935    //     cpgtext(max/(4.*count),0.75*orderedP[2*max],ss.str().c_str());
936    //     ss.str("");
937    //     ss << "c\\dN\\u = " << cN;
938    //     cpgtext(max/(4.*count),0.7*orderedP[2*max],ss.str().c_str());
939    //     ss.str("");
940    //     ss << "max = "<<max << " (out of " << count << ")";
941    //     cpgtext(max/(4.*count),0.65*orderedP[2*max],ss.str().c_str());
942    //     ss.str("");
943    //     ss << "Threshold = "<<zStat*this->Stats.getSpread()+this->Stats.getMiddle();
944    //     cpgtext(max/(4.*count),0.6*orderedP[2*max],ss.str().c_str());
945 
946    //     cpgslw(1);
947    //     cpgsci(RED);
948    //     cpgmove(0,0);
949    //     cpgdraw(1,slope);
950    //     cpgsci(BLUE);
951    //     cpgsls(DOTTED);
952    //     cpgmove(0,orderedP[max]);
953    //     cpgdraw(2*max/float(count),orderedP[max]);
954    //     cpgmove(max/float(count),0);
955    //     cpgdraw(max/float(count),orderedP[2*max]);
956    //     cpgsci(GREEN);
957    //     cpgsls(SOLID);
958    //     for(int i=1;i<=10;i++) {
959    //       ss.str("");
960    //       ss << float(i)/2. << "\\gs";
961    //       float prob = 0.5*erfc((float(i)/2.)/M_SQRT2);
962    //       cpgtick(0, 0, 0, orderedP[2*max],
963    //        prob/orderedP[2*max],
964    //        0, 1, 1.5, 90., ss.str().c_str());
965    //     }
966    //     cpgend();
967    //     delete [] xplot;
968    //   }
969    delete [] orderedP;
970
971  }
972  //--------------------------------------------------------------------
973
974  bool Cube::isDetection(long x, long y, long z)
975  {
976    /**
977     * Is a given voxel at position (x,y,z) a detection, based on the statistics
978     *  in the Cube's StatsContainer?
979     * If the pixel lies outside the valid range for the data array,
980     * return false.
981     * \param x X-value of the Cube's voxel to be tested.
982     * \param y Y-value of the Cube's voxel to be tested.
983     * \param z Z-value of the Cube's voxel to be tested.
984     */
985    long voxel = z*axisDim[0]*axisDim[1] + y*axisDim[0] + x;
986    return DataArray::isDetection(array[voxel]);
987  }
988  //--------------------------------------------------------------------
989
990  void Cube::calcObjectFluxes()
991  {
992    /**
993     *  A function to calculate the fluxes and centroids for each
994     *  object in the Cube's list of detections. Uses
995     *  Detection::calcFluxes() for each object.
996     */
997    std::vector<Detection>::iterator obj;
998    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
999      obj->calcFluxes(this->array, this->axisDim);
1000      if(this->par.getFlagUserThreshold())
1001        obj->setPeakSNR( obj->getPeakFlux() / this->Stats.getThreshold() );
1002      else
1003        obj->setPeakSNR( (obj->getPeakFlux() - this->Stats.getMiddle()) / this->Stats.getSpread() );
1004    }
1005  }
1006  //--------------------------------------------------------------------
1007
1008  void Cube::calcObjectWCSparams()
1009  {
1010    /**
1011     *  A function that calculates the WCS parameters for each object in the
1012     *  Cube's list of detections.
1013     *  Each object gets an ID number assigned to it (which is simply its order
1014     *   in the list), and if the WCS is good, the WCS paramters are calculated.
1015     */
1016
1017    std::vector<Detection>::iterator obj;
1018    int ct=0;
1019    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
1020      obj->setID(ct++);
1021      obj->setCentreType(this->par.getPixelCentre());
1022      obj->calcFluxes(this->array,this->axisDim);
1023      //      obj->calcWCSparams(this->array,this->axisDim,this->head);
1024      obj->calcWCSparams(this->head);
1025      obj->calcIntegFlux(this->array,this->axisDim,this->head);
1026   
1027      if(this->par.getFlagUserThreshold())
1028        obj->setPeakSNR( obj->getPeakFlux() / this->Stats.getThreshold() );
1029      else
1030        obj->setPeakSNR( (obj->getPeakFlux() - this->Stats.getMiddle()) / this->Stats.getSpread() );
1031
1032    } 
1033
1034    if(!this->head.isWCS()){
1035      // if the WCS is bad, set the object names to Obj01 etc
1036      int numspaces = int(log10(this->objectList->size())) + 1;
1037      std::stringstream ss;
1038      for(int i=0;i<this->objectList->size();i++){
1039        ss.str("");
1040        ss << "Obj" << std::setfill('0') << std::setw(numspaces) << i+1;
1041        obj->setName(ss.str());
1042      }
1043    }
1044 
1045  }
1046  //--------------------------------------------------------------------
1047
1048  void Cube::calcObjectWCSparams(std::vector< std::vector<PixelInfo::Voxel> > bigVoxList)
1049  {
1050    /**
1051     *  A function that calculates the WCS parameters for each object in the
1052     *  Cube's list of detections.
1053     *  Each object gets an ID number assigned to it (which is simply its order
1054     *   in the list), and if the WCS is good, the WCS paramters are calculated.
1055     *
1056     *  This version uses vectors of Voxels to define the fluxes.
1057     *
1058     * \param bigVoxList A vector of vectors of Voxels, with the same
1059     * number of elements as this->objectList, where each element is a
1060     * vector of Voxels corresponding to the same voxels in each
1061     * detection and indicating the flux of each voxel.
1062     */
1063 
1064    std::vector<Detection>::iterator obj;
1065    int ct=0;
1066    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
1067      obj->setID(ct+1);
1068      obj->setCentreType(this->par.getPixelCentre());
1069      obj->calcFluxes(bigVoxList[ct]);
1070      obj->calcWCSparams(this->head);
1071      obj->calcIntegFlux(bigVoxList[ct],this->head);
1072   
1073      if(this->par.getFlagUserThreshold())
1074        obj->setPeakSNR( obj->getPeakFlux() / this->Stats.getThreshold() );
1075      else
1076        obj->setPeakSNR( (obj->getPeakFlux() - this->Stats.getMiddle()) / this->Stats.getSpread() );
1077
1078      ct++;
1079    } 
1080
1081    if(!this->head.isWCS()){
1082      // if the WCS is bad, set the object names to Obj01 etc
1083      int numspaces = int(log10(this->objectList->size())) + 1;
1084      std::stringstream ss;
1085      for(int i=0;i<this->objectList->size();i++){
1086        ss.str("");
1087        ss << "Obj" << std::setfill('0') << std::setw(numspaces) << i+1;
1088        obj->setName(ss.str());
1089      }
1090    }
1091 
1092  }
1093  //--------------------------------------------------------------------
1094
1095  void Cube::updateDetectMap()
1096  {
1097    /**
1098     *  A function that, for each detected object in the cube's list, increments
1099     *   the cube's detection map by the required amount at each pixel.
1100     */
1101
1102    Scan temp;
1103    for(int obj=0;obj<this->objectList->size();obj++){
1104      long numZ=this->objectList->at(obj).pixels().getNumChanMap();
1105      for(int iz=0;iz<numZ;iz++){ // for each channel map
1106        Object2D *chanmap = new Object2D;
1107        *chanmap = this->objectList->at(obj).pixels().getChanMap(iz).getObject();
1108        for(int iscan=0;iscan<chanmap->getNumScan();iscan++){
1109          temp = chanmap->getScan(iscan);
1110          for(int x=temp.getX(); x <= temp.getXmax(); x++)
1111            this->detectMap[temp.getY()*this->axisDim[0] + x]++;
1112        } // end of loop over scans
1113        delete chanmap;
1114      } // end of loop over channel maps
1115    } // end of loop over objects.
1116
1117  }
1118  //--------------------------------------------------------------------
1119
1120  void Cube::updateDetectMap(Detection obj)
1121  {
1122    /**
1123     *  A function that, for the given object, increments the cube's
1124     *  detection map by the required amount at each pixel.
1125     *
1126     *  \param obj A Detection object that is being incorporated into the map.
1127     */
1128
1129    Scan temp;
1130    long numZ=obj.pixels().getNumChanMap();
1131    for(int iz=0;iz<numZ;iz++){ // for each channel map
1132      Object2D chanmap = obj.pixels().getChanMap(iz).getObject();
1133      for(int iscan=0;iscan<chanmap.getNumScan();iscan++){
1134        temp = chanmap.getScan(iscan);
1135        for(int x=temp.getX(); x <= temp.getXmax(); x++)
1136          this->detectMap[temp.getY()*this->axisDim[0] + x]++;
1137      } // end of loop over scans
1138    } // end of loop over channel maps
1139
1140  }
1141  //--------------------------------------------------------------------
1142
1143  float Cube::enclosedFlux(Detection obj)
1144  {
1145    /**
1146     *   A function to calculate the flux enclosed by the range
1147     *    of pixels detected in the object obj (not necessarily all
1148     *    pixels will have been detected).
1149     *
1150     *   \param obj The Detection under consideration.
1151     */
1152    obj.calcFluxes(this->array, this->axisDim);
1153    int xsize = obj.getXmax()-obj.getXmin()+1;
1154    int ysize = obj.getYmax()-obj.getYmin()+1;
1155    int zsize = obj.getZmax()-obj.getZmin()+1;
1156    std::vector <float> fluxArray(xsize*ysize*zsize,0.);
1157    for(int x=0;x<xsize;x++){
1158      for(int y=0;y<ysize;y++){
1159        for(int z=0;z<zsize;z++){
1160          fluxArray[x+y*xsize+z*ysize*xsize] =
1161            this->getPixValue(x+obj.getXmin(),
1162                              y+obj.getYmin(),
1163                              z+obj.getZmin());
1164          if(this->par.getFlagNegative())
1165            fluxArray[x+y*xsize+z*ysize*xsize] *= -1.;
1166        }
1167      }
1168    }
1169    float sum = 0.;
1170    for(int i=0;i<fluxArray.size();i++)
1171      if(!this->par.isBlank(fluxArray[i])) sum+=fluxArray[i];
1172    return sum;
1173  }
1174  //--------------------------------------------------------------------
1175
1176  void Cube::setupColumns()
1177  {
1178    /**
1179     *   A front-end to the two setup routines in columns.cc. 
1180     *
1181     *   This first gets the starting precisions, which may be from
1182     *   the input parameters. It then sets up the columns (calculates
1183     *   their widths and precisions and so on based on the values
1184     *   within). The precisions are also stored in each Detection
1185     *   object.
1186     *
1187     *   Need to have called calcObjectWCSparams() somewhere
1188     *   beforehand.
1189     */
1190
1191    std::vector<Detection>::iterator obj;
1192    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
1193      obj->setVelPrec( this->par.getPrecVel() );
1194      obj->setFpeakPrec( this->par.getPrecFlux() );
1195      obj->setXYZPrec( Column::prXYZ );
1196      obj->setPosPrec( Column::prWPOS );
1197      obj->setFintPrec( this->par.getPrecFlux() );
1198      obj->setSNRPrec( this->par.getPrecSNR() );
1199    }
1200 
1201    this->fullCols.clear();
1202    this->fullCols = getFullColSet(*(this->objectList), this->head);
1203
1204    this->logCols.clear();
1205    this->logCols = getLogColSet(*(this->objectList), this->head);
1206
1207    int vel,fpeak,fint,pos,xyz,snr;
1208    vel = fullCols[VEL].getPrecision();
1209    fpeak = fullCols[FPEAK].getPrecision();
1210    snr = fullCols[SNRPEAK].getPrecision();
1211    xyz = fullCols[X].getPrecision();
1212    xyz = std::max(xyz, fullCols[Y].getPrecision());
1213    xyz = std::max(xyz, fullCols[Z].getPrecision());
1214    if(this->head.isWCS()) fint = fullCols[FINT].getPrecision();
1215    else fint = fullCols[FTOT].getPrecision();
1216    pos = fullCols[WRA].getPrecision();
1217    pos = std::max(pos, fullCols[WDEC].getPrecision());
1218 
1219    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
1220      obj->setVelPrec(vel);
1221      obj->setFpeakPrec(fpeak);
1222      obj->setXYZPrec(xyz);
1223      obj->setPosPrec(pos);
1224      obj->setFintPrec(fint);
1225      obj->setSNRPrec(snr);
1226    }
1227
1228  }
1229  //--------------------------------------------------------------------
1230
1231  bool Cube::objAtSpatialEdge(Detection obj)
1232  {
1233    /**
1234     *   A function to test whether the object obj
1235     *    lies at the edge of the cube's spatial field --
1236     *    either at the boundary, or next to BLANKs.
1237     *
1238     *   \param obj The Detection under consideration.
1239     */
1240
1241    bool atEdge = false;
1242
1243    int pix = 0;
1244    std::vector<Voxel> voxlist = obj.pixels().getPixelSet();
1245    while(!atEdge && pix<voxlist.size()){
1246      // loop over each pixel in the object, until we find an edge pixel.
1247      for(int dx=-1;dx<=1;dx+=2){
1248        if( ((voxlist[pix].getX()+dx)<0) ||
1249            ((voxlist[pix].getX()+dx)>=this->axisDim[0]) )
1250          atEdge = true;
1251        else if(this->isBlank(voxlist[pix].getX()+dx,
1252                              voxlist[pix].getY(),
1253                              voxlist[pix].getZ()))
1254          atEdge = true;
1255      }
1256      for(int dy=-1;dy<=1;dy+=2){
1257        if( ((voxlist[pix].getY()+dy)<0) ||
1258            ((voxlist[pix].getY()+dy)>=this->axisDim[1]) )
1259          atEdge = true;
1260        else if(this->isBlank(voxlist[pix].getX(),
1261                              voxlist[pix].getY()+dy,
1262                              voxlist[pix].getZ()))
1263          atEdge = true;
1264      }
1265      pix++;
1266    }
1267
1268    return atEdge;
1269  }
1270  //--------------------------------------------------------------------
1271
1272  bool Cube::objAtSpectralEdge(Detection obj)
1273  {
1274    /** 
1275     *   A function to test whether the object obj
1276     *    lies at the edge of the cube's spectral extent --
1277     *    either at the boundary, or next to BLANKs.
1278     *
1279     *   /param obj The Detection under consideration.
1280     */
1281
1282    bool atEdge = false;
1283
1284    int pix = 0;
1285    std::vector<Voxel> voxlist = obj.pixels().getPixelSet();
1286    while(!atEdge && pix<voxlist.size()){
1287      // loop over each pixel in the object, until we find an edge pixel.
1288      for(int dz=-1;dz<=1;dz+=2){
1289        if( ((voxlist[pix].getZ()+dz)<0) ||
1290            ((voxlist[pix].getZ()+dz)>=this->axisDim[2]))
1291          atEdge = true;
1292        else if(this->isBlank(voxlist[pix].getX(),
1293                              voxlist[pix].getY(),
1294                              voxlist[pix].getZ()+dz))
1295          atEdge = true;
1296      }
1297      pix++;
1298    }
1299
1300    return atEdge;
1301  }
1302  //--------------------------------------------------------------------
1303
1304  void Cube::setObjectFlags()
1305  {
1306    /**   
1307     *   A function to set any warning flags for all the detected objects
1308     *    associated with the cube.
1309     *   Flags to be looked for:
1310     *    <ul><li> Negative enclosed flux (N)
1311     *        <li> Detection at edge of field (spatially) (E)
1312     *        <li> Detection at edge of spectral region (S)
1313     *    </ul>
1314     */
1315
1316    std::vector<Detection>::iterator obj;
1317    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
1318
1319      if( this->enclosedFlux(*obj) < 0. ) 
1320        obj->addToFlagText("N");
1321
1322      if( this->objAtSpatialEdge(*obj) )
1323        obj->addToFlagText("E");
1324
1325      if( this->objAtSpectralEdge(*obj) && (this->axisDim[2] > 2))
1326        obj->addToFlagText("S");
1327
1328    }
1329
1330  }
1331  //--------------------------------------------------------------------
1332
1333
1334
1335  /****************************************************************/
1336  /////////////////////////////////////////////////////////////
1337  //// Functions for Image class
1338  /////////////////////////////////////////////////////////////
1339
1340  Image::Image(long size){
1341    // need error handling in case size<0 !!!
1342    this->numPixels = this->numDim = 0;
1343    if(size<0)
1344      duchampError("Image(size)","Negative size -- could not define Image");
1345    else{
1346      if(size>0 && !this->arrayAllocated){
1347        this->array = new float[size];
1348        this->arrayAllocated = true;
1349      }
1350      this->numPixels = size;
1351      this->axisDim = new long[2];
1352      this->axisDimAllocated = true;
1353      this->numDim = 2;
1354    }
1355  }
1356  //--------------------------------------------------------------------
1357
1358  Image::Image(long *dimensions){
1359    this->numPixels = this->numDim = 0;
1360    int size = dimensions[0] * dimensions[1];
1361    if(size<0)
1362      duchampError("Image(dimArray)","Negative size -- could not define Image");
1363    else{
1364      this->numPixels = size;
1365      if(size>0){
1366        this->array = new float[size];
1367        this->arrayAllocated = true;
1368      }
1369      this->numDim=2;
1370      this->axisDim = new long[2];
1371      this->axisDimAllocated = true;
1372      for(int i=0;i<2;i++) this->axisDim[i] = dimensions[i];
1373    }
1374  }
1375  //--------------------------------------------------------------------
1376  //--------------------------------------------------------------------
1377
1378  void Image::saveArray(float *input, long size)
1379  {
1380    /**
1381     * Saves the array in input to the pixel array Image::array.
1382     * The size of the array given must be the same as the current number of
1383     * pixels, else an error message is returned and nothing is done.
1384     * \param input The array of values to be saved.
1385     * \param size The size of input.
1386     */
1387    if(size != this->numPixels)
1388      duchampError("Image::saveArray",
1389                   "Input array different size to existing array. Cannot save.");
1390    else {
1391      if(this->numPixels>0 && this->arrayAllocated) delete [] array;
1392      this->numPixels = size;
1393      if(this->numPixels>0){
1394        this->array = new float[size];
1395        this->arrayAllocated = true;
1396        for(int i=0;i<size;i++) this->array[i] = input[i];
1397      }
1398    }
1399  }
1400  //--------------------------------------------------------------------
1401
1402  void Image::extractSpectrum(float *Array, long *dim, long pixel)
1403  {
1404    /**
1405     *  A function to extract a 1-D spectrum from a 3-D array.
1406     *  The array is assumed to be 3-D with the third dimension the spectral one.
1407     *  The spectrum extracted is the one lying in the spatial pixel referenced
1408     *    by the third argument.
1409     *  The extracted spectrum is stored in the pixel array Image::array.
1410     * \param Array The array containing the pixel values, from which
1411     *               the spectrum is extracted.
1412     * \param dim The array of dimension values.
1413     * \param pixel The spatial pixel that contains the desired spectrum.
1414     */
1415    if((pixel<0)||(pixel>=dim[0]*dim[1]))
1416      duchampError("Image::extractSpectrum",
1417                   "Requested spatial pixel outside allowed range. Cannot save.");
1418    else if(dim[2] != this->numPixels)
1419      duchampError("Image::extractSpectrum",
1420                   "Input array different size to existing array. Cannot save.");
1421    else {
1422      if(this->numPixels>0 && this->arrayAllocated) delete [] array;
1423      this->numPixels = dim[2];
1424      if(this->numPixels>0){
1425        this->array = new float[dim[2]];
1426        this->arrayAllocated = true;
1427        for(int z=0;z<dim[2];z++) this->array[z] = Array[z*dim[0]*dim[1] + pixel];
1428      }
1429    }
1430  }
1431  //--------------------------------------------------------------------
1432
1433  void Image::extractSpectrum(Cube &cube, long pixel)
1434  {
1435    /**
1436     *  A function to extract a 1-D spectrum from a Cube class
1437     *  The spectrum extracted is the one lying in the spatial pixel referenced
1438     *    by the second argument.
1439     *  The extracted spectrum is stored in the pixel array Image::array.
1440     * \param cube The Cube containing the pixel values, from which the spectrum is extracted.
1441     * \param pixel The spatial pixel that contains the desired spectrum.
1442     */
1443    long zdim = cube.getDimZ();
1444    long spatSize = cube.getDimX()*cube.getDimY();
1445    if((pixel<0)||(pixel>=spatSize))
1446      duchampError("Image::extractSpectrum",
1447                   "Requested spatial pixel outside allowed range. Cannot save.");
1448    else if(zdim != this->numPixels)
1449      duchampError("Image::extractSpectrum",
1450                   "Input array different size to existing array. Cannot save.");
1451    else {
1452      if(this->numPixels>0 && this->arrayAllocated) delete [] array;
1453      this->numPixels = zdim;
1454      if(this->numPixels>0){
1455        this->array = new float[zdim];
1456        this->arrayAllocated = true;
1457        for(int z=0;z<zdim;z++)
1458          this->array[z] = cube.getPixValue(z*spatSize + pixel);
1459      }
1460    }
1461  }
1462  //--------------------------------------------------------------------
1463
1464  void Image::extractImage(float *Array, long *dim, long channel)
1465  {
1466    /**
1467     *  A function to extract a 2-D image from a 3-D array.
1468     *  The array is assumed to be 3-D with the third dimension the spectral one.
1469     *  The dimensions of the array are in the dim[] array.
1470     *  The image extracted is the one lying in the channel referenced
1471     *    by the third argument.
1472     *  The extracted image is stored in the pixel array Image::array.
1473     * \param Array The array containing the pixel values, from which the image is extracted.
1474     * \param dim The array of dimension values.
1475     * \param channel The spectral channel that contains the desired image.
1476     */
1477
1478    long spatSize = dim[0]*dim[1];
1479    if((channel<0)||(channel>=dim[2]))
1480      duchampError("Image::extractImage",
1481                   "Requested channel outside allowed range. Cannot save.");
1482    else if(spatSize != this->numPixels)
1483      duchampError("Image::extractImage",
1484                   "Input array different size to existing array. Cannot save.");
1485    else {
1486      if(this->numPixels>0 && this->arrayAllocated) delete [] array;
1487      this->numPixels = spatSize;
1488      if(this->numPixels>0){
1489        this->array = new float[spatSize];
1490        this->arrayAllocated = true;
1491        for(int npix=0; npix<spatSize; npix++)
1492          this->array[npix] = Array[channel*spatSize + npix];
1493      }
1494    }
1495  }
1496  //--------------------------------------------------------------------
1497
1498  void Image::extractImage(Cube &cube, long channel)
1499  {
1500    /**
1501     *  A function to extract a 2-D image from Cube class.
1502     *  The image extracted is the one lying in the channel referenced
1503     *    by the second argument.
1504     *  The extracted image is stored in the pixel array Image::array.
1505     * \param cube The Cube containing the pixel values, from which the image is extracted.
1506     * \param channel The spectral channel that contains the desired image.
1507     */
1508    long spatSize = cube.getDimX()*cube.getDimY();
1509    if((channel<0)||(channel>=cube.getDimZ()))
1510      duchampError("Image::extractImage",
1511                   "Requested channel outside allowed range. Cannot save.");
1512    else if(spatSize != this->numPixels)
1513      duchampError("Image::extractImage",
1514                   "Input array different size to existing array. Cannot save.");
1515    else {
1516      if(this->numPixels>0 && this->arrayAllocated) delete [] array;
1517      this->numPixels = spatSize;
1518      if(this->numPixels>0){
1519        this->array = new float[spatSize];
1520        this->arrayAllocated = true;
1521        for(int npix=0; npix<spatSize; npix++)
1522          this->array[npix] = cube.getPixValue(channel*spatSize + npix);
1523      }
1524    }
1525  }
1526  //--------------------------------------------------------------------
1527
1528  void Image::removeMW()
1529  {
1530    /**
1531     *  A function to remove the Milky Way range of channels from a 1-D spectrum.
1532     *  The array in this Image is assumed to be 1-D, with only the first axisDim
1533     *    equal to 1.
1534     *  The values of the MW channels are set to 0, unless they are BLANK.
1535     */
1536    if(this->par.getFlagMW() && (this->axisDim[1]==1) ){
1537      for(int z=0;z<this->axisDim[0];z++){
1538        if(!this->isBlank(z) && this->par.isInMW(z)) this->array[z]=0.;
1539      }
1540    }
1541  }
1542
1543}
Note: See TracBrowser for help on using the repository browser.