Пример #1
0
def mean_flow(M_log):
    # compute the mean flow by averaging the flow on the 5 movies and 10 times steps (more or less depending on the time ratio !!)
    Ux = []
    Uy = []

    M_ref = M_log[0]
    #    X=M_ref.x
    #    Y=M_ref.y

    t = M_ref.t
    Etot = []
    for tp in range(len(t)):
        Umoy, Vmoy = average(M_log, tp)

        E = np.sqrt(Umoy**2 + Vmoy**2)

        Etot.append(np.nanmean(E))
        print(np.nanmean(E))
        #        graphes.color_plot(X,Y,E,fignum=3)

        Ux.append(Umoy)
        Uy.append(Umoy)

    graphes.graph(t, Etot, fignum=-1, label='k^')
    graphes.legende('$t$ (s)', '$\sqrt{<E_c>}$ (mm/s)', '')

    graphes.graphloglog(t, Etot, fignum=-1, label='k^')
    graphes.legende('$t$ (s)', '$\sqrt{<E_c>}$ (mm/s)', '')

    return Ux, Uy
Пример #2
0
def add_theory(k, yy_k, alpha, fignum=0):
    for a in alpha:
        k0 = np.nanmean(k)
        val = np.nanmean(yy_k * (k / k0) ** (-a))
        std_val = np.nanstd(yy_k * (k / k0) ** (-a))

        #  print('Corrected spectrum : '+str(std_val/val*100)+' %')
        graphes.graphloglog(k, val * (k / k0) ** a, label='r--', fignum=fignum)
Пример #3
0
def display_fft_1d(k, S, fignum=1, label='k^', vmin=-3, vmax=0.5, theory=False, alpha=-5. / 3):
    # display in logscale
    #    k_log=np.log10(k)
    #    S_log=np.log10(S)
    #    print(k)
    #    print(S)
    graphes.graphloglog(k, S, fignum=fignum, label=label)

    if theory:
        A = np.mean(S * k ** (-alpha))
        graphes.graphloglog(k, A * k ** alpha, label='r--', fignum=fignum)
Пример #4
0
def get_cine_time(file, display=False):
    c = cine.Cine(file)
    # something gets wrong with the computation of the cine length
    n = c.len()
    print('Number of images : ' + str(n))
    times = np.asarray([c.get_time(i) for i in range(n)])

    if display:
        graphes.graphloglog(times[1:], np.diff(times), label='k')
        graphes.legende('t (s)', 'Dt (s)', file)

    return times
Пример #5
0
def main():
    file = '/Users/stephane/Documents/Experiences_local/Accelerated_grid/Set_time_scale/Logtime_movies/setup1_Dt_fps10000_n7000_Beta_1m.cine'
    times = get_cine_time(file)

    Dt = (times[1:] - times[:-1]) * 1000
    times = times[:-1]

    print(Dt)
    print(times)

    graphes.graphloglog(times, Dt, fignum=1, label='b^')
    graphes.legende('t (s)', 'Dt (ms)', '')

    compare_logtime(1)
Пример #6
0
def spectrum_1d(M, indices=None, norm_factor=1):
    Fourier.compute_spectrum_1d(M, Dt=3)
    S_k = np.nanmean(M.S_k[..., indices], axis=1) / norm_factor
    graphes.graphloglog(M.k, S_k, label='^-', fignum=1)

    k0 = 0.1
    i = np.argmin(np.abs(M.k - k0))
    A = S_k[i] * k0 ** (5. / 3)

    #    print('Total energy : '+np.sum(M.k*S_k))

    graphes.graph(M.k, A * M.k ** (-5. / 3), label='r--')
    figs = graphes.legende('$k$ (mm$^{-1}$)', 'E (m/s^2)', '')
    return figs
Пример #7
0
def time_correlation(Mlist, indices=None, display=False):
    """
    Compute the spatial averaged time of velocity autocorrelation
    Velocity autocorrelation functions in time are fitted by an exponential in time.
    Typical time tc gives the time correlation

    Parameters
    ----------
    Mlist : list of Mdata
    indices : list of int
        indices of Mlist elements to process. default value process all the elements
    display : bool
        default value False

    OUTPUT
    -----
    tf :
    tau :
        for each time in ft, timescale over which correlation is reduced to 1/e, on average
    """

    if indices is None:
        indices = range(len(Mlist))

    labels = ['k^', 'ro', 'bp', 'c8', 'g*']

    for i, indice in enumerate(indices):
        label = labels[i]

        M = Mlist[indice]
        tf, tau = compute_Ct(M, display=False, label='ko', fignum=1)

        graphes.graphloglog(tf, tau, fignum=9, label=label)
        graphes.legende('$t (s)$', '$\tau (s)$', '')

        # compute from the
        # t_d,E = decay.decay(M,label=label)
        t_d, E = Fourier.display_fft_vs_t(M, '1d', Dt=50, label=label)

        Ef = np.zeros(len(tf))
        for i, t in enumerate(tf):
            j = np.argmin(abs(t_d - t))
            #  print(str(j)+ ' : '+str(E[j]) + ", " + str(tau[i]))
            Ef[i] = E[j]

        graphes.graphloglog(Ef, tau, fignum=10, label=label)
        graphes.legende('$E (m^2/s^2)$', '$\tau (s)$', '')

    return tf, tau
