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

.. only:: html

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

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

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

.. _sphx_glr_tutorials_gradient.py:


Compute gradient of scalar field on a mesh
==========================================
:mod:`graphlow` can treat a mesh as a graph and
compute gradients of physical quantities given on the graph.

This tutorial shows how to compute the gradient of a scalar field on a mesh.

.. image:: ./images/sphx_glr_gradient_001.png
    :width: 300
    :align: center

.. GENERATED FROM PYTHON SOURCE LINES 15-16

Import necessary modules including :mod:`graphlow`.

.. GENERATED FROM PYTHON SOURCE LINES 16-23

.. code-block:: Python

    import numpy as np
    import pyvista as pv
    import torch

    import graphlow









.. GENERATED FROM PYTHON SOURCE LINES 24-28

Prepare grid mesh
-----------------
First, we define a function to generate grid data as the example mesh.
If you wish to use your own mesh, you can skip this step.

.. GENERATED FROM PYTHON SOURCE LINES 28-37

.. code-block:: Python

    def generate_grid(ni: int, nj: int) -> pv.StructuredGrid:
        x = np.linspace(-1, 1, ni, dtype=np.float32)
        y = np.linspace(-1, 1, nj, dtype=np.float32)
        X, Y = np.meshgrid(x, y, indexing="xy")
        Z = np.zeros([ni, nj], dtype=np.float32)
        grid = pv.StructuredGrid(X, Y, Z)
        return grid









.. GENERATED FROM PYTHON SOURCE LINES 38-47

Define a scalar field
---------------------
Next, we define a scalar field that depends on the coordinates.
We define a scalar field as follows:

.. math::
   \phi = x^2 - y^2

You can modify the scalar field as you like.

.. GENERATED FROM PYTHON SOURCE LINES 47-53

.. code-block:: Python

    def scalar_field(pos: np.ndarray) -> np.ndarray:
        x = pos[:, 0]
        y = pos[:, 1]
        return x * x - y * y









.. GENERATED FROM PYTHON SOURCE LINES 54-58

Compute gradient
----------------
To compute the gradient of a physical quantity using graphlow,
we use :func:`compute_isoAM`.

.. GENERATED FROM PYTHON SOURCE LINES 58-69

.. code-block:: Python

    def compute_gradient(
        mesh: graphlow.GraphlowMesh, phi: np.ndarray
    ) -> torch.Tensor:
        grad_adjs, _ = mesh.compute_isoAM(with_moment_matrix=True)
        grad_x = grad_adjs[0] @ phi
        grad_y = grad_adjs[1] @ phi
        grad_z = grad_adjs[2] @ phi
        grad_vectors = torch.stack((grad_x, grad_y, grad_z), dim=-1)
        return grad_vectors









.. GENERATED FROM PYTHON SOURCE LINES 70-74

Visualize
---------
To visualize the the scalar field and its gradient,
we define the following function.

.. GENERATED FROM PYTHON SOURCE LINES 74-84

.. code-block:: Python

    def draw(grid: pv.StructuredGrid):
        plotter = pv.Plotter(window_size=[800, 600])
        plotter.add_mesh(grid, scalars="phi", show_edges=True)
        plotter.add_arrows(
            grid.points, grid["grad_phi"], mag=0.1, show_scalar_bar=False
        )
        plotter.show_bounds(grid, location="outer")
        plotter.show()









.. GENERATED FROM PYTHON SOURCE LINES 85-88

Main
----
Finally, we define the main function to run the tutorial.

.. GENERATED FROM PYTHON SOURCE LINES 88-107

.. code-block:: Python

    ni = 11
    nj = 11


    def main():
        grid = generate_grid(ni, nj)
        mesh = graphlow.GraphlowMesh(grid)

        phi = scalar_field(mesh.points)
        grad_phi = compute_gradient(mesh, phi)

        grid["phi"] = phi.numpy()
        grid["grad_phi"] = grad_phi.numpy()

        draw(grid)


    if __name__ == "__main__":
        main()



.. image-sg:: /tutorials/images/sphx_glr_gradient_001.png
   :alt: gradient
   :srcset: /tutorials/images/sphx_glr_gradient_001.png
   :class: sphx-glr-single-img


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

 .. code-block:: none

    /home/runner/work/graphlow/graphlow/src/graphlow/processors/graph_processor.py:48: UserWarning: Sparse CSR tensor support is in beta state. If you miss a functionality in the sparse tensor support, please submit a feature request to https://github.com/pytorch/pytorch/issues. (Triggered internally at /pytorch/aten/src/ATen/SparseCsrTensorImpl.cpp:53.)
      cell_point_incidence = torch.sparse_csr_tensor(





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

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


.. _sphx_glr_download_tutorials_gradient.py:

.. only:: html

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

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

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

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

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

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

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


.. only:: html

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

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