示例#1
0
文件: core.py 项目: Bobfrat/pywafo
def main():
    import wafo.spectrum.models as sm
    import matplotlib
    matplotlib.interactive(True)
    Sj = sm.Jonswap()
    S = Sj.tospecdata()  # Make spec
    S.plot()
    R = S.tocovdata(rate=3)
    R.plot()
    x = R.sim(ns=1024 * 4)
    inds = np.hstack((21 + np.arange(20), 1000 + np.arange(20),
                      1024 * 4 - 21 + np.arange(20)))
    sample, mu1o, mu1o_std = R.simcond(x[:, 1],
                                       method='approx',
                                       i_unknown=inds)

    import matplotlib.pyplot as plt
    # inds = np.atleast_2d(inds).reshape((-1,1))
    plt.plot(x[:, 1], 'k.', label='observed values')
    plt.plot(inds, mu1o, '*', label='mu1o')
    plt.plot(inds, sample.ravel(), 'r+', label='samples')
    plt.plot(inds,
             mu1o - 2 * mu1o_std,
             'r',
             inds,
             mu1o + 2 * mu1o_std,
             'r',
             label='2 stdev')
    plt.legend()
    plt.show('hold')
示例#2
0
    def test_bandwidth(self):

        Sj = sm.Jonswap(Hm0=3, Tp=7)
        w = np.linspace(0, 4, 256)
        S = SpecData1D(Sj(w), w)  # Make spectrum object from numerical values
        vals = S.bandwidth([0, 1, 2, 3])
        true_vals = [0.73062845, 0.34476034, 0.68277527, 2.90817052]
        assert_array_almost_equal(vals, true_vals)
示例#3
0
def test_bandwidth():

    Sj = sm.Jonswap(Hm0=3, Tp=7)
    w = np.linspace(0, 4, 256)
    S = SpecData1D(Sj(w), w)  # Make spectrum object from numerical values
    vals = S.bandwidth([0, 1, 2, 3])
    true_vals = np.array([0.73062845, 0.34476034, 0.68277527, 2.90817052])
    assert ((np.abs(vals - true_vals) < 1e-7).all())
示例#4
0
 def test_tocovmatrix(self):
     Sj = sm.Jonswap()
     S = Sj.tospecdata()
     acfmat = S.tocov_matrix(nr=3, nt=256, dt=0.1)
     vals = acfmat[:2, :]
     true_vals = np.array(
         [[3.06073383, 0.0000000, -1.67748256, 0.],
          [3.05235423, -0.1674357, -1.66811444, 0.18693242]])
     self.assertTrue((np.abs(vals - true_vals) < 1e-7).all())
示例#5
0
def test_moment():
    Sj = sm.Jonswap(Hm0=5)
    S = Sj.tospecdata()  # Make spectrum ob
    vals, txt = S.moment()
    true_vals = [1.5614600345079888, 0.95567089481941048]
    true_txt = ['m0', 'm0tt']
    for tv, v in zip(true_vals, vals):
        assert (tv == v)
    for tv, v in zip(true_txt, txt):
        assert (tv == v)
示例#6
0
def test_stats_nl():

    Hs = 7.
    Sj = sm.Jonswap(Hm0=Hs, Tp=11)
    S = Sj.tospecdata()
    me, va, sk, ku = S.stats_nl(moments='mvsk')
    assert (me == 0.0)
    assert (va == 3.0608203389019537)
    assert (sk == 0.18673120577479801)
    assert (ku == 3.0619885212624176)
示例#7
0
def test_tocovdata():
    Sj = sm.Jonswap()
    S = Sj.tospecdata()
    Nt = len(S.data) - 1
    acf = S.tocovdata(nr=0, nt=Nt)
    vals = acf.data[:5]

    true_vals = np.array(
        [3.06090339, 2.22658399, 0.45307391, -1.17495501, -2.05649042])
    assert ((np.abs(vals - true_vals) < 1e-6).all())
示例#8
0
def test_sim():
    Sj = sm.Jonswap()
    S = Sj.tospecdata()
    #ns = 100
    #dt = .2
    #x1 = S.sim(ns, dt=dt)

    import scipy.stats as st
    x2 = S.sim(20000, 20)
    truth1 = [0, np.sqrt(S.moment(1)[0]), 0., 0.]
    funs = [np.mean, np.std, st.skew, st.kurtosis]
    for fun, trueval in zip(funs, truth1):
        res = fun(x2[:, 1::], axis=0)
        m = res.mean()
        sa = res.std()
        #trueval, m, sa
        assert (np.abs(m - trueval) < sa)
