-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpid_controller.py
More file actions
163 lines (131 loc) · 4.73 KB
/
pid_controller.py
File metadata and controls
163 lines (131 loc) · 4.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
"""
PID Controller Implementation
A Proportional-Integral-Derivative (PID) controller is a control loop mechanism
that continuously calculates an error value and applies a correction based on
proportional, integral, and derivative terms.
"""
import time
from typing import Optional, Tuple
class PIDController:
"""
A PID Controller class for control system applications.
The PID controller calculates an output based on the error between
a desired setpoint and the current process variable.
"""
def __init__(
self,
kp: float,
ki: float,
kd: float,
setpoint: float = 0.0,
output_limits: Optional[Tuple[float, float]] = None,
):
"""
Initialize the PID controller.
Args:
kp (float): Proportional gain
ki (float): Integral gain
kd (float): Derivative gain
setpoint (float): Target value
output_limits (tuple, optional): Min and max output limits (min, max)
"""
self.kp = kp
self.ki = ki
self.kd = kd
self.setpoint = setpoint
# Output limits
self.output_limits = output_limits
# Internal state variables
self._last_error = 0.0
self._integral = 0.0
self._last_time = None
self._first_update = True
# For tracking
self.error_history = []
self.output_history = []
self.time_history = []
def update(self, process_variable: float, dt: Optional[float] = None) -> float:
"""
Update the PID controller with a new process variable reading.
Args:
process_variable (float): Current measured value
dt (float, optional): Time step. If None, will calculate from system time
Returns:
float: Controller output
"""
# Calculate error
error = self.setpoint - process_variable
# Calculate time step
current_time = time.time()
if dt is None:
# Use automatic time calculation
if self._last_time is None:
self._last_time = current_time
dt = 0.0
else:
dt = current_time - self._last_time
self._last_time = current_time
# If dt is provided explicitly, use it directly
# Proportional term
proportional = self.kp * error
# Integral term
self._integral += error * dt
integral = self.ki * self._integral
# Derivative term
if dt > 0 and not self._first_update:
derivative = self.kd * (error - self._last_error) / dt
else:
derivative = 0.0
# Calculate output
output = proportional + integral + derivative
# Apply output limits
if self.output_limits is not None:
output = max(min(output, self.output_limits[1]), self.output_limits[0])
# Store values for next iteration
self._last_error = error
self._first_update = False
# Store history for analysis
self.error_history.append(error)
self.output_history.append(output)
self.time_history.append(current_time)
return output
def reset(self):
"""Reset the PID controller internal state."""
self._last_error = 0.0
self._integral = 0.0
self._last_time = None
self._first_update = True
self.error_history.clear()
self.output_history.clear()
self.time_history.clear()
def set_tunings(self, kp: float, ki: float, kd: float):
"""Update PID tuning parameters."""
self.kp = kp
self.ki = ki
self.kd = kd
def set_setpoint(self, setpoint: float):
"""Update the target setpoint."""
self.setpoint = setpoint
def set_output_limits(self, limits: Optional[Tuple[float, float]]):
"""Set output limits for the controller."""
self.output_limits = limits
def get_components(
self, process_variable: float, dt: Optional[float] = None
) -> Tuple[float, float, float]:
"""
Get the individual P, I, D components without updating the controller state.
Useful for analysis and tuning.
Args:
process_variable (float): Current measured value
dt (float, optional): Time step
Returns:
tuple: (proportional, integral, derivative) components
"""
error = self.setpoint - process_variable
proportional = self.kp * error
integral = self.ki * self._integral
if dt is not None and dt > 0:
derivative = self.kd * (error - self._last_error) / dt
else:
derivative = 0.0
return proportional, integral, derivative