Skip to content

Commit 40423fd

Browse files
committed
feat: Implémentation du module logging : un fichier log par voiture par simulation
1 parent 0e83a26 commit 40423fd

6 files changed

Lines changed: 81 additions & 78 deletions

File tree

scripts/lanch_one_simu.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,7 @@
1616
from CNN1DResNetExtractor import CNN1DResNetExtractor
1717
# -------------------------------------------------------------------------
1818

19-
def log(s: str):
20-
# Conservez votre fonction de log
21-
if B_DEBUG:
22-
print(s, file=open("/tmp/autotech/logs", "a"))
19+
2320

2421
# --- Chemin vers le fichier ONNX ---
2522

@@ -39,8 +36,6 @@ def init_onnx_runtime_session(onnx_path: str) -> ort.InferenceSession:
3936
os.mkdir("/tmp/autotech/")
4037

4138
os.system('if [ -n "$(ls /tmp/autotech)" ]; then rm /tmp/autotech/*; fi')
42-
if B_DEBUG:
43-
print("Webots started", file=open("/tmp/autotech/logs", "w"))
4439

4540

4641
# 2. Initialisation de la session ONNX Runtime

scripts/launch_train_multiprocessing.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import logging
12
import os
23
import sys
34

@@ -12,30 +13,27 @@
1213
if simu_path not in sys.path:
1314
sys.path.insert(0, simu_path)
1415

16+
from Simulateur.config import LOG_LEVEL
1517
from config import *
1618
from TemporalResNetExtractor import TemporalResNetExtractor
1719
from CNN1DResNetExtractor import CNN1DResNetExtractor
1820
from onnx_utils import *
1921

2022
from WebotsSimulationGymEnvironment import WebotsSimulationGymEnvironment
21-
if B_DEBUG: from DynamicActionPlotCallback import DynamicActionPlotDistributionCallback
22-
23-
def log(s: str):
24-
if B_DEBUG:
25-
print(s, file=open("/tmp/autotech/logs", "a"))
26-
23+
if LOG_LEVEL == logging.DEBUG: from DynamicActionPlotCallback import DynamicActionPlotDistributionCallback
2724

2825

2926
if __name__ == "__main__":
27+
3028
if not os.path.exists("/tmp/autotech/"):
3129
os.mkdir("/tmp/autotech/")
3230

3331
os.system('if [ -n "$(ls /tmp/autotech)" ]; then rm /tmp/autotech/*; fi')
34-
if B_DEBUG:
35-
print("Webots started", file=open("/tmp/autotech/logs", "w"))
32+
3633

3734
def make_env(simulation_rank: int, vehicle_rank: int):
38-
log(f"CAREFUL !!! created an SERVER env with {simulation_rank}_{vehicle_rank}")
35+
if LOG_LEVEL == logging.DEBUG:
36+
print("CAREFUL !!! created an SERVER env with {simulation_rank}_{vehicle_rank}")
3937
return WebotsSimulationGymEnvironment(simulation_rank, vehicle_rank)
4038

4139
envs = SubprocVecEnv([lambda simulation_rank=simulation_rank, vehicle_rank=vehicle_rank : make_env(simulation_rank, vehicle_rank) for vehicle_rank in range(n_vehicles) for simulation_rank in range(n_simulations)])
@@ -111,7 +109,7 @@ def make_env(simulation_rank: int, vehicle_rank: int):
111109
print(f"{model.batch_size=}")
112110
print(f"{model.device=}")
113111

114-
log(f"SERVER : finished executing")
112+
print("SERVER : finished executing")
115113

116114
# obs = envs.reset()
117115
# while True:
@@ -124,7 +122,7 @@ def make_env(simulation_rank: int, vehicle_rank: int):
124122
export_onnx(model)
125123
test_onnx(model)
126124

127-
if B_DEBUG:
125+
if LOG_LEVEL <= logging.DEBUG:
128126
model.learn(total_timesteps=500_000, callback=DynamicActionPlotDistributionCallback())
129127
else:
130128
model.learn(total_timesteps=500_000)

src/Simulateur/WebotsSimulationGymEnvironment.py

Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,6 @@
66
from config import *
77

88

