pep8 + build extensions for windows

master
Per.Andreas.Brodtkorb 10 years ago
parent 989bce6795
commit b72aad3b8d

Binary file not shown.

Binary file not shown.

@ -1,5 +1,5 @@
import numpy as np 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 dct as _dct
from scipy.fftpack import idct as _idct from scipy.fftpack import idct as _idct
import os 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 # Hack until scipy.fftpack.dct implement this functionality
x = _truncate_or_zero_pad(x, n, axis) x = _truncate_or_zero_pad(x, n, axis)
n = None 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)) dtype = np.result_type(np.float32, np.asarray(x))
x0 = np.asarray(x, dtype=dtype) x0 = np.asarray(x, dtype=dtype)
if dtype == complex: 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) return _dct(x0, type, n, axis, norm)
def test(type=2, dtype=None, normalize='ortho'): # @ReservedAssignment # def test(type=2, dtype=None, normalize='ortho'): # @ReservedAssignment
dtype = np.result_type(np.float64) # dtype = np.result_type(np.float64)
try: # try:
nm = {None: 0, 'ortho': 1}[normalize] # nm = {None: 0, 'ortho': 1}[normalize]
except KeyError: # except KeyError:
raise ValueError("Unknown normalize mode %s" % normalize) # raise ValueError("Unknown normalize mode %s" % normalize)
try: # try:
name = {'float64': 'ddct%d', 'float32': 'dct%d'}[dtype.name] # name = {'float64': 'ddct%d', 'float32': 'dct%d'}[dtype.name]
except KeyError: # except KeyError:
raise ValueError("dtype %s not supported" % dtype) # raise ValueError("dtype %s not supported" % dtype)
try: # try:
f = getattr(_fftpack, name % type) # f = getattr(_fftpack, name % type)
except AttributeError as e: # except AttributeError as e:
raise ValueError(str(e) + ". Type %d not understood" % type) # raise ValueError(str(e) + ". Type %d not understood" % type)
return f, nm # return f, nm
def idct(x, type=2, n=None, axis=-1, norm='ortho'): # @ReservedAssignment def idct(x, type=2, n=None, axis=-1, norm='ortho'): # @ReservedAssignment
@ -437,8 +437,8 @@ def test_dctn():
print(x) print(x)
print(' ') print(' ')
yn = dctn(a) #, shape=(10,), axes=(1,)) yn = dctn(a) # , shape=(10,), axes=(1,))
xn = idctn(yn) #, axes=(1,)) xn = idctn(yn) # , axes=(1,))
print('yn = dctn(a)') print('yn = dctn(a)')
print(yn) print(yn)
print('xn = idctn(yn)') print('xn = idctn(yn)')
@ -446,6 +446,7 @@ def test_dctn():
print(' ') print(' ')
print xn-a print xn-a
def test_dct2(): def test_dct2():
import scipy.ndimage as sn import scipy.ndimage as sn
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
@ -481,8 +482,14 @@ def test_docstrings():
doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE) 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__': if __name__ == '__main__':
test_dct2() print(test_commands())
# test_dct2()
# test_docstrings() # test_docstrings()
# test_dctn() # test_dctn()
# test_shiftdim() # test_shiftdim()

@ -1,6 +1,7 @@
# @UnresolvedImport import matplotlib.pyplot as plt
from pylab import subplot, plot, title, savefig, figure, arange, sin, random from pylab import subplot, plot, title, figure
from sg_filter import calc_coeff, smooth from numpy import random, arange, sin
from sg_filter import SavitzkyGolay, smoothn # calc_coeff, smooth
figure(figsize=(7, 12)) figure(figsize=(7, 12))
@ -8,11 +9,11 @@ figure(figsize=(7, 12))
# generate chirp signal # generate chirp signal
tvec = arange(0, 6.28, .02) tvec = arange(0, 6.28, .02)
signal = sin(tvec * (2.0 + tvec)) true_signal = sin(tvec * (2.0 + tvec))
# add noise to signal # add noise to signal
noise = random.normal(size=signal.shape) noise = random.normal(size=true_signal.shape)
signal += (2000. + .15 * noise) signal = true_signal + .15 * noise
# plot signal # plot signal
subplot(311) subplot(311)
@ -21,19 +22,21 @@ title('signal')
# smooth and plot signal # smooth and plot signal
subplot(312) subplot(312)
coeff = calc_coeff(8, 4) savgol = SavitzkyGolay(n=8, degree=4)
s_signal = smooth(signal, coeff) s_signal = savgol.smooth(signal)
s2 = smoothn(signal, robust=True)
plot(s_signal) plot(s_signal)
plot(s2)
plot(true_signal, 'r--')
title('smoothed signal') title('smoothed signal')
# smooth derivative of signal and plot it # smooth derivative of signal and plot it
subplot(313) subplot(313)
coeff = calc_coeff(8, 1, 1) savgol1 = SavitzkyGolay(n=8, degree=1, diff_order=1)
d_signal = smooth(signal, coeff)
d_signal = savgol1.smooth(signal)
plot(d_signal) plot(d_signal)
title('smoothed derivative of signal') title('smoothed derivative of signal')
# show plot plt.show('hold') # show plot
savefig("savitzky.png")

