예제 #1
0
def main():
    from pyphare.cpp import cpp_lib
    cpp = cpp_lib()

    from pyphare.pharesee.run import Run
    from pyphare.pharesee.hierarchy import flat_finest_field

    config()
    Simulator(gv.sim).run()

    if cpp.mpi_rank() == 0:

        vphi, t, phi, a, k = phase_speed(".", 0.01, 1000)

        r = Run(".")
        t = get_times_from_h5("EM_B.h5")
        fig, ax = plt.subplots(figsize=(9, 5), nrows=1)

        B = r.GetB(t[int(len(t) / 2)])
        by, xby = flat_finest_field(B, "By")
        ax.plot(xby, by, label="t = 500", alpha=0.6)

        sorted_patches = sorted(B.patch_levels[1].patches,
                                key=lambda p: p.box.lower[0])

        x0 = sorted_patches[0].patch_datas["By"].x[0]
        x1 = sorted_patches[-1].patch_datas["By"].x[-1]

        B = r.GetB(t[-1])
        by, xby = flat_finest_field(B, "By")
        ax.plot(xby, by, label="t = 1000", alpha=0.6)
        ax.plot(xby,
                wave(xby, 0.01, 2 * np.pi / 1000., 2 * np.pi / 1000 * 500),
                color="k",
                ls="--",
                label="T=500 (theory)")

        B = r.GetB(t[0])
        by, xby = flat_finest_field(B, "By")
        ax.plot(xby, by, label="t = 0", color="k")

        ax.set_xlabel("x")
        ax.set_ylabel(r"$B_y$")
        ax.legend(ncol=4, loc="upper center")
        ax.set_ylim((-0.012, 0.013))
        ax.set_title(r"$V_\phi = {:6.4f}$".format(vphi.mean()))

        ax.axvspan(x0, x1, alpha=0.2)
        fig.tight_layout()

        fig.savefig("alfven_wave.png", dpi=200)

        assert np.mean(np.abs(vphi - 1) < 5e-2)
예제 #2
0
def energies(path, kkind="iso"):
    """
    This loops over all times of a given run
    and return the magnetic and kinetic energy
    as a function of time.
    """
    r = Run(path)
    times = get_times_from_h5(r.path+"/EM_B.h5")
    Bnrj = np.zeros_like(times)
    K = np.zeros_like(times)
    for it,t in enumerate(times):
        B = r.GetB(t)
        protons = r.GetParticles(t, "protons")
        Bnrj[it] = mag_energy(B)
        K[it] = total_kinetic(protons,kind=kkind)
    return r, Bnrj, K, times
