master
pbrod 9 years ago
parent eca5368f75
commit 2c90a05f80

@ -160,6 +160,12 @@ class PlotData(object):
return interpolate.griddata( return interpolate.griddata(
self.args, self.data, points, **options) self.args, self.data, points, **options)
def to_cdf(self):
if isinstance(self.args, (list, tuple)): # Multidimensional data
raise NotImplementedError('integration for ndim>1 not implemented')
cdf = np.hstack((0, integrate.cumtrapz(self.data, self.args)))
return PlotData(cdf, np.copy(self.args), xlab='x', ylab='F(x)')
def integrate(self, a, b, **kwds): def integrate(self, a, b, **kwds):
''' '''
>>> x = np.linspace(0,5,60) >>> x = np.linspace(0,5,60)
@ -551,7 +557,7 @@ def plot2d(axis, wdata, plotflag, *args, **kwds):
clvec = np.sort(CL) clvec = np.sort(CL)
if plotflag in [1, 8, 9]: if plotflag in [1, 8, 9]:
h = axis.contour(*args1, levels=CL, **kwds) h = axis.contour(*args1, levels=clvec, **kwds)
# else: # else:
# [cs hcs] = contour3(f.x{:},f.f,CL,sym); # [cs hcs] = contour3(f.x{:},f.f,CL,sym);
@ -563,9 +569,7 @@ def plot2d(axis, wdata, plotflag, *args, **kwds):
'Only the first 12 levels will be listed in table.') 'Only the first 12 levels will be listed in table.')
clvals = PL[:ncl] if isPL else clvec[:ncl] clvals = PL[:ncl] if isPL else clvec[:ncl]
unused_axcl = cltext( unused_axcl = cltext(clvals, percent=isPL)
clvals,
percent=isPL) # print contour level text
elif any(plotflag == [7, 9]): elif any(plotflag == [7, 9]):
axis.clabel(h) axis.clabel(h)
else: else:

@ -1,6 +1,5 @@
from scipy import * import wafo.plotbackend.plotbackend as plt
from pylab import * import numpy as np
# pyreport -o chapter1.html chapter1.py # pyreport -o chapter1.html chapter1.py
#! CHAPTER1 demonstrates some applications of WAFO #! CHAPTER1 demonstrates some applications of WAFO
@ -15,16 +14,16 @@ from pylab import *
#! Section 1.4 Some applications of WAFO #! Section 1.4 Some applications of WAFO
#!--------------------------------------- #!---------------------------------------
#! Section 1.4.1 Simulation from spectrum, estimation of spectrum #! Section 1.4.1 Simulation from spectrum, estimation of spectrum
#!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#! Simulation of the sea surface from spectrum #! Simulation of the sea surface from spectrum
#! The following code generates 200 seconds of data sampled with 10Hz from #! The following code generates 200 seconds of data sampled with 10Hz from
#! the Torsethaugen spectrum #! the Torsethaugen spectrum
import wafo.spectrum.models as wsm import wafo.spectrum.models as wsm
S = wsm.Torsethaugen(Hm0=6, Tp=8); S = wsm.Torsethaugen(Hm0=6, Tp=8)
S1 = S.tospecdata() S1 = S.tospecdata()
S1.plot() S1.plot()
show() plt.show()
## ##
@ -32,23 +31,23 @@ import wafo.objects as wo
xs = S1.sim(ns=2000, dt=0.1) xs = S1.sim(ns=2000, dt=0.1)
ts = wo.mat2timeseries(xs) ts = wo.mat2timeseries(xs)
ts.plot_wave('-') ts.plot_wave('-')
show() plt.show()
#! Estimation of spectrum #! Estimation of spectrum
#!~~~~~~~~~~~~~~~~~~~~~~~ #!~~~~~~~~~~~~~~~~~~~~~~~
#! A common situation is that one wants to estimate the spectrum for wave #! A common situation is that one wants to estimate the spectrum for wave
#! measurements. The following code simulate 20 minutes signal sampled at 4Hz #! measurements. The following code simulate 20 minutes signal sampled at 4Hz
#! and compare the spectral estimate with the original Torsethaugen spectum. #! and compare the spectral estimate with the original Torsethaugen spectum.
clf() plt.clf()
Fs = 4; Fs = 4
xs = S1.sim(ns=fix(20 * 60 * Fs), dt=1. / Fs) xs = S1.sim(ns=np.fix(20 * 60 * Fs), dt=1. / Fs)
ts = wo.mat2timeseries(xs) ts = wo.mat2timeseries(xs)
Sest = ts.tospecdata(L=400) Sest = ts.tospecdata(L=400)
S1.plot() S1.plot()
Sest.plot('--') Sest.plot('--')
axis([0, 3, 0, 5]) # This may depend on the simulation plt.axis([0, 3, 0, 5])
show() plt.show()
#! Section 1.4.2 Probability distributions of wave characteristics. #! Section 1.4.2 Probability distributions of wave characteristics.
#!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -58,7 +57,7 @@ show()
#! In the following example we study the trough period extracted from the #! In the following example we study the trough period extracted from the
#! time series and compared with the theoretical density computed with exact #! time series and compared with the theoretical density computed with exact
#! spectrum, S1, and the estimated spectrum, Sest. #! spectrum, S1, and the estimated spectrum, Sest.
clf() plt.clf()
import wafo.misc as wm import wafo.misc as wm
dtyex = S1.to_t_pdf(pdef='Tt', paramt=(0, 10, 51), nit=3) dtyex = S1.to_t_pdf(pdef='Tt', paramt=(0, 10, 51), nit=3)
dtyest = Sest.to_t_pdf(pdef='Tt', paramt=(0, 10, 51), nit=3) dtyest = Sest.to_t_pdf(pdef='Tt', paramt=(0, 10, 51), nit=3)
@ -69,29 +68,29 @@ wm.plot_histgrm(T, bins=bins, normed=True)
dtyex.plot() dtyex.plot()
dtyest.plot('-.') dtyest.plot('-.')
axis([0, 10, 0, 0.35]) plt.axis([0, 10, 0, 0.35])
show() plt.show()
#! Section 1.4.3 Directional spectra #! Section 1.4.3 Directional spectra
#!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#! Here are a few lines of code, which produce directional spectra #! Here are a few lines of code, which produce directional spectra
#! with frequency independent and frequency dependent spreading. #! with frequency independent and frequency dependent spreading.
clf() plt.clf()
plotflag = 1 plotflag = 1
Nt = 101; # number of angles Nt = 101 # number of angles
th0 = pi / 2; # primary direction of waves th0 = np.pi / 2 # primary direction of waves
Sp = 15; # spreading parameter Sp = 15 # spreading parameter
D1 = wsm.Spreading(type='cos', theta0=th0, method=None) # frequency independent D1 = wsm.Spreading(type='cos', theta0=th0, method=None)
D12 = wsm.Spreading(type='cos', theta0=0, method='mitsuyasu') # frequency dependent D12 = wsm.Spreading(type='cos', theta0=0, method='mitsuyasu')
SD1 = D1.tospecdata2d(S1) SD1 = D1.tospecdata2d(S1)
SD12 = D12.tospecdata2d(S1) SD12 = D12.tospecdata2d(S1)
SD1.plot() SD1.plot()
SD12.plot()#linestyle='dashdot') SD12.plot() # linestyle='dashdot')
show() plt.show()
#! 3D Simulation of the sea surface #! 3D Simulation of the sea surface
#!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#! The simulations show that frequency dependent spreading leads to #! The simulations show that frequency dependent spreading leads to
#! much more irregular surface so the orientation of waves is less #! much more irregular surface so the orientation of waves is less
@ -120,7 +119,7 @@ show()
#! The figure is not shown in the Tutorial #! The figure is not shown in the Tutorial
# #
# Nx = 3; Ny = 2; Nt = 2 ^ 12; dx = 10; dy = 10;dt = 0.5; # Nx = 3; Ny = 2; Nt = 2 ^ 12; dx = 10; dy = 10;dt = 0.5;
# F = seasim(SD12, Nx, Ny, Nt, dx, dy, dt, 1, 0); # F = seasim(SD12, Nx, Ny, Nt, dx, dy, dt, 1, 0);
# Z = permute(F.Z, [3 1 2]); # Z = permute(F.Z, [3 1 2]);
# [X, Y] = meshgrid(F.x, F.y); # [X, Y] = meshgrid(F.x, F.y);
# N = Nx * Ny; # N = Nx * Ny;
@ -137,16 +136,16 @@ show()
#! Section 1.4.4 Fatigue, Load cycles and Markov models. #! Section 1.4.4 Fatigue, Load cycles and Markov models.
#! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#! Switching Markow chain of turningpoints #! Switching Markow chain of turningpoints
#! In fatigue applications the exact sample path is not important, but #! In fatigue applications the exact sample path is not important, but
#! only the tops and bottoms of the load, called the sequence of turning #! only the tops and bottoms of the load, called the sequence of turning
#! points (TP). From the turning points one can extract load cycles, from #! points (TP). From the turning points one can extract load cycles, from
#! which damage calculations and fatigue life predictions can be #! which damage calculations and fatigue life predictions can be
#! performed. #! performed.
#! #!
#! The commands below computes the intensity of rainflowcycles for #! The commands below computes the intensity of rainflowcycles for
#! the Gaussian model with spectrum S1 using the Markov approximation. #! the Gaussian model with spectrum S1 using the Markov approximation.
#! The rainflow cycles found in the simulated load signal are shown in the #! The rainflow cycles found in the simulated load signal are shown in the
#! figure. #! figure.
#clf() #clf()
@ -164,30 +163,30 @@ show()
#! Section 1.4.5 Extreme value statistics #! Section 1.4.5 Extreme value statistics
#!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Plot of yura87 data # Plot of yura87 data
clf() plt.clf()
import wafo.data as wd import wafo.data as wd
xn = wd.yura87() xn = wd.yura87()
#xn = load('yura87.dat'); #xn = load('yura87.dat');
subplot(211) plt.subplot(211)
plot(xn[::30, 0] / 3600, xn[::30, 1], '.') plt.plot(xn[::30, 0] / 3600, xn[::30, 1], '.')
title('Water level') plt.title('Water level')
ylabel('(m)') plt.ylabel('(m)')
#! Formation of 5 min maxima #! Formation of 5 min maxima
yura = xn[:85500, 1] yura = xn[:85500, 1]
yura = np.reshape(yura, (285, 300)).T yura = np.reshape(yura, (285, 300)).T
maxyura = yura.max(axis=0) maxyura = yura.max(axis=0)
subplot(212) plt.subplot(212)
plot(xn[299:85500:300, 0] / 3600, maxyura, '.') plt.plot(xn[299:85500:300, 0] / 3600, maxyura, '.')
xlabel('Time (h)') plt.xlabel('Time (h)')
ylabel('(m)') plt.ylabel('(m)')
title('Maximum 5 min water level') plt.title('Maximum 5 min water level')
show() plt.show()
#! Estimation of GEV for yuramax #! Estimation of GEV for yuramax
clf() plt.clf()
import wafo.stats as ws import wafo.stats as ws
phat = ws.genextreme.fit2(maxyura, method='ml') phat = ws.genextreme.fit2(maxyura, method='ml')
phat.plotfitsummary() phat.plotfitsummary()
show() plt.show()
#disp('Block = 11, Last block') #disp('Block = 11, Last block')

