Exemple #1
0
def test_findtc():
    x = sea()
    x1 = x[0:200, :]
    itc, iv = findtc(x1[:, 1], 0, 'dw')
    assert_allclose(itc, [28, 31, 39, 56, 64, 69, 78, 82, 83, 89, 94, 101, 108,
                          119, 131, 140, 148, 159, 173, 184])
    assert_allclose(iv, [19, 29, 34, 53, 60, 67, 76, 81, 82, 84, 90, 99, 103,
                         112, 127, 137, 143, 154, 166, 180, 185])
Exemple #2
0
def test_findtc():
    x = sea()
    x1 = x[0:200, :]
    itc, iv = findtc(x1[:, 1], 0, 'dw')
    assert_array_almost_equal(
        itc,
        np.array(
            [28, 31, 39, 56, 64, 69, 78, 82, 83, 89, 94, 101, 108,
             119, 131, 140, 148, 159, 173, 184]))
    assert_array_almost_equal(
        iv,
        np.array(
            [19, 29, 34, 53, 60, 67, 76, 81, 82, 84, 90, 99, 103,
             112, 127, 137, 143, 154, 166, 180, 185]))
Exemple #3
0
def _test_findpot():
    import matplotlib.pyplot as plt
    import wafo.data
    from wafo.misc import findtc
    x = wafo.data.sea()
    t, data = x[:, :].T
    itc, _iv = findtc(data, 0, 'dw')
    ytc, ttc = data[itc], t[itc]
    ymin = 2 * data.std()
    tmin = 10  # sec
    I = findpot(data, t, ymin, tmin)
    yp, tp = data[I], t[I]
    Ie = findpot(yp, tp, ymin, tmin)
    ye, te = yp[Ie], tp[Ie]
    plt.plot(t, data, ttc, ytc, 'ro', t, zeros(len(t)), ':', te, ye, 'kx', tp,
             yp, '+')
    plt.show()
Exemple #4
0
def _test_findpot():
    import pylab
    import wafo.data
    from wafo.misc import findtc
    x = wafo.data.sea()
    t, data = x[:, :].T
    itc, _iv = findtc(data, 0, 'dw')
    ytc, ttc = data[itc], t[itc]
    ymin = 2 * data.std()
    tmin = 10 # sec
    I = findpot(data, t, ymin, tmin)
    yp, tp = data[I], t[I]
    Ie = findpot(yp, tp, ymin, tmin)
    ye, te = yp[Ie], tp[Ie]
    pylab.plot(t, data, ttc,ytc,'ro', t, zeros(len(t)), ':', te, ye, 'kx', tp, yp, '+')
    pylab.show() #
    pass
Exemple #5
0
def statisticalana(t, series, h=0, mod='cw'):
    '''
    Return: significant values of crests, troughs, and double peaks,
            as well as mean level crossing period
    Parameters:
    -----------
    t: time, 1-d array
    series: data, 1-d array
    h: level, scalar
    mod: string, defines type of wave or crossing returned. Possible options are
        'dw' : downcrossing wave
        'uw' : upcrossing wave
        'cw' : crest wave
        'tw' : trough wave
        None : All crossings will be returned
    '''
    from wafo.objects import mat2timeseries
    from wafo.misc import findtc

    t = np.asarray(t, dtype='float')
    series = np.asarray(series, dtype='float')

    ts = mat2timeseries(np.stack((t, series), axis=-1))
    crestTroughID, crossID = findtc(ts.data, h, mod)

    ctp = series[crestTroughID] - h  # crest and trough point
    crests = ctp[ctp > 0]
    troughs = ctp[ctp <= 0]
    if series[crestTroughID[0]] < h:
        troughs = troughs[1:]
    n = min(crests.shape[0], troughs.shape[0])
    vpps = crests[:n] - troughs[:n]

    # mean level crossing period
    tLevelCrossing = t[crossID[::2]]

    # significant values (1/3 exceeding probability)
    ns = n // 3
    return np.mean(-np.sort(-crests)[:ns]) + h, np.mean(np.sort(troughs)[:ns]) + h,\
        np.mean(-np.sort(-vpps)[:ns]), np.mean(np.diff(tLevelCrossing))
