mpl.mlab

Numerical python functions written for compatability with MATLAB commands with the same names.

MATLAB compatible functions

cohere()
Coherence (normalized cross spectral density)
csd()
Cross spectral density uing Welch’s average periodogram
detrend()
Remove the mean or best fit line from an array
find()
Return the indices where some condition is true; numpy.nonzero is similar but more general.
griddata()
Interpolate irregularly distributed data to a regular grid.
prctile()
Find the percentiles of a sequence
prepca()
Principal Component Analysis
psd()
Power spectral density uing Welch’s average periodogram
rk4()
A 4th order runge kutta integrator for 1D or ND systems
specgram()
Spectrogram (spectrum over segments of time)

Miscellaneous functions

Functions that don’t exist in MATLAB, but are useful anyway:

cohere_pairs()
Coherence over all pairs. This is not a MATLAB function, but we compute coherence a lot in my lab, and we compute it for a lot of pairs. This function is optimized to do this efficiently by caching the direct FFTs.
rk4()
A 4th order Runge-Kutta ODE integrator in case you ever find yourself stranded without scipy (and the far superior scipy.integrate tools)
contiguous_regions()
Return the indices of the regions spanned by some logical mask
cross_from_below()
Return the indices where a 1D array crosses a threshold from below
cross_from_above()
Return the indices where a 1D array crosses a threshold from above
complex_spectrum()
Return the complex-valued frequency spectrum of a signal
magnitude_spectrum()
Return the magnitude of the frequency spectrum of a signal
angle_spectrum()
Return the angle (wrapped phase) of the frequency spectrum of a signal
phase_spectrum()
Return the phase (unwrapped angle) of the frequency spectrum of a signal
detrend_mean()
Remove the mean from a line.
demean()
Remove the mean from a line. This function is the same as as detrend_mean() except for the default axis.
detrend_linear()
Remove the best fit line from a line.
detrend_none()
Return the original line.
stride_windows()
Get all windows in an array in a memory-efficient manner
stride_repeat()
Repeat an array in a memory-efficient manner
apply_window()
Apply a window along a given axis

record array helper functions

A collection of helper methods for numpyrecord arrays

See misc-examples-index
rec2txt()
Pretty print a record array
rec2csv()
Store record array in CSV file
csv2rec()
Import record array from CSV file with type inspection
rec_append_fields()
Adds field(s)/array(s) to record array
rec_drop_fields()
Drop fields from record array
rec_join()
Join two record arrays on sequence of fields
recs_join()
A simple join of multiple recarrays using a single column as a key
rec_groupby()
Summarize data by groups (similar to SQL GROUP BY)
rec_summarize()
Helper code to filter rec array fields into new fields

For the rec viewer functions(e rec2csv), there are a bunch of Format objects you can pass into the functions that will do things like color negative values red, set percent formatting and scaling, etc.

Example usage:

r = csv2rec('somefile.csv', checkrows=0)

formatd = dict(
    weight = FormatFloat(2),
    change = FormatPercent(2),
    cost   = FormatThousands(2),
    )


rec2excel(r, 'test.xls', formatd=formatd)
rec2csv(r, 'test.csv', formatd=formatd)
scroll = rec2gtk(r, formatd=formatd)

win = gtk.Window()
win.set_size_request(600,800)
win.add(scroll)
win.show_all()
gtk.main()

Functions

