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

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

Primarily, solving ticket #39, by making sure the user threshold overrides the FDR method. Other tidying up as well.

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