| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- #!/usr/bin/env python3
- """Golden model for the standalone incremental PID contract harness."""
- from __future__ import annotations
- import json
- from dataclasses import dataclass
- from pathlib import Path
- ROOT = Path(__file__).resolve().parents[1]
- CONFIG_PATH = ROOT / "config" / "pid_channels.json"
- @dataclass(frozen=True)
- class PidConfig:
- a0: int
- a1: int
- a2: int
- out_min: int
- out_max: int
- def __post_init__(self) -> None:
- if self.out_min > self.out_max:
- raise ValueError("out_min must be <= out_max")
- class IncrementalPid:
- """Integer incremental PID model.
- Formula:
- u[k] = clamp(u[k-1] + A0*e[k] + A1*e[k-1] + A2*e[k-2])
- """
- def __init__(self, config: PidConfig) -> None:
- self.config = config
- self.e_k1 = 0
- self.e_k2 = 0
- self.u_k1 = 0
- def update(self, error: int) -> int:
- delta = (
- self.config.a0 * error
- + self.config.a1 * self.e_k1
- + self.config.a2 * self.e_k2
- )
- value = self.u_k1 + delta
- if value > self.config.out_max:
- value = self.config.out_max
- elif value < self.config.out_min:
- value = self.config.out_min
- self.e_k2 = self.e_k1
- self.e_k1 = error
- self.u_k1 = value
- return value
- def run_sequence(errors: list[int], config: PidConfig) -> list[int]:
- pid = IncrementalPid(config)
- return [pid.update(error) for error in errors]
- def load_contract_config(path: Path = CONFIG_PATH) -> dict[str, object]:
- with path.open("r", encoding="utf-8") as handle:
- return json.load(handle)
- def default_pid_config(path: Path = CONFIG_PATH) -> PidConfig:
- payload = load_contract_config(path)
- host = payload["default_host_config"]
- actuator = payload["actuator"]
- if not isinstance(host, dict) or not isinstance(actuator, dict):
- raise ValueError("pid contract config has invalid host or actuator section")
- return PidConfig(
- a0=int(host["a0"]),
- a1=int(host["a1"]),
- a2=int(host["a2"]),
- out_min=int(actuator["out_min"]),
- out_max=int(actuator["out_max"]),
- )
|