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

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

Solving a problem with Cormac's bugfixing testcase (fred.fits), where the GLON/GLAT WCS types were not being recognised by the wcslib code - wcsset was not reading them correctly and was providing blank values for lngtyp & lattyp. The new functions check these parameters and, if blank, use the first four letters of the CTYPEi keyword. A bit of a kludge, but this should be what wcsset does...

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