source: trunk/src/Detection/detection.cc @ 946

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

Fixing #140 - making sure the positions are in double format and we don't convert -1 in size_t to 1.e19 or thereabouts... Also improving the exception reporting.

File size: 37.4 KB
Line 
1// -----------------------------------------------------------------------
2// detection.cc : Member functions for the Detection class.
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 <iostream>
29#include <iomanip>
30#include <vector>
31#include <map>
32#include <string>
33#include <wcslib/wcs.h>
34#include <math.h>
35#include <duchamp/duchamp.hh>
36#include <duchamp/param.hh>
37#include <duchamp/fitsHeader.hh>
38#include <duchamp/Utils/utils.hh>
39#include <duchamp/PixelMap/Voxel.hh>
40#include <duchamp/PixelMap/Object3D.hh>
41#include <duchamp/Detection/detection.hh>
42#include <duchamp/Cubes/cubeUtils.hh>
43#include <duchamp/Detection/columns.hh>
44
45using namespace PixelInfo;
46
47namespace duchamp
48{
49
50  void Detection::defaultDetection()
51  {
52    this->xSubOffset = 0;
53    this->ySubOffset = 0;
54    this->zSubOffset = 0;
55    this->haveParams = false;
56    this->totalFlux = 0.;
57    this->peakFlux = 0.;
58    this->intFlux = 0.;
59    this->xpeak = 0;
60    this->ypeak = 0;
61    this->zpeak = 0;
62    this->peakSNR = 0.;
63    this->xCentroid = 0.;
64    this->yCentroid = 0.;
65    this->zCentroid = 0.;
66    this->centreType="centroid";
67    this->negSource = false;
68    this->flagText="";
69    this->id = -1;
70    this->name = "";
71    this->flagWCS=false;
72    this->specOK = true;
73    this->raS = "";
74    this->decS = "";
75    this->ra = 0.;
76    this->dec = 0.;
77    this->raWidth = 0.;
78    this->decWidth = 0.;
79    this->majorAxis = 0.;
80    this->minorAxis = 0.;
81    this->posang = 0.;
82    this->specUnits = "";
83    this->fluxUnits = "";
84    this->intFluxUnits = "";
85    this->lngtype = "RA";
86    this->lattype = "DEC";
87    this->vel = 0.;
88    this->velWidth = 0.;
89    this->velMin = 0.;
90    this->velMax = 0.;
91    this->w20 = 0.;
92    this->v20min = 0.;
93    this->v20max = 0.;
94    this->w50 = 0.;
95    this->v50min = 0.;
96    this->v50max = 0.;
97    this->posPrec = Column::prPOS;
98    this->xyzPrec = Column::prXYZ;
99    this->fintPrec = Column::prFLUX;
100    this->fpeakPrec = Column::prFLUX;
101    this->velPrec = Column::prVEL;
102    this->snrPrec = Column::prSNR;
103  }
104
105  Detection::Detection():
106    Object3D()
107  {
108    this->defaultDetection();
109  }
110
111  Detection::Detection(const Object3D& o):
112    Object3D(o)
113  {
114    this->defaultDetection();
115  }
116
117  Detection::Detection(const Detection& d):
118    Object3D(d)
119  {
120    operator=(d);
121  }
122
123  Detection& Detection::operator= (const Detection& d)
124  {
125    ((Object3D &) *this) = d;
126    this->xSubOffset   = d.xSubOffset;
127    this->ySubOffset   = d.ySubOffset;
128    this->zSubOffset   = d.zSubOffset;
129    this->haveParams   = d.haveParams;
130    this->totalFlux    = d.totalFlux;
131    this->intFlux      = d.intFlux;
132    this->peakFlux     = d.peakFlux;
133    this->xpeak        = d.xpeak;
134    this->ypeak        = d.ypeak;
135    this->zpeak        = d.zpeak;
136    this->peakSNR      = d.peakSNR;
137    this->xCentroid    = d.xCentroid;
138    this->yCentroid    = d.yCentroid;
139    this->zCentroid    = d.zCentroid;
140    this->centreType   = d.centreType;
141    this->negSource    = d.negSource;
142    this->flagText     = d.flagText;
143    this->id           = d.id;
144    this->name         = d.name;
145    this->flagWCS      = d.flagWCS;
146    this->specOK       = d.specOK;
147    this->raS          = d.raS;
148    this->decS         = d.decS;
149    this->ra           = d.ra;
150    this->dec          = d.dec;
151    this->raWidth      = d.raWidth;
152    this->decWidth     = d.decWidth;
153    this->majorAxis    = d.majorAxis;
154    this->minorAxis    = d.minorAxis;
155    this->posang       = d.posang;
156    this->specUnits    = d.specUnits;
157    this->fluxUnits    = d.fluxUnits;
158    this->intFluxUnits = d.intFluxUnits;
159    this->lngtype      = d.lngtype;
160    this->lattype      = d.lattype;
161    this->vel          = d.vel;
162    this->velWidth     = d.velWidth;
163    this->velMin       = d.velMin;
164    this->velMax       = d.velMax;
165    this->w20          = d.w20;
166    this->v20min       = d.v20min;
167    this->v20max       = d.v20max;
168    this->w50          = d.w50;
169    this->v50min       = d.v50min;
170    this->v50max       = d.v50max;
171    this->posPrec      = d.posPrec;
172    this->xyzPrec      = d.xyzPrec;
173    this->fintPrec     = d.fintPrec;
174    this->fpeakPrec    = d.fpeakPrec;
175    this->velPrec      = d.velPrec;
176    this->snrPrec      = d.snrPrec;
177    return *this;
178  }
179
180  //--------------------------------------------------------------------
181  float Detection::getXcentre()
182  {
183    if(this->centreType=="peak") return this->xpeak;
184    else if(this->centreType=="average") return this->getXaverage();
185    else return this->xCentroid;
186  }
187
188  float Detection::getYcentre()
189  {
190    if(this->centreType=="peak") return this->ypeak;
191    else if(this->centreType=="average") return this->getYaverage();
192    else return this->yCentroid;
193  }
194
195  float Detection::getZcentre()
196  {
197    if(this->centreType=="peak") return this->zpeak;
198    else if(this->centreType=="average") return this->getZaverage();
199    else return this->zCentroid;
200  }
201
202  //--------------------------------------------------------------------
203
204  bool Detection::voxelListsMatch(std::vector<Voxel> voxelList)
205  {
206    /// @details
207    ///  A test to see whether there is a 1-1 correspondence between
208    ///  the given list of Voxels and the voxel positions contained in
209    ///  this Detection's pixel list. No testing of the fluxes of the
210    ///  Voxels is done.
211    ///
212    /// \param voxelList The std::vector list of Voxels to be tested.
213
214    bool listsMatch = true;
215    // compare sizes
216    listsMatch = listsMatch && (voxelList.size() == this->getSize());
217    if(!listsMatch) return listsMatch;
218
219    // make sure all Detection pixels are in voxel list
220    listsMatch = listsMatch && this->voxelListCovered(voxelList);
221
222    // make sure all voxels are in Detection
223    std::vector<Voxel>::iterator vox;
224    for(vox=voxelList.begin();vox<voxelList.end();vox++)
225      listsMatch = listsMatch && this->isInObject(*vox);
226
227    return listsMatch;
228
229  }
230  //--------------------------------------------------------------------
231
232  bool Detection::voxelListCovered(std::vector<Voxel> voxelList)
233  {
234    ///  @details
235    ///  A test to see whether the given list of Voxels contains each
236    ///  position in this Detection's pixel list. It does not look for
237    ///  a 1-1 correspondence: the given list can be a super-set of the
238    ///  Detection. No testing of the fluxes of the Voxels is done.
239    ///
240    /// \param voxelList The std::vector list of Voxels to be tested.
241
242    bool listsMatch = true;
243
244    // make sure all Detection pixels are in voxel list
245    size_t v1=0;
246    std::vector<Voxel> detpixlist = this->getPixelSet();
247    while(listsMatch && v1<detpixlist.size()){
248      bool inList = false;
249      size_t v2=0;
250      while(!inList && v2<voxelList.size()){
251        inList = inList || detpixlist[v1].match(voxelList[v2]);
252        v2++;
253      }
254      listsMatch = listsMatch && inList;
255      v1++;
256    }
257
258    return listsMatch;
259
260  }
261  //--------------------------------------------------------------------
262
263  void Detection::calcFluxes(std::vector<Voxel> voxelList)
264  {
265    ///  @details
266    ///  A function that calculates total & peak fluxes (and the location
267    ///  of the peak flux) for a Detection.
268    ///
269    ///  \param fluxArray The array of flux values to calculate the
270    ///  flux parameters from.
271    ///  \param dim The dimensions of the flux array.
272   
273    //    this->haveParams = true;
274
275    this->totalFlux = this->peakFlux = 0;
276    this->xCentroid = this->yCentroid = this->zCentroid = 0.;
277
278    // first check that the voxel list and the Detection's pixel list
279    // have a 1-1 correspondence
280
281    if(!this->voxelListCovered(voxelList)){
282      DUCHAMPERROR("Detection::calcFluxes","Voxel list provided does not match");
283      return;
284    }
285
286    std::vector<Voxel>::iterator vox;
287    for(vox=voxelList.begin();vox<voxelList.end();vox++){
288      if(this->isInObject(*vox)){
289        long x = vox->getX();
290        long y = vox->getY();
291        long z = vox->getZ();
292        float f = vox->getF();
293        this->totalFlux += f;
294        this->xCentroid += x*f;
295        this->yCentroid += y*f;
296        this->zCentroid += z*f;
297        if( (vox==voxelList.begin()) ||  //first time round
298            (this->negSource&&(f<this->peakFlux)) ||
299            (!this->negSource&&(f>this->peakFlux))   )
300          {
301            this->peakFlux = f;
302            this->xpeak =    x;
303            this->ypeak =    y;
304            this->zpeak =    z;
305          }
306      }
307    }
308
309    this->xCentroid /= this->totalFlux;
310    this->yCentroid /= this->totalFlux;
311    this->zCentroid /= this->totalFlux;
312  }
313  //--------------------------------------------------------------------
314
315  void Detection::calcFluxes(std::map<Voxel,float> &voxelMap)
316  {
317    ///  @details
318    ///  A function that calculates total & peak fluxes (and the location
319    ///  of the peak flux) for a Detection.
320    ///
321    ///  \param fluxArray The array of flux values to calculate the
322    ///  flux parameters from.
323    ///  \param dim The dimensions of the flux array.
324   
325    //    this->haveParams = true;
326
327    this->totalFlux = this->peakFlux = 0;
328    this->xCentroid = this->yCentroid = this->zCentroid = 0.;
329
330    std::vector<Voxel> voxelList = this->getPixelSet();
331    std::vector<Voxel>::iterator vox;
332    for(vox=voxelList.begin();vox<voxelList.end();vox++){
333      if(voxelMap.find(*vox) == voxelMap.end()){
334        DUCHAMPERROR("Detection::calcFluxes","Voxel list provided does not match");
335        return;
336      }
337      else {
338        long x = vox->getX();
339        long y = vox->getY();
340        long z = vox->getZ();
341        float f = voxelMap[*vox];
342        this->totalFlux += f;
343        this->xCentroid += x*f;
344        this->yCentroid += y*f;
345        this->zCentroid += z*f;
346        if( (vox==voxelList.begin()) ||  //first time round
347            (this->negSource&&(f<this->peakFlux)) ||
348            (!this->negSource&&(f>this->peakFlux))   )
349          {
350            this->peakFlux = f;
351            this->xpeak =    x;
352            this->ypeak =    y;
353            this->zpeak =    z;
354          }
355      }
356    }
357
358    this->xCentroid /= this->totalFlux;
359    this->yCentroid /= this->totalFlux;
360    this->zCentroid /= this->totalFlux;
361  }
362  //--------------------------------------------------------------------
363
364  void Detection::calcFluxes(float *fluxArray, size_t *dim)
365  {
366    ///  @details
367    ///  A function that calculates total & peak fluxes (and the location
368    ///  of the peak flux) for a Detection.
369    ///
370    ///  \param fluxArray The array of flux values to calculate the
371    ///  flux parameters from.
372    ///  \param dim The dimensions of the flux array.
373
374    //    this->haveParams = true;
375
376    this->totalFlux = this->peakFlux = 0;
377    this->xCentroid = this->yCentroid = this->zCentroid = 0.;
378
379    std::vector<Voxel> voxList = this->getPixelSet();
380    std::vector<Voxel>::iterator vox=voxList.begin();
381    for(;vox<voxList.end();vox++){
382
383      long x=vox->getX();
384      long y=vox->getY();
385      long z=vox->getZ();
386      size_t ind = vox->arrayIndex(dim);
387      float f = fluxArray[ind];
388      this->totalFlux += f;
389      this->xCentroid += x*f;
390      this->yCentroid += y*f;
391      this->zCentroid += z*f;
392      if( (vox==voxList.begin()) ||
393          (this->negSource&&(f<this->peakFlux)) ||
394          (!this->negSource&&(f>this->peakFlux))   )
395        {
396          this->peakFlux = f;
397          this->xpeak = x;
398          this->ypeak = y;
399          this->zpeak = z;
400        }
401 
402    }
403
404    this->xCentroid /= this->totalFlux;
405    this->yCentroid /= this->totalFlux;
406    this->zCentroid /= this->totalFlux;
407  }
408  //--------------------------------------------------------------------
409
410  void Detection::calcWCSparams(FitsHeader &head)
411  {
412    ///  @details
413    ///  Use the input wcs to calculate the position and velocity
414    ///    information for the Detection.
415    ///  Quantities calculated:
416    ///  <ul><li> RA: ra [deg], ra (string), ra width.
417    ///      <li> Dec: dec [deg], dec (string), dec width.
418    ///      <li> Vel: vel [km/s], min & max vel, vel width.
419    ///      <li> coord type for all three axes, nuRest,
420    ///      <li> name (IAU-style, in equatorial or Galactic)
421    ///  </ul>
422    ///
423    ///  Note that the regular parameters are NOT recalculated!
424    ///
425    ///  \param head FitsHeader object that contains the WCS information.
426
427    if(head.isWCS()){
428
429      double *pixcrd = new double[15];
430      double *world  = new double[15];
431      /*
432        define a five-point array in 3D:
433        (x,y,z), (x,y,z1), (x,y,z2), (x1,y1,z), (x2,y2,z)
434        [note: x = central point, x1 = minimum x, x2 = maximum x etc.]
435        and convert to world coordinates.   
436      */
437      pixcrd[0]  = pixcrd[3] = pixcrd[6] = this->getXcentre();
438      pixcrd[9]  = this->getXmin()-0.5;
439      pixcrd[12] = this->getXmax()+0.5;
440      pixcrd[1]  = pixcrd[4] = pixcrd[7] = this->getYcentre();
441      pixcrd[10] = this->getYmin()-0.5;
442      pixcrd[13] = this->getYmax()+0.5;
443      pixcrd[2] = pixcrd[11] = pixcrd[14] = this->getZcentre();
444      pixcrd[5] = this->getZmin();
445      pixcrd[8] = this->getZmax();
446      int flag = head.pixToWCS(pixcrd, world, 5);
447      delete [] pixcrd;
448      if(flag!=0) {
449        DUCHAMPERROR("calcWCSparams", "Error in calculating the WCS for this object.");
450      }
451      else{
452       
453        // world now has the WCS coords for the five points
454        //    -- use this to work out WCS params
455 
456        this->haveParams = true;
457
458        this->specOK = head.canUseThirdAxis();
459        this->lngtype = head.WCS().lngtyp;
460        this->lattype = head.WCS().lattyp;
461        this->specUnits = head.getSpectralUnits();
462        this->fluxUnits = head.getFluxUnits();
463        // if fluxUnits are eg. Jy/beam, make intFluxUnits = Jy km/s
464        this->intFluxUnits = head.getIntFluxUnits();
465        this->ra   = world[0];
466        this->dec  = world[1];
467        int precision = -int(log10(fabs(head.WCS().cdelt[head.WCS().lng]*3600./10.)));
468        this->raS  = decToDMS(this->ra, this->lngtype,precision);
469        this->decS = decToDMS(this->dec,this->lattype,precision);
470        this->raWidth = angularSeparation(world[9],world[1],
471                                          world[12],world[1]) * 60.;
472        this->decWidth  = angularSeparation(world[0],world[10],
473                                            world[0],world[13]) * 60.;
474
475        Object2D spatMap = this->getSpatialMap();
476        std::pair<double,double> axes = spatMap.getPrincipleAxes();
477        this->majorAxis = std::max(axes.first,axes.second) * head.getAvPixScale();
478        this->minorAxis = std::min(axes.first,axes.second) * head.getAvPixScale();
479        this->posang = spatMap.getPositionAngle() * 180. / M_PI;
480
481        this->name = head.getIAUName(this->ra, this->dec);
482        this->vel    = head.specToVel(world[2]);
483        this->velMin = head.specToVel(world[5]);
484        this->velMax = head.specToVel(world[8]);
485        this->velWidth = fabs(this->velMax - this->velMin);
486
487        this->flagWCS = true;
488      }
489      delete [] world;
490
491    }
492  }
493  //--------------------------------------------------------------------
494
495  void Detection::calcIntegFlux(size_t zdim, std::vector<Voxel> voxelList, FitsHeader &head)
496  {
497    ///  @details
498    ///  Uses the input WCS to calculate the velocity-integrated flux,
499    ///   putting velocity in units of km/s.
500    ///  The fluxes used are taken from the Voxels, rather than an
501    ///   array of flux values.
502    ///  Integrates over full spatial and velocity range as given
503    ///   by the extrema calculated by calcWCSparams.
504    ///
505    ///  If the flux units end in "/beam" (eg. Jy/beam), then the flux is
506    ///  corrected by the beam size (in pixels). This is done by
507    ///  multiplying the integrated flux by the number of spatial pixels,
508    ///  and dividing by the beam size in pixels (e.g. Jy/beam * pix /
509    ///  pix/beam --> Jy)
510    ///
511    ///  \param zdim The size of the spectral axis (needed to find the velocity widths)
512    ///  \param voxelList The list of Voxels with flux information
513    ///  \param head FitsHeader object that contains the WCS information.
514
515    const double border = 1.;
516
517    if(!this->voxelListCovered(voxelList)){
518      DUCHAMPERROR("Detection::calcIntegFlux","Voxel list provided does not match");
519      return;
520    }
521
522    if(!head.is2D()){
523
524      this->haveParams = true;
525
526      // include one pixel either side in each direction
527      size_t xsize = (this->getXmax()-this->getXmin()+border*2+1);
528      size_t ysize = (this->getYmax()-this->getYmin()+border*2+1);
529      size_t zsize = (this->getZmax()-this->getZmin()+border*2+1);
530      size_t spatsize=xsize*ysize;
531      size_t size = xsize*ysize*zsize;
532      std::vector <bool> isObj(size,false);
533      double *localFlux = new double[size];
534      for(size_t i=0;i<size;i++) localFlux[i]=0.;
535
536      std::vector<Voxel>::iterator vox;
537      for(vox=voxelList.begin();vox<voxelList.end();vox++){
538        if(this->isInObject(*vox)){
539          long x = vox->getX();
540          long y = vox->getY();
541          long z = vox->getZ();
542          size_t pos = (x-this->getXmin()+border) + (y-this->getYmin()+border)*xsize
543            + (z-this->getZmin()+border)*xsize*ysize;
544          localFlux[pos] = vox->getF();
545          isObj[pos] = true;
546        }
547      }
548 
549      // work out the WCS coords for each pixel
550      double *world  = new double[size];
551      double xpt,ypt,zpt;
552      for(size_t i=0;i<size;i++){
553        xpt = double( this->getXmin() - border + i%xsize );
554        ypt = double( this->getYmin() - border + (i/xsize)%ysize );
555        zpt = double( this->getZmin() - border + i/(xsize*ysize) );
556        world[i] = head.pixToVel(xpt,ypt,zpt);
557      }
558
559      double integrated = 0.;
560      for(size_t pix=0; pix<spatsize; pix++){ // loop over each spatial pixel.
561        for(size_t z=0; z<zsize; z++){
562          size_t pos =  z*xsize*ysize + pix;
563          if(isObj[pos]){ // if it's an object pixel...
564            double deltaVel;
565            if(z==0)
566              deltaVel = (world[pos+xsize*ysize] - world[pos]);
567            else if(z==(zsize-1))
568              deltaVel = (world[pos] - world[pos-xsize*ysize]);
569            else
570              deltaVel = (world[pos+xsize*ysize] - world[pos-xsize*ysize]) / 2.;
571            integrated += localFlux[pos] * fabs(deltaVel);
572          }
573        }
574      }
575      this->intFlux = integrated;
576
577      delete [] world;
578      delete [] localFlux;
579
580      calcVelWidths(zdim,voxelList,head);
581
582    }
583    else // in this case there is just a 2D image.
584      this->intFlux = this->totalFlux;
585
586    if(head.isWCS()){
587      // correct for the beam size if the flux units string ends in "/beam"
588      if(head.needBeamSize()) this->intFlux  /= head.beam().area();
589    }
590
591  }
592  //--------------------------------------------------------------------
593
594  void Detection::calcIntegFlux(size_t zdim, std::map<Voxel,float> voxelMap, FitsHeader &head)
595  {
596    ///  @details
597    ///  Uses the input WCS to calculate the velocity-integrated flux,
598    ///   putting velocity in units of km/s.
599    ///  The fluxes used are taken from the Voxels, rather than an
600    ///   array of flux values.
601    ///  Integrates over full spatial and velocity range as given
602    ///   by the extrema calculated by calcWCSparams.
603    ///
604    ///  If the flux units end in "/beam" (eg. Jy/beam), then the flux is
605    ///  corrected by the beam size (in pixels). This is done by
606    ///  multiplying the integrated flux by the number of spatial pixels,
607    ///  and dividing by the beam size in pixels (e.g. Jy/beam * pix /
608    ///  pix/beam --> Jy)
609    ///
610    ///  \param zdim The size of the spectral axis (needed to find the velocity widths)
611    ///  \param voxelList The list of Voxels with flux information
612    ///  \param head FitsHeader object that contains the WCS information.
613
614    const double border = 1.;
615
616    if(!head.is2D()){
617
618      this->haveParams = true;
619
620      // include one pixel either side in each direction
621      size_t xsize = (this->getXmax()-this->getXmin()+border*2+1);
622      size_t ysize = (this->getYmax()-this->getYmin()+border*2+1);
623      size_t zsize = (this->getZmax()-this->getZmin()+border*2+1);
624      size_t spatsize=xsize*ysize;
625      size_t size = xsize*ysize*zsize;
626      std::vector <bool> isObj(size,false);
627      double *localFlux = new double[size];
628      for(size_t i=0;i<size;i++) localFlux[i]=0.;
629
630      std::vector<Voxel> voxelList = this->getPixelSet();
631      std::vector<Voxel>::iterator vox;
632      for(vox=voxelList.begin();vox<voxelList.end();vox++){
633        if(voxelMap.find(*vox) == voxelMap.end()){
634          DUCHAMPERROR("Detection::calcIntegFlux","Voxel list provided does not match");
635          return;
636        }       
637        else {
638          long x = vox->getX();
639          long y = vox->getY();
640          long z = vox->getZ();
641          size_t pos = (x-this->getXmin()+border) + (y-this->getYmin()+border)*xsize
642            + (z-this->getZmin()+border)*xsize*ysize;
643          localFlux[pos] = voxelMap[*vox];
644          isObj[pos] = true;
645        }
646      }
647 
648      // work out the WCS coords for each pixel
649      double *world  = new double[size];
650      double xpt,ypt,zpt;
651      for(size_t i=0;i<xsize*ysize*zsize;i++){
652        xpt = double( this->getXmin() - border + i%xsize );
653        ypt = double( this->getYmin() - border + (i/xsize)%ysize );
654        zpt = double( this->getZmin() - border + i/(xsize*ysize) );
655        world[i] = head.pixToVel(xpt,ypt,zpt);
656      }
657
658      double integrated = 0.;
659      for(size_t pix=0; pix<spatsize; pix++){ // loop over each spatial pixel.
660        for(size_t z=0; z<zsize; z++){
661          size_t pos =  z*xsize*ysize + pix;
662          if(isObj[pos]){ // if it's an object pixel...
663            double deltaVel;
664            if(z==0)
665              deltaVel = (world[pos+xsize*ysize] - world[pos]);
666            else if(z==(zsize-1))
667              deltaVel = (world[pos] - world[pos-xsize*ysize]);
668            else
669              deltaVel = (world[pos+xsize*ysize] - world[pos-xsize*ysize]) / 2.;
670            integrated += localFlux[pos] * fabs(deltaVel);
671          }
672        }
673      }
674      this->intFlux = integrated;
675
676      delete [] world;
677      delete [] localFlux;
678
679      calcVelWidths(zdim,voxelMap,head);
680
681    }
682    else // in this case there is just a 2D image.
683      this->intFlux = this->totalFlux;
684
685    if(head.isWCS()){
686      // correct for the beam size if the flux units string ends in "/beam"
687      if(head.needBeamSize()) this->intFlux  /= head.beam().area();
688    }
689
690  }
691  //--------------------------------------------------------------------
692
693  void Detection::calcIntegFlux(float *fluxArray, size_t *dim, FitsHeader &head)
694  {
695    ///  @details
696    ///  Uses the input WCS to calculate the velocity-integrated flux,
697    ///   putting velocity in units of km/s.
698    ///  Integrates over full spatial and velocity range as given
699    ///   by the extrema calculated by calcWCSparams.
700    ///
701    ///  If the flux units end in "/beam" (eg. Jy/beam), then the flux is
702    ///  corrected by the beam size (in pixels). This is done by
703    ///  multiplying the integrated flux by the number of spatial pixels,
704    ///  and dividing by the beam size in pixels (e.g. Jy/beam * pix /
705    ///  pix/beam --> Jy)
706    ///
707    ///  \param fluxArray The array of flux values.
708    ///  \param dim The dimensions of the flux array.
709    ///  \param head FitsHeader object that contains the WCS information.
710
711    if(!head.is2D()){
712
713      this->haveParams = true;
714
715      // include one pixel either side in each direction
716      size_t xsize = (this->xmax-this->xmin+3);
717      size_t ysize = (this->ymax-this->ymin+3);
718      size_t zsize = (this->zmax-this->zmin+3);
719      size_t spatsize = xsize*ysize;
720      size_t size = xsize*ysize*zsize;
721      std::vector <bool> isObj(size,false);
722      double *localFlux = new double[size];
723      for(size_t i=0;i<size;i++) localFlux[i]=0.;
724      // work out which pixels are object pixels
725      std::vector<Voxel> voxlist = this->getPixelSet();
726      for(std::vector<Voxel>::iterator v=voxlist.begin();v<voxlist.end();v++){
727        size_t pos=(v->getX()-this->xmin+1) + (v->getY()-this->ymin+1)*xsize
728          + (v->getZ()-this->zmin+1)*spatsize;
729        localFlux[pos] = fluxArray[v->arrayIndex(dim)];
730        isObj[pos] = true;
731      }
732 
733      // work out the WCS coords for each pixel
734      double *world  = new double[size];
735      double xpt,ypt,zpt;
736      size_t i=0;
737      for(size_t z=0;z<zsize;z++){
738        for(size_t y=0;y<ysize;y++){
739          for(size_t x=0;x<xsize;x++){
740            xpt=double(this->xmin - 1. + x);
741            ypt=double(this->ymin - 1. + y);
742            zpt=double(this->zmin - 1. + z);
743            world[i++] = head.pixToVel(xpt,ypt,zpt);
744          }
745        }
746      }
747
748      double integrated = 0.;
749      for(size_t pix=0; pix<xsize*ysize; pix++){ // loop over each spatial pixel.
750        for(size_t z=0; z<zsize; z++){
751          size_t pos =  z*xsize*ysize + pix;
752          if(isObj[pos]){ // if it's an object pixel...
753            double deltaVel;
754            if(z==0)
755              deltaVel = (world[pos+xsize*ysize] - world[pos]);
756            else if(z==(zsize-1))
757              deltaVel = (world[pos] - world[pos-xsize*ysize]);
758            else
759              deltaVel = (world[pos+xsize*ysize] - world[pos-xsize*ysize]) / 2.;
760            integrated += localFlux[pos] * fabs(deltaVel);
761          }
762        }
763      }
764      this->intFlux = integrated;
765
766      delete [] world;
767      delete [] localFlux;
768
769      calcVelWidths(fluxArray, dim, head);
770
771    }
772    else // in this case there is just a 2D image.
773      this->intFlux = this->totalFlux;
774
775    if(head.isWCS()){
776      // correct for the beam size if the flux units string ends in "/beam" and we have beam info
777      if(head.needBeamSize()) this->intFlux  /= head.beam().area();
778    }
779
780  }
781  //--------------------------------------------------------------------
782
783  void Detection::calcVelWidths(size_t zdim, std::vector<Voxel> voxelList, FitsHeader &head)
784  {
785    ///  @details
786    /// Calculates the widths of the detection at 20% and 50% of the
787    /// peak integrated flux. The procedure is as follows: first
788    /// generate an integrated flux spectrum (using all given voxels
789    /// that lie in the object's spatial map); find the peak; starting
790    /// at the spectral edges of the detection, move in or out until
791    /// you reach the 20% or 50% peak flux level. Linear interpolation
792    /// between points is done.
793    ///
794    ///  \param zdim The size of the spectral axis in the cube
795    ///  \param voxelList The list of Voxels with flux information
796    ///  \param head FitsHeader object that contains the WCS information.
797
798    float *intSpec = new float[zdim];
799    for(size_t i=0;i<zdim;i++) intSpec[i]=0;
800       
801    Object2D spatMap = this->getSpatialMap();
802    for(int s=0;s<spatMap.getNumScan();s++){
803      std::vector<Voxel>::iterator vox;
804      for(vox=voxelList.begin();vox<voxelList.end();vox++){
805        if(spatMap.isInObject(*vox)){
806          intSpec[vox->getZ()] += vox->getF();
807        }
808      }
809    }
810   
811    calcVelWidths(zdim, intSpec, head);
812
813    delete [] intSpec;
814
815  }
816
817  //--------------------------------------------------------------------
818
819  void Detection::calcVelWidths(size_t zdim, std::map<Voxel,float> voxelMap, FitsHeader &head)
820  {
821    ///  @details
822    /// Calculates the widths of the detection at 20% and 50% of the
823    /// peak integrated flux. The procedure is as follows: first
824    /// generate an integrated flux spectrum (using all given voxels
825    /// that lie in the object's spatial map); find the peak; starting
826    /// at the spectral edges of the detection, move in or out until
827    /// you reach the 20% or 50% peak flux level. Linear interpolation
828    /// between points is done.
829    ///
830    ///  \param zdim The size of the spectral axis in the cube
831    ///  \param voxelList The list of Voxels with flux information
832    ///  \param head FitsHeader object that contains the WCS information.
833
834    float *intSpec = new float[zdim];
835    for(size_t i=0;i<zdim;i++) intSpec[i]=0;
836       
837    std::vector<Voxel> voxelList = this->getPixelSet();
838    std::vector<Voxel>::iterator vox;
839    for(vox=voxelList.begin();vox<voxelList.end();vox++){
840      if(voxelMap.find(*vox) == voxelMap.end()){
841        DUCHAMPERROR("Detection::calcVelWidths","Voxel list provided does not match");
842        return;
843      }
844      else {
845        intSpec[vox->getZ()] += voxelMap[*vox];
846      }
847    }
848
849    calcVelWidths(zdim, intSpec, head);
850
851    delete [] intSpec;
852
853  }
854
855  //--------------------------------------------------------------------
856
857  void Detection::calcVelWidths(size_t zdim, float *intSpec, FitsHeader &head)
858  {
859
860    // finding the 20% & 50% points.  Start at the velmin & velmax
861    //  points. Then, if the int flux there is above the 20%/50%
862    //  limit, go out, otherwise go in. This is to deal with the
863    //  problems from double- (or multi-) peaked sources.
864
865    this->haveParams = true;
866
867    double zpt,xpt=double(this->getXcentre()),ypt=double(this->getYcentre());
868    bool goLeft;
869   
870    float peak=0.;
871    size_t peakLoc=0;
872    for(size_t z=this->getZmin();z<=size_t(this->getZmax());z++) {
873      if(z==0 || peak<intSpec[z]){
874        peak = intSpec[z];
875        peakLoc = z;
876      }
877    }
878   
879    size_t z=this->getZmin();
880    goLeft = intSpec[z]>peak*0.5;
881    if(goLeft) while(z>0 && intSpec[z]>peak*0.5) z--;
882    else       while(z<peakLoc && intSpec[z]<peak*0.5) z++;
883    if(z==0) this->v50min = this->velMin;
884    else{
885      if(goLeft) zpt = z + (peak*0.5-intSpec[z])/(intSpec[z+1]-intSpec[z]);
886      else       zpt = z - (peak*0.5-intSpec[z])/(intSpec[z-1]-intSpec[z]);
887      this->v50min = head.pixToVel(xpt,ypt,zpt);
888    }
889    z=this->getZmax();
890    goLeft = intSpec[z]<peak*0.5;
891    if(goLeft) while(z>peakLoc && intSpec[z]<peak*0.5) z--;
892    else       while(z<zdim    && intSpec[z]>peak*0.5) z++;
893    if(z==zdim) this->v50max = this->velMax;
894    else{
895      if(goLeft) zpt = z + (peak*0.5-intSpec[z])/(intSpec[z+1]-intSpec[z]);
896      else       zpt = z - (peak*0.5-intSpec[z])/(intSpec[z-1]-intSpec[z]);
897      this->v50max = head.pixToVel(xpt,ypt,zpt);
898    }
899    z=this->getZmin();
900    goLeft = intSpec[z]>peak*0.2;
901    if(goLeft) while(z>0 && intSpec[z]>peak*0.2) z--;
902    else       while(z<peakLoc && intSpec[z]<peak*0.2) z++;
903    if(z==0) this->v20min = this->velMin;
904    else{
905      if(goLeft) zpt = z + (peak*0.2-intSpec[z])/(intSpec[z+1]-intSpec[z]);
906      else       zpt = z - (peak*0.2-intSpec[z])/(intSpec[z-1]-intSpec[z]);
907      this->v20min = head.pixToVel(xpt,ypt,zpt);
908    }
909    z=this->getZmax();
910    goLeft = intSpec[z]<peak*0.2;
911    if(goLeft) while(z>peakLoc && intSpec[z]<peak*0.2) z--;
912    else       while(z<zdim    && intSpec[z]>peak*0.2) z++;
913    if(z==zdim) this->v20max = this->velMax;
914    else{
915      if(goLeft) zpt = z + (peak*0.2-intSpec[z])/(intSpec[z+1]-intSpec[z]);
916      else       zpt = z - (peak*0.2-intSpec[z])/(intSpec[z-1]-intSpec[z]);
917      this->v20max = head.pixToVel(xpt,ypt,zpt);
918    }
919
920    this->w20 = fabs(this->v20min - this->v20max);
921    this->w50 = fabs(this->v50min - this->v50max);
922
923
924  }
925  //--------------------------------------------------------------------
926
927  void Detection::calcVelWidths(float *fluxArray, size_t *dim, FitsHeader &head)
928  {
929    ///  @details
930    /// Calculates the widths of the detection at 20% and 50% of the
931    /// peak integrated flux. The procedure is as follows: first
932    /// generate an integrated flux spectrum (summing each spatial
933    /// pixel's spectrum); find the peak; starting at the spectral
934    /// edges of the detection, move in or out until you reach the 20%
935    /// or 50% peak flux level. Linear interpolation between points is
936    /// done.
937    ///
938    ///  \param fluxArray The array of flux values.
939    ///  \param dim The dimensions of the flux array.
940    ///  \param head FitsHeader object that contains the WCS information.
941
942    if(dim[2] > 2){
943
944      float *intSpec = new float[dim[2]];
945      size_t size=dim[0]*dim[1]*dim[2];
946      std::vector<bool> mask(size,true);
947      getIntSpec(*this,fluxArray,dim,mask,1.,intSpec);
948
949      this->calcVelWidths(dim[2],intSpec,head);
950
951      delete [] intSpec;
952
953    }
954    else{
955      this->v50min = this->v20min = this->velMin;
956      this->v50max = this->v20max = this->velMax;
957      this->w20 = fabs(this->v20min - this->v20max);
958      this->w50 = fabs(this->v50min - this->v50max);
959    }
960
961  }
962  //--------------------------------------------------------------------
963
964  void Detection::setOffsets(Param &par)
965  {
966    ///  @details
967    /// This function stores the values of the offsets for each cube axis.
968    /// The offsets are the starting values of the cube axes that may differ from
969    ///  the default value of 0 (for instance, if a subsection is being used).
970    /// The values will be used when the detection is outputted.
971
972    this->xSubOffset = par.getXOffset();
973    this->ySubOffset = par.getYOffset();
974    this->zSubOffset = par.getZOffset();
975  }
976  //--------------------------------------------------------------------
977
978  bool Detection::hasEnoughChannels(int minNumber)
979  {
980    ///  @details
981    /// A function to determine if the Detection has enough
982    /// contiguous channels to meet the minimum requirement
983    /// given as the argument.
984    /// \param minNumber How many channels is the minimum acceptable number?
985    /// \return True if there is at least one occurence of minNumber consecutive
986    /// channels present to return true. False otherwise.
987
988    // Preferred method -- need a set of minNumber consecutive channels present.
989
990    int numChan = this->getMaxAdjacentChannels();
991    bool result = (numChan >= minNumber);
992
993    return result;
994 
995  }
996  //--------------------------------------------------------------------
997
998  std::vector<int> Detection::getVertexSet()
999  {
1000    ///  @details
1001    /// Gets a list of points being the end-points of 1-pixel long
1002    /// segments drawing a border around the spatial extend of a
1003    /// detection. The vector is a series of 4 integers, being: x_0,
1004    /// y_0, x_1, y_1.
1005    /// \return The vector of vertex positions.
1006
1007    std::vector<int> vertexSet;
1008
1009    int xmin = this->getXmin() - 1;
1010    int xmax = this->getXmax() + 1;
1011    int ymin = this->getYmin() - 1;
1012    int ymax = this->getYmax() + 1;
1013    int xsize = xmax - xmin + 1;
1014    int ysize = ymax - ymin + 1;
1015
1016    std::vector<Voxel> voxlist = this->getPixelSet();
1017    std::vector<bool> isObj(xsize*ysize,false);
1018    std::vector<Voxel>::iterator vox;
1019    for(vox=voxlist.begin();vox<voxlist.end();vox++){
1020      size_t pos = (vox->getX()-xmin) +
1021        (vox->getY()-ymin)*xsize;
1022      isObj[pos] = true;
1023    }
1024    voxlist.clear();
1025   
1026    for(int x=xmin; x<=xmax; x++){
1027      // for each column...
1028      for(int y=ymin+1;y<=ymax;y++){
1029        int current  = (y-ymin)*xsize + x-xmin;
1030        int previous = (y-ymin-1)*xsize + x-xmin;
1031        if((isObj[current]&&!isObj[previous])   ||
1032           (!isObj[current]&&isObj[previous])){
1033          vertexSet.push_back(x);
1034          vertexSet.push_back(y);
1035          vertexSet.push_back(x+1);
1036          vertexSet.push_back(y);
1037        }
1038      }
1039    }
1040    for(int y=ymin; y<=ymax; y++){
1041      // now for each row...
1042      for(int x=xmin+1;x<=xmax;x++){
1043        int current  = (y-ymin)*xsize + x-xmin;
1044        int previous = (y-ymin)*xsize + x-xmin - 1;
1045        if((isObj[current]&&!isObj[previous])   ||
1046           (!isObj[current]&&isObj[previous])){
1047          vertexSet.push_back(x);
1048          vertexSet.push_back(y);
1049          vertexSet.push_back(x);
1050          vertexSet.push_back(y+1);
1051        }
1052      }
1053    }
1054
1055    return vertexSet;
1056 
1057  }
1058
1059 
1060  void Detection::addDetection(Detection &other)
1061  {
1062    for(std::map<long, Object2D>::iterator it = other.chanlist.begin(); it!=other.chanlist.end();it++)
1063      //      this->addChannel(*it);
1064      this->addChannel(it->first, it->second);
1065    this->haveParams = false; // make it appear as if the parameters haven't been calculated, so that we can re-calculate them 
1066  }
1067
1068  Detection operator+ (Detection &lhs, Detection &rhs)
1069  {
1070    Detection output = lhs;
1071    for(std::map<long, Object2D>::iterator it = rhs.chanlist.begin(); it!=rhs.chanlist.end();it++)
1072      output.addChannel(it->first, it->second);
1073    output.haveParams = false; // make it appear as if the parameters haven't been calculated, so that we can re-calculate them
1074    return output;
1075  }
1076   
1077
1078  bool Detection::canMerge(Detection &other, Param &par)
1079  {
1080    bool near = this->isNear(other,par);
1081    if(near) return this->isClose(other,par);
1082    else return near;
1083  }
1084
1085  bool Detection::isNear(Detection &other, Param &par)
1086  {
1087
1088    bool flagAdj = par.getFlagAdjacent();
1089    float threshS = par.getThreshS();
1090    float threshV = par.getThreshV();
1091
1092    long gap;
1093    if(flagAdj) gap = 1;
1094    else gap = long( ceil(threshS) );
1095
1096    bool areNear;
1097    // Test X ranges
1098    if((this->xmin-gap)<other.xmin) areNear=((this->xmax+gap)>=other.xmin);
1099    else areNear=(other.xmax>=(this->xmin-gap));
1100    // Test Y ranges
1101    if(areNear){
1102      if((this->ymin-gap)<other.ymin) areNear=areNear&&((this->ymax+gap)>=other.ymin);
1103      else areNear=areNear&&(other.ymax>=(this->ymin-gap));
1104    }
1105    // Test Z ranges
1106    if(areNear){
1107      gap = long(ceil(threshV));
1108      if((this->zmin-gap)<other.zmin) areNear=areNear&&((this->zmax+gap)>=other.zmin);
1109      else areNear=areNear&&(other.zmax>=(this->zmin-gap));
1110    }
1111   
1112    return areNear;
1113
1114  }
1115
1116  bool Detection::isClose(Detection &other, Param &par)
1117  {
1118    bool close = false;   // this will be the value returned
1119   
1120    bool flagAdj = par.getFlagAdjacent();
1121    float threshS = par.getThreshS();
1122    float threshV = par.getThreshV();
1123
1124    //
1125    // If we get to here, the pixel ranges overlap -- so we do a
1126    // pixel-by-pixel comparison to make sure they are actually
1127    // "close" according to the thresholds.  Otherwise, close=false,
1128    // and so don't need to do anything else before returning.
1129    //
1130
1131    std::vector<long> zlist1 = this->getChannelList();
1132    std::vector<long> zlist2 = other.getChannelList();
1133    Scan test1,test2;
1134
1135    for(size_t ct1=0; (!close && (ct1<zlist1.size())); ct1++){
1136      for(size_t ct2=0; (!close && (ct2<zlist2.size())); ct2++){
1137       
1138        if(abs(zlist1[ct1]-zlist2[ct2])<=threshV){
1139             
1140          Object2D temp1 = this->getChanMap(zlist1[ct1]);
1141          Object2D temp2 = other.getChanMap(zlist2[ct2]);
1142
1143          close = temp1.canMerge(temp2,threshS,flagAdj);
1144
1145        }
1146
1147      }
1148    }
1149       
1150    return close;
1151   
1152  }
1153
1154
1155
1156}
Note: See TracBrowser for help on using the repository browser.