def kde_demo5(N=500): """Demonstrate that the improved Sheather-Jones plug-in (hisj) is superior for 2D multimodal distributions KDEDEMO5 shows that the improved Sheather-Jones plug-in smoothing is better compared to normal reference rules (in this case the hns) Examples -------- >>> kde_demo5() """ data = np.hstack((st.norm.rvs(loc=5, scale=1, size=(2, N,)), st.norm.rvs(loc=-5, scale=1, size=(2, N,)))) kde = KDE(data, kernel=Kernel('gauss', 'hns')) f = kde(output='plot', plotflag=1, title='Ordinary KDE, hns={0:s}'.format(str(list(kde.hs)))) kde1 = KDE(data, kernel=Kernel('gauss', 'hisj')) f1 = kde1(output='plot', plotflag=1, title='Ordinary KDE, hisj={0:s}'.format(str(list(kde1.hs)))) plt.figure(0) plt.clf() f.plot() plt.plot(data[0], data[1], '.') plt.figure(1) plt.clf() f1.plot() plt.plot(data[0], data[1], '.')
lc.plot() plt.show() m_sea = ts.data.mean() f0_sea = np.interp(m_sea, lc.args, lc.data) extr_sea = len(tp.data) / (2 * T_sea) alfa_sea = f0_sea / extr_sea print('alfa = %g ' % alfa_sea) #! Section 4.3.2 Extraction of rainflow cycles #!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #! Min-max and rainflow cycle plots #!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ mM_rfc = tp.cycle_pairs(h=0.3) plt.clf() plt.subplot(122), mM.plot() plt.title('min-max cycle pairs') plt.subplot(121), mM_rfc.plot() plt.title('Rainflow filtered cycles') plt.show() #! Min-max and rainflow cycle distributions #!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import wafo.misc as wm ampmM_sea = mM.amplitudes() ampRFC_sea = mM_rfc.amplitudes() plt.clf() plt.subplot(121)
plt.show() m_sea = ts.data.mean() f0_sea = np.interp(m_sea, lc.args,lc.data) extr_sea = len(tp.data)/(2*T_sea) alfa_sea = f0_sea/extr_sea print('alfa = %g ' % alfa_sea) #! Section 4.3.2 Extraction of rainflow cycles #!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #! Min-max and rainflow cycle plots #!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ mM_rfc = tp.cycle_pairs(h=0.3) plt.clf() plt.subplot(122), mM.plot() plt.title('min-max cycle pairs') plt.subplot(121), mM_rfc.plot() plt.title('Rainflow filtered cycles') plt.show() #! Min-max and rainflow cycle distributions #!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import wafo.misc as wm ampmM_sea = mM.amplitudes() ampRFC_sea = mM_rfc.amplitudes() plt.clf() plt.subplot(121)
import scipy.signal as ss import wafo.data as wd import wafo.misc as wm import wafo.objects as wo import wafo.stats as ws import wafo.spectrum.models as wsm xx = wd.sea() xx[:, 1] = ss.detrend(xx[:, 1]) ts = wo.mat2timeseries(xx) Tcrcr, ix = ts.wave_periods(vh=0, pdef='c2c', wdef='tw', rate=8) Tc, ixc = ts.wave_periods(vh=0, pdef='u2d', wdef='tw', rate=8) #! Histogram of crestperiod compared to the kernel density estimate #!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import wafo.kdetools as wk plt.clf() print(Tc.mean()) print(Tc.max()) t = np.linspace(0.01,8,200); ftc = wk.TKDE(Tc, L2=0, inc=128) plt.plot(t,ftc.eval_grid(t), t, ftc.eval_grid_fast(t),'-.') wm.plot_histgrm(Tc, normed=True) plt.title('Kernel Density Estimates') plt.xlabel('Tc [s]') plt.axis([0, 8, 0, 0.5]) plt.show() #! Extreme waves - model check: the highest and steepest wave #!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def gaussq(fun, a, b, reltol=1e-3, abstol=1e-3, alpha=0, beta=0, wfun=1, trace=False, args=None): ''' Numerically evaluate integral, Gauss quadrature. Parameters ---------- fun : callable a,b : array-like lower and upper integration limits, respectively. reltol, abstol : real scalars, optional relative and absolute tolerance, respectively. (default reltol=abstool=1e-3). wfun : scalar integer, optional defining the weight function, p(x). (default wfun = 1) 1 : p(x) = 1 a =-1, b = 1 Gauss-Legendre 2 : p(x) = exp(-x^2) a =-inf, b = inf Hermite 3 : p(x) = x^alpha*exp(-x) a = 0, b = inf Laguerre 4 : p(x) = (x-a)^alpha*(b-x)^beta a =-1, b = 1 Jacobi 5 : p(x) = 1/sqrt((x-a)*(b-x)), a =-1, b = 1 Chebyshev 1'st kind 6 : p(x) = sqrt((x-a)*(b-x)), a =-1, b = 1 Chebyshev 2'nd kind 7 : p(x) = sqrt((x-a)/(b-x)), a = 0, b = 1 8 : p(x) = 1/sqrt(b-x), a = 0, b = 1 9 : p(x) = sqrt(b-x), a = 0, b = 1 trace : bool, optional If non-zero a point plot of the integrand (default False). gn : scalar integer number of base points to start the integration with (default 2). alpha, beta : real scalars, optional Shape parameters of Laguerre or Jacobi weight function (alpha,beta>-1) (default alpha=beta=0) Returns ------- val : ndarray evaluated integral err : ndarray error estimate, absolute tolerance abs(int-intold) Notes ----- GAUSSQ numerically evaluate integral using a Gauss quadrature. The Quadrature integrates a (2m-1)th order polynomial exactly and the integral is of the form b Int (p(x)* Fun(x)) dx a GAUSSQ is vectorized to accept integration limits A, B and coefficients P1,P2,...Pn, as matrices or scalars and the result is the common size of A, B and P1,P2,...,Pn. Examples --------- integration of x**2 from 0 to 2 and from 1 to 4 >>> from scitools import numpyutils as npt >>> A = [0, 1]; B = [2,4] >>> fun = npt.wrap2callable('x**2') >>> [val1,err1] = gaussq(fun,A,B) >>> val1 array([ 2.6666667, 21. ]) >>> err1 array([ 1.7763568e-15, 1.0658141e-14]) Integration of x^2*exp(-x) from zero to infinity: >>> fun2 = npt.wrap2callable('1') >>> val2, err2 = gaussq(fun2, 0, npt.inf, wfun=3, alpha=2) >>> val3, err3 = gaussq(lambda x: x**2,0, npt.inf, wfun=3, alpha=0) >>> val2, err2 (array([ 2.]), array([ 6.6613381e-15])) >>> val3, err3 (array([ 2.]), array([ 1.7763568e-15])) Integrate humps from 0 to 2 and from 1 to 4 >>> val4, err4 = gaussq(humps,A,B) See also -------- qrule gaussq2d ''' global _POINTS_AND_WEIGHTS max_iter = 11 gn = 2 if not hasattr(fun, '__call__'): raise ValueError('Function must be callable') A, B = np.atleast_1d(a, b) a_shape = np.atleast_1d(A.shape) b_shape = np.atleast_1d(B.shape) if np.prod(a_shape) == 1: # make sure the integration limits have correct size A = A * ones(b_shape) a_shape = b_shape elif np.prod(b_shape) == 1: B = B * ones(a_shape) elif any(a_shape != b_shape): raise ValueError('The integration limits must have equal size!') if args is None: num_parameters = 0 else: num_parameters = len(args) P0 = copy.deepcopy(args) isvector1 = zeros(num_parameters) nk = np.prod(a_shape) #% # of integrals we have to compute for ix in xrange(num_parameters): if is_numlike(P0[ix]): p0_shape = np.shape(P0[ix]) Np0 = np.prod(p0_shape) isvector1[ix] = (Np0 > 1) if isvector1[ix]: if nk == 1: a_shape = p0_shape nk = Np0 A = A * ones(a_shape) B = B * ones(a_shape) elif nk != Np0: raise ValueError('The input must have equal size!') P0[ix].shape = (-1, 1) # make sure it is a column k = np.arange(nk) val = zeros(nk) val_old = zeros(nk) abserr = zeros(nk) #setup mapping parameters A.shape = (-1, 1) B.shape = (-1, 1) jacob = (B - A) / 2 shift = 1 if wfun == 1:# Gauss-legendre dx = jacob elif wfun == 2 or wfun == 3: shift = 0 jacob = ones((nk, 1)) A = zeros((nk, 1)) dx = jacob elif wfun == 4: dx = jacob ** (alpha + beta + 1) elif wfun == 5: dx = ones((nk, 1)) elif wfun == 6: dx = jacob ** 2 elif wfun == 7: shift = 0 jacob = jacob * 2 dx = jacob elif wfun == 8: shift = 0 jacob = jacob * 2 dx = sqrt(jacob) elif wfun == 9: shift = 0 jacob = jacob * 2 dx = sqrt(jacob) ** 3 else: raise ValueError('unknown option') dx = dx.ravel() if trace: x_trace = [0, ]*max_iter y_trace = [0, ]*max_iter if num_parameters > 0: ix_vec, = np.where(isvector1) if len(ix_vec): P1 = copy.copy(P0) #% Break out of the iteration loop for three reasons: #% 1) the last update is very small (compared to int and compared to reltol) #% 2) There are more than 11 iterations. This should NEVER happen. for ix in xrange(max_iter): x_and_w = 'wfun%d_%d_%g_%g' % (wfun, gn, alpha, beta) if x_and_w in _POINTS_AND_WEIGHTS: xn, w = _POINTS_AND_WEIGHTS[x_and_w] else: xn, w = qrule(gn, wfun, alpha, beta) _POINTS_AND_WEIGHTS[x_and_w] = (xn, w) # calculate the x values x = (xn + shift) * jacob[k, :] + A[k, :] # calculate function values y=fun(x,p1,p2,....,pn) if num_parameters > 0: if len(ix_vec): #% Expand vector to the correct size for iy in ix_vec: P1[iy] = P0[iy][k, :] y = fun(x, **P1) else: y = fun(x, **P0) else: y = fun(x) val[k] = np.sum(w * y, axis=1) * dx[k] # do the integration sum(y.*w) if trace: x_trace.append(x.ravel()) y_trace.append(y.ravel()) hfig = plt.plot(x, y, 'r.') #hold on #drawnow,shg #if trace>1: # pause plt.setp(hfig, 'color', 'b') abserr[k] = abs(val_old[k] - val[k]) #absolute tolerance if ix > 1: k, = np.where(abserr > np.maximum(abs(reltol * val), abstol)) # abserr > abs(abstol))%indices to integrals which did not converge nk = len(k)# of integrals we have to compute again if nk : val_old[k] = val[k] else: break gn *= 2 #double the # of basepoints and weights else: if nk > 1: if (nk == np.prod(a_shape)): tmptxt = 'All integrals did not converge--singularities likely!' else: tmptxt = '%d integrals did not converge--singularities likely!' % (nk,) else: tmptxt = 'Integral did not converge--singularity likely!' warnings.warn(tmptxt) val.shape = a_shape # make sure int is the same size as the integration limits abserr.shape = a_shape if trace > 0: plt.clf() plt.plot(np.hstack(x_trace), np.hstack(y_trace), '+') return val, abserr
import scipy.signal as ss import wafo.data as wd import wafo.misc as wm import wafo.objects as wo import wafo.stats as ws import wafo.spectrum.models as wsm xx = wd.sea() xx[:, 1] = ss.detrend(xx[:, 1]) ts = wo.mat2timeseries(xx) Tcrcr, ix = ts.wave_periods(vh=0, pdef='c2c', wdef='tw', rate=8) Tc, ixc = ts.wave_periods(vh=0, pdef='u2d', wdef='tw', rate=8) #! Histogram of crestperiod compared to the kernel density estimate #!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import wafo.kdetools as wk plt.clf() print(Tc.mean()) print(Tc.max()) t = np.linspace(0.01, 8, 200) ftc = wk.TKDE(Tc, L2=0, inc=128) plt.plot(t, ftc.eval_grid(t), t, ftc.eval_grid_fast(t), '-.') wm.plot_histgrm(Tc, normed=True) plt.title('Kernel Density Estimates') plt.xlabel('Tc [s]') plt.axis([0, 8, 0, 0.5]) plt.show() #! Extreme waves - model check: the highest and steepest wave #!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def _plot_final_trace(self): if self.trace > 0: plt.clf() plt.plot(np.hstack(self.x_trace), np.hstack(self.y_trace), '+')