ajout test probleme ouvert dijkstra

This commit is contained in:
bezza 2025-05-26 18:28:48 +02:00
parent 469c810f44
commit fe280a1f42
5 changed files with 276 additions and 72 deletions

View file

@ -9,7 +9,7 @@ import org.insa.graphs.model.Arc;
import org.insa.graphs.model.Graph;
import org.insa.graphs.model.Node;
import org.insa.graphs.model.Path;
import org.insa.graphs.model.RoadInformation.RoadType;
public class DijkstraAlgorithm extends ShortestPathAlgorithm {
@ -21,6 +21,29 @@ public class DijkstraAlgorithm extends ShortestPathAlgorithm {
return new Label(node, false, Double.POSITIVE_INFINITY, null);
}
protected void tryUpdateLabel(Label[] labels, BinaryHeap<Label> heap, Node node,
double newCost, Arc pere) {
Label label = labels[node.getId()];
if (newCost < label.getCoutRealise()) {
if (label.getCoutRealise() != Double.POSITIVE_INFINITY) {
heap.remove(label);
}
label.setCoutRealise(newCost);
label.setPere(pere);
heap.insert(label);
notifyNodeReached(node);
}
}
protected void fonctionProblemeOuvert(RoadType typeDeRoute,Label[] labels, BinaryHeap<Label> heap, Node node,
double newCost, Arc pere){}
@Override
protected ShortestPathSolution doRun() {
@ -75,21 +98,10 @@ public class DijkstraAlgorithm extends ShortestPathAlgorithm {
// Correction ici : on utilise getCoutRealise() pour Dijkstra
double newCost = LabelActuel.getCoutRealise() + data.getCost(arc);
if (newCost < succLabel.getCoutRealise()) {
if (succLabel.getCoutRealise() != Double.POSITIVE_INFINITY) {
heap.remove(succLabel);
//System.out.println(succLabel.getTotalCost());// print de confirmation , pour verif si tous les couts qui sortent du tas sont croissant. getTotalcost pas croissant!!
}
succLabel.setCoutRealise(newCost);
succLabel.setPere(arc);
predecessorArcs[succ.getId()] = arc;
tryUpdateLabel(labels, heap, succ, newCost, arc);
// Insertion dans le tas car on est sûr qu'il n'est pas
fonctionProblemeOuvert(arc.getRoadInformation().getType(),labels, heap, succ, newCost, arc); //fonction uniquement pour probleme ouvert, permet de ne pas réécrire l'algorithme pour le problème ouvert
heap.insert(succLabel);
notifyNodeReached(succ);
}
}
}

View file

@ -1,16 +0,0 @@
/*public class LabelProblemeOuvert extends Label {
private double autonomieRestante;
public LabelProblemeOuvert(Node sommet, boolean marque, double cout, Arc pere, double autonomieRestante) {
super(sommet, marque, cout, pere);
this.autonomieRestante = autonomieRestante;
}
public double getAutonomieRestante() {
return autonomieRestante;
}
public void setAutonomieRestante(double autonomieRestante) {
this.autonomieRestante = autonomieRestante;
}
}*/

View file

@ -0,0 +1,26 @@
package org.insa.graphs.algorithm.shortestpath;
import org.insa.graphs.model.Arc;
import org.insa.graphs.model.Node;
public class LabelProblemeOuvert extends Label {
private double batteryLeft; //double pour la cohérence avec les autres couts qui sont en double eux aussi
public LabelProblemeOuvert(Node sommet, boolean marque, double cout, Arc pere, double batteryLeft) {
super(sommet, marque, cout, pere);
this.batteryLeft = batteryLeft;
}
public double getBatteryLeft() {
return batteryLeft;
}
public void setBatteryLeft(double batteryLeft) {
this.batteryLeft = batteryLeft;
}
@Override
public double getTotalCost() { //pourquoi getTotalCost ? psq il est utilisé dans le compareTo
return this.getCoutRealise();
}
}

View file

@ -1,6 +1,3 @@
/* je considère que les 200km d'autonomie atteint (200km avec le 22 kWh - Q90 Renault ZOE chargé à 90%)
cette autonomie est considéré en ville à 200km (à 30km/h de moyenne)
en mixte elle devient 154 km (47km/h de moyenne) ~3/4 de l'autonmie
@ -106,3 +103,197 @@ gérer le problème de la recharge, quand la faire ?
*/
package org.insa.graphs.algorithm.shortestpath;
import org.insa.graphs.algorithm.AbstractSolution.Status;
import org.insa.graphs.algorithm.utils.BinaryHeap;
import org.insa.graphs.model.Arc;
import org.insa.graphs.model.Graph;
import org.insa.graphs.model.Node;
import org.insa.graphs.model.RoadInformation.RoadType;
public class ProblemeOuvert extends DijkstraAlgorithm {
private double MAX_BATTERY = 200;
public ProblemeOuvert(ShortestPathData data) {
super(data);
}
@Override
protected LabelProblemeOuvert createLabel(Node node) {
return new LabelProblemeOuvert(node, false, Double.POSITIVE_INFINITY, null, MAX_BATTERY);
}
// Surcharge pour compatibilité avec DijkstraAlgorithm
@Override
protected void tryUpdateLabel(Label[] labels, BinaryHeap<Label> heap, Node node,
double newCost, Arc pere) {
// Si c'est bien un label de probleme ouvert, on applique la logique spécifique
if (labels instanceof LabelProblemeOuvert[]) {
LabelProblemeOuvert[] plabels = (LabelProblemeOuvert[]) labels;
double batteryLeft = plabels[node.getId()].getBatteryLeft();
tryUpdateLabelSpecifique(plabels, heap, node, newCost, batteryLeft, pere);
} else {
// Sinon, on garde le comportement normal du Dijkstra
super.tryUpdateLabel(labels, heap, node, newCost, pere);
}
}
// Version spécifique pour le problème ouvert (pas d'@Override ici)
protected void tryUpdateLabelSpecifique(LabelProblemeOuvert[] labels, BinaryHeap<Label> heap, Node node,
double newCost, double newBatteryLeft, Arc pere) {
LabelProblemeOuvert label = labels[node.getId()];
// On ne met à jour que si on a assez de batterie
if (newBatteryLeft < 0) return;
if (newCost < label.getCoutRealise() || (Math.abs(newCost - label.getCoutRealise()) < 1e-6 && newBatteryLeft > label.getBatteryLeft())) {
if (label.getCoutRealise() != Double.POSITIVE_INFINITY) {
heap.remove(label);
}
label.setCoutRealise(newCost);
label.setBatteryLeft(newBatteryLeft);
label.setPere(pere);
heap.insert(label);
notifyNodeReached(node);
}
}
// Surcharge pour compatibilité avec DijkstraAlgorithm
// (Pas d'@Override ici car il n'y a pas de méthode à surcharger dans la superclasse)
protected void fonctionProblemeOuvert(RoadType typeDeRoute, Label[] labels, BinaryHeap<Label> heap, Node node,
double newCost, Arc pere) {
// Si c'est bien un label de probleme ouvert, on applique la logique spécifique
if (labels instanceof LabelProblemeOuvert[]) {
fonctionProblemeOuvertSpecifique(typeDeRoute, (LabelProblemeOuvert[]) labels, heap, node, newCost, pere);
} else {
// Sinon, on garde le comportement normal du Dijkstra
super.fonctionProblemeOuvert(typeDeRoute, labels, heap, node, newCost, pere);
}
}
// Version spécifique pour le problème ouvert (pas d'@Override ici)
protected void fonctionProblemeOuvertSpecifique(RoadType typeDeRoute, LabelProblemeOuvert[] labels, BinaryHeap<Label> heap, Node node,
double newCost, Arc pere) {
if (typeDeRoute == RoadType.MOTORWAY) {
tryUpdateLabelSpecifique(labels, heap, node, newCost, MAX_BATTERY, pere);
}
}
@Override
protected ShortestPathSolution doRun() {
final ShortestPathData data = getInputData();
ShortestPathSolution solution = null;
Graph graph = data.getGraph();
int nbNodes = graph.size();
// Tableau des labels pour chaque sommet
LabelProblemeOuvert[] labels = new LabelProblemeOuvert[nbNodes];
// Tableau des arcs prédécesseurs pour reconstruire le chemin
Arc[] predecessorArcs = new Arc[nbNodes];
// Initialisation des labels
for (Node node : graph.getNodes()) {
labels[node.getId()] = createLabel(node);
}
// Origine : coût 0, batterie pleine
labels[data.getOrigin().getId()].setCoutRealise(0);
labels[data.getOrigin().getId()].setBatteryLeft(MAX_BATTERY);
BinaryHeap<Label> heap = new BinaryHeap<>();
heap.insert(labels[data.getOrigin().getId()]);
notifyOriginProcessed(data.getOrigin());
while (!heap.isEmpty()) {
LabelProblemeOuvert currentLabel = (LabelProblemeOuvert) heap.deleteMin();
Node currentNode = currentLabel.getSommetCourant();
// sommet traité
currentLabel.setMarque(true);
// On a atteint la destination on s'arrête
if (currentNode.equals(data.getDestination())) {
notifyDestinationReached(currentNode);
break;
}
// Pour chaque successeur
for (Arc arc : currentNode.getSuccessors()) {
if (!data.isAllowed(arc)) continue;
Node succ = arc.getDestination();
LabelProblemeOuvert succLabel = labels[succ.getId()];
if (succLabel.getMarque()) continue;
double arcCost = data.getCost(arc);
double batteryLeft = currentLabel.getBatteryLeft();
// Calcul de la batterie restante après avoir parcouru l'arc
double newBatteryLeft = batteryLeft - arcCost;
double newCost = currentLabel.getCoutRealise() + arcCost;
// Si pas assez de batterie, on ne continue pas
if (newBatteryLeft < 0) continue;
// Mise à jour du label si meilleur coût ou plus de batterie à coût égal
if (newCost < succLabel.getCoutRealise() ||
(Math.abs(newCost - succLabel.getCoutRealise()) < 1e-6 && newBatteryLeft > succLabel.getBatteryLeft())) {
if (succLabel.getCoutRealise() != Double.POSITIVE_INFINITY) {
heap.remove(succLabel);
}
succLabel.setCoutRealise(newCost);
succLabel.setBatteryLeft(newBatteryLeft);
succLabel.setPere(arc);
heap.insert(succLabel);
notifyNodeReached(succ);
}
// Si on arrive sur une autoroute, possibilité de recharger
if (arc.getRoadInformation().getType() == RoadType.MOTORWAY) {
double rechargeCost = newCost; // ici, pas de coût supplémentaire pour la recharge
double rechargeBattery = MAX_BATTERY;
if (rechargeCost < succLabel.getCoutRealise() ||
(Math.abs(rechargeCost - succLabel.getCoutRealise()) < 1e-6 && rechargeBattery > succLabel.getBatteryLeft())) {
if (succLabel.getCoutRealise() != Double.POSITIVE_INFINITY) {
heap.remove(succLabel);
}
succLabel.setCoutRealise(rechargeCost);
succLabel.setBatteryLeft(rechargeBattery);
succLabel.setPere(arc);
heap.insert(succLabel);
notifyNodeReached(succ);
}
}
}
}
// Construction de la solution
if (labels[data.getDestination().getId()].getPere() == null) {
solution = new ShortestPathSolution(data, Status.INFEASIBLE);
}
else {
// Reconstruire le chemin
java.util.ArrayList<Arc> arcs = new java.util.ArrayList<>();
Arc arc = labels[data.getDestination().getId()].getPere();
while (arc != null) {
arcs.add(arc);
arc = labels[arc.getOrigin().getId()].getPere();
}
java.util.Collections.reverse(arcs);
solution = new ShortestPathSolution(data, Status.OPTIMAL, new org.insa.graphs.model.Path(graph, arcs));
}
return solution;
}
}

View file

@ -1,14 +1,9 @@
package org.insa.graphs.gui.simple;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import org.insa.graphs.algorithm.AbstractInputData.Mode;
import org.insa.graphs.algorithm.ArcInspector;
import org.insa.graphs.algorithm.MyArcInspector;
@ -18,32 +13,16 @@ import org.insa.graphs.algorithm.shortestpath.DijkstraAlgorithm;
import org.insa.graphs.algorithm.shortestpath.ShortestPathData;
import org.insa.graphs.algorithm.shortestpath.ShortestPathSolution;
import org.insa.graphs.gui.drawing.Drawing;
import org.insa.graphs.gui.drawing.components.BasicDrawing;
import org.insa.graphs.gui.simple.Launch;
import org.insa.graphs.model.Arc;
import org.insa.graphs.model.Graph;
import org.insa.graphs.model.Node;
import org.insa.graphs.model.Path;
import org.insa.graphs.model.Arc;
import org.insa.graphs.model.io.BinaryGraphReader;
import org.insa.graphs.model.io.GraphReader;
public class TestDijkstra {
public static Drawing createDrawing() throws Exception {
BasicDrawing basicDrawing = new BasicDrawing();
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("BE Graphes - Launch");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(new Dimension(800, 600));
frame.setContentPane(basicDrawing);
frame.validate();
}
});
return basicDrawing;
}
// fonction pour tester un scénario
public static void testScenario(String map, int depart, int arrivee, Mode mode, boolean petitGraphe, boolean Astar, boolean restreint) throws Exception {
@ -73,6 +52,12 @@ public class TestDijkstra {
dijkstra = new DijkstraAlgorithm(data);
}
// Affichage graphique
final Drawing drawing = Launch.createDrawing();
//On utilise les observateurs pour Astar
drawing.drawGraph(graph);
ShortestPathSolution solution = dijkstra.run();
@ -144,11 +129,8 @@ public class TestDijkstra {
}
}
// Affichage graphique
// final Drawing drawing = createDrawing();
// drawing.drawGraph(graph);
// drawing.drawPath(path);
drawing.drawPath(path);
} else {
System.out.println("Aucun chemin trouvé.");
}
@ -165,20 +147,29 @@ public class TestDijkstra {
// testScenario("carre.mapgr", 0, 9999, Mode.LENGTH, true,false,false);
//cartes routières
System.out.println("== Test en distance ==");
testScenario("insa.mapgr", 369, 838, Mode.LENGTH, true,false,false);
// System.out.println("== Test en distance ==");
// testScenario("insa.mapgr", 369, 838, Mode.LENGTH, true,false,false);
System.out.println("== Test en temps ==");
testScenario("insa.mapgr", 369, 838, Mode.TIME, true,false,false);
// autres scénarios
// System.out.println("== Test en temps ==");
// testScenario("insa.mapgr", 369, 838, Mode.TIME, true,false,false);
// // autres scénarios
// System.out.println("== Trajet long (et pénible avec les enfants) ==");
// testScenario("bretagne.mapgr",564429,602395 , Mode.LENGTH, false,false,false);
System.out.println("== Test bug dijkstra temps ==");
testScenario("paris.mapgr", 27361, 36108, Mode.TIME, true,false,false);
// System.out.println("== Test bug dijkstra temps ==");
// testScenario("paris.mapgr", 27361, 36108, Mode.TIME, true,false,false); // ce test mettait en lumière un problème d'arrondi qui est mtn résolu.
//System.out.println("== Trajet impossible (piste cyclable) ==");
// testScenario("insa.mapgr",90,922 , Mode.LENGTH, false,false,true); //marche pas
//testScenario("insa.mapgr",90,922 , Mode.LENGTH, false,false,true);
//System.out.println("== Trajet impossible (piste cyclable) == sans restriction");
//testScenario("insa.mapgr",90,922 , Mode.LENGTH, true,false,false); //marche pas
//scénarios de comparaison Dijkstra vs Astar
System.out.println("== Dijkstra vs Astar (en temps) ==");
testScenario("paris.mapgr", 27361, 36108, Mode.TIME, true,false,false);
testScenario("paris.mapgr", 27361, 36108, Mode.TIME, true,true,false);
}
}