Пример #8
0
def measure_anisotropy(fileDir, t0, fpms):
    fileList, n = get_fileList(fileDir, 'npz')
    I = []
    for name in fileList:
        S = np.load(name)
        # print(name)
        I0 = anisotropy(S)
        I.append(I0)

    # default fps is 1000fps in PIV parameters files
    ft = 1. / fpms
    t = np.arange(t0, t0 + n * ft, ft)
    graphes.graphloglog(t, U, label)
    graphes.legende('t (ms)', 'I (norm.)', '')
    print(str(max(t)) + '   ' + str(max(U)))
Пример #9
0
def log_time_step(Dt, alpha, n):
    # Dt in ms
    # alpha : power coefficient , close to 1. greater than 1 means increasing time step
    # n : number of images
    Dt_list = [Dt * alpha**i for i in range(n)]
    Dt_array = np.asarray(Dt_list)

    Dt_array = np.floor(Dt_array / Dt) * Dt

    #   graphes.graph(np.arange(1,n+1),Dt_array,label='r+')
    #   graphes.legende('# of image','Dt (ms)','')

    t = np.cumsum(Dt_array) / 1000  # t in s
    graphes.graphloglog(t, Dt_array, 1, label='r+')
    graphes.legende('t (s)', 'Dt (ms)', '')
Пример #10
0
def taylor_scale(M, fignum=1, display=True, label='k^'):
    #author: stephane
    nx, ny, nt = M.shape()
    t = M.t
    Dt = 20
    step = 1

    lambda_R = {}
    Urms = []
    t_R = []
    for i in range(Dt, nt - Dt, step):
        t_R.append(t[i])
        lambdas, U = compute(M, i, Dt=Dt)
        Urms.append(U)
        if lambda_R == {}:
            for key in lambdas.keys():
                lambda_R[key] = [lambdas[key]]
        else:
            for key in lambdas.keys():
                lambda_R[key] += [lambdas[key]]

    graphes.semilogx(t_R,
                     lambda_R['t_moy'],
                     fignum=fignum,
                     label=label[0] + '^')
    graphes.semilogx(t_R,
                     lambda_R['l_moy'],
                     fignum=fignum,
                     label=label[0] + '>')

    graphes.graphloglog(t_R,
                        np.asarray(Urms) * np.asarray(lambda_R['t_moy']),
                        fignum=fignum + 1,
                        label=label)
    graphes.graphloglog(np.asarray(Urms),
                        np.asarray(lambda_R['t_moy']),
                        fignum=fignum + 2,
                        label=label)
    graphes.legende('<U' '>', 'lambda', '')
Пример #11
0
def compare_logtime(fignum=1):
    Dt = 0.1
    alpha = 1.001
    n = 7000

    log_time_step(Dt, alpha, n)

    # read time step
    file = '/Users/stephane/Documents/Experiences_local/Accelerated_grid/Set_time_scale/H1180mm_S300mm_decay/param_NL_Dt.txt'

    t_s, Dt = read_time_step(file)
    graphes.graphloglog(t_s, Dt, fignum=fignum, label='ko')

    Dir = os.path.dirname(file)
    print(Dir)

    params = {'Dt': Dt, 'alpha': alpha, 'n': n}
    s = rw_data.gen_name(params)
    file_fig = Dir + '' + '/' + 'Dt_vs_t_data_mes1'  # +s

    print(file_fig)
    graphes.save_fig(0, file_fig)
Пример #12
0
def compute_tc(Mlist, Corr_fun, fields, log=True):
    M = Mlist[0]

    labels = ['ro', 'k^']
    s = ''
    figs = {}

    for i, field in enumerate(fields):
        C = Corr_fun[field]

        t = []
        tau = []
        for tup in C:
            tc = tup[1]
            C_norm = tup[2]
            N = len(C_norm) / 2
            ind1 = np.argmin(np.abs(C_norm[N + 1] / 2. - C_norm[1:N]))
            ind2 = np.argmin(np.abs(C_norm[N + 1] / 2. - C_norm[N:]))
            tau.append(tc[ind2 + N] - tc[ind1])
            t.append(tc[N])

        if log:
            graphes.graphloglog(t, tau, fignum=1, label=labels[i])
            # graphes.set_axis(min(t),max(t),min(t),0.1)
        else:
            graphes.graph(t, tau, fignum=1, label=labels[i])
            graphes.set_axis(0, 0.4, 0, 0.1)
        s = s + field + ', '
        figs.update(graphes.legende('t (s)', 't_c (s)', s[:-2]))

        name = 'fx_' + str(int(np.floor(M.fx * 1000))) + 'm'
        graphes.save_figs(figs,
                          prefix='./Stat_avg/Time_correlation/Overview/' +
                          field + '/' + name,
                          dpi=300,
                          display=True,
                          frmt='png')
