
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "_as_gen/tests_ci/run_test_last_cfl_dt.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download__as_gen_tests_ci_run_test_last_cfl_dt.py>`
        to download the full example code.

.. rst-class:: sphx-glr-example-title

.. _sphx_glr__as_gen_tests_ci_run_test_last_cfl_dt.py:


CI test: last CFL dt stored in synchronized edges
=================================================

Checks that the SPH solver stores the last CFL timestep in the synchronized
edges and that ``model.get_last_cfl_dts()`` exposes it:

- without CFL detail, only the global ``"cfl_dt"`` edge exists,
- with CFL detail, one ``"cfl_dt_<type>"`` edge per enabled CFL condition
  exists as well, and ``"cfl_dt"`` is their minimum,
- the values are identical on every rank and survive a dump/reload.

.. GENERATED FROM PYTHON SOURCE LINES 13-134




.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    SPH setup: generating particles ...  
    SPH setup: Nstep = 59 ( 5.9e+01 ) Ntotal = 59 ( 5.9e+01 rank min = 2.0e+04 max = 5.9e+01) rate = 5.900000e+01 N.s^-1  
    SPH setup: Nstep = 100 ( 1.0e+02 ) Ntotal = 159 ( 1.6e+02 rank min = 5.8e+04 max = 1.6e+02) rate = 1.590000e+02 N.s^-1  
    SPH setup: Nstep = 102 ( 1.0e+02 ) Ntotal = 261 ( 2.6e+02 rank min = 1.5e+04 max = 2.6e+02) rate = 2.610000e+02 N.s^-1  
    SPH setup: Nstep = 8 ( 8.0e+00 ) Ntotal = 269 ( 2.7e+02 rank min = 3.3e+04 max = 2.7e+02) rate = 2.690000e+02 N.s^-1  
    SPH setup: the generation step took : 0.013146215000000001 s  
    SPH setup: final particle count = 269 beginning injection ...  
    SPH setup: injected          269 / 269 => 100.0% | ranks with patchs = 1 / 1  <- global loop -> (msg count : 0)  
    SPH setup: the injection step took : 0.012309426 s  
    SPH setup: the setup took : 0.029039625000000003 s  
    ---------------- t = 0, dt = 0 ---------------- 
    Warning: the unit system is not set                                           [sph::Config][rank=0] 
    Warning: the unit system is not set                                           [sph::Config][rank=0] 
    Warning: the unit system is not set                                           [sph::Config][rank=0] 
    Warning: High interface/patch volume ratio.                                  [InterfaceGen][rank=0]
        This can lead to high mpi overhead, try to increase the patch split crit  
    Warning: smoothing length is not converged, rerunning the iterator ...    [Smoothinglength][rank=0]
         largest h = 0.19599771799087468 unconverged cnt = 269   
    Warning: High interface/patch volume ratio.                                  [InterfaceGen][rank=0]
        This can lead to high mpi overhead, try to increase the patch split crit  
    Warning: smoothing length is not converged, rerunning the iterator ...    [Smoothinglength][rank=0]
         largest h = 0.21559748978996215 unconverged cnt = 146   
    Warning: High interface/patch volume ratio.                                  [InterfaceGen][rank=0]
        This can lead to high mpi overhead, try to increase the patch split crit  
    Warning: smoothing length is not converged, rerunning the iterator ...    [Smoothinglength][rank=0]
         largest h = 0.2371572387689584 unconverged cnt = 12   
    Warning: High interface/patch volume ratio.                                  [InterfaceGen][rank=0]
        This can lead to high mpi overhead, try to increase the patch split crit  
    Warning: the unit system is not set                                           [sph::Config][rank=0] 
    ---------------- t = 0, dt = 0.0006110884515229946 ---------------- 
    Warning: the unit system is not set                                           [sph::Config][rank=0] 
    Warning: the unit system is not set                                           [sph::Config][rank=0] 
    Warning: the unit system is not set                                           [sph::Config][rank=0] 
    Warning: High interface/patch volume ratio.                                  [InterfaceGen][rank=0]
        This can lead to high mpi overhead, try to increase the patch split crit  
    Warning: the unit system is not set                                           [sph::Config][rank=0] 
    last cfl dt (detail off): {'cfl_dt': 0.020786931140653973}
    SPH setup: generating particles ...  
    SPH setup: Nstep = 59 ( 5.9e+01 ) Ntotal = 59 ( 5.9e+01 rank min = 3.4e+05 max = 5.9e+01) rate = 5.900000e+01 N.s^-1  
    SPH setup: Nstep = 100 ( 1.0e+02 ) Ntotal = 159 ( 1.6e+02 rank min = 2.3e+05 max = 1.6e+02) rate = 1.590000e+02 N.s^-1  
    SPH setup: Nstep = 102 ( 1.0e+02 ) Ntotal = 261 ( 2.6e+02 rank min = 2.2e+05 max = 2.6e+02) rate = 2.610000e+02 N.s^-1  
    SPH setup: Nstep = 8 ( 8.0e+00 ) Ntotal = 269 ( 2.7e+02 rank min = 8.5e+04 max = 2.7e+02) rate = 2.690000e+02 N.s^-1  
    SPH setup: the generation step took : 0.001952099 s  
    SPH setup: final particle count = 269 beginning injection ...  
    SPH setup: injected          269 / 269 => 100.0% | ranks with patchs = 1 / 1  <- global loop -> (msg count : 0)  
    SPH setup: the injection step took : 0.002739735 s  
    SPH setup: the setup took : 0.005366381 s  
    ---------------- t = 0, dt = 0 ---------------- 
    Warning: the unit system is not set                                           [sph::Config][rank=0] 
    Warning: the unit system is not set                                           [sph::Config][rank=0] 
    Warning: the unit system is not set                                           [sph::Config][rank=0] 
    Warning: High interface/patch volume ratio.                                  [InterfaceGen][rank=0]
        This can lead to high mpi overhead, try to increase the patch split crit  
    Warning: smoothing length is not converged, rerunning the iterator ...    [Smoothinglength][rank=0]
         largest h = 0.19599771799087468 unconverged cnt = 269   
    Warning: High interface/patch volume ratio.                                  [InterfaceGen][rank=0]
        This can lead to high mpi overhead, try to increase the patch split crit  
    Warning: smoothing length is not converged, rerunning the iterator ...    [Smoothinglength][rank=0]
         largest h = 0.21559748978996215 unconverged cnt = 146   
    Warning: High interface/patch volume ratio.                                  [InterfaceGen][rank=0]
        This can lead to high mpi overhead, try to increase the patch split crit  
    Warning: smoothing length is not converged, rerunning the iterator ...    [Smoothinglength][rank=0]
         largest h = 0.2371572387689584 unconverged cnt = 12   
    Warning: High interface/patch volume ratio.                                  [InterfaceGen][rank=0]
        This can lead to high mpi overhead, try to increase the patch split crit  
    Warning: the unit system is not set                                           [sph::Config][rank=0] 
    ---------------- t = 0, dt = 0.0006110884515229946 ---------------- 
    Warning: the unit system is not set                                           [sph::Config][rank=0] 
    Warning: the unit system is not set                                           [sph::Config][rank=0] 
    Warning: the unit system is not set                                           [sph::Config][rank=0] 
    Warning: High interface/patch volume ratio.                                  [InterfaceGen][rank=0]
        This can lead to high mpi overhead, try to increase the patch split crit  
    Warning: the unit system is not set                                           [sph::Config][rank=0] 
    last cfl dt (detail on): {'cfl_dt': 0.020786931140653973, 'cfl_dt_courant': 0.02145652566989449, 'cfl_dt_force': 0.020786931140653973, 'cfl_dt_sink_sink': 92.50265378943428}
    last cfl dt test: OK






