pid_model.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #!/usr/bin/env python3
  2. """Golden model for the standalone incremental PID contract harness."""
  3. from __future__ import annotations
  4. import json
  5. from dataclasses import dataclass
  6. from pathlib import Path
  7. ROOT = Path(__file__).resolve().parents[1]
  8. CONFIG_PATH = ROOT / "config" / "pid_channels.json"
  9. @dataclass(frozen=True)
  10. class PidConfig:
  11. a0: int
  12. a1: int
  13. a2: int
  14. out_min: int
  15. out_max: int
  16. def __post_init__(self) -> None:
  17. if self.out_min > self.out_max:
  18. raise ValueError("out_min must be <= out_max")
  19. class IncrementalPid:
  20. """Integer incremental PID model.
  21. Formula:
  22. u[k] = clamp(u[k-1] + A0*e[k] + A1*e[k-1] + A2*e[k-2])
  23. """
  24. def __init__(self, config: PidConfig) -> None:
  25. self.config = config
  26. self.e_k1 = 0
  27. self.e_k2 = 0
  28. self.u_k1 = 0
  29. def update(self, error: int) -> int:
  30. delta = (
  31. self.config.a0 * error
  32. + self.config.a1 * self.e_k1
  33. + self.config.a2 * self.e_k2
  34. )
  35. value = self.u_k1 + delta
  36. if value > self.config.out_max:
  37. value = self.config.out_max
  38. elif value < self.config.out_min:
  39. value = self.config.out_min
  40. self.e_k2 = self.e_k1
  41. self.e_k1 = error
  42. self.u_k1 = value
  43. return value
  44. def run_sequence(errors: list[int], config: PidConfig) -> list[int]:
  45. pid = IncrementalPid(config)
  46. return [pid.update(error) for error in errors]
  47. def load_contract_config(path: Path = CONFIG_PATH) -> dict[str, object]:
  48. with path.open("r", encoding="utf-8") as handle:
  49. return json.load(handle)
  50. def default_pid_config(path: Path = CONFIG_PATH) -> PidConfig:
  51. payload = load_contract_config(path)
  52. host = payload["default_host_config"]
  53. actuator = payload["actuator"]
  54. if not isinstance(host, dict) or not isinstance(actuator, dict):
  55. raise ValueError("pid contract config has invalid host or actuator section")
  56. return PidConfig(
  57. a0=int(host["a0"]),
  58. a1=int(host["a1"]),
  59. a2=int(host["a2"]),
  60. out_min=int(actuator["out_min"]),
  61. out_max=int(actuator["out_max"]),
  62. )