amap((function, sequence[, sequence, ...) Works like map(), but it returns an array.
angle_spectrum(x[, Fs, window, pad_to, sides]) Compute the angle of the frequency spectrum (wrapped phase spectrum) of x.
apply_window(x, window[, axis, return_window]) Apply the given window to the given 1D or 2D array along the given axis.
base_repr(number[, base, padding]) Return the representation of a number in any given base.
binary_repr(number[, max_length]) Return the binary representation of the input number as a string.
bivariate_normal(X, Y[, sigmax, sigmay, ...]) Bivariate Gaussian distribution for equal shape X, Y.
center_matrix(M[, dim]) Return the matrix M with each row having zero mean and unit std.
cohere(x, y[, NFFT, Fs, detrend, window, ...]) The coherence between x and y.
cohere_pairs(X, ij[, NFFT, Fs, detrend, ...]) Call signature:
complex_spectrum(x[, Fs, window, pad_to, sides]) Compute the complex-valued frequency spectrum of x.
contiguous_regions(mask) return a list of (ind0, ind1) such that mask[ind0:ind1].all() is
cross_from_above(x, threshold) return the indices into x where x crosses some threshold from
cross_from_below(x, threshold) return the indices into x where x crosses some threshold from
csd(x, y[, NFFT, Fs, detrend, window, ...]) Compute the cross-spectral density.
csv2rec(fname[, comments, skiprows, ...]) Load data from comma/space/tab delimited file in fname into a numpy record array and return the record array.
csvformat_factory(format)
demean(x[, axis]) Return x minus its mean along the specified axis.
detrend(x[, key, axis]) Return x with its trend removed.
detrend_linear(y) Return x minus best fit line; ‘linear’ detrending.
detrend_mean(x[, axis]) Return x minus the mean(x).
detrend_none(x[, axis]) Return x: no detrending.
dist(x, y) Return the distance between two points.
dist_point_to_segment(p, s0, s1) Get the distance of a point to a segment.
distances_along_curve(X) Computes the distance between a set of successive points in N dimensions.
donothing_callback(*args)
entropy(y, bins) Return the entropy of the data in y in units of nat.
exp_safe(x) Compute exponentials which safely underflow to zero.
fftsurr(x[, detrend, window]) Compute an FFT phase randomized surrogate of x.
find(condition) Return the indices where ravel(condition) is true
frange(([start,] stop[, step, ...) Return a numpy ndarray containing a progression of floats.
get_formatd(r[, formatd]) build a formatd guaranteed to have a key for every dtype name
get_sparse_matrix(M, N[, frac]) Return a M x N sparse matrix with frac elements randomly filled.
get_xyz_where(Z, Cond) Z and Cond are M x N matrices. Z are data and Cond is
griddata(x, y, z, xi, yi[, interp]) Interpolates from a nonuniformly spaced grid to some other grid.
identity(n[, rank, dtype, typecode]) Returns the identity matrix of shape (n, n, ..., n) (rank r).
inside_poly(points, verts) points is a sequence of x, y points.
is_closed_polygon(X) Tests whether first and last object in a sequence are the same.
ispower2(n) Returns the log base 2 of n if n is a power of 2, zero otherwise.
isvector(X) Like the MATLAB function with the same name, returns True if the supplied numpy array or matrix X looks like a vector, meaning it has a one non-singleton axis (i.e., it can have multiple axes, but all must have length 1, except for one of them).
l1norm(a) Return the l1 norm of a, flattened out.
l2norm(a) Return the l2 norm of a, flattened out.
less_simple_linear_interpolation(x, y, xi[, ...]) This function provides simple (but somewhat less so than cbook.simple_linear_interpolation()) linear interpolation.
log2(x[, ln2]) Return the log(x) in base 2.
logspace(xmin, xmax, N) Return N values logarithmically spaced between xmin and xmax.
longest_contiguous_ones(x) Return the indices of the longest stretch of contiguous ones in x, assuming x is a vector of zeros and ones.
longest_ones(x) alias for longest_contiguous_ones
magnitude_spectrum(x[, Fs, window, pad_to, ...]) Compute the magnitude (absolute value) of the frequency spectrum of x.
movavg(x, n) Compute the len(n) moving average of x.
norm_flat(a[, p]) norm(a,p=2) -> l-p norm of a.flat
normpdf(x, *args) Return the normal pdf evaluated at x; args provides mu, sigma
offset_line(y, yerr) Offsets an array y by +/- an error and returns a tuple (y - err, y + err).
path_length(X) Computes the distance travelled along a polygonal curve in N dimensions.
phase_spectrum(x[, Fs, window, pad_to, sides]) Compute the phase of the frequency spectrum (unwrapped angle spectrum) of x.
poly_below(xmin, xs, ys) Given a sequence of xs and ys, return the vertices of a polygon that has a horizontal base at xmin and an upper bound at the ys.
poly_between(x, ylower, yupper) Given a sequence of x, ylower and yupper, return the polygon that fills the regions between them.
prctile(x[, p]) Return the percentiles of x.
prctile_rank(x, p) Return the rank for each element in x, return the rank 0..len(p).
psd(x[, NFFT, Fs, detrend, window, ...]) Compute the power spectral density.
quad2cubic(q0x, q0y, q1x, q1y, q2x, q2y) Converts a quadratic Bezier curve to a cubic approximation.
rec2csv(r, fname[, delimiter, formatd, ...]) Save the data from numpy recarray r into a comma-/space-/tab-delimited file.
rec2txt(r[, header, padding, precision, fields]) Returns a textual representation of a record array.
rec_append_fields(rec, names, arrs[, dtypes]) Return a new record array with field names populated with data from arrays in arrs.
rec_drop_fields(rec, names) Return a new numpy record array with fields in names dropped.
rec_groupby(r, groupby, stats) r is a numpy record array
rec_join(key, r1, r2[, jointype, defaults, ...]) Join record arrays r1 and r2 on key; key is a tuple of field names – if key is a string it is assumed to be a single attribute name.
rec_keep_fields(rec, names) Return a new numpy record array with only fields listed in names
rec_summarize(r, summaryfuncs) r is a numpy record array
recs_join(key, name, recs[, jointype, ...]) Join a sequence of record arrays on single column key.
rk4(derivs, y0, t) Integrate 1D or ND system of ODEs using 4-th order Runge-Kutta.
rms_flat(a) Return the root mean square of all the elements of a, flattened out.
safe_isinf(x) numpy.isinf() for arbitrary types
safe_isnan(x) numpy.isnan() for arbitrary types
segments_intersect(s1, s2) Return True if s1 and s2 intersect.
slopes(x, y) slopes() calculates the slope y‘(x)
specgram(x[, NFFT, Fs, detrend, window, ...]) Compute a spectrogram.
stineman_interp(xi, x, y[, yp]) Given data vectors x and y, the slope vector yp and a new abscissa vector xi, the function stineman_interp() uses Stineman interpolation to calculate a vector yi corresponding to xi.
stride_repeat(x, n[, axis]) Repeat the values in an array in a memory-efficient manner.
stride_windows(x, n[, noverlap, axis]) Get all windows of x with length n as a single array, using strides to avoid data duplication.
vector_lengths(X[, P, axis]) Finds the length of a set of vectors in n dimensions.
window_hanning(x) Return x times the hanning window of len(x).
window_none(x) No window function; simply return x.

Classes

FormatBool
FormatDate(fmt)
FormatDatetime([fmt])
FormatFloat([precision, scale])
FormatFormatStr(fmt)
FormatInt
FormatMillions([precision])
FormatObj
FormatPercent([precision])
FormatString
FormatThousands([precision])
GaussianKDE(dataset[, bw_method]) Representation of a kernel-density estimate using Gaussian kernels.
PCA(a[, standardize])
Path(vertices[, codes, ...]) Path represents a series of possibly disconnected,
map alias of imap
xrange xrange(start, stop[, step]) -> xrange object
zip alias of izip