.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "examples_gallery/simple_pdes/pde_heterogeneous_diffusion.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_simple_pdes_pde_heterogeneous_diffusion.py: Diffusion equation with spatial dependence ========================================== This example solve the `Diffusion equation `_ with a heterogeneous diffusivity: .. math:: \partial_t c = \nabla\bigr( D(\boldsymbol r) \nabla c \bigr) using the :class:`~pde.pdes.pde.PDE` class. In particular, we consider :math:`D(x) = 1.01 + \tanh(x)`, which gives a low diffusivity on the left side of the domain. Note that the naive implementation, :code:`PDE({"c": "divergence((1.01 + tanh(x)) * gradient(c))"})`, has numerical instabilities. This is because two finite difference approximations are nested. To arrive at a more stable numerical scheme, it is advisable to expand the divergence, .. math:: \partial_t c = D \nabla^2 c + \nabla D . \nabla c .. GENERATED FROM PYTHON SOURCE LINES 24-41 .. image-sg:: /examples_gallery/simple_pdes/images/sphx_glr_pde_heterogeneous_diffusion_001.png :alt: pde heterogeneous diffusion :srcset: /examples_gallery/simple_pdes/images/sphx_glr_pde_heterogeneous_diffusion_001.png :class: sphx-glr-single-img .. code-block:: Python from pde import PDE, CartesianGrid, MemoryStorage, ScalarField, plot_kymograph # Expanded definition of the PDE diffusivity = "1.01 + tanh(x)" term_1 = f"({diffusivity}) * laplace(c)" term_2 = f"dot(gradient({diffusivity}), gradient(c))" eq = PDE({"c": f"{term_1} + {term_2}"}, bc={"value": 0}) grid = CartesianGrid([[-5, 5]], 64) # generate grid field = ScalarField(grid, 1) # generate initial condition storage = MemoryStorage() # store intermediate information of the simulation res = eq.solve(field, 100, dt=1e-3, tracker=storage.tracker(1)) # solve the PDE plot_kymograph(storage) # visualize the result in a space-time plot .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 9.407 seconds) .. _sphx_glr_download_examples_gallery_simple_pdes_pde_heterogeneous_diffusion.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: pde_heterogeneous_diffusion.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: pde_heterogeneous_diffusion.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: pde_heterogeneous_diffusion.zip `