Пример #13
0
graphes.semilogy(M.t[indices], Y_moy[indices], label='ks-', fignum=1)
i0 = 28
T = 60
t0 = M.t[range(1, T - 9)]
print(M.t[i0])
# for i in range(nt//T-3):
#    ind = range(i0,i0+T-10)
#    graphes.graph([M.t[i0]],[Y_moy[i0]],label='rs',fignum=1)
figs = graphes.legende('Time (s)', 'Energy (mm$^2$/s$^{2}$)', '')
graphes.set_axis(0, 8, 10**1, 10**5)
#    graphes.graphloglog(t0,Y_moy[ind],label='.-',fignum=2)
#    i0 = i0+T
suffix = '_tmpsuffix_'
graphes.save_figs(figs, savedir=savedir + subdir, suffix=suffix + 'Evst')

graphes.graphloglog(t0, 10**3 * t0**(-2), label='r--', fignum=2)
graphes.graphloglog(t0, 10**3 * t0**(-1.4), label='r+--', fignum=2)
graphes.set_axis(10**-2, 10**0, 10**2, 10**5)

figs.update(
    graphes.legende('Translated Time (s) ', 'Energy (mm$^2$/s$^{2}$)', ''))
suffix = graphes.set_name(M, param=['freq', 'v'])
graphes.save_figs(figs, savedir=savedir + subdir, suffix=suffix + 'shaped')
plt.close('all')

########################################################
# Fourier to obtain Energy spectrum in k space
########################################################
M = Mlist[0]
# compute_spectrum_2d() returns S_E, kx, ky
# compute_spectrum_1d() returns S_E, k
Пример #14
0
def dispersion(Data, j, savedir):
    tmin = 20
    tmax = 160

    accurate = Data['accurate'][j]
    pos = Data['pos'][j]
    Mlist = Data['M'][j]
    A = Data['A'][j]

    figs = {}
    graphes

    for c, key in enumerate(accurate[0].keys()):
        Y = []
        for i, M in enumerate(Mlist):
            if accurate[i][key]:
                # c+=1
                Y.append(pos[i][key][tmin:tmax])
            else:
                print("not accurate")

        Y = np.asarray(Y)
        #        print(key)
        t = np.asarray(pos[i]['t'][tmin:tmax])
        graphes.set_fig(1)
        # graphes.errorbar(t,np.nanmean(Y,axis=0),0*t,np.nanstd(Y,axis=0),label='k',fignum=c+4)
        #        graphes.graph(t,np.nanstd(Y,axis=0),fignum=1,label=label)
        #        graphes.set_axis(0.05,0.45,0,15)
        #        figs.update(graphes.legende('Time (s)',key,''))

        #        graphes.graph(t**3,np.nanstd(Y,axis=0)**2,fignum=2,label=label)
        #        graphes.graph(t**3,1000*t**3,fignum=2,label='r-')
        #        graphes.set_axis(0.05**3,0.05,0,70)
        #        figs.update(graphes.legende('t^3',key+'^2',''))

        print(A)
        if A == 0:
            label = 'c'
        else:
            label = 'k-'

        if 'X' in key:
            graphes.graphloglog(t, np.nanstd(Y, axis=0), fignum=3, label=label)
            graphes.graphloglog(t, 30 * t**1.5, fignum=3, label='r--')
            #  graphes.graphloglog(t,8*t**0.5,fignum=3,label='r--')

            graphes.set_axis(0.05, 0.6, 0.01, 50)
            figs.update(graphes.legende('t', key + '', ''))

        if 'Y' in key:
            #            label='b-'
            graphes.graphloglog(t, np.nanstd(Y, axis=0), fignum=4, label=label)
            graphes.graphloglog(t, 30 * t**1.5, fignum=4, label='r--')
            #  graphes.graphloglog(t,8*t**0.5,fignum=4,label='r--')
            graphes.set_axis(0.05, 0.6, 0.01, 50)
            figs.update(graphes.legende('t', key + '', ''))

            #    graphes.graphloglog(t**3,1000*t**3,fignum=2,label='r-')
        # figs.update(graphes.legende('t',key+'',''))
        # print(c)
    return figs