示例#9
0
def test_normalize():
    Sj = sm.Jonswap(Hm0=5)
    S = Sj.tospecdata()  # Make spectrum ob
    S.moment(2)
    ([1.5614600345079888, 0.95567089481941048], ['m0', 'm0tt'])
    vals, _txt = S.moment(2)
    true_vals = [1.5614600345079888, 0.95567089481941048]
    for tv, v in zip(true_vals, vals):
        assert (tv == v)

    Sn = S.copy()
    Sn.normalize()

    # Now the moments should be one
    new_vals, _txt = Sn.moment(2)
    for v in new_vals:
        assert (np.abs(v - 1.0) < 1e-7)
示例#10
0
    def test_timeseries_trdata(self):
        Hs = 7.0
        Sj = sm.Jonswap(Hm0=Hs)
        S = Sj.tospecdata()  # Make spectrum object from numerical values
        S.tr = tm.TrOchi(mean=0, skew=0.16, kurt=0, sigma=Hs/4, ysigma=Hs/4)
        xs = S.sim(ns=2**20, iseed=10)
        ts = wo.mat2timeseries(xs)
        g0, _gemp = ts.trdata(monitor=False)  # Not Monitor the development

        # Equal weight on all points
        g1, _gemp = ts.trdata(method='mnonlinear', gvar=0.5)

        # Less weight on the ends
        g2, _gemp = ts.trdata(method='nonlinear', gvar=[3.5, 0.5, 3.5])
        self.assert_(1.2 < S.tr.dist2gauss() < 1.6)
        self.assert_(1.65 < g0.dist2gauss() < 2.05)
        self.assert_(0.54 < g1.dist2gauss() < 0.95)
        self.assert_(1.5 < g2.dist2gauss() < 1.9)
示例#11
0
def test_covariance():
    Sj = sm.Jonswap()
    S = Sj.tospecdata()  # Make spec
    R = S.tocovdata()
    dt = R.sampling_period()
    assert_equal(dt, 1.0471975511965976)
    S1 = R.tospecdata()
    assert_array_almost_equal(S.data[:10], S1.data[:10], 11)
    x = R.sim(ns=1000, dt=0.2, iseed=0)
    assert_array_almost_equal(x[:10, 0], [
        0.0, 1.04719755, 2.0943951, 3.14159265, 4.1887902, 5.23598776,
        6.28318531, 7.33038286, 8.37758041, 9.42477796
    ],
                              decimal=3)
    assert_array_almost_equal(x[:10, 1], [
        0.22155905, 1.21207066, 1.95670282, 2.11634902, 1.57967273, 0.2665005,
        -0.79630253, -1.31908028, -2.20056021, -1.84451748
    ],
                              decimal=3)
示例#12
0
def test_testgaussian():

    Hs = 7
    Sj = sm.Jonswap(Hm0=Hs)
    S0 = Sj.tospecdata()
    #ns =100; dt = .2
    #x1 = S0.sim(ns, dt=dt)

    S = S0.copy()
    me, _va, sk, ku = S.stats_nl(moments='mvsk')
    S.tr = wtm.TrHermite(mean=me,
                         sigma=Hs / 4,
                         skew=sk,
                         kurt=ku,
                         ysigma=Hs / 4)
    ys = wo.mat2timeseries(S.sim(ns=2**13))
    g0, _gemp = ys.trdata()
    t0 = g0.dist2gauss()
    t1 = S0.testgaussian(ns=2**13, t0=t0, cases=50)
    assert (sum(t1 > t0) < 5)
示例#13
0
def test_to_t_pdf():
    Sj = sm.Jonswap()
    S = Sj.tospecdata()
    f = S.to_t_pdf(pdef='Tc', paramt=(0, 10, 51), speed=7, seed=100)
    vals = ['%2.3f' % val for val in f.data[:10]]
    truevals = [
        '0.000', '0.014', '0.027', '0.040', '0.050', '0.059', '0.067', '0.073',
        '0.077', '0.082'
    ]
    for t, v in zip(truevals, vals):
        assert (t == v)

    # estimated error bounds
    vals = ['%2.4f' % val for val in f.err[:10]]
    truevals = [
        '0.0000', '0.0003', '0.0003', '0.0004', '0.0006', '0.0008', '0.0016',
        '0.0019', '0.0020', '0.0021'
    ]
    for t, v in zip(truevals, vals):
        assert (t == v)
