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

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

A large swathe of changes aimed at improving warning/error/exception handling. Now make use of macros and streams. Also, there is now a distinction between DUCHAMPERROR and DUCHAMPTHROW.

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