def waves_proc(df, i_burst, len_avg=600, i_burst_good_exactly=1):
    if not 'Pressure' in a.columns:
        return

    import wafo.objects as wo
    import wafo.misc as wm

    print('waves_proc')

    def df2ts(series):
        return wo.mat2timeseries(
            pd.concat(
                [(series.index.to_series() - series.index.values[0]).dt.total_seconds(),
                 series
                 ], axis=1).values)

    # i_burst, mean_burst_size = i_bursts_starts(df.index, dt_between_blocks = pd.Timedelta(minutes=10))

    if len(df) - i_burst[-1] < len_avg:
        last_burst = i_burst[-1]
        i_burst = i_burst[:-1]
    else:
        last_burst = len(df)

    # use freqencies as calculated for normal burst:
    wfreq = df2ts(df['Pressure'][slice(*i_burst[i_burst_good_exactly:(i_burst_good_exactly + 2)])]).tospecdata(
        L=600).args
    Sp = np.empty((i_burst.size, wfreq.size)) + np.NaN
    df['P_detrend'] = df['Pressure'] + np.NaN
    calc_spectrum_characteristics = ['Hm0', 'Tm_10', 'Tp', 'Ss', 'Rs']
    ar_spectrum_characteristics = np.empty((i_burst.size, len(calc_spectrum_characteristics))) + np.NaN
    # Hm0 = 4*sqrt(m0)                          - Significant wave height
    # Tm_10 = 2*pi*m_1/m0                       - Energy period
    # Tp = 2*pi*int S(w)^4 dw / int w*S(w)^4 dw - Peak Period
    # Ss = 2*pi*Hm0/(g*Tm02^2)                  - Significant wave steepness
    # Rs = Quality control parameter
    i_st = 0
    for i, i_en in enumerate(np.append(i_burst[1:], last_burst)):
        sl = slice(i_st + 1, i_en)  # we have bad 1st data in each burst. removing it
        # ?! df['Pressure'][sl].apply(lambda x: wm.detrendma(x, sl.stop - sl.start)).values returns all [0] objects
        try:
            ps_detr = df['Pressure'][sl]
            ps_detr -= ps_detr.rolling(600, min_periods=1, center=True, win_type='blackman').mean()
            ps_detr.interpolate('nearest', inplace=True)
            df['P_detrend'][sl] = ps_detr

            ts = df2ts(ps_detr)
            Sest = ts.tospecdata(L=600)

            if np.allclose(wfreq, Sest.args):
                Sp[i, :] = Sest.data
                ar_spectrum_characteristics[i, :] = \
                    Sest.characteristic(fact=calc_spectrum_characteristics, T=diff(ts.args[[0, -1]]))[0]
            else:
                print(f'burst #{i} of different length ({i_en - i_st}) skipped')
                # Sest.plot('-')

                # # Probability distribution of wave trough period
                # dt = Sest.to_t_pdf(pdef='Tt', paramt=(0, 10, 51), nit=3)
                # T, index = ts.wave_periods(vh=0, pdef='d2u')
                # 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)
                # bins = wm.good_bins(T, num_bins=25, odd=True)
                # wm.plot_histgrm(T, bins=bins, normed=True)
                # wave_parameters = ts.wave_parameters()
                # if wave_parameters['Ac']==[]:
                #    wave_parameters =
        except Exception as e:
            print(f'Error in burst #{i}: {e}')
        i_st = i_en
    ###

    # save calculated parameters
    export_df_to_csv(
        pd.DataFrame(ar_spectrum_characteristics, index=df.index[i_burst], columns=calc_spectrum_characteristics),
        cfg['out'],
        add_subdir='V,P_txt',
        add_suffix='spectrum_characteristics')

    export_df_to_csv(
        pd.DataFrame(Sp, index=df.index[i_burst], columns=wfreq),
        cfg['out'],
        add_subdir='V,P_txt',
        add_suffix='spectrum')

    # envelope ("ogibayushchaya") 
    ts = df2ts(df['P_detrend'].fillna(method='backfill'))
    ct = wm.findtc(ts.data, 0)[0]  # , kind='cw','tw'  # 0 is mean, 0 becouse it is derended
    ind_crest = ct[::2]
    ind_trough = ct[1::2]

    if False:
        plot(ps_detr, 'y')
        plot(ps_detr[ct[::2]], '.b')
        plot(ps_detr[ct[1::2]], '.r')
        ct += sl.start

        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)

        # @+others
        # @+node:korzh.20180608193514.1: *5* save plot
        # plt.setp(plt.gca().spines.values(), linewidth=1)
        fig = plt.figure();
        plt.gcf().set_size_inches(19, 7)
        ax = fig.add_axes([0.05, 0.05, 0.93, 0.93])
        ax.plot(df.index, df.P_detrend, '-k', linewidth=0.1)
        ax.plot(df.index[ind_crest], df.P_detrend[ind_crest], '-b', linewidth=1)
        ax.plot(df.index[ind_trough], df.P_detrend[ind_trough], '-r', linewidth=1)
        ax.set_ylim(-2, 2)
        ax.grid(True)
        # plt.savefig(Path(cfg['out']['db_path']).with_name(cfg['out']['table'] + '_P_detrend (600dpi)_18_1930-2300').with_suffix('.png'), dpi=600)
        # @-others

    return df, ind_crest, ind_trough