Activité pratique

Durée2h30

Consignes globales

L’objectif de cette activité est d’écrire des programmes pour guider votre rat à travers le labyrinthe grâce à des algorithmes de parcours. Nous allons tout d’abord nous placer dans un cas simple :

  • Un seul joueur.
  • Un seul morceau de fromage à attraper.
  • Pas de boue dans le labyrinthe.

Nous écrirons deux algorithmes de parcours, le parcours en profondeur (DFS) et le parcours en largeur (BFS). Nous verrons ensuite que ces deux approches partagent pas mal d’éléments en commun, ce qui nous permettra de mieux structurer nos programmes.

Important

Contrairement aux activités de programmation, algorithmique ou environnement (où chaque séance est indépendante des précédentes), vous n’avez pas à recréer de nouveau projet uv pour cette séance. Celui créé en séance 1 vous servira pour tout le projet.

Contenu de l’activité

Parcours en profondeur (DFS)

Préparation

Tout d’abord, nous allons créer un joueur et un script pour visualiser son comportement.

À faire

Avant de commencer, créez les fichiers nécessaires dans votre workspace PyRat en suivant les instructions ci-dessous.

Pour le moment, ne vous préoccupez pas du comportement de votre joueur, créez juste le strict minimum pour pouvoir lancer une partie avec votre joueur DFS sans que ça crashe.

  • players/dfs.py — Inspirez-vous de ce que vous avez fait en séance 1 pour créer un joueur DFS héritant de Player, et ayant :

    • Un constructeur __init__(...).
    • Une méthode preprocessing(...).
    • Une méthode turn(...).
  • games/visualize_dfs.py — Créez un fichier qui lancera une partie avec un joueur DFS, dans un labyrinthe respectant les critères listés plus haut (un seul fromage, pas de boue). Vous pouvez éventuellement définir une random_seed (pour toujours travailler avec le même labyrinthe) et une trace_length (pour suivre la trajectoire de votre joueur). Inspirez-vous des autres fichiers du sous-dossier games que vous avez rencontrés lors de la séance précédente.

Correction
Cliquez ici pour afficher la correction.

Comme indiqué dans les instructions, vous devez créer une classe héritant de Player, nommée DFS, dans un fichier dfs.py dans le sous-dossier players de pyrat_workspace. Faites attention à ce que turn(...) renvoie bien une action, qui peut être Action.NOTHING.

Il serait aussi bien de mettre à jour les documentations pour que ça corresponde au parcours en profondeur et pas à un RandomX ou TemplatePlayer selon le fichier dont vous êtes parti(e)s.

Vous devez également créer un script visualize_dfs.py dans le sous-dossier games. Attention à bien fixer les arguments mud_percentage et nb_cheese du constructeur de la classe Game. Le fichier devrait ressembler à ça :

​
##########################################################################################
########################################## INFO ##########################################
##########################################################################################

"""
This program is a solution to the practical session 2 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session2/practical/
"""

##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################

# External imports
import pprint

# PyRat imports
from pyrat import Game
from players.dfs import DFS

##########################################################################################
######################################### SCRIPT #########################################
##########################################################################################

if __name__ == "__main__":

    # Instantiate a game with a few arguments
    game_config = {"mud_percentage": 0.0,
                   "maze_width": 13,
                   "maze_height": 10,
                   "nb_cheese": 1,
                   "random_seed": 2,
                   "trace_length": 1000}

    # Instantiate a game with specified arguments
    game = Game(**game_config)

    # Instantiate the player
    player = DFS()
    game.add_player(player)

    # Start the game
    stats = game.start()
    pprint.pprint(stats)

##########################################################################################
##########################################################################################

La méthode traversal(...)

Implémentation

Comme vous avez pu l’étudier dans vos cours de programmation et d’algorithmique, la clé pour écrire un bon programme est de bien décomposer les tâches à effectuer en fonctions. Pour cela, au lieu d’effectuer directement le parcours dans une des méthodes du joueur, on vous demande d’écrire une méthode traversal(...) qui effectuera le parcours en profondeur, et renverra les distances depuis la source jusqu’à chaque sommet exploré, ainsi que la table de routage correspondante.

La distance à un sommet est la somme des poids des arêtes le long du chemin trouvé par le parcours (qui n’est pas forcément le plus court). Le poids de l’arête entre deux sommets voisins u et v s’obtient avec graph.get_weight(u, v). Il n’y a pas de boue dans les parties de cette séance : tous les poids valent alors 1, et la distance est simplement le nombre de déplacements. Cependant, les tests fournis plus bas utilisent des labyrinthes avec de la boue, et cette notion nous servira en séance 3 : utilisez donc bien graph.get_weight(...) pour calculer les distances.

À faire

Copiez-collez le code suivant dans votre fichier dfs.py, et complétez la méthode.

Notez que cette méthode prend en paramètre un objet de type Graph (et non un Maze, comme reçu par preprocessing(...) ou turn(...)). En effet, ce parcours est générique, et pourrait s’appliquer à d’autres types de graphes que des labyrinthes. De plus, la classe Maze hérite de Graph : vous pouvez donc fournir un objet de type Maze à traversal(...) sans aucun problème.

​
def traversal ( self,
                graph:  Graph,
                source: int
              ) ->      tuple[dict[int, int], dict[int, int | None]]:

    """
    This method performs a DFS traversal of a graph.
    It returns the explored vertices with associated distances.
    The distance to a vertex is the sum of the weights of the edges along the path found (given by ``graph.get_weight(...)``).
    It also returns the routing table, that is, the parent of each vertex in the traversal.

    Args:
        graph:  The graph to traverse.
        source: The source vertex of the traversal (we type it as int here because we will only manipulate mazes, but Graph uses Hashable as a more generic type).

    Returns:
        A tuple containing:
        - The distances from the source to each explored vertex.
        - The routing table, that is, the parent of each vertex in the traversal (None for the source).
    """

    # Your code here
Correction
Cliquez ici pour afficher la correction.

À terme, le joueur DFS devrait correspondre au diagramme de classes suivant :

Diagramme de classes UML du joueur DFS, qui hérite de Player Diagramme de classes UML du joueur DFS, qui hérite de Player

Et le programme devrait ressembler à ça. Cette correction donne directement la version finale du joueur : en plus de traversal(...), elle contient la méthode find_route(...) et l’attribut actions (utilisés dans preprocessing(...) et turn(...)), qui seront demandés dans les sections « Utiliser la table de routage » et « Assembler tout ça » plus bas.

​
##########################################################################################
########################################## INFO ##########################################
##########################################################################################

"""
This program is a solution to the practical session 2 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session2/practical/
"""

##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################

# PyRat imports
from pyrat import Player, Maze, GameState, Action, Graph

##########################################################################################
######################################### CLASSES ########################################
##########################################################################################

class DFS (Player):

    """
    *(This class inherits from* ``Player`` *).*

    This player performs a depth-first search (DFS) to explore the maze.
    Computation of the path is done in the ``preprocessing(...)`` method.
    The path is then followed in the ``turn(...)`` method.
    """
    
    ##################################################################################
    #                                   CONSTRUCTOR                                  #
    ##################################################################################

    def __init__ ( self,
                   *args:    object,
                   **kwargs: object
                 ) ->        None:

        """
        Initializes a new instance of the class.

        Args:
            args:   Arguments to pass to the parent constructor.
            kwargs: Keyword arguments to pass to the parent constructor.
        """

        # Inherit from parent class
        super().__init__(*args, **kwargs)

        # We create an attribute to store the actions to perform
        self.actions = None

    ##################################################################################
    #                                  PYRAT METHODS                                 #
    ##################################################################################

    def preprocessing ( self,
                        maze:       Maze,
                        game_state: GameState,
                      ) ->          None:
        
        """
        *(This method redefines the method of the parent class with the same name).*

        This method is called once at the beginning of the game.
        Here, we use a DFS algorithm to compute a path that reaches the piece of cheese from the initial position of the player.
        The actions corresponding to the path are stored in the ``actions`` attribute, and will be used in the ``turn(...)`` method.

        Args:
            maze:       An object representing the maze in which the player plays.
            game_state: An object representing the state of the game.
        """

        # We perform a DFS traversal of the maze graph from the initial position of the player
        my_location = game_state.player_locations[self.get_name()]
        distances, routing_table = self.traversal(maze, my_location)

        # Find the series of locations/actions to go from the player location to the first piece of cheese
        path = self.find_route(routing_table, my_location, game_state.cheese[0])
        self.actions = maze.locations_to_actions(path)

    ##################################################################################

    def turn ( self,
               maze:       Maze,
               game_state: GameState,
             ) ->          Action:

        """
        *(This method redefines the method of the parent class with the same name).*

        It is called at each turn of the game.
        It returns an action to perform among the possible actions, defined in the ``Action`` enumeration.
        The action is chosen by following the path computed in the ``preprocessing(...)`` method.

        Args:
            maze:       An object representing the maze in which the player plays.
            game_state: An object representing the state of the game.
        
        Returns:
            One of the possible actions.
        """

        # At each turn, we perform the next action in the list of actions
        return self.actions.pop(0)

    ##################################################################################
    #                                  OTHER METHODS                                 #
    ##################################################################################

    def traversal ( self,
                    graph:  Graph,
                    source: int
                  ) ->      tuple[dict[int, int], dict[int, int | None]]:

        """
        This method performs a DFS traversal of a graph.
        It returns the explored vertices with associated distances.
        It also returns the routing table, that is, the parent of each vertex in the traversal.
        
        Args:
            graph:  The graph to traverse.
            source: The source vertex of the traversal (we type it as int here because we will only manipulate mazes, but Graph uses Hashable as a more generic type).

        Returns:
            A tuple containing:
            - The distances from the source to each explored vertex.
              The distance to a vertex is the sum of the weights of the edges along the path found (given by ``graph.get_weight(...)``).
            - The routing table, that is, the parent of each vertex in the traversal (None for the source).
        """

        # Initialization
        distances = {}
        routing_table = {}

        # Initialize the list of vertices to visit
        vertices_to_visit = []
        vertices_to_visit.append((0, source, None))

        # Traversal
        while vertices_to_visit:

            # Get the next vertex to visit
            distance, vertex, parent = vertices_to_visit.pop()

            # Skip if already visited
            # This can happen if a vertex was added multiple times to the list by different neighbors
            if vertex in distances:
                continue

            # Update the distances and routing table
            distances[vertex] = distance
            routing_table[vertex] = parent

            # Add the neighbors not explored yet to the list of vertices to visit
            # The others would be ignored when extracted anyway
            for neighbor in graph.get_neighbors(vertex):
                if neighbor not in distances:
                    distance_to_neighbor = distances[vertex] + graph.get_weight(vertex, neighbor)
                    vertices_to_visit.append((distance_to_neighbor, neighbor, vertex))
        
        # Return the result
        return distances, routing_table

    ##################################################################################

    def find_route ( self,
                     routing_table: dict[int, int | None],
                     source:        int,
                     target:        int
                   ) ->             list[int]:

        """
        This method finds the route from a source vertex to a target vertex using a routing table.

        Args:
            routing_table: The routing table, that is, the parent of each vertex in the traversal (None for the source).
            source:        The source vertex.
            target:        The target vertex.

        Returns:
            The route from the source to the target as a list of vertices.
        """

        # Initialization
        route = [target]
        vertex = target

        # Find the route
        while vertex != source:
            vertex = routing_table[vertex]
            route.append(vertex)
        
        # Reverse the route
        route.reverse()
        return route

##########################################################################################
##########################################################################################
Tests

Avez-vous bien pensé à vérifier que votre méthode traversal(...) fonctionne ? On peut souvent faire des erreurs en écrivant du code, que ça soit un détail de raisonnement oublié, un cas un peu inhabituel pas géré, ou juste une erreur de syntaxe. Par défaut, une bonne approche est de partir du principe que tout code non testé est faux.

Vous avez vu en séance 2 de programmation comment exécuter des tests unitaires, et en séance 3 comment en concevoir. Pour le moment, nous allons vous fournir un fichier de tests pour vérifier votre implémentation de traversal(...) dans la classe DFS.

À faire

Téléchargez le fichier ci-dessous, et placez-le dans un nouveau dossier tests que vous créerez dans votre dossier pyrat_workspace.

Ce fichier présuppose que vous avez bien suivi les instructions jusqu’à présent, c’est-à-dire que votre joueur s’appelle bien DFS dans un fichier players/dfs.py, que traversal(...) a bien le prototype de la méthode donnée plus haut, etc.

À faire

Ouvrez l’onglet de tests dans VSCode , paramétrez-le pour utiliser unittest, puis cliquez sur le bouton « Run Test » pour exécuter les tests contenus dans le fichier.

