source: trunk/src/fitsHeader.cc @ 1448

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

AXA-537 - Cleaning up some memory usage.
Ensuring that we free up WCS allocations at the appropriate point.
Also other uses of calloc, in B3SplineFilter & the plotting

File size: 12.1 KB
Line 
1// -----------------------------------------------------------------------
2// fitsHeader.cc: Information about the FITS file's header.
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 <sstream>
30#include <string>
31#include <stdlib.h>
32#include <wcslib/wcs.h>
33#include <wcslib/wcsunits.h>
34#include <duchamp/duchamp.hh>
35#include <duchamp/param.hh>
36#include <duchamp/fitsHeader.hh>
37#include <duchamp/Utils/utils.hh>
38
39namespace duchamp
40{
41
42  FitsHeader::FitsHeader()
43  {
44    this->fptr = 0;
45    this->wcs = (struct wcsprm *)calloc(1,sizeof(struct wcsprm));
46    this->wcs->flag=-1;
47    wcsini(true, 3, this->wcs);
48    this->wcsIsGood = false;
49    this->nwcs = 0;
50    this->flag2D=false;
51    this->spectralUnits="";
52    this->spectralDescription=duchamp::duchampSpectralDescription[FREQUENCY];
53    this->originalFluxUnits="";
54    this->fluxUnits="";
55    this->intFluxUnits="";
56    this->scale=1.;
57    this->offset=0.;
58    this->power=1.;
59    this->itsBeam.empty();
60  }
61
62  FitsHeader::~FitsHeader()
63  {
64    /// @details Uses the WCSLIB function wcsvfree to clear the wcsprm struct.
65    wcsvfree(&nwcs,&wcs);
66    free(wcs);
67  }
68
69  FitsHeader::FitsHeader(const FitsHeader& h)
70  {
71    operator=(h);
72  }
73
74  FitsHeader& FitsHeader::operator= (const FitsHeader& h)
75  {
76    if(this == &h) return *this;
77    this->fptr = h.fptr;
78    this->wcs = (struct wcsprm *)calloc(1,sizeof(struct wcsprm));
79    this->wcs->flag     = -1;
80    wcsini(true, h.wcs->naxis, this->wcs);
81    wcscopy(true, h.wcs, this->wcs);
82    wcsset(this->wcs);
83    this->nwcs          = h.nwcs;
84    this->wcsIsGood     = h.wcsIsGood;
85    this->flag2D        = h.flag2D;
86    this->spectralUnits = h.spectralUnits;
87    this->spectralType  = h.spectralType;
88    this->spectralDescription = h.spectralDescription;
89    this->originalFluxUnits = h.originalFluxUnits;
90    this->fluxUnits     = h.fluxUnits;
91    this->intFluxUnits  = h.intFluxUnits;
92    this->itsBeam       = h.itsBeam;
93    this->blankKeyword  = h.blankKeyword;
94    this->bzeroKeyword  = h.bzeroKeyword;
95    this->bscaleKeyword = h.bscaleKeyword;
96    this->scale         = h.scale;
97    this->offset        = h.offset;
98    this->power         = h.power;
99    return *this;
100  }
101
102  int FitsHeader::openFITS(std::string name)
103  {
104    int status = 0;
105    if( fits_open_file(&this->fptr,name.c_str(),READONLY,&status) ){
106      fits_report_error(stderr, status);
107      // if(((status==URL_PARSE_ERROR)||(status==BAD_NAXIS))
108      //         &&(this->pars().getFlagSubsection()))
109      //        DUCHAMPERROR("Cube Reader", "It may be that the subsection you've entered is invalid. Either it has the wrong number of axes, or one axis has too large a range.");
110    }
111    return status;
112  }
113
114  int FitsHeader::closeFITS()
115  {
116    int status=0;
117    fits_close_file(this->fptr, &status);
118    if (status){
119      DUCHAMPWARN("Cube Reader","Error closing file: ");
120      fits_report_error(stderr, status);
121    }
122    return status;
123
124  }
125
126  void FitsHeader::setWCS(struct wcsprm *w)
127  {
128    ///  A function that assigns the wcs parameters, and runs
129    ///   wcsset to set it up correctly.
130    ///  Performs a check to see if the WCS is good (by looking at
131    ///   the lng and lat wcsprm parameters), and sets the wcsIsGood
132    ///   flag accordingly.
133    /// \param w A WCSLIB wcsprm struct with the correct parameters.
134
135    wcscopy(true, w, this->wcs);
136    wcsset(this->wcs);
137    if( (w->lng!=-1) && (w->lat!=-1) ) this->wcsIsGood = true;
138  }
139
140  struct wcsprm *FitsHeader::getWCScopy()
141  {
142    ///  A function that returns a properly initilized wcsprm object
143    ///  corresponding to the WCS.
144
145    struct wcsprm *wNew = (struct wcsprm *)calloc(1,sizeof(struct wcsprm));
146    wNew->flag=-1;
147    wcsini(true, this->wcs->naxis, wNew);
148    wcscopy(true, this->wcs, wNew);
149    wcsset(wNew);
150    return wNew;
151  }
152
153  int FitsHeader::wcsToPix(double xWorld, double yWorld, double zWorld, double &xPix, double &yPix, double &zPix)
154  {
155      double world[3],pix[3];
156      world[0]=xWorld;
157      world[1]=yWorld;
158      world[2]=zWorld;
159      int returnval = wcsToPixSingle(this->wcs, world, pix);
160      if(returnval==0){
161          xPix=pix[0];
162          yPix=pix[1];
163          zPix=pix[2];
164      }
165      else {
166          xPix=-1.;
167          yPix=-1.;
168          zPix=-1.;
169      }
170      return returnval;
171  }
172  int FitsHeader::wcsToPix(const double *world, double *pix)
173  {     
174    return wcsToPixSingle(this->wcs, world, pix); 
175  }
176  int FitsHeader::wcsToPix(const double *world, double *pix, const int npts)
177  {
178    return wcsToPixMulti(this->wcs, world, pix, npts); 
179  }
180  int FitsHeader::pixToWCS(double xPix, double yPix, double zPix, double &xWorld, double &yWorld, double &zWorld)
181  {
182      double world[3],pix[3];
183      pix[0]=xPix;
184      pix[1]=yPix;
185      pix[2]=zPix;
186      int returnval = pixToWCSSingle(this->wcs, pix, world);
187      if(returnval==0){
188          xWorld=world[0];
189          yWorld=world[1];
190          zWorld=world[2];
191      }
192      else {
193          xWorld=-1.;
194          yWorld=-1.;
195          zWorld=-1.;
196      }
197      return returnval;
198  }
199  int FitsHeader::pixToWCS(const double *pix, double *world)
200  {   
201    return pixToWCSSingle(this->wcs, pix, world); 
202  }
203  int FitsHeader::pixToWCS(const double *pix, double *world, const int npts)
204  {
205    return pixToWCSMulti(this->wcs, pix,world, npts); 
206  }
207
208
209  double FitsHeader::pixToVel(double &x, double &y, double &z)
210  {
211    double vel;
212    if(this->wcsIsGood){
213      double *pix   = new double[3];
214      double *world = new double[3];
215      pix[0] = x; pix[1] = y; pix[2] = z;
216      pixToWCSSingle(this->wcs,pix,world);
217      vel = this->specToVel(world[2]);
218      delete [] pix;
219      delete [] world;
220    }
221    else vel = z;
222    return vel;
223  }
224
225  double* FitsHeader::pixToVel(double &x, double &y, double *zarray, int size)
226  {
227    double *newzarray = new double[size];
228    if(this->wcsIsGood){
229      double *pix   = new double[size*3];
230      for(int i=0;i<size;i++){
231        pix[3*i]   = x;
232        pix[3*i+1] = y;
233        pix[3*i+2] = zarray[i];
234      }
235      double *world = new double[size*3];
236      pixToWCSMulti(this->wcs,pix,world,size);
237      delete [] pix;
238      for(int i=0;i<size;i++) newzarray[i] = this->specToVel(world[3*i+2]);
239      delete [] world;
240    }
241    else{
242      for(int i=0;i<size;i++) newzarray[i] = zarray[i];
243    }
244    return newzarray;
245  }
246
247  double FitsHeader::specToVel(const double &coord)
248  {
249    double vel;
250    if(power==1.0) vel =  coord*this->scale + this->offset;
251    else vel = pow( (coord*this->scale + this->offset), this->power);
252    return vel;
253  }
254
255  double FitsHeader::velToSpec(const float &velocity)
256  {
257    //   return velToCoord(this->wcs,velocity,this->spectralUnits);};
258    return (pow(velocity, 1./this->power) - this->offset) / this->scale;
259  }
260
261  std::string FitsHeader::getIAUName(double ra, double dec)
262  {
263    if(std::string(this->wcs->lngtyp)=="RA")
264      return getIAUNameEQ(ra, dec, this->wcs->equinox);
265    else
266      return getIAUNameGAL(ra, dec);
267  }
268
269  void FitsHeader::fixSpectralUnits(std::string units)
270  {
271    ///  Put the units for the FITS header into some sort of standard form.
272    ///
273    ///  We first get the desired spectral units from the Parameter set,
274    ///  and then transform the spectral units of the wcsprm struct to
275    ///  those units. If this doesn't work, we leave them as they are. If
276    ///  they are blank, we make them SPC and give an error message --
277    ///  this should hopefully NOT happen.
278    ///
279    ///  We also work out the units for the integrated flux. If there are
280    ///  three axes, we just append the spectral units to the flux units
281    ///  (removing "/beam" if it is present). If there are just two, we
282    ///  simply keep it the same, removing the "/beam".
283    ///
284    ///  \param par The parameter set telling us what the desired
285    ///             spectral units are.
286
287
288    double sc=1.;
289    double of=0.;
290    double po=1.;
291 
292    this->spectralUnits = this->wcs->cunit[this->wcs->spec];
293
294    if(units != ""){
295
296      if(this->wcsIsGood){
297 
298        int status = wcsunits( this->wcs->cunit[this->wcs->spec], units.c_str(), &sc, &of, &po);
299
300        if(status > 0){
301          DUCHAMPERROR("fixSpectralUnits","Conversion of spectral units from '" << this->wcs->cunit[this->wcs->spec] << "' to '" << units
302                       << "' failed, wcslib code = " << status << ": " << wcsunits_errmsg[status]);
303          if(this->spectralUnits==""){
304            DUCHAMPERROR("fixSpectralUnits", "Spectral units not specified. For data presentation, we will use dummy units of \"SPC\".\n"
305                         << "Please report this occurence -- it should not happen! In the meantime, you may want to set the CUNIT"
306                         << this->wcs->spec + 1 <<" keyword to make this work.");
307            this->spectralUnits = "SPC";
308          }
309        }
310        else this->spectralUnits = units;
311      }
312    }
313    this->scale = sc;
314    this->offset= of;
315    this->power = po;
316   
317  }
318
319  bool FitsHeader::needBeamSize()
320  {
321    ///  A function that tells you whether the beam correction is
322    ///  needed. It checks to see whether the flux units string ends in
323    ///  "/beam" (in which case the beam size etc is needed and
324    ///  integrated fluxes need to be corrected). If we don't have any beam
325    ///  information, this will return false.
326    ///  /return True if FitsHeader::fluxUnits ends in "/beam". False
327    ///  otherwise.
328
329    int size = this->fluxUnits.size();
330    if(this->itsBeam.origin()==EMPTY) return false; // we have no beam to correct with!
331    else if(size<6) return false;
332    else {
333      std::string tailOfFluxUnits = makelower(this->fluxUnits.substr(size-5,size));
334      return (tailOfFluxUnits == "/beam");
335    }
336  }
337
338  void FitsHeader::setIntFluxUnits()
339  {
340
341    /// Work out the integrated flux units, based on the spectral
342    /// units. If flux is per beam, trim the /beam from the flux
343    /// units. Then, if as long as the image is 3D, multiply by the
344    /// spectral units.
345   
346    if(this->needBeamSize())
347      this->intFluxUnits = this->fluxUnits.substr(0,this->fluxUnits.size()-5);
348    else
349      this->intFluxUnits = this->fluxUnits;
350
351    if(!this->flag2D) this->intFluxUnits += std::string(" ") + this->spectralUnits;
352
353  }
354
355  std::string FitsHeader::lngtype()
356  {
357    std::string lngtyp(this->wcs->lngtyp);
358    if(removeLeadingBlanks(lngtyp)==""){
359      lngtyp = this->wcs->ctype[this->wcs->lng];
360      return lngtyp.substr(0,4);
361    }
362    else return lngtyp;
363  }
364
365  std::string FitsHeader::lattype()
366  {
367    std::string lattyp(this->wcs->lattyp);
368    if(removeLeadingBlanks(lattyp)==""){
369      lattyp = this->wcs->ctype[this->wcs->lat];
370      return lattyp.substr(0,4);
371    }
372    else return lattyp;
373  }
374
375  float FitsHeader::getShapeScale()
376  {
377    // Returns a scale factor that will scale the reported size of the fitted ellipses to numbers that are sensible.
378      float scale;
379      float cdelt = fabs(this->wcs->cdelt[this->wcs->lng]);
380      if(cdelt>0.01) scale =1.;
381      else if(cdelt<1.e-3) scale=3600.;
382      else scale = 60.;
383      return scale;
384  }
385
386  std::string FitsHeader::getShapeUnits()
387  {
388      std::string units="deg";
389      float cdelt = fabs(this->wcs->cdelt[this->wcs->lng]);
390      if(cdelt>0.01) units="deg";
391      else if(cdelt<1.e-3) units="arcsec";
392      else units="arcmin";
393      return units;
394  }
395
396
397}
Note: See TracBrowser for help on using the repository browser.