diff options
author | Travis Oliphant <oliphant@enthought.com> | 2005-12-28 03:17:55 +0000 |
---|---|---|
committer | Travis Oliphant <oliphant@enthought.com> | 2005-12-28 03:17:55 +0000 |
commit | 922f7cf07fcce95f510222b464cdc757f40ef57f (patch) | |
tree | ddc75cce90be2bff70a0c2863c1b4996f1aadf34 | |
parent | 4b61fd0dc145083b566028edc691c5f2d1d5936f (diff) | |
download | numpy-922f7cf07fcce95f510222b464cdc757f40ef57f.tar.gz |
Added an mlab so that there is one file to replace the old MLab functionality.
-rw-r--r-- | scipy/base/convertcode.py | 2 | ||||
-rw-r--r-- | scipy/base/function_base.py | 171 | ||||
-rw-r--r-- | scipy/base/ma.py | 3 | ||||
-rw-r--r-- | scipy/base/mlab.py | 14 | ||||
-rw-r--r-- | scipy/base/oldnumeric.py | 64 | ||||
-rw-r--r-- | scipy/base/shape_base.py | 5 | ||||
-rw-r--r-- | scipy/base/src/arraymethods.c | 1 | ||||
-rw-r--r-- | scipy/base/tests/test_function_base.py | 10 | ||||
-rw-r--r-- | scipy/base/twodim_base.py | 4 |
9 files changed, 208 insertions, 66 deletions
diff --git a/scipy/base/convertcode.py b/scipy/base/convertcode.py index 1d93b94ed..792ed384c 100644 --- a/scipy/base/convertcode.py +++ b/scipy/base/convertcode.py @@ -99,7 +99,7 @@ def fromstr(filestr): filestr, fromall1 = changeimports(filestr, 'Precision', 'scipy.base') filestr, fromall2 = changeimports(filestr, 'numerix', 'scipy.base') filestr, fromall3 = changeimports(filestr, 'scipy_base', 'scipy.base') - filestr, fromall3 = changeimports(filestr, 'MLab', 'scipy.corelinalg') + filestr, fromall3 = changeimports(filestr, 'MLab', 'scipy.base.mlab') filestr, fromall3 = changeimports(filestr, 'LinearAlgebra', 'scipy.corelinalg') filestr, fromall3 = changeimports(filestr, 'RNG', 'scipy.random') filestr, fromall3 = changeimports(filestr, 'RandomArray', 'scipy.random') diff --git a/scipy/base/function_base.py b/scipy/base/function_base.py index 55f96fd5e..03d02e5c7 100644 --- a/scipy/base/function_base.py +++ b/scipy/base/function_base.py @@ -1,22 +1,25 @@ __all__ = ['logspace', 'linspace', 'round_', - 'select', 'piecewise', 'trim_zeros', 'alen', 'amax', 'amin', 'ptp', - 'copy', 'iterable', 'base_repr', 'binary_repr', 'prod', 'cumprod', + 'select', 'piecewise', 'trim_zeros', + 'copy', 'iterable', 'base_repr', 'binary_repr', 'diff', 'gradient', 'angle', 'unwrap', 'sort_complex', 'disp', 'unique', 'extract', 'insert', 'nansum', 'nanmax', 'nanargmax', 'nanargmin', 'nanmin', 'vectorize', 'asarray_chkfinite', 'average', - 'histogram', 'bincount', 'digitize'] + 'histogram', 'bincount', 'digitize', 'cov', 'corrcoef', 'msort', 'median', + 'sinc', 'hamming', 'hanning', 'bartlett', 'blackman', 'kaiser', 'trapz' + ] import types import math, operator import numeric as _nx from numeric import ones, zeros, arange, concatenate, array, asarray, empty -from numeric import ScalarType +from numeric import ScalarType, dot, where from umath import pi, multiply, add, arctan2, maximum, minimum, frompyfunc, \ - isnan, absolute + isnan, absolute, cos, less_equal, sqrt, sin from oldnumeric import ravel, nonzero, choose, \ - sometrue, alltrue, reshape, any, all, typecodes, ArrayType + sometrue, alltrue, reshape, any, all, typecodes, ArrayType, squeeze from type_check import ScalarType, isscalar -from shape_base import squeeze, atleast_1d +from shape_base import atleast_1d +from twodim_base import diag from scipy.base._compiled_base import digitize, bincount, _insert from ufunclike import sign @@ -65,7 +68,6 @@ def base_repr (number, base=2, padding=0): #end Fernando's utilities - def linspace(start, stop, num=50, endpoint=True, retstep=False): """Return evenly spaced numbers. @@ -196,12 +198,6 @@ def average(a, axis=0, weights=None, returned=False): else: return n/d - -def isaltered(): - val = str(type(_nx.array([1]))) - return 'scipy' in val - - def asarray_chkfinite(a): """Like asarray, but check that no NaNs or Infs are present. """ @@ -329,35 +325,6 @@ def copy(a): return array(a, copy=True) # Basic operations -def amax(a, axis=-1): - """Return the maximum of 'a' along dimension axis. - """ - return asarray(a).max(axis) - -def amin(a, axis=-1): - """Return the minimum of a along dimension axis. - """ - return asarray(a).min(axis) - -def alen(a): - """Return the length of a Python object interpreted as an array - """ - return len(asarray(a)) - -def ptp(a, axis=-1): - """Return maximum - minimum along the the given dimension - """ - return asarray(a).ptp(axis) - -def prod(a, axis=-1): - """Return the product of the elements along the given axis - """ - return asarray(a).prod(axis) - -def cumprod(a, axis=-1): - """Return the cumulative product of the elments along the given axis - """ - return asarray(a).cumprod(axis) def gradient(f, *varargs): """Calculate the gradient of an N-dimensional scalar function. @@ -722,3 +689,121 @@ def round_(a, decimals=0): else: return multiply(a, s) + +def cov(m,y=None, rowvar=0, bias=0): + """Estimate the covariance matrix. + + If m is a vector, return the variance. For matrices where each row + is an observation, and each column a variable, return the covariance + matrix. Note that in this case diag(cov(m)) is a vector of + variances for each column. + + cov(m) is the same as cov(m, m) + + Normalization is by (N-1) where N is the number of observations + (unbiased estimate). If bias is 1 then normalization is by N. + + If rowvar is zero, then each row is a variable with + observations in the columns. + """ + if y is None: + y = asarray(m) + else: + y = asarray(y) + m = asarray(m) + if rowvar: + m = m.transpose() + y = y.transpose() + if (m.shape[0] == 1): + m = m.transpose() + if (y.shape[0] == 1): + y = y.transpose() + N = m.shape[0] + if (y.shape[0] != N): + raise ValueError, "x and y must have the same number of observations." + m = m - m.mean(axis=0) + y = y - y.mean(axis=0) + if bias: + fact = N*1.0 + else: + fact = N-1.0 + + val = squeeze(dot(m.transpose(),y.conj()) / fact) + return val + +def corrcoef(x, y=None): + """The correlation coefficients + """ + c = cov(x, y) + d = diag(c) + return c/sqrt(multiply.outer(d,d)) + +def blackman(M): + """blackman(M) returns the M-point Blackman window. + """ + n = arange(0,M) + return 0.42-0.5*cos(2.0*pi*n/(M-1)) + 0.08*cos(4.0*pi*n/(M-1)) + +def bartlett(M): + """bartlett(M) returns the M-point Bartlett window. + """ + n = arange(0,M) + return where(less_equal(n,(M-1)/2.0),2.0*n/(M-1),2.0-2.0*n/(M-1)) + +def hanning(M): + """hanning(M) returns the M-point Hanning window. + """ + n = arange(0,M) + return 0.5-0.5*cos(2.0*pi*n/(M-1)) + +def hamming(M): + """hamming(M) returns the M-point Hamming window. + """ + n = arange(0,M) + return 0.54-0.46*cos(2.0*pi*n/(M-1)) + +def kaiser(M,beta): + """kaiser(M, beta) returns a Kaiser window of length M with shape parameter + beta. It depends on scipy.special (in full scipy) for the modified bessel + function i0. + """ + from scipy.special import i0 + n = arange(0,M) + alpha = (M-1)/2.0 + return i0(beta * sqrt(1-((n-alpha)/alpha)**2.0))/i0(beta) + +def sinc(x): + """sinc(x) returns sin(pi*x)/(pi*x) at all points of array x. + """ + y = pi* where(x == 0, 1.0e-20, x) + return sin(y)/y + +def msort(a): + return a.sort(0) + +def median(m): + """median(m) returns a median of m along the first dimension of m. + """ + sorted = msort(m) + if sorted.shape[0] % 2 == 1: + return sorted[int(sorted.shape[0]/2)] + else: + sorted = msort(m) + index=sorted.shape[0]/2 + return (sorted[index-1]+sorted[index])/2.0 + +def trapz(y, x=None, dx=1.0, axis=-1): + """Integrate y(x) using samples along the given axis and the composite + trapezoidal rule. If x is None, spacing given by dx is assumed. + """ + y = asarray(y) + if x is None: + d = dx + else: + d = diff(x,axis=axis) + nd = len(y.shape) + slice1 = [slice(None)]*nd + slice2 = [slice(None)]*nd + slice1[axis] = slice(1,None) + slice2[axis] = slice(None,-1) + return add.reduce(d * (y[slice1]+y[slice2])/2.0,axis) diff --git a/scipy/base/ma.py b/scipy/base/ma.py index 874c62319..691de03dd 100644 --- a/scipy/base/ma.py +++ b/scipy/base/ma.py @@ -12,9 +12,8 @@ import string, types, sys import umath import oldnumeric import function_base -from function_base import amax, amin from numeric import e, pi, newaxis, ndarray -from oldnumeric import typecodes +from oldnumeric import typecodes, amax, amin from numerictypes import * import numeric diff --git a/scipy/base/mlab.py b/scipy/base/mlab.py new file mode 100644 index 000000000..749600d9b --- /dev/null +++ b/scipy/base/mlab.py @@ -0,0 +1,14 @@ +# This module is for compatibility only. All functions are defined elsewhere. + +from numeric import * + +from twodim_base import eye, tri, diag, fliplr, flipud, rot90, tril, triu +from oldnumeric import amax as max +from oldnumeric import amin as min +from function_base import msort, median, trapz, diff, cov, corrcoef, kaiser, blackman, \ + bartlett, hanning, hamming, sinc, angle +from oldnumeric import cumsum, ptp, mean, std, prod, cumprod, squeeze +from polynomial import roots + +from scipy.random import rand, randn +from scipy.corelinalg import eig, svd diff --git a/scipy/base/oldnumeric.py b/scipy/base/oldnumeric.py index 1980b38e6..6e42209bb 100644 --- a/scipy/base/oldnumeric.py +++ b/scipy/base/oldnumeric.py @@ -19,11 +19,11 @@ __all__ = ['asarray', 'array', 'concatenate', # functions that are now methods 'take', 'reshape', 'choose', 'repeat', 'put', 'putmask', 'swapaxes', 'transpose', 'sort', 'argsort', 'argmax', 'argmin', - 'searchsorted', + 'searchsorted', 'alen', 'resize', 'diagonal', 'trace', 'ravel', 'nonzero', 'shape', - 'compress', 'clip', 'sum', 'product', 'sometrue', 'alltrue', - 'any', 'all', 'cumsum', 'cumproduct', 'ndim', - 'rank', 'size', 'around', + 'compress', 'clip', 'sum', 'product', 'prod', 'sometrue', 'alltrue', + 'any', 'all', 'cumsum', 'cumproduct', 'cumprod', 'ptp', 'ndim', + 'rank', 'size', 'around', 'mean', 'std', 'var', 'squeeze', 'amax', 'amin' ] import multiarray as mu @@ -260,6 +260,10 @@ def resize(a, new_shape): return reshape(a, new_shape) +def squeeze(a): + "Returns a with any ones from the shape of a removed" + return asarray(a).squeeze() + def diagonal(a, offset=0, axis1=0, axis2=1): """diagonal(a, offset=0, axis1=0, axis2=1) returns the given diagonals defined by the last two dimensions of the array. @@ -356,6 +360,36 @@ def cumproduct (x, axis=0, dtype=None): """Sum the array over the given axis.""" return asarray(x).cumprod(axis, dtype) +def ptp(a, axis=0): + """Return maximum - minimum along the the given dimension + """ + return asarray(a).ptp(axis) + +def amax(a, axis=0): + """Return the maximum of 'a' along dimension axis. + """ + return asarray(a).max(axis) + +def amin(a, axis=0): + """Return the minimum of a along dimension axis. + """ + return asarray(a).min(axis) + +def alen(a): + """Return the length of a Python object interpreted as an array + """ + return len(asarray(a)) + +def prod(a, axis=0): + """Return the product of the elements along the given axis + """ + return asarray(a).prod(axis) + +def cumprod(a, axis=0): + """Return the cumulative product of the elments along the given axis + """ + return asarray(a).cumprod(axis) + def ndim(a): try: return a.ndim @@ -368,15 +402,29 @@ def rank (a): """ try: return a.ndim - except: + except AttributeError: return asarray(a).ndim def size (a, axis=None): "Get the number of elements in sequence a, or along a certain axis." - a = asarray(a) if axis is None: - return a.size + try: + return a.size + except AttributeError: + return asarray(a).size else: - return a.shape[axis] + try: + return a.shape[axis] + except AttributeError: + return asarray(a).shape[axis] from function_base import round_ as around + +def mean(a, axis=0, dtype=None): + return asarray(a).mean(axis, dtype) + +def std(a, axis=0, dtype=None): + return asarray(a).std(axis, dtype) + +def var(a, axis=0, dtype=None): + return asarray(a).var(axis, dtype) diff --git a/scipy/base/shape_base.py b/scipy/base/shape_base.py index 4ea8f61a4..e8cc9bcd3 100644 --- a/scipy/base/shape_base.py +++ b/scipy/base/shape_base.py @@ -1,6 +1,6 @@ __all__ = ['atleast_1d','atleast_2d','atleast_3d','vstack','hstack', 'column_stack','dstack','array_split','split','hsplit', - 'vsplit','dsplit','squeeze','apply_over_axes','expand_dims', + 'vsplit','dsplit','apply_over_axes','expand_dims', 'apply_along_axis'] import numeric as _nx @@ -108,9 +108,6 @@ def expand_dims(a, axis): axis = axis + len(shape) + 1 return a.reshape(shape[:axis] + (1,) + shape[axis:]) -def squeeze(a): - "Returns a with any ones from the shape of a removed" - return asarray(a).squeeze() def atleast_1d(*arys): """ Force a sequence of arrays to each be at least 1D. diff --git a/scipy/base/src/arraymethods.c b/scipy/base/src/arraymethods.c index 0410b78b6..18ccc35ee 100644 --- a/scipy/base/src/arraymethods.c +++ b/scipy/base/src/arraymethods.c @@ -1281,7 +1281,6 @@ array_all(PyArrayObject *self, PyObject *args) return PyArray_All(self, axis); } - static char doc_stddev[] = "a.std(axis=None, dtype=None)"; static PyObject * diff --git a/scipy/base/tests/test_function_base.py b/scipy/base/tests/test_function_base.py index e727568a8..77beb14f7 100644 --- a/scipy/base/tests/test_function_base.py +++ b/scipy/base/tests/test_function_base.py @@ -114,7 +114,7 @@ class test_ptp(ScipyTestCase): [4,10.0,5.0], [8,3.0,2.0]] assert_equal(ptp(b,axis=0),[5.0,7.0,7.0]) - assert_equal(ptp(b),[6.0,6.0,6.0]) + assert_equal(ptp(b,axis=-1),[6.0,6.0,6.0]) class test_cumsum(ScipyTestCase): def check_basic(self): @@ -148,7 +148,7 @@ class test_prod(ScipyTestCase): assert_equal(prod(a),26400) assert_array_equal(prod(a2,axis=0), array([50,36,84,180],ctype)) - assert_array_equal(prod(a2),array([24, 1890, 600],ctype)) + assert_array_equal(prod(a2,axis=-1),array([24, 1890, 600],ctype)) class test_cumprod(ScipyTestCase): def check_basic(self): @@ -162,15 +162,15 @@ class test_cumprod(ScipyTestCase): self.failUnlessRaises(ArithmeticError, cumprod, a) self.failUnlessRaises(ArithmeticError, cumprod, a2, 1) self.failUnlessRaises(ArithmeticError, cumprod, a) - else: - assert_array_equal(cumprod(a), + else: + assert_array_equal(cumprod(a,axis=-1), array([1, 2, 20, 220, 1320, 6600, 26400],ctype)) assert_array_equal(cumprod(a2,axis=0), array([[ 1, 2, 3, 4], [ 5, 12, 21, 36], [50, 36, 84, 180]],ctype)) - assert_array_equal(cumprod(a2), + assert_array_equal(cumprod(a2,axis=-1), array([[ 1, 2, 6, 24], [ 5, 30, 210, 1890], [10, 30, 120, 600]],ctype)) diff --git a/scipy/base/twodim_base.py b/scipy/base/twodim_base.py index 3e7e392e8..b21532ea6 100644 --- a/scipy/base/twodim_base.py +++ b/scipy/base/twodim_base.py @@ -36,9 +36,9 @@ def rot90(m, k=1): raise ValueError, "Input must >= 2-d." k = k % 4 if k == 0: return m - elif k == 1: return transpose(fliplr(m)) + elif k == 1: return fliplr(m).transpose() elif k == 2: return fliplr(flipud(m)) - else: return fliplr(transpose(m)) # k==3 + else: return fliplr(m.transpose()) # k==3 def eye(N, M=None, k=0, dtype=int_): """ eye returns a N-by-M 2-d array where the k-th diagonal is all ones, |