Parcourons un peu ce fichier ensemble. Tout d’abord, il contient un peu de documentation, et quelques imports nécessaires. Puis, il introduit une classe DFS_Tests qui hérite de unittest.TestCase, la classe de base pour les tests unitaires dans Python. Cette classe contient un certain nombre d’éléments :

  • Une méthode setUpClass(...). Cette méthode est exécutée une unique fois, avant tous les autres tests de la classe. Elle permet notamment d’initialiser des éléments qui seront utilisés par tous les tests. Ici, nous nous en servons pour créer quelques labyrinthes fixés à l’avance, ainsi qu’une centaine de labyrinthes générés aléatoirement, sur lesquels nous exécuterons nos tests. Notez que cette méthode est une méthode de classe (et non d’instance) comme l’indiquent le décorateur @classmethod et le premier paramètre cls (par opposition à self pour les méthodes d’instance). Cela signifie que les attributs de classe qui y sont créés (ici cls.tree_maze, cls.cycle_maze, cls.disconnected_maze, et cls.random_mazes) seront partagés par toutes les méthodes de test de la classe DFS_Tests, et ne seront pas recréés pour chaque test.

    @classmethod
    def setUpClass (cls) -> None:
    
        """
        This method is called once, before all test methods.
        Here, we use it to create the mazes, so that they are shared by all tests instead of being created again in each test.
        """
    
        cls.tree_maze = ...
        cls.cycle_maze = ...
        cls.disconnected_maze = ...
        cls.random_mazes = ...
  • Ensuite, une méthode setUp(...), exécutée avant chaque test, qui instancie le joueur dont on veut tester les méthodes. Contrairement à setUpClass(...) qui est une méthode de classe, setUp(...) est une méthode d’instance (indiqué par le premier paramètre self). Cela signifie que self.player sera différent pour chaque test.

    def setUp (self) -> None:
    
        """
        This method is called before each test method.
        Here, we use it to instantiate a DFS player.
        """
    
        # Instantiate a DFS player to test its methods
        self.player = DFS()
  • La suite du fichier contient un certain nombre de tests pour la méthode traversal(...). Certains tests vérifient des propriétés sur les labyrinthes fixés (on s’attend à obtenir une sortie particulière) ; d’autres portent sur des labyrinthes tirés aléatoirement, et évaluent des propriétés générales (des invariants) des solutions trouvées. Pour vous aider à vous y retrouver, nous avons choisi de nommer chaque test de manière assez explicite, en suivant le modèle test___<tested method>___<test case>___<tested property>. On précise également pour chaque test s’il correspond à un cas normal, limite (corner case) ou d’erreur. Par exemple, le test suivant (un cas normal) évalue, sur un ensemble de labyrinthes générés aléatoirement, si les types des sorties de la méthode traversal(...) sont corrects :

    def test___dfs_traversal___random_mazes___output_types (self) -> None:
    
        """
        Category: normal use.
        This method tests the ``traversal(...)`` method on random mazes.
        It checks that outputs are of the expected types.
        """
    
        # Distances should be a dictionary with integer keys and values
        # The routing table should be a dictionary with integer keys and integer or None values
        for maze in self.random_mazes:
            start_vertex = maze.get_vertices()[0]
            distances, routing_table = self.player.traversal(maze, start_vertex)
            self.assertIsInstance(distances, dict, "Distances should be a dictionary")
            self.assertTrue(all(isinstance(k, int) and isinstance(v, int) for k, v in distances.items()), "Distances should have integer keys and values")
            self.assertIsInstance(routing_table, dict, "The routing table should be a dictionary")
            self.assertTrue(all(isinstance(k, int) and isinstance(v, (type(None), int)) for k, v in routing_table.items()), "The routing table should have integer keys, and integer or None values")
  • Enfin, nous fournissons d’ores et déjà des tests pour une méthode find_route(...) que nous allons développer dans la partie suivante. Jusque-là, vous avez défini les méthodes avant les tests. Nous allons passer à une approche dite test-driven, où les tests précèdent l’implémentation des méthodes.

Utiliser la table de routage

Implémentation

Maintenant que vous avez un algorithme de parcours qui marche (et testé !), écrivons une méthode qui exploite la table de routage pour renvoyer la série de cases à suivre pour atteindre une case donnée.

À faire

Copiez-collez le code suivant dans votre fichier dfs.py en tant que méthode de la classe DFS. Puis, complétez la méthode pour renvoyer une liste de sommets du graphe telle que le premier élément est la source et le dernier la cible.

​
def find_route ( self,
                 routing_table: dict[int, int | None],
                 source:        int,
                 target:        int
               ) ->             list[int]:

    """
    This method finds the route from a source vertex to a target vertex using a routing table.

    Args:
        routing_table: The routing table, that is, the parent of each vertex in the traversal (None for the source).
        source:        The source vertex.
        target:        The target vertex.

    Returns:
        The route from the source to the target as a list of vertices.
    """

    # Your code here

Pensez à régulièrement exécuter vos tests pour vérifier que votre code est correct.

Correction
Cliquez ici pour afficher la correction.

Voir le contenu de dfs.py dans une des boîtes de corrections plus haut.

Assembler tout ça

Implémentation

Maintenant, il ne reste plus qu’à assembler les morceaux !

À faire

Apportez les modifications suivantes à votre fichier dfs.py.

  • __init__(...) — Mettez à jour votre constructeur afin de déclarer un attribut self.actions = None. Vous pourriez directement l’initialiser avec une liste vide [], mais il est préférable de l’initialiser dans preprocessing(...) pour permettre de faire un reset(...) de la partie sans avoir des valeurs restantes de la partie précédente dans les attributs du joueur.

  • preprocessing(...) — Pendant la phase de prétraitement, utilisez les méthodes introduites précédemment (traversal(...) et find_route(...)) pour calculer les actions à effectuer depuis votre position initiale jusqu’à la position du seul morceau de fromage. Ensuite, stockez ces actions dans l’attribut self.actions.

    Information

    Quelques fonctions de PyRat qui vous seront utiles :

    • Vous pouvez obtenir votre position courante avec my_location = game_state.player_locations[self.get_name()].
    • S’il n’y a qu’un morceau de fromage dans le labyrinthe, sa position est donnée par game_state.cheese[0].
    • Pour obtenir des actions à partir d’un chemin, la classe Maze fournit une méthode locations_to_actions(...).
  • turn(...) — À chaque tour, vous devez retourner une action provenant de self.actions. Il suffit d’extraire la prochaine action à effectuer depuis cet attribut et de la renvoyer.

Correction
Cliquez ici pour afficher la correction.

Voir le contenu de dfs.py dans une des boîtes de corrections plus haut.

À quoi ça ressemble ?

À présent, utilisez votre script visualize_dfs.py pour observer votre joueur.

À faire

Son comportement est-il bon ? Pensez à l’étudier sur quelques labyrinthes distincts.

Vous devriez obtenir un rat qui se comporte comme suit :

Correction
Cliquez ici pour afficher la correction.

Le rat n’est pas censé revenir sur ses pas. Il a déroulé un algorithme en mémoire qui a déterminé un chemin (suite distincte de sommets). C’est un bon indicateur que ça se passe bien.

Pensez à tester sur plusieurs labyrinthes.

Parcours en largeur (BFS)

Comme vous avez pu le voir dans l’article sur les parcours, le DFS trouve un chemin qui n’est pas forcément le plus court. Nous allons maintenant utiliser un autre algorithme, appelé parcours en largeur (Breadth-First Search, BFS). Cet algorithme a la propriété de renvoyer le chemin le plus court dans un graphe non pondéré.

À faire

Suivez les mêmes étapes que pour le développement du parcours en profondeur (rappelées ci-dessous) pour créer un joueur qui suit un chemin trouvé par un parcours en largeur pour attraper le morceau de fromage.

  • Créez un fichier pour lancer une partie, nommé visualize_bfs.py, dans le sous-dossier games de votre workspace PyRat.

  • Créez un fichier joueur nommé bfs.py dans le sous-dossier players. Pour ce dernier, vous pouvez partir d’une copie de votre fichier dfs.py, car il n’y aura pas beaucoup de différences !

  • Adaptez les fonctions pour que votre rat effectue un parcours en largeur pour déterminer le chemin le plus court. N’oubliez pas de modifier la documentation, pour qu’elle décrive bien votre nouveau joueur.

  • N’oubliez pas non plus de tester vos fonctions ! Voici les tests que vous pouvez utiliser pour vous assurer que votre code fonctionne : tests/test_bfs.py.

    Information

    Remarquez à quel point les tests sont similaires à ceux du DFS. Lesquels diffèrent ? Pourquoi ?

Vous devriez obtenir un rat qui se comporte comme suit :

Correction
Cliquez ici pour afficher la correction.

Le joueur BFS a les mêmes attributs et méthodes que DFS :

Diagramme de classes UML du joueur BFS, qui hérite de Player Diagramme de classes UML du joueur BFS, qui hérite de Player

Voici les fichiers à produire :

​
##########################################################################################
########################################## INFO ##########################################
##########################################################################################

"""
This program is a solution to the practical session 2 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session2/practical/
"""

##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################

# PyRat imports
from pyrat import Player, Maze, GameState, Action, Graph

##########################################################################################
######################################### CLASSES ########################################
##########################################################################################

class BFS (Player):

    """
    *(This class inherits from* ``Player`` *).*

    This player performs a breadth-first search (BFS) to explore the maze.
    Computation of the path is done in the ``preprocessing(...)`` method.
    The path is then followed in the ``turn(...)`` method.
    """

    ##################################################################################
    #                                   CONSTRUCTOR                                  #
    ##################################################################################

    def __init__ ( self,
                   *args:    object,
                   **kwargs: object
                 ) ->        None:

        """
        Initializes a new instance of the class.

        Args:
            args:   Arguments to pass to the parent constructor.
            kwargs: Keyword arguments to pass to the parent constructor.
        """

        # Inherit from parent class
        super().__init__(*args, **kwargs)

        # We create an attribute to store the actions to perform
        self.actions = None

    ##################################################################################
    #                                  PYRAT METHODS                                 #
    ##################################################################################

    def preprocessing ( self,
                        maze:       Maze,
                        game_state: GameState,
                      ) ->          None:
        
        """
        *(This method redefines the method of the parent class with the same name).*

        This method is called once at the beginning of the game.
        Here, we use a BFS algorithm to compute a shortest path that reaches the piece of cheese from the initial position of the player.
        The actions corresponding to the path are stored in the ``actions`` attribute, and will be used in the ``turn(...)`` method.

        Args:
            maze:       An object representing the maze in which the player plays.
            game_state: An object representing the state of the game.
        """

        # We perform a BFS traversal of the maze graph from the initial position of the player
        my_location = game_state.player_locations[self.get_name()]
        distances, routing_table = self.traversal(maze, my_location)

        # Find the series of locations/actions to go from the player location to the first piece of cheese
        path = self.find_route(routing_table, my_location, game_state.cheese[0])
        self.actions = maze.locations_to_actions(path)

    ##################################################################################

    def turn ( self,
               maze:       Maze,
               game_state: GameState,
             ) ->          Action:

        """
        *(This method redefines the method of the parent class with the same name).*

        It is called at each turn of the game.
        It returns an action to perform among the possible actions, defined in the ``Action`` enumeration.
        The action is chosen by following the path computed in the ``preprocessing(...)`` method.

        Args:
            maze:       An object representing the maze in which the player plays.
            game_state: An object representing the state of the game.
        
        Returns:
            One of the possible actions.
        """

        # At each turn, we perform the next action in the list of actions
        return self.actions.pop(0)

    ##################################################################################
    #                                  OTHER METHODS                                 #
    ##################################################################################

    def traversal ( self,
                    graph:  Graph,
                    source: int
                  ) ->      tuple[dict[int, int], dict[int, int | None]]:

        """
        This method performs a BFS traversal of a graph.
        It returns the explored vertices with associated distances.
        It also returns the routing table, that is, the parent of each vertex in the traversal.
        
        Args:
            graph:  The graph to traverse.
            source: The source vertex of the traversal (we type it as int here because we will only manipulate mazes, but Graph uses Hashable as a more generic type).

        Returns:
            A tuple containing:
            - The distances from the source to each explored vertex.
              The distance to a vertex is the sum of the weights of the edges along the path found (given by ``graph.get_weight(...)``).
            - The routing table, that is, the parent of each vertex in the traversal (None for the source).
        """

        # Initialization
        distances = {}
        routing_table = {}

        # Initialize the list of vertices to visit
        vertices_to_visit = []
        vertices_to_visit.append((0, source, None))

        # Traversal
        while vertices_to_visit:

            # Get the next vertex to visit
            distance, vertex, parent = vertices_to_visit.pop(0)

            # Skip if already visited
            # This can happen if a vertex was added multiple times to the list by different neighbors
            if vertex in distances:
                continue

            # Update the distances and routing table
            distances[vertex] = distance
            routing_table[vertex] = parent

            # Add the neighbors not explored yet to the list of vertices to visit
            # The others would be ignored when extracted anyway
            for neighbor in graph.get_neighbors(vertex):
                if neighbor not in distances:
                    distance_to_neighbor = distances[vertex] + graph.get_weight(vertex, neighbor)
                    vertices_to_visit.append((distance_to_neighbor, neighbor, vertex))
        
        # Return the result
        return distances, routing_table

    ##################################################################################

    def find_route ( self,
                     routing_table: dict[int, int | None],
                     source:        int,
                     target:        int
                   ) ->             list[int]:

        """
        This method finds the route from a source vertex to a target vertex using a routing table.

        Args:
            routing_table: The routing table, that is, the parent of each vertex in the traversal (None for the source).
            source:        The source vertex.
            target:        The target vertex.

        Returns:
            The route from the source to the target as a list of vertices.
        """

        # Initialization
        route = [target]
        vertex = target

        # Find the route
        while vertex != source:
            vertex = routing_table[vertex]
            route.append(vertex)
        
        # Reverse the route
        route.reverse()
        return route