@ -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.')

@ -2,7 +2,6 @@
Misc Misc
''' '''
from __future__ import division from __future__ import division
import sys import sys
import fractions import fractions
import numpy as np import numpy as np

Binary file not shown.

Binary file not shown.

@ -5,7 +5,7 @@ import warnings
verbose = False verbose = False
if False: if False:
try: try:
from scitools import easyviz as plotbackend from scitools import easyviz as plotbackend # @UnresolvedImport
if verbose: if verbose:
print('wafo: plotbackend is set to scitools.easyviz') print('wafo: plotbackend is set to scitools.easyviz')
except: except:

Binary file not shown.

@ -14,7 +14,7 @@ from scipy.ndimage.morphology import distance_transform_edt
import warnings import warnings
from wafo.plotbackend import plotbackend as plt from wafo.plotbackend import plotbackend as plt
__all__ = ['SavitzkyGolay', 'Kalman', 'HodrickPrescott'] __all__ = ['SavitzkyGolay', 'Kalman', 'HodrickPrescott', 'smoothn']
class SavitzkyGolay(object): class SavitzkyGolay(object):

@ -7,7 +7,7 @@ TrLinear
''' '''
# !/usr/bin/env python # !/usr/bin/env python
from __future__ import division 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, from numpy import (sqrt, atleast_1d, abs, imag, sign, where, cos, arccos, ceil,
expm1, log1p, pi) expm1, log1p, pi)
import numpy as np import numpy as np
@ -106,10 +106,10 @@ class TrHermite(TrCommon2):
Example: Example:
-------- --------
""" + _example.replace('<generic>', 'TrHermite') + """ """ + _example.replace('<generic>', 'TrHermite') + """
>>> g.dist2gauss() >>> np.allclose(g.dist2gauss(), 0.88230868748851499)
0.88230868748851499 True
>>> g2.dist2gauss() >>> np.allclose(g2.dist2gauss(), 1.1411663205144991)
1.1411663205144991 True
See also See also
-------- --------
@ -336,10 +336,10 @@ class TrLinear(TrCommon2):
Example: Example:
-------- --------
""" + _example.replace('<generic>', 'TrLinear') + """ """ + _example.replace('<generic>', 'TrLinear') + """
>>> g.dist2gauss() >>> np.allclose(g.dist2gauss(), 0)
0.0 True
>>> g2.dist2gauss() >>> np.allclose(g2.dist2gauss(), 0)
3.8594770921678001e-31 True
See also See also
-------- --------
@ -404,10 +404,10 @@ class TrOchi(TrCommon2):
Example Example
------- -------
""" + _example.replace('<generic>', 'TrOchi') + """ """ + _example.replace('<generic>', 'TrOchi') + """
>>> g.dist2gauss() >>> np.allclose(g.dist2gauss(), 1.410698801056657)
1.410698801056657 True
>>> g2.dist2gauss() >>> np.allclose(g2.dist2gauss(), 1.988807188766706)
1.988807188766706 True
See also See also
-------- --------

