Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 46 additions & 35 deletions src/simulation/scripts/lanch_one_simu.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,31 @@
raise NotImplementedError("This file is currently begin worked on")

import os
import sys

from typing import *
import numpy as np
import onnxruntime as ort
import gymnasium as gym

from simulation import (
VehicleEnv,
)
from simulation import config as c
from utils import onnx_utils
from simulation.config import *
from utils import run_onnx_model

# -------------------------------------------------------------------------
from extractors import ( # noqa: F401
CNN1DResNetExtractor,
TemporalResNetExtractor,
)

from simulation import VehicleEnv

# --- Chemin vers le fichier ONNX ---
# -------------------------------------------------------------------------

ONNX_MODEL_PATH = "model.onnx"
ONNX_MODEL_PATH = "/home/exo/Bureau/CoVAPSy/model.onnx"


# --- Initialisation du moteur d'inférence ONNX Runtime (ORT) ---
# --- Launching of inference motor ONNX Runtime (ORT) ---
def init_onnx_runtime_session(onnx_path: str) -> ort.InferenceSession:
if not os.path.exists(onnx_path):
raise FileNotFoundError(
f"Le fichier ONNX est introuvable à : {onnx_path}. Veuillez l'exporter d'abord."
)

# Crée la session d'inférence
return ort.InferenceSession(
onnx_path
) # On peut modifier le providers afin de mettre une CUDA
raise FileNotFoundError(f"Le fichier ONNX est introuvable à : {onnx_path}. Veuillez l'exporter d'abord.")
return ort.InferenceSession(onnx_path)


if __name__ == "__main__":
Expand All @@ -38,7 +34,7 @@ def init_onnx_runtime_session(onnx_path: str) -> ort.InferenceSession:

os.system('if [ -n "$(ls /tmp/autotech)" ]; then rm /tmp/autotech/*; fi')

# 2. Initialisation de la session ONNX Runtime
# Starting of OnnxSession
try:
ort_session = init_onnx_runtime_session(ONNX_MODEL_PATH)
input_name = ort_session.get_inputs()[0].name
Expand All @@ -47,33 +43,48 @@ def init_onnx_runtime_session(onnx_path: str) -> ort.InferenceSession:
print(f"Input Name: {input_name}, Output Name: {output_name}")
except FileNotFoundError as e:
print(f"ERREUR : {e}")
print(
"Veuillez vous assurer que vous avez exécuté une fois le script d'entraînement pour exporter 'model.onnx'."
)
sys.exit(1)

# 3. Boucle d'inférence (Test)
env = VehicleEnv(0, 0)
obs = env.reset()
obs, _ = env.reset()

print("Début de la simulation en mode inférence...")

max_steps = 5000
step_count = 0

while True:
action = onnx_utils.run_onnx_model(ort_session, obs)
# 1. On récupère les logits (probabilités) bruts de l'ONNX
raw_action = run_onnx_model(ort_session, obs[None])
logits = np.array(raw_action).flatten()

# 2. On sépare le tableau en deux (Direction et Vitesse)
# On utilise n_actions_steering et n_actions_speed venant de config.py
steer_logits = logits[:n_actions_steering]
speed_logits = logits[n_actions_steering:]

# 3. L'IA choisit l'action qui a le score (logit) le plus élevé
action_steer = np.argmax(steer_logits)
action_speed = np.argmax(speed_logits)

# 4. Exécuter l'action dans l'environnement
obs, reward, done, info = env.step(action)
# 4. On crée le tableau final parfaitement formaté pour Webots (strictement 2 entiers)
action = np.array([action_steer, action_speed], dtype=np.int64)

# Note: L'environnement Webots gère généralement son propre affichage
# env.render() # Décommenter si votre env supporte le rendu externe
# 5. Exécuter l'action dans l'environnement
next_obs, reward, done, truncated, info = env.step(action)

step_count += 1

# Gestion des fins d'épisodes
if done:
print(f"Épisode(s) terminé(s) après {step_count} étapes.")
obs = env.reset()
step_count = 0

fresh_frame = next_obs[:, -1:]
obs, _ = env.reset()
env.context[:, -1:] = fresh_frame
obs = env.context
else:
obs = next_obs

# Fermeture propre (très important pour les processus parallèles SubprocVecEnv)
envs.close()
print("Simulation terminée. Environnements fermés.")
env.close()
print("Simulation terminée. Environnements fermés.")
4 changes: 3 additions & 1 deletion src/simulation/src/simulation/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

n_map = 2
n_simulations = 1
n_vehicles = 2
n_vehicles = 1
n_stupid_vehicles = 0
n_actions_steering = 16
n_actions_speed = 16
Expand All @@ -26,3 +26,5 @@

LOG_LEVEL = logging.INFO
FORMATTER = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

B_DEBUG = False
5 changes: 5 additions & 0 deletions src/simulation/src/utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
from .plot_model_io import PlotModelIO
import onnxruntime as ort
import numpy as np

__all__ = ["PlotModelIO"]

def run_onnx_model(session: ort.InferenceSession, x: np.ndarray):
return session.run(None, {"input": x})[0]
10 changes: 10 additions & 0 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.