Esempio n. 1
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
Esempio n. 2
0
    def test_restarts(self, dim, interp, simInput):
        print(f"test_restarts dim/interp:{dim}/{interp}")

        simput = copy.deepcopy(simInput)

        for key in ["cells", "dl", "boundary_types"]:
            simput[key] = [simput[key]] * dim

        if "refinement" not in simput:
            b0 = [[10 for i in range(dim)], [19 for i in range(dim)]]
            simput["refinement_boxes"] = {"L0": {"B0": b0}}
        else:  # https://github.com/LLNL/SAMRAI/issues/199
            # tagging can handle more than one timestep as it does not
            #  appear subject to regridding issues, so we make more timesteps
            #  to confirm simulations are still equivalent
            simput["time_step_nbr"] = 10

        # if restart time exists it "loads" from restart file
        #  otherwise just saves restart files based on timestamps
        assert "restart_time" not in simput["restart_options"]

        simput["interp_order"] = interp
        time_step = simput["time_step"]
        time_step_nbr = simput["time_step_nbr"]

        restart_idx = 4
        restart_time = time_step * restart_idx
        timestamps = [time_step * restart_idx, time_step * time_step_nbr]

        # first simulation
        local_out = f"{out}/test/{dim}/{interp}/mpi_n/{cpp.mpi_size()}/id{self.ddt_test_id()}"
        simput["restart_options"]["dir"] = local_out
        simput["diag_options"]["options"]["dir"] = local_out
        ph.global_vars.sim = None
        ph.global_vars.sim = ph.Simulation(**simput)
        assert "restart_time" not in ph.global_vars.sim.restart_options
        model = setup_model()
        dump_all_diags(model.populations, timestamps=np.array(timestamps))
        Simulator(ph.global_vars.sim).run().reset()
        self.register_diag_dir_for_cleanup(local_out)
        diag_dir0 = local_out

        # second restarted simulation
        local_out = f"{local_out}_n2"
        simput["diag_options"]["options"]["dir"] = local_out
        simput["restart_options"]["restart_time"] = restart_time
        ph.global_vars.sim = None
        ph.global_vars.sim = ph.Simulation(**simput)
        assert "restart_time" in ph.global_vars.sim.restart_options
        model = setup_model()
        dump_all_diags(model.populations, timestamps=np.array(timestamps))
        Simulator(ph.global_vars.sim).run().reset()
        self.register_diag_dir_for_cleanup(local_out)
        diag_dir1 = local_out

        def check(qty0, qty1, checker):
            checks = 0
            for ilvl, lvl0 in qty0.patch_levels.items():
                patch_level1 = qty1.patch_levels[ilvl]
                for p_idx, patch0 in enumerate(lvl0):
                    patch1 = patch_level1.patches[p_idx]
                    for pd_key, pd0 in patch0.patch_datas.items():
                        pd1 = patch1.patch_datas[pd_key]
                        self.assertNotEqual(id(pd0), id(pd1))
                        checker(pd0, pd1)
                        checks += 1
            return checks

        def check_particles(qty0, qty1):
            return check(
                qty0, qty1,
                lambda pd0, pd1: self.assertEqual(pd0.dataset, pd1.dataset))

        def check_field(qty0, qty1):
            return check(
                qty0, qty1, lambda pd0, pd1: np.testing.assert_equal(
                    pd0.dataset[:], pd1.dataset[:]))

        def count_levels_and_patches(qty):
            n_levels = len(qty.patch_levels)
            n_patches = 0
            for ilvl, lvl in qty.patch_levels.items():
                n_patches += len(qty.patch_levels[ilvl].patches)
            return n_levels, n_patches

        n_quantities_per_patch = 20
        pops = model.populations
        for time in timestamps:
            checks = 0

            run0 = Run(diag_dir0)
            run1 = Run(diag_dir1)
            checks += check_particles(run0.GetParticles(time, pops),
                                      run1.GetParticles(time, pops))
            checks += check_field(run0.GetB(time), run1.GetB(time))
            checks += check_field(run0.GetE(time), run1.GetE(time))
            checks += check_field(run0.GetNi(time), run1.GetNi(time))
            checks += check_field(run0.GetVi(time), run1.GetVi(time))

            for pop in pops:
                checks += check_field(run0.GetFlux(time, pop),
                                      run1.GetFlux(time, pop))
                checks += check_field(run0.GetN(time, pop),
                                      run1.GetN(time, pop))

            n_levels, n_patches = count_levels_and_patches(run0.GetB(time))
            self.assertEqual(n_levels, 2)  # at least 2 levels
            self.assertGreaterEqual(n_patches,
                                    n_levels)  # at least one patch per level
            self.assertEqual(checks, n_quantities_per_patch * n_patches)