예제 #3
0
def growth_b_right_hand(run_path):
    file = os.path.join(run_path, "EM_B.h5")
    times = get_times_from_h5(file)

    r = Run(run_path)
    first_mode = np.array([])

    from scipy.optimize import curve_fit

    for time in times:
        B_hier = r.GetB(time, merged=True, interp="linear")

        by_interpolator, xyz_finest = B_hier["By"]
        bz_interpolator, xyz_finest = B_hier["Bz"]

        # remove the last point so that "x" is periodic wo. last point = first point
        x = xyz_finest[0][:-1]

        by = by_interpolator(x)
        bz = by_interpolator(x)

        # get the mode 1, as it is the most unstable in a box of length 33
        mode1 = np.absolute(np.fft.fft(by-1j*bz)[1])
        first_mode = np.append(first_mode, mode1)

    popt, pcov = curve_fit(yaebx, times, first_mode, p0=[0.08, 0.09])

    # now the signal is stripped from its exponential part
    damped_mode=first_mode*yaebx(times, 1/popt[0], -popt[1])

    # find the omega for which "damped_mode" is the largest :
    # this term is twice the one it should be because "mode1" resulting from
    # an absolute value, this (cosx)^2 = cos(2x) then appears at the 2nd
    # harmonoic (hence the factor 0.5 to get "omega")
    # the factor "+1" is because we remove the DC component, so the value
    # given by argmax has also to miss this value
    omegas = np.fabs(np.fft.fft(damped_mode).real)
    omega = 0.5*(omegas[1:omegas.size//2].argmax()+1)*2*np.pi/times[-1]

    print(omegas[0:6])
    print(omegas[1:omegas.size//2].argmax())
    print(2*np.pi/times[-1])
    print(0.5*(omegas[1:omegas.size//2].argmax()+1)*2*np.pi/times[-1])

    return times, first_mode, popt[0], popt[1], damped_mode, omega
예제 #4
0
def phase_speed(run_path, ampl, xmax):
    from scipy.signal import medfilt
    from scipy.optimize import curve_fit
    import os
    time = get_times_from_h5(os.path.join(run_path, "EM_B.h5"))
    r = Run(run_path)
    phase = np.zeros_like(time)
    amplitude = np.zeros_like(time)
    wave_vec = np.zeros_like(time)

    for it, t in enumerate(time):
        B = r.GetB(t)
        by, xby = finest_field(B, "By")
        a, k, phi = curve_fit(wave, xby, by, p0=(ampl, 2 * np.pi / xmax, 0))[0]
        phase[it] = phi
        amplitude[it] = a
        wave_vec[it] = k

    vphi = medfilt(np.gradient(phase, time) / wave_vec, kernel_size=7)
    return vphi, time, phase, amplitude, wave_vec
예제 #5
0
def finest_field_plot(run_path, qty, **kwargs):
    """
    plot the given quantity (qty) at 'run_path' with only the finest data

    * run_path : the path of the run
    * qty : ['Bx', 'By', 'Bz', 'Ex', 'Ey', 'Ez', 'Fx', 'Fy', 'Fz', 'Vx', 'Vy', 'Vz', 'rho']

    kwargs:
    * ax : the handle for the fig axes
    * time : time (that should be in the time_stamps of the run)
    * interp : the type of interpolation for the interpolator
    * draw_style : steps-mid ou default... only for 1d
    * title : (str) title of the plot
    * xlabel, ylabel
    * xlim, ylim
    * filename : (str) if exists, save plot to figure under that name

    return value : fig,ax
    """

    import os
    from pyphare.pharesee.hierarchy import get_times_from_h5
    from pyphare.pharesee.run import Run
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    import pyphare.core.gridlayout as gridlayout

    r = Run(run_path)

    time = kwargs.get("time", None)
    dim = r.GetDl('finest', time).shape[0]
    interp = kwargs.get("interp", "nearest")
    domain = r.GetDomainSize()

    if qty in ['Bx', 'By', 'Bz']:
        file = os.path.join(run_path, "EM_B.h5")
        if time is None:
            times = get_times_from_h5(file)
            time = times[0]
        interpolator, finest_coords = r.GetB(time, merged=True,\
                                             interp=interp)[qty]
    elif qty in ['Ex', 'Ey', 'Ez']:
        file = os.path.join(run_path, "EM_E.h5")
        if time is None:
            times = get_times_from_h5(file)
            time = times[0]
        interpolator, finest_coords = r.GetE(time, merged=True,\
                                             interp=interp)[qty]
    elif qty in ['Vx', 'Vy', 'Vz']:
        file = os.path.join(run_path, "ions_bulkVelocity.h5")
        if time is None:
            times = get_times_from_h5(file)
            time = times[0]
        interpolator, finest_coords = r.GetVi(time, merged=True,\
                                              interp=interp)[qty]
    elif qty == 'rho':
        file = os.path.join(run_path, "ions_density.h5")
        if time is None:
            times = get_times_from_h5(file)
            time = times[0]
        interpolator, finest_coords = r.GetNi(time, merged=True,\
                                              interp=interp)[qty]
    elif qty in ("Jx", "Jy", "Jz"):
        file = os.path.join(run_path, "EM_B.h5")
        if time is None:
            times = get_times_from_h5(file)
            time = times[0]
        interpolator, finest_coords = r.GetJ(time, merged=True,\
                                              interp=interp)[qty]
    else:
        # ___ TODO : should also include the files for a given population
        raise ValueError(
            "qty should be in ['Bx', 'By', 'Bz', 'Ex', 'Ey', 'Ez', 'Fx', 'Fy', 'Fz', 'Vx', 'Vy', 'Vz', 'rho']"
        )

    if "ax" not in kwargs:
        fig, ax = plt.subplots()
    else:
        ax = kwargs["ax"]
        fig = ax.figure

    if dim == 1:
        drawstyle = kwargs.get("drawstyle", "steps-mid")

        ax.plot(finest_coords[0], interpolator(finest_coords[0]),\
                drawstyle=drawstyle)
    elif dim == 2:

        x = finest_coords[0]
        y = finest_coords[1]
        dx = x[1] - x[0]
        dy = y[1] - y[0]

        # pcolormesh considers DATA_ij to be the center of the pixel
        # and X,Y are the corners so XY need to be made 1 value larger
        # and shifted around DATA_ij
        x -= dx / 2
        x = np.append(x, x[-1] + dx)
        y -= dy / 2
        y = np.append(y, y[-1] + dy)

        X, Y = np.meshgrid(x, y)
        DATA = interpolator(X, Y)

        vmin = kwargs.get("vmin", np.nanmin(DATA))
        vmax = kwargs.get("vmax", np.nanmax(DATA))
        cmap = kwargs.get("cmap", 'Spectral_r')
        im = ax.pcolormesh(x, y, DATA, cmap=cmap, vmin=vmin, vmax=vmax)
        ax.set_aspect("equal")
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.08)
        cb = plt.colorbar(im, ax=ax, cax=cax)
    else:
        raise ValueError("finest_field_plot not yet ready for 3d")

    ax.set_title(kwargs.get("title", ""))

    ax.set_xlabel(kwargs.get("xlabel", "$x c / \omega_p$"))
    ax.set_ylabel(kwargs.get("ylabel", "$y c / \omega_p$"))

    if "xlim" in kwargs:
        ax.set_xlim(kwargs["xlim"])
    if "ylim" in kwargs:
        ax.set_ylim(kwargs["ylim"])

    if "filename" in kwargs:
        fig.savefig(kwargs["filename"])

    return fig, ax