updated .travis.yml

moved some funtions from numpy_utils -> misc.
pep8
master
pbrod 9 years ago
parent d989dcfb13
commit 7403d821df

@ -32,6 +32,7 @@ before_install:
- conda config --add channels https://conda.anaconda.org/omnia - conda config --add channels https://conda.anaconda.org/omnia
- conda config --add channels https://conda.anaconda.org/pbrod - conda config --add channels https://conda.anaconda.org/pbrod
- source activate condaenv - source activate condaenv
- sudo apt-get update
- sudo apt-get install gfortran - sudo apt-get install gfortran
# Install packages # Install packages
install: install:

@ -432,7 +432,9 @@ def test_docstrings():
def test_commands(): def test_commands():
import commands import commands
commands.getstatusoutput('preprocess -DFORMAT=html -DDEVICE=screen tutorial.do.txt > tmp_preprocess__tutorial.do.txt') commands.getstatusoutput('preprocess -DFORMAT=html -DDEVICE=screen ' +
'tutorial.do.txt > ' +
'tmp_preprocess__tutorial.do.txt')
if __name__ == '__main__': if __name__ == '__main__':

@ -1841,8 +1841,8 @@ class Kernel(object):
return self.hns(data) return self.hns(data)
name = self.name[:4].lower() name = self.name[:4].lower()
if name == 'epan': # Epanechnikov kernel if name == 'epan': # Epanechnikov kernel
a = (8.0 * (d + 4.0) * (2 * sqrt(pi)) a = (8.0 * (d + 4.0) * (2 * sqrt(pi)) ** d /
** d / sphere_volume(d)) ** (1. / (4.0 + d)) sphere_volume(d)) ** (1. / (4.0 + d))
elif name == 'biwe': # Bi-weight kernel elif name == 'biwe': # Bi-weight kernel
a = 2.7779 a = 2.7779
if d > 2: if d > 2:
@ -3318,8 +3318,8 @@ def kde_demo4(N=50):
f1.plot('b', label='hisj=%g' % kde1.hs) f1.plot('b', label='hisj=%g' % kde1.hs)
x = np.linspace(-4, 4) x = np.linspace(-4, 4)
for loc in [-5, 5]: for loc in [-5, 5]:
plt.plot(x + loc, st.norm.pdf(x, 0, scale=1) plt.plot(x + loc, st.norm.pdf(x, 0, scale=1) / 2, 'k:',
/ 2, 'k:', label='True density') label='True density')
plt.legend() plt.legend()

File diff suppressed because it is too large Load Diff

