PIDLongitudinalController implements longitudinal control using a PID.
| 89 | |
| 90 | |
| 91 | class PIDLongitudinalController(): |
| 92 | """ |
| 93 | PIDLongitudinalController implements longitudinal control using a PID. |
| 94 | """ |
| 95 | |
| 96 | |
| 97 | def __init__(self, vehicle, K_P=1.0, K_D=0.0, K_I=0.0, dt=0.03): |
| 98 | """ |
| 99 | Constructor method. |
| 100 | |
| 101 | :param vehicle: actor to apply to local planner logic onto |
| 102 | :param K_P: Proportional term |
| 103 | :param K_D: Differential term |
| 104 | :param K_I: Integral term |
| 105 | :param dt: time differential in seconds |
| 106 | """ |
| 107 | self._vehicle = vehicle |
| 108 | self._k_p = K_P |
| 109 | self._k_d = K_D |
| 110 | self._k_i = K_I |
| 111 | self._dt = dt |
| 112 | self._error_buffer = deque(maxlen=10) |
| 113 | |
| 114 | def run_step(self, target_speed, debug=False): |
| 115 | """ |
| 116 | Execute one step of longitudinal control to reach a given target speed. |
| 117 | |
| 118 | :param target_speed: target speed in Km/h |
| 119 | :param debug: boolean for debugging |
| 120 | :return: throttle control |
| 121 | """ |
| 122 | current_speed = get_speed(self._vehicle) |
| 123 | |
| 124 | if debug: |
| 125 | print('Current speed = {}'.format(current_speed)) |
| 126 | |
| 127 | return self._pid_control(target_speed, current_speed) |
| 128 | |
| 129 | def _pid_control(self, target_speed, current_speed): |
| 130 | """ |
| 131 | Estimate the throttle/brake of the vehicle based on the PID equations |
| 132 | |
| 133 | :param target_speed: target speed in Km/h |
| 134 | :param current_speed: current speed of the vehicle in Km/h |
| 135 | :return: throttle/brake control |
| 136 | """ |
| 137 | |
| 138 | error = target_speed - current_speed |
| 139 | self._error_buffer.append(error) |
| 140 | |
| 141 | if len(self._error_buffer) >= 2: |
| 142 | _de = (self._error_buffer[-1] - self._error_buffer[-2]) / self._dt |
| 143 | _ie = sum(self._error_buffer) * self._dt |
| 144 | else: |
| 145 | _de = 0.0 |
| 146 | _ie = 0.0 |
| 147 | |
| 148 | return np.clip((self._k_p * error) + (self._k_d * _de) + (self._k_i * _ie), -1.0, 1.0) |