Пример #15
0
def compute_Ct(M,
               tlist=None,
               t0=20,
               axes=['Ux', 'Ux'],
               p=1,
               display=False,
               label='ko',
               fignum=1):
    """

    Parameters
    ----------
    M :
    tlist :
    t0 : int
        frame number to start correlation function if tlist is None
    axes :
    p :
    display :
    label :
    fignum :

    Returns
    -------
    tf : float array of dim len(tlist) x 1 or, if tlist==None, len(range(t0, dimensions[2] - t0, Dt)) x 1
        the times probed for auto correlation
    tau : float array of dim len(tlist) x 1 or, if tlist==None, len(range(t0, dimensions[2] - t0, Dt)) x 1
        the correlation timescales evaluated at each time tf
    """
    display_part = False
    if tlist is None:
        Dt = 50
        dimensions = M.shape()
        tlist = range(t0, dimensions[2] - t0, Dt)

    tau = np.zeros(len(tlist))
    tf = np.zeros(len(tlist))

    for i, t in enumerate(tlist):
        X, Y, Yerr = stat_corr_t(M, t, axes=axes, p=1, display=False)
        try:
            popt, pcurv = scipy.optimize.curve_fit(fitting.exp, np.abs(X), Y)
        except ValueError:
            print("NaN values encountered, fit skipped")
            X, Y, Yerr = stat_corr_t(M, t, axe='E', p=1, display=True)
            # input()
            pcurv = []
            popt = [1]
        except RuntimeError:
            print(
                "Fitting did not converge, arbitrarly chosen to previous value"
            )
            pcurv = []
            if i == 0:
                popt = [1]
            else:
                popt = [tau[i - 1]]

        tf[i] = M.t[t]
        tau[i] = -1 / popt[0]
        #   print(str(M.t[t]) + ' : ' +str(tau[i]))

        if display_part:
            texp = np.abs(X)
            graphes.set_fig(1)
            graphes.errorbar(texp, Y, texp * 0, Yerr, fignum=0, label='ko')
            graphes.graph(texp, np.exp(texp, -1 / tau[i]), fignum=1, label='r')
            graphes.legende('$t/u^{2m}$', '$C_t$', '$m=1/2$')

    if display:
        graphes.graphloglog(tf, tau, fignum=fignum, label=label)
        graphes.legende('t (s)', 't_c', graphes.title(M))

    return tf, tau
Пример #16
0
def spatial_correlation(M,
                        compute=True,
                        rootdir='Corr_functions',
                        label='k^',
                        fignum=1,
                        display=True,
                        save=False):
    """Compute the spatial correlation function
    or display the correlation length as a function of time
    save the correlations function in txt files
    Fit using turbulence.tools.fitting.exp function

    Parameters
    -----
    M : Mdata object
    compute : bool
        default value : True
        if True, the correlations functions are computed, and save in txt files
        if False, load the previously computed correlations functions and display the correlation length as a function of timme
    rootdir : string
        subdirectory name for saving the corr functions. Base directory correspond to the location of the associated dataset.
    save : bool
        Whether to save the autocorrelation functions to disk

    Returns
    -------
    Corr_functions : list of numpy float arrays (size?)
        [Cxx, Cyy, Cxy, CEE]
    """
    if compute:
        # chose randomly the pair of indices that will be used for computing the spatial correlation function
        dlist = range(int(max(M.shape()) / 2))
        indices = {}
        N = 10**3
        for i, d in enumerate(dlist):
            indices[i] = d_2pts_rand(M.Ux[:, :, 0], d, N)
        print('Pair of indices computed')
        (ny, nx, nt) = M.shape()

        #  tref, d, Cxx, Cyy, Cxy, CEE = correlation_functions(M,dlist,indices,Dt=Dt)
        #  print('Correlation functions computed')

        step = 100
        Dt = 20
        tref, d, Cxx, Cyy, Cxy, CEE = display_corr_vs_t(M,
                                                        dlist,
                                                        indices,
                                                        step=step,
                                                        Dt=Dt,
                                                        label='-',
                                                        display=True)

        # How to save matrices in a single txt file ?
        #    filename = os.path.dirname(M.filename) + '/Corr_functions/' + name + '.txt'
        axes = ['xx', 'yy', 'xy', 'CEE']
        keys = ['d', 't'] + ['Corr_' + p for p in axes]

        Corr_functions = [Cxx, Cyy, Cxy, CEE]
        List_info = [d, tref] + Corr_functions

        if save:
            name = 'Corr_spatial_' + M.Id.get_id()
            filename = os.path.dirname(
                M.filename) + '/Corr_functions/' + name + '.txt'
            print(filename)
            rw_data.write_matrix(filename, keys, List_info)
            # for C in [Cxx,Cyy,Cxy,CEE]:
            #     rw_data.write_matrix(tref,D,C)

            print('Correlation functions saved in ' + filename)
        return Corr_functions
    else:
        # try first to load the data rfrom the Corr_functions directory
        Dir = os.path.dirname(M.filename) + '/' + rootdir
        filename = Dir + '/Corr_spatial_' + M.Id.get_id(
        ) + '.txt'  # print(filename)
        Header, Data, axes = rw_data.read_matrix(filename,
                                                 Hdelimiter='\t',
                                                 Ddelimiter='\t')
        print(Data.keys())
        nd = axes['d']
        nt = axes['t']

        print((nd, nt))
        Dt = 20
        for key in Data.keys():
            Data[key] = np.reshape(np.asarray(Data[key]), (nd, nt))
        #            Data[key]=cdata.smooth(Data[key],Dt)
        dimensions = M.shape()
        tlist = range(Dt, dimensions[2] - 3 * Dt, 1)
        lc = np.zeros(len(tlist))
        tf = np.zeros(len(tlist))

        display_part = True
        for i, t in enumerate(tlist):
            d = Data['d'][:, i]

            key = 'Corr_xx'
            Cd = Data[key][:, i] / Data[key][0, i]

            popt = fitting.fit(fitting.exp, d[0:10], Cd[0:10])

            tf[i] = M.t[t]
            lc[i] = -1 / popt[0]
            #   print(str(M.t[t]) + ' : ' +str(lc[i]))
            if display_part:
                if i % 100 == 0:
                    graphes.set_fig(1)
                    graphes.graph(d, Cd, fignum=0, label='ko')
                    graphes.graph(d, np.exp(d, -1 / lc[i]), label='r')
                    #   graphes.graph(d,parabola(d,-1/lc[i])+1,label='r')
                    graphes.legende('$d (mm)$', '$C_d$', '')
                    graphes.set_axes(0, 3, -1, 1.1)
                    # input()

        cdata.rm_nans([lc], d=2)

        if display:
            graphes.graphloglog(tf, lc, fignum=fignum, label=label)
            graphes.legende('$t (s)$', '$d (mm)$', graphes.title(M))

    return None