##########################################################################################
##########################################################################################
##########################################################################################
########################################## INFO ##########################################
##########################################################################################

"""
This program is a solution to the practical session 2 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session2/practical/
"""

##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################

# External imports
import pprint

# PyRat imports
from pyrat import Game
from players.bfs import BFS

##########################################################################################
######################################### SCRIPT #########################################
##########################################################################################

if __name__ == "__main__":

    # Instantiate a game with a few arguments
    game_config = {"mud_percentage": 0.0,
                   "maze_width": 13,
                   "maze_height": 10,
                   "nb_cheese": 1,
                   "random_seed": 2,
                   "trace_length": 1000}

    # Instantiate a game with specified arguments
    game = Game(**game_config)

    # Instantiate the player
    player = BFS()
    game.add_player(player)

    # Start the game
    stats = game.start()
    pprint.pprint(stats)

##########################################################################################
##########################################################################################

Pour passer de DFS à BFS, il suffit de remplacer vertices_to_visit.pop() par vertices_to_visit.pop(0) dans la boucle de traversal(...). Ça revient à manipuler la liste comme une file au lieu d’une pile.

Concernant les tests, la plupart sont identiques (au nom près), car ils vérifient des propriétés communes à tous les parcours : types des sorties, visite de tous les sommets atteignables, table de routage formant un arbre couvrant, distances cohérentes avec la table de routage, gestion des erreurs, tests de find_route(...), etc. Seuls deux tests diffèrent :

  • test___dfs_traversal___random_mazes___is_depth_first devient test___bfs_traversal___random_mazes___is_breadth_first. Dans l’arbre construit par un DFS, chaque arête du labyrinthe relie un sommet à l’un de ses ancêtres. Dans l’arbre construit par un BFS, deux voisins dans le labyrinthe sont à des profondeurs qui diffèrent d’au plus 1, car le BFS explore tous les sommets à 1 déplacement de la source, puis tous ceux à 2 déplacements, etc. C’est ce test qui distingue vraiment les deux parcours : les autres passeraient avec n’importe quel parcours.

  • test___dfs_traversal___fixed_mazes___expected_outputs (et son équivalent bfs) : les sorties attendues sur le labyrinthe en forme de cycle (cycle_maze) ne sont pas les mêmes. Un DFS fait le tour du cycle (dans un sens ou dans l’autre), alors qu’un BFS atteint d’abord les deux voisins de la source, puis le sommet opposé. Sur le labyrinthe en forme d’arbre (tree_maze), il n’existe qu’un chemin vers chaque sommet, donc les sorties attendues sont les mêmes pour les deux parcours.

Comparer aux programmes aléatoires

Maintenant que vous avez deux nouveaux joueurs, il serait intéressant de les comparer avec les joueurs aléatoires que vous avez développés lors de la séance précédente.

À faire

Adaptez (et renommez pour quelque chose de plus pertinent) le script evaluate_random_players.py pour intégrer les joueurs DFS et BFS dans l’analyse.

Essayez également de répondre aux questions suivantes :

  • Le joueur DFS prend-il un nombre moyen de tours significativement plus petit que le meilleur programme RandomX que vous avez écrit ?
  • Le joueur BFS prend-il un nombre moyen de tours significativement plus petit que DFS ?
Correction
Cliquez ici pour afficher la correction.

Voici un script qui fait ça. Il reprend aussi les joueurs Random6 et Random7, vus dans les sections « Pour aller plus loin » et « Pour aller encore plus loin » de la séance 1 : retirez-les si vous ne les avez pas programmés.

​
##########################################################################################
########################################## INFO ##########################################
##########################################################################################

"""
This program is a solution to the practical session 2 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session2/practical/
"""

##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################

# External imports
import tqdm.auto as tqdm
import matplotlib.pyplot as pyplot
import scipy.stats as scstats

# PyRat imports
from pyrat import Game, GameMode
from players.random1 import Random1
from players.random2 import Random2
from players.random3 import Random3
from players.random4 import Random4
from players.random5 import Random5
from players.random6 import Random6
from players.random7 import Random7
from players.dfs import DFS
from players.bfs import BFS

##########################################################################################
######################################### SCRIPT #########################################
##########################################################################################

if __name__ == "__main__":

    # Determines how many games will be played for each player
    nb_games = 1000

    # Customize the game elements
    game_config = {"mud_percentage": 0.0,
                   "nb_cheese": 1,
                   "game_mode": GameMode.SIMULATION}

    # Run the games for each player class
    players = [Random1(), Random2(), Random3(), Random4(), Random5(), Random6(), Random7(), DFS(), BFS()]
    results = {player.get_name(): [] for player in players}
    for player in players:
        for seed in tqdm.tqdm(range(nb_games), desc=player.get_name()):

            # Make the game with given seed
            game = Game(random_seed=seed, **game_config)
            game.add_player(player)
            stats = game.start()

            # Store the number of turns needed
            results[player.get_name()].append(stats["turns"])

    # Visualization of cumulative curves of numbers of turns taken per program
    max_turn = max([max(results[player]) for player in results])
    pyplot.figure(figsize=(10, 5))
    for player in results:
        turns = [0] + sorted(results[player]) + [max_turn]
        games_completed_per_turn = [len([turn for turn in results[player] if turn <= t]) * 100.0 / nb_games for t in turns]
        pyplot.plot(turns, games_completed_per_turn, label=player)
    pyplot.title("Comparison of turns needed to complete all %d games" % (nb_games))
    pyplot.xlabel("Turns per game")
    pyplot.ylabel("% of games completed")
    pyplot.xscale("log")
    pyplot.legend()
    pyplot.savefig("evaluate_random_vs_traversals.png")

    # Formal statistics to check if these curves are statistically significant
    for i, player_1 in enumerate(results):
        for j, player_2 in enumerate(results):
            if j > i:
                test_result = scstats.mannwhitneyu(results[player_1], results[player_2], alternative="two-sided")
                print("Mann-Whitney U test between turns of program '%s' and of program '%s':" % (player_1, player_2), test_result)

##########################################################################################
##########################################################################################

Il produit le graphique suivant, et des tests de Mann-Whitney pour toutes les paires de joueurs (en voici un extrait) :

Mann-Whitney U test between turns of program 'Random1' and of program 'Random5':
MannwhitneyuResult(statistic=np.float64(905395.5), pvalue=np.float64(2.4406973722993484e-216))

Mann-Whitney U test between turns of program 'Random5' and of program 'Random6':
MannwhitneyuResult(statistic=np.float64(875418.5), pvalue=np.float64(6.51509326950569e-186))

Mann-Whitney U test between turns of program 'Random5' and of program 'DFS':
MannwhitneyuResult(statistic=np.float64(761807.0), pvalue=np.float64(2.1257094003632124e-91))

Mann-Whitney U test between turns of program 'Random5' and of program 'BFS':
MannwhitneyuResult(statistic=np.float64(933008.5), pvalue=np.float64(9.449817703430092e-247))

Mann-Whitney U test between turns of program 'Random6' and of program 'Random7':
MannwhitneyuResult(statistic=np.float64(468236.5), pvalue=np.float64(0.01379698799921949))

Mann-Whitney U test between turns of program 'Random6' and of program 'DFS':
MannwhitneyuResult(statistic=np.float64(190956.0), pvalue=np.float64(1.1796295134455544e-126))

Mann-Whitney U test between turns of program 'Random6' and of program 'BFS':
MannwhitneyuResult(statistic=np.float64(597334.0), pvalue=np.float64(4.289618050994497e-14))

Mann-Whitney U test between turns of program 'Random7' and of program 'DFS':
MannwhitneyuResult(statistic=np.float64(217508.0), pvalue=np.float64(3.840436997512759e-106))

Mann-Whitney U test between turns of program 'Random7' and of program 'BFS':
MannwhitneyuResult(statistic=np.float64(632093.0), pvalue=np.float64(1.2222777727493456e-24))

Mann-Whitney U test between turns of program 'DFS' and of program 'BFS':
MannwhitneyuResult(statistic=np.float64(917496.5), pvalue=np.float64(1.4132231344750687e-229))

Du coup pour la première question :

  • Si on compare à Random5 (le meilleur de la partie obligatoire), DFS est significativement meilleur en moyenne.

  • Si on compare à Random6-7, on a bien une différence significative, et on observe que Random6-7 est meilleur en général, mais il lui faut beaucoup de tours sur quelques labyrinthes, alors que DFS n’a jamais de partie très longue.

  • On pourrait utiliser la même heuristique que Random6 et trier les sommets à explorer pour DFS. Il est très probable que ça améliore les résultats.

Et pour la seconde question :

  • Oui, et on a la garantie d’avoir un chemin le plus court pour un graphe non pondéré.

Factoriser les codes

Similarités et différences entre DFS et BFS

Comme vous l’avez peut-être remarqué, les codes de BFS et DFS sont extrêmement similaires. En fait, c’est la structure de données utilisée qui détermine l’ordre dans lequel les sommets sont explorés. En effet, avec une file (FIFO), le parcours effectue une recherche en largeur. Avec une pile (LIFO), le parcours effectue une recherche en profondeur.

Ainsi, de manière générale, un parcours peut être vu comme un algorithme global qui, à un moment donné, doit :

  • Créer une structure de données.
  • Ajouter un élément à la structure de données.
  • Extraire un élément de la structure de données.
  • Savoir si la structure de données est vide, pour arrêter le parcours.

Par ailleurs, la notion de parcours n’a pas vraiment sa place dans un joueur. Un parcours est un algorithme sur un graphe : il ne sait rien des fromages ou des tours de jeu, et pourrait servir dans bien d’autres contextes (dans d’autres joueurs, pour analyser un labyrinthe, etc.). Le rôle d’un joueur est de décider quoi faire à chaque tour. Il peut s’appuyer sur un parcours pour ça, mais il n’a pas besoin de savoir comment ce parcours fonctionne.

Il est donc plus pertinent de définir une classe de parcours à part, qui regroupe tout ce qui est commun aux parcours, et de la spécialiser selon la stratégie d’exploration souhaitée. Le paradigme de la programmation orientée objet (POO) rend cela pratique grâce à l’héritage. L’idée est de créer une classe de base qui factorise le code commun, et des sous-classes qui spécialisent les particularités. Le joueur, de son côté, n’a plus qu’à créer le parcours qui l’intéresse et à s’en servir.

Dans la suite de cette activité, nous allons mettre en place cette réorganisation ensemble. Schématiquement, elle correspond au diagramme suivant (si vous avez effectué la factorisation demandée en fin de séance 1, le diagramme pourra être un peu différent pour vous) :

Diagramme de classes UML des parcours et du joueur TraversalPlayer Diagramme de classes UML des parcours et du joueur TraversalPlayer

