| |
- amap(fn, *args)
- amap(function, sequence[, sequence, ...]) -> array.
Works like map(), but it returns an array. This is just a convenient
shorthand for numpy.array(map(...))
- approx_real(x)
- approx_real(x) : returns x.real if |x.imag| < |x.real| * _eps_approx.
This function is needed by sqrtm and allows further functions.
- base_repr(number, base=2, padding=0)
- Return the representation of a number in any given base.
- binary_repr(number, max_length=1025)
- Return the binary representation of the input number as a string.
This is more efficient than using base_repr with base 2.
Increase the value of max_length for very large numbers. Note that on
32-bit machines, 2**1023 is the largest integer power of 2 which can be
converted to a Python float.
- bivariate_normal(X, Y, sigmax=1.0, sigmay=1.0, mux=0.0, muy=0.0, sigmaxy=0.0)
- Bivariate gaussan distribution for equal shape X, Y
http://mathworld.wolfram.com/BivariateNormalDistribution.html
- center_matrix(M, dim=0)
- Return the matrix M with each row having zero mean and unit std
if dim=1 operate on columns instead of rows. (dim is opposite
to the numpy axis kwarg.)
- cohere(x, y, NFFT=256, Fs=2, detrend=<function detrend_none at 0x84b3cdc>, window=<function window_hanning at 0x84b3b8c>, noverlap=0)
- The coherence between x and y. Coherence is the normalized
cross spectral density
Cxy = |Pxy|^2/(Pxx*Pyy)
The return value is (Cxy, f), where f are the frequencies of the
coherence vector. See the docs for psd and csd for information
about the function arguments NFFT, detrend, window, noverlap, as
well as the methods used to compute Pxy, Pxx and Pyy.
Returns the tuple Cxy, freqs
- cohere_pairs(X, ij, NFFT=256, Fs=2, detrend=<function detrend_none at 0x84b3cdc>, window=<function window_hanning at 0x84b3b8c>, noverlap=0, preferSpeedOverMemory=True, progressCallback=<function donothing_callback at 0x84b3f0c>, returnPxx=False)
- Cxy, Phase, freqs = cohere_pairs( X, ij, ...)
Compute the coherence for all pairs in ij. X is a
numSamples,numCols numpy array. ij is a list of tuples (i,j).
Each tuple is a pair of indexes into the columns of X for which
you want to compute coherence. For example, if X has 64 columns,
and you want to compute all nonredundant pairs, define ij as
ij = []
for i in range(64):
for j in range(i+1,64):
ij.append( (i,j) )
The other function arguments, except for 'preferSpeedOverMemory'
(see below), are explained in the help string of 'psd'.
Return value is a tuple (Cxy, Phase, freqs).
Cxy -- a dictionary of (i,j) tuples -> coherence vector for that
pair. Ie, Cxy[(i,j) = cohere(X[:,i], X[:,j]). Number of
dictionary keys is len(ij)
Phase -- a dictionary of phases of the cross spectral density at
each frequency for each pair. keys are (i,j).
freqs -- a vector of frequencies, equal in length to either the
coherence or phase vectors for any i,j key. Eg, to make a coherence
Bode plot:
subplot(211)
plot( freqs, Cxy[(12,19)])
subplot(212)
plot( freqs, Phase[(12,19)])
For a large number of pairs, cohere_pairs can be much more
efficient than just calling cohere for each pair, because it
caches most of the intensive computations. If N is the number of
pairs, this function is O(N) for most of the heavy lifting,
whereas calling cohere for each pair is O(N^2). However, because
of the caching, it is also more memory intensive, making 2
additional complex arrays with approximately the same number of
elements as X.
The parameter 'preferSpeedOverMemory', if false, limits the
caching by only making one, rather than two, complex cache arrays.
This is useful if memory becomes critical. Even when
preferSpeedOverMemory is false, cohere_pairs will still give
significant performace gains over calling cohere for each pair,
and will use subtantially less memory than if
preferSpeedOverMemory is true. In my tests with a 43000,64 array
over all nonredundant pairs, preferSpeedOverMemory=1 delivered a
33% performace boost on a 1.7GHZ Athlon with 512MB RAM compared
with preferSpeedOverMemory=0. But both solutions were more than
10x faster than naievly crunching all possible pairs through
cohere.
See test/cohere_pairs_test.py in the src tree for an example
script that shows that this cohere_pairs and cohere give the same
results for a given pair.
- conv(x, y, mode=2)
- convolve x with y
- corrcoef(*args)
- corrcoef(X) where X is a matrix returns a matrix of correlation
coefficients for the columns of X.
corrcoef(x,y) where x and y are vectors returns the matrix of
correlation coefficients for x and y.
Numpy arrays can be real or complex
The correlation matrix is defined from the covariance matrix C as
r(i,j) = C[i,j] / sqrt(C[i,i]*C[j,j])
- csd(x, y, NFFT=256, Fs=2, detrend=<function detrend_none at 0x84b3cdc>, window=<function window_hanning at 0x84b3b8c>, noverlap=0)
- The cross spectral density Pxy by Welches average periodogram
method. The vectors x and y are divided into NFFT length
segments. Each segment is detrended by function detrend and
windowed by function window. noverlap gives the length of the
overlap between segments. The product of the direct FFTs of x and
y are averaged over each segment to compute Pxy, with a scaling to
correct for power loss due to windowing. Fs is the sampling
frequency.
NFFT must be even; a power of 2 is most efficient
window can be a function or a vector of length NFFT. To create
window vectors see numpy.blackman, numpy.hamming, numpy.bartlett,
scipy.signal, scipy.signal.get_window etc.
Returns the tuple Pxy, freqs
Refs:
Bendat & Piersol -- Random Data: Analysis and Measurement
Procedures, John Wiley & Sons (1986)
- csv2rec(fname, comments='#', skiprows=0, checkrows=5, delimiter=',', converterd=None, names=None, missing=None)
- Load data from comma/space/tab delimited file in fname into a
numpy record array and return the record array.
If names is None, a header row is required to automatically assign
the recarray names. The headers will be lower cased, spaces will
be converted to underscores, and illegal attribute name characters
removed. If names is not None, it is a sequence of names to use
for the column names. In this case, it is assumed there is no header row.
fname - can be a filename or a file handle. Support for gzipped
files is automatic, if the filename ends in .gz
comments - the character used to indicate the start of a comment
in the file
skiprows - is the number of rows from the top to skip
checkrows - is the number of rows to check to validate the column
data type. When set to zero all rows are validated.
converterd, if not None, is a dictionary mapping column number or
munged column name to a converter function
names, if not None, is a list of header names. In this case, no
header will be read from the file
if no rows are found, None is returned See examples/loadrec.py
- csvformat_factory(format)
- demean(x, axis=0)
- Return x minus its mean along the specified axis
- detrend(x, key=None)
- detrend_linear(y)
- Return y minus best fit line; 'linear' detrending
- detrend_mean(x)
- Return x minus the mean(x)
- detrend_none(x)
- Return x: no detrending
- diagonal_matrix(diag)
- Return square diagonal matrix whose non-zero elements are given by the
input array.
- 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.
p, s0, s1 are xy sequences
This algorithm from
http://softsurfer.com/Archive/algorithm_0102/algorithm_0102.htm#Distance%20to%20Ray%20or%20Segment
- donothing_callback(*args)
- entropy(y, bins)
- Return the entropy of the data in y
\sum p_i log2(p_i) where p_i is the probability of observing y in
the ith bin of bins. bins can be a number of bins or a range of
bins; see numpy.histogram
Compare S with analytic calculation for a Gaussian
x = mu + sigma*randn(200000)
Sanalytic = 0.5 * ( 1.0 + log(2*pi*sigma**2.0) )
- exp_safe(x)
- Compute exponentials which safely underflow to zero.
Slow but convenient to use. Note that numpy provides proper
floating point exception handling with access to the underlying
hardware.
- fftsurr(x, detrend=<function detrend_none at 0x84b3cdc>, window=<function window_none at 0x84b3bc4>)
- Compute an FFT phase randomized surrogate of x
- find(condition)
- Return the indices where ravel(condition) is true
- fix(x)
- Rounds towards zero.
x_rounded = fix(x) rounds the elements of x to the nearest integers
towards zero.
For negative numbers is equivalent to ceil and for positive to floor.
- frange(xini, xfin=None, delta=None, **kw)
- frange([start,] stop[, step, keywords]) -> array of floats
Return a numpy ndarray containing a progression of floats. Similar to
arange(), but defaults to a closed interval.
frange(x0, x1) returns [x0, x0+1, x0+2, ..., x1]; start defaults to 0, and
the endpoint *is included*. This behavior is different from that of
range() and arange(). This is deliberate, since frange will probably be
more useful for generating lists of points for function evaluation, and
endpoints are often desired in this use. The usual behavior of range() can
be obtained by setting the keyword 'closed=0', in this case frange()
basically becomes arange().
When step is given, it specifies the increment (or decrement). All
arguments can be floating point numbers.
frange(x0,x1,d) returns [x0,x0+d,x0+2d,...,xfin] where xfin<=x1.
frange can also be called with the keyword 'npts'. This sets the number of
points the list should contain (and overrides the value 'step' might have
been given). arange() doesn't offer this option.
Examples:
>>> frange(3)
array([ 0., 1., 2., 3.])
>>> frange(3,closed=0)
array([ 0., 1., 2.])
>>> frange(1,6,2)
array([1, 3, 5]) or 1,3,5,7, depending on floating point vagueries
>>> frange(1,6.5,npts=5)
array([ 1. , 2.375, 3.75 , 5.125, 6.5 ])
- fromfunction_kw(function, dimensions, **kwargs)
- Drop-in replacement for fromfunction() from numpy
Allows passing keyword arguments to the desired function.
Call it as (keywords are optional):
fromfunction_kw(MyFunction, dimensions, keywords)
The function MyFunction() is responsible for handling the dictionary of
keywords it will receive.
- get_formatd(r, formatd=None)
- build a formatd guaranteed to have a key for every dtype name
- get_sparse_matrix(M, N, frac=0.10000000000000001)
- return a MxN sparse matrix with frac elements randomly filled
- get_xyz_where(Z, Cond)
- Z and Cond are MxN matrices. Z are data and Cond is a boolean
matrix where some condition is satisfied. Return value is x,y,z
where x and y are the indices into Z and z are the values of Z at
those indices. x,y,z are 1D arrays
- gtkformat_factory(format, colnum)
- copy the format, perform any overrides, and attach an gtk style attrs
xalign = 0.
cell = None
- hist(y, bins=10, normed=0)
- Return the histogram of y with bins equally sized bins. If bins
is an array, use the bins. Return value is
(n,x) where n is the count for each bin in x
If normed is False, return the counts in the first element of the
return tuple. If normed is True, return the probability density
n/(len(y)*dbin)
If y has rank>1, it will be raveled. If y is masked, only
the unmasked values will be used.
Credits: the Numeric 22 documentation
- identity(n, rank=2, dtype='l', typecode=None)
- identity(n,r) returns the identity matrix of shape (n,n,...,n) (rank r).
For ranks higher than 2, this object is simply a multi-index Kronecker
delta:
/ 1 if i0=i1=...=iR,
id[i0,i1,...,iR] = -|
\ 0 otherwise.
Optionally a dtype (or typecode) may be given (it defaults to 'l').
Since rank defaults to 2, this function behaves in the default case (when
only n is given) like numpy.identity(n)--but surprisingly, it is
much faster.
- inside_poly(points, verts)
- points is a sequence of x,y points
verts is a sequence of x,y vertices of a poygon
return value is a sequence of indices into points for the points
that are inside the polygon
- ispower2(n)
- Returns the log base 2 of n if n is a power of 2, zero otherwise.
Note the potential ambiguity if n==1: 2**0==1, interpret accordingly.
- l1norm(a)
- Return the l1 norm of a, flattened out.
Implemented as a separate function (not a call to norm() for speed).
- l2norm(a)
- Return the l2 norm of a, flattened out.
Implemented as a separate function (not a call to norm() for speed).
- levypdf(x, gamma, alpha)
- Returm the levy pdf evaluated at x for params gamma, alpha
- liaupunov(x, fprime)
- x is a very long trajectory from a map, and fprime returns the
derivative of x. Return lambda = 1/n\sum ln|fprime(x_i)|. See Sec
10.5 Strogatz (1994)"Nonlinear Dynamics and Chaos".
See also http://en.wikipedia.org/wiki/Lyapunov_exponent.
What the function here calculates may not be what you really want;
caveat emptor.
It also seems that this function's name is badly misspelled.
- linspace(*args, **kw)
- load(fname, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False)
- Load ASCII data from fname into an array and return the array.
The data must be regular, same number of values in every row
fname can be a filename or a file handle. Support for gzipped files is
automatic, if the filename ends in .gz
matfile data is not supported; use scipy.io.mio module
Example usage:
X = load('test.dat') # data in two columns
t = X[:,0]
y = X[:,1]
Alternatively, you can do the same with "unpack"; see below
X = load('test.dat') # a matrix of data
x = load('test.dat') # a single column of data
comments - the character used to indicate the start of a comment
in the file
delimiter is a string-like character used to seperate values in the
file. If delimiter is unspecified or none, any whitespace string is
a separator.
converters, if not None, is a dictionary mapping column number to
a function that will convert that column to a float. Eg, if
column 0 is a date string: converters={0:datestr2num}
skiprows is the number of rows from the top to skip
usecols, if not None, is a sequence of integer column indexes to
extract where 0 is the first column, eg usecols=(1,4,5) to extract
just the 2nd, 5th and 6th columns
unpack, if True, will transpose the matrix allowing you to unpack
into named arguments on the left hand side
t,y = load('test.dat', unpack=True) # for two column data
x,y,z = load('somefile.dat', usecols=(3,5,7), unpack=True)
See examples/load_demo.py which exeercises many of these options.
- log2(x, ln2=0.69314718055994529)
- Return the log(x) in base 2.
This is a _slow_ function but which is guaranteed to return the correct
integer value if the input is an integer exact power of 2.
- logspace(xmin, xmax, N)
- 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.
If there are two equally long stretches, pick the first
- longest_ones(x)
- alias for longest_contiguous_ones
- mean(x, dim=None)
- mean_flat(a)
- Return the mean of all the elements of a, flattened out.
- meshgrid(x, y)
- mfuncC(f, x)
- mfuncC(f, x) : matrix function with possibly complex eigenvalues.
Note: Numeric defines (v,u) = eig(x) => x*u.T = u.T * Diag(v)
This function is needed by sqrtm and allows further functions.
- movavg(x, n)
- compute the len(n) moving average of x
- norm(x, y=2)
- Norm of a matrix or a vector according to Matlab.
The description is taken from Matlab:
For matrices...
NORM(X) is the largest singular value of X, max(svd(X)).
NORM(X,2) is the same as NORM(X).
NORM(X,1) is the 1-norm of X, the largest column sum,
= max(sum(abs((X)))).
NORM(X,inf) is the infinity norm of X, the largest row sum,
= max(sum(abs((X')))).
NORM(X,'fro') is the Frobenius norm, sqrt(sum(diag(X'*X))).
NORM(X,P) is available for matrix X only if P is 1, 2, inf or 'fro'.
For vectors...
NORM(V,P) = sum(abs(V).^P)^(1/P).
NORM(V) = norm(V,2).
NORM(V,inf) = max(abs(V)).
NORM(V,-inf) = min(abs(V)).
- norm_flat(a, p=2)
- norm(a,p=2) -> l-p norm of a.flat
Return the l-p norm of a, considered as a flat array. This is NOT a true
matrix norm, since arrays of arbitrary rank are always flattened.
p can be a number or the string 'Infinity' to get the L-infinity norm.
- normpdf(x, *args)
- Return the normal pdf evaluated at x; args provides mu, sigma
- orth(A)
- Orthogonalization procedure by Matlab.
The description is taken from its help:
Q = ORTH(A) is an orthonormal basis for the range of A.
That is, Q'*Q = I, the columns of Q span the same space as
the columns of A, and the number of columns of Q is the
rank of A.
- poly_below(xmin, xs, ys)
- given a sequence of xs and ys, return the vertices of a polygon
that has a horzontal base at xmin and an upper bound at the ys.
xmin is a scalar.
intended for use with Axes.fill, eg
xv, yv = poly_below(0, x, y)
ax.fill(xv, yv)
- poly_between(x, ylower, yupper)
- given a sequence of x, ylower and yupper, return the polygon that
fills the regions between them. ylower or yupper can be scalar or
iterable. If they are iterable, they must be equal in length to x
return value is x, y arrays for use with Axes.fill
- polyfit(*args, **kwargs)
- def polyfit(x,y,N)
Do a best fit polynomial of order N of y to x. Return value is a
vector of polynomial coefficients [pk ... p1 p0]. Eg, for N=2
p2*x0^2 + p1*x0 + p0 = y1
p2*x1^2 + p1*x1 + p0 = y1
p2*x2^2 + p1*x2 + p0 = y2
.....
p2*xk^2 + p1*xk + p0 = yk
Method: if X is a the Vandermonde Matrix computed from x (see
http://mathworld.wolfram.com/VandermondeMatrix.html), then the
polynomial least squares solution is given by the 'p' in
X*p = y
where X is a len(x) x N+1 matrix, p is a N+1 length vector, and y
is a len(x) x 1 vector
This equation can be solved as
p = (XT*X)^-1 * XT * y
where XT is the transpose of X and -1 denotes the inverse.
Numerically, however, this is not a good method, so we use
numpy.linalg.lstsq.
For more info, see
http://mathworld.wolfram.com/LeastSquaresFittingPolynomial.html,
but note that the k's and n's in the superscripts and subscripts
on that page. The linear algebra is correct, however.
See also polyval
- polyval(*args, **kwargs)
- y = polyval(p,x)
p is a vector of polynomial coeffients and y is the polynomial
evaluated at x.
Example code to remove a polynomial (quadratic) trend from y:
p = polyfit(x, y, 2)
trend = polyval(p, x)
resid = y - trend
See also polyfit
- prctile(x, p=(0.0, 25.0, 50.0, 75.0, 100.0))
- Return the percentiles of x. p can either be a sequence of
percentile values or a scalar. If p is a sequence the i-th element
of the return sequence is the p(i)-th percentile of x.
If p is a scalar, the largest value of x less than or equal
to the p percentage point in the sequence is returned.
- prctile_rank(x, p)
- return the for each element in x, return the rank 0..len(p) . Eg
if p=(25, 50, 75), the return value will be a len(x) array with
values in [0,1,2,3] where 0 indicates the value is less than the
25th percentile, 1 indicates the value is >= the 25th and < 50th
percentile, ... and 3 indicates the value is above the 75th
percentile cutoff
p is either an array of percentiles in [0..100] or a scalar which
indicates how many quantiles of data you want ranked
- prepca(P, frac=0)
- Compute the principal components of P. P is a numVars x
numObs array. frac is the minimum fraction of
variance that a component must contain to be included.
Return value are
Pcomponents : a numVars x numObs array
Trans : the weights matrix, ie, Pcomponents = Trans*P
fracVar : the fraction of the variance accounted for by each
component returned
A similar function of the same name was in the Matlab (TM)
R13 Neural Network Toolbox but is not found in later versions;
its successor seems to be called "processpcs".
- psd(x, NFFT=256, Fs=2, detrend=<function detrend_none at 0x84b3cdc>, window=<function window_hanning at 0x84b3b8c>, noverlap=0)
- The power spectral density by Welches average periodogram method.
The vector x is divided into NFFT length segments. Each segment
is detrended by function detrend and windowed by function window.
noperlap gives the length of the overlap between segments. The
absolute(fft(segment))**2 of each segment are averaged to compute Pxx,
with a scaling to correct for power loss due to windowing.
Fs is the sampling frequency (samples per time unit). It is used
to calculate the Fourier frequencies, freqs, in cycles per time
unit.
-- NFFT must be even; a power 2 is most efficient.
-- detrend is a functions, unlike in matlab where it is a vector.
-- window can be a function or a vector of length NFFT. To create window
vectors see numpy.blackman, numpy.hamming, numpy.bartlett,
scipy.signal, scipy.signal.get_window etc.
-- if length x < NFFT, it will be zero padded to NFFT
Returns the tuple Pxx, freqs
Refs:
Bendat & Piersol -- Random Data: Analysis and Measurement
Procedures, John Wiley & Sons (1986)
- rank(x)
- Returns the rank of a matrix.
The rank is understood here as the an estimation of the number of
linearly independent rows or columns (depending on the size of the
matrix).
Note that numerix.mlab.rank() is not equivalent to Matlab's rank.
This function is!
- rec2csv(r, fname, delimiter=',', formatd=None)
- Save the data from numpy record array r into a comma/space/tab
delimited file. The record array dtype names will be used for
column headers.
fname - can be a filename or a file handle. Support for gzipped
files is automatic, if the filename ends in .gz
- rec2gtk(r, formatd=None, rownum=0, autowin=True)
- save record array r to excel pyExcelerator worksheet ws
starting at rownum. if ws is string like, assume it is a
filename and save to it
formatd is a dictionary mapping dtype name -> FormatXL instances
This function creates a SortedStringsScrolledWindow (derived
from gtk.ScrolledWindow) and returns it. if autowin is True,
a gtk.Window is created, attached to the
SortedStringsScrolledWindow instance, shown and returned. If
autowin=False, the caller is responsible for adding the
SortedStringsScrolledWindow instance to a gtk widget and
showing it.
- rec_append_field(rec, name, arr, dtype=None)
- return a new record array with field name populated with data from array arr
- rec_drop_fields(rec, names)
- return a new numpy record array with fields in names dropped
- rec_join(key, r1, r2)
- join record arrays r1 and r2 on key; key is a tuple of field
names. if r1 and r2 have equal values on all the keys in the key
tuple, then their fields will be merged into a new record array
containing the union of the fields of r1 and r2
- rem(x, y)
- Remainder after division.
rem(x,y) is equivalent to x - y.*fix(x./y) in case y is not zero.
By convention (but contrary to numpy), rem(x,0) returns None.
This also differs from numpy.remainder, which uses floor instead of
fix.
- rk4(derivs, y0, t)
- Integrate 1D or ND system of ODEs from initial state y0 at sample
times t. derivs returns the derivative of the system and has the
signature
dy = derivs(yi, ti)
Example 1 :
## 2D system
def derivs6(x,t):
d1 = x[0] + 2*x[1]
d2 = -3*x[0] + 4*x[1]
return (d1, d2)
dt = 0.0005
t = arange(0.0, 2.0, dt)
y0 = (1,2)
yout = rk4(derivs6, y0, t)
Example 2:
## 1D system
alpha = 2
def derivs(x,t):
return -alpha*x + exp(-t)
y0 = 1
yout = rk4(derivs, y0, t)
If you have access to scipy, you should probably be using the
scipy.integrate tools rather than this function.
- rms_flat(a)
- Return the root mean square of all the elements of a, flattened out.
- safe_isnan(x)
- isnan for arbitrary types
- save(fname, X, fmt='%.18e', delimiter=' ')
- Save the data in X to file fname using fmt string to convert the
data to strings
fname can be a filename or a file handle. If the filename ends in .gz,
the file is automatically saved in compressed gzip format. The load()
command understands gzipped files transparently.
Example usage:
save('test.out', X) # X is an array
save('test1.out', (x,y,z)) # x,y,z equal sized 1D arrays
save('test2.out', x) # x is 1D
save('test3.out', x, fmt='%1.4e') # use exponential notation
delimiter is used to separate the fields, eg delimiter ',' for
comma-separated values
- segments_intersect(s1, s2)
- Return True if s1 and s2 intersect.
s1 and s2 are defined as
s1: (x1, y1), (x2, y2)
s2: (x3, y3), (x4, y4)
- slopes(x, y)
- SLOPES calculate the slope y'(x) Given data vectors X and Y SLOPES
calculates Y'(X), i.e the slope of a curve Y(X). The slope is
estimated using the slope obtained from that of a parabola through
any three consecutive points.
This method should be superior to that described in the appendix
of A CONSISTENTLY WELL BEHAVED METHOD OF INTERPOLATION by Russel
W. Stineman (Creative Computing July 1980) in at least one aspect:
Circles for interpolation demand a known aspect ratio between x-
and y-values. For many functions, however, the abscissa are given
in different dimensions, so an aspect ratio is completely
arbitrary.
The parabola method gives very similar results to the circle
method for most regular cases but behaves much better in special
cases
Norbert Nemec, Institute of Theoretical Physics, University or
Regensburg, April 2006 Norbert.Nemec at physik.uni-regensburg.de
(inspired by a original implementation by Halldor Bjornsson,
Icelandic Meteorological Office, March 2006 halldor at vedur.is)
- specgram(x, NFFT=256, Fs=2, detrend=<function detrend_none at 0x84b3cdc>, window=<function window_hanning at 0x84b3b8c>, noverlap=128)
- Compute a spectrogram of data in x. Data are split into NFFT
length segements and the PSD of each section is computed. The
windowing function window is applied to each segment, and the
amount of overlap of each segment is specified with noverlap.
window can be a function or a vector of length NFFT. To create
window vectors see numpy.blackman, numpy.hamming, numpy.bartlett,
scipy.signal, scipy.signal.get_window etc.
See psd for more info. (psd differs in the default overlap;
in returning the mean of the segment periodograms; and in not
returning times.)
If x is real (i.e. non-Complex) only the positive spectrum is
given. If x is Complex then the complete spectrum is given.
returns:
Pxx - 2-D array, columns are the periodograms of
successive segments
freqs - 1-D array of frequencies corresponding to
the rows in Pxx
t - 1-D array of times corresponding to midpoints of
segments.
- sqrtm(x)
- Returns the square root of a square matrix.
This means that s=sqrtm(x) implies s*s = x.
Note that s and x are matrices.
- stineman_interp(xi, x, y, yp=None)
- STINEMAN_INTERP Well behaved data interpolation. Given data
vectors X and Y, the slope vector YP and a new abscissa vector XI
the function stineman_interp(xi,x,y,yp) uses Stineman
interpolation to calculate a vector YI corresponding to XI.
Here's an example that generates a coarse sine curve, then
interpolates over a finer abscissa:
x = linspace(0,2*pi,20); y = sin(x); yp = cos(x)
xi = linspace(0,2*pi,40);
yi = stineman_interp(xi,x,y,yp);
plot(x,y,'o',xi,yi)
The interpolation method is described in the article A
CONSISTENTLY WELL BEHAVED METHOD OF INTERPOLATION by Russell
W. Stineman. The article appeared in the July 1980 issue of
Creative Computing with a note from the editor stating that while
they were
not an academic journal but once in a while something serious
and original comes in adding that this was
"apparently a real solution" to a well known problem.
For yp=None, the routine automatically determines the slopes using
the "slopes" routine.
X is assumed to be sorted in increasing order
For values xi[j] < x[0] or xi[j] > x[-1], the routine tries a
extrapolation. The relevance of the data obtained from this, of
course, questionable...
original implementation by Halldor Bjornsson, Icelandic
Meteorolocial Office, March 2006 halldor at vedur.is
completely reworked and optimized for Python by Norbert Nemec,
Institute of Theoretical Physics, University or Regensburg, April
2006 Norbert.Nemec at physik.uni-regensburg.de
- sum_flat(a)
- Return the sum of all the elements of a, flattened out.
It uses a.flat, and if a is not contiguous, a call to ravel(a) is made.
- trapz(x, y)
- Trapezoidal integral of y(x).
- vander(*args, **kwargs)
- X = vander(x,N=None)
The Vandermonde matrix of vector x. The i-th column of X is the
the i-th power of x. N is the maximum power to compute; if N is
None it defaults to len(x).
- window_hanning(x)
- return x times the hanning window of len(x)
- window_none(x)
- No window function; simply return x
- zeros_like(a)
- Return an array of zeros of the shape and typecode of a.
|