Пример #17
0
plt.close('all')
mm = mlist[0]
ind = 0
for skk in sk_disc:
    kk = k_disc[ind]

    print 'np.shape(skk) = ', np.shape(skk)
    print 'np.shape(kk) = ', np.shape(kk)
    todo = range(20, np.shape(skk)[1])
    colors = tcmaps.cubehelix_palette(n_colors=len(todo), start=0.5, rot=-0.75, check=False)
    print 'np.shape(colors) = ', np.shape(colors)
    dmyi = 0
    for ii in todo:
        print 'Plotting energy spectrum, item =', ii
        graphes.graphloglog(kk, skk[..., ii], 'k', color=colors[dmyi])
        dmyi += 1

    graphes.graph(mm.k, 100 * mm.k ** (-5. / 3), label='r-')
    figs = graphes.legende(r'$k$ [mm$^{-1}$]', r'$E$ [mm/s$^{2}$]', r'$S(k)$ for $r <$' + str(radii[ind]) + ' pixels')
    imout_dir = savedir + 'energy_spectrum_radius_sequence/' + date + '_' + str(index) + \
                '_energy_spectrum_radius_sequence/'
    if not os.path.exists(imout_dir):
        print 'le.ensure_dir: creating dir: ', imout_dir
        os.makedirs(imout_dir)

    figname = imout_dir + date + '_' + str(index) + '_energy_spectrum_radius{0:03d}'.format(radii[ind])
    print 'saving fig: ' + figname
    graphes.save_fig(1, figname, frmt='png', dpi=300, overwrite=True)
    plt.clf()
Пример #18
0
def decay(M,
          field,
          M_moy=None,
          display=False,
          label='',
          fignum=1,
          compute=True,
          fluctuations=False,
          log=True):
    """
    Compute the spatial-averaged time evolution of kinetic energy of a flow field
    
    INPUT
        M : Mdata object
            Data set containing a 2D dimensionnal flow (files Ux and Uy) as a function of time 
        display : boolean. defaulf value False
            To display the result of the computation
        label : standard matplotlib label format
        fignum : standard graphes.py fignum format
            (-1 : current figure, 0: clear figure, N(>1): set figure N)
    OUTPUT
        tf : 1d numpy array
            time axis
        Uf : 1d numpy array.
            Spatial average kinetic energy
    """
    Y = M.get(field)

    # compute decay of turbulent kinetic energy from the total energy.
    # to compute from a fit of the energy cascade go to Fourier.py
    if M_moy is not None:
        Ux = M.Ux - M_moy.Ux
        Uy = M.Uy - M_moy.Uy
    else:
        Ux = M.Ux
        Uy = M.Uy

    if compute and field == 'E':
        Y = (Ux**2 + Uy**2)
    else:
        Y = access.get_all(M, field)

    #    if fluctuations:
    #        Y = access.get_all(M,field) - (M.Ux**2+M.Uy**2)

    nx, ny, nt = Y.shape
    Y_t = np.reshape(Y, (nx * ny, nt))
    # retake the time instants from the cinefile itself
    #    times=time_step_sample.get_cine_time(M.Sdata.fileCine,False)
    # current : directly take the attribut t of M :
    times = M.t

    t = []
    U_rms = []
    # time of the free fall
    t0 = 0.  # .53#0;550/M.ft
    for i in range(nt):
        #        print(i)
        #        print(Dt[i],np.nanmedian(E_t[:,i]/Dt[i]**2,axis=0))

        #     U_rms.append(np.nanmedian(Y_t[:,i],axis=0))

        U_rms.append(np.sqrt(np.nanmedian(np.power(Y_t[:, i], 2), axis=0)))

        #        U_rms.append(np.nanmean(E_t[:,i]/Dt[i]**2,axis=0))
        #  t.append(times[int(M.im_index[i])]-t0)
        t.append(times[i] - t0)

    tf = np.asarray(t)
    Uf = np.asarray(U_rms)

    figs = {}
    if display:
        #        figs = {}
        #    graphes.graph(tf,Uf,fignum=fignum,label=label)
        if log:
            graphes.graphloglog(tf, Uf, fignum=fignum, label=label)
            graphes.set_axis(10**-2, 10**2, 10**-1, 10**6)
            #       graphes.graphloglog([10**-2,10**2],[10**-1,10**4],fignum=-2,label='r--')
            #  graphes.graphloglog([10**-1,10**3],[5*10**7,5*10**-1],fignum=-2,label='r--')
        else:
            graphes.graph(tf, Uf, fignum=fignum, label=label)

        figs.update(
            graphes.legende('$t$ (s)', '$<E>_{x,y}$ (mm^2/s^2)',
                            graphes.title(M)))
        return figs
    else:
        return tf, Uf