Le diagramme ci-dessus est ce que l’on appelle un diagramme de classes UML. Voici comment le lire :

  • On a cinq classes : Player, fournie par la bibliothèque PyRat (en orange), et TraversalPlayer, Traversal, BFSTraversal et DFSTraversal, qui font partie de votre workspace (en vert). Les cadres indiquent où se trouve chaque classe : players et utils/traversal sont des sous-dossiers de votre workspace.

  • Chaque boîte est une classe, avec trois compartiments : son nom, ses attributs, et ses méthodes.

  • Traversal, écrit en italique et marqué «abstract», est une classe abstraite, ce qui signifie qu’on ne peut pas l’instancier (cela n’aurait pas de sens de le faire, car elle ne définit aucune stratégie de parcours). Elle sert uniquement à abstraire la notion de parcours d’un graphe et regroupe les aspects communs à tous les algorithmes. En Python, une classe abstraite est une classe qui hérite de abc.ABC (Abstract Base Class).

  • La classe Traversal possède deux attributs : routing_table et distances. Ces attributs doivent être déclarés dans le constructeur de Traversal. La valeur de routing_table et distances est définie par la méthode traversal(...), et on peut la lire avec les méthodes get_routing_table(...) et get_distances(...). Le + devant chaque attribut et méthode indique qu’il est public, c’est-à-dire qu’on peut l’utiliser depuis l’extérieur de la classe (par exemple bfs.find_route(...)). À l’inverse, le - indique qu’il est privé, c’est-à-dire réservé à la classe elle-même (par exemple, seul TraversalPlayer manipule sa liste actions). Le # indique qu’il est protégé, c’est-à-dire réservé à la classe et à ses classes enfants.

  • La classe Traversal possède huit méthodes : get_distances(...), get_routing_table(...), traversal(...), find_route(...), initialize_structure(...), add_to_structure(...), get_from_structure(...) et is_structure_empty(...). Les quatre dernières sont en italique, ce qui signifie qu’elles sont abstraites, c’est-à-dire qu’elles ne font rien et doivent être implémentées dans les classes enfants. On les déclare quand même dans la classe Traversal car cela permet de fixer leur signature, c’est-à-dire le nombre et le type de leurs arguments, et leur type de retour. En Python, on déclare une méthode abstraite en utilisant le décorateur @abc.abstractmethod juste avant la déclaration de la méthode.

  • Une ligne terminée par un triangle creux est un héritage : les classes BFSTraversal et DFSTraversal héritent de Traversal. Elles héritent donc des attributs et méthodes définis dans Traversal, et peuvent utiliser ceux qui sont publics ou protégés. Contrairement à Traversal, elles sont instanciables.

  • Ces deux classes redéfinissent les méthodes abstraites de Traversal pour les rendre utilisables. Chacune range comme elle le souhaite la structure de données qui stocke les sommets à explorer, dans son propre attribut : une file queue pour BFSTraversal, et une pile stack pour DFSTraversal. Traversal n’a pas besoin de connaître cette structure : elle la manipule uniquement au travers de ces méthodes.

  • De la même manière, TraversalPlayer hérite de Player, comme tous les joueurs que vous avez écrits jusqu’ici.

  • La ligne avec un losange creux est une agrégation : TraversalPlayer utilise un objet Traversal, qu’il reçoit à sa création et range dans son attribut traversal_algorithm, par exemple TraversalPlayer(BFSTraversal()). Le 1 indique qu’il en utilise exactement un. Contrairement à une composition (losange plein), le joueur ne crée pas lui-même l’objet qu’il utilise : c’est le code qui crée le joueur qui choisit le parcours. Le joueur fonctionne ainsi avec n’importe quelle sous-classe de Traversal, y compris celles que vous écrirez plus tard, sans avoir à être modifié. Si aucun parcours n’est donné, il crée un BFSTraversal. Attention : chaque joueur doit recevoir son propre objet, car un parcours garde les résultats de son dernier appel.

  • Dans cette nouvelle organisation, routing_table et distances sont des attributs de Traversal, et non plus des variables de retour de la méthode traversal(...). L’objectif de ce changement est d’encapsuler la manière dont le résultat du parcours est stocké et manipulé, et de fournir à l’utilisateur de la classe Traversal une interface plus logique. Par exemple, on avait préalablement ce code, qui donnait à l’utilisateur la responsabilité de passer la table de routage comme argument de la fonction find_route(...) :

    distances, routing_table = self.traversal(maze, my_location)
    path = self.find_route(routing_table, my_location, game_state.cheese[0])

    On peut à présent cacher cette étape intermédiaire, de sorte que l’utilisateur n’ait qu’à faire :

    self.traversal_algorithm.traversal(maze, my_location)
    path = self.traversal_algorithm.find_route(game_state.cheese[0])

Implémentation

Construisons maintenant cette réorganisation ensemble ! Nous vous fournissons les fichiers correspondant aux classes du diagramme, et vous n’aurez qu’à compléter la classe Traversal.

À faire

Commencez par créer les fichiers nécessaires dans votre workspace PyRat, comme indiqué ci-dessous.

  • Tout d’abord, créez un nouveau sous-dossier utils (c’est un nom standard en programmation pour désigner une boîte à outils), et dans celui-ci, un sous-dossier traversal. Le dossier utils accueillera au fil des séances d’autres sous-dossiers (utils/tsp, utils/greedy…), un par thème : regrouper les fichiers par thème permet de s’y retrouver quand leur nombre augmente.

  • Créez les fichiers suivants dans votre workspace PyRat, en copiant-collant le code de l’onglet correspondant ci-dessous :

​
##########################################################################################
########################################## INFO ##########################################
##########################################################################################

"""
This program is provided during session 2 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session2/practical/
"""

##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################

# External imports
import abc

# PyRat imports
from pyrat import Graph

##########################################################################################
######################################### CLASSES ########################################
##########################################################################################

class Traversal (abc.ABC):

    """
    This is an abstract class that defines the interface for graph traversal algorithms.
    It is meant to be inherited by specific traversal algorithm implementations, such as breadth-first search (BFS) or depth-first search (DFS).
    
    Each subclass chooses the data structure that stores the vertices to visit, and keeps it as it wishes.
    The traversal only manipulates it through four abstract methods that must be implemented in the subclasses:
        * ``initialize_structure``: Initializes the data structure needed for the traversal.
        * ``add_to_structure``: Adds an element to the data structure.
        * ``get_from_structure``: Extracts an element from the data structure.
        * ``is_structure_empty``: Indicates whether the data structure is empty.
    The choice of data structure (e.g., queue, stack) will determine the behavior of the traversal algorithm.
    """

    ##################################################################################
    #                                   CONSTRUCTOR                                  #
    ##################################################################################

    def __init__ ( self,
                   *args:    object,
                   **kwargs: object
                 ) ->        None:

        """
        *(This class is abstract and meant to be subclassed, not instantiated directly).*

        Initializes a new instance of the class.

        Args:
            args:   Arguments to pass to the parent constructor.
            kwargs: Keyword arguments to pass to the parent constructor.
        """
        
        # Inherit from parent class
        super().__init__(*args, **kwargs)

        # Calling traversal will set these attributes
        self.routing_table = None
        self.distances = None

    ##################################################################################
    #                                     METHODS                                    #
    ##################################################################################

    def get_distances (self) -> dict[int, int]:

        """
        This method returns the distances computed by the last traversal.

        Returns:
            The distance from the source to each vertex explored, as a dictionary.
        """

        # Return the distances found
        return self.distances

    ##################################################################################

    def get_routing_table (self) -> dict[int, int | None]:

        """
        This method returns the routing table computed by the last traversal.

        Returns:
            The parent of each vertex explored, as a dictionary (None for the source).
        """

        # Return the routing table found
        return self.routing_table

    ##################################################################################

    def traversal ( self,
                    graph:  Graph,
                    source: int
                  ) ->      None:

        """
        This method performs a traversal of the given graph from the given source vertex.
        It computes the distances from the source to all other vertices, as well as a routing table that can be used to reconstruct paths.
        The distance to a vertex is the sum of the weights of the edges along the path found (given by ``graph.get_weight(...)``).
        The results are stored in the ``distances`` and ``routing_table`` attributes.
        
        Args:
            graph:  The graph to traverse.
            source: The source vertex of the traversal (we type it as int here because we will only manipulate mazes, but Graph uses Hashable as a more generic type).
        """

        # Initialization
        self.distances = {}
        self.routing_table = {}

        # Complete the method here
        # Use methods `self.initialize_structure()`, `self.add_to_structure(...)`, `self.get_from_structure()` and `self.is_structure_empty()` to manage the data structure, which each subclass stores as it wishes

    ##################################################################################

    def find_route ( self,
                     target: int
                   ) ->      list[int]:

        """
        This method finds the route from the source vertex to a target vertex using a routing table.

        Args:
            target: The target vertex.

        Returns:
            The route from the source to the target as a list of vertices.

        Raises:
            RuntimeError: If no traversal has been performed yet.
            ValueError: If the target was not reached by the last traversal (e.g., it is in another component of the graph).
        """

        # A route can only be found from the results of a traversal
        if self.routing_table is None:
            raise RuntimeError(f"Cannot find a route to {target!r}: no traversal has been performed yet")

        # The target must have been reached by the traversal
        if target not in self.routing_table:
            raise ValueError(f"Cannot find a route to {target!r}: it was not reached by the last traversal")

        # Your code here
        # Use the `self.routing_table` attribute to find the route from the source (vertex with parent None) to the target

    ##################################################################################

    @abc.abstractmethod
    def initialize_structure (self) -> None:

        """
        *(This method is abstract and must be implemented in the subclasses).*

        It initializes the data structure needed for the traversal.

        Raises:
            NotImplementedError: If called through ``super()``, as a subclass that does not redefine this method cannot be instantiated.
        """

        # This method must be implemented in the child classes
        # By default we raise an error
        raise NotImplementedError(f"{type(self).__name__} must redefine method 'initialize_structure' of Traversal")

    ##################################################################################

    @abc.abstractmethod
    def add_to_structure ( self,
                           element: object
                         ) ->       None:

        """
        *(This method is abstract and must be implemented in the subclasses).*

        It adds an element to the data structure.

        Args:
            element: The element to add, as a tuple (distance, vertex, parent).

        Raises:
            NotImplementedError: If called through ``super()``, as a subclass that does not redefine this method cannot be instantiated.
        """

        # This method must be implemented in the child classes
        # By default we raise an error
        raise NotImplementedError(f"{type(self).__name__} must redefine method 'add_to_structure' of Traversal")

    ##################################################################################

    @abc.abstractmethod
    def get_from_structure (self) -> object:

        """
        *(This method is abstract and must be implemented in the subclasses).*

        It extracts an element from the data structure.

        Returns:
            The extracted element, as a tuple (distance, vertex, parent).

        Raises:
            NotImplementedError: If called through ``super()``, as a subclass that does not redefine this method cannot be instantiated.
        """

        # This method must be implemented in the child classes
        # By default we raise an error
        raise NotImplementedError(f"{type(self).__name__} must redefine method 'get_from_structure' of Traversal")

    ##################################################################################

    @abc.abstractmethod
    def is_structure_empty (self) -> bool:

        """
        *(This method is abstract and must be implemented in the subclasses).*

        It indicates whether the data structure contains no more elements to extract.

        Returns:
            True if the data structure is empty, False otherwise.

        Raises:
            NotImplementedError: If called through ``super()``, as a subclass that does not redefine this method cannot be instantiated.
        """

        # This method must be implemented in the child classes
        # By default we raise an error
        raise NotImplementedError(f"{type(self).__name__} must redefine method 'is_structure_empty' of Traversal")

##########################################################################################
##########################################################################################
##########################################################################################
########################################## INFO ##########################################
##########################################################################################

"""
This program is provided during session 2 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session2/practical/
"""

##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################

# PyRat imports
from utils.traversal.traversal import Traversal

##########################################################################################
######################################### CLASSES ########################################
##########################################################################################

class BFSTraversal (Traversal):

    """
    This class implements a breadth-first search (BFS) traversal algorithm by defining the abstract methods from the parent class.
    We use a FIFO queue to indicate the order in which vertices should be explored.
    """

    ##################################################################################
    #                                   CONSTRUCTOR                                  #
    ##################################################################################

    def __init__ ( self,
                   *args:    object,
                   **kwargs: object
                 ) ->        None:

        """
        *(This class inherits from* ``Traversal`` *).*

        It implements a breadth-first search (BFS) traversal algorithm by defining the abstract methods from the parent class.
        We use a FIFO queue to indicate the order in which vertices should be explored.

        Args:
            args:   Arguments to pass to the parent constructor.
            kwargs: Keyword arguments to pass to the parent constructor.
        """
        
        # Inherit from parent class
        super().__init__(*args, **kwargs)

        # FIFO queue of the elements to visit, as a list, created by initialize_structure
        self.queue = None

    ##################################################################################
    #                                     METHODS                                    #
    ##################################################################################

    def initialize_structure (self) -> None:

        """
        *(This method redefines the method of the parent class with the same name).*

        It initializes the data structure needed for the traversal, and stores it in the ``queue`` attribute.
        Here, we use a list to implement a FIFO queue.
        """

        # We start with an empty list
        self.queue = []

    ##################################################################################

    def add_to_structure ( self,
                           element: object
                         ) ->       None:

        """
        *(This method redefines the method of the parent class with the same name).*

        It adds an element to the data structure stored in the ``queue`` attribute.
        Here, we append the element to the end of the list to implement a FIFO queue.

        Args:
            element: The element to add, as a tuple (distance, vertex, parent).
        """

        # We append the element to the end of the list
        self.queue.append(element)

    ##################################################################################

    def get_from_structure (self) -> object:

        """
        *(This method redefines the method of the parent class with the same name).*

        It extracts an element from the data structure stored in the ``queue`` attribute.
        Here, we remove and return the first element of the list to implement a FIFO queue.

        Returns:
            The extracted element, as a tuple (distance, vertex, parent).
        """

        # We remove and return the first element of the list
        return self.queue.pop(0)

    ##################################################################################

    def is_structure_empty (self) -> bool:

        """
        *(This method redefines the method of the parent class with the same name).*

        It indicates whether the data structure stored in the ``queue`` attribute contains no more elements to extract.
        Here, the FIFO queue is empty when the list has no element.

        Returns:
            True if the data structure is empty, False otherwise.
        """

        # The queue is empty when the list has no element
        return len(self.queue) == 0

