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

Last change on this file since 383 was 378, checked in by MatthewWhiting, 17 years ago

Large amount of changes, but really just making a "duchamp" namespace to encompass duchamp-specific stuff. Not the PixelMap? stuff though.

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