Remove modules

basic
Dan Howe 5 years ago
parent 02511aebc2
commit d336196e24

@ -1,69 +0,0 @@
<map version="0.8.1">
<!-- To view this file, download free mind mapping software FreeMind from http://freemind.sourceforge.net -->
<node CREATED="1268907205249" ID="Freemind_Link_1834025809" MODIFIED="1268920224244" STYLE="fork" TEXT="WAFO Objects">
<font NAME="SansSerif" SIZE="11"/>
<node CREATED="1268919537155" ID="Freemind_Link_823244205" MODIFIED="1268920190865" POSITION="right" STYLE="bubble" TEXT="SpecData1D" VSHIFT="36">
<node CREATED="1268908695254" ID="Freemind_Link_834391422" MODIFIED="1268908707582" TEXT="bandwidth"/>
<node CREATED="1268908733082" ID="Freemind_Link_1433599166" MODIFIED="1268908736348" TEXT="characteristic"/>
<node CREATED="1268908690441" ID="Freemind_Link_1284342306" MODIFIED="1268908694941" TEXT="normalize"/>
<node CREATED="1268908669144" ID="Freemind_Link_1815459961" MODIFIED="1268908677316" TEXT="nyquist_freq"/>
<node CREATED="1268908664160" ID="Freemind_Link_703739784" MODIFIED="1268919800253" TEXT="moment" VSHIFT="4"/>
<node CREATED="1268908678394" ID="Freemind_Link_1387269779" MODIFIED="1268919203464" TEXT="sampling_period" VSHIFT="3"/>
<node CREATED="1268908643159" ID="Freemind_Link_895051601" MODIFIED="1268908655410" TEXT="stats_nl"/>
<node CREATED="1268907362986" ID="Freemind_Link_1959199999" MODIFIED="1268920763548" TEXT="sim">
<arrowlink DESTINATION="Freemind_Link_1110096845" ENDARROW="Default" ENDINCLINATION="-26;-470;" ID="Freemind_Arrow_Link_658989110" STARTARROW="None" STARTINCLINATION="134;20;"/>
</node>
<node CREATED="1268908639894" ID="Freemind_Link_881848843" MODIFIED="1268920768236" TEXT="sim_nl" VSHIFT="-116">
<arrowlink DESTINATION="Freemind_Link_1110096845" ENDARROW="Default" ENDINCLINATION="-12;-203;" ID="Freemind_Arrow_Link_194892354" STARTARROW="None" STARTINCLINATION="286;65;"/>
</node>
<node CREATED="1268908656097" ID="Freemind_Link_932055041" MODIFIED="1268920049331" TEXT="testgaussian" VSHIFT="-11"/>
<node CREATED="1268908524408" ID="Freemind_Link_451836141" MODIFIED="1268920637967" TEXT="tocovdata" VSHIFT="122">
<arrowlink DESTINATION="Freemind_Link_1298097150" ENDARROW="Default" ENDINCLINATION="22;-61;" ID="Freemind_Arrow_Link_459039584" STARTARROW="None" STARTINCLINATION="155;-17;"/>
</node>
<node CREATED="1268907881846" ID="Freemind_Link_961675105" MODIFIED="1268908523861" TEXT="tocov_matrix"/>
<node CREATED="1268908531877" ID="Freemind_Link_1361566099" MODIFIED="1268920224244" TEXT="to_linspec"/>
<node CREATED="1268908548674" ID="Freemind_Link_28901814" MODIFIED="1268920222025" TEXT="to_specnorm"/>
<node CREATED="1268908684613" ID="Freemind_Link_180569473" MODIFIED="1268917666022" TEXT="resample"/>
</node>
<node CREATED="1268918310233" HGAP="471" ID="Freemind_Link_1110096845" MODIFIED="1268920768236" POSITION="right" STYLE="bubble" TEXT="TimeSeries" VSHIFT="-65">
<node CREATED="1268918758255" ID="Freemind_Link_1306080198" MODIFIED="1268920381237" STYLE="fork" TEXT="tospecdata"/>
<node CREATED="1268918767833" ID="Freemind_Link_1037382917" MODIFIED="1268920384363" STYLE="fork" TEXT="tocovdata"/>
<node CREATED="1268918809021" ID="Freemind_Link_767625747" MODIFIED="1268918816990" STYLE="fork" TEXT="wave_periods"/>
<node CREATED="1268918817396" ID="Freemind_Link_294440483" MODIFIED="1268918823943" STYLE="fork" TEXT="reconstruct"/>
<node CREATED="1268918824365" ID="Freemind_Link_1893872699" MODIFIED="1268920714281" STYLE="fork" TEXT="plot_wave" VSHIFT="29"/>
<node CREATED="1268918835318" ID="Freemind_Link_1625232632" MODIFIED="1268918848897" STYLE="fork" TEXT="plot_sp_wave"/>
<node CREATED="1268918669644" ID="Freemind_Link_525365373" MODIFIED="1268918757817" STYLE="fork" TEXT="sampling_period"/>
<node CREATED="1268918800427" ID="Freemind_Link_540262488" MODIFIED="1268920657436" STYLE="fork" TEXT="through_crest" VSHIFT="11">
<arrowlink DESTINATION="Freemind_Link_1866699423" ENDARROW="Default" ENDINCLINATION="120;-87;" ID="Freemind_Arrow_Link_724369012" STARTARROW="None" STARTINCLINATION="298;0;"/>
</node>
<node CREATED="1268918781115" ID="Freemind_Link_191369931" MODIFIED="1268920652670" STYLE="fork" TEXT="turning_points">
<arrowlink DESTINATION="Freemind_Link_1866699423" ENDARROW="Default" ENDINCLINATION="354;-263;" ID="Freemind_Arrow_Link_301423490" STARTARROW="None" STARTINCLINATION="-57;21;"/>
</node>
</node>
<node CREATED="1268917687085" ID="Freemind_Link_1298097150" MODIFIED="1268920673171" POSITION="right" STYLE="bubble" TEXT="CovData1D" VSHIFT="-212">
<node CREATED="1268917901666" ID="Freemind_Link_1791940512" MODIFIED="1268919887910" STYLE="fork" TEXT="tospecdata">
<arrowlink DESTINATION="Freemind_Link_823244205" ENDARROW="Default" ENDINCLINATION="14;87;" ID="Freemind_Arrow_Link_728651707" STARTARROW="None" STARTINCLINATION="-21;-38;"/>
</node>
<node CREATED="1268918164841" ID="Freemind_Link_1718380955" MODIFIED="1268918173622" STYLE="fork" TEXT="sampling_period"/>
<node CREATED="1268918174044" ID="Freemind_Link_1888500587" MODIFIED="1268920740704" STYLE="fork" TEXT="sim">
<arrowlink DESTINATION="Freemind_Link_1110096845" ENDARROW="Default" ENDINCLINATION="-2;21;" ID="Freemind_Arrow_Link_174025984" STARTARROW="None" STARTINCLINATION="271;12;"/>
</node>
<node CREATED="1268918178013" ID="Freemind_Link_757742844" MODIFIED="1268920750954" STYLE="fork" TEXT="simcond">
<arrowlink DESTINATION="Freemind_Link_1110096845" ENDARROW="Default" ENDINCLINATION="-46;173;" ID="Freemind_Arrow_Link_1889053469" STARTARROW="None" STARTINCLINATION="171;0;"/>
</node>
</node>
<node CREATED="1268918904132" ID="Freemind_Link_1866699423" MODIFIED="1268920673171" POSITION="right" STYLE="bubble" TEXT="TurningPoints">
<node CREATED="1268918978226" ID="Freemind_Link_1033172969" MODIFIED="1268918989023" STYLE="fork" TEXT="cycle_pairs"/>
</node>
<node CREATED="1268918988977" ID="Freemind_Link_280025207" MODIFIED="1268920787861" POSITION="right" STYLE="bubble" TEXT="CyclePairs" VSHIFT="91">
<node CREATED="1268919011477" ID="Freemind_Link_867889153" MODIFIED="1268919019180" STYLE="fork" TEXT="amplitudes"/>
<node CREATED="1268919019586" ID="Freemind_Link_40128767" MODIFIED="1268919024414" STYLE="fork" TEXT="damage"/>
<node CREATED="1268919025024" ID="Freemind_Link_1194799087" MODIFIED="1268919033727" STYLE="fork" TEXT="level_crossings"/>
</node>
<node CREATED="1268919295668" ID="Freemind_Link_106637151" MODIFIED="1268919305606" POSITION="right" STYLE="bubble" TEXT="LevelCrossings">
<node CREATED="1268919349809" ID="Freemind_Link_1941466065" MODIFIED="1268920453960" STYLE="fork" TEXT="sim"/>
<node CREATED="1268919305574" ID="Freemind_Link_1378561112" MODIFIED="1268919349122" STYLE="fork" TEXT="trdata"/>
</node>
<node CREATED="1268920796033" ID="_" MODIFIED="1268920800424" POSITION="right" STYLE="bubble" TEXT="TrData"/>
</node>
</map>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 240 KiB

@ -1,97 +0,0 @@
"""
Module extending the bitoperator capabilites of numpy
"""
from numpy import (bitwise_and, bitwise_or,
bitwise_not, binary_repr, # @UnusedImport
bitwise_xor, where, arange) # @UnusedImport
__all__ = ['bitwise_and', 'bitwise_or', 'bitwise_not', 'binary_repr',
'bitwise_xor', 'getbit', 'setbit', 'getbits', 'setbits']
def getbit(i, bit):
"""
Get bit at specified position
Parameters
----------
i : array-like of uints, longs
value to
bit : array-like of ints or longs
bit position between 0 and the number of bits in the uint class.
Examples
--------
>>> import numpy as np
>>> binary_repr(13)
'1101'
>>> getbit(13,np.arange(3,-1,-1))
array([1, 1, 0, 1])
>>> getbit(5, np.r_[0:4])
array([1, 0, 1, 0])
"""
return bitwise_and(i, 1 << bit) >> bit
def getbits(i, numbits=8):
"""
Returns bits of i in a list
"""
return getbit(i, arange(0, numbits))
def setbit(i, bit, value=1):
"""
Set bit at specified position
Parameters
----------
i : array-like of uints, longs
value to
bit : array-like of ints or longs
bit position between 0 and the number of bits in the uint class.
value : array-like of 0 or 1
value to set the bit to.
Examples
--------
Set bit fifth bit in the five bit binary binary representation of 9 (01001)
yields 25 (11001)
>>> setbit(9,4)
array(25)
"""
val1 = 1 << bit
val0 = bitwise_not(val1)
return where((value == 0) & (i == i) & (bit == bit), bitwise_and(i, val0),
bitwise_or(i, val1))
def setbits(bitlist):
"""
Set bits of val to values in bitlist
Example
-------
>>> setbits([1,1])
3
>>> setbits([1,0])
1
"""
val = 0
for i, j in enumerate(bitlist):
val |= j << i
return val
if __name__ == '__main__':
from wafo.testing import test_docstrings
test_docstrings(__file__)
# t = set(np.arange(8),1,1)
# t=get(0x84,np.arange(0,8))
# t=getbyte(0x84)
# t=get(0x84,[0, 1, 2, 3, 4, 5, 6, 7])
# t=get(0x20, 6)
# bit = [0 for i in range(8)]
# bit[7]=1
# t = setbits(bit)
# print(hex(t))

@ -1,3 +0,0 @@
# TODO Fix doctests in fig.py
collect_ignore = ["fig.py", "MSO.py", "MSPPT.py", "powerpoint.py",
"win32_utils.py"]