##########################################################################################
##########################################################################################
##########################################################################################
########################################## INFO ##########################################
##########################################################################################

"""
This program is provided during session 2 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session2/practical/
"""

##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################

# PyRat imports
from utils.traversal.traversal import Traversal

##########################################################################################
######################################### CLASSES ########################################
##########################################################################################

class DFSTraversal (Traversal):

    """
    This class implements a depth-first search (DFS) traversal algorithm by defining the abstract methods from the parent class.
    We use a LIFO stack to indicate the order in which vertices should be explored.
    """

    ##################################################################################
    #                                   CONSTRUCTOR                                  #
    ##################################################################################

    def __init__ ( self,
                   *args:    object,
                   **kwargs: object
                 ) ->        None:

        """
        *(This class inherits from* ``Traversal`` *).*

        It implements a depth-first search (DFS) traversal algorithm by defining the abstract methods from the parent class.
        We use a LIFO stack to indicate the order in which vertices should be explored.

        Args:
            args:   Arguments to pass to the parent constructor.
            kwargs: Keyword arguments to pass to the parent constructor.
        """
        
        # Inherit from parent class
        super().__init__(*args, **kwargs)

        # LIFO stack of the elements to visit, as a list, created by initialize_structure
        self.stack = None

    ##################################################################################
    #                                     METHODS                                    #
    ##################################################################################

    def initialize_structure (self) -> None:

        """
        *(This method redefines the method of the parent class with the same name).*

        It initializes the data structure needed for the traversal, and stores it in the ``stack`` attribute.
        Here, we use a list to implement a LIFO stack.
        """

        # We start with an empty list
        self.stack = []

    ##################################################################################

    def add_to_structure ( self,
                           element: object
                         ) ->       None:

        """
        *(This method redefines the method of the parent class with the same name).*

        It adds an element to the data structure stored in the ``stack`` attribute.
        Here, we append the element to the end of the list to implement a LIFO stack.

        Args:
            element: The element to add, as a tuple (distance, vertex, parent).
        """

        # We append the element to the end of the list
        self.stack.append(element)

    ##################################################################################

    def get_from_structure (self) -> object:

        """
        *(This method redefines the method of the parent class with the same name).*

        It extracts an element from the data structure stored in the ``stack`` attribute.
        Here, we remove and return the last element of the list to implement a LIFO stack.

        Returns:
            The extracted element, as a tuple (distance, vertex, parent).
        """

        # We remove and return the last element of the list
        return self.stack.pop()

    ##################################################################################

    def is_structure_empty (self) -> bool:

        """
        *(This method redefines the method of the parent class with the same name).*

        It indicates whether the data structure stored in the ``stack`` attribute contains no more elements to extract.
        Here, the LIFO stack is empty when the list has no element.

        Returns:
            True if the data structure is empty, False otherwise.
        """

        # The stack is empty when the list has no element
        return len(self.stack) == 0

##########################################################################################
##########################################################################################
##########################################################################################
########################################## INFO ##########################################
##########################################################################################

"""
This program is provided during session 2 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session2/practical/
"""

##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################

# PyRat imports
from pyrat import Player, Maze, GameState, Action
from utils.traversal.traversal import Traversal
from utils.traversal.bfs_traversal import BFSTraversal

##########################################################################################
######################################### CLASSES ########################################
##########################################################################################

class TraversalPlayer (Player):

    """
    *(This class inherits from* ``Player`` *).*

    This player controls a PyRat character that explores the maze using a graph traversal algorithm.
    The traversal algorithm is given at creation, as an object of a subclass of ``Traversal`` (e.g., ``BFSTraversal()``).
    """

    ##################################################################################
    #                                   CONSTRUCTOR                                  #
    ##################################################################################

    def __init__ ( self,
                   traversal_algorithm: Traversal | None = None,
                   *args:               object,
                   **kwargs:            object
                 ) ->                   None:

        """
        Initializes a new instance of the class.
        Here, the constructor is only used to initialize the player.
        It transmits the arguments to the parent constructor, which is responsible for initializing the name and the skin of the player.

        Args:
            traversal_algorithm: The traversal algorithm to use, as an object of a subclass of ``Traversal`` (default is a new ``BFSTraversal``).
                                 Each player needs its own object, as it stores the results of the last traversal.
            args:                Arguments to pass to the parent constructor.
            kwargs:              Keyword arguments to pass to the parent constructor.
        """

        # Inherit from parent class
        super().__init__(*args, **kwargs)

        # We create an attribute to store the actions to perform
        self.actions = None

        # We store the chosen traversal algorithm, or create the default one
        self.traversal_algorithm = traversal_algorithm if traversal_algorithm is not None else BFSTraversal()

    ##################################################################################
    #                                  PYRAT METHODS                                 #
    ##################################################################################

    def preprocessing ( self,
                        maze:       Maze,
                        game_state: GameState,
                      ) ->          None:
        
        """
        *(This method redefines the method of the parent class with the same name).*

        This method is called once at the beginning of the game.
        Here, we use the traversal algorithm to compute a path that reaches the piece of cheese from the initial position of the player.

        Args:
            maze:       An object representing the maze in which the player plays.
            game_state: An object representing the state of the game.
        """

        # We perform a traversal of the maze graph from the initial position of the player
        my_location = game_state.player_locations[self.get_name()]
        self.traversal_algorithm.traversal(maze, my_location)

        # Find the series of locations/actions to go from the player location to the first piece of cheese
        path = self.traversal_algorithm.find_route(game_state.cheese[0])
        self.actions = maze.locations_to_actions(path)

    ##################################################################################

    def turn ( self,
               maze:       Maze,
               game_state: GameState,
             ) ->          Action:

        """
        *(This method redefines the method of the parent class with the same name).*

        It is called at each turn of the game.
        It returns an action to perform among the possible actions, defined in the ``Action`` enumeration.

        Args:
            maze:       An object representing the maze in which the player plays.
            game_state: An object representing the state of the game.
        
        Returns:
            One of the possible actions.
        """

        # At each turn, we perform the next action in the list of actions
        return self.actions.pop(0)

##########################################################################################
##########################################################################################
##########################################################################################
########################################## INFO ##########################################
##########################################################################################

"""
This program is provided during session 2 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session2/practical/
"""

##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################

# External imports
import pprint

# PyRat imports
from pyrat import Game
from players.traversal_player import TraversalPlayer
from utils.traversal.bfs_traversal import BFSTraversal

##########################################################################################
######################################### SCRIPT #########################################
##########################################################################################

if __name__ == "__main__":

    # Instantiate a game with a few arguments
    game_config = {"mud_percentage": 0.0,
                   "maze_width": 13,
                   "maze_height": 10,
                   "nb_cheese": 1,
                   "random_seed": 2,
                   "trace_length": 1000}

    # Instantiate a game with specified arguments
    game = Game(**game_config)

    # Instantiate the player
    player = TraversalPlayer(BFSTraversal(), name="Factorized BFS")
    game.add_player(player)

    # Start the game
    stats = game.start()
    pprint.pprint(stats)

##########################################################################################
##########################################################################################
##########################################################################################
########################################## INFO ##########################################
##########################################################################################

"""
This program is provided during session 2 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session2/practical/
"""

##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################

# External imports
import pprint

# PyRat imports
from pyrat import Game
from players.traversal_player import TraversalPlayer
from utils.traversal.dfs_traversal import DFSTraversal

##########################################################################################
######################################### SCRIPT #########################################
##########################################################################################

if __name__ == "__main__":

    # Instantiate a game with a few arguments
    game_config = {"mud_percentage": 0.0,
                   "maze_width": 13,
                   "maze_height": 10,
                   "nb_cheese": 1,
                   "random_seed": 2,
                   "trace_length": 1000}

    # Instantiate a game with specified arguments
    game = Game(**game_config)

    # Instantiate the player
    player = TraversalPlayer(DFSTraversal(), name="Factorized DFS")
    game.add_player(player)

    # Start the game
    stats = game.start()
    pprint.pprint(stats)

##########################################################################################
##########################################################################################
À faire

Complétez les parties manquantes dans traversal.py, en vous inspirant de ce que vous avez fait précédemment lors de l’activité pratique.

Les fichiers bfs_traversal.py et dfs_traversal.py sont déjà fonctionnels. Regardez-les pour comprendre leurs différences.

Une fois terminé, lancez les scripts visualize_factorized_bfs.py et visualize_factorized_dfs.py (par exemple avec uv run games/visualize_factorized_bfs.py) pour exécuter des parties avec le nouveau joueur.

Correction
Cliquez ici pour afficher la correction.

Le fichier final devrait ressembler à ça. La correction intègre également l’arrêt prématuré du parcours (paramètre optionnel stop_vertices de traversal(...), qui renvoie alors le sommet d’arrêt trouvé), qui sera demandé dans la section « Arrêter l’algorithme de parcours plus tôt » plus bas :

​
##########################################################################################
########################################## INFO ##########################################
##########################################################################################

"""
This program is a solution to the practical session 2 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session2/practical/
"""

##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################

# External imports
import abc

# PyRat imports
from pyrat import Graph

##########################################################################################
######################################### CLASSES ########################################
##########################################################################################