@ -1,6 +1,5 @@
import wafo.plotbackend.plotbackend as plt
import numpy as np import numpy as np
from scipy import *
from pylab import *
# pyreport -o chapter2.html chapter2.py # pyreport -o chapter2.html chapter2.py
@ -10,15 +9,15 @@ from pylab import *
#! Chapter2 contains the commands used in Chapter 2 of the tutorial and #! Chapter2 contains the commands used in Chapter 2 of the tutorial and
#! present some tools for analysis of random functions with #! present some tools for analysis of random functions with
#! respect to their correlation, spectral and distributional properties. #! respect to their correlation, spectral and distributional properties.
#! The presentation is divided into three examples: #! The presentation is divided into three examples:
#! #!
#! Example1 is devoted to estimation of different parameters in the model. #! Example1 is devoted to estimation of different parameters in the model.
#! Example2 deals with spectral densities and #! Example2 deals with spectral densities and
#! Example3 presents the use of WAFO to simulate samples of a Gaussian #! Example3 presents the use of WAFO to simulate samples of a Gaussian
#! process. #! process.
#! #!
#! Some of the commands are edited for fast computation. #! Some of the commands are edited for fast computation.
#! #!
#! Section 2.1 Introduction and preliminary analysis #! Section 2.1 Introduction and preliminary analysis
#!==================================================== #!====================================================
#! Example 1: Sea data #! Example 1: Sea data
@ -37,15 +36,15 @@ tp = ts.turning_points()
cc = tp.cycle_pairs() cc = tp.cycle_pairs()
lc = cc.level_crossings() lc = cc.level_crossings()
lc.plot() lc.plot()
show() plt.show()
#! Average number of upcrossings per time unit #! Average number of upcrossings per time unit
#!---------------------------------------------- #!----------------------------------------------
#! Next we compute the mean frequency as the average number of upcrossings #! Next we compute the mean frequency as the average number of upcrossings
#! per time unit of the mean level (= 0); this may require interpolation in the #! per time unit of the mean level (= 0); this may require interpolation in the
#! crossing intensity curve, as follows. #! crossing intensity curve, as follows.
T = xx[:, 0].max() - xx[:, 0].min() T = xx[:, 0].max() - xx[:, 0].min()
f0 = np.interp(0, lc.args, lc.data, 0) / T #! zero up-crossing frequency f0 = np.interp(0, lc.args, lc.data, 0) / T # zero up-crossing frequency
print('f0 = %g' % f0) print('f0 = %g' % f0)
#! Turningpoints and irregularity factor #! Turningpoints and irregularity factor
@ -60,17 +59,17 @@ print('fm = %g, alpha = %g, ' % (fm, alfa))
#!------------------------ #!------------------------
#! We finish this section with some remarks about the quality #! We finish this section with some remarks about the quality
#! of the measured data. Especially sea surface measurements can be #! of the measured data. Especially sea surface measurements can be
#! of poor quality. We shall now check the quality of the dataset {\tt xx}. #! of poor quality. We shall now check the quality of the dataset {\tt xx}.
#! It is always good practice to visually examine the data #! It is always good practice to visually examine the data
#! before the analysis to get an impression of the quality, #! before the analysis to get an impression of the quality,
#! non-linearities and narrow-bandedness of the data. #! non-linearities and narrow-bandedness of the data.
#! First we shall plot the data and zoom in on a specific region. #! First we shall plot the data and zoom in on a specific region.
#! A part of sea data is visualized with the following commands #! A part of sea data is visualized with the following commands
clf() plt.clf()
ts.plot_wave('k-', tp, '*', nfig=1, nsub=1) ts.plot_wave('k-', tp, '*', nfig=1, nsub=1)
axis([0, 2, -2, 2]) plt.axis([0, 2, -2, 2])
show() plt.show()
#! Finding possible spurious points #! Finding possible spurious points
#!------------------------------------ #!------------------------------------
@ -91,58 +90,59 @@ inds, indg = wm.findoutliers(ts.data, zcrit, dcrit, ddcrit, verbose=True)
#!---------------------------------------------------- #!----------------------------------------------------
#! Periodogram: Raw spectrum #! Periodogram: Raw spectrum
#! #!
clf() plt.clf()
Lmax = 9500 Lmax = 9500
S = ts.tospecdata(L=Lmax) S = ts.tospecdata(L=Lmax)
S.plot() S.plot()
axis([0, 5, 0, 0.7]) plt.axis([0, 5, 0, 0.7])
show() plt.show()
#! Calculate moments #! Calculate moments
#!------------------- #!-------------------
mom, text = S.moment(nr=4) mom, text = S.moment(nr=4)
print('sigma = %g, m0 = %g' % (sa, sqrt(mom[0]))) print('sigma = %g, m0 = %g' % (sa, np.sqrt(mom[0])))
#! Section 2.2.1 Random functions in Spectral Domain - Gaussian processes #! Section 2.2.1 Random functions in Spectral Domain - Gaussian processes
#!-------------------------------------------------------------------------- #!--------------------------------------------------------------------------
#! Smoothing of spectral estimate #! Smoothing of spectral estimate
#!---------------------------------- #!----------------------------------
#! By decreasing Lmax the spectrum estimate becomes smoother. #! By decreasing Lmax the spectrum estimate becomes smoother.
clf() plt.clf()
Lmax0 = 200; Lmax1 = 50 Lmax0 = 200
Lmax1 = 50
S1 = ts.tospecdata(L=Lmax0) S1 = ts.tospecdata(L=Lmax0)
S2 = ts.tospecdata(L=Lmax1) S2 = ts.tospecdata(L=Lmax1)
S1.plot('-.') S1.plot('-.')
S2.plot() S2.plot()
show() plt.show()
#! Estimated autocovariance #! Estimated autocovariance
#!---------------------------- #!----------------------------
#! Obviously knowing the spectrum one can compute the covariance #! Obviously knowing the spectrum one can compute the covariance
#! function. The following code will compute the covariance for the #! function. The following code will compute the covariance for the
#! unimodal spectral density S1 and compare it with estimated #! unimodal spectral density S1 and compare it with estimated
#! covariance of the signal xx. #! covariance of the signal xx.
clf() plt.clf()
Lmax = 85 Lmax = 85
R1 = S1.tocovdata(nr=1) R1 = S1.tocovdata(nr=1)
Rest = ts.tocovdata(lag=Lmax) Rest = ts.tocovdata(lag=Lmax)
R1.plot('.') R1.plot('.')
Rest.plot() Rest.plot()
axis([0, 25, -0.1, 0.25]) plt.axis([0, 25, -0.1, 0.25])
show() plt.show()
#! We can see in Figure below that the covariance function corresponding to #! We can see in Figure below that the covariance function corresponding to
#! the spectral density S2 significantly differs from the one estimated #! the spectral density S2 significantly differs from the one estimated
#! directly from data. #! directly from data.
#! It can be seen in Figure above that the covariance corresponding to S1 #! It can be seen in Figure above that the covariance corresponding to S1
#! agrees much better with the estimated covariance function #! agrees much better with the estimated covariance function
clf() plt.clf()
R2 = S2.tocovdata(nr=1) R2 = S2.tocovdata(nr=1)
R2.plot('.') R2.plot('.')
Rest.plot() Rest.plot()
show() plt.show()
#! Section 2.2.2 Transformed Gaussian models #! Section 2.2.2 Transformed Gaussian models
#!------------------------------------------- #!-------------------------------------------
@ -154,68 +154,69 @@ rho3 = ws.skew(xx[:, 1])
rho4 = ws.kurtosis(xx[:, 1]) rho4 = ws.kurtosis(xx[:, 1])
sk, ku = S1.stats_nl(moments='sk') sk, ku = S1.stats_nl(moments='sk')
#! Comparisons of 3 transformations #! Comparisons of 3 transformations
clf() plt.clf()
import wafo.transform.models as wtm import wafo.transform.models as wtm
gh = wtm.TrHermite(mean=me, sigma=sa, skew=sk, kurt=ku).trdata() gh = wtm.TrHermite(mean=me, sigma=sa, skew=sk, kurt=ku).trdata()
g = wtm.TrLinear(mean=me, sigma=sa).trdata() # Linear transformation g = wtm.TrLinear(mean=me, sigma=sa).trdata() # Linear transformation
glc, gemp = lc.trdata(mean=me, sigma=sa) glc, gemp = lc.trdata(mean=me, sigma=sa)
glc.plot('b-') #! Transf. estimated from level-crossings glc.plot('b-') # Transf. estimated from level-crossings
gh.plot('b-.') #! Hermite Transf. estimated from moments gh.plot('b-.') # Hermite Transf. estimated from moments
g.plot('r') g.plot('r')
grid('on') plt.grid('on')
show() plt.show()
#! Test Gaussianity of a stochastic process #! Test Gaussianity of a stochastic process
#!------------------------------------------ #!------------------------------------------
#! TESTGAUSSIAN simulates e(g(u)-u) = int (g(u)-u)^2 du for Gaussian processes #! TESTGAUSSIAN simulates e(g(u)-u) = int (g(u)-u)^2 du for Gaussian processes
#! given the spectral density, S. The result is plotted if test0 is given. #! given the spectral density, S. The result is plotted if test0 is given.
#! This is useful for testing if the process X(t) is Gaussian. #! This is useful for testing if the process X(t) is Gaussian.
#! If 95% of TEST1 is less than TEST0 then X(t) is not Gaussian at a 5% level. #! If 95% of TEST1 is less than TEST0 then X(t) is not Gaussian at a 5% level.
#! #!
#! As we see from the figure below: none of the simulated values of test1 is #! As we see from the figure below: none of the simulated values of test1 is
#! above 1.00. Thus the data significantly departs from a Gaussian distribution. #! above 1.00. Thus the data significantly departs from a Gaussian distribution.
clf() plt.clf()
test0 = glc.dist2gauss() test0 = glc.dist2gauss()
#! the following test takes time #! the following test takes time
N = len(xx) N = len(xx)
test1 = S1.testgaussian(ns=N, cases=50, test0=test0) test1 = S1.testgaussian(ns=N, cases=50, test0=test0)
is_gaussian = sum(test1 > test0) > 5 is_gaussian = sum(test1 > test0) > 5
print(is_gaussian) print(is_gaussian)
show() plt.show()
#! Normalplot of data xx #! Normalplot of data xx
#!------------------------ #!------------------------
#! indicates that the underlying distribution has a "heavy" upper tail and a #! indicates that the underlying distribution has a "heavy" upper tail and a
#! "light" lower tail. #! "light" lower tail.
clf() plt.clf()
import pylab import pylab
ws.probplot(ts.data.ravel(), dist='norm', plot=pylab) ws.probplot(ts.data.ravel(), dist='norm', plot=pylab)
show() plt.show()
#! Section 2.2.3 Spectral densities of sea data #! Section 2.2.3 Spectral densities of sea data
#!----------------------------------------------- #!-----------------------------------------------
#! Example 2: Different forms of spectra #! Example 2: Different forms of spectra
#! #!
import wafo.spectrum.models as wsm import wafo.spectrum.models as wsm
clf() plt.clf()
Hm0 = 7; Tp = 11; Hm0 = 7
Tp = 11
spec = wsm.Jonswap(Hm0=Hm0, Tp=Tp).tospecdata() spec = wsm.Jonswap(Hm0=Hm0, Tp=Tp).tospecdata()
spec.plot() spec.plot()
show() plt.show()
#! Directional spectrum and Encountered directional spectrum #! Directional spectrum and Encountered directional spectrum
#! Directional spectrum #! Directional spectrum
clf() plt.clf()
D = wsm.Spreading('cos2s') D = wsm.Spreading('cos2s')
Sd = D.tospecdata2d(spec) Sd = D.tospecdata2d(spec)
Sd.plot() Sd.plot()
show() plt.show()
##!Encountered directional spectrum ##!Encountered directional spectrum
##!--------------------------------- ##!---------------------------------
#clf() #clf()
#Se = spec2spec(Sd,'encdir',0,10); #Se = spec2spec(Sd,'encdir',0,10);
#plotspec(Se), hold on #plotspec(Se), hold on
@ -254,10 +255,10 @@ show()
#disp('Block = 20'),pause(pstate) #disp('Block = 20'),pause(pstate)
# #
##!#! Section 2.3 Simulation of transformed Gaussian process ##!#! Section 2.3 Simulation of transformed Gaussian process
##!#! Example 3: Simulation of random sea ##!#! Example 3: Simulation of random sea
##! The reconstruct function replaces the spurious points of seasurface by ##! The reconstruct function replaces the spurious points of seasurface by
##! simulated data on the basis of the remaining data and a transformed Gaussian ##! simulated data on the basis of the remaining data and a transformed Gaussian
##! process. As noted previously one must be careful using the criteria ##! process. As noted previously one must be careful using the criteria
##! for finding spurious points when reconstructing a dataset, because ##! for finding spurious points when reconstructing a dataset, because
##! these criteria might remove the highest and steepest waves as we can see ##! these criteria might remove the highest and steepest waves as we can see
##! in this plot where the spurious points is indicated with a '+' sign: ##! in this plot where the spurious points is indicated with a '+' sign:
@ -269,13 +270,13 @@ show()
##!wafostamp('','(ER)') ##!wafostamp('','(ER)')
#disp('Block = 21'),pause(pstate) #disp('Block = 21'),pause(pstate)
# #
##! Compare transformation (grec) from reconstructed (y) ##! Compare transformation (grec) from reconstructed (y)
##! with original (glc) from (xx) ##! with original (glc) from (xx)
#clf #clf
#trplot(g), hold on #trplot(g), hold on
#plot(gemp(:,1),gemp(:,2)) #plot(gemp(:,1),gemp(:,2))
#plot(glc(:,1),glc(:,2),'-.') #plot(glc(:,1),glc(:,2),'-.')
#plot(grec(:,1),grec(:,2)), hold off #plot(grec(:,1),grec(:,2)), hold off
#disp('Block = 22'),pause(pstate) #disp('Block = 22'),pause(pstate)
# #
##!#! ##!#!
@ -284,7 +285,7 @@ show()
#x = dat2gaus(y,grec); #x = dat2gaus(y,grec);
#Sx = dat2spec(x,L); #Sx = dat2spec(x,L);
#disp('Block = 23'),pause(pstate) #disp('Block = 23'),pause(pstate)
# #
##!#! ##!#!
#clf #clf
#dt = spec2dt(Sx) #dt = spec2dt(Sx)
@ -294,27 +295,28 @@ show()
#waveplot(ysim,'-') #waveplot(ysim,'-')
##!wafostamp('','(CR)') ##!wafostamp('','(CR)')
#disp('Block = 24'),pause(pstate) #disp('Block = 24'),pause(pstate)
# #
#! Estimated spectrum compared to Torsethaugen spectrum #! Estimated spectrum compared to Torsethaugen spectrum
#!------------------------------------------------------- #!-------------------------------------------------------
clf() plt.clf()
fp = 1.1;dw = 0.01 fp = 1.1
dw = 0.01
H0 = S1.characteristic('Hm0')[0] H0 = S1.characteristic('Hm0')[0]
St = wsm.Torsethaugen(Hm0=H0,Tp=2*pi/fp).tospecdata(np.arange(0,5+dw/2,dw)) St = wsm.Torsethaugen(Hm0=H0,Tp=2*np.pi/fp).tospecdata(np.arange(0,5+dw/2,dw))
S1.plot() S1.plot()
St.plot('-.') St.plot('-.')
axis([0, 6, 0, 0.4]) plt.axis([0, 6, 0, 0.4])
show() plt.show()
#! Transformed Gaussian model compared to Gaussian model #! Transformed Gaussian model compared to Gaussian model
#!-------------------------------------------------------- #!--------------------------------------------------------
dt = St.sampling_period() dt = St.sampling_period()
va, sk, ku = St.stats_nl(moments='vsk' ) va, sk, ku = St.stats_nl(moments='vsk')
#sa = sqrt(va) #sa = sqrt(va)
gh = wtm.TrHermite(mean=me, sigma=sa, skew=sk, kurt=ku, ysigma=sa) gh = wtm.TrHermite(mean=me, sigma=sa, skew=sk, kurt=ku, ysigma=sa)
ysim_t = St.sim(ns=240, dt=0.5) ysim_t = St.sim(ns=240, dt=0.5)
xsim_t = ysim_t.copy() xsim_t = ysim_t.copy()
xsim_t[:,1] = gh.gauss2dat(ysim_t[:,1]) xsim_t[:,1] = gh.gauss2dat(ysim_t[:,1])
@ -322,4 +324,4 @@ xsim_t[:,1] = gh.gauss2dat(ysim_t[:,1])
ts_y = wo.mat2timeseries(ysim_t) ts_y = wo.mat2timeseries(ysim_t)
ts_x = wo.mat2timeseries(xsim_t) ts_x = wo.mat2timeseries(xsim_t)
ts_y.plot_wave(sym1='r.', ts=ts_x, sym2='b', sigma=sa, nsub=5, nfig=1) ts_y.plot_wave(sym1='r.', ts=ts_x, sym2='b', sigma=sa, nsub=5, nfig=1)
show() plt.show()