Пример #19
0
def make_plot(M, Range=None, color='k', field=['E', 'vorticity'], Dirbase=None, Dt=1, example=False, total=True,
              fignum=1, save=True):
    if Dirbase == None:
        Dirbase = '/Users/stephane/Documents/Experiences_local/Accelerated_grid/PIV_data/Test6/'  # local saving
        Dirbase = './Stat_avg/Panel/' + M.Id.date

    axes = flex_panel(M, fignum=fignum)

    # for axe in axes:
    #    plt.sca(axe)
    # plt.cla()

    frames = select_range(M, Range)

    #    field = ['Ux','Uy']
    #  field = ['E','vorticity']
    figs = {}

    if hasattr(M, 'id'):
        Dirname = Dirbase + '/' + M.Id.get_id() + '/' + graphes.remove_special_chars(str(field)) + '/'
    else:
        Dirname = Dirbase + '/JHTD_Data/' + graphes.remove_special_chars(str(field)) + '/'
    print(Dirname)

    if Dt > 1:
        print('Smoothed data')
        Dirname = Dirname + 'Smooth_Dt_' + str(int(Dt)) + '/'

    # Dt = 50
    t_moy, E_moy = access.avg_vs_t(M, 'E', frames, Dt=Dt)
    t_moy, Omega_moy = access.avg_vs_t(M, 'omega', frames, Dt=Dt)
    t_moy, Strain_moy = access.avg_vs_t(M, 'strain', frames, Dt=Dt)
    t_moy, Y_pdf_moy = access.avg_vs_t(M, field[1], frames, Dt=Dt)

    epsilon = scale.dissipation_rate(Omega_moy)  # dissipation rate
    eta = scale.K_scale(epsilon)  # dissipative scale

    micro_1 = np.sqrt(1. / 4 * E_moy / Strain_moy ** 2)
    micro_2 = np.sqrt(E_moy / (Omega_moy) ** 2)

    Re = scale.Re(micro_1, eta)
    Re_lambda_1 = scale.Re_lambda(E_moy, micro_1)
    Re_lambda_2 = scale.Re_lambda(E_moy, micro_2)

    L = scale.I_scale(Re, E_moy)

    #    plt.sca(axes[2])
    #    graphes.graphloglog(t_moy,E_moy,fignum=1,label=color+'o-')
    # Fourier.add_theory(t_moy,E_moy,[-2.],fignum=1)
    #    graphes.graphloglog(t_moy,Y_pdf_moy,fignum=1,label=color+'s-')
    #    graphes.graphloglog(t_moy,epsilon,fignum=1,label='gv-')
    # Fourier.add_theory(t_moy,epsilon,[-3.],fignum=1)
    #    figs.update(graphes.legende('t (s)','E (mm^2/s^2), epsilon(mm^2/s^-3)',''))

    plt.sca(axes[1])
    graphes.graphloglog(t_moy, eta, fignum=fignum, label=color + 'o-')
    graphes.graphloglog(t_moy, micro_1, fignum=fignum, label=color + 's-')
    graphes.graphloglog(t_moy, micro_2, fignum=fignum, label='cp-')
    graphes.graphloglog(t_moy, L, fignum=fignum, label='gv-')
    figs.update(graphes.legende('t (s)', 'eta (mm), lambda (mm)', ''))

    plt.sca(axes[2])
    graphes.graphloglog(t_moy, Re, fignum=fignum, label=color + 'o-')
    graphes.graphloglog(t_moy, Re_lambda_1, fignum=fignum, label=color + 's-')
    graphes.graphloglog(t_moy, Re_lambda_2, fignum=fignum, label='cp-')
    figs.update(graphes.legende('t (s)', 'Re , Re_lambda', ''))

    # print(t_moy)
    #    print(Y_moy)
    # print(t)
    #    print(Y_moy)
    indices = [0, 1]
    #    indices = [1,4]
    cla_axes = [axes[i] for i in indices]

    if save:
        graphes.save_figs(figs, savedir=Dirname, prefix='General', suffix='_vs_t', dpi=300, frmt='png', display=True)

    individual = False

    if example:
        frames_disp = [1200]
    else:
        step = frames[1] - frames[0]
        frames_disp = range(frames[0] + step * 10, frames[-1], step * 10)

    if individual:
        for frame in frames_disp:
            # print(frame)
            # print(frames)
            i = frames.index(frame)
            graphes.set_fig(1)
            for axe in cla_axes:
                plt.sca(axe)
                plt.cla()
            axes = flex_panel(M, fignum=1)

            if total:
                plt.sca(axes[0])
                graphes.Mplot(M, field[0], frame, fignum=1, log=True)
                plt.text(-10, 80, field[0], fontsize=20)

            plt.sca(axes[1])
            #   graphes.graphloglog(t_moy,eta,fignum=1,label='ko-')
            #   graphes.graphloglog(t_moy,micro,fignum=1,label='ks-')
            graphes.graph([t_moy[i]], [eta[i]], fignum=1, label='ro')
            graphes.graph([t_moy[i]], [micro_1[i]], fignum=1, label='rs')
            graphes.graph([t_moy[i]], [micro_2[i]], fignum=1, label='rp')
            graphes.graphloglog([t_moy[i]], [L[i]], fignum=1, label='rv-')

            plt.sca(axes[2])
            graphes.graphloglog([t_moy[i]], [Re[i]], fignum=1, label='ro-')
            graphes.graphloglog([t_moy[i]], [Re_lambda_1[i]], fignum=1, label='rs-')
            graphes.graphloglog([t_moy[i]], [Re_lambda_2[i]], fignum=1, label='rp-')

            plt.sca(axes[3])
            figs.update(graphes.pdf(M, 'Ux', frame, Dt=Dt, fignum=1, label='m^'))
            figs.update(graphes.pdf(M, 'Uy', frame, Dt=Dt, fignum=1, label='b>'))
            figs.update(graphes.legende('t (s)', 'Re , Re_lambda', ''))

            plt.sca(axes[4])
            figs.update(graphes.pdf(M, field[1], frame, Dt=Dt, fignum=1, label=color + '-'))

            #        graphes.Mplot(M,field[1],i,fignum=1,log=True)
            #        plt.text(-10,80,'PDF '+field[1],fontsize=20)
            #        figs.update(graphes.legende('','','Front view',cplot=True))
            graphes.save_figs(figs, savedir=Dirname, suffix='_' + str(frame), dpi=100, frmt='png', display=False)

    return axes
