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

Last change on this file since 474 was 468, checked in by MatthewWhiting, 16 years ago

Fixing some memory leaks.

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