|

.. code-block:: Python
   :lineno-start: 14


    import shamrock

    DUMP_NAME = "last_cfl_dt_test.sham"


    def build_model(show_cfl_detail):
        ctx = shamrock.Context()
        ctx.pdata_layout_new()

        model = shamrock.get_Model_SPH(context=ctx, vector_type="f64_3", sph_kernel="M4")

        cfg = model.gen_default_config()
        cfg.set_self_gravity_none()
        cfg.set_artif_viscosity_Constant(alpha_u=1.0, alpha_AV=1.0, beta_AV=2.0)
        cfg.set_eos_isothermal(1.0)
        cfg.set_particle_mass(1e-3)
        cfg.set_boundary_periodic()
        cfg.set_show_cfl_detail(show_cfl_detail)
        model.set_solver_config(cfg)

        model.init_scheduler(1000, 1)

        dr = 0.1
        bmin = (-0.6, -0.6, -0.6)
        bmax = (0.6, 0.6, 0.6)
        model.resize_simulation_box(bmin, bmax)

        setup = model.get_setup()
        gen = setup.make_generator_lattice_hcp(dr, bmin, bmax)
        setup.apply_setup(gen)

        model.set_field_value_lambda_f64_3("vxyz", lambda r: (1.0, 0.0, 0.0))

        model.add_sink(1.0, (0.1, 0.0, 0.0), (0.0, 0.05, 0.0), 0.05)
        model.add_sink(0.5, (-0.2, 0.1, 0.0), (0.0, -0.03, 0.0), 0.05)

        return ctx, model


    def check_in_sync(cfl):
        s = str(sorted(cfl.items()))
        # Collective: every rank must call this
        hist = shamrock.algs.all_string_histogram([s], delimiter="\n", hash_based=False)
        if len(hist) != 1 or next(iter(hist.values())) != shamrock.sys.world_size():
            raise RuntimeError(f"last cfl dt not in sync across ranks: {hist}")


    def check_detail_off():
        ctx, model = build_model(show_cfl_detail=False)

        cfl = model.get_last_cfl_dts()
        if cfl != {"cfl_dt": 0.0}:
            raise RuntimeError(f"expected only 'cfl_dt' = 0 before the first step, got {cfl}")

        model.timestep()  # first step only computes the initial dt
        model.timestep()

        cfl = model.get_last_cfl_dts()
        if shamrock.sys.world_rank() == 0:
            print("last cfl dt (detail off):", cfl)

        if set(cfl.keys()) != {"cfl_dt"}:
            raise RuntimeError(f"expected only 'cfl_dt' without cfl detail, got {cfl}")
        if cfl["cfl_dt"] != model.get_dt():
            raise RuntimeError(f"cfl_dt={cfl['cfl_dt']} != next dt={model.get_dt()}")

        check_in_sync(cfl)


    def check_detail_on():
        ctx, model = build_model(show_cfl_detail=True)

        expected = {"cfl_dt", "cfl_dt_courant", "cfl_dt_force", "cfl_dt_sink_sink"}

        cfl = model.get_last_cfl_dts()
        if cfl != {k: 0.0 for k in expected}:
            raise RuntimeError(f"expected {sorted(expected)} = 0 before the first step, got {cfl}")

        model.timestep()
        model.timestep()

        cfl = model.get_last_cfl_dts()
        if shamrock.sys.world_rank() == 0:
            print("last cfl dt (detail on):", cfl)

        if set(cfl.keys()) != expected:
            raise RuntimeError(f"expected keys {sorted(expected)}, got {sorted(cfl.keys())}")

        detail_min = min(v for k, v in cfl.items() if k != "cfl_dt")
        if cfl["cfl_dt"] != detail_min:
            raise RuntimeError(f"cfl_dt={cfl['cfl_dt']} != min of per-type cfl dt={detail_min}")
        if cfl["cfl_dt"] != model.get_dt():
            raise RuntimeError(f"cfl_dt={cfl['cfl_dt']} != next dt={model.get_dt()}")

        check_in_sync(cfl)

        model.dump(DUMP_NAME)

        del model
        del ctx

        ctx2 = shamrock.Context()
        ctx2.pdata_layout_new()
        model2 = shamrock.get_Model_SPH(context=ctx2, vector_type="f64_3", sph_kernel="M4")
        model2.load_from_dump(DUMP_NAME)

        cfl_reload = model2.get_last_cfl_dts()
        if cfl_reload != cfl:
            raise RuntimeError(
                f"last cfl dt changed across dump/reload:\n  before={cfl}\n  after ={cfl_reload}"
            )

        check_in_sync(cfl_reload)


    check_detail_off()
    check_detail_on()

    if shamrock.sys.world_rank() == 0:
        print("last cfl dt test: OK")


.. rst-class:: sphx-glr-timing

   **Total running time of the script:** (0 minutes 0.442 seconds)

**Estimated memory usage:**  217 MB


.. _sphx_glr_download__as_gen_tests_ci_run_test_last_cfl_dt.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: run_test_last_cfl_dt.ipynb <run_test_last_cfl_dt.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: run_test_last_cfl_dt.py <run_test_last_cfl_dt.py>`

    .. container:: sphx-glr-download sphx-glr-download-zip

      :download:`Download zipped: run_test_last_cfl_dt.zip <run_test_last_cfl_dt.zip>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
