pep8 + updated wafo.stats packages
parent
629ed411c9
commit
d308357c5b
@ -1,26 +1,27 @@
|
|||||||
|
from __future__ import division, print_function, absolute_import
|
||||||
|
|
||||||
from info import __doc__
|
from .info import __doc__
|
||||||
import misc
|
from . import misc
|
||||||
import data
|
from . import data
|
||||||
import demos
|
from . import demos
|
||||||
import kdetools
|
from . import kdetools
|
||||||
import objects
|
from . import objects
|
||||||
import spectrum
|
from . import spectrum
|
||||||
import transform
|
from . import transform
|
||||||
import definitions
|
from . import definitions
|
||||||
import polynomial
|
from . import polynomial
|
||||||
import stats
|
from . import stats
|
||||||
import interpolate
|
from . import interpolate
|
||||||
import dctpack
|
from . import dctpack
|
||||||
try:
|
try:
|
||||||
import fig
|
from . import fig
|
||||||
except ImportError:
|
except ImportError:
|
||||||
print 'fig import only supported on Windows'
|
print('fig import only supported on Windows')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from wafo.version import version as __version__
|
from wafo.version import version as __version__
|
||||||
except ImportError:
|
except ImportError:
|
||||||
__version__='nobuilt'
|
__version__ = 'nobuilt'
|
||||||
|
|
||||||
from numpy.testing import Tester
|
from numpy.testing import Tester
|
||||||
test = Tester().test
|
test = Tester().test
|
@ -1,98 +1,104 @@
|
|||||||
'''
|
'''
|
||||||
Module extending the bitoperator capabilites of numpy
|
Module extending the bitoperator capabilites of numpy
|
||||||
'''
|
'''
|
||||||
|
|
||||||
from numpy import (bitwise_and, bitwise_or, #@UnresolvedImport
|
from numpy import (bitwise_and, bitwise_or,
|
||||||
bitwise_not, binary_repr, #@UnresolvedImport @UnusedImport
|
bitwise_not, binary_repr, # @UnusedImport
|
||||||
bitwise_xor, where, arange) #@UnresolvedImport @UnusedImport
|
bitwise_xor, where, arange) # @UnusedImport
|
||||||
#import numpy as np
|
__all__ = ['bitwise_and', 'bitwise_or', 'bitwise_not', 'binary_repr',
|
||||||
__all__ = ['bitwise_and', 'bitwise_or', 'bitwise_not', 'binary_repr',
|
'bitwise_xor', 'getbit', 'setbit', 'getbits', 'setbits']
|
||||||
'bitwise_xor', 'getbit', 'setbit', 'getbits', 'setbits']
|
|
||||||
|
|
||||||
def getbit(i, bit):
|
def getbit(i, bit):
|
||||||
"""
|
"""
|
||||||
Get bit at specified position
|
Get bit at specified position
|
||||||
|
|
||||||
Parameters
|
Parameters
|
||||||
----------
|
----------
|
||||||
i : array-like of uints, longs
|
i : array-like of uints, longs
|
||||||
value to
|
value to
|
||||||
bit : array-like of ints or longs
|
bit : array-like of ints or longs
|
||||||
bit position between 0 and the number of bits in the uint class.
|
bit position between 0 and the number of bits in the uint class.
|
||||||
|
|
||||||
Examples
|
Examples
|
||||||
--------
|
--------
|
||||||
>>> import numpy as np
|
>>> import numpy as np
|
||||||
>>> binary_repr(13)
|
>>> binary_repr(13)
|
||||||
'1101'
|
'1101'
|
||||||
>>> getbit(13,np.arange(3,-1,-1))
|
>>> getbit(13,np.arange(3,-1,-1))
|
||||||
array([1, 1, 0, 1])
|
array([1, 1, 0, 1])
|
||||||
>>> getbit(5, np.r_[0:4])
|
>>> getbit(5, np.r_[0:4])
|
||||||
array([1, 0, 1, 0])
|
array([1, 0, 1, 0])
|
||||||
"""
|
"""
|
||||||
return bitwise_and(i, 1 << bit) >> bit
|
return bitwise_and(i, 1 << bit) >> bit
|
||||||
|
|
||||||
def getbits(i, numbits=8):
|
|
||||||
"""
|
def getbits(i, numbits=8):
|
||||||
Returns bits of i in a list
|
"""
|
||||||
"""
|
Returns bits of i in a list
|
||||||
return getbit(i, arange(0, numbits))
|
"""
|
||||||
|
return getbit(i, arange(0, numbits))
|
||||||
def setbit(i, bit, value=1):
|
|
||||||
"""
|
|
||||||
Set bit at specified position
|
def setbit(i, bit, value=1):
|
||||||
|
"""
|
||||||
Parameters
|
Set bit at specified position
|
||||||
----------
|
|
||||||
i : array-like of uints, longs
|
Parameters
|
||||||
value to
|
----------
|
||||||
bit : array-like of ints or longs
|
i : array-like of uints, longs
|
||||||
bit position between 0 and the number of bits in the uint class.
|
value to
|
||||||
value : array-like of 0 or 1
|
bit : array-like of ints or longs
|
||||||
value to set the bit to.
|
bit position between 0 and the number of bits in the uint class.
|
||||||
|
value : array-like of 0 or 1
|
||||||
Examples
|
value to set the bit to.
|
||||||
--------
|
|
||||||
Set bit fifth bit in the five bit binary binary representation of 9 (01001)
|
Examples
|
||||||
yields 25 (11001)
|
--------
|
||||||
>>> setbit(9,4)
|
Set bit fifth bit in the five bit binary binary representation of 9 (01001)
|
||||||
array(25)
|
yields 25 (11001)
|
||||||
"""
|
>>> setbit(9,4)
|
||||||
val1 = 1 << bit
|
array(25)
|
||||||
val0 = bitwise_not(val1)
|
"""
|
||||||
return where((value==0) & (i==i) & (bit==bit), bitwise_and(i, val0),
|
val1 = 1 << bit
|
||||||
bitwise_or(i, val1))
|
val0 = bitwise_not(val1)
|
||||||
|
return where((value == 0) & (i == i) & (bit == bit), bitwise_and(i, val0),
|
||||||
def setbits(bitlist):
|
bitwise_or(i, val1))
|
||||||
"""
|
|
||||||
Set bits of val to values in bitlist
|
|
||||||
|
def setbits(bitlist):
|
||||||
Example
|
"""
|
||||||
-------
|
Set bits of val to values in bitlist
|
||||||
>>> setbits([1,1])
|
|
||||||
3
|
Example
|
||||||
>>> setbits([1,0])
|
-------
|
||||||
1
|
>>> setbits([1,1])
|
||||||
"""
|
3
|
||||||
# return bitlist[7]<<7 | bitlist[6]<<6 | bitlist[5]<<5 | bitlist[4]<<4 | \
|
>>> setbits([1,0])
|
||||||
# bitlist[3]<<3 | bitlist[2]<<2 | bitlist[1]<<1 | bitlist[0]
|
1
|
||||||
val = 0
|
"""
|
||||||
for i, j in enumerate(bitlist):
|
# return bitlist[7]<<7 | bitlist[6]<<6 | bitlist[5]<<5 | bitlist[4]<<4 | \
|
||||||
val |= j << i
|
# bitlist[3]<<3 | bitlist[2]<<2 | bitlist[1]<<1 | bitlist[0]
|
||||||
return val
|
val = 0
|
||||||
|
for i, j in enumerate(bitlist):
|
||||||
def test_docstrings():
|
val |= j << i
|
||||||
import doctest
|
return val
|
||||||
doctest.testmod()
|
|
||||||
if __name__ == '__main__':
|
|
||||||
test_docstrings()
|
def test_docstrings():
|
||||||
|
import doctest
|
||||||
# t = set(np.arange(8),1,1)
|
print('Testing docstrings in %s' % __file__)
|
||||||
# t=get(0x84,np.arange(0,8))
|
doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
|
||||||
# t=getbyte(0x84)
|
|
||||||
# t=get(0x84,[0, 1, 2, 3, 4, 5, 6, 7])
|
if __name__ == '__main__':
|
||||||
# t=get(0x20, 6)
|
test_docstrings()
|
||||||
# bit = [0 for i in range(8)]
|
|
||||||
# bit[7]=1
|
# t = set(np.arange(8),1,1)
|
||||||
# t = setbits(bit)
|
# t=get(0x84,np.arange(0,8))
|
||||||
# print(hex(t))
|
# 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))
|
||||||
|
File diff suppressed because it is too large
Load Diff
@ -1,296 +1,305 @@
|
|||||||
"""
|
"""
|
||||||
WAFO defintions and numenclature
|
WAFO defintions and numenclature
|
||||||
|
|
||||||
crossings :
|
crossings :
|
||||||
cycle_pairs :
|
cycle_pairs :
|
||||||
turning_points :
|
turning_points :
|
||||||
wave_amplitudes :
|
wave_amplitudes :
|
||||||
wave_periods :
|
wave_periods :
|
||||||
waves :
|
waves :
|
||||||
|
|
||||||
Examples
|
Examples
|
||||||
--------
|
--------
|
||||||
In order to view the documentation do the following in an ipython window:
|
In order to view the documentation do the following in an ipython window:
|
||||||
|
|
||||||
>>> import wafo.definitions as wd
|
>>> import wafo.definitions as wd
|
||||||
>>> wd.crossings()
|
>>> wd.crossings()
|
||||||
|
|
||||||
or
|
or
|
||||||
>>> wd.crossings?
|
>>> wd.crossings?
|
||||||
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
def wave_amplitudes():
|
|
||||||
r"""
|
|
||||||
Wave amplitudes and heights definitions and nomenclature
|
def wave_amplitudes():
|
||||||
|
r"""
|
||||||
Definition of wave amplitudes and wave heights
|
Wave amplitudes and heights definitions and nomenclature
|
||||||
---------------------------------------------
|
|
||||||
|
Definition of wave amplitudes and wave heights
|
||||||
<----- Direction of wave propagation
|
---------------------------------------------
|
||||||
|
|
||||||
|
<----- Direction of wave propagation
|
||||||
|..............c_..........|
|
|
||||||
| /| \ |
|
|
||||||
Hd | _/ | \ | Hu
|
|..............c_..........|
|
||||||
M | / | \ |
|
| /| \ |
|
||||||
/ \ | M / Ac | \_ | c_
|
Hd | _/ | \ | Hu
|
||||||
F \ | / \m/ | \ | / \
|
M | / | \ |
|
||||||
------d----|---u------------------d---|---u----d------ level v
|
/ \ | M / Ac | \_ | c_
|
||||||
\ | /| \ | / \L
|
F \ | / \m/ | \ | / \
|
||||||
\_ | / | At \_|_/
|
------d----|---u------------------d---|---u----d------ level v
|
||||||
\|/..| t
|
\ | /| \ | / \L
|
||||||
t
|
\_ | / | At \_|_/
|
||||||
|
\|/..| t
|
||||||
Parameters
|
t
|
||||||
----------
|
|
||||||
Ac : crest amplitude
|
Parameters
|
||||||
At : trough amplitude
|
----------
|
||||||
Hd : wave height as defined for down crossing waves
|
Ac : crest amplitude
|
||||||
Hu : wave height as defined for up crossing waves
|
At : trough amplitude
|
||||||
|
Hd : wave height as defined for down crossing waves
|
||||||
See also
|
Hu : wave height as defined for up crossing waves
|
||||||
--------
|
|
||||||
waves, crossings, turning_points
|
See also
|
||||||
"""
|
--------
|
||||||
print(wave_amplitudes.__doc__)
|
waves, crossings, turning_points
|
||||||
|
"""
|
||||||
def crossings():
|
print(wave_amplitudes.__doc__)
|
||||||
r"""
|
|
||||||
Level v crossing definitions and nomenclature
|
|
||||||
|
def crossings():
|
||||||
Definition of level v crossings
|
r"""
|
||||||
-------------------------------
|
Level v crossing definitions and nomenclature
|
||||||
M
|
|
||||||
. . M M
|
Definition of level v crossings
|
||||||
. . . . . .
|
-------------------------------
|
||||||
F d . . L
|
M
|
||||||
-----------------------u-------d-------o----------------- level v
|
. . M M
|
||||||
. . . . u
|
. . . . . .
|
||||||
. m
|
F d . . L
|
||||||
m
|
-----------------------u-------d-------o----------------- level v
|
||||||
|
. . . . u
|
||||||
Let the letters 'm', 'M', 'F', 'L','d' and 'u' in the
|
. m
|
||||||
figure above denote local minimum, maximum, first value, last
|
m
|
||||||
value, down- and up-crossing, respectively. The remaining
|
|
||||||
sampled values are indicated with a '.'. Values that are identical
|
Let the letters 'm', 'M', 'F', 'L','d' and 'u' in the
|
||||||
with v, but do not cross the level is indicated with the letter 'o'.
|
figure above denote local minimum, maximum, first value, last
|
||||||
We have a level up-crossing at index, k, if
|
value, down- and up-crossing, respectively. The remaining
|
||||||
|
sampled values are indicated with a '.'. Values that are identical
|
||||||
x(k) < v and v < x(k+1)
|
with v, but do not cross the level is indicated with the letter 'o'.
|
||||||
or if
|
We have a level up-crossing at index, k, if
|
||||||
x(k) == v and v < x(k+1) and x(r) < v for some di < r <= k-1
|
|
||||||
|
x(k) < v and v < x(k+1)
|
||||||
where di is the index to the previous downcrossing.
|
or if
|
||||||
Similarly there is a level down-crossing at index, k, if
|
x(k) == v and v < x(k+1) and x(r) < v for some di < r <= k-1
|
||||||
|
|
||||||
x(k) > v and v > x(k+1)
|
where di is the index to the previous downcrossing.
|
||||||
or if
|
Similarly there is a level down-crossing at index, k, if
|
||||||
x(k) == v and v > x(k+1) and x(r) > v for some ui < r <= k-1
|
|
||||||
|
x(k) > v and v > x(k+1)
|
||||||
where ui is the index to the previous upcrossing.
|
or if
|
||||||
|
x(k) == v and v > x(k+1) and x(r) > v for some ui < r <= k-1
|
||||||
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.
|
where ui is the index to the previous upcrossing.
|
||||||
|
|
||||||
See also
|
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.
|
||||||
wave_periods, waves, turning_points, findcross, findtp
|
|
||||||
"""
|
See also
|
||||||
print(crossings.__doc__)
|
--------
|
||||||
|
wave_periods, waves, turning_points, findcross, findtp
|
||||||
def cycle_pairs():
|
"""
|
||||||
r"""
|
print(crossings.__doc__)
|
||||||
Cycle pairs definitions and numenclature
|
|
||||||
|
|
||||||
Definition of Max2min and min2Max cycle pair
|
def cycle_pairs():
|
||||||
--------------------------------------------
|
r"""
|
||||||
A min2Max cycle pair (mM) is defined as the pair of a minimum
|
Cycle pairs definitions and numenclature
|
||||||
and the following Maximum. Similarly a Max2min cycle pair (Mm)
|
|
||||||
is defined as the pair of a Maximum and the following minimum.
|
Definition of Max2min and min2Max cycle pair
|
||||||
(all turning points possibly rainflowfiltered before pairing into cycles.)
|
--------------------------------------------
|
||||||
|
A min2Max cycle pair (mM) is defined as the pair of a minimum
|
||||||
See also
|
and the following Maximum. Similarly a Max2min cycle pair (Mm)
|
||||||
--------
|
is defined as the pair of a Maximum and the following minimum.
|
||||||
turning_points
|
(all turning points possibly rainflowfiltered before pairing into cycles.)
|
||||||
"""
|
|
||||||
print(cycle_pairs.__doc__)
|
See also
|
||||||
|
--------
|
||||||
def wave_periods():
|
turning_points
|
||||||
r"""
|
"""
|
||||||
Wave periods (lengths) definitions and nomenclature
|
print(cycle_pairs.__doc__)
|
||||||
|
|
||||||
Definition of wave periods (lengths)
|
|
||||||
------------------------------------
|
def wave_periods():
|
||||||
|
r"""
|
||||||
|
Wave periods (lengths) definitions and nomenclature
|
||||||
<----- Direction of wave propagation
|
|
||||||
|
Definition of wave periods (lengths)
|
||||||
<-------Tu--------->
|
------------------------------------
|
||||||
: :
|
|
||||||
<---Tc-----> :
|
|
||||||
: : : <------Tcc---->
|
<----- Direction of wave propagation
|
||||||
M : c : : : :
|
|
||||||
/ \ : M / \_ : : c_ c
|
<-------Tu--------->
|
||||||
F \ :/ \m/ \: :/ \ / \
|
: :
|
||||||
------d--------u----------d-------u----d--------u---d-------- level v
|
<---Tc-----> :
|
||||||
\ / \ / :\_ _/: :\_ L
|
: : : <------Tcc---->
|
||||||
\_ / \_t_/ : \t_/ : : \m/
|
M : c : : : :
|
||||||
\t/ : : : :
|
/ \ : M / \_ : : c_ c
|
||||||
: : <---Tt---> :
|
F \ :/ \m/ \: :/ \ / \
|
||||||
<--------Ttt-------> : :
|
------d--------u----------d-------u----d--------u---d-------- level v
|
||||||
<-----Td----->
|
\ / \ / :\_ _/: :\_ L
|
||||||
Tu = Up crossing period
|
\_ / \_t_/ : \t_/ : : \m/
|
||||||
Td = Down crossing period
|
\t/ : : : :
|
||||||
Tc = Crest period, i.e., period between up crossing and
|
: : <---Tt---> :
|
||||||
the next down crossing
|
<--------Ttt-------> : :
|
||||||
Tt = Trough period, i.e., period between down crossing and
|
<-----Td----->
|
||||||
the next up crossing
|
Tu = Up crossing period
|
||||||
Ttt = Trough2trough period
|
Td = Down crossing period
|
||||||
Tcc = Crest2crest 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
|
||||||
<----- Direction of wave propagation
|
the next up crossing
|
||||||
|
Ttt = Trough2trough period
|
||||||
<--Tcf-> Tuc
|
Tcc = Crest2crest period
|
||||||
: : <-Tcb-> <->
|
|
||||||
M : c : : : :
|
|
||||||
/ \ : M / \_ c_ : : c
|
<----- Direction of wave propagation
|
||||||
F \ :/ \m/ \ / \___: :/ \
|
|
||||||
------d---------u----------d---------u-------d--------u---d------ level v
|
<--Tcf-> Tuc
|
||||||
:\_ / \ __/: \_ _/ \_ L
|
: : <-Tcb-> <->
|
||||||
: \_ / \_t_/ : \t_/ \m/
|
M : c : : : :
|
||||||
: \t/ : :
|
/ \ : M / \_ c_ : : c
|
||||||
: : : :
|
F \ :/ \m/ \ / \___: :/ \
|
||||||
<-Ttf-> <-Ttb->
|
------d---------u----------d---------u-------d--------u---d------ level v
|
||||||
|
:\_ / \ __/: \_ _/ \_ L
|
||||||
|
: \_ / \_t_/ : \t_/ \m/
|
||||||
Tcf = Crest front period, i.e., period between up crossing and crest
|
: \t/ : :
|
||||||
Tcb = Crest back period, i.e., period between crest and down crossing
|
: : : :
|
||||||
Ttf = Trough front period, i.e., period between down crossing and trough
|
<-Ttf-> <-Ttb->
|
||||||
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
|
Tcf = Crest front period, i.e., period between up crossing and crest
|
||||||
to all the other wave periods and wave lengths.
|
Tcb = Crest back period, i.e., period between crest and down crossing
|
||||||
|
Ttf = Trough front period, i.e., period between down crossing and trough
|
||||||
(The nomenclature for wave length is similar, just substitute T and
|
Ttb = Trough back period, i.e., period between trough and up crossing
|
||||||
period with L and length, respectively)
|
Also note that Tcf and Ttf can also be abbreviated by their crossing
|
||||||
|
marker, e.g. Tuc (u2c) and Tdt (d2t), respectively. Similar applies
|
||||||
<----- Direction of wave propagation
|
to all the other wave periods and wave lengths.
|
||||||
|
|
||||||
<--TMm-->
|
(The nomenclature for wave length is similar, just substitute T and
|
||||||
<-TmM-> : :
|
period with L and length, respectively)
|
||||||
M : : M :
|
|
||||||
/ \ : M /:\_ : M_ M
|
<----- Direction of wave propagation
|
||||||
F \ : / \m/ : \ : /: \ / \
|
|
||||||
\ : / : \ : / : \ / \
|
<--TMm-->
|
||||||
\ : / : \ : / : \_ _/ \_ L
|
<-TmM-> : :
|
||||||
\_ : / : \_m_/ : \m_/ \m/
|
M : : M :
|
||||||
\m/ : : : :
|
/ \ : M /:\_ : M_ M
|
||||||
<-----TMM-----> <----Tmm----->
|
F \ : / \m/ : \ : /: \ / \
|
||||||
|
\ : / : \ : / : \ / \
|
||||||
|
\ : / : \ : / : \_ _/ \_ L
|
||||||
TmM = Period between minimum and the following Maximum
|
\_ : / : \_m_/ : \m_/ \m/
|
||||||
TMm = Period between Maximum and the following minimum
|
\m/ : : : :
|
||||||
TMM = Period between Maximum and the following Maximum
|
<-----TMM-----> <----Tmm----->
|
||||||
Tmm = Period between minimum and the following minimum
|
|
||||||
|
|
||||||
See also
|
TmM = Period between minimum and the following Maximum
|
||||||
--------
|
TMm = Period between Maximum and the following minimum
|
||||||
waves,
|
TMM = Period between Maximum and the following Maximum
|
||||||
wave_amplitudes,
|
Tmm = Period between minimum and the following minimum
|
||||||
crossings,
|
|
||||||
turning_points
|
See also
|
||||||
"""
|
--------
|
||||||
print(wave_periods.__doc__)
|
waves,
|
||||||
def turning_points():
|
wave_amplitudes,
|
||||||
r"""
|
crossings,
|
||||||
Turning points definitions and numenclature
|
turning_points
|
||||||
|
"""
|
||||||
Definition of turningpoints
|
print(wave_periods.__doc__)
|
||||||
---------------------------
|
|
||||||
<----- Direction of wave propagation
|
|
||||||
|
def turning_points():
|
||||||
M M
|
r"""
|
||||||
/ \ .... M /:\_ M_ M
|
Turning points definitions and numenclature
|
||||||
F \ | / \m/ : \ /: \ / \
|
|
||||||
\ h | / : \ / : \ / \
|
Definition of turningpoints
|
||||||
\ | / : \ / : \_ _/ \_ L
|
---------------------------
|
||||||
\_ | / : \_m_/ : \m_/ \m/
|
<----- Direction of wave propagation
|
||||||
\m/ : : : :
|
|
||||||
<------Mw-----> <-----mw----->
|
M M
|
||||||
|
/ \ .... M /:\_ M_ M
|
||||||
Local minimum or maximum are indicated with the
|
F \ | / \m/ : \ /: \ / \
|
||||||
letters 'm' or 'M'. Turning points in this connection are all
|
\ h | / : \ / : \ / \
|
||||||
local max (M) and min (m) and the last (L) value and the
|
\ | / : \ / : \_ _/ \_ L
|
||||||
first (F) value if the first local extremum is a max.
|
\_ | / : \_m_/ : \m_/ \m/
|
||||||
|
\m/ : : : :
|
||||||
(This choice is made in order to get the exact up-crossing intensity
|
<------Mw-----> <-----mw----->
|
||||||
from rfc by mm2lc(tp2mm(rfc)) )
|
|
||||||
|
Local minimum or maximum are indicated with the
|
||||||
|
letters 'm' or 'M'. Turning points in this connection are all
|
||||||
See also
|
local max (M) and min (m) and the last (L) value and the
|
||||||
--------
|
first (F) value if the first local extremum is a max.
|
||||||
waves,
|
|
||||||
crossings,
|
(This choice is made in order to get the exact up-crossing intensity
|
||||||
cycle_pairs
|
from rfc by mm2lc(tp2mm(rfc)) )
|
||||||
findtp
|
|
||||||
|
|
||||||
"""
|
See also
|
||||||
print(turning_points.__doc__)
|
--------
|
||||||
def waves():
|
waves,
|
||||||
r"""
|
crossings,
|
||||||
Wave definitions and nomenclature
|
cycle_pairs
|
||||||
|
findtp
|
||||||
Definition of trough and crest
|
|
||||||
------------------------------
|
"""
|
||||||
A trough (t) is defined as the global minimum between a
|
print(turning_points.__doc__)
|
||||||
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.
|
def waves():
|
||||||
|
r"""
|
||||||
Definition of down- and up -crossing waves
|
Wave definitions and nomenclature
|
||||||
------------------------------------------
|
|
||||||
A level v-down-crossing wave (dw) is a wave from a
|
Definition of trough and crest
|
||||||
down-crossing to the following down-crossing.
|
------------------------------
|
||||||
Similarly, a level v-up-crossing wave (uw) is a wave from an up-crossing
|
A trough (t) is defined as the global minimum between a
|
||||||
to the next up-crossing.
|
level v down-crossing (d) and the next up-crossing (u)
|
||||||
|
and a crest (c) is defined as the global maximum between a
|
||||||
Definition of trough and crest waves
|
level v up-crossing and the following down-crossing.
|
||||||
------------------------------------
|
|
||||||
A trough-to-trough wave (tw) is a wave from a trough (t) to the
|
Definition of down- and up -crossing waves
|
||||||
following trough. The crest-to-crest wave (cw) is defined similarly.
|
------------------------------------------
|
||||||
|
A level v-down-crossing wave (dw) is a wave from a
|
||||||
|
down-crossing to the following down-crossing.
|
||||||
Definition of min2min and Max2Max wave
|
Similarly, a level v-up-crossing wave (uw) is a wave from an up-crossing
|
||||||
--------------------------------------
|
to the next up-crossing.
|
||||||
A min2min wave (mw) is defined starting from a minimum (m) and
|
|
||||||
ending in the following minimum.
|
Definition of trough and crest waves
|
||||||
Similarly a Max2Max wave (Mw) is thus a wave from a maximum (M)
|
------------------------------------
|
||||||
to the next maximum (all waves optionally rainflow filtered).
|
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.
|
||||||
<----- Direction of wave propagation
|
|
||||||
|
|
||||||
|
Definition of min2min and Max2Max wave
|
||||||
<------Mw-----> <----mw---->
|
--------------------------------------
|
||||||
M : : c :
|
A min2min wave (mw) is defined starting from a minimum (m) and
|
||||||
/ \ M : / \_ : c_ c
|
ending in the following minimum.
|
||||||
F \ / \m/ \ : /: \ /:\
|
Similarly a Max2Max wave (Mw) is thus a wave from a maximum (M)
|
||||||
------d--------u----------d-------u----d--------u---d------ level v
|
to the next maximum (all waves optionally rainflow filtered).
|
||||||
\ /: \ : /: : :\_ _/ : :\_ L
|
|
||||||
\_ / : \_t_/ : : : \t_/ : : \m/
|
<----- Direction of wave propagation
|
||||||
\t/ <-------uw---------> : <-----dw----->
|
|
||||||
: : : :
|
|
||||||
<--------tw--------> <------cw----->
|
<------Mw-----> <----mw---->
|
||||||
|
M : : c :
|
||||||
(F=first value and L=last value).
|
/ \ M : / \_ : c_ c
|
||||||
|
F \ / \m/ \ : /: \ /:\
|
||||||
See also
|
------d--------u----------d-------u----d--------u---d------ level v
|
||||||
--------
|
\ /: \ : /: : :\_ _/ : :\_ L
|
||||||
turning_points,
|
\_ / : \_t_/ : : : \t_/ : : \m/
|
||||||
crossings,
|
\t/ <-------uw---------> : <-----dw----->
|
||||||
wave_periods
|
: : : :
|
||||||
findtc,
|
<--------tw--------> <------cw----->
|
||||||
findcross
|
|
||||||
"""
|
(F=first value and L=last value).
|
||||||
print(waves.__doc__)
|
|
||||||
|
See also
|
||||||
|
--------
|
||||||
|
turning_points,
|
||||||
|
crossings,
|
||||||
|
wave_periods
|
||||||
|
findtc,
|
||||||
|
findcross
|
||||||
|
"""
|
||||||
|
print(waves.__doc__)
|
||||||
|
@ -1,132 +1,138 @@
|
|||||||
'''
|
'''
|
||||||
Created on 20. jan. 2011
|
Created on 20. jan. 2011
|
||||||
|
|
||||||
@author: pab
|
@author: pab
|
||||||
'''
|
'''
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from numpy import exp
|
from numpy import exp, meshgrid
|
||||||
from wafo.misc import meshgrid
|
__all__ = ['peaks', 'humps', 'magic']
|
||||||
__all__ = ['peaks', 'humps', 'magic']
|
|
||||||
|
|
||||||
def magic(n):
|
def magic(n):
|
||||||
'''
|
'''
|
||||||
Return magic square for n of any orders > 2.
|
Return magic square for n of any orders > 2.
|
||||||
|
|
||||||
A magic square has the property that the sum of every row and column,
|
A magic square has the property that the sum of every row and column,
|
||||||
as well as both diagonals, is the same number.
|
as well as both diagonals, is the same number.
|
||||||
|
|
||||||
Examples
|
Examples
|
||||||
--------
|
--------
|
||||||
>>> magic(3)
|
>>> magic(3)
|
||||||
array([[8, 1, 6],
|
array([[8, 1, 6],
|
||||||
[3, 5, 7],
|
[3, 5, 7],
|
||||||
[4, 9, 2]])
|
[4, 9, 2]])
|
||||||
|
|
||||||
>>> magic(4)
|
>>> magic(4)
|
||||||
array([[16, 2, 3, 13],
|
array([[16, 2, 3, 13],
|
||||||
[ 5, 11, 10, 8],
|
[ 5, 11, 10, 8],
|
||||||
[ 9, 7, 6, 12],
|
[ 9, 7, 6, 12],
|
||||||
[ 4, 14, 15, 1]])
|
[ 4, 14, 15, 1]])
|
||||||
|
|
||||||
>>> magic(6)
|
>>> magic(6)
|
||||||
array([[35, 1, 6, 26, 19, 24],
|
array([[35, 1, 6, 26, 19, 24],
|
||||||
[ 3, 32, 7, 21, 23, 25],
|
[ 3, 32, 7, 21, 23, 25],
|
||||||
[31, 9, 2, 22, 27, 20],
|
[31, 9, 2, 22, 27, 20],
|
||||||
[ 8, 28, 33, 17, 10, 15],
|
[ 8, 28, 33, 17, 10, 15],
|
||||||
[30, 5, 34, 12, 14, 16],
|
[30, 5, 34, 12, 14, 16],
|
||||||
[ 4, 36, 29, 13, 18, 11]])
|
[ 4, 36, 29, 13, 18, 11]])
|
||||||
'''
|
'''
|
||||||
if (n<3):
|
if (n < 3):
|
||||||
raise ValueError('n must be greater than 2.')
|
raise ValueError('n must be greater than 2.')
|
||||||
|
|
||||||
if np.mod(n,2)==1: # odd order
|
if np.mod(n, 2) == 1: # odd order
|
||||||
ix = np.arange(n) + 1
|
ix = np.arange(n) + 1
|
||||||
J, I = np.meshgrid(ix, ix)
|
J, I = np.meshgrid(ix, ix)
|
||||||
A = np.mod(I + J - (n + 3) / 2, n)
|
A = np.mod(I + J - (n + 3) / 2, n)
|
||||||
B = np.mod(I + 2 * J - 2, n)
|
B = np.mod(I + 2 * J - 2, n)
|
||||||
M = n * A + B + 1
|
M = n * A + B + 1
|
||||||
elif np.mod(n,4)==0: # doubly even order
|
elif np.mod(n, 4) == 0: # doubly even order
|
||||||
M = np.arange(1,n*n+1).reshape(n,n)
|
M = np.arange(1, n * n + 1).reshape(n, n)
|
||||||
ix = np.mod(np.arange(n) + 1,4)//2
|
ix = np.mod(np.arange(n) + 1, 4) // 2
|
||||||
J, I = np.meshgrid(ix, ix)
|
J, I = np.meshgrid(ix, ix)
|
||||||
iz = np.flatnonzero(I==J)
|
iz = np.flatnonzero(I == J)
|
||||||
M.put(iz, n*n+1-M.flat[iz])
|
M.put(iz, n * n + 1 - M.flat[iz])
|
||||||
else: # singly even order
|
else: # singly even order
|
||||||
p = n//2
|
p = n // 2
|
||||||
M0 = magic(p)
|
M0 = magic(p)
|
||||||
|
|
||||||
M = np.hstack((np.vstack((M0, M0+3*p*p)),np.vstack((M0+2*p*p, M0+p*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
|
if n > 2:
|
||||||
Jvec = np.hstack((np.arange(k), np.arange(n-k+1, n)))
|
k = (n - 2) // 4
|
||||||
for i in range(p):
|
Jvec = np.hstack((np.arange(k), np.arange(n - k + 1, n)))
|
||||||
for j in Jvec:
|
for i in range(p):
|
||||||
temp = M[i][j]
|
for j in Jvec:
|
||||||
M[i][j]=M[i+p][j]
|
temp = M[i][j]
|
||||||
M[i+p][j] = temp
|
M[i][j] = M[i + p][j]
|
||||||
|
M[i + p][j] = temp
|
||||||
i=k
|
|
||||||
j=0
|
i = k
|
||||||
temp = M[i][j];
|
j = 0
|
||||||
M[i][j] = M[i+p][j]
|
temp = M[i][j]
|
||||||
M[i+p][j] = temp;
|
M[i][j] = M[i + p][j]
|
||||||
|
M[i + p][j] = temp
|
||||||
j=i
|
|
||||||
temp=M[i+p][j]
|
j = i
|
||||||
M[i+p][j]=M[i][j]
|
temp = M[i + p][j]
|
||||||
M[i][j]=temp
|
M[i + p][j] = M[i][j]
|
||||||
|
M[i][j] = temp
|
||||||
return M
|
|
||||||
|
return M
|
||||||
def peaks(x=None, y=None, n=51):
|
|
||||||
'''
|
|
||||||
Return the "well" known MatLab (R) peaks function
|
def peaks(x=None, y=None, n=51):
|
||||||
evaluated in the [-3,3] x,y range
|
'''
|
||||||
|
Return the "well" known MatLab (R) peaks function
|
||||||
Example
|
evaluated in the [-3,3] x,y range
|
||||||
-------
|
|
||||||
>>> import matplotlib.pyplot as plt
|
Example
|
||||||
>>> x,y,z = peaks()
|
-------
|
||||||
|
>>> import matplotlib.pyplot as plt
|
||||||
h = plt.contourf(x,y,z)
|
>>> x,y,z = peaks()
|
||||||
|
|
||||||
'''
|
h = plt.contourf(x,y,z)
|
||||||
if x is None:
|
|
||||||
x = np.linspace(-3, 3, n)
|
'''
|
||||||
if y is None:
|
if x is None:
|
||||||
y = np.linspace(-3, 3, n)
|
x = np.linspace(-3, 3, n)
|
||||||
|
if y is None:
|
||||||
[x1, y1] = meshgrid(x, y)
|
y = np.linspace(-3, 3, n)
|
||||||
|
|
||||||
z = (3 * (1 - x1) ** 2 * exp(-(x1 ** 2) - (y1 + 1) ** 2)
|
[x1, y1] = meshgrid(x, y)
|
||||||
- 10 * (x1 / 5 - x1 ** 3 - y1 ** 5) * exp(-x1 ** 2 - y1 ** 2)
|
|
||||||
- 1. / 3 * exp(-(x1 + 1) ** 2 - y1 ** 2))
|
z = (3 * (1 - x1) ** 2 * exp(-(x1 ** 2) - (y1 + 1) ** 2)
|
||||||
|
- 10 * (x1 / 5 - x1 ** 3 - y1 ** 5) * exp(-x1 ** 2 - y1 ** 2)
|
||||||
return x1, y1, z
|
- 1. / 3 * exp(-(x1 + 1) ** 2 - y1 ** 2))
|
||||||
|
|
||||||
def humps(x=None):
|
return x1, y1, z
|
||||||
'''
|
|
||||||
Computes a function that has three roots, and some humps.
|
|
||||||
|
def humps(x=None):
|
||||||
Example
|
'''
|
||||||
-------
|
Computes a function that has three roots, and some humps.
|
||||||
>>> import matplotlib.pyplot as plt
|
|
||||||
>>> x = np.linspace(0,1)
|
Example
|
||||||
>>> y = humps(x)
|
-------
|
||||||
|
>>> import matplotlib.pyplot as plt
|
||||||
h = plt.plot(x,y)
|
>>> x = np.linspace(0,1)
|
||||||
'''
|
>>> y = humps(x)
|
||||||
if x is None:
|
|
||||||
y = np.linspace(0, 1)
|
h = plt.plot(x,y)
|
||||||
else:
|
'''
|
||||||
y = np.asarray(x)
|
if x is None:
|
||||||
|
y = np.linspace(0, 1)
|
||||||
return 1.0 / ((y - 0.3) ** 2 + 0.01) + 1.0 / ((y - 0.9) ** 2 + 0.04) + 2 * y - 5.2
|
else:
|
||||||
|
y = np.asarray(x)
|
||||||
def test_docstrings():
|
|
||||||
import doctest
|
return 1.0 / ((y - 0.3) ** 2 + 0.01) + 1.0 / ((y - 0.9) ** 2 + 0.04) + \
|
||||||
doctest.testmod()
|
2 * y - 5.2
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
test_docstrings()
|
def test_docstrings():
|
||||||
|
import doctest
|
||||||
|
print('Testing docstrings in %s' % __file__)
|
||||||
|
doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_docstrings()
|
||||||
|
@ -1,282 +1,267 @@
|
|||||||
'''
|
'''
|
||||||
Created on 20. jan. 2011
|
Created on 20. jan. 2011
|
||||||
|
|
||||||
@author: pab
|
@author: pab
|
||||||
|
|
||||||
license BSD
|
license BSD
|
||||||
'''
|
'''
|
||||||
from __future__ import division
|
from __future__ import division
|
||||||
import warnings
|
import warnings
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from wafo.plotbackend import plotbackend
|
from wafo.plotbackend import plotbackend
|
||||||
from matplotlib import mlab
|
from matplotlib import mlab
|
||||||
__all__ = ['cltext', 'epcolor', 'tallibing', 'test_docstrings']
|
__all__ = ['cltext', 'tallibing', 'test_docstrings']
|
||||||
|
|
||||||
_TALLIBING_GID = 'TALLIBING'
|
_TALLIBING_GID = 'TALLIBING'
|
||||||
_CLTEXT_GID = 'CLTEXT'
|
_CLTEXT_GID = 'CLTEXT'
|
||||||
|
|
||||||
def _matchfun(x, gidtxt):
|
|
||||||
if hasattr(x, 'get_gid'):
|
def _matchfun(x, gidtxt):
|
||||||
return x.get_gid() == gidtxt
|
if hasattr(x, 'get_gid'):
|
||||||
return False
|
return x.get_gid() == gidtxt
|
||||||
|
return False
|
||||||
def delete_text_object(gidtxt, figure=None, axis=None, verbose=False):
|
|
||||||
'''
|
|
||||||
Delete all text objects matching the gidtxt if it exists
|
def delete_text_object(gidtxt, figure=None, axis=None, verbose=False):
|
||||||
|
'''
|
||||||
Parameters
|
Delete all text objects matching the gidtxt if it exists
|
||||||
----------
|
|
||||||
gidtxt : string
|
Parameters
|
||||||
|
----------
|
||||||
figure, axis : objects
|
gidtxt : string
|
||||||
current figure and current axis, respectively.
|
|
||||||
verbose : bool
|
figure, axis : objects
|
||||||
If true print warnings when trying to delete non-existent objects
|
current figure and current axis, respectively.
|
||||||
'''
|
verbose : bool
|
||||||
if figure is None:
|
If true print warnings when trying to delete non-existent objects
|
||||||
figure = plotbackend.gcf()
|
'''
|
||||||
if axis is None:
|
if figure is None:
|
||||||
axis = figure.gca()
|
figure = plotbackend.gcf()
|
||||||
lmatchfun = lambda x : _matchfun(x, gidtxt)
|
if axis is None:
|
||||||
objs = axis.findobj(lmatchfun)
|
axis = figure.gca()
|
||||||
for obj in objs:
|
lmatchfun = lambda x: _matchfun(x, gidtxt)
|
||||||
try:
|
objs = axis.findobj(lmatchfun)
|
||||||
axis.texts.remove(obj)
|
for obj in objs:
|
||||||
except:
|
try:
|
||||||
if verbose:
|
axis.texts.remove(obj)
|
||||||
warnings.warn('Tried to delete a non-existing %s from axis' % gidtxt)
|
except:
|
||||||
objs = figure.findobj(lmatchfun)
|
if verbose:
|
||||||
for obj in objs:
|
warnings.warn(
|
||||||
try:
|
'Tried to delete a non-existing %s from axis' % gidtxt)
|
||||||
figure.texts.remove(obj)
|
objs = figure.findobj(lmatchfun)
|
||||||
except:
|
for obj in objs:
|
||||||
if verbose:
|
try:
|
||||||
warnings.warn('Tried to delete a non-existing %s from figure' % gidtxt)
|
figure.texts.remove(obj)
|
||||||
|
except:
|
||||||
def cltext(levels, percent=False, n=4, xs=0.036, ys=0.94, zs=0, figure=None, axis=None):
|
if verbose:
|
||||||
'''
|
warnings.warn(
|
||||||
Places contour level text in the current window
|
'Tried to delete a non-existing %s from figure' % gidtxt)
|
||||||
|
|
||||||
Parameters
|
|
||||||
----------
|
def cltext(levels, percent=False, n=4, xs=0.036, ys=0.94, zs=0, figure=None,
|
||||||
levels : vector
|
axis=None):
|
||||||
contour levels or the corresponding percent which the
|
'''
|
||||||
contour line encloses
|
Places contour level text in the current window
|
||||||
percent : bool
|
|
||||||
False if levels are the actual contour levels (default)
|
Parameters
|
||||||
True if levels are the corresponding percent which the
|
----------
|
||||||
contour line encloses
|
levels : vector
|
||||||
n : integer
|
contour levels or the corresponding percent which the
|
||||||
maximum N digits of precision (default 4)
|
contour line encloses
|
||||||
figure, axis : objects
|
percent : bool
|
||||||
current figure and current axis, respectively.
|
False if levels are the actual contour levels (default)
|
||||||
default figure = plotbackend.gcf(),
|
True if levels are the corresponding percent which the
|
||||||
axis = plotbackend.gca()
|
contour line encloses
|
||||||
|
n : integer
|
||||||
Returns
|
maximum N digits of precision (default 4)
|
||||||
-------
|
figure, axis : objects
|
||||||
h = handles to the text objects.
|
current figure and current axis, respectively.
|
||||||
|
default figure = plotbackend.gcf(),
|
||||||
|
axis = plotbackend.gca()
|
||||||
Notes
|
|
||||||
-----
|
Returns
|
||||||
CLTEXT creates text objects in the current figure and prints
|
-------
|
||||||
"Level curves at:" if percent is False and
|
h = handles to the text objects.
|
||||||
"Level curves enclosing:" otherwise
|
|
||||||
and the contour levels or percent.
|
|
||||||
|
Notes
|
||||||
The handles to the lines of text may also be found by
|
-----
|
||||||
h = findobj(gcf,'gid','CLTEXT','type','text');
|
CLTEXT creates text objects in the current figure and prints
|
||||||
h = findobj(gca,'gid','CLTEXT','type','text');
|
"Level curves at:" if percent is False and
|
||||||
To make the text objects follow the data in the axes set the units
|
"Level curves enclosing:" otherwise
|
||||||
for the text objects 'data' by
|
and the contour levels or percent.
|
||||||
set(h,'unit','data')
|
|
||||||
|
The handles to the lines of text may also be found by
|
||||||
Examples
|
h = findobj(gcf,'gid','CLTEXT','type','text');
|
||||||
--------
|
h = findobj(gca,'gid','CLTEXT','type','text');
|
||||||
>>> import wafo.graphutil as wg
|
To make the text objects follow the data in the axes set the units
|
||||||
>>> import wafo.demos as wd
|
for the text objects 'data' by
|
||||||
>>> import pylab as plt
|
set(h,'unit','data')
|
||||||
>>> x,y,z = wd.peaks();
|
|
||||||
>>> h = plt.contour(x,y,z)
|
Examples
|
||||||
>>> h = wg.cltext(h.levels)
|
--------
|
||||||
>>> plt.show()
|
>>> import wafo.graphutil as wg
|
||||||
'''
|
>>> import wafo.demos as wd
|
||||||
# TODO : Make it work like legend does (but without the box): include position options etc...
|
>>> import pylab as plt
|
||||||
if figure is None:
|
>>> x,y,z = wd.peaks();
|
||||||
figure = plotbackend.gcf()
|
>>> h = plt.contour(x,y,z)
|
||||||
if axis is None:
|
>>> h = wg.cltext(h.levels)
|
||||||
axis = figure.gca()
|
>>> plt.show()
|
||||||
|
'''
|
||||||
clevels = np.atleast_1d(levels)
|
# TODO : Make it work like legend does (but without the box): include
|
||||||
|
# position options etc...
|
||||||
|
if figure is None:
|
||||||
axpos = axis.get_position()
|
figure = plotbackend.gcf()
|
||||||
xint = axpos.intervalx
|
if axis is None:
|
||||||
yint = axpos.intervaly
|
axis = figure.gca()
|
||||||
|
|
||||||
xss = xint[0] + xs * (xint[1] - xint[0])
|
clevels = np.atleast_1d(levels)
|
||||||
yss = yint[0] + ys * (yint[1] - yint[0])
|
|
||||||
|
axpos = axis.get_position()
|
||||||
# delete cltext object if it exists
|
xint = axpos.intervalx
|
||||||
delete_text_object(_CLTEXT_GID, axis=axis)
|
yint = axpos.intervaly
|
||||||
|
|
||||||
charHeight = 1.0 / 33.0
|
xss = xint[0] + xs * (xint[1] - xint[0])
|
||||||
delta_y = charHeight
|
yss = yint[0] + ys * (yint[1] - yint[0])
|
||||||
|
|
||||||
if percent:
|
# delete cltext object if it exists
|
||||||
titletxt = 'Level curves enclosing:';
|
delete_text_object(_CLTEXT_GID, axis=axis)
|
||||||
else:
|
|
||||||
titletxt = 'Level curves at:';
|
charHeight = 1.0 / 33.0
|
||||||
|
delta_y = charHeight
|
||||||
format_ = '%0.' + ('%d' % n) + 'g\n'
|
|
||||||
|
if percent:
|
||||||
cltxt = ''.join([format_ % level for level in clevels.tolist()])
|
titletxt = 'Level curves enclosing:'
|
||||||
|
else:
|
||||||
titleProp = dict(gid=_CLTEXT_GID, horizontalalignment='left',
|
titletxt = 'Level curves at:'
|
||||||
verticalalignment='center', fontweight='bold', axes=axis) #
|
|
||||||
|
format_ = '%0.' + ('%d' % n) + 'g\n'
|
||||||
ha1 = figure.text(xss, yss, titletxt, **titleProp)
|
|
||||||
|
cltxt = ''.join([format_ % level for level in clevels.tolist()])
|
||||||
yss -= delta_y;
|
|
||||||
txtProp = dict(gid=_CLTEXT_GID, horizontalalignment='left',
|
titleProp = dict(gid=_CLTEXT_GID, horizontalalignment='left',
|
||||||
verticalalignment='top', axes=axis)
|
verticalalignment='center', fontweight='bold', axes=axis)
|
||||||
|
|
||||||
ha2 = figure.text(xss, yss, cltxt, **txtProp)
|
ha1 = figure.text(xss, yss, titletxt, **titleProp)
|
||||||
plotbackend.draw_if_interactive()
|
|
||||||
return ha1, ha2
|
yss -= delta_y
|
||||||
|
txtProp = dict(gid=_CLTEXT_GID, horizontalalignment='left',
|
||||||
def tallibing(x, y, n, **kwds):
|
verticalalignment='top', axes=axis)
|
||||||
'''
|
|
||||||
TALLIBING Display numbers on field-plot
|
ha2 = figure.text(xss, yss, cltxt, **txtProp)
|
||||||
|
plotbackend.draw_if_interactive()
|
||||||
CALL h=tallibing(x,y,n,size,color)
|
return ha1, ha2
|
||||||
|
|
||||||
x,y = position matrices
|
|
||||||
n = the corresponding matrix of the values to be written
|
def tallibing(*args, **kwds):
|
||||||
(non-integers are rounded)
|
'''
|
||||||
size = font size (optional) (default=8)
|
TALLIBING Display numbers on field-plot
|
||||||
color = color of text (optional) (default='white')
|
|
||||||
h = column-vector of handles to TEXT objects
|
CALL h=tallibing(x,y,n,size,color)
|
||||||
|
|
||||||
TALLIBING writes the numbers in a 2D array as text at the positions
|
Parameters
|
||||||
given by the x and y coordinate matrices.
|
----------
|
||||||
When plotting binned results, the number of datapoints in each
|
x, y : array
|
||||||
bin can be written on the bins in the plot.
|
position matrices
|
||||||
|
n : array
|
||||||
Example
|
corresponding matrix of the values to be written
|
||||||
-------
|
(non-integers are rounded)
|
||||||
>>> import wafo.graphutil as wg
|
mid_points : bool (default True)
|
||||||
>>> import wafo.demos as wd
|
data-point-positions are in the middle of bins instead of the corners
|
||||||
>>> [x,y,z] = wd.peaks(n=20)
|
size : int, (default=8)
|
||||||
>>> h0 = wg.epcolor(x,y,z)
|
font size (optional)
|
||||||
>>> h1 = wg.tallibing(x,y,z)
|
color : str, (default='white')
|
||||||
|
color of text (optional)
|
||||||
pcolor(x,y,z); shading interp;
|
|
||||||
|
Returns
|
||||||
See also
|
-------
|
||||||
--------
|
h : list
|
||||||
text
|
handles to TEXT objects
|
||||||
'''
|
|
||||||
|
TALLIBING writes the numbers in a 2D array as text at the positions
|
||||||
axis = kwds.pop('axis',None)
|
given by the x and y coordinate matrices.
|
||||||
if axis is None:
|
When plotting binned results, the number of datapoints in each
|
||||||
axis = plotbackend.gca()
|
bin can be written on the bins in the plot.
|
||||||
|
|
||||||
x, y, n = np.atleast_1d(x, y, n)
|
Example
|
||||||
if mlab.isvector(x) or mlab.isvector(y):
|
-------
|
||||||
x, y = np.meshgrid(x,y)
|
>>> import wafo.graphutil as wg
|
||||||
|
>>> import wafo.demos as wd
|
||||||
x = x.ravel()
|
>>> [x,y,z] = wd.peaks(n=20)
|
||||||
y = y.ravel()
|
>>> h0 = wg.pcolor(x,y,z)
|
||||||
n = n.ravel()
|
>>> h1 = wg.tallibing(x,y,z)
|
||||||
n = np.round(n)
|
|
||||||
|
See also
|
||||||
# delete tallibing object if it exists
|
--------
|
||||||
delete_text_object(_TALLIBING_GID, axis=axis)
|
text
|
||||||
|
'''
|
||||||
txtProp = dict(gid=_TALLIBING_GID, size=8, color='w', horizontalalignment='center',
|
|
||||||
verticalalignment='center', fontweight='demi', axes=axis)
|
axis = kwds.pop('axis', None)
|
||||||
|
if axis is None:
|
||||||
txtProp.update(**kwds)
|
axis = plotbackend.gca()
|
||||||
h = []
|
|
||||||
for xi,yi, ni in zip(x,y,n):
|
x, y, n = _parse_data(*args, **kwds)
|
||||||
if ni:
|
if mlab.isvector(x) or mlab.isvector(y):
|
||||||
h.append(axis.text(xi, yi, str(ni), **txtProp))
|
x, y = np.meshgrid(x, y)
|
||||||
plotbackend.draw_if_interactive()
|
|
||||||
return h
|
n = np.round(n)
|
||||||
|
|
||||||
def epcolor(*args, **kwds):
|
# delete tallibing object if it exists
|
||||||
'''
|
delete_text_object(_TALLIBING_GID, axis=axis)
|
||||||
Pseudocolor (checkerboard) plot with mid-bin positioning.
|
|
||||||
|
txtProp = dict(gid=_TALLIBING_GID, size=8, color='w',
|
||||||
h = epcolor(x,y,data)
|
horizontalalignment='center',
|
||||||
|
verticalalignment='center', fontweight='demi', axes=axis)
|
||||||
|
|
||||||
[x,y]= the axes corresponding to the data-positions. Vectors or
|
txtProp.update(**kwds)
|
||||||
matrices. If omitted, giving only data-matrix as inargument, the
|
h = []
|
||||||
matrix-indices are used as axes.
|
for xi, yi, ni in zip(x.ravel(), y.ravel(), n.ravel()):
|
||||||
data = data-matrix
|
if ni:
|
||||||
|
h.append(axis.text(xi, yi, str(ni), **txtProp))
|
||||||
EPCOLOR make a checkerboard plot where the data-point-positions are in
|
plotbackend.draw_if_interactive()
|
||||||
the middle of the bins instead of in the corners, and the last column
|
return h
|
||||||
and row of data are used.
|
|
||||||
|
|
||||||
|
def _parse_data(*args, **kwds):
|
||||||
Example:
|
nargin = len(args)
|
||||||
>>> import wafo.demos as wd
|
data = np.atleast_2d(args[-1]).copy()
|
||||||
>>> import wafo.graphutil as wg
|
M, N = data.shape
|
||||||
>>> x, y, z = wd.peaks(n=20)
|
if nargin == 1:
|
||||||
>>> h = wg.epcolor(x,y,z)
|
x = np.arange(N)
|
||||||
|
y = np.arange(M)
|
||||||
See also
|
elif nargin == 3:
|
||||||
--------
|
x, y = np.atleast_1d(*args[:-1])
|
||||||
pylab.pcolor
|
if min(x.shape) != 1:
|
||||||
'''
|
x = x[0]
|
||||||
axis = kwds.pop('axis',None)
|
if min(y.shape) != 1:
|
||||||
if axis is None:
|
y = y[:, 0]
|
||||||
axis = plotbackend.gca()
|
else:
|
||||||
midbin = kwds.pop('midbin', True)
|
raise ValueError(
|
||||||
if not midbin:
|
'Requires 3 or 1 in arguments! (x,y,data) or (data)')
|
||||||
ret = axis.pcolor(*args,**kwds)
|
if kwds.pop('mid_point', True):
|
||||||
plotbackend.draw_if_interactive()
|
xx = _find_mid_points(x)
|
||||||
return ret
|
yy = _find_mid_points(y)
|
||||||
|
return xx, yy, data
|
||||||
nargin = len(args)
|
return x, y, data
|
||||||
data = np.atleast_2d(args[-1]).copy()
|
|
||||||
M, N = data.shape
|
pcolor = plotbackend.pcolor
|
||||||
if nargin==1:
|
pcolormesh = plotbackend.pcolormesh
|
||||||
x = np.arange(N)
|
|
||||||
y = np.arange(M)
|
|
||||||
elif nargin==3:
|
def _find_mid_points(x):
|
||||||
x, y = np.atleast_1d(*args[:-1])
|
''' Return points half way between all values of X and outside the
|
||||||
if min(x.shape)!=1:
|
endpoints. The outer limits have same distance from X's endpoints as
|
||||||
x = x[0]
|
the limits just inside.
|
||||||
if min(y.shape)!=1:
|
'''
|
||||||
y = y[:,0]
|
dx = np.diff(x) * 0.5
|
||||||
else:
|
dx = np.hstack((dx, dx[-1]))
|
||||||
raise ValueError('pcolor takes 3 or 1 inarguments! (x,y,data) or (data)')
|
return x + dx
|
||||||
|
|
||||||
xx = _findbins(x)
|
|
||||||
yy = _findbins(y)
|
def test_docstrings():
|
||||||
ret = axis.pcolor(xx, yy, data, **kwds)
|
import doctest
|
||||||
plotbackend.draw_if_interactive()
|
print('Testing docstrings in %s' % __file__)
|
||||||
return ret
|
doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
def _findbins(x):
|
test_docstrings()
|
||||||
''' Return points half way between all values of X _and_ outside the
|
|
||||||
endpoints. The outer limits have same distance from X's endpoints as
|
|
||||||
the limits just inside.
|
|
||||||
'''
|
|
||||||
dx = np.diff(x) * 0.5
|
|
||||||
dx = np.hstack((dx, dx[-1]))
|
|
||||||
return np.hstack((x[0] - dx[0], x + dx))
|
|
||||||
|
|
||||||
|
|
||||||
def test_docstrings():
|
|
||||||
import doctest
|
|
||||||
doctest.testmod()
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
test_docstrings()
|
|
||||||
|
@ -1,136 +0,0 @@
|
|||||||
import numpy as np
|
|
||||||
|
|
||||||
|
|
||||||
def meshgrid(*xi, **kwargs):
|
|
||||||
"""
|
|
||||||
Return coordinate matrices from one or more coordinate vectors.
|
|
||||||
|
|
||||||
Make N-D coordinate arrays for vectorized evaluations of
|
|
||||||
N-D scalar/vector fields over N-D grids, given
|
|
||||||
one-dimensional coordinate arrays x1, x2,..., xn.
|
|
||||||
|
|
||||||
Parameters
|
|
||||||
----------
|
|
||||||
x1, x2,..., xn : array_like
|
|
||||||
1-D arrays representing the coordinates of a grid.
|
|
||||||
indexing : 'xy' or 'ij' (optional)
|
|
||||||
cartesian ('xy', default) or matrix ('ij') indexing of output
|
|
||||||
sparse : True or False (default) (optional)
|
|
||||||
If True a sparse grid is returned in order to conserve memory.
|
|
||||||
copy : True (default) or False (optional)
|
|
||||||
If False a view into the original arrays are returned in order to
|
|
||||||
conserve memory. Please note that sparse=False, copy=False will likely
|
|
||||||
return non-contiguous arrays. Furthermore, more than one element of a
|
|
||||||
broadcasted array may refer to a single memory location. If you
|
|
||||||
need to write to the arrays, make copies first.
|
|
||||||
|
|
||||||
Returns
|
|
||||||
-------
|
|
||||||
X1, X2,..., XN : ndarray
|
|
||||||
For vectors `x1`, `x2`,..., 'xn' with lengths ``Ni=len(xi)`` ,
|
|
||||||
return ``(N1, N2, N3,...Nn)`` shaped arrays if indexing='ij'
|
|
||||||
or ``(N2, N1, N3,...Nn)`` shaped arrays if indexing='xy'
|
|
||||||
with the elements of `xi` repeated to fill the matrix along
|
|
||||||
the first dimension for `x1`, the second for `x2` and so on.
|
|
||||||
|
|
||||||
Notes
|
|
||||||
-----
|
|
||||||
This function supports both indexing conventions through the indexing
|
|
||||||
keyword argument. Giving the string 'ij' returns a meshgrid with matrix
|
|
||||||
indexing, while 'xy' returns a meshgrid with Cartesian indexing. The
|
|
||||||
difference is illustrated by the following code snippet:
|
|
||||||
|
|
||||||
xv, yv = meshgrid(x, y, sparse=False, indexing='ij')
|
|
||||||
for i in range(nx):
|
|
||||||
for j in range(ny):
|
|
||||||
# treat xv[i,j], yv[i,j]
|
|
||||||
|
|
||||||
xv, yv = meshgrid(x, y, sparse=False, indexing='xy')
|
|
||||||
for i in range(nx):
|
|
||||||
for j in range(ny):
|
|
||||||
# treat xv[j,i], yv[j,i]
|
|
||||||
|
|
||||||
See Also
|
|
||||||
--------
|
|
||||||
index_tricks.mgrid : Construct a multi-dimensional "meshgrid"
|
|
||||||
using indexing notation.
|
|
||||||
index_tricks.ogrid : Construct an open multi-dimensional "meshgrid"
|
|
||||||
using indexing notation.
|
|
||||||
|
|
||||||
Examples
|
|
||||||
--------
|
|
||||||
>>> nx, ny = (3, 2)
|
|
||||||
>>> x = np.linspace(0, 1, nx)
|
|
||||||
>>> y = np.linspace(0, 1, ny)
|
|
||||||
>>> xv, yv = meshgrid(x, y)
|
|
||||||
>>> xv
|
|
||||||
array([[ 0. , 0.5, 1. ],
|
|
||||||
[ 0. , 0.5, 1. ]])
|
|
||||||
>>> yv
|
|
||||||
array([[ 0., 0., 0.],
|
|
||||||
[ 1., 1., 1.]])
|
|
||||||
>>> xv, yv = meshgrid(x, y, sparse=True) # make sparse output arrays
|
|
||||||
>>> xv
|
|
||||||
array([[ 0. , 0.5, 1. ]])
|
|
||||||
>>> yv
|
|
||||||
array([[ 0.],
|
|
||||||
[ 1.]])
|
|
||||||
|
|
||||||
`meshgrid` is very useful to evaluate functions on a grid.
|
|
||||||
|
|
||||||
>>> x = np.arange(-5, 5, 0.1)
|
|
||||||
>>> y = np.arange(-5, 5, 0.1)
|
|
||||||
>>> xx, yy = meshgrid(x, y, sparse=True)
|
|
||||||
>>> z = np.sin(xx**2+yy**2)/(xx**2+yy**2)
|
|
||||||
|
|
||||||
>>> import matplotlib.pyplot as plt
|
|
||||||
>>> h = plt.contourf(x,y,z)
|
|
||||||
"""
|
|
||||||
copy_ = kwargs.get('copy', True)
|
|
||||||
args = np.atleast_1d(*xi)
|
|
||||||
ndim = len(args)
|
|
||||||
|
|
||||||
if not isinstance(args, list) or ndim < 2:
|
|
||||||
raise TypeError(
|
|
||||||
'meshgrid() takes 2 or more arguments (%d given)' % int(ndim > 0))
|
|
||||||
|
|
||||||
sparse = kwargs.get('sparse', False)
|
|
||||||
indexing = kwargs.get('indexing', 'xy')
|
|
||||||
|
|
||||||
s0 = (1,) * ndim
|
|
||||||
output = [x.reshape(s0[:i] + (-1,) + s0[i + 1::])
|
|
||||||
for i, x in enumerate(args)]
|
|
||||||
|
|
||||||
shape = [x.size for x in output]
|
|
||||||
|
|
||||||
if indexing == 'xy':
|
|
||||||
# switch first and second axis
|
|
||||||
output[0].shape = (1, -1) + (1,) * (ndim - 2)
|
|
||||||
output[1].shape = (-1, 1) + (1,) * (ndim - 2)
|
|
||||||
shape[0], shape[1] = shape[1], shape[0]
|
|
||||||
|
|
||||||
if sparse:
|
|
||||||
if copy_:
|
|
||||||
return [x.copy() for x in output]
|
|
||||||
else:
|
|
||||||
return output
|
|
||||||
else:
|
|
||||||
# Return the full N-D matrix (not only the 1-D vector)
|
|
||||||
if copy_:
|
|
||||||
mult_fact = np.ones(shape, dtype=int)
|
|
||||||
return [x * mult_fact for x in output]
|
|
||||||
else:
|
|
||||||
return np.broadcast_arrays(*output)
|
|
||||||
|
|
||||||
|
|
||||||
def ndgrid(*args, **kwargs):
|
|
||||||
"""
|
|
||||||
Same as calling meshgrid with indexing='ij' (see meshgrid for
|
|
||||||
documentation).
|
|
||||||
"""
|
|
||||||
kwargs['indexing'] = 'ij'
|
|
||||||
return meshgrid(*args, **kwargs)
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
import doctest
|
|
||||||
doctest.testmod()
|
|
File diff suppressed because it is too large
Load Diff
@ -1,132 +1,144 @@
|
|||||||
from operator import itemgetter as _itemgetter
|
from operator import itemgetter as _itemgetter
|
||||||
from keyword import iskeyword as _iskeyword
|
from keyword import iskeyword as _iskeyword
|
||||||
import sys as _sys
|
import sys as _sys
|
||||||
|
|
||||||
def namedtuple(typename, field_names, verbose=False):
|
|
||||||
"""Returns a new subclass of tuple with named fields.
|
def namedtuple(typename, field_names, verbose=False):
|
||||||
|
"""Returns a new subclass of tuple with named fields.
|
||||||
>>> Point = namedtuple('Point', 'x y')
|
|
||||||
>>> Point.__doc__ # docstring for the new class
|
>>> Point = namedtuple('Point', 'x y')
|
||||||
'Point(x, y)'
|
>>> Point.__doc__ # docstring for the new class
|
||||||
>>> p = Point(11, y=22) # instantiate with positional args or keywords
|
'Point(x, y)'
|
||||||
>>> p[0] + p[1] # indexable like a plain tuple
|
>>> p = Point(11, y=22) # instantiate with positional args or keywords
|
||||||
33
|
>>> p[0] + p[1] # indexable like a plain tuple
|
||||||
>>> x, y = p # unpack like a regular tuple
|
33
|
||||||
>>> x, y
|
>>> x, y = p # unpack like a regular tuple
|
||||||
(11, 22)
|
>>> x, y
|
||||||
>>> p.x + p.y # fields also accessable by name
|
(11, 22)
|
||||||
33
|
>>> p.x + p.y # fields also accessable by name
|
||||||
>>> d = p._asdict() # convert to a dictionary
|
33
|
||||||
>>> d['x']
|
>>> d = p._asdict() # convert to a dictionary
|
||||||
11
|
>>> d['x']
|
||||||
>>> Point(**d) # convert from a dictionary
|
11
|
||||||
Point(x=11, y=22)
|
>>> Point(**d) # convert from a dictionary
|
||||||
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
|
Point(x=11, y=22)
|
||||||
Point(x=100, y=22)
|
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
|
||||||
|
Point(x=100, y=22)
|
||||||
"""
|
|
||||||
|
"""
|
||||||
# Parse and validate the field names. Validation serves two purposes,
|
|
||||||
# generating informative error messages and preventing template injection attacks.
|
# Parse and validate the field names. Validation serves two purposes,
|
||||||
if isinstance(field_names, basestring):
|
# generating informative error messages and preventing template injection
|
||||||
field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
|
# attacks.
|
||||||
field_names = tuple(field_names)
|
if isinstance(field_names, basestring):
|
||||||
for name in (typename,) + field_names:
|
# names separated by whitespace and/or commas
|
||||||
if not min(c.isalnum() or c=='_' for c in name):
|
field_names = field_names.replace(',', ' ').split()
|
||||||
raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
|
field_names = tuple(field_names)
|
||||||
if _iskeyword(name):
|
for name in (typename,) + field_names:
|
||||||
raise ValueError('Type names and field names cannot be a keyword: %r' % name)
|
if not min(c.isalnum() or c == '_' for c in name):
|
||||||
if name[0].isdigit():
|
raise ValueError(
|
||||||
raise ValueError('Type names and field names cannot start with a number: %r' % name)
|
'Type names and field names can only contain alphanumeric ' +
|
||||||
seen_names = set()
|
'characters and underscores: %r' % name)
|
||||||
for name in field_names:
|
if _iskeyword(name):
|
||||||
if name.startswith('_'):
|
raise ValueError(
|
||||||
raise ValueError('Field names cannot start with an underscore: %r' % name)
|
'Type names and field names cannot be a keyword: %r' % name)
|
||||||
if name in seen_names:
|
if name[0].isdigit():
|
||||||
raise ValueError('Encountered duplicate field name: %r' % name)
|
raise ValueError('Type names and field names cannot start ' +
|
||||||
seen_names.add(name)
|
'with a number: %r' % name)
|
||||||
|
seen_names = set()
|
||||||
# Create and fill-in the class template
|
for name in field_names:
|
||||||
numfields = len(field_names)
|
if name.startswith('_'):
|
||||||
argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
|
raise ValueError(
|
||||||
reprtxt = ', '.join('%s=%%r' % name for name in field_names)
|
'Field names cannot start with an underscore: %r' % name)
|
||||||
dicttxt = ', '.join('%r: t[%d]' % (name, pos) for pos, name in enumerate(field_names))
|
if name in seen_names:
|
||||||
template = '''class %(typename)s(tuple):
|
raise ValueError('Encountered duplicate field name: %r' % name)
|
||||||
'%(typename)s(%(argtxt)s)' \n
|
seen_names.add(name)
|
||||||
__slots__ = () \n
|
|
||||||
_fields = %(field_names)r \n
|
# Create and fill-in the class template
|
||||||
def __new__(cls, %(argtxt)s):
|
numfields = len(field_names)
|
||||||
return tuple.__new__(cls, (%(argtxt)s)) \n
|
# tuple repr without parens or quotes
|
||||||
@classmethod
|
argtxt = repr(field_names).replace("'", "")[1:-1]
|
||||||
def _make(cls, iterable, new=tuple.__new__, len=len):
|
reprtxt = ', '.join('%s=%%r' % name for name in field_names)
|
||||||
'Make a new %(typename)s object from a sequence or iterable'
|
dicttxt = ', '.join('%r: t[%d]' % (name, pos)
|
||||||
result = new(cls, iterable)
|
for pos, name in enumerate(field_names))
|
||||||
if len(result) != %(numfields)d:
|
template = '''class %(typename)s(tuple):
|
||||||
raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
|
'%(typename)s(%(argtxt)s)' \n
|
||||||
return result \n
|
__slots__ = () \n
|
||||||
def __repr__(self):
|
_fields = %(field_names)r \n
|
||||||
return '%(typename)s(%(reprtxt)s)' %% self \n
|
def __new__(cls, %(argtxt)s):
|
||||||
def _asdict(t):
|
return tuple.__new__(cls, (%(argtxt)s)) \n
|
||||||
'Return a new dict which maps field names to their values'
|
@classmethod
|
||||||
return {%(dicttxt)s} \n
|
def _make(cls, iterable, new=tuple.__new__, len=len):
|
||||||
def _replace(self, **kwds):
|
'Make a new %(typename)s object from a sequence or iterable'
|
||||||
'Return a new %(typename)s object replacing specified fields with new values'
|
result = new(cls, iterable)
|
||||||
result = self._make(map(kwds.pop, %(field_names)r, self))
|
if len(result) != %(numfields)d:
|
||||||
if kwds:
|
raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
|
||||||
raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
|
return result \n
|
||||||
return result \n\n''' % locals()
|
def __repr__(self):
|
||||||
for i, name in enumerate(field_names):
|
return '%(typename)s(%(reprtxt)s)' %% self \n
|
||||||
template += ' %s = property(itemgetter(%d))\n' % (name, i)
|
def _asdict(t):
|
||||||
if verbose:
|
'Return a new dict which maps field names to their values'
|
||||||
print template
|
return {%(dicttxt)s} \n
|
||||||
|
def _replace(self, **kwds):
|
||||||
# Execute the template string in a temporary namespace
|
'Return a new %(typename)s object replacing specified fields with new values'
|
||||||
namespace = dict(itemgetter=_itemgetter)
|
result = self._make(map(kwds.pop, %(field_names)r, self))
|
||||||
try:
|
if kwds:
|
||||||
exec template in namespace
|
raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
|
||||||
except SyntaxError, e:
|
return result \n\n''' % locals()
|
||||||
raise SyntaxError(e.message + ':\n' + template)
|
for i, name in enumerate(field_names):
|
||||||
result = namespace[typename]
|
template += ' %s = property(itemgetter(%d))\n' % (name, i)
|
||||||
|
if verbose:
|
||||||
# For pickling to work, the __module__ variable needs to be set to the frame
|
print template
|
||||||
# where the named tuple is created. Bypass this step in enviroments where
|
|
||||||
# sys._getframe is not defined (Jython for example).
|
# Execute the template string in a temporary namespace
|
||||||
if hasattr(_sys, '_getframe'):
|
namespace = dict(itemgetter=_itemgetter)
|
||||||
result.__module__ = _sys._getframe(1).f_globals['__name__']
|
try:
|
||||||
|
exec template in namespace
|
||||||
return result
|
except SyntaxError, e:
|
||||||
|
raise SyntaxError(e.message + ':\n' + template)
|
||||||
|
result = namespace[typename]
|
||||||
|
|
||||||
|
# For pickling to work, the __module__ variable needs to be set to the
|
||||||
|
# frame where the named tuple is created. Bypass this step in enviroments
|
||||||
|
# where sys._getframe is not defined (Jython for example).
|
||||||
if __name__ == '__main__':
|
if hasattr(_sys, '_getframe'):
|
||||||
# verify that instances can be pickled
|
result.__module__ = _sys._getframe(1).f_globals['__name__']
|
||||||
from cPickle import loads, dumps
|
|
||||||
Point = namedtuple('Point', 'x, y', True)
|
return result
|
||||||
p = Point(x=10, y=20)
|
|
||||||
assert p == loads(dumps(p))
|
|
||||||
|
if __name__ == '__main__':
|
||||||
# test and demonstrate ability to override methods
|
# verify that instances can be pickled
|
||||||
class Point(namedtuple('Point', 'x y')):
|
from cPickle import loads, dumps
|
||||||
@property
|
Point = namedtuple('Point', 'x, y', True)
|
||||||
def hypot(self):
|
p = Point(x=10, y=20)
|
||||||
return (self.x ** 2 + self.y ** 2) ** 0.5
|
assert p == loads(dumps(p))
|
||||||
def __str__(self):
|
|
||||||
return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
|
# test and demonstrate ability to override methods
|
||||||
|
class Point(namedtuple('Point', 'x y')):
|
||||||
for p in Point(3,4), Point(14,5), Point(9./7,6):
|
|
||||||
print p
|
@property
|
||||||
|
def hypot(self):
|
||||||
class Point(namedtuple('Point', 'x y')):
|
return (self.x ** 2 + self.y ** 2) ** 0.5
|
||||||
'Point class with optimized _make() and _replace() without error-checking'
|
|
||||||
_make = classmethod(tuple.__new__)
|
def __str__(self):
|
||||||
def _replace(self, _map=map, **kwds):
|
return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y,
|
||||||
return self._make(_map(kwds.get, ('x', 'y'), self))
|
self.hypot)
|
||||||
|
|
||||||
print Point(11, 22)._replace(x=100)
|
for p in Point(3, 4), Point(14, 5), Point(9. / 7, 6):
|
||||||
|
print p
|
||||||
import doctest
|
|
||||||
TestResults = namedtuple('TestResults', 'failed attempted')
|
class Point(namedtuple('Point', 'x y')):
|
||||||
print TestResults(*doctest.testmod())
|
'''Point class with optimized _make() and _replace()
|
||||||
|
without error-checking
|
||||||
|
'''
|
||||||
|
_make = classmethod(tuple.__new__)
|
||||||
|
|
||||||
|
def _replace(self, _map=map, **kwds):
|
||||||
|
return self._make(_map(kwds.get, ('x', 'y'), self))
|
||||||
|
|
||||||
|
print Point(11, 22)._replace(x=100)
|
||||||
|
|
||||||
|
import doctest
|
||||||
|
TestResults = namedtuple('TestResults', 'failed attempted')
|
||||||
|
print TestResults(*doctest.testmod())
|
||||||
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,303 +1,320 @@
|
|||||||
'''
|
'''
|
||||||
Created on 15. des. 2009
|
Created on 15. des. 2009
|
||||||
|
|
||||||
@author: pab
|
@author: pab
|
||||||
'''
|
'''
|
||||||
#import os
|
#import os
|
||||||
#import sys
|
#import sys
|
||||||
#import win32com
|
#import win32com
|
||||||
#from win32com.client.selecttlb import EnumTlbs
|
#from win32com.client.selecttlb import EnumTlbs
|
||||||
#typelib_mso = None
|
#typelib_mso = None
|
||||||
#typelib_msppt = None
|
#typelib_msppt = None
|
||||||
#for typelib in EnumTlbs():
|
# for typelib in EnumTlbs():
|
||||||
# d = typelib.desc.split(' ')
|
# d = typelib.desc.split(' ')
|
||||||
# if d[0] == 'Microsoft' and d[1] == 'Office' and d[3] == 'Object' and d[4] == 'Library':
|
# if d[0] == 'Microsoft' and d[1] == 'Office' and d[3] == 'Object' \
|
||||||
# typelib_mso = typelib
|
# and d[4] == 'Library':
|
||||||
# if d[0] == 'Microsoft' and d[1] == 'PowerPoint' and d[3] == 'Object' and d[4] == 'Library':
|
# typelib_mso = typelib
|
||||||
# typelib_msppt = typelib
|
# if d[0] == 'Microsoft' and d[1] == 'PowerPoint' and d[3] == 'Object' \
|
||||||
#if hasattr(sys, 'frozen'): # If we're an .exe file
|
# and d[4] == 'Library':
|
||||||
# win32com.__gen_path__ = os.path.dirname(sys.executable)
|
# typelib_msppt = typelib
|
||||||
## win32com.__gen_path__ = os.environ['TEMP']
|
# if hasattr(sys, 'frozen'): # If we're an .exe file
|
||||||
#if win32com.client.gencache.is_readonly:
|
# win32com.__gen_path__ = os.path.dirname(sys.executable)
|
||||||
# win32com.client.gencache.is_readonly = False
|
## win32com.__gen_path__ = os.environ['TEMP']
|
||||||
# win32com.client.gencache.Rebuild()
|
# if win32com.client.gencache.is_readonly:
|
||||||
#MSPPT = win32com.client.gencache.EnsureModule(typelib_msppt.clsid, typelib_msppt.lcid,
|
# win32com.client.gencache.is_readonly = False
|
||||||
# int(typelib_msppt.major), int(typelib_msppt.minor))
|
# win32com.client.gencache.Rebuild()
|
||||||
#MSO = win32com.client.gencache.EnsureModule(typelib_mso.clsid, typelib_mso.lcid,
|
# MSPPT = win32com.client.gencache.EnsureModule(typelib_msppt.clsid,
|
||||||
# int(typelib_mso.major), int(typelib_mso.minor))
|
# typelib_msppt.lcid,
|
||||||
import os
|
# int(typelib_msppt.major),
|
||||||
import warnings
|
# int(typelib_msppt.minor))
|
||||||
import win32com.client
|
# MSO = win32com.client.gencache.EnsureModule(typelib_mso.clsid,
|
||||||
import MSO
|
# typelib_mso.lcid,
|
||||||
import MSPPT
|
# int(typelib_mso.major), int(typelib_mso.minor))
|
||||||
from PIL import Image #@UnresolvedImport
|
import os
|
||||||
|
import warnings
|
||||||
g = globals()
|
import win32com.client
|
||||||
for c in dir(MSO.constants):
|
import MSO
|
||||||
g[c] = getattr(MSO.constants, c)
|
import MSPPT
|
||||||
for c in dir(MSPPT.constants):
|
from PIL import Image # @UnresolvedImport
|
||||||
g[c] = getattr(MSPPT.constants, c)
|
|
||||||
|
g = globals()
|
||||||
class Powerpoint(object):
|
for c in dir(MSO.constants):
|
||||||
def __init__(self, file_name=''):
|
g[c] = getattr(MSO.constants, c)
|
||||||
|
for c in dir(MSPPT.constants):
|
||||||
self.application = win32com.client.Dispatch("Powerpoint.Application")
|
g[c] = getattr(MSPPT.constants, c)
|
||||||
#self.application.Visible = True
|
|
||||||
self._visible = self.application.Visible
|
|
||||||
if file_name:
|
class Powerpoint(object):
|
||||||
self.presentation = self.application.Presentations.Open(file_name)
|
|
||||||
else:
|
def __init__(self, file_name=''):
|
||||||
self.presentation = self.application.Presentations.Add()
|
|
||||||
self.num_slides = 0
|
self.application = win32com.client.Dispatch("Powerpoint.Application")
|
||||||
# default picture width and height
|
#self.application.Visible = True
|
||||||
self.default_width = 500
|
self._visible = self.application.Visible
|
||||||
self.default_height = 400
|
if file_name:
|
||||||
self.title_font = 'Arial' #'Boopee'
|
self.presentation = self.application.Presentations.Open(file_name)
|
||||||
self.title_size = 36
|
else:
|
||||||
self.text_font = 'Arial' #'Boopee'
|
self.presentation = self.application.Presentations.Add()
|
||||||
self.text_size = 20
|
self.num_slides = 0
|
||||||
self.footer = ''
|
# default picture width and height
|
||||||
|
self.default_width = 500
|
||||||
def set_footer(self):
|
self.default_height = 400
|
||||||
'''
|
self.title_font = 'Arial' # 'Boopee'
|
||||||
Set Footer in SlideMaster and NotesMaster
|
self.title_size = 36
|
||||||
'''
|
self.text_font = 'Arial' # 'Boopee'
|
||||||
if self.footer:
|
self.text_size = 20
|
||||||
if self.presentation.HasTitleMaster:
|
self.footer = ''
|
||||||
TMHF = self.presentation.TitleMaster.HeadersFooters
|
|
||||||
TMHF.Footer.Text = self.footer
|
def set_footer(self):
|
||||||
TMHF.Footer.Visible = True
|
'''
|
||||||
|
Set Footer in SlideMaster and NotesMaster
|
||||||
SMHF = self.presentation.SlideMaster.HeadersFooters
|
'''
|
||||||
SMHF.Footer.Text = self.footer
|
if self.footer:
|
||||||
SMHF.Footer.Visible = True
|
if self.presentation.HasTitleMaster:
|
||||||
SMHF.SlideNumber.Visible= True
|
TMHF = self.presentation.TitleMaster.HeadersFooters
|
||||||
NMHF = self.presentation.NotesMaster.HeadersFooters
|
TMHF.Footer.Text = self.footer
|
||||||
NMHF.Footer.Text = self.footer
|
TMHF.Footer.Visible = True
|
||||||
NMHF.SlideNumber.Visible= True
|
|
||||||
for slide in self.presentation.Slides:
|
SMHF = self.presentation.SlideMaster.HeadersFooters
|
||||||
shapes = slide.Shapes
|
SMHF.Footer.Text = self.footer
|
||||||
for shape in shapes:
|
SMHF.Footer.Visible = True
|
||||||
if shape.Name=='Footer':
|
SMHF.SlideNumber.Visible = True
|
||||||
footer = shape
|
NMHF = self.presentation.NotesMaster.HeadersFooters
|
||||||
break
|
NMHF.Footer.Text = self.footer
|
||||||
else:
|
NMHF.SlideNumber.Visible = True
|
||||||
footer = shapes.AddTextbox(msoTextOrientationHorizontal, Left=0, Top=510, Width=720, Height=28.875) #@UndefinedVariable
|
for slide in self.presentation.Slides:
|
||||||
footer.Name = 'Footer'
|
shapes = slide.Shapes
|
||||||
footer.TextFrame.TextRange.Text = self.footer
|
for shape in shapes:
|
||||||
|
if shape.Name == 'Footer':
|
||||||
|
footer = shape
|
||||||
def add_title_slide(self, title, subtitle=''):
|
break
|
||||||
self.num_slides +=1
|
else:
|
||||||
slide = self.presentation.Slides.Add(self.num_slides, MSPPT.constants.ppLayoutTitle)
|
footer = shapes.AddTextbox(
|
||||||
|
msoTextOrientationHorizontal, # @UndefinedVariable
|
||||||
unused_title_id, unused_textbox_id = 1, 2
|
Left=0, Top=510, Width=720, Height=28.875)
|
||||||
for id_, title1 in enumerate([title, subtitle]):
|
footer.Name = 'Footer'
|
||||||
titlerange = slide.Shapes(id_+1).TextFrame.TextRange
|
footer.TextFrame.TextRange.Text = self.footer
|
||||||
titlerange.Text = title1
|
|
||||||
titlerange.Font.Name = self.title_font
|
def add_title_slide(self, title, subtitle=''):
|
||||||
titlerange.Font.Size = self.title_size-id_*12 if self.title_size>22 else self.title_size
|
self.num_slides += 1
|
||||||
|
slide = self.presentation.Slides.Add(
|
||||||
def add_slide(self, title='', texts='', notes='', image_file='',
|
self.num_slides, MSPPT.constants.ppLayoutTitle)
|
||||||
maxlevel=None, left=220, width=-1, height=-1):
|
|
||||||
self.num_slides +=1
|
unused_title_id, unused_textbox_id = 1, 2
|
||||||
slide = self.presentation.Slides.Add(self.num_slides, MSPPT.constants.ppLayoutText)
|
for id_, title1 in enumerate([title, subtitle]):
|
||||||
|
titlerange = slide.Shapes(id_ + 1).TextFrame.TextRange
|
||||||
self.add2slide(slide, title, texts, notes, image_file, maxlevel, left, width, height)
|
titlerange.Text = title1
|
||||||
return slide
|
titlerange.Font.Name = self.title_font
|
||||||
|
titlerange.Font.Size = self.title_size - id_ * \
|
||||||
def add2slide(self, slide, title='', texts='', notes='', image_file='',
|
12 if self.title_size > 22 else self.title_size
|
||||||
maxlevel=None, left=220, width=-1, height=-1, keep_aspect=True):
|
|
||||||
title_id, textbox_id = 1, 2
|
def add_slide(self, title='', texts='', notes='', image_file='',
|
||||||
if title:
|
maxlevel=None, left=220, width=-1, height=-1):
|
||||||
titlerange = slide.Shapes(title_id).TextFrame.TextRange
|
self.num_slides += 1
|
||||||
titlerange.Font.Name = self.title_font
|
slide = self.presentation.Slides.Add(
|
||||||
titlerange.Text = title
|
self.num_slides, MSPPT.constants.ppLayoutText)
|
||||||
titlerange.Font.Size = self.title_size
|
|
||||||
|
self.add2slide(slide, title, texts, notes, image_file, maxlevel, left,
|
||||||
if texts != '' and texts != ['']:
|
width, height)
|
||||||
#textrange = slide.Shapes(textbox_id).TextFrame.TextRange
|
return slide
|
||||||
self._add_text(slide, textbox_id, texts, maxlevel)
|
|
||||||
|
def add2slide(self, slide, title='', texts='', notes='', image_file='',
|
||||||
if image_file != '' and image_file != ['']:
|
maxlevel=None, left=220, width=-1, height=-1,
|
||||||
if keep_aspect:
|
keep_aspect=True):
|
||||||
im = Image.open(image_file)
|
title_id, textbox_id = 1, 2
|
||||||
t_w, t_h = im.size
|
if title:
|
||||||
if height<=0 and width<=0:
|
titlerange = slide.Shapes(title_id).TextFrame.TextRange
|
||||||
if t_w*self.default_height < t_h*self.default_width:
|
titlerange.Font.Name = self.title_font
|
||||||
height = self.default_height
|
titlerange.Text = title
|
||||||
else:
|
titlerange.Font.Size = self.title_size
|
||||||
width = self.default_width
|
|
||||||
if height<=0 and width:
|
if texts != '' and texts != ['']:
|
||||||
height = t_h * width / t_w
|
#textrange = slide.Shapes(textbox_id).TextFrame.TextRange
|
||||||
elif height and width <=0:
|
self._add_text(slide, textbox_id, texts, maxlevel)
|
||||||
width = t_w * height / t_h
|
|
||||||
|
if image_file != '' and image_file != ['']:
|
||||||
slide.Shapes.AddPicture(FileName=image_file, LinkToFile=False,
|
if keep_aspect:
|
||||||
SaveWithDocument=True,
|
im = Image.open(image_file)
|
||||||
Left=left, Top=110,
|
t_w, t_h = im.size
|
||||||
Width=width, Height=height) #400)
|
if height <= 0 and width <= 0:
|
||||||
if notes != '' and notes != ['']:
|
if t_w * self.default_height < t_h * self.default_width:
|
||||||
notespage = slide.NotesPage #.Shapes(2).TextFrame.TextRange
|
height = self.default_height
|
||||||
self._add_text(notespage, 2, notes)
|
else:
|
||||||
return slide
|
width = self.default_width
|
||||||
|
if height <= 0 and width:
|
||||||
def _add_text(self, page, id, txt, maxlevel=None): #@ReservedAssignment
|
height = t_h * width / t_w
|
||||||
page.Shapes(id).TextFrame.TextRange.Font.Name = self.text_font
|
elif height and width <= 0:
|
||||||
|
width = t_w * height / t_h
|
||||||
if isinstance(txt, dict):
|
|
||||||
self._add_text_from_dict(page, id, txt, 1, maxlevel)
|
slide.Shapes.AddPicture(FileName=image_file, LinkToFile=False,
|
||||||
elif isinstance(txt, (list, tuple)):
|
SaveWithDocument=True,
|
||||||
self._add_text_from_list(page, id, txt, maxlevel)
|
Left=left, Top=110,
|
||||||
else:
|
Width=width, Height=height) # 400)
|
||||||
unused_tr = page.Shapes(id).TextFrame.TextRange.InsertAfter(txt)
|
if notes != '' and notes != ['']:
|
||||||
unused_temp = page.Shapes(id).TextFrame.TextRange.InsertAfter('\r')
|
notespage = slide.NotesPage # .Shapes(2).TextFrame.TextRange
|
||||||
|
self._add_text(notespage, 2, notes)
|
||||||
page.Shapes(id).TextFrame.TextRange.Font.Size = self.text_size
|
return slide
|
||||||
|
|
||||||
def _add_text_from_dict(self, page, id, txt_dict, level, maxlevel=None): #@ReservedAssignment
|
def _add_text(self, page, id, txt, maxlevel=None): # @ReservedAssignment
|
||||||
if maxlevel is None or level<=maxlevel:
|
page.Shapes(id).TextFrame.TextRange.Font.Name = self.text_font
|
||||||
for name, subdict in txt_dict.iteritems():
|
|
||||||
tr = page.Shapes(id).TextFrame.TextRange.InsertAfter(name)
|
if isinstance(txt, dict):
|
||||||
unused_temp = page.Shapes(id).TextFrame.TextRange.InsertAfter('\r')
|
self._add_text_from_dict(page, id, txt, 1, maxlevel)
|
||||||
tr.IndentLevel = level
|
elif isinstance(txt, (list, tuple)):
|
||||||
self._add_text_from_dict(page, id, subdict, min(level+1,5), maxlevel)
|
self._add_text_from_list(page, id, txt, maxlevel)
|
||||||
|
else:
|
||||||
def _add_text_from_list(self, page, id, txt_list, maxlevel=None): #@ReservedAssignment
|
unused_tr = page.Shapes(id).TextFrame.TextRange.InsertAfter(txt)
|
||||||
for txt in txt_list:
|
unused_temp = page.Shapes(id).TextFrame.TextRange.InsertAfter('\r')
|
||||||
level = 1
|
|
||||||
while isinstance(txt, (list, tuple)):
|
page.Shapes(id).TextFrame.TextRange.Font.Size = self.text_size
|
||||||
txt = txt[0]
|
|
||||||
level += 1
|
def _add_text_from_dict(self, page, id, txt_dict, # @ReservedAssignment
|
||||||
if maxlevel is None or level<=maxlevel:
|
level, maxlevel=None):
|
||||||
tr = page.Shapes(id).TextFrame.TextRange.InsertAfter(txt)
|
if maxlevel is None or level <= maxlevel:
|
||||||
unused_temp = page.Shapes(id).TextFrame.TextRange.InsertAfter('\r')
|
for name, subdict in txt_dict.iteritems():
|
||||||
tr.IndentLevel = level
|
tr = page.Shapes(id).TextFrame.TextRange.InsertAfter(name)
|
||||||
|
unused_temp = page.Shapes(
|
||||||
|
id).TextFrame.TextRange.InsertAfter('\r')
|
||||||
def save(self, fullfile=''):
|
tr.IndentLevel = level
|
||||||
if fullfile:
|
self._add_text_from_dict(
|
||||||
self.presentation.SaveAs(FileName=fullfile)
|
page, id, subdict, min(level + 1, 5), maxlevel)
|
||||||
else:
|
|
||||||
self.presentation.Save()
|
def _add_text_from_list(self, page, id, # @ReservedAssignment
|
||||||
|
txt_list, maxlevel=None):
|
||||||
|
for txt in txt_list:
|
||||||
def quit(self): #@ReservedAssignment
|
level = 1
|
||||||
if self._visible:
|
while isinstance(txt, (list, tuple)):
|
||||||
self.presentation.Close()
|
txt = txt[0]
|
||||||
else:
|
level += 1
|
||||||
self.application.Quit()
|
if maxlevel is None or level <= maxlevel:
|
||||||
|
tr = page.Shapes(id).TextFrame.TextRange.InsertAfter(txt)
|
||||||
def quit_only_if_hidden(self):
|
unused_temp = page.Shapes(
|
||||||
if not self._visible:
|
id).TextFrame.TextRange.InsertAfter('\r')
|
||||||
self.application.Quit()
|
tr.IndentLevel = level
|
||||||
|
|
||||||
def test_powerpoint():
|
def save(self, fullfile=''):
|
||||||
# Make powerpoint
|
if fullfile:
|
||||||
|
self.presentation.SaveAs(FileName=fullfile)
|
||||||
ppt = Powerpoint()
|
else:
|
||||||
#time.
|
self.presentation.Save()
|
||||||
ppt.footer='This is the footer'
|
|
||||||
ppt.add_title_slide('Title', 'Per A.')
|
def quit(self): # @ReservedAssignment
|
||||||
ppt.add_slide(title='alsfkasldk', texts='asdflaf', notes='asdfas')
|
if self._visible:
|
||||||
ppt.set_footer()
|
self.presentation.Close()
|
||||||
|
else:
|
||||||
def make_ppt():
|
self.application.Quit()
|
||||||
application = win32com.client.Dispatch("Powerpoint.Application")
|
|
||||||
application.Visible = True
|
def quit_only_if_hidden(self):
|
||||||
presentation = application.Presentations.Add()
|
if not self._visible:
|
||||||
slide1 = presentation.Slides.Add(1, MSPPT.constants.ppLayoutText)
|
self.application.Quit()
|
||||||
|
|
||||||
|
|
||||||
# title = slide1.Shapes.AddTextBox(Type=msoTextOrientationHorizontal,Left=50, Top=10, Width=620, Height=70)
|
def test_powerpoint():
|
||||||
# title.TextFrame.TextRange.Text = 'Overskrift'
|
# Make powerpoint
|
||||||
|
|
||||||
|
ppt = Powerpoint()
|
||||||
title_id, textbox_id = 1,2
|
# time.
|
||||||
slide1.Shapes(title_id).TextFrame.TextRange.Text = 'Overskrift'
|
ppt.footer = 'This is the footer'
|
||||||
#slide1.Shapes(title_id).TextFrame.Width = 190
|
ppt.add_title_slide('Title', 'Per A.')
|
||||||
|
ppt.add_slide(title='alsfkasldk', texts='asdflaf', notes='asdfas')
|
||||||
|
ppt.set_footer()
|
||||||
slide1.Shapes(textbox_id).TextFrame.TextRange.InsertAfter('Test')
|
|
||||||
unused_tr = slide1.Shapes(textbox_id).TextFrame.TextRange.InsertAfter('\r')
|
|
||||||
slide1.Shapes(textbox_id).TextFrame.TextRange.IndentLevel = 1
|
def make_ppt():
|
||||||
tr = slide1.Shapes(textbox_id).TextFrame.TextRange.InsertAfter('tests')
|
application = win32com.client.Dispatch("Powerpoint.Application")
|
||||||
unused_tr0 = slide1.Shapes(textbox_id).TextFrame.TextRange.InsertAfter('\r')
|
application.Visible = True
|
||||||
tr.IndentLevel=2
|
presentation = application.Presentations.Add()
|
||||||
tr1 = slide1.Shapes(textbox_id).TextFrame.TextRange.InsertAfter('test3')
|
slide1 = presentation.Slides.Add(1, MSPPT.constants.ppLayoutText)
|
||||||
tr1.IndentLevel=3
|
|
||||||
#slide1.Shapes(textbox_id).TextFrame.TextRange.Text = 'Test \r test2'
|
# title = slide1.Shapes.AddTextBox(Type=msoTextOrientationHorizontal,
|
||||||
|
# Left=50, Top=10, Width=620, Height=70)
|
||||||
# textbox = slide1.Shapes.AddTextBox(Type=msoTextOrientationHorizontal,Left=30, Top=100, Width=190, Height=400)
|
# title.TextFrame.TextRange.Text = 'Overskrift'
|
||||||
# textbox.TextFrame.TextRange.Text = 'Test \r test2'
|
title_id, textbox_id = 1, 2
|
||||||
#picbox = slide1.Shapes(picb_id)
|
slide1.Shapes(title_id).TextFrame.TextRange.Text = 'Overskrift'
|
||||||
|
#slide1.Shapes(title_id).TextFrame.Width = 190
|
||||||
filename = r'c:\temp\data1_report1_and_2_Tr120_1.png'
|
|
||||||
slide1.Shapes.AddPicture(FileName=filename, LinkToFile=False,
|
slide1.Shapes(textbox_id).TextFrame.TextRange.InsertAfter('Test')
|
||||||
SaveWithDocument=True,
|
unused_tr = slide1.Shapes(textbox_id).TextFrame.TextRange.InsertAfter('\r')
|
||||||
Left=220, Top=100, Width=500, Height=420)
|
slide1.Shapes(textbox_id).TextFrame.TextRange.IndentLevel = 1
|
||||||
|
tr = slide1.Shapes(textbox_id).TextFrame.TextRange.InsertAfter('tests')
|
||||||
slide1.NotesPage.Shapes(2).TextFrame.TextRange.Text = 'test'
|
unused_tr0 = slide1.Shapes(
|
||||||
|
textbox_id).TextFrame.TextRange.InsertAfter('\r')
|
||||||
|
tr.IndentLevel = 2
|
||||||
|
tr1 = slide1.Shapes(textbox_id).TextFrame.TextRange.InsertAfter('test3')
|
||||||
# for shape in slide1.Shapes:
|
tr1.IndentLevel = 3
|
||||||
# shape.TextFrame.TextRange.Text = 'Test \r test2'
|
#slide1.Shapes(textbox_id).TextFrame.TextRange.Text = 'Test \r test2'
|
||||||
#slide1.Shapes.Titles.TextFrames.TestRange.Text
|
|
||||||
# shape = slide1.Shapes.AddShape(msoShapeRectangle, 300, 100, 400, 400)
|
# textbox = slide1.Shapes.AddTextBox(Type=msoTextOrientationHorizontal,
|
||||||
# shape.TextFrame.TextRange.Text = 'Test \n test2'
|
# Left=30, Top=100, Width=190, Height=400)
|
||||||
# shape.TextFrame.TextRange.Font.Size = 12
|
# textbox.TextFrame.TextRange.Text = 'Test \r test2'
|
||||||
|
#picbox = slide1.Shapes(picb_id)
|
||||||
#
|
|
||||||
# app = wx.PySimpleApp()
|
filename = r'c:\temp\data1_report1_and_2_Tr120_1.png'
|
||||||
# dialog = wx.FileDialog(None, 'Choose image file', defaultDir=os.getcwd(),
|
slide1.Shapes.AddPicture(FileName=filename, LinkToFile=False,
|
||||||
# wildcard='*.*',
|
SaveWithDocument=True,
|
||||||
# style=wx.OPEN | wx.CHANGE_DIR | wx.MULTIPLE)
|
Left=220, Top=100, Width=500, Height=420)
|
||||||
#
|
|
||||||
# if dialog.ShowModal() == wx.ID_OK:
|
slide1.NotesPage.Shapes(2).TextFrame.TextRange.Text = 'test'
|
||||||
# files_or_paths = dialog.GetPaths()
|
|
||||||
# for filename in files_or_paths:
|
|
||||||
# slide1.Shapes.AddPicture(FileName=filename, LinkToFile=False,
|
# for shape in slide1.Shapes:
|
||||||
# SaveWithDocument=True,
|
# shape.TextFrame.TextRange.Text = 'Test \r test2'
|
||||||
# Left=100, Top=100, Width=200, Height=200)
|
# slide1.Shapes.Titles.TextFrames.TestRange.Text
|
||||||
# dialog.Destroy()
|
# shape = slide1.Shapes.AddShape(msoShapeRectangle, 300, 100, 400, 400)
|
||||||
#presentation.Save()
|
# shape.TextFrame.TextRange.Text = 'Test \n test2'
|
||||||
#application.Quit()
|
# shape.TextFrame.TextRange.Font.Size = 12
|
||||||
def rename_ppt():
|
#
|
||||||
root = r'C:/pab/tsm_opeval/analysis_tsmps_aco_v2008b/plots'
|
# app = wx.PySimpleApp()
|
||||||
# root = r'C:/pab/tsm_opeval/analysis_tsmps_mag_v2008b/plots'
|
# dialog = wx.FileDialog(None, 'Choose image file', defaultDir=os.getcwd(),
|
||||||
# root = r'C:/pab/tsm_opeval/analysis_tsmps_mag_v2010a/plots'
|
# wildcard='*.*',
|
||||||
# root = r'C:/pab/tsm_opeval/analysis_tsmps_aco_v2010a/plots'
|
# style=wx.OPEN | wx.CHANGE_DIR | wx.MULTIPLE)
|
||||||
#filename = r'mag_sweep_best_tsmps_ship_eff0-10.ppt'
|
#
|
||||||
filenames = os.listdir(root)
|
# if dialog.ShowModal() == wx.ID_OK:
|
||||||
prefix = 'TSMPSv2008b_'
|
# files_or_paths = dialog.GetPaths()
|
||||||
#prefix = 'TSMPSv2010a_'
|
# for filename in files_or_paths:
|
||||||
for filename in filenames:
|
# slide1.Shapes.AddPicture(FileName=filename, LinkToFile=False,
|
||||||
if filename.endswith('.ppt'):
|
# SaveWithDocument=True,
|
||||||
try:
|
# Left=100, Top=100, Width=200, Height=200)
|
||||||
ppt = Powerpoint(os.path.join(root,filename))
|
# dialog.Destroy()
|
||||||
ppt.footer = prefix + filename
|
# presentation.Save()
|
||||||
ppt.set_footer()
|
# application.Quit()
|
||||||
ppt.save(os.path.join(root, ppt.footer))
|
def rename_ppt():
|
||||||
except:
|
root = r'C:/pab/tsm_opeval/analysis_tsmps_aco_v2008b/plots'
|
||||||
warnings.warn('Unable to load %s' % filename)
|
# root = r'C:/pab/tsm_opeval/analysis_tsmps_mag_v2008b/plots'
|
||||||
def load_file_into_ppt():
|
# root = r'C:/pab/tsm_opeval/analysis_tsmps_mag_v2010a/plots'
|
||||||
root = r'C:/pab/tsm_opeval/analysis_tsmps_aco_v2008b/plots'
|
# root = r'C:/pab/tsm_opeval/analysis_tsmps_aco_v2010a/plots'
|
||||||
# root = r'C:/pab/tsm_opeval/analysis_tsmps_mag_v2008b/plots'
|
#filename = r'mag_sweep_best_tsmps_ship_eff0-10.ppt'
|
||||||
# root = r'C:/pab/tsm_opeval/analysis_tsmps_mag_v2010a/plots'
|
filenames = os.listdir(root)
|
||||||
# root = r'C:/pab/tsm_opeval/analysis_tsmps_aco_v2010a/plots'
|
prefix = 'TSMPSv2008b_'
|
||||||
#filename = r'mag_sweep_best_tsmps_ship_eff0-10.ppt'
|
#prefix = 'TSMPSv2010a_'
|
||||||
filenames = os.listdir(root)
|
for filename in filenames:
|
||||||
prefix = 'TSMPSv2008b_'
|
if filename.endswith('.ppt'):
|
||||||
#prefix = 'TSMPSv2010a_'
|
try:
|
||||||
for filename in filenames:
|
ppt = Powerpoint(os.path.join(root, filename))
|
||||||
if filename.startswith(prefix) and filename.endswith('.ppt'):
|
ppt.footer = prefix + filename
|
||||||
try:
|
ppt.set_footer()
|
||||||
unused_ppt = Powerpoint(os.path.join(root,filename))
|
ppt.save(os.path.join(root, ppt.footer))
|
||||||
except:
|
except:
|
||||||
warnings.warn('Unable to load %s' % filename)
|
warnings.warn('Unable to load %s' % filename)
|
||||||
if __name__ == '__main__':
|
|
||||||
#make_ppt()
|
|
||||||
#test_powerpoint()
|
def load_file_into_ppt():
|
||||||
#load_file_into_ppt()
|
root = r'C:/pab/tsm_opeval/analysis_tsmps_aco_v2008b/plots'
|
||||||
rename_ppt()
|
# root = r'C:/pab/tsm_opeval/analysis_tsmps_mag_v2008b/plots'
|
||||||
|
# root = r'C:/pab/tsm_opeval/analysis_tsmps_mag_v2010a/plots'
|
||||||
|
# root = r'C:/pab/tsm_opeval/analysis_tsmps_aco_v2010a/plots'
|
||||||
|
#filename = r'mag_sweep_best_tsmps_ship_eff0-10.ppt'
|
||||||
|
filenames = os.listdir(root)
|
||||||
|
prefix = 'TSMPSv2008b_'
|
||||||
|
#prefix = 'TSMPSv2010a_'
|
||||||
|
for filename in filenames:
|
||||||
|
if filename.startswith(prefix) and filename.endswith('.ppt'):
|
||||||
|
try:
|
||||||
|
unused_ppt = Powerpoint(os.path.join(root, filename))
|
||||||
|
except:
|
||||||
|
warnings.warn('Unable to load %s' % filename)
|
||||||
|
if __name__ == '__main__':
|
||||||
|
# make_ppt()
|
||||||
|
# test_powerpoint()
|
||||||
|
# load_file_into_ppt()
|
||||||
|
rename_ppt()
|
||||||
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,76 +1,133 @@
|
|||||||
|
import unittest
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from wafo.spectrum.models import (Bretschneider, Jonswap, OchiHubble, Tmaspec,
|
|
||||||
Torsethaugen, McCormick, Wallop)
|
|
||||||
|
|
||||||
|
|
||||||
def test_bretschneider():
|
|
||||||
S = Bretschneider(Hm0=6.5, Tp=10)
|
|
||||||
vals = S((0, 1, 2, 3))
|
|
||||||
true_vals = np.array([0., 1.69350993, 0.06352698, 0.00844783])
|
|
||||||
assert((np.abs(vals - true_vals) < 1e-7).all())
|
|
||||||
|
|
||||||
|
|
||||||
def test_if_jonswap_with_gamma_one_equals_bretschneider():
|
|
||||||
S = Jonswap(Hm0=7, Tp=11, gamma=1)
|
|
||||||
vals = S((0, 1, 2, 3))
|
|
||||||
true_vals = np.array([0., 1.42694133, 0.05051648, 0.00669692])
|
|
||||||
assert((np.abs(vals - true_vals) < 1e-7).all())
|
|
||||||
|
|
||||||
w = np.linspace(0, 5)
|
|
||||||
S2 = Bretschneider(Hm0=7, Tp=11)
|
|
||||||
# JONSWAP with gamma=1 should be equal to Bretscneider:
|
|
||||||
assert(np.all(np.abs(S(w) - S2(w)) < 1.e-7))
|
|
||||||
|
|
||||||
|
|
||||||
def test_tmaspec():
|
|
||||||
S = Tmaspec(Hm0=7, Tp=11, gamma=1, h=10)
|
|
||||||
vals = S((0, 1, 2, 3))
|
|
||||||
true_vals = np.array([0., 0.70106233, 0.05022433, 0.00669692])
|
|
||||||
assert((np.abs(vals - true_vals) < 1e-7).all())
|
|
||||||
|
|
||||||
|
|
||||||
def test_torsethaugen():
|
|
||||||
|
|
||||||
S = Torsethaugen(Hm0=7, Tp=11, gamma=1, h=10)
|
|
||||||
vals = S((0, 1, 2, 3))
|
|
||||||
true_vals = np.array([0., 1.19989709, 0.05819794, 0.0093541])
|
|
||||||
assert((np.abs(vals - true_vals) < 1e-7).all())
|
|
||||||
|
|
||||||
vals = S.wind(range(4))
|
from wafo.spectrum.models import (Bretschneider, Jonswap, OchiHubble, Tmaspec,
|
||||||
true_vals = np.array([0., 1.13560528, 0.05529849, 0.00888989])
|
Torsethaugen, McCormick, Wallop, Spreading)
|
||||||
assert((np.abs(vals - true_vals) < 1e-7).all())
|
|
||||||
vals = S.swell(range(4))
|
|
||||||
true_vals = np.array([0., 0.0642918, 0.00289946, 0.00046421])
|
class TestCase(unittest.TestCase):
|
||||||
assert((np.abs(vals - true_vals) < 1e-7).all())
|
def assertListAlmostEqual(self, list1, list2, places=None, msg=None):
|
||||||
|
self.assertEqual(len(list1), len(list2))
|
||||||
|
for a, b in zip(list1, list2):
|
||||||
def test_ochihubble():
|
self.assertAlmostEqual(a, b, places, msg)
|
||||||
|
|
||||||
S = OchiHubble(par=2)
|
|
||||||
vals = S(range(4))
|
class TestSpectra(TestCase):
|
||||||
true_vals = np.array([0., 0.90155636, 0.04185445, 0.00583207])
|
def test_bretschneider(self):
|
||||||
assert((np.abs(vals - true_vals) < 1e-7).all())
|
S = Bretschneider(Hm0=6.5, Tp=10)
|
||||||
|
vals = S((0, 1, 2, 3)).tolist()
|
||||||
|
true_vals = [0., 1.69350993, 0.06352698, 0.00844783]
|
||||||
def test_mccormick():
|
self.assertListAlmostEqual(vals, true_vals)
|
||||||
|
|
||||||
S = McCormick(Hm0=6.5, Tp=10)
|
def test_if_jonswap_with_gamma_one_equals_bretschneider(self):
|
||||||
vals = S(range(4))
|
S = Jonswap(Hm0=7, Tp=11, gamma=1)
|
||||||
true_vals = np.array([0., 1.87865908, 0.15050447, 0.02994663])
|
vals = S((0, 1, 2, 3))
|
||||||
assert((np.abs(vals - true_vals) < 1e-7).all())
|
true_vals = np.array([0., 1.42694133, 0.05051648, 0.00669692])
|
||||||
|
self.assertListAlmostEqual(vals, true_vals)
|
||||||
|
w = np.linspace(0, 5)
|
||||||
def test_wallop():
|
S2 = Bretschneider(Hm0=7, Tp=11)
|
||||||
|
# JONSWAP with gamma=1 should be equal to Bretscneider:
|
||||||
S = Wallop(Hm0=6.5, Tp=10)
|
self.assertListAlmostEqual(S(w), S2(w))
|
||||||
vals = S(range(4))
|
|
||||||
true_vals = np.array([0.00000000e+00, 9.36921871e-01, 2.76991078e-03,
|
def test_tmaspec(self):
|
||||||
7.72996150e-05])
|
S = Tmaspec(Hm0=7, Tp=11, gamma=1, h=10)
|
||||||
assert((np.abs(vals - true_vals) < 1e-7).all())
|
vals = S((0, 1, 2, 3))
|
||||||
|
true_vals = np.array([0., 0.70106233, 0.05022433, 0.00669692])
|
||||||
|
self.assertListAlmostEqual(vals, true_vals)
|
||||||
|
|
||||||
|
def test_torsethaugen(self):
|
||||||
|
S = Torsethaugen(Hm0=7, Tp=11, gamma=1, h=10)
|
||||||
|
vals = S((0, 1, 2, 3))
|
||||||
|
true_vals = np.array([0., 1.19989709, 0.05819794, 0.0093541])
|
||||||
|
self.assertListAlmostEqual(vals, true_vals)
|
||||||
|
|
||||||
|
vals = S.wind(range(4))
|
||||||
|
true_vals = np.array([0., 1.13560528, 0.05529849, 0.00888989])
|
||||||
|
self.assertListAlmostEqual(vals, true_vals)
|
||||||
|
|
||||||
|
vals = S.swell(range(4))
|
||||||
|
true_vals = np.array([0., 0.0642918, 0.00289946, 0.00046421])
|
||||||
|
self.assertListAlmostEqual(vals, true_vals)
|
||||||
|
|
||||||
|
def test_ochihubble(self):
|
||||||
|
|
||||||
|
S = OchiHubble(par=2)
|
||||||
|
vals = S(range(4))
|
||||||
|
true_vals = np.array([0., 0.90155636, 0.04185445, 0.00583207])
|
||||||
|
self.assertListAlmostEqual(vals, true_vals)
|
||||||
|
|
||||||
|
def test_mccormick(self):
|
||||||
|
|
||||||
|
S = McCormick(Hm0=6.5, Tp=10)
|
||||||
|
vals = S(range(4))
|
||||||
|
true_vals = np.array([0., 1.87865908, 0.15050447, 0.02994663])
|
||||||
|
self.assertListAlmostEqual(vals, true_vals)
|
||||||
|
|
||||||
|
def test_wallop(self):
|
||||||
|
S = Wallop(Hm0=6.5, Tp=10)
|
||||||
|
vals = S(range(4))
|
||||||
|
true_vals = np.array([0.00000000e+00, 9.36921871e-01, 2.76991078e-03,
|
||||||
|
7.72996150e-05])
|
||||||
|
self.assertListAlmostEqual(vals, true_vals)
|
||||||
|
|
||||||
|
|
||||||
|
class TestSpreading(TestCase):
|
||||||
|
def test_cos2s(self):
|
||||||
|
theta = np.linspace(0, 2 * np.pi)
|
||||||
|
d = Spreading(type='cos2s')
|
||||||
|
dvals = [[1.10168934e+00],
|
||||||
|
[1.03576796e+00],
|
||||||
|
[8.60302298e-01],
|
||||||
|
[6.30309013e-01],
|
||||||
|
[4.06280137e-01],
|
||||||
|
[2.29514882e-01],
|
||||||
|
[1.13052757e-01],
|
||||||
|
[4.82339343e-02],
|
||||||
|
[1.76754409e-02],
|
||||||
|
[5.50490020e-03],
|
||||||
|
[1.43800617e-03],
|
||||||
|
[3.09907242e-04],
|
||||||
|
[5.39672445e-05],
|
||||||
|
[7.39553743e-06],
|
||||||
|
[7.70796579e-07],
|
||||||
|
[5.84247670e-08],
|
||||||
|
[3.03264905e-09],
|
||||||
|
[9.91950201e-11],
|
||||||
|
[1.81442131e-12],
|
||||||
|
[1.55028269e-14],
|
||||||
|
[4.63223469e-17],
|
||||||
|
[2.90526245e-20],
|
||||||
|
[1.35842977e-24],
|
||||||
|
[3.26077455e-31],
|
||||||
|
[1.65021852e-45],
|
||||||
|
[1.65021852e-45],
|
||||||
|
[3.26077455e-31],
|
||||||
|
[1.35842977e-24],
|
||||||
|
[2.90526245e-20],
|
||||||
|
[4.63223469e-17],
|
||||||
|
[1.55028269e-14],
|
||||||
|
[1.81442131e-12],
|
||||||
|
[9.91950201e-11],
|
||||||
|
[3.03264905e-09],
|
||||||
|
[5.84247670e-08],
|
||||||
|
[7.70796579e-07],
|
||||||
|
[7.39553743e-06],
|
||||||
|
[5.39672445e-05],
|
||||||
|
[3.09907242e-04],
|
||||||
|
[1.43800617e-03],
|
||||||
|
[5.50490020e-03],
|
||||||
|
[1.76754409e-02],
|
||||||
|
[4.82339343e-02],
|
||||||
|
[1.13052757e-01],
|
||||||
|
[2.29514882e-01],
|
||||||
|
[4.06280137e-01],
|
||||||
|
[6.30309013e-01],
|
||||||
|
[8.60302298e-01],
|
||||||
|
[1.03576796e+00],
|
||||||
|
[1.10168934e+00]]
|
||||||
|
|
||||||
|
self.assertListAlmostEqual(d(theta)[0], dvals)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
# main()
|
unittest.main()
|
||||||
import nose
|
|
||||||
nose.run()
|
|
||||||
#test_tmaspec()
|
|
||||||
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,116 @@
|
|||||||
|
"""
|
||||||
|
Sane parameters for stats.distributions.
|
||||||
|
"""
|
||||||
|
|
||||||
|
distcont = [
|
||||||
|
['alpha', (3.5704770516650459,)],
|
||||||
|
['anglit', ()],
|
||||||
|
['arcsine', ()],
|
||||||
|
['beta', (2.3098496451481823, 0.62687954300963677)],
|
||||||
|
['betaprime', (5, 6)],
|
||||||
|
['bradford', (0.29891359763170633,)],
|
||||||
|
['burr', (10.5, 4.3)],
|
||||||
|
['cauchy', ()],
|
||||||
|
['chi', (78,)],
|
||||||
|
['chi2', (55,)],
|
||||||
|
['cosine', ()],
|
||||||
|
['dgamma', (1.1023326088288166,)],
|
||||||
|
['dweibull', (2.0685080649914673,)],
|
||||||
|
['erlang', (10,)],
|
||||||
|
['expon', ()],
|
||||||
|
['exponpow', (2.697119160358469,)],
|
||||||
|
['exponweib', (2.8923945291034436, 1.9505288745913174)],
|
||||||
|
['f', (29, 18)],
|
||||||
|
['fatiguelife', (29,)], # correction numargs = 1
|
||||||
|
['fisk', (3.0857548622253179,)],
|
||||||
|
['foldcauchy', (4.7164673455831894,)],
|
||||||
|
['foldnorm', (1.9521253373555869,)],
|
||||||
|
['frechet_l', (3.6279911255583239,)],
|
||||||
|
['frechet_r', (1.8928171603534227,)],
|
||||||
|
['gamma', (1.9932305483800778,)],
|
||||||
|
['gausshyper', (13.763771604130699, 3.1189636648681431,
|
||||||
|
2.5145980350183019, 5.1811649903971615)], # veryslow
|
||||||
|
['genexpon', (9.1325976465418908, 16.231956600590632, 3.2819552690843983)],
|
||||||
|
['genextreme', (-0.1,)],
|
||||||
|
['gengamma', (4.4162385429431925, 3.1193091679242761)],
|
||||||
|
['genhalflogistic', (0.77274727809929322,)],
|
||||||
|
['genlogistic', (0.41192440799679475,)],
|
||||||
|
['genpareto', (0.1,)], # use case with finite moments
|
||||||
|
['gilbrat', ()],
|
||||||
|
['gompertz', (0.94743713075105251,)],
|
||||||
|
['gumbel_l', ()],
|
||||||
|
['gumbel_r', ()],
|
||||||
|
['halfcauchy', ()],
|
||||||
|
['halflogistic', ()],
|
||||||
|
['halfnorm', ()],
|
||||||
|
['hypsecant', ()],
|
||||||
|
['invgamma', (4.0668996136993067,)],
|
||||||
|
['invgauss', (0.14546264555347513,)],
|
||||||
|
['invweibull', (10.58,)],
|
||||||
|
['johnsonsb', (4.3172675099141058, 3.1837781130785063)],
|
||||||
|
['johnsonsu', (2.554395574161155, 2.2482281679651965)],
|
||||||
|
['ksone', (1000,)], # replace 22 by 100 to avoid failing range, ticket 956
|
||||||
|
['kstwobign', ()],
|
||||||
|
['laplace', ()],
|
||||||
|
['levy', ()],
|
||||||
|
['levy_l', ()],
|
||||||
|
['levy_stable', (0.35667405469844993,
|
||||||
|
-0.67450531578494011)], # NotImplementedError
|
||||||
|
# rvs not tested
|
||||||
|
['loggamma', (0.41411931826052117,)],
|
||||||
|
['logistic', ()],
|
||||||
|
['loglaplace', (3.2505926592051435,)],
|
||||||
|
['lognorm', (0.95368226960575331,)],
|
||||||
|
['lomax', (1.8771398388773268,)],
|
||||||
|
['maxwell', ()],
|
||||||
|
['mielke', (10.4, 3.6)],
|
||||||
|
['nakagami', (4.9673794866666237,)],
|
||||||
|
['ncf', (27, 27, 0.41578441799226107)],
|
||||||
|
['nct', (14, 0.24045031331198066)],
|
||||||
|
['ncx2', (21, 1.0560465975116415)],
|
||||||
|
['norm', ()],
|
||||||
|
['pareto', (2.621716532144454,)],
|
||||||
|
['pearson3', (0.1,)],
|
||||||
|
['powerlaw', (1.6591133289905851,)],
|
||||||
|
['powerlognorm', (2.1413923530064087, 0.44639540782048337)],
|
||||||
|
['powernorm', (4.4453652254590779,)],
|
||||||
|
['rayleigh', ()],
|
||||||
|
['rdist', (0.9,)], # feels also slow
|
||||||
|
['recipinvgauss', (0.63004267809369119,)],
|
||||||
|
['reciprocal', (0.0062309367010521255, 1.0062309367010522)],
|
||||||
|
['rice', (0.7749725210111873,)],
|
||||||
|
['semicircular', ()],
|
||||||
|
['t', (2.7433514990818093,)],
|
||||||
|
['triang', (0.15785029824528218,)],
|
||||||
|
['truncexpon', (4.6907725456810478,)],
|
||||||
|
['truncnorm', (-1.0978730080013919, 2.7306754109031979)],
|
||||||
|
['truncnorm', (0.1, 2.)],
|
||||||
|
['tukeylambda', (3.1321477856738267,)],
|
||||||
|
['uniform', ()],
|
||||||
|
['vonmises', (3.9939042581071398,)],
|
||||||
|
['vonmises_line', (3.9939042581071398,)],
|
||||||
|
['wald', ()],
|
||||||
|
['weibull_max', (2.8687961709100187,)],
|
||||||
|
['weibull_min', (1.7866166930421596,)],
|
||||||
|
['wrapcauchy', (0.031071279018614728,)]]
|
||||||
|
|
||||||
|
|
||||||
|
distdiscrete = [
|
||||||
|
['bernoulli',(0.3,)],
|
||||||
|
['binom', (5, 0.4)],
|
||||||
|
['boltzmann',(1.4, 19)],
|
||||||
|
['dlaplace', (0.8,)], # 0.5
|
||||||
|
['geom', (0.5,)],
|
||||||
|
['hypergeom',(30, 12, 6)],
|
||||||
|
['hypergeom',(21,3,12)], # numpy.random (3,18,12) numpy ticket:921
|
||||||
|
['hypergeom',(21,18,11)], # numpy.random (18,3,11) numpy ticket:921
|
||||||
|
['logser', (0.6,)], # reenabled, numpy ticket:921
|
||||||
|
['nbinom', (5, 0.5)],
|
||||||
|
['nbinom', (0.4, 0.4)], # from tickets: 583
|
||||||
|
['planck', (0.51,)], # 4.1
|
||||||
|
['poisson', (0.6,)],
|
||||||
|
['randint', (7, 31)],
|
||||||
|
['skellam', (15, 8)],
|
||||||
|
['zipf', (6.5,)]
|
||||||
|
]
|
||||||
|
|
@ -0,0 +1,54 @@
|
|||||||
|
"""Functions copypasted from newer versions of numpy.
|
||||||
|
|
||||||
|
"""
|
||||||
|
from __future__ import division, print_function, absolute_import
|
||||||
|
|
||||||
|
import warnings
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from scipy.lib._version import NumpyVersion
|
||||||
|
|
||||||
|
if NumpyVersion(np.__version__) > '1.7.0.dev':
|
||||||
|
_assert_warns = np.testing.assert_warns
|
||||||
|
else:
|
||||||
|
def _assert_warns(warning_class, func, *args, **kw):
|
||||||
|
r"""
|
||||||
|
Fail unless the given callable throws the specified warning.
|
||||||
|
|
||||||
|
This definition is copypasted from numpy 1.9.0.dev.
|
||||||
|
The version in earlier numpy returns None.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
warning_class : class
|
||||||
|
The class defining the warning that `func` is expected to throw.
|
||||||
|
func : callable
|
||||||
|
The callable to test.
|
||||||
|
*args : Arguments
|
||||||
|
Arguments passed to `func`.
|
||||||
|
**kwargs : Kwargs
|
||||||
|
Keyword arguments passed to `func`.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
The value returned by `func`.
|
||||||
|
|
||||||
|
"""
|
||||||
|
with warnings.catch_warnings(record=True) as l:
|
||||||
|
warnings.simplefilter('always')
|
||||||
|
result = func(*args, **kw)
|
||||||
|
if not len(l) > 0:
|
||||||
|
raise AssertionError("No warning raised when calling %s"
|
||||||
|
% func.__name__)
|
||||||
|
if not l[0].category is warning_class:
|
||||||
|
raise AssertionError("First warning for %s is not a "
|
||||||
|
"%s( is %s)" % (func.__name__, warning_class, l[0]))
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
if NumpyVersion(np.__version__) >= '1.6.0':
|
||||||
|
count_nonzero = np.count_nonzero
|
||||||
|
else:
|
||||||
|
def count_nonzero(a):
|
||||||
|
return (a != 0).sum()
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,209 +1,221 @@
|
|||||||
'''
|
'''
|
||||||
'''
|
'''
|
||||||
from __future__ import division
|
from __future__ import division
|
||||||
#import numpy as np
|
#import numpy as np
|
||||||
from numpy import trapz, sqrt, linspace #@UnresolvedImport
|
from numpy import trapz, sqrt, linspace # @UnresolvedImport
|
||||||
|
|
||||||
from wafo.wafodata import PlotData
|
from wafo.containers import PlotData
|
||||||
from wafo.misc import tranproc #, trangood
|
from wafo.misc import tranproc # , trangood
|
||||||
|
|
||||||
__all__ = ['TrData', 'TrCommon']
|
__all__ = ['TrData', 'TrCommon']
|
||||||
|
|
||||||
class TrCommon(object):
|
|
||||||
"""
|
class TrCommon(object):
|
||||||
<generic> transformation model, g.
|
|
||||||
|
"""
|
||||||
Information about the moments of the process can be obtained by site
|
<generic> transformation model, g.
|
||||||
specific data, laboratory measurements or by resort to theoretical models.
|
|
||||||
|
Information about the moments of the process can be obtained by site
|
||||||
Assumption
|
specific data, laboratory measurements or by resort to theoretical models.
|
||||||
----------
|
|
||||||
The Gaussian process, Y, distributed N(0,1) is related to the
|
Assumption
|
||||||
non-Gaussian process, X, by Y = g(X).
|
----------
|
||||||
|
The Gaussian process, Y, distributed N(0,1) is related to the
|
||||||
Methods
|
non-Gaussian process, X, by Y = g(X).
|
||||||
-------
|
|
||||||
dist2gauss : Returns a measure of departure from the Gaussian model, i.e.,
|
Methods
|
||||||
int (g(x)-xn)**2 dx where int. limits are given by X.
|
-------
|
||||||
dat2gauss : Transform non-linear data to Gaussian scale
|
dist2gauss : Returns a measure of departure from the Gaussian model, i.e.,
|
||||||
gauss2dat : Transform Gaussian data to non-linear scale
|
int (g(x)-xn)**2 dx where int. limits are given by X.
|
||||||
|
dat2gauss : Transform non-linear data to Gaussian scale
|
||||||
Member variables
|
gauss2dat : Transform Gaussian data to non-linear scale
|
||||||
----------------
|
|
||||||
mean, sigma, skew, kurt : real, scalar
|
Member variables
|
||||||
mean, standard-deviation, skewness and kurtosis, respectively, of the
|
----------------
|
||||||
non-Gaussian process. Default mean=0, sigma=1, skew=0.16, kurt=3.04.
|
mean, sigma, skew, kurt : real, scalar
|
||||||
skew=kurt-3=0 for a Gaussian process.
|
mean, standard-deviation, skewness and kurtosis, respectively, of the
|
||||||
"""
|
non-Gaussian process. Default mean=0, sigma=1, skew=0.16, kurt=3.04.
|
||||||
|
skew=kurt-3=0 for a Gaussian process.
|
||||||
def __init__(self, mean=0.0, var=1.0, skew=0.16, kurt=3.04, *args, **kwds):
|
"""
|
||||||
sigma = kwds.get('sigma',None)
|
|
||||||
if sigma is None:
|
def __init__(self, mean=0.0, var=1.0, skew=0.16, kurt=3.04, *args, **kwds):
|
||||||
sigma = sqrt(var)
|
sigma = kwds.get('sigma', None)
|
||||||
self.mean = mean
|
if sigma is None:
|
||||||
self.sigma = sigma
|
sigma = sqrt(var)
|
||||||
self.skew = skew
|
self.mean = mean
|
||||||
self.kurt = kurt
|
self.sigma = sigma
|
||||||
# Mean and std in the Gaussian world:
|
self.skew = skew
|
||||||
self.ymean = kwds.get('ymean', 0e0)
|
self.kurt = kurt
|
||||||
self.ysigma = kwds.get('ysigma', 1e0)
|
# Mean and std in the Gaussian world:
|
||||||
|
self.ymean = kwds.get('ymean', 0e0)
|
||||||
def __call__(self, x, *xi):
|
self.ysigma = kwds.get('ysigma', 1e0)
|
||||||
return self._dat2gauss(x, *xi)
|
|
||||||
|
def __call__(self, x, *xi):
|
||||||
def dist2gauss(self, x=None, xnmin=-5, xnmax=5, n=513):
|
return self._dat2gauss(x, *xi)
|
||||||
"""
|
|
||||||
Return a measure of departure from the Gaussian model.
|
def dist2gauss(self, x=None, xnmin=-5, xnmax=5, n=513):
|
||||||
|
"""
|
||||||
Parameters
|
Return a measure of departure from the Gaussian model.
|
||||||
----------
|
|
||||||
x : vector (default sigma*linspace(xnmin,xnmax,n)+mean)
|
Parameters
|
||||||
xnmin : real, scalar
|
----------
|
||||||
minimum on normalized scale
|
x : vector (default sigma*linspace(xnmin,xnmax,n)+mean)
|
||||||
xnmax : real, scalar
|
xnmin : real, scalar
|
||||||
maximum on normalized scale
|
minimum on normalized scale
|
||||||
n : integer, scalar
|
xnmax : real, scalar
|
||||||
number of evaluation points
|
maximum on normalized scale
|
||||||
|
n : integer, scalar
|
||||||
|
number of evaluation points
|
||||||
Returns
|
|
||||||
-------
|
|
||||||
t0 : real, scalar
|
Returns
|
||||||
a measure of departure from the Gaussian model calculated as
|
-------
|
||||||
trapz((xn-g(x))**2., xn) where int. limits is given by X.
|
t0 : real, scalar
|
||||||
"""
|
a measure of departure from the Gaussian model calculated as
|
||||||
if x is None:
|
trapz((xn-g(x))**2., xn) where int. limits is given by X.
|
||||||
xn = linspace(xnmin, xnmax, n)
|
"""
|
||||||
x = self.sigma*xn+self.mean
|
if x is None:
|
||||||
else:
|
xn = linspace(xnmin, xnmax, n)
|
||||||
xn = (x-self.mean)/self.sigma
|
x = self.sigma * xn + self.mean
|
||||||
|
else:
|
||||||
yn = (self._dat2gauss(x)-self.ymean)/self.ysigma
|
xn = (x - self.mean) / self.sigma
|
||||||
t0 = trapz((xn-yn)**2., xn)
|
|
||||||
return t0
|
yn = (self._dat2gauss(x) - self.ymean) / self.ysigma
|
||||||
|
t0 = trapz((xn - yn) ** 2., xn)
|
||||||
def gauss2dat(self, y, *yi):
|
return t0
|
||||||
"""
|
|
||||||
Transforms Gaussian data, y, to non-linear scale.
|
def gauss2dat(self, y, *yi):
|
||||||
|
"""
|
||||||
Parameters
|
Transforms Gaussian data, y, to non-linear scale.
|
||||||
----------
|
|
||||||
y, y1,..., yn : array-like
|
Parameters
|
||||||
input vectors with Gaussian data values, where yi is the i'th time
|
----------
|
||||||
derivative of y. (n<=4)
|
y, y1,..., yn : array-like
|
||||||
Returns
|
input vectors with Gaussian data values, where yi is the i'th time
|
||||||
-------
|
derivative of y. (n<=4)
|
||||||
x, x1,...,xn : array-like
|
Returns
|
||||||
transformed data to a non-linear scale
|
-------
|
||||||
|
x, x1,...,xn : array-like
|
||||||
See also
|
transformed data to a non-linear scale
|
||||||
--------
|
|
||||||
dat2gauss
|
See also
|
||||||
tranproc
|
--------
|
||||||
"""
|
dat2gauss
|
||||||
return self._gauss2dat(y, *yi)
|
tranproc
|
||||||
def _gauss2dat(self, y, *yi):
|
"""
|
||||||
pass
|
return self._gauss2dat(y, *yi)
|
||||||
def dat2gauss(self, x, *xi):
|
|
||||||
"""
|
def _gauss2dat(self, y, *yi):
|
||||||
Transforms non-linear data, x, to Gaussian scale.
|
pass
|
||||||
|
|
||||||
Parameters
|
def dat2gauss(self, x, *xi):
|
||||||
----------
|
"""
|
||||||
x, x1,...,xn : array-like
|
Transforms non-linear data, x, to Gaussian scale.
|
||||||
input vectors with non-linear data values, where xi is the i'th time
|
|
||||||
derivative of x. (n<=4)
|
Parameters
|
||||||
Returns
|
----------
|
||||||
-------
|
x, x1,...,xn : array-like
|
||||||
y, y1,...,yn : array-like
|
input vectors with non-linear data values, where xi is the i'th
|
||||||
transformed data to a Gaussian scale
|
time derivative of x. (n<=4)
|
||||||
|
Returns
|
||||||
See also
|
-------
|
||||||
--------
|
y, y1,...,yn : array-like
|
||||||
gauss2dat
|
transformed data to a Gaussian scale
|
||||||
tranproc.
|
|
||||||
"""
|
See also
|
||||||
return self._dat2gauss(x, *xi)
|
--------
|
||||||
def _dat2gauss(self, x, *xi):
|
gauss2dat
|
||||||
pass
|
tranproc.
|
||||||
|
"""
|
||||||
class TrData(PlotData, TrCommon):
|
return self._dat2gauss(x, *xi)
|
||||||
__doc__ = TrCommon.__doc__.split('mean')[0].replace('<generic>','Data' #@ReservedAssignment
|
|
||||||
) + """
|
def _dat2gauss(self, x, *xi):
|
||||||
data : array-like
|
pass
|
||||||
Gaussian values, Y
|
|
||||||
args : array-like
|
|
||||||
non-Gaussian values, X
|
class TrData(PlotData, TrCommon):
|
||||||
ymean, ysigma : real, scalars (default ymean=0, ysigma=1)
|
__doc__ = TrCommon.__doc__.split('mean')[0].replace('<generic>',
|
||||||
mean and standard-deviation, respectively, of the process in Gaussian world.
|
'Data') + """
|
||||||
mean, sigma : real, scalars
|
data : array-like
|
||||||
mean and standard-deviation, respectively, of the non-Gaussian process.
|
Gaussian values, Y
|
||||||
Default:
|
args : array-like
|
||||||
mean = self.gauss2dat(ymean),
|
non-Gaussian values, X
|
||||||
sigma = (self.gauss2dat(ysigma)-self.gauss2dat(-ysigma))/2
|
ymean, ysigma : real, scalars (default ymean=0, ysigma=1)
|
||||||
|
mean and standard-deviation, respectively, of the process in Gaussian
|
||||||
Example
|
world.
|
||||||
-------
|
mean, sigma : real, scalars
|
||||||
Construct a linear transformation model
|
mean and standard-deviation, respectively, of the non-Gaussian process.
|
||||||
>>> import numpy as np
|
Default:
|
||||||
>>> import wafo.transform as wt
|
mean = self.gauss2dat(ymean),
|
||||||
>>> sigma = 5; mean = 1
|
sigma = (self.gauss2dat(ysigma)-self.gauss2dat(-ysigma))/2
|
||||||
>>> u = np.linspace(-5,5); x = sigma*u+mean; y = u
|
|
||||||
>>> g = wt.TrData(y,x)
|
Example
|
||||||
>>> g.mean
|
-------
|
||||||
array([ 1.])
|
Construct a linear transformation model
|
||||||
>>> g.sigma
|
>>> import numpy as np
|
||||||
array([ 5.])
|
>>> import wafo.transform as wt
|
||||||
|
>>> sigma = 5; mean = 1
|
||||||
>>> g = wt.TrData(y,x,mean=1,sigma=5)
|
>>> u = np.linspace(-5,5); x = sigma*u+mean; y = u
|
||||||
>>> g.mean
|
>>> g = wt.TrData(y,x)
|
||||||
1
|
>>> g.mean
|
||||||
>>> g.sigma
|
array([ 1.])
|
||||||
5
|
>>> g.sigma
|
||||||
>>> g.dat2gauss(1,2,3)
|
array([ 5.])
|
||||||
[array([ 0.]), array([ 0.4]), array([ 0.6])]
|
|
||||||
|
>>> g = wt.TrData(y,x,mean=1,sigma=5)
|
||||||
Check that the departure from a Gaussian model is zero
|
>>> g.mean
|
||||||
>>> g.dist2gauss() < 1e-16
|
1
|
||||||
True
|
>>> g.sigma
|
||||||
"""
|
5
|
||||||
def __init__(self, *args, **kwds):
|
>>> g.dat2gauss(1,2,3)
|
||||||
options = dict(title='Transform',
|
[array([ 0.]), array([ 0.4]), array([ 0.6])]
|
||||||
xlab='x', ylab='g(x)',
|
|
||||||
plot_args=['r'],
|
Check that the departure from a Gaussian model is zero
|
||||||
plot_args_children=['g--'],)
|
>>> g.dist2gauss() < 1e-16
|
||||||
options.update(**kwds)
|
True
|
||||||
super(TrData, self).__init__(*args, **options)
|
"""
|
||||||
self.ymean = kwds.get('ymean', 0e0)
|
|
||||||
self.ysigma = kwds.get('ysigma', 1e0)
|
def __init__(self, *args, **kwds):
|
||||||
self.mean = kwds.get('mean', None)
|
options = dict(title='Transform',
|
||||||
self.sigma = kwds.get('sigma', None)
|
xlab='x', ylab='g(x)',
|
||||||
|
plot_args=['r'],
|
||||||
if self.mean is None:
|
plot_args_children=['g--'],)
|
||||||
#self.mean = np.mean(self.args) #
|
options.update(**kwds)
|
||||||
self.mean = self.gauss2dat(self.ymean)
|
super(TrData, self).__init__(*args, **options)
|
||||||
if self.sigma is None:
|
self.ymean = kwds.get('ymean', 0e0)
|
||||||
yp = self.ymean+self.ysigma
|
self.ysigma = kwds.get('ysigma', 1e0)
|
||||||
ym = self.ymean-self.ysigma
|
self.mean = kwds.get('mean', None)
|
||||||
self.sigma = (self.gauss2dat(yp)-self.gauss2dat(ym))/2.
|
self.sigma = kwds.get('sigma', None)
|
||||||
|
|
||||||
self.children = [PlotData((self.args-self.mean)/self.sigma, self.args)]
|
if self.mean is None:
|
||||||
|
#self.mean = np.mean(self.args) #
|
||||||
def trdata(self):
|
self.mean = self.gauss2dat(self.ymean)
|
||||||
return self
|
if self.sigma is None:
|
||||||
|
yp = self.ymean + self.ysigma
|
||||||
def _gauss2dat(self, y, *yi):
|
ym = self.ymean - self.ysigma
|
||||||
return tranproc(self.data, self.args, y, *yi)
|
self.sigma = (self.gauss2dat(yp) - self.gauss2dat(ym)) / 2.
|
||||||
|
|
||||||
def _dat2gauss(self, x, *xi):
|
self.children = [
|
||||||
return tranproc(self.args, self.data, x, *xi)
|
PlotData((self.args - self.mean) / self.sigma, self.args)]
|
||||||
|
|
||||||
def main():
|
def trdata(self):
|
||||||
pass
|
return self
|
||||||
|
|
||||||
if __name__ == '__main__':
|
def _gauss2dat(self, y, *yi):
|
||||||
if True: #False : #
|
return tranproc(self.data, self.args, y, *yi)
|
||||||
import doctest
|
|
||||||
doctest.testmod()
|
def _dat2gauss(self, x, *xi):
|
||||||
else:
|
return tranproc(self.args, self.data, x, *xi)
|
||||||
main()
|
|
||||||
|
class EstimateTransform(object):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def main():
|
||||||
|
pass
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
if True: # False : #
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
else:
|
||||||
|
main()
|
||||||
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,206 +1,210 @@
|
|||||||
"""
|
"""
|
||||||
Dispersion relation module
|
Dispersion relation module
|
||||||
--------------------------
|
--------------------------
|
||||||
k2w - Translates from wave number to frequency
|
k2w - Translates from wave number to frequency
|
||||||
w2k - Translates from frequency to wave number
|
w2k - Translates from frequency to wave number
|
||||||
"""
|
"""
|
||||||
import warnings
|
import warnings
|
||||||
#import numpy as np
|
#import numpy as np
|
||||||
from numpy import (atleast_1d, sqrt, ones_like, zeros_like, arctan2, where, tanh, any, #@UnresolvedImport
|
from numpy import (atleast_1d, sqrt, ones_like, zeros_like, arctan2, where,
|
||||||
sin, cos, sign, inf, flatnonzero, finfo, cosh, abs) #@UnresolvedImport
|
tanh, any, sin, cos, sign, inf,
|
||||||
|
flatnonzero, finfo, cosh, abs)
|
||||||
__all__ = ['k2w', 'w2k']
|
|
||||||
|
__all__ = ['k2w', 'w2k']
|
||||||
def k2w(k1, k2=0e0, h=inf, g=9.81, u1=0e0, u2=0e0):
|
|
||||||
''' Translates from wave number to frequency
|
|
||||||
using the dispersion relation
|
def k2w(k1, k2=0e0, h=inf, g=9.81, u1=0e0, u2=0e0):
|
||||||
|
''' Translates from wave number to frequency
|
||||||
Parameters
|
using the dispersion relation
|
||||||
----------
|
|
||||||
k1 : array-like
|
Parameters
|
||||||
wave numbers [rad/m].
|
----------
|
||||||
k2 : array-like, optional
|
k1 : array-like
|
||||||
second dimension wave number
|
wave numbers [rad/m].
|
||||||
h : real scalar, optional
|
k2 : array-like, optional
|
||||||
water depth [m].
|
second dimension wave number
|
||||||
g : real scalar, optional
|
h : real scalar, optional
|
||||||
acceleration of gravity, see gravity
|
water depth [m].
|
||||||
u1, u2 : real scalars, optional
|
g : real scalar, optional
|
||||||
current velocity [m/s] along dimension 1 and 2.
|
acceleration of gravity, see gravity
|
||||||
note: when u1!=0 | u2!=0 then theta is not calculated correctly
|
u1, u2 : real scalars, optional
|
||||||
|
current velocity [m/s] along dimension 1 and 2.
|
||||||
Returns
|
note: when u1!=0 | u2!=0 then theta is not calculated correctly
|
||||||
-------
|
|
||||||
w : ndarray
|
Returns
|
||||||
angular frequency [rad/s].
|
-------
|
||||||
theta : ndarray
|
w : ndarray
|
||||||
direction [rad].
|
angular frequency [rad/s].
|
||||||
|
theta : ndarray
|
||||||
Dispersion relation
|
direction [rad].
|
||||||
-------------------
|
|
||||||
w = sqrt(g*K*tanh(K*h)) ( 0 < w < inf)
|
Dispersion relation
|
||||||
theta = arctan2(k2,k1) (-pi < theta < pi)
|
-------------------
|
||||||
where
|
w = sqrt(g*K*tanh(K*h)) ( 0 < w < inf)
|
||||||
K = sqrt(k1**2+k2**2)
|
theta = arctan2(k2,k1) (-pi < theta < pi)
|
||||||
|
where
|
||||||
The shape of w and theta is the common shape of k1 and k2 according to the
|
K = sqrt(k1**2+k2**2)
|
||||||
numpy broadcasting rules.
|
|
||||||
|
The shape of w and theta is the common shape of k1 and k2 according to the
|
||||||
See also
|
numpy broadcasting rules.
|
||||||
--------
|
|
||||||
w2k
|
See also
|
||||||
|
--------
|
||||||
Example
|
w2k
|
||||||
-------
|
|
||||||
>>> from numpy import arange
|
Example
|
||||||
>>> import wafo.spectrum.dispersion_relation as wsd
|
-------
|
||||||
>>> wsd.k2w(arange(0.01,.5,0.2))[0]
|
>>> from numpy import arange
|
||||||
array([ 0.3132092 , 1.43530485, 2.00551739])
|
>>> import wafo.wave_theory.dispersion_relation as wsd
|
||||||
>>> wsd.k2w(arange(0.01,.5,0.2),h=20)[0]
|
>>> wsd.k2w(arange(0.01,.5,0.2))[0]
|
||||||
array([ 0.13914927, 1.43498213, 2.00551724])
|
array([ 0.3132092 , 1.43530485, 2.00551739])
|
||||||
'''
|
>>> wsd.k2w(arange(0.01,.5,0.2),h=20)[0]
|
||||||
|
array([ 0.13914927, 1.43498213, 2.00551724])
|
||||||
k1i, k2i, hi, gi, u1i, u2i = atleast_1d(k1, k2, h, g, u1, u2)
|
'''
|
||||||
|
|
||||||
if k1i.size == 0:
|
k1i, k2i, hi, gi, u1i, u2i = atleast_1d(k1, k2, h, g, u1, u2)
|
||||||
return zeros_like(k1i)
|
|
||||||
ku1 = k1i*u1i
|
if k1i.size == 0:
|
||||||
ku2 = k2i*u2i
|
return zeros_like(k1i)
|
||||||
|
ku1 = k1i * u1i
|
||||||
theta = arctan2(k2, k1)
|
ku2 = k2i * u2i
|
||||||
|
|
||||||
k = sqrt(k1i**2+k2i**2)
|
theta = arctan2(k2, k1)
|
||||||
w = where(k>0, ku1+ku2+sqrt(gi*k*tanh(k*hi)), 0.0)
|
|
||||||
|
k = sqrt(k1i ** 2 + k2i ** 2)
|
||||||
cond = (w<0)
|
w = where(k > 0, ku1 + ku2 + sqrt(gi * k * tanh(k * hi)), 0.0)
|
||||||
if any(cond):
|
|
||||||
txt0 = '''
|
cond = (w < 0)
|
||||||
Waves and current are in opposite directions
|
if any(cond):
|
||||||
making some of the frequencies negative.
|
txt0 = '''
|
||||||
Here we are forcing the negative frequencies to zero.
|
Waves and current are in opposite directions
|
||||||
'''
|
making some of the frequencies negative.
|
||||||
warnings.warn(txt0)
|
Here we are forcing the negative frequencies to zero.
|
||||||
w = where(cond, 0.0, w) # force w to zero
|
'''
|
||||||
|
warnings.warn(txt0)
|
||||||
return w, theta
|
w = where(cond, 0.0, w) # force w to zero
|
||||||
|
|
||||||
def w2k(w, theta=0.0, h=inf, g=9.81, count_limit=100):
|
return w, theta
|
||||||
'''
|
|
||||||
Translates from frequency to wave number
|
|
||||||
using the dispersion relation
|
def w2k(w, theta=0.0, h=inf, g=9.81, count_limit=100):
|
||||||
|
'''
|
||||||
Parameters
|
Translates from frequency to wave number
|
||||||
----------
|
using the dispersion relation
|
||||||
w : array-like
|
|
||||||
angular frequency [rad/s].
|
Parameters
|
||||||
theta : array-like, optional
|
----------
|
||||||
direction [rad].
|
w : array-like
|
||||||
h : real scalar, optional
|
angular frequency [rad/s].
|
||||||
water depth [m].
|
theta : array-like, optional
|
||||||
g : real scalar or array-like of size 2.
|
direction [rad].
|
||||||
constant of gravity [m/s**2] or 3D normalizing constant
|
h : real scalar, optional
|
||||||
|
water depth [m].
|
||||||
Returns
|
g : real scalar or array-like of size 2.
|
||||||
-------
|
constant of gravity [m/s**2] or 3D normalizing constant
|
||||||
k1, k2 : ndarray
|
|
||||||
wave numbers [rad/m] along dimension 1 and 2.
|
Returns
|
||||||
|
-------
|
||||||
Description
|
k1, k2 : ndarray
|
||||||
-----------
|
wave numbers [rad/m] along dimension 1 and 2.
|
||||||
Uses Newton Raphson method to find the wave number k in the dispersion relation
|
|
||||||
w**2= g*k*tanh(k*h).
|
Description
|
||||||
The solution k(w) => k1 = k(w)*cos(theta)
|
-----------
|
||||||
k2 = k(w)*sin(theta)
|
Uses Newton Raphson method to find the wave number k in the dispersion
|
||||||
The size of k1,k2 is the common shape of w and theta according to numpy
|
relation
|
||||||
broadcasting rules. If w or theta is scalar it functions as a constant
|
w**2= g*k*tanh(k*h).
|
||||||
matrix of the same shape as the other.
|
The solution k(w) => k1 = k(w)*cos(theta)
|
||||||
|
k2 = k(w)*sin(theta)
|
||||||
Example
|
The size of k1,k2 is the common shape of w and theta according to numpy
|
||||||
-------
|
broadcasting rules. If w or theta is scalar it functions as a constant
|
||||||
>>> import pylab as plb
|
matrix of the same shape as the other.
|
||||||
>>> import wafo.spectrum.dispersion_relation as wsd
|
|
||||||
>>> w = plb.linspace(0,3);
|
Example
|
||||||
>>> h = plb.plot(w,w2k(w)[0])
|
-------
|
||||||
>>> wsd.w2k(range(4))[0]
|
>>> import pylab as plb
|
||||||
array([ 0. , 0.1019368 , 0.4077472 , 0.91743119])
|
>>> import wafo.wave_theory.dispersion_relation as wsd
|
||||||
>>> wsd.w2k(range(4),h=20)[0]
|
>>> w = plb.linspace(0,3);
|
||||||
array([ 0. , 0.10503601, 0.40774726, 0.91743119])
|
>>> h = plb.plot(w,w2k(w)[0])
|
||||||
|
>>> wsd.w2k(range(4))[0]
|
||||||
>>> plb.close('all')
|
array([ 0. , 0.1019368 , 0.4077472 , 0.91743119])
|
||||||
|
>>> wsd.w2k(range(4),h=20)[0]
|
||||||
See also
|
array([ 0. , 0.10503601, 0.40774726, 0.91743119])
|
||||||
--------
|
|
||||||
k2w
|
>>> plb.close('all')
|
||||||
'''
|
|
||||||
wi, th, hi, gi = atleast_1d(w, theta, h, g)
|
See also
|
||||||
|
--------
|
||||||
if wi.size == 0:
|
k2w
|
||||||
return zeros_like(wi)
|
'''
|
||||||
|
wi, th, hi, gi = atleast_1d(w, theta, h, g)
|
||||||
k = 1.0*sign(wi)*wi**2.0 / gi[0] # deep water
|
|
||||||
if (hi > 10. ** 25).all():
|
if wi.size == 0:
|
||||||
k2 = k*sin(th)*gi[0]/gi[-1] #size np x nf
|
return zeros_like(wi)
|
||||||
k1 = k*cos(th)
|
|
||||||
return k1, k2
|
k = 1.0 * sign(wi) * wi ** 2.0 / gi[0] # deep water
|
||||||
|
if (hi > 10. ** 25).all():
|
||||||
|
k2 = k * sin(th) * gi[0] / gi[-1] # size np x nf
|
||||||
if gi.size > 1:
|
k1 = k * cos(th)
|
||||||
txt0 = '''
|
return k1, k2
|
||||||
Finite depth in combination with 3D normalization (len(g)=2) is not implemented yet.
|
|
||||||
'''
|
if gi.size > 1:
|
||||||
raise ValueError(txt0)
|
raise ValueError('Finite depth in combination with 3D normalization' +
|
||||||
|
' (len(g)=2) is not implemented yet.')
|
||||||
|
|
||||||
find = flatnonzero
|
find = flatnonzero
|
||||||
eps = finfo(float).eps
|
eps = finfo(float).eps
|
||||||
|
|
||||||
oshape = k.shape
|
oshape = k.shape
|
||||||
wi, k, hi = wi.ravel(), k.ravel(), hi.ravel()
|
wi, k, hi = wi.ravel(), k.ravel(), hi.ravel()
|
||||||
|
|
||||||
# Newton's Method
|
# Newton's Method
|
||||||
# Permit no more than count_limit iterations.
|
# Permit no more than count_limit iterations.
|
||||||
hi = hi * ones_like(k)
|
hi = hi * ones_like(k)
|
||||||
hn = zeros_like(k)
|
hn = zeros_like(k)
|
||||||
ix = find((wi<0) | (0<wi))
|
ix = find((wi < 0) | (0 < wi))
|
||||||
|
|
||||||
# Break out of the iteration loop for three reasons:
|
# Break out of the iteration loop for three reasons:
|
||||||
# 1) the last update is very small (compared to x)
|
# 1) the last update is very small (compared to x)
|
||||||
# 2) the last update is very small (compared to sqrt(eps))
|
# 2) the last update is very small (compared to sqrt(eps))
|
||||||
# 3) There are more than 100 iterations. This should NEVER happen.
|
# 3) There are more than 100 iterations. This should NEVER happen.
|
||||||
count = 0
|
count = 0
|
||||||
while (ix.size>0 and count < count_limit):
|
while (ix.size > 0 and count < count_limit):
|
||||||
ki = k[ix]
|
ki = k[ix]
|
||||||
kh = ki * hi[ix]
|
kh = ki * hi[ix]
|
||||||
hn[ix] = (ki*tanh(kh)-wi[ix]**2.0/gi)/(tanh(kh)+kh/(cosh(kh)**2.0))
|
hn[ix] = (ki * tanh(kh) - wi[ix] ** 2.0 / gi) / \
|
||||||
knew = ki - hn[ix]
|
(tanh(kh) + kh / (cosh(kh) ** 2.0))
|
||||||
# Make sure that the current guess is not zero.
|
knew = ki - hn[ix]
|
||||||
# When Newton's Method suggests steps that lead to zero guesses
|
# Make sure that the current guess is not zero.
|
||||||
# take a step 9/10ths of the way to zero:
|
# When Newton's Method suggests steps that lead to zero guesses
|
||||||
ksmall = find(abs(knew)==0)
|
# take a step 9/10ths of the way to zero:
|
||||||
if ksmall.size>0:
|
ksmall = find(abs(knew) == 0)
|
||||||
knew[ksmall] = ki[ksmall] / 10.0
|
if ksmall.size > 0:
|
||||||
hn[ix[ksmall]] = ki[ksmall]-knew[ksmall]
|
knew[ksmall] = ki[ksmall] / 10.0
|
||||||
|
hn[ix[ksmall]] = ki[ksmall] - knew[ksmall]
|
||||||
k[ix] = knew
|
|
||||||
# disp(['Iteration ',num2str(count),' Number of points left: ' num2str(length(ix)) ]),
|
k[ix] = knew
|
||||||
|
# disp(['Iteration ',num2str(count),' Number of points left: '
|
||||||
ix = find((abs(hn) > sqrt(eps)*abs(k)) * abs(hn) > sqrt(eps))
|
# num2str(length(ix)) ]),
|
||||||
count += 1
|
|
||||||
|
ix = find((abs(hn) > sqrt(eps) * abs(k)) * abs(hn) > sqrt(eps))
|
||||||
if count == count_limit:
|
count += 1
|
||||||
txt1 = ''' W2K did not converge.
|
|
||||||
The maximum error in the last step was: %13.8f''' % max(hn[ix])
|
if count == count_limit:
|
||||||
warnings.warn(txt1)
|
warnings.warn('W2K did not converge. The maximum error in the ' +
|
||||||
|
'last step was: %13.8f' % max(hn[ix]))
|
||||||
k.shape = oshape
|
|
||||||
|
k.shape = oshape
|
||||||
k2 = k*sin(th)
|
|
||||||
k1 = k*cos(th)
|
k2 = k * sin(th)
|
||||||
return k1, k2
|
k1 = k * cos(th)
|
||||||
|
return k1, k2
|
||||||
def main():
|
|
||||||
import doctest
|
|
||||||
doctest.testmod()
|
def test_docstrings():
|
||||||
|
import doctest
|
||||||
if __name__ == '__main__':
|
print('Testing docstrings in %s' % __file__)
|
||||||
main()
|
doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_docstrings()
|
||||||
|
@ -1,31 +1,35 @@
|
|||||||
'''
|
'''
|
||||||
Created on 19. juli 2010
|
Created on 19. juli 2010
|
||||||
|
|
||||||
@author: pab
|
@author: pab
|
||||||
'''
|
'''
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from wafo.wave_theory.dispersion_relation import w2k,k2w #@UnusedImport
|
from wafo.wave_theory.dispersion_relation import w2k, k2w # @UnusedImport
|
||||||
|
|
||||||
def test_k2w_infinite_water_depth():
|
|
||||||
vals = k2w(np.arange(0.01,.5,0.2))[0]
|
def test_k2w_infinite_water_depth():
|
||||||
true_vals = np.array([ 0.3132092 , 1.43530485, 2.00551739])
|
vals = k2w(np.arange(0.01, .5, 0.2))[0]
|
||||||
assert((np.abs(vals-true_vals)<1e-7).all())
|
true_vals = np.array([0.3132092, 1.43530485, 2.00551739])
|
||||||
|
assert((np.abs(vals - true_vals) < 1e-7).all())
|
||||||
def test_k2w_finite_water_depth():
|
|
||||||
vals = k2w(np.arange(0.01,.5,0.2),h=20)[0]
|
|
||||||
true_vals = np.array([ 0.13914927, 1.43498213, 2.00551724])
|
def test_k2w_finite_water_depth():
|
||||||
assert((np.abs(vals-true_vals)<1e-7).all())
|
vals = k2w(np.arange(0.01, .5, 0.2), h=20)[0]
|
||||||
|
true_vals = np.array([0.13914927, 1.43498213, 2.00551724])
|
||||||
def test_w2k_infinite_water_depth():
|
assert((np.abs(vals - true_vals) < 1e-7).all())
|
||||||
vals = w2k(range(4))[0]
|
|
||||||
true_vals = np.array([ 0. , 0.1019368 , 0.4077472 , 0.91743119])
|
|
||||||
assert((np.abs(vals-true_vals)<1e-7).all())
|
def test_w2k_infinite_water_depth():
|
||||||
|
vals = w2k(range(4))[0]
|
||||||
def test_w2k_finite_water_depth():
|
true_vals = np.array([0., 0.1019368, 0.4077472, 0.91743119])
|
||||||
vals = w2k(range(4),h=20)[0]
|
assert((np.abs(vals - true_vals) < 1e-7).all())
|
||||||
true_vals = np.array([ 0. , 0.10503601, 0.40774726, 0.91743119])
|
|
||||||
assert((np.abs(vals-true_vals)<1e-7).all())
|
|
||||||
|
def test_w2k_finite_water_depth():
|
||||||
if __name__ == '__main__':
|
vals = w2k(range(4), h=20)[0]
|
||||||
import nose
|
true_vals = np.array([0., 0.10503601, 0.40774726, 0.91743119])
|
||||||
nose.run()
|
assert((np.abs(vals - true_vals) < 1e-7).all())
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import nose
|
||||||
|
nose.run()
|
||||||
|
Loading…
Reference in New Issue