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
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()

@ -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

@ -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
'''
from __future__ import division
import sys
import fractions
import numpy as np

Binary file not shown.

Binary file not shown.

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

Binary file not shown.

@ -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):

@ -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('<generic>', '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('<generic>', '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('<generic>', '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
--------

@ -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,8 +353,7 @@ def plot1d(axis, args, data, dataCI, plotflag, *varargin, **kwds):
def plotscale(plotflag):
'''
Return plotscale from plotflag
"""Return plotscale from plotflag.
CALL scale = plotscale(plotflag)
@ -400,7 +398,8 @@ def plotscale(plotflag):
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

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

Loading…
Cancel
Save