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

Last change on this file since 803 was 803, checked in by MatthewWhiting, 13 years ago

Fixing typo.

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