@ -1,310 +0,0 @@
"""
WAFO defintions and numenclature
crossings :
cycle_pairs :
turning_points :
wave_amplitudes :
wave_periods :
waves :
Examples
--------
In order to view the documentation do the following in an ipython window:
import wafo.definitions as wd
wd.crossings()
or
wd.crossings?
"""
def wave_amplitudes():
r"""
Wave amplitudes and heights definitions and nomenclature
Definition of wave amplitudes and wave heights
---------------------------------------------
<----- Direction of wave propagation
|..............c_..........|
| /| \ |
Hd | _/ | \ | Hu
M | / | \ |
/ \ | M / Ac | \_ | c_
F \ | / \m/ | \ | / \
------d----|---u------------------d---|---u----d------ level v
\ | /| \ | / \L
\_ | / | At \_|_/
\|/..| t
t
Parameters
----------
Ac : crest amplitude
At : trough amplitude
Hd : wave height as defined for down crossing waves
Hu : wave height as defined for up crossing waves
See also
--------
waves, crossings, turning_points
"""
print(wave_amplitudes.__doc__)
def crossings():
r"""
Level v crossing definitions and nomenclature
Definition of level v crossings
-------------------------------
M
. . M M
. . . . . .
F d . . L
-----------------------u-------d-------o----------------- level v
. . . . u
. m
m
Let the letters 'm', 'M', 'F', 'L','d' and 'u' in the
figure above denote local minimum, maximum, first value, last
value, down- and up-crossing, respectively. The remaining
sampled values are indicated with a '.'. Values that are identical
with v, but do not cross the level is indicated with the letter 'o'.
We have a level up-crossing at index, k, if
x(k) < v and v < x(k+1)
or if
x(k) == v and v < x(k+1) and x(r) < v for some di < r <= k-1
where di is the index to the previous downcrossing.
Similarly there is a level down-crossing at index, k, if
x(k) > v and v > x(k+1)
or if
x(k) == v and v > x(k+1) and x(r) > v for some ui < r <= k-1
where ui is the index to the previous upcrossing.
The first (F) value is a up crossing if x(1) = v and x(2) > v.
Similarly, it is a down crossing if x(1) = v and x(2) < v.
See also
--------
wave_periods, waves, turning_points, findcross, findtp
"""
print(crossings.__doc__)
def cycle_pairs():
r"""
Cycle pairs definitions and numenclature
Definition of Max2min and min2Max cycle pair
--------------------------------------------
A min2Max cycle pair (mM) is defined as the pair of a minimum
and the following Maximum. Similarly a Max2min cycle pair (Mm)
is defined as the pair of a Maximum and the following minimum.
(all turning points possibly rainflowfiltered before pairing into cycles.)
See also
--------
turning_points
"""
print(cycle_pairs.__doc__)
def wave_periods():
r"""
Wave periods (lengths) definitions and nomenclature
Definition of wave periods (lengths)
------------------------------------
<----- Direction of wave propagation
<-------Tu--------->
: :
<---Tc-----> :
: : : <------Tcc---->
M : c : : : :
/ \ : M / \_ : : c_ c
F \ :/ \m/ \: :/ \ / \
------d--------u----------d-------u----d--------u---d-------- level v
\ / \ / :\_ _/: :\_ L
\_ / \_t_/ : \t_/ : : \m/
\t/ : : : :
: : <---Tt---> :
<--------Ttt-------> : :
<-----Td----->
Tu = Up crossing period
Td = Down crossing period
Tc = Crest period, i.e., period between up crossing and
the next down crossing
Tt = Trough period, i.e., period between down crossing and
the next up crossing
Ttt = Trough2trough period
Tcc = Crest2crest period
<----- Direction of wave propagation
<--Tcf-> Tuc
: : <-Tcb-> <->
M : c : : : :
/ \ : M / \_ c_ : : c
F \ :/ \m/ \ / \___: :/ \
------d---------u----------d---------u-------d--------u---d------ level v
:\_ / \ __/: \_ _/ \_ L
: \_ / \_t_/ : \t_/ \m/
: \t/ : :
: : : :
<-Ttf-> <-Ttb->
Tcf = Crest front period, i.e., period between up crossing and crest
Tcb = Crest back period, i.e., period between crest and down crossing
Ttf = Trough front period, i.e., period between down crossing and trough
Ttb = Trough back period, i.e., period between trough and up crossing
Also note that Tcf and Ttf can also be abbreviated by their crossing
marker, e.g. Tuc (u2c) and Tdt (d2t), respectively. Similar applies
to all the other wave periods and wave lengths.
(The nomenclature for wave length is similar, just substitute T and
period with L and length, respectively)
<----- Direction of wave propagation
<--TMm-->
<-TmM-> : :
M : : M :
/ \ : M /:\_ : M_ M
F \ : / \m/ : \ : /: \ / \
\ : / : \ : / : \ / \
\ : / : \ : / : \_ _/ \_ L
\_ : / : \_m_/ : \m_/ \m/
\m/ : : : :
<-----TMM-----> <----Tmm----->
TmM = Period between minimum and the following Maximum
TMm = Period between Maximum and the following minimum
TMM = Period between Maximum and the following Maximum
Tmm = Period between minimum and the following minimum
See also
--------
waves,
wave_amplitudes,
crossings,
turning_points
"""
print(wave_periods.__doc__)
def turning_points():
r"""
Turning points definitions and numenclature
Definition of turningpoints
---------------------------
<----- Direction of wave propagation
M M
/ \ .... M /:\_ M_ M
F \ | / \m/ : \ /: \ / \
\ h | / : \ / : \ / \
\ | / : \ / : \_ _/ \_ L
\_ | / : \_m_/ : \m_/ \m/
\m/ : : : :
<------Mw-----> <-----mw----->
Local minimum or maximum are indicated with the
letters 'm' or 'M'. Turning points in this connection are all
local max (M) and min (m) and the last (L) value and the
first (F) value if the first local extremum is a max.
(This choice is made in order to get the exact up-crossing intensity
from rfc by mm2lc(tp2mm(rfc)) )
See also
--------
waves,
crossings,
cycle_pairs
findtp
"""
print(turning_points.__doc__)
def waves():
r"""
Wave definitions and nomenclature
Definition of trough and crest
------------------------------
A trough (t) is defined as the global minimum between a
level v down-crossing (d) and the next up-crossing (u)
and a crest (c) is defined as the global maximum between a
level v up-crossing and the following down-crossing.
Definition of down- and up -crossing waves
------------------------------------------
A level v-down-crossing wave (dw) is a wave from a
down-crossing to the following down-crossing.
Similarly, a level v-up-crossing wave (uw) is a wave from an up-crossing
to the next up-crossing.
Definition of trough and crest waves
------------------------------------
A trough-to-trough wave (tw) is a wave from a trough (t) to the
following trough. The crest-to-crest wave (cw) is defined similarly.
Definition of min2min and Max2Max wave
--------------------------------------
A min2min wave (mw) is defined starting from a minimum (m) and
ending in the following minimum.
Similarly a Max2Max wave (Mw) is thus a wave from a maximum (M)
to the next maximum (all waves optionally rainflow filtered).
<----- Direction of wave propagation
<------Mw-----> <----mw---->
M : : c :
/ \ M : / \_ : c_ c
F \ / \m/ \ : /: \ /:\
------d--------u----------d-------u----d--------u---d------ level v
\ /: \ : /: : :\_ _/ : :\_ L
\_ / : \_t_/ : : : \t_/ : : \m/
\t/ <-------uw---------> : <-----dw----->
: : : :
<--------tw--------> <------cw----->
(F=first value and L=last value).
See also
--------
turning_points,
crossings,
wave_periods
findtc,
findcross
"""
print(waves.__doc__)
if __name__ == '__main__':
import doctest
doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)

@ -1,146 +0,0 @@
"""
Created on 20. jan. 2011
@author: pab
"""
import numpy as np
from numpy import exp, meshgrid
__all__ = ['peaks', 'humps', 'magic']
def _magic_odd_order(n):
ix = np.arange(n) + 1
J, I = np.meshgrid(ix, ix)
A = np.mod(I + J - (n + 3) / 2, n)
B = np.mod(I + 2 * J - 2, n)
M = n * A + B + 1
return M
def _magic_doubly_even_order(n):
M = np.arange(1, n * n + 1).reshape(n, n)
ix = np.mod(np.arange(n) + 1, 4) // 2
J, I = np.meshgrid(ix, ix)
iz = np.flatnonzero(I == J)
M.put(iz, n * n + 1 - M.flat[iz])
return M
def _magic_even_order(n):
p = n // 2
M0 = magic(p)
M = np.hstack((np.vstack((M0, M0 + 3 * p * p)),
np.vstack((M0 + 2 * p * p, M0 + p * p))))
if n > 2:
k = (n - 2) // 4
jvec = np.hstack((np.arange(k), np.arange(n - k + 1, n)))
for i in range(p):
for j in jvec:
temp = M[i][j]
M[i][j] = M[i + p][j]
M[i + p][j] = temp
i = k
j = 0
temp = M[i][j]
M[i][j] = M[i + p][j]
M[i + p][j] = temp
j = i
temp = M[i + p][j]
M[i + p][j] = M[i][j]
M[i][j] = temp
return M
def magic(n):
"""
Return magic square for n of any orders > 2.
A magic square has the property that the sum of every row and column,
as well as both diagonals, is the same number.
Examples
--------
>>> np.allclose(magic(3),
... [[8, 1, 6],
... [3, 5, 7],
... [4, 9, 2]])
True
>>> np.allclose(magic(4),
... [[16, 2, 3, 13],
... [ 5, 11, 10, 8],
... [ 9, 7, 6, 12],
... [ 4, 14, 15, 1]])
True
>>> np.allclose(magic(6),
... [[35, 1, 6, 26, 19, 24],
... [ 3, 32, 7, 21, 23, 25],
... [31, 9, 2, 22, 27, 20],
... [ 8, 28, 33, 17, 10, 15],
... [30, 5, 34, 12, 14, 16],
... [ 4, 36, 29, 13, 18, 11]])
True
"""
if (n < 3):
raise ValueError('n must be greater than 2.')
if np.mod(n, 2) == 1:
return _magic_odd_order(n)
elif np.mod(n, 4) == 0:
return _magic_doubly_even_order(n)
return _magic_even_order(n)
def peaks(x=None, y=None, n=51):
"""
Return the "well" known MatLab (R) peaks function
evaluated in the [-3,3] x,y range
Example
-------
>>> import matplotlib.pyplot as plt
>>> x,y,z = peaks()
h = plt.contourf(x,y,z)
"""
if x is None:
x = np.linspace(-3, 3, n)
if y is None:
y = np.linspace(-3, 3, n)
[x1, y1] = meshgrid(x, y)
z = (3 * (1 - x1) ** 2 * exp(-(x1 ** 2) - (y1 + 1) ** 2) -
10 * (x1 / 5 - x1 ** 3 - y1 ** 5) * exp(-x1 ** 2 - y1 ** 2) -
1. / 3 * exp(-(x1 + 1) ** 2 - y1 ** 2))
return x1, y1, z
def humps(x=None):
"""
Computes a function that has three roots, and some humps.
Example
-------
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(0,1)
>>> y = humps(x)
h = plt.plot(x,y)
"""
if x is None:
y = np.linspace(0, 1)
else:
y = np.asarray(x)
return 1.0 / ((y - 0.3) ** 2 + 0.01) + 1.0 / ((y - 0.9) ** 2 + 0.04) + \
2 * y - 5.2
if __name__ == '__main__':
from wafo.testing import test_docstrings
test_docstrings(__file__)

