| |
- 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.
- arange(...)
- arange(start, stop=None, step=1, typecode=None)
Just like range() except it returns an array whose type can be
specified by the keyword argument typecode.
- array(...)
- array(sequence, typecode=None, copy=1, savespace=0) will return a new array formed from the given (potentially nested) sequence with type given by typecode. If no typecode is given, then the type will be determined as the minimum type required to hold the objects in sequence. If copy is zero and sequence is already an array, a reference will be returned. If savespace is nonzero, the new array will maintain its precision in operations.
- arrayrange = arange(...)
- arange(start, stop=None, step=1, typecode=None)
Just like range() except it returns an array whose type can be
specified by the keyword argument typecode.
- 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, center columns rather than rows
- choose(...)
- choose(a, (b1,b2,...))
- cohere(x, y, NFFT=256, Fs=2, detrend=<function detrend_none>, window=<function window_hanning>, noverlap=0)
- cohere 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, windowm 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>, window=<function window_hanning>, noverlap=0, preferSpeedOverMemory=True, progressCallback=<function donothing_callback>, returnPxx=False)
- Cxy, Phase, freqs = cohere_pairs( X, ij, ...)
Compute the coherence for all pairs in ij. X is a
numSamples,numCols Numeric 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.
- corrcoef(*args)
- corrcoef(X) where X is a matrix returns a matrix of correlation
coefficients for each row of X.
corrcoef(x,y) where x and y are vectors returns the matrix or
correlation coefficients for x and y.
Numeric arrays can be real or complex
The correlation matrix is defined from the covariance matrix C as
r(i,j) = C[i,j] / (C[i,i]*C[j,j])
- cross_correlate(...)
- cross_correlate(a,v, mode=0)
- csd(x, y, NFFT=256, Fs=2, detrend=<function detrend_none>, window=<function window_hanning>, 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 a power of 2
Returns the tuple Pxy, freqs
Refs:
Bendat & Piersol -- Random Data: Analysis and Measurement
Procedures, John Wiley & Sons (1986)
- detrend(x, key=None)
- detrend_linear(x)
- Return x minus best fit line; 'linear' detrending
- detrend_mean(x)
- Return x minus the mean(x)
- detrend_none(x)
- Return x: no detrending
- 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 hist
Compare S with analytic calculation for a Gaussian
x = mu + sigma*randn(200000)
Sanalytic = 0.5 * ( 1.0 + log(2*pi*sigma**2.0) )
- find(condition)
- Return the indices where 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.
- fromstring(...)
- fromstring(string, typecode='l', count=-1) returns a new 1d array initialized from the raw binary data in string. If count is positive, the new array will have count elements, otherwise it's size is determined by the size of string.
- 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
Credits: the Numeric 22 documentation
- levypdf(x, gamma, alpha)
- Returm the levy pdf evaluated at x for params gamma, alpha
- linspace(xmin, xmax, N)
- longest_contiguous_ones(x)
- return the indicies of the longest stretch of contiguous ones in x,
assuming x is a vector of zeros and ones.
- longest_ones(x)
- return the indicies 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
- mean(x, dim=None)
- meshgrid(x, y)
- For vectors x, y with lengths Nx=len(x) and Ny=len(y), return X, Y
where X and Y are (Ny, Nx) shaped arrays with the elements of x
and y repeated to fill the matrix
EG,
[X, Y] = meshgrid([1,2,3], [4,5,6,7])
X =
1 2 3
1 2 3
1 2 3
1 2 3
Y =
4 4 4
5 5 5
6 6 6
7 7 7
- 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.
- 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)).
- 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.
- 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.
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(p, x)
- 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
percentil 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
- prepca(P, frac=0)
- Compute the principal components of P. P is a numVars x
numObservations numeric array. frac is the minimum fraction of
variance that a component must contain to be included
Return value are
Pcomponents : a num components x num observations numeric array
Trans : the weights matrix, ie, Pcomponents = Trans*P
fracVar : the fraction of the variance accounted for by each
component returned
- psd(x, NFFT=256, Fs=2, detrend=<function detrend_none>, window=<function window_hanning>, 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.
-- NFFT must be a power of 2
-- detrend and window are functions, unlike in matlab where they are
vectors.
-- 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 MLab.rank() is not equivalent to Matlab's rank.
This function is!
- 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, rem(x,0) returns None.
We keep the convention by Matlab:
"The input x and y must be real arrays of the same size, or real scalars."
- reshape(...)
- reshape(a, (d1, d2, ..., dn)). Change the shape of a to be an n-dimensional array with dimensions given by d1...dn. Note: the size specified for the new array must be exactly equal to the size of the old one or an error will occur.
- 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
# Numeric solution
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)
- searchsorted = binarysearch(...)
- binarysearch(a,v)
- specgram(x, NFFT=256, Fs=2, detrend=<function detrend_none>, window=<function window_hanning>, 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
See pdf for more info.
The returned times are the midpoints of the intervals over which
the ffts are calculated
- 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.
- take(...)
- take(a, indices, axis=0). Selects the elements in indices from array a along the given axis.
- trapz(x, y)
- vander(x, N=None)
- 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(...)
- zeros((d1,...,dn),typecode='l',savespace=0) will return a new array of shape (d1,...,dn) and type typecode with all it's entries initialized to zero. If savespace is nonzero the array will be a spacesaver array.
|