Added from __future__ import absolute_import +pep8

master
Per A Brodtkorb 7 years ago
parent 5d3b40355d
commit 5239906405

@ -1,8 +1,8 @@
from __future__ import absolute_import from __future__ import absolute_import, division, print_function
import warnings import warnings
from wafo.graphutil import cltext from wafo.graphutil import cltext
from wafo.plotbackend import plotbackend as plt from wafo.plotbackend import plotbackend as plt
from time import gmtime, strftime from wafo.misc import now
import numpy as np import numpy as np
from scipy.integrate.quadrature import cumtrapz # @UnresolvedImport from scipy.integrate.quadrature import cumtrapz # @UnresolvedImport
from scipy import interpolate from scipy import interpolate
@ -17,21 +17,22 @@ def empty_copy(obj):
def __init__(self): def __init__(self):
pass pass
newcopy = Empty() newcopy = Empty()
# pylint: disable=attribute-defined-outside-init
newcopy.__class__ = obj.__class__ newcopy.__class__ = obj.__class__
return newcopy return newcopy
def now(): def _set_seed(iseed):
''' if iseed is not None:
Return current date and time as a string try:
''' np.random.set_state(iseed)
return strftime("%a, %d %b %Y %H:%M:%S", gmtime()) except ValueError:
np.random.seed(iseed)
class PlotData(object): class PlotData(object):
''' """Container class for data with interpolation and plotting methods.
Container class for data with interpolation and plotting methods
Member variables Member variables
---------------- ----------------
@ -69,7 +70,7 @@ class PlotData(object):
>>> h = d3.plot() # plot data, CI red dotted line >>> h = d3.plot() # plot data, CI red dotted line
>>> h = d3.plot(plot_args_children=['b--']) # CI with blue dashed line >>> h = d3.plot(plot_args_children=['b--']) # CI with blue dashed line
''' """
def __init__(self, data=None, args=None, **kwds): def __init__(self, data=None, args=None, **kwds):
self.data = data self.data = data
@ -92,8 +93,7 @@ class PlotData(object):
return newcopy return newcopy
def eval_points(self, *points, **kwds): def eval_points(self, *points, **kwds):
''' """Interpolate data at points.
Interpolate data at points
Parameters Parameters
---------- ----------
@ -136,7 +136,8 @@ class PlotData(object):
See also See also
-------- --------
scipy.interpolate.griddata scipy.interpolate.griddata
'''
"""
options = dict(method='linear') options = dict(method='linear')
options.update(**kwds) options.update(**kwds)
if isinstance(self.args, (list, tuple)): # Multidimensional data if isinstance(self.args, (list, tuple)): # Multidimensional data

File diff suppressed because it is too large Load Diff

@ -5,12 +5,12 @@ Created on 20. jan. 2011
license BSD license BSD
''' '''
from __future__ import absolute_import, division from __future__ import absolute_import, division, print_function
import warnings import warnings
import numpy as np import numpy as np
from .plotbackend import plotbackend from .plotbackend import plotbackend
from matplotlib import mlab from matplotlib import mlab
__all__ = ['cltext', 'tallibing', 'test_docstrings'] __all__ = ['cltext', 'epcolor', 'tallibing', 'test_docstrings']
_TALLIBING_GID = 'TALLIBING' _TALLIBING_GID = 'TALLIBING'
_CLTEXT_GID = 'CLTEXT' _CLTEXT_GID = 'CLTEXT'
@ -108,9 +108,11 @@ def cltext(levels, percent=False, n=4, xs=0.036, ys=0.94, zs=0, figure=None,
>>> import wafo.demos as wd >>> import wafo.demos as wd
>>> import pylab as plt >>> import pylab as plt
>>> x,y,z = wd.peaks(); >>> x,y,z = wd.peaks();
>>> h = plt.contour(x,y,z)
>>> h = wg.cltext(h.levels)
>>> plt.close('all')
h = plt.contour(x,y,z)
h = wg.cltext(h.levels)
plt.show() plt.show()
''' '''
# TODO : Make it work like legend does (but without the box): include # TODO : Make it work like legend does (but without the box): include
@ -142,7 +144,6 @@ def cltext(levels, percent=False, n=4, xs=0.036, ys=0.94, zs=0, figure=None,
titletxt = 'Level curves enclosing:' titletxt = 'Level curves enclosing:'
else: else:
titletxt = 'Level curves at:' titletxt = 'Level curves at:'
format_ = '%0.' + ('%d' % n) + 'g\n' format_ = '%0.' + ('%d' % n) + 'g\n'
cltxt = ''.join([format_ % level for level in clevels.tolist()]) cltxt = ''.join([format_ % level for level in clevels.tolist()])
@ -196,9 +197,10 @@ def tallibing(*args, **kwds):
>>> import wafo.graphutil as wg >>> import wafo.graphutil as wg
>>> import wafo.demos as wd >>> import wafo.demos as wd
>>> [x,y,z] = wd.peaks(n=20) >>> [x,y,z] = wd.peaks(n=20)
>>> h = wg.pcolor(x,y,z)
>>> h = wg.tallibing(x,y,z)
h0 = wg.pcolor(x,y,z) pcolor(x,y,z); shading interp;
h1 = wg.tallibing(x,y,z)
See also See also
-------- --------

@ -246,7 +246,6 @@ def kreg_demo1(hs=None, fast=True, fun='hisj'):
plt.plot(x, y2[0], 'm', label='statsmodel') plt.plot(x, y2[0], 'm', label='statsmodel')
plt.legend() plt.legend()
# plt.show()
# print(kreg.tkde.tkde._inv_hs) # print(kreg.tkde.tkde._inv_hs)
# print(kreg.tkde.tkde.hs) # print(kreg.tkde.tkde.hs)

@ -3,7 +3,7 @@ Created on 15. des. 2016
@author: pab @author: pab
''' '''
from __future__ import division from __future__ import absolute_import, division, print_function
from scipy import sparse from scipy import sparse
import numpy as np import numpy as np
from wafo.testing import test_docstrings from wafo.testing import test_docstrings
@ -181,10 +181,10 @@ def accum(accmap, a, func=None, shape=None, fill_value=0, dtype=None):
def create_array_of_python_lists(accmap, a, shape): def create_array_of_python_lists(accmap, a, shape):
vals = np.empty(shape, dtype='O') vals = np.empty(shape, dtype='O')
for s in product(*[range(k) for k in shape]): for s in product(*[np.arange(k) for k in shape]):
vals[s] = [] vals[s] = []
for s in product(*[range(k) for k in a.shape]): for s in product(*[np.arange(k) for k in a.shape]):
indx = tuple(accmap[s]) indx = tuple(accmap[s])
val = a[s] val = a[s]
vals[indx].append(val) vals[indx].append(val)
@ -216,7 +216,7 @@ def accum(accmap, a, func=None, shape=None, fill_value=0, dtype=None):
# Create the output array. # Create the output array.
out = np.empty(shape, dtype=dtype) out = np.empty(shape, dtype=dtype)
for s in product(*[range(k) for k in shape]): for s in product(*[np.arange(k) for k in shape]):
if vals[s] == []: if vals[s] == []:
out[s] = fill_value out[s] = fill_value
else: else:

@ -10,12 +10,12 @@
# Licence: LGPL # Licence: LGPL
# ------------------------------------------------------------------------- # -------------------------------------------------------------------------
from __future__ import absolute_import, division from __future__ import absolute_import, division, print_function
# from abc import ABCMeta, abstractmethod # from abc import ABCMeta, abstractmethod
import copy import copy
import warnings import warnings
import numpy as np import numpy as np
import scipy.stats import scipy.stats as st
from scipy import interpolate, linalg, special from scipy import interpolate, linalg, special
from numpy import sqrt, atleast_2d, meshgrid from numpy import sqrt, atleast_2d, meshgrid
from numpy.fft import fftn, ifftn from numpy.fft import fftn, ifftn
@ -64,12 +64,15 @@ class _KDE(object):
self.xmax = xmax self.xmax = xmax
self.kernel = kernel if kernel else Kernel('gauss') self.kernel = kernel if kernel else Kernel('gauss')
self.args = None
@property @property
def inc(self): def inc(self):
return self._inc return self._inc
@inc.setter @inc.setter
def inc(self, inc): def inc(self, inc):
# pylint: disable=attribute-defined-outside-init
self._inc = inc self._inc = inc
@property @property
@ -78,6 +81,7 @@ class _KDE(object):
@dataset.setter @dataset.setter
def dataset(self, data): def dataset(self, data):
# pylint: disable=attribute-defined-outside-init
self._dataset = atleast_2d(data) self._dataset = atleast_2d(data)
@property @property
@ -103,6 +107,7 @@ class _KDE(object):
def xmin(self, xmin): def xmin(self, xmin):
if xmin is None: if xmin is None:
xmin = self.dataset.min(axis=-1) - 2 * self.sigma xmin = self.dataset.min(axis=-1) - 2 * self.sigma
# pylint: disable=attribute-defined-outside-init
self._xmin = self._check_xmin(xmin*np.ones(self.d)) self._xmin = self._check_xmin(xmin*np.ones(self.d))
def _check_xmin(self, xmin): def _check_xmin(self, xmin):
@ -116,7 +121,7 @@ class _KDE(object):
def xmax(self, xmax): def xmax(self, xmax):
if xmax is None: if xmax is None:
xmax = self.dataset.max(axis=-1) + 2 * self.sigma xmax = self.dataset.max(axis=-1) + 2 * self.sigma
# pylint: disable=attribute-defined-outside-init
self._xmax = self._check_xmax(xmax * np.ones(self.d)) self._xmax = self._check_xmax(xmax * np.ones(self.d))
def _check_xmax(self, xmax): def _check_xmax(self, xmax):
@ -174,7 +179,7 @@ class _KDE(object):
c_levels = qlevels(wdata.data, p=p_levels) c_levels = qlevels(wdata.data, p=p_levels)
wdata.clevels = c_levels wdata.clevels = c_levels
wdata.plevels = p_levels wdata.plevels = p_levels
except Exception as e: except ValueError as e:
msg = "Could not calculate contour levels!. ({})".format(str(e)) msg = "Could not calculate contour levels!. ({})".format(str(e))
warnings.warn(msg) warnings.warn(msg)
@ -459,7 +464,7 @@ class TKDE(_KDE):
f = self._scale_pdf(tf, points) f = self._scale_pdf(tf, points)
return f return f
def _eval_points(self, points): def _eval_points(self, points, **kwds):
"""Evaluate the estimated pdf on a set of points. """Evaluate the estimated pdf on a set of points.
Parameters Parameters
@ -633,6 +638,7 @@ class KDE(_KDE):
if h is None: if h is None:
h = self.kernel.get_smoothing(self.dataset) h = self.kernel.get_smoothing(self.dataset)
h = self._check_hs(h) h = self._check_hs(h)
# pylint: disable=attribute-defined-outside-init
self._inv_hs, deth = self._invert_hs(h) self._inv_hs, deth = self._invert_hs(h)
self._norm_factor = deth * self.n self._norm_factor = deth * self.n
self._hs = h self._hs = h
@ -649,6 +655,7 @@ class KDE(_KDE):
L1 = 10 L1 = 10
inc = max(48, (L1 * xyzrange / (tau * self.hs)).max()) inc = max(48, (L1 * xyzrange / (tau * self.hs)).max())
inc = 2 ** nextpow2(inc) inc = 2 ** nextpow2(inc)
# pylint: disable=attribute-defined-outside-init
self._inc = inc self._inc = inc
@property @property
@ -657,6 +664,7 @@ class KDE(_KDE):
@alpha.setter @alpha.setter
def alpha(self, alpha): def alpha(self, alpha):
# pylint: disable=attribute-defined-outside-init
self._alpha = alpha self._alpha = alpha
self._lambda = np.ones(self.n) self._lambda = np.ones(self.n)
if alpha > 0: if alpha > 0:
@ -881,6 +889,8 @@ class KRegression(object):
self.y = np.atleast_1d(y) self.y = np.atleast_1d(y)
self.p = p self.p = p
self._grdfun = None
def eval_grid_fast(self, *args, **kwds): def eval_grid_fast(self, *args, **kwds):
self._grdfun = self.tkde.eval_grid_fast self._grdfun = self.tkde.eval_grid_fast
return self.tkde.eval_grid_fun(self._eval_gridfun, *args, **kwds) return self.tkde.eval_grid_fun(self._eval_gridfun, *args, **kwds)
@ -941,6 +951,7 @@ class BKRegression(object):
hs1 = self._get_max_smoothing('hste')[0] hs1 = self._get_max_smoothing('hste')[0]
hs2 = self._get_max_smoothing('hos')[0] hs2 = self._get_max_smoothing('hos')[0]
hs_e = sqrt(hs1 * hs2) hs_e = sqrt(hs1 * hs2)
# pylint: disable=attribute-defined-outside-init
self._hs_e = hs_e self._hs_e = hs_e
def _set_smoothing(self, hs): def _set_smoothing(self, hs):
@ -997,7 +1008,6 @@ class BKRegression(object):
# Jeffreys intervall a=b=0.5 # Jeffreys intervall a=b=0.5
# st.beta.isf(alpha/2, y+a, n-y+b) y = n*p, n-y = n*(1-p) # st.beta.isf(alpha/2, y+a, n-y+b) y = n*p, n-y = n*(1-p)
a, b = self.a, self.b a, b = self.a, self.b
st = scipy.stats
pup = np.where(p == 1, 1, pup = np.where(p == 1, 1,
st.beta.isf(alpha / 2, n * p + a, n * (1 - p) + b)) st.beta.isf(alpha / 2, n * p + a, n * (1 - p) + b))
plo = np.where(p == 0, 0, plo = np.where(p == 0, 0,

@ -3,7 +3,7 @@ Created on 15. des. 2016
@author: pab @author: pab
''' '''
from __future__ import division from __future__ import absolute_import, division, print_function
from abc import ABCMeta, abstractmethod from abc import ABCMeta, abstractmethod
import warnings import warnings
import numpy as np import numpy as np
@ -16,6 +16,7 @@ from wafo.misc import tranproc # , trangood
from wafo.kdetools.gridding import gridcount from wafo.kdetools.gridding import gridcount
from wafo.dctpack import dct from wafo.dctpack import dct
from wafo.testing import test_docstrings from wafo.testing import test_docstrings
from six import with_metaclass
__all__ = ['Kernel', 'sphere_volume', 'qlevels', 'iqrange', 'percentile'] __all__ = ['Kernel', 'sphere_volume', 'qlevels', 'iqrange', 'percentile']
@ -260,8 +261,7 @@ def sphere_volume(d, r=1.0):
return (r ** d) * 2.0 * pi ** (d / 2.0) / (d * gamma(d / 2.0)) return (r ** d) * 2.0 * pi ** (d / 2.0) / (d * gamma(d / 2.0))
class _Kernel(object): class _Kernel(with_metaclass(ABCMeta)):
__metaclass__ = ABCMeta
def __init__(self, r=1.0, stats=None, name=''): def __init__(self, r=1.0, stats=None, name=''):
self.r = r # radius of effective support of kernel self.r = r # radius of effective support of kernel
@ -907,14 +907,16 @@ class Kernel(object):
x = np.linspace(0, 0.1, 150) x = np.linspace(0, 0.1, 150)
ai = x[0] ai = x[0]
bi = x[1]
f0 = fixed_point(ai, N, I, a2) f0 = fixed_point(ai, N, I, a2)
for bi in x[1:]: for xi in x[1:]:
bi = xi
f1 = fixed_point(bi, N, I, a2) f1 = fixed_point(bi, N, I, a2)
if f1 * f0 <= 0: if f1 * f0 <= 0:
# print('ai = %g, bi = %g' % (ai,bi)) # print('ai = %g, bi = %g' % (ai,bi))
break break
else: else:
ai = bi ai = xi
# use fzero to solve the equation t=zeta*gamma^[5](t) # use fzero to solve the equation t=zeta*gamma^[5](t)
try: try:

@ -1,12 +1,11 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" """
Dummy conftest.py for wafo. Dummy conftest.py for kdetools.
If you don't know what this is for, just leave it empty. If you don't know what this is for, just leave it empty.
Read more about conftest.py under: Read more about conftest.py under:
https://pytest.org/latest/plugins.html https://pytest.org/latest/plugins.html
""" """
from __future__ import print_function, absolute_import, division from __future__ import print_function, absolute_import, division
# pylint: disable=unused-import
import pytest # @UnusedImport import pytest # @UnusedImport

@ -3,7 +3,7 @@ Created on 23. des. 2016
@author: pab @author: pab
''' '''
from __future__ import division from __future__ import absolute_import, division, print_function
import unittest import unittest
import numpy as np import numpy as np
from numpy.testing import assert_allclose from numpy.testing import assert_allclose

@ -3,7 +3,7 @@ Created on 20. nov. 2010
@author: pab @author: pab
''' '''
from __future__ import division from __future__ import absolute_import, division, print_function
import unittest import unittest
import numpy as np import numpy as np
from numpy.testing import assert_allclose from numpy.testing import assert_allclose
@ -231,7 +231,8 @@ class TestRegression(unittest.TestCase):
0.0317357805015679, -0.0736187558312158, 0.04791463883941161, 0.0317357805015679, -0.0736187558312158, 0.04791463883941161,
0.0660021138871709, -0.1049359954387588, 0.0034961490852392463] 0.0660021138871709, -0.1049359954387588, 0.0034961490852392463]
# print(ei.tolist()) # print(ei.tolist())
y0 = 2*np.exp(-x**2/(2*0.3**2))+3*np.exp(-(x-1)**2/(2*0.7**2)) y0 = 2 * np.exp(-x**2 / (2 * 0.3**2)) + 3 * \
np.exp(-(x - 1)**2 / (2 * 0.7**2))
y = y0 + ei y = y0 + ei
kreg = wk.KRegression(x, y) kreg = wk.KRegression(x, y)
f = kreg(output='plotobj', title='Kernel regression', plotflag=1) f = kreg(output='plotobj', title='Kernel regression', plotflag=1)

@ -3,7 +3,7 @@ Created on 23. des. 2016
@author: pab @author: pab
''' '''
from __future__ import division from __future__ import absolute_import, division, print_function
import unittest import unittest
import numpy as np import numpy as np
from numpy.testing import assert_allclose from numpy.testing import assert_allclose

@ -1,7 +1,7 @@
''' '''
Misc Misc
''' '''
from __future__ import absolute_import, division from __future__ import absolute_import, division, print_function
import sys import sys
from wafo import numba_misc from wafo import numba_misc
import fractions import fractions
@ -37,14 +37,22 @@ __all__ = ['now', 'spaceline', 'narg_smallest', 'args_flat', 'is_numlike',
'findpeaks', 'findrfc', 'rfcfilter', 'findtp', 'findtc', 'findpeaks', 'findrfc', 'rfcfilter', 'findtp', 'findtc',
'findoutliers', 'common_shape', 'argsreduce', 'stirlerr', 'findoutliers', 'common_shape', 'argsreduce', 'stirlerr',
'getshipchar', 'dea3', 'getshipchar', 'dea3',
'betaloge', 'gravity', 'nextpow2', 'discretize', 'polar2cart', 'betaloge', 'gravity', 'nextpow2', 'discretize',
'cart2polar', 'meshgrid', 'ndgrid', 'trangood', 'tranproc', 'polar2cart', 'cart2polar', 'pol2cart', 'cart2pol',
'plot_histgrm', 'num2pistr', 'test_docstrings', 'lazywhere', 'meshgrid', 'ndgrid', 'trangood', 'tranproc',
'lazyselect', 'plot_histgrm', 'num2pistr', 'test_docstrings',
'lazywhere', 'lazyselect',
'piecewise', 'piecewise',
'valarray', 'check_random_state'] 'valarray', 'check_random_state']
def xor(a, b):
"""
Return True only when inputs differ.
"""
return a ^ b
def check_random_state(seed): def check_random_state(seed):
"""Turn seed into a np.random.RandomState instance """Turn seed into a np.random.RandomState instance
@ -87,7 +95,7 @@ def valarray(shape, value=np.NaN, typecode=None):
return out return out
def piecewise(condlist, funclist, xi=None, fill_value=0.0, args=(), **kw): def piecewise(condlist, funclist, xi=None, fillvalue=0.0, args=(), **kw):
""" """
Evaluate a piecewise-defined function. Evaluate a piecewise-defined function.
@ -151,7 +159,7 @@ def piecewise(condlist, funclist, xi=None, fill_value=0.0, args=(), **kw):
|funclist[0](x0[condlist[0]],x1[condlist[0]],...,xn[condlist[0]]) |funclist[0](x0[condlist[0]],x1[condlist[0]],...,xn[condlist[0]])
out = |funclist[1](x0[condlist[1]],x1[condlist[1]],...,xn[condlist[1]]) out = |funclist[1](x0[condlist[1]],x1[condlist[1]],...,xn[condlist[1]])
|... |...
|funclist[n2](x0[condlist[n2]],x1[condlist[n2]],...,xn[condlist[n2]]) |funclist[n2](x0[condlist[n2]], x1[condlist[n2]],..,xn[condlist[n2]])
|-- |--
Examples Examples
@ -159,8 +167,9 @@ def piecewise(condlist, funclist, xi=None, fill_value=0.0, args=(), **kw):
Define the sigma function, which is -1 for ``x < 0`` and +1 for ``x >= 0``. Define the sigma function, which is -1 for ``x < 0`` and +1 for ``x >= 0``.
>>> x = np.linspace(-2.5, 2.5, 6) >>> x = np.linspace(-2.5, 2.5, 6)
>>> piecewise([x < 0, x >= 0], [-1, 1]) >>> np.allclose(piecewise([x < 0, x >= 0], [-1, 1]),
array([-1., -1., -1., 1., 1., 1.]) ... [-1, -1, -1, 1, 1, 1])
True
Define the absolute value, which is ``-x`` for ``x <0`` and ``x`` for Define the absolute value, which is ``-x`` for ``x <0`` and ``x`` for
``x >= 0``. ``x >= 0``.
@ -185,8 +194,7 @@ def piecewise(condlist, funclist, xi=None, fill_value=0.0, args=(), **kw):
def check_shapes(condlist, funclist): def check_shapes(condlist, funclist):
nc, nf = len(condlist), len(funclist) nc, nf = len(condlist), len(funclist)
if nc not in [nf - 1, nf]: _assert(nc in [nf - 1, nf], "function list and condition list"
raise ValueError("function list and condition list" +
" must be the same length") " must be the same length")
check_shapes(condlist, funclist) check_shapes(condlist, funclist)
@ -197,21 +205,20 @@ def piecewise(condlist, funclist, xi=None, fill_value=0.0, args=(), **kw):
if xi is None: if xi is None:
arrays = () arrays = ()
dtype = np.result_type(*funclist) dtype = np.result_type(*funclist)
shape = condlist[0].shape
else: else:
if not isinstance(xi, tuple): if not isinstance(xi, tuple):
xi = (xi,) xi = (xi,)
arrays = np.broadcast_arrays(*xi) arrays = np.broadcast_arrays(*xi)
dtype = np.result_type(*arrays) dtype = np.result_type(*arrays)
shape = arrays[0].shape
out = valarray(shape, fill_value, dtype) out = valarray(condlist[0].shape, fillvalue, dtype)
for cond, func in zip(condlist, funclist): for cond, func in zip(condlist, funclist):
if isinstance(func, Callable): if cond.any():
temp = tuple(np.extract(cond, arr) for arr in arrays) + args if isinstance(func, collections.Callable):
np.place(out, cond, func(*temp, **kw)) temp = tuple(np.extract(cond, arr) for arr in arrays) + args
else: # func is a scalar value or a list np.place(out, cond, func(*temp, **kw))
np.putmask(out, cond, func) else: # func is a scalar value or a array
np.putmask(out, cond, func)
return out return out
@ -223,12 +230,12 @@ def lazywhere(cond, arrays, f, fillvalue=None, f2=None):
>>> a, b = np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8]) >>> a, b = np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8])
>>> def f(a, b): >>> def f(a, b):
... return a*b ... return a*b
>>> def f2(a, b):
... return np.ones(np.shape(a))*np.ones(np.shape(b))
>>> lazywhere(a > 2, (a, b), f, np.nan) >>> lazywhere(a > 2, (a, b), f, np.nan)
array([ nan, nan, 21., 32.]) array([ nan, nan, 21., 32.])
>>> def f2(a, b):
... return (a*b)**2
>>> lazywhere(a > 2, (a, b), f, f2=f2) >>> lazywhere(a > 2, (a, b), f, f2=f2)
array([ 1., 1., 21., 32.]) array([ 25., 144., 21., 32.])
Notice it assumes that all `arrays` are of the same shape, or can be Notice it assumes that all `arrays` are of the same shape, or can be
broadcasted together. broadcasted together.
@ -293,6 +300,10 @@ def lazyselect(condlist, choicelist, arrays, default=0):
def rotation_matrix(heading, pitch, roll): def rotation_matrix(heading, pitch, roll):
''' '''
Parameters
----------
heading, pitch, roll : real scalars
defining heading, pitch and roll in degrees.
Examples Examples
-------- --------
@ -681,7 +692,7 @@ class Bunch(object):
self.__dict__.update(kwargs) self.__dict__.update(kwargs)
def printf(format_, *args): def printf(format_, *args): # @ReservedAssignment
sys.stdout.write(format_ % args) sys.stdout.write(format_ % args)
@ -748,6 +759,7 @@ def detrendma(x, L):
Examples Examples
-------- --------
>>> import matplotlib.pyplot as plt
>>> import numpy as np >>> import numpy as np
>>> import wafo.misc as wm >>> import wafo.misc as wm
>>> exp = np.exp; cos = np.cos; randn = np.random.randn >>> exp = np.exp; cos = np.cos; randn = np.random.randn
@ -767,7 +779,6 @@ def detrendma(x, L):
>>> np.allclose(wm.detrendma(x2, L=1), [-1, 0, 0, 0, 1]) >>> np.allclose(wm.detrendma(x2, L=1), [-1, 0, 0, 0, 1])
True True
import pylab as plt
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')
@ -776,7 +787,7 @@ def detrendma(x, L):
Reconstruct Reconstruct
""" """
_assert(0 < L, 'L must be positive') _assert(0 < L, 'L must be positive')
_assert(L == round(L), 'L must be an integer') _assert(L == np.round(L), 'L must be an integer')
x1 = np.atleast_1d(x) x1 = np.atleast_1d(x)
if x1.shape[0] == 1: if x1.shape[0] == 1:
@ -820,7 +831,7 @@ def ecross(t, f, ind, v=0):
Example Example
------- -------
>>> from matplotlib import pylab as plt >>> from matplotlib import pyplot as plt
>>> import wafo.misc 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)
@ -857,12 +868,6 @@ def _findcross(xn, method='clib'):
return numba_misc.findcross(xn) return numba_misc.findcross(xn)
def xor(a, b):
"""
Return True only when inputs differ.
"""
return a ^ b
def findcross(x, v=0.0, kind=None, method='clib'): def findcross(x, v=0.0, kind=None, method='clib'):
''' '''
@ -891,7 +896,7 @@ def findcross(x, v=0.0, kind=None, method='clib'):
Example Example
------- -------
>>> from matplotlib import pylab as plt >>> from matplotlib import pyplot as plt
>>> import wafo.misc as wm >>> import wafo.misc as wm
>>> ones = np.ones >>> ones = np.ones
>>> np.allclose(findcross([0, 1, -1, 1], 0), [0, 1, 2]) >>> np.allclose(findcross([0, 1, -1, 1], 0), [0, 1, 2])
@ -935,19 +940,20 @@ def findcross(x, v=0.0, kind=None, method='clib'):
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 the first is a level v down-crossing # make sure that the first is a level v down-crossing
# if kind=='dw' or kind=='tw' # if kind=='dw' or kind=='tw'
# or make sure the first is a level v up-crossing # or that the first is a level v up-crossing
# if kind=='uw' or kind=='cw' # if kind=='uw' or kind=='cw'
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 kind is dw or uw # wavedef, i.e., make sure length(ind) is odd if dw or uw
# and even if kind is tw or cw # and even if tw or cw
is_odd = mod(ind.size, 2) is_odd = mod(n_c, 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:
@ -971,7 +977,7 @@ def findextrema(x):
Examples Examples
-------- --------
>>> import numpy as np >>> import numpy as np
>>> import pylab as plt >>> import matplotlib.pyplot as plt
>>> import wafo.misc as wm >>> import wafo.misc as wm
>>> t = np.linspace(0,7*np.pi,250) >>> t = np.linspace(0,7*np.pi,250)
>>> x = np.sin(t) >>> x = np.sin(t)
@ -1268,7 +1274,7 @@ def findtp(x, h=0.0, kind=None):
Example: Example:
-------- --------
>>> import pylab as plt >>> import matplotlib.pyplot as plt
>>> import wafo.misc as wm >>> import wafo.misc 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) + 0.3 * np.sin(5*t))) >>> x = np.hstack((t, np.cos(t) + 0.3 * np.sin(5*t)))
@ -1370,7 +1376,7 @@ def findtc(x_in, v=None, kind=None):
Example: Example:
-------- --------
>>> import pylab as plt >>> import matplotlib.pyplot as plt
>>> import wafo.misc as wm >>> import wafo.misc 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)))
@ -1575,8 +1581,7 @@ def findoutliers(x, zcrit=0.0, dcrit=None, ddcrit=None, verbose=False):
def common_shape(*args, ** kwds): def common_shape(*args, ** kwds):
''' """Return the common shape of a sequence of arrays.
Return the common shape of a sequence of arrays
Parameters Parameters
----------- -----------
@ -1610,7 +1615,8 @@ def common_shape(*args, ** kwds):
See also See also
-------- --------
broadcast, broadcast_arrays broadcast, broadcast_arrays
'''
"""
shape = kwds.get('shape') shape = kwds.get('shape')
x0 = 1 if shape is None else np.ones(shape) x0 = 1 if shape is None else np.ones(shape)
return tuple(np.broadcast(x0, *args).shape) return tuple(np.broadcast(x0, *args).shape)
@ -1946,9 +1952,9 @@ def gravity(phi=45):
>>> import wafo.misc as wm >>> import wafo.misc 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)-np.array([ 9.78049 , 9.78245014, 9.78803583, >>> np.allclose(wm.gravity(phi),
... 9.79640552, 9.80629387]))<1.e-7 ... [ 9.78049 , 9.78245014, 9.78803583, 9.79640552, 9.80629387])
array([ True, True, True, True, True], dtype=bool) True
See also See also
-------- --------
@ -2018,15 +2024,13 @@ def discretize(fun, a, b, tol=0.005, n=5, method='linear'):
------- -------
>>> import wafo.misc as wm >>> import wafo.misc as wm
>>> import numpy as np >>> import numpy as np
>>> import pylab as plt >>> import matplotlib.pyplot as plt
>>> x,y = wm.discretize(np.cos, 0, np.pi) >>> x,y = wm.discretize(np.cos, 0, np.pi)
>>> np.allclose(x[:5], >>> np.allclose(x[:5], [0., 0.19634954, 0.39269908, 0.58904862, 0.78539816])
... [ 0. , 0.19634954, 0.39269908, 0.58904862, 0.78539816])
True True
>>> xa,ya = wm.discretize(np.cos, 0, np.pi, method='adaptive') >>> xa,ya = wm.discretize(np.cos, 0, np.pi, method='adaptive')
>>> np.allclose(xa[:5], >>> np.allclose(xa[:5], [0., 0.19634954, 0.39269908, 0.58904862, 0.78539816])
... [ 0. , 0.19634954, 0.39269908, 0.58904862, 0.78539816])
True True
@ -2306,11 +2310,11 @@ def tranproc(x, f, x0, *xi):
Example Example
-------- --------
Derivative of g and the transformed Gaussian model. Derivative of g and the transformed Gaussian model.
>>> import pylab as plt >>> import matplotlib.pyplot as plt
>>> import wafo.misc as wm >>> import wafo.misc as wm
>>> import wafo.transform.models as wtm >>> import wafo.transform.models as wtm
>>> tr = wtm.TrHermite() >>> tr = wtm.TrHermite()
>>> x = linspace(-5,5,501) >>> x = np.linspace(-5, 5, 501)
>>> g = tr(x) >>> g = tr(x)
>>> gder = wm.tranproc(x, g, x, ones(g.shape[0])) >>> gder = wm.tranproc(x, g, x, ones(g.shape[0]))
>>> np.allclose(gder[1][:5], >>> np.allclose(gder[1][:5],
@ -2542,7 +2546,7 @@ def plot_histgrm(data, bins=None, range=None, # @ReservedAssignment
Example Example
------- -------
>>> import pylab as plt >>> import matplotlib.pyplot as plt
>>> import wafo.misc as wm >>> import wafo.misc as wm
>>> import wafo.stats as ws >>> import wafo.stats as ws
>>> R = ws.weibull_min.rvs(2,loc=0,scale=2, size=100) >>> R = ws.weibull_min.rvs(2,loc=0,scale=2, size=100)
@ -2551,10 +2555,11 @@ def plot_histgrm(data, bins=None, range=None, # @ReservedAssignment
>>> len(bins) >>> len(bins)
13 13
h0 = wm.plot_histgrm(R, bins, normed=True) >>> x = np.linspace(-3,16,200)
x = np.linspace(-3,16,200) >>> pdf = ws.weibull_min.pdf(x,2,0,2)
h1 = plt.plot(x,ws.weibull_min.pdf(x,2,0,2),'r') h0 = wm.plot_histgrm(R, 20, normed=True)
h1 = plt.plot(x, pdf,'r')
plt.close('all') plt.close('all')
See also See also
@ -2657,10 +2662,11 @@ def fourier(data, t=None, period=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, period=T, m=5) >>> a, b = wm.fourier(x, t, period=T, m=5)
>>> np.abs(a.ravel())<1e-12 >>> np.allclose(a, 0)
array([ True, True, True, True, True], dtype=bool) True
>>> np.abs(b.ravel()-np.array([ 0., 4., 0., 0., 0.]))<1e-12 >>> np.allclose(b.ravel(),
array([ True, True, True, True, True], dtype=bool) ... [ 0., 4., 0., 0., 0.])
True
See also See also
-------- --------

@ -17,7 +17,7 @@
# Licence: LGPL # Licence: LGPL
# ------------------------------------------------------------------------ # ------------------------------------------------------------------------
# !/usr/bin/env python # !/usr/bin/env python
from __future__ import absolute_import from __future__ import absolute_import, division, print_function
import warnings # @UnusedImport import warnings # @UnusedImport
from functools import reduce from functools import reduce
from numpy.polynomial import polyutils as pu from numpy.polynomial import polyutils as pu
@ -374,14 +374,17 @@ def ortho2poly(p):
>>> x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) >>> x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
>>> y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0]) >>> y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
>>> p = wp.orthofit(x, y, 3) >>> p = wp.orthofit(x, y, 3)
>>> p
array([[ 0. , -0.30285714, -0.16071429, 0.08703704], >>> np.allclose(p,[[ 0. , -0.30285714, -0.16071429, 0.08703704],
[ 0. , 2.5 , 2.5 , 2.5 ], ... [ 0. , 2.5 , 2.5 , 2.5 ],
[ 0. , 0. , 2.91666667, 2.13333333]]) ... [ 0. , 0. , 2.91666667, 2.13333333]])
>>> wp.ortho2poly(p) True
array([ 0.08703704, -0.81349206, 1.69312169, -0.03968254]) >>> np.allclose(wp.ortho2poly(p),
>>> wp.polyfit(x, y, 3) ... [ 0.08703704, -0.81349206, 1.69312169, -0.03968254])
array([ 0.08703704, -0.81349206, 1.69312169, -0.03968254]) True
>>> np.allclose(np.polyfit(x, y, 3),
... [ 0.08703704, -0.81349206, 1.69312169, -0.03968254])
True
References References
---------- ----------

Loading…
Cancel
Save