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

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

A large set of changes aimed at making the use of indexing variables consistent. We have moved to size_t as much as possible to represent the location in memory. This includes making the dimension array within DataArray? and derived classes an array of size_t variables. Still plenty of compilation warnings (principally comparing signed and unsigned variables) - these will need to be cleaned up.

File size: 37.3 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) duchampError("calcWCSparams",
449                               "Error in calculating the WCS for this object.\n");
450      else{
451
452        // world now has the WCS coords for the five points
453        //    -- use this to work out WCS params
454 
455        this->haveParams = true;
456
457        this->specOK = head.canUseThirdAxis();
458        this->lngtype = head.WCS().lngtyp;
459        this->lattype = head.WCS().lattyp;
460        this->specUnits = head.getSpectralUnits();
461        this->fluxUnits = head.getFluxUnits();
462        // if fluxUnits are eg. Jy/beam, make intFluxUnits = Jy km/s
463        this->intFluxUnits = head.getIntFluxUnits();
464        this->ra   = world[0];
465        this->dec  = world[1];
466        this->raS  = decToDMS(this->ra, this->lngtype);
467        this->decS = decToDMS(this->dec,this->lattype);
468        this->raWidth = angularSeparation(world[9],world[1],
469                                          world[12],world[1]) * 60.;
470        this->decWidth  = angularSeparation(world[0],world[10],
471                                            world[0],world[13]) * 60.;
472
473        Object2D spatMap = this->getSpatialMap();
474        std::pair<double,double> axes = spatMap.getPrincipleAxes();
475        this->majorAxis = std::max(axes.first,axes.second) * head.getAvPixScale();
476        this->minorAxis = std::min(axes.first,axes.second) * head.getAvPixScale();
477        this->posang = spatMap.getPositionAngle() * 180. / M_PI;
478
479        this->name = head.getIAUName(this->ra, this->dec);
480        this->vel    = head.specToVel(world[2]);
481        this->velMin = head.specToVel(world[5]);
482        this->velMax = head.specToVel(world[8]);
483        this->velWidth = fabs(this->velMax - this->velMin);
484
485        this->flagWCS = true;
486      }
487      delete [] world;
488
489    }
490  }
491  //--------------------------------------------------------------------
492
493  void Detection::calcIntegFlux(size_t zdim, std::vector<Voxel> voxelList, FitsHeader &head)
494  {
495    ///  @details
496    ///  Uses the input WCS to calculate the velocity-integrated flux,
497    ///   putting velocity in units of km/s.
498    ///  The fluxes used are taken from the Voxels, rather than an
499    ///   array of flux values.
500    ///  Integrates over full spatial and velocity range as given
501    ///   by the extrema calculated by calcWCSparams.
502    ///
503    ///  If the flux units end in "/beam" (eg. Jy/beam), then the flux is
504    ///  corrected by the beam size (in pixels). This is done by
505    ///  multiplying the integrated flux by the number of spatial pixels,
506    ///  and dividing by the beam size in pixels (e.g. Jy/beam * pix /
507    ///  pix/beam --> Jy)
508    ///
509    ///  \param zdim The size of the spectral axis (needed to find the velocity widths)
510    ///  \param voxelList The list of Voxels with flux information
511    ///  \param head FitsHeader object that contains the WCS information.
512
513    const int border = 1;
514
515    if(!this->voxelListCovered(voxelList)){
516      duchampError("Detection::calcIntegFlux","Voxel list provided does not match");
517      return;
518    }
519
520    if(!head.is2D()){
521
522      this->haveParams = true;
523
524      // include one pixel either side in each direction
525      size_t xsize = (this->getXmax()-this->getXmin()+border*2+1);
526      size_t ysize = (this->getYmax()-this->getYmin()+border*2+1);
527      size_t zsize = (this->getZmax()-this->getZmin()+border*2+1);
528      size_t spatsize=xsize*ysize;
529      size_t size = xsize*ysize*zsize;
530      std::vector <bool> isObj(size,false);
531      double *localFlux = new double[size];
532      for(size_t i=0;i<size;i++) localFlux[i]=0.;
533
534      std::vector<Voxel>::iterator vox;
535      for(vox=voxelList.begin();vox<voxelList.end();vox++){
536        if(this->isInObject(*vox)){
537          long x = vox->getX();
538          long y = vox->getY();
539          long z = vox->getZ();
540          size_t pos = (x-this->getXmin()+border) + (y-this->getYmin()+border)*xsize
541            + (z-this->getZmin()+border)*xsize*ysize;
542          localFlux[pos] = vox->getF();
543          isObj[pos] = true;
544        }
545      }
546 
547      // work out the WCS coords for each pixel
548      double *world  = new double[size];
549      double xpt,ypt,zpt;
550      for(size_t i=0;i<xsize*ysize*zsize;i++){
551        xpt = double( this->getXmin() - border + i%xsize );
552        ypt = double( this->getYmin() - border + (i/xsize)%ysize );
553        zpt = double( this->getZmin() - border + i/(xsize*ysize) );
554        world[i] = head.pixToVel(xpt,ypt,zpt);
555      }
556
557      double integrated = 0.;
558      for(size_t pix=0; pix<spatsize; pix++){ // loop over each spatial pixel.
559        for(size_t z=0; z<zsize; z++){
560          int pos =  z*xsize*ysize + pix;
561          if(isObj[pos]){ // if it's an object pixel...
562            double deltaVel;
563            if(z==0)
564              deltaVel = (world[pos+xsize*ysize] - world[pos]);
565            else if(z==(zsize-1))
566              deltaVel = (world[pos] - world[pos-xsize*ysize]);
567            else
568              deltaVel = (world[pos+xsize*ysize] - world[pos-xsize*ysize]) / 2.;
569            integrated += localFlux[pos] * fabs(deltaVel);
570          }
571        }
572      }
573      this->intFlux = integrated;
574
575      delete [] world;
576      delete [] localFlux;
577
578      calcVelWidths(zdim,voxelList,head);
579
580    }
581    else // in this case there is just a 2D image.
582      this->intFlux = this->totalFlux;
583
584    if(head.isWCS()){
585      // correct for the beam size if the flux units string ends in "/beam"
586      if(head.needBeamSize()) this->intFlux  /= head.beam().area();
587    }
588
589  }
590  //--------------------------------------------------------------------
591
592  void Detection::calcIntegFlux(size_t zdim, std::map<Voxel,float> voxelMap, FitsHeader &head)
593  {
594    ///  @details
595    ///  Uses the input WCS to calculate the velocity-integrated flux,
596    ///   putting velocity in units of km/s.
597    ///  The fluxes used are taken from the Voxels, rather than an
598    ///   array of flux values.
599    ///  Integrates over full spatial and velocity range as given
600    ///   by the extrema calculated by calcWCSparams.
601    ///
602    ///  If the flux units end in "/beam" (eg. Jy/beam), then the flux is
603    ///  corrected by the beam size (in pixels). This is done by
604    ///  multiplying the integrated flux by the number of spatial pixels,
605    ///  and dividing by the beam size in pixels (e.g. Jy/beam * pix /
606    ///  pix/beam --> Jy)
607    ///
608    ///  \param zdim The size of the spectral axis (needed to find the velocity widths)
609    ///  \param voxelList The list of Voxels with flux information
610    ///  \param head FitsHeader object that contains the WCS information.
611
612    const int border = 1;
613
614    if(!head.is2D()){
615
616      this->haveParams = true;
617
618      // include one pixel either side in each direction
619      size_t xsize = (this->getXmax()-this->getXmin()+border*2+1);
620      size_t ysize = (this->getYmax()-this->getYmin()+border*2+1);
621      size_t zsize = (this->getZmax()-this->getZmin()+border*2+1);
622      size_t spatsize=xsize*ysize;
623      size_t size = xsize*ysize*zsize;
624      std::vector <bool> isObj(size,false);
625      double *localFlux = new double[size];
626      for(size_t i=0;i<size;i++) localFlux[i]=0.;
627
628      std::vector<Voxel> voxelList = this->getPixelSet();
629      std::vector<Voxel>::iterator vox;
630      for(vox=voxelList.begin();vox<voxelList.end();vox++){
631        if(voxelMap.find(*vox) == voxelMap.end()){
632          duchampError("Detection::calcIntegFlux","Voxel list provided does not match");
633          return;
634        }       
635        else {
636          long x = vox->getX();
637          long y = vox->getY();
638          long z = vox->getZ();
639          size_t pos = (x-this->getXmin()+border) + (y-this->getYmin()+border)*xsize
640            + (z-this->getZmin()+border)*xsize*ysize;
641          localFlux[pos] = voxelMap[*vox];
642          isObj[pos] = true;
643        }
644      }
645 
646      // work out the WCS coords for each pixel
647      double *world  = new double[size];
648      double xpt,ypt,zpt;
649      for(size_t i=0;i<xsize*ysize*zsize;i++){
650        xpt = double( this->getXmin() - border + i%xsize );
651        ypt = double( this->getYmin() - border + (i/xsize)%ysize );
652        zpt = double( this->getZmin() - border + i/(xsize*ysize) );
653        world[i] = head.pixToVel(xpt,ypt,zpt);
654      }
655
656      double integrated = 0.;
657      for(size_t pix=0; pix<spatsize; pix++){ // loop over each spatial pixel.
658        for(size_t z=0; z<zsize; z++){
659          int pos =  z*xsize*ysize + pix;
660          if(isObj[pos]){ // if it's an object pixel...
661            double deltaVel;
662            if(z==0)
663              deltaVel = (world[pos+xsize*ysize] - world[pos]);
664            else if(z==(zsize-1))
665              deltaVel = (world[pos] - world[pos-xsize*ysize]);
666            else
667              deltaVel = (world[pos+xsize*ysize] - world[pos-xsize*ysize]) / 2.;
668            integrated += localFlux[pos] * fabs(deltaVel);
669          }
670        }
671      }
672      this->intFlux = integrated;
673
674      delete [] world;
675      delete [] localFlux;
676
677      calcVelWidths(zdim,voxelMap,head);
678
679    }
680    else // in this case there is just a 2D image.
681      this->intFlux = this->totalFlux;
682
683    if(head.isWCS()){
684      // correct for the beam size if the flux units string ends in "/beam"
685      if(head.needBeamSize()) this->intFlux  /= head.beam().area();
686    }
687
688  }
689  //--------------------------------------------------------------------
690
691  void Detection::calcIntegFlux(float *fluxArray, size_t *dim, FitsHeader &head)
692  {
693    ///  @details
694    ///  Uses the input WCS to calculate the velocity-integrated flux,
695    ///   putting velocity in units of km/s.
696    ///  Integrates over full spatial and velocity range as given
697    ///   by the extrema calculated by calcWCSparams.
698    ///
699    ///  If the flux units end in "/beam" (eg. Jy/beam), then the flux is
700    ///  corrected by the beam size (in pixels). This is done by
701    ///  multiplying the integrated flux by the number of spatial pixels,
702    ///  and dividing by the beam size in pixels (e.g. Jy/beam * pix /
703    ///  pix/beam --> Jy)
704    ///
705    ///  \param fluxArray The array of flux values.
706    ///  \param dim The dimensions of the flux array.
707    ///  \param head FitsHeader object that contains the WCS information.
708
709    if(!head.is2D()){
710
711      this->haveParams = true;
712
713      // include one pixel either side in each direction
714      size_t xsize = (this->xmax-this->xmin+3);
715      size_t ysize = (this->ymax-this->ymin+3);
716      size_t zsize = (this->zmax-this->zmin+3);
717      size_t spatsize = xsize*ysize;
718      size_t size = xsize*ysize*zsize;
719      std::vector <bool> isObj(size,false);
720      double *localFlux = new double[size];
721      for(int i=0;i<size;i++) localFlux[i]=0.;
722      // work out which pixels are object pixels
723      std::vector<Voxel> voxlist = this->getPixelSet();
724      for(std::vector<Voxel>::iterator v=voxlist.begin();v<voxlist.end();v++){
725        size_t pos=(v->getX()-this->xmin+1) + (v->getY()-this->ymin+1)*xsize
726          + (v->getZ()-this->zmin+1)*xsize*ysize;
727        localFlux[pos] = fluxArray[v->arrayIndex(dim)];
728        isObj[pos] = true;
729      }
730 
731      // work out the WCS coords for each pixel
732      double *world  = new double[size];
733      double xpt,ypt,zpt;
734      size_t i=0;
735      for(size_t z=0;z<zsize;z++){
736        for(size_t y=0;y<ysize;y++){
737          for(size_t x=0;x<xsize;x++){
738            xpt=double(this->xmin - 1 + x);
739            ypt=double(this->ymin - 1 + y);
740            zpt=double(this->zmin - 1 + z);
741            world[i++] = head.pixToVel(xpt,ypt,zpt);
742          }
743        }
744      }
745
746      double integrated = 0.;
747      for(size_t pix=0; pix<xsize*ysize; pix++){ // loop over each spatial pixel.
748        for(size_t z=0; z<zsize; z++){
749          int pos =  z*xsize*ysize + pix;
750          if(isObj[pos]){ // if it's an object pixel...
751            double deltaVel;
752            if(z==0)
753              deltaVel = (world[pos+xsize*ysize] - world[pos]);
754            else if(z==(zsize-1))
755              deltaVel = (world[pos] - world[pos-xsize*ysize]);
756            else
757              deltaVel = (world[pos+xsize*ysize] - world[pos-xsize*ysize]) / 2.;
758            integrated += localFlux[pos] * fabs(deltaVel);
759          }
760        }
761      }
762      this->intFlux = integrated;
763
764      delete [] world;
765      delete [] localFlux;
766
767      calcVelWidths(fluxArray, dim, head);
768
769    }
770    else // in this case there is just a 2D image.
771      this->intFlux = this->totalFlux;
772
773    if(head.isWCS()){
774      // correct for the beam size if the flux units string ends in "/beam" and we have beam info
775      if(head.needBeamSize()) this->intFlux  /= head.beam().area();
776    }
777
778  }
779  //--------------------------------------------------------------------
780
781  void Detection::calcVelWidths(size_t zdim, std::vector<Voxel> voxelList, FitsHeader &head)
782  {
783    ///  @details
784    /// Calculates the widths of the detection at 20% and 50% of the
785    /// peak integrated flux. The procedure is as follows: first
786    /// generate an integrated flux spectrum (using all given voxels
787    /// that lie in the object's spatial map); find the peak; starting
788    /// at the spectral edges of the detection, move in or out until
789    /// you reach the 20% or 50% peak flux level. Linear interpolation
790    /// between points is done.
791    ///
792    ///  \param zdim The size of the spectral axis in the cube
793    ///  \param voxelList The list of Voxels with flux information
794    ///  \param head FitsHeader object that contains the WCS information.
795
796    float *intSpec = new float[zdim];
797    for(int i=0;i<zdim;i++) intSpec[i]=0;
798       
799    Object2D spatMap = this->getSpatialMap();
800    for(int s=0;s<spatMap.getNumScan();s++){
801      std::vector<Voxel>::iterator vox;
802      for(vox=voxelList.begin();vox<voxelList.end();vox++){
803        if(spatMap.isInObject(*vox)){
804          intSpec[vox->getZ()] += vox->getF();
805        }
806      }
807    }
808   
809    calcVelWidths(zdim, intSpec, head);
810
811    delete [] intSpec;
812
813  }
814
815  //--------------------------------------------------------------------
816
817  void Detection::calcVelWidths(size_t zdim, std::map<Voxel,float> voxelMap, FitsHeader &head)
818  {
819    ///  @details
820    /// Calculates the widths of the detection at 20% and 50% of the
821    /// peak integrated flux. The procedure is as follows: first
822    /// generate an integrated flux spectrum (using all given voxels
823    /// that lie in the object's spatial map); find the peak; starting
824    /// at the spectral edges of the detection, move in or out until
825    /// you reach the 20% or 50% peak flux level. Linear interpolation
826    /// between points is done.
827    ///
828    ///  \param zdim The size of the spectral axis in the cube
829    ///  \param voxelList The list of Voxels with flux information
830    ///  \param head FitsHeader object that contains the WCS information.
831
832    float *intSpec = new float[zdim];
833    for(int i=0;i<zdim;i++) intSpec[i]=0;
834       
835    std::vector<Voxel> voxelList = this->getPixelSet();
836    std::vector<Voxel>::iterator vox;
837    for(vox=voxelList.begin();vox<voxelList.end();vox++){
838      if(voxelMap.find(*vox) == voxelMap.end()){
839        duchampError("Detection::calcVelWidths","Voxel list provided does not match");
840        return;
841      }
842      else {
843        intSpec[vox->getZ()] += voxelMap[*vox];
844      }
845    }
846
847    calcVelWidths(zdim, intSpec, head);
848
849    delete [] intSpec;
850
851  }
852
853  //--------------------------------------------------------------------
854
855  void Detection::calcVelWidths(size_t zdim, float *intSpec, FitsHeader &head)
856  {
857
858      // finding the 20% & 50% points.  Start at the velmin & velmax
859      //  points. Then, if the int flux there is above the 20%/50%
860      //  limit, go out, otherwise go in. This is to deal with the
861      //  problems from double- (or multi-) peaked sources.
862
863    this->haveParams = true;
864
865    double zpt,xpt=double(this->getXcentre()),ypt=double(this->getXcentre());
866    bool goLeft;
867   
868    float peak=0.;
869    int peakLoc=0;
870    for(int z=this->getZmin();z<=this->getZmax();z++) {
871      if(z==0 || peak<intSpec[z]){
872        peak = intSpec[z];
873        peakLoc = z;
874      }
875    }
876   
877    int z=this->getZmin();
878    goLeft = intSpec[z]>peak*0.5;
879    if(goLeft) while(z>0 && intSpec[z]>peak*0.5) z--;
880    else       while(z<peakLoc && intSpec[z]<peak*0.5) z++;
881    if(z==0) this->v50min = this->velMin;
882    else{
883      if(goLeft) zpt = z + (peak*0.5-intSpec[z])/(intSpec[z+1]-intSpec[z]);
884      else       zpt = z - (peak*0.5-intSpec[z])/(intSpec[z-1]-intSpec[z]);
885      this->v50min = head.pixToVel(xpt,ypt,zpt);
886    }
887    z=this->getZmax();
888    goLeft = intSpec[z]<peak*0.5;
889    if(goLeft) while(z>peakLoc && intSpec[z]<peak*0.5) z--;
890    else       while(z<zdim    && intSpec[z]>peak*0.5) z++;
891    if(z==zdim) this->v50max = this->velMax;
892    else{
893      if(goLeft) zpt = z + (peak*0.5-intSpec[z])/(intSpec[z+1]-intSpec[z]);
894      else       zpt = z - (peak*0.5-intSpec[z])/(intSpec[z-1]-intSpec[z]);
895      this->v50max = head.pixToVel(xpt,ypt,zpt);
896    }
897    z=this->getZmin();
898    goLeft = intSpec[z]>peak*0.2;
899    if(goLeft) while(z>0 && intSpec[z]>peak*0.2) z--;
900    else       while(z<peakLoc && intSpec[z]<peak*0.2) z++;
901    if(z==0) this->v20min = this->velMin;
902    else{
903      if(goLeft) zpt = z + (peak*0.2-intSpec[z])/(intSpec[z+1]-intSpec[z]);
904      else       zpt = z - (peak*0.2-intSpec[z])/(intSpec[z-1]-intSpec[z]);
905      this->v20min = head.pixToVel(xpt,ypt,zpt);
906    }
907    z=this->getZmax();
908    goLeft = intSpec[z]<peak*0.2;
909    if(goLeft) while(z>peakLoc && intSpec[z]<peak*0.2) z--;
910    else       while(z<zdim    && intSpec[z]>peak*0.2) z++;
911    if(z==zdim) this->v20max = this->velMax;
912    else{
913      if(goLeft) zpt = z + (peak*0.2-intSpec[z])/(intSpec[z+1]-intSpec[z]);
914      else       zpt = z - (peak*0.2-intSpec[z])/(intSpec[z-1]-intSpec[z]);
915      this->v20max = head.pixToVel(xpt,ypt,zpt);
916    }
917
918    this->w20 = fabs(this->v20min - this->v20max);
919    this->w50 = fabs(this->v50min - this->v50max);
920
921
922  }
923  //--------------------------------------------------------------------
924
925  void Detection::calcVelWidths(float *fluxArray, size_t *dim, FitsHeader &head)
926  {
927    ///  @details
928    /// Calculates the widths of the detection at 20% and 50% of the
929    /// peak integrated flux. The procedure is as follows: first
930    /// generate an integrated flux spectrum (summing each spatial
931    /// pixel's spectrum); find the peak; starting at the spectral
932    /// edges of the detection, move in or out until you reach the 20%
933    /// or 50% peak flux level. Linear interpolation between points is
934    /// done.
935    ///
936    ///  \param fluxArray The array of flux values.
937    ///  \param dim The dimensions of the flux array.
938    ///  \param head FitsHeader object that contains the WCS information.
939
940    if(dim[2] > 2){
941
942      float *intSpec = new float[dim[2]];
943      size_t size=dim[0]*dim[1]*dim[2];
944      std::vector<bool> mask(size,true);
945      getIntSpec(*this,fluxArray,dim,mask,1.,intSpec);
946
947      this->calcVelWidths(dim[2],intSpec,head);
948
949      delete [] intSpec;
950
951    }
952    else{
953      this->v50min = this->v20min = this->velMin;
954      this->v50max = this->v20max = this->velMax;
955      this->w20 = fabs(this->v20min - this->v20max);
956      this->w50 = fabs(this->v50min - this->v50max);
957    }
958
959  }
960  //--------------------------------------------------------------------
961
962  void Detection::setOffsets(Param &par)
963  {
964    ///  @details
965    /// This function stores the values of the offsets for each cube axis.
966    /// The offsets are the starting values of the cube axes that may differ from
967    ///  the default value of 0 (for instance, if a subsection is being used).
968    /// The values will be used when the detection is outputted.
969
970    this->xSubOffset = par.getXOffset();
971    this->ySubOffset = par.getYOffset();
972    this->zSubOffset = par.getZOffset();
973  }
974  //--------------------------------------------------------------------
975
976  bool Detection::hasEnoughChannels(int minNumber)
977  {
978    ///  @details
979    /// A function to determine if the Detection has enough
980    /// contiguous channels to meet the minimum requirement
981    /// given as the argument.
982    /// \param minNumber How many channels is the minimum acceptable number?
983    /// \return True if there is at least one occurence of minNumber consecutive
984    /// channels present to return true. False otherwise.
985
986    // Preferred method -- need a set of minNumber consecutive channels present.
987
988    int numChan = this->getMaxAdjacentChannels();
989    bool result = (numChan >= minNumber);
990
991    return result;
992 
993  }
994  //--------------------------------------------------------------------
995
996  std::vector<int> Detection::getVertexSet()
997  {
998    ///  @details
999    /// Gets a list of points being the end-points of 1-pixel long
1000    /// segments drawing a border around the spatial extend of a
1001    /// detection. The vector is a series of 4 integers, being: x_0,
1002    /// y_0, x_1, y_1.
1003    /// \return The vector of vertex positions.
1004
1005    std::vector<int> vertexSet;
1006
1007    int xmin = this->getXmin() - 1;
1008    int xmax = this->getXmax() + 1;
1009    int ymin = this->getYmin() - 1;
1010    int ymax = this->getYmax() + 1;
1011    int xsize = xmax - xmin + 1;
1012    int ysize = ymax - ymin + 1;
1013
1014    std::vector<Voxel> voxlist = this->getPixelSet();
1015    std::vector<bool> isObj(xsize*ysize,false);
1016    std::vector<Voxel>::iterator vox;
1017    for(vox=voxlist.begin();vox<voxlist.end();vox++){
1018      int pos = (vox->getX()-xmin) +
1019        (vox->getY()-ymin)*xsize;
1020      isObj[pos] = true;
1021    }
1022    voxlist.clear();
1023   
1024    for(int x=xmin; x<=xmax; x++){
1025      // for each column...
1026      for(int y=ymin+1;y<=ymax;y++){
1027        int current  = (y-ymin)*xsize + x-xmin;
1028        int previous = (y-ymin-1)*xsize + x-xmin;
1029        if((isObj[current]&&!isObj[previous])   ||
1030           (!isObj[current]&&isObj[previous])){
1031          vertexSet.push_back(x);
1032          vertexSet.push_back(y);
1033          vertexSet.push_back(x+1);
1034          vertexSet.push_back(y);
1035        }
1036      }
1037    }
1038    for(int y=ymin; y<=ymax; y++){
1039      // now for each row...
1040      for(int x=xmin+1;x<=xmax;x++){
1041        int current  = (y-ymin)*xsize + x-xmin;
1042        int previous = (y-ymin)*xsize + x-xmin - 1;
1043        if((isObj[current]&&!isObj[previous])   ||
1044           (!isObj[current]&&isObj[previous])){
1045          vertexSet.push_back(x);
1046          vertexSet.push_back(y);
1047          vertexSet.push_back(x);
1048          vertexSet.push_back(y+1);
1049        }
1050      }
1051    }
1052
1053    return vertexSet;
1054 
1055  }
1056
1057 
1058  void Detection::addDetection(Detection &other)
1059  {
1060    for(std::map<long, Object2D>::iterator it = other.chanlist.begin(); it!=other.chanlist.end();it++)
1061      //      this->addChannel(*it);
1062      this->addChannel(it->first, it->second);
1063    this->haveParams = false; // make it appear as if the parameters haven't been calculated, so that we can re-calculate them 
1064  }
1065
1066  Detection operator+ (Detection &lhs, Detection &rhs)
1067  {
1068    Detection output = lhs;
1069    for(std::map<long, Object2D>::iterator it = rhs.chanlist.begin(); it!=rhs.chanlist.end();it++)
1070      output.addChannel(it->first, it->second);
1071    output.haveParams = false; // make it appear as if the parameters haven't been calculated, so that we can re-calculate them
1072    return output;
1073  }
1074   
1075
1076  bool Detection::canMerge(Detection &other, Param &par)
1077  {
1078    bool near = this->isNear(other,par);
1079    if(near) return this->isClose(other,par);
1080    else return near;
1081  }
1082
1083  bool Detection::isNear(Detection &other, Param &par)
1084  {
1085
1086    bool flagAdj = par.getFlagAdjacent();
1087    float threshS = par.getThreshS();
1088    float threshV = par.getThreshV();
1089
1090    long gap;
1091    if(flagAdj) gap = 1;
1092    else gap = long( ceil(threshS) );
1093
1094    bool areNear;
1095    // Test X ranges
1096    if((this->xmin-gap)<other.xmin) areNear=((this->xmax+gap)>=other.xmin);
1097    else areNear=(other.xmax>=(this->xmin-gap));
1098    // Test Y ranges
1099    if(areNear){
1100      if((this->ymin-gap)<other.ymin) areNear=areNear&&((this->ymax+gap)>=other.ymin);
1101      else areNear=areNear&&(other.ymax>=(this->ymin-gap));
1102    }
1103    // Test Z ranges
1104    if(areNear){
1105      gap = long(ceil(threshV));
1106      if((this->zmin-gap)<other.zmin) areNear=areNear&&((this->zmax+gap)>=other.zmin);
1107      else areNear=areNear&&(other.zmax>=(this->zmin-gap));
1108    }
1109   
1110    return areNear;
1111
1112  }
1113
1114  bool Detection::isClose(Detection &other, Param &par)
1115  {
1116    bool close = false;   // this will be the value returned
1117   
1118    bool flagAdj = par.getFlagAdjacent();
1119    float threshS = par.getThreshS();
1120    float threshV = par.getThreshV();
1121
1122    //
1123    // If we get to here, the pixel ranges overlap -- so we do a
1124    // pixel-by-pixel comparison to make sure they are actually
1125    // "close" according to the thresholds.  Otherwise, close=false,
1126    // and so don't need to do anything else before returning.
1127    //
1128
1129    std::vector<long> zlist1 = this->getChannelList();
1130    std::vector<long> zlist2 = other.getChannelList();
1131    Scan test1,test2;
1132
1133    for(size_t ct1=0; (!close && (ct1<zlist1.size())); ct1++){
1134      for(size_t ct2=0; (!close && (ct2<zlist2.size())); ct2++){
1135       
1136        if(abs(zlist1[ct1]-zlist2[ct2])<=threshV){
1137             
1138          Object2D temp1 = this->getChanMap(zlist1[ct1]);
1139          Object2D temp2 = other.getChanMap(zlist2[ct2]);
1140
1141          close = temp1.canMerge(temp2,threshS,flagAdj);
1142
1143        }
1144
1145      }
1146    }
1147       
1148    return close;
1149   
1150  }
1151
1152
1153
1154}
Note: See TracBrowser for help on using the repository browser.