class Traversal (abc.ABC):

    """
    This is an abstract class that defines the interface for graph traversal algorithms.
    It is meant to be inherited by specific traversal algorithm implementations, such as breadth-first search (BFS) or depth-first search (DFS).
    
    Each subclass chooses the data structure that stores the vertices to visit, and keeps it as it wishes.
    The traversal only manipulates it through four abstract methods that must be implemented in the subclasses:
        * ``initialize_structure``: Initializes the data structure needed for the traversal.
        * ``add_to_structure``: Adds an element to the data structure.
        * ``get_from_structure``: Extracts an element from the data structure.
        * ``is_structure_empty``: Indicates whether the data structure is empty.
    The choice of data structure (e.g., queue, stack) will determine the behavior of the traversal algorithm.
    """

    ##################################################################################
    #                                   CONSTRUCTOR                                  #
    ##################################################################################

    def __init__ ( self,
                   *args:    object,
                   **kwargs: object
                 ) ->        None:

        """
        *(This class is abstract and meant to be subclassed, not instantiated directly).*

        Initializes a new instance of the class.

        Args:
            args:   Arguments to pass to the parent constructor.
            kwargs: Keyword arguments to pass to the parent constructor.
        """
        
        # Inherit from parent class
        super().__init__(*args, **kwargs)

        # Calling traversal will set these attributes
        self.routing_table = None
        self.distances = None

    ##################################################################################
    #                                     METHODS                                    #
    ##################################################################################

    def get_distances (self) -> dict[int, int]:

        """
        This method returns the distances computed by the last traversal.

        Returns:
            The distance from the source to each vertex explored, as a dictionary.
        """

        # Return the distances found
        return self.distances

    ##################################################################################

    def get_routing_table (self) -> dict[int, int | None]:

        """
        This method returns the routing table computed by the last traversal.

        Returns:
            The parent of each vertex explored, as a dictionary (None for the source).
        """

        # Return the routing table found
        return self.routing_table

    ##################################################################################

    def traversal ( self,
                    graph:         Graph,
                    source:        int,
                    stop_vertices: set[int] | list[int] | None = None
                  ) ->             int | None:

        """
        This method performs a traversal of the given graph from the given source vertex.
        It computes the distances from the source to all other vertices, as well as a routing table that can be used to reconstruct paths.
        The distance to a vertex is the sum of the weights of the edges along the path found (given by ``graph.get_weight(...)``).
        The results are stored in the ``distances`` and ``routing_table`` attributes.
        
        Args:
            graph:         The graph to traverse.
            source:        The source vertex of the traversal (we type it as int here because we will only manipulate mazes, but Graph uses Hashable as a more generic type).
            stop_vertices: A set or list of vertices at which to stop the traversal (default is None, meaning the traversal will visit all reachable vertices).

        Returns:
            The stop vertex at which the traversal stopped, or None if it did not stop early (no stop vertex given, or none reachable).
        """

        # Work with sets for efficiency
        # We also allow lists as input for convenience
        stop_vertices = set(stop_vertices) if stop_vertices is not None else set()

        # Initialization
        self.distances = {}
        self.routing_table = {}

        # Initialize the structure of vertices to visit
        self.initialize_structure()
        self.add_to_structure((0, source, None))

        # Traversal
        while not self.is_structure_empty():

            # Get the next vertex to visit
            distance, vertex, parent = self.get_from_structure()

            # Skip if already visited
            # This can happen if a vertex was added multiple times to the list by different neighbors
            if vertex in self.distances:
                continue

            # Update the distances and routing table
            self.distances[vertex] = distance
            self.routing_table[vertex] = parent

            # Stop if we reached a stop vertex, and tell which one it is
            if vertex in stop_vertices:
                return vertex

            # Add the neighbors not explored yet to the list of vertices to visit
            # The others would be ignored when extracted anyway
            for neighbor in graph.get_neighbors(vertex):
                if neighbor not in self.distances:
                    distance_to_neighbor = self.distances[vertex] + graph.get_weight(vertex, neighbor)
                    self.add_to_structure((distance_to_neighbor, neighbor, vertex))

        # No stop vertex was reached
        return None

    ##################################################################################

    def find_route ( self,
                     target: int
                   ) ->      list[int]:

        """
        This method finds the route from the source vertex to a target vertex using a routing table.

        Args:
            target: The target vertex.

        Returns:
            The route from the source to the target as a list of vertices.

        Raises:
            RuntimeError: If no traversal has been performed yet.
            ValueError: If the target was not reached by the last traversal (e.g., it is in another component of the graph, or it was not explored before an early stop).
        """

        # A route can only be found from the results of a traversal
        if self.routing_table is None:
            raise RuntimeError(f"Cannot find a route to {target!r}: no traversal has been performed yet")

        # The target must have been reached by the traversal
        if target not in self.routing_table:
            raise ValueError(f"Cannot find a route to {target!r}: it was not reached by the last traversal")

        # Initialization
        route = [target]
        vertex = target

        # Find the route
        while self.routing_table[vertex] is not None:
            vertex = self.routing_table[vertex]
            route.append(vertex)
        
        # Reverse the route
        route.reverse()
        return route

    ##################################################################################

    @abc.abstractmethod
    def initialize_structure (self) -> None:

        """
        *(This method is abstract and must be implemented in the subclasses).*

        It initializes the data structure needed for the traversal.

        Raises:
            NotImplementedError: If called through ``super()``, as a subclass that does not redefine this method cannot be instantiated.
        """

        # This method must be implemented in the child classes
        # By default we raise an error
        raise NotImplementedError(f"{type(self).__name__} must redefine method 'initialize_structure' of Traversal")

    ##################################################################################

    @abc.abstractmethod
    def add_to_structure ( self,
                           element: object
                         ) ->       None:

        """
        *(This method is abstract and must be implemented in the subclasses).*

        It adds an element to the data structure.

        Args:
            element: The element to add, as a tuple (distance, vertex, parent).

        Raises:
            NotImplementedError: If called through ``super()``, as a subclass that does not redefine this method cannot be instantiated.
        """

        # This method must be implemented in the child classes
        # By default we raise an error
        raise NotImplementedError(f"{type(self).__name__} must redefine method 'add_to_structure' of Traversal")

    ##################################################################################

    @abc.abstractmethod
    def get_from_structure (self) -> object:

        """
        *(This method is abstract and must be implemented in the subclasses).*

        It extracts an element from the data structure.

        Returns:
            The extracted element, as a tuple (distance, vertex, parent).

        Raises:
            NotImplementedError: If called through ``super()``, as a subclass that does not redefine this method cannot be instantiated.
        """

        # This method must be implemented in the child classes
        # By default we raise an error
        raise NotImplementedError(f"{type(self).__name__} must redefine method 'get_from_structure' of Traversal")

    ##################################################################################

    @abc.abstractmethod
    def is_structure_empty (self) -> bool:

        """
        *(This method is abstract and must be implemented in the subclasses).*

        It indicates whether the data structure contains no more elements to extract.

        Returns:
            True if the data structure is empty, False otherwise.

        Raises:
            NotImplementedError: If called through ``super()``, as a subclass that does not redefine this method cannot be instantiated.
        """

        # This method must be implemented in the child classes
        # By default we raise an error
        raise NotImplementedError(f"{type(self).__name__} must redefine method 'is_structure_empty' of Traversal")

##########################################################################################
##########################################################################################

Tests

Les fichiers tests/test_bfs.py et tests/test_dfs.py testent les joueurs BFS et DFS, et ne s’appliquent pas directement aux classes BFSTraversal et DFSTraversal. En effet, l’interface a changé : traversal(...) ne renvoie plus les distances et la table de routage, mais les stocke dans les attributs distances et routing_table (que l’on lit avec get_distances(...) et get_routing_table(...)), et find_route(...) ne prend plus que la cible en argument.

À faire

Adaptez tests/test_bfs.py et tests/test_dfs.py pour tester BFSTraversal et DFSTraversal (par exemple dans des fichiers tests/test_bfs_traversal.py et tests/test_dfs_traversal.py).

Correction
Cliquez ici pour afficher la correction.

La correction de la séance 3 contient un fichier tests/test_dijkstra_traversal.py organisé de cette manière (visible une fois les corrections de cette séance publiées). Vous pourrez en reprendre la structure :

  • setUp(...) instancie un objet de parcours (self.traversal_algorithm = DijkstraTraversal()) au lieu d’un joueur.

  • Une méthode utilitaire traverse(...) appelle traversal(...), puis renvoie les distances et la table de routage obtenues avec get_distances(...) et get_routing_table(...). Elle transmet aussi l’argument stop_vertices de l’arrêt prématuré, demandé dans la section « Arrêter l’algorithme de parcours plus tôt » plus bas : retirez-le si vous ne l’avez pas fait. Les tests de traversal(...) restent ainsi presque identiques : il suffit de remplacer self.player.traversal(...) par self.traverse(...).

  • Les tests de find_route(...) effectuent d’abord un parcours, puis appellent find_route(target). Les tests qui portaient sur l’argument source n’ont plus lieu d’être, et on peut en ajouter un pour vérifier qu’appeler find_route(...) avant tout parcours lève une erreur.

Pour aller plus loin

Arrêter l’algorithme de parcours plus tôt

Pour calculer les informations nécessaires pour se déplacer vers le morceau de fromage, il suffit uniquement de savoir où se trouve ce fromage. Cependant, le BFS et le DFS sont des algorithmes qui explorent le graphe jusqu’à ce que tous les sommets soient visités.

Dans notre cas, tous les calculs effectués après avoir trouvé ce morceau de fromage sont inutiles, car vous n’allez pas utiliser ces résultats. Une amélioration possible consiste donc à modifier l’algorithme de parcours pour qu’il s’arrête dès que toutes les informations nécessaires sont disponibles.

À faire

Adaptez votre algorithme de parcours (dans la version de base ou la version factorisée) pour fournir à traversal(...) une liste de sommets à trouver, sous la forme d’un paramètre optionnel. L’algorithme s’arrêtera quand un de ces sommets est visité, et renverra ce sommet (ou None si aucun ne l’a été).

En effet, le sommet trouvé n’est pas forcément le premier de la liste, et le joueur doit savoir vers lequel se diriger : les autres n’ont peut-être pas été explorés. Dans la version factorisée, c’est la seule valeur renvoyée par traversal(...). Dans la version de base, ajoutez-le aux valeurs déjà renvoyées (distances et table de routage).

Est-ce plus performant en temps de calcul que de tout explorer ? Comment pourriez-vous vérifier ça ?

Correction
Cliquez ici pour afficher la correction.

Le code de traversal.py dans le fichier plus haut intègre cette fonctionnalité. La méthode traversal(...) prend un paramètre optionnel stop_vertices : elle s’arrête dès qu’un de ces sommets est exploré, et renvoie celui qui a été trouvé (ou None si aucun ne l’a été). TraversalPlayer se dirige ensuite vers ce sommet, qui n’est pas forcément le premier de la liste.

Cela sera en effet plus efficace si une des cases cibles est trouvée proche du départ. Dans le pire des cas, l’algorithme explorera tout le graphe, et il n’y aura aucun impact.

Pour le vérifier, on peut mesurer le temps d’exécution de traversal(...) avec et sans arrêt prématuré (par exemple avec time.perf_counter()), sur un grand nombre de labyrinthes tirés aléatoirement, et comparer les moyennes. On peut aussi compter le nombre de sommets visités dans les deux cas (la taille de l’attribut distances), ce qui ne dépend pas de la machine utilisée.

Attention cependant à bien vérifier que l’algorithme a trouvé une des cases cibles avant de construire le chemin inverse (et ne l’a pas juste ajoutée à la liste des cases à considérer). Pour cette séance, ça ne fait pas vraiment de différence, mais ça changera des choses quand on passera à des graphes pondérés.

Voici une adaptation possible du joueur TraversalPlayer pour utiliser cette fonctionnalité :

​
##########################################################################################
########################################## INFO ##########################################
##########################################################################################

"""
This program is a solution to the practical session 2 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session2/practical/
"""

##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################

# PyRat imports
from pyrat import Player, Maze, GameState, Action
from utils.traversal.traversal import Traversal
from utils.traversal.bfs_traversal import BFSTraversal

##########################################################################################
######################################### CLASSES ########################################
##########################################################################################

class TraversalPlayer (Player):

    """
    *(This class inherits from* ``Player`` *).*

    This player controls a PyRat character that explores the maze using a graph traversal algorithm.
    The traversal algorithm is given at creation, as an object of a subclass of ``Traversal`` (e.g., ``BFSTraversal()``).
    """

    ##################################################################################
    #                                   CONSTRUCTOR                                  #
    ##################################################################################

    def __init__ ( self,
                   traversal_algorithm: Traversal | None = None,
                   *args:               object,
                   **kwargs:            object
                 ) ->                   None:

        """
        Initializes a new instance of the class.
        Here, the constructor is only used to initialize the player.
        It transmits the arguments to the parent constructor, which is responsible for initializing the name and the skin of the player.

        Args:
            traversal_algorithm: The traversal algorithm to use, as an object of a subclass of ``Traversal`` (default is a new ``BFSTraversal``).
                                 Each player needs its own object, as it stores the results of the last traversal.
            args:                Arguments to pass to the parent constructor.
            kwargs:              Keyword arguments to pass to the parent constructor.
        """

        # Inherit from parent class
        super().__init__(*args, **kwargs)

        # We create an attribute to store the actions to perform
        self.actions = None

        # We store the chosen traversal algorithm, or create the default one
        self.traversal_algorithm = traversal_algorithm if traversal_algorithm is not None else BFSTraversal()

    ##################################################################################
    #                                  PYRAT METHODS                                 #
    ##################################################################################

    def preprocessing ( self,
                        maze:       Maze,
                        game_state: GameState,
                      ) ->          None:
        
        """
        *(This method redefines the method of the parent class with the same name).*

        This method is called once at the beginning of the game.
        Here, we use the traversal algorithm to compute a path that reaches the piece of cheese from the initial position of the player.

        Args:
            maze:       An object representing the maze in which the player plays.
            game_state: An object representing the state of the game.
        """

        # We perform a traversal of the maze graph from the initial position of the player
        # It stops at the first piece of cheese encountered, which is not necessarily the first one in the list, and returns it
        my_location = game_state.player_locations[self.get_name()]
        target = self.traversal_algorithm.traversal(maze, my_location, game_state.cheese)

        # Find the series of locations/actions to go from the player location to that piece of cheese
        path = self.traversal_algorithm.find_route(target)
        self.actions = maze.locations_to_actions(path)

    ##################################################################################

    def turn ( self,
               maze:       Maze,
               game_state: GameState,
             ) ->          Action:

        """
        *(This method redefines the method of the parent class with the same name).*

        It is called at each turn of the game.
        It returns an action to perform among the possible actions, defined in the ``Action`` enumeration.

        Args:
            maze:       An object representing the maze in which the player plays.
            game_state: An object representing the state of the game.
        
        Returns:
            One of the possible actions.
        """

        # At each turn, we perform the next action in the list of actions
        return self.actions.pop(0)

##########################################################################################
##########################################################################################

Pour aller encore plus loin

Un parcours en profondeur récursif

Comme le parcours en profondeur utilise une pile, et que les fonctions récursives exploitent la pile d’appels de fonctions pour calculer un résultat, il est assez facile de programmer un DFS récursivement.

À faire

Trouvez des ressources en ligne pour vous guider, et lancez-vous !

Correction
Cliquez ici pour afficher la correction.

Voici le diagramme de classes du joueur RecursiveDFS, qui hérite de Player :

Diagramme de classes UML du joueur RecursiveDFS, qui hérite de Player Diagramme de classes UML du joueur RecursiveDFS, qui hérite de Player

Et voici une implémentation possible (players/recursive_dfs.py), ainsi qu’un script de jeu pour visualiser ce joueur :

​
##########################################################################################
########################################## INFO ##########################################
##########################################################################################

"""
This program is a solution to the practical session 2 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session2/practical/
"""

##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################

# PyRat imports
from pyrat import Player, Maze, GameState, Action, Graph

##########################################################################################
######################################### CLASSES ########################################
##########################################################################################