@ -1,65 +0,0 @@
# -*- coding: utf-8 -*-
"""
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.exe', '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.')

@ -1,908 +0,0 @@
# /usr/bin/env python
'''
Module FIG
------------
Module for manipulating windows/figures created using
pylab or enthought.mayavi.mlab on the windows platform.
Figure manipulation involves
maximization, minimization, hiding, closing, stacking or tiling.
It is assumed that the figures are uniquely numbered in the following way:
Figure 1
Figure 2
....
or
TVTK scene 1
TVTK scene 2
TVTK scene 3
...
Example
-------
>>> import pylab as p
>>> import wafo.fig as fig
>>> for ix in range(6):
... f = p.figure(ix)
>>> fig.stack('all')
>>> fig.stack(1,2)
>>> fig.hide(1)
>>> fig.restore(1)
>>> fig.tile()
>>> fig.pile()
>>> fig.maximize(4)
>>> fig.close('all')
'''
from __future__ import absolute_import, division, print_function
# import win32api
import win32gui
import win32con
import wx
import numpy
from win32gui import (EnumWindows, MoveWindow, GetWindowRect, FindWindow,
ShowWindow, BringWindowToTop)
__all__ = ['close', 'cycle', 'hide', 'keep', 'maximize', 'minimize', 'pile',
'restore', 'stack', 'tile', 'find_all_figure_numbers', 'set_size']
# Figure format strings to recognize in window title
FIGURE_TITLE_FORMATS = ('Figure', 'TVTK Scene', 'Chaco Plot Window: Figure')
_SCREENSIZE = None
class CycleDialog(wx.Dialog):
def _get_buttons(self):
hbox = wx.BoxSizer(wx.HORIZONTAL)
buttons = ['Forward', 'Back', 'Cancel']
callbacks = [self.on_forward, self.on_backward, self.on_cancel]
for button, callback in zip(buttons, callbacks):
button = wx.Button(self, -1, button, size=(70, 30))
self.Bind(wx.EVT_BUTTON, callback, button)
hbox.Add(button, 1, wx.ALIGN_CENTER)
return hbox
def _get_message(self):
label = ('Press back or forward to display previous or next figure(s),'
' respectively. Press cancel to quit.')
message = wx.StaticText(self, label=label, size=(240, 25))
return message
def __init__(self, parent, interval=None, title='Cycle dialog'):
super(CycleDialog, self).__init__(parent, title=title, size=(260, 130))
if isinstance(interval, (float, int)):
self.interval_milli_sec = interval * 1000
else:
self.interval_milli_sec = 30
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.on_forward, self.timer)
vbox = wx.BoxSizer(wx.VERTICAL)
vbox.Add(self._get_message(), 0, wx.ALIGN_CENTER | wx.TOP, 20)
vbox.Add(self._get_buttons(), 1, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 10)
self.SetSizer(vbox)
def ShowModal(self, *args, **kwargs):
self.timer.Start(self.interval_milli_sec, oneShot=True)
return super(CycleDialog, self).ShowModal(*args, **kwargs)
def on_forward(self, evt):
self.EndModal(wx.ID_FORWARD)
def on_backward(self, evt):
self.EndModal(wx.ID_BACKWARD)
def on_cancel(self, evt):
self.EndModal(wx.ID_CANCEL)
def _get_cycle_dialog(parent=None, interval=None):
app = wx.GetApp()
if not app:
app = wx.App(redirect=False)
frame = wx.Frame(None)
app.SetTopWindow(frame)
dlg = CycleDialog(parent, interval)
return dlg
def get_window_position_and_size(window_handle):
pos = GetWindowRect(window_handle)
return pos[0], pos[1], pos[2] - pos[0], pos[3] - pos[1]
def get_screen_position_and_size(window_handles):
"""Return screen position; X, Y and size; width, height.
Parameters
----------
window_handles: list of handles to open window figures
(Note: only needed the first time)
Returns
--------
X : coordinate of the left side of the screen.
Y : coordinate of the top of the screen.
width : screen horizontal size
height : screen vertical size
"""
# pylint: disable=global-statement
global _SCREENSIZE
if _SCREENSIZE is None:
window_handle = window_handles[0]
pos = get_window_position_and_size(window_handle)
_show_windows((window_handle,), win32con.SW_SHOWMAXIMIZED)
_SCREENSIZE = get_window_position_and_size(window_handle)
MoveWindow(window_handle, pos[0], pos[1], pos[2], pos[3], 1)
return _SCREENSIZE
def _get_screen_size(wnds):
screen_width, screen_height = get_screen_position_and_size(wnds)[2:4]
return screen_width, screen_height
def _windowEnumerationHandler(handle, result_list):
"""Pass to win32gui.EnumWindows() to generate list of window handle, window
text tuples."""
# pylint: disable=no-member
if win32gui.IsWindowVisible(handle):
result_list.append((handle, win32gui.GetWindowText(handle)))
def _find_window_handles_and_titles(wantedTitle=None):
"""Return list of window handle and window title tuples.
Parameter
---------
wantedTitle:
"""
handles_n_titles = []
EnumWindows(_windowEnumerationHandler, handles_n_titles)
if wantedTitle is None:
return handles_n_titles
else:
return [(handle, title)
for handle, title in handles_n_titles
if title.startswith(wantedTitle)]
def find_figure_handles(*figure_numbers):
"""Find figure handles from figure numbers."""
wnd_handles = []
for figure_number in _parse_figure_numbers(*figure_numbers):
for format_ in FIGURE_TITLE_FORMATS:
winTitle = format_ + ' %d' % figure_number
handle = FindWindow(None, winTitle)
if not handle == 0:
wnd_handles.append(handle)
return wnd_handles
def find_all_figure_numbers():
"""Return list of all figure numbers.
Example
-------
>>> import fig
>>> import pylab as p
>>> for ix in range(5):
... f = p.figure(ix)
... p.draw()
fig.find_all_figure_numbers()
[0, 1, 2, 3, 4]
>>> fig.close()
"""
figure_numbers = []
for wantedTitle in FIGURE_TITLE_FORMATS:
handles_n_titles = _find_window_handles_and_titles(wantedTitle)
for _handle, title in handles_n_titles:
try:
number = int(title.split()[-1])
figure_numbers.append(number)
except (TypeError, ValueError):
pass
# pylint: disable=no-member
return numpy.unique(figure_numbers).tolist()
def _parse_figure_numbers(*args):
figure_numbers = []
for arg in args:
if isinstance(arg, (list, tuple, set)):
for val in arg:
figure_numbers.append(int(val))
elif isinstance(arg, int):
figure_numbers.append(arg)
elif arg == 'all':
figure_numbers = find_all_figure_numbers()
break
else:
raise TypeError('Only integers arguments accepted!')
if len(figure_numbers) == 0:
figure_numbers = find_all_figure_numbers()
return figure_numbers
def _show_figure(figure_numbers, command):
"""Sets the specified figure's show state.
Parameters
----------
figure_numbers: list of figure numbers
command: one of following commands:
SW_FORCEMINIMIZE:
Minimizes a window, even if the thread that owns the window is not
responding. This flag should only be used when minimizing windows
from a different thread.
SW_HIDE:
Hides the window and activates another window.
SW_MAXIMIZE:
Maximizes the specified window.
SW_MINIMIZE:
Minimizes the specified window and activates the next top-level window
in the Z order.
SW_RESTORE:
Activates and displays the window. If the window is minimized or
maximized, the system restores it to its original size and position.
An application should specify this flag when restoring a minimized
window.
SW_SHOW:
Activates the window and displays it in its current size and position.
SW_SHOWDEFAULT:
Sets the show state based on the SW_ value specified in the STARTUPINFO
structure passed to the CreateProcess function by the program that
started the application.
SW_SHOWMAXIMIZED:
Activates the window and displays it as a maximized window.
SW_SHOWMINIMIZED:
Activates the window and displays it as a minimized window.
SW_SHOWMINNOACTIVE:
Displays the window as a minimized window. This value is similar to
SW_SHOWMINIMIZED, except the window is not activated.
SW_SHOWNA:
Displays the window in its current size and position. This value is
similar to SW_SHOW, except the window is not activated.
SW_SHOWNOACTIVATE:
Displays a window in its most recent size and position. This value is
similar to SW_SHOWNORMAL, except the window is not actived.
SW_SHOWNORMAL:
Activates and displays a window. If the window is minimized or
maximized, the system restores it to its original size and position.
An application should specify this flag when displaying the window for
the first time.
"""
for number in _parse_figure_numbers(*figure_numbers):
for format_ in FIGURE_TITLE_FORMATS:
title = format_ + ' %d' % number
handle = FindWindow(None, title)
if not handle == 0:
BringWindowToTop(handle)
ShowWindow(handle, command)
def _show_windows(handles, command, redraw_now=False):
"""Sets the specified window's show state.
Parameters
----------
handles: list of window handles
command: one of following commands:
SW_FORCEMINIMIZE:
Minimizes a window, even if the thread that owns the window is not
responding. This flag should only be used when minimizing windows
from a different thread.
SW_HIDE:
Hides the window and activates another window.
SW_MAXIMIZE:
Maximizes the specified window.
SW_MINIMIZE:
Minimizes the specified window and activates the next top-level window
in the Z order.
SW_RESTORE:
Activates and displays the window. If the window is minimized or
maximized, the system restores it to its original size and position.
An application should specify this flag when restoring a minimized
window.
SW_SHOW:
Activates the window and displays it in its current size and position.
SW_SHOWDEFAULT:
Sets the show state based on the SW_ value specified in the STARTUPINFO
structure passed to the CreateProcess function by the program that
started the application.
SW_SHOWMAXIMIZED:
Activates the window and displays it as a maximized window.
SW_SHOWMINIMIZED:
Activates the window and displays it as a minimized window.
SW_SHOWMINNOACTIVE:
Displays the window as a minimized window. This value is similar to
SW_SHOWMINIMIZED, except the window is not activated.
SW_SHOWNA:
Displays the window in its current size and position. This value is
similar to SW_SHOW, except the window is not activated.
SW_SHOWNOACTIVATE:
Displays a window in its most recent size and position. This value is
similar to SW_SHOWNORMAL, except the window is not actived.
SW_SHOWNORMAL:
Activates and displays a window. If the window is minimized or
maximized, the system restores it to its original size and position.
An application should specify this flag when displaying the window for
the first time.
redraw_now :
"""
# pylint: disable=no-member
for handle in handles:
if not handle == 0:
BringWindowToTop(handle)
ShowWindow(handle, command)
if redraw_now:
rect = GetWindowRect(handle)
win32gui.RedrawWindow(handle, rect, None, win32con.RDW_UPDATENOW)
def keep(*figure_numbers):
"""Keeps figure windows of your choice and closes the rest.
Parameters
----------
figure_numbers : list of integers specifying which figures to keep.
Example:
--------
# keep only figures 1,2,3,5 and 7
>>> import pylab as p
>>> import wafo.fig as fig
>>> for ix in range(10):
... f = p.figure(ix)
>>> fig.keep( range(1,4), 5, 7)
or
fig.keep([range(1,4), 5, 7])
>>> fig.close()
See also
--------
fig.close
"""
figs2keep = []
for fig in figure_numbers:
if isinstance(fig, (list, tuple, set)):
for val in fig:
figs2keep.append(int(val))
elif isinstance(fig, int):
figs2keep.append(fig)
else:
raise TypeError('Only integers arguments accepted!')
if len(figs2keep) > 0:
allfigs = set(find_all_figure_numbers())
figs2delete = allfigs.difference(figs2keep)
close(figs2delete)
def close(*figure_numbers):
""" Close figure window(s)
Parameters
----------
figure_numbers : list of integers or string
specifying which figures to close (default 'all').
Examples
--------
>>> import pylab as p
>>> import wafo.fig as fig
>>> for ix in range(5):
... f = p.figure(ix)
>>> fig.close(3,4) # close figure 3 and 4
>>> fig.close('all') # close all remaining figures
or even simpler
fig.close() # close all remaining figures
See also
--------
fig.keep
"""
# pylint: disable=no-member
for handle in find_figure_handles(*figure_numbers):
if win32gui.SendMessage(handle, win32con.WM_CLOSE, 0, 0):
win32gui.SendMessage(handle, win32con.WM_DESTROY, 0, 0)
def restore(*figure_numbers):
"""Restore figures window size and position to its default value.
Parameters
----------
figure_numbers : list of integers or string
specifying which figures to restor (default 'all').
Description
-----------
RESTORE Activates and displays the window. If the window is minimized
or maximized, the system restores it to its original size and position.
Examples
---------
>>> import pylab as p
>>> import wafo.fig as fig
>>> for ix in range(5):
... f = p.figure(ix)
>>> fig.restore('all') #Restores all figures
>>> fig.restore() #same as restore('all')
>>> fig.restore(p.gcf().number) #Restores the current figure
>>> fig.restore(3) #Restores figure 3
>>> fig.restore([2, 4]) #Restores figures 2 and 4
or alternatively
fig.restore(2, 4)
>>> fig.close()
See also
--------
fig.close,
fig.keep
"""
SW_RESTORE = win32con.SW_RESTORE
# SW_RESTORE = win32con.SW_SHOWDEFAULT
# SW_RESTORE = win32con.SW_SHOWNORMAL
_show_figure(figure_numbers, SW_RESTORE)
def hide(*figure_numbers):
"""hide figure(s) window.
Parameters
----------
figure_numbers : list of integers or string
specifying which figures to hide (default 'all').
Examples:
--------
>>> import wafo.fig as fig
>>> import pylab as p
>>> for ix in range(5):
... f = p.figure(ix)
>>> fig.hide('all') #hides all unhidden figures
>>> fig.hide() #same as hide('all')
>>> fig.hide(p.gcf().number) #hides the current figure
>>> fig.hide(3) #hides figure 3
>>> fig.hide([2, 4]) #hides figures 2 and 4
or alternatively
fig.hide(2, 4)
>>> fig.restore(list(range(5)))
>>> fig.close()
See also
--------
fig.cycle,
fig.keep,
fig.restore
"""
_show_figure(figure_numbers, win32con.SW_HIDE)
def minimize(*figure_numbers):
"""Minimize figure(s) window size.
Parameters
----------
figure_numbers : list of integers or string
specifying which figures to minimize (default 'all').
Examples:
---------
>>> import wafo.fig as fig
>>> import pylab as p
>>> for ix in range(5):
... f = p.figure(ix)
>>> fig.minimize('all') #Minimizes all unhidden figures
>>> fig.minimize() #same as minimize('all')
>>> fig.minimize(p.gcf().number) #Minimizes the current figure
>>> fig.minimize(3) #Minimizes figure 3
>>> fig.minimize([2, 4]) #Minimizes figures 2 and 4
or alternatively
fig.minimize(2, 4)
>>> fig.close()
See also
--------
fig.cycle,
fig.keep,
fig.restore
"""
_show_figure(figure_numbers, win32con.SW_SHOWMINIMIZED)
def maximize(*figure_numbers):
"""Maximize figure(s) window size.
Parameters
----------
figure_numbers : list of integers or string
specifying which figures to maximize (default 'all').
Examples:
---------
>>> import pylab as p
>>> import wafo.fig as fig
>>> for ix in range(5):
... f = p.figure(ix)
>>> fig.maximize('all') #Maximizes all unhidden figures
>>> fig.maximize() #same as maximize('all')
>>> fig.maximize(p.gcf().number) #Maximizes the current figure
>>> fig.maximize(3) #Maximizes figure 3
>>> fig.maximize([2, 4]) #Maximizes figures 2 and 4
or alternatively
fig.maximize(2, 4)
>>> fig.close()
See also
--------
fig.cycle,
fig.keep,
fig.restore
"""
_show_figure(figure_numbers, win32con.SW_SHOWMAXIMIZED)
def pile(*figure_numbers, **kwds):
"""Pile figure windows.
Parameters
----------
figure_numbers : list of integers or string
specifying which figures to pile (default 'all').
kwds : dict with the following keys
position :
width :
height :
Description
-------------
PILE piles all open figure windows on top of eachother
with complete overlap. PILE(FIGS) can be used to specify which
figures that should be piled. Figures are not sorted when specified.
Example:
--------
>>> import pylab as p
>>> import wafo.fig as fig
>>> for ix in range(7):
... f = p.figure(ix)
>>> fig.pile() # pile all open figures
>>> fig.pile(range(1,4), 5, 7) # pile figure 1,2,3,5 and 7
>>> fig.close()
See also
--------
fig.cycle, fig.keep, fig.maximize, fig.restore,
fig.stack, fig.tile
"""
wnds = find_figure_handles(*figure_numbers)
numfigs = len(wnds)
if numfigs > 0:
screen_width, screen_height = _get_screen_size(wnds)
pos = kwds.get(
'position', (int(screen_width / 5), int(screen_height / 4)))
width = kwds.get('width', int(screen_width / 2.5))
height = kwds.get('height', int(screen_height / 2))
for wnd in wnds:
MoveWindow(wnd, pos[0], pos[1], width, height, 1)
BringWindowToTop(wnd)
def set_size(*figure_numbers, **kwds):
"""Set size for figure windows.
Parameters
----------
figure_numbers : list of integers or string
specifying which figures to pile (default 'all').
kwds : dict with the following keys
width :
height :
Description
-------------
Set size sets the size of all open figure windows. SET_SIZE(FIGS)
can be used to specify which figures that should be resized.
Figures are not sorted when specified.
Example:
--------
>>> import pylab as p
>>> import fig
>>> for ix in range(7):
... f = p.figure(ix)
>>> fig.set_size(7, width=150, height=100)
>>> fig.set_size(range(1,4), 5,width=250, height=170)
>>> fig.close()
See also
--------
fig.cycle, fig.keep, fig.maximize, fig.restore,
fig.stack, fig.tile
"""
handles = find_figure_handles(*figure_numbers)
numfigs = len(handles)
if numfigs > 0:
screen_width, screen_height = _get_screen_size(handles)
width = kwds.get('width', int(screen_width / 2.5))
height = kwds.get('height', int(screen_height / 2))
new_pos = kwds.get('position', None)
pos = new_pos
for handle in handles:
if not new_pos:
pos = get_window_position_and_size(handle)
MoveWindow(handle, pos[0], pos[1], width, height, 1)
BringWindowToTop(handle)
def stack(*figure_numbers, **kwds):
"""Stack figure windows.
Parameters
----------
figure_numbers : list of integers or string
specifying which figures to stack (default 'all').
kwds : dict with the following keys
figs_per_stack :
number of figures per stack (default depends on screenheight)
Description
-----------
STACK stacks all open figure windows on top of eachother
with maximum overlap. STACK(FIGS) can be used to specify which
figures that should be stacked. Figures are not sorted when specified.
Example:
--------
>>> import pylab as p
>>> import wafo.fig as fig
>>> for ix in range(7):
... f = p.figure(ix)
>>> fig.stack() # stack all open figures
>>> fig.stack(range(1,4), 5, 7) # stack figure 1,2,3,5 and 7
>>> fig.close()
See also
--------
fig.cycle, fig.keep, fig.maximize, fig.restore,
fig.pile, fig.tile
"""
wnds = find_figure_handles(*figure_numbers)
numfigs = len(wnds)
if numfigs > 0:
screenpos = get_screen_position_and_size(wnds)
y_step = 25
x_step = border = 5
figs_per_stack = kwds.get(
'figs_per_stack',
int(numpy.fix(0.7 * (screenpos[3] - border) / y_step)))
for iy in range(numfigs):
pos = get_window_position_and_size(wnds[iy])
# print('[x, y, w, h] = ', pos)
ix = iy % figs_per_stack
ypos = int(screenpos[1] + ix * y_step + border)
xpos = int(screenpos[0] + ix * x_step + border)
MoveWindow(wnds[iy], xpos, ypos, pos[2], pos[3], 1)
BringWindowToTop(wnds[iy])
def tile(*figure_numbers, **kwds):
"""Tile figure windows.
Parameters
----------
figure_numbers : list of integers or string
specifying which figures to tile (default 'all').
kwds : dict with key pairs
specifying how many pairs of figures that are tiled at a time
Description
-----------
TILE places all open figure windows around on the screen with no
overlap. TILE(FIGS) can be used to specify which figures that
should be tiled. Figures are not sorted when specified.
Example:
--------
>>> import pylab as p
>>> import wafo.fig as fig
>>> for ix in range(7):
... f = p.figure(ix)
>>> fig.tile() # tile all open figures
>>> fig.tile( range(1,4), 5, 7) # tile figure 1,2,3,5 and 7
>>> fig.tile(range(1,11), pairs=2) # tile figure 1 to 10 two at a time
>>> fig.tile(range(1,11), pairs=3) # tile figure 1 to 10 three at a time
>>> fig.close()
See also
--------
fig.cycle, fig.keep, fig.maximize, fig.minimize
fig.restore, fig.pile, fig.stack
"""
wnds = find_figure_handles(*figure_numbers)
nfigs = len(wnds)
# Number of windows.
if nfigs > 0:
nfigspertile = kwds.get('pairs', nfigs)
ceil = numpy.ceil
sqrt = numpy.sqrt
maximum = numpy.maximum
nlayers = int(ceil(nfigs / nfigspertile))
# Number of figures horisontally.
nh = maximum(int(ceil(sqrt(nfigspertile))), 2)
# Number of figures vertically.
nv = maximum(int(ceil(nfigspertile / nh)), 2)
screenpos = get_screen_position_and_size(wnds)
screen_width, screen_heigth = screenpos[2:4]
hspc = 10 # Horisontal space.
topspc = 20 # Space above top figure.
medspc = 10 # Space between figures.
botspc = 20 # Space below bottom figure.
figwid = (screen_width - (nh + 1) * hspc) / nh
fighgt = (screen_heigth - (topspc + botspc) - (nv - 1) * medspc) / nv
figwid = int(numpy.round(figwid))
fighgt = int(numpy.round(fighgt))
idx = 0
for unused_ix in range(nlayers):
for row in range(nv):
figtop = int(screenpos[1] + topspc + row * (fighgt + medspc))
for col in range(nh):
if (row) * nh + col < nfigspertile:
if idx < nfigs:
figlft = int(
screenpos[0] + (col + 1) * hspc + col * figwid)
fighnd = wnds[idx]
MoveWindow(fighnd, figlft, figtop, figwid, fighgt,
1)
# Set position.
BringWindowToTop(fighnd)
idx += 1
class _CycleGenerator(object):
"""Cycle through figure windows.
Parameters
----------
figure_numbers : list of integers or string
specifying which figures to cycle through (default 'all').
kwds : dict with the following keys
pairs : number of figures to cycle in pairs (default 1)
maximize: If True maximize figure when viewing (default False)
interval : pause interval in seconds
Description
-----------
CYCLE brings up all open figure in ascending order and pauses after
each figure. Press escape to quit cycling, backspace to display previous
figure(s) and press any other key to display next figure(s)
When done, the figures are sorted in ascending order.
CYCLE(maximize=True) does the same thing, except figures are maximized.
CYCLE(pairs=2) cycle through all figures in pairs of 2.
Examples:
>>> import pylab as p
>>> import wafo.fig as fig
>>> for ix in range(4):
... f = p.figure(ix)
fig.cycle(range(3), interval=1) # Cycle trough figure 0 to 2
# Cycle trough figure 0 to 2 with figures maximized
fig.cycle(range(3), maximize=True, interval=1)
fig.cycle(interval=1) # Cycle through all figures one at a time
fig.tile(pairs=2, interval=1)
fig.cycle(pairs=2, interval=2) # Cycle through all figures two at a time
fig.cycle(pairs=2) # Manually cycle through all figures two at a time
>>> fig.close()
See also
--------
fig.keep, fig.maximize, fig.restore, fig.pile,
fig.stack, fig.tile
"""
escape_key = chr(27)
backspace_key = chr(8)
def __init__(self, **kwds):
self.dialog = None
maximize = kwds.get('maximize', False)
pairs = kwds.get('pairs', 1)
self.interval = kwds.get('interval', 'user_defined')
self.nfigspercycle = 1
if maximize:
self.command = win32con.SW_SHOWMAXIMIZED
else:
self.command = win32con.SW_SHOWNORMAL
if pairs is not None:
self.nfigspercycle = pairs
def _set_options(self, kwds):
self.__init__(**kwds)
def _iterate(self, handles):
i = 0
numfigs = len(handles)
self.dialog = _get_cycle_dialog(parent=None, interval=self.interval)
while 0 <= i and i < numfigs:
iu = min(i + self.nfigspercycle, numfigs)
yield handles[i:iu]
i = self.next_index(i)
self.dialog.Destroy()
raise StopIteration
def next_index(self, i):
result = self.dialog.ShowModal()
if result == wx.ID_FORWARD:
i += self.nfigspercycle
elif result == wx.ID_BACKWARD:
i -= self.nfigspercycle
else:
i = -1
return i
def __call__(self, *figure_numbers, **kwds):
handles = find_figure_handles(*figure_numbers)
numfigs = len(handles)
if numfigs > 0:
self._set_options(kwds)
for handle in self._iterate(handles):
_show_windows(handle, self.command, redraw_now=True)
_show_windows(handles, win32con.SW_SHOWNORMAL)
cycle = _CycleGenerator()
if __name__ == '__main__':
from wafo.testing import test_docstrings
import matplotlib
matplotlib.interactive(True)
test_docstrings(__file__)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -1,538 +0,0 @@
"""
Created on 20. aug. 2015
@author: pab
"""
from __future__ import division
from collections import namedtuple
import warnings
import numdifftools as nd
import numdifftools.nd_algopy as nda
from numdifftools.extrapolation import dea3
from numdifftools.limits import Limit
import numpy as np
from numpy import linalg
from numpy.polynomial.chebyshev import chebval, Chebyshev
from numpy.polynomial import polynomial
from wafo.misc import piecewise, findcross, ecross
_FINFO = np.finfo(float)
EPS = _FINFO.eps
_EPS = EPS
_TINY = _FINFO.tiny
_HUGE = _FINFO.max
def _assert(cond, msg):
if not cond:
raise ValueError(msg)
def _assert_warn(cond, msg):
if not cond:
warnings.warn(msg)
class PolyBasis(object):
@staticmethod
def _derivative(c, m):
return polynomial.polyder(c, m)
@staticmethod
def eval(t, c):
return polynomial.polyval(t, c)
@staticmethod
def _coefficients(k):
c = np.zeros(k + 1)
c[k] = 1
return c
def derivative(self, t, k, n=1):
c = self._coefficients(k)
d_c = self._derivative(c, m=n)
return self.eval(t, d_c)
def __call__(self, t, k):
return t**k
poly_basis = PolyBasis()
class ChebyshevBasis(PolyBasis):
@staticmethod
def _derivative(c, m):
cheb = Chebyshev(c)
dcheb = cheb.deriv(m=m)
return dcheb.coef
@staticmethod
def eval(t, c):
return chebval(t, c)
def __call__(self, t, k):
c = self._coefficients(k)
return self.eval(t, c)
chebyshev_basis = ChebyshevBasis()
def richardson(q_val, k):
# license BSD
# Richardson extrapolation with parameter estimation
c = np.real((q_val[k - 1] - q_val[k - 2]) / (q_val[k] - q_val[k - 1])) - 1.
# The lower bound 0.07 admits the singularity x.^-0.9
c = max(c, 0.07)
return q_val[k] + (q_val[k] - q_val[k - 1]) / c
def evans_webster_weights(omega, g, d_g, x, basis, *args, **kwds):
def psi(t, k):
return d_g(t, *args, **kwds) * basis(t, k)
j_w = 1j * omega
n = len(x)
a_matrix = np.zeros((n, n), dtype=complex)
rhs = np.zeros((n,), dtype=complex)
dbasis = basis.derivative
lim_g = Limit(g)
b_1 = np.exp(j_w * lim_g(1, *args, **kwds))
if np.isnan(b_1):
b_1 = 0.0
a_1 = np.exp(j_w * lim_g(-1, *args, **kwds))
if np.isnan(a_1):
a_1 = 0.0
lim_psi = Limit(psi)
for k in range(n):
rhs[k] = basis(1, k) * b_1 - basis(-1, k) * a_1
a_matrix[k] = (dbasis(x, k, n=1) + j_w * lim_psi(x, k))
solution = linalg.lstsq(a_matrix, rhs)
return solution[0]
def osc_weights(omega, g, d_g, x, basis, a_b, *args, **kwds):
def _g(t):
return g(scale * t + offset, *args, **kwds)
def _d_g(t):
return scale * d_g(scale * t + offset, *args, **kwds)
w = []
for a, b in zip(a_b[::2], a_b[1::2]):
scale = (b - a) / 2
offset = (a + b) / 2
w.append(evans_webster_weights(omega, _g, _d_g, x, basis))
return np.asarray(w).ravel()
class _Integrator(object):
info = namedtuple('info', ['error_estimate', 'n'])
def __init__(self, f, g, dg=None, a=-1, b=1, basis=chebyshev_basis, s=1,
precision=10, endpoints=True, full_output=False):
self.f = f
self.g = g
self.dg = nd.Derivative(g) if dg is None else dg
self.basis = basis
self.a = a
self.b = b
self.s = s
self.endpoints = endpoints
self.precision = precision
self.full_output = full_output
class QuadOsc(_Integrator):
def __init__(self, f, g, dg=None, a=-1, b=1, basis=chebyshev_basis, s=15,
precision=10, endpoints=False, full_output=False, maxiter=17):
self.maxiter = maxiter
super(QuadOsc, self).__init__(f, g, dg=dg, a=a, b=b, basis=basis, s=s,
precision=precision, endpoints=endpoints,
full_output=full_output)
@staticmethod
def _change_interval_to_0_1(f, g, d_g, a, _b):
def f_01(t, *args, **kwds):
den = 1 - t
return f(a + t / den, *args, **kwds) / den ** 2
def g_01(t, *args, **kwds):
return g(a + t / (1 - t), *args, **kwds)
def d_g_01(t, *args, **kwds):
den = 1 - t
return d_g(a + t / den, *args, **kwds) / den ** 2
return f_01, g_01, d_g_01, 0., 1.
@staticmethod
def _change_interval_to_m1_0(f, g, d_g, _a, b):
def f_m10(t, *args, **kwds):
den = 1 + t
return f(b + t / den, *args, **kwds) / den ** 2
def g_m10(t, *args, **kwds):
return g(b + t / (1 + t), *args, **kwds)
def d_g_m10(t, *args, **kwds):
den = 1 + t
return d_g(b + t / den, *args, **kwds) / den ** 2
return f_m10, g_m10, d_g_m10, -1.0, 0.0
@staticmethod
def _change_interval_to_m1_1(f, g, d_g, _a, _b):
def f_m11(t, *args, **kwds):
den = (1 - t**2)
return f(t / den, *args, **kwds) * (1 + t**2) / den ** 2
def g_m11(t, *args, **kwds):
den = (1 - t**2)
return g(t / den, *args, **kwds)
def d_g_m11(t, *args, **kwds):
den = (1 - t**2)
return d_g(t / den, *args, **kwds) * (1 + t**2) / den ** 2
return f_m11, g_m11, d_g_m11, -1., 1.
def _get_functions(self):
a, b = self.a, self.b
reverse = np.real(a) > np.real(b)
if reverse:
a, b = b, a
f, g, dg = self.f, self.g, self.dg
if a == b:
pass
elif np.isinf(a) | np.isinf(b):
# Check real limits
if ~np.isreal(a) | ~np.isreal(b) | np.isnan(a) | np.isnan(b):
raise ValueError('Infinite intervals must be real.')
# Change of variable
if np.isfinite(a) & np.isinf(b):
f, g, dg, a, b = self._change_interval_to_0_1(f, g, dg, a, b)
elif np.isinf(a) & np.isfinite(b):
f, g, dg, a, b = self._change_interval_to_m1_0(f, g, dg, a, b)
else: # -inf to inf
f, g, dg, a, b = self._change_interval_to_m1_1(f, g, dg, a, b)
return f, g, dg, a, b, reverse
def __call__(self, omega, *args, **kwds):
f, g, dg, a, b, reverse = self._get_functions()
val, err = self._quad_osc(f, g, dg, a, b, omega, *args, **kwds)
if reverse:
val = -val
if self.full_output:
return val, err
return val
@staticmethod
def _get_best_estimate(k, q_0, q_1, q_2):
if k >= 5:
q_v = np.hstack((q_0[k], q_1[k], q_2[k]))
q_w = np.hstack((q_0[k - 1], q_1[k - 1], q_2[k - 1]))
elif k >= 3:
q_v = np.hstack((q_0[k], q_1[k]))
q_w = np.hstack((q_0[k - 1], q_1[k - 1]))
else:
q_v = np.atleast_1d(q_0[k])
q_w = q_0[k - 1]
errors = np.atleast_1d(abs(q_v - q_w))
j = np.nanargmin(errors)
return q_v[j], errors[j]
def _extrapolate(self, k, q_0, q_1, q_2):
if k >= 4:
q_1[k] = dea3(q_0[k - 2], q_0[k - 1], q_0[k])[0]
q_2[k] = dea3(q_1[k - 2], q_1[k - 1], q_1[k])[0]
elif k >= 2:
q_1[k] = dea3(q_0[k - 2], q_0[k - 1], q_0[k])[0]
# # Richardson extrapolation
# if k >= 4:
# q_1[k] = richardson(q_0, k)
# q_2[k] = richardson(q_1, k)
# elif k >= 2:
# q_1[k] = richardson(q_0, k)
q, err = self._get_best_estimate(k, q_0, q_1, q_2)
return q, err
def _quad_osc(self, f, g, dg, a, b, omega, *args, **kwds):
if a == b:
q_val = b - a
err = np.abs(b - a)
return q_val, err
abseps = 10**-self.precision
max_iter = self.maxiter
basis = self.basis
if self.endpoints:
x_n = chebyshev_extrema(self.s)
else:
x_n = chebyshev_roots(self.s)
# x_n = tanh_sinh_open_nodes(self.s)
# One interval
hh = (b - a) / 2
x = (a + b) / 2 + hh * x_n # Nodes
dtype = complex
val0 = np.zeros((max_iter, 1), dtype=dtype) # Quadrature
val1 = np.zeros((max_iter, 1), dtype=dtype) # First extrapolation
val2 = np.zeros((max_iter, 1), dtype=dtype) # Second extrapolation
lim_f = Limit(f)
a_b = np.hstack([a, b])
wq = osc_weights(omega, g, dg, x_n, basis, a_b, *args, **kwds)
val0[0] = hh * np.sum(wq * lim_f(x, *args, **kwds))
# Successive bisection of intervals
nq = len(x_n)
n = nq
for k in range(1, max_iter):
n += nq * 2**k
hh = hh / 2
x = np.hstack([x + a, x + b]) / 2
a_b = np.hstack([a_b + a, a_b + b]) / 2
wq = osc_weights(omega, g, dg, x_n, basis, a_b, *args, **kwds)
val0[k] = hh * np.sum(wq * lim_f(x, *args, **kwds))
q_val, err = self._extrapolate(k, val0, val1, val2)
converged = (err <= abseps) | ~np.isfinite(q_val)
if converged:
break
_assert_warn(converged, 'Max number of iterations reached '
'without convergence.')
_assert_warn(np.isfinite(q_val),
'Integral approximation is Infinite or NaN.')
# The error estimate should not be zero
err += 2 * np.finfo(q_val).eps
return q_val, self.info(err, n)
def adaptive_levin_points(m, delta):
m_1 = m - 1
prm = 0.5
while prm * m_1 / delta >= 1:
delta = 2 * delta
k = np.arange(m)
x = piecewise([k < prm * m_1, k == np.ceil(prm * m_1)],
[-1 + k / delta, 0 * k, 1 - (m_1 - k) / delta])
return x
def open_levin_points(m, delta):
return adaptive_levin_points(m + 2, delta)[1:-1]
def chebyshev_extrema(m, delta=None):
k = np.arange(m)
x = np.cos(k * np.pi / (m - 1))
return x
def tanh_sinh_nodes(m, delta=None, tol=_EPS):
tmax = np.arcsinh(np.arctanh(1 - _EPS) * 2 / np.pi)
# tmax = 3.18
m_1 = int(np.floor(-np.log2(tmax / max(m - 1, 1)))) - 1
h = 2.0**-m_1
t = np.arange((m + 1) // 2 + 1) * h
x = np.tanh(np.pi / 2 * np.sinh(t))
k = np.flatnonzero(np.abs(x - 1) <= 10 * tol)
y = x[:k[0] + 1] if len(k) else x
return np.hstack((-y[:0:-1], y))
def tanh_sinh_open_nodes(m, delta=None, tol=_EPS):
return tanh_sinh_nodes(m + 1, delta, tol)[1:-1]
def chebyshev_roots(m, delta=None):
k = np.arange(1, 2 * m, 2) * 0.5
x = np.cos(k * np.pi / m)
return x
class AdaptiveLevin(_Integrator):
"""Return integral for the Levin-type and adaptive Levin-type methods"""
@staticmethod
def _a_levin(omega, f, g, d_g, x, s, basis, *args, **kwds):
def psi(t, k):
return d_g(t, *args, **kwds) * basis(t, k)
j_w = 1j * omega
nu = np.ones((len(x),), dtype=int)
nu[0] = nu[-1] = s
S = np.cumsum(np.hstack((nu, 0)))
S[-1] = 0
n = int(S[-2])
a_matrix = np.zeros((n, n), dtype=complex)
rhs = np.zeros((n,))
dff = Limit(nda.Derivative(f))
d_psi = Limit(nda.Derivative(psi))
dbasis = basis.derivative
for r, t in enumerate(x):
for j in range(S[r - 1], S[r]):
order = ((j - S[r - 1]) % nu[r]) # derivative order
dff.fun.n = order
rhs[j] = dff(t, *args, **kwds)
d_psi.fun.n = order
for k in range(n):
a_matrix[j, k] = (dbasis(t, k, n=order + 1) +
j_w * d_psi(t, k))
k1 = np.flatnonzero(1 - np.isfinite(rhs))
if k1.size > 0: # Remove singularities
warnings.warn('Singularities detected! ')
a_matrix[k1] = 0
rhs[k1] = 0
solution = linalg.lstsq(a_matrix, rhs)
v = basis.eval([-1, 1], solution[0])
lim_g = Limit(g)
g_b = np.exp(j_w * lim_g(1, *args, **kwds))
if np.isnan(g_b):
g_b = 0
g_a = np.exp(j_w * lim_g(-1, *args, **kwds))
if np.isnan(g_a):
g_a = 0
return v[1] * g_b - v[0] * g_a
def _get_integration_limits(self, omega, args, kwds):
a, b = self.a, self.b
M = 30
ab = [a]
scale = (b - a) / 2
n = 30
x = np.linspace(a, b, n + 1)
dg_x = np.asarray([scale * omega * self.dg(xi, *args, **kwds)
for xi in x])
i10 = findcross(dg_x, M)
i1 = findcross(dg_x, 1)
i0 = findcross(dg_x, 0)
im1 = findcross(dg_x, -1)
im10 = findcross(dg_x, -M)
x10 = ecross(x, dg_x, i10, M) if len(i10) else ()
x1 = ecross(x, dg_x, i1, 1) if len(i1) else ()
x0 = ecross(x, dg_x, i0, 0) if len(i0) else ()
xm1 = ecross(x, dg_x, im1, -1) if len(im1) else ()
xm10 = ecross(x, dg_x, im10, -M) if len(im10) else ()
for i in np.unique(np.hstack((x10, x1, x0, xm1, xm10))):
if x[0] < i < x[n]:
ab.append(i)
ab.append(b)
return ab
def __call__(self, omega, *args, **kwds):
ab = self._get_integration_limits(omega, args, kwds)
s = self.s
val = 0
n = 0
err = 0
for ai, bi in zip(ab[:-1], ab[1:]):
vali, infoi = self._QaL(s, ai, bi, omega, *args, **kwds)
val += vali
err += infoi.error_estimate
n += infoi.n
if self.full_output:
info = self.info(err, n)
return val, info
return val
@staticmethod
def _get_num_points(s, prec, betam):
return 1 if s > 1 else int(prec / max(np.log10(betam + 1), 1) + 1)
def _QaL(self, s, a, b, omega, *args, **kwds):
"""if s>1,the integral is computed by Q_s^L"""
scale = (b - a) / 2
offset = (a + b) / 2
prec = self.precision # desired precision
def ff(t, *args, **kwds):
return scale * self.f(scale * t + offset, *args, **kwds)
def gg(t, *args, **kwds):
return self.g(scale * t + offset, *args, **kwds)
def dgg(t, *args, **kwds):
return scale * self.dg(scale * t + offset, *args, **kwds)
dg_a = abs(omega * dgg(-1, *args, **kwds))
dg_b = abs(omega * dgg(1, *args, **kwds))
g_a = abs(omega * gg(-1, *args, **kwds))
g_b = abs(omega * gg(1, *args, **kwds))
delta, alpha = min(dg_a, dg_b), min(g_a, g_b)
betam = delta # * scale
if self.endpoints:
if delta < 10 or alpha <= 10 or s > 1:
points = chebyshev_extrema
else:
points = adaptive_levin_points
elif delta < 10 or alpha <= 10 or s > 1:
points = chebyshev_roots
else:
points = open_levin_points # tanh_sinh_open_nodes
m = self._get_num_points(s, prec, betam)
abseps = 10 * 10.0**-prec
num_collocation_point_list = m * 2**np.arange(1, 5) + 1
basis = self.basis
q_val = 1e+300
num_function_evaluations = 0
n = 0
for num_collocation_points in num_collocation_point_list:
n_old = n
q_old = q_val
x = points(num_collocation_points, betam)
n = len(x)
if n > n_old:
q_val = self._a_levin(omega, ff, gg, dgg, x, s, basis, *args,
**kwds)
num_function_evaluations += n
err = np.abs(q_val - q_old)
if err <= abseps:
break
info = self.info(err, num_function_evaluations)
return q_val, info
class EvansWebster(AdaptiveLevin):
"""Return integral for the Evans Webster method"""
def __init__(self, f, g, dg=None, a=-1, b=1, basis=chebyshev_basis, s=8,
precision=10, endpoints=False, full_output=False):
super(EvansWebster,
self).__init__(f, g, dg=dg, a=a, b=b, basis=basis, s=s,
precision=precision, endpoints=endpoints,
full_output=full_output)
def _a_levin(self, omega, ff, gg, dgg, x, s, basis, *args, **kwds):
w = evans_webster_weights(omega, gg, dgg, x, basis, *args, **kwds)
f = Limit(ff)(x, *args, **kwds)
return np.sum(f * w)
def _get_num_points(self, s, prec, betam):
return 8 if s > 1 else int(prec / max(np.log10(betam + 1), 1) + 1)
if __name__ == '__main__':
tanh_sinh_nodes(16)

@ -1,532 +0,0 @@
'''
All the software contained in this library is protected by copyright.
Permission to use, copy, modify, and distribute this software for any
purpose without fee is hereby granted, provided that this entire notice
is included in all copies of any software which is or includes a copy
or modification of this software and in all copies of the supporting
documentation for such software.
THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
WARRANTY. IN NO EVENT, NEITHER THE AUTHORS, NOR THE PUBLISHER, NOR ANY
MEMBER OF THE EDITORIAL BOARD OF THE JOURNAL "NUMERICAL ALGORITHMS",
NOR ITS EDITOR-IN-CHIEF, BE LIABLE FOR ANY ERROR IN THE SOFTWARE, ANY
MISUSE OF IT OR ANY DAMAGE ARISING OUT OF ITS USE. THE ENTIRE RISK OF
USING THE SOFTWARE LIES WITH THE PARTY DOING SO.
ANY USE OF THE SOFTWARE CONSTITUTES ACCEPTANCE OF THE TERMS OF THE
ABOVE STATEMENT.
AUTHORS:
Per A Brodtkorb
Python code Based on matlab code written by:
Marco Caliari
University of Verona, Italy
E-mail: marco.caliari@univr.it
Stefano de Marchi, Alvise Sommariva, Marco Vianello
University of Padua, Italy
E-mail: demarchi@math.unipd.it, alvise@math.unipd.it,
marcov@math.unipd.it
Reference
---------
Padua2DM: fast interpolation and cubature at the Padua points in Matlab/Octave
NUMERICAL ALGORITHMS, 56 (2011), PP. 45-60
Padua module
------------
In polynomial interpolation of two variables, the Padua points are the first
known example (and up to now the only one) of a unisolvent point set
(that is, the interpolating polynomial is unique) with minimal growth of their
Lebesgue constant, proven to be O(log2 n).
This module provides all the functions needed to perform interpolation and
cubature at the Padua points, together with the functions and the demos used
in the paper.
pdint.m : main function for interpolation at the Padua points
pdcub.m : main function for cubature at the Padua points
pdpts.m : function for the computation of the Padua points
padua_fit.m : function for the computation of the interpolation
coefficients by FFT (recommended)
pdcfsMM.m : function for the computation of the interpolation
coefficients by matrix multiplications
pdval.m : function for the evaluation of the interpolation
polynomial
pdwtsFFT.m : function for the computation of the cubature
weights by FFT
pdwtsMM.m : function for the computation of the cubature
weights by matrix multiplications (recommended)
funct.m : function containing some test functions
demo_pdint.m : demo script for pdint
demo_cputime_pdint.m : demo script for the computation of CPU time for
interpolation
demo_errors_pdint.m : demo script for the comparison of interpolation with
coefficients computed by FFT or by matrix
multiplications
demo_pdcub : demo script for pdcub
demo_cputime_pdcub.m : demo script for the computation of CPU time for
cubature
demo_errors_pdcub.m : demo script for the comparison of cubature with
weights computed by FFT or by matrix multiplications
demo_errors_pdcub_gl.m : demo script for the comparison of different cubature
formulas
cubature_square.m : function for the computation of some cubature
formulas for the square
omelyan_solovyan_rule.m : function for the computation of Omelyan-Solovyan
cubature points and weights
Contents.m : Contents file for Matlab
'''
from __future__ import absolute_import, division
import numpy as np
from numpy.fft import fft
from wafo.dctpack import dct
from wafo.polynomial import map_from_interval, map_to_interval
# from scipy.fftpack.realtransforms import dct
class _ExampleFunctions(object):
'''
Computes test function in the points (x, y)
Parameters
----------
x,y : array-like
evaluate the function in the points (x,y)
i : scalar int (default 0)
defining which test function to use. Options are
0: franke
1: half_sphere
2: poly_degree20
3: exp_fun1
4: exp_fun100
5: cos30
6: constant
7: exp_xy
8: runge
9: abs_cubed
10: gauss
11: exp_inv
Returns
-------
z : array-like
value of the function in the points (x,y)
'''
@staticmethod
def franke(x, y):
'''Franke function.
The value of the definite integral on the square [-1,1] x [-1,1],
obtained using a Padua Points cubature formula of degree 500, is
2.1547794245591083e+000 with an estimated absolute error of 8.88e-016.
The value of the definite integral on the square [0,1] x [0,1],
obtained using a Padua Points cubature formula of degree 500, is
4.06969589491556e-01 with an estimated absolute error of 8.88e-016.
Maple: 0.40696958949155611906
'''
def _exp(x, y, loc, scale, p2=2):
return np.exp(- (x - loc[0])**2 / scale[0] - (y - loc[1])**p2 / scale[1])
# exp = np.exp
x9, y9 = 9. * x, 9. * y
return (3. / 4 * _exp(x9, y9, [2, 2], [4, 4]) +
3. / 4 * _exp(x9, y9, [-1, -1], [49, 10], p2=1) +
1. / 2 * _exp(x9, y9, [7, 3], [4, 4]) -
1. / 5 * _exp(x9, y9, [4, 7], [1, 1]))
@staticmethod
def half_sphere(x, y):
'''The value of the definite integral on the square [-1,1] x [-1,1],
obtained using a Padua Points cubature formula of degree 2000, is
3.9129044444568244e+000 with an estimated absolute error of 3.22e-010.
'''
return ((x - 0.5)**2 + (y - 0.5)**2)**(1. / 2)
@staticmethod
def poly_degree20(x, y):
''''Bivariate polynomial having moderate degree.
The value of the definite integral on the square [-1,1] x
[-1,1], up to machine precision, is 18157.16017316017 (see ref. 6).
The value of the definite integral on the square [-1,1] x [-1,1],
obtained using a Padua Points cubature formula of degree 500,
is 1.8157160173160162e+004.
2D modification of an example by L.N.Trefethen (see ref. 7), f(x)=x^20.
'''
return (x + y)**20
@staticmethod
def exp_fun1(x, y):
''' The value of the definite integral on the square [-1,1] x [-1,1],
obtained using a Padua Points cubature formula of degree 2000,
is 2.1234596326670683e+001 with an estimated absolute error of
7.11e-015.
'''
return np.exp((x - 0.5)**2 + (y - 0.5)**2)
@staticmethod
def exp_fun100(x, y):
'''The value of the definite integral on the square [-1,1] x [-1,1],
obtained using a Padua Points cubature formula of degree 2000,
is 3.1415926535849605e-002 with an estimated absolute error of
3.47e-017.
'''
return np.exp(-100 * ((x - 0.5)**2 + (y - 0.5)**2))
@staticmethod
def cos30(x, y):
''' The value of the definite integral on the square [-1,1] x [-1,1],
obtained using a Padua Points cubature formula of degree 500,
is 4.3386955120336568e-003 with an estimated absolute error of
2.95e-017.
'''
return np.cos(30 * (x + y))
@staticmethod
def constant(x, y):
'''Constant.
To test interpolation and cubature at degree 0.
The value of the definite integral on the square [-1,1] x [-1,1]
is 4.
'''
return np.ones(np.shape(x + y))
@staticmethod
def exp_xy(x, y):
'''The value of the definite integral on the square [-1,1] x [-1,1]
is up to machine precision is 5.524391382167263 (see ref. 6).
2. The value of the definite integral on the square [-1,1] x [-1,1],
obtained using a Padua Points cubature formula of degree 500,
is 5.5243913821672628e+000 with an estimated absolute error of
0.00e+000.
2D modification of an example by L.N.Trefethen (see ref. 7),
f(x)=exp(x).
'''
return np.exp(x + y)
@staticmethod
def runge(x, y):
''' Bivariate Runge function: as 1D complex function is analytic
in a neighborhood of [-1; 1] but not throughout the complex plane.
The value of the definite integral on the square [-1,1] x [-1,1],
up to machine precision, is 0.597388947274307 (see ref. 6).
The value of the definite integral on the square [-1,1] x [-1,1],
obtained using a Padua Points cubature formula of degree 500,
is 5.9738894727430725e-001 with an estimated absolute error of
0.00e+000.
2D modification of an example by L.N.Trefethen (see ref. 7),
f(x)=1/(1+16*x^2).
'''
return 1. / (1 + 16 * (x**2 + y**2))
@staticmethod
def abs_cubed(x, y):
'''Low regular function.
The value of the definite integral on the square [-1,1] x [-1,1],
up to machine precision, is 2.508723139534059 (see ref. 6).
The value of the definite integral on the square [-1,1] x [-1,1],
obtained using a Padua Points cubature formula of degree 500,
is 2.5087231395340579e+000 with an estimated absolute error of
0.00e+000.
2D modification of an example by L.N.Trefethen (see ref. 7),
f(x)=abs(x)^3.
'''
return (x**2 + y**2)**(3 / 2)
@staticmethod
def gauss(x, y):
'''Bivariate gaussian: smooth function.
The value of the definite integral on the square [-1,1] x [-1,1],
up to machine precision, is 2.230985141404135 (see ref. 6).
The value of the definite integral on the square [-1,1] x [-1,1],
obtained using a Padua Points cubature formula of degree 500,
is 2.2309851414041333e+000 with an estimated absolute error of
2.66e-015.
2D modification of an example by L.N.Trefethen (see ref. 7),
f(x)=exp(-x^2).
'''
return np.exp(-x**2 - y**2)
@staticmethod
def exp_inv(x, y):
'''Bivariate example stemming from a 1D C-infinity function.
The value of the definite integral on the square [-1,1] x [-1,1],
up to machine precision, is 0.853358758654305 (see ref. 6).
The value of the definite integral on the square [-1,1] x [-1,1],
obtained using a Padua Points cubature formula of degree 2000,
is 8.5335875865430544e-001 with an estimated absolute error of
3.11e-015.
2D modification of an example by L.N.Trefethen (see ref. 7),
f(x)=exp(-1/x^2).
'''
arg_z = (x**2 + y**2)
# Avoid cases in which "arg_z=0", setting only in those instances
# "arg_z=eps".
arg_z = arg_z + (1 - np.abs(np.sign(arg_z))) * 1.e-100
arg_z = 1. / arg_z
return np.exp(-arg_z)
def __call__(self, x, y, i=0):
s = self
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.abs_cubed, s.gauss, s.exp_inv]
return test_function[i](x, y)
example_functions = _ExampleFunctions()
def _find_m(n):
ix = np.r_[1:(n + 1) * (n + 2):2]
if np.mod(n, 2) == 0:
n2 = n // 2
offset = np.array([[0, 1] * n2 + [0, ]] * (n2 + 1))
ix = ix - offset.ravel(order='F')
return ix
def padua_points(n, domain=(-1, 1, -1, 1)):
''' Return Padua points
Parameters
----------
n : scalar integer
interpolation degree
domain : vector [a,b,c,d]
defining the rectangle [a,b] x [c,d]. (default domain = (-1,1,-1,1))
Returns
-------
pad : array of shape (2 x (n+1)*(n+2)/2) such that
(pad[0,:], pad[1,: ]) defines the Padua points in the domain
rectangle [a,b] x [c,d].
or
X1,Y1,X2,Y2 : arrays
Two subgrids X1,Y1 and X2,Y2 defining the Padua points
-------------------------------------------------------------------------------
'''
a, b, c, d = domain
t0 = [np.pi] if n == 0 else np.linspace(0, np.pi, n + 1)
t1 = np.linspace(0, np.pi, n + 2)
zn = map_to_interval(np.cos(t0), a, b)
zn1 = map_to_interval(np.cos(t1), c, d)
Pad1, Pad2 = np.meshgrid(zn, zn1)
ix = _find_m(n)
return np.vstack((Pad1.ravel(order='F')[ix],
Pad2.ravel(order='F')[ix]))
def error_estimate(C0f):
''' Return interpolation error estimate from Padua coefficients
'''
n = C0f.shape[1]
C0f2 = np.fliplr(C0f)
errest = sum(np.abs(np.diag(C0f2)))
if (n >= 1):
errest = errest + sum(np.abs(np.diag(C0f2, -1)))
if (n >= 2):
errest = errest + sum(np.abs(np.diag(C0f2, -2)))
return 2 * errest
def padua_fit(Pad, fun, *args):
'''
Computes the Chebyshevs coefficients
so that f(x, y) can be approximated by:
f(x, y) = sum cjk*Tjk(x, y)
Parameters
----------
Pad : array-like
Padua points, as computed with padua_points function.
fun : function to be interpolated in the form
fun(x, y, *args), where *args are optional arguments for fun.
Returns
-------
coefficents: coefficient matrix
abs_err : interpolation error estimate
Example
------
>>> import numpy as np
>>> import wafo.padua as wp
>>> domain = [0, 1, 0, 1]
>>> a, b, c, d = domain
>>> points = wp.padua_points(21, domain)
>>> C0f, abs_error = wp.padua_fit(points, wp.example_functions.franke)
>>> x1 = np.linspace(a, b, 100)
>>> x2 = np.linspace(c, d, 101)
>>> val = wp.padua_val(x1, x2, C0f, domain, use_meshgrid=True)
>>> X1, X2 = np.meshgrid(x1, x2)
>>> true_val = wp.example_functions.franke(X1, X2)
>>> np.allclose(val, true_val, atol=10*abs_error)
True
>>> np.allclose(np.abs(val-true_val).max(), 0.0073174614275738296)
True
>>> np.allclose(abs_error, 0.0022486904061664046)
True
import matplotlib.pyplot as plt
plt.contour(x1, x2, val)
'''
N = np.shape(Pad)[1]
# recover the degree n from N = (n+1)(n+2)/2
n = int(round(-3 + np.sqrt(1 + 8 * N)) / 2)
C0f = fun(Pad[0], Pad[1], *args)
if (n > 0):
ix = _find_m(n)
GfT = np.zeros((n + 2) * (n + 1))
GfT[ix] = C0f * 2 / (n * (n + 1))
GfT = GfT.reshape(n + 1, n + 2)
GfT = GfT.T
GfT[0] = GfT[0] / 2
GfT[n + 1] = GfT[n + 1] / 2
GfT[:, 0] = GfT[:, 0] / 2
GfT[:, n] = GfT[:, n] / 2
Gf = GfT.T
# compute the interpolation coefficient matrix C0f by FFT
Gfhat = np.real(fft(Gf, 2 * n, axis=0))
Gfhathat = np.real(fft(Gfhat[:n + 1, :], 2 * (n + 1), axis=1))
C0f = 2 * Gfhathat[:, 0:n + 1]
C0f[0] = C0f[0, :] / np.sqrt(2)
C0f[:, 0] = C0f[:, 0] / np.sqrt(2)
C0f = np.fliplr(np.triu(np.fliplr(C0f)))
C0f[n] = C0f[n] / 2
return C0f, error_estimate(C0f)
def paduavals2coefs(f):
m = len(f)
n = int(round(-1.5 + np.sqrt(.25 + 2 * m)))
x = padua_points(n)
idx = _find_m(n)
w = 0 * x[0] + 1. / (n * (n + 1))
idx1 = np.all(np.abs(x) == 1, axis=0)
w[idx1] = .5 * w[idx1]
idx2 = np.all(np.abs(x) != 1, axis=0)
w[idx2] = 2 * w[idx2]
G = np.zeros(idx.max() + 1)
G[idx] = 4 * w * f
use_dct = 100 < n
if use_dct:
C = np.rot90(dct(dct(G.T).T)) # , axis=1)
else:
t1 = np.r_[0:n + 1].reshape(-1, 1)
Tn1 = np.cos(t1 * t1.T * np.pi / n)
t2 = np.r_[0:n + 2].reshape(-1, 1)
Tn2 = np.cos(t2 * t2.T * np.pi / (n + 1))
C = np.dot(Tn2, np.dot(G, Tn1))
C[0] = .5 * C[0]
C[:, 1] = .5 * C[:, 1]
C[0, -1] = .5 * C[0, -1]
del C[-1]
# Take upper-left triangular part:
return np.fliplr(np.triu(np.fliplr(C)))
# C = triu(C(:,end:-1:1));
# C = C(:,end:-1:1);
# TODO: padua_fit2 does not work correctly yet.
def padua_fit2(Pad, fun, *args):
# N = np.shape(Pad)[1]
# recover the degree n from N = (n+1)(n+2)/2
# _n = int(round(-3 + np.sqrt(1 + 8 * N)) / 2)
C0f = fun(Pad[0], Pad[1], *args)
return paduavals2coefs(C0f)
def _compute_moments(n):
k = np.r_[0:n:2]
mom = 2 * np.sqrt(2) / (1 - k ** 2)
mom[0] = 2
return mom
def padua_cubature(coefficients, domain=(-1, 1, -1, 1)):
'''
Compute the integral through the coefficient matrix.
'''
n = coefficients.shape[1]
mom = _compute_moments(n)
M1, M2 = np.meshgrid(mom, mom)
M = M1 * M2
C0fM = coefficients[0:n:2, 0:n:2] * M
a, b, c, d = domain
integral = (b - a) * (d - c) * C0fM.sum() / 4
return integral
def padua_val(X, Y, coefficients, domain=(-1, 1, -1, 1), use_meshgrid=False):
'''
Evaluate polynomial in padua form at X, Y.
Evaluate the interpolation polynomial defined through its coefficient
matrix coefficients at the target points X(:,1),X(:,2) or at the
meshgrid(X1,X2)
Parameters
----------
X, Y: array-like
evaluation points.
coefficients : array-like
coefficient matrix
domain : a vector [a,b,c,d]
defining the rectangle [a,b] x [c,d]
use_meshgrid: bool
If True interpolate at the points meshgrid(X, Y)
Returns
-------
fxy : array-like
evaluation of the interpolation polynomial at the target points
'''
def transform(tn, x, a, b):
xn = map_from_interval(x, a, b).clip(min=-1, max=1).reshape(1, -1)
tx = np.cos(tn * np.arccos(xn)) * np.sqrt(2)
tx[0] = 1
return tx
X, Y = np.atleast_1d(X, Y)
original_shape = X.shape
a, b, c, d = domain
n = np.shape(coefficients)[1]
tn = np.r_[0:n][:, None]
tx1 = transform(tn, X.ravel(), a, b)
tx2 = transform(tn, Y.ravel(), c, d)
if use_meshgrid: # eval on meshgrid points
return np.dot(tx1.T, np.dot(coefficients, tx2)).T
# scattered points
val = np.sum(np.dot(tx1.T, coefficients) * tx2.T, axis=1)
return val.reshape(original_shape)
if __name__ == '__main__':
from wafo.testing import test_docstrings
test_docstrings(__file__)

@ -1,18 +0,0 @@
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 25 14:55:34 2015
@author: dave
"""
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('wafo', parent_package, top_path)
config.add_subpackage('source')
config.make_config_py()
return config
if __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())

