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

Last change on this file since 463 was 461, checked in by MatthewWhiting, 16 years ago

A few fixes:

  • Fixed a bug in setupColumns and the VOTable output when there are no detections
  • Fixed some bugs from the tidy up in the last commit
  • Fixed conflicts between a manual threshold and growth thresholds. Introduced a manual growth threshold that must be used when a manual threshold is used.
  • Also, a manual threshold turns off the FDR flag.
  • Improved the growth threshold reporting in the results header.
File size: 51.8 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    theStream<<array.objectList->size()<<" detections:\n--------------\n";
309    for(int i=0;i<array.objectList->size();i++){
310      theStream << "Detection #" << array.objectList->at(i).getID()<<std::endl;
311      Detection *obj = new Detection;
312      *obj = array.objectList->at(i);
313      obj->addOffsets();
314      theStream<<*obj;
315      delete obj;
316    }
317    theStream<<"--------------\n";
318    return theStream;
319  }
320
321  /****************************************************************/
322  /////////////////////////////////////////////////////////////
323  //// Functions for Cube class
324  /////////////////////////////////////////////////////////////
325
326  Cube::Cube(){
327    /**
328     * Basic Constructor for Cube class.
329     * numDim set to 3, but numPixels to 0 and all bool flags to false.
330     * No allocation done.
331     */
332    numPixels=0; numDim=3;
333    reconExists = false; reconAllocated = false; baselineAllocated = false;
334  }
335  //--------------------------------------------------------------------
336
337  Cube::Cube(long size){
338    /**
339     * Alternative Cube constructor, where size is given but not individual
340     *  dimensions. Arrays are allocated as appropriate (according to the
341     *  relevant flags in Param set), but the Cube::axisDim array is not.
342     */
343    this->reconAllocated = false;
344    this->baselineAllocated = false;
345    this->axisDimAllocated = false;
346    this->arrayAllocated = false;
347    this->numPixels = this->numDim = 0;
348    if(size<0)
349      duchampError("Cube(size)","Negative size -- could not define Cube");
350    else{
351      if(size>0){
352        this->array = new float[size];
353        this->arrayAllocated = true;
354        if(this->par.getFlagATrous()||this->par.getFlagSmooth()){
355          this->recon = new float[size];
356          this->reconAllocated = true;
357        }
358        if(this->par.getFlagBaseline()){
359          this->baseline = new float[size];
360          this->baselineAllocated = true;
361        }
362      }
363      this->numPixels = size;
364      this->axisDim = new long[3];
365      this->axisDimAllocated = true;
366      this->numDim = 3;
367      this->reconExists = false;
368    }
369  }
370  //--------------------------------------------------------------------
371
372  Cube::Cube(long *dimensions){
373    /**
374     * Alternative Cube constructor, where sizes of dimensions are given.
375     * Arrays are allocated as appropriate (according to the
376     *  relevant flags in Param set), as is the Cube::axisDim array.
377     */
378    int size   = dimensions[0] * dimensions[1] * dimensions[2];
379    int imsize = dimensions[0] * dimensions[1];
380    this->reconAllocated = false;
381    this->baselineAllocated = false;
382    this->axisDimAllocated = false;
383    this->arrayAllocated = false;
384    this->numPixels = this->numDim = 0;
385    if((size<0) || (imsize<0) )
386      duchampError("Cube(dimArray)","Negative size -- could not define Cube");
387    else{
388      this->numPixels = size;
389      if(size>0){
390        this->array      = new float[size];
391        this->arrayAllocated = false;
392        this->detectMap  = new short[imsize];
393        if(this->par.getFlagATrous()||this->par.getFlagSmooth()){
394          this->recon    = new float[size];
395          this->reconAllocated = true;
396        }
397        if(this->par.getFlagBaseline()){
398          this->baseline = new float[size];
399          this->baselineAllocated = true;
400        }
401      }
402      this->numDim  = 3;
403      this->axisDim = new long[3];
404      this->axisDimAllocated = true;
405      for(int i=0;i<3     ;i++) this->axisDim[i]   = dimensions[i];
406      for(int i=0;i<imsize;i++) this->detectMap[i] = 0;
407      this->reconExists = false;
408    }
409  }
410  //--------------------------------------------------------------------
411
412  Cube::~Cube()
413  {
414    /**
415     *  The destructor deletes the memory allocated for Cube::detectMap, and,
416     *  if these have been allocated, Cube::recon and Cube::baseline.
417     */
418    delete [] this->detectMap;
419    if(this->reconAllocated)    delete [] this->recon;
420    if(this->baselineAllocated) delete [] this->baseline;
421  }
422  //--------------------------------------------------------------------
423
424  void Cube::initialiseCube(long *dimensions)
425  {
426    /**
427     *  This function will set the sizes of all arrays that will be used by Cube.
428     *  It will also define the values of the axis dimensions: this will be done
429     *   using the WCS in the FitsHeader class, so the WCS needs to be good and
430     *   have three axes. If this is not the case, the axes are assumed to be
431     *   ordered in the sense of lng,lat,spc.
432     *
433     *  \param dimensions An array of values giving the dimensions (sizes) for
434     *  all axes. 
435     */
436
437    int lng,lat,spc,size,imsize;
438 
439    if(this->head.isWCS() && (this->head.getNumAxes()>=3)){
440      // if there is a WCS and there is at least 3 axes
441      lng = this->head.WCS().lng;
442      lat = this->head.WCS().lat;
443      spc = this->head.WCS().spec;
444    }
445    else{
446      // just take dimensions[] at face value
447      lng = 0;
448      lat = 1;
449      spc = 2;
450    }
451
452    size   = dimensions[lng];
453    if(this->head.getNumAxes()>1) size *= dimensions[lat];
454    //   if(this->head.isSpecOK()) size *= dimensions[spc];
455    if(this->head.canUseThirdAxis()) size *= dimensions[spc];
456    imsize = dimensions[lng];
457    if(this->head.getNumAxes()>1) imsize *= dimensions[lat];
458
459    this->reconAllocated = false;
460    this->baselineAllocated = false;
461
462    if(this->axisDimAllocated){
463      delete [] this->axisDim;
464      this->axisDimAllocated = false;
465    }
466
467    if(this->arrayAllocated){
468      delete [] this->array;
469      this->arrayAllocated = false;
470    }
471
472    if((size<0) || (imsize<0) )
473      duchampError("Cube::initialiseCube(dimArray)",
474                   "Negative size -- could not define Cube.\n");
475    else{
476      this->numPixels = size;
477      if(size>0){
478        this->array      = new float[size];
479        this->arrayAllocated = true;
480        this->detectMap  = new short[imsize];
481        if(this->par.getFlagATrous() || this->par.getFlagSmooth()){
482          this->recon    = new float[size];
483          this->reconAllocated = true;
484        }
485        if(this->par.getFlagBaseline()){
486          this->baseline = new float[size];
487          this->baselineAllocated = true;
488        }
489      }
490      this->numDim  = 3;
491      this->axisDim = new long[this->numDim];
492      this->axisDimAllocated = true;
493      this->axisDim[0] = dimensions[lng];
494      if(this->head.getNumAxes()>1) this->axisDim[1] = dimensions[lat];
495      else this->axisDim[1] = 1;
496      //     if(this->head.isSpecOK()) this->axisDim[2] = dimensions[spc];
497      if(this->head.canUseThirdAxis()) this->axisDim[2] = dimensions[spc];
498      else this->axisDim[2] = 1;
499      for(int i=0;i<imsize;i++) this->detectMap[i] = 0;
500      this->reconExists = false;
501    }
502  }
503  //--------------------------------------------------------------------
504
505  int Cube::getCube(){ 
506    /**
507     * A front-end to the Cube::getCube() function, that does
508     *  subsection checks.
509     * Assumes the Param is set up properly.
510     */
511    std::string fname = par.getImageFile();
512    if(par.getFlagSubsection()) fname+=par.getSubsection();
513    return getCube(fname);
514  }
515  //--------------------------------------------------------------------
516
517  void Cube::saveArray(float *input, long size){
518    if(size != this->numPixels){
519      std::stringstream errmsg;
520      errmsg << "Input array different size to existing array ("
521             << size << " cf. " << this->numPixels << "). Cannot save.\n";
522      duchampError("Cube::saveArray",errmsg.str());
523    }
524    else {
525      if(this->numPixels>0 && this->arrayAllocated) delete [] array;
526      this->numPixels = size;
527      this->array = new float[size];
528      this->arrayAllocated = true;
529      for(int i=0;i<size;i++) this->array[i] = input[i];
530    }
531  }
532  //--------------------------------------------------------------------
533
534  void Cube::saveRecon(float *input, long size){
535    /**
536     * Saves the array in input to the reconstructed array Cube::recon
537     * The size of the array given must be the same as the current number of
538     * pixels, else an error message is returned and nothing is done.
539     * If the recon array has already been allocated, it is deleted first, and
540     * then the space is allocated.
541     * Afterwards, the appropriate flags are set.
542     * \param input The array of values to be saved.
543     * \param size The size of input.
544     */
545    if(size != this->numPixels){
546      std::stringstream errmsg;
547      errmsg << "Input array different size to existing array ("
548             << size << " cf. " << this->numPixels << "). Cannot save.\n";
549      duchampError("Cube::saveRecon",errmsg.str());
550    }
551    else {
552      if(this->numPixels>0){
553        if(this->reconAllocated) delete [] this->recon;
554        this->numPixels = size;
555        this->recon = new float[size];
556        this->reconAllocated = true;
557        for(int i=0;i<size;i++) this->recon[i] = input[i];
558        this->reconExists = true;
559      }
560    }
561  }
562  //--------------------------------------------------------------------
563
564  void Cube::getRecon(float *output){
565    /**
566     * The reconstructed array is written to output. The output array needs to
567     *  be defined beforehand: no checking is done on the memory.
568     * \param output The array that is written to.
569     */
570    // Need check for change in number of pixels!
571    for(int i=0;i<this->numPixels;i++){
572      if(this->reconExists) output[i] = this->recon[i];
573      else output[i] = 0.;
574    }
575  }
576  //--------------------------------------------------------------------
577
578  void Cube::removeMW()
579  {
580    /**
581     * The channels corresponding to the Milky Way range (as given by the Param
582     *  set) are all set to 0 in the pixel array.
583     * Only done if the appropriate flag is set, and the pixels are not BLANK.
584     * \deprecated
585     */
586    if(this->par.getFlagMW()){
587      for(int pix=0;pix<this->axisDim[0]*this->axisDim[1];pix++){
588        for(int z=0;z<this->axisDim[2];z++){
589          int pos = z*this->axisDim[0]*this->axisDim[1] + pix;
590          if(!this->isBlank(pos) && this->par.isInMW(z)) this->array[pos]=0.;
591        }
592      }
593    }
594  }
595  //--------------------------------------------------------------------
596
597  void Cube::setCubeStats()
598  {
599    /** 
600     *   Calculates the full statistics for the cube:
601     *     mean, rms, median, madfm
602     *   Only do this if the threshold has not been defined (ie. is still 0.,
603     *    its default).
604     *   Also work out the threshold and store it in the par set.
605     *   
606     *   Different from Cube::setCubeStatsOld() as it doesn't use the
607     *    getStats functions but has own versions of them hardcoded to
608     *    ignore BLANKs and MW channels. This saves on memory usage -- necessary
609     *    for dealing with very big files.
610     *
611     *   Three cases exist:
612     *  <ul><li>Simple case, with no reconstruction/smoothing: all stats
613     *          calculated from the original array.
614     *      <li>Wavelet reconstruction: mean & median calculated from the
615     *          original array, and stddev & madfm from the residual.
616     *      <li>Smoothing: all four stats calculated from the recon array
617     *          (which holds the smoothed data).
618     *  </ul>
619     */
620
621    if(this->par.getFlagUserThreshold() ){
622      // if the user has defined a threshold, set this in the StatsContainer
623      this->Stats.setThreshold( this->par.getThreshold() );
624    }
625    else{
626      // only work out the stats if we need to.
627      // the only reason we don't is if the user has specified a threshold.
628   
629      this->Stats.setRobust(this->par.getFlagRobustStats());
630
631      if(this->par.isVerbose())
632        std::cout << "Calculating the cube statistics... " << std::flush;
633   
634      long xysize = this->axisDim[0]*this->axisDim[1];
635
636      bool *mask = new bool[this->numPixels];
637      int vox,goodSize = 0;
638      for(int x=0;x<this->axisDim[0];x++){
639        for(int y=0;y<this->axisDim[1];y++){
640          for(int z=0;z<this->axisDim[2];z++){
641            vox = z * xysize + y*this->axisDim[0] + x;
642            mask[vox] = (!this->isBlank(vox) &&
643                         !this->par.isInMW(z) &&
644                         this->par.isStatOK(x,y,z) );
645            if(mask[vox]) goodSize++;
646          }
647        }
648      }
649
650      float mean,median,stddev,madfm;
651      if( this->par.getFlagATrous() ){
652        // Case #2 -- wavelet reconstruction
653        // just get mean & median from orig array, and rms & madfm from
654        // residual recompute array values to be residuals & then find
655        // stddev & madfm
656        if(!this->reconExists)
657          duchampError("setCubeStats",
658                       "Reconstruction not yet done!\nCannot calculate stats!\n");
659        else{
660          float *tempArray = new float[goodSize];
661
662          goodSize=0;
663          for(int x=0;x<this->axisDim[0];x++){
664            for(int y=0;y<this->axisDim[1];y++){
665              for(int z=0;z<this->axisDim[2];z++){
666                vox = z * xysize + y*this->axisDim[0] + x;
667                if(mask[vox]) tempArray[goodSize++] = this->array[vox];
668              }
669            }
670          }
671
672          // First, find the mean of the original array. Store it.
673          mean = tempArray[0];
674          for(int i=1;i<goodSize;i++) mean += tempArray[i];
675          mean /= float(goodSize);
676          mean = findMean(tempArray,goodSize);
677          this->Stats.setMean(mean);
678       
679          // Now sort it and find the median. Store it.
680          std::sort(tempArray,tempArray+goodSize);
681          if((goodSize%2)==0)
682            median = (tempArray[goodSize/2-1] + tempArray[goodSize/2])/2;
683          else median = tempArray[goodSize/2];
684          this->Stats.setMedian(median);
685
686          // Now calculate the residuals and find the mean & median of
687          // them. We don't store these, but they are necessary to find
688          // the sttdev & madfm.
689          goodSize = 0;
690          for(int p=0;p<xysize;p++){
691            for(int z=0;z<this->axisDim[2];z++){
692              vox = z * xysize + p;
693              if(mask[vox])
694                tempArray[goodSize++] = this->array[vox] - this->recon[vox];
695            }
696          }
697          mean = tempArray[0];
698          for(int i=1;i<goodSize;i++) mean += tempArray[i];
699          mean /= float(goodSize);
700          std::sort(tempArray,tempArray+goodSize);
701          if((goodSize%2)==0)
702            median = (tempArray[goodSize/2-1] + tempArray[goodSize/2])/2;
703          else median = tempArray[goodSize/2];
704
705          // Now find the standard deviation of the residuals. Store it.
706          stddev = (tempArray[0]-mean) * (tempArray[0]-mean);
707          for(int i=1;i<goodSize;i++)
708            stddev += (tempArray[i]-mean)*(tempArray[i]-mean);
709          stddev = sqrt(stddev/float(goodSize-1));
710          this->Stats.setStddev(stddev);
711
712          // Now find the madfm of the residuals. Store it.
713          for(int i=0;i<goodSize;i++){
714            if(tempArray[i]>median) tempArray[i] = tempArray[i]-median;
715            else tempArray[i] = median - tempArray[i];
716          }
717          std::sort(tempArray,tempArray+goodSize);
718          if((goodSize%2)==0)
719            madfm = (tempArray[goodSize/2-1] + tempArray[goodSize/2])/2;
720          else madfm = tempArray[goodSize/2];
721          this->Stats.setMadfm(madfm);
722
723          delete [] tempArray;
724        }
725      }
726      else if(this->par.getFlagSmooth()) {
727        // Case #3 -- smoothing
728        // get all four stats from the recon array, which holds the
729        // smoothed data. This can just be done with the
730        // StatsContainer::calculate function, using the mask generated
731        // earlier.
732        if(!this->reconExists)
733          duchampError("setCubeStats","Smoothing not yet done!\nCannot calculate stats!\n");
734        else this->Stats.calculate(this->recon,this->numPixels,mask);
735      }
736      else{
737        // Case #1 -- default case, with no smoothing or reconstruction.
738        // get all four stats from the original array. This can just be
739        // done with the StatsContainer::calculate function, using the
740        // mask generated earlier.
741        this->Stats.calculate(this->array,this->numPixels,mask);
742      }
743
744      this->Stats.setUseFDR( this->par.getFlagFDR() );
745      // If the FDR method has been requested, define the P-value
746      // threshold
747      if(this->par.getFlagFDR())  this->setupFDR();
748      else{
749        // otherwise, calculate threshold based on the requested SNR cut
750        // level, and then set the threshold parameter in the Par set.
751        this->Stats.setThresholdSNR( this->par.getCut() );
752        this->par.setThreshold( this->Stats.getThreshold() );
753      }
754   
755      delete [] mask;
756
757    }
758
759    if(this->par.isVerbose()){
760      std::cout << "Using ";
761      if(this->par.getFlagFDR()) std::cout << "effective ";
762      std::cout << "flux threshold of: ";
763      float thresh = this->Stats.getThreshold();
764      if(this->par.getFlagNegative()) thresh *= -1.;
765      std::cout << thresh << std::endl;
766    }
767
768  }
769  //--------------------------------------------------------------------
770
771  void Cube::setupFDR()
772  {
773    /**
774     *  Call the setupFDR(float *) function on the pixel array of the
775     *  cube. This is the usual way of running it.
776     *
777     *  However, if we are in smoothing mode, we calculate the FDR
778     *  parameters using the recon array, which holds the smoothed
779     *  data. Gives an error message if the reconExists flag is not set.
780     *
781     */
782    if(this->par.getFlagSmooth())
783      if(this->reconExists) this->setupFDR(this->recon);
784      else{
785        duchampError("setupFDR",
786                     "Smoothing not done properly! Using original array for defining threshold.\n");
787        this->setupFDR(this->array);
788      }
789    else if( this->par.getFlagATrous() ){
790      this->setupFDR(this->recon);
791    }
792    else{
793      this->setupFDR(this->array);
794    }
795  }
796  //--------------------------------------------------------------------
797
798  void Cube::setupFDR(float *input)
799  {
800    /** 
801     *   Determines the critical Probability value for the False
802     *   Discovery Rate detection routine. All pixels in the given arry
803     *   with Prob less than this value will be considered detections.
804     *
805     *   Note that the Stats of the cube need to be calculated first.
806     *
807     *   The Prob here is the probability, assuming a Normal
808     *   distribution, of obtaining a value as high or higher than the
809     *   pixel value (ie. only the positive tail of the PDF).
810     *
811     *   The probabilities are calculated using the
812     *   StatsContainer::getPValue(), which calculates the z-statistic,
813     *   and then the probability via
814     *   \f$0.5\operatorname{erfc}(z/\sqrt{2})\f$ -- giving the positive
815     *   tail probability.
816     */
817
818    // first calculate p-value for each pixel -- assume Gaussian for now.
819
820    float *orderedP = new float[this->numPixels];
821    int count = 0;
822    for(int x=0;x<this->axisDim[0];x++){
823      for(int y=0;y<this->axisDim[1];y++){
824        for(int z=0;z<this->axisDim[2];z++){
825          int pix = z * this->axisDim[0]*this->axisDim[1] +
826            y*this->axisDim[0] + x;
827
828          if(!(this->par.isBlank(this->array[pix])) && !this->par.isInMW(z)){
829            // only look at non-blank, valid pixels
830            //            orderedP[count++] = this->Stats.getPValue(this->array[pix]);
831            orderedP[count++] = this->Stats.getPValue(input[pix]);
832          }
833        }
834      }
835    }
836
837    // now order them
838    std::stable_sort(orderedP,orderedP+count);
839 
840    // now find the maximum P value.
841    int max = 0;
842    float cN = 0.;
843    int numVox = int(ceil(this->par.getBeamSize()));
844    //  if(this->head.isSpecOK()) numVox *= 2;
845    if(this->head.canUseThirdAxis()) numVox *= 2;
846    // why beamSize*2? we are doing this in 3D, so spectrally assume just the
847    //  neighbouring channels are correlated, but spatially all those within
848    //  the beam, so total number of voxels is 2*beamSize
849    for(int psfCtr=1;psfCtr<=numVox;psfCtr++) cN += 1./float(psfCtr);
850
851    double slope = this->par.getAlpha()/cN;
852    for(int loopCtr=0;loopCtr<count;loopCtr++) {
853      if( orderedP[loopCtr] < (slope * double(loopCtr+1)/ double(count)) ){
854        max = loopCtr;
855      }
856    }
857
858    this->Stats.setPThreshold( orderedP[max] );
859
860
861    // Find real value of the P threshold by finding the inverse of the
862    //  error function -- root finding with brute force technique
863    //  (relatively slow, but we only do it once).
864    double zStat     = 0.;
865    double deltaZ    = 0.1;
866    double tolerance = 1.e-6;
867    double initial   = 0.5 * erfc(zStat/M_SQRT2) - this->Stats.getPThreshold();
868    do{
869      zStat+=deltaZ;
870      double current = 0.5 * erfc(zStat/M_SQRT2) - this->Stats.getPThreshold();
871      if((initial*current)<0.){
872        zStat-=deltaZ;
873        deltaZ/=2.;
874      }
875    }while(deltaZ>tolerance);
876    this->Stats.setThreshold( zStat*this->Stats.getSpread() +
877                              this->Stats.getMiddle() );
878
879    ///////////////////////////
880    //   if(TESTING){
881    //     std::stringstream ss;
882    //     float *xplot = new float[2*max];
883    //     for(int i=0;i<2*max;i++) xplot[i]=float(i)/float(count);
884    //     cpgopen("latestFDR.ps/vcps");
885    //     cpgpap(8.,1.);
886    //     cpgslw(3);
887    //     cpgenv(0,float(2*max)/float(count),0,orderedP[2*max],0,0);
888    //     cpglab("i/N (index)", "p-value","");
889    //     cpgpt(2*max,xplot,orderedP,DOT);
890
891    //     ss.str("");
892    //     ss << "\\gm = " << this->Stats.getMiddle();
893    //     cpgtext(max/(4.*count),0.9*orderedP[2*max],ss.str().c_str());
894    //     ss.str("");
895    //     ss << "\\gs = " << this->Stats.getSpread();
896    //     cpgtext(max/(4.*count),0.85*orderedP[2*max],ss.str().c_str());
897    //     ss.str("");
898    //     ss << "Slope = " << slope;
899    //     cpgtext(max/(4.*count),0.8*orderedP[2*max],ss.str().c_str());
900    //     ss.str("");
901    //     ss << "Alpha = " << this->par.getAlpha();
902    //     cpgtext(max/(4.*count),0.75*orderedP[2*max],ss.str().c_str());
903    //     ss.str("");
904    //     ss << "c\\dN\\u = " << cN;
905    //     cpgtext(max/(4.*count),0.7*orderedP[2*max],ss.str().c_str());
906    //     ss.str("");
907    //     ss << "max = "<<max << " (out of " << count << ")";
908    //     cpgtext(max/(4.*count),0.65*orderedP[2*max],ss.str().c_str());
909    //     ss.str("");
910    //     ss << "Threshold = "<<zStat*this->Stats.getSpread()+this->Stats.getMiddle();
911    //     cpgtext(max/(4.*count),0.6*orderedP[2*max],ss.str().c_str());
912 
913    //     cpgslw(1);
914    //     cpgsci(RED);
915    //     cpgmove(0,0);
916    //     cpgdraw(1,slope);
917    //     cpgsci(BLUE);
918    //     cpgsls(DOTTED);
919    //     cpgmove(0,orderedP[max]);
920    //     cpgdraw(2*max/float(count),orderedP[max]);
921    //     cpgmove(max/float(count),0);
922    //     cpgdraw(max/float(count),orderedP[2*max]);
923    //     cpgsci(GREEN);
924    //     cpgsls(SOLID);
925    //     for(int i=1;i<=10;i++) {
926    //       ss.str("");
927    //       ss << float(i)/2. << "\\gs";
928    //       float prob = 0.5*erfc((float(i)/2.)/M_SQRT2);
929    //       cpgtick(0, 0, 0, orderedP[2*max],
930    //        prob/orderedP[2*max],
931    //        0, 1, 1.5, 90., ss.str().c_str());
932    //     }
933    //     cpgend();
934    //     delete [] xplot;
935    //   }
936    delete [] orderedP;
937
938  }
939  //--------------------------------------------------------------------
940
941  bool Cube::isDetection(long x, long y, long z)
942  {
943    /**
944     * Is a given voxel at position (x,y,z) a detection, based on the statistics
945     *  in the Cube's StatsContainer?
946     * If the pixel lies outside the valid range for the data array,
947     * return false.
948     * \param x X-value of the Cube's voxel to be tested.
949     * \param y Y-value of the Cube's voxel to be tested.
950     * \param z Z-value of the Cube's voxel to be tested.
951     */
952    long voxel = z*axisDim[0]*axisDim[1] + y*axisDim[0] + x;
953    return DataArray::isDetection(array[voxel]);
954  }
955  //--------------------------------------------------------------------
956
957  void Cube::calcObjectFluxes()
958  {
959    /**
960     *  A function to calculate the fluxes and centroids for each
961     *  object in the Cube's list of detections. Uses
962     *  Detection::calcFluxes() for each object.
963     */
964    std::vector<Detection>::iterator obj;
965    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
966      obj->calcFluxes(this->array, this->axisDim);
967      if(this->par.getFlagUserThreshold())
968        obj->setPeakSNR( obj->getPeakFlux() / this->Stats.getThreshold() );
969      else
970        obj->setPeakSNR( (obj->getPeakFlux() - this->Stats.getMiddle()) / this->Stats.getSpread() );
971    }
972  }
973  //--------------------------------------------------------------------
974
975  void Cube::calcObjectWCSparams()
976  {
977    /**
978     *  A function that calculates the WCS parameters for each object in the
979     *  Cube's list of detections.
980     *  Each object gets an ID number assigned to it (which is simply its order
981     *   in the list), and if the WCS is good, the WCS paramters are calculated.
982     */
983
984    std::vector<Detection>::iterator obj;
985    int ct=0;
986    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
987      obj->setID(ct++);
988      obj->setCentreType(this->par.getPixelCentre());
989      obj->calcFluxes(this->array,this->axisDim);
990      //      obj->calcWCSparams(this->array,this->axisDim,this->head);
991      obj->calcWCSparams(this->head);
992      obj->calcIntegFlux(this->array,this->axisDim,this->head);
993   
994      if(this->par.getFlagUserThreshold())
995        obj->setPeakSNR( obj->getPeakFlux() / this->Stats.getThreshold() );
996      else
997        obj->setPeakSNR( (obj->getPeakFlux() - this->Stats.getMiddle()) / this->Stats.getSpread() );
998
999    } 
1000
1001    if(!this->head.isWCS()){
1002      // if the WCS is bad, set the object names to Obj01 etc
1003      int numspaces = int(log10(this->objectList->size())) + 1;
1004      std::stringstream ss;
1005      for(int i=0;i<this->objectList->size();i++){
1006        ss.str("");
1007        ss << "Obj" << std::setfill('0') << std::setw(numspaces) << i+1;
1008        obj->setName(ss.str());
1009      }
1010    }
1011 
1012  }
1013  //--------------------------------------------------------------------
1014
1015  void Cube::calcObjectWCSparams(std::vector< std::vector<PixelInfo::Voxel> > bigVoxList)
1016  {
1017    /**
1018     *  A function that calculates the WCS parameters for each object in the
1019     *  Cube's list of detections.
1020     *  Each object gets an ID number assigned to it (which is simply its order
1021     *   in the list), and if the WCS is good, the WCS paramters are calculated.
1022     *
1023     *  This version uses vectors of Voxels to define the fluxes.
1024     *
1025     * \param bigVoxList A vector of vectors of Voxels, with the same
1026     * number of elements as this->objectList, where each element is a
1027     * vector of Voxels corresponding to the same voxels in each
1028     * detection and indicating the flux of each voxel.
1029     */
1030 
1031    std::vector<Detection>::iterator obj;
1032    int ct=0;
1033    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
1034      obj->setID(ct+1);
1035      obj->setCentreType(this->par.getPixelCentre());
1036      obj->calcFluxes(bigVoxList[ct]);
1037      obj->calcWCSparams(this->head);
1038      obj->calcIntegFlux(bigVoxList[ct],this->head);
1039   
1040      if(this->par.getFlagUserThreshold())
1041        obj->setPeakSNR( obj->getPeakFlux() / this->Stats.getThreshold() );
1042      else
1043        obj->setPeakSNR( (obj->getPeakFlux() - this->Stats.getMiddle()) / this->Stats.getSpread() );
1044
1045      ct++;
1046    } 
1047
1048    if(!this->head.isWCS()){
1049      // if the WCS is bad, set the object names to Obj01 etc
1050      int numspaces = int(log10(this->objectList->size())) + 1;
1051      std::stringstream ss;
1052      for(int i=0;i<this->objectList->size();i++){
1053        ss.str("");
1054        ss << "Obj" << std::setfill('0') << std::setw(numspaces) << i+1;
1055        obj->setName(ss.str());
1056      }
1057    }
1058 
1059  }
1060  //--------------------------------------------------------------------
1061
1062  void Cube::updateDetectMap()
1063  {
1064    /**
1065     *  A function that, for each detected object in the cube's list, increments
1066     *   the cube's detection map by the required amount at each pixel.
1067     */
1068
1069    Scan temp;
1070    for(int obj=0;obj<this->objectList->size();obj++){
1071      long numZ=this->objectList->at(obj).pixels().getNumChanMap();
1072      for(int iz=0;iz<numZ;iz++){ // for each channel map
1073        Object2D *chanmap = new Object2D;
1074        *chanmap = this->objectList->at(obj).pixels().getChanMap(iz).getObject();
1075        for(int iscan=0;iscan<chanmap->getNumScan();iscan++){
1076          temp = chanmap->getScan(iscan);
1077          for(int x=temp.getX(); x <= temp.getXmax(); x++)
1078            this->detectMap[temp.getY()*this->axisDim[0] + x]++;
1079        } // end of loop over scans
1080        delete chanmap;
1081      } // end of loop over channel maps
1082    } // end of loop over objects.
1083
1084  }
1085  //--------------------------------------------------------------------
1086
1087  void Cube::updateDetectMap(Detection obj)
1088  {
1089    /**
1090     *  A function that, for the given object, increments the cube's
1091     *  detection map by the required amount at each pixel.
1092     *
1093     *  \param obj A Detection object that is being incorporated into the map.
1094     */
1095
1096    Scan temp;
1097    long numZ=obj.pixels().getNumChanMap();
1098    for(int iz=0;iz<numZ;iz++){ // for each channel map
1099      Object2D chanmap = obj.pixels().getChanMap(iz).getObject();
1100      for(int iscan=0;iscan<chanmap.getNumScan();iscan++){
1101        temp = chanmap.getScan(iscan);
1102        for(int x=temp.getX(); x <= temp.getXmax(); x++)
1103          this->detectMap[temp.getY()*this->axisDim[0] + x]++;
1104      } // end of loop over scans
1105    } // end of loop over channel maps
1106
1107  }
1108  //--------------------------------------------------------------------
1109
1110  float Cube::enclosedFlux(Detection obj)
1111  {
1112    /**
1113     *   A function to calculate the flux enclosed by the range
1114     *    of pixels detected in the object obj (not necessarily all
1115     *    pixels will have been detected).
1116     *
1117     *   \param obj The Detection under consideration.
1118     */
1119    obj.calcFluxes(this->array, this->axisDim);
1120    int xsize = obj.getXmax()-obj.getXmin()+1;
1121    int ysize = obj.getYmax()-obj.getYmin()+1;
1122    int zsize = obj.getZmax()-obj.getZmin()+1;
1123    std::vector <float> fluxArray(xsize*ysize*zsize,0.);
1124    for(int x=0;x<xsize;x++){
1125      for(int y=0;y<ysize;y++){
1126        for(int z=0;z<zsize;z++){
1127          fluxArray[x+y*xsize+z*ysize*xsize] =
1128            this->getPixValue(x+obj.getXmin(),
1129                              y+obj.getYmin(),
1130                              z+obj.getZmin());
1131          if(this->par.getFlagNegative())
1132            fluxArray[x+y*xsize+z*ysize*xsize] *= -1.;
1133        }
1134      }
1135    }
1136    float sum = 0.;
1137    for(int i=0;i<fluxArray.size();i++)
1138      if(!this->par.isBlank(fluxArray[i])) sum+=fluxArray[i];
1139    return sum;
1140  }
1141  //--------------------------------------------------------------------
1142
1143  void Cube::setupColumns()
1144  {
1145    /**
1146     *   A front-end to the two setup routines in columns.cc. 
1147     *
1148     *   This first gets the starting precisions, which may be from
1149     *   the input parameters. It then sets up the columns (calculates
1150     *   their widths and precisions and so on based on the values
1151     *   within). The precisions are also stored in each Detection
1152     *   object.
1153     *
1154     *   Need to have called calcObjectWCSparams() somewhere
1155     *   beforehand.
1156     */
1157
1158    std::vector<Detection>::iterator obj;
1159    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
1160      obj->setVelPrec( this->par.getPrecVel() );
1161      obj->setFpeakPrec( this->par.getPrecFlux() );
1162      obj->setXYZPrec( Column::prXYZ );
1163      obj->setPosPrec( Column::prWPOS );
1164      obj->setFintPrec( this->par.getPrecFlux() );
1165      obj->setSNRPrec( this->par.getPrecSNR() );
1166    }
1167 
1168    this->fullCols.clear();
1169    this->fullCols = getFullColSet(*(this->objectList), this->head);
1170
1171    this->logCols.clear();
1172    this->logCols = getLogColSet(*(this->objectList), this->head);
1173
1174    int vel,fpeak,fint,pos,xyz,snr;
1175    vel = fullCols[VEL].getPrecision();
1176    fpeak = fullCols[FPEAK].getPrecision();
1177    snr = fullCols[SNRPEAK].getPrecision();
1178    xyz = fullCols[X].getPrecision();
1179    xyz = std::max(xyz, fullCols[Y].getPrecision());
1180    xyz = std::max(xyz, fullCols[Z].getPrecision());
1181    if(this->head.isWCS()) fint = fullCols[FINT].getPrecision();
1182    else fint = fullCols[FTOT].getPrecision();
1183    pos = fullCols[WRA].getPrecision();
1184    pos = std::max(pos, fullCols[WDEC].getPrecision());
1185 
1186    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
1187      obj->setVelPrec(vel);
1188      obj->setFpeakPrec(fpeak);
1189      obj->setXYZPrec(xyz);
1190      obj->setPosPrec(pos);
1191      obj->setFintPrec(fint);
1192      obj->setSNRPrec(snr);
1193    }
1194
1195  }
1196  //--------------------------------------------------------------------
1197
1198  bool Cube::objAtSpatialEdge(Detection obj)
1199  {
1200    /**
1201     *   A function to test whether the object obj
1202     *    lies at the edge of the cube's spatial field --
1203     *    either at the boundary, or next to BLANKs.
1204     *
1205     *   \param obj The Detection under consideration.
1206     */
1207
1208    bool atEdge = false;
1209
1210    int pix = 0;
1211    std::vector<Voxel> voxlist = obj.pixels().getPixelSet();
1212    while(!atEdge && pix<voxlist.size()){
1213      // loop over each pixel in the object, until we find an edge pixel.
1214      for(int dx=-1;dx<=1;dx+=2){
1215        if( ((voxlist[pix].getX()+dx)<0) ||
1216            ((voxlist[pix].getX()+dx)>=this->axisDim[0]) )
1217          atEdge = true;
1218        else if(this->isBlank(voxlist[pix].getX()+dx,
1219                              voxlist[pix].getY(),
1220                              voxlist[pix].getZ()))
1221          atEdge = true;
1222      }
1223      for(int dy=-1;dy<=1;dy+=2){
1224        if( ((voxlist[pix].getY()+dy)<0) ||
1225            ((voxlist[pix].getY()+dy)>=this->axisDim[1]) )
1226          atEdge = true;
1227        else if(this->isBlank(voxlist[pix].getX(),
1228                              voxlist[pix].getY()+dy,
1229                              voxlist[pix].getZ()))
1230          atEdge = true;
1231      }
1232      pix++;
1233    }
1234
1235    return atEdge;
1236  }
1237  //--------------------------------------------------------------------
1238
1239  bool Cube::objAtSpectralEdge(Detection obj)
1240  {
1241    /** 
1242     *   A function to test whether the object obj
1243     *    lies at the edge of the cube's spectral extent --
1244     *    either at the boundary, or next to BLANKs.
1245     *
1246     *   /param obj The Detection under consideration.
1247     */
1248
1249    bool atEdge = false;
1250
1251    int pix = 0;
1252    std::vector<Voxel> voxlist = obj.pixels().getPixelSet();
1253    while(!atEdge && pix<voxlist.size()){
1254      // loop over each pixel in the object, until we find an edge pixel.
1255      for(int dz=-1;dz<=1;dz+=2){
1256        if( ((voxlist[pix].getZ()+dz)<0) ||
1257            ((voxlist[pix].getZ()+dz)>=this->axisDim[2]))
1258          atEdge = true;
1259        else if(this->isBlank(voxlist[pix].getX(),
1260                              voxlist[pix].getY(),
1261                              voxlist[pix].getZ()+dz))
1262          atEdge = true;
1263      }
1264      pix++;
1265    }
1266
1267    return atEdge;
1268  }
1269  //--------------------------------------------------------------------
1270
1271  void Cube::setObjectFlags()
1272  {
1273    /**   
1274     *   A function to set any warning flags for all the detected objects
1275     *    associated with the cube.
1276     *   Flags to be looked for:
1277     *    <ul><li> Negative enclosed flux (N)
1278     *        <li> Detection at edge of field (spatially) (E)
1279     *        <li> Detection at edge of spectral region (S)
1280     *    </ul>
1281     */
1282
1283    std::vector<Detection>::iterator obj;
1284    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
1285
1286      if( this->enclosedFlux(*obj) < 0. ) 
1287        obj->addToFlagText("N");
1288
1289      if( this->objAtSpatialEdge(*obj) )
1290        obj->addToFlagText("E");
1291
1292      if( this->objAtSpectralEdge(*obj) && (this->axisDim[2] > 2))
1293        obj->addToFlagText("S");
1294
1295    }
1296
1297  }
1298  //--------------------------------------------------------------------
1299
1300
1301
1302  /****************************************************************/
1303  /////////////////////////////////////////////////////////////
1304  //// Functions for Image class
1305  /////////////////////////////////////////////////////////////
1306
1307  Image::Image(long size){
1308    // need error handling in case size<0 !!!
1309    this->numPixels = this->numDim = 0;
1310    if(size<0)
1311      duchampError("Image(size)","Negative size -- could not define Image");
1312    else{
1313      if(size>0 && !this->arrayAllocated){
1314        this->array = new float[size];
1315        this->arrayAllocated = true;
1316      }
1317      this->numPixels = size;
1318      this->axisDim = new long[2];
1319      this->axisDimAllocated = true;
1320      this->numDim = 2;
1321    }
1322  }
1323  //--------------------------------------------------------------------
1324
1325  Image::Image(long *dimensions){
1326    this->numPixels = this->numDim = 0;
1327    int size = dimensions[0] * dimensions[1];
1328    if(size<0)
1329      duchampError("Image(dimArray)","Negative size -- could not define Image");
1330    else{
1331      this->numPixels = size;
1332      if(size>0){
1333        this->array = new float[size];
1334        this->arrayAllocated = true;
1335      }
1336      this->numDim=2;
1337      this->axisDim = new long[2];
1338      for(int i=0;i<2;i++) this->axisDim[i] = dimensions[i];
1339    }
1340  }
1341  //--------------------------------------------------------------------
1342  //--------------------------------------------------------------------
1343
1344  void Image::saveArray(float *input, long size)
1345  {
1346    /**
1347     * Saves the array in input to the pixel array Image::array.
1348     * The size of the array given must be the same as the current number of
1349     * pixels, else an error message is returned and nothing is done.
1350     * \param input The array of values to be saved.
1351     * \param size The size of input.
1352     */
1353    if(size != this->numPixels)
1354      duchampError("Image::saveArray",
1355                   "Input array different size to existing array. Cannot save.");
1356    else {
1357      if(this->numPixels>0 && this->arrayAllocated) delete [] array;
1358      this->numPixels = size;
1359      if(this->numPixels>0){
1360        this->array = new float[size];
1361        this->arrayAllocated = true;
1362        for(int i=0;i<size;i++) this->array[i] = input[i];
1363      }
1364    }
1365  }
1366  //--------------------------------------------------------------------
1367
1368  void Image::extractSpectrum(float *Array, long *dim, long pixel)
1369  {
1370    /**
1371     *  A function to extract a 1-D spectrum from a 3-D array.
1372     *  The array is assumed to be 3-D with the third dimension the spectral one.
1373     *  The spectrum extracted is the one lying in the spatial pixel referenced
1374     *    by the third argument.
1375     *  The extracted spectrum is stored in the pixel array Image::array.
1376     * \param Array The array containing the pixel values, from which
1377     *               the spectrum is extracted.
1378     * \param dim The array of dimension values.
1379     * \param pixel The spatial pixel that contains the desired spectrum.
1380     */
1381    if((pixel<0)||(pixel>=dim[0]*dim[1]))
1382      duchampError("Image::extractSpectrum",
1383                   "Requested spatial pixel outside allowed range. Cannot save.");
1384    else if(dim[2] != this->numPixels)
1385      duchampError("Image::extractSpectrum",
1386                   "Input array different size to existing array. Cannot save.");
1387    else {
1388      if(this->numPixels>0 && this->arrayAllocated) delete [] array;
1389      this->numPixels = dim[2];
1390      if(this->numPixels>0){
1391        this->array = new float[dim[2]];
1392        this->arrayAllocated = true;
1393        for(int z=0;z<dim[2];z++) this->array[z] = Array[z*dim[0]*dim[1] + pixel];
1394      }
1395    }
1396  }
1397  //--------------------------------------------------------------------
1398
1399  void Image::extractSpectrum(Cube &cube, long pixel)
1400  {
1401    /**
1402     *  A function to extract a 1-D spectrum from a Cube class
1403     *  The spectrum extracted is the one lying in the spatial pixel referenced
1404     *    by the second argument.
1405     *  The extracted spectrum is stored in the pixel array Image::array.
1406     * \param cube The Cube containing the pixel values, from which the spectrum is extracted.
1407     * \param pixel The spatial pixel that contains the desired spectrum.
1408     */
1409    long zdim = cube.getDimZ();
1410    long spatSize = cube.getDimX()*cube.getDimY();
1411    if((pixel<0)||(pixel>=spatSize))
1412      duchampError("Image::extractSpectrum",
1413                   "Requested spatial pixel outside allowed range. Cannot save.");
1414    else if(zdim != this->numPixels)
1415      duchampError("Image::extractSpectrum",
1416                   "Input array different size to existing array. Cannot save.");
1417    else {
1418      if(this->numPixels>0 && this->arrayAllocated) delete [] array;
1419      this->numPixels = zdim;
1420      if(this->numPixels>0){
1421        this->array = new float[zdim];
1422        this->arrayAllocated = true;
1423        for(int z=0;z<zdim;z++)
1424          this->array[z] = cube.getPixValue(z*spatSize + pixel);
1425      }
1426    }
1427  }
1428  //--------------------------------------------------------------------
1429
1430  void Image::extractImage(float *Array, long *dim, long channel)
1431  {
1432    /**
1433     *  A function to extract a 2-D image from a 3-D array.
1434     *  The array is assumed to be 3-D with the third dimension the spectral one.
1435     *  The dimensions of the array are in the dim[] array.
1436     *  The image extracted is the one lying in the channel referenced
1437     *    by the third argument.
1438     *  The extracted image is stored in the pixel array Image::array.
1439     * \param Array The array containing the pixel values, from which the image is extracted.
1440     * \param dim The array of dimension values.
1441     * \param channel The spectral channel that contains the desired image.
1442     */
1443
1444    long spatSize = dim[0]*dim[1];
1445    if((channel<0)||(channel>=dim[2]))
1446      duchampError("Image::extractImage",
1447                   "Requested channel outside allowed range. Cannot save.");
1448    else if(spatSize != this->numPixels)
1449      duchampError("Image::extractImage",
1450                   "Input array different size to existing array. Cannot save.");
1451    else {
1452      if(this->numPixels>0 && this->arrayAllocated) delete [] array;
1453      this->numPixels = spatSize;
1454      if(this->numPixels>0){
1455        this->array = new float[spatSize];
1456        this->arrayAllocated = true;
1457        for(int npix=0; npix<spatSize; npix++)
1458          this->array[npix] = Array[channel*spatSize + npix];
1459      }
1460    }
1461  }
1462  //--------------------------------------------------------------------
1463
1464  void Image::extractImage(Cube &cube, long channel)
1465  {
1466    /**
1467     *  A function to extract a 2-D image from Cube class.
1468     *  The image extracted is the one lying in the channel referenced
1469     *    by the second argument.
1470     *  The extracted image is stored in the pixel array Image::array.
1471     * \param cube The Cube containing the pixel values, from which the image is extracted.
1472     * \param channel The spectral channel that contains the desired image.
1473     */
1474    long spatSize = cube.getDimX()*cube.getDimY();
1475    if((channel<0)||(channel>=cube.getDimZ()))
1476      duchampError("Image::extractImage",
1477                   "Requested channel outside allowed range. Cannot save.");
1478    else if(spatSize != this->numPixels)
1479      duchampError("Image::extractImage",
1480                   "Input array different size to existing array. Cannot save.");
1481    else {
1482      if(this->numPixels>0 && this->arrayAllocated) delete [] array;
1483      this->numPixels = spatSize;
1484      if(this->numPixels>0){
1485        this->array = new float[spatSize];
1486        this->arrayAllocated = true;
1487        for(int npix=0; npix<spatSize; npix++)
1488          this->array[npix] = cube.getPixValue(channel*spatSize + npix);
1489      }
1490    }
1491  }
1492  //--------------------------------------------------------------------
1493
1494  void Image::removeMW()
1495  {
1496    /**
1497     *  A function to remove the Milky Way range of channels from a 1-D spectrum.
1498     *  The array in this Image is assumed to be 1-D, with only the first axisDim
1499     *    equal to 1.
1500     *  The values of the MW channels are set to 0, unless they are BLANK.
1501     */
1502    if(this->par.getFlagMW() && (this->axisDim[1]==1) ){
1503      for(int z=0;z<this->axisDim[0];z++){
1504        if(!this->isBlank(z) && this->par.isInMW(z)) this->array[z]=0.;
1505      }
1506    }
1507  }
1508
1509}
Note: See TracBrowser for help on using the repository browser.