9-
def log(s: str):
10-
if B_DEBUG:
11-
print(s, file=open("/tmp/autotech/logs", "a"))
129
class WebotsSimulationGymEnvironment(gym.Env):
1310
"""
1411
One environment for each vehicle
@@ -19,11 +16,20 @@ class WebotsSimulationGymEnvironment(gym.Env):
1916

2017
def __init__(self, simulation_rank: int, vehicle_rank: int):
2118

22-
log("vvvvvvvvvvvvvvvvvvvvvvvvvv Initialisation vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv")
19+
2320
super().__init__()
2421
self.simulation_rank = simulation_rank
2522
self.vehicle_rank = vehicle_rank
2623

24+
self.handler = logging.FileHandler(f"/tmp/autotech/Voiture_{self.simulation_rank}_{self.vehicle_rank}.log")
25+
self.handler.setFormatter(FORMATTER)
26+
self.log = logging.getLogger("SERVER")
27+
self.log.setLevel(level=LOG_LEVEL)
28+
self.log.addHandler(self.handler)
29+
30+
31+
self.log.info("Initialisation started")
32+
2733
# this is only true if lidar_horizontal_resolution = camera_horizontal_resolution
2834
box_min = np.zeros([2, context_size, lidar_horizontal_resolution], dtype=np.float32)
2935
box_max = np.ones([2, context_size, lidar_horizontal_resolution], dtype=np.float32) * 30
@@ -34,7 +40,7 @@ def __init__(self, simulation_rank: int, vehicle_rank: int):
3440
if not os.path.exists("/tmp/autotech"):
3541
os.mkdir("/tmp/autotech")
3642

37-
log(f"SERVER{simulation_rank}_{vehicle_rank} : {simulation_rank}_{vehicle_rank}")
43+
self.log.debug(f"Creation of the pipes")
3844

3945
os.mkfifo(f"/tmp/autotech/{simulation_rank}_{vehicle_rank}toserver.pipe")
4046
os.mkfifo(f"/tmp/autotech/serverto{simulation_rank}_{vehicle_rank}.pipe")
@@ -46,12 +52,13 @@ def __init__(self, simulation_rank: int, vehicle_rank: int):
4652
webots {__file__.rsplit('/', 1)[0]}/worlds/piste{simulation_rank % n_map}.wbt --mode=fast --minimize --batch --stdout &
4753
echo $! {simulation_rank}_{vehicle_rank} >>/tmp/autotech/simulationranks
4854
""")
49-
log(f"SERVER{simulation_rank}_{vehicle_rank} : serverto{simulation_rank}_{vehicle_rank}.pipe")
55+
56+
self.log.debug("Connection to the vehicle")
5057
self.fifo_w = open(f"/tmp/autotech/serverto{simulation_rank}_{vehicle_rank}.pipe", "wb")
51-
log(f"SERVER{simulation_rank}_{vehicle_rank} : {simulation_rank}_{vehicle_rank}toserver.pipe")
58+
self.log.debug("Connection to the supervisor")
5259
self.fifo_r = open(f"/tmp/autotech/{simulation_rank}_{vehicle_rank}toserver.pipe", "rb")
5360

54-
log("----------------------------- Inititalisation ---------------------------------")
61+
self.log.info("Initialisation finished\n")
5562

5663
def reset(self, seed=0):
5764
# basically useless function
@@ -60,26 +67,26 @@ def reset(self, seed=0):
6067
# this is true for lidar_horizontal_resolution = camera_horizontal_resolution
6168
self.context = obs = np.zeros([2, context_size, lidar_horizontal_resolution], dtype=np.float32)
6269
info = {}
63-
log(f"SERVER{self.simulation_rank}_{self.vehicle_rank} : finished reset")
70+
self.log.info(f"reset finished\n")
6471
return obs, info
6572

6673
def step(self, action):
6774

68-
log("vvvvvvvvvvvvvvvvvvvvvvvvvv STEP vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv")
69-
log(f"SERVER{self.simulation_rank}_{self.vehicle_rank} : sending {action=}")
75+
self.log.info("Starting step")
76+
self.log.info(f"sending {action=}")
7077
self.fifo_w.write(action.tobytes())
7178
self.fifo_w.flush()
7279

7380
# communication with the supervisor
74-
log(f"SERVER{self.simulation_rank}_{self.vehicle_rank} : trying to read the fifo_r")
81+
self.log.debug("trying to get info from supervisor")
7582
cur_state = np.frombuffer(self.fifo_r.read(np.dtype(np.float32).itemsize * (n_sensors + lidar_horizontal_resolution + camera_horizontal_resolution)), dtype=np.float32)
76-
log(f"SERVER{self.simulation_rank}_{self.vehicle_rank} : received {cur_state=}")
83+
self.log.info(f"received {cur_state=}")
7784
reward = np.frombuffer(self.fifo_r.read(np.dtype(np.float32).itemsize), dtype=np.float32)[0] # scalar
78-
log(f"SERVER{self.simulation_rank}_{self.vehicle_rank} : received {reward=}")
85+
self.log.info(f"received {reward=}")
7986
done = np.frombuffer(self.fifo_r.read(np.dtype(np.bool).itemsize), dtype=np.bool)[0] # scalar
80-
log(f"SERVER{self.simulation_rank}_{self.vehicle_rank} : received {done=}")
87+
self.log.info(f"received {done=}")
8188
truncated = np.frombuffer(self.fifo_r.read(np.dtype(np.bool).itemsize), dtype=np.bool)[0] # scalar
82-
log(f"SERVER{self.simulation_rank}_{self.vehicle_rank} : received {truncated=}")
89+
self.log.info(f"received {truncated=}")
8390
info = {}
8491

