source: tags/release-1.1.6/src/Cubes/cubes.cc @ 1112

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

A couple of bug fixes from studying Enno's RM cube.

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