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

.. only:: html

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

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

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

.. _sphx_glr_tutorials_personalized_pagerank.py:


.. _tutorials-personalized_pagerank:

===============================
Personalized PageRank on a grid
===============================

This example demonstrates how to calculate and visualize personalized PageRank on a grid. We use the :meth:`igraph.Graph.personalized_pagerank` method, and demonstrate the effects on a grid graph.

.. GENERATED FROM PYTHON SOURCE LINES 12-15

.. note::

   The PageRank score of a vertex reflects the probability that a random walker will be at that vertex over the long run. At each step the walker has a 1 - damping chance to restart the walk and pick a starting vertex according to the probabilities defined in the reset vector.

.. GENERATED FROM PYTHON SOURCE LINES 15-21

.. code-block:: Python


    import igraph as ig
    import matplotlib.cm as cm
    import matplotlib.pyplot as plt
    import numpy as np








.. GENERATED FROM PYTHON SOURCE LINES 22-27

We define a function that plots the graph on a Matplotlib axis, along with
its personalized PageRank values. The function also generates a
color bar on the side to see how the values change.
We use `Matplotlib's Normalize class <https://matplotlib.org/stable/api/_as_gen/matplotlib.colors.Normalize.html>`_
to set the colors and ensure that our color bar range is correct.

.. GENERATED FROM PYTHON SOURCE LINES 27-68

.. code-block:: Python



    def plot_pagerank(graph: ig.Graph, p_pagerank: list[float]):
        """Plots personalized PageRank values on a grid graph with a colorbar.

        Parameters
        ----------
        graph : ig.Graph
            graph to plot
        p_pagerank : list[float]
            calculated personalized PageRank values
        """
        # Create the axis for matplotlib
        _, ax = plt.subplots(figsize=(8, 8))

        # Create a matplotlib colormap
        # coolwarm goes from blue (lowest value) to red (highest value)
        cmap = cm.coolwarm

        # Normalize the PageRank values for colormap
        normalized_pagerank = ig.rescale(p_pagerank)

        graph.vs["color"] = [cmap(pr) for pr in normalized_pagerank]
        graph.vs["size"] = ig.rescale(p_pagerank, (20, 40))
        graph.es["color"] = "gray"
        graph.es["width"] = 1.5

        # Plot the graph
        ig.plot(graph, target=ax, layout=graph.layout_grid())

        # Add a colorbar
        sm = cm.ScalarMappable(
            norm=plt.Normalize(min(p_pagerank), max(p_pagerank)), cmap=cmap
        )
        plt.colorbar(sm, ax=ax, label="Personalized PageRank")

        plt.title("Graph with Personalized PageRank")
        plt.axis("equal")
        plt.show()









.. GENERATED FROM PYTHON SOURCE LINES 69-70

First, we generate a graph, e.g. a Lattice Graph, which basically is a ``dim x dim`` grid:

.. GENERATED FROM PYTHON SOURCE LINES 70-74

.. code-block:: Python

    dim = 5
    grid_size = (dim, dim)  # dim rows, dim columns
    g = ig.Graph.Lattice(dim=grid_size, circular=False)








.. GENERATED FROM PYTHON SOURCE LINES 75-76

Then we initialize the ``reset_vector`` (it's length should be equal to the number of vertices in the graph):

.. GENERATED FROM PYTHON SOURCE LINES 76-78

.. code-block:: Python

    reset_vector = np.zeros(g.vcount())








.. GENERATED FROM PYTHON SOURCE LINES 79-80

Then we set the nodes to prioritize, for example nodes with indices ``0`` and ``18``:

.. GENERATED FROM PYTHON SOURCE LINES 80-83

.. code-block:: Python

    reset_vector[0] = 1
    reset_vector[18] = 0.65








.. GENERATED FROM PYTHON SOURCE LINES 84-85

Then we calculate the personalized PageRank:

.. GENERATED FROM PYTHON SOURCE LINES 85-87

.. code-block:: Python

    personalized_page_rank = g.personalized_pagerank(damping=0.85, reset=reset_vector)








.. GENERATED FROM PYTHON SOURCE LINES 88-89

Finally, we plot the graph with the personalized PageRank values:

.. GENERATED FROM PYTHON SOURCE LINES 89-92

.. code-block:: Python

    plot_pagerank(g, personalized_page_rank)





.. image-sg:: /tutorials/images/sphx_glr_personalized_pagerank_001.png
   :alt: Graph with Personalized PageRank
   :srcset: /tutorials/images/sphx_glr_personalized_pagerank_001.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 93-94

Alternatively, we can play around with the ``damping`` parameter:

.. GENERATED FROM PYTHON SOURCE LINES 94-96

.. code-block:: Python

    personalized_page_rank = g.personalized_pagerank(damping=0.45, reset=reset_vector)








.. GENERATED FROM PYTHON SOURCE LINES 97-98

Here we can see the same plot with the new damping parameter:

.. GENERATED FROM PYTHON SOURCE LINES 98-99

.. code-block:: Python

    plot_pagerank(g, personalized_page_rank)



.. image-sg:: /tutorials/images/sphx_glr_personalized_pagerank_002.png
   :alt: Graph with Personalized PageRank
   :srcset: /tutorials/images/sphx_glr_personalized_pagerank_002.png
   :class: sphx-glr-single-img






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

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


.. _sphx_glr_download_tutorials_personalized_pagerank.py:

.. only:: html

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

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

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

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

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

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

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


.. only:: html

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

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