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.
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 |
---|
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
|
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.
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. **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.
|
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. **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.
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 |
---|
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 |
flatten(sequence) -> list
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]
|
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
|
---|---|
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 |
---|
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.
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: | 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’.
Inputs : | filename – string. prepended to all open figures figs – int or list.
format – string or list of strings.
pdfmode – string;
|
---|---|
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 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 : |
|
---|
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)
|
Sample a 1D Posterior Distribution Function (1d-histogram)
Inputs : |
|
---|
Sample a 2D Cumulative 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)
|