diff --git a/src/lib.rs b/src/lib.rs index e621b6a..6a64e2e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -23,6 +23,7 @@ pub mod stratum_submit; pub mod stratum_v1; pub mod stratum_wire; pub mod stratum_work; +pub mod tuning; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Vendor { diff --git a/src/tuning.rs b/src/tuning.rs new file mode 100644 index 0000000..6588878 --- /dev/null +++ b/src/tuning.rs @@ -0,0 +1,383 @@ +// SPDX-License-Identifier: MIT +//! Adaptive tuning. +//! +//! The miner targets a power draw, a hashrate, or an operating point chosen for the ambient +//! temperature. Rather than picking a preset, a bounded PID moves the chain frequency inside the +//! profile envelope each control period, and a thermal guard can always override it downward. +//! +//! The controller is deliberately conservative: bounded output, rate limit, deadband, derivative +//! on the measurement (no setpoint kick) and conditional integration (no windup while saturated). + +use crate::detect::Envelope; + +/// What the operator asked for. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum TuningTarget { + /// Hold this DC power draw; efficiency follows from the power point. + PowerW(f32), + /// Maximise hashrate up to this value. + HashrateThs(f32), +} + +/// Controller tuning. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PidConfig { + pub kp: f32, + pub ki: f32, + pub kd: f32, + pub out_min: f32, + pub out_max: f32, + /// Maximum output change per second. + pub max_step_per_s: f32, + /// Errors inside this band are ignored. + pub deadband: f32, +} + +impl Default for PidConfig { + fn default() -> Self { + Self { + kp: 0.5, + ki: 0.1, + kd: 0.0, + out_min: 0.0, + out_max: 1_000.0, + max_step_per_s: 50.0, + deadband: 1.0, + } + } +} + +/// A bounded PID with anti-windup and rate limiting. +#[derive(Clone, Debug)] +pub struct Pid { + config: PidConfig, + integral: f32, + last_measurement: Option, + output: f32, +} + +impl Pid { + pub fn new(config: PidConfig, initial_output: f32) -> Self { + Self { + config, + integral: 0.0, + last_measurement: None, + output: initial_output.clamp(config.out_min, config.out_max), + } + } + + pub fn output(&self) -> f32 { + self.output + } + + /// Advance one control period and return the new output. + pub fn update(&mut self, setpoint: f32, measurement: f32, dt_s: f32) -> f32 { + if !dt_s.is_finite() || dt_s <= 0.0 { + return self.output; + } + let error = setpoint - measurement; + if error.abs() <= self.config.deadband { + self.last_measurement = Some(measurement); + return self.output; + } + let derivative = match self.last_measurement { + Some(previous) => -(measurement - previous) / dt_s, + None => 0.0, + }; + let candidate = self.config.kp * error + self.integral + self.config.kd * derivative; + let saturated = candidate > self.config.out_max || candidate < self.config.out_min; + // Conditional integration: never accumulate while the actuator is pinned in the direction + // of the error, or the loop unwinds slowly after a saturation episode. + let pinning = (candidate > self.config.out_max && error > 0.0) + || (candidate < self.config.out_min && error < 0.0); + if !saturated || !pinning { + self.integral += self.config.ki * error * dt_s; + } + let mut desired = self.config.kp * error + self.integral + self.config.kd * derivative; + desired = desired.clamp(self.config.out_min, self.config.out_max); + let max_step = self.config.max_step_per_s * dt_s; + let step = (desired - self.output).clamp(-max_step, max_step); + self.output = (self.output + step).clamp(self.config.out_min, self.config.out_max); + self.last_measurement = Some(measurement); + self.output + } +} + +/// What the loop needs to know each period. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Observation { + pub power_w: Option, + pub hashrate_ths: Option, + /// Hottest sensor in millidegrees, when telemetry is available. + pub hottest_mc: Option, +} + +/// Why the loop could not produce a command. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum TuningError { + /// The measurement the target needs is missing this period. + NoMeasurement, +} + +/// The tuning loop: one PID over chain frequency, bounded by the profile envelope. +#[derive(Clone, Debug)] +pub struct TuningLoop { + pid: Pid, + envelope: Envelope, + target: TuningTarget, + ceiling_mc: i32, +} + +impl TuningLoop { + /// Start from the conservative floor of the envelope. + pub fn new(target: TuningTarget, envelope: Envelope, pid: PidConfig, ceiling_mc: i32) -> Self { + let config = PidConfig { + out_min: f32::from(envelope.f_min_mhz), + out_max: f32::from(envelope.f_max_mhz), + ..pid + }; + let start = f32::from(envelope.f_min_mhz); + Self { + pid: Pid::new(config, start), + envelope, + target, + ceiling_mc, + } + } + + pub fn frequency_mhz(&self) -> u16 { + self.pid.output().round() as u16 + } + + /// One control period. Returns the frequency to apply, inside the envelope. + pub fn step(&mut self, observation: Observation, dt_s: f32) -> Result { + // Thermal guard: a hot sensor always derates, whatever the target says. + if let Some(hottest) = observation.hottest_mc { + if hottest >= self.ceiling_mc { + let derated = (self.pid.output() - 25.0).max(f32::from(self.envelope.f_min_mhz)); + self.pid = Pid::new( + PidConfig { + out_min: f32::from(self.envelope.f_min_mhz), + out_max: f32::from(self.envelope.f_max_mhz), + ..self.pid.config + }, + derated, + ); + return Ok(self.frequency_mhz()); + } + } + let (setpoint, measurement) = match self.target { + TuningTarget::PowerW(setpoint) => (setpoint, observation.power_w), + TuningTarget::HashrateThs(setpoint) => (setpoint, observation.hashrate_ths), + }; + let measurement = measurement.ok_or(TuningError::NoMeasurement)?; + self.pid.update(setpoint, measurement, dt_s); + Ok(self.frequency_mhz()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn envelope() -> Envelope { + Envelope { + v_min_mv: 1100, + v_max_mv: 1500, + f_min_mhz: 300, + f_max_mhz: 700, + } + } + + #[test] + fn pid_drives_the_plant_to_the_setpoint() { + let mut pid = Pid::new( + PidConfig { + kp: 0.02, + ki: 0.01, + kd: 0.0, + out_min: 0.0, + out_max: 700.0, + max_step_per_s: 1_000.0, + deadband: 0.0, + }, + 0.0, + ); + // Plant: power = 5 W per MHz. + let mut power = 0.0_f32; + for _ in 0..400 { + // Setpoint 3 kW needs 600 MHz, inside the 700 MHz ceiling of the controller. + let freq = pid.update(3_000.0, power, 1.0); + power = 5.0 * freq; + } + assert!((power - 3_000.0).abs() < 50.0, "power settled at {power}"); + } + + #[test] + fn output_is_rate_limited() { + let mut pid = Pid::new( + PidConfig { + kp: 1.0, + ki: 0.0, + kd: 0.0, + out_min: 0.0, + out_max: 1_000.0, + max_step_per_s: 10.0, + deadband: 0.0, + }, + 0.0, + ); + let first = pid.update(1_000.0, 0.0, 1.0); + assert!((first - 10.0).abs() < f32::EPSILON, "got {first}"); + let second = pid.update(1_000.0, 0.0, 1.0); + assert!((second - 20.0).abs() < f32::EPSILON, "got {second}"); + } + + #[test] + fn deadband_holds_the_output() { + let mut pid = Pid::new( + PidConfig { + kp: 1.0, + ki: 0.1, + kd: 0.0, + out_min: 0.0, + out_max: 1_000.0, + max_step_per_s: 100.0, + deadband: 5.0, + }, + 100.0, + ); + let before = pid.output(); + let after = pid.update(102.0, 100.0, 1.0); + assert!((after - before).abs() < f32::EPSILON); + } + + #[test] + fn saturation_does_not_wind_up_the_integral() { + let mut pid = Pid::new( + PidConfig { + kp: 1.0, + ki: 1.0, + kd: 0.0, + out_min: 0.0, + out_max: 100.0, + max_step_per_s: 1_000.0, + deadband: 0.0, + }, + 0.0, + ); + for _ in 0..100 { + pid.update(1_000.0, 0.0, 1.0); + } + assert!((pid.output() - 100.0).abs() < 0.01); + // Reverse the error: the output must leave the rail promptly. + for _ in 0..5 { + pid.update(0.0, 200.0, 1.0); + } + assert!( + pid.output() < 99.0, + "output stuck at the rail: {}", + pid.output() + ); + } + + #[test] + fn tuning_loop_moves_frequency_inside_the_envelope() { + let mut loop_ = TuningLoop::new( + TuningTarget::PowerW(2_400.0), + envelope(), + PidConfig { + kp: 0.2, + ki: 0.05, + kd: 0.0, + out_min: 0.0, + out_max: 0.0, + max_step_per_s: 50.0, + deadband: 0.0, + }, + 95_000, + ); + let mut freq = loop_.frequency_mhz(); + for _ in 0..100 { + let power = 4.0 * f32::from(freq); + freq = loop_ + .step( + Observation { + power_w: Some(power), + hashrate_ths: None, + hottest_mc: Some(70_000), + }, + 1.0, + ) + .expect("step"); + assert!((300..=700).contains(&freq), "out of envelope: {freq}"); + } + let power = 4.0 * f32::from(freq); + assert!((power - 2_400.0).abs() < 200.0, "power settled at {power}"); + } + + #[test] + fn thermal_guard_derates_regardless_of_target() { + let mut loop_ = TuningLoop::new( + TuningTarget::HashrateThs(200.0), + envelope(), + PidConfig::default(), + 90_000, + ); + // Push frequency up first. + for _ in 0..50 { + loop_ + .step( + Observation { + power_w: None, + hashrate_ths: Some(10.0), + hottest_mc: Some(60_000), + }, + 1.0, + ) + .expect("step"); + } + let hot = loop_.frequency_mhz(); + let derated = loop_ + .step( + Observation { + power_w: None, + hashrate_ths: Some(10.0), + hottest_mc: Some(91_000), + }, + 1.0, + ) + .expect("step"); + assert!( + derated < hot, + "thermal guard did not derate: {derated} vs {hot}" + ); + } + + #[test] + fn missing_measurement_is_an_error() { + let mut loop_ = TuningLoop::new( + TuningTarget::PowerW(3_000.0), + envelope(), + PidConfig::default(), + 95_000, + ); + assert_eq!( + loop_.step( + Observation { + power_w: None, + hashrate_ths: Some(1.0), + hottest_mc: None + }, + 1.0 + ), + Err(TuningError::NoMeasurement) + ); + } + + #[test] + fn zero_dt_holds_the_output() { + let mut pid = Pid::new(PidConfig::default(), 42.0); + assert!((pid.update(100.0, 0.0, 0.0) - 42.0).abs() < f32::EPSILON); + } +}