示例#14
0
def test_sim_nl():

    Sj = sm.Jonswap()
    S = Sj.tospecdata()
    #    ns = 100
    #    dt = .2
    #    x1 = S.sim_nl(ns, dt=dt)
    import scipy.stats as st
    x2, _x1 = S.sim_nl(ns=20000, cases=40)
    truth1 = [0, np.sqrt(S.moment(1)[0][0])] + S.stats_nl(moments='sk')
    truth1[-1] = truth1[-1] - 3

    # truth1
    #[0, 1.7495200310090633, 0.18673120577479801, 0.061988521262417606]

    funs = [np.mean, np.std, st.skew, st.kurtosis]
    for fun, trueval in zip(funs, truth1):
        res = fun(x2[:, 1::], axis=0)
        m = res.mean()
        sa = res.std()
        #trueval, m, sa
        assert (np.abs(m - trueval) < 2 * sa)
示例#15
0
#!------------------------
#! indicates that the underlying distribution has a "heavy" upper tail and a
#! "light" lower tail.
clf()
import pylab
ws.probplot(ts.data.ravel(), dist='norm', plot=pylab)
show()
#! Section 2.2.3 Spectral densities of sea data
#!-----------------------------------------------
#! Example 2: Different forms of spectra
#!
import wafo.spectrum.models as wsm
clf()
Hm0 = 7
Tp = 11
spec = wsm.Jonswap(Hm0=Hm0, Tp=Tp).tospecdata()
spec.plot()
show()

#! Directional spectrum and Encountered directional spectrum
#! Directional spectrum
clf()
D = wsm.Spreading('cos2s')
Sd = D.tospecdata2d(spec)
Sd.plot()
show()

##!Encountered directional spectrum
##!---------------------------------
#clf()
#Se = spec2spec(Sd,'encdir',0,10);
示例#16
0
Tcb = wave_data['Tcb']
Tc = Tcf + Tcb
fTcAc = wk.TKDE([Tc, Ac], L2=0.5, inc=256).eval_grid_fast(output='plot')
fTcAc.labels.labx = 'Tc [s]'
fTcAc.labels.laby = 'Ac [m]'
fTcAc.plot()
plt.hold(True)
plt.plot(Tc, Ac, 'k.')
plt.hold(False)
plt.show()
#wafostamp([],'(ER)')
#disp('Block = 11'), pause(pstate)

#!#! Example 4:  Simple wave characteristics obtained from Jonswap spectrum
plt.clf()
S = wsm.Jonswap(Hm0=5, Tp=10).tospecdata()
m, mt = S.moment(nr=4, even=False)
print(m)
print(mt)
# disp('Block = 12'), pause(pstate)

plt.clf()
S.bandwidth(['alpha'])
ch, Sa2, chtxt = S.characteristic(['Hm0', 'Tm02'])

# disp('Block = 13'), pause(pstate)