@ -1,268 +0,0 @@
'''
Created on 13. mar. 2018
@author: pab
'''
import numpy as np
from numpy import pi, sqrt
import wafo.transform.estimation as te
import wafo.transform as wt
from wafo.containers import PlotData
from wafo.kdetools.kernels import qlevels
from wafo.misc import tranproc
import warnings
def _set_default_t_h_g(t, h, g, m0, m2):
if g is None:
y = np.linspace(-5, 5)
x = sqrt(m0) * y + 0
g = wt.TrData(y, x)
if t is None:
tt1 = 2 * pi * sqrt(m0 / m2)
t = np.linspace(0, 1.7 * tt1, 51)
if h is None:
px = g.gauss2dat([0, 4.])
px = abs(px[1] - px[0])
h = np.linspace(0, 1.3 * px, 41)
return h, t, g
def lh83pdf(t=None, h=None, mom=None, g=None):
"""
LH83PDF Longuet-Higgins (1983) approximation of the density (Tc,Ac)
in a stationary Gaussian transform process X(t) where
Y(t) = g(X(t)) (Y zero-mean Gaussian, X non-Gaussian).
CALL: f = lh83pdf(t,h,[m0,m1,m2],g);
f = density of wave characteristics of half-wavelength
in a stationary Gaussian transformed process X(t),
where Y(t) = g(X(t)) (Y zero-mean Gaussian)
t,h = vectors of periods and amplitudes, respectively.
default depending on the spectral moments
m0,m1,m2 = the 0'th,1'st and 2'nd moment of the spectral density
with angular frequency.
g = space transformation, Y(t)=g(X(t)), default: g is identity
transformation, i.e. X(t) = Y(t) is Gaussian,
The transformation, g, can be estimated using lc2tr
or dat2tr or given apriori by ochi.
Example
-------
>>> import wafo.spectrum.models as sm
>>> Sj = sm.Jonswap()
>>> w = np.linspace(0,4,256)
>>> S = Sj.tospecdata(w) #Make spectrum object from numerical values
>>> S = sm.SpecData1D(Sj(w),w) # Alternatively do it manually
>>> mom, mom_txt = S.moment(nr=2, even=False)
>>> f = lh83pdf(mom=mom)
>>> f.plot()
See also
--------
cav76pdf, lc2tr, dat2tr
References
----------
Longuet-Higgins, M.S. (1983)
"On the joint distribution wave periods and amplitudes in a
random wave field", Proc. R. Soc. A389, pp 24--258
Longuet-Higgins, M.S. (1975)
"On the joint distribution wave periods and amplitudes of sea waves",
J. geophys. Res. 80, pp 2688--2694
"""
# tested on: matlab 5.3
# History:
# Revised pab 01.04.2001
# - Added example
# - Better automatic scaling for h,t
# revised by IR 18.06.2000, fixing transformation and transposing t and h to fit simpson req.
# revised by pab 28.09.1999
# made more efficient calculation of f
# by Igor Rychlik
m0, m1, m2 = mom
h, t, g = _set_default_t_h_g(t, h, g, m0, m2)
L0 = m0
L1 = m1 / (2 * pi)
L2 = m2 / (2 * pi)**2
eps2 = sqrt((L2 * L0) / (L1**2) - 1)
if np.any(~np.isreal(eps2)):
raise ValueError('input moments are not correct')
const = 4 / sqrt(pi) / eps2 / (1 + 1 / sqrt(1 + eps2**2))
a = len(h)
b = len(t)
der = np.ones((a, 1))
h_lh = g.dat2gauss(h.ravel(), der.ravel())
der = abs(h_lh[1]) # abs(h_lh[:, 1])
h_lh = h_lh[0]
# Normalization + transformation of t and h ???????
# Without any transformation
t_lh = t / (L0 / L1)
#h_lh = h_lh/sqrt(2*L0)
h_lh = h_lh / sqrt(2)
t_lh = 2 * t_lh
# Computation of the distribution
T, H = np.meshgrid(t_lh[1:b], h_lh)
f_th = np.zeros((a, b))
tmp = const * der[:, None] * (H / T)**2 * np.exp(-H**2. *
(1 + ((1 - 1. / T) / eps2)**2)) / ((L0 / L1) * sqrt(2) / 2)
f_th[:, 1:b] = tmp
f = PlotData(f_th, (t, h),
xlab='Tc', ylab='Ac',
title='Joint density of (Tc,Ac) - Longuet-Higgins (1983)',
plot_kwds=dict(plotflag=1))
return _add_contour_levels(f)
def cav76pdf(t=None, h=None, mom=None, g=None):
"""
CAV76PDF Cavanie et al. (1976) approximation of the density (Tc,Ac)
in a stationary Gaussian transform process X(t) where
Y(t) = g(X(t)) (Y zero-mean Gaussian, X non-Gaussian).
CALL: f = cav76pdf(t,h,[m0,m2,m4],g);
f = density of wave characteristics of half-wavelength
in a stationary Gaussian transformed process X(t),
where Y(t) = g(X(t)) (Y zero-mean Gaussian)
t,h = vectors of periods and amplitudes, respectively.
default depending on the spectral moments
m0,m2,m4 = the 0'th, 2'nd and 4'th moment of the spectral density
with angular frequency.
g = space transformation, Y(t)=g(X(t)), default: g is identity
transformation, i.e. X(t) = Y(t) is Gaussian,
The transformation, g, can be estimated using lc2tr
or dat2tr or given a priori by ochi.
[] = default values are used.
Example
-------
>>> import wafo.spectrum.models as sm
>>> Sj = sm.Jonswap()
>>> w = np.linspace(0,4,256)
>>> S = Sj.tospecdata(w) #Make spectrum object from numerical values
>>> S = sm.SpecData1D(Sj(w),w) # Alternatively do it manually
>>> mom, mom_txt = S.moment(nr=4, even=True)
>>> f = cav76pdf(mom=mom)
>>> f.plot()
See also
--------
lh83pdf, lc2tr, dat2tr
References
----------
Cavanie, A., Arhan, M. and Ezraty, R. (1976)
"A statistical relationship between individual heights and periods of
storm waves".
In Proceedings Conference on Behaviour of Offshore Structures,
Trondheim, pp. 354--360
Norwegian Institute of Technology, Trondheim, Norway
Lindgren, G. and Rychlik, I. (1982)
Wave Characteristics Distributions for Gaussian Waves --
Wave-lenght, Amplitude and Steepness, Ocean Engng vol 9, pp. 411-432.
"""
# tested on: matlab 5.3 NB! note
# History:
# revised pab 04.11.2000
# - fixed xlabels i.e. f.labx={'Tc','Ac'}
# revised by IR 4 X 2000. fixed transform and normalisation
# using Lindgren & Rychlik (1982) paper.
# At the end of the function there is a text with derivation of the density.
#
# revised by jr 21.02.2000
# - Introduced cell array for f.x for use with pdfplot
# by pab 28.09.1999
m0, m2, m4 = mom
h, t, g = _set_default_t_h_g(t, h, g, m0, m2)
eps4 = 1.0 - m2**2 / (m0 * m4)
alfa = m2 / sqrt(m0 * m4)
if np.any(~np.isreal(eps4)):
raise ValueError('input moments are not correct')
a = len(h)
b = len(t)
der = np.ones((a, 1))
h_lh = g.dat2gauss(h.ravel(), der.ravel())
der = abs(h_lh[1])
h_lh = h_lh[0]
# Normalization + transformation of t and h
pos = 2 / (1 + alfa) # inverse of a fraction of positive maxima
cons = 2 * pi**4 * pos / sqrt(2 * pi) / m4 / sqrt((1 - alfa**2))
# Tm=2*pi*sqrt(m0/m2)/alpha; #mean period between positive maxima
t_lh = t
h_lh = sqrt(m0) * h_lh
# Computation of the distribution
T, H = np.meshgrid(t_lh[1:b], h_lh)
f_th = np.zeros((a, b))
f_th[:, 1:b] = cons * der[:, None] * (H**2 / (T**5)) * np.exp(-0.5 * (
H / T**2)**2. * ((T**2 - pi**2 * m2 / m4)**2 / (m0 * (1 - alfa**2)) + pi**4 / m4))
f = PlotData(f_th, (t, h),
xlab='Tc', ylab='Ac',
title='Joint density of (Tc,Ac) - Cavanie et al. (1976)',
plot_kwds=dict(plotflag=1))
return _add_contour_levels(f)
def _add_contour_levels(f):
p_levels = np.r_[10:90:20, 95, 99, 99.9]
try:
c_levels = qlevels(f.data, p=p_levels)
f.clevels = c_levels
f.plevels = p_levels
except ValueError as e:
msg = "Could not calculate contour levels!. ({})".format(str(e))
warnings.warn(msg)
return f
# Let U,Z be the height and second derivative (curvature) at a local maximum in a Gaussian proces
# with spectral moments m0,m2,m4. The conditional density ($U>0$) has the following form
#$$
# f(z,u)=c \frac{1}{\sqrt{2\pi}}\frac{1}{\sqrt{m0(1-\alpha^2)}}\exp(-0.5\left(\frac{u-z(m2/m4)}
# {\sqrt{m0(1-\alpha^2)}}\right)^2)\frac{|z|}{m4}\exp(-0.5z^2/m4), \quad z<0,
#$$
# where $c=2/(1+\alpha)$, $\alpha=m2/\sqrt{m0\cdot m4}$.
#
# The cavanie approximation is based on the model $X(t)=U \cos(\pi t/T)$, consequently
# we have $U=H$ and by twice differentiation $Z=-U(\pi^2/T)^2\cos(0)$. The variable change has Jacobian
# $2\pi^2 H/T^3$ giving the final formula for the density of $T,H$
#$$
# f(t,h)=c \frac{2\pi^4}{\sqrt{2\pi}}\frac{1}{m4\sqrt{m0(1-\alpha^2)}}\frac{h^2}{t^5}
# \exp(-0.5\frac{h^2}{t^4}\left(\left(\frac{t^2-\pi^2(m2/m4)}
# {\sqrt{m0(1-\alpha^2)}}\right)^2+\frac{\pi^4}{m4}\right)).
#$$
#
#
def test_docstrings():
import doctest
print('Testing docstrings in %s' % __file__)
doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
if __name__ == '__main__':
test_docstrings()

