From b72aad3b8d295ad9c7ee8957f6998ec9d0ae985e Mon Sep 17 00:00:00 2001 From: "Per.Andreas.Brodtkorb" Date: Sun, 1 Feb 2015 11:20:48 +0000 Subject: [PATCH] pep8 + build extensions for windows --- pywafo/src/wafo/c_library.pyd | Bin 96229 -> 96229 bytes pywafo/src/wafo/cov2mod.pyd | Bin 151805 -> 151805 bytes pywafo/src/wafo/dctpack.py | 47 ++++++++------- pywafo/src/wafo/demo_sg.py | 29 +++++---- pywafo/src/wafo/f2py_tools.py | 63 ++++++++++++++++++++ pywafo/src/wafo/misc.py | 1 - pywafo/src/wafo/mvn.pyd | Bin 137405 -> 137405 bytes pywafo/src/wafo/mvnprdmod.pyd | Bin 167918 -> 167918 bytes pywafo/src/wafo/plotbackend.py | 4 +- pywafo/src/wafo/rindmod.pyd | Bin 413434 -> 413434 bytes pywafo/src/wafo/sg_filter.py | 2 +- pywafo/src/wafo/source/mvn/mvn.pyd | Bin 137405 -> 137405 bytes pywafo/src/wafo/source/mvnprd/mvnprdmod.pyd | Bin 167918 -> 167918 bytes pywafo/src/wafo/source/rind2007/rindmod.pyd | Bin 413434 -> 413434 bytes pywafo/src/wafo/transform/models.py | 26 ++++---- pywafo/src/wafo/wafodata.py | 55 +++++++++-------- pywafo/src/wafo/win32_utils.py | 4 +- 17 files changed, 151 insertions(+), 80 deletions(-) create mode 100644 pywafo/src/wafo/f2py_tools.py diff --git a/pywafo/src/wafo/c_library.pyd b/pywafo/src/wafo/c_library.pyd index 57f0ea821f455ae43def3eba4433af69f61a1d71..5b6243eddb2668d37200cb01bde5665ca8a54943 100644 GIT binary patch delta 31 mcmaF*p7rT_)(IWVJ2=lx?Dl2)b7A8xt>qxzX7&~L&I14mco2~Q delta 31 mcmaF*p7rT_)(IWVb0xM+?Dl1v^lsxVt>qxzX7&~L&I14dybt*R diff --git a/pywafo/src/wafo/cov2mod.pyd b/pywafo/src/wafo/cov2mod.pyd index c1290478f9a85edbb77ded3a047ee42c83c69898..7f295721112ab58e3afd6a7c0f6d8409e9eca8bb 100644 GIT binary patch delta 35 pcmeynkn`_C&IujN2RP47?Dl1n$!)x~^%kR6EJ$EGdmQ7pPXHz@5C#AM delta 35 pcmeynkn`_C&IujNizT*9?Dl0^*VTAy>n%pDSdhSW_Bh6Gp8zf25M=-W diff --git a/pywafo/src/wafo/dctpack.py b/pywafo/src/wafo/dctpack.py index a6224ad..6408108 100644 --- a/pywafo/src/wafo/dctpack.py +++ b/pywafo/src/wafo/dctpack.py @@ -1,5 +1,5 @@ import numpy as np -from scipy.fftpack import _fftpack +# from scipy.fftpack import _fftpack from scipy.fftpack import dct as _dct from scipy.fftpack import idct as _idct import os @@ -127,7 +127,7 @@ def dct(x, type=2, n=None, axis=-1, norm='ortho'): # @ReservedAssignment # Hack until scipy.fftpack.dct implement this functionality x = _truncate_or_zero_pad(x, n, axis) n = None - return _dct(x, type, n, axis, norm) + # return _dct(x, type, n, axis, norm) dtype = np.result_type(np.float32, np.asarray(x)) x0 = np.asarray(x, dtype=dtype) if dtype == complex: @@ -137,21 +137,21 @@ def dct(x, type=2, n=None, axis=-1, norm='ortho'): # @ReservedAssignment return _dct(x0, type, n, axis, norm) -def test(type=2, dtype=None, normalize='ortho'): # @ReservedAssignment - dtype = np.result_type(np.float64) - try: - nm = {None: 0, 'ortho': 1}[normalize] - except KeyError: - raise ValueError("Unknown normalize mode %s" % normalize) - try: - name = {'float64': 'ddct%d', 'float32': 'dct%d'}[dtype.name] - except KeyError: - raise ValueError("dtype %s not supported" % dtype) - try: - f = getattr(_fftpack, name % type) - except AttributeError as e: - raise ValueError(str(e) + ". Type %d not understood" % type) - return f, nm +# def test(type=2, dtype=None, normalize='ortho'): # @ReservedAssignment +# dtype = np.result_type(np.float64) +# try: +# nm = {None: 0, 'ortho': 1}[normalize] +# except KeyError: +# raise ValueError("Unknown normalize mode %s" % normalize) +# try: +# name = {'float64': 'ddct%d', 'float32': 'dct%d'}[dtype.name] +# except KeyError: +# raise ValueError("dtype %s not supported" % dtype) +# try: +# f = getattr(_fftpack, name % type) +# except AttributeError as e: +# raise ValueError(str(e) + ". Type %d not understood" % type) +# return f, nm def idct(x, type=2, n=None, axis=-1, norm='ortho'): # @ReservedAssignment @@ -437,8 +437,8 @@ def test_dctn(): print(x) print(' ') - yn = dctn(a) #, shape=(10,), axes=(1,)) - xn = idctn(yn) #, axes=(1,)) + yn = dctn(a) # , shape=(10,), axes=(1,)) + xn = idctn(yn) # , axes=(1,)) print('yn = dctn(a)') print(yn) print('xn = idctn(yn)') @@ -446,6 +446,7 @@ def test_dctn(): print(' ') print xn-a + def test_dct2(): import scipy.ndimage as sn import matplotlib.pyplot as plt @@ -481,8 +482,14 @@ def test_docstrings(): doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE) +def test_commands(): + import commands + commands.getstatusoutput('preprocess -DFORMAT=html -DDEVICE=screen tutorial.do.txt > tmp_preprocess__tutorial.do.txt') + + if __name__ == '__main__': - test_dct2() + print(test_commands()) + # test_dct2() # test_docstrings() # test_dctn() # test_shiftdim() diff --git a/pywafo/src/wafo/demo_sg.py b/pywafo/src/wafo/demo_sg.py index ce15cb1..66cdeda 100644 --- a/pywafo/src/wafo/demo_sg.py +++ b/pywafo/src/wafo/demo_sg.py @@ -1,6 +1,7 @@ -# @UnresolvedImport -from pylab import subplot, plot, title, savefig, figure, arange, sin, random -from sg_filter import calc_coeff, smooth +import matplotlib.pyplot as plt +from pylab import subplot, plot, title, figure +from numpy import random, arange, sin +from sg_filter import SavitzkyGolay, smoothn # calc_coeff, smooth figure(figsize=(7, 12)) @@ -8,11 +9,11 @@ figure(figsize=(7, 12)) # generate chirp signal tvec = arange(0, 6.28, .02) -signal = sin(tvec * (2.0 + tvec)) +true_signal = sin(tvec * (2.0 + tvec)) # add noise to signal -noise = random.normal(size=signal.shape) -signal += (2000. + .15 * noise) +noise = random.normal(size=true_signal.shape) +signal = true_signal + .15 * noise # plot signal subplot(311) @@ -21,19 +22,21 @@ title('signal') # smooth and plot signal subplot(312) -coeff = calc_coeff(8, 4) -s_signal = smooth(signal, coeff) - +savgol = SavitzkyGolay(n=8, degree=4) +s_signal = savgol.smooth(signal) +s2 = smoothn(signal, robust=True) plot(s_signal) +plot(s2) +plot(true_signal, 'r--') title('smoothed signal') # smooth derivative of signal and plot it subplot(313) -coeff = calc_coeff(8, 1, 1) -d_signal = smooth(signal, coeff) +savgol1 = SavitzkyGolay(n=8, degree=1, diff_order=1) + +d_signal = savgol1.smooth(signal) plot(d_signal) title('smoothed derivative of signal') -# show plot -savefig("savitzky.png") +plt.show('hold') # show plot diff --git a/pywafo/src/wafo/f2py_tools.py b/pywafo/src/wafo/f2py_tools.py new file mode 100644 index 0000000..45bcb5a --- /dev/null +++ b/pywafo/src/wafo/f2py_tools.py @@ -0,0 +1,63 @@ +""" +f2py c_library.pyf c_functions.c -c + +See also http://www.scipy.org/Cookbook/CompilingExtensionsOnWindowsWithMinGW +""" +import os +import sys + + +def which(program): + """ + Return filepath to program if it exists + + In order to test if a certain executable exists, it will search for the + program name in the environment variables. + If program is a full path to an executable, it will check it exists + + Copied from: + http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python/ + It is supposed to mimic the UNIX command "which" + """ + + def is_exe(fpath): + return os.path.exists(fpath) and os.access(fpath, os.X_OK) + + fpath, unused_fname = os.path.split(program) + if fpath: + if is_exe(program): + return program + else: + for path in os.environ["PATH"].split(os.pathsep): + exe_file = os.path.join(path, program) + if is_exe(exe_file): + return exe_file + + return None + + +def f2py_call_str(): + '''Return which f2py callable is in the path regardless of platform''' + + # define possible options: + # on Arch Linux, python and f2py are the calls corresponding to python 3 + # and python2/f2py2 for python 2 + # other Linux versions might still use python/f2py for python 2 + + if os.path.basename(sys.executable).endswith('2'): + options = ('f2py2', 'f2py2.6', 'f2py2.7',) + else: # on Windows and other Linux using python/f2py + options = ('f2py.bat', 'f2py', 'f2py2.6', 'f2py2.7', 'f2py.py',) + for k in options: + if which(k): + # Found the f2py path, no need to look further + f2py_call = k + f2py_path = which(k) + break + + try: + print 'found f2py in:', f2py_path + return f2py_call + except NameError: + raise UserWarning('Couldn\'t locate f2py. ' + 'Should be part of NumPy installation.') diff --git a/pywafo/src/wafo/misc.py b/pywafo/src/wafo/misc.py index 468bb58..6fa00cb 100644 --- a/pywafo/src/wafo/misc.py +++ b/pywafo/src/wafo/misc.py @@ -2,7 +2,6 @@ Misc ''' from __future__ import division - import sys import fractions import numpy as np diff --git a/pywafo/src/wafo/mvn.pyd b/pywafo/src/wafo/mvn.pyd index c76f9e22e335316ab7465e4ce3c2f602e14615ae..5dbb792dee15dac821244c4e0c0007e3000815c4 100644 GIT binary patch delta 35 qcmdnHkz?;hjtL#iM>)?;?Dl1v{=f0o)?18Pk|2TY>{5)|{s90e;t&4- delta 35 pcmdnHkz?;hjtL#i%O$oYIN DL*W+U delta 48 zcmex0SMt|f$q60I>m{~K?Dl0!DQmpddW*637E|jj=B>9_w9bNL+S$*sY-c~m`ndrB DF2NQi diff --git a/pywafo/src/wafo/sg_filter.py b/pywafo/src/wafo/sg_filter.py index 157ed29..5b1059e 100644 --- a/pywafo/src/wafo/sg_filter.py +++ b/pywafo/src/wafo/sg_filter.py @@ -14,7 +14,7 @@ from scipy.ndimage.morphology import distance_transform_edt import warnings from wafo.plotbackend import plotbackend as plt -__all__ = ['SavitzkyGolay', 'Kalman', 'HodrickPrescott'] +__all__ = ['SavitzkyGolay', 'Kalman', 'HodrickPrescott', 'smoothn'] class SavitzkyGolay(object): diff --git a/pywafo/src/wafo/source/mvn/mvn.pyd b/pywafo/src/wafo/source/mvn/mvn.pyd index 3fba514c4a3fc71f49a68cce7a0de96b6b4defa0..5dbb792dee15dac821244c4e0c0007e3000815c4 100644 GIT binary patch delta 35 qcmdnHkz?;hjtL#iM>)?;?Dl1v{=f0o)?18Pk|2TY>{5)|{s90e;t&4- delta 35 pcmdnHkz?;hjtL#i4ymUncKb4QY-_x=^%kR+BuHR8yAb5#IcqYu9T delta 40 ucmaDipX=Rxt_dB?uBoRdcKb4aKFrj3d+TjR%}kI;J9`%6cJ?f$=c)jE=Mf12 diff --git a/pywafo/src/wafo/source/rind2007/rindmod.pyd b/pywafo/src/wafo/source/rind2007/rindmod.pyd index a038fca6c76c1cc669e56212040ff02bdbd8b3d5..e497cd4953e0626c244ca028d8ca098b86c89f45 100644 GIT binary patch delta 49 zcmex0SMt|f$q60ImpRW(?Dl1T5W&`XyY)6>>usji+ss>UvuK_LNwu?|W7*Drj`ec` E08Q-{?EnA( delta 49 zcmex0SMt|f$q60I-l?Z2cKb4);%9HX-Flm`^)^%MZRV}FSv1drq}tifv215Q$NISe E05`7|F#rGn diff --git a/pywafo/src/wafo/transform/models.py b/pywafo/src/wafo/transform/models.py index 2fb9d31..4d6a821 100644 --- a/pywafo/src/wafo/transform/models.py +++ b/pywafo/src/wafo/transform/models.py @@ -7,7 +7,7 @@ TrLinear ''' # !/usr/bin/env python from __future__ import division -from scipy.optimize import brentq +from scipy.optimize import brentq # @UnresolvedImport from numpy import (sqrt, atleast_1d, abs, imag, sign, where, cos, arccos, ceil, expm1, log1p, pi) import numpy as np @@ -106,10 +106,10 @@ class TrHermite(TrCommon2): Example: -------- """ + _example.replace('', 'TrHermite') + """ - >>> g.dist2gauss() - 0.88230868748851499 - >>> g2.dist2gauss() - 1.1411663205144991 + >>> np.allclose(g.dist2gauss(), 0.88230868748851499) + True + >>> np.allclose(g2.dist2gauss(), 1.1411663205144991) + True See also -------- @@ -336,10 +336,10 @@ class TrLinear(TrCommon2): Example: -------- """ + _example.replace('', 'TrLinear') + """ - >>> g.dist2gauss() - 0.0 - >>> g2.dist2gauss() - 3.8594770921678001e-31 + >>> np.allclose(g.dist2gauss(), 0) + True + >>> np.allclose(g2.dist2gauss(), 0) + True See also -------- @@ -404,10 +404,10 @@ class TrOchi(TrCommon2): Example ------- """ + _example.replace('', 'TrOchi') + """ - >>> g.dist2gauss() - 1.410698801056657 - >>> g2.dist2gauss() - 1.988807188766706 + >>> np.allclose(g.dist2gauss(), 1.410698801056657) + True + >>> np.allclose(g2.dist2gauss(), 1.988807188766706) + True See also -------- diff --git a/pywafo/src/wafo/wafodata.py b/pywafo/src/wafo/wafodata.py index 57a2a5e..5faea07 100644 --- a/pywafo/src/wafo/wafodata.py +++ b/pywafo/src/wafo/wafodata.py @@ -21,7 +21,7 @@ def empty_copy(obj): def _set_seed(iseed): - if iseed != None: + if iseed is not None: try: np.random.set_state(iseed) except: @@ -29,16 +29,13 @@ def _set_seed(iseed): def now(): - ''' - Return current date and time as a string - ''' + """Return current date and time as a string.""" return strftime("%a, %d %b %Y %H:%M:%S", gmtime()) class PlotData(object): - ''' - Container class for data objects in WAFO + """Container class for data objects in WAFO. Member variables ---------------- @@ -72,7 +69,8 @@ class PlotData(object): -------- specdata, covdata - ''' + + """ def __init__(self, data=None, args=None, *args2, **kwds): self.data = data @@ -95,7 +93,7 @@ class PlotData(object): axis = plotbackend.gca() tmp = None plotflag = kwds.get('plotflag', None) - if not plotflag and self.children != None: + if not plotflag and self.children is not None: plotbackend.hold('on') tmp = [] child_args = kwds.pop( @@ -105,7 +103,7 @@ class PlotData(object): child_kwds['axis'] = axis for child in self.children: tmp1 = child.plot(*child_args, **child_kwds) - if tmp1 != None: + if tmp1 is not None: tmp.append(tmp1) if len(tmp) == 0: tmp = None @@ -179,9 +177,8 @@ class PlotData(object): return newcopy def setplotter(self, plotmethod=None): - ''' - Set plotter based on the data type data_1d, data_2d, data_3d or data_nd - ''' + """Set plotter based on the data type data_1d, data_2d, data_3d or + data_nd.""" if isinstance(self.args, (list, tuple)): # Multidimensional data ndim = len(self.args) if ndim < 2: @@ -212,7 +209,8 @@ class AxisLabels: return self.__str__() def __str__(self): - return '%s\n%s\n%s\n%s\n' % (self.title, self.xlab, self.ylab, self.zlab) + return '%s\n%s\n%s\n%s\n' % (self.title, self.xlab, self.ylab, + self.zlab) def copy(self): newcopy = empty_copy(self) @@ -226,7 +224,7 @@ class AxisLabels: h1 = axis.set_title(self.title) h2 = axis.set_xlabel(self.xlab) h3 = axis.set_ylabel(self.ylab) - #h4 = plotbackend.zlabel(self.zlab) + # h4 = plotbackend.zlabel(self.zlab) return h1, h2, h3 except: pass @@ -306,8 +304,9 @@ def plot1d(axis, args, data, dataCI, plotflag, *varargin, **kwds): elif plottype == 3: H = axis.stem(args, data, *varargin, **kwds) elif plottype == 4: - H = axis.errorbar( - args, data, yerr=[dataCI[:, 0] - data, dataCI[:, 1] - data], *varargin, **kwds) + H = axis.errorbar(args, data, + yerr=[dataCI[:, 0] - data, dataCI[:, 1] - data], + *varargin, **kwds) elif plottype == 5: H = axis.bar(args, data, *varargin, **kwds) elif plottype == 6: @@ -354,13 +353,12 @@ def plot1d(axis, args, data, dataCI, plotflag, *varargin, **kwds): def plotscale(plotflag): - ''' - Return plotscale from plotflag + """Return plotscale from plotflag. CALL scale = plotscale(plotflag) plotflag = integer defining plotscale. - Let scaleId = floor(plotflag/100). + Let scaleId = floor(plotflag/100). If scaleId < 8 then: 0 'linear' : Linear scale on all axes. 1 'xlog' : Log scale on x-axis. @@ -377,11 +375,11 @@ def plotscale(plotflag): scale = string defining plotscale valid options are: 'linear', 'xlog', 'ylog', 'xylog', 'zlog', 'xzlog', - 'yzlog', 'xyzlog' + 'yzlog', 'xyzlog' Example >>> for id in range(100,701,100): - ... plotscale(id) + ... plotscale(id) 'xlog' 'ylog' 'xylog' @@ -390,17 +388,18 @@ def plotscale(plotflag): 'yzlog' 'xyzlog' - >>> plotscale(200) + >>> plotscale(200) 'ylog' - >>> plotscale(300) + >>> plotscale(300) 'xylog' - >>> plotscale(300) + >>> plotscale(300) 'xylog' - See also + See also -------- transformdata - ''' + + """ scaleId = plotflag // 100 if scaleId > 7: logXscaleId = np.mod(scaleId, 10) > 0 @@ -429,8 +428,8 @@ def transformdata(x, f, plotflag): data = -np.log1p(-cumtrapz(f, x)) else: if any(f < 0): - raise ValueError( - 'Invalid plotflag: Data or dataCI is negative, but must be positive') + raise ValueError('Invalid plotflag: Data or dataCI is ' + 'negative, but must be positive') data = 10 * np.log10(f) return data diff --git a/pywafo/src/wafo/win32_utils.py b/pywafo/src/wafo/win32_utils.py index 086e0ef..3e53b1c 100644 --- a/pywafo/src/wafo/win32_utils.py +++ b/pywafo/src/wafo/win32_utils.py @@ -223,7 +223,7 @@ class WarnDlg(Thread): self.start() # Run the thread def run(self): -# MessageBox(self.message, self.title, win32con.MB_ICONWARNING) + # MessageBox(self.message, self.title, win32con.MB_ICONWARNING) MessageBox(0, self.message, self.title, win32con.MB_ICONWARNING | win32con.MB_SYSTEMMODAL) @@ -240,7 +240,7 @@ class ErrorDlg(Thread): self.start() # Run in thread def run(self): -# MessageBox(self.message, self.title, win32con.MB_ICONERROR) + # MessageBox(self.message, self.title, win32con.MB_ICONERROR) MessageBox(0, self.message, self.title, win32con.MB_ICONERROR | win32con.MB_SYSTEMMODAL)