Пример #20
0
def vertical_spreading(M, N, Dt=10, label='k^'):
    """
    Compute the vertical profile of RMS velocity as a function of time
    
    INPUT
    -----
    
    OUTPUT
    -----
    figs : dict
        key correspond to figure index, value to their standarzied filename
    """
    n = 160
    ti = 50

    figs = {}

    z0 = -M.param.stroke  # !!!
    z_1 = np.zeros(n)
    z_2 = np.zeros(n)

    t = np.zeros(n)
    E = np.zeros(n)

    indices = [(i + 1) * N + ti for i in range(n)]
    for i, t0 in enumerate(indices):
        z_1[i], z_2[i], E[i], std_E = velocity_profile(M,
                                                       i,
                                                       t0,
                                                       Dt=Dt,
                                                       display=True)
        t[i] = M.t[t0]
        # average on horizontal line (if rotated, correspond to vertical line)
    # compute the vertical RMS velocity profile

    fig = 1
    graphes.set_fig(fig)
    graphes.graph(t, z_1 - z0, fignum=fig, label=label)
    graphes.graph(t, z_2 - z0, fignum=fig, label=label)
    figs.update(graphes.legende('$t$ (s)', '$Front position z$ (mm)', ''))

    fig = 2
    graphes.set_fig(fig)
    graphes.graphloglog(t, np.abs(z0 - z_1), fignum=fig, label=label)
    graphes.graphloglog(t, np.abs(z0 - z_2), fignum=fig, label=label)

    graphes.graphloglog(t, np.power(t, 0.5) * 10**2, fignum=fig, label='r--')
    figs.update(graphes.legende('$t$ (s)', '$Front position z (log)$ (mm)',
                                ''))

    fig = 3
    graphes.set_fig(fig)
    graphes.graphloglog(t, E, fignum=fig, label=label)
    figs.update(graphes.legende('$t$ (s)', '$U_{rms}$ (mm/s)', ''))

    t_min = 6 * 10**-2
    t_max = 4 * 10**-1
    indices = np.where(np.logical_and(t < t_max, t > t_min))
    t_part = t[indices]
    z_part = np.abs(z0 - z_1[indices])

    P = np.polyfit(np.log(t_part / t_min), np.log(z_part), 1)
    C = np.exp(P[1])
    nu = C**2 / t_min
    print(P[0], C)
    print('Effective diffusion coefficient : ' + str(nu) + ' mm^2/s')

    graphes.graphloglog(t, C * np.power(t / t_min, P[0]), fignum=2, label='r-')
    figs.update(graphes.legende('$t$ (s)', '$Front position z (log)$ (mm)',
                                ''))

    graphes.save_figs(figs,
                      savedir='./Spreading/',
                      suffix='',
                      prefix='2015_12_28_front_both_C')

    return figs