@ -21,7 +21,7 @@ def empty_copy(obj):
def _set_seed(iseed): def _set_seed(iseed):
if iseed != None: if iseed is not None:
try: try:
np.random.set_state(iseed) np.random.set_state(iseed)
except: except:
@ -29,16 +29,13 @@ def _set_seed(iseed):
def now(): 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()) return strftime("%a, %d %b %Y %H:%M:%S", gmtime())
class PlotData(object): class PlotData(object):
''' """Container class for data objects in WAFO.
Container class for data objects in WAFO
Member variables Member variables
---------------- ----------------
@ -72,7 +69,8 @@ class PlotData(object):
-------- --------
specdata, specdata,
covdata covdata
'''
"""
def __init__(self, data=None, args=None, *args2, **kwds): def __init__(self, data=None, args=None, *args2, **kwds):
self.data = data self.data = data
@ -95,7 +93,7 @@ class PlotData(object):
axis = plotbackend.gca() axis = plotbackend.gca()
tmp = None tmp = None
plotflag = kwds.get('plotflag', 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') plotbackend.hold('on')
tmp = [] tmp = []
child_args = kwds.pop( child_args = kwds.pop(
@ -105,7 +103,7 @@ class PlotData(object):
child_kwds['axis'] = axis child_kwds['axis'] = axis
for child in self.children: for child in self.children:
tmp1 = child.plot(*child_args, **child_kwds) tmp1 = child.plot(*child_args, **child_kwds)
if tmp1 != None: if tmp1 is not None:
tmp.append(tmp1) tmp.append(tmp1)
if len(tmp) == 0: if len(tmp) == 0:
tmp = None tmp = None
@ -179,9 +177,8 @@ class PlotData(object):
return newcopy return newcopy
def setplotter(self, plotmethod=None): def setplotter(self, plotmethod=None):
''' """Set plotter based on the data type data_1d, data_2d, data_3d or
Set plotter based on the data type data_1d, data_2d, data_3d or data_nd data_nd."""
'''
if isinstance(self.args, (list, tuple)): # Multidimensional data if isinstance(self.args, (list, tuple)): # Multidimensional data
ndim = len(self.args) ndim = len(self.args)
if ndim < 2: if ndim < 2:
@ -212,7 +209,8 @@ class AxisLabels:
return self.__str__() return self.__str__()
def __str__(self): 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): def copy(self):
newcopy = empty_copy(self) newcopy = empty_copy(self)
@ -226,7 +224,7 @@ class AxisLabels:
h1 = axis.set_title(self.title) h1 = axis.set_title(self.title)
h2 = axis.set_xlabel(self.xlab) h2 = axis.set_xlabel(self.xlab)
h3 = axis.set_ylabel(self.ylab) h3 = axis.set_ylabel(self.ylab)
#h4 = plotbackend.zlabel(self.zlab) # h4 = plotbackend.zlabel(self.zlab)
return h1, h2, h3 return h1, h2, h3
except: except:
pass pass
@ -306,8 +304,9 @@ def plot1d(axis, args, data, dataCI, plotflag, *varargin, **kwds):
elif plottype == 3: elif plottype == 3:
H = axis.stem(args, data, *varargin, **kwds) H = axis.stem(args, data, *varargin, **kwds)
elif plottype == 4: elif plottype == 4:
H = axis.errorbar( H = axis.errorbar(args, data,
args, data, yerr=[dataCI[:, 0] - data, dataCI[:, 1] - data], *varargin, **kwds) yerr=[dataCI[:, 0] - data, dataCI[:, 1] - data],
*varargin, **kwds)
elif plottype == 5: elif plottype == 5:
H = axis.bar(args, data, *varargin, **kwds) H = axis.bar(args, data, *varargin, **kwds)
elif plottype == 6: elif plottype == 6:
@ -354,8 +353,7 @@ def plot1d(axis, args, data, dataCI, plotflag, *varargin, **kwds):
def plotscale(plotflag): def plotscale(plotflag):
''' """Return plotscale from plotflag.
Return plotscale from plotflag
CALL scale = plotscale(plotflag) CALL scale = plotscale(plotflag)
@ -400,7 +398,8 @@ def plotscale(plotflag):
See also See also
-------- --------
transformdata transformdata
'''
"""
scaleId = plotflag // 100 scaleId = plotflag // 100
if scaleId > 7: if scaleId > 7:
logXscaleId = np.mod(scaleId, 10) > 0 logXscaleId = np.mod(scaleId, 10) > 0
@ -429,8 +428,8 @@ def transformdata(x, f, plotflag):
data = -np.log1p(-cumtrapz(f, x)) data = -np.log1p(-cumtrapz(f, x))
else: else:
if any(f < 0): if any(f < 0):
raise ValueError( raise ValueError('Invalid plotflag: Data or dataCI is '
'Invalid plotflag: Data or dataCI is negative, but must be positive') 'negative, but must be positive')
data = 10 * np.log10(f) data = 10 * np.log10(f)
return data return data

@ -223,7 +223,7 @@ class WarnDlg(Thread):
self.start() # Run the thread self.start() # Run the thread
def run(self): 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, MessageBox(0, self.message, self.title,
win32con.MB_ICONWARNING | win32con.MB_SYSTEMMODAL) win32con.MB_ICONWARNING | win32con.MB_SYSTEMMODAL)
@ -240,7 +240,7 @@ class ErrorDlg(Thread):
self.start() # Run in thread self.start() # Run in thread
def run(self): 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, MessageBox(0, self.message, self.title,
win32con.MB_ICONERROR | win32con.MB_SYSTEMMODAL) win32con.MB_ICONERROR | win32con.MB_SYSTEMMODAL)

Loading…
Cancel
Save