File diff suppressed because it is too large Load Diff

@ -1,17 +1,14 @@
import numpy as np
from scipy import *
from pylab import *
#! CHAPTER4 contains the commands used in Chapter 4 of the tutorial #! CHAPTER4 contains the commands used in Chapter 4 of the tutorial
#!================================================================= #!=================================================================
#! #!
#! CALL: Chapter4 #! CALL: Chapter4
#! #!
#! Some of the commands are edited for fast computation. #! Some of the commands are edited for fast computation.
#! Each set of commands is followed by a 'pause' command. #! Each set of commands is followed by a 'pause' command.
#! #!
#! This routine also can print the figures; #! This routine also can print the figures;
#! For printing the figures on directory ../bilder/ edit the file and put #! For printing the figures on directory ../bilder/ edit the file and put
#! printing=1; #! printing=1;
#! Tested on Matlab 5.3 #! Tested on Matlab 5.3
@ -23,76 +20,80 @@ from pylab import *
#! Created by GL July 13, 2000 #! Created by GL July 13, 2000
#! from commands used in Chapter 4 #! from commands used in Chapter 4
#! #!
#! Chapter 4 Fatigue load analysis and rain-flow cycles #! Chapter 4 Fatigue load analysis and rain-flow cycles
#!------------------------------------------------------ #!------------------------------------------------------
printing=0; printing = 0
#! Section 4.3.1 Crossing intensity #! Section 4.3.1 Crossing intensity
#!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import numpy as np
from wafo.plotbackend import plotbackend as plt
import wafo.data as wd import wafo.data as wd
import wafo.objects as wo import wafo.objects as wo
xx_sea = wd.sea() xx_sea = wd.sea()
ts = wo.mat2timeseries(xx_sea) ts = wo.mat2timeseries(xx_sea)
tp = ts.turning_points() tp = ts.turning_points()
mM = tp.cycle_pairs(kind='min2max') mM = tp.cycle_pairs(kind='min2max')
lc = mM.level_crossings(intensity=True) lc = mM.level_crossings(intensity=True)
T_sea = ts.args[-1]-ts.args[0] T_sea = ts.args[-1]-ts.args[0]
subplot(1,2,1) plt.subplot(1,2,1)
lc.plot() lc.plot()
subplot(1,2,2) plt.subplot(1,2,2)
lc.setplotter(plotmethod='step') lc.setplotter(plotmethod='step')
lc.plot() lc.plot()
show() plt.show()
m_sea = ts.data.mean() m_sea = ts.data.mean()
f0_sea = interp(m_sea, lc.args,lc.data) f0_sea = np.interp(m_sea, lc.args,lc.data)
extr_sea = len(tp.data)/(2*T_sea) extr_sea = len(tp.data)/(2*T_sea)
alfa_sea = f0_sea/extr_sea alfa_sea = f0_sea/extr_sea
print('alfa = %g ' % alfa_sea ) print('alfa = %g ' % alfa_sea)
#! Section 4.3.2 Extraction of rainflow cycles #! Section 4.3.2 Extraction of rainflow cycles
#!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#! Min-max and rainflow cycle plots #! Min-max and rainflow cycle plots
#!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
mM_rfc = tp.cycle_pairs(h=0.3) mM_rfc = tp.cycle_pairs(h=0.3)
clf() plt.clf()
subplot(122), plt.subplot(122),
mM.plot() mM.plot()
title('min-max cycle pairs') plt.title('min-max cycle pairs')
subplot(121), plt.subplot(121),
mM_rfc.plot() mM_rfc.plot()
title('Rainflow filtered cycles') plt.title('Rainflow filtered cycles')
show() plt.show()
#! Min-max and rainflow cycle distributions #! Min-max and rainflow cycle distributions
#!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import wafo.misc as wm import wafo.misc as wm
ampmM_sea = mM.amplitudes() ampmM_sea = mM.amplitudes()
ampRFC_sea = mM_rfc.amplitudes() ampRFC_sea = mM_rfc.amplitudes()
clf() plt.clf()
subplot(121) plt.subplot(121)
wm.plot_histgrm(ampmM_sea,25) wm.plot_histgrm(ampmM_sea,25)
ylim = gca().get_ylim() ylim = plt.gca().get_ylim()
title('min-max amplitude distribution') plt.title('min-max amplitude distribution')
subplot(122) plt.subplot(122)
wm.plot_histgrm(ampRFC_sea,25) wm.plot_histgrm(ampRFC_sea,25)
gca().set_ylim(ylim) plt.gca().set_ylim(ylim)
title('Rainflow amplitude distribution') plt.title('Rainflow amplitude distribution')
show() plt.show()
#!#! Section 4.3.3 Simulation of rainflow cycles #!#! Section 4.3.3 Simulation of rainflow cycles
#!#! Simulation of cycles in a Markov model #!#! Simulation of cycles in a Markov model
n=41; param_m=[-1, 1, n]; param_D=[1, n, n]; # n = 41
u_markov=levels(param_m); # param_m = [-1, 1, n]
G_markov=mktestmat(param_m,[-0.2, 0.2],0.15,1); # param_D = [1, n, n]
T_markov=5000; # u_markov=levels(param_m);
# G_markov=mktestmat(param_m,[-0.2, 0.2],0.15,1);
# T_markov=5000;
#xxD_markov=mctpsim({G_markov [,]},T_markov); #xxD_markov=mctpsim({G_markov [,]},T_markov);
#xx_markov=[(1:T_markov)' u_markov(xxD_markov)']; #xx_markov=[(1:T_markov)' u_markov(xxD_markov)'];
#clf #clf
@ -118,7 +119,7 @@ T_markov=5000;
#xx_herm = spec2sdat(spec_norm,[2^15 1],0.1); #xx_herm = spec2sdat(spec_norm,[2^15 1],0.1);
##! ????? PJ, JR 11-Apr-2001 ##! ????? PJ, JR 11-Apr-2001
##! NOTE, in the simulation program spec2sdat ##! NOTE, in the simulation program spec2sdat
##!the spectrum must be normalized to variance 1 ##!the spectrum must be normalized to variance 1
##! ????? ##! ?????
#h = 0.2; #h = 0.2;
#[dtp,u_herm,xx_herm_1]=dat2dtp(param_h,xx_herm,h); #[dtp,u_herm,xx_herm_1]=dat2dtp(param_h,xx_herm,h);
@ -142,7 +143,7 @@ T_markov=5000;
#title('h=0') #title('h=0')
#subplot(122), ccplot(RFC_herm_1) #subplot(122), ccplot(RFC_herm_1)
#title('h=0.2') #title('h=0.2')
#if (printing==1), print -deps ../bilder/fatigue_8.eps #if (printing==1), print -deps ../bilder/fatigue_8.eps
#end #end
#wafostamp([],'(ER)') #wafostamp([],'(ER)')
#disp('Block 7'),pause(pstate) #disp('Block 7'),pause(pstate)
@ -157,17 +158,17 @@ T_markov=5000;
#wafostamp([],'(ER)') #wafostamp([],'(ER)')
#disp('Block 8'),pause(pstate) #disp('Block 8'),pause(pstate)
# #
##!#! ##!#!
#clf #clf
#cmatplot(u_markov,u_markov,{G_markov Grfc_markov},3) #cmatplot(u_markov,u_markov,{G_markov Grfc_markov},3)
#wafostamp([],'(ER)') #wafostamp([],'(ER)')
#disp('Block 9'),pause(pstate) #disp('Block 9'),pause(pstate)
# #
##!#! Min-max-matrix and theoretical rainflow matrix for test Markov sequence. ##!#! Min-max-matrix and theoretical rainflow matrix for test Markov sequence.
#cmatplot(u_markov,u_markov,{G_markov Grfc_markov},4) #cmatplot(u_markov,u_markov,{G_markov Grfc_markov},4)
#subplot(121), axis('square'), title('min2max transition matrix') #subplot(121), axis('square'), title('min2max transition matrix')
#subplot(122), axis('square'), title('Rainflow matrix') #subplot(122), axis('square'), title('Rainflow matrix')
#if (printing==1), print -deps ../bilder/fatigue_9.eps #if (printing==1), print -deps ../bilder/fatigue_9.eps
#end #end
#wafostamp([],'(ER)') #wafostamp([],'(ER)')
#disp('Block 10'),pause(pstate) #disp('Block 10'),pause(pstate)
@ -176,10 +177,10 @@ T_markov=5000;
#n=length(u_markov); #n=length(u_markov);
#Frfc_markov=dtp2rfm(xxD_markov,n); #Frfc_markov=dtp2rfm(xxD_markov,n);
#clf #clf
#cmatplot(u_markov,u_markov,{Frfc_markov Grfc_markov*T_markov/2},3) #cmatplot(u_markov,u_markov,{Frfc_markov Grfc_markov*T_markov/2},3)
#subplot(121), axis('square'), title('Observed rainflow matrix') #subplot(121), axis('square'), title('Observed rainflow matrix')
#subplot(122), axis('square'), title('Theoretical rainflow matrix') #subplot(122), axis('square'), title('Theoretical rainflow matrix')
#if (printing==1), print -deps ../bilder/fatigue_10.eps #if (printing==1), print -deps ../bilder/fatigue_10.eps
#end #end
#wafostamp([],'(ER)') #wafostamp([],'(ER)')
#disp('Block 11'),pause(pstate) #disp('Block 11'),pause(pstate)
@ -193,7 +194,7 @@ T_markov=5000;
#cmatplot(u_markov,u_markov,{Frfc_markov_smooth Grfc_markov*T_markov/2},4) #cmatplot(u_markov,u_markov,{Frfc_markov_smooth Grfc_markov*T_markov/2},4)
#subplot(121), axis('square'), title('Smoothed observed rainflow matrix') #subplot(121), axis('square'), title('Smoothed observed rainflow matrix')
#subplot(122), axis('square'), title('Theoretical rainflow matrix') #subplot(122), axis('square'), title('Theoretical rainflow matrix')
#if (printing==1), print -deps ../bilder/fatigue_11.eps #if (printing==1), print -deps ../bilder/fatigue_11.eps
#end #end
#wafostamp([],'(ER)') #wafostamp([],'(ER)')
#disp('Block 12'),pause(pstate) #disp('Block 12'),pause(pstate)
@ -214,7 +215,7 @@ T_markov=5000;
#cmatplot(u_herm,u_herm,{GmM3_herm.f Grfc_herm},4) #cmatplot(u_herm,u_herm,{GmM3_herm.f Grfc_herm},4)
#subplot(121), axis('square'), title('min-max matrix') #subplot(121), axis('square'), title('min-max matrix')
#subplot(122), axis('square'), title('Theoretical rainflow matrix') #subplot(122), axis('square'), title('Theoretical rainflow matrix')
#if (printing==1), print -deps ../bilder/fatigue_12.eps #if (printing==1), print -deps ../bilder/fatigue_12.eps
#end #end
#wafostamp([],'(ER)') #wafostamp([],'(ER)')
#disp('Block 14'),pause(pstate) #disp('Block 14'),pause(pstate)
@ -230,7 +231,7 @@ T_markov=5000;
#disp('Block 15'),pause(pstate) #disp('Block 15'),pause(pstate)
# #
# #
##!#! Observed smoothed and theoretical min-max matrix, ##!#! Observed smoothed and theoretical min-max matrix,
##!#! (and observed smoothed and theoretical rainflow matrix for Hermite-transformed Gaussian waves). ##!#! (and observed smoothed and theoretical rainflow matrix for Hermite-transformed Gaussian waves).
#tp_herm=dat2tp(xx_herm); #tp_herm=dat2tp(xx_herm);
#RFC_herm=tp2rfc(tp_herm); #RFC_herm=tp2rfc(tp_herm);
@ -246,11 +247,11 @@ T_markov=5000;
#subplot(222), axis('square'), title('Theoretical min-max matrix') #subplot(222), axis('square'), title('Theoretical min-max matrix')
#subplot(223), axis('square'), title('Observed smoothed rainflow matrix') #subplot(223), axis('square'), title('Observed smoothed rainflow matrix')
#subplot(224), axis('square'), title('Theoretical rainflow matrix') #subplot(224), axis('square'), title('Theoretical rainflow matrix')
#if (printing==1), print -deps ../bilder/fatigue_13.eps #if (printing==1), print -deps ../bilder/fatigue_13.eps
#end #end
#wafostamp([],'(ER)') #wafostamp([],'(ER)')
#disp('Block 16'),pause(pstate) #disp('Block 16'),pause(pstate)
# #
##!#! Section 4.3.5 Simulation from crossings and rainflow structure ##!#! Section 4.3.5 Simulation from crossings and rainflow structure
# #
##!#! Crossing spectrum (smooth curve) and obtained spectrum (wiggled curve) ##!#! Crossing spectrum (smooth curve) and obtained spectrum (wiggled curve)
@ -271,7 +272,7 @@ T_markov=5000;
#subplot(212) #subplot(212)
#plot(xx_herm_sim1(:,1),xx_herm_sim1(:,2)) #plot(xx_herm_sim1(:,1),xx_herm_sim1(:,2))
#title('Simulated load, \alpha = 0.25') #title('Simulated load, \alpha = 0.25')
#if (printing==1), print -deps ../bilder/fatigue_14_25.eps #if (printing==1), print -deps ../bilder/fatigue_14_25.eps
#end #end
#wafostamp([],'(ER)') #wafostamp([],'(ER)')
#disp('Block 16'),pause(pstate) #disp('Block 16'),pause(pstate)
@ -290,7 +291,7 @@ T_markov=5000;
#subplot(212) #subplot(212)
#plot(xx_herm_sim2(:,1),xx_herm_sim2(:,2)) #plot(xx_herm_sim2(:,1),xx_herm_sim2(:,2))
#title('Simulated load, \alpha = 0.75') #title('Simulated load, \alpha = 0.75')
#if (printing==1), print -deps ../bilder/fatigue_14_75.eps #if (printing==1), print -deps ../bilder/fatigue_14_75.eps
#end #end
#wafostamp([],'(ER)') #wafostamp([],'(ER)')
#disp('Block 17'),pause(pstate) #disp('Block 17'),pause(pstate)
@ -310,7 +311,7 @@ T_markov=5000;
#clf #clf
#plot(mu_markov(:,1),mu_markov(:,2),muObs_markov(:,1),muObs_markov(:,2),'--') #plot(mu_markov(:,1),mu_markov(:,2),muObs_markov(:,1),muObs_markov(:,2),'--')
#title('Theoretical and observed crossing intensity ') #title('Theoretical and observed crossing intensity ')
#if (printing==1), print -deps ../bilder/fatigue_15.eps #if (printing==1), print -deps ../bilder/fatigue_15.eps
#end #end
#wafostamp([],'(ER)') #wafostamp([],'(ER)')
#disp('Block 19'),pause(pstate) #disp('Block 19'),pause(pstate)
@ -324,13 +325,13 @@ T_markov=5000;
#disp('Block 20'),pause(pstate) #disp('Block 20'),pause(pstate)
# #
#Dmat_markov = cmat2dmat(param_m,Grfc_markov,beta); #Dmat_markov = cmat2dmat(param_m,Grfc_markov,beta);
#DmatObs_markov = cmat2dmat(param_m,Frfc_markov,beta)/(T_markov/2); #DmatObs_markov = cmat2dmat(param_m,Frfc_markov,beta)/(T_markov/2);
#clf #clf
#subplot(121), cmatplot(u_markov,u_markov,Dmat_markov,4) #subplot(121), cmatplot(u_markov,u_markov,Dmat_markov,4)
#title('Theoretical damage matrix') #title('Theoretical damage matrix')
#subplot(122), cmatplot(u_markov,u_markov,DmatObs_markov,4) #subplot(122), cmatplot(u_markov,u_markov,DmatObs_markov,4)
#title('Observed damage matrix') #title('Observed damage matrix')
#if (printing==1), print -deps ../bilder/fatigue_16.eps #if (printing==1), print -deps ../bilder/fatigue_16.eps
#end #end
#wafostamp([],'(ER)') #wafostamp([],'(ER)')
#disp('Block 21'),pause(pstate) #disp('Block 21'),pause(pstate)
@ -356,7 +357,7 @@ T_markov=5000;
##!#! Check of S-N-model on normal probability paper. ##!#! Check of S-N-model on normal probability paper.
# #
#normplot(reshape(log(N),8,5)) #normplot(reshape(log(N),8,5))
#if (printing==1), print -deps ../bilder/fatigue_17.eps #if (printing==1), print -deps ../bilder/fatigue_17.eps
#end #end
#wafostamp([],'(ER)') #wafostamp([],'(ER)')
#disp('Block 23'),pause(pstate) #disp('Block 23'),pause(pstate)
@ -366,7 +367,7 @@ T_markov=5000;
#[e0,beta0,s20] = snplot(s,N,12); #[e0,beta0,s20] = snplot(s,N,12);
#title('S-N-data with estimated N(s)','FontSize',20) #title('S-N-data with estimated N(s)','FontSize',20)
#set(gca,'FontSize',20) #set(gca,'FontSize',20)
#if (printing==1), print -deps ../bilder/fatigue_18a.eps #if (printing==1), print -deps ../bilder/fatigue_18a.eps
#end #end
#wafostamp([],'(ER)') #wafostamp([],'(ER)')
#disp('Block 24'),pause(pstate) #disp('Block 24'),pause(pstate)
@ -376,7 +377,7 @@ T_markov=5000;
#[e0,beta0,s20] = snplot(s,N,14); #[e0,beta0,s20] = snplot(s,N,14);
#title('S-N-data with estimated N(s)','FontSize',20) #title('S-N-data with estimated N(s)','FontSize',20)
#set(gca,'FontSize',20) #set(gca,'FontSize',20)
#if (printing==1), print -deps ../bilder/fatigue_18b.eps #if (printing==1), print -deps ../bilder/fatigue_18b.eps
#end #end
#wafostamp([],'(ER)') #wafostamp([],'(ER)')
#disp('Block 25'),pause(pstate) #disp('Block 25'),pause(pstate)
@ -388,7 +389,7 @@ T_markov=5000;
#dRFC = DRFC/T_sea; #dRFC = DRFC/T_sea;
#plot(beta,dRFC), axis([3 8 0 0.25]) #plot(beta,dRFC), axis([3 8 0 0.25])
#title('Damage intensity as function of \beta') #title('Damage intensity as function of \beta')
#if (printing==1), print -deps ../bilder/fatigue_19.eps #if (printing==1), print -deps ../bilder/fatigue_19.eps
#end #end
#wafostamp([],'(ER)') #wafostamp([],'(ER)')
#disp('Block 26'),pause(pstate) #disp('Block 26'),pause(pstate)
@ -400,7 +401,7 @@ T_markov=5000;
#[t2,F2] = ftf(e0,dam0,s20,5,1); #[t2,F2] = ftf(e0,dam0,s20,5,1);
#plot(t0,F0,t1,F1,t2,F2) #plot(t0,F0,t1,F1,t2,F2)
#title('Fatigue life distribution function') #title('Fatigue life distribution function')
#if (printing==1), print -deps ../bilder/fatigue_20.eps #if (printing==1), print -deps ../bilder/fatigue_20.eps
#end #end
#wafostamp([],'(ER)') #wafostamp([],'(ER)')
#disp('Block 27, last block') #disp('Block 27, last block')