class RecursiveDFS (Player):

    """
    *(This class inherits from* ``Player`` *).*

    This player performs a depth-first search (DFS) to explore the maze.
    Computation of the path is done in the ``preprocessing(...)`` method.
    The path is then followed in the ``turn(...)`` method.
    """
    
    ##################################################################################
    #                                   CONSTRUCTOR                                  #
    ##################################################################################

    def __init__ ( self,
                   *args:    object,
                   **kwargs: object
                 ) ->        None:

        """
        Initializes a new instance of the class.

        Args:
            args:   Arguments to pass to the parent constructor.
            kwargs: Keyword arguments to pass to the parent constructor.
        """

        # Inherit from parent class
        super().__init__(*args, **kwargs)

        # We create an attribute to store the actions to perform
        self.actions = None

    ##################################################################################
    #                                  PYRAT METHODS                                 #
    ##################################################################################

    def preprocessing ( self,
                        maze:       Maze,
                        game_state: GameState,
                      ) ->          None:
        
        """
        *(This method redefines the method of the parent class with the same name).*

        This method is called once at the beginning of the game.
        Here, we use a DFS algorithm to compute a path that reaches the piece of cheese from the initial position of the player.
        The actions corresponding to the path are stored in the ``actions`` attribute, and will be used in the ``turn(...)`` method.

        Args:
            maze:       An object representing the maze in which the player plays.
            game_state: An object representing the state of the game.
        """

        # We perform a DFS traversal of the maze graph from the initial position of the player
        my_location = game_state.player_locations[self.get_name()]
        distances, routing_table = self.traversal(maze, my_location)

        # Find the series of locations/actions to go from the player location to the first piece of cheese
        path = self.find_route(routing_table, my_location, game_state.cheese[0])
        self.actions = maze.locations_to_actions(path)

    ##################################################################################

    def turn ( self,
               maze:       Maze,
               game_state: GameState,
             ) ->          Action:

        """
        *(This method redefines the method of the parent class with the same name).*

        It is called at each turn of the game.
        It returns an action to perform among the possible actions, defined in the ``Action`` enumeration.
        The action is chosen by following the path computed in the ``preprocessing(...)`` method.

        Args:
            maze:       An object representing the maze in which the player plays.
            game_state: An object representing the state of the game.
        
        Returns:
            One of the possible actions.
        """

        # At each turn, we perform the next action in the list of actions
        return self.actions.pop(0)

    ##################################################################################
    #                                  OTHER METHODS                                 #
    ##################################################################################

    def traversal ( self,
                    graph:  Graph,
                    source: int
                  ) ->      tuple[dict[int, int], dict[int, int | None]]:

        """
        This method performs a recursive DFS traversal of a graph.
        It returns the explored vertices with associated distances.
        The distance to a vertex is the sum of the weights of the edges along the path found (given by ``graph.get_weight(...)``).
        It also returns the routing table, that is, the parent of each vertex in the traversal.
        
        Args:
            graph:  The graph to traverse.
            source: The source vertex of the traversal (we type it as int here because we will only manipulate mazes, but Graph uses Hashable as a more generic type).

        Returns:
            A tuple containing:
            - The distances from the source to each explored vertex.
            - The routing table, that is, the parent of each vertex in the traversal (None for the source).
        """

        # Initialization
        distances = {}
        routing_table = {}

        # Recursive subfunction that performs the DFS traversal
        # The explored vertices are the keys of the distances dictionary, which the subfunction modifies without reassigning it
        def __dfs ( current_vertex:   int,
                    current_distance: int,
                    parent_vertex:    int | None
                  ) ->                None:

            # Store the distance and parent of the current vertex, which marks it as explored
            distances[current_vertex] = current_distance
            routing_table[current_vertex] = parent_vertex

            # Explore the neighbors of the current vertex not explored yet
            for neighbor in graph.get_neighbors(current_vertex):
                if neighbor not in distances:
                    __dfs(neighbor, current_distance + graph.get_weight(current_vertex, neighbor), current_vertex)
        
        # Use the recursive subfunction to perform the DFS traversal from the source
        __dfs(source, 0, None)
        return distances, routing_table

    ##################################################################################

    def find_route ( self,
                     routing_table: dict[int, int | None],
                     source:        int,
                     target:        int
                   ) ->             list[int]:

        """
        This method finds the route from a source vertex to a target vertex using a routing table.

        Args:
            routing_table: The routing table, that is, the parent of each vertex in the traversal (None for the source).
            source:        The source vertex.
            target:        The target vertex.

        Returns:
            The route from the source to the target as a list of vertices.
        """

        # Initialization
        route = [target]
        vertex = target

        # Find the route
        while vertex != source:
            vertex = routing_table[vertex]
            route.append(vertex)
        
        # Reverse the route
        route.reverse()
        return route

##########################################################################################
##########################################################################################
##########################################################################################
########################################## INFO ##########################################
##########################################################################################

"""
This program is a solution to the practical session 2 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session2/practical/
"""

##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################

# External imports
import pprint

# PyRat imports
from pyrat import Game
from players.recursive_dfs import RecursiveDFS

##########################################################################################
######################################### SCRIPT #########################################
##########################################################################################

if __name__ == "__main__":

    # Instantiate a game with a few arguments
    game_config = {"mud_percentage": 0.0,
                   "maze_width": 13,
                   "maze_height": 10,
                   "nb_cheese": 1,
                   "random_seed": 2,
                   "trace_length": 1000}

    # Instantiate a game with specified arguments
    game = Game(**game_config)

    # Instantiate the player
    player = RecursiveDFS()
    game.add_player(player)

    # Start the game
    stats = game.start()
    pprint.pprint(stats)

##########################################################################################
##########################################################################################

L’algorithme IDDFS

Une autre piste que vous pouvez explorer est de programmer un algorithme appelé IDDFS. Cet algorithme combine des aspects des algorithmes BFS et DFS : comme le BFS, il trouve un chemin avec le nombre minimal de déplacements, et comme le DFS, il n’a besoin que d’une mémoire proportionnelle à la profondeur explorée, bien moins que le BFS.

À faire

Renseignez-vous sur cet algorithme. Devriez-vous l’utiliser dans le projet ?

Correction
Cliquez ici pour afficher la correction.

Non. L’IDDFS est intéressant quand la mémoire est la contrainte principale, par exemple dans des graphes immenses où on ne peut pas mémoriser tous les sommets rencontrés. Ce gain de mémoire se paie en temps de calcul :

  • Les sommets proches du départ sont explorés à nouveau à chaque itération.

  • Comme on ne mémorise que le chemin en cours, et pas les sommets déjà visités, un même sommet peut être atteint par de nombreux chemins différents. Dans un labyrinthe avec des cycles, le nombre de chemins explorés peut croître exponentiellement avec la profondeur.

Soit $n$ le nombre de sommets du graphe (cases du labyrinthe). Dans un labyrinthe PyRat, chaque sommet a au plus 4 voisins, donc un BFS a une complexité de $O(n)$, et la mémoire qu’il utilise (une entrée par case, soit quelques centaines en général) n’est pas un problème. Le BFS est donc préférable ici.

À faire

Implémentez cet algorithme (ou trouvez une bibliothèque qui le propose).

Correction
Cliquez ici pour afficher la correction.

L’IDDFS effectue des parcours en profondeur dont la profondeur est limitée, en augmentant cette limite petit à petit (0, 1, 2, etc.) jusqu’à trouver le fromage :

  • Comme le BFS, il trouve un chemin avec le nombre minimal de déplacements, car tous les chemins de longueur d sont explorés avant ceux de longueur d + 1.

  • Comme le DFS, il n’a besoin de mémoriser que le chemin en cours d’exploration, et pas tous les sommets rencontrés. C’est pour ça qu’il renvoie directement le chemin vers le fromage, plutôt qu’une table de routage.

  • En contrepartie, les sommets proches du départ sont explorés à nouveau à chaque itération. Pour éviter de tourner en rond dans les cycles du labyrinthe, on n’explore pas les sommets déjà présents dans le chemin en cours.

Voici le diagramme de classes du joueur IDDFS, qui hérite de Player :

Diagramme de classes UML du joueur IDDFS, qui hérite de Player Diagramme de classes UML du joueur IDDFS, qui hérite de Player

Et voici une implémentation possible (players/iddfs.py), ainsi qu’un script de jeu pour visualiser ce joueur :

​
##########################################################################################
########################################## INFO ##########################################
##########################################################################################

"""
This program is a solution to the practical session 2 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session2/practical/
"""

##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################

# PyRat imports
from pyrat import Player, Maze, GameState, Action, Graph

##########################################################################################
######################################### CLASSES ########################################
##########################################################################################

class IDDFS (Player):

    """
    *(This class inherits from* ``Player`` *).*

    This player performs an iterative deepening depth-first search (IDDFS) to find the piece of cheese.
    IDDFS performs depth-limited DFS traversals with an increasing depth limit (0, 1, 2, etc.), until the target is found.
    Like a BFS, it finds a route with the minimum number of moves.
    Like a DFS, it only needs to store the route currently explored, instead of all vertices met so far.
    The price to pay is that vertices close to the source are explored again at each iteration.
    Computation of the path is done in the ``preprocessing(...)`` method.
    The path is then followed in the ``turn(...)`` method.
    """

    ##################################################################################
    #                                   CONSTRUCTOR                                  #
    ##################################################################################

    def __init__ ( self,
                   *args:    object,
                   **kwargs: object
                 ) ->        None:

        """
        Initializes a new instance of the class.

        Args:
            args:   Arguments to pass to the parent constructor.
            kwargs: Keyword arguments to pass to the parent constructor.
        """

        # Inherit from parent class
        super().__init__(*args, **kwargs)

        # We create an attribute to store the actions to perform
        self.actions = None

    ##################################################################################
    #                                  PYRAT METHODS                                 #
    ##################################################################################

    def preprocessing ( self,
                        maze:       Maze,
                        game_state: GameState,
                      ) ->          None:

        """
        *(This method redefines the method of the parent class with the same name).*

        This method is called once at the beginning of the game.
        Here, we use the IDDFS algorithm to compute a path that reaches the piece of cheese from the initial position of the player.
        The actions corresponding to the path are stored in the ``actions`` attribute, and will be used in the ``turn(...)`` method.

        Args:
            maze:       An object representing the maze in which the player plays.
            game_state: An object representing the state of the game.
        """

        # Contrary to BFS and DFS, IDDFS directly returns the route to the target, and not a routing table
        my_location = game_state.player_locations[self.get_name()]
        route = self.iddfs(maze, my_location, game_state.cheese[0])
        self.actions = maze.locations_to_actions(route)

    ##################################################################################

    def turn ( self,
               maze:       Maze,
               game_state: GameState,
             ) ->          Action:

        """
        *(This method redefines the method of the parent class with the same name).*

        It is called at each turn of the game.
        It returns an action to perform among the possible actions, defined in the ``Action`` enumeration.
        The action is chosen by following the path computed in the ``preprocessing(...)`` method.

        Args:
            maze:       An object representing the maze in which the player plays.
            game_state: An object representing the state of the game.

        Returns:
            One of the possible actions.
        """

        # At each turn, we perform the next action in the list of actions
        return self.actions.pop(0)

    ##################################################################################
    #                                  OTHER METHODS                                 #
    ##################################################################################

    def iddfs ( self,
                graph:  Graph,
                source: int,
                target: int
              ) ->      list[int] | None:

        """
        This method performs an iterative deepening depth-first search (IDDFS) in a graph.
        It performs depth-limited searches with an increasing depth limit, until the target is found.
        Since all routes of length ``depth`` are explored before those of length ``depth + 1``, the route found has the minimum number of edges.

        Args:
            graph:  The graph in which to search.
            source: The source vertex of the search.
            target: The vertex to find.

        Returns:
            The route from the source to the target as a list of vertices, or None if the target cannot be reached from the source.
        """

        # We increase the depth limit until the target is found
        depth = 0
        while True:

            # The route is filled by the depth-limited search
            route = [source]
            found, remaining = self.depth_limited_search(graph, route, target, depth)
            if found:
                return route

            # If no route was cut by the depth limit, increasing it will not find anything new
            if not remaining:
                return None
            depth += 1

    ##################################################################################

    def depth_limited_search ( self,
                               graph:  Graph,
                               route:  list[int],
                               target: int,
                               depth:  int
                             ) ->      tuple[bool, bool]:

        """
        This method performs a recursive DFS from the last vertex of a route, without going further than a given depth.
        Vertices already in the route are not explored again, so that the search does not loop forever in the cycles of the graph.
        The route is updated in place: if the target is found, it contains the route from the source to the target.

        Args:
            graph:  The graph in which to search.
            route:  The route from the source to the current vertex (the last one in the list).
            target: The vertex to find.
            depth:  The maximum number of edges that can still be added to the route.

        Returns:
            A tuple containing:
            - Whether the target was found.
            - Whether some routes were cut by the depth limit (if not, increasing the depth limit is useless).
        """

        # Stop if the target is reached
        current_vertex = route[-1]
        if current_vertex == target:
            return True, True

        # Stop if the depth limit is reached, but indicate that the search could go further
        if depth == 0:
            return False, True

        # Explore the neighbors that are not already in the route
        remaining = False
        for neighbor in graph.get_neighbors(current_vertex):
            if neighbor not in route:

                # The neighbor is added to the route for the recursive call, and removed if the target was not found through it
                route.append(neighbor)
                found, neighbor_remaining = self.depth_limited_search(graph, route, target, depth - 1)
                if found:
                    return True, True
                route.pop()
                remaining = remaining or neighbor_remaining

        # The target was not found from the current vertex
        return False, remaining

