Contents:
A collection of tools, tips, and tricks.
2009-07-20 22:36 IJC: Created
2010-10-28 11:53 IJMC: Updated documentation for Sphinx.
2011-06-15 09:34 IJMC: More functions have been added; cleaned documentation.
Return the total (astronomical) magnitude of two combined sources.
INPUTS: |
|
---|
Combine fields in two objects with the same attributes. A handy function!
INPUTS: | obj1, obj2 : objects of the same kind |
---|---|
RETURNS: | obj12 : new object, with fields of 1 and 2 combined.
-1, if the objects have absolutely no attributes in common. |
NOTES: | Methods/attributes beginning with an underscore (_) are not combined. |
Return overlapping area of two circles. From Wolfram Mathworld.
r1, r2 are the radii of the circles.
d is the distance between their centers.
If input is a Numpy array, return it. If it is of type str, use Pyfits to read in the file and return it. Keyword options are available for the calls to pyfits.getdata and numpy.array. If input is None, return noneoutput.
Planck function in wavelength.
INPUTS: |
|
---|
Value returned is in (nearly) cgs units: erg/s/cm^2/micron/sr
Planck function in frequency.
INPUTS: |
|
---|
Value returned is in cgs units: erg/s/cm^2/Hz/sr
Return all possible combinations of the elements in an input sequence. The last returned element will be the empty list.
E.g., combinations([0,1]) returns [[0, 1], [0], [1], []]
Requirements: | copy |
---|
Plot filled contours of irregularly-spaced data. :USAGE:
First three inputs must use syntax ‘contour(X,Y,Z)’.
Can set “nbinx=50” or “nbiny=50” for number of bins.
Otherwise, syntax is the same as for matplotlib’s ‘contourf’.
EXAMPLE: | import tools
import numpy as np
|
---|---|
SEE_ALSO: |
Copy axis limits from one axes to another.
INPUTS: | a1, a2 – either (1) handles to axes objects, or (2) figure numbers. If figures have subplots, you can refer to a particular subplot using decimal notation. So, 1.3 would refer to subplot 3 of figure 1. |
---|---|
REQUIREMENTS: | matplotlib (when this is written...) |
Compute the Discrete Correlation Function for unevenly sampled data.
If your data are evenly sampled, just use numpy.correlate()!
INPUTS: | t – (1D sequence) - time sampling of input data. x, y – (1D sequences) - input data. Note that t, x, y should all have the same lengths! |
---|---|
OPTIONAL INPUT: | zerolag – (bool) - whether to compute DCF for zero-lag datapoints. nbin – (int) - number of computed correlation/lag values to average over
reterr – bool - False or True |
RETURNS: | meanlags – average lag in each averaged bin rdcf – DCF value in each averaged bin rdcf_err – uncertainty in the DCF value for each averaged bin |
SEE ALSO: | numpy.correlate() |
REQUIREMENTS: | Numerical analysis routines, numpy |
Take an input Dict, and turn it into an object with fields corresponding to the dict’s keys.
SEE_ALSO: | :func:obj2dict` |
---|
Draw a circular patch on the current, or specified, axes.
INPUT: | x, y – center of circle radius – radius of circle |
---|---|
OPTIONAL INPUT: | ax – Axis to draw upon. if None, defaults to current axes. dodraw – if True, call ‘draw()’ function to immediately re-draw axes. **kw – options passable to matplotlib.patches.Circle() |
NOTE: | Axes will NOT auto-rescale after this is called. |
Draw an elliptical patch on the current, or specified, axes.
INPUT: | x, y – center of ellipse width – width of ellipse height – width of ellipse |
---|---|
OPTIONAL INPUT: | ax – Axis to draw upon. if None, defaults to current axes. dodraw – if True, call ‘draw()’ function to immediately re-draw axes.
|
NOTE: | Axes will NOT auto-rescale after this is called. |
SEE_ALSO: |
Draw a rectangle patch on the current, or specified, axes.
INPUT: | xy – numpy array of coordinates, with shape Nx2. |
---|---|
OPTIONAL INPUT: | ax – Axis to draw upon. if None, defaults to current axes. dodraw – if True, call ‘draw()’ function to immediately re-draw axes. **kw – options passable to matplotlib.patches.Polygon() |
SEE ALSO: | |
NOTE: | Axes will NOT auto-rescale after this is called. |
Draw a rectangle patch on the current, or specified, axes.
INPUT: | x, y – lower-left corner of rectangle width, height – dimensions of rectangle |
||
---|---|---|---|
OPTIONAL INPUT: |
|
%% Determine the diameter in pixels for a given Encircled Energy % % [d, ee] = ee_psf(psf, energy) % [d, ee] = ee_psf(psf, energy, center); % % INPUTS: psf - array representing a point spread function % energy- encircled energy percentage (default = 0.8). % Can also be a vector of values, in which case the % outputs ‘d’ and ‘encircledenergy’ are also vectors. % OPTIONAL INPUT: % center- [x y] coordinates of the center of the psf. If not % passed, defaults to the coordinates of the maximum- % valued point of the psf array. % % OUTPUTS: d - diameter of circle enclosing ‘energy’ [pix] at the % corresponding desired encircled energy value % ee - encircled energy at computed ‘d’ at the % corresponding desired encircled energy value %function [d, encircledenergy] = ee_psf(psf, energy, center)
Weideman 1994’s approximate complex error function.
INPUTS: | z : real or complex float N : number of terms to use. |
---|---|
NOTES: | returns w(z) = exp(-z**2) erfc(-1j*z) |
Bin down datasets in X and Y for errorbar plotting
INPUTS: | x – (array) independent variable data y – (array) dependent variable data
|
---|---|
OPTIONAL INPUT: |
|
OUTPUTS: | a tuple of four arrays to be passed to matplotlib.pyplot.errorbar: xx – locations of the aggregated x-datapoint in each bin yy – locations of the aggregated y-datapoint in each bin xerr – x-errorbars yerr – y-errorbars |
EXAMPLE: | x = hstack((arange(10), arange(20)+40))
y = randn(len(x))
xbins = [-1,15,70]
xx,yy,xerr,yerr = errxy(x,y,xbins)
plot(x,y, '.b')
errorbar(xx,yy,xerr=xerr,yerr=yerr, fmt='or')
|
NOTES: |
|
SEE ALSO: | matplotlib.pyplot.errorbar, analysis.removeoutliers() |
REQUIREMENTS: | numpy, Numerical analysis routines |
Compute the Cardelli et al. 1989 A_lam/A_V extinction (reddening).
INTPUTS: |
|
---|---|
OUTPUTS: |
|
NOTES: | This is only valid for wavelengths in the range 0.3 - 3.3 microns! |
Extract a specified rectangular subregion from a FITS file.
INPUTS: |
|
---|---|
OUTPUTS: | (subregion_data, [fitsfile_header, corners_used]) If the specified header keyword is not found, or the specified corners return an error, then this function will crash inelegantly. |
NOTE: | WCS headers will not be updated, so be careful when using this routine for imaging data! |
Returns the discrete, linear convolution of 1-D sequences a and v, using Fast Fourier Transforms. Restrictions are: a and v must both be real-valued, and len(a)>len(v).
REQUIREMENTS: | Numerical analysis routines, numpy |
---|
Wrapper script for NumPy interpolation. Culls duplicate values and puts x into a monotonically increasing grid.
INPUTS: |
|
---|---|
EXAMPLE: | import numpy as np
x = np.linspace(-3,3,61)
v = np.sin(x)
u = np.array([-2.50, -2.25, -1.85, -1.55, -1.20, -0.85, -0.50, -0.10, 0, 0.75, 0.85, 1.05, 1.45, 1.85, 2.00, 2.25, 2.75 ])
b = feps_interpol(x,v,u)
|
NOTES: | Converted from IDL code from J. Bouwman. Documentation was: ;(SH Feb 26 1999) ;We need to make the grid mononic therefore spline needs to do ;some cleaning before execution |
Helper tool for simply linear interpolation.
INPUTS:
- validValues : sequence
List of valid values
- thisValue : scalar
Value of interest.
OUTPUTS: (TwoClosestValues, relativeFractions)
Find corner coordinates of approximate rectangle shapes in an array.
INPUTS: | a : 2D Numpy array
|
---|
Find all large values in input vector that are separated by at least ‘wid’ pixels.
INPUTS: | vec (sequence) – 1D vector sep (scalar) – minimum separation of returned peaks thresh (scalar) – ignore all peaks lower than this value. |
---|---|
EXAMPLE: | import pylab as py import tools x = py.linspace(0, 10, 100) # Generate fake time index y = py.sin(6.28*x/10.) + py.sin(6.28*x/2.) # Generate fake data peakvals, peaklocs = tools.find_peaks(y, sep=10) # Find the peaks py.plot(x, y, ‘-‘, x[peaklocs], peakvals, ‘or’) # Plot them |
RETURNS: | peakvals, peakindices |
Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables).
OPTIONAL INPUTS: | |
---|---|
|
|
Examples: | >>> [1, 2, [3,4], (5,6)]
[1, 2, [3, 4], (5, 6)]
>>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10)])
[1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]
|
Compute the Gelman-Rubin convergence metric for MCMC chains.
INPUTS: |
|
---|---|
OUTPUTS: | R metric. If this is ‘close to 1.0,’ then your chains have converged to the same distribution. The definition of ‘close’ could be 1.2, 1.1, 1.01... it’s up to you! |
REFERENCE: | Eq. 20 of Gelman & Rubin 1992, Statistical Sciences, Vol. 7, p. 457 |
Get starting positions for EmCee walkers.
INPUTS: |
|
---|
Return a list of filenames meeting certain criteria.
INPUTS: | path – (str) path to directory to be scanned
|
---|
Find confidence levels and optimal parameters.
INPUTS: |
|
---|---|
OUTPUTS: | |
SEE ALSO: | |
REQUIREMENTS: | numpy |
Compute 2-d histogram data for specified bins.
INPUT: | x y |
---|---|
OPTIONAL INPUT: |
|
OUTPUT: |
|
SEE ALSO: | numpy.histogram2d() |
REQUIREMENTS: | numpy |
Take a set of parameters and histogram them. Assume that the larger of the array’s two dimensions is N (the number of instantiations) and the smaller is M (the number of parameters).
Options: | nbins sets the number of bins normed sets the histogram normalization if newfig is False, plot into the current figure. labs is a list of string labels cumulative plots normalized cumulative distribution function minorticks displays minor tick marks
color sets the plotting color. |
---|---|
Requirements: | numpy, pylab |
Rotate a SQUARE image by theta (in radians)
SYNTAX: res = imrot (img, theta)
NOTES: | This is VERY SLOW and only uses nearest-neighbor interpolation. Image must be square; size remains the same |
---|
Compute the delta-chi^2 corresponding to the given parameters.
INPUTS: |
|
||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
RETURNS: | Desired delta-Chi-squared value. |
||||||||||||
EXAMPLE: | # Reproduce Table 1 of Avni (1976)
import tools
dofs = [1, 2, 3, 4]
confs = [0.68, 0.90, 0.99]
for conf in confs:
for dof in dofs:
print ("%5.2f " % tools.invChisq(dof, conf=conf)),
print " "
|
||||||||||||
NOTES: | Some typical values for a Normal (Gaussian) distribution:
|
Create an object based on FITS header keys extracted from a filelist.
Inputs: | filelist – sequence of strings representing filenames (for PyFITS) keys – sequence of strings representing header keys |
---|
#Keys not found in a file will result in the string value
REQUIREMENTS: | pyfits, Spitzer/MIPS 24 micron Analysis Routines |
---|
Color legend text to match linecolor.
Inputs: | ‘leg’ is a legend object.
|
---|
You may need to refresh the figure to see the changes.
Load a pickle from a given filename. If it can’t be loaded by pickle, return -1 – otherwise return the pickled object.
Multiply two functions together.
EXAMPLE: | import numpy as np
multifunc([.785, .785], np.cos, np.sin, 1) # returns cos(pi/4) * sin(pi/4) ~ 0.5
|
---|---|
EXAMPLE: | import pylab as py
import tools
x = 2*py.pi * py.linspace(-5, 5, 500)
y = tools.multifunc([x/8., x], np.sin, np.sin, 1).ravel()
py.plot(x, y)
|
Multiply results of several functions together.
INPUTS: |
|
---|---|
EXAMPLE: | import numpy as np
multifunc_general([.785, .785], (np.cos, np.sin), (1, 1)) # returns cos(pi/4) * sin(pi/4) ~ 0.5
|
EXAMPLE: | import pylab as py
import tools
x = 2*py.pi * py.linspace(-10, 10, 500)
y = tools.multifunc_general([x/8., x], (np.sin, np.sin), (1, 1)).ravel()
py.plot(x, y)
|
Return one greater than the largest-numbered figure currently open. If no figures are open, return unity.
No inputs or options.
Try to convert any generic object into a multi-extension FITS file. We examine each attribute of the object: if a string or scalar, we addit to the Primary HDU header. If a sequence of numbers, we add it as an extension with the appropriate name.
It probably wouldn’t work for heirarchical objects whose attributes are themselves complicated objects; probably also won’t work for complex-valued arrays.
Convert an object into a dict. Ignore functions & methods, and any attributes starting with the ‘ignore’ keys.
SEE_ALSO: | dict2obj() |
---|
Plot cross-correlations between projection of principal components onto data and a model.
INPUTS: |
model – numpy array. Should be shape M.
xl – int. +/- X-limits to display in plots. |
---|---|
Requirements: | pylab, numpy, Phase curve spectroscopic analysis, and associated subroutines. |
Usage is pretty specific to echelle-data
Convert planet/star size and flux contrasts to brightness temperatures.
INPUTS: |
|
---|
Plot x,y data with an evolving z component by changing its color using a matplotlib colormap ‘cm’ object.
Will bomb if z elements are non-finite.
OPTIONS: |
|
---|---|
SEE ALSO: | contourg(), matplotlib.colormaps() |
REQUIREMENTS: | pylab |
Plot correlation coefficient matrix in one big, huge, honkin’ figure. Color-code the figure based on the correlation coefficients between parameters.
INPUTS: | params – (M x N array) M instantiations of a set of N parameters. |
---|---|
OPTIONS: | labs – (list) labels for each of the N parameters tit – (str) title for figure xrot/yrot – (float) axis label rotation, in degrees cmap – (matplotlib cm) – colormap for color-coding. figsize – (2-list) – width and height of figure plotregion – (4-list) – (left, bottom, width, height) of plotted region in each figure n – (int) – number of subplots across each figure
|
REQUIREMENTS: | pylab, NIRSPEC Data Analysis |
NOTES: | Based on the concept by Nymyer and Harrington at U. Central Florida Beware of plotting two many points, and clogging your system! |
Plot 1D data in a histogram-like format. If x-coordinates are specified, they refer to the centers of the histogram bars.
ploth(x, y) # plot x and y using solid linestyle (default)
ploth(x, y, 'bo') # plot x and y using blue circle markers w/no line
ploth(y) # plot y using x as index array 0..N-1
ploth(y, 'r*--') # ditto, but with red star corners and dashed line
OPTIONS: |
|
---|---|
REQUIREMENTS: | numpy, Numerical analysis routines |
Plot contours and histograms for 2D likelihood array.
INPUTS: | L : 2d Numpy array
xlabel : str ylabel : str
|
---|
Return plot properties to help distinguish many types of plot symbols.
INPUT: | i – int. |
---|---|
OPTIONAL INPUT: | c – color, or list of colors accepted by pylab.plot s – symbol, or list of symbols accepted by pylab.plot l – linestyle, or list of linestyles accepted by pylab.plot |
OUTPUT: | tuple of (color, symbol, linestyle) |
REQUIREMENTS: | numpy |
Remove all instances of ‘obj’ from list ‘seq’
INPUT: | seq – (list) list from which to pop elements obj – target object to remove |
---|---|
EXAMPLE: | import tools
b = [3, 'spam', range(5)]
tools.popall(b, 4)
print b
|
NOTES: | – Will fail if ‘obj’ is itself a list.
– Has not been tested for extremely deep lists |
SEE ALSO: |
Take a set of parameters and plot them. Assume that the larger of the array’s two dimensions is N (the number of instantiations) and the smaller is M (the number of parameters).
If npts is not None, then pick only every (N/npts)th point. if newfig is False, plot into the current figure.
REQUIREMENTS: | numpy, pylab |
---|
Print desired figures using designated ‘format’. Concatenate PDFs.
Inputs: | filename – string. prepended to all open figures figs – int or list.
format – string or list of strings.
pdfmode – string;
closefigs – bool
|
---|---|
NOTES: | If no explicit path is passed and a subdirectory ‘figures’ exists in the current directory, the figures will be printed in ‘figures’ instead. |
EXAMPLE: | from pylab import *
figure(1); plot(arange(10), randn(10), 'ob')
figure(2); plot(arange(15), randn(15), '-xr')
printfigs('testing')
!open testing.pdf
|
Read ASCII-format Dartmouth Isochrone files into Python.
INPUTS: |
|
---|---|
OUTPUT: | A Pythonic object with fields derived from the input file. It will have fields named ‘Y’, ‘Z’, ‘Zeff’, ‘ages_Gyr’, ‘isochrones’, ‘photometricSystem’, etc. The ‘isochrones’ field is a list of isochrones, one at each age step. It will have fields whose names correspond to photometric bandpasses (see the example below), as well as standard fields such as ‘LogG’, ‘LogTeff’, ‘LogL_Lo’, ‘M_Mo’, etc. |
NOTES: | You can download the models at the DSEP website: http://stellar.dartmouth.edu/~models/ |
REQUIREMENTS: | As written, requires NumPy. (But could be easily rewritten to avoid this, if necessary). |
EXAMPLE: | # Reproduce Fig. 4 of Dotter et al. (2008):
import tools
import pylab as py
filename = 'fehp00afep0.UBVRIJHKsKp'
models = tools.readDartmouthIsochrones(filename, mode='2012')
age2plot = 4 # Plot 4 Gyr track
age_index = (models.ages_Gyr==age2plot).nonzero()[0]
this_isochrone = models.isochrones[age_index]
py.figure()
ax1=py.subplot(121)
py.plot(this_isochrone.LogTeff, this_isochrone.LogL_Lo)
py.xlabel('log T_eff')
py.ylabel('log L/L_sun')
py.axis([3.9, 3.4, -3, 4])
leg = legend(['DSEP'], 3)
ax2=py.subplot(122)
py.plot(this_isochrone.V - this_isochrone.I, this_isochrone.V)
py.xlabel('V - I')
py.ylabel('M_V')
py.axis([0.25, 4, 14, -2])
[ax.minorticks_on() for ax in [ax1, ax2]]
|
Read in a raw PostScript plot datafile and output Numpy arrays.
INPUTS: |
|
---|---|
FILE_FORMAT: |
|
OUTPUTS: | (x, y) – tuple of 1D arrays |
Replace all instances of ‘obj’ with ‘rep’ in list ‘seq’
INPUT: | seq – (list) list within which to find-and-replace elements obj – target object to replace rep – replacement object |
---|---|
EXAMPLE: | import tools
b = [2, ['spam', ['eggs', 5, dict(spam=3)]]]
tools.replaceall(b, 'spam', 'bacon')
print b
|
NOTES: | – Will fail if ‘obj’ is itself a list.
– Has not been tested for extremely deep lists |
SEE ALSO: |
Resample a 2D array by a given factor, using bilinear interpolation.
INPUTS: |
|
---|
Resample parameters of an isochrone-type object.
INPUTS: |
|
---|---|
NOTES: | We use numpy.interp() for the resampling; if ‘x’ is not an always-increasing array then interp() may have problems. Similarly, interp() offers no extrapolation beyond the original limits of iso.xName. |
Round a value and its associated error(s) to 2 decimal places.
INPUTS: | value, error : scalars |
---|---|
OUTPUTS: | value, error |
EXAMPLE: | import tools
tools.roundparams(1.23456, .09876)
|
SEE_ALSO: |
Round all input values to the smallest number of digits used.
INPUTS: |
|
---|---|
EXAMPLE: | import tools
tools.roundvals([235, -4, 0.045380])
|
SEE_ALSO: |
Sample a 1D Posterior Distribution Function (1d-histogram)
INPUTS: |
|
---|
Sample a 2D Probability Distribution Function (2d-histogram)
INPUTS: |
|
---|---|
NOTES: | Note that this approach uses simple, dumb nearest-neighbor interpolation when drawing candidate samples. Exceedingly granular CDFs may suffer. Note that this code isn’t optimized; try it with small samples before you use it on large ones! |
Save a pickle to a given filename. If it can’t be saved by pickle, return -1 – otherwise return the file object.
To save multiple objects in one file, use (e.g.) a dict:
tools.savepickle(dict(a=[1,2], b=’eggs’), filename)
Extract a series of integers from a string. Slow but robust.
readints(‘[124, 56|abcdsfad4589.2]’)
will return:
[124, 56, 4589, 2]
Shift a 2D image by the specified number of integer pixels.
INPUTS: |
|
---|
Add two functions together.
EXAMPLE: | import numpy as np
sumfunc([.785, .785], np.cos, np.sin, 1) # returns cos(pi/4) + sin(pi/4) ~ XXX
|
---|---|
EXAMPLE: | import pylab as py
import tools
x = 2*py.pi * py.linspace(-5, 5, 500)
y = tools.sumfunc([x/8., x], np.sin, np.sin, 1).ravel()
py.plot(x, y)
|
Add results of several functions together.
INPUTS: |
|
---|---|
EXAMPLE: | import numpy as np
sumfunc_general([.785, .785], (np.cos, np.sin), (1, 1))
|
EXAMPLE: | import pylab as py
import tools
x = 2*py.pi * py.linspace(-10, 10, 500)
y = tools.sumfunc_general([x/8., x], (np.sin, np.sin), (1, 1)).ravel()
py.plot(x, y)
|
Generate a figure from a list of strings.
INPUTS: |
|
---|---|
OPTIONS: | any options valid for passing to matplotlib.text Also: the dict ‘figoptions’ will be passed to figure() |
RETURNS: | (fig, ax) – handles to Figure and Axes that were created |