source: tags/release-1.2.2/src/Detection/detection.cc @ 1455

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

Ticket #162 - A large refactoring of the Column-related code. Columns have moved to Outputs, and in a new namespace Catalogues. The interface has changed, using strings to record the type rather
than the enum. Also included is a new class CatalogueSpecification?, that is designed to hold a collection of Columns. This is not yet implemented - everything still uses the full & log column
vectors, and the code still passes the verification script.

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