Activité pratique
Durée2h30Consignes globales
Cette activité prolonge la précédente : vous allez programmer un nouvel algorithme de parcours, l’algorithme de Dijkstra, qui permet de trouver des plus courts chemins dans un graphe pondéré. Nous allons travailler avec la configuration suivante :
- Un seul joueur.
- Un seul morceau de fromage à attraper.
- On ajoute de la boue dans le labyrinthe (20-30% des arêtes).
Autant que possible, vous repartirez du code factorisé à la fin de la séance 2 : vous verrez que l’algorithme de Dijkstra s’y intègre très naturellement. Vous comparerez ensuite ce nouveau joueur aux précédents.
Cette séance sera moins guidée que la précédente, et ce sera de plus en plus le cas à mesure que vous avancerez dans le projet. Nous restons néanmoins disponibles pour vous aider si vous avez des questions, en classe ou sur Discord.
Important
Le code produit lors de cette séance (et des précédentes) fera partie du premier livrable évalué. Consultez les détails sur la page de la séance.
Contenu de l’activité
Constater le problème
L’algorithme BFS trouve le chemin qui comporte le moins de cases. Dans un labyrinthe sans boue, c’est aussi le chemin le plus rapide. Voyons ce qu’il en est quand on ajoute de la boue.
À faire
À l’aide des scripts développés lors de la séance précédente (par exemple visualize_factorized_bfs.py, ou visualize_bfs.py), visualisez le comportement d’un joueur BFS dans un labyrinthe avec de la boue. Quel est le souci ?
Correction
Cliquez ici pour afficher la correction.
Reprenez le script de la séance précédente, et modifiez les arguments du constructeur de Game pour avoir de la boue. Par exemple, prenez mud_percentage=20.0.
Le joueur BFS ne prend pas en compte les coûts de déplacement différents. Il ne distingue pas entre un chemin avec de la boue et un chemin sans boue. Il trouvera donc le chemin le plus court en nombre de cases, mais pas nécessairement le chemin le plus rapide en termes de temps de déplacement.
Algorithme de Dijkstra
Partir de la version factorisée
Lors de la séance précédente, vous avez factorisé les parcours en profondeur et en largeur dans une classe abstraite Traversal. Ses sous-classes BFSTraversal et DFSTraversal ne diffèrent que par la structure de données qui stocke les sommets à explorer : une file pour l’une, une pile pour l’autre.
Information
Vous n’avez pas terminé la factorisation de la séance 2 ? Ce n’est pas grave : créez plutôt un nouveau joueur Dijkstra, dans un fichier players/dijkstra.py, en partant d’une copie de votre fichier bfs.py. Vous réfléchirez à la factorisation des codes après.
Comme vous l’avez vu dans l’article sur l’algorithme de Dijkstra, cet algorithme suit exactement le même schéma. Seule la structure change : c’est une file de priorité (un tas min), qui renvoie toujours le sommet le plus proche de la source parmi ceux qui restent à explorer.
À faire
Avant d’écrire du code, reprenez le diagramme UML de la séance 2, et réfléchissez aux questions ci-dessous.
- Quelle(s) classe(s) faut-il créer ou modifier pour ajouter l’algorithme de Dijkstra à cette organisation ? Complétez le diagramme en conséquence (sur papier, ça suffit).
- Quels attributs et méthodes doivent être créés ?
- La bibliothèque
heapq, présentée dans l’article sur les tas min, vous sera utile. Comment pouvez-vous l’utiliser ? - Votre méthode
traversal(...)utilise-t-elle les poids des arêtes pour calculer les distances ? Si vous devez la modifier, cela change-t-il quelque chose pourBFSTraversaletDFSTraversal?
Correction
Cliquez ici pour afficher la correction.
Il suffit de créer une nouvelle sous-classe DijkstraTraversal de Traversal, dans un fichier utils/traversal/dijkstra_traversal.py. TraversalPlayer n’a pas besoin d’être modifié : il suffit de lui donner un objet de cette classe à sa création, avec TraversalPlayer(DijkstraTraversal()). La correction en fait aussi le parcours par défaut du joueur :
Le diagramme intègre aussi l’arrêt prématuré du parcours (paramètre optionnel stop_vertices de traversal(...), qui renvoie alors le sommet d’arrêt trouvé), vu dans la section « Pour aller plus loin » de la séance précédente.
Pour les questions :
-
Comme
BFSTraversaletDFSTraversal, la nouvelle classe a un seul attribut, qui contient sa structure de données (ici, une file de priorité). Il faut ensuite définir les quatre méthodes qui gèrent cette structure,initialize_structure(...),add_to_structure(...),get_from_structure(...)etis_structure_empty(...).Traversaln’a pas à changer. -
Avec
heapq, la structure est une simple liste :initialize_structure(...)range une liste vide dans un attributheapdeDijkstraTraversal,add_to_structure(...)utiliseheapq.heappush(...),get_from_structure(...)utiliseheapq.heappop(...), etis_structure_empty(...)teste si la liste est vide. -
heapqcompare les tuples composante par composante. La distance doit donc être la première composante, sous la forme(distance, sommet, parent). Si le sommet venait en premier, le tas renverrait le sommet de plus petit numéro, ce qui n’a aucun sens ici. -
La distance d’un voisin doit être calculée en ajoutant le poids de l’arête (
graph.get_weight(...)), et non en ajoutant 1. PourBFSTraversaletDFSTraversal, l’ordre d’exploration ne dépend pas de la distance (il est fixé par la file ou la pile), donc les chemins trouvés ne changent pas. Seules les distances stockées changent : ce sont maintenant les longueurs des chemins trouvés, en tenant compte des poids.
Si vous avez repris la correction de traversal.py de la séance précédente, elle respecte déjà ces deux derniers points, et n’a pas besoin d’être modifiée.
Préparation
À faire
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 sans que ça crashe.
-
utils/traversal/dijkstra_traversal.py— Créez une classeDijkstraTraversalhéritant deTraversal, en vous inspirant debfs_traversal.py.Si vous n’avez pas factorisé à la séance précédente, vous pouvez commencer par créer directement une classe
Dijkstradansplayers/dijkstra.pyen vous inspirant deplayers/bfs.py. -
players/traversal_player.py— Rien à modifier : le joueur reçoit son parcours à sa création. Vous pouvez éventuellement faire deDijkstraTraversalson parcours par défaut, utilisé quand aucun parcours n’est donné.Si vous n’avez pas factorisé à la séance précédente, vous n’avez rien à faire ici.
-
games/visualize_factorized_dijkstra.py— Créez un script qui lancera une partie avec ce joueur, dans un labyrinthe respectant les critères listés plus haut. Vous pouvez éventuellement définir unerandom_seed(pour toujours travailler avec le même labyrinthe) et unetrace_length(pour suivre la trajectoire de votre joueur).Si vous n’avez pas factorisé à la séance précédente, nommez plutôt votre script
games/visualize_dijkstra.py. -
tests/test_dijkstra_traversal.py— Créez un fichier qui contiendra les tests unitaires de votre algorithme. Pour le moment, créez juste le fichier avec une classe de tests copiée-collée detest_bfs_traversal.py(ou detest_bfs.py), en changeant le nom de la classe et en enlevant les méthodes de test.Si vous n’avez pas factorisé à la séance précédente, nommez plutôt votre fichier
tests/test_dijkstra.py.
Correction
Cliquez ici pour afficher la correction.
Faites attention à bien fixer les arguments mud_percentage et nb_cheese du constructeur de la classe Game. Pour la version factorisée, le script de jeu devrait ressembler à ça :
##########################################################################################
########################################## INFO ##########################################
##########################################################################################
"""
This program is a solution to the practical session 3 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session3/practical/
"""
##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################
# External imports
import pprint
# PyRat imports
from pyrat import Game
from players.traversal_player import TraversalPlayer
from utils.traversal.dijkstra_traversal import DijkstraTraversal
##########################################################################################
######################################### SCRIPT #########################################
##########################################################################################
if __name__ == "__main__":
# Instantiate a game with a few arguments
game_config = {"mud_percentage": 20.0,
"maze_width": 13,
"maze_height": 10,
"nb_cheese": 1,
"random_seed": 42,
"trace_length": 1000}
# Instantiate a game with specified arguments
game = Game(**game_config)
# Instantiate the player
player = TraversalPlayer(DijkstraTraversal(), name="Factorized Dijkstra")
game.add_player(player)
# Start the game
stats = game.start()
pprint.pprint(stats)
##########################################################################################
##########################################################################################Et pour la version non factorisée :
##########################################################################################
########################################## INFO ##########################################
##########################################################################################
"""
This program is a solution to the practical session 3 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session3/practical/
"""
##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################
# External imports
import pprint
# PyRat imports
from pyrat import Game
from players.dijkstra import Dijkstra
##########################################################################################
######################################### SCRIPT #########################################
##########################################################################################
if __name__ == "__main__":
# Instantiate a game with a few arguments
game_config = {"mud_percentage": 20.0,
"maze_width": 13,
"maze_height": 10,
"nb_cheese": 1,
"random_seed": 42,
"trace_length": 1000}
# Instantiate a game with specified arguments
game = Game(**game_config)
# Instantiate the player
player = Dijkstra()
game.add_player(player)
# Start the game
stats = game.start()
pprint.pprint(stats)
##########################################################################################
##########################################################################################Les autres fichiers sont donnés en correction plus bas.
Implémentation
À faire
Complétez la classe DijkstraTraversal (ou le joueur Dijkstra), en vous appuyant sur vos réponses aux questions plus haut.
Correction
Cliquez ici pour afficher la correction.
Pour la version factorisée, voici la classe DijkstraTraversal, et le joueur TraversalPlayer adapté (il intègre aussi l’arrêt prématuré du parcours, vu dans la section « Pour aller plus loin » de la séance précédente). Par rapport à la correction de la séance précédente, seul le parcours par défaut du joueur change : c’est maintenant DijkstraTraversal. Leur diagramme de classes est donné dans la correction de la section « Partir de la version factorisée » :
##########################################################################################
########################################## INFO ##########################################
##########################################################################################
"""
This program is a solution to the practical session 3 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session3/practical/
"""
##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################
# External imports
import heapq
# PyRat imports
from utils.traversal.traversal import Traversal
##########################################################################################
######################################### CLASSES ########################################
##########################################################################################
class DijkstraTraversal (Traversal):
"""
This class implements Dijkstra's traversal algorithm by defining the abstract methods from the parent class.
We use a priority 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 Dijkstra's traversal algorithm by defining the abstract methods from the parent class.
We use a priority 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)
# Priority queue of the elements to visit, as a list managed by heapq, created by initialize_structure
self.heap = 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 ``heap`` attribute.
Here, we use a priority queue, as a list managed by ``heapq``.
"""
# We start with an empty list, which is a valid heap
self.heap = []
##################################################################################
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 ``heap`` attribute.
Here, we add the element to the priority queue using ``heapq.heappush``.
Args:
element: The element to add, as a tuple (distance, vertex, parent).
"""
# We push the element into the heap
heapq.heappush(self.heap, 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 ``heap`` attribute.
Here, we remove and return the element with the smallest distance (first component of the tuple) using ``heapq.heappop``.
Returns:
The extracted element, as a tuple (distance, vertex, parent).
"""
# We pop the element with the smallest distance from the heap
return heapq.heappop(self.heap)
##################################################################################
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 ``heap`` attribute contains no more elements to extract.
Here, the priority queue is empty when the heap has no element.
Returns:
True if the data structure is empty, False otherwise.
"""
# The priority queue is empty when the heap has no element
return len(self.heap) == 0
##########################################################################################
####################################################################################################################################################################################
########################################## INFO ##########################################
##########################################################################################
"""
This program is a solution to the practical session 3 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session3/practical/
"""
##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################
# PyRat imports
from pyrat import Player, Maze, GameState, Action
from utils.traversal.traversal import Traversal
from utils.traversal.dijkstra_traversal import DijkstraTraversal
##########################################################################################
######################################### 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 ``DijkstraTraversal``).
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 DijkstraTraversal()
##################################################################################
# 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 la version non factorisée, voici le diagramme de classes du joueur Dijkstra :
Et voici son code :
##########################################################################################
########################################## INFO ##########################################
##########################################################################################
"""
This program is a solution to the practical session 3 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session3/practical/
"""
##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################
# External imports
import heapq
# PyRat imports
from pyrat import Player, Maze, GameState, Action, Graph
##########################################################################################
######################################### CLASSES ########################################
##########################################################################################
class Dijkstra (Player):
"""
*(This class inherits from* ``Player`` *).*
This player performs Dijkstra's algorithm to find the shortest path in 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 Dijkstra's 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 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 Dijkstra's algorithm on 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 = []
heapq.heappush(vertices_to_visit, (0, source, None))
# Traversal
while vertices_to_visit:
# Get the next vertex to visit
distance, vertex, parent = heapq.heappop(vertices_to_visit)
# 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)
heapq.heappush(vertices_to_visit, (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
Pour programmer et tester votre algorithme, vous pouvez choisir entre deux approches :
-
Approche classique — La méthode la plus courante pour développer un programme est de programmer le corps d’une méthode, puis de la tester. Une fois validée, passez à la méthode suivante, etc., jusqu’à ce que toutes les méthodes soient programmées.
-
Développement piloté par les tests — Si vous préférez, avant de coder le contenu de vos méthodes, vous pouvez déjà écrire les tests unitaires. Cela vous permettra de tester vos méthodes plus fréquemment pendant leur développement, et vous pourrez être convaincu(e)s de votre travail lorsqu’elles passeront tous les tests que vous avez conçus.
Que vous les écriviez avant ou après le code, il est important de concevoir des tests qui vous convainquent que votre programme fonctionne comme prévu !
Par exemple, supposons que vous souhaitiez concevoir un test pour vous assurer que Dijkstra trouve le chemin le plus court dans un graphe pondéré, contrairement à un BFS. Intuitivement, vous voulez créer un graphe fixe, identifier le chemin le plus court à la main, et vérifier que la sortie de Dijkstra correspond à ce chemin. Cependant, le choix du graphe utilisé a une grande importance :
-
Si vous choisissez un labyrinthe dans lequel il n’y a qu’un seul chemin entre votre position initiale et le morceau de fromage, alors les algorithmes BFS et Dijkstra trouveront tous deux le chemin correct.
-
De même, s’il n’y a pas de boue le long du chemin le plus court entre votre position initiale et le morceau de fromage (ou s’il est toujours plus rapide de traverser cette boue que de l’éviter), alors encore une fois, les algorithmes BFS et Dijkstra trouveront le chemin correct.
À faire
Prenez un moment pour réfléchir et lister les tests unitaires que vous souhaitez effectuer. Pour chaque test, déterminez s’il correspond à une utilisation normale, à un cas limite (une entrée valide mais inhabituelle), ou à une erreur possible.
Programmez ensuite ces tests, et exécutez-les fréquemment pour vous assurer que votre code fonctionne comme prévu.
Correction
Cliquez ici pour afficher la correction.
Pour la méthode traversal(...) :
-
Quelques idées de tests d’utilisation normale :
- Tester avec des graphes non pondérés (tous les poids égaux) et comparer la longueur des chemins trouvés avec
BFS. - Tester avec des graphes pondérés contrôlés où on connaît déjà les plus courts chemins.
- Tester avec des graphes pondérés plus complexes, et vérifier que la longueur des chemins trouvés est toujours inférieure ou égale à celle des chemins trouvés par
BFS.
- Tester avec des graphes non pondérés (tous les poids égaux) et comparer la longueur des chemins trouvés avec
-
Quelques idées de tests d’erreurs possibles, qui devraient lever des exceptions :
- Tester avec une source qui n’existe pas dans le graphe.
- Appeler la méthode avec des arguments de types incorrects (par exemple, une chaîne au lieu d’un graphe).
-
Quelques idées de tests de cas limites, qui devraient quand même fonctionner :
- Tester avec un graphe non connexe. On devrait toujours obtenir les plus courts chemins pour les sommets atteignables.
Notez qu’il est inutile de tester des poids négatifs : l’algorithme de Dijkstra ne les gère pas, mais il ne lève pas d’exception pour autant, il renvoie simplement des distances fausses (voir la section sur l’algorithme de Bellman-Ford plus bas). De toute façon, un labyrinthe PyRat ne peut pas contenir de poids négatifs : MazeFromDict les refuse.
Pour la méthode find_route(...) :
-
Quelques idées de tests d’utilisation normale :
- Tester avec des prédécesseurs valides et vérifier que le chemin renvoyé est correct.
- Tester avec la source égale à la cible, et vérifier que le chemin renvoyé est juste la source.
-
Quelques idées de tests d’erreurs possibles, qui devraient lever des exceptions :
- Tester avec une cible qui n’est pas atteignable depuis la source (par exemple dans un graphe non connexe).
- Tester avec une source ou une cible qui n’existent pas dans le dictionnaire des prédécesseurs.
- Appeler la méthode avec des arguments de types incorrects (par exemple, une liste au lieu d’un dictionnaire).
-
Quelques idées de tests de cas limites, qui devraient quand même fonctionner :
- Tester avec un dictionnaire des prédécesseurs qui ne couvre pas tous les sommets du graphe. On devrait toujours obtenir un chemin correct si la cible est atteignable.
Voici des tests pour chacune des deux versions, organisés comme ceux fournis pour le BFS et le DFS lors de la séance précédente (un test par propriété, regroupés en utilisation normale, cas limites et cas d’erreur). Deux points méritent l’attention :
-
Le test
distances_are_minimalest propre à l’algorithme de Dijkstra : il vérifie qu’aucune arête ne permet de raccourcir une distance trouvée, ce qui garantit qu’il s’agit bien de plus courts chemins. Un BFS échoue à ce test dès que contourner une case de boue est plus rapide que de la traverser. C’est le cas du labyrinthemud_cycle_maze, utilisé dans le testfixed_mazes___expected_outputs, où le plus court chemin fait le tour du cycle au lieu de traverser la boue. -
Dans la version factorisée, les résultats du parcours sont lus avec
get_distances(...)etget_routing_table(...), au lieu d’être renvoyés partraversal(...), etfind_route(...)ne prend que la cible en argument. Les tests vérifient aussi que deux parcours successifs sont bien indépendants. -
Les tests de la version factorisée portent aussi sur l’arrêt prématuré du parcours (paramètre
stop_vertices, et sommet d’arrêt renvoyé partraversal(...)), vu dans la section « Pour aller plus loin » de la séance précédente. Si votre classeTraversalne le gère pas, supprimez ces tests, ainsi que l’argumentstop_verticesde la méthode utilitairetraverse(...), qui le transmet àtraversal(...).
Voici les tests de la version factorisée :
##########################################################################################
########################################## INFO ##########################################
##########################################################################################
"""
This program is a solution to the practical session 3 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session3/practical/
We have chosen to organize tests as follows:
* Methods are tested by multiple tests, to have each test focusing on a specific aspect of the method.
* Tests are named test___<tested method>___<test case>___<tested property> (this is a choice, anything named ``test_*`` is fine).
* Random mazes are created once in ``setUpClass(...)``, and shared by all tests, so that each test is as short as possible.
We basically perform two types of tests here:
* On random mazes: To make sure that the methods work as expected in various cases.
This allows to test invariants (e.g., the output is of a specific type), but not specific results.
* On manually created mazes: To make sure that the methods work as expected in specific cases.
This allows to test specific results (e.g., the output on this particular instance is equal to that specific value).
Also, tests are grouped in three categories:
* Normal use: The method is called as it is meant to be.
* Corner cases: The method is called with valid but unusual inputs (e.g., the smallest possible graph).
* Error cases: The method is called with invalid inputs, and should raise an exception.
"""
##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################
# External imports
import copy
import random
import unittest
# PyRat imports
from pyrat import Graph, RandomMaze, MazeFromDict, PyRatException
from utils.traversal.dijkstra_traversal import DijkstraTraversal
##########################################################################################
######################################### CLASSES ########################################
##########################################################################################
class DijkstraTraversal_Tests (unittest.TestCase):
"""
*(This class inherits from* ``unittest.TestCase`` *).*
This class tests the methods of the DijkstraTraversal class.
For each method, we test it with a few different configurations.
Contrary to the Dijkstra player, the results of a traversal are stored in attributes of the object, rather than returned.
"""
##################################################################################
# INITIALIZATION #
##################################################################################
@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.
"""
# A 3x3 maze with no cycle (a tree), with some mud
# Whatever the order of exploration, there is a unique routing table for a given start
# [0] --- [1] ~3~ [2]
# |
# [3] --- [4] [5]
# ~2~ ~5~
# [6] --- [7] --- [8]
cls.tree_maze = MazeFromDict({0: {1: 1},
1: {0: 1, 2: 3, 4: 1},
2: {1: 3},
3: {4: 1},
4: {1: 1, 3: 1, 7: 2},
5: {8: 5},
6: {7: 1},
7: {4: 2, 6: 1, 8: 1},
8: {7: 1, 5: 5}})
# A 2x2 maze forming a single cycle, with no mud
# Dijkstra first reaches the two neighbors of the start (at distance 1), and then the opposite vertex from one of them
# [0] --- [1]
# | |
# [2] --- [3]
cls.cycle_maze = MazeFromDict({0: {1: 1, 2: 1},
1: {0: 1, 3: 1},
2: {0: 1, 3: 1},
3: {1: 1, 2: 1}})
# The same cycle, with mud between the start and one of its neighbors
# Going around the cycle is faster than crossing the mud (whereas a BFS would cross it)
# [0] ~5~ [1]
# | |
# [2] --- [3]
cls.mud_cycle_maze = MazeFromDict({0: {1: 5, 2: 1},
1: {0: 5, 3: 1},
2: {0: 1, 3: 1},
3: {1: 1, 2: 1}})
# A maze with two connected components {0, 1} and {2, 3}
# [0] --- [1]
#
# [2] --- [3]
cls.disconnected_maze = MazeFromDict({0: {1: 1},
1: {0: 1},
2: {3: 1},
3: {2: 1}})
# We use a random number generator (RNG) with a fixed seed, so that tests are reproducible
rng = random.Random(42)
# Create 100 random mazes, with no holes
# We use various sizes and densities, and add some mud so that edges do not all have weight 1
cls.random_mazes = []
for _ in range(100):
cls.random_mazes.append(RandomMaze(width=rng.randint(2, 30),
height=rng.randint(2, 30),
wall_percentage=rng.uniform(20.0, 100.0),
mud_percentage=rng.uniform(0.0, 50.0),
mud_range=(2, 10),
random_seed=rng.randint(0, 2**31 - 1)))
##################################################################################
def setUp (self) -> None:
"""
This method is called before each test method.
Here, we use it to instantiate a DijkstraTraversal object.
"""
# Instantiate a DijkstraTraversal object to test its methods
self.traversal_algorithm = DijkstraTraversal()
##################################################################################
# HELPERS #
##################################################################################
def traverse ( self,
graph: Graph,
source: int,
stop_vertices: set[int] | list[int] | None = None
) -> tuple[dict[int, int], dict[int, int | None]]:
"""
This method performs a traversal, and returns its results, which are stored in attributes of the object.
This way, tests can be written as for the Dijkstra player, which returns them.
Args:
graph: The graph to traverse.
source: The source vertex of the traversal.
stop_vertices: The vertices at which to stop the traversal (None to traverse the whole graph).
Returns:
A tuple containing the distances and the routing table found by the traversal.
"""
# Perform the traversal and get its results
self.traversal_algorithm.traversal(graph, source, stop_vertices)
return self.traversal_algorithm.get_distances(), self.traversal_algorithm.get_routing_table()
##################################################################################
# TESTS (dijkstra_traversal.traversal) #
##################################################################################
def test___dijkstra_traversal_traversal___random_mazes___output_types (self) -> None:
"""
Category: normal use.
This method tests the ``traversal(...)`` method on random mazes.
It checks that the method returns nothing, and that the attributes it sets are of the expected types.
"""
# The method should return nothing, as results are stored in attributes
self.assertIsNone(self.traversal_algorithm.traversal(self.random_mazes[0], self.random_mazes[0].get_vertices()[0]), "The traversal should return nothing")
# 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.traverse(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")
##################################################################################
def test___dijkstra_traversal_traversal___random_mazes___all_vertices_visited (self) -> None:
"""
Category: normal use.
This method tests the ``traversal(...)`` method on random mazes.
It checks that all vertices are visited, and appear in both outputs.
This assumes that the maze is connected, which is the case for random mazes generated by PyRat.
"""
# Both outputs should have the maze vertices as keys
for maze in self.random_mazes:
start_vertex = maze.get_vertices()[0]
distances, routing_table = self.traverse(maze, start_vertex)
self.assertEqual(set(distances.keys()), set(maze.get_vertices()), "Distances should be given for all vertices of the maze, and only for them")
self.assertEqual(set(routing_table.keys()), set(maze.get_vertices()), "The routing table should contain all vertices of the maze, and only them")
##################################################################################
def test___dijkstra_traversal_traversal___random_mazes___routing_table_is_spanning_tree (self) -> None:
"""
Category: normal use.
This method tests the ``traversal(...)`` method on random mazes.
It checks that the routing table is a tree, rooted at the start vertex, that only uses edges of the maze.
"""
# The start vertex is the root, all other vertices go up to it without cycle, and each parent is a neighbor in the maze
# To check this, we go up from each vertex to the root, to find all its ancestors in the tree
for maze in self.random_mazes:
start_vertex = maze.get_vertices()[0]
_, routing_table = self.traverse(maze, start_vertex)
ancestors = {}
for vertex in routing_table:
ancestors[vertex] = set()
ancestor = routing_table[vertex]
while ancestor is not None:
self.assertNotIn(ancestor, ancestors[vertex], f"The routing table contains a cycle (vertex {ancestor} is met twice when going up from vertex {vertex})")
ancestors[vertex].add(ancestor)
ancestor = routing_table[ancestor]
self.assertIsNone(routing_table[start_vertex], "The start vertex should have no parent in the routing table")
for vertex in routing_table.keys() - {start_vertex}:
self.assertIn(start_vertex, ancestors[vertex], f"Going up the routing table from vertex {vertex} should lead to the start vertex")
self.assertIn(routing_table[vertex], maze.get_neighbors(vertex), f"The parent of vertex {vertex} in the routing table should be one of its neighbors in the maze")
##################################################################################
def test___dijkstra_traversal_traversal___random_mazes___distances_match_routing_table (self) -> None:
"""
Category: normal use.
This method tests the ``traversal(...)`` method on random mazes.
It checks that distances are 0 for the start vertex, and strictly positive for all other vertices.
It also checks that they are increasing along the routing table, and more precisely that the distance to each vertex is the distance to its parent plus the weight of the edge between them.
Since mazes contain mud, this also checks that edge weights are taken into account.
"""
# The start vertex is at distance 0, and the distance increases by the weight of each edge in the routing table
for maze in self.random_mazes:
start_vertex = maze.get_vertices()[0]
distances, routing_table = self.traverse(maze, start_vertex)
self.assertEqual(distances[start_vertex], 0, "The distance to the start vertex should be 0")
for vertex in routing_table.keys() - {start_vertex}:
parent = routing_table[vertex]
self.assertGreater(distances[vertex], 0, f"The distance to vertex {vertex} should be strictly positive")
self.assertGreater(distances[vertex], distances[parent], f"The distance to vertex {vertex} should be greater than the distance to its parent {parent}")
self.assertEqual(distances[vertex], distances[parent] + maze.get_weight(parent, vertex), f"The distance to vertex {vertex} should be the distance to its parent {parent} plus the weight of the edge between them")
##################################################################################
def test___dijkstra_traversal_traversal___random_mazes___distances_are_minimal (self) -> None:
"""
Category: normal use.
This method tests the ``traversal(...)`` method on random mazes.
It checks that the distances found are the lengths of shortest paths, and not just of any path.
Previous tests would also pass with a BFS or a DFS, for instance.
Thanks to the previous tests, we know that the distance to each vertex is the length of the path given by the routing table.
Such distances are those of shortest paths if no edge allows a shortcut, i.e., if for each edge between vertices u and v, distance(v) <= distance(u) + weight(u, v).
Indeed, starting from the source, this inequality shows step by step that no path to a vertex can be shorter than its distance.
A BFS does not have this property when there is mud, since it ignores the weights when choosing the order of exploration.
"""
# No edge of the maze should allow a shortcut, in either direction
for maze in self.random_mazes:
start_vertex = maze.get_vertices()[0]
distances, _ = self.traverse(maze, start_vertex)
for vertex_1, vertex_2 in maze.get_edges():
weight = maze.get_weight(vertex_1, vertex_2)
self.assertLessEqual(distances[vertex_2], distances[vertex_1] + weight, f"Going to vertex {vertex_2} through vertex {vertex_1} is shorter than the distance found, which cannot happen with Dijkstra's algorithm")
self.assertLessEqual(distances[vertex_1], distances[vertex_2] + weight, f"Going to vertex {vertex_1} through vertex {vertex_2} is shorter than the distance found, which cannot happen with Dijkstra's algorithm")
##################################################################################
def test___dijkstra_traversal_traversal___random_mazes___maze_unchanged (self) -> None:
"""
Category: normal use.
This method tests the ``traversal(...)`` method on random mazes.
It checks that the traversal does not modify the maze.
"""
# The maze should be the same before and after the traversal
for maze in self.random_mazes:
start_vertex = maze.get_vertices()[0]
maze_before = copy.deepcopy(maze.as_dict())
self.traverse(maze, start_vertex)
self.assertEqual(maze.as_dict(), maze_before, "The traversal should not modify the maze")
##################################################################################
def test___dijkstra_traversal_traversal___fixed_mazes___expected_outputs (self) -> None:
"""
Category: normal use.
This method tests the ``traversal(...)`` method on some manually created mazes.
In general, Dijkstra's algorithm has multiple valid outputs, depending on how ties between equal distances are broken.
Here, we choose mazes for which we can list all valid outputs (see the ``setUpClass(...)`` method).
"""
# Test cases, with all valid outputs (distances, routing table) for each of them
TESTS = [{"maze": self.tree_maze,
"start": 4,
"outputs": [({4: 0, 1: 1, 3: 1, 7: 2, 0: 2, 2: 4, 6: 3, 8: 3, 5: 8},
{4: None, 1: 4, 3: 4, 7: 4, 0: 1, 2: 1, 6: 7, 8: 7, 5: 8})]},
{"maze": self.tree_maze,
"start": 0,
"outputs": [({0: 0, 1: 1, 2: 4, 4: 2, 3: 3, 7: 4, 6: 5, 8: 5, 5: 10},
{0: None, 1: 0, 2: 1, 4: 1, 3: 4, 7: 4, 6: 7, 8: 7, 5: 8})]},
{"maze": self.cycle_maze,
"start": 0,
"outputs": [({0: 0, 1: 1, 2: 1, 3: 2}, {0: None, 1: 0, 2: 0, 3: 1}),
({0: 0, 1: 1, 2: 1, 3: 2}, {0: None, 1: 0, 2: 0, 3: 2})]},
{"maze": self.mud_cycle_maze,
"start": 0,
"outputs": [({0: 0, 2: 1, 3: 2, 1: 3}, {0: None, 2: 0, 3: 2, 1: 3})]}]
# Outputs should match one of the expected ones
for test in TESTS:
outputs = self.traverse(test["maze"], test["start"])
self.assertIn(outputs, test["outputs"], f"Unexpected outputs for a traversal from vertex {test['start']}")
##################################################################################
def test___dijkstra_traversal_traversal___fixed_mazes___stops_at_closest_stop_vertex (self) -> None:
"""
Category: normal use.
This method tests the ``traversal(...)`` method with stop vertices (early stop of the traversal).
The traversal should stop as soon as one of them is explored, which is the closest one to the source, and return it.
"""
# From vertex 4 in the tree maze, vertex 2 is at distance 4, and vertex 5 at distance 8 (see the ``setUpClass(...)`` method)
# All vertices at distance at most 4 are explored before vertex 2, but not vertex 5
stop_vertex = self.traversal_algorithm.traversal(self.tree_maze, 4, {2, 5})
self.assertEqual(stop_vertex, 2, "The traversal should stop at the closest stop vertex")
self.assertEqual(self.traversal_algorithm.get_distances(), {4: 0, 1: 1, 3: 1, 0: 2, 7: 2, 6: 3, 8: 3, 2: 4}, "Only vertices up to the closest stop vertex should be explored")
self.assertEqual(self.traversal_algorithm.find_route(2), [4, 1, 2], "The route to the stop vertex found should be available")
##################################################################################
def test___dijkstra_traversal_traversal___fixed_mazes___no_stop_vertex_found (self) -> None:
"""
Category: normal use.
This method tests the ``traversal(...)`` method without stop vertices, or with stop vertices that cannot be reached.
The whole component of the source should be explored, and no stop vertex should be returned.
"""
# Without stop vertices, the whole maze is explored
self.assertIsNone(self.traversal_algorithm.traversal(self.tree_maze, 4), "No stop vertex should be found without stop vertices")
self.assertEqual(set(self.traversal_algorithm.get_distances().keys()), set(self.tree_maze.get_vertices()), "The whole maze should be explored without stop vertices")
# Vertices 2 and 3 cannot be reached from 0 in the disconnected maze
self.assertIsNone(self.traversal_algorithm.traversal(self.disconnected_maze, 0, {2, 3}), "No stop vertex should be found if none can be reached")
self.assertEqual(set(self.traversal_algorithm.get_distances().keys()), {0, 1}, "The whole component of the source should be explored if no stop vertex can be reached")
##################################################################################
def test___dijkstra_traversal_traversal___fixed_mazes___successive_traversals_independent (self) -> None:
"""
Category: normal use.
This method tests the ``traversal(...)`` method when it is called several times on the same object.
Since results are stored in attributes, each traversal should start from scratch, and not keep anything from the previous one.
"""
# A first traversal with an early stop, then a second one on another maze
self.traverse(self.tree_maze, 4, {2})
distances, routing_table = self.traverse(self.disconnected_maze, 0)
self.assertEqual((distances, routing_table), ({0: 0, 1: 1}, {0: None, 1: 0}), "A traversal should not keep results of a previous one")
##################################################################################
def test___dijkstra_traversal_traversal___single_vertex_graph___only_source_visited (self) -> None:
"""
Category: corner case.
This method tests the ``traversal(...)`` method on the smallest possible graph, with a single vertex and no edge.
PyRat mazes need at least two cells, so we use a graph here.
"""
# Only the source should be visited
graph = Graph()
graph.add_vertex(0)
self.assertEqual(self.traverse(graph, 0), ({0: 0}, {0: None}), "Only the source should be visited in a graph with a single vertex")
##################################################################################
def test___dijkstra_traversal_traversal___disconnected_maze___only_component_visited (self) -> None:
"""
Category: corner case.
This method tests the ``traversal(...)`` method on a maze that is not connected.
Only the vertices that can be reached from the source should be visited.
"""
# Vertices 2 and 3 cannot be reached from 0
self.assertEqual(self.traverse(self.disconnected_maze, 0), ({0: 0, 1: 1}, {0: None, 1: 0}), "Only the vertices reachable from the source should be visited")
##################################################################################
def test___dijkstra_traversal_traversal___source_is_stop_vertex___only_source_visited (self) -> None:
"""
Category: corner case.
This method tests the ``traversal(...)`` method when the source is itself a stop vertex.
The traversal should stop immediately, after exploring the source only.
"""
# The source is the first vertex explored
self.assertEqual(self.traversal_algorithm.traversal(self.tree_maze, 4, {4, 5}), 4, "The source should be the stop vertex found")
self.assertEqual((self.traversal_algorithm.get_distances(), self.traversal_algorithm.get_routing_table()), ({4: 0}, {4: None}), "Only the source should be explored if it is a stop vertex")
##################################################################################
def test___dijkstra_traversal_traversal___stop_vertices_as_list___same_as_set (self) -> None:
"""
Category: corner case.
This method tests the ``traversal(...)`` method when stop vertices are given as a list rather than a set.
Both are accepted, and should give the same results.
"""
# Same traversal, with a set and a list
outputs_set = self.traverse(self.tree_maze, 4, {2, 5})
outputs_list = self.traverse(self.tree_maze, 4, [5, 2])
self.assertEqual(outputs_list, outputs_set, "Stop vertices given as a list should give the same results as a set")
##################################################################################
def test___dijkstra_traversal_traversal___source_not_in_maze___raises_error (self) -> None:
"""
Category: error case.
This method tests the ``traversal(...)`` method when the source is not a vertex of the maze.
PyRat raises a ``PyRatException`` when asking for the neighbors of a vertex that does not exist.
"""
# Cell 9 does not exist in this maze
with self.assertRaises(PyRatException, msg="A traversal from a vertex that is not in the maze should raise an error"):
self.traverse(self.disconnected_maze, 9)
##################################################################################
def test___dijkstra_traversal_traversal___graph_not_a_graph___raises_error (self) -> None:
"""
Category: error case.
This method tests the ``traversal(...)`` method when the graph is not a PyRat ``Graph`` (unexpected argument).
The error is raised by Python when trying to call ``get_neighbors(...)`` on an object that does not have this method.
"""
# None and a dictionary do not have a get_neighbors(...) method
with self.assertRaises(AttributeError, msg="A traversal of None should raise an error"):
self.traverse(None, 0)
with self.assertRaises(AttributeError, msg="A traversal of a dictionary should raise an error, even if it describes a graph"):
self.traverse({0: {1: 1}, 1: {0: 1}}, 0)
##################################################################################
def test___dijkstra_traversal_traversal___source_wrong_type___raises_error (self) -> None:
"""
Category: error case.
This method tests the ``traversal(...)`` method when the source is not an integer (unexpected argument).
Such a source cannot be a vertex of the maze, so PyRat raises a ``PyRatException``, as when the source does not exist.
"""
# "0" is a string, not the integer 0
with self.assertRaises(PyRatException, msg="A traversal from a string should raise an error"):
self.traverse(self.disconnected_maze, "0")
with self.assertRaises(PyRatException, msg="A traversal from None should raise an error"):
self.traverse(self.disconnected_maze, None)
##################################################################################
# TESTS (dijkstra_traversal.find_route) #
##################################################################################
def test___dijkstra_traversal_find_route___random_mazes___output_types (self) -> None:
"""
Category: normal use.
This method tests the ``find_route(...)`` method on random mazes.
It checks that the output is a list of integers.
"""
# The route should be a list of integers
for maze in self.random_mazes:
start_vertex, target_vertex = maze.get_vertices()[0], maze.get_vertices()[-1]
self.traverse(maze, start_vertex)
route = self.traversal_algorithm.find_route(target_vertex)
self.assertIsInstance(route, list, "The route should be a list")
self.assertTrue(all(isinstance(v, int) for v in route), "The route should only contain integers")
##################################################################################
def test___dijkstra_traversal_find_route___random_mazes___follows_routing_table (self) -> None:
"""
Category: normal use.
This method tests the ``find_route(...)`` method on random mazes.
It checks that the route goes from the source of the traversal to the target, following the routing table.
Since the routing table is a tree of the maze (tested above), the route is then a path in the maze with no repeated vertex.
"""
# The route starts at the source, ends at the target, and each vertex is the parent of the next one
for maze in self.random_mazes:
start_vertex, target_vertex = maze.get_vertices()[0], maze.get_vertices()[-1]
_, routing_table = self.traverse(maze, start_vertex)
route = self.traversal_algorithm.find_route(target_vertex)
self.assertEqual(route[0], start_vertex, "The route should start at the source of the traversal")
self.assertEqual(route[-1], target_vertex, "The route should end at the target vertex")
self.assertTrue(all(routing_table[route[j + 1]] == route[j] for j in range(len(route) - 1)), "Each vertex of the route should be the parent of the next one in the routing table")
##################################################################################
def test___dijkstra_traversal_find_route___random_mazes___routing_table_unchanged (self) -> None:
"""
Category: normal use.
This method tests the ``find_route(...)`` method on random mazes.
It checks that finding a route does not modify the routing table.
This is important, since the same routing table may be used to find routes to multiple targets.
"""
# The routing table should be the same before and after finding the route
for maze in self.random_mazes:
start_vertex, target_vertex = maze.get_vertices()[0], maze.get_vertices()[-1]
_, routing_table = self.traverse(maze, start_vertex)
routing_table_before = copy.deepcopy(routing_table)
self.traversal_algorithm.find_route(target_vertex)
self.assertEqual(self.traversal_algorithm.get_routing_table(), routing_table_before, "Finding a route should not modify the routing table")
##################################################################################
def test___dijkstra_traversal_find_route___tree_maze___expected_outputs (self) -> None:
"""
Category: normal use.
This method tests the ``find_route(...)`` method on the routing table of a known tree maze.
For a given routing table and target, there is a unique valid route.
"""
# Traversal of the tree maze from vertex 4 (see the ``setUpClass(...)`` method)
# Its routing table is {4: None, 1: 4, 3: 4, 7: 4, 0: 1, 2: 1, 6: 7, 8: 7, 5: 8}
self.traverse(self.tree_maze, 4)
# The route should be exactly the expected one
self.assertEqual(self.traversal_algorithm.find_route(3), [4, 3], "Wrong route to vertex 3")
self.assertEqual(self.traversal_algorithm.find_route(2), [4, 1, 2], "Wrong route to vertex 2")
self.assertEqual(self.traversal_algorithm.find_route(5), [4, 7, 8, 5], "Wrong route to vertex 5")
##################################################################################
def test___dijkstra_traversal_find_route___target_is_source___single_vertex_route (self) -> None:
"""
Category: corner case.
This method tests the ``find_route(...)`` method when the target is the source of the traversal (the root of the routing table).
The route should only contain that vertex.
"""
# Traversal of the tree maze from vertex 4 (see the ``setUpClass(...)`` method)
self.traverse(self.tree_maze, 4)
# The route should only contain the source
self.assertEqual(self.traversal_algorithm.find_route(4), [4], "The route to the source should only contain the source")
##################################################################################
def test___dijkstra_traversal_find_route___before_traversal___raises_error (self) -> None:
"""
Category: error case.
This method tests the ``find_route(...)`` method when no traversal has been performed yet.
There is no routing table to follow, so the method raises a ``RuntimeError``.
"""
# The object was just created in ``setUp(...)``
with self.assertRaises(RuntimeError, msg="Finding a route before any traversal should raise an error"):
self.traversal_algorithm.find_route(0)
##################################################################################
def test___dijkstra_traversal_find_route___target_not_reached___raises_error (self) -> None:
"""
Category: error case.
This method tests the ``find_route(...)`` method when the target was not reached by the traversal.
This happens in a disconnected maze, or when the traversal stopped early, and the method raises a ``ValueError``.
"""
# Vertex 2 cannot be reached from 0 in the disconnected maze
self.traverse(self.disconnected_maze, 0)
with self.assertRaises(ValueError, msg="Finding a route to a vertex in another component should raise an error"):
self.traversal_algorithm.find_route(2)
# Vertex 5 is not explored when the traversal stops at vertex 2 (see the tests on stop vertices)
self.traverse(self.tree_maze, 4, {2})
with self.assertRaises(ValueError, msg="Finding a route to a vertex not explored before an early stop should raise an error"):
self.traversal_algorithm.find_route(5)
##################################################################################
def test___dijkstra_traversal_find_route___unexpected_arguments___raises_error (self) -> None:
"""
Category: error case.
This method tests the ``find_route(...)`` method with a target of unexpected type.
Such a target cannot be in the routing table, so the method raises the same ``ValueError`` as for a target that was not reached.
"""
# Traversal of the tree maze from vertex 4 (see the ``setUpClass(...)`` method)
self.traverse(self.tree_maze, 4)
# "5" is a string, not the integer 5 that is in the routing table
with self.assertRaises(ValueError, msg="Finding a route to a string should raise an error"):
self.traversal_algorithm.find_route("5")
with self.assertRaises(ValueError, msg="Finding a route to None should raise an error"):
self.traversal_algorithm.find_route(None)
##########################################################################################
######################################### SCRIPT #########################################
##########################################################################################
if __name__ == "__main__":
# Run all tests
unittest.main(verbosity=2)
##########################################################################################
##########################################################################################Et ceux de la version non factorisée :
##########################################################################################
########################################## INFO ##########################################
##########################################################################################
"""
This program is a solution to the practical session 3 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session3/practical/
We have chosen to organize tests as follows:
* Methods are tested by multiple tests, to have each test focusing on a specific aspect of the method.
* Tests are named test___<tested method>___<test case>___<tested property> (this is a choice, anything named ``test_*`` is fine).
* Random mazes are created once in ``setUpClass(...)``, and shared by all tests, so that each test is as short as possible.
We basically perform two types of tests here:
* On random mazes: To make sure that the methods work as expected in various cases.
This allows to test invariants (e.g., the output is of a specific type), but not specific results.
* On manually created mazes: To make sure that the methods work as expected in specific cases.
This allows to test specific results (e.g., the output on this particular instance is equal to that specific value).
Also, tests are grouped in three categories:
* Normal use: The method is called as it is meant to be.
* Corner cases: The method is called with valid but unusual inputs (e.g., the smallest possible graph).
* Error cases: The method is called with invalid inputs, and should raise an exception.
"""
##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################
# External imports
import copy
import random
import unittest
# PyRat imports
from pyrat import Graph, RandomMaze, MazeFromDict, PyRatException
from players.dijkstra import Dijkstra
##########################################################################################
######################################### CLASSES ########################################
##########################################################################################
class Dijkstra_Tests (unittest.TestCase):
"""
*(This class inherits from* ``unittest.TestCase`` *).*
This class tests the methods of the Dijkstra class.
For each method, we test it with a few different configurations.
"""
##################################################################################
# INITIALIZATION #
##################################################################################
@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.
"""
# A 3x3 maze with no cycle (a tree), with some mud
# Whatever the order of exploration, there is a unique routing table for a given start
# [0] --- [1] ~3~ [2]
# |
# [3] --- [4] [5]
# ~2~ ~5~
# [6] --- [7] --- [8]
cls.tree_maze = MazeFromDict({0: {1: 1},
1: {0: 1, 2: 3, 4: 1},
2: {1: 3},
3: {4: 1},
4: {1: 1, 3: 1, 7: 2},
5: {8: 5},
6: {7: 1},
7: {4: 2, 6: 1, 8: 1},
8: {7: 1, 5: 5}})
# A 2x2 maze forming a single cycle, with no mud
# Dijkstra first reaches the two neighbors of the start (at distance 1), and then the opposite vertex from one of them
# [0] --- [1]
# | |
# [2] --- [3]
cls.cycle_maze = MazeFromDict({0: {1: 1, 2: 1},
1: {0: 1, 3: 1},
2: {0: 1, 3: 1},
3: {1: 1, 2: 1}})
# The same cycle, with mud between the start and one of its neighbors
# Going around the cycle is faster than crossing the mud (whereas a BFS would cross it)
# [0] ~5~ [1]
# | |
# [2] --- [3]
cls.mud_cycle_maze = MazeFromDict({0: {1: 5, 2: 1},
1: {0: 5, 3: 1},
2: {0: 1, 3: 1},
3: {1: 1, 2: 1}})
# A maze with two connected components {0, 1} and {2, 3}
# [0] --- [1]
#
# [2] --- [3]
cls.disconnected_maze = MazeFromDict({0: {1: 1},
1: {0: 1},
2: {3: 1},
3: {2: 1}})
# We use a random number generator (RNG) with a fixed seed, so that tests are reproducible
rng = random.Random(42)
# Create 100 random mazes, with no holes
# We use various sizes and densities, and add some mud so that edges do not all have weight 1
cls.random_mazes = []
for _ in range(100):
cls.random_mazes.append(RandomMaze(width=rng.randint(2, 30),
height=rng.randint(2, 30),
wall_percentage=rng.uniform(20.0, 100.0),
mud_percentage=rng.uniform(0.0, 50.0),
mud_range=(2, 10),
random_seed=rng.randint(0, 2**31 - 1)))
##################################################################################
def setUp (self) -> None:
"""
This method is called before each test method.
Here, we use it to instantiate a Dijkstra player.
"""
# Instantiate a Dijkstra player to test its methods
self.player = Dijkstra()
##################################################################################
# TESTS (dijkstra.traversal) #
##################################################################################
def test___dijkstra_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")
##################################################################################
def test___dijkstra_traversal___random_mazes___all_vertices_visited (self) -> None:
"""
Category: normal use.
This method tests the ``traversal(...)`` method on random mazes.
It checks that all vertices are visited, and appear in both outputs.
This assumes that the maze is connected, which is the case for random mazes generated by PyRat.
"""
# Both outputs should have the maze vertices as keys
for maze in self.random_mazes:
start_vertex = maze.get_vertices()[0]
distances, routing_table = self.player.traversal(maze, start_vertex)
self.assertEqual(set(distances.keys()), set(maze.get_vertices()), "Distances should be given for all vertices of the maze, and only for them")
self.assertEqual(set(routing_table.keys()), set(maze.get_vertices()), "The routing table should contain all vertices of the maze, and only them")
##################################################################################
def test___dijkstra_traversal___random_mazes___routing_table_is_spanning_tree (self) -> None:
"""
Category: normal use.
This method tests the ``traversal(...)`` method on random mazes.
It checks that the routing table is a tree, rooted at the start vertex, that only uses edges of the maze.
"""
# The start vertex is the root, all other vertices go up to it without cycle, and each parent is a neighbor in the maze
# To check this, we go up from each vertex to the root, to find all its ancestors in the tree
for maze in self.random_mazes:
start_vertex = maze.get_vertices()[0]
_, routing_table = self.player.traversal(maze, start_vertex)
ancestors = {}
for vertex in routing_table:
ancestors[vertex] = set()
ancestor = routing_table[vertex]
while ancestor is not None:
self.assertNotIn(ancestor, ancestors[vertex], f"The routing table contains a cycle (vertex {ancestor} is met twice when going up from vertex {vertex})")
ancestors[vertex].add(ancestor)
ancestor = routing_table[ancestor]
self.assertIsNone(routing_table[start_vertex], "The start vertex should have no parent in the routing table")
for vertex in routing_table.keys() - {start_vertex}:
self.assertIn(start_vertex, ancestors[vertex], f"Going up the routing table from vertex {vertex} should lead to the start vertex")
self.assertIn(routing_table[vertex], maze.get_neighbors(vertex), f"The parent of vertex {vertex} in the routing table should be one of its neighbors in the maze")
##################################################################################
def test___dijkstra_traversal___random_mazes___distances_match_routing_table (self) -> None:
"""
Category: normal use.
This method tests the ``traversal(...)`` method on random mazes.
It checks that distances are 0 for the start vertex, and strictly positive for all other vertices.
It also checks that they are increasing along the routing table, and more precisely that the distance to each vertex is the distance to its parent plus the weight of the edge between them.
Since mazes contain mud, this also checks that edge weights are taken into account.
"""
# The start vertex is at distance 0, and the distance increases by the weight of each edge in the routing table
for maze in self.random_mazes:
start_vertex = maze.get_vertices()[0]
distances, routing_table = self.player.traversal(maze, start_vertex)
self.assertEqual(distances[start_vertex], 0, "The distance to the start vertex should be 0")
for vertex in routing_table.keys() - {start_vertex}:
parent = routing_table[vertex]
self.assertGreater(distances[vertex], 0, f"The distance to vertex {vertex} should be strictly positive")
self.assertGreater(distances[vertex], distances[parent], f"The distance to vertex {vertex} should be greater than the distance to its parent {parent}")
self.assertEqual(distances[vertex], distances[parent] + maze.get_weight(parent, vertex), f"The distance to vertex {vertex} should be the distance to its parent {parent} plus the weight of the edge between them")
##################################################################################
def test___dijkstra_traversal___random_mazes___distances_are_minimal (self) -> None:
"""
Category: normal use.
This method tests the ``traversal(...)`` method on random mazes.
It checks that the distances found are the lengths of shortest paths, and not just of any path.
Previous tests would also pass with a BFS or a DFS, for instance.
Thanks to the previous tests, we know that the distance to each vertex is the length of the path given by the routing table.
Such distances are those of shortest paths if no edge allows a shortcut, i.e., if for each edge between vertices u and v, distance(v) <= distance(u) + weight(u, v).
Indeed, starting from the source, this inequality shows step by step that no path to a vertex can be shorter than its distance.
A BFS does not have this property when there is mud, since it ignores the weights when choosing the order of exploration.
"""
# No edge of the maze should allow a shortcut, in either direction
for maze in self.random_mazes:
start_vertex = maze.get_vertices()[0]
distances, _ = self.player.traversal(maze, start_vertex)
for vertex_1, vertex_2 in maze.get_edges():
weight = maze.get_weight(vertex_1, vertex_2)
self.assertLessEqual(distances[vertex_2], distances[vertex_1] + weight, f"Going to vertex {vertex_2} through vertex {vertex_1} is shorter than the distance found, which cannot happen with Dijkstra's algorithm")
self.assertLessEqual(distances[vertex_1], distances[vertex_2] + weight, f"Going to vertex {vertex_1} through vertex {vertex_2} is shorter than the distance found, which cannot happen with Dijkstra's algorithm")
##################################################################################
def test___dijkstra_traversal___random_mazes___maze_unchanged (self) -> None:
"""
Category: normal use.
This method tests the ``traversal(...)`` method on random mazes.
It checks that the traversal does not modify the maze.
"""
# The maze should be the same before and after the traversal
for maze in self.random_mazes:
start_vertex = maze.get_vertices()[0]
maze_before = copy.deepcopy(maze.as_dict())
self.player.traversal(maze, start_vertex)
self.assertEqual(maze.as_dict(), maze_before, "The traversal should not modify the maze")
##################################################################################
def test___dijkstra_traversal___fixed_mazes___expected_outputs (self) -> None:
"""
Category: normal use.
This method tests the ``traversal(...)`` method on some manually created mazes.
In general, Dijkstra's algorithm has multiple valid outputs, depending on how ties between equal distances are broken.
Here, we choose mazes for which we can list all valid outputs (see the ``setUpClass(...)`` method).
"""
# Test cases, with all valid outputs (distances, routing table) for each of them
TESTS = [{"maze": self.tree_maze,
"start": 4,
"outputs": [({4: 0, 1: 1, 3: 1, 7: 2, 0: 2, 2: 4, 6: 3, 8: 3, 5: 8},
{4: None, 1: 4, 3: 4, 7: 4, 0: 1, 2: 1, 6: 7, 8: 7, 5: 8})]},
{"maze": self.tree_maze,
"start": 0,
"outputs": [({0: 0, 1: 1, 2: 4, 4: 2, 3: 3, 7: 4, 6: 5, 8: 5, 5: 10},
{0: None, 1: 0, 2: 1, 4: 1, 3: 4, 7: 4, 6: 7, 8: 7, 5: 8})]},
{"maze": self.cycle_maze,
"start": 0,
"outputs": [({0: 0, 1: 1, 2: 1, 3: 2}, {0: None, 1: 0, 2: 0, 3: 1}),
({0: 0, 1: 1, 2: 1, 3: 2}, {0: None, 1: 0, 2: 0, 3: 2})]},
{"maze": self.mud_cycle_maze,
"start": 0,
"outputs": [({0: 0, 2: 1, 3: 2, 1: 3}, {0: None, 2: 0, 3: 2, 1: 3})]}]
# Outputs should match one of the expected ones
for test in TESTS:
outputs = self.player.traversal(test["maze"], test["start"])
self.assertIn(outputs, test["outputs"], f"Unexpected outputs for a traversal from vertex {test['start']}")
##################################################################################
def test___dijkstra_traversal___single_vertex_graph___only_source_visited (self) -> None:
"""
Category: corner case.
This method tests the ``traversal(...)`` method on the smallest possible graph, with a single vertex and no edge.
PyRat mazes need at least two cells, so we use a graph here.
"""
# Only the source should be visited
graph = Graph()
graph.add_vertex(0)
self.assertEqual(self.player.traversal(graph, 0), ({0: 0}, {0: None}), "Only the source should be visited in a graph with a single vertex")
##################################################################################
def test___dijkstra_traversal___disconnected_maze___only_component_visited (self) -> None:
"""
Category: corner case.
This method tests the ``traversal(...)`` method on a maze that is not connected.
Only the vertices that can be reached from the source should be visited.
"""
# Vertices 2 and 3 cannot be reached from 0
self.assertEqual(self.player.traversal(self.disconnected_maze, 0), ({0: 0, 1: 1}, {0: None, 1: 0}), "Only the vertices reachable from the source should be visited")
##################################################################################
def test___dijkstra_traversal___source_not_in_maze___raises_error (self) -> None:
"""
Category: error case.
This method tests the ``traversal(...)`` method when the source is not a vertex of the maze.
PyRat raises a ``PyRatException`` when asking for the neighbors of a vertex that does not exist.
"""
# Cell 9 does not exist in this maze
with self.assertRaises(PyRatException, msg="A traversal from a vertex that is not in the maze should raise an error"):
self.player.traversal(self.disconnected_maze, 9)
##################################################################################
def test___dijkstra_traversal___graph_not_a_graph___raises_error (self) -> None:
"""
Category: error case.
This method tests the ``traversal(...)`` method when the graph is not a PyRat ``Graph`` (unexpected argument).
The error is raised by Python when trying to call ``get_neighbors(...)`` on an object that does not have this method.
"""
# None and a dictionary do not have a get_neighbors(...) method
with self.assertRaises(AttributeError, msg="A traversal of None should raise an error"):
self.player.traversal(None, 0)
with self.assertRaises(AttributeError, msg="A traversal of a dictionary should raise an error, even if it describes a graph"):
self.player.traversal({0: {1: 1}, 1: {0: 1}}, 0)
##################################################################################
def test___dijkstra_traversal___source_wrong_type___raises_error (self) -> None:
"""
Category: error case.
This method tests the ``traversal(...)`` method when the source is not an integer (unexpected argument).
Such a source cannot be a vertex of the maze, so PyRat raises a ``PyRatException``, as when the source does not exist.
"""
# "0" is a string, not the integer 0
with self.assertRaises(PyRatException, msg="A traversal from a string should raise an error"):
self.player.traversal(self.disconnected_maze, "0")
with self.assertRaises(PyRatException, msg="A traversal from None should raise an error"):
self.player.traversal(self.disconnected_maze, None)
##################################################################################
# TESTS (dijkstra.find_route) #
##################################################################################
def test___dijkstra_find_route___random_mazes___output_types (self) -> None:
"""
Category: normal use.
This method tests the ``find_route(...)`` method on random mazes.
It checks that the output is a list of integers.
"""
# The route should be a list of integers
for maze in self.random_mazes:
start_vertex, target_vertex = maze.get_vertices()[0], maze.get_vertices()[-1]
_, routing_table = self.player.traversal(maze, start_vertex)
route = self.player.find_route(routing_table, start_vertex, target_vertex)
self.assertIsInstance(route, list, "The route should be a list")
self.assertTrue(all(isinstance(v, int) for v in route), "The route should only contain integers")
##################################################################################
def test___dijkstra_find_route___random_mazes___follows_routing_table (self) -> None:
"""
Category: normal use.
This method tests the ``find_route(...)`` method on random mazes.
It checks that the route goes from the start to the target, following the routing table.
Since the routing table is a tree of the maze (tested above), the route is then a path in the maze with no repeated vertex.
"""
# The route starts at the start, ends at the target, and each vertex is the parent of the next one
for maze in self.random_mazes:
start_vertex, target_vertex = maze.get_vertices()[0], maze.get_vertices()[-1]
_, routing_table = self.player.traversal(maze, start_vertex)
route = self.player.find_route(routing_table, start_vertex, target_vertex)
self.assertEqual(route[0], start_vertex, "The route should start at the start vertex")
self.assertEqual(route[-1], target_vertex, "The route should end at the target vertex")
self.assertTrue(all(routing_table[route[j + 1]] == route[j] for j in range(len(route) - 1)), "Each vertex of the route should be the parent of the next one in the routing table")
##################################################################################
def test___dijkstra_find_route___random_mazes___routing_table_unchanged (self) -> None:
"""
Category: normal use.
This method tests the ``find_route(...)`` method on random mazes.
It checks that finding a route does not modify the routing table.
This is important, since the same routing table may be used to find routes to multiple targets.
"""
# The routing table should be the same before and after finding the route
for maze in self.random_mazes:
start_vertex, target_vertex = maze.get_vertices()[0], maze.get_vertices()[-1]
_, routing_table = self.player.traversal(maze, start_vertex)
routing_table_before = copy.deepcopy(routing_table)
self.player.find_route(routing_table, start_vertex, target_vertex)
self.assertEqual(routing_table, routing_table_before, "Finding a route should not modify the routing table")
##################################################################################
def test___dijkstra_find_route___fixed_routing_table___expected_outputs (self) -> None:
"""
Category: normal use.
This method tests the ``find_route(...)`` method on a manually created routing table.
For a given routing table, source and target, there is a unique valid route.
"""
# Routing table obtained with a traversal of the tree maze from vertex 4 (see the ``setUpClass(...)`` method)
routing_table = {4: None, 1: 4, 3: 4, 7: 4, 0: 1, 2: 1, 6: 7, 8: 7, 5: 8}
# The route should be exactly the expected one
self.assertEqual(self.player.find_route(routing_table, 4, 3), [4, 3], "Wrong route from vertex 4 to vertex 3")
self.assertEqual(self.player.find_route(routing_table, 4, 2), [4, 1, 2], "Wrong route from vertex 4 to vertex 2")
self.assertEqual(self.player.find_route(routing_table, 4, 5), [4, 7, 8, 5], "Wrong route from vertex 4 to vertex 5")
##################################################################################
def test___dijkstra_find_route___source_is_target___single_vertex_route (self) -> None:
"""
Category: corner case.
This method tests the ``find_route(...)`` method when the source and the target are the same vertex.
The route should only contain that vertex, whether it is the root of the routing table or not.
"""
# Routing table obtained with a traversal of the tree maze from vertex 4 (see the ``setUpClass(...)`` method)
routing_table = {4: None, 1: 4, 3: 4, 7: 4, 0: 1, 2: 1, 6: 7, 8: 7, 5: 8}
# The route should only contain the source
self.assertEqual(self.player.find_route(routing_table, 4, 4), [4], "The route from the root to itself should only contain the root")
self.assertEqual(self.player.find_route(routing_table, 7, 7), [7], "The route from a vertex to itself should only contain that vertex, even if it is not the root")
##################################################################################
def test___dijkstra_find_route___source_is_not_root___partial_route (self) -> None:
"""
Category: corner case.
This method tests the ``find_route(...)`` method when the source is not the root of the routing table, but is an ancestor of the target.
The route should stop at the source, and not go up to the root.
"""
# Routing table obtained with a traversal of the tree maze from vertex 4 (see the ``setUpClass(...)`` method)
routing_table = {4: None, 1: 4, 3: 4, 7: 4, 0: 1, 2: 1, 6: 7, 8: 7, 5: 8}
# The route should start at the source
self.assertEqual(self.player.find_route(routing_table, 1, 2), [1, 2], "The route from vertex 1 to vertex 2 should start at vertex 1, not at the root")
self.assertEqual(self.player.find_route(routing_table, 7, 5), [7, 8, 5], "The route from vertex 7 to vertex 5 should start at vertex 7, not at the root")
##################################################################################
def test___dijkstra_find_route___source_not_in_routing_table___raises_error (self) -> None:
"""
Category: error case.
This method tests the ``find_route(...)`` method when the source is not in the routing table.
Going up from the target, the root is reached without meeting the source, and its parent (None) is not in the routing table.
"""
# Routing table obtained with a traversal of the tree maze from vertex 4 (see the ``setUpClass(...)`` method)
routing_table = {4: None, 1: 4, 3: 4, 7: 4, 0: 1, 2: 1, 6: 7, 8: 7, 5: 8}
# Vertex 9 is not in the routing table
with self.assertRaises(KeyError, msg="Finding a route from a vertex that is not in the routing table should raise an error"):
self.player.find_route(routing_table, 9, 5)
##################################################################################
def test___dijkstra_find_route___target_not_in_routing_table___raises_error (self) -> None:
"""
Category: error case.
This method tests the ``find_route(...)`` method when the target is not in the routing table.
This happens when the target was not reached by the traversal, e.g., in a disconnected maze.
"""
# Routing table obtained with a traversal of the tree maze from vertex 4 (see the ``setUpClass(...)`` method)
routing_table = {4: None, 1: 4, 3: 4, 7: 4, 0: 1, 2: 1, 6: 7, 8: 7, 5: 8}
# Vertex 9 is not in the routing table
with self.assertRaises(KeyError, msg="Finding a route to a vertex that is not in the routing table should raise an error"):
self.player.find_route(routing_table, 4, 9)
##################################################################################
def test___dijkstra_find_route___unexpected_arguments___raises_error (self) -> None:
"""
Category: error case.
This method tests the ``find_route(...)`` method with arguments of unexpected types.
"""
# Routing table obtained with a traversal of the tree maze from vertex 4 (see the ``setUpClass(...)`` method)
routing_table = {4: None, 1: 4, 3: 4, 7: 4, 0: 1, 2: 1, 6: 7, 8: 7, 5: 8}
# None is not a routing table, and "5" is a string, not the integer 5 that is in the routing table
with self.assertRaises(TypeError, msg="Finding a route in None should raise an error"):
self.player.find_route(None, 4, 5)
with self.assertRaises(KeyError, msg="Finding a route to a string should raise an error"):
self.player.find_route(routing_table, 4, "5")
##################################################################################
def test___dijkstra_find_route___invalid_routing_table___raises_error (self) -> None:
"""
Category: error case.
This method tests the ``find_route(...)`` method with a routing table that cannot be the output of a traversal.
Here, a vertex has a parent that is not in the routing table.
Note that a routing table with a cycle (e.g., ``{1: 2, 2: 1}``) would make the method loop forever, so we do not test that case.
"""
# The parent of vertex 1 is vertex 5, which is not in the routing table
with self.assertRaises(KeyError, msg="Finding a route with a parent that is not in the routing table should raise an error"):
self.player.find_route({0: None, 1: 5}, 0, 1)
##################################################################################
def test___dijkstra_find_route___source_not_ancestor_of_target___raises_error (self) -> None:
"""
Category: error case.
This method tests the ``find_route(...)`` method when the source is not an ancestor of the target in the routing table.
In that case, there is no route to follow from the source to the target.
"""
# Routing table obtained with a traversal of the tree maze from vertex 4 (see the ``setUpClass(...)`` method)
routing_table = {4: None, 1: 4, 3: 4, 7: 4, 0: 1, 2: 1, 6: 7, 8: 7, 5: 8}
# Vertex 3 is in another branch than vertex 5
with self.assertRaises(KeyError, msg="Finding a route from a vertex that is not an ancestor of the target should raise an error"):
self.player.find_route(routing_table, 3, 5)
##########################################################################################
######################################### SCRIPT #########################################
##########################################################################################
if __name__ == "__main__":
# Run all tests
unittest.main(verbosity=2)
##########################################################################################
##########################################################################################À quoi ça ressemble ?
À présent, utilisez votre script de visualisation pour observer votre joueur. La vidéo suivante montre un exemple de ce que vous devriez observer :
Notez que le rat a volontairement évité la boue car le nombre de tours nécessaires pour l’esquiver est inférieur au nombre de tours nécessaires pour la traverser.
Comparer avec les autres parcours
Lors des séances précédentes, vous avez comparé vos joueurs en les faisant jouer un grand nombre de parties, puis en comparant leurs nombres de tours moyens. Maintenant que vous avez un joueur de plus, il est tentant de recommencer en l’ajoutant simplement à la liste. Mais une comparaison n’est utile que si elle répond à une question précise, et une bonne comparaison se prépare.
À faire
Avant d’écrire votre script, réfléchissez aux questions suivantes. Écrivez ensuite un script qui met en œuvre la comparaison que vous avez choisie.
-
Quels joueurs comparer ? Est-il utile de comparer à nouveau Dijkstra aux joueurs aléatoires, ou au DFS ? Quelle est la comparaison qui vous apprendra vraiment quelque chose ?
-
Que sait-on déjà du résultat ? D’après le cours, certaines propriétés doivent être vraies sur chaque labyrinthe, et pas seulement en moyenne. Lesquelles ? Comment vérifier qu’elles sont bien respectées, plutôt que de le supposer ?
-
Que mesurer ? Le nombre de tours est-il la seule mesure intéressante ? Que gagne-t-on en utilisant Dijkstra, et que perd-on ? Pour compter les cases traversées, notez que
stats["players"][name]["actions"]donne le nombre de déplacements effectués dans chaque direction. -
Sur quels labyrinthes ? Que gagne-t-on à faire jouer tous les joueurs sur les mêmes labyrinthes ? Quel paramètre du jeu faire varier pour voir quand Dijkstra fait vraiment la différence ?
Correction
Cliquez ici pour afficher la correction.
La première idée est de reprendre le script des séances précédentes, en y ajoutant simplement le joueur Dijkstra, et en mettant de la boue dans les labyrinthes. Ce script 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 3 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session3/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
from players.dijkstra import Dijkstra
##########################################################################################
######################################### 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": 30.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(), Dijkstra()]
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_weighted.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 'DFS' and of program 'BFS':
MannwhitneyuResult(statistic=np.float64(942846.0), pvalue=np.float64(8.965401864417458e-258))
Mann-Whitney U test between turns of program 'DFS' and of program 'Dijkstra':
MannwhitneyuResult(statistic=np.float64(959817.0), pvalue=np.float64(9.410337210363598e-278))
Mann-Whitney U test between turns of program 'BFS' and of program 'Dijkstra':
MannwhitneyuResult(statistic=np.float64(585881.0), pvalue=np.float64(2.8689460106101822e-11))On voit bien que Dijkstra prend en moyenne moins de tours que BFS, et que la différence est significative. Mais cette comparaison reste assez pauvre : elle noie la comparaison intéressante parmi des dizaines d’autres, ne vérifie aucune propriété attendue, ne dit pas dans quelles conditions Dijkstra fait la différence, et ne mesure pas ce qu’il coûte. Les questions ci-dessus permettent d’aller plus loin.
Quelques éléments de réponse :
-
Les joueurs aléatoires et le DFS sont déjà moins bons que le BFS : la comparaison intéressante est BFS contre Dijkstra.
-
Dijkstra trouve le chemin le plus rapide, donc il ne peut jamais prendre plus de tours que BFS sur un labyrinthe donné. À l’inverse, BFS trouve le chemin qui comporte le moins de cases, donc Dijkstra ne peut jamais en traverser moins. Sans boue, les deux joueurs doivent même mettre le même nombre de tours, et traverser le même nombre de cases (mais pas forcément par le même chemin, s’il y a plusieurs plus courts chemins). Ces propriétés se vérifient labyrinthe par labyrinthe : une seule exception révélerait un bug.
-
On mesure le nombre de tours (ce que Dijkstra gagne), mais aussi le nombre de cases traversées (ce qu’il paie pour éviter la boue).
-
Faire jouer les deux joueurs sur les mêmes labyrinthes (mêmes
random_seed) permet de les comparer labyrinthe par labyrinthe, et donc de vérifier les propriétés ci-dessus. Faire varier le pourcentage de boue permet de voir dans quelles conditions Dijkstra fait la différence.
Voici un script qui met en œuvre cette comparaison :
##########################################################################################
########################################## INFO ##########################################
##########################################################################################
"""
This program is a solution to the practical session 3 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session3/practical/
It compares BFS and Dijkstra on the same mazes, for several percentages of mud.
Rather than comparing average numbers of turns, it compares the two players maze by maze, which allows to:
* Check a property that must hold on every maze (Dijkstra is never slower than BFS).
* Measure how often, and by how much, Dijkstra is faster.
* Use a paired statistical test, which is more powerful than comparing two independent samples.
"""
##########################################################################################
######################################### 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.traversal_player import TraversalPlayer
from utils.traversal.bfs_traversal import BFSTraversal
from utils.traversal.dijkstra_traversal import DijkstraTraversal
##########################################################################################
######################################### SCRIPT #########################################
##########################################################################################
if __name__ == "__main__":
# Number of mazes per percentage of mud, and percentages of mud to study
# With 0% of mud, both players should behave identically, which is a good sanity check
nb_games = 200
mud_percentages = [0.0, 10.0, 20.0, 30.0, 40.0, 50.0]
# Customize the game elements
game_config = {"nb_cheese": 1,
"game_mode": GameMode.SIMULATION}
# The players to compare
# Random players and DFS are left out, as we already know they are worse than BFS
# A new traversal object is created for each game, as a traversal stores its last results
algorithms = {"BFS": BFSTraversal,
"Dijkstra": DijkstraTraversal}
# For each percentage of mud, both players play the same mazes (same random seeds)
# We store the number of turns needed to catch the cheese, and the number of cells traversed
results = {}
for mud_percentage in mud_percentages:
results[mud_percentage] = {name: {"turns": [], "moves": []} for name in algorithms}
for seed in tqdm.tqdm(range(nb_games), desc="%d%% of mud" % mud_percentage):
for name, algorithm in algorithms.items():
# Play the game
game = Game(random_seed=seed, mud_percentage=mud_percentage, **game_config)
game.add_player(TraversalPlayer(algorithm(), name=name))
stats = game.start()
# Store the results
actions = stats["players"][name]["actions"]
results[mud_percentage][name]["turns"].append(stats["turns"])
results[mud_percentage][name]["moves"].append(sum(actions[direction] for direction in ["north", "south", "east", "west"]))
# Analysis, maze by maze, for each percentage of mud
share_faster = []
mean_gain = []
mean_extra_moves = []
for mud_percentage in mud_percentages:
# Differences between both players on each maze
bfs, dijkstra = results[mud_percentage]["BFS"], results[mud_percentage]["Dijkstra"]
gains = [b - d for b, d in zip(bfs["turns"], dijkstra["turns"])]
extra_moves = [d - b for b, d in zip(bfs["moves"], dijkstra["moves"])]
# Properties that must hold on every maze
# Dijkstra finds the fastest route, so it can never take more turns than BFS
# BFS finds the route with the fewest cells, so Dijkstra can never traverse fewer cells
nb_slower = len([gain for gain in gains if gain < 0])
nb_fewer_moves = len([extra for extra in extra_moves if extra < 0])
# How often, and by how much, Dijkstra is faster
gains_when_faster = [gain for gain in gains if gain > 0]
share_faster.append(100.0 * len(gains_when_faster) / nb_games)
mean_gain.append(sum(gains_when_faster) / len(gains_when_faster) if gains_when_faster else 0.0)
mean_extra_moves.append(sum(extra_moves) / nb_games)
# Paired test, as both players played the same mazes
# It cannot be computed if both players are always equal
if any(gains):
test_result = scstats.wilcoxon(bfs["turns"], dijkstra["turns"], alternative="greater")
p_value = "%.2e" % test_result.pvalue
else:
p_value = "not computable (identical results)"
# Report
print("%d%% of mud:" % mud_percentage)
print(" Mazes where Dijkstra is slower than BFS (should be 0): %d" % nb_slower)
print(" Mazes where Dijkstra traverses fewer cells than BFS (should be 0): %d" % nb_fewer_moves)
print(" Mazes where Dijkstra is strictly faster: %.1f%%" % share_faster[-1])
print(" Turns saved when Dijkstra is faster: %.2f on average" % mean_gain[-1])
print(" Extra cells traversed by Dijkstra: %.2f on average" % mean_extra_moves[-1])
print(" Wilcoxon signed-rank test (BFS takes more turns than Dijkstra): p-value = %s" % p_value)
# Visualization
figure, axes = pyplot.subplots(1, 2, figsize=(11, 4.5))
axes[0].plot(mud_percentages, share_faster, marker="o")
axes[0].set_title("Mazes where Dijkstra is strictly faster than BFS")
axes[0].set_xlabel("Percentage of mud")
axes[0].set_ylabel("% of mazes")
axes[1].plot(mud_percentages, mean_gain, marker="o", label="Turns saved when Dijkstra is faster")
axes[1].plot(mud_percentages, mean_extra_moves, marker="s", label="Extra cells traversed by Dijkstra")
axes[1].set_title("What Dijkstra saves, and what it costs")
axes[1].set_xlabel("Percentage of mud")
axes[1].set_ylabel("Average over the mazes")
axes[1].legend()
figure.tight_layout()
pyplot.savefig("compare_bfs_dijkstra.png")
##########################################################################################
##########################################################################################Et voici sa sortie :

0% of mud:
Mazes where Dijkstra is slower than BFS (should be 0): 0
Mazes where Dijkstra traverses fewer cells than BFS (should be 0): 0
Mazes where Dijkstra is strictly faster: 0.0%
Turns saved when Dijkstra is faster: 0.00 on average
Extra cells traversed by Dijkstra: 0.00 on average
Wilcoxon signed-rank test (BFS takes more turns than Dijkstra): p-value = not computable (identical results)
10% of mud:
Mazes where Dijkstra is slower than BFS (should be 0): 0
Mazes where Dijkstra traverses fewer cells than BFS (should be 0): 0
Mazes where Dijkstra is strictly faster: 33.0%
Turns saved when Dijkstra is faster: 5.50 on average
Extra cells traversed by Dijkstra: 0.73 on average
Wilcoxon signed-rank test (BFS takes more turns than Dijkstra): p-value = 7.56e-13
20% of mud:
Mazes where Dijkstra is slower than BFS (should be 0): 0
Mazes where Dijkstra traverses fewer cells than BFS (should be 0): 0
Mazes where Dijkstra is strictly faster: 49.0%
Turns saved when Dijkstra is faster: 7.02 on average
Extra cells traversed by Dijkstra: 1.32 on average
Wilcoxon signed-rank test (BFS takes more turns than Dijkstra): p-value = 3.93e-18
30% of mud:
Mazes where Dijkstra is slower than BFS (should be 0): 0
Mazes where Dijkstra traverses fewer cells than BFS (should be 0): 0
Mazes where Dijkstra is strictly faster: 58.0%
Turns saved when Dijkstra is faster: 7.62 on average
Extra cells traversed by Dijkstra: 1.54 on average
Wilcoxon signed-rank test (BFS takes more turns than Dijkstra): p-value = 4.17e-21
40% of mud:
Mazes where Dijkstra is slower than BFS (should be 0): 0
Mazes where Dijkstra traverses fewer cells than BFS (should be 0): 0
Mazes where Dijkstra is strictly faster: 56.5%
Turns saved when Dijkstra is faster: 7.94 on average
Extra cells traversed by Dijkstra: 1.54 on average
Wilcoxon signed-rank test (BFS takes more turns than Dijkstra): p-value = 1.30e-20
50% of mud:
Mazes where Dijkstra is slower than BFS (should be 0): 0
Mazes where Dijkstra traverses fewer cells than BFS (should be 0): 0
Mazes where Dijkstra is strictly faster: 61.0%
Turns saved when Dijkstra is faster: 6.93 on average
Extra cells traversed by Dijkstra: 1.28 on average
Wilcoxon signed-rank test (BFS takes more turns than Dijkstra): p-value = 4.11e-22On peut en tirer les conclusions suivantes :
-
Les propriétés attendues sont vérifiées sur tous les labyrinthes : sans boue, les deux joueurs mettent le même nombre de tours et traversent le même nombre de cases, et avec de la boue, Dijkstra n’est jamais plus lent que BFS (en nombre de tours).
-
Plus il y a de boue, plus Dijkstra fait souvent la différence : d’un labyrinthe sur trois avec 10% de boue, à plus d’un sur deux à partir de 30%. Dans les autres labyrinthes, le chemin le plus court en cases est aussi le plus rapide (il ne traverse pas de boue, ou la boue est inévitable).
-
Quand Dijkstra est plus rapide, il fait gagner 5,5 à 8 tours en moyenne. En contrepartie, en moyenne sur l’ensemble des labyrinthes (y compris ceux où il n’est pas plus rapide), Dijkstra traverse entre 0,7 et 1,5 case de plus que BFS. Attention, les deux courbes du graphique de droite ne sont donc pas moyennées sur les mêmes labyrinthes : les tours gagnés le sont sur les labyrinthes où Dijkstra est strictement plus rapide, et les cases supplémentaires sur tous les labyrinthes. Le gain en tours ne croît plus au-delà de 40% de boue : une explication possible est que la boue devient alors difficile à éviter, même pour Dijkstra.
-
Les p-values très faibles confirment que la différence est statistiquement significative dès 10% de boue. Le script utilise le test de Wilcoxon plutôt que celui de Mann-Whitney, car les deux joueurs jouent sur les mêmes labyrinthes (voir la section « Pour aller encore plus loin » de la séance 1). Mais ici, les vérifications labyrinthe par labyrinthe sont plus parlantes qu’un test : elles montrent à la fois que Dijkstra est meilleur, et quand il l’est.
Pour aller plus loin
Comparer deux implémentations de la file de priorité
La complexité de l’algorithme de Dijkstra dépend de la file de priorité utilisée (voir la section sur la complexité dans l’article sur l’algorithme de Dijkstra). Avec un tas min comme celui de heapq, elle est de $O(n \cdot log(n))$ dans un labyrinthe PyRat. Avec une simple liste non triée, dans laquelle on cherche le minimum à chaque extraction, elle est de $O(n^2)$ dans le pire des cas.
Grâce à la factorisation, essayer une autre structure de données revient simplement à créer une nouvelle sous-classe de Traversal. Profitons-en pour vérifier en pratique ce que dit la théorie !
À faire
-
Créez une classe
ListDijkstraTraversal, héritant deTraversal, dont la structure est une liste non triée. L’ajout d’un élément se fait à la fin de la liste, et l’extraction parcourt toute la liste pour trouver l’élément de plus petite distance. Vous pouvez vous inspirer de la classeListBasedMinHeapprésentée dans l’article sur les tas min. -
Écrivez un script qui mesure, pour des labyrinthes de taille croissante, le temps moyen d’un parcours complet avec
DijkstraTraversalet avecListDijkstraTraversal. Vérifiez au passage que les deux versions trouvent bien les mêmes distances. -
Tracez ces temps en fonction du nombre de cases, en échelle log-log. Dans cette échelle, la pente d’une courbe donne l’exposant $k$ d’une durée en $O(n^k)$. Les pentes obtenues correspondent-elles à la théorie ?
Information
Quelques indications :
- La fonction
time.perf_counter()permet de mesurer précisément une durée. - La génération de grands labyrinthes est lente. Plutôt que de générer beaucoup de labyrinthes, générez-en un par taille, et répétez plusieurs fois le parcours pour en moyenner la durée.
- La classe
RandomMazede PyRat permet de créer un labyrinthe rectangulaire sans lancer de partie. Son constructeur attend les argumentswidth,height,wall_percentageetmud_percentage(ces deux derniers étant des nombres réels), ainsi quemud_rangelorsqu’il y a de la boue (par exemple,mud_range=[4, 9]). Un argumentrandom_seedoptionnel permet de toujours obtenir le même labyrinthe.
Correction
Cliquez ici pour afficher la correction.
Grâce à la factorisation, il suffit d’ajouter une nouvelle sous-classe de Traversal, qui ne définit que sa structure de données et les quatre méthodes qui la gèrent, comme DijkstraTraversal. Le script de mesure utilise directement les deux classes de parcours : il n’est donc pas nécessaire de modifier TraversalPlayer. Voici le diagramme de classes complété :
Et voici la nouvelle classe, et un script qui effectue les mesures :
##########################################################################################
########################################## INFO ##########################################
##########################################################################################
"""
This program is a solution to the practical session 3 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session3/practical/
"""
##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################
# PyRat imports
from utils.traversal.traversal import Traversal
##########################################################################################
######################################### CLASSES ########################################
##########################################################################################
class ListDijkstraTraversal (Traversal):
"""
This class implements Dijkstra's traversal algorithm by defining the abstract methods from the parent class.
Contrary to ``DijkstraTraversal``, the priority queue is a plain unsorted list, in which we look for the minimum each time an element is extracted.
It finds the same routes, and is only meant to be compared with ``DijkstraTraversal`` in terms of computation time.
"""
##################################################################################
# CONSTRUCTOR #
##################################################################################
def __init__ ( self,
*args: object,
**kwargs: object
) -> None:
"""
*(This class inherits from* ``Traversal`` *).*
It implements Dijkstra's traversal algorithm by defining the abstract methods from the parent class.
The priority queue is a plain unsorted list.
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)
# Unsorted list of the elements to visit, created by initialize_structure
self.unsorted_list = 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 ``unsorted_list`` attribute.
Here, we use an unsorted list.
"""
# We start with an empty list
self.unsorted_list = []
##################################################################################
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 ``unsorted_list`` attribute.
Here, we simply append the element at the end of the list, which takes a constant time.
Args:
element: The element to add, as a tuple (distance, vertex, parent).
"""
# We append the element to the structure
self.unsorted_list.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 ``unsorted_list`` attribute.
Here, we go through the whole list to find the element with the smallest distance, which takes a time proportional to the size of the list.
Returns:
The extracted element, as a tuple (distance, vertex, parent).
"""
# We find the smallest element, and remove it from the list
min_index = min(range(len(self.unsorted_list)), key=lambda i: self.unsorted_list[i])
return self.unsorted_list.pop(min_index)
##################################################################################
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 ``unsorted_list`` attribute contains no more elements to extract.
Here, the structure is empty when the list has no element.
Returns:
True if the data structure is empty, False otherwise.
"""
# The structure is empty when the list has no element
return len(self.unsorted_list) == 0
##########################################################################################
####################################################################################################################################################################################
########################################## INFO ##########################################
##########################################################################################
"""
This program is a solution to the practical session 3 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session3/practical/
It measures the computation time of Dijkstra's algorithm with two implementations of the priority queue:
* ``DijkstraTraversal``, which uses a binary heap (``heapq``).
* ``ListDijkstraTraversal``, which uses an unsorted list.
Both are run on the same mazes of increasing sizes, and must find the same distances.
The slope of each curve in log-log scale is then compared with the complexity studied in the course.
"""
##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################
# External imports
import time
import numpy
import tqdm.auto as tqdm
import matplotlib.pyplot as pyplot
# PyRat imports
from pyrat import RandomMaze
from utils.traversal.dijkstra_traversal import DijkstraTraversal
from utils.traversal.list_dijkstra_traversal import ListDijkstraTraversal
##########################################################################################
######################################### SCRIPT #########################################
##########################################################################################
if __name__ == "__main__":
# Maze sizes to study (square mazes)
# Generating large mazes takes a lot of time, so we use one maze per size, and repeat each traversal a few times instead
sizes = [10, 20, 30, 40, 50, 60, 70, 80]
nb_repeats = 5
# Customize the maze elements
# We use mazes with no holes, so that the number of cells is exactly the square of the size
maze_config = {"wall_percentage": 60.0,
"mud_percentage": 20.0,
"mud_range": [4, 9]}
# The traversals to compare
traversals = {"heapq": DijkstraTraversal(),
"Unsorted list": ListDijkstraTraversal()}
# Measure the average time of a complete traversal, for each size
nb_cells = []
durations = {name: [] for name in traversals}
for size in tqdm.tqdm(sizes):
# Create a maze, that will be traversed from its first cell
maze = RandomMaze(width=size, height=size, random_seed=size, **maze_config)
source = maze.get_vertices()[0]
nb_cells.append(len(maze.get_vertices()))
# Time each traversal
for name, traversal_algorithm in traversals.items():
start = time.perf_counter()
for _ in range(nb_repeats):
traversal_algorithm.traversal(maze, source)
durations[name].append((time.perf_counter() - start) / nb_repeats)
# Both implementations must find the same distances
assert traversals["heapq"].get_distances() == traversals["Unsorted list"].get_distances(), f"The heapq and unsorted list traversals found different distances on the maze of size {size}x{size}"
# The slope of a curve in log-log scale gives the exponent k of a duration in O(n^k)
for name in traversals:
slope = numpy.polyfit(numpy.log(nb_cells[2:]), numpy.log(durations[name][2:]), 1)[0]
print("%s: duration in O(n^%.2f) on these mazes" % (name, slope))
print("Ratio between both durations on the largest mazes: %.1f" % (durations["Unsorted list"][-1] / durations["heapq"][-1]))
# Visualization
pyplot.figure(figsize=(7, 4.5))
for name in traversals:
pyplot.plot(nb_cells, durations[name], marker="o", label=name)
pyplot.title("Duration of a complete Dijkstra traversal")
pyplot.xlabel("Number of cells in the maze")
pyplot.ylabel("Duration (s)")
pyplot.xscale("log")
pyplot.yscale("log")
pyplot.legend()
pyplot.tight_layout()
pyplot.savefig("measure_priority_queues.png")
##########################################################################################
##########################################################################################Et voici sa sortie :

heapq: duration in O(n^1.04) on these mazes
Unsorted list: duration in O(n^1.51) on these mazes
Ratio between both durations on the largest mazes: 10.5On peut en tirer les conclusions suivantes :
-
Avec
heapq, la pente est proche de 1, ce qui est cohérent avec une complexité en $O(n \cdot log(n))$ : sur ces tailles, le facteur $log(n)$ est presque invisible. -
Avec la liste non triée, la durée croît nettement plus vite, et l’écart se creuse avec la taille du labyrinthe (un facteur 10 pour 6400 cases). La pente est pourtant d’environ 1,5, et non de 2. En effet, $O(n^2)$ est une borne dans le pire des cas : la liste ne contient à chaque instant que les sommets « en bordure » de la zone déjà explorée, et dans un labyrinthe, cette bordure reste petite par rapport au nombre total de cases. Une complexité théorique dit comment un algorithme se comporte au pire, et la mesure dit comment il se comporte sur les données réelles : les deux sont utiles.
-
Pour les labyrinthes de taille par défaut (15×13 avec 80% de cases, soit environ 156 cases), les deux versions mettent moins d’une milliseconde. Le choix de la structure n’a donc d’importance que pour de grands graphes, ou si l’algorithme doit être appelé de très nombreuses fois (ce qui arrivera dans les séances suivantes !).
Pour aller encore plus loin
L’algorithme de Floyd-Warshall
L’algorithme de Dijkstra est ce que nous appelons un algorithme « 1-to-* ». Cela signifie qu’il trouvera les chemins les plus courts d’une position initiale unique à toutes les autres positions du graphe.
L’algorithme de Floyd-Warshall est ce que nous appelons un algorithme « *-to-* ». Il calculera simultanément tous les chemins les plus courts de tous les sommets à tous les sommets.
À 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 dans le graphe (cases du labyrinthe).
Dans un labyrinthe PyRat, l’algorithme de Dijkstra a une complexité de $O(n \cdot log(n))$. Par conséquent, si nous l’exécutons depuis chaque position possible ($n$ fois), nous obtenons une complexité de $O(n^2 \cdot log(n))$.
Comme l’algorithme de Floyd-Warshall a une complexité de $O(n^3)$, utiliser plusieurs fois l’algorithme de Dijkstra est préférable.
À faire
Essayez d’implémenter cet algorithme (ou cherchez une bibliothèque qui le fait).
Correction
Cliquez ici pour afficher la correction.
Voici le diagramme de classes d’un joueur FloydWarshall utilisant cet algorithme. Comme les plus courts chemins sont connus depuis toutes les cases, il se dirige vers le morceau de fromage le plus proche, puis vers le suivant, sans nouveau calcul (cette stratégie est un algorithme glouton, que vous étudierez en détail lors de la séance 5) :
Et voici son code, ainsi qu’un script de jeu pour le visualiser, qui utilise donc plusieurs morceaux de fromage :
##########################################################################################
########################################## INFO ##########################################
##########################################################################################
"""
This program is a solution to the practical session 3 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session3/practical/
"""
##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################
# PyRat imports
from pyrat import Player, Maze, GameState, Action, Graph
##########################################################################################
######################################### CLASSES ########################################
##########################################################################################
class FloydWarshall (Player):
"""
*(This class inherits from* ``Player`` *).*
This player performs Floyd-Warshall's algorithm to find the shortest paths between all pairs of vertices in the maze.
Computation of the paths is done in the ``preprocessing(...)`` method.
Since shortest paths are known from every location, the player heads to the closest piece of cheese, and retargets as soon as it is eaten, without any new computation.
The path to the current target is 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 attributes to store the results of Floyd-Warshall's algorithm
self.distances = None
self.routing_tables = None
# 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 Floyd-Warshall's algorithm to compute the shortest paths between all pairs of vertices.
The results are stored in the ``distances`` and ``routing_tables`` attributes, and will be used in the ``turn(...)`` method.
We also compute the actions leading to the closest piece of cheese, and store them in the ``actions`` attribute.
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
# Contrary to Dijkstra's algorithm, this gives us the shortest paths from all vertices, not only from our initial location
self.distances, self.routing_tables = self.traversal(maze)
# Find the series of locations/actions to go from the player location to the closest piece of cheese
my_location = game_state.player_locations[self.get_name()]
self.actions = self.actions_to_closest_cheese(maze, my_location, game_state.cheese)
##################################################################################
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 to the current target.
When that path is over, the target has been eaten, and we head to the closest remaining piece of cheese.
Since Floyd-Warshall's algorithm already gave us the shortest paths from our new location, this requires no new computation.
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.
"""
# If there is no action left, we have reached our target, so we pick a new one
if len(self.actions) == 0:
my_location = game_state.player_locations[self.get_name()]
self.actions = self.actions_to_closest_cheese(maze, my_location, game_state.cheese)
# If there is still nothing to do (no more cheese), we do not move
if len(self.actions) == 0:
return Action.NOTHING
# Otherwise, we perform the next action in the list of actions
return self.actions.pop(0)
##################################################################################
# OTHER METHODS #
##################################################################################
def actions_to_closest_cheese ( self,
maze: Maze,
source: int,
cheese: list[int]
) -> list[Action]:
"""
This method uses the results of Floyd-Warshall's algorithm to find the actions leading from a source vertex to the closest piece of cheese.
Args:
maze: An object representing the maze in which the player plays.
source: The vertex from which to start.
cheese: The locations of the remaining pieces of cheese.
Returns:
The list of actions to perform to reach the closest piece of cheese (empty if there is no cheese left).
"""
# No cheese left, nothing to do
if len(cheese) == 0:
return []
# The distances from the source to all vertices are already known
# We use them to find the closest piece of cheese
target = min(cheese, key=lambda location: self.distances[source][location])
# Find the series of locations/actions to go from the source to the target
path = self.find_route(self.routing_tables[source], source, target)
actions = maze.locations_to_actions(path)
return actions
##################################################################################
def traversal ( self,
graph: Graph,
) -> tuple[dict[int, dict[int, int]], dict[int, dict[int, int | None]]]:
"""
This method performs Floyd-Warshall's algorithm on a graph.
It returns distances between vertices.
It also returns the routing table for each vertex.
Args:
graph: The graph to traverse.
Returns:
A tuple containing:
- The distances from each vertex to each vertex (``float('inf')`` if unreachable).
- For each vertex, the routing table from this vertex, that is, the parent of each vertex in the traversal (None for the source).
"""
# Initialization
vertices = list(graph.get_vertices())
distances = {u: {v: float('inf') for v in vertices} for u in vertices}
routing_tables = {u: {v: None for v in vertices} for u in vertices}
# Distance to itself
for u in vertices:
distances[u][u] = 0
# Direct edges
for u in vertices:
for v in graph.get_neighbors(u):
w = graph.get_weight(u, v)
distances[u][v] = w
routing_tables[u][v] = u
# Floyd-Warshall
for k in vertices:
for i in vertices:
for j in vertices:
dist_through_k = distances[i][k] + distances[k][j]
if dist_through_k < distances[i][j]:
distances[i][j] = dist_through_k
routing_tables[i][j] = routing_tables[k][j]
# Return the result
return distances, routing_tables
##################################################################################
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 3 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session3/practical/
"""
##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################
# External imports
import pprint
# PyRat imports
from pyrat import Game
from players.floyd_warshall import FloydWarshall
##########################################################################################
######################################### SCRIPT #########################################
##########################################################################################
if __name__ == "__main__":
# Instantiate a game with a few arguments
game_config = {"mud_percentage": 20.0,
"maze_width": 13,
"maze_height": 10,
"nb_cheese": 5,
"random_seed": 42,
"trace_length": 1000}
# Instantiate a game with specified arguments
game = Game(**game_config)
# Instantiate the player
player = FloydWarshall()
game.add_player(player)
# Start the game
stats = game.start()
pprint.pprint(stats)
##########################################################################################
##########################################################################################L’algorithme de Bellman-Ford
L’algorithme de Bellman-Ford est également un algorithme « 1-to-* ». Cependant, contrairement à l’algorithme de Dijkstra, il a la propriété de pouvoir trouver le chemin le plus court si certains arcs ont des poids négatifs. De plus, il peut être utilisé pour détecter un cycle absorbant dans le graphe.
À faire
Renseignez-vous sur cet algorithme. Devriez-vous l’utiliser dans le projet ?
Correction
Cliquez ici pour afficher la correction.
L’algorithme de Bellman-Ford a une complexité de $O(mn)$, avec $n$ le nombre de sommets dans le graphe et $m$ le nombre d’arcs dans le graphe. Dans le cas d’un jeu PyRat, chaque sommet a au plus 4 voisins. Par conséquent, dans ce cas particulier, l’algorithme de Bellman-Ford a une complexité de $O(4n \cdot n)$, soit $O(n^2)$.
Comme nous n’avons pas de poids négatifs dans un labyrinthe PyRat (ce qui justifierait le choix de l’algorithme de Bellman-Ford), l’algorithme de Dijkstra est préférable.
À faire
Essayez d’implémenter cet algorithme (ou cherchez une bibliothèque qui le fait).
Correction
Cliquez ici pour afficher la correction.
L’algorithme de Bellman-Ford procède par « relâchements » successifs : relâcher un arc $(u, v)$ de poids $w$ consiste à vérifier si passer par $u$ donne un chemin plus court vers $v$, c’est-à-dire si $d(u) + w < d(v)$, et à mettre à jour $d(v)$ si c’est le cas.
- Au départ, la source est à distance 0, et tous les autres sommets à une distance infinie.
- On relâche tous les arcs du graphe, et on recommence $n - 1$ fois. Après $k$ passes, les distances sont correctes pour tous les sommets qui ont un plus court chemin d’au plus $k$ arcs. Comme un plus court chemin a au plus $n - 1$ arcs, $n - 1$ passes suffisent. Si une passe ne change rien, les suivantes ne changeront rien non plus, et on peut s’arrêter plus tôt.
- Si un arc peut encore être relâché après ces $n - 1$ passes, c’est qu’il existe un cycle absorbant : on pourrait en faire le tour indéfiniment pour diminuer les distances. On lève alors une exception.
Voici le diagramme de classes d’un joueur BellmanFord utilisant cet algorithme :
Et voici son code, ainsi qu’un script de jeu pour le visualiser :
##########################################################################################
########################################## INFO ##########################################
##########################################################################################
"""
This program is a solution to the practical session 3 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session3/practical/
"""
##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################
# PyRat imports
from pyrat import Player, Maze, GameState, Action, Graph
##########################################################################################
######################################### CLASSES ########################################
##########################################################################################
class BellmanFord (Player):
"""
*(This class inherits from* ``Player`` *).*
This player performs Bellman-Ford's algorithm to find the shortest paths from its initial location to all other vertices of the maze.
Contrary to Dijkstra's algorithm, Bellman-Ford's algorithm also works with negative weights, and detects absorbing (negative) cycles.
Computation of the path to the piece of cheese 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 Bellman-Ford's 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 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.
"""
# If there is nothing left to do, we do not move
if len(self.actions) == 0:
return Action.NOTHING
# Otherwise, 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 Bellman-Ford's algorithm on 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.
The graph may have negative weights, as long as it has no absorbing cycle.
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 reachable vertex.
- The routing table, that is, the parent of each reachable vertex in the traversal (None for the source).
Raises:
ValueError: If the graph contains an absorbing cycle reachable from the source.
"""
# List all edges, with their weights
# An undirected edge is listed in both directions
edges = [(u, v, graph.get_weight(u, v)) for u in graph.get_vertices() for v in graph.get_neighbors(u)]
# Initialization
# All vertices are at an infinite distance, except the source
distances = {vertex: float("inf") for vertex in graph.get_vertices()}
routing_table = {vertex: None for vertex in graph.get_vertices()}
distances[source] = 0
# A shortest path has at most n - 1 edges, so n - 1 rounds of relaxations are enough
# After round k, distances are correct for all vertices that have a shortest path with at most k edges
for _ in range(len(distances) - 1):
# Relax all edges, i.e., check if going through u gives a shorter path to v
updated = False
for u, v, weight in edges:
if distances[u] + weight < distances[v]:
distances[v] = distances[u] + weight
routing_table[v] = u
updated = True
# If nothing changed during a round, nothing will change in the next ones either
if not updated:
break
# If an edge can still be relaxed, there is an absorbing cycle (we can go around it to decrease distances indefinitely)
for u, v, weight in edges:
if distances[u] + weight < distances[v]:
raise ValueError(f"Cannot compute shortest paths from {source!r}: the graph contains an absorbing cycle reachable from it (edge {u!r} -> {v!r} of weight {weight!r} can still be relaxed after all rounds)")
# Only keep the reachable vertices, as Dijkstra's algorithm does
reachable = [vertex for vertex in distances if distances[vertex] != float("inf")]
distances = {vertex: distances[vertex] for vertex in reachable}
routing_table = {vertex: routing_table[vertex] for vertex in reachable}
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 3 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session3/practical/
"""
##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################
# External imports
import pprint
# PyRat imports
from pyrat import Game
from players.bellman_ford import BellmanFord
##########################################################################################
######################################### SCRIPT #########################################
##########################################################################################
if __name__ == "__main__":
# Instantiate a game with a few arguments
game_config = {"mud_percentage": 20.0,
"maze_width": 13,
"maze_height": 10,
"nb_cheese": 1,
"random_seed": 42,
"trace_length": 1000}
# Instantiate a game with specified arguments
game = Game(**game_config)
# Instantiate the player
player = BellmanFord()
game.add_player(player)
# Start the game
stats = game.start()
pprint.pprint(stats)
##########################################################################################
##########################################################################################Dans un labyrinthe PyRat, ce joueur trouve exactement les mêmes distances que le joueur Dijkstra. Pour voir la différence, il faut des poids négatifs. Reprenons l’exemple de l’article sur l’algorithme de Dijkstra, avec un graphe orienté (symmetric=False par défaut dans add_edge(...)) :
from pyrat import Graph
from players.bellman_ford import BellmanFord
from players.dijkstra import Dijkstra
# Graph with arcs (u, a) of weight 2, (u, b) of weight 3, and (b, a) of weight -2
u, a, b = 0, 1, 2
graph = Graph()
for vertex in [u, a, b]:
graph.add_vertex(vertex)
graph.add_edge(u, a, 2)
graph.add_edge(u, b, 3)
graph.add_edge(b, a, -2)
# Compare the distances found
print("Bellman-Ford:", BellmanFord().traversal(graph, u)[0])
print("Dijkstra:", Dijkstra().traversal(graph, u)[0])Voici la sortie obtenue :
Bellman-Ford: {0: 0, 1: 1, 2: 3}
Dijkstra: {0: 0, 1: 2, 2: 3}Bellman-Ford trouve bien le chemin de longueur 1 de $u$ à $a$, qui passe par $b$, alors que Dijkstra s’arrête au chemin direct de longueur 2.
L’algorithme de Johnson
L’algorithme de Johnson est un algorithme « *-to-* », qui exploite l’algorithme de Bellman-Ford pour trouver tous les chemins les plus courts dans le graphe.
À faire
Renseignez-vous sur cet algorithme. Devriez-vous l’utiliser dans le projet ?
Correction
Cliquez ici pour afficher la correction.
L’algorithme de Johnson a une complexité de $O(nm \cdot log(n))$ avec un tas binaire comme heapq ($O(n^2 \cdot log(n) + nm)$ avec un tas de Fibonacci), avec $n$ le nombre de sommets dans le graphe et $m$ le nombre d’arcs dans le graphe.
Dans un labyrinthe PyRat, chaque case a au plus 4 voisins, donc $m = O(n)$ : c’est la même complexité, $O(n^2 \cdot log(n))$, que $n$ appels à l’algorithme de Dijkstra, auxquels Johnson ajoute un appel à l’algorithme de Bellman-Ford. Comme nous n’avons pas de poids négatifs dans un labyrinthe PyRat (ce qui justifierait le choix de l’algorithme de Johnson), plusieurs appels à l’algorithme de Dijkstra sont préférables.
À faire
Essayez d’implémenter cet algorithme (ou cherchez une bibliothèque qui le fait).
Correction
Cliquez ici pour afficher la correction.
L’algorithme de Johnson calcule les plus courts chemins entre toutes les paires de sommets en appelant l’algorithme de Dijkstra depuis chaque sommet. Comme Dijkstra ne fonctionne pas avec des poids négatifs, il modifie d’abord les poids pour les rendre positifs ou nuls, sans changer les plus courts chemins :
- On ajoute au graphe un sommet virtuel $q$, relié à tous les autres sommets par un arc de poids 0.
- On lance l’algorithme de Bellman-Ford depuis $q$. Il donne une valeur $h(v)$ pour chaque sommet $v$ (la distance de $q$ à $v$), et détecte au passage les cycles absorbants.
- On remplace le poids de chaque arc $(u, v)$ par $w(u, v) + h(u) - h(v)$. Ce nouveau poids est positif ou nul, car $h(v) \leq h(u) + w(u, v)$ (sinon Bellman-Ford aurait trouvé un chemin plus court vers $v$ en passant par $u$).
- On lance l’algorithme de Dijkstra depuis chaque sommet sur le graphe modifié. Le long d’un chemin de $u$ à $v$, les termes en $h$ s’annulent deux à deux, sauf $h(u)$ et $h(v)$. Tous les chemins de $u$ à $v$ sont donc allongés de la même quantité $h(u) - h(v)$ : les plus courts chemins restent les mêmes, et on retrouve les vraies distances en retirant cette quantité.
Voici le diagramme de classes d’un joueur Johnson utilisant cet algorithme. Comme pour Floyd-Warshall, les plus courts chemins sont connus depuis toutes les cases : le joueur se dirige donc vers le fromage le plus proche, puis vers le suivant, sans nouveau calcul (stratégie gloutonne, comme pour Floyd-Warshall).
Et voici son code, ainsi qu’un script de jeu pour le visualiser :
##########################################################################################
########################################## INFO ##########################################
##########################################################################################
"""
This program is a solution to the practical session 3 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session3/practical/
"""
##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################
# External imports
import heapq
# PyRat imports
from pyrat import Player, Maze, GameState, Action, Graph
##########################################################################################
######################################### CLASSES ########################################
##########################################################################################
class Johnson (Player):
"""
*(This class inherits from* ``Player`` *).*
This player performs Johnson's algorithm to find the shortest paths between all pairs of vertices in the maze.
Johnson's algorithm works as follows:
1. A virtual vertex is added to the graph, with an edge of weight 0 to every other vertex.
2. Bellman-Ford's algorithm is run from this virtual vertex, which gives a value ``h(v)`` for each vertex ``v``.
3. Each edge ``(u, v)`` is reweighted as ``w(u, v) + h(u) - h(v)``, which makes all weights non-negative, while keeping the same shortest paths.
4. Dijkstra's algorithm is run from each vertex on the reweighted graph, and distances are corrected back to the original weights.
Computation of the paths is done in the ``preprocessing(...)`` method.
As for Floyd-Warshall's algorithm, shortest paths are known from every location, so the player heads to the closest piece of cheese, and retargets as soon as it is eaten, without any new computation.
The path to the current target is 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 attributes to store the results of Johnson's algorithm
self.distances = None
self.routing_tables = None
# 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 Johnson's algorithm to compute the shortest paths between all pairs of vertices.
The results are stored in the ``distances`` and ``routing_tables`` attributes, and will be used in the ``turn(...)`` method.
We also compute the actions leading to the closest piece of cheese, and store them in the ``actions`` attribute.
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 shortest paths from all vertices
self.distances, self.routing_tables = self.traversal(maze)
# Find the series of locations/actions to go from the player location to the closest piece of cheese
my_location = game_state.player_locations[self.get_name()]
self.actions = self.actions_to_closest_cheese(maze, my_location, game_state.cheese)
##################################################################################
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 to the current target.
When that path is over, the target has been eaten, and we head to the closest remaining piece of cheese.
Since Johnson's algorithm already gave us the shortest paths from our new location, this requires no new computation.
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.
"""
# If there is no action left, we have reached our target, so we pick a new one
if len(self.actions) == 0:
my_location = game_state.player_locations[self.get_name()]
self.actions = self.actions_to_closest_cheese(maze, my_location, game_state.cheese)
# If there is still nothing to do (no more cheese), we do not move
if len(self.actions) == 0:
return Action.NOTHING
# Otherwise, we perform the next action in the list of actions
return self.actions.pop(0)
##################################################################################
# OTHER METHODS #
##################################################################################
def actions_to_closest_cheese ( self,
maze: Maze,
source: int,
cheese: list[int]
) -> list[Action]:
"""
This method uses the results of Johnson's algorithm to find the actions leading from a source vertex to the closest piece of cheese.
Args:
maze: An object representing the maze in which the player plays.
source: The vertex from which to start.
cheese: The locations of the remaining pieces of cheese.
Returns:
The list of actions to perform to reach the closest piece of cheese (empty if there is no cheese left).
"""
# No cheese left, nothing to do
if len(cheese) == 0:
return []
# The distances from the source to all vertices are already known
# We use them to find the closest piece of cheese
target = min(cheese, key=lambda location: self.distances[source][location])
# Find the series of locations/actions to go from the source to the target
path = self.find_route(self.routing_tables[source], source, target)
actions = maze.locations_to_actions(path)
return actions
##################################################################################
def traversal ( self,
graph: Graph,
) -> tuple[dict[int, dict[int, int]], dict[int, dict[int, int | None]]]:
"""
This method performs Johnson's algorithm on a graph.
It returns distances between vertices.
It also returns the routing table for each vertex.
The graph may have negative weights, as long as it has no absorbing cycle.
Args:
graph: The graph to traverse.
Returns:
A tuple containing:
- The distances from each vertex to each reachable vertex.
- For each vertex, the routing table from this vertex, that is, the parent of each reachable vertex in the traversal (None for the source).
Raises:
ValueError: If the graph contains an absorbing cycle.
"""
# Step 1: we create a copy of the graph, with a virtual vertex linked to all vertices by an edge of weight 0
# Edges are directed, so that the virtual vertex cannot be reached from the others
# We use a string to name it, so that it cannot be confused with a cell of the maze
virtual_vertex = "virtual"
augmented_graph = Graph()
for u in graph.get_vertices():
augmented_graph.add_vertex(u)
for u in graph.get_vertices():
for v in graph.get_neighbors(u):
augmented_graph.add_edge(u, v, graph.get_weight(u, v))
augmented_graph.add_vertex(virtual_vertex)
for u in graph.get_vertices():
augmented_graph.add_edge(virtual_vertex, u, 0)
# Step 2: Bellman-Ford's algorithm from the virtual vertex gives a value h(v) for each vertex v
# It also detects absorbing cycles, as all vertices are reachable from the virtual vertex
h = self.bellman_ford(augmented_graph, virtual_vertex)
# Step 3: reweight the edges of the original graph, as w(u, v) + h(u) - h(v)
# These new weights are non-negative, so Dijkstra's algorithm can be used
reweighted_graph = Graph()
for u in graph.get_vertices():
reweighted_graph.add_vertex(u)
for u in graph.get_vertices():
for v in graph.get_neighbors(u):
reweighted_graph.add_edge(u, v, graph.get_weight(u, v) + h[u] - h[v])
# Step 4: Dijkstra's algorithm from each vertex, and correction of the distances
# Along any path from u to v, the h terms cancel out, except h(u) and h(v)
distances = {}
routing_tables = {}
for u in graph.get_vertices():
reweighted_distances, routing_tables[u] = self.dijkstra(reweighted_graph, u)
distances[u] = {v: reweighted_distances[v] - h[u] + h[v] for v in reweighted_distances}
# Return the result
return distances, routing_tables
##################################################################################
def bellman_ford ( self,
graph: Graph,
source: object
) -> dict[object, int]:
"""
This method performs Bellman-Ford's algorithm on a graph, and returns the distances from the source to all reachable vertices.
See the ``BellmanFord`` player for more details on this algorithm.
Args:
graph: The graph to traverse.
source: The source vertex of the traversal.
Returns:
The distances from the source to each reachable vertex.
Raises:
ValueError: If the graph contains an absorbing cycle reachable from the source.
"""
# List all edges, with their weights
edges = [(u, v, graph.get_weight(u, v)) for u in graph.get_vertices() for v in graph.get_neighbors(u)]
# Initialization
distances = {vertex: float("inf") for vertex in graph.get_vertices()}
distances[source] = 0
# At most n - 1 rounds of relaxations
for _ in range(len(distances) - 1):
updated = False
for u, v, weight in edges:
if distances[u] + weight < distances[v]:
distances[v] = distances[u] + weight
updated = True
if not updated:
break
# Detection of absorbing cycles
for u, v, weight in edges:
if distances[u] + weight < distances[v]:
raise ValueError(f"Cannot compute shortest paths: the graph contains an absorbing cycle (edge {u!r} -> {v!r} of weight {weight!r} can still be relaxed after all rounds of Bellman-Ford's algorithm)")
# Return the distances to reachable vertices
return {vertex: distances[vertex] for vertex in distances if distances[vertex] != float("inf")}
##################################################################################
def dijkstra ( self,
graph: Graph,
source: int
) -> tuple[dict[int, int], dict[int, int | None]]:
"""
This method performs Dijkstra's algorithm on a graph with non-negative weights.
See the ``Dijkstra`` player for more details on this algorithm.
Args:
graph: The graph to traverse.
source: The source vertex of the traversal.
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 = {}
vertices_to_visit = [(0, source, None)]
# Traversal
while vertices_to_visit:
# Get the closest vertex not explored yet
distance, vertex, parent = heapq.heappop(vertices_to_visit)
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 vertices to visit
# The others would be ignored when extracted anyway, so this only avoids useless elements in the heap
for neighbor in graph.get_neighbors(vertex):
if neighbor not in distances:
heapq.heappush(vertices_to_visit, (distance + graph.get_weight(vertex, 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 3 of the PyRat project:
https://hub.imt-atlantique.fr/ueinfo-fise1a/s5/project/session3/practical/
"""
##########################################################################################
######################################### IMPORTS ########################################
##########################################################################################
# External imports
import pprint
# PyRat imports
from pyrat import Game
from players.johnson import Johnson
##########################################################################################
######################################### SCRIPT #########################################
##########################################################################################
if __name__ == "__main__":
# Instantiate a game with a few arguments
game_config = {"mud_percentage": 20.0,
"maze_width": 13,
"maze_height": 10,
"nb_cheese": 5,
"random_seed": 42,
"trace_length": 1000}
# Instantiate a game with specified arguments
game = Game(**game_config)
# Instantiate the player
player = Johnson()
game.add_player(player)
# Start the game
stats = game.start()
pprint.pprint(stats)
##########################################################################################
##########################################################################################Dans un labyrinthe PyRat, tous les poids sont positifs : chaque sommet est donc à distance 0 du sommet virtuel, et $h(v) = 0$ pour tout $v$. Les poids ne changent pas, et l’algorithme de Johnson revient exactement à lancer l’algorithme de Dijkstra depuis chaque case, après un appel inutile à Bellman-Ford. C’est une autre manière de voir pourquoi il n’a pas d’intérêt dans le projet.