@ -1,258 +0,0 @@
from __future__ import division
from numpy import round
from threading import Thread
from time import sleep
from win32gui import (InitCommonControls, CallWindowProc, CreateWindowEx,
CreateWindow, SetWindowLong, SendMessage, ShowWindow,
PumpWaitingMessages, PostQuitMessage, DestroyWindow,
MessageBox, EnumWindows, GetClassName)
from win32api import GetModuleHandle, GetSystemMetrics # @UnresolvedImport
from win32api import SetWindowLong as api_SetWindowLong # @UnresolvedImport
from commctrl import (TOOLTIPS_CLASS, TTM_GETDELAYTIME, TTM_SETDELAYTIME,
TTDT_INITIAL, TTDT_AUTOPOP)
import win32con
WM_USER = win32con.WM_USER
PBM_SETRANGE = (WM_USER + 1)
PBM_SETPOS = (WM_USER + 2)
PBM_DELTAPOS = (WM_USER + 3)
PBM_SETSTEP = (WM_USER + 4)
PBM_STEPIT = (WM_USER + 5)
PBM_SETRANGE32 = (WM_USER + 6)
PBM_GETRANGE = (WM_USER + 7)
PBM_GETPOS = (WM_USER + 8)
PBM_SETBARCOLOR = (WM_USER + 9)
PBM_SETMARQUEE = (WM_USER + 10)
PBM_GETSTEP = (WM_USER + 13)
PBM_GETBKCOLOR = (WM_USER + 14)
PBM_GETBARCOLOR = (WM_USER + 15)
PBM_SETSTATE = (WM_USER + 16)
PBM_GETSTATE = (WM_USER + 17)
PBS_SMOOTH = 0x01
PBS_VERTICAL = 0x04
PBS_MARQUEE = 0x08
PBS_SMOOTHREVERSE = 0x10
PBST_NORMAL = 1
PBST_ERROR = 2
PBST_PAUSED = 3
WC_DIALOG = 32770
WM_SETTEXT = win32con.WM_SETTEXT
def MAKELPARAM(a, b):
return (a & 0xffff) | ((b & 0xffff) << 16)
def _get_tooltip_handles(hwnd, resultList):
'''
Adds a window handle to resultList if its class-name is 'tooltips_class32',
i.e. the window is a tooltip.
'''
if GetClassName(hwnd) == TOOLTIPS_CLASS:
resultList.append(hwnd)
def set_max_pop_delay_on_tooltip(tooltip):
'''
Sets maximum auto-pop delay (delay before hiding) on an instance of
wx.ToolTip.
NOTE: The tooltip's SetDelay method is used just to identify the correct
tooltip.
'''
test_value = 12345
# Set initial delay just to identify tooltip.
tooltip.SetDelay(test_value)
handles = []
EnumWindows(_get_tooltip_handles, handles)
for hwnd in handles:
if SendMessage(hwnd, TTM_GETDELAYTIME, TTDT_INITIAL) == test_value:
SendMessage(hwnd, TTM_SETDELAYTIME, TTDT_AUTOPOP, 32767)
tooltip.SetDelay(500) # Restore default value
class Waitbar(Thread):
def __init__(self, title='Waitbar', can_abort=True, max_val=100):
Thread.__init__(self) # Initialize thread
self.title = title
self.can_abort = can_abort
self.max_val = max_val
InitCommonControls()
self.hinst = GetModuleHandle(None)
self.started = False
self.position = 0
self.do_update = False
self.start() # Run the thread
while not self.started:
sleep(0.1) # Wait until the dialog is ready
def DlgProc(self, hwnd, uMsg, wParam, lParam):
if uMsg == win32con.WM_DESTROY:
api_SetWindowLong(self.dialog,
win32con.GWL_WNDPROC,
self.oldWndProc)
if uMsg == win32con.WM_CLOSE:
self.started = False
if uMsg == win32con.WM_COMMAND and self.can_abort:
self.started = False
return CallWindowProc(self.oldWndProc, hwnd, uMsg, wParam, lParam)
def BuildWindow(self):
width = 400
height = 100
self.dialog = CreateWindowEx(
win32con.WS_EX_TOPMOST,
WC_DIALOG,
self.title + ' (0%)',
win32con.WS_VISIBLE | win32con.WS_OVERLAPPEDWINDOW,
int(round(
GetSystemMetrics(win32con.SM_CXSCREEN) * .5 - width * .5)),
int(round(
GetSystemMetrics(win32con.SM_CYSCREEN) * .5 - height * .5)),
width,
height,
0,
0,
self.hinst,
None)
self.progbar = CreateWindow(
# win32con.WS_EX_DLGMODALFRAME,
'msctls_progress32',
'',
win32con.WS_VISIBLE | win32con.WS_CHILD,
10,
10,
width - 30,
20,
self.dialog,
0,
0,
None)
if self.can_abort:
self.button = CreateWindow(
# win32con.WS_EX_DLGMODALFRAME,
'BUTTON',
'Cancel',
win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.BS_PUSHBUTTON, # @IgnorePep8
int(width / 2.75),
40,
100,
20,
self.dialog,
0,
0,
None)
self.oldWndProc = SetWindowLong(
self.dialog,
win32con.GWL_WNDPROC,
self.DlgProc)
SendMessage(self.progbar, PBM_SETRANGE, 0, MAKELPARAM(0, self.max_val))
# win32gui.SendMessage(self.progbar, PBM_SETSTEP, 0, 10)
# win32gui.SendMessage(self.progbar, PBM_SETMARQUEE, 0, 0)
ShowWindow(self.progbar, win32con.SW_SHOW)
def run(self):
self.BuildWindow()
self.started = True
while self.started:
PumpWaitingMessages()
if self.do_update:
SendMessage(self.progbar, PBM_SETPOS,
int(self.position % self.max_val), 0)
percentage = int(round(100.0 * self.position / self.max_val))
SendMessage(self.dialog, WM_SETTEXT, 0,
self.title + ' (%d%%)' % percentage)
# SendMessage(self.progbar, PBM_STEPIT, 0, 0)
self.do_update = False
sleep(0.1)
PostQuitMessage(0)
DestroyWindow(self.dialog)
def update(self, pos):
if self.started:
if not self.do_update:
self.position = pos
self.do_update = True
return True
return False
def close(self):
self.started = False
# class Waitbar2(Dialog, Thread):
# def __init__(self, title='Waitbar'):
# template = [[title, (0, 0, 215, 36),
# (win32con.DS_MODALFRAME | win32con.WS_POPUP |
# win32con.WS_VISIBLE | win32con.WS_CAPTION |
# win32con.WS_SYSMENU | win32con.DS_SETFONT |
# win32con.WS_GROUP | win32con.WS_EX_TOPMOST),
# | win32con.DS_SYSMODAL),
# None, (8, "MS Sans Serif")], ]
# Dialog.__init__(self, id=template)
# Thread.__init__(self) # Initialize thread
# self.started = False
# self.start() # Run the thread
# while not self.started:
# sleep(0.1) # Wait until the dialog is ready
#
# def OnInitDialog(self):
# rc = Dialog.OnInitDialog(self)
# self.pbar = CreateProgressCtrl()
# self.pbar.CreateWindow (win32con.WS_CHILD | win32con.WS_VISIBLE,
# (10, 10, 310, 24), self, 1001)
# self.started = True
# return rc
#
# def run(self):
# self.DoModal()
#
# def update(self, pos):
# self.pbar.SetPos(int(pos))
#
# def close(self):
# self.OnCancel()
class WarnDlg(Thread):
def __init__(self, message='', title='Warning!'):
Thread.__init__(self) # Initialize thread
self.title = title
self.message = message
self.start() # Run the thread
def run(self):
# MessageBox(self.message, self.title, win32con.MB_ICONWARNING)
MessageBox(0, self.message, self.title,
win32con.MB_ICONWARNING | win32con.MB_SYSTEMMODAL)
class ErrorDlg(Thread):
def __init__(self, message='', title='Error!', blocking=False):
Thread.__init__(self) # Initialize thread
self.title = title
self.message = message
if blocking:
self.run() # Run without threading
else:
self.start() # Run in thread
def run(self):
# MessageBox(self.message, self.title, win32con.MB_ICONERROR)
MessageBox(0, self.message, self.title,
win32con.MB_ICONERROR | win32con.MB_SYSTEMMODAL)
if __name__ == '__main__':
WarnDlg('This is an example of a warning', 'Warning!')
ErrorDlg('This is an example of an error message')
wb = Waitbar('Waitbar example')
# wb2 = Waitbar2('Waitbar example')
for i in range(20):
print(wb.update(i * 5))
# wb2.update(i)
sleep(0.1)
wb.close()
# wb2.close()
Loading…
Cancel
Save