@ -6,12 +6,13 @@ import collections
import sys import sys
import fractions import fractions
import numpy as np import numpy as np
from numpy import (abs, amax, any, logical_and, arange, linspace, atleast_1d, from numpy import (
array, asarray, broadcast_arrays, ceil, floor, frexp, hypot, meshgrid,
sqrt, arctan2, sin, cos, exp, log, log1p, mod, diff, finfo, abs, amax, any, logical_and, arange, linspace, atleast_1d,
inf, pi, interp, isnan, isscalar, zeros, ones, linalg, asarray, ceil, floor, frexp, hypot,
r_, sign, unique, hstack, vstack, nonzero, where, extract, sqrt, arctan2, sin, cos, exp, log, log1p, mod, diff,
meshgrid) finfo, inf, pi, interp, isnan, isscalar, zeros, ones, linalg,
r_, sign, unique, hstack, vstack, nonzero, where, extract)
from scipy.special import gammaln from scipy.special import gammaln
from scipy.integrate import trapz, simps from scipy.integrate import trapz, simps
import warnings import warnings
@ -22,6 +23,8 @@ try:
except: except:
clib = None clib = None
floatinfo = finfo(float) floatinfo = finfo(float)
_TINY = np.finfo(float).tiny
_EPS = np.finfo(float).eps
__all__ = ['now', 'spaceline', 'narg_smallest', 'args_flat', 'is_numlike', __all__ = ['now', 'spaceline', 'narg_smallest', 'args_flat', 'is_numlike',
@ -29,9 +32,10 @@ __all__ = ['now', 'spaceline', 'narg_smallest', 'args_flat', 'is_numlike',
'parse_kwargs', 'detrendma', 'ecross', 'findcross', 'findextrema', 'parse_kwargs', 'detrendma', 'ecross', 'findcross', 'findextrema',
'findpeaks', 'findrfc', 'rfcfilter', 'findtp', 'findtc', 'findpeaks', 'findrfc', 'rfcfilter', 'findtp', 'findtc',
'findoutliers', 'common_shape', 'argsreduce', 'stirlerr', 'findoutliers', 'common_shape', 'argsreduce', 'stirlerr',
'betaloge', 'gravity', 'nextpow2', 'discretize', 'pol2cart', 'betaloge', 'gravity', 'nextpow2', 'discretize', 'polar2cart',
'cart2pol', 'meshgrid', 'ndgrid', 'trangood', 'tranproc', 'cart2polar', 'meshgrid', 'ndgrid', 'trangood', 'tranproc',
'plot_histgrm', 'num2pistr', 'test_docstrings', 'lazywhere', 'plot_histgrm', 'num2pistr', 'test_docstrings', 'lazywhere',
'piecewise',
'valarray'] 'valarray']
@ -209,23 +213,24 @@ def rotation_matrix(heading, pitch, roll):
''' '''
Examples Examples
>>> import numpy as np
>>> rotation_matrix(heading=0, pitch=0, roll=0) >>> rotation_matrix(heading=0, pitch=0, roll=0)
array([[ 1., 0., 0.], array([[ 1., 0., 0.],
[ 0., 1., 0.], [ 0., 1., 0.],
[ 0., 0., 1.]]) [ 0., 0., 1.]])
>>> np.all(np.abs(rotation_matrix(heading=180, pitch=0, roll=0)- >>> np.all(np.abs(rotation_matrix(heading=180, pitch=0, roll=0)-
... array([[ -1.000000e+00, -1.224647e-16, 0.000000e+00], ... np.array([[ -1.000000e+00, -1.224647e-16, 0.000000e+00],
... [ 1.224647e-16, -1.000000e+00, 0.000000e+00], ... [ 1.224647e-16, -1.000000e+00, 0.000000e+00],
... [ -0.000000e+00, 0.000000e+00, 1.000000e+00]]))<1e-7) ... [ -0.000000e+00, 0.000000e+00, 1.000000e+00]]))<1e-7)
True True
>>> np.all(np.abs(rotation_matrix(heading=0, pitch=180, roll=0)- >>> np.all(np.abs(rotation_matrix(heading=0, pitch=180, roll=0)-
... array([[ -1.000000e+00, 0.000000e+00, 1.224647e-16], ... np.array([[ -1.000000e+00, 0.000000e+00, 1.224647e-16],
... [ -0.000000e+00, 1.000000e+00, 0.000000e+00], ... [ -0.000000e+00, 1.000000e+00, 0.000000e+00],
... [ -1.224647e-16, -0.000000e+00, -1.000000e+00]]))<1e-7) ... [ -1.224647e-16, -0.000000e+00, -1.000000e+00]]))<1e-7)
True True
>>> np.all(np.abs(rotation_matrix(heading=0, pitch=0, roll=180)- >>> np.all(np.abs(rotation_matrix(heading=0, pitch=0, roll=180)-
... array([[ 1.000000e+00, 0.000000e+00, 0.000000e+00], ... np.array([[ 1.000000e+00, 0.000000e+00, 0.000000e+00],
... [ 0.000000e+00, -1.000000e+00, -1.224647e-16], ... [ 0.000000e+00, -1.000000e+00, -1.224647e-16],
... [ -0.000000e+00, 1.224647e-16, -1.000000e+00]]))<1e-7) ... [ -0.000000e+00, 1.224647e-16, -1.000000e+00]]))<1e-7)
True True
@ -235,7 +240,7 @@ def rotation_matrix(heading, pitch, roll):
deg2rad = np.pi / 180 deg2rad = np.pi / 180
H = heading * deg2rad H = heading * deg2rad
P = pitch * deg2rad P = pitch * deg2rad
R = roll * deg2rad # Convert to radians R = roll * deg2rad # Convert to radians
data.put(0, cos(H) * cos(P)) data.put(0, cos(H) * cos(P))
data.put(1, cos(H) * sin(P) * sin(R) - sin(H) * cos(R)) data.put(1, cos(H) * sin(P) * sin(R) - sin(H) * cos(R))
@ -327,13 +332,12 @@ def spaceline(start_point, stop_point, num=10):
[ 2.5 , 0. , 0. ], [ 2.5 , 0. , 0. ],
[ 2.75, 0. , 0. ], [ 2.75, 0. , 0. ],
[ 3. , 0. , 0. ]]) [ 3. , 0. , 0. ]])
''' '''
num = int(num) num = int(num)
e1, e2 = np.atleast_1d(start_point, stop_point) e1, e2 = np.atleast_1d(start_point, stop_point)
e2m1 = e2 - e1 e2m1 = e2 - e1
length = np.sqrt((e2m1 ** 2).sum()) length = np.sqrt((e2m1 ** 2).sum())
# length = sqrt((E2[0]-E1(1))^2 + (E2(2)-E1(2))^2 + (E2(3)-E1(3))^2); # length = sqrt((E2[0]-E1(1))^2 + (E2(2)-E1(2))^2 + (E2(3)-E1(3))^2)
C = e2m1 / length C = e2m1 / length
delta = length / float(num - 1) delta = length / float(num - 1)
return np.array([e1 + n * delta * C for n in range(num)]) return np.array([e1 + n * delta * C for n in range(num)])
@ -400,37 +404,14 @@ def args_flat(*args):
'POS array must be of shape N x 3!') 'POS array must be of shape N x 3!')
return pos, None return pos, None
elif nargin == 3: elif nargin == 3:
x, y, z = broadcast_arrays(*args[:3]) x, y, z = np.broadcast_arrays(*args[:3])
c_shape = x.shape c_shape = x.shape
return np.vstack((x.ravel(), y.ravel(), z.ravel())).T, c_shape return np.vstack((x.ravel(), y.ravel(), z.ravel())).T, c_shape
else: else:
raise ValueError('Number of arguments must be 1 or 3!') raise ValueError('Number of arguments must be 1 or 3!')
def _check_and_adjust_shape(shape, nsub=None): def index2sub(shape, index, order='C'):
s = np.atleast_1d(shape)
ndim = len(s)
if ndim < 1:
raise ValueError('Shape vector must have at least 1 element.')
ndim = len(s)
if nsub is None:
nsub = ndim
if ndim <= nsub: # add trailing singleton dimensions
s = np.hstack([s, np.ones(nsub - ndim, dtype=int)])
else: # Adjust for linear indexing on last element
s = np.hstack([s[:nsub - 1], np.prod(s[nsub - 1:])])
return s
def _sub2index_factor(shape, order='C'):
''' Return multiplier needed for calculating linear index
from multiple subscripts.
'''
step = 1 if order == 'F' else -1 # C order
return np.hstack([1, np.cumprod(shape[::step][:-1])])[::step]
def index2sub(shape, index, nsub=None, order='C'):
''' '''
Returns Multiple subscripts from linear index. Returns Multiple subscripts from linear index.
@ -440,8 +421,6 @@ def index2sub(shape, index, nsub=None, order='C'):
shape of array shape of array
index : index :
linear index into array linear index into array
nsub : int optional
Number of subscripts returned. default nsub=len(shape)
order : {'C','F'}, optional order : {'C','F'}, optional
The order of the linear index. The order of the linear index.
'C' means C (row-major) order. 'C' means C (row-major) order.
@ -468,18 +447,7 @@ def index2sub(shape, index, nsub=None, order='C'):
-------- --------
sub2index sub2index
''' '''
ndx = np.atleast_1d(index) return np.unravel_index(index, shape, order=order)
s = _check_and_adjust_shape(shape, nsub)
k = _sub2index_factor(s, order)
n = len(s)
step = -1 if order == 'F' else 1 # C order
subscripts = [0, ] * n
for i in range(n)[::step]:
vi = np.remainder(ndx, k[i])
subscript = np.array((ndx - vi) / k[i], dtype=int)
subscripts[i] = subscript
ndx = vi
return tuple(subscripts)
def sub2index(shape, *subscripts, **kwds): def sub2index(shape, *subscripts, **kwds):
@ -518,21 +486,7 @@ def sub2index(shape, *subscripts, **kwds):
-------- --------
index2sub index2sub
''' '''
nsub = len(subscripts) return np.ravel_multi_index(subscripts, shape, **kwds)
s = _check_and_adjust_shape(shape, nsub)
k = _sub2index_factor(s, **kwds)
ndx = 0
s0 = np.shape(subscripts[0])
for i, subscript in enumerate(subscripts):
np.testing.assert_equal(s0, np.shape(subscript),
'The subscripts vectors must all ' +
'be of the same shape.')
if (np.any(subscript < 0)) or (np.any(s[i] <= subscript)):
raise IndexError('Out of range subscript.')
ndx = ndx + k[i] * subscript
return ndx
def is_numlike(obj): def is_numlike(obj):
@ -683,12 +637,14 @@ def detrendma(x, L):
Examples Examples
-------- --------
>>> import utilities.numpy_utils as wm
>>> import pylab as plt >>> import pylab as plt
>>> exp = plt.exp; cos = plt.cos; randn = plt.randn >>> exp = plt.exp; cos = plt.cos; randn = plt.randn
>>> x = plt.linspace(0,1,200) >>> x = plt.linspace(0,1,200)
>>> y = exp(x)+cos(5*2*pi*x)+1e-1*randn(x.size) >>> y = exp(x)+cos(5*2*pi*x)+1e-1*randn(x.size)
>>> y0 = detrendma(y,20); tr = y-y0 >>> y0 = wm.detrendma(y,20); tr = y-y0
>>> h = plt.plot(x, y, x, y0, 'r', x, exp(x), 'k', x, tr, 'm') >>> h = plt.plot(x, y, x, y0, 'r', x, exp(x), 'k', x, tr, 'm')
>>> plt.close('all') >>> plt.close('all')
See also See also
@ -744,7 +700,7 @@ def ecross(t, f, ind, v=0):
Example Example
------- -------
>>> from matplotlib import pylab as plt >>> from matplotlib import pylab as plt
>>> import utilities.numpy_utils as wm >>> import wafo.misc as wm
>>> ones = np.ones >>> ones = np.ones
>>> t = np.linspace(0,7*np.pi,250) >>> t = np.linspace(0,7*np.pi,250)
>>> x = np.sin(t) >>> x = np.sin(t)
@ -752,8 +708,8 @@ def ecross(t, f, ind, v=0):
>>> ind >>> ind
array([ 9, 25, 80, 97, 151, 168, 223, 239]) array([ 9, 25, 80, 97, 151, 168, 223, 239])
>>> t0 = wm.ecross(t,x,ind,0.75) >>> t0 = wm.ecross(t,x,ind,0.75)
>>> np.abs(t0 - np.array([ 0.84910514, 2.2933879, 7.13205663, 8.57630119, >>> np.abs(t0 - np.array([0.84910514, 2.2933879 , 7.13205663, 8.57630119,
... 13.41484739, 14.85909194, 19.69776067, 21.14204343]))<1e-7 ... 13.41484739, 14.85909194, 19.69776067, 21.14204343]))<1e-7
array([ True, True, True, True, True, True, True, True], dtype=bool) array([ True, True, True, True, True, True, True, True], dtype=bool)
>>> a = plt.plot(t, x, '.', t[ind], x[ind], 'r.', t, ones(t.shape)*0.75, >>> a = plt.plot(t, x, '.', t[ind], x[ind], 'r.', t, ones(t.shape)*0.75,
@ -767,8 +723,8 @@ def ecross(t, f, ind, v=0):
# Tested on: Python 2.5 # Tested on: Python 2.5
# revised pab Feb2004 # revised pab Feb2004
# By pab 18.06.2001 # By pab 18.06.2001
return t[ind] + (v - f[ind]) * (t[ind + 1] - t[ind]) / \ return (t[ind] + (v - f[ind]) * (t[ind + 1] - t[ind]) /
(f[ind + 1] - f[ind]) (f[ind + 1] - f[ind]))
def _findcross(xn): def _findcross(xn):
@ -806,6 +762,13 @@ def _findcross(xn):
return ind return ind
def xor(a, b):
"""
Return True only when inputs differ.
"""
return a ^ b
def findcross(x, v=0.0, kind=None): def findcross(x, v=0.0, kind=None):
''' '''
Return indices to level v up and/or downcrossings of a vector Return indices to level v up and/or downcrossings of a vector
@ -872,20 +835,19 @@ def findcross(x, v=0.0, kind=None):
t_0 = int(xn[ind[0] + 1] < 0) t_0 = int(xn[ind[0] + 1] < 0)
ind = ind[t_0::2] ind = ind[t_0::2]
elif kind in ('dw', 'uw', 'tw', 'cw'): elif kind in ('dw', 'uw', 'tw', 'cw'):
# make sure that the first is a level v down-crossing # make sure the first is a level v down-crossing
# if kind=='dw' or kind=='tw' # if wdef=='dw' or wdef=='tw'
# or that the first is a level v up-crossing # or make sure the first is a level v up-crossing
# if kind=='uw' or kind=='cw' # if wdef=='uw' or wdef=='cw'
xor = lambda a, b: a ^ b
first_is_down_crossing = int(xn[ind[0]] > xn[ind[0] + 1]) first_is_down_crossing = int(xn[ind[0]] > xn[ind[0] + 1])
if xor(first_is_down_crossing, kind in ('dw', 'tw')): if xor(first_is_down_crossing, kind in ('dw', 'tw')):
ind = ind[1::] ind = ind[1::]
n_c = ind.size # number of level v crossings
# make sure the number of troughs and crests are according to the # make sure the number of troughs and crests are according to the
# wavedef, i.e., make sure length(ind) is odd if dw or uw # wavedef, i.e., make sure length(ind) is odd if dw or uw
# and even if tw or cw # and even if tw or cw
is_odd = mod(n_c, 2) is_odd = mod(ind.size, 2)
if xor(is_odd, kind in ('dw', 'uw')): if xor(is_odd, kind in ('dw', 'uw')):
ind = ind[:-1] ind = ind[:-1]
else: else:
@ -1041,7 +1003,7 @@ def findrfc_astm(tp):
return sig_rfc return sig_rfc
def findrfc(tp, hmin=0.0, method='clib'): def findrfc(tp, h=0.0, method='clib'):
''' '''
Return indices to rainflow cycles of a sequence of TP. Return indices to rainflow cycles of a sequence of TP.
@ -1064,10 +1026,10 @@ def findrfc(tp, hmin=0.0, method='clib'):
Example: Example:
-------- --------
>>> import pylab as plt >>> import matplotlib.pyplot as plt
>>> import utilities.numpy_utils as wm >>> import utilities.numpy_utils as wm
>>> t = plt.linspace(0,7*np.pi,250) >>> t = np.linspace(0,7*np.pi,250)
>>> x = plt.sin(t)+0.1*np.sin(50*t) >>> x = np.sin(t)+0.1*np.sin(50*t)
>>> ind = wm.findextrema(x) >>> ind = wm.findextrema(x)
>>> ti, tp = t[ind], x[ind] >>> ti, tp = t[ind], x[ind]
@ -1127,7 +1089,7 @@ def findrfc(tp, hmin=0.0, method='clib'):
Tmi = Tstart + 2 * j Tmi = Tstart + 2 * j
j -= 1 j -= 1
if (xminus >= xplus): if (xminus >= xplus):
if (y[2 * i + 1] - xminus >= hmin): if (y[2 * i + 1] - xminus >= h):
ind[ix] = Tmi ind[ix] = Tmi
ix += 1 ix += 1
ind[ix] = (Tstart + 2 * i + 1) ind[ix] = (Tstart + 2 * i + 1)
@ -1143,7 +1105,7 @@ def findrfc(tp, hmin=0.0, method='clib'):
Tpl = (Tstart + 2 * j + 2) Tpl = (Tstart + 2 * j + 2)
j += 1 j += 1
else: else:
if ((y[2 * i + 1] - xminus) >= hmin): if ((y[2 * i + 1] - xminus) >= h):
ind[ix] = Tmi ind[ix] = Tmi
ix += 1 ix += 1
ind[ix] = (Tstart + 2 * i + 1) ind[ix] = (Tstart + 2 * i + 1)
@ -1154,12 +1116,12 @@ def findrfc(tp, hmin=0.0, method='clib'):
# goto L180 # goto L180
# L170: # L170:
if (xplus <= xminus): if (xplus <= xminus):
if ((y[2 * i + 1] - xminus) >= hmin): if ((y[2 * i + 1] - xminus) >= h):
ind[ix] = Tmi ind[ix] = Tmi
ix += 1 ix += 1
ind[ix] = (Tstart + 2 * i + 1) ind[ix] = (Tstart + 2 * i + 1)
ix += 1 ix += 1
elif ((y[2 * i + 1] - xplus) >= hmin): elif ((y[2 * i + 1] - xplus) >= h):
ind[ix] = (Tstart + 2 * i + 1) ind[ix] = (Tstart + 2 * i + 1)
ix += 1 ix += 1
ind[ix] = Tpl ind[ix] = Tpl
@ -1169,7 +1131,7 @@ def findrfc(tp, hmin=0.0, method='clib'):
# iy=i # iy=i
# /* for i */ # /* for i */
else: else:
ind, ix = clib.findrfc(y, hmin) ind, ix = clib.findrfc(y, h)
return np.sort(ind[:ix]) return np.sort(ind[:ix])
@ -1271,13 +1233,8 @@ def mctp2rfc(fmM, fMm=None):
fx = NN * (A / (1 - B * A) * e) fx = NN * (A / (1 - B * A) * e)
else: else:
rh = np.eye(A.shape[0]) - np.dot(B, A) rh = np.eye(A.shape[0]) - np.dot(B, A)
fx = np.dot( # least squares
NN, fx = np.dot(NN, np.dot(A, linalg.solve(rh, e)))
np.dot(
A,
linalg.solve(
rh,
e))) # least squares
# end # end
# end # end
f_rfc[N - 1 - k, k - i] = fx + DRFC f_rfc[N - 1 - k, k - i] = fx + DRFC
@ -1339,19 +1296,29 @@ def rfcfilter(x, h, method=0):
Examples: Examples:
--------- ---------
# 1. Filtered signal y is the turning points of x. # 1. Filtered signal y is the turning points of x.
>>> import utilities.data >>> import utilities.data as data
>>> import utilities.numpy_utils as wm >>> import utilities.numpy_utils as wm
>>> x = utilities.data.sea() >>> x = data.sea()
>>> y = wm.rfcfilter(x[:,1], h=0, method=1) >>> y = wm.rfcfilter(x[:,1], h=0, method=1)
>>> np.all(np.abs(y[0:5]-np.array([-1.2004945 , 0.83950546, -0.09049454, >>> np.all(np.abs(y[0:5]-np.array([-1.2004945 , 0.83950546, -0.09049454,
... -0.02049454, -0.09049454]))<1e-7) ... -0.02049454, -0.09049454]))<1e-7)
True True
>>> y.shape
(2172,)
# 2. This removes all rainflow cycles with range less than 0.5. # 2. This removes all rainflow cycles with range less than 0.5.
>>> y1 = wm.rfcfilter(x[:,1], h=0.5) >>> y1 = wm.rfcfilter(x[:,1], h=0.5)
>>> y1.shape
(863,)
>>> np.all(np.abs(y1[0:5]-np.array([-1.2004945 , 0.83950546, -0.43049454, >>> np.all(np.abs(y1[0:5]-np.array([-1.2004945 , 0.83950546, -0.43049454,
... 0.34950546, -0.51049454]))<1e-7) ... 0.34950546, -0.51049454]))<1e-7)
True True
>>> ind = wm.findtp(x[:,1], h=0.5)
>>> y2 = x[ind,1]
>>> y2[0:5]
array([-1.2004945 , 0.83950546, -0.43049454, 0.34950546, -0.51049454])
>>> y2[-5::]
array([ 0.83950546, -0.64049454, 0.65950546, -1.0004945 , 0.91950546])
See also See also
-------- --------
@ -1364,21 +1331,27 @@ def rfcfilter(x, h, method=0):
j = 0 j = 0
t0 = 0 t0 = 0
y0 = y[t0] y0 = y[t0]
z0 = 0 z0 = 0
def aleb(a, b):
return a <= b
def altb(a, b):
return a < b
if method == 0: if method == 0:
cmpfun1 = lambda a, b: a <= b cmpfun1 = aleb
cmpfun2 = lambda a, b: a < b cmpfun2 = altb
else: else:
cmpfun1 = lambda a, b: a < b cmpfun1 = altb
cmpfun2 = lambda a, b: a <= b cmpfun2 = aleb
# The rainflow filter # The rainflow filter
for tim1, yi in enumerate(y[1::]): for tim1, yi in enumerate(y[1::]):
fpi = y0 + h fpi = y0 + h
fmi = y0 - h fmi = y0 - h
ti = tim1 + 1 ti = tim1 + 1
#yi = y[ti] # yi = y[ti]
if z0 == 0: if z0 == 0:
if cmpfun1(yi, fmi): if cmpfun1(yi, fmi):
@ -1390,7 +1363,7 @@ def rfcfilter(x, h, method=0):
t1, y1 = (t0, y0) if z1 == 0 else (ti, yi) t1, y1 = (t0, y0) if z1 == 0 else (ti, yi)
else: else:
if (((z0 == +1) & cmpfun1(yi, fmi)) | if (((z0 == +1) & cmpfun1(yi, fmi)) |
((z0 == -1) & cmpfun2(yi, fpi))): ((z0 == -1) & cmpfun2(yi, fpi))):
z1 = -1 z1 = -1
elif (((z0 == +1) & cmpfun2(fmi, yi)) | elif (((z0 == +1) & cmpfun2(fmi, yi)) |
((z0 == -1) & cmpfun1(fpi, yi))): ((z0 == -1) & cmpfun1(fpi, yi))):
@ -1417,7 +1390,7 @@ def rfcfilter(x, h, method=0):
t0, y0, z0 = t1, y1, z1 t0, y0, z0 = t1, y1, z1
# end # end
#% Update y if last y0 is greater than (or equal) threshold # Update y if last y0 is greater than (or equal) threshold
if cmpfun1(h, abs(y0 - y[t[j]])): if cmpfun1(h, abs(y0 - y[t[j]])):
j += 1 j += 1
t[j] = t0 t[j] = t0
@ -1456,19 +1429,20 @@ def findtp(x, h=0.0, kind=None):
>>> import pylab as plt >>> import pylab as plt
>>> import utilities.numpy_utils as wm >>> import utilities.numpy_utils as wm
>>> t = np.linspace(0,30,500).reshape((-1,1)) >>> t = np.linspace(0,30,500).reshape((-1,1))
>>> x = np.hstack((t, np.cos(t))) >>> x = np.hstack((t, np.cos(t) + 0.3 * np.sin(5*t)))
>>> x1 = x[0:200,:] >>> x1 = x[0:100,:]
>>> itp = wm.findtp(x1[:,1],0,'Mw') >>> itp = wm.findtp(x1[:,1],0,'Mw')
>>> itph = wm.findtp(x1[:,1],0.3,'Mw') >>> itph = wm.findtp(x1[:,1],0.3,'Mw')
>>> tp = x1[itp,:] >>> tp = x1[itp,:]
>>> tph = x1[itph,:] >>> tph = x1[itph,:]
>>> a = plt.plot(x1[:,0],x1[:,1],tp[:,0],tp[:,1],'ro', >>> a = plt.plot(x1[:,0],x1[:,1],
... tph[:,1],tph[:,1],'k.') ... tp[:,0],tp[:,1],'ro',
... tph[:,0],tph[:,1],'k.')
>>> plt.close('all') >>> plt.close('all')
>>> itp >>> itp
array([105, 157, 199]) array([ 5, 18, 24, 38, 46, 57, 70, 76, 91, 98, 99])
>>> itph >>> itph
array([105]) array([91])
See also See also
--------- ---------
@ -1487,9 +1461,9 @@ def findtp(x, h=0.0, kind=None):
return None return None
# In order to get the exact up-crossing intensity from rfc by # In order to get the exact up-crossing intensity from rfc by
# mm2lc(tp2mm(rfc)) we have to add the indices # mm2lc(tp2mm(rfc)) we have to add the indices to the last value
# to the last value (and also the first if the # (and also the first if the sequence of turning points does not start
# sequence of turning points does not start with a minimum). # with a minimum).
if kind == 'astm': if kind == 'astm':
# the Nieslony approach always put the first loading point as the first # the Nieslony approach always put the first loading point as the first
@ -1510,7 +1484,6 @@ def findtp(x, h=0.0, kind=None):
ind = ind[ind1] ind = ind[ind1]
if kind in ('mw', 'Mw'): if kind in ('mw', 'Mw'):
xor = lambda a, b: a ^ b
# make sure that the first is a Max if wdef == 'Mw' # make sure that the first is a Max if wdef == 'Mw'
# or make sure that the first is a min if wdef == 'mw' # or make sure that the first is a min if wdef == 'mw'
first_is_max = (x[ind[0]] > x[ind[1]]) first_is_max = (x[ind[0]] > x[ind[1]])
@ -1582,11 +1555,8 @@ def findtc(x_in, v=None, kind=None):
return zeros(0, dtype=np.int), zeros(0, dtype=np.int) return zeros(0, dtype=np.int), zeros(0, dtype=np.int)
# determine the number of trough2crest (or crest2trough) cycles # determine the number of trough2crest (or crest2trough) cycles
isodd = mod(n_c, 2) is_even = mod(n_c + 1, 2)
if isodd: n_tc = int((n_c - 1 - is_even) / 2)
n_tc = int((n_c - 1) / 2)
else:
n_tc = int((n_c - 2) / 2)
# allocate variables before the loop increases the speed # allocate variables before the loop increases the speed
ind = zeros(n_c - 1, dtype=np.int) ind = zeros(n_c - 1, dtype=np.int)
@ -1604,16 +1574,16 @@ def findtc(x_in, v=None, kind=None):
# trough # trough
ind[n_c - 2] = x[v_ind[n_c - 2] + 1:v_ind[n_c - 1]].argmin() ind[n_c - 2] = x[v_ind[n_c - 2] + 1:v_ind[n_c - 1]].argmin()
else: # %%%% the first is a up-crossing else: # the first is a up-crossing
for i in xrange(n_tc): for i in xrange(n_tc):
# trough # crest
j = 2 * i j = 2 * i
ind[j] = x[v_ind[j] + 1:v_ind[j + 1] + 1].argmax() ind[j] = x[v_ind[j] + 1:v_ind[j + 1] + 1].argmax()
# crest # trough
ind[j + 1] = x[v_ind[j + 1] + 1:v_ind[j + 2] + 1].argmin() ind[j + 1] = x[v_ind[j + 1] + 1:v_ind[j + 2] + 1].argmin()
if (2 * n_tc + 1 < n_c) and (kind in (None, 'cw')): if (2 * n_tc + 1 < n_c) and (kind in (None, 'cw')):
# trough # crest
ind[n_c - 2] = x[v_ind[n_c - 2] + 1:v_ind[n_c - 1]].argmax() ind[n_c - 2] = x[v_ind[n_c - 2] + 1:v_ind[n_c - 1]].argmax()
return v_ind[:n_c - 1] + ind + 1, v_ind return v_ind[:n_c - 1] + ind + 1, v_ind
@ -1786,9 +1756,8 @@ def findoutliers(x, zcrit=0.0, dcrit=None, ddcrit=None, verbose=False):
if zcrit == 0.: if zcrit == 0.:
print('Found %d consecutive equal values' % indz.size) print('Found %d consecutive equal values' % indz.size)
else: else:
print( print('Found %d consecutive values less than %g apart.' %
'Found %d consecutive values less than %g apart.' % (indz.size, zcrit))
(indz.size, zcrit))
indg = ones(xn.size, dtype=bool) indg = ones(xn.size, dtype=bool)
if ind.size > 1: if ind.size > 1:
@ -1937,7 +1906,7 @@ def stirlerr(n):
Example Example
------- -------
>>> import utilities.numpy_utils as wm >>> import utilities.numpy_utils as wm
>>> np.abs(wm.stirlerr(2)-array([ 0.0413407]))<1e-7 >>> np.abs(wm.stirlerr(2)- 0.0413407)<1e-7
array([ True], dtype=bool) array([ True], dtype=bool)
See also See also
@ -1949,11 +1918,10 @@ def stirlerr(n):
----------- -----------
Catherine Loader (2000). Catherine Loader (2000).
Fast and Accurate Computation of Binomial Probabilities Fast and Accurate Computation of Binomial Probabilities
<http://www.herine.net/stat/software/dbinom.html> <http://lists.gnu.org/archive/html/octave-maintainers/2011-09/pdfK0uKOST642.pdf>
<http://www.citeseer.ist.psu.edu/312695.html>
''' '''
S0 = 0.083333333333333333333 # /* 1/12 */ S0 = 0.083333333333333333333 # /* 1/12 */
S1 = 0.00277777777777777777778 # /* 1/360 */ S1 = 0.00277777777777777777778 # /* 1/360 */
S2 = 0.00079365079365079365079365 # /* 1/1260 */ S2 = 0.00079365079365079365079365 # /* 1/1260 */
S3 = 0.000595238095238095238095238 # /* 1/1680 */ S3 = 0.000595238095238095238095238 # /* 1/1680 */
@ -2016,9 +1984,9 @@ def binomln(z, w):
# log(n!) = stirlerr(n) + log( sqrt(2*pi*n)*(n/exp(1))**n ) # log(n!) = stirlerr(n) + log( sqrt(2*pi*n)*(n/exp(1))**n )
# y = gammaln(z+1)-gammaln(w+1)-gammaln(z-w+1) # y = gammaln(z+1)-gammaln(w+1)-gammaln(z-w+1)
zpw = z - w zpw = z - w
return (stirlerr(z + 1) - stirlerr(w + 1) - 0.5 * log(2 * pi) return (stirlerr(z + 1) - stirlerr(w + 1) - 0.5 * log(2 * pi) -
- (w + 0.5) * log1p(w) + (z + 0.5) * log1p(z) - stirlerr(zpw + 1) (w + 0.5) * log1p(w) + (z + 0.5) * log1p(z) - stirlerr(zpw + 1) -
- (zpw + 0.5) * log1p(zpw) + 1) (zpw + 0.5) * log1p(zpw) + 1)
def betaloge(z, w): def betaloge(z, w):
@ -2052,8 +2020,9 @@ def betaloge(z, w):
''' '''
# y = gammaln(z)+gammaln(w)-gammaln(z+w) # y = gammaln(z)+gammaln(w)-gammaln(z+w)
zpw = z + w zpw = z + w
return (stirlerr(z) + stirlerr(w) + 0.5 * log(2 * pi) + (w - 0.5) * log(w) return (stirlerr(z) + stirlerr(w) + 0.5 * log(2 * pi) +
+ (z - 0.5) * log(z) - stirlerr(zpw) - (zpw - 0.5) * log(zpw)) (w - 0.5) * log(w) + (z - 0.5) * log(z) - stirlerr(zpw) -
(zpw - 0.5) * log(zpw))
# stirlings approximation: # stirlings approximation:
# (-(zpw-0.5).*log(zpw) +(w-0.5).*log(w)+(z-0.5).*log(z) +0.5*log(2*pi)) # (-(zpw-0.5).*log(zpw) +(w-0.5).*log(w)+(z-0.5).*log(z) +0.5*log(2*pi))
@ -2085,7 +2054,7 @@ def gravity(phi=45):
>>> import utilities.numpy_utils as wm >>> import utilities.numpy_utils as wm
>>> import numpy as np >>> import numpy as np
>>> phi = np.linspace(0,45,5) >>> phi = np.linspace(0,45,5)
>>> np.abs(wm.gravity(phi)-array([ 9.78049 , 9.78245014, 9.78803583, >>> np.abs(wm.gravity(phi)-np.array([ 9.78049 , 9.78245014, 9.78803583,
... 9.79640552, 9.80629387]))<1.e-7 ... 9.79640552, 9.80629387]))<1.e-7
array([ True, True, True, True, True], dtype=bool) array([ True, True, True, True, True], dtype=bool)
@ -2104,8 +2073,81 @@ def gravity(phi=45):
''' '''
phir = phi * pi / 180. # change from degrees to radians phir = phi * pi / 180. # change from degrees to radians
return 9.78049 * \ return 9.78049 * (1. + 0.0052884 * sin(phir) ** 2. -
(1. + 0.0052884 * sin(phir) ** 2. - 0.0000059 * sin(2 * phir) ** 2.) 0.0000059 * sin(2 * phir) ** 2.)
def dea3(v0, v1, v2):
'''
Extrapolate a slowly convergent sequence
Parameters
----------
v0, v1, v2 : array-like
3 values of a convergent sequence to extrapolate
Returns
-------
result : array-like
extrapolated value
abserr : array-like
absolute error estimate
Description
-----------
DEA3 attempts to extrapolate nonlinearly to a better estimate
of the sequence's limiting value, thus improving the rate of
convergence. The routine is based on the epsilon algorithm of
P. Wynn, see [1]_.
Example
-------
# integrate sin(x) from 0 to pi/2
>>> import numpy as np
>>> import numdifftools as nd
>>> Ei= np.zeros(3)
>>> linfun = lambda k : np.linspace(0,np.pi/2.,2.**(k+5)+1)
>>> for k in np.arange(3):
... x = linfun(k)
... Ei[k] = np.trapz(np.sin(x),x)
>>> [En, err] = nd.dea3(Ei[0], Ei[1], Ei[2])
>>> truErr = Ei-1.
>>> (truErr, err, En)
(array([ -2.00805680e-04, -5.01999079e-05, -1.25498825e-05]),
array([ 0.00020081]), array([ 1.]))
See also
--------
dea
Reference
---------
.. [1] C. Brezinski (1977)
"Acceleration de la convergence en analyse numerique",
"Lecture Notes in Math.", vol. 584,
Springer-Verlag, New York, 1977.
'''
E0, E1, E2 = np.atleast_1d(v0, v1, v2)
abs = np.abs # @ReservedAssignment
max = np.maximum # @ReservedAssignment
delta2, delta1 = E2 - E1, E1 - E0
err2, err1 = abs(delta2), abs(delta1)
tol2, tol1 = max(abs(E2), abs(E1)) * _EPS, max(abs(E1), abs(E0)) * _EPS
with warnings.catch_warnings():
warnings.simplefilter("ignore") # ignore division by zero and overflow
ss = 1.0 / delta2 - 1.0 / delta1
smallE2 = (abs(ss * E1) <= 1.0e-3).ravel()
result = 1.0 * E2
abserr = err1 + err2 + abs(E2) * _EPS * 10.0
converged = (err1 <= tol1) & (err2 <= tol2).ravel() | smallE2
k4, = (1 - converged).nonzero()
if k4.size > 0:
result[k4] = E1[k4] + 1.0 / ss[k4]
abserr[k4] = err1[k4] + err2[k4] + abs(result[k4] - E2[k4])
return result, abserr
def nextpow2(x): def nextpow2(x):
@ -2176,8 +2218,6 @@ def _discretize_linear(fun, a, b, tol=0.005, n=5):
''' '''
Automatic discretization of function, linear gridding Automatic discretization of function, linear gridding
''' '''
tiny = floatinfo.tiny
x = linspace(a, b, n) x = linspace(a, b, n)
y = fun(x) y = fun(x)
@ -2192,7 +2232,7 @@ def _discretize_linear(fun, a, b, tol=0.005, n=5):
x = linspace(a, b, n) x = linspace(a, b, n)
y = fun(x) y = fun(x)
y00 = interp(x, x0, y0) y00 = interp(x, x0, y0)
err = 0.5 * amax(abs((y00 - y) / (abs(y00 + y) + tiny))) err = 0.5 * amax(abs((y00 - y) / (abs(y00 + y) + _TINY)))
return x, y return x, y
@ -2200,7 +2240,6 @@ def _discretize_adaptive(fun, a, b, tol=0.005, n=5):
''' '''
Automatic discretization of function, adaptive gridding. Automatic discretization of function, adaptive gridding.
''' '''
tiny = floatinfo.tiny
n += (mod(n, 2) == 0) # make sure n is odd n += (mod(n, 2) == 0) # make sure n is odd
x = linspace(a, b, n) x = linspace(a, b, n)
fx = fun(x) fx = fun(x)
@ -2222,7 +2261,7 @@ def _discretize_adaptive(fun, a, b, tol=0.005, n=5):
fy = fun(y) fy = fun(y)
fy0 = interp(y, x, fx) fy0 = interp(y, x, fx)
erri = 0.5 * (abs((fy0 - fy) / (abs(fy0 + fy) + tiny))) erri = 0.5 * (abs((fy0 - fy) / (abs(fy0 + fy) + _TINY)))
err = erri.max() err = erri.max()
@ -2281,7 +2320,6 @@ def cart2polar(x, y, z=None):
return t, r return t, r
else: else:
return t, r, z return t, r, z
cart2pol = cart2polar cart2pol = cart2polar
@ -2358,8 +2396,7 @@ def trangood(x, f, min_n=None, min_x=None, max_x=None, max_n=inf):
xn = xo[-1] xn = xo[-1]
x0 = xo[0] x0 = xo[0]
L = float(xn - x0) L = float(xn - x0)
eps = floatinfo.eps if ((nf < min_n) or (max_n < nf) or any(abs(ddx) > 10 * _EPS * (L))):
if ((nf < min_n) or (max_n < nf) or any(abs(ddx) > 10 * eps * (L))):
# pab 07.01.2001: Always choose the stepsize df so that # pab 07.01.2001: Always choose the stepsize df so that
# it is an exactly representable number. # it is an exactly representable number.
# This is important when calculating numerical derivatives and is # This is important when calculating numerical derivatives and is
@ -2439,8 +2476,6 @@ def tranproc(x, f, x0, *xi):
-------- --------
trangood. trangood.
""" """
eps = floatinfo.eps
xo, fo, x0 = atleast_1d(x, f, x0) xo, fo, x0 = atleast_1d(x, f, x0)
xi = atleast_1d(*xi) xi = atleast_1d(*xi)
if not isinstance(xi, list): if not isinstance(xi, list):
@ -2464,10 +2499,11 @@ def tranproc(x, f, x0, *xi):
if N > 0: if N > 0:
y = [y0] y = [y0]
hn = xo[1] - xo[0] hn = xo[1] - xo[0]
if hn ** N < sqrt(eps): if hn ** N < sqrt(_EPS):
warnings.warn('Numerical problems may occur for the derivatives' + msg = ('Numerical problems may occur for the derivatives in ' +
' in tranproc. The sampling of the transformation' + 'tranproc.\n' +
' may be too small.') 'The sampling of the transformation may be too small.')
warnings.warn(msg)
# Transform X with the derivatives of f. # Transform X with the derivatives of f.
fxder = zeros((N, x0.size)) fxder = zeros((N, x0.size))
@ -2504,8 +2540,8 @@ def tranproc(x, f, x0, *xi):
fxder[1] * (3. * xi[1] ** 2. + 4. * xi[0] * xi[1])) fxder[1] * (3. * xi[1] ** 2. + 4. * xi[0] * xi[1]))
y.append(y4) y.append(y4)
if N > 4: if N > 4:
warnings.warn('Transformation of derivatives of' + warnings.warn('Transformation of derivatives of ' +
' order>4 not supported.') 'order>4 not supported.')
return y # y0,y1,y2,y3,y4 return y # y0,y1,y2,y3,y4
@ -2517,10 +2553,11 @@ def good_bins(data=None, range=None, num_bins=None, # @ReservedAssignment
---------- ----------
data : array-like data : array-like
the data the data
range : (float, float), (default data.min(), data.max()) range : (float, float)
minimum and maximum range of bins minimum and maximum range of bins (default data.min(), data.max())
num_bins : scalar integer, (default depending on num_data=len(data)) num_bins : scalar integer
approximate number of bins wanted approximate number of bins wanted
(default depending on num_data=len(data))
odd : bool odd : bool
placement of bins (0 or 1) (default 0) placement of bins (0 or 1) (default 0)
loose : bool loose : bool
@ -2621,14 +2658,14 @@ def plot_histgrm(data, bins=None, range=None, # @ReservedAssignment
if bins is None: if bins is None:
bins = np.ceil(4 * np.sqrt(np.sqrt(len(x)))) bins = np.ceil(4 * np.sqrt(np.sqrt(len(x))))
# , new=True) @ReservedAssignment bin_, limits = np.histogram(
y, limits = np.histogram(data, bins=bins, normed=normed, weights=weights) data, bins=bins, normed=normed, weights=weights)
limits.shape = (-1, 1) limits.shape = (-1, 1)
xx = limits.repeat(3, axis=1) xx = limits.repeat(3, axis=1)
xx.shape = (-1,) xx.shape = (-1,)
xx = xx[1:-1] xx = xx[1:-1]
y.shape = (-1, 1) bin_.shape = (-1, 1)
yy = y.repeat(3, axis=1) yy = bin_.repeat(3, axis=1)
# yy[0,0] = 0.0 # pdf # yy[0,0] = 0.0 # pdf
yy[:, 0] = 0.0 # histogram yy[:, 0] = 0.0 # histogram
yy.shape = (-1,) yy.shape = (-1,)
@ -2719,8 +2756,10 @@ def fourier(data, t=None, T=None, m=None, n=None, method='trapz'):
>>> t = np.linspace(0,4*T) >>> t = np.linspace(0,4*T)
>>> x = np.sin(t) >>> x = np.sin(t)
>>> a, b = wm.fourier(x, t, T=T, m=5) >>> a, b = wm.fourier(x, t, T=T, m=5)
>>> (np.round(a.ravel()), np.round(b.ravel())) >>> np.abs(a.ravel())<1e-12
(array([ 0., 0., 0., 0., 0.]), array([ 0., 4., 0., 0., 0.])) array([ True, True, True, True, True], dtype=bool)
>>> np.abs(b.ravel()-np.array([ 0., 4., 0., 0., 0.]))<1e-12
array([ True, True, True, True, True], dtype=bool)
See also See also
-------- --------
@ -2778,93 +2817,9 @@ def fourier(data, t=None, T=None, m=None, n=None, method='trapz'):
return a, b return a, b
def _test_find_cross():
t = findcross([0, 0, 1, -1, 1], 0) # @UnusedVariable
def _test_common_shape():
A = ones((4, 1))
B = 2
C = ones((1, 5)) * 5
common_shape(A, B, C)
common_shape(A, B, C, shape=(3, 4, 1))
A = ones((4, 1))
B = 2
C = ones((1, 5)) * 5
common_shape(A, B, C, shape=(4, 5))
def _test_meshgrid():
x = array([-1, -0.5, 1, 4, 5], float)
y = array([0, -2, -5], float)
xv, yv = meshgrid(x, y, sparse=False)
print(xv)
print(yv)
xv, yv = meshgrid(x, y, sparse=True) # make sparse output arrays
print(xv)
print(yv)
print(meshgrid(0, 1, 5, sparse=True)) # just a 3D point
print(meshgrid([0, 1, 5], sparse=True)) # just a 3D point
xv, yv = meshgrid(y, y)
yv[0, 0] = 10
print(xv)
print(yv)
# >>> xv
# array([[ 0. , 0.5, 1. ]])
# >>> yv
# array([[ 0.],
# [ 1.]])
# array([[-1. , -0.5, 1. , 4. , 5. ],
# [-1. , -0.5, 1. , 4. , 5. ],
# [-1. , -0.5, 1. , 4. , 5. ]])
##
# array([[ 0., 0., 0., 0., 0.],
# [-2., -2., -2., -2., -2.],
# [-5., -5., -5., -5., -5.]])
def _test_tranproc():
# import utilitiestransform.models as wtm
tr = lambda x: x # wtm.TrHermite()
x = linspace(-5, 5, 501)
g = tr(x)
_gder = tranproc(x, g, x, ones(g.size))
pass
# >>> gder(:,1) = g(:,1)
# >>> plot(g(:,1),[g(:,2),gder(:,2)])
# >>> plot(g(:,1),pdfnorm(g(:,2)).*gder(:,2),g(:,1),pdfnorm(g(:,1)))
# >>> legend('Transformed model','Gaussian model')
def _test_detrend():
import pylab as plt
cos = np.cos
randn = np.random.randn
x = linspace(0, 1, 200)
y = exp(x) + cos(5 * 2 * pi * x) + 1e-1 * randn(x.size)
y0 = detrendma(y, 20)
tr = y - y0
plt.plot(x, y, x, y0, 'r', x, exp(x), 'k', x, tr, 'm')
def _test_extrema():
import pylab as plt
from pylab import plot
t = plt.linspace(0, 7 * pi, 250)
x = plt.sin(t) + 0.1 * sin(50 * t)
ind = findextrema(x)
ti, tp = t[ind], x[ind]
plot(t, x, '.', ti, tp, 'r.')
_ind1 = findrfc(tp, 0.3)
def _test_discretize():
import pylab as plt
x, y = discretize(cos, 0, pi)
plt.plot(x, y)
plt.show() plt.show()
plt.close('all') plt.close('all')
@ -2915,14 +2870,14 @@ def profile_main1():
import pstats import pstats
prof = cProfile.Profile() prof = cProfile.Profile()
prof = prof.runctx("real_main()", globals(), locals()) prof = prof.runctx("real_main()", globals(), locals())
print "<pre>" print("<pre>")
stats = pstats.Stats(prof) stats = pstats.Stats(prof)
stats.sort_stats("time") # Or cumulative stats.sort_stats("time") # Or cumulative
stats.print_stats(80) # 80 = how many to print stats.print_stats(80) # 80 = how many to print
# The rest is optional. # The rest is optional.
# stats.print_callees() # stats.print_callees()
# stats.print_callers() # stats.print_callers()
print "</pre>" print("</pre>")
main = profile_main1 main = profile_main1

@ -274,7 +274,7 @@ class _ExampleFunctions(object):
arg_z = 1. / arg_z arg_z = 1. / arg_z
return np.exp(-arg_z) return np.exp(-arg_z)
def __call__(self, x, y, id=0): def __call__(self, x, y, id=0): # @ReservedAssignment
s = self s = self
test_function = [s.franke, s.half_sphere, s.poly_degree20, s.exp_fun1, test_function = [s.franke, s.half_sphere, s.poly_degree20, s.exp_fun1,
s.exp_fun100, s.cos30, s.constant, s.exp_xy, s.runge, s.exp_fun100, s.cos30, s.constant, s.exp_xy, s.runge,
@ -410,7 +410,7 @@ def paduavals2coefs(f):
else: else:
# dct = @(c) chebtech2.coeffs2vals(c); # dct = @(c) chebtech2.coeffs2vals(c);
C = np.rot90(dct(dct(G.T).T)) #, axis=1) C = np.rot90(dct(dct(G.T).T)) # , axis=1)
C[0] = .5 * C[0] C[0] = .5 * C[0]
C[:, 1] = .5 * C[:, 1] C[:, 1] = .5 * C[:, 1]

@ -17,14 +17,14 @@
# Licence: LGPL # Licence: LGPL
# ------------------------------------------------------------------------- # -------------------------------------------------------------------------
# !/usr/bin/env python # !/usr/bin/env python
import warnings import warnings # @UnusedImport
from numpy.polynomial import polyutils as pu from numpy.polynomial import polyutils as pu
from plotbackend import plotbackend as plt from plotbackend import plotbackend as plt
import numpy as np import numpy as np
from numpy import (zeros, ones, zeros_like, array, asarray, newaxis, arange, from numpy import (zeros, asarray, newaxis, arange,
logical_or, any, pi, cos, round, diff, all, exp, atleast_1d, logical_or, any, pi, cos, round, diff, all, exp,
where, extract, linalg, sign, concatenate, floor, isreal, where, extract, linalg, sign, concatenate, floor,
conj, remainder, linspace, sum, meshgrid, hstack) linspace, sum, meshgrid)
from scipy.fftpack import dct, idct as _idct from scipy.fftpack import dct, idct as _idct
from numpy.lib.polynomial import * # @UnusedWildImport from numpy.lib.polynomial import * # @UnusedWildImport
@ -110,9 +110,9 @@ def polyint(p, m=1, k=None):
raise ValueError("Order of integral must be positive (see polyder)") raise ValueError("Order of integral must be positive (see polyder)")
if k is None: if k is None:
k = zeros(m, float) k = zeros(m, float)
k = atleast_1d(k) k = np.atleast_1d(k)
if len(k) == 1 and m > 1: if len(k) == 1 and m > 1:
k = k[0] * ones(m, float) k = k[0] * np.ones(m, float)
if len(k) < m: if len(k) < m:
raise ValueError( raise ValueError(
"k must be a scalar or a rank-1 array of length 1 or >m.") "k must be a scalar or a rank-1 array of length 1 or >m.")
@ -127,7 +127,7 @@ def polyint(p, m=1, k=None):
if p.ndim > 1: if p.ndim > 1:
ix = ix[..., newaxis] ix = ix[..., newaxis]
pieces = p.shape[-1] pieces = p.shape[-1]
k0 = k[0] * ones((1, pieces), dtype=int) k0 = k[0] * np.ones((1, pieces), dtype=int)
else: else:
k0 = [k[0]] k0 = [k[0]]
y = np.concatenate((p.__truediv__(ix), k0), axis=0) y = np.concatenate((p.__truediv__(ix), k0), axis=0)
@ -260,8 +260,8 @@ def polydeg(x, y):
# developed in a series of orthogonal polynomials. # developed in a series of orthogonal polynomials.
ys = np.ones((N,)) * y.mean() ys = np.ones((N,)) * y.mean()
# correction for small sample sizes # correction for small sample sizes
AIC = 2 + N * \ logsum2 = (np.log(2 * pi * ((ys - y) ** 2).sum() / N) + 1)
(np.log(2 * pi * ((ys - y) ** 2).sum() / N) + 1) + 4 / (N - 2) AIC = 2 + N * logsum2 + 4 / (N - 2)
n = 1 n = 1
nit = 0 nit = 0
@ -495,7 +495,7 @@ def polyreloc(p, x, y=0.0):
""" """
truepoly = isinstance(p, poly1d) truepoly = isinstance(p, poly1d)
r = atleast_1d(p).copy() r = np.atleast_1d(p).copy()
n = r.shape[0] n = r.shape[0]
# Relocate polynomial using Horner's algorithm # Relocate polynomial using Horner's algorithm
@ -548,7 +548,7 @@ def polyrescl(p, x, y=1.0):
""" """
truepoly = isinstance(p, poly1d) truepoly = isinstance(p, poly1d)
r = atleast_1d(p) r = np.atleast_1d(p)
n = r.shape[0] n = r.shape[0]
xscale = (float(x) ** arange(1 - n, 1)) xscale = (float(x) ** arange(1 - n, 1))
@ -591,7 +591,7 @@ def polytrim(p):
if truepoly: if truepoly:
return p return p
else: else:
r = atleast_1d(p).copy() r = np.atleast_1d(p).copy()
# Remove leading zeros # Remove leading zeros
is_not_lead_zeros = logical_or.accumulate(r != 0, axis=0) is_not_lead_zeros = logical_or.accumulate(r != 0, axis=0)
if r.ndim == 1: if r.ndim == 1:
@ -630,7 +630,7 @@ def poly2hstr(p, variable='x'):
""" """
var = variable var = variable
coefs = polytrim(atleast_1d(p)) coefs = polytrim(np.atleast_1d(p))
order = len(coefs) - 1 # Order of polynomial. order = len(coefs) - 1 # Order of polynomial.
s = '' # Initialize output string. s = '' # Initialize output string.
ix = 1 ix = 1
@ -719,7 +719,7 @@ def poly2str(p, variable='x'):
var = variable var = variable
# Remove leading zeros # Remove leading zeros
coeffs = polytrim(atleast_1d(p)) coeffs = polytrim(np.atleast_1d(p))
N = len(coeffs) - 1 N = len(coeffs) - 1
@ -1094,7 +1094,7 @@ def chebpoly(n, x=None, kind=1):
""" """
if x is None: # Calculate coefficients. if x is None: # Calculate coefficients.
if n == 0: if n == 0:
p = ones(1) p = np.ones(1)
else: else:
p = round(pow(2, n - 2 + kind) * poly(chebroot(n, kind=kind))) p = round(pow(2, n - 2 + kind) * poly(chebroot(n, kind=kind)))
p[1::2] = 0 p[1::2] = 0
@ -1102,7 +1102,7 @@ def chebpoly(n, x=None, kind=1):
else: # Evaluate polynomial in chebychev form else: # Evaluate polynomial in chebychev form
ck = zeros(n + 1) ck = zeros(n + 1)
ck[0] = 1. ck[0] = 1.
return _chebval(atleast_1d(x), ck, kind=kind) return _chebval(np.atleast_1d(x), ck, kind=kind)
def chebfit(fun, n=10, a=-1, b=1, trace=False): def chebfit(fun, n=10, a=-1, b=1, trace=False):
@ -1188,7 +1188,8 @@ def chebfit_dct(f, n=(10, ), domain=None):
Fit Chebyshev series to N-dimensional function Fit Chebyshev series to N-dimensional function
so that f(x1, x2,..., xn) can be approximated by: so that f(x1, x2,..., xn) can be approximated by:
.. math:: f(x_1, x_2,...,x_n) = \\sum_{i,j,...k} c_i T_i(x_1)*...*c_k T_k(x_n) , .. math:: f(x_1, x_2,...,x_n) =
\\sum_{i,j,...k} c_i T_i(x_1)*...*c_k T_k(x_n) ,
where Tk is the k'th Chebyshev polynomial of the first kind. where Tk is the k'th Chebyshev polynomial of the first kind.
@ -1251,10 +1252,10 @@ def chebfit_dct(f, n=(10, ), domain=None):
if hasattr(f, '__call__'): if hasattr(f, '__call__'):
if domain is None: if domain is None:
domain = (-1,1) * len(n) domain = (-1, 1) * len(n)
domain = np.atleast_2d(domain).reshape((-1, 2)) domain = np.atleast_2d(domain).reshape((-1, 2))
xi = [map_to_interval(chebroot(ni), d[0], d[1]) xi = [map_to_interval(chebroot(ni), d[0], d[1])
for ni, d in zip(n, domain)] for ni, d in zip(n, domain)]
Xi = np.meshgrid(*xi) Xi = np.meshgrid(*xi)
ck = f(*Xi) ck = f(*Xi)
else: else:
@ -1263,7 +1264,7 @@ def chebfit_dct(f, n=(10, ), domain=None):
ndim = len(n) ndim = len(n)
for i in range(ndim): for i in range(ndim):
ck = dct(ck[...,::-1]) ck = dct(ck[..., ::-1])
ck[..., 0] = ck[..., 0] / 2. ck[..., 0] = ck[..., 0] / 2.
if i < ndim-1: if i < ndim-1:
ck = np.rollaxis(ck, axis=-1) ck = np.rollaxis(ck, axis=-1)
@ -1591,8 +1592,8 @@ class Cheb1d(object):
def __eq__(self, other): def __eq__(self, other):
other = Cheb1d(other) other = Cheb1d(other)
return (all(self.coeffs == other.coeffs) and (self.a == other.a) return (all(self.coeffs == other.coeffs) and (self.a == other.a) and
and (self.b == other.b) and (self.kind == other.kind)) (self.b == other.b) and (self.kind == other.kind))
def __ne__(self, other): def __ne__(self, other):
return any(self.coeffs != other.coeffs) or (self.a != other.a) or ( return any(self.coeffs != other.coeffs) or (self.a != other.a) or (
@ -1830,8 +1831,8 @@ def padefitlsq(fun, m, k, a=-1, b=1, trace=False, x=None, end_points=True):
if trace: if trace:
plt.plot(x, fs, '+') plt.plot(x, fs, '+')
wt = ones((npt)) wt = np.ones((npt))
ee = ones((npt)) ee = np.ones((npt))
mad = 0 mad = 0
u = zeros((npt, ncof)) u = zeros((npt, ncof))
@ -1989,37 +1990,40 @@ def chebvandernd(deg, *xi):
------- -------
vander : ndarray vander : ndarray
The shape of the returned matrix is ``x1.shape + (order,)``, where The shape of the returned matrix is ``x1.shape + (order,)``, where
:math:`order = (deg[0]+1)*(deg([1]+1)*...*(deg[n-1]+1)`. The dtype will :math:`order = (deg[0]+1)*(deg([1]+1)*...*(deg[n-1]+1)`. The dtype
be the same as the converted `x1`, `x2`, ... `xn`. will be the same as the converted `x1`, `x2`, ... `xn`.
See Also See Also
-------- --------
chebvander, chebvalnd, chebfitnd chebvander, chebvalnd, chebfitnd
""" """
ideg = [int(d) for d in deg] ideg = [int(d) for d in deg]
is_valid = np.array([id == d and id >= 0 for id, d in zip(ideg, deg)]) is_valid = np.array([di == d and di >= 0 for di, d in zip(ideg, deg)])
if np.any(is_valid != 1): if np.any(is_valid != 1):
raise ValueError("degrees must be non-negative integers") raise ValueError("degrees must be non-negative integers")
ndim = len(xi) ndim = len(xi)
if len(ideg)!=ndim: if len(ideg) != ndim:
raise ValueError('length of deg must be the same as number of dimensions') msg = 'length of deg must be the same as number of dimensions'
raise ValueError(msg)
xi = np.array(xi, copy=0) + 0.0 xi = np.array(xi, copy=0) + 0.0
chebvander = np.polynomial.chebyshev.chebvander chebvander = np.polynomial.chebyshev.chebvander
shape0 = xi[0].shape shape0 = xi[0].shape
s0 = (1,) * ndim s0 = (1,) * ndim
vxi = [chebvander(x, d).reshape(shape0 + s0[:i] + (-1,) + s0[i + 1::]) vxi = [chebvander(x, d).reshape(shape0 + s0[:i] + (-1,) + s0[i + 1::])
for i, (d, x) in enumerate(zip(ideg, xi))] for i, (d, x) in enumerate(zip(ideg, xi))]
v = reduce(np.multiply, vxi) v = reduce(np.multiply, vxi)
return v.reshape(v.shape[:-ndim] + (-1,)) return v.reshape(v.shape[:-ndim] + (-1,))
def chebfitnd(xi, f, deg, rcond=None, full=False, w=None): def chebfitnd(xi, f, deg, rcond=None, full=False, w=None):
""" """
Least squares fit of Chebyshev series to N-dimensional data. Least squares fit of Chebyshev series to N-dimensional data.
Return the coefficients of a Chebyshev series of degree `deg` that is the Return the coefficients of a Chebyshev series of degree `deg` that is the
least squares fit to the data values `f` given at points `x1`, `x2`,..., `xn` least squares fit to the data values `f` given at points
`x1`, `x2`,..., `xn`
The fitted polynomial(s) are in the form The fitted polynomial(s) are in the form
.. math:: p(x,y) = c_00 + c_11 * T_1(x)*T_1(y) + ..c_ij * T_i(x)*T_j(y). .. math:: p(x,y) = c_00 + c_11 * T_1(x)*T_1(y) + ..c_ij * T_i(x)*T_j(y).
@ -2033,7 +2037,8 @@ def chebfitnd(xi, f, deg, rcond=None, full=False, w=None):
f : array_like f : array_like
function values at the sample points ``(x1[i], x2[i], ..., xn[i])``. function values at the sample points ``(x1[i], x2[i], ..., xn[i])``.
deg : list deg : list
Degrees of the fitting series in the x1, x2, ..., xn directions, respectively. Degrees of the fitting series in the x1, x2, ..., xn directions,
respectively.
rcond : float, optional rcond : float, optional
Relative condition number of the fit. Singular values smaller than Relative condition number of the fit. Singular values smaller than
this relative to the largest singular value will be ignored. The this relative to the largest singular value will be ignored. The
@ -2103,7 +2108,7 @@ def chebfitnd(xi, f, deg, rcond=None, full=False, w=None):
Examples Examples
-------- --------
""" """
xi_ = np.array(xi, copy=0) + 0.0 # xi = np.array(xi, copy=0) + 0.0
z = np.array(f) z = np.array(f)
degrees = np.asarray(deg, dtype=int) degrees = np.asarray(deg, dtype=int)
orders = degrees + 1 orders = degrees + 1
@ -2112,7 +2117,7 @@ def chebfitnd(xi, f, deg, rcond=None, full=False, w=None):
ndims = np.array([x.ndim for x in xi]) ndims = np.array([x.ndim for x in xi])
ndim = len(ndims) ndim = len(ndims)
sizes = np.array([x.size for x in xi]) sizes = np.array([x.size for x in xi])
if np.any(ndims!=ndim) or z.ndim!=ndim: if np.any(ndims != ndim) or z.ndim != ndim:
raise TypeError("expected %dD array for x1, x2,...,xn and f" % ndim) raise TypeError("expected %dD array for x1, x2,...,xn and f" % ndim)
if np.any(sizes == 0): if np.any(sizes == 0):
raise TypeError("expected non-empty vector for xi") raise TypeError("expected non-empty vector for xi")
@ -2148,13 +2153,15 @@ def chebfitnd(xi, f, deg, rcond=None, full=False, w=None):
else: else:
return c return c
def chebvalnd(c, *xi): def chebvalnd(c, *xi):
""" """
Evaluate a N-D Chebyshev series at points (x1, x2, ..., xn). Evaluate a N-D Chebyshev series at points (x1, x2, ..., xn).
This function returns the values: This function returns the values:
.. math:: p(x1,x2,...,xn) = \\sum_{i,j,...,k} c_{i,j,...,k} * T_i(x1) * T_j(x2)*...* T_k(xn) .. math:: p(x1,x2,...,xn) =
\\sum_{i,j,...,k} c_{i,j,...,k} * T_i(x1) * T_j(x2)*...* T_k(xn)
The parameters `x1`, `x2`, ...., `xn` are converted to arrays only if The parameters `x1`, `x2`, ...., `xn` are converted to arrays only if
they are tuples or a lists, otherwise they are treated as a scalars and they are tuples or a lists, otherwise they are treated as a scalars and
@ -2171,14 +2178,14 @@ def chebvalnd(c, *xi):
c : array_like c : array_like
Array of coefficients ordered so that the coefficient of the term of Array of coefficients ordered so that the coefficient of the term of
multi-degree i,j,...,k is contained in ``c[i,j,...,k]``. If `c` has multi-degree i,j,...,k is contained in ``c[i,j,...,k]``. If `c` has
dimension greater than N the remaining indices enumerate multiple sets of dimension greater than N the remaining indices enumerate multiple sets
coefficients. of coefficients.
x1, x2,..., xn : array_like, compatible object x1, x2,..., xn : array_like, compatible object
The N dimensional series is evaluated at the points The N dimensional series is evaluated at the points
`(x1, x2,...,xn)`, where `x1`, `x2`,..., `xn` must have the same shape. `(x1, x2,...,xn)`, where `x1`, `x2`,..., `xn` must have the same shape.
If any of `x1`, `x2`, ..., `xn` is a list or tuple, it is first converted If any of `x1`, `x2`, ..., `xn` is a list or tuple, it is first
to an ndarray, otherwise it is left unchanged and if it isn't an converted to an ndarray, otherwise it is left unchanged and if it isn't
ndarray it is treated as a scalar. an ndarray it is treated as a scalar.
Returns Returns
------- -------
@ -2194,12 +2201,13 @@ def chebvalnd(c, *xi):
xi = np.array(xi, copy=0) xi = np.array(xi, copy=0)
except: except:
raise ValueError('x, y, z are incompatible') raise ValueError('x, y, z are incompatible')
chebval = np.polynomial.chebyshev.chebval chebval = np.polynomial.chebyshev.chebval
c = chebval(xi[0], c) c = chebval(xi[0], c)
for x in xi[1:]: for x in xi[1:]:
c = chebval(x, c, tensor=False) c = chebval(x, c, tensor=False)
return c return c
def chebgridnd(c, *xi): def chebgridnd(c, *xi):
""" """
Evaluate a N-D Chebyshev series on the Cartesian product of x1, x2,..., xn. Evaluate a N-D Chebyshev series on the Cartesian product of x1, x2,..., xn.
@ -2212,8 +2220,8 @@ def chebgridnd(c, *xi):
`a` from `x1`, `b` from `x2`, and so on. The resulting points form `a` from `x1`, `b` from `x2`, and so on. The resulting points form
a grid with `x1` in the first dimension, `x2` in the second, and so on. a grid with `x1` in the first dimension, `x2` in the second, and so on.
The parameters `x1`, `x2`, ... and `xn` are converted to arrays only if they The parameters `x1`, `x2`, ... and `xn` are converted to arrays only if
are tuples or a lists, otherwise they are treated as a scalars. In they are tuples or a lists, otherwise they are treated as a scalars. In
either case, either `x1`, `x2`,... and `xn` or their elements must support either case, either `x1`, `x2`,... and `xn` or their elements must support
multiplication and addition both with themselves and with the elements multiplication and addition both with themselves and with the elements
of `c`. of `c`.
@ -2247,26 +2255,25 @@ def chebgridnd(c, *xi):
-------- --------
chebval, chebvalnd, chebfitnd chebval, chebvalnd, chebfitnd
""" """
chebval = np.polynomial.chebyshev.chebval chebval = np.polynomial.chebyshev.chebval
for x in xi: for x in xi:
c = chebval(x, c) c = chebval(x, c)
return c return c
def test_chebfit1d():
n = 63
x = chebroot(n=64, kind=1)
def test_chebfit1d():
def f(x): def f(x):
return np.exp(-x**2) return np.exp(-x**2)
z = f(x) # x = chebroot(n=64, kind=1)
# z = f(x)
c = chebfit(f, n=64)[::-1] c = chebfit(f, n=64)[::-1]
xi = np.linspace(-1, 1, 151) xi = np.linspace(-1, 1, 151)
zi = np.polynomial.chebyshev.chebval(xi, c) zi = np.polynomial.chebyshev.chebval(xi, c)
#plt.plot(xi, zi,'.', xi, f(xi)) # plt.plot(xi, zi,'.', xi, f(xi))
plt.semilogy(xi, np.abs(zi-f(xi))) plt.semilogy(xi, np.abs(zi-f(xi)))
plt.show('hold') plt.show('hold')
@ -2276,28 +2283,30 @@ def test_chebfit2d():
xorder, yorder = n-1, n-1 xorder, yorder = n-1, n-1
x = chebroot(n=n, kind=1) x = chebroot(n=n, kind=1)
xgrid, ygrid = meshgrid(x, x) xgrid, ygrid = meshgrid(x, x)
def f(x, y): def f(x, y):
return np.exp(-x**2-6*y**2) return np.exp(-x**2-6*y**2)
zgrid = f(xgrid, ygrid) zgrid = f(xgrid, ygrid)
#v2d = np.polynomial.chebyshev.chebvander2d(xgrid, ygrid, [xorder,yorder]).reshape((-1, (xorder+1)*(yorder+1))) # v2d = np.polynomial.chebyshev.chebvander2d(xgrid, ygrid,
#coeff, residuals, rank, s = np.linalg.lstsq(v2d, zgrid.ravel()) # [xorder,yorder]).reshape((-1, (xorder+1)*(yorder+1)))
#doeff = coeff.reshape(xorder+1,yorder+1) # coeff, residuals, rank, s = np.linalg.lstsq(v2d, zgrid.ravel())
dcoeff2 = chebfitnd((xgrid, ygrid), zgrid, [xorder,yorder]) # doeff = coeff.reshape(xorder+1,yorder+1)
dcoeff = chebfit_dct(f, n=(xorder+1,yorder+1)) _dcoeff2 = chebfitnd((xgrid, ygrid), zgrid, [xorder, yorder])
dcoeff = chebfit_dct(f, n=(xorder+1, yorder+1))
xi = np.linspace(-1, 1, 151) xi = np.linspace(-1, 1, 151)
Xi,Yi = np.meshgrid(xi, xi) Xi, Yi = np.meshgrid(xi, xi)
Zi = f(Xi, Yi) Zi = f(Xi, Yi)
zzi = chebvalnd(dcoeff, Xi, Yi) zzi = chebvalnd(dcoeff, Xi, Yi)
devi = Zi - zzi _devi = Zi - zzi
# plot residuals # plot residuals
#zz = np.polynomial.chebyshev.chebval2d(xgrid, ygrid, dcoeff) # zz = np.polynomial.chebyshev.chebval2d(xgrid, ygrid, dcoeff)
zz = chebvalnd(dcoeff, xgrid, ygrid) zz = chebvalnd(dcoeff, xgrid, ygrid)
dev = zgrid - zz dev = zgrid - zz
#plt.spy(np.abs(dcoeff)>1e-13) # plt.spy(np.abs(dcoeff)>1e-13)
plt.contourf(xgrid, ygrid, np.abs(dev)) plt.contourf(xgrid, ygrid, np.abs(dev))
#plt.contourf(Xi, Yi, np.abs(devi)) # plt.contourf(Xi, Yi, np.abs(devi))
plt.colorbar() plt.colorbar()
# plt.semilogy(np.abs(devi.ravel())) # plt.semilogy(np.abs(devi.ravel()))
plt.show('hold') plt.show('hold')

File diff suppressed because it is too large Load Diff

@ -3,12 +3,12 @@ Created on 15. des. 2009
@author: pab @author: pab
''' '''
#import os # import os
#import sys # import sys
#import win32com # import win32com
#from win32com.client.selecttlb import EnumTlbs # from win32com.client.selecttlb import EnumTlbs
#typelib_mso = None # typelib_mso = None
#typelib_msppt = None # typelib_msppt = None
# for typelib in EnumTlbs(): # for typelib in EnumTlbs():
# d = typelib.desc.split(' ') # d = typelib.desc.split(' ')
# if d[0] == 'Microsoft' and d[1] == 'Office' and d[3] == 'Object' \ # if d[0] == 'Microsoft' and d[1] == 'Office' and d[3] == 'Object' \
@ -19,7 +19,7 @@ Created on 15. des. 2009
# typelib_msppt = typelib # typelib_msppt = typelib
# if hasattr(sys, 'frozen'): # If we're an .exe file # if hasattr(sys, 'frozen'): # If we're an .exe file
# win32com.__gen_path__ = os.path.dirname(sys.executable) # win32com.__gen_path__ = os.path.dirname(sys.executable)
## win32com.__gen_path__ = os.environ['TEMP'] # # win32com.__gen_path__ = os.environ['TEMP']
# if win32com.client.gencache.is_readonly: # if win32com.client.gencache.is_readonly:
# win32com.client.gencache.is_readonly = False # win32com.client.gencache.is_readonly = False
# win32com.client.gencache.Rebuild() # win32com.client.gencache.Rebuild()
@ -49,7 +49,7 @@ class Powerpoint(object):
def __init__(self, file_name=''): def __init__(self, file_name=''):
self.application = win32com.client.Dispatch("Powerpoint.Application") self.application = win32com.client.Dispatch("Powerpoint.Application")
#self.application.Visible = True # self.application.Visible = True
self._visible = self.application.Visible self._visible = self.application.Visible
if file_name: if file_name:
self.presentation = self.application.Presentations.Open(file_name) self.presentation = self.application.Presentations.Open(file_name)
@ -129,7 +129,7 @@ class Powerpoint(object):
titlerange.Font.Size = self.title_size titlerange.Font.Size = self.title_size
if texts != '' and texts != ['']: if texts != '' and texts != ['']:
#textrange = slide.Shapes(textbox_id).TextFrame.TextRange # textrange = slide.Shapes(textbox_id).TextFrame.TextRange
self._add_text(slide, textbox_id, texts, maxlevel) self._add_text(slide, textbox_id, texts, maxlevel)
if image_file != '' and image_file != ['']: if image_file != '' and image_file != ['']:
@ -213,7 +213,6 @@ def test_powerpoint():
# Make powerpoint # Make powerpoint
ppt = Powerpoint() ppt = Powerpoint()
# time.
ppt.footer = 'This is the footer' ppt.footer = 'This is the footer'
ppt.add_title_slide('Title', 'Per A.') ppt.add_title_slide('Title', 'Per A.')
ppt.add_slide(title='alsfkasldk', texts='asdflaf', notes='asdfas') ppt.add_slide(title='alsfkasldk', texts='asdflaf', notes='asdfas')
@ -231,7 +230,7 @@ def make_ppt():
# title.TextFrame.TextRange.Text = 'Overskrift' # title.TextFrame.TextRange.Text = 'Overskrift'
title_id, textbox_id = 1, 2 title_id, textbox_id = 1, 2
slide1.Shapes(title_id).TextFrame.TextRange.Text = 'Overskrift' slide1.Shapes(title_id).TextFrame.TextRange.Text = 'Overskrift'
#slide1.Shapes(title_id).TextFrame.Width = 190 # slide1.Shapes(title_id).TextFrame.Width = 190
slide1.Shapes(textbox_id).TextFrame.TextRange.InsertAfter('Test') slide1.Shapes(textbox_id).TextFrame.TextRange.InsertAfter('Test')
unused_tr = slide1.Shapes(textbox_id).TextFrame.TextRange.InsertAfter('\r') unused_tr = slide1.Shapes(textbox_id).TextFrame.TextRange.InsertAfter('\r')
@ -242,12 +241,12 @@ def make_ppt():
tr.IndentLevel = 2 tr.IndentLevel = 2
tr1 = slide1.Shapes(textbox_id).TextFrame.TextRange.InsertAfter('test3') tr1 = slide1.Shapes(textbox_id).TextFrame.TextRange.InsertAfter('test3')
tr1.IndentLevel = 3 tr1.IndentLevel = 3
#slide1.Shapes(textbox_id).TextFrame.TextRange.Text = 'Test \r test2' # slide1.Shapes(textbox_id).TextFrame.TextRange.Text = 'Test \r test2'
# textbox = slide1.Shapes.AddTextBox(Type=msoTextOrientationHorizontal, # textbox = slide1.Shapes.AddTextBox(Type=msoTextOrientationHorizontal,
# Left=30, Top=100, Width=190, Height=400) # Left=30, Top=100, Width=190, Height=400)
# textbox.TextFrame.TextRange.Text = 'Test \r test2' # textbox.TextFrame.TextRange.Text = 'Test \r test2'
#picbox = slide1.Shapes(picb_id) # picbox = slide1.Shapes(picb_id)
filename = r'c:\temp\data1_report1_and_2_Tr120_1.png' filename = r'c:\temp\data1_report1_and_2_Tr120_1.png'
slide1.Shapes.AddPicture(FileName=filename, LinkToFile=False, slide1.Shapes.AddPicture(FileName=filename, LinkToFile=False,
@ -280,13 +279,8 @@ def make_ppt():
# application.Quit() # application.Quit()
def rename_ppt(): def rename_ppt():
root = r'C:/pab/tsm_opeval/analysis_tsmps_aco_v2008b/plots' root = r'C:/pab/tsm_opeval/analysis_tsmps_aco_v2008b/plots'
# root = r'C:/pab/tsm_opeval/analysis_tsmps_mag_v2008b/plots'
# root = r'C:/pab/tsm_opeval/analysis_tsmps_mag_v2010a/plots'
# root = r'C:/pab/tsm_opeval/analysis_tsmps_aco_v2010a/plots'
#filename = r'mag_sweep_best_tsmps_ship_eff0-10.ppt'
filenames = os.listdir(root) filenames = os.listdir(root)
prefix = 'TSMPSv2008b_' prefix = 'TSMPSv2008b_'
#prefix = 'TSMPSv2010a_'
for filename in filenames: for filename in filenames:
if filename.endswith('.ppt'): if filename.endswith('.ppt'):
try: try:
@ -300,13 +294,8 @@ def rename_ppt():
def load_file_into_ppt(): def load_file_into_ppt():
root = r'C:/pab/tsm_opeval/analysis_tsmps_aco_v2008b/plots' root = r'C:/pab/tsm_opeval/analysis_tsmps_aco_v2008b/plots'
# root = r'C:/pab/tsm_opeval/analysis_tsmps_mag_v2008b/plots'
# root = r'C:/pab/tsm_opeval/analysis_tsmps_mag_v2010a/plots'
# root = r'C:/pab/tsm_opeval/analysis_tsmps_aco_v2010a/plots'
#filename = r'mag_sweep_best_tsmps_ship_eff0-10.ppt'
filenames = os.listdir(root) filenames = os.listdir(root)
prefix = 'TSMPSv2008b_' prefix = 'TSMPSv2008b_'
#prefix = 'TSMPSv2010a_'
for filename in filenames: for filename in filenames:
if filename.startswith(prefix) and filename.endswith('.ppt'): if filename.startswith(prefix) and filename.endswith('.ppt'):
try: try:

@ -5,6 +5,7 @@ Created on Sun Oct 25 14:55:34 2015
@author: dave @author: dave
""" """
def configuration(parent_package='', top_path=None): def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration from numpy.distutils.misc_util import Configuration
config = Configuration('wafo', parent_package, top_path) config = Configuration('wafo', parent_package, top_path)

@ -3,12 +3,11 @@ Created on 17. juli 2010
@author: pab @author: pab
''' '''
import numpy as np # @UnusedImport import numpy as np
from numpy import pi, inf # @UnusedImport from numpy import pi, inf
from numpy.testing import assert_array_almost_equal from numpy.testing import assert_array_almost_equal
from wafo.gaussian import (Rind, prbnormtndpc, prbnormndpc, prbnormnd, from wafo.gaussian import (Rind, prbnormtndpc, prbnormndpc, prbnormnd,
cdfnorm2d, prbnorm2d) cdfnorm2d, prbnorm2d)
from numpy.ma.testutils import assert_array_almost_equal
def test_rind(): def test_rind():
@ -31,7 +30,7 @@ def test_rind():
A = np.repeat(Blo, n) A = np.repeat(Blo, n)
B = np.repeat(Bup, n) # Integration limits B = np.repeat(Bup, n) # Integration limits
E1, err1, terr1 = rind(np.triu(Sc), m, A, B) # same as E0 E1, _err1, _terr1 = rind(np.triu(Sc), m, A, B) # same as E0
assert(np.abs(E1 - Et) < err0 + terr0) assert(np.abs(E1 - Et) < err0 + terr0)
t = 'E1 = %2.5f' % E1 t = 'E1 = %2.5f' % E1
@ -59,8 +58,10 @@ def test_rind():
Bup2 = np.inf Bup2 = np.inf
indI2 = [-1, 1] indI2 = [-1, 1]
rind2 = Rind(method=1) rind2 = Rind(method=1)
g2 = lambda x: (
x * (np.pi / 2 + np.arcsin(x)) + np.sqrt(1 - x**2)) / (2 * np.pi) def g2(x):
return (x * (np.pi / 2 + np.arcsin(x)) +
np.sqrt(1 - x**2)) / (2 * np.pi)
assert_array_almost_equal(g2(rho2), 0.24137214191774381) # exact value assert_array_almost_equal(g2(rho2), 0.24137214191774381) # exact value
E3, err3, terr3 = rind(Sc2, m2, Blo2, Bup2, indI2, nt=0) E3, err3, terr3 = rind(Sc2, m2, Blo2, Bup2, indI2, nt=0)
@ -84,18 +85,21 @@ def test_prbnormtndpc():
rho2 = np.random.rand(2) rho2 = np.random.rand(2)
a2 = np.zeros(2) a2 = np.zeros(2)
b2 = np.repeat(np.inf, 2) b2 = np.repeat(np.inf, 2)
[val2, err2, ift2] = prbnormtndpc(rho2, a2, b2) val2, err2, _ift2 = prbnormtndpc(rho2, a2, b2)
g2 = lambda x: 0.25 + np.arcsin(x[0] * x[1]) / (2 * pi)
E2 = g2(rho2) # % exact value def g2(x):
return 0.25 + np.arcsin(x[0] * x[1]) / (2 * pi)
E2 = g2(rho2) # exact value
assert(np.abs(E2 - val2) < err2) assert(np.abs(E2 - val2) < err2)
rho3 = np.random.rand(3) rho3 = np.random.rand(3)
a3 = np.zeros(3) a3 = np.zeros(3)
b3 = np.repeat(inf, 3) b3 = np.repeat(inf, 3)
[val3, err3, ift3] = prbnormtndpc(rho3, a3, b3) val3, err3, _ift3 = prbnormtndpc(rho3, a3, b3)
g3 = lambda x: 0.5 - \
sum(np.sort( def g3(x):
np.arccos([x[0] * x[1], x[0] * x[2], x[1] * x[2]]))) / (4 * pi) return 0.5 - sum(np.sort(np.arccos([x[0] * x[1], x[0] * x[2],
x[1] * x[2]]))) / (4 * pi)
E3 = g3(rho3) # Exact value E3 = g3(rho3) # Exact value
assert(np.abs(E3 - val3) < err3) assert(np.abs(E3 - val3) < err3)
@ -105,17 +109,21 @@ def test_prbnormndpc():
rho2 = np.random.rand(2) rho2 = np.random.rand(2)
a2 = np.zeros(2) a2 = np.zeros(2)
b2 = np.repeat(np.inf, 2) b2 = np.repeat(np.inf, 2)
[val2, err2, ift2] = prbnormndpc(rho2, a2, b2) val2, err2, _ift2 = prbnormndpc(rho2, a2, b2)
g2 = lambda x: 0.25 + np.arcsin(x[0] * x[1]) / (2 * pi)
E2 = g2(rho2) # % exact value def g2(x):
return 0.25 + np.arcsin(x[0] * x[1]) / (2 * pi)
E2 = g2(rho2) # exact value
assert(np.abs(E2 - val2) < err2) assert(np.abs(E2 - val2) < err2)
rho3 = np.random.rand(3) rho3 = np.random.rand(3)
a3 = np.zeros(3) a3 = np.zeros(3)
b3 = np.repeat(inf, 3) b3 = np.repeat(inf, 3)
[val3, err3, ift3] = prbnormndpc(rho3, a3, b3) val3, err3, _ift3 = prbnormndpc(rho3, a3, b3)
g3 = lambda x: 0.5 - sum(np.sort(np.arccos([x[0] * x[1], x[0] * x[2],
x[1] * x[2]]))) / (4 * pi) def g3(x):
return 0.5 - sum(np.sort(np.arccos([x[0] * x[1], x[0] * x[2],
x[1] * x[2]]))) / (4 * pi)
E3 = g3(rho3) # Exact value E3 = g3(rho3) # Exact value
assert(np.abs(E3 - val3) < err3) assert(np.abs(E3 - val3) < err3)
@ -153,7 +161,7 @@ def test_prbnorm2d():
a = [-1, -2] a = [-1, -2]
b = [1, 1] b = [1, 1]
r = 0.3 r = 0.3
assert_array_almost_equal(prbnorm2d(a,b,r), [ 0.56659121]) assert_array_almost_equal(prbnorm2d(a, b, r), 0.56659121)
if __name__ == '__main__': if __name__ == '__main__':
import doctest import doctest

@ -1,6 +1,7 @@
from numpy.testing import (run_module_suite, assert_equal, assert_almost_equal, from numpy.testing import (run_module_suite, assert_equal, assert_almost_equal,
assert_array_equal, assert_array_almost_equal) assert_array_equal, assert_array_almost_equal,
TestCase, assert_, assert_raises,)
import numpy as np import numpy as np
from numpy import array, cos, exp, linspace, pi, sin, diff, arange, ones from numpy import array, cos, exp, linspace, pi, sin, diff, arange, ones
@ -10,7 +11,10 @@ from wafo.misc import (JITImport, Bunch, detrendma, DotDict, findcross, ecross,
findoutliers, common_shape, argsreduce, stirlerr, findoutliers, common_shape, argsreduce, stirlerr,
getshipchar, betaloge, hygfz, getshipchar, betaloge, hygfz,
gravity, nextpow2, discretize, polar2cart, gravity, nextpow2, discretize, polar2cart,
cart2polar, tranproc) cart2polar, tranproc,
rotation_matrix, rotate_2d, spaceline,
args_flat, sub2index, index2sub, piecewise,
parse_kwargs)
def test_JITImport(): def test_JITImport():
@ -342,6 +346,17 @@ def test_stirlerr():
0.02767793, 0.02079067])) 0.02767793, 0.02079067]))
def test_parse_kwargs():
opt = dict(arg1=1, arg2=3)
opt = parse_kwargs(opt, arg1=5)
assert(opt['arg1'] == 5)
assert(opt['arg2'] == 3)
opt2 = dict(arg3=15)
opt = parse_kwargs(opt, **opt2)
assert('arg3' not in opt)
def test_getshipchar(): def test_getshipchar():
sc = getshipchar(10, 'service_speed') sc = getshipchar(10, 'service_speed')
true_sc = dict(beam=29, true_sc = dict(beam=29,
@ -380,7 +395,7 @@ def test_nextpow2():
def test_discretize(): def test_discretize():
x, y = discretize(np.cos, 0, np.pi, tol=0.0051) x, y = discretize(np.cos, 0, np.pi, tol=0.05)
assert_array_almost_equal( assert_array_almost_equal(
x, x,
np.array( np.array(
@ -470,5 +485,241 @@ def test_tranproc():
0.86643821, 0.83096482])) 0.86643821, 0.83096482]))
class TestPiecewise(TestCase):
def test_condition_is_single_bool_list(self):
assert_raises(ValueError, piecewise, [0, 0], [True, False], [1])
def test_condition_is_list_of_single_bool_list(self):
x = piecewise([0, 0], [[True, False]], [1])
assert_array_equal(x, [1, 0])
def test_conditions_is_list_of_single_bool_array(self):
x = piecewise([0, 0], [np.array([True, False])], [1])
assert_array_equal(x, [1, 0])
def test_condition_is_single_int_array(self):
assert_raises(ValueError, piecewise, [0, 0], np.array([1, 0]), [1])
def test_condition_is_list_of_single_int_array(self):
x = piecewise([0, 0], [np.array([1, 0])], [1])
assert_array_equal(x, [1, 0])
def test_simple(self):
x = piecewise([0, 0], [[False, True]], [lambda x:-1])
assert_array_equal(x, [0, -1])
x = piecewise([1, 2], [[True, False], [False, True]], [3, 4])
assert_array_equal(x, [3, 4])
def test_default(self):
# No value specified for x[1], should be 0
x = piecewise([1, 2], [[True, False]], [2])
assert_array_equal(x, [2, 0])
# Should set x[1] to 3
x = piecewise([1, 2], [[True, False]], [2, 3])
assert_array_equal(x, [2, 3])
def test_0d(self):
x = np.array(3)
y = piecewise(x, [x > 3], [4, 0])
assert_(y.ndim == 0)
assert_(y == 0)
x = 5
y = piecewise(x, [[True], [False]], [1, 0])
assert_(y.ndim == 0)
assert_(y == 1)
def test_abs_function(self):
x = np.linspace(-2.5, 2.5, 6)
vals = piecewise((x,), [x < 0, x >= 0], [lambda x: -x, lambda x: x])
assert_array_equal(vals,
[2.5, 1.5, 0.5, 0.5, 1.5, 2.5])
def test_abs_function_with_scalar(self):
x = np.array(-2.5)
vals = piecewise((x,), [x < 0, x >= 0], [lambda x: -x, lambda x: x])
assert_(vals == 2.5)
def test_otherwise_condition(self):
x = np.linspace(-2.5, 2.5, 6)
vals = piecewise((x,), [x < 0, ], [lambda x: -x, lambda x: x])
assert_array_equal(vals, [2.5, 1.5, 0.5, 0.5, 1.5, 2.5])
def test_passing_further_args_to_fun(self):
def fun0(x, y, scale=1.):
return -x*y/scale
def fun1(x, y, scale=1.):
return x*y/scale
x = np.linspace(-2.5, 2.5, 6)
vals = piecewise((x,), [x < 0, ], [fun0, fun1], args=(2.,), scale=2.)
assert_array_equal(vals, [2.5, 1.5, 0.5, 0.5, 1.5, 2.5])
def test_step_function(self):
x = np.linspace(-2.5, 2.5, 6)
vals = piecewise(x, [x < 0, x >= 0], [-1, 1])
assert_array_equal(vals, [-1., -1., -1., 1., 1., 1.])
def test_step_function_with_scalar(self):
x = 1
vals = piecewise(x, [x < 0, x >= 0], [-1, 1])
assert_(vals == 1)
def test_function_with_two_args(self):
x = np.linspace(-2, 2, 5)
X, Y = np.meshgrid(x, x)
vals = piecewise(
(X, Y), [X * Y < 0, ], [lambda x, y: -x * y, lambda x, y: x * y])
assert_array_equal(vals, [[4., 2., -0., 2., 4.],
[2., 1., -0., 1., 2.],
[-0., -0., 0., 0., 0.],
[2., 1., 0., 1., 2.],
[4., 2., 0., 2., 4.]])
def test_fill_value_and_function_with_two_args(self):
x = np.linspace(-2, 2, 5)
X, Y = np.meshgrid(x, x)
vals = piecewise((X, Y), [X * Y < -0.5, X * Y > 0.5],
[lambda x, y: -x * y, lambda x, y: x * y],
fill_value=np.nan)
nan = np.nan
assert_array_equal(vals, [[4., 2., nan, 2., 4.],
[2., 1., nan, 1., 2.],
[nan, nan, nan, nan, nan],
[2., 1., nan, 1., 2.],
[4., 2., nan, 2., 4.]])
def test_fill_value2_and_function_with_two_args(self):
x = np.linspace(-2, 2, 5)
X, Y = np.meshgrid(x, x)
vals = piecewise((X, Y), [X * Y < -0.5, X * Y > 0.5],
[lambda x, y: -x * y, lambda x, y: x * y, np.nan])
nan = np.nan
assert_array_equal(vals, [[4., 2., nan, 2., 4.],
[2., 1., nan, 1., 2.],
[nan, nan, nan, nan, nan],
[2., 1., nan, 1., 2.],
[4., 2., nan, 2., 4.]])
class TestRotationMatrix(TestCase):
def test_h0_p0_r0(self):
vals = rotation_matrix(heading=0, pitch=0, roll=0).tolist()
truevals = [[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]]
self.assertListEqual(vals, truevals)
def test_h180_p0_r0(self):
vals = rotation_matrix(heading=180, pitch=0, roll=0).tolist()
truevals = [[-1.0, -1.2246467991473532e-16, 0.0],
[1.2246467991473532e-16, -1.0, 0.0],
[-0.0, 0.0, 1.0]]
self.assertListEqual(vals, truevals)
def test_h0_p180_r0(self):
vals = rotation_matrix(heading=0, pitch=180, roll=0).tolist()
truevals = [[-1.0, 0.0, 1.2246467991473532e-16],
[-0.0, 1.0, 0.0],
[-1.2246467991473532e-16, -0.0, -1.0]]
self.assertListEqual(vals, truevals)
def test_h0_p0_r180(self):
vals = rotation_matrix(heading=0, pitch=180, roll=0).tolist()
truevals = [[-1.0, 0.0, 1.2246467991473532e-16],
[-0.0, 1.0, 0.0],
[-1.2246467991473532e-16, -0.0, -1.0]]
self.assertListEqual(vals, truevals)
class TestRotate2d(TestCase):
def test_rotate_0deg(self):
vals = list(rotate_2d(x=1, y=0, angle_deg=0))
truevals = [1.0, 0.0]
self.assertListEqual(vals, truevals)
def test_rotate_90deg(self):
vals = list(rotate_2d(x=1, y=0, angle_deg=90))
truevals = [6.123233995736766e-17, 1.0]
self.assertListEqual(vals, truevals)
def test_rotate_180deg(self):
vals = list(rotate_2d(x=1, y=0, angle_deg=180))
truevals = [-1.0, 1.2246467991473532e-16]
self.assertListEqual(vals, truevals)
def test_rotate_360deg(self):
vals = list(rotate_2d(x=1, y=0, angle_deg=360))
truevals = [1.0, -2.4492935982947064e-16]
self.assertListEqual(vals, truevals)
class TestSpaceLine(TestCase):
def test_space_line(self):
vals = spaceline((2, 0, 0), (3, 0, 0), num=5).tolist()
truevals = [[2., 0., 0.],
[2.25, 0., 0.],
[2.5, 0., 0.],
[2.75, 0., 0.],
[3., 0., 0.]]
self.assertListEqual(vals, truevals)
class TestArgsFlat(TestCase):
def test_1_vector_and_2_scalar_args(self):
x = [1, 2, 3]
pos, c_shape = args_flat(x, 2, 3)
truepos = [[1, 2, 3],
[2, 2, 3],
[3, 2, 3]]
truec_shape = [3, ]
self.assertListEqual(pos.tolist(), truepos)
self.assertListEqual(list(c_shape), truec_shape)
def test_1_vector_args(self):
pos1, c_shape1 = args_flat([1, 2, 3])
truepos1 = [[1, 2, 3]]
truec_shape1 = None
self.assertListEqual(pos1.tolist(), truepos1)
self.assertIs(c_shape1, truec_shape1)
def test_3_scalar_args(self):
pos1, c_shape1 = args_flat(1, 2, 3)
truepos1 = [[1, 2, 3]]
truec_shape1 = []
self.assertListEqual(pos1.tolist(), truepos1)
self.assertListEqual(list(c_shape1), truec_shape1)
def test_3_scalar_args_version2(self):
pos1, c_shape1 = args_flat([1], 2, 3)
truepos1 = [[1, 2, 3]]
truec_shape1 = [1, ]
self.assertListEqual(pos1.tolist(), truepos1)
self.assertListEqual(list(c_shape1), truec_shape1)
class TestSub2index2Sub(TestCase):
def test_sub2index_and_index2sub(self):
shape = (3, 3, 4)
a = np.arange(np.prod(shape)).reshape(shape)
trueval = a[1, 2, 3]
order = 'C'
i = sub2index(shape, 1, 2, 3, order=order)
self.assertEquals(i, 23)
val = a.ravel(order)[i]
self.assertEquals(val, trueval)
sub = index2sub(shape, i, order=order)
for j, true_sub_j in enumerate([1, 2, 3]):
self.assertEquals(sub[j].tolist(), true_sub_j)
if __name__ == '__main__': if __name__ == '__main__':
run_module_suite() run_module_suite()

@ -6,9 +6,9 @@ from numpy.testing import (
# ) # )
import unittest as local_unittest import unittest as local_unittest
import numpy as np
from wafo.numpy_utils import (rotation_matrix, rotate_2d, spaceline, from wafo.numpy_utils import (rotation_matrix, rotate_2d, spaceline,
args_flat, sub2index, index2sub, piecewise) args_flat, sub2index, index2sub, piecewise)
import numpy as np
class TestPiecewise(TestCase): class TestPiecewise(TestCase):

Loading…
Cancel
Save