astLib-0.8.0/0000775000175000017500000000000012377541253013266 5ustar mattymatty00000000000000astLib-0.8.0/README0000644000175000017500000001421512375447230014145 0ustar mattymatty00000000000000astLib: python astronomy modules version: 0.8.0 (c) 2007-2012 Matt Hilton (c) 2013-2014 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. As such, the astStats module is unlikely to be extended beyond its present state due to the extensive statistical routines provided by scipy (I also recommend the Python bindings for GNU R - http://rpy.sourceforge.net). Some scripts using astLib can be found in the examples/ folder in this archive. ------------------------------------------------------------------------------------------------------------- INSTALLATION astLib 0.8.0 requires: * Python (tested on versions 2.7.6 and 3.4.0) * PyFITS - http://www.stsci.edu/resources/software_hardware/pyfits (tested on version 3.3) * numpy - http://numpy.scipy.org (tested on version 1.8.1) * scipy - http://scipy.org (tested on version 0.13.3) * matplotlib - http://matplotlib.sourceforge.net (tested on versions 1.3.1) optional: * Python Imaging Library - http://www.pythonware.com/products/pil (tested on version 1.1.7) * astropy - http://www.astropy.org/ (tested on 0.4) This is currently only used if pyfits is not installed (astropy.io.fits at present provides a drop-in replacement for pyfits). 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 Kubuntu 14.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.5/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.8.0/setup.py0000644000175000017500000001014012375455346014777 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.8.7"+os.path.sep #oFiles=glob.glob(sourceDir+"*.o") #print oFiles oFiles = ['PyWCSTools/wcssubs-3.8.7/cel.o', 'PyWCSTools/wcssubs-3.8.7/wcs.o', 'PyWCSTools/wcssubs-3.8.7/proj.o', 'PyWCSTools/wcssubs-3.8.7/distort.o', 'PyWCSTools/wcssubs-3.8.7/wcsinit.o', 'PyWCSTools/wcssubs-3.8.7/wcslib.o', 'PyWCSTools/wcssubs-3.8.7/poly.o', 'PyWCSTools/wcssubs-3.8.7/platepos.o', 'PyWCSTools/wcssubs-3.8.7/zpxpos.o', 'PyWCSTools/wcssubs-3.8.7/iget.o', 'PyWCSTools/wcssubs-3.8.7/imio.o', 'PyWCSTools/wcssubs-3.8.7/dsspos.o', 'PyWCSTools/wcssubs-3.8.7/tnxpos.o', 'PyWCSTools/wcssubs-3.8.7/wcscon.o', 'PyWCSTools/wcssubs-3.8.7/fitsfile.o', 'PyWCSTools/wcssubs-3.8.7/dateutil.o', 'PyWCSTools/wcssubs-3.8.7/imhfile.o', 'PyWCSTools/wcssubs-3.8.7/lin.o', 'PyWCSTools/wcssubs-3.8.7/fileutil.o', 'PyWCSTools/wcssubs-3.8.7/wcstrig.o', 'PyWCSTools/wcssubs-3.8.7/slasubs.o', 'PyWCSTools/wcssubs-3.8.7/sph.o', 'PyWCSTools/wcssubs-3.8.7/worldpos.o', 'PyWCSTools/wcssubs-3.8.7/hget.o', 'PyWCSTools/wcssubs-3.8.7/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.8.7 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.8.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.8.0/docs/0000775000175000017500000000000012377541253014216 5ustar mattymatty00000000000000astLib-0.8.0/docs/astLib/0000775000175000017500000000000012377541253015434 5ustar mattymatty00000000000000astLib-0.8.0/docs/astLib/astLib.astWCS-pysrc.html0000644000175000017500000033041712375434532022046 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.8.0/docs/astLib/astLib.astPlots-pysrc.html0000644000175000017500000117435412375434532022522 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.8.0/docs/astLib/toc-astLib-module.html0000644000175000017500000000214212375434532021602 0ustar mattymatty00000000000000 astLib

Module astLib


Variables

__package__

[hide private] astLib-0.8.0/docs/astLib/astLib.astStats-pysrc.html0000644000175000017500000054463512375434532022521 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.8.0/docs/astLib/astLib.astCoords-pysrc.html0000644000175000017500000030016212375434532022635 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.8.0/docs/astLib/index.html0000644000175000017500000000111412375434532017423 0ustar mattymatty00000000000000 API Documentation astLib-0.8.0/docs/astLib/epydoc.js0000644000175000017500000002452512375434532017262 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.8.0/docs/astLib/astLib.astSED.TopHatPassband-class.html0000664000175000017500000002061712375434532024644 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.8.0/docs/astLib/astLib.astImages-module.html0000644000175000017500000015115412375434532022743 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.8.0/docs/astLib/frames.html0000644000175000017500000000111412375434532017571 0ustar mattymatty00000000000000 API Documentation astLib-0.8.0/docs/astLib/astLib.astWCS.WCS-class.html0000644000175000017500000010274512375434532022447 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.8.0/docs/astLib/module-tree.html0000644000175000017500000001162012375434532020541 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.8.0/docs/astLib/astLib.astCalc-module.html0000644000175000017500000012376512375434532022407 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.8.0/docs/astLib/astLib.astSED.StellarPopulation-class.html0000664000175000017500000005172712375434532025460 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.8.0/docs/astLib/astLib-pysrc.html0000644000175000017500000001365112375434532020701 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.8.0/docs/astLib/help.html0000644000175000017500000002472712375434532017263 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:

  • A description of the package.
  • A list of the modules and sub-packages contained by the package.
  • A summary of the classes defined by the package.
  • A summary of the functions defined by the package.
  • A summary of the variables defined by the package.
  • A detailed description of each function defined by the package.
  • A detailed description of each variable defined by the package.

Each Module Documentation page contains:

  • A description of the module.
  • A summary of the classes defined by the module.
  • A summary of the functions defined by the module.
  • A summary of the variables defined by the module.
  • A detailed description of each function defined by the module.
  • A detailed description of each variable defined by the module.

Each Class Documentation page contains:

  • A class inheritance diagram.
  • A list of known subclasses.
  • A description of the class.
  • A summary of the methods defined by the class.
  • A summary of the instance variables defined by the class.
  • A summary of the class (static) variables defined by the class.
  • A detailed description of each method defined by the class.
  • A detailed description of each instance variable defined by the class.
  • A detailed description of each class (static) variable defined by the class.

Project Documentation

The Trees page contains the module and class hierarchies:

  • The module hierarchy lists every package and module, with modules grouped into packages. At the top level, and within each package, modules and sub-packages are listed alphabetically.
  • The class hierarchy lists every class, grouped by base class. If a class has more than one base class, then it will be listed under each base class. At the top level, and under each base class, classes are listed alphabetically.

The Index page contains indices of terms and identifiers:

  • The term index lists every term indexed by any object's documentation. For each term, the index provides links to each place where the term is indexed.
  • The identifier index lists the (short) name of every package, module, class, method, function, variable, and parameter. For each identifier, the index provides a short description, and a link to its documentation.

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.8.0/docs/astLib/class-tree.html0000644000175000017500000001414012375434532020361 0ustar mattymatty00000000000000 Class Hierarchy
 
[hide private]
[frames] | no frames]
[ Module Hierarchy | Class Hierarchy ]