#!#! Section 3.3.2 Explicit form approximations of wave characteristic densities
#!#! Longuett-Higgins model for Tc and Ac
# plt.clf()
# t = np.linspace(0,15,100)
示例#17
0
def demo_tide_filter():
    """
    Examples
    --------
    >>> demo_tide_filter()

    >>> plt.close()
    """
    # import statsmodels.api as sa
    import wafo.spectrum.models as sm
    sd = 10
    Sj = sm.Jonswap(Hm0=4. * sd)
    S = Sj.tospecdata()

    q = (0.1 * sd)**2  # variance of process noise s the car operates
    r = (100 * sd)**2  # variance of measurement error
    b = 0  # no system input
    u = 0  # no system input

    from scipy.signal import butter, filtfilt, lfilter_zi  # lfilter,
    freq_tide = 1. / (12 * 60 * 60)
    freq_wave = 1. / 10
    freq_filt = freq_wave / 10
    dt = 1.
    freq = 1. / dt
    fn = (freq / 2)

    P = 10 * np.diag([1, 0.01])
    R = r
    H = np.atleast_2d([1, 0])

    F = np.atleast_2d([[0, 1], [0, 0]])
    A, Q = lti_disc(F, L=None, Q=np.diag([0, q]), dt=dt)

    t = np.arange(0, 60 * 12, 1. / freq)
    w = 2 * np.pi * freq  # 1 Hz
    tide = 100 * np.sin(freq_tide * w * t + 2 * np.pi / 4) + 100
    y = tide + S.sim(len(t), dt=1. / freq)[:, 1].ravel()
    #     lowess = sa.nonparametric.lowess
    #     y2 = lowess(y, t, frac=0.5)[:,1]

    filt = Kalman(R=R, x=np.array([[tide[0]], [0]]), P=P, A=A, Q=Q, H=H, B=b)
    filt2 = Kalman(R=R, x=np.array([[tide[0]], [0]]), P=P, A=A, Q=Q, H=H, B=b)
    # y = tide + 0.5 * np.sin(freq_wave * w * t)
    # Butterworth filter
    b, a = butter(9, (freq_filt / fn), btype='low')
    # y2 = [lowess(y[max(i-60,0):i + 1], t[max(i-60,0):i + 1], frac=.3)[-1,1]
    #    for i in range(len(y))]
    # y2 = [lfilter(b, a, y[:i + 1])[i] for i in range(len(y))]
    # y3 = filtfilt(b, a, y[:16]).tolist() + [filtfilt(b, a, y[:i + 1])[i]
    #    for i in range(16, len(y))]
    # y0 = medfilt(y, 41)
    _zi = lfilter_zi(b, a)
    # y2 = lfilter(b, a, y)#, zi=y[0]*zi)  # standard filter
    y3 = filtfilt(b, a, y)  # filter with phase shift correction
    y4 = []
    y5 = []
    for _i, j in enumerate(y):
        tmp = np.ravel(filt(j, u=u))
        tmp = np.ravel(filt2(tmp[0], u=u))
        #         if i==0:
        #             print(filt.x)
        #             print(filt2.x)
        y4.append(tmp[0])
        y5.append(tmp[1])
    _y0 = medfilt(y4, 41)
    # print(filt.P)
    # plot

    plt.plot(t, y, 'r.-', linewidth=2, label='raw data')
    # plt.plot(t, y2, 'b.-', linewidth=2, label='lowess @ %g Hz' % freq_filt)
    # plt.plot(t, y2, 'b.-', linewidth=2, label='filter @ %g Hz' % freq_filt)
    plt.plot(t, y3, 'g.-', linewidth=2, label='filtfilt @ %g Hz' % freq_filt)
    plt.plot(t, y4, 'k.-', linewidth=2, label='kalman')
    # plt.plot(t, y5, 'k.', linewidth=2, label='kalman2')
    plt.plot(t, tide, 'y-', linewidth=2, label='True tide')
    plt.legend(frameon=False, fontsize=14)
    plt.xlabel("Time [s]")
    plt.ylabel("Amplitude")
示例#18
0
import wafo.spectrum.models as wsm
import matplotlib.pyplot as plt
import numpy as np
from pprint import pprint

print("\n\n\n")

# creating Jonswap spectrum from wafo methods
S1 = wsm.Jonswap(Hm0=7, Tp=11, gamma=1)
S1_specData = S1.tospecdata()

# plot spectrum via wafo style
S1_specData.plot()
S1_specData.show()

# getting angular frequency and spectrum variables
freq = S1_specData.args  # w    [rad/s]
spec = S1_specData.data  # S(w) [m2.s/rad]

# matplotlib plot
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(freq, spec, label="direct from [wafo.tospecdata] method")
plt.xlabel(r'Frequency [rad/s]', fontsize=12)
plt.ylabel(r'$S(\omega)$ $[m^2.s/rad]$', fontsize=12)
plt.legend(loc="upper left")
plt.show()

# I can use directly the wave spectrum and define my own frequency range
w = np.linspace(0, 2, 400)
fig = plt.figure()
示例#19
0
def test_nyquist_freq():
    Sj = sm.Jonswap(Hm0=5)
    S = Sj.tospecdata()  # Make spectrum ob
    assert (S.nyquist_freq() == 3.0)
示例#20
0
 def setUp(self):
     self.Sj = sm.Jonswap(Hm0=7.0, Tp=11)
     self.S = self.Sj.tospecdata()
示例#21
0
 def setUp(self):
     self.Sj = sm.Jonswap(Hm0=5.0)
     self.S = self.Sj.tospecdata()
示例#22
0
def test_sampling_period():
    Sj = sm.Jonswap(Hm0=5)
    S = Sj.tospecdata()  # Make spectrum ob
    assert (S.sampling_period() == 1.0471975511965976)