##########################################################################################
##########################################################################################
##########################################################################################
########################################## INFO ##########################################
##########################################################################################

"""
This program is a solution to the practical session 2 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session2/practical/
"""

##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################

# External imports
import pprint

# PyRat imports
from pyrat import Game
from players.iddfs import IDDFS

##########################################################################################
######################################### SCRIPT #########################################
##########################################################################################

if __name__ == "__main__":

    # Instantiate a game with a few arguments
    game_config = {"mud_percentage": 0.0,
                   "maze_width": 13,
                   "maze_height": 10,
                   "nb_cheese": 1,
                   "random_seed": 2,
                   "trace_length": 1000}

    # Instantiate a game with specified arguments
    game = Game(**game_config)

    # Instantiate the player
    player = IDDFS()
    game.add_player(player)

    # Start the game
    stats = game.start()
    pprint.pprint(stats)

##########################################################################################
##########################################################################################

L’algorithme de Seidel

Alors que le BFS fournit le plus court chemin d’un sommet vers tous les autres, l’algorithme de Seidel permet d’obtenir les plus courts chemins entre tous les sommets dans un graphe non pondéré.

À faire

Renseignez-vous sur cet algorithme. Devriez-vous l’utiliser dans le projet ?

Correction
Cliquez ici pour afficher la correction.

Soit $n$ le nombre de sommets du graphe (cases du labyrinthe).

L’algorithme de Seidel s’applique aux graphes non pondérés et non orientés. Il repose sur des produits de matrices denses de taille $n \times n$, et a une complexité de $O(n^\omega \cdot \log(n))$, où $O(n^\omega)$ est le coût d’un produit de deux telles matrices ($\omega = 3$ avec l’algorithme naïf, et $\omega \approx 2{,}37$ avec les meilleurs algorithmes connus).

Dans un labyrinthe PyRat, chaque sommet a au plus 4 voisins, donc un BFS a une complexité de $O(n)$. En l’exécutant depuis chaque sommet ($n$ fois), on obtient toutes les distances en $O(n^2)$.

Comme l’algorithme de Seidel ne tire pas parti du faible nombre d’arêtes du labyrinthe, utiliser plusieurs fois le BFS est préférable. De plus, l’algorithme de Seidel ignore la boue.

À faire

Implémentez cet algorithme (ou trouvez une bibliothèque qui le propose).

Correction
Cliquez ici pour afficher la correction.

L’algorithme de Seidel travaille sur la matrice d’adjacence du graphe, et calcule les distances entre toutes les paires de sommets :

  • On construit un nouveau graphe, dans lequel deux sommets sont reliés s’ils sont à distance 1 ou 2 dans le graphe d’origine. Sa matrice d’adjacence s’obtient à partir du carré de la matrice d’adjacence d’origine, dont l’entrée [i, j] compte les chemins de longueur 2 entre i et j.

  • Les distances dans ce nouveau graphe sont environ deux fois plus petites, et on les calcule récursivement. La récursion s’arrête quand tous les sommets sont reliés entre eux.

  • On en déduit les distances dans le graphe d’origine : une distance d devient ⌈d / 2⌉ dans le nouveau graphe, et un produit matriciel permet de savoir si d était paire ou impaire.

Cet algorithme ne fonctionne que pour des graphes non pondérés et connexes : la boue est donc ignorée. Une fois les distances connues, on trouve un plus court chemin vers le fromage en se déplaçant, à chaque étape, vers un voisin qui est un pas plus près du fromage.

Voici le diagramme de classes du joueur Seidel, qui hérite de Player :

Diagramme de classes UML du joueur Seidel, qui hérite de Player Diagramme de classes UML du joueur Seidel, qui hérite de Player

Et voici une implémentation possible (players/seidel.py), ainsi qu’un script de jeu pour visualiser ce joueur :

​
##########################################################################################
########################################## INFO ##########################################
##########################################################################################

"""
This program is a solution to the practical session 2 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session2/practical/
"""

##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################

# External imports
import numpy

# PyRat imports
from pyrat import Player, Maze, GameState, Action, Graph

##########################################################################################
######################################### CLASSES ########################################
##########################################################################################

class Seidel (Player):

    """
    *(This class inherits from* ``Player`` *).*

    This player uses Seidel's algorithm to compute the shortest distances between all pairs of vertices of the maze.
    It then uses these distances to find a shortest path to the piece of cheese.
    Seidel's algorithm only works for unweighted, undirected and connected graphs, so mud is ignored.
    Computation of the path is done in the ``preprocessing(...)`` method.
    The path is then followed in the ``turn(...)`` method.
    """

    ##################################################################################
    #                                   CONSTRUCTOR                                  #
    ##################################################################################

    def __init__ ( self,
                   *args:    object,
                   **kwargs: object
                 ) ->        None:

        """
        Initializes a new instance of the class.

        Args:
            args:   Arguments to pass to the parent constructor.
            kwargs: Keyword arguments to pass to the parent constructor.
        """

        # Inherit from parent class
        super().__init__(*args, **kwargs)

        # We create an attribute to store the actions to perform
        self.actions = None

    ##################################################################################
    #                                  PYRAT METHODS                                 #
    ##################################################################################

    def preprocessing ( self,
                        maze:       Maze,
                        game_state: GameState,
                      ) ->          None:

        """
        *(This method redefines the method of the parent class with the same name).*

        This method is called once at the beginning of the game.
        Here, we use Seidel's algorithm to compute the distances between all pairs of vertices, and deduce a shortest path to the piece of cheese.
        The actions corresponding to the path are stored in the ``actions`` attribute, and will be used in the ``turn(...)`` method.

        Args:
            maze:       An object representing the maze in which the player plays.
            game_state: An object representing the state of the game.
        """

        # We compute the distances between all pairs of vertices
        vertices, distances = self.seidel(maze)

        # Find the series of locations/actions to go from the player location to the first piece of cheese
        my_location = game_state.player_locations[self.get_name()]
        path = self.find_route(maze, vertices, distances, my_location, game_state.cheese[0])
        self.actions = maze.locations_to_actions(path)

    ##################################################################################

    def turn ( self,
               maze:       Maze,
               game_state: GameState,
             ) ->          Action:

        """
        *(This method redefines the method of the parent class with the same name).*

        It is called at each turn of the game.
        It returns an action to perform among the possible actions, defined in the ``Action`` enumeration.
        The action is chosen by following the path computed in the ``preprocessing(...)`` method.

        Args:
            maze:       An object representing the maze in which the player plays.
            game_state: An object representing the state of the game.

        Returns:
            One of the possible actions.
        """

        # At each turn, we perform the next action in the list of actions
        return self.actions.pop(0)

    ##################################################################################
    #                                  OTHER METHODS                                 #
    ##################################################################################

    def seidel ( self,
                 graph: Graph
               ) ->     tuple[list[int], numpy.ndarray]:

        """
        This method computes the distances (in number of edges) between all pairs of vertices of a graph, using Seidel's algorithm.
        The graph must be connected, which is always the case for a PyRat maze.
        Edge weights are ignored.

        Args:
            graph: The graph to analyze.

        Returns:
            A tuple containing:
            - The list of vertices, giving the order of the rows and columns of the matrix.
            - The matrix of distances, where entry ``[i, j]`` is the distance between the i-th and j-th vertices of the list.
        """

        # We build the adjacency matrix of the graph, with 1 if there is an edge between two vertices (whatever its weight), and 0 otherwise
        # Rows and columns follow the order of the list of vertices, so we need to know the index of each vertex in this list
        # We use floats rather than integers, because numpy computes products of float matrices much faster (values remain exact integers)
        vertices = graph.get_vertices()
        index = {vertex: i for i, vertex in enumerate(vertices)}
        adjacency_matrix = numpy.zeros((len(vertices), len(vertices)))
        for vertex in vertices:
            for neighbor in graph.get_neighbors(vertex):
                adjacency_matrix[index[vertex], index[neighbor]] = 1

        # The distances are computed recursively, and converted back to integers
        distances = self.all_pairs_distances(adjacency_matrix).astype(int)
        return vertices, distances

    ##################################################################################

    def all_pairs_distances ( self,
                              adjacency_matrix: numpy.ndarray
                            ) ->                numpy.ndarray:

        """
        This method is the recursive part of Seidel's algorithm (called APD on Wikipedia).
        The idea is to build a graph in which two vertices are linked if they are at distance 1 or 2 in the original graph.
        Distances in this new graph are about half of those in the original graph, and are computed recursively.
        They are then used to deduce the distances in the original graph.
        The recursion stops when all vertices are linked, as all distances are then 1 (or 0 between a vertex and itself).

        Args:
            adjacency_matrix: The adjacency matrix of the graph (1 if there is an edge, 0 otherwise).

        Returns:
            The matrix of distances between all pairs of vertices.
        """

        # Entry [i, j] of the squared adjacency matrix is the number of paths of length 2 between i and j
        nb_vertices = adjacency_matrix.shape[0]
        squared_matrix = adjacency_matrix @ adjacency_matrix

        # In the new graph, i and j are linked if there is a path of length 1 or 2 between them (but a vertex is not linked to itself)
        new_adjacency_matrix = ((adjacency_matrix == 1) | (squared_matrix > 0)).astype(float)
        numpy.fill_diagonal(new_adjacency_matrix, 0)

        # Stop if all vertices are linked, as distances are then 1, except for those that were 2 in the original graph
        if numpy.all(new_adjacency_matrix + numpy.eye(nb_vertices) == 1):
            return 2 * new_adjacency_matrix - adjacency_matrix

        # Distances in the new graph
        new_distances = self.all_pairs_distances(new_adjacency_matrix)

        # A distance d in the original graph becomes ceil(d / 2) in the new graph, so it is either 2 * new_distance or 2 * new_distance - 1
        # Entry [i, j] of this product is the sum of the new distances from i to the neighbors of j in the original graph
        # If d is even, these neighbors are at a new distance of at least new_distance[i, j], so the sum is at least new_distance[i, j] * degree(j)
        # If d is odd, at least one of them is closer, and all are at most at new_distance[i, j], so the sum is lower
        sums_on_neighbors = new_distances @ adjacency_matrix
        degrees = adjacency_matrix.sum(axis=0)
        distance_is_odd = sums_on_neighbors < new_distances * degrees
        return 2 * new_distances - distance_is_odd

    ##################################################################################

    def find_route ( self,
                     graph:     Graph,
                     vertices:  list[int],
                     distances: numpy.ndarray,
                     source:    int,
                     target:    int
                   ) ->         list[int]:

        """
        This method finds a shortest route from a source vertex to a target vertex using the matrix of distances.
        From the source, we repeatedly move to a neighbor that is one step closer to the target.

        Args:
            graph:     The graph in which to find the route.
            vertices:  The list of vertices, giving the order of the rows and columns of the matrix.
            distances: The matrix of distances between all pairs of vertices.
            source:    The source vertex.
            target:    The target vertex.

        Returns:
            The route from the source to the target as a list of vertices.
        """

        # We need to know the index of each vertex in the matrix
        index = {vertex: i for i, vertex in enumerate(vertices)}

        # Starting from the source, we move to a neighbor that is closer to the target until we reach it
        route = [source]
        while route[-1] != target:
            current_vertex = route[-1]
            for neighbor in graph.get_neighbors(current_vertex):
                if distances[index[neighbor], index[target]] == distances[index[current_vertex], index[target]] - 1:
                    route.append(neighbor)
                    break
        return route

##########################################################################################
##########################################################################################
##########################################################################################
########################################## INFO ##########################################
##########################################################################################

"""
This program is a solution to the practical session 2 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session2/practical/
"""

##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################

# External imports
import pprint

# PyRat imports
from pyrat import Game
from players.seidel import Seidel

##########################################################################################
######################################### SCRIPT #########################################
##########################################################################################

if __name__ == "__main__":

    # Instantiate a game with a few arguments
    game_config = {"mud_percentage": 0.0,
                   "maze_width": 13,
                   "maze_height": 10,
                   "nb_cheese": 1,
                   "random_seed": 2,
                   "trace_length": 1000}

    # Instantiate a game with specified arguments
    game = Game(**game_config)

    # Instantiate the player
    player = Seidel()
    game.add_player(player)

    # Start the game
    stats = game.start()
    pprint.pprint(stats)

##########################################################################################
##########################################################################################