Class Hierarchy

  • astLib.astPlots.ImagePlot: This class describes a matplotlib image plot containing an astronomical image with an associated WCS.
  • astLib.astSED.Passband: This class describes a filter transmission curve.
  • astLib.astSED.SED: This class describes a Spectral Energy Distribution (SED).
    • astLib.astSED.VegaSED: This class stores the SED of Vega, used for calculation of magnitudes on the Vega system.
  • astLib.astSED.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.
    • astLib.astSED.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.
    • astLib.astSED.M05Model: This class describes a Maraston 2005 stellar population model.
    • astLib.astSED.P09Model: This class describes a Percival et al 2009 (BaSTI; http://albione.oa-teramo.inaf.it) stellar population model.
  • astLib.astWCS.WCS: This class provides methods for accessing information from the World Coordinate System (WCS) contained in the header of a FITS image.
astLib-0.8.0/docs/astLib/astLib.astSED.M05Model-class.html0000664000175000017500000002120212375434532023302 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.8.0/docs/astLib/astLib.astWCS-module.html0000644000175000017500000002717512375434532022177 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.8.0/docs/astLib/toc-astLib.astPlots-module.html0000644000175000017500000000345712375434532023424 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.8.0/docs/astLib/astLib.astPlots-module.html0000644000175000017500000003756612375434532022651 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.8.0/docs/astLib/epydoc.css0000644000175000017500000003722712375434532017441 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.8.0/docs/astLib/astLib.astStats-module.html0000644000175000017500000013720612375434532022636 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.8.0/docs/astLib/toc-astLib.astStats-module.html0000644000175000017500000000625512375434532023420 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.8.0/docs/astLib/toc-everything.html0000644000175000017500000003057412375434532021277 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.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.8.0/docs/astLib/astLib.astSED.Passband-class.html0000664000175000017500000003532512375434532023526 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.8.0/docs/astLib/astLib.astSED.P09Model-class.html0000664000175000017500000001744112375434532023323 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.8.0/docs/astLib/astLib.astSED.SED-class.html0000664000175000017500000012033312375434532022400 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.8.0/docs/astLib/astLib.astImages-pysrc.html0000644000175000017500000111337312375434532022620 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.8.0/docs/astLib/astLib.astCalc-pysrc.html0000644000175000017500000035306712375434532022262 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.8.0/docs/astLib/astLib.astSED-pysrc.html0000664000175000017500000121524612375434532022032 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.8.0/docs/astLib/toc-astLib.astWCS-module.html0000644000175000017500000000262512375434532022753 0ustar mattymatty00000000000000 astWCS

Module astWCS


Classes

WCS

Functions

findWCSOverlap

Variables

NUMPY_MODE
lconv

[hide private] astLib-0.8.0/docs/astLib/astLib.astSED.VegaSED-class.html0000664000175000017500000002100712375434532023201 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.8.0/docs/astLib/astLib.astSED-module.html0000664000175000017500000007721712375434532022162 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.8.0/docs/astLib/toc-astLib.astImages-module.html0000644000175000017500000000521412375434532023521 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.8.0/docs/astLib/identifier-index.html0000644000175000017500000013276712375434532021566 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.8.0/docs/astLib/astLib-module.html0000644000175000017500000001572012375434532021025 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.8.0/docs/astLib/astLib.astCoords-module.html0000644000175000017500000005656512375434532023001 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.8.0/docs/astLib/toc-astLib.astSED-module.html0000664000175000017500000000541212375434532022731 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.8.0/docs/astLib/api-objects.txt0000644000175000017500000003374412375434532020405 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.8.0/docs/astLib/toc.html0000644000175000017500000000476412375434532017117 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.8.0/docs/astLib/astLib.astPlots.ImagePlot-class.html0000664000175000017500000012207612375434532024342 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.8.0/docs/astLib/toc-astLib.astCalc-module.html0000644000175000017500000000635312375434532023163 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.8.0/docs/astLib/astLib.astSED.BC03Model-class.html0000664000175000017500000002047612375434532023404 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.8.0/docs/astLib/redirect.html0000644000175000017500000000262612375434532020126 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.8.0/docs/astLib/toc-astLib.astCoords-module.html0000644000175000017500000000345012375434532023545 0ustar mattymatty00000000000000 astCoords

Module astCoords


Functions

calcAngSepDeg
calcRADecSearchBox
convertCoords
decimal2dms
decimal2hms
dms2decimal
hms2decimal
shiftRADec

[hide private] astLib-0.8.0/docs/astLib/crarr.png0000644000175000017500000000052412375434532017251 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.8.0/PyWCSTools/0000775000175000017500000000000012377541253015254 5ustar mattymatty00000000000000astLib-0.8.0/PyWCSTools/wcs.py0000644000175000017500000006372312264477570016440 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.8.0/PyWCSTools/__init__.py0000644000175000017500000000032012264477570017363 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.8.0/PyWCSTools/wcscon.py0000644000175000017500000000445112264477570017131 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.8.0/PyWCSTools/wcssubs-3.8.7/0000775000175000017500000000000012377541253017420 5ustar mattymatty00000000000000astLib-0.8.0/PyWCSTools/wcssubs-3.8.7/wcscon_wrap.c0000664000175000017500000034645612375433416022132 0ustar mattymatty00000000000000/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.11 * * 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 0x020011 #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.8.0/PyWCSTools/wcssubs-3.8.7/poly.c0000664000175000017500000005467512375432743020571 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