8592
cur_state = np.nan_to_num(cur_state[n_sensors:], nan=0., posinf=30.)
@@ -92,8 +99,7 @@ def step(self, action):
9299
[lidar_obs[None], camera_obs[None]]
93100
], axis=1)
94101

95-
log(f"SERVER{self.simulation_rank}_{self.vehicle_rank} : step over")
96-
log("----------------------------- STEP ---------------------------------")
102+
self.log.info("step over")
97103

98104
return obs, reward, done, truncated, info
99105

src/Simulateur/config.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# just a file that lets us define some constants that are used in multiple files the simulation
22
from torch.cuda import is_available
3+
import logging
4+
35

46
n_map = 2
57
n_simulations = 2
@@ -15,4 +17,5 @@
1517
lidar_horizontal_resolution = 1024 # DON'T CHANGE THIS VALUE PLS
1618
camera_horizontal_resolution = 1024 # DON'T CHANGE THIS VALUE PLS
1719

18-
B_DEBUG = True
20+
LOG_LEVEL = logging.DEBUG
21+
FORMATTER = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

src/Simulateur/controllers/controllerVehicleDriver/controllerVehicleDriver.py

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import os
55
import re
66
import sys
7+
import logging
78

89
# add src/Simulateur to sys.path
910
path = __file__.rsplit('/', 3)[0]
@@ -12,12 +13,6 @@
1213
from config import *
1314
from vehicle import Driver
1415

15-
16-
17-
def log(s: str):
18-
if True:
19-
print(s, file=open("/tmp/autotech/logs", "a"))
20-
2116
class VehicleDriver(Driver):
2217
"""
2318
This class is a subclass of the Driver class and is used to control the vehicle.
@@ -27,6 +22,7 @@ class VehicleDriver(Driver):
2722
def __init__(self):
2823
super().__init__()
2924

25+
3026
basicTimeStep = int(self.getBasicTimeStep())
3127
self.sensorTime = basicTimeStep // 4
3228

@@ -63,9 +59,15 @@ def __init__(self):
6359
).group(1)
6460
)
6561

66-
log(f"CLIENT{self.simulation_rank}/{self.i} : serverto{self.simulation_rank}_{self.i}.pipe")
62+
self.handler = logging.FileHandler(f"/tmp/autotech/Voiture_{self.simulation_rank}_{self.i}.log")
63+
self.handler.setFormatter(FORMATTER)
64+
self.log = logging.getLogger("CLIENT")
65+
self.log.setLevel(level=LOG_LEVEL)
66+
self.log.addHandler(self.handler)
67+
68+
self.log.debug("Connection to the server")
6769
self.fifo_r = open(f"/tmp/autotech/serverto{self.simulation_rank}_{self.i}.pipe", "rb")
68-
log(f"CLIENT{self.simulation_rank}/{self.i} : {self.simulation_rank}_{self.i}tosupervisor.pipe")
70+
self.log.debug("Connection with the supervisor")
6971
self.fifo_w = open(f"/tmp/autotech/{self.simulation_rank}_{self.i}tosupervisor.pipe", "wb")
7072

7173

@@ -109,15 +111,16 @@ def step(self):
109111
# sends observation to the supervisor
110112

111113
# First to be executed
112-
log(f"CLIENT{self.simulation_rank}/{self.i} : trying to write obs")
114+
115+
self.log.info("Starting step")
113116
obs = self.observe()
114-
log(f"CLIENT{self.simulation_rank}/{self.i} : driver sending {obs=}")
117+
self.log.info(f"Observe {obs=}")
115118
self.fifo_w.write(obs.tobytes())
116119
self.fifo_w.flush()
117120

118-
log(f"CLIENT{self.simulation_rank}/{self.i} : trying to read from fifo")
121+
self.log.debug("Trying to read action from the server")
119122
action = np.frombuffer(self.fifo_r.read(np.dtype(np.int64).itemsize * 2), dtype=np.int64)
120-
log(f"CLIENT{self.simulation_rank}/{self.i} : received {action=}")
123+
self.log.info(f"received {action=}")
121124

122125
# Simulation step
123126

@@ -149,6 +152,7 @@ def run(self):
149152
#----------------Programme principal--------------------
150153
def main():
151154
driver = VehicleDriver()
155+
driver.log.info("Starting the vehicle driver\n")
152156
driver.run()
153157

154158

0 commit comments

Comments
 (0)