Skip to content

Commit aab5c5f

Browse files
committed
Merge branch 'wrapper3'
2 parents 88103bf + 33499cd commit aab5c5f

5 files changed

Lines changed: 83 additions & 19 deletions

File tree

src/HL/Autotech_constant.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
MAX_SOFT_SPEED = 0.5
55
MIN_SOFT_SPEED = 0.1
6-
MAX_ANGLE = 18
6+
MAX_ANGLE = 14
77
CRASH_DIST = 110
88
REAR_BACKUP_DIST = 100 #mm Distance at which the car will NOT reverse due to the obstacle behind it
99
LIDAR_DATA_AMPLITUDE = 1

src/HL/Car.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@
1515
from ToF import ToF
1616

1717
class Car:
18-
def __init__(self, driving_strategy=Driver().farthest_distants):
18+
def __init__(self, driver):
1919
"""Initialize the car's components."""
20-
20+
2121
def _initialize_speed_limits():
2222
"""Set the car's speed limits."""
2323
self.vitesse_max_m_s_hard = 8 # Maximum hardware speed
@@ -70,7 +70,7 @@ def _initialize_lidar():
7070
except Exception as e:
7171
log.error(f"Error initializing Lidar: {e}")
7272
raise
73-
73+
7474
def _initialize_camera():
7575
"""Initialize the camera."""
7676
try:
@@ -103,7 +103,7 @@ def _initialize_tof():
103103

104104
# Initialize Lidar
105105
_initialize_lidar()
106-
106+
107107
_initialize_camera()
108108

109109
_initialize_tof()
@@ -117,25 +117,25 @@ def _initialize_tof():
117117
def set_vitesse_m_s(self, vitesse_m_s):
118118
"""Set the car's speed in meters per second."""
119119
# Clamp the speed to the maximum and minimum speed
120-
vitesse_m_s = max(-self.vitesse_max_m_s_hard, min(vitesse_m_s, self.vitesse_max_m_s_soft))
120+
vitesse_m_s = max(-self.vitesse_max_m_s_hard, min(vitesse_m_s, self.vitesse_max_m_s_soft))
121121
vitesse_pwm = vitesse_m_s * (self.delta_pwm_max_prop)/self.vitesse_max_m_s_hard
122-
122+
123123
if vitesse_m_s == 0:
124124
pwm = self.pwm_stop_prop
125125
elif vitesse_m_s > 0:
126126
pwm= self.pwm_stop_prop + self.direction_prop*(self.point_mort_prop + vitesse_pwm)
127-
127+
128128
elif vitesse_m_s < 0:
129129
pwm= self.pwm_stop_prop - self.direction_prop*(self.point_mort_prop - vitesse_pwm)
130-
130+
131131
self.pwm_prop.change_duty_cycle(pwm)
132132
# log.debug(f"Vitesse: {vitesse_m_s} m/s, PWM: {pwm}")
133133

134134

135135
def set_direction_degre(self, angle_degre):
136136
"""Set the car's steering angle in degrees."""
137137
angle_pwm = self.angle_pwm_centre + self.direction * ((self.angle_pwm_max - self.angle_pwm_min) * angle_degre / (2 * MAX_ANGLE))
138-
138+
139139
# Clamp the angle to the maximum and minimum angle
140140
angle_pwm = max(self.angle_pwm_min, min(angle_pwm, self.angle_pwm_max))
141141
# log.debug(f"Angle: {angle_degre}°, PWM: {angle_pwm}")
@@ -166,7 +166,7 @@ def stop(self):
166166
log.info("Arrêt du moteur")
167167
self.lidar.stop()
168168
# exit() #not to be used in prodution/library? https://www.geeksforgeeks.org/python-exit-commands-quit-exit-sys-exit-and-os-_exit/
169-
169+
170170
def has_Crashed(self):
171171

172172
small_distances = [d for d in self.lidar.rDistance[200:880] if 0 < d < CRASH_DIST] # 360 to 720 is the front of the car. 1/3 of the fov of the lidar
@@ -179,7 +179,7 @@ def has_Crashed(self):
179179
time.sleep(0.1)
180180
return True
181181
return False
182-
182+
183183
def turn_around(self):
184184
"""Turn the car around."""
185185
log.info("Turning around")
@@ -241,7 +241,7 @@ def main(self):
241241
bp2 = Button("GPIO6")
242242
try:
243243
Schumacher = Driver(128, 128)
244-
GR86 = Car(Schumacher.ai)
244+
GR86 = Car(Schumacher)
245245
log.info("Initialisation terminée")
246246
if input("Appuyez sur D pour démarrer ou tout autre touche pour quitter") in ("D", "d") or bp2.is_pressed:
247247
log.info("Depart")
@@ -252,9 +252,9 @@ def main(self):
252252
except KeyboardInterrupt:
253253
GR86.stop()
254254
log.info("Le programme a été arrêté par l'utilisateur")
255-
255+
256256
except Exception as e: # catch all exceptions to stop the car
257257
GR86.stop()
258258
log.error("Erreur inconnue")
259259
raise e # re-raise the exception to see the error message
260-
260+

src/HL/Driver.py

Lines changed: 68 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,55 @@
11
import math
2+
from matplotlib import pyplot as plt
23
import scipy as sp
34
from scipy.special import softmax
45
import numpy as np
56
import onnxruntime as ort
7+
import logging as log
68

