.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "examples_gallery/advanced_pdes/post_step_hook_class.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_examples_gallery_advanced_pdes_post_step_hook_class.py: Post-step hook function in a custom class ========================================= The hook function created by :meth:`~pde.pdes.PDEBase.make_post_step_hook` is called after each time step. The function can modify the state, keep track of additional information, and abort the simulation. .. GENERATED FROM PYTHON SOURCE LINES 9-41 .. image-sg:: /examples_gallery/advanced_pdes/images/sphx_glr_post_step_hook_class_001.png :alt: Total correction=651.6439721484724 :srcset: /examples_gallery/advanced_pdes/images/sphx_glr_post_step_hook_class_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none 0%| | 0/10000.0 [00:00 1 # get violating entries overshoot = (state_data[i] - 1).sum() # get total correction state_data[i] = 1 # limit data entries post_step_data += overshoot # accumulate total correction if post_step_data > 400: # Abort simulation when correction exceeds 400 # Note that the `post_step_data` of the previous step will be returned. raise StopIteration return post_step_hook, 0.0 # hook function and initial value for data def evolution_rate(self, state, t=0): """Evaluate the right hand side of the evolution equation.""" return state.__class__(state.grid, data=1) # constant growth grid = UnitGrid([64, 64]) # generate grid state = ScalarField.random_uniform(grid, 0.0, 0.5) # generate initial condition eq = CustomPDE() result = eq.solve(state, dt=0.1, t_range=1e4) result.plot(title=f"Total correction={eq.diagnostics['solver']['post_step_data']}") .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.058 seconds) .. _sphx_glr_download_examples_gallery_advanced_pdes_post_step_hook_class.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: post_step_hook_class.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: post_step_hook_class.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: post_step_hook_class.zip `