Skip to content

Commit

Permalink
limits
Browse files Browse the repository at this point in the history
  • Loading branch information
CamDavidsonPilon committed Jul 6, 2023
1 parent 2b91e97 commit ee88be9
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
1 change: 1 addition & 0 deletions pioreactor/automations/temperature/thermostat.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def __init__(self, target_temperature: float | str, **kwargs) -> None:
job_name=self.job_name,
target_name="temperature",
output_limits=(-25, 25), # avoid whiplashing
derivative_smoothing=0.50,
)

def execute(self) -> UpdatedHeaterDC:
Expand Down
18 changes: 11 additions & 7 deletions pioreactor/utils/streaming_calculations.py
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,7 @@ def __init__(
experiment: Optional[str] = None,
job_name: Optional[str] = None,
target_name: Optional[str] = None,
derivative_smoothing=0.1,
derivative_smoothing=0.0,
) -> None:
# PID coefficients
self.Kp = Kp
Expand Down Expand Up @@ -433,6 +433,7 @@ def update(self, input_: float, dt: float = 1.0) -> float:
error = self.setpoint - input_
# Update error sum with clamping for anti-windup
self.error_sum += error * dt

if self.output_limits[0] is not None:
self.error_sum = max(self.error_sum, self.output_limits[0])
if self.output_limits[1] is not None:
Expand All @@ -441,16 +442,19 @@ def update(self, input_: float, dt: float = 1.0) -> float:
# Calculate error derivative with smoothing
derivative = (error - self.error_prev) / dt
derivative = (
self.derivative_smoothing * derivative
+ (1.0 - self.derivative_smoothing) * self.derivative_prev
)
1 - self.derivative_smoothing
) * derivative + self.derivative_smoothing * self.derivative_prev

# Update state variables
self.error_prev = error
self.derivative_prev = derivative

# Calculate PID output
output = self.Kp * error + self.Ki * self.error_sum + self.Kd * derivative
if self.output_limits[0] is not None:
output = max(output, self.output_limits[0])
if self.output_limits[1] is not None:
output = min(output, self.output_limits[1])

self._last_input = input_
self._last_output = output
Expand All @@ -467,9 +471,9 @@ def publish_pid_stats(self) -> None:
"Kd": self.Kd,
"Ki": self.Ki,
"Kp": self.Kp,
"integral": self.error_sum,
"proportional": self.error_prev,
"derivative": self.derivative_prev,
"integral": self.Ki * self.error_sum,
"proportional": self.Kp * self.error_prev,
"derivative": self.Kd * self.derivative_prev,
"latest_input": self._last_input,
"latest_output": self._last_output,
"job_name": self.job_name,
Expand Down

0 comments on commit ee88be9

Please sign in to comment.