79
from Autotech_constant import SPEED_LOOKUP, ANGLE_LOOKUP, MODEL_PATH, Temperature
810

911

1012

1113
class Driver:
1214
def __init__(self, context_size=0, horizontal_size=0):
15+
self.context_size = context_size
16+
self.horizontal_size = horizontal_size
1317
self.ai_session = ort.InferenceSession(MODEL_PATH)
1418
self.context = np.zeros([2, context_size, horizontal_size], dtype=np.float32)
1519

20+
if log.getLogger().isEnabledFor(log.DEBUG):
21+
self.fig, self.ax = plt.subplots(4, 1, figsize=(10, 8))
22+
self.steering_bars = self.ax[0].bar(range(16), np.zeros(16), color='blue')
23+
self.steering_avg = [
24+
self.ax[0].plot([0, 0], [0, 1], color=(i/3, 1 - i/3, 0), label='Average')[0]
25+
for i in range(4)
26+
]
27+
self.ax[0].set_ylim(0, 1) # Probabilities range from 0 to 1
28+
self.ax[0].set_title('Steering Action Probabilities')
29+
30+
# Speed bars
31+
self.speed_bars = self.ax[1].bar(range(16), np.zeros(16), color='blue')
32+
self.speed_avg = self.ax[1].plot([0, 0], [0, 1], color='red', label='Average')[0]
33+
self.ax[1].set_ylim(0, 1) # Probabilities range from 0 to 1
34+
self.ax[1].set_title('Speed Action Probabilities')
35+
36+
# LiDAR img
37+
self.lidar_img = self.ax[2].imshow(
38+
np.zeros((128, 128)),
39+
cmap='gray', vmin=0, vmax=np.log(31)
40+
)
41+
self.ax[2].set_title('LiDAR Image')
42+
43+
# Camera img
44+
self.camera_img = self.ax[3].imshow(
45+
np.zeros((128, 128, 3)),
46+
cmap='RdYlGn', vmin=-1, vmax=1
47+
)
48+
self.ax[3].set_title('Camera Image')
49+
50+
def reset(self):
51+
self.context = np.zeros([2, self.context_size, self.horizontal_size], dtype=np.float32)
52+
1653
def omniscent(self, lidar_data, camera_data):
1754
return self.ai_update_lidar_camera(lidar_data, camera_data)
1855

@@ -23,10 +60,12 @@ def simple_minded(self, lidar_data):
2360
return self.farthest_distants(lidar_data)
2461

2562
def ai_update_lidar_camera(self, lidar_data, camera_data):
63+
log.info(f"MIN MAX lidar_data: {(min(lidar_data), max(lidar_data))}")
64+
2665
lidar_data = sp.ndimage.zoom(
2766
np.array(lidar_data, dtype=np.float32),
2867
128/len(lidar_data)
29-
)
68+
) / 1000 * 0.8
3069
camera_data = sp.ndimage.zoom(
3170
np.array(camera_data, dtype=np.float32),
3271
128/len(camera_data)
@@ -38,15 +77,40 @@ def ai_update_lidar_camera(self, lidar_data, camera_data):
3877
], axis=1)
3978

4079
# 2 vectors direction and speed. direction is between hard left at index 0 and hard right at index 1. speed is between min speed at index 0 and max speed at index 1
41-
vect = self.ai_session.run(None, {'input': self.context})[0][0]
80+
vect = self.ai_session.run(None, {'input': self.context[None]})[0][0]
4281

4382
vect_dir, vect_prop = vect[:16], vect[16:] # split the vector in 2
4483
vect_dir = softmax(vect_dir) # distribution de probabilité
4584
vect_prop = softmax(vect_prop)
4685

47-
angle = sum(SPEED_LOOKUP*vect_dir) # moyenne pondérée des angles
86+
if log.getLogger().isEnabledFor(log.DEBUG):
87+
log.info(f"MIN MAX lidar_data: {(min(lidar_data), max(lidar_data))}")
88+
self.lidar_img.set_array(np.log(1 + self.context[0]))
89+
self.camera_img.set_array(self.context[1])
90+
91+
for i, bar in enumerate(self.steering_bars):
92+
bar.set_height(vect_dir[i].item())
93+
94+
for i in range(4):
95+
steering_avg = (vect_dir / vect_dir.sum() * np.arange(16)).sum().item()
96+
self.steering_avg[i].set_xdata([steering_avg, steering_avg])
97+
98+
for i, bar in enumerate(self.speed_bars):
99+
bar.set_height(vect_dir[i].item())
100+
101+
speed_avg = (vect_dir * np.arange(16)).sum().item()
102+
self.speed_avg.set_xdata([speed_avg, speed_avg])
103+
104+
plt.draw()
105+
plt.pause(1e-8)
106+
107+
108+
print(" ".join([f"{x:.1f}" for x in vect_dir]))
109+
print(" ".join([f"{x:.1f}" for x in vect_prop]), flush=True)
110+
111+
angle = sum(ANGLE_LOOKUP*vect_dir) # moyenne pondérée des angles
48112
# moyenne pondérée des vitesses
49-
vitesse = sum(ANGLE_LOOKUP*vect_prop)
113+
vitesse = sum(SPEED_LOOKUP*vect_prop)
50114

51115
return angle, vitesse
52116

src/HL/modelTemporal1.onnx

45.7 MB
Binary file not shown.

src/HL/model_RSNET2D.onnx

0 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)