Пример #21
0
def display_fft_vs_t(m, dimension='1d', Dt=20, fignum=0, label='^', display=False):
    """
    Parameters
    ----------
    m :
    dimension:
    Dt:
    fignum:
    label:
    display:

    Returns
    -------
    t, E_t
    """
    display_part = True
    #  plt.close(1)
    if dimension == '1d':
        S_k_2d, kx, ky = energy_spectrum_2d(m, Dt=Dt)
        S_k, k = energy_spectrum_1d(m, Dt=Dt)
    if dimension == '2d':
        S_k, kx, ky = energy_spectrum_2d(m, Dt=Dt)
    # start=580
    #    end=700
    #    step=10
    # print(S_k)
    if dimension == '1d':
        x = [10 ** 0, 10 ** 1.5]
        y = [10 ** -0.5, 10 ** -3]
        # graphes.graph(x,y,-1,'r-')

        #   t0=590
        # time_serie=range(t0+10,10000,50)#[round(t0*i**2) for i in np.arange(1,4,0.3)]

    # origin of time
    t0 = 0.  # .51
    tref = np.asarray(m.t) - t0
    #  tref=1-tref
    nt = len(tref)
    # time_serie=[600,900,1200,1600,1900,2900,5000,8000]

    #  time_serie=[i for i in np.arange(400,650,10)]
    #  time_serie=range(10,nt-2)
    step = 1
    time_serie = range(Dt + 1, nt - Dt * 3 - 11, step)  # [50,120,200,300,400,450,550]
    # print(nt-Dt*3-11)
    #   t0=500
    #   time_serie=[round(i)+t0 for i in np.logspace(1,3.973) if round(i)+t0<nt]
    # time_serie=range(start,end,50)

    alpha = np.zeros(len(time_serie))
    beta = np.zeros(len(time_serie))
    epsilon = np.zeros(len(time_serie))

    t_alpha = np.zeros(len(time_serie))

    #    graphes.hist(k)
    kmin = -2.7
    kmax = -1.7
    # print(np.log10(k))
    tmax = 300;
    for i, t in enumerate(time_serie):
        #   print(t)
        if tref[t] < tmax:
            if dimension == '1d':
                k_log = np.log10(k)
                S_log = np.log10(S_k[:, t])
                indices = np.logical_and(k_log > kmin, k_log < kmax)
                #  print(indices)
                #  print(S_log)
                k_log = k_log[indices]
                S_log = S_log[indices]
                P = np.polyfit(k_log, S_log, 1)

                alpha[i] = 10 ** P[1]  # *np.mean(k)**P[0]
                beta[i] = P[0]

                C_k = 0.55
                epsilon[i] = (alpha[i] / C_k) ** (3 / 2)
                t_alpha[i] = tref[t]

                # if t>min(time_serie):
                #     Dt=tref[time_serie.index(t)]-tref[time_serie.index(t-1)]
                #     print(Dt,alpha[time_serie.index(t)])
                #    print((t_alpha,alpha))
                if display_part:
                    graphes.set_fig(1)
                    # graphes.subplot(1,2,1)
                    k0 = np.min(k);
                    display_fft_1d(k, (k / k0) ** (5 / 3) * S_k[:, t] / alpha[i], fignum=1, label='')
                    display_fft_1d(k, (k / k0) * S_k[:, t] / alpha[i], fignum=2, label='')

                    # normalized
                    #   print(t_alpha[i])
                    # display_fft_1d(k,np.abs(S_k[:,t]/t_alpha[i]),fignum=1)

                    # graphes.graphloglog(k[indices],10**np.polyval(P,k_log),label='r--')
                    display_fft(m, t, dimension)

                    # graphes.subplot(1,2,2)
                    #  graphes.vfield_plot(m,t,fignum=2)

                    # there is a slighlty degeneracy of the spectrum along both axis. Removes |kx| < epsilon and |ky| < epsilon for every k ?
                    #   display_fft_2d(kx,ky,S_k_2d[:,:,t],fignum=3)
                    #   display_fft(m,t,dimension)


                    #   input()

            if dimension == '2d':
                display_fft_2d(kx, ky, S_k[:, :, t])
                display_fft(m, t, dimension)

    if display:
        #        title='$Z$ = '+str(m.Sdata.param.Zplane/10)+' cm'
        #    graphes.legende('$t$ (s)','$E (a.u.)$',title
        graphes.graphloglog(t_alpha, alpha, label=label, fignum=7)
        graphes.graphloglog([10 ** -1, 10 ** 3], [10 ** 8, 10 ** 0], label='r--', fignum=7)
        graphes.legende('$t$ (s)', '$E_{\lambda}$ (a.u.)', graphes.set_title(m))

        graphes.semilogx(t_alpha, beta, label=label, fignum=8)
        #    graphes.semilogx(t_alpha,beta,label=label,fignum=0)
        graphes.semilogx([10 ** -1, 10 ** 3], [-5 / 3, -5 / 3], label='r-', fignum=8)
        graphes.set_axis(10 ** -1, 10 ** 3, -2.5, 0)
        graphes.legende('$t$ (s)', 'exponent', graphes.set_title(m))

        # plot the dissipative scale as a function of time
        nu = 1  # in mm^2/s
        eta = (nu ** 3 / np.asarray(epsilon)) ** (1 / 4)
        graphes.graphloglog(t_alpha, eta, label=label, fignum=9)
        graphes.graphloglog([10 ** -1, 10 ** 3], [10 ** 8, 10 ** 0], label='r--', fignum=9)
        graphes.legende('$t$ (s)', '$\eta$ (mm)', graphes.set_title(m))

    E_t = epsilon
    t = t_alpha
    return t, E_t