astLib-0.10.0/0000775000175000017500000000000013247150772013336 5ustar mattymatty00000000000000astLib-0.10.0/docs/0000775000175000017500000000000013247150772014266 5ustar mattymatty00000000000000astLib-0.10.0/docs/astLib/0000775000175000017500000000000013247150772015504 5ustar mattymatty00000000000000astLib-0.10.0/docs/astLib/toc-astLib.astSED-module.html0000664000175000017500000000541213047255533023001 0ustar mattymatty00000000000000 astSED

Module astSED


Classes

BC03Model
M05Model
P09Model
Passband
SED
StellarPopulation
TopHatPassband
VegaSED

Functions

Jy2Mag
fitSEDDict
flux2Mag
mag2Flux
mag2Jy
mags2SEDDict
makeModelSEDDictList

Variables

AB
SOL
VEGA
__package__

[hide private] astLib-0.10.0/docs/astLib/astLib-pysrc.html0000644000175000017500000001365113047255533020751 0ustar mattymatty00000000000000 astLib
Package astLib
[hide private]
[frames] | no frames]

Source Code for Package astLib

 1  """ 
 2  astLib - python astronomy modules 
 3   
 4  (c) 2007-2012 Matt Hilton 
 5   
 6  (c) 2013-2014 Matt Hilton & Steven Boada 
 7   
 8  U{http://astlib.sourceforge.net} 
 9   
10  See the README file for information on usage and installation. 
11  See the LICENSE file for information on distribution. 
12   
13  """ 
14   
15  __all__=['astCalc', 'astCoords', 'astImages', 'astPlots', 'astStats', 'astWCS', 'astSED'] 
16  __version__ = '0.8.0' 
17   

astLib-0.10.0/docs/astLib/astLib.astSED-pysrc.html0000664000175000017500000121524613047255533022102 0ustar mattymatty00000000000000 astLib.astSED
Package astLib :: Module astSED
[hide private]
[frames] | no frames]

Source Code for Module astLib.astSED

   1  """module for performing calculations on Spectral Energy Distributions (SEDs) 
   2   
   3  (c) 2007-2013 Matt Hilton  
   4   
   5  U{http://astlib.sourceforge.net} 
   6   
   7  This module provides classes for manipulating SEDs, in particular the Bruzual & Charlot 2003, Maraston 
   8  2005, and Percival et al 2009 stellar population synthesis models are currently supported. Functions are  
   9  provided for calculating the evolution of colours and magnitudes in these models with redshift etc., and  
  10  for fitting broadband photometry using these models. 
  11   
  12  @var VEGA: The SED of Vega, used for calculation of magnitudes on the Vega system. 
  13  @type VEGA: L{SED} object 
  14  @var AB: Flat spectrum SED, used for calculation of magnitudes on the AB system. 
  15  @type AB: L{SED} object 
  16  @var SOL: The SED of the Sun. 
  17  @type SOL: L{SED} object 
  18   
  19  """ 
  20   
  21  #------------------------------------------------------------------------------------------------------------ 
  22  import sys 
  23  import numpy 
  24  import math 
  25  import operator 
  26  try: 
  27      from scipy import interpolate 
  28      from scipy import ndimage 
  29      from scipy import optimize 
  30  except: 
  31      print("WARNING: astSED: failed to import scipy modules - some functions will not work.") 
  32  import astLib 
  33  from astLib import astCalc 
  34  import os 
  35  try: 
  36      import matplotlib 
  37      from matplotlib import pylab 
  38      matplotlib.interactive(False) 
  39  except: 
  40      print("WARNING: astSED: failed to import matplotlib - some functions will not work.") 
  41  import glob 
  42   
  43  #------------------------------------------------------------------------------------------------------------ 
44 -class Passband:
45 """This class describes a filter transmission curve. Passband objects are created by loading data from 46 from text files containing wavelength in angstroms in the first column, relative transmission efficiency 47 in the second column (whitespace delimited). For example, to create a Passband object for the 2MASS J 48 filter: 49 50 passband=astSED.Passband("J_2MASS.res") 51 52 where "J_2MASS.res" is a file in the current working directory that describes the filter. 53 54 Wavelength units can be specified as 'angstroms', 'nanometres' or 'microns'; if either of the latter, 55 they will be converted to angstroms. 56 57 """
58 - def __init__(self, fileName, normalise = True, inputUnits = 'angstroms', wavelengthColumn = 0, transmissionColumn = 1):
59 60 inFile=open(fileName, "r") 61 lines=inFile.readlines() 62 63 wavelength=[] 64 transmission=[] 65 for line in lines: 66 67 if line[0] != "#" and len(line) > 3: 68 69 bits=line.split() 70 transmission.append(float(bits[transmissionColumn])) 71 wavelength.append(float(bits[wavelengthColumn])) 72 73 self.wavelength=numpy.array(wavelength) 74 self.transmission=numpy.array(transmission) 75 76 if inputUnits == 'angstroms': 77 pass 78 elif inputUnits == 'nanometres': 79 self.wavelength=self.wavelength*10.0 80 elif inputUnits == 'microns': 81 self.wavelength=self.wavelength*10000.0 82 elif inputUnits == 'mm': 83 self.wavelength=self.wavelength*1e7 84 elif inputUnits == 'GHz': 85 self.wavelength=3e8/(self.wavelength*1e9) 86 self.wavelength=self.wavelength*1e10 87 else: 88 raise Exception("didn't understand passband input units") 89 90 # Sort into ascending order of wavelength otherwise normalisation will be wrong 91 merged=numpy.array([self.wavelength, self.transmission]).transpose() 92 sortedMerged=numpy.array(sorted(merged, key=operator.itemgetter(0))) 93 self.wavelength=sortedMerged[:, 0] 94 self.transmission=sortedMerged[:, 1] 95 96 if normalise == True: 97 self.transmission=self.transmission/numpy.trapz(self.transmission, self.wavelength) 98 99 # Store a ready-to-go interpolation object to speed calculation of fluxes up 100 self.interpolator=interpolate.interp1d(self.wavelength, self.transmission, kind='linear')
101
102 - def asList(self):
103 """Returns a two dimensional list of [wavelength, transmission], suitable for plotting by gnuplot. 104 105 @rtype: list 106 @return: list in format [wavelength, transmission] 107 108 """ 109 110 listData=[] 111 for l, f in zip(self.wavelength, self.transmission): 112 listData.append([l, f]) 113 114 return listData
115
116 - def rescale(self, maxTransmission):
117 """Rescales the passband so that maximum value of the transmission is equal to maxTransmission. 118 Useful for plotting. 119 120 @type maxTransmission: float 121 @param maxTransmission: maximum value of rescaled transmission curve 122 123 """ 124 125 self.transmission=self.transmission*(maxTransmission/self.transmission.max())
126
127 - def plot(self, xmin = 'min', xmax = 'max', maxTransmission = None):
128 """Plots the passband, rescaling the maximum of the tranmission curve to maxTransmission if 129 required. 130 131 @type xmin: float or 'min' 132 @param xmin: minimum of the wavelength range of the plot 133 @type xmax: float or 'max' 134 @param xmax: maximum of the wavelength range of the plot 135 @type maxTransmission: float 136 @param maxTransmission: maximum value of rescaled transmission curve 137 138 """ 139 140 if maxTransmission != None: 141 self.rescale(maxTransmission) 142 143 pylab.matplotlib.interactive(True) 144 pylab.plot(self.wavelength, self.transmission) 145 146 if xmin == 'min': 147 xmin=self.wavelength.min() 148 if xmax == 'max': 149 xmax=self.wavelength.max() 150 151 pylab.xlim(xmin, xmax) 152 pylab.xlabel("Wavelength") 153 pylab.ylabel("Relative Flux")
154
155 - def effectiveWavelength(self):
156 """Calculates effective wavelength for the passband. This is the same as equation (3) of 157 Carter et al. 2009. 158 159 @rtype: float 160 @return: effective wavelength of the passband, in Angstroms 161 162 """ 163 164 a=numpy.trapz(self.transmission*self.wavelength, self.wavelength) 165 b=numpy.trapz(self.transmission/self.wavelength, self.wavelength) 166 effWavelength=numpy.sqrt(a/b) 167 168 return effWavelength
169 170 #------------------------------------------------------------------------------------------------------------
171 -class TopHatPassband(Passband):
172 """This class generates a passband with a top hat response between the given wavelengths. 173 174 """ 175
176 - def __init__(self, wavelengthMin, wavelengthMax, normalise = True):
177 """Generates a passband object with top hat response between wavelengthMin, wavelengthMax. 178 Units are assumed to be Angstroms. 179 180 @type wavelengthMin: float 181 @param wavelengthMin: minimum of the wavelength range of the passband 182 @type wavelengthMax: float 183 @param wavelengthMax: maximum of the wavelength range of the passband 184 @type normalise: bool 185 @param normalise: if True, scale such that total area under the passband over the wavelength 186 range is 1. 187 188 """ 189 190 self.wavelength=numpy.arange(wavelengthMin, wavelengthMax+10, 10, dtype = float) 191 self.transmission=numpy.ones(self.wavelength.shape, dtype = float) 192 193 if normalise == True: 194 self.transmission=self.transmission/numpy.trapz(self.transmission, self.wavelength) 195 196 # Store a ready-to-go interpolation object to speed calculation of fluxes up 197 self.interpolator=interpolate.interp1d(self.wavelength, self.transmission, kind='linear')
198 199 200 #------------------------------------------------------------------------------------------------------------
201 -class SED:
202 """This class describes a Spectral Energy Distribution (SED). 203 204 To create a SED object, lists (or numpy arrays) of wavelength and relative flux must be provided. The SED 205 can optionally be redshifted. The wavelength units of SEDs are assumed to be Angstroms - flux 206 calculations using Passband and SED objects specified with different wavelength units will be incorrect. 207 208 The L{StellarPopulation} class (and derivatives) can be used to extract SEDs for specified ages from e.g. 209 the Bruzual & Charlot 2003 or Maraston 2005 models. 210 211 """ 212
213 - def __init__(self, wavelength = [], flux = [], z = 0.0, ageGyr = None, normalise = False, label = None):
214 215 # We keep a copy of the wavelength, flux at z = 0, as it's more robust to copy that 216 # to self.wavelength, flux and redshift it, rather than repeatedly redshifting the same 217 # arrays back and forth 218 self.z0wavelength=numpy.array(wavelength) 219 self.z0flux=numpy.array(flux) 220 self.wavelength=numpy.array(wavelength) 221 self.flux=numpy.array(flux) 222 self.z=z 223 self.label=label # plain text label, handy for using in photo-z codes 224 225 # Store the intrinsic (i.e. unextincted) flux in case we change extinction 226 self.EBMinusV=0.0 227 self.intrinsic_z0flux=numpy.array(flux) 228 229 if normalise == True: 230 self.normalise() 231 232 if z != 0.0: 233 self.redshift(z) 234 235 self.ageGyr=ageGyr
236 237
238 - def copy(self):
239 """Copies the SED, returning a new SED object 240 241 @rtype: L{SED} object 242 @return: SED 243 244 """ 245 246 newSED=SED(wavelength = self.z0wavelength, flux = self.z0flux, z = self.z, ageGyr = self.ageGyr, 247 normalise = False, label = self.label) 248 249 return newSED
250 251
252 - def loadFromFile(self, fileName):
253 """Loads SED from a white space delimited file in the format wavelength, flux. Lines beginning with 254 # are ignored. 255 256 @type fileName: string 257 @param fileName: path to file containing wavelength, flux data 258 259 """ 260 261 inFile=open(fileName, "r") 262 lines=inFile.readlines() 263 inFile.close() 264 wavelength=[] 265 flux=[] 266 wholeLines=[] 267 for line in lines: 268 if line[0] != "#" and len(line) > 3: 269 bits=line.split() 270 wavelength.append(float(bits[0])) 271 flux.append(float(bits[1])) 272 273 # Sort SED so wavelength is in ascending order 274 if wavelength[0] > wavelength[-1]: 275 wavelength.reverse() 276 flux.reverse() 277 278 self.z0wavelength=numpy.array(wavelength) 279 self.z0flux=numpy.array(flux) 280 self.wavelength=numpy.array(wavelength) 281 self.flux=numpy.array(flux)
282
283 - def writeToFile(self, fileName):
284 """Writes SED to a white space delimited file in the format wavelength, flux. 285 286 @type fileName: string 287 @param fileName: path to file 288 289 """ 290 291 outFile=open(fileName, "w") 292 for l, f in zip(self.wavelength, self.flux): 293 outFile.write(str(l)+" "+str(f)+"\n") 294 outFile.close()
295
296 - def asList(self):
297 """Returns a two dimensional list of [wavelength, flux], suitable for plotting by gnuplot. 298 299 @rtype: list 300 @return: list in format [wavelength, flux] 301 302 """ 303 304 listData=[] 305 for l, f in zip(self.wavelength, self.flux): 306 listData.append([l, f]) 307 308 return listData
309
310 - def plot(self, xmin = 'min', xmax = 'max'):
311 """Produces a simple (wavelength, flux) plot of the SED. 312 313 @type xmin: float or 'min' 314 @param xmin: minimum of the wavelength range of the plot 315 @type xmax: float or 'max' 316 @param xmax: maximum of the wavelength range of the plot 317 318 """ 319 320 pylab.matplotlib.interactive(True) 321 pylab.plot(self.wavelength, self.flux) 322 323 if xmin == 'min': 324 xmin=self.wavelength.min() 325 if xmax == 'max': 326 xmax=self.wavelength.max() 327 328 # Sensible y scale 329 plotMask=numpy.logical_and(numpy.greater(self.wavelength, xmin), numpy.less(self.wavelength, xmax)) 330 plotMax=self.flux[plotMask].max() 331 pylab.ylim(0, plotMax*1.1) 332 pylab.xlim(xmin, xmax) 333 pylab.xlabel("Wavelength") 334 pylab.ylabel("Relative Flux")
335
336 - def integrate(self, wavelengthMin = 'min', wavelengthMax = 'max'):
337 """Calculates flux in SED within given wavelength range. 338 339 @type wavelengthMin: float or 'min' 340 @param wavelengthMin: minimum of the wavelength range 341 @type wavelengthMax: float or 'max' 342 @param wavelengthMax: maximum of the wavelength range 343 @rtype: float 344 @return: relative flux 345 346 """ 347 348 if wavelengthMin == 'min': 349 wavelengthMin=self.wavelength.min() 350 if wavelengthMax == 'max': 351 wavelengthMax=self.wavelength.max() 352 353 mask=numpy.logical_and(numpy.greater(self.wavelength, wavelengthMin), \ 354 numpy.less(self.wavelength, wavelengthMax)) 355 flux=numpy.trapz(self.flux[mask], self.wavelength[mask]) 356 357 return flux
358
359 - def smooth(self, smoothPix):
360 """Smooths SED.flux with a uniform (boxcar) filter of width smoothPix. Cannot be undone. 361 362 @type smoothPix: int 363 @param smoothPix: size of uniform filter applied to SED, in pixels 364 365 """ 366 smoothed=ndimage.uniform_filter1d(self.flux, smoothPix) 367 self.flux=smoothed
368
369 - def redshift(self, z):
370 """Redshifts the SED to redshift z. 371 372 @type z: float 373 @param z: redshift 374 375 """ 376 377 # We have to conserve energy so the area under the redshifted SED has to be equal to 378 # the area under the unredshifted SED, otherwise magnitude calculations will be wrong 379 # when comparing SEDs at different zs 380 self.wavelength=numpy.zeros(self.z0wavelength.shape[0]) 381 self.flux=numpy.zeros(self.z0flux.shape[0]) 382 self.wavelength=self.wavelength+self.z0wavelength 383 self.flux=self.flux+self.z0flux 384 385 z0TotalFlux=numpy.trapz(self.z0wavelength, self.z0flux) 386 self.wavelength=self.wavelength*(1.0+z) 387 zTotalFlux=numpy.trapz(self.wavelength, self.flux) 388 self.flux=self.flux*(z0TotalFlux/zTotalFlux) 389 self.z=z
390
391 - def normalise(self, minWavelength = 'min', maxWavelength = 'max'):
392 """Normalises the SED such that the area under the specified wavelength range is equal to 1. 393 394 @type minWavelength: float or 'min' 395 @param minWavelength: minimum wavelength of range over which to normalise SED 396 @type maxWavelength: float or 'max' 397 @param maxWavelength: maximum wavelength of range over which to normalise SED 398 399 """ 400 if minWavelength == 'min': 401 minWavelength=self.wavelength.min() 402 if maxWavelength == 'max': 403 maxWavelength=self.wavelength.max() 404 405 lowCut=numpy.greater(self.wavelength, minWavelength) 406 highCut=numpy.less(self.wavelength, maxWavelength) 407 totalCut=numpy.logical_and(lowCut, highCut) 408 sedFluxSlice=self.flux[totalCut] 409 sedWavelengthSlice=self.wavelength[totalCut] 410 411 self.flux=self.flux/numpy.trapz(abs(sedFluxSlice), sedWavelengthSlice)#self.wavelength)
412
413 - def normaliseToMag(self, ABMag, passband):
414 """Normalises the SED to match the flux equivalent to the given AB magnitude in the given passband. 415 416 @type ABMag: float 417 @param ABMag: AB magnitude to which the SED is to be normalised at the given passband 418 @type passband: an L{Passband} object 419 @param passband: passband at which normalisation to AB magnitude is calculated 420 421 """ 422 423 magFlux=mag2Flux(ABMag, 0.0, passband) 424 sedFlux=self.calcFlux(passband) 425 norm=magFlux[0]/sedFlux 426 self.flux=self.flux*norm 427 self.z0flux=self.z0flux*norm
428
429 - def matchFlux(self, matchSED, minWavelength, maxWavelength):
430 """Matches the flux in the wavelength range given by minWavelength, maxWavelength to the 431 flux in the same region in matchSED. Useful for plotting purposes. 432 433 @type matchSED: L{SED} object 434 @param matchSED: SED to match flux to 435 @type minWavelength: float 436 @param minWavelength: minimum of range in which to match flux of current SED to matchSED 437 @type maxWavelength: float 438 @param maxWavelength: maximum of range in which to match flux of current SED to matchSED 439 440 """ 441 442 interpMatch=interpolate.interp1d(matchSED.wavelength, matchSED.flux, kind='linear') 443 interpSelf=interpolate.interp1d(self.wavelength, self.flux, kind='linear') 444 445 wavelengthRange=numpy.arange(minWavelength, maxWavelength, 5.0) 446 447 matchFlux=numpy.trapz(interpMatch(wavelengthRange), wavelengthRange) 448 selfFlux=numpy.trapz(interpSelf(wavelengthRange), wavelengthRange) 449 450 self.flux=self.flux*(matchFlux/selfFlux)
451 452
453 - def calcFlux(self, passband):
454 """Calculates flux in the given passband. 455 456 @type passband: L{Passband} object 457 @param passband: filter passband through which to calculate the flux from the SED 458 @rtype: float 459 @return: flux 460 461 """ 462 lowCut=numpy.greater(self.wavelength, passband.wavelength.min()) 463 highCut=numpy.less(self.wavelength, passband.wavelength.max()) 464 totalCut=numpy.logical_and(lowCut, highCut) 465 sedFluxSlice=self.flux[totalCut] 466 sedWavelengthSlice=self.wavelength[totalCut] 467 468 # Use linear interpolation to rebin the passband to the same dimensions as the 469 # part of the SED we're interested in 470 sedInBand=passband.interpolator(sedWavelengthSlice)*sedFluxSlice 471 totalFlux=numpy.trapz(sedInBand*sedWavelengthSlice, sedWavelengthSlice) 472 totalFlux=totalFlux/numpy.trapz(passband.interpolator(sedWavelengthSlice)\ 473 *sedWavelengthSlice, sedWavelengthSlice) 474 475 return totalFlux
476
477 - def calcMag(self, passband, addDistanceModulus = True, magType = "Vega"):
478 """Calculates magnitude in the given passband. If addDistanceModulus == True, 479 then the distance modulus (5.0*log10*(dl*1e5), where dl is the luminosity distance 480 in Mpc at the redshift of the L{SED}) is added. 481 482 @type passband: L{Passband} object 483 @param passband: filter passband through which to calculate the magnitude from the SED 484 @type addDistanceModulus: bool 485 @param addDistanceModulus: if True, adds 5.0*log10*(dl*1e5) to the mag returned, where 486 dl is the luminosity distance (Mpc) corresponding to the SED z 487 @type magType: string 488 @param magType: either "Vega" or "AB" 489 @rtype: float 490 @return: magnitude through the given passband on the specified magnitude system 491 492 """ 493 f1=self.calcFlux(passband) 494 if magType == "Vega": 495 f2=VEGA.calcFlux(passband) 496 elif magType == "AB": 497 f2=AB.calcFlux(passband) 498 499 mag=-2.5*math.log10(f1/f2) 500 if magType == "Vega": 501 mag=mag+0.026 # Add 0.026 because Vega has V=0.026 (e.g. Bohlin & Gilliland 2004) 502 503 if self.z > 0.0 and addDistanceModulus == True: 504 appMag=5.0*math.log10(astCalc.dl(self.z)*1e5)+mag 505 else: 506 appMag=mag 507 508 return appMag
509
510 - def calcColour(self, passband1, passband2, magType = "Vega"):
511 """Calculates the colour passband1-passband2. 512 513 @type passband1: L{Passband} object 514 @param passband1: filter passband through which to calculate the first magnitude 515 @type passband2: L{Passband} object 516 @param passband1: filter passband through which to calculate the second magnitude 517 @type magType: string 518 @param magType: either "Vega" or "AB" 519 @rtype: float 520 @return: colour defined by passband1 - passband2 on the specified magnitude system 521 522 """ 523 mag1=self.calcMag(passband1, magType = magType, addDistanceModulus = True) 524 mag2=self.calcMag(passband2, magType = magType, addDistanceModulus = True) 525 526 colour=mag1-mag2 527 return colour
528
529 - def getSEDDict(self, passbands):
530 """This is a convenience function for pulling out fluxes from a SED for a given set of passbands 531 in the same format as made by L{mags2SEDDict} - designed to make fitting code simpler. 532 533 @type passbands: list of L{Passband} objects 534 @param passbands: list of passbands through which fluxes will be calculated 535 536 """ 537 538 flux=[] 539 wavelength=[] 540 for p in passbands: 541 flux.append(self.calcFlux(p)) 542 wavelength.append(p.effectiveWavelength()) 543 544 SEDDict={} 545 SEDDict['flux']=numpy.array(flux) 546 SEDDict['wavelength']=numpy.array(wavelength) 547 548 return SEDDict
549
550 - def extinctionCalzetti(self, EBMinusV):
551 """Applies the Calzetti et al. 2000 (ApJ, 533, 682) extinction law to the SED with the given 552 E(B-V) amount of extinction. R_v' = 4.05 is assumed (see equation (5) of Calzetti et al.). 553 554 @type EBMinusV: float 555 @param EBMinusV: extinction E(B-V), in magnitudes 556 557 """ 558 559 self.EBMinusV=EBMinusV 560 561 # All done in rest frame 562 self.z0flux=self.intrinsic_z0flux 563 564 # Allow us to set EBMinusV == 0 to turn extinction off 565 if EBMinusV > 0: 566 # Note that EBMinusV is assumed to be Es as in equations (2) - (5) 567 # Note here wavelength units have to be microns for constants to make sense 568 RvPrime=4.05 # equation (5) of Calzetti et al. 2000 569 shortWavelengthMask=numpy.logical_and(numpy.greater_equal(self.z0wavelength, 1200), \ 570 numpy.less(self.z0wavelength, 6300)) 571 longWavelengthMask=numpy.logical_and(numpy.greater_equal(self.z0wavelength, 6300), \ 572 numpy.less_equal(self.z0wavelength, 22000)) 573 wavelengthMicrons=numpy.array(self.z0wavelength/10000.0, dtype=numpy.float64) 574 kPrime=numpy.zeros(self.z0wavelength.shape[0], dtype=numpy.float64) 575 kPrimeLong=(2.659*(-1.857 \ 576 +1.040/wavelengthMicrons \ 577 ))+RvPrime 578 kPrimeShort=(2.659*(-2.156 \ 579 +1.509/wavelengthMicrons \ 580 -0.198/wavelengthMicrons**2 \ 581 +0.011/wavelengthMicrons**3 \ 582 ))+RvPrime 583 kPrime[longWavelengthMask]=kPrimeLong[longWavelengthMask] 584 kPrime[shortWavelengthMask]=kPrimeShort[shortWavelengthMask] 585 586 # Here we extrapolate kPrime in similar way to what HYPERZ does 587 # Short wavelengths 588 try: 589 interpolator=interpolate.interp1d(self.z0wavelength, kPrimeShort, kind='linear') 590 slope=(interpolator(1100.0)-interpolator(1200.0))/(1100.0-1200.0) 591 intercept=interpolator(1200.0)-(slope*1200.0) 592 mask=numpy.less(self.z0wavelength, 1200.0) 593 kPrime[mask]=slope*self.z0wavelength[mask]+intercept 594 595 # Long wavelengths 596 interpolator=interpolate.interp1d(self.z0wavelength, kPrimeLong, kind='linear') 597 slope=(interpolator(21900.0)-interpolator(22000.0))/(21900.0-22000.0) 598 intercept=interpolator(21900.0)-(slope*21900.0) 599 mask=numpy.greater(self.z0wavelength, 22000.0) 600 kPrime[mask]=slope*self.z0wavelength[mask]+intercept 601 except: 602 raise Exception("This SED has a wavelength range that doesn't cover ~1200-22000 Angstroms") 603 604 # Never let go negative 605 kPrime[numpy.less_equal(kPrime, 0.0)]=1e-6 606 607 reddening=numpy.power(10, 0.4*EBMinusV*kPrime) 608 self.z0flux=self.z0flux/reddening 609 610 self.redshift(self.z)
611 612 #------------------------------------------------------------------------------------------------------------
613 -class VegaSED(SED):
614 """This class stores the SED of Vega, used for calculation of magnitudes on the Vega system. 615 616 The Vega SED used is taken from Bohlin 2007 (http://adsabs.harvard.edu/abs/2007ASPC..364..315B), and is 617 available from the STScI CALSPEC library (http://www.stsci.edu/hst/observatory/cdbs/calspec.html). 618 619 """ 620
621 - def __init__(self, normalise = False):
622 623 VEGA_SED_PATH=astLib.__path__[0]+os.path.sep+"data"+os.path.sep+"bohlin2006_Vega.sed" # from HST CALSPEC 624 625 inFile=open(VEGA_SED_PATH, "r") 626 lines=inFile.readlines() 627 628 wavelength=[] 629 flux=[] 630 for line in lines: 631 632 if line[0] != "#" and len(line) > 3: 633 634 bits=line.split() 635 flux.append(float(bits[1])) 636 wavelength.append(float(bits[0])) 637 638 self.wavelength=numpy.array(wavelength) 639 self.flux=numpy.array(flux, dtype=numpy.float64) 640 641 # We may want to redshift reference SEDs to calculate rest-frame colors from SEDs at different zs 642 self.z0wavelength=numpy.array(wavelength) 643 self.z0flux=numpy.array(flux, dtype=numpy.float64) 644 self.z=0.0
645 646 #if normalise == True: 647 #self.flux=self.flux/numpy.trapz(self.flux, self.wavelength) 648 #self.z0flux=self.z0flux/numpy.trapz(self.z0flux, self.z0wavelength) 649 650 #------------------------------------------------------------------------------------------------------------
651 -class StellarPopulation:
652 """This class describes a stellar population model, either a Simple Stellar Population (SSP) or a 653 Composite Stellar Population (CSP), such as the models of Bruzual & Charlot 2003 or Maraston 2005. 654 655 The constructor for this class can be used for generic SSPs or CSPs stored in white space delimited text 656 files, containing columns for age, wavelength, and flux. Columns are counted from 0 ... n. Lines starting 657 with # are ignored. 658 659 The classes L{M05Model} (for Maraston 2005 models), L{BC03Model} (for Bruzual & Charlot 2003 models), and 660 L{P09Model} (for Percival et al. 2009 models) are derived from this class. The only difference between 661 them is the code used to load in the model data. 662 663 """
664 - def __init__(self, fileName, ageColumn = 0, wavelengthColumn = 1, fluxColumn = 2):
665 666 inFile=open(fileName, "r") 667 lines=inFile.readlines() 668 inFile.close() 669 670 self.fileName=fileName 671 672 # Extract a list of model ages and valid wavelengths from the file 673 self.ages=[] 674 self.wavelengths=[] 675 for line in lines: 676 if line[0] !="#" and len(line) > 3: 677 bits=line.split() 678 age=float(bits[ageColumn]) 679 wavelength=float(bits[wavelengthColumn]) 680 if age not in self.ages: 681 self.ages.append(age) 682 if wavelength not in self.wavelengths: 683 self.wavelengths.append(wavelength) 684 685 # Construct a grid of flux - rows correspond to each wavelength, columns to age 686 self.fluxGrid=numpy.zeros([len(self.ages), len(self.wavelengths)]) 687 for line in lines: 688 if line[0] !="#" and len(line) > 3: 689 bits=line.split() 690 sedAge=float(bits[ageColumn]) 691 sedWavelength=float(bits[wavelengthColumn]) 692 sedFlux=float(bits[fluxColumn]) 693 694 row=self.ages.index(sedAge) 695 column=self.wavelengths.index(sedWavelength) 696 697 self.fluxGrid[row][column]=sedFlux
698
699 - def getSED(self, ageGyr, z = 0.0, normalise = False, label = None):
700 """Extract a SED for given age. Do linear interpolation between models if necessary. 701 702 @type ageGyr: float 703 @param ageGyr: age of the SED in Gyr 704 @type z: float 705 @param z: redshift the SED from z = 0 to z = z 706 @type normalise: bool 707 @param normalise: normalise the SED to have area 1 708 @rtype: L{SED} object 709 @return: SED 710 711 """ 712 713 if ageGyr in self.ages: 714 715 flux=self.fluxGrid[self.ages.index(ageGyr)] 716 sed=SED(self.wavelengths, flux, z = z, normalise = normalise, label = label) 717 return sed 718 719 else: 720 721 # Use interpolation, iterating over each wavelength column 722 flux=[] 723 for i in range(len(self.wavelengths)): 724 interpolator=interpolate.interp1d(self.ages, self.fluxGrid[:,i], kind='linear') 725 sedFlux=interpolator(ageGyr) 726 flux.append(sedFlux) 727 sed=SED(self.wavelengths, flux, z = z, normalise = normalise, label = label) 728 return sed
729
730 - def getColourEvolution(self, passband1, passband2, zFormation, zStepSize = 0.05, magType = "Vega"):
731 """Calculates the evolution of the colour observed through passband1 - passband2 for the 732 StellarPopulation with redshift, from z = 0 to z = zFormation. 733 734 @type passband1: L{Passband} object 735 @param passband1: filter passband through which to calculate the first magnitude 736 @type passband2: L{Passband} object 737 @param passband2: filter passband through which to calculate the second magnitude 738 @type zFormation: float 739 @param zFormation: formation redshift of the StellarPopulation 740 @type zStepSize: float 741 @param zStepSize: size of interval in z at which to calculate model colours 742 @type magType: string 743 @param magType: either "Vega" or "AB" 744 @rtype: dictionary 745 @return: dictionary of numpy.arrays in format {'z', 'colour'} 746 747 """ 748 749 zSteps=int(math.ceil(zFormation/zStepSize)) 750 zData=[] 751 colourData=[] 752 for i in range(1, zSteps): 753 zc=i*zStepSize 754 age=astCalc.tl(zFormation)-astCalc.tl(zc) 755 sed=self.getSED(age, z = zc) 756 colour=sed.calcColour(passband1, passband2, magType = magType) 757 zData.append(zc) 758 colourData.append(colour) 759 760 zData=numpy.array(zData) 761 colourData=numpy.array(colourData) 762 763 return {'z': zData, 'colour': colourData}
764
765 - def getMagEvolution(self, passband, magNormalisation, zNormalisation, zFormation, zStepSize = 0.05, 766 onePlusZSteps = False, magType = "Vega"):
767 """Calculates the evolution with redshift (from z = 0 to z = zFormation) of apparent magnitude 768 in the observed frame through the passband for the StellarPopulation, normalised to magNormalisation 769 (apparent) at z = zNormalisation. 770 771 @type passband: L{Passband} object 772 @param passband: filter passband through which to calculate the magnitude 773 @type magNormalisation: float 774 @param magNormalisation: sets the apparent magnitude of the SED at zNormalisation 775 @type zNormalisation: float 776 @param zNormalisation: the redshift at which the magnitude normalisation is carried out 777 @type zFormation: float 778 @param zFormation: formation redshift of the StellarPopulation 779 @type zStepSize: float 780 @param zStepSize: size of interval in z at which to calculate model magnitudes 781 @type onePlusZSteps: bool 782 @param onePlusZSteps: if True, zSteps are (1+z)*zStepSize, otherwise zSteps are linear 783 @type magType: string 784 @param magType: either "Vega" or "AB" 785 @rtype: dictionary 786 @return: dictionary of numpy.arrays in format {'z', 'mag'} 787 788 """ 789 790 # Count upwards in z steps as interpolation doesn't work if array ordered z decreasing 791 zSteps=int(math.ceil(zFormation/zStepSize)) 792 zData=[] 793 magData=[] 794 absMagData=[] 795 zc0=0.0 796 for i in range(1, zSteps): 797 if onePlusZSteps == False: 798 zc=i*zStepSize 799 else: 800 zc=zc0+(1+zc0)*zStepSize 801 zc0=zc 802 if zc >= zFormation: 803 break 804 age=astCalc.tl(zFormation)-astCalc.tl(zc) 805 sed=self.getSED(age, z = zc) 806 mag=sed.calcMag(passband, magType = magType, addDistanceModulus = True) 807 zData.append(zc) 808 magData.append(mag) 809 absMagData.append(sed.calcMag(passband, addDistanceModulus = False)) 810 811 zData=numpy.array(zData) 812 magData=numpy.array(magData) 813 814 # Do the normalisation 815 interpolator=interpolate.interp1d(zData, magData, kind='linear') 816 modelNormMag=interpolator(zNormalisation) 817 normConstant=magNormalisation-modelNormMag 818 magData=magData+normConstant 819 820 return {'z': zData, 'mag': magData}
821
822 - def calcEvolutionCorrection(self, zFrom, zTo, zFormation, passband, magType = "Vega"):
823 """Calculates the evolution correction in magnitudes in the rest frame through the passband 824 from redshift zFrom to redshift zTo, where the stellarPopulation is assumed to be formed 825 at redshift zFormation. 826 827 @type zFrom: float 828 @param zFormation: redshift to evolution correct from 829 @type zTo: float 830 @param zTo: redshift to evolution correct to 831 @type zFormation: float 832 @param zFormation: formation redshift of the StellarPopulation 833 @type passband: L{Passband} object 834 @param passband: filter passband through which to calculate magnitude 835 @type magType: string 836 @param magType: either "Vega" or "AB" 837 @rtype: float 838 @return: evolution correction in magnitudes in the rest frame 839 840 """ 841 842 ageFrom=astCalc.tl(zFormation)-astCalc.tl(zFrom) 843 ageTo=astCalc.tl(zFormation)-astCalc.tl(zTo) 844 845 fromSED=self.getSED(ageFrom) 846 toSED=self.getSED(ageTo) 847 848 fromMag=fromSED.calcMag(passband, magType = magType, addDistanceModulus = False) 849 toMag=toSED.calcMag(passband, magType = magType, addDistanceModulus = False) 850 851 return fromMag-toMag
852 853 #------------------------------------------------------------------------------------------------------------
854 -class M05Model(StellarPopulation):
855 """This class describes a Maraston 2005 stellar population model. To load a composite stellar population 856 model (CSP) for a tau = 0.1 Gyr burst of star formation, solar metallicity, Salpeter IMF: 857 858 m05csp = astSED.M05Model(M05_DIR+"/csp_e_0.10_z02_salp.sed_agb") 859 860 where M05_DIR is set to point to the directory where the Maraston 2005 models are stored on your system. 861 862 The file format of the Maraston 2005 simple stellar poulation (SSP) models is different to the file 863 format used for the CSPs, and this needs to be specified using the fileType parameter. To load a SSP with 864 solar metallicity, red horizontal branch morphology: 865 866 m05ssp = astSED.M05Model(M05_DIR+"/sed.ssz002.rhb", fileType = "ssp") 867 868 The wavelength units of SEDs from M05 models are Angstroms, with flux in units of erg/s/Angstrom. 869 870 """
871 - def __init__(self, fileName, fileType = "csp"):
872 873 self.modelFamily="M05" 874 875 inFile=open(fileName, "r") 876 lines=inFile.readlines() 877 inFile.close() 878 879 self.fileName=fileName 880 881 if fileType == "csp": 882 ageColumn=0 883 wavelengthColumn=1 884 fluxColumn=2 885 elif fileType == "ssp": 886 ageColumn=0 887 wavelengthColumn=2 888 fluxColumn=3 889 else: 890 raise Exception("fileType must be 'ssp' or 'csp'") 891 892 # Extract a list of model ages and valid wavelengths from the file 893 self.ages=[] 894 self.wavelengths=[] 895 for line in lines: 896 if line[0] !="#" and len(line) > 3: 897 bits=line.split() 898 age=float(bits[ageColumn]) 899 wavelength=float(bits[wavelengthColumn]) 900 if age not in self.ages: 901 self.ages.append(age) 902 if wavelength not in self.wavelengths: 903 self.wavelengths.append(wavelength) 904 905 # Construct a grid of flux - rows correspond to each wavelength, columns to age 906 self.fluxGrid=numpy.zeros([len(self.ages), len(self.wavelengths)]) 907 for line in lines: 908 if line[0] !="#" and len(line) > 3: 909 bits=line.split() 910 sedAge=float(bits[ageColumn]) 911 sedWavelength=float(bits[wavelengthColumn]) 912 sedFlux=float(bits[fluxColumn]) 913 914 row=self.ages.index(sedAge) 915 column=self.wavelengths.index(sedWavelength) 916 917 self.fluxGrid[row][column]=sedFlux
918 919 #------------------------------------------------------------------------------------------------------------
920 -class BC03Model(StellarPopulation):
921 """This class describes a Bruzual & Charlot 2003 stellar population model, extracted from a GALAXEV .ised 922 file using the galaxevpl program that is included in GALAXEV. The file format is white space delimited, 923 with wavelength in the first column. Subsequent columns contain the model fluxes for SEDs of different 924 ages, as specified when running galaxevpl. The age corresponding to each flux column is taken from the 925 comment line beginning "# Age (yr)", and is converted to Gyr. 926 927 For example, to load a tau = 0.1 Gyr burst of star formation, solar metallicity, Salpeter IMF model 928 stored in a file (created by galaxevpl) called "csp_lr_solar_0p1Gyr.136": 929 930 bc03model = BC03Model("csp_lr_solar_0p1Gyr.136") 931 932 The wavelength units of SEDs from BC03 models are Angstroms. Flux is converted into units of 933 erg/s/Angstrom (the units in the files output by galaxevpl are LSun/Angstrom). 934 935 """ 936
937 - def __init__(self, fileName):
938 939 self.modelFamily="BC03" 940 self.fileName=fileName 941 942 inFile=open(fileName, "r") 943 lines=inFile.readlines() 944 inFile.close() 945 946 # Extract a list of model ages - BC03 ages are in years, so convert to Gyr 947 self.ages=[] 948 for line in lines: 949 if line.find("# Age (yr)") != -1: 950 rawAges=line[line.find("# Age (yr)")+10:].split() 951 for age in rawAges: 952 self.ages.append(float(age)/1e9) 953 954 # Extract a list of valid wavelengths from the file 955 # If we have many ages in the file, this is more complicated... 956 lambdaLinesCount=0 957 startFluxDataLine=None 958 for i in range(len(lines)): 959 line=lines[i] 960 if "# Lambda(A)" in line: 961 lambdaLinesCount=lambdaLinesCount+1 962 if line[0] != "#" and len(line) > 3 and startFluxDataLine == None: 963 startFluxDataLine=i 964 self.wavelengths=[] 965 for i in range(startFluxDataLine, len(lines), lambdaLinesCount): 966 line=lines[i] 967 bits=line.split() 968 self.wavelengths.append(float(bits[0])) 969 970 # Construct a grid of flux - rows correspond to each wavelength, columns to age 971 self.fluxGrid=numpy.zeros([len(self.ages), len(self.wavelengths)]) 972 for i in range(startFluxDataLine, len(lines), lambdaLinesCount): 973 line=lines[i] 974 bits=[] 975 for k in range(i, i+lambdaLinesCount): 976 bits=bits+lines[k].split() 977 ageFluxes=bits[1:] 978 sedWavelength=float(bits[0]) 979 column=self.wavelengths.index(sedWavelength) 980 for row in range(len(ageFluxes)): 981 sedFlux=float(ageFluxes[row]) 982 self.fluxGrid[row][column]=sedFlux 983 984 # Convert flux into erg/s/Angstrom - native units of galaxevpl files are LSun/Angstrom 985 self.fluxGrid=self.fluxGrid*3.826e33
986 987 #------------------------------------------------------------------------------------------------------------
988 -class P09Model(StellarPopulation):
989 """This class describes a Percival et al 2009 (BaSTI; http://albione.oa-teramo.inaf.it) stellar 990 population model. We assume that the synthetic spectra for each model are unpacked under the directory 991 pointed to by fileName. 992 993 The wavelength units of SEDs from P09 models are converted to Angstroms. Flux is converted into units of 994 erg/s/Angstrom (the units in the BaSTI low-res spectra are 4.3607e-33 erg/s/m). 995 996 """ 997
998 - def __init__(self, fileName):
999 1000 self.modelFamily="P09" 1001 1002 files=glob.glob(fileName+os.path.sep+"*.t??????") 1003 1004 self.fileName=fileName 1005 1006 # Map end of filenames to ages in Gyr 1007 extensionAgeMap={} 1008 self.ages=[] 1009 for f in files: 1010 ext=f.split(".")[-1] 1011 ageGyr=float(f[-5:])/1e3 1012 self.ages.append(ageGyr) 1013 extensionAgeMap[ext]=ageGyr 1014 self.ages.sort() 1015 1016 # Construct a grid of flux - rows correspond to each wavelength, columns to age 1017 self.wavelengths=None 1018 self.fluxGrid=None 1019 for i in range(len(self.ages)): 1020 for e in extensionAgeMap.keys(): 1021 if extensionAgeMap[e] == self.ages[i]: 1022 inFileName=glob.glob(fileName+os.path.sep+"*."+e)[0] 1023 inFile=open(inFileName, "r") 1024 lines=inFile.readlines() 1025 inFile.close() 1026 wavelength=[] 1027 flux=[] 1028 for line in lines: 1029 bits=line.split() 1030 wavelength.append(float(bits[0])*10.0) # units in file are nm, not angstroms 1031 flux.append(float(bits[1])) 1032 if self.wavelengths == None: 1033 self.wavelengths=wavelength 1034 if self.fluxGrid == None: 1035 self.fluxGrid=numpy.zeros([len(self.ages), len(self.wavelengths)]) 1036 self.fluxGrid[i]=flux 1037 1038 # Convert flux into erg/s/Angstrom - native units in BaSTI files are 4.3607e-33 erg/s/m 1039 self.fluxGrid=self.fluxGrid/4.3607e-33/1e10
1040 1041 #------------------------------------------------------------------------------------------------------------
1042 -def makeModelSEDDictList(modelList, z, passbandsList, labelsList = [], EBMinusVList = [0.0], forceYoungerThanUniverse = True):
1043 """This routine makes a list of SEDDict dictionaries (see L{mags2SEDDict}) for fitting using 1044 L{fitSEDDict}. This speeds up the fitting as this allows us to calculate model SED magnitudes only once, 1045 if all objects to be fitted are at the same redshift. We add some meta data to the modelSEDDicts (e.g. 1046 the model file names). 1047 1048 The effect of extinction by dust (assuming the Calzetti et al. 2000 law) can be included by giving a list 1049 of E(B-V) values. 1050 1051 If forceYoungerThanUniverse == True, ages which are older than the universe at the given z will not be 1052 included. 1053 1054 @type modelList: list of L{StellarPopulation} model objects 1055 @param modelList: list of StellarPopulation models to include 1056 @type z: float 1057 @param z: redshift to apply to all stellar population models in modelList 1058 @type EBMinusVList: list 1059 @param EBMinusVList: list of E(B-V) extinction values to apply to all models, in magnitudes 1060 @type labelsList: list 1061 @param labelsList: optional list used for labelling passbands in output SEDDicts 1062 @type forceYoungerThanUniverse: bool 1063 @param forceYoungerThanUniverse: if True, do not allow models that exceed the age of the universe at z 1064 @rtype: list 1065 @return: list of dictionaries containing model fluxes, to be used as input to L{fitSEDDict}. 1066 1067 """ 1068 1069 # Otherwise if this is the case we won't actually make any model SEDDicts ... 1070 if EBMinusVList == []: 1071 EBMinusVList=[0.0] 1072 1073 modelSEDDictList=[] 1074 for m in range(len(modelList)): 1075 testAges=numpy.array(modelList[m].ages) 1076 if forceYoungerThanUniverse == True: 1077 testAges=testAges[numpy.logical_and(numpy.less(testAges, astCalc.tz(z)), numpy.greater(testAges, 0))] 1078 for t in testAges: 1079 s=modelList[m].getSED(t, z = z, label=modelList[m].fileName+" - age="+str(t)+" Gyr") 1080 for EBMinusV in EBMinusVList: 1081 try: 1082 s.extinctionCalzetti(EBMinusV) 1083 except: 1084 raise Exception("Model %s has a wavelength range that doesn't cover ~1200-22000 Angstroms" % (modelList[m].fileName)) 1085 modelSEDDict=s.getSEDDict(passbandsList) 1086 modelSEDDict['labels']=labelsList 1087 modelSEDDict['E(B-V)']=EBMinusV 1088 modelSEDDict['ageGyr']=t 1089 modelSEDDict['z']=z 1090 modelSEDDict['fileName']=modelList[m].fileName 1091 modelSEDDict['modelListIndex']=m 1092 modelSEDDictList.append(modelSEDDict) 1093 1094 return modelSEDDictList
1095 1096 #------------------------------------------------------------------------------------------------------------
1097 -def fitSEDDict(SEDDict, modelSEDDictList):
1098 """Fits the given SED dictionary (made using L{mags2SEDDict}) with the given list of model SED 1099 dictionaries. The latter should be made using L{makeModelSEDDictList}, and entries for fluxes should 1100 correspond directly between the model and SEDDict. 1101 1102 Returns a dictionary with best fit values. 1103 1104 @type SEDDict: dictionary, in format of L{mags2SEDDict} 1105 @param SEDDict: dictionary of observed fluxes and uncertainties, in format of L{mags2SEDDict} 1106 @type modelSEDDictList: list of dictionaries, in format of L{makeModelSEDDictList} 1107 @param modelSEDDictList: list of dictionaries containing fluxes of models to be fitted to the observed 1108 fluxes listed in the SEDDict. This should be made using L{makeModelSEDDictList}. 1109 @rtype: dictionary 1110 @return: results of the fitting - keys: 1111 - 'minChiSq': minimum chi squared value of best fit 1112 - 'chiSqContrib': corresponding contribution at each passband to the minimum chi squared value 1113 - 'ageGyr': the age in Gyr of the best fitting model 1114 - 'modelFileName': the file name of the stellar population model corresponding to the best fit 1115 - 'modelListIndex': the index of the best fitting model in the input modelSEDDictList 1116 - 'norm': the normalisation that the best fit model should be multiplied by to match the SEDDict 1117 - 'z': the redshift of the best fit model 1118 - 'E(B-V)': the extinction, E(B-V), in magnitudes, of the best fit model 1119 1120 """ 1121 1122 modelFlux=[] 1123 for modelSEDDict in modelSEDDictList: 1124 modelFlux.append(modelSEDDict['flux']) 1125 modelFlux=numpy.array(modelFlux) 1126 sedFlux=numpy.array([SEDDict['flux']]*len(modelSEDDictList)) 1127 sedFluxErr=numpy.array([SEDDict['fluxErr']]*len(modelSEDDictList)) 1128 1129 # Analytic expression below is for normalisation at minimum chi squared (see note book) 1130 norm=numpy.sum((modelFlux*sedFlux)/(sedFluxErr**2), axis=1)/numpy.sum(modelFlux**2/sedFluxErr**2, axis=1) 1131 norms=numpy.array([norm]*modelFlux.shape[1]).transpose() 1132 chiSq=numpy.sum(((sedFlux-norms*modelFlux)**2)/sedFluxErr**2, axis=1) 1133 chiSq[numpy.isnan(chiSq)]=1e6 # throw these out, should check this out and handle more gracefully 1134 minChiSq=chiSq.min() 1135 bestMatchIndex=numpy.equal(chiSq, minChiSq).nonzero()[0][0] 1136 bestNorm=norm[bestMatchIndex] 1137 bestChiSq=minChiSq 1138 bestChiSqContrib=((sedFlux[bestMatchIndex]-norms[bestMatchIndex]*modelFlux[bestMatchIndex])**2)\ 1139 /sedFluxErr[bestMatchIndex]**2 1140 1141 resultsDict={'minChiSq': bestChiSq, 1142 'chiSqContrib': bestChiSqContrib, 1143 'allChiSqValues': chiSq, 1144 'ageGyr': modelSEDDictList[bestMatchIndex]['ageGyr'], 1145 'modelFileName': modelSEDDictList[bestMatchIndex]['fileName'], 1146 'modelListIndex': modelSEDDictList[bestMatchIndex]['modelListIndex'], 1147 'norm': bestNorm, 1148 'z': modelSEDDictList[bestMatchIndex]['z'], 1149 'E(B-V)': modelSEDDictList[bestMatchIndex]['E(B-V)']} 1150 1151 return resultsDict
1152 1153 #------------------------------------------------------------------------------------------------------------
1154 -def mags2SEDDict(ABMags, ABMagErrs, passbands):
1155 """Takes a set of corresponding AB magnitudes, uncertainties, and passbands, and 1156 returns a dictionary with keys 'flux', 'fluxErr', 'wavelength'. Fluxes are in units of 1157 erg/s/cm^2/Angstrom, wavelength in Angstroms. These dictionaries are the staple diet of the 1158 L{fitSEDDict} routine. 1159 1160 @type ABMags: list or numpy array 1161 @param ABMags: AB magnitudes, specified in corresponding order to passbands and ABMagErrs 1162 @type ABMagErrs: list or numpy array 1163 @param ABMagErrs: AB magnitude errors, specified in corresponding order to passbands and ABMags 1164 @type passbands: list of L{Passband} objects 1165 @param passbands: passband objects, specified in corresponding order to ABMags and ABMagErrs 1166 @rtype: dictionary 1167 @return: dictionary with keys {'flux', 'fluxErr', 'wavelength'}, suitable for input to L{fitSEDDict} 1168 1169 """ 1170 1171 flux=[] 1172 fluxErr=[] 1173 wavelength=[] 1174 for m, e, p in zip(ABMags, ABMagErrs, passbands): 1175 f, err=mag2Flux(m, e, p) 1176 flux.append(f) 1177 fluxErr.append(err) 1178 wavelength.append(p.effectiveWavelength()) 1179 1180 SEDDict={} 1181 SEDDict['flux']=numpy.array(flux) 1182 SEDDict['fluxErr']=numpy.array(fluxErr) 1183 SEDDict['wavelength']=numpy.array(wavelength) 1184 1185 return SEDDict
1186 1187 #------------------------------------------------------------------------------------------------------------
1188 -def mag2Flux(ABMag, ABMagErr, passband):
1189 """Converts given AB magnitude and uncertainty into flux, in erg/s/cm^2/Angstrom. 1190 1191 @type ABMag: float 1192 @param ABMag: magnitude on AB system in passband 1193 @type ABMagErr: float 1194 @param ABMagErr: uncertainty in AB magnitude in passband 1195 @type passband: L{Passband} object 1196 @param passband: L{Passband} object at which ABMag was measured 1197 @rtype: list 1198 @return: [flux, fluxError], in units of erg/s/cm^2/Angstrom 1199 1200 """ 1201 1202 fluxJy=(10**23.0)*10**(-(ABMag+48.6)/2.5) # AB mag 1203 aLambda=3e-13 # for conversion to erg s-1 cm-2 angstrom-1 with lambda in microns 1204 effLMicron=passband.effectiveWavelength()*(1e-10/1e-6) 1205 fluxWLUnits=aLambda*fluxJy/effLMicron**2 1206 1207 fluxJyErr=(10**23.0)*10**(-(ABMag-ABMagErr+48.6)/2.5) # AB mag 1208 fluxWLUnitsErr=aLambda*fluxJyErr/effLMicron**2 1209 fluxWLUnitsErr=fluxWLUnitsErr-fluxWLUnits 1210 1211 return [fluxWLUnits, fluxWLUnitsErr]
1212 1213 #------------------------------------------------------------------------------------------------------------
1214 -def flux2Mag(flux, fluxErr, passband):
1215 """Converts given flux and uncertainty in erg/s/cm^2/Angstrom into AB magnitudes. 1216 1217 @type flux: float 1218 @param flux: flux in erg/s/cm^2/Angstrom in passband 1219 @type fluxErr: float 1220 @param fluxErr: uncertainty in flux in passband, in erg/s/cm^2/Angstrom 1221 @type passband: L{Passband} object 1222 @param passband: L{Passband} object at which ABMag was measured 1223 @rtype: list 1224 @return: [ABMag, ABMagError], in AB magnitudes 1225 1226 """ 1227 1228 # aLambda = 3x10-5 for effective wavelength in angstroms 1229 aLambda=3e-13 # for conversion to erg s-1 cm-2 angstrom-1 with lambda in microns 1230 effLMicron=passband.effectiveWavelength()*(1e-10/1e-6) 1231 1232 fluxJy=(flux*effLMicron**2)/aLambda 1233 mag=-2.5*numpy.log10(fluxJy/10**23)-48.6 1234 1235 fluxErrJy=(fluxErr*effLMicron**2)/aLambda 1236 magErr=mag-(-2.5*numpy.log10((fluxJy+fluxErrJy)/10**23)-48.6) 1237 1238 return [mag, magErr]
1239 1240 #------------------------------------------------------------------------------------------------------------
1241 -def mag2Jy(ABMag):
1242 """Converts an AB magnitude into flux density in Jy 1243 1244 @type ABMag: float 1245 @param ABMag: AB magnitude 1246 @rtype: float 1247 @return: flux density in Jy 1248 1249 """ 1250 1251 fluxJy=((10**23)*10**(-(float(ABMag)+48.6)/2.5)) 1252 1253 return fluxJy
1254 1255 1256 #------------------------------------------------------------------------------------------------------------
1257 -def Jy2Mag(fluxJy):
1258 """Converts flux density in Jy into AB magnitude 1259 1260 @type fluxJy: float 1261 @param fluxJy: flux density in Jy 1262 @rtype: float 1263 @return: AB magnitude 1264 1265 """ 1266 1267 ABMag=-2.5*(numpy.log10(fluxJy)-23.0)-48.6 1268 1269 return ABMag
1270 1271 #------------------------------------------------------------------------------------------------------------ 1272 # Data 1273 VEGA=VegaSED() 1274 1275 # AB SED has constant flux density 3631 Jy 1276 AB=SED(wavelength = numpy.logspace(1, 8, 1e5), flux = numpy.ones(1e6)) 1277 AB.flux=(3e-5*3631)/(AB.wavelength**2) 1278 AB.z0flux=AB.flux[:] 1279 1280 # Solar SED from HST CALSPEC (http://www.stsci.edu/hst/observatory/cdbs/calspec.html) 1281 SOL=SED() 1282 SOL.loadFromFile(astLib.__path__[0]+os.path.sep+"data"+os.path.sep+"sun_reference_stis_001.ascii") 1283

astLib-0.10.0/docs/astLib/astLib.astSED.VegaSED-class.html0000664000175000017500000002100713047255533023251 0ustar mattymatty00000000000000 astLib.astSED.VegaSED
Package astLib :: Module astSED :: Class VegaSED
[hide private]
[frames] | no frames]

Class VegaSED

source code

SED --+
      |
     VegaSED

This class stores the SED of Vega, used for calculation of magnitudes on the Vega system.

The Vega SED used is taken from Bohlin 2007 (http://adsabs.harvard.edu/abs/2007ASPC..364..315B), and is available from the STScI CALSPEC library (http://www.stsci.edu/hst/observatory/cdbs/calspec.html).

Instance Methods [hide private]
 
__init__(self, normalise=False) source code

Inherited from SED: asList, calcColour, calcFlux, calcMag, copy, extinctionCalzetti, getSEDDict, integrate, loadFromFile, matchFlux, normalise, normaliseToMag, plot, redshift, smooth, writeToFile

Method Details [hide private]

__init__(self, normalise=False)
(Constructor)

source code 
Overrides: SED.__init__

astLib-0.10.0/docs/astLib/astLib.astImages-pysrc.html0000644000175000017500000111337313047255533022670 0ustar mattymatty00000000000000 astLib.astImages
Package astLib :: Module astImages
[hide private]
[frames] | no frames]

Source Code for Module astLib.astImages

   1  """module for simple .fits image tasks (rotation, clipping out sections, making .pngs etc.) 
   2   
   3  (c) 2007-2014 Matt Hilton  
   4   
   5  U{http://astlib.sourceforge.net} 
   6   
   7  Some routines in this module will fail if, e.g., asked to clip a section from a .fits image at a 
   8  position not found within the image (as determined using the WCS). Where this occurs, the function 
   9  will return None. An error message will be printed to the console when this happens if 
  10  astImages.REPORT_ERRORS=True (the default). Testing if an astImages function returns None can be 
  11  used to handle errors in scripts.  
  12   
  13  """ 
  14   
  15  REPORT_ERRORS=True 
  16   
  17  import os 
  18  import sys 
  19  import math 
  20  from astLib import astWCS 
  21   
  22  # So far as I can tell in astropy 0.4 the API is the same as pyfits for what we need... 
  23  try: 
  24      import pyfits 
  25  except: 
  26      try: 
  27          from astropy.io import fits as pyfits 
  28      except: 
  29          raise Exception, "couldn't import either pyfits or astropy.io.fits" 
  30       
  31  try: 
  32      from scipy import ndimage 
  33      from scipy import interpolate 
  34  except ImportError: 
  35      print("WARNING: astImages: failed to import scipy.ndimage - some functions will not work.") 
  36  import numpy 
  37  try: 
  38      import matplotlib 
  39      from matplotlib import pylab 
  40      matplotlib.interactive(False) 
  41  except ImportError: 
  42      print("WARNING: astImages: failed to import matplotlib - some functions will not work.") 
  43   
  44  #--------------------------------------------------------------------------------------------------- 
45 -def clipImageSectionWCS(imageData, imageWCS, RADeg, decDeg, clipSizeDeg, returnWCS = True):
46 """Clips a square or rectangular section from an image array at the given celestial coordinates. 47 An updated WCS for the clipped section is optionally returned, as well as the x, y pixel 48 coordinates in the original image corresponding to the clipped section. 49 50 Note that the clip size is specified in degrees on the sky. For projections that have varying 51 real pixel scale across the map (e.g. CEA), use L{clipUsingRADecCoords} instead. 52 53 @type imageData: numpy array 54 @param imageData: image data array 55 @type imageWCS: astWCS.WCS 56 @param imageWCS: astWCS.WCS object 57 @type RADeg: float 58 @param RADeg: coordinate in decimal degrees 59 @type decDeg: float 60 @param decDeg: coordinate in decimal degrees 61 @type clipSizeDeg: float or list in format [widthDeg, heightDeg] 62 @param clipSizeDeg: if float, size of square clipped section in decimal degrees; if list, 63 size of clipped section in degrees in x, y axes of image respectively 64 @type returnWCS: bool 65 @param returnWCS: if True, return an updated WCS for the clipped section 66 @rtype: dictionary 67 @return: clipped image section (numpy array), updated astWCS WCS object for 68 clipped image section, and coordinates of clipped section in imageData in format 69 {'data', 'wcs', 'clippedSection'}. 70 71 """ 72 73 imHeight=imageData.shape[0] 74 imWidth=imageData.shape[1] 75 xImScale=imageWCS.getXPixelSizeDeg() 76 yImScale=imageWCS.getYPixelSizeDeg() 77 78 if type(clipSizeDeg) == float: 79 xHalfClipSizeDeg=clipSizeDeg/2.0 80 yHalfClipSizeDeg=xHalfClipSizeDeg 81 elif type(clipSizeDeg) == list or type(clipSizeDeg) == tuple: 82 xHalfClipSizeDeg=clipSizeDeg[0]/2.0 83 yHalfClipSizeDeg=clipSizeDeg[1]/2.0 84 else: 85 raise Exception("did not understand clipSizeDeg: should be float, or [widthDeg, heightDeg]") 86 87 xHalfSizePix=xHalfClipSizeDeg/xImScale 88 yHalfSizePix=yHalfClipSizeDeg/yImScale 89 90 cPixCoords=imageWCS.wcs2pix(RADeg, decDeg) 91 92 cTopLeft=[cPixCoords[0]+xHalfSizePix, cPixCoords[1]+yHalfSizePix] 93 cBottomRight=[cPixCoords[0]-xHalfSizePix, cPixCoords[1]-yHalfSizePix] 94 95 X=[int(round(cTopLeft[0])),int(round(cBottomRight[0]))] 96 Y=[int(round(cTopLeft[1])),int(round(cBottomRight[1]))] 97 98 X.sort() 99 Y.sort() 100 101 if X[0] < 0: 102 X[0]=0 103 if X[1] > imWidth: 104 X[1]=imWidth 105 if Y[0] < 0: 106 Y[0]=0 107 if Y[1] > imHeight: 108 Y[1]=imHeight 109 110 clippedData=imageData[Y[0]:Y[1],X[0]:X[1]] 111 112 # Update WCS 113 if returnWCS == True: 114 try: 115 oldCRPIX1=imageWCS.header['CRPIX1'] 116 oldCRPIX2=imageWCS.header['CRPIX2'] 117 clippedWCS=imageWCS.copy() 118 clippedWCS.header['NAXIS1']=clippedData.shape[1] 119 clippedWCS.header['NAXIS2']=clippedData.shape[0] 120 clippedWCS.header['CRPIX1']=oldCRPIX1-X[0] 121 clippedWCS.header['CRPIX2']=oldCRPIX2-Y[0] 122 clippedWCS.updateFromHeader() 123 124 except KeyError: 125 126 if REPORT_ERRORS == True: 127 128 print("WARNING: astImages.clipImageSectionWCS() : no CRPIX1, CRPIX2 keywords found - not updating clipped image WCS.") 129 130 clippedData=imageData[Y[0]:Y[1],X[0]:X[1]] 131 clippedWCS=imageWCS.copy() 132 else: 133 clippedWCS=None 134 135 return {'data': clippedData, 'wcs': clippedWCS, 'clippedSection': [X[0], X[1], Y[0], Y[1]]}
136 137 #---------------------------------------------------------------------------------------------------
138 -def clipImageSectionPix(imageData, XCoord, YCoord, clipSizePix):
139 """Clips a square or rectangular section from an image array at the given pixel coordinates. 140 141 @type imageData: numpy array 142 @param imageData: image data array 143 @type XCoord: float 144 @param XCoord: coordinate in pixels 145 @type YCoord: float 146 @param YCoord: coordinate in pixels 147 @type clipSizePix: float or list in format [widthPix, heightPix] 148 @param clipSizePix: if float, size of square clipped section in pixels; if list, 149 size of clipped section in pixels in x, y axes of output image respectively 150 @rtype: numpy array 151 @return: clipped image section 152 153 """ 154 155 imHeight=imageData.shape[0] 156 imWidth=imageData.shape[1] 157 158 if type(clipSizePix) == float or type(clipSizePix) == int: 159 xHalfClipSizePix=int(round(clipSizePix/2.0)) 160 yHalfClipSizePix=xHalfClipSizePix 161 elif type(clipSizePix) == list or type(clipSizePix) == tuple: 162 xHalfClipSizePix=int(round(clipSizePix[0]/2.0)) 163 yHalfClipSizePix=int(round(clipSizePix[1]/2.0)) 164 else: 165 raise Exception("did not understand clipSizePix: should be float, or [widthPix, heightPix]") 166 167 cTopLeft=[XCoord+xHalfClipSizePix, YCoord+yHalfClipSizePix] 168 cBottomRight=[XCoord-xHalfClipSizePix, YCoord-yHalfClipSizePix] 169 170 X=[int(round(cTopLeft[0])),int(round(cBottomRight[0]))] 171 Y=[int(round(cTopLeft[1])),int(round(cBottomRight[1]))] 172 173 X.sort() 174 Y.sort() 175 176 if X[0] < 0: 177 X[0]=0 178 if X[1] > imWidth: 179 X[1]=imWidth 180 if Y[0] < 0: 181 Y[0]=0 182 if Y[1] > imHeight: 183 Y[1]=imHeight 184 185 return imageData[Y[0]:Y[1],X[0]:X[1]]
186 187 #---------------------------------------------------------------------------------------------------
188 -def clipRotatedImageSectionWCS(imageData, imageWCS, RADeg, decDeg, clipSizeDeg, returnWCS = True):
189 """Clips a square or rectangular section from an image array at the given celestial coordinates. 190 The resulting clip is rotated and/or flipped such that North is at the top, and East appears at 191 the left. An updated WCS for the clipped section is also returned. Note that the alignment 192 of the rotated WCS is currently not perfect - however, it is probably good enough in most 193 cases for use with L{ImagePlot} for plotting purposes. 194 195 Note that the clip size is specified in degrees on the sky. For projections that have varying 196 real pixel scale across the map (e.g. CEA), use L{clipUsingRADecCoords} instead. 197 198 @type imageData: numpy array 199 @param imageData: image data array 200 @type imageWCS: astWCS.WCS 201 @param imageWCS: astWCS.WCS object 202 @type RADeg: float 203 @param RADeg: coordinate in decimal degrees 204 @type decDeg: float 205 @param decDeg: coordinate in decimal degrees 206 @type clipSizeDeg: float 207 @param clipSizeDeg: if float, size of square clipped section in decimal degrees; if list, 208 size of clipped section in degrees in RA, dec. axes of output rotated image respectively 209 @type returnWCS: bool 210 @param returnWCS: if True, return an updated WCS for the clipped section 211 @rtype: dictionary 212 @return: clipped image section (numpy array), updated astWCS WCS object for 213 clipped image section, in format {'data', 'wcs'}. 214 215 @note: Returns 'None' if the requested position is not found within the image. If the image 216 WCS does not have keywords of the form CD1_1 etc., the output WCS will not be rotated. 217 218 """ 219 220 halfImageSize=imageWCS.getHalfSizeDeg() 221 imageCentre=imageWCS.getCentreWCSCoords() 222 imScale=imageWCS.getPixelSizeDeg() 223 224 if type(clipSizeDeg) == float: 225 xHalfClipSizeDeg=clipSizeDeg/2.0 226 yHalfClipSizeDeg=xHalfClipSizeDeg 227 elif type(clipSizeDeg) == list or type(clipSizeDeg) == tuple: 228 xHalfClipSizeDeg=clipSizeDeg[0]/2.0 229 yHalfClipSizeDeg=clipSizeDeg[1]/2.0 230 else: 231 raise Exception("did not understand clipSizeDeg: should be float, or [widthDeg, heightDeg]") 232 233 diagonalHalfSizeDeg=math.sqrt((xHalfClipSizeDeg*xHalfClipSizeDeg) \ 234 +(yHalfClipSizeDeg*yHalfClipSizeDeg)) 235 236 diagonalHalfSizePix=diagonalHalfSizeDeg/imScale 237 238 if RADeg>imageCentre[0]-halfImageSize[0] and RADeg<imageCentre[0]+halfImageSize[0] \ 239 and decDeg>imageCentre[1]-halfImageSize[1] and decDeg<imageCentre[1]+halfImageSize[1]: 240 241 imageDiagonalClip=clipImageSectionWCS(imageData, imageWCS, RADeg, 242 decDeg, diagonalHalfSizeDeg*2.0) 243 diagonalClip=imageDiagonalClip['data'] 244 diagonalWCS=imageDiagonalClip['wcs'] 245 246 rotDeg=diagonalWCS.getRotationDeg() 247 imageRotated=ndimage.rotate(diagonalClip, rotDeg) 248 if diagonalWCS.isFlipped() == 1: 249 imageRotated=pylab.fliplr(imageRotated) 250 251 # Handle WCS rotation 252 rotatedWCS=diagonalWCS.copy() 253 rotRadians=math.radians(rotDeg) 254 255 if returnWCS == True: 256 try: 257 258 CD11=rotatedWCS.header['CD1_1'] 259 CD21=rotatedWCS.header['CD2_1'] 260 CD12=rotatedWCS.header['CD1_2'] 261 CD22=rotatedWCS.header['CD2_2'] 262 if rotatedWCS.isFlipped() == 1: 263 CD11=CD11*-1 264 CD12=CD12*-1 265 CDMatrix=numpy.array([[CD11, CD12], [CD21, CD22]], dtype=numpy.float64) 266 267 rotRadians=rotRadians 268 rot11=math.cos(rotRadians) 269 rot12=math.sin(rotRadians) 270 rot21=-math.sin(rotRadians) 271 rot22=math.cos(rotRadians) 272 rotMatrix=numpy.array([[rot11, rot12], [rot21, rot22]], dtype=numpy.float64) 273 newCDMatrix=numpy.dot(rotMatrix, CDMatrix) 274 275 P1=diagonalWCS.header['CRPIX1'] 276 P2=diagonalWCS.header['CRPIX2'] 277 V1=diagonalWCS.header['CRVAL1'] 278 V2=diagonalWCS.header['CRVAL2'] 279 280 PMatrix=numpy.zeros((2,), dtype = numpy.float64) 281 PMatrix[0]=P1 282 PMatrix[1]=P2 283 284 # BELOW IS HOW TO WORK OUT THE NEW REF PIXEL 285 CMatrix=numpy.array([imageRotated.shape[1]/2.0, imageRotated.shape[0]/2.0]) 286 centreCoords=diagonalWCS.getCentreWCSCoords() 287 alphaRad=math.radians(centreCoords[0]) 288 deltaRad=math.radians(centreCoords[1]) 289 thetaRad=math.asin(math.sin(deltaRad)*math.sin(math.radians(V2)) + \ 290 math.cos(deltaRad)*math.cos(math.radians(V2))*math.cos(alphaRad-math.radians(V1))) 291 phiRad=math.atan2(-math.cos(deltaRad)*math.sin(alphaRad-math.radians(V1)), \ 292 math.sin(deltaRad)*math.cos(math.radians(V2)) - \ 293 math.cos(deltaRad)*math.sin(math.radians(V2))*math.cos(alphaRad-math.radians(V1))) + \ 294 math.pi 295 RTheta=(180.0/math.pi)*(1.0/math.tan(thetaRad)) 296 297 xy=numpy.zeros((2,), dtype=numpy.float64) 298 xy[0]=RTheta*math.sin(phiRad) 299 xy[1]=-RTheta*math.cos(phiRad) 300 newPMatrix=CMatrix - numpy.dot(numpy.linalg.inv(newCDMatrix), xy) 301 302 # But there's a small offset to CRPIX due to the rotatedImage being rounded to an integer 303 # number of pixels (not sure this helps much) 304 #d=numpy.dot(rotMatrix, [diagonalClip.shape[1], diagonalClip.shape[0]]) 305 #offset=abs(d)-numpy.array(imageRotated.shape) 306 307 rotatedWCS.header['NAXIS1']=imageRotated.shape[1] 308 rotatedWCS.header['NAXIS2']=imageRotated.shape[0] 309 rotatedWCS.header['CRPIX1']=newPMatrix[0] 310 rotatedWCS.header['CRPIX2']=newPMatrix[1] 311 rotatedWCS.header['CRVAL1']=V1 312 rotatedWCS.header['CRVAL2']=V2 313 rotatedWCS.header['CD1_1']=newCDMatrix[0][0] 314 rotatedWCS.header['CD2_1']=newCDMatrix[1][0] 315 rotatedWCS.header['CD1_2']=newCDMatrix[0][1] 316 rotatedWCS.header['CD2_2']=newCDMatrix[1][1] 317 rotatedWCS.updateFromHeader() 318 319 except KeyError: 320 321 if REPORT_ERRORS == True: 322 print("WARNING: astImages.clipRotatedImageSectionWCS() : no CDi_j keywords found - not rotating WCS.") 323 324 imageRotated=diagonalClip 325 rotatedWCS=diagonalWCS 326 327 imageRotatedClip=clipImageSectionWCS(imageRotated, rotatedWCS, RADeg, decDeg, clipSizeDeg) 328 329 if returnWCS == True: 330 return {'data': imageRotatedClip['data'], 'wcs': imageRotatedClip['wcs']} 331 else: 332 return {'data': imageRotatedClip['data'], 'wcs': None} 333 334 else: 335 336 if REPORT_ERRORS==True: 337 print("""ERROR: astImages.clipRotatedImageSectionWCS() : 338 RADeg, decDeg are not within imageData.""") 339 340 return None
341 342 #---------------------------------------------------------------------------------------------------
343 -def clipUsingRADecCoords(imageData, imageWCS, RAMin, RAMax, decMin, decMax, returnWCS = True):
344 """Clips a section from an image array at the pixel coordinates corresponding to the given 345 celestial coordinates. 346 347 @type imageData: numpy array 348 @param imageData: image data array 349 @type imageWCS: astWCS.WCS 350 @param imageWCS: astWCS.WCS object 351 @type RAMin: float 352 @param RAMin: minimum RA coordinate in decimal degrees 353 @type RAMax: float 354 @param RAMax: maximum RA coordinate in decimal degrees 355 @type decMin: float 356 @param decMin: minimum dec coordinate in decimal degrees 357 @type decMax: float 358 @param decMax: maximum dec coordinate in decimal degrees 359 @type returnWCS: bool 360 @param returnWCS: if True, return an updated WCS for the clipped section 361 @rtype: dictionary 362 @return: clipped image section (numpy array), updated astWCS WCS object for 363 clipped image section, and corresponding pixel coordinates in imageData in format 364 {'data', 'wcs', 'clippedSection'}. 365 366 @note: Returns 'None' if the requested position is not found within the image. 367 368 """ 369 370 imHeight=imageData.shape[0] 371 imWidth=imageData.shape[1] 372 373 xMin, yMin=imageWCS.wcs2pix(RAMin, decMin) 374 xMax, yMax=imageWCS.wcs2pix(RAMax, decMax) 375 xMin=int(round(xMin)) 376 xMax=int(round(xMax)) 377 yMin=int(round(yMin)) 378 yMax=int(round(yMax)) 379 X=[xMin, xMax] 380 X.sort() 381 Y=[yMin, yMax] 382 Y.sort() 383 384 if X[0] < 0: 385 X[0]=0 386 if X[1] > imWidth: 387 X[1]=imWidth 388 if Y[0] < 0: 389 Y[0]=0 390 if Y[1] > imHeight: 391 Y[1]=imHeight 392 393 clippedData=imageData[Y[0]:Y[1],X[0]:X[1]] 394 395 # Update WCS 396 if returnWCS == True: 397 try: 398 oldCRPIX1=imageWCS.header['CRPIX1'] 399 oldCRPIX2=imageWCS.header['CRPIX2'] 400 clippedWCS=imageWCS.copy() 401 clippedWCS.header['NAXIS1']=clippedData.shape[1] 402 clippedWCS.header['NAXIS2']=clippedData.shape[0] 403 clippedWCS.header['CRPIX1']=oldCRPIX1-X[0] 404 clippedWCS.header['CRPIX2']=oldCRPIX2-Y[0] 405 clippedWCS.updateFromHeader() 406 407 except KeyError: 408 409 if REPORT_ERRORS == True: 410 411 print("WARNING: astImages.clipUsingRADecCoords() : no CRPIX1, CRPIX2 keywords found - not updating clipped image WCS.") 412 413 clippedData=imageData[Y[0]:Y[1],X[0]:X[1]] 414 clippedWCS=imageWCS.copy() 415 else: 416 clippedWCS=None 417 418 return {'data': clippedData, 'wcs': clippedWCS, 'clippedSection': [X[0], X[1], Y[0], Y[1]]}
419 420 #---------------------------------------------------------------------------------------------------
421 -def scaleImage(imageData, imageWCS, scaleFactor):
422 """Scales image array and WCS by the given scale factor. 423 424 @type imageData: numpy array 425 @param imageData: image data array 426 @type imageWCS: astWCS.WCS 427 @param imageWCS: astWCS.WCS object 428 @type scaleFactor: float or list or tuple 429 @param scaleFactor: factor to resize image by - if tuple or list, in format 430 [x scale factor, y scale factor] 431 @rtype: dictionary 432 @return: image data (numpy array), updated astWCS WCS object for image, in format {'data', 'wcs'}. 433 434 """ 435 436 if type(scaleFactor) == int or type(scaleFactor) == float: 437 scaleFactor=[float(scaleFactor), float(scaleFactor)] 438 scaledData=ndimage.zoom(imageData, scaleFactor) 439 440 # Take care of offset due to rounding in scaling image to integer pixel dimensions 441 properDimensions=numpy.array(imageData.shape)*scaleFactor 442 offset=properDimensions-numpy.array(scaledData.shape) 443 444 # Rescale WCS 445 try: 446 oldCRPIX1=imageWCS.header['CRPIX1'] 447 oldCRPIX2=imageWCS.header['CRPIX2'] 448 CD11=imageWCS.header['CD1_1'] 449 CD21=imageWCS.header['CD2_1'] 450 CD12=imageWCS.header['CD1_2'] 451 CD22=imageWCS.header['CD2_2'] 452 except KeyError: 453 # Try the older FITS header format 454 try: 455 oldCRPIX1=imageWCS.header['CRPIX1'] 456 oldCRPIX2=imageWCS.header['CRPIX2'] 457 CD11=imageWCS.header['CDELT1'] 458 CD21=0 459 CD12=0 460 CD22=imageWCS.header['CDELT2'] 461 except KeyError: 462 if REPORT_ERRORS == True: 463 print("WARNING: astImages.rescaleImage() : no CDij or CDELT keywords found - not updating WCS.") 464 scaledWCS=imageWCS.copy() 465 return {'data': scaledData, 'wcs': scaledWCS} 466 467 CDMatrix=numpy.array([[CD11, CD12], [CD21, CD22]], dtype=numpy.float64) 468 scaleFactorMatrix=numpy.array([[1.0/scaleFactor[0], 0], [0, 1.0/scaleFactor[1]]]) 469 scaledCDMatrix=numpy.dot(scaleFactorMatrix, CDMatrix) 470 471 scaledWCS=imageWCS.copy() 472 scaledWCS.header['NAXIS1']=scaledData.shape[1] 473 scaledWCS.header['NAXIS2']=scaledData.shape[0] 474 scaledWCS.header['CRPIX1']=oldCRPIX1*scaleFactor[0]+offset[1] 475 scaledWCS.header['CRPIX2']=oldCRPIX2*scaleFactor[1]+offset[0] 476 scaledWCS.header['CD1_1']=scaledCDMatrix[0][0] 477 scaledWCS.header['CD2_1']=scaledCDMatrix[1][0] 478 scaledWCS.header['CD1_2']=scaledCDMatrix[0][1] 479 scaledWCS.header['CD2_2']=scaledCDMatrix[1][1] 480 scaledWCS.updateFromHeader() 481 482 return {'data': scaledData, 'wcs': scaledWCS}
483 484 #---------------------------------------------------------------------------------------------------
485 -def intensityCutImage(imageData, cutLevels):
486 """Creates a matplotlib.pylab plot of an image array with the specified cuts in intensity 487 applied. This routine is used by L{saveBitmap} and L{saveContourOverlayBitmap}, which both 488 produce output as .png, .jpg, etc. images. 489 490 @type imageData: numpy array 491 @param imageData: image data array 492 @type cutLevels: list 493 @param cutLevels: sets the image scaling - available options: 494 - pixel values: cutLevels=[low value, high value]. 495 - histogram equalisation: cutLevels=["histEq", number of bins ( e.g. 1024)] 496 - relative: cutLevels=["relative", cut per cent level (e.g. 99.5)] 497 - smart: cutLevels=["smart", cut per cent level (e.g. 99.5)] 498 ["smart", 99.5] seems to provide good scaling over a range of different images. 499 @rtype: dictionary 500 @return: image section (numpy.array), matplotlib image normalisation (matplotlib.colors.Normalize), in the format {'image', 'norm'}. 501 502 @note: If cutLevels[0] == "histEq", then only {'image'} is returned. 503 504 """ 505 506 oImWidth=imageData.shape[1] 507 oImHeight=imageData.shape[0] 508 509 # Optional histogram equalisation 510 if cutLevels[0]=="histEq": 511 512 imageData=histEq(imageData, cutLevels[1]) 513 anorm=pylab.Normalize(imageData.min(), imageData.max()) 514 515 elif cutLevels[0]=="relative": 516 517 # this turns image data into 1D array then sorts 518 sorted=numpy.sort(numpy.ravel(imageData)) 519 maxValue=sorted.max() 520 minValue=sorted.min() 521 522 # want to discard the top and bottom specified 523 topCutIndex=len(sorted-1) \ 524 -int(math.floor(float((100.0-cutLevels[1])/100.0)*len(sorted-1))) 525 bottomCutIndex=int(math.ceil(float((100.0-cutLevels[1])/100.0)*len(sorted-1))) 526 topCut=sorted[topCutIndex] 527 bottomCut=sorted[bottomCutIndex] 528 anorm=pylab.Normalize(bottomCut, topCut) 529 530 elif cutLevels[0]=="smart": 531 532 # this turns image data into 1Darray then sorts 533 sorted=numpy.sort(numpy.ravel(imageData)) 534 maxValue=sorted.max() 535 minValue=sorted.min() 536 numBins=10000 # 0.01 per cent accuracy 537 binWidth=(maxValue-minValue)/float(numBins) 538 histogram=ndimage.histogram(sorted, minValue, maxValue, numBins) 539 540 # Find the bin with the most pixels in it, set that as our minimum 541 # Then search through the bins until we get to a bin with more/or the same number of 542 # pixels in it than the previous one. 543 # We take that to be the maximum. 544 # This means that we avoid the traps of big, bright, saturated stars that cause 545 # problems for relative scaling 546 backgroundValue=histogram.max() 547 foundBackgroundBin=False 548 foundTopBin=False 549 lastBin=-10000 550 for i in range(len(histogram)): 551 552 if histogram[i]>=lastBin and foundBackgroundBin==True: 553 554 # Added a fudge here to stop us picking for top bin a bin within 555 # 10 percent of the background pixel value 556 if (minValue+(binWidth*i))>bottomBinValue*1.1: 557 topBinValue=minValue+(binWidth*i) 558 foundTopBin=True 559 break 560 561 if histogram[i]==backgroundValue and foundBackgroundBin==False: 562 bottomBinValue=minValue+(binWidth*i) 563 foundBackgroundBin=True 564 565 lastBin=histogram[i] 566 567 if foundTopBin==False: 568 topBinValue=maxValue 569 570 #Now we apply relative scaling to this 571 smartClipped=numpy.clip(sorted, bottomBinValue, topBinValue) 572 topCutIndex=len(smartClipped-1) \ 573 -int(math.floor(float((100.0-cutLevels[1])/100.0)*len(smartClipped-1))) 574 bottomCutIndex=int(math.ceil(float((100.0-cutLevels[1])/100.0)*len(smartClipped-1))) 575 topCut=smartClipped[topCutIndex] 576 bottomCut=smartClipped[bottomCutIndex] 577 anorm=pylab.Normalize(bottomCut, topCut) 578 else: 579 580 # Normalise using given cut levels 581 anorm=pylab.Normalize(cutLevels[0], cutLevels[1]) 582 583 if cutLevels[0]=="histEq": 584 return {'image': imageData.copy()} 585 else: 586 return {'image': imageData.copy(), 'norm': anorm}
587 588 #---------------------------------------------------------------------------------------------------
589 -def resampleToTanProjection(imageData, imageWCS, outputPixDimensions=[600, 600]):
590 """Resamples an image and WCS to a tangent plane projection. Purely for plotting purposes 591 (e.g., ensuring RA, dec. coordinate axes perpendicular). 592 593 @type imageData: numpy array 594 @param imageData: image data array 595 @type imageWCS: astWCS.WCS 596 @param imageWCS: astWCS.WCS object 597 @type outputPixDimensions: list 598 @param outputPixDimensions: [width, height] of output image in pixels 599 @rtype: dictionary 600 @return: image data (numpy array), updated astWCS WCS object for image, in format {'data', 'wcs'}. 601 602 """ 603 604 RADeg, decDeg=imageWCS.getCentreWCSCoords() 605 xPixelScale=imageWCS.getXPixelSizeDeg() 606 yPixelScale=imageWCS.getYPixelSizeDeg() 607 xSizeDeg, ySizeDeg=imageWCS.getFullSizeSkyDeg() 608 xSizePix=int(round(outputPixDimensions[0])) 609 ySizePix=int(round(outputPixDimensions[1])) 610 xRefPix=xSizePix/2.0 611 yRefPix=ySizePix/2.0 612 xOutPixScale=xSizeDeg/xSizePix 613 yOutPixScale=ySizeDeg/ySizePix 614 cardList=pyfits.CardList() 615 cardList.append(pyfits.Card('NAXIS', 2)) 616 cardList.append(pyfits.Card('NAXIS1', xSizePix)) 617 cardList.append(pyfits.Card('NAXIS2', ySizePix)) 618 cardList.append(pyfits.Card('CTYPE1', 'RA---TAN')) 619 cardList.append(pyfits.Card('CTYPE2', 'DEC--TAN')) 620 cardList.append(pyfits.Card('CRVAL1', RADeg)) 621 cardList.append(pyfits.Card('CRVAL2', decDeg)) 622 cardList.append(pyfits.Card('CRPIX1', xRefPix+1)) 623 cardList.append(pyfits.Card('CRPIX2', yRefPix+1)) 624 cardList.append(pyfits.Card('CDELT1', -xOutPixScale)) 625 cardList.append(pyfits.Card('CDELT2', xOutPixScale)) # Makes more sense to use same pix scale 626 cardList.append(pyfits.Card('CUNIT1', 'DEG')) 627 cardList.append(pyfits.Card('CUNIT2', 'DEG')) 628 newHead=pyfits.Header(cards=cardList) 629 newWCS=astWCS.WCS(newHead, mode='pyfits') 630 newImage=numpy.zeros([ySizePix, xSizePix]) 631 632 tanImage=resampleToWCS(newImage, newWCS, imageData, imageWCS, highAccuracy=True, 633 onlyOverlapping=False) 634 635 return tanImage
636 637 #---------------------------------------------------------------------------------------------------
638 -def resampleToWCS(im1Data, im1WCS, im2Data, im2WCS, highAccuracy = False, onlyOverlapping = True):
639 """Resamples data corresponding to second image (with data im2Data, WCS im2WCS) onto the WCS 640 of the first image (im1Data, im1WCS). The output, resampled image is of the pixel same 641 dimensions of the first image. This routine is for assisting in plotting - performing 642 photometry on the output is not recommended. 643 644 Set highAccuracy == True to sample every corresponding pixel in each image; otherwise only 645 every nth pixel (where n is the ratio of the image scales) will be sampled, with values 646 in between being set using a linear interpolation (much faster). 647 648 Set onlyOverlapping == True to speed up resampling by only resampling the overlapping 649 area defined by both image WCSs. 650 651 @type im1Data: numpy array 652 @param im1Data: image data array for first image 653 @type im1WCS: astWCS.WCS 654 @param im1WCS: astWCS.WCS object corresponding to im1Data 655 @type im2Data: numpy array 656 @param im2Data: image data array for second image (to be resampled to match first image) 657 @type im2WCS: astWCS.WCS 658 @param im2WCS: astWCS.WCS object corresponding to im2Data 659 @type highAccuracy: bool 660 @param highAccuracy: if True, sample every corresponding pixel in each image; otherwise, sample 661 every nth pixel, where n = the ratio of the image scales. 662 @type onlyOverlapping: bool 663 @param onlyOverlapping: if True, only consider the overlapping area defined by both image WCSs 664 (speeds things up) 665 @rtype: dictionary 666 @return: numpy image data array and associated WCS in format {'data', 'wcs'} 667 668 """ 669 670 resampledData=numpy.zeros(im1Data.shape) 671 672 # Find overlap - speed things up 673 # But have a border so as not to require the overlap to be perfect 674 # There's also no point in oversampling image 1 if it's much higher res than image 2 675 xPixRatio=(im2WCS.getXPixelSizeDeg()/im1WCS.getXPixelSizeDeg())/2.0 676 yPixRatio=(im2WCS.getYPixelSizeDeg()/im1WCS.getYPixelSizeDeg())/2.0 677 xBorder=xPixRatio*10.0 678 yBorder=yPixRatio*10.0 679 if highAccuracy == False: 680 if xPixRatio > 1: 681 xPixStep=int(math.ceil(xPixRatio)) 682 else: 683 xPixStep=1 684 if yPixRatio > 1: 685 yPixStep=int(math.ceil(yPixRatio)) 686 else: 687 yPixStep=1 688 else: 689 xPixStep=1 690 yPixStep=1 691 692 if onlyOverlapping == True: 693 overlap=astWCS.findWCSOverlap(im1WCS, im2WCS) 694 xOverlap=[overlap['wcs1Pix'][0], overlap['wcs1Pix'][1]] 695 yOverlap=[overlap['wcs1Pix'][2], overlap['wcs1Pix'][3]] 696 xOverlap.sort() 697 yOverlap.sort() 698 xMin=int(math.floor(xOverlap[0]-xBorder)) 699 xMax=int(math.ceil(xOverlap[1]+xBorder)) 700 yMin=int(math.floor(yOverlap[0]-yBorder)) 701 yMax=int(math.ceil(yOverlap[1]+yBorder)) 702 xRemainder=(xMax-xMin) % xPixStep 703 yRemainder=(yMax-yMin) % yPixStep 704 if xRemainder != 0: 705 xMax=xMax+xRemainder 706 if yRemainder != 0: 707 yMax=yMax+yRemainder 708 # Check that we're still within the image boundaries, to be on the safe side 709 if xMin < 0: 710 xMin=0 711 if xMax > im1Data.shape[1]: 712 xMax=im1Data.shape[1] 713 if yMin < 0: 714 yMin=0 715 if yMax > im1Data.shape[0]: 716 yMax=im1Data.shape[0] 717 else: 718 xMin=0 719 xMax=im1Data.shape[1] 720 yMin=0 721 yMax=im1Data.shape[0] 722 723 for x in range(xMin, xMax, xPixStep): 724 for y in range(yMin, yMax, yPixStep): 725 RA, dec=im1WCS.pix2wcs(x, y) 726 x2, y2=im2WCS.wcs2pix(RA, dec) 727 x2=int(round(x2)) 728 y2=int(round(y2)) 729 if x2 >= 0 and x2 < im2Data.shape[1] and y2 >= 0 and y2 < im2Data.shape[0]: 730 resampledData[y][x]=im2Data[y2][x2] 731 732 # linear interpolation 733 if highAccuracy == False: 734 for row in range(resampledData.shape[0]): 735 vals=resampledData[row, numpy.arange(xMin, xMax, xPixStep)] 736 index2data=interpolate.interp1d(numpy.arange(0, vals.shape[0], 1), vals) 737 interpedVals=index2data(numpy.arange(0, vals.shape[0]-1, 1.0/xPixStep)) 738 resampledData[row, xMin:xMin+interpedVals.shape[0]]=interpedVals 739 for col in range(resampledData.shape[1]): 740 vals=resampledData[numpy.arange(yMin, yMax, yPixStep), col] 741 index2data=interpolate.interp1d(numpy.arange(0, vals.shape[0], 1), vals) 742 interpedVals=index2data(numpy.arange(0, vals.shape[0]-1, 1.0/yPixStep)) 743 resampledData[yMin:yMin+interpedVals.shape[0], col]=interpedVals 744 745 # Note: should really just copy im1WCS keywords into im2WCS and return that 746 # Only a problem if we're using this for anything other than plotting 747 return {'data': resampledData, 'wcs': im1WCS.copy()}
748 749 #---------------------------------------------------------------------------------------------------
750 -def generateContourOverlay(backgroundImageData, backgroundImageWCS, contourImageData, contourImageWCS, \ 751 contourLevels, contourSmoothFactor = 0, highAccuracy = False):
752 """Rescales an image array to be used as a contour overlay to have the same dimensions as the 753 background image, and generates a set of contour levels. The image array from which the contours 754 are to be generated will be resampled to the same dimensions as the background image data, and 755 can be optionally smoothed using a Gaussian filter. The sigma of the Gaussian filter 756 (contourSmoothFactor) is specified in arcsec. 757 758 @type backgroundImageData: numpy array 759 @param backgroundImageData: background image data array 760 @type backgroundImageWCS: astWCS.WCS 761 @param backgroundImageWCS: astWCS.WCS object of the background image data array 762 @type contourImageData: numpy array 763 @param contourImageData: image data array from which contours are to be generated 764 @type contourImageWCS: astWCS.WCS 765 @param contourImageWCS: astWCS.WCS object corresponding to contourImageData 766 @type contourLevels: list 767 @param contourLevels: sets the contour levels - available options: 768 - values: contourLevels=[list of values specifying each level] 769 - linear spacing: contourLevels=['linear', min level value, max level value, number 770 of levels] - can use "min", "max" to automatically set min, max levels from image data 771 - log spacing: contourLevels=['log', min level value, max level value, number of 772 levels] - can use "min", "max" to automatically set min, max levels from image data 773 @type contourSmoothFactor: float 774 @param contourSmoothFactor: standard deviation (in arcsec) of Gaussian filter for 775 pre-smoothing of contour image data (set to 0 for no smoothing) 776 @type highAccuracy: bool 777 @param highAccuracy: if True, sample every corresponding pixel in each image; otherwise, sample 778 every nth pixel, where n = the ratio of the image scales. 779 780 """ 781 782 # For compromise between speed and accuracy, scale a copy of the background 783 # image down to a scale that is one pixel = 1/5 of a pixel in the contour image 784 # But only do this if it has CDij keywords as we know how to scale those 785 if ("CD1_1" in backgroundImageWCS.header) == True: 786 xScaleFactor=backgroundImageWCS.getXPixelSizeDeg()/(contourImageWCS.getXPixelSizeDeg()/5.0) 787 yScaleFactor=backgroundImageWCS.getYPixelSizeDeg()/(contourImageWCS.getYPixelSizeDeg()/5.0) 788 scaledBackground=scaleImage(backgroundImageData, backgroundImageWCS, (xScaleFactor, yScaleFactor)) 789 scaled=resampleToWCS(scaledBackground['data'], scaledBackground['wcs'], 790 contourImageData, contourImageWCS, highAccuracy = highAccuracy) 791 scaledContourData=scaled['data'] 792 scaledContourWCS=scaled['wcs'] 793 scaledBackground=True 794 else: 795 scaled=resampleToWCS(backgroundImageData, backgroundImageWCS, 796 contourImageData, contourImageWCS, highAccuracy = highAccuracy) 797 scaledContourData=scaled['data'] 798 scaledContourWCS=scaled['wcs'] 799 scaledBackground=False 800 801 if contourSmoothFactor > 0: 802 sigmaPix=(contourSmoothFactor/3600.0)/scaledContourWCS.getPixelSizeDeg() 803 scaledContourData=ndimage.gaussian_filter(scaledContourData, sigmaPix) 804 805 # Various ways of setting the contour levels 806 # If just a list is passed in, use those instead 807 if contourLevels[0] == "linear": 808 if contourLevels[1] == "min": 809 xMin=contourImageData.flatten().min() 810 else: 811 xMin=float(contourLevels[1]) 812 if contourLevels[2] == "max": 813 xMax=contourImageData.flatten().max() 814 else: 815 xMax=float(contourLevels[2]) 816 nLevels=contourLevels[3] 817 xStep=(xMax-xMin)/(nLevels-1) 818 cLevels=[] 819 for j in range(nLevels+1): 820 level=xMin+j*xStep 821 cLevels.append(level) 822 823 elif contourLevels[0] == "log": 824 if contourLevels[1] == "min": 825 xMin=contourImageData.flatten().min() 826 else: 827 xMin=float(contourLevels[1]) 828 if contourLevels[2] == "max": 829 xMax=contourImageData.flatten().max() 830 else: 831 xMax=float(contourLevels[2]) 832 if xMin <= 0.0: 833 raise Exception("minimum contour level set to <= 0 and log scaling chosen.") 834 xLogMin=math.log10(xMin) 835 xLogMax=math.log10(xMax) 836 nLevels=contourLevels[3] 837 xLogStep=(xLogMax-xLogMin)/(nLevels-1) 838 cLevels=[] 839 prevLevel=0 840 for j in range(nLevels+1): 841 level=math.pow(10, xLogMin+j*xLogStep) 842 cLevels.append(level) 843 844 else: 845 cLevels=contourLevels 846 847 # Now blow the contour image data back up to the size of the original image 848 if scaledBackground == True: 849 scaledBack=scaleImage(scaledContourData, scaledContourWCS, (1.0/xScaleFactor, 1.0/yScaleFactor))['data'] 850 else: 851 scaledBack=scaledContourData 852 853 return {'scaledImage': scaledBack, 'contourLevels': cLevels}
854 855 #---------------------------------------------------------------------------------------------------
856 -def saveBitmap(outputFileName, imageData, cutLevels, size, colorMapName):
857 """Makes a bitmap image from an image array; the image format is specified by the 858 filename extension. (e.g. ".jpg" =JPEG, ".png"=PNG). 859 860 @type outputFileName: string 861 @param outputFileName: filename of output bitmap image 862 @type imageData: numpy array 863 @param imageData: image data array 864 @type cutLevels: list 865 @param cutLevels: sets the image scaling - available options: 866 - pixel values: cutLevels=[low value, high value]. 867 - histogram equalisation: cutLevels=["histEq", number of bins ( e.g. 1024)] 868 - relative: cutLevels=["relative", cut per cent level (e.g. 99.5)] 869 - smart: cutLevels=["smart", cut per cent level (e.g. 99.5)] 870 ["smart", 99.5] seems to provide good scaling over a range of different images. 871 @type size: int 872 @param size: size of output image in pixels 873 @type colorMapName: string 874 @param colorMapName: name of a standard matplotlib colormap, e.g. "hot", "cool", "gray" 875 etc. (do "help(pylab.colormaps)" in the Python interpreter to see available options) 876 877 """ 878 879 cut=intensityCutImage(imageData, cutLevels) 880 881 # Make plot 882 aspectR=float(cut['image'].shape[0])/float(cut['image'].shape[1]) 883 pylab.figure(figsize=(10,10*aspectR)) 884 pylab.axes([0,0,1,1]) 885 886 try: 887 colorMap=pylab.cm.get_cmap(colorMapName) 888 except AssertionError: 889 raise Exception(colorMapName+" is not a defined matplotlib colormap.") 890 891 if cutLevels[0]=="histEq": 892 pylab.imshow(cut['image'], interpolation="bilinear", origin='lower', cmap=colorMap) 893 894 else: 895 pylab.imshow(cut['image'], interpolation="bilinear", norm=cut['norm'], origin='lower', 896 cmap=colorMap) 897 898 pylab.axis("off") 899 900 pylab.savefig("out_astImages.png") 901 pylab.close("all") 902 903 try: 904 from PIL import Image 905 except: 906 raise Exception("astImages.saveBitmap requires the Python Imaging Library to be installed.") 907 im=Image.open("out_astImages.png") 908 im.thumbnail((int(size),int(size))) 909 im.save(outputFileName) 910 911 os.remove("out_astImages.png")
912 913 #---------------------------------------------------------------------------------------------------
914 -def saveContourOverlayBitmap(outputFileName, backgroundImageData, backgroundImageWCS, cutLevels, \ 915 size, colorMapName, contourImageData, contourImageWCS, \ 916 contourSmoothFactor, contourLevels, contourColor, contourWidth):
917 """Makes a bitmap image from an image array, with a set of contours generated from a 918 second image array overlaid. The image format is specified by the file extension 919 (e.g. ".jpg"=JPEG, ".png"=PNG). The image array from which the contours are to be generated 920 can optionally be pre-smoothed using a Gaussian filter. 921 922 @type outputFileName: string 923 @param outputFileName: filename of output bitmap image 924 @type backgroundImageData: numpy array 925 @param backgroundImageData: background image data array 926 @type backgroundImageWCS: astWCS.WCS 927 @param backgroundImageWCS: astWCS.WCS object of the background image data array 928 @type cutLevels: list 929 @param cutLevels: sets the image scaling - available options: 930 - pixel values: cutLevels=[low value, high value]. 931 - histogram equalisation: cutLevels=["histEq", number of bins ( e.g. 1024)] 932 - relative: cutLevels=["relative", cut per cent level (e.g. 99.5)] 933 - smart: cutLevels=["smart", cut per cent level (e.g. 99.5)] 934 ["smart", 99.5] seems to provide good scaling over a range of different images. 935 @type size: int 936 @param size: size of output image in pixels 937 @type colorMapName: string 938 @param colorMapName: name of a standard matplotlib colormap, e.g. "hot", "cool", "gray" 939 etc. (do "help(pylab.colormaps)" in the Python interpreter to see available options) 940 @type contourImageData: numpy array 941 @param contourImageData: image data array from which contours are to be generated 942 @type contourImageWCS: astWCS.WCS 943 @param contourImageWCS: astWCS.WCS object corresponding to contourImageData 944 @type contourSmoothFactor: float 945 @param contourSmoothFactor: standard deviation (in pixels) of Gaussian filter for 946 pre-smoothing of contour image data (set to 0 for no smoothing) 947 @type contourLevels: list 948 @param contourLevels: sets the contour levels - available options: 949 - values: contourLevels=[list of values specifying each level] 950 - linear spacing: contourLevels=['linear', min level value, max level value, number 951 of levels] - can use "min", "max" to automatically set min, max levels from image data 952 - log spacing: contourLevels=['log', min level value, max level value, number of 953 levels] - can use "min", "max" to automatically set min, max levels from image data 954 @type contourColor: string 955 @param contourColor: color of the overlaid contours, specified by the name of a standard 956 matplotlib color, e.g., "black", "white", "cyan" 957 etc. (do "help(pylab.colors)" in the Python interpreter to see available options) 958 @type contourWidth: int 959 @param contourWidth: width of the overlaid contours 960 961 """ 962 963 cut=intensityCutImage(backgroundImageData, cutLevels) 964 965 # Make plot of just the background image 966 aspectR=float(cut['image'].shape[0])/float(cut['image'].shape[1]) 967 pylab.figure(figsize=(10,10*aspectR)) 968 pylab.axes([0,0,1,1]) 969 970 try: 971 colorMap=pylab.cm.get_cmap(colorMapName) 972 except AssertionError: 973 raise Exception(colorMapName+" is not a defined matplotlib colormap.") 974 975 if cutLevels[0]=="histEq": 976 pylab.imshow(cut['image'], interpolation="bilinear", origin='lower', cmap=colorMap) 977 978 else: 979 pylab.imshow(cut['image'], interpolation="bilinear", norm=cut['norm'], origin='lower', 980 cmap=colorMap) 981 982 pylab.axis("off") 983 984 # Add the contours 985 contourData=generateContourOverlay(backgroundImageData, backgroundImageWCS, contourImageData, \ 986 contourImageWCS, contourLevels, contourSmoothFactor) 987 988 pylab.contour(contourData['scaledImage'], contourData['contourLevels'], colors=contourColor, 989 linewidths=contourWidth) 990 991 pylab.savefig("out_astImages.png") 992 pylab.close("all") 993 994 try: 995 from PIL import Image 996 except: 997 raise Exception("astImages.saveContourOverlayBitmap requires the Python Imaging Library to be installed") 998 999 im=Image.open("out_astImages.png") 1000 im.thumbnail((int(size),int(size))) 1001 im.save(outputFileName) 1002 1003 os.remove("out_astImages.png")
1004 1005 #---------------------------------------------------------------------------------------------------
1006 -def saveFITS(outputFileName, imageData, imageWCS = None):
1007 """Writes an image array to a new .fits file. 1008 1009 @type outputFileName: string 1010 @param outputFileName: filename of output FITS image 1011 @type imageData: numpy array 1012 @param imageData: image data array 1013 @type imageWCS: astWCS.WCS object 1014 @param imageWCS: image WCS object 1015 1016 @note: If imageWCS=None, the FITS image will be written with a rudimentary header containing 1017 no meta data. 1018 1019 """ 1020 1021 if os.path.exists(outputFileName): 1022 os.remove(outputFileName) 1023 1024 newImg=pyfits.HDUList() 1025 1026 if imageWCS!=None: 1027 hdu=pyfits.PrimaryHDU(None, imageWCS.header) 1028 else: 1029 hdu=pyfits.PrimaryHDU(None, None) 1030 1031 hdu.data=imageData 1032 newImg.append(hdu) 1033 newImg.writeto(outputFileName) 1034 newImg.close()
1035 1036 #---------------------------------------------------------------------------------------------------
1037 -def histEq(inputArray, numBins):
1038 """Performs histogram equalisation of the input numpy array. 1039 1040 @type inputArray: numpy array 1041 @param inputArray: image data array 1042 @type numBins: int 1043 @param numBins: number of bins in which to perform the operation (e.g. 1024) 1044 @rtype: numpy array 1045 @return: image data array 1046 1047 """ 1048 1049 imageData=inputArray 1050 1051 # histogram equalisation: we want an equal number of pixels in each intensity range 1052 sortedDataIntensities=numpy.sort(numpy.ravel(imageData)) 1053 median=numpy.median(sortedDataIntensities) 1054 1055 # Make cumulative histogram of data values, simple min-max used to set bin sizes and range 1056 dataCumHist=numpy.zeros(numBins) 1057 minIntensity=sortedDataIntensities.min() 1058 maxIntensity=sortedDataIntensities.max() 1059 histRange=maxIntensity-minIntensity 1060 binWidth=histRange/float(numBins-1) 1061 for i in range(len(sortedDataIntensities)): 1062 binNumber=int(math.ceil((sortedDataIntensities[i]-minIntensity)/binWidth)) 1063 addArray=numpy.zeros(numBins) 1064 onesArray=numpy.ones(numBins-binNumber) 1065 onesRange=list(range(binNumber, numBins)) 1066 numpy.put(addArray, onesRange, onesArray) 1067 dataCumHist=dataCumHist+addArray 1068 1069 # Make ideal cumulative histogram 1070 idealValue=dataCumHist.max()/float(numBins) 1071 idealCumHist=numpy.arange(idealValue, dataCumHist.max()+idealValue, idealValue) 1072 1073 # Map the data to the ideal 1074 for y in range(imageData.shape[0]): 1075 for x in range(imageData.shape[1]): 1076 # Get index corresponding to dataIntensity 1077 intensityBin=int(math.ceil((imageData[y][x]-minIntensity)/binWidth)) 1078 1079 # Guard against rounding errors (happens rarely I think) 1080 if intensityBin<0: 1081 intensityBin=0 1082 if intensityBin>len(dataCumHist)-1: 1083 intensityBin=len(dataCumHist)-1 1084 1085 # Get the cumulative frequency corresponding intensity level in the data 1086 dataCumFreq=dataCumHist[intensityBin] 1087 1088 # Get the index of the corresponding ideal cumulative frequency 1089 idealBin=numpy.searchsorted(idealCumHist, dataCumFreq) 1090 idealIntensity=(idealBin*binWidth)+minIntensity 1091 imageData[y][x]=idealIntensity 1092 1093 return imageData
1094 1095 #---------------------------------------------------------------------------------------------------
1096 -def normalise(inputArray, clipMinMax):
1097 """Clips the inputArray in intensity and normalises the array such that minimum and maximum 1098 values are 0, 1. Clip in intensity is specified by clipMinMax, a list in the format 1099 [clipMin, clipMax] 1100 1101 Used for normalising image arrays so that they can be turned into RGB arrays that matplotlib 1102 can plot (see L{astPlots.ImagePlot}). 1103 1104 @type inputArray: numpy array 1105 @param inputArray: image data array 1106 @type clipMinMax: list 1107 @param clipMinMax: [minimum value of clipped array, maximum value of clipped array] 1108 @rtype: numpy array 1109 @return: normalised array with minimum value 0, maximum value 1 1110 1111 """ 1112 clipped=inputArray.clip(clipMinMax[0], clipMinMax[1]) 1113 slope=1.0/(clipMinMax[1]-clipMinMax[0]) 1114 intercept=-clipMinMax[0]*slope 1115 clipped=clipped*slope+intercept 1116 1117 return clipped
1118

astLib-0.10.0/docs/astLib/toc-astLib.astStats-module.html0000644000175000017500000000625513047255533023470 0ustar mattymatty00000000000000 astStats

Module astStats


Functions

MAD
OLSFit
binner
biweightClipped
biweightLSFit
biweightLocation
biweightScale
biweightTransform
clippedMeanStdev
clippedWeightedLSFit
cumulativeBinner
mean
median
modeEstimate
rms
stdev
weightedBinner
weightedLSFit
weightedMean
weightedStdev

Variables

REPORT_ERRORS
__package__

[hide private] astLib-0.10.0/docs/astLib/toc-everything.html0000644000175000017500000003057413047255533021347 0ustar mattymatty00000000000000 Everything

Everything


All Classes

astLib.astPlots.ImagePlot
astLib.astSED.BC03Model
astLib.astSED.M05Model
astLib.astSED.P09Model
astLib.astSED.Passband
astLib.astSED.SED
astLib.astSED.StellarPopulation
astLib.astSED.TopHatPassband
astLib.astSED.VegaSED
astLib.astWCS.WCS

All Functions

astLib.astCalc.DeltaVz
astLib.astCalc.Ez
astLib.astCalc.Ez2
astLib.astCalc.OmegaLz
astLib.astCalc.OmegaMz
astLib.astCalc.OmegaRz
astLib.astCalc.RVirialXRayCluster
astLib.astCalc.absMag
astLib.astCalc.dVcdz
astLib.astCalc.da
astLib.astCalc.dc
astLib.astCalc.dc2z
astLib.astCalc.dl
astLib.astCalc.dl2z
astLib.astCalc.dm
astLib.astCalc.t0
astLib.astCalc.tl
astLib.astCalc.tl2z
astLib.astCalc.tz
astLib.astCalc.tz2z
astLib.astCoords.calcAngSepDeg
astLib.astCoords.calcRADecSearchBox
astLib.astCoords.convertCoords
astLib.astCoords.decimal2dms
astLib.astCoords.decimal2hms
astLib.astCoords.dms2decimal
astLib.astCoords.hms2decimal
astLib.astCoords.shiftRADec
astLib.astImages.clipImageSectionPix
astLib.astImages.clipImageSectionWCS
astLib.astImages.clipRotatedImageSectionWCS
astLib.astImages.clipUsingRADecCoords
astLib.astImages.generateContourOverlay
astLib.astImages.histEq
astLib.astImages.intensityCutImage
astLib.astImages.normalise
astLib.astImages.resampleToTanProjection
astLib.astImages.resampleToWCS
astLib.astImages.saveBitmap
astLib.astImages.saveContourOverlayBitmap
astLib.astImages.saveFITS
astLib.astImages.scaleImage
astLib.astPlots.u
astLib.astSED.Jy2Mag
astLib.astSED.fitSEDDict
astLib.astSED.flux2Mag
astLib.astSED.mag2Flux
astLib.astSED.mag2Jy
astLib.astSED.mags2SEDDict
astLib.astSED.makeModelSEDDictList
astLib.astStats.MAD
astLib.astStats.OLSFit
astLib.astStats.binner
astLib.astStats.biweightClipped
astLib.astStats.biweightLSFit
astLib.astStats.biweightLocation
astLib.astStats.biweightScale
astLib.astStats.biweightTransform
astLib.astStats.clippedMeanStdev
astLib.astStats.clippedWeightedLSFit
astLib.astStats.cumulativeBinner
astLib.astStats.mean
astLib.astStats.median
astLib.astStats.modeEstimate
astLib.astStats.rms
astLib.astStats.stdev
astLib.astStats.weightedBinner
astLib.astStats.weightedLSFit
astLib.astStats.weightedMean
astLib.astStats.weightedStdev
astLib.astWCS.findWCSOverlap

All Variables

astLib.__package__
astLib.astCalc.C_LIGHT
astLib.astCalc.H0
astLib.astCalc.OMEGA_L0
astLib.astCalc.OMEGA_M0
astLib.astCalc.OMEGA_R0
astLib.astCalc.__package__
astLib.astImages.REPORT_ERRORS
astLib.astPlots.DECIMAL_TICK_STEPS
astLib.astPlots.DEC_TICK_STEPS
astLib.astPlots.DEG
astLib.astPlots.DOUBLE_PRIME
astLib.astPlots.PRIME
astLib.astPlots.RA_TICK_STEPS
astLib.astSED.AB
astLib.astSED.SOL
astLib.astSED.VEGA
astLib.astSED.__package__
astLib.astStats.REPORT_ERRORS
astLib.astStats.__package__
astLib.astWCS.NUMPY_MODE
astLib.astWCS.lconv

[hide private] astLib-0.10.0/docs/astLib/astLib.astWCS-module.html0000644000175000017500000002717513047255533022247 0ustar mattymatty00000000000000 astLib.astWCS
Package astLib :: Module astWCS
[hide private]
[frames] | no frames]

Module astWCS

source code

module for handling World Coordinate Systems (WCS)

(c) 2007-2012 Matt Hilton

(c) 2013-2014 Matt Hilton & Steven Boada

http://astlib.sourceforge.net

This is a higher level interface to some of the routines in PyWCSTools (distributed with astLib). PyWCSTools is a simple SWIG wrapping of WCSTools by Jessica Mink (http://tdc-www.harvard.edu/software/wcstools/). It is intended is to make this interface complete enough such that direct use of PyWCSTools is unnecessary.

Classes [hide private]
  WCS
This class provides methods for accessing information from the World Coordinate System (WCS) contained in the header of a FITS image.
Functions [hide private]
dictionary
findWCSOverlap(wcs1, wcs2)
Finds the minimum, maximum WCS coords that overlap between wcs1 and wcs2.
source code
Variables [hide private]
bool NUMPY_MODE = True
If True (default), pixel coordinates accepted/returned by routines such as astWCS.WCS.pix2wcs, astWCS.WCS.wcs2pix have (0, 0) as the origin.
  lconv = locale.localeconv()
Function Details [hide private]

findWCSOverlap(wcs1, wcs2)

source code 

Finds the minimum, maximum WCS coords that overlap between wcs1 and wcs2. Returns these coordinates, plus the corresponding pixel coordinates for each wcs. Useful for clipping overlapping region between two images.

Returns: dictionary
dictionary with keys 'overlapWCS' (min, max RA, dec of overlap between wcs1, wcs2) 'wcs1Pix', 'wcs2Pix' (pixel coords in each input WCS that correspond to 'overlapWCS' coords)

Variables Details [hide private]

NUMPY_MODE

If True (default), pixel coordinates accepted/returned by routines such as astWCS.WCS.pix2wcs, astWCS.WCS.wcs2pix have (0, 0) as the origin. Set to False to make these routines accept/return pixel coords with (1, 1) as the origin (i.e. to match the FITS convention, default behaviour prior to astLib version 0.3.0).
Type:
bool
Value:
True

astLib-0.10.0/docs/astLib/astLib.astSED.P09Model-class.html0000664000175000017500000001744113047255533023373 0ustar mattymatty00000000000000 astLib.astSED.P09Model
Package astLib :: Module astSED :: Class P09Model
[hide private]
[frames] | no frames]

Class P09Model

source code

StellarPopulation --+
                    |
                   P09Model

This class describes a Percival et al 2009 (BaSTI; http://albione.oa-teramo.inaf.it) stellar population model. We assume that the synthetic spectra for each model are unpacked under the directory pointed to by fileName.

The wavelength units of SEDs from P09 models are converted to Angstroms. Flux is converted into units of erg/s/Angstrom (the units in the BaSTI low-res spectra are 4.3607e-33 erg/s/m).

Instance Methods [hide private]
 
__init__(self, fileName) source code

Inherited from StellarPopulation: calcEvolutionCorrection, getColourEvolution, getMagEvolution, getSED

Method Details [hide private]

__init__(self, fileName)
(Constructor)

source code 
Overrides: StellarPopulation.__init__

astLib-0.10.0/docs/astLib/class-tree.html0000644000175000017500000001414013047255533020431 0ustar mattymatty00000000000000 Class Hierarchy
 
[hide private]
[frames] | no frames]
[ Module Hierarchy | Class Hierarchy ]

Class Hierarchy

astLib-0.10.0/docs/astLib/help.html0000644000175000017500000002472713047255533017333 0ustar mattymatty00000000000000 Help
 
[hide private]
[frames] | no frames]

API Documentation

This document contains the API (Application Programming Interface) documentation for this project. Documentation for the Python objects defined by the project is divided into separate pages for each package, module, and class. The API documentation also includes two pages containing information about the project as a whole: a trees page, and an index page.

Object Documentation

Each Package Documentation page contains:

Each Module Documentation page contains:

Each Class Documentation page contains:

Project Documentation

The Trees page contains the module and class hierarchies:

The Index page contains indices of terms and identifiers:

The Table of Contents

The table of contents occupies the two frames on the left side of the window. The upper-left frame displays the project contents, and the lower-left frame displays the module contents:

Project
Contents
...
API
Documentation
Frame


Module
Contents
 
...
 

The project contents frame contains a list of all packages and modules that are defined by the project. Clicking on an entry will display its contents in the module contents frame. Clicking on a special entry, labeled "Everything," will display the contents of the entire project.

The module contents frame contains a list of every submodule, class, type, exception, function, and variable defined by a module or package. Clicking on an entry will display its documentation in the API documentation frame. Clicking on the name of the module, at the top of the frame, will display the documentation for the module itself.

The "frames" and "no frames" buttons below the top navigation bar can be used to control whether the table of contents is displayed or not.

The Navigation Bar

A navigation bar is located at the top and bottom of every page. It indicates what type of page you are currently viewing, and allows you to go to related pages. The following table describes the labels on the navigation bar. Note that not some labels (such as [Parent]) are not displayed on all pages.

Label Highlighted when... Links to...
[Parent] (never highlighted) the parent of the current package
[Package] viewing a package the package containing the current object
[Module] viewing a module the module containing the current object
[Class] viewing a class the class containing the current object
[Trees] viewing the trees page the trees page
[Index] viewing the index page the index page
[Help] viewing the help page the help page

The "show private" and "hide private" buttons below the top navigation bar can be used to control whether documentation for private objects is displayed. Private objects are usually defined as objects whose (short) names begin with a single underscore, but do not end with an underscore. For example, "_x", "__pprint", and "epydoc.epytext._tokenize" are private objects; but "re.sub", "__init__", and "type_" are not. However, if a module defines the "__all__" variable, then its contents are used to decide which objects are private.

A timestamp below the bottom navigation bar indicates when each page was last updated.

astLib-0.10.0/docs/astLib/epydoc.js0000644000175000017500000002452513047255533017332 0ustar mattymatty00000000000000function toggle_private() { // Search for any private/public links on this page. Store // their old text in "cmd," so we will know what action to // take; and change their text to the opposite action. var cmd = "?"; var elts = document.getElementsByTagName("a"); for(var i=0; i...
"; elt.innerHTML = s; } } function toggle(id) { elt = document.getElementById(id+"-toggle"); if (elt.innerHTML == "-") collapse(id); else expand(id); return false; } function highlight(id) { var elt = document.getElementById(id+"-def"); if (elt) elt.className = "py-highlight-hdr"; var elt = document.getElementById(id+"-expanded"); if (elt) elt.className = "py-highlight"; var elt = document.getElementById(id+"-collapsed"); if (elt) elt.className = "py-highlight"; } function num_lines(s) { var n = 1; var pos = s.indexOf("\n"); while ( pos > 0) { n += 1; pos = s.indexOf("\n", pos+1); } return n; } // Collapse all blocks that mave more than `min_lines` lines. function collapse_all(min_lines) { var elts = document.getElementsByTagName("div"); for (var i=0; i 0) if (elt.id.substring(split, elt.id.length) == "-expanded") if (num_lines(elt.innerHTML) > min_lines) collapse(elt.id.substring(0, split)); } } function expandto(href) { var start = href.indexOf("#")+1; if (start != 0 && start != href.length) { if (href.substring(start, href.length) != "-") { collapse_all(4); pos = href.indexOf(".", start); while (pos != -1) { var id = href.substring(start, pos); expand(id); pos = href.indexOf(".", pos+1); } var id = href.substring(start, href.length); expand(id); highlight(id); } } } function kill_doclink(id) { var parent = document.getElementById(id); parent.removeChild(parent.childNodes.item(0)); } function auto_kill_doclink(ev) { if (!ev) var ev = window.event; if (!this.contains(ev.toElement)) { var parent = document.getElementById(this.parentID); parent.removeChild(parent.childNodes.item(0)); } } function doclink(id, name, targets_id) { var elt = document.getElementById(id); // If we already opened the box, then destroy it. // (This case should never occur, but leave it in just in case.) if (elt.childNodes.length > 1) { elt.removeChild(elt.childNodes.item(0)); } else { // The outer box: relative + inline positioning. var box1 = document.createElement("div"); box1.style.position = "relative"; box1.style.display = "inline"; box1.style.top = 0; box1.style.left = 0; // A shadow for fun var shadow = document.createElement("div"); shadow.style.position = "absolute"; shadow.style.left = "-1.3em"; shadow.style.top = "-1.3em"; shadow.style.background = "#404040"; // The inner box: absolute positioning. var box2 = document.createElement("div"); box2.style.position = "relative"; box2.style.border = "1px solid #a0a0a0"; box2.style.left = "-.2em"; box2.style.top = "-.2em"; box2.style.background = "white"; box2.style.padding = ".3em .4em .3em .4em"; box2.style.fontStyle = "normal"; box2.onmouseout=auto_kill_doclink; box2.parentID = id; // Get the targets var targets_elt = document.getElementById(targets_id); var targets = targets_elt.getAttribute("targets"); var links = ""; target_list = targets.split(","); for (var i=0; i" + target[0] + ""; } // Put it all together. elt.insertBefore(box1, elt.childNodes.item(0)); //box1.appendChild(box2); box1.appendChild(shadow); shadow.appendChild(box2); box2.innerHTML = "Which "+name+" do you want to see documentation for?" + ""; } return false; } function get_anchor() { var href = location.href; var start = href.indexOf("#")+1; if ((start != 0) && (start != href.length)) return href.substring(start, href.length); } function redirect_url(dottedName) { // Scan through each element of the "pages" list, and check // if "name" matches with any of them. for (var i=0; i-m" or "-c"; // extract the portion & compare it to dottedName. var pagename = pages[i].substring(0, pages[i].length-2); if (pagename == dottedName.substring(0,pagename.length)) { // We've found a page that matches `dottedName`; // construct its URL, using leftover `dottedName` // content to form an anchor. var pagetype = pages[i].charAt(pages[i].length-1); var url = pagename + ((pagetype=="m")?"-module.html": "-class.html"); if (dottedName.length > pagename.length) url += "#" + dottedName.substring(pagename.length+1, dottedName.length); return url; } } } astLib-0.10.0/docs/astLib/astLib.astSED.StellarPopulation-class.html0000664000175000017500000005172713047255533025530 0ustar mattymatty00000000000000 astLib.astSED.StellarPopulation
Package astLib :: Module astSED :: Class StellarPopulation
[hide private]
[frames] | no frames]

Class StellarPopulation

source code

Known Subclasses:

This class describes a stellar population model, either a Simple Stellar Population (SSP) or a Composite Stellar Population (CSP), such as the models of Bruzual & Charlot 2003 or Maraston 2005.

The constructor for this class can be used for generic SSPs or CSPs stored in white space delimited text files, containing columns for age, wavelength, and flux. Columns are counted from 0 ... n. Lines starting with # are ignored.

The classes M05Model (for Maraston 2005 models), BC03Model (for Bruzual & Charlot 2003 models), and P09Model (for Percival et al. 2009 models) are derived from this class. The only difference between them is the code used to load in the model data.

Instance Methods [hide private]
 
__init__(self, fileName, ageColumn=0, wavelengthColumn=1, fluxColumn=2) source code
SED object
getSED(self, ageGyr, z=0.0, normalise=False, label=None)
Extract a SED for given age.
source code
dictionary
getColourEvolution(self, passband1, passband2, zFormation, zStepSize=0.05, magType='Vega')
Calculates the evolution of the colour observed through passband1 - passband2 for the StellarPopulation with redshift, from z = 0 to z = zFormation.
source code
dictionary
getMagEvolution(self, passband, magNormalisation, zNormalisation, zFormation, zStepSize=0.05, onePlusZSteps=False, magType='Vega')
Calculates the evolution with redshift (from z = 0 to z = zFormation) of apparent magnitude in the observed frame through the passband for the StellarPopulation, normalised to magNormalisation (apparent) at z = zNormalisation.
source code
float
calcEvolutionCorrection(self, zFrom, zTo, zFormation, passband, magType='Vega')
Calculates the evolution correction in magnitudes in the rest frame through the passband from redshift zFrom to redshift zTo, where the stellarPopulation is assumed to be formed at redshift zFormation.
source code
Method Details [hide private]

getSED(self, ageGyr, z=0.0, normalise=False, label=None)

source code 

Extract a SED for given age. Do linear interpolation between models if necessary.

Parameters:
  • ageGyr (float) - age of the SED in Gyr
  • z (float) - redshift the SED from z = 0 to z = z
  • normalise (bool) - normalise the SED to have area 1
Returns: SED object
SED

getColourEvolution(self, passband1, passband2, zFormation, zStepSize=0.05, magType='Vega')

source code 

Calculates the evolution of the colour observed through passband1 - passband2 for the StellarPopulation with redshift, from z = 0 to z = zFormation.

Parameters:
  • passband1 (Passband object) - filter passband through which to calculate the first magnitude
  • passband2 (Passband object) - filter passband through which to calculate the second magnitude
  • zFormation (float) - formation redshift of the StellarPopulation
  • zStepSize (float) - size of interval in z at which to calculate model colours
  • magType (string) - either "Vega" or "AB"
Returns: dictionary
dictionary of numpy.arrays in format {'z', 'colour'}

getMagEvolution(self, passband, magNormalisation, zNormalisation, zFormation, zStepSize=0.05, onePlusZSteps=False, magType='Vega')

source code 

Calculates the evolution with redshift (from z = 0 to z = zFormation) of apparent magnitude in the observed frame through the passband for the StellarPopulation, normalised to magNormalisation (apparent) at z = zNormalisation.

Parameters:
  • passband (Passband object) - filter passband through which to calculate the magnitude
  • magNormalisation (float) - sets the apparent magnitude of the SED at zNormalisation
  • zNormalisation (float) - the redshift at which the magnitude normalisation is carried out
  • zFormation (float) - formation redshift of the StellarPopulation
  • zStepSize (float) - size of interval in z at which to calculate model magnitudes
  • onePlusZSteps (bool) - if True, zSteps are (1+z)*zStepSize, otherwise zSteps are linear
  • magType (string) - either "Vega" or "AB"
Returns: dictionary
dictionary of numpy.arrays in format {'z', 'mag'}

calcEvolutionCorrection(self, zFrom, zTo, zFormation, passband, magType='Vega')

source code 

Calculates the evolution correction in magnitudes in the rest frame through the passband from redshift zFrom to redshift zTo, where the stellarPopulation is assumed to be formed at redshift zFormation.

Parameters:
  • zFormation (float) - redshift to evolution correct from
  • zTo (float) - redshift to evolution correct to
  • zFormation (float) - formation redshift of the StellarPopulation
  • passband (Passband object) - filter passband through which to calculate magnitude
  • magType (string) - either "Vega" or "AB"
  • zFrom (float)
Returns: float
evolution correction in magnitudes in the rest frame

astLib-0.10.0/docs/astLib/toc-astLib.astImages-module.html0000644000175000017500000000521413047255533023571 0ustar mattymatty00000000000000 astImages

Module astImages


Functions

clipImageSectionPix
clipImageSectionWCS
clipRotatedImageSectionWCS
clipUsingRADecCoords
generateContourOverlay
histEq
intensityCutImage
normalise
resampleToTanProjection
resampleToWCS
saveBitmap
saveContourOverlayBitmap
saveFITS
scaleImage

Variables

REPORT_ERRORS

[hide private] astLib-0.10.0/docs/astLib/astLib.astPlots-pysrc.html0000644000175000017500000117435413047255533022572 0ustar mattymatty00000000000000 astLib.astPlots
Package astLib :: Module astPlots
[hide private]
[frames] | no frames]

Source Code for Module astLib.astPlots

   1  """module for producing astronomical plots 
   2   
   3  (c) 2007-2013 Matt Hilton  
   4   
   5  U{http://astlib.sourceforge.net} 
   6   
   7  This module provides the matplotlib powered ImagePlot class, which is designed to be flexible.  
   8  ImagePlots can have RA, Dec. coordinate axes, contour overlays, and have objects marked in them,  
   9  using WCS coordinates. RGB plots are supported too. 
  10   
  11  @var DEC_TICK_STEPS: Defines the possible coordinate label steps on the delination axis in 
  12  sexagesimal mode. Dictionary format: {'deg', 'unit'} 
  13  @type DEC_TICK_STEPS: dictionary list 
  14   
  15  @var RA_TICK_STEPS: Defines the possible coordinate label steps on the right ascension axis in 
  16  sexagesimal mode. Dictionary format: {'deg', 'unit'} 
  17  @type RA_TICK_STEPS: dictionary list 
  18   
  19  @var DECIMAL_TICK_STEPS: Defines the possible coordinate label steps on both coordinate axes in 
  20  decimal degrees mode. 
  21  @type DECIMAL_TICK_STEPS: list 
  22   
  23  @var DEG: Variable to stand in for the degrees symbol. 
  24  @type DEG: string 
  25   
  26  @var PRIME: Variable to stand in for the prime symbol. 
  27  @type PRIME: string 
  28   
  29  @var DOUBLE_PRIME: Variable to stand in for the double prime symbol. 
  30  @type DOUBLE_PRIME: string 
  31   
  32  """ 
  33   
  34  import math 
  35  from . import astImages 
  36  from . import astWCS 
  37  from . import astCoords 
  38  import numpy 
  39  import pyfits 
  40  from scipy import interpolate 
  41  import pylab 
  42  import matplotlib.patches as patches 
  43  import sys 
  44   
  45  # Handle unicode python 2 and 3 
  46  if sys.version < '3': 
  47      import codecs 
48 - def u(x):
49 return codecs.unicode_escape_decode(x)[0]
50 else:
51 - def u(x):
52 return x
53 54 DEC_TICK_STEPS=[{'deg': 1.0/60.0/60.0, 'unit': "s"}, 55 {'deg': 2.0/60.0/60.0, 'unit': "s"}, 56 {'deg': 5.0/60.0/60.0, 'unit': "s"}, 57 {'deg': 10.0/60.0/60.0, 'unit': "s"}, 58 {'deg': 30.0/60.0/60.0, 'unit': "s"}, 59 {'deg': 1.0/60.0, 'unit': "m"}, 60 {'deg': 2.0/60.0, 'unit': "m"}, 61 {'deg': 5.0/60.0, 'unit': "m"}, 62 {'deg': 15.0/60.0, 'unit': "m"}, 63 {'deg': 30.0/60.0, 'unit': "m"}, 64 {'deg': 1.0, 'unit': "d"}, 65 {'deg': 2.0, 'unit': "d"}, 66 {'deg': 4.0, 'unit': "d"}, 67 {'deg': 5.0, 'unit': "d"}, 68 {'deg': 10.0, 'unit': "d"}, 69 {'deg': 20.0, 'unit': "d"}, 70 {'deg': 30.0, 'unit': "d"}] 71 72 RA_TICK_STEPS=[ {'deg': (0.5/60.0/60.0/24.0)*360.0, 'unit': "s"}, 73 {'deg': (1.0/60.0/60.0/24.0)*360.0, 'unit': "s"}, 74 {'deg': (2.0/60.0/60.0/24.0)*360.0, 'unit': "s"}, 75 {'deg': (4.0/60.0/60.0/24.0)*360.0, 'unit': "s"}, 76 {'deg': (5.0/60.0/60.0/24.0)*360.0, 'unit': "s"}, 77 {'deg': (10.0/60.0/60.0/24.0)*360.0, 'unit': "s"}, 78 {'deg': (20.0/60.0/60.0/24.0)*360.0, 'unit': "s"}, 79 {'deg': (30.0/60.0/60.0/24.0)*360.0, 'unit': "s"}, 80 {'deg': (1.0/60.0/24.0)*360.0, 'unit': "m"}, 81 {'deg': (2.0/60.0/24.0)*360.0, 'unit': "m"}, 82 {'deg': (5.0/60.0/24.0)*360.0, 'unit': "m"}, 83 {'deg': (10.0/60.0/24.0)*360.0, 'unit': "m"}, 84 {'deg': (20.0/60.0/24.0)*360.0, 'unit': "m"}, 85 {'deg': (30.0/60.0/24.0)*360.0, 'unit': "m"}, 86 {'deg': (1.0/24.0)*360.0, 'unit': "h"}, 87 {'deg': (3.0/24.0)*360.0, 'unit': "h"}, 88 {'deg': (6.0/24.0)*360.0, 'unit': "h"}, 89 {'deg': (12.0/24.0)*360.0, 'unit': "h"}] 90 91 DECIMAL_TICK_STEPS=[0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 2.5, 5.0, 10.0, 30.0, 90.0] 92 93 DEG = u("\N{DEGREE SIGN}") 94 PRIME = "$^\prime$" 95 DOUBLE_PRIME = "$^{\prime\prime}$" 96 97 #---------------------------------------------------------------------------------------------------
98 -class ImagePlot:
99 """This class describes a matplotlib image plot containing an astronomical image with an 100 associated WCS. 101 102 Objects within the image boundaries can be marked by passing their WCS coordinates to 103 L{ImagePlot.addPlotObjects}. 104 105 Other images can be overlaid using L{ImagePlot.addContourOverlay}. 106 107 For images rotated with North at the top, East at the left (as can be done using 108 L{astImages.clipRotatedImageSectionWCS} or L{astImages.resampleToTanProjection}, WCS coordinate 109 axes can be plotted, with tick marks set appropriately for the image size. Otherwise, a compass 110 can be plotted showing the directions of North and East in the image. 111 112 RGB images are also supported. 113 114 The plot can of course be tweaked further after creation using matplotlib/pylab commands. 115 116 """
117 - def __init__(self, imageData, imageWCS, axes = [0.1,0.1,0.8,0.8], \ 118 cutLevels = ["smart", 99.5], colorMapName = "gray", title = None, axesLabels = "sexagesimal", \ 119 axesFontFamily="serif", axesFontSize=12.0, RATickSteps="auto", decTickSteps="auto", 120 colorBar = False, interpolation = "bilinear"):
121 """Makes an ImagePlot from the given image array and astWCS. For coordinate axes to work, the 122 image and WCS should have been rotated such that East is at the left, North is at the top 123 (see e.g. L{astImages.clipRotatedImageSectionWCS}, or L{astImages.resampleToTanProjection}). 124 125 If imageData is given as a list in the format [r, g, b], a color RGB plot will be made. However, 126 in this case the cutLevels must be specified manually for each component as a list - 127 i.e. cutLevels = [[r min, r max], [g min, g max], [b min, b max]]. In this case of course, the 128 colorMap will be ignored. All r, g, b image arrays must have the same dimensions. 129 130 Set axesLabels = None to make a plot without coordinate axes plotted. 131 132 The axes can be marked in either sexagesimal or decimal celestial coordinates. If RATickSteps 133 or decTickSteps are set to "auto", the appropriate axis scales will be determined automatically 134 from the size of the image array and associated WCS. The tick step sizes can be overidden. 135 If the coordinate axes are in sexagesimal format a dictionary in the format {'deg', 'unit'} is 136 needed (see L{RA_TICK_STEPS} and L{DEC_TICK_STEPS} for examples). If the coordinate axes are in 137 decimal format, the tick step size is specified simply in RA, dec decimal degrees. 138 139 @type imageData: numpy array or list 140 @param imageData: image data array or list of numpy arrays [r, g, b] 141 @type imageWCS: astWCS.WCS 142 @param imageWCS: astWCS.WCS object 143 @type axes: list 144 @param axes: specifies where in the current figure to draw the finder chart (see pylab.axes) 145 @type cutLevels: list 146 @param cutLevels: sets the image scaling - available options: 147 - pixel values: cutLevels=[low value, high value]. 148 - histogram equalisation: cutLevels=["histEq", number of bins ( e.g. 1024)] 149 - relative: cutLevels=["relative", cut per cent level (e.g. 99.5)] 150 - smart: cutLevels=["smart", cut per cent level (e.g. 99.5)] 151 ["smart", 99.5] seems to provide good scaling over a range of different images. 152 Note that for RGB images, cut levels must be specified manually i.e. as a list: 153 [[r min, rmax], [g min, g max], [b min, b max]] 154 @type colorMapName: string 155 @param colorMapName: name of a standard matplotlib colormap, e.g. "hot", "cool", "gray" 156 etc. (do "help(pylab.colormaps)" in the Python interpreter to see available options) 157 @type title: string 158 @param title: optional title for the plot 159 @type axesLabels: string 160 @param axesLabels: either "sexagesimal" (for H:M:S, D:M:S), "decimal" (for decimal degrees) 161 or None (for no coordinate axes labels) 162 @type axesFontFamily: string 163 @param axesFontFamily: matplotlib fontfamily, e.g. 'serif', 'sans-serif' etc. 164 @type axesFontSize: float 165 @param axesFontSize: font size of axes labels and titles (in points) 166 @type colorBar: bool 167 @param colorBar: if True, plot a vertical color bar at the side of the image indicating the intensity 168 scale. 169 @type interpolation: string 170 @param interpolation: interpolation to apply to the image plot (see the documentation for 171 the matplotlib.pylab.imshow command) 172 173 """ 174 175 self.RADeg, self.decDeg=imageWCS.getCentreWCSCoords() 176 self.wcs=imageWCS 177 178 # Handle case where imageData is [r, g, b] 179 if type(imageData) == list: 180 if len(imageData) == 3: 181 if len(cutLevels) == 3: 182 r=astImages.normalise(imageData[0], cutLevels[0]) 183 g=astImages.normalise(imageData[1], cutLevels[1]) 184 b=astImages.normalise(imageData[2], cutLevels[2]) 185 rgb=numpy.array([r.transpose(), g.transpose(), b.transpose()]) 186 rgb=rgb.transpose() 187 self.data=rgb 188 self.rgbImage=True 189 else: 190 raise Exception("tried to create a RGB array, but cutLevels is not a list of 3 lists") 191 192 else: 193 raise Exception("tried to create a RGB array but imageData is not a list of 3 arrays") 194 else: 195 self.data=imageData 196 self.rgbImage=False 197 198 self.axes=pylab.axes(axes) 199 self.cutLevels=cutLevels 200 self.colorMapName=colorMapName 201 self.title=title 202 self.axesLabels=axesLabels 203 self.colorBar=colorBar 204 self.axesFontSize=axesFontSize 205 self.axesFontFamily=axesFontFamily 206 207 self.flipXAxis=False 208 self.flipYAxis=False 209 210 self.interpolation=interpolation 211 212 if self.axesLabels != None: 213 214 # Allow user to override the automatic coord tick spacing 215 if self.axesLabels == "sexagesimal": 216 if RATickSteps != "auto": 217 if type(RATickSteps) != dict or "deg" not in list(RATickSteps.keys()) \ 218 or "unit" not in list(RATickSteps.keys()): 219 raise Exception("RATickSteps needs to be in format {'deg', 'unit'} for sexagesimal axes labels") 220 if decTickSteps != "auto": 221 if type(decTickSteps) != dict or "deg" not in list(decTickSteps.keys()) \ 222 or "unit" not in list(decTickSteps.keys()): 223 raise Exception("decTickSteps needs to be in format {'deg', 'unit'} for sexagesimal axes labels") 224 elif self.axesLabels == "decimal": 225 if RATickSteps != "auto": 226 if type(RATickSteps) != float: 227 raise Exception("RATickSteps needs to be a float (if not 'auto') for decimal axes labels") 228 if decTickSteps != "auto": 229 if type(decTickSteps) != float: 230 raise Exception("decTickSteps needs to be a float (if not 'auto') for decimal axes labels") 231 self.RATickSteps=RATickSteps 232 self.decTickSteps=decTickSteps 233 234 self.calcWCSAxisLabels(axesLabels = self.axesLabels) 235 236 # this list stores objects to overplot, add to it using addPlotObjects() 237 self.plotObjects=[] 238 239 # this list stores image data to overlay as contours, add to it using addContourOverlay() 240 self.contourOverlays=[] 241 242 self.draw()
243 244
245 - def draw(self):
246 """Redraws the ImagePlot. 247 248 """ 249 250 pylab.axes(self.axes) 251 pylab.cla() 252 253 if self.title != None: 254 pylab.title(self.title) 255 try: 256 colorMap=pylab.cm.get_cmap(self.colorMapName) 257 except AssertionError: 258 raise Exception(self.colorMapName+"is not a defined matplotlib colormap.") 259 260 if self.rgbImage == False: 261 self.cutImage=astImages.intensityCutImage(self.data, self.cutLevels) 262 if self.cutLevels[0]=="histEq": 263 pylab.imshow(self.cutImage['image'], interpolation=self.interpolation, origin='lower', cmap=colorMap) 264 else: 265 pylab.imshow(self.cutImage['image'], interpolation=self.interpolation, norm=self.cutImage['norm'], \ 266 origin='lower', cmap=colorMap) 267 else: 268 pylab.imshow(self.data, interpolation="bilinear", origin='lower') 269 270 if self.colorBar == True: 271 pylab.colorbar(shrink=0.8) 272 273 for c in self.contourOverlays: 274 pylab.contour(c['contourData']['scaledImage'], c['contourData']['contourLevels'], 275 colors=c['color'], linewidths=c['width']) 276 277 for p in self.plotObjects: 278 for x, y, l in zip(p['x'], p['y'], p['objLabels']): 279 if p['symbol'] == "circle": 280 c=patches.Circle((x, y), radius=p['sizePix']/2.0, fill=False, edgecolor=p['color'], 281 linewidth=p['width']) 282 self.axes.add_patch(c) 283 elif p['symbol'] == "box": 284 c=patches.Rectangle((x-p['sizePix']/2, y-p['sizePix']/2), p['sizePix'], p['sizePix'], 285 fill=False, edgecolor=p['color'], linewidth=p['width']) 286 self.axes.add_patch(c) 287 elif p['symbol'] == "cross": 288 pylab.plot([x-p['sizePix']/2, x+p['sizePix']/2], [y, y], linestyle='-', 289 linewidth=p['width'], color= p['color']) 290 pylab.plot([x, x], [y-p['sizePix']/2, y+p['sizePix']/2], linestyle='-', 291 linewidth=p['width'], color= p['color']) 292 elif p['symbol'] == "diamond": 293 c=patches.RegularPolygon([x, y], 4, radius=p['sizePix']/2, orientation=0, 294 edgecolor=p['color'], fill=False, linewidth=p['width']) 295 self.axes.add_patch(c) 296 if l != None: 297 pylab.text(x, y+p['sizePix']/1.5, l, horizontalalignment='center', \ 298 fontsize=p['objLabelSize'], color=p['color']) 299 300 if p['symbol'] == "compass": 301 x=p['x'][0] 302 y=p['y'][0] 303 ra=p['RA'][0] 304 dec=p['dec'][0] 305 306 westPoint,eastPoint,southPoint,northPoint=astCoords.calcRADecSearchBox(ra, dec, p['sizeArcSec']/3600.0/2.0) 307 northPix=self.wcs.wcs2pix(ra, northPoint) 308 eastPix=self.wcs.wcs2pix(eastPoint, dec) 309 310 edx=eastPix[0]-x 311 edy=eastPix[1]-y 312 ndx=northPix[0]-x 313 ndy=northPix[1]-y 314 nArrow=patches.Arrow(x, y, ndx, ndy, edgecolor=p['color'], facecolor=p['color'], width=p['width']) 315 eArrow=patches.Arrow(x, y, edx, edy, edgecolor=p['color'], facecolor=p['color'], width=p['width']) 316 self.axes.add_patch(nArrow) 317 self.axes.add_patch(eArrow) 318 pylab.text(x+ndx+ndx*0.2, y+ndy+ndy*0.2, "N", horizontalalignment='center', 319 verticalalignment='center', fontsize=p['objLabelSize'], color=p['color']) 320 pylab.text(x+edx+edx*0.2, y+edy+edy*0.2, "E", horizontalalignment='center', 321 verticalalignment='center', fontsize=p['objLabelSize'], color=p['color']) 322 323 if p['symbol'] == "scaleBar": 324 x=p['x'][0] 325 y=p['y'][0] 326 ra=p['RA'][0] 327 dec=p['dec'][0] 328 329 westPoint,eastPoint,southPoint,northPoint=astCoords.calcRADecSearchBox(ra, dec, p['sizeArcSec']/3600.0/2.0) 330 northPix=self.wcs.wcs2pix(ra, northPoint) 331 eastPix=self.wcs.wcs2pix(eastPoint, dec) 332 edx=eastPix[0]-x 333 edy=eastPix[1]-y 334 ndx=northPix[0]-x 335 ndy=northPix[1]-y 336 337 eArrow=patches.Arrow(x, y, edx, edy, edgecolor=p['color'], facecolor=p['color'], width=p['width']) 338 wArrow=patches.Arrow(x, y, -edx, edy, edgecolor=p['color'], facecolor=p['color'], width=p['width']) 339 340 self.axes.add_patch(eArrow) 341 self.axes.add_patch(wArrow) 342 343 # Work out label 344 scaleLabel=None 345 if p['sizeArcSec'] < 60.0: 346 scaleLabel="%.0f %s" % (p['sizeArcSec'], DOUBLE_PRIME) 347 elif p['sizeArcSec'] >= 60.0 and p['sizeArcSec'] < 3600.0: 348 scaleLabel="%.0f %s" % (p['sizeArcSec']/60.0, PRIME) 349 else: 350 scaleLabel="%.0f %s" % (p['sizeArcSec']/3600.0, DEG) 351 352 pylab.text(x, y+0.025*self.data.shape[1], scaleLabel, horizontalalignment='center', 353 verticalalignment='center', fontsize=p['objLabelSize'], color=p['color']) 354 355 if self.axesLabels != None: 356 pylab.xticks(self.ticsRA[0], self.ticsRA[1], weight='normal', family=self.axesFontFamily, \ 357 fontsize=self.axesFontSize) 358 pylab.yticks(self.ticsDec[0], self.ticsDec[1], weight='normal', family=self.axesFontFamily, \ 359 fontsize=self.axesFontSize) 360 pylab.xlabel(self.RAAxisLabel, family=self.axesFontFamily, fontsize=self.axesFontSize) 361 pylab.ylabel(self.decAxisLabel, family=self.axesFontFamily, fontsize=self.axesFontSize) 362 else: 363 pylab.xticks([], []) 364 pylab.yticks([], []) 365 pylab.xlabel("") 366 pylab.ylabel("") 367 368 if self.flipXAxis == False: 369 pylab.xlim(0, self.data.shape[1]-1) 370 else: 371 pylab.xlim(self.data.shape[1]-1, 0) 372 if self.flipYAxis == False: 373 pylab.ylim(0, self.data.shape[0]-1) 374 else: 375 pylab.ylim(self.data.shape[0]-1, 0)
376 377
378 - def addContourOverlay(self, contourImageData, contourWCS, tag, levels = ["linear", "min", "max", 5], 379 width = 1, color = "white", smooth = 0, highAccuracy = False):
380 """Adds image data to the ImagePlot as a contour overlay. The contours can be removed using 381 L{removeContourOverlay}. If a contour overlay already exists with this tag, it will be replaced. 382 383 @type contourImageData: numpy array 384 @param contourImageData: image data array from which contours are to be generated 385 @type contourWCS: astWCS.WCS 386 @param contourWCS: astWCS.WCS object for the image to be contoured 387 @type tag: string 388 @param tag: identifying tag for this set of contours 389 @type levels: list 390 @param levels: sets the contour levels - available options: 391 - values: contourLevels=[list of values specifying each level] 392 - linear spacing: contourLevels=['linear', min level value, max level value, number 393 of levels] - can use "min", "max" to automatically set min, max levels from image data 394 - log spacing: contourLevels=['log', min level value, max level value, number of 395 levels] - can use "min", "max" to automatically set min, max levels from image data 396 @type width: int 397 @param width: width of the overlaid contours 398 @type color: string 399 @param color: color of the overlaid contours, specified by the name of a standard 400 matplotlib color, e.g., "black", "white", "cyan" 401 etc. (do "help(pylab.colors)" in the Python interpreter to see available options) 402 @type smooth: float 403 @param smooth: standard deviation (in arcsec) of Gaussian filter for 404 pre-smoothing of contour image data (set to 0 for no smoothing) 405 @type highAccuracy: bool 406 @param highAccuracy: if True, sample every corresponding pixel in each image; otherwise, sample 407 every nth pixel, where n = the ratio of the image scales. 408 409 """ 410 411 if self.rgbImage == True: 412 backgroundData=self.data[:,:,0] 413 else: 414 backgroundData=self.data 415 contourData=astImages.generateContourOverlay(backgroundData, self.wcs, contourImageData, \ 416 contourWCS, levels, smooth, highAccuracy = highAccuracy) 417 418 alreadyGot=False 419 for c in self.contourOverlays: 420 if c['tag'] == tag: 421 c['contourData']=contourData 422 c['tag']=tag 423 c['color']=color 424 c['width']=width 425 alreadyGot=True 426 427 if alreadyGot == False: 428 self.contourOverlays.append({'contourData': contourData, 'tag': tag, 'color': color, \ 429 'width': width}) 430 self.draw()
431 432
433 - def removeContourOverlay(self, tag):
434 """Removes the contourOverlay from the ImagePlot corresponding to the tag. 435 436 @type tag: string 437 @param tag: tag for contour overlay in ImagePlot.contourOverlays to be removed 438 439 """ 440 441 index=0 442 for p in self.contourOverlays: 443 if p['tag'] == tag: 444 self.plotObjects.remove(self.plotObjects[index]) 445 index=index+1 446 self.draw()
447 448
449 - def addPlotObjects(self, objRAs, objDecs, tag, symbol="circle", size=4.0, width=1.0, color="yellow", 450 objLabels = None, objLabelSize = 12.0):
451 """Add objects with RA, dec coords objRAs, objDecs to the ImagePlot. Only objects that fall within 452 the image boundaries will be plotted. 453 454 symbol specifies the type of symbol with which to mark the object in the image. The following 455 values are allowed: 456 - "circle" 457 - "box" 458 - "cross" 459 - "diamond" 460 461 size specifies the diameter in arcsec of the symbol (if plotSymbol == "circle"), or the width 462 of the box in arcsec (if plotSymbol == "box") 463 464 width specifies the thickness of the symbol lines in pixels 465 466 color can be any valid matplotlib color (e.g. "red", "green", etc.) 467 468 The objects can be removed from the plot by using removePlotObjects(), and then calling 469 draw(). If the ImagePlot already has a set of plotObjects with the same tag, they will be 470 replaced. 471 472 @type objRAs: numpy array or list 473 @param objRAs: object RA coords in decimal degrees 474 @type objDecs: numpy array or list 475 @param objDecs: corresponding object Dec. coords in decimal degrees 476 @type tag: string 477 @param tag: identifying tag for this set of objects 478 @type symbol: string 479 @param symbol: either "circle", "box", "cross", or "diamond" 480 @type size: float 481 @param size: size of symbols to plot (radius in arcsec, or width of box) 482 @type width: float 483 @param width: width of symbols in pixels 484 @type color: string 485 @param color: any valid matplotlib color string, e.g. "red", "green" etc. 486 @type objLabels: list 487 @param objLabels: text labels to plot next to objects in figure 488 @type objLabelSize: float 489 @param objLabelSize: size of font used for object labels (in points) 490 491 """ 492 493 pixCoords=self.wcs.wcs2pix(objRAs, objDecs) 494 495 xMax=self.data.shape[1] 496 yMax=self.data.shape[0] 497 498 if objLabels == None: 499 objLabels=[None]*len(objRAs) 500 501 xInPlot=[] 502 yInPlot=[] 503 RAInPlot=[] 504 decInPlot=[] 505 labelInPlot=[] 506 for p, r, d, l in zip(pixCoords, objRAs, objDecs, objLabels): 507 if p[0] >= 0 and p[0] < xMax and p[1] >= 0 and p[1] < yMax: 508 xInPlot.append(p[0]) 509 yInPlot.append(p[1]) 510 RAInPlot.append(r) 511 decInPlot.append(d) 512 labelInPlot.append(l) 513 514 xInPlot=numpy.array(xInPlot) 515 yInPlot=numpy.array(yInPlot) 516 RAInPlot=numpy.array(RAInPlot) 517 decInPlot=numpy.array(decInPlot) 518 519 # Size of symbols in pixels in plot - converted from arcsec 520 sizePix=(size/3600.0)/self.wcs.getPixelSizeDeg() 521 522 alreadyGot=False 523 for p in self.plotObjects: 524 if p['tag'] == tag: 525 p['x']=xInPlot 526 p['y']=yInPlot 527 p['RA']=RAInPlot 528 p['dec']=decInPlot 529 p['tag']=tag 530 p['objLabels']=objLabels 531 p['symbol']=symbol 532 p['sizePix']=sizePix 533 p['sizeArcSec']=size 534 p['width']=width 535 p['color']=color 536 p['objLabelSize']=objLabelSize 537 alreadyGot=True 538 539 if alreadyGot == False: 540 self.plotObjects.append({'x': xInPlot, 'y': yInPlot, 'RA': RAInPlot, 'dec': decInPlot, 541 'tag': tag, 'objLabels': labelInPlot, 'symbol': symbol, 542 'sizePix': sizePix, 'width': width, 'color': color, 543 'objLabelSize': objLabelSize, 'sizeArcSec': size}) 544 self.draw()
545 546
547 - def removePlotObjects(self, tag):
548 """Removes the plotObjects from the ImagePlot corresponding to the tag. The plot must be redrawn 549 for the change to take effect. 550 551 @type tag: string 552 @param tag: tag for set of objects in ImagePlot.plotObjects to be removed 553 554 """ 555 556 index=0 557 for p in self.plotObjects: 558 if p['tag'] == tag: 559 self.plotObjects.remove(self.plotObjects[index]) 560 index=index+1 561 self.draw()
562 563
564 - def addCompass(self, location, sizeArcSec, color = "white", fontSize = 12, \ 565 width = 20.0):
566 """Adds a compass to the ImagePlot at the given location ('N', 'NE', 'E', 'SE', 'S', 567 'SW', 'W', or 'NW'). Note these aren't directions on the WCS coordinate grid, they are 568 relative positions on the plot - so N is top centre, NE is top right, SW is bottom right etc.. 569 Alternatively, pixel coordinates (x, y) in the image can be given. 570 571 @type location: string or tuple 572 @param location: location in the plot where the compass is drawn: 573 - string: N, NE, E, SE, S, SW, W or NW 574 - tuple: (x, y) 575 @type sizeArcSec: float 576 @param sizeArcSec: length of the compass arrows on the plot in arc seconds 577 @type color: string 578 @param color: any valid matplotlib color string 579 @type fontSize: float 580 @param fontSize: size of font used to label N and E, in points 581 @type width: float 582 @param width: width of arrows used to mark compass 583 584 """ 585 586 if type(location) == str: 587 cRADeg, cDecDeg=self.wcs.getCentreWCSCoords() 588 RAMin, RAMax, decMin, decMax=self.wcs.getImageMinMaxWCSCoords() 589 westPoint,eastPoint,southPoint,northPoint=astCoords.calcRADecSearchBox(cRADeg, cDecDeg, sizeArcSec/3600.0/2.0) 590 sizeRADeg=eastPoint-westPoint 591 sizeDecDeg=northPoint-southPoint 592 xSizePix=(sizeArcSec/3600.0)/self.wcs.getXPixelSizeDeg() 593 ySizePix=(sizeArcSec/3600.0)/self.wcs.getYPixelSizeDeg() 594 X=self.data.shape[1] 595 Y=self.data.shape[0] 596 xBufferPix=0.5*xSizePix 597 yBufferPix=0.5*ySizePix 598 cx, cy=self.wcs.wcs2pix(cRADeg, cDecDeg) 599 foundLocation=False 600 x=cy 601 y=cx 602 if self.wcs.isFlipped() == False: 603 if location.find("N") != -1: 604 y=Y-2*yBufferPix 605 foundLocation=True 606 if location.find("S") != -1: 607 y=yBufferPix 608 foundLocation=True 609 if location.find("E") != -1: 610 x=xBufferPix*2 611 foundLocation=True 612 if location.find("W") != -1: 613 x=X-xBufferPix 614 foundLocation=True 615 else: 616 if location.find("S") != -1: 617 y=Y-2*yBufferPix 618 foundLocation=True 619 if location.find("N") != -1: 620 y=yBufferPix 621 foundLocation=True 622 if location.find("W") != -1: 623 x=xBufferPix*2 624 foundLocation=True 625 if location.find("E") != -1: 626 x=X-xBufferPix 627 foundLocation=True 628 if foundLocation == False: 629 raise Exception("didn't understand location string for scale bar (should be e.g. N, S, E, W).") 630 RADeg, decDeg=self.wcs.pix2wcs(x, y) 631 elif type(location) == tuple or type(location) == list: 632 x, y=location 633 RADeg, decDeg=self.wcs.pix2wcs(x, y) 634 else: 635 raise Exception("didn't understand location for scale bar - should be string or tuple.") 636 637 alreadyGot=False 638 for p in self.plotObjects: 639 if p['tag'] == "compass": 640 p['x']=[x] 641 p['y']=[y] 642 p['RA']=[RADeg] 643 p['dec']=[decDeg] 644 p['tag']="compass" 645 p['objLabels']=[None] 646 p['symbol']="compass" 647 p['sizeArcSec']=sizeArcSec 648 p['width']=width 649 p['color']=color 650 p['objLabelSize']=fontSize 651 alreadyGot=True 652 653 if alreadyGot == False: 654 self.plotObjects.append({'x': [x], 'y': [y], 'RA': [RADeg], 'dec': [decDeg], 655 'tag': "compass", 'objLabels': [None], 'symbol': "compass", 656 'width': width, 'color': color, 657 'objLabelSize': fontSize, 'sizeArcSec': sizeArcSec}) 658 self.draw()
659 660
661 - def addScaleBar(self, location, sizeArcSec, color = "white", fontSize = 12, \ 662 width = 20.0):
663 """Adds a scale bar to the ImagePlot at the given location ('N', 'NE', 'E', 'SE', 'S', 664 'SW', 'W', or 'NW'). Note these aren't directions on the WCS coordinate grid, they are 665 relative positions on the plot - so N is top centre, NE is top right, SW is bottom right etc.. 666 Alternatively, pixel coordinates (x, y) in the image can be given. 667 668 @type location: string or tuple 669 @param location: location in the plot where the compass is drawn: 670 - string: N, NE, E, SE, S, SW, W or NW 671 - tuple: (x, y) 672 @type sizeArcSec: float 673 @param sizeArcSec: scale length to indicate on the plot in arc seconds 674 @type color: string 675 @param color: any valid matplotlib color string 676 @type fontSize: float 677 @param fontSize: size of font used to label N and E, in points 678 @type width: float 679 @param width: width of arrow used to mark scale 680 681 """ 682 683 # Work out where the scale bar is going in WCS coords from the relative location given 684 if type(location) == str: 685 cRADeg, cDecDeg=self.wcs.getCentreWCSCoords() 686 RAMin, RAMax, decMin, decMax=self.wcs.getImageMinMaxWCSCoords() 687 westPoint,eastPoint,southPoint,northPoint=astCoords.calcRADecSearchBox(cRADeg, cDecDeg, sizeArcSec/3600.0/2.0) 688 sizeRADeg=eastPoint-westPoint 689 sizeDecDeg=northPoint-southPoint 690 xSizePix=(sizeArcSec/3600.0)/self.wcs.getXPixelSizeDeg() 691 ySizePix=(sizeArcSec/3600.0)/self.wcs.getYPixelSizeDeg() 692 X=self.data.shape[1] 693 Y=self.data.shape[0] 694 xBufferPix=0.6*ySizePix 695 yBufferPix=0.05*Y 696 cx, cy=self.wcs.wcs2pix(cRADeg, cDecDeg) 697 foundLocation=False 698 x=cy 699 y=cx 700 if self.wcs.isFlipped() == False: 701 if location.find("N") != -1: 702 y=Y-1.5*yBufferPix 703 foundLocation=True 704 if location.find("S") != -1: 705 y=yBufferPix 706 foundLocation=True 707 if location.find("E") != -1: 708 x=xBufferPix 709 foundLocation=True 710 if location.find("W") != -1: 711 x=X-xBufferPix 712 foundLocation=True 713 else: 714 if location.find("S") != -1: 715 y=Y-1.5*yBufferPix 716 foundLocation=True 717 if location.find("N") != -1: 718 y=yBufferPix 719 foundLocation=True 720 if location.find("W") != -1: 721 x=xBufferPix 722 foundLocation=True 723 if location.find("E") != -1: 724 x=X-xBufferPix 725 foundLocation=True 726 if foundLocation == False: 727 raise Exception("didn't understand location string for scale bar (should be e.g. N, S, E, W).") 728 RADeg, decDeg=self.wcs.pix2wcs(x, y) 729 elif type(location) == tuple or type(location) == list: 730 x, y=location 731 RADeg, decDeg=self.wcs.pix2wcs(x, y) 732 else: 733 raise Exception("didn't understand location for scale bar - should be string or tuple.") 734 735 alreadyGot=False 736 for p in self.plotObjects: 737 if p['tag'] == "scaleBar": 738 p['x']=[x] 739 p['y']=[y] 740 p['RA']=[RADeg] 741 p['dec']=[decDeg] 742 p['tag']="scaleBar" 743 p['objLabels']=[None] 744 p['symbol']="scaleBar" 745 p['sizeArcSec']=sizeArcSec 746 p['width']=width 747 p['color']=color 748 p['objLabelSize']=fontSize 749 alreadyGot=True 750 751 if alreadyGot == False: 752 self.plotObjects.append({'x': [x], 'y': [y], 'RA': [RADeg], 'dec': [decDeg], 753 'tag': "scaleBar", 'objLabels': [None], 'symbol': "scaleBar", 754 'width': width, 'color': color, 755 'objLabelSize': fontSize, 'sizeArcSec': sizeArcSec}) 756 self.draw()
757 758
759 - def calcWCSAxisLabels(self, axesLabels = "decimal"):
760 """This function calculates the positions of coordinate labels for the RA and Dec axes of the 761 ImagePlot. The tick steps are calculated automatically unless self.RATickSteps, 762 self.decTickSteps are set to values other than "auto" (see L{ImagePlot.__init__}). 763 764 The ImagePlot must be redrawn for changes to be applied. 765 766 @type axesLabels: string 767 @param axesLabels: either "sexagesimal" (for H:M:S, D:M:S), "decimal" (for decimal degrees), 768 or None for no coordinate axes labels 769 770 """ 771 772 # Label equinox on axes 773 equinox=self.wcs.getEquinox() 774 if equinox<1984: 775 equinoxLabel="B"+str(int(equinox)) 776 else: 777 equinoxLabel="J"+str(int(equinox)) 778 779 self.axesLabels=axesLabels 780 781 ticsDict=self.getTickSteps() 782 783 # Manual override - note: no minor tick marks anymore, but may want to bring them back 784 if self.RATickSteps != "auto": 785 ticsDict['major']['RA']=self.RATickSteps 786 if self.decTickSteps != "auto": 787 ticsDict['major']['dec']=self.decTickSteps 788 789 RALocs=[] 790 decLocs=[] 791 RALabels=[] 792 decLabels=[] 793 key="major" 794 #for key in ticsDict.keys(): # key is major or minor 795 if self.axesLabels == "sexagesimal": 796 self.RAAxisLabel="R.A. ("+equinoxLabel+")" 797 self.decAxisLabel="Dec. ("+equinoxLabel+")" 798 RADegStep=ticsDict[key]['RA']['deg'] 799 decDegStep=ticsDict[key]['dec']['deg'] 800 elif self.axesLabels == "decimal": 801 self.RAAxisLabel="R.A. Degrees ("+equinoxLabel+")" 802 self.decAxisLabel="Dec. Degrees ("+equinoxLabel+")" 803 RADegStep=ticsDict[key]['RA'] 804 decDegStep=ticsDict[key]['dec'] 805 else: 806 raise Exception("axesLabels must be either 'sexagesimal' or 'decimal'") 807 808 xArray=numpy.arange(0, self.data.shape[1], 1) 809 yArray=numpy.arange(0, self.data.shape[0], 1) 810 xWCS=self.wcs.pix2wcs(xArray, numpy.zeros(xArray.shape[0], dtype=float)) 811 yWCS=self.wcs.pix2wcs(numpy.zeros(yArray.shape[0], dtype=float), yArray) 812 xWCS=numpy.array(xWCS) 813 yWCS=numpy.array(yWCS) 814 ras=xWCS[:,0] 815 decs=yWCS[:,1] 816 RAEdges=numpy.array([ras[0], ras[-1]]) 817 RAMin=RAEdges.min() 818 RAMax=RAEdges.max() 819 decMin=decs.min() 820 decMax=decs.max() 821 822 # Work out if wrapped around 823 midRAPix, midDecPix=self.wcs.wcs2pix((RAEdges[1]+RAEdges[0])/2.0, (decMax+decMin)/2.0) 824 if midRAPix < 0 or midRAPix > self.wcs.header['NAXIS1']: 825 wrappedRA=True 826 else: 827 wrappedRA=False 828 829 # Note RA, dec work in opposite sense below because E at left 830 if ras[1] < ras[0]: 831 self.flipXAxis=False 832 ra2x=interpolate.interp1d(ras[::-1], xArray[::-1], kind='linear') 833 else: 834 self.flipXAxis=True 835 ra2x=interpolate.interp1d(ras, xArray, kind='linear') 836 if decs[1] < decs[0]: 837 self.flipYAxis=True 838 dec2y=interpolate.interp1d(decs[::-1], yArray[::-1], kind='linear') 839 else: 840 self.flipYAxis=False 841 dec2y=interpolate.interp1d(decs, yArray, kind='linear') 842 843 if wrappedRA == False: 844 RAPlotMin=RADegStep*math.modf(RAMin/RADegStep)[1] 845 RAPlotMax=RADegStep*math.modf(RAMax/RADegStep)[1] 846 if RAPlotMin < RAMin: 847 RAPlotMin=RAPlotMin+RADegStep 848 if RAPlotMax >= RAMax: 849 RAPlotMax=RAPlotMax-RADegStep 850 RADegs=numpy.arange(RAPlotMin, RAPlotMax+0.0001, RADegStep) 851 else: 852 RAPlotMin=RADegStep*math.modf(RAMin/RADegStep)[1] 853 RAPlotMax=RADegStep*math.modf(RAMax/RADegStep)[1] 854 if RAPlotMin > RAMin: 855 RAPlotMin=RAPlotMin-RADegStep 856 if RAPlotMax <= RAMax: 857 RAPlotMax=RAPlotMax+RADegStep 858 for i in range(ras.shape[0]): 859 if ras[i] >= RAMax and ras[i] <= 360.0: 860 ras[i]=ras[i]-360.0 861 if ras[1] < ras[0]: 862 ra2x=interpolate.interp1d(ras[::-1], xArray[::-1], kind='linear') 863 else: 864 ra2x=interpolate.interp1d(ras, xArray, kind='linear') 865 RADegs=numpy.arange(RAPlotMin, RAPlotMax-360.0-0.0001, -RADegStep) 866 867 decPlotMin=decDegStep*math.modf(decMin/decDegStep)[1] 868 decPlotMax=decDegStep*math.modf(decMax/decDegStep)[1] 869 if decPlotMin < decMin: 870 decPlotMin=decPlotMin+decDegStep 871 if decPlotMax >= decMax: 872 decPlotMax=decPlotMax-decDegStep 873 decDegs=numpy.arange(decPlotMin, decPlotMax+0.0001, decDegStep) 874 875 if key == "major": 876 if axesLabels == "sexagesimal": 877 for r in RADegs: 878 if r < 0: 879 r=r+360.0 880 h, m, s=astCoords.decimal2hms(r, ":").split(":") 881 hInt=int(round(float(h))) 882 if ticsDict[key]['RA']['unit'] == 'h' and (60.0-float(m)) < 0.01: # Check for rounding error 883 hInt=hInt+1 884 if hInt < 10: 885 hString="0"+str(hInt) 886 else: 887 hString=str(hInt) 888 mInt=int(round(float(m))) 889 if ticsDict[key]['RA']['unit'] == 'm' and (60.0-float(s)) < 0.01: # Check for rounding error 890 mInt=mInt+1 891 if mInt < 10: 892 mString="0"+str(mInt) 893 else: 894 mString=str(mInt) 895 sInt=int(round(float(s))) 896 if sInt < 10: 897 sString="0"+str(sInt) 898 else: 899 sString=str(sInt) 900 if ticsDict[key]['RA']['unit'] == 'h': 901 rString=hString+"$^{\sf{h}}$" 902 elif ticsDict[key]['RA']['unit'] == 'm': 903 rString=hString+"$^{\sf{h}}$"+mString+"$^{\sf{m}}$" 904 else: 905 rString=hString+"$^{\sf{h}}$"+mString+"$^{\sf{m}}$"+sString+"$^{\sf{s}}$" 906 RALabels.append(rString) 907 for D in decDegs: 908 d, m, s=astCoords.decimal2dms(D, ":").split(":") 909 dInt=int(round(float(d))) 910 if ticsDict[key]['dec']['unit'] == 'd' and (60.0-float(m)) < 0.01: # Check for rounding error 911 dInt=dInt+1 912 if dInt < 10 and dInt >= 0 and D > 0: 913 dString="+0"+str(dInt) 914 elif dInt > -10 and dInt <= 0 and D < 0: 915 dString="-0"+str(abs(dInt)) 916 elif dInt >= 10: 917 dString="+"+str(dInt) 918 else: 919 dString=str(dInt) 920 mInt=int(round(float(m))) 921 if ticsDict[key]['dec']['unit'] == 'm' and (60.0-float(s)) < 0.01: # Check for rounding error 922 mInt=mInt+1 923 if mInt < 10: 924 mString="0"+str(mInt) 925 else: 926 mString=str(mInt) 927 sInt=int(round(float(s))) 928 if sInt < 10: 929 sString="0"+str(sInt) 930 else: 931 sString=str(sInt) 932 if ticsDict[key]['dec']['unit'] == 'd': 933 dString=dString+DEG 934 elif ticsDict[key]['dec']['unit'] == 'm': 935 dString=dString+DEG+mString+PRIME 936 else: 937 dString=dString+DEG+mString+PRIME+sString+DOUBLE_PRIME 938 decLabels.append(dString) 939 elif axesLabels == "decimal": 940 941 if wrappedRA == False: 942 RALabels=RALabels+RADegs.tolist() 943 else: 944 nonNegativeLabels=[] 945 for r in RADegs: 946 if r < 0: 947 r=r+360.0 948 nonNegativeLabels.append(r) 949 RALabels=RALabels+nonNegativeLabels 950 decLabels=decLabels+decDegs.tolist() 951 952 # Format RALabels, decLabels to same number of d.p. 953 dpNumRA=len(str(ticsDict['major']['RA']).split(".")[-1]) 954 dpNumDec=len(str(ticsDict['major']['dec']).split(".")[-1]) 955 for i in range(len(RALabels)): 956 fString="%."+str(dpNumRA)+"f" 957 RALabels[i]=fString % (RALabels[i]) 958 for i in range(len(decLabels)): 959 fString="%."+str(dpNumDec)+"f" 960 decLabels[i]=fString % (decLabels[i]) 961 962 if key == 'minor': 963 RALabels=RALabels+RADegs.shape[0]*[''] 964 decLabels=decLabels+decDegs.shape[0]*[''] 965 966 RALocs=RALocs+ra2x(RADegs).tolist() 967 decLocs=decLocs+dec2y(decDegs).tolist() 968 969 self.ticsRA=[RALocs, RALabels] 970 self.ticsDec=[decLocs, decLabels]
971 972
973 - def save(self, fileName):
974 """Saves the ImagePlot in any format that matplotlib can understand, as determined from the 975 fileName extension. 976 977 @type fileName: string 978 @param fileName: path where plot will be written 979 980 """ 981 982 pylab.draw() 983 pylab.savefig(fileName)
984 985
986 - def getTickSteps(self):
987 """Chooses the appropriate WCS coordinate tick steps for the plot based on its size. 988 Whether the ticks are decimal or sexagesimal is set by self.axesLabels. 989 990 Note: minor ticks not used at the moment. 991 992 @rtype: dictionary 993 @return: tick step sizes for major, minor plot ticks, in format {'major', 'minor'} 994 995 """ 996 997 # Aim for 5 major tick marks on a plot 998 xArray=numpy.arange(0, self.data.shape[1], 1) 999 yArray=numpy.arange(0, self.data.shape[0], 1) 1000 xWCS=self.wcs.pix2wcs(xArray, numpy.zeros(xArray.shape[0], dtype=float)) 1001 yWCS=self.wcs.pix2wcs(numpy.zeros(yArray.shape[0], dtype=float), yArray) 1002 xWCS=numpy.array(xWCS) 1003 yWCS=numpy.array(yWCS) 1004 ras=xWCS[:,0] 1005 decs=yWCS[:,1] 1006 RAEdges=numpy.array([ras[0], ras[-1]]) 1007 RAMin=RAEdges.min() 1008 RAMax=RAEdges.max() 1009 decMin=decs.min() 1010 decMax=decs.max() 1011 1012 # Work out if wrapped around 1013 midRAPix, midDecPix=self.wcs.wcs2pix((RAEdges[1]+RAEdges[0])/2.0, (decMax+decMin)/2.0) 1014 if midRAPix < 0 or midRAPix > self.wcs.header['NAXIS1']: 1015 wrappedRA=True 1016 else: 1017 wrappedRA=False 1018 if wrappedRA == False: 1019 RAWidthDeg=RAMax-RAMin 1020 else: 1021 RAWidthDeg=(360.0-RAMax)+RAMin 1022 decHeightDeg=decMax-decMin 1023 1024 ticsDict={} 1025 ticsDict['major']={} 1026 ticsDict['minor']={} 1027 if self.axesLabels == "sexagesimal": 1028 1029 matchIndex = 0 1030 for i in range(len(RA_TICK_STEPS)): 1031 if RAWidthDeg/2.5 > RA_TICK_STEPS[i]['deg']: 1032 matchIndex = i 1033 1034 ticsDict['major']['RA']=RA_TICK_STEPS[matchIndex] 1035 ticsDict['minor']['RA']=RA_TICK_STEPS[matchIndex-1] 1036 1037 matchIndex = 0 1038 for i in range(len(DEC_TICK_STEPS)): 1039 if decHeightDeg/2.5 > DEC_TICK_STEPS[i]['deg']: 1040 matchIndex = i 1041 1042 ticsDict['major']['dec']=DEC_TICK_STEPS[matchIndex] 1043 ticsDict['minor']['dec']=DEC_TICK_STEPS[matchIndex-1] 1044 1045 return ticsDict 1046 1047 elif self.axesLabels == "decimal": 1048 1049 matchIndex = 0 1050 for i in range(len(DECIMAL_TICK_STEPS)): 1051 if RAWidthDeg/2.5 > DECIMAL_TICK_STEPS[i]: 1052 matchIndex = i 1053 1054 ticsDict['major']['RA']=DECIMAL_TICK_STEPS[matchIndex] 1055 ticsDict['minor']['RA']=DECIMAL_TICK_STEPS[matchIndex-1] 1056 1057 matchIndex = 0 1058 for i in range(len(DECIMAL_TICK_STEPS)): 1059 if decHeightDeg/2.5 > DECIMAL_TICK_STEPS[i]: 1060 matchIndex = i 1061 1062 ticsDict['major']['dec']=DECIMAL_TICK_STEPS[matchIndex] 1063 ticsDict['minor']['dec']=DECIMAL_TICK_STEPS[matchIndex-1] 1064 1065 return ticsDict 1066 1067 else: 1068 raise Exception("axesLabels must be either 'sexagesimal' or 'decimal'")
1069

astLib-0.10.0/docs/astLib/astLib.astSED-module.html0000664000175000017500000007721713047255533022232 0ustar mattymatty00000000000000 astLib.astSED
Package astLib :: Module astSED
[hide private]
[frames] | no frames]

Module astSED

source code

module for performing calculations on Spectral Energy Distributions (SEDs)

(c) 2007-2013 Matt Hilton

http://astlib.sourceforge.net

This module provides classes for manipulating SEDs, in particular the Bruzual & Charlot 2003, Maraston 2005, and Percival et al 2009 stellar population synthesis models are currently supported. Functions are provided for calculating the evolution of colours and magnitudes in these models with redshift etc., and for fitting broadband photometry using these models.

Classes [hide private]
  Passband
This class describes a filter transmission curve.
  TopHatPassband
This class generates a passband with a top hat response between the given wavelengths.
  SED
This class describes a Spectral Energy Distribution (SED).
  VegaSED
This class stores the SED of Vega, used for calculation of magnitudes on the Vega system.
  StellarPopulation
This class describes a stellar population model, either a Simple Stellar Population (SSP) or a Composite Stellar Population (CSP), such as the models of Bruzual & Charlot 2003 or Maraston 2005.
  M05Model
This class describes a Maraston 2005 stellar population model.
  BC03Model
This class describes a Bruzual & Charlot 2003 stellar population model, extracted from a GALAXEV .ised file using the galaxevpl program that is included in GALAXEV.
  P09Model
This class describes a Percival et al 2009 (BaSTI; http://albione.oa-teramo.inaf.it) stellar population model.
Functions [hide private]
list
makeModelSEDDictList(modelList, z, passbandsList, labelsList=[], EBMinusVList=[0.0], forceYoungerThanUniverse=True)
This routine makes a list of SEDDict dictionaries (see mags2SEDDict) for fitting using fitSEDDict.
source code
dictionary
fitSEDDict(SEDDict, modelSEDDictList)
Fits the given SED dictionary (made using mags2SEDDict) with the given list of model SED dictionaries.
source code
dictionary
mags2SEDDict(ABMags, ABMagErrs, passbands)
Takes a set of corresponding AB magnitudes, uncertainties, and passbands, and returns a dictionary with keys 'flux', 'fluxErr', 'wavelength'.
source code
list
mag2Flux(ABMag, ABMagErr, passband)
Converts given AB magnitude and uncertainty into flux, in erg/s/cm^2/Angstrom.
source code
list
flux2Mag(flux, fluxErr, passband)
Converts given flux and uncertainty in erg/s/cm^2/Angstrom into AB magnitudes.
source code
float
mag2Jy(ABMag)
Converts an AB magnitude into flux density in Jy
source code
float
Jy2Mag(fluxJy)
Converts flux density in Jy into AB magnitude
source code
Variables [hide private]
SED object VEGA = VegaSED()
The SED of Vega, used for calculation of magnitudes on the Vega system.
SED object AB = SED(wavelength= numpy.logspace(1, 8, 1e5), flux= numpy.on...
Flat spectrum SED, used for calculation of magnitudes on the AB system.
SED object SOL = SED()
The SED of the Sun.
  __package__ = 'astLib'
Function Details [hide private]

makeModelSEDDictList(modelList, z, passbandsList, labelsList=[], EBMinusVList=[0.0], forceYoungerThanUniverse=True)

source code 

This routine makes a list of SEDDict dictionaries (see mags2SEDDict) for fitting using fitSEDDict. This speeds up the fitting as this allows us to calculate model SED magnitudes only once, if all objects to be fitted are at the same redshift. We add some meta data to the modelSEDDicts (e.g. the model file names).

The effect of extinction by dust (assuming the Calzetti et al. 2000 law) can be included by giving a list of E(B-V) values.

If forceYoungerThanUniverse == True, ages which are older than the universe at the given z will not be included.

Parameters:
  • modelList (list of StellarPopulation model objects) - list of StellarPopulation models to include
  • z (float) - redshift to apply to all stellar population models in modelList
  • EBMinusVList (list) - list of E(B-V) extinction values to apply to all models, in magnitudes
  • labelsList (list) - optional list used for labelling passbands in output SEDDicts
  • forceYoungerThanUniverse (bool) - if True, do not allow models that exceed the age of the universe at z
Returns: list
list of dictionaries containing model fluxes, to be used as input to fitSEDDict.

fitSEDDict(SEDDict, modelSEDDictList)

source code 

Fits the given SED dictionary (made using mags2SEDDict) with the given list of model SED dictionaries. The latter should be made using makeModelSEDDictList, and entries for fluxes should correspond directly between the model and SEDDict.

Returns a dictionary with best fit values.

Parameters:
  • SEDDict (dictionary, in format of mags2SEDDict) - dictionary of observed fluxes and uncertainties, in format of mags2SEDDict
  • modelSEDDictList (list of dictionaries, in format of makeModelSEDDictList) - list of dictionaries containing fluxes of models to be fitted to the observed fluxes listed in the SEDDict. This should be made using makeModelSEDDictList.
Returns: dictionary
results of the fitting - keys:
  • 'minChiSq': minimum chi squared value of best fit
  • 'chiSqContrib': corresponding contribution at each passband to the minimum chi squared value
  • 'ageGyr': the age in Gyr of the best fitting model
  • 'modelFileName': the file name of the stellar population model corresponding to the best fit
  • 'modelListIndex': the index of the best fitting model in the input modelSEDDictList
  • 'norm': the normalisation that the best fit model should be multiplied by to match the SEDDict
  • 'z': the redshift of the best fit model
  • 'E(B-V)': the extinction, E(B-V), in magnitudes, of the best fit model

mags2SEDDict(ABMags, ABMagErrs, passbands)

source code 

Takes a set of corresponding AB magnitudes, uncertainties, and passbands, and returns a dictionary with keys 'flux', 'fluxErr', 'wavelength'. Fluxes are in units of erg/s/cm^2/Angstrom, wavelength in Angstroms. These dictionaries are the staple diet of the fitSEDDict routine.

Parameters:
  • ABMags (list or numpy array) - AB magnitudes, specified in corresponding order to passbands and ABMagErrs
  • ABMagErrs (list or numpy array) - AB magnitude errors, specified in corresponding order to passbands and ABMags
  • passbands (list of Passband objects) - passband objects, specified in corresponding order to ABMags and ABMagErrs
Returns: dictionary
dictionary with keys {'flux', 'fluxErr', 'wavelength'}, suitable for input to fitSEDDict

mag2Flux(ABMag, ABMagErr, passband)

source code 

Converts given AB magnitude and uncertainty into flux, in erg/s/cm^2/Angstrom.

Parameters:
  • ABMag (float) - magnitude on AB system in passband
  • ABMagErr (float) - uncertainty in AB magnitude in passband
  • passband (Passband object) - Passband object at which ABMag was measured
Returns: list
[flux, fluxError], in units of erg/s/cm^2/Angstrom

flux2Mag(flux, fluxErr, passband)

source code 

Converts given flux and uncertainty in erg/s/cm^2/Angstrom into AB magnitudes.

Parameters:
  • flux (float) - flux in erg/s/cm^2/Angstrom in passband
  • fluxErr (float) - uncertainty in flux in passband, in erg/s/cm^2/Angstrom
  • passband (Passband object) - Passband object at which ABMag was measured
Returns: list
[ABMag, ABMagError], in AB magnitudes

mag2Jy(ABMag)

source code 

Converts an AB magnitude into flux density in Jy

Parameters:
  • ABMag (float) - AB magnitude
Returns: float
flux density in Jy

Jy2Mag(fluxJy)

source code 

Converts flux density in Jy into AB magnitude

Parameters:
  • fluxJy (float) - flux density in Jy
Returns: float
AB magnitude

Variables Details [hide private]

AB

Flat spectrum SED, used for calculation of magnitudes on the AB system.
Type:
SED object
Value:
SED(wavelength= numpy.logspace(1, 8, 1e5), flux= numpy.ones(1e6))

astLib-0.10.0/docs/astLib/astLib.astStats-pysrc.html0000644000175000017500000054463513047255533022571 0ustar mattymatty00000000000000 astLib.astStats
Package astLib :: Module astStats
[hide private]
[frames] | no frames]

Source Code for Module astLib.astStats

  1  """module for performing statistical calculations. 
  2   
  3  (c) 2007-2012 Matt Hilton  
  4   
  5  (c) 2013-2014 Matt Hilton & Steven Boada 
  6   
  7  U{http://astlib.sourceforge.net} 
  8   
  9  This module (as you may notice) provides very few statistical routines. It does, however, provide 
 10  biweight (robust) estimators of location and scale, as described in Beers et al. 1990 (AJ, 100, 
 11  32), in addition to a robust least squares fitting routine that uses the biweight transform. 
 12   
 13  Some routines may fail if they are passed lists with few items and encounter a `divide by zero' 
 14  error. Where this occurs, the function will return None. An error message will be printed to the 
 15  console when this happens if astStats.REPORT_ERRORS=True (the default). Testing if an 
 16  astStats function returns None can be used to handle errors in scripts.  
 17   
 18  For extensive statistics modules, the Python bindings for GNU R (U{http://rpy.sourceforge.net}), or 
 19  SciPy (U{http://www.scipy.org}) are suggested. 
 20   
 21  """ 
 22   
 23  import math 
 24  import numpy 
 25  import sys 
 26   
 27  REPORT_ERRORS=True 
 28   
 29  #--------------------------------------------------------------------------------------------------- 
30 -def mean(dataList):
31 """Calculates the mean average of a list of numbers. 32 33 @type dataList: list or numpy array 34 @param dataList: input data, must be a one dimensional list 35 @rtype: float 36 @return: mean average 37 38 """ 39 return numpy.mean(dataList)
40 41 #---------------------------------------------------------------------------------------------------
42 -def weightedMean(dataList):
43 """Calculates the weighted mean average of a two dimensional list (value, weight) of 44 numbers. 45 46 @type dataList: list 47 @param dataList: input data, must be a two dimensional list in format [value, weight] 48 @rtype: float 49 @return: weighted mean average 50 51 """ 52 sum=0 53 weightSum=0 54 for item in dataList: 55 sum=sum+float(item[0]*item[1]) 56 weightSum=weightSum+item[1] 57 if len(dataList)>0: 58 mean=sum/weightSum 59 else: 60 mean=0 61 return mean
62 63 #---------------------------------------------------------------------------------------------------
64 -def stdev(dataList):
65 """Calculates the (sample) standard deviation of a list of numbers. 66 67 @type dataList: list or numpy array 68 @param dataList: input data, must be a one dimensional list 69 @rtype: float 70 @return: standard deviation 71 72 """ 73 return numpy.std(dataList)
74 75 #---------------------------------------------------------------------------------------------------
76 -def rms(dataList):
77 """Calculates the root mean square of a list of numbers. 78 79 @type dataList: list 80 @param dataList: input data, must be a one dimensional list 81 @rtype: float 82 @return: root mean square 83 84 """ 85 dataListSq=[] 86 for item in dataList: 87 dataListSq.append(item*item) 88 listMeanSq=mean(dataListSq) 89 rms=math.sqrt(listMeanSq) 90 91 return rms
92 93 #---------------------------------------------------------------------------------------------------
94 -def weightedStdev(dataList):
95 """Calculates the weighted (sample) standard deviation of a list of numbers. 96 97 @type dataList: list 98 @param dataList: input data, must be a two dimensional list in format [value, weight] 99 @rtype: float 100 @return: weighted standard deviation 101 102 @note: Returns None if an error occurs. 103 104 """ 105 listMean=weightedMean(dataList) 106 sum=0 107 wSum=0 108 wNonZero=0 109 for item in dataList: 110 if item[1]>0.0: 111 sum=sum+float((item[0]-listMean)/item[1])*float((item[0]-listMean)/item[1]) 112 wSum=wSum+float(1.0/item[1])*float(1.0/item[1]) 113 114 if len(dataList)>1: 115 nFactor=float(len(dataList))/float(len(dataList)-1) 116 stdev=math.sqrt(nFactor*(sum/wSum)) 117 else: 118 if REPORT_ERRORS==True: 119 print("""ERROR: astStats.weightedStdev() : dataList contains < 2 items.""") 120 stdev=None 121 return stdev
122 123 #---------------------------------------------------------------------------------------------------
124 -def median(dataList):
125 """Calculates the median of a list of numbers. 126 127 @type dataList: list or numpy array 128 @param dataList: input data, must be a one dimensional list 129 @rtype: float 130 @return: median average 131 132 """ 133 return numpy.median(dataList)
134 135 #---------------------------------------------------------------------------------------------------
136 -def modeEstimate(dataList):
137 """Returns an estimate of the mode of a set of values by mode=(3*median)-(2*mean). 138 139 @type dataList: list 140 @param dataList: input data, must be a one dimensional list 141 @rtype: float 142 @return: estimate of mode average 143 144 """ 145 mode=(3*median(dataList))-(2*mean(dataList)) 146 147 return mode
148 149 #---------------------------------------------------------------------------------------------------
150 -def MAD(dataList):
151 """Calculates the Median Absolute Deviation of a list of numbers. 152 153 @type dataList: list 154 @param dataList: input data, must be a one dimensional list 155 @rtype: float 156 @return: median absolute deviation 157 158 """ 159 listMedian=median(dataList) 160 161 # Calculate |x-M| values 162 diffModuli=[] 163 for item in dataList: 164 diffModuli.append(math.fabs(item-listMedian)) 165 166 MAD=median(diffModuli) 167 168 return MAD
169 170 #---------------------------------------------------------------------------------------------------
171 -def biweightLocation(dataList, tuningConstant):
172 """Calculates the biweight location estimator (like a robust average) of a list of 173 numbers. 174 175 @type dataList: list 176 @param dataList: input data, must be a one dimensional list 177 @type tuningConstant: float 178 @param tuningConstant: 6.0 is recommended. 179 @rtype: float 180 @return: biweight location 181 182 @note: Returns None if an error occurs. 183 184 """ 185 C=tuningConstant 186 listMedian=median(dataList) 187 listMAD=MAD(dataList) 188 if listMAD!=0: 189 uValues=[] 190 for item in dataList: 191 uValues.append((item-listMedian)/(C*listMAD)) 192 193 top=0 # numerator equation (5) Beers et al if you like 194 bottom=0 # denominator 195 for i in range(len(uValues)): 196 if math.fabs(uValues[i])<=1.0: 197 top=top+((dataList[i]-listMedian) \ 198 *(1.0-(uValues[i]*uValues[i])) \ 199 *(1.0-(uValues[i]*uValues[i]))) 200 201 bottom=bottom+((1.0-(uValues[i]*uValues[i])) \ 202 *(1.0-(uValues[i]*uValues[i]))) 203 204 CBI=listMedian+(top/bottom) 205 206 else: 207 if REPORT_ERRORS==True: 208 print("""ERROR: astStats: biweightLocation() : MAD() returned 0.""") 209 return None 210 211 return CBI
212 213 #---------------------------------------------------------------------------------------------------
214 -def biweightScale(dataList, tuningConstant):
215 """Calculates the biweight scale estimator (like a robust standard deviation) of a list 216 of numbers. 217 218 @type dataList: list 219 @param dataList: input data, must be a one dimensional list 220 @type tuningConstant: float 221 @param tuningConstant: 9.0 is recommended. 222 @rtype: float 223 @return: biweight scale 224 225 @note: Returns None if an error occurs. 226 227 """ 228 C=tuningConstant 229 230 # Calculate |x-M| values and u values 231 listMedian=median(dataList) 232 listMAD=MAD(dataList) 233 diffModuli=[] 234 for item in dataList: 235 diffModuli.append(math.fabs(item-listMedian)) 236 uValues=[] 237 for item in dataList: 238 try: 239 uValues.append((item-listMedian)/(C*listMAD)) 240 except ZeroDivisionError: 241 if REPORT_ERRORS==True: 242 print("""ERROR: astStats.biweightScale() : divide by zero error.""") 243 return None 244 245 top=0 # numerator equation (9) Beers et al 246 bottom=0 247 valCount=0 # Count values where u<1 only 248 249 for i in range(len(uValues)): 250 # Skip u values >1 251 if math.fabs(uValues[i])<=1.0: 252 u2Term=1.0-(uValues[i]*uValues[i]) 253 u4Term=math.pow(u2Term, 4) 254 top=top+((diffModuli[i]*diffModuli[i])*u4Term) 255 bottom=bottom+(u2Term*(1.0-(5.0*(uValues[i]*uValues[i])))) 256 valCount=valCount+1 257 258 top=math.sqrt(top) 259 bottom=math.fabs(bottom) 260 261 SBI=math.pow(float(valCount), 0.5)*(top/bottom) 262 return SBI
263 264 #---------------------------------------------------------------------------------------------------
265 -def biweightClipped(dataList, tuningConstant, sigmaCut):
266 """Iteratively calculates biweight location and scale, using sigma clipping, for a list 267 of values. The calculation is performed on the first column of a multi-dimensional 268 list; other columns are ignored. 269 270 @type dataList: list 271 @param dataList: input data 272 @type tuningConstant: float 273 @param tuningConstant: 6.0 is recommended for location estimates, 9.0 is recommended for 274 scale estimates 275 @type sigmaCut: float 276 @param sigmaCut: sigma clipping to apply 277 @rtype: dictionary 278 @return: estimate of biweight location, scale, and list of non-clipped data, in the format 279 {'biweightLocation', 'biweightScale', 'dataList'} 280 281 @note: Returns None if an error occurs. 282 283 """ 284 285 iterations=0 286 clippedValues=[] 287 for row in dataList: 288 if type(row)==list: 289 clippedValues.append(row[0]) 290 else: 291 clippedValues.append(row) 292 293 while iterations<11 and len(clippedValues)>5: 294 295 cbi=biweightLocation(clippedValues, tuningConstant) 296 sbi=biweightScale(clippedValues, tuningConstant) 297 298 # check for either biweight routine falling over 299 # happens when feed in lots of similar numbers 300 # e.g. when bootstrapping with a small sample 301 if cbi==None or sbi==None: 302 303 if REPORT_ERRORS==True: 304 print("""ERROR: astStats : biweightClipped() : 305 divide by zero error.""") 306 307 return None 308 309 else: 310 311 clippedValues=[] 312 clippedData=[] 313 for row in dataList: 314 if type(row)==list: 315 if row[0]>cbi-(sigmaCut*sbi) \ 316 and row[0]<cbi+(sigmaCut*sbi): 317 clippedValues.append(row[0]) 318 clippedData.append(row) 319 else: 320 if row>cbi-(sigmaCut*sbi) \ 321 and row<cbi+(sigmaCut*sbi): 322 clippedValues.append(row) 323 clippedData.append(row) 324 325 iterations=iterations+1 326 327 return {'biweightLocation':cbi, 'biweightScale':sbi, 'dataList':clippedData}
328 329 #---------------------------------------------------------------------------------------------------
330 -def biweightTransform(dataList, tuningConstant):
331 """Calculates the biweight transform for a set of values. Useful for using as weights in 332 robust line fitting. 333 334 @type dataList: list 335 @param dataList: input data, must be a one dimensional list 336 @type tuningConstant: float 337 @param tuningConstant: 6.0 is recommended for location estimates, 9.0 is recommended for 338 scale estimates 339 @rtype: list 340 @return: list of biweights 341 342 """ 343 C=tuningConstant 344 345 # Calculate |x-M| values and u values 346 listMedian=abs(median(dataList)) 347 cutoff=C*listMedian 348 biweights=[] 349 for item in dataList: 350 if abs(item)<cutoff: 351 biweights.append([item, 352 (1.0-((item/cutoff)*(item/cutoff))) \ 353 *(1.0-((item/cutoff)*(item/cutoff)))]) 354 else: 355 biweights.append([item, 0.0]) 356 357 return biweights
358 359 #---------------------------------------------------------------------------------------------------
360 -def OLSFit(dataList):
361 """Performs an ordinary least squares fit on a two dimensional list of numbers. 362 Minimum number of data points is 5. 363 364 @type dataList: list 365 @param dataList: input data, must be a two dimensional list in format [x, y] 366 @rtype: dictionary 367 @return: slope and intercept on y-axis, with associated errors, in the format 368 {'slope', 'intercept', 'slopeError', 'interceptError'} 369 370 @note: Returns None if an error occurs. 371 372 """ 373 sumX=0 374 sumY=0 375 sumXY=0 376 sumXX=0 377 n=float(len(dataList)) 378 if n > 2: 379 for item in dataList: 380 sumX=sumX+item[0] 381 sumY=sumY+item[1] 382 sumXY=sumXY+(item[0]*item[1]) 383 sumXX=sumXX+(item[0]*item[0]) 384 m=((n*sumXY)-(sumX*sumY))/((n*sumXX)-(sumX*sumX)) 385 c=((sumXX*sumY)-(sumX*sumXY))/((n*sumXX)-(sumX*sumX)) 386 387 sumRes=0 388 for item in dataList: 389 390 sumRes=sumRes+((item[1]-(m*item[0])-c) \ 391 *(item[1]-(m*item[0])-c)) 392 393 sigma=math.sqrt((1.0/(n-2))*sumRes) 394 395 try: 396 mSigma=(sigma*math.sqrt(n))/math.sqrt((n*sumXX)-(sumX*sumX)) 397 except: 398 mSigma=numpy.nan 399 try: 400 cSigma=(sigma*math.sqrt(sumXX))/math.sqrt((n*sumXX)-(sumX*sumX)) 401 except: 402 cSigma=numpy.nan 403 else: 404 if REPORT_ERRORS==True: 405 print("""ERROR: astStats.OLSFit() : dataList contains < 3 items.""") 406 407 return None 408 409 return {'slope':m, 410 'intercept':c, 411 'slopeError':mSigma, 412 'interceptError':cSigma}
413 414 #---------------------------------------------------------------------------------------------------
415 -def clippedMeanStdev(dataList, sigmaCut = 3.0, maxIterations = 10.0):
416 """Calculates the clipped mean and stdev of a list of numbers. 417 418 @type dataList: list 419 @param dataList: input data, one dimensional list of numbers 420 @type sigmaCut: float 421 @param sigmaCut: clipping in Gaussian sigma to apply 422 @type maxIterations: int 423 @param maxIterations: maximum number of iterations 424 @rtype: dictionary 425 @return: format {'clippedMean', 'clippedStdev', 'numPoints'} 426 427 """ 428 429 listCopy=[] 430 for d in dataList: 431 listCopy.append(d) 432 listCopy=numpy.array(listCopy) 433 434 iterations=0 435 while iterations < maxIterations and len(listCopy) > 4: 436 437 m=listCopy.mean() 438 s=listCopy.std() 439 440 listCopy=listCopy[numpy.less(abs(listCopy), abs(m+sigmaCut*s))] 441 442 iterations=iterations+1 443 444 return {'clippedMean': m, 'clippedStdev': s, 'numPoints': listCopy.shape[0]}
445 446 #---------------------------------------------------------------------------------------------------
447 -def clippedWeightedLSFit(dataList, sigmaCut):
448 """Performs a weighted least squares fit on a list of numbers with sigma clipping. Minimum number of data 449 points is 5. 450 451 @type dataList: list 452 @param dataList: input data, must be a three dimensional list in format [x, y, y weight] 453 @rtype: dictionary 454 @return: slope and intercept on y-axis, with associated errors, in the format 455 {'slope', 'intercept', 'slopeError', 'interceptError'} 456 457 @note: Returns None if an error occurs. 458 459 """ 460 461 iterations=0 462 clippedValues=[] 463 for row in dataList: 464 clippedValues.append(row) 465 466 while iterations<11 and len(clippedValues)>4: 467 468 fitResults=weightedLSFit(clippedValues, "errors") 469 470 if fitResults['slope'] == None: 471 472 if REPORT_ERRORS==True: 473 print("""ERROR: astStats : clippedWeightedLSFit() : 474 divide by zero error.""") 475 476 return None 477 478 else: 479 480 clippedValues=[] 481 for row in dataList: 482 483 # Trim points more than sigmaCut*sigma away from the fitted line 484 fit=fitResults['slope']*row[0]+fitResults['intercept'] 485 res=row[1]-fit 486 if abs(res)/row[2] < sigmaCut: 487 clippedValues.append(row) 488 489 iterations=iterations+1 490 491 # store the number of values that made it through the clipping process 492 fitResults['numDataPoints']=len(clippedValues) 493 494 return fitResults
495 496 #---------------------------------------------------------------------------------------------------
497 -def weightedLSFit(dataList, weightType):
498 """Performs a weighted least squares fit on a three dimensional list of numbers [x, y, y error]. 499 500 @type dataList: list 501 @param dataList: input data, must be a three dimensional list in format [x, y, y error] 502 @type weightType: string 503 @param weightType: if "errors", weights are calculated assuming the input data is in the 504 format [x, y, error on y]; if "weights", the weights are assumed to be already calculated and 505 stored in a fourth column [x, y, error on y, weight] (as used by e.g. L{astStats.biweightLSFit}) 506 @rtype: dictionary 507 @return: slope and intercept on y-axis, with associated errors, in the format 508 {'slope', 'intercept', 'slopeError', 'interceptError'} 509 510 @note: Returns None if an error occurs. 511 512 """ 513 if weightType == "weights": 514 sumW=0 515 sumWX=0 516 sumWY=0 517 sumWXY=0 518 sumWXX=0 519 n=float(len(dataList)) 520 if n > 4: 521 for item in dataList: 522 W=item[3] 523 sumWX=sumWX+(W*item[0]) 524 sumWY=sumWY+(W*item[1]) 525 sumWXY=sumWXY+(W*item[0]*item[1]) 526 sumWXX=sumWXX+(W*item[0]*item[0]) 527 sumW=sumW+W 528 #print sumW, sumWXX, sumWX 529 530 try: 531 m=((sumW*sumWXY)-(sumWX*sumWY)) \ 532 /((sumW*sumWXX)-(sumWX*sumWX)) 533 except ZeroDivisionError: 534 if REPORT_ERRORS == True: 535 print("ERROR: astStats.weightedLSFit() : divide by zero error.") 536 return None 537 538 try: 539 c=((sumWXX*sumWY)-(sumWX*sumWXY)) \ 540 /((sumW*sumWXX)-(sumWX*sumWX)) 541 except ZeroDivisionError: 542 if REPORT_ERRORS == True: 543 print("ERROR: astStats.weightedLSFit() : divide by zero error.") 544 return None 545 546 sumRes=0 547 for item in dataList: 548 549 sumRes=sumRes+((item[1]-(m*item[0])-c) \ 550 *(item[1]-(m*item[0])-c)) 551 552 sigma=math.sqrt((1.0/(n-2))*sumRes) 553 554 # Can get div0 errors here so check 555 # When biweight fitting converges this shouldn't happen 556 if (n*sumWXX)-(sumWX*sumWX)>0.0: 557 558 mSigma=(sigma*math.sqrt(n)) \ 559 /math.sqrt((n*sumWXX)-(sumWX*sumWX)) 560 561 cSigma=(sigma*math.sqrt(sumWXX)) \ 562 /math.sqrt((n*sumWXX)-(sumWX*sumWX)) 563 564 else: 565 566 if REPORT_ERRORS==True: 567 print("""ERROR: astStats.weightedLSFit() 568 : divide by zero error.""") 569 return None 570 571 else: 572 if REPORT_ERRORS==True: 573 print("""ERROR: astStats.weightedLSFit() : 574 dataList contains < 5 items.""") 575 return None 576 577 elif weightType == "errors": 578 sumX=0 579 sumY=0 580 sumXY=0 581 sumXX=0 582 sumSigma=0 583 n=float(len(dataList)) 584 for item in dataList: 585 sumX=sumX+(item[0]/(item[2]*item[2])) 586 sumY=sumY+(item[1]/(item[2]*item[2])) 587 sumXY=sumXY+((item[0]*item[1])/(item[2]*item[2])) 588 sumXX=sumXX+((item[0]*item[0])/(item[2]*item[2])) 589 sumSigma=sumSigma+(1.0/(item[2]*item[2])) 590 delta=(sumSigma*sumXX)-(sumX*sumX) 591 m=((sumSigma*sumXY)-(sumX*sumY))/delta 592 c=((sumXX*sumY)-(sumX*sumXY))/delta 593 mSigma=math.sqrt(sumSigma/delta) 594 cSigma=math.sqrt(sumXX/delta) 595 596 return {'slope':m, 597 'intercept':c, 598 'slopeError':mSigma, 599 'interceptError':cSigma}
600 601 #---------------------------------------------------------------------------------------------------
602 -def biweightLSFit(dataList, tuningConstant, sigmaCut = None):
603 """Performs a weighted least squares fit, where the weights used are the biweight 604 transforms of the residuals to the previous best fit .i.e. the procedure is iterative, 605 and converges very quickly (iterations is set to 10 by default). Minimum number of data 606 points is 10. 607 608 This seems to give slightly different results to the equivalent R routine, so use at your 609 own risk! 610 611 @type dataList: list 612 @param dataList: input data, must be a three dimensional list in format [x, y, y weight] 613 @type tuningConstant: float 614 @param tuningConstant: 6.0 is recommended for location estimates, 9.0 is recommended for 615 scale estimates 616 @type sigmaCut: float 617 @param sigmaCut: sigma clipping to apply (set to None if not required) 618 @rtype: dictionary 619 @return: slope and intercept on y-axis, with associated errors, in the format 620 {'slope', 'intercept', 'slopeError', 'interceptError'} 621 622 @note: Returns None if an error occurs. 623 624 """ 625 626 dataCopy=[] 627 for row in dataList: 628 dataCopy.append(row) 629 630 # First perform unweighted fit, then calculate residuals 631 results=OLSFit(dataCopy) 632 origLen=len(dataCopy) 633 for k in range(10): 634 m=results['slope'] 635 c=results['intercept'] 636 res=[] 637 for item in dataCopy: 638 res.append((m*item[0]+c)-item[1]) 639 640 if len(res)>5: 641 # For clipping, trim away things >3 sigma 642 # away from median 643 if sigmaCut != None: 644 absRes=[] 645 for item in res: 646 absRes.append(abs(item)) 647 sigma=stdev(absRes) 648 count=0 649 for item in absRes: 650 if item>(sigmaCut*sigma) \ 651 and len(dataCopy)>2: 652 del dataCopy[count] 653 del res[count] 654 655 # Index of datalist gets out of 656 # sync with absRes as we delete 657 # items 658 count=count-1 659 660 count=count+1 661 662 # Biweight transform residuals 663 weights=biweightTransform(res, tuningConstant) 664 665 # Perform weighted fit, using biweight transforms 666 # of residuals as weight 667 wData=[] 668 for i in range(len(dataCopy)): 669 wData.append([dataCopy[i][0], dataCopy[i][1], dataCopy[i][2], weights[i][1]]) 670 671 results=weightedLSFit(wData, "weights") 672 673 return results
674 675 #---------------------------------------------------------------------------------------------------
676 -def cumulativeBinner(data, binMin, binMax, binTotal):
677 """Bins the input data cumulatively. 678 679 @param data: input data, must be a one dimensional list 680 @type binMin: float 681 @param binMin: minimum value from which to bin data 682 @type binMax: float 683 @param binMax: maximum value from which to bin data 684 @type binTotal: int 685 @param binTotal: number of bins 686 @rtype: list 687 @return: binned data, in format [bin centre, frequency] 688 689 """ 690 #Bin data 691 binStep=float(binMax-binMin)/binTotal 692 bins=[] 693 totalItems=len(data) 694 for i in range(binTotal): 695 bins.append(0) 696 for item in data: 697 if item>(binMin+(i*binStep)): 698 bins[i]=bins[i]+1.0/totalItems 699 700 # Gnuplot requires points at bin midpoints 701 coords=[] 702 for i in range(binTotal): 703 coords.append([binMin+(float(i+0.5)*binStep), bins[i]]) 704 705 return coords
706 707 #---------------------------------------------------------------------------------------------------
708 -def binner(data, binMin, binMax, binTotal):
709 """Bins the input data.. 710 711 @param data: input data, must be a one dimensional list 712 @type binMin: float 713 @param binMin: minimum value from which to bin data 714 @type binMax: float 715 @param binMax: maximum value from which to bin data 716 @type binTotal: int 717 @param binTotal: number of bins 718 @rtype: list 719 @return: binned data, in format [bin centre, frequency] 720 721 """ 722 #Bin data 723 binStep=float(binMax-binMin)/binTotal 724 bins=[] 725 for i in range(binTotal): 726 bins.append(0) 727 for item in data: 728 if item>(binMin+(i*binStep)) \ 729 and item<=(binMin+((i+1)*binStep)): 730 bins[i]=bins[i]+1 731 732 # Gnuplot requires points at bin midpoints 733 coords=[] 734 for i in range(binTotal): 735 coords.append([binMin+(float(i+0.5)*binStep), bins[i]]) 736 737 return coords
738 739 #---------------------------------------------------------------------------------------------------
740 -def weightedBinner(data, weights, binMin, binMax, binTotal):
741 """Bins the input data, recorded frequency is sum of weights in bin. 742 743 @param data: input data, must be a one dimensional list 744 @type binMin: float 745 @param binMin: minimum value from which to bin data 746 @type binMax: float 747 @param binMax: maximum value from which to bin data 748 @type binTotal: int 749 @param binTotal: number of bins 750 @rtype: list 751 @return: binned data, in format [bin centre, frequency] 752 753 """ 754 #Bin data 755 binStep=float(binMax-binMin)/binTotal 756 bins=[] 757 for i in range(binTotal): 758 bins.append(0.0) 759 for item, weight in zip(data, weights): 760 if item>(binMin+(i*binStep)) \ 761 and item<=(binMin+((i+1)*binStep)): 762 bins[i]=bins[i]+weight 763 764 # Gnuplot requires points at bin midpoints 765 coords=[] 766 for i in range(binTotal): 767 coords.append([binMin+(float(i+0.5)*binStep), bins[i]]) 768 769 return coords
770 771 #--------------------------------------------------------------------------------------------------- 772

astLib-0.10.0/docs/astLib/astLib.astWCS-pysrc.html0000644000175000017500000033041713047255533022116 0ustar mattymatty00000000000000 astLib.astWCS
Package astLib :: Module astWCS
[hide private]
[frames] | no frames]

Source Code for Module astLib.astWCS

  1  """module for handling World Coordinate Systems (WCS) 
  2   
  3  (c) 2007-2012 Matt Hilton 
  4   
  5  (c) 2013-2014 Matt Hilton & Steven Boada 
  6   
  7  U{http://astlib.sourceforge.net} 
  8   
  9  This is a higher level interface to some of the routines in PyWCSTools 
 10  (distributed with astLib). 
 11  PyWCSTools is a simple SWIG wrapping of WCSTools by Jessica Mink 
 12  (U{http://tdc-www.harvard.edu/software/wcstools/}). It is intended is to make 
 13  this interface complete enough such that direct use of PyWCSTools is 
 14  unnecessary. 
 15   
 16  @var NUMPY_MODE: If True (default), pixel coordinates accepted/returned by 
 17      routines such as L{astWCS.WCS.pix2wcs}, L{astWCS.WCS.wcs2pix} have (0, 0) 
 18      as the origin. Set to False to make these routines accept/return pixel 
 19      coords with (1, 1) as the origin (i.e. to match the FITS convention, 
 20      default behaviour prior to astLib version 0.3.0). 
 21  @type NUMPY_MODE: bool 
 22   
 23  """ 
 24   
 25  #----------------------------------------------------------------------------- 
 26   
 27  # So far as I can tell in astropy 0.4 the API is the same as pyfits for what we need... 
 28  try: 
 29      import pyfits 
 30  except: 
 31      try: 
 32          from astropy.io import fits as pyfits 
 33      except: 
 34          raise Exception, "couldn't import either pyfits or astropy.io.fits" 
 35  from PyWCSTools import wcs 
 36  import numpy 
 37  import locale 
 38   
 39  # if True, -1 from pixel coords to be zero-indexed like numpy. If False, use 
 40  # FITS convention. 
 41  NUMPY_MODE = True 
 42   
 43  # Check for the locale bug when decimal separator isn't '.' (atof used in 
 44  # libwcs) 
 45  lconv = locale.localeconv() 
 46  if lconv['decimal_point'] != '.': 
 47      print("WARNING: decimal point separator is not '.' - astWCS coordinate conversions will not work.") 
 48      print("Workaround: after importing any modules that set the locale (e.g. matplotlib) do the following:") 
 49      print("   import locale") 
 50      print("   locale.setlocale(locale.LC_NUMERIC, 'C')") 
 51   
 52  #----------------------------------------------------------------------------- 
53 -class WCS:
54 """This class provides methods for accessing information from the World 55 Coordinate System (WCS) contained in the header of a FITS image. 56 Conversions between pixel and WCS coordinates can also be performed. 57 58 To create a WCS object from a FITS file called "test.fits", simply: 59 60 WCS=astWCS.WCS("test.fits") 61 62 Likewise, to create a WCS object from the pyfits.header of "test.fits": 63 64 img=pyfits.open("test.fits") 65 header=img[0].header 66 WCS=astWCS.WCS(header, mode = "pyfits") 67 68 """ 69
70 - def __init__(self, headerSource, extensionName = 0, mode = "image", zapKeywords = []):
71 """Creates a WCS object using either the information contained in the 72 header of the specified .fits image, or from a pyfits.header object. 73 Set mode = "pyfits" if the headerSource is a pyfits.header. 74 75 For some images from some archives, particular header keywords such as 76 COMMENT or HISTORY may contain unprintable strings. If you encounter 77 this, try setting zapKeywords = ['COMMENT', 'HISTORY'] (for example). 78 79 @type headerSource: string or pyfits.header 80 @param headerSource: filename of input .fits image, or a pyfits.header 81 object 82 @type extensionName: int or string 83 @param extensionName: name or number of .fits extension in which image 84 data is stored 85 @type mode: string 86 @param mode: set to "image" if headerSource is a .fits file name, or 87 set to "pyfits" if headerSource is a pyfits.header object 88 @type zapKeywords: list 89 @param: zapKeywords: keywords to remove from the header before making 90 astWCS object. 91 92 @note: The meta data provided by headerSource is stored in WCS.header 93 as a pyfits.header object. 94 95 """ 96 97 self.mode = mode 98 self.headerSource = headerSource 99 self.extensionName = extensionName 100 101 if self.mode == "image": 102 img = pyfits.open(self.headerSource) 103 # silentfix below won't deal with unprintable strings 104 # so here we optionally remove problematic keywords 105 for z in zapKeywords: 106 if z in img[self.extensionName].header.keys(): 107 for count in range(img[self.extensionName].header.count(z)): 108 img[self.extensionName].header.remove(z) 109 img.verify('silentfix') # solves problems with non-standard headers 110 self.header = img[self.extensionName].header 111 img.close() 112 elif self.mode == "pyfits": 113 for z in zapKeywords: 114 if z in self.headerSource.keys(): 115 for count in range(self.headerSource.count(z)): 116 self.headerSource.remove(z) 117 self.header=headerSource 118 119 self.updateFromHeader()
120 121
122 - def copy(self):
123 """Copies the WCS object to a new object. 124 125 @rtype: astWCS.WCS object 126 @return: WCS object 127 128 """ 129 130 # This only sets up a new WCS object, doesn't do a deep copy 131 ret = WCS(self.headerSource, self.extensionName, self.mode) 132 133 # This fixes copy bug 134 ret.header = self.header.copy() 135 ret.updateFromHeader() 136 137 return ret
138 139
140 - def updateFromHeader(self):
141 """Updates the WCS object using information from WCS.header. This 142 routine should be called whenever changes are made to WCS keywords in 143 WCS.header. 144 145 """ 146 147 # Updated for pyfits 3.1+ 148 newHead=pyfits.Header() 149 for i in self.header.items(): 150 if len(str(i[1])) < 70: 151 if len(str(i[0])) <= 8: 152 newHead.append((i[0], i[1])) 153 else: 154 newHead.append(('HIERARCH '+i[0], i[1])) 155 156 # Workaround for ZPN bug when PV2_3 == 0 (as in, e.g., ESO WFI images) 157 if "PV2_3" in list(newHead.keys()) and newHead['PV2_3'] == 0 and newHead['CTYPE1'] == 'RA---ZPN': 158 newHead["PV2_3"]=1e-15 159 160 cardstring = "" 161 for card in newHead.cards: 162 cardstring = cardstring+str(card) 163 164 self.WCSStructure = wcs.wcsinit(cardstring)
165 166
167 - def getCentreWCSCoords(self):
168 """Returns the RA and dec coordinates (in decimal degrees) at the 169 centre of the WCS. 170 171 @rtype: list 172 @return: coordinates in decimal degrees in format [RADeg, decDeg] 173 174 """ 175 full = wcs.wcsfull(self.WCSStructure) 176 177 RADeg = full[0] 178 decDeg = full[1] 179 180 return [RADeg, decDeg]
181 182
183 - def getFullSizeSkyDeg(self):
184 """Returns the width, height of the image according to the WCS in 185 decimal degrees on the sky (i.e., with the projection taken into 186 account). 187 188 @rtype: list 189 @return: width and height of image in decimal degrees on the sky in 190 format [width, height] 191 192 """ 193 full = wcs.wcsfull(self.WCSStructure) 194 195 width = full[2] 196 height = full[3] 197 198 return [width, height]
199 200
201 - def getHalfSizeDeg(self):
202 """Returns the half-width, half-height of the image according to the 203 WCS in RA and dec degrees. 204 205 @rtype: list 206 @return: half-width and half-height of image in R.A., dec. decimal 207 degrees in format [half-width, half-height] 208 209 """ 210 half = wcs.wcssize(self.WCSStructure) 211 212 width = half[2] 213 height = half[3] 214 215 return [width, height]
216 217
218 - def getImageMinMaxWCSCoords(self):
219 """Returns the minimum, maximum WCS coords defined by the size of the 220 parent image (as defined by the NAXIS keywords in the image header). 221 222 @rtype: list 223 @return: [minimum R.A., maximum R.A., minimum Dec., maximum Dec.] 224 225 """ 226 227 # Get size of parent image this WCS is taken from 228 maxX = self.header['NAXIS1'] 229 maxY = self.header['NAXIS2'] 230 minX = 1.0 231 minY = 1.0 232 233 if NUMPY_MODE == True: 234 maxX = maxX-1 235 maxY = maxY-1 236 minX = minX-1 237 minY = minY-1 238 239 bottomLeft = self.pix2wcs(minX, minY) 240 topRight = self.pix2wcs(maxX, maxY) 241 242 xCoords = [bottomLeft[0], topRight[0]] 243 yCoords = [bottomLeft[1], topRight[1]] 244 xCoords.sort() 245 yCoords.sort() 246 247 return [xCoords[0], xCoords[1], yCoords[0], yCoords[1]]
248 249
250 - def wcs2pix(self, RADeg, decDeg):
251 """Returns the pixel coordinates corresponding to the input WCS 252 coordinates (given in decimal degrees). RADeg, decDeg can be single 253 floats, or lists or numpy arrays. 254 255 @rtype: list 256 @return: pixel coordinates in format [x, y] 257 258 """ 259 260 if type(RADeg) == numpy.ndarray or type(RADeg) == list: 261 if type(decDeg) == numpy.ndarray or type(decDeg) == list: 262 pixCoords = [] 263 for ra, dec in zip(RADeg, decDeg): 264 pix = wcs.wcs2pix(self.WCSStructure, float(ra), float(dec)) 265 # Below handles CEA wraparounds 266 if pix[0] < 1: 267 xTest = ((self.header['CRPIX1'])-(ra-360.0) / 268 self.getXPixelSizeDeg()) 269 if xTest >= 1 and xTest < self.header['NAXIS1']: 270 pix[0] = xTest 271 if NUMPY_MODE == True: 272 pix[0] = pix[0]-1 273 pix[1] = pix[1]-1 274 pixCoords.append([pix[0], pix[1]]) 275 else: 276 pixCoords = (wcs.wcs2pix(self.WCSStructure, float(RADeg), 277 float(decDeg))) 278 # Below handles CEA wraparounds 279 if pixCoords[0] < 1: 280 xTest = ((self.header['CRPIX1'])-(RADeg-360.0) / 281 self.getXPixelSizeDeg()) 282 if xTest >= 1 and xTest < self.header['NAXIS1']: 283 pixCoords[0] = xTest 284 if NUMPY_MODE == True: 285 pixCoords[0] = pixCoords[0]-1 286 pixCoords[1] = pixCoords[1]-1 287 pixCoords = [pixCoords[0], pixCoords[1]] 288 289 return pixCoords
290 291
292 - def pix2wcs(self, x, y):
293 """Returns the WCS coordinates corresponding to the input pixel 294 coordinates. 295 296 @rtype: list 297 @return: WCS coordinates in format [RADeg, decDeg] 298 299 """ 300 if type(x) == numpy.ndarray or type(x) == list: 301 if type(y) == numpy.ndarray or type(y) == list: 302 WCSCoords = [] 303 for xc, yc in zip(x, y): 304 if NUMPY_MODE == True: 305 xc += 1 306 yc += 1 307 WCSCoords.append(wcs.pix2wcs(self.WCSStructure, float(xc), 308 float(yc))) 309 else: 310 if NUMPY_MODE == True: 311 x += 1 312 y += 1 313 WCSCoords = wcs.pix2wcs(self.WCSStructure, float(x), float(y)) 314 315 return WCSCoords
316 317
318 - def coordsAreInImage(self, RADeg, decDeg):
319 """Returns True if the given RA, dec coordinate is within the image 320 boundaries. 321 322 @rtype: bool 323 @return: True if coordinate within image, False if not. 324 325 """ 326 327 pixCoords = wcs.wcs2pix(self.WCSStructure, RADeg, decDeg) 328 if pixCoords[0] >= 0 and pixCoords[0] < self.header['NAXIS1'] and \ 329 pixCoords[1] >= 0 and pixCoords[1] < self.header['NAXIS2']: 330 return True 331 else: 332 return False
333 334
335 - def getRotationDeg(self):
336 """Returns the rotation angle in degrees around the axis, North through 337 East. 338 339 @rtype: float 340 @return: rotation angle in degrees 341 342 """ 343 return self.WCSStructure.rot
344 345
346 - def isFlipped(self):
347 """Returns 1 if image is reflected around axis, otherwise returns 0. 348 349 @rtype: int 350 @return: 1 if image is flipped, 0 otherwise 351 352 """ 353 return self.WCSStructure.imflip
354 355
356 - def getPixelSizeDeg(self):
357 """Returns the pixel scale of the WCS. This is the average of the x, y 358 pixel scales. 359 360 @rtype: float 361 @return: pixel size in decimal degrees 362 363 """ 364 365 avSize = (abs(self.WCSStructure.xinc)+abs(self.WCSStructure.yinc))/2.0 366 367 return avSize
368 369
370 - def getXPixelSizeDeg(self):
371 """Returns the pixel scale along the x-axis of the WCS in degrees. 372 373 @rtype: float 374 @return: pixel size in decimal degrees 375 376 """ 377 378 avSize = abs(self.WCSStructure.xinc) 379 380 return avSize
381 382
383 - def getYPixelSizeDeg(self):
384 """Returns the pixel scale along the y-axis of the WCS in degrees. 385 386 @rtype: float 387 @return: pixel size in decimal degrees 388 389 """ 390 391 avSize = abs(self.WCSStructure.yinc) 392 393 return avSize
394 395
396 - def getEquinox(self):
397 """Returns the equinox of the WCS. 398 399 @rtype: float 400 @return: equinox of the WCS 401 402 """ 403 return self.WCSStructure.equinox
404 405
406 - def getEpoch(self):
407 """Returns the epoch of the WCS. 408 409 @rtype: float 410 @return: epoch of the WCS 411 412 """ 413 return self.WCSStructure.epoch
414 415 416 #----------------------------------------------------------------------------- 417 # Functions for comparing WCS objects
418 -def findWCSOverlap(wcs1, wcs2):
419 """Finds the minimum, maximum WCS coords that overlap between wcs1 and 420 wcs2. Returns these coordinates, plus the corresponding pixel coordinates 421 for each wcs. Useful for clipping overlapping region between two images. 422 423 @rtype: dictionary 424 @return: dictionary with keys 'overlapWCS' (min, max RA, dec of overlap 425 between wcs1, wcs2) 'wcs1Pix', 'wcs2Pix' (pixel coords in each input 426 WCS that correspond to 'overlapWCS' coords) 427 428 """ 429 430 mm1 = wcs1.getImageMinMaxWCSCoords() 431 mm2 = wcs2.getImageMinMaxWCSCoords() 432 433 overlapWCSCoords = [0.0, 0.0, 0.0, 0.0] 434 435 # Note order swapping below is essential 436 # Min RA 437 if mm1[0] - mm2[0] <= 0.0: 438 overlapWCSCoords[0] = mm2[0] 439 else: 440 overlapWCSCoords[0] = mm1[0] 441 442 # Max RA 443 if mm1[1] - mm2[1] <= 0.0: 444 overlapWCSCoords[1] = mm1[1] 445 else: 446 overlapWCSCoords[1] = mm2[1] 447 448 # Min dec. 449 if mm1[2] - mm2[2] <= 0.0: 450 overlapWCSCoords[2] = mm2[2] 451 else: 452 overlapWCSCoords[2] = mm1[2] 453 454 # Max dec. 455 if mm1[3] - mm2[3] <= 0.0: 456 overlapWCSCoords[3] = mm1[3] 457 else: 458 overlapWCSCoords[3] = mm2[3] 459 460 # Get corresponding pixel coords 461 p1Low = wcs1.wcs2pix(overlapWCSCoords[0], overlapWCSCoords[2]) 462 p1High = wcs1.wcs2pix(overlapWCSCoords[1], overlapWCSCoords[3]) 463 p1 = [p1Low[0], p1High[0], p1Low[1], p1High[1]] 464 465 p2Low = wcs2.wcs2pix(overlapWCSCoords[0], overlapWCSCoords[2]) 466 p2High = wcs2.wcs2pix(overlapWCSCoords[1], overlapWCSCoords[3]) 467 p2 = [p2Low[0], p2High[0], p2Low[1], p2High[1]] 468 469 return {'overlapWCS': overlapWCSCoords, 'wcs1Pix': p1, 'wcs2Pix': p2}
470 471 #----------------------------------------------------------------------------- 472

astLib-0.10.0/docs/astLib/identifier-index.html0000644000175000017500000013276713047255533021636 0ustar mattymatty00000000000000 Identifier Index
 
[hide private]
[frames] | no frames]

Identifier Index

[ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ ]

A

B

C

D

E

F

G

H

I

J

L

M

N

O

P

R

S

T

U

V

W

_



astLib-0.10.0/docs/astLib/astLib.astPlots.ImagePlot-class.html0000664000175000017500000012207613047255533024412 0ustar mattymatty00000000000000 astLib.astPlots.ImagePlot
Package astLib :: Module astPlots :: Class ImagePlot
[hide private]
[frames] | no frames]

Class ImagePlot

source code

This class describes a matplotlib image plot containing an astronomical image with an associated WCS.

Objects within the image boundaries can be marked by passing their WCS coordinates to ImagePlot.addPlotObjects.

Other images can be overlaid using ImagePlot.addContourOverlay.

For images rotated with North at the top, East at the left (as can be done using astImages.clipRotatedImageSectionWCS or astImages.resampleToTanProjection, WCS coordinate axes can be plotted, with tick marks set appropriately for the image size. Otherwise, a compass can be plotted showing the directions of North and East in the image.

RGB images are also supported.

The plot can of course be tweaked further after creation using matplotlib/pylab commands.

Instance Methods [hide private]
 
__init__(self, imageData, imageWCS, axes=[0.1,0.1,0.8,0.8], cutLevels=["smart",99.5], colorMapName="gray", title=None, axesLabels="sexagesimal", axesFontFamily="serif", axesFontSize=12.0, RATickSteps="auto", decTickSteps="auto", colorBar=False, interpolation="bilinear")
Makes an ImagePlot from the given image array and astWCS.
source code
 
draw(self)
Redraws the ImagePlot.
source code
 
addContourOverlay(self, contourImageData, contourWCS, tag, levels=["linear","min","max",5], width=1, color="white", smooth=0, highAccuracy=False)
Adds image data to the ImagePlot as a contour overlay.
source code
 
removeContourOverlay(self, tag)
Removes the contourOverlay from the ImagePlot corresponding to the tag.
source code
 
addPlotObjects(self, objRAs, objDecs, tag, symbol="circle", size=4.0, width=1.0, color="yellow", objLabels=None, objLabelSize=12.0)
Add objects with RA, dec coords objRAs, objDecs to the ImagePlot.
source code
 
removePlotObjects(self, tag)
Removes the plotObjects from the ImagePlot corresponding to the tag.
source code
 
addCompass(self, location, sizeArcSec, color="white", fontSize=12, width=20.0)
Adds a compass to the ImagePlot at the given location ('N', 'NE', 'E', 'SE', 'S', 'SW', 'W', or 'NW').
source code
 
addScaleBar(self, location, sizeArcSec, color="white", fontSize=12, width=20.0)
Adds a scale bar to the ImagePlot at the given location ('N', 'NE', 'E', 'SE', 'S', 'SW', 'W', or 'NW').
source code
 
calcWCSAxisLabels(self, axesLabels="decimal")
This function calculates the positions of coordinate labels for the RA and Dec axes of the ImagePlot.
source code
 
save(self, fileName)
Saves the ImagePlot in any format that matplotlib can understand, as determined from the fileName extension.
source code
dictionary
getTickSteps(self)
Chooses the appropriate WCS coordinate tick steps for the plot based on its size.
source code
Method Details [hide private]

__init__(self, imageData, imageWCS, axes=[0.1,0.1,0.8,0.8], cutLevels=["smart",99.5], colorMapName="gray", title=None, axesLabels="sexagesimal", axesFontFamily="serif", axesFontSize=12.0, RATickSteps="auto", decTickSteps="auto", colorBar=False, interpolation="bilinear")
(Constructor)

source code 

Makes an ImagePlot from the given image array and astWCS. For coordinate axes to work, the image and WCS should have been rotated such that East is at the left, North is at the top (see e.g. astImages.clipRotatedImageSectionWCS, or astImages.resampleToTanProjection).

If imageData is given as a list in the format [r, g, b], a color RGB plot will be made. However, in this case the cutLevels must be specified manually for each component as a list - i.e. cutLevels = [[r min, r max], [g min, g max], [b min, b max]]. In this case of course, the colorMap will be ignored. All r, g, b image arrays must have the same dimensions.

Set axesLabels = None to make a plot without coordinate axes plotted.

The axes can be marked in either sexagesimal or decimal celestial coordinates. If RATickSteps or decTickSteps are set to "auto", the appropriate axis scales will be determined automatically from the size of the image array and associated WCS. The tick step sizes can be overidden. If the coordinate axes are in sexagesimal format a dictionary in the format {'deg', 'unit'} is needed (see RA_TICK_STEPS and DEC_TICK_STEPS for examples). If the coordinate axes are in decimal format, the tick step size is specified simply in RA, dec decimal degrees.

Parameters:
  • imageData (numpy array or list) - image data array or list of numpy arrays [r, g, b]
  • imageWCS (astWCS.WCS) - astWCS.WCS object
  • axes (list) - specifies where in the current figure to draw the finder chart (see pylab.axes)
  • cutLevels (list) - sets the image scaling - available options:
    • pixel values: cutLevels=[low value, high value].
    • histogram equalisation: cutLevels=["histEq", number of bins ( e.g. 1024)]
    • relative: cutLevels=["relative", cut per cent level (e.g. 99.5)]
    • smart: cutLevels=["smart", cut per cent level (e.g. 99.5)]

    ["smart", 99.5] seems to provide good scaling over a range of different images. Note that for RGB images, cut levels must be specified manually i.e. as a list: [[r min, rmax], [g min, g max], [b min, b max]]

  • colorMapName (string) - name of a standard matplotlib colormap, e.g. "hot", "cool", "gray" etc. (do "help(pylab.colormaps)" in the Python interpreter to see available options)
  • title (string) - optional title for the plot
  • axesLabels (string) - either "sexagesimal" (for H:M:S, D:M:S), "decimal" (for decimal degrees) or None (for no coordinate axes labels)
  • axesFontFamily (string) - matplotlib fontfamily, e.g. 'serif', 'sans-serif' etc.
  • axesFontSize (float) - font size of axes labels and titles (in points)
  • colorBar (bool) - if True, plot a vertical color bar at the side of the image indicating the intensity scale.
  • interpolation (string) - interpolation to apply to the image plot (see the documentation for the matplotlib.pylab.imshow command)

addContourOverlay(self, contourImageData, contourWCS, tag, levels=["linear","min","max",5], width=1, color="white", smooth=0, highAccuracy=False)

source code 

Adds image data to the ImagePlot as a contour overlay. The contours can be removed using removeContourOverlay. If a contour overlay already exists with this tag, it will be replaced.

Parameters:
  • contourImageData (numpy array) - image data array from which contours are to be generated
  • contourWCS (astWCS.WCS) - astWCS.WCS object for the image to be contoured
  • tag (string) - identifying tag for this set of contours
  • levels (list) - sets the contour levels - available options:
    • values: contourLevels=[list of values specifying each level]
    • linear spacing: contourLevels=['linear', min level value, max level value, number of levels] - can use "min", "max" to automatically set min, max levels from image data
    • log spacing: contourLevels=['log', min level value, max level value, number of levels] - can use "min", "max" to automatically set min, max levels from image data
  • width (int) - width of the overlaid contours
  • color (string) - color of the overlaid contours, specified by the name of a standard matplotlib color, e.g., "black", "white", "cyan" etc. (do "help(pylab.colors)" in the Python interpreter to see available options)
  • smooth (float) - standard deviation (in arcsec) of Gaussian filter for pre-smoothing of contour image data (set to 0 for no smoothing)
  • highAccuracy (bool) - if True, sample every corresponding pixel in each image; otherwise, sample every nth pixel, where n = the ratio of the image scales.

removeContourOverlay(self, tag)

source code 

Removes the contourOverlay from the ImagePlot corresponding to the tag.

Parameters:
  • tag (string) - tag for contour overlay in ImagePlot.contourOverlays to be removed

addPlotObjects(self, objRAs, objDecs, tag, symbol="circle", size=4.0, width=1.0, color="yellow", objLabels=None, objLabelSize=12.0)

source code 

Add objects with RA, dec coords objRAs, objDecs to the ImagePlot. Only objects that fall within the image boundaries will be plotted.

symbol specifies the type of symbol with which to mark the object in the image. The following values are allowed:

  • "circle"
  • "box"
  • "cross"
  • "diamond"

size specifies the diameter in arcsec of the symbol (if plotSymbol == "circle"), or the width of the box in arcsec (if plotSymbol == "box")

width specifies the thickness of the symbol lines in pixels

color can be any valid matplotlib color (e.g. "red", "green", etc.)

The objects can be removed from the plot by using removePlotObjects(), and then calling draw(). If the ImagePlot already has a set of plotObjects with the same tag, they will be replaced.

Parameters:
  • objRAs (numpy array or list) - object RA coords in decimal degrees
  • objDecs (numpy array or list) - corresponding object Dec. coords in decimal degrees
  • tag (string) - identifying tag for this set of objects
  • symbol (string) - either "circle", "box", "cross", or "diamond"
  • size (float) - size of symbols to plot (radius in arcsec, or width of box)
  • width (float) - width of symbols in pixels
  • color (string) - any valid matplotlib color string, e.g. "red", "green" etc.
  • objLabels (list) - text labels to plot next to objects in figure
  • objLabelSize (float) - size of font used for object labels (in points)

removePlotObjects(self, tag)

source code 

Removes the plotObjects from the ImagePlot corresponding to the tag. The plot must be redrawn for the change to take effect.

Parameters:
  • tag (string) - tag for set of objects in ImagePlot.plotObjects to be removed

addCompass(self, location, sizeArcSec, color="white", fontSize=12, width=20.0)

source code 

Adds a compass to the ImagePlot at the given location ('N', 'NE', 'E', 'SE', 'S', 'SW', 'W', or 'NW'). Note these aren't directions on the WCS coordinate grid, they are relative positions on the plot - so N is top centre, NE is top right, SW is bottom right etc.. Alternatively, pixel coordinates (x, y) in the image can be given.

Parameters:
  • location (string or tuple) - location in the plot where the compass is drawn:
    • string: N, NE, E, SE, S, SW, W or NW
    • tuple: (x, y)
  • sizeArcSec (float) - length of the compass arrows on the plot in arc seconds
  • color (string) - any valid matplotlib color string
  • fontSize (float) - size of font used to label N and E, in points
  • width (float) - width of arrows used to mark compass

addScaleBar(self, location, sizeArcSec, color="white", fontSize=12, width=20.0)

source code 

Adds a scale bar to the ImagePlot at the given location ('N', 'NE', 'E', 'SE', 'S', 'SW', 'W', or 'NW'). Note these aren't directions on the WCS coordinate grid, they are relative positions on the plot - so N is top centre, NE is top right, SW is bottom right etc.. Alternatively, pixel coordinates (x, y) in the image can be given.

Parameters:
  • location (string or tuple) - location in the plot where the compass is drawn:
    • string: N, NE, E, SE, S, SW, W or NW
    • tuple: (x, y)
  • sizeArcSec (float) - scale length to indicate on the plot in arc seconds
  • color (string) - any valid matplotlib color string
  • fontSize (float) - size of font used to label N and E, in points
  • width (float) - width of arrow used to mark scale

calcWCSAxisLabels(self, axesLabels="decimal")

source code 

This function calculates the positions of coordinate labels for the RA and Dec axes of the ImagePlot. The tick steps are calculated automatically unless self.RATickSteps, self.decTickSteps are set to values other than "auto" (see ImagePlot.__init__).

The ImagePlot must be redrawn for changes to be applied.

Parameters:
  • axesLabels (string) - either "sexagesimal" (for H:M:S, D:M:S), "decimal" (for decimal degrees), or None for no coordinate axes labels

save(self, fileName)

source code 

Saves the ImagePlot in any format that matplotlib can understand, as determined from the fileName extension.

Parameters:
  • fileName (string) - path where plot will be written

getTickSteps(self)

source code 

Chooses the appropriate WCS coordinate tick steps for the plot based on its size. Whether the ticks are decimal or sexagesimal is set by self.axesLabels.

Note: minor ticks not used at the moment.

Returns: dictionary
tick step sizes for major, minor plot ticks, in format {'major', 'minor'}

astLib-0.10.0/docs/astLib/astLib.astSED.Passband-class.html0000664000175000017500000003532513047255533023576 0ustar mattymatty00000000000000 astLib.astSED.Passband
Package astLib :: Module astSED :: Class Passband
[hide private]
[frames] | no frames]

Class Passband

source code

Known Subclasses:

This class describes a filter transmission curve. Passband objects are created by loading data from from text files containing wavelength in angstroms in the first column, relative transmission efficiency in the second column (whitespace delimited). For example, to create a Passband object for the 2MASS J filter:

passband=astSED.Passband("J_2MASS.res")

where "J_2MASS.res" is a file in the current working directory that describes the filter.

Wavelength units can be specified as 'angstroms', 'nanometres' or 'microns'; if either of the latter, they will be converted to angstroms.

Instance Methods [hide private]
 
__init__(self, fileName, normalise=True, inputUnits='angstroms', wavelengthColumn=0, transmissionColumn=1) source code
list
asList(self)
Returns a two dimensional list of [wavelength, transmission], suitable for plotting by gnuplot.
source code
 
rescale(self, maxTransmission)
Rescales the passband so that maximum value of the transmission is equal to maxTransmission.
source code
 
plot(self, xmin='min', xmax='max', maxTransmission=None)
Plots the passband, rescaling the maximum of the tranmission curve to maxTransmission if required.
source code
float
effectiveWavelength(self)
Calculates effective wavelength for the passband.
source code
Method Details [hide private]

asList(self)

source code 

Returns a two dimensional list of [wavelength, transmission], suitable for plotting by gnuplot.

Returns: list
list in format [wavelength, transmission]

rescale(self, maxTransmission)

source code 

Rescales the passband so that maximum value of the transmission is equal to maxTransmission. Useful for plotting.

Parameters:
  • maxTransmission (float) - maximum value of rescaled transmission curve

plot(self, xmin='min', xmax='max', maxTransmission=None)

source code 

Plots the passband, rescaling the maximum of the tranmission curve to maxTransmission if required.

Parameters:
  • xmin (float or 'min') - minimum of the wavelength range of the plot
  • xmax (float or 'max') - maximum of the wavelength range of the plot
  • maxTransmission (float) - maximum value of rescaled transmission curve

effectiveWavelength(self)

source code 

Calculates effective wavelength for the passband. This is the same as equation (3) of Carter et al. 2009.

Returns: float
effective wavelength of the passband, in Angstroms

astLib-0.10.0/docs/astLib/astLib.astCoords-module.html0000644000175000017500000005656513047255533023051 0ustar mattymatty00000000000000 astLib.astCoords
Package astLib :: Module astCoords
[hide private]
[frames] | no frames]

Module astCoords

source code

module for coordinate manipulation (conversions, calculations etc.)

(c) 2007-2012 Matt Hilton

(c) 2013-2014 Matt Hilton & Steven Boada

http://astlib.sourceforge.net

Functions [hide private]
float
hms2decimal(RAString, delimiter)
Converts a delimited string of Hours:Minutes:Seconds format into decimal degrees.
source code
float
dms2decimal(decString, delimiter)
Converts a delimited string of Degrees:Minutes:Seconds format into decimal degrees.
source code
string
decimal2hms(RADeg, delimiter)
Converts decimal degrees to string in Hours:Minutes:Seconds format with user specified delimiter.
source code
string
decimal2dms(decDeg, delimiter)
Converts decimal degrees to string in Degrees:Minutes:Seconds format with user specified delimiter.
source code
float or numpy array, depending upon type of RADeg2, decDeg2
calcAngSepDeg(RADeg1, decDeg1, RADeg2, decDeg2)
Calculates the angular separation of two positions on the sky (specified in decimal degrees) in decimal degrees, assuming a tangent plane projection (so separation has to be <90 deg).
source code
float [newRA, newDec]
shiftRADec(ra1, dec1, deltaRA, deltaDec)
Computes new right ascension and declination shifted from the original by some delta RA and delta DEC.
source code
list
convertCoords(inputSystem, outputSystem, coordX, coordY, epoch)
Converts specified coordinates (given in decimal degrees) between J2000, B1950, and Galactic.
source code
list
calcRADecSearchBox(RADeg, decDeg, radiusSkyDeg)
Calculates minimum and maximum RA, dec coords needed to define a box enclosing a circle of radius radiusSkyDeg around the given RADeg, decDeg coordinates.
source code
Function Details [hide private]

hms2decimal(RAString, delimiter)

source code 

Converts a delimited string of Hours:Minutes:Seconds format into decimal degrees.

Parameters:
  • RAString (string) - coordinate string in H:M:S format
  • delimiter (string) - delimiter character in RAString
Returns: float
coordinate in decimal degrees

dms2decimal(decString, delimiter)

source code 

Converts a delimited string of Degrees:Minutes:Seconds format into decimal degrees.

Parameters:
  • decString (string) - coordinate string in D:M:S format
  • delimiter (string) - delimiter character in decString
Returns: float
coordinate in decimal degrees

decimal2hms(RADeg, delimiter)

source code 

Converts decimal degrees to string in Hours:Minutes:Seconds format with user specified delimiter.

Parameters:
  • RADeg (float) - coordinate in decimal degrees
  • delimiter (string) - delimiter character in returned string
Returns: string
coordinate string in H:M:S format

decimal2dms(decDeg, delimiter)

source code 

Converts decimal degrees to string in Degrees:Minutes:Seconds format with user specified delimiter.

Parameters:
  • decDeg (float) - coordinate in decimal degrees
  • delimiter (string) - delimiter character in returned string
Returns: string
coordinate string in D:M:S format

calcAngSepDeg(RADeg1, decDeg1, RADeg2, decDeg2)

source code 

Calculates the angular separation of two positions on the sky (specified in decimal degrees) in decimal degrees, assuming a tangent plane projection (so separation has to be <90 deg). Note that RADeg2, decDeg2 can be numpy arrays.

Parameters:
  • RADeg1 (float) - R.A. in decimal degrees for position 1
  • decDeg1 (float) - dec. in decimal degrees for position 1
  • RADeg2 (float or numpy array) - R.A. in decimal degrees for position 2
  • decDeg2 (float or numpy array) - dec. in decimal degrees for position 2
Returns: float or numpy array, depending upon type of RADeg2, decDeg2
angular separation in decimal degrees

shiftRADec(ra1, dec1, deltaRA, deltaDec)

source code 

Computes new right ascension and declination shifted from the original by some delta RA and delta DEC. Input position is decimal degrees. Shifts (deltaRA, deltaDec) are arcseconds, and output is decimal degrees. Based on an IDL routine of the same name.

Parameters:
  • ra1 (R.A. in decimal degrees) - float
  • dec1 (dec. in decimal degrees) - float
  • deltaRA (shift in R.A. in arcseconds) - float
  • deltaDec (shift in dec. in arcseconds) - float
Returns: float [newRA, newDec]
shifted R.A. and dec.

convertCoords(inputSystem, outputSystem, coordX, coordY, epoch)

source code 

Converts specified coordinates (given in decimal degrees) between J2000, B1950, and Galactic.

Parameters:
  • inputSystem (string) - system of the input coordinates (either "J2000", "B1950" or "GALACTIC")
  • outputSystem (string) - system of the returned coordinates (either "J2000", "B1950" or "GALACTIC")
  • coordX (float) - longitude coordinate in decimal degrees, e.g. R. A.
  • coordY (float) - latitude coordinate in decimal degrees, e.g. dec.
  • epoch (float) - epoch of the input coordinates
Returns: list
coordinates in decimal degrees in requested output system

calcRADecSearchBox(RADeg, decDeg, radiusSkyDeg)

source code 

Calculates minimum and maximum RA, dec coords needed to define a box enclosing a circle of radius radiusSkyDeg around the given RADeg, decDeg coordinates. Useful for freeform queries of e.g. SDSS, UKIDSS etc.. Uses calcAngSepDeg, so has the same limitations.

Parameters:
  • RADeg (float) - RA coordinate of centre of search region
  • decDeg (float) - dec coordinate of centre of search region
  • radiusSkyDeg (float) - radius in degrees on the sky used to define search region
Returns: list
[RAMin, RAMax, decMin, decMax] - coordinates in decimal degrees defining search box

astLib-0.10.0/docs/astLib/epydoc.css0000644000175000017500000003722713047255533017511 0ustar mattymatty00000000000000 /* Epydoc CSS Stylesheet * * This stylesheet can be used to customize the appearance of epydoc's * HTML output. * */ /* Default Colors & Styles * - Set the default foreground & background color with 'body'; and * link colors with 'a:link' and 'a:visited'. * - Use bold for decision list terms. * - The heading styles defined here are used for headings *within* * docstring descriptions. All headings used by epydoc itself use * either class='epydoc' or class='toc' (CSS styles for both * defined below). */ body { background: #ffffff; color: #000000; } p { margin-top: 0.5em; margin-bottom: 0.5em; } a:link { color: #0000ff; } a:visited { color: #204080; } dt { font-weight: bold; } h1 { font-size: +140%; font-style: italic; font-weight: bold; } h2 { font-size: +125%; font-style: italic; font-weight: bold; } h3 { font-size: +110%; font-style: italic; font-weight: normal; } code { font-size: 100%; } /* N.B.: class, not pseudoclass */ a.link { font-family: monospace; } /* Page Header & Footer * - The standard page header consists of a navigation bar (with * pointers to standard pages such as 'home' and 'trees'); a * breadcrumbs list, which can be used to navigate to containing * classes or modules; options links, to show/hide private * variables and to show/hide frames; and a page title (using *

). The page title may be followed by a link to the * corresponding source code (using 'span.codelink'). * - The footer consists of a navigation bar, a timestamp, and a * pointer to epydoc's homepage. */ h1.epydoc { margin: 0; font-size: +140%; font-weight: bold; } h2.epydoc { font-size: +130%; font-weight: bold; } h3.epydoc { font-size: +115%; font-weight: bold; margin-top: 0.2em; } td h3.epydoc { font-size: +115%; font-weight: bold; margin-bottom: 0; } table.navbar { background: #a0c0ff; color: #000000; border: 2px groove #c0d0d0; } table.navbar table { color: #000000; } th.navbar-select { background: #70b0ff; color: #000000; } table.navbar a { text-decoration: none; } table.navbar a:link { color: #0000ff; } table.navbar a:visited { color: #204080; } span.breadcrumbs { font-size: 85%; font-weight: bold; } span.options { font-size: 70%; } span.codelink { font-size: 85%; } td.footer { font-size: 85%; } /* Table Headers * - Each summary table and details section begins with a 'header' * row. This row contains a section title (marked by * 'span.table-header') as well as a show/hide private link * (marked by 'span.options', defined above). * - Summary tables that contain user-defined groups mark those * groups using 'group header' rows. */ td.table-header { background: #70b0ff; color: #000000; border: 1px solid #608090; } td.table-header table { color: #000000; } td.table-header table a:link { color: #0000ff; } td.table-header table a:visited { color: #204080; } span.table-header { font-size: 120%; font-weight: bold; } th.group-header { background: #c0e0f8; color: #000000; text-align: left; font-style: italic; font-size: 115%; border: 1px solid #608090; } /* Summary Tables (functions, variables, etc) * - Each object is described by a single row of the table with * two cells. The left cell gives the object's type, and is * marked with 'code.summary-type'. The right cell gives the * object's name and a summary description. * - CSS styles for the table's header and group headers are * defined above, under 'Table Headers' */ table.summary { border-collapse: collapse; background: #e8f0f8; color: #000000; border: 1px solid #608090; margin-bottom: 0.5em; } td.summary { border: 1px solid #608090; } code.summary-type { font-size: 85%; } table.summary a:link { color: #0000ff; } table.summary a:visited { color: #204080; } /* Details Tables (functions, variables, etc) * - Each object is described in its own div. * - A single-row summary table w/ table-header is used as * a header for each details section (CSS style for table-header * is defined above, under 'Table Headers'). */ table.details { border-collapse: collapse; background: #e8f0f8; color: #000000; border: 1px solid #608090; margin: .2em 0 0 0; } table.details table { color: #000000; } table.details a:link { color: #0000ff; } table.details a:visited { color: #204080; } /* Fields */ dl.fields { margin-left: 2em; margin-top: 1em; margin-bottom: 1em; } dl.fields dd ul { margin-left: 0em; padding-left: 0em; } dl.fields dd ul li ul { margin-left: 2em; padding-left: 0em; } div.fields { margin-left: 2em; } div.fields p { margin-bottom: 0.5em; } /* Index tables (identifier index, term index, etc) * - link-index is used for indices containing lists of links * (namely, the identifier index & term index). * - index-where is used in link indices for the text indicating * the container/source for each link. * - metadata-index is used for indices containing metadata * extracted from fields (namely, the bug index & todo index). */ table.link-index { border-collapse: collapse; background: #e8f0f8; color: #000000; border: 1px solid #608090; } td.link-index { border-width: 0px; } table.link-index a:link { color: #0000ff; } table.link-index a:visited { color: #204080; } span.index-where { font-size: 70%; } table.metadata-index { border-collapse: collapse; background: #e8f0f8; color: #000000; border: 1px solid #608090; margin: .2em 0 0 0; } td.metadata-index { border-width: 1px; border-style: solid; } table.metadata-index a:link { color: #0000ff; } table.metadata-index a:visited { color: #204080; } /* Function signatures * - sig* is used for the signature in the details section. * - .summary-sig* is used for the signature in the summary * table, and when listing property accessor functions. * */ .sig-name { color: #006080; } .sig-arg { color: #008060; } .sig-default { color: #602000; } .summary-sig { font-family: monospace; } .summary-sig-name { color: #006080; font-weight: bold; } table.summary a.summary-sig-name:link { color: #006080; font-weight: bold; } table.summary a.summary-sig-name:visited { color: #006080; font-weight: bold; } .summary-sig-arg { color: #006040; } .summary-sig-default { color: #501800; } /* Subclass list */ ul.subclass-list { display: inline; } ul.subclass-list li { display: inline; } /* To render variables, classes etc. like functions */ table.summary .summary-name { color: #006080; font-weight: bold; font-family: monospace; } table.summary a.summary-name:link { color: #006080; font-weight: bold; font-family: monospace; } table.summary a.summary-name:visited { color: #006080; font-weight: bold; font-family: monospace; } /* Variable values * - In the 'variable details' sections, each varaible's value is * listed in a 'pre.variable' box. The width of this box is * restricted to 80 chars; if the value's repr is longer than * this it will be wrapped, using a backslash marked with * class 'variable-linewrap'. If the value's repr is longer * than 3 lines, the rest will be ellided; and an ellipsis * marker ('...' marked with 'variable-ellipsis') will be used. * - If the value is a string, its quote marks will be marked * with 'variable-quote'. * - If the variable is a regexp, it is syntax-highlighted using * the re* CSS classes. */ pre.variable { padding: .5em; margin: 0; background: #dce4ec; color: #000000; border: 1px solid #708890; } .variable-linewrap { color: #604000; font-weight: bold; } .variable-ellipsis { color: #604000; font-weight: bold; } .variable-quote { color: #604000; font-weight: bold; } .variable-group { color: #008000; font-weight: bold; } .variable-op { color: #604000; font-weight: bold; } .variable-string { color: #006030; } .variable-unknown { color: #a00000; font-weight: bold; } .re { color: #000000; } .re-char { color: #006030; } .re-op { color: #600000; } .re-group { color: #003060; } .re-ref { color: #404040; } /* Base tree * - Used by class pages to display the base class hierarchy. */ pre.base-tree { font-size: 80%; margin: 0; } /* Frames-based table of contents headers * - Consists of two frames: one for selecting modules; and * the other listing the contents of the selected module. * - h1.toc is used for each frame's heading * - h2.toc is used for subheadings within each frame. */ h1.toc { text-align: center; font-size: 105%; margin: 0; font-weight: bold; padding: 0; } h2.toc { font-size: 100%; font-weight: bold; margin: 0.5em 0 0 -0.3em; } /* Syntax Highlighting for Source Code * - doctest examples are displayed in a 'pre.py-doctest' block. * If the example is in a details table entry, then it will use * the colors specified by the 'table pre.py-doctest' line. * - Source code listings are displayed in a 'pre.py-src' block. * Each line is marked with 'span.py-line' (used to draw a line * down the left margin, separating the code from the line * numbers). Line numbers are displayed with 'span.py-lineno'. * The expand/collapse block toggle button is displayed with * 'a.py-toggle' (Note: the CSS style for 'a.py-toggle' should not * modify the font size of the text.) * - If a source code page is opened with an anchor, then the * corresponding code block will be highlighted. The code * block's header is highlighted with 'py-highlight-hdr'; and * the code block's body is highlighted with 'py-highlight'. * - The remaining py-* classes are used to perform syntax * highlighting (py-string for string literals, py-name for names, * etc.) */ pre.py-doctest { padding: .5em; margin: 1em; background: #e8f0f8; color: #000000; border: 1px solid #708890; } table pre.py-doctest { background: #dce4ec; color: #000000; } pre.py-src { border: 2px solid #000000; background: #f0f0f0; color: #000000; } .py-line { border-left: 2px solid #000000; margin-left: .2em; padding-left: .4em; } .py-lineno { font-style: italic; font-size: 90%; padding-left: .5em; } a.py-toggle { text-decoration: none; } div.py-highlight-hdr { border-top: 2px solid #000000; border-bottom: 2px solid #000000; background: #d8e8e8; } div.py-highlight { border-bottom: 2px solid #000000; background: #d0e0e0; } .py-prompt { color: #005050; font-weight: bold;} .py-more { color: #005050; font-weight: bold;} .py-string { color: #006030; } .py-comment { color: #003060; } .py-keyword { color: #600000; } .py-output { color: #404040; } .py-name { color: #000050; } .py-name:link { color: #000050 !important; } .py-name:visited { color: #000050 !important; } .py-number { color: #005000; } .py-defname { color: #000060; font-weight: bold; } .py-def-name { color: #000060; font-weight: bold; } .py-base-class { color: #000060; } .py-param { color: #000060; } .py-docstring { color: #006030; } .py-decorator { color: #804020; } /* Use this if you don't want links to names underlined: */ /*a.py-name { text-decoration: none; }*/ /* Graphs & Diagrams * - These CSS styles are used for graphs & diagrams generated using * Graphviz dot. 'img.graph-without-title' is used for bare * diagrams (to remove the border created by making the image * clickable). */ img.graph-without-title { border: none; } img.graph-with-title { border: 1px solid #000000; } span.graph-title { font-weight: bold; } span.graph-caption { } /* General-purpose classes * - 'p.indent-wrapped-lines' defines a paragraph whose first line * is not indented, but whose subsequent lines are. * - The 'nomargin-top' class is used to remove the top margin (e.g. * from lists). The 'nomargin' class is used to remove both the * top and bottom margin (but not the left or right margin -- * for lists, that would cause the bullets to disappear.) */ p.indent-wrapped-lines { padding: 0 0 0 7em; text-indent: -7em; margin: 0; } .nomargin-top { margin-top: 0; } .nomargin { margin-top: 0; margin-bottom: 0; } /* HTML Log */ div.log-block { padding: 0; margin: .5em 0 .5em 0; background: #e8f0f8; color: #000000; border: 1px solid #000000; } div.log-error { padding: .1em .3em .1em .3em; margin: 4px; background: #ffb0b0; color: #000000; border: 1px solid #000000; } div.log-warning { padding: .1em .3em .1em .3em; margin: 4px; background: #ffffb0; color: #000000; border: 1px solid #000000; } div.log-info { padding: .1em .3em .1em .3em; margin: 4px; background: #b0ffb0; color: #000000; border: 1px solid #000000; } h2.log-hdr { background: #70b0ff; color: #000000; margin: 0; padding: 0em 0.5em 0em 0.5em; border-bottom: 1px solid #000000; font-size: 110%; } p.log { font-weight: bold; margin: .5em 0 .5em 0; } tr.opt-changed { color: #000000; font-weight: bold; } tr.opt-default { color: #606060; } pre.log { margin: 0; padding: 0; padding-left: 1em; } astLib-0.10.0/docs/astLib/astLib.astImages-module.html0000644000175000017500000015115413047255533023013 0ustar mattymatty00000000000000 astLib.astImages
Package astLib :: Module astImages
[hide private]
[frames] | no frames]

Module astImages

source code

module for simple .fits image tasks (rotation, clipping out sections, making .pngs etc.)

(c) 2007-2014 Matt Hilton

http://astlib.sourceforge.net

Some routines in this module will fail if, e.g., asked to clip a section from a .fits image at a position not found within the image (as determined using the WCS). Where this occurs, the function will return None. An error message will be printed to the console when this happens if astImages.REPORT_ERRORS=True (the default). Testing if an astImages function returns None can be used to handle errors in scripts.

Functions [hide private]
dictionary
clipImageSectionWCS(imageData, imageWCS, RADeg, decDeg, clipSizeDeg, returnWCS=True)
Clips a square or rectangular section from an image array at the given celestial coordinates.
source code
numpy array
clipImageSectionPix(imageData, XCoord, YCoord, clipSizePix)
Clips a square or rectangular section from an image array at the given pixel coordinates.
source code
dictionary
clipRotatedImageSectionWCS(imageData, imageWCS, RADeg, decDeg, clipSizeDeg, returnWCS=True)
Clips a square or rectangular section from an image array at the given celestial coordinates.
source code
dictionary
clipUsingRADecCoords(imageData, imageWCS, RAMin, RAMax, decMin, decMax, returnWCS=True)
Clips a section from an image array at the pixel coordinates corresponding to the given celestial coordinates.
source code
dictionary
scaleImage(imageData, imageWCS, scaleFactor)
Scales image array and WCS by the given scale factor.
source code
dictionary
intensityCutImage(imageData, cutLevels)
Creates a matplotlib.pylab plot of an image array with the specified cuts in intensity applied.
source code
dictionary
resampleToTanProjection(imageData, imageWCS, outputPixDimensions=[600,600])
Resamples an image and WCS to a tangent plane projection.
source code
dictionary
resampleToWCS(im1Data, im1WCS, im2Data, im2WCS, highAccuracy=False, onlyOverlapping=True)
Resamples data corresponding to second image (with data im2Data, WCS im2WCS) onto the WCS of the first image (im1Data, im1WCS).
source code
 
generateContourOverlay(backgroundImageData, backgroundImageWCS, contourImageData, contourImageWCS, contourLevels, contourSmoothFactor=0, highAccuracy=False)
Rescales an image array to be used as a contour overlay to have the same dimensions as the background image, and generates a set of contour levels.
source code
 
saveBitmap(outputFileName, imageData, cutLevels, size, colorMapName)
Makes a bitmap image from an image array; the image format is specified by the filename extension.
source code
 
saveContourOverlayBitmap(outputFileName, backgroundImageData, backgroundImageWCS, cutLevels, size, colorMapName, contourImageData, contourImageWCS, contourSmoothFactor, contourLevels, contourColor, contourWidth)
Makes a bitmap image from an image array, with a set of contours generated from a second image array overlaid.
source code
 
saveFITS(outputFileName, imageData, imageWCS=None)
Writes an image array to a new .fits file.
source code
numpy array
histEq(inputArray, numBins)
Performs histogram equalisation of the input numpy array.
source code
numpy array
normalise(inputArray, clipMinMax)
Clips the inputArray in intensity and normalises the array such that minimum and maximum values are 0, 1.
source code
Variables [hide private]
  REPORT_ERRORS = True
Function Details [hide private]

clipImageSectionWCS(imageData, imageWCS, RADeg, decDeg, clipSizeDeg, returnWCS=True)

source code 

Clips a square or rectangular section from an image array at the given celestial coordinates. An updated WCS for the clipped section is optionally returned, as well as the x, y pixel coordinates in the original image corresponding to the clipped section.

Note that the clip size is specified in degrees on the sky. For projections that have varying real pixel scale across the map (e.g. CEA), use clipUsingRADecCoords instead.

Parameters:
  • imageData (numpy array) - image data array
  • imageWCS (astWCS.WCS) - astWCS.WCS object
  • RADeg (float) - coordinate in decimal degrees
  • decDeg (float) - coordinate in decimal degrees
  • clipSizeDeg (float or list in format [widthDeg, heightDeg]) - if float, size of square clipped section in decimal degrees; if list, size of clipped section in degrees in x, y axes of image respectively
  • returnWCS (bool) - if True, return an updated WCS for the clipped section
Returns: dictionary
clipped image section (numpy array), updated astWCS WCS object for clipped image section, and coordinates of clipped section in imageData in format {'data', 'wcs', 'clippedSection'}.

clipImageSectionPix(imageData, XCoord, YCoord, clipSizePix)

source code 

Clips a square or rectangular section from an image array at the given pixel coordinates.

Parameters:
  • imageData (numpy array) - image data array
  • XCoord (float) - coordinate in pixels
  • YCoord (float) - coordinate in pixels
  • clipSizePix (float or list in format [widthPix, heightPix]) - if float, size of square clipped section in pixels; if list, size of clipped section in pixels in x, y axes of output image respectively
Returns: numpy array
clipped image section

clipRotatedImageSectionWCS(imageData, imageWCS, RADeg, decDeg, clipSizeDeg, returnWCS=True)

source code 

Clips a square or rectangular section from an image array at the given celestial coordinates. The resulting clip is rotated and/or flipped such that North is at the top, and East appears at the left. An updated WCS for the clipped section is also returned. Note that the alignment of the rotated WCS is currently not perfect - however, it is probably good enough in most cases for use with ImagePlot for plotting purposes.

Note that the clip size is specified in degrees on the sky. For projections that have varying real pixel scale across the map (e.g. CEA), use clipUsingRADecCoords instead.

Parameters:
  • imageData (numpy array) - image data array
  • imageWCS (astWCS.WCS) - astWCS.WCS object
  • RADeg (float) - coordinate in decimal degrees
  • decDeg (float) - coordinate in decimal degrees
  • clipSizeDeg (float) - if float, size of square clipped section in decimal degrees; if list, size of clipped section in degrees in RA, dec. axes of output rotated image respectively
  • returnWCS (bool) - if True, return an updated WCS for the clipped section
Returns: dictionary
clipped image section (numpy array), updated astWCS WCS object for clipped image section, in format {'data', 'wcs'}.

Note: Returns 'None' if the requested position is not found within the image. If the image WCS does not have keywords of the form CD1_1 etc., the output WCS will not be rotated.

clipUsingRADecCoords(imageData, imageWCS, RAMin, RAMax, decMin, decMax, returnWCS=True)

source code 

Clips a section from an image array at the pixel coordinates corresponding to the given celestial coordinates.

Parameters:
  • imageData (numpy array) - image data array
  • imageWCS (astWCS.WCS) - astWCS.WCS object
  • RAMin (float) - minimum RA coordinate in decimal degrees
  • RAMax (float) - maximum RA coordinate in decimal degrees
  • decMin (float) - minimum dec coordinate in decimal degrees
  • decMax (float) - maximum dec coordinate in decimal degrees
  • returnWCS (bool) - if True, return an updated WCS for the clipped section
Returns: dictionary
clipped image section (numpy array), updated astWCS WCS object for clipped image section, and corresponding pixel coordinates in imageData in format {'data', 'wcs', 'clippedSection'}.

Note: Returns 'None' if the requested position is not found within the image.

scaleImage(imageData, imageWCS, scaleFactor)

source code 

Scales image array and WCS by the given scale factor.

Parameters:
  • imageData (numpy array) - image data array
  • imageWCS (astWCS.WCS) - astWCS.WCS object
  • scaleFactor (float or list or tuple) - factor to resize image by - if tuple or list, in format [x scale factor, y scale factor]
Returns: dictionary
image data (numpy array), updated astWCS WCS object for image, in format {'data', 'wcs'}.

intensityCutImage(imageData, cutLevels)

source code 

Creates a matplotlib.pylab plot of an image array with the specified cuts in intensity applied. This routine is used by saveBitmap and saveContourOverlayBitmap, which both produce output as .png, .jpg, etc. images.

Parameters:
  • imageData (numpy array) - image data array
  • cutLevels (list) - sets the image scaling - available options:
    • pixel values: cutLevels=[low value, high value].
    • histogram equalisation: cutLevels=["histEq", number of bins ( e.g. 1024)]
    • relative: cutLevels=["relative", cut per cent level (e.g. 99.5)]
    • smart: cutLevels=["smart", cut per cent level (e.g. 99.5)]

    ["smart", 99.5] seems to provide good scaling over a range of different images.

Returns: dictionary
image section (numpy.array), matplotlib image normalisation (matplotlib.colors.Normalize), in the format {'image', 'norm'}.

Note: If cutLevels[0] == "histEq", then only {'image'} is returned.

resampleToTanProjection(imageData, imageWCS, outputPixDimensions=[600,600])

source code 

Resamples an image and WCS to a tangent plane projection. Purely for plotting purposes (e.g., ensuring RA, dec. coordinate axes perpendicular).

Parameters:
  • imageData (numpy array) - image data array
  • imageWCS (astWCS.WCS) - astWCS.WCS object
  • outputPixDimensions (list) - [width, height] of output image in pixels
Returns: dictionary
image data (numpy array), updated astWCS WCS object for image, in format {'data', 'wcs'}.

resampleToWCS(im1Data, im1WCS, im2Data, im2WCS, highAccuracy=False, onlyOverlapping=True)

source code 

Resamples data corresponding to second image (with data im2Data, WCS im2WCS) onto the WCS of the first image (im1Data, im1WCS). The output, resampled image is of the pixel same dimensions of the first image. This routine is for assisting in plotting - performing photometry on the output is not recommended.

Set highAccuracy == True to sample every corresponding pixel in each image; otherwise only every nth pixel (where n is the ratio of the image scales) will be sampled, with values in between being set using a linear interpolation (much faster).

Set onlyOverlapping == True to speed up resampling by only resampling the overlapping area defined by both image WCSs.

Parameters:
  • im1Data (numpy array) - image data array for first image
  • im1WCS (astWCS.WCS) - astWCS.WCS object corresponding to im1Data
  • im2Data (numpy array) - image data array for second image (to be resampled to match first image)
  • im2WCS (astWCS.WCS) - astWCS.WCS object corresponding to im2Data
  • highAccuracy (bool) - if True, sample every corresponding pixel in each image; otherwise, sample every nth pixel, where n = the ratio of the image scales.
  • onlyOverlapping (bool) - if True, only consider the overlapping area defined by both image WCSs (speeds things up)
Returns: dictionary
numpy image data array and associated WCS in format {'data', 'wcs'}

generateContourOverlay(backgroundImageData, backgroundImageWCS, contourImageData, contourImageWCS, contourLevels, contourSmoothFactor=0, highAccuracy=False)

source code 

Rescales an image array to be used as a contour overlay to have the same dimensions as the background image, and generates a set of contour levels. The image array from which the contours are to be generated will be resampled to the same dimensions as the background image data, and can be optionally smoothed using a Gaussian filter. The sigma of the Gaussian filter (contourSmoothFactor) is specified in arcsec.

Parameters:
  • backgroundImageData (numpy array) - background image data array
  • backgroundImageWCS (astWCS.WCS) - astWCS.WCS object of the background image data array
  • contourImageData (numpy array) - image data array from which contours are to be generated
  • contourImageWCS (astWCS.WCS) - astWCS.WCS object corresponding to contourImageData
  • contourLevels (list) - sets the contour levels - available options:
    • values: contourLevels=[list of values specifying each level]
    • linear spacing: contourLevels=['linear', min level value, max level value, number of levels] - can use "min", "max" to automatically set min, max levels from image data
    • log spacing: contourLevels=['log', min level value, max level value, number of levels] - can use "min", "max" to automatically set min, max levels from image data
  • contourSmoothFactor (float) - standard deviation (in arcsec) of Gaussian filter for pre-smoothing of contour image data (set to 0 for no smoothing)
  • highAccuracy (bool) - if True, sample every corresponding pixel in each image; otherwise, sample every nth pixel, where n = the ratio of the image scales.

saveBitmap(outputFileName, imageData, cutLevels, size, colorMapName)

source code 

Makes a bitmap image from an image array; the image format is specified by the filename extension. (e.g. ".jpg" =JPEG, ".png"=PNG).

Parameters:
  • outputFileName (string) - filename of output bitmap image
  • imageData (numpy array) - image data array
  • cutLevels (list) - sets the image scaling - available options:
    • pixel values: cutLevels=[low value, high value].
    • histogram equalisation: cutLevels=["histEq", number of bins ( e.g. 1024)]
    • relative: cutLevels=["relative", cut per cent level (e.g. 99.5)]
    • smart: cutLevels=["smart", cut per cent level (e.g. 99.5)]

    ["smart", 99.5] seems to provide good scaling over a range of different images.

  • size (int) - size of output image in pixels
  • colorMapName (string) - name of a standard matplotlib colormap, e.g. "hot", "cool", "gray" etc. (do "help(pylab.colormaps)" in the Python interpreter to see available options)

saveContourOverlayBitmap(outputFileName, backgroundImageData, backgroundImageWCS, cutLevels, size, colorMapName, contourImageData, contourImageWCS, contourSmoothFactor, contourLevels, contourColor, contourWidth)

source code 

Makes a bitmap image from an image array, with a set of contours generated from a second image array overlaid. The image format is specified by the file extension (e.g. ".jpg"=JPEG, ".png"=PNG). The image array from which the contours are to be generated can optionally be pre-smoothed using a Gaussian filter.

Parameters:
  • outputFileName (string) - filename of output bitmap image
  • backgroundImageData (numpy array) - background image data array
  • backgroundImageWCS (astWCS.WCS) - astWCS.WCS object of the background image data array
  • cutLevels (list) - sets the image scaling - available options:
    • pixel values: cutLevels=[low value, high value].
    • histogram equalisation: cutLevels=["histEq", number of bins ( e.g. 1024)]
    • relative: cutLevels=["relative", cut per cent level (e.g. 99.5)]
    • smart: cutLevels=["smart", cut per cent level (e.g. 99.5)]

    ["smart", 99.5] seems to provide good scaling over a range of different images.

  • size (int) - size of output image in pixels
  • colorMapName (string) - name of a standard matplotlib colormap, e.g. "hot", "cool", "gray" etc. (do "help(pylab.colormaps)" in the Python interpreter to see available options)
  • contourImageData (numpy array) - image data array from which contours are to be generated
  • contourImageWCS (astWCS.WCS) - astWCS.WCS object corresponding to contourImageData
  • contourSmoothFactor (float) - standard deviation (in pixels) of Gaussian filter for pre-smoothing of contour image data (set to 0 for no smoothing)
  • contourLevels (list) - sets the contour levels - available options:
    • values: contourLevels=[list of values specifying each level]
    • linear spacing: contourLevels=['linear', min level value, max level value, number of levels] - can use "min", "max" to automatically set min, max levels from image data
    • log spacing: contourLevels=['log', min level value, max level value, number of levels] - can use "min", "max" to automatically set min, max levels from image data
  • contourColor (string) - color of the overlaid contours, specified by the name of a standard matplotlib color, e.g., "black", "white", "cyan" etc. (do "help(pylab.colors)" in the Python interpreter to see available options)
  • contourWidth (int) - width of the overlaid contours

saveFITS(outputFileName, imageData, imageWCS=None)

source code 

Writes an image array to a new .fits file.

Parameters:
  • outputFileName (string) - filename of output FITS image
  • imageData (numpy array) - image data array
  • imageWCS (astWCS.WCS object) - image WCS object

Note: If imageWCS=None, the FITS image will be written with a rudimentary header containing no meta data.

histEq(inputArray, numBins)

source code 

Performs histogram equalisation of the input numpy array.

Parameters:
  • inputArray (numpy array) - image data array
  • numBins (int) - number of bins in which to perform the operation (e.g. 1024)
Returns: numpy array
image data array

normalise(inputArray, clipMinMax)

source code 

Clips the inputArray in intensity and normalises the array such that minimum and maximum values are 0, 1. Clip in intensity is specified by clipMinMax, a list in the format [clipMin, clipMax]

Used for normalising image arrays so that they can be turned into RGB arrays that matplotlib can plot (see astPlots.ImagePlot).

Parameters:
  • inputArray (numpy array) - image data array
  • clipMinMax (list) - [minimum value of clipped array, maximum value of clipped array]
Returns: numpy array
normalised array with minimum value 0, maximum value 1

astLib-0.10.0/docs/astLib/astLib.astSED.TopHatPassband-class.html0000664000175000017500000002061713047255533024714 0ustar mattymatty00000000000000 astLib.astSED.TopHatPassband
Package astLib :: Module astSED :: Class TopHatPassband
[hide private]
[frames] | no frames]

Class TopHatPassband

source code

Passband --+
           |
          TopHatPassband

This class generates a passband with a top hat response between the given wavelengths.

Instance Methods [hide private]
 
__init__(self, wavelengthMin, wavelengthMax, normalise=True)
Generates a passband object with top hat response between wavelengthMin, wavelengthMax.
source code

Inherited from Passband: asList, effectiveWavelength, plot, rescale

Method Details [hide private]

__init__(self, wavelengthMin, wavelengthMax, normalise=True)
(Constructor)

source code 

Generates a passband object with top hat response between wavelengthMin, wavelengthMax. Units are assumed to be Angstroms.

Parameters:
  • wavelengthMin (float) - minimum of the wavelength range of the passband
  • wavelengthMax (float) - maximum of the wavelength range of the passband
  • normalise (bool) - if True, scale such that total area under the passband over the wavelength range is 1.
Overrides: Passband.__init__

astLib-0.10.0/docs/astLib/index.html0000644000175000017500000000111413047255533017473 0ustar mattymatty00000000000000 API Documentation astLib-0.10.0/docs/astLib/redirect.html0000644000175000017500000000262613047255533020176 0ustar mattymatty00000000000000Epydoc Redirect Page

Epydoc Auto-redirect page

When javascript is enabled, this page will redirect URLs of the form redirect.html#dotted.name to the documentation for the object with the given fully-qualified dotted name.

 

astLib-0.10.0/docs/astLib/astLib.astSED.BC03Model-class.html0000664000175000017500000002047613047255533023454 0ustar mattymatty00000000000000 astLib.astSED.BC03Model
Package astLib :: Module astSED :: Class BC03Model
[hide private]
[frames] | no frames]

Class BC03Model

source code

StellarPopulation --+
                    |
                   BC03Model

This class describes a Bruzual & Charlot 2003 stellar population model, extracted from a GALAXEV .ised file using the galaxevpl program that is included in GALAXEV. The file format is white space delimited, with wavelength in the first column. Subsequent columns contain the model fluxes for SEDs of different ages, as specified when running galaxevpl. The age corresponding to each flux column is taken from the comment line beginning "# Age (yr)", and is converted to Gyr.

For example, to load a tau = 0.1 Gyr burst of star formation, solar metallicity, Salpeter IMF model stored in a file (created by galaxevpl) called "csp_lr_solar_0p1Gyr.136":

bc03model = BC03Model("csp_lr_solar_0p1Gyr.136")

The wavelength units of SEDs from BC03 models are Angstroms. Flux is converted into units of erg/s/Angstrom (the units in the files output by galaxevpl are LSun/Angstrom).

Instance Methods [hide private]
 
__init__(self, fileName) source code

Inherited from StellarPopulation: calcEvolutionCorrection, getColourEvolution, getMagEvolution, getSED

Method Details [hide private]

__init__(self, fileName)
(Constructor)

source code 
Overrides: StellarPopulation.__init__

astLib-0.10.0/docs/astLib/toc-astLib.astPlots-module.html0000644000175000017500000000345713047255533023474 0ustar mattymatty00000000000000 astPlots

Module astPlots


Classes

ImagePlot

Functions

u

Variables

DECIMAL_TICK_STEPS
DEC_TICK_STEPS
DEG
DOUBLE_PRIME
PRIME
RA_TICK_STEPS

[hide private] astLib-0.10.0/docs/astLib/module-tree.html0000644000175000017500000001162013047255533020611 0ustar mattymatty00000000000000 Module Hierarchy
 
[hide private]
[frames] | no frames]
[ Module Hierarchy | Class Hierarchy ]

Module Hierarchy

  • astLib: astLib - python astronomy modules
    • astLib.astCalc: module for performing common calculations
    • astLib.astCoords: module for coordinate manipulation (conversions, calculations etc.)
    • astLib.astImages: module for simple .fits image tasks (rotation, clipping out sections, making .pngs etc.)
    • astLib.astPlots: module for producing astronomical plots
    • astLib.astSED: module for performing calculations on Spectral Energy Distributions (SEDs)
    • astLib.astStats: module for performing statistical calculations.
    • astLib.astWCS: module for handling World Coordinate Systems (WCS)
astLib-0.10.0/docs/astLib/api-objects.txt0000644000175000017500000003374413047255533020455 0ustar mattymatty00000000000000astLib astLib-module.html astLib.__package__ astLib-module.html#__package__ astLib.astCalc astLib.astCalc-module.html astLib.astCalc.OMEGA_M0 astLib.astCalc-module.html#OMEGA_M0 astLib.astCalc.OmegaMz astLib.astCalc-module.html#OmegaMz astLib.astCalc.dm astLib.astCalc-module.html#dm astLib.astCalc.OmegaRz astLib.astCalc-module.html#OmegaRz astLib.astCalc.tl2z astLib.astCalc-module.html#tl2z astLib.astCalc.tz astLib.astCalc-module.html#tz astLib.astCalc.dl2z astLib.astCalc-module.html#dl2z astLib.astCalc.Ez2 astLib.astCalc-module.html#Ez2 astLib.astCalc.__package__ astLib.astCalc-module.html#__package__ astLib.astCalc.OmegaLz astLib.astCalc-module.html#OmegaLz astLib.astCalc.tl astLib.astCalc-module.html#tl astLib.astCalc.RVirialXRayCluster astLib.astCalc-module.html#RVirialXRayCluster astLib.astCalc.dVcdz astLib.astCalc-module.html#dVcdz astLib.astCalc.DeltaVz astLib.astCalc-module.html#DeltaVz astLib.astCalc.dl astLib.astCalc-module.html#dl astLib.astCalc.absMag astLib.astCalc-module.html#absMag astLib.astCalc.OMEGA_L0 astLib.astCalc-module.html#OMEGA_L0 astLib.astCalc.dc astLib.astCalc-module.html#dc astLib.astCalc.da astLib.astCalc-module.html#da astLib.astCalc.OMEGA_R0 astLib.astCalc-module.html#OMEGA_R0 astLib.astCalc.C_LIGHT astLib.astCalc-module.html#C_LIGHT astLib.astCalc.dc2z astLib.astCalc-module.html#dc2z astLib.astCalc.H0 astLib.astCalc-module.html#H0 astLib.astCalc.t0 astLib.astCalc-module.html#t0 astLib.astCalc.tz2z astLib.astCalc-module.html#tz2z astLib.astCalc.Ez astLib.astCalc-module.html#Ez astLib.astCoords astLib.astCoords-module.html astLib.astCoords.decimal2hms astLib.astCoords-module.html#decimal2hms astLib.astCoords.calcAngSepDeg astLib.astCoords-module.html#calcAngSepDeg astLib.astCoords.decimal2dms astLib.astCoords-module.html#decimal2dms astLib.astCoords.dms2decimal astLib.astCoords-module.html#dms2decimal astLib.astCoords.shiftRADec astLib.astCoords-module.html#shiftRADec astLib.astCoords.hms2decimal astLib.astCoords-module.html#hms2decimal astLib.astCoords.calcRADecSearchBox astLib.astCoords-module.html#calcRADecSearchBox astLib.astCoords.convertCoords astLib.astCoords-module.html#convertCoords astLib.astImages astLib.astImages-module.html astLib.astImages.resampleToTanProjection astLib.astImages-module.html#resampleToTanProjection astLib.astImages.intensityCutImage astLib.astImages-module.html#intensityCutImage astLib.astImages.clipRotatedImageSectionWCS astLib.astImages-module.html#clipRotatedImageSectionWCS astLib.astImages.saveFITS astLib.astImages-module.html#saveFITS astLib.astImages.resampleToWCS astLib.astImages-module.html#resampleToWCS astLib.astImages.clipImageSectionWCS astLib.astImages-module.html#clipImageSectionWCS astLib.astImages.saveBitmap astLib.astImages-module.html#saveBitmap astLib.astImages.generateContourOverlay astLib.astImages-module.html#generateContourOverlay astLib.astImages.scaleImage astLib.astImages-module.html#scaleImage astLib.astImages.normalise astLib.astImages-module.html#normalise astLib.astImages.clipImageSectionPix astLib.astImages-module.html#clipImageSectionPix astLib.astImages.clipUsingRADecCoords astLib.astImages-module.html#clipUsingRADecCoords astLib.astImages.REPORT_ERRORS astLib.astImages-module.html#REPORT_ERRORS astLib.astImages.histEq astLib.astImages-module.html#histEq astLib.astImages.saveContourOverlayBitmap astLib.astImages-module.html#saveContourOverlayBitmap astLib.astPlots astLib.astPlots-module.html astLib.astPlots.RA_TICK_STEPS astLib.astPlots-module.html#RA_TICK_STEPS astLib.astPlots.PRIME astLib.astPlots-module.html#PRIME astLib.astPlots.DEC_TICK_STEPS astLib.astPlots-module.html#DEC_TICK_STEPS astLib.astPlots.u astLib.astPlots-module.html#u astLib.astPlots.DOUBLE_PRIME astLib.astPlots-module.html#DOUBLE_PRIME astLib.astPlots.DEG astLib.astPlots-module.html#DEG astLib.astPlots.DECIMAL_TICK_STEPS astLib.astPlots-module.html#DECIMAL_TICK_STEPS astLib.astSED astLib.astSED-module.html astLib.astSED.makeModelSEDDictList astLib.astSED-module.html#makeModelSEDDictList astLib.astSED.fitSEDDict astLib.astSED-module.html#fitSEDDict astLib.astSED.SOL astLib.astSED-module.html#SOL astLib.astSED.__package__ astLib.astSED-module.html#__package__ astLib.astSED.VEGA astLib.astSED-module.html#VEGA astLib.astSED.mag2Jy astLib.astSED-module.html#mag2Jy astLib.astSED.mags2SEDDict astLib.astSED-module.html#mags2SEDDict astLib.astSED.AB astLib.astSED-module.html#AB astLib.astSED.flux2Mag astLib.astSED-module.html#flux2Mag astLib.astSED.Jy2Mag astLib.astSED-module.html#Jy2Mag astLib.astSED.mag2Flux astLib.astSED-module.html#mag2Flux astLib.astStats astLib.astStats-module.html astLib.astStats.rms astLib.astStats-module.html#rms astLib.astStats.clippedWeightedLSFit astLib.astStats-module.html#clippedWeightedLSFit astLib.astStats.biweightScale astLib.astStats-module.html#biweightScale astLib.astStats.stdev astLib.astStats-module.html#stdev astLib.astStats.biweightTransform astLib.astStats-module.html#biweightTransform astLib.astStats.biweightClipped astLib.astStats-module.html#biweightClipped astLib.astStats.weightedLSFit astLib.astStats-module.html#weightedLSFit astLib.astStats.__package__ astLib.astStats-module.html#__package__ astLib.astStats.cumulativeBinner astLib.astStats-module.html#cumulativeBinner astLib.astStats.clippedMeanStdev astLib.astStats-module.html#clippedMeanStdev astLib.astStats.binner astLib.astStats-module.html#binner astLib.astStats.biweightLSFit astLib.astStats-module.html#biweightLSFit astLib.astStats.weightedStdev astLib.astStats-module.html#weightedStdev astLib.astStats.modeEstimate astLib.astStats-module.html#modeEstimate astLib.astStats.REPORT_ERRORS astLib.astStats-module.html#REPORT_ERRORS astLib.astStats.weightedMean astLib.astStats-module.html#weightedMean astLib.astStats.weightedBinner astLib.astStats-module.html#weightedBinner astLib.astStats.median astLib.astStats-module.html#median astLib.astStats.OLSFit astLib.astStats-module.html#OLSFit astLib.astStats.MAD astLib.astStats-module.html#MAD astLib.astStats.biweightLocation astLib.astStats-module.html#biweightLocation astLib.astStats.mean astLib.astStats-module.html#mean astLib.astWCS astLib.astWCS-module.html astLib.astWCS.findWCSOverlap astLib.astWCS-module.html#findWCSOverlap astLib.astWCS.lconv astLib.astWCS-module.html#lconv astLib.astWCS.NUMPY_MODE astLib.astWCS-module.html#NUMPY_MODE astLib.astPlots.ImagePlot astLib.astPlots.ImagePlot-class.html astLib.astPlots.ImagePlot.draw astLib.astPlots.ImagePlot-class.html#draw astLib.astPlots.ImagePlot.addContourOverlay astLib.astPlots.ImagePlot-class.html#addContourOverlay astLib.astPlots.ImagePlot.addPlotObjects astLib.astPlots.ImagePlot-class.html#addPlotObjects astLib.astPlots.ImagePlot.calcWCSAxisLabels astLib.astPlots.ImagePlot-class.html#calcWCSAxisLabels astLib.astPlots.ImagePlot.addCompass astLib.astPlots.ImagePlot-class.html#addCompass astLib.astPlots.ImagePlot.getTickSteps astLib.astPlots.ImagePlot-class.html#getTickSteps astLib.astPlots.ImagePlot.removeContourOverlay astLib.astPlots.ImagePlot-class.html#removeContourOverlay astLib.astPlots.ImagePlot.removePlotObjects astLib.astPlots.ImagePlot-class.html#removePlotObjects astLib.astPlots.ImagePlot.addScaleBar astLib.astPlots.ImagePlot-class.html#addScaleBar astLib.astPlots.ImagePlot.save astLib.astPlots.ImagePlot-class.html#save astLib.astPlots.ImagePlot.__init__ astLib.astPlots.ImagePlot-class.html#__init__ astLib.astSED.BC03Model astLib.astSED.BC03Model-class.html astLib.astSED.StellarPopulation.calcEvolutionCorrection astLib.astSED.StellarPopulation-class.html#calcEvolutionCorrection astLib.astSED.StellarPopulation.getSED astLib.astSED.StellarPopulation-class.html#getSED astLib.astSED.StellarPopulation.getMagEvolution astLib.astSED.StellarPopulation-class.html#getMagEvolution astLib.astSED.BC03Model.__init__ astLib.astSED.BC03Model-class.html#__init__ astLib.astSED.StellarPopulation.getColourEvolution astLib.astSED.StellarPopulation-class.html#getColourEvolution astLib.astSED.M05Model astLib.astSED.M05Model-class.html astLib.astSED.StellarPopulation.calcEvolutionCorrection astLib.astSED.StellarPopulation-class.html#calcEvolutionCorrection astLib.astSED.StellarPopulation.getSED astLib.astSED.StellarPopulation-class.html#getSED astLib.astSED.StellarPopulation.getMagEvolution astLib.astSED.StellarPopulation-class.html#getMagEvolution astLib.astSED.M05Model.__init__ astLib.astSED.M05Model-class.html#__init__ astLib.astSED.StellarPopulation.getColourEvolution astLib.astSED.StellarPopulation-class.html#getColourEvolution astLib.astSED.P09Model astLib.astSED.P09Model-class.html astLib.astSED.StellarPopulation.calcEvolutionCorrection astLib.astSED.StellarPopulation-class.html#calcEvolutionCorrection astLib.astSED.StellarPopulation.getSED astLib.astSED.StellarPopulation-class.html#getSED astLib.astSED.StellarPopulation.getMagEvolution astLib.astSED.StellarPopulation-class.html#getMagEvolution astLib.astSED.P09Model.__init__ astLib.astSED.P09Model-class.html#__init__ astLib.astSED.StellarPopulation.getColourEvolution astLib.astSED.StellarPopulation-class.html#getColourEvolution astLib.astSED.Passband astLib.astSED.Passband-class.html astLib.astSED.Passband.rescale astLib.astSED.Passband-class.html#rescale astLib.astSED.Passband.plot astLib.astSED.Passband-class.html#plot astLib.astSED.Passband.effectiveWavelength astLib.astSED.Passband-class.html#effectiveWavelength astLib.astSED.Passband.asList astLib.astSED.Passband-class.html#asList astLib.astSED.Passband.__init__ astLib.astSED.Passband-class.html#__init__ astLib.astSED.SED astLib.astSED.SED-class.html astLib.astSED.SED.plot astLib.astSED.SED-class.html#plot astLib.astSED.SED.copy astLib.astSED.SED-class.html#copy astLib.astSED.SED.calcFlux astLib.astSED.SED-class.html#calcFlux astLib.astSED.SED.redshift astLib.astSED.SED-class.html#redshift astLib.astSED.SED.loadFromFile astLib.astSED.SED-class.html#loadFromFile astLib.astSED.SED.normalise astLib.astSED.SED-class.html#normalise astLib.astSED.SED.smooth astLib.astSED.SED-class.html#smooth astLib.astSED.SED.writeToFile astLib.astSED.SED-class.html#writeToFile astLib.astSED.SED.normaliseToMag astLib.astSED.SED-class.html#normaliseToMag astLib.astSED.SED.extinctionCalzetti astLib.astSED.SED-class.html#extinctionCalzetti astLib.astSED.SED.__init__ astLib.astSED.SED-class.html#__init__ astLib.astSED.SED.getSEDDict astLib.astSED.SED-class.html#getSEDDict astLib.astSED.SED.integrate astLib.astSED.SED-class.html#integrate astLib.astSED.SED.matchFlux astLib.astSED.SED-class.html#matchFlux astLib.astSED.SED.calcColour astLib.astSED.SED-class.html#calcColour astLib.astSED.SED.asList astLib.astSED.SED-class.html#asList astLib.astSED.SED.calcMag astLib.astSED.SED-class.html#calcMag astLib.astSED.StellarPopulation astLib.astSED.StellarPopulation-class.html astLib.astSED.StellarPopulation.calcEvolutionCorrection astLib.astSED.StellarPopulation-class.html#calcEvolutionCorrection astLib.astSED.StellarPopulation.getSED astLib.astSED.StellarPopulation-class.html#getSED astLib.astSED.StellarPopulation.getColourEvolution astLib.astSED.StellarPopulation-class.html#getColourEvolution astLib.astSED.StellarPopulation.__init__ astLib.astSED.StellarPopulation-class.html#__init__ astLib.astSED.StellarPopulation.getMagEvolution astLib.astSED.StellarPopulation-class.html#getMagEvolution astLib.astSED.TopHatPassband astLib.astSED.TopHatPassband-class.html astLib.astSED.Passband.rescale astLib.astSED.Passband-class.html#rescale astLib.astSED.Passband.plot astLib.astSED.Passband-class.html#plot astLib.astSED.Passband.effectiveWavelength astLib.astSED.Passband-class.html#effectiveWavelength astLib.astSED.Passband.asList astLib.astSED.Passband-class.html#asList astLib.astSED.TopHatPassband.__init__ astLib.astSED.TopHatPassband-class.html#__init__ astLib.astSED.VegaSED astLib.astSED.VegaSED-class.html astLib.astSED.SED.plot astLib.astSED.SED-class.html#plot astLib.astSED.SED.matchFlux astLib.astSED.SED-class.html#matchFlux astLib.astSED.SED.getSEDDict astLib.astSED.SED-class.html#getSEDDict astLib.astSED.SED.redshift astLib.astSED.SED-class.html#redshift astLib.astSED.SED.loadFromFile astLib.astSED.SED-class.html#loadFromFile astLib.astSED.SED.normalise astLib.astSED.SED-class.html#normalise astLib.astSED.SED.smooth astLib.astSED.SED-class.html#smooth astLib.astSED.SED.writeToFile astLib.astSED.SED-class.html#writeToFile astLib.astSED.SED.normaliseToMag astLib.astSED.SED-class.html#normaliseToMag astLib.astSED.SED.extinctionCalzetti astLib.astSED.SED-class.html#extinctionCalzetti astLib.astSED.SED.asList astLib.astSED.SED-class.html#asList astLib.astSED.SED.calcFlux astLib.astSED.SED-class.html#calcFlux astLib.astSED.SED.integrate astLib.astSED.SED-class.html#integrate astLib.astSED.SED.copy astLib.astSED.SED-class.html#copy astLib.astSED.SED.calcColour astLib.astSED.SED-class.html#calcColour astLib.astSED.VegaSED.__init__ astLib.astSED.VegaSED-class.html#__init__ astLib.astSED.SED.calcMag astLib.astSED.SED-class.html#calcMag astLib.astWCS.WCS astLib.astWCS.WCS-class.html astLib.astWCS.WCS.getYPixelSizeDeg astLib.astWCS.WCS-class.html#getYPixelSizeDeg astLib.astWCS.WCS.getImageMinMaxWCSCoords astLib.astWCS.WCS-class.html#getImageMinMaxWCSCoords astLib.astWCS.WCS.getXPixelSizeDeg astLib.astWCS.WCS-class.html#getXPixelSizeDeg astLib.astWCS.WCS.getEquinox astLib.astWCS.WCS-class.html#getEquinox astLib.astWCS.WCS.coordsAreInImage astLib.astWCS.WCS-class.html#coordsAreInImage astLib.astWCS.WCS.getCentreWCSCoords astLib.astWCS.WCS-class.html#getCentreWCSCoords astLib.astWCS.WCS.getEpoch astLib.astWCS.WCS-class.html#getEpoch astLib.astWCS.WCS.updateFromHeader astLib.astWCS.WCS-class.html#updateFromHeader astLib.astWCS.WCS.__init__ astLib.astWCS.WCS-class.html#__init__ astLib.astWCS.WCS.isFlipped astLib.astWCS.WCS-class.html#isFlipped astLib.astWCS.WCS.pix2wcs astLib.astWCS.WCS-class.html#pix2wcs astLib.astWCS.WCS.getRotationDeg astLib.astWCS.WCS-class.html#getRotationDeg astLib.astWCS.WCS.copy astLib.astWCS.WCS-class.html#copy astLib.astWCS.WCS.getFullSizeSkyDeg astLib.astWCS.WCS-class.html#getFullSizeSkyDeg astLib.astWCS.WCS.getPixelSizeDeg astLib.astWCS.WCS-class.html#getPixelSizeDeg astLib.astWCS.WCS.getHalfSizeDeg astLib.astWCS.WCS-class.html#getHalfSizeDeg astLib.astWCS.WCS.wcs2pix astLib.astWCS.WCS-class.html#wcs2pix astLib-0.10.0/docs/astLib/crarr.png0000644000175000017500000000052413047255533017321 0ustar mattymatty00000000000000‰PNG  IHDR e¢E,tEXtCreation TimeTue 22 Aug 2006 00:43:10 -0500` XtIMEÖ)Ó}Ö pHYsÂÂnÐu>gAMA± üaEPLTEÿÿÿÍð×ÏÀ€f4sW áÛЊrD`@bCÜÕÈéäÜ–X{`,¯Ÿ€lN‡o@õóðª™xdEðí螊dÐÆ´”~TÖwÅvtRNS@æØfMIDATxÚc`@¼ì¼0&+š—Šˆ°»(’ˆ€ ;; /ðEXùØ‘?Ð n ƒª†— b;'ª+˜˜YÐ#œ(r<£"IEND®B`‚astLib-0.10.0/docs/astLib/toc-astLib.astCoords-module.html0000644000175000017500000000345013047255533023615 0ustar mattymatty00000000000000 astCoords

Module astCoords


Functions

calcAngSepDeg
calcRADecSearchBox
convertCoords
decimal2dms
decimal2hms
dms2decimal
hms2decimal
shiftRADec

[hide private] astLib-0.10.0/docs/astLib/astLib.astCalc-module.html0000644000175000017500000012376513047255533022457 0ustar mattymatty00000000000000 astLib.astCalc
Package astLib :: Module astCalc
[hide private]
[frames] | no frames]

Module astCalc

source code

module for performing common calculations

(c) 2007-2011 Matt Hilton

(c) 2013-2014 Matt Hilton & Steven Boada

http://astlib.sourceforge.net

The focus in this module is at present on calculations of distances in a given cosmology. The parameters for the cosmological model are set using the variables OMEGA_M0, OMEGA_L0, OMEGA_R0, H0 in the module namespace (see below for details).

Functions [hide private]
float
dl(z)
Calculates the luminosity distance in Mpc at redshift z.
source code
float
da(z)
Calculates the angular diameter distance in Mpc at redshift z.
source code
float
dm(z)
Calculates the transverse comoving distance (proper motion distance) in Mpc at redshift z.
source code
float
dc(z)
Calculates the line of sight comoving distance in Mpc at redshift z.
source code
float
dVcdz(z)
Calculates the line of sight comoving volume element per steradian dV/dz at redshift z.
source code
float
dl2z(distanceMpc)
Calculates the redshift z corresponding to the luminosity distance given in Mpc.
source code
float
dc2z(distanceMpc)
Calculates the redshift z corresponding to the comoving distance given in Mpc.
source code
float
t0()
Calculates the age of the universe in Gyr at z=0 for the current set of cosmological parameters.
source code
float
tl(z)
Calculates the lookback time in Gyr to redshift z for the current set of cosmological parameters.
source code
float
tz(z)
Calculates the age of the universe at redshift z for the current set of cosmological parameters.
source code
float
tl2z(tlGyr)
Calculates the redshift z corresponding to lookback time tlGyr given in Gyr.
source code
float
tz2z(tzGyr)
Calculates the redshift z corresponding to age of the universe tzGyr given in Gyr.
source code
float
absMag(appMag, distMpc)
Calculates the absolute magnitude of an object at given luminosity distance in Mpc.
source code
float
Ez(z)
Calculates the value of E(z), which describes evolution of the Hubble parameter with redshift, at redshift z for the current set of cosmological parameters.
source code
float
Ez2(z)
Calculates the value of E(z)^2, which describes evolution of the Hubble parameter with redshift, at redshift z for the current set of cosmological parameters.
source code
float
OmegaMz(z)
Calculates the matter density of the universe at redshift z.
source code
float
OmegaLz(z)
Calculates the dark energy density of the universe at redshift z.
source code
float
OmegaRz(z)
Calculates the radiation density of the universe at redshift z.
source code
float
DeltaVz(z)
Calculates the density contrast of a virialised region ΔV(z), assuming a ΛCDM-type flat cosmology.
source code
float
RVirialXRayCluster(kT, z, betaT)
Calculates the virial radius (in Mpc) of a galaxy cluster at redshift z with X-ray temperature kT, assuming self-similar evolution and a flat cosmology.
source code
Variables [hide private]
float OMEGA_M0 = 0.3
The matter density parameter at z=0.
float OMEGA_L0 = 0.7
The dark energy density (in the form of a cosmological constant) at z=0.
float OMEGA_R0 = 8.24e-05
The radiation density at z=0 (note this is only used currently in calculation of Ez).
float H0 = 70.0
The Hubble parameter (in km/s/Mpc) at z=0.
float C_LIGHT = 300000.0
The speed of light in km/s.
  __package__ = 'astLib'
Function Details [hide private]

dl(z)

source code 

Calculates the luminosity distance in Mpc at redshift z.

Parameters:
  • z (float) - redshift
Returns: float
luminosity distance in Mpc

da(z)

source code 

Calculates the angular diameter distance in Mpc at redshift z.

Parameters:
  • z (float) - redshift
Returns: float
angular diameter distance in Mpc

dm(z)

source code 

Calculates the transverse comoving distance (proper motion distance) in Mpc at redshift z.

Parameters:
  • z (float) - redshift
Returns: float
transverse comoving distance (proper motion distance) in Mpc

dc(z)

source code 

Calculates the line of sight comoving distance in Mpc at redshift z.

Parameters:
  • z (float) - redshift
Returns: float
transverse comoving distance (proper motion distance) in Mpc

dVcdz(z)

source code 

Calculates the line of sight comoving volume element per steradian dV/dz at redshift z.

Parameters:
  • z (float) - redshift
Returns: float
comoving volume element per steradian

dl2z(distanceMpc)

source code 

Calculates the redshift z corresponding to the luminosity distance given in Mpc.

Parameters:
  • distanceMpc (float) - distance in Mpc
Returns: float
redshift

dc2z(distanceMpc)

source code 

Calculates the redshift z corresponding to the comoving distance given in Mpc.

Parameters:
  • distanceMpc (float) - distance in Mpc
Returns: float
redshift

t0()

source code 

Calculates the age of the universe in Gyr at z=0 for the current set of cosmological parameters.

Returns: float
age of the universe in Gyr at z=0

tl(z)

source code 

Calculates the lookback time in Gyr to redshift z for the current set of cosmological parameters.

Parameters:
  • z (float) - redshift
Returns: float
lookback time in Gyr to redshift z

tz(z)

source code 

Calculates the age of the universe at redshift z for the current set of cosmological parameters.

Parameters:
  • z (float) - redshift
Returns: float
age of the universe in Gyr at redshift z

tl2z(tlGyr)

source code 

Calculates the redshift z corresponding to lookback time tlGyr given in Gyr.

Parameters:
  • tlGyr (float) - lookback time in Gyr
Returns: float
redshift

Note: Raises ValueError if tlGyr is not positive.

tz2z(tzGyr)

source code 

Calculates the redshift z corresponding to age of the universe tzGyr given in Gyr.

Parameters:
  • tzGyr (float) - age of the universe in Gyr
Returns: float
redshift

Note: Raises ValueError if Universe age not positive

absMag(appMag, distMpc)

source code 

Calculates the absolute magnitude of an object at given luminosity distance in Mpc.

Parameters:
  • appMag (float) - apparent magnitude of object
  • distMpc (float) - distance to object in Mpc
Returns: float
absolute magnitude of object

Ez(z)

source code 

Calculates the value of E(z), which describes evolution of the Hubble parameter with redshift, at redshift z for the current set of cosmological parameters. See, e.g., Bryan & Norman 1998 (ApJ, 495, 80).

Parameters:
  • z (float) - redshift
Returns: float
value of E(z) at redshift z

Ez2(z)

source code 

Calculates the value of E(z)^2, which describes evolution of the Hubble parameter with redshift, at redshift z for the current set of cosmological parameters. See, e.g., Bryan & Norman 1998 (ApJ, 495, 80).

Parameters:
  • z (float) - redshift
Returns: float
value of E(z)^2 at redshift z

OmegaMz(z)

source code 

Calculates the matter density of the universe at redshift z. See, e.g., Bryan & Norman 1998 (ApJ, 495, 80).

Parameters:
  • z (float) - redshift
Returns: float
matter density of universe at redshift z

OmegaLz(z)

source code 

Calculates the dark energy density of the universe at redshift z.

Parameters:
  • z (float) - redshift
Returns: float
dark energy density of universe at redshift z

OmegaRz(z)

source code 

Calculates the radiation density of the universe at redshift z.

Parameters:
  • z (float) - redshift
Returns: float
radiation density of universe at redshift z

DeltaVz(z)

source code 

Calculates the density contrast of a virialised region ΔV(z), assuming a ΛCDM-type flat cosmology. See, e.g., Bryan & Norman 1998 (ApJ, 495, 80).

Parameters:
  • z (float) - redshift
Returns: float
density contrast of a virialised region at redshift z

Note: If OMEGA_M0+OMEGA_L0 is not equal to 1, this routine exits and prints an error message to the console.

RVirialXRayCluster(kT, z, betaT)

source code 

Calculates the virial radius (in Mpc) of a galaxy cluster at redshift z with X-ray temperature kT, assuming self-similar evolution and a flat cosmology. See Arnaud et al. 2002 (A&A, 389, 1) and Bryan & Norman 1998 (ApJ, 495, 80). A flat ΛCDM-type flat cosmology is assumed.

Parameters:
  • kT (float) - cluster X-ray temperature in keV
  • z (float) - redshift
  • betaT (float) - the normalisation of the virial relation, for which Evrard et al. 1996 (ApJ,469, 494) find a value of 1.05
Returns: float
virial radius of cluster in Mpc

Note: If OMEGA_M0+OMEGA_L0 is not equal to 1, this routine exits and prints an error message to the console.


astLib-0.10.0/docs/astLib/toc.html0000644000175000017500000000476413047255533017167 0ustar mattymatty00000000000000 Table of Contents

Table of Contents


Everything

Modules

astLib
astLib.astCalc
astLib.astCoords
astLib.astImages
astLib.astPlots
astLib.astSED
astLib.astStats
astLib.astWCS

[hide private] astLib-0.10.0/docs/astLib/astLib.astCalc-pysrc.html0000644000175000017500000035306713047255533022332 0ustar mattymatty00000000000000 astLib.astCalc
Package astLib :: Module astCalc
[hide private]
[frames] | no frames]

Source Code for Module astLib.astCalc

  1  """module for performing common calculations 
  2   
  3  (c) 2007-2011 Matt Hilton 
  4   
  5  (c) 2013-2014 Matt Hilton & Steven Boada 
  6   
  7  U{http://astlib.sourceforge.net} 
  8   
  9  The focus in this module is at present on calculations of distances in a given 
 10  cosmology. The parameters for the cosmological model are set using the 
 11  variables OMEGA_M0, OMEGA_L0, OMEGA_R0, H0 in the module namespace (see below for details). 
 12   
 13  @var OMEGA_M0: The matter density parameter at z=0. 
 14  @type OMEGA_M0: float 
 15   
 16  @var OMEGA_L0: The dark energy density (in the form of a cosmological 
 17      constant) at z=0. 
 18  @type OMEGA_L0: float 
 19   
 20  @var OMEGA_R0: The radiation density at z=0 (note this is only used currently 
 21      in calculation of L{Ez}). 
 22  @type OMEGA_R0: float 
 23   
 24  @var H0: The Hubble parameter (in km/s/Mpc) at z=0. 
 25  @type H0: float 
 26   
 27  @var C_LIGHT: The speed of light in km/s. 
 28  @type C_LIGHT: float 
 29   
 30  """ 
 31   
 32  OMEGA_M0 = 0.3 
 33  OMEGA_L0 = 0.7 
 34  OMEGA_R0 = 8.24E-5 
 35  H0 = 70.0 
 36   
 37  C_LIGHT = 3.0e5 
 38   
 39  import math 
 40  try: 
 41      from scipy import integrate 
 42  except ImportError: 
 43      print "WARNING: astCalc failed to import scipy modules - ", 
 44      print "some functions will not work" 
 45   
 46  #import sys 
 47   
 48  #------------------------------------------------------------------------------ 
49 -def dl(z):
50 """Calculates the luminosity distance in Mpc at redshift z. 51 52 @type z: float 53 @param z: redshift 54 @rtype: float 55 @return: luminosity distance in Mpc 56 57 """ 58 59 DM = dm(z) 60 DL = (1.0+z)*DM 61 62 return DL
63 64 #------------------------------------------------------------------------------
65 -def da(z):
66 """Calculates the angular diameter distance in Mpc at redshift z. 67 68 @type z: float 69 @param z: redshift 70 @rtype: float 71 @return: angular diameter distance in Mpc 72 73 """ 74 DM = dm(z) 75 DA = DM/(1.0+z) 76 77 return DA
78 79 #------------------------------------------------------------------------------
80 -def dm(z):
81 """Calculates the transverse comoving distance (proper motion distance) in 82 Mpc at redshift z. 83 84 @type z: float 85 @param z: redshift 86 @rtype: float 87 @return: transverse comoving distance (proper motion distance) in Mpc 88 89 """ 90 91 OMEGA_K = 1.0 - OMEGA_M0 - OMEGA_L0 92 93 # Integration limits 94 xMax = 1.0 95 xMin = 1.0 / (1.0 + z) 96 97 # Function to be integrated 98 yn = lambda x: (1.0/math.sqrt(OMEGA_M0*x + OMEGA_L0*math.pow(x, 4) + 99 OMEGA_K*math.pow(x, 2))) 100 101 integralValue, integralError = integrate.quad(yn, xMin, xMax) 102 103 if OMEGA_K > 0.0: 104 DM = (C_LIGHT/H0 * math.pow(abs(OMEGA_K), -0.5) * 105 math.sinh(math.sqrt(abs(OMEGA_K)) * integralValue)) 106 elif OMEGA_K == 0.0: 107 DM = C_LIGHT/H0 * integralValue 108 elif OMEGA_K < 0.0: 109 DM = (C_LIGHT/H0 * math.pow(abs(OMEGA_K), -0.5) * 110 math.sin(math.sqrt(abs(OMEGA_K)) * integralValue)) 111 112 return DM
113 114 #------------------------------------------------------------------------------
115 -def dc(z):
116 """Calculates the line of sight comoving distance in Mpc at redshift z. 117 118 @type z: float 119 @param z: redshift 120 @rtype: float 121 @return: transverse comoving distance (proper motion distance) in Mpc 122 123 """ 124 125 OMEGA_K = 1.0 - OMEGA_M0 - OMEGA_L0 126 127 # Integration limits 128 xMax = 1.0 129 xMin = 1.0 / (1.0 + z) 130 131 # Function to be integrated 132 yn = lambda x: (1.0/math.sqrt(OMEGA_M0*x + OMEGA_L0*math.pow(x, 4) + 133 OMEGA_K*math.pow(x, 2))) 134 135 integralValue, integralError = integrate.quad(yn, xMin, xMax) 136 137 DC= C_LIGHT/H0*integralValue 138 139 return DC
140 141 #------------------------------------------------------------------------------
142 -def dVcdz(z):
143 """Calculates the line of sight comoving volume element per steradian dV/dz 144 at redshift z. 145 146 @type z: float 147 @param z: redshift 148 @rtype: float 149 @return: comoving volume element per steradian 150 151 """ 152 153 dH = C_LIGHT/H0 154 dVcdz=(dH*(math.pow(da(z),2))*(math.pow(1+z,2))/Ez(z)) 155 156 return dVcdz
157 158 #------------------------------------------------------------------------------
159 -def dl2z(distanceMpc):
160 """Calculates the redshift z corresponding to the luminosity distance given 161 in Mpc. 162 163 @type distanceMpc: float 164 @param distanceMpc: distance in Mpc 165 @rtype: float 166 @return: redshift 167 168 """ 169 170 dTarget = distanceMpc 171 172 toleranceMpc = 0.1 173 174 zMin = 0.0 175 zMax = 10.0 176 177 diff = dl(zMax) - dTarget 178 while diff < 0: 179 zMax = zMax + 5.0 180 diff = dl(zMax) - dTarget 181 182 zTrial = zMin + (zMax-zMin)/2.0 183 184 dTrial = dl(zTrial) 185 diff = dTrial - dTarget 186 while abs(diff) > toleranceMpc: 187 188 if diff > 0: 189 zMax = zMax - (zMax-zMin)/2.0 190 else: 191 zMin = zMin + (zMax-zMin)/2.0 192 193 zTrial = zMin + (zMax-zMin)/2.0 194 dTrial = dl(zTrial) 195 diff = dTrial - dTarget 196 197 return zTrial
198 199 #------------------------------------------------------------------------------
200 -def dc2z(distanceMpc):
201 """Calculates the redshift z corresponding to the comoving distance given 202 in Mpc. 203 204 @type distanceMpc: float 205 @param distanceMpc: distance in Mpc 206 @rtype: float 207 @return: redshift 208 209 """ 210 211 dTarget = distanceMpc 212 213 toleranceMpc = 0.1 214 215 zMin = 0.0 216 zMax = 10.0 217 218 diff = dc(zMax) - dTarget 219 while diff < 0: 220 zMax = zMax + 5.0 221 diff = dc(zMax) - dTarget 222 223 zTrial = zMin + (zMax-zMin)/2.0 224 225 dTrial = dc(zTrial) 226 diff = dTrial - dTarget 227 while abs(diff) > toleranceMpc: 228 229 if diff > 0: 230 zMax = zMax - (zMax-zMin)/2.0 231 else: 232 zMin = zMin + (zMax-zMin)/2.0 233 234 zTrial = zMin + (zMax-zMin)/2.0 235 dTrial = dc(zTrial) 236 diff = dTrial - dTarget 237 238 return zTrial
239 240 #------------------------------------------------------------------------------
241 -def t0():
242 """Calculates the age of the universe in Gyr at z=0 for the current set of 243 cosmological parameters. 244 245 @rtype: float 246 @return: age of the universe in Gyr at z=0 247 248 """ 249 250 OMEGA_K = 1.0 - OMEGA_M0 - OMEGA_L0 251 252 # Integration limits 253 xMax = 1.0 254 xMin = 0 255 256 # Function to be integrated 257 yn = lambda x: (x/math.sqrt(OMEGA_M0*x + OMEGA_L0*math.pow(x, 4) + 258 OMEGA_K*math.pow(x, 2))) 259 260 integralValue, integralError = integrate.quad(yn, xMin, xMax) 261 262 T0 = (1.0/H0*integralValue*3.08e19)/3.16e7/1e9 263 264 return T0
265 266 #------------------------------------------------------------------------------
267 -def tl(z):
268 """ Calculates the lookback time in Gyr to redshift z for the current set 269 of cosmological parameters. 270 271 @type z: float 272 @param z: redshift 273 @rtype: float 274 @return: lookback time in Gyr to redshift z 275 276 """ 277 OMEGA_K = 1.0 - OMEGA_M0 - OMEGA_L0 278 279 # Integration limits 280 xMax = 1.0 281 xMin = 1./(1.+z) 282 283 # Function to be integrated 284 yn = lambda x: (x/math.sqrt(OMEGA_M0*x + OMEGA_L0*math.pow(x, 4) + 285 OMEGA_K*math.pow(x, 2))) 286 287 integralValue, integralError = integrate.quad(yn, xMin, xMax) 288 289 T0 = (1.0/H0*integralValue*3.08e19)/3.16e7/1e9 290 291 return T0
292 293 #------------------------------------------------------------------------------
294 -def tz(z):
295 """Calculates the age of the universe at redshift z for the current set of 296 cosmological parameters. 297 298 @type z: float 299 @param z: redshift 300 @rtype: float 301 @return: age of the universe in Gyr at redshift z 302 303 """ 304 305 TZ = t0() - tl(z) 306 307 return TZ
308 309 #------------------------------------------------------------------------------
310 -def tl2z(tlGyr):
311 """Calculates the redshift z corresponding to lookback time tlGyr given in 312 Gyr. 313 314 @type tlGyr: float 315 @param tlGyr: lookback time in Gyr 316 @rtype: float 317 @return: redshift 318 319 @note: Raises ValueError if tlGyr is not positive. 320 321 """ 322 if tlGyr < 0.: 323 raise ValueError('Lookback time must be positive') 324 325 tTarget = tlGyr 326 327 toleranceGyr = 0.001 328 329 zMin = 0.0 330 zMax = 10.0 331 332 diff = tl(zMax) - tTarget 333 while diff < 0: 334 zMax = zMax + 5.0 335 diff = tl(zMax) - tTarget 336 337 zTrial = zMin + (zMax-zMin)/2.0 338 339 tTrial = tl(zTrial) 340 diff = tTrial - tTarget 341 while abs(diff) > toleranceGyr: 342 343 if diff > 0: 344 zMax = zMax - (zMax-zMin)/2.0 345 else: 346 zMin = zMin + (zMax-zMin)/2.0 347 348 zTrial = zMin + (zMax-zMin)/2.0 349 tTrial = tl(zTrial) 350 diff = tTrial - tTarget 351 352 return zTrial
353 354 #------------------------------------------------------------------------------
355 -def tz2z(tzGyr):
356 """Calculates the redshift z corresponding to age of the universe tzGyr 357 given in Gyr. 358 359 @type tzGyr: float 360 @param tzGyr: age of the universe in Gyr 361 @rtype: float 362 @return: redshift 363 364 @note: Raises ValueError if Universe age not positive 365 366 """ 367 if tzGyr <= 0: 368 raise ValueError('Universe age must be positive.') 369 tl = t0() - tzGyr 370 z = tl2z(tl) 371 372 return z
373 374 #------------------------------------------------------------------------------
375 -def absMag(appMag, distMpc):
376 """Calculates the absolute magnitude of an object at given luminosity 377 distance in Mpc. 378 379 @type appMag: float 380 @param appMag: apparent magnitude of object 381 @type distMpc: float 382 @param distMpc: distance to object in Mpc 383 @rtype: float 384 @return: absolute magnitude of object 385 386 """ 387 absMag = appMag - (5.0*math.log10(distMpc*1.0e5)) 388 389 return absMag
390 391 #------------------------------------------------------------------------------
392 -def Ez(z):
393 """Calculates the value of E(z), which describes evolution of the Hubble 394 parameter with redshift, at redshift z for the current set of cosmological 395 parameters. See, e.g., Bryan & Norman 1998 (ApJ, 495, 80). 396 397 @type z: float 398 @param z: redshift 399 @rtype: float 400 @return: value of E(z) at redshift z 401 402 """ 403 404 Ez = math.sqrt(Ez2(z)) 405 406 return Ez
407 408 #------------------------------------------------------------------------------
409 -def Ez2(z):
410 """Calculates the value of E(z)^2, which describes evolution of the Hubble 411 parameter with redshift, at redshift z for the current set of cosmological 412 parameters. See, e.g., Bryan & Norman 1998 (ApJ, 495, 80). 413 414 @type z: float 415 @param z: redshift 416 @rtype: float 417 @return: value of E(z)^2 at redshift z 418 419 """ 420 # This form of E(z) is more reliable at high redshift. It is basically the 421 # same for all redshifts below 10. But above that, the radiation term 422 # begins to dominate. From Peebles 1993. 423 424 Ez2 = (OMEGA_R0 * math.pow(1.0+z, 4) + 425 OMEGA_M0* math.pow(1.0+z, 3) + 426 (1.0- OMEGA_M0- OMEGA_L0) * 427 math.pow(1.0+z, 2) + OMEGA_L0) 428 429 return Ez2
430 431 #------------------------------------------------------------------------------
432 -def OmegaMz(z):
433 """Calculates the matter density of the universe at redshift z. See, e.g., 434 Bryan & Norman 1998 (ApJ, 495, 80). 435 436 @type z: float 437 @param z: redshift 438 @rtype: float 439 @return: matter density of universe at redshift z 440 441 """ 442 ez2 = Ez2(z) 443 444 Omega_Mz = (OMEGA_M0*math.pow(1.0+z, 3))/ez2 445 446 return Omega_Mz
447 448 #------------------------------------------------------------------------------
449 -def OmegaLz(z):
450 """ Calculates the dark energy density of the universe at redshift z. 451 452 @type z: float 453 @param z: redshift 454 @rtype: float 455 @return: dark energy density of universe at redshift z 456 457 """ 458 ez2 = Ez2(z) 459 460 return OMEGA_L0/ez2
461 462 #------------------------------------------------------------------------------
463 -def OmegaRz(z):
464 """ Calculates the radiation density of the universe at redshift z. 465 466 @type z: float 467 @param z: redshift 468 @rtype: float 469 @return: radiation density of universe at redshift z 470 471 """ 472 ez2 = Ez2(z) 473 474 return OMEGA_R0*math.pow(1+z, 4)/ez2
475 476 #------------------------------------------------------------------------------
477 -def DeltaVz(z):
478 """Calculates the density contrast of a virialised region S{Delta}V(z), 479 assuming a S{Lambda}CDM-type flat cosmology. See, e.g., Bryan & Norman 480 1998 (ApJ, 495, 80). 481 482 @type z: float 483 @param z: redshift 484 @rtype: float 485 @return: density contrast of a virialised region at redshift z 486 487 @note: If OMEGA_M0+OMEGA_L0 is not equal to 1, this routine exits and 488 prints an error 489 message to the console. 490 491 """ 492 493 OMEGA_K = 1.0 - OMEGA_M0 - OMEGA_L0 494 495 if OMEGA_K == 0.0: 496 Omega_Mz = OmegaMz(z) 497 deltaVz = (18.0*math.pow(math.pi, 2)+82.0*(Omega_Mz-1.0)-39.0 * 498 math.pow(Omega_Mz-1, 2)) 499 return deltaVz 500 else: 501 raise Exception("cosmology is NOT flat.")
502 503 #------------------------------------------------------------------------------
504 -def RVirialXRayCluster(kT, z, betaT):
505 """Calculates the virial radius (in Mpc) of a galaxy cluster at redshift z 506 with X-ray temperature kT, assuming self-similar evolution and a flat 507 cosmology. See Arnaud et al. 2002 (A&A, 389, 1) and Bryan & Norman 1998 508 (ApJ, 495, 80). A flat S{Lambda}CDM-type flat cosmology is assumed. 509 510 @type kT: float 511 @param kT: cluster X-ray temperature in keV 512 @type z: float 513 @param z: redshift 514 @type betaT: float 515 @param betaT: the normalisation of the virial relation, for which Evrard et 516 al. 1996 (ApJ,469, 494) find a value of 1.05 517 @rtype: float 518 @return: virial radius of cluster in Mpc 519 520 @note: If OMEGA_M0+OMEGA_L0 is not equal to 1, this routine exits and 521 prints an error message to the console. 522 523 """ 524 525 OMEGA_K = 1.0 - OMEGA_M0 - OMEGA_L0 526 527 if OMEGA_K == 0.0: 528 Omega_Mz = OmegaMz(z) 529 deltaVz = (18.0 * math.pow(math.pi, 2) + 82.0 * (Omega_Mz-1.0)- 39.0 * 530 math.pow(Omega_Mz-1, 2)) 531 deltaz = (deltaVz*OMEGA_M0)/(18.0*math.pow(math.pi, 2)*Omega_Mz) 532 533 # The equation quoted in Arnaud, Aghanim & Neumann is for h50, so need 534 # to scale it 535 h50 = H0/50.0 536 Rv = (3.80*math.sqrt(betaT)*math.pow(deltaz, -0.5) * 537 math.pow(1.0+z, (-3.0/2.0)) * math.sqrt(kT/10.0)*(1.0/h50)) 538 539 return Rv 540 541 else: 542 raise Exception("cosmology is NOT flat.")
543 544 #------------------------------------------------------------------------------ 545

astLib-0.10.0/docs/astLib/toc-astLib.astWCS-module.html0000644000175000017500000000262513047255533023023 0ustar mattymatty00000000000000 astWCS

Module astWCS


Classes

WCS

Functions

findWCSOverlap

Variables

NUMPY_MODE
lconv

[hide private] astLib-0.10.0/docs/astLib/astLib.astCoords-pysrc.html0000644000175000017500000030016213047255533022705 0ustar mattymatty00000000000000 astLib.astCoords
Package astLib :: Module astCoords
[hide private]
[frames] | no frames]

Source Code for Module astLib.astCoords

  1  """module for coordinate manipulation (conversions, calculations etc.) 
  2   
  3  (c) 2007-2012 Matt Hilton 
  4   
  5  (c) 2013-2014 Matt Hilton & Steven Boada 
  6   
  7  U{http://astlib.sourceforge.net} 
  8   
  9  """ 
 10   
 11  import sys 
 12  import math 
 13  import numpy 
 14  from PyWCSTools import wcscon 
 15   
 16  #----------------------------------------------------------------------------- 
17 -def hms2decimal(RAString, delimiter):
18 """Converts a delimited string of Hours:Minutes:Seconds format into decimal 19 degrees. 20 21 @type RAString: string 22 @param RAString: coordinate string in H:M:S format 23 @type delimiter: string 24 @param delimiter: delimiter character in RAString 25 @rtype: float 26 @return: coordinate in decimal degrees 27 28 """ 29 # is it in HH:MM:SS format? 30 if delimiter == "": 31 RABits = str(RAString).split() 32 else: 33 RABits = str(RAString).split(delimiter) 34 if len(RABits) > 1: 35 RAHDecimal = float(RABits[0]) 36 if len(RABits) > 1: 37 RAHDecimal = RAHDecimal+(float(RABits[1])/60.0) 38 if len(RABits) > 2: 39 RAHDecimal = RAHDecimal+(float(RABits[2])/3600.0) 40 RADeg = (RAHDecimal/24.0)*360.0 41 else: 42 RADeg = float(RAString) 43 44 return RADeg
45 46 #-----------------------------------------------------------------------------
47 -def dms2decimal(decString, delimiter):
48 """Converts a delimited string of Degrees:Minutes:Seconds format into 49 decimal degrees. 50 51 @type decString: string 52 @param decString: coordinate string in D:M:S format 53 @type delimiter: string 54 @param delimiter: delimiter character in decString 55 @rtype: float 56 @return: coordinate in decimal degrees 57 58 """ 59 # is it in DD:MM:SS format? 60 if delimiter == "": 61 decBits = str(decString).split() 62 else: 63 decBits = str(decString).split(delimiter) 64 if len(decBits) > 1: 65 decDeg = float(decBits[0]) 66 if decBits[0].find("-") != -1: 67 if len(decBits) > 1: 68 decDeg = decDeg-(float(decBits[1])/60.0) 69 if len(decBits) > 2: 70 decDeg = decDeg-(float(decBits[2])/3600.0) 71 else: 72 if len(decBits) > 1: 73 decDeg = decDeg+(float(decBits[1])/60.0) 74 if len(decBits) > 2: 75 decDeg = decDeg+(float(decBits[2])/3600.0) 76 else: 77 decDeg = float(decString) 78 79 return decDeg
80 81 #-----------------------------------------------------------------------------
82 -def decimal2hms(RADeg, delimiter):
83 """Converts decimal degrees to string in Hours:Minutes:Seconds format with 84 user specified delimiter. 85 86 @type RADeg: float 87 @param RADeg: coordinate in decimal degrees 88 @type delimiter: string 89 @param delimiter: delimiter character in returned string 90 @rtype: string 91 @return: coordinate string in H:M:S format 92 93 """ 94 hours = (RADeg/360.0)*24 95 #if hours < 10 and hours >= 1: 96 if 1 <= hours < 10: 97 sHours = "0"+str(hours)[0] 98 elif hours >= 10: 99 sHours = str(hours)[:2] 100 elif hours < 1: 101 sHours = "00" 102 103 if str(hours).find(".") == -1: 104 mins = float(hours)*60.0 105 else: 106 mins = float(str(hours)[str(hours).index("."):])*60.0 107 #if mins<10 and mins>=1: 108 if 1 <= mins<10: 109 sMins = "0"+str(mins)[:1] 110 elif mins >= 10: 111 sMins = str(mins)[:2] 112 elif mins < 1: 113 sMins = "00" 114 115 secs = (hours-(float(sHours)+float(sMins)/60.0))*3600.0 116 #if secs < 10 and secs>0.001: 117 if 0.001 < secs < 10: 118 sSecs = "0"+str(secs)[:str(secs).find(".")+4] 119 elif secs < 0.0001: 120 sSecs = "00.001" 121 else: 122 sSecs = str(secs)[:str(secs).find(".")+4] 123 if len(sSecs) < 5: 124 sSecs = sSecs+"00" # So all to 3dp 125 126 if float(sSecs) == 60.000: 127 sSecs = "00.00" 128 sMins = str(int(sMins)+1) 129 if int(sMins) == 60: 130 sMins = "00" 131 sDeg = str(int(sDeg)+1) 132 133 return sHours+delimiter+sMins+delimiter+sSecs
134 135 #------------------------------------------------------------------------------
136 -def decimal2dms(decDeg, delimiter):
137 """Converts decimal degrees to string in Degrees:Minutes:Seconds format 138 with user specified delimiter. 139 140 @type decDeg: float 141 @param decDeg: coordinate in decimal degrees 142 @type delimiter: string 143 @param delimiter: delimiter character in returned string 144 @rtype: string 145 @return: coordinate string in D:M:S format 146 147 """ 148 # Positive 149 if decDeg > 0: 150 #if decDeg < 10 and decDeg>=1: 151 if 1 <= decDeg < 10: 152 sDeg = "0"+str(decDeg)[0] 153 elif decDeg >= 10: 154 sDeg = str(decDeg)[:2] 155 elif decDeg < 1: 156 sDeg = "00" 157 158 if str(decDeg).find(".") == -1: 159 mins = float(decDeg)*60.0 160 else: 161 mins = float(str(decDeg)[str(decDeg).index("."):])*60 162 #if mins<10 and mins>=1: 163 if 1 <= mins < 10: 164 sMins = "0"+str(mins)[:1] 165 elif mins >= 10: 166 sMins = str(mins)[:2] 167 elif mins < 1: 168 sMins = "00" 169 170 secs = (decDeg-(float(sDeg)+float(sMins)/60.0))*3600.0 171 #if secs<10 and secs>0: 172 if 0 < secs < 10: 173 sSecs = "0"+str(secs)[:str(secs).find(".")+3] 174 elif secs < 0.001: 175 sSecs = "00.00" 176 else: 177 sSecs = str(secs)[:str(secs).find(".")+3] 178 if len(sSecs) < 5: 179 sSecs = sSecs+"0" # So all to 2dp 180 181 if float(sSecs) == 60.00: 182 sSecs = "00.00" 183 sMins = str(int(sMins)+1) 184 if int(sMins) == 60: 185 sMins = "00" 186 sDeg = str(int(sDeg)+1) 187 188 return "+"+sDeg+delimiter+sMins+delimiter+sSecs 189 190 else: 191 #if decDeg>-10 and decDeg<=-1: 192 if -10 < decDeg <= -1: 193 sDeg = "-0"+str(decDeg)[1] 194 elif decDeg <= -10: 195 sDeg = str(decDeg)[:3] 196 elif decDeg > -1: 197 sDeg = "-00" 198 199 if str(decDeg).find(".") == -1: 200 mins = float(decDeg)*-60.0 201 else: 202 mins = float(str(decDeg)[str(decDeg).index("."):])*60 203 #if mins<10 and mins>=1: 204 if 1 <= mins < 10: 205 sMins = "0"+str(mins)[:1] 206 elif mins >= 10: 207 sMins = str(mins)[:2] 208 elif mins < 1: 209 sMins = "00" 210 211 secs = (decDeg-(float(sDeg)-float(sMins)/60.0))*3600.0 212 #if secs>-10 and secs<0: 213 # so don't get minus sign 214 if -10 < secs < 0: 215 sSecs = "0"+str(secs)[1:str(secs).find(".")+3] 216 elif secs > -0.001: 217 sSecs = "00.00" 218 else: 219 sSecs = str(secs)[1:str(secs).find(".")+3] 220 if len(sSecs) < 5: 221 sSecs = sSecs+"0" # So all to 2dp 222 223 if float(sSecs) == 60.00: 224 sSecs = "00.00" 225 sMins = str(int(sMins)+1) 226 if int(sMins) == 60: 227 sMins = "00" 228 sDeg = str(int(sDeg)-1) 229 230 return sDeg+delimiter+sMins+delimiter+sSecs
231 232 #-----------------------------------------------------------------------------
233 -def calcAngSepDeg(RADeg1, decDeg1, RADeg2, decDeg2):
234 """Calculates the angular separation of two positions on the sky (specified 235 in decimal degrees) in decimal degrees, assuming a tangent plane projection 236 (so separation has to be <90 deg). Note that RADeg2, decDeg2 can be numpy 237 arrays. 238 239 @type RADeg1: float 240 @param RADeg1: R.A. in decimal degrees for position 1 241 @type decDeg1: float 242 @param decDeg1: dec. in decimal degrees for position 1 243 @type RADeg2: float or numpy array 244 @param RADeg2: R.A. in decimal degrees for position 2 245 @type decDeg2: float or numpy array 246 @param decDeg2: dec. in decimal degrees for position 2 247 @rtype: float or numpy array, depending upon type of RADeg2, decDeg2 248 @return: angular separation in decimal degrees 249 250 """ 251 cRA = numpy.radians(RADeg1) 252 cDec = numpy.radians(decDeg1) 253 254 gRA = numpy.radians(RADeg2) 255 gDec = numpy.radians(decDeg2) 256 257 dRA = cRA-gRA 258 dDec = gDec-cDec 259 cosC = ((numpy.sin(gDec)*numpy.sin(cDec)) + 260 (numpy.cos(gDec)*numpy.cos(cDec) * numpy.cos(gRA-cRA))) 261 x = (numpy.cos(cDec)*numpy.sin(gRA-cRA))/cosC 262 y = (((numpy.cos(gDec)*numpy.sin(cDec)) - (numpy.sin(gDec) * 263 numpy.cos(cDec)*numpy.cos(gRA-cRA)))/cosC) 264 r = numpy.degrees(numpy.sqrt(x*x+y*y)) 265 266 return r
267 268 #-----------------------------------------------------------------------------
269 -def shiftRADec(ra1, dec1, deltaRA, deltaDec):
270 """Computes new right ascension and declination shifted from the original 271 by some delta RA and delta DEC. Input position is decimal degrees. Shifts 272 (deltaRA, deltaDec) are arcseconds, and output is decimal degrees. Based on 273 an IDL routine of the same name. 274 275 @param ra1: float 276 @type ra1: R.A. in decimal degrees 277 @param dec1: float 278 @type dec1: dec. in decimal degrees 279 @param deltaRA: float 280 @type deltaRA: shift in R.A. in arcseconds 281 @param deltaDec: float 282 @type deltaDec: shift in dec. in arcseconds 283 @rtype: float [newRA, newDec] 284 @return: shifted R.A. and dec. 285 286 """ 287 288 d2r = math.pi/180. 289 as2r = math.pi/648000. 290 291 # Convert everything to radians 292 rara1 = ra1*d2r 293 dcrad1 = dec1*d2r 294 shiftRArad = deltaRA*as2r 295 shiftDCrad = deltaDec*as2r 296 297 # Shift! 298 deldec2 = 0.0 299 sindis = math.sin(shiftRArad / 2.0) 300 sindelRA = sindis / math.cos(dcrad1) 301 delra = 2.0*math.asin(sindelRA) / d2r 302 303 # Make changes 304 ra2 = ra1+delra 305 dec2 = dec1 +deltaDec / 3600.0 306 307 return ra2, dec2
308 309 #-----------------------------------------------------------------------------
310 -def convertCoords(inputSystem, outputSystem, coordX, coordY, epoch):
311 """Converts specified coordinates (given in decimal degrees) between J2000, 312 B1950, and Galactic. 313 314 @type inputSystem: string 315 @param inputSystem: system of the input coordinates (either "J2000", 316 "B1950" or "GALACTIC") 317 @type outputSystem: string 318 @param outputSystem: system of the returned coordinates (either "J2000", 319 "B1950" or "GALACTIC") 320 @type coordX: float 321 @param coordX: longitude coordinate in decimal degrees, e.g. R. A. 322 @type coordY: float 323 @param coordY: latitude coordinate in decimal degrees, e.g. dec. 324 @type epoch: float 325 @param epoch: epoch of the input coordinates 326 @rtype: list 327 @return: coordinates in decimal degrees in requested output system 328 329 """ 330 331 if inputSystem=="J2000" or inputSystem=="B1950" or inputSystem=="GALACTIC": 332 if outputSystem=="J2000" or outputSystem=="B1950" or \ 333 outputSystem=="GALACTIC": 334 335 outCoords=wcscon.wcscon(wcscon.wcscsys(inputSystem), 336 wcscon.wcscsys(outputSystem), 0, 0, coordX, coordY, epoch) 337 338 return outCoords 339 340 raise Exception("inputSystem and outputSystem must be 'J2000', 'B1950'" 341 "or 'GALACTIC'")
342 343 #-----------------------------------------------------------------------------
344 -def calcRADecSearchBox(RADeg, decDeg, radiusSkyDeg):
345 """Calculates minimum and maximum RA, dec coords needed to define a box 346 enclosing a circle of radius radiusSkyDeg around the given RADeg, decDeg 347 coordinates. Useful for freeform queries of e.g. SDSS, UKIDSS etc.. Uses 348 L{calcAngSepDeg}, so has the same limitations. 349 350 @type RADeg: float 351 @param RADeg: RA coordinate of centre of search region 352 @type decDeg: float 353 @param decDeg: dec coordinate of centre of search region 354 @type radiusSkyDeg: float 355 @param radiusSkyDeg: radius in degrees on the sky used to define search 356 region 357 @rtype: list 358 @return: [RAMin, RAMax, decMin, decMax] - coordinates in decimal degrees 359 defining search box 360 361 """ 362 363 tolerance = 1e-5 # in degrees on sky 364 targetHalfSizeSkyDeg = radiusSkyDeg 365 funcCalls = ["calcAngSepDeg(RADeg, decDeg, guess, decDeg)", 366 "calcAngSepDeg(RADeg, decDeg, guess, decDeg)", 367 "calcAngSepDeg(RADeg, decDeg, RADeg, guess)", 368 "calcAngSepDeg(RADeg, decDeg, RADeg, guess)"] 369 coords = [RADeg, RADeg, decDeg, decDeg] 370 signs = [1.0, -1.0, 1.0, -1.0] 371 results = [] 372 for f, c, sign in zip(funcCalls, coords, signs): 373 # Initial guess range 374 maxGuess = sign*targetHalfSizeSkyDeg*10.0 375 minGuess = sign*targetHalfSizeSkyDeg/10.0 376 guessStep = (maxGuess-minGuess)/10.0 377 guesses = numpy.arange(minGuess+c, maxGuess+c, guessStep) 378 for i in range(50): 379 minSizeDiff = 1e6 380 bestGuess = None 381 for guess in guesses: 382 sizeDiff = abs(eval(f)-targetHalfSizeSkyDeg) 383 if sizeDiff < minSizeDiff: 384 minSizeDiff = sizeDiff 385 bestGuess = guess 386 if minSizeDiff < tolerance: 387 break 388 else: 389 guessRange = abs((maxGuess-minGuess)) 390 maxGuess = bestGuess+guessRange/4.0 391 minGuess = bestGuess-guessRange/4.0 392 guessStep = (maxGuess-minGuess)/10.0 393 guesses = numpy.arange(minGuess, maxGuess, guessStep) 394 results.append(bestGuess) 395 396 RAMax = results[0] 397 RAMin = results[1] 398 decMax = results[2] 399 decMin = results[3] 400 401 return [RAMin, RAMax, decMin, decMax]
402

astLib-0.10.0/docs/astLib/frames.html0000644000175000017500000000111413047255533017641 0ustar mattymatty00000000000000 API Documentation astLib-0.10.0/docs/astLib/astLib.astSED.M05Model-class.html0000664000175000017500000002120213047255533023352 0ustar mattymatty00000000000000 astLib.astSED.M05Model
Package astLib :: Module astSED :: Class M05Model
[hide private]
[frames] | no frames]

Class M05Model

source code

StellarPopulation --+
                    |
                   M05Model

This class describes a Maraston 2005 stellar population model. To load a composite stellar population model (CSP) for a tau = 0.1 Gyr burst of star formation, solar metallicity, Salpeter IMF:

m05csp = astSED.M05Model(M05_DIR+"/csp_e_0.10_z02_salp.sed_agb")

where M05_DIR is set to point to the directory where the Maraston 2005 models are stored on your system.

The file format of the Maraston 2005 simple stellar poulation (SSP) models is different to the file format used for the CSPs, and this needs to be specified using the fileType parameter. To load a SSP with solar metallicity, red horizontal branch morphology:

m05ssp = astSED.M05Model(M05_DIR+"/sed.ssz002.rhb", fileType = "ssp")

The wavelength units of SEDs from M05 models are Angstroms, with flux in units of erg/s/Angstrom.

Instance Methods [hide private]
 
__init__(self, fileName, fileType='csp') source code

Inherited from StellarPopulation: calcEvolutionCorrection, getColourEvolution, getMagEvolution, getSED

Method Details [hide private]

__init__(self, fileName, fileType='csp')
(Constructor)

source code 
Overrides: StellarPopulation.__init__

astLib-0.10.0/docs/astLib/astLib.astStats-module.html0000644000175000017500000013720613047255533022706 0ustar mattymatty00000000000000 astLib.astStats
Package astLib :: Module astStats
[hide private]
[frames] | no frames]

Module astStats

source code

module for performing statistical calculations.

(c) 2007-2012 Matt Hilton

(c) 2013-2014 Matt Hilton & Steven Boada

http://astlib.sourceforge.net

This module (as you may notice) provides very few statistical routines. It does, however, provide biweight (robust) estimators of location and scale, as described in Beers et al. 1990 (AJ, 100, 32), in addition to a robust least squares fitting routine that uses the biweight transform.

Some routines may fail if they are passed lists with few items and encounter a `divide by zero' error. Where this occurs, the function will return None. An error message will be printed to the console when this happens if astStats.REPORT_ERRORS=True (the default). Testing if an astStats function returns None can be used to handle errors in scripts.

For extensive statistics modules, the Python bindings for GNU R (http://rpy.sourceforge.net), or SciPy (http://www.scipy.org) are suggested.

Functions [hide private]
float
mean(dataList)
Calculates the mean average of a list of numbers.
source code
float
weightedMean(dataList)
Calculates the weighted mean average of a two dimensional list (value, weight) of numbers.
source code
float
stdev(dataList)
Calculates the (sample) standard deviation of a list of numbers.
source code
float
rms(dataList)
Calculates the root mean square of a list of numbers.
source code
float
weightedStdev(dataList)
Calculates the weighted (sample) standard deviation of a list of numbers.
source code
float
median(dataList)
Calculates the median of a list of numbers.
source code
float
modeEstimate(dataList)
Returns an estimate of the mode of a set of values by mode=(3*median)-(2*mean).
source code
float
MAD(dataList)
Calculates the Median Absolute Deviation of a list of numbers.
source code
float
biweightLocation(dataList, tuningConstant)
Calculates the biweight location estimator (like a robust average) of a list of numbers.
source code
float
biweightScale(dataList, tuningConstant)
Calculates the biweight scale estimator (like a robust standard deviation) of a list of numbers.
source code
dictionary
biweightClipped(dataList, tuningConstant, sigmaCut)
Iteratively calculates biweight location and scale, using sigma clipping, for a list of values.
source code
list
biweightTransform(dataList, tuningConstant)
Calculates the biweight transform for a set of values.
source code
dictionary
OLSFit(dataList)
Performs an ordinary least squares fit on a two dimensional list of numbers.
source code
dictionary
clippedMeanStdev(dataList, sigmaCut=3.0, maxIterations=10.0)
Calculates the clipped mean and stdev of a list of numbers.
source code
dictionary
clippedWeightedLSFit(dataList, sigmaCut)
Performs a weighted least squares fit on a list of numbers with sigma clipping.
source code
dictionary
weightedLSFit(dataList, weightType)
Performs a weighted least squares fit on a three dimensional list of numbers [x, y, y error].
source code
dictionary
biweightLSFit(dataList, tuningConstant, sigmaCut=None)
Performs a weighted least squares fit, where the weights used are the biweight transforms of the residuals to the previous best fit .i.e.
source code
list
cumulativeBinner(data, binMin, binMax, binTotal)
Bins the input data cumulatively.
source code
list
binner(data, binMin, binMax, binTotal)
Bins the input data..
source code
list
weightedBinner(data, weights, binMin, binMax, binTotal)
Bins the input data, recorded frequency is sum of weights in bin.
source code
Variables [hide private]
  REPORT_ERRORS = True
  __package__ = 'astLib'
Function Details [hide private]

mean(dataList)

source code 

Calculates the mean average of a list of numbers.

Parameters:
  • dataList (list or numpy array) - input data, must be a one dimensional list
Returns: float
mean average

weightedMean(dataList)

source code 

Calculates the weighted mean average of a two dimensional list (value, weight) of numbers.

Parameters:
  • dataList (list) - input data, must be a two dimensional list in format [value, weight]
Returns: float
weighted mean average

stdev(dataList)

source code 

Calculates the (sample) standard deviation of a list of numbers.

Parameters:
  • dataList (list or numpy array) - input data, must be a one dimensional list
Returns: float
standard deviation

rms(dataList)

source code 

Calculates the root mean square of a list of numbers.

Parameters:
  • dataList (list) - input data, must be a one dimensional list
Returns: float
root mean square

weightedStdev(dataList)

source code 

Calculates the weighted (sample) standard deviation of a list of numbers.

Parameters:
  • dataList (list) - input data, must be a two dimensional list in format [value, weight]
Returns: float
weighted standard deviation

Note: Returns None if an error occurs.

median(dataList)

source code 

Calculates the median of a list of numbers.

Parameters:
  • dataList (list or numpy array) - input data, must be a one dimensional list
Returns: float
median average

modeEstimate(dataList)

source code 

Returns an estimate of the mode of a set of values by mode=(3*median)-(2*mean).

Parameters:
  • dataList (list) - input data, must be a one dimensional list
Returns: float
estimate of mode average

MAD(dataList)

source code 

Calculates the Median Absolute Deviation of a list of numbers.

Parameters:
  • dataList (list) - input data, must be a one dimensional list
Returns: float
median absolute deviation

biweightLocation(dataList, tuningConstant)

source code 

Calculates the biweight location estimator (like a robust average) of a list of numbers.

Parameters:
  • dataList (list) - input data, must be a one dimensional list
  • tuningConstant (float) - 6.0 is recommended.
Returns: float
biweight location

Note: Returns None if an error occurs.

biweightScale(dataList, tuningConstant)

source code 

Calculates the biweight scale estimator (like a robust standard deviation) of a list of numbers.

Parameters:
  • dataList (list) - input data, must be a one dimensional list
  • tuningConstant (float) - 9.0 is recommended.
Returns: float
biweight scale

Note: Returns None if an error occurs.

biweightClipped(dataList, tuningConstant, sigmaCut)

source code 

Iteratively calculates biweight location and scale, using sigma clipping, for a list of values. The calculation is performed on the first column of a multi-dimensional list; other columns are ignored.

Parameters:
  • dataList (list) - input data
  • tuningConstant (float) - 6.0 is recommended for location estimates, 9.0 is recommended for scale estimates
  • sigmaCut (float) - sigma clipping to apply
Returns: dictionary
estimate of biweight location, scale, and list of non-clipped data, in the format {'biweightLocation', 'biweightScale', 'dataList'}

Note: Returns None if an error occurs.

biweightTransform(dataList, tuningConstant)

source code 

Calculates the biweight transform for a set of values. Useful for using as weights in robust line fitting.

Parameters:
  • dataList (list) - input data, must be a one dimensional list
  • tuningConstant (float) - 6.0 is recommended for location estimates, 9.0 is recommended for scale estimates
Returns: list
list of biweights

OLSFit(dataList)

source code 

Performs an ordinary least squares fit on a two dimensional list of numbers. Minimum number of data points is 5.

Parameters:
  • dataList (list) - input data, must be a two dimensional list in format [x, y]
Returns: dictionary
slope and intercept on y-axis, with associated errors, in the format {'slope', 'intercept', 'slopeError', 'interceptError'}

Note: Returns None if an error occurs.

clippedMeanStdev(dataList, sigmaCut=3.0, maxIterations=10.0)

source code 

Calculates the clipped mean and stdev of a list of numbers.

Parameters:
  • dataList (list) - input data, one dimensional list of numbers
  • sigmaCut (float) - clipping in Gaussian sigma to apply
  • maxIterations (int) - maximum number of iterations
Returns: dictionary
format {'clippedMean', 'clippedStdev', 'numPoints'}

clippedWeightedLSFit(dataList, sigmaCut)

source code 

Performs a weighted least squares fit on a list of numbers with sigma clipping. Minimum number of data points is 5.

Parameters:
  • dataList (list) - input data, must be a three dimensional list in format [x, y, y weight]
Returns: dictionary
slope and intercept on y-axis, with associated errors, in the format {'slope', 'intercept', 'slopeError', 'interceptError'}

Note: Returns None if an error occurs.

weightedLSFit(dataList, weightType)

source code 

Performs a weighted least squares fit on a three dimensional list of numbers [x, y, y error].

Parameters:
  • dataList (list) - input data, must be a three dimensional list in format [x, y, y error]
  • weightType (string) - if "errors", weights are calculated assuming the input data is in the format [x, y, error on y]; if "weights", the weights are assumed to be already calculated and stored in a fourth column [x, y, error on y, weight] (as used by e.g. astStats.biweightLSFit)
Returns: dictionary
slope and intercept on y-axis, with associated errors, in the format {'slope', 'intercept', 'slopeError', 'interceptError'}

Note: Returns None if an error occurs.

biweightLSFit(dataList, tuningConstant, sigmaCut=None)

source code 

Performs a weighted least squares fit, where the weights used are the biweight transforms of the residuals to the previous best fit .i.e. the procedure is iterative, and converges very quickly (iterations is set to 10 by default). Minimum number of data points is 10.

This seems to give slightly different results to the equivalent R routine, so use at your own risk!

Parameters:
  • dataList (list) - input data, must be a three dimensional list in format [x, y, y weight]
  • tuningConstant (float) - 6.0 is recommended for location estimates, 9.0 is recommended for scale estimates
  • sigmaCut (float) - sigma clipping to apply (set to None if not required)
Returns: dictionary
slope and intercept on y-axis, with associated errors, in the format {'slope', 'intercept', 'slopeError', 'interceptError'}

Note: Returns None if an error occurs.

cumulativeBinner(data, binMin, binMax, binTotal)

source code 

Bins the input data cumulatively.

Parameters:
  • data - input data, must be a one dimensional list
  • binMin (float) - minimum value from which to bin data
  • binMax (float) - maximum value from which to bin data
  • binTotal (int) - number of bins
Returns: list
binned data, in format [bin centre, frequency]

binner(data, binMin, binMax, binTotal)

source code 

Bins the input data..

Parameters:
  • data - input data, must be a one dimensional list
  • binMin (float) - minimum value from which to bin data
  • binMax (float) - maximum value from which to bin data
  • binTotal (int) - number of bins
Returns: list
binned data, in format [bin centre, frequency]

weightedBinner(data, weights, binMin, binMax, binTotal)

source code 

Bins the input data, recorded frequency is sum of weights in bin.

Parameters:
  • data - input data, must be a one dimensional list
  • binMin (float) - minimum value from which to bin data
  • binMax (float) - maximum value from which to bin data
  • binTotal (int) - number of bins
Returns: list
binned data, in format [bin centre, frequency]

astLib-0.10.0/docs/astLib/astLib.astSED.SED-class.html0000664000175000017500000012033313047255533022450 0ustar mattymatty00000000000000 astLib.astSED.SED
Package astLib :: Module astSED :: Class SED
[hide private]
[frames] | no frames]

Class SED

source code

Known Subclasses:

This class describes a Spectral Energy Distribution (SED).

To create a SED object, lists (or numpy arrays) of wavelength and relative flux must be provided. The SED can optionally be redshifted. The wavelength units of SEDs are assumed to be Angstroms - flux calculations using Passband and SED objects specified with different wavelength units will be incorrect.

The StellarPopulation class (and derivatives) can be used to extract SEDs for specified ages from e.g. the Bruzual & Charlot 2003 or Maraston 2005 models.

Instance Methods [hide private]
 
__init__(self, wavelength=[], flux=[], z=0.0, ageGyr=None, normalise=False, label=None) source code
SED object
copy(self)
Copies the SED, returning a new SED object
source code
 
loadFromFile(self, fileName)
Loads SED from a white space delimited file in the format wavelength, flux.
source code
 
writeToFile(self, fileName)
Writes SED to a white space delimited file in the format wavelength, flux.
source code
list
asList(self)
Returns a two dimensional list of [wavelength, flux], suitable for plotting by gnuplot.
source code
 
plot(self, xmin='min', xmax='max')
Produces a simple (wavelength, flux) plot of the SED.
source code
float
integrate(self, wavelengthMin='min', wavelengthMax='max')
Calculates flux in SED within given wavelength range.
source code
 
smooth(self, smoothPix)
Smooths SED.flux with a uniform (boxcar) filter of width smoothPix.
source code
 
redshift(self, z)
Redshifts the SED to redshift z.
source code
 
normalise(self, minWavelength='min', maxWavelength='max')
Normalises the SED such that the area under the specified wavelength range is equal to 1.
source code
 
normaliseToMag(self, ABMag, passband)
Normalises the SED to match the flux equivalent to the given AB magnitude in the given passband.
source code
 
matchFlux(self, matchSED, minWavelength, maxWavelength)
Matches the flux in the wavelength range given by minWavelength, maxWavelength to the flux in the same region in matchSED.
source code
float
calcFlux(self, passband)
Calculates flux in the given passband.
source code
float
calcMag(self, passband, addDistanceModulus=True, magType='Vega')
Calculates magnitude in the given passband.
source code
float
calcColour(self, passband1, passband2, magType='Vega')
Calculates the colour passband1-passband2.
source code
 
getSEDDict(self, passbands)
This is a convenience function for pulling out fluxes from a SED for a given set of passbands in the same format as made by mags2SEDDict - designed to make fitting code simpler.
source code
 
extinctionCalzetti(self, EBMinusV)
Applies the Calzetti et al.
source code
Method Details [hide private]

copy(self)

source code 

Copies the SED, returning a new SED object

Returns: SED object
SED

loadFromFile(self, fileName)

source code 

Loads SED from a white space delimited file in the format wavelength, flux. Lines beginning with # are ignored.

Parameters:
  • fileName (string) - path to file containing wavelength, flux data

writeToFile(self, fileName)

source code 

Writes SED to a white space delimited file in the format wavelength, flux.

Parameters:
  • fileName (string) - path to file

asList(self)

source code 

Returns a two dimensional list of [wavelength, flux], suitable for plotting by gnuplot.

Returns: list
list in format [wavelength, flux]

plot(self, xmin='min', xmax='max')

source code 

Produces a simple (wavelength, flux) plot of the SED.

Parameters:
  • xmin (float or 'min') - minimum of the wavelength range of the plot
  • xmax (float or 'max') - maximum of the wavelength range of the plot

integrate(self, wavelengthMin='min', wavelengthMax='max')

source code 

Calculates flux in SED within given wavelength range.

Parameters:
  • wavelengthMin (float or 'min') - minimum of the wavelength range
  • wavelengthMax (float or 'max') - maximum of the wavelength range
Returns: float
relative flux

smooth(self, smoothPix)

source code 

Smooths SED.flux with a uniform (boxcar) filter of width smoothPix. Cannot be undone.

Parameters:
  • smoothPix (int) - size of uniform filter applied to SED, in pixels

redshift(self, z)

source code 

Redshifts the SED to redshift z.

Parameters:
  • z (float) - redshift

normalise(self, minWavelength='min', maxWavelength='max')

source code 

Normalises the SED such that the area under the specified wavelength range is equal to 1.

Parameters:
  • minWavelength (float or 'min') - minimum wavelength of range over which to normalise SED
  • maxWavelength (float or 'max') - maximum wavelength of range over which to normalise SED

normaliseToMag(self, ABMag, passband)

source code 

Normalises the SED to match the flux equivalent to the given AB magnitude in the given passband.

Parameters:
  • ABMag (float) - AB magnitude to which the SED is to be normalised at the given passband
  • passband (an Passband object) - passband at which normalisation to AB magnitude is calculated

matchFlux(self, matchSED, minWavelength, maxWavelength)

source code 

Matches the flux in the wavelength range given by minWavelength, maxWavelength to the flux in the same region in matchSED. Useful for plotting purposes.

Parameters:
  • matchSED (SED object) - SED to match flux to
  • minWavelength (float) - minimum of range in which to match flux of current SED to matchSED
  • maxWavelength (float) - maximum of range in which to match flux of current SED to matchSED

calcFlux(self, passband)

source code 

Calculates flux in the given passband.

Parameters:
  • passband (Passband object) - filter passband through which to calculate the flux from the SED
Returns: float
flux

calcMag(self, passband, addDistanceModulus=True, magType='Vega')

source code 

Calculates magnitude in the given passband. If addDistanceModulus == True, then the distance modulus (5.0*log10*(dl*1e5), where dl is the luminosity distance in Mpc at the redshift of the SED) is added.

Parameters:
  • passband (Passband object) - filter passband through which to calculate the magnitude from the SED
  • addDistanceModulus (bool) - if True, adds 5.0*log10*(dl*1e5) to the mag returned, where dl is the luminosity distance (Mpc) corresponding to the SED z
  • magType (string) - either "Vega" or "AB"
Returns: float
magnitude through the given passband on the specified magnitude system

calcColour(self, passband1, passband2, magType='Vega')

source code 

Calculates the colour passband1-passband2.

Parameters:
  • passband1 (Passband object) - filter passband through which to calculate the first magnitude
  • passband1 (Passband object) - filter passband through which to calculate the second magnitude
  • magType (string) - either "Vega" or "AB"
  • passband2 (Passband object)
Returns: float
colour defined by passband1 - passband2 on the specified magnitude system

getSEDDict(self, passbands)

source code 

This is a convenience function for pulling out fluxes from a SED for a given set of passbands in the same format as made by mags2SEDDict - designed to make fitting code simpler.

Parameters:
  • passbands (list of Passband objects) - list of passbands through which fluxes will be calculated

extinctionCalzetti(self, EBMinusV)

source code 

Applies the Calzetti et al. 2000 (ApJ, 533, 682) extinction law to the SED with the given E(B-V) amount of extinction. R_v' = 4.05 is assumed (see equation (5) of Calzetti et al.).

Parameters:
  • EBMinusV (float) - extinction E(B-V), in magnitudes

astLib-0.10.0/docs/astLib/toc-astLib.astCalc-module.html0000644000175000017500000000635313047255533023233 0ustar mattymatty00000000000000 astCalc

Module astCalc


Functions

DeltaVz
Ez
Ez2
OmegaLz
OmegaMz
OmegaRz
RVirialXRayCluster
absMag
dVcdz
da
dc
dc2z
dl
dl2z
dm
t0
tl
tl2z
tz
tz2z

Variables

C_LIGHT
H0
OMEGA_L0
OMEGA_M0
OMEGA_R0
__package__

[hide private] astLib-0.10.0/docs/astLib/astLib-module.html0000644000175000017500000001572013047255533021075 0ustar mattymatty00000000000000 astLib
Package astLib
[hide private]
[frames] | no frames]

Package astLib

source code

astLib - python astronomy modules

(c) 2007-2012 Matt Hilton

(c) 2013-2014 Matt Hilton & Steven Boada

http://astlib.sourceforge.net

See the README file for information on usage and installation. See the LICENSE file for information on distribution.


Version: 0.8.0

Submodules [hide private]
  • astLib.astCalc: module for performing common calculations
  • astLib.astCoords: module for coordinate manipulation (conversions, calculations etc.)
  • astLib.astImages: module for simple .fits image tasks (rotation, clipping out sections, making .pngs etc.)
  • astLib.astPlots: module for producing astronomical plots
  • astLib.astSED: module for performing calculations on Spectral Energy Distributions (SEDs)
  • astLib.astStats: module for performing statistical calculations.
  • astLib.astWCS: module for handling World Coordinate Systems (WCS)

Variables [hide private]
  __package__ = None
astLib-0.10.0/docs/astLib/toc-astLib-module.html0000644000175000017500000000214213047255533021652 0ustar mattymatty00000000000000 astLib

Module astLib


Variables


[hide private] astLib-0.10.0/docs/astLib/astLib.astPlots-module.html0000644000175000017500000003756613047255533022721 0ustar mattymatty00000000000000 astLib.astPlots
Package astLib :: Module astPlots
[hide private]
[frames] | no frames]

Module astPlots

source code

module for producing astronomical plots

(c) 2007-2013 Matt Hilton

http://astlib.sourceforge.net

This module provides the matplotlib powered ImagePlot class, which is designed to be flexible. ImagePlots can have RA, Dec. coordinate axes, contour overlays, and have objects marked in them, using WCS coordinates. RGB plots are supported too.

Classes [hide private]
  ImagePlot
This class describes a matplotlib image plot containing an astronomical image with an associated WCS.
Functions [hide private]
 
u(x) source code
Variables [hide private]
dictionary list DEC_TICK_STEPS = [{'deg': 1.0/ 60.0/ 60.0, 'unit': "s"}, {'deg...
Defines the possible coordinate label steps on the delination axis in sexagesimal mode.
dictionary list RA_TICK_STEPS = [{'deg':(0.5/ 60.0/ 60.0/ 24.0)* 360.0, 'unit'...
Defines the possible coordinate label steps on the right ascension axis in sexagesimal mode.
list DECIMAL_TICK_STEPS = [0.001, 0.0025, 0.005, 0.01, 0.025, 0.05,...
Defines the possible coordinate label steps on both coordinate axes in decimal degrees mode.
string DEG = u("\N{DEGREE SIGN}")
Variable to stand in for the degrees symbol.
string PRIME = "$^\prime$"
Variable to stand in for the prime symbol.
string DOUBLE_PRIME = "$^{\prime\prime}$"
Variable to stand in for the double prime symbol.
Variables Details [hide private]

DEC_TICK_STEPS

Defines the possible coordinate label steps on the delination axis in sexagesimal mode. Dictionary format: {'deg', 'unit'}
Type:
dictionary list
Value:
[{'deg': 1.0/ 60.0/ 60.0, 'unit': "s"}, {'deg': 2.0/ 60.0/ 60.0, 'unit\
': "s"}, {'deg': 5.0/ 60.0/ 60.0, 'unit': "s"}, {'deg': 10.0/ 60.0/ 60\
.0, 'unit': "s"}, {'deg': 30.0/ 60.0/ 60.0, 'unit': "s"}, {'deg': 1.0/\
 60.0, 'unit': "m"}, {'deg': 2.0/ 60.0, 'unit': "m"}, {'deg': 5.0/ 60.\
0, 'unit': "m"}, {'deg': 15.0/ 60.0, 'unit': "m"}, {'deg': 30.0/ 60.0,\
 'unit': "m"}, {'deg': 1.0, 'unit': "d"}, {'deg': 2.0, 'unit': "d"}, {\
'deg': 4.0, 'unit': "d"}, {'deg': 5.0, 'unit': "d"}, {'deg': 10.0, 'un\
it': "d"}, {'deg': 20.0, 'unit': "d"}, {'deg': 30.0, 'unit': "d"}]

RA_TICK_STEPS

Defines the possible coordinate label steps on the right ascension axis in sexagesimal mode. Dictionary format: {'deg', 'unit'}
Type:
dictionary list
Value:
[{'deg':(0.5/ 60.0/ 60.0/ 24.0)* 360.0, 'unit': "s"}, {'deg':(1.0/ 60.\
0/ 60.0/ 24.0)* 360.0, 'unit': "s"}, {'deg':(2.0/ 60.0/ 60.0/ 24.0)* 3\
60.0, 'unit': "s"}, {'deg':(4.0/ 60.0/ 60.0/ 24.0)* 360.0, 'unit': "s"\
}, {'deg':(5.0/ 60.0/ 60.0/ 24.0)* 360.0, 'unit': "s"}, {'deg':(10.0/ \
60.0/ 60.0/ 24.0)* 360.0, 'unit': "s"}, {'deg':(20.0/ 60.0/ 60.0/ 24.0\
)* 360.0, 'unit': "s"}, {'deg':(30.0/ 60.0/ 60.0/ 24.0)* 360.0, 'unit'\
: "s"}, {'deg':(1.0/ 60.0/ 24.0)* 360.0, 'unit': "m"}, {'deg':(2.0/ 60\
.0/ 24.0)* 360.0, 'unit': "m"}, {'deg':(5.0/ 60.0/ 24.0)* 360.0, 'unit\
...

DECIMAL_TICK_STEPS

Defines the possible coordinate label steps on both coordinate axes in decimal degrees mode.
Type:
list
Value:
[0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 2.\
5, 5.0, 10.0, 30.0, 90.0]

astLib-0.10.0/docs/astLib/astLib.astWCS.WCS-class.html0000644000175000017500000010274513047255533022517 0ustar mattymatty00000000000000 astLib.astWCS.WCS
Package astLib :: Module astWCS :: Class WCS
[hide private]
[frames] | no frames]

Class WCS

source code

This class provides methods for accessing information from the World Coordinate System (WCS) contained in the header of a FITS image. Conversions between pixel and WCS coordinates can also be performed.

To create a WCS object from a FITS file called "test.fits", simply:

WCS=astWCS.WCS("test.fits")

Likewise, to create a WCS object from the pyfits.header of "test.fits":

img=pyfits.open("test.fits") header=img[0].header WCS=astWCS.WCS(header, mode = "pyfits")

Instance Methods [hide private]
 
__init__(self, headerSource, extensionName=0, mode="image", zapKeywords=[])
Creates a WCS object using either the information contained in the header of the specified .fits image, or from a pyfits.header object.
source code
astWCS.WCS object
copy(self)
Copies the WCS object to a new object.
source code
 
updateFromHeader(self)
Updates the WCS object using information from WCS.header.
source code
list
getCentreWCSCoords(self)
Returns the RA and dec coordinates (in decimal degrees) at the centre of the WCS.
source code
list
getFullSizeSkyDeg(self)
Returns the width, height of the image according to the WCS in decimal degrees on the sky (i.e., with the projection taken into account).
source code
list
getHalfSizeDeg(self)
Returns the half-width, half-height of the image according to the WCS in RA and dec degrees.
source code
list
getImageMinMaxWCSCoords(self)
Returns the minimum, maximum WCS coords defined by the size of the parent image (as defined by the NAXIS keywords in the image header).
source code
list
wcs2pix(self, RADeg, decDeg)
Returns the pixel coordinates corresponding to the input WCS coordinates (given in decimal degrees).
source code
list
pix2wcs(self, x, y)
Returns the WCS coordinates corresponding to the input pixel coordinates.
source code
bool
coordsAreInImage(self, RADeg, decDeg)
Returns True if the given RA, dec coordinate is within the image boundaries.
source code
float
getRotationDeg(self)
Returns the rotation angle in degrees around the axis, North through East.
source code
int
isFlipped(self)
Returns 1 if image is reflected around axis, otherwise returns 0.
source code
float
getPixelSizeDeg(self)
Returns the pixel scale of the WCS.
source code
float
getXPixelSizeDeg(self)
Returns the pixel scale along the x-axis of the WCS in degrees.
source code
float
getYPixelSizeDeg(self)
Returns the pixel scale along the y-axis of the WCS in degrees.
source code
float
getEquinox(self)
Returns the equinox of the WCS.
source code
float
getEpoch(self)
Returns the epoch of the WCS.
source code
Method Details [hide private]

__init__(self, headerSource, extensionName=0, mode="image", zapKeywords=[])
(Constructor)

source code 

Creates a WCS object using either the information contained in the header of the specified .fits image, or from a pyfits.header object. Set mode = "pyfits" if the headerSource is a pyfits.header.

For some images from some archives, particular header keywords such as COMMENT or HISTORY may contain unprintable strings. If you encounter this, try setting zapKeywords = ['COMMENT', 'HISTORY'] (for example).

Parameters:
  • headerSource (string or pyfits.header) - filename of input .fits image, or a pyfits.header object
  • extensionName (int or string) - name or number of .fits extension in which image data is stored
  • mode (string) - set to "image" if headerSource is a .fits file name, or set to "pyfits" if headerSource is a pyfits.header object
  • zapKeywords (list)

Note: The meta data provided by headerSource is stored in WCS.header as a pyfits.header object.

copy(self)

source code 

Copies the WCS object to a new object.

Returns: astWCS.WCS object
WCS object

updateFromHeader(self)

source code 

Updates the WCS object using information from WCS.header. This routine should be called whenever changes are made to WCS keywords in WCS.header.

getCentreWCSCoords(self)

source code 

Returns the RA and dec coordinates (in decimal degrees) at the centre of the WCS.

Returns: list
coordinates in decimal degrees in format [RADeg, decDeg]

getFullSizeSkyDeg(self)

source code 

Returns the width, height of the image according to the WCS in decimal degrees on the sky (i.e., with the projection taken into account).

Returns: list
width and height of image in decimal degrees on the sky in format [width, height]

getHalfSizeDeg(self)

source code 

Returns the half-width, half-height of the image according to the WCS in RA and dec degrees.

Returns: list
half-width and half-height of image in R.A., dec. decimal degrees in format [half-width, half-height]

getImageMinMaxWCSCoords(self)

source code 

Returns the minimum, maximum WCS coords defined by the size of the parent image (as defined by the NAXIS keywords in the image header).

Returns: list
[minimum R.A., maximum R.A., minimum Dec., maximum Dec.]

wcs2pix(self, RADeg, decDeg)

source code 

Returns the pixel coordinates corresponding to the input WCS coordinates (given in decimal degrees). RADeg, decDeg can be single floats, or lists or numpy arrays.

Returns: list
pixel coordinates in format [x, y]

pix2wcs(self, x, y)

source code 

Returns the WCS coordinates corresponding to the input pixel coordinates.

Returns: list
WCS coordinates in format [RADeg, decDeg]

coordsAreInImage(self, RADeg, decDeg)

source code 

Returns True if the given RA, dec coordinate is within the image boundaries.

Returns: bool
True if coordinate within image, False if not.

getRotationDeg(self)

source code 

Returns the rotation angle in degrees around the axis, North through East.

Returns: float
rotation angle in degrees

isFlipped(self)

source code 

Returns 1 if image is reflected around axis, otherwise returns 0.

Returns: int
1 if image is flipped, 0 otherwise

getPixelSizeDeg(self)

source code 

Returns the pixel scale of the WCS. This is the average of the x, y pixel scales.

Returns: float
pixel size in decimal degrees

getXPixelSizeDeg(self)

source code 

Returns the pixel scale along the x-axis of the WCS in degrees.

Returns: float
pixel size in decimal degrees

getYPixelSizeDeg(self)

source code 

Returns the pixel scale along the y-axis of the WCS in degrees.

Returns: float
pixel size in decimal degrees

getEquinox(self)

source code 

Returns the equinox of the WCS.

Returns: float
equinox of the WCS

getEpoch(self)

source code 

Returns the epoch of the WCS.

Returns: float
epoch of the WCS

astLib-0.10.0/examples/0000775000175000017500000000000013247150772015154 5ustar mattymatty00000000000000astLib-0.10.0/examples/compassTest/0000775000175000017500000000000013247150772017461 5ustar mattymatty00000000000000astLib-0.10.0/examples/compassTest/compassTest.py0000664000175000017500000000100013246706754022335 0ustar mattymatty00000000000000#!/usr/bin/env python #File: compassTest/compassTest.py #Created: Sat Dec 15 17:29:28 2012 #Last Change: Sat Dec 15 17:29:42 2012 # -*- coding: utf-8 -*- # # Test of contour plot import astropy.io.fits as pyfits from astLib import * import pylab TEST_IMAGE = "../../../testingData/testImage1.fits" img = pyfits.open(TEST_IMAGE) wcs = astWCS.WCS(TEST_IMAGE) d = img[0].data f = astPlots.ImagePlot(d, wcs, axes = [0, 0, 1, 1]) f.addCompass("SE", 60.0, color = 'red') f.draw() f.save("output_compassTest.png") astLib-0.10.0/examples/cosmologyTest/0000775000175000017500000000000013247150772020027 5ustar mattymatty00000000000000astLib-0.10.0/examples/cosmologyTest/cosmologyTest.py0000644000175000017500000000253313047255533023254 0ustar mattymatty00000000000000#!/usr/bin/env python #File: cosmologyTest/cosmologyTest.py #Created: Sat Dec 15 17:23:27 2012 #Last Change: Sat Dec 15 17:25:32 2012 # -*- coding: utf-8 -*- # # Tests astCalc routines from astLib import astCalc import numpy import pylab import IPython import sys pylab.matplotlib.interactive(True) omegaMs = [1.0, 0.2, 0.05] omegaLs = [0.0, 0.8, 0.0] styles = ['r-', 'b--', 'g:'] z = numpy.arange(0, 6, 0.1) # da pylab.clf() for m, l, s in zip(omegaMs, omegaLs, styles): astCalc.OMEGA_M0 = m astCalc.OMEGA_L = l label = "$\Omega_{m0}$ = %.2f $\Omega_\Lambda$ = %.2f" % (m, l) dH = astCalc.C_LIGHT/astCalc.H0 plotData = [] for i in z: plotData.append(astCalc.da(i)/dH) pylab.plot(z, plotData, s, label=label) pylab.ylim(0, 0.5) pylab.xlim(0, 5) pylab.xlabel("$z$") pylab.ylabel("$D_A/D_H$") pylab.legend(loc='lower right') # dV/dz pylab.clf() for m, l, s in zip(omegaMs, omegaLs, styles): astCalc.OMEGA_M0 = m astCalc.OMEGA_L = l label = "$\Omega_{m0}$ = %.2f $\Omega_\Lambda$ = %.2f" % (m, l) dH = astCalc.C_LIGHT/astCalc.H0 plotData = [] for i in z: plotData.append((1.0/dH)**3*astCalc.dVcdz(i)) pylab.plot(z, plotData, s, label=label) pylab.ylim(0, 1.1) pylab.xlim(0, 5) pylab.xlabel("$z$") pylab.ylabel("$(1/D_H)^3 dV/dz/d\Omega$") pylab.legend(loc='upper left') IPython.embed() sys.exit() astLib-0.10.0/examples/simpleRGB/0000775000175000017500000000000013247150772017000 5ustar mattymatty00000000000000astLib-0.10.0/examples/simpleRGB/simpleRGB.py0000664000175000017500000000161613246706754021210 0ustar mattymatty00000000000000#!/usr/bin/env python #File: simpleRGB/simpleRGB.py #Created: Sat Dec 15 17:25:44 2012 #Last Change: Sat Dec 15 17:26:38 2012 # -*- coding: utf-8 -*- # # Simple RGB ImagePlot example import numpy import astropy.io.fits as pyfits import pylab from astLib import * # Load the images - these have to be aligned to pixel and same pixel # dimensions rimg = pyfits.open("../../../testingData/stephanDSS2IR.fits") gimg = pyfits.open("../../../testingData/stephanDSS2Red.fits") bimg = pyfits.open("../../../testingData/stephanDSS2Blue.fits") wcs = astWCS.WCS("../../../testingData/stephanDSS2Blue.fits") r = rimg[0].data g = gimg[0].data b = bimg[0].data rCut = [r.min(), r.max()] gCut = [g.min(), g.max()] bCut = [b.min(), b.max()] # Make the figure p = astPlots.ImagePlot([r, g, b], wcs, axes = [0.12, 0.12, 0.8, 0.8], cutLevels = [rCut, gCut, bCut], title="Stephan's Quintet") p.save("output_simpleRGB.png") astLib-0.10.0/examples/rectangularClipTest/0000775000175000017500000000000013247150772021133 5ustar mattymatty00000000000000astLib-0.10.0/examples/rectangularClipTest/rectangularClipTest.py0000664000175000017500000000256013246706754025475 0ustar mattymatty00000000000000#!/usr/bin/env python #File: rectangularClipTest/rectangularClipTest.py #Created: Sat Dec 15 17:26:52 2012 #Last Change: Sat Dec 15 17:29:07 2012 # -*- coding: utf-8 -*- # # Quick script to test out rotation, clipping - rectangles import astropy.io.fits as pyfits from astLib import * # Regular clipping rputines test img = pyfits.open("../../../testingData/testImage3.fits") wcs = astWCS.WCS("../../../testingData/testImage3.fits") d = img[0].data RADeg, decDeg = wcs.getCentreWCSCoords() RADeg = RADeg+1.2/60.0 decDeg = decDeg-1.0/60.0 widthDeg = 18.0/60.0 heightDeg = 12.3/60.0 clip = astImages.clipRotatedImageSectionWCS(d, wcs, RADeg, decDeg, [widthDeg, heightDeg]) clipnr = astImages.clipImageSectionWCS(d, wcs, RADeg, decDeg, [widthDeg, heightDeg]) clippix = astImages.clipImageSectionPix(d, 500.0, 500.0, [100.0, 200.0]) astImages.saveFITS("output_rotated.fits", clip['data'], clip['wcs']) astImages.saveFITS("output_notRotated.fits", clipnr['data'], clipnr['wcs']) astImages.saveFITS("output_pixelCoords.fits", clippix, None) # RA, dec coords clipping routine img = pyfits.open("../../../testingData/testCEAImage.fits") wcs = astWCS.WCS("../../../testingData/testCEAImage.fits") d = img[0].data clip = astImages.clipUsingRADecCoords(img[0].data, wcs, 30.0, 50.0, -55.0, -50.0) astImages.saveFITS("output_RADecClipped.fits", clip['data'], clip['wcs']) astLib-0.10.0/examples/CMRRestFrameConversion/0000775000175000017500000000000013247150772021454 5ustar mattymatty00000000000000astLib-0.10.0/examples/CMRRestFrameConversion/CMRRestFrameConversion.py0000664000175000017500000003615113246706754026342 0ustar mattymatty00000000000000#!/usr/bin/env python #File: CMRRestFrameConversion.py #Created: Sat Dec 15 17:03:04 2012 #Last Change: Sat Dec 15 17:03:50 2012 # -*- coding: utf-8 -*- # # Calculates (U-V)z slopes, scatters and intercepts of a given color--magnitude # relation. # Follows the procedure in Appendix II of Mei et al. 2009 (ApJ, 690, 42), # except here we convert # mags to apparent mags at the distance of the Coma cluster. from astLib import astSED from astLib import astStats from astLib import astCalc from scipy import stats from scipy import optimize from scipy import interpolate import numpy import pylab import os import sys import random import math import pickle import string random.seed() #----------------------------------------------------------------------------- # Constants etc. # number of bootstrap samples, for estimating errors BOOTSTRAPS = 1000 # number of galaxies, gets * number of models, having same age in each # metallicity bin NGAL = 25 FILTER_DIR = "../../../testingData/filters/" # Map between short filter names on command line and paths, labels etc.. filterMap=[] filterMap.append({'shortName': 'r625', 'filePath': FILTER_DIR+'F625W_WFC.res', 'plotLabel': 'r625'}) filterMap.append({'shortName': 'i775', 'filePath': FILTER_DIR+'F775W_WFC.res', 'plotLabel': 'i775'}) filterMap.append({'shortName': 'z850', 'filePath': FILTER_DIR+'F850LP_WFC.res', 'plotLabel': 'z850'}) filterMap.append({'shortName': 'U', 'filePath': FILTER_DIR+'U_Johnson.res', 'plotLabel': 'U'}) filterMap.append({'shortName': 'V', 'filePath': FILTER_DIR+'V_Johnson.res', 'plotLabel': 'V'}) # Literature CMR results we want to convert, in their native format litCMRs = [] litCMRs.append({'name': 'RX J0152.7-1357 (Mei et al. 2009)', 'redshift': 0.83, 'colour': 'r625-z850', 'mag': 'i775', 'slope': -0.040, 'slopeErr': 0.017, 'intercept': 1.93, 'interceptErr': 0.02, 'zeroMag': 22.5, 'scatter': 0.079, 'scatterErr': 0.008, 'magType': "AB"}) #----------------------------------------------------------------------------- def GetCMR(nameFragment, dictList): """Finds the CMR dictionary in the litCMRs or results list, by looking for nameFragment in name. """ foundCMR = None for dict in dictList: if nameFragment in dict['name']: foundCMR = dict return foundCMR #------------------------------------------------------------------------------ def CalcTransformedCMRWithZM(obsCMR, fitMags, fitCols): """Calculates the CMR transformed to the rest frame, using the results of the magnitude and colour conversion fits. See handwritten notes for the tedious algebra involved. """ # we use the following notation s, zp for slope, zeropoint, append Err for # errors # CMR for CMR, Mag for fitMags, Col for fitCols sCMR = obsCMR['slope'] zpCMR = obsCMR['intercept'] zmCMR = obsCMR['zeroMag'] sMag = fitMags['slope'] zpMag=fitMags['intercept'] sCol = fitCols['slope'] zpCol = fitCols['intercept'] transformedZeroMag = obsCMR['transformedZeroMag'] a = sCMR**-1+sMag b = sCol/a c = zpCMR/sCMR d = c-zpMag-zmCMR e = d/a f = sCol*e # this last term is if we want to transform to e.g. match Mei et al. g = zpCol+f+(b*transformedZeroMag) restCMRSlope = b restCMRIntercept = g restCMRScatter = obsCMR['scatter']*fitCols['slope'] return ({'slope': restCMRSlope, 'intercept': restCMRIntercept, 'scatter': restCMRScatter}) #----------------------------------------------------------------------------- def BootstrapTransformedCMRErrorsWithZM(obsCMR, fitMags, fitCols): """Estimates errors on transformed CMR fit (i.e., into rest frame), by assuming the errors on the observed CMR fit, colour transformation fit, and mag. transformation fit have Gaussian distributions. """ # we use the following notation s, zp for slope, zeropoint, append Err for # errors # CMR for CMR, Mag for fitMags, Col for fitCols sCMR = obsCMR['slope'] sCMRErr = obsCMR['slopeErr'] zpCMR = obsCMR['intercept'] zpCMRErr = obsCMR['interceptErr'] sMag = fitMags['slope'] sMagErr = fitMags['slopeError'] zpMag = fitMags['intercept'] zpMagErr = fitMags['interceptError'] sCol = fitCols['slope'] sColErr = fitCols['slopeError'] zpCol = fitCols['intercept'] zpColErr = fitCols['interceptError'] bsFitResults = [] for n in range(BOOTSTRAPS): bsCMR = {} bsMag = {} bsCol = {} bsCMR['slope'] = random.normalvariate(sCMR, sCMRErr) bsCMR['intercept'] = random.normalvariate(zpCMR, zpCMRErr) bsCMR['zeroMag'] = obsCMR['zeroMag'] bsMag['slope'] = random.normalvariate(sMag, sMagErr) bsMag['intercept'] = random.normalvariate(zpMag, zpMagErr) bsCol['slope'] = random.normalvariate(sCol, sColErr) bsCol['intercept'] = random.normalvariate(zpCol, zpColErr) bsCMR['scatter'] = random.normalvariate(obsCMR['scatter'], obsCMR['scatterErr']) bsCMR['transformedZeroMag'] = obsCMR['transformedZeroMag'] bsFitResults.append(CalcTransformedCMRWithZM(bsCMR, bsMag, bsCol)) bsSlopes = [] bsIntercepts = [] bsScatters = [] for bsResult in bsFitResults: bsSlopes.append(bsResult['slope']) bsIntercepts.append(bsResult['intercept']) bsScatters.append(bsResult['scatter']) bsSlopes = numpy.array(bsSlopes) bsIntercepts = numpy.array(bsIntercepts) bsScatters = numpy.array(bsScatters) restCMRSlopeErr = numpy.std(bsSlopes) restCMRInterceptErr = numpy.std(bsIntercepts) restCMRScatterErr = numpy.std(bsScatters) return ({'slopeErr': restCMRSlopeErr, 'interceptErr':restCMRInterceptErr, 'scatterErr': restCMRScatterErr}) #----------------------------------------------------------------------------- def LoadModels(fileNameList, modelType = "bc03"): """Creates a list of stellar population models from the given list of model file names. """ models = [] for f in fileNameList: if modelType == "bc03": models.append(astSED.BC03Model(f)) elif modelType == "m05": models.append(astSED.M05Model(f)) return models #----------------------------------------------------------------------------- def GetPassbandFileNames(inputColour): """Given a mag (e.g. i775) or colour string e.g. r625-z850, lookup the appropriate file name(s) in the filterMap, and return the paths in a list. """ bands = inputColour.split("-") p = [] for b in bands: p.append(None) for row in filterMap: for i in range(len(bands)): if row['shortName'] == bands[i]: p[i]=row['filePath'] if None in p: print("ERROR : couldn't parse colour using filterMap") sys.exit() else: return p #----------------------------------------------------------------------------- def LoadPassbands(fileNameList, redshift = None, redshiftPassbands = False): """Creates a list of passband objects from the given list of passband file names. """ passbands = [] for f in fileNameList: p = astSED.Passband(f) if redshiftPassbands == True and redshift != None: p.wavelength=p.wavelength*(1.0+redshift) passbands.append(p) return passbands #----------------------------------------------------------------------------- def CalcColourMagTransformation(cmr, restColPassbands, restMagPassband): """Calculates the transformation equations needed to convert the given cmr into the rest frame at Coma, for the given passbands. """ print((">>> Calculating colour, mag transform for CMR " + litCMR['name']+"...")) inputColour = cmr['colour'] inputMag = cmr['mag'] zCluster = cmr['redshift'] # Range of formation zs to match Mei et al. 2008 zfMax = 7.0 zfMin = 2.0 observedColPassbandFileNames = GetPassbandFileNames(inputColour) observedMagPassbandFileName = GetPassbandFileNames(inputMag) observedColLabel = inputColour observedMagLabel = inputMag # Load stuff observedColPassbands = LoadPassbands(observedColPassbandFileNames) observedMagPassband = LoadPassbands(observedMagPassbandFileName)[0] # Generate galaxy models, we'll hold them all in memory here and use them # all in a bit print("--> Generating simulated galaxy sample ...") restGalaxies = [] observedGalaxies = [] for n in range(NGAL): print("... n = "+str(n+1)+"/"+str(NGAL)+" ...") zfChoice = random.uniform(zfMin, zfMax) ageChoice = astCalc.tl(zfChoice)-astCalc.tl(zCluster) for i in range(len(models)): modelChoice = i restGalaxies.append(models[modelChoice].getSED(ageChoice, z=0.02)) observedGalaxies.append(models[modelChoice].getSED(ageChoice, z=zCluster)) # Fit for colour conversion observedColours = [] restColours = [] for o, r in zip(observedGalaxies, restGalaxies): restColours.append(r.calcColour(restColPassbands[0], restColPassbands[1], magType="Vega")) observedColours.append(o.calcColour(observedColPassbands[0], observedColPassbands[1], magType=cmr['magType'])) restColours = numpy.array(restColours) observedColours = numpy.array(observedColours) fitColData = [] for x, y in zip(observedColours, restColours): fitColData.append([x, y]) fitCols=astStats.OLSFit(fitColData) res = restColours-(fitCols['slope']*observedColours+fitCols['intercept']) # scatter of residuals, use as fit error scatter = astStats.biweightScale(res, 6.0) # Fit for mag conversion restMinusObservedAppMags = [] for o, r, obsCol, restCol in zip(observedGalaxies, restGalaxies, observedColours, restColours): restMinusObservedAppMags.append(r.calcMag(restMagPassband, magType="Vega")-o.calcMag(observedMagPassband, magType=cmr['magType'])) restMinusObservedAppMags = numpy.array(restMinusObservedAppMags) fitMagData = [] for x, y in zip(observedColours, restMinusObservedAppMags): fitMagData.append([x, y]) fitMags = astStats.OLSFit(fitMagData) trans = {'name': cmr['name'], 'fitCols': fitCols, 'fitMags': fitMags, 'observedColours': observedColours, 'restColours': restColours, 'restMinusObservedAppMags': restMinusObservedAppMags} return trans #----------------------------------------------------------------------------- def GetCSPModel(labelToFind, models, modelLabels): """Given a list of models and a matching list of labels, returns the model matching the given label. """ foundModel = None for m, l in zip(models, modelLabels): if l == labelToFind: foundModel = m return foundModel #----------------------------------------------------------------------------- def ApplyCMRTransformation(cmr, trans): """Applies the magnitude and colour transformations stored in trans to the CMR. """ print((">>> Transforming CMR "+cmr['name']+" to Coma rest frame"+ restColour+" ...")) # Check that col, mag transformations and cmrs match up, otherwise # something is seriously screwed up if cmr['name'] != trans['name']: print("ERROR: cmrs and transformation lists not paired!") sys.exit() fitMags = trans['fitMags'] fitCols = trans['fitCols'] transformedCMR = CalcTransformedCMRWithZM(cmr, fitMags, fitCols) transformedCMRErrs = BootstrapTransformedCMRErrorsWithZM(cmr, fitMags, fitCols) result = {'name': cmr['name'], 'redshift': cmr['redshift'], 'colour': restColour, 'mag': restMag, 'slope': transformedCMR['slope'], 'slopeErr': transformedCMRErrs['slopeErr'], 'intercept': transformedCMR['intercept'], 'interceptErr': transformedCMRErrs['interceptErr'], 'zeroMag': cmr['transformedZeroMag'], 'scatter': transformedCMR['scatter'], 'scatterErr': transformedCMRErrs['scatterErr']} return result #----------------------------------------------------------------------------- # Main # Input parameters MODEL_TYPE="bc03" modelFileNames = ["../../../testingData/models/tau0p1Gyr_m42.20", "../../../testingData/models/tau0p1Gyr_m52.20", "../../../testingData/models/tau0p1Gyr_m62.20", "../../../testingData/models/tau0p1Gyr_m72.20"] models = LoadModels(modelFileNames, modelType = MODEL_TYPE) # Target colour and mag bands restColPassbandFileNames = [FILTER_DIR+"U_Johnson.res", FILTER_DIR+"B_Johnson.res"] restMagPassbandFileName = [FILTER_DIR+"B_Johnson.res"] restColour = "U-B" # component of output file name restMag = "B" restColLabel = "(U-B)rest" restMagLabel = "B" restColPassbands = LoadPassbands(restColPassbandFileNames) restMagPassband = LoadPassbands(restMagPassbandFileName)[0] # Evaluate CMR zero point in the rest frame of Coma at intercept of zero for litCMR in litCMRs: litCMR['transformedZeroMag'] = 0.0 # Calculate the colour, mag transformations to take each CMR to the Coma rest frame transformations = [] for litCMR in litCMRs: trans = CalcColourMagTransformation(litCMR, restColPassbands, restMagPassband) transformations.append(trans) # Transform the literature CMRs to the rest frame passbands at Coma results = [] for litCMR, trans in zip(litCMRs, transformations): result = ApplyCMRTransformation(litCMR, trans) results.append(result) # Write results to a text file outFile = open("output_CMRRestConversion.txt", "w") # Colour, mag transformation outFile.write("# Color, mag %s rest frame transformation fit coeffs:\n" % (restColour)) for t in transformations: outFile.write("name = %s\n" % (t['name'])) outFile.write("# Color transformation:\n") outFile.write("slope = %.5f\n" % (t['fitCols']['slope'])) outFile.write("slopeError = %.5f\n" % (t['fitCols']['slopeError'])) outFile.write("intercept = %.5f\n" % (t['fitCols']['intercept'])) outFile.write("interceptError = %.5f\n" % (t['fitCols']['interceptError'])) outFile.write("# Mag transformation:\n") outFile.write("slope = %.5f\n" % (t['fitMags']['slope'])) outFile.write("slopeError = %.5f\n" % (t['fitMags']['slopeError'])) outFile.write("intercept = %.5f\n" % (t['fitMags']['intercept'])) outFile.write("interceptError = %.5f\n" % (t['fitMags']['interceptError'])) # Transformed CMR outFile.write("# Transformed CMR:\n") keyOrder = ["name", "redshift", "colour", "mag", "zeroMag", "slope", "slopeErr", "intercept", "interceptErr", "scatter", "scatterErr"] for r in results: for k in keyOrder: for key in list(r.keys()): if str(key) == k: if type(r[key]) == str: outFile.write("%s = %s\n" % (key, r[key])) else: outFile.write("%s = %.3f\n" % (key, float(r[key]))) outFile.close() astLib-0.10.0/examples/NEDQueryPlot/0000775000175000017500000000000013247150772017447 5ustar mattymatty00000000000000astLib-0.10.0/examples/NEDQueryPlot/NEDQueryPlot.py0000664000175000017500000001372713246706754022334 0ustar mattymatty00000000000000#!/usr/bin/python #File: NEDQueryPlot/NEDQueryPlot.py #Created: Sat Dec 15 17:16:16 2012 #Last Change: Sat Dec 15 17:23:11 2012 # -*- coding: utf-8 -*- # # Fetches DSS image at a given position from Skyview, makes a plot listing NED # matches found in image #----------------------------------------------------------------------------- import sys import os import math try: from urllib.request import urlretrieve except ImportError: from urllib import urlretrieve from astLib import * import astropy.io.fits as pyfits import pylab #----------------------------------------------------------------------------- def queryNED(RAMin, RAMax, decMin, decMax): """Queries NED, returns list of objects. RAMin, RAMax, decMin, decMax, all in degrees """ # Just galaxies, groups urlretrieve("http://nedwww.ipac.caltech.edu/cgi-bin/nph-allsky?ra_constraint=Between&ra_1=%.6fd&ra_2=%.6fd&dec_constraint=Between&dec_1=%.6fd&dec_2=%.6fd&glon_constraint=Unconstrained&glon_1=&glon_2=&glat_constraint=Unconstrained&glat_1=&glat_2=&hconst=73&omegam=0.27&omegav=0.73&corr_z=1&z_constraint=Unconstrained&z_value1=&z_value2=&z_unit=z&flux_constraint=Unconstrained&flux_value1=&flux_value2=&flux_unit=Jy&frat_constraint=Unconstrained&ot_include=ANY&in_objtypes1=GGroups&in_objtypes1=Galaxies&nmp_op=ANY&out_csys=Equatorial&out_equinox=J2000.0&obj_sort=RA+or+Longitude&of=ascii_tab&zv_breaker=30000.0&list_limit=5&img_stamp=YES" % (RAMin, RAMax, decMin, decMax), "result.txt") inFile = open("result.txt", "r") lines = inFile.readlines() dataStarted = False labels = [] names = [] RAs = [] decs = [] sourceTypes = [] redshifts = [] for line in lines: bits = line.split("\t") if bits[0] == "1": dataStarted = True if dataStarted == True: labels.append(bits[0]) names.append(bits[1]) RAs.append(float(bits[2])) decs.append(float(bits[3])) sourceTypes.append(str(bits[4])) if bits[6] == '': redshifts.append('N/A') else: redshifts.append(str(bits[6])) return ({'labels': labels, 'names': names, 'RAs': RAs, 'decs': decs, 'sourceTypes': sourceTypes, 'redshifts': redshifts}) #------------------------------------------------------------------------- # Main # Query NED at this position - it's Stephan's quintet RADeg = 338.98963 decDeg = 33.95991 name = "Stephan's Quintet" if os.path.exists("fitsImages") == False: os.makedirs("fitsImages") fitsFolder = "fitsImages" outImageName = name.replace(" ", "_")+".png" outFITS = name.replace(" ", "_")+".fits" print("... fetching image from skyview ...") if os.path.exists(fitsFolder+os.path.sep+outFITS) == True: os.remove(fitsFolder+os.path.sep+outFITS) urlretrieve("http://skyview.gsfc.nasa.gov/cgi-bin/images?Position="+str(RADeg)+","+str(decDeg)+"&Size=0.1&Pixels=1000&Projection=Tan&Grid=J2000&Survey=digitized+sky+survey&Coordinates=J2000&Return=fits", fitsFolder+os.path.sep+outFITS) img = pyfits.open(fitsFolder+os.path.sep+outFITS) wcs = astWCS.WCS(fitsFolder+os.path.sep+outFITS) imgData = img[0].data RAMin, RAMax, decMin, decMax=wcs.getImageMinMaxWCSCoords() objs = queryNED(RAMin, RAMax, decMin, decMax) fig = pylab.figure(figsize=(10,14)) pylab.figtext(0.5, 0.96, name, fontsize=20, horizontalalignment='center') pylab.figtext(0.5, 0.94, "R.A, Dec. (J2000) = %s, %s" % (astCoords.decimal2hms(RADeg, ":"), astCoords.decimal2dms(decDeg, ":")), fontsize=14, horizontalalignment='center') plot = astPlots.ImagePlot(imgData, wcs, cutLevels=[2000,7000], axes=[0.125, 0.425, 0.8, 0.5]) plot.addPlotObjects([RADeg], [decDeg], 'actPosition', symbol='cross', color='cyan', size=8.0) pylab.figtext(0.125, 0.35, "NED Matches:", fontweight='bold', fontsize=16) pylab.figtext(0.125, 0.325, "ID", fontsize=14, horizontalalignment='left', verticalalignment='baseline', fontweight='bold') pylab.figtext(0.16, 0.325, "Name", fontsize=14, horizontalalignment='left', verticalalignment='baseline', fontweight='bold') pylab.figtext(0.42, 0.325, "R.A. (deg.)", fontsize=14, horizontalalignment='left', verticalalignment='baseline', fontweight='bold') pylab.figtext(0.57, 0.325, "Dec. (deg.)", fontsize=14, horizontalalignment='left', verticalalignment='baseline', fontweight='bold') pylab.figtext(0.72, 0.325, "Type", fontsize=14, horizontalalignment='left', verticalalignment='baseline', fontweight='bold') pylab.figtext(0.8, 0.325, "Redshift", fontsize=14, horizontalalignment='left', verticalalignment='baseline', fontweight='bold') rowSpacing=0.02 if len(objs['RAs']) > 0: plot.addPlotObjects(objs['RAs'], objs['decs'], 'nedObjects', objLabels=objs['labels'], size=8.0) for i in range(len(objs['RAs'])): pylab.figtext(0.125, 0.32-(i+1)*rowSpacing, objs['labels'][i], fontsize=10, horizontalalignment='left', verticalalignment='baseline') pylab.figtext(0.16, 0.32-(i+1)*rowSpacing, objs['names'][i], fontsize=10, horizontalalignment='left', verticalalignment='baseline') pylab.figtext(0.42, 0.32-(i+1)*rowSpacing, "%.6f" % objs['RAs'][i], fontsize=10, horizontalalignment='left', verticalalignment='baseline') pylab.figtext(0.57, 0.32-(i+1)*rowSpacing, "%.6f" % objs['decs'][i], fontsize=10, horizontalalignment='left', verticalalignment='baseline') pylab.figtext(0.72, 0.32-(i+1)*rowSpacing, objs['sourceTypes'][i], fontsize=10, horizontalalignment='left', verticalalignment='baseline') pylab.figtext(0.8, 0.32-(i+1)*rowSpacing, objs['redshifts'][i], fontsize=10, horizontalalignment='left', verticalalignment='baseline') else: pylab.figtext(0.5, 0.32-rowSpacing, 'No matches found', fontsize=10, fontstyle='italic', horizontalalignment='center', verticalalignment='baseline') plot.draw() plot.save(outImageName) pylab.close() img.close() astLib-0.10.0/examples/rgbTest/0000775000175000017500000000000013247150772016566 5ustar mattymatty00000000000000astLib-0.10.0/examples/rgbTest/rgbTest.py0000664000175000017500000000445313246706754020566 0ustar mattymatty00000000000000#!/usr/bin/env python #File: rgbTest/rgbTest.py #Created: Sat Dec 15 17:29:50 2012 #Last Change: Sat Dec 15 17:35:08 2012 # -*- coding: utf-8 -*- # # Example RGB ImagePlot with objects marked and a contour overlay import numpy import astropy.io.fits as pyfits import pylab from astLib import * # Load in list of objects to plot - a tab-delimited text file in format id, ra, dec, group sRAs = [] sDecs = [] sLabels = [] pRAs = [] pDecs = [] pLabels = [] inFile = open("../../../testingData/testData.csv", "r") lines = inFile.readlines() for line in lines: if line[0] != "#": bits = line.split() label = bits[0] ra = float(bits[1]) dec = float(bits[2]) group = int(bits[3]) if group == 1: sLabels.append(label) sRAs.append(ra) sDecs.append(dec) elif group == 2: pLabels.append(label) pRAs.append(ra) pDecs.append(dec) inFile.close() # Load the images - these have to be aligned to pixel and same pixel dimensions rimg = pyfits.open("../../../testingData/testImageR.fits") gimg = pyfits.open("../../../testingData/testImageG.fits") bimg = pyfits.open("../../../testingData/testImageB.fits") wcs = astWCS.WCS("../../../testingData/testImageR.fits") r = rimg[0].data g = gimg[0].data b = bimg[0].data rCut = [-50, 1000] gCut = [-50, 1000] bCut = [-50, 800] ximg = pyfits.open("../../../testingData/testXRayImage.fits") xwcs = astWCS.WCS("../../../testingData/testXRayImage.fits") x = ximg[0].data cLevels = [2e-05, 2.517e-05, 3.16764e-05, 3.98647e-05, 5.01697e-05, 6.31385e-05, 7.94597e-05, 0.0001] # Make the figure - this is a big, high-res version pylab.figure(figsize=(20,20)) p = astPlots.ImagePlot([r, g, b], wcs, cutLevels = [rCut, gCut, bCut], axesLabels="sexagesimal", axesFontSize=26.0, axes = [0.12,0.12,0.8,0.8]) p.addContourOverlay(x, xwcs, 'xmm-contours', levels=cLevels, smooth=5.0) p.addPlotObjects(sRAs, sDecs, 'spec-members', objLabels=sLabels, symbol="circle", color="cyan", width=2.0, size=2.0, objLabelSize=12.0) p.addPlotObjects(pRAs, pDecs, 'phot-members', objLabels=pLabels, symbol="box", color="yellow", width=2.0, size=2.0, objLabelSize=12.0) # Add a compass because we can p.addCompass("SW", 10, width=50.0, fontSize=30.0) p.draw() p.save("output_rgbTest.png") astLib-0.10.0/examples/scaleTest/0000775000175000017500000000000013247150772017103 5ustar mattymatty00000000000000astLib-0.10.0/examples/scaleTest/scaleTest.py0000664000175000017500000000114213247150353021375 0ustar mattymatty00000000000000#!/usr/bin/env python #File: scaleTest/scaleTest.py #Created: Sat Dec 15 17:15:17 2012 #Last Change: Sat Dec 15 17:15:56 2012 # -*- coding: utf-8 -*- # # Test of image scaling from astLib import * import astropy.io.fits as pyfits TEST_IMAGE = "../../../testingData/testImage1.fits" img = pyfits.open(TEST_IMAGE) wcs = astWCS.WCS(TEST_IMAGE) d = img[0].data scaled = astImages.scaleImage(d, wcs, 0.55) astImages.saveFITS("output_scaleTest.fits", scaled['data'], scaled['wcs']) scaledUp = astImages.scaleImage(d, wcs, 1.43) astImages.saveFITS("output_scaleTest_up.fits", scaledUp['data'], scaledUp['wcs']) astLib-0.10.0/examples/contourTest/0000775000175000017500000000000013247150772017505 5ustar mattymatty00000000000000astLib-0.10.0/examples/contourTest/contourTest.py0000664000175000017500000000147213246706754022422 0ustar mattymatty00000000000000#!/usr/bin/env python #File: contourTest/contourTest.py #Created: Sat Dec 15 17:04:57 2012 #Last Change: Sat Dec 15 17:05:29 2012 # -*- coding: utf-8 -*- # # Test of contour plot import astropy.io.fits as pyfits from astLib import * import pylab import numpy TEST_IMAGE = "../../../testingData/testImage2.fits" TEST_CONTOUR_IMAGE = "../../../testingData/testXRayImage.fits" img = pyfits.open(TEST_IMAGE) wcs = astWCS.WCS(TEST_IMAGE) d = img[0].data ximg = pyfits.open(TEST_CONTOUR_IMAGE) xwcs = astWCS.WCS(TEST_CONTOUR_IMAGE) xd = ximg[0].data f = astPlots.ImagePlot(d, wcs, axesLabels='decimal') cLevels = ['log', numpy.median(xd.flatten()), xd.max(), 10] f.addContourOverlay(xd, xwcs, 'xmm', levels=cLevels, smooth=5.0, color='cyan', width=1, highAccuracy=False) f.draw() f.save("output_contourTest.png") astLib-0.10.0/examples/MStarEvolution/0000775000175000017500000000000013247150772020107 5ustar mattymatty00000000000000astLib-0.10.0/examples/MStarEvolution/MStarEvolution.py0000664000175000017500000000232013047255533023410 0ustar mattymatty00000000000000#!/usr/bin/env python #File: MStarEvolution/MStarEvolution.py #Created: Sat Dec 15 17:06:36 2012 #Last Change: Sat Dec 15 17:08:15 2012 # -*- coding: utf-8 -*- # # Calculates evolution of the characteristic magnitude M* in the galaxy # luminosity function, in the K band, normalised using De Propris et al. 1999 # (not fitted), and overplots data from astLib import astSED import numpy import pylab bc03 = astSED.BC03Model("../../../testingData/models/tau0p1Gyr_m62.1") K = astSED.Passband("../../../testingData/filters/K_2MASS.res") DP99Mags = [14.84, 15.16, 15.64, 15.74, 16.50, 16.38, 16.85, 17.57, 17.51, 18.05] DP99zs = [0.15, 0.20, 0.25, 0.32, 0.40, 0.46, 0.54, 0.61, 0.79, 0.9] pylab.plot(DP99zs, DP99Mags, 'ro', label='DP1999') magTrack2 = bc03.getMagEvolution(K, 15.74, 0.32, 2.0, zStepSize=0.1, onePlusZSteps=True) magTrack5 = bc03.getMagEvolution(K, 15.74, 0.32, 5.0, zStepSize=0.1, onePlusZSteps=True) pylab.plot(magTrack2['z'], magTrack2['mag'], 'b--', label='zf=2.0') pylab.plot(magTrack5['z'], magTrack5['mag'], 'r--', label='zf=5.0') pylab.xlim(0, 2) pylab.ylim(13, 22) pylab.xlabel('redshift') pylab.ylabel('Ks (Vega)') pylab.legend() pylab.savefig("magEvo.png") astLib-0.10.0/examples/rotatedClipTest/0000775000175000017500000000000013247150772020266 5ustar mattymatty00000000000000astLib-0.10.0/examples/rotatedClipTest/rotatedClipTest.py0000664000175000017500000000145213246706754023762 0ustar mattymatty00000000000000#!/usr/bin/env python #File: rotatedClipTest/rotatedClipTest.py #Created: Sat Dec 15 17:05:45 2012 #Last Change: Sat Dec 15 17:06:28 2012 # -*- coding: utf-8 -*- # # Quick script to test out rotation, clipping import astropy.io.fits as pyfits from astLib import * img = pyfits.open("../../../testingData/testImage1.fits") wcs = astWCS.WCS("../../../testingData/testImage1.fits") d = img[0].data # Clip slightly off centre RADeg, decDeg = wcs.getCentreWCSCoords() RADeg = RADeg+1.2/60.0 decDeg = decDeg-1.0/60.0 clip = astImages.clipRotatedImageSectionWCS(d, wcs, RADeg, decDeg, 3.0/60.0) clipnr = astImages.clipImageSectionWCS(d, wcs, RADeg, decDeg, 3.0/60.0) astImages.saveFITS("output_rotated.fits", clip['data'], clip['wcs']) astImages.saveFITS("output_notRotated.fits", clipnr['data'], clipnr['wcs']) astLib-0.10.0/examples/coordConvert/0000775000175000017500000000000013247150772017623 5ustar mattymatty00000000000000astLib-0.10.0/examples/coordConvert/coordConvert.py0000644000175000017500000000470613047255533022650 0ustar mattymatty00000000000000#!/usr/bin/python #File: coordConvert/coordConvert.py #Created: Sat Dec 15 17:08:26 2012 #Last Change: Sat Dec 15 17:15:07 2012 # -*- coding: utf-8 -*- # # Converts file fed in into hms, dms format # from astLib import astCoords import sys # Main if len(sys.argv) < 8: print ("Run: % coordConvert.py ") else: inFile = sys.argv[1] outFile = sys.argv[2] RACol = int(sys.argv[3])-1 decCol = int(sys.argv[4])-1 way = sys.argv[5] delimiter = sys.argv[6] colDelim = str(sys.argv[7]).rstrip("\n") if colDelim == "tab": colDelim = "\t" wayOk = False if way == "to_decimal": wayOk = True if way == "to_hmsdms": wayOk = True if wayOk == False: print(": either \"to_decimal\" or \"to_hmsdms\"") sys.exit() reader = open(inFile, "r") lines = reader.readlines() reader.close() writer = open(outFile, "w") for row in lines: if len(row)>1: if "#" not in row[:1]: rowBits = row.split("\t") if way == "to_decimal": RADeg = astCoords.hms2decimal(rowBits[RACol], delimiter) decDeg = astCoords.dms2decimal(rowBits[decCol], delimiter) if way == "to_hmsdms": RADeg = astCoords.decimal2hms(float(rowBits[RACol]), delimiter) decDeg = astCoords.decimal2dms(float(rowBits[decCol]), delimiter) writeString = "" for i in range(len(rowBits)): if i == RACol: writeString = writeString+str(RADeg)+"\t" elif i == decCol: writeString = writeString+str(decDeg)+"\t" elif rowBits[i].find("\n") != -1: writeString = writeString+str(rowBits[i]) else: writeString = writeString+str(rowBits[i])+"\t" # new line character already included writer.write(writeString.replace("\n", "").replace("\t", colDelim)+"\n") else: writer.write(row.replace("\t", colDelim)) writer.close() #----------------------------------------------------------------------------- astLib-0.10.0/README0000664000175000017500000001371713246706754014235 0ustar mattymatty00000000000000astLib: python astronomy modules version: 0.10.0 (c) 2007-2012 Matt Hilton (c) 2013-2018 Matt Hilton & Steven Boada http://astlib.sourceforge.net email: matt.hilton@mykolab.com ------------------------------------------------------------------------------------------------------------- INTRODUCTION astLib provides some tools for research astronomers who use Python. It is divided into several modules: - astCalc (general calculations, e.g. luminosity distance etc.) - astCoords (coordinate conversions etc.) - astImages (clip sections from .fits etc.) - astPlots (provides a flexible image plot class, e.g. plot image with catalogue objects overlaid) - astSED (calculate colours, magnitudes from stellar population models or spectral templates, fit photometric observations using stellar population models etc.) - astStats (statistics, e.g. biweight location/scale estimators etc.) - astWCS (routines for using FITS World Coordinate System information) The astWCS module is a higher level interface to PyWCSTools, a simple SWIG (http://www.swig.org) wrapping of some of the routines from WCSTools by Jessica Mink (http://tdc-www.harvard.edu/software/wcstools/). It is used by some routines in astCoords, astImages and astPlots. The goal of astLib is to provide features useful to astronomers that are not included in the scipy (http://scipy.org), numpy (http://numpy.scipy.org) or matplotlib (http://matplotlib.sourceforge.net) modules on which astLib depends. For a more extensive set of python astronomy modules, see astropy (http://www.astropy.org/). Some scripts using astLib can be found in the examples/ folder in this archive. ------------------------------------------------------------------------------------------------------------- INSTALLATION astLib 0.10.0 requires: * Python (tested on versions 2.7.12+) * Astropy - http://www.astropy.org (tested on version 2.0.4) * numpy - http://numpy.scipy.org (tested on version 1.14.1) * scipy - http://scipy.org (tested on version 0.18.1) * matplotlib - http://matplotlib.sourceforge.net (tested on version 2.1.0) From astLib 0.10.0, pyfits is no longer supported, as STScI have depreciated it. If you still require pyfits instead of Astropy, please continue to use astLib 0.9.3. optional: * Python Imaging Library - http://www.pythonware.com/products/pil (tested on version 1.1.7) Other versions of the software listed above are likely to work - I'm unable to test every possible combination. For reference, astLib is currently developed on KDE neon/Ubuntu 16.04 (x86_64). Note that it is possible to use some astLib functions (such as the astWCS module) without installing all of the python modules listed above. To install astLib system wide (and build and install PyWCSTools), simply: % sudo python setup.py install in the directory this README is in. If you do not have root access to your machine, astLib can be installed in your home directory by doing the following: % python setup.py install --prefix=$HOME/python-modules and adding something like the following to your .bashrc (or equivalent): export PYTHONPATH=$PYTHONPATH:$HOME/python-modules/lib/python2.7/site-packages ------------------------------------------------------------------------------------------------------------- USAGE To access the routines in the astLib modules, simply: % from astLib import astCalc % from astLib import astCoords % from astLib import astWCS etc. The astWCS module currently provides access to what are (I think) the most commonly needed WCS information and functions (such as converting between pixel and WCS coordinates etc.). However, should you wish to access the wrapped WCSTools routines themselves directly: % from PyWCSTools import wcs % from PyWCSTools import wcscon etc. Note that PyWCSTools only includes some functions from wcs.c and wcscon.c at present. For examples of usage, look at the Python code for the astLib.astWCS module. Documentation for the WCSTools routines can be found here: http://tdc-www.harvard.edu/software/wcstools/subroutines/libwcs.wcs.html. ------------------------------------------------------------------------------------------------------------- KNOWN ISSUES This may no longer apply, but just in case... Recent versions of matplotlib (on which astLib depends) now use locale information. On systems where the decimal point separator is not '.' (e.g. Germany), the astWCS coordinate conversions routines will give strange results if this is not accounted for. As of version 0.3.0, the astWCS module will detect if this is the case and print a warning message to the console. The workaround for this issue is to add the following after importing any python modules that expicitly set the locale (such as matplotlib): % import locale % locale.setlocale(locale.LC_NUMERIC, 'C')" Thanks to Markus Demleitner for pointing this out. ------------------------------------------------------------------------------------------------------------- DOCUMENTATION Documentation is available on the web at: http://astlib.sourceforge.net/?q=docs0.7 The API reference documentation (generated using epydoc) is also supplied in HTML format in this archive under the docs/astLib/ directory. ------------------------------------------------------------------------------------------------------------- BUGS Please email bug reports to matt.hilton@mykolab.com, or alternatively use the bug tracker: http://sourceforge.net/p/astlib/bugs/ Please include details of your operating system, python version, and versions of the python packages required by astLib that you have installed on your machine. For any WCS-related bugs, it would be helpful if you could also include the image header as a text file so that I can reproduce them easily. ------------------------------------------------------------------------------------------------------------- astLib-0.10.0/setup.py0000664000175000017500000001014113246706754015053 0ustar mattymatty00000000000000# -*- coding: utf-8 -*- #File: setup.py #Created: Sat Dec 15 19:40:30 2012 #Last Change: Sat Dec 15 19:42:45 2012 import os import glob from distutils.core import setup from distutils.command.build_ext import build_ext from distutils.extension import Extension import distutils.ccompiler import distutils.command.config import distutils.sysconfig from pkg_resources import require topDir = os.getcwd() sourceDir = "PyWCSTools"+os.path.sep+"wcssubs-3.9.0"+os.path.sep #oFiles=glob.glob(sourceDir+"*.o") #print oFiles oFiles = ['PyWCSTools/wcssubs-3.9.0/cel.o', 'PyWCSTools/wcssubs-3.9.0/wcs.o', 'PyWCSTools/wcssubs-3.9.0/proj.o', 'PyWCSTools/wcssubs-3.9.0/distort.o', 'PyWCSTools/wcssubs-3.9.0/wcsinit.o', 'PyWCSTools/wcssubs-3.9.0/wcslib.o', 'PyWCSTools/wcssubs-3.9.0/poly.o', 'PyWCSTools/wcssubs-3.9.0/platepos.o', 'PyWCSTools/wcssubs-3.9.0/zpxpos.o', 'PyWCSTools/wcssubs-3.9.0/iget.o', 'PyWCSTools/wcssubs-3.9.0/imio.o', 'PyWCSTools/wcssubs-3.9.0/dsspos.o', 'PyWCSTools/wcssubs-3.9.0/tnxpos.o', 'PyWCSTools/wcssubs-3.9.0/wcscon.o', 'PyWCSTools/wcssubs-3.9.0/fitsfile.o', 'PyWCSTools/wcssubs-3.9.0/dateutil.o', 'PyWCSTools/wcssubs-3.9.0/imhfile.o', 'PyWCSTools/wcssubs-3.9.0/lin.o', 'PyWCSTools/wcssubs-3.9.0/fileutil.o', 'PyWCSTools/wcssubs-3.9.0/wcstrig.o', 'PyWCSTools/wcssubs-3.9.0/slasubs.o', 'PyWCSTools/wcssubs-3.9.0/sph.o', 'PyWCSTools/wcssubs-3.9.0/worldpos.o', 'PyWCSTools/wcssubs-3.9.0/hget.o', 'PyWCSTools/wcssubs-3.9.0/hput.o'] exampleScripts = glob.glob("scripts"+os.path.sep+"*.py") class build_PyWCSTools_ext(build_ext): def build_extensions(self): os.chdir(sourceDir) # This line is tough to make match the style guide cc =distutils.ccompiler.new_compiler( distutils.ccompiler.get_default_compiler()) distutils.command.config.customize_compiler(cc) # Suppress warnings from compiling WCSTools wcssubs-3.9.0 if "-Wstrict-prototypes" in cc.compiler_so: cc.compiler_so.pop(cc.compiler_so.index("-Wstrict-prototypes")) if "-Wall" in cc.compiler_so: cc.compiler_so.pop(cc.compiler_so.index("-Wall")) WCSToolsCFiles = glob.glob("*.c") WCSToolsCFiles.pop(WCSToolsCFiles.index("wcs_wrap.c")) WCSToolsCFiles.pop(WCSToolsCFiles.index("wcscon_wrap.c")) cc.compile(WCSToolsCFiles) os.chdir(topDir) build_ext.build_extensions(self) setup(name='astLib', version='0.10.0', url='http://astlib.sourceforge.net', download_url='http://sourceforge.net/project/platformdownload.php?group_id=202537', author='Matt Hilton', author_email='matt.hilton@mykolab.com', classifiers=['Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Natural Language :: English', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: Scientific/Engineering :: Astronomy', 'Topic :: Software Development :: Libraries'], description='A set of python modules for producing simple plots, statistics, common calculations, coordinate conversions, and manipulating FITS images with World Coordinate System (WCS) information.', long_description="""astLib is a set of Python modules that provides some tools for research astronomers. It can be used for simple plots, statistics, common calculations, coordinate conversions, and manipulating FITS images with World Coordinate System (WCS) information through PyWCSTools - a simple wrapping of WCSTools by Jessica Mink. PyWCSTools is distributed (and developed) as part of astLib.""", packages=['astLib', 'PyWCSTools'], package_data={'astLib': ['data/*']}, cmdclass={"build_ext": build_PyWCSTools_ext}, scripts=exampleScripts, ext_modules=[ Extension('PyWCSTools._wcscon', [sourceDir+"wcscon_wrap.c"], extra_objects=oFiles), Extension('PyWCSTools._wcs', [sourceDir+"wcs_wrap.c"], extra_objects=oFiles) ] ) astLib-0.10.0/PKG-INFO0000664000175000017500000000251413247150772014435 0ustar mattymatty00000000000000Metadata-Version: 1.1 Name: astLib Version: 0.10.0 Summary: A set of python modules for producing simple plots, statistics, common calculations, coordinate conversions, and manipulating FITS images with World Coordinate System (WCS) information. Home-page: http://astlib.sourceforge.net Author: Matt Hilton Author-email: matt.hilton@mykolab.com License: UNKNOWN Download-URL: http://sourceforge.net/project/platformdownload.php?group_id=202537 Description: astLib is a set of Python modules that provides some tools for research astronomers. It can be used for simple plots, statistics, common calculations, coordinate conversions, and manipulating FITS images with World Coordinate System (WCS) information through PyWCSTools - a simple wrapping of WCSTools by Jessica Mink. PyWCSTools is distributed (and developed) as part of astLib. Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Intended Audience :: Science/Research Classifier: License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL) Classifier: Natural Language :: English Classifier: Operating System :: POSIX Classifier: Programming Language :: Python Classifier: Topic :: Scientific/Engineering :: Astronomy Classifier: Topic :: Software Development :: Libraries astLib-0.10.0/CHANGE_LOG0000664000175000017500000001674413246706754014731 0ustar mattymatty00000000000000CHANGE LOG: VERSION 0.10.0 -------------- * No new features added; this version breaks compatibility with pyfits (which has been depreciated by STScI) and Astropy is now a requirement. If you still require a version that works with pyfits, please continue to use astLib 0.9.3. VERSION 0.9.0 ------------- * A bug fix release, primarily for compatibility with numpy 1.12+ and pyfits 3.4. No new features added. VERSION 0.8.0 ------------- * Upgraded underlying wcssubs to version 3.8.7, and added a bug fix for repeat runs of coord conversion encountered when using images with polynomial distortion coefficients (thanks to Ralf Kotulla; this error not reproduced on Kubuntu). * Some updates to avoid using deprecated features in pyfits (so now require pyfits 3.3 or astropy 0.4) and matplotlib. * Added zapKeywords option when creating WCS objects in astWCS - this can help in dealing with some malformed FITS headers (the usual culprits are COMMENT or HISTORY keywords with unprintable characters). * Fixed an index bug in MAD, median that affected biweightScale, biweightLocation calculations in astStats (small shift in values that ought to be insignificant in to any result that relies on the use of the biweight). * Some improvements in astCalc (using scipy for integration, tl2z and tz2z now throw exceptions for negative values). VERSION 0.7.0 ------------- * Python 2.6-3.2 now supported. * Fixed bug in effective wavelength calculation (1 per cent effect depending on band). * Changed h, m, s in image plot labels to non-italic. * Added choice of interpolation used in ImagePlot. * Added OmegaLz, OmegaRz, and updated Ez, Ez2 functions to account for radiation density. * Added shiftRADec function. * Added a workaround for bug in handling ZPN projections if PV2_3 == 0. * Updated astWCS to avoid using a depreciated function in pyfits 3.0+. VERSION 0.6.1 ------------- * Bug fix: doing e.g. 'from astLib import astWCS' no longer pulls in e.g. pylab from the other modules. VERSION 0.6.0 ------------- * Thanks to an upgrade of the WCSTools C-routines, WCSs with polynomial distortion coefficients (i.e. with PVi_j type header keywords) are now supported transparently (thanks to Wes Fraser for help with this). * Fixed bug with handling WCSs with SIP distortion coefficients (i.e. A_i_j, B_i_j type header keywords; thanks to L.W. Piotrowski for this one). * Fixed convergence bug in astCoords.calcRASearchBox() at high declination. * Fixed scalebar length bug and placement of scalebar and compass objects in plots should be much improved. VERSION 0.5.0 ------------- * astWCS.WCS.wcs2pix() now gracefully handles RA wraparounds in e.g. CEA images that cover > 180 degrees. * Added routines to convert from Jy <-> AB mag (Jy2Mag, mag2Jy) in astSED * Some miscellaneous bug fixes in astSED - renamed renormaliseToMag() -> normaliseToMag(), fixed BC03Model() to read galaxevpl files with arbitrary number of ages, force age > 0 in makeModelSEDDict() * Fixed bug parsing non-standard FITS headers in astWCS.WCS * Added more input unit options to astSED.Passband() * Added astCoords.calcRASearchBox() function (handy for freeform SQL queries of e.g. SDSS, UKIDSS) VERSION 0.4.0 ------------- * astPlots.ImagePlot now works under python 2.6 - this bug was related to the WCS <-> pixel coordinate conversion routines handling of numpy arrays (now fixed). * Fixed tick label bug in astPlots.ImagePlot around dec == +/- 00 degrees, when using sexagesimal labels (thanks Toby). * astCoords.calcAngSepDeg() now accepts and returns arrays - this makes it easy (and fast) to sort a bunch of objects by radial distance from some point. * Removed the astSED.SED.calcAbsMag(), astSED.SED.calcAppMag() functions and replaced with astSED.SED.calcMag(), with option to add distance modulus. * Fixed bug in flux calculation from SEDs. * Vega and AB SEDs are now in physical units. Added Sun (SOL) SED. * Can now apply Calzetti et al. (2000) extinction law to SED objects. * Rewritten, fast SED fitting code in astSED module. Several new related functions (flux2Mag(), mag2Flux() etc.) * Changed astImages.clipImageSectionWCS() and astImages.clipUsingRADecCoords() to additionally return the corresponding pixel coordinates in the parent image to the clipped section. VERSION 0.3.2 ------------- * Fixed bugs in NEDQueryPlot.py, MStarEvolution.py example scripts. * Fixed bug when handling HIERARCH keywords (thanks to Stefano). This also fixes bug when handling headers made by astrometry.net (I believe). * Added TopHatPassband class to astSED. * Changed so that PIL only imported in the couple of routines it is needed by (and got rid of annoying warning message when PIL not installed). * Fixed the occasional rounding error appearing in astPlot axis labelling. * Improved default y-axis scaling for astSED plotting function. Added SED integrate function. * Added astCalc.dVcdz() - calculates volume element for given cosmology and redshift. * Some updates in the astSED module to work with changes in scipy 0.7.x interpolation routines. * Fixed astImages.scaleImage() to work with CRDELTi keywords (thanks to Ben Keller for this). * Some code has been added towards fitting SEDs in the astSED module - this code is not fully tested yet (astSED.fitSEDDict()). VERSION 0.3.1 ------------- * Fixed bug in contour overlays so should now work on any image with any valid WCS that WCSTools understands. * Speeded up contour overlay generation significantly - can select a "high accuracy" mode that is similar to the old method. * Fixed bug when parsing FITS headers with extra long header cards (as can be found in e.g. headers of some Chandra images). Previously, these would cause the coordinate conversion routines to fail. * Added cross and diamond plot symbols to ImagePlot. * Added scale bar to ImagePlot. * Changes such as adding plot objects or contour overlays in ImagePlot now cause the plot to be redrawn - i.e. calling ImagePlot.draw after such changes is no longer necessary. * Rewritten coordinate axes labelling in ImagePlot - should now be much more robust, and automatically choose sensible tick steps. If it doesn't, it can now be overridden using the RATickSteps, decTickSteps parameters. Dropped option for minor tick marks for now. * Added clipUsingRADecCoords, resampleToTanProjection to astImages module. * Fixed bug in astCoords conversion from decimal to dms/hms: previously, sometimes seconds in dms/hms could equal 60.00 instead of 00.00. VERSION 0.3.0 ------------- * Added the astSED module. * Fixed bug in astImages.clipImageSectionWCS, where if returnWCS = False, didn't return data. * Added NUMPY_MODE to astWCS and enabled it by default (i.e., WCS pixel coordinates are now zero indexed). * Tidied up astImages clipping routines - now return dictionaries with keys 'data', 'wcs' (instead of 'clippedData', 'clippedWCS' as previously). Also, clipping routines can now clip rectangles if given a list in format [width, height]. * Removed astPlots finderChart, contourOverlayChart macros and replaced them with a new ImagePlot class. This has a much better, simpler but more flexible interface with several new features (e.g. overplotting objects with RA, dec. coords). * Now raising exceptions rather than printing error messages and exiting when things go wrong. * Added several new miscellaneous functions across the modules. * Added new example scripts. * Added a warning about potential locale problems for locales where decimal point separator is not '.'. astLib-0.10.0/PyWCSTools/0000775000175000017500000000000013247150772015324 5ustar mattymatty00000000000000astLib-0.10.0/PyWCSTools/__init__.py0000644000175000017500000000032013047255533017425 0ustar mattymatty00000000000000# PyWCSTools - a simple SWIG wrapping of WCSTools (http://tdc-www.harvard.edu/software/wcstools/) by Doug Mink # # (c) 2007, 2008 Matt Hilton # # See the README file for information on usage and distribution.astLib-0.10.0/PyWCSTools/wcscon.py0000644000175000017500000000445113047255533017173 0ustar mattymatty00000000000000# This file was automatically generated by SWIG (http://www.swig.org). # Version 2.0.7 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info if version_info >= (2,6,0): def swig_import_helper(): from os.path import dirname import imp fp = None try: fp, pathname, description = imp.find_module('_wcscon', [dirname(__file__)]) except ImportError: import _wcscon return _wcscon if fp is not None: try: _mod = imp.load_module('_wcscon', fp, pathname, description) finally: fp.close() return _mod _wcscon = swig_import_helper() del swig_import_helper else: import _wcscon del version_info try: _swig_property = property except NameError: pass # Python < 2.2 doesn't have 'property'. def _swig_setattr_nondynamic(self,class_type,name,value,static=1): if (name == "thisown"): return self.this.own(value) if (name == "this"): if type(value).__name__ == 'SwigPyObject': self.__dict__[name] = value return method = class_type.__swig_setmethods__.get(name,None) if method: return method(self,value) if (not static): self.__dict__[name] = value else: raise AttributeError("You cannot add attributes to %s" % self) def _swig_setattr(self,class_type,name,value): return _swig_setattr_nondynamic(self,class_type,name,value,0) def _swig_getattr(self,class_type,name): if (name == "thisown"): return self.this.own() method = class_type.__swig_getmethods__.get(name,None) if method: return method(self) raise AttributeError(name) def _swig_repr(self): try: strthis = "proxy of " + self.this.__repr__() except: strthis = "" return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) try: _object = object _newclass = 1 except AttributeError: class _object : pass _newclass = 0 def wcscon(*args): """wcscon(sys1, sys2, eq1, eq2, INOUT, INOUT, epoch)""" return _wcscon.wcscon(*args) def wcscsys(*args): """wcscsys(wcstring) -> int""" return _wcscon.wcscsys(*args) # This file is compatible with both classic and new-style classes. astLib-0.10.0/PyWCSTools/wcs.py0000644000175000017500000006372313047255533016502 0ustar mattymatty00000000000000# This file was automatically generated by SWIG (http://www.swig.org). # Version 2.0.7 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info if version_info >= (2,6,0): def swig_import_helper(): from os.path import dirname import imp fp = None try: fp, pathname, description = imp.find_module('_wcs', [dirname(__file__)]) except ImportError: import _wcs return _wcs if fp is not None: try: _mod = imp.load_module('_wcs', fp, pathname, description) finally: fp.close() return _mod _wcs = swig_import_helper() del swig_import_helper else: import _wcs del version_info try: _swig_property = property except NameError: pass # Python < 2.2 doesn't have 'property'. def _swig_setattr_nondynamic(self,class_type,name,value,static=1): if (name == "thisown"): return self.this.own(value) if (name == "this"): if type(value).__name__ == 'SwigPyObject': self.__dict__[name] = value return method = class_type.__swig_setmethods__.get(name,None) if method: return method(self,value) if (not static): self.__dict__[name] = value else: raise AttributeError("You cannot add attributes to %s" % self) def _swig_setattr(self,class_type,name,value): return _swig_setattr_nondynamic(self,class_type,name,value,0) def _swig_getattr(self,class_type,name): if (name == "thisown"): return self.this.own() method = class_type.__swig_getmethods__.get(name,None) if method: return method(self) raise AttributeError(name) def _swig_repr(self): try: strthis = "proxy of " + self.this.__repr__() except: strthis = "" return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) try: _object = object _newclass = 1 except AttributeError: class _object : pass _newclass = 0 def new_doubleArray(*args): """new_doubleArray(nelements) -> double *""" return _wcs.new_doubleArray(*args) def delete_doubleArray(*args): """delete_doubleArray(ary)""" return _wcs.delete_doubleArray(*args) def doubleArray_getitem(*args): """doubleArray_getitem(ary, index) -> double""" return _wcs.doubleArray_getitem(*args) def doubleArray_setitem(*args): """doubleArray_setitem(ary, index, value)""" return _wcs.doubleArray_setitem(*args) def wcsinit(*args): """wcsinit(hstring) -> WorldCoor""" return _wcs.wcsinit(*args) def wcsxinit(*args): """wcsxinit(cra, cdec, secpix, xrpix, yrpix, nxpix, nypix, rotate, equinox, epoch, proj) -> WorldCoor""" return _wcs.wcsxinit(*args) def wcskinit(*args): """ wcskinit(nxpix, nypix, ctype1, ctype2, crpix1, crpix2, crval1, crval2, cd, cdelt1, cdelt2, crota, equinox, epoch) -> WorldCoor """ return _wcs.wcskinit(*args) def iswcs(*args): """iswcs(wcs) -> int""" return _wcs.iswcs(*args) def nowcs(*args): """nowcs(wcs) -> int""" return _wcs.nowcs(*args) def wcs2pix(*args): """wcs2pix(wcs, xpos, ypos)""" return _wcs.wcs2pix(*args) def pix2wcs(*args): """pix2wcs(wcs, xpix, ypix)""" return _wcs.pix2wcs(*args) def wcscent(*args): """wcscent(wcs)""" return _wcs.wcscent(*args) def getradecsys(*args): """getradecsys(wcs) -> char *""" return _wcs.getradecsys(*args) def wcsoutinit(*args): """wcsoutinit(wcs, coorsys)""" return _wcs.wcsoutinit(*args) def wcsininit(*args): """wcsininit(wcs, coorsys)""" return _wcs.wcsininit(*args) def getwcsout(*args): """getwcsout(wcs) -> char *""" return _wcs.getwcsout(*args) def getwcsin(*args): """getwcsin(wcs) -> char *""" return _wcs.getwcsin(*args) def wcssize(*args): """wcssize(wcs)""" return _wcs.wcssize(*args) def wcsfull(*args): """wcsfull(wcs)""" return _wcs.wcsfull(*args) class WorldCoor(_object): """Proxy of C WorldCoor struct""" __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, WorldCoor, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, WorldCoor, name) __repr__ = _swig_repr __swig_setmethods__["xref"] = _wcs.WorldCoor_xref_set __swig_getmethods__["xref"] = _wcs.WorldCoor_xref_get if _newclass:xref = _swig_property(_wcs.WorldCoor_xref_get, _wcs.WorldCoor_xref_set) __swig_setmethods__["yref"] = _wcs.WorldCoor_yref_set __swig_getmethods__["yref"] = _wcs.WorldCoor_yref_get if _newclass:yref = _swig_property(_wcs.WorldCoor_yref_get, _wcs.WorldCoor_yref_set) __swig_setmethods__["xrefpix"] = _wcs.WorldCoor_xrefpix_set __swig_getmethods__["xrefpix"] = _wcs.WorldCoor_xrefpix_get if _newclass:xrefpix = _swig_property(_wcs.WorldCoor_xrefpix_get, _wcs.WorldCoor_xrefpix_set) __swig_setmethods__["yrefpix"] = _wcs.WorldCoor_yrefpix_set __swig_getmethods__["yrefpix"] = _wcs.WorldCoor_yrefpix_get if _newclass:yrefpix = _swig_property(_wcs.WorldCoor_yrefpix_get, _wcs.WorldCoor_yrefpix_set) __swig_setmethods__["xinc"] = _wcs.WorldCoor_xinc_set __swig_getmethods__["xinc"] = _wcs.WorldCoor_xinc_get if _newclass:xinc = _swig_property(_wcs.WorldCoor_xinc_get, _wcs.WorldCoor_xinc_set) __swig_setmethods__["yinc"] = _wcs.WorldCoor_yinc_set __swig_getmethods__["yinc"] = _wcs.WorldCoor_yinc_get if _newclass:yinc = _swig_property(_wcs.WorldCoor_yinc_get, _wcs.WorldCoor_yinc_set) __swig_setmethods__["rot"] = _wcs.WorldCoor_rot_set __swig_getmethods__["rot"] = _wcs.WorldCoor_rot_get if _newclass:rot = _swig_property(_wcs.WorldCoor_rot_get, _wcs.WorldCoor_rot_set) __swig_setmethods__["cd"] = _wcs.WorldCoor_cd_set __swig_getmethods__["cd"] = _wcs.WorldCoor_cd_get if _newclass:cd = _swig_property(_wcs.WorldCoor_cd_get, _wcs.WorldCoor_cd_set) __swig_setmethods__["dc"] = _wcs.WorldCoor_dc_set __swig_getmethods__["dc"] = _wcs.WorldCoor_dc_get if _newclass:dc = _swig_property(_wcs.WorldCoor_dc_get, _wcs.WorldCoor_dc_set) __swig_setmethods__["equinox"] = _wcs.WorldCoor_equinox_set __swig_getmethods__["equinox"] = _wcs.WorldCoor_equinox_get if _newclass:equinox = _swig_property(_wcs.WorldCoor_equinox_get, _wcs.WorldCoor_equinox_set) __swig_setmethods__["epoch"] = _wcs.WorldCoor_epoch_set __swig_getmethods__["epoch"] = _wcs.WorldCoor_epoch_get if _newclass:epoch = _swig_property(_wcs.WorldCoor_epoch_get, _wcs.WorldCoor_epoch_set) __swig_setmethods__["nxpix"] = _wcs.WorldCoor_nxpix_set __swig_getmethods__["nxpix"] = _wcs.WorldCoor_nxpix_get if _newclass:nxpix = _swig_property(_wcs.WorldCoor_nxpix_get, _wcs.WorldCoor_nxpix_set) __swig_setmethods__["nypix"] = _wcs.WorldCoor_nypix_set __swig_getmethods__["nypix"] = _wcs.WorldCoor_nypix_get if _newclass:nypix = _swig_property(_wcs.WorldCoor_nypix_get, _wcs.WorldCoor_nypix_set) __swig_setmethods__["plate_ra"] = _wcs.WorldCoor_plate_ra_set __swig_getmethods__["plate_ra"] = _wcs.WorldCoor_plate_ra_get if _newclass:plate_ra = _swig_property(_wcs.WorldCoor_plate_ra_get, _wcs.WorldCoor_plate_ra_set) __swig_setmethods__["plate_dec"] = _wcs.WorldCoor_plate_dec_set __swig_getmethods__["plate_dec"] = _wcs.WorldCoor_plate_dec_get if _newclass:plate_dec = _swig_property(_wcs.WorldCoor_plate_dec_get, _wcs.WorldCoor_plate_dec_set) __swig_setmethods__["plate_scale"] = _wcs.WorldCoor_plate_scale_set __swig_getmethods__["plate_scale"] = _wcs.WorldCoor_plate_scale_get if _newclass:plate_scale = _swig_property(_wcs.WorldCoor_plate_scale_get, _wcs.WorldCoor_plate_scale_set) __swig_setmethods__["x_pixel_offset"] = _wcs.WorldCoor_x_pixel_offset_set __swig_getmethods__["x_pixel_offset"] = _wcs.WorldCoor_x_pixel_offset_get if _newclass:x_pixel_offset = _swig_property(_wcs.WorldCoor_x_pixel_offset_get, _wcs.WorldCoor_x_pixel_offset_set) __swig_setmethods__["y_pixel_offset"] = _wcs.WorldCoor_y_pixel_offset_set __swig_getmethods__["y_pixel_offset"] = _wcs.WorldCoor_y_pixel_offset_get if _newclass:y_pixel_offset = _swig_property(_wcs.WorldCoor_y_pixel_offset_get, _wcs.WorldCoor_y_pixel_offset_set) __swig_setmethods__["x_pixel_size"] = _wcs.WorldCoor_x_pixel_size_set __swig_getmethods__["x_pixel_size"] = _wcs.WorldCoor_x_pixel_size_get if _newclass:x_pixel_size = _swig_property(_wcs.WorldCoor_x_pixel_size_get, _wcs.WorldCoor_x_pixel_size_set) __swig_setmethods__["y_pixel_size"] = _wcs.WorldCoor_y_pixel_size_set __swig_getmethods__["y_pixel_size"] = _wcs.WorldCoor_y_pixel_size_get if _newclass:y_pixel_size = _swig_property(_wcs.WorldCoor_y_pixel_size_get, _wcs.WorldCoor_y_pixel_size_set) __swig_setmethods__["ppo_coeff"] = _wcs.WorldCoor_ppo_coeff_set __swig_getmethods__["ppo_coeff"] = _wcs.WorldCoor_ppo_coeff_get if _newclass:ppo_coeff = _swig_property(_wcs.WorldCoor_ppo_coeff_get, _wcs.WorldCoor_ppo_coeff_set) __swig_setmethods__["x_coeff"] = _wcs.WorldCoor_x_coeff_set __swig_getmethods__["x_coeff"] = _wcs.WorldCoor_x_coeff_get if _newclass:x_coeff = _swig_property(_wcs.WorldCoor_x_coeff_get, _wcs.WorldCoor_x_coeff_set) __swig_setmethods__["y_coeff"] = _wcs.WorldCoor_y_coeff_set __swig_getmethods__["y_coeff"] = _wcs.WorldCoor_y_coeff_get if _newclass:y_coeff = _swig_property(_wcs.WorldCoor_y_coeff_get, _wcs.WorldCoor_y_coeff_set) __swig_setmethods__["xpix"] = _wcs.WorldCoor_xpix_set __swig_getmethods__["xpix"] = _wcs.WorldCoor_xpix_get if _newclass:xpix = _swig_property(_wcs.WorldCoor_xpix_get, _wcs.WorldCoor_xpix_set) __swig_setmethods__["ypix"] = _wcs.WorldCoor_ypix_set __swig_getmethods__["ypix"] = _wcs.WorldCoor_ypix_get if _newclass:ypix = _swig_property(_wcs.WorldCoor_ypix_get, _wcs.WorldCoor_ypix_set) __swig_setmethods__["zpix"] = _wcs.WorldCoor_zpix_set __swig_getmethods__["zpix"] = _wcs.WorldCoor_zpix_get if _newclass:zpix = _swig_property(_wcs.WorldCoor_zpix_get, _wcs.WorldCoor_zpix_set) __swig_setmethods__["xpos"] = _wcs.WorldCoor_xpos_set __swig_getmethods__["xpos"] = _wcs.WorldCoor_xpos_get if _newclass:xpos = _swig_property(_wcs.WorldCoor_xpos_get, _wcs.WorldCoor_xpos_set) __swig_setmethods__["ypos"] = _wcs.WorldCoor_ypos_set __swig_getmethods__["ypos"] = _wcs.WorldCoor_ypos_get if _newclass:ypos = _swig_property(_wcs.WorldCoor_ypos_get, _wcs.WorldCoor_ypos_set) __swig_setmethods__["crpix"] = _wcs.WorldCoor_crpix_set __swig_getmethods__["crpix"] = _wcs.WorldCoor_crpix_get if _newclass:crpix = _swig_property(_wcs.WorldCoor_crpix_get, _wcs.WorldCoor_crpix_set) __swig_setmethods__["crval"] = _wcs.WorldCoor_crval_set __swig_getmethods__["crval"] = _wcs.WorldCoor_crval_get if _newclass:crval = _swig_property(_wcs.WorldCoor_crval_get, _wcs.WorldCoor_crval_set) __swig_setmethods__["cdelt"] = _wcs.WorldCoor_cdelt_set __swig_getmethods__["cdelt"] = _wcs.WorldCoor_cdelt_get if _newclass:cdelt = _swig_property(_wcs.WorldCoor_cdelt_get, _wcs.WorldCoor_cdelt_set) __swig_setmethods__["pc"] = _wcs.WorldCoor_pc_set __swig_getmethods__["pc"] = _wcs.WorldCoor_pc_get if _newclass:pc = _swig_property(_wcs.WorldCoor_pc_get, _wcs.WorldCoor_pc_set) __swig_setmethods__["projp"] = _wcs.WorldCoor_projp_set __swig_getmethods__["projp"] = _wcs.WorldCoor_projp_get if _newclass:projp = _swig_property(_wcs.WorldCoor_projp_get, _wcs.WorldCoor_projp_set) __swig_setmethods__["pvfail"] = _wcs.WorldCoor_pvfail_set __swig_getmethods__["pvfail"] = _wcs.WorldCoor_pvfail_get if _newclass:pvfail = _swig_property(_wcs.WorldCoor_pvfail_get, _wcs.WorldCoor_pvfail_set) __swig_setmethods__["projppv"] = _wcs.WorldCoor_projppv_set __swig_getmethods__["projppv"] = _wcs.WorldCoor_projppv_get if _newclass:projppv = _swig_property(_wcs.WorldCoor_projppv_get, _wcs.WorldCoor_projppv_set) __swig_setmethods__["inv_x"] = _wcs.WorldCoor_inv_x_set __swig_getmethods__["inv_x"] = _wcs.WorldCoor_inv_x_get if _newclass:inv_x = _swig_property(_wcs.WorldCoor_inv_x_get, _wcs.WorldCoor_inv_x_set) __swig_setmethods__["inv_y"] = _wcs.WorldCoor_inv_y_set __swig_getmethods__["inv_y"] = _wcs.WorldCoor_inv_y_get if _newclass:inv_y = _swig_property(_wcs.WorldCoor_inv_y_get, _wcs.WorldCoor_inv_y_set) __swig_setmethods__["longpole"] = _wcs.WorldCoor_longpole_set __swig_getmethods__["longpole"] = _wcs.WorldCoor_longpole_get if _newclass:longpole = _swig_property(_wcs.WorldCoor_longpole_get, _wcs.WorldCoor_longpole_set) __swig_setmethods__["latpole"] = _wcs.WorldCoor_latpole_set __swig_getmethods__["latpole"] = _wcs.WorldCoor_latpole_get if _newclass:latpole = _swig_property(_wcs.WorldCoor_latpole_get, _wcs.WorldCoor_latpole_set) __swig_setmethods__["rodeg"] = _wcs.WorldCoor_rodeg_set __swig_getmethods__["rodeg"] = _wcs.WorldCoor_rodeg_get if _newclass:rodeg = _swig_property(_wcs.WorldCoor_rodeg_get, _wcs.WorldCoor_rodeg_set) __swig_setmethods__["imrot"] = _wcs.WorldCoor_imrot_set __swig_getmethods__["imrot"] = _wcs.WorldCoor_imrot_get if _newclass:imrot = _swig_property(_wcs.WorldCoor_imrot_get, _wcs.WorldCoor_imrot_set) __swig_setmethods__["pa_north"] = _wcs.WorldCoor_pa_north_set __swig_getmethods__["pa_north"] = _wcs.WorldCoor_pa_north_get if _newclass:pa_north = _swig_property(_wcs.WorldCoor_pa_north_get, _wcs.WorldCoor_pa_north_set) __swig_setmethods__["pa_east"] = _wcs.WorldCoor_pa_east_set __swig_getmethods__["pa_east"] = _wcs.WorldCoor_pa_east_get if _newclass:pa_east = _swig_property(_wcs.WorldCoor_pa_east_get, _wcs.WorldCoor_pa_east_set) __swig_setmethods__["radvel"] = _wcs.WorldCoor_radvel_set __swig_getmethods__["radvel"] = _wcs.WorldCoor_radvel_get if _newclass:radvel = _swig_property(_wcs.WorldCoor_radvel_get, _wcs.WorldCoor_radvel_set) __swig_setmethods__["zvel"] = _wcs.WorldCoor_zvel_set __swig_getmethods__["zvel"] = _wcs.WorldCoor_zvel_get if _newclass:zvel = _swig_property(_wcs.WorldCoor_zvel_get, _wcs.WorldCoor_zvel_set) __swig_setmethods__["zpzd"] = _wcs.WorldCoor_zpzd_set __swig_getmethods__["zpzd"] = _wcs.WorldCoor_zpzd_get if _newclass:zpzd = _swig_property(_wcs.WorldCoor_zpzd_get, _wcs.WorldCoor_zpzd_set) __swig_setmethods__["zpr"] = _wcs.WorldCoor_zpr_set __swig_getmethods__["zpr"] = _wcs.WorldCoor_zpr_get if _newclass:zpr = _swig_property(_wcs.WorldCoor_zpr_get, _wcs.WorldCoor_zpr_set) __swig_setmethods__["imflip"] = _wcs.WorldCoor_imflip_set __swig_getmethods__["imflip"] = _wcs.WorldCoor_imflip_get if _newclass:imflip = _swig_property(_wcs.WorldCoor_imflip_get, _wcs.WorldCoor_imflip_set) __swig_setmethods__["prjcode"] = _wcs.WorldCoor_prjcode_set __swig_getmethods__["prjcode"] = _wcs.WorldCoor_prjcode_get if _newclass:prjcode = _swig_property(_wcs.WorldCoor_prjcode_get, _wcs.WorldCoor_prjcode_set) __swig_setmethods__["latbase"] = _wcs.WorldCoor_latbase_set __swig_getmethods__["latbase"] = _wcs.WorldCoor_latbase_get if _newclass:latbase = _swig_property(_wcs.WorldCoor_latbase_get, _wcs.WorldCoor_latbase_set) __swig_setmethods__["ncoeff1"] = _wcs.WorldCoor_ncoeff1_set __swig_getmethods__["ncoeff1"] = _wcs.WorldCoor_ncoeff1_get if _newclass:ncoeff1 = _swig_property(_wcs.WorldCoor_ncoeff1_get, _wcs.WorldCoor_ncoeff1_set) __swig_setmethods__["ncoeff2"] = _wcs.WorldCoor_ncoeff2_set __swig_getmethods__["ncoeff2"] = _wcs.WorldCoor_ncoeff2_get if _newclass:ncoeff2 = _swig_property(_wcs.WorldCoor_ncoeff2_get, _wcs.WorldCoor_ncoeff2_set) __swig_setmethods__["zpnp"] = _wcs.WorldCoor_zpnp_set __swig_getmethods__["zpnp"] = _wcs.WorldCoor_zpnp_get if _newclass:zpnp = _swig_property(_wcs.WorldCoor_zpnp_get, _wcs.WorldCoor_zpnp_set) __swig_setmethods__["changesys"] = _wcs.WorldCoor_changesys_set __swig_getmethods__["changesys"] = _wcs.WorldCoor_changesys_get if _newclass:changesys = _swig_property(_wcs.WorldCoor_changesys_get, _wcs.WorldCoor_changesys_set) __swig_setmethods__["printsys"] = _wcs.WorldCoor_printsys_set __swig_getmethods__["printsys"] = _wcs.WorldCoor_printsys_get if _newclass:printsys = _swig_property(_wcs.WorldCoor_printsys_get, _wcs.WorldCoor_printsys_set) __swig_setmethods__["ndec"] = _wcs.WorldCoor_ndec_set __swig_getmethods__["ndec"] = _wcs.WorldCoor_ndec_get if _newclass:ndec = _swig_property(_wcs.WorldCoor_ndec_get, _wcs.WorldCoor_ndec_set) __swig_setmethods__["degout"] = _wcs.WorldCoor_degout_set __swig_getmethods__["degout"] = _wcs.WorldCoor_degout_get if _newclass:degout = _swig_property(_wcs.WorldCoor_degout_get, _wcs.WorldCoor_degout_set) __swig_setmethods__["tabsys"] = _wcs.WorldCoor_tabsys_set __swig_getmethods__["tabsys"] = _wcs.WorldCoor_tabsys_get if _newclass:tabsys = _swig_property(_wcs.WorldCoor_tabsys_get, _wcs.WorldCoor_tabsys_set) __swig_setmethods__["rotmat"] = _wcs.WorldCoor_rotmat_set __swig_getmethods__["rotmat"] = _wcs.WorldCoor_rotmat_get if _newclass:rotmat = _swig_property(_wcs.WorldCoor_rotmat_get, _wcs.WorldCoor_rotmat_set) __swig_setmethods__["coorflip"] = _wcs.WorldCoor_coorflip_set __swig_getmethods__["coorflip"] = _wcs.WorldCoor_coorflip_get if _newclass:coorflip = _swig_property(_wcs.WorldCoor_coorflip_get, _wcs.WorldCoor_coorflip_set) __swig_setmethods__["offscl"] = _wcs.WorldCoor_offscl_set __swig_getmethods__["offscl"] = _wcs.WorldCoor_offscl_get if _newclass:offscl = _swig_property(_wcs.WorldCoor_offscl_get, _wcs.WorldCoor_offscl_set) __swig_setmethods__["wcson"] = _wcs.WorldCoor_wcson_set __swig_getmethods__["wcson"] = _wcs.WorldCoor_wcson_get if _newclass:wcson = _swig_property(_wcs.WorldCoor_wcson_get, _wcs.WorldCoor_wcson_set) __swig_setmethods__["naxis"] = _wcs.WorldCoor_naxis_set __swig_getmethods__["naxis"] = _wcs.WorldCoor_naxis_get if _newclass:naxis = _swig_property(_wcs.WorldCoor_naxis_get, _wcs.WorldCoor_naxis_set) __swig_setmethods__["naxes"] = _wcs.WorldCoor_naxes_set __swig_getmethods__["naxes"] = _wcs.WorldCoor_naxes_get if _newclass:naxes = _swig_property(_wcs.WorldCoor_naxes_get, _wcs.WorldCoor_naxes_set) __swig_setmethods__["wcsproj"] = _wcs.WorldCoor_wcsproj_set __swig_getmethods__["wcsproj"] = _wcs.WorldCoor_wcsproj_get if _newclass:wcsproj = _swig_property(_wcs.WorldCoor_wcsproj_get, _wcs.WorldCoor_wcsproj_set) __swig_setmethods__["linmode"] = _wcs.WorldCoor_linmode_set __swig_getmethods__["linmode"] = _wcs.WorldCoor_linmode_get if _newclass:linmode = _swig_property(_wcs.WorldCoor_linmode_get, _wcs.WorldCoor_linmode_set) __swig_setmethods__["detector"] = _wcs.WorldCoor_detector_set __swig_getmethods__["detector"] = _wcs.WorldCoor_detector_get if _newclass:detector = _swig_property(_wcs.WorldCoor_detector_get, _wcs.WorldCoor_detector_set) __swig_setmethods__["instrument"] = _wcs.WorldCoor_instrument_set __swig_getmethods__["instrument"] = _wcs.WorldCoor_instrument_get if _newclass:instrument = _swig_property(_wcs.WorldCoor_instrument_get, _wcs.WorldCoor_instrument_set) __swig_setmethods__["ctype"] = _wcs.WorldCoor_ctype_set __swig_getmethods__["ctype"] = _wcs.WorldCoor_ctype_get if _newclass:ctype = _swig_property(_wcs.WorldCoor_ctype_get, _wcs.WorldCoor_ctype_set) __swig_setmethods__["c1type"] = _wcs.WorldCoor_c1type_set __swig_getmethods__["c1type"] = _wcs.WorldCoor_c1type_get if _newclass:c1type = _swig_property(_wcs.WorldCoor_c1type_get, _wcs.WorldCoor_c1type_set) __swig_setmethods__["c2type"] = _wcs.WorldCoor_c2type_set __swig_getmethods__["c2type"] = _wcs.WorldCoor_c2type_get if _newclass:c2type = _swig_property(_wcs.WorldCoor_c2type_get, _wcs.WorldCoor_c2type_set) __swig_setmethods__["ptype"] = _wcs.WorldCoor_ptype_set __swig_getmethods__["ptype"] = _wcs.WorldCoor_ptype_get if _newclass:ptype = _swig_property(_wcs.WorldCoor_ptype_get, _wcs.WorldCoor_ptype_set) __swig_setmethods__["units"] = _wcs.WorldCoor_units_set __swig_getmethods__["units"] = _wcs.WorldCoor_units_get if _newclass:units = _swig_property(_wcs.WorldCoor_units_get, _wcs.WorldCoor_units_set) __swig_setmethods__["radecsys"] = _wcs.WorldCoor_radecsys_set __swig_getmethods__["radecsys"] = _wcs.WorldCoor_radecsys_get if _newclass:radecsys = _swig_property(_wcs.WorldCoor_radecsys_get, _wcs.WorldCoor_radecsys_set) __swig_setmethods__["radecout"] = _wcs.WorldCoor_radecout_set __swig_getmethods__["radecout"] = _wcs.WorldCoor_radecout_get if _newclass:radecout = _swig_property(_wcs.WorldCoor_radecout_get, _wcs.WorldCoor_radecout_set) __swig_setmethods__["radecin"] = _wcs.WorldCoor_radecin_set __swig_getmethods__["radecin"] = _wcs.WorldCoor_radecin_get if _newclass:radecin = _swig_property(_wcs.WorldCoor_radecin_get, _wcs.WorldCoor_radecin_set) __swig_setmethods__["eqin"] = _wcs.WorldCoor_eqin_set __swig_getmethods__["eqin"] = _wcs.WorldCoor_eqin_get if _newclass:eqin = _swig_property(_wcs.WorldCoor_eqin_get, _wcs.WorldCoor_eqin_set) __swig_setmethods__["eqout"] = _wcs.WorldCoor_eqout_set __swig_getmethods__["eqout"] = _wcs.WorldCoor_eqout_get if _newclass:eqout = _swig_property(_wcs.WorldCoor_eqout_get, _wcs.WorldCoor_eqout_set) __swig_setmethods__["sysin"] = _wcs.WorldCoor_sysin_set __swig_getmethods__["sysin"] = _wcs.WorldCoor_sysin_get if _newclass:sysin = _swig_property(_wcs.WorldCoor_sysin_get, _wcs.WorldCoor_sysin_set) __swig_setmethods__["syswcs"] = _wcs.WorldCoor_syswcs_set __swig_getmethods__["syswcs"] = _wcs.WorldCoor_syswcs_get if _newclass:syswcs = _swig_property(_wcs.WorldCoor_syswcs_get, _wcs.WorldCoor_syswcs_set) __swig_setmethods__["sysout"] = _wcs.WorldCoor_sysout_set __swig_getmethods__["sysout"] = _wcs.WorldCoor_sysout_get if _newclass:sysout = _swig_property(_wcs.WorldCoor_sysout_get, _wcs.WorldCoor_sysout_set) __swig_setmethods__["center"] = _wcs.WorldCoor_center_set __swig_getmethods__["center"] = _wcs.WorldCoor_center_get if _newclass:center = _swig_property(_wcs.WorldCoor_center_get, _wcs.WorldCoor_center_set) __swig_setmethods__["wcsl"] = _wcs.WorldCoor_wcsl_set __swig_getmethods__["wcsl"] = _wcs.WorldCoor_wcsl_get if _newclass:wcsl = _swig_property(_wcs.WorldCoor_wcsl_get, _wcs.WorldCoor_wcsl_set) __swig_setmethods__["lin"] = _wcs.WorldCoor_lin_set __swig_getmethods__["lin"] = _wcs.WorldCoor_lin_get if _newclass:lin = _swig_property(_wcs.WorldCoor_lin_get, _wcs.WorldCoor_lin_set) __swig_setmethods__["cel"] = _wcs.WorldCoor_cel_set __swig_getmethods__["cel"] = _wcs.WorldCoor_cel_get if _newclass:cel = _swig_property(_wcs.WorldCoor_cel_get, _wcs.WorldCoor_cel_set) __swig_setmethods__["prj"] = _wcs.WorldCoor_prj_set __swig_getmethods__["prj"] = _wcs.WorldCoor_prj_get if _newclass:prj = _swig_property(_wcs.WorldCoor_prj_get, _wcs.WorldCoor_prj_set) __swig_setmethods__["lngcor"] = _wcs.WorldCoor_lngcor_set __swig_getmethods__["lngcor"] = _wcs.WorldCoor_lngcor_get if _newclass:lngcor = _swig_property(_wcs.WorldCoor_lngcor_get, _wcs.WorldCoor_lngcor_set) __swig_setmethods__["latcor"] = _wcs.WorldCoor_latcor_set __swig_getmethods__["latcor"] = _wcs.WorldCoor_latcor_get if _newclass:latcor = _swig_property(_wcs.WorldCoor_latcor_get, _wcs.WorldCoor_latcor_set) __swig_setmethods__["distcode"] = _wcs.WorldCoor_distcode_set __swig_getmethods__["distcode"] = _wcs.WorldCoor_distcode_get if _newclass:distcode = _swig_property(_wcs.WorldCoor_distcode_get, _wcs.WorldCoor_distcode_set) __swig_setmethods__["distort"] = _wcs.WorldCoor_distort_set __swig_getmethods__["distort"] = _wcs.WorldCoor_distort_get if _newclass:distort = _swig_property(_wcs.WorldCoor_distort_get, _wcs.WorldCoor_distort_set) __swig_setmethods__["command_format"] = _wcs.WorldCoor_command_format_set __swig_getmethods__["command_format"] = _wcs.WorldCoor_command_format_get if _newclass:command_format = _swig_property(_wcs.WorldCoor_command_format_get, _wcs.WorldCoor_command_format_set) __swig_setmethods__["ltm"] = _wcs.WorldCoor_ltm_set __swig_getmethods__["ltm"] = _wcs.WorldCoor_ltm_get if _newclass:ltm = _swig_property(_wcs.WorldCoor_ltm_get, _wcs.WorldCoor_ltm_set) __swig_setmethods__["ltv"] = _wcs.WorldCoor_ltv_set __swig_getmethods__["ltv"] = _wcs.WorldCoor_ltv_get if _newclass:ltv = _swig_property(_wcs.WorldCoor_ltv_get, _wcs.WorldCoor_ltv_set) __swig_setmethods__["idpix"] = _wcs.WorldCoor_idpix_set __swig_getmethods__["idpix"] = _wcs.WorldCoor_idpix_get if _newclass:idpix = _swig_property(_wcs.WorldCoor_idpix_get, _wcs.WorldCoor_idpix_set) __swig_setmethods__["ndpix"] = _wcs.WorldCoor_ndpix_set __swig_getmethods__["ndpix"] = _wcs.WorldCoor_ndpix_get if _newclass:ndpix = _swig_property(_wcs.WorldCoor_ndpix_get, _wcs.WorldCoor_ndpix_set) __swig_setmethods__["wcs"] = _wcs.WorldCoor_wcs_set __swig_getmethods__["wcs"] = _wcs.WorldCoor_wcs_get if _newclass:wcs = _swig_property(_wcs.WorldCoor_wcs_get, _wcs.WorldCoor_wcs_set) __swig_setmethods__["wcsdep"] = _wcs.WorldCoor_wcsdep_set __swig_getmethods__["wcsdep"] = _wcs.WorldCoor_wcsdep_get if _newclass:wcsdep = _swig_property(_wcs.WorldCoor_wcsdep_get, _wcs.WorldCoor_wcsdep_set) __swig_setmethods__["wcsname"] = _wcs.WorldCoor_wcsname_set __swig_getmethods__["wcsname"] = _wcs.WorldCoor_wcsname_get if _newclass:wcsname = _swig_property(_wcs.WorldCoor_wcsname_get, _wcs.WorldCoor_wcsname_set) __swig_setmethods__["wcschar"] = _wcs.WorldCoor_wcschar_set __swig_getmethods__["wcschar"] = _wcs.WorldCoor_wcschar_get if _newclass:wcschar = _swig_property(_wcs.WorldCoor_wcschar_get, _wcs.WorldCoor_wcschar_set) __swig_setmethods__["logwcs"] = _wcs.WorldCoor_logwcs_set __swig_getmethods__["logwcs"] = _wcs.WorldCoor_logwcs_get if _newclass:logwcs = _swig_property(_wcs.WorldCoor_logwcs_get, _wcs.WorldCoor_logwcs_set) def __init__(self): """__init__(self) -> WorldCoor""" this = _wcs.new_WorldCoor() try: self.this.append(this) except: self.this = this __swig_destroy__ = _wcs.delete_WorldCoor __del__ = lambda self : None; WorldCoor_swigregister = _wcs.WorldCoor_swigregister WorldCoor_swigregister(WorldCoor) # This file is compatible with both classic and new-style classes. astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/0000775000175000017500000000000013247150772017462 5ustar mattymatty00000000000000astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/proj.c0000664000175000017500000030565313047255533020613 0ustar mattymatty00000000000000/*============================================================================ * * WCSLIB - an implementation of the FITS WCS proposal. * Copyright (C) 1995-2002, Mark Calabretta * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Correspondence concerning WCSLIB may be directed to: * Internet email: mcalabre@atnf.csiro.au * Postal address: Dr. Mark Calabretta, * Australia Telescope National Facility, * P.O. Box 76, * Epping, NSW, 2121, * AUSTRALIA * *============================================================================= * * C implementation of the spherical map projections recognized by the FITS * "World Coordinate System" (WCS) convention. * * Summary of routines * ------------------- * Each projection is implemented via separate functions for the forward, * *fwd(), and reverse, *rev(), transformation. * * Initialization routines, *set(), compute intermediate values from the * projection parameters but need not be called explicitly - see the * explanation of prj.flag below. * * prjset prjfwd prjrev Driver routines (see below). * * azpset azpfwd azprev AZP: zenithal/azimuthal perspective * szpset szpfwd szprev SZP: slant zenithal perspective * tanset tanfwd tanrev TAN: gnomonic * stgset stgfwd stgrev STG: stereographic * sinset sinfwd sinrev SIN: orthographic/synthesis * arcset arcfwd arcrev ARC: zenithal/azimuthal equidistant * zpnset zpnfwd zpnrev ZPN: zenithal/azimuthal polynomial * zeaset zeafwd zearev ZEA: zenithal/azimuthal equal area * airset airfwd airrev AIR: Airy * cypset cypfwd cyprev CYP: cylindrical perspective * ceaset ceafwd cearev CEA: cylindrical equal area * carset carfwd carrev CAR: Cartesian * merset merfwd merrev MER: Mercator * sflset sflfwd sflrev SFL: Sanson-Flamsteed * parset parfwd parrev PAR: parabolic * molset molfwd molrev MOL: Mollweide * aitset aitfwd aitrev AIT: Hammer-Aitoff * copset copfwd coprev COP: conic perspective * coeset coefwd coerev COE: conic equal area * codset codfwd codrev COD: conic equidistant * cooset coofwd coorev COO: conic orthomorphic * bonset bonfwd bonrev BON: Bonne * pcoset pcofwd pcorev PCO: polyconic * tscset tscfwd tscrev TSC: tangential spherical cube * cscset cscfwd cscrev CSC: COBE quadrilateralized spherical cube * qscset qscfwd qscrev QSC: quadrilateralized spherical cube * * * Driver routines; prjset(), prjfwd() & prjrev() * ---------------------------------------------- * A set of driver routines are available for use as a generic interface to * the specific projection routines. The interfaces to prjfwd() and prjrev() * are the same as those of the forward and reverse transformation routines * for the specific projections (see below). * * The interface to prjset() differs slightly from that of the initialization * routines for the specific projections and unlike them it must be invoked * explicitly to use prjfwd() and prjrev(). * * Given: * pcode[4] const char * WCS projection code. * * Given and/or returned: * prj prjprm* Projection parameters (see below). * * Function return value: * int Error status * 0: Success. * * * Initialization routine; *set() * ------------------------------ * Initializes members of a prjprm data structure which hold intermediate * values. Note that this routine need not be called directly; it will be * invoked by prjfwd() and prjrev() if the "flag" structure member is * anything other than a predefined magic value. * * Given and/or returned: * prj prjprm* Projection parameters (see below). * * Function return value: * int Error status * 0: Success. * 1: Invalid projection parameters. * * Forward transformation; *fwd() * ----------------------------- * Compute (x,y) coordinates in the plane of projection from native spherical * coordinates (phi,theta). * * Given: * phi, const double * theta Longitude and latitude of the projected point in * native spherical coordinates, in degrees. * * Given and returned: * prj prjprm* Projection parameters (see below). * * Returned: * x,y double* Projected coordinates. * * Function return value: * int Error status * 0: Success. * 1: Invalid projection parameters. * 2: Invalid value of (phi,theta). * * Reverse transformation; *rev() * ----------------------------- * Compute native spherical coordinates (phi,theta) from (x,y) coordinates in * the plane of projection. * * Given: * x,y const double * Projected coordinates. * * Given and returned: * prj prjprm* Projection parameters (see below). * * Returned: * phi, double* Longitude and latitude of the projected point in * theta native spherical coordinates, in degrees. * * Function return value: * int Error status * 0: Success. * 1: Invalid projection parameters. * 2: Invalid value of (x,y). * 1: Invalid projection parameters. * * Projection parameters * --------------------- * The prjprm struct consists of the following: * * int flag * This flag must be set to zero whenever any of p[10] or r0 are set * or changed. This signals the initialization routine to recompute * intermediaries. flag may also be set to -1 to disable strict bounds * checking for the AZP, SZP, TAN, SIN, ZPN, and COP projections. * * double r0 * r0; The radius of the generating sphere for the projection, a linear * scaling parameter. If this is zero, it will be reset to the default * value of 180/pi (the value for FITS WCS). * * double p[10] * The first 10 elements contain projection parameters which correspond * to the PROJPn keywords in FITS, so p[0] is PROJP0, and p[9] is * PROJP9. Many projections use p[1] (PROJP1) and some also use p[2] * (PROJP2). ZPN is the only projection which uses any of the others. * * The remaining members of the prjprm struct are maintained by the * initialization routines and should not be modified. This is done for the * sake of efficiency and to allow an arbitrary number of contexts to be * maintained simultaneously. * * char code[4] * Three-letter projection code. * * double phi0, theta0 * Native longitude and latitude of the reference point, in degrees. * * double w[10] * int n * Intermediate values derived from the projection parameters. * * int (*prjfwd)() * int (*prjrev)() * Pointers to the forward and reverse projection routines. * * Usage of the p[] array as it applies to each projection is described in * the prologue to each trio of projection routines. * * Argument checking * ----------------- * Forward routines: * * The values of phi and theta (the native longitude and latitude) * normally lie in the range [-180,180] for phi, and [-90,90] for theta. * However, all forward projections will accept any value of phi and will * not normalize it. * * The forward projection routines do not explicitly check that theta lies * within the range [-90,90]. They do check for any value of theta which * produces an invalid argument to the projection equations (e.g. leading * to division by zero). The forward routines for AZP, SZP, TAN, SIN, * ZPN, and COP also return error 2 if (phi,theta) corresponds to the * overlapped (far) side of the projection but also return the * corresponding value of (x,y). This strict bounds checking may be * relaxed by setting prj->flag to -1 (rather than 0) when these * projections are initialized. * * Reverse routines: * * Error checking on the projected coordinates (x,y) is limited to that * required to ascertain whether a solution exists. Where a solution does * exist no check is made that the value of phi and theta obtained lie * within the ranges [-180,180] for phi, and [-90,90] for theta. * * Accuracy * -------- * Closure to a precision of at least 1E-10 degree of longitude and latitude * has been verified for typical projection parameters on the 1 degree grid * of native longitude and latitude (to within 5 degrees of any latitude * where the projection may diverge). * * Author: Mark Calabretta, Australia Telescope National Facility * $Id: proj.c,v 2.20 2002/04/03 01:25:29 mcalabre Exp $ *===========================================================================*/ #include #include #include #include "wcslib.h" int npcode = 26; char pcodes[26][4] = {"AZP", "SZP", "TAN", "STG", "SIN", "ARC", "ZPN", "ZEA", "AIR", "CYP", "CEA", "CAR", "MER", "COP", "COE", "COD", "COO", "SFL", "PAR", "MOL", "AIT", "BON", "PCO", "TSC", "CSC", "QSC"}; const int AZP = 101; const int SZP = 102; const int TAN = 103; const int STG = 104; const int SIN = 105; const int ARC = 106; const int ZPN = 107; const int ZEA = 108; const int AIR = 109; const int CYP = 201; const int CEA = 202; const int CAR = 203; const int MER = 204; const int SFL = 301; const int PAR = 302; const int MOL = 303; const int AIT = 401; const int COP = 501; const int COE = 502; const int COD = 503; const int COO = 504; const int BON = 601; const int PCO = 602; const int TSC = 701; const int CSC = 702; const int QSC = 703; /* Map error number to error message for each function. */ const char *prjset_errmsg[] = { 0, "Invalid projection parameters"}; const char *prjfwd_errmsg[] = { 0, "Invalid projection parameters", "Invalid value of (phi,theta)"}; const char *prjrev_errmsg[] = { 0, "Invalid projection parameters", "Invalid value of (x,y)"}; #define copysgn(X, Y) ((Y) < 0.0 ? -fabs(X) : fabs(X)) #define copysgni(X, Y) ((Y) < 0 ? -abs(X) : abs(X)) /*==========================================================================*/ int prjset(pcode, prj) const char pcode[4]; struct prjprm *prj; { /* Set pointers to the forward and reverse projection routines. */ if (strcmp(pcode, "AZP") == 0) { azpset(prj); } else if (strcmp(pcode, "SZP") == 0) { szpset(prj); } else if (strcmp(pcode, "TAN") == 0) { tanset(prj); } else if (strcmp(pcode, "STG") == 0) { stgset(prj); } else if (strcmp(pcode, "SIN") == 0) { sinset(prj); } else if (strcmp(pcode, "ARC") == 0) { arcset(prj); } else if (strcmp(pcode, "ZPN") == 0) { zpnset(prj); } else if (strcmp(pcode, "ZEA") == 0) { zeaset(prj); } else if (strcmp(pcode, "AIR") == 0) { airset(prj); } else if (strcmp(pcode, "CYP") == 0) { cypset(prj); } else if (strcmp(pcode, "CEA") == 0) { ceaset(prj); } else if (strcmp(pcode, "CAR") == 0) { carset(prj); } else if (strcmp(pcode, "MER") == 0) { merset(prj); } else if (strcmp(pcode, "SFL") == 0) { sflset(prj); } else if (strcmp(pcode, "PAR") == 0) { parset(prj); } else if (strcmp(pcode, "MOL") == 0) { molset(prj); } else if (strcmp(pcode, "AIT") == 0) { aitset(prj); } else if (strcmp(pcode, "COP") == 0) { copset(prj); } else if (strcmp(pcode, "COE") == 0) { coeset(prj); } else if (strcmp(pcode, "COD") == 0) { codset(prj); } else if (strcmp(pcode, "COO") == 0) { cooset(prj); } else if (strcmp(pcode, "BON") == 0) { bonset(prj); } else if (strcmp(pcode, "PCO") == 0) { pcoset(prj); } else if (strcmp(pcode, "TSC") == 0) { tscset(prj); } else if (strcmp(pcode, "CSC") == 0) { cscset(prj); } else if (strcmp(pcode, "QSC") == 0) { qscset(prj); } else { /* Unrecognized projection code. */ return 1; } return 0; } /*--------------------------------------------------------------------------*/ int prjfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { return prj->prjfwd(phi, theta, prj, x, y); } /*--------------------------------------------------------------------------*/ int prjrev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { return prj->prjrev(x, y, prj, phi, theta); } /*============================================================================ * AZP: zenithal/azimuthal perspective projection. * * Given: * prj->p[1] Distance parameter, mu in units of r0. * prj->p[2] Tilt angle, gamma in degrees. * * Given and/or returned: * prj->flag AZP, or -AZP if prj->flag is given < 0. * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "AZP" * prj->phi0 0.0 * prj->theta0 90.0 * prj->w[0] r0*(mu+1) * prj->w[1] tan(gamma) * prj->w[2] sec(gamma) * prj->w[3] cos(gamma) * prj->w[4] sin(gamma) * prj->w[5] asin(-1/mu) for |mu| >= 1, -90 otherwise * prj->w[6] mu*cos(gamma) * prj->w[7] 1 if |mu*cos(gamma)| < 1, 0 otherwise * prj->prjfwd Pointer to azpfwd(). * prj->prjrev Pointer to azprev(). *===========================================================================*/ int azpset(prj) struct prjprm *prj; { strcpy(prj->code, "AZP"); prj->flag = copysgni (AZP, prj->flag); prj->phi0 = 0.0; prj->theta0 = 90.0; if (prj->r0 == 0.0) prj->r0 = R2D; prj->w[0] = prj->r0*(prj->p[1] + 1.0); if (prj->w[0] == 0.0) { return 1; } prj->w[3] = cosdeg (prj->p[2]); if (prj->w[3] == 0.0) { return 1; } prj->w[2] = 1.0/prj->w[3]; prj->w[4] = sindeg (prj->p[2]); prj->w[1] = prj->w[4] / prj->w[3]; if (fabs(prj->p[1]) > 1.0) { prj->w[5] = asindeg (-1.0/prj->p[1]); } else { prj->w[5] = -90.0; } prj->w[6] = prj->p[1] * prj->w[3]; prj->w[7] = (fabs(prj->w[6]) < 1.0) ? 1.0 : 0.0; prj->prjfwd = azpfwd; prj->prjrev = azprev; return 0; } /*--------------------------------------------------------------------------*/ int azpfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { double a, b, cphi, cthe, r, s, t; if (abs(prj->flag) != AZP) { if (azpset(prj)) return 1; } cphi = cosdeg (phi); cthe = cosdeg (theta); s = prj->w[1]*cphi; t = (prj->p[1] + sindeg (theta)) + cthe*s; if (t == 0.0) { return 2; } r = prj->w[0]*cthe/t; *x = r*sindeg (phi); *y = -r*cphi*prj->w[2]; /* Bounds checking. */ if (prj->flag > 0) { /* Overlap. */ if (theta < prj->w[5]) { return 2; } /* Divergence. */ if (prj->w[7] > 0.0) { t = prj->p[1] / sqrt(1.0 + s*s); if (fabs(t) <= 1.0) { s = atandeg (-s); t = asindeg (t); a = s - t; b = s + t + 180.0; if (a > 90.0) a -= 360.0; if (b > 90.0) b -= 360.0; if (theta < ((a > b) ? a : b)) { return 2; } } } } return 0; } /*--------------------------------------------------------------------------*/ int azprev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { double a, b, r, s, t, ycosg; const double tol = 1.0e-13; if (abs(prj->flag) != AZP) { if (azpset(prj)) return 1; } ycosg = y*prj->w[3]; r = sqrt(x*x + ycosg*ycosg); if (r == 0.0) { *phi = 0.0; *theta = 90.0; } else { *phi = atan2deg (x, -ycosg); s = r / (prj->w[0] + y*prj->w[4]); t = s*prj->p[1]/sqrt(s*s + 1.0); s = atan2deg (1.0, s); if (fabs(t) > 1.0) { t = copysgn (90.0,t); if (fabs(t) > 1.0+tol) { return 2; } } else { t = asindeg (t); } a = s - t; b = s + t + 180.0; if (a > 90.0) a -= 360.0; if (b > 90.0) b -= 360.0; *theta = (a > b) ? a : b; } return 0; } /*============================================================================ * SZP: slant zenithal perspective projection. * * Given: * prj->p[1] Distance of the point of projection from the centre of the * generating sphere, mu in units of r0. * prj->p[2] Native longitude, phi_c, and ... * prj->p[3] Native latitude, theta_c, on the planewards side of the * intersection of the line through the point of projection * and the centre of the generating sphere, phi_c in degrees. * * Given and/or returned: * prj->flag SZP, or -SZP if prj->flag is given < 0. * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "SZP" * prj->phi0 0.0 * prj->theta0 90.0 * prj->w[0] 1/r0 * prj->w[1] xp = -mu*cos(theta_c)*sin(phi_c) * prj->w[2] yp = mu*cos(theta_c)*cos(phi_c) * prj->w[3] zp = mu*sin(theta_c) + 1 * prj->w[4] r0*xp * prj->w[5] r0*yp * prj->w[6] r0*zp * prj->w[7] (zp - 1)^2 * prj->w[8] asin(1-zp) if |1 - zp| < 1, -90 otherwise * prj->prjfwd Pointer to szpfwd(). * prj->prjrev Pointer to szprev(). *===========================================================================*/ int szpset(prj) struct prjprm *prj; { strcpy(prj->code, "SZP"); prj->flag = copysgni (SZP, prj->flag); prj->phi0 = 0.0; prj->theta0 = 90.0; if (prj->r0 == 0.0) prj->r0 = R2D; prj->w[0] = 1.0/prj->r0; prj->w[3] = prj->p[1] * sindeg (prj->p[3]) + 1.0; if (prj->w[3] == 0.0) { return 1; } prj->w[1] = -prj->p[1] * cosdeg (prj->p[3]) * sindeg (prj->p[2]); prj->w[2] = prj->p[1] * cosdeg (prj->p[3]) * cosdeg (prj->p[2]); prj->w[4] = prj->r0 * prj->w[1]; prj->w[5] = prj->r0 * prj->w[2]; prj->w[6] = prj->r0 * prj->w[3]; prj->w[7] = (prj->w[3] - 1.0) * prj->w[3] - 1.0; if (fabs(prj->w[3] - 1.0) < 1.0) { prj->w[8] = asindeg (1.0 - prj->w[3]); } else { prj->w[8] = -90.0; } prj->prjfwd = szpfwd; prj->prjrev = szprev; return 0; } /*--------------------------------------------------------------------------*/ int szpfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { double a, b, cphi, cthe, s, sphi, t; if (abs(prj->flag) != SZP) { if (szpset(prj)) return 1; } cphi = cosdeg (phi); sphi = sindeg (phi); cthe = cosdeg (theta); s = 1.0 - sindeg (theta); t = prj->w[3] - s; if (t == 0.0) { return 2; } *x = (prj->w[6]*cthe*sphi - prj->w[4]*s)/t; *y = -(prj->w[6]*cthe*cphi + prj->w[5]*s)/t; /* Bounds checking. */ if (prj->flag > 0) { /* Divergence. */ if (theta < prj->w[8]) { return 2; } /* Overlap. */ if (fabs(prj->p[1]) > 1.0) { s = prj->w[1]*sphi - prj->w[2]*cphi; t = 1.0/sqrt(prj->w[7] + s*s); if (fabs(t) <= 1.0) { s = atan2deg (s, prj->w[3] - 1.0); t = asindeg (t); a = s - t; b = s + t + 180.0; if (a > 90.0) a -= 360.0; if (b > 90.0) b -= 360.0; if (theta < ((a > b) ? a : b)) { return 2; } } } } return 0; } /*--------------------------------------------------------------------------*/ int szprev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { double a, b, c, d, r2, sth1, sth2, sthe, sxy, t, x1, xp, y1, yp, z; const double tol = 1.0e-13; if (abs(prj->flag) != SZP) { if (szpset(prj)) return 1; } xp = x*prj->w[0]; yp = y*prj->w[0]; r2 = xp*xp + yp*yp; x1 = (xp - prj->w[1])/prj->w[3]; y1 = (yp - prj->w[2])/prj->w[3]; sxy = xp*x1 + yp*y1; if (r2 < 1.0e-10) { /* Use small angle formula. */ z = r2/2.0; *theta = 90.0 - R2D*sqrt(r2/(1.0 + sxy)); } else { t = x1*x1 + y1*y1; a = t + 1.0; b = sxy - t; c = r2 - sxy - sxy + t - 1.0; d = b*b - a*c; /* Check for a solution. */ if (d < 0.0) { return 2; } d = sqrt(d); /* Choose solution closest to pole. */ sth1 = (-b + d)/a; sth2 = (-b - d)/a; sthe = (sth1 > sth2) ? sth1 : sth2; if (sthe > 1.0) { if (sthe-1.0 < tol) { sthe = 1.0; } else { sthe = (sth1 < sth2) ? sth1 : sth2; } } if (sthe < -1.0) { if (sthe+1.0 > -tol) { sthe = -1.0; } } if (sthe > 1.0 || sthe < -1.0) { return 2; } *theta = asindeg (sthe); z = 1.0 - sthe; } *phi = atan2deg (xp - x1*z, -(yp - y1*z)); return 0; } /*============================================================================ * TAN: gnomonic projection. * * Given and/or returned: * prj->flag TAN, or -TAN if prj->flag is given < 0. * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "TAN" * prj->phi0 0.0 * prj->theta0 90.0 * prj->prjfwd Pointer to tanfwd(). * prj->prjrev Pointer to tanrev(). *===========================================================================*/ int tanset(prj) struct prjprm *prj; { int k; strcpy(prj->code, "TAN"); prj->flag = copysgni (TAN, prj->flag); prj->phi0 = 0.0; prj->theta0 = 90.0; if (prj->r0 == 0.0) prj->r0 = R2D; prj->prjfwd = tanfwd; prj->prjrev = tanrev; for (k = (MAXPV-1); k >= 0 && prj->ppv[k] == 0.0 && prj->ppv[k+MAXPV] == 0.0; k--); if (k < 0) k = 0; prj->npv = k; return 0; } /*--------------------------------------------------------------------------*/ int tanfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { double r, s; double xp[2]; if (abs(prj->flag) != TAN) { if(tanset(prj)) return 1; } s = sindeg (theta); if (s <= 0.0) { return 2; } r = prj->r0*cosdeg (theta)/s; xp[0] = r*sindeg (phi); xp[1] = -r*cosdeg (phi); *x = prj->inv_x? poly_func(prj->inv_x, xp) : xp[0]; *y = prj->inv_y? poly_func(prj->inv_y, xp) : xp[1]; if (prj->flag > 0 && s < 0.0) { return 2; } return 0; } /*--------------------------------------------------------------------------*/ int tanrev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { double r; double xp; double yp; if (abs(prj->flag) != TAN) { if (tanset(prj)) return 1; } if (prj->npv) { raw_to_pv(prj, x,y, &xp, &yp); } else { xp = x; yp = y; } r = sqrt(xp*xp + yp*yp); if (r == 0.0) { *phi = 0.0; } else { *phi = atan2deg (xp, -yp); } *theta = atan2deg (prj->r0, r); return 0; } /*============================================================================ * STG: stereographic projection. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "STG" * prj->flag STG * prj->phi0 0.0 * prj->theta0 90.0 * prj->w[0] 2*r0 * prj->w[1] 1/(2*r0) * prj->prjfwd Pointer to stgfwd(). * prj->prjrev Pointer to stgrev(). *===========================================================================*/ int stgset(prj) struct prjprm *prj; { strcpy(prj->code, "STG"); prj->flag = STG; prj->phi0 = 0.0; prj->theta0 = 90.0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 360.0/PI; prj->w[1] = PI/360.0; } else { prj->w[0] = 2.0*prj->r0; prj->w[1] = 1.0/prj->w[0]; } prj->prjfwd = stgfwd; prj->prjrev = stgrev; return 0; } /*--------------------------------------------------------------------------*/ int stgfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { double r, s; if (prj->flag != STG) { if (stgset(prj)) return 1; } s = 1.0 + sindeg (theta); if (s == 0.0) { return 2; } r = prj->w[0]*cosdeg (theta)/s; *x = r*sindeg (phi); *y = -r*cosdeg (phi); return 0; } /*--------------------------------------------------------------------------*/ int stgrev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { double r; if (prj->flag != STG) { if (stgset(prj)) return 1; } r = sqrt(x*x + y*y); if (r == 0.0) { *phi = 0.0; } else { *phi = atan2deg (x, -y); } *theta = 90.0 - 2.0*atandeg (r*prj->w[1]); return 0; } /*============================================================================ * SIN: orthographic/synthesis projection. * * Given: * prj->p[1:2] Obliqueness parameters, xi and eta. * * Given and/or returned: * prj->flag SIN, or -SIN if prj->flag is given < 0. * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "SIN" * prj->phi0 0.0 * prj->theta0 90.0 * prj->w[0] 1/r0 * prj->w[1] xi**2 + eta**2 * prj->w[2] xi**2 + eta**2 + 1 * prj->w[3] xi**2 + eta**2 - 1 * prj->prjfwd Pointer to sinfwd(). * prj->prjrev Pointer to sinrev(). *===========================================================================*/ int sinset(prj) struct prjprm *prj; { strcpy(prj->code, "SIN"); prj->flag = copysgni (SIN, prj->flag); prj->phi0 = 0.0; prj->theta0 = 90.0; if (prj->r0 == 0.0) prj->r0 = R2D; prj->w[0] = 1.0/prj->r0; prj->w[1] = prj->p[1]*prj->p[1] + prj->p[2]*prj->p[2]; prj->w[2] = prj->w[1] + 1.0; prj->w[3] = prj->w[1] - 1.0; prj->prjfwd = sinfwd; prj->prjrev = sinrev; return 0; } /*--------------------------------------------------------------------------*/ int sinfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { double cphi, cthe, sphi, t, z; if (abs(prj->flag) != SIN) { if (sinset(prj)) return 1; } t = (90.0 - fabs(theta))*D2R; if (t < 1.0e-5) { if (theta > 0.0) { z = t*t/2.0; } else { z = 2.0 - t*t/2.0; } cthe = t; } else { z = 1.0 - sindeg (theta); cthe = cosdeg (theta); } cphi = cosdeg (phi); sphi = sindeg (phi); *x = prj->r0*(cthe*sphi + prj->p[1]*z); *y = -prj->r0*(cthe*cphi - prj->p[2]*z); /* Validate this solution. */ if (prj->flag > 0) { if (prj->w[1] == 0.0) { /* Orthographic projection. */ if (theta < 0.0) { return 2; } } else { /* "Synthesis" projection. */ t = -atandeg (prj->p[1]*sphi - prj->p[2]*cphi); if (theta < t) { return 2; } } } return 0; } /*--------------------------------------------------------------------------*/ int sinrev (x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { const double tol = 1.0e-13; double a, b, c, d, r2, sth1, sth2, sthe, sxy, x0, x1, xp, y0, y1, yp, z; if (abs(prj->flag) != SIN) { if (sinset(prj)) return 1; } /* Compute intermediaries. */ x0 = x*prj->w[0]; y0 = y*prj->w[0]; r2 = x0*x0 + y0*y0; if (prj->w[1] == 0.0) { /* Orthographic projection. */ if (r2 != 0.0) { *phi = atan2deg (x0, -y0); } else { *phi = 0.0; } if (r2 < 0.5) { *theta = acosdeg (sqrt(r2)); } else if (r2 <= 1.0) { *theta = asindeg (sqrt(1.0 - r2)); } else { return 2; } } else { /* "Synthesis" projection. */ x1 = prj->p[1]; y1 = prj->p[2]; sxy = x0*x1 + y0*y1; if (r2 < 1.0e-10) { /* Use small angle formula. */ z = r2/2.0; *theta = 90.0 - R2D*sqrt(r2/(1.0 + sxy)); } else { a = prj->w[2]; b = sxy - prj->w[1]; c = r2 - sxy - sxy + prj->w[3]; d = b*b - a*c; /* Check for a solution. */ if (d < 0.0) { return 2; } d = sqrt(d); /* Choose solution closest to pole. */ sth1 = (-b + d)/a; sth2 = (-b - d)/a; sthe = (sth1 > sth2) ? sth1 : sth2; if (sthe > 1.0) { if (sthe-1.0 < tol) { sthe = 1.0; } else { sthe = (sth1 < sth2) ? sth1 : sth2; } } if (sthe < -1.0) { if (sthe+1.0 > -tol) { sthe = -1.0; } } if (sthe > 1.0 || sthe < -1.0) { return 2; } *theta = asindeg (sthe); z = 1.0 - sthe; } xp = -y0 + prj->p[2]*z; yp = x0 - prj->p[1]*z; if (xp == 0.0 && yp == 0.0) { *phi = 0.0; } else { *phi = atan2deg (yp,xp); } } return 0; } /*============================================================================ * ARC: zenithal/azimuthal equidistant projection. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "ARC" * prj->flag ARC * prj->phi0 0.0 * prj->theta0 90.0 * prj->w[0] r0*(pi/180) * prj->w[1] (180/pi)/r0 * prj->prjfwd Pointer to arcfwd(). * prj->prjrev Pointer to arcrev(). *===========================================================================*/ int arcset(prj) struct prjprm *prj; { strcpy(prj->code, "ARC"); prj->flag = ARC; prj->phi0 = 0.0; prj->theta0 = 90.0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 1.0; prj->w[1] = 1.0; } else { prj->w[0] = prj->r0*D2R; prj->w[1] = 1.0/prj->w[0]; } prj->prjfwd = arcfwd; prj->prjrev = arcrev; return 0; } /*--------------------------------------------------------------------------*/ int arcfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { double r; if (prj->flag != ARC) { if (arcset(prj)) return 1; } r = prj->w[0]*(90.0 - theta); *x = r*sindeg (phi); *y = -r*cosdeg (phi); return 0; } /*--------------------------------------------------------------------------*/ int arcrev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { double r; if (prj->flag != ARC) { if (arcset(prj)) return 1; } r = sqrt(x*x + y*y); if (r == 0.0) { *phi = 0.0; } else { *phi = atan2deg (x, -y); } *theta = 90.0 - r*prj->w[1]; return 0; } /*============================================================================ * ZPN: zenithal/azimuthal polynomial projection. * * Given: * prj->p[0:9] Polynomial coefficients. * * Given and/or returned: * prj->flag ZPN, or -ZPN if prj->flag is given < 0. * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "ZPN" * prj->phi0 0.0 * prj->theta0 90.0 * prj->n Degree of the polynomial, N. * prj->w[0] Co-latitude of the first point of inflection (N > 2). * prj->w[1] Radius of the first point of inflection (N > 2). * prj->prjfwd Pointer to zpnfwd(). * prj->prjrev Pointer to zpnrev(). *===========================================================================*/ int zpnset(prj) struct prjprm *prj; { int i, j, k; double d, d1, d2, r, zd, zd1, zd2; const double tol = 1.0e-13; strcpy(prj->code, "ZPN"); prj->flag = copysgni (ZPN, prj->flag); prj->phi0 = 0.0; prj->theta0 = 90.0; if (prj->r0 == 0.0) prj->r0 = R2D; /* Find the highest non-zero coefficient. */ for (k = 9; k >= 0 && prj->p[k] == 0.0; k--){ i = 0; } /* if (k < 0) return 1; */ /* if (k < 0 switch to ARC projection */ if (k < 0) { return (arcset (prj)); } prj->n = k; /* No negative derivative -> no point of inflection. */ zd = PI; /* Processing subroutines */ prj->prjfwd = zpnfwd; prj->prjrev = zpnrev; if (k >= 3) { /* Find the point of inflection closest to the pole. */ zd1 = 0.0; d1 = prj->p[1]; if (d1 <= 0.0) { return 1; } /* Find the point where the derivative first goes negative. */ for (i = 0; i < 180; i++) { zd2 = i*D2R; d2 = 0.0; for (j = k; j > 0; j--) { d2 = d2*zd2 + j*prj->p[j]; } if (d2 <= 0.0) break; zd1 = zd2; d1 = d2; } if (i == 180) { /* No negative derivative -> no point of inflection. */ zd = PI; } else { /* Find where the derivative is zero. */ for (i = 1; i <= 10; i++) { zd = zd1 - d1*(zd2-zd1)/(d2-d1); d = 0.0; for (j = k; j > 0; j--) { d = d*zd + j*prj->p[j]; } if (fabs(d) < tol) break; if (d < 0.0) { zd2 = zd; d2 = d; } else { zd1 = zd; d1 = d; } } } r = 0.0; for (j = k; j >= 0; j--) { r = r*zd + prj->p[j]; } prj->w[0] = zd; prj->w[1] = r; } return 0; } /*--------------------------------------------------------------------------*/ int zpnfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { int j; double r, s; if (abs(prj->flag) != ZPN) { if (zpnset(prj)) return 1; } s = (90.0 - theta)*D2R; r = 0.0; for (j = 9; j >= 0; j--) { r = r*s + prj->p[j]; } r = prj->r0*r; *x = r*sindeg (phi); *y = -r*cosdeg (phi); if (prj->flag > 0 && s > prj->w[0]) { return 2; } return 0; } /*--------------------------------------------------------------------------*/ int zpnrev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { int i, j, k; double a, b, c, d, lambda, r, r1, r2, rt, zd, zd1, zd2; const double tol = 1.0e-13; if (abs(prj->flag) != ZPN) { if (zpnset(prj)) return 1; } k = prj->n; r = sqrt(x*x + y*y)/prj->r0; if (k < 1) { /* Constant - no solution. */ return 1; } else if (k == 1) { /* Linear. */ zd = (r - prj->p[0])/prj->p[1]; } else if (k == 2) { /* Quadratic. */ a = prj->p[2]; b = prj->p[1]; c = prj->p[0] - r; d = b*b - 4.0*a*c; if (d < 0.0) { return 2; } d = sqrt(d); /* Choose solution closest to pole. */ zd1 = (-b + d)/(2.0*a); zd2 = (-b - d)/(2.0*a); zd = (zd1zd2) ? zd1 : zd2; if (zd < 0.0) { if (zd < -tol) { return 2; } zd = 0.0; } else if (zd > PI) { if (zd > PI+tol) { return 2; } zd = PI; } } else { /* Higher order - solve iteratively. */ zd1 = 0.0; r1 = prj->p[0]; zd2 = prj->w[0]; r2 = prj->w[1]; if (r < r1) { if (r < r1-tol) { return 2; } zd = zd1; } else if (r > r2) { if (r > r2+tol) { return 2; } zd = zd2; } else { /* Disect the interval. */ for (j = 0; j < 100; j++) { lambda = (r2 - r)/(r2 - r1); if (lambda < 0.1) { lambda = 0.1; } else if (lambda > 0.9) { lambda = 0.9; } zd = zd2 - lambda*(zd2 - zd1); rt = 0.0; for (i = k; i >= 0; i--) { rt = (rt * zd) + prj->p[i]; } if (rt < r) { if (r-rt < tol) break; r1 = rt; zd1 = zd; } else { if (rt-r < tol) break; r2 = rt; zd2 = zd; } if (fabs(zd2-zd1) < tol) break; } } } if (r == 0.0) { *phi = 0.0; } else { *phi = atan2deg (x, -y); } *theta = 90.0 - zd*R2D; return 0; } /*============================================================================ * ZEA: zenithal/azimuthal equal area projection. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "ZEA" * prj->flag ZEA * prj->phi0 0.0 * prj->theta0 90.0 * prj->w[0] 2*r0 * prj->w[1] 1/(2*r0) * prj->prjfwd Pointer to zeafwd(). * prj->prjrev Pointer to zearev(). *===========================================================================*/ int zeaset(prj) struct prjprm *prj; { strcpy(prj->code, "ZEA"); prj->flag = ZEA; prj->phi0 = 0.0; prj->theta0 = 90.0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 360.0/PI; prj->w[1] = PI/360.0; } else { prj->w[0] = 2.0*prj->r0; prj->w[1] = 1.0/prj->w[0]; } prj->prjfwd = zeafwd; prj->prjrev = zearev; return 0; } /*--------------------------------------------------------------------------*/ int zeafwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { double r; if (prj->flag != ZEA) { if (zeaset(prj)) return 1; } r = prj->w[0]*sindeg ((90.0 - theta)/2.0); *x = r*sindeg (phi); *y = -r*cosdeg (phi); return 0; } /*--------------------------------------------------------------------------*/ int zearev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { double r, s; const double tol = 1.0e-12; if (prj->flag != ZEA) { if (zeaset(prj)) return 1; } r = sqrt(x*x + y*y); if (r == 0.0) { *phi = 0.0; } else { *phi = atan2deg (x, -y); } s = r*prj->w[1]; if (fabs(s) > 1.0) { if (fabs(r - prj->w[0]) < tol) { *theta = -90.0; } else { return 2; } } else { *theta = 90.0 - 2.0*asindeg (s); } return 0; } /*============================================================================ * AIR: Airy's projection. * * Given: * prj->p[1] Latitude theta_b within which the error is minimized, in * degrees. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "AIR" * prj->flag AIR * prj->phi0 0.0 * prj->theta0 90.0 * prj->w[0] 2*r0 * prj->w[1] ln(cos(xi_b))/tan(xi_b)**2, where xi_b = (90-theta_b)/2 * prj->w[2] 1/2 - prj->w[1] * prj->w[3] 2*r0*prj->w[2] * prj->w[4] tol, cutoff for using small angle approximation, in * radians. * prj->w[5] prj->w[2]*tol * prj->w[6] (180/pi)/prj->w[2] * prj->prjfwd Pointer to airfwd(). * prj->prjrev Pointer to airrev(). *===========================================================================*/ int airset(prj) struct prjprm *prj; { const double tol = 1.0e-4; double cxi; strcpy(prj->code, "AIR"); prj->flag = AIR; prj->phi0 = 0.0; prj->theta0 = 90.0; if (prj->r0 == 0.0) prj->r0 = R2D; prj->w[0] = 2.0*prj->r0; if (prj->p[1] == 90.0) { prj->w[1] = -0.5; prj->w[2] = 1.0; } else if (prj->p[1] > -90.0) { cxi = cosdeg ((90.0 - prj->p[1])/2.0); prj->w[1] = log(cxi)*(cxi*cxi)/(1.0-cxi*cxi); prj->w[2] = 0.5 - prj->w[1]; } else { return 1; } prj->w[3] = prj->w[0] * prj->w[2]; prj->w[4] = tol; prj->w[5] = prj->w[2]*tol; prj->w[6] = R2D/prj->w[2]; prj->prjfwd = airfwd; prj->prjrev = airrev; return 0; } /*--------------------------------------------------------------------------*/ int airfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { double cxi, r, txi, xi; if (prj->flag != AIR) { if (airset(prj)) return 1; } if (theta == 90.0) { r = 0.0; } else if (theta > -90.0) { xi = D2R*(90.0 - theta)/2.0; if (xi < prj->w[4]) { r = xi*prj->w[3]; } else { cxi = cosdeg ((90.0 - theta)/2.0); txi = sqrt(1.0-cxi*cxi)/cxi; r = -prj->w[0]*(log(cxi)/txi + prj->w[1]*txi); } } else { return 2; } *x = r*sindeg (phi); *y = -r*cosdeg (phi); return 0; } /*--------------------------------------------------------------------------*/ int airrev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { int j; double cxi, lambda, r, r1, r2, rt, txi, x1, x2, xi; const double tol = 1.0e-12; if (prj->flag != AIR) { if (airset(prj)) return 1; } r = sqrt(x*x + y*y)/prj->w[0]; if (r == 0.0) { xi = 0.0; } else if (r < prj->w[5]) { xi = r*prj->w[6]; } else { /* Find a solution interval. */ x1 = 1.0; r1 = 0.0; for (j = 0; j < 30; j++) { x2 = x1/2.0; txi = sqrt(1.0-x2*x2)/x2; r2 = -(log(x2)/txi + prj->w[1]*txi); if (r2 >= r) break; x1 = x2; r1 = r2; } if (j == 30) return 2; for (j = 0; j < 100; j++) { /* Weighted division of the interval. */ lambda = (r2-r)/(r2-r1); if (lambda < 0.1) { lambda = 0.1; } else if (lambda > 0.9) { lambda = 0.9; } cxi = x2 - lambda*(x2-x1); txi = sqrt(1.0-cxi*cxi)/cxi; rt = -(log(cxi)/txi + prj->w[1]*txi); if (rt < r) { if (r-rt < tol) break; r1 = rt; x1 = cxi; } else { if (rt-r < tol) break; r2 = rt; x2 = cxi; } } if (j == 100) return 2; xi = acosdeg (cxi); } if (r == 0.0) { *phi = 0.0; } else { *phi = atan2deg (x, -y); } *theta = 90.0 - 2.0*xi; return 0; } /*============================================================================ * CYP: cylindrical perspective projection. * * Given: * prj->p[1] Distance of point of projection from the centre of the * generating sphere, mu, in units of r0. * prj->p[2] Radius of the cylinder of projection, lambda, in units of * r0. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "CYP" * prj->flag CYP * prj->phi0 0.0 * prj->theta0 0.0 * prj->w[0] r0*lambda*(pi/180) * prj->w[1] (180/pi)/(r0*lambda) * prj->w[2] r0*(mu + lambda) * prj->w[3] 1/(r0*(mu + lambda)) * prj->prjfwd Pointer to cypfwd(). * prj->prjrev Pointer to cyprev(). *===========================================================================*/ int cypset(prj) struct prjprm *prj; { strcpy(prj->code, "CYP"); prj->flag = CYP; prj->phi0 = 0.0; prj->theta0 = 0.0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = prj->p[2]; if (prj->w[0] == 0.0) { return 1; } prj->w[1] = 1.0/prj->w[0]; prj->w[2] = R2D*(prj->p[1] + prj->p[2]); if (prj->w[2] == 0.0) { return 1; } prj->w[3] = 1.0/prj->w[2]; } else { prj->w[0] = prj->r0*prj->p[2]*D2R; if (prj->w[0] == 0.0) { return 1; } prj->w[1] = 1.0/prj->w[0]; prj->w[2] = prj->r0*(prj->p[1] + prj->p[2]); if (prj->w[2] == 0.0) { return 1; } prj->w[3] = 1.0/prj->w[2]; } prj->prjfwd = cypfwd; prj->prjrev = cyprev; return 0; } /*--------------------------------------------------------------------------*/ int cypfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { double s; if (prj->flag != CYP) { if (cypset(prj)) return 1; } s = prj->p[1] + cosdeg (theta); if (s == 0.0) { return 2; } *x = prj->w[0]*phi; *y = prj->w[2]*sindeg (theta)/s; return 0; } /*--------------------------------------------------------------------------*/ int cyprev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { double eta; if (prj->flag != CYP) { if (cypset(prj)) return 1; } *phi = x*prj->w[1]; eta = y*prj->w[3]; *theta = atan2deg (eta,1.0) + asindeg (eta*prj->p[1]/sqrt(eta*eta+1.0)); return 0; } /*============================================================================ * CEA: cylindrical equal area projection. * * Given: * prj->p[1] Square of the cosine of the latitude at which the * projection is conformal, lambda. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "CEA" * prj->flag CEA * prj->phi0 0.0 * prj->theta0 0.0 * prj->w[0] r0*(pi/180) * prj->w[1] (180/pi)/r0 * prj->w[2] r0/lambda * prj->w[3] lambda/r0 * prj->prjfwd Pointer to ceafwd(). * prj->prjrev Pointer to cearev(). *===========================================================================*/ int ceaset(prj) struct prjprm *prj; { strcpy(prj->code, "CEA"); prj->flag = CEA; prj->phi0 = 0.0; prj->theta0 = 0.0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 1.0; prj->w[1] = 1.0; if (prj->p[1] <= 0.0 || prj->p[1] > 1.0) { return 1; } prj->w[2] = prj->r0/prj->p[1]; prj->w[3] = prj->p[1]/prj->r0; } else { prj->w[0] = prj->r0*D2R; prj->w[1] = R2D/prj->r0; if (prj->p[1] <= 0.0 || prj->p[1] > 1.0) { return 1; } prj->w[2] = prj->r0/prj->p[1]; prj->w[3] = prj->p[1]/prj->r0; } prj->prjfwd = ceafwd; prj->prjrev = cearev; return 0; } /*--------------------------------------------------------------------------*/ int ceafwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { if (prj->flag != CEA) { if (ceaset(prj)) return 1; } *x = prj->w[0]*phi; *y = prj->w[2]*sindeg (theta); return 0; } /*--------------------------------------------------------------------------*/ int cearev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { double s; const double tol = 1.0e-13; if (prj->flag != CEA) { if (ceaset(prj)) return 1; } s = y*prj->w[3]; if (fabs(s) > 1.0) { if (fabs(s) > 1.0+tol) { return 2; } s = copysgn (1.0,s); } *phi = x*prj->w[1]; *theta = asindeg (s); return 0; } /*============================================================================ * CAR: Cartesian projection. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "CAR" * prj->flag CAR * prj->phi0 0.0 * prj->theta0 0.0 * prj->w[0] r0*(pi/180) * prj->w[1] (180/pi)/r0 * prj->prjfwd Pointer to carfwd(). * prj->prjrev Pointer to carrev(). *===========================================================================*/ int carset(prj) struct prjprm *prj; { strcpy(prj->code, "CAR"); prj->flag = CAR; prj->phi0 = 0.0; prj->theta0 = 0.0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 1.0; prj->w[1] = 1.0; } else { prj->w[0] = prj->r0*D2R; prj->w[1] = 1.0/prj->w[0]; } prj->prjfwd = carfwd; prj->prjrev = carrev; return 0; } /*--------------------------------------------------------------------------*/ int carfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { if (prj->flag != CAR) { if (carset(prj)) return 1; } *x = prj->w[0]*phi; *y = prj->w[0]*theta; return 0; } /*--------------------------------------------------------------------------*/ int carrev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { if (prj->flag != CAR) { if (carset(prj)) return 1; } *phi = prj->w[1]*x; *theta = prj->w[1]*y; return 0; } /*============================================================================ * MER: Mercator's projection. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "MER" * prj->flag MER * prj->phi0 0.0 * prj->theta0 0.0 * prj->w[0] r0*(pi/180) * prj->w[1] (180/pi)/r0 * prj->prjfwd Pointer to merfwd(). * prj->prjrev Pointer to merrev(). *===========================================================================*/ int merset(prj) struct prjprm *prj; { strcpy(prj->code, "MER"); prj->flag = MER; prj->phi0 = 0.0; prj->theta0 = 0.0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 1.0; prj->w[1] = 1.0; } else { prj->w[0] = prj->r0*D2R; prj->w[1] = 1.0/prj->w[0]; } prj->prjfwd = merfwd; prj->prjrev = merrev; return 0; } /*--------------------------------------------------------------------------*/ int merfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { if (prj->flag != MER) { if (merset(prj)) return 1; } if (theta <= -90.0 || theta >= 90.0) { return 2; } *x = prj->w[0]*phi; *y = prj->r0*log(tandeg ((90.0+theta)/2.0)); return 0; } /*--------------------------------------------------------------------------*/ int merrev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { if (prj->flag != MER) { if (merset(prj)) return 1; } *phi = x*prj->w[1]; *theta = 2.0*atandeg (exp(y/prj->r0)) - 90.0; return 0; } /*============================================================================ * SFL: Sanson-Flamsteed ("global sinusoid") projection. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "SFL" * prj->flag SFL * prj->phi0 0.0 * prj->theta0 0.0 * prj->w[0] r0*(pi/180) * prj->w[1] (180/pi)/r0 * prj->prjfwd Pointer to sflfwd(). * prj->prjrev Pointer to sflrev(). *===========================================================================*/ int sflset(prj) struct prjprm *prj; { strcpy(prj->code, "SFL"); prj->flag = SFL; prj->phi0 = 0.0; prj->theta0 = 0.0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 1.0; prj->w[1] = 1.0; } else { prj->w[0] = prj->r0*D2R; prj->w[1] = 1.0/prj->w[0]; } prj->prjfwd = sflfwd; prj->prjrev = sflrev; return 0; } /*--------------------------------------------------------------------------*/ int sflfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { if (prj->flag != SFL) { if (sflset(prj)) return 1; } *x = prj->w[0]*phi*cosdeg (theta); *y = prj->w[0]*theta; return 0; } /*--------------------------------------------------------------------------*/ int sflrev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { double w; if (prj->flag != SFL) { if (sflset(prj)) return 1; } w = cos(y/prj->r0); if (w == 0.0) { *phi = 0.0; } else { *phi = x*prj->w[1]/cos(y/prj->r0); } *theta = y*prj->w[1]; return 0; } /*============================================================================ * PAR: parabolic projection. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "PAR" * prj->flag PAR * prj->phi0 0.0 * prj->theta0 0.0 * prj->w[0] r0*(pi/180) * prj->w[1] (180/pi)/r0 * prj->w[2] pi*r0 * prj->w[3] 1/(pi*r0) * prj->prjfwd Pointer to parfwd(). * prj->prjrev Pointer to parrev(). *===========================================================================*/ int parset(prj) struct prjprm *prj; { strcpy(prj->code, "PAR"); prj->flag = PAR; prj->phi0 = 0.0; prj->theta0 = 0.0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 1.0; prj->w[1] = 1.0; prj->w[2] = 180.0; prj->w[3] = 1.0/prj->w[2]; } else { prj->w[0] = prj->r0*D2R; prj->w[1] = 1.0/prj->w[0]; prj->w[2] = PI*prj->r0; prj->w[3] = 1.0/prj->w[2]; } prj->prjfwd = parfwd; prj->prjrev = parrev; return 0; } /*--------------------------------------------------------------------------*/ int parfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { double s; if (prj->flag != PAR) { if (parset(prj)) return 1; } s = sindeg (theta/3.0); *x = prj->w[0]*phi*(1.0 - 4.0*s*s); *y = prj->w[2]*s; return 0; } /*--------------------------------------------------------------------------*/ int parrev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { double s, t; if (prj->flag != PAR) { if (parset(prj)) return 1; } s = y*prj->w[3]; if (s > 1.0 || s < -1.0) { return 2; } t = 1.0 - 4.0*s*s; if (t == 0.0) { if (x == 0.0) { *phi = 0.0; } else { return 2; } } else { *phi = prj->w[1]*x/t; } *theta = 3.0*asindeg (s); return 0; } /*============================================================================ * MOL: Mollweide's projection. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "MOL" * prj->flag MOL * prj->phi0 0.0 * prj->theta0 0.0 * prj->w[0] sqrt(2)*r0 * prj->w[1] sqrt(2)*r0/90 * prj->w[2] 1/(sqrt(2)*r0) * prj->w[3] 90/r0 * prj->prjfwd Pointer to molfwd(). * prj->prjrev Pointer to molrev(). *===========================================================================*/ int molset(prj) struct prjprm *prj; { strcpy(prj->code, "MOL"); prj->flag = MOL; prj->phi0 = 0.0; prj->theta0 = 0.0; if (prj->r0 == 0.0) prj->r0 = R2D; prj->w[0] = SQRT2*prj->r0; prj->w[1] = prj->w[0]/90.0; prj->w[2] = 1.0/prj->w[0]; prj->w[3] = 90.0/prj->r0; prj->w[4] = 2.0/PI; prj->prjfwd = molfwd; prj->prjrev = molrev; return 0; } /*--------------------------------------------------------------------------*/ int molfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { int j; double gamma, resid, u, v, v0, v1; const double tol = 1.0e-13; if (prj->flag != MOL) { if (molset(prj)) return 1; } if (fabs(theta) == 90.0) { *x = 0.0; *y = copysgn (prj->w[0],theta); } else if (theta == 0.0) { *x = prj->w[1]*phi; *y = 0.0; } else { u = PI*sindeg (theta); v0 = -PI; v1 = PI; v = u; for (j = 0; j < 100; j++) { resid = (v - u) + sin(v); if (resid < 0.0) { if (resid > -tol) break; v0 = v; } else { if (resid < tol) break; v1 = v; } v = (v0 + v1)/2.0; } gamma = v/2.0; *x = prj->w[1]*phi*cos(gamma); *y = prj->w[0]*sin(gamma); } return 0; } /*--------------------------------------------------------------------------*/ int molrev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { double s, y0, z; const double tol = 1.0e-12; if (prj->flag != MOL) { if (molset(prj)) return 1; } y0 = y/prj->r0; s = 2.0 - y0*y0; if (s <= tol) { if (s < -tol) { return 2; } s = 0.0; if (fabs(x) > tol) { return 2; } *phi = 0.0; } else { s = sqrt(s); *phi = prj->w[3]*x/s; } z = y*prj->w[2]; if (fabs(z) > 1.0) { if (fabs(z) > 1.0+tol) { return 2; } z = copysgn (1.0,z) + y0*s/PI; } else { z = asin(z)*prj->w[4] + y0*s/PI; } if (fabs(z) > 1.0) { if (fabs(z) > 1.0+tol) { return 2; } z = copysgn (1.0,z); } *theta = asindeg (z); return 0; } /*============================================================================ * AIT: Hammer-Aitoff projection. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "AIT" * prj->flag AIT * prj->phi0 0.0 * prj->theta0 0.0 * prj->w[0] 2*r0**2 * prj->w[1] 1/(2*r0)**2 * prj->w[2] 1/(4*r0)**2 * prj->w[3] 1/(2*r0) * prj->prjfwd Pointer to aitfwd(). * prj->prjrev Pointer to aitrev(). *===========================================================================*/ int aitset(prj) struct prjprm *prj; { strcpy(prj->code, "AIT"); prj->flag = AIT; prj->phi0 = 0.0; prj->theta0 = 0.0; if (prj->r0 == 0.0) prj->r0 = R2D; prj->w[0] = 2.0*prj->r0*prj->r0; prj->w[1] = 1.0/(2.0*prj->w[0]); prj->w[2] = prj->w[1]/4.0; prj->w[3] = 1.0/(2.0*prj->r0); prj->prjfwd = aitfwd; prj->prjrev = aitrev; return 0; } /*--------------------------------------------------------------------------*/ int aitfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { double cthe, w; if (prj->flag != AIT) { if (aitset(prj)) return 1; } cthe = cosdeg (theta); w = sqrt(prj->w[0]/(1.0 + cthe*cosdeg (phi/2.0))); *x = 2.0*w*cthe*sindeg (phi/2.0); *y = w*sindeg (theta); return 0; } /*--------------------------------------------------------------------------*/ int aitrev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { double s, u, xp, yp, z; const double tol = 1.0e-13; if (prj->flag != AIT) { if (aitset(prj)) return 1; } u = 1.0 - x*x*prj->w[2] - y*y*prj->w[1]; if (u < 0.0) { if (u < -tol) { return 2; } u = 0.0; } z = sqrt(u); s = z*y/prj->r0; if (fabs(s) > 1.0) { if (fabs(s) > 1.0+tol) { return 2; } s = copysgn (1.0,s); } xp = 2.0*z*z - 1.0; yp = z*x*prj->w[3]; if (xp == 0.0 && yp == 0.0) { *phi = 0.0; } else { *phi = 2.0*atan2deg (yp, xp); } *theta = asindeg (s); return 0; } /*============================================================================ * COP: conic perspective projection. * * Given: * prj->p[1] sigma = (theta2+theta1)/2 * prj->p[2] delta = (theta2-theta1)/2, where theta1 and theta2 are the * latitudes of the standard parallels, in degrees. * * Given and/or returned: * prj->flag COP, or -COP if prj->flag is given < 0. * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "COP" * prj->phi0 0.0 * prj->theta0 sigma * prj->w[0] C = sin(sigma) * prj->w[1] 1/C * prj->w[2] Y0 = r0*cos(delta)*cot(sigma) * prj->w[3] r0*cos(delta) * prj->w[4] 1/(r0*cos(delta) * prj->w[5] cot(sigma) * prj->prjfwd Pointer to copfwd(). * prj->prjrev Pointer to coprev(). *===========================================================================*/ int copset(prj) struct prjprm *prj; { strcpy(prj->code, "COP"); prj->flag = copysgni (COP, prj->flag); prj->phi0 = 0.0; prj->theta0 = prj->p[1]; if (prj->r0 == 0.0) prj->r0 = R2D; prj->w[0] = sindeg (prj->p[1]); if (prj->w[0] == 0.0) { return 1; } prj->w[1] = 1.0/prj->w[0]; prj->w[3] = prj->r0*cosdeg (prj->p[2]); if (prj->w[3] == 0.0) { return 1; } prj->w[4] = 1.0/prj->w[3]; prj->w[5] = 1.0/tandeg (prj->p[1]); prj->w[2] = prj->w[3]*prj->w[5]; prj->prjfwd = copfwd; prj->prjrev = coprev; return 0; } /*--------------------------------------------------------------------------*/ int copfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { double a, r, s, t; if (abs(prj->flag) != COP) { if (copset(prj)) return 1; } t = theta - prj->p[1]; s = cosdeg (t); if (s == 0.0) { return 2; } a = prj->w[0]*phi; r = prj->w[2] - prj->w[3]*sindeg (t)/s; *x = r*sindeg (a); *y = prj->w[2] - r*cosdeg (a); if (prj->flag > 0 && r*prj->w[0] < 0.0) { return 2; } return 0; } /*--------------------------------------------------------------------------*/ int coprev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { double a, dy, r; if (abs(prj->flag) != COP) { if (copset(prj)) return 1; } dy = prj->w[2] - y; r = sqrt(x*x + dy*dy); if (prj->p[1] < 0.0) r = -r; if (r == 0.0) { a = 0.0; } else { a = atan2deg (x/r, dy/r); } *phi = a*prj->w[1]; *theta = prj->p[1] + atandeg (prj->w[5] - r*prj->w[4]); return 0; } /*============================================================================ * COE: conic equal area projection. * * Given: * prj->p[1] sigma = (theta2+theta1)/2 * prj->p[2] delta = (theta2-theta1)/2, where theta1 and theta2 are the * latitudes of the standard parallels, in degrees. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "COE" * prj->flag COE * prj->phi0 0.0 * prj->theta0 sigma * prj->w[0] C = (sin(theta1) + sin(theta2))/2 * prj->w[1] 1/C * prj->w[2] Y0 = chi*sqrt(psi - 2C*sindeg (sigma)) * prj->w[3] chi = r0/C * prj->w[4] psi = 1 + sin(theta1)*sin(theta2) * prj->w[5] 2C * prj->w[6] (1 + sin(theta1)*sin(theta2))*(r0/C)**2 * prj->w[7] C/(2*r0**2) * prj->w[8] chi*sqrt(psi + 2C) * prj->prjfwd Pointer to coefwd(). * prj->prjrev Pointer to coerev(). *===========================================================================*/ int coeset(prj) struct prjprm *prj; { double theta1, theta2; strcpy(prj->code, "COE"); prj->flag = COE; prj->phi0 = 0.0; prj->theta0 = prj->p[1]; if (prj->r0 == 0.0) prj->r0 = R2D; theta1 = prj->p[1] - prj->p[2]; theta2 = prj->p[1] + prj->p[2]; prj->w[0] = (sindeg (theta1) + sindeg (theta2))/2.0; if (prj->w[0] == 0.0) { return 1; } prj->w[1] = 1.0/prj->w[0]; prj->w[3] = prj->r0/prj->w[0]; prj->w[4] = 1.0 + sindeg (theta1)*sindeg (theta2); prj->w[5] = 2.0*prj->w[0]; prj->w[6] = prj->w[3]*prj->w[3]*prj->w[4]; prj->w[7] = 1.0/(2.0*prj->r0*prj->w[3]); prj->w[8] = prj->w[3]*sqrt(prj->w[4] + prj->w[5]); prj->w[2] = prj->w[3]*sqrt(prj->w[4] - prj->w[5]*sindeg (prj->p[1])); prj->prjfwd = coefwd; prj->prjrev = coerev; return 0; } /*--------------------------------------------------------------------------*/ int coefwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { double a, r; if (prj->flag != COE) { if (coeset(prj)) return 1; } a = phi*prj->w[0]; if (theta == -90.0) { r = prj->w[8]; } else { r = prj->w[3]*sqrt(prj->w[4] - prj->w[5]*sindeg (theta)); } *x = r*sindeg (a); *y = prj->w[2] - r*cosdeg (a); return 0; } /*--------------------------------------------------------------------------*/ int coerev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { double a, dy, r, w; const double tol = 1.0e-12; if (prj->flag != COE) { if (coeset(prj)) return 1; } dy = prj->w[2] - y; r = sqrt(x*x + dy*dy); if (prj->p[1] < 0.0) r = -r; if (r == 0.0) { a = 0.0; } else { a = atan2deg (x/r, dy/r); } *phi = a*prj->w[1]; if (fabs(r - prj->w[8]) < tol) { *theta = -90.0; } else { w = (prj->w[6] - r*r)*prj->w[7]; if (fabs(w) > 1.0) { if (fabs(w-1.0) < tol) { *theta = 90.0; } else if (fabs(w+1.0) < tol) { *theta = -90.0; } else { return 2; } } else { *theta = asindeg (w); } } return 0; } /*============================================================================ * COD: conic equidistant projection. * * Given: * prj->p[1] sigma = (theta2+theta1)/2 * prj->p[2] delta = (theta2-theta1)/2, where theta1 and theta2 are the * latitudes of the standard parallels, in degrees. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "COD" * prj->flag COD * prj->phi0 0.0 * prj->theta0 sigma * prj->w[0] C = r0*sin(sigma)*sin(delta)/delta * prj->w[1] 1/C * prj->w[2] Y0 = delta*cot(delta)*cot(sigma) * prj->w[3] Y0 + sigma * prj->prjfwd Pointer to codfwd(). * prj->prjrev Pointer to codrev(). *===========================================================================*/ int codset(prj) struct prjprm *prj; { strcpy(prj->code, "COD"); prj->flag = COD; prj->phi0 = 0.0; prj->theta0 = prj->p[1]; if (prj->r0 == 0.0) prj->r0 = R2D; if (prj->p[2] == 0.0) { prj->w[0] = prj->r0*sindeg (prj->p[1])*D2R; } else { prj->w[0] = prj->r0*sindeg (prj->p[1])*sindeg (prj->p[2])/prj->p[2]; } if (prj->w[0] == 0.0) { return 1; } prj->w[1] = 1.0/prj->w[0]; prj->w[2] = prj->r0*cosdeg (prj->p[2])*cosdeg (prj->p[1])/prj->w[0]; prj->w[3] = prj->w[2] + prj->p[1]; prj->prjfwd = codfwd; prj->prjrev = codrev; return 0; } /*--------------------------------------------------------------------------*/ int codfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { double a, r; if (prj->flag != COD) { if (codset(prj)) return 1; } a = prj->w[0]*phi; r = prj->w[3] - theta; *x = r*sindeg (a); *y = prj->w[2] - r*cosdeg (a); return 0; } /*--------------------------------------------------------------------------*/ int codrev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { double a, dy, r; if (prj->flag != COD) { if (codset(prj)) return 1; } dy = prj->w[2] - y; r = sqrt(x*x + dy*dy); if (prj->p[1] < 0.0) r = -r; if (r == 0.0) { a = 0.0; } else { a = atan2deg (x/r, dy/r); } *phi = a*prj->w[1]; *theta = prj->w[3] - r; return 0; } /*============================================================================ * COO: conic orthomorphic projection. * * Given: * prj->p[1] sigma = (theta2+theta1)/2 * prj->p[2] delta = (theta2-theta1)/2, where theta1 and theta2 are the * latitudes of the standard parallels, in degrees. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "COO" * prj->flag COO * prj->phi0 0.0 * prj->theta0 sigma * prj->w[0] C = ln(cos(theta2)/cos(theta1))/ln(tan(tau2)/tan(tau1)) * where tau1 = (90 - theta1)/2 * tau2 = (90 - theta2)/2 * prj->w[1] 1/C * prj->w[2] Y0 = psi*tan((90-sigma)/2)**C * prj->w[3] psi = (r0*cos(theta1)/C)/tan(tau1)**C * prj->w[4] 1/psi * prj->prjfwd Pointer to coofwd(). * prj->prjrev Pointer to coorev(). *===========================================================================*/ int cooset(prj) struct prjprm *prj; { double cos1, cos2, tan1, tan2, theta1, theta2; strcpy(prj->code, "COO"); prj->flag = COO; prj->phi0 = 0.0; prj->theta0 = prj->p[1]; if (prj->r0 == 0.0) prj->r0 = R2D; theta1 = prj->p[1] - prj->p[2]; theta2 = prj->p[1] + prj->p[2]; tan1 = tandeg ((90.0 - theta1)/2.0); cos1 = cosdeg (theta1); if (theta1 == theta2) { prj->w[0] = sindeg (theta1); } else { tan2 = tandeg ((90.0 - theta2)/2.0); cos2 = cosdeg (theta2); prj->w[0] = log(cos2/cos1)/log(tan2/tan1); } if (prj->w[0] == 0.0) { return 1; } prj->w[1] = 1.0/prj->w[0]; prj->w[3] = prj->r0*(cos1/prj->w[0])/pow(tan1,prj->w[0]); if (prj->w[3] == 0.0) { return 1; } prj->w[2] = prj->w[3]*pow(tandeg ((90.0 - prj->p[1])/2.0),prj->w[0]); prj->w[4] = 1.0/prj->w[3]; prj->prjfwd = coofwd; prj->prjrev = coorev; return 0; } /*--------------------------------------------------------------------------*/ int coofwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { double a, r; if (prj->flag != COO) { if (cooset(prj)) return 1; } a = prj->w[0]*phi; if (theta == -90.0) { if (prj->w[0] < 0.0) { r = 0.0; } else { return 2; } } else { r = prj->w[3]*pow(tandeg ((90.0 - theta)/2.0),prj->w[0]); } *x = r*sindeg (a); *y = prj->w[2] - r*cosdeg (a); return 0; } /*--------------------------------------------------------------------------*/ int coorev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { double a, dy, r; if (prj->flag != COO) { if (cooset(prj)) return 1; } dy = prj->w[2] - y; r = sqrt(x*x + dy*dy); if (prj->p[1] < 0.0) r = -r; if (r == 0.0) { a = 0.0; } else { a = atan2deg (x/r, dy/r); } *phi = a*prj->w[1]; if (r == 0.0) { if (prj->w[0] < 0.0) { *theta = -90.0; } else { return 2; } } else { *theta = 90.0 - 2.0*atandeg (pow(r*prj->w[4],prj->w[1])); } return 0; } /*============================================================================ * BON: Bonne's projection. * * Given: * prj->p[1] Bonne conformal latitude, theta1, in degrees. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "BON" * prj->flag BON * prj->phi0 0.0 * prj->theta0 0.0 * prj->w[1] r0*pi/180 * prj->w[2] Y0 = r0*(cot(theta1) + theta1*pi/180) * prj->prjfwd Pointer to bonfwd(). * prj->prjrev Pointer to bonrev(). *===========================================================================*/ int bonset(prj) struct prjprm *prj; { strcpy(prj->code, "BON"); prj->flag = BON; prj->phi0 = 0.0; prj->theta0 = 0.0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[1] = 1.0; prj->w[2] = prj->r0*cosdeg (prj->p[1])/sindeg (prj->p[1]) + prj->p[1]; } else { prj->w[1] = prj->r0*D2R; prj->w[2] = prj->r0*(cosdeg (prj->p[1])/sindeg (prj->p[1]) + prj->p[1]*D2R); } prj->prjfwd = bonfwd; prj->prjrev = bonrev; return 0; } /*--------------------------------------------------------------------------*/ int bonfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { double a, r; if (prj->p[1] == 0.0) { /* Sanson-Flamsteed. */ return sflfwd(phi, theta, prj, x, y); } if (prj->flag != BON) { if (bonset(prj)) return 1; } r = prj->w[2] - theta*prj->w[1]; a = prj->r0*phi*cosdeg (theta)/r; *x = r*sindeg (a); *y = prj->w[2] - r*cosdeg (a); return 0; } /*--------------------------------------------------------------------------*/ int bonrev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { double a, cthe, dy, r; if (prj->p[1] == 0.0) { /* Sanson-Flamsteed. */ return sflrev(x, y, prj, phi, theta); } if (prj->flag != BON) { if (bonset(prj)) return 1; } dy = prj->w[2] - y; r = sqrt(x*x + dy*dy); if (prj->p[1] < 0.0) r = -r; if (r == 0.0) { a = 0.0; } else { a = atan2deg (x/r, dy/r); } *theta = (prj->w[2] - r)/prj->w[1]; cthe = cosdeg (*theta); if (cthe == 0.0) { *phi = 0.0; } else { *phi = a*(r/prj->r0)/cthe; } return 0; } /*============================================================================ * PCO: polyconic projection. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "PCO" * prj->flag PCO * prj->phi0 0.0 * prj->theta0 0.0 * prj->w[0] r0*(pi/180) * prj->w[1] 1/r0 * prj->w[2] 2*r0 * prj->prjfwd Pointer to pcofwd(). * prj->prjrev Pointer to pcorev(). *===========================================================================*/ int pcoset(prj) struct prjprm *prj; { strcpy(prj->code, "PCO"); prj->flag = PCO; prj->phi0 = 0.0; prj->theta0 = 0.0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 1.0; prj->w[1] = 1.0; prj->w[2] = 360.0/PI; } else { prj->w[0] = prj->r0*D2R; prj->w[1] = 1.0/prj->w[0]; prj->w[2] = 2.0*prj->r0; } prj->prjfwd = pcofwd; prj->prjrev = pcorev; return 0; } /*--------------------------------------------------------------------------*/ int pcofwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { double a, cthe, cotthe, sthe; if (prj->flag != PCO) { if (pcoset(prj)) return 1; } cthe = cosdeg (theta); sthe = sindeg (theta); a = phi*sthe; if (sthe == 0.0) { *x = prj->w[0]*phi; *y = 0.0; } else { cotthe = cthe/sthe; *x = prj->r0*cotthe*sindeg (a); *y = prj->r0*(cotthe*(1.0 - cosdeg (a)) + theta*D2R); } return 0; } /*--------------------------------------------------------------------------*/ int pcorev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { int j; double f, fneg, fpos, lambda, tanthe, theneg, thepos, w, xp, xx, ymthe, yp; const double tol = 1.0e-12; if (prj->flag != PCO) { if (pcoset(prj)) return 1; } w = fabs(y*prj->w[1]); if (w < tol) { *phi = x*prj->w[1]; *theta = 0.0; } else if (fabs(w-90.0) < tol) { *phi = 0.0; *theta = copysgni (90.0,y); } else { /* Iterative solution using weighted division of the interval. */ if (y > 0.0) { thepos = 90.0; } else { thepos = -90.0; } theneg = 0.0; xx = x*x; ymthe = y - prj->w[0]*thepos; fpos = xx + ymthe*ymthe; fneg = -999.0; for (j = 0; j < 64; j++) { if (fneg < -100.0) { /* Equal division of the interval. */ *theta = (thepos+theneg)/2.0; } else { /* Weighted division of the interval. */ lambda = fpos/(fpos-fneg); if (lambda < 0.1) { lambda = 0.1; } else if (lambda > 0.9) { lambda = 0.9; } *theta = thepos - lambda*(thepos-theneg); } /* Compute the residue. */ ymthe = y - prj->w[0]*(*theta); tanthe = tandeg (*theta); f = xx + ymthe*(ymthe - prj->w[2]/tanthe); /* Check for convergence. */ if (fabs(f) < tol) break; if (fabs(thepos-theneg) < tol) break; /* Redefine the interval. */ if (f > 0.0) { thepos = *theta; fpos = f; } else { theneg = *theta; fneg = f; } } xp = prj->r0 - ymthe*tanthe; yp = x*tanthe; if (xp == 0.0 && yp == 0.0) { *phi = 0.0; } else { *phi = atan2deg (yp, xp)/sindeg (*theta); } } return 0; } /*============================================================================ * TSC: tangential spherical cube projection. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "TSC" * prj->flag TSC * prj->phi0 0.0 * prj->theta0 0.0 * prj->w[0] r0*(pi/4) * prj->w[1] (4/pi)/r0 * prj->prjfwd Pointer to tscfwd(). * prj->prjrev Pointer to tscrev(). *===========================================================================*/ int tscset(prj) struct prjprm *prj; { strcpy(prj->code, "TSC"); prj->flag = TSC; prj->phi0 = 0.0; prj->theta0 = 0.0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 45.0; prj->w[1] = 1.0/45.0; } else { prj->w[0] = prj->r0*PI/4.0; prj->w[1] = 1.0/prj->w[0]; } prj->prjfwd = tscfwd; prj->prjrev = tscrev; return 0; } /*--------------------------------------------------------------------------*/ int tscfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { int face; double cthe, l, m, n, rho; double x0 = 0.0; double y0 = 0.0; double xf = 0.0; double yf = 0.0; const double tol = 1.0e-12; if (prj->flag != TSC) { if (tscset(prj)) return 1; } cthe = cosdeg (theta); l = cthe*cosdeg (phi); m = cthe*sindeg (phi); n = sindeg (theta); face = 0; rho = n; if (l > rho) { face = 1; rho = l; } if (m > rho) { face = 2; rho = m; } if (-l > rho) { face = 3; rho = -l; } if (-m > rho) { face = 4; rho = -m; } if (-n > rho) { face = 5; rho = -n; } if (face == 0) { xf = m/rho; yf = -l/rho; x0 = 0.0; y0 = 2.0; } else if (face == 1) { xf = m/rho; yf = n/rho; x0 = 0.0; y0 = 0.0; } else if (face == 2) { xf = -l/rho; yf = n/rho; x0 = 2.0; y0 = 0.0; } else if (face == 3) { xf = -m/rho; yf = n/rho; x0 = 4.0; y0 = 0.0; } else if (face == 4) { xf = l/rho; yf = n/rho; x0 = 6.0; y0 = 0.0; } else if (face == 5) { xf = m/rho; yf = l/rho; x0 = 0.0; y0 = -2.0; } if (fabs(xf) > 1.0) { if (fabs(xf) > 1.0+tol) { return 2; } xf = copysgn (1.0,xf); } if (fabs(yf) > 1.0) { if (fabs(yf) > 1.0+tol) { return 2; } yf = copysgn (1.0,yf); } *x = prj->w[0]*(xf + x0); *y = prj->w[0]*(yf + y0); return 0; } /*--------------------------------------------------------------------------*/ int tscrev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { double l, m, n, xf, yf; if (prj->flag != TSC) { if (tscset(prj)) return 1; } xf = x*prj->w[1]; yf = y*prj->w[1]; /* Check bounds. */ if (fabs(xf) <= 1.0) { if (fabs(yf) > 3.0) return 2; } else { if (fabs(xf) > 7.0) return 2; if (fabs(yf) > 1.0) return 2; } /* Map negative faces to the other side. */ if (xf < -1.0) xf += 8.0; /* Determine the face. */ if (xf > 5.0) { /* face = 4 */ xf = xf - 6.0; m = -1.0/sqrt(1.0 + xf*xf + yf*yf); l = -m*xf; n = -m*yf; } else if (xf > 3.0) { /* face = 3 */ xf = xf - 4.0; l = -1.0/sqrt(1.0 + xf*xf + yf*yf); m = l*xf; n = -l*yf; } else if (xf > 1.0) { /* face = 2 */ xf = xf - 2.0; m = 1.0/sqrt(1.0 + xf*xf + yf*yf); l = -m*xf; n = m*yf; } else if (yf > 1.0) { /* face = 0 */ yf = yf - 2.0; n = 1.0/sqrt(1.0 + xf*xf + yf*yf); l = -n*yf; m = n*xf; } else if (yf < -1.0) { /* face = 5 */ yf = yf + 2.0; n = -1.0/sqrt(1.0 + xf*xf + yf*yf); l = -n*yf; m = -n*xf; } else { /* face = 1 */ l = 1.0/sqrt(1.0 + xf*xf + yf*yf); m = l*xf; n = l*yf; } if (l == 0.0 && m == 0.0) { *phi = 0.0; } else { *phi = atan2deg (m, l); } *theta = asindeg (n); return 0; } /*============================================================================ * CSC: COBE quadrilateralized spherical cube projection. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "CSC" * prj->flag CSC * prj->phi0 0.0 * prj->theta0 0.0 * prj->w[0] r0*(pi/4) * prj->w[1] (4/pi)/r0 * prj->prjfwd Pointer to cscfwd(). * prj->prjrev Pointer to cscrev(). *===========================================================================*/ int cscset(prj) struct prjprm *prj; { strcpy(prj->code, "CSC"); prj->flag = CSC; prj->phi0 = 0.0; prj->theta0 = 0.0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 45.0; prj->w[1] = 1.0/45.0; } else { prj->w[0] = prj->r0*PI/4.0; prj->w[1] = 1.0/prj->w[0]; } prj->prjfwd = cscfwd; prj->prjrev = cscrev; return 0; } /*--------------------------------------------------------------------------*/ int cscfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { int face; double cthe, eta, l, m, n, rho, xi; const float tol = 1.0e-7; float a, a2, a2b2, a4, ab, b, b2, b4, ca2, cb2; float x0 = 0.0; float y0 = 0.0; float xf = 0.0; float yf = 0.0; const float gstar = 1.37484847732; const float mm = 0.004869491981; const float gamma = -0.13161671474; const float omega1 = -0.159596235474; const float d0 = 0.0759196200467; const float d1 = -0.0217762490699; const float c00 = 0.141189631152; const float c10 = 0.0809701286525; const float c01 = -0.281528535557; const float c11 = 0.15384112876; const float c20 = -0.178251207466; const float c02 = 0.106959469314; if (prj->flag != CSC) { if (cscset(prj)) return 1; } cthe = cosdeg (theta); l = cthe*cosdeg (phi); m = cthe*sindeg (phi); n = sindeg (theta); face = 0; rho = n; if (l > rho) { face = 1; rho = l; } if (m > rho) { face = 2; rho = m; } if (-l > rho) { face = 3; rho = -l; } if (-m > rho) { face = 4; rho = -m; } if (-n > rho) { face = 5; rho = -n; } if (face == 0) { xi = m; eta = -l; x0 = 0.0; y0 = 2.0; } else if (face == 1) { xi = m; eta = n; x0 = 0.0; y0 = 0.0; } else if (face == 2) { xi = -l; eta = n; x0 = 2.0; y0 = 0.0; } else if (face == 3) { xi = -m; eta = n; x0 = 4.0; y0 = 0.0; } else if (face == 4) { xi = l; eta = n; x0 = 6.0; y0 = 0.0; } else if (face == 5) { xi = m; eta = l; x0 = 0.0; y0 = -2.0; } a = xi/rho; b = eta/rho; a2 = a*a; b2 = b*b; ca2 = 1.0 - a2; cb2 = 1.0 - b2; /* Avoid floating underflows. */ ab = fabs(a*b); a4 = (a2 > 1.0e-16) ? a2*a2 : 0.0; b4 = (b2 > 1.0e-16) ? b2*b2 : 0.0; a2b2 = (ab > 1.0e-16) ? a2*b2 : 0.0; xf = a*(a2 + ca2*(gstar + b2*(gamma*ca2 + mm*a2 + cb2*(c00 + c10*a2 + c01*b2 + c11*a2b2 + c20*a4 + c02*b4)) + a2*(omega1 - ca2*(d0 + d1*a2)))); yf = b*(b2 + cb2*(gstar + a2*(gamma*cb2 + mm*b2 + ca2*(c00 + c10*b2 + c01*a2 + c11*a2b2 + c20*b4 + c02*a4)) + b2*(omega1 - cb2*(d0 + d1*b2)))); if (fabs(xf) > 1.0) { if (fabs(xf) > 1.0+tol) { return 2; } xf = copysgn (1.0,xf); } if (fabs(yf) > 1.0) { if (fabs(yf) > 1.0+tol) { return 2; } yf = copysgn (1.0,yf); } *x = prj->w[0]*(x0 + xf); *y = prj->w[0]*(y0 + yf); return 0; } /*--------------------------------------------------------------------------*/ int cscrev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { int face; double l = 0.0; double m = 0.0; double n = 0.0; float a, b, xf, xx, yf, yy, z0, z1, z2, z3, z4, z5, z6; const float p00 = -0.27292696; const float p10 = -0.07629969; const float p20 = -0.22797056; const float p30 = 0.54852384; const float p40 = -0.62930065; const float p50 = 0.25795794; const float p60 = 0.02584375; const float p01 = -0.02819452; const float p11 = -0.01471565; const float p21 = 0.48051509; const float p31 = -1.74114454; const float p41 = 1.71547508; const float p51 = -0.53022337; const float p02 = 0.27058160; const float p12 = -0.56800938; const float p22 = 0.30803317; const float p32 = 0.98938102; const float p42 = -0.83180469; const float p03 = -0.60441560; const float p13 = 1.50880086; const float p23 = -0.93678576; const float p33 = 0.08693841; const float p04 = 0.93412077; const float p14 = -1.41601920; const float p24 = 0.33887446; const float p05 = -0.63915306; const float p15 = 0.52032238; const float p06 = 0.14381585; if (prj->flag != CSC) { if (cscset(prj)) return 1; } xf = x*prj->w[1]; yf = y*prj->w[1]; /* Check bounds. */ if (fabs(xf) <= 1.0) { if (fabs(yf) > 3.0) return 2; } else { if (fabs(xf) > 7.0) return 2; if (fabs(yf) > 1.0) return 2; } /* Map negative faces to the other side. */ if (xf < -1.0) xf += 8.0; /* Determine the face. */ if (xf > 5.0) { face = 4; xf = xf - 6.0; } else if (xf > 3.0) { face = 3; xf = xf - 4.0; } else if (xf > 1.0) { face = 2; xf = xf - 2.0; } else if (yf > 1.0) { face = 0; yf = yf - 2.0; } else if (yf < -1.0) { face = 5; yf = yf + 2.0; } else { face = 1; } xx = xf*xf; yy = yf*yf; z0 = p00 + xx*(p10 + xx*(p20 + xx*(p30 + xx*(p40 + xx*(p50 + xx*(p60)))))); z1 = p01 + xx*(p11 + xx*(p21 + xx*(p31 + xx*(p41 + xx*(p51))))); z2 = p02 + xx*(p12 + xx*(p22 + xx*(p32 + xx*(p42)))); z3 = p03 + xx*(p13 + xx*(p23 + xx*(p33))); z4 = p04 + xx*(p14 + xx*(p24)); z5 = p05 + xx*(p15); z6 = p06; a = z0 + yy*(z1 + yy*(z2 + yy*(z3 + yy*(z4 + yy*(z5 + yy*z6))))); a = xf + xf*(1.0 - xx)*a; z0 = p00 + yy*(p10 + yy*(p20 + yy*(p30 + yy*(p40 + yy*(p50 + yy*(p60)))))); z1 = p01 + yy*(p11 + yy*(p21 + yy*(p31 + yy*(p41 + yy*(p51))))); z2 = p02 + yy*(p12 + yy*(p22 + yy*(p32 + yy*(p42)))); z3 = p03 + yy*(p13 + yy*(p23 + yy*(p33))); z4 = p04 + yy*(p14 + yy*(p24)); z5 = p05 + yy*(p15); z6 = p06; b = z0 + xx*(z1 + xx*(z2 + xx*(z3 + xx*(z4 + xx*(z5 + xx*z6))))); b = yf + yf*(1.0 - yy)*b; if (face == 0) { n = 1.0/sqrt(a*a + b*b + 1.0); l = -b*n; m = a*n; } else if (face == 1) { l = 1.0/sqrt(a*a + b*b + 1.0); m = a*l; n = b*l; } else if (face == 2) { m = 1.0/sqrt(a*a + b*b + 1.0); l = -a*m; n = b*m; } else if (face == 3) { l = -1.0/sqrt(a*a + b*b + 1.0); m = a*l; n = -b*l; } else if (face == 4) { m = -1.0/sqrt(a*a + b*b + 1.0); l = -a*m; n = -b*m; } else if (face == 5) { n = -1.0/sqrt(a*a + b*b + 1.0); l = -b*n; m = -a*n; } if (l == 0.0 && m == 0.0) { *phi = 0.0; } else { *phi = atan2deg (m, l); } *theta = asindeg (n); return 0; } /*============================================================================ * QSC: quadrilaterilized spherical cube projection. * * Given and/or returned: * prj->r0 r0; reset to 180/pi if 0. * * Returned: * prj->code "QSC" * prj->flag QSC * prj->phi0 0.0 * prj->theta0 0.0 * prj->w[0] r0*(pi/4) * prj->w[1] (4/pi)/r0 * prj->prjfwd Pointer to qscfwd(). * prj->prjrev Pointer to qscrev(). *===========================================================================*/ int qscset(prj) struct prjprm *prj; { strcpy(prj->code, "QSC"); prj->flag = QSC; prj->phi0 = 0.0; prj->theta0 = 0.0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 45.0; prj->w[1] = 1.0/45.0; } else { prj->w[0] = prj->r0*PI/4.0; prj->w[1] = 1.0/prj->w[0]; } prj->prjfwd = qscfwd; prj->prjrev = qscrev; return 0; } /*--------------------------------------------------------------------------*/ int qscfwd(phi, theta, prj, x, y) const double phi, theta; struct prjprm *prj; double *x, *y; { int face; double cthe, l, m, n, omega, p, rho, rhu, t, tau; double xi = 0.0; double eta = 0.0; double x0 = 0.0; double y0 = 0.0; double xf = 0.0; double yf = 0.0; const double tol = 1.0e-12; if (prj->flag != QSC) { if (qscset(prj)) return 1; } if (fabs(theta) == 90.0) { *x = 0.0; *y = copysgn (2.0*prj->w[0],theta); return 0; } cthe = cosdeg (theta); l = cthe*cosdeg (phi); m = cthe*sindeg (phi); n = sindeg (theta); face = 0; rho = n; if (l > rho) { face = 1; rho = l; } if (m > rho) { face = 2; rho = m; } if (-l > rho) { face = 3; rho = -l; } if (-m > rho) { face = 4; rho = -m; } if (-n > rho) { face = 5; rho = -n; } rhu = 1.0 - rho; if (face == 0) { xi = m; eta = -l; if (rhu < 1.0e-8) { /* Small angle formula. */ t = (90.0 - theta)*D2R; rhu = t*t/2.0; } x0 = 0.0; y0 = 2.0; } else if (face == 1) { xi = m; eta = n; if (rhu < 1.0e-8) { /* Small angle formula. */ t = theta*D2R; p = fmod(phi,360.0); if (p < -180.0) p += 360.0; if (p > 180.0) p -= 360.0; p *= D2R; rhu = (p*p + t*t)/2.0; } x0 = 0.0; y0 = 0.0; } else if (face == 2) { xi = -l; eta = n; if (rhu < 1.0e-8) { /* Small angle formula. */ t = theta*D2R; p = fmod(phi,360.0); if (p < -180.0) p += 360.0; p = (90.0 - p)*D2R; rhu = (p*p + t*t)/2.0; } x0 = 2.0; y0 = 0.0; } else if (face == 3) { xi = -m; eta = n; if (rhu < 1.0e-8) { /* Small angle formula. */ t = theta*D2R; p = fmod(phi,360.0); if (p < 0.0) p += 360.0; p = (180.0 - p)*D2R; rhu = (p*p + t*t)/2.0; } x0 = 4.0; y0 = 0.0; } else if (face == 4) { xi = l; eta = n; if (rhu < 1.0e-8) { /* Small angle formula. */ t = theta*D2R; p = fmod(phi,360.0); if (p > 180.0) p -= 360.0; p *= (90.0 + p)*D2R; rhu = (p*p + t*t)/2.0; } x0 = 6; y0 = 0.0; } else if (face == 5) { xi = m; eta = l; if (rhu < 1.0e-8) { /* Small angle formula. */ t = (90.0 + theta)*D2R; rhu = t*t/2.0; } x0 = 0.0; y0 = -2; } if (xi == 0.0 && eta == 0.0) { xf = 0.0; yf = 0.0; } else if (-xi >= fabs(eta)) { omega = eta/xi; tau = 1.0 + omega*omega; xf = -sqrt(rhu/(1.0-1.0/sqrt(1.0+tau))); yf = (xf/15.0)*(atandeg (omega) - asindeg (omega/sqrt(tau+tau))); } else if (xi >= fabs(eta)) { omega = eta/xi; tau = 1.0 + omega*omega; xf = sqrt(rhu/(1.0-1.0/sqrt(1.0+tau))); yf = (xf/15.0)*(atandeg (omega) - asindeg (omega/sqrt(tau+tau))); } else if (-eta > fabs(xi)) { omega = xi/eta; tau = 1.0 + omega*omega; yf = -sqrt(rhu/(1.0-1.0/sqrt(1.0+tau))); xf = (yf/15.0)*(atandeg (omega) - asindeg (omega/sqrt(tau+tau))); } else if (eta > fabs(xi)) { omega = xi/eta; tau = 1.0 + omega*omega; yf = sqrt(rhu/(1.0-1.0/sqrt(1.0+tau))); xf = (yf/15.0)*(atandeg (omega) - asindeg (omega/sqrt(tau+tau))); } if (fabs(xf) > 1.0) { if (fabs(xf) > 1.0+tol) { return 2; } xf = copysgn (1.0,xf); } if (fabs(yf) > 1.0) { if (fabs(yf) > 1.0+tol) { return 2; } yf = copysgn (1.0,yf); } *x = prj->w[0]*(xf + x0); *y = prj->w[0]*(yf + y0); return 0; } /*--------------------------------------------------------------------------*/ int qscrev(x, y, prj, phi, theta) const double x, y; struct prjprm *prj; double *phi, *theta; { int direct, face; double omega, rho, rhu, tau, xf, yf, w; double l = 0.0; double m = 0.0; double n = 0.0; const double tol = 1.0e-12; if (prj->flag != QSC) { if (qscset(prj)) return 1; } xf = x*prj->w[1]; yf = y*prj->w[1]; /* Check bounds. */ if (fabs(xf) <= 1.0) { if (fabs(yf) > 3.0) return 2; } else { if (fabs(xf) > 7.0) return 2; if (fabs(yf) > 1.0) return 2; } /* Map negative faces to the other side. */ if (xf < -1.0) xf += 8.0; /* Determine the face. */ if (xf > 5.0) { face = 4; xf = xf - 6.0; } else if (xf > 3.0) { face = 3; xf = xf - 4.0; } else if (xf > 1.0) { face = 2; xf = xf - 2.0; } else if (yf > 1.0) { face = 0; yf = yf - 2.0; } else if (yf < -1.0) { face = 5; yf = yf + 2.0; } else { face = 1; } direct = (fabs(xf) > fabs(yf)); if (direct) { if (xf == 0.0) { omega = 0.0; tau = 1.0; rho = 1.0; rhu = 0.0; } else { w = 15.0*yf/xf; omega = sindeg (w)/(cosdeg (w) - SQRT2INV); tau = 1.0 + omega*omega; rhu = xf*xf*(1.0 - 1.0/sqrt(1.0 + tau)); rho = 1.0 - rhu; } } else { if (yf == 0.0) { omega = 0.0; tau = 1.0; rho = 1.0; rhu = 0.0; } else { w = 15.0*xf/yf; omega = sindeg (w)/(cosdeg (w) - SQRT2INV); tau = 1.0 + omega*omega; rhu = yf*yf*(1.0 - 1.0/sqrt(1.0 + tau)); rho = 1.0 - rhu; } } if (rho < -1.0) { if (rho < -1.0-tol) { return 2; } rho = -1.0; rhu = 2.0; w = 0.0; } else { w = sqrt(rhu*(2.0-rhu)/tau); } if (face == 0) { n = rho; if (direct) { m = w; if (xf < 0.0) m = -m; l = -m*omega; } else { l = w; if (yf > 0.0) l = -l; m = -l*omega; } } else if (face == 1) { l = rho; if (direct) { m = w; if (xf < 0.0) m = -m; n = m*omega; } else { n = w; if (yf < 0.0) n = -n; m = n*omega; } } else if (face == 2) { m = rho; if (direct) { l = w; if (xf > 0.0) l = -l; n = -l*omega; } else { n = w; if (yf < 0.0) n = -n; l = -n*omega; } } else if (face == 3) { l = -rho; if (direct) { m = w; if (xf > 0.0) m = -m; n = -m*omega; } else { n = w; if (yf < 0.0) n = -n; m = -n*omega; } } else if (face == 4) { m = -rho; if (direct) { l = w; if (xf < 0.0) l = -l; n = l*omega; } else { n = w; if (yf < 0.0) n = -n; l = n*omega; } } else if (face == 5) { n = -rho; if (direct) { m = w; if (xf < 0.0) m = -m; l = m*omega; } else { l = w; if (yf < 0.0) l = -l; m = l*omega; } } if (l == 0.0 && m == 0.0) { *phi = 0.0; } else { *phi = atan2deg (m, l); } *theta = asindeg (n); return 0; } /* This routine comes from E. Bertin sextractor-2.8.6 */ int raw_to_pv(struct prjprm *prj, double x, double y, double *xo, double *yo) { int k; double *a,*b, r,r3,r5,r7,xy,x2,x3,x4,x5,x6,x7,y2,y3,y4,y5,y6,y7,xp,yp; k=prj->npv; a = prj->ppv+MAXPV; /* Latitude comes first for compatibility */ b = prj->ppv; /* Longitude */ xp = *(a++); xp += *(a++)*x; yp = *(b++); yp += *(b++)*y; if (!--k) goto poly_end; xp += *(a++)*y; yp += *(b++)*x; if (!--k) goto poly_end; r = sqrt(x*x + y*y); xp += *(a++)*r; yp += *(b++)*r; if (!--k) goto poly_end; xp += *(a++)*(x2=x*x); yp += *(b++)*(y2=y*y); if (!--k) goto poly_end; xp += *(a++)*(xy=x*y); yp += *(b++)*xy; if (!--k) goto poly_end; xp += *(a++)*y2; yp += *(b++)*x2; if (!--k) goto poly_end; xp += *(a++)*(x3=x*x2); yp += *(b++)*(y3=y*y2); if (!--k) goto poly_end; xp += *(a++)*x2*y; yp += *(b++)*y2*x; if (!--k) goto poly_end; xp += *(a++)*x*y2; yp += *(b++)*y*x2; if (!--k) goto poly_end; xp += *(a++)*y3; yp += *(b++)*x3; if (!--k) goto poly_end; xp += *(a++)*(r3=r*r*r); yp += *(b++)*r3; if (!--k) goto poly_end; xp += *(a++)*(x4=x2*x2); yp += *(b++)*(y4=y2*y2); if (!--k) goto poly_end; xp += *(a++)*x3*y; yp += *(b++)*y3*x; if (!--k) goto poly_end; xp += *(a++)*x2*y2; yp += *(b++)*x2*y2; if (!--k) goto poly_end; xp += *(a++)*x*y3; yp += *(b++)*y*x3; if (!--k) goto poly_end; xp += *(a++)*y4; yp += *(b++)*x4; if (!--k) goto poly_end; xp += *(a++)*(x5=x4*x); yp += *(b++)*(y5=y4*y); if (!--k) goto poly_end; xp += *(a++)*x4*y; yp += *(b++)*y4*x; if (!--k) goto poly_end; xp += *(a++)*x3*y2; yp += *(b++)*y3*x2; if (!--k) goto poly_end; xp += *(a++)*x2*y3; yp += *(b++)*y2*x3; if (!--k) goto poly_end; xp += *(a++)*x*y4; yp += *(b++)*y*x4; if (!--k) goto poly_end; xp += *(a++)*y5; yp += *(b++)*x5; if (!--k) goto poly_end; xp += *(a++)*(r5=r3*r*r); yp += *(b++)*r5; if (!--k) goto poly_end; xp += *(a++)*(x6=x5*x); yp += *(b++)*(y6=y5*y); if (!--k) goto poly_end; xp += *(a++)*x5*y; yp += *(b++)*y5*x; if (!--k) goto poly_end; xp += *(a++)*x4*y2; yp += *(b++)*y4*x2; if (!--k) goto poly_end; xp += *(a++)*x3*y3; yp += *(b++)*y3*x3; if (!--k) goto poly_end; xp += *(a++)*x2*y4; yp += *(b++)*y2*x4; if (!--k) goto poly_end; xp += *(a++)*x*y5; yp += *(b++)*y*x5; if (!--k) goto poly_end; xp += *(a++)*y6; yp += *(b++)*x6; if (!--k) goto poly_end; xp += *(a++)*(x7=x6*x); yp += *(b++)*(y7=y6*y); if (!--k) goto poly_end; xp += *(a++)*x6*y; yp += *(b++)*y6*x; if (!--k) goto poly_end; xp += *(a++)*x5*y2; yp += *(b++)*y5*x2; if (!--k) goto poly_end; xp += *(a++)*x4*y3; yp += *(b++)*y4*x3; if (!--k) goto poly_end; xp += *(a++)*x3*y4; yp += *(b++)*y3*x4; if (!--k) goto poly_end; xp += *(a++)*x2*y5; yp += *(b++)*y2*x5; if (!--k) goto poly_end; xp += *(a++)*x*y6; yp += *(b++)*y*x6; if (!--k) goto poly_end; xp += *(a++)*y7; yp += *(b++)*x7; if (!--k) goto poly_end; xp += *a*(r7=r5*r*r); yp += *b*r7; poly_end: *xo = xp; *yo = yp; return 0; } /* Dec 20 1999 Doug Mink - Change cosd() and sind() to cosdeg() and sindeg() * Dec 20 1999 Doug Mink - Include wcslib.h, which includes proj.h, wcsmath.h * Dec 20 1999 Doug Mink - Define copysign only if it is not defined * Dec 20 1999 Doug Mink - tanfwd() returns error if s<=0.0, not only if s==0.0 * * Jun 2 2000 Doug Mink - include stdlib.h to get abs() * * Feb 15 2001 Doug Mink - update zearev() for WCSLIB 2.6 * Sep 19 2001 Doug Mink - Make above changes for WCSLIB 2.7 * * Mar 15 2002 Doug Mink - Make above changes for WCSLIB 2.8.2 * * Feb 3 2003 Doug Mink - Use locally defined copysgn() and copysgni(), * not copysign() * Apr 1 2003 Doug Mink - include string.h for strcpy() and strcmp() * * Mar 14 2011 Doug Mink - If no coefficients in ZPN, make ARC * Mar 14 2011 Doug Mink - Add Emmanuel Bertin's TAN polynomial from Ed Los */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/cel.c0000664000175000017500000003572513047255533020404 0ustar mattymatty00000000000000/*============================================================================= * * WCSLIB - an implementation of the FITS WCS proposal. * Copyright (C) 1995-2002, Mark Calabretta * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Correspondence concerning WCSLIB may be directed to: * Internet email: mcalabre@atnf.csiro.au * Postal address: Dr. Mark Calabretta, * Australia Telescope National Facility, * P.O. Box 76, * Epping, NSW, 2121, * AUSTRALIA * *============================================================================= * * C routines which implement the FITS World Coordinate System (WCS) * convention. * * Summary of routines * ------------------- * These routines are provided as drivers for the lower level spherical * coordinate transformation and projection routines. There are separate * driver routines for the forward, celfwd(), and reverse, celrev(), * transformations. * * An initialization routine, celset(), computes intermediate values from * the transformation parameters but need not be called explicitly - see the * explanation of cel.flag below. * * * Initialization routine; celset() * -------------------------------- * Initializes members of a celprm data structure which hold intermediate * values. Note that this routine need not be called directly; it will be * invoked by celfwd() and celrev() if the "flag" structure member is * anything other than a predefined magic value. * * Given: * pcode[4] const char * WCS projection code (see below). * * Given and returned: * cel celprm* Spherical coordinate transformation parameters * (see below). * prj prjprm* Projection parameters (usage is described in the * prologue to "proj.c"). * * Function return value: * int Error status * 0: Success. * 1: Invalid coordinate transformation parameters. * 2: Ill-conditioned coordinate transformation * parameters. * * Forward transformation; celfwd() * -------------------------------- * Compute (x,y) coordinates in the plane of projection from celestial * coordinates (lng,lat). * * Given: * pcode[4] const char * WCS projection code (see below). * lng,lat const double * Celestial longitude and latitude of the projected * point, in degrees. * * Given and returned: * cel celprm* Spherical coordinate transformation parameters * (see below). * * Returned: * phi, double* Longitude and latitude in the native coordinate * theta system of the projection, in degrees. * * Given and returned: * prj prjprm* Projection parameters (usage is described in the * prologue to "proj.c"). * * Returned: * x,y double* Projected coordinates, "degrees". * * Function return value: * int Error status * 0: Success. * 1: Invalid coordinate transformation parameters. * 2: Invalid projection parameters. * 3: Invalid value of (lng,lat). * * Reverse transformation; celrev() * -------------------------------- * Compute the celestial coordinates (lng,lat) of the point with projected * coordinates (x,y). * * Given: * pcode[4] const char * WCS projection code (see below). * x,y const double * Projected coordinates, "degrees". * * Given and returned: * prj prjprm* Projection parameters (usage is described in the * prologue to "proj.c"). * * Returned: * phi, double* Longitude and latitude in the native coordinate * theta system of the projection, in degrees. * * Given and returned: * cel celprm* Spherical coordinate transformation parameters * (see below). * * Returned: * lng,lat double* Celestial longitude and latitude of the projected * point, in degrees. * * Function return value: * int Error status * 0: Success. * 1: Invalid coordinate transformation parameters. * 2: Invalid projection parameters. * 3: Invalid value of (x,y). * * Coordinate transformation parameters * ------------------------------------ * The celprm struct consists of the following: * * int flag * The celprm struct contains pointers to the forward and reverse * projection routines as well as intermediaries computed from the * reference coordinates (see below). Whenever the projection code * (pcode) or any of ref[4] are set or changed then this flag must be * set to zero to signal the initialization routine, celset(), to * redetermine the function pointers and recompute intermediaries. * Once this has been done pcode itself is ignored. * * double ref[4] * The first pair of values should be set to the celestial longitude * and latitude (usually right ascension and declination) of the * reference point of the projection. These are given by the CRVALn * keywords in FITS. * * The second pair of values are the native longitude of the celestial * pole and the celestial latitude of the native pole and correspond to * FITS keywords LONPOLE and LATPOLE. * * LONPOLE defaults to 0 degrees if the celestial latitude of the * reference point of the projection is greater than the native * latitude, otherwise 180 degrees. (This is the condition for the * celestial latitude to increase in the same direction as the native * latitude at the reference point.) ref[2] may be set to 999.0 to * indicate that the correct default should be substituted. * * In some circumstances the celestial latitude of the native pole may * be determined by the first three values only to within a sign and * LATPOLE is used to choose between the two solutions. LATPOLE is * set in ref[3] and the solution closest to this value is used to * reset ref[3]. It is therefore legitimate, for example, to set * ref[3] to 999.0 to choose the more northerly solution - the default * if the LATPOLE card is omitted from the FITS header. For the * special case where the reference point of the projection is at * native latitude zero, its celestial latitude is zero, and * LONPOLE = +/- 90 then the celestial latitude of the pole is not * determined by the first three reference values and LATPOLE * specifies it completely. * * The remaining members of the celprm struct are maintained by the * initialization routines and should not be modified. This is done for the * sake of efficiency and to allow an arbitrary number of contexts to be * maintained simultaneously. * * double euler[5] * Euler angles and associated intermediaries derived from the * coordinate reference values. * * * WCS projection codes * -------------------- * Zenithals/azimuthals: * AZP: zenithal/azimuthal perspective * TAN: gnomonic * STG: stereographic * SIN: synthesis (generalized orthographic) * ARC: zenithal/azimuthal equidistant * ZPN: zenithal/azimuthal polynomial * ZEA: zenithal/azimuthal equal area * AIR: Airy * * Cylindricals: * CYP: cylindrical perspective * CEA: cylindrical equal area * CAR: Cartesian * MER: Mercator * * Pseudo-cylindricals: * SFL: Sanson-Flamsteed * PAR: parabolic * MOL: Mollweide * * Conventional: * AIT: Hammer-Aitoff * * Conics: * COP: conic perspective * COD: conic equidistant * COE: conic equal area * COO: conic orthomorphic * * Polyconics: * BON: Bonne * PCO: polyconic * * Quad-cubes: * TSC: tangential spherical cube * CSC: COBE quadrilateralized spherical cube * QSC: quadrilateralized spherical cube * * Author: Mark Calabretta, Australia Telescope National Facility * $Id: cel.c,v 2.14 2002/04/03 01:25:29 mcalabre Exp $ *===========================================================================*/ #include #include #include "wcslib.h" /* Map error number to error message for each function. */ const char *celset_errmsg[] = { 0, "Invalid coordinate transformation parameters", "Ill-conditioned coordinate transformation parameters"}; const char *celfwd_errmsg[] = { 0, "Invalid coordinate transformation parameters", "Invalid projection parameters", "Invalid value of (lng,lat)"}; const char *celrev_errmsg[] = { 0, "Invalid coordinate transformation parameters", "Invalid projection parameters", "Invalid value of (x,y)"}; int celset(pcode, cel, prj) const char pcode[4]; struct celprm *cel; struct prjprm *prj; { int dophip; const double tol = 1.0e-10; double clat0, cphip, cthe0, slat0, sphip, sthe0; double latp, latp1, latp2; double u, v, x, y, z; /* Initialize the projection driver routines. */ if (prjset(pcode, prj)) { return 1; } /* Set default for native longitude of the celestial pole? */ dophip = (cel->ref[2] == 999.0); /* Compute celestial coordinates of the native pole. */ if (prj->theta0 == 90.0) { /* Reference point is at the native pole. */ if (dophip) { /* Set default for longitude of the celestial pole. */ cel->ref[2] = 180.0; } latp = cel->ref[1]; cel->ref[3] = latp; cel->euler[0] = cel->ref[0]; cel->euler[1] = 90.0 - latp; } else { /* Reference point away from the native pole. */ /* Set default for longitude of the celestial pole. */ if (dophip) { cel->ref[2] = (cel->ref[1] < prj->theta0) ? 180.0 : 0.0; } clat0 = cosdeg (cel->ref[1]); slat0 = sindeg (cel->ref[1]); cphip = cosdeg (cel->ref[2]); sphip = sindeg (cel->ref[2]); cthe0 = cosdeg (prj->theta0); sthe0 = sindeg (prj->theta0); x = cthe0*cphip; y = sthe0; z = sqrt(x*x + y*y); if (z == 0.0) { if (slat0 != 0.0) { return 1; } /* latp determined by LATPOLE in this case. */ latp = cel->ref[3]; } else { if (fabs(slat0/z) > 1.0) { return 1; } u = atan2deg (y,x); v = acosdeg (slat0/z); latp1 = u + v; if (latp1 > 180.0) { latp1 -= 360.0; } else if (latp1 < -180.0) { latp1 += 360.0; } latp2 = u - v; if (latp2 > 180.0) { latp2 -= 360.0; } else if (latp2 < -180.0) { latp2 += 360.0; } if (fabs(cel->ref[3]-latp1) < fabs(cel->ref[3]-latp2)) { if (fabs(latp1) < 90.0+tol) { latp = latp1; } else { latp = latp2; } } else { if (fabs(latp2) < 90.0+tol) { latp = latp2; } else { latp = latp1; } } cel->ref[3] = latp; } cel->euler[1] = 90.0 - latp; z = cosdeg (latp)*clat0; if (fabs(z) < tol) { if (fabs(clat0) < tol) { /* Celestial pole at the reference point. */ cel->euler[0] = cel->ref[0]; cel->euler[1] = 90.0 - prj->theta0; } else if (latp > 0.0) { /* Celestial pole at the native north pole.*/ cel->euler[0] = cel->ref[0] + cel->ref[2] - 180.0; cel->euler[1] = 0.0; } else if (latp < 0.0) { /* Celestial pole at the native south pole. */ cel->euler[0] = cel->ref[0] - cel->ref[2]; cel->euler[1] = 180.0; } } else { x = (sthe0 - sindeg (latp)*slat0)/z; y = sphip*cthe0/clat0; if (x == 0.0 && y == 0.0) { return 1; } cel->euler[0] = cel->ref[0] - atan2deg (y,x); } /* Make euler[0] the same sign as ref[0]. */ if (cel->ref[0] >= 0.0) { if (cel->euler[0] < 0.0) cel->euler[0] += 360.0; } else { if (cel->euler[0] > 0.0) cel->euler[0] -= 360.0; } } cel->euler[2] = cel->ref[2]; cel->euler[3] = cosdeg (cel->euler[1]); cel->euler[4] = sindeg (cel->euler[1]); cel->flag = CELSET; /* Check for ill-conditioned parameters. */ if (fabs(latp) > 90.0+tol) { return 2; } return 0; } /*--------------------------------------------------------------------------*/ int celfwd(pcode, lng, lat, cel, phi, theta, prj, x, y) const char pcode[4]; const double lng, lat; struct celprm *cel; double *phi, *theta; struct prjprm *prj; double *x, *y; { int err; if (cel->flag != CELSET) { if (celset(pcode, cel, prj)) return 1; } /* Compute native coordinates. */ sphfwd(lng, lat, cel->euler, phi, theta); /* Apply forward projection. */ if ((err = prj->prjfwd(*phi, *theta, prj, x, y))) { return err == 1 ? 2 : 3; } return 0; } /*--------------------------------------------------------------------------*/ int celrev(pcode, x, y, prj, phi, theta, cel, lng, lat) const char pcode[4]; const double x, y; struct prjprm *prj; double *phi, *theta; struct celprm *cel; double *lng, *lat; { int err; if (cel->flag != CELSET) { if(celset(pcode, cel, prj)) return 1; } /* Apply reverse projection. */ if ((err = prj->prjrev(x, y, prj, phi, theta))) { return err == 1 ? 2 : 3; } /* Compute native coordinates. */ sphrev(*phi, *theta, cel->euler, lng, lat); return 0; } /* Dec 20 1999 Doug Mink - Change cosd() and sind() to cosdeg() and sindeg() * Dec 20 1999 Doug Mink - Include wcslib.h, which includes wcsmath.h and cel.h * * Dec 18 2000 Doug Mink - Include string.h for strcmp() * * Mar 20 2001 Doug Mink - Add () around err assignments in if statements * Sep 19 2001 Doug Mink - Add above changes to WCSLIB-2.7 cel.c * * Mar 12 2002 Doug Mink - Add changes to WCSLIB-2.8.2 cel.c */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/wcs_wrap.c0000664000175000017500000131245413047255533021464 0ustar mattymatty00000000000000/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.12 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make * changes to this file unless you know what you are doing--modify the SWIG * interface file instead. * ----------------------------------------------------------------------------- */ #define SWIGPYTHON #define SWIG_PYTHON_DIRECTOR_NO_VTABLE /* ----------------------------------------------------------------------------- * This section contains generic SWIG labels for method/variable * declarations/attributes, and other compiler dependent labels. * ----------------------------------------------------------------------------- */ /* template workaround for compilers that cannot correctly implement the C++ standard */ #ifndef SWIGTEMPLATEDISAMBIGUATOR # if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560) # define SWIGTEMPLATEDISAMBIGUATOR template # elif defined(__HP_aCC) /* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */ /* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */ # define SWIGTEMPLATEDISAMBIGUATOR template # else # define SWIGTEMPLATEDISAMBIGUATOR # endif #endif /* inline attribute */ #ifndef SWIGINLINE # if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) # define SWIGINLINE inline # else # define SWIGINLINE # endif #endif /* attribute recognised by some compilers to avoid 'unused' warnings */ #ifndef SWIGUNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif # elif defined(__ICC) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif #endif #ifndef SWIG_MSC_UNSUPPRESS_4505 # if defined(_MSC_VER) # pragma warning(disable : 4505) /* unreferenced local function has been removed */ # endif #endif #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) # else # define SWIGUNUSEDPARM(p) p SWIGUNUSED # endif #endif /* internal SWIG method */ #ifndef SWIGINTERN # define SWIGINTERN static SWIGUNUSED #endif /* internal inline SWIG method */ #ifndef SWIGINTERNINLINE # define SWIGINTERNINLINE SWIGINTERN SWIGINLINE #endif /* exporting methods */ #if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) # ifndef GCC_HASCLASSVISIBILITY # define GCC_HASCLASSVISIBILITY # endif #endif #ifndef SWIGEXPORT # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # if defined(STATIC_LINKED) # define SWIGEXPORT # else # define SWIGEXPORT __declspec(dllexport) # endif # else # if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) # define SWIGEXPORT __attribute__ ((visibility("default"))) # else # define SWIGEXPORT # endif # endif #endif /* calling conventions for Windows */ #ifndef SWIGSTDCALL # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # define SWIGSTDCALL __stdcall # else # define SWIGSTDCALL # endif #endif /* Deal with Microsoft's attempt at deprecating C standard runtime functions */ #if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) # define _CRT_SECURE_NO_DEPRECATE #endif /* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */ #if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE) # define _SCL_SECURE_NO_DEPRECATE #endif #if defined(_DEBUG) && defined(SWIG_PYTHON_INTERPRETER_NO_DEBUG) /* Use debug wrappers with the Python release dll */ # undef _DEBUG # include # define _DEBUG #else # include #endif /* ----------------------------------------------------------------------------- * swigrun.swg * * This file contains generic C API SWIG runtime support for pointer * type checking. * ----------------------------------------------------------------------------- */ /* This should only be incremented when either the layout of swig_type_info changes, or for whatever reason, the runtime changes incompatibly */ #define SWIG_RUNTIME_VERSION "4" /* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ #ifdef SWIG_TYPE_TABLE # define SWIG_QUOTE_STRING(x) #x # define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x) # define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE) #else # define SWIG_TYPE_TABLE_NAME #endif /* You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for creating a static or dynamic library from the SWIG runtime code. In 99.9% of the cases, SWIG just needs to declare them as 'static'. But only do this if strictly necessary, ie, if you have problems with your compiler or suchlike. */ #ifndef SWIGRUNTIME # define SWIGRUNTIME SWIGINTERN #endif #ifndef SWIGRUNTIMEINLINE # define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE #endif /* Generic buffer size */ #ifndef SWIG_BUFFER_SIZE # define SWIG_BUFFER_SIZE 1024 #endif /* Flags for pointer conversions */ #define SWIG_POINTER_DISOWN 0x1 #define SWIG_CAST_NEW_MEMORY 0x2 /* Flags for new pointer objects */ #define SWIG_POINTER_OWN 0x1 /* Flags/methods for returning states. The SWIG conversion methods, as ConvertPtr, return an integer that tells if the conversion was successful or not. And if not, an error code can be returned (see swigerrors.swg for the codes). Use the following macros/flags to set or process the returning states. In old versions of SWIG, code such as the following was usually written: if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { // success code } else { //fail code } Now you can be more explicit: int res = SWIG_ConvertPtr(obj,vptr,ty.flags); if (SWIG_IsOK(res)) { // success code } else { // fail code } which is the same really, but now you can also do Type *ptr; int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags); if (SWIG_IsOK(res)) { // success code if (SWIG_IsNewObj(res) { ... delete *ptr; } else { ... } } else { // fail code } I.e., now SWIG_ConvertPtr can return new objects and you can identify the case and take care of the deallocation. Of course that also requires SWIG_ConvertPtr to return new result values, such as int SWIG_ConvertPtr(obj, ptr,...) { if () { if () { *ptr = ; return SWIG_NEWOBJ; } else { *ptr = ; return SWIG_OLDOBJ; } } else { return SWIG_BADOBJ; } } Of course, returning the plain '0(success)/-1(fail)' still works, but you can be more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the SWIG errors code. Finally, if the SWIG_CASTRANK_MODE is enabled, the result code allows to return the 'cast rank', for example, if you have this int food(double) int fooi(int); and you call food(1) // cast rank '1' (1 -> 1.0) fooi(1) // cast rank '0' just use the SWIG_AddCast()/SWIG_CheckState() */ #define SWIG_OK (0) #define SWIG_ERROR (-1) #define SWIG_IsOK(r) (r >= 0) #define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) /* The CastRankLimit says how many bits are used for the cast rank */ #define SWIG_CASTRANKLIMIT (1 << 8) /* The NewMask denotes the object was created (using new/malloc) */ #define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1) /* The TmpMask is for in/out typemaps that use temporal objects */ #define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1) /* Simple returning values */ #define SWIG_BADOBJ (SWIG_ERROR) #define SWIG_OLDOBJ (SWIG_OK) #define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK) #define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK) /* Check, add and del mask methods */ #define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r) #define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r) #define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK)) #define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r) #define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r) #define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK)) /* Cast-Rank Mode */ #if defined(SWIG_CASTRANK_MODE) # ifndef SWIG_TypeRank # define SWIG_TypeRank unsigned long # endif # ifndef SWIG_MAXCASTRANK /* Default cast allowed */ # define SWIG_MAXCASTRANK (2) # endif # define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) # define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) SWIGINTERNINLINE int SWIG_AddCast(int r) { return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; } SWIGINTERNINLINE int SWIG_CheckState(int r) { return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; } #else /* no cast-rank mode */ # define SWIG_AddCast(r) (r) # define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) #endif #include #ifdef __cplusplus extern "C" { #endif typedef void *(*swig_converter_func)(void *, int *); typedef struct swig_type_info *(*swig_dycast_func)(void **); /* Structure to store information on one type */ typedef struct swig_type_info { const char *name; /* mangled name of this type */ const char *str; /* human readable name of this type */ swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ struct swig_cast_info *cast; /* linked list of types that can cast into this type */ void *clientdata; /* language specific type data */ int owndata; /* flag if the structure owns the clientdata */ } swig_type_info; /* Structure to store a type and conversion function used for casting */ typedef struct swig_cast_info { swig_type_info *type; /* pointer to type that is equivalent to this type */ swig_converter_func converter; /* function to cast the void pointers */ struct swig_cast_info *next; /* pointer to next cast in linked list */ struct swig_cast_info *prev; /* pointer to the previous cast */ } swig_cast_info; /* Structure used to store module information * Each module generates one structure like this, and the runtime collects * all of these structures and stores them in a circularly linked list.*/ typedef struct swig_module_info { swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ size_t size; /* Number of types in this module */ struct swig_module_info *next; /* Pointer to next element in circularly linked list */ swig_type_info **type_initial; /* Array of initially generated type structures */ swig_cast_info **cast_initial; /* Array of initially generated casting structures */ void *clientdata; /* Language specific module data */ } swig_module_info; /* Compare two type names skipping the space characters, therefore "char*" == "char *" and "Class" == "Class", etc. Return 0 when the two name types are equivalent, as in strncmp, but skipping ' '. */ SWIGRUNTIME int SWIG_TypeNameComp(const char *f1, const char *l1, const char *f2, const char *l2) { for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { while ((*f1 == ' ') && (f1 != l1)) ++f1; while ((*f2 == ' ') && (f2 != l2)) ++f2; if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; } return (int)((l1 - f1) - (l2 - f2)); } /* Check type equivalence in a name list like ||... Return 0 if equal, -1 if nb < tb, 1 if nb > tb */ SWIGRUNTIME int SWIG_TypeCmp(const char *nb, const char *tb) { int equiv = 1; const char* te = tb + strlen(tb); const char* ne = nb; while (equiv != 0 && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = SWIG_TypeNameComp(nb, ne, tb, te); if (*ne) ++ne; } return equiv; } /* Check type equivalence in a name list like ||... Return 0 if not equal, 1 if equal */ SWIGRUNTIME int SWIG_TypeEquiv(const char *nb, const char *tb) { return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0; } /* Check the typename */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheck(const char *c, swig_type_info *ty) { if (ty) { swig_cast_info *iter = ty->cast; while (iter) { if (strcmp(iter->type->name, c) == 0) { if (iter == ty->cast) return iter; /* Move iter to the top of the linked list */ iter->prev->next = iter->next; if (iter->next) iter->next->prev = iter->prev; iter->next = ty->cast; iter->prev = 0; if (ty->cast) ty->cast->prev = iter; ty->cast = iter; return iter; } iter = iter->next; } } return 0; } /* Identical to SWIG_TypeCheck, except strcmp is replaced with a pointer comparison */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *ty) { if (ty) { swig_cast_info *iter = ty->cast; while (iter) { if (iter->type == from) { if (iter == ty->cast) return iter; /* Move iter to the top of the linked list */ iter->prev->next = iter->next; if (iter->next) iter->next->prev = iter->prev; iter->next = ty->cast; iter->prev = 0; if (ty->cast) ty->cast->prev = iter; ty->cast = iter; return iter; } iter = iter->next; } } return 0; } /* Cast a pointer up an inheritance hierarchy */ SWIGRUNTIMEINLINE void * SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); } /* Dynamic pointer casting. Down an inheritance hierarchy */ SWIGRUNTIME swig_type_info * SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { swig_type_info *lastty = ty; if (!ty || !ty->dcast) return ty; while (ty && (ty->dcast)) { ty = (*ty->dcast)(ptr); if (ty) lastty = ty; } return lastty; } /* Return the name associated with this type */ SWIGRUNTIMEINLINE const char * SWIG_TypeName(const swig_type_info *ty) { return ty->name; } /* Return the pretty name associated with this type, that is an unmangled type name in a form presentable to the user. */ SWIGRUNTIME const char * SWIG_TypePrettyName(const swig_type_info *type) { /* The "str" field contains the equivalent pretty names of the type, separated by vertical-bar characters. We choose to print the last name, as it is often (?) the most specific. */ if (!type) return NULL; if (type->str != NULL) { const char *last_name = type->str; const char *s; for (s = type->str; *s; s++) if (*s == '|') last_name = s+1; return last_name; } else return type->name; } /* Set the clientdata field for a type */ SWIGRUNTIME void SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { swig_cast_info *cast = ti->cast; /* if (ti->clientdata == clientdata) return; */ ti->clientdata = clientdata; while (cast) { if (!cast->converter) { swig_type_info *tc = cast->type; if (!tc->clientdata) { SWIG_TypeClientData(tc, clientdata); } } cast = cast->next; } } SWIGRUNTIME void SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { SWIG_TypeClientData(ti, clientdata); ti->owndata = 1; } /* Search for a swig_type_info structure only by mangled name Search is a O(log #types) We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_MangledTypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { swig_module_info *iter = start; do { if (iter->size) { register size_t l = 0; register size_t r = iter->size - 1; do { /* since l+r >= 0, we can (>> 1) instead (/ 2) */ register size_t i = (l + r) >> 1; const char *iname = iter->types[i]->name; if (iname) { register int compare = strcmp(name, iname); if (compare == 0) { return iter->types[i]; } else if (compare < 0) { if (i) { r = i - 1; } else { break; } } else if (compare > 0) { l = i + 1; } } else { break; /* should never happen */ } } while (l <= r); } iter = iter->next; } while (iter != end); return 0; } /* Search for a swig_type_info structure for either a mangled name or a human readable name. It first searches the mangled names of the types, which is a O(log #types) If a type is not found it then searches the human readable names, which is O(#types). We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_TypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { /* STEP 1: Search the name field using binary search */ swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); if (ret) { return ret; } else { /* STEP 2: If the type hasn't been found, do a complete search of the str field (the human readable name) */ swig_module_info *iter = start; do { register size_t i = 0; for (; i < iter->size; ++i) { if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) return iter->types[i]; } iter = iter->next; } while (iter != end); } /* neither found a match */ return 0; } /* Pack binary data into a string */ SWIGRUNTIME char * SWIG_PackData(char *c, void *ptr, size_t sz) { static const char hex[17] = "0123456789abcdef"; register const unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register unsigned char uu = *u; *(c++) = hex[(uu & 0xf0) >> 4]; *(c++) = hex[uu & 0xf]; } return c; } /* Unpack binary data from a string */ SWIGRUNTIME const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { register unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register char d = *(c++); register unsigned char uu; if ((d >= '0') && (d <= '9')) uu = ((d - '0') << 4); else if ((d >= 'a') && (d <= 'f')) uu = ((d - ('a'-10)) << 4); else return (char *) 0; d = *(c++); if ((d >= '0') && (d <= '9')) uu |= (d - '0'); else if ((d >= 'a') && (d <= 'f')) uu |= (d - ('a'-10)); else return (char *) 0; *u = uu; } return c; } /* Pack 'void *' into a string buffer. */ SWIGRUNTIME char * SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { char *r = buff; if ((2*sizeof(void *) + 2) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,&ptr,sizeof(void *)); if (strlen(name) + 1 > (bsz - (r - buff))) return 0; strcpy(r,name); return buff; } SWIGRUNTIME const char * SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { *ptr = (void *) 0; return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sizeof(void *)); } SWIGRUNTIME char * SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { char *r = buff; size_t lname = (name ? strlen(name) : 0); if ((2*sz + 2 + lname) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,ptr,sz); if (lname) { strncpy(r,name,lname+1); } else { *r = 0; } return buff; } SWIGRUNTIME const char * SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { memset(ptr,0,sz); return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sz); } #ifdef __cplusplus } #endif /* Errors in SWIG */ #define SWIG_UnknownError -1 #define SWIG_IOError -2 #define SWIG_RuntimeError -3 #define SWIG_IndexError -4 #define SWIG_TypeError -5 #define SWIG_DivisionByZero -6 #define SWIG_OverflowError -7 #define SWIG_SyntaxError -8 #define SWIG_ValueError -9 #define SWIG_SystemError -10 #define SWIG_AttributeError -11 #define SWIG_MemoryError -12 #define SWIG_NullReferenceError -13 /* Compatibility macros for Python 3 */ #if PY_VERSION_HEX >= 0x03000000 #define PyClass_Check(obj) PyObject_IsInstance(obj, (PyObject *)&PyType_Type) #define PyInt_Check(x) PyLong_Check(x) #define PyInt_AsLong(x) PyLong_AsLong(x) #define PyInt_FromLong(x) PyLong_FromLong(x) #define PyInt_FromSize_t(x) PyLong_FromSize_t(x) #define PyString_Check(name) PyBytes_Check(name) #define PyString_FromString(x) PyUnicode_FromString(x) #define PyString_Format(fmt, args) PyUnicode_Format(fmt, args) #define PyString_AsString(str) PyBytes_AsString(str) #define PyString_Size(str) PyBytes_Size(str) #define PyString_InternFromString(key) PyUnicode_InternFromString(key) #define Py_TPFLAGS_HAVE_CLASS Py_TPFLAGS_BASETYPE #define PyString_AS_STRING(x) PyUnicode_AS_STRING(x) #define _PyLong_FromSsize_t(x) PyLong_FromSsize_t(x) #endif #ifndef Py_TYPE # define Py_TYPE(op) ((op)->ob_type) #endif /* SWIG APIs for compatibility of both Python 2 & 3 */ #if PY_VERSION_HEX >= 0x03000000 # define SWIG_Python_str_FromFormat PyUnicode_FromFormat #else # define SWIG_Python_str_FromFormat PyString_FromFormat #endif /* Warning: This function will allocate a new string in Python 3, * so please call SWIG_Python_str_DelForPy3(x) to free the space. */ SWIGINTERN char* SWIG_Python_str_AsChar(PyObject *str) { #if PY_VERSION_HEX >= 0x03000000 char *cstr; char *newstr; Py_ssize_t len; str = PyUnicode_AsUTF8String(str); PyBytes_AsStringAndSize(str, &cstr, &len); newstr = (char *) malloc(len+1); memcpy(newstr, cstr, len+1); Py_XDECREF(str); return newstr; #else return PyString_AsString(str); #endif } #if PY_VERSION_HEX >= 0x03000000 # define SWIG_Python_str_DelForPy3(x) free( (void*) (x) ) #else # define SWIG_Python_str_DelForPy3(x) #endif SWIGINTERN PyObject* SWIG_Python_str_FromChar(const char *c) { #if PY_VERSION_HEX >= 0x03000000 return PyUnicode_FromString(c); #else return PyString_FromString(c); #endif } /* Add PyOS_snprintf for old Pythons */ #if PY_VERSION_HEX < 0x02020000 # if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM) # define PyOS_snprintf _snprintf # else # define PyOS_snprintf snprintf # endif #endif /* A crude PyString_FromFormat implementation for old Pythons */ #if PY_VERSION_HEX < 0x02020000 #ifndef SWIG_PYBUFFER_SIZE # define SWIG_PYBUFFER_SIZE 1024 #endif static PyObject * PyString_FromFormat(const char *fmt, ...) { va_list ap; char buf[SWIG_PYBUFFER_SIZE * 2]; int res; va_start(ap, fmt); res = vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); return (res < 0 || res >= (int)sizeof(buf)) ? 0 : PyString_FromString(buf); } #endif /* Add PyObject_Del for old Pythons */ #if PY_VERSION_HEX < 0x01060000 # define PyObject_Del(op) PyMem_DEL((op)) #endif #ifndef PyObject_DEL # define PyObject_DEL PyObject_Del #endif /* A crude PyExc_StopIteration exception for old Pythons */ #if PY_VERSION_HEX < 0x02020000 # ifndef PyExc_StopIteration # define PyExc_StopIteration PyExc_RuntimeError # endif # ifndef PyObject_GenericGetAttr # define PyObject_GenericGetAttr 0 # endif #endif /* Py_NotImplemented is defined in 2.1 and up. */ #if PY_VERSION_HEX < 0x02010000 # ifndef Py_NotImplemented # define Py_NotImplemented PyExc_RuntimeError # endif #endif /* A crude PyString_AsStringAndSize implementation for old Pythons */ #if PY_VERSION_HEX < 0x02010000 # ifndef PyString_AsStringAndSize # define PyString_AsStringAndSize(obj, s, len) {*s = PyString_AsString(obj); *len = *s ? strlen(*s) : 0;} # endif #endif /* PySequence_Size for old Pythons */ #if PY_VERSION_HEX < 0x02000000 # ifndef PySequence_Size # define PySequence_Size PySequence_Length # endif #endif /* PyBool_FromLong for old Pythons */ #if PY_VERSION_HEX < 0x02030000 static PyObject *PyBool_FromLong(long ok) { PyObject *result = ok ? Py_True : Py_False; Py_INCREF(result); return result; } #endif /* Py_ssize_t for old Pythons */ /* This code is as recommended by: */ /* http://www.python.org/dev/peps/pep-0353/#conversion-guidelines */ #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) typedef int Py_ssize_t; # define PY_SSIZE_T_MAX INT_MAX # define PY_SSIZE_T_MIN INT_MIN typedef inquiry lenfunc; typedef intargfunc ssizeargfunc; typedef intintargfunc ssizessizeargfunc; typedef intobjargproc ssizeobjargproc; typedef intintobjargproc ssizessizeobjargproc; typedef getreadbufferproc readbufferproc; typedef getwritebufferproc writebufferproc; typedef getsegcountproc segcountproc; typedef getcharbufferproc charbufferproc; static long PyNumber_AsSsize_t (PyObject *x, void *SWIGUNUSEDPARM(exc)) { long result = 0; PyObject *i = PyNumber_Int(x); if (i) { result = PyInt_AsLong(i); Py_DECREF(i); } return result; } #endif #if PY_VERSION_HEX < 0x02050000 #define PyInt_FromSize_t(x) PyInt_FromLong((long)x) #endif #if PY_VERSION_HEX < 0x02040000 #define Py_VISIT(op) \ do { \ if (op) { \ int vret = visit((op), arg); \ if (vret) \ return vret; \ } \ } while (0) #endif #if PY_VERSION_HEX < 0x02030000 typedef struct { PyTypeObject type; PyNumberMethods as_number; PyMappingMethods as_mapping; PySequenceMethods as_sequence; PyBufferProcs as_buffer; PyObject *name, *slots; } PyHeapTypeObject; #endif #if PY_VERSION_HEX < 0x02030000 typedef destructor freefunc; #endif #if ((PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION > 6) || \ (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION > 0) || \ (PY_MAJOR_VERSION > 3)) # define SWIGPY_USE_CAPSULE # define SWIGPY_CAPSULE_NAME ((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION ".type_pointer_capsule" SWIG_TYPE_TABLE_NAME) #endif #if PY_VERSION_HEX < 0x03020000 #define PyDescr_TYPE(x) (((PyDescrObject *)(x))->d_type) #define PyDescr_NAME(x) (((PyDescrObject *)(x))->d_name) #endif /* ----------------------------------------------------------------------------- * error manipulation * ----------------------------------------------------------------------------- */ SWIGRUNTIME PyObject* SWIG_Python_ErrorType(int code) { PyObject* type = 0; switch(code) { case SWIG_MemoryError: type = PyExc_MemoryError; break; case SWIG_IOError: type = PyExc_IOError; break; case SWIG_RuntimeError: type = PyExc_RuntimeError; break; case SWIG_IndexError: type = PyExc_IndexError; break; case SWIG_TypeError: type = PyExc_TypeError; break; case SWIG_DivisionByZero: type = PyExc_ZeroDivisionError; break; case SWIG_OverflowError: type = PyExc_OverflowError; break; case SWIG_SyntaxError: type = PyExc_SyntaxError; break; case SWIG_ValueError: type = PyExc_ValueError; break; case SWIG_SystemError: type = PyExc_SystemError; break; case SWIG_AttributeError: type = PyExc_AttributeError; break; default: type = PyExc_RuntimeError; } return type; } SWIGRUNTIME void SWIG_Python_AddErrorMsg(const char* mesg) { PyObject *type = 0; PyObject *value = 0; PyObject *traceback = 0; if (PyErr_Occurred()) PyErr_Fetch(&type, &value, &traceback); if (value) { char *tmp; PyObject *old_str = PyObject_Str(value); PyErr_Clear(); Py_XINCREF(type); PyErr_Format(type, "%s %s", tmp = SWIG_Python_str_AsChar(old_str), mesg); SWIG_Python_str_DelForPy3(tmp); Py_DECREF(old_str); Py_DECREF(value); } else { PyErr_SetString(PyExc_RuntimeError, mesg); } } #if defined(SWIG_PYTHON_NO_THREADS) # if defined(SWIG_PYTHON_THREADS) # undef SWIG_PYTHON_THREADS # endif #endif #if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */ # if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL) # if (PY_VERSION_HEX >= 0x02030000) /* For 2.3 or later, use the PyGILState calls */ # define SWIG_PYTHON_USE_GIL # endif # endif # if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */ # ifndef SWIG_PYTHON_INITIALIZE_THREADS # define SWIG_PYTHON_INITIALIZE_THREADS PyEval_InitThreads() # endif # ifdef __cplusplus /* C++ code */ class SWIG_Python_Thread_Block { bool status; PyGILState_STATE state; public: void end() { if (status) { PyGILState_Release(state); status = false;} } SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} ~SWIG_Python_Thread_Block() { end(); } }; class SWIG_Python_Thread_Allow { bool status; PyThreadState *save; public: void end() { if (status) { PyEval_RestoreThread(save); status = false; }} SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} ~SWIG_Python_Thread_Allow() { end(); } }; # define SWIG_PYTHON_THREAD_BEGIN_BLOCK SWIG_Python_Thread_Block _swig_thread_block # define SWIG_PYTHON_THREAD_END_BLOCK _swig_thread_block.end() # define SWIG_PYTHON_THREAD_BEGIN_ALLOW SWIG_Python_Thread_Allow _swig_thread_allow # define SWIG_PYTHON_THREAD_END_ALLOW _swig_thread_allow.end() # else /* C code */ # define SWIG_PYTHON_THREAD_BEGIN_BLOCK PyGILState_STATE _swig_thread_block = PyGILState_Ensure() # define SWIG_PYTHON_THREAD_END_BLOCK PyGILState_Release(_swig_thread_block) # define SWIG_PYTHON_THREAD_BEGIN_ALLOW PyThreadState *_swig_thread_allow = PyEval_SaveThread() # define SWIG_PYTHON_THREAD_END_ALLOW PyEval_RestoreThread(_swig_thread_allow) # endif # else /* Old thread way, not implemented, user must provide it */ # if !defined(SWIG_PYTHON_INITIALIZE_THREADS) # define SWIG_PYTHON_INITIALIZE_THREADS # endif # if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK) # define SWIG_PYTHON_THREAD_BEGIN_BLOCK # endif # if !defined(SWIG_PYTHON_THREAD_END_BLOCK) # define SWIG_PYTHON_THREAD_END_BLOCK # endif # if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW) # define SWIG_PYTHON_THREAD_BEGIN_ALLOW # endif # if !defined(SWIG_PYTHON_THREAD_END_ALLOW) # define SWIG_PYTHON_THREAD_END_ALLOW # endif # endif #else /* No thread support */ # define SWIG_PYTHON_INITIALIZE_THREADS # define SWIG_PYTHON_THREAD_BEGIN_BLOCK # define SWIG_PYTHON_THREAD_END_BLOCK # define SWIG_PYTHON_THREAD_BEGIN_ALLOW # define SWIG_PYTHON_THREAD_END_ALLOW #endif /* ----------------------------------------------------------------------------- * Python API portion that goes into the runtime * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #endif /* ----------------------------------------------------------------------------- * Constant declarations * ----------------------------------------------------------------------------- */ /* Constant Types */ #define SWIG_PY_POINTER 4 #define SWIG_PY_BINARY 5 /* Constant information structure */ typedef struct swig_const_info { int type; char *name; long lvalue; double dvalue; void *pvalue; swig_type_info **ptype; } swig_const_info; /* ----------------------------------------------------------------------------- * Wrapper of PyInstanceMethod_New() used in Python 3 * It is exported to the generated module, used for -fastproxy * ----------------------------------------------------------------------------- */ #if PY_VERSION_HEX >= 0x03000000 SWIGRUNTIME PyObject* SWIG_PyInstanceMethod_New(PyObject *SWIGUNUSEDPARM(self), PyObject *func) { return PyInstanceMethod_New(func); } #else SWIGRUNTIME PyObject* SWIG_PyInstanceMethod_New(PyObject *SWIGUNUSEDPARM(self), PyObject *SWIGUNUSEDPARM(func)) { return NULL; } #endif #ifdef __cplusplus } #endif /* ----------------------------------------------------------------------------- * pyrun.swg * * This file contains the runtime support for Python modules * and includes code for managing global variables and pointer * type checking. * * ----------------------------------------------------------------------------- */ /* Common SWIG API */ /* for raw pointers */ #define SWIG_Python_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0) #define SWIG_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtr(obj, pptr, type, flags) #define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own) #ifdef SWIGPYTHON_BUILTIN #define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(self, ptr, type, flags) #else #define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(NULL, ptr, type, flags) #endif #define SWIG_InternalNewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(NULL, ptr, type, flags) #define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) #define SWIG_AcquirePtr(ptr, src) SWIG_Python_AcquirePtr(ptr, src) #define swig_owntype int /* for raw packed data */ #define SWIG_ConvertPacked(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) #define SWIG_NewPackedObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) /* for class or struct pointers */ #define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_ConvertPtr(obj, pptr, type, flags) #define SWIG_NewInstanceObj(ptr, type, flags) SWIG_NewPointerObj(ptr, type, flags) /* for C or C++ function pointers */ #define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_Python_ConvertFunctionPtr(obj, pptr, type) #define SWIG_NewFunctionPtrObj(ptr, type) SWIG_Python_NewPointerObj(NULL, ptr, type, 0) /* for C++ member pointers, ie, member methods */ #define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) #define SWIG_NewMemberObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) /* Runtime API */ #define SWIG_GetModule(clientdata) SWIG_Python_GetModule(clientdata) #define SWIG_SetModule(clientdata, pointer) SWIG_Python_SetModule(pointer) #define SWIG_NewClientData(obj) SwigPyClientData_New(obj) #define SWIG_SetErrorObj SWIG_Python_SetErrorObj #define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg #define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) #define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) #define SWIG_fail goto fail /* Runtime API implementation */ /* Error manipulation */ SWIGINTERN void SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; PyErr_SetObject(errtype, obj); Py_DECREF(obj); SWIG_PYTHON_THREAD_END_BLOCK; } SWIGINTERN void SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; PyErr_SetString(errtype, msg); SWIG_PYTHON_THREAD_END_BLOCK; } #define SWIG_Python_Raise(obj, type, desc) SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj) /* Set a constant value */ #if defined(SWIGPYTHON_BUILTIN) SWIGINTERN void SwigPyBuiltin_AddPublicSymbol(PyObject *seq, const char *key) { PyObject *s = PyString_InternFromString(key); PyList_Append(seq, s); Py_DECREF(s); } SWIGINTERN void SWIG_Python_SetConstant(PyObject *d, PyObject *public_interface, const char *name, PyObject *obj) { #if PY_VERSION_HEX < 0x02030000 PyDict_SetItemString(d, (char *)name, obj); #else PyDict_SetItemString(d, name, obj); #endif Py_DECREF(obj); if (public_interface) SwigPyBuiltin_AddPublicSymbol(public_interface, name); } #else SWIGINTERN void SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { #if PY_VERSION_HEX < 0x02030000 PyDict_SetItemString(d, (char *)name, obj); #else PyDict_SetItemString(d, name, obj); #endif Py_DECREF(obj); } #endif /* Append a value to the result obj */ SWIGINTERN PyObject* SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) { #if !defined(SWIG_PYTHON_OUTPUT_TUPLE) if (!result) { result = obj; } else if (result == Py_None) { Py_DECREF(result); result = obj; } else { if (!PyList_Check(result)) { PyObject *o2 = result; result = PyList_New(1); PyList_SetItem(result, 0, o2); } PyList_Append(result,obj); Py_DECREF(obj); } return result; #else PyObject* o2; PyObject* o3; if (!result) { result = obj; } else if (result == Py_None) { Py_DECREF(result); result = obj; } else { if (!PyTuple_Check(result)) { o2 = result; result = PyTuple_New(1); PyTuple_SET_ITEM(result, 0, o2); } o3 = PyTuple_New(1); PyTuple_SET_ITEM(o3, 0, obj); o2 = result; result = PySequence_Concat(o2, o3); Py_DECREF(o2); Py_DECREF(o3); } return result; #endif } /* Unpack the argument tuple */ SWIGINTERN int SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) { if (!args) { if (!min && !max) { return 1; } else { PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", name, (min == max ? "" : "at least "), (int)min); return 0; } } if (!PyTuple_Check(args)) { if (min <= 1 && max >= 1) { register int i; objs[0] = args; for (i = 1; i < max; ++i) { objs[i] = 0; } return 2; } PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); return 0; } else { register Py_ssize_t l = PyTuple_GET_SIZE(args); if (l < min) { PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", name, (min == max ? "" : "at least "), (int)min, (int)l); return 0; } else if (l > max) { PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", name, (min == max ? "" : "at most "), (int)max, (int)l); return 0; } else { register int i; for (i = 0; i < l; ++i) { objs[i] = PyTuple_GET_ITEM(args, i); } for (; l < max; ++l) { objs[l] = 0; } return i + 1; } } } /* A functor is a function object with one single object argument */ #if PY_VERSION_HEX >= 0x02020000 #define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunctionObjArgs(functor, obj, NULL); #else #define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunction(functor, "O", obj); #endif /* Helper for static pointer initialization for both C and C++ code, for example static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...); */ #ifdef __cplusplus #define SWIG_STATIC_POINTER(var) var #else #define SWIG_STATIC_POINTER(var) var = 0; if (!var) var #endif /* ----------------------------------------------------------------------------- * Pointer declarations * ----------------------------------------------------------------------------- */ /* Flags for new pointer objects */ #define SWIG_POINTER_NOSHADOW (SWIG_POINTER_OWN << 1) #define SWIG_POINTER_NEW (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN) #define SWIG_POINTER_IMPLICIT_CONV (SWIG_POINTER_DISOWN << 1) #define SWIG_BUILTIN_TP_INIT (SWIG_POINTER_OWN << 2) #define SWIG_BUILTIN_INIT (SWIG_BUILTIN_TP_INIT | SWIG_POINTER_OWN) #ifdef __cplusplus extern "C" { #endif /* How to access Py_None */ #if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # ifndef SWIG_PYTHON_NO_BUILD_NONE # ifndef SWIG_PYTHON_BUILD_NONE # define SWIG_PYTHON_BUILD_NONE # endif # endif #endif #ifdef SWIG_PYTHON_BUILD_NONE # ifdef Py_None # undef Py_None # define Py_None SWIG_Py_None() # endif SWIGRUNTIMEINLINE PyObject * _SWIG_Py_None(void) { PyObject *none = Py_BuildValue((char*)""); Py_DECREF(none); return none; } SWIGRUNTIME PyObject * SWIG_Py_None(void) { static PyObject *SWIG_STATIC_POINTER(none) = _SWIG_Py_None(); return none; } #endif /* The python void return value */ SWIGRUNTIMEINLINE PyObject * SWIG_Py_Void(void) { PyObject *none = Py_None; Py_INCREF(none); return none; } /* SwigPyClientData */ typedef struct { PyObject *klass; PyObject *newraw; PyObject *newargs; PyObject *destroy; int delargs; int implicitconv; PyTypeObject *pytype; } SwigPyClientData; SWIGRUNTIMEINLINE int SWIG_Python_CheckImplicit(swig_type_info *ty) { SwigPyClientData *data = (SwigPyClientData *)ty->clientdata; return data ? data->implicitconv : 0; } SWIGRUNTIMEINLINE PyObject * SWIG_Python_ExceptionType(swig_type_info *desc) { SwigPyClientData *data = desc ? (SwigPyClientData *) desc->clientdata : 0; PyObject *klass = data ? data->klass : 0; return (klass ? klass : PyExc_RuntimeError); } SWIGRUNTIME SwigPyClientData * SwigPyClientData_New(PyObject* obj) { if (!obj) { return 0; } else { SwigPyClientData *data = (SwigPyClientData *)malloc(sizeof(SwigPyClientData)); /* the klass element */ data->klass = obj; Py_INCREF(data->klass); /* the newraw method and newargs arguments used to create a new raw instance */ if (PyClass_Check(obj)) { data->newraw = 0; data->newargs = obj; Py_INCREF(obj); } else { #if (PY_VERSION_HEX < 0x02020000) data->newraw = 0; #else data->newraw = PyObject_GetAttrString(data->klass, (char *)"__new__"); #endif if (data->newraw) { Py_INCREF(data->newraw); data->newargs = PyTuple_New(1); PyTuple_SetItem(data->newargs, 0, obj); } else { data->newargs = obj; } Py_INCREF(data->newargs); } /* the destroy method, aka as the C++ delete method */ data->destroy = PyObject_GetAttrString(data->klass, (char *)"__swig_destroy__"); if (PyErr_Occurred()) { PyErr_Clear(); data->destroy = 0; } if (data->destroy) { int flags; Py_INCREF(data->destroy); flags = PyCFunction_GET_FLAGS(data->destroy); #ifdef METH_O data->delargs = !(flags & (METH_O)); #else data->delargs = 0; #endif } else { data->delargs = 0; } data->implicitconv = 0; data->pytype = 0; return data; } } SWIGRUNTIME void SwigPyClientData_Del(SwigPyClientData *data) { Py_XDECREF(data->newraw); Py_XDECREF(data->newargs); Py_XDECREF(data->destroy); } /* =============== SwigPyObject =====================*/ typedef struct { PyObject_HEAD void *ptr; swig_type_info *ty; int own; PyObject *next; #ifdef SWIGPYTHON_BUILTIN PyObject *dict; #endif } SwigPyObject; SWIGRUNTIME PyObject * SwigPyObject_long(SwigPyObject *v) { return PyLong_FromVoidPtr(v->ptr); } SWIGRUNTIME PyObject * SwigPyObject_format(const char* fmt, SwigPyObject *v) { PyObject *res = NULL; PyObject *args = PyTuple_New(1); if (args) { if (PyTuple_SetItem(args, 0, SwigPyObject_long(v)) == 0) { PyObject *ofmt = SWIG_Python_str_FromChar(fmt); if (ofmt) { #if PY_VERSION_HEX >= 0x03000000 res = PyUnicode_Format(ofmt,args); #else res = PyString_Format(ofmt,args); #endif Py_DECREF(ofmt); } Py_DECREF(args); } } return res; } SWIGRUNTIME PyObject * SwigPyObject_oct(SwigPyObject *v) { return SwigPyObject_format("%o",v); } SWIGRUNTIME PyObject * SwigPyObject_hex(SwigPyObject *v) { return SwigPyObject_format("%x",v); } SWIGRUNTIME PyObject * #ifdef METH_NOARGS SwigPyObject_repr(SwigPyObject *v) #else SwigPyObject_repr(SwigPyObject *v, PyObject *args) #endif { const char *name = SWIG_TypePrettyName(v->ty); PyObject *repr = SWIG_Python_str_FromFormat("", (name ? name : "unknown"), (void *)v); if (v->next) { # ifdef METH_NOARGS PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next); # else PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next, args); # endif # if PY_VERSION_HEX >= 0x03000000 PyObject *joined = PyUnicode_Concat(repr, nrep); Py_DecRef(repr); Py_DecRef(nrep); repr = joined; # else PyString_ConcatAndDel(&repr,nrep); # endif } return repr; } SWIGRUNTIME int SwigPyObject_compare(SwigPyObject *v, SwigPyObject *w) { void *i = v->ptr; void *j = w->ptr; return (i < j) ? -1 : ((i > j) ? 1 : 0); } /* Added for Python 3.x, would it also be useful for Python 2.x? */ SWIGRUNTIME PyObject* SwigPyObject_richcompare(SwigPyObject *v, SwigPyObject *w, int op) { PyObject* res; if( op != Py_EQ && op != Py_NE ) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } res = PyBool_FromLong( (SwigPyObject_compare(v, w)==0) == (op == Py_EQ) ? 1 : 0); return res; } SWIGRUNTIME PyTypeObject* SwigPyObject_TypeOnce(void); #ifdef SWIGPYTHON_BUILTIN static swig_type_info *SwigPyObject_stype = 0; SWIGRUNTIME PyTypeObject* SwigPyObject_type(void) { SwigPyClientData *cd; assert(SwigPyObject_stype); cd = (SwigPyClientData*) SwigPyObject_stype->clientdata; assert(cd); assert(cd->pytype); return cd->pytype; } #else SWIGRUNTIME PyTypeObject* SwigPyObject_type(void) { static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyObject_TypeOnce(); return type; } #endif SWIGRUNTIMEINLINE int SwigPyObject_Check(PyObject *op) { #ifdef SWIGPYTHON_BUILTIN PyTypeObject *target_tp = SwigPyObject_type(); if (PyType_IsSubtype(op->ob_type, target_tp)) return 1; return (strcmp(op->ob_type->tp_name, "SwigPyObject") == 0); #else return (Py_TYPE(op) == SwigPyObject_type()) || (strcmp(Py_TYPE(op)->tp_name,"SwigPyObject") == 0); #endif } SWIGRUNTIME PyObject * SwigPyObject_New(void *ptr, swig_type_info *ty, int own); SWIGRUNTIME void SwigPyObject_dealloc(PyObject *v) { SwigPyObject *sobj = (SwigPyObject *) v; PyObject *next = sobj->next; if (sobj->own == SWIG_POINTER_OWN) { swig_type_info *ty = sobj->ty; SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; PyObject *destroy = data ? data->destroy : 0; if (destroy) { /* destroy is always a VARARGS method */ PyObject *res; if (data->delargs) { /* we need to create a temporary object to carry the destroy operation */ PyObject *tmp = SwigPyObject_New(sobj->ptr, ty, 0); res = SWIG_Python_CallFunctor(destroy, tmp); Py_DECREF(tmp); } else { PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); PyObject *mself = PyCFunction_GET_SELF(destroy); res = ((*meth)(mself, v)); } Py_XDECREF(res); } #if !defined(SWIG_PYTHON_SILENT_MEMLEAK) else { const char *name = SWIG_TypePrettyName(ty); printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); } #endif } Py_XDECREF(next); PyObject_DEL(v); } SWIGRUNTIME PyObject* SwigPyObject_append(PyObject* v, PyObject* next) { SwigPyObject *sobj = (SwigPyObject *) v; #ifndef METH_O PyObject *tmp = 0; if (!PyArg_ParseTuple(next,(char *)"O:append", &tmp)) return NULL; next = tmp; #endif if (!SwigPyObject_Check(next)) { return NULL; } sobj->next = next; Py_INCREF(next); return SWIG_Py_Void(); } SWIGRUNTIME PyObject* #ifdef METH_NOARGS SwigPyObject_next(PyObject* v) #else SwigPyObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) #endif { SwigPyObject *sobj = (SwigPyObject *) v; if (sobj->next) { Py_INCREF(sobj->next); return sobj->next; } else { return SWIG_Py_Void(); } } SWIGINTERN PyObject* #ifdef METH_NOARGS SwigPyObject_disown(PyObject *v) #else SwigPyObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) #endif { SwigPyObject *sobj = (SwigPyObject *)v; sobj->own = 0; return SWIG_Py_Void(); } SWIGINTERN PyObject* #ifdef METH_NOARGS SwigPyObject_acquire(PyObject *v) #else SwigPyObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) #endif { SwigPyObject *sobj = (SwigPyObject *)v; sobj->own = SWIG_POINTER_OWN; return SWIG_Py_Void(); } SWIGINTERN PyObject* SwigPyObject_own(PyObject *v, PyObject *args) { PyObject *val = 0; #if (PY_VERSION_HEX < 0x02020000) if (!PyArg_ParseTuple(args,(char *)"|O:own",&val)) #elif (PY_VERSION_HEX < 0x02050000) if (!PyArg_UnpackTuple(args, (char *)"own", 0, 1, &val)) #else if (!PyArg_UnpackTuple(args, "own", 0, 1, &val)) #endif { return NULL; } else { SwigPyObject *sobj = (SwigPyObject *)v; PyObject *obj = PyBool_FromLong(sobj->own); if (val) { #ifdef METH_NOARGS if (PyObject_IsTrue(val)) { SwigPyObject_acquire(v); } else { SwigPyObject_disown(v); } #else if (PyObject_IsTrue(val)) { SwigPyObject_acquire(v,args); } else { SwigPyObject_disown(v,args); } #endif } return obj; } } #ifdef METH_O static PyMethodDef swigobject_methods[] = { {(char *)"disown", (PyCFunction)SwigPyObject_disown, METH_NOARGS, (char *)"releases ownership of the pointer"}, {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_NOARGS, (char *)"acquires ownership of the pointer"}, {(char *)"own", (PyCFunction)SwigPyObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, {(char *)"append", (PyCFunction)SwigPyObject_append, METH_O, (char *)"appends another 'this' object"}, {(char *)"next", (PyCFunction)SwigPyObject_next, METH_NOARGS, (char *)"returns the next 'this' object"}, {(char *)"__repr__",(PyCFunction)SwigPyObject_repr, METH_NOARGS, (char *)"returns object representation"}, {0, 0, 0, 0} }; #else static PyMethodDef swigobject_methods[] = { {(char *)"disown", (PyCFunction)SwigPyObject_disown, METH_VARARGS, (char *)"releases ownership of the pointer"}, {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_VARARGS, (char *)"aquires ownership of the pointer"}, {(char *)"own", (PyCFunction)SwigPyObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, {(char *)"append", (PyCFunction)SwigPyObject_append, METH_VARARGS, (char *)"appends another 'this' object"}, {(char *)"next", (PyCFunction)SwigPyObject_next, METH_VARARGS, (char *)"returns the next 'this' object"}, {(char *)"__repr__",(PyCFunction)SwigPyObject_repr, METH_VARARGS, (char *)"returns object representation"}, {0, 0, 0, 0} }; #endif #if PY_VERSION_HEX < 0x02020000 SWIGINTERN PyObject * SwigPyObject_getattr(SwigPyObject *sobj,char *name) { return Py_FindMethod(swigobject_methods, (PyObject *)sobj, name); } #endif SWIGRUNTIME PyTypeObject* SwigPyObject_TypeOnce(void) { static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; static PyNumberMethods SwigPyObject_as_number = { (binaryfunc)0, /*nb_add*/ (binaryfunc)0, /*nb_subtract*/ (binaryfunc)0, /*nb_multiply*/ /* nb_divide removed in Python 3 */ #if PY_VERSION_HEX < 0x03000000 (binaryfunc)0, /*nb_divide*/ #endif (binaryfunc)0, /*nb_remainder*/ (binaryfunc)0, /*nb_divmod*/ (ternaryfunc)0,/*nb_power*/ (unaryfunc)0, /*nb_negative*/ (unaryfunc)0, /*nb_positive*/ (unaryfunc)0, /*nb_absolute*/ (inquiry)0, /*nb_nonzero*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ 0, /*nb_and*/ 0, /*nb_xor*/ 0, /*nb_or*/ #if PY_VERSION_HEX < 0x03000000 0, /*nb_coerce*/ #endif (unaryfunc)SwigPyObject_long, /*nb_int*/ #if PY_VERSION_HEX < 0x03000000 (unaryfunc)SwigPyObject_long, /*nb_long*/ #else 0, /*nb_reserved*/ #endif (unaryfunc)0, /*nb_float*/ #if PY_VERSION_HEX < 0x03000000 (unaryfunc)SwigPyObject_oct, /*nb_oct*/ (unaryfunc)SwigPyObject_hex, /*nb_hex*/ #endif #if PY_VERSION_HEX >= 0x03000000 /* 3.0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index, nb_inplace_divide removed */ #elif PY_VERSION_HEX >= 0x02050000 /* 2.5.0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */ #elif PY_VERSION_HEX >= 0x02020000 /* 2.2.0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */ #elif PY_VERSION_HEX >= 0x02000000 /* 2.0.0 */ 0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */ #endif }; static PyTypeObject swigpyobject_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { /* PyObject header changed in Python 3 */ #if PY_VERSION_HEX >= 0x03000000 PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif (char *)"SwigPyObject", /* tp_name */ sizeof(SwigPyObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)SwigPyObject_dealloc, /* tp_dealloc */ 0, /* tp_print */ #if PY_VERSION_HEX < 0x02020000 (getattrfunc)SwigPyObject_getattr, /* tp_getattr */ #else (getattrfunc)0, /* tp_getattr */ #endif (setattrfunc)0, /* tp_setattr */ #if PY_VERSION_HEX >= 0x03000000 0, /* tp_reserved in 3.0.1, tp_compare in 3.0.0 but not used */ #else (cmpfunc)SwigPyObject_compare, /* tp_compare */ #endif (reprfunc)SwigPyObject_repr, /* tp_repr */ &SwigPyObject_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)0, /* tp_hash */ (ternaryfunc)0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ swigobject_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ (richcmpfunc)SwigPyObject_richcompare,/* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0, /* tp_iter */ 0, /* tp_iternext */ swigobject_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #if PY_VERSION_HEX >= 0x02060000 0, /* tp_version */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; swigpyobject_type = tmp; type_init = 1; #if PY_VERSION_HEX < 0x02020000 swigpyobject_type.ob_type = &PyType_Type; #else if (PyType_Ready(&swigpyobject_type) < 0) return NULL; #endif } return &swigpyobject_type; } SWIGRUNTIME PyObject * SwigPyObject_New(void *ptr, swig_type_info *ty, int own) { SwigPyObject *sobj = PyObject_NEW(SwigPyObject, SwigPyObject_type()); if (sobj) { sobj->ptr = ptr; sobj->ty = ty; sobj->own = own; sobj->next = 0; } return (PyObject *)sobj; } /* ----------------------------------------------------------------------------- * Implements a simple Swig Packed type, and use it instead of string * ----------------------------------------------------------------------------- */ typedef struct { PyObject_HEAD void *pack; swig_type_info *ty; size_t size; } SwigPyPacked; SWIGRUNTIME int SwigPyPacked_print(SwigPyPacked *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { char result[SWIG_BUFFER_SIZE]; fputs("pack, v->size, 0, sizeof(result))) { fputs("at ", fp); fputs(result, fp); } fputs(v->ty->name,fp); fputs(">", fp); return 0; } SWIGRUNTIME PyObject * SwigPyPacked_repr(SwigPyPacked *v) { char result[SWIG_BUFFER_SIZE]; if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { return SWIG_Python_str_FromFormat("", result, v->ty->name); } else { return SWIG_Python_str_FromFormat("", v->ty->name); } } SWIGRUNTIME PyObject * SwigPyPacked_str(SwigPyPacked *v) { char result[SWIG_BUFFER_SIZE]; if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){ return SWIG_Python_str_FromFormat("%s%s", result, v->ty->name); } else { return SWIG_Python_str_FromChar(v->ty->name); } } SWIGRUNTIME int SwigPyPacked_compare(SwigPyPacked *v, SwigPyPacked *w) { size_t i = v->size; size_t j = w->size; int s = (i < j) ? -1 : ((i > j) ? 1 : 0); return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size); } SWIGRUNTIME PyTypeObject* SwigPyPacked_TypeOnce(void); SWIGRUNTIME PyTypeObject* SwigPyPacked_type(void) { static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyPacked_TypeOnce(); return type; } SWIGRUNTIMEINLINE int SwigPyPacked_Check(PyObject *op) { return ((op)->ob_type == SwigPyPacked_TypeOnce()) || (strcmp((op)->ob_type->tp_name,"SwigPyPacked") == 0); } SWIGRUNTIME void SwigPyPacked_dealloc(PyObject *v) { if (SwigPyPacked_Check(v)) { SwigPyPacked *sobj = (SwigPyPacked *) v; free(sobj->pack); } PyObject_DEL(v); } SWIGRUNTIME PyTypeObject* SwigPyPacked_TypeOnce(void) { static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; static PyTypeObject swigpypacked_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { /* PyObject header changed in Python 3 */ #if PY_VERSION_HEX>=0x03000000 PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif (char *)"SwigPyPacked", /* tp_name */ sizeof(SwigPyPacked), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)SwigPyPacked_dealloc, /* tp_dealloc */ (printfunc)SwigPyPacked_print, /* tp_print */ (getattrfunc)0, /* tp_getattr */ (setattrfunc)0, /* tp_setattr */ #if PY_VERSION_HEX>=0x03000000 0, /* tp_reserved in 3.0.1 */ #else (cmpfunc)SwigPyPacked_compare, /* tp_compare */ #endif (reprfunc)SwigPyPacked_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)0, /* tp_hash */ (ternaryfunc)0, /* tp_call */ (reprfunc)SwigPyPacked_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ swigpacked_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #if PY_VERSION_HEX >= 0x02060000 0, /* tp_version */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; swigpypacked_type = tmp; type_init = 1; #if PY_VERSION_HEX < 0x02020000 swigpypacked_type.ob_type = &PyType_Type; #else if (PyType_Ready(&swigpypacked_type) < 0) return NULL; #endif } return &swigpypacked_type; } SWIGRUNTIME PyObject * SwigPyPacked_New(void *ptr, size_t size, swig_type_info *ty) { SwigPyPacked *sobj = PyObject_NEW(SwigPyPacked, SwigPyPacked_type()); if (sobj) { void *pack = malloc(size); if (pack) { memcpy(pack, ptr, size); sobj->pack = pack; sobj->ty = ty; sobj->size = size; } else { PyObject_DEL((PyObject *) sobj); sobj = 0; } } return (PyObject *) sobj; } SWIGRUNTIME swig_type_info * SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size) { if (SwigPyPacked_Check(obj)) { SwigPyPacked *sobj = (SwigPyPacked *)obj; if (sobj->size != size) return 0; memcpy(ptr, sobj->pack, size); return sobj->ty; } else { return 0; } } /* ----------------------------------------------------------------------------- * pointers/data manipulation * ----------------------------------------------------------------------------- */ SWIGRUNTIMEINLINE PyObject * _SWIG_This(void) { return SWIG_Python_str_FromChar("this"); } static PyObject *swig_this = NULL; SWIGRUNTIME PyObject * SWIG_This(void) { if (swig_this == NULL) swig_this = _SWIG_This(); return swig_this; } /* #define SWIG_PYTHON_SLOW_GETSET_THIS */ /* TODO: I don't know how to implement the fast getset in Python 3 right now */ #if PY_VERSION_HEX>=0x03000000 #define SWIG_PYTHON_SLOW_GETSET_THIS #endif SWIGRUNTIME SwigPyObject * SWIG_Python_GetSwigThis(PyObject *pyobj) { PyObject *obj; if (SwigPyObject_Check(pyobj)) return (SwigPyObject *) pyobj; #ifdef SWIGPYTHON_BUILTIN (void)obj; # ifdef PyWeakref_CheckProxy if (PyWeakref_CheckProxy(pyobj)) { pyobj = PyWeakref_GET_OBJECT(pyobj); if (pyobj && SwigPyObject_Check(pyobj)) return (SwigPyObject*) pyobj; } # endif return NULL; #else obj = 0; #if (!defined(SWIG_PYTHON_SLOW_GETSET_THIS) && (PY_VERSION_HEX >= 0x02030000)) if (PyInstance_Check(pyobj)) { obj = _PyInstance_Lookup(pyobj, SWIG_This()); } else { PyObject **dictptr = _PyObject_GetDictPtr(pyobj); if (dictptr != NULL) { PyObject *dict = *dictptr; obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; } else { #ifdef PyWeakref_CheckProxy if (PyWeakref_CheckProxy(pyobj)) { PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; } #endif obj = PyObject_GetAttr(pyobj,SWIG_This()); if (obj) { Py_DECREF(obj); } else { if (PyErr_Occurred()) PyErr_Clear(); return 0; } } } #else obj = PyObject_GetAttr(pyobj,SWIG_This()); if (obj) { Py_DECREF(obj); } else { if (PyErr_Occurred()) PyErr_Clear(); return 0; } #endif if (obj && !SwigPyObject_Check(obj)) { /* a PyObject is called 'this', try to get the 'real this' SwigPyObject from it */ return SWIG_Python_GetSwigThis(obj); } return (SwigPyObject *)obj; #endif } /* Acquire a pointer value */ SWIGRUNTIME int SWIG_Python_AcquirePtr(PyObject *obj, int own) { if (own == SWIG_POINTER_OWN) { SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); if (sobj) { int oldown = sobj->own; sobj->own = own; return oldown; } } return 0; } /* Convert a pointer value */ SWIGRUNTIME int SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) { int res; SwigPyObject *sobj; int implicit_conv = (flags & SWIG_POINTER_IMPLICIT_CONV) != 0; if (!obj) return SWIG_ERROR; if (obj == Py_None && !implicit_conv) { if (ptr) *ptr = 0; return SWIG_OK; } res = SWIG_ERROR; sobj = SWIG_Python_GetSwigThis(obj); if (own) *own = 0; while (sobj) { void *vptr = sobj->ptr; if (ty) { swig_type_info *to = sobj->ty; if (to == ty) { /* no type cast needed */ if (ptr) *ptr = vptr; break; } else { swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); if (!tc) { sobj = (SwigPyObject *)sobj->next; } else { if (ptr) { int newmemory = 0; *ptr = SWIG_TypeCast(tc,vptr,&newmemory); if (newmemory == SWIG_CAST_NEW_MEMORY) { assert(own); /* badly formed typemap which will lead to a memory leak - it must set and use own to delete *ptr */ if (own) *own = *own | SWIG_CAST_NEW_MEMORY; } } break; } } } else { if (ptr) *ptr = vptr; break; } } if (sobj) { if (own) *own = *own | sobj->own; if (flags & SWIG_POINTER_DISOWN) { sobj->own = 0; } res = SWIG_OK; } else { if (implicit_conv) { SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; if (data && !data->implicitconv) { PyObject *klass = data->klass; if (klass) { PyObject *impconv; data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ impconv = SWIG_Python_CallFunctor(klass, obj); data->implicitconv = 0; if (PyErr_Occurred()) { PyErr_Clear(); impconv = 0; } if (impconv) { SwigPyObject *iobj = SWIG_Python_GetSwigThis(impconv); if (iobj) { void *vptr; res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0); if (SWIG_IsOK(res)) { if (ptr) { *ptr = vptr; /* transfer the ownership to 'ptr' */ iobj->own = 0; res = SWIG_AddCast(res); res = SWIG_AddNewMask(res); } else { res = SWIG_AddCast(res); } } } Py_DECREF(impconv); } } } } if (!SWIG_IsOK(res) && obj == Py_None) { if (ptr) *ptr = 0; if (PyErr_Occurred()) PyErr_Clear(); res = SWIG_OK; } } return res; } /* Convert a function ptr value */ SWIGRUNTIME int SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) { if (!PyCFunction_Check(obj)) { return SWIG_ConvertPtr(obj, ptr, ty, 0); } else { void *vptr = 0; /* here we get the method pointer for callbacks */ const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; if (desc) desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; if (!desc) return SWIG_ERROR; if (ty) { swig_cast_info *tc = SWIG_TypeCheck(desc,ty); if (tc) { int newmemory = 0; *ptr = SWIG_TypeCast(tc,vptr,&newmemory); assert(!newmemory); /* newmemory handling not yet implemented */ } else { return SWIG_ERROR; } } else { *ptr = vptr; } return SWIG_OK; } } /* Convert a packed value value */ SWIGRUNTIME int SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) { swig_type_info *to = SwigPyPacked_UnpackData(obj, ptr, sz); if (!to) return SWIG_ERROR; if (ty) { if (to != ty) { /* check type cast? */ swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); if (!tc) return SWIG_ERROR; } } return SWIG_OK; } /* ----------------------------------------------------------------------------- * Create a new pointer object * ----------------------------------------------------------------------------- */ /* Create a new instance object, without calling __init__, and set the 'this' attribute. */ SWIGRUNTIME PyObject* SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this) { #if (PY_VERSION_HEX >= 0x02020000) PyObject *inst = 0; PyObject *newraw = data->newraw; if (newraw) { inst = PyObject_Call(newraw, data->newargs, NULL); if (inst) { #if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) PyObject **dictptr = _PyObject_GetDictPtr(inst); if (dictptr != NULL) { PyObject *dict = *dictptr; if (dict == NULL) { dict = PyDict_New(); *dictptr = dict; PyDict_SetItem(dict, SWIG_This(), swig_this); } } #else PyObject *key = SWIG_This(); PyObject_SetAttr(inst, key, swig_this); #endif } } else { #if PY_VERSION_HEX >= 0x03000000 inst = PyBaseObject_Type.tp_new((PyTypeObject*) data->newargs, Py_None, Py_None); if (inst) { PyObject_SetAttr(inst, SWIG_This(), swig_this); Py_TYPE(inst)->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG; } #else PyObject *dict = PyDict_New(); if (dict) { PyDict_SetItem(dict, SWIG_This(), swig_this); inst = PyInstance_NewRaw(data->newargs, dict); Py_DECREF(dict); } #endif } return inst; #else #if (PY_VERSION_HEX >= 0x02010000) PyObject *inst = 0; PyObject *dict = PyDict_New(); if (dict) { PyDict_SetItem(dict, SWIG_This(), swig_this); inst = PyInstance_NewRaw(data->newargs, dict); Py_DECREF(dict); } return (PyObject *) inst; #else PyInstanceObject *inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type); if (inst == NULL) { return NULL; } inst->in_class = (PyClassObject *)data->newargs; Py_INCREF(inst->in_class); inst->in_dict = PyDict_New(); if (inst->in_dict == NULL) { Py_DECREF(inst); return NULL; } #ifdef Py_TPFLAGS_HAVE_WEAKREFS inst->in_weakreflist = NULL; #endif #ifdef Py_TPFLAGS_GC PyObject_GC_Init(inst); #endif PyDict_SetItem(inst->in_dict, SWIG_This(), swig_this); return (PyObject *) inst; #endif #endif } SWIGRUNTIME void SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) { PyObject *dict; #if (PY_VERSION_HEX >= 0x02020000) && !defined(SWIG_PYTHON_SLOW_GETSET_THIS) PyObject **dictptr = _PyObject_GetDictPtr(inst); if (dictptr != NULL) { dict = *dictptr; if (dict == NULL) { dict = PyDict_New(); *dictptr = dict; } PyDict_SetItem(dict, SWIG_This(), swig_this); return; } #endif dict = PyObject_GetAttrString(inst, (char*)"__dict__"); PyDict_SetItem(dict, SWIG_This(), swig_this); Py_DECREF(dict); } SWIGINTERN PyObject * SWIG_Python_InitShadowInstance(PyObject *args) { PyObject *obj[2]; if (!SWIG_Python_UnpackTuple(args, "swiginit", 2, 2, obj)) { return NULL; } else { SwigPyObject *sthis = SWIG_Python_GetSwigThis(obj[0]); if (sthis) { SwigPyObject_append((PyObject*) sthis, obj[1]); } else { SWIG_Python_SetSwigThis(obj[0], obj[1]); } return SWIG_Py_Void(); } } /* Create a new pointer object */ SWIGRUNTIME PyObject * SWIG_Python_NewPointerObj(PyObject *self, void *ptr, swig_type_info *type, int flags) { SwigPyClientData *clientdata; PyObject * robj; int own; if (!ptr) return SWIG_Py_Void(); clientdata = type ? (SwigPyClientData *)(type->clientdata) : 0; own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; if (clientdata && clientdata->pytype) { SwigPyObject *newobj; if (flags & SWIG_BUILTIN_TP_INIT) { newobj = (SwigPyObject*) self; if (newobj->ptr) { PyObject *next_self = clientdata->pytype->tp_alloc(clientdata->pytype, 0); while (newobj->next) newobj = (SwigPyObject *) newobj->next; newobj->next = next_self; newobj = (SwigPyObject *)next_self; } } else { newobj = PyObject_New(SwigPyObject, clientdata->pytype); } if (newobj) { newobj->ptr = ptr; newobj->ty = type; newobj->own = own; newobj->next = 0; #ifdef SWIGPYTHON_BUILTIN newobj->dict = 0; #endif return (PyObject*) newobj; } return SWIG_Py_Void(); } assert(!(flags & SWIG_BUILTIN_TP_INIT)); robj = SwigPyObject_New(ptr, type, own); if (robj && clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); Py_DECREF(robj); robj = inst; } return robj; } /* Create a new packed object */ SWIGRUNTIMEINLINE PyObject * SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) { return ptr ? SwigPyPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); } /* -----------------------------------------------------------------------------* * Get type list * -----------------------------------------------------------------------------*/ #ifdef SWIG_LINK_RUNTIME void *SWIG_ReturnGlobalTypeList(void *); #endif SWIGRUNTIME swig_module_info * SWIG_Python_GetModule(void *SWIGUNUSEDPARM(clientdata)) { static void *type_pointer = (void *)0; /* first check if module already created */ if (!type_pointer) { #ifdef SWIG_LINK_RUNTIME type_pointer = SWIG_ReturnGlobalTypeList((void *)0); #else # ifdef SWIGPY_USE_CAPSULE type_pointer = PyCapsule_Import(SWIGPY_CAPSULE_NAME, 0); # else type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME); # endif if (PyErr_Occurred()) { PyErr_Clear(); type_pointer = (void *)0; } #endif } return (swig_module_info *) type_pointer; } #if PY_MAJOR_VERSION < 2 /* PyModule_AddObject function was introduced in Python 2.0. The following function is copied out of Python/modsupport.c in python version 2.3.4 */ SWIGINTERN int PyModule_AddObject(PyObject *m, char *name, PyObject *o) { PyObject *dict; if (!PyModule_Check(m)) { PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs module as first arg"); return SWIG_ERROR; } if (!o) { PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs non-NULL value"); return SWIG_ERROR; } dict = PyModule_GetDict(m); if (dict == NULL) { /* Internal error -- modules must have a dict! */ PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", PyModule_GetName(m)); return SWIG_ERROR; } if (PyDict_SetItemString(dict, name, o)) return SWIG_ERROR; Py_DECREF(o); return SWIG_OK; } #endif SWIGRUNTIME void #ifdef SWIGPY_USE_CAPSULE SWIG_Python_DestroyModule(PyObject *obj) #else SWIG_Python_DestroyModule(void *vptr) #endif { #ifdef SWIGPY_USE_CAPSULE swig_module_info *swig_module = (swig_module_info *) PyCapsule_GetPointer(obj, SWIGPY_CAPSULE_NAME); #else swig_module_info *swig_module = (swig_module_info *) vptr; #endif swig_type_info **types = swig_module->types; size_t i; for (i =0; i < swig_module->size; ++i) { swig_type_info *ty = types[i]; if (ty->owndata) { SwigPyClientData *data = (SwigPyClientData *) ty->clientdata; if (data) SwigPyClientData_Del(data); } } Py_DECREF(SWIG_This()); swig_this = NULL; } SWIGRUNTIME void SWIG_Python_SetModule(swig_module_info *swig_module) { #if PY_VERSION_HEX >= 0x03000000 /* Add a dummy module object into sys.modules */ PyObject *module = PyImport_AddModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION); #else static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} }; /* Sentinel */ PyObject *module = Py_InitModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, swig_empty_runtime_method_table); #endif #ifdef SWIGPY_USE_CAPSULE PyObject *pointer = PyCapsule_New((void *) swig_module, SWIGPY_CAPSULE_NAME, SWIG_Python_DestroyModule); if (pointer && module) { PyModule_AddObject(module, (char*)"type_pointer_capsule" SWIG_TYPE_TABLE_NAME, pointer); } else { Py_XDECREF(pointer); } #else PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, SWIG_Python_DestroyModule); if (pointer && module) { PyModule_AddObject(module, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME, pointer); } else { Py_XDECREF(pointer); } #endif } /* The python cached type query */ SWIGRUNTIME PyObject * SWIG_Python_TypeCache(void) { static PyObject *SWIG_STATIC_POINTER(cache) = PyDict_New(); return cache; } SWIGRUNTIME swig_type_info * SWIG_Python_TypeQuery(const char *type) { PyObject *cache = SWIG_Python_TypeCache(); PyObject *key = SWIG_Python_str_FromChar(type); PyObject *obj = PyDict_GetItem(cache, key); swig_type_info *descriptor; if (obj) { #ifdef SWIGPY_USE_CAPSULE descriptor = (swig_type_info *) PyCapsule_GetPointer(obj, NULL); #else descriptor = (swig_type_info *) PyCObject_AsVoidPtr(obj); #endif } else { swig_module_info *swig_module = SWIG_GetModule(0); descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); if (descriptor) { #ifdef SWIGPY_USE_CAPSULE obj = PyCapsule_New((void*) descriptor, NULL, NULL); #else obj = PyCObject_FromVoidPtr(descriptor, NULL); #endif PyDict_SetItem(cache, key, obj); Py_DECREF(obj); } } Py_DECREF(key); return descriptor; } /* For backward compatibility only */ #define SWIG_POINTER_EXCEPTION 0 #define SWIG_arg_fail(arg) SWIG_Python_ArgFail(arg) #define SWIG_MustGetPtr(p, type, argnum, flags) SWIG_Python_MustGetPtr(p, type, argnum, flags) SWIGRUNTIME int SWIG_Python_AddErrMesg(const char* mesg, int infront) { if (PyErr_Occurred()) { PyObject *type = 0; PyObject *value = 0; PyObject *traceback = 0; PyErr_Fetch(&type, &value, &traceback); if (value) { char *tmp; PyObject *old_str = PyObject_Str(value); Py_XINCREF(type); PyErr_Clear(); if (infront) { PyErr_Format(type, "%s %s", mesg, tmp = SWIG_Python_str_AsChar(old_str)); } else { PyErr_Format(type, "%s %s", tmp = SWIG_Python_str_AsChar(old_str), mesg); } SWIG_Python_str_DelForPy3(tmp); Py_DECREF(old_str); } return 1; } else { return 0; } } SWIGRUNTIME int SWIG_Python_ArgFail(int argnum) { if (PyErr_Occurred()) { /* add information about failing argument */ char mesg[256]; PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); return SWIG_Python_AddErrMesg(mesg, 1); } else { return 0; } } SWIGRUNTIMEINLINE const char * SwigPyObject_GetDesc(PyObject *self) { SwigPyObject *v = (SwigPyObject *)self; swig_type_info *ty = v ? v->ty : 0; return ty ? ty->str : ""; } SWIGRUNTIME void SWIG_Python_TypeError(const char *type, PyObject *obj) { if (type) { #if defined(SWIG_COBJECT_TYPES) if (obj && SwigPyObject_Check(obj)) { const char *otype = (const char *) SwigPyObject_GetDesc(obj); if (otype) { PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'SwigPyObject(%s)' is received", type, otype); return; } } else #endif { const char *otype = (obj ? obj->ob_type->tp_name : 0); if (otype) { PyObject *str = PyObject_Str(obj); const char *cstr = str ? SWIG_Python_str_AsChar(str) : 0; if (cstr) { PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", type, otype, cstr); SWIG_Python_str_DelForPy3(cstr); } else { PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", type, otype); } Py_XDECREF(str); return; } } PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); } else { PyErr_Format(PyExc_TypeError, "unexpected type is received"); } } /* Convert a pointer value, signal an exception on a type mismatch */ SWIGRUNTIME void * SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int SWIGUNUSEDPARM(argnum), int flags) { void *result; if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { PyErr_Clear(); #if SWIG_POINTER_EXCEPTION if (flags) { SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj); SWIG_Python_ArgFail(argnum); } #endif } return result; } #ifdef SWIGPYTHON_BUILTIN SWIGRUNTIME int SWIG_Python_NonDynamicSetAttr(PyObject *obj, PyObject *name, PyObject *value) { PyTypeObject *tp = obj->ob_type; PyObject *descr; PyObject *encoded_name; descrsetfunc f; int res = -1; # ifdef Py_USING_UNICODE if (PyString_Check(name)) { name = PyUnicode_Decode(PyString_AsString(name), PyString_Size(name), NULL, NULL); if (!name) return -1; } else if (!PyUnicode_Check(name)) # else if (!PyString_Check(name)) # endif { PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", name->ob_type->tp_name); return -1; } else { Py_INCREF(name); } if (!tp->tp_dict) { if (PyType_Ready(tp) < 0) goto done; } descr = _PyType_Lookup(tp, name); f = NULL; if (descr != NULL) f = descr->ob_type->tp_descr_set; if (!f) { if (PyString_Check(name)) { encoded_name = name; Py_INCREF(name); } else { encoded_name = PyUnicode_AsUTF8String(name); } PyErr_Format(PyExc_AttributeError, "'%.100s' object has no attribute '%.200s'", tp->tp_name, PyString_AsString(encoded_name)); Py_DECREF(encoded_name); } else { res = f(descr, obj, value); } done: Py_DECREF(name); return res; } #endif #ifdef __cplusplus } #endif #define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) #define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else /* -------- TYPES TABLE (BEGIN) -------- */ #define SWIGTYPE_p_Distort swig_types[0] #define SWIGTYPE_p_IRAFsurface swig_types[1] #define SWIGTYPE_p_WorldCoor swig_types[2] #define SWIGTYPE_p_a_32__char swig_types[3] #define SWIGTYPE_p_a_9__char swig_types[4] #define SWIGTYPE_p_celprm swig_types[5] #define SWIGTYPE_p_char swig_types[6] #define SWIGTYPE_p_double swig_types[7] #define SWIGTYPE_p_int swig_types[8] #define SWIGTYPE_p_linprm swig_types[9] #define SWIGTYPE_p_p_char swig_types[10] #define SWIGTYPE_p_poly swig_types[11] #define SWIGTYPE_p_prjprm swig_types[12] #define SWIGTYPE_p_wcsprm swig_types[13] static swig_type_info *swig_types[15]; static swig_module_info swig_module = {swig_types, 14, 0, 0, 0, 0}; #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) /* -------- TYPES TABLE (END) -------- */ #if (PY_VERSION_HEX <= 0x02000000) # if !defined(SWIG_PYTHON_CLASSIC) # error "This python version requires swig to be run with the '-classic' option" # endif #endif /*----------------------------------------------- @(target):= _wcs.so ------------------------------------------------*/ #if PY_VERSION_HEX >= 0x03000000 # define SWIG_init PyInit__wcs #else # define SWIG_init init_wcs #endif #define SWIG_name "_wcs" #define SWIGVERSION 0x020012 #define SWIG_VERSION SWIGVERSION #define SWIG_as_voidptr(a) (void *)((const void *)(a)) #define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a)) static double *new_doubleArray(size_t nelements) { return (double *)malloc((nelements)*sizeof(double)); } static void delete_doubleArray(double *ary) { free((char*)ary); } static double doubleArray_getitem(double *ary, size_t index) { return ary[index]; } static void doubleArray_setitem(double *ary, size_t index, double value) { ary[index] = value; } SWIGINTERN int SWIG_AsVal_double (PyObject *obj, double *val) { int res = SWIG_TypeError; if (PyFloat_Check(obj)) { if (val) *val = PyFloat_AsDouble(obj); return SWIG_OK; } else if (PyInt_Check(obj)) { if (val) *val = PyInt_AsLong(obj); return SWIG_OK; } else if (PyLong_Check(obj)) { double v = PyLong_AsDouble(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); } } #ifdef SWIG_PYTHON_CAST_MODE { int dispatch = 0; double d = PyFloat_AsDouble(obj); if (!PyErr_Occurred()) { if (val) *val = d; return SWIG_AddCast(SWIG_OK); } else { PyErr_Clear(); } if (!dispatch) { long v = PyLong_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_AddCast(SWIG_AddCast(SWIG_OK)); } else { PyErr_Clear(); } } } #endif return res; } #include #include SWIGINTERNINLINE int SWIG_CanCastAsInteger(double *d, double min, double max) { double x = *d; if ((min <= x && x <= max)) { double fx = floor(x); double cx = ceil(x); double rd = ((x - fx) < 0.5) ? fx : cx; /* simple rint */ if ((errno == EDOM) || (errno == ERANGE)) { errno = 0; } else { double summ, reps, diff; if (rd < x) { diff = x - rd; } else if (rd > x) { diff = rd - x; } else { return 1; } summ = rd + x; reps = diff/summ; if (reps < 8*DBL_EPSILON) { *d = rd; return 1; } } } return 0; } SWIGINTERN int SWIG_AsVal_unsigned_SS_long (PyObject *obj, unsigned long *val) { #if PY_VERSION_HEX < 0x03000000 if (PyInt_Check(obj)) { long v = PyInt_AsLong(obj); if (v >= 0) { if (val) *val = v; return SWIG_OK; } else { return SWIG_OverflowError; } } else #endif if (PyLong_Check(obj)) { unsigned long v = PyLong_AsUnsignedLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); #if PY_VERSION_HEX >= 0x03000000 { long v = PyLong_AsLong(obj); if (!PyErr_Occurred()) { if (v < 0) { return SWIG_OverflowError; } } else { PyErr_Clear(); } } #endif } } #ifdef SWIG_PYTHON_CAST_MODE { int dispatch = 0; unsigned long v = PyLong_AsUnsignedLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_AddCast(SWIG_OK); } else { PyErr_Clear(); } if (!dispatch) { double d; int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d)); if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, 0, ULONG_MAX)) { if (val) *val = (unsigned long)(d); return res; } } } #endif return SWIG_TypeError; } SWIGINTERNINLINE int SWIG_AsVal_size_t (PyObject * obj, size_t *val) { unsigned long v; int res = SWIG_AsVal_unsigned_SS_long (obj, val ? &v : 0); if (SWIG_IsOK(res) && val) *val = (size_t)(v); return res; } #define SWIG_From_double PyFloat_FromDouble #include "wcs.h" SWIGINTERN swig_type_info* SWIG_pchar_descriptor(void) { static int init = 0; static swig_type_info* info = 0; if (!init) { info = SWIG_TypeQuery("_p_char"); init = 1; } return info; } SWIGINTERN int SWIG_AsCharPtrAndSize(PyObject *obj, char** cptr, size_t* psize, int *alloc) { #if PY_VERSION_HEX>=0x03000000 if (PyUnicode_Check(obj)) #else if (PyString_Check(obj)) #endif { char *cstr; Py_ssize_t len; #if PY_VERSION_HEX>=0x03000000 if (!alloc && cptr) { /* We can't allow converting without allocation, since the internal representation of string in Python 3 is UCS-2/UCS-4 but we require a UTF-8 representation. TODO(bhy) More detailed explanation */ return SWIG_RuntimeError; } obj = PyUnicode_AsUTF8String(obj); PyBytes_AsStringAndSize(obj, &cstr, &len); if(alloc) *alloc = SWIG_NEWOBJ; #else PyString_AsStringAndSize(obj, &cstr, &len); #endif if (cptr) { if (alloc) { /* In python the user should not be able to modify the inner string representation. To warranty that, if you define SWIG_PYTHON_SAFE_CSTRINGS, a new/copy of the python string buffer is always returned. The default behavior is just to return the pointer value, so, be careful. */ #if defined(SWIG_PYTHON_SAFE_CSTRINGS) if (*alloc != SWIG_OLDOBJ) #else if (*alloc == SWIG_NEWOBJ) #endif { *cptr = (char *)memcpy((char *)malloc((len + 1)*sizeof(char)), cstr, sizeof(char)*(len + 1)); *alloc = SWIG_NEWOBJ; } else { *cptr = cstr; *alloc = SWIG_OLDOBJ; } } else { #if PY_VERSION_HEX>=0x03000000 assert(0); /* Should never reach here in Python 3 */ #endif *cptr = SWIG_Python_str_AsChar(obj); } } if (psize) *psize = len + 1; #if PY_VERSION_HEX>=0x03000000 Py_XDECREF(obj); #endif return SWIG_OK; } else { swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); if (pchar_descriptor) { void* vptr = 0; if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { if (cptr) *cptr = (char *) vptr; if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; if (alloc) *alloc = SWIG_OLDOBJ; return SWIG_OK; } } } return SWIG_TypeError; } #include #if !defined(SWIG_NO_LLONG_MAX) # if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__) # define LLONG_MAX __LONG_LONG_MAX__ # define LLONG_MIN (-LLONG_MAX - 1LL) # define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL) # endif #endif SWIGINTERN int SWIG_AsVal_long (PyObject *obj, long* val) { if (PyInt_Check(obj)) { if (val) *val = PyInt_AsLong(obj); return SWIG_OK; } else if (PyLong_Check(obj)) { long v = PyLong_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); } } #ifdef SWIG_PYTHON_CAST_MODE { int dispatch = 0; long v = PyInt_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_AddCast(SWIG_OK); } else { PyErr_Clear(); } if (!dispatch) { double d; int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d)); if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, LONG_MAX)) { if (val) *val = (long)(d); return res; } } } #endif return SWIG_TypeError; } SWIGINTERN int SWIG_AsVal_int (PyObject * obj, int *val) { long v; int res = SWIG_AsVal_long (obj, &v); if (SWIG_IsOK(res)) { if ((v < INT_MIN || v > INT_MAX)) { return SWIG_OverflowError; } else { if (val) *val = (int)(v); } } return res; } SWIGINTERNINLINE PyObject* SWIG_From_int (int value) { return PyInt_FromLong((long) value); } SWIGINTERNINLINE PyObject * SWIG_FromCharPtrAndSize(const char* carray, size_t size) { if (carray) { if (size > INT_MAX) { swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); return pchar_descriptor ? SWIG_InternalNewPointerObj((char *)(carray), pchar_descriptor, 0) : SWIG_Py_Void(); } else { #if PY_VERSION_HEX >= 0x03000000 return PyUnicode_FromStringAndSize(carray, (int)(size)); #else return PyString_FromStringAndSize(carray, (int)(size)); #endif } } else { return SWIG_Py_Void(); } } SWIGINTERNINLINE PyObject * SWIG_FromCharPtr(const char *cptr) { return SWIG_FromCharPtrAndSize(cptr, (cptr ? strlen(cptr) : 0)); } SWIGINTERN int SWIG_AsCharArray(PyObject * obj, char *val, size_t size) { char* cptr = 0; size_t csize = 0; int alloc = SWIG_OLDOBJ; int res = SWIG_AsCharPtrAndSize(obj, &cptr, &csize, &alloc); if (SWIG_IsOK(res)) { if ((csize == size + 1) && cptr && !(cptr[csize-1])) --csize; if (csize <= size) { if (val) { if (csize) memcpy(val, cptr, csize*sizeof(char)); if (csize < size) memset(val + csize, 0, (size - csize)*sizeof(char)); } if (alloc == SWIG_NEWOBJ) { free((char*)cptr); res = SWIG_DelNewMask(res); } return res; } if (alloc == SWIG_NEWOBJ) free((char*)cptr); } return SWIG_TypeError; } SWIGINTERN int SWIG_AsVal_char (PyObject * obj, char *val) { int res = SWIG_AsCharArray(obj, val, 1); if (!SWIG_IsOK(res)) { long v; res = SWIG_AddCast(SWIG_AsVal_long (obj, &v)); if (SWIG_IsOK(res)) { if ((CHAR_MIN <= v) && (v <= CHAR_MAX)) { if (val) *val = (char)(v); } else { res = SWIG_OverflowError; } } } return res; } SWIGINTERNINLINE PyObject * SWIG_From_char (char c) { return SWIG_FromCharPtrAndSize(&c,1); } #ifdef __cplusplus extern "C" { #endif SWIGINTERN PyObject *_wrap_new_doubleArray(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; size_t arg1 ; size_t val1 ; int ecode1 = 0 ; PyObject * obj0 = 0 ; double *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:new_doubleArray",&obj0)) SWIG_fail; ecode1 = SWIG_AsVal_size_t(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "new_doubleArray" "', argument " "1"" of type '" "size_t""'"); } arg1 = (size_t)(val1); result = (double *)new_doubleArray(arg1); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_double, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete_doubleArray(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; double *arg1 = (double *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:delete_doubleArray",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_double, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_doubleArray" "', argument " "1"" of type '" "double *""'"); } arg1 = (double *)(argp1); delete_doubleArray(arg1); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_doubleArray_getitem(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; double *arg1 = (double *) 0 ; size_t arg2 ; void *argp1 = 0 ; int res1 = 0 ; size_t val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"OO:doubleArray_getitem",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_double, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "doubleArray_getitem" "', argument " "1"" of type '" "double *""'"); } arg1 = (double *)(argp1); ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "doubleArray_getitem" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); result = (double)doubleArray_getitem(arg1,arg2); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_doubleArray_setitem(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; double *arg1 = (double *) 0 ; size_t arg2 ; double arg3 ; void *argp1 = 0 ; int res1 = 0 ; size_t val2 ; int ecode2 = 0 ; double val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OOO:doubleArray_setitem",&obj0,&obj1,&obj2)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_double, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "doubleArray_setitem" "', argument " "1"" of type '" "double *""'"); } arg1 = (double *)(argp1); ecode2 = SWIG_AsVal_size_t(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "doubleArray_setitem" "', argument " "2"" of type '" "size_t""'"); } arg2 = (size_t)(val2); ecode3 = SWIG_AsVal_double(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "doubleArray_setitem" "', argument " "3"" of type '" "double""'"); } arg3 = (double)(val3); doubleArray_setitem(arg1,arg2,arg3); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_wcsinit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; char *arg1 = (char *) 0 ; int res1 ; char *buf1 = 0 ; int alloc1 = 0 ; PyObject * obj0 = 0 ; struct WorldCoor *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:wcsinit",&obj0)) SWIG_fail; res1 = SWIG_AsCharPtrAndSize(obj0, &buf1, NULL, &alloc1); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "wcsinit" "', argument " "1"" of type '" "char *""'"); } arg1 = (char *)(buf1); result = (struct WorldCoor *)wcsinit(arg1); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_WorldCoor, 0 | 0 ); if (alloc1 == SWIG_NEWOBJ) free((char*)buf1); return resultobj; fail: if (alloc1 == SWIG_NEWOBJ) free((char*)buf1); return NULL; } SWIGINTERN PyObject *_wrap_wcsxinit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; double arg1 ; double arg2 ; double arg3 ; int arg4 ; int arg5 ; int arg6 ; int arg7 ; double arg8 ; int arg9 ; double arg10 ; char *arg11 = (char *) 0 ; double val1 ; int ecode1 = 0 ; double val2 ; int ecode2 = 0 ; double val3 ; int ecode3 = 0 ; int val4 ; int ecode4 = 0 ; int val5 ; int ecode5 = 0 ; int val6 ; int ecode6 = 0 ; int val7 ; int ecode7 = 0 ; double val8 ; int ecode8 = 0 ; int val9 ; int ecode9 = 0 ; double val10 ; int ecode10 = 0 ; int res11 ; char *buf11 = 0 ; int alloc11 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; PyObject * obj3 = 0 ; PyObject * obj4 = 0 ; PyObject * obj5 = 0 ; PyObject * obj6 = 0 ; PyObject * obj7 = 0 ; PyObject * obj8 = 0 ; PyObject * obj9 = 0 ; PyObject * obj10 = 0 ; struct WorldCoor *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOOO:wcsxinit",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9,&obj10)) SWIG_fail; ecode1 = SWIG_AsVal_double(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "wcsxinit" "', argument " "1"" of type '" "double""'"); } arg1 = (double)(val1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "wcsxinit" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); ecode3 = SWIG_AsVal_double(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "wcsxinit" "', argument " "3"" of type '" "double""'"); } arg3 = (double)(val3); ecode4 = SWIG_AsVal_int(obj3, &val4); if (!SWIG_IsOK(ecode4)) { SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "wcsxinit" "', argument " "4"" of type '" "int""'"); } arg4 = (int)(val4); ecode5 = SWIG_AsVal_int(obj4, &val5); if (!SWIG_IsOK(ecode5)) { SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "wcsxinit" "', argument " "5"" of type '" "int""'"); } arg5 = (int)(val5); ecode6 = SWIG_AsVal_int(obj5, &val6); if (!SWIG_IsOK(ecode6)) { SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "wcsxinit" "', argument " "6"" of type '" "int""'"); } arg6 = (int)(val6); ecode7 = SWIG_AsVal_int(obj6, &val7); if (!SWIG_IsOK(ecode7)) { SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "wcsxinit" "', argument " "7"" of type '" "int""'"); } arg7 = (int)(val7); ecode8 = SWIG_AsVal_double(obj7, &val8); if (!SWIG_IsOK(ecode8)) { SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "wcsxinit" "', argument " "8"" of type '" "double""'"); } arg8 = (double)(val8); ecode9 = SWIG_AsVal_int(obj8, &val9); if (!SWIG_IsOK(ecode9)) { SWIG_exception_fail(SWIG_ArgError(ecode9), "in method '" "wcsxinit" "', argument " "9"" of type '" "int""'"); } arg9 = (int)(val9); ecode10 = SWIG_AsVal_double(obj9, &val10); if (!SWIG_IsOK(ecode10)) { SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "wcsxinit" "', argument " "10"" of type '" "double""'"); } arg10 = (double)(val10); res11 = SWIG_AsCharPtrAndSize(obj10, &buf11, NULL, &alloc11); if (!SWIG_IsOK(res11)) { SWIG_exception_fail(SWIG_ArgError(res11), "in method '" "wcsxinit" "', argument " "11"" of type '" "char *""'"); } arg11 = (char *)(buf11); result = (struct WorldCoor *)wcsxinit(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_WorldCoor, 0 | 0 ); if (alloc11 == SWIG_NEWOBJ) free((char*)buf11); return resultobj; fail: if (alloc11 == SWIG_NEWOBJ) free((char*)buf11); return NULL; } SWIGINTERN PyObject *_wrap_wcskinit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; int arg1 ; int arg2 ; char *arg3 = (char *) 0 ; char *arg4 = (char *) 0 ; double arg5 ; double arg6 ; double arg7 ; double arg8 ; double *arg9 = (double *) 0 ; double arg10 ; double arg11 ; double arg12 ; double arg13 ; double arg14 ; int val1 ; int ecode1 = 0 ; int val2 ; int ecode2 = 0 ; int res3 ; char *buf3 = 0 ; int alloc3 = 0 ; int res4 ; char *buf4 = 0 ; int alloc4 = 0 ; double val5 ; int ecode5 = 0 ; double val6 ; int ecode6 = 0 ; double val7 ; int ecode7 = 0 ; double val8 ; int ecode8 = 0 ; void *argp9 = 0 ; int res9 = 0 ; double val10 ; int ecode10 = 0 ; double val11 ; int ecode11 = 0 ; double val12 ; int ecode12 = 0 ; double val13 ; int ecode13 = 0 ; double val14 ; int ecode14 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; PyObject * obj3 = 0 ; PyObject * obj4 = 0 ; PyObject * obj5 = 0 ; PyObject * obj6 = 0 ; PyObject * obj7 = 0 ; PyObject * obj8 = 0 ; PyObject * obj9 = 0 ; PyObject * obj10 = 0 ; PyObject * obj11 = 0 ; PyObject * obj12 = 0 ; PyObject * obj13 = 0 ; struct WorldCoor *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"OOOOOOOOOOOOOO:wcskinit",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6,&obj7,&obj8,&obj9,&obj10,&obj11,&obj12,&obj13)) SWIG_fail; ecode1 = SWIG_AsVal_int(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "wcskinit" "', argument " "1"" of type '" "int""'"); } arg1 = (int)(val1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "wcskinit" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "wcskinit" "', argument " "3"" of type '" "char *""'"); } arg3 = (char *)(buf3); res4 = SWIG_AsCharPtrAndSize(obj3, &buf4, NULL, &alloc4); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "wcskinit" "', argument " "4"" of type '" "char *""'"); } arg4 = (char *)(buf4); ecode5 = SWIG_AsVal_double(obj4, &val5); if (!SWIG_IsOK(ecode5)) { SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "wcskinit" "', argument " "5"" of type '" "double""'"); } arg5 = (double)(val5); ecode6 = SWIG_AsVal_double(obj5, &val6); if (!SWIG_IsOK(ecode6)) { SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "wcskinit" "', argument " "6"" of type '" "double""'"); } arg6 = (double)(val6); ecode7 = SWIG_AsVal_double(obj6, &val7); if (!SWIG_IsOK(ecode7)) { SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "wcskinit" "', argument " "7"" of type '" "double""'"); } arg7 = (double)(val7); ecode8 = SWIG_AsVal_double(obj7, &val8); if (!SWIG_IsOK(ecode8)) { SWIG_exception_fail(SWIG_ArgError(ecode8), "in method '" "wcskinit" "', argument " "8"" of type '" "double""'"); } arg8 = (double)(val8); res9 = SWIG_ConvertPtr(obj8, &argp9,SWIGTYPE_p_double, 0 | 0 ); if (!SWIG_IsOK(res9)) { SWIG_exception_fail(SWIG_ArgError(res9), "in method '" "wcskinit" "', argument " "9"" of type '" "double *""'"); } arg9 = (double *)(argp9); ecode10 = SWIG_AsVal_double(obj9, &val10); if (!SWIG_IsOK(ecode10)) { SWIG_exception_fail(SWIG_ArgError(ecode10), "in method '" "wcskinit" "', argument " "10"" of type '" "double""'"); } arg10 = (double)(val10); ecode11 = SWIG_AsVal_double(obj10, &val11); if (!SWIG_IsOK(ecode11)) { SWIG_exception_fail(SWIG_ArgError(ecode11), "in method '" "wcskinit" "', argument " "11"" of type '" "double""'"); } arg11 = (double)(val11); ecode12 = SWIG_AsVal_double(obj11, &val12); if (!SWIG_IsOK(ecode12)) { SWIG_exception_fail(SWIG_ArgError(ecode12), "in method '" "wcskinit" "', argument " "12"" of type '" "double""'"); } arg12 = (double)(val12); ecode13 = SWIG_AsVal_double(obj12, &val13); if (!SWIG_IsOK(ecode13)) { SWIG_exception_fail(SWIG_ArgError(ecode13), "in method '" "wcskinit" "', argument " "13"" of type '" "double""'"); } arg13 = (double)(val13); ecode14 = SWIG_AsVal_double(obj13, &val14); if (!SWIG_IsOK(ecode14)) { SWIG_exception_fail(SWIG_ArgError(ecode14), "in method '" "wcskinit" "', argument " "14"" of type '" "double""'"); } arg14 = (double)(val14); result = (struct WorldCoor *)wcskinit(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11,arg12,arg13,arg14); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_WorldCoor, 0 | 0 ); if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); if (alloc4 == SWIG_NEWOBJ) free((char*)buf4); return resultobj; fail: if (alloc3 == SWIG_NEWOBJ) free((char*)buf3); if (alloc4 == SWIG_NEWOBJ) free((char*)buf4); return NULL; } SWIGINTERN PyObject *_wrap_iswcs(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:iswcs",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "iswcs" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int)iswcs(arg1); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_nowcs(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:nowcs",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "nowcs" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int)nowcs(arg1); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_wcs2pix(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; double arg3 ; double *arg4 = (double *) 0 ; double *arg5 = (double *) 0 ; int *arg6 = (int *) 0 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; double val3 ; int ecode3 = 0 ; double temp4 ; int res4 = SWIG_TMPOBJ ; double temp5 ; int res5 = SWIG_TMPOBJ ; int temp6 ; int res6 = SWIG_TMPOBJ ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; arg4 = &temp4; arg5 = &temp5; arg6 = &temp6; if (!PyArg_ParseTuple(args,(char *)"OOO:wcs2pix",&obj0,&obj1,&obj2)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "wcs2pix" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "wcs2pix" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); ecode3 = SWIG_AsVal_double(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "wcs2pix" "', argument " "3"" of type '" "double""'"); } arg3 = (double)(val3); wcs2pix(arg1,arg2,arg3,arg4,arg5,arg6); resultobj = SWIG_Py_Void(); if (SWIG_IsTmpObj(res4)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg4))); } else { int new_flags = SWIG_IsNewObj(res4) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg4), SWIGTYPE_p_double, new_flags)); } if (SWIG_IsTmpObj(res5)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg5))); } else { int new_flags = SWIG_IsNewObj(res5) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg5), SWIGTYPE_p_double, new_flags)); } if (SWIG_IsTmpObj(res6)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg6))); } else { int new_flags = SWIG_IsNewObj(res6) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg6), SWIGTYPE_p_int, new_flags)); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_pix2wcs(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; double arg3 ; double *arg4 = (double *) 0 ; double *arg5 = (double *) 0 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; double val3 ; int ecode3 = 0 ; double temp4 ; int res4 = SWIG_TMPOBJ ; double temp5 ; int res5 = SWIG_TMPOBJ ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; arg4 = &temp4; arg5 = &temp5; if (!PyArg_ParseTuple(args,(char *)"OOO:pix2wcs",&obj0,&obj1,&obj2)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pix2wcs" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "pix2wcs" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); ecode3 = SWIG_AsVal_double(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "pix2wcs" "', argument " "3"" of type '" "double""'"); } arg3 = (double)(val3); pix2wcs(arg1,arg2,arg3,arg4,arg5); resultobj = SWIG_Py_Void(); if (SWIG_IsTmpObj(res4)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg4))); } else { int new_flags = SWIG_IsNewObj(res4) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg4), SWIGTYPE_p_double, new_flags)); } if (SWIG_IsTmpObj(res5)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg5))); } else { int new_flags = SWIG_IsNewObj(res5) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg5), SWIGTYPE_p_double, new_flags)); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_wcscent(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:wcscent",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "wcscent" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); wcscent(arg1); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_getradecsys(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:getradecsys",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "getradecsys" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (char *)getradecsys(arg1); resultobj = SWIG_FromCharPtr((const char *)result); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_wcsoutinit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; char *arg2 = (char *) 0 ; void *argp1 = 0 ; int res1 = 0 ; int res2 ; char *buf2 = 0 ; int alloc2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:wcsoutinit",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "wcsoutinit" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "wcsoutinit" "', argument " "2"" of type '" "char *""'"); } arg2 = (char *)(buf2); wcsoutinit(arg1,arg2); resultobj = SWIG_Py_Void(); if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); return resultobj; fail: if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); return NULL; } SWIGINTERN PyObject *_wrap_wcsininit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; char *arg2 = (char *) 0 ; void *argp1 = 0 ; int res1 = 0 ; int res2 ; char *buf2 = 0 ; int alloc2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:wcsininit",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "wcsininit" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "wcsininit" "', argument " "2"" of type '" "char *""'"); } arg2 = (char *)(buf2); wcsininit(arg1,arg2); resultobj = SWIG_Py_Void(); if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); return resultobj; fail: if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); return NULL; } SWIGINTERN PyObject *_wrap_getwcsout(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:getwcsout",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "getwcsout" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (char *)getwcsout(arg1); resultobj = SWIG_FromCharPtr((const char *)result); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_getwcsin(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:getwcsin",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "getwcsin" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (char *)getwcsin(arg1); resultobj = SWIG_FromCharPtr((const char *)result); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_wcssize(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double *arg2 = (double *) 0 ; double *arg3 = (double *) 0 ; double *arg4 = (double *) 0 ; double *arg5 = (double *) 0 ; void *argp1 = 0 ; int res1 = 0 ; double temp2 ; int res2 = SWIG_TMPOBJ ; double temp3 ; int res3 = SWIG_TMPOBJ ; double temp4 ; int res4 = SWIG_TMPOBJ ; double temp5 ; int res5 = SWIG_TMPOBJ ; PyObject * obj0 = 0 ; arg2 = &temp2; arg3 = &temp3; arg4 = &temp4; arg5 = &temp5; if (!PyArg_ParseTuple(args,(char *)"O:wcssize",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "wcssize" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); wcssize(arg1,arg2,arg3,arg4,arg5); resultobj = SWIG_Py_Void(); if (SWIG_IsTmpObj(res2)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg2))); } else { int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_double, new_flags)); } if (SWIG_IsTmpObj(res3)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg3))); } else { int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_double, new_flags)); } if (SWIG_IsTmpObj(res4)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg4))); } else { int new_flags = SWIG_IsNewObj(res4) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg4), SWIGTYPE_p_double, new_flags)); } if (SWIG_IsTmpObj(res5)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg5))); } else { int new_flags = SWIG_IsNewObj(res5) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg5), SWIGTYPE_p_double, new_flags)); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_wcsfull(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double *arg2 = (double *) 0 ; double *arg3 = (double *) 0 ; double *arg4 = (double *) 0 ; double *arg5 = (double *) 0 ; void *argp1 = 0 ; int res1 = 0 ; double temp2 ; int res2 = SWIG_TMPOBJ ; double temp3 ; int res3 = SWIG_TMPOBJ ; double temp4 ; int res4 = SWIG_TMPOBJ ; double temp5 ; int res5 = SWIG_TMPOBJ ; PyObject * obj0 = 0 ; arg2 = &temp2; arg3 = &temp3; arg4 = &temp4; arg5 = &temp5; if (!PyArg_ParseTuple(args,(char *)"O:wcsfull",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "wcsfull" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); wcsfull(arg1,arg2,arg3,arg4,arg5); resultobj = SWIG_Py_Void(); if (SWIG_IsTmpObj(res2)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg2))); } else { int new_flags = SWIG_IsNewObj(res2) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg2), SWIGTYPE_p_double, new_flags)); } if (SWIG_IsTmpObj(res3)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg3))); } else { int new_flags = SWIG_IsNewObj(res3) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg3), SWIGTYPE_p_double, new_flags)); } if (SWIG_IsTmpObj(res4)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg4))); } else { int new_flags = SWIG_IsNewObj(res4) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg4), SWIGTYPE_p_double, new_flags)); } if (SWIG_IsTmpObj(res5)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg5))); } else { int new_flags = SWIG_IsNewObj(res5) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg5), SWIGTYPE_p_double, new_flags)); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_xref_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_xref_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_xref_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_xref_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->xref = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_xref_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_xref_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_xref_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->xref); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_yref_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_yref_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_yref_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_yref_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->yref = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_yref_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_yref_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_yref_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->yref); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_xrefpix_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_xrefpix_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_xrefpix_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_xrefpix_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->xrefpix = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_xrefpix_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_xrefpix_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_xrefpix_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->xrefpix); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_yrefpix_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_yrefpix_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_yrefpix_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_yrefpix_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->yrefpix = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_yrefpix_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_yrefpix_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_yrefpix_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->yrefpix); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_xinc_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_xinc_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_xinc_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_xinc_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->xinc = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_xinc_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_xinc_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_xinc_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->xinc); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_yinc_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_yinc_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_yinc_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_yinc_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->yinc = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_yinc_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_yinc_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_yinc_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->yinc); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_rot_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_rot_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_rot_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_rot_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->rot = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_rot_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_rot_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_rot_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->rot); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_cd_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double *arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_cd_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_cd_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_double, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_cd_set" "', argument " "2"" of type '" "double [4]""'"); } arg2 = (double *)(argp2); { if (arg2) { size_t ii = 0; for (; ii < (size_t)4; ++ii) arg1->cd[ii] = arg2[ii]; } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""cd""' of type '""double [4]""'"); } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_cd_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_cd_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_cd_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double *)(double *) ((arg1)->cd); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_double, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_dc_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double *arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_dc_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_dc_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_double, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_dc_set" "', argument " "2"" of type '" "double [4]""'"); } arg2 = (double *)(argp2); { if (arg2) { size_t ii = 0; for (; ii < (size_t)4; ++ii) arg1->dc[ii] = arg2[ii]; } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""dc""' of type '""double [4]""'"); } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_dc_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_dc_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_dc_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double *)(double *) ((arg1)->dc); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_double, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_equinox_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_equinox_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_equinox_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_equinox_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->equinox = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_equinox_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_equinox_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_equinox_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->equinox); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_epoch_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_epoch_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_epoch_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_epoch_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->epoch = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_epoch_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_epoch_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_epoch_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->epoch); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_nxpix_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_nxpix_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_nxpix_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_nxpix_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->nxpix = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_nxpix_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_nxpix_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_nxpix_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->nxpix); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_nypix_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_nypix_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_nypix_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_nypix_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->nypix = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_nypix_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_nypix_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_nypix_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->nypix); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_plate_ra_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_plate_ra_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_plate_ra_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_plate_ra_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->plate_ra = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_plate_ra_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_plate_ra_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_plate_ra_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->plate_ra); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_plate_dec_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_plate_dec_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_plate_dec_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_plate_dec_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->plate_dec = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_plate_dec_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_plate_dec_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_plate_dec_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->plate_dec); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_plate_scale_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_plate_scale_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_plate_scale_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_plate_scale_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->plate_scale = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_plate_scale_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_plate_scale_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_plate_scale_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->plate_scale); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_x_pixel_offset_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_x_pixel_offset_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_x_pixel_offset_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_x_pixel_offset_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->x_pixel_offset = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_x_pixel_offset_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_x_pixel_offset_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_x_pixel_offset_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->x_pixel_offset); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_y_pixel_offset_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_y_pixel_offset_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_y_pixel_offset_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_y_pixel_offset_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->y_pixel_offset = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_y_pixel_offset_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_y_pixel_offset_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_y_pixel_offset_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->y_pixel_offset); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_x_pixel_size_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_x_pixel_size_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_x_pixel_size_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_x_pixel_size_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->x_pixel_size = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_x_pixel_size_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_x_pixel_size_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_x_pixel_size_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->x_pixel_size); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_y_pixel_size_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_y_pixel_size_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_y_pixel_size_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_y_pixel_size_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->y_pixel_size = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_y_pixel_size_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_y_pixel_size_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_y_pixel_size_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->y_pixel_size); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ppo_coeff_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double *arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_ppo_coeff_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ppo_coeff_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_double, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_ppo_coeff_set" "', argument " "2"" of type '" "double [6]""'"); } arg2 = (double *)(argp2); { if (arg2) { size_t ii = 0; for (; ii < (size_t)6; ++ii) arg1->ppo_coeff[ii] = arg2[ii]; } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""ppo_coeff""' of type '""double [6]""'"); } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ppo_coeff_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_ppo_coeff_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ppo_coeff_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double *)(double *) ((arg1)->ppo_coeff); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_double, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_x_coeff_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double *arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_x_coeff_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_x_coeff_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_double, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_x_coeff_set" "', argument " "2"" of type '" "double [20]""'"); } arg2 = (double *)(argp2); { if (arg2) { size_t ii = 0; for (; ii < (size_t)20; ++ii) arg1->x_coeff[ii] = arg2[ii]; } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""x_coeff""' of type '""double [20]""'"); } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_x_coeff_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_x_coeff_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_x_coeff_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double *)(double *) ((arg1)->x_coeff); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_double, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_y_coeff_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double *arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_y_coeff_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_y_coeff_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_double, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_y_coeff_set" "', argument " "2"" of type '" "double [20]""'"); } arg2 = (double *)(argp2); { if (arg2) { size_t ii = 0; for (; ii < (size_t)20; ++ii) arg1->y_coeff[ii] = arg2[ii]; } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""y_coeff""' of type '""double [20]""'"); } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_y_coeff_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_y_coeff_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_y_coeff_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double *)(double *) ((arg1)->y_coeff); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_double, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_xpix_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_xpix_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_xpix_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_xpix_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->xpix = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_xpix_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_xpix_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_xpix_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->xpix); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ypix_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_ypix_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ypix_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_ypix_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->ypix = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ypix_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_ypix_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ypix_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->ypix); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_zpix_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_zpix_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_zpix_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_zpix_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->zpix = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_zpix_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_zpix_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_zpix_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->zpix); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_xpos_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_xpos_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_xpos_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_xpos_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->xpos = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_xpos_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_xpos_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_xpos_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->xpos); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ypos_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_ypos_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ypos_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_ypos_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->ypos = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ypos_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_ypos_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ypos_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->ypos); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_crpix_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double *arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_crpix_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_crpix_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_double, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_crpix_set" "', argument " "2"" of type '" "double [9]""'"); } arg2 = (double *)(argp2); { if (arg2) { size_t ii = 0; for (; ii < (size_t)9; ++ii) arg1->crpix[ii] = arg2[ii]; } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""crpix""' of type '""double [9]""'"); } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_crpix_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_crpix_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_crpix_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double *)(double *) ((arg1)->crpix); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_double, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_crval_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double *arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_crval_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_crval_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_double, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_crval_set" "', argument " "2"" of type '" "double [9]""'"); } arg2 = (double *)(argp2); { if (arg2) { size_t ii = 0; for (; ii < (size_t)9; ++ii) arg1->crval[ii] = arg2[ii]; } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""crval""' of type '""double [9]""'"); } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_crval_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_crval_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_crval_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double *)(double *) ((arg1)->crval); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_double, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_cdelt_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double *arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_cdelt_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_cdelt_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_double, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_cdelt_set" "', argument " "2"" of type '" "double [9]""'"); } arg2 = (double *)(argp2); { if (arg2) { size_t ii = 0; for (; ii < (size_t)9; ++ii) arg1->cdelt[ii] = arg2[ii]; } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""cdelt""' of type '""double [9]""'"); } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_cdelt_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_cdelt_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_cdelt_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double *)(double *) ((arg1)->cdelt); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_double, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_pc_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double *arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_pc_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_pc_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_double, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_pc_set" "', argument " "2"" of type '" "double [81]""'"); } arg2 = (double *)(argp2); { if (arg2) { size_t ii = 0; for (; ii < (size_t)81; ++ii) arg1->pc[ii] = arg2[ii]; } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""pc""' of type '""double [81]""'"); } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_pc_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_pc_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_pc_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double *)(double *) ((arg1)->pc); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_double, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_projp_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double *arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_projp_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_projp_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_double, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_projp_set" "', argument " "2"" of type '" "double [10]""'"); } arg2 = (double *)(argp2); { if (arg2) { size_t ii = 0; for (; ii < (size_t)10; ++ii) arg1->projp[ii] = arg2[ii]; } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""projp""' of type '""double [10]""'"); } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_projp_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_projp_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_projp_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double *)(double *) ((arg1)->projp); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_double, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_pvfail_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_pvfail_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_pvfail_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_pvfail_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->pvfail = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_pvfail_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_pvfail_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_pvfail_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->pvfail); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_projppv_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double *arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_projppv_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_projppv_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_double, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_projppv_set" "', argument " "2"" of type '" "double [2*MAXPV]""'"); } arg2 = (double *)(argp2); { if (arg2) { size_t ii = 0; for (; ii < (size_t)2*MAXPV; ++ii) arg1->projppv[ii] = arg2[ii]; } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""projppv""' of type '""double [2*MAXPV]""'"); } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_projppv_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_projppv_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_projppv_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double *)(double *) ((arg1)->projppv); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_double, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_inv_x_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; struct poly *arg2 = (struct poly *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_inv_x_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_inv_x_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_poly, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_inv_x_set" "', argument " "2"" of type '" "struct poly *""'"); } arg2 = (struct poly *)(argp2); if (arg1) (arg1)->inv_x = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_inv_x_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; struct poly *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_inv_x_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_inv_x_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (struct poly *) ((arg1)->inv_x); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_poly, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_inv_y_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; struct poly *arg2 = (struct poly *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_inv_y_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_inv_y_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_poly, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_inv_y_set" "', argument " "2"" of type '" "struct poly *""'"); } arg2 = (struct poly *)(argp2); if (arg1) (arg1)->inv_y = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_inv_y_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; struct poly *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_inv_y_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_inv_y_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (struct poly *) ((arg1)->inv_y); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_poly, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_longpole_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_longpole_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_longpole_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_longpole_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->longpole = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_longpole_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_longpole_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_longpole_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->longpole); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_latpole_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_latpole_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_latpole_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_latpole_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->latpole = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_latpole_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_latpole_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_latpole_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->latpole); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_rodeg_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_rodeg_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_rodeg_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_rodeg_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->rodeg = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_rodeg_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_rodeg_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_rodeg_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->rodeg); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_imrot_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_imrot_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_imrot_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_imrot_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->imrot = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_imrot_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_imrot_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_imrot_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->imrot); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_pa_north_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_pa_north_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_pa_north_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_pa_north_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->pa_north = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_pa_north_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_pa_north_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_pa_north_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->pa_north); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_pa_east_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_pa_east_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_pa_east_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_pa_east_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->pa_east = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_pa_east_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_pa_east_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_pa_east_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->pa_east); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_radvel_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_radvel_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_radvel_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_radvel_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->radvel = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_radvel_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_radvel_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_radvel_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->radvel); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_zvel_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_zvel_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_zvel_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_zvel_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->zvel = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_zvel_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_zvel_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_zvel_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->zvel); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_zpzd_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_zpzd_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_zpzd_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_zpzd_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->zpzd = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_zpzd_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_zpzd_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_zpzd_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->zpzd); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_zpr_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_zpr_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_zpr_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_zpr_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->zpr = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_zpr_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_zpr_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_zpr_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->zpr); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_imflip_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_imflip_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_imflip_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_imflip_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->imflip = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_imflip_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_imflip_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_imflip_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->imflip); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_prjcode_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_prjcode_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_prjcode_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_prjcode_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->prjcode = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_prjcode_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_prjcode_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_prjcode_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->prjcode); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_latbase_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_latbase_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_latbase_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_latbase_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->latbase = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_latbase_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_latbase_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_latbase_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->latbase); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ncoeff1_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_ncoeff1_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ncoeff1_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_ncoeff1_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->ncoeff1 = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ncoeff1_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_ncoeff1_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ncoeff1_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->ncoeff1); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ncoeff2_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_ncoeff2_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ncoeff2_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_ncoeff2_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->ncoeff2 = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ncoeff2_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_ncoeff2_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ncoeff2_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->ncoeff2); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_zpnp_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_zpnp_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_zpnp_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_zpnp_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->zpnp = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_zpnp_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_zpnp_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_zpnp_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->zpnp); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_changesys_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_changesys_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_changesys_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_changesys_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->changesys = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_changesys_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_changesys_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_changesys_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->changesys); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_printsys_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_printsys_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_printsys_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_printsys_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->printsys = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_printsys_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_printsys_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_printsys_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->printsys); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ndec_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_ndec_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ndec_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_ndec_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->ndec = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ndec_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_ndec_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ndec_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->ndec); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_degout_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_degout_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_degout_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_degout_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->degout = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_degout_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_degout_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_degout_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->degout); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_tabsys_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_tabsys_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_tabsys_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_tabsys_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->tabsys = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_tabsys_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_tabsys_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_tabsys_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->tabsys); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_rotmat_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_rotmat_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_rotmat_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_rotmat_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->rotmat = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_rotmat_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_rotmat_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_rotmat_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->rotmat); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_coorflip_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_coorflip_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_coorflip_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_coorflip_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->coorflip = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_coorflip_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_coorflip_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_coorflip_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->coorflip); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_offscl_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_offscl_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_offscl_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_offscl_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->offscl = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_offscl_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_offscl_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_offscl_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->offscl); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_wcson_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_wcson_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_wcson_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_wcson_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->wcson = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_wcson_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_wcson_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_wcson_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->wcson); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_naxis_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_naxis_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_naxis_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_naxis_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->naxis = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_naxis_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_naxis_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_naxis_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->naxis); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_naxes_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_naxes_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_naxes_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_naxes_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->naxes = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_naxes_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_naxes_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_naxes_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->naxes); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_wcsproj_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_wcsproj_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_wcsproj_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_wcsproj_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->wcsproj = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_wcsproj_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_wcsproj_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_wcsproj_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->wcsproj); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_linmode_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_linmode_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_linmode_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_linmode_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->linmode = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_linmode_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_linmode_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_linmode_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->linmode); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_detector_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_detector_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_detector_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_detector_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->detector = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_detector_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_detector_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_detector_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->detector); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_instrument_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; char *arg2 ; void *argp1 = 0 ; int res1 = 0 ; char temp2[32] ; int res2 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_instrument_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_instrument_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_AsCharArray(obj1, temp2, 32); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_instrument_set" "', argument " "2"" of type '" "char [32]""'"); } arg2 = (char *)(temp2); if (arg2) memcpy(arg1->instrument,arg2,32*sizeof(char)); else memset(arg1->instrument,0,32*sizeof(char)); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_instrument_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_instrument_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_instrument_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (char *)(char *) ((arg1)->instrument); { size_t size = 32; while (size && (result[size - 1] == '\0')) --size; resultobj = SWIG_FromCharPtrAndSize(result, size); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ctype_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; char (*arg2)[9] ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_ctype_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ctype_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_a_9__char, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_ctype_set" "', argument " "2"" of type '" "char [9][9]""'"); } arg2 = (char (*)[9])(argp2); { if (arg2) { size_t ii = 0; for (; ii < (size_t)9; ++ii) { if (arg2[ii]) { size_t jj = 0; for (; jj < (size_t)9; ++jj) arg1->ctype[ii][jj] = arg2[ii][jj]; } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""ctype""' of type '""char [9][9]""'"); } } } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""ctype""' of type '""char [9][9]""'"); } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ctype_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char (*result)[9] = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_ctype_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ctype_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (char (*)[9])(char (*)[9]) ((arg1)->ctype); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_a_9__char, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_c1type_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; char *arg2 ; void *argp1 = 0 ; int res1 = 0 ; char temp2[9] ; int res2 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_c1type_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_c1type_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_AsCharArray(obj1, temp2, 9); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_c1type_set" "', argument " "2"" of type '" "char [9]""'"); } arg2 = (char *)(temp2); if (arg2) memcpy(arg1->c1type,arg2,9*sizeof(char)); else memset(arg1->c1type,0,9*sizeof(char)); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_c1type_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_c1type_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_c1type_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (char *)(char *) ((arg1)->c1type); { size_t size = 9; while (size && (result[size - 1] == '\0')) --size; resultobj = SWIG_FromCharPtrAndSize(result, size); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_c2type_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; char *arg2 ; void *argp1 = 0 ; int res1 = 0 ; char temp2[9] ; int res2 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_c2type_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_c2type_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_AsCharArray(obj1, temp2, 9); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_c2type_set" "', argument " "2"" of type '" "char [9]""'"); } arg2 = (char *)(temp2); if (arg2) memcpy(arg1->c2type,arg2,9*sizeof(char)); else memset(arg1->c2type,0,9*sizeof(char)); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_c2type_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_c2type_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_c2type_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (char *)(char *) ((arg1)->c2type); { size_t size = 9; while (size && (result[size - 1] == '\0')) --size; resultobj = SWIG_FromCharPtrAndSize(result, size); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ptype_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; char *arg2 ; void *argp1 = 0 ; int res1 = 0 ; char temp2[9] ; int res2 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_ptype_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ptype_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_AsCharArray(obj1, temp2, 9); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_ptype_set" "', argument " "2"" of type '" "char [9]""'"); } arg2 = (char *)(temp2); if (arg2) memcpy(arg1->ptype,arg2,9*sizeof(char)); else memset(arg1->ptype,0,9*sizeof(char)); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ptype_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_ptype_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ptype_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (char *)(char *) ((arg1)->ptype); { size_t size = 9; while (size && (result[size - 1] == '\0')) --size; resultobj = SWIG_FromCharPtrAndSize(result, size); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_units_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; char (*arg2)[32] ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_units_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_units_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_a_32__char, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_units_set" "', argument " "2"" of type '" "char [9][32]""'"); } arg2 = (char (*)[32])(argp2); { if (arg2) { size_t ii = 0; for (; ii < (size_t)9; ++ii) { if (arg2[ii]) { size_t jj = 0; for (; jj < (size_t)32; ++jj) arg1->units[ii][jj] = arg2[ii][jj]; } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""units""' of type '""char [9][32]""'"); } } } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""units""' of type '""char [9][32]""'"); } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_units_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char (*result)[32] = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_units_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_units_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (char (*)[32])(char (*)[32]) ((arg1)->units); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_a_32__char, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_radecsys_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; char *arg2 ; void *argp1 = 0 ; int res1 = 0 ; char temp2[32] ; int res2 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_radecsys_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_radecsys_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_AsCharArray(obj1, temp2, 32); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_radecsys_set" "', argument " "2"" of type '" "char [32]""'"); } arg2 = (char *)(temp2); if (arg2) memcpy(arg1->radecsys,arg2,32*sizeof(char)); else memset(arg1->radecsys,0,32*sizeof(char)); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_radecsys_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_radecsys_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_radecsys_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (char *)(char *) ((arg1)->radecsys); { size_t size = 32; while (size && (result[size - 1] == '\0')) --size; resultobj = SWIG_FromCharPtrAndSize(result, size); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_radecout_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; char *arg2 ; void *argp1 = 0 ; int res1 = 0 ; char temp2[32] ; int res2 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_radecout_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_radecout_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_AsCharArray(obj1, temp2, 32); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_radecout_set" "', argument " "2"" of type '" "char [32]""'"); } arg2 = (char *)(temp2); if (arg2) memcpy(arg1->radecout,arg2,32*sizeof(char)); else memset(arg1->radecout,0,32*sizeof(char)); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_radecout_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_radecout_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_radecout_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (char *)(char *) ((arg1)->radecout); { size_t size = 32; while (size && (result[size - 1] == '\0')) --size; resultobj = SWIG_FromCharPtrAndSize(result, size); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_radecin_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; char *arg2 ; void *argp1 = 0 ; int res1 = 0 ; char temp2[32] ; int res2 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_radecin_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_radecin_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_AsCharArray(obj1, temp2, 32); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_radecin_set" "', argument " "2"" of type '" "char [32]""'"); } arg2 = (char *)(temp2); if (arg2) memcpy(arg1->radecin,arg2,32*sizeof(char)); else memset(arg1->radecin,0,32*sizeof(char)); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_radecin_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_radecin_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_radecin_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (char *)(char *) ((arg1)->radecin); { size_t size = 32; while (size && (result[size - 1] == '\0')) --size; resultobj = SWIG_FromCharPtrAndSize(result, size); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_eqin_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_eqin_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_eqin_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_eqin_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->eqin = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_eqin_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_eqin_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_eqin_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->eqin); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_eqout_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double arg2 ; void *argp1 = 0 ; int res1 = 0 ; double val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_eqout_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_eqout_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_double(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_eqout_set" "', argument " "2"" of type '" "double""'"); } arg2 = (double)(val2); if (arg1) (arg1)->eqout = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_eqout_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_eqout_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_eqout_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double) ((arg1)->eqout); resultobj = SWIG_From_double((double)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_sysin_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_sysin_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_sysin_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_sysin_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->sysin = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_sysin_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_sysin_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_sysin_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->sysin); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_syswcs_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_syswcs_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_syswcs_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_syswcs_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->syswcs = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_syswcs_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_syswcs_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_syswcs_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->syswcs); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_sysout_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_sysout_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_sysout_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_sysout_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->sysout = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_sysout_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_sysout_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_sysout_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->sysout); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_center_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; char *arg2 ; void *argp1 = 0 ; int res1 = 0 ; char temp2[32] ; int res2 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_center_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_center_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_AsCharArray(obj1, temp2, 32); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_center_set" "', argument " "2"" of type '" "char [32]""'"); } arg2 = (char *)(temp2); if (arg2) memcpy(arg1->center,arg2,32*sizeof(char)); else memset(arg1->center,0,32*sizeof(char)); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_center_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_center_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_center_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (char *)(char *) ((arg1)->center); { size_t size = 32; while (size && (result[size - 1] == '\0')) --size; resultobj = SWIG_FromCharPtrAndSize(result, size); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_wcsl_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; struct wcsprm arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_wcsl_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_wcsl_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); { res2 = SWIG_ConvertPtr(obj1, &argp2, SWIGTYPE_p_wcsprm, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_wcsl_set" "', argument " "2"" of type '" "struct wcsprm""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "WorldCoor_wcsl_set" "', argument " "2"" of type '" "struct wcsprm""'"); } else { arg2 = *((struct wcsprm *)(argp2)); } } if (arg1) (arg1)->wcsl = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_wcsl_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; struct wcsprm result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_wcsl_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_wcsl_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = ((arg1)->wcsl); resultobj = SWIG_NewPointerObj((struct wcsprm *)memcpy((struct wcsprm *)malloc(sizeof(struct wcsprm)),&result,sizeof(struct wcsprm)), SWIGTYPE_p_wcsprm, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_lin_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; struct linprm arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_lin_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_lin_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); { res2 = SWIG_ConvertPtr(obj1, &argp2, SWIGTYPE_p_linprm, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_lin_set" "', argument " "2"" of type '" "struct linprm""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "WorldCoor_lin_set" "', argument " "2"" of type '" "struct linprm""'"); } else { arg2 = *((struct linprm *)(argp2)); } } if (arg1) (arg1)->lin = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_lin_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; struct linprm result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_lin_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_lin_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = ((arg1)->lin); resultobj = SWIG_NewPointerObj((struct linprm *)memcpy((struct linprm *)malloc(sizeof(struct linprm)),&result,sizeof(struct linprm)), SWIGTYPE_p_linprm, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_cel_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; struct celprm arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_cel_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_cel_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); { res2 = SWIG_ConvertPtr(obj1, &argp2, SWIGTYPE_p_celprm, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_cel_set" "', argument " "2"" of type '" "struct celprm""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "WorldCoor_cel_set" "', argument " "2"" of type '" "struct celprm""'"); } else { arg2 = *((struct celprm *)(argp2)); } } if (arg1) (arg1)->cel = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_cel_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; struct celprm result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_cel_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_cel_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = ((arg1)->cel); resultobj = SWIG_NewPointerObj((struct celprm *)memcpy((struct celprm *)malloc(sizeof(struct celprm)),&result,sizeof(struct celprm)), SWIGTYPE_p_celprm, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_prj_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; struct prjprm arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_prj_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_prj_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); { res2 = SWIG_ConvertPtr(obj1, &argp2, SWIGTYPE_p_prjprm, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_prj_set" "', argument " "2"" of type '" "struct prjprm""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "WorldCoor_prj_set" "', argument " "2"" of type '" "struct prjprm""'"); } else { arg2 = *((struct prjprm *)(argp2)); } } if (arg1) (arg1)->prj = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_prj_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; struct prjprm result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_prj_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_prj_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = ((arg1)->prj); resultobj = SWIG_NewPointerObj((struct prjprm *)memcpy((struct prjprm *)malloc(sizeof(struct prjprm)),&result,sizeof(struct prjprm)), SWIGTYPE_p_prjprm, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_lngcor_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; struct IRAFsurface *arg2 = (struct IRAFsurface *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_lngcor_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_lngcor_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_IRAFsurface, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_lngcor_set" "', argument " "2"" of type '" "struct IRAFsurface *""'"); } arg2 = (struct IRAFsurface *)(argp2); if (arg1) (arg1)->lngcor = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_lngcor_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; struct IRAFsurface *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_lngcor_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_lngcor_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (struct IRAFsurface *) ((arg1)->lngcor); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_IRAFsurface, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_latcor_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; struct IRAFsurface *arg2 = (struct IRAFsurface *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_latcor_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_latcor_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_IRAFsurface, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_latcor_set" "', argument " "2"" of type '" "struct IRAFsurface *""'"); } arg2 = (struct IRAFsurface *)(argp2); if (arg1) (arg1)->latcor = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_latcor_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; struct IRAFsurface *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_latcor_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_latcor_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (struct IRAFsurface *) ((arg1)->latcor); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_IRAFsurface, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_distcode_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_distcode_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_distcode_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_distcode_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->distcode = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_distcode_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_distcode_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_distcode_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->distcode); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_distort_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; struct Distort arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_distort_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_distort_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); { res2 = SWIG_ConvertPtr(obj1, &argp2, SWIGTYPE_p_Distort, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_distort_set" "', argument " "2"" of type '" "struct Distort""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "WorldCoor_distort_set" "', argument " "2"" of type '" "struct Distort""'"); } else { arg2 = *((struct Distort *)(argp2)); } } if (arg1) (arg1)->distort = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_distort_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; struct Distort result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_distort_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_distort_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = ((arg1)->distort); resultobj = SWIG_NewPointerObj((struct Distort *)memcpy((struct Distort *)malloc(sizeof(struct Distort)),&result,sizeof(struct Distort)), SWIGTYPE_p_Distort, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_command_format_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; char **arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_command_format_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_command_format_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_p_char, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_command_format_set" "', argument " "2"" of type '" "char *[10]""'"); } arg2 = (char **)(argp2); { if (arg2) { size_t ii = 0; for (; ii < (size_t)10; ++ii) arg1->command_format[ii] = arg2[ii]; } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""command_format""' of type '""char *[10]""'"); } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_command_format_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char **result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_command_format_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_command_format_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (char **)(char **) ((arg1)->command_format); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_p_char, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ltm_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double *arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_ltm_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ltm_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_double, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_ltm_set" "', argument " "2"" of type '" "double [4]""'"); } arg2 = (double *)(argp2); { if (arg2) { size_t ii = 0; for (; ii < (size_t)4; ++ii) arg1->ltm[ii] = arg2[ii]; } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""ltm""' of type '""double [4]""'"); } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ltm_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_ltm_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ltm_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double *)(double *) ((arg1)->ltm); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_double, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ltv_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; double *arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_ltv_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ltv_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_double, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_ltv_set" "', argument " "2"" of type '" "double [2]""'"); } arg2 = (double *)(argp2); { if (arg2) { size_t ii = 0; for (; ii < (size_t)2; ++ii) arg1->ltv[ii] = arg2[ii]; } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""ltv""' of type '""double [2]""'"); } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ltv_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; double *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_ltv_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ltv_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (double *)(double *) ((arg1)->ltv); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_double, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_idpix_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int *arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_idpix_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_idpix_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_int, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_idpix_set" "', argument " "2"" of type '" "int [2]""'"); } arg2 = (int *)(argp2); { if (arg2) { size_t ii = 0; for (; ii < (size_t)2; ++ii) arg1->idpix[ii] = arg2[ii]; } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""idpix""' of type '""int [2]""'"); } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_idpix_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_idpix_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_idpix_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int *)(int *) ((arg1)->idpix); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_int, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ndpix_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int *arg2 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_ndpix_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ndpix_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_int, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_ndpix_set" "', argument " "2"" of type '" "int [2]""'"); } arg2 = (int *)(argp2); { if (arg2) { size_t ii = 0; for (; ii < (size_t)2; ++ii) arg1->ndpix[ii] = arg2[ii]; } else { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""ndpix""' of type '""int [2]""'"); } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_ndpix_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_ndpix_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_ndpix_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int *)(int *) ((arg1)->ndpix); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_int, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_wcs_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; struct WorldCoor *arg2 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_wcs_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_wcs_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_WorldCoor, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_wcs_set" "', argument " "2"" of type '" "struct WorldCoor *""'"); } arg2 = (struct WorldCoor *)(argp2); if (arg1) (arg1)->wcs = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_wcs_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; struct WorldCoor *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_wcs_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_wcs_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (struct WorldCoor *) ((arg1)->wcs); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_WorldCoor, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_wcsdep_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; struct WorldCoor *arg2 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_wcsdep_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_wcsdep_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_WorldCoor, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_wcsdep_set" "', argument " "2"" of type '" "struct WorldCoor *""'"); } arg2 = (struct WorldCoor *)(argp2); if (arg1) (arg1)->wcsdep = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_wcsdep_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; struct WorldCoor *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_wcsdep_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_wcsdep_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (struct WorldCoor *) ((arg1)->wcsdep); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_WorldCoor, 0 | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_wcsname_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; char *arg2 = (char *) 0 ; void *argp1 = 0 ; int res1 = 0 ; int res2 ; char *buf2 = 0 ; int alloc2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_wcsname_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_wcsname_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "WorldCoor_wcsname_set" "', argument " "2"" of type '" "char *""'"); } arg2 = (char *)(buf2); if (arg1->wcsname) free((char*)arg1->wcsname); if (arg2) { size_t size = strlen((const char *)(arg2)) + 1; arg1->wcsname = (char *)(char *)memcpy((char *)malloc((size)*sizeof(char)), (const char *)(arg2), sizeof(char)*(size)); } else { arg1->wcsname = 0; } resultobj = SWIG_Py_Void(); if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); return resultobj; fail: if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_wcsname_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_wcsname_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_wcsname_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (char *) ((arg1)->wcsname); resultobj = SWIG_FromCharPtr((const char *)result); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_wcschar_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; char arg2 ; void *argp1 = 0 ; int res1 = 0 ; char val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_wcschar_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_wcschar_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_char(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_wcschar_set" "', argument " "2"" of type '" "char""'"); } arg2 = (char)(val2); if (arg1) (arg1)->wcschar = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_wcschar_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; char result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_wcschar_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_wcschar_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (char) ((arg1)->wcschar); resultobj = SWIG_From_char((char)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_logwcs_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; int arg2 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:WorldCoor_logwcs_set",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_logwcs_set" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "WorldCoor_logwcs_set" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); if (arg1) (arg1)->logwcs = arg2; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_WorldCoor_logwcs_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:WorldCoor_logwcs_get",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "WorldCoor_logwcs_get" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); result = (int) ((arg1)->logwcs); resultobj = SWIG_From_int((int)(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_new_WorldCoor(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *result = 0 ; if (!PyArg_ParseTuple(args,(char *)":new_WorldCoor")) SWIG_fail; result = (struct WorldCoor *)calloc(1, sizeof(struct WorldCoor)); resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_WorldCoor, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete_WorldCoor(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; struct WorldCoor *arg1 = (struct WorldCoor *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:delete_WorldCoor",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_WorldCoor, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_WorldCoor" "', argument " "1"" of type '" "struct WorldCoor *""'"); } arg1 = (struct WorldCoor *)(argp1); free((char *) arg1); resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *WorldCoor_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_WorldCoor, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } static PyMethodDef SwigMethods[] = { { (char *)"SWIG_PyInstanceMethod_New", (PyCFunction)SWIG_PyInstanceMethod_New, METH_O, NULL}, { (char *)"new_doubleArray", _wrap_new_doubleArray, METH_VARARGS, (char *)"new_doubleArray(nelements) -> double *"}, { (char *)"delete_doubleArray", _wrap_delete_doubleArray, METH_VARARGS, (char *)"delete_doubleArray(ary)"}, { (char *)"doubleArray_getitem", _wrap_doubleArray_getitem, METH_VARARGS, (char *)"doubleArray_getitem(ary, index) -> double"}, { (char *)"doubleArray_setitem", _wrap_doubleArray_setitem, METH_VARARGS, (char *)"doubleArray_setitem(ary, index, value)"}, { (char *)"wcsinit", _wrap_wcsinit, METH_VARARGS, (char *)"wcsinit(hstring) -> WorldCoor"}, { (char *)"wcsxinit", _wrap_wcsxinit, METH_VARARGS, (char *)"wcsxinit(cra, cdec, secpix, xrpix, yrpix, nxpix, nypix, rotate, equinox, epoch, proj) -> WorldCoor"}, { (char *)"wcskinit", _wrap_wcskinit, METH_VARARGS, (char *)"\n" "wcskinit(nxpix, nypix, ctype1, ctype2, crpix1, crpix2, crval1, crval2, cd, cdelt1, cdelt2, \n" " crota, equinox, epoch) -> WorldCoor\n" ""}, { (char *)"iswcs", _wrap_iswcs, METH_VARARGS, (char *)"iswcs(wcs) -> int"}, { (char *)"nowcs", _wrap_nowcs, METH_VARARGS, (char *)"nowcs(wcs) -> int"}, { (char *)"wcs2pix", _wrap_wcs2pix, METH_VARARGS, (char *)"wcs2pix(wcs, xpos, ypos)"}, { (char *)"pix2wcs", _wrap_pix2wcs, METH_VARARGS, (char *)"pix2wcs(wcs, xpix, ypix)"}, { (char *)"wcscent", _wrap_wcscent, METH_VARARGS, (char *)"wcscent(wcs)"}, { (char *)"getradecsys", _wrap_getradecsys, METH_VARARGS, (char *)"getradecsys(wcs) -> char *"}, { (char *)"wcsoutinit", _wrap_wcsoutinit, METH_VARARGS, (char *)"wcsoutinit(wcs, coorsys)"}, { (char *)"wcsininit", _wrap_wcsininit, METH_VARARGS, (char *)"wcsininit(wcs, coorsys)"}, { (char *)"getwcsout", _wrap_getwcsout, METH_VARARGS, (char *)"getwcsout(wcs) -> char *"}, { (char *)"getwcsin", _wrap_getwcsin, METH_VARARGS, (char *)"getwcsin(wcs) -> char *"}, { (char *)"wcssize", _wrap_wcssize, METH_VARARGS, (char *)"wcssize(wcs)"}, { (char *)"wcsfull", _wrap_wcsfull, METH_VARARGS, (char *)"wcsfull(wcs)"}, { (char *)"WorldCoor_xref_set", _wrap_WorldCoor_xref_set, METH_VARARGS, (char *)"WorldCoor_xref_set(self, xref)"}, { (char *)"WorldCoor_xref_get", _wrap_WorldCoor_xref_get, METH_VARARGS, (char *)"WorldCoor_xref_get(self) -> double"}, { (char *)"WorldCoor_yref_set", _wrap_WorldCoor_yref_set, METH_VARARGS, (char *)"WorldCoor_yref_set(self, yref)"}, { (char *)"WorldCoor_yref_get", _wrap_WorldCoor_yref_get, METH_VARARGS, (char *)"WorldCoor_yref_get(self) -> double"}, { (char *)"WorldCoor_xrefpix_set", _wrap_WorldCoor_xrefpix_set, METH_VARARGS, (char *)"WorldCoor_xrefpix_set(self, xrefpix)"}, { (char *)"WorldCoor_xrefpix_get", _wrap_WorldCoor_xrefpix_get, METH_VARARGS, (char *)"WorldCoor_xrefpix_get(self) -> double"}, { (char *)"WorldCoor_yrefpix_set", _wrap_WorldCoor_yrefpix_set, METH_VARARGS, (char *)"WorldCoor_yrefpix_set(self, yrefpix)"}, { (char *)"WorldCoor_yrefpix_get", _wrap_WorldCoor_yrefpix_get, METH_VARARGS, (char *)"WorldCoor_yrefpix_get(self) -> double"}, { (char *)"WorldCoor_xinc_set", _wrap_WorldCoor_xinc_set, METH_VARARGS, (char *)"WorldCoor_xinc_set(self, xinc)"}, { (char *)"WorldCoor_xinc_get", _wrap_WorldCoor_xinc_get, METH_VARARGS, (char *)"WorldCoor_xinc_get(self) -> double"}, { (char *)"WorldCoor_yinc_set", _wrap_WorldCoor_yinc_set, METH_VARARGS, (char *)"WorldCoor_yinc_set(self, yinc)"}, { (char *)"WorldCoor_yinc_get", _wrap_WorldCoor_yinc_get, METH_VARARGS, (char *)"WorldCoor_yinc_get(self) -> double"}, { (char *)"WorldCoor_rot_set", _wrap_WorldCoor_rot_set, METH_VARARGS, (char *)"WorldCoor_rot_set(self, rot)"}, { (char *)"WorldCoor_rot_get", _wrap_WorldCoor_rot_get, METH_VARARGS, (char *)"WorldCoor_rot_get(self) -> double"}, { (char *)"WorldCoor_cd_set", _wrap_WorldCoor_cd_set, METH_VARARGS, (char *)"WorldCoor_cd_set(self, cd)"}, { (char *)"WorldCoor_cd_get", _wrap_WorldCoor_cd_get, METH_VARARGS, (char *)"WorldCoor_cd_get(self) -> double [4]"}, { (char *)"WorldCoor_dc_set", _wrap_WorldCoor_dc_set, METH_VARARGS, (char *)"WorldCoor_dc_set(self, dc)"}, { (char *)"WorldCoor_dc_get", _wrap_WorldCoor_dc_get, METH_VARARGS, (char *)"WorldCoor_dc_get(self) -> double [4]"}, { (char *)"WorldCoor_equinox_set", _wrap_WorldCoor_equinox_set, METH_VARARGS, (char *)"WorldCoor_equinox_set(self, equinox)"}, { (char *)"WorldCoor_equinox_get", _wrap_WorldCoor_equinox_get, METH_VARARGS, (char *)"WorldCoor_equinox_get(self) -> double"}, { (char *)"WorldCoor_epoch_set", _wrap_WorldCoor_epoch_set, METH_VARARGS, (char *)"WorldCoor_epoch_set(self, epoch)"}, { (char *)"WorldCoor_epoch_get", _wrap_WorldCoor_epoch_get, METH_VARARGS, (char *)"WorldCoor_epoch_get(self) -> double"}, { (char *)"WorldCoor_nxpix_set", _wrap_WorldCoor_nxpix_set, METH_VARARGS, (char *)"WorldCoor_nxpix_set(self, nxpix)"}, { (char *)"WorldCoor_nxpix_get", _wrap_WorldCoor_nxpix_get, METH_VARARGS, (char *)"WorldCoor_nxpix_get(self) -> double"}, { (char *)"WorldCoor_nypix_set", _wrap_WorldCoor_nypix_set, METH_VARARGS, (char *)"WorldCoor_nypix_set(self, nypix)"}, { (char *)"WorldCoor_nypix_get", _wrap_WorldCoor_nypix_get, METH_VARARGS, (char *)"WorldCoor_nypix_get(self) -> double"}, { (char *)"WorldCoor_plate_ra_set", _wrap_WorldCoor_plate_ra_set, METH_VARARGS, (char *)"WorldCoor_plate_ra_set(self, plate_ra)"}, { (char *)"WorldCoor_plate_ra_get", _wrap_WorldCoor_plate_ra_get, METH_VARARGS, (char *)"WorldCoor_plate_ra_get(self) -> double"}, { (char *)"WorldCoor_plate_dec_set", _wrap_WorldCoor_plate_dec_set, METH_VARARGS, (char *)"WorldCoor_plate_dec_set(self, plate_dec)"}, { (char *)"WorldCoor_plate_dec_get", _wrap_WorldCoor_plate_dec_get, METH_VARARGS, (char *)"WorldCoor_plate_dec_get(self) -> double"}, { (char *)"WorldCoor_plate_scale_set", _wrap_WorldCoor_plate_scale_set, METH_VARARGS, (char *)"WorldCoor_plate_scale_set(self, plate_scale)"}, { (char *)"WorldCoor_plate_scale_get", _wrap_WorldCoor_plate_scale_get, METH_VARARGS, (char *)"WorldCoor_plate_scale_get(self) -> double"}, { (char *)"WorldCoor_x_pixel_offset_set", _wrap_WorldCoor_x_pixel_offset_set, METH_VARARGS, (char *)"WorldCoor_x_pixel_offset_set(self, x_pixel_offset)"}, { (char *)"WorldCoor_x_pixel_offset_get", _wrap_WorldCoor_x_pixel_offset_get, METH_VARARGS, (char *)"WorldCoor_x_pixel_offset_get(self) -> double"}, { (char *)"WorldCoor_y_pixel_offset_set", _wrap_WorldCoor_y_pixel_offset_set, METH_VARARGS, (char *)"WorldCoor_y_pixel_offset_set(self, y_pixel_offset)"}, { (char *)"WorldCoor_y_pixel_offset_get", _wrap_WorldCoor_y_pixel_offset_get, METH_VARARGS, (char *)"WorldCoor_y_pixel_offset_get(self) -> double"}, { (char *)"WorldCoor_x_pixel_size_set", _wrap_WorldCoor_x_pixel_size_set, METH_VARARGS, (char *)"WorldCoor_x_pixel_size_set(self, x_pixel_size)"}, { (char *)"WorldCoor_x_pixel_size_get", _wrap_WorldCoor_x_pixel_size_get, METH_VARARGS, (char *)"WorldCoor_x_pixel_size_get(self) -> double"}, { (char *)"WorldCoor_y_pixel_size_set", _wrap_WorldCoor_y_pixel_size_set, METH_VARARGS, (char *)"WorldCoor_y_pixel_size_set(self, y_pixel_size)"}, { (char *)"WorldCoor_y_pixel_size_get", _wrap_WorldCoor_y_pixel_size_get, METH_VARARGS, (char *)"WorldCoor_y_pixel_size_get(self) -> double"}, { (char *)"WorldCoor_ppo_coeff_set", _wrap_WorldCoor_ppo_coeff_set, METH_VARARGS, (char *)"WorldCoor_ppo_coeff_set(self, ppo_coeff)"}, { (char *)"WorldCoor_ppo_coeff_get", _wrap_WorldCoor_ppo_coeff_get, METH_VARARGS, (char *)"WorldCoor_ppo_coeff_get(self) -> double [6]"}, { (char *)"WorldCoor_x_coeff_set", _wrap_WorldCoor_x_coeff_set, METH_VARARGS, (char *)"WorldCoor_x_coeff_set(self, x_coeff)"}, { (char *)"WorldCoor_x_coeff_get", _wrap_WorldCoor_x_coeff_get, METH_VARARGS, (char *)"WorldCoor_x_coeff_get(self) -> double [20]"}, { (char *)"WorldCoor_y_coeff_set", _wrap_WorldCoor_y_coeff_set, METH_VARARGS, (char *)"WorldCoor_y_coeff_set(self, y_coeff)"}, { (char *)"WorldCoor_y_coeff_get", _wrap_WorldCoor_y_coeff_get, METH_VARARGS, (char *)"WorldCoor_y_coeff_get(self) -> double [20]"}, { (char *)"WorldCoor_xpix_set", _wrap_WorldCoor_xpix_set, METH_VARARGS, (char *)"WorldCoor_xpix_set(self, xpix)"}, { (char *)"WorldCoor_xpix_get", _wrap_WorldCoor_xpix_get, METH_VARARGS, (char *)"WorldCoor_xpix_get(self) -> double"}, { (char *)"WorldCoor_ypix_set", _wrap_WorldCoor_ypix_set, METH_VARARGS, (char *)"WorldCoor_ypix_set(self, ypix)"}, { (char *)"WorldCoor_ypix_get", _wrap_WorldCoor_ypix_get, METH_VARARGS, (char *)"WorldCoor_ypix_get(self) -> double"}, { (char *)"WorldCoor_zpix_set", _wrap_WorldCoor_zpix_set, METH_VARARGS, (char *)"WorldCoor_zpix_set(self, zpix)"}, { (char *)"WorldCoor_zpix_get", _wrap_WorldCoor_zpix_get, METH_VARARGS, (char *)"WorldCoor_zpix_get(self) -> double"}, { (char *)"WorldCoor_xpos_set", _wrap_WorldCoor_xpos_set, METH_VARARGS, (char *)"WorldCoor_xpos_set(self, xpos)"}, { (char *)"WorldCoor_xpos_get", _wrap_WorldCoor_xpos_get, METH_VARARGS, (char *)"WorldCoor_xpos_get(self) -> double"}, { (char *)"WorldCoor_ypos_set", _wrap_WorldCoor_ypos_set, METH_VARARGS, (char *)"WorldCoor_ypos_set(self, ypos)"}, { (char *)"WorldCoor_ypos_get", _wrap_WorldCoor_ypos_get, METH_VARARGS, (char *)"WorldCoor_ypos_get(self) -> double"}, { (char *)"WorldCoor_crpix_set", _wrap_WorldCoor_crpix_set, METH_VARARGS, (char *)"WorldCoor_crpix_set(self, crpix)"}, { (char *)"WorldCoor_crpix_get", _wrap_WorldCoor_crpix_get, METH_VARARGS, (char *)"WorldCoor_crpix_get(self) -> double [9]"}, { (char *)"WorldCoor_crval_set", _wrap_WorldCoor_crval_set, METH_VARARGS, (char *)"WorldCoor_crval_set(self, crval)"}, { (char *)"WorldCoor_crval_get", _wrap_WorldCoor_crval_get, METH_VARARGS, (char *)"WorldCoor_crval_get(self) -> double [9]"}, { (char *)"WorldCoor_cdelt_set", _wrap_WorldCoor_cdelt_set, METH_VARARGS, (char *)"WorldCoor_cdelt_set(self, cdelt)"}, { (char *)"WorldCoor_cdelt_get", _wrap_WorldCoor_cdelt_get, METH_VARARGS, (char *)"WorldCoor_cdelt_get(self) -> double [9]"}, { (char *)"WorldCoor_pc_set", _wrap_WorldCoor_pc_set, METH_VARARGS, (char *)"WorldCoor_pc_set(self, pc)"}, { (char *)"WorldCoor_pc_get", _wrap_WorldCoor_pc_get, METH_VARARGS, (char *)"WorldCoor_pc_get(self) -> double [81]"}, { (char *)"WorldCoor_projp_set", _wrap_WorldCoor_projp_set, METH_VARARGS, (char *)"WorldCoor_projp_set(self, projp)"}, { (char *)"WorldCoor_projp_get", _wrap_WorldCoor_projp_get, METH_VARARGS, (char *)"WorldCoor_projp_get(self) -> double [10]"}, { (char *)"WorldCoor_pvfail_set", _wrap_WorldCoor_pvfail_set, METH_VARARGS, (char *)"WorldCoor_pvfail_set(self, pvfail)"}, { (char *)"WorldCoor_pvfail_get", _wrap_WorldCoor_pvfail_get, METH_VARARGS, (char *)"WorldCoor_pvfail_get(self) -> int"}, { (char *)"WorldCoor_projppv_set", _wrap_WorldCoor_projppv_set, METH_VARARGS, (char *)"WorldCoor_projppv_set(self, projppv)"}, { (char *)"WorldCoor_projppv_get", _wrap_WorldCoor_projppv_get, METH_VARARGS, (char *)"WorldCoor_projppv_get(self) -> double [2*MAXPV]"}, { (char *)"WorldCoor_inv_x_set", _wrap_WorldCoor_inv_x_set, METH_VARARGS, (char *)"WorldCoor_inv_x_set(self, inv_x)"}, { (char *)"WorldCoor_inv_x_get", _wrap_WorldCoor_inv_x_get, METH_VARARGS, (char *)"WorldCoor_inv_x_get(self) -> struct poly *"}, { (char *)"WorldCoor_inv_y_set", _wrap_WorldCoor_inv_y_set, METH_VARARGS, (char *)"WorldCoor_inv_y_set(self, inv_y)"}, { (char *)"WorldCoor_inv_y_get", _wrap_WorldCoor_inv_y_get, METH_VARARGS, (char *)"WorldCoor_inv_y_get(self) -> struct poly *"}, { (char *)"WorldCoor_longpole_set", _wrap_WorldCoor_longpole_set, METH_VARARGS, (char *)"WorldCoor_longpole_set(self, longpole)"}, { (char *)"WorldCoor_longpole_get", _wrap_WorldCoor_longpole_get, METH_VARARGS, (char *)"WorldCoor_longpole_get(self) -> double"}, { (char *)"WorldCoor_latpole_set", _wrap_WorldCoor_latpole_set, METH_VARARGS, (char *)"WorldCoor_latpole_set(self, latpole)"}, { (char *)"WorldCoor_latpole_get", _wrap_WorldCoor_latpole_get, METH_VARARGS, (char *)"WorldCoor_latpole_get(self) -> double"}, { (char *)"WorldCoor_rodeg_set", _wrap_WorldCoor_rodeg_set, METH_VARARGS, (char *)"WorldCoor_rodeg_set(self, rodeg)"}, { (char *)"WorldCoor_rodeg_get", _wrap_WorldCoor_rodeg_get, METH_VARARGS, (char *)"WorldCoor_rodeg_get(self) -> double"}, { (char *)"WorldCoor_imrot_set", _wrap_WorldCoor_imrot_set, METH_VARARGS, (char *)"WorldCoor_imrot_set(self, imrot)"}, { (char *)"WorldCoor_imrot_get", _wrap_WorldCoor_imrot_get, METH_VARARGS, (char *)"WorldCoor_imrot_get(self) -> double"}, { (char *)"WorldCoor_pa_north_set", _wrap_WorldCoor_pa_north_set, METH_VARARGS, (char *)"WorldCoor_pa_north_set(self, pa_north)"}, { (char *)"WorldCoor_pa_north_get", _wrap_WorldCoor_pa_north_get, METH_VARARGS, (char *)"WorldCoor_pa_north_get(self) -> double"}, { (char *)"WorldCoor_pa_east_set", _wrap_WorldCoor_pa_east_set, METH_VARARGS, (char *)"WorldCoor_pa_east_set(self, pa_east)"}, { (char *)"WorldCoor_pa_east_get", _wrap_WorldCoor_pa_east_get, METH_VARARGS, (char *)"WorldCoor_pa_east_get(self) -> double"}, { (char *)"WorldCoor_radvel_set", _wrap_WorldCoor_radvel_set, METH_VARARGS, (char *)"WorldCoor_radvel_set(self, radvel)"}, { (char *)"WorldCoor_radvel_get", _wrap_WorldCoor_radvel_get, METH_VARARGS, (char *)"WorldCoor_radvel_get(self) -> double"}, { (char *)"WorldCoor_zvel_set", _wrap_WorldCoor_zvel_set, METH_VARARGS, (char *)"WorldCoor_zvel_set(self, zvel)"}, { (char *)"WorldCoor_zvel_get", _wrap_WorldCoor_zvel_get, METH_VARARGS, (char *)"WorldCoor_zvel_get(self) -> double"}, { (char *)"WorldCoor_zpzd_set", _wrap_WorldCoor_zpzd_set, METH_VARARGS, (char *)"WorldCoor_zpzd_set(self, zpzd)"}, { (char *)"WorldCoor_zpzd_get", _wrap_WorldCoor_zpzd_get, METH_VARARGS, (char *)"WorldCoor_zpzd_get(self) -> double"}, { (char *)"WorldCoor_zpr_set", _wrap_WorldCoor_zpr_set, METH_VARARGS, (char *)"WorldCoor_zpr_set(self, zpr)"}, { (char *)"WorldCoor_zpr_get", _wrap_WorldCoor_zpr_get, METH_VARARGS, (char *)"WorldCoor_zpr_get(self) -> double"}, { (char *)"WorldCoor_imflip_set", _wrap_WorldCoor_imflip_set, METH_VARARGS, (char *)"WorldCoor_imflip_set(self, imflip)"}, { (char *)"WorldCoor_imflip_get", _wrap_WorldCoor_imflip_get, METH_VARARGS, (char *)"WorldCoor_imflip_get(self) -> int"}, { (char *)"WorldCoor_prjcode_set", _wrap_WorldCoor_prjcode_set, METH_VARARGS, (char *)"WorldCoor_prjcode_set(self, prjcode)"}, { (char *)"WorldCoor_prjcode_get", _wrap_WorldCoor_prjcode_get, METH_VARARGS, (char *)"WorldCoor_prjcode_get(self) -> int"}, { (char *)"WorldCoor_latbase_set", _wrap_WorldCoor_latbase_set, METH_VARARGS, (char *)"WorldCoor_latbase_set(self, latbase)"}, { (char *)"WorldCoor_latbase_get", _wrap_WorldCoor_latbase_get, METH_VARARGS, (char *)"WorldCoor_latbase_get(self) -> int"}, { (char *)"WorldCoor_ncoeff1_set", _wrap_WorldCoor_ncoeff1_set, METH_VARARGS, (char *)"WorldCoor_ncoeff1_set(self, ncoeff1)"}, { (char *)"WorldCoor_ncoeff1_get", _wrap_WorldCoor_ncoeff1_get, METH_VARARGS, (char *)"WorldCoor_ncoeff1_get(self) -> int"}, { (char *)"WorldCoor_ncoeff2_set", _wrap_WorldCoor_ncoeff2_set, METH_VARARGS, (char *)"WorldCoor_ncoeff2_set(self, ncoeff2)"}, { (char *)"WorldCoor_ncoeff2_get", _wrap_WorldCoor_ncoeff2_get, METH_VARARGS, (char *)"WorldCoor_ncoeff2_get(self) -> int"}, { (char *)"WorldCoor_zpnp_set", _wrap_WorldCoor_zpnp_set, METH_VARARGS, (char *)"WorldCoor_zpnp_set(self, zpnp)"}, { (char *)"WorldCoor_zpnp_get", _wrap_WorldCoor_zpnp_get, METH_VARARGS, (char *)"WorldCoor_zpnp_get(self) -> int"}, { (char *)"WorldCoor_changesys_set", _wrap_WorldCoor_changesys_set, METH_VARARGS, (char *)"WorldCoor_changesys_set(self, changesys)"}, { (char *)"WorldCoor_changesys_get", _wrap_WorldCoor_changesys_get, METH_VARARGS, (char *)"WorldCoor_changesys_get(self) -> int"}, { (char *)"WorldCoor_printsys_set", _wrap_WorldCoor_printsys_set, METH_VARARGS, (char *)"WorldCoor_printsys_set(self, printsys)"}, { (char *)"WorldCoor_printsys_get", _wrap_WorldCoor_printsys_get, METH_VARARGS, (char *)"WorldCoor_printsys_get(self) -> int"}, { (char *)"WorldCoor_ndec_set", _wrap_WorldCoor_ndec_set, METH_VARARGS, (char *)"WorldCoor_ndec_set(self, ndec)"}, { (char *)"WorldCoor_ndec_get", _wrap_WorldCoor_ndec_get, METH_VARARGS, (char *)"WorldCoor_ndec_get(self) -> int"}, { (char *)"WorldCoor_degout_set", _wrap_WorldCoor_degout_set, METH_VARARGS, (char *)"WorldCoor_degout_set(self, degout)"}, { (char *)"WorldCoor_degout_get", _wrap_WorldCoor_degout_get, METH_VARARGS, (char *)"WorldCoor_degout_get(self) -> int"}, { (char *)"WorldCoor_tabsys_set", _wrap_WorldCoor_tabsys_set, METH_VARARGS, (char *)"WorldCoor_tabsys_set(self, tabsys)"}, { (char *)"WorldCoor_tabsys_get", _wrap_WorldCoor_tabsys_get, METH_VARARGS, (char *)"WorldCoor_tabsys_get(self) -> int"}, { (char *)"WorldCoor_rotmat_set", _wrap_WorldCoor_rotmat_set, METH_VARARGS, (char *)"WorldCoor_rotmat_set(self, rotmat)"}, { (char *)"WorldCoor_rotmat_get", _wrap_WorldCoor_rotmat_get, METH_VARARGS, (char *)"WorldCoor_rotmat_get(self) -> int"}, { (char *)"WorldCoor_coorflip_set", _wrap_WorldCoor_coorflip_set, METH_VARARGS, (char *)"WorldCoor_coorflip_set(self, coorflip)"}, { (char *)"WorldCoor_coorflip_get", _wrap_WorldCoor_coorflip_get, METH_VARARGS, (char *)"WorldCoor_coorflip_get(self) -> int"}, { (char *)"WorldCoor_offscl_set", _wrap_WorldCoor_offscl_set, METH_VARARGS, (char *)"WorldCoor_offscl_set(self, offscl)"}, { (char *)"WorldCoor_offscl_get", _wrap_WorldCoor_offscl_get, METH_VARARGS, (char *)"WorldCoor_offscl_get(self) -> int"}, { (char *)"WorldCoor_wcson_set", _wrap_WorldCoor_wcson_set, METH_VARARGS, (char *)"WorldCoor_wcson_set(self, wcson)"}, { (char *)"WorldCoor_wcson_get", _wrap_WorldCoor_wcson_get, METH_VARARGS, (char *)"WorldCoor_wcson_get(self) -> int"}, { (char *)"WorldCoor_naxis_set", _wrap_WorldCoor_naxis_set, METH_VARARGS, (char *)"WorldCoor_naxis_set(self, naxis)"}, { (char *)"WorldCoor_naxis_get", _wrap_WorldCoor_naxis_get, METH_VARARGS, (char *)"WorldCoor_naxis_get(self) -> int"}, { (char *)"WorldCoor_naxes_set", _wrap_WorldCoor_naxes_set, METH_VARARGS, (char *)"WorldCoor_naxes_set(self, naxes)"}, { (char *)"WorldCoor_naxes_get", _wrap_WorldCoor_naxes_get, METH_VARARGS, (char *)"WorldCoor_naxes_get(self) -> int"}, { (char *)"WorldCoor_wcsproj_set", _wrap_WorldCoor_wcsproj_set, METH_VARARGS, (char *)"WorldCoor_wcsproj_set(self, wcsproj)"}, { (char *)"WorldCoor_wcsproj_get", _wrap_WorldCoor_wcsproj_get, METH_VARARGS, (char *)"WorldCoor_wcsproj_get(self) -> int"}, { (char *)"WorldCoor_linmode_set", _wrap_WorldCoor_linmode_set, METH_VARARGS, (char *)"WorldCoor_linmode_set(self, linmode)"}, { (char *)"WorldCoor_linmode_get", _wrap_WorldCoor_linmode_get, METH_VARARGS, (char *)"WorldCoor_linmode_get(self) -> int"}, { (char *)"WorldCoor_detector_set", _wrap_WorldCoor_detector_set, METH_VARARGS, (char *)"WorldCoor_detector_set(self, detector)"}, { (char *)"WorldCoor_detector_get", _wrap_WorldCoor_detector_get, METH_VARARGS, (char *)"WorldCoor_detector_get(self) -> int"}, { (char *)"WorldCoor_instrument_set", _wrap_WorldCoor_instrument_set, METH_VARARGS, (char *)"WorldCoor_instrument_set(self, instrument)"}, { (char *)"WorldCoor_instrument_get", _wrap_WorldCoor_instrument_get, METH_VARARGS, (char *)"WorldCoor_instrument_get(self) -> char [32]"}, { (char *)"WorldCoor_ctype_set", _wrap_WorldCoor_ctype_set, METH_VARARGS, (char *)"WorldCoor_ctype_set(self, ctype)"}, { (char *)"WorldCoor_ctype_get", _wrap_WorldCoor_ctype_get, METH_VARARGS, (char *)"WorldCoor_ctype_get(self) -> char [9][9]"}, { (char *)"WorldCoor_c1type_set", _wrap_WorldCoor_c1type_set, METH_VARARGS, (char *)"WorldCoor_c1type_set(self, c1type)"}, { (char *)"WorldCoor_c1type_get", _wrap_WorldCoor_c1type_get, METH_VARARGS, (char *)"WorldCoor_c1type_get(self) -> char [9]"}, { (char *)"WorldCoor_c2type_set", _wrap_WorldCoor_c2type_set, METH_VARARGS, (char *)"WorldCoor_c2type_set(self, c2type)"}, { (char *)"WorldCoor_c2type_get", _wrap_WorldCoor_c2type_get, METH_VARARGS, (char *)"WorldCoor_c2type_get(self) -> char [9]"}, { (char *)"WorldCoor_ptype_set", _wrap_WorldCoor_ptype_set, METH_VARARGS, (char *)"WorldCoor_ptype_set(self, ptype)"}, { (char *)"WorldCoor_ptype_get", _wrap_WorldCoor_ptype_get, METH_VARARGS, (char *)"WorldCoor_ptype_get(self) -> char [9]"}, { (char *)"WorldCoor_units_set", _wrap_WorldCoor_units_set, METH_VARARGS, (char *)"WorldCoor_units_set(self, units)"}, { (char *)"WorldCoor_units_get", _wrap_WorldCoor_units_get, METH_VARARGS, (char *)"WorldCoor_units_get(self) -> char [9][32]"}, { (char *)"WorldCoor_radecsys_set", _wrap_WorldCoor_radecsys_set, METH_VARARGS, (char *)"WorldCoor_radecsys_set(self, radecsys)"}, { (char *)"WorldCoor_radecsys_get", _wrap_WorldCoor_radecsys_get, METH_VARARGS, (char *)"WorldCoor_radecsys_get(self) -> char [32]"}, { (char *)"WorldCoor_radecout_set", _wrap_WorldCoor_radecout_set, METH_VARARGS, (char *)"WorldCoor_radecout_set(self, radecout)"}, { (char *)"WorldCoor_radecout_get", _wrap_WorldCoor_radecout_get, METH_VARARGS, (char *)"WorldCoor_radecout_get(self) -> char [32]"}, { (char *)"WorldCoor_radecin_set", _wrap_WorldCoor_radecin_set, METH_VARARGS, (char *)"WorldCoor_radecin_set(self, radecin)"}, { (char *)"WorldCoor_radecin_get", _wrap_WorldCoor_radecin_get, METH_VARARGS, (char *)"WorldCoor_radecin_get(self) -> char [32]"}, { (char *)"WorldCoor_eqin_set", _wrap_WorldCoor_eqin_set, METH_VARARGS, (char *)"WorldCoor_eqin_set(self, eqin)"}, { (char *)"WorldCoor_eqin_get", _wrap_WorldCoor_eqin_get, METH_VARARGS, (char *)"WorldCoor_eqin_get(self) -> double"}, { (char *)"WorldCoor_eqout_set", _wrap_WorldCoor_eqout_set, METH_VARARGS, (char *)"WorldCoor_eqout_set(self, eqout)"}, { (char *)"WorldCoor_eqout_get", _wrap_WorldCoor_eqout_get, METH_VARARGS, (char *)"WorldCoor_eqout_get(self) -> double"}, { (char *)"WorldCoor_sysin_set", _wrap_WorldCoor_sysin_set, METH_VARARGS, (char *)"WorldCoor_sysin_set(self, sysin)"}, { (char *)"WorldCoor_sysin_get", _wrap_WorldCoor_sysin_get, METH_VARARGS, (char *)"WorldCoor_sysin_get(self) -> int"}, { (char *)"WorldCoor_syswcs_set", _wrap_WorldCoor_syswcs_set, METH_VARARGS, (char *)"WorldCoor_syswcs_set(self, syswcs)"}, { (char *)"WorldCoor_syswcs_get", _wrap_WorldCoor_syswcs_get, METH_VARARGS, (char *)"WorldCoor_syswcs_get(self) -> int"}, { (char *)"WorldCoor_sysout_set", _wrap_WorldCoor_sysout_set, METH_VARARGS, (char *)"WorldCoor_sysout_set(self, sysout)"}, { (char *)"WorldCoor_sysout_get", _wrap_WorldCoor_sysout_get, METH_VARARGS, (char *)"WorldCoor_sysout_get(self) -> int"}, { (char *)"WorldCoor_center_set", _wrap_WorldCoor_center_set, METH_VARARGS, (char *)"WorldCoor_center_set(self, center)"}, { (char *)"WorldCoor_center_get", _wrap_WorldCoor_center_get, METH_VARARGS, (char *)"WorldCoor_center_get(self) -> char [32]"}, { (char *)"WorldCoor_wcsl_set", _wrap_WorldCoor_wcsl_set, METH_VARARGS, (char *)"WorldCoor_wcsl_set(self, wcsl)"}, { (char *)"WorldCoor_wcsl_get", _wrap_WorldCoor_wcsl_get, METH_VARARGS, (char *)"WorldCoor_wcsl_get(self) -> struct wcsprm"}, { (char *)"WorldCoor_lin_set", _wrap_WorldCoor_lin_set, METH_VARARGS, (char *)"WorldCoor_lin_set(self, lin)"}, { (char *)"WorldCoor_lin_get", _wrap_WorldCoor_lin_get, METH_VARARGS, (char *)"WorldCoor_lin_get(self) -> struct linprm"}, { (char *)"WorldCoor_cel_set", _wrap_WorldCoor_cel_set, METH_VARARGS, (char *)"WorldCoor_cel_set(self, cel)"}, { (char *)"WorldCoor_cel_get", _wrap_WorldCoor_cel_get, METH_VARARGS, (char *)"WorldCoor_cel_get(self) -> struct celprm"}, { (char *)"WorldCoor_prj_set", _wrap_WorldCoor_prj_set, METH_VARARGS, (char *)"WorldCoor_prj_set(self, prj)"}, { (char *)"WorldCoor_prj_get", _wrap_WorldCoor_prj_get, METH_VARARGS, (char *)"WorldCoor_prj_get(self) -> struct prjprm"}, { (char *)"WorldCoor_lngcor_set", _wrap_WorldCoor_lngcor_set, METH_VARARGS, (char *)"WorldCoor_lngcor_set(self, lngcor)"}, { (char *)"WorldCoor_lngcor_get", _wrap_WorldCoor_lngcor_get, METH_VARARGS, (char *)"WorldCoor_lngcor_get(self) -> struct IRAFsurface *"}, { (char *)"WorldCoor_latcor_set", _wrap_WorldCoor_latcor_set, METH_VARARGS, (char *)"WorldCoor_latcor_set(self, latcor)"}, { (char *)"WorldCoor_latcor_get", _wrap_WorldCoor_latcor_get, METH_VARARGS, (char *)"WorldCoor_latcor_get(self) -> struct IRAFsurface *"}, { (char *)"WorldCoor_distcode_set", _wrap_WorldCoor_distcode_set, METH_VARARGS, (char *)"WorldCoor_distcode_set(self, distcode)"}, { (char *)"WorldCoor_distcode_get", _wrap_WorldCoor_distcode_get, METH_VARARGS, (char *)"WorldCoor_distcode_get(self) -> int"}, { (char *)"WorldCoor_distort_set", _wrap_WorldCoor_distort_set, METH_VARARGS, (char *)"WorldCoor_distort_set(self, distort)"}, { (char *)"WorldCoor_distort_get", _wrap_WorldCoor_distort_get, METH_VARARGS, (char *)"WorldCoor_distort_get(self) -> struct Distort"}, { (char *)"WorldCoor_command_format_set", _wrap_WorldCoor_command_format_set, METH_VARARGS, (char *)"WorldCoor_command_format_set(self, command_format)"}, { (char *)"WorldCoor_command_format_get", _wrap_WorldCoor_command_format_get, METH_VARARGS, (char *)"WorldCoor_command_format_get(self) -> char *[10]"}, { (char *)"WorldCoor_ltm_set", _wrap_WorldCoor_ltm_set, METH_VARARGS, (char *)"WorldCoor_ltm_set(self, ltm)"}, { (char *)"WorldCoor_ltm_get", _wrap_WorldCoor_ltm_get, METH_VARARGS, (char *)"WorldCoor_ltm_get(self) -> double [4]"}, { (char *)"WorldCoor_ltv_set", _wrap_WorldCoor_ltv_set, METH_VARARGS, (char *)"WorldCoor_ltv_set(self, ltv)"}, { (char *)"WorldCoor_ltv_get", _wrap_WorldCoor_ltv_get, METH_VARARGS, (char *)"WorldCoor_ltv_get(self) -> double [2]"}, { (char *)"WorldCoor_idpix_set", _wrap_WorldCoor_idpix_set, METH_VARARGS, (char *)"WorldCoor_idpix_set(self, idpix)"}, { (char *)"WorldCoor_idpix_get", _wrap_WorldCoor_idpix_get, METH_VARARGS, (char *)"WorldCoor_idpix_get(self) -> int [2]"}, { (char *)"WorldCoor_ndpix_set", _wrap_WorldCoor_ndpix_set, METH_VARARGS, (char *)"WorldCoor_ndpix_set(self, ndpix)"}, { (char *)"WorldCoor_ndpix_get", _wrap_WorldCoor_ndpix_get, METH_VARARGS, (char *)"WorldCoor_ndpix_get(self) -> int [2]"}, { (char *)"WorldCoor_wcs_set", _wrap_WorldCoor_wcs_set, METH_VARARGS, (char *)"WorldCoor_wcs_set(self, wcs)"}, { (char *)"WorldCoor_wcs_get", _wrap_WorldCoor_wcs_get, METH_VARARGS, (char *)"WorldCoor_wcs_get(self) -> WorldCoor"}, { (char *)"WorldCoor_wcsdep_set", _wrap_WorldCoor_wcsdep_set, METH_VARARGS, (char *)"WorldCoor_wcsdep_set(self, wcsdep)"}, { (char *)"WorldCoor_wcsdep_get", _wrap_WorldCoor_wcsdep_get, METH_VARARGS, (char *)"WorldCoor_wcsdep_get(self) -> WorldCoor"}, { (char *)"WorldCoor_wcsname_set", _wrap_WorldCoor_wcsname_set, METH_VARARGS, (char *)"WorldCoor_wcsname_set(self, wcsname)"}, { (char *)"WorldCoor_wcsname_get", _wrap_WorldCoor_wcsname_get, METH_VARARGS, (char *)"WorldCoor_wcsname_get(self) -> char *"}, { (char *)"WorldCoor_wcschar_set", _wrap_WorldCoor_wcschar_set, METH_VARARGS, (char *)"WorldCoor_wcschar_set(self, wcschar)"}, { (char *)"WorldCoor_wcschar_get", _wrap_WorldCoor_wcschar_get, METH_VARARGS, (char *)"WorldCoor_wcschar_get(self) -> char"}, { (char *)"WorldCoor_logwcs_set", _wrap_WorldCoor_logwcs_set, METH_VARARGS, (char *)"WorldCoor_logwcs_set(self, logwcs)"}, { (char *)"WorldCoor_logwcs_get", _wrap_WorldCoor_logwcs_get, METH_VARARGS, (char *)"WorldCoor_logwcs_get(self) -> int"}, { (char *)"new_WorldCoor", _wrap_new_WorldCoor, METH_VARARGS, (char *)"new_WorldCoor() -> WorldCoor"}, { (char *)"delete_WorldCoor", _wrap_delete_WorldCoor, METH_VARARGS, (char *)"delete_WorldCoor(self)"}, { (char *)"WorldCoor_swigregister", WorldCoor_swigregister, METH_VARARGS, NULL}, { NULL, NULL, 0, NULL } }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ static swig_type_info _swigt__p_Distort = {"_p_Distort", "struct Distort *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_IRAFsurface = {"_p_IRAFsurface", "struct IRAFsurface *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_WorldCoor = {"_p_WorldCoor", "struct WorldCoor *|WorldCoor *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_a_32__char = {"_p_a_32__char", "char (*)[32]", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_a_9__char = {"_p_a_9__char", "char (*)[9]", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_celprm = {"_p_celprm", "struct celprm *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_double = {"_p_double", "double *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_int = {"_p_int", "int *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_linprm = {"_p_linprm", "struct linprm *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_p_char = {"_p_p_char", "char **", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_poly = {"_p_poly", "struct poly *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_prjprm = {"_p_prjprm", "struct prjprm *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_wcsprm = {"_p_wcsprm", "struct wcsprm *", 0, 0, (void*)0, 0}; static swig_type_info *swig_type_initial[] = { &_swigt__p_Distort, &_swigt__p_IRAFsurface, &_swigt__p_WorldCoor, &_swigt__p_a_32__char, &_swigt__p_a_9__char, &_swigt__p_celprm, &_swigt__p_char, &_swigt__p_double, &_swigt__p_int, &_swigt__p_linprm, &_swigt__p_p_char, &_swigt__p_poly, &_swigt__p_prjprm, &_swigt__p_wcsprm, }; static swig_cast_info _swigc__p_Distort[] = { {&_swigt__p_Distort, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_IRAFsurface[] = { {&_swigt__p_IRAFsurface, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_WorldCoor[] = { {&_swigt__p_WorldCoor, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_a_32__char[] = { {&_swigt__p_a_32__char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_a_9__char[] = { {&_swigt__p_a_9__char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_celprm[] = { {&_swigt__p_celprm, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_double[] = { {&_swigt__p_double, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_int[] = { {&_swigt__p_int, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_linprm[] = { {&_swigt__p_linprm, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_p_char[] = { {&_swigt__p_p_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_poly[] = { {&_swigt__p_poly, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_prjprm[] = { {&_swigt__p_prjprm, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_wcsprm[] = { {&_swigt__p_wcsprm, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { _swigc__p_Distort, _swigc__p_IRAFsurface, _swigc__p_WorldCoor, _swigc__p_a_32__char, _swigc__p_a_9__char, _swigc__p_celprm, _swigc__p_char, _swigc__p_double, _swigc__p_int, _swigc__p_linprm, _swigc__p_p_char, _swigc__p_poly, _swigc__p_prjprm, _swigc__p_wcsprm, }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ static swig_const_info swig_const_table[] = { {0, 0, 0, 0.0, 0, 0}}; #ifdef __cplusplus } #endif /* ----------------------------------------------------------------------------- * Type initialization: * This problem is tough by the requirement that no dynamic * memory is used. Also, since swig_type_info structures store pointers to * swig_cast_info structures and swig_cast_info structures store pointers back * to swig_type_info structures, we need some lookup code at initialization. * The idea is that swig generates all the structures that are needed. * The runtime then collects these partially filled structures. * The SWIG_InitializeModule function takes these initial arrays out of * swig_module, and does all the lookup, filling in the swig_module.types * array with the correct data and linking the correct swig_cast_info * structures together. * * The generated swig_type_info structures are assigned staticly to an initial * array. We just loop through that array, and handle each type individually. * First we lookup if this type has been already loaded, and if so, use the * loaded structure instead of the generated one. Then we have to fill in the * cast linked list. The cast data is initially stored in something like a * two-dimensional array. Each row corresponds to a type (there are the same * number of rows as there are in the swig_type_initial array). Each entry in * a column is one of the swig_cast_info structures for that type. * The cast_initial array is actually an array of arrays, because each row has * a variable number of columns. So to actually build the cast linked list, * we find the array of casts associated with the type, and loop through it * adding the casts to the list. The one last trick we need to do is making * sure the type pointer in the swig_cast_info struct is correct. * * First off, we lookup the cast->type name to see if it is already loaded. * There are three cases to handle: * 1) If the cast->type has already been loaded AND the type we are adding * casting info to has not been loaded (it is in this module), THEN we * replace the cast->type pointer with the type pointer that has already * been loaded. * 2) If BOTH types (the one we are adding casting info to, and the * cast->type) are loaded, THEN the cast info has already been loaded by * the previous module so we just ignore it. * 3) Finally, if cast->type has not already been loaded, then we add that * swig_cast_info to the linked list (because the cast->type) pointer will * be correct. * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #if 0 } /* c-mode */ #endif #endif #if 0 #define SWIGRUNTIME_DEBUG #endif SWIGRUNTIME void SWIG_InitializeModule(void *clientdata) { size_t i; swig_module_info *module_head, *iter; int found, init; /* check to see if the circular list has been setup, if not, set it up */ if (swig_module.next==0) { /* Initialize the swig_module */ swig_module.type_initial = swig_type_initial; swig_module.cast_initial = swig_cast_initial; swig_module.next = &swig_module; init = 1; } else { init = 0; } /* Try and load any already created modules */ module_head = SWIG_GetModule(clientdata); if (!module_head) { /* This is the first module loaded for this interpreter */ /* so set the swig module into the interpreter */ SWIG_SetModule(clientdata, &swig_module); module_head = &swig_module; } else { /* the interpreter has loaded a SWIG module, but has it loaded this one? */ found=0; iter=module_head; do { if (iter==&swig_module) { found=1; break; } iter=iter->next; } while (iter!= module_head); /* if the is found in the list, then all is done and we may leave */ if (found) return; /* otherwise we must add out module into the list */ swig_module.next = module_head->next; module_head->next = &swig_module; } /* When multiple interpreters are used, a module could have already been initialized in a different interpreter, but not yet have a pointer in this interpreter. In this case, we do not want to continue adding types... everything should be set up already */ if (init == 0) return; /* Now work on filling in swig_module.types */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: size %d\n", swig_module.size); #endif for (i = 0; i < swig_module.size; ++i) { swig_type_info *type = 0; swig_type_info *ret; swig_cast_info *cast; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); #endif /* if there is another module already loaded */ if (swig_module.next != &swig_module) { type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); } if (type) { /* Overwrite clientdata field */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found type %s\n", type->name); #endif if (swig_module.type_initial[i]->clientdata) { type->clientdata = swig_module.type_initial[i]->clientdata; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); #endif } } else { type = swig_module.type_initial[i]; } /* Insert casting types */ cast = swig_module.cast_initial[i]; while (cast->type) { /* Don't need to add information already in the list */ ret = 0; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); #endif if (swig_module.next != &swig_module) { ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); #ifdef SWIGRUNTIME_DEBUG if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); #endif } if (ret) { if (type == swig_module.type_initial[i]) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: skip old type %s\n", ret->name); #endif cast->type = ret; ret = 0; } else { /* Check for casting already in the list */ swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); #ifdef SWIGRUNTIME_DEBUG if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); #endif if (!ocast) ret = 0; } } if (!ret) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); #endif if (type->cast) { type->cast->prev = cast; cast->next = type->cast; } type->cast = cast; } cast++; } /* Set entry in modules->types array equal to the type */ swig_module.types[i] = type; } swig_module.types[i] = 0; #ifdef SWIGRUNTIME_DEBUG printf("**** SWIG_InitializeModule: Cast List ******\n"); for (i = 0; i < swig_module.size; ++i) { int j = 0; swig_cast_info *cast = swig_module.cast_initial[i]; printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); while (cast->type) { printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); cast++; ++j; } printf("---- Total casts: %d\n",j); } printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif } /* This function will propagate the clientdata field of type to * any new swig_type_info structures that have been added into the list * of equivalent types. It is like calling * SWIG_TypeClientData(type, clientdata) a second time. */ SWIGRUNTIME void SWIG_PropagateClientData(void) { size_t i; swig_cast_info *equiv; static int init_run = 0; if (init_run) return; init_run = 1; for (i = 0; i < swig_module.size; i++) { if (swig_module.types[i]->clientdata) { equiv = swig_module.types[i]->cast; while (equiv) { if (!equiv->converter) { if (equiv->type && !equiv->type->clientdata) SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); } equiv = equiv->next; } } } } #ifdef __cplusplus #if 0 { /* c-mode */ #endif } #endif #ifdef __cplusplus extern "C" { #endif /* Python-specific SWIG API */ #define SWIG_newvarlink() SWIG_Python_newvarlink() #define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr) #define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants) /* ----------------------------------------------------------------------------- * global variable support code. * ----------------------------------------------------------------------------- */ typedef struct swig_globalvar { char *name; /* Name of global variable */ PyObject *(*get_attr)(void); /* Return the current value */ int (*set_attr)(PyObject *); /* Set the value */ struct swig_globalvar *next; } swig_globalvar; typedef struct swig_varlinkobject { PyObject_HEAD swig_globalvar *vars; } swig_varlinkobject; SWIGINTERN PyObject * swig_varlink_repr(swig_varlinkobject *SWIGUNUSEDPARM(v)) { #if PY_VERSION_HEX >= 0x03000000 return PyUnicode_InternFromString(""); #else return PyString_FromString(""); #endif } SWIGINTERN PyObject * swig_varlink_str(swig_varlinkobject *v) { #if PY_VERSION_HEX >= 0x03000000 PyObject *str = PyUnicode_InternFromString("("); PyObject *tail; PyObject *joined; swig_globalvar *var; for (var = v->vars; var; var=var->next) { tail = PyUnicode_FromString(var->name); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; if (var->next) { tail = PyUnicode_InternFromString(", "); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; } } tail = PyUnicode_InternFromString(")"); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; #else PyObject *str = PyString_FromString("("); swig_globalvar *var; for (var = v->vars; var; var=var->next) { PyString_ConcatAndDel(&str,PyString_FromString(var->name)); if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", ")); } PyString_ConcatAndDel(&str,PyString_FromString(")")); #endif return str; } SWIGINTERN int swig_varlink_print(swig_varlinkobject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { char *tmp; PyObject *str = swig_varlink_str(v); fprintf(fp,"Swig global variables "); fprintf(fp,"%s\n", tmp = SWIG_Python_str_AsChar(str)); SWIG_Python_str_DelForPy3(tmp); Py_DECREF(str); return 0; } SWIGINTERN void swig_varlink_dealloc(swig_varlinkobject *v) { swig_globalvar *var = v->vars; while (var) { swig_globalvar *n = var->next; free(var->name); free(var); var = n; } } SWIGINTERN PyObject * swig_varlink_getattr(swig_varlinkobject *v, char *n) { PyObject *res = NULL; swig_globalvar *var = v->vars; while (var) { if (strcmp(var->name,n) == 0) { res = (*var->get_attr)(); break; } var = var->next; } if (res == NULL && !PyErr_Occurred()) { PyErr_SetString(PyExc_NameError,"Unknown C global variable"); } return res; } SWIGINTERN int swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) { int res = 1; swig_globalvar *var = v->vars; while (var) { if (strcmp(var->name,n) == 0) { res = (*var->set_attr)(p); break; } var = var->next; } if (res == 1 && !PyErr_Occurred()) { PyErr_SetString(PyExc_NameError,"Unknown C global variable"); } return res; } SWIGINTERN PyTypeObject* swig_varlink_type(void) { static char varlink__doc__[] = "Swig var link object"; static PyTypeObject varlink_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { /* PyObject header changed in Python 3 */ #if PY_VERSION_HEX >= 0x03000000 PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif (char *)"swigvarlink", /* tp_name */ sizeof(swig_varlinkobject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor) swig_varlink_dealloc, /* tp_dealloc */ (printfunc) swig_varlink_print, /* tp_print */ (getattrfunc) swig_varlink_getattr, /* tp_getattr */ (setattrfunc) swig_varlink_setattr, /* tp_setattr */ 0, /* tp_compare */ (reprfunc) swig_varlink_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc) swig_varlink_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ varlink__doc__, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #if PY_VERSION_HEX >= 0x02060000 0, /* tp_version */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; varlink_type = tmp; type_init = 1; #if PY_VERSION_HEX < 0x02020000 varlink_type.ob_type = &PyType_Type; #else if (PyType_Ready(&varlink_type) < 0) return NULL; #endif } return &varlink_type; } /* Create a variable linking object for use later */ SWIGINTERN PyObject * SWIG_Python_newvarlink(void) { swig_varlinkobject *result = PyObject_NEW(swig_varlinkobject, swig_varlink_type()); if (result) { result->vars = 0; } return ((PyObject*) result); } SWIGINTERN void SWIG_Python_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) { swig_varlinkobject *v = (swig_varlinkobject *) p; swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); if (gv) { size_t size = strlen(name)+1; gv->name = (char *)malloc(size); if (gv->name) { strncpy(gv->name,name,size); gv->get_attr = get_attr; gv->set_attr = set_attr; gv->next = v->vars; } } v->vars = gv; } SWIGINTERN PyObject * SWIG_globals(void) { static PyObject *_SWIG_globals = 0; if (!_SWIG_globals) _SWIG_globals = SWIG_newvarlink(); return _SWIG_globals; } /* ----------------------------------------------------------------------------- * constants/methods manipulation * ----------------------------------------------------------------------------- */ /* Install Constants */ SWIGINTERN void SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { PyObject *obj = 0; size_t i; for (i = 0; constants[i].type; ++i) { switch(constants[i].type) { case SWIG_PY_POINTER: obj = SWIG_InternalNewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0); break; case SWIG_PY_BINARY: obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); break; default: obj = 0; break; } if (obj) { PyDict_SetItemString(d, constants[i].name, obj); Py_DECREF(obj); } } } /* -----------------------------------------------------------------------------*/ /* Fix SwigMethods to carry the callback ptrs when needed */ /* -----------------------------------------------------------------------------*/ SWIGINTERN void SWIG_Python_FixMethods(PyMethodDef *methods, swig_const_info *const_table, swig_type_info **types, swig_type_info **types_initial) { size_t i; for (i = 0; methods[i].ml_name; ++i) { const char *c = methods[i].ml_doc; if (c && (c = strstr(c, "swig_ptr: "))) { int j; swig_const_info *ci = 0; const char *name = c + 10; for (j = 0; const_table[j].type; ++j) { if (strncmp(const_table[j].name, name, strlen(const_table[j].name)) == 0) { ci = &(const_table[j]); break; } } if (ci) { void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; if (ptr) { size_t shift = (ci->ptype) - types; swig_type_info *ty = types_initial[shift]; size_t ldoc = (c - methods[i].ml_doc); size_t lptr = strlen(ty->name)+2*sizeof(void*)+2; char *ndoc = (char*)malloc(ldoc + lptr + 10); if (ndoc) { char *buff = ndoc; strncpy(buff, methods[i].ml_doc, ldoc); buff += ldoc; strncpy(buff, "swig_ptr: ", 10); buff += 10; SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); methods[i].ml_doc = ndoc; } } } } } } #ifdef __cplusplus } #endif /* -----------------------------------------------------------------------------* * Partial Init method * -----------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" #endif SWIGEXPORT #if PY_VERSION_HEX >= 0x03000000 PyObject* #else void #endif SWIG_init(void) { PyObject *m, *d, *md; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef SWIG_module = { # if PY_VERSION_HEX >= 0x03020000 PyModuleDef_HEAD_INIT, # else { PyObject_HEAD_INIT(NULL) NULL, /* m_init */ 0, /* m_index */ NULL, /* m_copy */ }, # endif (char *) SWIG_name, NULL, -1, SwigMethods, NULL, NULL, NULL, NULL }; #endif #if defined(SWIGPYTHON_BUILTIN) static SwigPyClientData SwigPyObject_clientdata = { 0, 0, 0, 0, 0, 0, 0 }; static PyGetSetDef this_getset_def = { (char *)"this", &SwigPyBuiltin_ThisClosure, NULL, NULL, NULL }; static SwigPyGetSet thisown_getset_closure = { (PyCFunction) SwigPyObject_own, (PyCFunction) SwigPyObject_own }; static PyGetSetDef thisown_getset_def = { (char *)"thisown", SwigPyBuiltin_GetterClosure, SwigPyBuiltin_SetterClosure, NULL, &thisown_getset_closure }; PyObject *metatype_args; PyTypeObject *builtin_pytype; int builtin_base_count; swig_type_info *builtin_basetype; PyObject *tuple; PyGetSetDescrObject *static_getset; PyTypeObject *metatype; SwigPyClientData *cd; PyObject *public_interface, *public_symbol; PyObject *this_descr; PyObject *thisown_descr; int i; (void)builtin_pytype; (void)builtin_base_count; (void)builtin_basetype; (void)tuple; (void)static_getset; /* metatype is used to implement static member variables. */ metatype_args = Py_BuildValue("(s(O){})", "SwigPyObjectType", &PyType_Type); assert(metatype_args); metatype = (PyTypeObject *) PyType_Type.tp_call((PyObject *) &PyType_Type, metatype_args, NULL); assert(metatype); Py_DECREF(metatype_args); metatype->tp_setattro = (setattrofunc) &SwigPyObjectType_setattro; assert(PyType_Ready(metatype) >= 0); #endif /* Fix SwigMethods to carry the callback ptrs when needed */ SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); #if PY_VERSION_HEX >= 0x03000000 m = PyModule_Create(&SWIG_module); #else m = Py_InitModule((char *) SWIG_name, SwigMethods); #endif md = d = PyModule_GetDict(m); (void)md; SWIG_InitializeModule(0); #ifdef SWIGPYTHON_BUILTIN SwigPyObject_stype = SWIG_MangledTypeQuery("_p_SwigPyObject"); assert(SwigPyObject_stype); cd = (SwigPyClientData*) SwigPyObject_stype->clientdata; if (!cd) { SwigPyObject_stype->clientdata = &SwigPyObject_clientdata; SwigPyObject_clientdata.pytype = SwigPyObject_TypeOnce(); } else if (SwigPyObject_TypeOnce()->tp_basicsize != cd->pytype->tp_basicsize) { PyErr_SetString(PyExc_RuntimeError, "Import error: attempted to load two incompatible swig-generated modules."); # if PY_VERSION_HEX >= 0x03000000 return NULL; # else return; # endif } /* All objects have a 'this' attribute */ this_descr = PyDescr_NewGetSet(SwigPyObject_type(), &this_getset_def); (void)this_descr; /* All objects have a 'thisown' attribute */ thisown_descr = PyDescr_NewGetSet(SwigPyObject_type(), &thisown_getset_def); (void)thisown_descr; public_interface = PyList_New(0); public_symbol = 0; (void)public_symbol; PyDict_SetItemString(md, "__all__", public_interface); Py_DECREF(public_interface); for (i = 0; SwigMethods[i].ml_name != NULL; ++i) SwigPyBuiltin_AddPublicSymbol(public_interface, SwigMethods[i].ml_name); for (i = 0; swig_const_table[i].name != 0; ++i) SwigPyBuiltin_AddPublicSymbol(public_interface, swig_const_table[i].name); #endif SWIG_InstallConstants(d,swig_const_table); #if PY_VERSION_HEX >= 0x03000000 return m; #else return; #endif } astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/sph.c0000664000175000017500000001643113047255533020424 0ustar mattymatty00000000000000/*============================================================================ * * WCSLIB - an implementation of the FITS WCS proposal. * Copyright (C) 1995-2002, Mark Calabretta * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Correspondence concerning WCSLIB may be directed to: * Internet email: mcalabre@atnf.csiro.au * Postal address: Dr. Mark Calabretta, * Australia Telescope National Facility, * P.O. Box 76, * Epping, NSW, 2121, * AUSTRALIA * *============================================================================= * * C routines for the spherical coordinate transformations used by the FITS * "World Coordinate System" (WCS) convention. * * Summary of routines * ------------------- * The spherical coordinate transformations are implemented via separate * functions for the transformation in each direction. * * Forward transformation; sphfwd() * -------------------------------- * Transform celestial coordinates to the native coordinates of a projection. * * Given: * lng,lat double Celestial longitude and latitude, in degrees. * eul[5] double Euler angles for the transformation: * 0: Celestial longitude of the native pole, in * degrees. * 1: Celestial colatitude of the native pole, or * native colatitude of the celestial pole, in * degrees. * 2: Native longitude of the celestial pole, in * degrees. * 3: cos(eul[1]) * 4: sin(eul[1]) * * Returned: * phi, double Longitude and latitude in the native coordinate * theta system of the projection, in degrees. * * Function return value: * int Error status * 0: Success. * * Reverse transformation; sphrev() * -------------------------------- * Transform native coordinates of a projection to celestial coordinates. * * Given: * phi, double Longitude and latitude in the native coordinate * theta system of the projection, in degrees. * eul[5] double Euler angles for the transformation: * 0: Celestial longitude of the native pole, in * degrees. * 1: Celestial colatitude of the native pole, or * native colatitude of the celestial pole, in * degrees. * 2: Native longitude of the celestial pole, in * degrees. * 3: cos(eul[1]) * 4: sin(eul[1]) * * Returned: * lng,lat double Celestial longitude and latitude, in degrees. * * Function return value: * int Error status * 0: Success. * * Author: Mark Calabretta, Australia Telescope National Facility * $Id: sph.c,v 2.7 2002/04/03 01:25:29 mcalabre Exp $ *===========================================================================*/ #include #include "wcslib.h" #ifndef __STDC__ #ifndef const #define const #endif #endif const double tol = 1.0e-5; int sphfwd (lng, lat, eul, phi, theta) const double lat, lng, eul[5]; double *phi, *theta; { double coslat, coslng, dlng, dphi, sinlat, sinlng, x, y, z; coslat = cosdeg (lat); sinlat = sindeg (lat); dlng = lng - eul[0]; coslng = cosdeg (dlng); sinlng = sindeg (dlng); /* Compute the native longitude. */ x = sinlat*eul[4] - coslat*eul[3]*coslng; if (fabs(x) < tol) { /* Rearrange formula to reduce roundoff errors. */ x = -cosdeg (lat+eul[1]) + coslat*eul[3]*(1.0 - coslng); } y = -coslat*sinlng; if (x != 0.0 || y != 0.0) { dphi = atan2deg (y, x); } else { /* Change of origin of longitude. */ dphi = dlng - 180.0; } *phi = eul[2] + dphi; /* Normalize the native longitude. */ if (*phi > 180.0) { *phi -= 360.0; } else if (*phi < -180.0) { *phi += 360.0; } /* Compute the native latitude. */ if (fmod(dlng,180.0) == 0.0) { *theta = lat + coslng*eul[1]; if (*theta > 90.0) *theta = 180.0 - *theta; if (*theta < -90.0) *theta = -180.0 - *theta; } else { z = sinlat*eul[3] + coslat*eul[4]*coslng; /* Use an alternative formula for greater numerical accuracy. */ if (fabs(z) > 0.99) { if (z < 0) *theta = -acosdeg (sqrt(x*x+y*y)); else *theta = acosdeg (sqrt(x*x+y*y)); } else { *theta = asindeg (z); } } return 0; } /*-----------------------------------------------------------------------*/ int sphrev (phi, theta, eul, lng, lat) const double phi, theta, eul[5]; double *lng, *lat; { double cosphi, costhe, dlng, dphi, sinphi, sinthe, x, y, z; costhe = cosdeg (theta); sinthe = sindeg (theta); dphi = phi - eul[2]; cosphi = cosdeg (dphi); sinphi = sindeg (dphi); /* Compute the celestial longitude. */ x = sinthe*eul[4] - costhe*eul[3]*cosphi; if (fabs(x) < tol) { /* Rearrange formula to reduce roundoff errors. */ x = -cosdeg (theta+eul[1]) + costhe*eul[3]*(1.0 - cosphi); } y = -costhe*sinphi; if (x != 0.0 || y != 0.0) { dlng = atan2deg (y, x); } else { /* Change of origin of longitude. */ dlng = dphi + 180.0; } *lng = eul[0] + dlng; /* Normalize the celestial longitude. */ if (eul[0] >= 0.0) { if (*lng < 0.0) *lng += 360.0; } else { if (*lng > 0.0) *lng -= 360.0; } if (*lng > 360.0) { *lng -= 360.0; } else if (*lng < -360.0) { *lng += 360.0; } /* Compute the celestial latitude. */ if (fmod(dphi,180.0) == 0.0) { *lat = theta + cosphi*eul[1]; if (*lat > 90.0) *lat = 180.0 - *lat; if (*lat < -90.0) *lat = -180.0 - *lat; } else { z = sinthe*eul[3] + costhe*eul[4]*cosphi; /* Use an alternative formula for greater numerical accuracy. */ if (fabs(z) > 0.99) { if (z < 0) *lat = -acosdeg (sqrt(x*x+y*y)); else *lat = acosdeg (sqrt(x*x+y*y)); } else { *lat = asindeg (z); } } return 0; } /* Dec 20 1999 Doug Mink - Change cosd() and sind() to cosdeg() and sindeg() * Dec 20 1999 Doug Mink - Include wcslib.h, which includes wcstrig.h, sph.h * Dec 20 1999 Doug Mink - Define copysign only if it is not already defined * * Jan 5 2000 Doug Mink - Drop copysign * * Sep 19 2001 Doug Mink - No change for WCSLIB 2.7 */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/fitshead.h0000664000175000017500000004735713047255533021441 0ustar mattymatty00000000000000/*** File fitshead.h FITS header access subroutines *** January 9, 2007 *** By Jessica Mink, jmink@cfa.harvard.edu *** Harvard-Smithsonian Center for Astrophysics *** Copyright (C) 1996-2007 *** Smithsonian Astrophysical Observatory, Cambridge, MA, USA This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Correspondence concerning WCSTools should be addressed as follows: Internet email: jmink@cfa.harvard.edu Postal address: Jessica Mink Smithsonian Astrophysical Observatory 60 Garden St. Cambridge, MA 02138 USA */ /* Declarations for subroutines in hget.c, hput.c, and iget.c */ #ifndef _fitshead_h_ #define _fitshead_h_ #include #ifdef __cplusplus /* C++ prototypes */ extern "C" { #endif #ifdef __STDC__ /* Full ANSI prototypes */ /* Subroutines in hget.c */ int hgeti2( /* Extract short value from FITS header */ const char* hstring, /* FITS header string */ const char* keyword, /* FITS keyword */ short* val); /* short integer value (returned) */ int hgeti4c( /* Extract int value from FITS header */ const char* hstring, /* FITS header string */ const char* keyword, /* FITS keyword */ const char* wchar, /* WCS to use (A-Z or null) */ int* val); /* integer value (returned) */ int hgeti4( /* Extract int value from FITS header */ const char* hstring, /* FITS header string */ const char* keyword, /* FITS keyword */ int* val); /* integer value (returned) */ int hgetr4( /* Extract float value from FITS header */ const char* hstring, /* FITS header string */ const char* keyword, /* FITS keyword */ float* val); /* float value (returned) */ int hgetr8c( /* Extract double value from FITS header */ const char* hstring, /* FITS header string */ const char* keyword, /* FITS keyword */ const char* wchar, /* WCS to use (A-Z or null) */ double* val); /* double value (returned) */ int hgetr8( /* Extract double value from FITS header */ const char* hstring, /* FITS header string */ const char* keyword, /* FITS keyword */ double* val); /* double value (returned) */ int hgetra( /* Extract right ascension from FITS header */ const char* hstring, /* FITS header string */ const char* keyword, /* FITS keyword */ double* ra); /* RA in degrees (returned) */ int hgetdec( /* Extract declination from FITS header */ const char* hstring, /* FITS header string */ const char* keyword, /* FITS keyword */ double* dec); /* Dec in degrees (returned) */ int hgetdate( /* Extract date from FITS header */ const char* hstring, /* FITS header string */ const char* keyword, /* FITS keyword */ double* date); /* Date in fractional years (returned) */ int hgetl( /* Extract boolean value from FITS header */ const char* hstring, /* FITS header string */ const char* keyword, /* FITS keyword */ int* lval); /* 1 if T, 0 if F (returned) */ int hgetsc( /* Extract string value from FITS header */ const char* hstring, /* FITS header string */ const char* keyword, /* FITS keyword */ const char* wchar, /* WCS to use (A-Z or null) */ const int lstr, /* maximum length of returned string */ char* string); /* null-terminated string value (returned) */ int hgets( /* Extract string value from FITS header */ const char* hstring, /* FITS header string */ const char* keyword, /* FITS keyword */ const int lstr, /* maximum length of returned string */ char* string); /* null-terminated string value (returned) */ int hgetm ( /* Extract string from multiple keywords */ const char* hstring, /* FITS header string */ const char* keyword, /* FITS keyword */ const int lstr, /* maximum length of returned string */ char* string); /* null-terminated string value (returned) */ int hgetndec( /* Find number of decimal places in FITS value*/ const char* hstring, /* FITS header string */ const char* keyword, /* FITS keyword */ int* ndec); /* number of decimal places (returned) */ char* hgetc( /* Return pointer to value for FITS keyword */ const char* hstring, /* FITS header string */ const char* keyword); /* FITS keyword */ char* ksearch( /* Return pointer to keyword in FITS header */ const char* hstring, /* FITS header string */ const char* keyword); /* FITS keyword */ char *blsearch ( const char* hstring, /* FITS header string */ const char* keyword); /* FITS keyword */ char *strsrch ( /* Find string s2 within string s1 */ const char* s1, /* String to search */ const char* s2); /* String to look for */ char *strnsrch ( /* Find string s2 within string s1 */ const char* s1, /* String to search */ const char* s2, /* String to look for */ const int ls1); /* Length of string being searched */ char *strcsrch ( /* Find string s2 within string s1 (no case) */ const char* s1, /* String to search */ const char* s2); /* String to look for */ char *strncsrch ( /* Find string s2 within string s1 (no case) */ const char* s1, /* String to search */ const char* s2, /* String to look for */ const int ls1); /* Length of string being searched */ int hlength( /* Set length of unterminated FITS header */ const char *header, /* FITS header */ const int lhead); /* Allocated length of FITS header */ int gethlength( /* Get length of current FITS header */ char* header); /* FITS header */ double str2ra( /* Return RA in degrees from string */ const char* in); /* Character string (hh:mm:ss.sss or dd.dddd) */ double str2dec( /* Return Dec in degrees from string */ const char* in); /* Character string (dd:mm:ss.sss or dd.dddd) */ int isnum( /* Return 1 if number, else 0 */ const char* string); /* Character string which may be a number */ int notnum( /* Return 0 if number, else 1 */ const char* string); /* Character string which may be a number */ int numdec( /* Return number of decimal places in number */ const char* string); /* Character string which may be a number */ void strfix( /* Clean up extraneous characters in string */ char* string, /* Character string which may be a number */ int fillblank, /* If 1, blanks are replaced by underscores */ int dropzero); /* If 1, drop trailing zeroes from string */ char *getltime(void); /* Return current local time in ISO format */ char *getutime(void); /* Return current UT as an ISO-format string */ /* Subroutines in iget.c */ int mgetstr( /* Extract string from multiline FITS keyword */ const char* hstring, /* FITS header string */ const char* mkey, /* FITS keyword root _n added for extra lines */ const char* keyword, /* IRAF keyword */ const int lstr, /* maximum length of returned string */ char* string); /* null-terminated string value (returned) */ int mgeti4( /* Extract int from multiline FITS keyword */ const char* hstring, /* FITS header string */ const char* mkey, /* FITS keyword root _n added for extra lines */ const char* keyword, /* IRAF keyword */ int* ival); /* int keyword value (returned) */ int mgetr8( /* Extract double from multiline FITS keyword */ const char* hstring, /* FITS header string */ const char* mkey, /* FITS keyword root _n added for extra lines */ const char* keyword, /* IRAF keyword */ double* dval); /* double keyword value (returned) */ int igeti4( /* Extract int from IRAF keyword string */ const char* hstring, /* Multiline IRAF keyword string value */ const char* keyword, /* IRAF keyword */ int* val); /* int value (returned) */ int igetr4( /* Extract float from IRAF keyword string */ const char* hstring, /* Multiline IRAF keyword string value */ const char* keyword, /* IRAF keyword */ float* val); /* float value (returned) */ int igetr8( /* Extract double from IRAF keyword string */ const char* hstring, /* Multiline IRAF keyword string value */ const char* keyword, /* IRAF keyword */ double* val); /* double value (returned) */ int igets( /* Extract string from IRAF keyword string */ const char* hstring, /* Multiline IRAF keyword string value */ const char* keyword, /* IRAF keyword */ const int lstr, /* maximum length of returned string */ char* string); /* null-terminated string value (returned) */ char *igetc( /* Extract string from IRAF keyword string */ const char* hstring, /* Multiline IRAF keyword string value */ const char* keyword); /* IRAF keyword */ /* Subroutines in hput.c */ /* All hput* routines return 0 if successful, else -1 */ int hputi2( /* Implant short value into FITS header */ char* hstring, /* FITS header string (modified) */ const char* keyword, /* FITS keyword */ short ival); /* short value */ int hputi4( /* Implant int value into FITS header */ char* hstring, /* FITS header string (modified) */ const char* keyword, /* FITS keyword */ const int ival); /* int value */ int hputr4( /* Implant float value into FITS header */ char* hstring, /* FITS header string (modified) */ const char* keyword, /* FITS keyword */ const float* rval); /* float (4 byte) value */ int hputr8( /* Implant short into FITS header */ char* hstring, /* FITS header string (modified) */ const char* keyword, /* FITS keyword */ const double dval); /* double value */ int hputnr8( /* double with specified number of decimal places */ char* hstring, /* FITS header string (modified) */ const char* keyword, /* FITS keyword */ const int ndec, /* Number of decimal places in keyword value */ const double dval); /* double value */ int hputs( /* Quoted character string into FITS header */ char* hstring, /* FITS header string (modified) */ const char* keyword, /* FITS keyword */ const char* cval); /* Character string value */ int hputm( /* Quoted character string, mutiple keywords */ char* hstring, /* FITS header string (modified) */ const char* keyword, /* FITS keyword */ const char* cval); /* Character string value */ int hputcom( /* Add comment to keyword line in FITS header */ char* hstring, /* FITS header string (modified) */ const char* keyword, /* FITS keyword */ const char* comment); /* Comment string */ int hputra( /* Right ascension in degrees into hh:mm:ss.sss */ char* hstring, /* FITS header string (modified) */ const char* keyword, /* FITS keyword */ const double ra); /* Right ascension in degrees */ int hputdec( /* Declination in degrees into dd:mm:ss.ss */ char* hstring, /* FITS header string (modified) */ const char* keyword, /* FITS keyword */ const double dec); /* Declination in degrees */ int hputl( /* Implant boolean value into FITS header */ char* hstring, /* FITS header string (modified) */ const char* keyword, /* FITS keyword */ const int lval); /* 0->F, else ->T */ int hputc( /* Implant character string without quotes */ char* hstring, /* FITS header string (modified) */ const char* keyword, /* FITS keyword */ const char* cval); /* Character string value */ int hdel( /* Delete a keyword line from a FITS header */ char* hstring, /* FITS header string (modified) */ const char* keyword); /* FITS keyword to delete */ int hadd( /* Add a keyword line from a FITS header */ char* hplace, /* Location in FITS header string (modified) */ const char* keyword); /* FITS keyword to add */ int hchange( /* Change a keyword name in a FITS header */ char* hstring, /* FITS header string (modified) */ const char* keyword1, /* Current FITS keyword name */ const char* keyword2); /* New FITS keyword name */ void ra2str( /* Convert degrees to hh:mm:ss.ss */ char *string, /* Character string (returned) */ int lstr, /* Length of string */ const double ra, /* Right ascension in degrees */ const int ndec); /* Number of decimal places in seconds */ void dec2str( /* Convert degrees to dd:mm:ss.ss */ char *string, /* Character string (returned) */ int lstr, /* Length of string */ const double dec, /* Declination in degrees */ const int ndec); /* Number of decimal places in arcseconds */ void deg2str( /* Format angle into decimal degrees string */ char *string, /* Character string (returned) */ int lstr, /* Length of string */ const double deg, /* Angle in degrees */ const int ndec); /* Number of decimal places in degrees */ void num2str( /* Format number into string */ char *string, /* Character string (returned) */ const double num, /* Number */ const int field, /* Total field size in characters */ const int ndec); /* Number of decimal places */ void setheadshrink( /* 0 to keep blank line when keyword deleted */ const int hsh); /* 1 to shrink header by one line */ void setleaveblank( /* 1 to keep blank line where keyword deleted */ const int hsh); /* 0 to shrink header by one line */ #else /* K&R prototypes */ /* Subroutines in hget.c */ /* Extract a value from a FITS header for given keyword */ extern int hgeti4(); /* int (Multiple WCS) */ extern int hgeti4c(); /* int */ extern int hgeti2(); /* short */ extern int hgetr4(); /* float */ extern int hgetr8(); /* double */ extern int hgetr8c(); /* double (Multiple WCS) */ extern int hgetra(); /* Right ascension in degrees from string */ extern int hgetdec(); /* Declination in degrees from string */ extern int hgetdate(); /* Date in years from FITS date string */ extern int hgetl(); /* T->1, F->0 from FITS logical entry */ extern int hgets(); /* Previously allocated string */ extern int hgetsc(); /* Previously allocated string (Multiple WCS) */ extern int hgetm(); /* Previously allocated string from multiple keywords */ extern char *hgetc(); /* Return pointer to string */ extern int hgetndec(); /* Number of decimal places in keyword value */ /* Subroutines to convert strings to RA and Dec in degrees */ extern double str2ra(); extern double str2dec(); /* Check to see whether a string is a number or not */ extern int isnum(); extern int notnum(); extern int decnum(); /* Find given keyword entry in FITS header */ extern char *ksearch(); /* Find beginning of fillable blank line before FITS header keyword */ extern char *blsearch(); /* Search for substring s2 within string s1 */ extern char *strsrch (); /* s1 null-terminated */ extern char *strnsrch (); /* s1 ls1 characters long */ extern char *strcsrch (); /* s1 null-terminated (case-insensitive) */ extern char *strncsrch (); /* s1 ls1 characters long (case-insensitive) */ extern void strfix(); /* Drop or change extraneous characters in string */ /* Set length of header which is not null-terminated */ extern int hlength(); /* Get length of current FITS header */ extern int gethlength(); /* Subroutines in iget.c */ extern int mgetstr(); /* Previously allocated string from multiline keyword */ extern int mgetr8(); /* double from multiline keyword */ extern int mgeti4(); /* int from multiline keyword */ extern int igeti4(); /* long integer from IRAF compound keyword value */ extern int igetr4(); /* real from IRAF compound keyword value */ extern int igetr8(); /* double from IRAF compound keyword value */ extern int igets(); /* character string from IRAF compound keyword value */ extern char *igetc(); /* Extract string from IRAF keyword string */ /* Subroutines in hput.c */ /* Implant a value into a FITS header for given keyword */ extern int hputi4(); /* int */ extern int hputi2(); /* short */ extern int hputr4(); /* float */ extern int hputr8(); /* double */ extern int hputnr8(); /* double with specified number of decimal places */ extern int hputra(); /* Right ascension in degrees into hh:mm:ss.sss */ extern int hputdec(); /* Declination in degrees into dd:mm:ss.ss */ extern int hputl(); /* 0 -> F, else T FITS logical entry */ extern int hputs(); /* Quoted character string */ extern int hputm(); /* Quoted character string into mutiple keywords */ extern int hputc(); /* Character string without quotes (returns 0 if OK) */ extern int hputcom(); /* Comment after keyword=value (returns 0 if OK) */ extern int hdel(); /* Delete a keyword line from a FITS header */ extern int hadd(); /* Add a keyword line to a FITS header */ extern int hchange(); /* Change a keyword name in a FITS header */ extern void setheadshrink(); /* Set flag for deleted keyword space disposition*/ extern void setleaveblank(); /* Set flag for deleted keyword space disposition*/ /* Subroutines to convert RA and Dec in degrees to strings */ extern void ra2str(); extern void dec2str(); extern void deg2str(); extern void num2str(); extern int numdec(); /* Return number of decimal places in number */ extern char *getltime(); /* Return current local time in ISO format */ extern char *getutime(); /* Return current UT as an ISO-format string */ #endif /* __STDC__ */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* fitshead_h_ */ /* Apr 26 1996 Add HGETDATE to get year from date string * May 22 1996 Return double from STR2RA and STR2DEC * May 31 1996 Use stream I/O for reading as well as writing * Jun 12 1996 Add byte-swapping subroutines * Jul 10 1996 FITS header now allocated in subroutines * Jul 17 1996 Add FITS table column extraction subroutines * Jul 19 1996 Add declarations for header implanting subroutines * Aug 5 1996 Add HLENGTH for FITS headers which are not null-terminated * Aug 5 1996 Add STRNSRCH for FITS headers which are not null-terminated * Aug 6 1996 Add HPUTNR8 to save a specified number of decimal places * Aug 6 1996 Add MOVEPIX, HDEL and HCHANGE declarations * Nov 1 1996 Add DEG2STR * Dec 12 1996 Add ISNUM * * Oct 10 1997 FITS file opening subroutines now return int instead of FILE * * * Mar 12 1998 Add NOTNUM * Apr 30 1998 Clean up declarations and add more comments * May 12 1998 Add MGETS, MGETR8, MGETI4 for IRAF multi-line keywords * May 26 1998 Add HGETNDEC for number of decimal places in keyword value * May 27 1998 Add BLSEARCH to find usable blank lines in header * May 27 1998 Split off fitsio and imhio subroutines to fitsio.h * May 27 1998 Add all subroutines in hget.c, hput.c, and iget.c to C++ dec. * Jun 24 1998 Add string lengths to ra2str(), dec2str, and deg2str() calls * Jun 25 1998 Fix other C++ declarations with added string lengths * Aug 31 1998 Add current date subroutines getltime() and getutime() * Oct 28 1998 Add missing hgetc() to non c++ declarations * * Oct 6 1999 Add gethlength() to return current size of header * Oct 14 1999 All HPUT subroutines now return an error code, 0 if OK, else -1 * Oct 15 1999 Add hputcom() declaration * Oct 21 1999 Add hgetm() declaration * * Mar 22 2000 Add int to iget*() declarations * Mar 27 2000 Add hputm() declaration * * Apr 3 2002 Add hgeti4c(), hgetr8c(), and hgetsc() * Apr 8 2002 Include sys/types.h * Aug 30 2002 Add strcsrch() and strncsrch() * * Sep 23 2003 Change mgets() to mgetstr() to avoid name collision at UCO Lick * Oct 20 2003 Add numdec() to return the number of decimal places in a string * * Feb 26 2004 Add igetc(), formerly internal to iget.c * Jul 1 2004 Add setheadshrink() for hdel() * Aug 30 2004 Add numdec() to non-C++ declarations * * May 22 2006 Add setleaveblank() to leave blank line where keyword is deleted * Jun 28 2006 Add strfix() to clean up characters in strings * Nov 29 2006 Drop semicolon at end of C++ ifdef * * Jan 9 2007 Fix declarations so ANSI prototypes are not just for C++ */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/wcs.h.orig0000664000175000017500000014144313047255533021374 0ustar mattymatty00000000000000/*** File libwcs/wcs.h *** February 1, 2013 *** By Jessica Mink, jmink@cfa.harvard.edu *** Harvard-Smithsonian Center for Astrophysics *** Copyright (C) 1994-2013 *** Smithsonian Astrophysical Observatory, Cambridge, MA, USA This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Correspondence concerning WCSTools should be addressed as follows: Internet email: jmink@cfa.harvard.edu Postal address: Jessica Mink Smithsonian Astrophysical Observatory 60 Garden St. Cambridge, MA 02138 USA */ #ifndef _wcs_h_ #define _wcs_h_ #include "wcslib.h" #include "fitshead.h" /* SIRTF distortion matrix coefficients */ #define DISTMAX 10 struct Distort { int a_order; /* max power for the 1st dimension */ double a[DISTMAX][DISTMAX]; /* coefficient array of 1st dimension */ int b_order; /* max power for 1st dimension */ double b[DISTMAX][DISTMAX]; /* coefficient array of 2nd dimension */ int ap_order; /* max power for the 1st dimension */ double ap[DISTMAX][DISTMAX]; /* coefficient array of 1st dimension */ int bp_order; /* max power for 1st dimension */ double bp[DISTMAX][DISTMAX]; /* coefficient array of 2nd dimension */ }; struct WorldCoor { double xref; /* X reference coordinate value (deg) */ double yref; /* Y reference coordinate value (deg) */ double xrefpix; /* X reference pixel */ double yrefpix; /* Y reference pixel */ double xinc; /* X coordinate increment (deg) */ double yinc; /* Y coordinate increment (deg) */ double rot; /* rotation around axis (deg) (N through E) */ double cd[4]; /* rotation matrix */ double dc[4]; /* inverse rotation matrix */ double equinox; /* Equinox of coordinates default to 1950.0 */ double epoch; /* Epoch of coordinates default to equinox */ double nxpix; /* Number of pixels in X-dimension of image */ double nypix; /* Number of pixels in Y-dimension of image */ double plate_ra; /* Right ascension of plate center */ double plate_dec; /* Declination of plate center */ double plate_scale; /* Plate scale in arcsec/mm */ double x_pixel_offset; /* X pixel offset of image lower right */ double y_pixel_offset; /* Y pixel offset of image lower right */ double x_pixel_size; /* X pixel_size */ double y_pixel_size; /* Y pixel_size */ double ppo_coeff[6]; /* pixel to plate coefficients for DSS */ double x_coeff[20]; /* X coefficients for plate model */ double y_coeff[20]; /* Y coefficients for plate model */ double xpix; /* X (RA) coordinate (pixels) */ double ypix; /* Y (dec) coordinate (pixels) */ double zpix; /* Z (face) coordinate (pixels) */ double xpos; /* X (RA) coordinate (deg) */ double ypos; /* Y (dec) coordinate (deg) */ double crpix[9]; /* Values of CRPIXn keywords */ double crval[9]; /* Values of CRVALn keywords */ double cdelt[9]; /* Values of CDELTn keywords */ double pc[81]; /* Values of PCiiijjj keywords */ double projp[10]; /* Constants for various projections */ int pvfail; /* If non-zero, significant inaccuracy likely to occur in projection */ double projppv[2*MAXPV]; /* SCAMP constants for the PV coordinates */ struct poly *inv_x; /* SCAMP projection correction polynom in x */ struct poly *inv_y; /* SCAMP projection correction polynom in y */ double longpole; /* Longitude of North Pole in degrees */ double latpole; /* Latitude of North Pole in degrees */ double rodeg; /* Radius of the projection generating sphere */ double imrot; /* Rotation angle of north pole */ double pa_north; /* Position angle of north (0=horizontal) */ double pa_east; /* Position angle of east (0=horizontal) */ double radvel; /* Radial velocity (km/sec away from observer)*/ double zvel; /* Radial velocity (v/c away from observer)*/ double zpzd; /* Colat of FIP (degs) */ double zpr; /* Radius of FIP (degs) */ int imflip; /* If not 0, image is reflected around axis */ int prjcode; /* projection code (-1-32) */ int latbase; /* Latitude base 90 (NPA), 0 (LAT), -90 (SPA) */ int ncoeff1; /* Number of x-axis plate fit coefficients */ int ncoeff2; /* Number of y-axis plate fit coefficients */ int zpnp; /* ZP polynomial order (0-9) */ int changesys; /* 1 for FK4->FK5, 2 for FK5->FK4 */ /* 3 for FK4->galactic, 4 for FK5->galactic */ int printsys; /* 1 to print coordinate system, else 0 */ int ndec; /* Number of decimal places in PIX2WCST */ int degout; /* 1 to always print degrees in PIX2WCST */ int tabsys; /* 1 to put tab between RA & Dec, else 0 */ int rotmat; /* 0 if CDELT, CROTA; 1 if CD */ int coorflip; /* 0 if x=RA, y=Dec; 1 if x=Dec, y=RA */ int offscl; /* 0 if OK, 1 if offscale */ int wcson; /* 1 if WCS is set, else 0 */ int naxis; /* Number of axes in image (for WCSLIB 3.0) */ int naxes; /* Number of axes in image */ int wcsproj; /* WCS_OLD: AIPS worldpos() and worldpix() WCS_NEW: Mark Calabretta's WCSLIB subroutines WCS_BEST: WCSLIB for all but CAR,COE,NCP WCS_ALT: AIPS for all but CAR,COE,NCP */ int linmode; /* 0=system only, 1=units, 2=system+units */ int detector; /* Instrument detector number */ char instrument[32]; /* Instrument name */ char ctype[9][9]; /* Values of CTYPEn keywords */ char c1type[9]; /* 1st coordinate type code: RA--, GLON, ELON */ char c2type[9]; /* 2nd coordinate type code: DEC-, GLAT, ELAT */ char ptype[9]; /* projection type code: SIN, TAN, ARC, NCP, GLS, MER, AIT, etc */ char units[9][32]; /* Units if LINEAR */ char radecsys[32]; /* Reference frame: FK4, FK4-NO-E, FK5, GAPPT*/ char radecout[32]; /* Output reference frame: FK4,FK5,GAL,ECL */ char radecin[32]; /* Input reference frame: FK4,FK5,GAL,ECL */ double eqin; /* Input equinox (match sysin if 0.0) */ double eqout; /* Output equinox (match sysout if 0.0) */ int sysin; /* Input coordinate system code */ int syswcs; /* WCS coordinate system code */ int sysout; /* Output coordinate system code */ /* WCS_B1950, WCS_J2000, WCS_ICRS, WCS_GALACTIC, * WCS_ECLIPTIC, WCS_LINEAR, WCS_ALTAZ */ char center[32]; /* Center coordinates (with frame) */ struct wcsprm wcsl; /* WCSLIB main projection parameters */ struct linprm lin; /* WCSLIB image/pixel conversion parameters */ struct celprm cel; /* WCSLIB projection type */ struct prjprm prj; /* WCSLIB projection parameters */ struct IRAFsurface *lngcor; /* RA/longitude correction structure */ struct IRAFsurface *latcor; /* Dec/latitude correction structure */ int distcode; /* Distortion code 0=none 1=SIRTF */ struct Distort distort; /* SIRTF distortion coefficients */ char *command_format[10]; /* WCS command formats */ /* where %s is replaced by WCS coordinates */ /* where %f is replaced by the image filename */ /* where %x is replaced by image coordinates */ double ltm[4]; /* Image rotation matrix */ double ltv[2]; /* Image offset */ int idpix[2]; /* First pixel to use in image (x, y) */ int ndpix[2]; /* Number of pixels to use in image (x, y) */ struct WorldCoor *wcs; /* WCS upon which this WCS depends */ struct WorldCoor *wcsdep; /* WCS depending on this WCS */ char *wcsname; /* WCS name (defaults to NULL pointer) */ char wcschar; /* WCS character (A-Z, null, space) */ int logwcs; /* 1 if DC-FLAG is set for log wavelength */ }; /* Projections (1-26 are WCSLIB) (values for wcs->prjcode) */ #define WCS_PIX -1 /* Pixel WCS */ #define WCS_LIN 0 /* Linear projection */ #define WCS_AZP 1 /* Zenithal/Azimuthal Perspective */ #define WCS_SZP 2 /* Zenithal/Azimuthal Perspective */ #define WCS_TAN 3 /* Gnomonic = Tangent Plane */ #define WCS_SIN 4 /* Orthographic/synthesis */ #define WCS_STG 5 /* Stereographic */ #define WCS_ARC 6 /* Zenithal/azimuthal equidistant */ #define WCS_ZPN 7 /* Zenithal/azimuthal PolyNomial */ #define WCS_ZEA 8 /* Zenithal/azimuthal Equal Area */ #define WCS_AIR 9 /* Airy */ #define WCS_CYP 10 /* CYlindrical Perspective */ #define WCS_CAR 11 /* Cartesian */ #define WCS_MER 12 /* Mercator */ #define WCS_CEA 13 /* Cylindrical Equal Area */ #define WCS_COP 14 /* Conic PerSpective (COP) */ #define WCS_COD 15 /* COnic equiDistant */ #define WCS_COE 16 /* COnic Equal area */ #define WCS_COO 17 /* COnic Orthomorphic */ #define WCS_BON 18 /* Bonne */ #define WCS_PCO 19 /* Polyconic */ #define WCS_SFL 20 /* Sanson-Flamsteed (GLobal Sinusoidal) */ #define WCS_PAR 21 /* Parabolic */ #define WCS_AIT 22 /* Hammer-Aitoff */ #define WCS_MOL 23 /* Mollweide */ #define WCS_CSC 24 /* COBE quadrilateralized Spherical Cube */ #define WCS_QSC 25 /* Quadrilateralized Spherical Cube */ #define WCS_TSC 26 /* Tangential Spherical Cube */ #define WCS_NCP 27 /* Special case of SIN */ #define WCS_GLS 28 /* Same as SFL */ #define WCS_DSS 29 /* Digitized Sky Survey plate solution */ #define WCS_PLT 30 /* Plate fit polynomials (SAO) */ #define WCS_TNX 31 /* Gnomonic = Tangent Plane (NOAO with corrections) */ #define WCS_ZPX 32 /* Gnomonic = Tangent Plane (NOAO with corrections) */ #define WCS_TPV 33 /* Gnomonic = Tangent Plane (NOAO with corrections) */ #define NWCSTYPE 34 /* Number of WCS types (-1 really means no WCS) */ /* Coordinate systems */ #define WCS_J2000 1 /* J2000(FK5) right ascension and declination */ #define WCS_B1950 2 /* B1950(FK4) right ascension and declination */ #define WCS_GALACTIC 3 /* Galactic longitude and latitude */ #define WCS_ECLIPTIC 4 /* Ecliptic longitude and latitude */ #define WCS_ALTAZ 5 /* Azimuth and altitude/elevation */ #define WCS_LINEAR 6 /* Linear with optional units */ #define WCS_NPOLE 7 /* Longitude and north polar angle */ #define WCS_SPA 8 /* Longitude and south polar angle */ #define WCS_PLANET 9 /* Longitude and latitude on planet */ #define WCS_XY 10 /* X-Y Cartesian coordinates */ #define WCS_ICRS 11 /* ICRS right ascension and declination */ /* Method to use */ #define WCS_BEST 0 /* Use best WCS projections */ #define WCS_ALT 1 /* Use not best WCS projections */ #define WCS_OLD 2 /* Use AIPS WCS projections */ #define WCS_NEW 3 /* Use WCSLIB 2.5 WCS projections */ /* Distortion codes (values for wcs->distcode) */ #define DISTORT_NONE 0 /* No distortion coefficients */ #define DISTORT_SIRTF 1 /* SIRTF distortion matrix */ #ifndef PI #define PI 3.141592653589793238462643 #endif /* pi/(180*3600): arcseconds to radians */ #define AS2R 4.8481368110953e-6 /* Conversions among hours of RA, degrees and radians. */ #define degrad(x) ((x)*PI/180.) #define raddeg(x) ((x)*180./PI) #define hrdeg(x) ((x)*15.) #define deghr(x) ((x)/15.) #define hrrad(x) degrad(hrdeg(x)) #define radhr(x) deghr(raddeg(x)) #define secrad(x) ((x)*AS2R) /* TNX/ZPX surface fitting structure and flags */ struct IRAFsurface { double xrange; /* 2. / (xmax - xmin), polynomials */ double xmaxmin; /* - (xmax + xmin) / 2., polynomials */ double yrange; /* 2. / (ymax - ymin), polynomials */ double ymaxmin; /* - (ymax + ymin) / 2., polynomials */ int type; /* type of curve to be fitted */ int xorder; /* order of the fit in x */ int yorder; /* order of the fit in y */ int xterms; /* cross terms for polynomials */ int ncoeff; /* total number of coefficients */ double *coeff; /* pointer to coefficient vector */ double *xbasis; /* pointer to basis functions (all x) */ double *ybasis; /* pointer to basis functions (all y) */ }; /* TNX/ZPX permitted types of surfaces */ #define TNX_CHEBYSHEV 1 #define TNX_LEGENDRE 2 #define TNX_POLYNOMIAL 3 /* TNX/ZPX cross-terms flags */ #define TNX_XNONE 0 /* no x-terms (old no) */ #define TNX_XFULL 1 /* full x-terms (new yes) */ #define TNX_XHALF 2 /* half x-terms (new) */ #ifdef __cplusplus /* C++ prototypes */ extern "C" { #endif #ifdef __STDC__ /* Full ANSI prototypes */ /* WCS data structure initialization subroutines in wcsinit.c */ struct WorldCoor *wcsinit ( /* set up WCS structure from a FITS image header */ const char* hstring); struct WorldCoor *wcsninit ( /* set up WCS structure from a FITS image header */ const char* hstring, /* FITS header */ int len); /* Length of FITS header */ struct WorldCoor *wcsinitn ( /* set up WCS structure from a FITS image header */ const char* hstring, /* FITS header */ const char* wcsname); /* WCS name */ struct WorldCoor *wcsninitn ( /* set up WCS structure from a FITS image header */ const char* hstring, /* FITS header */ int len, /* Length of FITS header */ const char* wcsname); /* WCS name */ struct WorldCoor *wcsinitc ( /* set up WCS structure from a FITS image header */ const char* hstring, /* FITS header */ char *wcschar); /* WCS character (A-Z) */ struct WorldCoor *wcsninitc ( /* set up WCS structure from a FITS image header */ const char* hstring, /* FITS header */ int len, /* Length of FITS header */ char *wcschar); /* WCS character (A-Z) */ char *uppercase ( /* Convert string of any case to uppercase */ const char *string); /* String to convert */ /* WCS subroutines in wcs.c */ void wcsfree ( /* Free a WCS structure and its contents */ struct WorldCoor *wcs); /* World coordinate system structure */ int wcstype( /* Set projection type from header CTYPEs */ struct WorldCoor *wcs, /* World coordinate system structure */ char *ctype1, /* FITS WCS projection for axis 1 */ char *ctype2); /* FITS WCS projection for axis 2 */ int iswcs( /* Returns 1 if wcs structure set, else 0 */ struct WorldCoor *wcs); /* World coordinate system structure */ int nowcs( /* Returns 0 if wcs structure set, else 1 */ struct WorldCoor *wcs); /* World coordinate system structure */ int pix2wcst ( /* Convert pixel coordinates to World Coordinate string */ struct WorldCoor *wcs, /* World coordinate system structure */ double xpix, /* Image horizontal coordinate in pixels */ double ypix, /* Image vertical coordinate in pixels */ char *wcstring, /* World coordinate string (returned) */ int lstr); /* Length of world coordinate string (returned) */ void pix2wcs ( /* Convert pixel coordinates to World Coordinates */ struct WorldCoor *wcs, /* World coordinate system structure */ double xpix, /* Image horizontal coordinate in pixels */ double ypix, /* Image vertical coordinate in pixels */ double *xpos, /* Longitude/Right Ascension in degrees (returned) */ double *ypos); /* Latitude/Declination in degrees (returned) */ void wcsc2pix ( /* Convert World Coordinates to pixel coordinates */ struct WorldCoor *wcs, /* World coordinate system structure */ double xpos, /* Longitude/Right Ascension in degrees */ double ypos, /* Latitude/Declination in degrees */ char *coorsys, /* Coordinate system (B1950, J2000, etc) */ double *xpix, /* Image horizontal coordinate in pixels (returned) */ double *ypix, /* Image vertical coordinate in pixels (returned) */ int *offscl); void wcs2pix ( /* Convert World Coordinates to pixel coordinates */ struct WorldCoor *wcs, /* World coordinate system structure */ double xpos, /* Longitude/Right Ascension in degrees */ double ypos, /* Latitude/Declination in degrees */ double *xpix, /* Image horizontal coordinate in pixels (returned) */ double *ypix, /* Image vertical coordinate in pixels (returned) */ int *offscl); double wcsdist( /* Compute angular distance between 2 sky positions */ double ra1, /* First longitude/right ascension in degrees */ double dec1, /* First latitude/declination in degrees */ double ra2, /* Second longitude/right ascension in degrees */ double dec2); /* Second latitude/declination in degrees */ double wcsdist1( /* Compute angular distance between 2 sky positions */ double ra1, /* First longitude/right ascension in degrees */ double dec1, /* First latitude/declination in degrees */ double ra2, /* Second longitude/right ascension in degrees */ double dec2); /* Second latitude/declination in degrees */ double wcsdiff( /* Compute angular distance between 2 sky positions */ double ra1, /* First longitude/right ascension in degrees */ double dec1, /* First latitude/declination in degrees */ double ra2, /* Second longitude/right ascension in degrees */ double dec2); /* Second latitude/declination in degrees */ struct WorldCoor* wcsxinit( /* set up a WCS structure from arguments */ double cra, /* Center right ascension in degrees */ double cdec, /* Center declination in degrees */ double secpix, /* Number of arcseconds per pixel */ double xrpix, /* Reference pixel X coordinate */ double yrpix, /* Reference pixel X coordinate */ int nxpix, /* Number of pixels along x-axis */ int nypix, /* Number of pixels along y-axis */ double rotate, /* Rotation angle (clockwise positive) in degrees */ int equinox, /* Equinox of coordinates, 1950 and 2000 supported */ double epoch, /* Epoch of coordinates, used for FK4/FK5 conversion * no effect if 0 */ char *proj); /* Projection */ struct WorldCoor* wcskinit( /* set up WCS structure from keyword values */ int naxis1, /* Number of pixels along x-axis */ int naxis2, /* Number of pixels along y-axis */ char *ctype1, /* FITS WCS projection for axis 1 */ char *ctype2, /* FITS WCS projection for axis 2 */ double crpix1, /* Reference pixel coordinates */ double crpix2, /* Reference pixel coordinates */ double crval1, /* Coordinate at reference pixel in degrees */ double crval2, /* Coordinate at reference pixel in degrees */ double *cd, /* Rotation matrix, used if not NULL */ double cdelt1, /* scale in degrees/pixel, if cd is NULL */ double cdelt2, /* scale in degrees/pixel, if cd is NULL */ double crota, /* Rotation angle in degrees, if cd is NULL */ int equinox, /* Equinox of coordinates, 1950 and 2000 supported */ double epoch); /* Epoch of coordinates, for FK4/FK5 conversion */ void wcsshift( /* Change center of WCS */ struct WorldCoor *wcs, /* World coordinate system structure */ double cra, /* New center right ascension in degrees */ double cdec, /* New center declination in degrees */ char *coorsys); /* FK4 or FK5 coordinates (1950 or 2000) */ void wcsfull( /* Return RA and Dec of image center, size in degrees */ struct WorldCoor *wcs, /* World coordinate system structure */ double *cra, /* Right ascension of image center (deg) (returned) */ double *cdec, /* Declination of image center (deg) (returned) */ double *width, /* Width in degrees (returned) */ double *height); /* Height in degrees (returned) */ void wcscent( /* Print the image center and size in WCS units */ struct WorldCoor *wcs); /* World coordinate system structure */ void wcssize( /* Return image center and size in RA and Dec */ struct WorldCoor *wcs, /* World coordinate system structure */ double *cra, /* Right ascension of image center (deg) (returned) */ double *cdec, /* Declination of image center (deg) (returned) */ double *dra, /* Half-width in right ascension (deg) (returned) */ double *ddec); /* Half-width in declination (deg) (returned) */ void wcsrange( /* Return min and max RA and Dec of image in degrees */ struct WorldCoor *wcs, /* World coordinate system structure */ double *ra1, /* Min. right ascension of image (deg) (returned) */ double *ra2, /* Max. right ascension of image (deg) (returned) */ double *dec1, /* Min. declination of image (deg) (returned) */ double *dec2); /* Max. declination of image (deg) (returned) */ void wcscdset( /* Set scaling and rotation from CD matrix */ struct WorldCoor *wcs, /* World coordinate system structure */ double *cd); /* CD matrix, ignored if NULL */ void wcsdeltset( /* set scaling, rotation from CDELTi, CROTA2 */ struct WorldCoor *wcs, /* World coordinate system structure */ double cdelt1, /* degrees/pixel in first axis (or both axes) */ double cdelt2, /* degrees/pixel in second axis if nonzero */ double crota); /* Rotation counterclockwise in degrees */ void wcspcset( /* set scaling, rotation from CDELTs and PC matrix */ struct WorldCoor *wcs, /* World coordinate system structure */ double cdelt1, /* degrees/pixel in first axis (or both axes) */ double cdelt2, /* degrees/pixel in second axis if nonzero */ double *pc); /* Rotation matrix, ignored if NULL */ void setwcserr( /* Set WCS error message for later printing */ char *errmsg); /* Error mesage < 80 char */ void wcserr(void); /* Print WCS error message to stderr */ void setdefwcs( /* Set flag to use AIPS WCS instead of WCSLIB */ int oldwcs); /* 1 for AIPS WCS subroutines, else WCSLIB */ int getdefwcs(void); /* Return flag for AIPS WCS set by setdefwcs */ char *getradecsys( /* Return name of image coordinate system */ struct WorldCoor *wcs); /* World coordinate system structure */ void wcsoutinit( /* Set output coordinate system for pix2wcs */ struct WorldCoor *wcs, /* World coordinate system structure */ char *coorsys); /* Coordinate system (B1950, J2000, etc) */ char *getwcsout( /* Return current output coordinate system */ struct WorldCoor *wcs); /* World coordinate system structure */ void wcsininit( /* Set input coordinate system for wcs2pix */ struct WorldCoor *wcs, /* World coordinate system structure */ char *coorsys); /* Coordinate system (B1950, J2000, etc) */ char *getwcsin( /* Return current input coordinate system */ struct WorldCoor *wcs); /* World coordinate system structure */ int setwcsdeg( /* Set WCS coordinate output format */ struct WorldCoor *wcs, /* World coordinate system structure */ int degout); /* 1= degrees, 0= hh:mm:ss dd:mm:ss */ int wcsndec( /* Set or get number of output decimal places */ struct WorldCoor *wcs, /* World coordinate system structure */ int ndec); /* Number of decimal places in output string if < 0, return current ndec unchanged */ int wcsreset( /* Change WCS using arguments */ struct WorldCoor *wcs, /* World coordinate system data structure */ double crpix1, /* Horizontal reference pixel */ double crpix2, /* Vertical reference pixel */ double crval1, /* Reference pixel horizontal coordinate in degrees */ double crval2, /* Reference pixel vertical coordinate in degrees */ double cdelt1, /* Horizontal scale in degrees/pixel, ignored if cd is not NULL */ double cdelt2, /* Vertical scale in degrees/pixel, ignored if cd is not NULL */ double crota, /* Rotation angle in degrees, ignored if cd is not NULL */ double *cd); /* Rotation matrix, used if not NULL */ void wcseqset( /* Change equinox of reference pixel coordinates in WCS */ struct WorldCoor *wcs, /* World coordinate system data structure */ double equinox); /* Desired equinox as fractional year */ void setwcslin( /* Set pix2wcst() mode for LINEAR coordinates */ struct WorldCoor *wcs, /* World coordinate system structure */ int mode); /* 0: x y linear, 1: x units x units 2: x y linear units */ int wcszin( /* Set third dimension for cube projections */ int izpix); /* Set coordinate in third dimension (face) */ int wcszout ( /* Return coordinate in third dimension */ struct WorldCoor *wcs); /* World coordinate system structure */ void wcscominit( /* Initialize catalog search command set by -wcscom */ struct WorldCoor *wcs, /* World coordinate system structure */ int i, /* Number of command (0-9) to initialize */ char *command); /* command with %s where coordinates will go */ void wcscom( /* Execute catalog search command set by -wcscom */ struct WorldCoor *wcs, /* World coordinate system structure */ int i, /* Number of command (0-9) to execute */ char *filename, /* Image file name */ double xfile, /* Horizontal image pixel coordinates for WCS command */ double yfile, /* Vertical image pixel coordinates for WCS command */ char *wcstring); /* WCS String from pix2wcst() */ void savewcscom( /* Save WCS shell command */ int i, /* i of 10 possible shell commands */ char *wcscom); /* Shell command using output WCS string */ char *getwcscom( /* Return WCS shell command */ int i); /* i of 10 possible shell commands */ void setwcscom( /* Set WCS shell commands from stored values */ struct WorldCoor *wcs); /* World coordinate system structure */ void freewcscom( /* Free memory storing WCS shell commands */ struct WorldCoor *wcs); /* World coordinate system structure */ void setwcsfile( /* Set filename for WCS error message */ char *filename); /* FITS or IRAF file name */ int cpwcs ( /* Copy WCS keywords with no suffix to ones with suffix */ char **header, /* Pointer to start of FITS header */ char *cwcs); /* Keyword suffix character for output WCS */ void savewcscoor( /* Save output coordinate system */ char *wcscoor); /* coordinate system (J2000, B1950, galactic) */ char *getwcscoor(void); /* Return output coordinate system */ /* Coordinate conversion subroutines in wcscon.c */ void wcsconv( /* Convert between coordinate systems and equinoxes */ int sys1, /* Input coordinate system (J2000, B1950, ECLIPTIC, GALACTIC */ int sys2, /* Output coordinate system (J2000, B1950, ECLIPTIC, G ALACTIC */ double eq1, /* Input equinox (default of sys1 if 0.0) */ double eq2, /* Output equinox (default of sys2 if 0.0) */ double ep1, /* Input Besselian epoch in years */ double ep2, /* Output Besselian epoch in years */ double *dtheta, /* Longitude or right ascension in degrees Input in sys1, returned in sys2 */ double *dphi, /* Latitude or declination in degrees Input in sys1, returned in sys2 */ double *ptheta, /* Longitude or right ascension proper motion in deg/year Input in sys1, returned in sys2 */ double *pphi, /* Latitude or declination proper motion in deg/year */ double *px, /* Parallax in arcseconds */ double *rv); /* Radial velocity in km/sec */ void wcsconp( /* Convert between coordinate systems and equinoxes */ int sys1, /* Input coordinate system (J2000, B1950, ECLIPTIC, GALACTIC */ int sys2, /* Output coordinate system (J2000, B1950, ECLIPTIC, G ALACTIC */ double eq1, /* Input equinox (default of sys1 if 0.0) */ double eq2, /* Output equinox (default of sys2 if 0.0) */ double ep1, /* Input Besselian epoch in years */ double ep2, /* Output Besselian epoch in years */ double *dtheta, /* Longitude or right ascension in degrees Input in sys1, returned in sys2 */ double *dphi, /* Latitude or declination in degrees Input in sys1, returned in sys2 */ double *ptheta, /* Longitude or right ascension proper motion in degrees/year Input in sys1, returned in sys2 */ double *pphi); /* Latitude or declination proper motion in degrees/year Input in sys1, returned in sys2 */ void wcscon( /* Convert between coordinate systems and equinoxes */ int sys1, /* Input coordinate system (J2000, B1950, ECLIPTIC, GALACTIC */ int sys2, /* Output coordinate system (J2000, B1950, ECLIPTIC, G ALACTIC */ double eq1, /* Input equinox (default of sys1 if 0.0) */ double eq2, /* Output equinox (default of sys2 if 0.0) */ double *dtheta, /* Longitude or right ascension in degrees Input in sys1, returned in sys2 */ double *dphi, /* Latitude or declination in degrees Input in sys1, returned in sys2 */ double epoch); /* Besselian epoch in years */ void fk425e ( /* Convert B1950(FK4) to J2000(FK5) coordinates */ double *ra, /* Right ascension in degrees (B1950 in, J2000 out) */ double *dec, /* Declination in degrees (B1950 in, J2000 out) */ double epoch); /* Besselian epoch in years */ void fk524e ( /* Convert J2000(FK5) to B1950(FK4) coordinates */ double *ra, /* Right ascension in degrees (J2000 in, B1950 out) */ double *dec, /* Declination in degrees (J2000 in, B1950 out) */ double epoch); /* Besselian epoch in years */ int wcscsys( /* Return code for coordinate system in string */ char *coorsys); /* Coordinate system (B1950, J2000, etc) */ double wcsceq ( /* Set equinox from string (return 0.0 if not obvious) */ char *wcstring); /* Coordinate system (B1950, J2000, etc) */ void wcscstr ( /* Set coordinate system type string from system and equinox */ char *cstr, /* Coordinate system string (returned) */ int syswcs, /* Coordinate system code */ double equinox, /* Equinox of coordinate system */ double epoch); /* Epoch of coordinate system */ void d2v3 ( /* Convert RA and Dec in degrees and distance to vector */ double rra, /* Right ascension in degrees */ double rdec, /* Declination in degrees */ double r, /* Distance to object in same units as pos */ double pos[3]); /* x,y,z geocentric equatorial position of object (returned) */ void s2v3 ( /* Convert RA and Dec in radians and distance to vector */ double rra, /* Right ascension in radians */ double rdec, /* Declination in radians */ double r, /* Distance to object in same units as pos */ double pos[3]); /* x,y,z geocentric equatorial position of object (returned) */ void v2d3 ( /* Convert vector to RA and Dec in degrees and distance */ double pos[3], /* x,y,z geocentric equatorial position of object */ double *rra, /* Right ascension in degrees (returned) */ double *rdec, /* Declination in degrees (returned) */ double *r); /* Distance to object in same units as pos (returned) */ void v2s3 ( /* Convert vector to RA and Dec in radians and distance */ double pos[3], /* x,y,z geocentric equatorial position of object */ double *rra, /* Right ascension in radians (returned) */ double *rdec, /* Declination in radians (returned) */ double *r); /* Distance to object in same units as pos (returned) */ /* Distortion model subroutines in distort.c */ void distortinit ( /* Set distortion coefficients from FITS header */ struct WorldCoor *wcs, /* World coordinate system structure */ const char* hstring); /* FITS header */ void setdistcode ( /* Set WCS distortion code string from CTYPEi value */ struct WorldCoor *wcs, /* World coordinate system structure */ char *ctype); /* CTYPE value from FITS header */ char *getdistcode ( /* Return distortion code string for CTYPEi */ struct WorldCoor *wcs); /* World coordinate system structure */ int DelDistort ( /* Delete all distortion-related fields */ char *header, /* FITS header */ int verbose); /* If !=0, print keywords as deleted */ void pix2foc ( /* Convert pixel to focal plane coordinates */ struct WorldCoor *wcs, /* World coordinate system structure */ double x, /* Image pixel horizontal coordinate */ double y, /* Image pixel vertical coordinate */ double *u, /* Focal plane horizontal coordinate(returned) */ double *v); /* Focal plane vertical coordinate (returned) */ void foc2pix ( /* Convert focal plane to pixel coordinates */ struct WorldCoor *wcs, /* World coordinate system structure */ double u, /* Focal plane horizontal coordinate */ double v, /* Focal plane vertical coordinate */ double *x, /* Image pixel horizontal coordinate(returned) */ double *y); /* Image pixel vertical coordinate (returned) */ /* Other projection subroutines */ /* 8 projections using AIPS algorithms (worldpos.c) */ int worldpos ( /* Convert from pixel location to RA,Dec */ double xpix, /* x pixel number (RA or long without rotation) */ double ypix, /* y pixel number (Dec or lat without rotation) */ struct WorldCoor *wcs, /* WCS parameter structure */ double *xpos, /* x (RA) coordinate (deg) (returned) */ double *ypos); /* y (dec) coordinate (deg) (returned) */ int worldpix ( /* Convert from RA,Dec to pixel location */ double xpos, /* x (RA) coordinate (deg) */ double ypos, /* y (dec) coordinate (deg) */ struct WorldCoor *wcs, /* WCS parameter structure */ double *xpix, /* x pixel number (RA or long without rotation) */ double *ypix); /* y pixel number (dec or lat without rotation) */ /* Digital Sky Survey projection (dsspos.c) */ int dsspos ( /* Convert from pixel location to RA,Dec */ double xpix, /* x pixel number (RA or long without rotation) */ double ypix, /* y pixel number (Dec or lat without rotation) */ struct WorldCoor *wcs, /* WCS parameter structure */ double *xpos, /* x (RA) coordinate (deg) (returned) */ double *ypos); /* y (dec) coordinate (deg) (returned) */ int dsspix ( /* Convert from RA,Dec to pixel location */ double xpos, /* x (RA) coordinate (deg) */ double ypos, /* y (dec) coordinate (deg) */ struct WorldCoor *wcs, /* WCS parameter structure */ double *xpix, /* x pixel number (RA or long without rotation) */ double *ypix); /* y pixel number (dec or lat without rotation) */ /* SAO TDC TAN projection with higher order terms (platepos.c) */ int platepos ( /* Convert from pixel location to RA,Dec */ double xpix, /* x pixel number (RA or long without rotation) */ double ypix, /* y pixel number (Dec or lat without rotation) */ struct WorldCoor *wcs, /* WCS parameter structure */ double *xpos, /* x (RA) coordinate (deg) (returned) */ double *ypos); /* y (dec) coordinate (deg) (returned) */ int platepix ( /* Convert from RA,Dec to pixel location */ double xpos, /* x (RA) coordinate (deg) */ double ypos, /* y (dec) coordinate (deg) */ struct WorldCoor *wcs, /* WCS parameter structure */ double *xpix, /* x pixel number (RA or long without rotation) */ double *ypix); /* y pixel number (dec or lat without rotation) */ void SetFITSPlate ( /* Set FITS header plate fit coefficients from structure */ char *header, /* Image FITS header */ struct WorldCoor *wcs); /* WCS structure */ int SetPlate ( /* Set plate fit coefficients in structure from arguments */ struct WorldCoor *wcs, /* World coordinate system structure */ int ncoeff1, /* Number of coefficients for x */ int ncoeff2, /* Number of coefficients for y */ double *coeff); /* Plate fit coefficients */ int GetPlate ( /* Return plate fit coefficients from structure in arguments */ struct WorldCoor *wcs, /* World coordinate system structure */ int *ncoeff1, /* Number of coefficients for x */ int *ncoeff2, /* Number of coefficients for y) */ double *coeff); /* Plate fit coefficients */ /* IRAF TAN projection with higher order terms (tnxpos.c) */ int tnxinit ( /* initialize the gnomonic forward or inverse transform */ const char *header, /* FITS header */ struct WorldCoor *wcs); /* pointer to WCS structure */ int tnxpos ( /* forward transform (physical to world) gnomonic projection. */ double xpix, /* Image X coordinate */ double ypix, /* Image Y coordinate */ struct WorldCoor *wcs, /* pointer to WCS descriptor */ double *xpos, /* Right ascension (returned) */ double *ypos); /* Declination (returned) */ int tnxpix ( /* Inverse transform (world to physical) gnomonic projection */ double xpos, /* Right ascension */ double ypos, /* Declination */ struct WorldCoor *wcs, /* Pointer to WCS descriptor */ double *xpix, /* Image X coordinate (returned) */ double *ypix); /* Image Y coordinate (returned) */ /* IRAF ZPN projection with higher order terms (zpxpos.c) */ int zpxinit ( /* initialize the zenithal forward or inverse transform */ const char *header, /* FITS header */ struct WorldCoor *wcs); /* pointer to WCS structure */ int zpxpos ( /* forward transform (physical to world) */ double xpix, /* Image X coordinate */ double ypix, /* Image Y coordinate */ struct WorldCoor *wcs, /* pointer to WCS descriptor */ double *xpos, /* Right ascension (returned) */ double *ypos); /* Declination (returned) */ int zpxpix ( /* Inverse transform (world to physical) */ double xpos, /* Right ascension */ double ypos, /* Declination */ struct WorldCoor *wcs, /* Pointer to WCS descriptor */ double *xpix, /* Image X coordinate (returned) */ double *ypix); /* Image Y coordinate (returned) */ #else /* K&R prototypes */ /* WCS subroutines in wcs.c */ struct WorldCoor *wcsinit(); /* set up a WCS structure from a FITS image header */ struct WorldCoor *wcsninit(); /* set up a WCS structure from a FITS image header */ struct WorldCoor *wcsinitn(); /* set up a WCS structure from a FITS image header */ struct WorldCoor *wcsninitn(); /* set up a WCS structure from a FITS image header */ struct WorldCoor *wcsinitc(); /* set up a WCS structure from a FITS image header */ struct WorldCoor *wcsninitc(); /* set up a WCS structure from a FITS image header */ struct WorldCoor *wcsxinit(); /* set up a WCS structure from arguments */ struct WorldCoor *wcskinit(); /* set up a WCS structure from keyword values */ char *uppercase(); /* Convert string of any case to uppercase */ void wcsfree(void); /* Free a WCS structure and its contents */ int wcstype(); /* Set projection type from header CTYPEs */ void wcscdset(); /* Set scaling and rotation from CD matrix */ void wcsdeltset(); /* set scaling and rotation from CDELTs and CROTA2 */ void wcspcset(); /* set scaling and rotation from CDELTs and PC matrix */ int iswcs(); /* Return 1 if WCS structure is filled, else 0 */ int nowcs(); /* Return 0 if WCS structure is filled, else 1 */ void wcsshift(); /* Reset the center of a WCS structure */ void wcscent(); /* Print the image center and size in WCS units */ void wcssize(); /* Return RA and Dec of image center, size in RA and Dec */ void wcsfull(); /* Return RA and Dec of image center, size in degrees */ void wcsrange(); /* Return min and max RA and Dec of image in degrees */ double wcsdist(); /* Distance in degrees between two sky coordinates */ double wcsdist1(); /* Compute angular distance between 2 sky positions */ double wcsdiff(); /* Distance in degrees between two sky coordinates */ void wcscominit(); /* Initialize catalog search command set by -wcscom */ void wcscom(); /* Execute catalog search command set by -wcscom */ char *getradecsys(); /* Return current value of coordinate system */ void wcsoutinit(); /* Initialize WCS output coordinate system for use by pix2wcs */ char *getwcsout(); /* Return current value of WCS output coordinate system */ void wcsininit(); /* Initialize WCS input coordinate system for use by wcs2pix */ char *getwcsin(); /* Return current value of WCS input coordinate system */ int setwcsdeg(); /* Set WCS output in degrees (1) or hh:mm:ss dd:mm:ss (0) */ int wcsndec(); /* Set or get number of output decimal places */ int wcsreset(); /* Change WCS using arguments */ void wcseqset(); /* Change equinox of reference pixel coordinates in WCS */ void wcscstr(); /* Return system string from system code, equinox, epoch */ void setwcslin(); /* Set output string mode for LINEAR coordinates */ int pix2wcst(); /* Convert pixel coordinates to World Coordinate string */ void pix2wcs(); /* Convert pixel coordinates to World Coordinates */ void wcsc2pix(); /* Convert World Coordinates to pixel coordinates */ void wcs2pix(); /* Convert World Coordinates to pixel coordinates */ void setdefwcs(); /* Call to use AIPS classic WCS (also not PLT/TNX/ZPX */ int getdefwcs(); /* Call to get flag for AIPS classic WCS */ int wcszin(); /* Set coordinate in third dimension (face) */ int wcszout(); /* Return coordinate in third dimension */ void wcserr(); /* Print WCS error message to stderr */ void setwcserr(); /* Set WCS error message for later printing */ void savewcscoor(); /* Save output coordinate system */ char *getwcscoor(); /* Return output coordinate system */ void savewcscom(); /* Save WCS shell command */ char *getwcscom(); /* Return WCS shell command */ void setwcscom(); /* Set WCS shell commands from stored values */ void freewcscom(); /* Free memory used to store WCS shell commands */ void setwcsfile(); /* Set filename for WCS error message */ int cpwcs(); /* Copy WCS keywords with no suffix to ones with suffix */ /* Coordinate conversion subroutines in wcscon.c */ void wcscon(); /* Convert between coordinate systems and equinoxes */ void wcsconp(); /* Convert between coordinate systems and equinoxes */ void wcsconv(); /* Convert between coordinate systems and equinoxes */ void fk425e(); /* Convert B1950(FK4) to J2000(FK5) coordinates */ void fk524e(); /* Convert J2000(FK5) to B1950(FK4) coordinates */ int wcscsys(); /* Set coordinate system from string */ double wcsceq(); /* Set equinox from string (return 0.0 if not obvious) */ void d2v3(); /* Convert RA and Dec in degrees and distance to vector */ void s2v3(); /* Convert RA and Dec in radians and distance to vector */ void v2d3(); /* Convert vector to RA and Dec in degrees and distance */ void v2s3(); /* Convert vector to RA and Dec in radians and distance */ /* Distortion model subroutines in distort.c */ void distortinit(); /* Set distortion coefficients from FITS header */ void setdistcode(); /* Set WCS distortion code string from CTYPEi value */ char *getdistcode(); /* Return distortion code string for CTYPEi */ int DelDistort(); /* Delete all distortion-related fields */ void pix2foc(); /* pixel coordinates -> focal plane coordinates */ void foc2pix(); /* focal plane coordinates -> pixel coordinates */ /* Other projection subroutines */ /* 8 projections using AIPS algorithms (worldpos.c) */ extern int worldpos(); /* Convert from pixel location to RA,Dec */ extern int worldpix(); /* Convert from RA,Dec to pixel location */ /* Digital Sky Survey projection (dsspos.c) */ extern int dsspos(); /* Convert from pixel location to RA,Dec */ extern int dsspix(); /* Convert from RA,Dec to pixel location */ /* SAO TDC TAN projection with higher order terms (platepos.c) */ extern int platepos(); /* Convert from pixel location to RA,Dec */ extern int platepix(); /* Convert from RA,Dec to pixel location */ extern void SetFITSPlate(); /* Set FITS header plate fit coefficients from structure */ extern int SetPlate(); /* Set plate fit coefficients in structure from arguments */ extern int GetPlate(); /* Return plate fit coefficients from structure in arguments */ /* IRAF TAN projection with higher order terms (tnxpos.c) */ extern int tnxinit(); /* initialize the gnomonic forward or inverse transform */ extern int tnxpos(); /* forward transform (physical to world) gnomonic projection. */ extern int tnxpix(); /* Inverse transform (world to physical) gnomonic projection */ /* IRAF ZPN projection with higher order terms (zpxpos.c) */ extern int zpxinit(); /* initialize the gnomonic forward or inverse transform */ extern int zpxpos(); /* forward transform (physical to world) gnomonic projection. */ extern int zpxpix(); /* Inverse transform (world to physical) gnomonic projection */ #endif /* __STDC__ */ #ifdef __cplusplus } #endif #endif /* _wcs_h_ */ /* Oct 26 1994 New file * Dec 21 1994 Add rotation matrix * Dec 22 1994 Add flag for coordinate reversal * Mar 6 1995 Add parameters for Digital Sky Survey plate fit * Jun 8 1995 Add parameters for coordinate system change * Jun 21 1995 Add parameter for plate scale * Jul 6 1995 Add parameter to note whether WCS is set * Aug 8 1995 Add parameter to note whether to print coordinate system * Oct 16 1995 Add parameters to save image dimensions and center coordinates * Feb 15 1996 Add coordinate conversion functions * Feb 20 1996 Add flag for tab tables * Apr 26 1996 Add epoch of positions (actual date of image) * Jul 5 1996 Add subroutine declarations * Jul 19 1996 Add WCSFULL declaration * Aug 5 1996 Add WCSNINIT to initialize WCS for non-terminated header * Oct 31 1996 Add DCnn inverse rotation matrix * Nov 1 1996 Add NDEC number of decimal places in output * * May 22 1997 Change range of pcode from 1-8 to -1-8 for linear transform * Sep 12 1997 Add chip rotation MROT, XMPIX, YMPIX * * Jan 7 1998 Add INSTRUME and DETECTOR for HST metric correction * Jan 16 1998 Add Mark Calabretta's WCSLIB data structures * Jan 16 1998 Add LONGPOLE, LATPOLE, and PROJP constants for Calabretta * Jan 22 1998 Add ctype[], crpix[], crval[], and cdelt[] for Calabretta * Jan 23 1998 Change wcsset() to wcsxinit() and pcode to prjcode * Jan 23 1998 Define projection type flags * Jan 26 1998 Remove chip rotation * Jan 26 1998 Add chip correction polynomial * Feb 3 1998 Add number of coefficients for residual fit * Feb 5 1998 Make cd and dc matrices vectors, not individual elements * Feb 19 1998 Add projection names * Feb 23 1998 Add TNX projection from NOAO * Mar 3 1998 Add NOAO plate fit and residual fit * Mar 12 1998 Add variables for TNX correction surface * Mar 23 1998 Add PLT plate fit polynomial projection; reassign DSS * Mar 23 1998 Drop plate_fit flag from structure * Mar 25 1998 Add npcoeff to wcs structure for new plate fit WCS * Apr 7 1998 Change amd_i_coeff to i_coeff * Apr 8 1998 Add wcseqset() and wcsreset() subroutine declarations * Apr 10 1998 Rearrange order of nonstandard WCS types * Apr 13 1998 Add setdefwcs() subroutine declaration * Apr 14 1998 Add coordinate systems and wcscoor() * Apr 24 1998 Add units * Apr 28 1998 Change coordinate system flags to WCS_* * Apr 28 1998 Change projection flags to WCS_* * Apr 28 1998 Add wcsc2pix() * May 7 1998 Add C++ declarations * May 13 1998 Add eqin and eqout for conversions to and from equinoxes * May 14 1998 Add declarations for coordinate conversion subroutines * May 27 1998 Add blsearch() * May 27 1998 Change linear projection back to WCS_LIN from WCS_LPR * May 27 1998 Move hget.c and hput.c C++ declarations to fitshead.h * May 27 1998 Include fitshead.h * May 29 1998 Add wcskinit() * Jun 1 1998 Add wcserr() * Jun 11 1998 Add initialization support subroutines * Jun 18 1998 Add wcspcset() * Jun 25 1998 Add wcsndec() * Jul 6 1998 Add wcszin() and wcszout() to use third dimension of images * Jul 7 1998 Change setdegout() to setwcsdeg(); setlinmode() to setwcslin() * Jul 17 1998 Add savewcscoor(), getwcscoor(), savewcscom(), and getwcscom() * Aug 14 1998 Add freewcscom(), setwcscom(), and multiple WCS commands * Sep 3 1998 Add pa_north, pa_east, imrot and imflip to wcs structure * Sep 14 1998 Add latbase for AXAF North Polar angle (NPOL not LAT-) * Sep 16 1998 Make WCS_system start at 1; add NPOLE * Sep 17 1998 Add wcscstr() * Sep 21 1998 Add wcsconp() to convert proper motions, too. * Dec 2 1998 Add WCS type for planet surface * Jan 20 1999 Add declaration of wcsfree() * Jun 16 1999 Add declaration of wcsrange() * Oct 21 1999 Add declaration of setwcsfile() * * Jan 28 2000 Add flags for choice of WCS projection subroutines * Jun 26 2000 Add XY coordinate system * Nov 2 2000 Add wcsconv() to convert coordinates when parallax or rv known * * Jan 17 2001 Add idpix and ndpix for trim section, ltm for readout rotation * Jan 31 2001 Add wcsinitn(), wcsninitn(), wcsinitc(), and wcsninitc() * Feb 20 2001 Add wcs->wcs to main data structure * Mar 20 2001 Close unclosed comment in wcsconv() argument list * * Apr 3 2002 Add SZP and second GLS/SFL projection * Apr 9 2002 Add wcs->wcsdep for pointer to WCS depending on this WCS * Apr 26 2002 Add wcs->wcsname and wcs->wcschar to identify WCS structure * May 9 2002 Add wcs->radvel and wcs->zvel for radial velocity in km/sec * * Apr 1 2003 Add wcs->distort Distort structure for distortion correction * Apr 1 2003 Add foc2pix() and pix2foc() subroutines for distortion correction * May 1 2003 Add missing semicolons after C++ declarations of previous two functions * Oct 1 2003 Rename wcs->naxes to wcs->naxis to match WCSLIB 3.2 * Nov 3 2003 Add distinit(), setdistcode(), and getdistcode() to distort.c * Dec 3 2003 Add back wcs->naxes for backward compatibility * * Aug 30 2004 Add DelDistort() * * Nov 1 2005 Add WCS_ICRS * * Jan 5 2006 Add secrad() * Apr 21 2006 Increase maximum number of axes from 4 to 8 * Apr 24 2006 Increase maximum number of axes to 9 * Nov 29 2006 Drop semicolon at end of C++ ifdef * Dec 21 2006 Add cpwcs() * * Jan 4 2007 Drop extra declaration of wcscstr() * Jan 4 2007 Fix declarations so ANSI prototypes are not just for C++ * Jan 9 2007 Add fk425e() and fk524e() subroutines * Jan 9 2007 Add worldpos.c, dsspos.c, platepos.c, and tnxpos.c subroutines * Jan 10 2007 Add ANSI prototypes for all subroutines * Feb 1 2007 Add wcs.wcslog for log wavelength * Jul 25 2007 Add v2s3(), s2v3(), d2v3(), v2d3() for coordinate-vector conversion * * Mar 31 2010 Add wcsdist1(), an alternate method * Apr 07 2010 Add NWCSTYPE to keep it aligned with actual number of WCS types * * Mar 11 2011 Add NOAO ZPX projection parameters and subroutines (Frank Valdes) * Mar 14 2011 Add SCAMP polynomial projection coefficients * Sep 1 2011 Add TPV TAN projectioin with SCAT PV terms * Sep 9 2011 Fix comment on TPV declaration * * Feb 1 2013 Add uppercase() from wcsinit() * Feb 25 2013 Pass const string to uppercase() */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/wcs.i0000644000175000017500000002260013047255533020425 0ustar mattymatty00000000000000// Wrapping of WCSTools wcs.c // // Not wrapping the functions that return WCS coords as string because can convert using decimal2hms() etc. in astCoords %feature("autodoc", "0"); %module (package="PyWCSTools") wcs %include "carrays.i" %include "typemaps.i" %array_functions(double, doubleArray) /* %feature("autodoc", "1") */ %{ #include "wcs.h" %} /* WORKING */ struct WorldCoor *wcsinit(char *hstring); /* set up a WCS structure from a FITS image header */ struct WorldCoor *wcsxinit(double cra, double cdec, double secpix, int xrpix, int yrpix, int nxpix, int nypix, double rotate, int equinox, double epoch, char *proj); /* set up a WCS structure from arguments */ struct WorldCoor *wcskinit(int nxpix, int nypix, char *ctype1, char *ctype2, double crpix1, double crpix2, double crval1, double crval2, double *cd, double cdelt1, double cdelt2, double crota, double equinox, double epoch); /* set up a WCS structure from keyword values */ int iswcs(struct WorldCoor *wcs); /* Return 1 if WCS structure is filled, else 0 */ int nowcs(struct WorldCoor *wcs); /* Return 0 if WCS structure is filled, else 1 */ %apply double *OUTPUT { double *xpix, double *ypix, int *offscl}; void wcs2pix(struct WorldCoor *wcs, double xpos, double ypos, double *xpix, double *ypix, int *offscl); /* Convert World Coordinates to pixel coordinates */ %apply double *OUTPUT { double *xpos, double *ypos}; void pix2wcs(struct WorldCoor *wcs, double xpix, double ypix, double *xpos, double *ypos); /* Convert pixel coordinates to World Coordinates */ void wcscent(struct WorldCoor *wcs); /* Print the image center and size in WCS units */ char *getradecsys(struct WorldCoor *wcs); /* Return current value of coordinate system */ void wcsoutinit(struct WorldCoor *wcs, char *coorsys); /* Initialize WCS output coordinate system for use by pix2wcs */ void wcsininit(struct WorldCoor *wcs, char *coorsys); /* Initialize WCS input coordinate system for use by wcs2pix */ char *getwcsout(struct WorldCoor *wcs); /* Return current value of WCS output coordinate system */ char *getwcsin(struct WorldCoor *wcs); /* Return current value of WCS input coordinate system */ %apply double *OUTPUT {double *cra, double *cdec, double *dra, double *ddec}; void wcssize(struct WorldCoor *wcs, double *cra, double *cdec, double *dra, double *ddec); /* Return RA and Dec of image center, size in RA and Dec */ %apply double *OUTPUT {double *width, double *height}; void wcsfull(struct WorldCoor *wcs, double *cra, double *cdec, double *width, double *height); /* Return RA and Dec of image center, size in degrees */ struct WorldCoor { double xref; /* X reference coordinate value (deg) */ double yref; /* Y reference coordinate value (deg) */ double xrefpix; /* X reference pixel */ double yrefpix; /* Y reference pixel */ double xinc; /* X coordinate increment (deg) */ double yinc; /* Y coordinate increment (deg) */ double rot; /* rotation around axis (deg) (N through E) */ double cd[4]; /* rotation matrix */ double dc[4]; /* inverse rotation matrix */ double equinox; /* Equinox of coordinates default to 1950.0 */ double epoch; /* Epoch of coordinates default to equinox */ double nxpix; /* Number of pixels in X-dimension of image */ double nypix; /* Number of pixels in Y-dimension of image */ double plate_ra; /* Right ascension of plate center */ double plate_dec; /* Declination of plate center */ double plate_scale; /* Plate scale in arcsec/mm */ double x_pixel_offset; /* X pixel offset of image lower right */ double y_pixel_offset; /* Y pixel offset of image lower right */ double x_pixel_size; /* X pixel_size */ double y_pixel_size; /* Y pixel_size */ double ppo_coeff[6]; /* pixel to plate coefficients for DSS */ double x_coeff[20]; /* X coefficients for plate model */ double y_coeff[20]; /* Y coefficients for plate model */ double xpix; /* X (RA) coordinate (pixels) */ double ypix; /* Y (dec) coordinate (pixels) */ double zpix; /* Z (face) coordinate (pixels) */ double xpos; /* X (RA) coordinate (deg) */ double ypos; /* Y (dec) coordinate (deg) */ double crpix[9]; /* Values of CRPIXn keywords */ double crval[9]; /* Values of CRVALn keywords */ double cdelt[9]; /* Values of CDELTn keywords */ double pc[81]; /* Values of PCiiijjj keywords */ double projp[10]; /* Constants for various projections */ int pvfail; /* If non-zero, significant inaccuracy likely to occur in projection */ double projppv[2*MAXPV]; /* SCAMP constants for the PV coordinates */ struct poly *inv_x; /* SCAMP projection correction polynom in x */ struct poly *inv_y; /* SCAMP projection correction polynom in y */ double longpole; /* Longitude of North Pole in degrees */ double latpole; /* Latitude of North Pole in degrees */ double rodeg; /* Radius of the projection generating sphere */ double imrot; /* Rotation angle of north pole */ double pa_north; /* Position angle of north (0=horizontal) */ double pa_east; /* Position angle of east (0=horizontal) */ double radvel; /* Radial velocity (km/sec away from observer)*/ double zvel; /* Radial velocity (v/c away from observer)*/ double zpzd; /* Colat of FIP (degs) */ double zpr; /* Radius of FIP (degs) */ int imflip; /* If not 0, image is reflected around axis */ int prjcode; /* projection code (-1-32) */ int latbase; /* Latitude base 90 (NPA), 0 (LAT), -90 (SPA) */ int ncoeff1; /* Number of x-axis plate fit coefficients */ int ncoeff2; /* Number of y-axis plate fit coefficients */ int zpnp; /* ZP polynomial order (0-9) */ int changesys; /* 1 for FK4->FK5, 2 for FK5->FK4 */ /* 3 for FK4->galactic, 4 for FK5->galactic */ int printsys; /* 1 to print coordinate system, else 0 */ int ndec; /* Number of decimal places in PIX2WCST */ int degout; /* 1 to always print degrees in PIX2WCST */ int tabsys; /* 1 to put tab between RA & Dec, else 0 */ int rotmat; /* 0 if CDELT, CROTA; 1 if CD */ int coorflip; /* 0 if x=RA, y=Dec; 1 if x=Dec, y=RA */ int offscl; /* 0 if OK, 1 if offscale */ int wcson; /* 1 if WCS is set, else 0 */ int naxis; /* Number of axes in image (for WCSLIB 3.0) */ int naxes; /* Number of axes in image */ int wcsproj; /* WCS_OLD: AIPS worldpos() and worldpix() WCS_NEW: Mark Calabretta's WCSLIB subroutines WCS_BEST: WCSLIB for all but CAR,COE,NCP WCS_ALT: AIPS for all but CAR,COE,NCP */ int linmode; /* 0=system only, 1=units, 2=system+units */ int detector; /* Instrument detector number */ char instrument[32]; /* Instrument name */ char ctype[9][9]; /* Values of CTYPEn keywords */ char c1type[9]; /* 1st coordinate type code: RA--, GLON, ELON */ char c2type[9]; /* 2nd coordinate type code: DEC-, GLAT, ELAT */ char ptype[9]; /* projection type code: SIN, TAN, ARC, NCP, GLS, MER, AIT, etc */ char units[9][32]; /* Units if LINEAR */ char radecsys[32]; /* Reference frame: FK4, FK4-NO-E, FK5, GAPPT*/ char radecout[32]; /* Output reference frame: FK4,FK5,GAL,ECL */ char radecin[32]; /* Input reference frame: FK4,FK5,GAL,ECL */ double eqin; /* Input equinox (match sysin if 0.0) */ double eqout; /* Output equinox (match sysout if 0.0) */ int sysin; /* Input coordinate system code */ int syswcs; /* WCS coordinate system code */ int sysout; /* Output coordinate system code */ /* WCS_B1950, WCS_J2000, WCS_ICRS, WCS_GALACTIC, * WCS_ECLIPTIC, WCS_LINEAR, WCS_ALTAZ */ char center[32]; /* Center coordinates (with frame) */ struct wcsprm wcsl; /* WCSLIB main projection parameters */ struct linprm lin; /* WCSLIB image/pixel conversion parameters */ struct celprm cel; /* WCSLIB projection type */ struct prjprm prj; /* WCSLIB projection parameters */ struct IRAFsurface *lngcor; /* RA/longitude correction structure */ struct IRAFsurface *latcor; /* Dec/latitude correction structure */ int distcode; /* Distortion code 0=none 1=SIRTF */ struct Distort distort; /* SIRTF distortion coefficients */ char *command_format[10]; /* WCS command formats */ /* where %s is replaced by WCS coordinates */ /* where %f is replaced by the image filename */ /* where %x is replaced by image coordinates */ double ltm[4]; /* Image rotation matrix */ double ltv[2]; /* Image offset */ int idpix[2]; /* First pixel to use in image (x, y) */ int ndpix[2]; /* Number of pixels to use in image (x, y) */ struct WorldCoor *wcs; /* WCS upon which this WCS depends */ struct WorldCoor *wcsdep; /* WCS depending on this WCS */ char *wcsname; /* WCS name (defaults to NULL pointer) */ char wcschar; /* WCS character (A-Z, null, space) */ int logwcs; /* 1 if DC-FLAG is set for log wavelength */ }; astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/fileutil.c0000664000175000017500000005223313047255533021447 0ustar mattymatty00000000000000/*** File libwcs/fileutil.c *** August 28, 2014 *** By Jessica Mink, jmink@cfa.harvard.edu *** Harvard-Smithsonian Center for Astrophysics *** Copyright (C) 1999-2014 *** Smithsonian Astrophysical Observatory, Cambridge, MA, USA This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Correspondence concerning WCSTools should be addressed as follows: Internet email: jmink@cfa.harvard.edu Postal address: Jessica Mink Smithsonian Astrophysical Observatory 60 Garden St. Cambridge, MA 02138 USA * Module: fileutil.c (ASCII file utilities) * Purpose: Find out things about ASCII files * Subroutine: getfilelines (filename) * Return number of lines in an ASCII file * Subroutine: getfilebuff (filename) * Return entire file contents in a character string * Subroutine: getfilesize (filename) * Return size of a binary or ASCII file * Subroutine: isimlist (filename) * Return 1 if file is list of FITS or IRAF image files, else 0 * Subroutine: isimlistd (filename, rootdir) * Return 1 if file is list of FITS or IRAF image files, else 0 * Subroutine: isfilelist (filename, rootdir) * Return 1 if file is list of readable files, else 0 * Subroutine: isfile (filename) * Return 1 if file is a readable file, else 0 * Subroutine: first_token (diskfile, ncmax, token) * Return the first token from the next line of an ASCII file * Subroutine: next_line (diskfile, ncmax, line) * Read the next line of an ASCII file and return its length * Subroutine: stc2s (spchar, string) * Replace character in string with space * Subroutine: sts2c (spchar, string) * Replace spaces in string with character * Subroutine: istiff (filename) * Return 1 if file is a readable TIFF graphics file, else 0 * Subroutine: isjpeg (filename) * Return 1 if file is a readable JPEG graphics file, else 0 * int setoken (tokens, string, cwhite) * Tokenize a string for easy decoding * int nextoken (tokens, token, maxchars) * Get next token from tokenized string * int getoken (tokens, itok, token, maxchars) * Get specified token from tokenized string */ #include #ifndef VMS #include #endif #include #include #include #include #include #include "fitsfile.h" #include #include /* GETFILELINES -- return number of lines in one file */ int getfilelines (filename) char *filename; /* Name of file for which to find number of lines */ { char *buffer, *bufline; int nlines = 0; char newline = 10; /* Read file */ buffer = getfilebuff (filename); /* Count lines in file */ if (buffer != NULL) { bufline = buffer; nlines = 0; while ((bufline = strchr (bufline, newline)) != NULL) { bufline = bufline + 1; nlines++; } free (buffer); return (nlines); } else { return (0); } } /* GETFILEBUFF -- return entire file contents in one character string */ char * getfilebuff (filename) char *filename; /* Name of file for which to find number of lines */ { FILE *diskfile; int lfile, nr, lbuff, ipt, ibuff; char *buffer, *newbuff, *nextbuff; /* Treat stdin differently */ if (!strcmp (filename, "stdin")) { lbuff = 5000; lfile = lbuff; buffer = NULL; ipt = 0; for (ibuff = 0; ibuff < 10; ibuff++) { if ((newbuff = realloc (buffer, lfile+1)) != NULL) { buffer = newbuff; nextbuff = buffer + ipt; nr = fread (nextbuff, 1, lbuff, stdin); if (nr == lbuff) break; else { ipt = ipt + lbuff; lfile = lfile + lbuff; } } else { fprintf (stderr,"GETFILEBUFF: No room for %d-byte buffer\n", lfile); break; } } return (buffer); } /* Open file */ if ((diskfile = fopen (filename, "rb")) == NULL) return (NULL); /* Find length of file */ if (fseek (diskfile, 0, 2) == 0) lfile = ftell (diskfile); else lfile = 0; if (lfile < 1) { fprintf (stderr,"GETFILEBUFF: File %s is empty\n", filename); fclose (diskfile); return (NULL); } /* Allocate buffer to hold entire file and read it */ if ((buffer = calloc (1, lfile+1)) != NULL) { fseek (diskfile, 0, 0); nr = fread (buffer, 1, lfile, diskfile); if (nr < lfile) { fprintf (stderr,"GETFILEBUFF: File %s: read %d / %d bytes\n", filename, nr, lfile); free (buffer); fclose (diskfile); return (NULL); } buffer[lfile] = (char) 0; fclose (diskfile); return (buffer); } else { fprintf (stderr,"GETFILEBUFF: File %s: no room for %d-byte buffer\n", filename, lfile); fclose (diskfile); return (NULL); } } /* GETFILESIZE -- return size of one file in bytes */ int getfilesize (filename) char *filename; /* Name of file for which to find size */ { struct stat statbuff; if (stat (filename, &statbuff)) return (0); else return ((int) statbuff.st_size); } int getfilesize0 (filename) char *filename; /* Name of file for which to find size */ { FILE *diskfile; long filesize; /* Open file */ if ((diskfile = fopen (filename, "rb")) == NULL) return (-1); /* Move to end of the file */ if (fseek (diskfile, 0, 2) == 0) /* Position is the size of the file */ filesize = ftell (diskfile); else filesize = -1; fclose (diskfile); return ((int) filesize); } /* ISIMLIST -- Return 1 if list of FITS or IRAF files, else 0 */ int isimlist (filename) char *filename; /* Name of possible list file */ { FILE *diskfile; char token[256]; int ncmax = 254; if ((diskfile = fopen (filename, "r")) == NULL) return (0); else { first_token (diskfile, ncmax, token); fclose (diskfile); if (isfits (token) | isiraf (token)) return (1); else return (0); } } /* ISIMLISTD -- Return 1 if list of FITS or IRAF files, else 0 */ int isimlistd (filename, rootdir) char *filename; /* Name of possible list file */ char *rootdir; /* Name of root directory for files in list */ { FILE *diskfile; char token[256]; char filepath[256]; int ncmax = 254; if ((diskfile = fopen (filename, "r")) == NULL) return (0); else { first_token (diskfile, ncmax, token); fclose (diskfile); if (rootdir != NULL) { strcpy (filepath, rootdir); strcat (filepath, "/"); strcat (filepath, token); } else strcpy (filepath, token); if (isfits (filepath) | isiraf (filepath)) return (1); else return (0); } } /* ISFILELIST -- Return 1 if list of readable files, else 0 */ int isfilelist (filename, rootdir) char *filename; /* Name of possible list file */ char *rootdir; /* Name of root directory for files in list */ { FILE *diskfile; char token[256]; char filepath[256]; int ncmax = 254; if ((diskfile = fopen (filename, "r")) == NULL) return (0); else { first_token (diskfile, ncmax, token); fclose (diskfile); if (rootdir != NULL) { strcpy (filepath, rootdir); strcat (filepath, "/"); strcat (filepath, token); } else strcpy (filepath, token); if (isfile (filepath)) return (1); else return (0); } } /* ISFILE -- Return 1 if file is a readable file, else 0 */ int isfile (filename) char *filename; /* Name of file to check */ { struct stat statbuff; if (!strcasecmp (filename, "stdin")) return (1); else if (access (filename, R_OK)) return (0); else if (stat (filename, &statbuff)) return (0); else { if (S_ISDIR(statbuff.st_mode) && S_IFDIR) return (2); else return (1); } } /* NEXT_LINE -- Read the next line of an ASCII file, returning length */ /* Lines beginning with # are ignored*/ int next_line (diskfile, ncmax, line) FILE *diskfile; /* File descriptor for ASCII file */ int ncmax; /* Maximum number of characters returned */ char *line; /* Next line (returned) */ { char *lastchar; /* If line can be read, add null at the end of the first token */ if (fgets (line, ncmax, diskfile) != NULL) { while (line[0] == '#') { (void) fgets (line, ncmax, diskfile); } /* If only character is a control character, return a NULL string */ if ((strlen(line)==1) && (line[0]<32)){ line[0] = (char)0; return (1); } lastchar = line + strlen (line) - 1; /* Remove trailing spaces or control characters */ while (*lastchar <= 32) *lastchar-- = 0; return (strlen (line)); } else return (0); } /* FIRST_TOKEN -- Return first token from the next line of an ASCII file */ /* Lines beginning with # are ignored */ int first_token (diskfile, ncmax, token) FILE *diskfile; /* File descriptor for ASCII file */ int ncmax; /* Maximum number of characters returned */ char *token; /* First token on next line (returned) */ { char *lastchar, *lspace; /* If line can be read, add null at the end of the first token */ if (fgets (token, ncmax, diskfile) != NULL) { while (token[0] == '#') { (void) fgets (token, ncmax, diskfile); } /* If only character is a control character, return a NULL */ if ((strlen(token)==1) && (token[0]<32)){ token[0]=0; return (1); } lastchar = token + strlen (token) - 1; /* Remove trailing spaces or control characters */ while (*lastchar <= 32) *lastchar-- = 0; if ((lspace = strchr (token, ' ')) != NULL) { *lspace = (char) 0; } return (1); } else return (0); } /* Replace character in string with space */ int stc2s (spchar, string) char *spchar; /* Character to replace with spaces */ char *string; { int i, lstr, n; lstr = strlen (string); n = 0; for (i = 0; i < lstr; i++) { if (string[i] == spchar[0]) { n++; string[i] = ' '; } } return (n); } /* Replace spaces in string with character */ int sts2c (spchar, string) char *spchar; /* Character with which to replace spaces */ char *string; { int i, lstr, n; lstr = strlen (string); n = 0; for (i = 0; i < lstr; i++) { if (string[i] == ' ') { n++; string[i] = spchar[0]; } } return (n); } /* ISTIFF -- Return 1 if TIFF file, else 0 */ int istiff (filename) char *filename; /* Name of file to check */ { int diskfile; char keyword[16]; int nbr; /* First check to see if this is an assignment */ if (strchr (filename, '=')) return (0); /* Check file extension */ if (strsrch (filename, ".tif") || strsrch (filename, ".tiff") || strsrch (filename, ".TIFF") || strsrch (filename, ".TIF")) return (1); /* If no TIFF file suffix, try opening the file */ else { if ((diskfile = open (filename, O_RDONLY)) < 0) return (0); else { nbr = read (diskfile, keyword, 4); close (diskfile); if (nbr < 4) return (0); else if (!strncmp (keyword, "II", 2)) return (1); else if (!strncmp (keyword, "MM", 2)) return (1); else return (0); } } } /* ISJPEG -- Return 1 if JPEG file, else 0 */ int isjpeg (filename) char *filename; /* Name of file to check */ { int diskfile; char keyword[16]; int nbr; /* First check to see if this is an assignment */ if (strchr (filename, '=')) return (0); /* Check file extension */ if (strsrch (filename, ".jpg") || strsrch (filename, ".jpeg") || strsrch (filename, ".JPEG") || strsrch (filename, ".jfif") || strsrch (filename, ".jfi") || strsrch (filename, ".JFIF") || strsrch (filename, ".JFI") || strsrch (filename, ".JPG")) return (1); /* If no JPEG file suffix, try opening the file */ else { if ((diskfile = open (filename, O_RDONLY)) < 0) return (0); else { nbr = read (diskfile, keyword, 2); close (diskfile); if (nbr < 4) return (0); else if (keyword[0] == (char) 0xFF && keyword[1] == (char) 0xD8) return (1); else return (0); } } } /* ISGIF -- Return 1 if GIF file, else 0 */ int isgif (filename) char *filename; /* Name of file to check */ { int diskfile; char keyword[16]; int nbr; /* First check to see if this is an assignment */ if (strchr (filename, '=')) return (0); /* Check file extension */ if (strsrch (filename, ".gif") || strsrch (filename, ".GIF")) return (1); /* If no GIF file suffix, try opening the file */ else { if ((diskfile = open (filename, O_RDONLY)) < 0) return (0); else { nbr = read (diskfile, keyword, 6); close (diskfile); if (nbr < 4) return (0); else if (!strncmp (keyword, "GIF", 3)) return (1); else return (0); } } } static int maxtokens = MAXTOKENS; /* Set maximum number of tokens from wcscat.h*/ /* -- SETOKEN -- tokenize a string for easy decoding */ int setoken (tokens, string, cwhite) struct Tokens *tokens; /* Token structure returned */ char *string; /* character string to tokenize */ char *cwhite; /* additional whitespace characters * if = tab, disallow spaces and commas */ { char squote, dquote, jch, newline; char *iq, *stri, *wtype, *str0, *inew; int i,j,naddw, ltok; newline = (char) 10; squote = (char) 39; dquote = (char) 34; if (string == NULL) return (0); /* Line is terminated by newline or NULL */ inew = strchr (string, newline); if (inew != NULL) tokens->lline = inew - string - 1; else tokens->lline = strlen (string); /* Save current line in structure */ tokens->line = string; /* Add extra whitespace characters */ if (cwhite == NULL) naddw = 0; else naddw = strlen (cwhite); /* if character is tab, allow only tabs and nulls as separators */ if (naddw > 0 && !strncmp (cwhite, "tab", 3)) { tokens->white[0] = (char) 9; /* Tab */ tokens->white[1] = (char) 0; /* NULL (end of string) */ tokens->nwhite = 2; } /* if character is bar, allow only bars and nulls as separators */ else if (naddw > 0 && !strncmp (cwhite, "bar", 3)) { tokens->white[0] = '|'; /* Bar */ tokens->white[1] = (char) 0; /* NULL (end of string) */ tokens->nwhite = 2; } /* otherwise, allow spaces, tabs, commas, nulls, and cwhite */ else { tokens->nwhite = 4 + naddw;; tokens->white[0] = ' '; /* Space */ tokens->white[1] = (char) 9; /* Tab */ tokens->white[2] = ','; /* Comma */ tokens->white[3] = (char) 124; /* Vertical bar */ tokens->white[4] = (char) 0; /* Null (end of string) */ if (tokens->nwhite > 20) tokens->nwhite = 20; if (naddw > 0) { i = 0; for (j = 4; j < tokens->nwhite; j++) { tokens->white[j] = cwhite[i]; i++; } } } tokens->white[tokens->nwhite] = (char) 0; tokens->ntok = 0; tokens->itok = 0; iq = string - 1; for (i = 0; i < maxtokens; i++) { tokens->tok1[i] = NULL; tokens->ltok[i] = 0; } /* Process string one character at a time */ stri = string; str0 = string; while (stri < string+tokens->lline) { /* Keep stuff between quotes in one token */ if (stri <= iq) continue; jch = *stri; /* Handle quoted strings */ if (jch == squote) iq = strchr (stri+1, squote); else if (jch == dquote) iq = strchr (stri+1, dquote); else iq = stri; if (iq > stri) { tokens->ntok = tokens->ntok + 1; if (tokens->ntok > maxtokens) return (maxtokens); tokens->tok1[tokens->ntok] = stri + 1; tokens->ltok[tokens->ntok] = (iq - stri) - 1; stri = iq + 1; str0 = iq + 1; continue; } /* Search for unquoted tokens */ wtype = strchr (tokens->white, jch); /* If this is one of the additional whitespace characters, * pass as a separate token */ if (wtype > tokens->white + 3) { /* Terminate token before whitespace */ if (stri > str0) { tokens->ntok = tokens->ntok + 1; if (tokens->ntok > maxtokens) return (maxtokens); tokens->tok1[tokens->ntok] = str0; tokens->ltok[tokens->ntok] = stri - str0; } /* Make whitespace character next token; start new one */ tokens->ntok = tokens->ntok + 1; if (tokens->ntok > maxtokens) return (maxtokens); tokens->tok1[tokens->ntok] = stri; tokens->ltok[tokens->ntok] = 1; stri++; str0 = stri; } /* Pass previous token if regular whitespace or NULL */ else if (wtype != NULL || jch == (char) 0) { /* Ignore leading whitespace */ if (stri == str0) { stri++; str0 = stri; } /* terminate token before whitespace; start new one */ else { tokens->ntok = tokens->ntok + 1; if (tokens->ntok > maxtokens) return (maxtokens); tokens->tok1[tokens->ntok] = str0; tokens->ltok[tokens->ntok] = stri - str0; stri++; str0 = stri; } } /* Keep going if not whitespace */ else stri++; } /* Add token terminated by end of line */ if (str0 < stri) { tokens->ntok = tokens->ntok + 1; if (tokens->ntok > maxtokens) return (maxtokens); tokens->tok1[tokens->ntok] = str0; ltok = stri - str0 + 1; tokens->ltok[tokens->ntok] = ltok; /* Deal with white space just before end of line */ jch = str0[ltok-1]; if (strchr (tokens->white, jch)) { ltok = ltok - 1; tokens->ltok[tokens->ntok] = ltok; tokens->ntok = tokens->ntok + 1; tokens->tok1[tokens->ntok] = str0 + ltok; tokens->ltok[tokens->ntok] = 0; } } tokens->itok = 0; return (tokens->ntok); } /* NEXTOKEN -- get next token from tokenized string */ int nextoken (tokens, token, maxchars) struct Tokens *tokens; /* Token structure returned */ char *token; /* token (returned) */ int maxchars; /* Maximum length of token */ { int ltok; /* length of token string (returned) */ int it, i; int maxc = maxchars - 1; tokens->itok = tokens->itok + 1; it = tokens->itok; if (it > tokens->ntok) it = tokens->ntok; else if (it < 1) it = 1; ltok = tokens->ltok[it]; if (ltok > maxc) ltok = maxc; strncpy (token, tokens->tok1[it], ltok); for (i = ltok; i < maxc; i++) token[i] = (char) 0; return (ltok); } /* GETOKEN -- get specified token from tokenized string */ int getoken (tokens, itok, token, maxchars) struct Tokens *tokens; /* Token structure returned */ int itok; /* token sequence number of token * if <0, get whole string after token -itok * if =0, get whole string */ char *token; /* token (returned) */ int maxchars; /* Maximum length of token */ { int ltok; /* length of token string (returned) */ int it, i; int maxc = maxchars - 1; it = itok; if (it > 0 ) { if (it > tokens->ntok) it = tokens->ntok; ltok = tokens->ltok[it]; if (ltok > maxc) ltok = maxc; strncpy (token, tokens->tok1[it], ltok); } else if (it < 0) { if (it < -tokens->ntok) it = -tokens->ntok; ltok = tokens->line + tokens->lline - tokens->tok1[-it]; if (ltok > maxc) ltok = maxc; strncpy (token, tokens->tok1[-it], ltok); } else { ltok = tokens->lline; if (ltok > maxc) ltok = maxc; strncpy (token, tokens->tok1[1], ltok); } for (i = ltok; i < maxc; i++) token[i] = (char) 0; return (ltok); } /* * Jul 14 1999 New subroutines * Jul 15 1999 Add getfilebuff() * Oct 15 1999 Fix format eror in error message * Oct 21 1999 Fix declarations after lint * Dec 9 1999 Add next_token(); set pointer to next token in first_token * * Sep 25 2001 Add isfilelist(); move isfile() from catutil.c * * Jan 4 2002 Allow getfilebuffer() to read from stdin * Jan 8 2002 Add sts2c() and stc2s() for space-replaced strings * Mar 22 2002 Clean up isfilelist() * Aug 1 2002 Return 1 if file is stdin in isfile() * * Feb 4 2003 Open catalog file rb instead of r (Martin Ploner, Bern) * Mar 5 2003 Add isimlistd() to check image lists with root directory * May 27 2003 Use file stat call in getfilesize() instead of opening file * Jul 17 2003 Add root directory argument to isfilelist() * * Sep 29 2004 Drop next_token() to avoid conflict with subroutine in catutil.c * * Sep 26 2005 In first_token, return NULL if token is only control character * * Feb 23 2006 Add istiff(), isjpeg(), isgif() to check TIFF, JPEG, GIF files * Jun 20 2006 Cast call to fgets() void * * Jan 5 2007 Change stc2s() and sts2c() to pass single character as pointer * Jan 11 2007 Move token access subroutines from catutil.c * * Aug 28 2014 Return length from next_line(): 0=unsuccessful */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/lin.c0000664000175000017500000003042413047255533020412 0ustar mattymatty00000000000000/*============================================================================= * * WCSLIB - an implementation of the FITS WCS proposal. * Copyright (C) 1995-2002, Mark Calabretta * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Correspondence concerning WCSLIB may be directed to: * Internet email: mcalabre@atnf.csiro.au * Postal address: Dr. Mark Calabretta, * Australia Telescope National Facility, * P.O. Box 76, * Epping, NSW, 2121, * AUSTRALIA * *============================================================================= * * C routines which implement the FITS World Coordinate System (WCS) * convention. * * Summary of routines * ------------------- * These utility routines apply the linear transformation defined by the WCS * FITS header cards. There are separate routines for the image-to-pixel, * linfwd(), and pixel-to-image, linrev(), transformations. * * An initialization routine, linset(), computes intermediate values from * the transformation parameters but need not be called explicitly - see the * explanation of lin.flag below. * * An auxiliary matrix inversion routine, matinv(), is included. It uses * LU-triangular factorization with scaled partial pivoting. * * * Initialization routine; linset() * -------------------------------- * Initializes members of a linprm data structure which hold intermediate * values. Note that this routine need not be called directly; it will be * invoked by linfwd() and linrev() if the "flag" structure member is * anything other than a predefined magic value. * * Given and/or returned: * lin linprm* Linear transformation parameters (see below). * * Function return value: * int Error status * 0: Success. * 1: Memory allocation error. * 2: PC matrix is singular. * * Forward transformation; linfwd() * -------------------------------- * Compute pixel coordinates from image coordinates. Note that where * celestial coordinate systems are concerned the image coordinates * correspond to (x,y) in the plane of projection, not celestial (lng,lat). * * Given: * imgcrd const double[] * Image (world) coordinate. * * Given and returned: * lin linprm* Linear transformation parameters (see below). * * Returned: * pixcrd d[] Pixel coordinate. * * Function return value: * int Error status * 0: Success. * 1: The transformation is not invertible. * * Reverse transformation; linrev() * -------------------------------- * Compute image coordinates from pixel coordinates. Note that where * celestial coordinate systems are concerned the image coordinates * correspond to (x,y) in the plane of projection, not celestial (lng,lat). * * Given: * pixcrd const double[] * Pixel coordinate. * * Given and/or returned: * lin linprm* Linear transformation parameters (see below). * * Returned: * imgcrd d[] Image (world) coordinate. * * Function return value: * int Error status * 0: Success. * 1: Error. * * Linear transformation parameters * -------------------------------- * The linprm struct consists of the following: * * int flag * This flag must be set to zero whenever any of the following members * are set or modified. This signals the initialization routine, * linset(), to recompute intermediaries. * int naxis * Number of image axes. * double *crpix * Pointer to the first element of an array of double containing the * coordinate reference pixel, CRPIXn. * double *pc * Pointer to the first element of the PC (pixel coordinate) * transformation matrix. The expected order is * * lin.pc = {PC1_1, PC1_2, PC2_1, PC2_2}; * * This may be conveniently constructed from a two-dimensional array * via * * double m[2][2] = {{PC1_1, PC1_2}, * {PC2_1, PC2_2}}; * * which is equivalent to, * * double m[2][2]; * m[0][0] = PC1_1; * m[0][1] = PC1_2; * m[1][0] = PC2_1; * m[1][1] = PC2_2; * * for which the storage order is * * PC1_1, PC1_2, PC2_1, PC2_2 * * so it would be legitimate to set lin.pc = *m. * double *cdelt * Pointer to the first element of an array of double containing the * coordinate increments, CDELTn. * * The remaining members of the linprm struct are maintained by the * initialization routine and should not be modified. * * double *piximg * Pointer to the first element of the matrix containing the product * of the CDELTn diagonal matrix and the PC matrix. * double *imgpix * Pointer to the first element of the inverse of the piximg matrix. * * linset allocates storage for the above arrays using malloc(). Note, * however, that these routines do not free this storage so if a linprm * variable has itself been malloc'd then these structure members must be * explicitly freed before the linprm variable is free'd otherwise a memory * leak will result. * * Author: Mark Calabretta, Australia Telescope National Facility * $Id: lin.c,v 2.8 2002/01/30 06:04:03 mcalabre Exp $ *===========================================================================*/ #include #include #include "wcslib.h" /* Map error number to error message for each function. */ const char *linset_errmsg[] = { 0, "Memory allocation error", "PC matrix is singular"}; const char *linfwd_errmsg[] = { 0, "Memory allocation error", "PC matrix is singular"}; const char *linrev_errmsg[] = { 0, "Memory allocation error", "PC matrix is singular"}; int linset(lin) struct linprm *lin; { int i, ij, j, mem, n; n = lin->naxis; /* Allocate memory for internal arrays. */ mem = n * n * sizeof(double); lin->piximg = (double*)malloc(mem); if (lin->piximg == (double*)0) return 1; lin->imgpix = (double*)malloc(mem); if (lin->imgpix == (double*)0) { free(lin->piximg); return 1; } /* Compute the pixel-to-image transformation matrix. */ for (i = 0, ij = 0; i < n; i++) { for (j = 0; j < n; j++, ij++) { lin->piximg[ij] = lin->cdelt[i] * lin->pc[ij]; } } /* Compute the image-to-pixel transformation matrix. */ if (matinv(n, lin->piximg, lin->imgpix)) return 2; lin->flag = LINSET; return 0; } /*--------------------------------------------------------------------------*/ int linfwd(imgcrd, lin, pixcrd) const double imgcrd[]; struct linprm *lin; double pixcrd[]; { int i, ij, j, n; n = lin->naxis; if (lin->flag != LINSET) { if (linset(lin)) return 1; } for (i = 0, ij = 0; i < n; i++) { pixcrd[i] = 0.0; for (j = 0; j < n; j++, ij++) { pixcrd[i] += lin->imgpix[ij] * imgcrd[j]; } } for (j = 0; j < n; j++) { pixcrd[j] += lin->crpix[j]; } return 0; } /*--------------------------------------------------------------------------*/ int linrev(pixcrd, lin, imgcrd) const double pixcrd[]; struct linprm *lin; double imgcrd[]; { int i, ij, j, n; double temp; n = lin->naxis; if (lin->flag != LINSET) { if (linset(lin)) return 1; } for (i = 0; i < n; i++) { imgcrd[i] = 0.0; } for (j = 0; j < n; j++) { temp = pixcrd[j] - lin->crpix[j]; for (i = 0, ij = j; i < n; i++, ij+=n) { imgcrd[i] += lin->piximg[ij] * temp; } } return 0; } /*--------------------------------------------------------------------------*/ int matinv(n, mat, inv) const int n; const double mat[]; double inv[]; { register int i, ij, ik, j, k, kj, pj; int itemp, mem, *mxl, *lxm, pivot; double colmax, *lu, *rowmax, dtemp; /* Allocate memory for internal arrays. */ mem = n * sizeof(int); if ((mxl = (int*)malloc(mem)) == (int*)0) return 1; if ((lxm = (int*)malloc(mem)) == (int*)0) { free(mxl); return 1; } mem = n * sizeof(double); if ((rowmax = (double*)malloc(mem)) == (double*)0) { free(mxl); free(lxm); return 1; } mem *= n; if ((lu = (double*)malloc(mem)) == (double*)0) { free(mxl); free(lxm); free(rowmax); return 1; } /* Initialize arrays. */ for (i = 0, ij = 0; i < n; i++) { /* Vector which records row interchanges. */ mxl[i] = i; rowmax[i] = 0.0; for (j = 0; j < n; j++, ij++) { dtemp = fabs(mat[ij]); if (dtemp > rowmax[i]) rowmax[i] = dtemp; lu[ij] = mat[ij]; } /* A row of zeroes indicates a singular matrix. */ if (rowmax[i] == 0.0) { free(mxl); free(lxm); free(rowmax); free(lu); return 2; } } /* Form the LU triangular factorization using scaled partial pivoting. */ for (k = 0; k < n; k++) { /* Decide whether to pivot. */ colmax = fabs(lu[k*n+k]) / rowmax[k]; pivot = k; for (i = k+1; i < n; i++) { ik = i*n + k; dtemp = fabs(lu[ik]) / rowmax[i]; if (dtemp > colmax) { colmax = dtemp; pivot = i; } } if (pivot > k) { /* We must pivot, interchange the rows of the design matrix. */ for (j = 0, pj = pivot*n, kj = k*n; j < n; j++, pj++, kj++) { dtemp = lu[pj]; lu[pj] = lu[kj]; lu[kj] = dtemp; } /* Amend the vector of row maxima. */ dtemp = rowmax[pivot]; rowmax[pivot] = rowmax[k]; rowmax[k] = dtemp; /* Record the interchange for later use. */ itemp = mxl[pivot]; mxl[pivot] = mxl[k]; mxl[k] = itemp; } /* Gaussian elimination. */ for (i = k+1; i < n; i++) { ik = i*n + k; /* Nothing to do if lu[ik] is zero. */ if (lu[ik] != 0.0) { /* Save the scaling factor. */ lu[ik] /= lu[k*n+k]; /* Subtract rows. */ for (j = k+1; j < n; j++) { lu[i*n+j] -= lu[ik]*lu[k*n+j]; } } } } /* mxl[i] records which row of mat corresponds to row i of lu. */ /* lxm[i] records which row of lu corresponds to row i of mat. */ for (i = 0; i < n; i++) { lxm[mxl[i]] = i; } /* Determine the inverse matrix. */ for (i = 0, ij = 0; i < n; i++) { for (j = 0; j < n; j++, ij++) { inv[ij] = 0.0; } } for (k = 0; k < n; k++) { inv[lxm[k]*n+k] = 1.0; /* Forward substitution. */ for (i = lxm[k]+1; i < n; i++) { for (j = lxm[k]; j < i; j++) { inv[i*n+k] -= lu[i*n+j]*inv[j*n+k]; } } /* Backward substitution. */ for (i = n-1; i >= 0; i--) { for (j = i+1; j < n; j++) { inv[i*n+k] -= lu[i*n+j]*inv[j*n+k]; } inv[i*n+k] /= lu[i*n+i]; } } free(mxl); free(lxm); free(rowmax); free(lu); return 0; } /* Dec 20 1999 Doug Mink - Include wcslib.h, which includes lin.h * * Feb 15 2001 Doug Mink - Add comments for WCSLIB 2.6; no code changes * Sep 19 2001 Doug Mink - Add above change to WCSLIB 2.7 code * Nov 20 2001 Doug Mink - Always include stdlib.h * * Jan 15 2002 Bill Joye - Add ifdef so this compiles on MacOS/X * * Nov 18 2003 Doug Mink - Include stdlib.h instead of malloc.h */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/imhfile.c0000664000175000017500000014774513047255533021264 0ustar mattymatty00000000000000/*** File imhfile.c *** March 27, 2012 *** By Jessica Mink, jmink@cfa.harvard.edu *** Harvard-Smithsonian Center for Astrophysics *** Copyright (C) 1996-2012 *** Smithsonian Astrophysical Observatory, Cambridge, MA, USA This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Correspondence concerning WCSTools should be addressed as follows: Internet email: jmink@cfa.harvard.edu Postal address: Jessica Mink Smithsonian Astrophysical Observatory 60 Garden St. Cambridge, MA 02138 USA * Module: imhfile.c (IRAF .imh image file reading and writing) * Purpose: Read and write IRAF image files (and translate headers) * Subroutine: check_immagic (irafheader, teststring ) * Verify that file is valid IRAF imhdr or impix * Subroutine: irafrhead (filename, lfhead, fitsheader, lihead) * Read IRAF image header * Subroutine: irafrimage (fitsheader) * Read IRAF image pixels (call after irafrhead) * Subroutine: same_path (pixname, hdrname) * Put filename and header path together * Subroutine: iraf2fits (hdrname, irafheader, nbiraf, nbfits) * Convert IRAF image header to FITS image header * Subroutine: irafwhead (hdrname, irafheader, fitsheader) * Write IRAF header file * Subroutine: irafwimage (hdrname, irafheader, fitsheader, image ) * Write IRAF image and header files * Subroutine: fits2iraf (fitsheader, irafheader) * Convert FITS image header to IRAF image header * Subroutine: irafgeti4 (irafheader, offset) * Get 4-byte integer from arbitrary part of IRAF header * Subroutine: irafgetc2 (irafheader, offset) * Get character string from arbitrary part of IRAF v.1 header * Subroutine: irafgetc (irafheader, offset) * Get character string from arbitrary part of IRAF header * Subroutine: iraf2str (irafstring, nchar) * Convert 2-byte/char IRAF string to 1-byte/char string * Subroutine: str2iraf (string, irafstring, nchar) * Convert 1-byte/char string to IRAF 2-byte/char string * Subroutine: irafswap (bitpix,string,nbytes) * Swap bytes in string in place, with FITS bits/pixel code * Subroutine: irafswap2 (string,nbytes) * Swap bytes in string in place * Subroutine irafswap4 (string,nbytes) * Reverse bytes of Integer*4 or Real*4 vector in place * Subroutine irafswap8 (string,nbytes) * Reverse bytes of Real*8 vector in place * Subroutine irafsize (filename) * Return length of file in bytes * Subroutine isiraf (filename) * Return 1 if IRAF .imh file, else 0 * Copyright: 2000 Smithsonian Astrophysical Observatory * You may do anything you like with this file except remove * this copyright. The Smithsonian Astrophysical Observatory * makes no representations about the suitability of this * software for any purpose. It is provided "as is" without * express or implied warranty. */ #include /* define stderr, FD, and NULL */ #include #include #include #include #include #include #include "fitsfile.h" /* Parameters from iraf/lib/imhdr.h for IRAF version 1 images */ #define SZ_IMPIXFILE 79 /* name of pixel storage file */ #define SZ_IMHDRFILE 79 /* length of header storage file */ #define SZ_IMTITLE 79 /* image title string */ #define LEN_IMHDR 2052 /* length of std header */ /* Parameters from iraf/lib/imhdr.h for IRAF version 2 images */ #define SZ_IM2PIXFILE 255 /* name of pixel storage file */ #define SZ_IM2HDRFILE 255 /* name of header storage file */ #define SZ_IM2TITLE 383 /* image title string */ #define LEN_IM2HDR 2046 /* length of std header */ /* Offsets into header in bytes for parameters in IRAF version 1 images */ #define IM_HDRLEN 12 /* Length of header in 4-byte ints */ #define IM_PIXTYPE 16 /* Datatype of the pixels */ #define IM_NDIM 20 /* Number of dimensions */ #define IM_LEN 24 /* Length (as stored) */ #define IM_PHYSLEN 52 /* Physical length (as stored) */ #define IM_PIXOFF 88 /* Offset of the pixels */ #define IM_CTIME 108 /* Time of image creation */ #define IM_MTIME 112 /* Time of last modification */ #define IM_LIMTIME 116 /* Time of min,max computation */ #define IM_MAX 120 /* Maximum pixel value */ #define IM_MIN 124 /* Maximum pixel value */ #define IM_PIXFILE 412 /* Name of pixel storage file */ #define IM_HDRFILE 572 /* Name of header storage file */ #define IM_TITLE 732 /* Image name string */ /* Offsets into header in bytes for parameters in IRAF version 2 images */ #define IM2_HDRLEN 6 /* Length of header in 4-byte ints */ #define IM2_PIXTYPE 10 /* Datatype of the pixels */ #define IM2_SWAPPED 14 /* Pixels are byte swapped */ #define IM2_NDIM 18 /* Number of dimensions */ #define IM2_LEN 22 /* Length (as stored) */ #define IM2_PHYSLEN 50 /* Physical length (as stored) */ #define IM2_PIXOFF 86 /* Offset of the pixels */ #define IM2_CTIME 106 /* Time of image creation */ #define IM2_MTIME 110 /* Time of last modification */ #define IM2_LIMTIME 114 /* Time of min,max computation */ #define IM2_MAX 118 /* Maximum pixel value */ #define IM2_MIN 122 /* Maximum pixel value */ #define IM2_PIXFILE 126 /* Name of pixel storage file */ #define IM2_HDRFILE 382 /* Name of header storage file */ #define IM2_TITLE 638 /* Image name string */ /* Codes from iraf/unix/hlib/iraf.h */ #define TY_CHAR 2 #define TY_SHORT 3 #define TY_INT 4 #define TY_LONG 5 #define TY_REAL 6 #define TY_DOUBLE 7 #define TY_COMPLEX 8 #define TY_POINTER 9 #define TY_STRUCT 10 #define TY_USHORT 11 #define TY_UBYTE 12 #define LEN_IRAFHDR 25000 #define LEN_PIXHDR 1024 #define LEN_FITSHDR 11520 int check_immagic(); int irafgeti4(); float irafgetr4(); char *irafgetc2(); char *irafgetc(); char *iraf2str(); static char *same_path(); static void irafputr4(); static void irafputi4(); static void irafputc2(); static void irafputc(); static void str2iraf(); static int headswap=-1; /* =1 to swap data bytes of foreign IRAF file */ static void irafswap(); static void irafswap2(); static void irafswap4(); static void irafswap8(); int head_version (); int pix_version (); int irafncmp (); static int machswap(); static int irafsize(); #define SECONDS_1970_TO_1980 315532800L /* Subroutine: irafrhead * Purpose: Open and read the iraf .imh file, translating it to FITS, too. * Returns: NULL if failure, else pointer to IRAF .imh image header * Notes: The imhdr format is defined in iraf/lib/imhdr.h, some of * which defines or mimicked, above. */ char * irafrhead (filename, lihead) char *filename; /* Name of IRAF header file */ int *lihead; /* Length of IRAF image header in bytes (returned) */ { FILE *fd; int nbr; char *irafheader; int nbhead, nbytes; int imhver; headswap = -1; *lihead = 0; /* open the image header file */ fd = fopen (filename, "rb"); if (fd == NULL) { fprintf (stderr, "IRAFRHEAD: cannot open file %s to read\n", filename); return (NULL); } /* Find size of image header file */ if ((nbhead = irafsize (fd)) <= 0) { fprintf (stderr, "IRAFRHEAD: cannot read file %s, size = %d\n", filename, nbhead); return (NULL); } /* allocate initial sized buffer */ nbytes = nbhead + 5000; irafheader = (char *) calloc (nbytes/4, 4); if (irafheader == NULL) { (void)fprintf(stderr, "IRAFRHEAD Cannot allocate %d-byte header\n", nbytes); return (NULL); } *lihead = nbytes; /* Read IRAF header */ nbr = fread (irafheader, 1, nbhead, fd); fclose (fd); /* Reject if header less than minimum length */ if (nbr < LEN_PIXHDR) { (void)fprintf(stderr, "IRAFRHEAD header file %s: %d / %d bytes read.\n", filename,nbr,LEN_PIXHDR); free (irafheader); return (NULL); } /* Check header magic word */ imhver = head_version (irafheader); if (imhver < 1) { free (irafheader); (void)fprintf(stderr, "IRAFRHEAD: %s is not a valid IRAF image header\n", filename); return(NULL); } /* check number of image dimensions if (imhver == 2) ndim = irafgeti4 (irafheader, IM2_NDIM]) else ndim = irafgeti4 (irafheader, IM_NDIM]) if (ndim < 2) { free (irafheader); (void)fprintf(stderr, "File %s does not contain 2d image\n", filename); return (NULL); } */ return (irafheader); } char * irafrimage (fitsheader) char *fitsheader; /* FITS image header (filled) */ { FILE *fd; char *bang; int naxis, naxis1, naxis2, naxis3, npaxis1, npaxis2,bitpix, bytepix, pixswap, i; char *image; int nbr, nbimage, nbaxis, nbl, nbdiff, lpname; char *pixheader; char *linebuff, *pixchar; int imhver, lpixhead, len; char pixname[SZ_IM2PIXFILE+1]; char newpixname[SZ_IM2HDRFILE+1]; /* Convert pixel file name to character string */ hgetm (fitsheader, "PIXFIL", SZ_IM2PIXFILE, pixname); /* Drop trailing spaces */ lpname = strlen (pixname); pixchar = pixname + lpname - 1; while (*pixchar == ' ') *pixchar = (char) 0; hgeti4 (fitsheader, "PIXOFF", &lpixhead); /* Open pixel file, ignoring machine name if present */ if ((bang = strchr (pixname, '!')) != NULL ) fd = fopen (bang + 1, "rb"); else fd = fopen (pixname, "rb"); /* If not at pathname in header, try same directory as header file */ if (!fd) { hgetm (fitsheader, "IMHFIL", SZ_IM2HDRFILE, newpixname); len = strlen (newpixname); newpixname[len-3] = 'p'; newpixname[len-2] = 'i'; newpixname[len-1] = 'x'; fd = fopen (newpixname, "rb"); } /* Print error message and exit if pixel file is not found */ if (!fd) { (void)fprintf(stderr, "IRAFRIMAGE: Cannot open IRAF pixel file %s\n", pixname); return (NULL); } /* Read pixel header */ pixheader = (char *) calloc (lpixhead/4, 4); if (pixheader == NULL) { (void)fprintf(stderr, "IRAFRIMAGE Cannot allocate %d-byte pixel header\n", lpixhead); return (NULL); } nbr = fread (pixheader, 1, lpixhead, fd); /* Check size of pixel header */ if (nbr < lpixhead) { (void)fprintf(stderr, "IRAF pixel file %s: %d / %d bytes read.\n", pixname,nbr,LEN_PIXHDR); free (pixheader); fclose (fd); return (NULL); } /* check pixel header magic word */ imhver = pix_version (pixheader); if (imhver < 1) { (void)fprintf(stderr, "File %s not valid IRAF pixel file.\n", pixname); free (pixheader); fclose (fd); return(NULL); } free (pixheader); /* Find number of bytes to read */ hgeti4 (fitsheader,"NAXIS",&naxis); hgeti4 (fitsheader,"NAXIS1",&naxis1); hgeti4 (fitsheader,"NAXIS2",&naxis2); hgeti4 (fitsheader,"NPAXIS1",&npaxis1); hgeti4 (fitsheader,"NPAXIS2",&npaxis2); hgeti4 (fitsheader,"BITPIX",&bitpix); if (bitpix < 0) bytepix = -bitpix / 8; else bytepix = bitpix / 8; /* If either dimension is one and image is 3-D, read all three dimensions */ if (naxis == 3 && ((naxis1 == 1) | (naxis2 == 1))) { hgeti4 (fitsheader,"NAXIS3",&naxis3); nbimage = naxis1 * naxis2 * naxis3 * bytepix; } else { nbimage = naxis1 * naxis2 * bytepix; naxis3 = 1; } if (bytepix > 4) image = (char *) calloc (nbimage/8, 8); else if (bytepix > 2) image = (char *) calloc (nbimage/4, 4); else if (bytepix > 1) image = (char *) calloc (nbimage/2, 2); else image = (char *) calloc (nbimage, 1); if (image == NULL) { (void)fprintf(stderr, "IRAFRIMAGE Cannot allocate %d-byte image buffer\n", nbimage); return (NULL); } /* Read IRAF image all at once if physical and image dimensions are the same */ if (npaxis1 == naxis1) nbr = fread (image, 1, nbimage, fd); /* Read IRAF image one line at a time if physical and image dimensions differ */ else { nbdiff = (npaxis1 - naxis1) * bytepix; nbaxis = naxis1 * bytepix; linebuff = image; nbr = 0; if (naxis2 == 1 && naxis3 > 1) naxis2 = naxis3; for (i = 0; i < naxis2; i++) { nbl = fread (linebuff, 1, nbaxis, fd); nbr = nbr + nbl; (void) fseek (fd, nbdiff, SEEK_CUR); linebuff = linebuff + nbaxis; } } fclose (fd); /* Check size of image */ if (nbr < nbimage) { (void)fprintf(stderr, "IRAF pixel file %s: %d / %d bytes read.\n", pixname,nbr,nbimage); free (image); return (NULL); } /* Byte-reverse image, if necessary */ pixswap = 0; hgetl (fitsheader, "PIXSWAP", &pixswap); if (pixswap) irafswap (bitpix, image, nbimage); return (image); } /* Return IRAF image format version number from magic word in IRAF header*/ int head_version (irafheader) char *irafheader; /* IRAF image header from file */ { /* Check header file magic word */ if (irafncmp (irafheader, "imhdr", 5) != 0 ) { if (strncmp (irafheader, "imhv2", 5) != 0) return (0); else return (2); } else return (1); } /* Return IRAF image format version number from magic word in IRAF pixel file */ int pix_version (irafheader) char *irafheader; /* IRAF image header from file */ { /* Check pixel file header magic word */ if (irafncmp (irafheader, "impix", 5) != 0) { if (strncmp (irafheader, "impv2", 5) != 0) return (0); else return (2); } else return (1); } /* Verify that file is valid IRAF imhdr or impix by checking first 5 chars * Returns: 0 on success, 1 on failure */ int irafncmp (irafheader, teststring, nc) char *irafheader; /* IRAF image header from file */ char *teststring; /* C character string to compare */ int nc; /* Number of characters to compate */ { char *line; headswap = -1; if ((line = iraf2str (irafheader, nc)) == NULL) return (1); if (strncmp (line, teststring, nc) == 0) { free (line); return (0); } else { free (line); return (1); } } /* Convert IRAF image header to FITS image header, returning FITS header */ char * iraf2fits (hdrname, irafheader, nbiraf, nbfits) char *hdrname; /* IRAF header file name (may be path) */ char *irafheader; /* IRAF image header */ int nbiraf; /* Number of bytes in IRAF header */ int *nbfits; /* Number of bytes in FITS header (returned) */ { char *objname; /* object name from FITS file */ int lstr, i, j, k, ib, nax, nbits, nl; int lname = 0; char *pixname, *newpixname, *bang, *chead; char *fitsheader; int nblock, nlines; char *fhead, *fhead1, *fp, endline[81]; char irafchar; char fitsline[81]; char *dstring; int pixtype; int imhver, n, imu, pixoff, impixoff, immax, immin, imtime; int imndim, imlen, imphyslen, impixtype, pixswap, hpixswap, mtime; float rmax, rmin; headswap = -1; /* Set up last line of FITS header */ (void)strncpy (endline,"END", 3); for (i = 3; i < 80; i++) endline[i] = ' '; endline[80] = 0; /* Check header magic word */ imhver = head_version (irafheader); if (imhver < 1) { (void)fprintf(stderr, "File %s not valid IRAF image header\n", hdrname); return(NULL); } if (imhver == 2) { nlines = 24 + ((nbiraf - LEN_IM2HDR) / 81); imndim = IM2_NDIM; imlen = IM2_LEN; imphyslen = IM2_PHYSLEN; impixtype = IM2_PIXTYPE; impixoff = IM2_PIXOFF; imtime = IM2_MTIME; immax = IM2_MAX; immin = IM2_MIN; } else { nlines = 24 + ((nbiraf - LEN_IMHDR) / 162); imndim = IM_NDIM; imlen = IM_LEN; imphyslen = IM_PHYSLEN; impixtype = IM_PIXTYPE; impixoff = IM_PIXOFF; imtime = IM_MTIME; immax = IM_MAX; immin = IM_MIN; } /* Initialize FITS header */ nblock = (nlines * 80) / 2880; *nbfits = (nblock + 5) * 2880 + 4; fitsheader = (char *) calloc (*nbfits, 1); if (fitsheader == NULL) { (void)fprintf(stderr, "IRAF2FITS Cannot allocate %d-byte FITS header\n", *nbfits); return (NULL); } hlength (fitsheader, *nbfits); fhead = fitsheader; (void)strncpy (fitsheader, endline, 80); hputl (fitsheader, "SIMPLE", 1); fhead = fhead + 80; /* Set pixel size in FITS header */ pixtype = irafgeti4 (irafheader, impixtype); switch (pixtype) { case TY_CHAR: nbits = 8; break; case TY_UBYTE: nbits = 8; break; case TY_SHORT: nbits = 16; break; case TY_USHORT: nbits = -16; break; case TY_INT: case TY_LONG: nbits = 32; break; case TY_REAL: nbits = -32; break; case TY_DOUBLE: nbits = -64; break; default: (void)fprintf(stderr,"Unsupported data type: %d\n", pixtype); return (NULL); } hputi4 (fitsheader,"BITPIX",nbits); hputcom (fitsheader,"BITPIX", "IRAF .imh pixel type"); fhead = fhead + 80; /* Set image dimensions in FITS header */ nax = irafgeti4 (irafheader, imndim); hputi4 (fitsheader,"NAXIS",nax); hputcom (fitsheader,"NAXIS", "IRAF .imh naxis"); fhead = fhead + 80; n = irafgeti4 (irafheader, imlen); hputi4 (fitsheader, "NAXIS1", n); hputcom (fitsheader,"NAXIS1", "IRAF .imh image naxis[1]"); fhead = fhead + 80; if (nax > 1) { n = irafgeti4 (irafheader, imlen+4); hputi4 (fitsheader, "NAXIS2", n); hputcom (fitsheader,"NAXIS2", "IRAF .imh image naxis[2]"); } else hputi4 (fitsheader, "NAXIS2", 1); hputcom (fitsheader,"NAXIS2", "IRAF .imh naxis[2]"); fhead = fhead + 80; if (nax > 2) { n = irafgeti4 (irafheader, imlen+8); hputi4 (fitsheader, "NAXIS3", n); hputcom (fitsheader,"NAXIS3", "IRAF .imh image naxis[3]"); fhead = fhead + 80; } if (nax > 3) { n = irafgeti4 (irafheader, imlen+12); hputi4 (fitsheader, "NAXIS4", n); hputcom (fitsheader,"NAXIS4", "IRAF .imh image naxis[4]"); fhead = fhead + 80; } /* Set object name in FITS header */ if (imhver == 2) objname = irafgetc (irafheader, IM2_TITLE, SZ_IM2TITLE); else objname = irafgetc2 (irafheader, IM_TITLE, SZ_IMTITLE); if ((lstr = strlen (objname)) < 8) { for (i = lstr; i < 8; i++) objname[i] = ' '; objname[8] = 0; } hputs (fitsheader,"OBJECT",objname); hputcom (fitsheader,"OBJECT", "IRAF .imh title"); free (objname); fhead = fhead + 80; /* Save physical axis lengths so image file can be read */ n = irafgeti4 (irafheader, imphyslen); hputi4 (fitsheader, "NPAXIS1", n); hputcom (fitsheader,"NPAXIS1", "IRAF .imh physical naxis[1]"); fhead = fhead + 80; if (nax > 1) { n = irafgeti4 (irafheader, imphyslen+4); hputi4 (fitsheader, "NPAXIS2", n); hputcom (fitsheader,"NPAXIS2", "IRAF .imh physical naxis[2]"); fhead = fhead + 80; } if (nax > 2) { n = irafgeti4 (irafheader, imphyslen+8); hputi4 (fitsheader, "NPAXIS3", n); hputcom (fitsheader,"NPAXIS3", "IRAF .imh physical naxis[3]"); fhead = fhead + 80; } if (nax > 3) { n = irafgeti4 (irafheader, imphyslen+12); hputi4 (fitsheader, "NPAXIS4", n); hputcom (fitsheader,"NPAXIS4", "IRAF .imh physical naxis[4]"); fhead = fhead + 80; } /* Save image minimum and maximum in header */ rmax = irafgetr4 (irafheader, immax); rmin = irafgetr4 (irafheader, immin); if (rmin != rmax) { hputr4 (fitsheader, "IRAFMIN", &rmin); fhead = fhead + 80; hputcom (fitsheader,"IRAFMIN", "IRAF .imh minimum"); hputr4 (fitsheader, "IRAFMAX", &rmax); hputcom (fitsheader,"IRAFMAX", "IRAF .imh maximum"); fhead = fhead + 80; } /* Save image header filename in header */ nl = hputm (fitsheader,"IMHFIL",hdrname); if (nl > 0) { lname = strlen (hdrname); strcpy (fitsline, "IRAF header file name"); if (lname < 43) hputcom (fitsheader,"IMHFIL_1", fitsline); else if (lname > 67 && lname < 110) hputcom (fitsheader,"IMHFIL_2", fitsline); else if (lname > 134 && lname < 177) hputcom (fitsheader,"IMHFIL_3", fitsline); } if (nl > 0) fhead = fhead + (nl * 80); /* Save image pixel file pathname in header */ if (imhver == 2) pixname = irafgetc (irafheader, IM2_PIXFILE, SZ_IM2PIXFILE); else pixname = irafgetc2 (irafheader, IM_PIXFILE, SZ_IMPIXFILE); if (strncmp(pixname, "HDR", 3) == 0 ) { newpixname = same_path (pixname, hdrname); free (pixname); pixname = newpixname; } if (strchr (pixname, '/') == NULL && strchr (pixname, '$') == NULL) { newpixname = same_path (pixname, hdrname); free (pixname); pixname = newpixname; } if ((bang = strchr (pixname, '!')) != NULL ) nl = hputm (fitsheader,"PIXFIL",bang+1); else nl = hputm (fitsheader,"PIXFIL",pixname); free (pixname); if (nl > 0) { strcpy (fitsline, "IRAF .pix pixel file"); if (lname < 43) hputcom (fitsheader,"PIXFIL_1", fitsline); else if (lname > 67 && lname < 110) hputcom (fitsheader,"PIXFIL_2", fitsline); else if (lname > 134 && lname < 177) hputcom (fitsheader,"PIXFIL_3", fitsline); } if (nl > 0) fhead = fhead + (nl * 80); /* Save image offset from star of pixel file */ pixoff = irafgeti4 (irafheader, impixoff); pixoff = (pixoff - 1) * 2; hputi4 (fitsheader, "PIXOFF", pixoff); hputcom (fitsheader,"PIXOFF", "IRAF .pix pixel offset (Do not change!)"); fhead = fhead + 80; /* Save IRAF file format version in header */ hputi4 (fitsheader,"IMHVER",imhver); hputcom (fitsheader,"IMHVER", "IRAF .imh format version (1 or 2)"); fhead = fhead + 80; /* Set flag if header numbers are byte-reversed on this machine */ if (machswap() != headswap) hputl (fitsheader, "HEADSWAP", 1); else hputl (fitsheader, "HEADSWAP", 0); hputcom (fitsheader,"HEADSWAP", "IRAF header, FITS byte orders differ if T"); fhead = fhead + 80; /* Set flag if image pixels are byte-reversed on this machine */ if (imhver == 2) { hpixswap = irafgeti4 (irafheader, IM2_SWAPPED); if (headswap && !hpixswap) pixswap = 1; else if (!headswap && hpixswap) pixswap = 1; else pixswap = 0; } else pixswap = headswap; if (machswap() != pixswap) hputl (fitsheader, "PIXSWAP", 1); else hputl (fitsheader, "PIXSWAP", 0); hputcom (fitsheader,"PIXSWAP", "IRAF pixels, FITS byte orders differ if T"); fhead = fhead + 80; /* Read modification time */ mtime = irafgeti4 (irafheader, imtime); if (mtime == 0) dstring = lt2fd (); else dstring = tsi2fd (mtime); hputs (fitsheader, "DATE-MOD", dstring); hputcom (fitsheader,"DATE-MOD", "Date of latest file modification"); free (dstring); fhead = fhead + 80; /* Add user portion of IRAF header to FITS header */ fitsline[80] = 0; if (imhver == 2) { imu = LEN_IM2HDR; chead = irafheader; j = 0; for (k = 0; k < 80; k++) fitsline[k] = ' '; for (i = imu; i < nbiraf; i++) { irafchar = chead[i]; if (irafchar == 0) break; else if (irafchar == 10) { (void)strncpy (fhead, fitsline, 80); /* fprintf (stderr,"%80s\n",fitsline); */ if (strncmp (fitsline, "OBJECT ", 7) != 0) { fhead = fhead + 80; } for (k = 0; k < 80; k++) fitsline[k] = ' '; j = 0; } else { if (j > 80) { if (strncmp (fitsline, "OBJECT ", 7) != 0) { (void)strncpy (fhead, fitsline, 80); /* fprintf (stderr,"%80s\n",fitsline); */ j = 9; fhead = fhead + 80; } for (k = 0; k < 80; k++) fitsline[k] = ' '; } if (irafchar > 32 && irafchar < 127) fitsline[j] = irafchar; j++; } } } else { imu = LEN_IMHDR; chead = irafheader; if (headswap == 1) ib = 0; else ib = 1; for (k = 0; k < 80; k++) fitsline[k] = ' '; j = 0; for (i = imu; i < nbiraf; i=i+2) { irafchar = chead[i+ib]; if (irafchar == 0) break; else if (irafchar == 10) { if (strncmp (fitsline, "OBJECT ", 7) != 0) { (void)strncpy (fhead, fitsline, 80); fhead = fhead + 80; } /* fprintf (stderr,"%80s\n",fitsline); */ j = 0; for (k = 0; k < 80; k++) fitsline[k] = ' '; } else { if (j > 80) { if (strncmp (fitsline, "OBJECT ", 7) != 0) { (void)strncpy (fhead, fitsline, 80); j = 9; fhead = fhead + 80; } /* fprintf (stderr,"%80s\n",fitsline); */ for (k = 0; k < 80; k++) fitsline[k] = ' '; } if (irafchar > 32 && irafchar < 127) fitsline[j] = irafchar; j++; } } } /* Add END to last line */ (void)strncpy (fhead, endline, 80); /* Find end of last 2880-byte block of header */ fhead = ksearch (fitsheader, "END") + 80; nblock = *nbfits / 2880; fhead1 = fitsheader + (nblock * 2880); /* Pad rest of header with spaces */ strncpy (endline," ",3); for (fp = fhead; fp < fhead1; fp = fp + 80) { (void)strncpy (fp, endline,80); } return (fitsheader); } int irafwhead (hdrname, lhead, irafheader, fitsheader) char *hdrname; /* Name of IRAF header file */ int lhead; /* Length of IRAF header */ char *irafheader; /* IRAF header */ char *fitsheader; /* FITS image header */ { int fd; int nbw, nbhead, lphead, pixswap; /* Get rid of redundant header information */ hgeti4 (fitsheader, "PIXOFF", &lphead); hgeti4 (fitsheader, "PIXSWAP", &pixswap); /* Write IRAF header file */ /* Convert FITS header to IRAF header */ irafheader = fits2iraf (fitsheader, irafheader, lhead, &nbhead); if (irafheader == NULL) { fprintf (stderr, "IRAFWIMAGE: file %s header error\n", hdrname); return (-1); } /* Open the output file */ if (!access (hdrname, 0)) { fd = open (hdrname, O_WRONLY); if (fd < 3) { fprintf (stderr, "IRAFWIMAGE: file %s not writeable\n", hdrname); return (0); } } else { fd = open (hdrname, O_RDWR+O_CREAT, 0666); if (fd < 3) { fprintf (stderr, "IRAFWIMAGE: cannot create file %s\n", hdrname); return (0); } } /* Write IRAF header to disk file */ nbw = write (fd, irafheader, nbhead); (void) ftruncate (fd, nbhead); close (fd); if (nbw < nbhead) { (void)fprintf(stderr, "IRAF header file %s: %d / %d bytes written.\n", hdrname, nbw, nbhead); return (-1); } return (nbw); } /* IRAFWIMAGE -- write IRAF .imh header file and .pix image file * No matter what the input, this always writes in the local byte order */ int irafwimage (hdrname, lhead, irafheader, fitsheader, image ) char *hdrname; /* Name of IRAF header file */ int lhead; /* Length of IRAF header */ char *irafheader; /* IRAF header */ char *fitsheader; /* FITS image header */ char *image; /* IRAF image */ { int fd; char *bang; int nbw, bytepix, bitpix, naxis, naxis1, naxis2, nbimage, lphead; char *pixn, *newpixname; char pixname[SZ_IM2PIXFILE+1]; int imhver, pixswap; hgeti4 (fitsheader, "IMHVER", &imhver); if (!hgetm (fitsheader, "PIXFIL", SZ_IM2PIXFILE, pixname)) { if (imhver == 2) pixn = irafgetc (irafheader, IM2_PIXFILE, SZ_IM2PIXFILE); else pixn = irafgetc2 (irafheader, IM_PIXFILE, SZ_IMPIXFILE); if (strncmp(pixn, "HDR", 3) == 0 ) { newpixname = same_path (pixn, hdrname); strcpy (pixname, newpixname); free (newpixname); } else { if ((bang = strchr (pixn, '!')) != NULL ) strcpy (pixname, bang+1); else strcpy (pixname, pixn); } free (pixn); } /* Find number of bytes to write */ hgeti4 (fitsheader,"NAXIS",&naxis); hgeti4 (fitsheader,"NAXIS1",&naxis1); hgeti4 (fitsheader,"NAXIS2",&naxis2); hgeti4 (fitsheader,"BITPIX",&bitpix); if (bitpix < 0) bytepix = -bitpix / 8; else bytepix = bitpix / 8; /* If either dimension is one and image is 3-D, read all three dimensions */ if (naxis == 3 && ((naxis1 == 1) | (naxis2 == 1))) { int naxis3; hgeti4 (fitsheader,"NAXIS3",&naxis3); nbimage = naxis1 * naxis2 * naxis3 * bytepix; } else nbimage = naxis1 * naxis2 * bytepix; /* Read information about pixel file from header */ hgeti4 (fitsheader, "PIXOFF", &lphead); hgeti4 (fitsheader, "PIXSWAP", &pixswap); /* Write IRAF header file */ if (irafwhead (hdrname, lhead, irafheader, fitsheader)) return (0); /* Open the output file */ if (!access (pixname, 0)) { fd = open (pixname, O_WRONLY); if (fd < 3) { fprintf (stderr, "IRAFWIMAGE: file %s not writeable\n", pixname); return (0); } } else { fd = open (pixname, O_RDWR+O_CREAT, 0666); if (fd < 3) { fprintf (stderr, "IRAFWIMAGE: cannot create file %s\n", pixname); return (0); } } /* Write header to IRAF pixel file */ if (imhver == 2) irafputc ("impv2", irafheader, 0, 5); else irafputc2 ("impix", irafheader, 0, 5); nbw = write (fd, irafheader, lphead); /* Byte-reverse image, if necessary */ if (pixswap) irafswap (bitpix, image, nbimage); /* Write data to IRAF pixel file */ nbw = write (fd, image, nbimage); close (fd); return (nbw); } /* Put filename and header path together */ static char * same_path (pixname, hdrname) char *pixname; /* IRAF pixel file pathname */ char *hdrname; /* IRAF image header file pathname */ { int len, plen; char *newpixname; newpixname = (char *) calloc (SZ_IM2PIXFILE, 1); /* Pixel file is in same directory as header */ if (strncmp(pixname, "HDR$", 4) == 0 ) { (void)strncpy (newpixname, hdrname, SZ_IM2PIXFILE); /* find the end of the pathname */ len = strlen (newpixname); #ifndef VMS while( (len > 0) && (newpixname[len-1] != '/') ) #else while( (len > 0) && (newpixname[len-1] != ']') && (newpixname[len-1] != ':') ) #endif len--; /* add name */ newpixname[len] = '\0'; plen = strlen (pixname) - 4; if (len + plen > SZ_IM2PIXFILE) (void)strncat (newpixname, &pixname[4], SZ_IM2PIXFILE - len); else (void)strncat (newpixname, &pixname[4], plen); } /* Bare pixel file with no path is assumed to be same as HDR$filename */ else if (strchr (pixname, '/') == NULL && strchr (pixname, '$') == NULL) { (void)strncpy (newpixname, hdrname, SZ_IM2PIXFILE); /* find the end of the pathname */ len = strlen (newpixname); #ifndef VMS while( (len > 0) && (newpixname[len-1] != '/') ) #else while( (len > 0) && (newpixname[len-1] != ']') && (newpixname[len-1] != ':') ) #endif len--; /* add name */ newpixname[len] = '\0'; (void)strncat (newpixname, pixname, SZ_IM2PIXFILE); } /* Pixel file has same name as header file, but with .pix extension */ else if (strncmp (pixname, "HDR", 3) == 0) { /* load entire header name string into name buffer */ (void)strncpy (newpixname, hdrname, SZ_IM2PIXFILE); len = strlen (newpixname); newpixname[len-3] = 'p'; newpixname[len-2] = 'i'; newpixname[len-1] = 'x'; } return (newpixname); } /* Convert FITS image header to IRAF image header, returning IRAF header */ /* No matter what the input, this always writes in the local byte order */ char * fits2iraf (fitsheader, irafheader, nbhead, nbiraf) char *fitsheader; /* FITS image header */ char *irafheader; /* IRAF image header (returned updated) */ int nbhead; /* Length of IRAF header */ int *nbiraf; /* Length of returned IRAF header */ { int i, n, pixoff, lhdrdir; short *irafp, *irafs, *irafu; char *iraf2u, *iraf2p, *filename, *hdrdir; char *fitsend, *fitsp, pixfile[SZ_IM2PIXFILE], hdrfile[SZ_IM2HDRFILE]; char title[SZ_IM2TITLE], temp[80]; int nax, nlfits, imhver, nbits, pixtype, hdrlength, mtime; int imndim, imlen, imphyslen, impixtype, imhlen, imtime, immax, immin; float rmax, rmin; hgeti4 (fitsheader, "IMHVER", &imhver); hdel (fitsheader, "IMHVER"); hdel (fitsheader, "IMHVER"); hgetl (fitsheader, "HEADSWAP", &headswap); hdel (fitsheader, "HEADSWAP"); hdel (fitsheader, "HEADSWAP"); if (imhver == 2) { imhlen = IM2_HDRLEN; imndim = IM2_NDIM; imlen = IM2_LEN; imtime = IM2_MTIME; imphyslen = IM2_PHYSLEN; impixtype = IM2_PIXTYPE; immax = IM2_MAX; immin = IM2_MIN; } else { imhlen = IM_HDRLEN; imndim = IM_NDIM; imlen = IM_LEN; imtime = IM_MTIME; imphyslen = IM_PHYSLEN; impixtype = IM_PIXTYPE; immax = IM_MAX; immin = IM_MIN; } /* Delete FITS header keyword not needed by IRAF */ hdel (fitsheader,"SIMPLE"); /* Set IRAF image data type */ hgeti4 (fitsheader,"BITPIX", &nbits); switch (nbits) { case 8: pixtype = TY_CHAR; break; case -8: pixtype = TY_UBYTE; break; case 16: pixtype = TY_SHORT; break; case -16: pixtype = TY_USHORT; break; case 32: pixtype = TY_INT; break; case -32: pixtype = TY_REAL; break; case -64: pixtype = TY_DOUBLE; break; default: (void)fprintf(stderr,"Unsupported data type: %d\n", nbits); return (NULL); } irafputi4 (irafheader, impixtype, pixtype); hdel (fitsheader,"BITPIX"); /* Set IRAF image dimensions */ hgeti4 (fitsheader,"NAXIS",&nax); irafputi4 (irafheader, imndim, nax); hdel (fitsheader,"NAXIS"); hgeti4 (fitsheader, "NAXIS1", &n); irafputi4 (irafheader, imlen, n); irafputi4 (irafheader, imphyslen, n); hdel (fitsheader,"NAXIS1"); hgeti4 (fitsheader,"NAXIS2",&n); irafputi4 (irafheader, imlen+4, n); irafputi4 (irafheader, imphyslen+4, n); hdel (fitsheader,"NAXIS2"); if (nax > 2) { hgeti4 (fitsheader,"NAXIS3",&n); irafputi4 (irafheader, imlen+8, n); irafputi4 (irafheader, imphyslen+8, n); hdel (fitsheader,"NAXIS3"); } if (nax > 3) { hgeti4 (fitsheader,"NAXIS4",&n); irafputi4 (irafheader, imlen+12, n); irafputi4 (irafheader, imphyslen+12, n); hdel (fitsheader,"NAXIS4"); } /* Set image pixel value limits */ rmin = 0.0; hgetr4 (fitsheader, "IRAFMIN", &rmin); rmax = 0.0; hgetr4 (fitsheader, "IRAFMAX", &rmax); if (rmin != rmax) { irafputr4 (irafheader, immax, rmax); irafputr4 (irafheader, immin, rmin); } hdel (fitsheader, "IRAFMIN"); hdel (fitsheader, "IRAFMAX"); /* Replace pixel file name, if it is in the FITS header */ if (hgetm (fitsheader, "PIXFIL", SZ_IM2PIXFILE, pixfile)) { if (strchr (pixfile, '/')) { if (hgetm (fitsheader, "IMHFIL", SZ_IM2HDRFILE, hdrfile)) { hdrdir = strrchr (hdrfile, '/'); if (hdrdir != NULL) { lhdrdir = hdrdir - hdrfile + 1; if (!strncmp (pixfile, hdrfile, lhdrdir)) { filename = pixfile + lhdrdir; strcpy (temp, "HDR$"); strcat (temp,filename); strcpy (pixfile, temp); } } if (pixfile[0] != '/' && pixfile[0] != 'H') { strcpy (temp, "HDR$"); strcat (temp,pixfile); strcpy (pixfile, temp); } } } if (imhver == 2) irafputc (pixfile, irafheader, IM2_PIXFILE, SZ_IM2PIXFILE); else irafputc2 (pixfile, irafheader, IM_PIXFILE, SZ_IMPIXFILE); hdel (fitsheader,"PIXFIL_1"); hdel (fitsheader,"PIXFIL_2"); hdel (fitsheader,"PIXFIL_3"); hdel (fitsheader,"PIXFIL_4"); } /* Replace header file name, if it is in the FITS header */ if (hgetm (fitsheader, "IMHFIL", SZ_IM2HDRFILE, pixfile)) { if (!strchr (pixfile,'/') && !strchr (pixfile,'$')) { strcpy (temp, "HDR$"); strcat (temp,pixfile); strcpy (pixfile, temp); } if (imhver == 2) irafputc (pixfile, irafheader, IM2_HDRFILE, SZ_IM2HDRFILE); else irafputc2 (pixfile, irafheader, IM_HDRFILE, SZ_IMHDRFILE); hdel (fitsheader, "IMHFIL_1"); hdel (fitsheader, "IMHFIL_2"); hdel (fitsheader, "IMHFIL_3"); hdel (fitsheader, "IMHFIL_4"); } /* Replace image title, if it is in the FITS header */ if (hgets (fitsheader, "OBJECT", SZ_IM2TITLE, title)) { if (imhver == 2) irafputc (title, irafheader, IM2_TITLE, SZ_IM2TITLE); else irafputc2 (title, irafheader, IM_TITLE, SZ_IMTITLE); hdel (fitsheader, "OBJECT"); } hgeti4 (fitsheader, "PIXOFF", &pixoff); hdel (fitsheader, "PIXOFF"); hdel (fitsheader, "PIXOFF"); hdel (fitsheader, "PIXSWAP"); hdel (fitsheader, "PIXSWAP"); hdel (fitsheader, "DATE-MOD"); hdel (fitsheader, "DATE-MOD"); fitsend = ksearch (fitsheader,"END"); /* Find length of FITS header */ fitsend = ksearch (fitsheader,"END"); nlfits = ((fitsend - fitsheader) / 80); /* Find new length of IRAF header */ if (imhver == 2) *nbiraf = LEN_IM2HDR + (81 * nlfits); else *nbiraf = LEN_IMHDR + (162 * nlfits); if (*nbiraf > nbhead) irafheader = realloc (irafheader, *nbiraf); /* Reset modification time */ mtime = lt2tsi (); irafputi4 (irafheader, imtime, mtime); /* Replace user portion of IRAF header with remaining FITS header */ if (imhver == 2) { iraf2u = irafheader + LEN_IM2HDR; iraf2p = iraf2u; for (fitsp = fitsheader; fitsp < fitsend; fitsp = fitsp + 80) { for (i = 0; i < 80; i++) *iraf2p++ = fitsp[i]; *iraf2p++ = 10; } *iraf2p++ = 0; *nbiraf = iraf2p - irafheader; hdrlength = 1 + *nbiraf / 2; } else { irafs = (short *)irafheader; irafu = irafs + (LEN_IMHDR / 2); irafp = irafu; for (fitsp = fitsheader; fitsp < fitsend; fitsp = fitsp + 80) { for (i = 0; i < 80; i++) *irafp++ = (short) fitsp[i]; *irafp++ = 10; } *irafp++ = 0; *irafp++ = 32; *nbiraf = 2 * (irafp - irafs); hdrlength = *nbiraf / 4; } /* Length of header file */ irafputi4 (irafheader, imhlen, hdrlength); /* Offset in .pix file to first pixel data hputi4 (fitsheader, "PIXOFF", pixoff); */ /* Return number of bytes in new IRAF header */ return (irafheader); } int irafgeti4 (irafheader, offset) char *irafheader; /* IRAF image header */ int offset; /* Number of bytes to skip before number */ { char *ctemp, *cheader; int temp; cheader = irafheader; ctemp = (char *) &temp; /* If header swap flag not set, set it now */ if (headswap < 0) { if (cheader[offset] > 0) headswap = 1; else headswap = 0; } if (machswap() != headswap) { ctemp[3] = cheader[offset]; ctemp[2] = cheader[offset+1]; ctemp[1] = cheader[offset+2]; ctemp[0] = cheader[offset+3]; } else { ctemp[0] = cheader[offset]; ctemp[1] = cheader[offset+1]; ctemp[2] = cheader[offset+2]; ctemp[3] = cheader[offset+3]; } return (temp); } float irafgetr4 (irafheader, offset) char *irafheader; /* IRAF image header */ int offset; /* Number of bytes to skip before number */ { char *ctemp, *cheader; float temp; cheader = irafheader; ctemp = (char *) &temp; /* If header swap flag not set, set it now */ if (headswap < 0) { if (cheader[offset] > 0) headswap = 1; else headswap = 0; } if (machswap() != headswap) { ctemp[3] = cheader[offset]; ctemp[2] = cheader[offset+1]; ctemp[1] = cheader[offset+2]; ctemp[0] = cheader[offset+3]; } else { ctemp[0] = cheader[offset]; ctemp[1] = cheader[offset+1]; ctemp[2] = cheader[offset+2]; ctemp[3] = cheader[offset+3]; } return (temp); } /* IRAFGETC2 -- Get character string from arbitrary part of v.1 IRAF header */ char * irafgetc2 (irafheader, offset, nc) char *irafheader; /* IRAF image header */ int offset; /* Number of bytes to skip before string */ int nc; /* Maximum number of characters in string */ { char *irafstring, *string; irafstring = irafgetc (irafheader, offset, 2*(nc+1)); string = iraf2str (irafstring, nc); free (irafstring); return (string); } /* IRAFGETC -- Get character string from arbitrary part of IRAF header */ char * irafgetc (irafheader, offset, nc) char *irafheader; /* IRAF image header */ int offset; /* Number of bytes to skip before string */ int nc; /* Maximum number of characters in string */ { char *ctemp, *cheader; int i; cheader = irafheader; ctemp = (char *) calloc (nc+1, 1); if (ctemp == NULL) { (void)fprintf(stderr, "IRAFGETC Cannot allocate %d-byte variable\n", nc+1); return (NULL); } for (i = 0; i < nc; i++) { ctemp[i] = cheader[offset+i]; if (ctemp[i] > 0 && ctemp[i] < 32) ctemp[i] = ' '; } return (ctemp); } /* Convert IRAF 2-byte/char string to 1-byte/char string */ char * iraf2str (irafstring, nchar) char *irafstring; /* IRAF 2-byte/character string */ int nchar; /* Number of characters in string */ { char *string; int i, j; /* Set swap flag according to position of nulls in 2-byte characters */ if (headswap < 0) { if (irafstring[0] != 0 && irafstring[1] == 0) headswap = 1; else if (irafstring[0] == 0 && irafstring[1] != 0) headswap = 0; else return (NULL); } string = (char *) calloc (nchar+1, 1); if (string == NULL) { (void)fprintf(stderr, "IRAF2STR Cannot allocate %d-byte variable\n", nchar+1); return (NULL); } /* Swap bytes, if requested */ if (headswap) j = 0; else j = 1; /* Convert appropriate byte of input to output character */ for (i = 0; i < nchar; i++) { string[i] = irafstring[j]; j = j + 2; } return (string); } /* IRAFPUTI4 -- Insert 4-byte integer into arbitrary part of IRAF header */ static void irafputi4 (irafheader, offset, inum) char *irafheader; /* IRAF image header */ int offset; /* Number of bytes to skip before number */ int inum; /* Number to put into header */ { char *cn, *chead; chead = irafheader; cn = (char *) &inum; if (headswap < 0) headswap = 0; if (headswap != machswap()) { chead[offset+3] = cn[0]; chead[offset+2] = cn[1]; chead[offset+1] = cn[2]; chead[offset] = cn[3]; } else { chead[offset] = cn[0]; chead[offset+1] = cn[1]; chead[offset+2] = cn[2]; chead[offset+3] = cn[3]; } return; } /* IRAFPUTR4 -- Insert 4-byte real number into arbitrary part of IRAF header */ static void irafputr4 (irafheader, offset, rnum) char *irafheader; /* IRAF image header */ int offset; /* Number of bytes to skip before number */ float rnum; /* Number to put into header */ { char *cn, *chead; chead = irafheader; cn = (char *) &rnum; if (headswap < 0) headswap = 0; if (headswap != machswap()) { chead[offset+3] = cn[0]; chead[offset+2] = cn[1]; chead[offset+1] = cn[2]; chead[offset] = cn[3]; } else { chead[offset] = cn[0]; chead[offset+1] = cn[1]; chead[offset+2] = cn[2]; chead[offset+3] = cn[3]; } return; } /* IRAFPUTC2 -- Insert character string into arbitrary part of v.1 IRAF header */ static void irafputc2 (string, irafheader, offset, nc) char *string; /* String to insert into header */ char *irafheader; /* IRAF image header */ int offset; /* Number of bytes to skip before string */ int nc; /* Maximum number of characters in string */ { char *irafstring; irafstring = (char *) calloc (2 * nc, 1); if (irafstring == NULL) { (void)fprintf(stderr, "IRAFPUTC2 Cannot allocate %d-byte variable\n", 2 * nc); } str2iraf (string, irafstring, nc); irafputc (irafstring, irafheader, offset, 2*nc); return; } /* IRAFPUTC -- Insert character string into arbitrary part of IRAF header */ static void irafputc (string, irafheader, offset, nc) char *string; /* String to insert into header */ char *irafheader; /* IRAF image header */ int offset; /* Number of bytes to skip before string */ int nc; /* Maximum number of characters in string */ { char *chead; int i; chead = irafheader; for (i = 0; i < nc; i++) chead[offset+i] = string[i]; return; } /* STR2IRAF -- Convert 1-byte/char string to IRAF 2-byte/char string */ static void str2iraf (string, irafstring, nchar) char *string; /* 1-byte/character string */ char *irafstring; /* IRAF 2-byte/character string */ int nchar; /* Maximum number of characters in IRAF string */ { int i, j, nc, nbytes; nc = strlen (string); /* Fill output string with zeroes */ nbytes = nchar * 2; for (i = 0; i < nbytes; i++) irafstring[i] = 0; /* If swapped, start with first byte of 2-byte characters */ if (headswap) j = 0; else j = 1; /* Move input characters to appropriate bytes of output */ for (i = 0; i < nchar; i++) { if (i > nc) irafstring[j] = 0; else irafstring[j] = string[i]; j = j + 2; } return; } /* IRAFSWAP -- Reverse bytes of any type of vector in place */ static void irafswap (bitpix, string, nbytes) int bitpix; /* Number of bits per pixel */ /* 16 = short, -16 = unsigned short, 32 = int */ /* -32 = float, -64 = double */ char *string; /* Address of starting point of bytes to swap */ int nbytes; /* Number of bytes to swap */ { switch (bitpix) { case 16: if (nbytes < 2) return; irafswap2 (string,nbytes); break; case 32: if (nbytes < 4) return; irafswap4 (string,nbytes); break; case -16: if (nbytes < 2) return; irafswap2 (string,nbytes); break; case -32: if (nbytes < 4) return; irafswap4 (string,nbytes); break; case -64: if (nbytes < 8) return; irafswap8 (string,nbytes); break; } return; } /* IRAFSWAP2 -- Swap bytes in string in place */ static void irafswap2 (string,nbytes) char *string; /* Address of starting point of bytes to swap */ int nbytes; /* Number of bytes to swap */ { char *sbyte, temp, *slast; slast = string + nbytes; sbyte = string; while (sbyte < slast) { temp = sbyte[0]; sbyte[0] = sbyte[1]; sbyte[1] = temp; sbyte= sbyte + 2; } return; } /* IRAFSWAP4 -- Reverse bytes of Integer*4 or Real*4 vector in place */ static void irafswap4 (string,nbytes) char *string; /* Address of Integer*4 or Real*4 vector */ int nbytes; /* Number of bytes to reverse */ { char *sbyte, *slast; char temp0, temp1, temp2, temp3; slast = string + nbytes; sbyte = string; while (sbyte < slast) { temp3 = sbyte[0]; temp2 = sbyte[1]; temp1 = sbyte[2]; temp0 = sbyte[3]; sbyte[0] = temp0; sbyte[1] = temp1; sbyte[2] = temp2; sbyte[3] = temp3; sbyte = sbyte + 4; } return; } /* IRAFSWAP8 -- Reverse bytes of Real*8 vector in place */ static void irafswap8 (string,nbytes) char *string; /* Address of Real*8 vector */ int nbytes; /* Number of bytes to reverse */ { char *sbyte, *slast; char temp[8]; slast = string + nbytes; sbyte = string; while (sbyte < slast) { temp[7] = sbyte[0]; temp[6] = sbyte[1]; temp[5] = sbyte[2]; temp[4] = sbyte[3]; temp[3] = sbyte[4]; temp[2] = sbyte[5]; temp[1] = sbyte[6]; temp[0] = sbyte[7]; sbyte[0] = temp[0]; sbyte[1] = temp[1]; sbyte[2] = temp[2]; sbyte[3] = temp[3]; sbyte[4] = temp[4]; sbyte[5] = temp[5]; sbyte[6] = temp[6]; sbyte[7] = temp[7]; sbyte = sbyte + 8; } return; } /* Set flag if machine on which program is executing is not FITS byte order * ( i.e., if it is an Alpha or PC instead of a Sun ) */ static int machswap () { char *ctest; int itest; itest = 1; ctest = (char *)&itest; if (*ctest) return (1); else return (0); } /* ISIRAF -- return 1 if IRAF imh file, else 0 */ int isiraf (filename) char *filename; /* Name of file for which to find size */ { if (strchr (filename, '=')) return (0); else if (strsrch (filename, ".imh")) return (1); else return (0); } /* IRAFSIZE -- return size of file in bytes */ static int irafsize (diskfile) FILE *diskfile; /* Descriptor of file for which to find size */ { long filesize; long offset; offset = (long) 0; /* Move to end of the file */ if (fseek (diskfile, offset, SEEK_END) == 0) { /* Position is the size of the file */ filesize = ftell (diskfile); /* Move file pointer back tot he start of the file */ fseek (diskfile, offset, SEEK_SET); } else filesize = -1; return (filesize); } /* Feb 15 1996 New file * Apr 10 1996 Add more documentation * Apr 17 1996 Print error message on open failure * Jun 5 1996 Add byte swapping (reversal); use streams * Jun 10 1996 Make fixes after running lint * Jun 12 1996 Use IMSWAP subroutines instead of local ones * Jul 3 1996 Go back to using local IRAFSWAP subroutines * Jul 3 1996 Write to pixel file from FITS header * Jul 10 1996 Allocate all headers * Aug 13 1996 Add unistd.h to include list * Aug 26 1996 Allow 1-d images; fix comments; fix arguments after lint * Aug 26 1996 Add IRAF header lingth argument to IRAFWIMAGE and IRAFWHEAD * Aug 28 1996 Clean up code in IRAF2FITS * Aug 30 1996 Use write instead of fwrite * Sep 4 1996 Fix write mode bug * Oct 15 1996 Drop unused variables * Oct 17 1996 Minor fix after lint; cast arguments to STR2IRAF * * May 15 1997 Fix returned header length in IRAF2FITS * Dec 19 1997 Add IRAF version 2 .imh files * * Jan 2 1998 Allow uneven length of user parameter lines in IRAF headers * Jan 6 1998 Fix output of imh2 headers; allow newlines in imh1 headers * Jan 14 1998 Handle byte reversing correctly * Apr 17 1998 Add new IRAF data types unsigned char and unsigned short * Apr 30 1998 Fix error return if illegal data type after Allan Brighton * May 15 1998 Delete header keywords used for IRAF binary values * May 15 1998 Fix bug so FITS OBJECT is put into IRAF title * May 26 1998 Fix bug in fits2iraf keeping track of end of header * May 27 1998 Include fitsio.h instead of fitshead.h * Jun 4 1998 Write comments into header for converted IRAF binary values * Jun 4 1998 Pad FITS strings to 8 character minimum * Jul 24 1998 Write header file length to IRAF header file * Jul 27 1998 Print error messages to stderr for all failed malloc's * Jul 27 1998 Fix bug padding FITS header with spaces in iraf2fits * Jul 27 1998 Write modification time to IRAF header file * Aug 6 1998 Change fitsio.h to fitsfile.h; imhio.c to imhfile.c * Oct 1 1998 Set irafswap flag only once per file * Oct 5 1998 Add subroutines irafsize() and isiraf() * Nov 16 1998 Fix byte-swap checking * * Jan 27 1999 Read and write all of 3D image if one dimension is =1 * Jul 13 1999 Improve error messages; change irafsize() argument to fd * Sep 22 1999 Don't copy OBJECT keyword from .imh file; use binary title * Oct 14 1999 Set FITS header length * Oct 20 1999 Allocate 5000 extra bytes for IRAF header * Nov 2 1999 Fix getclocktime() to use only time.h subroutines * Nov 2 1999 Add modification date and time to FITS header in iraf2fits() * Nov 24 1999 Delete HEADSWAP, IMHVER, DATE-MOD from header before writing * Nov 29 1999 Delete PIXSWAP, IRAF-MIN, IRAF-MAX from header before writing * * Jan 13 2000 Fix bug which dropped characters in iraf2fits() * Feb 3 2000 Declare timezone long, not time_t; drop unused variable * Mar 7 2000 Add more code to keep pixel file path short * Mar 10 2000 Fix bugs when writing .imh file headers * Mar 21 2000 Change computation of IRAF time tags to use only data structure * Mar 22 2000 Move IRAF time tag computation to lt2tsi() in dateutil.c * Mar 24 2000 Use Unix file update time if none in header * Mar 27 2000 Use hputm() to save file paths up to 256 characters * Mar 27 2000 Write filename comments after 1st keyword with short value * Mar 27 2000 Allocate pixel file name in same_path to imh2 length * Mar 29 2000 Add space after last linefeed of header in fits2iraf() * Apr 28 2000 Dimension pixname in irafwimage() * May 1 2000 Fix code for updating pixel file name with HDR$ in fits2iraf() * Jun 2 2000 Drop unused variables in fits2iraf() after lint * Jun 12 2000 If pixel filename has no / or $, use same path as header file * Sep 6 2000 Use header directory if pixel file not found at its pathname * * Jan 11 2001 Print all messages to stderr * Aug 24 2001 In isiraf(), return 0 if argument contains an equal sign * * Apr 8 2002 Fix bug in error message for unidentified nbits in fits2iraf() * * Feb 4 2003 Open catalog file rb instead of r (Martin Ploner, Bern) * Oct 31 2003 Read image only in irafrimage() if physical dimension > image dim. * Nov 3 2003 Set NAXISi to image, not physical dimensions in iraf2fits() * * Jun 13 2005 Drop trailing spaces on pixel file name * * Jun 20 2006 Initialize uninitialized variables * * Jan 4 2007 Change hputr4() calls to send pointer to value * Jan 8 2007 Drop unused variable nbx in irafrimage() * Jan 8 2007 Align header and image buffers properly by 4 and by BITPIX * * May 20 2011 Free newpixname, not pixname in irafwimage() * * Mar 27 2012 Fix pixname's appending to newpixname to avoid overflow */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/hput.c0000664000175000017500000007720713047255533020622 0ustar mattymatty00000000000000/*** File libwcs/hput.c *** September 9, 2011 *** By Jessica Mink, jmink@cfa.harvard.edu *** Harvard-Smithsonian Center for Astrophysics *** Copyright (C) 1995-2011 *** Smithsonian Astrophysical Observatory, Cambridge, MA, USA This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Correspondence concerning WCSTools should be addressed as follows: Internet email: jmink@cfa.harvard.edu Postal address: Jessica Mink Smithsonian Astrophysical Observatory 60 Garden St. Cambridge, MA 02138 USA * Module: hput.c (Put FITS Header parameter values) * Purpose: Implant values for parameters into FITS header string * Subroutine: hputi4 (hstring,keyword,ival) sets int ival * Subroutine: hputr4 (hstring,keyword,rval) sets real*4 rval * Subroutine: hputr8 (hstring,keyword,dval) sets real*8 dval * Subroutine: hputnr8 (hstring,keyword,ndec,dval) sets real*8 dval * Subroutine: hputra (hstring,keyword,lval) sets right ascension as string * Subroutine: hputdec (hstring,keyword,lval) sets declination as string * Subroutine: hputl (hstring,keyword,lval) sets logical lval * Subroutine: hputs (hstring,keyword,cval) sets character string adding '' * Subroutine: hputm (hstring,keyword,cval) sets multi-line character string * Subroutine: hputc (hstring,keyword,cval) sets character string cval * Subroutine: hdel (hstring,keyword) deletes entry for keyword keyword * Subroutine: hadd (hplace,keyword) adds entry for keyword at hplace * Subroutine: hchange (hstring,keyword1,keyword2) changes keyword for entry * Subroutine: hputcom (hstring,keyword,comment) sets comment for parameter keyword * Subroutine: ra2str (out, lstr, ra, ndec) converts RA from degrees to string * Subroutine: dec2str (out, lstr, dec, ndec) converts Dec from degrees to string * Subroutine: deg2str (out, lstr, deg, ndec) converts degrees to string * Subroutine: num2str (out, num, field, ndec) converts number to string * Subroutine: getltime () returns current local time as ISO-style string * Subroutine: getutime () returns current UT as ISO-style string */ #include #include /* NULL, strlen, strstr, strcpy */ #include #include #include #include "fitshead.h" static int verbose=0; /* Set to 1 to print error messages and other info */ static void fixnegzero(); /* HPUTI4 - Set int keyword = ival in FITS header string */ int hputi4 (hstring,keyword,ival) char *hstring; /* FITS-style header information in the format = {/ } each entry is padded with spaces to 80 characters */ const char *keyword; /* Name of the variable in header to be returned. If no line begins with this string, one is created. The first 8 characters of keyword must be unique. */ int ival; /* int number */ { char value[30]; /* Translate value from binary to ASCII */ sprintf (value,"%d",ival); /* Put value into header string */ return (hputc (hstring,keyword,value)); } /* HPUTR4 - Set float keyword = rval in FITS header string */ int hputr4 (hstring, keyword, rval) char *hstring; /* FITS header string */ const char *keyword; /* Keyword name */ const float *rval; /* float number */ { char value[30]; /* Translate value from binary to ASCII */ sprintf (value, "%f", *rval); /* Remove sign if string is -0 or extension thereof */ fixnegzero (value); /* Put value into header string */ return (hputc (hstring, keyword, value)); } /* HPUTR8 - Set double keyword = dval in FITS header string */ int hputr8 (hstring, keyword, dval) char *hstring; /* FITS header string */ const char *keyword; /* Keyword name */ const double dval; /* double number */ { char value[30]; /* Translate value from binary to ASCII */ sprintf (value, "%g", dval); /* Remove sign if string is -0 or extension thereof */ fixnegzero (value); /* Put value into header string */ return (hputc (hstring, keyword, value)); } /* HPUTNR8 - Set double keyword = dval in FITS header string */ int hputnr8 (hstring, keyword, ndec, dval) char *hstring; /* FITS header string */ const char *keyword; /* Keyword name */ const int ndec; /* Number of decimal places to print */ const double dval; /* double number */ { char value[30]; char format[8]; int i, lval; /* Translate value from binary to ASCII */ if (ndec < 0) { sprintf (format, "%%.%dg", -ndec); sprintf (value, format, dval); lval = (int) strlen (value); for (i = 0; i < lval; i++) if (value[i] == 'e') value[i] = 'E'; } else { sprintf (format, "%%.%df", ndec); sprintf (value, format, dval); } /* Remove sign if string is -0 or extension thereof */ fixnegzero (value); /* Put value into header string */ return (hputc (hstring, keyword, value)); } /* HPUTRA - Set double keyword = hh:mm:ss.sss in FITS header string */ int hputra (hstring, keyword, ra) char *hstring; /* FITS header string */ const char *keyword; /* Keyword name */ const double ra; /* Right ascension in degrees */ { char value[30]; /* Translate value from binary to ASCII */ ra2str (value, 30, ra, 3); /* Remove sign if string is -0 or extension thereof */ fixnegzero (value); /* Put value into header string */ return (hputs (hstring, keyword, value)); } /* HPUTDEC - Set double keyword = dd:mm:ss.sss in FITS header string */ int hputdec (hstring, keyword, dec) char *hstring; /* FITS header string */ const char *keyword; /* Keyword name */ const double dec; /* Declination in degrees */ { char value[30]; /* Translate value from binary to ASCII */ dec2str (value, 30, dec, 2); /* Remove sign if string is -0 or extension thereof */ fixnegzero (value); /* Put value into header string */ return (hputs (hstring, keyword, value)); } /* FIXNEGZERO -- Drop - sign from beginning of any string which is all zeros */ static void fixnegzero (string) char *string; { int i, lstr; if (string[0] != '-') return; /* Drop out if any non-zero digits in this string */ lstr = (int) strlen (string); for (i = 1; i < lstr; i++) { if (string[i] > '0' && string[i] <= '9') return; if (string[i] == 'd' || string[i] == 'e' || string[i] == ' ') break; } /* Drop - from start of string; overwrite string in place */ for (i = 1; i < lstr; i++) string[i-1] = string[i]; string[lstr-1] = (char) 0; return; } /* HPUTL - Set keyword = F if lval=0, else T, in FITS header string */ int hputl (hstring, keyword,lval) char *hstring; /* FITS header */ const char *keyword; /* Keyword name */ const int lval; /* logical variable (0=false, else true) */ { char value[8]; /* Translate value from binary to ASCII */ if (lval) strcpy (value, "T"); else strcpy (value, "F"); /* Put value into header string */ return (hputc (hstring,keyword,value)); } /* HPUTM - Set multi-line character string in FITS header string */ /* return number of keywords written */ int hputm (hstring,keyword,cval) char *hstring; /* FITS header */ const char *keyword; /* Keyword name root (6 characters or less) */ const char *cval; /* character string containing the value for variable keyword. trailing and leading blanks are removed. */ { int lroot, lcv, i, ii, nkw, lkw, lval; int comment = 0; const char *v; char keyroot[8], newkey[12], value[80]; char squot = 39; /* If COMMENT or HISTORY, use the same keyword on every line */ lkw = (int) strlen (keyword); if (lkw == 7 && (strncmp (keyword,"COMMENT",7) == 0 || strncmp (keyword,"HISTORY",7) == 0)) { comment = 1; lroot = 0; } /* Set up keyword root, shortening it to 6 characters, if necessary */ else { comment = 0; strcpy (keyroot, keyword); lroot = (int) strlen (keyroot); if (lroot > 6) { keyroot[6] = (char) 0; lroot = 6; } } /* Write keyword value one line of up to 67 characters at a time */ ii = '1'; nkw = 0; lcv = (int) strlen (cval); if (!comment) { strcpy (newkey, keyroot); strcat (newkey, "_"); newkey[lroot+2] = (char) 0; } v = cval; while (lcv > 0) { if (lcv > 67) lval = 67; else lval = lcv; value[0] = squot; for (i = 1; i <= lval; i++) value[i] = *v++; /* Pad short strings to 8 characters */ if (lval < 8) { for (i = lval+1; i < 9; i++) value[i] = ' '; lval = 8; } value[lval+1] = squot; value[lval+2] = (char) 0; /* Add this line to the header */ if (comment) i = hputc (hstring, keyroot, value); else { newkey[lroot+1] = ii; ii++; i = hputc (hstring, newkey, value); } if (i != 0) return (i); nkw++; if (lcv > 67) lcv = lcv - 67; else break; } return (nkw); } /* HPUTS - Set character string keyword = 'cval' in FITS header string */ int hputs (hstring,keyword,cval) char *hstring; /* FITS header */ const char *keyword; /* Keyword name */ const char *cval; /* character string containing the value for variable keyword. trailing and leading blanks are removed. */ { char squot = 39; char value[80]; int lcval, i, lkeyword; /* If COMMENT or HISTORY, just add it as is */ lkeyword = (int) strlen (keyword); if (lkeyword == 7 && (strncmp (keyword,"COMMENT",7) == 0 || strncmp (keyword,"HISTORY",7) == 0)) return (hputc (hstring,keyword,cval)); /* find length of variable string */ lcval = (int) strlen (cval); if (lcval > 67) lcval = 67; /* Put single quote at start of string */ value[0] = squot; strncpy (&value[1],cval,lcval); /* If string is less than eight characters, pad it with spaces */ if (lcval < 8) { for (i = lcval; i < 8; i++) { value[i+1] = ' '; } lcval = 8; } /* Add single quote and null to end of string */ value[lcval+1] = squot; value[lcval+2] = (char) 0; /* Put value into header string */ return (hputc (hstring,keyword,value)); } /* HPUTC - Set character string keyword = value in FITS header string */ /* Return -1 if error, 0 if OK */ int hputc (hstring,keyword,value) char *hstring; const char *keyword; const char *value; /* character string containing the value for variable keyword. trailing and leading blanks are removed. */ { char squot = 39; char line[100]; char newcom[50]; char *vp, *v1, *v2, *q1, *q2, *c1, *ve; int lkeyword, lcom, lval, lc, lv1, lhead, lblank, ln, nc, i; /* Find length of keyword, value, and header */ lkeyword = (int) strlen (keyword); lval = (int) strlen (value); lhead = gethlength (hstring); /* If COMMENT or HISTORY, always add it just before the END */ if (lkeyword == 7 && (strncmp (keyword,"COMMENT",7) == 0 || strncmp (keyword,"HISTORY",7) == 0)) { /* First look for blank lines before END */ v1 = blsearch (hstring, "END"); /* Otherwise, create a space for it at the end of the header */ if (v1 == NULL) { /* Find end of header */ v1 = ksearch (hstring,"END"); /* Align pointer at start of 80-character line */ lc = v1 - hstring; ln = lc / 80; nc = ln * 80; v1 = hstring + nc; v2 = v1 + 80; /* If header length is exceeded, return error code */ if (v2 - hstring > lhead) { return (-1); } /* Move END down 80 characters */ strncpy (v2, v1, 80); } else v2 = v1 + 80; /* Insert keyword */ strncpy (v1,keyword,7); /* Pad with spaces */ for (vp = v1+lkeyword; vp < v2; vp++) *vp = ' '; if (lval > 71) lv1 = 71; else lv1 = lval; /* Insert comment */ strncpy (v1+9,value,lv1); return (0); } /* Otherwise search for keyword */ else v1 = ksearch (hstring,keyword); /* If parameter is not found, find a place to put it */ if (v1 == NULL) { /* First look for blank lines before END */ v1 = blsearch (hstring, "END"); /* Otherwise, create a space for it at the end of the header */ if (v1 == NULL) { ve = ksearch (hstring,"END"); v1 = ve; /* Align pointer at start of 80-character line */ lc = v1 - hstring; ln = lc / 80; nc = ln * 80; v1 = hstring + nc; v2 = v1 + 80; /* If header length is exceeded, return error code */ if (v2 - hstring > lhead) { return (-1); } strncpy (v2, ve, 80); } else v2 = v1 + 80; lcom = 0; newcom[0] = 0; } /* Otherwise, extract the entry for this keyword from the header */ else { /* Align pointer at start of 80-character line */ lc = v1 - hstring; ln = lc / 80; nc = ln * 80; v1 = hstring + nc; v2 = v1 + 80; strncpy (line, v1, 80); line[80] = 0; v2 = v1 + 80; /* check for quoted value */ q1 = strchr (line, squot); if (q1 != NULL) { q2 = strchr (q1+1,squot); if (q2 != NULL) c1 = strchr (q2,'/'); else c1 = strrchr (line+79,'/'); } else c1 = strchr (line,'/'); /* extract comment and discount trailing spaces */ if (c1 != NULL) { lcom = 80 - (c1 + 2 - line); strncpy (newcom, c1+2, lcom); vp = newcom + lcom - 1; while (vp-- > newcom && *vp == ' ') lcom--; } else { newcom[0] = 0; lcom = 0; } } /* Fill new entry with spaces */ for (vp = v1; vp < v2; vp++) *vp = ' '; /* Copy keyword to new entry */ strncpy (v1, keyword, lkeyword); /* Add parameter value in the appropriate place */ vp = v1 + 8; *vp = '='; vp = v1 + 9; *vp = ' '; vp = vp + 1; if (*value == squot) { strncpy (vp, value, lval); if (lval+12 > 31) lc = lval + 12; else lc = 30; } else { vp = v1 + 30 - lval; strncpy (vp, value, lval); lc = 30; } /* Add comment in the appropriate place */ if (lcom > 0) { if (lc+2+lcom > 80) lcom = 77 - lc; vp = v1 + lc; /* Jul 16 1997: was vp = v1 + lc * 2 */ *vp++ = ' '; *vp++ = '/'; *vp++ = ' '; lblank = v2 - vp; for (i = 0; i < lblank; i++) vp[i] = ' '; if (lcom > lblank) lcom = lblank; strncpy (vp, newcom, lcom); } if (verbose) { if (lcom > 0) fprintf (stderr,"HPUT: %s = %s / %s\n",keyword, value, newcom); else fprintf (stderr,"HPUT: %s = %s\n",keyword, value); } return (0); } /* HPUTCOM - Set comment for keyword or on line in FITS header string */ int hputcom (hstring,keyword,comment) char *hstring; const char *keyword; const char *comment; { char squot, slash, space; char line[100]; int lkeyword, lcom, lhead, i, lblank, ln, nc, lc; char *vp, *v1, *v2, *c0, *c1, *q1, *q2; squot = (char) 39; slash = (char) 47; space = (char) 32; /* Find length of variable name */ lkeyword = (int) strlen (keyword); lhead = gethlength (hstring); lcom = (int) strlen (comment); /* If COMMENT or HISTORY, always add it just before the END */ if (lkeyword == 7 && (strncmp (keyword,"COMMENT",7) == 0 || strncmp (keyword,"HISTORY",7) == 0)) { /* Find end of header */ v1 = ksearch (hstring,"END"); /* Align pointer at start of 80-character line */ lc = v1 - hstring; ln = lc / 80; nc = ln * 80; v1 = hstring + nc; v2 = v1 + 80; /* If header length is exceeded, return error code */ if (v2 - hstring > lhead) { return (-1); } /* Move END down 80 characters */ strncpy (v2, v1, 80); /* blank out new line and insert keyword */ for (vp = v1; vp < v2; vp++) *vp = ' '; strncpy (v1, keyword, lkeyword); c0 = v1 + lkeyword; } /* Search header string for variable name */ else { v1 = ksearch (hstring,keyword); /* If parameter is not found, return without doing anything */ if (v1 == NULL) { if (verbose) fprintf (stderr,"HPUTCOM: %s not found\n",keyword); return (-1); } /* Align pointer at start of 80-character line */ lc = v1 - hstring; ln = lc / 80; nc = ln * 80; v1 = hstring + nc; v2 = v1 + 80; /* Extract entry for this variable from the header */ strncpy (line, v1, 80); line[80] = '\0'; /* Null-terminate line before strchr call */ /* check for quoted value */ q1 = strchr (line,squot); c1 = strchr (line,slash); if (q1 != NULL) { if (c1 != NULL && q1 < c1) { q2 = strchr (q1+1, squot); if (q2 == NULL) { q2 = c1 - 1; while (*q2 == space) q2--; q2++; } else if (c1 < q2) c1 = strchr (q2, slash); } else if (c1 == NULL) { q2 = strchr (q1+1, squot); if (q2 == NULL) { q2 = line + 79; while (*q2 == space) q2--; q2++; } } else q1 = NULL; q2 = NULL; } else q2 = NULL; if (c1 != NULL) c0 = v1 + (c1 - line) - 1; else if (q2 == NULL || q2-line < 30) c0 = v1 + 30; else c0 = v1 + (q2 - line) + 1; /* allan: 1997-09-30, was c0=q2+2 */ /* If comment will not fit at all, return */ if (c0 - v1 > 77) return (-1); strncpy (c0, " / ",3); } /* Create new entry */ if (lcom > 0) { c1 = c0 + 3; lblank = v1 + 79 - c1; if (lcom > lblank) lcom = lblank; for (i = 0; i < lblank; i++) c1[i] = ' '; strncpy (c1, comment, lcom); } if (verbose) { fprintf (stderr,"HPUTCOM: %s / %s\n",keyword,comment); } return (0); } static int leaveblank = 0; /* If 1, leave blank line when deleting */ void setleaveblank (lb) int lb; { leaveblank = lb; return; } static int headshrink=1; /* Set to 1 to drop line after deleting keyword */ void setheadshrink (hsh) int hsh; {headshrink = hsh; return;} /* HDEL - Set character string keyword = value in FITS header string * returns 1 if entry deleted, else 0 */ int hdel (hstring,keyword) char *hstring; /* FITS header */ const char *keyword; /* Keyword of entry to be deleted */ { char *v, *v1, *v2, *ve; /* Search for keyword */ v1 = ksearch (hstring,keyword); /* If keyword is not found, return header unchanged */ if (v1 == NULL) { return (0); } /* Find end of header */ ve = ksearch (hstring,"END"); /* If headshrink is 0, leave END where it is */ if (!leaveblank && !headshrink) ve = ve - 80; /* Cover deleted keyword line with spaces */ if (leaveblank) { v2 = v1 + 80; for (v = ve; v < v2; v++) *v = ' '; } /* Shift rest of header up one line */ else { for (v = v1; v < ve; v = v + 80) { v2 = v + 80; strncpy (v, v2, 80); } /* Cover former last line with spaces */ v2 = ve + 80; for (v = ve; v < v2; v++) *v = ' '; } return (1); } /* HADD - Add character string keyword = value to FITS header string * returns 1 if entry added, else 0 * Call hputx() to put value into entry */ int hadd (hplace, keyword) char *hplace; /* FITS header position for new keyword */ const char *keyword; /* Keyword of entry to be deleted */ { char *v, *v1, *v2, *ve; int i, lkey; /* Find end of header */ ve = ksearch (hplace,"END"); /* If END is not found, return header unchanged */ if (ve == NULL) { return (0); } v1 = hplace; /* Shift rest of header down one line */ /* limit bug found by Paolo Montegriffo fixed 2000-04-19 */ for (v = ve; v >= v1; v = v - 80) { v2 = v + 80; strncpy (v2, v, 80); } /* Cover former first line with new keyword */ lkey = (int) strlen (keyword); strncpy (hplace, keyword, lkey); if (lkey < 8) { for (i = lkey; i < 8; i++) hplace[i] = ' '; hplace[8] = '='; } for (i = 9; i < 80; i++) hplace[i] = ' '; return (1); } /* HCHANGE - Changes keyword for entry from keyword1 to keyword2 in FITS header string * returns 1 if entry changed, else 0 */ int hchange (hstring, keyword1, keyword2) char *hstring; /* FITS header */ const char *keyword1; /* Keyword to be changed */ const char *keyword2; /* New keyword name */ { char *v, *v1; const char *v2; int lv2, i; /* Search for keyword */ v1 = ksearch (hstring,keyword1); /* If keyword is not found, return header unchanged */ if (!v1) return (0); else { lv2 = (int) strlen (keyword2); v = v1; v2 = keyword2; for (i = 0; i < 8; i++) { if (i < lv2) v[i] = v2[i]; else v[i] = ' '; } } return (1); } /* Write the right ascension ra in sexagesimal format into string*/ void ra2str (string, lstr, ra, ndec) char *string; /* Character string (returned) */ int lstr; /* Maximum number of characters in string */ double ra; /* Right ascension in degrees */ int ndec; /* Number of decimal places in seconds */ { double a,b; double seconds; char tstring[64]; int hours; int minutes; int isec, ltstr; double dsgn; /* Keep RA between 0 and 360 */ if (ra < 0.0 ) { ra = -ra; dsgn = -1.0; } else dsgn = 1.0; ra = fmod(ra, 360.0); ra *= dsgn; if (ra < 0.0) ra = ra + 360.0; a = ra / 15.0; /* Convert to hours */ hours = (int) a; /* Compute minutes */ b = (a - (double)hours) * 60.0; minutes = (int) b; /* Compute seconds */ seconds = (b - (double)minutes) * 60.0; if (ndec > 5) { if (seconds > 59.999999) { seconds = 0.0; minutes = minutes + 1; } if (minutes > 59) { minutes = 0; hours = hours + 1; } hours = hours % 24; (void) sprintf (tstring,"%02d:%02d:%09.6f",hours,minutes,seconds); } else if (ndec > 4) { if (seconds > 59.99999) { seconds = 0.0; minutes = minutes + 1; } if (minutes > 59) { minutes = 0; hours = hours + 1; } hours = hours % 24; (void) sprintf (tstring,"%02d:%02d:%08.5f",hours,minutes,seconds); } else if (ndec > 3) { if (seconds > 59.9999) { seconds = 0.0; minutes = minutes + 1; } if (minutes > 59) { minutes = 0; hours = hours + 1; } hours = hours % 24; (void) sprintf (tstring,"%02d:%02d:%07.4f",hours,minutes,seconds); } else if (ndec > 2) { if (seconds > 59.999) { seconds = 0.0; minutes = minutes + 1; } if (minutes > 59) { minutes = 0; hours = hours + 1; } hours = hours % 24; (void) sprintf (tstring,"%02d:%02d:%06.3f",hours,minutes,seconds); } else if (ndec > 1) { if (seconds > 59.99) { seconds = 0.0; minutes = minutes + 1; } if (minutes > 59) { minutes = 0; hours = hours + 1; } hours = hours % 24; (void) sprintf (tstring,"%02d:%02d:%05.2f",hours,minutes,seconds); } else if (ndec > 0) { if (seconds > 59.9) { seconds = 0.0; minutes = minutes + 1; } if (minutes > 59) { minutes = 0; hours = hours + 1; } hours = hours % 24; (void) sprintf (tstring,"%02d:%02d:%04.1f",hours,minutes,seconds); } else { isec = (int)(seconds + 0.5); if (isec > 59) { isec = 0; minutes = minutes + 1; } if (minutes > 59) { minutes = 0; hours = hours + 1; } hours = hours % 24; (void) sprintf (tstring,"%02d:%02d:%02d",hours,minutes,isec); } /* Move formatted string to returned string */ ltstr = (int) strlen (tstring); if (ltstr < lstr-1) strcpy (string, tstring); else { strncpy (string, tstring, lstr-1); string[lstr-1] = 0; } return; } /* Write the variable a in sexagesimal format into string */ void dec2str (string, lstr, dec, ndec) char *string; /* Character string (returned) */ int lstr; /* Maximum number of characters in string */ double dec; /* Declination in degrees */ int ndec; /* Number of decimal places in arcseconds */ { double a, b, dsgn, deg1; double seconds; char sign; int degrees; int minutes; int isec, ltstr; char tstring[64]; /* Keep angle between -180 and 360 degrees */ deg1 = dec; if (deg1 < 0.0 ) { deg1 = -deg1; dsgn = -1.0; } else dsgn = 1.0; deg1 = fmod(deg1, 360.0); deg1 *= dsgn; if (deg1 <= -180.0) deg1 = deg1 + 360.0; a = deg1; /* Set sign and do all the rest with a positive */ if (a < 0) { sign = '-'; a = -a; } else sign = '+'; /* Convert to degrees */ degrees = (int) a; /* Compute minutes */ b = (a - (double)degrees) * 60.0; minutes = (int) b; /* Compute seconds */ seconds = (b - (double)minutes) * 60.0; if (ndec > 5) { if (seconds > 59.999999) { seconds = 0.0; minutes = minutes + 1; } if (minutes > 59) { minutes = 0; degrees = degrees + 1; } (void) sprintf (tstring,"%c%02d:%02d:%09.6f",sign,degrees,minutes,seconds); } else if (ndec > 4) { if (seconds > 59.99999) { seconds = 0.0; minutes = minutes + 1; } if (minutes > 59) { minutes = 0; degrees = degrees + 1; } (void) sprintf (tstring,"%c%02d:%02d:%08.5f",sign,degrees,minutes,seconds); } else if (ndec > 3) { if (seconds > 59.9999) { seconds = 0.0; minutes = minutes + 1; } if (minutes > 59) { minutes = 0; degrees = degrees + 1; } (void) sprintf (tstring,"%c%02d:%02d:%07.4f",sign,degrees,minutes,seconds); } else if (ndec > 2) { if (seconds > 59.999) { seconds = 0.0; minutes = minutes + 1; } if (minutes > 59) { minutes = 0; degrees = degrees + 1; } (void) sprintf (tstring,"%c%02d:%02d:%06.3f",sign,degrees,minutes,seconds); } else if (ndec > 1) { if (seconds > 59.99) { seconds = 0.0; minutes = minutes + 1; } if (minutes > 59) { minutes = 0; degrees = degrees + 1; } (void) sprintf (tstring,"%c%02d:%02d:%05.2f",sign,degrees,minutes,seconds); } else if (ndec > 0) { if (seconds > 59.9) { seconds = 0.0; minutes = minutes + 1; } if (minutes > 59) { minutes = 0; degrees = degrees + 1; } (void) sprintf (tstring,"%c%02d:%02d:%04.1f",sign,degrees,minutes,seconds); } else { isec = (int)(seconds + 0.5); if (isec > 59) { isec = 0; minutes = minutes + 1; } if (minutes > 59) { minutes = 0; degrees = degrees + 1; } (void) sprintf (tstring,"%c%02d:%02d:%02d",sign,degrees,minutes,isec); } /* Move formatted string to returned string */ ltstr = (int) strlen (tstring); if (ltstr < lstr-1) strcpy (string, tstring); else { strncpy (string, tstring, lstr-1); string[lstr-1] = 0; } return; } /* Write the angle a in decimal format into string */ void deg2str (string, lstr, deg, ndec) char *string; /* Character string (returned) */ int lstr; /* Maximum number of characters in string */ double deg; /* Angle in degrees */ int ndec; /* Number of decimal places in degree string */ { char degform[8]; int field, ltstr; char tstring[64]; double deg1; double dsgn; /* Keep angle between -180 and 360 degrees */ deg1 = deg; if (deg1 < 0.0 ) { deg1 = -deg1; dsgn = -1.0; } else dsgn = 1.0; deg1 = fmod(deg1, 360.0); deg1 *= dsgn; if (deg1 <= -180.0) deg1 = deg1 + 360.0; /* Write angle to string, adding 4 digits to number of decimal places */ field = ndec + 4; if (ndec > 0) { sprintf (degform, "%%%d.%df", field, ndec); sprintf (tstring, degform, deg1); } else { sprintf (degform, "%%%4d", field); sprintf (tstring, degform, (int)deg1); } /* Move formatted string to returned string */ ltstr = (int) strlen (tstring); if (ltstr < lstr-1) strcpy (string, tstring); else { strncpy (string, tstring, lstr-1); string[lstr-1] = 0; } return; } /* Write the variable a in decimal format into field-character string */ void num2str (string, num, field, ndec) char *string; /* Character string (returned) */ double num; /* Number */ int field; /* Number of characters in output field (0=any) */ int ndec; /* Number of decimal places in degree string */ { char numform[8]; if (field > 0) { if (ndec > 0) { sprintf (numform, "%%%d.%df", field, ndec); sprintf (string, numform, num); } else { sprintf (numform, "%%%dd", field); sprintf (string, numform, (int)num); } } else { if (ndec > 0) { sprintf (numform, "%%.%df", ndec); sprintf (string, numform, num); } else { sprintf (string, "%d", (int)num); } } return; } /* Dec 14 1995 Original subroutines * Feb 5 1996 Added HDEL to delete keyword entry from FITS header * Feb 7 1996 Add EOS to LINE in HPUTC * Feb 21 1996 Add RA2STR and DEC2STR string routines * Jul 19 1996 Add HPUTRA and HPUTDEC * Jul 22 1996 Add HCHANGE to change keywords * Aug 5 1996 Add HPUTNR8 to save specific number of decimal places * Oct 15 1996 Fix spelling * Nov 1 1996 Add DEG2STR to set specific number of decimal places * Nov 1 1996 Allow DEC2STR to handle upt to 6 decimal places * * Mar 20 1997 Fix format error in DEG2STR * Jul 7 1997 Fix 2 errors in HPUTCOM found by Allan Brighton * Jul 16 1997 Fix error in HPUTC found by Allan Brighton * Jul 17 1997 Fix error in HPUTC found by Allan Brighton * Sep 30 1997 Fix error in HPUTCOM found by Allan Brighton * Dec 15 1997 Fix minor bugs after lint * Dec 31 1997 Always put two hour digits in RA2STR * * Feb 25 1998 Add HADD to insert keywords at specific locations * Mar 27 1998 If n is negative, write g format in HPUTNR8() * Apr 24 1998 Add NUM2STR() for easy output formatting * Apr 30 1998 Use BLSEARCH() to overwrite blank lines before END * May 27 1998 Keep Dec between -90 and +90 in DEC2STR() * May 28 1998 Keep RA between 0 and 360 in RA2STR() * Jun 2 1998 Fix bug when filling in blank lines before END * Jun 24 1998 Add string length to ra2str(), dec2str(), and deg2str() * Jun 25 1998 Make string converstion subroutines more robust * Aug 31 1998 Add getltime() and getutime() * Sep 28 1998 Null-terminate comment in HPUTCOM (Allan Brighton) * Oct 1 1998 Change clock declaration in getltime() from int (Allan Brighton) * * Jan 28 1999 Fix bug to avoid writing HISTORY or COMMENT past 80 characters * Jul 14 1999 Pad string in hputs() to minimum of 8 characters * Aug 16 1999 Keep angle between -180 and +360 in dec2str() * Oct 6 1999 Reallocate header buffer if it is too small in hputc() * Oct 14 1999 Do not reallocate header; return error if not successful * * Mar 2 2000 Do not add quotes if adding HISTORY or COMMENT with hputs() * Mar 22 2000 Move getutime() and getltime() to dateutil.c * Mar 27 2000 Add hputm() for muti-line keywords * Mar 27 2000 Fix bug testing for space to fit comment in hputcom() * Apr 19 2000 Fix bug in hadd() which overwrote line * Jun 2 2000 Dropped unused variable lv in hputm() after lint * Jul 20 2000 Drop unused variables blank and i in hputc() * * Jan 11 2001 Print all messages to stderr * Jan 18 2001 Drop declaration of blsearch(); it is in fitshead.h * * Jan 4 2002 Fix placement of comments * * Jul 1 2004 Add headshrink to optionally keep blank lines in header * Sep 3 2004 Fix bug so comments are not pushed onto next line if long value * Sep 16 2004 Add fixnegzero() to avoid putting signed zero values in header * * May 22 2006 Add option to leave blank line when deleting a keyword * Jun 15 2006 Fix comment alignment in hputc() and hputcom() * Jun 20 2006 Initialized uninitialized variables in hputm() and hputcom() * * Jan 4 2007 Declare keyword to be const * Jan 4 2007 Drop unused subroutine hputi2() * Jan 5 2007 Drop ksearch() declarations; it is now in fitshead.h * Jan 16 2007 Fix bugs in ra2str() and dec2str() so ndec=0 works * Aug 20 2007 Fix bug so comments after quoted keywords work * Aug 22 2007 If closing quote not found, make one up * * Sep 9 2011 Always initialize q2 and lroot */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/fitsfile.c0000664000175000017500000017262613047255533021450 0ustar mattymatty00000000000000/*** File libwcs/fitsfile.c *** July 25, 2014 *** By Jessica Mink, jmink@cfa.harvard.edu *** Harvard-Smithsonian Center for Astrophysics *** Copyright (C) 1996-2014 *** Smithsonian Astrophysical Observatory, Cambridge, MA, USA This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Correspondence concerning WCSTools should be addressed as follows: Internet email: jmink@cfa.harvard.edu Postal address: Jessica Mink Smithsonian Astrophysical Observatory 60 Garden St. Cambridge, MA 02138 USA * Module: fitsfile.c (FITS file reading and writing) * Purpose: Read and write FITS image and table files * fitsropen (inpath) * Open a FITS file for reading, returning a FILE pointer * fitsrhead (filename, lhead, nbhead) * Read FITS header and return it * fitsrtail (filename, lhead, nbhead) * Read appended FITS header and return it * fitsrsect (filename, nbhead, header, fd, x0, y0, nx, ny) * Read section of a FITS image, having already read the header * fitsrimage (filename, nbhead, header) * Read FITS image, having already ready the header * fitsrfull (filename, nbhead, header) * Read a FITS image of any dimension * fitsrtopen (inpath, nk, kw, nrows, nchar, nbhead) * Open a FITS table file for reading; return header information * fitsrthead (header, nk, kw, nrows, nchar, nbhead) * Extract FITS table information from a FITS header * fitsrtline (fd, nbhead, lbuff, tbuff, irow, nbline, line) * Read next line of FITS table file * ftgetr8 (entry, kw) * Extract column from FITS table line as double * ftgetr4 (entry, kw) * Extract column from FITS table line as float * ftgeti4 (entry, kw) * Extract column from FITS table line as int * ftgeti2 (entry, kw) * Extract column from FITS table line as short * ftgetc (entry, kw, string, maxchar) * Extract column from FITS table line as a character string * fitswimage (filename, header, image) * Write FITS header and image * fitswext (filename, header, image) * Write FITS header and image as extension to existing FITS file * fitswhdu (fd, filename, header, image) * Write FITS header and image as extension to file descriptor * fitscimage (filename, header, filename0) * Write FITS header and copy FITS image * fitswhead (filename, header) * Write FITS header and keep file open for further writing * fitswexhead (filename, header) * Write FITS header only to FITS extension without writing data * isfits (filename) * Return 1 if file is a FITS file, else 0 * fitsheadsize (header) * Return size of FITS header in bytes */ #include #ifndef VMS #include #endif #include #include #include #include #include #include "fitsfile.h" static int verbose=0; /* Print diagnostics */ static char fitserrmsg[80]; static int fitsinherit = 1; /* Append primary header to extension header */ void setfitsinherit (inh) int inh; {fitsinherit = inh; return;} static off_t ibhead = 0; /* Number of bytes read before header starts */ off_t getfitsskip() {return (ibhead);} /* FITSRHEAD -- Read a FITS header */ char * fitsrhead (filename, lhead, nbhead) char *filename; /* Name of FITS image file */ int *lhead; /* Allocated length of FITS header in bytes (returned) */ int *nbhead; /* Number of bytes before start of data (returned) */ /* This includes all skipped image extensions */ { int fd; char *header; /* FITS image header (filled) */ int extend; int nbytes,naxis, i; int ntry,nbr,irec,nrec, nbh, ipos, npos, nbprim, lprim, lext; int nax1, nax2, nax3, nax4, nbpix, ibpix, nblock, nbskip; char fitsbuf[2884]; char *headend; /* Pointer to last line of header */ char *headnext; /* Pointer to next line of header to be added */ int hdu; /* header/data unit counter */ int extnum; /* desired header data number (0=primary -1=first with data -2=use EXTNAME) */ char extname[32]; /* FITS extension name */ char extnam[32]; /* Desired FITS extension name */ char *ext; /* FITS extension name or number in header, if any */ char *pheader; /* Primary header (naxis is 0) */ char cext = 0; char *rbrac; /* Pointer to right bracket if present in file name */ char *mwcs; /* Pointer to WCS name separated by % */ char *newhead; /* New larger header */ int nbh0; /* Length of old too small header */ char *pheadend; int inherit = 1; /* Value of INHERIT keyword in FITS extension header */ int extfound = 0; /* Set to one if desired FITS extension is found */ int npcount; pheader = NULL; lprim = 0; header = NULL; /* Check for FITS WCS specification and ignore for file opening */ mwcs = strchr (filename, '%'); if (mwcs != NULL) *mwcs = (char) 0; /* Check for FITS extension and ignore for file opening */ rbrac = NULL; ext = strchr (filename, ','); if (ext == NULL) { ext = strchr (filename, '['); if (ext != NULL) { rbrac = strchr (filename, ']'); if (rbrac != NULL) *rbrac = (char) 0; } } if (ext != NULL) { cext = *ext; *ext = (char) 0; } /* Open the image file and read the header */ if (strncasecmp (filename,"stdin",5)) { fd = -1; fd = fitsropen (filename); } #ifndef VMS else { fd = STDIN_FILENO; extnum = -1; } #endif if (ext != NULL) { if (isnum (ext+1)) extnum = atoi (ext+1); else { extnum = -2; strcpy (extnam, ext+1); } } else extnum = -1; /* Repair the damage done to the file-name string during parsing */ if (ext != NULL) *ext = cext; if (rbrac != NULL) *rbrac = ']'; if (mwcs != NULL) *mwcs = '%'; if (fd < 0) { fprintf (stderr,"FITSRHEAD: cannot read file %s\n", filename); return (NULL); } nbytes = FITSBLOCK; *nbhead = 0; headend = NULL; nbh = FITSBLOCK * 20 + 4; header = (char *) calloc ((unsigned int) nbh, 1); (void) hlength (header, nbh); headnext = header; nrec = 1; hdu = 0; ibhead = 0; /* Read FITS header from input file one FITS block at a time */ irec = 0; ibhead = 0; while (irec < 500) { nbytes = FITSBLOCK; for (ntry = 0; ntry < 10; ntry++) { for (i = 0; i < 2884; i++) fitsbuf[i] = 0; nbr = read (fd, fitsbuf, nbytes); if (verbose) fprintf (stderr,"FITSRHEAD: %d header bytes read\n",nbr); /* Short records allowed only if they have the last header line */ if (nbr < nbytes) { headend = ksearch (fitsbuf,"END"); if (headend == NULL) { if (ntry < 9) { if (verbose) fprintf (stderr,"FITSRHEAD: %d / %d bytes read %d\n", nbr,nbytes,ntry); } else { snprintf(fitserrmsg,79,"FITSRHEAD: '%d / %d bytes of header read from %s\n" ,nbr,nbytes,filename); #ifndef VMS if (fd != STDIN_FILENO) #endif (void)close (fd); free (header); /* if (pheader != NULL) return (pheader); */ if (extnum != -1 && !extfound) { *ext = (char) 0; if (extnum < 0) { snprintf (fitserrmsg,79, "FITSRHEAD: Extension %s not found in file %s", extnam, filename); } else { snprintf (fitserrmsg,79, "FITSRHEAD: Extension %d not found in file %s", extnum, filename); } *ext = cext; } else if (hdu > 0) { snprintf (fitserrmsg,79, "FITSRHEAD: No extensions found in file %s", filename); hdu = 0; if (pheader != NULL) { *lhead = nbprim; *nbhead = nbprim; return (pheader); } break; } else { snprintf (fitserrmsg,79, "FITSRHEAD: No header found in file %s", filename); } return (NULL); } } else break; } else break; } /* Replace control characters and nulls with spaces */ for (i = 0; i < 2880; i++) if (fitsbuf[i] < 32 || i > nbr) fitsbuf[i] = 32; if (nbr < 2880) nbr = 2880; /* Move current FITS record into header string */ strncpy (headnext, fitsbuf, nbr); *nbhead = *nbhead + nbr; nrec = nrec + 1; *(headnext+nbr+1) = 0; ibhead = ibhead + 2880; if (verbose) fprintf (stderr,"FITSRHEAD: %d bytes in header\n",ibhead); /* Check to see if this is the final record in this header */ headend = ksearch (fitsbuf,"END"); if (headend == NULL) { /* Double size of header buffer if too small */ if (nrec * FITSBLOCK > nbh) { nbh0 = nbh - 4; nbh = (nrec * 2 * FITSBLOCK) + 4; newhead = (char *) calloc (1,(unsigned int) nbh); if (newhead) { for (i = 0; i < nbh0; i++) newhead[i] = header[i]; free (header); newhead[nbh-3] = (char) 0; header = newhead; (void) hlength (header, nbh); headnext = header + ((nrec-1) * FITSBLOCK); } else { fprintf (stderr,"FITSRHEAD: %d bytes cannot be allocated for header\n",nbh); exit (1); } } else headnext = headnext + FITSBLOCK; } else { naxis = 0; hgeti4 (header,"NAXIS",&naxis); /* If header has no data, save it for appending to desired header */ if (naxis < 1) { nbprim = nrec * FITSBLOCK; headend = ksearch (header,"END"); lprim = headend + 80 - header; pheader = (char *) calloc ((unsigned int) nbprim, 1); for (i = 0; i < lprim; i++) pheader[i] = header[i]; for (i = lprim; i < nbprim; i++) pheader[i] = ' '; } /* If header has no data, start with the next record */ if (naxis < 1 && extnum == -1) { extend = 0; hgetl (header,"EXTEND",&extend); if (naxis == 0 && extend) { headnext = header; *headend = ' '; headend = NULL; nrec = 1; hdu = hdu + 1; } else { break; } } /* If this is the desired header data unit, keep it */ else if (extnum != -1) { if (extnum > -1 && hdu == extnum) { extfound = 1; break; } else if (extnum < 0) { extname[0] = 0; hgets (header, "EXTNAME", 32, extname); if (!strcmp (extnam,extname)) { extfound = 1; break; } } /* If this is not desired header data unit, skip over data */ hdu = hdu + 1; nblock = 0; ibhead = 0; if (naxis > 0) { ibpix = 0; hgeti4 (header,"BITPIX",&ibpix); if (ibpix < 0) { nbpix = -ibpix / 8; } else { nbpix = ibpix / 8; } nax1 = 1; hgeti4 (header,"NAXIS1",&nax1); nax2 = 1; if (naxis > 1) { hgeti4 (header,"NAXIS2",&nax2); } nax3 = 1; if (naxis > 2) { hgeti4 (header,"NAXIS3",&nax3); } nax4 = 1; if (naxis > 3) { hgeti4 (header,"NAXIS4",&nax4); } nbskip = nax1 * nax2 * nax3 * nax4 * nbpix; nblock = nbskip / 2880; if (nblock*2880 < nbskip) { nblock = nblock + 1; } npcount = 0; hgeti4 (header,"PCOUNT", &npcount); if (npcount > 0) { nbskip = nbskip + npcount; nblock = nbskip / 2880; if (nblock*2880 < nbskip) nblock = nblock + 1; } } else { nblock = 0; } *nbhead = *nbhead + (nblock * 2880); /* Set file pointer to beginning of next header/data unit */ if (nblock > 0) { #ifndef VMS if (fd != STDIN_FILENO) { ipos = lseek (fd, *nbhead, SEEK_SET); npos = *nbhead; } else { #else { #endif ipos = 0; for (i = 0; i < nblock; i++) { nbytes = FITSBLOCK; nbr = read (fd, fitsbuf, nbytes); if (nbr < nbytes) { ipos = ipos + nbr; break; } else { ipos = ipos + nbytes; } } npos = nblock * 2880; } if (ipos < npos) { snprintf (fitserrmsg,79,"FITSRHEAD: %d / %d bytes skipped\n", ipos,npos); extfound = 0; break; } } headnext = header; headend = NULL; nrec = 1; } else { break; } } } #ifndef VMS if (fd != STDIN_FILENO) (void)close (fd); #endif /* Print error message and return null if extension not found */ if (extnum != -1 && !extfound) { if (extnum < 0) fprintf (stderr, "FITSRHEAD: Extension %s not found in file %s\n",extnam, filename); else fprintf (stderr, "FITSRHEAD: Extension %d not found in file %s\n",extnum, filename); if (pheader != NULL) { free (pheader); pheader = NULL; } return (NULL); } /* Allocate an extra block for good measure */ *lhead = (nrec + 1) * FITSBLOCK; if (*lhead > nbh) { newhead = (char *) calloc (1,(unsigned int) *lhead); for (i = 0; i < nbh; i++) newhead[i] = header[i]; free (header); header = newhead; (void) hlength (header, *lhead); } else *lhead = nbh; /* If INHERIT keyword is FALSE, never append primary header */ if (hgetl (header, "INHERIT", &inherit)) { if (!inherit && fitsinherit) fitsinherit = 0; } /* Append primary data header to extension header */ if (pheader != NULL && extnum != 0 && fitsinherit && hdu > 0) { extname[0] = 0; hgets (header, "XTENSION", 32, extname); if (!strcmp (extname,"IMAGE")) { strncpy (header, "SIMPLE ", 8); hputl (header, "SIMPLE", 1); } headend = blsearch (header,"END"); if (headend == NULL) headend = ksearch (header, "END"); lext = headend - header; /* Update primary header for inclusion at end of extension header */ hchange (pheader, "SIMPLE", "ROOTHEAD"); hchange (pheader, "NEXTEND", "NUMEXT"); hdel (pheader, "BITPIX"); hdel (pheader, "NAXIS"); hdel (pheader, "EXTEND"); hputl (pheader, "ROOTEND",1); pheadend = ksearch (pheader,"END"); lprim = pheadend + 320 - pheader; if (lext + lprim > nbh) { nrec = (lext + lprim) / FITSBLOCK; if (FITSBLOCK*nrec < lext+lprim) nrec = nrec + 1; *lhead = (nrec+1) * FITSBLOCK; newhead = (char *) calloc (1,(unsigned int) *lhead); for (i = 0; i < nbh; i++) newhead[i] = header[i]; free (header); header = newhead; headend = header + lext; (void) hlength (header, *lhead); } hputs (header,"COMMENT","-------------------------------------------"); hputs (header,"COMMENT","Information from Primary Header"); hputs (header,"COMMENT","-------------------------------------------"); headend = blsearch (header,"END"); if (headend == NULL) headend = ksearch (header, "END"); pheader[lprim] = 0; strncpy (headend, pheader, lprim); if (pheader != NULL) { free (pheader); pheader = NULL; } } ibhead = *nbhead - ibhead; return (header); } /* FITSRTAIL -- Read FITS header appended to graphics file */ char * fitsrtail (filename, lhead, nbhead) char *filename; /* Name of image file */ int *lhead; /* Allocated length of FITS header in bytes (returned) */ int *nbhead; /* Number of bytes before start of data (returned) */ /* This includes all skipped image extensions */ { int fd; char *header; /* FITS image header (filled) */ int nbytes, i, ndiff; int nbr, irec; off_t offset; char *mwcs; /* Pointer to WCS name separated by % */ char *headstart; char *newhead; header = NULL; /* Check for FITS WCS specification and ignore for file opening */ mwcs = strchr (filename, '%'); if (mwcs != NULL) *mwcs = (char) 0; /* Open the image file and read the header */ if (strncasecmp (filename,"stdin",5)) { fd = -1; fd = fitsropen (filename); } #ifndef VMS else { fd = STDIN_FILENO; } #endif /* Repair the damage done to the file-name string during parsing */ if (mwcs != NULL) *mwcs = '%'; if (fd < 0) { fprintf (stderr,"FITSRTAIL: cannot read file %s\n", filename); return (NULL); } nbytes = FITSBLOCK; *nbhead = 0; *lhead = 0; /* Read FITS header from end of input file one FITS block at a time */ irec = 0; while (irec < 100) { nbytes = FITSBLOCK * (irec + 2); header = (char *) calloc ((unsigned int) nbytes, 1); offset = lseek (fd, -nbytes, SEEK_END); if (offset < 0) { free (header); header = NULL; nbytes = 0; break; } for (i = 0; i < nbytes; i++) header[i] = 0; nbr = read (fd, header, nbytes); /* Check for SIMPLE at start of header */ for (i = 0; i < nbr; i++) if (header[i] < 32) header[i] = 32; if ((headstart = ksearch (header,"SIMPLE"))) { if (headstart != header) { ndiff = headstart - header; newhead = (char *) calloc ((unsigned int) nbytes, 1); for (i = 0; i < nbytes-ndiff; i++) newhead[i] = headstart[i]; free (header); header = newhead; } *lhead = nbytes; *nbhead = nbytes; break; } free (header); } (void) hlength (header, nbytes); #ifndef VMS if (fd != STDIN_FILENO) (void)close (fd); #endif return (header); } /* FITSRSECT -- Read a piece of a FITS image, having already read the header */ char * fitsrsect (filename, header, nbhead, x0, y0, nx, ny, nlog) char *filename; /* Name of FITS image file */ char *header; /* FITS header for image (previously read) */ int nbhead; /* Actual length of image header(s) in bytes */ int x0, y0; /* FITS image coordinate of first pixel */ int nx; /* Number of columns to read (less than NAXIS1) */ int ny; /* Number of rows to read (less than NAXIS2) */ int nlog; /* Note progress mod this rows */ { int fd; /* File descriptor */ int nbimage, naxis1, naxis2, bytepix, nbread; int bitpix, naxis, nblocks, nbytes, nbr; int x1, y1, nbline, nyleft; off_t impos, nblin; char *image, *imline, *imlast; int ilog = 0; int row; /* Open the image file and read the header */ if (strncasecmp (filename,"stdin", 5)) { fd = -1; fd = fitsropen (filename); if (fd < 0) { snprintf (fitserrmsg,79, "FITSRSECT: cannot read file %s\n", filename); return (NULL); } /* Skip over FITS header and whatever else needs to be skipped */ if (lseek (fd, nbhead, SEEK_SET) < 0) { (void)close (fd); snprintf (fitserrmsg,79, "FITSRSECT: cannot skip header of file %s\n", filename); return (NULL); } } #ifndef VMS else fd = STDIN_FILENO; #endif /* Compute size of image in bytes using relevant header parameters */ naxis = 1; hgeti4 (header,"NAXIS",&naxis); naxis1 = 1; hgeti4 (header,"NAXIS1",&naxis1); naxis2 = 1; hgeti4 (header,"NAXIS2",&naxis2); bitpix = 0; hgeti4 (header,"BITPIX",&bitpix); if (bitpix == 0) { /* snprintf (fitserrmsg,79, "FITSRSECT: BITPIX is 0; image not read\n"); */ (void)close (fd); return (NULL); } bytepix = bitpix / 8; if (bytepix < 0) bytepix = -bytepix; /* Keep X coordinates within image limits */ if (x0 < 1) x0 = 1; else if (x0 > naxis1) x0 = naxis1; x1 = x0 + nx - 1; if (x1 < 1) x1 = 1; else if (x1 > naxis1) x1 = naxis1; nx = x1 - x0 + 1; /* Keep Y coordinates within image limits */ if (y0 < 1) y0 = 1; else if (y0 > naxis2) y0 = naxis2; y1 = y0 + ny - 1; if (y1 < 1) y1 = 1; else if (y1 > naxis2) y1 = naxis2; ny = y1 - y0 + 1; /* Number of bytes in output image */ nbline = nx * bytepix; nbimage = nbline * ny; /* Set number of bytes to integral number of 2880-byte blocks */ nblocks = nbimage / FITSBLOCK; if (nblocks * FITSBLOCK < nbimage) nblocks = nblocks + 1; nbytes = nblocks * FITSBLOCK; /* Allocate image section to be read */ image = (char *) malloc (nbytes); nyleft = ny; imline = image; nbr = 0; /* Computer pointer to first byte of input image to read */ nblin = naxis1 * bytepix; impos = ((y0 - 1) * nblin) + ((x0 - 1) * bytepix); row = y0 - 1; /* Read image section one line at a time */ while (nyleft-- > 0) { if (lseek (fd, impos, SEEK_CUR) >= 0) { nbread = read (fd, imline, nbline); nbr = nbr + nbread; impos = nblin - nbread; imline = imline + nbline; row++; if (++ilog == nlog) { ilog = 0; fprintf (stderr, "Row %5d extracted ", row); (void) putc (13,stderr); } } } if (nlog) fprintf (stderr, "\n"); /* Fill rest of image with zeroes */ imline = image + nbimage; imlast = image + nbytes; while (imline++ < imlast) *imline = (char) 0; /* Byte-reverse image, if necessary */ if (imswapped ()) imswap (bitpix, image, nbytes); return (image); } /* FITSRIMAGE -- Read a FITS image */ char * fitsrimage (filename, nbhead, header) char *filename; /* Name of FITS image file */ int nbhead; /* Actual length of image header(s) in bytes */ char *header; /* FITS header for image (previously read) */ { int fd; int nbimage, naxis1, naxis2, bytepix, nbread; int bitpix, naxis, nblocks, nbytes, nbleft, nbr; int simple; char *image, *imleft; /* Open the image file and read the header */ if (strncasecmp (filename,"stdin", 5)) { fd = -1; fd = fitsropen (filename); if (fd < 0) { snprintf (fitserrmsg,79, "FITSRIMAGE: cannot read file %s\n", filename); return (NULL); } /* Skip over FITS header and whatever else needs to be skipped */ if (lseek (fd, nbhead, SEEK_SET) < 0) { (void)close (fd); snprintf (fitserrmsg,79, "FITSRIMAGE: cannot skip header of file %s\n", filename); return (NULL); } } #ifndef VMS else fd = STDIN_FILENO; #endif /* If SIMPLE=F in header, simply put post-header part of file in buffer */ hgetl (header, "SIMPLE", &simple); if (!simple) { nbytes = getfilesize (filename) - nbhead; if ((image = (char *) malloc (nbytes + 1)) == NULL) { /* snprintf (fitserrmsg,79, "FITSRIMAGE: %d-byte image buffer cannot be allocated\n"); */ (void)close (fd); return (NULL); } hputi4 (header, "NBDATA", nbytes); nbread = read (fd, image, nbytes); return (image); } /* Compute size of image in bytes using relevant header parameters */ naxis = 1; hgeti4 (header,"NAXIS",&naxis); naxis1 = 1; hgeti4 (header,"NAXIS1",&naxis1); naxis2 = 1; hgeti4 (header,"NAXIS2",&naxis2); bitpix = 0; hgeti4 (header,"BITPIX",&bitpix); if (bitpix == 0) { /* snprintf (fitserrmsg,79, "FITSRIMAGE: BITPIX is 0; image not read\n"); */ (void)close (fd); return (NULL); } bytepix = bitpix / 8; if (bytepix < 0) bytepix = -bytepix; /* If either dimension is one and image is 3-D, read all three dimensions */ if (naxis == 3 && (naxis1 ==1 || naxis2 == 1)) { int naxis3; hgeti4 (header,"NAXIS3",&naxis3); nbimage = naxis1 * naxis2 * naxis3 * bytepix; } else nbimage = naxis1 * naxis2 * bytepix; /* Set number of bytes to integral number of 2880-byte blocks */ nblocks = nbimage / FITSBLOCK; if (nblocks * FITSBLOCK < nbimage) nblocks = nblocks + 1; nbytes = nblocks * FITSBLOCK; /* Allocate and read image */ image = (char *) malloc (nbytes); nbleft = nbytes; imleft = image; nbr = 0; while (nbleft > 0) { nbread = read (fd, imleft, nbleft); nbr = nbr + nbread; #ifndef VMS if (fd == STDIN_FILENO && nbread < nbleft && nbread > 0) { nbleft = nbleft - nbread; imleft = imleft + nbread; } else #endif nbleft = 0; } #ifndef VMS if (fd != STDIN_FILENO) (void)close (fd); #endif if (nbr < nbimage) { snprintf (fitserrmsg,79, "FITSRIMAGE: %d of %d bytes read from file %s\n", nbr, nbimage, filename); return (NULL); } /* Byte-reverse image, if necessary */ if (imswapped ()) imswap (bitpix, image, nbytes); return (image); } /* FITSRFULL -- Read a FITS image of any dimension */ char * fitsrfull (filename, nbhead, header) char *filename; /* Name of FITS image file */ int nbhead; /* Actual length of image header(s) in bytes */ char *header; /* FITS header for image (previously read) */ { int fd; int nbimage, naxisi, iaxis, bytepix, nbread; int bitpix, naxis, nblocks, nbytes, nbleft, nbr, simple; char keyword[16]; char *image, *imleft; /* Open the image file and read the header */ if (strncasecmp (filename,"stdin", 5)) { fd = -1; fd = fitsropen (filename); if (fd < 0) { snprintf (fitserrmsg,79, "FITSRFULL: cannot read file %s\n", filename); return (NULL); } /* Skip over FITS header and whatever else needs to be skipped */ if (lseek (fd, nbhead, SEEK_SET) < 0) { (void)close (fd); snprintf (fitserrmsg,79, "FITSRFULL: cannot skip header of file %s\n", filename); return (NULL); } } #ifndef VMS else fd = STDIN_FILENO; #endif /* If SIMPLE=F in header, simply put post-header part of file in buffer */ hgetl (header, "SIMPLE", &simple); if (!simple) { nbytes = getfilesize (filename) - nbhead; if ((image = (char *) malloc (nbytes + 1)) == NULL) { snprintf (fitserrmsg,79, "FITSRFULL: %d-byte image buffer cannot be allocated\n",nbytes+1); (void)close (fd); return (NULL); } hputi4 (header, "NBDATA", nbytes); nbread = read (fd, image, nbytes); return (image); } /* Find number of bytes per pixel */ bitpix = 0; hgeti4 (header,"BITPIX",&bitpix); if (bitpix == 0) { snprintf (fitserrmsg,79, "FITSRFULL: BITPIX is 0; image not read\n"); (void)close (fd); return (NULL); } bytepix = bitpix / 8; if (bytepix < 0) bytepix = -bytepix; nbimage = bytepix; /* Compute size of image in bytes using relevant header parameters */ naxis = 1; hgeti4 (header,"NAXIS",&naxis); for (iaxis = 1; iaxis <= naxis; iaxis++) { sprintf (keyword, "NAXIS%d", iaxis); naxisi = 1; hgeti4 (header,keyword,&naxisi); nbimage = nbimage * naxisi; } /* Set number of bytes to integral number of 2880-byte blocks */ nblocks = nbimage / FITSBLOCK; if (nblocks * FITSBLOCK < nbimage) nblocks = nblocks + 1; nbytes = nblocks * FITSBLOCK; /* Allocate and read image */ image = (char *) malloc (nbytes); nbleft = nbytes; imleft = image; nbr = 0; while (nbleft > 0) { nbread = read (fd, imleft, nbleft); nbr = nbr + nbread; #ifndef VMS if (fd == STDIN_FILENO && nbread < nbleft && nbread > 0) { nbleft = nbleft - nbread; imleft = imleft + nbread; } else #endif nbleft = 0; } #ifndef VMS if (fd != STDIN_FILENO) (void)close (fd); #endif if (nbr < nbimage) { snprintf (fitserrmsg,79, "FITSRFULL: %d of %d image bytes read from file %s\n", nbr, nbimage, filename); return (NULL); } /* Byte-reverse image, if necessary */ if (imswapped ()) imswap (bitpix, image, nbytes); return (image); } /* FITSROPEN -- Open a FITS file, returning the file descriptor */ int fitsropen (inpath) char *inpath; /* Pathname for FITS tables file to read */ { int ntry; int fd; /* file descriptor for FITS tables file (returned) */ char *ext; /* extension name or number */ char cext = 0; char *rbrac; char *mwcs; /* Pointer to WCS name separated by % */ /* Check for FITS WCS specification and ignore for file opening */ mwcs = strchr (inpath, '%'); /* Check for FITS extension and ignore for file opening */ ext = strchr (inpath, ','); rbrac = NULL; if (ext == NULL) { ext = strchr (inpath, '['); if (ext != NULL) { rbrac = strchr (inpath, ']'); } } /* Open input file */ for (ntry = 0; ntry < 3; ntry++) { if (ext != NULL) { cext = *ext; *ext = 0; } if (rbrac != NULL) *rbrac = (char) 0; if (mwcs != NULL) *mwcs = (char) 0; fd = open (inpath, O_RDONLY); if (ext != NULL) *ext = cext; if (rbrac != NULL) *rbrac = ']'; if (mwcs != NULL) *mwcs = '%'; if (fd >= 0) break; else if (ntry == 2) { snprintf (fitserrmsg,79, "FITSROPEN: cannot read file %s\n", inpath); return (-1); } } if (verbose) fprintf (stderr,"FITSROPEN: input file %s opened\n",inpath); return (fd); } static int offset1=0; static int offset2=0; /* FITSRTOPEN -- Open FITS table file and fill structure with * pointers to selected keywords * Return file descriptor (-1 if unsuccessful) */ int fitsrtopen (inpath, nk, kw, nrows, nchar, nbhead) char *inpath; /* Pathname for FITS tables file to read */ int *nk; /* Number of keywords to use */ struct Keyword **kw; /* Structure for desired entries */ int *nrows; /* Number of rows in table (returned) */ int *nchar; /* Number of characters in one table row (returned) */ int *nbhead; /* Number of characters before table starts */ { char temp[16]; int fd; int lhead; /* Maximum length in bytes of FITS header */ char *header; /* Header for FITS tables file to read */ /* Read FITS header from input file */ header = fitsrhead (inpath, &lhead, nbhead); if (!header) { snprintf (fitserrmsg,79,"FITSRTOPEN: %s is not a FITS file\n",inpath); return (0); } /* Make sure this file is really a FITS table file */ temp[0] = 0; (void) hgets (header,"XTENSION",16,temp); if (strlen (temp) == 0) { snprintf (fitserrmsg,79, "FITSRTOPEN: %s is not a FITS table file\n",inpath); free ((void *) header); return (0); } /* If it is a FITS file, get table information from the header */ else if (!strcmp (temp, "TABLE") || !strcmp (temp, "BINTABLE")) { if (fitsrthead (header, nk, kw, nrows, nchar)) { snprintf (fitserrmsg,79, "FITSRTOPEN: Cannot read FITS table from %s\n",inpath); free ((void *) header); return (-1); } else { fd = fitsropen (inpath); offset1 = 0; offset2 = 0; free ((void *) header); return (fd); } } /* If it is another FITS extension note it and return */ else { snprintf (fitserrmsg,79, "FITSRTOPEN: %s is a %s extension, not table\n", inpath, temp); free ((void *) header); return (0); } } static struct Keyword *pw; /* Structure for all entries */ static int *lpnam; /* length of name for each field */ static int bfields = 0; /* FITSRTHEAD -- From FITS table header, read pointers to selected keywords */ int fitsrthead (header, nk, kw, nrows, nchar) char *header; /* Header for FITS tables file to read */ int *nk; /* Number of keywords to use */ struct Keyword **kw; /* Structure for desired entries */ int *nrows; /* Number of rows in table (returned) */ int *nchar; /* Number of characters in one table row (returned) */ { struct Keyword *rw; /* Structure for desired entries */ int nfields; int ifield, ik, i, ikf, ltform, kl; char *h0, *h1, *tf1, *tf2; char tname[12]; char temp[16]; char tform[16]; int tverb; int bintable = 0; h0 = header; /* Make sure this is really a FITS table file header */ temp[0] = 0; hgets (header,"XTENSION",16,temp); if (strlen (temp) == 0) { snprintf (fitserrmsg,79, "FITSRTHEAD: Not a FITS table header\n"); return (-1); } else if (!strcmp (temp, "BINTABLE")) { bintable = 1; } else if (strcmp (temp, "TABLE")) { snprintf (fitserrmsg,79, "FITSRTHEAD: %s extension, not TABLE\n",temp); return (-1); } /* Get table size from FITS header */ *nchar = 0; hgeti4 (header,"NAXIS1",nchar); *nrows = 0; hgeti4 (header,"NAXIS2", nrows); if (*nrows <= 0 || *nchar <= 0) { snprintf (fitserrmsg,79, "FITSRTHEAD: cannot read %d x %d table\n", *nrows,*nchar); return (-1); } /* Set up table for access to individual fields */ nfields = 0; hgeti4 (header,"TFIELDS",&nfields); if (verbose) fprintf (stderr, "FITSRTHEAD: %d fields per table entry\n", nfields); if (nfields > bfields) { if (bfields > 0) free ((void *)pw); pw = (struct Keyword *) calloc (nfields, sizeof(struct Keyword)); if (pw == NULL) { snprintf (fitserrmsg,79,"FITSRTHEAD: cannot allocate table structure\n"); return (-1); } if (bfields > 0) free ((void *)lpnam); lpnam = (int *) calloc (nfields, sizeof(int)); if (lpnam == NULL) { snprintf (fitserrmsg,79,"FITSRTHEAD: cannot allocate length structure\n"); return (-1); } bfields = nfields; } tverb = verbose; verbose = 0; ikf = 0; for (ifield = 0; ifield < nfields; ifield++) { /* Name of field */ for (i = 0; i < 12; i++) tname[i] = 0; sprintf (tname, "TTYPE%d", ifield+1);; temp[0] = 0; h1 = ksearch (h0,tname); h0 = h1; hgets (h0,tname,16,temp); strcpy (pw[ifield].kname,temp); pw[ifield].lname = strlen (pw[ifield].kname); /* Sequence of field on line */ pw[ifield].kn = ifield + 1; /* First column of field */ if (bintable) pw[ifield].kf = ikf; else { for (i = 0; i < 12; i++) tname[i] = 0; sprintf (tname, "TBCOL%d", ifield+1); pw[ifield].kf = 0; hgeti4 (h0,tname, &pw[ifield].kf); } /* Length of field */ for (i = 0; i < 12; i++) tname[i] = 0; sprintf (tname, "TFORM%d", ifield+1);; tform[0] = 0; hgets (h0,tname,16,tform); strcpy (pw[ifield].kform, tform); ltform = strlen (tform); if (tform[ltform-1] == 'A') { pw[ifield].kform[0] = 'A'; for (i = 0; i < ltform-1; i++) pw[ifield].kform[i+1] = tform[i]; pw[ifield].kform[ltform] = (char) 0; tf1 = pw[ifield].kform + 1; kl = atof (tf1); } else if (!strcmp (tform,"I")) kl = 2; else if (!strcmp (tform, "J")) kl = 4; else if (!strcmp (tform, "E")) kl = 4; else if (!strcmp (tform, "D")) kl = 8; else { tf1 = tform + 1; tf2 = strchr (tform,'.'); if (tf2 != NULL) *tf2 = ' '; kl = atoi (tf1); } pw[ifield].kl = kl; ikf = ikf + kl; } /* Set up table for access to desired fields */ verbose = tverb; if (verbose) fprintf (stderr, "FITSRTHEAD: %d keywords read\n", *nk); /* If nk = 0, allocate and return structures for all table fields */ if (*nk <= 0) { *kw = pw; *nk = nfields; return (0); } else rw = *kw; /* Find each desired keyword in the header */ for (ik = 0; ik < *nk; ik++) { if (rw[ik].kn <= 0) { for (ifield = 0; ifield < nfields; ifield++) { if (rw[ik].lname != pw[ifield].lname) continue; if (strcmp (pw[ifield].kname, rw[ik].kname) == 0) { break; } } } else ifield = rw[ik].kn - 1; /* Set pointer, lentth, and name in returned array of structures */ rw[ik].kn = ifield + 1; rw[ik].kf = pw[ifield].kf - 1; rw[ik].kl = pw[ifield].kl; strcpy (rw[ik].kform, pw[ifield].kform); strcpy (rw[ik].kname, pw[ifield].kname); } return (0); } int fitsrtline (fd, nbhead, lbuff, tbuff, irow, nbline, line) int fd; /* File descriptor for FITS file */ int nbhead; /* Number of bytes in FITS header */ int lbuff; /* Number of bytes in table buffer */ char *tbuff; /* FITS table buffer */ int irow; /* Number of table row to read */ int nbline; /* Number of bytes to read for this line */ char *line; /* One line of FITS table (returned) */ { int nbuff, nlbuff; int nbr = 0; int offset, offend, ntry, ioff; char *tbuff1; offset = nbhead + (nbline * irow); offend = offset + nbline - 1; /* Read a new buffer of the FITS table into memory if needed */ if (offset < offset1 || offend > offset2) { nlbuff = lbuff / nbline; nbuff = nlbuff * nbline; for (ntry = 0; ntry < 3; ntry++) { ioff = lseek (fd, offset, SEEK_SET); if (ioff < offset) { if (ntry == 2) return (0); else continue; } nbr = read (fd, tbuff, nbuff); if (nbr < nbline) { if (verbose) fprintf (stderr, "FITSRTLINE: %d / %d bytes read %d\n", nbr,nbuff,ntry); if (ntry == 2) return (nbr); } else break; } offset1 = offset; offset2 = offset + nbr - 1; strncpy (line, tbuff, nbline); return (nbline); } else { tbuff1 = tbuff + (offset - offset1); strncpy (line, tbuff1, nbline); return (nbline); } } void fitsrtlset () { offset1 = 0; offset2 = 0; return; } /* FTGETI2 -- Extract n'th column from FITS table line as short */ short ftgeti2 (entry, kw) char *entry; /* Row or entry from table */ struct Keyword *kw; /* Table column information from FITS header */ { char temp[30]; short i; int j; float r; double d; if (ftgetc (entry, kw, temp, 30)) { if (!strcmp (kw->kform, "I")) moveb (temp, (char *) &i, 2, 0, 0); else if (!strcmp (kw->kform, "J")) { moveb (temp, (char *) &j, 4, 0, 0); i = (short) j; } else if (!strcmp (kw->kform, "E")) { moveb (temp, (char *) &r, 4, 0, 0); i = (short) r; } else if (!strcmp (kw->kform, "D")) { moveb (temp, (char *) &d, 8, 0, 0); i = (short) d; } else i = (short) atof (temp); return (i); } else return ((short) 0); } /* FTGETI4 -- Extract n'th column from FITS table line as int */ int ftgeti4 (entry, kw) char *entry; /* Row or entry from table */ struct Keyword *kw; /* Table column information from FITS header */ { char temp[30]; short i; int j; float r; double d; if (ftgetc (entry, kw, temp, 30)) { if (!strcmp (kw->kform, "I")) { moveb (temp, (char *) &i, 2, 0, 0); j = (int) i; } else if (!strcmp (kw->kform, "J")) moveb (temp, (char *) &j, 4, 0, 0); else if (!strcmp (kw->kform, "E")) { moveb (temp, (char *) &r, 4, 0, 0); j = (int) r; } else if (!strcmp (kw->kform, "D")) { moveb (temp, (char *) &d, 8, 0, 0); j = (int) d; } else j = (int) atof (temp); return (j); } else return (0); } /* FTGETR4 -- Extract n'th column from FITS table line as float */ float ftgetr4 (entry, kw) char *entry; /* Row or entry from table */ struct Keyword *kw; /* Table column information from FITS header */ { char temp[30]; short i; int j; float r; double d; if (ftgetc (entry, kw, temp, 30)) { if (!strcmp (kw->kform, "I")) { moveb (temp, (char *) &i, 2, 0, 0); r = (float) i; } else if (!strcmp (kw->kform, "J")) { moveb (temp, (char *) &j, 4, 0, 0); r = (float) j; } else if (!strcmp (kw->kform, "E")) moveb (temp, (char *) &r, 4, 0, 0); else if (!strcmp (kw->kform, "D")) { moveb (temp, (char *) &d, 8, 0, 0); r = (float) d; } else r = (float) atof (temp); return (r); } else return ((float) 0.0); } /* FTGETR8 -- Extract n'th column from FITS table line as double */ double ftgetr8 (entry, kw) char *entry; /* Row or entry from table */ struct Keyword *kw; /* Table column information from FITS header */ { char temp[30]; short i; int j; float r; double d; if (ftgetc (entry, kw, temp, 30)) { if (!strcmp (kw->kform, "I")) { moveb (temp, (char *) &i, 2, 0, 0); d = (double) i; } else if (!strcmp (kw->kform, "J")) { moveb (temp, (char *) &j, 4, 0, 0); d = (double) j; } else if (!strcmp (kw->kform, "E")) { moveb (temp, (char *) &r, 4, 0, 0); d = (double) r; } else if (!strcmp (kw->kform, "D")) moveb (temp, (char *) &d, 8, 0, 0); else d = atof (temp); return (d); } else return ((double) 0.0); } /* FTGETC -- Extract n'th column from FITS table line as character string */ int ftgetc (entry, kw, string, maxchar) char *entry; /* Row or entry from table */ struct Keyword *kw; /* Table column information from FITS header */ char *string; /* Returned string */ int maxchar; /* Maximum number of characters in returned string */ { int length = maxchar; if (kw->kl < length) length = kw->kl; if (length > 0) { strncpy (string, entry+kw->kf, length); string[length] = 0; return ( 1 ); } else return ( 0 ); } extern int errno; /*FITSWIMAGE -- Write FITS header and image */ int fitswimage (filename, header, image) char *filename; /* Name of FITS image file */ char *header; /* FITS image header */ char *image; /* FITS image pixels */ { int fd; /* Open the output file */ if (strcasecmp (filename,"stdout") ) { if (!access (filename, 0)) { fd = open (filename, O_WRONLY); if (fd < 3) { snprintf (fitserrmsg,79, "FITSWIMAGE: file %s not writeable\n", filename); return (0); } } else { fd = open (filename, O_RDWR+O_CREAT, 0666); if (fd < 3) { snprintf (fitserrmsg,79, "FITSWIMAGE: cannot create file %s\n", filename); return (0); } } } #ifndef VMS else fd = STDOUT_FILENO; #endif return (fitswhdu (fd, filename, header, image)); } /*FITSWEXT -- Write FITS header and image as extension to a file */ int fitswext (filename, header, image) char *filename; /* Name of IFTS image file */ char *header; /* FITS image header */ char *image; /* FITS image pixels */ { int fd; /* Open the output file */ if (strcasecmp (filename,"stdout") ) { if (!access (filename, 0)) { fd = open (filename, O_WRONLY); if (fd < 3) { snprintf (fitserrmsg,79, "FITSWEXT: file %s not writeable\n", filename); return (0); } } else { fd = open (filename, O_APPEND, 0666); if (fd < 3) { snprintf (fitserrmsg,79, "FITSWEXT: cannot append to file %s\n", filename); return (0); } } } #ifndef VMS else fd = STDOUT_FILENO; #endif return (fitswhdu (fd, filename, header, image)); } /* FITSWHDU -- Write FITS head and image as extension */ int fitswhdu (fd, filename, header, image) int fd; /* File descriptor */ char *filename; /* Name of IFTS image file */ char *header; /* FITS image header */ char *image; /* FITS image pixels */ { int nbhead, nbimage, nblocks, bytepix, i, nbhw; int bitpix, naxis, iaxis, naxisi, nbytes, nbw, nbpad, nbwp, simple; char *endhead, *padding; double bzero, bscale; char keyword[32]; /* Change BITPIX=-16 files to BITPIX=16 with BZERO and BSCALE */ bitpix = 0; hgeti4 (header,"BITPIX",&bitpix); if (bitpix == -16) { if (!hgetr8 (header, "BZERO", &bzero) && !hgetr8 (header, "BSCALE", &bscale)) { bitpix = 16; hputi4 (header, "BITPIX", bitpix); hputr8 (header, "BZERO", 32768.0); hputr8 (header, "BSCALE", 1.0); } } /* Write header to file */ endhead = ksearch (header,"END") + 80; nbhead = endhead - header; nbhw = write (fd, header, nbhead); if (nbhw < nbhead) { snprintf (fitserrmsg,79, "FITSWHDU: wrote %d / %d bytes of header to file %s\n", nbhw, nbhead, filename); (void)close (fd); return (0); } /* Write extra spaces to make an integral number of 2880-byte blocks */ nblocks = nbhead / FITSBLOCK; if (nblocks * FITSBLOCK < nbhead) nblocks = nblocks + 1; nbytes = nblocks * FITSBLOCK; nbpad = nbytes - nbhead; padding = (char *)calloc (1, nbpad); for (i = 0; i < nbpad; i++) padding[i] = ' '; nbwp = write (fd, padding, nbpad); if (nbwp < nbpad) { snprintf (fitserrmsg,79, "FITSWHDU: wrote %d / %d bytes of header padding to file %s\n", nbwp, nbpad, filename); (void)close (fd); return (0); } nbhw = nbhw + nbwp; free (padding); /* Return if file has no data */ if (bitpix == 0 || image == NULL) { /* snprintf (fitserrmsg,79, "FITSWHDU: BITPIX is 0; image not written\n"); */ (void)close (fd); return (0); } /* If SIMPLE=F in header, just write whatever is in the buffer */ hgetl (header, "SIMPLE", &simple); if (!simple) { hgeti4 (header, "NBDATA", &nbytes); nbimage = nbytes; } else { /* Compute size of pixel in bytes */ bytepix = bitpix / 8; if (bytepix < 0) bytepix = -bytepix; nbimage = bytepix; /* Compute size of image in bytes using relevant header parameters */ naxis = 1; hgeti4 (header,"NAXIS",&naxis); for (iaxis = 1; iaxis <= naxis; iaxis++) { sprintf (keyword, "NAXIS%d", iaxis); naxisi = 1; hgeti4 (header,keyword,&naxisi); nbimage = nbimage * naxisi; } /* Number of bytes to write is an integral number of FITS blocks */ nblocks = nbimage / FITSBLOCK; if (nblocks * FITSBLOCK < nbimage) nblocks = nblocks + 1; nbytes = nblocks * FITSBLOCK; /* Byte-reverse image before writing, if necessary */ if (imswapped ()) imswap (bitpix, image, nbimage); } /* Write image to file */ nbw = write (fd, image, nbimage); if (nbw < nbimage) { snprintf (fitserrmsg,79, "FITSWHDU: wrote %d / %d bytes of image to file %s\n", nbw, nbimage, filename); return (0); } /* Write extra zeroes to make an integral number of 2880-byte blocks */ nbpad = nbytes - nbimage; if (nbpad > 0) { padding = (char *)calloc (1, nbpad); nbwp = write (fd, padding, nbpad); if (nbwp < nbpad) { snprintf (fitserrmsg,79, "FITSWHDU: wrote %d / %d bytes of image padding to file %s\n", nbwp, nbpad, filename); (void)close (fd); return (0); } free (padding); } else nbwp = 0; (void)close (fd); /* Byte-reverse image after writing, if necessary */ if (imswapped ()) imswap (bitpix, image, nbimage); nbw = nbw + nbwp + nbhw; return (nbw); } /*FITSCIMAGE -- Write FITS header and copy FITS image Return number of bytes in output image, 0 if failure */ int fitscimage (filename, header, filename0) char *filename; /* Name of output FITS image file */ char *header; /* FITS image header */ char *filename0; /* Name of input FITS image file */ { int fdout, fdin; int nbhead, nbimage, nblocks, bytepix; int bitpix, naxis, naxis1, naxis2, nbytes, nbw, nbpad, nbwp; char *endhead, *lasthead, *padding; char *image; /* FITS image pixels */ char *oldhead; /* Input file image header */ int nbhead0; /* Length of input file image header */ int lhead0; int nbbuff, nbuff, ibuff, nbr, nbdata; /* Compute size of image in bytes using relevant header parameters */ naxis = 1; hgeti4 (header, "NAXIS", &naxis); naxis1 = 1; hgeti4 (header, "NAXIS1", &naxis1); naxis2 = 1; hgeti4 (header, "NAXIS2", &naxis2); hgeti4 (header, "BITPIX", &bitpix); bytepix = bitpix / 8; if (bytepix < 0) bytepix = -bytepix; /* If either dimension is one and image is 3-D, read all three dimensions */ if (naxis == 3 && (naxis1 ==1 || naxis2 == 1)) { int naxis3; hgeti4 (header,"NAXIS3",&naxis3); nbimage = naxis1 * naxis2 * naxis3 * bytepix; } else nbimage = naxis1 * naxis2 * bytepix; nblocks = nbimage / FITSBLOCK; if (nblocks * FITSBLOCK < nbimage) nblocks = nblocks + 1; nbytes = nblocks * FITSBLOCK; /* Allocate image buffer */ nbbuff = FITSBLOCK * 100; if (nbytes < nbbuff) nbbuff = nbytes; image = (char *) calloc (1, nbbuff); nbuff = nbytes / nbbuff; if (nbytes > nbuff * nbbuff) nbuff = nbuff + 1; /* Read input file header */ if ((oldhead = fitsrhead (filename0, &lhead0, &nbhead0)) == NULL) { snprintf (fitserrmsg, 79,"FITSCIMAGE: header of input file %s cannot be read\n", filename0); return (0); } /* Find size of output header */ nbhead = fitsheadsize (header); /* If overwriting, be more careful if new header is longer than old */ if (!strcmp (filename, filename0) && nbhead > nbhead0) { if ((image = fitsrimage (filename0, nbhead0, oldhead)) == NULL) { snprintf (fitserrmsg,79, "FITSCIMAGE: cannot read image from file %s\n", filename0); free (oldhead); return (0); } return (fitswimage (filename, header, image)); } free (oldhead); /* Open the input file and skip over the header */ if (strcasecmp (filename0,"stdin")) { fdin = -1; fdin = fitsropen (filename0); if (fdin < 0) { snprintf (fitserrmsg, 79,"FITSCIMAGE: cannot read file %s\n", filename0); return (0); } /* Skip over FITS header */ if (lseek (fdin, nbhead0, SEEK_SET) < 0) { (void)close (fdin); snprintf (fitserrmsg,79, "FITSCIMAGE: cannot skip header of file %s\n", filename0); return (0); } } #ifndef VMS else fdin = STDIN_FILENO; #endif /* Open the output file */ if (!access (filename, 0)) { fdout = open (filename, O_WRONLY); if (fdout < 3) { snprintf (fitserrmsg,79, "FITSCIMAGE: file %s not writeable\n", filename); return (0); } } else { fdout = open (filename, O_RDWR+O_CREAT, 0666); if (fdout < 3) { snprintf (fitserrmsg,79, "FITSCHEAD: cannot create file %s\n", filename); return (0); } } /* Pad header with spaces */ endhead = ksearch (header,"END") + 80; lasthead = header + nbhead; while (endhead < lasthead) *(endhead++) = ' '; /* Write header to file */ nbw = write (fdout, header, nbhead); if (nbw < nbhead) { snprintf (fitserrmsg, 79,"FITSCIMAGE: wrote %d / %d bytes of header to file %s\n", nbw, nbytes, filename); (void)close (fdout); (void)close (fdin); return (0); } /* Return if no data */ if (bitpix == 0) { (void)close (fdout); (void)close (fdin); return (nbhead); } nbdata = 0; for (ibuff = 0; ibuff < nbuff; ibuff++) { nbr = read (fdin, image, nbbuff); if (nbr > 0) { nbw = write (fdout, image, nbr); nbdata = nbdata + nbw; } } /* Write extra to make integral number of 2880-byte blocks */ nblocks = nbdata / FITSBLOCK; if (nblocks * FITSBLOCK < nbdata) nblocks = nblocks + 1; nbytes = nblocks * FITSBLOCK; nbpad = nbytes - nbdata; padding = (char *)calloc (1,nbpad); nbwp = write (fdout, padding, nbpad); nbw = nbdata + nbwp; free (padding); (void)close (fdout); (void)close (fdin); if (nbw < nbimage) { snprintf (fitserrmsg, 79, "FITSWIMAGE: wrote %d / %d bytes of image to file %s\n", nbw, nbimage, filename); return (0); } else return (nbw); } /* FITSWHEAD -- Write FITS header and keep file open for further writing */ int fitswhead (filename, header) char *filename; /* Name of IFTS image file */ char *header; /* FITS image header */ { int fd; int nbhead, nblocks; int nbytes, nbw; char *endhead, *lasthead; /* Open the output file */ if (!access (filename, 0)) { fd = open (filename, O_WRONLY); if (fd < 3) { snprintf (fitserrmsg, 79, "FITSWHEAD: file %s not writeable\n", filename); return (0); } } else { fd = open (filename, O_RDWR+O_CREAT, 0666); if (fd < 3) { snprintf (fitserrmsg, 79, "FITSWHEAD: cannot create file %s\n", filename); return (0); } } /* Write header to file */ endhead = ksearch (header,"END") + 80; nbhead = endhead - header; nblocks = nbhead / FITSBLOCK; if (nblocks * FITSBLOCK < nbhead) nblocks = nblocks + 1; nbytes = nblocks * FITSBLOCK; /* Pad header with spaces */ lasthead = header + nbytes; while (endhead < lasthead) *(endhead++) = ' '; nbw = write (fd, header, nbytes); if (nbw < nbytes) { fprintf (stderr, "FITSWHEAD: wrote %d / %d bytes of header to file %s\n", nbw, nbytes, filename); (void)close (fd); return (0); } return (fd); } /* FITSWEXHEAD -- Write FITS header in place */ int fitswexhead (filename, header) char *filename; /* Name of FITS image file with ,extension */ char *header; /* FITS image header */ { int fd; int nbhead, lhead; int nbw, nbnew, nbold; char *endhead, *lasthead, *oldheader; char *ext, cext; /* Compare size of existing header to size of new header */ fitsinherit = 0; oldheader = fitsrhead (filename, &lhead, &nbhead); if (oldheader == NULL) { snprintf (fitserrmsg, 79, "FITSWEXHEAD: file %s cannot be read\n", filename); return (-1); } nbold = fitsheadsize (oldheader); nbnew = fitsheadsize (header); /* Return if the new header is bigger than the old header */ if (nbnew > nbold) { snprintf (fitserrmsg, 79, "FITSWEXHEAD: old header %d bytes, new header %d bytes\n", nbold,nbnew); free (oldheader); oldheader = NULL; return (-1); } /* Add blank lines if new header is smaller than the old header */ else if (nbnew < nbold) { strcpy (oldheader, header); endhead = ksearch (oldheader,"END"); lasthead = oldheader + nbold; while (endhead < lasthead) *(endhead++) = ' '; strncpy (lasthead-80, "END", 3); } /* Pad header with spaces */ else { endhead = ksearch (header,"END") + 80; lasthead = header + nbnew; while (endhead < lasthead) *(endhead++) = ' '; strncpy (oldheader, header, nbnew); } /* Check for FITS extension and ignore for file opening */ ext = strchr (filename, ','); if (ext == NULL) ext = strchr (filename, '['); if (ext != NULL) { cext = *ext; *ext = (char) 0; } /* Open the output file */ fd = open (filename, O_WRONLY); if (ext != NULL) *ext = cext; if (fd < 3) { snprintf (fitserrmsg, 79, "FITSWEXHEAD: file %s not writeable\n", filename); return (-1); } /* Skip to appropriate place in file */ (void) lseek (fd, ibhead, SEEK_SET); /* Write header to file */ nbw = write (fd, oldheader, nbold); (void)close (fd); free (oldheader); oldheader = NULL; if (nbw < nbold) { fprintf (stderr, "FITSWHEAD: wrote %d / %d bytes of header to file %s\n", nbw, nbold, filename); return (-1); } return (0); } /* ISFITS -- Return 1 if FITS file, else 0 */ int isfits (filename) char *filename; /* Name of file for which to find size */ { int diskfile; char keyword[16]; char *comma; int nbr; /* First check to see if this is an assignment */ if (strchr (filename, '=')) return (0); /* Check for stdin (input from pipe) */ else if (!strcasecmp (filename,"stdin")) return (1); /* Then check file extension else if (strsrch (filename, ".fit") || strsrch (filename, ".fits") || strsrch (filename, ".fts")) return (1); */ /* If no FITS file extension, try opening the file */ else { if ((comma = strchr (filename,','))) *comma = (char) 0; if ((diskfile = open (filename, O_RDONLY)) < 0) { if (comma) *comma = ','; return (0); } else { nbr = read (diskfile, keyword, 8); if (comma) *comma = ','; close (diskfile); if (nbr < 8) return (0); else if (!strncmp (keyword, "SIMPLE", 6)) return (1); else return (0); } } } /* FITSHEADSIZE -- Find size of FITS header */ int fitsheadsize (header) char *header; /* FITS header */ { char *endhead; int nbhead, nblocks; endhead = ksearch (header,"END") + 80; nbhead = endhead - header; nblocks = nbhead / FITSBLOCK; if (nblocks * FITSBLOCK < nbhead) nblocks = nblocks + 1; return (nblocks * FITSBLOCK); } /* Print error message */ void fitserr () { fprintf (stderr, "%s\n",fitserrmsg); return; } /* MOVEB -- Copy nbytes bytes from source+offs to dest+offd (any data type) */ void moveb (source, dest, nbytes, offs, offd) char *source; /* Pointer to source */ char *dest; /* Pointer to destination */ int nbytes; /* Number of bytes to move */ int offs; /* Offset in bytes in source from which to start copying */ int offd; /* Offset in bytes in destination to which to start copying */ { char *from, *last, *to; from = source + offs; to = dest + offd; last = from + nbytes; while (from < last) *(to++) = *(from++); return; } /* * Feb 8 1996 New subroutines * Apr 10 1996 Add subroutine list at start of file * Apr 17 1996 Print error message to stderr * May 2 1996 Write using stream IO * May 14 1996 If FITSRTOPEN NK is zero, return all keywords in header * May 17 1996 Make header internal to FITSRTOPEN * Jun 3 1996 Use stream I/O for input as well as output * Jun 10 1996 Remove unused variables after running lint * Jun 12 1996 Deal with byte-swapped images * Jul 11 1996 Rewrite code to separate header and data reading * Aug 6 1996 Fixed small defects after lint * Aug 6 1996 Drop unused NBHEAD argument from FITSRTHEAD * Aug 13 1996 If filename is stdin, read from standard input instead of file * Aug 30 1996 Use write for output, not fwrite * Sep 4 1996 Fix mode when file is created * Oct 15 1996 Drop column argument from FGET* subroutines * Oct 15 1996 Drop unused variable * Dec 17 1996 Add option to skip bytes in file before reading the header * Dec 27 1996 Turn nonprinting header characters into spaces * * Oct 9 1997 Add FITS extension support as filename,extension * Dec 15 1997 Fix minor bugs after lint * * Feb 23 1998 Do not append primary header if getting header for ext. 0 * Feb 23 1998 Accept either bracketed or comma extension * Feb 24 1998 Add SIMPLE keyword to start of extracted extension * Apr 30 1998 Fix error return if not table file after Allan Brighton * May 4 1998 Fix error in argument sequence in HGETS call * May 27 1998 Include fitsio.h and imio.h * Jun 1 1998 Add VMS fixes from Harry Payne at STScI * Jun 3 1998 Fix bug reading EXTNAME * Jun 11 1998 Initialize all header parameters before reading them * Jul 13 1998 Clarify argument definitions * Aug 6 1998 Rename fitsio.c to fitsfile.c to avoid conflict with CFITSIO * Aug 13 1998 Add FITSWHEAD to write only header * Sep 25 1998 Allow STDIN or stdin for standard input reading * Oct 5 1998 Add isfits() to decide whether a file is FITS * Oct 9 1998 Assume stdin and STDIN to be FITS files in isfits() * Nov 30 1998 Fix bug found by Andreas Wicenec when reading large headers * Dec 8 1998 Fix bug introduced by previous bug fix * * Jan 4 1999 Do not print error message if BITPIX is 0 * Jan 27 1999 Read and write all of 3D images if one dimension is 1 * Jan 27 1999 Pad out data to integral number of 2880-byte blocks * Apr 29 1999 Write BITPIX=-16 files as BITPIX=16 with BSCALE and BZERO * Apr 30 1999 Add % as alternative to , to denote sub-images * May 25 1999 Set buffer offsets to 0 when FITS table file is opened * Jul 14 1999 Do not try to write image data if BITPIX is 0 * Sep 27 1999 Add STDOUT as output filename option in fitswimage() * Oct 6 1999 Set header length global variable hget.lhead0 in fitsrhead() * Oct 14 1999 Update header length as it is changed in fitsrhead() * Oct 20 1999 Change | in if statements to || * Oct 25 1999 Change most malloc() calls to calloc() * Nov 24 1999 Add fitscimage() * * Feb 23 2000 Fix problem with some error returns in fitscimage() * Mar 17 2000 Drop unused variables after lint * Jul 20 2000 Drop BITPIX and NAXIS from primary header if extension printerd * Jul 20 2000 Start primary part of header with ROOTHEAD keyword * Jul 28 2000 Add loop to deal with buffered stdin * * Jan 11 2001 Print all messages to stderr * Jan 12 2001 Add extension back onto filename after fitsropen() (Guy Rixon) * Jan 18 2001 Drop EXTEND keyword when extracting an extension * Jan 18 2001 Add fitswext() to append HDU and fitswhdu() to do actual writing * Jan 22 2001 Ignore WCS name or letter following a : in file name in fitsrhead() * Jan 30 2001 Fix FITSCIMAGE so it doesn't overwrite data when overwriting a file * Feb 20 2001 Ignore WCS name or letter following a : in file name in fitsropen() * Feb 23 2001 Initialize rbrac in fitsropen() * Mar 8 2001 Use % instead of : for WCS specification in file name * Mar 9 2001 Fix bug so primary header is always appended to secondary header * Mar 9 2001 Change NEXTEND to NUMEXT in appended primary header * Mar 20 2001 Declare fitsheadsize() in fitschead() * Apr 24 2001 When matching column names, use longest length * Jun 27 2001 In fitsrthead(), allocate pw and lpnam only if more space needed * Aug 24 2001 In isfits(), return 0 if argument contains an equal sign * * Jan 28 2002 In fitsrhead(), allow stdin to include extension and/or WCS selection * Jun 18 2002 Save error messages as fitserrmsg and use fitserr() to print them * Oct 21 2002 Add fitsrsect() to read a section of an image * * Feb 4 2003 Open catalog file rb instead of r (Martin Ploner, Bern) * Apr 2 2003 Drop unused variable in fitsrsect() * Jul 11 2003 Use strcasecmp() to check for stdout and stdin * Aug 1 2003 If no other header, return root header from fitsrhead() * Aug 20 2003 Add fitsrfull() to read n-dimensional FITS images * Aug 21 2003 Modify fitswimage() to always write n-dimensional FITS images * Nov 18 2003 Fix minor bug in fitswhdu() * Dec 3 2003 Remove unused variable lasthead in fitswhdu() * * May 3 2004 Do not always append primary header to extension header * May 3 2004 Add ibhead as position of header read in file * May 19 2004 Do not reset ext if NULL in fitswexhead() * Jul 1 2004 Initialize INHERIT to 1 * Aug 30 2004 Move fitsheadsize() declaration to fitsfile.h * Aug 31 2004 If SIMPLE=F, put whatever is in file after header in image * * Mar 17 2005 Use unbuffered I/O in isfits() for robustness * Jun 27 2005 Drop unused variable nblocks in fitswexhead() * Aug 8 2005 Fix space-padding bug in fitswexhead() found by Armin Rest * Sep 30 2005 Fix fitsrsect() to position relatively, not absolutely * Oct 28 2005 Add error message if desired FITS extension is not found * Oct 28 2005 Fix initialization problem found by Sergey Koposov * * Feb 23 2006 Add fitsrtail() to read appended FITS headers * Feb 27 2006 Add file name to header-reading error messages * May 3 2006 Remove declarations of unused variables * Jun 20 2006 Initialize uninitialized variables * Nov 2 2006 Change all realloc() calls to calloc() * * Jan 5 2007 In fitsrtail(), change control characters in header to spaces * Apr 30 2007 Improve error reporting in FITSRFULL * Nov 28 2007 Add support to BINTABLE in ftget*() and fitsrthead() * Dec 20 2007 Add data heap numerated by PCOUNT when skipping HDU in fitsrhead() * Dec 20 2007 Return NULL pointer if fitsrhead() cannot find requested HDU * * Apr 7 2008 Drop comma from name when reading file in isfits() * Jun 27 2008 Do not append primary data header if it is the only header * Nov 21 2008 In fitswhead(), print message if too few bytes written * * Sep 18 2009 In fitswexhead() write to error string instead of stderr * Sep 22 2009 In fitsrthead(), fix lengths for ASCII numeric table entries * Sep 25 2009 Add subroutine moveb() and fix calls to it * Sep 25 2009 Fix several small errors found by Jessicalas Burke * * Mar 29 2010 In fitswhead(), always pad blocks to 2880 bytes with spaces * Mar 31 2010 In fitsrhead(), fix bug reading long primary headers * * Sep 15 2011 In fitsrsect() declare impos and nblin off_t * Sep 15 2011 In fitsrtail() declare offset off_t * Sep 15 2011 Declare global variable ibhead off_t * * Jul 25 2014 Fix bug when reallocating buffer for long headers */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/COPYING0000644000175000017500000005775213047255533020532 0ustar mattymatty00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/distort.c0000664000175000017500000002303013047255533021313 0ustar mattymatty00000000000000/*** File libwcs/distort.c *** January 4, 2007 *** By Jessica Mink, jmink@cfa.harvard.edu, *** Based on code written by Jing Li, IPAC *** Harvard-Smithsonian Center for Astrophysics *** Copyright (C) 2004-2007 *** Smithsonian Astrophysical Observatory, Cambridge, MA, USA This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Correspondence concerning WCSTools should be addressed as follows: Internet email: jmink@cfa.harvard.edu Postal address: Jessica Mink Smithsonian Astrophysical Observatory 60 Garden St. Cambridge, MA 02138 USA * Module: distort.c (World Coordinate Systems) * Purpose: Convert focal plane coordinates to pixels and vice versa: * Subroutine: distortinit (wcs, hstring) set distortion coefficients from FITS header * Subroutine: DelDistort (header, verbose) delete distortion coefficients in FITS header * Subroutine: pix2foc (wcs, x, y, u, v) pixel coordinates -> focal plane coordinates * Subroutine: foc2pix (wcs, u, v, x, y) focal plane coordinates -> pixel coordinates * Subroutine: setdistcode (wcs,ctype) sets distortion code from CTYPEi * Subroutine: getdistcode (wcs) returns distortion code string for CTYPEi */ #include #include #include #include #include "wcs.h" void distortinit (wcs, hstring) struct WorldCoor *wcs; /* World coordinate system structure */ const char *hstring; /* character string containing FITS header information in the format = [/ ] */ { int i, j, m; char keyword[12]; /* Read distortion coefficients, if present */ if (wcs->distcode == DISTORT_SIRTF) { if (wcs->wcsproj == WCS_OLD) { wcs->wcsproj = WCS_NEW; wcs->distort.a_order = 0; wcs->distort.b_order = 0; wcs->distort.ap_order = 0; wcs->distort.bp_order = 0; } else { if (!hgeti4 (hstring, "A_ORDER", &wcs->distort.a_order)) { setwcserr ("DISTINIT: Missing A_ORDER keyword for Spitzer distortion"); } else { m = wcs->distort.a_order; for (i = 0; i <= m; i++) { for (j = 0; j <= m; j++) { wcs->distort.a[i][j] = 0.0; } } for (i = 0; i <= m; i++) { for (j = 0; j <= m-i; j++) { sprintf (keyword, "A_%d_%d", i, j); hgetr8 (hstring, keyword, &wcs->distort.a[i][j]); } } } if (!hgeti4 (hstring, "B_ORDER", &wcs->distort.b_order)) { setwcserr ("DISTINIT: Missing B_ORDER keyword for Spitzer distortion"); } else { m = wcs->distort.b_order; for (i = 0; i <= m; i++) { for (j = 0; j <= m; j++) { wcs->distort.b[i][j] = 0.0; } } for (i = 0; i <= m; i++) { for (j = 0; j <= m-i; j++) { sprintf (keyword, "B_%d_%d", i, j); hgetr8 (hstring, keyword, &wcs->distort.b[i][j]); } } } if (!hgeti4 (hstring, "AP_ORDER", &wcs->distort.ap_order)) { setwcserr ("DISTINIT: Missing AP_ORDER keyword for Spitzer distortion"); } else { m = wcs->distort.ap_order; for (i = 0; i <= m; i++) { for (j = 0; j <= m; j++) { wcs->distort.ap[i][j] = 0.0; } } for (i = 0; i <= m; i++) { for (j = 0; j <= m-i; j++) { sprintf (keyword, "AP_%d_%d", i, j); hgetr8 (hstring, keyword, &wcs->distort.ap[i][j]); } } } if (!hgeti4 (hstring, "BP_ORDER", &wcs->distort.bp_order)) { setwcserr ("DISTINIT: Missing BP_ORDER keyword for Spitzer distortion"); } else { m = wcs->distort.bp_order; for (i = 0; i <= m; i++) { for (j = 0; j <= m; j++) { wcs->distort.bp[i][j] = 0.0; } } for (i = 0; i <= m; i++) { for (j = 0; j <= m-i; j++) { sprintf (keyword, "BP_%d_%d", i, j); hgetr8 (hstring, keyword, &wcs->distort.bp[i][j]); } } } } } return; } /* Delete all distortion-related fields. * return 0 if at least one such field is found, else -1. */ int DelDistort (header, verbose) char *header; int verbose; { char keyword[16]; char str[32]; int i, j, m; int lctype; int n; n = 0; if (hgeti4 (header, "A_ORDER", &m)) { for (i = 0; i <= m; i++) { for (j = 0; j <= m-i; j++) { sprintf (keyword, "A_%d_%d", i, j); hdel (header, keyword); n++; } } hdel (header, "A_ORDER"); n++; } if (hgeti4 (header, "AP_ORDER", &m)) { for (i = 0; i <= m; i++) { for (j = 0; j <= m-i; j++) { sprintf (keyword, "AP_%d_%d", i, j); hdel (header, keyword); n++; } } hdel (header, "AP_ORDER"); n++; } if (hgeti4 (header, "B_ORDER", &m)) { for (i = 0; i <= m; i++) { for (j = 0; j <= m-i; j++) { sprintf (keyword, "B_%d_%d", i, j); hdel (header, keyword); n++; } } hdel (header, "B_ORDER"); n++; } if (hgeti4 (header, "BP_ORDER", &m)) { for (i = 0; i <= m; i++) { for (j = 0; j <= m-i; j++) { sprintf (keyword, "BP_%d_%d", i, j); hdel (header, keyword); n++; } } hdel (header, "BP_ORDER"); n++; } if (n > 0 && verbose) fprintf (stderr,"%d keywords deleted\n", n); /* Remove WCS distortion code from CTYPEi in FITS header */ if (hgets (header, "CTYPE1", 31, str)) { lctype = strlen (str); if (lctype > 8) { str[8] = (char) 0; hputs (header, "CTYPE1", str); } } if (hgets (header, "CTYPE2", 31, str)) { lctype = strlen (str); if (lctype > 8) { str[8] = (char) 0; hputs (header, "CTYPE2", str); } } return (n); } void foc2pix (wcs, x, y, u, v) struct WorldCoor *wcs; /* World coordinate system structure */ double x, y; /* Focal plane coordinates */ double *u, *v; /* Image pixel coordinates (returned) */ { int m, n, i, j, k; double s[DISTMAX], sum; double temp_x, temp_y; /* Spitzer distortion */ if (wcs->distcode == DISTORT_SIRTF) { m = wcs->distort.ap_order; n = wcs->distort.bp_order; temp_x = x - wcs->xrefpix; temp_y = y - wcs->yrefpix; /* compute u */ for (j = 0; j <= m; j++) { s[j] = wcs->distort.ap[m-j][j]; for (k = j-1; k >= 0; k--) { s[j] = (temp_y * s[j]) + wcs->distort.ap[m-j][k]; } } sum = s[0]; for (i=m; i>=1; i--){ sum = (temp_x * sum) + s[m-i+1]; } *u = sum; /* compute v*/ for (j = 0; j <= n; j++) { s[j] = wcs->distort.bp[n-j][j]; for (k = j-1; k >= 0; k--) { s[j] = temp_y*s[j] + wcs->distort.bp[n-j][k]; } } sum = s[0]; for (i = n; i >= 1; i--) sum = temp_x * sum + s[n-i+1]; *v = sum; *u = x + *u; *v = y + *v; } /* If no distortion, return pixel positions unchanged */ else { *u = x; *v = y; } return; } void pix2foc (wcs, u, v, x, y) struct WorldCoor *wcs; /* World coordinate system structure */ double u, v; /* Image pixel coordinates */ double *x, *y; /* Focal plane coordinates (returned) */ { int m, n, i, j, k; double s[DISTMAX], sum; double temp_u, temp_v; /* Spitzer distortion */ if (wcs->distcode == DISTORT_SIRTF) { m = wcs->distort.a_order; n = wcs->distort.b_order; temp_u = u - wcs->xrefpix; temp_v = v - wcs->yrefpix; /* compute u */ for (j = 0; j <= m; j++) { s[j] = wcs->distort.a[m-j][j]; for (k = j-1; k >= 0; k--) { s[j] = (temp_v * s[j]) + wcs->distort.a[m-j][k]; } } sum = s[0]; for (i=m; i>=1; i--){ sum = temp_u*sum + s[m-i+1]; } *x = sum; /* compute v*/ for (j=0; j<=n; j++) { s[j] = wcs->distort.b[n-j][j]; for (k=j-1; k>=0; k--) { s[j] =temp_v*s[j] + wcs->distort.b[n-j][k]; } } sum = s[0]; for (i=n; i>=1; i--) sum = temp_u*sum + s[n-i+1]; *y = sum; *x = u + *x; *y = v + *y; /* *x = u + *x + coeff.crpix1; */ /* *y = v + *y + coeff.crpix2; */ } /* If no distortion, return pixel positions unchanged */ else { *x = u; *y = v; } return; } /* SETDISTCODE -- Set WCS distortion code from CTYPEi in FITS header */ void setdistcode (wcs, ctype) struct WorldCoor *wcs; /* World coordinate system structure */ char *ctype; /* Value of CTYPEi from FITS header */ { char *extension; int lctype; lctype = strlen (ctype); if (lctype < 9) wcs->distcode = DISTORT_NONE; else { extension = ctype + 8; if (!strncmp (extension, "-SIP", 4)) wcs->distcode = DISTORT_SIRTF; else wcs->distcode = DISTORT_NONE; } return; } /* GETDISTCODE -- Return NULL if no distortion or code from wcs.h */ char * getdistcode (wcs) struct WorldCoor *wcs; /* World coordinate system structure */ { char *dcode; /* Distortion string for CTYPEi */ if (wcs->distcode == DISTORT_SIRTF) { dcode = (char *) calloc (8, sizeof (char)); strcpy (dcode, "-SIP"); } else dcode = NULL; return (dcode); } /* Apr 2 2003 New subroutines * Nov 3 2003 Add getdistcode to return distortion code string * Nov 10 2003 Include unistd.h to get definition of NULL * Nov 18 2003 Include string.h to get strlen() * * Jan 9 2004 Add DelDistort() to delete distortion keywords * * Jan 4 2007 Declare header const char* * * Feb 25 2011 Change SIRTF to Spitzer (long overdue!) */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/wcslib.c0000664000175000017500000012621113047255533021113 0ustar mattymatty00000000000000/*============================================================================= * * WCSLIB - an implementation of the FITS WCS proposal. * Copyright (C) 1995-2002, Mark Calabretta * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Correspondence concerning WCSLIB may be directed to: * Internet email: mcalabre@atnf.csiro.au * Postal address: Dr. Mark Calabretta, * Australia Telescope National Facility, * P.O. Box 76, * Epping, NSW, 2121, * AUSTRALIA * *============================================================================= * * C routines which implement the FITS World Coordinate System (WCS) * convention. * * Summary of routines * ------------------- * wcsfwd() and wcsrev() are high level driver routines for the WCS linear * transformation, spherical coordinate transformation, and spherical * projection routines. * * Given either the celestial longitude or latitude plus an element of the * pixel coordinate a hybrid routine, wcsmix(), iteratively solves for the * unknown elements. * * An initialization routine, wcsset(), computes indices from the ctype * array but need not be called explicitly - see the explanation of * wcs.flag below. * * * Initialization routine; wcsset() * -------------------------------- * Initializes elements of a wcsprm data structure which holds indices into * the coordinate arrays. Note that this routine need not be called directly; * it will be invoked by wcsfwd() and wcsrev() if the "flag" structure member * is anything other than a predefined magic value. * * Given: * naxis const int * Number of image axes. * ctype[][9] * const char * Coordinate axis types corresponding to the FITS * CTYPEn header cards. * * Returned: * wcs wcsprm* Indices for the celestial coordinates obtained * by parsing the ctype[] array (see below). * * Function return value: * int Error status * 0: Success. * 1: Inconsistent or unrecognized coordinate axis * types. * * * Forward transformation; wcsfwd() * -------------------------------- * Compute the pixel coordinate for given world coordinates. * * Given: * ctype[][9] * const char * Coordinate axis types corresponding to the FITS * CTYPEn header cards. * * Given or returned: * wcs wcsprm* Indices for the celestial coordinates obtained * by parsing the ctype[] array (see below). * * Given: * world const double[] * World coordinates. world[wcs->lng] and * world[wcs->lat] are the celestial longitude and * latitude, in degrees. * * Given: * crval const double[] * Coordinate reference values corresponding to the FITS * CRVALn header cards (see note 2). * * Given and returned: * cel celprm* Spherical coordinate transformation parameters (usage * is described in the prologue to "cel.c"). * * Returned: * phi, double* Longitude and latitude in the native coordinate * theta system of the projection, in degrees. * * Given and returned: * prj prjprm* Projection parameters (usage is described in the * prologue to "proj.c"). * * Returned: * imgcrd double[] Image coordinate. imgcrd[wcs->lng] and * imgcrd[wcs->lat] are the projected x-, and * y-coordinates, in "degrees". For quadcube * projections with a CUBEFACE axis the face number is * also returned in imgcrd[wcs->cubeface]. * * Given and returned: * lin linprm* Linear transformation parameters (usage is described * in the prologue to "lin.c"). * * Returned: * pixcrd double[] Pixel coordinate. * * Function return value: * int Error status * 0: Success. * 1: Invalid coordinate transformation parameters. * 2: Invalid projection parameters. * 3: Invalid world coordinate. * 4: Invalid linear transformation parameters. * * * Reverse transformation; wcsrev() * -------------------------------- * Compute world coordinates for a given pixel coordinate. * * Given: * ctype[][9] * const char * Coordinate axis types corresponding to the FITS * CTYPEn header cards. * * Given or returned: * wcs wcsprm* Indices for the celestial coordinates obtained * by parsing the ctype[] array (see below). * * Given: * pixcrd const double[] * Pixel coordinate. * * Given and returned: * lin linprm* Linear transformation parameters (usage is described * in the prologue to "lin.c"). * * Returned: * imgcrd double[] Image coordinate. imgcrd[wcs->lng] and * imgcrd[wcs->lat] are the projected x-, and * y-coordinates, in "degrees". * * Given and returned: * prj prjprm* Projection parameters (usage is described in the * prologue to "proj.c"). * * Returned: * phi, double* Longitude and latitude in the native coordinate * theta system of the projection, in degrees. * * Given: * crval const double[] * Coordinate reference values corresponding to the FITS * CRVALn header cards (see note 2). * * Given and returned: * cel celprm* Spherical coordinate transformation parameters * (usage is described in the prologue to "cel.c"). * * Returned: * world double[] World coordinates. world[wcs->lng] and * world[wcs->lat] are the celestial longitude and * latitude, in degrees. * * Function return value: * int Error status * 0: Success. * 1: Invalid coordinate transformation parameters. * 2: Invalid projection parameters. * 3: Invalid pixel coordinate. * 4: Invalid linear transformation parameters. * * * Hybrid transformation; wcsmix() * ------------------------------- * Given either the celestial longitude or latitude plus an element of the * pixel coordinate solve for the remaining elements by iterating on the * unknown celestial coordinate element using wcsfwd(). * * Given: * ctype[][9] * const char * Coordinate axis types corresponding to the FITS * CTYPEn header cards. * * Given or returned: * wcs wcsprm* Indices for the celestial coordinates obtained * by parsing the ctype[] array (see below). * * Given: * mixpix const int * Which element of the pixel coordinate is given. * mixcel const int * Which element of the celestial coordinate is * given: * 1: Celestial longitude is given in * world[wcs->lng], latitude returned in * world[wcs->lat]. * 2: Celestial latitude is given in * world[wcs->lat], longitude returned in * world[wcs->lng]. * vspan[2] const double * Solution interval for the celestial coordinate, in * degrees. The ordering of the two limits is * irrelevant. Longitude ranges may be specified with * any convenient normalization, for example [-120,+120] * is the same as [240,480], except that the solution * will be returned with the same normalization, i.e. * lie within the interval specified. * vstep const double * Step size for solution search, in degrees. If zero, * a sensible, although perhaps non-optimal default will * be used. * viter int * If a solution is not found then the step size will be * halved and the search recommenced. viter controls * how many times the step size is halved. The allowed * range is 5 - 10. * * Given and returned: * world double[] World coordinates. world[wcs->lng] and * world[wcs->lat] are the celestial longitude and * latitude, in degrees. Which is given and which * returned depends on the value of mixcel. All other * elements are given. * * Given: * crval const double[] * Coordinate reference values corresponding to the FITS * CRVALn header cards (see note 2). * * Given and returned: * cel celprm* Spherical coordinate transformation parameters * (usage is described in the prologue to "cel.c"). * * Returned: * phi, double* Longitude and latitude in the native coordinate * theta system of the projection, in degrees. * * Given and returned: * prj prjprm* Projection parameters (usage is described in the * prologue to "proj.c"). * * Returned: * imgcrd double[] Image coordinate. imgcrd[wcs->lng] and * imgcrd[wcs->lat] are the projected x-, and * y-coordinates, in "degrees". * * Given and returned: * lin linprm* Linear transformation parameters (usage is described * in the prologue to "lin.c"). * * Given and returned: * pixcrd double[] Pixel coordinate. The element indicated by mixpix is * given and the remaining elements are returned. * * Function return value: * int Error status * 0: Success. * 1: Invalid coordinate transformation parameters. * 2: Invalid projection parameters. * 3: Coordinate transformation error. * 4: Invalid linear transformation parameters. * 5: No solution found in the specified interval. * * * Notes * ----- * 1) The CTYPEn must in be upper case and there must be 0 or 1 pair of * matched celestial axis types. The ctype[][9] should be padded with * blanks on the right and null-terminated. * * 2) Elements of the crval[] array which correspond to celestial axes are * ignored, the reference coordinate values in cel->ref[0] and * cel->ref[1] are the ones used. * * 3) These functions recognize the NCP projection and convert it to the * equivalent SIN projection. * * They also recognize GLS as a synonym for SFL. * * 4) The quadcube projections (TSC, CSC, QSC) may be represented in FITS in * either of two ways: * * a) The six faces may be laid out in one plane and numbered as * follows: * * 0 * * 4 3 2 1 4 3 2 * * 5 * * Faces 2, 3 and 4 may appear on one side or the other (or both). * The forward routines map faces 2, 3 and 4 to the left but the * inverse routines accept them on either side. * * b) The "COBE" convention in which the six faces are stored in a * three-dimensional structure using a "CUBEFACE" axis indexed from * 0 to 5 as above. * * These routines support both methods; wcsset() determines which is * being used by the presence or absence of a CUBEFACE axis in ctype[]. * wcsfwd() and wcsrev() translate the CUBEFACE axis representation to * the single plane representation understood by the lower-level WCSLIB * projection routines. * * * WCS indexing parameters * ----------------------- * The wcsprm struct consists of the following: * * int flag * The wcsprm struct contains indexes and other information derived * from the CTYPEn. Whenever any of the ctype[] are set or changed * this flag must be set to zero to signal the initialization routine, * wcsset() to redetermine the indices. The flag is set to 999 if * there is no celestial axis pair in the CTYPEn. * * char pcode[4] * The WCS projection code. * * char lngtyp[5], lattyp[5] * WCS celestial axis types. * * int lng,lat * Indices into the imgcrd[], and world[] arrays as described above. * These may also serve as indices for the celestial longitude and * latitude axes in the pixcrd[] array provided that the PC matrix * does not transpose axes. * * int cubeface * Index into the pixcrd[] array for the CUBEFACE axis. This is * optionally used for the quadcube projections where each cube face is * stored on a separate axis. * * * wcsmix() algorithm * ------------------ * Initially the specified solution interval is checked to see if it's a * "crossing" interval. If it isn't, a search is made for a crossing * solution by iterating on the unknown celestial coordinate starting at * the upper limit of the solution interval and decrementing by the * specified step size. A crossing is indicated if the trial value of the * pixel coordinate steps through the value specified. If a crossing * interval is found then the solution is determined by a modified form of * "regula falsi" division of the crossing interval. If no crossing * interval was found within the specified solution interval then a search * is made for a "non-crossing" solution as may arise from a point of * tangency. The process is complicated by having to make allowance for * the discontinuities that occur in all map projections. * * Once one solution has been determined others may be found by subsequent * invokations of wcsmix() with suitably restricted solution intervals. * * Note the circumstance which arises when the solution point lies at a * native pole of a projection in which the pole is represented as a * finite curve, for example the zenithals and conics. In such cases two * or more valid solutions may exist but WCSMIX only ever returns one. * * Because of its generality wcsmix() is very compute-intensive. For * compute-limited applications more efficient special-case solvers could * be written for simple projections, for example non-oblique cylindrical * projections. * * Author: Mark Calabretta, Australia Telescope National Facility * $Id: wcs.c,v 2.23 2002/04/03 01:25:29 mcalabre Exp $ *===========================================================================*/ #include #include #include #include #include "wcslib.h" /* Map error number to error message for each function. */ const char *wcsset_errmsg[] = { 0, "Inconsistent or unrecognized coordinate axis types"}; const char *wcsfwd_errmsg[] = { 0, "Invalid coordinate transformation parameters", "Invalid projection parameters", "Invalid world coordinate", "Invalid linear transformation parameters"}; const char *wcsrev_errmsg[] = { 0, "Invalid coordinate transformation parameters", "Invalid projection parameters", "Invalid pixel coordinate", "Invalid linear transformation parameters"}; const char *wcsmix_errmsg[] = { 0, "Invalid coordinate transformation parameters", "Invalid projection parameters", "Coordinate transformation error", "Invalid linear transformation parameters", "No solution found in the specified interval"}; #define signb(X) ((X) < 0.0 ? 1 : 0) int wcsset (naxis, ctype, wcs) const int naxis; const char ctype[][9]; struct wcsprm *wcs; { int nalias = 2; char aliases [2][4] = {"NCP", "GLS"}; int j, k; int *ndx = NULL; char requir[9]; strcpy(wcs->pcode, ""); strcpy(requir, ""); wcs->lng = -1; wcs->lat = -1; wcs->cubeface = -1; for (j = 0; j < naxis; j++) { if (ctype[j][4] != '-') { if (strcmp(ctype[j], "CUBEFACE") == 0) { if (wcs->cubeface == -1) { wcs->cubeface = j; } else { /* Multiple CUBEFACE axes! */ return 1; } } continue; } /* Got an axis qualifier, is it a recognized WCS projection? */ for (k = 0; k < npcode; k++) { if (strncmp(&ctype[j][5], pcodes[k], 3) == 0) break; } if (k == npcode) { /* Maybe it's a projection alias. */ for (k = 0; k < nalias; k++) { if (strncmp(&ctype[j][5], aliases[k], 3) == 0) break; } /* Not recognized. */ if (k == nalias) { continue; } } /* Parse the celestial axis type. */ if (strcmp(wcs->pcode, "") == 0) { sprintf(wcs->pcode, "%.3s", &ctype[j][5]); if (strncmp(ctype[j], "RA--", 4) == 0) { wcs->lng = j; strcpy(wcs->lngtyp, "RA"); strcpy(wcs->lattyp, "DEC"); ndx = &wcs->lat; sprintf(requir, "DEC--%s", wcs->pcode); } else if (strncmp(ctype[j], "DEC-", 4) == 0) { wcs->lat = j; strcpy(wcs->lngtyp, "RA"); strcpy(wcs->lattyp, "DEC"); ndx = &wcs->lng; sprintf(requir, "RA---%s", wcs->pcode); } else if (strncmp(&ctype[j][1], "LON", 3) == 0) { wcs->lng = j; sprintf(wcs->lngtyp, "%cLON", ctype[j][0]); sprintf(wcs->lattyp, "%cLAT", ctype[j][0]); ndx = &wcs->lat; sprintf(requir, "%s-%s", wcs->lattyp, wcs->pcode); } else if (strncmp(&ctype[j][1], "LAT", 3) == 0) { wcs->lat = j; sprintf(wcs->lngtyp, "%cLON", ctype[j][0]); sprintf(wcs->lattyp, "%cLAT", ctype[j][0]); ndx = &wcs->lng; sprintf(requir, "%s-%s", wcs->lngtyp, wcs->pcode); } else if (strncmp(&ctype[j][2], "LN", 2) == 0) { wcs->lng = j; sprintf(wcs->lngtyp, "%c%cLN", ctype[j][0], ctype[j][1]); sprintf(wcs->lattyp, "%c%cLT", ctype[j][0], ctype[j][1]); ndx = &wcs->lat; sprintf(requir, "%s-%s", wcs->lattyp, wcs->pcode); } else if (strncmp(&ctype[j][2], "LT", 2) == 0) { wcs->lat = j; sprintf(wcs->lngtyp, "%c%cLN", ctype[j][0], ctype[j][1]); sprintf(wcs->lattyp, "%c%cLT", ctype[j][0], ctype[j][1]); ndx = &wcs->lng; sprintf(requir, "%s-%s", wcs->lngtyp, wcs->pcode); } else { /* Unrecognized celestial type. */ return 1; } } else { if (strncmp(ctype[j], requir, 8) != 0) { /* Inconsistent projection types. */ return 1; } if (ndx == NULL) return 1; *ndx = j; strcpy(requir, ""); } } if (strcmp(requir, "")) { /* Unmatched celestial axis. */ return 1; } /* Do simple alias translations. */ if (strncmp(wcs->pcode, "GLS", 3) == 0) { strcpy(wcs->pcode, "SFL"); } if (strcmp(wcs->pcode, "")) { wcs->flag = WCSSET; } else { /* Signal for no celestial axis pair. */ wcs->flag = 999; } return 0; } /*--------------------------------------------------------------------------*/ int wcsfwd(ctype, wcs, world, crval, cel, phi, theta, prj, imgcrd, lin, pixcrd) const char ctype[][9]; struct wcsprm* wcs; const double world[]; const double crval[]; struct celprm *cel; double *phi, *theta; struct prjprm *prj; double imgcrd[]; struct linprm *lin; double pixcrd[]; { int err, j; double offset; /* Initialize if required. */ if (wcs->flag != WCSSET) { if (wcsset(lin->naxis, ctype, wcs)) return 1; } /* Convert to relative physical coordinates. */ for (j = 0; j < lin->naxis; j++) { if (j == wcs->lng) continue; if (j == wcs->lat) continue; imgcrd[j] = world[j] - crval[j]; } if (wcs->flag != 999) { /* Compute projected coordinates. */ if (strcmp(wcs->pcode, "NCP") == 0) { /* Convert NCP to SIN. */ if (cel->ref[1] == 0.0) { return 2; } strcpy(wcs->pcode, "SIN"); prj->p[1] = 0.0; prj->p[2] = cosdeg (cel->ref[1])/sindeg (cel->ref[1]); prj->flag = (prj->flag < 0) ? -1 : 0; } if ((err = celfwd(wcs->pcode, world[wcs->lng], world[wcs->lat], cel, phi, theta, prj, &imgcrd[wcs->lng], &imgcrd[wcs->lat]))) { return err; } /* Do we have a CUBEFACE axis? */ if (wcs->cubeface != -1) { /* Separation between faces. */ if (prj->r0 == 0.0) { offset = 90.0; } else { offset = prj->r0*PI/2.0; } /* Stack faces in a cube. */ if (imgcrd[wcs->lat] < -0.5*offset) { imgcrd[wcs->lat] += offset; imgcrd[wcs->cubeface] = 5.0; } else if (imgcrd[wcs->lat] > 0.5*offset) { imgcrd[wcs->lat] -= offset; imgcrd[wcs->cubeface] = 0.0; } else if (imgcrd[wcs->lng] > 2.5*offset) { imgcrd[wcs->lng] -= 3.0*offset; imgcrd[wcs->cubeface] = 4.0; } else if (imgcrd[wcs->lng] > 1.5*offset) { imgcrd[wcs->lng] -= 2.0*offset; imgcrd[wcs->cubeface] = 3.0; } else if (imgcrd[wcs->lng] > 0.5*offset) { imgcrd[wcs->lng] -= offset; imgcrd[wcs->cubeface] = 2.0; } else { imgcrd[wcs->cubeface] = 1.0; } } } /* Apply forward linear transformation. */ if (linfwd(imgcrd, lin, pixcrd)) { return 4; } return 0; } /*--------------------------------------------------------------------------*/ int wcsrev(ctype, wcs, pixcrd, lin, imgcrd, prj, phi, theta, crval, cel, world) const char ctype[][9]; struct wcsprm *wcs; const double pixcrd[]; struct linprm *lin; double imgcrd[]; struct prjprm *prj; double *phi, *theta; const double crval[]; struct celprm *cel; double world[]; { int err, face, j; double offset; /* Initialize if required. */ if (wcs->flag != WCSSET) { if (wcsset(lin->naxis, ctype, wcs)) return 1; } /* Apply reverse linear transformation. */ if (linrev(pixcrd, lin, imgcrd)) { return 4; } /* Convert to world coordinates. */ for (j = 0; j < lin->naxis; j++) { if (j == wcs->lng) continue; if (j == wcs->lat) continue; world[j] = imgcrd[j] + crval[j]; } if (wcs->flag != 999) { /* Do we have a CUBEFACE axis? */ if (wcs->cubeface != -1) { face = (int)(imgcrd[wcs->cubeface] + 0.5); if (fabs(imgcrd[wcs->cubeface]-face) > 1e-10) { return 3; } /* Separation between faces. */ if (prj->r0 == 0.0) { offset = 90.0; } else { offset = prj->r0*PI/2.0; } /* Lay out faces in a plane. */ switch (face) { case 0: imgcrd[wcs->lat] += offset; break; case 1: break; case 2: imgcrd[wcs->lng] += offset; break; case 3: imgcrd[wcs->lng] += offset*2; break; case 4: imgcrd[wcs->lng] += offset*3; break; case 5: imgcrd[wcs->lat] -= offset; break; default: return 3; } } /* Compute celestial coordinates. */ if (strcmp(wcs->pcode, "NCP") == 0) { /* Convert NCP to SIN. */ if (cel->ref[1] == 0.0) { return 2; } strcpy(wcs->pcode, "SIN"); prj->p[1] = 0.0; prj->p[2] = cosdeg (cel->ref[1])/sindeg (cel->ref[1]); prj->flag = (prj->flag < 0) ? -1 : 0; } if ((err = celrev(wcs->pcode, imgcrd[wcs->lng], imgcrd[wcs->lat], prj, phi, theta, cel, &world[wcs->lng], &world[wcs->lat]))) { return err; } } return 0; } /*--------------------------------------------------------------------------*/ int wcsmix(ctype, wcs, mixpix, mixcel, vspan, vstep, viter, world, crval, cel, phi, theta, prj, imgcrd, lin, pixcrd) const char ctype[][9]; struct wcsprm *wcs; const int mixpix, mixcel; const double vspan[2], vstep; int viter; double world[]; const double crval[]; struct celprm *cel; double *phi, *theta; struct prjprm *prj; double imgcrd[]; struct linprm *lin; double pixcrd[]; { const int niter = 60; int crossed, err, istep, iter, j, k, nstep, retry; const double tol = 1.0e-10; const double tol2 = 100.0*tol; double lambda, span[2], step; double pixmix; double dlng, lng, lng0, lng0m, lng1, lng1m; double dlat, lat, lat0, lat0m, lat1, lat1m; double d, d0, d0m, d1, d1m; double dx = 0.0; double dabs, dmin, lmin; double dphi, phi0, phi1; struct celprm cel0; /* Initialize if required. */ if (wcs->flag != WCSSET) { if (wcsset(lin->naxis, ctype, wcs)) return 1; } /* Check vspan. */ if (vspan[0] <= vspan[1]) { span[0] = vspan[0]; span[1] = vspan[1]; } else { /* Swap them. */ span[0] = vspan[1]; span[1] = vspan[0]; } /* Check vstep. */ step = fabs(vstep); if (step == 0.0) { step = (span[1] - span[0])/10.0; if (step > 1.0 || step == 0.0) step = 1.0; } /* Check viter. */ nstep = viter; if (nstep < 5) { nstep = 5; } else if (nstep > 10) { nstep = 10; } /* Given pixel element. */ pixmix = pixcrd[mixpix]; /* Iterate on the step size. */ for (istep = 0; istep <= nstep; istep++) { if (istep) step /= 2.0; /* Iterate on the sky coordinate between the specified range. */ if (mixcel == 1) { /* Celestial longitude is given. */ /* Check whether the solution interval is a crossing interval. */ lat0 = span[0]; world[wcs->lat] = lat0; if ((err = wcsfwd(ctype, wcs, world, crval, cel, phi, theta, prj, imgcrd, lin, pixcrd))) { return err; } d0 = pixcrd[mixpix] - pixmix; dabs = fabs(d0); if (dabs < tol) return 0; lat1 = span[1]; world[wcs->lat] = lat1; if ((err = wcsfwd(ctype, wcs, world, crval, cel, phi, theta, prj, imgcrd, lin, pixcrd))) { return err; } d1 = pixcrd[mixpix] - pixmix; dabs = fabs(d1); if (dabs < tol) return 0; lmin = lat1; dmin = dabs; /* Check for a crossing point. */ if (signb(d0) != signb(d1)) { crossed = 1; dx = d1; } else { crossed = 0; lat0 = span[1]; } for (retry = 0; retry < 4; retry++) { /* Refine the solution interval. */ while (lat0 > span[0]) { lat0 -= step; if (lat0 < span[0]) lat0 = span[0]; world[wcs->lat] = lat0; if ((err = wcsfwd(ctype, wcs, world, crval, cel, phi, theta, prj, imgcrd, lin, pixcrd))) { return err; } d0 = pixcrd[mixpix] - pixmix; /* Check for a solution. */ dabs = fabs(d0); if (dabs < tol) return 0; /* Record the point of closest approach. */ if (dabs < dmin) { lmin = lat0; dmin = dabs; } /* Check for a crossing point. */ if (signb(d0) != signb(d1)) { crossed = 2; dx = d0; break; } /* Advance to the next subinterval. */ lat1 = lat0; d1 = d0; } if (crossed) { /* A crossing point was found. */ for (iter = 0; iter < niter; iter++) { /* Use regula falsi division of the interval. */ lambda = d0/(d0-d1); if (lambda < 0.1) { lambda = 0.1; } else if (lambda > 0.9) { lambda = 0.9; } dlat = lat1 - lat0; lat = lat0 + lambda*dlat; world[wcs->lat] = lat; if ((err = wcsfwd(ctype, wcs, world, crval, cel, phi, theta, prj, imgcrd, lin, pixcrd))) { return err; } /* Check for a solution. */ d = pixcrd[mixpix] - pixmix; dabs = fabs(d); if (dabs < tol) return 0; if (dlat < tol) { /* An artifact of numerical imprecision. */ if (dabs < tol2) return 0; /* Must be a discontinuity. */ break; } /* Record the point of closest approach. */ if (dabs < dmin) { lmin = lat; dmin = dabs; } if (signb(d0) == signb(d)) { lat0 = lat; d0 = d; } else { lat1 = lat; d1 = d; } } /* No convergence, must have been a discontinuity. */ if (crossed == 1) lat0 = span[1]; lat1 = lat0; d1 = dx; crossed = 0; } else { /* No crossing point; look for a tangent point. */ if (lmin == span[0]) break; if (lmin == span[1]) break; lat = lmin; lat0 = lat - step; if (lat0 < span[0]) lat0 = span[0]; lat1 = lat + step; if (lat1 > span[1]) lat1 = span[1]; world[wcs->lat] = lat0; if ((err = wcsfwd(ctype, wcs, world, crval, cel, phi, theta, prj, imgcrd, lin, pixcrd))) { return err; } d0 = fabs(pixcrd[mixpix] - pixmix); d = dmin; world[wcs->lat] = lat1; if ((err = wcsfwd(ctype, wcs, world, crval, cel, phi, theta, prj, imgcrd, lin, pixcrd))) { return err; } d1 = fabs(pixcrd[mixpix] - pixmix); for (iter = 0; iter < niter; iter++) { lat0m = (lat0 + lat)/2.0; world[wcs->lat] = lat0m; if ((err = wcsfwd(ctype, wcs, world, crval, cel, phi, theta, prj, imgcrd, lin, pixcrd))) { return err; } d0m = fabs(pixcrd[mixpix] - pixmix); if (d0m < tol) return 0; lat1m = (lat1 + lat)/2.0; world[wcs->lat] = lat1m; if ((err = wcsfwd(ctype, wcs, world, crval, cel, phi, theta, prj, imgcrd, lin, pixcrd))) { return err; } d1m = fabs(pixcrd[mixpix] - pixmix); if (d1m < tol) return 0; if (d0m < d && d0m <= d1m) { lat1 = lat; d1 = d; lat = lat0m; d = d0m; } else if (d1m < d) { lat0 = lat; d0 = d; lat = lat1m; d = d1m; } else { lat0 = lat0m; d0 = d0m; lat1 = lat1m; d1 = d1m; } } } } } else { /* Celestial latitude is given. */ /* Check whether the solution interval is a crossing interval. */ lng0 = span[0]; world[wcs->lng] = lng0; if ((err = wcsfwd(ctype, wcs, world, crval, cel, phi, theta, prj, imgcrd, lin, pixcrd))) { return err; } d0 = pixcrd[mixpix] - pixmix; dabs = fabs(d0); if (dabs < tol) return 0; lng1 = span[1]; world[wcs->lng] = lng1; if ((err = wcsfwd(ctype, wcs, world, crval, cel, phi, theta, prj, imgcrd, lin, pixcrd))) { return err; } d1 = pixcrd[mixpix] - pixmix; dabs = fabs(d1); if (dabs < tol) return 0; lmin = lng1; dmin = dabs; /* Check for a crossing point. */ if (signb(d0) != signb(d1)) { crossed = 1; dx = d1; } else { crossed = 0; lng0 = span[1]; } for (retry = 0; retry < 4; retry++) { /* Refine the solution interval. */ while (lng0 > span[0]) { lng0 -= step; if (lng0 < span[0]) lng0 = span[0]; world[wcs->lng] = lng0; if ((err = wcsfwd(ctype, wcs, world, crval, cel, phi, theta, prj, imgcrd, lin, pixcrd))) { return err; } d0 = pixcrd[mixpix] - pixmix; /* Check for a solution. */ dabs = fabs(d0); if (dabs < tol) return 0; /* Record the point of closest approach. */ if (dabs < dmin) { lmin = lng0; dmin = dabs; } /* Check for a crossing point. */ if (signb(d0) != signb(d1)) { crossed = 2; dx = d0; break; } /* Advance to the next subinterval. */ lng1 = lng0; d1 = d0; } if (crossed) { /* A crossing point was found. */ for (iter = 0; iter < niter; iter++) { /* Use regula falsi division of the interval. */ lambda = d0/(d0-d1); if (lambda < 0.1) { lambda = 0.1; } else if (lambda > 0.9) { lambda = 0.9; } dlng = lng1 - lng0; lng = lng0 + lambda*dlng; world[wcs->lng] = lng; if ((err = wcsfwd(ctype, wcs, world, crval, cel, phi, theta, prj, imgcrd, lin, pixcrd))) { return err; } /* Check for a solution. */ d = pixcrd[mixpix] - pixmix; dabs = fabs(d); if (dabs < tol) return 0; if (dlng < tol) { /* An artifact of numerical imprecision. */ if (dabs < tol2) return 0; /* Must be a discontinuity. */ break; } /* Record the point of closest approach. */ if (dabs < dmin) { lmin = lng; dmin = dabs; } if (signb(d0) == signb(d)) { lng0 = lng; d0 = d; } else { lng1 = lng; d1 = d; } } /* No convergence, must have been a discontinuity. */ if (crossed == 1) lng0 = span[1]; lng1 = lng0; d1 = dx; crossed = 0; } else { /* No crossing point; look for a tangent point. */ if (lmin == span[0]) break; if (lmin == span[1]) break; lng = lmin; lng0 = lng - step; if (lng0 < span[0]) lng0 = span[0]; lng1 = lng + step; if (lng1 > span[1]) lng1 = span[1]; world[wcs->lng] = lng0; if ((err = wcsfwd(ctype, wcs, world, crval, cel, phi, theta, prj, imgcrd, lin, pixcrd))) { return err; } d0 = fabs(pixcrd[mixpix] - pixmix); d = dmin; world[wcs->lng] = lng1; if ((err = wcsfwd(ctype, wcs, world, crval, cel, phi, theta, prj, imgcrd, lin, pixcrd))) { return err; } d1 = fabs(pixcrd[mixpix] - pixmix); for (iter = 0; iter < niter; iter++) { lng0m = (lng0 + lng)/2.0; world[wcs->lng] = lng0m; if ((err = wcsfwd(ctype, wcs, world, crval, cel, phi, theta, prj, imgcrd, lin, pixcrd))) { return err; } d0m = fabs(pixcrd[mixpix] - pixmix); if (d0m < tol) return 0; lng1m = (lng1 + lng)/2.0; world[wcs->lng] = lng1m; if ((err = wcsfwd(ctype, wcs, world, crval, cel, phi, theta, prj, imgcrd, lin, pixcrd))) { return err; } d1m = fabs(pixcrd[mixpix] - pixmix); if (d1m < tol) return 0; if (d0m < d && d0m <= d1m) { lng1 = lng; d1 = d; lng = lng0m; d = d0m; } else if (d1m < d) { lng0 = lng; d0 = d; lng = lng1m; d = d1m; } else { lng0 = lng0m; d0 = d0m; lng1 = lng1m; d1 = d1m; } } } } } } /* Set cel0 to the unity transformation. */ cel0.flag = CELSET; cel0.ref[0] = cel->ref[0]; cel0.ref[1] = cel->ref[1]; cel0.ref[2] = cel->ref[2]; cel0.ref[3] = cel->ref[3]; cel0.euler[0] = -90.0; cel0.euler[1] = 0.0; cel0.euler[2] = 90.0; cel0.euler[3] = 1.0; cel0.euler[4] = 0.0; /* No convergence, check for aberrant behaviour at a native pole. */ *theta = -90.0; for (j = 1; j <= 2; j++) { /* Could the celestial coordinate element map to a native pole? */ *theta = -*theta; err = sphrev(0.0, *theta, cel->euler, &lng, &lat); if (mixcel == 1) { if (fabs(fmod(world[wcs->lng]-lng,360.0)) > tol) continue; if (lat < span[0]) continue; if (lat > span[1]) continue; world[wcs->lat] = lat; } else { if (fabs(world[wcs->lat]-lat) > tol) continue; if (lng < span[0]) lng += 360.0; if (lng > span[1]) lng -= 360.0; if (lng < span[0]) continue; if (lng > span[1]) continue; world[wcs->lng] = lng; } /* Is there a solution for the given pixel coordinate element? */ lng = world[wcs->lng]; lat = world[wcs->lat]; /* Feed native coordinates to wcsfwd() with cel0 set to unity. */ world[wcs->lng] = -180.0; world[wcs->lat] = *theta; if ((err = wcsfwd(ctype, wcs, world, crval, &cel0, phi, theta, prj, imgcrd, lin, pixcrd))) { return err; } d0 = pixcrd[mixpix] - pixmix; /* Check for a solution. */ if (fabs(d0) < tol) { /* Recall saved world coordinates. */ world[wcs->lng] = lng; world[wcs->lat] = lat; return 0; } /* Search for a crossing interval. */ phi0 = -180.0; for (k = -179; k <= 180; k++) { phi1 = (double) k; world[wcs->lng] = phi1; if ((err = wcsfwd(ctype, wcs, world, crval, &cel0, phi, theta, prj, imgcrd, lin, pixcrd))) { return err; } d1 = pixcrd[mixpix] - pixmix; /* Check for a solution. */ dabs = fabs(d1); if (dabs < tol) { /* Recall saved world coordinates. */ world[wcs->lng] = lng; world[wcs->lat] = lat; return 0; } /* Is it a crossing interval? */ if (signb(d0) != signb(d1)) break; phi0 = phi1; d0 = d1; } for (iter = 1; iter <= niter; iter++) { /* Use regula falsi division of the interval. */ lambda = d0/(d0-d1); if (lambda < 0.1) { lambda = 0.1; } else if (lambda > 0.9) { lambda = 0.9; } dphi = phi1 - phi0; world[wcs->lng] = phi0 + lambda*dphi; if ((err = wcsfwd(ctype, wcs, world, crval, &cel0, phi, theta, prj, imgcrd, lin, pixcrd))) { return err; } /* Check for a solution. */ d = pixcrd[mixpix] - pixmix; dabs = fabs(d); if (dabs < tol || (dphi < tol && dabs < tol2)) { /* Recall saved world coordinates. */ world[wcs->lng] = lng; world[wcs->lat] = lat; return 0; } if (signb(d0) == signb(d)) { phi0 = world[wcs->lng]; d0 = d; } else { phi1 = world[wcs->lng]; d1 = d; } } } /* No solution. */ return 5; } /* Dec 20 1999 Doug Mink - Change signbit() to signb() and always define it * Dec 20 1999 Doug Mink - Include wcslib.h, which includes wcs.h, wcstrig.h * * Mar 20 2001 Doug Mink - Include stdio.h for sprintf() * Mar 20 2001 Doug Mink - Add () around err assignments in if statements * Sep 19 2001 Doug Mink - Add above changes to WCSLIB-2.7 version * * Mar 15 2002 Doug Mink - Add above changes to WCSLIB-2.8.2 * Apr 3 2002 Mark Calabretta - Fix bug in code checking section * * Jun 20 2006 Doug Mink - Initialized uninitialized variables */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/imio.c0000664000175000017500000011152413047255533020566 0ustar mattymatty00000000000000/*** File wcslib/imio.c *** October 30, 2012 *** By Jessica Mink, jmink@cfa.harvard.edu *** Harvard-Smithsonian Center for Astrophysics *** Copyright (C) 1996-2012 *** Smithsonian Astrophysical Observatory, Cambridge, MA, USA This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Correspondence concerning WCSTools should be addressed as follows: Internet email: jmink@cfa.harvard.edu Postal address: Jessica Mink Smithsonian Astrophysical Observatory 60 Garden St. Cambridge, MA 02138 USA * Module: imio.c (image pixel manipulation) * Purpose: Read and write pixels from arbitrary data type 2D arrays * Subroutine: getpix (image, bitpix, w, h, bz, bs, x, y) * Read pixel from 2D image of any numeric type (0,0 lower left) * Subroutine: getpix1 (image, bitpix, w, h, bz, bs, x, y) * Read pixel from 2D image of any numeric type (1,1 lower left) * Subroutine: putpix (image, bitpix, w, h, bz, bs, x, y, dpix) * Write pixel into 2D image of any numeric type (0,0 lower left) * Subroutine: putpix1 (image, bitpix, w, h, bz, bs, x, y, dpix) * Write pixel into 2D image of any numeric type (1,1 lower left) * Subroutine: addpix (image, bitpix, w, h, bz, bs, x, y, dpix) * Copy pixel into 2D image of any numeric type (0,0 lower left) * Subroutine: addpix1 (image, bitpix, w, h, bz, bs, x, y, dpix) * Add pixel into 2D image of any numeric type (1,1 lower left) * Subroutine: maxvec (image, bitpix, bz, bs, pix1, npix) * Get maximum of vector from 2D image of any numeric type * Subroutine: minvec (image, bitpix, bz, bs, pix1, npix) * Get minimum of vector from 2D image of any numeric type * Subroutine: getvec (image, bitpix, bz, bs, pix1, npix, dvec) * Get vector from 2D image of any numeric type * Subroutine: putvec (image, bitpix, bz, bs, pix1, npix, dvec) * Copy pixel vector into a vector of any numeric type * Subroutine: addvec (image, bitpix, bz, bs, pix1, npix, dpix) * Add constant to pixel values in a vector * Subroutine: multvec (image, bitpix, bz, bs, pix1, npix, dpix) * Multiply pixel values in a vector by a constant * Subroutine: fillvec (image, bitpix, bz, bs, pix1, npix, dpix) * Copy pixel value in a vector of any numeric type * Subroutine: fillvec1 (image, bitpix, bz, bs, pix1, npix, dpix) * Copy pixel value int a vector of any numeric type * Subroutine: movepix (image1, bitpix, w1, x1, y1, image2, w2, x2, y2) * Copy pixel from one image location to another * Subroutine: imswap (bitpix,string,nbytes) * Swap bytes in string in place, with FITS bits/pixel code * Subroutine: imswap2 (string,nbytes) * Swap bytes in string in place * Subroutine imswap4 (string,nbytes) * Reverse bytes of Integer*4 or Real*4 vector in place * Subroutine imswap8 (string,nbytes) * Reverse bytes of Real*8 vector in place * Subroutine imswapped () * Return 1 if PC/DEC byte order, else 0 */ #include #include #include "fitsfile.h" static int scale = 1; /* If 0, skip scaling step */ void setscale (scale0) int scale0; {scale = scale0; return;} /* GETPIX1 -- Get pixel from 2D FITS image of any numeric type */ double getpix1 (image, bitpix, w, h, bzero, bscale, x, y) char *image; /* Image array as 1-D vector */ int bitpix; /* FITS bits per pixel */ /* 16 = short, -16 = unsigned short, 32 = int */ /* -32 = float, -64 = double */ int w; /* Image width in pixels */ int h; /* Image height in pixels */ double bzero; /* Zero point for pixel scaling */ double bscale; /* Scale factor for pixel scaling */ int x; /* One-based horizontal pixel number */ int y; /* One-based vertical pixel number */ { return (getpix (image, bitpix, w, h, bzero, bscale, x-1, y-1)); } /* GETPIX -- Get pixel from 2D image of any numeric type */ double getpix (image, bitpix, w, h, bzero, bscale, x, y) char *image; /* Image array as 1-D vector */ int bitpix; /* FITS bits per pixel */ /* 16 = short, -16 = unsigned short, 32 = int */ /* -32 = float, -64 = double */ int w; /* Image width in pixels */ int h; /* Image height in pixels */ double bzero; /* Zero point for pixel scaling */ double bscale; /* Scale factor for pixel scaling */ int x; /* Zero-based horizontal pixel number */ int y; /* Zero-based vertical pixel number */ { short *im2; int *im4; unsigned char *im1; unsigned short *imu; float *imr; double *imd; double dpix; /* Return 0 if coordinates are not inside image */ if (x < 0 || x >= w) return (0.0); if (y < 0 || y >= h) return (0.0); /* Extract pixel from appropriate type of array */ switch (bitpix) { case 8: im1 = (unsigned char *)image; dpix = (double) im1[(y*w) + x]; break; case 16: im2 = (short *)image; dpix = (double) im2[(y*w) + x]; break; case 32: im4 = (int *)image; dpix = (double) im4[(y*w) + x]; break; case -16: imu = (unsigned short *)image; dpix = (double) imu[(y*w) + x]; break; case -32: imr = (float *)image; dpix = (double) imr[(y*w) + x]; break; case -64: imd = (double *)image; dpix = imd[(y*w) + x]; break; default: dpix = 0.0; } if (scale) return (bzero + (bscale * dpix)); else return (dpix); } /* PUTPIX1 -- Copy pixel into 2D FITS image of any numeric type */ void putpix1 (image, bitpix, w, h, bzero, bscale, x, y, dpix) char *image; int bitpix; /* Number of bits per pixel */ /* 16 = short, -16 = unsigned short, 32 = int */ /* -32 = float, -64 = double */ int w; /* Image width in pixels */ int h; /* Image height in pixels */ double bzero; /* Zero point for pixel scaling */ double bscale; /* Scale factor for pixel scaling */ int x; /* One-based horizontal pixel number */ int y; /* One-based vertical pixel number */ double dpix; { putpix (image, bitpix, w, h, bzero, bscale, x-1, y-1, dpix); return; } /* PUTPIX -- Copy pixel into 2D image of any numeric type */ void putpix (image, bitpix, w, h, bzero, bscale, x, y, dpix) char *image; int bitpix; /* Number of bits per pixel */ /* 16 = short, -16 = unsigned short, 32 = int */ /* -32 = float, -64 = double */ int w; /* Image width in pixels */ int h; /* Image height in pixels */ double bzero; /* Zero point for pixel scaling */ double bscale; /* Scale factor for pixel scaling */ int x; int y; double dpix; { double *imd; float *imr; int *im4; short *im2; unsigned short *imu; unsigned char *im1; /* Return if coordinates are not inside image */ if (x < 0 || x >= w) return; if (y < 0 || y >= h) return; if (scale) dpix = (dpix - bzero) / bscale; switch (bitpix) { case 8: im1 = (unsigned char *)image; if (dpix < 0) im1[(y*w) + x] = (unsigned char) (dpix - 0.5); else im1[(y*w) + x] = (unsigned char) (dpix + 0.5); break; case 16: im2 = (short *)image; if (dpix < 0) im2[(y*w) + x] = (short) (dpix - 0.5); else im2[(y*w) + x] = (short) (dpix + 0.5); break; case 32: im4 = (int *)image; if (dpix < 0) im4[(y*w) + x] = (int) (dpix - 0.5); else im4[(y*w) + x] = (int) (dpix + 0.5); break; case -16: imu = (unsigned short *)image; if (dpix < 0) imu[(y*w) + x] = (unsigned short) 0; else imu[(y*w) + x] = (unsigned short) (dpix + 0.5); break; case -32: imr = (float *)image; imr[(y*w) + x] = (float) dpix; break; case -64: imd = (double *)image; imd[(y*w) + x] = dpix; break; } return; } /* ADDPIX1 -- Add pixel value into 2D FITS image of any numeric type */ void addpix1 (image, bitpix, w, h, bzero, bscale, x, y, dpix) char *image; int bitpix; /* Number of bits per pixel */ /* 16 = short, -16 = unsigned short, 32 = int */ /* -32 = float, -64 = double */ int w; /* Image width in pixels */ int h; /* Image height in pixels */ double bzero; /* Zero point for pixel scaling */ double bscale; /* Scale factor for pixel scaling */ int x; /* One-based horizontal pixel number */ int y; /* One-based vertical pixel number */ double dpix; /* Value to add to pixel */ { addpix (image, bitpix, w, h, bzero, bscale, x-1, y-1, dpix); return; } /* ADDPIX -- Add constant to pixel values in 2D image of any numeric type */ void addpix (image, bitpix, w, h, bzero, bscale, x, y, dpix) char *image; int bitpix; /* Number of bits per pixel */ /* 16 = short, -16 = unsigned short, 32 = int */ /* -32 = float, -64 = double */ int w; /* Image width in pixels */ int h; /* Image height in pixels */ double bzero; /* Zero point for pixel scaling */ double bscale; /* Scale factor for pixel scaling */ int x; /* Zero-based horizontal pixel number */ int y; /* Zero-based vertical pixel number */ double dpix; /* Value to add to pixel */ { double *imd; float *imr; int *im4; short *im2; unsigned short *imu; unsigned char *im1; int ipix; /* Return if coordinates are not inside image */ if (x < 0 || x >= w) return; if (y < 0 || y >= h) return; if (scale) dpix = (dpix - bzero) / bscale; ipix = (y * w) + x; switch (bitpix) { case 8: im1 = (unsigned char *)image; if (dpix < 0) image[ipix] = im1[ipix] + (unsigned char) (dpix - 0.5); else image[ipix] = im1[ipix] + (unsigned char) (dpix + 0.5); break; case 16: im2 = (short *)image; if (dpix < 0) im2[ipix] = im2[ipix] + (short) (dpix - 0.5); else im2[ipix] = im2[ipix] + (short) (dpix + 0.5); break; case 32: im4 = (int *)image; if (dpix < 0) im4[ipix] = im4[ipix] + (int) (dpix - 0.5); else im4[ipix] = im4[ipix] + (int) (dpix + 0.5); break; case -16: imu = (unsigned short *)image; if (dpix > 0) imu[ipix] = imu[ipix] + (unsigned short) (dpix + 0.5); break; case -32: imr = (float *)image; imr[ipix] = imr[ipix] + (float) dpix; break; case -64: imd = (double *)image; imd[ipix] = imd[ipix] + dpix; break; } return; } /* MOVEPIX -- Copy pixel between images */ void movepix (image1, bitpix1, w1, x1, y1, image2, bitpix2, w2, x2, y2) char *image1; /* Pointer to first pixel in input image */ int bitpix1; /* Bits per input pixel (FITS codes) */ /* 16 = short, -16 = unsigned short, 32 = int */ /* -32 = float, -64 = double */ int w1; /* Number of horizontal pixels in input image */ int x1, y1; /* Row and column for input pixel */ char *image2; /* Pointer to first pixel in output image */ int bitpix2; /* Bits per output pixel (FITS codes) */ /* 16 = short, -16 = unsigned short, 32 = int */ /* -32 = float, -64 = double */ int w2; /* Number of horizontal pixels in output image */ int x2, y2; /* Row and column for output pixel */ { double dpix, *imd1, *imd2; float rpix, *imr1, *imr2; int *imi1, *imi2; short *ims1, *ims2; unsigned short *imu1, *imu2; unsigned char *imc1, *imc2; if (x1 < 0 || x2 < 0 || x1 >= w1 || x2 >= w2) return; if (y1 < 0 || y2 < 0) return; switch (bitpix1) { case 8: imc1 = (unsigned char *)image1; switch (bitpix2) { case 8: imc2 = (unsigned char *)image2; imc2[(y2*w2) + x2] = imc1[(y1*w1) + x1]; break; case 16: ims2 = (short *)image2; ims2[(y2*w2) + x2] = (short) imc1[(y1*w1) + x1]; break; case 32: imi2 = (int *)image2; imi2[(y2*w2) + x2] = (int) imc1[(y1*w1) + x1]; break; case -16: imu2 = (unsigned short *)image2; imu2[(y2*w2) + x2] = (unsigned short) imc1[(y1*w1) + x1]; break; case -32: imr2 = (float *)image2; imr2[(y2*w2) + x2] = (float) imc1[(y1*w1) + x1]; break; case -64: imd2 = (double *)image2; imd2[(y2*w2) + x2] = (double) imc1[(y1*w1) + x1]; break; } break; case 16: ims1 = (short *)image1; switch (bitpix2) { case 8: imc2 = (unsigned char *)image1; imc2[(y2*w2) + x2] = (unsigned char) ims1[(y1*w1) + x1]; break; case 16: ims2 = (short *)image2; ims2[(y2*w2) + x2] = ims1[(y1*w1) + x1]; break; case 32: imi2 = (int *)image2; imi2[(y2*w2) + x2] = (int) ims1[(y1*w1) + x1]; break; case -16: imu2 = (unsigned short *)image2; imu2[(y2*w2) + x2] = (unsigned short) ims1[(y1*w1) + x1]; break; case -32: imr2 = (float *)image2; imr2[(y2*w2) + x2] = (float) ims1[(y1*w1) + x1]; break; case -64: imd2 = (double *)image2; imd2[(y2*w2) + x2] = (double) ims1[(y1*w1) + x1]; break; } break; case 32: imi1 = (int *)image1; switch (bitpix2) { case 8: imc2 = (unsigned char *)image2; imc2[(y2*w2) + x2] = (unsigned char) imi1[(y1*w1) + x1]; break; case 16: ims2 = (short *)image2; ims2[(y2*w2) + x2] = (short) imi1[(y1*w1) + x1]; break; case 32: imi2 = (int *)image2; imi2[(y2*w2) + x2] = imi1[(y1*w1) + x1]; break; case -16: imu2 = (unsigned short *)image2; imu2[(y2*w2) + x2] = (unsigned short) imi1[(y1*w1) + x1]; break; case -32: imr2 = (float *)image2; imr2[(y2*w2) + x2] = (float) imi1[(y1*w1) + x1]; break; case -64: imd2 = (double *)image2; imd2[(y2*w2) + x2] = (double) imi1[(y1*w1) + x1]; break; } break; case -16: imu1 = (unsigned short *)image1; switch (bitpix2) { case 8: imc2 = (unsigned char *)image2; imc2[(y2*w2) + x2] = (unsigned char) imu1[(y1*w1) + x1]; break; case 16: ims2 = (short *)image2; ims2[(y2*w2) + x2] = (short) imu1[(y1*w1) + x1]; break; case 32: imi2 = (int *)image2; imi2[(y2*w2) + x2] = (int) imu1[(y1*w1) + x1]; break; case -16: imu2 = (unsigned short *)image2; imu2[(y2*w2) + x2] = imu1[(y1*w1) + x1]; break; case -32: imr2 = (float *)image2; imr2[(y2*w2) + x2] = (float) imu1[(y1*w1) + x1]; break; case -64: imd2 = (double *)image2; imd2[(y2*w2) + x2] = (double) imu1[(y1*w1) + x1]; break; } break; case -32: imr1 = (float *)image1; rpix = imr1[(y1*w1) + x1]; switch (bitpix2) { case 8: imc2 = (unsigned char *)image2; if (rpix < 0.0) imc2[(y2*w2) + x2] = (unsigned char) 0; else imc2[(y2*w2) + x2] = (unsigned char) (rpix + 0.5); break; case 16: ims2 = (short *)image2; if (rpix < 0.0) ims2[(y2*w2) + x2] = (short) (rpix - 0.5); else ims2[(y2*w2) + x2] = (short) (rpix + 0.5); break; case 32: imi2 = (int *)image2; if (rpix < 0.0) imi2[(y2*w2) + x2] = (int) (rpix - 0.5); else imi2[(y2*w2) + x2] = (int) (rpix + 0.5); break; case -16: imu2 = (unsigned short *)image2; if (rpix < 0.0) imu2[(y2*w2) + x2] = (unsigned short) 0; else imu2[(y2*w2) + x2] = (unsigned short) (rpix + 0.5); break; case -32: imr2 = (float *)image2; imr2[(y2*w2) + x2] = rpix; break; case -64: imd2 = (double *)image2; imd2[(y2*w2) + x2] = (double) rpix; break; } break; case -64: imd1 = (double *)image1; dpix = imd1[(y1*w1) + x1]; switch (bitpix2) { case 8: imc2 = (unsigned char *)image2; if (dpix < 0.0) imc2[(y2*w2) + x2] = (unsigned char) 0; else imc2[(y2*w2) + x2] = (unsigned char) (dpix + 0.5); break; case 16: ims2 = (short *)image2; if (dpix < 0.0) ims2[(y2*w2) + x2] = (short) (dpix - 0.5); else ims2[(y2*w2) + x2] = (short) (dpix + 0.5); break; case 32: imi2 = (int *)image2; if (dpix < 0.0) imi2[(y2*w2) + x2] = (int) (dpix - 0.5); else imi2[(y2*w2) + x2] = (int) (dpix + 0.5); break; case -16: imu2 = (unsigned short *)image2; if (dpix < 0.0) imu2[(y2*w2) + x2] = (unsigned short) 0; else imu2[(y2*w2) + x2] = (unsigned short) (dpix + 0.5); break; case -32: imr2 = (float *)image2; imr2[(y2*w2) + x2] = (float) dpix; break; case -64: imd2 = (double *)image2; imd2[(y2*w2) + x2] = dpix; break; } break; } return; } /* MAXVEC -- Get maximum value in vector from 2D image of any numeric type */ double maxvec (image, bitpix, bzero, bscale, pix1, npix) char *image; /* Image array from which to read vector */ int bitpix; /* Number of bits per pixel in image */ /* 16 = short, -16 = unsigned short, 32 = int */ /* -32 = float, -64 = double */ double bzero; /* Zero point for pixel scaling */ double bscale; /* Scale factor for pixel scaling */ int pix1; /* Offset of first pixel to check */ int npix; /* Number of pixels to check */ { short *im2, imax2, ip2; int *im4, imax4, ip4; unsigned short *imu, imaxu, ipu; float *imr, imaxr, ipr; double *imd; double dmax = 0.0; double ipd; int ipix, pix2; unsigned char *imc, imaxc, ipc; pix2 = pix1 + npix; switch (bitpix) { case 8: imc = (unsigned char *)(image); imaxc = *(imc + pix1); for (ipix = pix1; ipix < pix2; ipix++) { ipc = *(imc + ipix); if (ipc > imaxc) imaxc = ipc; } dmax = (double) imaxc; break; case 16: im2 = (short *)image; imax2 = *(im2 + pix1); for (ipix = pix1; ipix < pix2; ipix++) { ip2 = *(im2 + ipix); if (ip2 > imax2) imax2 = ip2; } dmax = (double) imax2; break; case 32: im4 = (int *)image; imax4 = *(im4 + pix1); for (ipix = pix1; ipix < pix2; ipix++) { ip4 = *(im4 + ipix); if (ip4 > imax4) imax4 = ip4; } dmax = (double) imax4; break; case -16: imu = (unsigned short *)image; imaxu = *(imu + pix1); for (ipix = pix1; ipix < pix2; ipix++) { ipu = *(imu + ipix); if (ipu > imaxu) imaxu = ipu; } dmax = (double) imaxu; break; case -32: imr = (float *)image; imaxr = *(imr + pix1); for (ipix = pix1; ipix < pix2; ipix++) { ipr = *(imr + ipix); if (ipr > imaxr) imax2 = ipr; } dmax = (double) imaxr; break; case -64: imd = (double *)image; dmax = *(imd + pix1); for (ipix = pix1; ipix < pix2; ipix++) { ipd = *(imd + ipix); if (ipd > dmax) dmax = ipd; } break; } /* Scale data if either BZERO or BSCALE keyword has been set */ if (scale && (bzero != 0.0 || bscale != 1.0)) dmax = (dmax * bscale) + bzero; return (dmax); } /* MINVEC -- Get minimum value in vector from 2D image of any numeric type */ double minvec (image, bitpix, bzero, bscale, pix1, npix) char *image; /* Image array from which to read vector */ int bitpix; /* Number of bits per pixel in image */ /* 16 = short, -16 = unsigned short, 32 = int */ /* -32 = float, -64 = double */ double bzero; /* Zero point for pixel scaling */ double bscale; /* Scale factor for pixel scaling */ int pix1; /* Offset of first pixel to check */ int npix; /* Number of pixels to check */ { short *im2, imin2, ip2; int *im4, imin4, ip4; unsigned short *imu, iminu, ipu; float *imr, iminr, ipr; double *imd, ipd; double dmin = 0.0; int ipix, pix2; unsigned char *imc, cmin, cp; pix2 = pix1 + npix; switch (bitpix) { case 8: imc = (unsigned char *)image; cmin = *(imc + pix1); for (ipix = pix1; ipix < pix2; ipix++) { cp = *(imc + ipix); if (cp < cmin) cmin = cp; } dmin = (double) cmin; break; case 16: im2 = (short *)image + pix1; imin2 = *im2; for (ipix = pix1; ipix < pix2; ipix++) { ip2 = *(im2 + ipix); if (ip2 < imin2) imin2 = ip2; } dmin = (double) imin2; break; case 32: im4 = (int *)image; imin4 = *(im4 + pix1); for (ipix = pix1; ipix < pix2; ipix++) { ip4 = *(im4 + ipix); if (ip4 < imin4) imin4 = ip4; } dmin = (double) imin4; break; case -16: imu = (unsigned short *)image; iminu = *(imu + pix1); for (ipix = pix1; ipix < pix2; ipix++) { ipu = *(imu + ipix); if (ipu < iminu) iminu = ipu; } dmin = (double) iminu; break; case -32: imr = (float *)image; iminr = *(imr + pix1); for (ipix = pix1; ipix < pix2; ipix++) { ipr = *(imr + ipix); if (ipr < iminr) iminr = ipr; } dmin = (double) iminr; break; case -64: imd = (double *)image; dmin = *(imd + pix1); for (ipix = pix1; ipix < pix2; ipix++) { ipd = *(imd + ipix); if (ipd < dmin) dmin = ipd; } break; } /* Scale data if either BZERO or BSCALE keyword has been set */ if (scale && (bzero != 0.0 || bscale != 1.0)) dmin = (dmin * bscale) + bzero; return (dmin); } /* ADDVEC -- Add constant to pixel values in 2D image of any numeric type */ void addvec (image, bitpix, bzero, bscale, pix1, npix, dpix) char *image; /* Image array from which to extract vector */ int bitpix; /* Number of bits per pixel in image */ /* 16 = short, -16 = unsigned short, 32 = int */ /* -32 = float, -64 = double */ double bzero; /* Zero point for pixel scaling */ double bscale; /* Scale factor for pixel scaling */ int pix1; /* Offset of first pixel to extract */ int npix; /* Number of pixels to extract */ double dpix; /* Value to add to pixels */ { unsigned char *imc, ccon; short *im2, jcon; int *im4, icon; unsigned short *imu, ucon; float *imr, rcon; double *imd; int ipix, pix2; pix2 = pix1 + npix; if (scale) dpix = (dpix - bzero) / bscale; switch (bitpix) { case 8: imc = (unsigned char *) (image + pix1); if (dpix < 0) ccon = (unsigned char) (dpix - 0.5); else ccon = (unsigned char) (dpix + 0.5); for (ipix = pix1; ipix < pix2; ipix++) *imc++ += ccon; break; case 16: im2 = (short *) (image + pix1); if (dpix < 0) jcon = (short) (dpix - 0.5); else jcon = (short) (dpix + 0.5); for (ipix = pix1; ipix < pix2; ipix++) *im2++ += jcon; break; case 32: im4 = (int *) (image + pix1); if (dpix < 0) icon = (int) (dpix - 0.5); else icon = (int) (dpix + 0.5); for (ipix = pix1; ipix < pix2; ipix++) *im4++ += icon; break; case -16: imu = (unsigned short *) (image + pix1); if (dpix > 0) { ucon = (unsigned short) (dpix + 0.5); imu = (unsigned short *) (image + pix1); for (ipix = pix1; ipix < pix2; ipix++) *imu++ += ucon; } else { icon = (int) (dpix - 0.5); imu = (unsigned short *) (image + pix1); for (ipix = pix1; ipix < pix2; ipix++) { unsigned short tmp = (icon + (int) *imu); *imu++ += tmp; } } break; case -32: rcon = (float) dpix; imr = (float *) (image + pix1); for (ipix = pix1; ipix < pix2; ipix++) *imr++ += rcon; break; case -64: imd = (double *) (image + pix1); for (ipix = pix1; ipix < pix2; ipix++) *imd++ += dpix; break; } return; } /* MULTVEC -- Multiply pixel values in place in 2D image of any numeric type */ void multvec (image, bitpix, bzero, bscale, pix1, npix, dpix) char *image; /* Image array from which to extract vector */ int bitpix; /* Number of bits per pixel in image */ /* 16 = short, -16 = unsigned short, 32 = int */ /* -32 = float, -64 = double */ double bzero; /* Zero point for pixel scaling */ double bscale; /* Scale factor for pixel scaling */ int pix1; /* Offset of first pixel to extract */ int npix; /* Number of pixels to extract */ double dpix; /* Value by which to multiply pixels */ { char *imc, ccon; short *im2, jcon; int *im4, icon, isint; unsigned short *imu, ucon; float *imr, rcon; double *imd, dcon, dval; int ipix, pix2; pix2 = pix1 + npix; if (scale) dpix = (dpix - bzero) / bscale; ipix = (int) dpix; dcon = (double) ipix; if (dcon == dpix) isint = 1; else isint = 0; switch (bitpix) { case 8: imc = image + pix1; if (isint) { if (dpix < 0) ccon = (char) (dpix - 0.5); else ccon = (char) (dpix + 0.5); for (ipix = pix1; ipix < pix2; ipix++) *imc++ *= ccon; } else { for (ipix = pix1; ipix < pix2; ipix++) { dval = ((double) *imc) * dpix; if (dval < 256.0) *imc++ = (char) dval; else *imc++ = (char) 255; } } break; case 16: im2 = (short *) (image + pix1); if (isint) { im2 = (short *)image; if (dpix < 0) jcon = (short) (dpix - 0.5); else jcon = (short) (dpix + 0.5); for (ipix = pix1; ipix < pix2; ipix++) *im2++ *= jcon; } else { for (ipix = pix1; ipix < pix2; ipix++) { dval = ((double) *im2) * dpix; if (dval < 32768.0) *im2++ = (short) dval; else *im2++ = (short) 32767; } } break; case 32: im4 = (int *) (image + pix1); if (isint) { if (dpix < 0) icon = (int) (dpix - 0.5); else icon = (int) (dpix + 0.5); for (ipix = pix1; ipix < pix2; ipix++) *im4++ *= icon; } else { for (ipix = pix1; ipix < pix2; ipix++) { dval = ((double) *im4) * dpix; if (dval < 32768.0) *im4++ = (int) dval; else *im4++ = (int) 32767; } } break; case -16: imu = (unsigned short *) (image + pix1); if (dpix > 0) { ucon = (unsigned short) (dpix + 0.5); imu = (unsigned short *) (image + pix1); for (ipix = pix1; ipix < pix2; ipix++) *imu++ *= ucon; } break; case -32: rcon = (float) dpix; imr = (float *) (image + pix1); for (ipix = pix1; ipix < pix2; ipix++) *imr++ *= rcon; break; case -64: imd = (double *) (image + pix1); for (ipix = pix1; ipix < pix2; ipix++) *imd++ *= dpix; break; } return; } /* GETVEC -- Get vector from 2D image of any numeric type */ void getvec (image, bitpix, bzero, bscale, pix1, npix, dvec0) char *image; /* Image array from which to extract vector */ int bitpix; /* Number of bits per pixel in image */ /* 16 = short, -16 = unsigned short, 32 = int */ /* -32 = float, -64 = double */ double bzero; /* Zero point for pixel scaling */ double bscale; /* Scale factor for pixel scaling */ int pix1; /* Offset of first pixel to extract */ int npix; /* Number of pixels to extract */ double *dvec0; /* Vector of pixels (returned) */ { short *im2; int *im4; unsigned short *imu; float *imr; double *imd; double *dvec; int ipix, pix2; pix2 = pix1 + npix; dvec = dvec0; switch (bitpix) { case 8: for (ipix = pix1; ipix < pix2; ipix++) *dvec++ = (double) *(image + ipix); break; case 16: im2 = (short *)image; for (ipix = pix1; ipix < pix2; ipix++) *dvec++ = (double) *(im2 + ipix); break; case 32: im4 = (int *)image; for (ipix = pix1; ipix < pix2; ipix++) *dvec++ = (double) *(im4 + ipix); break; case -16: imu = (unsigned short *)image; for (ipix = pix1; ipix < pix2; ipix++) *dvec++ = (double) *(imu + ipix); break; case -32: imr = (float *)image; for (ipix = pix1; ipix < pix2; ipix++) *dvec++ = (double) *(imr + ipix); break; case -64: imd = (double *)image; for (ipix = pix1; ipix < pix2; ipix++) *dvec++ = (double) *(imd + ipix); break; } /* Scale data if either BZERO or BSCALE keyword has been set */ if (scale && (bzero != 0.0 || bscale != 1.0)) { dvec = dvec0; for (ipix = pix1; ipix < pix2; ipix++) { *dvec = (*dvec * bscale) + bzero; dvec++; } } return; } /* PUTVEC -- Copy pixel vector into 2D image of any numeric type */ void putvec (image, bitpix, bzero, bscale, pix1, npix, dvec) char *image; /* Image into which to copy vector */ int bitpix; /* Number of bits per pixel im image */ /* 16 = short, -16 = unsigned short, 32 = int */ /* -32 = float, -64 = double */ double bzero; /* Zero point for pixel scaling */ double bscale; /* Scale factor for pixel scaling */ int pix1; /* Offset of first pixel of vector in image */ int npix; /* Number of pixels to copy */ double *dvec; /* Vector of pixels to copy */ { short *im2; int *im4; unsigned short *imu; float *imr; double *imd; int ipix, pix2; double *dp = dvec; pix2 = pix1 + npix; /* Scale data if either BZERO or BSCALE keyword has been set */ if (scale && (bzero != 0.0 || bscale != 1.0)) { for (ipix = pix1; ipix < pix2; ipix++) { *dp = (*dp - bzero) / bscale; dp++; } dp = dvec; } switch (bitpix) { case 8: for (ipix = pix1; ipix < pix2; ipix++) *(image+ipix) = (char) *dp++; break; case 16: im2 = (short *)image; for (ipix = pix1; ipix < pix2; ipix++) { if (*dp < 0.0) *(im2+ipix) = (short) (*dp++ - 0.5); else *(im2+ipix) = (short) (*dp++ + 0.5); } break; case 32: im4 = (int *)image; for (ipix = pix1; ipix < pix2; ipix++) { if (*dp < 0.0) *(im4+ipix) = (int) (*dp++ - 0.5); else *(im4+ipix) = (int) (*dp++ + 0.5); } break; case -16: imu = (unsigned short *)image; for (ipix = pix1; ipix < pix2; ipix++) { if (*dp < 0.0) *(imu+ipix) = (unsigned short) 0; else *(imu+ipix) = (unsigned short) (*dp++ + 0.5); } break; case -32: imr = (float *)image; for (ipix = pix1; ipix < pix2; ipix++) *(imr+ipix) = (float) *dp++; break; case -64: imd = (double *)image; for (ipix = pix1; ipix < pix2; ipix++) *(imd+ipix) = (double) *dp++; break; } return; } /* FILLVEC1 -- Copy single value into a vector of any numeric type */ void fillvec1 (image, bitpix, bzero, bscale, pix1, npix, dpix) char *image; /* Vector to fill */ int bitpix; /* Number of bits per pixel im image */ /* 16 = short, -16 = unsigned short, 32 = int */ /* -32 = float, -64 = double */ double bzero; /* Zero point for pixel scaling */ double bscale; /* Scale factor for pixel scaling */ int pix1; /* First pixel to fill */ int npix; /* Number of pixels to fill */ double dpix; /* Value with which to fill pixels */ { fillvec (image, bitpix, bzero, bscale, pix1-1, npix, dpix); return; } /* FILLVEC -- Copy single value into a vector of any numeric type */ void fillvec (image, bitpix, bzero, bscale, pix1, npix, dpix) char *image; /* Vector to fill */ int bitpix; /* Number of bits per pixel im image */ /* 16 = short, -16 = unsigned short, 32 = int */ /* -32 = float, -64 = double */ double bzero; /* Zero point for pixel scaling */ double bscale; /* Scale factor for pixel scaling */ int pix1; /* First pixel to fill */ int npix; /* Number of pixels to fill */ double dpix; /* Value with which to fill pixels */ { char ipc; short *im2, ip2; int *im4, ip4; unsigned short *imu, ipu; float *imr, ipr; double *imd; int ipix, pix2; double dp; pix2 = pix1 + npix; /* Scale data if either BZERO or BSCALE keyword has been set */ dp = dpix; if (scale && (bzero != 0.0 || bscale != 1.0)) dp = (dp - bzero) / bscale; switch (bitpix) { case 8: if (dp < 0.0) ipc = (char) (dp - 0.5); else ipc = (char) (dp + 0.5); for (ipix = pix1; ipix < pix2; ipix++) image[ipix] = ipc; break; case 16: im2 = (short *)image; if (dp < 0.0) ip2 = (short) (dp - 0.5); else ip2 = (short) (dp + 0.5); for (ipix = pix1; ipix < pix2; ipix++) im2[ipix] = ip2; break; case 32: im4 = (int *)image; if (dp < 0.0) ip4 = (int) (dp - 0.5); else ip4 = (int) (dp + 0.5); for (ipix = pix1; ipix < pix2; ipix++) im4[ipix] = ip4; break; case -16: imu = (unsigned short *)image; if (dp < 0.0) ipu = (unsigned short) (dp - 0.5); else ipu = (unsigned short) (dp + 0.5); for (ipix = pix1; ipix < pix2; ipix++) imu[ipix] = ipu; break; case -32: imr = (float *)image; ipr = (float) dp; for (ipix = pix1; ipix < pix2; ipix++) imr[ipix] = ipr; break; case -64: imd = (double *)image; for (ipix = pix1; ipix < pix2; ipix++) imd[ipix] = dp; break; } return; } /* IMSWAP -- Reverse bytes of any type of vector in place */ void imswap (bitpix, string, nbytes) int bitpix; /* Number of bits per pixel */ /* 16 = short, -16 = unsigned short, 32 = int */ /* -32 = float, -64 = double */ char *string; /* Address of starting point of bytes to swap */ int nbytes; /* Number of bytes to swap */ { switch (bitpix) { case 8: break; case 16: if (nbytes < 2) return; imswap2 (string,nbytes); break; case 32: if (nbytes < 4) return; imswap4 (string,nbytes); break; case -16: if (nbytes < 2) return; imswap2 (string,nbytes); break; case -32: if (nbytes < 4) return; imswap4 (string,nbytes); break; case -64: if (nbytes < 8) return; imswap8 (string,nbytes); break; } return; } /* IMSWAP2 -- Swap bytes in string in place */ void imswap2 (string,nbytes) char *string; /* Address of starting point of bytes to swap */ int nbytes; /* Number of bytes to swap */ { char *sbyte, temp, *slast; slast = string + nbytes; sbyte = string; while (sbyte < slast) { temp = sbyte[0]; sbyte[0] = sbyte[1]; sbyte[1] = temp; sbyte= sbyte + 2; } return; } /* IMSWAP4 -- Reverse bytes of Integer*4 or Real*4 vector in place */ void imswap4 (string,nbytes) char *string; /* Address of Integer*4 or Real*4 vector */ int nbytes; /* Number of bytes to reverse */ { char *sbyte, *slast; char temp0, temp1, temp2, temp3; slast = string + nbytes; sbyte = string; while (sbyte < slast) { temp3 = sbyte[0]; temp2 = sbyte[1]; temp1 = sbyte[2]; temp0 = sbyte[3]; sbyte[0] = temp0; sbyte[1] = temp1; sbyte[2] = temp2; sbyte[3] = temp3; sbyte = sbyte + 4; } return; } /* IMSWAP8 -- Reverse bytes of Real*8 vector in place */ void imswap8 (string,nbytes) char *string; /* Address of Real*8 vector */ int nbytes; /* Number of bytes to reverse */ { char *sbyte, *slast; char temp[8]; slast = string + nbytes; sbyte = string; while (sbyte < slast) { temp[7] = sbyte[0]; temp[6] = sbyte[1]; temp[5] = sbyte[2]; temp[4] = sbyte[3]; temp[3] = sbyte[4]; temp[2] = sbyte[5]; temp[1] = sbyte[6]; temp[0] = sbyte[7]; sbyte[0] = temp[0]; sbyte[1] = temp[1]; sbyte[2] = temp[2]; sbyte[3] = temp[3]; sbyte[4] = temp[4]; sbyte[5] = temp[5]; sbyte[6] = temp[6]; sbyte[7] = temp[7]; sbyte = sbyte + 8; } return; } /* IMSWAPPED -- Returns 0 if big-endian (Sun,Mac), 1 if little-endian(PC,Alpha) */ int imswapped () { char *ctest; int itest; itest = 1; ctest = (char *)&itest; if (*ctest) return (1); else return (0); } /* Apr 17 1996 New file * May 22 1996 Add H so that PUTPIX and GETPIX can check coordinates * Jun 11 1996 Simplify NEWIMAGE subroutine * Jun 12 1996 Add byte-swapping subroutines * * Jul 24 1997 Add 8-bit option to subroutines * * May 27 1998 Include imio.h instead of fitshead.h * Jun 17 1998 Fix bug, changing all unsigned int's to unsigned short's * * Apr 29 1999 Add scaling to getpix, putpix, getvec, and putvec * Apr 29 1999 Fix bug in getvec in dealing with 1-byte data * Sep 14 1999 Change dp incrementing so it works on Alpha compiler * Sep 27 1999 Add interface for 1-based (FITS) image access * Sep 27 1999 Add addpix() and addpix1() * Dec 14 1999 In putpix(), addpix(), putvec(), round when output is integer * * Sep 20 2000 In getvec(), scale only if necessary * * Nov 27 2001 In movepix(), add char to char move * * Jan 23 2002 Add global scale switch to turn off scaling * Jun 4 2002 In getvec() and putvec(), change dpix to dvec * Jun 4 2002 Add addvec() to add to a vector * Jul 19 2002 Fix getvec() bug rescaling scaled numbers * * May 20 2003 Declare scale0 in setscale() * * Jan 28 2004 Add image limit check to movepix() * Feb 27 2004 Add fillvec() and fillvec1() to set vector to a constant * * Jun 27 2005 Fix major bug in fillvec(); pass value dpix in fillvec1(), too * Aug 18 2005 Add maxvec(), addvec(), and multvec() * * Mar 1 2006 Fix bug of occasional double application of bscale in getvec() * Apr 3 2006 Fix bad cast in unisigned int section of addvec() * May 3 2006 Code fixes in addpix and multpix suggested by Robert Lupton * Jun 8 2006 Drop erroneous second im2 assignment without offset in addvec() * Jun 20 2006 Fix typos masquerading as unitialized variables * * Jan 8 2007 Include fitsfile.h instead of imio.h * Jun 11 2007 Add minvec() and speed up maxvec() * * Apr 12 2012 Fix 8-bit variables to be unsigned char * Oct 19 2012 Fix errors with character images in minvec() and maxvec() * Oct 31 2012 Fix errors with short images in minvec() and maxvec() * Oct 31 2012 Drop unused variable il2 from minvec() */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/tnxpos.c0000664000175000017500000010050013047255533021154 0ustar mattymatty00000000000000/*** File wcslib/tnxpos.c *** September 17, 2008 *** By Jessica Mink, jmink@cfa.harvard.edu *** Harvard-Smithsonian Center for Astrophysics *** After IRAF mwcs/wftnx.x and mwcs/wfgsurfit.x *** Copyright (C) 1998-2008 *** Smithsonian Astrophysical Observatory, Cambridge, MA, USA This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Correspondence concerning WCSTools should be addressed as follows: Internet email: jmink@cfa.harvard.edu Postal address: Jessica Mink Smithsonian Astrophysical Observatory 60 Garden St. Cambridge, MA 02138 USA */ #include #include #include #include "wcs.h" #define SPHTOL 0.00001 #define BADCVAL 0.0 #define MAX(a,b) (((a) > (b)) ? (a) : (b)) #define MIN(a,b) (((a) < (b)) ? (a) : (b)) /* wftnx -- wcs function driver for the gnomonic projection with correction. * tnxinit (header, wcs) * tnxclose (wcs) * tnxfwd (xpix, ypix, wcs, xpos, ypos) Pixels to WCS * tnxrev (xpos, ypos, wcs, xpix, ypix) WCS to pixels */ #define max_niter 500 #define SZ_ATSTRING 2000 static void wf_gsclose(); static void wf_gsb1pol(); static void wf_gsb1leg(); static void wf_gsb1cheb(); /* tnxinit -- initialize the gnomonic forward or inverse transform. * initialization for this transformation consists of, determining which * axis is ra / lon and which is dec / lat, computing the celestial longitude * and colatitude of the native pole, reading in the the native longitude * of the pole of the celestial coordinate system longpole from the attribute * list, precomputing euler angles and various intermediaries derived from the * coordinate reference values, and reading in the projection parameter ro * from the attribute list. if longpole is undefined then a value of 180.0 * degrees is assumed. if ro is undefined a value of 180.0 / pi is assumed. * the tan projection is equivalent to the azp projection with mu set to 0.0. * in order to determine the axis order, the parameter "axtype={ra|dec} * {xlon|glat}{xlon|elat}" must have been set in the attribute list for the * function. the longpole and ro parameters may be set in either or both of * the axes attribute lists, but the value in the ra axis attribute list takes * precedence. */ int tnxinit (header, wcs) const char *header; /* FITS header */ struct WorldCoor *wcs; /* pointer to WCS structure */ { struct IRAFsurface *wf_gsopen(); char *str1, *str2, *lngstr, *latstr; extern void wcsrotset(); /* allocate space for the attribute strings */ str1 = malloc (SZ_ATSTRING); str2 = malloc (SZ_ATSTRING); hgetm (header, "WAT1", SZ_ATSTRING, str1); hgetm (header, "WAT2", SZ_ATSTRING, str2); lngstr = malloc (SZ_ATSTRING); latstr = malloc (SZ_ATSTRING); /* determine the native longitude of the pole of the celestial coordinate system corresponding to the FITS keyword longpole. this number has no default and should normally be set to 180 degrees. search both axes for this quantity. */ if (wcs->longpole > 360.0) { if (!igetr8 (str1, "longpole", &wcs->longpole)) { if (!igetr8 (str2, "longpole", &wcs->longpole)) wcs->longpole = 180.0; } } /* Fetch the ro projection parameter which is the radius of the generating sphere for the projection. if ro is absent which is the usual case set it to 180 / pi. search both axes for this quantity. */ if (!igetr8 (str1, "ro", &wcs->rodeg)) { if (!igetr8 (str2, "ro", &wcs->rodeg)) wcs->rodeg = 180.0 / PI; } /* Fetch the longitude correction surface. note that the attribute string may be of any length so the length of atvalue may have to be adjusted. */ if (!igets (str1, "lngcor", SZ_ATSTRING, lngstr)) { if (!igets (str2, "lngcor", SZ_ATSTRING, lngstr)) wcs->lngcor = NULL; else wcs->lngcor = wf_gsopen (lngstr); } else wcs->lngcor = wf_gsopen (lngstr); /* Fetch the latitude correction surface. note that the attribute string may be of any length so the length of atvalue may have to be adjusted. */ if (!igets (str2, "latcor", SZ_ATSTRING, latstr)) { if (!igets (str1, "latcor", SZ_ATSTRING, latstr)) wcs->latcor = NULL; else wcs->latcor = wf_gsopen (latstr); } else wcs->latcor = wf_gsopen (latstr); /* Compute image rotation */ wcsrotset (wcs); /* free working space. */ free (str1); free (str2); free (lngstr); free (latstr); /* Return 1 if there are no correction coefficients */ if (wcs->latcor == NULL && wcs->lngcor == NULL) return (1); else return (0); } /* tnxpos -- forward transform (physical to world) gnomonic projection. */ int tnxpos (xpix, ypix, wcs, xpos, ypos) double xpix, ypix; /*i physical coordinates (x, y) */ struct WorldCoor *wcs; /*i pointer to WCS descriptor */ double *xpos, *ypos; /*o world coordinates (ra, dec) */ { int ira, idec; double x, y, r, phi, theta, costhe, sinthe, dphi, cosphi, sinphi, dlng, z; double colatp, coslatp, sinlatp, longp; double xs, ys, ra, dec, xp, yp; double wf_gseval(); /* Convert from pixels to image coordinates */ xpix = xpix - wcs->crpix[0]; ypix = ypix - wcs->crpix[1]; /* Scale and rotate using CD matrix */ if (wcs->rotmat) { x = xpix * wcs->cd[0] + ypix * wcs->cd[1]; y = xpix * wcs->cd[2] + ypix * wcs->cd[3]; } else { /* Check axis increments - bail out if either 0 */ if (wcs->cdelt[0] == 0.0 || wcs->cdelt[1] == 0.0) { *xpos = 0.0; *ypos = 0.0; return 2; } /* Scale using CDELT */ xs = xpix * wcs->cdelt[0]; ys = ypix * wcs->cdelt[1]; /* Take out rotation from CROTA */ if (wcs->rot != 0.0) { double cosr = cos (degrad (wcs->rot)); double sinr = sin (degrad (wcs->rot)); x = xs * cosr - ys * sinr; y = xs * sinr + ys * cosr; } else { x = xs; y = ys; } } /* get the axis numbers */ if (wcs->coorflip) { ira = 1; idec = 0; } else { ira = 0; idec = 1; } colatp = degrad (90.0 - wcs->crval[idec]); coslatp = cos(colatp); sinlatp = sin(colatp); longp = degrad(wcs->longpole); /* Compute native spherical coordinates phi and theta in degrees from the projected coordinates. this is the projection part of the computation */ if (wcs->lngcor != NULL) xp = x + wf_gseval (wcs->lngcor, x, y); else xp = x; if (wcs->latcor != NULL) yp = y + wf_gseval (wcs->latcor, x, y); else yp = y; x = xp; y = yp; r = sqrt (x * x + y * y); /* Compute phi */ if (r == 0.0) phi = 0.0; else phi = atan2 (x, -y); /* Compute theta */ theta = atan2 (wcs->rodeg, r); /* Compute the celestial coordinates ra and dec from the native coordinates phi and theta. this is the spherical geometry part of the computation */ costhe = cos (theta); sinthe = sin (theta); dphi = phi - longp; cosphi = cos (dphi); sinphi = sin (dphi); /* Compute the ra */ x = sinthe * sinlatp - costhe * coslatp * cosphi; if (fabs (x) < SPHTOL) x = -cos (theta + colatp) + costhe * coslatp * (1.0 - cosphi); y = -costhe * sinphi; if (x != 0.0 || y != 0.0) dlng = atan2 (y, x); else dlng = dphi + PI ; ra = wcs->crval[ira] + raddeg(dlng); /* normalize ra */ if (wcs->crval[ira] >= 0.0) { if (ra < 0.0) ra = ra + 360.0; } else { if (ra > 0.0) ra = ra - 360.0; } if (ra > 360.0) ra = ra - 360.0; else if (ra < -360.0) ra = ra + 360.0; /* compute the dec */ if (fmod (dphi, PI) == 0.0) { dec = raddeg(theta + cosphi * colatp); if (dec > 90.0) dec = 180.0 - dec; if (dec < -90.0) dec = -180.0 - dec; } else { z = sinthe * coslatp + costhe * sinlatp * cosphi; if (fabs(z) > 0.99) { if (z >= 0.0) dec = raddeg(acos (sqrt(x * x + y * y))); else dec = raddeg(-acos (sqrt(x * x + y * y))); } else dec = raddeg(asin (z)); } /* store the results */ *xpos = ra; *ypos = dec; return (0); } /* tnxpix -- inverse transform (world to physical) gnomonic projection */ int tnxpix (xpos, ypos, wcs, xpix, ypix) double xpos, ypos; /*i world coordinates (ra, dec) */ struct WorldCoor *wcs; /*i pointer to WCS descriptor */ double *xpix, *ypix; /*o physical coordinates (x, y) */ { int ira, idec, niter; double ra, dec, cosdec, sindec, cosra, sinra, x, y, phi, theta; double s, r, dphi, z, dpi, dhalfpi, twopi, tx; double xm, ym, f, fx, fy, g, gx, gy, denom, dx, dy; double colatp, coslatp, sinlatp, longp, sphtol; double wf_gseval(), wf_gsder(); /* get the axis numbers */ if (wcs->coorflip) { ira = 1; idec = 0; } else { ira = 0; idec = 1; } /* Compute the transformation from celestial coordinates ra and dec to native coordinates phi and theta. this is the spherical geometry part of the transformation */ ra = degrad (xpos - wcs->crval[ira]); dec = degrad (ypos); cosra = cos (ra); sinra = sin (ra); cosdec = cos (dec); sindec = sin (dec); colatp = degrad (90.0 - wcs->crval[idec]); coslatp = cos (colatp); sinlatp = sin (colatp); if (wcs->longpole == 999.0) longp = degrad (180.0); else longp = degrad(wcs->longpole); dpi = PI; dhalfpi = dpi * 0.5; twopi = PI + PI; sphtol = SPHTOL; /* Compute phi */ x = sindec * sinlatp - cosdec * coslatp * cosra; if (fabs(x) < sphtol) x = -cos (dec + colatp) + cosdec * coslatp * (1.0 - cosra); y = -cosdec * sinra; if (x != 0.0 || y != 0.0) dphi = atan2 (y, x); else dphi = ra - dpi; phi = longp + dphi; if (phi > dpi) phi = phi - twopi; else if (phi < -dpi) phi = phi + twopi; /* Compute theta */ if (fmod (ra, dpi) == 0.0) { theta = dec + cosra * colatp; if (theta > dhalfpi) theta = dpi - theta; if (theta < -dhalfpi) theta = -dpi - theta; } else { z = sindec * coslatp + cosdec * sinlatp * cosra; if (fabs (z) > 0.99) { if (z >= 0.0) theta = acos (sqrt(x * x + y * y)); else theta = -acos (sqrt(x * x + y * y)); } else theta = asin (z); } /* Compute the transformation from native coordinates phi and theta to projected coordinates x and y */ s = sin (theta); if (s == 0.0) { x = BADCVAL; y = BADCVAL; } else { r = wcs->rodeg * cos (theta) / s; if (wcs->lngcor == NULL && wcs->latcor == NULL) { if (wcs->coorflip) { y = r * sin (phi); x = -r * cos (phi); } else { x = r * sin (phi); y = -r * cos (phi); } } else { xm = r * sin (phi); ym = -r * cos (phi); x = xm; y = ym; niter = 0; while (niter < max_niter) { if (wcs->lngcor != NULL) { f = x + wf_gseval (wcs->lngcor, x, y) - xm; fx = wf_gsder (wcs->lngcor, x, y, 1, 0); fx = 1.0 + fx; fy = wf_gsder (wcs->lngcor, x, y, 0, 1); } else { f = x - xm; fx = 1.0 ; fy = 0.0; } if (wcs->latcor != NULL) { g = y + wf_gseval (wcs->latcor, x, y) - ym; gx = wf_gsder (wcs->latcor, x, y, 1, 0); gy = wf_gsder (wcs->latcor, x, y, 0, 1); gy = 1.0 + gy; } else { g = y - ym; gx = 0.0 ; gy = 1.0; } denom = fx * gy - fy * gx; if (denom == 0.0) break; dx = (-f * gy + g * fy) / denom; dy = (-g * fx + f * gx) / denom; x = x + dx; y = y + dy; if (MAX(MAX(fabs(dx),fabs(dy)),MAX(fabs(f),fabs(g))) < 2.80e-8) break; niter = niter + 1; } /* Reverse x and y if axes flipped */ if (wcs->coorflip) { tx = x; x = y; y = tx; } } } /* Scale and rotate using CD matrix */ if (wcs->rotmat) { *xpix = x * wcs->dc[0] + y * wcs->dc[1]; *ypix = x * wcs->dc[2] + y * wcs->dc[3]; } else { /* Correct for rotation */ if (wcs->rot!=0.0) { double cosr = cos (degrad (wcs->rot)); double sinr = sin (degrad (wcs->rot)); *xpix = x * cosr + y * sinr; *ypix = y * cosr - x * sinr; } else { *xpix = x; *ypix = y; } /* Scale using CDELT */ if (wcs->xinc != 0.) *xpix = *xpix / wcs->xinc; if (wcs->yinc != 0.) *ypix = *ypix / wcs->yinc; } /* Convert to pixels */ *xpix = *xpix + wcs->xrefpix; *ypix = *ypix + wcs->yrefpix; return (0); } /* TNXCLOSE -- free up the distortion surface pointers */ void tnxclose (wcs) struct WorldCoor *wcs; /* pointer to the WCS descriptor */ { if (wcs->lngcor != NULL) wf_gsclose (wcs->lngcor); if (wcs->latcor != NULL) wf_gsclose (wcs->latcor); return; } /* copyright(c) 1986 association of universities for research in astronomy inc. * wfgsurfit.x -- surface fitting package used by wcs function drivers. * Translated to C from SPP by Jessica Mink, SAO, May 26, 1998 * * the following routines are used by the experimental function drivers tnx * and zpx to decode polynomial fits stored in the image header in the form * of a list of parameters and coefficients into surface descriptors in * ra / dec or longitude latitude. the polynomial surfaces so encoded consist * of corrections to function drivers tan and zpn. the package routines are * modelled after the equivalent gsurfit routines and are consistent with them. * the routines are: * * sf = wf_gsopen (wattstr) * wf_gsclose (sf) * * z = wf_gseval (sf, x, y) * ncoeff = wf_gscoeff (sf, coeff) * zder = wf_gsder (sf, x, y, nxder, nyder) * * wf_gsopen is used to open a surface fit encoded in a wcs attribute, returning * the sf surface fitting descriptor. wf_gsclose should be called later to free * the descriptor. wf_gseval is called to evaluate the surface at a point. */ #define SZ_GSCOEFFBUF 20 /* define the structure elements for the wf_gsrestore task */ #define TNX_SAVETYPE 0 #define TNX_SAVEXORDER 1 #define TNX_SAVEYORDER 2 #define TNX_SAVEXTERMS 3 #define TNX_SAVEXMIN 4 #define TNX_SAVEXMAX 5 #define TNX_SAVEYMIN 6 #define TNX_SAVEYMAX 7 #define TNX_SAVECOEFF 8 /* wf_gsopen -- decode the longitude / latitude or ra / dec mwcs attribute * and return a gsurfit compatible surface descriptor. */ struct IRAFsurface * wf_gsopen (astr) char *astr; /* the input mwcs attribute string */ { double dval; char *estr; int npar, szcoeff; double *coeff; struct IRAFsurface *gs; struct IRAFsurface *wf_gsrestore(); if (astr[1] == 0) return (NULL); gs = NULL; npar = 0; szcoeff = SZ_GSCOEFFBUF; coeff = (double *) malloc (szcoeff * sizeof (double)); estr = astr; while (*estr != (char) 0) { dval = strtod (astr, &estr); if (*estr == '.') estr++; if (*estr != (char) 0) { npar++; if (npar >= szcoeff) { szcoeff = szcoeff + SZ_GSCOEFFBUF; coeff = (double *) realloc (coeff, (szcoeff * sizeof (double))); } coeff[npar-1] = dval; astr = estr; while (*astr == ' ') astr++; } } gs = wf_gsrestore (coeff); free (coeff); if (npar == 0) return (NULL); else return (gs); } /* wf_gsclose -- procedure to free the surface descriptor */ static void wf_gsclose (sf) struct IRAFsurface *sf; /* the surface descriptor */ { if (sf != NULL) { if (sf->xbasis != NULL) free (sf->xbasis); if (sf->ybasis != NULL) free (sf->ybasis); if (sf->coeff != NULL) free (sf->coeff); free (sf); } return; } /* wf_gseval -- procedure to evaluate the fitted surface at a single point. * the wf->ncoeff coefficients are stored in the vector pointed to by sf->coeff. */ double wf_gseval (sf, x, y) struct IRAFsurface *sf; /* pointer to surface descriptor structure */ double x; /* x value */ double y; /* y value */ { double sum, accum; int i, ii, k, maxorder, xorder; /* Calculate the basis functions */ switch (sf->type) { case TNX_CHEBYSHEV: wf_gsb1cheb (x, sf->xorder, sf->xmaxmin, sf->xrange, sf->xbasis); wf_gsb1cheb (y, sf->yorder, sf->ymaxmin, sf->yrange, sf->ybasis); break; case TNX_LEGENDRE: wf_gsb1leg (x, sf->xorder, sf->xmaxmin, sf->xrange, sf->xbasis); wf_gsb1leg (y, sf->yorder, sf->ymaxmin, sf->yrange, sf->ybasis); break; case TNX_POLYNOMIAL: wf_gsb1pol (x, sf->xorder, sf->xbasis); wf_gsb1pol (y, sf->yorder, sf->ybasis); break; default: fprintf (stderr,"TNX_GSEVAL: unknown surface type\n"); return (0.0); } /* Initialize accumulator basis functions */ sum = 0.0; /* Loop over y basis functions */ if (sf->xorder > sf->yorder) maxorder = sf->xorder + 1; else maxorder = sf->yorder + 1; xorder = sf->xorder; ii = 0; for (i = 0; i < sf->yorder; i++) { /* Loop over the x basis functions */ accum = 0.0; for (k = 0; k < xorder; k++) { accum = accum + sf->coeff[ii] * sf->xbasis[k]; ii = ii + 1; } accum = accum * sf->ybasis[i]; sum = sum + accum; /* Elements of the coefficient vector where neither k = 1 or i = 1 are not calculated if sf->xterms = no. */ if (sf->xterms == TNX_XNONE) xorder = 1; else if (sf->xterms == TNX_XHALF) { if ((i + 1 + sf->xorder + 1) > maxorder) xorder = xorder - 1; } } return (sum); } /* TNX_GSCOEFF -- procedure to fetch the number and magnitude of the coefficients * if the sf->xterms = wf_xbi (yes) then the number of coefficients will be * (sf->xorder * sf->yorder); if wf_xterms is wf_xtri then the number * of coefficients will be (sf->xorder * sf->yorder - order * * (order - 1) / 2) where order is the minimum of the x and yorders; if * sf->xterms = TNX_XNONE then the number of coefficients will be * (sf->xorder + sf->yorder - 1). */ int wf_gscoeff (sf, coeff) struct IRAFsurface *sf; /* pointer to the surface fitting descriptor */ double *coeff; /* the coefficients of the fit */ { int ncoeff; /* the number of coefficients */ int i; /* Exctract coefficients from data structure and calculate their number */ ncoeff = sf->ncoeff; for (i = 0; i < ncoeff; i++) coeff[i] = sf->coeff[i]; return (ncoeff); } static double *coeff = NULL; static int nbcoeff = 0; /* wf_gsder -- procedure to calculate a new surface which is a derivative of * the input surface. */ double wf_gsder (sf1, x, y, nxd, nyd) struct IRAFsurface *sf1; /* pointer to the previous surface */ double x; /* x values */ double y; /* y values */ int nxd, nyd; /* order of the derivatives in x and y */ { int nxder, nyder, i, j, k, nbytes; int order, maxorder1, maxorder2, nmove1, nmove2; struct IRAFsurface *sf2 = 0; double *ptr1, *ptr2; double zfit, norm; double wf_gseval(); if (sf1 == NULL) return (0.0); if (nxd < 0 || nyd < 0) { fprintf (stderr, "TNX_GSDER: order of derivatives cannot be < 0\n"); return (0.0); } if (nxd == 0 && nyd == 0) { zfit = wf_gseval (sf1, x, y); return (zfit); } /* Allocate space for new surface */ sf2 = (struct IRAFsurface *) malloc (sizeof (struct IRAFsurface)); /* Check the order of the derivatives */ nxder = MIN (nxd, sf1->xorder - 1); nyder = MIN (nyd, sf1->yorder - 1); /* Set up new surface */ sf2->type = sf1->type; /* Set the derivative surface parameters */ if (sf2->type == TNX_LEGENDRE || sf2->type == TNX_CHEBYSHEV || sf2->type == TNX_POLYNOMIAL) { sf2->xterms = sf1->xterms; /* Find the order of the new surface */ switch (sf2->xterms) { case TNX_XNONE: if (nxder > 0 && nyder > 0) { sf2->xorder = 1; sf2->yorder = 1; sf2->ncoeff = 1; } else if (nxder > 0) { sf2->xorder = MAX (1, sf1->xorder - nxder); sf2->yorder = 1; sf2->ncoeff = sf2->xorder; } else if (nyder > 0) { sf2->xorder = 1; sf2->yorder = MAX (1, sf1->yorder - nyder); sf2->ncoeff = sf2->yorder; } break; case TNX_XHALF: maxorder1 = MAX (sf1->xorder+1, sf1->yorder+1); order = MAX(1, MIN(maxorder1-1-nyder-nxder,sf1->xorder-nxder)); sf2->xorder = order; order = MAX(1, MIN(maxorder1-1-nyder-nxder,sf1->yorder-nyder)); sf2->yorder = order; order = MIN (sf2->xorder, sf2->yorder); sf2->ncoeff = sf2->xorder * sf2->yorder - (order*(order-1)/2); break; default: sf2->xorder = MAX (1, sf1->xorder - nxder); sf2->yorder = MAX (1, sf1->yorder - nyder); sf2->ncoeff = sf2->xorder * sf2->yorder; } /* define the data limits */ sf2->xrange = sf1->xrange; sf2->xmaxmin = sf1->xmaxmin; sf2->yrange = sf1->yrange; sf2->ymaxmin = sf1->ymaxmin; } else { fprintf (stderr, "TNX_GSDER: unknown surface type %d\n", sf2->type); return (0.0); } /* Allocate space for coefficients and basis functions */ nbytes = sf2->ncoeff * sizeof(double); sf2->coeff = (double *) malloc (nbytes); nbytes = sf2->xorder * sizeof(double); sf2->xbasis = (double *) malloc (nbytes); nbytes = sf2->yorder * sizeof(double); sf2->ybasis = (double *) malloc (nbytes); /* Get coefficients */ nbytes = sf1->ncoeff * sizeof(double); if (nbytes > nbcoeff) { if (nbcoeff > 0) coeff = (double *) realloc (coeff, nbytes); else coeff = (double *) malloc (nbytes); nbcoeff = nbytes; } (void) wf_gscoeff (sf1, coeff); /* Compute the new coefficients */ switch (sf2->xterms) { case TNX_XFULL: ptr2 = sf2->coeff + (sf2->yorder - 1) * sf2->xorder; ptr1 = coeff + (sf1->yorder - 1) * sf1->xorder; for (i = sf1->yorder - 1; i >= nyder; i--) { for (j = i; j >= i-nyder+1; j--) { for (k = 0; k < sf2->xorder; k++) ptr1[nxder+k] = ptr1[nxder+k] * (double)(j); } for (j = sf1->xorder; j >= nxder+1; j--) { for (k = j; k >= j-nxder+1; k--) ptr1[j-1] = ptr1[j-1] * (double)(k - 1); } for (j = 0; j < sf2->xorder; j++) ptr2[j] = ptr1[nxder+j]; ptr2 = ptr2 - sf2->xorder; ptr1 = ptr1 - sf1->xorder; } break; case TNX_XHALF: maxorder1 = MAX (sf1->xorder + 1, sf1->yorder + 1); maxorder2 = MAX (sf2->xorder + 1, sf2->yorder + 1); ptr2 = sf2->coeff + sf2->ncoeff; ptr1 = coeff + sf1->ncoeff; for (i = sf1->yorder; i >= nyder+1; i--) { nmove1 = MAX (0, MIN (maxorder1 - i, sf1->xorder)); nmove2 = MAX (0, MIN (maxorder2 - i + nyder, sf2->xorder)); ptr1 = ptr1 - nmove1; ptr2 = ptr2 - nmove2; for (j = i; j > i - nyder + 1; j--) { for (k = 0; k < nmove2; k++) ptr1[nxder+k] = ptr1[nxder+k] * (double)(j-1); } for (j = nmove1; j >= nxder+1; j--) { for (k = j; k >= j-nxder+1; k--) ptr1[j-1] = ptr1[j-1] * (double)(k - 1); } for (j = 0; j < nmove2; j++) ptr2[j] = ptr1[nxder+j]; } break; default: if (nxder > 0 && nyder > 0) sf2->coeff[0] = 0.0; else if (nxder > 0) { ptr1 = coeff; ptr2 = sf2->coeff + sf2->ncoeff - 1; for (j = sf1->xorder; j >= nxder+1; j--) { for (k = j; k >= j - nxder + 1; k--) ptr1[j-1] = ptr1[j-1] * (double)(k - 1); ptr2[0] = ptr1[j-1]; ptr2 = ptr2 - 1; } } else if (nyder > 0) { ptr1 = coeff + sf1->ncoeff - 1; ptr2 = sf2->coeff; for (i = sf1->yorder; i >= nyder + 1; i--) { for (j = i; j >= i - nyder + 1; j--) *ptr1 = *ptr1 * (double)(j - 1); ptr1 = ptr1 - 1; } for (i = 0; i < sf2->ncoeff; i++) ptr2[i] = ptr1[i+1]; } } /* evaluate the derivatives */ zfit = wf_gseval (sf2, x, y); /* normalize */ if (sf2->type != TNX_POLYNOMIAL) { norm = pow (sf2->xrange, (double)nxder) * pow (sf2->yrange, (double)nyder); zfit = norm * zfit; } /* free the space */ wf_gsclose (sf2); return (zfit); } /* wf_gsrestore -- procedure to restore the surface fit encoded in the image header as a list of double precision parameters and coefficients to the surface descriptor for use by the evaluating routines. the surface parameters, surface type, xorder (or number of polynomial terms in x), yorder (or number of polynomial terms in y), xterms, xmin, xmax and ymin and ymax, are stored in the first eight elements of the double array fit, followed by the wf->ncoeff surface coefficients. */ struct IRAFsurface * wf_gsrestore (fit) double *fit; /* array containing the surface parameters and coefficients */ { struct IRAFsurface *sf; /* surface descriptor */ int surface_type, xorder, yorder, order, i; double xmin, xmax, ymin, ymax; xorder = (int) (fit[TNX_SAVEXORDER] + 0.5); if (xorder < 1) { fprintf (stderr, "wf_gsrestore: illegal x order %d\n", xorder); return (NULL); } yorder = (int) (fit[TNX_SAVEYORDER] + 0.5); if (yorder < 1) { fprintf (stderr, "wf_gsrestore: illegal y order %d\n", yorder); return (NULL); } xmin = fit[TNX_SAVEXMIN]; xmax = fit[TNX_SAVEXMAX]; if (xmax <= xmin) { fprintf (stderr, "wf_gsrestore: illegal x range %f-%f\n",xmin,xmax); return (NULL); } ymin = fit[TNX_SAVEYMIN]; ymax = fit[TNX_SAVEYMAX]; if (ymax <= ymin) { fprintf (stderr, "wf_gsrestore: illegal y range %f-%f\n",ymin,ymax); return (NULL); } /* Set surface type dependent surface descriptor parameters */ surface_type = (int) (fit[TNX_SAVETYPE] + 0.5); if (surface_type == TNX_LEGENDRE || surface_type == TNX_CHEBYSHEV || surface_type == TNX_POLYNOMIAL) { /* allocate space for the surface descriptor */ sf = (struct IRAFsurface *) malloc (sizeof (struct IRAFsurface)); sf->xorder = xorder; sf->xrange = 2.0 / (xmax - xmin); sf->xmaxmin = - (xmax + xmin) / 2.0; sf->yorder = yorder; sf->yrange = 2.0 / (ymax - ymin); sf->ymaxmin = - (ymax + ymin) / 2.0; sf->xterms = fit[TNX_SAVEXTERMS]; switch (sf->xterms) { case TNX_XNONE: sf->ncoeff = sf->xorder + sf->yorder - 1; break; case TNX_XHALF: order = MIN (xorder, yorder); sf->ncoeff = sf->xorder * sf->yorder - order * (order-1) / 2; break; case TNX_XFULL: sf->ncoeff = sf->xorder * sf->yorder; break; } } else { fprintf (stderr, "wf_gsrestore: unknown surface type %d\n", surface_type); return (NULL); } /* Set remaining curve parameters */ sf->type = surface_type; /* Restore coefficient array */ sf->coeff = (double *) malloc (sf->ncoeff*sizeof (double)); for (i = 0; i < sf->ncoeff; i++) sf->coeff[i] = fit[TNX_SAVECOEFF+i]; /* Allocate space for basis vectors */ sf->xbasis = (double *) malloc (sf->xorder*sizeof (double)); sf->ybasis = (double *) malloc (sf->yorder*sizeof (double)); return (sf); } /* wf_gsb1pol -- procedure to evaluate all the non-zero polynomial functions for a single point and given order. */ static void wf_gsb1pol (x, order, basis) double x; /*i data point */ int order; /*i order of polynomial, order = 1, constant */ double *basis; /*o basis functions */ { int i; basis[0] = 1.0; if (order == 1) return; basis[1] = x; if (order == 2) return; for (i = 2; i < order; i++) basis[i] = x * basis[i-1]; return; } /* wf_gsb1leg -- procedure to evaluate all the non-zero legendre functions for a single point and given order. */ static void wf_gsb1leg (x, order, k1, k2, basis) double x; /*i data point */ int order; /*i order of polynomial, order = 1, constant */ double k1, k2; /*i normalizing constants */ double *basis; /*o basis functions */ { int i; double ri, xnorm; basis[0] = 1.0; if (order == 1) return; xnorm = (x + k1) * k2 ; basis[1] = xnorm; if (order == 2) return; for (i = 2; i < order; i++) { ri = i; basis[i] = ((2.0 * ri - 1.0) * xnorm * basis[i-1] - (ri - 1.0) * basis[i-2]) / ri; } return; } /* wf_gsb1cheb -- procedure to evaluate all the non-zero chebyshev function coefficients for a given x and order. */ static void wf_gsb1cheb (x, order, k1, k2, basis) double x; /*i number of data points */ int order; /*i order of polynomial, 1 is a constant */ double k1, k2; /*i normalizing constants */ double *basis; /*o array of basis functions */ { int i; double xnorm; basis[0] = 1.0; if (order == 1) return; xnorm = (x + k1) * k2; basis[1] = xnorm; if (order == 2) return; for (i = 2; i < order; i++) basis[i] = 2. * xnorm * basis[i-1] - basis[i-2]; return; } /* Set surface polynomial from arguments */ int tnxpset (wcs, xorder, yorder, xterms, coeff) struct WorldCoor *wcs; /* World coordinate system structure */ int xorder; /* Number of x coefficients (same for x and y) */ int yorder; /* Number of y coefficients (same for x and y) */ int xterms; /* Number of xy coefficients (same for x and y) */ double *coeff; /* Plate fit coefficients */ { double *ycoeff; struct IRAFsurface *wf_gspset (); wcs->prjcode = WCS_TNX; wcs->lngcor = wf_gspset (xorder, yorder, xterms, coeff); ycoeff = coeff + wcs->lngcor->ncoeff; wcs->latcor = wf_gspset (xorder, yorder, xterms, ycoeff); return 0; } /* wf_gspset -- procedure to set the surface descriptor for use by the evaluating routines. from arguments. The surface parameters are surface type, xorder (number of polynomial terms in x), yorder (number of polynomial terms in y), xterms, and the surface coefficients. */ struct IRAFsurface * wf_gspset (xorder, yorder, xterms, coeff) int xorder; int yorder; int xterms; double *coeff; { struct IRAFsurface *sf; /* surface descriptor */ int surface_type, order, i; double xmin, xmax; double ymin, ymax; surface_type = TNX_POLYNOMIAL; xmin = 0.0; xmax = 0.0; ymin = 0.0; ymax = 0.0; if (surface_type == TNX_LEGENDRE || surface_type == TNX_CHEBYSHEV || surface_type == TNX_POLYNOMIAL) { /* allocate space for the surface descriptor */ sf = (struct IRAFsurface *) malloc (sizeof (struct IRAFsurface)); sf->xorder = xorder; sf->xrange = 2.0 / (xmax - xmin); sf->xmaxmin = -(xmax + xmin) / 2.0; sf->yorder = yorder; sf->yrange = 2.0 / (ymax - ymin); sf->ymaxmin = - (ymax + ymin) / 2.0; sf->xterms = xterms; switch (sf->xterms) { case TNX_XNONE: sf->ncoeff = sf->xorder + sf->yorder - 1; break; case TNX_XHALF: order = MIN (xorder, yorder); sf->ncoeff = sf->xorder * sf->yorder - order * (order-1) / 2; break; case TNX_XFULL: sf->ncoeff = sf->xorder * sf->yorder; break; } } else { fprintf (stderr, "TNX_GSSET: unknown surface type %d\n", surface_type); return (NULL); } /* Set remaining curve parameters */ sf->type = surface_type; /* Restore coefficient array */ sf->coeff = (double *) malloc (sf->ncoeff*sizeof (double)); for (i = 0; i < sf->ncoeff; i++) sf->coeff[i] = coeff[i]; /* Allocate space for basis vectors */ sf->xbasis = (double *) malloc (sf->xorder*sizeof (double)); sf->ybasis = (double *) malloc (sf->yorder*sizeof (double)); return (sf); } /* Mar 26 1998 New subroutines, translated from SPP * Apr 28 1998 Change all local flags to TNX_* and projection flag to WCS_TNX * May 11 1998 Fix use of pole longitude default * Sep 4 1998 Fix missed assignment in tnxpos from Allen Harris, SAO * Sep 10 1998 Fix bugs in tnxpix() * Sep 10 1998 Fix missed assignment in tnxpix from Allen Harris, SAO * * Oct 22 1999 Drop unused variables, fix case statements after lint * Dec 10 1999 Fix bug in gsder() which failed to allocate enough memory * Dec 10 1999 Compute wcs->rot using wcsrotset() in tnxinit() * * Feb 14 2001 Fixed off-by-one bug in legendre evaluation (Mike Jarvis) * * Apr 11 2002 Fix bug when .-terminated substring in wf_gsopen() * Apr 29 2002 Clean up code * Jun 26 2002 Increase size of WAT strings from 500 to 2000 * * Jun 27 2005 Drop unused arguments k1 and k2 from wf_gsb1pol() * * Jan 8 2007 Drop unused variable ncoeff in wf_gsder() * Jan 9 2007 Declare header const char in tnxinit() * Apr 3 2007 Fix offsets to hit last cooefficient in wf_gsder() * * Sep 5 2008 Fix wf_gseval() call in tnxpos() so unmodified x and y are used * Sep 9 2008 Fix loop in TNX_XFULL section of wf_gsder() * (last two bugs found by Ed Los) * Sep 17 2008 Fix tnxpos for null correction case (fix by Ed Los) */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/wcsinit.c0000664000175000017500000014057713047255533021323 0ustar mattymatty00000000000000/*** File libwcs/wcsinit.c *** July 24, 2013 *** By Jessica Mink, jmink@cfa.harvard.edu *** Harvard-Smithsonian Center for Astrophysics *** Copyright (C) 1998-2013 *** Smithsonian Astrophysical Observatory, Cambridge, MA, USA This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Correspondence concerning WCSTools should be addressed as follows: Internet email: jmink@cfa.harvard.edu Postal address: Jessica Mink Smithsonian Astrophysical Observatory 60 Garden St. Cambridge, MA 02138 USA * Module: wcsinit.c (World Coordinate Systems) * Purpose: Convert FITS WCS to pixels and vice versa: * Subroutine: wcsinit (hstring) sets a WCS structure from an image header * Subroutine: wcsninit (hstring,lh) sets a WCS structure from fixed-length header * Subroutine: wcsinitn (hstring, name) sets a WCS structure for specified WCS * Subroutine: wcsninitn (hstring,lh, name) sets a WCS structure for specified WCS * Subroutine: wcsinitc (hstring, mchar) sets a WCS structure if multiple * Subroutine: wcsninitc (hstring,lh,mchar) sets a WCS structure if multiple * Subroutine: wcschar (hstring, name) returns suffix for specifed WCS * Subroutine: wcseq (hstring, wcs) set radecsys and equinox from image header * Subroutine: wcseqm (hstring, wcs, mchar) set radecsys and equinox if multiple */ #include /* strstr, NULL */ #include /* stderr */ #include #include "wcs.h" #ifndef VMS #include #endif static void wcseq(); static void wcseqm(); static void wcsioset(); void wcsrotset(); char wcschar(); /* set up a WCS structure from a FITS image header lhstring bytes long * for a specified WCS name */ struct WorldCoor * wcsninitn (hstring, lhstring, name) const char *hstring; /* character string containing FITS header information in the format = [/ ] */ int lhstring; /* Length of FITS header in bytes */ const char *name; /* character string with identifying name of WCS */ { hlength (hstring, lhstring); return (wcsinitn (hstring, name)); } /* set up a WCS structure from a FITS image header for specified WCSNAME */ struct WorldCoor * wcsinitn (hstring, name) const char *hstring; /* character string containing FITS header information in the format = [/ ] */ const char *name; /* character string with identifying name of WCS */ { char mchar; /* Suffix character for one of multiple WCS */ mchar = wcschar (hstring, name); if (mchar == '_') { fprintf (stderr, "WCSINITN: WCS name %s not matched in FITS header\n", name); return (NULL); } return (wcsinitc (hstring, &mchar)); } /* WCSCHAR -- Find the letter for a specific WCS conversion */ char wcschar (hstring, name) const char *hstring; /* character string containing FITS header information in the format = [/ ] */ const char *name; /* Name of WCS conversion to be matched (case-independent) */ { char *upname; char cwcs, charwcs; int iwcs; char keyword[12]; char *upval, value[72]; /* If no WCS character, return 0 */ if (name == NULL) return ((char) 0); /* Convert input name to upper case */ upname = uppercase (name); /* If single character name, return that character */ if (strlen (upname) == 1) return (upname[0]); /* Try to match input name to available WCSNAME names in header */ strcpy (keyword, "WCSNAME"); keyword[8] = (char) 0; charwcs = '_'; for (iwcs = 0; iwcs < 27; iwcs++) { if (iwcs > 0) cwcs = (char) (64 + iwcs); else cwcs = (char) 0; keyword[7] = cwcs; if (hgets (hstring, keyword, 72, value)) { upval = uppercase (value); if (!strcmp (upval, upname)) charwcs = cwcs; free (upval); } } free (upname); return (charwcs); } /* Make string of arbitrary case all uppercase */ char * uppercase (string) const char *string; { int lstring, i; char *upstring; lstring = strlen (string); upstring = (char *) calloc (1,lstring+1); for (i = 0; i < lstring; i++) { if (string[i] > 96 && string[i] < 123) upstring[i] = string[i] - 32; else upstring[i] = string[i]; } upstring[lstring] = (char) 0; return (upstring); } /* set up a WCS structure from a FITS image header lhstring bytes long */ struct WorldCoor * wcsninit (hstring, lhstring) const char *hstring; /* character string containing FITS header information in the format = [/ ] */ int lhstring; /* Length of FITS header in bytes */ { char mchar; /* Suffix character for one of multiple WCS */ mchar = (char) 0; hlength (hstring, lhstring); return (wcsinitc (hstring, &mchar)); } /* set up a WCS structure from a FITS image header lhstring bytes long */ struct WorldCoor * wcsninitc (hstring, lhstring, mchar) const char *hstring; /* character string containing FITS header information in the format = [/ ] */ int lhstring; /* Length of FITS header in bytes */ char *mchar; /* Suffix character for one of multiple WCS */ { hlength (hstring, lhstring); if (mchar[0] == ' ') mchar[0] = (char) 0; return (wcsinitc (hstring, mchar)); } /* set up a WCS structure from a FITS image header */ struct WorldCoor * wcsinit (hstring) const char *hstring; /* character string containing FITS header information in the format = [/ ] */ { char mchar; /* Suffix character for one of multiple WCS */ mchar = (char) 0; return (wcsinitc (hstring, &mchar)); } /* set up a WCS structure from a FITS image header for specified suffix */ struct WorldCoor * wcsinitc (hstring, wchar) const char *hstring; /* character string containing FITS header information in the format = [/ ] */ char *wchar; /* Suffix character for one of multiple WCS */ { struct WorldCoor *wcs, *depwcs; char ctype1[32], ctype2[32], tstring[32]; char pvkey1[8],pvkey2[8],pvkey3[8]; char *hcoeff; /* pointer to first coeff's in header */ char decsign; double rah,ram,ras, dsign,decd,decm,decs; double dec_deg,ra_hours, secpix, ra0, ra1, dec0, dec1, cvel; double cdelt1, cdelt2, cd[4], pc[81]; char keyword[16]; int ieq, i, j, k, naxes, cd11p, cd12p, cd21p, cd22p; int ilat; /* coordinate for latitude or declination */ /* int ix1, ix2, iy1, iy2, idx1, idx2, idy1, idy2; double dxrefpix, dyrefpix; */ char temp[80]; char wcsname[64]; /* Name of WCS depended on by current WCS */ char mchar; char cspace = (char) ' '; char cnull = (char) 0; double mjd; double rot; double ut; int nax; int twod; extern int tnxinit(); extern int zpxinit(); extern int platepos(); extern int dsspos(); void invert_wcs(); wcs = (struct WorldCoor *) calloc (1, sizeof(struct WorldCoor)); /* Set WCS character and name in structure */ mchar = wchar[0]; if (mchar == ' ') mchar = cnull; wcs->wcschar = mchar; if (hgetsc (hstring, "WCSNAME", &mchar, 63, wcsname)) { wcs->wcsname = (char *) calloc (strlen (wcsname)+2, 1); strcpy (wcs->wcsname, wcsname); } /* Set WCSLIB flags so that structures will be reinitialized */ wcs->cel.flag = 0; wcs->lin.flag = 0; wcs->wcsl.flag = 0; wcs->wcsl.cubeface = -1; /* Initialize to no plate fit */ wcs->ncoeff1 = 0; wcs->ncoeff2 = 0; /* Initialize to no CD matrix */ cdelt1 = 0.0; cdelt2 = 0.0; cd[0] = 0.0; cd[1] = 0.0; cd[2] = 0.0; cd[3] = 0.0; pc[0] = 0.0; wcs->rotmat = 0; wcs->rot = 0.0; /* Header parameters independent of projection */ naxes = 0; hgeti4c (hstring, "WCSAXES", &mchar, &naxes); if (naxes == 0) hgeti4 (hstring, "WCSAXES", &naxes); if (naxes == 0) hgeti4 (hstring, "NAXIS", &naxes); if (naxes == 0) hgeti4 (hstring, "WCSDIM", &naxes); if (naxes < 1) { setwcserr ("WCSINIT: No WCSAXES, NAXIS, or WCSDIM keyword"); wcsfree (wcs); return (NULL); } if (naxes > 2) naxes = 2; wcs->naxis = naxes; wcs->naxes = naxes; wcs->lin.naxis = naxes; wcs->nxpix = 0; hgetr8 (hstring, "NAXIS1", &wcs->nxpix); if (wcs->nxpix < 1) hgetr8 (hstring, "IMAGEW", &wcs->nxpix); if (wcs->nxpix < 1) { setwcserr ("WCSINIT: No NAXIS1 or IMAGEW keyword"); wcsfree (wcs); return (NULL); } wcs->nypix = 0; hgetr8 (hstring, "NAXIS2", &wcs->nypix); if (wcs->nypix < 1) hgetr8 (hstring, "IMAGEH", &wcs->nypix); if (naxes > 1 && wcs->nypix < 1) { setwcserr ("WCSINIT: No NAXIS2 or IMAGEH keyword"); wcsfree (wcs); return (NULL); } /* Reset number of axes to only those with dimension greater than one */ nax = 0; for (i = 0; i < naxes; i++) { /* Check for number of pixels in axis more than one */ strcpy (keyword, "NAXIS"); sprintf (temp, "%d", i+1); strcat (keyword, temp); if (!hgeti4 (hstring, keyword, &j)) { if (i == 0 && wcs->nxpix > 1) { /* fprintf (stderr,"WCSINIT: Missing keyword %s set to %.0f from IMAGEW\n", keyword, wcs->nxpix); */ j = wcs->nxpix; } else if (i == 1 && wcs->nypix > 1) { /* fprintf (stderr,"WCSINIT: Missing keyword %s set to %.0f from IMAGEH\n", keyword, wcs->nypix); */ j = wcs->nypix; } else fprintf (stderr,"WCSINIT: Missing keyword %s assumed 1\n",keyword); } /* Check for TAB WCS in axis */ strcpy (keyword, "CTYPE"); strcat (keyword, temp); if (hgets (hstring, keyword, 16, temp)) { if (strsrch (temp, "-TAB")) j = 0; } if (j > 1) nax = nax + 1; } naxes = nax; wcs->naxes = nax; wcs->naxis = nax; hgets (hstring, "INSTRUME", 16, wcs->instrument); hgeti4 (hstring, "DETECTOR", &wcs->detector); wcs->wcsproj = getdefwcs(); wcs->logwcs = 0; hgeti4 (hstring, "DC-FLAG", &wcs->logwcs); /* Initialize rotation matrices */ for (i = 0; i < 81; i++) wcs->pc[i] = 0.0; for (i = 0; i < 81; i++) pc[i] = 0.0; for (i = 0; i < naxes; i++) wcs->pc[(i*naxes)+i] = 1.0; for (i = 0; i < naxes; i++) pc[(i*naxes)+i] = 1.0; for (i = 0; i < 9; i++) wcs->cdelt[i] = 0.0; for (i = 0; i < naxes; i++) wcs->cdelt[i] = 1.0; /* If the current world coordinate system depends on another, set it now */ if (hgetsc (hstring, "WCSDEP",&mchar, 63, wcsname)) { if ((wcs->wcs = wcsinitn (hstring, wcsname)) == NULL) { setwcserr ("WCSINIT: depended on WCS could not be set"); wcsfree (wcs); return (NULL); } depwcs = wcs->wcs; depwcs->wcsdep = wcs; } else wcs->wcs = NULL; /* Read radial velocity from image header */ wcs->radvel = 0.0; wcs->zvel = 0.0; cvel = 299792.5; if (hgetr8c (hstring, "VSOURCE", &mchar, &wcs->radvel)) wcs->zvel = wcs->radvel / cvel; else if (hgetr8c (hstring, "ZSOURCE", &mchar, &wcs->zvel)) wcs->radvel = wcs->zvel * cvel; else if (hgetr8 (hstring, "VELOCITY", &wcs->radvel)) wcs->zvel = wcs->radvel / cvel; for (i = 0; i < 10; i++) { wcs->prj.p[i] = 0.0; } /* World coordinate system reference coordinate information */ if (hgetsc (hstring, "CTYPE1", &mchar, 16, ctype1)) { /* Read second coordinate type */ strcpy (ctype2, ctype1); if (!hgetsc (hstring, "CTYPE2", &mchar, 16, ctype2)) twod = 0; else twod = 1; strcpy (wcs->ctype[0], ctype1); strcpy (wcs->ctype[1], ctype2); if (strsrch (ctype2, "LAT") || strsrch (ctype2, "DEC")) ilat = 2; else ilat = 1; /* Read third and fourth coordinate types, if present */ strcpy (wcs->ctype[2], ""); hgetsc (hstring, "CTYPE3", &mchar, 9, wcs->ctype[2]); strcpy (wcs->ctype[3], ""); hgetsc (hstring, "CTYPE4", &mchar, 9, wcs->ctype[3]); /* Set projection type in WCS data structure */ if (wcstype (wcs, ctype1, ctype2)) { wcsfree (wcs); return (NULL); } /* Get units, if present, for linear coordinates */ if (wcs->prjcode == WCS_LIN) { if (!hgetsc (hstring, "CUNIT1", &mchar, 16, wcs->units[0])) { if (!mgetstr (hstring, "WAT1", "units", 16, wcs->units[0])) { wcs->units[0][0] = 0; } } if (!strcmp (wcs->units[0], "pixel")) wcs->prjcode = WCS_PIX; if (twod) { if (!hgetsc (hstring, "CUNIT2", &mchar, 16, wcs->units[1])) { if (!mgetstr (hstring, "WAT2", "units", 16, wcs->units[1])) { wcs->units[1][0] = 0; } } if (!strcmp (wcs->units[0], "pixel")) wcs->prjcode = WCS_PIX; } } /* Reference pixel coordinates and WCS value */ wcs->crpix[0] = 1.0; hgetr8c (hstring, "CRPIX1", &mchar, &wcs->crpix[0]); wcs->crpix[1] = 1.0; hgetr8c (hstring, "CRPIX2", &mchar, &wcs->crpix[1]); wcs->xrefpix = wcs->crpix[0]; wcs->yrefpix = wcs->crpix[1]; wcs->crval[0] = 0.0; hgetr8c (hstring, "CRVAL1", &mchar, &wcs->crval[0]); wcs->crval[1] = 0.0; hgetr8c (hstring, "CRVAL2", &mchar, &wcs->crval[1]); if (wcs->syswcs == WCS_NPOLE) wcs->crval[1] = 90.0 - wcs->crval[1]; if (wcs->syswcs == WCS_SPA) wcs->crval[1] = wcs->crval[1] - 90.0; wcs->xref = wcs->crval[0]; wcs->yref = wcs->crval[1]; if (wcs->coorflip) { wcs->cel.ref[0] = wcs->crval[1]; wcs->cel.ref[1] = wcs->crval[0]; } else { wcs->cel.ref[0] = wcs->crval[0]; wcs->cel.ref[1] = wcs->crval[1]; } wcs->longpole = 999.0; hgetr8c (hstring, "LONPOLE", &mchar, &wcs->longpole); wcs->cel.ref[2] = wcs->longpole; wcs->latpole = 999.0; hgetr8c (hstring, "LATPOLE", &mchar, &wcs->latpole); wcs->cel.ref[3] = wcs->latpole; wcs->lin.crpix = wcs->crpix; wcs->lin.cdelt = wcs->cdelt; wcs->lin.pc = wcs->pc; /* Projection constants (this should be projection-dependent */ wcs->prj.r0 = 0.0; hgetr8c (hstring, "PROJR0", &mchar, &wcs->prj.r0); /* FITS WCS interim proposal projection constants */ for (i = 0; i < 10; i++) { sprintf (keyword,"PROJP%d",i); hgetr8c (hstring, keyword, &mchar, &wcs->prj.p[i]); } sprintf (pvkey1, "PV%d_1", ilat); sprintf (pvkey2, "PV%d_2", ilat); sprintf (pvkey3, "PV%d_3", ilat); /* FITS WCS standard projection constants (projection-dependent) */ if (wcs->prjcode == WCS_AZP || wcs->prjcode == WCS_SIN || wcs->prjcode == WCS_COP || wcs->prjcode == WCS_COE || wcs->prjcode == WCS_COD || wcs->prjcode == WCS_COO) { hgetr8c (hstring, pvkey1, &mchar, &wcs->prj.p[1]); hgetr8c (hstring, pvkey2, &mchar, &wcs->prj.p[2]); } else if (wcs->prjcode == WCS_SZP) { hgetr8c (hstring, pvkey1, &mchar, &wcs->prj.p[1]); hgetr8c (hstring, pvkey2, &mchar, &wcs->prj.p[2]); if (wcs->prj.p[3] == 0.0) wcs->prj.p[3] = 90.0; hgetr8c (hstring, pvkey3, &mchar, &wcs->prj.p[3]); } else if (wcs->prjcode == WCS_CEA) { if (wcs->prj.p[1] == 0.0) wcs->prj.p[1] = 1.0; hgetr8c (hstring, pvkey1, &mchar, &wcs->prj.p[1]); } else if (wcs->prjcode == WCS_CYP) { if (wcs->prj.p[1] == 0.0) wcs->prj.p[1] = 1.0; hgetr8c (hstring, pvkey1, &mchar, &wcs->prj.p[1]); if (wcs->prj.p[2] == 0.0) wcs->prj.p[2] = 1.0; hgetr8c (hstring, pvkey2, &mchar, &wcs->prj.p[2]); } else if (wcs->prjcode == WCS_AIR) { if (wcs->prj.p[1] == 0.0) wcs->prj.p[1] = 90.0; hgetr8c (hstring, pvkey1, &mchar, &wcs->prj.p[1]); } else if (wcs->prjcode == WCS_BON) { hgetr8c (hstring, pvkey1, &mchar, &wcs->prj.p[1]); } else if (wcs->prjcode == WCS_ZPN) { for (i = 0; i < 10; i++) { sprintf (keyword,"PV%d_%d", ilat, i); hgetr8c (hstring, keyword, &mchar, &wcs->prj.p[i]); } } /* Initialize TNX, defaulting to TAN if there is a problem */ if (wcs->prjcode == WCS_TNX) { if (tnxinit (hstring, wcs)) { wcs->ctype[0][6] = 'A'; wcs->ctype[0][7] = 'N'; wcs->ctype[1][6] = 'A'; wcs->ctype[1][7] = 'N'; wcs->prjcode = WCS_TAN; } } /* Initialize ZPX, defaulting to ZPN if there is a problem */ if (wcs->prjcode == WCS_ZPX) { if (zpxinit (hstring, wcs)) { wcs->ctype[0][7] = 'N'; wcs->ctype[1][7] = 'N'; wcs->prjcode = WCS_ZPN; } } /* Set TPV to TAN as SCAMP coefficients will be added below */ if (wcs->prjcode == WCS_TPV) { wcs->ctype[0][6] = 'A'; wcs->ctype[0][7] = 'N'; wcs->ctype[1][6] = 'A'; wcs->ctype[1][7] = 'N'; wcs->prjcode = WCS_TAN; } /* Coordinate reference frame, equinox, and epoch */ if (wcs->wcsproj > 0) wcseqm (hstring, wcs, &mchar); wcsioset (wcs); /* Read distortion coefficients, if present */ distortinit (wcs, hstring); /* Use polynomial fit instead of projection, if present */ wcs->ncoeff1 = 0; wcs->ncoeff2 = 0; cd11p = hgetr8c (hstring, "CD1_1", &mchar, &cd[0]); cd12p = hgetr8c (hstring, "CD1_2", &mchar, &cd[1]); cd21p = hgetr8c (hstring, "CD2_1", &mchar, &cd[2]); cd22p = hgetr8c (hstring, "CD2_2", &mchar, &cd[3]); if (wcs->wcsproj != WCS_OLD && (hcoeff = ksearch (hstring,"CO1_1")) != NULL) { wcs->prjcode = WCS_PLT; (void)strcpy (wcs->ptype, "PLATE"); for (i = 0; i < 20; i++) { sprintf (keyword,"CO1_%d", i+1); wcs->x_coeff[i] = 0.0; if (hgetr8 (hcoeff, keyword, &wcs->x_coeff[i])) wcs->ncoeff1 = i + 1; } hcoeff = ksearch (hstring,"CO2_1"); for (i = 0; i < 20; i++) { sprintf (keyword,"CO2_%d",i+1); wcs->y_coeff[i] = 0.0; if (hgetr8 (hcoeff, keyword, &wcs->y_coeff[i])) wcs->ncoeff2 = i + 1; } /* Compute a nominal scale factor */ platepos (wcs->crpix[0], wcs->crpix[1], wcs, &ra0, &dec0); platepos (wcs->crpix[0], wcs->crpix[1]+1.0, wcs, &ra1, &dec1); wcs->yinc = dec1 - dec0; wcs->xinc = -wcs->yinc; /* Compute image rotation angle */ wcs->wcson = 1; wcsrotset (wcs); rot = degrad (wcs->rot); /* Compute scale at reference pixel */ platepos (wcs->crpix[0], wcs->crpix[1], wcs, &ra0, &dec0); platepos (wcs->crpix[0]+cos(rot), wcs->crpix[1]+sin(rot), wcs, &ra1, &dec1); wcs->cdelt[0] = -wcsdist (ra0, dec0, ra1, dec1); wcs->xinc = wcs->cdelt[0]; platepos (wcs->crpix[0]+sin(rot), wcs->crpix[1]+cos(rot), wcs, &ra1, &dec1); wcs->cdelt[1] = wcsdist (ra0, dec0, ra1, dec1); wcs->yinc = wcs->cdelt[1]; /* Set CD matrix from header */ wcs->cd[0] = cd[0]; wcs->cd[1] = cd[1]; wcs->cd[2] = cd[2]; wcs->cd[3] = cd[3]; (void) matinv (2, wcs->cd, wcs->dc); } /* Else use CD matrix, if present */ else if (cd11p || cd12p || cd21p || cd22p) { wcs->rotmat = 1; wcscdset (wcs, cd); } /* Else get scaling from CDELT1 and CDELT2 */ else if (hgetr8c (hstring, "CDELT1", &mchar, &cdelt1) != 0) { hgetr8c (hstring, "CDELT2", &mchar, &cdelt2); /* If CDELT1 or CDELT2 is 0 or missing */ if (cdelt1 == 0.0 || (wcs->nypix > 1 && cdelt2 == 0.0)) { if (ksearch (hstring,"SECPIX") != NULL || ksearch (hstring,"PIXSCALE") != NULL || ksearch (hstring,"PIXSCAL1") != NULL || ksearch (hstring,"XPIXSIZE") != NULL || ksearch (hstring,"SECPIX1") != NULL) { secpix = 0.0; hgetr8 (hstring,"SECPIX",&secpix); if (secpix == 0.0) hgetr8 (hstring,"PIXSCALE",&secpix); if (secpix == 0.0) { hgetr8 (hstring,"SECPIX1",&secpix); if (secpix != 0.0) { if (cdelt1 == 0.0) cdelt1 = -secpix / 3600.0; if (cdelt2 == 0.0) { hgetr8 (hstring,"SECPIX2",&secpix); cdelt2 = secpix / 3600.0; } } else { hgetr8 (hstring,"XPIXSIZE",&secpix); if (secpix != 0.0) { if (cdelt1 == 0.0) cdelt1 = -secpix / 3600.0; if (cdelt2 == 0.0) { hgetr8 (hstring,"YPIXSIZE",&secpix); cdelt2 = secpix / 3600.0; } } else { hgetr8 (hstring,"PIXSCAL1",&secpix); if (secpix != 0.0 && cdelt1 == 0.0) cdelt1 = -secpix / 3600.0; if (cdelt2 == 0.0) { hgetr8 (hstring,"PIXSCAL2",&secpix); cdelt2 = secpix / 3600.0; } } } } else { if (cdelt1 == 0.0) cdelt1 = -secpix / 3600.0; if (cdelt2 == 0.0) cdelt2 = secpix / 3600.0; } } } if (cdelt2 == 0.0 && wcs->nypix > 1) cdelt2 = -cdelt1; wcs->cdelt[2] = 1.0; wcs->cdelt[3] = 1.0; /* Initialize rotation matrix */ for (i = 0; i < 81; i++) { pc[i] = 0.0; wcs->pc[i] = 0.0; } for (i = 0; i < naxes; i++) pc[(i*naxes)+i] = 1.0; /* Read FITS WCS interim rotation matrix */ if (!mchar && hgetr8 (hstring,"PC001001",&pc[0]) != 0) { k = 0; for (i = 0; i < naxes; i++) { for (j = 0; j < naxes; j++) { if (i == j) pc[k] = 1.0; else pc[k] = 0.0; sprintf (keyword, "PC00%1d00%1d", i+1, j+1); hgetr8 (hstring, keyword, &pc[k++]); } } wcspcset (wcs, cdelt1, cdelt2, pc); } /* Read FITS WCS standard rotation matrix */ else if (hgetr8c (hstring, "PC1_1", &mchar, &pc[0]) != 0) { k = 0; for (i = 0; i < naxes; i++) { for (j = 0; j < naxes; j++) { if (i == j) pc[k] = 1.0; else pc[k] = 0.0; sprintf (keyword, "PC%1d_%1d", i+1, j+1); hgetr8c (hstring, keyword, &mchar, &pc[k++]); } } wcspcset (wcs, cdelt1, cdelt2, pc); } /* Otherwise, use CROTAn */ else { rot = 0.0; if (ilat == 2) hgetr8c (hstring, "CROTA2", &mchar, &rot); else hgetr8c (hstring,"CROTA1", &mchar, &rot); wcsdeltset (wcs, cdelt1, cdelt2, rot); } } /* If no scaling is present, set to 1 per pixel, no rotation */ else { wcs->xinc = 1.0; wcs->yinc = 1.0; wcs->cdelt[0] = 1.0; wcs->cdelt[1] = 1.0; wcs->rot = 0.0; wcs->rotmat = 0; setwcserr ("WCSINIT: setting CDELT to 1"); } /* SCAMP convention */ if (wcs->prjcode == WCS_TAN && wcs->naxis == 2) { int n = 0; if (wcs->inv_x) { poly_end(wcs->inv_x); wcs->inv_x = NULL; } if (wcs->inv_y) { poly_end(wcs->inv_y); wcs->inv_y = NULL; } wcs->pvfail = 0; for (i = 0; i < (2*MAXPV); i++) { wcs->projppv[i] = 0.0; wcs->prj.ppv[i] = 0.0; } for (k = 0; k < 2; k++) { for (j = 0; j < MAXPV; j++) { sprintf(keyword, "PV%d_%d", k+1, j); if (hgetr8c(hstring, keyword,&mchar, &wcs->projppv[j+k*MAXPV]) == 0) { wcs->projppv[j+k*MAXPV] = 0.0; } else n++; } } /* If any PVi_j are set, add them in the structure if no SIRTF distortion*/ if (n > 0 && wcs->distcode != DISTORT_SIRTF) { n = 0; for (k = MAXPV; k >= 0; k--) { /* lat comes first for compatibility reasons */ wcs->prj.ppv[k] = wcs->projppv[k+wcs->wcsl.lat*MAXPV]; wcs->prj.ppv[k+MAXPV] = wcs->projppv[k+wcs->wcsl.lng*MAXPV]; if (!n && (wcs->prj.ppv[k] || wcs->prj.ppv[k+MAXPV])) { n = k+1; } } invert_wcs(wcs); /* Need to call tanset again */ wcs->cel.flag = 0; } } /* If linear or pixel WCS, print "degrees" */ if (!strncmp (wcs->ptype,"LINEAR",6) || !strncmp (wcs->ptype,"PIXEL",5)) { wcs->degout = -1; wcs->ndec = 5; } /* Epoch of image (from observation date, if possible) */ if (hgetr8 (hstring, "MJD-OBS", &mjd)) wcs->epoch = 1900.0 + (mjd - 15019.81352) / 365.242198781; else if (!hgetdate (hstring,"DATE-OBS",&wcs->epoch)) { if (!hgetdate (hstring,"DATE",&wcs->epoch)) { if (!hgetr8 (hstring,"EPOCH",&wcs->epoch)) wcs->epoch = wcs->equinox; } } /* Add time of day if not part of DATE-OBS string */ else { hgets (hstring,"DATE-OBS",32,tstring); if (!strchr (tstring,'T')) { if (hgetr8 (hstring, "UT",&ut)) wcs->epoch = wcs->epoch + (ut / (24.0 * 365.242198781)); else if (hgetr8 (hstring, "UTMID",&ut)) wcs->epoch = wcs->epoch + (ut / (24.0 * 365.242198781)); } } wcs->wcson = 1; } else if (mchar != cnull && mchar != cspace) { (void) sprintf (temp, "WCSINITC: No image scale for WCS %c", mchar); setwcserr (temp); wcsfree (wcs); return (NULL); } /* Plate solution coefficients */ else if (ksearch (hstring,"PLTRAH") != NULL) { wcs->prjcode = WCS_DSS; hcoeff = ksearch (hstring,"PLTRAH"); hgetr8 (hcoeff,"PLTRAH",&rah); hgetr8 (hcoeff,"PLTRAM",&ram); hgetr8 (hcoeff,"PLTRAS",&ras); ra_hours = rah + (ram / (double)60.0) + (ras / (double)3600.0); wcs->plate_ra = hrrad (ra_hours); decsign = '+'; hgets (hcoeff,"PLTDECSN", 1, &decsign); if (decsign == '-') dsign = -1.; else dsign = 1.; hgetr8 (hcoeff,"PLTDECD",&decd); hgetr8 (hcoeff,"PLTDECM",&decm); hgetr8 (hcoeff,"PLTDECS",&decs); dec_deg = dsign * (decd+(decm/(double)60.0)+(decs/(double)3600.0)); wcs->plate_dec = degrad (dec_deg); hgetr8 (hstring,"EQUINOX",&wcs->equinox); hgeti4 (hstring,"EQUINOX",&ieq); if (ieq == 1950) strcpy (wcs->radecsys,"FK4"); else strcpy (wcs->radecsys,"FK5"); wcs->epoch = wcs->equinox; hgetr8 (hstring,"EPOCH",&wcs->epoch); (void)sprintf (wcs->center,"%2.0f:%2.0f:%5.3f %c%2.0f:%2.0f:%5.3f %s", rah,ram,ras,decsign,decd,decm,decs,wcs->radecsys); hgetr8 (hstring,"PLTSCALE",&wcs->plate_scale); hgetr8 (hstring,"XPIXELSZ",&wcs->x_pixel_size); hgetr8 (hstring,"YPIXELSZ",&wcs->y_pixel_size); hgetr8 (hstring,"CNPIX1",&wcs->x_pixel_offset); hgetr8 (hstring,"CNPIX2",&wcs->y_pixel_offset); hcoeff = ksearch (hstring,"PPO1"); for (i = 0; i < 6; i++) { sprintf (keyword,"PPO%d", i+1); wcs->ppo_coeff[i] = 0.0; hgetr8 (hcoeff,keyword,&wcs->ppo_coeff[i]); } hcoeff = ksearch (hstring,"AMDX1"); for (i = 0; i < 20; i++) { sprintf (keyword,"AMDX%d", i+1); wcs->x_coeff[i] = 0.0; hgetr8 (hcoeff, keyword, &wcs->x_coeff[i]); } hcoeff = ksearch (hstring,"AMDY1"); for (i = 0; i < 20; i++) { sprintf (keyword,"AMDY%d",i+1); wcs->y_coeff[i] = 0.0; hgetr8 (hcoeff, keyword, &wcs->y_coeff[i]); } wcs->wcson = 1; (void)strcpy (wcs->c1type, "RA"); (void)strcpy (wcs->c2type, "DEC"); (void)strcpy (wcs->ptype, "DSS"); wcs->degout = 0; wcs->ndec = 3; /* Compute a nominal reference pixel at the image center */ strcpy (wcs->ctype[0], "RA---DSS"); strcpy (wcs->ctype[1], "DEC--DSS"); wcs->crpix[0] = 0.5 * wcs->nxpix; wcs->crpix[1] = 0.5 * wcs->nypix; wcs->xrefpix = wcs->crpix[0]; wcs->yrefpix = wcs->crpix[1]; dsspos (wcs->crpix[0], wcs->crpix[1], wcs, &ra0, &dec0); wcs->crval[0] = ra0; wcs->crval[1] = dec0; wcs->xref = wcs->crval[0]; wcs->yref = wcs->crval[1]; /* Compute a nominal scale factor */ dsspos (wcs->crpix[0], wcs->crpix[1]+1.0, wcs, &ra1, &dec1); wcs->yinc = dec1 - dec0; wcs->xinc = -wcs->yinc; wcsioset (wcs); /* Compute image rotation angle */ wcs->wcson = 1; wcsrotset (wcs); rot = degrad (wcs->rot); /* Compute image scale at center */ dsspos (wcs->crpix[0]+cos(rot), wcs->crpix[1]+sin(rot), wcs, &ra1, &dec1); wcs->cdelt[0] = -wcsdist (ra0, dec0, ra1, dec1); dsspos (wcs->crpix[0]+sin(rot), wcs->crpix[1]+cos(rot), wcs, &ra1, &dec1); wcs->cdelt[1] = wcsdist (ra0, dec0, ra1, dec1); /* Set all other image scale parameters */ wcsdeltset (wcs, wcs->cdelt[0], wcs->cdelt[1], wcs->rot); } /* Approximate world coordinate system if plate scale is known */ else if ((ksearch (hstring,"SECPIX") != NULL || ksearch (hstring,"PIXSCALE") != NULL || ksearch (hstring,"PIXSCAL1") != NULL || ksearch (hstring,"XPIXSIZE") != NULL || ksearch (hstring,"SECPIX1") != NULL)) { secpix = 0.0; hgetr8 (hstring,"SECPIX",&secpix); if (secpix == 0.0) hgetr8 (hstring,"PIXSCALE",&secpix); if (secpix == 0.0) { hgetr8 (hstring,"SECPIX1",&secpix); if (secpix != 0.0) { cdelt1 = -secpix / 3600.0; hgetr8 (hstring,"SECPIX2",&secpix); cdelt2 = secpix / 3600.0; } else { hgetr8 (hstring,"XPIXSIZE",&secpix); if (secpix != 0.0) { cdelt1 = -secpix / 3600.0; hgetr8 (hstring,"YPIXSIZE",&secpix); cdelt2 = secpix / 3600.0; } else { hgetr8 (hstring,"PIXSCAL1",&secpix); cdelt1 = -secpix / 3600.0; hgetr8 (hstring,"PIXSCAL2",&secpix); cdelt2 = secpix / 3600.0; } } } else { cdelt2 = secpix / 3600.0; cdelt1 = -cdelt2; } /* Get rotation angle from the header, if it's there */ rot = 0.0; hgetr8 (hstring,"CROTA1", &rot); if (wcs->rot == 0.) hgetr8 (hstring,"CROTA2", &rot); /* Set CD and PC matrices */ wcsdeltset (wcs, cdelt1, cdelt2, rot); /* By default, set reference pixel to center of image */ wcs->crpix[0] = 0.5 + (wcs->nxpix * 0.5); wcs->crpix[1] = 0.5 + (wcs->nypix * 0.5); /* Get reference pixel from the header, if it's there */ if (ksearch (hstring,"CRPIX1") != NULL) { hgetr8 (hstring,"CRPIX1",&wcs->crpix[0]); hgetr8 (hstring,"CRPIX2",&wcs->crpix[1]); } /* Use center of detector array as reference pixel else if (ksearch (hstring,"DETSIZE") != NULL || ksearch (hstring,"DETSEC") != NULL) { char *ic; hgets (hstring, "DETSIZE", 32, temp); ic = strchr (temp, ':'); if (ic != NULL) *ic = ' '; ic = strchr (temp, ','); if (ic != NULL) *ic = ' '; ic = strchr (temp, ':'); if (ic != NULL) *ic = ' '; ic = strchr (temp, ']'); if (ic != NULL) *ic = cnull; sscanf (temp, "%d %d %d %d", &idx1, &idx2, &idy1, &idy2); dxrefpix = 0.5 * (double) (idx1 + idx2 - 1); dyrefpix = 0.5 * (double) (idy1 + idy2 - 1); hgets (hstring, "DETSEC", 32, temp); ic = strchr (temp, ':'); if (ic != NULL) *ic = ' '; ic = strchr (temp, ','); if (ic != NULL) *ic = ' '; ic = strchr (temp, ':'); if (ic != NULL) *ic = ' '; ic = strchr (temp, ']'); if (ic != NULL) *ic = cnull; sscanf (temp, "%d %d %d %d", &ix1, &ix2, &iy1, &iy2); wcs->crpix[0] = dxrefpix - (double) (ix1 - 1); wcs->crpix[1] = dyrefpix - (double) (iy1 - 1); } */ wcs->xrefpix = wcs->crpix[0]; wcs->yrefpix = wcs->crpix[1]; wcs->crval[0] = -999.0; if (!hgetra (hstring,"RA",&wcs->crval[0])) { setwcserr ("WCSINIT: No RA with SECPIX, no WCS"); wcsfree (wcs); return (NULL); } wcs->crval[1] = -999.0; if (!hgetdec (hstring,"DEC",&wcs->crval[1])) { setwcserr ("WCSINIT No DEC with SECPIX, no WCS"); wcsfree (wcs); return (NULL); } wcs->xref = wcs->crval[0]; wcs->yref = wcs->crval[1]; wcs->coorflip = 0; wcs->cel.ref[0] = wcs->crval[0]; wcs->cel.ref[1] = wcs->crval[1]; wcs->cel.ref[2] = 999.0; if (!hgetr8 (hstring,"LONPOLE",&wcs->cel.ref[2])) hgetr8 (hstring,"LONGPOLE",&wcs->cel.ref[2]); wcs->cel.ref[3] = 999.0; hgetr8 (hstring,"LATPOLE",&wcs->cel.ref[3]); /* Epoch of image (from observation date, if possible) */ if (hgetr8 (hstring, "MJD-OBS", &mjd)) wcs->epoch = 1900.0 + (mjd - 15019.81352) / 365.242198781; else if (!hgetdate (hstring,"DATE-OBS",&wcs->epoch)) { if (!hgetdate (hstring,"DATE",&wcs->epoch)) { if (!hgetr8 (hstring,"EPOCH",&wcs->epoch)) wcs->epoch = wcs->equinox; } } /* Add time of day if not part of DATE-OBS string */ else { hgets (hstring,"DATE-OBS",32,tstring); if (!strchr (tstring,'T')) { if (hgetr8 (hstring, "UT",&ut)) wcs->epoch = wcs->epoch + (ut / (24.0 * 365.242198781)); else if (hgetr8 (hstring, "UTMID",&ut)) wcs->epoch = wcs->epoch + (ut / (24.0 * 365.242198781)); } } /* Coordinate reference frame and equinox */ (void) wcstype (wcs, "RA---TAN", "DEC--TAN"); wcs->coorflip = 0; wcseq (hstring,wcs); wcsioset (wcs); wcs->degout = 0; wcs->ndec = 3; wcs->wcson = 1; } else { setwcserr ("WCSINIT: No image scale"); wcsfree (wcs); return (NULL); } wcs->lin.crpix = wcs->crpix; wcs->lin.cdelt = wcs->cdelt; wcs->lin.pc = wcs->pc; wcs->printsys = 1; wcs->tabsys = 0; wcs->linmode = 0; /* Initialize special WCS commands */ setwcscom (wcs); return (wcs); } /******* invert_wcs *********************************************************** PROTO void invert_wcs(wcsstruct *wcs) PURPOSE Invert WCS projection mapping (using a polynomial). INPUT WCS structure. OUTPUT -. NOTES . AUTHOR E. Bertin (IAP) VERSION 06/11/2003 ***/ void invert_wcs( struct WorldCoor *wcs) { polystruct *poly; double pixin[NAXISPV],raw[NAXISPV],rawmin[NAXISPV]; double *outpos,*outpost, *lngpos,*lngpost; double *latpos,*latpost,lngstep,latstep, rawsize, epsilon; int group[] = {1,1}; /* Don't ask, this is needed by poly_init()! */ int i,j,lng,lat,deg, maxflag; char errstr[80]; double xmin; double ymin; double xmax; double ymax; double lngmin; double latmin; /* Check first that inversion is not straightforward */ lng = wcs->wcsl.lng; lat = wcs->wcsl.lat; if (wcs->naxis != NAXISPV) { return; } if (strcmp(wcs->wcsl.pcode, "TAN") != 0) { return; } if ((wcs->projppv[1+lng*MAXPV] == 0) && (wcs->projppv[1+lat*MAXPV] == 0)) { return; } if (wcs->wcs != NULL) { pix2wcs(wcs->wcs,0,0,&xmin,&ymin); pix2wcs(wcs->wcs,wcs->nxpix,wcs->nypix,&xmax,&ymax); } else { xmin = 0; ymin = 0; xmax = wcs->nxpix; ymax = wcs->nypix; } /* We define x as "longitude" and y as "latitude" projections */ /* We assume that PCxx cross-terms with additional dimensions are small */ /* Sample the whole image with a regular grid */ if (lng == 0) { lngstep = (xmax-xmin)/(WCS_NGRIDPOINTS-1.0); lngmin = xmin; latstep = (ymax-ymin)/(WCS_NGRIDPOINTS-1.0); latmin = ymin; } else { lngstep = (ymax-ymin)/(WCS_NGRIDPOINTS-1.0); lngmin = ymin; latstep = (xmax-xmin)/(WCS_NGRIDPOINTS-1.0); latmin = xmin; } outpos = (double *)calloc(2*WCS_NGRIDPOINTS2,sizeof(double)); lngpos = (double *)calloc(WCS_NGRIDPOINTS2,sizeof(double)); latpos = (double *)calloc(WCS_NGRIDPOINTS2,sizeof(double)); raw[lat] = rawmin[lat] = 0.5+latmin; raw[lng] = rawmin[lng] = 0.5+lngmin; outpost = outpos; lngpost = lngpos; latpost = latpos; for (j=WCS_NGRIDPOINTS; j--; raw[lat]+=latstep) { raw[lng] = rawmin[lng]; for (i=WCS_NGRIDPOINTS; i--; raw[lng]+=lngstep) { if (linrev(raw, &wcs->lin, pixin)) { sprintf (errstr,"*Error*: incorrect linear conversion in %s", wcs->wcsl.pcode); setwcserr (errstr); } *(lngpost++) = pixin[lng]; *(latpost++) = pixin[lat]; raw_to_pv (&wcs->prj,pixin[lng],pixin[lat], outpost, outpost+1); outpost += 2; } } /* Invert "longitude" */ /* Compute the extent of the pixel in reduced projected coordinates */ linrev(rawmin, &wcs->lin, pixin); pixin[lng] += S2D; linfwd(pixin, &wcs->lin, raw); rawsize = sqrt((raw[lng]-rawmin[lng])*(raw[lng]-rawmin[lng]) +(raw[lat]-rawmin[lat])*(raw[lat]-rawmin[lat]))*D2S; if (!rawsize) { sprintf (errstr,"*Error*: incorrect linear conversion in %s", wcs->wcsl.pcode); setwcserr (errstr); } epsilon = WCS_INVACCURACY/rawsize; /* Find the lowest degree polynom */ poly = NULL; /* to avoid gcc -Wall warnings */ maxflag = 1; for (deg=1; deg<=WCS_INVMAXDEG && maxflag; deg++) { if (deg>1) { poly_end(poly); } poly = poly_init(group, 2, °, 1); poly_fit(poly, outpos, lngpos, NULL, WCS_NGRIDPOINTS2, NULL); maxflag = 0; outpost = outpos; lngpost = lngpos; for (i=WCS_NGRIDPOINTS2; i--; outpost+=2) { if (fabs(poly_func(poly, outpost)-*(lngpost++))>epsilon) { maxflag = 1; break; } } } if (maxflag) { setwcserr ("WARNING: Significant inaccuracy likely to occur in projection"); wcs->pvfail = 1; } /* Now link the created structure */ wcs->prj.inv_x = wcs->inv_x = poly; /* Invert "latitude" */ /* Compute the extent of the pixel in reduced projected coordinates */ linrev(rawmin, &wcs->lin, pixin); pixin[lat] += S2D; linfwd(pixin, &wcs->lin, raw); rawsize = sqrt((raw[lng]-rawmin[lng])*(raw[lng]-rawmin[lng]) +(raw[lat]-rawmin[lat])*(raw[lat]-rawmin[lat]))*D2S; if (!rawsize) { sprintf (errstr,"*Error*: incorrect linear conversion in %s", wcs->wcsl.pcode); setwcserr (errstr); } epsilon = WCS_INVACCURACY/rawsize; /* Find the lowest degree polynom */ maxflag = 1; for (deg=1; deg<=WCS_INVMAXDEG && maxflag; deg++) { if (deg>1) poly_end(poly); poly = poly_init(group, 2, °, 1); poly_fit(poly, outpos, latpos, NULL, WCS_NGRIDPOINTS2, NULL); maxflag = 0; outpost = outpos; latpost = latpos; for (i=WCS_NGRIDPOINTS2; i--; outpost+=2) { if (fabs(poly_func(poly, outpost)-*(latpost++))>epsilon) { maxflag = 1; break; } } } if (maxflag) { setwcserr ("WARNING: Significant inaccuracy likely to occur in projection"); wcs->pvfail = 1; } /* Now link the created structure */ wcs->prj.inv_y = wcs->inv_y = poly; /* Free memory */ free(outpos); free(lngpos); free(latpos); return; } /* Set coordinate system of image, input, and output */ static void wcsioset (wcs) struct WorldCoor *wcs; { if (strlen (wcs->radecsys) == 0 || wcs->prjcode == WCS_LIN) strcpy (wcs->radecsys, "LINEAR"); if (wcs->prjcode == WCS_PIX) strcpy (wcs->radecsys, "PIXEL"); wcs->syswcs = wcscsys (wcs->radecsys); if (wcs->syswcs == WCS_B1950) strcpy (wcs->radecout, "FK4"); else if (wcs->syswcs == WCS_J2000) strcpy (wcs->radecout, "FK5"); else strcpy (wcs->radecout, wcs->radecsys); wcs->sysout = wcscsys (wcs->radecout); wcs->eqout = wcs->equinox; strcpy (wcs->radecin, wcs->radecsys); wcs->sysin = wcscsys (wcs->radecin); wcs->eqin = wcs->equinox; return; } static void wcseq (hstring, wcs) char *hstring; /* character string containing FITS header information in the format = [/ ] */ struct WorldCoor *wcs; /* World coordinate system data structure */ { char mchar; /* Suffix character for one of multiple WCS */ mchar = (char) 0; wcseqm (hstring, wcs, &mchar); return; } static void wcseqm (hstring, wcs, mchar) char *hstring; /* character string containing FITS header information in the format = [/ ] */ struct WorldCoor *wcs; /* World coordinate system data structure */ char *mchar; /* Suffix character for one of multiple WCS */ { int ieq = 0; int eqhead = 0; char systring[32], eqstring[32]; char radeckey[16], eqkey[16]; char tstring[32]; double ut; /* Set equinox from EQUINOX, EPOCH, or RADECSYS; default to 2000 */ systring[0] = 0; eqstring[0] = 0; if (mchar[0]) { sprintf (eqkey, "EQUINOX%c", mchar[0]); sprintf (radeckey, "RADECSYS%c", mchar[0]); } else { strcpy (eqkey, "EQUINOX"); sprintf (radeckey, "RADECSYS"); } if (!hgets (hstring, eqkey, 31, eqstring)) { if (hgets (hstring, "EQUINOX", 31, eqstring)) strcpy (eqkey, "EQUINOX"); } if (!hgets (hstring, radeckey, 31, systring)) { if (hgets (hstring, "RADECSYS", 31, systring)) sprintf (radeckey, "RADECSYS"); } if (eqstring[0] == 'J') { wcs->equinox = atof (eqstring+1); ieq = atoi (eqstring+1); strcpy (systring, "FK5"); } else if (eqstring[0] == 'B') { wcs->equinox = atof (eqstring+1); ieq = (int) atof (eqstring+1); strcpy (systring, "FK4"); } else if (hgeti4 (hstring, eqkey, &ieq)) { hgetr8 (hstring, eqkey, &wcs->equinox); eqhead = 1; } else if (hgeti4 (hstring,"EPOCH",&ieq)) { if (ieq == 0) { ieq = 1950; wcs->equinox = 1950.0; } else { hgetr8 (hstring,"EPOCH",&wcs->equinox); eqhead = 1; } } else if (systring[0] != (char)0) { if (!strncmp (systring,"FK4",3)) { wcs->equinox = 1950.0; ieq = 1950; } else if (!strncmp (systring,"ICRS",4)) { wcs->equinox = 2000.0; ieq = 2000; } else if (!strncmp (systring,"FK5",3)) { wcs->equinox = 2000.0; ieq = 2000; } else if (!strncmp (systring,"GAL",3)) { wcs->equinox = 2000.0; ieq = 2000; } else if (!strncmp (systring,"ECL",3)) { wcs->equinox = 2000.0; ieq = 2000; } } if (ieq == 0) { wcs->equinox = 2000.0; ieq = 2000; if (!strncmp (wcs->c1type, "RA",2) || !strncmp (wcs->c1type,"DEC",3)) strcpy (systring,"FK5"); } /* Epoch of image (from observation date, if possible) */ if (!hgetdate (hstring,"DATE-OBS",&wcs->epoch)) { if (!hgetdate (hstring,"DATE",&wcs->epoch)) { if (!hgetr8 (hstring,"EPOCH",&wcs->epoch)) wcs->epoch = wcs->equinox; } } /* Add time of day if not part of DATE-OBS string */ else { hgets (hstring,"DATE-OBS",32,tstring); if (!strchr (tstring,'T')) { if (hgetr8 (hstring, "UT",&ut)) wcs->epoch = wcs->epoch + (ut / (24.0 * 365.242198781)); else if (hgetr8 (hstring, "UTMID",&ut)) wcs->epoch = wcs->epoch + (ut / (24.0 * 365.242198781)); } } if (wcs->epoch == 0.0) wcs->epoch = wcs->equinox; /* Set coordinate system from keyword, if it is present */ if (systring[0] == (char) 0) hgets (hstring, radeckey, 31, systring); if (systring[0] != (char) 0) { strcpy (wcs->radecsys,systring); if (!eqhead) { if (!strncmp (wcs->radecsys,"FK4",3)) wcs->equinox = 1950.0; else if (!strncmp (wcs->radecsys,"FK5",3)) wcs->equinox = 2000.0; else if (!strncmp (wcs->radecsys,"ICRS",4)) wcs->equinox = 2000.0; else if (!strncmp (wcs->radecsys,"GAL",3) && ieq == 0) wcs->equinox = 2000.0; } } /* Otherwise set coordinate system from equinox */ /* Systemless coordinates cannot be translated using b, j, or g commands */ else if (wcs->syswcs != WCS_NPOLE) { if (ieq > 1980) strcpy (wcs->radecsys,"FK5"); else strcpy (wcs->radecsys,"FK4"); } /* Set galactic coordinates if GLON or GLAT are in C1TYPE */ if (wcs->c1type[0] == 'G') strcpy (wcs->radecsys,"GALACTIC"); else if (wcs->c1type[0] == 'E') strcpy (wcs->radecsys,"ECLIPTIC"); else if (wcs->c1type[0] == 'S') strcpy (wcs->radecsys,"SGALACTC"); else if (wcs->c1type[0] == 'H') strcpy (wcs->radecsys,"HELIOECL"); else if (wcs->c1type[0] == 'A') strcpy (wcs->radecsys,"ALTAZ"); else if (wcs->c1type[0] == 'L') strcpy (wcs->radecsys,"LINEAR"); wcs->syswcs = wcscsys (wcs->radecsys); return; } /* Jun 11 1998 Split off header-dependent WCS initialization from other subs * Jun 15 1998 Fix major bug in wcsinit() when synthesizing WCS from header * Jun 18 1998 Fix bug in CD initialization; split PC initialization off * Jun 18 1998 Split PC initialization off into subroutine wcspcset() * Jun 24 1998 Set equinox from RADECSYS only if EQUINOX and EPOCH not present * Jul 6 1998 Read third and fourth axis CTYPEs * Jul 7 1998 Initialize eqin and eqout to equinox, * Jul 9 1998 Initialize rotation matrices correctly * Jul 13 1998 Initialize rotation, scale for polynomial and DSS projections * Aug 6 1998 Fix CROTA computation for DSS projection * Sep 4 1998 Fix CROTA, CDELT computation for DSS and polynomial projections * Sep 14 1998 If DATE-OBS not found, check for DATE * Sep 14 1998 If B or J present in EQUINOX, use that info to set system * Sep 29 1998 Initialize additional WCS commands from the environment * Sep 29 1998 Fix bug which read DATE as number rather than formatted date * Dec 2 1998 Read projection constants from header (bug fix) * * Feb 9 1999 Set rotation angle correctly when using DSS projection * Feb 19 1999 Fill in CDELTs from scale keyword if absent or zero * Feb 19 1999 Add PIXSCALE as possible default arcseconds per pixel * Apr 7 1999 Add error checking for NAXIS and NAXIS1 keywords * Apr 7 1999 Do not set systring if epoch is 0 and not RA/Dec * Jul 8 1999 In RADECSYS, use FK5 and FK4 instead of J2000 and B1950 * Oct 15 1999 Free wcs using wcsfree() * Oct 20 1999 Add multiple WCS support using new subroutine names * Oct 21 1999 Delete unused variables after lint; declare dsspos() * Nov 9 1999 Add wcschar() to check WCSNAME keywords for desired WCS * Nov 9 1999 Check WCSPREx keyword to find out if chained WCS's * * Jan 6 1999 Add wcsinitn() to initialize from specific WCSNAME * Jan 24 2000 Set CD matrix from header even if using polynomial * Jan 27 2000 Fix MJD to epoch conversion for when MJD-OBS is the only date * Jan 28 2000 Set CD matrix for DSS projection, too * Jan 28 2000 Use wcsproj instead of oldwcs * Dec 18 2000 Fix error in hgets() call in wcschar() * Dec 29 2000 Compute inverse CD matrix even if polynomial solution * Dec 29 2000 Add PROJR0 keyword for WCSLIB projections * Dec 29 2000 Use CDi_j matrix if any elements are present * * Jan 31 2001 Fix to allow 1D WCS * Jan 31 2001 Treat single character WCS name as WCS character * Feb 20 2001 Implement WCSDEPx nested WCS's * Feb 23 2001 Initialize all 4 terms of CD matrix * Feb 28 2001 Fix bug which read CRPIX1 into CRPIX2 * Mar 20 2001 Compare mchar to (char)0, not null * Mar 21 2001 Move ic declaration into commented out code * Jul 12 2001 Read PROJPn constants into proj.p array instead of PVn * Sep 7 2001 Set system to galactic or ecliptic based on CTYPE, not RADECSYS * Oct 11 2001 Set ctype[0] as well as ctype[1] to TAN for TNX projections * Oct 19 2001 WCSDIM keyword overrides zero value of NAXIS * * Feb 19 2002 Add XPIXSIZE/YPIXSIZE (KPNO) as default image scale keywords * Mar 12 2002 Add LONPOLE as well as LONGPOLE for WCSLIB 2.8 * Apr 3 2002 Implement hget8c() and hgetsc() to simplify code * Apr 3 2002 Add PVj_n projection constants in addition to PROJPn * Apr 19 2002 Increase numeric keyword value length from 16 to 31 * Apr 19 2002 Fix bug which didn't set radecsys keyword name * Apr 24 2002 If no WCS present for specified letter, return null * Apr 26 2002 Implement WCSAXESa keyword as first choice for number of axes * Apr 26 2002 Add wcschar and wcsname to WCS structure * May 9 2002 Add radvel and zvel to WCS structure * May 13 2002 Free everything which is allocated * May 28 2002 Read 10 prj.p instead of maximum of 100 * May 31 2002 Fix bugs with PV reading * May 31 2002 Initialize syswcs, sysin, sysout in wcsioset() * Sep 25 2002 Fix subroutine calls for radvel and latpole * Dec 6 2002 Correctly compute pixel at center of image for default CRPIX * * Jan 2 2002 Do not reinitialize projection vector for PV input * Jan 3 2002 For ZPN, read PVi_0 to PVi_9, not PVi_1 to PVi_10 * Mar 27 2003 Clean up default center computation * Apr 3 2003 Add input for SIRTF distortion coefficients * May 8 2003 Change PROJP reading to start with 0 instead of 1 * May 22 2003 Add ZPX approximation, reading projpn from WATi * May 28 2003 Avoid reinitializing coefficients set by PROJP * Jun 26 2003 Initialize xref and yref to -999.0 * Sep 23 2003 Change mgets() to mgetstr() to avoid name collision at UCO Lick * Oct 1 2003 Rename wcs->naxes to wcs->naxis to match WCSLIB 3.2 * Nov 3 2003 Initialize distortion coefficients in distortinit() in distort.c * Dec 1 2003 Change p[0,1,2] initializations to p[1,2,3] * Dec 3 2003 Add back wcs->naxes for backward compatibility * Dec 3 2003 Remove unused variables j,m in wcsinitc() * Dec 12 2003 Fix call to setwcserr() with format in it * * Feb 26 2004 Add parameters for ZPX projection * * Jun 22 2005 Drop declaration of variable wcserrmsg which is not used * Nov 9 2005 Use CROTA1 if CTYPE1 is LAT/DEC, CROTA2 if CTYPE2 is LAT/DEC * * Mar 9 2006 Get Epoch of observation from MJD-OBS or DATE-OBS/UT unless DSS * Apr 24 2006 Initialize rotation matrices * Apr 25 2006 Ignore axes with dimension of one * May 19 2006 Initialize all of 9x9 PC matrix; read in loops * Aug 21 2006 Limit naxes to 2 everywhere; RA and DEC should always be 1st * Oct 6 2006 If units are pixels, projection type is PIXEL * Oct 30 2006 Initialize cube face to -1, not a cube projection * * Jan 4 2007 Drop declarations of wcsinitc() and wcsinitn() already in wcs.h * Jan 8 2007 Change WCS letter from char to char* * Feb 1 2007 Read IRAF log wavelength flag DC-FLAG to wcs.logwcs * Feb 15 2007 Check for wcs->wcsproj > 0 instead of CTYPEi != LINEAR or PIXEL * Mar 13 2007 Try for RA, DEC, SECPIX if WCS character is space or null * Apr 27 2007 Ignore axes with TAB WCS for now * Oct 17 2007 Fix bug testing &mchar instead of mchar in if statement * * May 9 2008 Initialize TNX projection when projection types first set * Jun 27 2008 If NAXIS1 and NAXIS2 not present, check for IMAGEW and IMAGEH * * Mar 24 2009 Fix dimension bug if NAXISi not present (fix from John Burns) * * Mar 11 2011 Add NOAO ZPX projection (Frank Valdes) * Mar 18 2011 Add invert_wcs() by Emmanuel Bertin for SCAMP * Mar 18 2011 Change Bertin's ARCSEC/DEG to S2D and DEG/ARCSEC to D2S * Sep 1 2011 Add TPV as TAN with SCAMP PVs * * Oct 19 2012 Drop unused variable iszpx; fix bug in latmin assignment * * Feb 1 2013 Externalize uppercase() * Feb 07 2013 Avoid SWARP distortion if SIRTF distortion is present * Jul 25 2013 Initialize n=0 when checking for SCAMP distortion terms (fix from Martin Kuemmel) */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/NEWS0000644000175000017500000005003713047255533020163 0ustar mattymatty00000000000000WCSTools WCS subroutine library release history Version 3.9.0 (July 25, 2014) fileutil.c: Add next_line() to return one line of file fitfile.c: fix buffer reallocation bug in fitsrhead() Version 3.8.7 (October 31, 2012) dateutil.c: Unused l0 dropped from jd2lst(); ts2ss from jd2mst() imio.c: Fix errors with short and character images in minvec(), maxvec() wcs.c: Drop d1 and d2 from wcsdist(); diffi from wcsdist1() wcs.c: Drop depwcs; it's in main wcs structure wcsinit.c: Drop unused variable iszpx; fix bug in latmin assignment zpxpos.c: Fix code for quadratic near pole catutil.c: Skip trailing right bracket in aget*() Version 3.8.6 (August 10, 2012) All: Update author name imio.c: Fix 8-bit variables to be unsigned char Version 3.8.5 (April 12, 2012) imio.c: Change 8-bit pixel values from char to unsigned char fitsfile.c: Always check first 8 characters of FITS files for "SIMPLE" Version 3.8.4 (September 1, 2011) imgetwcs.c, wcsinit.c, wcs.c, wcs.h, worldpos.c: Add TPV WCS for TAN with PV terms Version 3.8.3 (May 20, 2011) hget.c: Free allocated memory in strnsrch() to eliminate memory leak (2011-05-19) imhfile.c: Free *newpixname* not pixname. (2011-05-20) wcsinit.c: Change error() calls to setwcserr() wcslib.h: Declare undeclared SCAMP subroutine raw-to-pv() wcs.c: Fix wcsfree() so it frees depended-on WCS structures (2011-05-09) March 18, 2011 - Release 3.8.2 zpxpos.c, wcs.c, wcsinit.c: Add support for NOAO ZPX protection (Frank Valdes) imsetwcs.c: Allocate NMAXMAG instead of number of magnitudes, nmag wcsinit.c,wcs.c,proj.c: Support SCAMP TAN distortion correction (Ed Los) wcsinit.c: ARSEC and DEG constants used by SCAMP replaced by S2D and D2S proj.c: If no PV coefficients in ZPN projection, make it ARC wcs.c: Fix bug involving dependent WCS's (Ed Los) April 30, 2010 - Release 3.8.1 scat,imcat: Set GSC2 magnitudes > 90 to 99.99 gethead: Fix buffer reallocation bug which crashed reading very large headers gethead: Fix trailing spaces on ASCII file quoted string values gethead: Fix problems with string value extraction changing ASCII files skycoor: Use number of decimal places from -n for -r difference if set wcscon.c: Fix bug in fk524() e-term computation; fix J<->B conversions fitsfile.c: In fitswhead(), always pad blocks to 2880 bytes with spaces and fix bug dealing with large primary headers wcscon.c: Fix bug in computing the magnitude of the e-terms in fk524() and drop ep1 assignment after line 178 in wcsconp() November 13, 2009 - Release 3.8.0 dateutil.c: Fix possible bug in nutation subroutine fitsfile.c: Add subroutine moveb() and fix binary table calls to it Fix lengths for ASCII numeric table entries in fitsrthead() fitsfile.h: Add moveb() which is used by binary FITS table code in fitsfile.c hget.c: In strfix(), if parentheses enclose a number, drop them November 21, 2008 - Release 3.7.6 fitsfile.c: In fitswhead() do not print write error if nw = nbytes dateutil.c: Use IAU 2006 nutation for sidereal time computations dateutil.c: Add ang2hr(), ang2deg(), deg2ang(), and ang2hr() to convert betweem decimal floating point degrees and vigesimal hours or degrees tnxpos.c: Fix image to world coordinate system transformation and WCS to image transformation July 1, 2008 - Release 3.7.5 wcsinit.c: Initialize TNX projection when projection types first set and check for IMAGEW and IMAGEH if NAXIS1 and NAXIS2 not present, fitsfile.c: Drop comma from name when reading file in isfits() and do not append primary data header if it is the only header May 9, 2008 - Release 3.7.4 fitsfile.c: In isfits(), allow extensions in FITS files without .fit or .fts wcsinit.c: Call tnxinit() before any projection calls are made March 20, 2008 - Release 3.7.3 wcs.c: Compute angular separation in wcsdist() using arcos December 31, 2007 - Release 3.7.2 wcscon.c: In wcsconp, make it clear that proper motion is in spherical coordinates fitsfile.c: Add support to BINTABLE in ftget*() and fitsrthead() fitsfile.c: Add data heap numerated by PCOUNT when skipping HDU in fitsrhead() fitsfile.c: Return NULL pointer if fitsrhead() cannot find requested HDU fitswcs.c: Print error message set by fitsrhead() November 9, 2007 - Release 3.7.1 wcsinit.c: Fix bug which tested &mchar instead of mchar in if statement August 24, 2007 - Release 3.7.0 hget.c: If a closing quote isn't found in a string value, make one up hput.c: Fix bug in comment insertion and deal correctly with missing quotes June 11, 2007 - Release 3.6.9 imio.c: Add minvec() and speed up maxvec() April 3, 2007 - Release 3.6.8 hget.c: Initial header length to zero in hlength() if lhead argument <= 0 wcs.c: In wcstype(), set to WCS_PIX if CTYPEi starts with "DET" wcs.c: In wcspset(), use correct cdelts when converting PC matrix to CD matrix wcsinit.c: Fix bug so RA, DEC, SECPIX can be used to set a WCS tnxpos.c: Fix bug so it doesn't crash January 16, 2007 - Release 3.6.7 wcs.h: Fix and add ANSI C prototypes imio.h: Drop as it has been included in fitsfile.h for several releases now fitsfile.h, fitshead.h: Add ANSI C prototypes wcsinitc(),wcsninitc(),hgeti4c(),hgetr8c(),hgetsc(): Change WCS letter argument from char to char* hget.c: Declare header and keyword const char in most subroutines hput.c: Declare keyword and value const in most subroutines hput.c: Fix bug in ra2str() and dec2str() so ndec=0 works imio.c: Include fitsfile.h instead of imio.h wcslib.h: Drop semicolon at end of c++ ifdef wcslib.h: Drop second declaration of SZP subroutines November 2, 2006 - Release 3.6.6 fitsfile.c: Use calloc() when reallocating header as it is read wcsinit.c: Limit naxes to 2 everywhere; RA and DEC should always be 1st wcsinit.c: If either CUNITi is "pixel" set projection to WCS_XY wcscon.c: In wcscsys, set system to WCS_XY if PIXEL projection wcscon.c: In wcscsys, set system to WCS_LINEAR if LINEAR coordinate system dateutil.c, fitshead.h: Add sidereal time to UT and vice versa June 30, 2006 - Release 3.6.5 wcsinit.c: Deal with up to 9x9 PC matrix wcs.c: Limit WCSLIB dimensions to two (this will change in 4.0) hput.c: Fix comment placement and replacement hget.c: Add strfix(), a utility to clean up strings May 3, 2006 - Release 3.6.4 fileutil.c: Add istiff(), isjpeg(), isgif() to check TIFF, JPEG, GIF files fitsfile.c: Add fitsrtail() to read appended FITS headers fitsfile.c: Add file name to header-reading error messages fitswcs.c: Add code to read FITS header appended to TIFF file imio.c: Fix bug of occasional double application of bscale in getvec() Clean up arithmetic and increment in addpix() and multpix() imsetwcs.c: Allow number of decimal places in image coordinates to be set wcsinit.c: Get Epoch of observation from MJD-OBS or DATE-OBS/UT unless DSS wcsinit.c: Set wcs->naxes to actual number of image WCS axes, usually 2 wcscon.c,dateutil.c,fitsfile.c: Drop declarations of unused variables wcs.c: Fix calls to avoid type conflicts in Linux January 5, 2006 - Release 3.6.3 wcs.h: Add WCS_ICRS to list of coordinate systems wcsinit.c: Initialize sys to WCS_ICRS if appropriate wcscon.c: Avoid precesssing ICRS coordinates wcscon.c: Fix precession which broke in 3.6.1 July 21, 2005 - Release 3.6.2 wcs.c: Fix wcsrange() to return correct range around RA=0 Clean up accumulated unused and misdeclared variables using lint April 13, 2005 - Release 3.6.1 Remove all sla_lib subroutines and calls thereto from wcscon.c, replacing them with local code. March 17, 2005 - Release 3.6.0 In wcs.c, fix bug in wcsrotset() so angles > 360 are set to angle - 360, not 360 Use unbuffered read() in isfits() in fitsfile.c ------------------------ November 01, 2004 - Release 3.5.8 In wcs.c, keep wcs->rot between 0 and 360 degrees (360.0 -> 0.0) September 21, 2004 - Release 3.5.7 In pix2wcs(), if spherical coordinate output, keep 0 < long/RA < 360 Fix bug in wcsfull() when wrapping around RA=0:00 In hput.c, add fixnegzero() to avoid putting -0.000 in header September 3, 2004 - Release 3.5.6 Modify FITS file reading software to get image size from file size if SIMPLE is F, so FITS headers with WCS can be used on arbitrary files. In hget.c, fix bug so comment is not pushed onto the next line if character value string lengthens (off by one bug). July 13, 2004 - Release 3.5.5 Add headshrink to hput.c to optionally keep blank lines after keywords are deleted. Read D, d, E, and e as exponent delimiters in floating point values in hget.c May 6, 2004 - Release 3.5.4 Add fitswexhead() to fitsfile.c to overwrite FITS extension headers April 16, 2004 - Release 3.5.3 Use strncsrch() in hget.c to get differently-cased keywords. February 3, 2004 - Release 3.5.2 In worldpix() in worldpos.c, allow ra/long. to exceed 180 if reference pixel is more than 180 degrees from image (1,1). December 12, 2003 - Release 3.5.1 Change p[0,1,2] initializations to p[1,2,3] in wcsinit.c to match proj.c (This affects constants for AZP,SIN,COP,COE,COD,COO,SZP,CEA,CYP,AIR,BON) Add wcs->naxes back into wcs structure for backward compatibility; it should always be equal to wcs->naxis. Fix bug in numdec() to return 0 if no digits after decimal point Fix call to setwcserr() with format in it November 17, 2003 - Release 3.5.0 Rename mgets() to mgetstr() in iget.c, wcsinit.c and fitshead.h Add numdec() to hget.c to return number of decimal places in numeric string Change wcs->naxes to wcs->naxis to prepare for WCSLIB 3.* In iraf2fits() and irafrimage(), use image, not physical, dimensions. In iraf2fits(), set NAXISi to image dimensions, NPAXISi to physical dimensions. Fix bugs in wcsfull() in wcs.c Move all distortion-related code to distort.c; include unistd.h Include stdlib.h instead of malloc.h in lin.c and drop malloc.h from matchstar.c ------------------------ August 22, 2003 - Release 3.4.2 Add fitsrfull() subroutine to read FITS files with more than 2 dimensions Modify fitswimage() to write FITS files with more than 2 dimensions July 11, 2003 - Release 3.4.1 Use strncmp to check for both stdin and stdout in fitsfile.c May 30, 2003 - Release 3.4.0 Add partial support for ZPX projection Fix bug reading COE and other projections when PROJPn coefficients were accidently reinitialized ------------------------ May 8, 2003 - Release 3.3.4 Add two missing semicolons in C++ declarations in wcs.h Read prj.p[0] from PROJP0 for ZPN projections, instead of ignoring it April 3, 2003 - Release 3.3.2 Add distortion conversion for SIRTF images March 27, 2003 - Release 3.3.1 Add conversions to and from Heliocentric Julian Dates to dateutil.c Open FITS and IMH files "rb" instead of "r" for Linux compatibility Add isimlistd() to fileutil.c to check for list of images in a specified directory Fix default center pixel computation in GetFITSWCS(); it was off by half a pixel January 30, 2003 - Release 3.3.0 Fix bug in dateutil.c ts2gst() sidereal time conversion. ------------------------ January 3, 2003 - Release 3.2.1 Fix bug in wcsinit() which failed to read PVi_0, and now initialize PVi_j in only once place. December 6, 2002 - Release 3.2.0 Add ET/TDT/TT and sidereal time conversion to dateutil.c Fix subroutine calls for radvel and latpole and correctly compute pixel at center of image for default CRPIX in wcsinit.c Add fitsrsect() to fitsfile.c to read a section of an image ------------------------ August 30, 2002 - Release 3.1.3 Fix bug in imio.c getvec() dealing with scaled images Add case-insensitive string search subroutines strcsrch() and strncsrch() Accept stdin as file in isfile() Add Ephemeris time conversions to dateutil() July 8, 2002 - Release 3.1.2 Fix bug in date utilities which always rounded to integer seconds of UT Fix bugs in date utilities to handle BC (negative) dates to JD 0. June 26, 2002 - Release 3.1.1 Fix bugs which caused TNX projection to fail Fix two bugs in wcsinit() which caused setting RADECSYS when an EQUINOX keyword is present. Write FITS error messages to string accessible by fitserr() Put SAO-written software under Gnu Lesser Public License April 12, 2002 - Release 3.1.0 Implement WCSLIB 2.9 Support PV entry of constants and PCi_j rotation matrices in wcsinit.c Support inversion (WCS->pix) of multiple dependent WCSs Add hgetri4c(), hgetr8c(), and hgetsc() for multiple WCS handling Fix bug in TNX projection software which caused an infinite loop during coefficient parsing. ------------------------ February 13, 2002 - Release 3.0.7 Fix bug in ecliptic coordinate conversion in wcscon.c Allow "stdin" to include extension and/or WCS selection in fitsfile.c Add a global switch to turn off scaling in imio.c Add ifdef to lin.c so it will compile under Mac OS/X December 4, 2001 - Release 3.0.6 In movepix(), add char to char move Always include stdlib.h in lin.c September 25, 2001 - Release 3.0.5 Implement WCSLIB version 2.7 Fix Makefile to include header files appropriately Accept FITS dates as yyyy/mm/dd Fix bug in str2dec() which misinterpreting strings with leading spaces Fix bug in isnum() which caused bad answer if trailing spaces Add fileutil.c, which includes various file info utilities September 7, 2001 - Release 3.0.3 Disallow files with = in their name in isfits() and isiraf() Set coordinate system from CTYPE if not equatorial July 12, 2001 - Release 3.0 Read PROJPn projection constants in wcsinit() ------------------------ March 30, 2001 - Release 2.9.4 Fix possible header length problem in hget.c March 22, 2001 - Release 2.9.3 Fix minor bugs in wcs.h, wcs.c, and wcsinit.c, wcslib.c, fitsfile.c, and cel.c found by gcc on Linux and possible memory leak in wcs.c March 9, 2001 - Release 2.9.2 In fitsfile.c, change multiple WCS separator in FITS file names from : to % and fix bug which failed to read multi-extension files if END was not preceded by a blank line in the extension's header. February 28, 2001 - Release 2.9.1 Fix major bug in wcsinit() which always set CRPIX2 the same as CRPIX1 February 23, 2001 - Release 2.9.0 FITS reading subroutines are fixed to ignore WCS name or character specified as :name or :character at end of filename. wcsinit() has new APIs which specify either a WCSNAME, wcsinitn(), or a WCS character, wcsinitc(), to allow use of multiple WCS's in a single FITS header. The WCSDEPx keyword has been added to indicate dependence on another WCS, though this feature has not been thoroughly debugged. fitscimage() is fixed so it doesn't overwrite data when overwriting a file An off-by-one bug was fixed for some polynomial types in tnxpos(). The WCSLIB subroutines were brought up to release 2.6 with very minor changes ------------------------ December 29, 2000 - Release 2.8.6 Fix handling of embedded + or - in isnum() in hget.c Default to 2000 for EQUINOX and EPOCH and FK5 for RADECSYS, if keywords not present. In wcscon.c, fk425() and fk524() algorithms were updated to include parallax and rv, proper motion is added by wcscon*() after fk425() or fk524() from system epoch, and proper motion units in fk524p() and fk425p() were fixed. In wcsinit.c, a bug initializing CD matrix was fixed. In cel.c, include string.h for strcmp(). September 29, 2000 - Release 2.8.5 wcsinit will now use a CD matrix if ANY CD keywords are present in header In getvec() in imio.c, move scaling outside of loop and make it conditional. Read .pix files in same directory as .imh file, if not otherwise found. August 1, 2000 - Release 2.8.3 Improve handling of 1-D WCS data. Fix numerous warning-generating bugs. Fix bug in ep2jd()/jd2ep() so both start year at 1/1 0:00 June 13, 2000 - Release 2.8.2 If imh pixel file has no directory, *always* use same as header file June 9, 2000 - Release 2.8.1 Read keyword values in hget.c even if no equal sign is present. June 2, 2000 - Release 2.8.0 Only a few minor changes due to running lint on everything ------------------------ May 10, 2000 - Release 2.7.4 In wcstype(), default to WCS_LIN, not error (after Bill Joye) May 1, 2000 - Release 2.7.3 Bug in hadd() fixed so new line is not overwritten. Pixel files whcih are in subdirectories of files where IRAF .imh header files reside are now dealt with correctly. All dates in the old FITS format (dd/mm/yy) where the year ranges from 0 to 999 have 1900 added to them: 01/05/100 becomes 2000-05-01. March 27, 2000 - Release 2.7.2 In hputs(), do not add quotes if writing COMMENT or HISTORY In fits2iraf(), in imhfile.c, minimize length of path in pixel file name Fix code to deal with .imh file paths longer than 67 characters. In platepix(), use inverse CD matrix to get better initial x,y value Change the maximum header string length in the hget header reading subroutines from 57600 to 256000 Replace oldsys with wcsproj in the WCS data structure so that more options are available, such as forcing use of AIPS or WCSLIB projection subroutines Add setdatedec() to set the number of decimal places in FITS date strings returned by dateutil subroutines Fix precession code to deal correctly with equinoxes other than J2000 and B1950. Move all date operations to dateutil.c, including current time used in imhfile.c February 23, 2000 - Release 2.7.0 Upgrade WCSLIB subroutines to WCSLIB 2.5 from 2.4 Add MJD and Besselian and Julian epoch conversion to dateutil.c Use WCSLIB CAR, COE, NCP projections if oldsys is 1, else use worldpos() Set CD matrix when using DSS projection Change oldwcs in wcs.h from switch to multi-value flag wcsproj, default is same Fix minor bug in fitsfile.c fitscimage error returns. ------------------------ January 11, 2000 - Release 2.6.12 Fix bug in dateutil() to get fractional year to date conversion right December 20, 1999 - Release 2.6.11 Fix bug in hgetdate() to get ISO minutes and seconds right Upgrade dateutil() to do many date conversions December 10, 1999 - Release 2.6.10 Fix bug which caused strings starting with d and e followed by numbers to be declared numeric even though they're not really numbers Fix bug in dateutil.c ts2jd() which does not affect SAOimage Fix bugs dealing with NOAO TNX projection November 17, 1999 - Release 2.6.9 Fix bug which caused loss of NCP projection November 5, 1999 - Release 2.6.8 Change release number to match WCSTools Clean up code in all subroutines using lint Add DATE-MOD to FITS header in iraf2fits() Added dateutil.c file for conversions between date formats (used by iraf2fits()) Return error code from hput*() subroutines if header buffer length exceeded. ------------------------ May 5, 1999 - Release 1.26 hget.c, iget.c Use POSIX-compliant limits.h instead of values.h April 7, 1999 - Release 1.26 wcs.c Fix bug in dealing with EPOCHless non-equatorial coordinates wcsinit.c Add optional filename to printed error messages April 5, 1999 - Release 1.26 hget.c Check all string lengths before copying; ignore ^M at 80th character February 22, 1999 - Release 1.26 wcs.c Fix bug dealing with SPA and NPA coordinates Use faaces 0-5, not 1-6 for quad cube projections wcsinit.c Fix computed rotation angle for DSS projection February 9, 1999 - Release 1.26 fitsfile.c: Allow BITPIX=0 dataless images wcsinit.c: Fix bug initializing DSS image rotation wcs.c: Free lin.imgpix and lin.piximg in wcsfree() hput.c: Fix bug to avoid writing HISTORY or COMMENT lines past 80 chars ------------------------ December 8, 1998 - Release 1.25 fitsfile.c: Fix bug in fitsrhead() reading FITS table files caused by fix below November 30, 1998 - Release 1.25 fitsfile.c: Fix bug dealing with very large headers in fitsrhead() November 12, 1998 - Release 1.25 dsspos.c: Fix possible divide by zero problems fitsfile.c: Add isfits() which checks filename or first line of header imhfile.c: Add isiraf() which checks filename for .imh hget.c: Assume 2-digit year in hyphen-separated date means FITS, not ISO tnxpos.c: Fix multiple bugs wcscon.c: Add wcscstr() to get coordinate system as a character string wcscon.c: Add subroutine wcsconp() to convert coordinates + proper motions wcs.c: Add North and South Polar Angle coordinate systems wcs.c: Build WCS command initialization by getenv() into wcs*init() wcs.c: Fix bug in wcssize(); fix bug with rotated mirrored images wcslib.h: Add cel.h, lin.h, proj.h, and wcstrig.h to wcslib.h worldpos.c: Fix bug in inverse (sky to pixel) COE projection cel.c, lin.c, proj.c, sph.c, wcstrig.c: Include only wcslib.h astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/hget.c0000664000175000017500000014222313047255533020560 0ustar mattymatty00000000000000/*** File libwcs/hget.c *** May 19, 2011 *** By Jessica Mink, jmink@cfa.harvard.edu *** Harvard-Smithsonian Center for Astrophysics *** Copyright (C) 1994-2011 *** Smithsonian Astrophysical Observatory, Cambridge, MA, USA This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Correspondence concerning WCSTools should be addressed as follows: Internet email: jmink@cfa.harvard.edu Postal address: Jessica Mink Smithsonian Astrophysical Observatory 60 Garden St. Cambridge, MA 02138 USA * Module: hget.c (Get FITS Header parameter values) * Purpose: Extract values for variables from FITS header string * Subroutine: hgeti2 (hstring,keyword,ival) returns short integer * Subroutine: hgeti4c (hstring,keyword,wchar,ival) returns long integer * Subroutine: hgeti4 (hstring,keyword,ival) returns long integer * Subroutine: hgetr4 (hstring,keyword,rval) returns real * Subroutine: hgetra (hstring,keyword,ra) returns double RA in degrees * Subroutine: hgetdec (hstring,keyword,dec) returns double Dec in degrees * Subroutine: hgetr8c (hstring,keyword,wchar,dval) returns double * Subroutine: hgetr8 (hstring,keyword,dval) returns double * Subroutine: hgetl (hstring,keyword,lval) returns logical int (0=F, 1=T) * Subroutine: hgetsc (hstring,keyword,wchar,lstr,str) returns character string * Subroutine: hgets (hstring,keyword, lstr, str) returns character string * Subroutine: hgetm (hstring,keyword, lstr, str) returns multi-keyword string * Subroutine: hgetdate (hstring,keyword,date) returns date as fractional year * Subroutine: hgetndec (hstring, keyword, ndec) returns number of dec. places * Subroutine: hgetc (hstring,keyword) returns character string * Subroutine: blsearch (hstring,keyword) returns pointer to blank lines before keyword * Subroutine: ksearch (hstring,keyword) returns pointer to header string entry * Subroutine: str2ra (in) converts string to right ascension in degrees * Subroutine: str2dec (in) converts string to declination in degrees * Subroutine: strsrch (s1, s2) finds string s2 in null-terminated string s1 * Subroutine: strnsrch (s1, s2, ls1) finds string s2 in ls1-byte string s1 * Subroutine: hlength (header,lhead) sets length of FITS header for searching * Subroutine: isnum (string) returns 1 if integer, 2 if fp number, else 0 * Subroutine: notnum (string) returns 0 if number, else 1 * Subroutine: numdec (string) returns number of decimal places in numeric string * Subroutine: strfix (string,blankfill,zerodrop) removes extraneous characters */ #include /* NULL, strlen, strstr, strcpy */ #include #include "fitshead.h" /* FITS header extraction subroutines */ #include #ifndef VMS #include #else #define INT_MAX 2147483647 /* Biggest number that can fit in long */ #define SHRT_MAX 32767 #endif #define VLENGTH 81 #ifdef USE_SAOLIB static int use_saolib=0; #endif char *hgetc (); static char val[VLENGTH+1]; static int multiline = 0; static int lhead0 = 0; /* Length of header string */ /* Set the length of the header string, if not terminated by NULL */ int hlength (header, lhead) const char *header; /* FITS header */ int lhead; /* Maximum length of FITS header */ { char *hend; if (lhead > 0) lhead0 = lhead; else { lhead0 = 0; hend = ksearch (header,"END"); lhead0 = hend + 80 - header; } return (lhead0); } /* Return the length of the header string, computing it if lhead0 not set */ int gethlength (header) char *header; /* FITS header */ { if (lhead0 > 0) return (lhead0); else return (hlength (header, 0)); } /* Extract Integer*4 value for variable from FITS header string */ int hgeti4c (hstring,keyword,wchar,ival) const char *hstring; /* character string containing FITS header information in the format = {/ } */ const char *keyword; /* character string containing the name of the keyword the value of which is returned. hget searches for a line beginning with this string. if "[n]" is present, the n'th token in the value is returned. (the first 8 characters must be unique) */ const char *wchar; /* Character of multiple WCS header; =0 if unused */ int *ival; /* Keyword value returned */ { char keyword1[16]; int lkey; if (wchar[0] < (char) 64) return (hgeti4 (hstring, keyword, ival)); else { strcpy (keyword1, keyword); lkey = strlen (keyword); keyword1[lkey] = wchar[0]; keyword1[lkey+1] = (char) 0; return (hgeti4 (hstring, keyword1, ival)); } } /* Extract long value for variable from FITS header string */ int hgeti4 (hstring,keyword,ival) const char *hstring; /* character string containing FITS header information in the format = {/ } */ const char *keyword; /* character string containing the name of the keyword the value of which is returned. hget searches for a line beginning with this string. if "[n]" is present, the n'th token in the value is returned. (the first 8 characters must be unique) */ int *ival; { char *value; double dval; int minint; int lval; char *dchar; /* Get value and comment from header string */ value = hgetc (hstring,keyword); /* Translate value from ASCII to binary */ if (value != NULL) { if (value[0] == '#') value++; minint = -INT_MAX - 1; lval = strlen (value); if (lval > VLENGTH) { strncpy (val, value, VLENGTH); val[VLENGTH] = (char) 0; } else strcpy (val, value); if (isnum (val) == 2) { if ((dchar = strchr (val, 'D'))) *dchar = 'e'; if ((dchar = strchr (val, 'd'))) *dchar = 'e'; if ((dchar = strchr (val, 'E'))) *dchar = 'e'; } dval = atof (val); if (dval+0.001 > INT_MAX) *ival = INT_MAX; else if (dval >= 0) *ival = (int) (dval + 0.001); else if (dval-0.001 < minint) *ival = minint; else *ival = (int) (dval - 0.001); return (1); } else { return (0); } } /* Extract integer*2 value for variable from fits header string */ int hgeti2 (hstring,keyword,ival) const char *hstring; /* character string containing FITS header information in the format = {/ } */ const char *keyword; /* character string containing the name of the keyword the value of which is returned. hget searches for a line beginning with this string. if "[n]" is present, the n'th token in the value is returned. (the first 8 characters must be unique) */ short *ival; { char *value; double dval; int minshort; int lval; char *dchar; /* Get value and comment from header string */ value = hgetc (hstring,keyword); /* Translate value from ASCII to binary */ if (value != NULL) { if (value[0] == '#') value++; lval = strlen (value); if (lval > VLENGTH) { strncpy (val, value, VLENGTH); val[VLENGTH] = (char) 0; } else strcpy (val, value); if (isnum (val) == 2) { if ((dchar = strchr (val, 'D'))) *dchar = 'e'; if ((dchar = strchr (val, 'd'))) *dchar = 'e'; if ((dchar = strchr (val, 'E'))) *dchar = 'e'; } dval = atof (val); minshort = -SHRT_MAX - 1; if (dval+0.001 > SHRT_MAX) *ival = SHRT_MAX; else if (dval >= 0) *ival = (short) (dval + 0.001); else if (dval-0.001 < minshort) *ival = minshort; else *ival = (short) (dval - 0.001); return (1); } else { return (0); } } /* Extract real value for variable from FITS header string */ int hgetr4 (hstring,keyword,rval) const char *hstring; /* character string containing FITS header information in the format = {/ } */ const char *keyword; /* character string containing the name of the keyword the value of which is returned. hget searches for a line beginning with this string. if "[n]" is present, the n'th token in the value is returned. (the first 8 characters must be unique) */ float *rval; { char *value; int lval; char *dchar; /* Get value and comment from header string */ value = hgetc (hstring,keyword); /* translate value from ASCII to binary */ if (value != NULL) { if (value[0] == '#') value++; lval = strlen (value); if (lval > VLENGTH) { strncpy (val, value, VLENGTH); val[VLENGTH] = (char) 0; } else strcpy (val, value); if (isnum (val) == 2) { if ((dchar = strchr (val, 'D'))) *dchar = 'e'; if ((dchar = strchr (val, 'd'))) *dchar = 'e'; if ((dchar = strchr (val, 'E'))) *dchar = 'e'; } *rval = (float) atof (val); return (1); } else { return (0); } } /* Extract real*8 right ascension in degrees from FITS header string */ int hgetra (hstring,keyword,dval) const char *hstring; /* character string containing FITS header information in the format = {/ } */ const char *keyword; /* character string containing the name of the keyword the value of which is returned. hget searches for a line beginning with this string. if "[n]" is present, the n'th token in the value is returned. (the first 8 characters must be unique) */ double *dval; /* Right ascension in degrees (returned) */ { char *value; /* Get value from header string */ value = hgetc (hstring,keyword); /* Translate value from ASCII colon-delimited string to binary */ if (value != NULL) { *dval = str2ra (value); return (1); } else return (0); } /* Extract real*8 declination in degrees from FITS header string */ int hgetdec (hstring,keyword,dval) const char *hstring; /* character string containing FITS header information in the format = {/ } */ const char *keyword; /* character string containing the name of the keyword the value of which is returned. hget searches for a line beginning with this string. if "[n]" is present, the n'th token in the value is returned. (the first 8 characters must be unique) */ double *dval; /* Right ascension in degrees (returned) */ { char *value; /* Get value from header string */ value = hgetc (hstring,keyword); /* Translate value from ASCII colon-delimited string to binary */ if (value != NULL) { *dval = str2dec (value); return (1); } else return (0); } /* Extract real*8 value for variable from FITS header string */ int hgetr8c (hstring,keyword,wchar,dval) const char *hstring; /* character string containing FITS header information in the format = {/ } */ const char *keyword; /* character string containing the name of the keyword the value of which is returned. hget searches for a line beginning with this string. if "[n]" is present, the n'th token in the value is returned. (the first 8 characters must be unique) */ const char *wchar; /* Character of multiple WCS header; =0 if unused */ double *dval; /* Keyword value returned */ { char keyword1[16]; int lkey; if (wchar[0] < (char) 64) return (hgetr8 (hstring, keyword, dval)); else { strcpy (keyword1, keyword); lkey = strlen (keyword); keyword1[lkey] = wchar[0]; keyword1[lkey+1] = (char) 0; return (hgetr8 (hstring, keyword1, dval)); } } /* Extract real*8 value for variable from FITS header string */ int hgetr8 (hstring,keyword,dval) const char *hstring; /* character string containing FITS header information in the format = {/ } */ const char *keyword; /* character string containing the name of the keyword the value of which is returned. hget searches for a line beginning with this string. if "[n]" is present, the n'th token in the value is returned. (the first 8 characters must be unique) */ double *dval; { char *value; int lval; char *dchar; /* Get value and comment from header string */ value = hgetc (hstring,keyword); /* Translate value from ASCII to binary */ if (value != NULL) { if (value[0] == '#') value++; lval = strlen (value); if (lval > VLENGTH) { strncpy (val, value, VLENGTH); val[VLENGTH] = (char) 0; } else strcpy (val, value); if (isnum (val) == 2) { if ((dchar = strchr (val, 'D'))) *dchar = 'e'; if ((dchar = strchr (val, 'd'))) *dchar = 'e'; if ((dchar = strchr (val, 'E'))) *dchar = 'e'; } *dval = atof (val); return (1); } else { return (0); } } /* Extract logical value for variable from FITS header string */ int hgetl (hstring,keyword,ival) const char *hstring; /* character string containing FITS header information in the format = {/ } */ const char *keyword; /* character string containing the name of the keyword the value of which is returned. hget searches for a line beginning with this string. if "[n]" is present, the n'th token in the value is returned. (the first 8 characters must be unique) */ int *ival; { char *value; char newval; int lval; /* Get value and comment from header string */ value = hgetc (hstring,keyword); /* Translate value from ASCII to binary */ if (value != NULL) { lval = strlen (value); if (lval > VLENGTH) { strncpy (val, value, VLENGTH); val[VLENGTH] = (char) 0; } else strcpy (val, value); newval = val[0]; if (newval == 't' || newval == 'T') *ival = 1; else *ival = 0; return (1); } else { return (0); } } /* Extract real*8 date from FITS header string (dd/mm/yy or dd-mm-yy) */ int hgetdate (hstring,keyword,dval) const char *hstring; /* character string containing FITS header information in the format = {/ } */ const char *keyword; /* character string containing the name of the keyword the value of which is returned. hget searches for a line beginning with this string. if "[n]" is present, the n'th token in the value is returned. (the first 8 characters must be unique) */ double *dval; { double yeardays, seconds, fday; char *value,*sstr, *dstr, *tstr, *cstr, *nval; int year, month, day, yday, i, hours, minutes; static int mday[12] = {31,28,31,30,31,30,31,31,30,31,30,31}; /* Get value and comment from header string */ value = hgetc (hstring,keyword); /* Translate value from ASCII to binary */ if (value != NULL) { sstr = strchr (value,'/'); dstr = strchr (value,'-'); /* Original FITS date format: dd/mm/yy */ if (sstr > value) { *sstr = '\0'; day = (int) atof (value); *sstr = '/'; nval = sstr + 1; sstr = strchr (nval,'/'); if (sstr == NULL) sstr = strchr (nval,'-'); if (sstr > value) { *sstr = '\0'; month = (int) atof (nval); *sstr = '/'; nval = sstr + 1; year = (int) atof (nval); if (day > 31) { yday = year; year = day; day = yday; } if (year >= 0 && year <= 49) year = year + 2000; else if (year < 100) year = year + 1900; if ((year % 4) == 0) mday[1] = 29; else mday[1] = 28; if ((year % 100) == 0 && (year % 400) != 0) mday[1] = 28; if (day > mday[month-1]) day = mday[month-1]; else if (day < 1) day = 1; if (mday[1] == 28) yeardays = 365.0; else yeardays = 366.0; yday = day - 1; for (i = 0; i < month-1; i++) yday = yday + mday[i]; *dval = (double) year + ((double)yday / yeardays); return (1); } else return (0); } /* New FITS date format: yyyy-mm-ddThh:mm:ss[.sss] */ else if (dstr > value) { *dstr = '\0'; year = (int) atof (value); *dstr = '-'; nval = dstr + 1; dstr = strchr (nval,'-'); month = 1; day = 1; tstr = NULL; if (dstr > value) { *dstr = '\0'; month = (int) atof (nval); *dstr = '-'; nval = dstr + 1; tstr = strchr (nval,'T'); if (tstr > value) *tstr = '\0'; day = (int) atof (nval); if (tstr > value) *tstr = 'T'; } /* If year is < 32, it is really day of month in old format */ if (year < 32) { i = year; year = day + 1900; day = i; } if ((year % 4) == 0) mday[1] = 29; else mday[1] = 28; if ((year % 100) == 0 && (year % 400) != 0) mday[1] = 28; if (day > mday[month-1]) day = mday[month-1]; else if (day < 1) day = 1; if (mday[1] == 28) yeardays = 365.0; else yeardays = 366.0; yday = day - 1; for (i = 0; i < month-1; i++) yday = yday + mday[i]; *dval = (double) year + ((double)yday / yeardays); /* Extract time, if it is present */ if (tstr > value) { nval = tstr + 1; hours = 0.0; minutes = 0.0; seconds = 0.0; cstr = strchr (nval,':'); if (cstr > value) { *cstr = '\0'; hours = (int) atof (nval); *cstr = ':'; nval = cstr + 1; cstr = strchr (nval,':'); if (cstr > value) { *cstr = '\0'; minutes = (int) atof (nval); *cstr = ':'; nval = cstr + 1; seconds = atof (nval); } else { minutes = (int) atof (nval); seconds = 0.0; } } fday = ((3.6e3 * (double)hours) + (6.e1 * (double)minutes) + seconds) / 8.64e4; *dval = *dval + (fday / yeardays); } return (1); } else return (0); } else return (0); } /* Extract IRAF multiple-keyword string value from FITS header string */ int hgetm (hstring, keyword, lstr, str) const char *hstring; /* character string containing FITS header information in the format = {/ } */ const char *keyword; /* character string containing the root name of the keyword the value of which is returned. hget searches for a line beginning with this string. if "[n]" is present, the n'th token in the value is returned. (the first 8 characters must be unique) */ const int lstr; /* Size of str in characters */ char *str; /* String (returned) */ { char *value; char *stri; char keywordi[16]; int lval, lstri, ikey; char keyform[8]; stri = str; lstri = lstr; sprintf (keywordi, "%s_1", keyword); if (ksearch (hstring, keywordi)) strcpy (keyform, "%s_%d"); else { sprintf (keywordi, "%s_01", keyword); if (ksearch (hstring, keywordi)) strcpy (keyform, "%s_%02d"); else { sprintf (keywordi, "%s_001", keyword); if (ksearch (hstring, keywordi)) strcpy (keyform, "%s_%03d"); else if (ksearch (hstring, keywordi)) strcpy (keyform, "%s_%03d"); else return (0); } } /* Loop through sequentially-named keywords */ multiline = 1; for (ikey = 1; ikey < 500; ikey++) { sprintf (keywordi, keyform, keyword, ikey); /* Get value for this keyword */ value = hgetc (hstring, keywordi); if (value != NULL) { lval = strlen (value); if (lval < lstri) strcpy (stri, value); else if (lstri > 1) { strncpy (stri, value, lstri-1); stri[lstri] = (char) 0; break; } else { str[0] = value[0]; break; } } else break; stri = stri + lval; lstri = lstri - lval; } multiline = 0; /* Return 1 if any keyword found, else 0 */ if (ikey > 1) return (1); else return (0); } /* Extract string value for variable from FITS header string */ int hgetsc (hstring,keyword,wchar,lstr,str) const char *hstring; /* character string containing FITS header information in the format = {/ } */ const char *keyword; /* character string containing the name of the keyword the value of which is returned. hget searches for a line beginning with this string. if "[n]" is present, the n'th token in the value is returned. (the first 8 characters must be unique) */ const char *wchar; /* Character of multiple WCS header; =0 if unused */ const int lstr; /* Size of str in characters */ char *str; /* String (returned) */ { char keyword1[16]; int lkey; if (wchar[0] < (char) 64) return (hgets (hstring, keyword, lstr, str)); else { strcpy (keyword1, keyword); lkey = strlen (keyword); keyword1[lkey] = wchar[0]; keyword1[lkey+1] = (char) 0; return (hgets (hstring, keyword1, lstr, str)); } } /* Extract string value for variable from FITS header string */ int hgets (hstring, keyword, lstr, str) const char *hstring; /* character string containing FITS header information in the format = {/ } */ const char *keyword; /* character string containing the name of the keyword the value of which is returned. hget searches for a line beginning with this string. if "[n]" is present, the n'th token in the value is returned. (the first 8 characters must be unique) */ const int lstr; /* Size of str in characters */ char *str; /* String (returned) */ { char *value; int lval; /* Get value and comment from header string */ value = hgetc (hstring,keyword); if (value != NULL) { lval = strlen (value); if (lval < lstr) strcpy (str, value); else if (lstr > 1) strncpy (str, value, lstr-1); else str[0] = value[0]; return (1); } else return (0); } /* Extract number of decimal places for value in FITS header string */ int hgetndec (hstring, keyword, ndec) const char *hstring; /* character string containing FITS header information in the format = {/ } */ const char *keyword; /* character string containing the name of the keyword the value of which is returned. hget searches for a line beginning with this string. if "[n]" is present, the n'th token in the value is returned. (the first 8 characters must be unique) */ int *ndec; /* Number of decimal places in keyword value */ { char *value; int i, nchar; /* Get value and comment from header string */ value = hgetc (hstring,keyword); /* Find end of string and count backward to decimal point */ *ndec = 0; if (value != NULL) { nchar = strlen (value); for (i = nchar-1; i >= 0; i--) { if (value[i] == '.') return (1); *ndec = *ndec + 1; } return (1); } else return (0); } /* Extract character value for variable from FITS header string */ char * hgetc (hstring,keyword0) const char *hstring; /* character string containing FITS header information in the format = {/ } */ const char *keyword0; /* character string containing the name of the keyword the value of which is returned. hget searches for a line beginning with this string. if "[n]" is present, the n'th token in the value is returned. (the first 8 characters must be unique) */ { static char cval[80]; char *value; char cwhite[2]; char squot[2], dquot[2], lbracket[2], rbracket[2], slash[2], comma[2]; char space; char keyword[81]; /* large for ESO hierarchical keywords */ char line[100]; char *vpos, *cpar; char *q1, *q2, *v1, *v2, *c1, *brack1, *brack2; int ipar, i, lkey; #ifdef USE_SAOLIB int iel=1, ip=1, nel, np, ier; char *get_fits_head_str(); if( !use_saolib ){ #endif squot[0] = (char) 39; squot[1] = (char) 0; dquot[0] = (char) 34; dquot[1] = (char) 0; lbracket[0] = (char) 91; lbracket[1] = (char) 0; comma[0] = (char) 44; comma[1] = (char) 0; rbracket[0] = (char) 93; rbracket[1] = (char) 0; slash[0] = (char) 47; slash[1] = (char) 0; space = (char) 32; /* Find length of variable name */ strncpy (keyword,keyword0, sizeof(keyword)-1); brack1 = strsrch (keyword,lbracket); if (brack1 == NULL) brack1 = strsrch (keyword,comma); if (brack1 != NULL) { *brack1 = '\0'; brack1++; } /* Search header string for variable name */ vpos = ksearch (hstring,keyword); /* Exit if not found */ if (vpos == NULL) return (NULL); /* Initialize line to nulls */ for (i = 0; i < 100; i++) line[i] = 0; /* In standard FITS, data lasts until 80th character */ /* Extract entry for this variable from the header */ strncpy (line,vpos,80); /* Check for quoted value */ q1 = strsrch (line,squot); c1 = strsrch (line,slash); if (q1 != NULL) { if (c1 != NULL && q1 < c1) { q2 = strsrch (q1+1,squot); if (q2 == NULL) { q2 = c1 - 1; while (*q2 == space) q2--; q2++; } else if (c1 < q2) c1 = strsrch (q2,slash); } else if (c1 == NULL) { q2 = strsrch (q1+1,squot); if (q2 == NULL) { q2 = line + 79; while (*q2 == space) q2--; q2++; } } else q1 = NULL; } else { q1 = strsrch (line,dquot); if (q1 != NULL) { if (c1 != NULL && q1 < c1) { q2 = strsrch (q1+1,dquot); if (q2 == NULL) { q2 = c1 - 1; while (*q2 == space) q2--; q2++; } else if (c1 < q2) c1 = strsrch (q2,slash); } else if (c1 == NULL) { q2 = strsrch (q1+1,dquot); if (q2 == NULL) { q2 = line + 79; while (*q2 == space) q2--; q2++; } } else q1 = NULL; } else { q1 = NULL; q2 = line + 10; } } /* Extract value and remove excess spaces */ if (q1 != NULL) { v1 = q1 + 1; v2 = q2; } else { v1 = strsrch (line,"="); if (v1 == NULL) v1 = line + 9; else v1 = v1 + 1; c1 = strsrch (line,"/"); if (c1 != NULL) v2 = c1; else v2 = line + 79; } /* Ignore leading spaces if not multiline */ if (!multiline) { while (*v1 == ' ' && v1 < v2) { v1++; } } /* Drop trailing spaces */ *v2 = '\0'; if (!multiline) { v2--; while ((*v2 == ' ' || *v2 == (char) 13) && v2 > v1) { *v2 = '\0'; v2--; } } /* Convert -zero to just plain 0 */ if (!strcmp (v1, "-0")) v1++; strcpy (cval,v1); value = cval; /* If keyword has brackets, extract appropriate token from value */ if (brack1 != NULL) { brack2 = strsrch (brack1,rbracket); if (brack2 != NULL) *brack2 = '\0'; if (isnum (brack1)) { ipar = atoi (brack1); cwhite[0] = ' '; cwhite[1] = '\0'; if (ipar > 0) { for (i = 1; i <= ipar; i++) { cpar = strtok (v1,cwhite); v1 = NULL; } if (cpar != NULL) { strcpy (cval,cpar); value = cval; } else value = NULL; } /* If token counter is negative, include rest of value */ else if (ipar < 0) { for (i = 1; i < -ipar; i++) { v1 = strchr (v1, ' '); if (v1 == NULL) break; else v1 = v1 + 1; } if (v1 != NULL) { strcpy (cval, v1); value = cval; } else value = NULL; } } else { lkey = strlen (brack1); for (i = 0; i < lkey; i++) { if (brack1[i] > 64 && brack1[i] < 91) brack1[i] = brack1[i] + 32; } v1 = igetc (cval, brack1); if (v1) { strcpy (cval,v1); value = cval; } else value = NULL; } } return (value); #ifdef USE_SAOLIB } else { return(get_fits_head_str(keyword0, iel, ip, &nel, &np, &ier, hstring)); } #endif } /* Find beginning of fillable blank line before FITS header keyword line */ char * blsearch (hstring,keyword) /* Find entry for keyword keyword in FITS header string hstring. (the keyword may have a maximum of eight letters) NULL is returned if the keyword is not found */ const char *hstring; /* character string containing fits-style header information in the format = {/ } the default is that each entry is 80 characters long; however, lines may be of arbitrary length terminated by nulls, carriage returns or linefeeds, if packed is true. */ const char *keyword; /* character string containing the name of the variable to be returned. ksearch searches for a line beginning with this string. The string may be a character literal or a character variable terminated by a null or '$'. it is truncated to 8 characters. */ { const char *headlast; char *loc, *headnext, *pval, *lc, *line; char *bval; int icol, nextchar, lkey, nleft, lhstr; pval = 0; /* Search header string for variable name */ if (lhead0) lhstr = lhead0; else { lhstr = 0; while (lhstr < 256000 && hstring[lhstr] != 0) lhstr++; } headlast = hstring + lhstr; headnext = (char *) hstring; pval = NULL; while (headnext < headlast) { nleft = headlast - headnext; loc = strncsrch (headnext, keyword, nleft); /* Exit if keyword is not found */ if (loc == NULL) { break; } icol = (loc - hstring) % 80; lkey = strlen (keyword); nextchar = (int) *(loc + lkey); /* If this is not in the first 8 characters of a line, keep searching */ if (icol > 7) headnext = loc + 1; /* If parameter name in header is longer, keep searching */ else if (nextchar != 61 && nextchar > 32 && nextchar < 127) headnext = loc + 1; /* If preceeding characters in line are not blanks, keep searching */ else { line = loc - icol; for (lc = line; lc < loc; lc++) { if (*lc != ' ') headnext = loc + 1; } /* Return pointer to start of line if match */ if (loc >= headnext) { pval = line; break; } } } /* Return NULL to calling program if keyword is not found */ if (pval == NULL) return (pval); /* Return NULL if keyword is found at start of FITS header string */ if (pval == hstring) return (NULL); /* Find last nonblank in FITS header string line before requested keyword */ bval = pval - 80; while (!strncmp (bval," ",8) && bval >= hstring) bval = bval - 80; bval = bval + 80; /* Return pointer to calling program if blank lines found */ if (bval < pval && bval >= hstring) return (bval); else return (NULL); } /* Find FITS header line containing specified keyword */ char * ksearch (hstring,keyword) /* Find entry for keyword keyword in FITS header string hstring. (the keyword may have a maximum of eight letters) NULL is returned if the keyword is not found */ const char *hstring; /* character string containing fits-style header information in the format = {/ } the default is that each entry is 80 characters long; however, lines may be of arbitrary length terminated by nulls, carriage returns or linefeeds, if packed is true. */ const char *keyword; /* character string containing the name of the variable to be returned. ksearch searches for a line beginning with this string. The string may be a character literal or a character variable terminated by a null or '$'. it is truncated to 8 characters. */ { const char *headlast; char *loc, *headnext, *pval, *lc, *line; int icol, nextchar, lkey, nleft, lhead, lmax; #ifdef USE_SAOLIB int iel=1, ip=1, nel, np, ier; char *get_fits_head_str(); if( !use_saolib ){ #endif pval = 0; /* Find current length of header string */ if (lhead0) lmax = lhead0; else lmax = 256000; for (lhead = 0; lhead < lmax; lhead++) { if (hstring[lhead] <= (char) 0) break; } /* Search header string for variable name */ headlast = hstring + lhead; headnext = (char *) hstring; pval = NULL; while (headnext < headlast) { nleft = headlast - headnext; loc = strncsrch (headnext, keyword, nleft); /* Exit if keyword is not found */ if (loc == NULL) { break; } icol = (loc - hstring) % 80; lkey = strlen (keyword); nextchar = (int) *(loc + lkey); /* If this is not in the first 8 characters of a line, keep searching */ if (icol > 7) headnext = loc + 1; /* If parameter name in header is longer, keep searching */ else if (nextchar != 61 && nextchar > 32 && nextchar < 127) headnext = loc + 1; /* If preceeding characters in line are not blanks, keep searching */ else { line = loc - icol; for (lc = line; lc < loc; lc++) { if (*lc != ' ') headnext = loc + 1; } /* Return pointer to start of line if match */ if (loc >= headnext) { pval = line; break; } } } /* Return pointer to calling program */ return (pval); #ifdef USE_SAOLIB } else { if (get_fits_head_str(keyword,iel,ip,&nel,&np,&ier,hstring) != NULL) return(hstring); else return(NULL); } #endif } /* Return the right ascension in degrees from sexagesimal hours or decimal degrees */ double str2ra (in) const char *in; /* Character string of sexigesimal hours or decimal degrees */ { double ra; /* Right ascension in degrees (returned) */ ra = str2dec (in); if (strsrch (in,":")) ra = ra * 15.0; return (ra); } /* Return the declination in degrees from sexagesimal or decimal degrees */ double str2dec (in) const char *in; /* Character string of sexigesimal or decimal degrees */ { double dec; /* Declination in degrees (returned) */ double deg, min, sec, sign; char *value, *c1, *c2; int lval; char *dchar; dec = 0.0; /* Return 0.0 if string is null */ if (in == NULL) return (dec); /* Translate value from ASCII colon-delimited string to binary */ if (in[0]) { value = (char *) in; /* Remove leading spaces */ while (*value == ' ') value++; /* Save sign */ if (*value == '-') { sign = -1.0; value++; } else if (*value == '+') { sign = 1.0; value++; } else sign = 1.0; /* Turn comma into space */ if ((c1 = strsrch (value,",")) != NULL) *c1 = ' '; /* Remove trailing spaces */ lval = strlen (value); while (value[lval-1] == ' ') lval--; if ((c1 = strsrch (value,":")) == NULL) c1 = strnsrch (value," ",lval); if (c1 != NULL) { *c1 = 0; deg = (double) atoi (value); *c1 = ':'; value = c1 + 1; if ((c2 = strsrch (value,":")) == NULL) c2 = strsrch (value," "); if (c2 != NULL) { *c2 = 0; min = (double) atoi (value); *c2 = ':'; value = c2 + 1; sec = atof (value); } else { sec = 0.0; if ((c1 = strsrch (value,".")) != NULL) min = atof (value); if (strlen (value) > 0) min = (double) atoi (value); } dec = sign * (deg + (min / 60.0) + (sec / 3600.0)); } else if (isnum (value) == 2) { if ((dchar = strchr (value, 'D'))) *dchar = 'e'; if ((dchar = strchr (value, 'd'))) *dchar = 'e'; if ((dchar = strchr (value, 'E'))) *dchar = 'e'; dec = sign * atof (value); } else dec = sign * (double) atoi (value); } return (dec); } /* Find string s2 within null-terminated string s1 */ char * strsrch (s1, s2) const char *s1; /* String to search */ const char *s2; /* String to look for */ { int ls1; ls1 = strlen (s1); return (strnsrch (s1, s2, ls1)); } /* Find string s2 within string s1 */ char * strnsrch (s1, s2, ls1) const char *s1; /* String to search */ const char *s2; /* String to look for */ const int ls1; /* Length of string being searched */ { char *s,*s1e; char cfirst,clast; int i,ls2; /* Return null string if either pointer is NULL */ if (s1 == NULL || s2 == NULL) return (NULL); /* A zero-length pattern is found in any string */ ls2 = strlen (s2); if (ls2 ==0) return ((char *) s1); /* Only a zero-length string can be found in a zero-length string */ if (ls1 ==0) return (NULL); cfirst = (char) s2[0]; clast = (char) s2[ls2-1]; s1e = (char *) s1 + (int) ls1 - ls2 + 1; s = (char *) s1; while (s < s1e) { /* Search for first character in pattern string */ if (*s == cfirst) { /* If single character search, return */ if (ls2 == 1) return (s); /* Search for last character in pattern string if first found */ if (s[ls2-1] == clast) { /* If two-character search, return */ if (ls2 == 2) return (s); /* If 3 or more characters, check for rest of search string */ i = 1; while (i < ls2 && s[i] == s2[i]) i++; /* If entire string matches, return */ if (i >= ls2) return (s); } } s++; } return (NULL); } /* Find string s2 within null-terminated string s1 (case-free search) */ char * strcsrch (s1, s2) const char *s1; /* String to search */ const char *s2; /* String to look for */ { int ls1; ls1 = strlen ((char *) s1); return (strncsrch (s1, s2, ls1)); } /* Find string s2 within string s1 (case-free search) */ char * strncsrch (s1, s2, ls1) const char *s1; /* String to search */ const char *s2; /* String to look for */ const int ls1; /* Length of string being searched */ { char *s,*s1e, sl, *os2; char cfirst,ocfirst; char clast = ' '; char oclast = ' '; int i,ls2; /* Return null string if either pointer is NULL */ if (s1 == NULL || s2 == NULL) return (NULL); /* A zero-length pattern is found in any string */ ls2 = strlen (s2); if (ls2 ==0) return ((char *) s1); /* Only a zero-length string can be found in a zero-length string */ os2 = NULL; if (ls1 ==0) return (NULL); /* For one or two characters, set opposite case first and last letters */ if (ls2 < 3) { cfirst = (char) s2[0]; if (cfirst > 96 && cfirst < 123) ocfirst = cfirst - 32; else if (cfirst > 64 && cfirst < 91) ocfirst = cfirst + 32; else ocfirst = cfirst; if (ls2 > 1) { clast = s2[1]; if (clast > 96 && clast < 123) oclast = clast - 32; else if (clast > 64 && clast < 91) oclast = clast + 32; else oclast = clast; } } /* Else duplicate string with opposite case letters for comparison */ else { os2 = (char *) calloc (ls2, 1); for (i = 0; i < ls2; i++) { if (s2[i] > 96 && s2[i] < 123) os2[i] = s2[i] - 32; else if (s2[i] > 64 && s2[i] < 91) os2[i] = s2[i] + 32; else os2[i] = s2[i]; } cfirst = s2[0]; ocfirst = os2[0]; clast = s2[ls2-1]; oclast = os2[ls2-1]; } /* Loop through input string, character by character */ s = (char *) s1; s1e = s + (int) ls1 - ls2 + 1; while (s < s1e) { /* Search for first character in pattern string */ if (*s == cfirst || *s == ocfirst) { /* If single character search, return */ if (ls2 == 1) { if (os2 != NULL) free (os2); return (s); } /* Search for last character in pattern string if first found */ sl = s[ls2-1]; if (sl == clast || sl == oclast) { /* If two-character search, return */ if (ls2 == 2) { if (os2 != NULL) free (os2); return (s); } /* If 3 or more characters, check for rest of search string */ i = 1; while (i < ls2 && (s[i] == (char) s2[i] || s[i] == os2[i])) i++; /* If entire string matches, return */ if (i >= ls2) { if (os2 != NULL) free (os2); return (s); } } } s++; } if (os2 != NULL) free (os2); return (NULL); } int notnum (string) const char *string; /* Character string */ { if (isnum (string)) return (0); else return (1); } /* ISNUM-- Return 1 if string is an integer number, 2 if floating point, 3 if sexigesimal, with or without decimal point else 0 */ int isnum (string) const char *string; /* Character string */ { int lstr, i, nd, cl; char cstr, cstr1; int fpcode; /* Return 0 if string is NULL */ if (string == NULL) return (0); lstr = strlen (string); nd = 0; cl = 0; fpcode = 1; /* Return 0 if string starts with a D or E */ cstr = string[0]; if (cstr == 'D' || cstr == 'd' || cstr == 'E' || cstr == 'e') { return (0); } /* Remove trailing spaces */ while (string[lstr-1] == ' ') lstr--; /* Numeric strings contain 0123456789-+ and d or e for exponents */ for (i = 0; i < lstr; i++) { cstr = string[i]; if (cstr == '\n') break; /* Ignore leading spaces */ if (cstr == ' ' && nd == 0) continue; if ((cstr < 48 || cstr > 57) && cstr != '+' && cstr != '-' && cstr != 'D' && cstr != 'd' && cstr != 'E' && cstr != 'e' && cstr != ':' && cstr != '.') return (0); else if (cstr == '+' || cstr == '-') { if (string[i+1] == '-' || string[i+1] == '+') return (0); else if (i > 0) { cstr1 = string[i-1]; if (cstr1 != 'D' && cstr1 != 'd' && cstr1 != 'E' && cstr1 != 'e' && cstr1 != ':' && cstr1 != ' ') return (0); } } else if (cstr >= 47 && cstr <= 57) nd++; /* Check for colon */ else if (cstr == 58) cl++; if (cstr=='.' || cstr=='d' || cstr=='e' || cstr=='d' || cstr=='e') fpcode = 2; } if (nd > 0) { if (cl) fpcode = 3; return (fpcode); } else return (0); } /* NUMDEC -- Return number of decimal places in numeric string (-1 if not number) */ int numdec (string) const char *string; /* Numeric string */ { char *cdot; int lstr; if (notnum (string) && !strchr (string, ':')) return (-1); else { lstr = strlen (string); if ((cdot = strchr (string, '.')) == NULL) return (0); else return (lstr - (cdot - string) - 1); } } #ifdef USE_SAOLIB int set_saolib(hstring) void *hstring; { if( *((int *)hstring) == 142857 ) use_saolib = 1; else use_saolib = 0; } #endif /* Remove exponent, leading #, surrounding parentheses, and/or trailing zeroes, if reasonable */ void strfix (string, fillblank, dropzero) char *string; /* String to modify */ int fillblank; /* If nonzero, fill blanks with underscores */ int dropzero; /* If nonzero, drop trailing zeroes */ { char *sdot, *s, *strend, *str, ctemp, *slast; int ndek, lstr, i; /* If number, ignore leading # and remove trailing non-numeric character */ if (string[0] == '#') { strend = string + strlen (string); str = string + 1; strend = str + strlen (str) - 1; ctemp = *strend; if (!isnum (strend)) *strend = (char) 0; if (isnum (str)) { strend = string + strlen (string); for (str = string; str < strend; str++) *str = *(str + 1); } else *strend = ctemp; } /* Remove parentheses if they enclose the string */ if (string[0] == '(') { lstr = strlen (string); if (string[lstr-1] == ')') { string[lstr-1] = (char) 0; strend = string + lstr - 1; for (str = string; str < strend; str++) *str = *(str+1); string[lstr-2] = (char) 0; } } /* Remove positive exponent if there are enough digits given */ if (isnum (string) > 1 && strsrch (string, "E+") != NULL) { lstr = strlen (string); ndek = (int) (string[lstr-1] - 48); ndek = ndek + (10 * ((int) (string[lstr-2] - 48))); if (ndek < lstr - 7) { lstr = lstr - 4; string[lstr] = (char) 0; string[lstr+1] = (char) 0; string[lstr+2] = (char) 0; string[lstr+3] = (char) 0; sdot = strchr (string, '.'); if (ndek > 0 && sdot != NULL) { for (i = 1; i <= ndek; i++) { *sdot = *(sdot+1); sdot++; *sdot = '.'; } } } } /* Remove trailing zeroes if they are not significant */ if (dropzero) { if (isnum (string) > 1 && strchr (string, '.') != NULL && strsrch (string, "E-") == NULL && strsrch (string, "E+") == NULL && strsrch (string, "e-") == NULL && strsrch (string, "e+") == NULL) { lstr = strlen (string); s = string + lstr - 1; while (*s == '0' && lstr > 1) { if (*(s - 1) != '.') { *s = (char) 0; lstr --; } s--; } } } /* Remove trailing decimal point */ lstr = strlen (string); s = string + lstr - 1; if (*s == '.') *s = (char) 0; /* Replace embedded blanks with underscores, if requested to */ if (fillblank) { lstr = strlen (string); slast = string + lstr; for (s = string; s < slast; s++) { if (*s == ' ') *s = '_'; } } return; } /* Oct 28 1994 New program * * Mar 1 1995 Search for / after second quote, not first one * May 2 1995 Initialize line in HGETC; deal with logicals in HGETL better * May 4 1995 Declare STRSRCH in KSEARCH * Aug 7 1995 Fix line initialization in HGETC * Dec 22 1995 Add HGETRA and HGETDEC to get degrees from xx:xx:xx.xxx string * * Jan 26 1996 Fix HGETL to not crash when parameter is not present * Feb 1 1996 Fix HGETC to deal with quotes correctly * Feb 1 1996 Fix HGETDEG to deal with sign correctly * Feb 6 1996 Add HGETS to update character strings * Feb 8 1996 Fix STRSRCH to find final characters in string * Feb 23 1996 Add string to degree conversions * Apr 26 1996 Add HGETDATE to get fractional year from date string * May 22 1996 Fix documentation; return double from STR2RA and STR2DEC * May 28 1996 Fix string translation of RA and Dec when no seconds * Jun 10 1996 Remove unused variables after running lint * Jun 17 1996 Fix bug which failed to return single character strings * Jul 1 1996 Skip sign when reading declination after testing for it * Jul 19 1996 Do not divide by 15 if RA header value is already in degrees * Aug 5 1996 Add STRNSRCH to search strings which are not null-terminated * Aug 6 1996 Make minor changes after lint * Aug 8 1996 Fix ksearch bug which finds wrong keywords * Aug 13 1996 Fix sign bug in STR2DEC for degrees * Aug 26 1996 Drop unused variables ICOL0, NLINE, PREVCHAR from KSEARCH * Sep 10 1996 Fix header length setting code * Oct 15 1996 Clean up loops and fix ICOL assignment * Nov 13 1996 Handle integer degrees correctly in STR2DEC * Nov 21 1996 Make changes for Linux thanks to Sidik Isani * Dec 12 1996 Add ISNUM to check to see whether strings are numbers * * Jan 22 1997 Add ifdefs for Eric Mandel (SAOtng) * Jan 27 1997 Convert to integer through ATOF so exponents are recognized * Jul 25 1997 Implement FITS version of ISO date format * * Feb 24 1998 Implement code to return IRAF multiple-keyword strings * Mar 12 1998 Add subroutine NOTNUM * Mar 27 1998 Add changes to match SKYCAT version * Apr 30 1998 Add BLSEARCH() to find blank lines before END * May 27 1998 Add HGETNDEC() to get number of decimal places in entry * Jun 1 1998 Add VMS patch from Harry Payne at StSci * Jun 18 1998 Fix code which extracts tokens from string values * Jul 21 1998 Drop minus sign for values of -0 * Sep 29 1998 Treat hyphen-separated date as old format if 2-digit year * Oct 7 1998 Clean up search for last blank line * * Apr 5 1999 Check lengths of strings before copying them * May 5 1999 values.h -> POSIX limits.h: MAXINT->INT_MAX, MAXSHORT->SHRT_MAX * Jul 15 1999 Add hgetm() options of 1- or 2-digit keyword extensions * Oct 6 1999 Add gethlength() to return header length * Oct 14 1999 In ksearch(), search only to null not to end of buffer * Oct 15 1999 Return 1 from hgetndec() if successful * Oct 20 1999 Drop unused variable after lint (val in hgetndec) * Dec 3 1999 Fix isnum() to reject strings starting with a d or e * Dec 20 1999 Update hgetdate() to get minutes and seconds right * * Feb 10 2000 Parse RA and Dec with spaces as well as colons as separators * Feb 11 2000 Add null at end of multi-line keyword value character string * Feb 25 2000 Change max search string length from 57600 to 256000 * Mar 15 2000 Deal with missing second quotes in string values * Mar 17 2000 Return 2 from isnum() if number is floating point (.de) * Mar 17 2000 Ignore leading # for numeric values in header * Mar 21 2000 Implement -n to get string value starting with nth token * Apr 5 2000 Reject +- in isnum() * Jun 9 2000 Read keyword values even if no equal sign is present * Sep 20 2000 Ignore linefeed at end of number in isnum() * Oct 23 2000 Fix handling of embedded + or - in isnum() * * Jan 19 2000 Return 0 from isnum(), str2ra(), and str2dec() if string is null * Mar 30 2001 Fix header length finding algorithm in ksearch() * Jul 13 2001 Make val[] static int instead of int; drop unused variables * Sep 12 2001 Read yyyy/mm/dd dates as well as dd/mm/yyyy * Sep 20 2001 Ignore leading spaces in str2dec() * Sep 20 2001 Ignore trailing spaces in isnum() * * Apr 3 2002 Add hgetr8c(), hgeti4c(), and hgetsc() for multiple WCS handling * Apr 26 2002 Fix bug in hgetsc(), hgeti4c(), and hgetr8c() found by Bill Joye * Jun 26 2002 Do not drop leading or trailing spaces in multi-line values * Aug 6 2002 Add strcsrch() and strncsrch() for case-insensitive searches * Aug 30 2002 Fix bug so strcsrch() really is case-insensitive * Oct 20 2003 Add numdec() to return number of decimal places in a string * Dec 9 2003 Fix numdec() to return 0 if no digits after decimal point * * Feb 26 2004 Extract value from keyword=value strings within a keyword value * Apr 9 2004 Use strncsrch() in ksearch() to find differently-cased keywords * Apr 28 2004 Free os2 in strncsrch() only if it is allocated * Jul 13 2004 Accept D, d, E, or e as exponent delimiter in floating points * Aug 30 2004 Change numdec() to accept sexigesimal numbers (:'s) * * Jun 27 2005 Drop unused variables * Aug 30 2005 Adjust code in hlength() * * Jun 20 2006 Initialize uninitialized variables in strnsrch() * Jun 29 2006 Add new subroutine strfix() to clean strings for other uses * Jul 13 2006 Increase maximum number of multiline keywords from 20 to 500 * * Jan 4 2007 Declare header, keyword to be const * Jan 4 2007 Change WCS letter from char to char* * Feb 28 2007 If header length is not set in hlength, set it to 0 * May 31 2007 Add return value of 3 to isnum() if string has colon(s) * Aug 22 2007 If closing quote not found, make one up * * Nov 12 2009 In strfix(), if drop enclosing parantheses * * Apr 19 2011 In str2dec(), change comma to space * May 19 2011 In strncsrch() always free allocated memory before returning */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/zpxpos.c0000664000175000017500000004363313047255533021201 0ustar mattymatty00000000000000/*** File wcslib/zpxpos.c *** October 31, 2012 *** By Frank Valdes, valdes@noao.edu *** Modified from tnxpos.c by Jessica Mink, jmink@cfa.harvard.edu *** Harvard-Smithsonian Center for Astrophysics *** After IRAF mwcs/wfzpx.x *** Copyright (C) 1998-2012 *** Smithsonian Astrophysical Observatory, Cambridge, MA, USA This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Correspondence concerning WCSTools should be addressed as follows: Internet email: jmink@cfa.harvard.edu Postal address: Jessica Mink Smithsonian Astrophysical Observatory 60 Garden St. Cambridge, MA 02138 USA */ #include #include #include #include #include "wcs.h" #define TOL 1e-13 #define SPHTOL 0.00001 #define BADCVAL 0.0 #define MAX(a,b) (((a) > (b)) ? (a) : (b)) #define MIN(a,b) (((a) < (b)) ? (a) : (b)) /* wfzpx -- wcs function driver for the zenithal / azimuthal polynomial. * zpxinit (header, wcs) * zpxclose (wcs) * zpxfwd (xpix, ypix, wcs, xpos, ypos) Pixels to WCS * zpxrev (xpos, ypos, wcs, xpix, ypix) WCS to pixels */ #define max_niter 500 #define SZ_ATSTRING 2000 static void wf_gsclose(); /* zpxinit -- initialize the zenithal/azimuthal polynomial forward or * inverse transform. initialization for this transformation consists of, * determining which axis is ra / lon and which is dec / lat, computing the * celestial longitude and colatitude of the native pole, reading in the the * native longitude of the pole of the celestial coordinate system longpole * from the attribute list, precomputing the euler angles and various * intermediary functions of the reference coordinates, reading in the * projection parameter ro from the attribute list, reading in up to ten * polynomial coefficients, and, for polynomial orders greater than 2 computing * the colatitude and radius of the first point of inflection. if longpole is * undefined then a value of 180.0 degrees is assumed. if ro is undefined a * value of 180.0 / pi is assumed. if the polynomial coefficients are all zero * then an error condition is posted. if the order of the polynomial is 2 or * greater and there is no point of inflection an error condition is posted. * the zpx projection with an order of 1 and 0th and 1st coefficients of 0.0 * and 1.0 respectively is equivalent to the arc projtection. in order to * determine the axis order, the parameter "axtype={ra|dec} {xlon|xlat}" must * have been set in the attribute list for the function. the longpole and ro * parameters may be set in either or both of the axes attribute lists, but the * value in the ra axis attribute list takes precedence. */ int zpxinit (header, wcs) const char *header; /* FITS header */ struct WorldCoor *wcs; /* pointer to WCS structure */ { int i, j; struct IRAFsurface *wf_gsopen(); char key[8], *str1, *str2, *lngstr, *latstr, *header1; double zd1, d1, zd2,d2, zd, d, r; extern void wcsrotset(); /* allocate space for the attribute strings */ str1 = malloc (SZ_ATSTRING); str2 = malloc (SZ_ATSTRING); if (!hgetm (header, "WAT1", SZ_ATSTRING, str1)) { /* this is a kludge to handle NOAO archived data where the first * WAT cards are in the primary header and this code does not * implement the inheritance convention. since zpx is largely an * NOAO system and it doesn't make sense for WAT1 to be missing if * ctype is ZPX, this block is only triggered with this kludge. * there had to be a few changes to defeat the caching of the * index of the header string so that the added cards are also * found. */ header1 = malloc (strlen(header)+200); strcpy (header1, "WAT1_001= 'wtype=zpx axtype=ra projp0=0. projp1=1. projp2=0. projp3=337.74 proj'WAT2_001= 'wtype=zpx axtype=dec projp0=0. projp1=1. projp2=0. projp3=337.74 pro'"); strcat (header1, header); hgetm (header1, "WAT1", SZ_ATSTRING, str1); hgetm (header1, "WAT2", SZ_ATSTRING, str2); free (header1); } hgetm (header, "WAT2", SZ_ATSTRING, str2); lngstr = malloc (SZ_ATSTRING); latstr = malloc (SZ_ATSTRING); /* determine the native longitude of the pole of the celestial coordinate system corresponding to the FITS keyword longpole. this number has no default and should normally be set to 180 degrees. search both axes for this quantity. */ if (wcs->longpole > 360.0) { if (!igetr8 (str1, "longpole", &wcs->longpole)) { if (!igetr8 (str2, "longpole", &wcs->longpole)) wcs->longpole = 180.0; } } /* Fetch the ro projection parameter which is the radius of the generating sphere for the projection. if ro is absent which is the usual case set it to 180 / pi. search both axes for this quantity. */ if (!igetr8 (str1, "ro", &wcs->rodeg)) { if (!igetr8 (str2, "ro", &wcs->rodeg)) wcs->rodeg = 180.0 / PI; } /* Fetch the zenithal polynomial coefficients. */ for (i = 0; i < 10; i++) { sprintf (key,"projp%d",i); if (!igetr8 (str1, key, &wcs->prj.p[i])) wcs->prj.p[i] = 0.0; } /* Fetch the longitude correction surface. note that the attribute string may be of any length so the length of atvalue may have to be adjusted. */ if (!igets (str1, "lngcor", SZ_ATSTRING, lngstr)) { if (!igets (str2, "lngcor", SZ_ATSTRING, lngstr)) wcs->lngcor = NULL; else wcs->lngcor = wf_gsopen (lngstr); } else wcs->lngcor = wf_gsopen (lngstr); /* Fetch the latitude correction surface. note that the attribute string may be of any length so the length of atvalue may have to be adjusted. */ if (!igets (str2, "latcor", SZ_ATSTRING, latstr)) { if (!igets (str1, "latcor", SZ_ATSTRING, latstr)) wcs->latcor = NULL; else wcs->latcor = wf_gsopen (latstr); } else wcs->latcor = wf_gsopen (latstr); /* Determine the number of ZP coefficients */ for (i = 9; i >= 0 && wcs->prj.p[i] == 0.; i--); wcs->zpnp = i; if (i >= 3) { /* Find the point of inflection closest to the pole. */ zd1 = 0.; d1 = wcs->prj.p[1]; /* Find the point where the derivative first goes negative. */ for (i = 1; i<= 180; i++) { zd2 = PI * i / 180.0; d2 = 0.; for (j = wcs->zpnp; j >= 1; j--) { d2 = d2 * zd2 + j * wcs->prj.p[j]; } if (d2 <= 0.) break; zd1 = zd2; d1 = d2; } /* Find where the derivative is 0. */ if (d2 <= 0.0) { for (i = 1; i <= 10; i++) { zd = zd1 - d1 * (zd2 - zd1) / (d2 - d1); d = 0.; for (j = wcs->zpnp; j >= 1; j--) { d = d * zd + j * wcs->prj.p[j]; } if (fabs(d) < TOL) break; if (d < 0.) { zd2 = zd; d2 = d; } else { zd1 = zd; d1 = d; } } } /* No negative derivative. */ else zd = PI; r = 0.; for (j = wcs->zpnp; j >= 0; j--) r = r * zd + wcs->prj.p[j]; wcs->zpzd = zd; wcs->zpr = r; } /* Compute image rotation */ wcsrotset (wcs); /* free working space. */ free (str1); free (str2); free (lngstr); free (latstr); /* Return 1 if there are no correction coefficients */ if (wcs->latcor == NULL && wcs->lngcor == NULL) return (1); else return (0); } /* zpxpos -- forward transform (physical to world) gnomonic projection. */ int zpxpos (xpix, ypix, wcs, xpos, ypos) double xpix, ypix; /*i physical coordinates (x, y) */ struct WorldCoor *wcs; /*i pointer to WCS descriptor */ double *xpos, *ypos; /*o world coordinates (ra, dec) */ { int i, j, k, ira, idec; double x, y, r, phi, theta, costhe, sinthe, dphi, cosphi, sinphi, dlng, z; double colatp, coslatp, sinlatp, longp; double xs, ys, ra, dec, xp, yp; double a, b, c, d, zd, zd1, zd2, r1, r2, rt, lambda; double wf_gseval(); /* Convert from pixels to image coordinates */ xpix = xpix - wcs->crpix[0]; ypix = ypix - wcs->crpix[1]; /* Scale and rotate using CD matrix */ if (wcs->rotmat) { x = xpix * wcs->cd[0] + ypix * wcs->cd[1]; y = xpix * wcs->cd[2] + ypix * wcs->cd[3]; } else { /* Check axis increments - bail out if either 0 */ if (wcs->cdelt[0] == 0.0 || wcs->cdelt[1] == 0.0) { *xpos = 0.0; *ypos = 0.0; return 2; } /* Scale using CDELT */ xs = xpix * wcs->cdelt[0]; ys = ypix * wcs->cdelt[1]; /* Take out rotation from CROTA */ if (wcs->rot != 0.0) { double cosr = cos (degrad (wcs->rot)); double sinr = sin (degrad (wcs->rot)); x = xs * cosr - ys * sinr; y = xs * sinr + ys * cosr; } else { x = xs; y = ys; } } /* Get the axis numbers */ if (wcs->coorflip) { ira = 1; idec = 0; } else { ira = 0; idec = 1; } colatp = degrad (90.0 - wcs->crval[idec]); coslatp = cos(colatp); sinlatp = sin(colatp); longp = degrad(wcs->longpole); /* Compute native spherical coordinates phi and theta in degrees from the projected coordinates. this is the projection part of the computation */ k = wcs->zpnp; if (wcs->lngcor != NULL) xp = x + wf_gseval (wcs->lngcor, x, y); else xp = x; if (wcs->latcor != NULL) yp = y + wf_gseval (wcs->latcor, x, y); else yp = y; x = xp; y = yp; r = sqrt (x * x + y * y) / wcs->rodeg; /* Solve */ /* Constant no solution */ if (k < 1) { *xpos = BADCVAL; *ypos = BADCVAL; return (1); } /* Linear */ else if (k == 1) { zd = (r - wcs->prj.p[0]) / wcs->prj.p[1]; } /* Quadratic */ else if (k == 2) { a = wcs->prj.p[2]; b = wcs->prj.p[1]; c = wcs->prj.p[0] - r; d = b * b - 4. * a * c; if (d < 0.) { *xpos = BADCVAL; *ypos = BADCVAL; return (1); } d = sqrt (d); /* Choose solution closest to the pole */ zd1 = (-b + d) / (2. * a); zd2 = (-b - d) / (2. * a); if (zd1 < zd2) zd = zd1; else zd = zd2; if (zd < -TOL) { if (zd1 > zd2) zd = zd1; else zd = zd2; } if (zd < 0.) { if (zd < -TOL) { *xpos = BADCVAL; *ypos = BADCVAL; return (1); } zd = 0.; } else if (zd > PI) { if (zd > (PI + TOL)) { *xpos = BADCVAL; *ypos = BADCVAL; return (1); } zd = PI; } } /* Higher order solve iteratively */ else { zd1 = 0.; r1 = wcs->prj.p[0]; zd2 = wcs->zpzd; r2 = wcs->zpr; if (r < r1) { if (r < (r1 - TOL)) { *xpos = BADCVAL; *ypos = BADCVAL; return (1); } zd = zd1; } else if (r > r2) { if (r > (r2 + TOL)) { *xpos = BADCVAL; *ypos = BADCVAL; return (1); } zd = zd2; } else { for (j=0; j<100; j++) { lambda = (r2 - r) / (r2 - r1); if (lambda < 0.1) lambda = 0.1; else if (lambda > 0.9) lambda = 0.9; zd = zd2 - lambda * (zd2 - zd1); rt = 0.; for (i=k; i>=0; i--) rt = (rt * zd) + wcs->prj.p[i]; if (rt < r) { if ((r - rt) < TOL) break; r1 = rt; zd1 = zd; } else { if ((rt - r) < TOL) break; r2 = rt; zd2 = zd; } lambda = zd2 - zd1; lambda = fabs (zd2 - zd1); if (fabs (zd2 - zd1) < TOL) break; } } } /* Compute phi */ if (r == 0.0) phi = 0.0; else phi = atan2 (x, -y); /* Compute theta */ theta = PI / 2 - zd; /* Compute the celestial coordinates ra and dec from the native coordinates phi and theta. this is the spherical geometry part of the computation */ costhe = cos (theta); sinthe = sin (theta); dphi = phi - longp; cosphi = cos (dphi); sinphi = sin (dphi); /* Compute the ra */ x = sinthe * sinlatp - costhe * coslatp * cosphi; if (fabs (x) < SPHTOL) x = -cos (theta + colatp) + costhe * coslatp * (1.0 - cosphi); y = -costhe * sinphi; if (x != 0.0 || y != 0.0) dlng = atan2 (y, x); else dlng = dphi + PI ; ra = wcs->crval[ira] + raddeg(dlng); /* normalize ra */ if (wcs->crval[ira] >= 0.0) { if (ra < 0.0) ra = ra + 360.0; } else { if (ra > 0.0) ra = ra - 360.0; } if (ra > 360.0) ra = ra - 360.0; else if (ra < -360.0) ra = ra + 360.0; /* compute the dec */ if (fmod (dphi, PI) == 0.0) { dec = raddeg(theta + cosphi * colatp); if (dec > 90.0) dec = 180.0 - dec; if (dec < -90.0) dec = -180.0 - dec; } else { z = sinthe * coslatp + costhe * sinlatp * cosphi; if (fabs(z) > 0.99) { if (z >= 0.0) dec = raddeg(acos (sqrt(x * x + y * y))); else dec = raddeg(-acos (sqrt(x * x + y * y))); } else dec = raddeg(asin (z)); } /* store the results */ *xpos = ra; *ypos = dec; return (0); } /* zpxpix -- inverse transform (world to physical) for the zenithal * azimuthal polynomial projection. */ int zpxpix (xpos, ypos, wcs, xpix, ypix) double xpos, ypos; /*i world coordinates (ra, dec) */ struct WorldCoor *wcs; /*i pointer to WCS descriptor */ double *xpix, *ypix; /*o physical coordinates (x, y) */ { int i, ira, idec, niter; double ra, dec, cosdec, sindec, cosra, sinra, x, y, phi, theta; double s, r, dphi, z, dpi, dhalfpi, twopi, tx; double xm, ym, f, fx, fy, g, gx, gy, denom, dx, dy; double colatp, coslatp, sinlatp, longp, sphtol; double wf_gseval(), wf_gsder(); /* get the axis numbers */ if (wcs->coorflip) { ira = 1; idec = 0; } else { ira = 0; idec = 1; } /* Compute the transformation from celestial coordinates ra and dec to native coordinates phi and theta. this is the spherical geometry part of the transformation */ ra = degrad (xpos - wcs->crval[ira]); dec = degrad (ypos); cosra = cos (ra); sinra = sin (ra); cosdec = cos (dec); sindec = sin (dec); colatp = degrad (90.0 - wcs->crval[idec]); coslatp = cos (colatp); sinlatp = sin (colatp); if (wcs->longpole == 999.0) longp = degrad (180.0); else longp = degrad(wcs->longpole); dpi = PI; dhalfpi = dpi * 0.5; twopi = PI + PI; sphtol = SPHTOL; /* Compute phi */ x = sindec * sinlatp - cosdec * coslatp * cosra; if (fabs(x) < sphtol) x = -cos (dec + colatp) + cosdec * coslatp * (1.0 - cosra); y = -cosdec * sinra; if (x != 0.0 || y != 0.0) dphi = atan2 (y, x); else dphi = ra - dpi; phi = longp + dphi; if (phi > dpi) phi = phi - twopi; else if (phi < -dpi) phi = phi + twopi; /* Compute theta */ if (fmod (ra, dpi) == 0.0) { theta = dec + cosra * colatp; if (theta > dhalfpi) theta = dpi - theta; if (theta < -dhalfpi) theta = -dpi - theta; } else { z = sindec * coslatp + cosdec * sinlatp * cosra; if (fabs (z) > 0.99) { if (z >= 0.0) theta = acos (sqrt(x * x + y * y)); else theta = -acos (sqrt(x * x + y * y)); } else theta = asin (z); } /* Compute the transformation from native coordinates phi and theta to projected coordinates x and y */ s = dhalfpi - theta; r = 0.; for (i=9; i>=0; i--) r = r * s + wcs->prj.p[i]; r = wcs->rodeg * r; if (wcs->lngcor == NULL && wcs->latcor == NULL) { if (wcs->coorflip) { y = r * sin (phi); x = -r * cos (phi); } else { x = r * sin (phi); y = -r * cos (phi); } } else { xm = r * sin (phi); ym = -r * cos (phi); x = xm; y = ym; niter = 0; while (niter < max_niter) { if (wcs->lngcor != NULL) { f = x + wf_gseval (wcs->lngcor, x, y) - xm; fx = wf_gsder (wcs->lngcor, x, y, 1, 0); fx = 1.0 + fx; fy = wf_gsder (wcs->lngcor, x, y, 0, 1); } else { f = x - xm; fx = 1.0 ; fy = 0.0; } if (wcs->latcor != NULL) { g = y + wf_gseval (wcs->latcor, x, y) - ym; gx = wf_gsder (wcs->latcor, x, y, 1, 0); gy = wf_gsder (wcs->latcor, x, y, 0, 1); gy = 1.0 + gy; } else { g = y - ym; gx = 0.0 ; gy = 1.0; } denom = fx * gy - fy * gx; if (denom == 0.0) break; dx = (-f * gy + g * fy) / denom; dy = (-g * fx + f * gx) / denom; x = x + dx; y = y + dy; if (MAX(MAX(fabs(dx),fabs(dy)),MAX(fabs(f),fabs(g))) < 2.80e-8) break; niter = niter + 1; } /* Reverse x and y if axes flipped */ if (wcs->coorflip) { tx = x; x = y; y = tx; } } /* Scale and rotate using CD matrix */ if (wcs->rotmat) { *xpix = x * wcs->dc[0] + y * wcs->dc[1]; *ypix = x * wcs->dc[2] + y * wcs->dc[3]; } else { /* Correct for rotation */ if (wcs->rot!=0.0) { double cosr = cos (degrad (wcs->rot)); double sinr = sin (degrad (wcs->rot)); *xpix = x * cosr + y * sinr; *ypix = y * cosr - x * sinr; } else { *xpix = x; *ypix = y; } /* Scale using CDELT */ if (wcs->xinc != 0.) *xpix = *xpix / wcs->xinc; if (wcs->yinc != 0.) *ypix = *ypix / wcs->yinc; } /* Convert to pixels */ *xpix = *xpix + wcs->xrefpix; *ypix = *ypix + wcs->yrefpix; return (0); } /* ZPXCLOSE -- free up the distortion surface pointers */ void zpxclose (wcs) struct WorldCoor *wcs; /* pointer to the WCS descriptor */ { if (wcs->lngcor != NULL) wf_gsclose (wcs->lngcor); if (wcs->latcor != NULL) wf_gsclose (wcs->latcor); return; } /* wf_gsclose -- procedure to free the surface descriptor */ static void wf_gsclose (sf) struct IRAFsurface *sf; /* the surface descriptor */ { if (sf != NULL) { if (sf->xbasis != NULL) free (sf->xbasis); if (sf->ybasis != NULL) free (sf->ybasis); if (sf->coeff != NULL) free (sf->coeff); free (sf); } return; } /* * Mar 8 2011 Created from tnxpos.c and wfzpx.x * * Oct 31 2012 End comment on line 346 after pole; fix code thereafter */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/wcscon.i0000644000175000017500000000244713047255533021134 0ustar mattymatty00000000000000// Wrapping of WCSTools wcscon.c // This does general coord conversion and does not need a WCS %feature("autodoc", "0"); %module (package="PyWCSTools") wcscon %include "typemaps.i" // %apply double *OUTPUT {double *dtheta, double *dphi, double *ptheta, double *pphi}; // void wcsconp (int sys1, int sys2, double eq1, double eq2, double ep1, double ep2, double *dtheta, double *dphi, double *ptheta, double *pphi); // void wcsconp (int sys1, int sys2, double eq1, double eq2, double ep1, double ep2, double *dtheta, double *dphi, double *ptheta, double *pphi); // %apply double *OUTPUT {double *dtheta, double *dphi, double *ptheta, double *pphi, double *px, double *rv}; // void wcsconv (int sys1, int sys2, double eq1, double eq2, double ep1, double ep2, double *dtheta, double *dphi, double *ptheta, double *pphi, double *px, double *rv); // void wcsconv (int sys1, int sys2, double eq1, double eq2, double ep1, double ep2, double *dtheta, double *dphi, double *ptheta, double *pphi, double *px, double *rv); // %apply double *OUTPUT {double *dtheta, double *dphi}; // void wcscon (int sys1, int sys2, double eq1, double eq2, double *dtheta, double *dphi, double epoch); void wcscon (int sys1, int sys2, double eq1, double eq2, double *INOUT, double *INOUT, double epoch); int wcscsys (char *wcstring); astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/platepos.c0000664000175000017500000002540013047255533021455 0ustar mattymatty00000000000000/*** File saoimage/wcslib/platepos.c *** February 29, 2000 *** By Jessica Mink, jmink@cfa.harvard.edu *** Harvard-Smithsonian Center for Astrophysics *** Copyright (C) 1998-2002 *** Smithsonian Astrophysical Observatory, Cambridge, MA, USA This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Correspondence concerning WCSTools should be addressed as follows: Internet email: jmink@cfa.harvard.edu Postal address: Jessica Mink Smithsonian Astrophysical Observatory 60 Garden St. Cambridge, MA 02138 USA * Module: platepos.c (Plate solution WCS conversion * Purpose: Compute WCS from plate fit * Subroutine: platepos() converts from pixel location to RA,Dec * Subroutine: platepix() converts from RA,Dec to pixel location These functions are based on the astrmcal.c portion of GETIMAGE by J. Doggett and the documentation distributed with the Digital Sky Survey. */ #include #include #include #include "wcs.h" int platepos (xpix, ypix, wcs, xpos, ypos) /* Routine to determine accurate position for pixel coordinates */ /* returns 0 if successful otherwise 1 = angle too large for projection; */ /* based on amdpos() from getimage */ /* Input: */ double xpix; /* x pixel number (RA or long without rotation) */ double ypix; /* y pixel number (dec or lat without rotation) */ struct WorldCoor *wcs; /* WCS parameter structure */ /* Output: */ double *xpos; /* Right ascension or longitude in degrees */ double *ypos; /* Declination or latitude in degrees */ { double x, y, x2, y2, x3, y3, r2; double xi, xir, eta, etar, raoff, ra, dec, ra0, dec0; double twopi = 6.28318530717959; double ctan, ccos; int ncoeff1 = wcs->ncoeff1; int ncoeff2 = wcs->ncoeff2; /* Ignore magnitude and color terms double mag = 0.0; double color = 0.0; */ /* Convert from pixels to millimeters */ x = xpix - wcs->crpix[0]; y = ypix - wcs->crpix[1]; x2 = x * x; y2 = y * y; x3 = x * x2; y3 = y * y2; r2 = x2 + y2; /* Compute xi,eta coordinates in degrees from x,y and plate model */ xi = wcs->x_coeff[ 0] + wcs->x_coeff[ 1]*x + wcs->x_coeff[ 2]*y + wcs->x_coeff[ 3]*x2 + wcs->x_coeff[ 4]*y2 + wcs->x_coeff[ 5]*x*y; if (ncoeff1 > 6) xi = xi + wcs->x_coeff[ 6]*x3 + wcs->x_coeff[ 7]*y3; if (ncoeff1 > 8) { xi = xi + wcs->x_coeff[ 8]*x2*y + wcs->x_coeff[ 9]*x*y2 + wcs->x_coeff[10]*(r2) + wcs->x_coeff[11]*x*r2 + wcs->x_coeff[12]*y*r2; } eta = wcs->y_coeff[ 0] + wcs->y_coeff[ 1]*x + wcs->y_coeff[ 2]*y + wcs->y_coeff[ 3]*x2 + wcs->y_coeff[ 4]*y2 + wcs->y_coeff[ 5]*x*y; if (ncoeff2 > 6) eta = eta + wcs->y_coeff[ 6]*x3 + wcs->y_coeff[ 7]*y3; if (ncoeff2 > 8) { eta = eta + wcs->y_coeff[ 8]*x2*y + wcs->y_coeff[ 9]*y2*x + wcs->y_coeff[10]*r2 + wcs->y_coeff[11]*x*r2 + wcs->y_coeff[12]*y*r2; } /* Convert to radians */ xir = degrad (xi); etar = degrad (eta); /* Convert to RA and Dec */ ra0 = degrad (wcs->crval[0]); dec0 = degrad (wcs->crval[1]); ctan = tan (dec0); ccos = cos (dec0); raoff = atan2 (xir / ccos, 1.0 - etar * ctan); ra = raoff + ra0; if (ra < 0.0) ra = ra + twopi; *xpos = raddeg (ra); dec = atan (cos (raoff) / ((1.0 - (etar * ctan)) / (etar + ctan))); *ypos = raddeg (dec); return 0; } int platepix (xpos, ypos, wcs, xpix, ypix) /* Routine to determine pixel coordinates for sky position */ /* returns 0 if successful otherwise 1 = angle too large for projection; */ /* based on amdinv() from getimage */ /* Input: */ double xpos; /* Right ascension or longitude in degrees */ double ypos; /* Declination or latitude in degrees */ struct WorldCoor *wcs; /* WCS parameter structure */ /* Output: */ double *xpix; /* x pixel number (RA or long without rotation) */ double *ypix; /* y pixel number (dec or lat without rotation) */ { double xi,eta,x,y,xy,x2,y2,x2y,y2x,x3,y3,r2,dx,dy; double tdec,ctan,ccos,traoff, craoff, etar, xir; double f,fx,fy,g,gx,gy; double ra0, dec0, ra, dec; double tolerance = 0.0000005; int max_iterations = 50; int i; int ncoeff1 = wcs->ncoeff1; int ncoeff2 = wcs->ncoeff2; /* Convert RA and Dec in radians to standard coordinates on a plate */ ra = degrad (xpos); dec = degrad (ypos); tdec = tan (dec); ra0 = degrad (wcs->crval[0]); dec0 = degrad (wcs->crval[1]); ctan = tan (dec0); ccos = cos (dec0); traoff = tan (ra - ra0); craoff = cos (ra - ra0); etar = (1.0 - ctan * craoff / tdec) / (ctan + (craoff / tdec)); xir = traoff * ccos * (1.0 - (etar * ctan)); xi = raddeg (xir); eta = raddeg (etar); /* Set initial value for x,y */ x = xi * wcs->dc[0] + eta * wcs->dc[1]; y = xi * wcs->dc[2] + eta * wcs->dc[3]; /* if (wcs->x_coeff[1] == 0.0) x = xi - wcs->x_coeff[0]; else x = (xi - wcs->x_coeff[0]) / wcs->x_coeff[1]; if (wcs->y_coeff[2] == 0.0) y = eta - wcs->y_coeff[0]; else y = (eta - wcs->y_coeff[0]) / wcs->y_coeff[2]; */ /* Iterate by Newton's method */ for (i = 0; i < max_iterations; i++) { /* X plate model */ xy = x * y; x2 = x * x; y2 = y * y; x3 = x2 * x; y3 = y2 * y; x2y = x2 * y; y2x = y2 * x; r2 = x2 + y2; f = wcs->x_coeff[0] + wcs->x_coeff[1]*x + wcs->x_coeff[2]*y + wcs->x_coeff[3]*x2 + wcs->x_coeff[4]*y2 + wcs->x_coeff[5]*xy; /* Derivative of X model wrt x */ fx = wcs->x_coeff[1] + wcs->x_coeff[3]*2.0*x + wcs->x_coeff[5]*y; /* Derivative of X model wrt y */ fy = wcs->x_coeff[2] + wcs->x_coeff[4]*2.0*y + wcs->x_coeff[5]*x; if (ncoeff1 > 6) { f = f + wcs->x_coeff[6]*x3 + wcs->x_coeff[7]*y3; fx = fx + wcs->x_coeff[6]*3.0*x2; fy = fy + wcs->x_coeff[7]*3.0*y2; } if (ncoeff1 > 8) { f = f + wcs->x_coeff[8]*x2y + wcs->x_coeff[9]*y2x + wcs->x_coeff[10]*r2 + wcs->x_coeff[11]*x*r2 + wcs->x_coeff[12]*y*r2; fx = fx + wcs->x_coeff[8]*2.0*xy + wcs->x_coeff[9]*y2 + wcs->x_coeff[10]*2.0*x + wcs->x_coeff[11]*(3.0*x2+y2) + wcs->x_coeff[12]*2.0*xy; fy = fy + wcs->x_coeff[8]*x2 + wcs->x_coeff[9]*2.0*xy + wcs->x_coeff[10]*2.0*y + wcs->x_coeff[11]*2.0*xy + wcs->x_coeff[12]*(3.0*y2+x2); } /* Y plate model */ g = wcs->y_coeff[0] + wcs->y_coeff[1]*x + wcs->y_coeff[2]*y + wcs->y_coeff[3]*x2 + wcs->y_coeff[4]*y2 + wcs->y_coeff[5]*xy; /* Derivative of Y model wrt x */ gx = wcs->y_coeff[1] + wcs->y_coeff[3]*2.0*x + wcs->y_coeff[5]*y; /* Derivative of Y model wrt y */ gy = wcs->y_coeff[2] + wcs->y_coeff[4]*2.0*y + wcs->y_coeff[5]*x; if (ncoeff2 > 6) { g = g + wcs->y_coeff[6]*x3 + wcs->y_coeff[7]*y3; gx = gx + wcs->y_coeff[6]*3.0*x2; gy = gy + wcs->y_coeff[7]*3.0*y2; } if (ncoeff2 > 8) { g = g + wcs->y_coeff[8]*x2y + wcs->y_coeff[9]*y2x + wcs->y_coeff[10]*r2 + wcs->y_coeff[11]*x*r2 + wcs->y_coeff[12]*y*r2; gx = gx + wcs->y_coeff[8]*2.0*xy + wcs->y_coeff[9]*y2 + wcs->y_coeff[10]*2.0*x + wcs->y_coeff[11]*(3.0*x2+y2) + wcs->y_coeff[12]*2.0*xy; gy = gy + wcs->y_coeff[8]*x2 + wcs->y_coeff[9]*2.0*xy + wcs->y_coeff[10]*2.0*y + wcs->y_coeff[11]*2.0*xy + wcs->y_coeff[12]*(3.0*y2+x2); } f = f - xi; g = g - eta; dx = ((-f * gy) + (g * fy)) / ((fx * gy) - (fy * gx)); dy = ((-g * fx) + (f * gx)) / ((fx * gy) - (fy * gx)); x = x + dx; y = y + dy; if ((fabs(dx) < tolerance) && (fabs(dy) < tolerance)) break; } /* Convert from plate pixels to image pixels */ *xpix = x + wcs->crpix[0]; *ypix = y + wcs->crpix[1]; /* If position is off of the image, return offscale code */ if (*xpix < 0.5 || *xpix > wcs->nxpix+0.5) return -1; if (*ypix < 0.5 || *ypix > wcs->nypix+0.5) return -1; return 0; } /* Set plate fit coefficients in structure from arguments */ int SetPlate (wcs, ncoeff1, ncoeff2, coeff) struct WorldCoor *wcs; /* World coordinate system structure */ int ncoeff1; /* Number of coefficients for x */ int ncoeff2; /* Number of coefficients for y */ double *coeff; /* Plate fit coefficients */ { int i; if (nowcs (wcs) || (ncoeff1 < 1 && ncoeff2 < 1)) return 1; wcs->ncoeff1 = ncoeff1; wcs->ncoeff2 = ncoeff2; wcs->prjcode = WCS_PLT; for (i = 0; i < 20; i++) { if (i < ncoeff1) wcs->x_coeff[i] = coeff[i]; else wcs->x_coeff[i] = 0.0; } for (i = 0; i < 20; i++) { if (i < ncoeff2) wcs->y_coeff[i] = coeff[ncoeff1+i]; else wcs->y_coeff[i] = 0.0; } return 0; } /* Return plate fit coefficients from structure in arguments */ int GetPlate (wcs, ncoeff1, ncoeff2, coeff) struct WorldCoor *wcs; /* World coordinate system structure */ int *ncoeff1; /* Number of coefficients for x */ int *ncoeff2; /* Number of coefficients for y) */ double *coeff; /* Plate fit coefficients */ { int i; if (nowcs (wcs)) return 1; *ncoeff1 = wcs->ncoeff1; *ncoeff2 = wcs->ncoeff2; for (i = 0; i < *ncoeff1; i++) coeff[i] = wcs->x_coeff[i]; for (i = 0; i < *ncoeff2; i++) coeff[*ncoeff1+i] = wcs->y_coeff[i]; return 0; } /* Set FITS header plate fit coefficients from structure */ void SetFITSPlate (header, wcs) char *header; /* Image FITS header */ struct WorldCoor *wcs; /* WCS structure */ { char keyword[16]; int i; for (i = 0; i < wcs->ncoeff1; i++) { sprintf (keyword,"CO1_%d",i+1); hputnr8 (header, keyword, -15, wcs->x_coeff[i]); } for (i = 0; i < wcs->ncoeff2; i++) { sprintf (keyword,"CO2_%d",i+1); hputnr8 (header, keyword, -15, wcs->y_coeff[i]); } return; } /* Mar 27 1998 New subroutines for direct image pixel <-> sky polynomials * Apr 10 1998 Make terms identical for both x and y polynomials * Apr 10 1998 Allow different numbers of coefficients for x and y * Apr 16 1998 Drom NCOEFF header parameter * Apr 28 1998 Change projection flags to WCS_* * Sep 10 1998 Check for xc1 and yc2 divide by zero after Allen Harris, SAO * * Oct 21 1999 Drop unused variables after lint * * Feb 29 2000 Use inverse CD matrix to get initial X,Y in platepix() * as suggested by Paolo Montegriffo from Bologna Ast. Obs. */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/wcs.c0000664000175000017500000025214513047255533020432 0ustar mattymatty00000000000000/*** File libwcs/wcs.c *** October 19, 2012 *** By Jessica Mink, jmink@cfa.harvard.edu *** Harvard-Smithsonian Center for Astrophysics *** Copyright (C) 1994-2012 *** Smithsonian Astrophysical Observatory, Cambridge, MA, USA This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Correspondence concerning WCSTools should be addressed as follows: Internet email: jmink@cfa.harvard.edu Postal address: Jessica Mink Smithsonian Astrophysical Observatory 60 Garden St. Cambridge, MA 02138 USA * Module: wcs.c (World Coordinate Systems) * Purpose: Convert FITS WCS to pixels and vice versa: * Subroutine: wcsxinit (cra,cdec,secpix,xrpix,yrpix,nxpix,nypix,rotate,equinox,epoch,proj) * sets a WCS structure from arguments * Subroutine: wcskinit (nxpix,nypix,ctype1,ctype2,crpix1,crpix2,crval1,crval2, cd,cdelt1,cdelt2,crota,equinox,epoch) * sets a WCS structure from keyword-based arguments * Subroutine: wcsreset (wcs,crpix1,crpix2,crval1,crval2,cdelt1,cdelt2,crota,cd, equinox) * resets an existing WCS structure from arguments * Subroutine: wcsdeltset (wcs,cdelt1,cdelt2,crota) sets rotation and scaling * Subroutine: wcscdset (wcs, cd) sets rotation and scaling from a CD matrix * Subroutine: wcspcset (wcs,cdelt1,cdelt2,pc) sets rotation and scaling * Subroutine: wcseqset (wcs, equinox) resets an existing WCS structure to new equinox * Subroutine: iswcs(wcs) returns 1 if WCS structure is filled, else 0 * Subroutine: nowcs(wcs) returns 0 if WCS structure is filled, else 1 * Subroutine: wcscent (wcs) prints the image center and size in WCS units * Subroutine: wcssize (wcs, cra, cdec, dra, ddec) returns image center and size * Subroutine: wcsfull (wcs, cra, cdec, width, height) returns image center and size * Subroutine: wcsrange (wcs, ra1, ra2, dec1, dec2) returns image coordinate limits * Subroutine: wcsshift (wcs,cra,cdec) resets the center of a WCS structure * Subroutine: wcsdist (x1,y1,x2,y2) compute angular distance between ra/dec or lat/long * Subroutine: wcsdiff (x1,y1,x2,y2) compute angular distance between ra/dec or lat/long * Subroutine: wcscominit (wcs,command) sets up a command format for execution by wcscom * Subroutine: wcsoutinit (wcs,coor) sets up the coordinate system used by pix2wcs * Subroutine: getwcsout (wcs) returns current output coordinate system used by pix2wcs * Subroutine: wcsininit (wcs,coor) sets up the coordinate system used by wcs2pix * Subroutine: getwcsin (wcs) returns current input coordinate system used by wcs2pix * Subroutine: setwcsdeg(wcs, new) sets WCS output in degrees or hh:mm:ss * Subroutine: getradecsys(wcs) returns current coordinate system type * Subroutine: wcscom (wcs,file,x,y,wcstr) executes a command using the current world coordinates * Subroutine: setwcslin (wcs, mode) sets output string mode for LINEAR * Subroutine: pix2wcst (wcs,xpix,ypix,wcstring,lstr) pixels -> sky coordinate string * Subroutine: pix2wcs (wcs,xpix,ypix,xpos,ypos) pixel coordinates -> sky coordinates * Subroutine: wcsc2pix (wcs,xpos,ypos,coorsys,xpix,ypix,offscl) sky coordinates -> pixel coordinates * Subroutine: wcs2pix (wcs,xpos,ypos,xpix,ypix,offscl) sky coordinates -> pixel coordinates * Subroutine: wcszin (izpix) sets third dimension for pix2wcs() and pix2wcst() * Subroutine: wcszout (wcs) returns third dimension from wcs2pix() * Subroutine: setwcsfile (filename) Set file name for error messages * Subroutine: setwcserr (errmsg) Set error message * Subroutine: wcserr() Print error message * Subroutine: setdefwcs (wcsproj) Set flag to choose AIPS or WCSLIB WCS subroutines * Subroutine: getdefwcs() Get flag to switch between AIPS and WCSLIB subroutines * Subroutine: savewcscoor (wcscoor) * Subroutine: getwcscoor() Return preset output default coordinate system * Subroutine: savewcscom (i, wcscom) Save specified WCS command * Subroutine: setwcscom (wcs) Initialize WCS commands * Subroutine: getwcscom (i) Return specified WCS command * Subroutine: wcsfree (wcs) Free storage used by WCS structure * Subroutine: freewcscom (wcs) Free storage used by WCS commands * Subroutine: cpwcs (&header, cwcs) */ #include /* strstr, NULL */ #include /* stderr */ #include #include "wcs.h" #ifndef VMS #include #endif static char wcserrmsg[80]; static char wcsfile[256]={""}; static void wcslibrot(); void wcsrotset(); static int wcsproj0 = 0; static int izpix = 0; static double zpix = 0.0; void wcsfree (wcs) struct WorldCoor *wcs; /* WCS structure */ { if (nowcs (wcs)) { /* Free WCS structure if allocated but not filled */ if (wcs) free (wcs); return; } /* Free WCS on which this WCS depends */ if (wcs->wcs) { wcsfree (wcs->wcs); wcs->wcs = NULL; } freewcscom (wcs); if (wcs->wcsname != NULL) free (wcs->wcsname); if (wcs->lin.imgpix != NULL) free (wcs->lin.imgpix); if (wcs->lin.piximg != NULL) free (wcs->lin.piximg); if (wcs->inv_x != NULL) poly_end (wcs->inv_x); if (wcs->inv_y != NULL) poly_end (wcs->inv_y); free (wcs); return; } /* Set up a WCS structure from subroutine arguments */ struct WorldCoor * wcsxinit (cra,cdec,secpix,xrpix,yrpix,nxpix,nypix,rotate,equinox,epoch,proj) double cra; /* Center right ascension in degrees */ double cdec; /* Center declination in degrees */ double secpix; /* Number of arcseconds per pixel */ double xrpix; /* Reference pixel X coordinate */ double yrpix; /* Reference pixel X coordinate */ int nxpix; /* Number of pixels along x-axis */ int nypix; /* Number of pixels along y-axis */ double rotate; /* Rotation angle (clockwise positive) in degrees */ int equinox; /* Equinox of coordinates, 1950 and 2000 supported */ double epoch; /* Epoch of coordinates, used for FK4/FK5 conversion * no effect if 0 */ char *proj; /* Projection */ { struct WorldCoor *wcs; double cdelt1, cdelt2; wcs = (struct WorldCoor *) calloc (1, sizeof(struct WorldCoor)); /* Set WCSLIB flags so that structures will be reinitialized */ wcs->cel.flag = 0; wcs->lin.flag = 0; wcs->wcsl.flag = 0; /* Image dimensions */ wcs->naxis = 2; wcs->naxes = 2; wcs->lin.naxis = 2; wcs->nxpix = nxpix; wcs->nypix = nypix; wcs->wcsproj = wcsproj0; wcs->crpix[0] = xrpix; wcs->crpix[1] = yrpix; wcs->xrefpix = wcs->crpix[0]; wcs->yrefpix = wcs->crpix[1]; wcs->lin.crpix = wcs->crpix; wcs->crval[0] = cra; wcs->crval[1] = cdec; wcs->xref = wcs->crval[0]; wcs->yref = wcs->crval[1]; wcs->cel.ref[0] = wcs->crval[0]; wcs->cel.ref[1] = wcs->crval[1]; wcs->cel.ref[2] = 999.0; strcpy (wcs->c1type,"RA"); strcpy (wcs->c2type,"DEC"); /* Allan Brighton: 28.4.98: for backward compat., remove leading "--" */ while (proj && *proj == '-') proj++; strcpy (wcs->ptype,proj); strcpy (wcs->ctype[0],"RA---"); strcpy (wcs->ctype[1],"DEC--"); strcat (wcs->ctype[0],proj); strcat (wcs->ctype[1],proj); if (wcstype (wcs, wcs->ctype[0], wcs->ctype[1])) { wcsfree (wcs); return (NULL); } /* Approximate world coordinate system from a known plate scale */ cdelt1 = -secpix / 3600.0; cdelt2 = secpix / 3600.0; wcsdeltset (wcs, cdelt1, cdelt2, rotate); wcs->lin.cdelt = wcs->cdelt; wcs->lin.pc = wcs->pc; /* Coordinate reference frame and equinox */ wcs->equinox = (double) equinox; if (equinox > 1980) strcpy (wcs->radecsys,"FK5"); else strcpy (wcs->radecsys,"FK4"); if (epoch > 0) wcs->epoch = epoch; else wcs->epoch = 0.0; wcs->wcson = 1; wcs->syswcs = wcscsys (wcs->radecsys); wcsoutinit (wcs, wcs->radecsys); wcsininit (wcs, wcs->radecsys); wcs->eqout = 0.0; wcs->printsys = 1; wcs->tabsys = 0; /* Initialize special WCS commands */ setwcscom (wcs); return (wcs); } /* Set up a WCS structure from subroutine arguments based on FITS keywords */ struct WorldCoor * wcskinit (naxis1, naxis2, ctype1, ctype2, crpix1, crpix2, crval1, crval2, cd, cdelt1, cdelt2, crota, equinox, epoch) int naxis1; /* Number of pixels along x-axis */ int naxis2; /* Number of pixels along y-axis */ char *ctype1; /* FITS WCS projection for axis 1 */ char *ctype2; /* FITS WCS projection for axis 2 */ double crpix1, crpix2; /* Reference pixel coordinates */ double crval1, crval2; /* Coordinates at reference pixel in degrees */ double *cd; /* Rotation matrix, used if not NULL */ double cdelt1, cdelt2; /* scale in degrees/pixel, ignored if cd is not NULL */ double crota; /* Rotation angle in degrees, ignored if cd is not NULL */ int equinox; /* Equinox of coordinates, 1950 and 2000 supported */ double epoch; /* Epoch of coordinates, used for FK4/FK5 conversion * no effect if 0 */ { struct WorldCoor *wcs; wcs = (struct WorldCoor *) calloc (1, sizeof(struct WorldCoor)); /* Set WCSLIB flags so that structures will be reinitialized */ wcs->cel.flag = 0; wcs->lin.flag = 0; wcs->wcsl.flag = 0; /* Image dimensions */ wcs->naxis = 2; wcs->naxes = 2; wcs->lin.naxis = 2; wcs->nxpix = naxis1; wcs->nypix = naxis2; wcs->wcsproj = wcsproj0; wcs->crpix[0] = crpix1; wcs->crpix[1] = crpix2; wcs->xrefpix = wcs->crpix[0]; wcs->yrefpix = wcs->crpix[1]; wcs->lin.crpix = wcs->crpix; if (wcstype (wcs, ctype1, ctype2)) { wcsfree (wcs); return (NULL); } if (wcs->latbase == 90) crval2 = 90.0 - crval2; else if (wcs->latbase == -90) crval2 = crval2 - 90.0; wcs->crval[0] = crval1; wcs->crval[1] = crval2; wcs->xref = wcs->crval[0]; wcs->yref = wcs->crval[1]; wcs->cel.ref[0] = wcs->crval[0]; wcs->cel.ref[1] = wcs->crval[1]; wcs->cel.ref[2] = 999.0; if (cd != NULL) wcscdset (wcs, cd); else if (cdelt1 != 0.0) wcsdeltset (wcs, cdelt1, cdelt2, crota); else { wcsdeltset (wcs, 1.0, 1.0, crota); setwcserr ("WCSRESET: setting CDELT to 1"); } wcs->lin.cdelt = wcs->cdelt; wcs->lin.pc = wcs->pc; /* Coordinate reference frame and equinox */ wcs->equinox = (double) equinox; if (equinox > 1980) strcpy (wcs->radecsys,"FK5"); else strcpy (wcs->radecsys,"FK4"); if (epoch > 0) wcs->epoch = epoch; else wcs->epoch = 0.0; wcs->wcson = 1; strcpy (wcs->radecout, wcs->radecsys); wcs->syswcs = wcscsys (wcs->radecsys); wcsoutinit (wcs, wcs->radecsys); wcsininit (wcs, wcs->radecsys); wcs->eqout = 0.0; wcs->printsys = 1; wcs->tabsys = 0; /* Initialize special WCS commands */ setwcscom (wcs); return (wcs); } /* Set projection in WCS structure from FITS keyword values */ int wcstype (wcs, ctype1, ctype2) struct WorldCoor *wcs; /* World coordinate system structure */ char *ctype1; /* FITS WCS projection for axis 1 */ char *ctype2; /* FITS WCS projection for axis 2 */ { int i, iproj; int nctype = NWCSTYPE; char ctypes[NWCSTYPE][4]; char dtypes[10][4]; /* Initialize projection types */ strcpy (ctypes[0], "LIN"); strcpy (ctypes[1], "AZP"); strcpy (ctypes[2], "SZP"); strcpy (ctypes[3], "TAN"); strcpy (ctypes[4], "SIN"); strcpy (ctypes[5], "STG"); strcpy (ctypes[6], "ARC"); strcpy (ctypes[7], "ZPN"); strcpy (ctypes[8], "ZEA"); strcpy (ctypes[9], "AIR"); strcpy (ctypes[10], "CYP"); strcpy (ctypes[11], "CAR"); strcpy (ctypes[12], "MER"); strcpy (ctypes[13], "CEA"); strcpy (ctypes[14], "COP"); strcpy (ctypes[15], "COD"); strcpy (ctypes[16], "COE"); strcpy (ctypes[17], "COO"); strcpy (ctypes[18], "BON"); strcpy (ctypes[19], "PCO"); strcpy (ctypes[20], "SFL"); strcpy (ctypes[21], "PAR"); strcpy (ctypes[22], "AIT"); strcpy (ctypes[23], "MOL"); strcpy (ctypes[24], "CSC"); strcpy (ctypes[25], "QSC"); strcpy (ctypes[26], "TSC"); strcpy (ctypes[27], "NCP"); strcpy (ctypes[28], "GLS"); strcpy (ctypes[29], "DSS"); strcpy (ctypes[30], "PLT"); strcpy (ctypes[31], "TNX"); strcpy (ctypes[32], "ZPX"); strcpy (ctypes[33], "TPV"); /* Initialize distortion types */ strcpy (dtypes[1], "SIP"); if (!strncmp (ctype1, "LONG",4)) strncpy (ctype1, "XLON",4); strcpy (wcs->ctype[0], ctype1); strcpy (wcs->c1type, ctype1); strcpy (wcs->ptype, ctype1); /* Linear coordinates */ if (!strncmp (ctype1,"LINEAR",6)) wcs->prjcode = WCS_LIN; /* Pixel coordinates */ else if (!strncmp (ctype1,"PIXEL",6)) wcs->prjcode = WCS_PIX; /*Detector pixel coordinates */ else if (strsrch (ctype1,"DET")) wcs->prjcode = WCS_PIX; /* Set up right ascension, declination, latitude, or longitude */ else if (ctype1[0] == 'R' || ctype1[0] == 'D' || ctype1[0] == 'A' || ctype1[1] == 'L') { wcs->c1type[0] = ctype1[0]; wcs->c1type[1] = ctype1[1]; if (ctype1[2] == '-') { wcs->c1type[2] = 0; iproj = 3; } else { wcs->c1type[2] = ctype1[2]; iproj = 4; if (ctype1[3] == '-') { wcs->c1type[3] = 0; } else { wcs->c1type[3] = ctype1[3]; wcs->c1type[4] = 0; } } if (ctype1[iproj] == '-') iproj = iproj + 1; if (ctype1[iproj] == '-') iproj = iproj + 1; if (ctype1[iproj] == '-') iproj = iproj + 1; if (ctype1[iproj] == '-') iproj = iproj + 1; wcs->ptype[0] = ctype1[iproj]; wcs->ptype[1] = ctype1[iproj+1]; wcs->ptype[2] = ctype1[iproj+2]; wcs->ptype[3] = 0; sprintf (wcs->ctype[0],"%-4s%4s",wcs->c1type,wcs->ptype); for (i = 0; i < 8; i++) if (wcs->ctype[0][i] == ' ') wcs->ctype[0][i] = '-'; /* Find projection type */ wcs->prjcode = 0; /* default type is linear */ for (i = 1; i < nctype; i++) { if (!strncmp(wcs->ptype, ctypes[i], 3)) wcs->prjcode = i; } /* Handle "obsolete" NCP projection (now WCSLIB should be OK) if (wcs->prjcode == WCS_NCP) { if (wcs->wcsproj == WCS_BEST) wcs->wcsproj = WCS_OLD; else if (wcs->wcsproj == WCS_ALT) wcs->wcsproj = WCS_NEW; } */ /* Work around bug in WCSLIB handling of CAR projection else if (wcs->prjcode == WCS_CAR) { if (wcs->wcsproj == WCS_BEST) wcs->wcsproj = WCS_OLD; else if (wcs->wcsproj == WCS_ALT) wcs->wcsproj = WCS_NEW; } */ /* Work around bug in WCSLIB handling of COE projection else if (wcs->prjcode == WCS_COE) { if (wcs->wcsproj == WCS_BEST) wcs->wcsproj = WCS_OLD; else if (wcs->wcsproj == WCS_ALT) wcs->wcsproj = WCS_NEW; } else if (wcs->wcsproj == WCS_BEST) */ if (wcs->wcsproj == WCS_BEST) wcs->wcsproj = WCS_NEW; else if (wcs->wcsproj == WCS_ALT) wcs->wcsproj = WCS_OLD; /* if (wcs->wcsproj == WCS_OLD && ( wcs->prjcode != WCS_STG && wcs->prjcode != WCS_AIT && wcs->prjcode != WCS_MER && wcs->prjcode != WCS_GLS && wcs->prjcode != WCS_ARC && wcs->prjcode != WCS_TAN && wcs->prjcode != WCS_TNX && wcs->prjcode != WCS_SIN && wcs->prjcode != WCS_PIX && wcs->prjcode != WCS_LIN && wcs->prjcode != WCS_CAR && wcs->prjcode != WCS_COE && wcs->prjcode != WCS_NCP && wcs->prjcode != WCS_ZPX)) wcs->wcsproj = WCS_NEW; */ /* Handle NOAO corrected TNX as uncorrected TAN if oldwcs is set */ if (wcs->wcsproj == WCS_OLD && wcs->prjcode == WCS_TNX) { wcs->ctype[0][6] = 'A'; wcs->ctype[0][7] = 'N'; wcs->prjcode = WCS_TAN; } /* Handle NOAO corrected ZPX as uncorrected ZPN if oldwcs is set */ if (wcs->wcsproj == WCS_OLD && wcs->prjcode == WCS_ZPX) { wcs->ctype[0][6] = 'P'; wcs->ctype[0][7] = 'N'; wcs->prjcode = WCS_ZPN; } } /* If not sky coordinates, assume linear */ else { wcs->prjcode = WCS_LIN; return (0); } /* Second coordinate type */ if (!strncmp (ctype2, "NPOL",4)) { ctype2[0] = ctype1[0]; strncpy (ctype2+1, "LAT",3); wcs->latbase = 90; strcpy (wcs->radecsys,"NPOLE"); wcs->syswcs = WCS_NPOLE; } else if (!strncmp (ctype2, "SPA-",4)) { ctype2[0] = ctype1[0]; strncpy (ctype2+1, "LAT",3); wcs->latbase = -90; strcpy (wcs->radecsys,"SPA"); wcs->syswcs = WCS_SPA; } else wcs->latbase = 0; strcpy (wcs->ctype[1], ctype2); strcpy (wcs->c2type, ctype2); /* Linear coordinates */ if (!strncmp (ctype2,"LINEAR",6)) wcs->prjcode = WCS_LIN; /* Pixel coordinates */ else if (!strncmp (ctype2,"PIXEL",6)) wcs->prjcode = WCS_PIX; /* Set up right ascension, declination, latitude, or longitude */ else if (ctype2[0] == 'R' || ctype2[0] == 'D' || ctype2[0] == 'A' || ctype2[1] == 'L') { wcs->c2type[0] = ctype2[0]; wcs->c2type[1] = ctype2[1]; if (ctype2[2] == '-') { wcs->c2type[2] = 0; iproj = 3; } else { wcs->c2type[2] = ctype2[2]; iproj = 4; if (ctype2[3] == '-') { wcs->c2type[3] = 0; } else { wcs->c2type[3] = ctype2[3]; wcs->c2type[4] = 0; } } if (ctype2[iproj] == '-') iproj = iproj + 1; if (ctype2[iproj] == '-') iproj = iproj + 1; if (ctype2[iproj] == '-') iproj = iproj + 1; if (ctype2[iproj] == '-') iproj = iproj + 1; wcs->ptype[0] = ctype2[iproj]; wcs->ptype[1] = ctype2[iproj+1]; wcs->ptype[2] = ctype2[iproj+2]; wcs->ptype[3] = 0; if (!strncmp (ctype1, "DEC", 3) || !strncmp (ctype1+1, "LAT", 3)) wcs->coorflip = 1; else wcs->coorflip = 0; if (ctype2[1] == 'L' || ctype2[0] == 'A') { wcs->degout = 1; wcs->ndec = 5; } else { wcs->degout = 0; wcs->ndec = 3; } sprintf (wcs->ctype[1],"%-4s%4s",wcs->c2type,wcs->ptype); for (i = 0; i < 8; i++) if (wcs->ctype[1][i] == ' ') wcs->ctype[1][i] = '-'; } /* If not sky coordinates, assume linear */ else { wcs->prjcode = WCS_LIN; } /* Set distortion code from CTYPE1 extension */ setdistcode (wcs, ctype1); return (0); } int wcsreset (wcs, crpix1, crpix2, crval1, crval2, cdelt1, cdelt2, crota, cd) struct WorldCoor *wcs; /* World coordinate system data structure */ double crpix1, crpix2; /* Reference pixel coordinates */ double crval1, crval2; /* Coordinates at reference pixel in degrees */ double cdelt1, cdelt2; /* scale in degrees/pixel, ignored if cd is not NULL */ double crota; /* Rotation angle in degrees, ignored if cd is not NULL */ double *cd; /* Rotation matrix, used if not NULL */ { if (nowcs (wcs)) return (-1); /* Set WCSLIB flags so that structures will be reinitialized */ wcs->cel.flag = 0; wcs->lin.flag = 0; wcs->wcsl.flag = 0; /* Reference pixel coordinates and WCS value */ wcs->crpix[0] = crpix1; wcs->crpix[1] = crpix2; wcs->xrefpix = wcs->crpix[0]; wcs->yrefpix = wcs->crpix[1]; wcs->lin.crpix = wcs->crpix; wcs->crval[0] = crval1; wcs->crval[1] = crval2; wcs->xref = wcs->crval[0]; wcs->yref = wcs->crval[1]; if (wcs->coorflip) { wcs->cel.ref[1] = wcs->crval[0]; wcs->cel.ref[0] = wcs->crval[1]; } else { wcs->cel.ref[0] = wcs->crval[0]; wcs->cel.ref[1] = wcs->crval[1]; } /* Keep ref[2] and ref[3] from input */ /* Initialize to no plate fit */ wcs->ncoeff1 = 0; wcs->ncoeff2 = 0; if (cd != NULL) wcscdset (wcs, cd); else if (cdelt1 != 0.0) wcsdeltset (wcs, cdelt1, cdelt2, crota); else { wcs->xinc = 1.0; wcs->yinc = 1.0; setwcserr ("WCSRESET: setting CDELT to 1"); } /* Coordinate reference frame, equinox, and epoch */ if (!strncmp (wcs->ptype,"LINEAR",6) || !strncmp (wcs->ptype,"PIXEL",5)) wcs->degout = -1; wcs->wcson = 1; return (0); } void wcseqset (wcs, equinox) struct WorldCoor *wcs; /* World coordinate system data structure */ double equinox; /* Desired equinox as fractional year */ { if (nowcs (wcs)) return; /* Leave WCS alone if already at desired equinox */ if (wcs->equinox == equinox) return; /* Convert center from B1950 (FK4) to J2000 (FK5) */ if (equinox == 2000.0 && wcs->equinox == 1950.0) { if (wcs->coorflip) { fk425e (&wcs->crval[1], &wcs->crval[0], wcs->epoch); wcs->cel.ref[1] = wcs->crval[0]; wcs->cel.ref[0] = wcs->crval[1]; } else { fk425e (&wcs->crval[0], &wcs->crval[1], wcs->epoch); wcs->cel.ref[0] = wcs->crval[0]; wcs->cel.ref[1] = wcs->crval[1]; } wcs->xref = wcs->crval[0]; wcs->yref = wcs->crval[1]; wcs->equinox = 2000.0; strcpy (wcs->radecsys, "FK5"); wcs->syswcs = WCS_J2000; wcs->cel.flag = 0; wcs->wcsl.flag = 0; } /* Convert center from J2000 (FK5) to B1950 (FK4) */ else if (equinox == 1950.0 && wcs->equinox == 2000.0) { if (wcs->coorflip) { fk524e (&wcs->crval[1], &wcs->crval[0], wcs->epoch); wcs->cel.ref[1] = wcs->crval[0]; wcs->cel.ref[0] = wcs->crval[1]; } else { fk524e (&wcs->crval[0], &wcs->crval[1], wcs->epoch); wcs->cel.ref[0] = wcs->crval[0]; wcs->cel.ref[1] = wcs->crval[1]; } wcs->xref = wcs->crval[0]; wcs->yref = wcs->crval[1]; wcs->equinox = 1950.0; strcpy (wcs->radecsys, "FK4"); wcs->syswcs = WCS_B1950; wcs->cel.flag = 0; wcs->wcsl.flag = 0; } wcsoutinit (wcs, wcs->radecsys); wcsininit (wcs, wcs->radecsys); return; } /* Set scale and rotation in WCS structure */ void wcscdset (wcs, cd) struct WorldCoor *wcs; /* World coordinate system structure */ double *cd; /* CD matrix, ignored if NULL */ { double tcd; if (cd == NULL) return; wcs->rotmat = 1; wcs->cd[0] = cd[0]; wcs->cd[1] = cd[1]; wcs->cd[2] = cd[2]; wcs->cd[3] = cd[3]; (void) matinv (2, wcs->cd, wcs->dc); /* Compute scale */ wcs->xinc = sqrt (cd[0]*cd[0] + cd[2]*cd[2]); wcs->yinc = sqrt (cd[1]*cd[1] + cd[3]*cd[3]); /* Deal with x=Dec/y=RA case */ if (wcs->coorflip) { tcd = cd[1]; cd[1] = -cd[2]; cd[2] = -tcd; } wcslibrot (wcs); wcs->wcson = 1; /* Compute image rotation */ wcsrotset (wcs); wcs->cdelt[0] = wcs->xinc; wcs->cdelt[1] = wcs->yinc; return; } /* Set scale and rotation in WCS structure from axis scale and rotation */ void wcsdeltset (wcs, cdelt1, cdelt2, crota) struct WorldCoor *wcs; /* World coordinate system structure */ double cdelt1; /* degrees/pixel in first axis (or both axes) */ double cdelt2; /* degrees/pixel in second axis if nonzero */ double crota; /* Rotation counterclockwise in degrees */ { double *pci; double crot, srot; int i, j, naxes; naxes = wcs->naxis; if (naxes > 2) naxes = 2; wcs->cdelt[0] = cdelt1; if (cdelt2 != 0.0) wcs->cdelt[1] = cdelt2; else wcs->cdelt[1] = cdelt1; wcs->xinc = wcs->cdelt[0]; wcs->yinc = wcs->cdelt[1]; pci = wcs->pc; for (i = 0; i < naxes; i++) { for (j = 0; j < naxes; j++) { if (i ==j) *pci = 1.0; else *pci = 0.0; pci++; } } wcs->rotmat = 0; /* If image is reversed, value of CROTA is flipped, too */ wcs->rot = crota; if (wcs->rot < 0.0) wcs->rot = wcs->rot + 360.0; if (wcs->rot >= 360.0) wcs->rot = wcs->rot - 360.0; crot = cos (degrad(wcs->rot)); if (cdelt1 * cdelt2 > 0) srot = sin (-degrad(wcs->rot)); else srot = sin (degrad(wcs->rot)); /* Set CD matrix */ wcs->cd[0] = wcs->cdelt[0] * crot; if (wcs->cdelt[0] < 0) wcs->cd[1] = -fabs (wcs->cdelt[1]) * srot; else wcs->cd[1] = fabs (wcs->cdelt[1]) * srot; if (wcs->cdelt[1] < 0) wcs->cd[2] = fabs (wcs->cdelt[0]) * srot; else wcs->cd[2] = -fabs (wcs->cdelt[0]) * srot; wcs->cd[3] = wcs->cdelt[1] * crot; (void) matinv (2, wcs->cd, wcs->dc); /* Set rotation matrix */ wcslibrot (wcs); /* Set image rotation and mirroring */ if (wcs->coorflip) { if (wcs->cdelt[0] < 0 && wcs->cdelt[1] > 0) { wcs->imflip = 1; wcs->imrot = wcs->rot - 90.0; if (wcs->imrot < -180.0) wcs->imrot = wcs->imrot + 360.0; wcs->pa_north = wcs->rot; wcs->pa_east = wcs->rot - 90.0; if (wcs->pa_east < -180.0) wcs->pa_east = wcs->pa_east + 360.0; } else if (wcs->cdelt[0] > 0 && wcs->cdelt[1] < 0) { wcs->imflip = 1; wcs->imrot = wcs->rot + 90.0; if (wcs->imrot > 180.0) wcs->imrot = wcs->imrot - 360.0; wcs->pa_north = wcs->rot; wcs->pa_east = wcs->rot - 90.0; if (wcs->pa_east < -180.0) wcs->pa_east = wcs->pa_east + 360.0; } else if (wcs->cdelt[0] > 0 && wcs->cdelt[1] > 0) { wcs->imflip = 0; wcs->imrot = wcs->rot + 90.0; if (wcs->imrot > 180.0) wcs->imrot = wcs->imrot - 360.0; wcs->pa_north = wcs->imrot; wcs->pa_east = wcs->rot + 90.0; if (wcs->pa_east > 180.0) wcs->pa_east = wcs->pa_east - 360.0; } else if (wcs->cdelt[0] < 0 && wcs->cdelt[1] < 0) { wcs->imflip = 0; wcs->imrot = wcs->rot - 90.0; if (wcs->imrot < -180.0) wcs->imrot = wcs->imrot + 360.0; wcs->pa_north = wcs->imrot; wcs->pa_east = wcs->rot + 90.0; if (wcs->pa_east > 180.0) wcs->pa_east = wcs->pa_east - 360.0; } } else { if (wcs->cdelt[0] < 0 && wcs->cdelt[1] > 0) { wcs->imflip = 0; wcs->imrot = wcs->rot; wcs->pa_north = wcs->rot + 90.0; if (wcs->pa_north > 180.0) wcs->pa_north = wcs->pa_north - 360.0; wcs->pa_east = wcs->rot + 180.0; if (wcs->pa_east > 180.0) wcs->pa_east = wcs->pa_east - 360.0; } else if (wcs->cdelt[0] > 0 && wcs->cdelt[1] < 0) { wcs->imflip = 0; wcs->imrot = wcs->rot + 180.0; if (wcs->imrot > 180.0) wcs->imrot = wcs->imrot - 360.0; wcs->pa_north = wcs->imrot + 90.0; if (wcs->pa_north > 180.0) wcs->pa_north = wcs->pa_north - 360.0; wcs->pa_east = wcs->imrot + 180.0; if (wcs->pa_east > 180.0) wcs->pa_east = wcs->pa_east - 360.0; } else if (wcs->cdelt[0] > 0 && wcs->cdelt[1] > 0) { wcs->imflip = 1; wcs->imrot = -wcs->rot; wcs->pa_north = wcs->imrot + 90.0; if (wcs->pa_north > 180.0) wcs->pa_north = wcs->pa_north - 360.0; wcs->pa_east = wcs->rot; } else if (wcs->cdelt[0] < 0 && wcs->cdelt[1] < 0) { wcs->imflip = 1; wcs->imrot = wcs->rot + 180.0; if (wcs->imrot > 180.0) wcs->imrot = wcs->imrot - 360.0; wcs->pa_north = wcs->imrot + 90.0; if (wcs->pa_north > 180.0) wcs->pa_north = wcs->pa_north - 360.0; wcs->pa_east = wcs->rot + 90.0; if (wcs->pa_east > 180.0) wcs->pa_east = wcs->pa_east - 360.0; } } return; } /* Set scale and rotation in WCS structure */ void wcspcset (wcs, cdelt1, cdelt2, pc) struct WorldCoor *wcs; /* World coordinate system structure */ double cdelt1; /* degrees/pixel in first axis (or both axes) */ double cdelt2; /* degrees/pixel in second axis if nonzero */ double *pc; /* Rotation matrix, ignored if NULL */ { double *pci, *pc0i; int i, j, naxes; if (pc == NULL) return; naxes = wcs->naxis; /* if (naxes > 2) naxes = 2; */ if (naxes < 1 || naxes > 9) { naxes = wcs->naxes; wcs->naxis = naxes; } wcs->cdelt[0] = cdelt1; if (cdelt2 != 0.0) wcs->cdelt[1] = cdelt2; else wcs->cdelt[1] = cdelt1; wcs->xinc = wcs->cdelt[0]; wcs->yinc = wcs->cdelt[1]; /* Set rotation matrix */ pci = wcs->pc; pc0i = pc; for (i = 0; i < naxes; i++) { for (j = 0; j < naxes; j++) { *pci = *pc0i; pci++; pc0i++; } } /* Set CD matrix */ if (naxes > 1) { wcs->cd[0] = pc[0] * wcs->cdelt[0]; wcs->cd[1] = pc[1] * wcs->cdelt[0]; wcs->cd[2] = pc[naxes] * wcs->cdelt[1]; wcs->cd[3] = pc[naxes+1] * wcs->cdelt[1]; } else { wcs->cd[0] = pc[0] * wcs->cdelt[0]; wcs->cd[1] = 0.0; wcs->cd[2] = 0.0; wcs->cd[3] = 1.0; } (void) matinv (2, wcs->cd, wcs->dc); wcs->rotmat = 1; (void)linset (&wcs->lin); wcs->wcson = 1; wcsrotset (wcs); return; } /* Set up rotation matrix for WCSLIB projection subroutines */ static void wcslibrot (wcs) struct WorldCoor *wcs; /* World coordinate system structure */ { int i, mem, naxes; naxes = wcs->naxis; if (naxes > 2) naxes = 2; if (naxes < 1 || naxes > 9) { naxes = wcs->naxes; wcs->naxis = naxes; } mem = naxes * naxes * sizeof(double); if (wcs->lin.piximg == NULL) wcs->lin.piximg = (double*)malloc(mem); if (wcs->lin.piximg != NULL) { if (wcs->lin.imgpix == NULL) wcs->lin.imgpix = (double*)malloc(mem); if (wcs->lin.imgpix != NULL) { wcs->lin.flag = LINSET; if (naxes == 2) { for (i = 0; i < 4; i++) { wcs->lin.piximg[i] = wcs->cd[i]; } } else if (naxes == 3) { for (i = 0; i < 9; i++) wcs->lin.piximg[i] = 0.0; wcs->lin.piximg[0] = wcs->cd[0]; wcs->lin.piximg[1] = wcs->cd[1]; wcs->lin.piximg[3] = wcs->cd[2]; wcs->lin.piximg[4] = wcs->cd[3]; wcs->lin.piximg[8] = 1.0; } else if (naxes == 4) { for (i = 0; i < 16; i++) wcs->lin.piximg[i] = 0.0; wcs->lin.piximg[0] = wcs->cd[0]; wcs->lin.piximg[1] = wcs->cd[1]; wcs->lin.piximg[4] = wcs->cd[2]; wcs->lin.piximg[5] = wcs->cd[3]; wcs->lin.piximg[10] = 1.0; wcs->lin.piximg[15] = 1.0; } (void) matinv (naxes, wcs->lin.piximg, wcs->lin.imgpix); wcs->lin.crpix = wcs->crpix; wcs->lin.cdelt = wcs->cdelt; wcs->lin.pc = wcs->pc; wcs->lin.flag = LINSET; } } return; } /* Compute image rotation */ void wcsrotset (wcs) struct WorldCoor *wcs; /* World coordinate system structure */ { int off; double cra, cdec, xc, xn, xe, yc, yn, ye; /* If image is one-dimensional, leave rotation angle alone */ if (wcs->nxpix < 1.5 || wcs->nypix < 1.5) { wcs->imrot = wcs->rot; wcs->pa_north = wcs->rot + 90.0; wcs->pa_east = wcs->rot + 180.0; return; } /* Do not try anything if image is LINEAR (not Cartesian projection) */ if (wcs->syswcs == WCS_LINEAR) return; wcs->xinc = fabs (wcs->xinc); wcs->yinc = fabs (wcs->yinc); /* Compute position angles of North and East in image */ xc = wcs->xrefpix; yc = wcs->yrefpix; pix2wcs (wcs, xc, yc, &cra, &cdec); if (wcs->coorflip) { wcs2pix (wcs, cra+wcs->yinc, cdec, &xe, &ye, &off); wcs2pix (wcs, cra, cdec+wcs->xinc, &xn, &yn, &off); } else { wcs2pix (wcs, cra+wcs->xinc, cdec, &xe, &ye, &off); wcs2pix (wcs, cra, cdec+wcs->yinc, &xn, &yn, &off); } wcs->pa_north = raddeg (atan2 (yn-yc, xn-xc)); if (wcs->pa_north < -90.0) wcs->pa_north = wcs->pa_north + 360.0; wcs->pa_east = raddeg (atan2 (ye-yc, xe-xc)); if (wcs->pa_east < -90.0) wcs->pa_east = wcs->pa_east + 360.0; /* Compute image rotation angle from North */ if (wcs->pa_north < -90.0) wcs->imrot = 270.0 + wcs->pa_north; else wcs->imrot = wcs->pa_north - 90.0; /* Compute CROTA */ if (wcs->coorflip) { wcs->rot = wcs->imrot + 90.0; if (wcs->rot < 0.0) wcs->rot = wcs->rot + 360.0; } else wcs->rot = wcs->imrot; if (wcs->rot < 0.0) wcs->rot = wcs->rot + 360.0; if (wcs->rot >= 360.0) wcs->rot = wcs->rot - 360.0; /* Set image mirror flag based on axis orientation */ wcs->imflip = 0; if (wcs->pa_east - wcs->pa_north < -80.0 && wcs->pa_east - wcs->pa_north > -100.0) wcs->imflip = 1; if (wcs->pa_east - wcs->pa_north < 280.0 && wcs->pa_east - wcs->pa_north > 260.0) wcs->imflip = 1; if (wcs->pa_north - wcs->pa_east > 80.0 && wcs->pa_north - wcs->pa_east < 100.0) wcs->imflip = 1; if (wcs->coorflip) { if (wcs->imflip) wcs->yinc = -wcs->yinc; } else { if (!wcs->imflip) wcs->xinc = -wcs->xinc; } return; } /* Return 1 if WCS structure is filled, else 0 */ int iswcs (wcs) struct WorldCoor *wcs; /* World coordinate system structure */ { if (wcs == NULL) return (0); else return (wcs->wcson); } /* Return 0 if WCS structure is filled, else 1 */ int nowcs (wcs) struct WorldCoor *wcs; /* World coordinate system structure */ { if (wcs == NULL) return (1); else return (!wcs->wcson); } /* Reset the center of a WCS structure */ void wcsshift (wcs,rra,rdec,coorsys) struct WorldCoor *wcs; /* World coordinate system structure */ double rra; /* Reference pixel right ascension in degrees */ double rdec; /* Reference pixel declination in degrees */ char *coorsys; /* FK4 or FK5 coordinates (1950 or 2000) */ { if (nowcs (wcs)) return; /* Approximate world coordinate system from a known plate scale */ wcs->crval[0] = rra; wcs->crval[1] = rdec; wcs->xref = wcs->crval[0]; wcs->yref = wcs->crval[1]; /* Coordinate reference frame */ strcpy (wcs->radecsys,coorsys); wcs->syswcs = wcscsys (coorsys); if (wcs->syswcs == WCS_B1950) wcs->equinox = 1950.0; else wcs->equinox = 2000.0; return; } /* Print position of WCS center, if WCS is set */ void wcscent (wcs) struct WorldCoor *wcs; /* World coordinate system structure */ { double xpix,ypix, xpos1, xpos2, ypos1, ypos2; char wcstring[32]; double width, height, secpix, secpixh, secpixw; int lstr = 32; if (nowcs (wcs)) (void)fprintf (stderr,"No WCS information available\n"); else { if (wcs->prjcode == WCS_DSS) (void)fprintf (stderr,"WCS plate center %s\n", wcs->center); xpix = 0.5 * wcs->nxpix; ypix = 0.5 * wcs->nypix; (void) pix2wcst (wcs,xpix,ypix,wcstring, lstr); (void)fprintf (stderr,"WCS center %s %s %s %s at pixel (%.2f,%.2f)\n", wcs->ctype[0],wcs->ctype[1],wcstring,wcs->ptype,xpix,ypix); /* Image width */ (void) pix2wcs (wcs,1.0,ypix,&xpos1,&ypos1); (void) pix2wcs (wcs,wcs->nxpix,ypix,&xpos2,&ypos2); if (wcs->syswcs == WCS_LINEAR) { width = xpos2 - xpos1; if (width < 100.0) (void)fprintf (stderr, "WCS width = %.5f %s ",width, wcs->units[0]); else (void)fprintf (stderr, "WCS width = %.3f %s ",width, wcs->units[0]); } else { width = wcsdist (xpos1,ypos1,xpos2,ypos2); if (width < 1/60.0) (void)fprintf (stderr, "WCS width = %.2f arcsec ",width*3600.0); else if (width < 1.0) (void)fprintf (stderr, "WCS width = %.2f arcmin ",width*60.0); else (void)fprintf (stderr, "WCS width = %.3f degrees ",width); } secpixw = width / (wcs->nxpix - 1.0); /* Image height */ (void) pix2wcs (wcs,xpix,1.0,&xpos1,&ypos1); (void) pix2wcs (wcs,xpix,wcs->nypix,&xpos2,&ypos2); if (wcs->syswcs == WCS_LINEAR) { height = ypos2 - ypos1; if (height < 100.0) (void)fprintf (stderr, " height = %.5f %s ",height, wcs->units[1]); else (void)fprintf (stderr, " height = %.3f %s ",height, wcs->units[1]); } else { height = wcsdist (xpos1,ypos1,xpos2,ypos2); if (height < 1/60.0) (void) fprintf (stderr, " height = %.2f arcsec",height*3600.0); else if (height < 1.0) (void) fprintf (stderr, " height = %.2f arcmin",height*60.0); else (void) fprintf (stderr, " height = %.3f degrees",height); } secpixh = height / (wcs->nypix - 1.0); /* Image scale */ if (wcs->syswcs == WCS_LINEAR) { (void) fprintf (stderr,"\n"); (void) fprintf (stderr,"WCS %.5f %s/pixel, %.5f %s/pixel\n", wcs->xinc,wcs->units[0],wcs->yinc,wcs->units[1]); } else { if (wcs->xinc != 0.0 && wcs->yinc != 0.0) secpix = (fabs(wcs->xinc) + fabs(wcs->yinc)) * 0.5 * 3600.0; else if (secpixh > 0.0 && secpixw > 0.0) secpix = (secpixw + secpixh) * 0.5 * 3600.0; else if (wcs->xinc != 0.0 || wcs->yinc != 0.0) secpix = (fabs(wcs->xinc) + fabs(wcs->yinc)) * 3600.0; else secpix = (secpixw + secpixh) * 3600.0; if (secpix < 100.0) (void) fprintf (stderr, " %.3f arcsec/pixel\n",secpix); else if (secpix < 3600.0) (void) fprintf (stderr, " %.3f arcmin/pixel\n",secpix/60.0); else (void) fprintf (stderr, " %.3f degrees/pixel\n",secpix/3600.0); } } return; } /* Return RA and Dec of image center, plus size in RA and Dec */ void wcssize (wcs, cra, cdec, dra, ddec) struct WorldCoor *wcs; /* World coordinate system structure */ double *cra; /* Right ascension of image center (deg) (returned) */ double *cdec; /* Declination of image center (deg) (returned) */ double *dra; /* Half-width in right ascension (deg) (returned) */ double *ddec; /* Half-width in declination (deg) (returned) */ { double width, height; /* Find right ascension and declination of coordinates */ if (iswcs(wcs)) { wcsfull (wcs, cra, cdec, &width, &height); *dra = 0.5 * width / cos (degrad (*cdec)); *ddec = 0.5 * height; } else { *cra = 0.0; *cdec = 0.0; *dra = 0.0; *ddec = 0.0; } return; } /* Return RA and Dec of image center, plus size in degrees */ void wcsfull (wcs, cra, cdec, width, height) struct WorldCoor *wcs; /* World coordinate system structure */ double *cra; /* Right ascension of image center (deg) (returned) */ double *cdec; /* Declination of image center (deg) (returned) */ double *width; /* Width in degrees (returned) */ double *height; /* Height in degrees (returned) */ { double xpix, ypix, xpos1, xpos2, ypos1, ypos2, xcpix, ycpix; double xcent, ycent; /* Find right ascension and declination of coordinates */ if (iswcs(wcs)) { xcpix = (0.5 * wcs->nxpix) + 0.5; ycpix = (0.5 * wcs->nypix) + 0.5; (void) pix2wcs (wcs,xcpix,ycpix,&xcent, &ycent); *cra = xcent; *cdec = ycent; /* Compute image width in degrees */ xpix = 0.500001; (void) pix2wcs (wcs,xpix,ycpix,&xpos1,&ypos1); xpix = wcs->nxpix + 0.499999; (void) pix2wcs (wcs,xpix,ycpix,&xpos2,&ypos2); if (strncmp (wcs->ptype,"LINEAR",6) && strncmp (wcs->ptype,"PIXEL",5)) { *width = wcsdist (xpos1,ypos1,xpos2,ypos2); } else *width = sqrt (((ypos2-ypos1) * (ypos2-ypos1)) + ((xpos2-xpos1) * (xpos2-xpos1))); /* Compute image height in degrees */ ypix = 0.5; (void) pix2wcs (wcs,xcpix,ypix,&xpos1,&ypos1); ypix = wcs->nypix + 0.5; (void) pix2wcs (wcs,xcpix,ypix,&xpos2,&ypos2); if (strncmp (wcs->ptype,"LINEAR",6) && strncmp (wcs->ptype,"PIXEL",5)) *height = wcsdist (xpos1,ypos1,xpos2,ypos2); else *height = sqrt (((ypos2-ypos1) * (ypos2-ypos1)) + ((xpos2-xpos1) * (xpos2-xpos1))); } else { *cra = 0.0; *cdec = 0.0; *width = 0.0; *height = 0.0; } return; } /* Return minimum and maximum RA and Dec of image in degrees */ void wcsrange (wcs, ra1, ra2, dec1, dec2) struct WorldCoor *wcs; /* World coordinate system structure */ double *ra1; /* Minimum right ascension of image (deg) (returned) */ double *ra2; /* Maximum right ascension of image (deg) (returned) */ double *dec1; /* Minimum declination of image (deg) (returned) */ double *dec2; /* Maximum declination of image (deg) (returned) */ { double xpos1, xpos2, xpos3, xpos4, ypos1, ypos2, ypos3, ypos4, temp; if (iswcs(wcs)) { /* Compute image corner coordinates in degrees */ (void) pix2wcs (wcs,1.0,1.0,&xpos1,&ypos1); (void) pix2wcs (wcs,1.0,wcs->nypix,&xpos2,&ypos2); (void) pix2wcs (wcs,wcs->nxpix,1.0,&xpos3,&ypos3); (void) pix2wcs (wcs,wcs->nxpix,wcs->nypix,&xpos4,&ypos4); /* Find minimum right ascension or longitude */ *ra1 = xpos1; if (xpos2 < *ra1) *ra1 = xpos2; if (xpos3 < *ra1) *ra1 = xpos3; if (xpos4 < *ra1) *ra1 = xpos4; /* Find maximum right ascension or longitude */ *ra2 = xpos1; if (xpos2 > *ra2) *ra2 = xpos2; if (xpos3 > *ra2) *ra2 = xpos3; if (xpos4 > *ra2) *ra2 = xpos4; if (wcs->syswcs != WCS_LINEAR && wcs->syswcs != WCS_XY) { if (*ra2 - *ra1 > 180.0) { temp = *ra1; *ra1 = *ra2; *ra2 = temp; } } /* Find minimum declination or latitude */ *dec1 = ypos1; if (ypos2 < *dec1) *dec1 = ypos2; if (ypos3 < *dec1) *dec1 = ypos3; if (ypos4 < *dec1) *dec1 = ypos4; /* Find maximum declination or latitude */ *dec2 = ypos1; if (ypos2 > *dec2) *dec2 = ypos2; if (ypos3 > *dec2) *dec2 = ypos3; if (ypos4 > *dec2) *dec2 = ypos4; } else { *ra1 = 0.0; *ra2 = 0.0; *dec1 = 0.0; *dec2 = 0.0; } return; } /* Compute distance in degrees between two sky coordinates */ double wcsdist (x1,y1,x2,y2) double x1,y1; /* (RA,Dec) or (Long,Lat) in degrees */ double x2,y2; /* (RA,Dec) or (Long,Lat) in degrees */ { double r, diffi; double pos1[3], pos2[3], w, diff; int i; /* Convert two vectors to direction cosines */ r = 1.0; d2v3 (x1, y1, r, pos1); d2v3 (x2, y2, r, pos2); /* Modulus squared of half the difference vector */ w = 0.0; for (i = 0; i < 3; i++) { diffi = pos1[i] - pos2[i]; w = w + (diffi * diffi); } w = w / 4.0; if (w > 1.0) w = 1.0; /* Angle beween the vectors */ diff = 2.0 * atan2 (sqrt (w), sqrt (1.0 - w)); diff = raddeg (diff); return (diff); } /* Compute distance in degrees between two sky coordinates */ double wcsdist1 (x1,y1,x2,y2) double x1,y1; /* (RA,Dec) or (Long,Lat) in degrees */ double x2,y2; /* (RA,Dec) or (Long,Lat) in degrees */ { double d1, d2, r; double pos1[3], pos2[3], w, diff; int i; /* Convert two vectors to direction cosines */ r = 1.0; d2v3 (x1, y1, r, pos1); d2v3 (x2, y2, r, pos2); w = 0.0; d1 = 0.0; d2 = 0.0; for (i = 0; i < 3; i++) { w = w + (pos1[i] * pos2[i]); d1 = d1 + (pos1[i] * pos1[i]); d2 = d2 + (pos2[i] * pos2[i]); } diff = acosdeg (w / (sqrt (d1) * sqrt (d2))); return (diff); } /* Compute distance in degrees between two sky coordinates away from pole */ double wcsdiff (x1,y1,x2,y2) double x1,y1; /* (RA,Dec) or (Long,Lat) in degrees */ double x2,y2; /* (RA,Dec) or (Long,Lat) in degrees */ { double xdiff, ydiff, ycos, diff; ycos = cos (degrad ((y2 + y1) / 2.0)); xdiff = x2 - x1; if (xdiff > 180.0) xdiff = xdiff - 360.0; if (xdiff < -180.0) xdiff = xdiff + 360.0; xdiff = xdiff / ycos; ydiff = (y2 - y1); diff = sqrt ((xdiff * xdiff) + (ydiff * ydiff)); return (diff); } /* Initialize catalog search command set by -wcscom */ void wcscominit (wcs, i, command) struct WorldCoor *wcs; /* World coordinate system structure */ int i; /* Number of command (0-9) to initialize */ char *command; /* command with %s where coordinates will go */ { int lcom,icom; if (iswcs(wcs)) { lcom = strlen (command); if (lcom > 0) { if (wcs->command_format[i] != NULL) free (wcs->command_format[i]); wcs->command_format[i] = (char *) calloc (lcom+2, 1); if (wcs->command_format[i] == NULL) return; for (icom = 0; icom < lcom; icom++) { if (command[icom] == '_') wcs->command_format[i][icom] = ' '; else wcs->command_format[i][icom] = command[icom]; } wcs->command_format[i][lcom] = 0; } } return; } /* Execute Unix command with world coordinates (from x,y) and/or filename */ void wcscom ( wcs, i, filename, xfile, yfile, wcstring ) struct WorldCoor *wcs; /* World coordinate system structure */ int i; /* Number of command (0-9) to execute */ char *filename; /* Image file name */ double xfile,yfile; /* Image pixel coordinates for WCS command */ char *wcstring; /* WCS String from pix2wcst() */ { char command[120]; char comform[120]; char xystring[32]; char *fileform, *posform, *imform; int ier; if (nowcs (wcs)) { (void)fprintf(stderr,"WCSCOM: no WCS\n"); return; } if (wcs->command_format[i] != NULL) strcpy (comform, wcs->command_format[i]); else strcpy (comform, "sgsc -ah %s"); if (comform[0] > 0) { /* Create and execute search command */ fileform = strsrch (comform,"%f"); imform = strsrch (comform,"%x"); posform = strsrch (comform,"%s"); if (imform != NULL) { *(imform+1) = 's'; (void)sprintf (xystring, "%.2f %.2f", xfile, yfile); if (fileform != NULL) { *(fileform+1) = 's'; if (posform == NULL) { if (imform < fileform) (void)sprintf(command, comform, xystring, filename); else (void)sprintf(command, comform, filename, xystring); } else if (fileform < posform) { if (imform < fileform) (void)sprintf(command, comform, xystring, filename, wcstring); else if (imform < posform) (void)sprintf(command, comform, filename, xystring, wcstring); else (void)sprintf(command, comform, filename, wcstring, xystring); } else if (imform < posform) (void)sprintf(command, comform, xystring, wcstring, filename); else if (imform < fileform) (void)sprintf(command, comform, wcstring, xystring, filename); else (void)sprintf(command, comform, wcstring, filename, xystring); } else if (posform == NULL) (void)sprintf(command, comform, xystring); else if (imform < posform) (void)sprintf(command, comform, xystring, wcstring); else (void)sprintf(command, comform, wcstring, xystring); } else if (fileform != NULL) { *(fileform+1) = 's'; if (posform == NULL) (void)sprintf(command, comform, filename); else if (fileform < posform) (void)sprintf(command, comform, filename, wcstring); else (void)sprintf(command, comform, wcstring, filename); } else (void)sprintf(command, comform, wcstring); ier = system (command); if (ier) (void)fprintf(stderr,"WCSCOM: %s failed %d\n",command,ier); } return; } /* Initialize WCS output coordinate system for use by PIX2WCS() */ void wcsoutinit (wcs, coorsys) struct WorldCoor *wcs; /* World coordinate system structure */ char *coorsys; /* Input world coordinate system: FK4, FK5, B1950, J2000, GALACTIC, ECLIPTIC fk4, fk5, b1950, j2000, galactic, ecliptic */ { int sysout, i; if (nowcs (wcs)) return; /* If argument is null, set to image system and equinox */ if (coorsys == NULL || strlen (coorsys) < 1 || !strcmp(coorsys,"IMSYS") || !strcmp(coorsys,"imsys")) { sysout = wcs->syswcs; strcpy (wcs->radecout, wcs->radecsys); wcs->eqout = wcs->equinox; if (sysout == WCS_B1950) { if (wcs->eqout != 1950.0) { wcs->radecout[0] = 'B'; sprintf (wcs->radecout+1,"%.4f", wcs->equinox); i = strlen(wcs->radecout) - 1; if (wcs->radecout[i] == '0') wcs->radecout[i] = (char)0; i = strlen(wcs->radecout) - 1; if (wcs->radecout[i] == '0') wcs->radecout[i] = (char)0; i = strlen(wcs->radecout) - 1; if (wcs->radecout[i] == '0') wcs->radecout[i] = (char)0; } else strcpy (wcs->radecout, "B1950"); } else if (sysout == WCS_J2000) { if (wcs->eqout != 2000.0) { wcs->radecout[0] = 'J'; sprintf (wcs->radecout+1,"%.4f", wcs->equinox); i = strlen(wcs->radecout) - 1; if (wcs->radecout[i] == '0') wcs->radecout[i] = (char)0; i = strlen(wcs->radecout) - 1; if (wcs->radecout[i] == '0') wcs->radecout[i] = (char)0; i = strlen(wcs->radecout) - 1; if (wcs->radecout[i] == '0') wcs->radecout[i] = (char)0; } else strcpy (wcs->radecout, "J2000"); } } /* Ignore new coordinate system if it is not supported */ else { if ((sysout = wcscsys (coorsys)) < 0) return; /* Do not try to convert linear or alt-az coordinates */ if (sysout != wcs->syswcs && (wcs->syswcs == WCS_LINEAR || wcs->syswcs == WCS_ALTAZ)) return; strcpy (wcs->radecout, coorsys); wcs->eqout = wcsceq (coorsys); } wcs->sysout = sysout; if (wcs->wcson) { /* Set output in degrees flag and number of decimal places */ if (wcs->sysout == WCS_GALACTIC || wcs->sysout == WCS_ECLIPTIC || wcs->sysout == WCS_PLANET) { wcs->degout = 1; wcs->ndec = 5; } else if (wcs->sysout == WCS_ALTAZ) { wcs->degout = 1; wcs->ndec = 5; } else if (wcs->sysout == WCS_NPOLE || wcs->sysout == WCS_SPA) { wcs->degout = 1; wcs->ndec = 5; } else { wcs->degout = 0; wcs->ndec = 3; } } return; } /* Return current value of WCS output coordinate system set by -wcsout */ char * getwcsout(wcs) struct WorldCoor *wcs; /* World coordinate system structure */ { if (nowcs (wcs)) return (NULL); else return(wcs->radecout); } /* Initialize WCS input coordinate system for use by WCS2PIX() */ void wcsininit (wcs, coorsys) struct WorldCoor *wcs; /* World coordinate system structure */ char *coorsys; /* Input world coordinate system: FK4, FK5, B1950, J2000, GALACTIC, ECLIPTIC fk4, fk5, b1950, j2000, galactic, ecliptic */ { int sysin, i; if (nowcs (wcs)) return; /* If argument is null, set to image system and equinox */ if (coorsys == NULL || strlen (coorsys) < 1) { wcs->sysin = wcs->syswcs; strcpy (wcs->radecin, wcs->radecsys); wcs->eqin = wcs->equinox; if (wcs->sysin == WCS_B1950) { if (wcs->eqin != 1950.0) { wcs->radecin[0] = 'B'; sprintf (wcs->radecin+1,"%.4f", wcs->equinox); i = strlen(wcs->radecin) - 1; if (wcs->radecin[i] == '0') wcs->radecin[i] = (char)0; i = strlen(wcs->radecin) - 1; if (wcs->radecin[i] == '0') wcs->radecin[i] = (char)0; i = strlen(wcs->radecin) - 1; if (wcs->radecin[i] == '0') wcs->radecin[i] = (char)0; } else strcpy (wcs->radecin, "B1950"); } else if (wcs->sysin == WCS_J2000) { if (wcs->eqin != 2000.0) { wcs->radecin[0] = 'J'; sprintf (wcs->radecin+1,"%.4f", wcs->equinox); i = strlen(wcs->radecin) - 1; if (wcs->radecin[i] == '0') wcs->radecin[i] = (char)0; i = strlen(wcs->radecin) - 1; if (wcs->radecin[i] == '0') wcs->radecin[i] = (char)0; i = strlen(wcs->radecin) - 1; if (wcs->radecin[i] == '0') wcs->radecin[i] = (char)0; } else strcpy (wcs->radecin, "J2000"); } } /* Ignore new coordinate system if it is not supported */ if ((sysin = wcscsys (coorsys)) < 0) return; wcs->sysin = sysin; wcs->eqin = wcsceq (coorsys); strcpy (wcs->radecin, coorsys); return; } /* Return current value of WCS input coordinate system set by wcsininit */ char * getwcsin (wcs) struct WorldCoor *wcs; /* World coordinate system structure */ { if (nowcs (wcs)) return (NULL); else return (wcs->radecin); } /* Set WCS output in degrees or hh:mm:ss dd:mm:ss, returning old flag value */ int setwcsdeg(wcs, new) struct WorldCoor *wcs; /* World coordinate system structure */ int new; /* 1: degrees, 0: h:m:s d:m:s */ { int old; if (nowcs (wcs)) return (0); old = wcs->degout; wcs->degout = new; if (new == 1 && old == 0 && wcs->ndec == 3) wcs->ndec = 6; if (new == 0 && old == 1 && wcs->ndec == 5) wcs->ndec = 3; return(old); } /* Set number of decimal places in pix2wcst output string */ int wcsndec (wcs, ndec) struct WorldCoor *wcs; /* World coordinate system structure */ int ndec; /* Number of decimal places in output string */ /* If < 0, return current unchanged value */ { if (nowcs (wcs)) return (0); else if (ndec >= 0) wcs->ndec = ndec; return (wcs->ndec); } /* Return current value of coordinate system */ char * getradecsys(wcs) struct WorldCoor *wcs; /* World coordinate system structure */ { if (nowcs (wcs)) return (NULL); else return (wcs->radecsys); } /* Set output string mode for LINEAR coordinates */ void setwcslin (wcs, mode) struct WorldCoor *wcs; /* World coordinate system structure */ int mode; /* mode = 0: x y linear mode = 1: x units x units mode = 2: x y linear units */ { if (iswcs (wcs)) wcs->linmode = mode; return; } /* Convert pixel coordinates to World Coordinate string */ int pix2wcst (wcs, xpix, ypix, wcstring, lstr) struct WorldCoor *wcs; /* World coordinate system structure */ double xpix,ypix; /* Image coordinates in pixels */ char *wcstring; /* World coordinate string (returned) */ int lstr; /* Length of world coordinate string (returned) */ { double xpos,ypos; char rastr[32], decstr[32]; int minlength, lunits, lstring; if (nowcs (wcs)) { if (lstr > 0) wcstring[0] = 0; return(0); } pix2wcs (wcs,xpix,ypix,&xpos,&ypos); /* If point is off scale, set string accordingly */ if (wcs->offscl) { (void)sprintf (wcstring,"Off map"); return (1); } /* Print coordinates in degrees */ else if (wcs->degout == 1) { minlength = 9 + (2 * wcs->ndec); if (lstr > minlength) { deg2str (rastr, 32, xpos, wcs->ndec); deg2str (decstr, 32, ypos, wcs->ndec); if (wcs->tabsys) (void)sprintf (wcstring,"%s %s", rastr, decstr); else (void)sprintf (wcstring,"%s %s", rastr, decstr); lstr = lstr - minlength; } else { if (wcs->tabsys) strncpy (wcstring,"********* **********",lstr); else strncpy (wcstring,"*******************",lstr); lstr = 0; } } /* print coordinates in sexagesimal notation */ else if (wcs->degout == 0) { minlength = 18 + (2 * wcs->ndec); if (lstr > minlength) { if (wcs->sysout == WCS_J2000 || wcs->sysout == WCS_B1950) { ra2str (rastr, 32, xpos, wcs->ndec); dec2str (decstr, 32, ypos, wcs->ndec-1); } else { dec2str (rastr, 32, xpos, wcs->ndec); dec2str (decstr, 32, ypos, wcs->ndec); } if (wcs->tabsys) { (void)sprintf (wcstring,"%s %s", rastr, decstr); } else { (void)sprintf (wcstring,"%s %s", rastr, decstr); } lstr = lstr - minlength; } else { if (wcs->tabsys) { strncpy (wcstring,"************* *************",lstr); } else { strncpy (wcstring,"**************************",lstr); } lstr = 0; } } /* Label galactic coordinates */ if (wcs->sysout == WCS_GALACTIC) { if (lstr > 9 && wcs->printsys) { if (wcs->tabsys) strcat (wcstring," galactic"); else strcat (wcstring," galactic"); } } /* Label ecliptic coordinates */ else if (wcs->sysout == WCS_ECLIPTIC) { if (lstr > 9 && wcs->printsys) { if (wcs->tabsys) strcat (wcstring," ecliptic"); else strcat (wcstring," ecliptic"); } } /* Label planet coordinates */ else if (wcs->sysout == WCS_PLANET) { if (lstr > 9 && wcs->printsys) { if (wcs->tabsys) strcat (wcstring," planet"); else strcat (wcstring," planet"); } } /* Label alt-az coordinates */ else if (wcs->sysout == WCS_ALTAZ) { if (lstr > 7 && wcs->printsys) { if (wcs->tabsys) strcat (wcstring," alt-az"); else strcat (wcstring," alt-az"); } } /* Label north pole angle coordinates */ else if (wcs->sysout == WCS_NPOLE) { if (lstr > 7 && wcs->printsys) { if (wcs->tabsys) strcat (wcstring," long-npa"); else strcat (wcstring," long-npa"); } } /* Label south pole angle coordinates */ else if (wcs->sysout == WCS_SPA) { if (lstr > 7 && wcs->printsys) { if (wcs->tabsys) strcat (wcstring," long-spa"); else strcat (wcstring," long-spa"); } } /* Label equatorial coordinates */ else if (wcs->sysout==WCS_B1950 || wcs->sysout==WCS_J2000) { if (lstr > (int) strlen(wcs->radecout)+1 && wcs->printsys) { if (wcs->tabsys) strcat (wcstring," "); else strcat (wcstring," "); strcat (wcstring, wcs->radecout); } } /* Output linear coordinates */ else { num2str (rastr, xpos, 0, wcs->ndec); num2str (decstr, ypos, 0, wcs->ndec); lstring = strlen (rastr) + strlen (decstr) + 1; lunits = strlen (wcs->units[0]) + strlen (wcs->units[1]) + 2; if (wcs->syswcs == WCS_LINEAR && wcs->linmode == 1) { if (lstr > lstring + lunits) { if (strlen (wcs->units[0]) > 0) { strcat (rastr, " "); strcat (rastr, wcs->units[0]); } if (strlen (wcs->units[1]) > 0) { strcat (decstr, " "); strcat (decstr, wcs->units[1]); } lstring = lstring + lunits; } } if (lstr > lstring) { if (wcs->tabsys) (void)sprintf (wcstring,"%s %s", rastr, decstr); else (void)sprintf (wcstring,"%s %s", rastr, decstr); } else { if (wcs->tabsys) strncpy (wcstring,"********** *********",lstr); else strncpy (wcstring,"*******************",lstr); } if (wcs->syswcs == WCS_LINEAR && wcs->linmode != 1 && lstr > lstring + 7) strcat (wcstring, " linear"); if (wcs->syswcs == WCS_LINEAR && wcs->linmode == 2 && lstr > lstring + lunits + 7) { if (strlen (wcs->units[0]) > 0) { strcat (wcstring, " "); strcat (wcstring, wcs->units[0]); } if (strlen (wcs->units[1]) > 0) { strcat (wcstring, " "); strcat (wcstring, wcs->units[1]); } } } return (1); } /* Convert pixel coordinates to World Coordinates */ void pix2wcs (wcs,xpix,ypix,xpos,ypos) struct WorldCoor *wcs; /* World coordinate system structure */ double xpix,ypix; /* x and y image coordinates in pixels */ double *xpos,*ypos; /* RA and Dec in degrees (returned) */ { double xpi, ypi, xp, yp; double eqin, eqout; int wcspos(); if (nowcs (wcs)) return; wcs->xpix = xpix; wcs->ypix = ypix; wcs->zpix = zpix; wcs->offscl = 0; /* If this WCS is converted from another WCS rather than pixels, convert now */ if (wcs->wcs != NULL) { pix2wcs (wcs->wcs, xpix, ypix, &xpi, &ypi); } else { pix2foc (wcs, xpix, ypix, &xpi, &ypi); } /* Convert image coordinates to sky coordinates */ /* Use Digitized Sky Survey plate fit */ if (wcs->prjcode == WCS_DSS) { if (dsspos (xpi, ypi, wcs, &xp, &yp)) wcs->offscl = 1; } /* Use SAO plate fit */ else if (wcs->prjcode == WCS_PLT) { if (platepos (xpi, ypi, wcs, &xp, &yp)) wcs->offscl = 1; } /* Use NOAO IRAF corrected plane tangent projection */ else if (wcs->prjcode == WCS_TNX) { if (tnxpos (xpi, ypi, wcs, &xp, &yp)) wcs->offscl = 1; } /* Use NOAO IRAF corrected zenithal projection */ else if (wcs->prjcode == WCS_ZPX) { if (zpxpos (xpi, ypi, wcs, &xp, &yp)) wcs->offscl = 1; } /* Use Classic AIPS projections */ else if (wcs->wcsproj == WCS_OLD || wcs->prjcode <= 0) { if (worldpos (xpi, ypi, wcs, &xp, &yp)) wcs->offscl = 1; } /* Use Mark Calabretta's WCSLIB projections */ else if (wcspos (xpi, ypi, wcs, &xp, &yp)) wcs->offscl = 1; /* Do not change coordinates if offscale */ if (wcs->offscl) { *xpos = 0.0; *ypos = 0.0; } else { /* Convert coordinates to output system, if not LINEAR */ if (wcs->prjcode > 0) { /* Convert coordinates to desired output system */ eqin = wcs->equinox; eqout = wcs->eqout; wcscon (wcs->syswcs,wcs->sysout,eqin,eqout,&xp,&yp,wcs->epoch); } if (wcs->latbase == 90) yp = 90.0 - yp; else if (wcs->latbase == -90) yp = yp - 90.0; wcs->xpos = xp; wcs->ypos = yp; *xpos = xp; *ypos = yp; } /* Keep RA/longitude within range if spherical coordinate output (Not LINEAR or XY) */ if (wcs->sysout > 0 && wcs->sysout != 6 && wcs->sysout != 10) { if (*xpos < 0.0) *xpos = *xpos + 360.0; else if (*xpos > 360.0) *xpos = *xpos - 360.0; } return; } /* Convert World Coordinates to pixel coordinates */ void wcs2pix (wcs, xpos, ypos, xpix, ypix, offscl) struct WorldCoor *wcs; /* World coordinate system structure */ double xpos,ypos; /* World coordinates in degrees */ double *xpix,*ypix; /* Image coordinates in pixels */ int *offscl; /* 0 if within bounds, else off scale */ { wcsc2pix (wcs, xpos, ypos, wcs->radecin, xpix, ypix, offscl); return; } /* Convert World Coordinates to pixel coordinates */ void wcsc2pix (wcs, xpos, ypos, coorsys, xpix, ypix, offscl) struct WorldCoor *wcs; /* World coordinate system structure */ double xpos,ypos; /* World coordinates in degrees */ char *coorsys; /* Input world coordinate system: FK4, FK5, B1950, J2000, GALACTIC, ECLIPTIC fk4, fk5, b1950, j2000, galactic, ecliptic * If NULL, use image WCS */ double *xpix,*ypix; /* Image coordinates in pixels */ int *offscl; /* 0 if within bounds, else off scale */ { double xp, yp, xpi, ypi; double eqin, eqout; int sysin; int wcspix(); if (nowcs (wcs)) return; *offscl = 0; xp = xpos; yp = ypos; if (wcs->latbase == 90) yp = 90.0 - yp; else if (wcs->latbase == -90) yp = yp - 90.0; if (coorsys == NULL) { sysin = wcs->syswcs; eqin = wcs->equinox; } else { sysin = wcscsys (coorsys); eqin = wcsceq (coorsys); } wcs->zpix = 1.0; /* Convert coordinates to same system as image */ if (sysin > 0 && sysin != 6 && sysin != 10) { eqout = wcs->equinox; wcscon (sysin, wcs->syswcs, eqin, eqout, &xp, &yp, wcs->epoch); } /* Convert sky coordinates to image coordinates */ /* Use Digitized Sky Survey plate fit */ if (wcs->prjcode == WCS_DSS) { if (dsspix (xp, yp, wcs, &xpi, &ypi)) *offscl = 1; } /* Use SAO polynomial plate fit */ else if (wcs->prjcode == WCS_PLT) { if (platepix (xp, yp, wcs, &xpi, &ypi)) *offscl = 1; } /* Use NOAO IRAF corrected plane tangent projection */ else if (wcs->prjcode == WCS_TNX) { if (tnxpix (xp, yp, wcs, &xpi, &ypi)) *offscl = 1; } /* Use NOAO IRAF corrected zenithal projection */ else if (wcs->prjcode == WCS_ZPX) { if (zpxpix (xp, yp, wcs, &xpi, &ypi)) *offscl = 1; } /* Use Classic AIPS projections */ else if (wcs->wcsproj == WCS_OLD || wcs->prjcode <= 0) { if (worldpix (xp, yp, wcs, &xpi, &ypi)) *offscl = 1; } /* Use Mark Calabretta's WCSLIB projections */ else if (wcspix (xp, yp, wcs, &xpi, &ypi)) { *offscl = 1; } /* If this WCS is converted from another WCS rather than pixels, convert now */ if (wcs->wcs != NULL) { wcsc2pix (wcs->wcs, xpi, ypi, NULL, xpix, ypix, offscl); } else { foc2pix (wcs, xpi, ypi, xpix, ypix); /* Set off-scale flag to 2 if off image but within bounds of projection */ if (!*offscl) { if (*xpix < 0.5 || *ypix < 0.5) *offscl = 2; else if (*xpix > wcs->nxpix + 0.5 || *ypix > wcs->nypix + 0.5) *offscl = 2; } } wcs->offscl = *offscl; wcs->xpos = xpos; wcs->ypos = ypos; wcs->xpix = *xpix; wcs->ypix = *ypix; return; } int wcspos (xpix, ypix, wcs, xpos, ypos) /* Input: */ double xpix; /* x pixel number (RA or long without rotation) */ double ypix; /* y pixel number (dec or lat without rotation) */ struct WorldCoor *wcs; /* WCS parameter structure */ /* Output: */ double *xpos; /* x (RA) coordinate (deg) */ double *ypos; /* y (dec) coordinate (deg) */ { int offscl; int i; int wcsrev(); double wcscrd[4], imgcrd[4], pixcrd[4]; double phi, theta; *xpos = 0.0; *ypos = 0.0; pixcrd[0] = xpix; pixcrd[1] = ypix; if (wcs->prjcode == WCS_CSC || wcs->prjcode == WCS_QSC || wcs->prjcode == WCS_TSC) pixcrd[2] = (double) (izpix + 1); else pixcrd[2] = zpix; pixcrd[3] = 1.0; for (i = 0; i < 4; i++) imgcrd[i] = 0.0; offscl = wcsrev ((void *)&wcs->ctype, &wcs->wcsl, pixcrd, &wcs->lin, imgcrd, &wcs->prj, &phi, &theta, wcs->crval, &wcs->cel, wcscrd); if (offscl == 0) { *xpos = wcscrd[wcs->wcsl.lng]; *ypos = wcscrd[wcs->wcsl.lat]; } return (offscl); } int wcspix (xpos, ypos, wcs, xpix, ypix) /* Input: */ double xpos; /* x (RA) coordinate (deg) */ double ypos; /* y (dec) coordinate (deg) */ struct WorldCoor *wcs; /* WCS parameter structure */ /* Output: */ double *xpix; /* x pixel number (RA or long without rotation) */ double *ypix; /* y pixel number (dec or lat without rotation) */ { int offscl; int wcsfwd(); double wcscrd[4], imgcrd[4], pixcrd[4]; double phi, theta; *xpix = 0.0; *ypix = 0.0; if (wcs->wcsl.flag != WCSSET) { if (wcsset (wcs->lin.naxis, (void *)&wcs->ctype, &wcs->wcsl) ) return (1); } /* Set input for WCSLIB subroutines */ wcscrd[0] = 0.0; wcscrd[1] = 0.0; wcscrd[2] = 0.0; wcscrd[3] = 0.0; wcscrd[wcs->wcsl.lng] = xpos; wcscrd[wcs->wcsl.lat] = ypos; /* Initialize output for WCSLIB subroutines */ pixcrd[0] = 0.0; pixcrd[1] = 0.0; pixcrd[2] = 1.0; pixcrd[3] = 1.0; imgcrd[0] = 0.0; imgcrd[1] = 0.0; imgcrd[2] = 1.0; imgcrd[3] = 1.0; /* Invoke WCSLIB subroutines for coordinate conversion */ offscl = wcsfwd ((void *)&wcs->ctype, &wcs->wcsl, wcscrd, wcs->crval, &wcs->cel, &phi, &theta, &wcs->prj, imgcrd, &wcs->lin, pixcrd); if (!offscl) { *xpix = pixcrd[0]; *ypix = pixcrd[1]; if (wcs->prjcode == WCS_CSC || wcs->prjcode == WCS_QSC || wcs->prjcode == WCS_TSC) wcs->zpix = pixcrd[2] - 1.0; else wcs->zpix = pixcrd[2]; } return (offscl); } /* Set third dimension for cube projections */ int wcszin (izpix0) int izpix0; /* coordinate in third dimension (if < 0, return current value without changing it */ { if (izpix0 > -1) { izpix = izpix0; zpix = (double) izpix0; } return (izpix); } /* Return third dimension for cube projections */ int wcszout (wcs) struct WorldCoor *wcs; /* WCS parameter structure */ { return ((int) wcs->zpix); } /* Set file name for error messages */ void setwcsfile (filename) char *filename; /* FITS or IRAF file with WCS */ { if (strlen (filename) < 256) strcpy (wcsfile, filename); else strncpy (wcsfile, filename, 255); return; } /* Set error message */ void setwcserr (errmsg) char *errmsg; /* Error mesage < 80 char */ { strcpy (wcserrmsg, errmsg); return; } /* Print error message */ void wcserr () { if (strlen (wcsfile) > 0) fprintf (stderr, "%s in file %s\n",wcserrmsg, wcsfile); else fprintf (stderr, "%s\n",wcserrmsg); return; } /* Flag to use AIPS WCS subroutines instead of WCSLIB */ void setdefwcs (wp) int wp; { wcsproj0 = wp; return; } int getdefwcs () { return (wcsproj0); } /* Save output default coordinate system */ static char wcscoor0[16]; void savewcscoor (wcscoor) char *wcscoor; { strcpy (wcscoor0, wcscoor); return; } /* Return preset output default coordinate system */ char * getwcscoor () { return (wcscoor0); } /* Save default commands */ static char *wcscom0[10]; void savewcscom (i, wcscom) int i; char *wcscom; { int lcom; if (i < 0) i = 0; else if (i > 9) i = 9; lcom = strlen (wcscom) + 2; wcscom0[i] = (char *) calloc (lcom, 1); if (wcscom0[i] != NULL) strcpy (wcscom0[i], wcscom); return; } void setwcscom (wcs) struct WorldCoor *wcs; /* WCS parameter structure */ { char envar[16]; int i; char *str; if (nowcs(wcs)) return; for (i = 0; i < 10; i++) { if (i == 0) strcpy (envar, "WCS_COMMAND"); else sprintf (envar, "WCS_COMMAND%d", i); if (wcscom0[i] != NULL) wcscominit (wcs, i, wcscom0[i]); else if ((str = getenv (envar)) != NULL) wcscominit (wcs, i, str); else if (i == 1) wcscominit (wcs, i, "sua2 -ah %s"); /* F1= Search USNO-A2.0 Catalog */ else if (i == 2) wcscominit (wcs, i, "sgsc -ah %s"); /* F2= Search HST GSC */ else if (i == 3) wcscominit (wcs, i, "sty2 -ah %s"); /* F3= Search Tycho-2 Catalog */ else if (i == 4) wcscominit (wcs, i, "sppm -ah %s"); /* F4= Search PPM Catalog */ else if (i == 5) wcscominit (wcs, i, "ssao -ah %s"); /* F5= Search SAO Catalog */ else wcs->command_format[i] = NULL; } return; } char * getwcscom (i) int i; { return (wcscom0[i]); } void freewcscom (wcs) struct WorldCoor *wcs; /* WCS parameter structure */ { int i; for (i = 0; i < 10; i++) { if (wcscom0[i] != NULL) { free (wcscom0[i]); wcscom0[i] = NULL; } } if (iswcs (wcs)) { for (i = 0; i < 10; i++) { if (wcs->command_format[i] != NULL) { free (wcs->command_format[i]); } } } return; } int cpwcs (header, cwcs) char **header; /* Pointer to start of FITS header */ char *cwcs; /* Keyword suffix character for output WCS */ { double tnum; int dkwd[100]; int i, maxnkwd, ikwd, nleft, lbuff, lhead, nkwd, nbytes; int nkwdw; char **kwd; char *newhead, *oldhead; char kwdc[16], keyword[16]; char tstr[80]; /* Allocate array of keywords to be transferred */ maxnkwd = 100; kwd = (char **)calloc (maxnkwd, sizeof(char *)); for (ikwd = 0; ikwd < maxnkwd; ikwd++) kwd[ikwd] = (char *) calloc (16, 1); /* Make list of all possible keywords to be transferred */ nkwd = 0; strcpy (kwd[++nkwd], "EPOCH"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "EQUINOX"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "RADECSYS"); dkwd[nkwd] = 0; strcpy (kwd[++nkwd], "CTYPE1"); dkwd[nkwd] = 0; strcpy (kwd[++nkwd], "CTYPE2"); dkwd[nkwd] = 0; strcpy (kwd[++nkwd], "CRVAL1"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "CRVAL2"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "CDELT1"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "CDELT2"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "CRPIX1"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "CRPIX2"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "CROTA1"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "CROTA2"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "CD1_1"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "CD1_2"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "CD2_1"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "CD2_2"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "PC1_1"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "PC1_2"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "PC2_1"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "PC2_2"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "PC001001"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "PC001002"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "PC002001"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "PC002002"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "LATPOLE"); dkwd[nkwd] = 1; strcpy (kwd[++nkwd], "LONPOLE"); dkwd[nkwd] = 1; for (i = 1; i < 13; i++) { sprintf (keyword,"CO1_%d", i); strcpy (kwd[++nkwd], keyword); dkwd[nkwd] = 1; } for (i = 1; i < 13; i++) { sprintf (keyword,"CO2_%d", i); strcpy (kwd[++nkwd], keyword); dkwd[nkwd] = 1; } for (i = 0; i < 10; i++) { sprintf (keyword,"PROJP%d", i); strcpy (kwd[++nkwd], keyword); dkwd[nkwd] = 1; } for (i = 0; i < MAXPV; i++) { sprintf (keyword,"PV1_%d", i); strcpy (kwd[++nkwd], keyword); dkwd[nkwd] = 1; } for (i = 0; i < MAXPV; i++) { sprintf (keyword,"PV2_%d", i); strcpy (kwd[++nkwd], keyword); dkwd[nkwd] = 1; } /* Allocate new header buffer if needed */ lhead = (ksearch (*header, "END") - *header) + 80; lbuff = gethlength (*header); nleft = (lbuff - lhead) / 80; if (nleft < nkwd) { nbytes = lhead + (nkwd * 80) + 400; newhead = (char *) calloc (1, nbytes); strncpy (newhead, *header, lhead); oldhead = *header; header = &newhead; free (oldhead); } /* Copy keywords to new WCS ID in header */ nkwdw = 0; for (i = 0; i < nkwd; i++) { if (dkwd[i]) { if (hgetr8 (*header, kwd[i], &tnum)) { nkwdw++; if (!strncmp (kwd[i], "PC0", 3)) { if (!strcmp (kwd[i], "PC001001")) strcpy (kwdc, "PC1_1"); else if (!strcmp (kwd[i], "PC001002")) strcpy (kwdc, "PC1_2"); else if (!strcmp (kwd[i], "PC002001")) strcpy (kwdc, "PC2_1"); else strcpy (kwdc, "PC2_2"); } else strcpy (kwdc, kwd[i]); strncat (kwdc, cwcs, 1); (void)hputr8 (*header, kwdc, tnum); } } else { if (hgets (*header, kwd[i], 80, tstr)) { nkwdw++; if (!strncmp (kwd[i], "RADECSYS", 8)) strcpy (kwdc, "RADECSY"); else strcpy (kwdc, kwd[i]); strncat (kwdc, cwcs, 1); hputs (*header, kwdc, tstr); } } } /* Free keyword list array */ for (ikwd = 0; ikwd < maxnkwd; ikwd++) free (kwd[ikwd]); free (kwd); kwd = NULL; return (nkwdw); } /* Oct 28 1994 new program * Dec 21 1994 Implement CD rotation matrix * Dec 22 1994 Allow RA and DEC to be either x,y or y,x * * Mar 6 1995 Add Digital Sky Survey plate fit * May 2 1995 Add prototype of PIX2WCST to WCSCOM * May 25 1995 Print leading zero for hours and degrees * Jun 21 1995 Add WCS2PIX to get pixels from WCS * Jun 21 1995 Read plate scale from FITS header for plate solution * Jul 6 1995 Pass WCS structure as argument; malloc it in WCSINIT * Jul 6 1995 Check string lengths in PIX2WCST * Aug 16 1995 Add galactic coordinate conversion to PIX2WCST * Aug 17 1995 Return 0 from iswcs if wcs structure is not yet set * Sep 8 1995 Do not include malloc.h if VMS * Sep 8 1995 Check for legal WCS before trying anything * Sep 8 1995 Do not try to set WCS if missing key keywords * Oct 18 1995 Add WCSCENT and WCSDIST to print center and size of image * Nov 6 1995 Include stdlib.h instead of malloc.h * Dec 6 1995 Fix format statement in PIX2WCST * Dec 19 1995 Change MALLOC to CALLOC to initialize array to zeroes * Dec 19 1995 Explicitly initialize rotation matrix and yinc * Dec 22 1995 If SECPIX is set, use approximate WCS * Dec 22 1995 Always print coordinate system * * Jan 12 1996 Use plane-tangent, not linear, projection if SECPIX is set * Jan 12 1996 Add WCSSET to set WCS without an image * Feb 15 1996 Replace all calls to HGETC with HGETS * Feb 20 1996 Add tab table output from PIX2WCST * Apr 2 1996 Convert all equinoxes to B1950 or J2000 * Apr 26 1996 Get and use image epoch for accurate FK4/FK5 conversions * May 16 1996 Clean up internal documentation * May 17 1996 Return width in right ascension degrees, not sky degrees * May 24 1996 Remove extraneous print command from WCSSIZE * May 28 1996 Add NOWCS and WCSSHIFT subroutines * Jun 11 1996 Drop unused variables after running lint * Jun 12 1996 Set equinox as well as system in WCSSHIFT * Jun 14 1996 Make DSS keyword searches more robust * Jul 1 1996 Allow for SECPIX1 and SECPIX2 keywords * Jul 2 1996 Test for CTYPE1 instead of CRVAL1 * Jul 5 1996 Declare all subroutines in wcs.h * Jul 19 1996 Add subroutine WCSFULL to return real image size * Aug 12 1996 Allow systemless coordinates which cannot be converted * Aug 15 1996 Allow LINEAR WCS to pass numbers through transparently * Aug 15 1996 Add WCSERR to print error message under calling program control * Aug 16 1996 Add latitude and longitude as image coordinate types * Aug 26 1996 Fix arguments to HLENGTH in WCSNINIT * Aug 28 1996 Explicitly set OFFSCL in WCS2PIX if coordinates outside image * Sep 3 1996 Return computed pixel values even if they are offscale * Sep 6 1996 Allow filename to be passed by WCSCOM * Oct 8 1996 Default to 2000 for EQUINOX and EPOCH and FK5 for RADECSYS * Oct 8 1996 If EPOCH is 0 and EQUINOX is not set, default to 1950 and FK4 * Oct 15 1996 Add comparison when testing an assignment * Oct 16 1996 Allow PIXEL CTYPE which means WCS is same as image coordinates * Oct 21 1996 Add WCS_COMMAND environment variable * Oct 25 1996 Add image scale to WCSCENT * Oct 30 1996 Fix bugs in WCS2PIX * Oct 31 1996 Fix CD matrix rotation angle computation * Oct 31 1996 Use inline degree <-> radian conversion functions * Nov 1 1996 Add option to change number of decimal places in PIX2WCST * Nov 5 1996 Set wcs->crot to 1 if rotation matrix is used * Dec 2 1996 Add altitide/azimuth coordinates * Dec 13 1996 Fix search format setting from environment * * Jan 22 1997 Add ifdef for Eric Mandel (SAOtng) * Feb 5 1997 Add wcsout for Eric Mandel * Mar 20 1997 Drop unused variable STR in WCSCOM * May 21 1997 Do not make pixel coordinates mod 360 in PIX2WCST * May 22 1997 Add PIXEL prjcode = -1; * Jul 11 1997 Get center pixel x and y from header even if no WCS * Aug 7 1997 Add NOAO PIXSCALi keywords for default WCS * Oct 15 1997 Do not reset reference pixel in WCSSHIFT * Oct 20 1997 Set chip rotation * Oct 24 1997 Keep longitudes between 0 and 360, not -180 and +180 * Nov 5 1997 Do no compute crot and srot; they are now computed in worldpos * Dec 16 1997 Set rotation and axis increments from CD matrix * * Jan 6 1998 Deal with J2000 and B1950 as EQUINOX values (from ST) * Jan 7 1998 Read INSTRUME and DETECTOR header keywords * Jan 7 1998 Fix tab-separated output * Jan 9 1998 Precess coordinates if either FITS projection or *DSS plate* * Jan 16 1998 Change PTYPE to not include initial hyphen * Jan 16 1998 Change WCSSET to WCSXINIT to avoid conflict with Calabretta * Jan 23 1998 Change PCODE to PRJCODE to avoid conflict with Calabretta * Jan 27 1998 Add LATPOLE and LONGPOLE for Calabretta projections * Feb 5 1998 Make cd and dc into vectors; use matinv() to invert cd * Feb 5 1998 In wcsoutinit(), check that corsys is a valid pointer * Feb 18 1998 Fix bugs for Calabretta projections * Feb 19 1998 Add wcs structure access subroutines from Eric Mandel * Feb 19 1998 Add wcsreset() to make sure derived values are reset * Feb 19 1998 Always set oldwcs to 1 if NCP projection * Feb 19 1998 Add subroutine to set oldwcs default * Feb 20 1998 Initialize projection types one at a time for SunOS C * Feb 23 1998 Add TNX projection from NOAO; treat it as TAN * Feb 23 1998 Compute size based on max and min coordinates, not sides * Feb 26 1998 Add code to set center pixel if part of detector array * Mar 6 1998 Write 8-character values to RADECSYS * Mar 9 1998 Add naxis to WCS structure * Mar 16 1998 Use separate subroutine for IRAF TNX projection * Mar 20 1998 Set PC matrix if more than two axes and it's not in header * Mar 20 1998 Reset lin flag in WCSRESET if CDELTn * Mar 20 1998 Set CD matrix with CDELTs and CROTA in wcsinit and wcsreset * Mar 20 1998 Allow initialization of rotation angle alone * Mar 23 1998 Use dsspos() and dsspix() instead of platepos() and platepix() * Mar 24 1998 Set up PLT/PLATE plate polynomial fit using platepos() and platepix() * Mar 25 1998 Read plate fit coefficients from header in getwcscoeffs() * Mar 27 1998 Check for FITS WCS before DSS WCS * Mar 27 1998 Compute scale from edges if xinc and yinc not set in wcscent() * Apr 6 1998 Change plate coefficient keywords from PLTij to COi_j * Apr 6 1998 Read all coefficients in line instead of with subroutine * Apr 7 1998 Change amd_i_coeff to i_coeff * Apr 8 1998 Add wcseqset to change equinox after wcs has been set * Apr 10 1998 Use separate counters for x and y polynomial coefficients * Apr 13 1998 Use CD/CDELT+CDROTA if oldwcs is set * Apr 14 1998 Use codes instead of strings for various coordinate systems * Apr 14 1998 Separate input coordinate conversion from output conversion * Apr 14 1998 Use wcscon() for most coordinate conversion * Apr 17 1998 Always compute cdelt[] * Apr 17 1998 Deal with reversed axis more correctly * Apr 17 1998 Compute rotation angle and approximate CDELTn for polynomial * Apr 23 1998 Deprecate xref/yref in favor of crval[] * Apr 23 1998 Deprecate xrefpix/yrefpix in favor of crpix[] * Apr 23 1998 Add LINEAR to coordinate system types * Apr 23 1998 Always use AIPS subroutines for LINEAR or PIXEL * Apr 24 1998 Format linear coordinates better * Apr 28 1998 Change coordinate system flags to WCS_* * Apr 28 1998 Change projection flags to WCS_* * Apr 28 1998 Add subroutine wcsc2pix for coordinates to pixels with system * Apr 28 1998 Add setlinmode() to set output string mode for LINEAR coordinates * Apr 30 1998 Fix bug by setting degree flag for lat and long in wcsinit() * Apr 30 1998 Allow leading "-"s in projecting in wcsxinit() * May 1 1998 Assign new output coordinate system only if legitimate system * May 1 1998 Do not allow oldwcs=1 unless allowed projection * May 4 1998 Fix bug in units reading for LINEAR coordinates * May 6 1998 Initialize to no CD matrix * May 6 1998 Use TAN instead of TNX if oldwcs * May 12 1998 Set 3rd and 4th coordinates in wcspos() * May 12 1998 Return *xpos and *ypos = 0 in pix2wcs() if offscale * May 12 1998 Declare undeclared external subroutines after lint * May 13 1998 Add equinox conversion to specified output equinox * May 13 1998 Set output or input system to image with null argument * May 15 1998 Return reference pixel, cdelts, and rotation for DSS * May 20 1998 Fix bad bug so setlinmode() is no-op if wcs not set * May 20 1998 Fix bug so getwcsout() returns null pointer if wcs not set * May 27 1998 Change WCS_LPR back to WCS_LIN; allow CAR in oldwcs * May 28 1998 Go back to old WCSFULL, computing height and width from center * May 29 1998 Add wcskinit() to initialize WCS from arguments * May 29 1998 Add wcstype() to set projection from arguments * May 29 1998 Add wcscdset(), and wcsdeltset() to set scale from arguments * Jun 1 1998 In wcstype(), reconstruct ctype for WCS structure * Jun 11 1998 Split off header-dependent subroutines to wcsinit.c * Jun 18 1998 Add wcspcset() for PC matrix initialization * Jun 24 1998 Add string lengths to ra2str(), dec2str, and deg2str() calls * Jun 25 1998 Use AIPS software for CAR projection * Jun 25 1998 Add wcsndec to set number of decimal places in output string * Jul 6 1998 Add wcszin() and wcszout() to use third dimension of images * Jul 7 1998 Change setlinmode() to setwcslin(); setdegout() to setwcsdeg() * Jul 10 1998 Initialize matrices correctly for naxis > 2 in wcs<>set() * Jul 16 1998 Initialize coordinates to be returned in wcspos() * Jul 17 1998 Link lin structure arrays to wcs structure arrays * Jul 20 1998 In wcscdset() compute sign of xinc and yinc from CD1_1, CD 2_2 * Jul 20 1998 In wcscdset() compute sign of rotation based on CD1_1, CD 1_2 * Jul 22 1998 Add wcslibrot() to compute lin() rotation matrix * Jul 30 1998 Set wcs->naxes and lin.naxis in wcsxinit() and wcskinit() * Aug 5 1998 Use old WCS subroutines to deal with COE projection (for ESO) * Aug 14 1998 Add option to print image coordinates with wcscom() * Aug 14 1998 Add multiple command options to wcscom*() * Aug 31 1998 Declare undeclared arguments to wcspcset() * Sep 3 1998 Set CD rotation and cdelts from sky axis position angles * Sep 16 1998 Add option to use North Polar Angle instead of Latitude * Sep 29 1998 Initialize additional WCS commands from the environment * Oct 14 1998 Fix bug in wcssize() which didn't divide dra by cos(dec) * Nov 12 1998 Fix sign of CROTA when either axis is reflected * Dec 2 1998 Fix non-arcsecond scale factors in wcscent() * Dec 2 1998 Add PLANET coordinate system to pix2wcst() * Jan 20 1999 Free lin.imgpix and lin.piximg in wcsfree() * Feb 22 1999 Fix bug setting latitude reference value of latbase != 0 * Feb 22 1999 Fix bug so that quad cube faces are 0-5, not 1-6 * Mar 16 1999 Always initialize all 4 imgcrds and pixcrds in wcspix() * Mar 16 1999 Always return (0,0) from wcs2pix if offscale * Apr 7 1999 Add code to put file name in error messages * Apr 7 1999 Document utility subroutines at end of file * May 6 1999 Fix bug printing height of LINEAR image * Jun 16 1999 Add wcsrange() to return image RA and Dec limits * Jul 8 1999 Always use FK5 and FK4 instead of J2000 and B1950 in RADECSYS * Aug 16 1999 Print dd:mm:ss dd:mm:ss if not J2000 or B1950 output * Aug 20 1999 Add WCS string argument to wcscom(); don't compute it there * Aug 20 1999 Change F3 WCS command default from Tycho to ACT * Oct 15 1999 Free wcs using wcsfree() * Oct 21 1999 Drop declarations of unused functions after lint * Oct 25 1999 Drop out of wcsfree() if wcs is null pointer * Nov 17 1999 Fix bug which caused software to miss NCP projection * * Jan 24 2000 Default to AIPS for NCP, CAR, and COE proj.; if -z use WCSLIB * Feb 24 2000 If coorsys is null in wcsc2pix, wcs->radecin is assumed * May 10 2000 In wcstype(), default to WCS_LIN, not error (after Bill Joye) * Jun 22 2000 In wcsrotset(), leave rotation angle alone in 1-d image * Jul 3 2000 Initialize wcscrd[] to zero in wcspix() * * Feb 20 2001 Add recursion to wcs2pix() and pix2wcs() for dependent WCS's * Mar 20 2001 Add braces to avoid ambiguity in if/else groupings * Mar 22 2001 Free WCS structure in wcsfree even if it is not filled * Sep 12 2001 Fix bug which omitted tab in pix2wcst() galactic coord output * * Mar 7 2002 Fix bug which gave wrong pa's and rotation for reflected RA * (but correct WCS conversions!) * Mar 28 2002 Add SZP projection * Apr 3 2002 Synchronize projection types with other subroutines * Apr 3 2002 Drop special cases of projections * Apr 9 2002 Implement inversion of multiple WCSs in wcsc2pix() * Apr 25 2002 Use Tycho-2 catalog instead of ACT in setwcscom() * May 13 2002 Free WCSNAME in wcsfree() * * Mar 31 2003 Add distcode to wcstype() * Apr 1 2003 Add calls to foc2pix() in wcs2pix() and pix2foc() in pix2wcs() * May 20 2003 Declare argument i in savewcscom() * Sep 29 2003 Fix bug to compute width and height correctly in wcsfull() * Sep 29 2003 Fix bug to deal with all-sky images orrectly in wcsfull() * Oct 1 2003 Rename wcs->naxes to wcs->naxis to match WCSLIB 3.2 * Nov 3 2003 Set distortion code by calling setdistcode() in wcstype() * Dec 3 2003 Add back wcs->naxes for compatibility * Dec 3 2003 Add braces in if...else in pix2wcst() * * Sep 17 2004 If spherical coordinate output, keep 0 < long/RA < 360 * Sep 17 2004 Fix bug in wcsfull() when wrapping around RA=0:00 * Nov 1 2004 Keep wcs->rot between 0 and 360 * * Mar 9 2005 Fix bug in wcsrotset() which set rot > 360 to 360 * Jun 27 2005 Fix ctype in calls to wcs subroutines * Jul 21 2005 Fix bug in wcsrange() at RA ~= 0.0 * * Apr 24 2006 Always set inverse CD matrix to 2 dimensions in wcspcset() * May 3 2006 (void *) pointers so arguments match type, from Robert Lupton * Jun 30 2006 Set only 2-dimensional PC matrix; that is all lin* can deal with * Oct 30 2006 In pix2wcs(), do not limit x to between 0 and 360 if XY or LINEAR * Oct 30 2006 In wcsc2pix(), do not precess LINEAR or XY coordinates * Dec 21 2006 Add cpwcs() to copy WCS keywords to new suffix * * Jan 4 2007 Fix pointer to header in cpwcs() * Jan 5 2007 Drop declarations of wcscon(); it is in wcs.h * Jan 9 2006 Drop declarations of fk425e() and fk524e(); moved to wcs.h * Jan 9 2006 Drop *pix() and *pos() external declarations; moved to wcs.h * Jan 9 2006 Drop matinv() external declaration; it is already in wcslib.h * Feb 15 2007 If CTYPEi contains DET, set to WCS_PIX projection * Feb 23 2007 Fix bug when checking for "DET" in CTYPEi * Apr 2 2007 Fix PC to CD matrix conversion * Jul 25 2007 Compute distance between two coordinates using d2v3() * * Apr 7 2010 In wcstype() set number of WCS projections from NWCSTYPE * * Mar 11 2011 Add NOAO ZPX projection (Frank Valdes) * Mar 14 2011 Delete j<=MAXPV PVi_j parameters (for SCAMP polynomials via Ed Los) * Mar 17 2011 Fix WCSDEP bug found by Ed Los * May 9 2011 Free WCS structure recursively if WCSDEP is used * Sep 1 2011 Add TPV projection type for SCAMP TAN with PVs * * Oct 19 2012 Drop d1 and d2 from wcsdist(); diffi from wcsdist1() * Oct 19 2012 Drop depwcs; it's in main wcs structure */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/Readme0000644000175000017500000000326513047255533020605 0ustar mattymatty00000000000000WCSsubs Subroutines These subroutines, developed as part of the WCSTools software package, constitute a self-contained package for accessing the world coordinate systems of FITS or IRAF(.imh) images, with image header I/O contained in fitsfile.c and imhfile.c, and WCS initialization and use through the subroutines in wcs.c. WCS information for an image is kept in a single data structure defined in wcs.h. Pixel to WCS translations are done by calls to pix2wcst() or pix2wcs(). WCS to pixel translations are done by calls to wcs2pix() or wcsc2pix(). The contents of the files are briefly described in Files. Dependencies between these files are given in Makefile. Documentation, to some extent, is online at http://tdc-www.harvard.edu/software/wcstools/libwcs.wcs.html Documentation for the entire open-source WCSTools package is online at http://tdc-www.harvard.edu/software/wcstools/ Projection code in wcspos.c is by Bill Cotton of NRAO and is protected by the Gnu Lesser General Public License, which is stated in the file COPYING. Projection code in wcslib.c, cel.c, lin.c, proj.c, wcstrig.c, and sph.c is by Mark Calabretta of CSIRO and is also protected by the Gnu Lesser General Public License. Code in slasubs.c is by Pat Wallace of the Starlink project at Cambridge University. Doug Mink is responsible for the rest of the code, unless otherwise noted in the source file. Unless otherwise noted, this code is Copyright 2003 by the Smithsonian Astrophysical Observatory and protected by the Gnu Lesser General Public License. -Jessica Mink (jmink@cfa.harvard.edu) Telescope Data Center Harvard-Smithsonian Center for Astrophysics Cambridge, Massachusetts http://tdc-www.harvard.edu/mink astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/wcstrig.c0000664000175000017500000001062313047255533021311 0ustar mattymatty00000000000000/*============================================================================ * * WCSLIB - an implementation of the FITS WCS proposal. * Copyright (C) 1995-2002, Mark Calabretta * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Correspondence concerning WCSLIB may be directed to: * Internet email: mcalabre@atnf.csiro.au * Postal address: Dr. Mark Calabretta, * Australia Telescope National Facility, * P.O. Box 76, * Epping, NSW, 2121, * AUSTRALIA * *============================================================================= * * The functions defined herein are trigonometric or inverse trigonometric * functions which take or return angular arguments in decimal degrees. * * $Id: wcstrig.c,v 2.8 2002/04/03 01:25:29 mcalabre Exp $ *---------------------------------------------------------------------------*/ #include #include "wcslib.h" const double d2r = PI / 180.0; const double r2d = 180.0 / PI; double cosdeg (angle) const double angle; { double resid; resid = fabs(fmod(angle,360.0)); if (resid == 0.0) { return 1.0; } else if (resid == 90.0) { return 0.0; } else if (resid == 180.0) { return -1.0; } else if (resid == 270.0) { return 0.0; } return cos(angle*d2r); } /*--------------------------------------------------------------------------*/ double sindeg (angle) const double angle; { double resid; resid = fmod(angle-90.0,360.0); if (resid == 0.0) { return 1.0; } else if (resid == 90.0) { return 0.0; } else if (resid == 180.0) { return -1.0; } else if (resid == 270.0) { return 0.0; } return sin(angle*d2r); } /*--------------------------------------------------------------------------*/ double tandeg (angle) const double angle; { double resid; resid = fmod(angle,360.0); if (resid == 0.0 || fabs(resid) == 180.0) { return 0.0; } else if (resid == 45.0 || resid == 225.0) { return 1.0; } else if (resid == -135.0 || resid == -315.0) { return -1.0; } return tan(angle*d2r); } /*--------------------------------------------------------------------------*/ double acosdeg(v) const double v; { if (v >= 1.0) { if (v-1.0 < WCSTRIG_TOL) return 0.0; } else if (v == 0.0) { return 90.0; } else if (v <= -1.0) { if (v+1.0 > -WCSTRIG_TOL) return 180.0; } return acos(v)*r2d; } /*--------------------------------------------------------------------------*/ double asindeg (v) const double v; { if (v <= -1.0) { if (v+1.0 > -WCSTRIG_TOL) return -90.0; } else if (v == 0.0) { return 0.0; } else if (v >= 1.0) { if (v-1.0 < WCSTRIG_TOL) return 90.0; } return asin(v)*r2d; } /*--------------------------------------------------------------------------*/ double atandeg (v) const double v; { if (v == -1.0) { return -45.0; } else if (v == 0.0) { return 0.0; } else if (v == 1.0) { return 45.0; } return atan(v)*r2d; } /*--------------------------------------------------------------------------*/ double atan2deg (y, x) const double x, y; { if (y == 0.0) { if (x >= 0.0) { return 0.0; } else if (x < 0.0) { return 180.0; } } else if (x == 0.0) { if (y > 0.0) { return 90.0; } else if (y < 0.0) { return -90.0; } } return atan2(y,x)*r2d; } /* Dec 20 1999 Doug Mink - Change cosd() and sind() to cosdeg() and sindeg() * Dec 20 1999 Doug Mink - Include wcslib.h, which includes wcstrig.h * Dec 20 1999 Doug Mink - Use PI from wcslib.h, not locally defined * * Sep 19 2001 Doug Mink - No change for WCSLIB 2.7 */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/worldpos.c0000664000175000017500000005101513047255533021500 0ustar mattymatty00000000000000/* worldpos.c -- WCS Algorithms from Classic AIPS. * September 1, 2011 * Copyright (C) 1994-2011 * Associated Universities, Inc. Washington DC, USA. * With code added by Jessica Mink, Smithsonian Astrophysical Observatory * and Allan Brighton and Andreas Wicenec, ESO * and Frank Valdes, NOAO * Module: worldpos.c * Purpose: Perform forward and reverse WCS computations for 8 projections * Subroutine: worldpos() converts from pixel location to RA,Dec * Subroutine: worldpix() converts from RA,Dec to pixel location -=-=-=-=-=-=- This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Correspondence concerning AIPS should be addressed as follows: Internet email: aipsmail@nrao.edu Postal address: AIPS Group National Radio Astronomy Observatory 520 Edgemont Road Charlottesville, VA 22903-2475 USA -=-=-=-=-=-=- These two ANSI C functions, worldpos() and worldpix(), perform forward and reverse WCS computations for 8 types of projective geometries ("-SIN", "-TAN", "-ARC", "-NCP", "-GLS" or "-SFL", "-MER", "-AIT", "-STG", "CAR", and "COE"): worldpos() converts from pixel location to RA,Dec worldpix() converts from RA,Dec to pixel location where "(RA,Dec)" are more generically (long,lat). These functions are based on the WCS implementation of Classic AIPS, an implementation which has been in production use for more than ten years. See the two memos by Eric Greisen ftp://fits.cv.nrao.edu/fits/documents/wcs/aips27.ps.Z ftp://fits.cv.nrao.edu/fits/documents/wcs/aips46.ps.Z for descriptions of the 8 projective geometries and the algorithms. Footnotes in these two documents describe the differences between these algorithms and the 1993-94 WCS draft proposal (see URL below). In particular, these algorithms support ordinary field rotation, but not skew geometries (CD or PC matrix cases). Also, the MER and AIT algorithms work correctly only for CRVALi=(0,0). Users should note that GLS projections with yref!=0 will behave differently in this code than in the draft WCS proposal. The NCP projection is now obsolete (it is a special case of SIN). WCS syntax and semantics for various advanced features is discussed in the draft WCS proposal by Greisen and Calabretta at: ftp://fits.cv.nrao.edu/fits/documents/wcs/wcs.all.ps.Z -=-=-=- The original version of this code was Emailed to D.Wells on Friday, 23 September by Bill Cotton , who described it as a "..more or less.. exact translation from the AIPSish..". Changes were made by Don Wells during the period October 11-13, 1994: 1) added GNU license and header comments 2) added testpos.c program to perform extensive circularity tests 3) changed float-->double to get more than 7 significant figures 4) testpos.c circularity test failed on MER and AIT. B.Cotton found that "..there were a couple of lines of code [in] the wrong place as a result of merging several Fortran routines." 5) testpos.c found 0h wraparound in worldpix() and worldpos(). 6) E.Greisen recommended removal of various redundant if-statements, and addition of a 360d difference test to MER case of worldpos(). 7) D.Mink changed input to data structure and implemented rotation matrix. */ #include #include #include #include "wcs.h" int worldpos (xpix, ypix, wcs, xpos, ypos) /* Routine to determine accurate position for pixel coordinates */ /* returns 0 if successful otherwise 1 = angle too large for projection; */ /* does: -SIN, -TAN, -ARC, -NCP, -GLS or -SFL, -MER, -AIT projections */ /* anything else is linear */ /* Input: */ double xpix; /* x pixel number (RA or long without rotation) */ double ypix; /* y pixel number (Dec or lat without rotation) */ struct WorldCoor *wcs; /* WCS parameter structure */ /* Output: */ double *xpos; /* x (RA) coordinate (deg) */ double *ypos; /* y (dec) coordinate (deg) */ { double cosr, sinr, dx, dy, dz, tx; double sins, coss, dt, l, m, mg, da, dd, cos0, sin0; double rat = 0.0; double dect = 0.0; double mt, a, y0, td, r2; /* allan: for COE */ double dec0, ra0, decout, raout; double geo1, geo2, geo3; double cond2r=1.745329252e-2; double twopi = 6.28318530717959; double deps = 1.0e-5; /* Structure elements */ double xref; /* X reference coordinate value (deg) */ double yref; /* Y reference coordinate value (deg) */ double xrefpix; /* X reference pixel */ double yrefpix; /* Y reference pixel */ double xinc; /* X coordinate increment (deg) */ double yinc; /* Y coordinate increment (deg) */ double rot; /* Optical axis rotation (deg) (N through E) */ int itype = wcs->prjcode; /* Set local projection parameters */ xref = wcs->xref; yref = wcs->yref; xrefpix = wcs->xrefpix; yrefpix = wcs->yrefpix; xinc = wcs->xinc; yinc = wcs->yinc; rot = degrad (wcs->rot); cosr = cos (rot); sinr = sin (rot); /* Offset from ref pixel */ dx = xpix - xrefpix; dy = ypix - yrefpix; /* Scale and rotate using CD matrix */ if (wcs->rotmat) { tx = dx * wcs->cd[0] + dy * wcs->cd[1]; dy = dx * wcs->cd[2] + dy * wcs->cd[3]; dx = tx; } /* Scale and rotate using CDELTn and CROTA2 */ else { /* Check axis increments - bail out if either 0 */ if ((xinc==0.0) || (yinc==0.0)) { *xpos=0.0; *ypos=0.0; return 2; } /* Scale using CDELT */ dx = dx * xinc; dy = dy * yinc; /* Take out rotation from CROTA */ if (rot != 0.0) { tx = dx * cosr - dy * sinr; dy = dx * sinr + dy * cosr; dx = tx; } } /* Flip coordinates if necessary */ if (wcs->coorflip) { tx = dx; dx = dy; dy = tx; } /* Default, linear result for error or pixel return */ *xpos = xref + dx; *ypos = yref + dy; if (itype <= 0) return 0; /* Convert to radians */ if (wcs->coorflip) { dec0 = degrad (xref); ra0 = degrad (yref); } else { ra0 = degrad (xref); dec0 = degrad (yref); } l = degrad (dx); m = degrad (dy); sins = l*l + m*m; decout = 0.0; raout = 0.0; cos0 = cos (dec0); sin0 = sin (dec0); /* Process by case */ switch (itype) { case WCS_CAR: /* -CAR Cartesian (was WCS_PIX pixel and WCS_LIN linear) */ rat = ra0 + l; dect = dec0 + m; break; case WCS_SIN: /* -SIN sin*/ if (sins>1.0) return 1; coss = sqrt (1.0 - sins); dt = sin0 * coss + cos0 * m; if ((dt>1.0) || (dt<-1.0)) return 1; dect = asin (dt); rat = cos0 * coss - sin0 * m; if ((rat==0.0) && (l==0.0)) return 1; rat = atan2 (l, rat) + ra0; break; case WCS_TAN: /* -TAN tan */ case WCS_TNX: /* -TNX tan with polynomial correction */ case WCS_TPV: /* -TPV tan with polynomial correction */ case WCS_ZPX: /* -ZPX zpn with polynomial correction */ if (sins>1.0) return 1; dect = cos0 - m * sin0; if (dect==0.0) return 1; rat = ra0 + atan2 (l, dect); dect = atan (cos(rat-ra0) * (m * cos0 + sin0) / dect); break; case WCS_ARC: /* -ARC Arc*/ if (sins>=twopi*twopi/4.0) return 1; sins = sqrt(sins); coss = cos (sins); if (sins!=0.0) sins = sin (sins) / sins; else sins = 1.0; dt = m * cos0 * sins + sin0 * coss; if ((dt>1.0) || (dt<-1.0)) return 1; dect = asin (dt); da = coss - dt * sin0; dt = l * sins * cos0; if ((da==0.0) && (dt==0.0)) return 1; rat = ra0 + atan2 (dt, da); break; case WCS_NCP: /* -NCP North celestial pole*/ dect = cos0 - m * sin0; if (dect==0.0) return 1; rat = ra0 + atan2 (l, dect); dt = cos (rat-ra0); if (dt==0.0) return 1; dect = dect / dt; if ((dect>1.0) || (dect<-1.0)) return 1; dect = acos (dect); if (dec0<0.0) dect = -dect; break; case WCS_GLS: /* -GLS global sinusoid */ case WCS_SFL: /* -SFL Samson-Flamsteed */ dect = dec0 + m; if (fabs(dect)>twopi/4.0) return 1; coss = cos (dect); if (fabs(l)>twopi*coss/2.0) return 1; rat = ra0; if (coss>deps) rat = rat + l / coss; break; case WCS_MER: /* -MER mercator*/ dt = yinc * cosr + xinc * sinr; if (dt==0.0) dt = 1.0; dy = degrad (yref/2.0 + 45.0); dx = dy + dt / 2.0 * cond2r; dy = log (tan (dy)); dx = log (tan (dx)); geo2 = degrad (dt) / (dx - dy); geo3 = geo2 * dy; geo1 = cos (degrad (yref)); if (geo1<=0.0) geo1 = 1.0; rat = l / geo1 + ra0; if (fabs(rat - ra0) > twopi) return 1; /* added 10/13/94 DCW/EWG */ dt = 0.0; if (geo2!=0.0) dt = (m + geo3) / geo2; dt = exp (dt); dect = 2.0 * atan (dt) - twopi / 4.0; break; case WCS_AIT: /* -AIT Aitoff*/ dt = yinc*cosr + xinc*sinr; if (dt==0.0) dt = 1.0; dt = degrad (dt); dy = degrad (yref); dx = sin(dy+dt)/sqrt((1.0+cos(dy+dt))/2.0) - sin(dy)/sqrt((1.0+cos(dy))/2.0); if (dx==0.0) dx = 1.0; geo2 = dt / dx; dt = xinc*cosr - yinc* sinr; if (dt==0.0) dt = 1.0; dt = degrad (dt); dx = 2.0 * cos(dy) * sin(dt/2.0); if (dx==0.0) dx = 1.0; geo1 = dt * sqrt((1.0+cos(dy)*cos(dt/2.0))/2.0) / dx; geo3 = geo2 * sin(dy) / sqrt((1.0+cos(dy))/2.0); rat = ra0; dect = dec0; if ((l==0.0) && (m==0.0)) break; dz = 4.0 - l*l/(4.0*geo1*geo1) - ((m+geo3)/geo2)*((m+geo3)/geo2) ; if ((dz>4.0) || (dz<2.0)) return 1;; dz = 0.5 * sqrt (dz); dd = (m+geo3) * dz / geo2; if (fabs(dd)>1.0) return 1;; dd = asin (dd); if (fabs(cos(dd))1.0) return 1;; da = asin (da); rat = ra0 + 2.0 * da; dect = dd; break; case WCS_STG: /* -STG Sterographic*/ dz = (4.0 - sins) / (4.0 + sins); if (fabs(dz)>1.0) return 1; dect = dz * sin0 + m * cos0 * (1.0+dz) / 2.0; if (fabs(dect)>1.0) return 1; dect = asin (dect); rat = cos(dect); if (fabs(rat)1.0) return 1; rat = asin (rat); mg = 1.0 + sin(dect) * sin0 + cos(dect) * cos0 * cos(rat); if (fabs(mg)deps) rat = twopi/2.0 - rat; rat = ra0 + rat; break; case WCS_COE: /* COE projection code from Andreas Wicenic, ESO */ td = tan (dec0); y0 = 1.0 / td; mt = y0 - m; if (dec0 < 0.) a = atan2 (l,-mt); else a = atan2 (l, mt); rat = ra0 - (a / sin0); r2 = (l * l) + (mt * mt); dect = asin (1.0 / (sin0 * 2.0) * (1.0 + sin0*sin0 * (1.0 - r2))); break; } /* Return RA in range */ raout = rat; decout = dect; if (raout-ra0>twopi/2.0) raout = raout - twopi; if (raout-ra0<-twopi/2.0) raout = raout + twopi; if (raout < 0.0) raout += twopi; /* added by DCW 10/12/94 */ /* Convert units back to degrees */ *xpos = raddeg (raout); *ypos = raddeg (decout); return 0; } /* End of worldpos */ int worldpix (xpos, ypos, wcs, xpix, ypix) /*-----------------------------------------------------------------------*/ /* routine to determine accurate pixel coordinates for an RA and Dec */ /* returns 0 if successful otherwise: */ /* 1 = angle too large for projection; */ /* 2 = bad values */ /* does: SIN, TAN, ARC, NCP, GLS or SFL, MER, AIT, STG, CAR, COE projections */ /* anything else is linear */ /* Input: */ double xpos; /* x (RA) coordinate (deg) */ double ypos; /* y (dec) coordinate (deg) */ struct WorldCoor *wcs; /* WCS parameter structure */ /* Output: */ double *xpix; /* x pixel number (RA or long without rotation) */ double *ypix; /* y pixel number (dec or lat without rotation) */ { double dx, dy, ra0, dec0, ra, dec, coss, sins, dt, da, dd, sint; double l, m, geo1, geo2, geo3, sinr, cosr, tx, x, a2, a3, a4; double rthea,gamby2,a,b,c,phi,an,rap,v,tthea,co1,co2,co3,co4,ansq; /* COE */ double cond2r=1.745329252e-2, deps=1.0e-5, twopi=6.28318530717959; /* Structure elements */ double xref; /* x reference coordinate value (deg) */ double yref; /* y reference coordinate value (deg) */ double xrefpix; /* x reference pixel */ double yrefpix; /* y reference pixel */ double xinc; /* x coordinate increment (deg) */ double yinc; /* y coordinate increment (deg) */ double rot; /* Optical axis rotation (deg) (from N through E) */ int itype; /* Set local projection parameters */ xref = wcs->xref; yref = wcs->yref; xrefpix = wcs->xrefpix; yrefpix = wcs->yrefpix; xinc = wcs->xinc; yinc = wcs->yinc; rot = degrad (wcs->rot); cosr = cos (rot); sinr = sin (rot); /* Projection type */ itype = wcs->prjcode; /* Nonlinear position */ if (itype > 0) { if (wcs->coorflip) { dec0 = degrad (xref); ra0 = degrad (yref); dt = xpos - yref; } else { ra0 = degrad (xref); dec0 = degrad (yref); dt = xpos - xref; } /* 0h wrap-around tests added by D.Wells 10/12/1994: */ /* Modified to exclude weird reference pixels by D.Mink 2/3/2004 */ if (xrefpix*xinc > 180.0 || xrefpix*xinc < -180.0) { if (dt > 360.0) xpos -= 360.0; if (dt < 0.0) xpos += 360.0; } else { if (dt > 180.0) xpos -= 360.0; if (dt < -180.0) xpos += 360.0; } /* NOTE: changing input argument xpos is OK (call-by-value in C!) */ ra = degrad (xpos); dec = degrad (ypos); /* Compute direction cosine */ coss = cos (dec); sins = sin (dec); l = sin(ra-ra0) * coss; sint = sins * sin(dec0) + coss * cos(dec0) * cos(ra-ra0); } else { l = 0.0; sint = 0.0; sins = 0.0; coss = 0.0; ra = 0.0; dec = 0.0; ra0 = 0.0; dec0 = 0.0; m = 0.0; } /* Process by case */ switch (itype) { case WCS_CAR: /* -CAR Cartesian */ l = ra - ra0; m = dec - dec0; break; case WCS_SIN: /* -SIN sin*/ if (sint<0.0) return 1; m = sins * cos(dec0) - coss * sin(dec0) * cos(ra-ra0); break; case WCS_TNX: /* -TNX tan with polynomial correction */ case WCS_TPV: /* -TPV tan with polynomial correction */ case WCS_ZPX: /* -ZPX zpn with polynomial correction */ case WCS_TAN: /* -TAN tan */ if (sint<=0.0) return 1; m = sins * sin(dec0) + coss * cos(dec0) * cos(ra-ra0); l = l / m; m = (sins * cos(dec0) - coss * sin(dec0) * cos(ra-ra0)) / m; break; case WCS_ARC: /* -ARC Arc*/ m = sins * sin(dec0) + coss * cos(dec0) * cos(ra-ra0); if (m<-1.0) m = -1.0; if (m>1.0) m = 1.0; m = acos (m); if (m!=0) m = m / sin(m); else m = 1.0; l = l * m; m = (sins * cos(dec0) - coss * sin(dec0) * cos(ra-ra0)) * m; break; case WCS_NCP: /* -NCP North celestial pole*/ if (dec0==0.0) return 1; /* can't stand the equator */ else m = (cos(dec0) - coss * cos(ra-ra0)) / sin(dec0); break; case WCS_GLS: /* -GLS global sinusoid */ case WCS_SFL: /* -SFL Samson-Flamsteed */ dt = ra - ra0; if (fabs(dec)>twopi/4.0) return 1; if (fabs(dec0)>twopi/4.0) return 1; m = dec - dec0; l = dt * coss; break; case WCS_MER: /* -MER mercator*/ dt = yinc * cosr + xinc * sinr; if (dt==0.0) dt = 1.0; dy = degrad (yref/2.0 + 45.0); dx = dy + dt / 2.0 * cond2r; dy = log (tan (dy)); dx = log (tan (dx)); geo2 = degrad (dt) / (dx - dy); geo3 = geo2 * dy; geo1 = cos (degrad (yref)); if (geo1<=0.0) geo1 = 1.0; dt = ra - ra0; l = geo1 * dt; dt = dec / 2.0 + twopi / 8.0; dt = tan (dt); if (dttwopi/4.0) return 1; dt = yinc*cosr + xinc*sinr; if (dt==0.0) dt = 1.0; dt = degrad (dt); dy = degrad (yref); dx = sin(dy+dt)/sqrt((1.0+cos(dy+dt))/2.0) - sin(dy)/sqrt((1.0+cos(dy))/2.0); if (dx==0.0) dx = 1.0; geo2 = dt / dx; dt = xinc*cosr - yinc* sinr; if (dt==0.0) dt = 1.0; dt = degrad (dt); dx = 2.0 * cos(dy) * sin(dt/2.0); if (dx==0.0) dx = 1.0; geo1 = dt * sqrt((1.0+cos(dy)*cos(dt/2.0))/2.0) / dx; geo3 = geo2 * sin(dy) / sqrt((1.0+cos(dy))/2.0); dt = sqrt ((1.0 + cos(dec) * cos(da))/2.0); if (fabs(dt)twopi/4.0) return 1; dd = 1.0 + sins * sin(dec0) + coss * cos(dec0) * cos(da); if (fabs(dd)rotmat) l = rap * an * (1.0 - ansq/6.0) * (wcs->cd[0] / fabs(wcs->cd[0])); else l = rap * an * (1.0 - ansq/6.0) * (xinc / fabs(xinc)); m = rthea - (rap * (1.0 - ansq/2.0)); break; } /* end of itype switch */ /* Convert back to degrees */ if (itype > 0) { dx = raddeg (l); dy = raddeg (m); } /* For linear or pixel projection */ else { dx = xpos - xref; dy = ypos - yref; } if (wcs->coorflip) { tx = dx; dx = dy; dy = tx; } /* Scale and rotate using CD matrix */ if (wcs->rotmat) { tx = dx * wcs->dc[0] + dy * wcs->dc[1]; dy = dx * wcs->dc[2] + dy * wcs->dc[3]; dx = tx; } /* Scale and rotate using CDELTn and CROTA2 */ else { /* Correct for rotation */ if (rot!=0.0) { tx = dx*cosr + dy*sinr; dy = dy*cosr - dx*sinr; dx = tx; } /* Scale using CDELT */ if (xinc != 0.) dx = dx / xinc; if (yinc != 0.) dy = dy / yinc; } /* Convert to pixels */ *xpix = dx + xrefpix; if (itype == WCS_CAR) { if (*xpix > wcs->nxpix) { x = *xpix - (360.0 / xinc); if (x > 0.0) *xpix = x; } else if (*xpix < 0) { x = *xpix + (360.0 / xinc); if (x <= wcs->nxpix) *xpix = x; } } *ypix = dy + yrefpix; return 0; } /* end worldpix */ /* Oct 26 1995 Fix bug which interchanged RA and Dec twice when coorflip * * Oct 31 1996 Fix CD matrix use in WORLDPIX * Nov 4 1996 Eliminate extra code for linear projection in WORLDPIX * Nov 5 1996 Add coordinate flip in WORLDPIX * * May 22 1997 Avoid angle wraparound when CTYPE is pixel * Jun 4 1997 Return without angle conversion from worldpos if type is PIXEL * * Oct 20 1997 Add chip rotation; compute rotation angle trig functions * Jan 23 1998 Change PCODE to PRJCODE * Jan 26 1998 Remove chip rotation code * Feb 5 1998 Make cd[] and dc[] vectors; use xinc, yinc, rot from init * Feb 23 1998 Add NOAO TNX projection as TAN * Apr 28 1998 Change projection flags to WCS_* * May 27 1998 Skip limit checking for linear projection * Jun 25 1998 Fix inverse for CAR projection * Aug 5 1998 Allan Brighton: Added COE projection (code from A. Wicenec, ESO) * Sep 30 1998 Fix bug in COE inverse code to get sign correct * * Oct 21 1999 Drop unused y from worldpix() * * Apr 3 2002 Use GLS and SFL interchangeably * * Feb 3 2004 Let ra be >180 in worldpix() if ref pixel is >180 deg away * * Jun 20 2006 Initialize uninitialized variables * * Mar 11 2011 Initialize ZPX * Sep 1 2011 Add TPV projection as TAN */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/dateutil.c0000664000175000017500000035002713047255533021447 0ustar mattymatty00000000000000/*** File libwcs/dateutil.c *** October 19, 2012 *** By Jessica Mink, jmink@cfa.harvard.edu *** Harvard-Smithsonian Center for Astrophysics *** Copyright (C) 1999-2012 *** Smithsonian Astrophysical Observatory, Cambridge, MA, USA This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Correspondence concerning WCSTools should be addressed as follows: Internet email: jmink@cfa.harvard.edu Postal address: Jessica Mink Smithsonian Astrophysical Observatory 60 Garden St. Cambridge, MA 02138 USA */ /* Date and time conversion routines using the following conventions: ang = Angle in fractional degrees deg = Angle in degrees as dd:mm:ss.ss doy = 2 floating point numbers: year and day, including fraction, of year *** First day of year is 1, not zero. dt = 2 floating point numbers: yyyy.mmdd, hh.mmssssss ep = fractional year, often epoch of a position including proper motion epb = Besselian epoch = 365.242198781-day years based on 1900.0 epj = Julian epoch = 365.25-day years based on 2000.0 fd = FITS date string which may be any of the following: yyyy.ffff (fractional year) dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard FITS use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) hr = Sexigesimal hours as hh:mm:dd.ss jd = Julian Date lt = Local time mjd = modified Julian Date = JD - 2400000.5 ofd = FITS date string (dd/mm/yy before 2000, else no return) time = use fd2* with no date to convert time as hh:mm:ss.ss to sec, day, year ts = UT seconds since 1950-01-01T00:00 (used for ephemeris computations) tsi = local seconds since 1980-01-01T00:00 (used by IRAF as a time tag) tsu = UT seconds since 1970-01-01T00:00 (used as Unix system time) tsd = UT seconds of current day ut = Universal Time (UTC) et = Ephemeris Time (or TDB or TT) = TAI + 32.184 seconds tai = International Atomic Time (Temps Atomique International) = ET - 32.184 seconds gps = GPS time = TAI - 19 seconds mst = Mean Greenwich Sidereal Time gst = Greenwich Sidereal Time (includes nutation) lst = Local Sidereal Time (includes nutation) (longitude must be set) hjd = Heliocentric Julian Date mhjd = modified Heliocentric Julian Date = HJD - 2400000.5 * ang2hr (angle) * Convert angle in decimal floating point degrees to hours as hh:mm:ss.ss * ang2deg (angle) * Convert angle in decimal floating point degrees to degrees as dd:mm:ss.ss * deg2ang (angle as dd:mm:ss.ss) * Convert angle in degrees as dd:mm:ss.ss to decimal floating point degrees * ang2hr (angle) * Convert angle in hours as hh:mm:ss.ss to decimal floating point degrees * * doy2dt (year, doy, date, time) * Convert year and day of year to date as yyyy.ddmm and time as hh.mmsss * doy2ep, doy2epb, doy2epj (date, time) * Convert year and day of year to fractional year * doy2fd (year, doy) * Convert year and day of year to FITS date string * doy2mjd (year, doy) * Convert year and day of year to modified Julian date * * dt2doy (date, time, year, doy) * Convert date as yyyy.ddmm and time as hh.mmsss to year and day of year * dt2ep, dt2epb, dt2epj (date, time) * Convert date as yyyy.ddmm and time as hh.mmsss to fractional year * dt2fd (date, time) * Convert date as yyyy.ddmm and time as hh.mmsss to FITS date string * dt2i (date,time,iyr,imon,iday,ihr,imn,sec, ndsec) * Convert yyyy.mmdd hh.mmssss to year month day hours minutes seconds * dt2jd (date,time) * Convert date as yyyy.ddmm and time as hh.mmsss to Julian date * dt2mjd (date,time) * Convert date as yyyy.ddmm and time as hh.mmsss to modified Julian date * dt2ts (date,time) * Convert date (yyyy.ddmm) and time (hh.mmsss) to seconds since 1950-01-01 * dt2tsi (date,time) * Convert date (yyyy.ddmm) and time (hh.mmsss) to seconds since 1980-01-01 * dt2tsu (date,time) * Convert date (yyyy.ddmm) and time (hh.mmsss) to seconds since 1970-01-01 * * ep2dt, epb2dt, epj2dt (epoch,date, time) * Convert fractional year to date as yyyy.ddmm and time as hh.mmsss * ep2fd, epb2fd, epj2fd (epoch) * Convert epoch to FITS ISO date string * ep2i, epb2i, epj2i (epoch,iyr,imon,iday,ihr,imn,sec, ndsec) * Convert fractional year to year month day hours minutes seconds * ep2jd, epb2jd, epj2jd (epoch) * Convert fractional year as used in epoch to Julian date * ep2mjd, epb2mjd, epj2mjd (epoch) * Convert fractional year as used in epoch to modified Julian date * ep2ts, epb2ts, epj2ts (epoch) * Convert fractional year to seconds since 1950.0 * * et2fd (string) * Convert from ET (or TDT or TT) in FITS format to UT in FITS format * fd2et (string) * Convert from UT in FITS format to ET (or TDT or TT) in FITS format * jd2jed (dj) * Convert from Julian Date to Julian Ephemeris Date * jed2jd (dj) * Convert from Julian Ephemeris Date to Julian Date * dt2et (date, time) * Convert date (yyyy.ddmm) and time (hh.mmsss) to ephemeris time * edt2dt (date, time) * Convert ephemeris date (yyyy.ddmm) and time (hh.mmsss) to UT * dt2tai (date, time) * Convert date (yyyy.ddmm) and time (hh.mmsss) to TAI date and time * tai2dt (date, time) * Convert TAI date (yyyy.ddmm) and time (hh.mmsss) to UT * ts2ets (tsec) * Convert from UT in seconds since 1950-01-01 to ET in same format * ets2ts (tsec) * Convert from ET in seconds since 1950-01-01 to UT in same format * * fd2ep, fd2epb, fd2epj (string) * Convert FITS date string to fractional year * Convert time alone to fraction of Besselian year * fd2doy (string, year, doy) * Convert FITS standard date string to year and day of year * fd2dt (string, date, time) * Convert FITS date string to date as yyyy.ddmm and time as hh.mmsss * Convert time alone to hh.mmssss with date set to 0.0 * fd2i (string,iyr,imon,iday,ihr,imn,sec, ndsec) * Convert FITS standard date string to year month day hours min sec * Convert time alone to hours min sec, year month day are zero * fd2jd (string) * Convert FITS standard date string to Julian date * Convert time alone to fraction of day * fd2mjd (string) * Convert FITS standard date string to modified Julian date * fd2ts (string) * Convert FITS standard date string to seconds since 1950.0 * Convert time alone to seconds of day * fd2fd (string) * Convert FITS standard date string to ISO FITS date string * fd2of (string) * Convert FITS standard date string to old-format FITS date and time * fd2ofd (string) * Convert FITS standard date string to old-format FITS date string * fd2oft (string) * Convert time part of FITS standard date string to FITS date string * * jd2doy (dj, year, doy) * Convert Julian date to year and day of year * jd2dt (dj,date,time) * Convert Julian date to date as yyyy.mmdd and time as hh.mmssss * jd2ep, jd2epb, jd2epj (dj) * Convert Julian date to fractional year as used in epoch * jd2fd (dj) * Convert Julian date to FITS ISO date string * jd2i (dj,iyr,imon,iday,ihr,imn,sec, ndsec) * Convert Julian date to year month day hours min sec * jd2mjd (dj) * Convert Julian date to modified Julian date * jd2ts (dj) * Convert Julian day to seconds since 1950.0 * * lt2dt() * Return local time as yyyy.mmdd and time as hh.mmssss * lt2fd() * Return local time as FITS ISO date string * lt2tsi() * Return local time as IRAF seconds since 1980-01-01 00:00 * lt2tsu() * Return local time as Unix seconds since 1970-01-01 00:00 * lt2ts() * Return local time as Unix seconds since 1950-01-01 00:00 * * mjd2doy (dj,year,doy) * Convert modified Julian date to date as year and day of year * mjd2dt (dj,date,time) * Convert modified Julian date to date as yyyy.mmdd and time as hh.mmssss * mjd2ep, mjd2epb, mjd2epj (dj) * Convert modified Julian date to fractional year as used in epoch * mjd2fd (dj) * Convert modified Julian date to FITS ISO date string * mjd2i (dj,iyr,imon,iday,ihr,imn,sec, ndsec) * Convert modified Julian date to year month day hours min sec * mjd2jd (dj) * Convert modified Julian date to Julian date * mjd2ts (dj) * Convert modified Julian day to seconds since 1950.0 * * ts2dt (tsec,date,time) * Convert seconds since 1950.0 to date as yyyy.ddmm and time as hh.mmsss * ts2ep, ts2epb, ts2epj (tsec) * Convert seconds since 1950.0 to fractional year * ts2fd (tsec) * Convert seconds since 1950.0 to FITS standard date string * ts2i (tsec,iyr,imon,iday,ihr,imn,sec, ndsec) * Convert sec since 1950.0 to year month day hours minutes seconds * ts2jd (tsec) * Convert seconds since 1950.0 to Julian date * ts2mjd (tsec) * Convert seconds since 1950.0 to modified Julian date * tsi2fd (tsec) * Convert seconds since 1980-01-01 to FITS standard date string * tsi2dt (tsec,date,time) * Convert seconds since 1980-01-01 to date as yyyy.ddmm, time as hh.mmsss * tsu2fd (tsec) * Convert seconds since 1970-01-01 to FITS standard date string * tsu2tsi (tsec) * Convert UT seconds since 1970-01-01 to local seconds since 1980-01-01 * tsu2dt (tsec,date,time) * Convert seconds since 1970-01-01 to date as yyyy.ddmm, time as hh.mmsss * * tsd2fd (tsec) * Convert seconds since start of day to FITS time, hh:mm:ss.ss * tsd2dt (tsec) * Convert seconds since start of day to hh.mmssss * * fd2gst (string) * convert from FITS date Greenwich Sidereal Time * dt2gst (date, time) * convert from UT as yyyy.mmdd hh.mmssss to Greenwich Sidereal Time * ts2gst (tsec) * Calculate Greenwich Sidereal Time given Universal Time * in seconds since 1951-01-01T0:00:00 * fd2mst (string) * convert from FITS UT date to Mean Sidereal Time * dt2gmt (date, time) * convert from UT as yyyy.mmdd hh.mmssss to Mean Sidereal Time * ts2mst (tsec) * Calculate Mean Sidereal Time given Universal Time * in seconds since 1951-01-01T0:00:00 * jd2mst (string) * convert from Julian Date to Mean Sidereal Time * mst2fd (string) * convert to current UT in FITS format given Greenwich Mean Sidereal Time * mst2jd (dj) * convert to current UT as Julian Date given Greenwich Mean Sidereal Time * jd2lst (dj) * Calculate Local Sidereal Time from Julian Date * ts2lst (tsec) * Calculate Local Sidereal Time given UT in seconds since 1951-01-01T0:00 * fd2lst (string) * Calculate Local Sidereal Time given Universal Time as FITS ISO date * lst2jd (dj, lst) * Calculate Julian Date given current Julian date and Local Sidereal Time * lst2fd (string, lst) * Calculate Julian Date given current UT date and Local Sidereal Time * gst2fd (string) * Calculate current UT given UT date and Greenwich Sidereal Time * gst2jd (dj) * Calculate current UT given UT date and Greenwich Sidereal Time as JD * * compnut (dj, dpsi, deps, eps0) * Compute the longitude and obliquity components of nutation and * mean obliquity from the IAU 1980 theory * * utdt (dj) * Compute difference between UT and dynamical time (ET-UT) * ut2dt (year, doy) * Current Universal Time to year and day of year * ut2dt (date, time) * Current Universal Time to date (yyyy.mmdd) and time (hh.mmsss) * ut2ep(), ut2epb(), ut2epj() * Current Universal Time to fractional year, Besselian, Julian epoch * ut2fd() * Current Universal Time to FITS ISO date string * ut2jd() * Current Universal Time to Julian Date * ut2mjd() * Current Universal Time to Modified Julian Date * ut2tsi() * Current Universal Time to IRAF seconds since 1980-01-01T00:00 * ut2tsu() * Current Universal Time to Unix seconds since 1970-01-01T00:00 * ut2ts() * Current Universal Time to seconds since 1950-01-01T00:00 * isdate (string) * Return 1 if string is a FITS date (old or ISO) * * Internally-used subroutines * * fixdate (iyr, imon, iday, ihr, imn, sec, ndsec) * Round seconds and make sure date and time numbers are within limits * caldays (year, month) * Calculate days in month 1-12 given year (Gregorian calendar only * dint (dnum) * Return integer part of floating point number * dmod (dnum) * Return Mod of floating point number */ #include #include #include #include #include #include #include "wcs.h" #include "fitsfile.h" static double suntl(); static void fixdate(); static int caldays(); static double dint(); static double dmod(); static double longitude = 0.0; /* longitude of observatory in degrees (+=west) */ void setlongitude (longitude0) double longitude0; { longitude = longitude0; return; } static int ndec = 3; void setdatedec (nd) int nd; { ndec = nd; return; } /* ANG2HR -- Convert angle in fraction degrees to hours as hh:mm:ss.ss */ void ang2hr (angle, lstr, string) double angle; /* Angle in fractional degrees */ int lstr; /* Maximum number of characters in string */ char *string; /* Character string (hh:mm:ss.ss returned) */ { angle = angle / 15.0; dec2str (string, lstr, angle, ndec); return; } /* ANG2DEG -- Convert angle in fraction degrees to degrees as dd:mm:ss.ss */ void ang2deg (angle, lstr, string) double angle; /* Angle in fractional degrees */ int lstr; /* Maximum number of characters in string */ char *string; /* Character string (dd:mm:ss.ss returned) */ { dec2str (string, lstr, angle, ndec); return; } /* DEG2ANG -- Convert angle in degrees as dd:mm:ss.ss to fractional degrees */ double deg2ang (angle) char *angle; /* Angle as dd:mm:ss.ss */ { double deg; deg = str2dec (angle); return (deg); } /* HR2ANG -- Convert angle in hours as hh:mm:ss.ss to fractional degrees */ double hr2ang (angle) char *angle; /* Angle in sexigesimal hours (hh:mm:ss.sss) */ { double deg; deg = str2dec (angle); deg = deg * 15.0; return (deg); } /* DT2FD-- convert vigesimal date and time to FITS date, yyyy-mm-ddThh:mm:ss.ss */ char * dt2fd (date, time) double date; /* Date as yyyy.mmdd yyyy = calendar year (e.g. 1973) mm = calendar month (e.g. 04 = april) dd = calendar day (e.g. 15) */ double time; /* Time as hh.mmssxxxx *if time<0, it is time as -(fraction of a day) hh = hour of day (0 .le. hh .le. 23) nn = minutes (0 .le. nn .le. 59) ss = seconds (0 .le. ss .le. 59) xxxx = tenths of milliseconds (0 .le. xxxx .le. 9999) */ { int iyr,imon,iday,ihr,imn; double sec; int nf; char *string; char tstring[32], dstring[32]; char outform[64]; dt2i (date, time, &iyr,&imon,&iday,&ihr,&imn,&sec, ndec); /* Convert to ISO date format */ string = (char *) calloc (32, sizeof (char)); /* Make time string */ if (time != 0.0 || ndec > 0) { if (ndec == 0) nf = 2; else nf = 3 + ndec; if (ndec > 0) { sprintf (outform, "%%02d:%%02d:%%0%d.%df", nf, ndec); sprintf (tstring, outform, ihr, imn, sec); } else { sprintf (outform, "%%02d:%%02d:%%0%dd", nf); sprintf (tstring, outform, ihr, imn, (int)(sec+0.5)); } } /* Make date string */ if (date != 0.0) sprintf (dstring, "%4d-%02d-%02d", iyr, imon, iday); /* Make FITS (ISO) date string */ if (date == 0.0) strcpy (string, tstring); else if (time == 0.0 && ndec < 1) strcpy (string, dstring); else sprintf (string, "%sT%s", dstring, tstring); return (string); } /* DT2JD-- convert from date as yyyy.mmdd and time as hh.mmsss to Julian Date * Return fractional days if date is zero */ double dt2jd (date,time) double date; /* Date as yyyy.mmdd yyyy = calendar year (e.g. 1973) mm = calendar month (e.g. 04 = april) dd = calendar day (e.g. 15) */ double time; /* Time as hh.mmssxxxx *if time<0, it is time as -(fraction of a day) hh = hour of day (0 .le. hh .le. 23) nn = minutes (0 .le. nn .le. 59) ss = seconds (0 .le. ss .le. 59) xxxx = tenths of milliseconds (0 .le. xxxx .le. 9999) */ { double dj; /* Julian date (returned) */ double tsec; /* seconds since 1950.0 */ tsec = dt2ts (date, time); if (date == 0.0) dj = tsec / 86400.0; else dj = ts2jd (tsec); return (dj); } /* DT2MJD-- convert from date yyyy.mmdd time hh.mmsss to modified Julian Date * Return fractional days if date is zero */ double dt2mjd (date,time) double date; /* Date as yyyy.mmdd yyyy = calendar year (e.g. 1973) mm = calendar month (e.g. 04 = april) dd = calendar day (e.g. 15) */ double time; /* Time as hh.mmssxxxx *if time<0, it is time as -(fraction of a day) hh = hour of day (0 .le. hh .le. 23) nn = minutes (0 .le. nn .le. 59) ss = seconds (0 .le. ss .le. 59) xxxx = tenths of milliseconds (0 .le. xxxx .le. 9999) */ { double dj; /* Modified Julian date (returned) */ double tsec; /* seconds since 1950.0 */ tsec = dt2ts (date, time); if (date == 0.0) dj = tsec / 86400.0; else dj = ts2jd (tsec); return (dj - 2400000.5); } /* HJD2JD-- convert Heliocentric Julian Date to (geocentric) Julian date */ double hjd2jd (dj, ra, dec, sys) double dj; /* Heliocentric Julian date */ double ra; /* Right ascension (degrees) */ double dec; /* Declination (degrees) */ int sys; /* J2000, B1950, GALACTIC, ECLIPTIC */ { double lt; /* Light travel difference to the Sun (days) */ lt = suntl (dj, ra, dec, sys); /* Return Heliocentric Julian Date */ return (dj - lt); } /* JD2HJD-- convert (geocentric) Julian date to Heliocentric Julian Date */ double jd2hjd (dj, ra, dec, sys) double dj; /* Julian date (geocentric) */ double ra; /* Right ascension (degrees) */ double dec; /* Declination (degrees) */ int sys; /* J2000, B1950, GALACTIC, ECLIPTIC */ { double lt; /* Light travel difference to the Sun (days) */ lt = suntl (dj, ra, dec, sys); /* Return Heliocentric Julian Date */ return (dj + lt); } /* MHJD2MJD-- convert modified Heliocentric Julian Date to modified geocentric Julian date */ double mhjd2mjd (mhjd, ra, dec, sys) double mhjd; /* Modified Heliocentric Julian date */ double ra; /* Right ascension (degrees) */ double dec; /* Declination (degrees) */ int sys; /* J2000, B1950, GALACTIC, ECLIPTIC */ { double lt; /* Light travel difference to the Sun (days) */ double hjd; /* Heliocentric Julian date */ hjd = mjd2jd (mhjd); lt = suntl (hjd, ra, dec, sys); /* Return Heliocentric Julian Date */ return (jd2mjd (hjd - lt)); } /* MJD2MHJD-- convert modified geocentric Julian date tp modified Heliocentric Julian Date */ double mjd2mhjd (mjd, ra, dec, sys) double mjd; /* Julian date (geocentric) */ double ra; /* Right ascension (degrees) */ double dec; /* Declination (degrees) */ int sys; /* J2000, B1950, GALACTIC, ECLIPTIC */ { double lt; /* Light travel difference to the Sun (days) */ double dj; /* Julian date (geocentric) */ dj = mjd2jd (mjd); lt = suntl (dj, ra, dec, sys); /* Return Heliocentric Julian Date */ return (jd2mjd (dj + lt)); } /* SUNTL-- compute light travel time to heliocentric correction in days */ /* Translated into C from IRAF SPP noao.astutils.asttools.asthjd.x */ static double suntl (dj, ra, dec, sys) double dj; /* Julian date (geocentric) */ double ra; /* Right ascension (degrees) */ double dec; /* Declination (degrees) */ int sys; /* J2000, B1950, GALACTIC, ECLIPTIC */ { double t; /* Number of Julian centuries since J1900 */ double manom; /* Mean anomaly of the Earth's orbit (degrees) */ double lperi; /* Mean longitude of perihelion (degrees) */ double oblq; /* Mean obliquity of the ecliptic (degrees) */ double eccen; /* Eccentricity of the Earth's orbit (dimensionless) */ double eccen2, eccen3; double tanom; /* True anomaly (approximate formula) (radians) */ double slong; /* True longitude of the Sun from the Earth (radians) */ double rs; /* Distance to the sun (AU) */ double lt; /* Light travel difference to the Sun (days) */ double l; /* Longitude of star in orbital plane of Earth (radians) */ double b; /* Latitude of star in orbital plane of Earth (radians) */ double epoch; /* Epoch of obervation */ double rs1,rs2; t = (dj - 2415020.0) / 36525.0; /* Compute earth orbital parameters */ manom = 358.47583 + (t * (35999.04975 - t * (0.000150 + t * 0.000003))); lperi = 101.22083 + (t * (1.7191733 + t * (0.000453 + t * 0.000003))); oblq = 23.452294 - (t * (0.0130125 + t * (0.00000164 - t * 0.000000503))); eccen = 0.01675104 - (t * (0.00004180 + t * 0.000000126)); eccen2 = eccen * eccen; eccen3 = eccen * eccen2; /* Convert to principle angles */ manom = manom - (360.0 * (dint) (manom / 360.0)); lperi = lperi - (360.0 * (dint) (lperi / 360.0)); /* Convert to radians */ manom = degrad (manom); lperi = degrad (lperi); oblq = degrad (oblq); /* True anomaly */ tanom = manom + (2 * eccen - 0.25 * eccen3) * sin (manom) + 1.25 * eccen2 * sin (2 * manom) + 13./12. * eccen3 * sin (3 * manom); /* Distance to the Sun */ rs1 = 1.0 - eccen2; rs2 = 1.0 + (eccen * cos (tanom)); rs = rs1 / rs2; /* True longitude of the Sun seen from the Earth */ slong = lperi + tanom + PI; /* Longitude and latitude of star in orbital plane of the Earth */ epoch = jd2ep (dj); wcscon (sys, WCS_ECLIPTIC, 0.0, 0.0, &ra, &dec, epoch); l = degrad (ra); b = degrad (dec); /* Light travel difference to the Sun */ lt = -0.005770 * rs * cos (b) * cos (l - slong); /* Return light travel difference */ return (lt); } /* JD2DT-- convert Julian date to date as yyyy.mmdd and time as hh.mmssss */ void jd2dt (dj,date,time) double dj; /* Julian date */ double *date; /* Date as yyyy.mmdd (returned) */ double *time; /* Time as hh.mmssxxxx (returned) */ { int iyr,imon,iday,ihr,imn; double sec; /* Convert Julian Date to date and time */ jd2i (dj, &iyr, &imon, &iday, &ihr, &imn, &sec, 4); /* Convert date to yyyy.mmdd */ if (iyr < 0) { *date = (double) (-iyr) + 0.01 * (double) imon + 0.0001 * (double) iday; *date = -(*date); } else *date = (double) iyr + 0.01 * (double) imon + 0.0001 * (double) iday; /* Convert time to hh.mmssssss */ *time = (double) ihr + 0.01 * (double) imn + 0.0001 * sec; return; } /* JD2I-- convert Julian date to date as year, month, and day, and time hours, minutes, and seconds */ /* after Fliegel and Van Flander, CACM 11, 657 (1968) */ void jd2i (dj, iyr, imon, iday, ihr, imn, sec, ndsec) double dj; /* Julian date */ int *iyr; /* year (returned) */ int *imon; /* month (returned) */ int *iday; /* day (returned) */ int *ihr; /* hours (returned) */ int *imn; /* minutes (returned) */ double *sec; /* seconds (returned) */ int ndsec; /* Number of decimal places in seconds (0=int) */ { double tsec; double frac, dts, ts, sday; int jd, l, n, i, j; tsec = jd2ts (dj); /* ts2i (tsec, iyr, imon, iday, ihr, imn, sec, ndsec); */ /* Round seconds to 0 - 4 decimal places */ if (tsec < 0.0) dts = -0.5; else dts = 0.5; if (ndsec < 1) ts = dint (tsec + dts); else if (ndsec < 2) ts = dint (tsec * 10.0 + dts) / 10.0; else if (ndsec < 3) ts = dint (tsec * 100.0 + dts) / 100.0; else if (ndsec < 4) ts = dint (tsec * 1000.0 + dts) / 1000.0; else ts = dint (tsec * 10000.0 + dts) / 10000.0; /* Convert back to Julian Date */ dj = ts2jd (ts); /* Compute time from fraction of a day */ frac = dmod (dj, 1.0); if (frac < 0.5) { jd = (int) (dj - frac); sday = (frac + 0.5) * 86400.0; } else { jd = (int) (dj - frac) + 1; sday = (frac - 0.5) * 86400.0; } *ihr = (int) (sday / 3600.0); sday = sday - (double) (*ihr * 3600); *imn = (int) (sday / 60.0); *sec = sday - (double) (*imn * 60); /* Compute day, month, year */ l = jd + 68569; n = (4 * l) / 146097; l = l - (146097 * n + 3) / 4; i = (4000 * (l + 1)) / 1461001; l = l - (1461 * i) / 4 + 31; j = (80 * l) / 2447; *iday = l - (2447 * j) / 80; l = j / 11; *imon = j + 2 - (12 * l); *iyr = 100 * (n - 49) + i + l; return; } /* JD2MJD-- convert Julian Date to Modified Julian Date */ double jd2mjd (dj) double dj; /* Julian Date */ { return (dj - 2400000.5); } /* JD2EP-- convert Julian date to fractional year as used in epoch */ double jd2ep (dj) double dj; /* Julian date */ { double date, time; jd2dt (dj, &date, &time); return (dt2ep (date, time)); } /* JD2EPB-- convert Julian date to Besselian epoch */ double jd2epb (dj) double dj; /* Julian date */ { return (1900.0 + (dj - 2415020.31352) / 365.242198781); } /* JD2EPJ-- convert Julian date to Julian epoch */ double jd2epj (dj) double dj; /* Julian date */ { return (2000.0 + (dj - 2451545.0) / 365.25); } /* LT2DT-- Return local time as yyyy.mmdd and time as hh.mmssss */ void lt2dt(date, time) double *date; /* Date as yyyy.mmdd (returned) */ double *time; /* Time as hh.mmssxxxx (returned) */ { time_t tsec; struct timeval tp; struct timezone tzp; struct tm *ts; gettimeofday (&tp,&tzp); tsec = tp.tv_sec; ts = localtime (&tsec); if (ts->tm_year < 1000) *date = (double) (ts->tm_year + 1900); else *date = (double) ts->tm_year; *date = *date + (0.01 * (double) (ts->tm_mon + 1)); *date = *date + (0.0001 * (double) ts->tm_mday); *time = (double) ts->tm_hour; *time = *time + (0.01 * (double) ts->tm_min); *time = *time + (0.0001 * (double) ts->tm_sec); return; } /* LT2FD-- Return current local time as FITS ISO date string */ char * lt2fd() { time_t tsec; struct tm *ts; struct timeval tp; struct timezone tzp; int month, day, year, hour, minute, second; char *isotime; gettimeofday (&tp,&tzp); tsec = tp.tv_sec; ts = localtime (&tsec); year = ts->tm_year; if (year < 1000) year = year + 1900; month = ts->tm_mon + 1; day = ts->tm_mday; hour = ts->tm_hour; minute = ts->tm_min; second = ts->tm_sec; isotime = (char *) calloc (32, sizeof (char)); sprintf (isotime, "%04d-%02d-%02dT%02d:%02d:%02d", year, month, day, hour, minute, second); return (isotime); } /* LT2TSI-- Return local time as IRAF seconds since 1980-01-01 00:00 */ int lt2tsi() { return ((int)(lt2ts() - 946684800.0)); } /* LT2TSU-- Return local time as Unix seconds since 1970-01-01 00:00 */ time_t lt2tsu() { return ((time_t)(lt2ts() - 631152000.0)); } /* LT2TS-- Return local time as Unix seconds since 1950-01-01 00:00 */ double lt2ts() { double tsec; char *datestring; datestring = lt2fd(); tsec = fd2ts (datestring); free (datestring); return (tsec); } /* MJD2DT-- convert Modified Julian Date to date (yyyy.mmdd) time (hh.mmssss) */ void mjd2dt (dj,date,time) double dj; /* Modified Julian Date */ double *date; /* Date as yyyy.mmdd (returned) yyyy = calendar year (e.g. 1973) mm = calendar month (e.g. 04 = april) dd = calendar day (e.g. 15) */ double *time; /* Time as hh.mmssxxxx (returned) *if time<0, it is time as -(fraction of a day) hh = hour of day (0 .le. hh .le. 23) nn = minutes (0 .le. nn .le. 59) ss = seconds (0 .le. ss .le. 59) xxxx = tenths of milliseconds (0 .le. xxxx .le. 9999) */ { double tsec; tsec = jd2ts (dj + 2400000.5); ts2dt (tsec, date, time); return; } /* MJD2I-- convert Modified Julian Date to date as year, month, day and time as hours, minutes, seconds */ void mjd2i (dj, iyr, imon, iday, ihr, imn, sec, ndsec) double dj; /* Modified Julian Date */ int *iyr; /* year (returned) */ int *imon; /* month (returned) */ int *iday; /* day (returned) */ int *ihr; /* hours (returned) */ int *imn; /* minutes (returned) */ double *sec; /* seconds (returned) */ int ndsec; /* Number of decimal places in seconds (0=int) */ { double tsec; tsec = jd2ts (dj + 2400000.5); ts2i (tsec, iyr, imon, iday, ihr, imn, sec, ndsec); return; } /* MJD2DOY-- convert Modified Julian Date to Year,Day-of-Year */ void mjd2doy (dj, year, doy) double dj; /* Modified Julian Date */ int *year; /* Year (returned) */ double *doy; /* Day of year with fraction (returned) */ { jd2doy (dj + 2400000.5, year, doy); return; } /* MJD2JD-- convert Modified Julian Date to Julian Date */ double mjd2jd (dj) double dj; /* Modified Julian Date */ { return (dj + 2400000.5); } /* MJD2EP-- convert Modified Julian Date to fractional year */ double mjd2ep (dj) double dj; /* Modified Julian Date */ { double date, time; jd2dt (dj + 2400000.5, &date, &time); return (dt2ep (date, time)); } /* MJD2EPB-- convert Modified Julian Date to Besselian epoch */ double mjd2epb (dj) double dj; /* Modified Julian Date */ { return (1900.0 + (dj - 15019.81352) / 365.242198781); } /* MJD2EPJ-- convert Modified Julian Date to Julian epoch */ double mjd2epj (dj) double dj; /* Modified Julian Date */ { return (2000.0 + (dj - 51544.5) / 365.25); } /* MJD2FD-- convert modified Julian date to FITS date, yyyy-mm-ddThh:mm:ss.ss */ char * mjd2fd (dj) double dj; /* Modified Julian date */ { return (jd2fd (dj + 2400000.5)); } /* MJD2TS-- convert modified Julian date to seconds since 1950.0 */ double mjd2ts (dj) double dj; /* Modified Julian date */ { return ((dj - 33282.0) * 86400.0); } /* EP2FD-- convert fractional year to FITS date, yyyy-mm-ddThh:mm:ss.ss */ char * ep2fd (epoch) double epoch; /* Date as fractional year */ { double tsec; /* seconds since 1950.0 (returned) */ tsec = ep2ts (epoch); return (ts2fd (tsec)); } /* EPB2FD-- convert Besselian epoch to FITS date, yyyy-mm-ddThh:mm:ss.ss */ char * epb2fd (epoch) double epoch; /* Besselian epoch (fractional 365.242198781-day years) */ { double dj; /* Julian Date */ dj = epb2jd (epoch); return (jd2fd (dj)); } /* EPJ2FD-- convert Julian epoch to FITS date, yyyy-mm-ddThh:mm:ss.ss */ char * epj2fd (epoch) double epoch; /* Julian epoch (fractional 365.25-day years) */ { double dj; /* Julian Date */ dj = epj2jd (epoch); return (jd2fd (dj)); } /* EP2TS-- convert fractional year to seconds since 1950.0 */ double ep2ts (epoch) double epoch; /* Date as fractional year */ { double dj; dj = ep2jd (epoch); return ((dj - 2433282.5) * 86400.0); } /* EPB2TS-- convert Besselian epoch to seconds since 1950.0 */ double epb2ts (epoch) double epoch; /* Besselian epoch (fractional 365.242198781-day years) */ { double dj; dj = epb2jd (epoch); return ((dj - 2433282.5) * 86400.0); } /* EPJ2TS-- convert Julian epoch to seconds since 1950.0 */ double epj2ts (epoch) double epoch; /* Julian epoch (fractional 365.25-day years) */ { double dj; dj = epj2jd (epoch); return ((dj - 2433282.5) * 86400.0); } /* EPB2EP-- convert Besselian epoch to fractional years */ double epb2ep (epoch) double epoch; /* Besselian epoch (fractional 365.242198781-day years) */ { double dj; dj = epb2jd (epoch); return (jd2ep (dj)); } /* EP2EPB-- convert fractional year to Besselian epoch */ double ep2epb (epoch) double epoch; /* Fractional year */ { double dj; dj = ep2jd (epoch); return (jd2epb (dj)); } /* EPJ2EP-- convert Julian epoch to fractional year */ double epj2ep (epoch) double epoch; /* Julian epoch (fractional 365.25-day years) */ { double dj; dj = epj2jd (epoch); return (jd2ep (dj)); } /* EP2EPJ-- convert fractional year to Julian epoch */ double ep2epj (epoch) double epoch; /* Fractional year */ { double dj; dj = ep2jd (epoch); return (jd2epj (dj)); } /* EP2I-- convert fractional year to year month day hours min sec */ void ep2i (epoch, iyr, imon, iday, ihr, imn, sec, ndsec) double epoch; /* Date as fractional year */ int *iyr; /* year (returned) */ int *imon; /* month (returned) */ int *iday; /* day (returned) */ int *ihr; /* hours (returned) */ int *imn; /* minutes (returned) */ double *sec; /* seconds (returned) */ int ndsec; /* Number of decimal places in seconds (0=int) */ { double date, time; ep2dt (epoch, &date, &time); dt2i (date, time, iyr,imon,iday,ihr,imn,sec, ndsec); return; } /* EPB2I-- convert Besselian epoch to year month day hours min sec */ void epb2i (epoch, iyr, imon, iday, ihr, imn, sec, ndsec) double epoch; /* Besselian epoch (fractional 365.242198781-day years) */ int *iyr; /* year (returned) */ int *imon; /* month (returned) */ int *iday; /* day (returned) */ int *ihr; /* hours (returned) */ int *imn; /* minutes (returned) */ double *sec; /* seconds (returned) */ int ndsec; /* Number of decimal places in seconds (0=int) */ { double date, time; epb2dt (epoch, &date, &time); dt2i (date, time, iyr,imon,iday,ihr,imn,sec, ndsec); return; } /* EPJ2I-- convert Julian epoch to year month day hours min sec */ void epj2i (epoch, iyr, imon, iday, ihr, imn, sec, ndsec) double epoch; /* Julian epoch (fractional 365.25-day years) */ int *iyr; /* year (returned) */ int *imon; /* month (returned) */ int *iday; /* day (returned) */ int *ihr; /* hours (returned) */ int *imn; /* minutes (returned) */ double *sec; /* seconds (returned) */ int ndsec; /* Number of decimal places in seconds (0=int) */ { double date, time; epj2dt (epoch, &date, &time); dt2i (date, time, iyr,imon,iday,ihr,imn,sec, ndsec); return; } /* EP2JD-- convert fractional year as used in epoch to Julian date */ double ep2jd (epoch) double epoch; /* Date as fractional year */ { double dj; /* Julian date (returned)*/ double date, time; ep2dt (epoch, &date, &time); dj = dt2jd (date, time); return (dj); } /* EPB2JD-- convert Besselian epoch to Julian Date */ double epb2jd (epoch) double epoch; /* Besselian epoch (fractional 365.242198781-day years) */ { return (2415020.31352 + ((epoch - 1900.0) * 365.242198781)); } /* EPJ2JD-- convert Julian epoch to Julian Date */ double epj2jd (epoch) double epoch; /* Julian epoch (fractional 365.25-day years) */ { return (2451545.0 + ((epoch - 2000.0) * 365.25)); } /* EP2MJD-- convert fractional year as used in epoch to modified Julian date */ double ep2mjd (epoch) double epoch; /* Date as fractional year */ { double dj; /* Julian date (returned)*/ double date, time; ep2dt (epoch, &date, &time); dj = dt2jd (date, time); return (dj - 2400000.5); } /* EPB2MJD-- convert Besselian epoch to modified Julian Date */ double epb2mjd (epoch) double epoch; /* Besselian epoch (fractional 365.242198781-day years) */ { return (15019.81352 + ((epoch - 1900.0) * 365.242198781)); } /* EPJ2MJD-- convert Julian epoch to modified Julian Date */ double epj2mjd (epoch) double epoch; /* Julian epoch (fractional 365.25-day years) */ { return (51544.5 + ((epoch - 2000.0) * 365.25)); } /* EPB2EPJ-- convert Besselian epoch to Julian epoch */ double epb2epj (epoch) double epoch; /* Besselian epoch (fractional 365.242198781-day years) */ { double dj; /* Julian date */ dj = epb2jd (epoch); return (jd2epj (dj)); } /* EPJ2EPB-- convert Julian epoch to Besselian epoch */ double epj2epb (epoch) double epoch; /* Julian epoch (fractional 365.25-day years) */ { double dj; /* Julian date */ dj = epj2jd (epoch); return (jd2epb (dj)); } /* JD2FD-- convert Julian date to FITS date, yyyy-mm-ddThh:mm:ss.ss */ char * jd2fd (dj) double dj; /* Julian date */ { double tsec; /* seconds since 1950.0 (returned) */ tsec = (dj - 2433282.5) * 86400.0; return (ts2fd (tsec)); } /* JD2TS-- convert Julian date to seconds since 1950.0 */ double jd2ts (dj) double dj; /* Julian date */ { return ((dj - 2433282.5) * 86400.0); } /* JD2TSI-- convert Julian date to IRAF seconds since 1980-01-01T0:00 */ int jd2tsi (dj) double dj; /* Julian date */ { double ts; ts = (dj - 2444239.5) * 86400.0; return ((int) ts); } /* JD2TSU-- convert Julian date to Unix seconds since 1970-01-01T0:00 */ time_t jd2tsu (dj) double dj; /* Julian date */ { return ((time_t)((dj - 2440587.5) * 86400.0)); } /* DT2DOY-- convert yyyy.mmdd hh.mmss to year and day of year */ void dt2doy (date, time, year, doy) double date; /* Date as yyyy.mmdd */ double time; /* Time as hh.mmssxxxx */ int *year; /* Year (returned) */ double *doy; /* Day of year with fraction (returned) */ { double dj; /* Julian date */ double dj0; /* Julian date on January 1 0:00 */ double date0; /* January first of date's year */ double dyear; dyear = floor (date); date0 = dyear + 0.0101; dj0 = dt2jd (date0, 0.0); dj = dt2jd (date, time); *year = (int) (dyear + 0.00000001); *doy = dj - dj0 + 1.0; return; } /* DOY2DT-- convert year and day of year to yyyy.mmdd hh.mmss */ void doy2dt (year, doy, date, time) int year; /* Year */ double doy; /* Day of year with fraction */ double *date; /* Date as yyyy.mmdd (returned) */ double *time; /* Time as hh.mmssxxxx (returned) */ { double dj; /* Julian date */ double dj0; /* Julian date on January 1 0:00 */ double date0; /* January first of date's year */ date0 = year + 0.0101; dj0 = dt2jd (date0, 0.0); dj = dj0 + doy - 1.0; jd2dt (dj, date, time); return; } /* DOY2EP-- convert year and day of year to fractional year as used in epoch */ double doy2ep (year, doy) int year; /* Year */ double doy; /* Day of year with fraction */ { double date, time; doy2dt (year, doy, &date, &time); return (dt2ep (date, time)); } /* DOY2EPB-- convert year and day of year to Besellian epoch */ double doy2epb (year, doy) int year; /* Year */ double doy; /* Day of year with fraction */ { double dj; dj = doy2jd (year, doy); return (jd2epb (dj)); } /* DOY2EPJ-- convert year and day of year to Julian epoch */ double doy2epj (year, doy) int year; /* Year */ double doy; /* Day of year with fraction */ { double dj; dj = doy2jd (year, doy); return (jd2epj (dj)); } /* DOY2FD-- convert year and day of year to FITS date */ char * doy2fd (year, doy) int year; /* Year */ double doy; /* Day of year with fraction */ { double dj; /* Julian date */ dj = doy2jd (year, doy); return (jd2fd (dj)); } /* DOY2JD-- convert year and day of year to Julian date */ double doy2jd (year, doy) int year; /* Year */ double doy; /* Day of year with fraction */ { double dj0; /* Julian date */ double date; /* Date as yyyy.mmdd (returned) */ double time; /* Time as hh.mmssxxxx (returned) */ date = (double) year + 0.0101; time = 0.0; dj0 = dt2jd (date, time); return (dj0 + doy - 1.0); } /* DOY2MJD-- convert year and day of year to Julian date */ double doy2mjd (year, doy) int year; /* Year */ double doy; /* Day of year with fraction */ { double dj0; /* Julian date */ double date; /* Date as yyyy.mmdd (returned) */ double time; /* Time as hh.mmssxxxx (returned) */ date = (double) year + 0.0101; time = 0.0; dj0 = dt2jd (date, time); return (dj0 + doy - 1.0 - 2400000.5); } /* DOY2TSU-- convert from FITS date to Unix seconds since 1970-01-01T0:00 */ time_t doy2tsu (year, doy) int year; /* Year */ double doy; /* Day of year with fraction */ { double dj; dj = doy2jd (year, doy); return ((time_t)jd2ts (dj)); } /* DOY2TSI-- convert from FITS date to IRAF seconds since 1980-01-01T0:00 */ int doy2tsi (year, doy) int year; /* Year */ double doy; /* Day of year with fraction */ { double dj; dj = doy2jd (year, doy); return ((int)jd2tsi (dj)); } /* DOY2TS-- convert year, day of year to seconds since 1950 */ double doy2ts (year, doy) int year; /* Year */ double doy; /* Day of year with fraction */ { double dj; dj = doy2jd (year, doy); return (jd2ts (dj)); } /* FD2DOY-- convert FITS date to year and day of year */ void fd2doy (string, year, doy) char *string; /* FITS date string, which may be: fractional year dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ int *year; /* Year (returned) */ double *doy; /* Day of year with fraction (returned) */ { double dj; /* Julian date */ dj = fd2jd (string); jd2doy (dj, year, doy); return; } /* JD2DOY-- convert Julian date to year and day of year */ void jd2doy (dj, year, doy) double dj; /* Julian date */ int *year; /* Year (returned) */ double *doy; /* Day of year with fraction (returned) */ { double date; /* Date as yyyy.mmdd (returned) */ double time; /* Time as hh.mmssxxxx (returned) */ double dj0; /* Julian date at 0:00 on 1/1 */ double dyear; jd2dt (dj, &date, &time); *year = (int) date; dyear = (double) *year; dj0 = dt2jd (dyear+0.0101, 0.0); *doy = dj - dj0 + 1.0; return; } /* TS2JD-- convert seconds since 1950.0 to Julian date */ double ts2jd (tsec) double tsec; /* seconds since 1950.0 */ { return (2433282.5 + (tsec / 86400.0)); } /* TS2MJD-- convert seconds since 1950.0 to modified Julian date */ double ts2mjd (tsec) double tsec; /* seconds since 1950.0 */ { return (33282.0 + (tsec / 86400.0)); } /* TS2EP-- convert seconds since 1950.0 to fractional year as used in epoch */ double ts2ep (tsec) double tsec; /* Seconds since 1950.0 */ { double date, time; ts2dt (tsec, &date, &time); return (dt2ep (date, time)); } /* TS2EPB-- convert seconds since 1950.0 to Besselian epoch */ double ts2epb (tsec) double tsec; /* Seconds since 1950.0 */ { double dj; /* Julian Date */ dj = ts2jd (tsec); return (jd2epb (dj)); } /* TS2EPB-- convert seconds since 1950.0 to Julian epoch */ double ts2epj (tsec) double tsec; /* Seconds since 1950.0 */ { double dj; /* Julian Date */ dj = ts2jd (tsec); return (jd2epj (dj)); } /* DT2EP-- convert from date, time as yyyy.mmdd hh.mmsss to fractional year */ double dt2ep (date, time) double date; /* Date as yyyy.mmdd yyyy = calendar year (e.g. 1973) mm = calendar month (e.g. 04 = april) dd = calendar day (e.g. 15) */ double time; /* Time as hh.mmssxxxx *if time<0, it is time as -(fraction of a day) hh = hour of day (0 .le. hh .le. 23) nn = minutes (0 .le. nn .le. 59) ss = seconds (0 .le. ss .le. 59) xxxx = tenths of milliseconds (0 .le. xxxx .le. 9999) */ { double epoch; /* Date as fractional year (returned) */ double dj, dj0, dj1, date0, time0, date1; dj = dt2jd (date, time); if (date == 0.0) epoch = dj / 365.2422; else { time0 = 0.0; date0 = dint (date) + 0.0101; date1 = dint (date) + 1.0101; dj0 = dt2jd (date0, time0); dj1 = dt2jd (date1, time0); epoch = dint (date) + ((dj - dj0) / (dj1 - dj0)); } return (epoch); } /* DT2EPB-- convert from date, time as yyyy.mmdd hh.mmsss to Besselian epoch */ double dt2epb (date, time) double date; /* Date as yyyy.mmdd yyyy = calendar year (e.g. 1973) mm = calendar month (e.g. 04 = april) dd = calendar day (e.g. 15) */ double time; /* Time as hh.mmssxxxx *if time<0, it is time as -(fraction of a day) hh = hour of day (0 .le. hh .le. 23) nn = minutes (0 .le. nn .le. 59) ss = seconds (0 .le. ss .le. 59) xxxx = tenths of milliseconds (0 .le. xxxx .le. 9999) */ { double dj; /* Julian date */ double epoch; /* Date as fractional year (returned) */ dj = dt2jd (date, time); if (date == 0.0) epoch = dj / 365.242198781; else epoch = jd2epb (dj); return (epoch); } /* DT2EPJ-- convert from date, time as yyyy.mmdd hh.mmsss to Julian epoch */ double dt2epj (date, time) double date; /* Date as yyyy.mmdd yyyy = calendar year (e.g. 1973) mm = calendar month (e.g. 04 = april) dd = calendar day (e.g. 15) */ double time; /* Time as hh.mmssxxxx *if time<0, it is time as -(fraction of a day) hh = hour of day (0 .le. hh .le. 23) nn = minutes (0 .le. nn .le. 59) ss = seconds (0 .le. ss .le. 59) xxxx = tenths of milliseconds (0 .le. xxxx .le. 9999) */ { double dj; /* Julian date */ double epoch; /* Date as fractional year (returned) */ dj = dt2jd (date, time); if (date == 0.0) epoch = dj / 365.25; else epoch = jd2epj (dj); return (epoch); } /* EP2DT-- convert from fractional year to date, time as yyyy.mmdd hh.mmsss */ void ep2dt (epoch, date, time) double epoch; /* Date as fractional year */ double *date; /* Date as yyyy.mmdd (returned) yyyy = calendar year (e.g. 1973) mm = calendar month (e.g. 04 = april) dd = calendar day (e.g. 15) */ double *time; /* Time as hh.mmssxxxx (returned) *if time<0, it is time as -(fraction of a day) hh = hour of day (0 .le. hh .le. 23) nn = minutes (0 .le. nn .le. 59) ss = seconds (0 .le. ss .le. 59) xxxx = tenths of milliseconds (0 .le. xxxx .le. 9999) */ { double dj, dj0, dj1, date0, time0, date1, epochi, epochf; time0 = 0.0; epochi = dint (epoch); epochf = epoch - epochi; date0 = epochi + 0.0101; date1 = epochi + 1.0101; dj0 = dt2jd (date0, time0); dj1 = dt2jd (date1, time0); dj = dj0 + epochf * (dj1 - dj0); jd2dt (dj, date, time); return; } /* EPB2DT-- convert from Besselian epoch to date, time as yyyy.mmdd hh.mmsss */ void epb2dt (epoch, date, time) double epoch; /* Besselian epoch (fractional 365.242198781-day years) */ double *date; /* Date as yyyy.mmdd (returned) yyyy = calendar year (e.g. 1973) mm = calendar month (e.g. 04 = april) dd = calendar day (e.g. 15) */ double *time; /* Time as hh.mmssxxxx (returned) *if time<0, it is time as -(fraction of a day) hh = hour of day (0 .le. hh .le. 23) nn = minutes (0 .le. nn .le. 59) ss = seconds (0 .le. ss .le. 59) xxxx = tenths of milliseconds (0 .le. xxxx .le. 9999) */ { double dj; /* Julian date */ dj = epb2jd (epoch); jd2dt (dj, date, time); } /* EPJ2DT-- convert from Julian epoch to date, time as yyyy.mmdd hh.mmsss */ void epj2dt (epoch, date, time) double epoch; /* Julian epoch (fractional 365.25-day years) */ double *date; /* Date as yyyy.mmdd (returned) yyyy = calendar year (e.g. 1973) mm = calendar month (e.g. 04 = april) dd = calendar day (e.g. 15) */ double *time; /* Time as hh.mmssxxxx (returned) *if time<0, it is time as -(fraction of a day) hh = hour of day (0 .le. hh .le. 23) nn = minutes (0 .le. nn .le. 59) ss = seconds (0 .le. ss .le. 59) xxxx = tenths of milliseconds (0 .le. xxxx .le. 9999) */ { double dj; /* Julian date */ dj = epj2jd (epoch); jd2dt (dj, date, time); } /* FD2JD-- convert FITS standard date to Julian date */ double fd2jd (string) char *string; /* FITS date string, which may be: fractional year dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ { double date, time; fd2dt (string, &date, &time); return (dt2jd (date, time)); } /* FD2MJD-- convert FITS standard date to modified Julian date */ double fd2mjd (string) char *string; /* FITS date string, which may be: fractional year dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ { return (fd2jd (string) - 2400000.5); } /* FD2TSU-- convert from FITS date to Unix seconds since 1970-01-01T0:00 */ time_t fd2tsu (string) char *string; /* FITS date string, which may be: fractional year dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ { double date, time; fd2dt (string, &date, &time); return (dt2tsu (date, time)); } /* FD2TSI-- convert from FITS date to IRAF seconds since 1980-01-01T0:00 */ int fd2tsi (string) char *string; /* FITS date string, which may be: fractional year dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ { double date, time; fd2dt (string, &date, &time); return (dt2tsi (date, time)); } /* FD2TS-- convert FITS standard date to seconds since 1950 */ double fd2ts (string) char *string; /* FITS date string, which may be: fractional year dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ { double date, time; fd2dt (string, &date, &time); return (dt2ts (date, time)); } /* FD2FD-- convert any FITS standard date to ISO FITS standard date */ char * fd2fd (string) char *string; /* FITS date string, which may be: fractional year dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ { double date, time; fd2dt (string, &date, &time); return (dt2fd (date, time)); } /* FD2OF-- convert any FITS standard date to old FITS standard date time */ char * fd2of (string) char *string; /* FITS date string, which may be: fractional year dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ { int iyr,imon,iday,ihr,imn; double sec; fd2i (string,&iyr,&imon,&iday,&ihr,&imn,&sec, 3); /* Convert to old FITS date format */ string = (char *) calloc (32, sizeof (char)); if (iyr < 1900) sprintf (string, "*** date out of range ***"); else if (iyr < 2000) sprintf (string, "%02d/%02d/%02d %02d:%02d:%06.3f", iday, imon, iyr-1900, ihr, imn, sec); else if (iyr < 2900.0) sprintf (string, "%02d/%02d/%3d %02d:%02d:%6.3f", iday, imon, iyr-1900, ihr, imn, sec); else sprintf (string, "*** date out of range ***"); return (string); } /* TAI-UTC from the U.S. Naval Observatory */ /* ftp://maia.usno.navy.mil/ser7/tai-utc.dat */ static double taijd[26]={2441317.5, 2441499.5, 2441683.5, 2442048.5, 2442413.5, 2442778.5, 2443144.5, 2443509.5, 2443874.5, 2444239.5, 2444786.5, 2445151.5, 2445516.5, 2446247.5, 2447161.5, 2447892.5, 2448257.5, 2448804.5, 2449169.5, 2449534.5, 2450083.5, 2450630.5, 2451179.5, 2453736.5, 2454832.5, 2456293.5}; static double taidt[26]={10.0,11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0, 20.0,21.0,22.0,23.0,24.0,25.0,26.0,27.0,28.0,29.0,30.0,31.0,32.0, 33.0,34.0,35.0}; static double dttab[173]={13.7,13.4,13.1,12.9,12.7,12.6,12.5,12.5,12.5,12.5, 12.5,12.5,12.5,12.5,12.5,12.5,12.5,12.4,12.3,12.2,12.0,11.7,11.4, 11.1,10.6,10.2, 9.6, 9.1, 8.6, 8.0, 7.5, 7.0, 6.6, 6.3, 6.0, 5.8, 5.7, 5.6, 5.6, 5.6, 5.7, 5.8, 5.9, 6.1, 6.2, 6.3, 6.5, 6.6, 6.8, 6.9, 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7, 7.7, 7.8, 7.8,7.88,7.82, 7.54, 6.97, 6.40, 6.02, 5.41, 4.10, 2.92, 1.82, 1.61, 0.10,-1.02, -1.28,-2.69,-3.24,-3.64,-4.54,-4.71,-5.11,-5.40,-5.42,-5.20,-5.46, -5.46,-5.79,-5.63,-5.64,-5.80,-5.66,-5.87,-6.01,-6.19,-6.64,-6.44, -6.47,-6.09,-5.76,-4.66,-3.74,-2.72,-1.54,-0.02, 1.24, 2.64, 3.86, 5.37, 6.14, 7.75, 9.13,10.46,11.53,13.36,14.65,16.01,17.20,18.24, 19.06,20.25,20.95,21.16,22.25,22.41,23.03,23.49,23.62,23.86,24.49, 24.34,24.08,24.02,24.00,23.87,23.95,23.86,23.93,23.73,23.92,23.96, 24.02,24.33,24.83,25.30,25.70,26.24,26.77,27.28,27.78,28.25,28.71, 29.15,29.57,29.97,30.36,30.72,31.07,31.35,31.68,32.18,32.68,33.15, 33.59,34.00,34.47,35.03,35.73,36.54,37.43,38.29,39.20,40.18,41.17, 42.23}; /* TAI2FD-- convert from TAI in FITS format to UT in FITS format */ char * tai2fd (string) char *string; /* FITS date string, which may be: fractional year dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ { double dj0, dj, tsec, dt; dj0 = fd2jd (string); dt = utdt (dj0); dj = dj0 - (dt / 86400.0); dt = utdt (dj); tsec = fd2ts (string); tsec = tsec - dt + 32.184; return (ts2fd (tsec)); } /* FD2TAI-- convert from UT in FITS format to TAI in FITS format */ char * fd2tai (string) char *string; /* FITS date string, which may be: fractional year dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ { double dj, tsec, dt; dj = fd2jd (string); dt = utdt (dj); tsec = fd2ts (string); tsec = tsec + dt - 32.184; return (ts2fd (tsec)); } /* DT2TAI-- convert from UT as yyyy.mmdd hh.mmssss to TAI in same format */ void dt2tai (date, time) double *date; /* Date as yyyy.mmdd */ double *time; /* Time as hh.mmssxxxx *if time<0, it is time as -(fraction of a day) */ { double dj, dt, tsec; dj = dt2jd (*date, *time); dt = utdt (dj); tsec = dt2ts (*date, *time); tsec = tsec + dt - 32.184; ts2dt (tsec, date, time); return; } /* TAI2DT-- convert from TAI as yyyy.mmdd hh.mmssss to UT in same format */ void tai2dt (date, time) double *date; /* Date as yyyy.mmdd */ double *time; /* Time as hh.mmssxxxx *if time<0, it is time as -(fraction of a day) */ { double dj, dt, tsec, tsec0; dj = dt2jd (*date, *time); dt = utdt (dj); tsec0 = dt2ts (*date, *time); tsec = tsec0 + dt; dj = ts2jd (tsec); dt = utdt (dj); tsec = tsec0 + dt + 32.184; ts2dt (tsec, date, time); return; } /* ET2FD-- convert from ET (or TDT or TT) in FITS format to UT in FITS format */ char * et2fd (string) char *string; /* FITS date string, which may be: fractional year dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ { double dj0, dj, tsec, dt; dj0 = fd2jd (string); dt = utdt (dj0); dj = dj0 - (dt / 86400.0); dt = utdt (dj); tsec = fd2ts (string); tsec = tsec - dt; return (ts2fd (tsec)); } /* FD2ET-- convert from UT in FITS format to ET (or TDT or TT) in FITS format */ char * fd2et (string) char *string; /* FITS date string, which may be: fractional year dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ { double dj, tsec, dt; dj = fd2jd (string); dt = utdt (dj); tsec = fd2ts (string); tsec = tsec + dt; return (ts2fd (tsec)); } /* DT2ET-- convert from UT as yyyy.mmdd hh.mmssss to ET in same format */ void dt2et (date, time) double *date; /* Date as yyyy.mmdd */ double *time; /* Time as hh.mmssxxxx *if time<0, it is time as -(fraction of a day) */ { double dj, dt, tsec; dj = dt2jd (*date, *time); dt = utdt (dj); tsec = dt2ts (*date, *time); tsec = tsec + dt; ts2dt (tsec, date, time); return; } /* EDT2DT-- convert from ET as yyyy.mmdd hh.mmssss to UT in same format */ void edt2dt (date, time) double *date; /* Date as yyyy.mmdd */ double *time; /* Time as hh.mmssxxxx *if time<0, it is time as -(fraction of a day) */ { double dj, dt, tsec, tsec0; dj = dt2jd (*date, *time); dt = utdt (dj); tsec0 = dt2ts (*date, *time); tsec = tsec0 + dt; dj = ts2jd (tsec); dt = utdt (dj); tsec = tsec0 + dt; ts2dt (tsec, date, time); return; } /* JD2JED-- convert from Julian Date to Julian Ephemeris Date */ double jd2jed (dj) double dj; /* Julian Date */ { double dt; dt = utdt (dj); return (dj + (dt / 86400.0)); } /* JED2JD-- convert from Julian Ephemeris Date to Julian Date */ double jed2jd (dj) double dj; /* Julian Ephemeris Date */ { double dj0, dt; dj0 = dj; dt = utdt (dj); dj = dj0 - (dt / 86400.0); dt = utdt (dj); return (dj - (dt / 86400.0)); } /* TS2ETS-- convert from UT in seconds since 1950-01-01 to ET in same format */ double ts2ets (tsec) double tsec; { double dj, dt; dj = ts2jd (tsec); dt = utdt (dj); return (tsec + dt); } /* ETS2TS-- convert from ET in seconds since 1950-01-01 to UT in same format */ double ets2ts (tsec) double tsec; { double dj, dj0, dt; dj0 = ts2jd (tsec); dt = utdt (dj0); dj = dj0 - (dt / 86400.0); dt = utdt (dj); return (tsec - dt); } /* UTDT-- Compute difference between UT and dynamical time (ET-UT) */ double utdt (dj) double dj; /* Julian Date (UT) */ { double dt, date, time, ts, ts1, ts0, date0, yfrac, diff, cj; int i, iyr, iyear; /* If after 1972-01-01, use tabulated TAI-UT */ if (dj >= 2441317.5) { dt = 0.0; for (i = 22; i > 0; i--) { if (dj >= taijd[i]) dt = taidt[i]; } dt = dt + 32.184; } /* For 1800-01-01 to 1972-01-01, use table of ET-UT from AE */ else if (dj >= 2378496.5) { jd2dt (dj, &date, &time); ts = jd2ts (dj); iyear = (int) date; iyr = iyear - 1800; date0 = (double) iyear + 0.0101; ts0 = dt2ts (date0, 0.0); date0 = (double) (iyear + 1) + 0.0101; ts1 = dt2ts (date0, 0.0); yfrac = (ts - ts0) / (ts1 - ts0); diff = dttab[iyr+1] - dttab[iyr]; dt = dttab[iyr] + (diff * yfrac); } /* Compute back to 1600 using formula from McCarthy and Babcock (1986) */ else if (dj >= 2305447.5) { cj = (dj - 2378496.5) / 36525.0; dt = 5.156 + 13.3066 * (cj - 0.19) * (cj - 0.19); } /* Compute back to 948 using formula from Stephenson and Morrison (1984) */ else if (dj >= 2067309.5) { cj = (dj - 2378496.5) / 36525.0; dt = 25.5 * cj * cj; } /*Compute back to 390 BC using formula from Stephenson and Morrison (1984)*/ else if (dj >= 0.0) { cj = (dj = 2378496.5) / 36525.0; dt = 1360.0 + (320.0 * cj) + (44.3 * cj * cj); } else dt = 0.0; return (dt); } /* FD2OFD-- convert any FITS standard date to old FITS standard date */ char * fd2ofd (string) char *string; /* FITS date string, which may be: fractional year dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ { int iyr,imon,iday,ihr,imn; double sec; fd2i (string,&iyr,&imon,&iday,&ihr,&imn,&sec, 3); /* Convert to old FITS date format */ string = (char *) calloc (32, sizeof (char)); if (iyr < 1900) sprintf (string, "*** date out of range ***"); else if (iyr < 2000) sprintf (string, "%02d/%02d/%02d", iday, imon, iyr-1900); else if (iyr < 2900.0) sprintf (string, "%02d/%02d/%3d", iday, imon, iyr-1900); else sprintf (string, "*** date out of range ***"); return (string); } /* FD2OFT-- convert any FITS standard date to old FITS standard time */ char * fd2oft (string) char *string; /* FITS date string, which may be: fractional year dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ { int iyr,imon,iday,ihr,imn; double sec; fd2i (string,&iyr,&imon,&iday,&ihr,&imn,&sec, 3); /* Convert to old FITS date format */ string = (char *) calloc (32, sizeof (char)); sprintf (string, "%02d:%02d:%06.3f", ihr, imn, sec); return (string); } /* FD2DT-- convert FITS standard date to date, time as yyyy.mmdd hh.mmsss */ void fd2dt (string, date, time) char *string; /* FITS date string, which may be: fractional year dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ double *date; /* Date as yyyy.mmdd (returned) yyyy = calendar year (e.g. 1973) mm = calendar month (e.g. 04 = april) dd = calendar day (e.g. 15) */ double *time; /* Time as hh.mmssxxxx (returned) *if time<0, it is time as -(fraction of a day) hh = hour of day (0 .le. hh .le. 23) nn = minutes (0 .le. nn .le. 59) ss = seconds (0 .le. ss .le. 59) xxxx = tenths of milliseconds (0 .le. xxxx .le. 9999) */ { int iyr,imon,iday,ihr,imn; double sec; fd2i (string,&iyr,&imon,&iday,&ihr,&imn,&sec, 4); /* Convert date to yyyy.mmdd */ if (iyr < 0) { *date = (double) (-iyr) + 0.01 * (double) imon + 0.0001 * (double) iday; *date = -(*date); } else *date = (double) iyr + 0.01 * (double) imon + 0.0001 * (double) iday; /* Convert time to hh.mmssssss */ *time = (double) ihr + 0.01 * (double) imn + 0.0001 * sec; return; } /* FD2EP-- convert from FITS standard date to fractional year */ double fd2ep (string) char *string; /* FITS date string, which may be: yyyy.ffff (fractional year) dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard FITS use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ { double dj; /* Julian date */ dj = fd2jd (string); if (dj < 1.0) return (dj / 365.2422); else return (jd2ep (dj)); } /* FD2EPB-- convert from FITS standard date to Besselian epoch */ double fd2epb (string) char *string; /* FITS date string, which may be: yyyy.ffff (fractional year) dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard FITS use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ { double dj; /* Julian date */ dj = fd2jd (string); if (dj < 1.0) return (dj / 365.242198781); else return (jd2epb (dj)); } /* FD2EPJ-- convert from FITS standard date to Julian epoch */ double fd2epj (string) char *string; /* FITS date string, which may be: yyyy.ffff (fractional year) dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard FITS use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ { double dj; /* Julian date */ dj = fd2jd (string); if (dj < 1.0) return (dj / 365.25); else return (jd2epj (dj)); } /* DT2TSU-- convert from date and time to Unix seconds since 1970-01-01T0:00 */ time_t dt2tsu (date,time) double date; /* Date as yyyy.mmdd */ double time; /* Time as hh.mmssxxxx *if time<0, it is time as -(fraction of a day) */ { return ((time_t)(dt2ts (date, time) - 631152000.0)); } /* DT2TSI-- convert from date and time to IRAF seconds since 1980-01-01T0:00 */ int dt2tsi (date,time) double date; /* Date as yyyy.mmdd */ double time; /* Time as hh.mmssxxxx *if time<0, it is time as -(fraction of a day) */ { return ((int)(dt2ts (date, time) - 946684800.0)); } /* DT2TS-- convert from date, time as yyyy.mmdd hh.mmsss to sec since 1950.0 */ double dt2ts (date,time) double date; /* Date as yyyy.mmdd yyyy = calendar year (e.g. 1973) mm = calendar month (e.g. 04 = april) dd = calendar day (e.g. 15) */ double time; /* Time as hh.mmssxxxx *if time<0, it is time as -(fraction of a day) hh = hour of day (0 .le. hh .le. 23) nn = minutes (0 .le. nn .le. 59) ss = seconds (0 .le. ss .le. 59) xxxx = tenths of milliseconds (0 .le. xxxx .le. 9999) */ { double tsec; /* Seconds past 1950.0 (returned) */ double dh,dm,dd; int iy,im,id; /* Calculate the number of full years, months, and days already * elapsed since 0h, March 1, -1 (up to most recent midnight). */ /* convert time of day to elapsed seconds */ /* If time is < 0, it is assumed to be a fractional day */ if (time < 0.0) tsec = time * -86400.0; else { dh = (int) (time + 0.0000000001); dm = (int) (((time - dh) * 100.0) + 0.0000000001); tsec = (time * 10000.0) - (dh * 10000.0) - (dm * 100.0); tsec = (int) (tsec * 100000.0 + 0.0001) / 100000.0; tsec = tsec + (dm * 60.0) + (dh * 3600.0); } /* Calculate the number of full months elapsed since * the current or most recent March */ if (date >= 0.0301) { iy = (int) (date + 0.0000000001); im = (int) (((date - (double) (iy)) * 10000.0) + 0.00000001); id = im % 100; im = (im / 100) + 9; if (im < 12) iy = iy - 1; im = im % 12; id = id - 1; /* starting with March as month 0 and ending with the following * February as month 11, the calculation of the number of days * per month reduces to a simple formula. the following statement * determines the number of whole days elapsed since 3/1/-1 and then * subtracts the 712163 days between then and 1/1/1950. it converts * the result to seconds and adds the accumulated seconds above. */ id = id + ((im+1+im/6+im/11)/2 * 31) + ((im-im/6-im/11)/2 * 30) + (iy / 4) - (iy / 100) + (iy / 400); dd = (double) id + (365.0 * (double) iy) - 712163.0; tsec = tsec + (dd * 86400.0); } return (tsec); } /* TS2DT-- convert seconds since 1950.0 to date, time as yyyy.mmdd hh.mmssss */ void ts2dt (tsec,date,time) double tsec; /* Seconds past 1950.0 */ double *date; /* Date as yyyy.mmdd (returned) yyyy = calendar year (e.g. 1973) mm = calendar month (e.g. 04 = april) dd = calendar day (e.g. 15) */ double *time; /* Time as hh.mmssxxxx (returned) *if time<0, it is time as -(fraction of a day) hh = hour of day (0 .le. hh .le. 23) nn = minutes (0 .le. nn .le. 59) ss = seconds (0 .le. ss .le. 59) xxxx = tenths of milliseconds (0 .le. xxxx .le. 9999) */ { int iyr,imon,iday,ihr,imn; double sec; ts2i (tsec,&iyr,&imon,&iday,&ihr,&imn,&sec, 4); /* Convert date to yyyy.mmdd */ if (iyr < 0) { *date = (double) (-iyr) + 0.01 * (double) imon + 0.0001 * (double) iday; *date = -(*date); } else *date = (double) iyr + 0.01 * (double) imon + 0.0001 * (double) iday; /* Convert time to hh.mmssssss */ *time = (double) ihr + 0.01 * (double) imn + 0.0001 * sec; return; } /* TSI2DT-- Convert seconds since 1980-01-01 to date yyyy.ddmm, time hh.mmsss */ void tsi2dt (isec,date,time) int isec; /* Seconds past 1980-01-01 */ double *date; /* Date as yyyy.mmdd (returned) */ double *time; /* Time as hh.mmssxxxx (returned) */ { ts2dt (tsi2ts (isec), date, time); } /* TSI2FD-- Convert seconds since 1980-01-01 to FITS standard date string */ char * tsi2fd (isec) int isec; /* Seconds past 1980-01-01 */ { return (ts2fd (tsi2ts (isec))); } /* TSI2TS-- Convert seconds since 1980-01-01 to seconds since 1950-01-01 */ double tsi2ts (isec) int isec; /* Seconds past 1980-01-01 */ { return ((double) isec + 946684800.0); } /* TSU2FD-- Convert seconds since 1970-01-01 to FITS standard date string */ char * tsu2fd (isec) time_t isec; /* Seconds past 1970-01-01 */ { return (ts2fd (tsu2ts (isec))); } /* TSU2DT-- Convert seconds since 1970-01-01 to date yyyy.ddmm, time hh.mmsss */ void tsu2dt (isec,date,time) time_t isec; /* Seconds past 1970-01-01 */ double *date; /* Date as yyyy.mmdd (returned) */ double *time; /* Time as hh.mmssxxxx (returned) */ { ts2dt (tsu2ts (isec), date, time); } /* TSU2TS-- Convert seconds since 1970-01-01 to seconds since 1950-01-01 */ double tsu2ts (isec) time_t isec; /* Seconds past 1970-01-01 */ { return ((double) isec + 631152000.0); } /* TSU2TSI-- UT seconds since 1970-01-01 to local seconds since 1980-01-01 */ int tsu2tsi (isec) time_t isec; /* Seconds past 1970-01-01 */ { double date, time; struct tm *ts; /* Get local time from UT seconds */ ts = localtime (&isec); if (ts->tm_year < 1000) date = (double) (ts->tm_year + 1900); else date = (double) ts->tm_year; date = date + (0.01 * (double) (ts->tm_mon + 1)); date = date + (0.0001 * (double) ts->tm_mday); time = (double) ts->tm_hour; time = time + (0.01 * (double) ts->tm_min); time = time + (0.0001 * (double) ts->tm_sec); return ((int)(dt2ts (date, time) - 631152000.0)); } /* TS2FD-- convert seconds since 1950.0 to FITS date, yyyy-mm-ddThh:mm:ss.ss */ char * ts2fd (tsec) double tsec; /* Seconds past 1950.0 */ { double date, time; ts2dt (tsec, &date, &time); return (dt2fd (date, time)); } /* TSD2FD-- convert seconds since start of day to FITS time, hh:mm:ss.ss */ char * tsd2fd (tsec) double tsec; /* Seconds since start of day */ { double date, time; char *thms, *fdate; int lfd, nbc; ts2dt (tsec, &date, &time); fdate = dt2fd (date, time); thms = (char *) calloc (16, 1); lfd = strlen (fdate); nbc = lfd - 11; strncpy (thms, fdate+11, nbc); return (thms); } /* TSD2DT-- convert seconds since start of day to hh.mmssss */ double tsd2dt (tsec) double tsec; /* Seconds since start of day */ { double date, time; ts2dt (tsec, &date, &time); return (time); } /* DT2I-- convert vigesimal date and time to year month day hours min sec */ void dt2i (date, time, iyr, imon, iday, ihr, imn, sec, ndsec) double date; /* Date as yyyy.mmdd (returned) yyyy = calendar year (e.g. 1973) mm = calendar month (e.g. 04 = april) dd = calendar day (e.g. 15) */ double time; /* Time as hh.mmssxxxx (returned) *if time<0, it is time as -(fraction of a day) hh = hour of day (0 .le. hh .le. 23) nn = minutes (0 .le. nn .le. 59) ss = seconds (0 .le. ss .le. 59) xxxx = tenths of milliseconds (0 .le. xxxx .le. 9999) */ int *iyr; /* year (returned) */ int *imon; /* month (returned) */ int *iday; /* day (returned) */ int *ihr; /* hours (returned) */ int *imn; /* minutes (returned) */ double *sec; /* seconds (returned) */ int ndsec; /* Number of decimal places in seconds (0=int) */ { double t,d; t = time; if (date < 0.0) d = -date; else d = date; /* Extract components of time */ *ihr = dint (t + 0.000000001); t = 100.0 * (t - (double) *ihr); *imn = dint (t + 0.0000001); *sec = 100.0 * (t - (double) *imn); /* Extract components of date */ *iyr = dint (d + 0.00001); d = 100.0 * (d - (double) *iyr); if (date < 0.0) *iyr = - *iyr; *imon = dint (d + 0.001); d = 100.0 * (d - (double) *imon); *iday = dint (d + 0.1); /* Make sure date and time are legal */ fixdate (iyr, imon, iday, ihr, imn, sec, ndsec); return; } /* FD2I-- convert from FITS standard date to year, mon, day, hours, min, sec */ void fd2i (string, iyr, imon, iday, ihr, imn, sec, ndsec) char *string; /* FITS date string, which may be: yyyy.ffff (fractional year) dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard FITS use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ int *iyr; /* year (returned) */ int *imon; /* month (returned) */ int *iday; /* day (returned) */ int *ihr; /* hours (returned) */ int *imn; /* minutes (returned) */ double *sec; /* seconds (returned) */ int ndsec; /* Number of decimal places in seconds (0=int) */ { double tsec, fday, hr, mn; int i; char *sstr, *dstr, *tstr, *cstr, *nval, *fstr; /* Initialize all returned data to zero */ *iyr = 0; *imon = 0; *iday = 0; *ihr = 0; *imn = 0; *sec = 0.0; /* Return if no input string */ if (string == NULL) return; /* Check for various non-numeric characters */ sstr = strchr (string,'/'); dstr = strchr (string,'-'); if (dstr == string) dstr = strchr (string+1, '-'); fstr = strchr (string, '.'); tstr = strchr (string,'T'); if (tstr == NULL) tstr = strchr (string, 'Z'); if (tstr == NULL) tstr = strchr (string, 'S'); if (fstr != NULL && tstr != NULL && fstr > tstr) fstr = NULL; cstr = strchr (string,':'); /* Original FITS date format: dd/mm/yy */ if (sstr > string) { *sstr = '\0'; *iday = (int) atof (string); if (*iday > 31) { *iyr = *iday; if (*iyr >= 0 && *iyr <= 49) *iyr = *iyr + 2000; else if (*iyr < 1000) *iyr = *iyr + 1900; *sstr = '/'; nval = sstr + 1; sstr = strchr (nval,'/'); if (sstr > string) { *sstr = '\0'; *imon = (int) atof (nval); *sstr = '/'; nval = sstr + 1; *iday = (int) atof (nval); } } else { *sstr = '/'; nval = sstr + 1; sstr = strchr (nval,'/'); if (sstr == NULL) sstr = strchr (nval,'-'); if (sstr > string) { *sstr = '\0'; *imon = (int) atof (nval); *sstr = '/'; nval = sstr + 1; *iyr = (int) atof (nval); if (*iyr >= 0 && *iyr <= 49) *iyr = *iyr + 2000; else if (*iyr < 1000) *iyr = *iyr + 1900; } } tstr = strchr (string,'_'); if (tstr == NULL) return; } /* New FITS date format: yyyy-mm-ddThh:mm:ss[.sss] */ else if (dstr > string) { *dstr = '\0'; *iyr = (int) atof (string); *dstr = '-'; nval = dstr + 1; dstr = strchr (nval,'-'); *imon = 1; *iday = 1; /* Decode year, month, and day */ if (dstr > string) { *dstr = '\0'; *imon = (int) atof (nval); *dstr = '-'; nval = dstr + 1; if (tstr > string) *tstr = '\0'; *iday = (int) atof (nval); /* If fraction of a day is present, turn it into a time */ if (fstr != NULL) { fday = atof (fstr); hr = fday * 24.0; *ihr = (int) hr; mn = 60.0 * (hr - (double) *ihr); *imn = (int) mn; *sec = 60.0 * (mn - (double) *imn); } if (tstr > string) *tstr = 'T'; } /* If date is > 31, it is really year in old format */ if (*iday > 31) { i = *iyr; if (*iday < 100) *iyr = *iday + 1900; else *iyr = *iday; *iday = i; } } /* In rare cases, a FITS time is entered as an epoch */ else if (tstr == NULL && cstr == NULL && isnum (string)) { tsec = ep2ts (atof (string)); ts2i (tsec,iyr,imon,iday,ihr,imn,sec, ndsec); return; } /* Extract time, if it is present */ if (tstr > string || cstr > string) { if (tstr > string) nval = tstr + 1; else nval = string; cstr = strchr (nval,':'); if (cstr > string) { *cstr = '\0'; *ihr = (int) atof (nval); *cstr = ':'; nval = cstr + 1; cstr = strchr (nval,':'); if (cstr > string) { *cstr = '\0'; *imn = (int) atof (nval); *cstr = ':'; nval = cstr + 1; *sec = atof (nval); } else *imn = (int) atof (nval); } else *ihr = (int) atof (nval); } else ndsec = -1; /* Make sure date and time are legal */ fixdate (iyr, imon, iday, ihr, imn, sec, ndsec); return; } /* TS2I-- convert sec since 1950.0 to year month day hours minutes seconds */ void ts2i (tsec,iyr,imon,iday,ihr,imn,sec, ndsec) double tsec; /* seconds since 1/1/1950 0:00 */ int *iyr; /* year (returned) */ int *imon; /* month (returned) */ int *iday; /* day (returned) */ int *ihr; /* hours (returned) */ int *imn; /* minutes (returned) */ double *sec; /* seconds (returned) */ int ndsec; /* Number of decimal places in seconds (0=int) */ { double t,days, ts, dts; int nc,nc4,nly,ny,m,im; /* Round seconds to 0 - 4 decimal places */ ts = tsec + 61530883200.0; if (ts < 0.0) dts = -0.5; else dts = 0.5; if (ndsec < 1) t = dint (ts + dts) * 10000.0; else if (ndsec < 2) t = dint (ts * 10.0 + dts) * 1000.0; else if (ndsec < 3) t = dint (ts * 100.0 + dts) * 100.0; else if (ndsec < 4) t = dint (ts * 1000.0 + dts) * 10.0; else t = dint (ts * 10000.0 + dts); ts = t / 10000.0; /* Time of day (hours, minutes, seconds */ *ihr = (int) (dmod (ts/3600.0, 24.0)); *imn = (int) (dmod (ts/60.0, 60.0)); *sec = dmod (ts, 60.0); /* Number of days since 0 hr 0/0/0000 */ days = dint ((t / 864000000.0) + 0.000001); /* Number of leap centuries (400 years) */ nc4 = (int) ((days / 146097.0) + 0.00001); /* Number of centuries since last /400 */ days = days - (146097.0 * (double) (nc4)); nc = (int) ((days / 36524.0) + 0.000001); if (nc > 3) nc = 3; /* Number of leap years since last century */ days = days - (36524.0 * nc); nly = (int) ((days / 1461.0) + 0.0000000001); /* Number of years since last leap year */ days = days - (1461.0 * (double) nly); ny = (int) ((days / 365.0) + 0.00000001); if (ny > 3) ny = 3; /* Day of month */ days = days - (365.0 * (double) ny); if (days < 0) { m = 0; *iday = 29; } else { *iday = (int) (days + 0.00000001) + 1; for (m = 1; m <= 12; m++) { im = (m + ((m - 1) / 5)) % 2; /* fprintf (stderr,"%d %d %d %d\n", m, im, *iday, nc); */ if (*iday-1 < im+30) break; *iday = *iday - im - 30; } } /* Month */ *imon = ((m+1) % 12) + 1; /* Year */ *iyr = nc4*400 + nc*100 + nly*4 + ny + m/11; /* Make sure date and time are legal */ fixdate (iyr, imon, iday, ihr, imn, sec, ndsec); return; } /* UT2DOY-- Current Universal Time as year, day of year */ void ut2doy (year, doy) int *year; /* Year (returned) */ double *doy; /* Day of year (returned) */ { double date, time; ut2dt (&date, &time); dt2doy (date, time, year, doy); return; } /* UT2DT-- Current Universal Time as date (yyyy.mmdd) and time (hh.mmsss) */ void ut2dt(date, time) double *date; /* Date as yyyy.mmdd (returned) */ double *time; /* Time as hh.mmssxxxx (returned) */ { time_t tsec; struct timeval tp; struct timezone tzp; struct tm *ts; gettimeofday (&tp,&tzp); tsec = tp.tv_sec; ts = gmtime (&tsec); if (ts->tm_year < 1000) *date = (double) (ts->tm_year + 1900); else *date = (double) ts->tm_year; *date = *date + (0.01 * (double) (ts->tm_mon + 1)); *date = *date + (0.0001 * (double) ts->tm_mday); *time = (double) ts->tm_hour; *time = *time + (0.01 * (double) ts->tm_min); *time = *time + (0.0001 * (double) ts->tm_sec); return; } /* UT2EP-- Return current Universal Time as fractional year */ double ut2ep() { return (jd2ep (ut2jd())); } /* UT2EPB-- Return current Universal Time as Besselian epoch */ double ut2epb() { return (jd2epb (ut2jd())); } /* UT2EPJ-- Return current Universal Time as Julian epoch */ double ut2epj() { return (jd2epj (ut2jd())); } /* UT2FD-- Return current Universal Time as FITS ISO date string */ char * ut2fd() { int year, month, day, hour, minute, second; time_t tsec; struct timeval tp; struct timezone tzp; struct tm *ts; char *isotime; gettimeofday (&tp,&tzp); tsec = tp.tv_sec; ts = gmtime (&tsec); year = ts->tm_year; if (year < 1000) year = year + 1900; month = ts->tm_mon + 1; day = ts->tm_mday; hour = ts->tm_hour; minute = ts->tm_min; second = ts->tm_sec; isotime = (char *) calloc (32, sizeof (char)); sprintf (isotime, "%04d-%02d-%02dT%02d:%02d:%02d", year, month, day, hour, minute, second); return (isotime); } /* UT2JD-- Return current Universal Time as Julian Date */ double ut2jd() { return (fd2jd (ut2fd())); } /* UT2MJD-- convert current UT to Modified Julian Date */ double ut2mjd () { return (ut2jd() - 2400000.5); } /* UT2TS-- current Universal Time as IRAF seconds since 1950-01-01T00:00 */ double ut2ts() { double tsec; char *datestring; datestring = ut2fd(); tsec = fd2ts (datestring); free (datestring); return (tsec); } /* UT2TSI-- current Universal Time as IRAF seconds since 1980-01-01T00:00 */ int ut2tsi() { return ((int)(ut2ts() - 946684800.0)); } /* UT2TSU-- current Universal Time as IRAF seconds since 1970-01-01T00:00 */ time_t ut2tsu() { return ((time_t)(ut2ts () - 631152000.0)); } /* FD2GST-- convert from FITS date to Greenwich Sidereal Time */ char * fd2gst (string) char *string; /* FITS date string, which may be: fractional year dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ { double dj, gsec, date, time; dj = fd2jd (string); gsec = jd2gst (dj); ts2dt (gsec, &date, &time); date = 0.0; return (dt2fd (date, time)); } /* DT2GST-- convert from UT as yyyy.mmdd hh.mmssss to Greenwich Sidereal Time*/ void dt2gst (date, time) double *date; /* Date as yyyy.mmdd */ double *time; /* Time as hh.mmssxxxx *if time<0, it is time as -(fraction of a day) */ { double dj, gsec; dj = dt2ts (*date, *time); gsec = jd2gst (dj); ts2dt (gsec, date, time); *date = 0.0; return; } /* JD2LST - Local Sidereal Time in seconds from Julian Date */ double jd2lst (dj) double dj; /* Julian Date */ { double gst, lst; /* Compute Greenwich Sidereal Time at this epoch */ gst = jd2gst (dj); /* Subtract longitude (degrees to seconds of time) */ lst = gst - (240.0 * longitude); if (lst < 0.0) lst = lst + 86400.0; else if (lst > 86400.0) lst = lst - 86400.0; return (lst); } /* FD2LST - Local Sidereal Time as hh:mm:ss.ss from Universal Time as FITS ISO date */ char * fd2lst (string) char *string; /* FITS date string, which may be: fractional year dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard use before 2000) yyyy-mm-dd (FITS standard after 1999) */ { double dj, date, time, lst; dj = fd2jd (string); lst = jd2lst (dj); ts2dt (lst, &date, &time); date = 0.0; return (dt2fd (date, time)); } /* DT2LST - Local Sidereal Time as hh.mmssss from Universal Time as yyyy.mmdd hh.mmssss */ void dt2lst (date, time) double *date; /* Date as yyyy.mmdd */ double *time; /* Time as hh.mmssxxxx *if time<0, it is time as -(fraction of a day) */ { double dj, lst, date0; dj = dt2jd (*date, *time); lst = jd2lst (dj); date0 = 0.0; ts2dt (lst, &date0, time); return; } /* TS2LST - Local Sidereal Time in seconds of day * from Universal Time in seconds since 1951-01-01T0:00:00 */ double ts2lst (tsec) double tsec; /* time since 1950.0 in UT seconds */ { double gst; /* Greenwich Sidereal Time in seconds since 0:00 */ double lst; /* Local Sidereal Time in seconds since 0:00 */ double gsec, date; /* Greenwich Sidereal Time */ gsec = ts2gst (tsec); date = 0.0; ts2dt (gsec, &date, &gst); lst = gst - (longitude / 15.0); if (lst < 0.0) lst = lst + 86400.0; else if (lst > 86400.0) lst = lst - 86400.0; return (lst); } /* LST2FD - calculate current UT given Local Sidereal Time * plus date in FITS ISO format (yyyy-mm-dd) * Return UT date and time in FITS ISO format */ char * lst2fd (string) char *string; /* UT Date, LST as yyyy-mm-ddShh:mm:ss.ss */ { double sdj, dj; sdj = fd2jd (string); dj = lst2jd (sdj); return (jd2fd (dj)); } /* LST2JD - calculate current Julian Date given Local Sidereal Time * plus current Julian Date (0.5 at 0:00 UT) * Return UT date and time as Julian Date */ double lst2jd (sdj) double sdj; /* Julian Date of desired day at 0:00 UT + sidereal time */ { double gst; /* Greenwich Sidereal Time in seconds since 0:00 */ double lsd; /* Local Sidereal Time in seconds since 0:00 */ double gst0, tsd, dj1, dj0, eqnx; int idj; /* Julian date at 0:00 UT */ idj = (int) sdj; dj0 = (double) idj + 0.5; if (dj0 > sdj) dj0 = dj0 - 1.0; /* Greenwich Sidereal Time at 0:00 UT in seconds */ gst0 = jd2gst (dj0); /* Sidereal seconds since 0:00 */ lsd = (sdj - dj0) * 86400.0; /* Remove longitude for current Greenwich Sidereal Time in seconds */ /* (convert longitude from degrees to seconds of time) */ gst = lsd + (longitude * 240.0); /* Time since 0:00 UT */ tsd = (gst - gst0) / 1.0027379093; /* Julian Date (UT) */ dj1 = dj0 + (tsd / 86400.0); /* Equation of the equinoxes converted to UT seconds */ eqnx = eqeqnx (dj1) / 1.002739093; /* Remove equation of equinoxes */ dj1 = dj1 - (eqnx / 86400.0); if (dj1 < dj0) dj1 = dj1 + 1.0; return (dj1); } /* MST2FD - calculate current UT given Greenwich Mean Sidereal Time * plus date in FITS ISO format (yyyy-mm-ddShh:mm:ss.ss) * Return UT date and time in FITS ISO format */ char * mst2fd (string) char *string; /* UT Date, MST as yyyy-mm-ddShh:mm:ss.ss */ { double sdj, dj; sdj = fd2jd (string); dj = mst2jd (sdj); return (jd2fd (dj)); } /* MST2JD - calculate current UT given Greenwich Mean Sidereal Time * plus date in Julian Date (0:00 UT + Mean Sidereal Time) * Return UT date and time as Julian Date */ double mst2jd (sdj) double sdj; /* UT Date, MST as Julian Date */ { double tsd, djd, st0, dj0, dj; dj0 = (double) ((int) sdj) + 0.5; /* Greenwich Mean Sidereal Time at 0:00 UT in seconds */ st0 = jd2mst (dj0); /* Mean Sidereal Time in seconds */ tsd = (sdj - dj0) * 86400.0; if (tsd < 0.0) tsd = tsd + 86400.0; /* Convert to fraction of a day since 0:00 UT */ djd = ((tsd - st0) / 1.0027379093) / 86400.0; /* Julian Date */ dj = dj0 + djd; if (dj < dj0) dj = dj + (1.0 / 1.0027379093); return (dj); } /* GST2FD - calculate current UT given Greenwich Sidereal Time * plus date in FITS ISO format (yyyy-mm-ddShh:mm:ss.ss) * Return UT date and time in FITS ISO format */ char * gst2fd (string) char *string; /* UT Date, GST as yyyy-mm-ddShh:mm:ss.ss */ { double sdj, dj; sdj = fd2jd (string); dj = gst2jd (sdj); return (jd2fd (dj)); } /* GST2JD - calculate current UT given Greenwich Sidereal Time * plus date as Julian Date (JD at 0:00 UT + sidereal time) * Return UT date and time as Julian Date */ double gst2jd (sdj) double sdj; /* UT Date, GST as Julian Date */ { double dj, tsd, djd, st0, dj0, eqnx; dj0 = (double) ((int) sdj) + 0.5; /* Greenwich Mean Sidereal Time at 0:00 UT in seconds */ st0 = jd2mst (dj0); /* Mean Sidereal Time in seconds */ tsd = (sdj - dj0) * 86400.0; if (tsd < 0.0) tsd = tsd + 86400.0; /* Convert to fraction of a day since 0:00 UT */ djd = ((tsd - st0) / 1.0027379093) / 86400.0; /* Julian Date */ dj = dj0 + djd; /* Equation of the equinoxes (converted to UT seconds) */ eqnx = eqeqnx (dj) / 1.002737909; dj = dj - eqnx / 86400.0; if (dj < dj0) dj = dj + 1.0; return (dj); } /* LST2DT - calculate current UT given Local Sidereal Time as hh.mmsss * plus date as yyyy.mmdd * Return UT time as hh.mmssss */ double lst2dt (date0, time0) double date0; /* UT date as yyyy.mmdd */ double time0; /* LST as hh.mmssss */ { double gst; /* Greenwich Sidereal Time in seconds since 0:00 */ double lst; /* Local Sidereal Time in seconds since 0:00 */ double date1; /* UT date as yyyy.mmdd */ double time1; /* UT as hh.mmssss */ double tsec0, gst0, tsd, tsec; /* Greenwich Sidereal Time at 0:00 UT */ tsec0 = dt2ts (date0, 0.0); gst0 = ts2gst (tsec0); /* Current Greenwich Sidereal Time in seconds */ /* (convert longitude from degrees to seconds of time) */ lst = dt2ts (0.0, time0); gst = lst + (longitude * 240.0); /* Time since 0:00 UT */ tsd = (gst - gst0) / 1.0027379093; /* UT date and time */ tsec = tsec0 + tsd; ts2dt (tsec, &date1, &time1); return (time1); } /* TS2GST - calculate Greenwich Sidereal Time given Universal Time * in seconds since 1951-01-01T0:00:00 * Return sidereal time of day in seconds */ double ts2gst (tsec) double tsec; /* time since 1950.0 in UT seconds */ { double gst; /* Greenwich Sidereal Time in seconds since 0:00 */ double tsd, eqnx, dj; int its; /* Elapsed time as of 0:00 UT */ if (tsec >= 0.0) { its = (int) (tsec + 0.5); tsd = (double) (its % 86400); } else { its = (int) (-tsec + 0.5); tsd = (double) (86400 - (its % 86400)); } /* Mean sidereal time */ gst = ts2mst (tsec); /* Equation of the equinoxes */ dj = ts2jd (tsec); eqnx = eqeqnx (dj); /* Apparent sidereal time at 0:00 ut */ gst = gst + eqnx; /* Current sidereal time */ gst = gst + (tsd * 1.0027379093); gst = dmod (gst,86400.0); return (gst); } /* FD2MST-- convert from FITS date Mean Sidereal Time */ char * fd2mst (string) char *string; /* FITS date string, which may be: fractional year dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ { double gsec, date, time, dj; dj = fd2jd (string); gsec = jd2mst (dj); ts2dt (gsec, &date, &time); date = 0.0; return (dt2fd (date, time)); } /* DT2MST-- convert from UT as yyyy.mmdd hh.mmssss to Mean Sidereal Time in the same format */ void dt2mst (date, time) double *date; /* Date as yyyy.mmdd */ double *time; /* Time as hh.mmssxxxx *if time<0, it is time as -(fraction of a day) */ { double date0, gsec, dj; date0 = *date; dj = dt2jd (*date, *time); gsec = jd2mst (dj); ts2dt (gsec, date, time); *date = date0; return; } /* TS2MST - calculate Greenwich Mean Sidereal Time given Universal Time * in seconds since 1951-01-01T0:00:00 */ double ts2mst (tsec) double tsec; /* time since 1950.0 in UT seconds */ { double dj; dj = ts2jd (tsec); return (jd2mst (dj)); } /* JD2MST - Julian Date to Greenwich Mean Sidereal Time using IAU 2000 * Return sideral time in seconds of time * (from USNO NOVAS package * http://aa.usno.navy.mil/software/novas/novas_info.html */ double jd2mst2 (dj) double dj; /* Julian Date */ { double dt, t, t2, t3, mst, st; dt = dj - 2451545.0; t = dt / 36525.0; t2 = t * t; t3 = t2 * t; /* Compute Greenwich Mean Sidereal Time in seconds */ st = (8640184.812866 * t) + (3155760000.0 * t) - (0.0000062 * t3) + (0.093104 * t2) + 67310.54841; mst = dmod (st, 86400.0); if (mst < 0.0) mst = mst + 86400.0; return (mst); } /* MJD2MST - Modified Julian Date to Greenwich Mean Sidereal Time using IAU 2000 * Return sideral time in seconds of time * (from USNO NOVAS package * http://aa.usno.navy.mil/software/novas/novas_info.html */ double mjd2mst (dj) double dj; /* Modified Julian Date */ { double dt, t, t2, t3, mst, st; dt = dj - 51544.5; t = dt / 36525.0; t2 = t * t; t3 = t2 * t; /* Compute Greenwich Mean Sidereal Time in seconds */ st = (8640184.812866 * t) + (3155760000.0 * t) - (0.0000062 * t3) + (0.093104 * t2) + 67310.54841; mst = dmod (st, 86400.0); if (mst < 0.0) mst = mst + 86400.0; return (mst); } /* JD2GST - Julian Date to Greenwich Sideral Time * Return sideral time in seconds of time * (Jean Meeus, Astronomical Algorithms, Willmann-Bell, 1991, pp 83-84) */ double jd2gst (dj) double dj; /* Julian Date */ { double dj0, gmt, gst, tsd, eqnx, ssd, l0; double ts2ss = 1.00273790935; int ijd; /* Julian date at 0:00 UT */ ijd = (int) dj; dj0 = (double) ijd + 0.5; if (dj0 > dj) dj0 = dj0 - 1.0; /* Greenwich mean sidereal time at 0:00 UT in seconds */ l0 = longitude; longitude = 0.0; gmt = jd2mst (dj0); longitude = l0; /* Equation of the equinoxes */ eqnx = eqeqnx (dj); /* Apparent sidereal time at 0:00 ut */ gst = gmt + eqnx; /* UT seconds since 0:00 */ tsd = (dj - dj0) * 86400.0; ssd = tsd * ts2ss; /* Current sidereal time */ gst = gst + ssd; gst = dmod (gst, 86400.0); return (gst); } /* EQEQNX - Compute equation of the equinoxes for apparent sidereal time */ double eqeqnx (dj) double dj; /* Julian Date */ { double dt, edj, dpsi, deps, obl, eqnx; double rad2tsec = 13750.98708; /* Convert UT to Ephemeris Time (TDB or TT)*/ dt = utdt (dj); edj = dj + dt / 86400.0; /* Nutation and obliquity */ compnut (edj, &dpsi, &deps, &obl); /* Correct obliquity for nutation */ obl = obl + deps; /* Equation of the equinoxes in seconds */ eqnx = (dpsi * cos (obl)) * rad2tsec; return (eqnx); } /* JD2MST - Julian Date to Mean Sideral Time * Return sideral time in seconds of time * (Jean Meeus, Astronomical Algorithms, Willmann-Bell, 1991, pp 83-84) */ double jd2mst (dj) double dj; /* Julian Date */ { double dt, t, mst; dt = dj - 2451545.0; t = dt / 36525.0; /* Compute Greenwich mean sidereal time in degrees (Meeus, page 84) */ mst = 280.46061837 + (360.98564736629 * dt) + (0.000387933 * t * t) - (t * t * t / 38710000.0); /* Keep degrees between 0 and 360 */ while (mst > 360.0) mst = mst - 360.0; while (mst < 0.0) mst = mst + 360.0; /* Convert to time in seconds (3600 / 15) */ mst = mst * 240.0; /* Subtract longitude (degrees to seconds of time) */ mst = mst - (240.0 * longitude); if (mst < 0.0) mst = mst + 86400.0; else if (mst > 86400.0) mst = mst - 86400.0; return (mst); } /* COMPNUT - Compute nutation using the IAU 2000b model */ /* Translated from Pat Wallace's Fortran subroutine iau_nut00b (June 26 2007) into C by Jessica Mink on September 5, 2008 */ #define NLS 77 /* number of terms in the luni-solar nutation model */ void compnut (dj, dpsi, deps, eps0) double dj; /* Julian Date */ double *dpsi; /* Nutation in longitude in radians (returned) */ double *deps; /* Nutation in obliquity in radians (returned) */ double *eps0; /* Mean obliquity in radians (returned) */ /* This routine is translated from the International Astronomical Union's * Fortran SOFA (Standards Of Fundamental Astronomy) software collection. * * notes: * * 1) the nutation components in longitude and obliquity are in radians * and with respect to the equinox and ecliptic of date. the * obliquity at j2000 is assumed to be the lieske et al. (1977) value * of 84381.448 arcsec. (the errors that result from using this * routine with the iau 2006 value of 84381.406 arcsec can be * neglected.) * * the nutation model consists only of luni-solar terms, but includes * also a fixed offset which compensates for certain long-period * planetary terms (note 7). * * 2) this routine is an implementation of the iau 2000b abridged * nutation model formally adopted by the iau general assembly in * 2000. the routine computes the mhb_2000_short luni-solar nutation * series (luzum 2001), but without the associated corrections for * the precession rate adjustments and the offset between the gcrs * and j2000 mean poles. * * 3) the full IAU 2000a (mhb2000) nutation model contains nearly 1400 * terms. the IAU 2000b model (mccarthy & luzum 2003) contains only * 77 terms, plus additional simplifications, yet still delivers * results of 1 mas accuracy at present epochs. this combination of * accuracy and size makes the IAU 2000b abridged nutation model * suitable for most practical applications. * * the routine delivers a pole accurate to 1 mas from 1900 to 2100 * (usually better than 1 mas, very occasionally just outside 1 mas). * the full IAU 2000a model, which is implemented in the routine * iau_nut00a (q.v.), delivers considerably greater accuracy at * current epochs; however, to realize this improved accuracy, * corrections for the essentially unpredictable free-core-nutation * (fcn) must also be included. * * 4) the present routine provides classical nutation. the * mhb_2000_short algorithm, from which it is adapted, deals also * with (i) the offsets between the gcrs and mean poles and (ii) the * adjustments in longitude and obliquity due to the changed * precession rates. these additional functions, namely frame bias * and precession adjustments, are supported by the sofa routines * iau_bi00 and iau_pr00. * * 6) the mhb_2000_short algorithm also provides "total" nutations, * comprising the arithmetic sum of the frame bias, precession * adjustments, and nutation (luni-solar + planetary). these total * nutations can be used in combination with an existing IAU 1976 * precession implementation, such as iau_pmat76, to deliver gcrs-to- * true predictions of mas accuracy at current epochs. however, for * symmetry with the iau_nut00a routine (q.v. for the reasons), the * sofa routines do not generate the "total nutations" directly. * should they be required, they could of course easily be generated * by calling iau_bi00, iau_pr00 and the present routine and adding * the results. * * 7) the IAU 2000b model includes "planetary bias" terms that are fixed * in size but compensate for long-period nutations. the amplitudes * quoted in mccarthy & luzum (2003), namely dpsi = -1.5835 mas and * depsilon = +1.6339 mas, are optimized for the "total nutations" * method described in note 6. the luzum (2001) values used in this * sofa implementation, namely -0.135 mas and +0.388 mas, are * optimized for the "rigorous" method, where frame bias, precession * and nutation are applied separately and in that order. during the * interval 1995-2050, the sofa implementation delivers a maximum * error of 1.001 mas (not including fcn). * * References from original Fortran subroutines: * * Hilton, J. et al., 2006, Celest.Mech.Dyn.Astron. 94, 351 * * Lieske, J.H., Lederle, T., Fricke, W., Morando, B., "Expressions * for the precession quantities based upon the IAU 1976 system of * astronomical constants", Astron.Astrophys. 58, 1-2, 1-16. (1977) * * Luzum, B., private communication, 2001 (Fortran code * mhb_2000_short) * * McCarthy, D.D. & Luzum, B.J., "An abridged model of the * precession-nutation of the celestial pole", Cel.Mech.Dyn.Astron. * 85, 37-49 (2003) * * Simon, J.-L., Bretagnon, P., Chapront, J., Chapront-Touze, M., * Francou, G., Laskar, J., Astron.Astrophys. 282, 663-683 (1994) * */ { double as2r = 0.000004848136811095359935899141; /* arcseconds to radians */ double dmas2r = as2r / 1000.0; /* milliarcseconds to radians */ double as2pi = 1296000.0; /* arc seconds in a full circle */ double d2pi = 6.283185307179586476925287; /* 2pi */ double u2r = as2r / 10000000.0; /* units of 0.1 microarcsecond to radians */ double dj0 = 2451545.0; /* reference epoch (j2000), jd */ double djc = 36525.0; /* Days per julian century */ /* Miscellaneous */ double t, el, elp, f, d, om, arg, dp, de, sarg, carg; double dpsils, depsls, dpsipl, depspl; int i, j; int nls = NLS; /* number of terms in the luni-solar nutation model */ /* Fixed offset in lieu of planetary terms (radians) */ double dpplan = - 0.135 * dmas2r; double deplan = + 0.388 * dmas2r; /* Tables of argument and term coefficients */ /* Coefficients for fundamental arguments */ /* Luni-solar argument multipliers: */ /* l l' f d om */ static int nals[5*NLS]= {0, 0, 0, 0, 1, 0, 0, 2, -2, 2, 0, 0, 2, 0, 2, 0, 0, 0, 0, 2, 0, 1, 0, 0, 0, 0, 1, 2, -2, 2, 1, 0, 0, 0, 0, 0, 0, 2, 0, 1, 1, 0, 2, 0, 2, 0, -1, 2, -2, 2, 0, 0, 2, -2, 1, -1, 0, 2, 0, 2, -1, 0, 0, 2, 0, 1, 0, 0, 0, 1, -1, 0, 0, 0, 1, -1, 0, 2, 2, 2, 1, 0, 2, 0, 1, -2, 0, 2, 0, 1, 0, 0, 0, 2, 0, 0, 0, 2, 2, 2, 0, -2, 2, -2, 2, -2, 0, 0, 2, 0, 2, 0, 2, 0, 2, 1, 0, 2, -2, 2, -1, 0, 2, 0, 1, 2, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 1, -1, 0, 0, 2, 1, 0, 2, 2, -2, 2, 0, 0, -2, 2, 0, 1, 0, 0, -2, 1, 0, -1, 0, 0, 1, -1, 0, 2, 2, 1, 0, 2, 0, 0, 0, 1, 0, 2, 2, 2, -2, 0, 2, 0, 0, 0, 1, 2, 0, 2, 0, 0, 2, 2, 1, 0, -1, 2, 0, 2, 0, 0, 0, 2, 1, 1, 0, 2, -2, 1, 2, 0, 2, -2, 2, -2, 0, 0, 2, 1, 2, 0, 2, 0, 1, 0, -1, 2, -2, 1, 0, 0, 0, -2, 1, -1, -1, 0, 2, 0, 2, 0, 0, -2, 1, 1, 0, 0, 2, 0, 0, 1, 2, -2, 1, 1, -1, 0, 0, 0, -2, 0, 2, 0, 2, 3, 0, 2, 0, 2, 0, -1, 0, 2, 0, 1, -1, 2, 0, 2, 0, 0, 0, 1, 0, -1, -1, 2, 2, 2, -1, 0, 2, 0, 0, 0, -1, 2, 2, 2, -2, 0, 0, 0, 1, 1, 1, 2, 0, 2, 2, 0, 0, 0, 1, -1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 2, 0, 0, -1, 0, 2, -2, 1, 1, 0, 0, 0, 2, -1, 0, 0, 1, 0, 0, 0, 2, 1, 2, -1, 0, 2, 4, 2, -1, 1, 0, 1, 1, 0, -2, 2, -2, 1, 1, 0, 2, 2, 1, -2, 0, 2, 2, 2, -1, 0, 0, 0, 2, 1, 1, 2, -2, 2}; /* Luni-solar nutation coefficients, in 1e-7 arcsec */ /* longitude (sin, t*sin, cos), obliquity (cos, t*cos, sin) */ static double cls[6*NLS]= {-172064161.0, -174666.0, 33386.0, 92052331.0, 9086.0, 15377.0, -13170906.0, -1675.0, -13696.0, 5730336.0, -3015.0, -4587.0, -2276413.0, -234.0, 2796.0, 978459.0, -485.0, 1374.0, 2074554.0, 207.0, -698.0, -897492.0, 470.0, -291.0, 1475877.0, -3633.0, 11817.0, 73871.0, -184.0, -1924.0, -516821.0, 1226.0, -524.0, 224386.0, -677.0, -174.0, 711159.0, 73.0, -872.0, -6750.0, 0.0, 358.0, -387298.0, -367.0, 380.0, 200728.0, 18.0, 318.0, -301461.0, -36.0, 816.0, 129025.0, -63.0, 367.0, 215829.0, -494.0, 111.0, -95929.0, 299.0, 132.0, 128227.0, 137.0, 181.0, -68982.0, -9.0, 39.0, 123457.0, 11.0, 19.0, -53311.0, 32.0, -4.0, 156994.0, 10.0, -168.0, -1235.0, 0.0, 82.0, 63110.0, 63.0, 27.0, -33228.0, 0.0, -9.0, -57976.0, -63.0, -189.0, 31429.0, 0.0, -75.0, -59641.0, -11.0, 149.0, 25543.0, -11.0, 66.0, -51613.0, -42.0, 129.0, 26366.0, 0.0, 78.0, 45893.0, 50.0, 31.0, -24236.0, -10.0, 20.0, 63384.0, 11.0, -150.0, -1220.0, 0.0, 29.0, -38571.0, -1.0, 158.0, 16452.0, -11.0, 68.0, 32481.0, 0.0, 0.0, -13870.0, 0.0, 0.0, -47722.0, 0.0, -18.0, 477.0, 0.0, -25.0, -31046.0, -1.0, 131.0, 13238.0, -11.0, 59.0, 28593.0, 0.0, -1.0, -12338.0, 10.0, -3.0, 20441.0, 21.0, 10.0, -10758.0, 0.0, -3.0, 29243.0, 0.0, -74.0, -609.0, 0.0, 13.0, 25887.0, 0.0, -66.0, -550.0, 0.0, 11.0, -14053.0, -25.0, 79.0, 8551.0, -2.0, -45.0, 15164.0, 10.0, 11.0, -8001.0, 0.0, -1.0, -15794.0, 72.0, -16.0, 6850.0, -42.0, -5.0, 21783.0, 0.0, 13.0, -167.0, 0.0, 13.0, -12873.0, -10.0, -37.0, 6953.0, 0.0, -14.0, -12654.0, 11.0, 63.0, 6415.0, 0.0, 26.0, -10204.0, 0.0, 25.0, 5222.0, 0.0, 15.0, 16707.0, -85.0, -10.0, 168.0, -1.0, 10.0, -7691.0, 0.0, 44.0, 3268.0, 0.0, 19.0, -11024.0, 0.0, -14.0, 104.0, 0.0, 2.0, 7566.0, -21.0, -11.0, -3250.0, 0.0, -5.0, -6637.0, -11.0, 25.0, 3353.0, 0.0, 14.0, -7141.0, 21.0, 8.0, 3070.0, 0.0, 4.0, -6302.0, -11.0, 2.0, 3272.0, 0.0, 4.0, 5800.0, 10.0, 2.0, -3045.0, 0.0, -1.0, 6443.0, 0.0, -7.0, -2768.0, 0.0, -4.0, -5774.0, -11.0, -15.0, 3041.0, 0.0, -5.0, -5350.0, 0.0, 21.0, 2695.0, 0.0, 12.0, -4752.0, -11.0, -3.0, 2719.0, 0.0, -3.0, -4940.0, -11.0, -21.0, 2720.0, 0.0, -9.0, 7350.0, 0.0, -8.0, -51.0, 0.0, 4.0, 4065.0, 0.0, 6.0, -2206.0, 0.0, 1.0, 6579.0, 0.0, -24.0, -199.0, 0.0, 2.0, 3579.0, 0.0, 5.0, -1900.0, 0.0, 1.0, 4725.0, 0.0, -6.0, -41.0, 0.0, 3.0, -3075.0, 0.0, -2.0, 1313.0, 0.0, -1.0, -2904.0, 0.0, 15.0, 1233.0, 0.0, 7.0, 4348.0, 0.0, -10.0, -81.0, 0.0, 2.0, -2878.0, 0.0, 8.0, 1232.0, 0.0, 4.0, -4230.0, 0.0, 5.0, -20.0, 0.0, -2.0, -2819.0, 0.0, 7.0, 1207.0, 0.0, 3.0, -4056.0, 0.0, 5.0, 40.0, 0.0, -2.0, -2647.0, 0.0, 11.0, 1129.0, 0.0, 5.0, -2294.0, 0.0, -10.0, 1266.0, 0.0, -4.0, 2481.0, 0.0, -7.0, -1062.0, 0.0, -3.0, 2179.0, 0.0, -2.0, -1129.0, 0.0, -2.0, 3276.0, 0.0, 1.0, -9.0, 0.0, 0.0, -3389.0, 0.0, 5.0, 35.0, 0.0, -2.0, 3339.0, 0.0, -13.0, -107.0, 0.0, 1.0, -1987.0, 0.0, -6.0, 1073.0, 0.0, -2.0, -1981.0, 0.0, 0.0, 854.0, 0.0, 0.0, 4026.0, 0.0, -353.0, -553.0, 0.0, -139.0, 1660.0, 0.0, -5.0, -710.0, 0.0, -2.0, -1521.0, 0.0, 9.0, 647.0, 0.0, 4.0, 1314.0, 0.0, 0.0, -700.0, 0.0, 0.0, -1283.0, 0.0, 0.0, 672.0, 0.0, 0.0, -1331.0, 0.0, 8.0, 663.0, 0.0, 4.0, 1383.0, 0.0, -2.0, -594.0, 0.0, -2.0, 1405.0, 0.0, 4.0, -610.0, 0.0, 2.0, 1290.0, 0.0, 0.0, -556.0, 0.0, 0.0}; /* Interval between fundamental epoch J2000.0 and given date (JC) */ t = (dj - dj0) / djc; /* Luni-solar nutation */ /* Fundamental (delaunay) arguments from Simon et al. (1994) */ /* Mean anomaly of the moon */ el = fmod (485868.249036 + (1717915923.2178 * t), as2pi) * as2r; /* Mean anomaly of the sun */ elp = fmod (1287104.79305 + (129596581.0481 * t), as2pi) * as2r; /* Mean argument of the latitude of the moon */ f = fmod (335779.526232 + (1739527262.8478 * t), as2pi) * as2r; /* Mean elongation of the moon from the sun */ d = fmod (1072260.70369 + (1602961601.2090 * t), as2pi ) * as2r; /* Mean longitude of the ascending node of the moon */ om = fmod (450160.398036 - (6962890.5431 * t), as2pi ) * as2r; /* Initialize the nutation values */ dp = 0.0; de = 0.0; /* Summation of luni-solar nutation series (in reverse order) */ for (i = nls; i > 0; i=i-1) { j = i - 1; /* Argument and functions */ arg = fmod ( (double) (nals[5*j]) * el + (double) (nals[1+5*j]) * elp + (double) (nals[2+5*j]) * f + (double) (nals[3+5*j]) * d + (double) (nals[4+5*j]) * om, d2pi); sarg = sin (arg); carg = cos (arg); /* Terms */ dp = dp + (cls[6*j] + cls[1+6*j] * t) * sarg + cls[2+6*j] * carg; de = de + (cls[3+6*j] + cls[4+6*j] * t) * carg + cls[5+6*j] * sarg; } /* Convert from 0.1 microarcsec units to radians */ dpsils = dp * u2r; depsls = de * u2r; /* In lieu of planetary nutation */ /* Fixed offset to correct for missing terms in truncated series */ dpsipl = dpplan; depspl = deplan; /* Results */ /* Add luni-solar and planetary components */ *dpsi = dpsils + dpsipl; *deps = depsls + depspl; /* Mean Obliquity in radians (IAU 2006, Hilton, et al.) */ *eps0 = ( 84381.406 + ( -46.836769 + ( -0.0001831 + ( 0.00200340 + ( -0.000000576 + ( -0.0000000434 ) * t ) * t ) * t ) * t ) * t ) * as2r; } /* ISDATE - Return 1 if string is an old or ISO FITS standard date */ int isdate (string) char *string; /* Possible FITS date string, which may be: dd/mm/yy (FITS standard before 2000) dd-mm-yy (nonstandard FITS use before 2000) yyyy-mm-dd (FITS standard after 1999) yyyy-mm-ddThh:mm:ss.ss (FITS standard after 1999) */ { int iyr = 0; /* year (returned) */ int imon = 0; /* month (returned) */ int iday = 0; /* day (returned) */ int i; char *sstr, *dstr, *tstr, *nval; /* Translate string from ASCII to binary */ if (string == NULL) return (0); sstr = strchr (string,'/'); dstr = strchr (string,'-'); if (dstr == string) dstr = strchr (string+1,'-'); tstr = strchr (string,'T'); /* Original FITS date format: dd/mm/yy */ if (sstr > string) { *sstr = '\0'; iday = (int) atof (string); *sstr = '/'; nval = sstr + 1; sstr = strchr (nval,'/'); if (sstr == NULL) sstr = strchr (nval,'-'); if (sstr > string) { *sstr = '\0'; imon = (int) atof (nval); *sstr = '/'; nval = sstr + 1; iyr = (int) atof (nval); if (iyr < 1000) iyr = iyr + 1900; } if (imon > 0 && iday > 0) return (1); else return (0); } /* New FITS date format: yyyy-mm-ddThh:mm:ss[.sss] */ else if (dstr > string) { *dstr = '\0'; iyr = (int) atof (string); nval = dstr + 1; *dstr = '-'; dstr = strchr (nval,'-'); imon = 0; iday = 0; /* Decode year, month, and day */ if (dstr > string) { *dstr = '\0'; imon = (int) atof (nval); *dstr = '-'; nval = dstr + 1; if (tstr > string) *tstr = '\0'; iday = (int) atof (nval); if (tstr > string) *tstr = 'T'; } /* If day is > 31, it is really year in old format */ if (iday > 31) { i = iyr; if (iday < 100) iyr = iday + 1900; else iyr = iday; iday = i; } if (imon > 0 && iday > 0) return (1); else return (0); } /* If FITS date is entered as an epoch, return 0 anyway */ else return (0); } /* Round seconds and make sure date and time numbers are within limits */ static void fixdate (iyr, imon, iday, ihr, imn, sec, ndsec) int *iyr; /* year (returned) */ int *imon; /* month (returned) */ int *iday; /* day (returned) */ int *ihr; /* hours (returned) */ int *imn; /* minutes (returned) */ double *sec; /* seconds (returned) */ int ndsec; /* Number of decimal places in seconds (0=int) */ { double days; /* Round seconds to 0 - 4 decimal places (no rounding if <0, >4) */ if (ndsec == 0) *sec = dint (*sec + 0.5); else if (ndsec < 2) *sec = dint (*sec * 10.0 + 0.5) / 10.0; else if (ndsec < 3) *sec = dint (*sec * 100.0 + 0.5) / 100.0; else if (ndsec < 4) *sec = dint (*sec * 1000.0 + 0.5) / 1000.0; else if (ndsec < 5) *sec = dint (*sec * 10000.0 + 0.5) / 10000.0; /* Adjust minutes and hours */ if (*sec > 60.0) { *sec = *sec - 60.0; *imn = *imn + 1; } if (*imn > 60) { *imn = *imn - 60; *ihr = *ihr + 1; } /* Return if no date */ if (*iyr == 0 && *imon == 0 && *iday == 0) return; /* Adjust date */ if (*ihr > 23) { *ihr = *ihr - 24; *iday = *iday + 1; } days = caldays (*iyr, *imon); if (*iday > days) { *iday = *iday - days; *imon = *imon + 1; } if (*iday < 1) { *imon = *imon - 1; if (*imon < 1) { *imon = *imon + 12; *iyr = *iyr - 1; } days = caldays (*iyr, *imon); *iday = *iday + days; } if (*imon < 1) { *imon = *imon + 12; *iyr = *iyr - 1; days = caldays (*iyr, *imon); if (*iday > days) { *iday = *iday - days; *imon = *imon + 1; } } if (*imon > 12) { *imon = *imon - 12; *iyr = *iyr + 1; } return; } /* Calculate days in month 1-12 given year (Gregorian calendar only) */ static int caldays (year, month) int year; /* 4-digit year */ int month; /* Month (1=January, 2=February, etc.) */ { if (month < 1) { month = month + 12; year = year + 1; } if (month > 12) { month = month - 12; year = year + 1; } switch (month) { case 1: return (31); case 2: if (year%400 == 0) return (29); else if (year%100 == 0) return (28); else if (year%4 == 0) return (29); else return (28); case 3: return (31); case 4: return (30); case 5: return (31); case 6: return (30); case 7: return (31); case 8: return (31); case 9: return (30); case 10: return (31); case 11: return (30); case 12: return (31); default: return (0); } } static double dint (dnum) double dnum; { double dn; if (dnum < 0.0) dn = -floor (-dnum); else dn = floor (dnum); return (dn); } static double dmod (dnum, dm) double dnum, dm; { double dnumx, dnumi, dnumf; if (dnum < 0.0) dnumx = -dnum; else dnumx = dnum; dnumi = dint (dnumx / dm); if (dnum < 0.0) dnumf = dnum + (dnumi * dm); else if (dnum > 0.0) dnumf = dnum - (dnumi * dm); else dnumf = 0.0; return (dnumf); } /* Jul 1 1999 New file, based on iolib/jcon.f and iolib/vcon.f and hgetdate() * Oct 21 1999 Fix declarations after lint * Oct 27 1999 Fix bug to return epoch if fractional year input * Dec 9 1999 Fix bug in ts2jd() found by Pete Ratzlaff (SAO) * Dec 17 1999 Add all unimplemented conversions * Dec 20 1999 Add isdate(); leave date, time strings unchanged in fd2i() * Dec 20 1999 Make all fd2*() subroutines deal with time alone * * Jan 3 2000 In old FITS format, year 100 is assumed to be 2000 * Jan 11 2000 Fix epoch to date conversion so .0 is 0:00, not 12:00 * Jan 21 2000 Add separate Besselian and Julian epoch computations * Jan 28 2000 Add Modified Julian Date conversions * Mar 2 2000 Implement decimal places for FITS date string * Mar 14 2000 Fix bug in dealing with 2000-02-29 in ts2i() * Mar 22 2000 Add lt2* and ut2* to get current time as local and UT * Mar 24 2000 Fix calloc() calls * Mar 24 2000 Add tsi2* and tsu2* to convert IRAF and Unix seconds * May 1 2000 In old FITS format, all years < 1000 get 1900 added to them * Aug 1 2000 Make ep2jd and jd2ep consistently starting at 1/1 0:00 * * Jan 11 2001 Print all messages to stderr * May 21 2001 Add day of year conversions * May 25 2001 Allow fraction of day in FITS date instead of time * * Apr 8 2002 Change all long declaration to time_t * May 13 2002 Fix bugs found by lint * Jul 5 2002 Fix bug in fixdate() so fractional seconds come out * Jul 8 2002 Fix rounding bug in t2i() * Jul 8 2002 Try Fliegel and Van Flandern's algorithm for JD to UT date * Jul 8 2002 If first character of string is -, check for other -'s in isdate * Sep 10 2002 Add ET/TDT/TT conversion from UT subroutines * Sep 10 2002 Add sidereal time conversions * * Jan 30 2003 Fix typo in ts2gst() * Mar 7 2003 Add conversions for heliocentric julian dates * May 20 2003 Declare nd in setdatedec() * Jul 18 2003 Add code to parse Las Campanas dates * * Mar 24 2004 If ndec > 0, add UT to FITS date even if it is 0:00:00 * * Oct 14 2005 Add tsd2fd() and tsd2dt() * * May 3 2006 Drop declaration of unused variables * Jun 20 2006 Initialized uninitialized variables * Aug 2 2006 Add local sidereal time * Sep 13 2006 Add more local sidereal time subroutines * Oct 2 2006 Add UT to old FITS date conversions * Oct 6 2006 Add eqeqnx() to compute equation of the equinoxes * * Jan 8 2007 Remove unused variables * * Sep 5 2008 Replace nutation with IAU 2006 model translated from SOFA * Sep 9 2008 Add ang2hr(), ang2deg(), hr2ang(), deg2ang() * Sep 10 2008 Add longitude to mean standard time (default = Greenwich) * Oct 8 2008 Clean up sidereal time computations * * Sep 24 2009 Add end to comment "Coefficients for fundamental arguments" * * Jan 11 2012 Add TAI, TT, GPS time * Oct 19 2012 Unused l0 dropped from jd2lst(); ts2ss from jd2mst() */ astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/wcscon_wrap.c0000664000175000017500000034645613047255533022174 0ustar mattymatty00000000000000/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.12 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make * changes to this file unless you know what you are doing--modify the SWIG * interface file instead. * ----------------------------------------------------------------------------- */ #define SWIGPYTHON #define SWIG_PYTHON_DIRECTOR_NO_VTABLE /* ----------------------------------------------------------------------------- * This section contains generic SWIG labels for method/variable * declarations/attributes, and other compiler dependent labels. * ----------------------------------------------------------------------------- */ /* template workaround for compilers that cannot correctly implement the C++ standard */ #ifndef SWIGTEMPLATEDISAMBIGUATOR # if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560) # define SWIGTEMPLATEDISAMBIGUATOR template # elif defined(__HP_aCC) /* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */ /* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */ # define SWIGTEMPLATEDISAMBIGUATOR template # else # define SWIGTEMPLATEDISAMBIGUATOR # endif #endif /* inline attribute */ #ifndef SWIGINLINE # if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) # define SWIGINLINE inline # else # define SWIGINLINE # endif #endif /* attribute recognised by some compilers to avoid 'unused' warnings */ #ifndef SWIGUNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif # elif defined(__ICC) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif #endif #ifndef SWIG_MSC_UNSUPPRESS_4505 # if defined(_MSC_VER) # pragma warning(disable : 4505) /* unreferenced local function has been removed */ # endif #endif #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) # else # define SWIGUNUSEDPARM(p) p SWIGUNUSED # endif #endif /* internal SWIG method */ #ifndef SWIGINTERN # define SWIGINTERN static SWIGUNUSED #endif /* internal inline SWIG method */ #ifndef SWIGINTERNINLINE # define SWIGINTERNINLINE SWIGINTERN SWIGINLINE #endif /* exporting methods */ #if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) # ifndef GCC_HASCLASSVISIBILITY # define GCC_HASCLASSVISIBILITY # endif #endif #ifndef SWIGEXPORT # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # if defined(STATIC_LINKED) # define SWIGEXPORT # else # define SWIGEXPORT __declspec(dllexport) # endif # else # if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) # define SWIGEXPORT __attribute__ ((visibility("default"))) # else # define SWIGEXPORT # endif # endif #endif /* calling conventions for Windows */ #ifndef SWIGSTDCALL # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # define SWIGSTDCALL __stdcall # else # define SWIGSTDCALL # endif #endif /* Deal with Microsoft's attempt at deprecating C standard runtime functions */ #if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) # define _CRT_SECURE_NO_DEPRECATE #endif /* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */ #if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE) # define _SCL_SECURE_NO_DEPRECATE #endif #if defined(_DEBUG) && defined(SWIG_PYTHON_INTERPRETER_NO_DEBUG) /* Use debug wrappers with the Python release dll */ # undef _DEBUG # include # define _DEBUG #else # include #endif /* ----------------------------------------------------------------------------- * swigrun.swg * * This file contains generic C API SWIG runtime support for pointer * type checking. * ----------------------------------------------------------------------------- */ /* This should only be incremented when either the layout of swig_type_info changes, or for whatever reason, the runtime changes incompatibly */ #define SWIG_RUNTIME_VERSION "4" /* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ #ifdef SWIG_TYPE_TABLE # define SWIG_QUOTE_STRING(x) #x # define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x) # define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE) #else # define SWIG_TYPE_TABLE_NAME #endif /* You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for creating a static or dynamic library from the SWIG runtime code. In 99.9% of the cases, SWIG just needs to declare them as 'static'. But only do this if strictly necessary, ie, if you have problems with your compiler or suchlike. */ #ifndef SWIGRUNTIME # define SWIGRUNTIME SWIGINTERN #endif #ifndef SWIGRUNTIMEINLINE # define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE #endif /* Generic buffer size */ #ifndef SWIG_BUFFER_SIZE # define SWIG_BUFFER_SIZE 1024 #endif /* Flags for pointer conversions */ #define SWIG_POINTER_DISOWN 0x1 #define SWIG_CAST_NEW_MEMORY 0x2 /* Flags for new pointer objects */ #define SWIG_POINTER_OWN 0x1 /* Flags/methods for returning states. The SWIG conversion methods, as ConvertPtr, return an integer that tells if the conversion was successful or not. And if not, an error code can be returned (see swigerrors.swg for the codes). Use the following macros/flags to set or process the returning states. In old versions of SWIG, code such as the following was usually written: if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { // success code } else { //fail code } Now you can be more explicit: int res = SWIG_ConvertPtr(obj,vptr,ty.flags); if (SWIG_IsOK(res)) { // success code } else { // fail code } which is the same really, but now you can also do Type *ptr; int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags); if (SWIG_IsOK(res)) { // success code if (SWIG_IsNewObj(res) { ... delete *ptr; } else { ... } } else { // fail code } I.e., now SWIG_ConvertPtr can return new objects and you can identify the case and take care of the deallocation. Of course that also requires SWIG_ConvertPtr to return new result values, such as int SWIG_ConvertPtr(obj, ptr,...) { if () { if () { *ptr = ; return SWIG_NEWOBJ; } else { *ptr = ; return SWIG_OLDOBJ; } } else { return SWIG_BADOBJ; } } Of course, returning the plain '0(success)/-1(fail)' still works, but you can be more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the SWIG errors code. Finally, if the SWIG_CASTRANK_MODE is enabled, the result code allows to return the 'cast rank', for example, if you have this int food(double) int fooi(int); and you call food(1) // cast rank '1' (1 -> 1.0) fooi(1) // cast rank '0' just use the SWIG_AddCast()/SWIG_CheckState() */ #define SWIG_OK (0) #define SWIG_ERROR (-1) #define SWIG_IsOK(r) (r >= 0) #define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) /* The CastRankLimit says how many bits are used for the cast rank */ #define SWIG_CASTRANKLIMIT (1 << 8) /* The NewMask denotes the object was created (using new/malloc) */ #define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1) /* The TmpMask is for in/out typemaps that use temporal objects */ #define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1) /* Simple returning values */ #define SWIG_BADOBJ (SWIG_ERROR) #define SWIG_OLDOBJ (SWIG_OK) #define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK) #define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK) /* Check, add and del mask methods */ #define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r) #define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r) #define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK)) #define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r) #define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r) #define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK)) /* Cast-Rank Mode */ #if defined(SWIG_CASTRANK_MODE) # ifndef SWIG_TypeRank # define SWIG_TypeRank unsigned long # endif # ifndef SWIG_MAXCASTRANK /* Default cast allowed */ # define SWIG_MAXCASTRANK (2) # endif # define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) # define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) SWIGINTERNINLINE int SWIG_AddCast(int r) { return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; } SWIGINTERNINLINE int SWIG_CheckState(int r) { return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; } #else /* no cast-rank mode */ # define SWIG_AddCast(r) (r) # define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) #endif #include #ifdef __cplusplus extern "C" { #endif typedef void *(*swig_converter_func)(void *, int *); typedef struct swig_type_info *(*swig_dycast_func)(void **); /* Structure to store information on one type */ typedef struct swig_type_info { const char *name; /* mangled name of this type */ const char *str; /* human readable name of this type */ swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ struct swig_cast_info *cast; /* linked list of types that can cast into this type */ void *clientdata; /* language specific type data */ int owndata; /* flag if the structure owns the clientdata */ } swig_type_info; /* Structure to store a type and conversion function used for casting */ typedef struct swig_cast_info { swig_type_info *type; /* pointer to type that is equivalent to this type */ swig_converter_func converter; /* function to cast the void pointers */ struct swig_cast_info *next; /* pointer to next cast in linked list */ struct swig_cast_info *prev; /* pointer to the previous cast */ } swig_cast_info; /* Structure used to store module information * Each module generates one structure like this, and the runtime collects * all of these structures and stores them in a circularly linked list.*/ typedef struct swig_module_info { swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ size_t size; /* Number of types in this module */ struct swig_module_info *next; /* Pointer to next element in circularly linked list */ swig_type_info **type_initial; /* Array of initially generated type structures */ swig_cast_info **cast_initial; /* Array of initially generated casting structures */ void *clientdata; /* Language specific module data */ } swig_module_info; /* Compare two type names skipping the space characters, therefore "char*" == "char *" and "Class" == "Class", etc. Return 0 when the two name types are equivalent, as in strncmp, but skipping ' '. */ SWIGRUNTIME int SWIG_TypeNameComp(const char *f1, const char *l1, const char *f2, const char *l2) { for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { while ((*f1 == ' ') && (f1 != l1)) ++f1; while ((*f2 == ' ') && (f2 != l2)) ++f2; if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; } return (int)((l1 - f1) - (l2 - f2)); } /* Check type equivalence in a name list like ||... Return 0 if equal, -1 if nb < tb, 1 if nb > tb */ SWIGRUNTIME int SWIG_TypeCmp(const char *nb, const char *tb) { int equiv = 1; const char* te = tb + strlen(tb); const char* ne = nb; while (equiv != 0 && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = SWIG_TypeNameComp(nb, ne, tb, te); if (*ne) ++ne; } return equiv; } /* Check type equivalence in a name list like ||... Return 0 if not equal, 1 if equal */ SWIGRUNTIME int SWIG_TypeEquiv(const char *nb, const char *tb) { return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0; } /* Check the typename */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheck(const char *c, swig_type_info *ty) { if (ty) { swig_cast_info *iter = ty->cast; while (iter) { if (strcmp(iter->type->name, c) == 0) { if (iter == ty->cast) return iter; /* Move iter to the top of the linked list */ iter->prev->next = iter->next; if (iter->next) iter->next->prev = iter->prev; iter->next = ty->cast; iter->prev = 0; if (ty->cast) ty->cast->prev = iter; ty->cast = iter; return iter; } iter = iter->next; } } return 0; } /* Identical to SWIG_TypeCheck, except strcmp is replaced with a pointer comparison */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *ty) { if (ty) { swig_cast_info *iter = ty->cast; while (iter) { if (iter->type == from) { if (iter == ty->cast) return iter; /* Move iter to the top of the linked list */ iter->prev->next = iter->next; if (iter->next) iter->next->prev = iter->prev; iter->next = ty->cast; iter->prev = 0; if (ty->cast) ty->cast->prev = iter; ty->cast = iter; return iter; } iter = iter->next; } } return 0; } /* Cast a pointer up an inheritance hierarchy */ SWIGRUNTIMEINLINE void * SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); } /* Dynamic pointer casting. Down an inheritance hierarchy */ SWIGRUNTIME swig_type_info * SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { swig_type_info *lastty = ty; if (!ty || !ty->dcast) return ty; while (ty && (ty->dcast)) { ty = (*ty->dcast)(ptr); if (ty) lastty = ty; } return lastty; } /* Return the name associated with this type */ SWIGRUNTIMEINLINE const char * SWIG_TypeName(const swig_type_info *ty) { return ty->name; } /* Return the pretty name associated with this type, that is an unmangled type name in a form presentable to the user. */ SWIGRUNTIME const char * SWIG_TypePrettyName(const swig_type_info *type) { /* The "str" field contains the equivalent pretty names of the type, separated by vertical-bar characters. We choose to print the last name, as it is often (?) the most specific. */ if (!type) return NULL; if (type->str != NULL) { const char *last_name = type->str; const char *s; for (s = type->str; *s; s++) if (*s == '|') last_name = s+1; return last_name; } else return type->name; } /* Set the clientdata field for a type */ SWIGRUNTIME void SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { swig_cast_info *cast = ti->cast; /* if (ti->clientdata == clientdata) return; */ ti->clientdata = clientdata; while (cast) { if (!cast->converter) { swig_type_info *tc = cast->type; if (!tc->clientdata) { SWIG_TypeClientData(tc, clientdata); } } cast = cast->next; } } SWIGRUNTIME void SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { SWIG_TypeClientData(ti, clientdata); ti->owndata = 1; } /* Search for a swig_type_info structure only by mangled name Search is a O(log #types) We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_MangledTypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { swig_module_info *iter = start; do { if (iter->size) { register size_t l = 0; register size_t r = iter->size - 1; do { /* since l+r >= 0, we can (>> 1) instead (/ 2) */ register size_t i = (l + r) >> 1; const char *iname = iter->types[i]->name; if (iname) { register int compare = strcmp(name, iname); if (compare == 0) { return iter->types[i]; } else if (compare < 0) { if (i) { r = i - 1; } else { break; } } else if (compare > 0) { l = i + 1; } } else { break; /* should never happen */ } } while (l <= r); } iter = iter->next; } while (iter != end); return 0; } /* Search for a swig_type_info structure for either a mangled name or a human readable name. It first searches the mangled names of the types, which is a O(log #types) If a type is not found it then searches the human readable names, which is O(#types). We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_TypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { /* STEP 1: Search the name field using binary search */ swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); if (ret) { return ret; } else { /* STEP 2: If the type hasn't been found, do a complete search of the str field (the human readable name) */ swig_module_info *iter = start; do { register size_t i = 0; for (; i < iter->size; ++i) { if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) return iter->types[i]; } iter = iter->next; } while (iter != end); } /* neither found a match */ return 0; } /* Pack binary data into a string */ SWIGRUNTIME char * SWIG_PackData(char *c, void *ptr, size_t sz) { static const char hex[17] = "0123456789abcdef"; register const unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register unsigned char uu = *u; *(c++) = hex[(uu & 0xf0) >> 4]; *(c++) = hex[uu & 0xf]; } return c; } /* Unpack binary data from a string */ SWIGRUNTIME const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { register unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register char d = *(c++); register unsigned char uu; if ((d >= '0') && (d <= '9')) uu = ((d - '0') << 4); else if ((d >= 'a') && (d <= 'f')) uu = ((d - ('a'-10)) << 4); else return (char *) 0; d = *(c++); if ((d >= '0') && (d <= '9')) uu |= (d - '0'); else if ((d >= 'a') && (d <= 'f')) uu |= (d - ('a'-10)); else return (char *) 0; *u = uu; } return c; } /* Pack 'void *' into a string buffer. */ SWIGRUNTIME char * SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { char *r = buff; if ((2*sizeof(void *) + 2) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,&ptr,sizeof(void *)); if (strlen(name) + 1 > (bsz - (r - buff))) return 0; strcpy(r,name); return buff; } SWIGRUNTIME const char * SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { *ptr = (void *) 0; return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sizeof(void *)); } SWIGRUNTIME char * SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { char *r = buff; size_t lname = (name ? strlen(name) : 0); if ((2*sz + 2 + lname) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,ptr,sz); if (lname) { strncpy(r,name,lname+1); } else { *r = 0; } return buff; } SWIGRUNTIME const char * SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { memset(ptr,0,sz); return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sz); } #ifdef __cplusplus } #endif /* Errors in SWIG */ #define SWIG_UnknownError -1 #define SWIG_IOError -2 #define SWIG_RuntimeError -3 #define SWIG_IndexError -4 #define SWIG_TypeError -5 #define SWIG_DivisionByZero -6 #define SWIG_OverflowError -7 #define SWIG_SyntaxError -8 #define SWIG_ValueError -9 #define SWIG_SystemError -10 #define SWIG_AttributeError -11 #define SWIG_MemoryError -12 #define SWIG_NullReferenceError -13 /* Compatibility macros for Python 3 */ #if PY_VERSION_HEX >= 0x03000000 #define PyClass_Check(obj) PyObject_IsInstance(obj, (PyObject *)&PyType_Type) #define PyInt_Check(x) PyLong_Check(x) #define PyInt_AsLong(x) PyLong_AsLong(x) #define PyInt_FromLong(x) PyLong_FromLong(x) #define PyInt_FromSize_t(x) PyLong_FromSize_t(x) #define PyString_Check(name) PyBytes_Check(name) #define PyString_FromString(x) PyUnicode_FromString(x) #define PyString_Format(fmt, args) PyUnicode_Format(fmt, args) #define PyString_AsString(str) PyBytes_AsString(str) #define PyString_Size(str) PyBytes_Size(str) #define PyString_InternFromString(key) PyUnicode_InternFromString(key) #define Py_TPFLAGS_HAVE_CLASS Py_TPFLAGS_BASETYPE #define PyString_AS_STRING(x) PyUnicode_AS_STRING(x) #define _PyLong_FromSsize_t(x) PyLong_FromSsize_t(x) #endif #ifndef Py_TYPE # define Py_TYPE(op) ((op)->ob_type) #endif /* SWIG APIs for compatibility of both Python 2 & 3 */ #if PY_VERSION_HEX >= 0x03000000 # define SWIG_Python_str_FromFormat PyUnicode_FromFormat #else # define SWIG_Python_str_FromFormat PyString_FromFormat #endif /* Warning: This function will allocate a new string in Python 3, * so please call SWIG_Python_str_DelForPy3(x) to free the space. */ SWIGINTERN char* SWIG_Python_str_AsChar(PyObject *str) { #if PY_VERSION_HEX >= 0x03000000 char *cstr; char *newstr; Py_ssize_t len; str = PyUnicode_AsUTF8String(str); PyBytes_AsStringAndSize(str, &cstr, &len); newstr = (char *) malloc(len+1); memcpy(newstr, cstr, len+1); Py_XDECREF(str); return newstr; #else return PyString_AsString(str); #endif } #if PY_VERSION_HEX >= 0x03000000 # define SWIG_Python_str_DelForPy3(x) free( (void*) (x) ) #else # define SWIG_Python_str_DelForPy3(x) #endif SWIGINTERN PyObject* SWIG_Python_str_FromChar(const char *c) { #if PY_VERSION_HEX >= 0x03000000 return PyUnicode_FromString(c); #else return PyString_FromString(c); #endif } /* Add PyOS_snprintf for old Pythons */ #if PY_VERSION_HEX < 0x02020000 # if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM) # define PyOS_snprintf _snprintf # else # define PyOS_snprintf snprintf # endif #endif /* A crude PyString_FromFormat implementation for old Pythons */ #if PY_VERSION_HEX < 0x02020000 #ifndef SWIG_PYBUFFER_SIZE # define SWIG_PYBUFFER_SIZE 1024 #endif static PyObject * PyString_FromFormat(const char *fmt, ...) { va_list ap; char buf[SWIG_PYBUFFER_SIZE * 2]; int res; va_start(ap, fmt); res = vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); return (res < 0 || res >= (int)sizeof(buf)) ? 0 : PyString_FromString(buf); } #endif /* Add PyObject_Del for old Pythons */ #if PY_VERSION_HEX < 0x01060000 # define PyObject_Del(op) PyMem_DEL((op)) #endif #ifndef PyObject_DEL # define PyObject_DEL PyObject_Del #endif /* A crude PyExc_StopIteration exception for old Pythons */ #if PY_VERSION_HEX < 0x02020000 # ifndef PyExc_StopIteration # define PyExc_StopIteration PyExc_RuntimeError # endif # ifndef PyObject_GenericGetAttr # define PyObject_GenericGetAttr 0 # endif #endif /* Py_NotImplemented is defined in 2.1 and up. */ #if PY_VERSION_HEX < 0x02010000 # ifndef Py_NotImplemented # define Py_NotImplemented PyExc_RuntimeError # endif #endif /* A crude PyString_AsStringAndSize implementation for old Pythons */ #if PY_VERSION_HEX < 0x02010000 # ifndef PyString_AsStringAndSize # define PyString_AsStringAndSize(obj, s, len) {*s = PyString_AsString(obj); *len = *s ? strlen(*s) : 0;} # endif #endif /* PySequence_Size for old Pythons */ #if PY_VERSION_HEX < 0x02000000 # ifndef PySequence_Size # define PySequence_Size PySequence_Length # endif #endif /* PyBool_FromLong for old Pythons */ #if PY_VERSION_HEX < 0x02030000 static PyObject *PyBool_FromLong(long ok) { PyObject *result = ok ? Py_True : Py_False; Py_INCREF(result); return result; } #endif /* Py_ssize_t for old Pythons */ /* This code is as recommended by: */ /* http://www.python.org/dev/peps/pep-0353/#conversion-guidelines */ #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) typedef int Py_ssize_t; # define PY_SSIZE_T_MAX INT_MAX # define PY_SSIZE_T_MIN INT_MIN typedef inquiry lenfunc; typedef intargfunc ssizeargfunc; typedef intintargfunc ssizessizeargfunc; typedef intobjargproc ssizeobjargproc; typedef intintobjargproc ssizessizeobjargproc; typedef getreadbufferproc readbufferproc; typedef getwritebufferproc writebufferproc; typedef getsegcountproc segcountproc; typedef getcharbufferproc charbufferproc; static long PyNumber_AsSsize_t (PyObject *x, void *SWIGUNUSEDPARM(exc)) { long result = 0; PyObject *i = PyNumber_Int(x); if (i) { result = PyInt_AsLong(i); Py_DECREF(i); } return result; } #endif #if PY_VERSION_HEX < 0x02050000 #define PyInt_FromSize_t(x) PyInt_FromLong((long)x) #endif #if PY_VERSION_HEX < 0x02040000 #define Py_VISIT(op) \ do { \ if (op) { \ int vret = visit((op), arg); \ if (vret) \ return vret; \ } \ } while (0) #endif #if PY_VERSION_HEX < 0x02030000 typedef struct { PyTypeObject type; PyNumberMethods as_number; PyMappingMethods as_mapping; PySequenceMethods as_sequence; PyBufferProcs as_buffer; PyObject *name, *slots; } PyHeapTypeObject; #endif #if PY_VERSION_HEX < 0x02030000 typedef destructor freefunc; #endif #if ((PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION > 6) || \ (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION > 0) || \ (PY_MAJOR_VERSION > 3)) # define SWIGPY_USE_CAPSULE # define SWIGPY_CAPSULE_NAME ((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION ".type_pointer_capsule" SWIG_TYPE_TABLE_NAME) #endif #if PY_VERSION_HEX < 0x03020000 #define PyDescr_TYPE(x) (((PyDescrObject *)(x))->d_type) #define PyDescr_NAME(x) (((PyDescrObject *)(x))->d_name) #endif /* ----------------------------------------------------------------------------- * error manipulation * ----------------------------------------------------------------------------- */ SWIGRUNTIME PyObject* SWIG_Python_ErrorType(int code) { PyObject* type = 0; switch(code) { case SWIG_MemoryError: type = PyExc_MemoryError; break; case SWIG_IOError: type = PyExc_IOError; break; case SWIG_RuntimeError: type = PyExc_RuntimeError; break; case SWIG_IndexError: type = PyExc_IndexError; break; case SWIG_TypeError: type = PyExc_TypeError; break; case SWIG_DivisionByZero: type = PyExc_ZeroDivisionError; break; case SWIG_OverflowError: type = PyExc_OverflowError; break; case SWIG_SyntaxError: type = PyExc_SyntaxError; break; case SWIG_ValueError: type = PyExc_ValueError; break; case SWIG_SystemError: type = PyExc_SystemError; break; case SWIG_AttributeError: type = PyExc_AttributeError; break; default: type = PyExc_RuntimeError; } return type; } SWIGRUNTIME void SWIG_Python_AddErrorMsg(const char* mesg) { PyObject *type = 0; PyObject *value = 0; PyObject *traceback = 0; if (PyErr_Occurred()) PyErr_Fetch(&type, &value, &traceback); if (value) { char *tmp; PyObject *old_str = PyObject_Str(value); PyErr_Clear(); Py_XINCREF(type); PyErr_Format(type, "%s %s", tmp = SWIG_Python_str_AsChar(old_str), mesg); SWIG_Python_str_DelForPy3(tmp); Py_DECREF(old_str); Py_DECREF(value); } else { PyErr_SetString(PyExc_RuntimeError, mesg); } } #if defined(SWIG_PYTHON_NO_THREADS) # if defined(SWIG_PYTHON_THREADS) # undef SWIG_PYTHON_THREADS # endif #endif #if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */ # if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL) # if (PY_VERSION_HEX >= 0x02030000) /* For 2.3 or later, use the PyGILState calls */ # define SWIG_PYTHON_USE_GIL # endif # endif # if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */ # ifndef SWIG_PYTHON_INITIALIZE_THREADS # define SWIG_PYTHON_INITIALIZE_THREADS PyEval_InitThreads() # endif # ifdef __cplusplus /* C++ code */ class SWIG_Python_Thread_Block { bool status; PyGILState_STATE state; public: void end() { if (status) { PyGILState_Release(state); status = false;} } SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} ~SWIG_Python_Thread_Block() { end(); } }; class SWIG_Python_Thread_Allow { bool status; PyThreadState *save; public: void end() { if (status) { PyEval_RestoreThread(save); status = false; }} SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} ~SWIG_Python_Thread_Allow() { end(); } }; # define SWIG_PYTHON_THREAD_BEGIN_BLOCK SWIG_Python_Thread_Block _swig_thread_block # define SWIG_PYTHON_THREAD_END_BLOCK _swig_thread_block.end() # define SWIG_PYTHON_THREAD_BEGIN_ALLOW SWIG_Python_Thread_Allow _swig_thread_allow # define SWIG_PYTHON_THREAD_END_ALLOW _swig_thread_allow.end() # else /* C code */ # define SWIG_PYTHON_THREAD_BEGIN_BLOCK PyGILState_STATE _swig_thread_block = PyGILState_Ensure() # define SWIG_PYTHON_THREAD_END_BLOCK PyGILState_Release(_swig_thread_block) # define SWIG_PYTHON_THREAD_BEGIN_ALLOW PyThreadState *_swig_thread_allow = PyEval_SaveThread() # define SWIG_PYTHON_THREAD_END_ALLOW PyEval_RestoreThread(_swig_thread_allow) # endif # else /* Old thread way, not implemented, user must provide it */ # if !defined(SWIG_PYTHON_INITIALIZE_THREADS) # define SWIG_PYTHON_INITIALIZE_THREADS # endif # if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK) # define SWIG_PYTHON_THREAD_BEGIN_BLOCK # endif # if !defined(SWIG_PYTHON_THREAD_END_BLOCK) # define SWIG_PYTHON_THREAD_END_BLOCK # endif # if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW) # define SWIG_PYTHON_THREAD_BEGIN_ALLOW # endif # if !defined(SWIG_PYTHON_THREAD_END_ALLOW) # define SWIG_PYTHON_THREAD_END_ALLOW # endif # endif #else /* No thread support */ # define SWIG_PYTHON_INITIALIZE_THREADS # define SWIG_PYTHON_THREAD_BEGIN_BLOCK # define SWIG_PYTHON_THREAD_END_BLOCK # define SWIG_PYTHON_THREAD_BEGIN_ALLOW # define SWIG_PYTHON_THREAD_END_ALLOW #endif /* ----------------------------------------------------------------------------- * Python API portion that goes into the runtime * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #endif /* ----------------------------------------------------------------------------- * Constant declarations * ----------------------------------------------------------------------------- */ /* Constant Types */ #define SWIG_PY_POINTER 4 #define SWIG_PY_BINARY 5 /* Constant information structure */ typedef struct swig_const_info { int type; char *name; long lvalue; double dvalue; void *pvalue; swig_type_info **ptype; } swig_const_info; /* ----------------------------------------------------------------------------- * Wrapper of PyInstanceMethod_New() used in Python 3 * It is exported to the generated module, used for -fastproxy * ----------------------------------------------------------------------------- */ #if PY_VERSION_HEX >= 0x03000000 SWIGRUNTIME PyObject* SWIG_PyInstanceMethod_New(PyObject *SWIGUNUSEDPARM(self), PyObject *func) { return PyInstanceMethod_New(func); } #else SWIGRUNTIME PyObject* SWIG_PyInstanceMethod_New(PyObject *SWIGUNUSEDPARM(self), PyObject *SWIGUNUSEDPARM(func)) { return NULL; } #endif #ifdef __cplusplus } #endif /* ----------------------------------------------------------------------------- * pyrun.swg * * This file contains the runtime support for Python modules * and includes code for managing global variables and pointer * type checking. * * ----------------------------------------------------------------------------- */ /* Common SWIG API */ /* for raw pointers */ #define SWIG_Python_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0) #define SWIG_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtr(obj, pptr, type, flags) #define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own) #ifdef SWIGPYTHON_BUILTIN #define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(self, ptr, type, flags) #else #define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(NULL, ptr, type, flags) #endif #define SWIG_InternalNewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(NULL, ptr, type, flags) #define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) #define SWIG_AcquirePtr(ptr, src) SWIG_Python_AcquirePtr(ptr, src) #define swig_owntype int /* for raw packed data */ #define SWIG_ConvertPacked(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) #define SWIG_NewPackedObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) /* for class or struct pointers */ #define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_ConvertPtr(obj, pptr, type, flags) #define SWIG_NewInstanceObj(ptr, type, flags) SWIG_NewPointerObj(ptr, type, flags) /* for C or C++ function pointers */ #define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_Python_ConvertFunctionPtr(obj, pptr, type) #define SWIG_NewFunctionPtrObj(ptr, type) SWIG_Python_NewPointerObj(NULL, ptr, type, 0) /* for C++ member pointers, ie, member methods */ #define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) #define SWIG_NewMemberObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) /* Runtime API */ #define SWIG_GetModule(clientdata) SWIG_Python_GetModule(clientdata) #define SWIG_SetModule(clientdata, pointer) SWIG_Python_SetModule(pointer) #define SWIG_NewClientData(obj) SwigPyClientData_New(obj) #define SWIG_SetErrorObj SWIG_Python_SetErrorObj #define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg #define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) #define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) #define SWIG_fail goto fail /* Runtime API implementation */ /* Error manipulation */ SWIGINTERN void SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; PyErr_SetObject(errtype, obj); Py_DECREF(obj); SWIG_PYTHON_THREAD_END_BLOCK; } SWIGINTERN void SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; PyErr_SetString(errtype, msg); SWIG_PYTHON_THREAD_END_BLOCK; } #define SWIG_Python_Raise(obj, type, desc) SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj) /* Set a constant value */ #if defined(SWIGPYTHON_BUILTIN) SWIGINTERN void SwigPyBuiltin_AddPublicSymbol(PyObject *seq, const char *key) { PyObject *s = PyString_InternFromString(key); PyList_Append(seq, s); Py_DECREF(s); } SWIGINTERN void SWIG_Python_SetConstant(PyObject *d, PyObject *public_interface, const char *name, PyObject *obj) { #if PY_VERSION_HEX < 0x02030000 PyDict_SetItemString(d, (char *)name, obj); #else PyDict_SetItemString(d, name, obj); #endif Py_DECREF(obj); if (public_interface) SwigPyBuiltin_AddPublicSymbol(public_interface, name); } #else SWIGINTERN void SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { #if PY_VERSION_HEX < 0x02030000 PyDict_SetItemString(d, (char *)name, obj); #else PyDict_SetItemString(d, name, obj); #endif Py_DECREF(obj); } #endif /* Append a value to the result obj */ SWIGINTERN PyObject* SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) { #if !defined(SWIG_PYTHON_OUTPUT_TUPLE) if (!result) { result = obj; } else if (result == Py_None) { Py_DECREF(result); result = obj; } else { if (!PyList_Check(result)) { PyObject *o2 = result; result = PyList_New(1); PyList_SetItem(result, 0, o2); } PyList_Append(result,obj); Py_DECREF(obj); } return result; #else PyObject* o2; PyObject* o3; if (!result) { result = obj; } else if (result == Py_None) { Py_DECREF(result); result = obj; } else { if (!PyTuple_Check(result)) { o2 = result; result = PyTuple_New(1); PyTuple_SET_ITEM(result, 0, o2); } o3 = PyTuple_New(1); PyTuple_SET_ITEM(o3, 0, obj); o2 = result; result = PySequence_Concat(o2, o3); Py_DECREF(o2); Py_DECREF(o3); } return result; #endif } /* Unpack the argument tuple */ SWIGINTERN int SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) { if (!args) { if (!min && !max) { return 1; } else { PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", name, (min == max ? "" : "at least "), (int)min); return 0; } } if (!PyTuple_Check(args)) { if (min <= 1 && max >= 1) { register int i; objs[0] = args; for (i = 1; i < max; ++i) { objs[i] = 0; } return 2; } PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); return 0; } else { register Py_ssize_t l = PyTuple_GET_SIZE(args); if (l < min) { PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", name, (min == max ? "" : "at least "), (int)min, (int)l); return 0; } else if (l > max) { PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", name, (min == max ? "" : "at most "), (int)max, (int)l); return 0; } else { register int i; for (i = 0; i < l; ++i) { objs[i] = PyTuple_GET_ITEM(args, i); } for (; l < max; ++l) { objs[l] = 0; } return i + 1; } } } /* A functor is a function object with one single object argument */ #if PY_VERSION_HEX >= 0x02020000 #define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunctionObjArgs(functor, obj, NULL); #else #define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunction(functor, "O", obj); #endif /* Helper for static pointer initialization for both C and C++ code, for example static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...); */ #ifdef __cplusplus #define SWIG_STATIC_POINTER(var) var #else #define SWIG_STATIC_POINTER(var) var = 0; if (!var) var #endif /* ----------------------------------------------------------------------------- * Pointer declarations * ----------------------------------------------------------------------------- */ /* Flags for new pointer objects */ #define SWIG_POINTER_NOSHADOW (SWIG_POINTER_OWN << 1) #define SWIG_POINTER_NEW (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN) #define SWIG_POINTER_IMPLICIT_CONV (SWIG_POINTER_DISOWN << 1) #define SWIG_BUILTIN_TP_INIT (SWIG_POINTER_OWN << 2) #define SWIG_BUILTIN_INIT (SWIG_BUILTIN_TP_INIT | SWIG_POINTER_OWN) #ifdef __cplusplus extern "C" { #endif /* How to access Py_None */ #if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # ifndef SWIG_PYTHON_NO_BUILD_NONE # ifndef SWIG_PYTHON_BUILD_NONE # define SWIG_PYTHON_BUILD_NONE # endif # endif #endif #ifdef SWIG_PYTHON_BUILD_NONE # ifdef Py_None # undef Py_None # define Py_None SWIG_Py_None() # endif SWIGRUNTIMEINLINE PyObject * _SWIG_Py_None(void) { PyObject *none = Py_BuildValue((char*)""); Py_DECREF(none); return none; } SWIGRUNTIME PyObject * SWIG_Py_None(void) { static PyObject *SWIG_STATIC_POINTER(none) = _SWIG_Py_None(); return none; } #endif /* The python void return value */ SWIGRUNTIMEINLINE PyObject * SWIG_Py_Void(void) { PyObject *none = Py_None; Py_INCREF(none); return none; } /* SwigPyClientData */ typedef struct { PyObject *klass; PyObject *newraw; PyObject *newargs; PyObject *destroy; int delargs; int implicitconv; PyTypeObject *pytype; } SwigPyClientData; SWIGRUNTIMEINLINE int SWIG_Python_CheckImplicit(swig_type_info *ty) { SwigPyClientData *data = (SwigPyClientData *)ty->clientdata; return data ? data->implicitconv : 0; } SWIGRUNTIMEINLINE PyObject * SWIG_Python_ExceptionType(swig_type_info *desc) { SwigPyClientData *data = desc ? (SwigPyClientData *) desc->clientdata : 0; PyObject *klass = data ? data->klass : 0; return (klass ? klass : PyExc_RuntimeError); } SWIGRUNTIME SwigPyClientData * SwigPyClientData_New(PyObject* obj) { if (!obj) { return 0; } else { SwigPyClientData *data = (SwigPyClientData *)malloc(sizeof(SwigPyClientData)); /* the klass element */ data->klass = obj; Py_INCREF(data->klass); /* the newraw method and newargs arguments used to create a new raw instance */ if (PyClass_Check(obj)) { data->newraw = 0; data->newargs = obj; Py_INCREF(obj); } else { #if (PY_VERSION_HEX < 0x02020000) data->newraw = 0; #else data->newraw = PyObject_GetAttrString(data->klass, (char *)"__new__"); #endif if (data->newraw) { Py_INCREF(data->newraw); data->newargs = PyTuple_New(1); PyTuple_SetItem(data->newargs, 0, obj); } else { data->newargs = obj; } Py_INCREF(data->newargs); } /* the destroy method, aka as the C++ delete method */ data->destroy = PyObject_GetAttrString(data->klass, (char *)"__swig_destroy__"); if (PyErr_Occurred()) { PyErr_Clear(); data->destroy = 0; } if (data->destroy) { int flags; Py_INCREF(data->destroy); flags = PyCFunction_GET_FLAGS(data->destroy); #ifdef METH_O data->delargs = !(flags & (METH_O)); #else data->delargs = 0; #endif } else { data->delargs = 0; } data->implicitconv = 0; data->pytype = 0; return data; } } SWIGRUNTIME void SwigPyClientData_Del(SwigPyClientData *data) { Py_XDECREF(data->newraw); Py_XDECREF(data->newargs); Py_XDECREF(data->destroy); } /* =============== SwigPyObject =====================*/ typedef struct { PyObject_HEAD void *ptr; swig_type_info *ty; int own; PyObject *next; #ifdef SWIGPYTHON_BUILTIN PyObject *dict; #endif } SwigPyObject; SWIGRUNTIME PyObject * SwigPyObject_long(SwigPyObject *v) { return PyLong_FromVoidPtr(v->ptr); } SWIGRUNTIME PyObject * SwigPyObject_format(const char* fmt, SwigPyObject *v) { PyObject *res = NULL; PyObject *args = PyTuple_New(1); if (args) { if (PyTuple_SetItem(args, 0, SwigPyObject_long(v)) == 0) { PyObject *ofmt = SWIG_Python_str_FromChar(fmt); if (ofmt) { #if PY_VERSION_HEX >= 0x03000000 res = PyUnicode_Format(ofmt,args); #else res = PyString_Format(ofmt,args); #endif Py_DECREF(ofmt); } Py_DECREF(args); } } return res; } SWIGRUNTIME PyObject * SwigPyObject_oct(SwigPyObject *v) { return SwigPyObject_format("%o",v); } SWIGRUNTIME PyObject * SwigPyObject_hex(SwigPyObject *v) { return SwigPyObject_format("%x",v); } SWIGRUNTIME PyObject * #ifdef METH_NOARGS SwigPyObject_repr(SwigPyObject *v) #else SwigPyObject_repr(SwigPyObject *v, PyObject *args) #endif { const char *name = SWIG_TypePrettyName(v->ty); PyObject *repr = SWIG_Python_str_FromFormat("", (name ? name : "unknown"), (void *)v); if (v->next) { # ifdef METH_NOARGS PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next); # else PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next, args); # endif # if PY_VERSION_HEX >= 0x03000000 PyObject *joined = PyUnicode_Concat(repr, nrep); Py_DecRef(repr); Py_DecRef(nrep); repr = joined; # else PyString_ConcatAndDel(&repr,nrep); # endif } return repr; } SWIGRUNTIME int SwigPyObject_compare(SwigPyObject *v, SwigPyObject *w) { void *i = v->ptr; void *j = w->ptr; return (i < j) ? -1 : ((i > j) ? 1 : 0); } /* Added for Python 3.x, would it also be useful for Python 2.x? */ SWIGRUNTIME PyObject* SwigPyObject_richcompare(SwigPyObject *v, SwigPyObject *w, int op) { PyObject* res; if( op != Py_EQ && op != Py_NE ) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } res = PyBool_FromLong( (SwigPyObject_compare(v, w)==0) == (op == Py_EQ) ? 1 : 0); return res; } SWIGRUNTIME PyTypeObject* SwigPyObject_TypeOnce(void); #ifdef SWIGPYTHON_BUILTIN static swig_type_info *SwigPyObject_stype = 0; SWIGRUNTIME PyTypeObject* SwigPyObject_type(void) { SwigPyClientData *cd; assert(SwigPyObject_stype); cd = (SwigPyClientData*) SwigPyObject_stype->clientdata; assert(cd); assert(cd->pytype); return cd->pytype; } #else SWIGRUNTIME PyTypeObject* SwigPyObject_type(void) { static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyObject_TypeOnce(); return type; } #endif SWIGRUNTIMEINLINE int SwigPyObject_Check(PyObject *op) { #ifdef SWIGPYTHON_BUILTIN PyTypeObject *target_tp = SwigPyObject_type(); if (PyType_IsSubtype(op->ob_type, target_tp)) return 1; return (strcmp(op->ob_type->tp_name, "SwigPyObject") == 0); #else return (Py_TYPE(op) == SwigPyObject_type()) || (strcmp(Py_TYPE(op)->tp_name,"SwigPyObject") == 0); #endif } SWIGRUNTIME PyObject * SwigPyObject_New(void *ptr, swig_type_info *ty, int own); SWIGRUNTIME void SwigPyObject_dealloc(PyObject *v) { SwigPyObject *sobj = (SwigPyObject *) v; PyObject *next = sobj->next; if (sobj->own == SWIG_POINTER_OWN) { swig_type_info *ty = sobj->ty; SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; PyObject *destroy = data ? data->destroy : 0; if (destroy) { /* destroy is always a VARARGS method */ PyObject *res; if (data->delargs) { /* we need to create a temporary object to carry the destroy operation */ PyObject *tmp = SwigPyObject_New(sobj->ptr, ty, 0); res = SWIG_Python_CallFunctor(destroy, tmp); Py_DECREF(tmp); } else { PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); PyObject *mself = PyCFunction_GET_SELF(destroy); res = ((*meth)(mself, v)); } Py_XDECREF(res); } #if !defined(SWIG_PYTHON_SILENT_MEMLEAK) else { const char *name = SWIG_TypePrettyName(ty); printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); } #endif } Py_XDECREF(next); PyObject_DEL(v); } SWIGRUNTIME PyObject* SwigPyObject_append(PyObject* v, PyObject* next) { SwigPyObject *sobj = (SwigPyObject *) v; #ifndef METH_O PyObject *tmp = 0; if (!PyArg_ParseTuple(next,(char *)"O:append", &tmp)) return NULL; next = tmp; #endif if (!SwigPyObject_Check(next)) { return NULL; } sobj->next = next; Py_INCREF(next); return SWIG_Py_Void(); } SWIGRUNTIME PyObject* #ifdef METH_NOARGS SwigPyObject_next(PyObject* v) #else SwigPyObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) #endif { SwigPyObject *sobj = (SwigPyObject *) v; if (sobj->next) { Py_INCREF(sobj->next); return sobj->next; } else { return SWIG_Py_Void(); } } SWIGINTERN PyObject* #ifdef METH_NOARGS SwigPyObject_disown(PyObject *v) #else SwigPyObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) #endif { SwigPyObject *sobj = (SwigPyObject *)v; sobj->own = 0; return SWIG_Py_Void(); } SWIGINTERN PyObject* #ifdef METH_NOARGS SwigPyObject_acquire(PyObject *v) #else SwigPyObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) #endif { SwigPyObject *sobj = (SwigPyObject *)v; sobj->own = SWIG_POINTER_OWN; return SWIG_Py_Void(); } SWIGINTERN PyObject* SwigPyObject_own(PyObject *v, PyObject *args) { PyObject *val = 0; #if (PY_VERSION_HEX < 0x02020000) if (!PyArg_ParseTuple(args,(char *)"|O:own",&val)) #elif (PY_VERSION_HEX < 0x02050000) if (!PyArg_UnpackTuple(args, (char *)"own", 0, 1, &val)) #else if (!PyArg_UnpackTuple(args, "own", 0, 1, &val)) #endif { return NULL; } else { SwigPyObject *sobj = (SwigPyObject *)v; PyObject *obj = PyBool_FromLong(sobj->own); if (val) { #ifdef METH_NOARGS if (PyObject_IsTrue(val)) { SwigPyObject_acquire(v); } else { SwigPyObject_disown(v); } #else if (PyObject_IsTrue(val)) { SwigPyObject_acquire(v,args); } else { SwigPyObject_disown(v,args); } #endif } return obj; } } #ifdef METH_O static PyMethodDef swigobject_methods[] = { {(char *)"disown", (PyCFunction)SwigPyObject_disown, METH_NOARGS, (char *)"releases ownership of the pointer"}, {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_NOARGS, (char *)"acquires ownership of the pointer"}, {(char *)"own", (PyCFunction)SwigPyObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, {(char *)"append", (PyCFunction)SwigPyObject_append, METH_O, (char *)"appends another 'this' object"}, {(char *)"next", (PyCFunction)SwigPyObject_next, METH_NOARGS, (char *)"returns the next 'this' object"}, {(char *)"__repr__",(PyCFunction)SwigPyObject_repr, METH_NOARGS, (char *)"returns object representation"}, {0, 0, 0, 0} }; #else static PyMethodDef swigobject_methods[] = { {(char *)"disown", (PyCFunction)SwigPyObject_disown, METH_VARARGS, (char *)"releases ownership of the pointer"}, {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_VARARGS, (char *)"aquires ownership of the pointer"}, {(char *)"own", (PyCFunction)SwigPyObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, {(char *)"append", (PyCFunction)SwigPyObject_append, METH_VARARGS, (char *)"appends another 'this' object"}, {(char *)"next", (PyCFunction)SwigPyObject_next, METH_VARARGS, (char *)"returns the next 'this' object"}, {(char *)"__repr__",(PyCFunction)SwigPyObject_repr, METH_VARARGS, (char *)"returns object representation"}, {0, 0, 0, 0} }; #endif #if PY_VERSION_HEX < 0x02020000 SWIGINTERN PyObject * SwigPyObject_getattr(SwigPyObject *sobj,char *name) { return Py_FindMethod(swigobject_methods, (PyObject *)sobj, name); } #endif SWIGRUNTIME PyTypeObject* SwigPyObject_TypeOnce(void) { static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; static PyNumberMethods SwigPyObject_as_number = { (binaryfunc)0, /*nb_add*/ (binaryfunc)0, /*nb_subtract*/ (binaryfunc)0, /*nb_multiply*/ /* nb_divide removed in Python 3 */ #if PY_VERSION_HEX < 0x03000000 (binaryfunc)0, /*nb_divide*/ #endif (binaryfunc)0, /*nb_remainder*/ (binaryfunc)0, /*nb_divmod*/ (ternaryfunc)0,/*nb_power*/ (unaryfunc)0, /*nb_negative*/ (unaryfunc)0, /*nb_positive*/ (unaryfunc)0, /*nb_absolute*/ (inquiry)0, /*nb_nonzero*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ 0, /*nb_and*/ 0, /*nb_xor*/ 0, /*nb_or*/ #if PY_VERSION_HEX < 0x03000000 0, /*nb_coerce*/ #endif (unaryfunc)SwigPyObject_long, /*nb_int*/ #if PY_VERSION_HEX < 0x03000000 (unaryfunc)SwigPyObject_long, /*nb_long*/ #else 0, /*nb_reserved*/ #endif (unaryfunc)0, /*nb_float*/ #if PY_VERSION_HEX < 0x03000000 (unaryfunc)SwigPyObject_oct, /*nb_oct*/ (unaryfunc)SwigPyObject_hex, /*nb_hex*/ #endif #if PY_VERSION_HEX >= 0x03000000 /* 3.0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index, nb_inplace_divide removed */ #elif PY_VERSION_HEX >= 0x02050000 /* 2.5.0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */ #elif PY_VERSION_HEX >= 0x02020000 /* 2.2.0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */ #elif PY_VERSION_HEX >= 0x02000000 /* 2.0.0 */ 0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */ #endif }; static PyTypeObject swigpyobject_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { /* PyObject header changed in Python 3 */ #if PY_VERSION_HEX >= 0x03000000 PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif (char *)"SwigPyObject", /* tp_name */ sizeof(SwigPyObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)SwigPyObject_dealloc, /* tp_dealloc */ 0, /* tp_print */ #if PY_VERSION_HEX < 0x02020000 (getattrfunc)SwigPyObject_getattr, /* tp_getattr */ #else (getattrfunc)0, /* tp_getattr */ #endif (setattrfunc)0, /* tp_setattr */ #if PY_VERSION_HEX >= 0x03000000 0, /* tp_reserved in 3.0.1, tp_compare in 3.0.0 but not used */ #else (cmpfunc)SwigPyObject_compare, /* tp_compare */ #endif (reprfunc)SwigPyObject_repr, /* tp_repr */ &SwigPyObject_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)0, /* tp_hash */ (ternaryfunc)0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ swigobject_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ (richcmpfunc)SwigPyObject_richcompare,/* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0, /* tp_iter */ 0, /* tp_iternext */ swigobject_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #if PY_VERSION_HEX >= 0x02060000 0, /* tp_version */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; swigpyobject_type = tmp; type_init = 1; #if PY_VERSION_HEX < 0x02020000 swigpyobject_type.ob_type = &PyType_Type; #else if (PyType_Ready(&swigpyobject_type) < 0) return NULL; #endif } return &swigpyobject_type; } SWIGRUNTIME PyObject * SwigPyObject_New(void *ptr, swig_type_info *ty, int own) { SwigPyObject *sobj = PyObject_NEW(SwigPyObject, SwigPyObject_type()); if (sobj) { sobj->ptr = ptr; sobj->ty = ty; sobj->own = own; sobj->next = 0; } return (PyObject *)sobj; } /* ----------------------------------------------------------------------------- * Implements a simple Swig Packed type, and use it instead of string * ----------------------------------------------------------------------------- */ typedef struct { PyObject_HEAD void *pack; swig_type_info *ty; size_t size; } SwigPyPacked; SWIGRUNTIME int SwigPyPacked_print(SwigPyPacked *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { char result[SWIG_BUFFER_SIZE]; fputs("pack, v->size, 0, sizeof(result))) { fputs("at ", fp); fputs(result, fp); } fputs(v->ty->name,fp); fputs(">", fp); return 0; } SWIGRUNTIME PyObject * SwigPyPacked_repr(SwigPyPacked *v) { char result[SWIG_BUFFER_SIZE]; if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { return SWIG_Python_str_FromFormat("", result, v->ty->name); } else { return SWIG_Python_str_FromFormat("", v->ty->name); } } SWIGRUNTIME PyObject * SwigPyPacked_str(SwigPyPacked *v) { char result[SWIG_BUFFER_SIZE]; if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){ return SWIG_Python_str_FromFormat("%s%s", result, v->ty->name); } else { return SWIG_Python_str_FromChar(v->ty->name); } } SWIGRUNTIME int SwigPyPacked_compare(SwigPyPacked *v, SwigPyPacked *w) { size_t i = v->size; size_t j = w->size; int s = (i < j) ? -1 : ((i > j) ? 1 : 0); return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size); } SWIGRUNTIME PyTypeObject* SwigPyPacked_TypeOnce(void); SWIGRUNTIME PyTypeObject* SwigPyPacked_type(void) { static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyPacked_TypeOnce(); return type; } SWIGRUNTIMEINLINE int SwigPyPacked_Check(PyObject *op) { return ((op)->ob_type == SwigPyPacked_TypeOnce()) || (strcmp((op)->ob_type->tp_name,"SwigPyPacked") == 0); } SWIGRUNTIME void SwigPyPacked_dealloc(PyObject *v) { if (SwigPyPacked_Check(v)) { SwigPyPacked *sobj = (SwigPyPacked *) v; free(sobj->pack); } PyObject_DEL(v); } SWIGRUNTIME PyTypeObject* SwigPyPacked_TypeOnce(void) { static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; static PyTypeObject swigpypacked_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { /* PyObject header changed in Python 3 */ #if PY_VERSION_HEX>=0x03000000 PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif (char *)"SwigPyPacked", /* tp_name */ sizeof(SwigPyPacked), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)SwigPyPacked_dealloc, /* tp_dealloc */ (printfunc)SwigPyPacked_print, /* tp_print */ (getattrfunc)0, /* tp_getattr */ (setattrfunc)0, /* tp_setattr */ #if PY_VERSION_HEX>=0x03000000 0, /* tp_reserved in 3.0.1 */ #else (cmpfunc)SwigPyPacked_compare, /* tp_compare */ #endif (reprfunc)SwigPyPacked_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)0, /* tp_hash */ (ternaryfunc)0, /* tp_call */ (reprfunc)SwigPyPacked_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ swigpacked_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #if PY_VERSION_HEX >= 0x02060000 0, /* tp_version */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; swigpypacked_type = tmp; type_init = 1; #if PY_VERSION_HEX < 0x02020000 swigpypacked_type.ob_type = &PyType_Type; #else if (PyType_Ready(&swigpypacked_type) < 0) return NULL; #endif } return &swigpypacked_type; } SWIGRUNTIME PyObject * SwigPyPacked_New(void *ptr, size_t size, swig_type_info *ty) { SwigPyPacked *sobj = PyObject_NEW(SwigPyPacked, SwigPyPacked_type()); if (sobj) { void *pack = malloc(size); if (pack) { memcpy(pack, ptr, size); sobj->pack = pack; sobj->ty = ty; sobj->size = size; } else { PyObject_DEL((PyObject *) sobj); sobj = 0; } } return (PyObject *) sobj; } SWIGRUNTIME swig_type_info * SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size) { if (SwigPyPacked_Check(obj)) { SwigPyPacked *sobj = (SwigPyPacked *)obj; if (sobj->size != size) return 0; memcpy(ptr, sobj->pack, size); return sobj->ty; } else { return 0; } } /* ----------------------------------------------------------------------------- * pointers/data manipulation * ----------------------------------------------------------------------------- */ SWIGRUNTIMEINLINE PyObject * _SWIG_This(void) { return SWIG_Python_str_FromChar("this"); } static PyObject *swig_this = NULL; SWIGRUNTIME PyObject * SWIG_This(void) { if (swig_this == NULL) swig_this = _SWIG_This(); return swig_this; } /* #define SWIG_PYTHON_SLOW_GETSET_THIS */ /* TODO: I don't know how to implement the fast getset in Python 3 right now */ #if PY_VERSION_HEX>=0x03000000 #define SWIG_PYTHON_SLOW_GETSET_THIS #endif SWIGRUNTIME SwigPyObject * SWIG_Python_GetSwigThis(PyObject *pyobj) { PyObject *obj; if (SwigPyObject_Check(pyobj)) return (SwigPyObject *) pyobj; #ifdef SWIGPYTHON_BUILTIN (void)obj; # ifdef PyWeakref_CheckProxy if (PyWeakref_CheckProxy(pyobj)) { pyobj = PyWeakref_GET_OBJECT(pyobj); if (pyobj && SwigPyObject_Check(pyobj)) return (SwigPyObject*) pyobj; } # endif return NULL; #else obj = 0; #if (!defined(SWIG_PYTHON_SLOW_GETSET_THIS) && (PY_VERSION_HEX >= 0x02030000)) if (PyInstance_Check(pyobj)) { obj = _PyInstance_Lookup(pyobj, SWIG_This()); } else { PyObject **dictptr = _PyObject_GetDictPtr(pyobj); if (dictptr != NULL) { PyObject *dict = *dictptr; obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; } else { #ifdef PyWeakref_CheckProxy if (PyWeakref_CheckProxy(pyobj)) { PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; } #endif obj = PyObject_GetAttr(pyobj,SWIG_This()); if (obj) { Py_DECREF(obj); } else { if (PyErr_Occurred()) PyErr_Clear(); return 0; } } } #else obj = PyObject_GetAttr(pyobj,SWIG_This()); if (obj) { Py_DECREF(obj); } else { if (PyErr_Occurred()) PyErr_Clear(); return 0; } #endif if (obj && !SwigPyObject_Check(obj)) { /* a PyObject is called 'this', try to get the 'real this' SwigPyObject from it */ return SWIG_Python_GetSwigThis(obj); } return (SwigPyObject *)obj; #endif } /* Acquire a pointer value */ SWIGRUNTIME int SWIG_Python_AcquirePtr(PyObject *obj, int own) { if (own == SWIG_POINTER_OWN) { SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); if (sobj) { int oldown = sobj->own; sobj->own = own; return oldown; } } return 0; } /* Convert a pointer value */ SWIGRUNTIME int SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) { int res; SwigPyObject *sobj; int implicit_conv = (flags & SWIG_POINTER_IMPLICIT_CONV) != 0; if (!obj) return SWIG_ERROR; if (obj == Py_None && !implicit_conv) { if (ptr) *ptr = 0; return SWIG_OK; } res = SWIG_ERROR; sobj = SWIG_Python_GetSwigThis(obj); if (own) *own = 0; while (sobj) { void *vptr = sobj->ptr; if (ty) { swig_type_info *to = sobj->ty; if (to == ty) { /* no type cast needed */ if (ptr) *ptr = vptr; break; } else { swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); if (!tc) { sobj = (SwigPyObject *)sobj->next; } else { if (ptr) { int newmemory = 0; *ptr = SWIG_TypeCast(tc,vptr,&newmemory); if (newmemory == SWIG_CAST_NEW_MEMORY) { assert(own); /* badly formed typemap which will lead to a memory leak - it must set and use own to delete *ptr */ if (own) *own = *own | SWIG_CAST_NEW_MEMORY; } } break; } } } else { if (ptr) *ptr = vptr; break; } } if (sobj) { if (own) *own = *own | sobj->own; if (flags & SWIG_POINTER_DISOWN) { sobj->own = 0; } res = SWIG_OK; } else { if (implicit_conv) { SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; if (data && !data->implicitconv) { PyObject *klass = data->klass; if (klass) { PyObject *impconv; data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ impconv = SWIG_Python_CallFunctor(klass, obj); data->implicitconv = 0; if (PyErr_Occurred()) { PyErr_Clear(); impconv = 0; } if (impconv) { SwigPyObject *iobj = SWIG_Python_GetSwigThis(impconv); if (iobj) { void *vptr; res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0); if (SWIG_IsOK(res)) { if (ptr) { *ptr = vptr; /* transfer the ownership to 'ptr' */ iobj->own = 0; res = SWIG_AddCast(res); res = SWIG_AddNewMask(res); } else { res = SWIG_AddCast(res); } } } Py_DECREF(impconv); } } } } if (!SWIG_IsOK(res) && obj == Py_None) { if (ptr) *ptr = 0; if (PyErr_Occurred()) PyErr_Clear(); res = SWIG_OK; } } return res; } /* Convert a function ptr value */ SWIGRUNTIME int SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) { if (!PyCFunction_Check(obj)) { return SWIG_ConvertPtr(obj, ptr, ty, 0); } else { void *vptr = 0; /* here we get the method pointer for callbacks */ const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; if (desc) desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; if (!desc) return SWIG_ERROR; if (ty) { swig_cast_info *tc = SWIG_TypeCheck(desc,ty); if (tc) { int newmemory = 0; *ptr = SWIG_TypeCast(tc,vptr,&newmemory); assert(!newmemory); /* newmemory handling not yet implemented */ } else { return SWIG_ERROR; } } else { *ptr = vptr; } return SWIG_OK; } } /* Convert a packed value value */ SWIGRUNTIME int SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) { swig_type_info *to = SwigPyPacked_UnpackData(obj, ptr, sz); if (!to) return SWIG_ERROR; if (ty) { if (to != ty) { /* check type cast? */ swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); if (!tc) return SWIG_ERROR; } } return SWIG_OK; } /* ----------------------------------------------------------------------------- * Create a new pointer object * ----------------------------------------------------------------------------- */ /* Create a new instance object, without calling __init__, and set the 'this' attribute. */ SWIGRUNTIME PyObject* SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this) { #if (PY_VERSION_HEX >= 0x02020000) PyObject *inst = 0; PyObject *newraw = data->newraw; if (newraw) { inst = PyObject_Call(newraw, data->newargs, NULL); if (inst) { #if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) PyObject **dictptr = _PyObject_GetDictPtr(inst); if (dictptr != NULL) { PyObject *dict = *dictptr; if (dict == NULL) { dict = PyDict_New(); *dictptr = dict; PyDict_SetItem(dict, SWIG_This(), swig_this); } } #else PyObject *key = SWIG_This(); PyObject_SetAttr(inst, key, swig_this); #endif } } else { #if PY_VERSION_HEX >= 0x03000000 inst = PyBaseObject_Type.tp_new((PyTypeObject*) data->newargs, Py_None, Py_None); if (inst) { PyObject_SetAttr(inst, SWIG_This(), swig_this); Py_TYPE(inst)->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG; } #else PyObject *dict = PyDict_New(); if (dict) { PyDict_SetItem(dict, SWIG_This(), swig_this); inst = PyInstance_NewRaw(data->newargs, dict); Py_DECREF(dict); } #endif } return inst; #else #if (PY_VERSION_HEX >= 0x02010000) PyObject *inst = 0; PyObject *dict = PyDict_New(); if (dict) { PyDict_SetItem(dict, SWIG_This(), swig_this); inst = PyInstance_NewRaw(data->newargs, dict); Py_DECREF(dict); } return (PyObject *) inst; #else PyInstanceObject *inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type); if (inst == NULL) { return NULL; } inst->in_class = (PyClassObject *)data->newargs; Py_INCREF(inst->in_class); inst->in_dict = PyDict_New(); if (inst->in_dict == NULL) { Py_DECREF(inst); return NULL; } #ifdef Py_TPFLAGS_HAVE_WEAKREFS inst->in_weakreflist = NULL; #endif #ifdef Py_TPFLAGS_GC PyObject_GC_Init(inst); #endif PyDict_SetItem(inst->in_dict, SWIG_This(), swig_this); return (PyObject *) inst; #endif #endif } SWIGRUNTIME void SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) { PyObject *dict; #if (PY_VERSION_HEX >= 0x02020000) && !defined(SWIG_PYTHON_SLOW_GETSET_THIS) PyObject **dictptr = _PyObject_GetDictPtr(inst); if (dictptr != NULL) { dict = *dictptr; if (dict == NULL) { dict = PyDict_New(); *dictptr = dict; } PyDict_SetItem(dict, SWIG_This(), swig_this); return; } #endif dict = PyObject_GetAttrString(inst, (char*)"__dict__"); PyDict_SetItem(dict, SWIG_This(), swig_this); Py_DECREF(dict); } SWIGINTERN PyObject * SWIG_Python_InitShadowInstance(PyObject *args) { PyObject *obj[2]; if (!SWIG_Python_UnpackTuple(args, "swiginit", 2, 2, obj)) { return NULL; } else { SwigPyObject *sthis = SWIG_Python_GetSwigThis(obj[0]); if (sthis) { SwigPyObject_append((PyObject*) sthis, obj[1]); } else { SWIG_Python_SetSwigThis(obj[0], obj[1]); } return SWIG_Py_Void(); } } /* Create a new pointer object */ SWIGRUNTIME PyObject * SWIG_Python_NewPointerObj(PyObject *self, void *ptr, swig_type_info *type, int flags) { SwigPyClientData *clientdata; PyObject * robj; int own; if (!ptr) return SWIG_Py_Void(); clientdata = type ? (SwigPyClientData *)(type->clientdata) : 0; own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; if (clientdata && clientdata->pytype) { SwigPyObject *newobj; if (flags & SWIG_BUILTIN_TP_INIT) { newobj = (SwigPyObject*) self; if (newobj->ptr) { PyObject *next_self = clientdata->pytype->tp_alloc(clientdata->pytype, 0); while (newobj->next) newobj = (SwigPyObject *) newobj->next; newobj->next = next_self; newobj = (SwigPyObject *)next_self; } } else { newobj = PyObject_New(SwigPyObject, clientdata->pytype); } if (newobj) { newobj->ptr = ptr; newobj->ty = type; newobj->own = own; newobj->next = 0; #ifdef SWIGPYTHON_BUILTIN newobj->dict = 0; #endif return (PyObject*) newobj; } return SWIG_Py_Void(); } assert(!(flags & SWIG_BUILTIN_TP_INIT)); robj = SwigPyObject_New(ptr, type, own); if (robj && clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); Py_DECREF(robj); robj = inst; } return robj; } /* Create a new packed object */ SWIGRUNTIMEINLINE PyObject * SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) { return ptr ? SwigPyPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); } /* -----------------------------------------------------------------------------* * Get type list * -----------------------------------------------------------------------------*/ #ifdef SWIG_LINK_RUNTIME void *SWIG_ReturnGlobalTypeList(void *); #endif SWIGRUNTIME swig_module_info * SWIG_Python_GetModule(void *SWIGUNUSEDPARM(clientdata)) { static void *type_pointer = (void *)0; /* first check if module already created */ if (!type_pointer) { #ifdef SWIG_LINK_RUNTIME type_pointer = SWIG_ReturnGlobalTypeList((void *)0); #else # ifdef SWIGPY_USE_CAPSULE type_pointer = PyCapsule_Import(SWIGPY_CAPSULE_NAME, 0); # else type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME); # endif if (PyErr_Occurred()) { PyErr_Clear(); type_pointer = (void *)0; } #endif } return (swig_module_info *) type_pointer; } #if PY_MAJOR_VERSION < 2 /* PyModule_AddObject function was introduced in Python 2.0. The following function is copied out of Python/modsupport.c in python version 2.3.4 */ SWIGINTERN int PyModule_AddObject(PyObject *m, char *name, PyObject *o) { PyObject *dict; if (!PyModule_Check(m)) { PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs module as first arg"); return SWIG_ERROR; } if (!o) { PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs non-NULL value"); return SWIG_ERROR; } dict = PyModule_GetDict(m); if (dict == NULL) { /* Internal error -- modules must have a dict! */ PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", PyModule_GetName(m)); return SWIG_ERROR; } if (PyDict_SetItemString(dict, name, o)) return SWIG_ERROR; Py_DECREF(o); return SWIG_OK; } #endif SWIGRUNTIME void #ifdef SWIGPY_USE_CAPSULE SWIG_Python_DestroyModule(PyObject *obj) #else SWIG_Python_DestroyModule(void *vptr) #endif { #ifdef SWIGPY_USE_CAPSULE swig_module_info *swig_module = (swig_module_info *) PyCapsule_GetPointer(obj, SWIGPY_CAPSULE_NAME); #else swig_module_info *swig_module = (swig_module_info *) vptr; #endif swig_type_info **types = swig_module->types; size_t i; for (i =0; i < swig_module->size; ++i) { swig_type_info *ty = types[i]; if (ty->owndata) { SwigPyClientData *data = (SwigPyClientData *) ty->clientdata; if (data) SwigPyClientData_Del(data); } } Py_DECREF(SWIG_This()); swig_this = NULL; } SWIGRUNTIME void SWIG_Python_SetModule(swig_module_info *swig_module) { #if PY_VERSION_HEX >= 0x03000000 /* Add a dummy module object into sys.modules */ PyObject *module = PyImport_AddModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION); #else static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} }; /* Sentinel */ PyObject *module = Py_InitModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, swig_empty_runtime_method_table); #endif #ifdef SWIGPY_USE_CAPSULE PyObject *pointer = PyCapsule_New((void *) swig_module, SWIGPY_CAPSULE_NAME, SWIG_Python_DestroyModule); if (pointer && module) { PyModule_AddObject(module, (char*)"type_pointer_capsule" SWIG_TYPE_TABLE_NAME, pointer); } else { Py_XDECREF(pointer); } #else PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, SWIG_Python_DestroyModule); if (pointer && module) { PyModule_AddObject(module, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME, pointer); } else { Py_XDECREF(pointer); } #endif } /* The python cached type query */ SWIGRUNTIME PyObject * SWIG_Python_TypeCache(void) { static PyObject *SWIG_STATIC_POINTER(cache) = PyDict_New(); return cache; } SWIGRUNTIME swig_type_info * SWIG_Python_TypeQuery(const char *type) { PyObject *cache = SWIG_Python_TypeCache(); PyObject *key = SWIG_Python_str_FromChar(type); PyObject *obj = PyDict_GetItem(cache, key); swig_type_info *descriptor; if (obj) { #ifdef SWIGPY_USE_CAPSULE descriptor = (swig_type_info *) PyCapsule_GetPointer(obj, NULL); #else descriptor = (swig_type_info *) PyCObject_AsVoidPtr(obj); #endif } else { swig_module_info *swig_module = SWIG_GetModule(0); descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); if (descriptor) { #ifdef SWIGPY_USE_CAPSULE obj = PyCapsule_New((void*) descriptor, NULL, NULL); #else obj = PyCObject_FromVoidPtr(descriptor, NULL); #endif PyDict_SetItem(cache, key, obj); Py_DECREF(obj); } } Py_DECREF(key); return descriptor; } /* For backward compatibility only */ #define SWIG_POINTER_EXCEPTION 0 #define SWIG_arg_fail(arg) SWIG_Python_ArgFail(arg) #define SWIG_MustGetPtr(p, type, argnum, flags) SWIG_Python_MustGetPtr(p, type, argnum, flags) SWIGRUNTIME int SWIG_Python_AddErrMesg(const char* mesg, int infront) { if (PyErr_Occurred()) { PyObject *type = 0; PyObject *value = 0; PyObject *traceback = 0; PyErr_Fetch(&type, &value, &traceback); if (value) { char *tmp; PyObject *old_str = PyObject_Str(value); Py_XINCREF(type); PyErr_Clear(); if (infront) { PyErr_Format(type, "%s %s", mesg, tmp = SWIG_Python_str_AsChar(old_str)); } else { PyErr_Format(type, "%s %s", tmp = SWIG_Python_str_AsChar(old_str), mesg); } SWIG_Python_str_DelForPy3(tmp); Py_DECREF(old_str); } return 1; } else { return 0; } } SWIGRUNTIME int SWIG_Python_ArgFail(int argnum) { if (PyErr_Occurred()) { /* add information about failing argument */ char mesg[256]; PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); return SWIG_Python_AddErrMesg(mesg, 1); } else { return 0; } } SWIGRUNTIMEINLINE const char * SwigPyObject_GetDesc(PyObject *self) { SwigPyObject *v = (SwigPyObject *)self; swig_type_info *ty = v ? v->ty : 0; return ty ? ty->str : ""; } SWIGRUNTIME void SWIG_Python_TypeError(const char *type, PyObject *obj) { if (type) { #if defined(SWIG_COBJECT_TYPES) if (obj && SwigPyObject_Check(obj)) { const char *otype = (const char *) SwigPyObject_GetDesc(obj); if (otype) { PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'SwigPyObject(%s)' is received", type, otype); return; } } else #endif { const char *otype = (obj ? obj->ob_type->tp_name : 0); if (otype) { PyObject *str = PyObject_Str(obj); const char *cstr = str ? SWIG_Python_str_AsChar(str) : 0; if (cstr) { PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", type, otype, cstr); SWIG_Python_str_DelForPy3(cstr); } else { PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", type, otype); } Py_XDECREF(str); return; } } PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); } else { PyErr_Format(PyExc_TypeError, "unexpected type is received"); } } /* Convert a pointer value, signal an exception on a type mismatch */ SWIGRUNTIME void * SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int SWIGUNUSEDPARM(argnum), int flags) { void *result; if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { PyErr_Clear(); #if SWIG_POINTER_EXCEPTION if (flags) { SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj); SWIG_Python_ArgFail(argnum); } #endif } return result; } #ifdef SWIGPYTHON_BUILTIN SWIGRUNTIME int SWIG_Python_NonDynamicSetAttr(PyObject *obj, PyObject *name, PyObject *value) { PyTypeObject *tp = obj->ob_type; PyObject *descr; PyObject *encoded_name; descrsetfunc f; int res = -1; # ifdef Py_USING_UNICODE if (PyString_Check(name)) { name = PyUnicode_Decode(PyString_AsString(name), PyString_Size(name), NULL, NULL); if (!name) return -1; } else if (!PyUnicode_Check(name)) # else if (!PyString_Check(name)) # endif { PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", name->ob_type->tp_name); return -1; } else { Py_INCREF(name); } if (!tp->tp_dict) { if (PyType_Ready(tp) < 0) goto done; } descr = _PyType_Lookup(tp, name); f = NULL; if (descr != NULL) f = descr->ob_type->tp_descr_set; if (!f) { if (PyString_Check(name)) { encoded_name = name; Py_INCREF(name); } else { encoded_name = PyUnicode_AsUTF8String(name); } PyErr_Format(PyExc_AttributeError, "'%.100s' object has no attribute '%.200s'", tp->tp_name, PyString_AsString(encoded_name)); Py_DECREF(encoded_name); } else { res = f(descr, obj, value); } done: Py_DECREF(name); return res; } #endif #ifdef __cplusplus } #endif #define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) #define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else /* -------- TYPES TABLE (BEGIN) -------- */ #define SWIGTYPE_p_char swig_types[0] #define SWIGTYPE_p_double swig_types[1] static swig_type_info *swig_types[3]; static swig_module_info swig_module = {swig_types, 2, 0, 0, 0, 0}; #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) /* -------- TYPES TABLE (END) -------- */ #if (PY_VERSION_HEX <= 0x02000000) # if !defined(SWIG_PYTHON_CLASSIC) # error "This python version requires swig to be run with the '-classic' option" # endif #endif /*----------------------------------------------- @(target):= _wcscon.so ------------------------------------------------*/ #if PY_VERSION_HEX >= 0x03000000 # define SWIG_init PyInit__wcscon #else # define SWIG_init init_wcscon #endif #define SWIG_name "_wcscon" #define SWIGVERSION 0x020012 #define SWIG_VERSION SWIGVERSION #define SWIG_as_voidptr(a) (void *)((const void *)(a)) #define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a)) #include #if !defined(SWIG_NO_LLONG_MAX) # if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__) # define LLONG_MAX __LONG_LONG_MAX__ # define LLONG_MIN (-LLONG_MAX - 1LL) # define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL) # endif #endif SWIGINTERN int SWIG_AsVal_double (PyObject *obj, double *val) { int res = SWIG_TypeError; if (PyFloat_Check(obj)) { if (val) *val = PyFloat_AsDouble(obj); return SWIG_OK; } else if (PyInt_Check(obj)) { if (val) *val = PyInt_AsLong(obj); return SWIG_OK; } else if (PyLong_Check(obj)) { double v = PyLong_AsDouble(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); } } #ifdef SWIG_PYTHON_CAST_MODE { int dispatch = 0; double d = PyFloat_AsDouble(obj); if (!PyErr_Occurred()) { if (val) *val = d; return SWIG_AddCast(SWIG_OK); } else { PyErr_Clear(); } if (!dispatch) { long v = PyLong_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_AddCast(SWIG_AddCast(SWIG_OK)); } else { PyErr_Clear(); } } } #endif return res; } #include #include SWIGINTERNINLINE int SWIG_CanCastAsInteger(double *d, double min, double max) { double x = *d; if ((min <= x && x <= max)) { double fx = floor(x); double cx = ceil(x); double rd = ((x - fx) < 0.5) ? fx : cx; /* simple rint */ if ((errno == EDOM) || (errno == ERANGE)) { errno = 0; } else { double summ, reps, diff; if (rd < x) { diff = x - rd; } else if (rd > x) { diff = rd - x; } else { return 1; } summ = rd + x; reps = diff/summ; if (reps < 8*DBL_EPSILON) { *d = rd; return 1; } } } return 0; } SWIGINTERN int SWIG_AsVal_long (PyObject *obj, long* val) { if (PyInt_Check(obj)) { if (val) *val = PyInt_AsLong(obj); return SWIG_OK; } else if (PyLong_Check(obj)) { long v = PyLong_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); } } #ifdef SWIG_PYTHON_CAST_MODE { int dispatch = 0; long v = PyInt_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_AddCast(SWIG_OK); } else { PyErr_Clear(); } if (!dispatch) { double d; int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d)); if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, LONG_MAX)) { if (val) *val = (long)(d); return res; } } } #endif return SWIG_TypeError; } SWIGINTERN int SWIG_AsVal_int (PyObject * obj, int *val) { long v; int res = SWIG_AsVal_long (obj, &v); if (SWIG_IsOK(res)) { if ((v < INT_MIN || v > INT_MAX)) { return SWIG_OverflowError; } else { if (val) *val = (int)(v); } } return res; } #define SWIG_From_double PyFloat_FromDouble SWIGINTERN swig_type_info* SWIG_pchar_descriptor(void) { static int init = 0; static swig_type_info* info = 0; if (!init) { info = SWIG_TypeQuery("_p_char"); init = 1; } return info; } SWIGINTERN int SWIG_AsCharPtrAndSize(PyObject *obj, char** cptr, size_t* psize, int *alloc) { #if PY_VERSION_HEX>=0x03000000 if (PyUnicode_Check(obj)) #else if (PyString_Check(obj)) #endif { char *cstr; Py_ssize_t len; #if PY_VERSION_HEX>=0x03000000 if (!alloc && cptr) { /* We can't allow converting without allocation, since the internal representation of string in Python 3 is UCS-2/UCS-4 but we require a UTF-8 representation. TODO(bhy) More detailed explanation */ return SWIG_RuntimeError; } obj = PyUnicode_AsUTF8String(obj); PyBytes_AsStringAndSize(obj, &cstr, &len); if(alloc) *alloc = SWIG_NEWOBJ; #else PyString_AsStringAndSize(obj, &cstr, &len); #endif if (cptr) { if (alloc) { /* In python the user should not be able to modify the inner string representation. To warranty that, if you define SWIG_PYTHON_SAFE_CSTRINGS, a new/copy of the python string buffer is always returned. The default behavior is just to return the pointer value, so, be careful. */ #if defined(SWIG_PYTHON_SAFE_CSTRINGS) if (*alloc != SWIG_OLDOBJ) #else if (*alloc == SWIG_NEWOBJ) #endif { *cptr = (char *)memcpy((char *)malloc((len + 1)*sizeof(char)), cstr, sizeof(char)*(len + 1)); *alloc = SWIG_NEWOBJ; } else { *cptr = cstr; *alloc = SWIG_OLDOBJ; } } else { #if PY_VERSION_HEX>=0x03000000 assert(0); /* Should never reach here in Python 3 */ #endif *cptr = SWIG_Python_str_AsChar(obj); } } if (psize) *psize = len + 1; #if PY_VERSION_HEX>=0x03000000 Py_XDECREF(obj); #endif return SWIG_OK; } else { swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); if (pchar_descriptor) { void* vptr = 0; if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { if (cptr) *cptr = (char *) vptr; if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; if (alloc) *alloc = SWIG_OLDOBJ; return SWIG_OK; } } } return SWIG_TypeError; } SWIGINTERNINLINE PyObject* SWIG_From_int (int value) { return PyInt_FromLong((long) value); } #ifdef __cplusplus extern "C" { #endif SWIGINTERN PyObject *_wrap_wcscon(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; int arg1 ; int arg2 ; double arg3 ; double arg4 ; double *arg5 = (double *) 0 ; double *arg6 = (double *) 0 ; double arg7 ; int val1 ; int ecode1 = 0 ; int val2 ; int ecode2 = 0 ; double val3 ; int ecode3 = 0 ; double val4 ; int ecode4 = 0 ; double temp5 ; int res5 = 0 ; double temp6 ; int res6 = 0 ; double val7 ; int ecode7 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; PyObject * obj3 = 0 ; PyObject * obj4 = 0 ; PyObject * obj5 = 0 ; PyObject * obj6 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OOOOOOO:wcscon",&obj0,&obj1,&obj2,&obj3,&obj4,&obj5,&obj6)) SWIG_fail; ecode1 = SWIG_AsVal_int(obj0, &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "wcscon" "', argument " "1"" of type '" "int""'"); } arg1 = (int)(val1); ecode2 = SWIG_AsVal_int(obj1, &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "wcscon" "', argument " "2"" of type '" "int""'"); } arg2 = (int)(val2); ecode3 = SWIG_AsVal_double(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "wcscon" "', argument " "3"" of type '" "double""'"); } arg3 = (double)(val3); ecode4 = SWIG_AsVal_double(obj3, &val4); if (!SWIG_IsOK(ecode4)) { SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "wcscon" "', argument " "4"" of type '" "double""'"); } arg4 = (double)(val4); if (!(SWIG_IsOK((res5 = SWIG_ConvertPtr(obj4,SWIG_as_voidptrptr(&arg5),SWIGTYPE_p_double,0))))) { double val; int ecode = SWIG_AsVal_double(obj4, &val); if (!SWIG_IsOK(ecode)) { SWIG_exception_fail(SWIG_ArgError(ecode), "in method '" "wcscon" "', argument " "5"" of type '" "double""'"); } temp5 = (double)(val); arg5 = &temp5; res5 = SWIG_AddTmpMask(ecode); } if (!(SWIG_IsOK((res6 = SWIG_ConvertPtr(obj5,SWIG_as_voidptrptr(&arg6),SWIGTYPE_p_double,0))))) { double val; int ecode = SWIG_AsVal_double(obj5, &val); if (!SWIG_IsOK(ecode)) { SWIG_exception_fail(SWIG_ArgError(ecode), "in method '" "wcscon" "', argument " "6"" of type '" "double""'"); } temp6 = (double)(val); arg6 = &temp6; res6 = SWIG_AddTmpMask(ecode); } ecode7 = SWIG_AsVal_double(obj6, &val7); if (!SWIG_IsOK(ecode7)) { SWIG_exception_fail(SWIG_ArgError(ecode7), "in method '" "wcscon" "', argument " "7"" of type '" "double""'"); } arg7 = (double)(val7); wcscon(arg1,arg2,arg3,arg4,arg5,arg6,arg7); resultobj = SWIG_Py_Void(); if (SWIG_IsTmpObj(res5)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg5))); } else { int new_flags = SWIG_IsNewObj(res5) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg5), SWIGTYPE_p_double, new_flags)); } if (SWIG_IsTmpObj(res6)) { resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_From_double((*arg6))); } else { int new_flags = SWIG_IsNewObj(res6) ? (SWIG_POINTER_OWN | 0 ) : 0 ; resultobj = SWIG_Python_AppendOutput(resultobj, SWIG_NewPointerObj((void*)(arg6), SWIGTYPE_p_double, new_flags)); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_wcscsys(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; char *arg1 = (char *) 0 ; int res1 ; char *buf1 = 0 ; int alloc1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:wcscsys",&obj0)) SWIG_fail; res1 = SWIG_AsCharPtrAndSize(obj0, &buf1, NULL, &alloc1); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "wcscsys" "', argument " "1"" of type '" "char *""'"); } arg1 = (char *)(buf1); result = (int)wcscsys(arg1); resultobj = SWIG_From_int((int)(result)); if (alloc1 == SWIG_NEWOBJ) free((char*)buf1); return resultobj; fail: if (alloc1 == SWIG_NEWOBJ) free((char*)buf1); return NULL; } static PyMethodDef SwigMethods[] = { { (char *)"SWIG_PyInstanceMethod_New", (PyCFunction)SWIG_PyInstanceMethod_New, METH_O, NULL}, { (char *)"wcscon", _wrap_wcscon, METH_VARARGS, (char *)"wcscon(sys1, sys2, eq1, eq2, INOUT, INOUT, epoch)"}, { (char *)"wcscsys", _wrap_wcscsys, METH_VARARGS, (char *)"wcscsys(wcstring) -> int"}, { NULL, NULL, 0, NULL } }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_double = {"_p_double", "double *", 0, 0, (void*)0, 0}; static swig_type_info *swig_type_initial[] = { &_swigt__p_char, &_swigt__p_double, }; static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_double[] = { {&_swigt__p_double, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { _swigc__p_char, _swigc__p_double, }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ static swig_const_info swig_const_table[] = { {0, 0, 0, 0.0, 0, 0}}; #ifdef __cplusplus } #endif /* ----------------------------------------------------------------------------- * Type initialization: * This problem is tough by the requirement that no dynamic * memory is used. Also, since swig_type_info structures store pointers to * swig_cast_info structures and swig_cast_info structures store pointers back * to swig_type_info structures, we need some lookup code at initialization. * The idea is that swig generates all the structures that are needed. * The runtime then collects these partially filled structures. * The SWIG_InitializeModule function takes these initial arrays out of * swig_module, and does all the lookup, filling in the swig_module.types * array with the correct data and linking the correct swig_cast_info * structures together. * * The generated swig_type_info structures are assigned staticly to an initial * array. We just loop through that array, and handle each type individually. * First we lookup if this type has been already loaded, and if so, use the * loaded structure instead of the generated one. Then we have to fill in the * cast linked list. The cast data is initially stored in something like a * two-dimensional array. Each row corresponds to a type (there are the same * number of rows as there are in the swig_type_initial array). Each entry in * a column is one of the swig_cast_info structures for that type. * The cast_initial array is actually an array of arrays, because each row has * a variable number of columns. So to actually build the cast linked list, * we find the array of casts associated with the type, and loop through it * adding the casts to the list. The one last trick we need to do is making * sure the type pointer in the swig_cast_info struct is correct. * * First off, we lookup the cast->type name to see if it is already loaded. * There are three cases to handle: * 1) If the cast->type has already been loaded AND the type we are adding * casting info to has not been loaded (it is in this module), THEN we * replace the cast->type pointer with the type pointer that has already * been loaded. * 2) If BOTH types (the one we are adding casting info to, and the * cast->type) are loaded, THEN the cast info has already been loaded by * the previous module so we just ignore it. * 3) Finally, if cast->type has not already been loaded, then we add that * swig_cast_info to the linked list (because the cast->type) pointer will * be correct. * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #if 0 } /* c-mode */ #endif #endif #if 0 #define SWIGRUNTIME_DEBUG #endif SWIGRUNTIME void SWIG_InitializeModule(void *clientdata) { size_t i; swig_module_info *module_head, *iter; int found, init; /* check to see if the circular list has been setup, if not, set it up */ if (swig_module.next==0) { /* Initialize the swig_module */ swig_module.type_initial = swig_type_initial; swig_module.cast_initial = swig_cast_initial; swig_module.next = &swig_module; init = 1; } else { init = 0; } /* Try and load any already created modules */ module_head = SWIG_GetModule(clientdata); if (!module_head) { /* This is the first module loaded for this interpreter */ /* so set the swig module into the interpreter */ SWIG_SetModule(clientdata, &swig_module); module_head = &swig_module; } else { /* the interpreter has loaded a SWIG module, but has it loaded this one? */ found=0; iter=module_head; do { if (iter==&swig_module) { found=1; break; } iter=iter->next; } while (iter!= module_head); /* if the is found in the list, then all is done and we may leave */ if (found) return; /* otherwise we must add out module into the list */ swig_module.next = module_head->next; module_head->next = &swig_module; } /* When multiple interpreters are used, a module could have already been initialized in a different interpreter, but not yet have a pointer in this interpreter. In this case, we do not want to continue adding types... everything should be set up already */ if (init == 0) return; /* Now work on filling in swig_module.types */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: size %d\n", swig_module.size); #endif for (i = 0; i < swig_module.size; ++i) { swig_type_info *type = 0; swig_type_info *ret; swig_cast_info *cast; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); #endif /* if there is another module already loaded */ if (swig_module.next != &swig_module) { type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); } if (type) { /* Overwrite clientdata field */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found type %s\n", type->name); #endif if (swig_module.type_initial[i]->clientdata) { type->clientdata = swig_module.type_initial[i]->clientdata; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); #endif } } else { type = swig_module.type_initial[i]; } /* Insert casting types */ cast = swig_module.cast_initial[i]; while (cast->type) { /* Don't need to add information already in the list */ ret = 0; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); #endif if (swig_module.next != &swig_module) { ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); #ifdef SWIGRUNTIME_DEBUG if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); #endif } if (ret) { if (type == swig_module.type_initial[i]) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: skip old type %s\n", ret->name); #endif cast->type = ret; ret = 0; } else { /* Check for casting already in the list */ swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); #ifdef SWIGRUNTIME_DEBUG if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); #endif if (!ocast) ret = 0; } } if (!ret) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); #endif if (type->cast) { type->cast->prev = cast; cast->next = type->cast; } type->cast = cast; } cast++; } /* Set entry in modules->types array equal to the type */ swig_module.types[i] = type; } swig_module.types[i] = 0; #ifdef SWIGRUNTIME_DEBUG printf("**** SWIG_InitializeModule: Cast List ******\n"); for (i = 0; i < swig_module.size; ++i) { int j = 0; swig_cast_info *cast = swig_module.cast_initial[i]; printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); while (cast->type) { printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); cast++; ++j; } printf("---- Total casts: %d\n",j); } printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif } /* This function will propagate the clientdata field of type to * any new swig_type_info structures that have been added into the list * of equivalent types. It is like calling * SWIG_TypeClientData(type, clientdata) a second time. */ SWIGRUNTIME void SWIG_PropagateClientData(void) { size_t i; swig_cast_info *equiv; static int init_run = 0; if (init_run) return; init_run = 1; for (i = 0; i < swig_module.size; i++) { if (swig_module.types[i]->clientdata) { equiv = swig_module.types[i]->cast; while (equiv) { if (!equiv->converter) { if (equiv->type && !equiv->type->clientdata) SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); } equiv = equiv->next; } } } } #ifdef __cplusplus #if 0 { /* c-mode */ #endif } #endif #ifdef __cplusplus extern "C" { #endif /* Python-specific SWIG API */ #define SWIG_newvarlink() SWIG_Python_newvarlink() #define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr) #define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants) /* ----------------------------------------------------------------------------- * global variable support code. * ----------------------------------------------------------------------------- */ typedef struct swig_globalvar { char *name; /* Name of global variable */ PyObject *(*get_attr)(void); /* Return the current value */ int (*set_attr)(PyObject *); /* Set the value */ struct swig_globalvar *next; } swig_globalvar; typedef struct swig_varlinkobject { PyObject_HEAD swig_globalvar *vars; } swig_varlinkobject; SWIGINTERN PyObject * swig_varlink_repr(swig_varlinkobject *SWIGUNUSEDPARM(v)) { #if PY_VERSION_HEX >= 0x03000000 return PyUnicode_InternFromString(""); #else return PyString_FromString(""); #endif } SWIGINTERN PyObject * swig_varlink_str(swig_varlinkobject *v) { #if PY_VERSION_HEX >= 0x03000000 PyObject *str = PyUnicode_InternFromString("("); PyObject *tail; PyObject *joined; swig_globalvar *var; for (var = v->vars; var; var=var->next) { tail = PyUnicode_FromString(var->name); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; if (var->next) { tail = PyUnicode_InternFromString(", "); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; } } tail = PyUnicode_InternFromString(")"); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; #else PyObject *str = PyString_FromString("("); swig_globalvar *var; for (var = v->vars; var; var=var->next) { PyString_ConcatAndDel(&str,PyString_FromString(var->name)); if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", ")); } PyString_ConcatAndDel(&str,PyString_FromString(")")); #endif return str; } SWIGINTERN int swig_varlink_print(swig_varlinkobject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { char *tmp; PyObject *str = swig_varlink_str(v); fprintf(fp,"Swig global variables "); fprintf(fp,"%s\n", tmp = SWIG_Python_str_AsChar(str)); SWIG_Python_str_DelForPy3(tmp); Py_DECREF(str); return 0; } SWIGINTERN void swig_varlink_dealloc(swig_varlinkobject *v) { swig_globalvar *var = v->vars; while (var) { swig_globalvar *n = var->next; free(var->name); free(var); var = n; } } SWIGINTERN PyObject * swig_varlink_getattr(swig_varlinkobject *v, char *n) { PyObject *res = NULL; swig_globalvar *var = v->vars; while (var) { if (strcmp(var->name,n) == 0) { res = (*var->get_attr)(); break; } var = var->next; } if (res == NULL && !PyErr_Occurred()) { PyErr_SetString(PyExc_NameError,"Unknown C global variable"); } return res; } SWIGINTERN int swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) { int res = 1; swig_globalvar *var = v->vars; while (var) { if (strcmp(var->name,n) == 0) { res = (*var->set_attr)(p); break; } var = var->next; } if (res == 1 && !PyErr_Occurred()) { PyErr_SetString(PyExc_NameError,"Unknown C global variable"); } return res; } SWIGINTERN PyTypeObject* swig_varlink_type(void) { static char varlink__doc__[] = "Swig var link object"; static PyTypeObject varlink_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { /* PyObject header changed in Python 3 */ #if PY_VERSION_HEX >= 0x03000000 PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif (char *)"swigvarlink", /* tp_name */ sizeof(swig_varlinkobject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor) swig_varlink_dealloc, /* tp_dealloc */ (printfunc) swig_varlink_print, /* tp_print */ (getattrfunc) swig_varlink_getattr, /* tp_getattr */ (setattrfunc) swig_varlink_setattr, /* tp_setattr */ 0, /* tp_compare */ (reprfunc) swig_varlink_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc) swig_varlink_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ varlink__doc__, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #if PY_VERSION_HEX >= 0x02060000 0, /* tp_version */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; varlink_type = tmp; type_init = 1; #if PY_VERSION_HEX < 0x02020000 varlink_type.ob_type = &PyType_Type; #else if (PyType_Ready(&varlink_type) < 0) return NULL; #endif } return &varlink_type; } /* Create a variable linking object for use later */ SWIGINTERN PyObject * SWIG_Python_newvarlink(void) { swig_varlinkobject *result = PyObject_NEW(swig_varlinkobject, swig_varlink_type()); if (result) { result->vars = 0; } return ((PyObject*) result); } SWIGINTERN void SWIG_Python_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) { swig_varlinkobject *v = (swig_varlinkobject *) p; swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); if (gv) { size_t size = strlen(name)+1; gv->name = (char *)malloc(size); if (gv->name) { strncpy(gv->name,name,size); gv->get_attr = get_attr; gv->set_attr = set_attr; gv->next = v->vars; } } v->vars = gv; } SWIGINTERN PyObject * SWIG_globals(void) { static PyObject *_SWIG_globals = 0; if (!_SWIG_globals) _SWIG_globals = SWIG_newvarlink(); return _SWIG_globals; } /* ----------------------------------------------------------------------------- * constants/methods manipulation * ----------------------------------------------------------------------------- */ /* Install Constants */ SWIGINTERN void SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { PyObject *obj = 0; size_t i; for (i = 0; constants[i].type; ++i) { switch(constants[i].type) { case SWIG_PY_POINTER: obj = SWIG_InternalNewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0); break; case SWIG_PY_BINARY: obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); break; default: obj = 0; break; } if (obj) { PyDict_SetItemString(d, constants[i].name, obj); Py_DECREF(obj); } } } /* -----------------------------------------------------------------------------*/ /* Fix SwigMethods to carry the callback ptrs when needed */ /* -----------------------------------------------------------------------------*/ SWIGINTERN void SWIG_Python_FixMethods(PyMethodDef *methods, swig_const_info *const_table, swig_type_info **types, swig_type_info **types_initial) { size_t i; for (i = 0; methods[i].ml_name; ++i) { const char *c = methods[i].ml_doc; if (c && (c = strstr(c, "swig_ptr: "))) { int j; swig_const_info *ci = 0; const char *name = c + 10; for (j = 0; const_table[j].type; ++j) { if (strncmp(const_table[j].name, name, strlen(const_table[j].name)) == 0) { ci = &(const_table[j]); break; } } if (ci) { void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; if (ptr) { size_t shift = (ci->ptype) - types; swig_type_info *ty = types_initial[shift]; size_t ldoc = (c - methods[i].ml_doc); size_t lptr = strlen(ty->name)+2*sizeof(void*)+2; char *ndoc = (char*)malloc(ldoc + lptr + 10); if (ndoc) { char *buff = ndoc; strncpy(buff, methods[i].ml_doc, ldoc); buff += ldoc; strncpy(buff, "swig_ptr: ", 10); buff += 10; SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); methods[i].ml_doc = ndoc; } } } } } } #ifdef __cplusplus } #endif /* -----------------------------------------------------------------------------* * Partial Init method * -----------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" #endif SWIGEXPORT #if PY_VERSION_HEX >= 0x03000000 PyObject* #else void #endif SWIG_init(void) { PyObject *m, *d, *md; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef SWIG_module = { # if PY_VERSION_HEX >= 0x03020000 PyModuleDef_HEAD_INIT, # else { PyObject_HEAD_INIT(NULL) NULL, /* m_init */ 0, /* m_index */ NULL, /* m_copy */ }, # endif (char *) SWIG_name, NULL, -1, SwigMethods, NULL, NULL, NULL, NULL }; #endif #if defined(SWIGPYTHON_BUILTIN) static SwigPyClientData SwigPyObject_clientdata = { 0, 0, 0, 0, 0, 0, 0 }; static PyGetSetDef this_getset_def = { (char *)"this", &SwigPyBuiltin_ThisClosure, NULL, NULL, NULL }; static SwigPyGetSet thisown_getset_closure = { (PyCFunction) SwigPyObject_own, (PyCFunction) SwigPyObject_own }; static PyGetSetDef thisown_getset_def = { (char *)"thisown", SwigPyBuiltin_GetterClosure, SwigPyBuiltin_SetterClosure, NULL, &thisown_getset_closure }; PyObject *metatype_args; PyTypeObject *builtin_pytype; int builtin_base_count; swig_type_info *builtin_basetype; PyObject *tuple; PyGetSetDescrObject *static_getset; PyTypeObject *metatype; SwigPyClientData *cd; PyObject *public_interface, *public_symbol; PyObject *this_descr; PyObject *thisown_descr; int i; (void)builtin_pytype; (void)builtin_base_count; (void)builtin_basetype; (void)tuple; (void)static_getset; /* metatype is used to implement static member variables. */ metatype_args = Py_BuildValue("(s(O){})", "SwigPyObjectType", &PyType_Type); assert(metatype_args); metatype = (PyTypeObject *) PyType_Type.tp_call((PyObject *) &PyType_Type, metatype_args, NULL); assert(metatype); Py_DECREF(metatype_args); metatype->tp_setattro = (setattrofunc) &SwigPyObjectType_setattro; assert(PyType_Ready(metatype) >= 0); #endif /* Fix SwigMethods to carry the callback ptrs when needed */ SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); #if PY_VERSION_HEX >= 0x03000000 m = PyModule_Create(&SWIG_module); #else m = Py_InitModule((char *) SWIG_name, SwigMethods); #endif md = d = PyModule_GetDict(m); (void)md; SWIG_InitializeModule(0); #ifdef SWIGPYTHON_BUILTIN SwigPyObject_stype = SWIG_MangledTypeQuery("_p_SwigPyObject"); assert(SwigPyObject_stype); cd = (SwigPyClientData*) SwigPyObject_stype->clientdata; if (!cd) { SwigPyObject_stype->clientdata = &SwigPyObject_clientdata; SwigPyObject_clientdata.pytype = SwigPyObject_TypeOnce(); } else if (SwigPyObject_TypeOnce()->tp_basicsize != cd->pytype->tp_basicsize) { PyErr_SetString(PyExc_RuntimeError, "Import error: attempted to load two incompatible swig-generated modules."); # if PY_VERSION_HEX >= 0x03000000 return NULL; # else return; # endif } /* All objects have a 'this' attribute */ this_descr = PyDescr_NewGetSet(SwigPyObject_type(), &this_getset_def); (void)this_descr; /* All objects have a 'thisown' attribute */ thisown_descr = PyDescr_NewGetSet(SwigPyObject_type(), &thisown_getset_def); (void)thisown_descr; public_interface = PyList_New(0); public_symbol = 0; (void)public_symbol; PyDict_SetItemString(md, "__all__", public_interface); Py_DECREF(public_interface); for (i = 0; SwigMethods[i].ml_name != NULL; ++i) SwigPyBuiltin_AddPublicSymbol(public_interface, SwigMethods[i].ml_name); for (i = 0; swig_const_table[i].name != 0; ++i) SwigPyBuiltin_AddPublicSymbol(public_interface, swig_const_table[i].name); #endif SWIG_InstallConstants(d,swig_const_table); #if PY_VERSION_HEX >= 0x03000000 return m; #else return; #endif } astLib-0.10.0/PyWCSTools/wcssubs-3.9.0/poly.c0000664000175000017500000005467513047255533020631 0ustar mattymatty00000000000000 /* poly.c *%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% * * Part of: A program using Polynomials * * Author: E.BERTIN (IAP) * * Contents: Polynomial fitting * * Last modify: 08/03/2005 * *%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #include "wcslib.h" #define QCALLOC(ptr, typ, nel) \ {if (!(ptr = (typ *)calloc((size_t)(nel),sizeof(typ)))) \ qerror("Not enough memory for ", \ #ptr " (" #nel " elements) !");;} #define QMALLOC(ptr, typ, nel) \ {if (!(ptr = (typ *)malloc((size_t)(nel)*sizeof(typ)))) \ qerror("Not enough memory for ", \ #ptr " (" #nel " elements) !");;} /********************************* qerror ************************************/ /* I hope it will never be used! */ void qerror(char *msg1, char *msg2) { fprintf(stderr, "\n> %s%s\n\n",msg1,msg2); exit(-1); } /****** poly_init ************************************************************ PROTO polystruct *poly_init(int *group, int ndim, int *degree, int ngroup) PURPOSE Allocate and initialize a polynom structure. INPUT 1D array containing the group for each parameter, number of dimensions (parameters), 1D array with the polynomial degree for each group, number of groups. OUTPUT polystruct pointer. NOTES -. AUTHOR E. Bertin (IAP) VERSION 08/03/2003 ***/ polystruct *poly_init(int *group, int ndim, int *degree, int ngroup) { void qerror(char *msg1, char *msg2); polystruct *poly; char str[512]; int nd[POLY_MAXDIM]; int *groupt, d,g,n,num,den; QCALLOC(poly, polystruct, 1); if ((poly->ndim=ndim) > POLY_MAXDIM) { sprintf(str, "The dimensionality of the polynom (%d) exceeds the maximum\n" "allowed one (%d)", ndim, POLY_MAXDIM); qerror("*Error*: ", str); } if (ndim) QMALLOC(poly->group, int, poly->ndim); for (groupt=poly->group, d=ndim; d--;) *(groupt++) = *(group++)-1; poly->ngroup = ngroup; if (ngroup) { group = poly->group; /* Forget the original *group */ QMALLOC(poly->degree, int, poly->ngroup); /*-- Compute the number of context parameters for each group */ memset(nd, 0, ngroup*sizeof(int)); for (d=0; d=ngroup) qerror("*Error*: polynomial GROUP out of range", ""); nd[g]++; } } /* Compute the total number of coefficients */ poly->ncoeff = 1; for (g=0; gdegree[g]=*(degree++))>POLY_MAXDEGREE) { sprintf(str, "The degree of the polynom (%d) exceeds the maximum\n" "allowed one (%d)", poly->degree[g], POLY_MAXDEGREE); qerror("*Error*: ", str); } /*-- There are (n+d)!/(n!d!) coeffs per group, that is Prod_(i<=d) (n+i)/i */ for (num=den=1, n=nd[g]; d; num*=(n+d), den*=d--); poly->ncoeff *= num/den; } QMALLOC(poly->basis, double, poly->ncoeff); QCALLOC(poly->coeff, double, poly->ncoeff); return poly; } /****** poly_end ************************************************************* PROTO void poly_end(polystruct *poly) PURPOSE Free a polynom structure and everything it contains. INPUT polystruct pointer. OUTPUT -. NOTES -. AUTHOR E. Bertin (IAP, Leiden observatory & ESO) VERSION 09/04/2000 ***/ void poly_end(polystruct *poly) { if (poly) { free(poly->coeff); free(poly->basis); free(poly->degree); free(poly->group); free(poly); } } /****** poly_func ************************************************************ PROTO double poly_func(polystruct *poly, double *pos) PURPOSE Evaluate a multidimensional polynom. INPUT polystruct pointer, pointer to the 1D array of input vector data. OUTPUT Polynom value. NOTES Values of the basis functions are updated in poly->basis. AUTHOR E. Bertin (IAP) VERSION 03/03/2004 ***/ double poly_func(polystruct *poly, double *pos) { double xpol[POLY_MAXDIM+1]; double *post, *xpolt, *basis, *coeff, xval; long double val; int expo[POLY_MAXDIM+1], gexpo[POLY_MAXDIM+1]; int *expot, *degree,*degreet, *group,*groupt, *gexpot, d,g,t, ndim; /* Prepare the vectors and counters */ ndim = poly->ndim; basis = poly->basis; coeff = poly->coeff; group = poly->group; degree = poly->degree; if (ndim) { for (xpolt=xpol, expot=expo, post=pos, d=ndim; --d;) { *(++xpolt) = 1.0; *(++expot) = 0; } for (gexpot=gexpo, degreet=degree, g=poly->ngroup; g--;) *(gexpot++) = *(degreet++); if (gexpo[*group]) gexpo[*group]--; } /* The constant term is handled separately */ val = *(coeff++); *(basis++) = 1.0; *expo = 1; *xpol = *pos; /* Compute the rest of the polynom */ for (t=poly->ncoeff; --t; ) { /*-- xpol[0] contains the current product of the x^n's */ val += (*(basis++)=*xpol)**(coeff++); /*-- A complex recursion between terms of the polynom speeds up computations */ /*-- Not too good for roundoff errors (prefer Horner's), but much easier for */ /*-- multivariate polynomials: this is why we use a long double accumulator */ post = pos; groupt = group; expot = expo; xpolt = xpol; for (d=0; dncoeff; ndim = poly->ndim; matsize = ncoeff*ncoeff; basis = poly->basis; extbasist = extbasis; QCALLOC(alpha, double, matsize); QCALLOC(beta, double, ncoeff); /* Subtract an average offset to maintain precision (droped for now ) */ /* if (x) { for (d=0; dcoeff; for (j=ncoeff; j--;) *(coeff++) = *(betat++); /* poly_addcste(poly, offset); */ free(beta); return; } /****** poly_addcste ********************************************************* PROTO void poly_addcste(polystruct *poly, double *cste) PURPOSE Modify matrix coefficients to mimick the effect of adding a cst to the input of a polynomial. INPUT Pointer to the polynomial structure, Pointer to the vector of cst. OUTPUT -. NOTES Requires quadruple-precision. **For the time beeing, this function returns completely wrong results!!** AUTHOR E. Bertin (IAP) VERSION 03/03/2004 ***/ void poly_addcste(polystruct *poly, double *cste) { long double *acoeff; double *coeff,*mcoeff,*mcoefft, val; int *mpowers,*powers,*powerst,*powerst2, i,j,n,p, denum, flag, maxdegree, ncoeff, ndim; ncoeff = poly->ncoeff; ndim = poly->ndim; maxdegree = 0; for (j=0; jngroup; j++) if (maxdegree < poly->degree[j]) maxdegree = poly->degree[j]; maxdegree++; /* Actually we need maxdegree+1 terms */ QCALLOC(acoeff, long double, ncoeff); QCALLOC(mcoeff, double, ndim*maxdegree); QCALLOC(mpowers, int, ndim); mcoefft = mcoeff; /* To avoid gcc -Wall warnings */ powerst = powers = poly_powers(poly); coeff = poly->coeff; for (i=0; i