source: tags/release-1.2.2/src/Cubes/cubes.cc

Last change on this file was 1066, checked in by MatthewWhiting, 12 years ago

Cleaning up - removing all the old commented out code. We can also remove entirely the file src/Cubes/VOTable.cc, by incorporating the outputDetectionsVOTable() function to detectionIO.cc

File size: 67.8 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/Outputs/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 Catalogues;
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 size_t[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 size_t[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, size_t 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)", "Negative size -- could not define DataArray");
147    }
148    else if(nDim<0){
149      DUCHAMPERROR("DataArray(nDim,size)", "Negative number of dimensions: could not define DataArray");
150    }
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 size_t[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, size_t *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)", "Negative number of dimensions: could not define DataArray");
180    }
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)", "Negative size: could not define DataArray");
186      }
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 size_t[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(size_t &x, size_t &y, size_t &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(size_t *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(size_t i=0;i<this->numPixels;i++) output[i] = this->array[i];
259  }
260  //--------------------------------------------------------------------
261
262  void DataArray::saveArray(float *input, size_t 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", "Input array different size to existing array. Cannot save.");
273    }
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(size_t 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(size_t 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(size_t 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    }
397    else{
398      if(size>0){
399        this->array = new float[size];
400        this->arrayAllocated = true;
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->numPixels = size;
411      this->axisDim = new size_t[3];
412      this->axisDimAllocated = true;
413      this->numDim = 3;
414      this->reconExists = false;
415    }
416  }
417  //--------------------------------------------------------------------
418
419  Cube::Cube(size_t *dimensions)
420  {
421    /// Alternative Cube constructor, where sizes of dimensions are given.
422    /// Arrays are allocated as appropriate (according to the
423    ///  relevant flags in Param set), as is the Cube::axisDim array.
424
425    int size   = dimensions[0] * dimensions[1] * dimensions[2];
426    int imsize = dimensions[0] * dimensions[1];
427    this->reconAllocated = false;
428    this->baselineAllocated = false;
429    this->axisDimAllocated = false;
430    this->arrayAllocated = false;
431    this->numPixels = this->numDim = 0;
432    if((size<0) || (imsize<0) ){
433      DUCHAMPERROR("Cube(dimArray)","Negative size -- could not define Cube");
434    }
435    else{
436      this->numPixels = size;
437      if(size>0){
438        this->array      = new float[size];
439        this->arrayAllocated = true;
440        this->detectMap  = new short[imsize];
441        if(this->par.getFlagATrous()||this->par.getFlagSmooth()){
442          this->recon    = new float[size];
443          this->reconAllocated = true;
444        }
445        if(this->par.getFlagBaseline()){
446          this->baseline = new float[size];
447          this->baselineAllocated = true;
448        }
449      }
450      this->numDim  = 3;
451      this->axisDim = new size_t[3];
452      this->axisDimAllocated = true;
453      for(int i=0;i<3     ;i++) this->axisDim[i]   = dimensions[i];
454      for(int i=0;i<imsize;i++) this->detectMap[i] = 0;
455      this->reconExists = false;
456    }
457  }
458  //--------------------------------------------------------------------
459
460  Cube::~Cube()
461  {
462    /// @details
463    ///  The destructor deletes the memory allocated for Cube::detectMap, and,
464    ///  if these have been allocated, Cube::recon and Cube::baseline.
465
466    if(this->numPixels>0 && this->arrayAllocated) delete [] this->detectMap;
467    if(this->reconAllocated)    delete [] this->recon;
468    if(this->baselineAllocated) delete [] this->baseline;
469  }
470  //--------------------------------------------------------------------
471
472  Cube::Cube(const Cube &c):
473    DataArray(c)
474  {
475    this->operator=(c);
476  }
477  //--------------------------------------------------------------------
478
479  Cube& Cube::operator=(const Cube &c)
480  {
481    if(this==&c) return *this;
482    if(this->arrayAllocated) delete [] this->detectMap;
483    ((DataArray &) *this) = c;
484    this->reconExists = c.reconExists;
485    if(this->reconAllocated) delete [] this->recon;
486    this->reconAllocated = c.reconAllocated;
487    if(this->reconAllocated) {
488      this->recon = new float[this->numPixels];
489      for(size_t i=0;i<size_t(this->numPixels);i++) this->recon[i] = c.recon[i];
490    }
491    if(this->arrayAllocated){
492      this->detectMap = new short[this->axisDim[0]*this->axisDim[1]];
493      for(size_t i=0;i<size_t(this->axisDim[0]*this->axisDim[1]);i++) this->detectMap[i] = c.detectMap[i];
494    }
495    if(this->baselineAllocated) delete [] this->baseline;
496    this->baselineAllocated = c.baselineAllocated;
497    if(this->baselineAllocated){
498      this->baseline = new float[this->numPixels];
499      for(size_t i=0;i<size_t(this->numPixels);i++) this->baseline[i] = c.baseline[i];
500    }
501    this->head = c.head;
502    this->fullCols = c.fullCols;
503    return *this;
504  }
505  //--------------------------------------------------------------------
506
507  Cube* Cube::slice(Section subsection)
508  {
509    Cube *output = new Cube;
510    Section thisSection;
511    std::string nullsec=nullSection(this->numDim);
512    if(this->par.section().isParsed()) thisSection=this->par.section();
513    else{
514      thisSection = Section(nullsec);
515      thisSection.parse(this->axisDim, this->numDim);
516    }
517
518    subsection.parse(this->axisDim, this->numDim);
519    if(subsection.isValid()){
520      output->par = this->par;
521      output->par.section() = thisSection * subsection;
522      output->par.setXOffset(output->par.getXOffset()+subsection.getStart(0));
523      output->par.setYOffset(output->par.getYOffset()+subsection.getStart(1));
524      output->par.setZOffset(output->par.getZOffset()+subsection.getStart(2));
525      output->head = this->head;
526      // correct the reference pixel in the WCS
527      output->head.WCS().crpix[output->head.WCS().lng] -= subsection.getStart(output->head.WCS().lng);
528      output->head.WCS().crpix[output->head.WCS().lat] -= subsection.getStart(output->head.WCS().lat);
529      if(output->head.WCS().spec>0)
530        output->head.WCS().crpix[output->head.WCS().spec] -= subsection.getStart(output->head.WCS().spec);
531      output->Stats = this->Stats;
532      output->fullCols = this->fullCols;
533      size_t *dims = new size_t[3];
534      for(size_t i=0;i<3;i++){
535        dims[i] = subsection.getDimList()[i];
536        std::cout << "Dim " << i+1 << " = " << dims[i] << "\n";
537      }
538     
539      output->initialiseCube(dims,true);
540      for(size_t z=0;z<output->axisDim[2];z++){
541        for(size_t y=0;y<output->axisDim[1];y++){
542          for(size_t x=0;x<output->axisDim[0];x++){
543            size_t impos=x+y*output->axisDim[0];
544            size_t pos=impos+z*output->axisDim[0]*output->axisDim[1];
545            if(pos>=output->numPixels) DUCHAMPERROR("cube slicer","Out of bounds in new Cube");
546            size_t imposIn=(x+subsection.getStart(0)) + (y+subsection.getStart(1))*this->axisDim[0];
547            size_t posIn=imposIn + (z+subsection.getStart(2))*this->axisDim[0]*this->axisDim[1];
548            if(posIn>=this->numPixels) DUCHAMPERROR("cube slicer","Out of bounds in new Cube");
549            output->array[pos] = this->array[posIn];
550            output->detectMap[impos] = this->detectMap[imposIn];
551            if(this->reconAllocated) output->recon[pos] = this->recon[posIn];
552            if(this->baselineAllocated) output->baseline[pos] = this->baseline[posIn];
553          }
554        }
555      }
556       std::cout << this->par << "\n"<<output->par <<"\n";
557    }
558    else{
559      DUCHAMPERROR("cube slicer","Subsection does not parse");
560    }
561
562    return output;
563
564  }
565  //--------------------------------------------------------------------
566
567  OUTCOME Cube::initialiseCube(long *dimensions, bool allocateArrays)
568  {
569    int numAxes = this->head.getNumAxes();
570    if(numAxes<=0) numAxes=3;
571    size_t *dim = new size_t[numAxes];
572    for(int i=0;i<numAxes;i++) dim[i]=dimensions[i];
573    OUTCOME outcome=this->initialiseCube(dim,allocateArrays);
574    delete [] dim;
575    return outcome;
576  }
577
578
579  OUTCOME Cube::initialiseCube(size_t *dimensions, bool allocateArrays)
580  {
581    /// @details
582    ///  This function will set the sizes of all arrays that will be used by Cube.
583    ///  It will also define the values of the axis dimensions: this will be done
584    ///   using the WCS in the FitsHeader class, so the WCS needs to be good and
585    ///   have three axes. If this is not the case, the axes are assumed to be
586    ///   ordered in the sense of lng,lat,spc.
587    ///
588    ///  \param dimensions An array of values giving the dimensions (sizes) for
589    ///  all axes. 
590    ///  \param allocateArrays A flag indicating whether to allocate
591    ///  the memory for the data arrays: the default is true. The
592    ///  dimension arrays will be allocated and filled.
593
594    int lng,lat,spc;
595    size_t size,imsize;
596 
597    int numAxes = this->head.getNumAxes();
598    if(numAxes<=0) numAxes=3;
599
600    if(this->head.isWCS() && (numAxes>=3) && (this->head.WCS().spec>=0)){
601      // if there is a WCS and there is at least 3 axes
602      lng = this->head.WCS().lng;
603      lat = this->head.WCS().lat;
604      spc = this->head.WCS().spec;
605    }
606    else{
607      // just take dimensions[] at face value
608      lng = 0;
609      lat = 1;
610      spc = 2;
611    }
612
613    size   = dimensions[lng];
614    if(numAxes>1) size *= dimensions[lat];
615    if(this->head.canUseThirdAxis() && numAxes>spc) size *= dimensions[spc];
616
617    imsize = dimensions[lng];
618    if(numAxes>1) imsize *= dimensions[lat];
619
620    this->reconAllocated = false;
621    this->baselineAllocated = false;
622
623    if(this->axisDimAllocated){
624      delete [] this->axisDim;
625      this->axisDimAllocated = false;
626    }
627
628    if(this->arrayAllocated){
629      delete [] this->array;
630      delete [] this->detectMap;
631      this->arrayAllocated = false;
632    }
633    if(this->reconAllocated){
634      delete [] this->recon;
635      this->reconAllocated = false;
636    }
637    if(this->baselineAllocated){
638      delete [] this->baseline;
639      this->baselineAllocated = false;
640    }
641
642    if((size<0) || (imsize<0) ) {
643      DUCHAMPERROR("Cube::initialiseCube(dimArray)", "Negative size -- could not define Cube.");
644      return FAILURE;
645    }
646    else{
647      this->numPixels = size;
648      this->numDim  = 3;
649
650      this->axisDim = new size_t[this->numDim];
651      this->axisDimAllocated = true;
652      this->axisDim[0] = dimensions[lng];
653      if(numAxes>1) this->axisDim[1] = dimensions[lat];
654      else this->axisDim[1] = 1;
655      if(this->head.canUseThirdAxis() && numAxes>spc) this->axisDim[2] = dimensions[spc];
656      else this->axisDim[2] = 1;
657
658      this->numNondegDim=0;
659      for(int i=0;i<3;i++) if(this->axisDim[i]>1) this->numNondegDim++;
660
661      if(this->numNondegDim == 1){
662        if(!head.isWCS()) std::swap(this->axisDim[0],this->axisDim[2]);
663        imsize=this->axisDim[2];
664      }
665
666      bool haveChanged=false;
667      int change=0;
668      if(this->par.getMinPix() > this->axisDim[0]*this->axisDim[1]){
669        DUCHAMPWARN("Cube::initialiseCube", "The value of minPix ("<<this->par.getMinPix()<<") is greater than the image size. Setting to "<<this->axisDim[0]*this->axisDim[1]);
670        change=this->par.getMinPix() - this->axisDim[0]*this->axisDim[1];
671        haveChanged=true;
672        this->par.setMinPix(this->axisDim[0]*this->axisDim[1]);
673      }
674      if(this->par.getMinChannels() > this->axisDim[2]){
675        DUCHAMPWARN("Cube::initialiseCube", "The value of minChannels ("<<this->par.getMinChannels()<<") is greater than the spectral size. Setting to "<<this->axisDim[2]);
676        change=this->par.getMinChannels() - this->axisDim[2];
677        haveChanged=true;
678        this->par.setMinChannels(this->axisDim[2]);
679      }
680      if(haveChanged){
681        DUCHAMPWARN("Cube::initialiseCube","Reducing minVoxels to "<<this->par.getMinVoxels() - change<<" to accomodate these changes" );
682        this->par.setMinVoxels(this->par.getMinVoxels() - change);
683      }
684     
685      if(this->par.getFlagSmooth()){
686        if(this->par.getSmoothType()=="spectral" && this->numNondegDim==2){
687          DUCHAMPWARN("Cube::initialiseCube", "Spectral smooth requested, but have a 2D image. Setting flagSmooth=false");
688          this->par.setFlagSmooth(false);
689        }
690        if(this->par.getSmoothType()=="spatial" && this->numNondegDim==1){
691          DUCHAMPWARN("Cube::initialiseCube", "Spatial smooth requested, but have a 1D image. Setting flagSmooth=false");
692          this->par.setFlagSmooth(false);
693        }
694      }
695      if(this->par.getFlagATrous()){
696        for(int d=3; d>=1; d--){
697          if(this->par.getReconDim()==d && this->numNondegDim==(d-1)){
698            DUCHAMPWARN("Cube::initialiseCube", d << "D reconstruction requested, but image is " << d-1 <<"D. Setting flagAtrous=false");
699            this->par.setFlagATrous(false);
700          }
701        }
702      }
703
704      if(allocateArrays && this->par.isVerbose()) this->reportMemorySize(std::cout,allocateArrays);
705
706      this->reconExists = false;
707      if(size>0 && allocateArrays){
708        this->array      = new float[size];
709        this->arrayAllocated = true;
710        this->detectMap  = new short[imsize];
711        for(size_t i=0;i<imsize;i++) this->detectMap[i] = 0;
712        if(this->par.getFlagATrous() || this->par.getFlagSmooth()){
713          this->recon    = new float[size];
714          this->reconAllocated = true;
715          for(size_t i=0;i<size;i++) this->recon[i] = 0.;
716        }
717        if(this->par.getFlagBaseline()){
718          this->baseline = new float[size];
719          this->baselineAllocated = true;
720          for(size_t i=0;i<size;i++) this->baseline[i] = 0.;
721        }
722      }
723    }
724    return SUCCESS;
725  }
726  //--------------------------------------------------------------------
727
728  void Cube::reportMemorySize(std::ostream &theStream, bool allocateArrays)
729  {
730    std::string unitlist[4]={"kB","MB","GB","TB"};
731    size_t size=axisDim[0]*axisDim[1]*axisDim[2];
732    size_t imsize=axisDim[0]*axisDim[1];
733   
734      // Calculate and report the total size of memory to be allocated.
735      float allocSize=3*sizeof(size_t);  // axisDim
736      float arrAllocSize=0.;
737      if(size>0 && allocateArrays){
738        allocSize += size * sizeof(float); // array
739        arrAllocSize = size*sizeof(float);
740        allocSize += imsize * sizeof(short); // detectMap
741        if(this->par.getFlagATrous() || this->par.getFlagSmooth())
742          allocSize += size * sizeof(float); // recon
743        if(this->par.getFlagBaseline())
744          allocSize += size * sizeof(float); // baseline
745      }
746      std::string units="bytes";
747      for(int i=0;i<4 && allocSize>1024.;i++){
748        allocSize/=1024.;
749        arrAllocSize /= 1024.;
750        units=unitlist[i];
751      }
752
753      theStream << "\n About to allocate " << allocSize << units;
754      if(arrAllocSize > 0.) theStream << " of which " << arrAllocSize << units << " is for the image\n";
755      else theStream << "\n";
756  }
757
758
759  bool Cube::is2D()
760  {
761    /// @details
762    ///   Check whether the image is 2-dimensional, by counting
763    ///   the number of dimensions that are greater than 1
764
765    if(this->head.WCS().naxis==2) return true;
766    else{
767      int numDim=0;
768      for(int i=0;i<this->numDim;i++) if(axisDim[i]>1) numDim++;
769      return numDim<=2;
770    }
771
772  }
773  //--------------------------------------------------------------------
774
775  OUTCOME Cube::getCube()
776  { 
777    ///  @details
778    /// A front-end to the Cube::getCube() function, that does
779    ///  subsection checks.
780    /// Assumes the Param is set up properly.
781
782    std::string fname = par.getImageFile();
783    if(par.getFlagSubsection()) fname+=par.getSubsection();
784    return getCube(fname);
785  }
786  //--------------------------------------------------------------------
787
788  void Cube::saveArray(float *input, size_t size)
789  {
790    if(size != this->numPixels){
791      DUCHAMPERROR("Cube::saveArray","Input array different size to existing array (" << size << " cf. " << this->numPixels << "). Cannot save.");
792    }
793    else {
794      if(this->numPixels>0 && this->arrayAllocated) delete [] array;
795      this->numPixels = size;
796      this->array = new float[size];
797      this->arrayAllocated = true;
798      for(size_t i=0;i<size;i++) this->array[i] = input[i];
799    }
800  }
801  //--------------------------------------------------------------------
802
803  void Cube::saveArray(std::vector<float> &input)
804  {
805    /// @details
806    /// Saves the array in input to the pixel array Cube::array.
807    /// The size of the array given must be the same as the current number of
808    /// pixels, else an error message is returned and nothing is done.
809    /// \param input The array of values to be saved.
810
811    if(input.size() != this->numPixels){
812      DUCHAMPERROR("Cube::saveArray","Input array different size to existing array (" << input.size() << " cf. " << this->numPixels << "). Cannot save.");
813    }
814    else {
815      if(this->numPixels>0 && this->arrayAllocated) delete [] this->array;
816      this->numPixels = input.size();
817      this->array = new float[input.size()];
818      this->arrayAllocated = true;
819      for(size_t i=0;i<input.size();i++) this->array[i] = input[i];
820    }
821  }
822  //--------------------------------------------------------------------
823
824  void Cube::saveRecon(float *input, size_t size)
825  {
826    /// @details
827    /// Saves the array in input to the reconstructed array Cube::recon
828    /// The size of the array given must be the same as the current number of
829    /// pixels, else an error message is returned and nothing is done.
830    /// If the recon array has already been allocated, it is deleted first, and
831    /// then the space is allocated.
832    /// Afterwards, the appropriate flags are set.
833    /// \param input The array of values to be saved.
834    /// \param size The size of input.
835
836    if(size != this->numPixels){
837      DUCHAMPERROR("Cube::saveRecon","Input array different size to existing array (" << size << " cf. " << this->numPixels << "). Cannot save.");
838    }
839    else {
840      if(this->numPixels>0){
841        if(this->reconAllocated) delete [] this->recon;
842        this->numPixels = size;
843        this->recon = new float[size];
844        this->reconAllocated = true;
845        for(size_t i=0;i<size;i++) this->recon[i] = input[i];
846        this->reconExists = true;
847      }
848    }
849  }
850  //--------------------------------------------------------------------
851
852  void Cube::getRecon(float *output)
853  {
854    /// @details
855    /// The reconstructed array is written to output. The output array needs to
856    ///  be defined beforehand: no checking is done on the memory.
857    /// \param output The array that is written to.
858
859    // Need check for change in number of pixels!
860    for(size_t i=0;i<this->numPixels;i++){
861      if(this->reconExists) output[i] = this->recon[i];
862      else output[i] = 0.;
863    }
864  }
865  //--------------------------------------------------------------------
866
867  void Cube::removeMW()
868  {
869    /// @details
870    /// The channels corresponding to the Milky Way range (as given by the Param
871    ///  set) are all set to 0 in the pixel array.
872    /// Only done if the appropriate flag is set, and the pixels are not BLANK.
873    /// \deprecated
874
875    if(this->par.getFlagMW()){
876      for(size_t pix=0;pix<this->axisDim[0]*this->axisDim[1];pix++){
877        for(size_t z=0;z<this->axisDim[2];z++){
878          size_t pos = z*this->axisDim[0]*this->axisDim[1] + pix;
879          if(!this->isBlank(pos) && this->par.isInMW(z)) this->array[pos]=0.;
880        }
881      }
882    }
883  }
884  //--------------------------------------------------------------------
885
886  void Cube::setCubeStats()
887  {
888    ///   @details
889    ///   Calculates the full statistics for the cube:
890    ///     mean, rms, median, madfm
891    ///   Only do this if the threshold has not been defined (ie. is still 0.,
892    ///    its default).
893    ///   Also work out the threshold and store it in the par set.
894    ///   
895    ///   Different from Cube::setCubeStatsOld() as it doesn't use the
896    ///    getStats functions but has own versions of them hardcoded to
897    ///    ignore BLANKs and MW channels. This saves on memory usage -- necessary
898    ///    for dealing with very big files.
899    ///
900    ///   Three cases exist:
901    ///  <ul><li>Simple case, with no reconstruction/smoothing: all stats
902    ///          calculated from the original array.
903    ///      <li>Wavelet reconstruction: mean & median calculated from the
904    ///          original array, and stddev & madfm from the residual.
905    ///      <li>Smoothing: all four stats calculated from the recon array
906    ///          (which holds the smoothed data).
907    ///  </ul>
908
909    if(this->par.getFlagUserThreshold() ){
910      // if the user has defined a threshold, set this in the StatsContainer
911      this->Stats.setThreshold( this->par.getThreshold() );
912    }
913    else{
914      // only work out the stats if we need to.
915      // the only reason we don't is if the user has specified a threshold.
916   
917      this->Stats.setRobust(this->par.getFlagRobustStats());
918
919      if(this->par.isVerbose())
920        std::cout << "Calculating the cube statistics... " << std::flush;
921   
922      // size_t xysize = this->axisDim[0]*this->axisDim[1];
923
924      bool *mask = new bool[this->numPixels];
925      size_t vox=0,goodSize = 0;
926      for(size_t z=0;z<this->axisDim[2];z++){
927        for(size_t y=0;y<this->axisDim[1];y++){
928          for(size_t x=0;x<this->axisDim[0];x++){
929            //      vox = z * xysize + y*this->axisDim[0] + x;
930            bool isBlank=this->isBlank(vox);
931            bool isMW = this->par.isInMW(z);
932            bool statOK = this->par.isStatOK(x,y,z);
933            mask[vox] = (!isBlank && !isMW && statOK );
934            if(mask[vox]) goodSize++;
935            vox++;
936          }
937        }
938      }
939
940      //      float mean,median,stddev,madfm;
941      if( this->par.getFlagATrous() ){
942        // Case #2 -- wavelet reconstruction
943        // just get mean & median from orig array, and rms & madfm from
944        // residual recompute array values to be residuals & then find
945        // stddev & madfm
946        if(!this->reconExists){
947          DUCHAMPERROR("setCubeStats", "Reconstruction not yet done! Cannot calculate stats!");
948        }
949        else{
950          float *tempArray = new float[goodSize];
951
952          goodSize=0;
953          vox=0;
954          for(size_t z=0;z<this->axisDim[2];z++){
955            for(size_t y=0;y<this->axisDim[1];y++){
956              for(size_t x=0;x<this->axisDim[0];x++){
957                //              vox = z * xysize + y*this->axisDim[0] + x;
958                if(mask[vox]) tempArray[goodSize++] = this->array[vox];
959                vox++;
960              }
961            }
962          }
963
964          // First, find the mean of the original array. Store it.
965          this->Stats.setMean( findMean<float>(tempArray, goodSize) );
966       
967          // Now sort it and find the median. Store it.
968          this->Stats.setMedian( findMedian<float>(tempArray, goodSize, true) );
969
970          // Now calculate the residuals and find the mean & median of
971          // them. We don't store these, but they are necessary to find
972          // the sttdev & madfm.
973          goodSize = 0;
974          //      for(int p=0;p<xysize;p++){
975          vox=0;
976          for(size_t z=0;z<this->axisDim[2];z++){
977            for(size_t y=0;y<this->axisDim[1];y++){
978              for(size_t x=0;x<this->axisDim[0];x++){
979                //            vox = z * xysize + p;
980              if(mask[vox])
981                tempArray[goodSize++] = this->array[vox] - this->recon[vox];
982              vox++;
983              }
984            }
985          }
986           
987          this->Stats.setStddev( findStddev<float>(tempArray, goodSize) );
988
989          // Now find the madfm of the residuals. Store it.
990          this->Stats.setMadfm( findMADFM(tempArray, goodSize, true) );
991
992          delete [] tempArray;
993        }
994      }
995      else if(this->par.getFlagSmooth()) {
996        // Case #3 -- smoothing
997        // get all four stats from the recon array, which holds the
998        // smoothed data. This can just be done with the
999        // StatsContainer::calculate function, using the mask generated
1000        // earlier.
1001        if(!this->reconExists){
1002          DUCHAMPERROR("setCubeStats","Smoothing not yet done! Cannot calculate stats!");
1003        }
1004        else this->Stats.calculate(this->recon,this->numPixels,mask);
1005      }
1006      else{
1007        // Case #1 -- default case, with no smoothing or reconstruction.
1008        // get all four stats from the original array. This can just be
1009        // done with the StatsContainer::calculate function, using the
1010        // mask generated earlier.
1011        this->Stats.calculate(this->array,this->numPixels,mask);
1012      }
1013
1014      this->Stats.setUseFDR( this->par.getFlagFDR() );
1015      // If the FDR method has been requested, define the P-value
1016      // threshold
1017      if(this->par.getFlagFDR())  this->setupFDR();
1018      else{
1019        // otherwise, calculate threshold based on the requested SNR cut
1020        // level, and then set the threshold parameter in the Par set.
1021        this->Stats.setThresholdSNR( this->par.getCut() );
1022        this->par.setThreshold( this->Stats.getThreshold() );
1023      }
1024   
1025      delete [] mask;
1026
1027    }
1028
1029    if(this->par.isVerbose()){
1030      std::cout << "Using ";
1031      if(this->par.getFlagFDR()) std::cout << "effective ";
1032      std::cout << "flux threshold of: ";
1033      float thresh = this->Stats.getThreshold();
1034      if(this->par.getFlagNegative()) thresh *= -1.;
1035      std::cout << thresh;
1036      if(this->par.getFlagGrowth()){
1037        std::cout << " and growing to threshold of: ";
1038        if(this->par.getFlagUserGrowthThreshold()) thresh= this->par.getGrowthThreshold();
1039        else thresh= this->Stats.snrToValue(this->par.getGrowthCut());
1040        if(this->par.getFlagNegative()) thresh *= -1.;
1041        std::cout << thresh;
1042      }
1043      std::cout << std::endl;
1044    }
1045
1046  }
1047  //--------------------------------------------------------------------
1048
1049  void Cube::setupFDR()
1050  {
1051    /// @details
1052    ///  Call the setupFDR(float *) function on the pixel array of the
1053    ///  cube. This is the usual way of running it.
1054    ///
1055    ///  However, if we are in smoothing mode, we calculate the FDR
1056    ///  parameters using the recon array, which holds the smoothed
1057    ///  data. Gives an error message if the reconExists flag is not set.
1058
1059    if(this->par.getFlagSmooth())
1060      if(this->reconExists) this->setupFDR(this->recon);
1061      else{
1062        DUCHAMPERROR("setupFDR", "Smoothing not done properly! Using original array for defining threshold.");
1063        this->setupFDR(this->array);
1064      }
1065    else if( this->par.getFlagATrous() ){
1066      if(this->reconExists) this->setupFDR(this->recon);
1067      else{
1068        DUCHAMPERROR("setupFDR", "Reconstruction not done properly! Using original array for defining threshold.");
1069        this->setupFDR(this->array);
1070      }
1071    }
1072    else{
1073      this->setupFDR(this->array);
1074    }
1075  }
1076  //--------------------------------------------------------------------
1077
1078  void Cube::setupFDR(float *input)
1079  {
1080    ///   @details
1081    ///   Determines the critical Probability value for the False
1082    ///   Discovery Rate detection routine. All pixels in the given arry
1083    ///   with Prob less than this value will be considered detections.
1084    ///
1085    ///   Note that the Stats of the cube need to be calculated first.
1086    ///
1087    ///   The Prob here is the probability, assuming a Normal
1088    ///   distribution, of obtaining a value as high or higher than the
1089    ///   pixel value (ie. only the positive tail of the PDF).
1090    ///
1091    ///   The probabilities are calculated using the
1092    ///   StatsContainer::getPValue(), which calculates the z-statistic,
1093    ///   and then the probability via
1094    ///   \f$0.5\operatorname{erfc}(z/\sqrt{2})\f$ -- giving the positive
1095    ///   tail probability.
1096
1097    // first calculate p-value for each pixel -- assume Gaussian for now.
1098
1099    float *orderedP = new float[this->numPixels];
1100    size_t count = 0;
1101    for(size_t x=0;x<this->axisDim[0];x++){
1102      for(size_t y=0;y<this->axisDim[1];y++){
1103        for(size_t z=0;z<this->axisDim[2];z++){
1104          size_t pix = z * this->axisDim[0]*this->axisDim[1] +
1105            y*this->axisDim[0] + x;
1106
1107          if(!(this->par.isBlank(this->array[pix])) && !this->par.isInMW(z)){
1108            // only look at non-blank, valid pixels
1109            //            orderedP[count++] = this->Stats.getPValue(this->array[pix]);
1110            orderedP[count++] = this->Stats.getPValue(input[pix]);
1111          }
1112        }
1113      }
1114    }
1115
1116    // now order them
1117    std::stable_sort(orderedP,orderedP+count);
1118 
1119    // now find the maximum P value.
1120    size_t max = 0;
1121    double cN = 0.;
1122    // Calculate number of correlated pixels. Assume all spatial
1123    // pixels within the beam are correlated, and multiply this by the
1124    // number of correlated pixels as determined by the beam
1125    int numVox;
1126    if(this->head.beam().isDefined()) numVox = int(ceil(this->head.beam().area()));
1127    else  numVox = 1;
1128    if(this->head.canUseThirdAxis()) numVox *= this->par.getFDRnumCorChan();
1129    for(int psfCtr=1;psfCtr<=numVox;psfCtr++) cN += 1./float(psfCtr);
1130
1131    double slope = this->par.getAlpha()/cN;
1132    for(size_t loopCtr=0;loopCtr<count;loopCtr++) {
1133      if( orderedP[loopCtr] < (slope * double(loopCtr+1)/ double(count)) ){
1134        max = loopCtr;
1135      }
1136    }
1137
1138    this->Stats.setPThreshold( orderedP[max] );
1139
1140
1141    // Find real value of the P threshold by finding the inverse of the
1142    //  error function -- root finding with brute force technique
1143    //  (relatively slow, but we only do it once).
1144    double zStat     = 0.;
1145    double deltaZ    = 0.1;
1146    double tolerance = 1.e-6;
1147    double initial   = 0.5 * erfc(zStat/M_SQRT2) - this->Stats.getPThreshold();
1148    do{
1149      zStat+=deltaZ;
1150      double current = 0.5 * erfc(zStat/M_SQRT2) - this->Stats.getPThreshold();
1151      if((initial*current)<0.){
1152        zStat-=deltaZ;
1153        deltaZ/=2.;
1154      }
1155    }while(deltaZ>tolerance);
1156    this->Stats.setThreshold( zStat*this->Stats.getSpread() +
1157                              this->Stats.getMiddle() );
1158
1159    ///////////////////////////
1160    //   if(TESTING){
1161    //     std::stringstream ss;
1162    //     float *xplot = new float[2*max];
1163    //     for(int i=0;i<2*max;i++) xplot[i]=float(i)/float(count);
1164    //     cpgopen("latestFDR.ps/vcps");
1165    //     cpgpap(8.,1.);
1166    //     cpgslw(3);
1167    //     cpgenv(0,float(2*max)/float(count),0,orderedP[2*max],0,0);
1168    //     cpglab("i/N (index)", "p-value","");
1169    //     cpgpt(2*max,xplot,orderedP,DOT);
1170
1171    //     ss.str("");
1172    //     ss << "\\gm = " << this->Stats.getMiddle();
1173    //     cpgtext(max/(4.*count),0.9*orderedP[2*max],ss.str().c_str());
1174    //     ss.str("");
1175    //     ss << "\\gs = " << this->Stats.getSpread();
1176    //     cpgtext(max/(4.*count),0.85*orderedP[2*max],ss.str().c_str());
1177    //     ss.str("");
1178    //     ss << "Slope = " << slope;
1179    //     cpgtext(max/(4.*count),0.8*orderedP[2*max],ss.str().c_str());
1180    //     ss.str("");
1181    //     ss << "Alpha = " << this->par.getAlpha();
1182    //     cpgtext(max/(4.*count),0.75*orderedP[2*max],ss.str().c_str());
1183    //     ss.str("");
1184    //     ss << "c\\dN\\u = " << cN;
1185    //     cpgtext(max/(4.*count),0.7*orderedP[2*max],ss.str().c_str());
1186    //     ss.str("");
1187    //     ss << "max = "<<max << " (out of " << count << ")";
1188    //     cpgtext(max/(4.*count),0.65*orderedP[2*max],ss.str().c_str());
1189    //     ss.str("");
1190    //     ss << "Threshold = "<<zStat*this->Stats.getSpread()+this->Stats.getMiddle();
1191    //     cpgtext(max/(4.*count),0.6*orderedP[2*max],ss.str().c_str());
1192 
1193    //     cpgslw(1);
1194    //     cpgsci(RED);
1195    //     cpgmove(0,0);
1196    //     cpgdraw(1,slope);
1197    //     cpgsci(BLUE);
1198    //     cpgsls(DOTTED);
1199    //     cpgmove(0,orderedP[max]);
1200    //     cpgdraw(2*max/float(count),orderedP[max]);
1201    //     cpgmove(max/float(count),0);
1202    //     cpgdraw(max/float(count),orderedP[2*max]);
1203    //     cpgsci(GREEN);
1204    //     cpgsls(SOLID);
1205    //     for(int i=1;i<=10;i++) {
1206    //       ss.str("");
1207    //       ss << float(i)/2. << "\\gs";
1208    //       float prob = 0.5*erfc((float(i)/2.)/M_SQRT2);
1209    //       cpgtick(0, 0, 0, orderedP[2*max],
1210    //        prob/orderedP[2*max],
1211    //        0, 1, 1.5, 90., ss.str().c_str());
1212    //     }
1213    //     cpgend();
1214    //     delete [] xplot;
1215    //   }
1216    delete [] orderedP;
1217
1218  }
1219  //--------------------------------------------------------------------
1220
1221  void Cube::Search()
1222  {
1223    /// @details
1224    /// This acts as a switching function to select the correct searching function based on the user's parameters.
1225    /// @param verboseFlag If true, text is written to stdout describing the search function being used.
1226    if(this->par.getFlagATrous()){
1227      if(this->par.isVerbose()) std::cout<<"Commencing search in reconstructed cube..."<<std::endl;
1228      this->ReconSearch();
1229    } 
1230    else if(this->par.getFlagSmooth()){
1231      if(this->par.isVerbose()) std::cout<<"Commencing search in smoothed cube..."<<std::endl;
1232      this->SmoothSearch();
1233    }
1234    else{
1235      if(this->par.isVerbose()) std::cout<<"Commencing search in cube..."<<std::endl;
1236      this->CubicSearch();
1237    }
1238
1239  }
1240
1241  bool Cube::isDetection(size_t x, size_t y, size_t z)
1242  {
1243    ///  @details
1244    /// Is a given voxel at position (x,y,z) a detection, based on the statistics
1245    ///  in the Cube's StatsContainer?
1246    /// If the pixel lies outside the valid range for the data array,
1247    /// return false.
1248    /// \param x X-value of the Cube's voxel to be tested.
1249    /// \param y Y-value of the Cube's voxel to be tested.
1250    /// \param z Z-value of the Cube's voxel to be tested.
1251
1252    size_t voxel = z*axisDim[0]*axisDim[1] + y*axisDim[0] + x;
1253    return DataArray::isDetection(array[voxel]);
1254  }
1255  //--------------------------------------------------------------------
1256
1257  void Cube::calcObjectFluxes()
1258  {
1259    /// @details
1260    ///  A function to calculate the fluxes and centroids for each
1261    ///  object in the Cube's list of detections. Uses
1262    ///  Detection::calcFluxes() for each object.
1263
1264    std::vector<Detection>::iterator obj;
1265    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
1266      obj->calcFluxes(this->array, this->axisDim);
1267      if(this->par.getFlagUserThreshold())
1268        obj->setPeakSNR( obj->getPeakFlux() / this->Stats.getThreshold() );
1269      else
1270        obj->setPeakSNR( (obj->getPeakFlux() - this->Stats.getMiddle()) / this->Stats.getSpread() );
1271    }
1272  }
1273  //--------------------------------------------------------------------
1274
1275  void Cube::calcObjectWCSparams()
1276  {
1277    ///  @details
1278    ///  A function that calculates the WCS parameters for each object in the
1279    ///  Cube's list of detections.
1280    ///  Each object gets an ID number assigned to it (which is simply its order
1281    ///   in the list), and if the WCS is good, the WCS paramters are calculated.
1282
1283    std::vector<Detection>::iterator obj;
1284    int ct=0;
1285    ProgressBar bar;
1286    if(this->par.isVerbose()) bar.init(this->objectList->size());
1287    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
1288      //      std::cerr << ct << ' ' << this->array << '\n';
1289      if(this->par.isVerbose()) bar.update(ct);
1290      obj->setID(ct++);
1291      if(!obj->hasParams()){
1292        obj->setCentreType(this->par.getPixelCentre());
1293        obj->calcFluxes(this->array,this->axisDim);
1294        //      obj->calcWCSparams(this->array,this->axisDim,this->head);
1295        obj->calcWCSparams(this->head);
1296        obj->calcIntegFlux(this->array,this->axisDim,this->head);
1297
1298        if(this->par.getFlagUserThreshold())
1299          obj->setPeakSNR( obj->getPeakFlux() / this->Stats.getThreshold() );
1300        else
1301          obj->setPeakSNR( (obj->getPeakFlux() - this->Stats.getMiddle()) / this->Stats.getSpread() );
1302      }
1303    } 
1304    if(this->par.isVerbose()) bar.remove();
1305
1306    if(!this->head.isWCS()){
1307      // if the WCS is bad, set the object names to Obj01 etc
1308      int numspaces = int(log10(this->objectList->size())) + 1;
1309      std::stringstream ss;
1310      for(size_t i=0;i<this->objectList->size();i++){
1311        ss.str("");
1312        ss << "Obj" << std::setfill('0') << std::setw(numspaces) << i+1;
1313        this->objectList->at(i).setName(ss.str());
1314      }
1315    }
1316 
1317  }
1318  //--------------------------------------------------------------------
1319
1320  void Cube::calcObjectWCSparams(std::vector< std::vector<PixelInfo::Voxel> > bigVoxList)
1321  {
1322    ///  @details
1323    ///  A function that calculates the WCS parameters for each object in the
1324    ///  Cube's list of detections.
1325    ///  Each object gets an ID number assigned to it (which is simply its order
1326    ///   in the list), and if the WCS is good, the WCS paramters are calculated.
1327    ///
1328    ///  This version uses vectors of Voxels to define the fluxes.
1329    ///
1330    /// \param bigVoxList A vector of vectors of Voxels, with the same
1331    /// number of elements as this->objectList, where each element is a
1332    /// vector of Voxels corresponding to the same voxels in each
1333    /// detection and indicating the flux of each voxel.
1334 
1335    std::vector<Detection>::iterator obj;
1336    int ct=0;
1337    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
1338      obj->setID(ct+1);
1339      if(!obj->hasParams()){
1340        obj->setCentreType(this->par.getPixelCentre());
1341        obj->calcFluxes(bigVoxList[ct]);
1342        obj->calcWCSparams(this->head);
1343        obj->calcIntegFlux(this->axisDim[2],bigVoxList[ct],this->head);
1344       
1345        if(this->par.getFlagUserThreshold())
1346          obj->setPeakSNR( obj->getPeakFlux() / this->Stats.getThreshold() );
1347        else
1348          obj->setPeakSNR( (obj->getPeakFlux() - this->Stats.getMiddle()) / this->Stats.getSpread() );
1349      }
1350      ct++;
1351    } 
1352
1353    if(!this->head.isWCS()){
1354      // if the WCS is bad, set the object names to Obj01 etc
1355      int numspaces = int(log10(this->objectList->size())) + 1;
1356      std::stringstream ss;
1357      for(size_t i=0;i<this->objectList->size();i++){
1358        ss.str("");
1359        ss << "Obj" << std::setfill('0') << std::setw(numspaces) << i+1;
1360        this->objectList->at(i).setName(ss.str());
1361      }
1362    }
1363 
1364  }
1365  //--------------------------------------------------------------------
1366
1367  void Cube::calcObjectWCSparams(std::map<PixelInfo::Voxel,float> &voxelMap)
1368  {
1369    ///  @details
1370    ///  A function that calculates the WCS parameters for each object in the
1371    ///  Cube's list of detections.
1372    ///  Each object gets an ID number assigned to it (which is simply its order
1373    ///   in the list), and if the WCS is good, the WCS paramters are calculated.
1374    ///
1375    ///  This version uses vectors of Voxels to define the fluxes.
1376    ///
1377    /// \param bigVoxList A vector of vectors of Voxels, with the same
1378    /// number of elements as this->objectList, where each element is a
1379    /// vector of Voxels corresponding to the same voxels in each
1380    /// detection and indicating the flux of each voxel.
1381 
1382    std::vector<Detection>::iterator obj;
1383    int ct=0;
1384    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
1385      obj->setID(ct+1);
1386      if(!obj->hasParams()){
1387        obj->setCentreType(this->par.getPixelCentre());
1388        obj->calcFluxes(voxelMap);
1389        obj->calcWCSparams(this->head);
1390        obj->calcIntegFlux(this->axisDim[2],voxelMap,this->head);
1391       
1392        if(this->par.getFlagUserThreshold())
1393          obj->setPeakSNR( obj->getPeakFlux() / this->Stats.getThreshold() );
1394        else
1395          obj->setPeakSNR( (obj->getPeakFlux() - this->Stats.getMiddle()) / this->Stats.getSpread() );
1396      }
1397      ct++;
1398    } 
1399
1400    if(!this->head.isWCS()){
1401      // if the WCS is bad, set the object names to Obj01 etc
1402      int numspaces = int(log10(this->objectList->size())) + 1;
1403      std::stringstream ss;
1404      for(size_t i=0;i<this->objectList->size();i++){
1405        ss.str("");
1406        ss << "Obj" << std::setfill('0') << std::setw(numspaces) << i+1;
1407        this->objectList->at(i).setName(ss.str());
1408      }
1409    }
1410 
1411  }
1412  //--------------------------------------------------------------------
1413
1414  void Cube::updateDetectMap()
1415  {
1416    /// @details A function that, for each detected object in the
1417    ///  cube's list, increments the cube's detection map by the
1418    ///  required amount at each pixel. Uses
1419    ///  updateDetectMap(Detection).
1420
1421    std::vector<Detection>::iterator obj;
1422    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
1423      this->updateDetectMap(*obj);
1424    }
1425
1426  }
1427  //--------------------------------------------------------------------
1428
1429  void Cube::updateDetectMap(Detection obj)
1430  {
1431    ///  @details
1432    ///  A function that, for the given object, increments the cube's
1433    ///  detection map by the required amount at each pixel.
1434    ///
1435    ///  \param obj A Detection object that is being incorporated into the map.
1436
1437    std::vector<Voxel> vlist = obj.getPixelSet();
1438    for(std::vector<Voxel>::iterator vox=vlist.begin();vox<vlist.end();vox++) {
1439      if(this->numNondegDim==1)
1440        this->detectMap[vox->getZ()]++;
1441      else
1442        this->detectMap[vox->getX()+vox->getY()*this->axisDim[0]]++;
1443    }
1444  }
1445  //--------------------------------------------------------------------
1446
1447  float Cube::enclosedFlux(Detection obj)
1448  {
1449    ///  @details
1450    ///   A function to calculate the flux enclosed by the range
1451    ///    of pixels detected in the object obj (not necessarily all
1452    ///    pixels will have been detected).
1453    ///
1454    ///   \param obj The Detection under consideration.
1455
1456    obj.calcFluxes(this->array, this->axisDim);
1457    int xsize = obj.getXmax()-obj.getXmin()+1;
1458    int ysize = obj.getYmax()-obj.getYmin()+1;
1459    int zsize = obj.getZmax()-obj.getZmin()+1;
1460    std::vector <float> fluxArray(xsize*ysize*zsize,0.);
1461    for(int x=0;x<xsize;x++){
1462      for(int y=0;y<ysize;y++){
1463        for(int z=0;z<zsize;z++){
1464          fluxArray[x+y*xsize+z*ysize*xsize] =
1465            this->getPixValue(x+obj.getXmin(),
1466                              y+obj.getYmin(),
1467                              z+obj.getZmin());
1468          if(this->par.getFlagNegative())
1469            fluxArray[x+y*xsize+z*ysize*xsize] *= -1.;
1470        }
1471      }
1472    }
1473    float sum = 0.;
1474    for(size_t i=0;i<fluxArray.size();i++)
1475      if(!this->par.isBlank(fluxArray[i])) sum+=fluxArray[i];
1476    return sum;
1477  }
1478  //--------------------------------------------------------------------
1479
1480  void Cube::setupColumns()
1481  {
1482    /// @details
1483    ///  A front-end to the two setup routines in columns.cc. 
1484    ///
1485    ///  This first gets the starting precisions, which may be from
1486    ///  the input parameters. It then sets up the columns (calculates
1487    ///  their widths and precisions and so on based on the values
1488    ///  within). The precisions are also stored in each Detection
1489    ///  object.
1490    ///
1491    ///  Need to have called calcObjectWCSparams() somewhere
1492    ///  beforehand.
1493
1494    std::vector<Detection>::iterator obj;
1495    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
1496      obj->setVelPrec( this->par.getPrecVel() );
1497      obj->setFpeakPrec( this->par.getPrecFlux() );
1498      obj->setXYZPrec( Catalogues::prXYZ );
1499      obj->setPosPrec( Catalogues::prWPOS );
1500      obj->setFintPrec( this->par.getPrecFlux() );
1501      obj->setSNRPrec( this->par.getPrecSNR() );
1502    }
1503 
1504    this->fullCols = getFullColSet(*(this->objectList), this->head);
1505
1506    int vel,fpeak,fint,pos,xyz,snr;
1507    vel = fullCols.column("VEL").getPrecision();
1508    fpeak = fullCols.column("FPEAK").getPrecision();
1509    snr = fullCols.column("SNRPEAK").getPrecision();
1510    xyz = fullCols.column("X").getPrecision();
1511    xyz = std::max(xyz, fullCols.column("Y").getPrecision());
1512    xyz = std::max(xyz, fullCols.column("Z").getPrecision());
1513    if(this->head.isWCS()) fint = fullCols.column("FINT").getPrecision();
1514    else fint = fullCols.column("FTOT").getPrecision();
1515    pos = fullCols.column("WRA").getPrecision();
1516    pos = std::max(pos, fullCols.column("WDEC").getPrecision());
1517 
1518    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
1519      obj->setVelPrec(vel);
1520      obj->setFpeakPrec(fpeak);
1521      obj->setXYZPrec(xyz);
1522      obj->setPosPrec(pos);
1523      obj->setFintPrec(fint);
1524      obj->setSNRPrec(snr);
1525    }
1526
1527  }
1528  //--------------------------------------------------------------------
1529
1530  bool Cube::objAtSpatialEdge(Detection obj)
1531  {
1532    ///  @details
1533    ///   A function to test whether the object obj
1534    ///    lies at the edge of the cube's spatial field --
1535    ///    either at the boundary, or next to BLANKs.
1536    ///
1537    ///   \param obj The Detection under consideration.
1538
1539    bool atEdge = false;
1540
1541    size_t pix = 0;
1542    std::vector<Voxel> voxlist = obj.getPixelSet();
1543    while(!atEdge && pix<voxlist.size()){
1544      // loop over each pixel in the object, until we find an edge pixel.
1545      for(int dx=-1;dx<=1;dx+=2){
1546        if( ((voxlist[pix].getX()+dx)<0) ||
1547            ((voxlist[pix].getX()+dx)>=int(this->axisDim[0])) )
1548          atEdge = true;
1549        else if(this->isBlank(voxlist[pix].getX()+dx,
1550                              voxlist[pix].getY(),
1551                              voxlist[pix].getZ()))
1552          atEdge = true;
1553      }
1554      for(int dy=-1;dy<=1;dy+=2){
1555        if( ((voxlist[pix].getY()+dy)<0) ||
1556            ((voxlist[pix].getY()+dy)>=int(this->axisDim[1])) )
1557          atEdge = true;
1558        else if(this->isBlank(voxlist[pix].getX(),
1559                              voxlist[pix].getY()+dy,
1560                              voxlist[pix].getZ()))
1561          atEdge = true;
1562      }
1563      pix++;
1564    }
1565
1566    return atEdge;
1567  }
1568  //--------------------------------------------------------------------
1569
1570  bool Cube::objAtSpectralEdge(Detection obj)
1571  {
1572    ///   @details
1573    ///   A function to test whether the object obj
1574    ///    lies at the edge of the cube's spectral extent --
1575    ///    either at the boundary, or next to BLANKs.
1576    ///
1577    ///   \param obj The Detection under consideration.
1578
1579    bool atEdge = false;
1580
1581    size_t pix = 0;
1582    std::vector<Voxel> voxlist = obj.getPixelSet();
1583    while(!atEdge && pix<voxlist.size()){
1584      // loop over each pixel in the object, until we find an edge pixel.
1585      for(int dz=-1;dz<=1;dz+=2){
1586        if( ((voxlist[pix].getZ()+dz)<0) ||
1587            ((voxlist[pix].getZ()+dz)>=int(this->axisDim[2])) )
1588          atEdge = true;
1589        else if(this->isBlank(voxlist[pix].getX(),
1590                              voxlist[pix].getY(),
1591                              voxlist[pix].getZ()+dz))
1592          atEdge = true;
1593      }
1594      pix++;
1595    }
1596
1597    return atEdge;
1598  }
1599  //--------------------------------------------------------------------
1600
1601  bool Cube::objNextToMW(Detection obj)
1602  {
1603    ///   @details A function to test whether the object obj lies
1604    ///   adjacent to the MW range or straddles it (conceivably, you
1605    ///   could have disconnected channels in your object that don't
1606    ///   touch the MW range, but lie either side - in this case we
1607    ///   want the flag). If flagMW=false we will always return false.
1608    ///
1609    ///   \param obj The Detection under consideration.
1610
1611    bool isNext = this->par.getFlagMW() &&
1612      ((obj.getZmin() <= this->par.getMaxMW()+1) && (obj.getZmax() >= this->par.getMinMW()-1));
1613   
1614    return isNext;
1615
1616  }
1617  //--------------------------------------------------------------------
1618
1619  void Cube::setObjectFlags()
1620  {
1621    /// @details
1622    ///   A function to set any warning flags for all the detected objects
1623    ///    associated with the cube.
1624    ///   Flags to be looked for:
1625    ///    <ul><li> Negative enclosed flux (N)
1626    ///        <li> Detection at edge of field (spatially) (E)
1627    ///        <li> Detection at edge of spectral region (S)
1628    ///    </ul>
1629
1630    std::vector<Detection>::iterator obj;
1631    for(obj=this->objectList->begin();obj<this->objectList->end();obj++){
1632
1633      if( this->enclosedFlux(*obj) < 0. ) 
1634        obj->addToFlagText("N");
1635
1636      if( this->objAtSpatialEdge(*obj) )
1637        obj->addToFlagText("E");
1638
1639      if( this->objAtSpectralEdge(*obj) && (this->axisDim[2] > 2))
1640        obj->addToFlagText("S");
1641
1642      if( this->objNextToMW(*obj) )
1643        obj->addToFlagText("M");
1644
1645      if(obj->getFlagText()=="") obj->addToFlagText("-");
1646
1647    }
1648
1649  }
1650  //--------------------------------------------------------------------
1651
1652  /****************************************************************/
1653  /////////////////////////////////////////////////////////////
1654  //// Functions for Image class
1655  /////////////////////////////////////////////////////////////
1656
1657  Image::Image(size_t size)
1658  {
1659    // need error handling in case size<0 !!!
1660    this->numPixels = this->numDim = 0;
1661    this->minSize = 2;
1662    if(size<0){
1663      DUCHAMPERROR("Image(size)","Negative size -- could not define Image");
1664    }
1665    else{
1666      if(size>0 && !this->arrayAllocated){
1667        this->array = new float[size];
1668        this->arrayAllocated = true;
1669      }
1670      this->numPixels = size;
1671      this->axisDim = new size_t[2];
1672      this->axisDimAllocated = true;
1673      this->numDim = 2;
1674    }
1675  }
1676  //--------------------------------------------------------------------
1677
1678  Image::Image(size_t *dimensions)
1679  {
1680    this->numPixels = this->numDim = 0;
1681    this->minSize = 2;
1682    int size = dimensions[0] * dimensions[1];
1683    if(size<0){
1684      DUCHAMPERROR("Image(dimArray)","Negative size -- could not define Image");
1685    }
1686    else{
1687      this->numPixels = size;
1688      if(size>0){
1689        this->array = new float[size];
1690        this->arrayAllocated = true;
1691      }
1692      this->numDim=2;
1693      this->axisDim = new size_t[2];
1694      this->axisDimAllocated = true;
1695      for(int i=0;i<2;i++) this->axisDim[i] = dimensions[i];
1696    }
1697  }
1698  //--------------------------------------------------------------------
1699  Image::Image(const Image &i):
1700    DataArray(i)
1701  {
1702    this->operator=(i);
1703  }
1704
1705  Image& Image::operator=(const Image &i)
1706  {
1707    if(this==&i) return *this;
1708    ((DataArray &) *this) = i;
1709    this->minSize = i.minSize;
1710    return *this;
1711  }
1712
1713  //--------------------------------------------------------------------
1714
1715  void Image::saveArray(float *input, size_t size)
1716  {
1717    /// @details
1718    /// Saves the array in input to the pixel array Image::array.
1719    /// The size of the array given must be the same as the current number of
1720    /// pixels, else an error message is returned and nothing is done.
1721    /// \param input The array of values to be saved.
1722    /// \param size The size of input.
1723
1724    if(size != this->numPixels){
1725      DUCHAMPERROR("Image::saveArray", "Input array different size to existing array. Cannot save.");
1726    }
1727    else {
1728      if(this->numPixels>0 && this->arrayAllocated) delete [] array;
1729      this->numPixels = size;
1730      if(this->numPixels>0){
1731        this->array = new float[size];
1732        this->arrayAllocated = true;
1733        for(size_t i=0;i<size;i++) this->array[i] = input[i];
1734      }
1735    }
1736  }
1737  //--------------------------------------------------------------------
1738
1739  void Image::extractSpectrum(float *Array, size_t *dim, size_t pixel)
1740  {
1741    /// @details
1742    ///  A function to extract a 1-D spectrum from a 3-D array.
1743    ///  The array is assumed to be 3-D with the third dimension the spectral one.
1744    ///  The spectrum extracted is the one lying in the spatial pixel referenced
1745    ///    by the third argument.
1746    ///  The extracted spectrum is stored in the pixel array Image::array.
1747    /// \param Array The array containing the pixel values, from which
1748    ///               the spectrum is extracted.
1749    /// \param dim The array of dimension values.
1750    /// \param pixel The spatial pixel that contains the desired spectrum.
1751
1752    if((pixel<0)||(pixel>=dim[0]*dim[1])){
1753      DUCHAMPERROR("Image::extractSpectrum", "Requested spatial pixel outside allowed range. Cannot save.");
1754    }
1755    else if(dim[2] != this->numPixels){
1756      DUCHAMPERROR("Image::extractSpectrum", "Input array different size to existing array. Cannot save.");
1757    }
1758    else {
1759      if(this->numPixels>0 && this->arrayAllocated) delete [] array;
1760      this->numPixels = dim[2];
1761      if(this->numPixels>0){
1762        this->array = new float[dim[2]];
1763        this->arrayAllocated = true;
1764        for(size_t z=0;z<dim[2];z++) this->array[z] = Array[z*dim[0]*dim[1] + pixel];
1765      }
1766    }
1767  }
1768  //--------------------------------------------------------------------
1769
1770  void Image::extractSpectrum(Cube &cube, size_t pixel)
1771  {
1772    /// @details
1773    ///  A function to extract a 1-D spectrum from a Cube class
1774    ///  The spectrum extracted is the one lying in the spatial pixel referenced
1775    ///    by the second argument.
1776    ///  The extracted spectrum is stored in the pixel array Image::array.
1777    /// \param cube The Cube containing the pixel values, from which the spectrum is extracted.
1778    /// \param pixel The spatial pixel that contains the desired spectrum.
1779
1780    size_t zdim = cube.getDimZ();
1781    size_t spatSize = cube.getDimX()*cube.getDimY();
1782    if((pixel<0)||(pixel>=spatSize)){
1783      DUCHAMPERROR("Image::extractSpectrum", "Requested spatial pixel outside allowed range. Cannot save.");
1784    }
1785    else if(zdim != this->numPixels){
1786      DUCHAMPERROR("Image::extractSpectrum", "Input array different size to existing array. Cannot save.");
1787    }
1788    else {
1789      if(this->numPixels>0 && this->arrayAllocated) delete [] array;
1790      this->numPixels = zdim;
1791      if(this->numPixels>0){
1792        this->array = new float[zdim];
1793        this->arrayAllocated = true;
1794        for(size_t z=0;z<zdim;z++)
1795          this->array[z] = cube.getPixValue(z*spatSize + pixel);
1796      }
1797    }
1798  }
1799  //--------------------------------------------------------------------
1800
1801  void Image::extractImage(float *Array, size_t *dim, size_t channel)
1802  {
1803    /// @details
1804    ///  A function to extract a 2-D image from a 3-D array.
1805    ///  The array is assumed to be 3-D with the third dimension the spectral one.
1806    ///  The dimensions of the array are in the dim[] array.
1807    ///  The image extracted is the one lying in the channel referenced
1808    ///    by the third argument.
1809    ///  The extracted image is stored in the pixel array Image::array.
1810    /// \param Array The array containing the pixel values, from which the image is extracted.
1811    /// \param dim The array of dimension values.
1812    /// \param channel The spectral channel that contains the desired image.
1813
1814    size_t spatSize = dim[0]*dim[1];
1815    if((channel<0)||(channel>=dim[2])){
1816      DUCHAMPERROR("Image::extractImage", "Requested channel outside allowed range. Cannot save.");
1817    }
1818    else if(spatSize != this->numPixels){
1819      DUCHAMPERROR("Image::extractImage", "Input array different size to existing array. Cannot save.");
1820    }
1821    else {
1822      if(this->numPixels>0 && this->arrayAllocated) delete [] array;
1823      this->numPixels = spatSize;
1824      if(this->numPixels>0){
1825        this->array = new float[spatSize];
1826        this->arrayAllocated = true;
1827        for(size_t npix=0; npix<spatSize; npix++)
1828          this->array[npix] = Array[channel*spatSize + npix];
1829      }
1830    }
1831  }
1832  //--------------------------------------------------------------------
1833
1834  void Image::extractImage(Cube &cube, size_t channel)
1835  {
1836    /// @details
1837    ///  A function to extract a 2-D image from Cube class.
1838    ///  The image extracted is the one lying in the channel referenced
1839    ///    by the second argument.
1840    ///  The extracted image is stored in the pixel array Image::array.
1841    /// \param cube The Cube containing the pixel values, from which the image is extracted.
1842    /// \param channel The spectral channel that contains the desired image.
1843
1844    size_t spatSize = cube.getDimX()*cube.getDimY();
1845    if((channel<0)||(channel>=cube.getDimZ())){
1846      DUCHAMPERROR("Image::extractImage", "Requested channel outside allowed range. Cannot save.");
1847    }
1848    else if(spatSize != this->numPixels){
1849      DUCHAMPERROR("Image::extractImage", "Input array different size to existing array. Cannot save.");
1850    }
1851    else {
1852      if(this->numPixels>0 && this->arrayAllocated) delete [] array;
1853      this->numPixels = spatSize;
1854      if(this->numPixels>0){
1855        this->array = new float[spatSize];
1856        this->arrayAllocated = true;
1857        for(size_t npix=0; npix<spatSize; npix++)
1858          this->array[npix] = cube.getPixValue(channel*spatSize + npix);
1859      }
1860    }
1861  }
1862  //--------------------------------------------------------------------
1863
1864  void Image::removeMW()
1865  {
1866    /// @details
1867    ///  A function to remove the Milky Way range of channels from a 1-D spectrum.
1868    ///  The array in this Image is assumed to be 1-D, with only the first axisDim
1869    ///    equal to 1.
1870    ///  The values of the MW channels are set to 0, unless they are BLANK.
1871
1872    if(this->par.getFlagMW() && (this->axisDim[1]==1) ){
1873      for(size_t z=0;z<this->axisDim[0];z++){
1874        if(!this->isBlank(z) && this->par.isInMW(z)) this->array[z]=0.;
1875      }
1876    }
1877  }
1878  //--------------------------------------------------------------------
1879
1880  std::vector<Object2D> Image::findSources2D()
1881  {
1882    std::vector<bool> thresholdedArray(this->axisDim[0]*this->axisDim[1]);
1883    for(size_t posY=0;posY<this->axisDim[1];posY++){
1884      for(size_t posX=0;posX<this->axisDim[0];posX++){
1885        size_t loc = posX + this->axisDim[0]*posY;
1886        thresholdedArray[loc] = this->isDetection(posX,posY);
1887      }
1888    }
1889    return lutz_detect(thresholdedArray, this->axisDim[0], this->axisDim[1], this->minSize);
1890  }
1891
1892  std::vector<Scan> Image::findSources1D()
1893  {
1894    std::vector<bool> thresholdedArray(this->axisDim[0]);
1895    for(size_t posX=0;posX<this->axisDim[0];posX++){
1896      thresholdedArray[posX] = this->isDetection(posX,0);
1897    }
1898    return spectrumDetect(thresholdedArray, this->axisDim[0], this->minSize);
1899  }
1900
1901
1902  std::vector< std::vector<PixelInfo::Voxel> > Cube::getObjVoxList()
1903  {
1904   
1905    std::vector< std::vector<PixelInfo::Voxel> > biglist;
1906   
1907    std::vector<Detection>::iterator obj;
1908    for(obj=this->objectList->begin(); obj<this->objectList->end(); obj++) {
1909
1910      Cube *subcube = new Cube;
1911      subcube->pars() = this->par;
1912      subcube->pars().setVerbosity(false);
1913      subcube->pars().setFlagSubsection(true);
1914      duchamp::Section sec = obj->getBoundingSection();
1915      subcube->pars().setSubsection( sec.getSection() );
1916      if(subcube->pars().verifySubsection() == FAILURE)
1917        DUCHAMPERROR("get object voxel list","Unable to verify the subsection - something's wrong!");
1918      if(subcube->getCube() == FAILURE)
1919        DUCHAMPERROR("get object voxel list","Unable to read the FITS file - something's wrong!");
1920      std::vector<PixelInfo::Voxel> voxlist = obj->getPixelSet();
1921      std::vector<PixelInfo::Voxel>::iterator vox;
1922      for(vox=voxlist.begin(); vox<voxlist.end(); vox++){
1923        size_t pix = (vox->getX()-subcube->pars().getXOffset()) +
1924          subcube->getDimX()*(vox->getY()-subcube->pars().getYOffset()) +
1925          subcube->getDimX()*subcube->getDimY()*(vox->getZ()-subcube->pars().getZOffset());
1926        vox->setF( subcube->getPixValue(pix) );
1927      }
1928      biglist.push_back(voxlist);
1929      delete subcube;
1930
1931    }
1932
1933    return biglist;
1934
1935  }
1936
1937}
Note: See TracBrowser for help on using the repository browser.