@ -1,195 +1,238 @@
%% CHAPTER5 contains the commands used in Chapter 5 of the tutorial ## CHAPTER5 contains the commands used in Chapter 5 of the tutorial
% #
% CALL: Chapter5 # CALL: Chapter5
% #
% Some of the commands are edited for fast computation. # Some of the commands are edited for fast computation.
% Each set of commands is followed by a 'pause' command. # Each set of commands is followed by a 'pause' command.
% #
% Tested on Matlab 5.3 # Tested on Matlab 5.3
% History # History
% Added Return values by GL August 2008 # Added Return values by GL August 2008
% Revised pab sept2005 # Revised pab sept2005
% Added sections -> easier to evaluate using cellmode evaluation. # Added sections -> easier to evaluate using cellmode evaluation.
% Created by GL July 13, 2000 # Created by GL July 13, 2000
% from commands used in Chapter 5 # from commands used in Chapter 5
% #
%% Chapter 5 Extreme value analysis ## Chapter 5 Extreme value analysis
%% Section 5.1 Weibull and Gumbel papers ## Section 5.1 Weibull and Gumbel papers
from __future__ import division
import numpy as np
import scipy.interpolate as si
from wafo.plotbackend import plotbackend as plt
import wafo.data as wd
import wafo.objects as wo
import wafo.stats as ws
import wafo.kdetools as wk
pstate = 'off' pstate = 'off'
% Significant wave-height data on Weibull paper, # Significant wave-height data on Weibull paper,
clf
Hs = load('atlantic.dat'); fig = plt.figure()
wei = plotweib(Hs) ax = fig.add_subplot(111)
wafostamp([],'(ER)') Hs = wd.atlantic()
disp('Block = 1'),pause(pstate) wei = ws.weibull_min.fit(Hs)
tmp = ws.probplot(Hs, wei, ws.weibull_min, plot=ax)
%% plt.show()
% Significant wave-height data on Gumbel paper, #wafostamp([],'(ER)')
clf #disp('Block = 1'),pause(pstate)
gum=plotgumb(Hs)
wafostamp([],'(ER)') ##
disp('Block = 2'),pause(pstate) # Significant wave-height data on Gumbel paper,
plt.clf()
%% ax = fig.add_subplot(111)
% Significant wave-height data on Normal probability paper, gum = ws.gumbel_r.fit(Hs)
plotnorm(log(Hs),1,0); tmp1 = ws.probplot(Hs, gum, ws.gumbel_r, plot=ax)
wafostamp([],'(ER)') #wafostamp([],'(ER)')
disp('Block = 3'),pause(pstate) plt.show()
#disp('Block = 2'),pause(pstate)
%%
% Return values in the Gumbel distribution ##
clf # Significant wave-height data on Normal probability paper,
T=1:100000; plt.clf()
sT=gum(2) - gum(1)*log(-log(1-1./T)); ax = fig.add_subplot(111)
semilogx(T,sT), hold phat = ws.norm.fit2(np.log(Hs))
N=1:length(Hs); Nmax=max(N); phat.plotresq()
plot(Nmax./N,sort(Hs,'descend'),'.') #tmp2 = ws.probplot(np.log(Hs), phat, ws.norm, plot=ax)
title('Return values in the Gumbel model')
xlabel('Return period') #wafostamp([],'(ER)')
ylabel('Return value') plt.show()
wafostamp([],'(ER)') #disp('Block = 3'),pause(pstate)
disp('Block = 4'),pause(pstate)
##
%% Section 5.2 Generalized Pareto and Extreme Value distributions # Return values in the Gumbel distribution
%% Section 5.2.1 Generalized Extreme Value distribution plt.clf()
T = np.r_[1:100000]
% Empirical distribution of significant wave-height with estimated sT = gum[0] - gum[1] * np.log(-np.log1p(-1./T))
% Generalized Extreme Value distribution, plt.semilogx(T, sT)
gev=fitgev(Hs,'plotflag',2) plt.hold(True)
wafostamp([],'(ER)') # ws.edf(Hs).plot()
disp('Block = 5a'),pause(pstate) Nmax = len(Hs)
N = np.r_[1:Nmax+1]
clf
x = linspace(0,14,200); plt.plot(Nmax/N, sorted(Hs, reverse=True), '.')
plotkde(Hs,[x;pdfgev(x,gev)]') plt.title('Return values in the Gumbel model')
disp('Block = 5b'),pause(pstate) plt.xlabel('Return period')
plt.ylabel('Return value')
% Analysis of yura87 wave data. #wafostamp([],'(ER)')
% Wave data interpolated (spline) and organized in 5-minute intervals plt.show()
% Normalized to mean 0 and std = 1 to get stationary conditions. #disp('Block = 4'),pause(pstate)
% maximum level over each 5-minute interval analysed by GEV
xn = load('yura87.dat'); ## Section 5.2 Generalized Pareto and Extreme Value distributions
XI = 0:0.25:length(xn); ## Section 5.2.1 Generalized Extreme Value distribution
N = length(XI); N = N-mod(N,4*60*5);
YI = interp1(xn(:,1),xn(:,2),XI(1:N),'spline'); # Empirical distribution of significant wave-height with estimated
YI = reshape(YI,4*60*5,N/(4*60*5)); % Each column holds 5 minutes of # Generalized Extreme Value distribution,
% interpolated data. gev = ws.genextreme.fit2(Hs)
Y5 = (YI-ones(1200,1)*mean(YI))./(ones(1200,1)*std(YI)); gev.plotfitsummary()
Y5M = max(Y5); # wafostamp([],'(ER)')
Y5gev = fitgev(Y5M,'method','mps','plotflag',2) # disp('Block = 5a'),pause(pstate)
wafostamp([],'(ER)')
disp('Block = 6'),pause(pstate) plt.clf()
x = np.linspace(0,14,200)
%% Section 5.2.2 Generalized Pareto distribution kde = wk.TKDE(Hs, L2=0.5)(x, output='plot')
kde.plot()
% Exceedances of significant wave-height data over level 3, plt.hold(True)
gpd3 = fitgenpar(Hs(Hs>3)-3,'plotflag',1); plt.plot(x, gev.pdf(x),'--')
wafostamp([],'(ER)') # disp('Block = 5b'),pause(pstate)
%% # Analysis of yura87 wave data.
figure # Wave data interpolated (spline) and organized in 5-minute intervals
% Exceedances of significant wave-height data over level 7, # Normalized to mean 0 and std = 1 to get stationary conditions.
gpd7 = fitgenpar(Hs(Hs>7),'fixpar',[nan,nan,7],'plotflag',1); # maximum level over each 5-minute interval analysed by GEV
wafostamp([],'(ER)') xn = wd.yura87()
disp('Block = 6'),pause(pstate) XI = np.r_[1:len(xn):0.25] - .99
N = len(XI)
%% N = N - np.mod(N, 4*60*5)
%Simulates 100 values from the GEV distribution with parameters (0.3, 1, 2), then estimates the
%parameters using two different methods and plots the estimated distribution functions together YI = si.interp1d(xn[:, 0],xn[:, 1], kind='linear')(XI)
%with the empirical distribution. YI = YI.reshape(4*60*5, N/(4*60*5)) # Each column holds 5 minutes of
Rgev = rndgev(0.3,1,2,1,100); # interpolated data.
gp = fitgev(Rgev,'method','pwm'); Y5 = (YI - YI.mean(axis=0)) / YI.std(axis=0)
gm = fitgev(Rgev,'method','ml','start',gp.params,'plotflag',0); Y5M = Y5.maximum(axis=0)
Y5gev = ws.genextreme.fit2(Y5M,method='mps')
x=sort(Rgev); Y5gev.plotfitsummary()
plotedf(Rgev,gp,{'-','r-'}); #wafostamp([],'(ER)')
hold on #disp('Block = 6'),pause(pstate)
plot(x,cdfgev(x,gm),'--')
hold off ## Section 5.2.2 Generalized Pareto distribution
wafostamp([],'(ER)')
disp('Block =7'),pause(pstate) # Exceedances of significant wave-height data over level 3,
gpd3 = ws.genpareto.fit2(Hs[Hs>3]-3, floc=0)
%% gpd3.plotfitsummary()
% ; #wafostamp([],'(ER)')
Rgpd = rndgenpar(0.4,1,0,1,100);
plotedf(Rgpd); ##
hold on plt.figure()
gp = fitgenpar(Rgpd,'method','pkd','plotflag',0); # Exceedances of significant wave-height data over level 7,
x=sort(Rgpd); gpd7 = ws.genpareto.fit2(Hs(Hs>7), floc=7)
plot(x,cdfgenpar(x,gp)) gpd7.plotfitsummary()
% gm = fitgenpar(Rgpd,'method','mom','plotflag',0); # wafostamp([],'(ER)')
% plot(x,cdfgenpar(x,gm),'g--') # disp('Block = 6'),pause(pstate)
gw = fitgenpar(Rgpd,'method','pwm','plotflag',0);
plot(x,cdfgenpar(x,gw),'g:') ##
gml = fitgenpar(Rgpd,'method','ml','plotflag',0); #Simulates 100 values from the GEV distribution with parameters (0.3, 1, 2),
plot(x,cdfgenpar(x,gml),'--') # then estimates the parameters using two different methods and plots the
gmps = fitgenpar(Rgpd,'method','mps','plotflag',0); # estimated distribution functions together with the empirical distribution.
plot(x,cdfgenpar(x,gmps),'r-.') Rgev = ws.genextreme.rvs(0.3,1,2,size=100)
hold off gp = ws.genextreme.fit2(Rgev, method='mps');
wafostamp([],'(ER)') gm = ws.genextreme.fit2(Rgev, *gp.par.tolist(), method='ml')
disp('Block = 8'),pause(pstate) gm.plotfitsummary()
%% gp.plotecdf()
% Return values for the GEV distribution plt.hold(True)
T = logspace(1,5,10); plt.plot(x, gm.cdf(x), '--')
[sT, sTlo, sTup] = invgev(1./T,Y5gev,'lowertail',false,'proflog',true); plt.hold(False)
#wafostamp([],'(ER)')
%T = 2:100000; #disp('Block =7'),pause(pstate)
%k=Y5gev.params(1); mu=Y5gev.params(3); sigma=Y5gev.params(2);
%sT1 = invgev(1./T,Y5gev,'lowertail',false); ##
%sT=mu + sigma/k*(1-(-log(1-1./T)).^k); # ;
clf Rgpd = ws.genpareto.rvs(0.4,0, 1,size=100)
semilogx(T,sT,T,sTlo,'r',T,sTup,'r'), hold gp = ws.genpareto.fit2(Rgpd, method='mps')
N=1:length(Y5M); Nmax=max(N); gml = ws.genpareto.fit2(Rgpd, method='ml')
plot(Nmax./N,sort(Y5M,'descend'),'.')
title('Return values in the GEV model') gp.plotecdf()
xlabel('Return priod') x = sorted(Rgpd)
ylabel('Return value') plt.hold(True)
grid on plt.plot(x, gml.cdf(x))
disp('Block = 9'),pause(pstate) # gm = fitgenpar(Rgpd,'method','mom','plotflag',0);
# plot(x,cdfgenpar(x,gm),'g--')
%% Section 5.3 POT-analysis #gw = fitgenpar(Rgpd,'method','pwm','plotflag',0);
#plot(x,cdfgenpar(x,gw),'g:')
% Estimated expected exceedance over level u as function of u. #gml = fitgenpar(Rgpd,'method','ml','plotflag',0);
clf #plot(x,cdfgenpar(x,gml),'--')
plotreslife(Hs,'umin',2,'umax',10,'Nu',200); #gmps = fitgenpar(Rgpd,'method','mps','plotflag',0);
wafostamp([],'(ER)') #plot(x,cdfgenpar(x,gmps),'r-.')
disp('Block = 10'),pause(pstate) plt.hold(False)
#wafostamp([],'(ER)')
%% #disp('Block = 8'),pause(pstate)
% Estimated distribution functions of monthly maxima
%with the POT method (solid), ##
% fitting a GEV (dashed) and the empirical distribution. # Return values for the GEV distribution
T = np.logspace(1, 5, 10);
% POT- method #[sT, sTlo, sTup] = invgev(1./T,Y5gev,'lowertail',false,'proflog',true);
gpd7 = fitgenpar(Hs(Hs>7)-7,'method','pwm','plotflag',0);
khat = gpd7.params(1); #T = 2:100000;
sigmahat = gpd7.params(2); #k=Y5gev.params(1); mu=Y5gev.params(3); sigma=Y5gev.params(2);
muhat = length(Hs(Hs>7))/(7*3*2); #sT1 = invgev(1./T,Y5gev,'lowertail',false);
bhat = sigmahat/muhat^khat; #sT=mu + sigma/k*(1-(-log(1-1./T)).^k);
ahat = 7-(bhat-sigmahat)/khat; plt.clf()
x = linspace(5,15,200); #plt.semilogx(T,sT,T,sTlo,'r',T,sTup,'r')
plot(x,cdfgev(x,khat,bhat,ahat)) #plt.hold(True)
disp('Block = 11'),pause(pstate) #N = np.r_[1:len(Y5M)]
#Nmax = max(N);
%% #plot(Nmax./N, sorted(Y5M,reverse=True), '.')
% Since we have data to compute the monthly maxima mm over #plt.title('Return values in the GEV model')
%42 months we can also try to fit a #plt.xlabel('Return priod')
% GEV distribution directly: #plt.ylabel('Return value')
mm = zeros(1,41); #plt.grid(True)
for i=1:41 #disp('Block = 9'),pause(pstate)
mm(i)=max(Hs(((i-1)*14+1):i*14));
end ## Section 5.3 POT-analysis
gev=fitgev(mm); # Estimated expected exceedance over level u as function of u.
hold on plt.clf()
plotedf(mm)
plot(x,cdfgev(x,gev),'--') mrl = ws.reslife(Hs,'umin',2,'umax',10,'Nu',200);
hold off mrl.plot()
wafostamp([],'(ER)') #wafostamp([],'(ER)')
disp('Block = 12, Last block'),pause(pstate) #disp('Block = 10'),pause(pstate)
##
# Estimated distribution functions of monthly maxima
#with the POT method (solid),
# fitting a GEV (dashed) and the empirical distribution.
# POT- method
gpd7 = ws.genpareto.fit2(Hs(Hs>7)-7, method='mps', floc=0)
khat, loc, sigmahat = gpd7.par
muhat = len(Hs[Hs>7])/(7*3*2)
bhat = sigmahat/muhat**khat
ahat = 7-(bhat-sigmahat)/khat
x = np.linspace(5,15,200);
plt.plot(x,ws.genextreme.cdf(x, khat,bhat,ahat))
# disp('Block = 11'),pause(pstate)
##
# Since we have data to compute the monthly maxima mm over
#42 months we can also try to fit a
# GEV distribution directly:
mm = np.zeros((1,41))
for i in range(41):
mm[i] = max(Hs[((i-1)*14+1):i*14])
gev = ws.genextreme.fit2(mm)
plt.hold(True)
gev.plotecdf()
plt.hold(False)
#wafostamp([],'(ER)')
#disp('Block = 12, Last block'),pause(pstate)

@ -45,7 +45,10 @@ def delete_text_object(gidtxt, figure=None, axis=None, verbose=False):
def _delete_gid_objects(handle, gidtxt, verbose): def _delete_gid_objects(handle, gidtxt, verbose):
objs = handle.findobj(lmatchfun) objs = handle.findobj(lmatchfun)
name = handle.__name__ try:
name = handle.__class__.__name__
except AttributeError:
name = 'unknown object'
msg = "Tried to delete a non-existing {0} from {1}".format(gidtxt, msg = "Tried to delete a non-existing {0} from {1}".format(gidtxt,
name) name)
for obj in objs: for obj in objs:
@ -127,7 +130,10 @@ def cltext(levels, percent=False, n=4, xs=0.036, ys=0.94, zs=0, figure=None,
yss = yint[0] + ys * (yint[1] - yint[0]) yss = yint[0] + ys * (yint[1] - yint[0])
# delete cltext object if it exists # delete cltext object if it exists
delete_text_object(_CLTEXT_GID, axis=axis) try:
delete_text_object(_CLTEXT_GID, axis=axis)
except Exception:
pass
charHeight = 1.0 / 33.0 charHeight = 1.0 / 33.0
delta_y = charHeight delta_y = charHeight

@ -3447,8 +3447,10 @@ class SpecData1D(PlotData):
>>> S.bandwidth([0,'eps2',2,3]) >>> S.bandwidth([0,'eps2',2,3])
array([ 0.73062845, 0.34476034, 0.68277527, 2.90817052]) array([ 0.73062845, 0.34476034, 0.68277527, 2.90817052])
''' '''
m, unused_mtxt = self.moment(nr=4, even=False)
m, unused_mtxt = self.moment(nr=4, even=False)
if isinstance(factors, str):
factors = [factors]
fact_dict = dict(alpha=0, eps2=1, eps4=3, qp=3, Qp=3) fact_dict = dict(alpha=0, eps2=1, eps4=3, qp=3, Qp=3)
fact = array([fact_dict.get(idx, idx) fact = array([fact_dict.get(idx, idx)
for idx in list(factors)], dtype=int) for idx in list(factors)], dtype=int)

Loading…
Cancel
Save