source: trunk/src/Cubes/cubes.cc

Last change on this file was 1450, checked in by MatthewWhiting, 4 years ago

AXA-537 - Adding a bit more care in the pointer handling, particularly for the reconFilter in the copy constructor

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