Skip to main content

sim_components/
pneumatic.rs

1//! Pneumatic cylinders beside the servo axes: a double-acting cylinder moved by a directional valve, not by a drive.
2//! `attach` puts the cylinders of a config on any machine; each brings states of its own after the machine's, its
3//! signals (`cylinder.<id>.*`) and its checks (`cushion-energy`, `load-factor`). The cycle commands it by its valve
4//! (a segment's `valves`) and waits for its end-position sensors (a segment's `wait`), see `control`.
5//!
6//! The model (docs/model-reference.md, "Pneumatic cylinder"):
7//!
8//! - Two chambers, cap side (1, area A1 = pi D^2 / 4) and rod side (2, A2 = A1 - pi d^2 / 4), each a control volume of
9//!   an ideal gas (R = 287.058 J/(kg K), kappa = 1.4) with its mass m and internal energy U as states:
10//!   V1 = V01 + A1 x, V2 = V02 + A2 (s - x), p = (kappa - 1) U / V, T = p V / (m R),
11//!   dm/dt = mdot, dU/dt = h_in mdot + Q - p dV/dt, h = cp T of the gas that flows (the port's going in, the chamber's
12//!   going out), Q = alpha A (T_wall - T) (`heat_transfer_w_k`). alpha A = 0 is adiabatic; alpha A large against
13//!   m cv / (the process's time) is isothermal: the two limits.
14//! - Every flow path an ISO 6358 element of sonic conductance C and critical pressure ratio b: mdot = C p_up rho0
15//!   sqrt(T0 / T_up) psi, psi = 1 at p_down / p_up <= b (choked), sqrt(1 - ((r - b) / (1 - b))^2) above; rho0 =
16//!   1.185 kg/m3 and T0 = 293.15 K (ANR, ISO 8778). Elements in series (valve, tube, throttle) combine to
17//!   C = (sum C_i^-3)^(-1/3) and 1 - b = C^2 sum (1 - b_i) / C_i^2: the second keeps the sum of the pressure drops at
18//!   small drops, where the elliptic law is dp ~ mdot^2 (1 - b) / C^2 (`Flow::series`).
19//! - A 5/2 valve (or a 5/3 with a closed centre) that switches `valve_switch_time_s` after its command; inflow through
20//!   valve and tube (the throttles' and the cushions' check valves open), outflow also through the meter-out throttle
21//!   of that chamber, or within the cushion length of its end through the cushion's bleed screw behind that throttle.
22//! - The piston: (m + payload) dv/dt = p1 A1 - p2 A2 - p_atm (A1 - A2) - F_load - m g sin(incline) - F_seal + F_stop,
23//!   the seal's friction a Stribeck curve whose Coulomb level rises with the chambers' mean gauge pressure, the end
24//!   stops `mech::HardStop` (elastic bumpers).
25//!
26//! shortcut: the flow law's last 0.5 % before the pressures meet is a straight line through zero (`LINEAR`), not
27//! the root: the root's slope is infinite there, which no fixed step integrates. ISO 6358-3 has a laminar region of
28//! its own there; take it in if a test against measured data ever needs the last 0.5 % of a pressure.
29//! The cylinder rides on the machine without acting back on it: its weight and its reaction are in the masses of the
30//! machine's body that carries it. That is exact only for a cylinder at right angles to the linear axes that carry it
31//! and on no rotary one, so `attach` checks it (`along_carrying_axis`): a cylinder extends in the x-z plane at
32//! `incline_deg` above x, direction (cos, 0, sin), and a file whose cylinder has a component along the direction of a
33//! linear axis that carries it, or rides on a rotary axis, is refused.
34
35use crate::mech::HardStop;
36use sim_core::{AxisInfo, BeltSection, FrictionContact, MotorInfo, ThermalPart};
37use sim_core::{Config, ConfigError, Machine, RatingCheck, Scene, SignalInfo};
38
39/// Gas constant of air, J/(kg K), and its ratio of specific heats.
40pub const R: f64 = 287.058;
41pub const KAPPA: f64 = 1.4;
42pub const CV: f64 = R / (KAPPA - 1.0);
43pub const CP: f64 = KAPPA * CV;
44/// ANR reference (ISO 8778, the reference of ISO 6358): density and temperature.
45pub const RHO0: f64 = 1.185;
46pub const T0: f64 = 293.15;
47/// A catalogue's dm^3/(s bar) in m^3/(s Pa).
48pub const DM3_S_BAR: f64 = 1e-3 / 1e5;
49/// The flow law is a straight line over the last `LINEAR` of the pressure ratio before 1 (see the module's shortcut).
50const LINEAR: f64 = 0.005;
51/// The most an eigenvalue (rate, or angular frequency) times the integrator's sub-step may be: RK4 is stable to 2.78 on
52/// the real axis and 2.83 on the imaginary one; 2 leaves room for what the estimates leave out.
53const STABLE: f64 = 2.0;
54const G: f64 = 9.80665;
55/// States per cylinder: position, speed, mass and internal energy of the cap and the rod chamber, then running totals
56/// for the balances: air drawn from the supply (kg), enthalpy from the supply and to the exhaust (J), heat from the
57/// wall (J), work lost to seal friction and the stops' dampers (J).
58pub const STATES: usize = 11;
59const X: usize = 0;
60const V: usize = 1;
61const M1: usize = 2;
62const U1: usize = 3;
63const M2: usize = 4;
64const U2: usize = 5;
65pub const AIR: usize = 6;
66pub const H_IN: usize = 7;
67pub const H_OUT: usize = 8;
68pub const HEAT: usize = 9;
69pub const LOSS: usize = 10;
70
71/// The keys of a cylinder's table (`values` of a `[[machine.cylinder]]`), with placeholder values: what a machine
72/// file's schema adds for each cylinder. docs/config-reference.md tells them.
73pub const TABLE: &str = r#"
74piston_diameter_m = 0.032
75rod_diameter_m = 0.012
76stroke_m = 0.1
77moved_mass_kg = 0.5
78payload_kg = 0.0
79incline_deg = 0.0
80dead_volume_cap_m3 = 5.0e-6
81dead_volume_rod_m3 = 5.0e-6
82supply_pressure_bar = 6.0
83ambient_pressure_pa = 101325.0
84ambient_temperature_k = 293.15
85heat_transfer_w_k = 0.05
86valve = "5/2"
87valve_c_dm3_s_bar = 1.0
88valve_b = 0.3
89valve_switch_time_s = 0.015
90tube_c_dm3_s_bar = 2.0
91tube_b = 0.4
92throttle_extend_c_dm3_s_bar = 0.3
93throttle_retract_c_dm3_s_bar = 0.3
94throttle_b = 0.3
95cushion_length_m = 0.017
96cushion_bleed_c_dm3_s_bar = 0.05
97cushion_bleed_b = 0.3
98stop_stiffness_n_m = 1.0e6
99stop_damping_n_s_m = 500.0
100friction_coulomb_n = 10.0
101friction_coulomb_n_bar = 2.0
102friction_stiction_ratio = 1.5
103friction_stribeck_m_s = 0.01
104friction_viscous_n_s_m = 20.0
105friction_smoothing_m_s = 0.002
106load_force_n = 0.0
107sensor_band_m = 0.002
108sensor_delay_s = 0.005
109start = "retracted"
110rated_cushion_energy_j = 0.4
111load_factor_limit = 0.7
112compressor_energy_kwh_m3 = 0.12
113"#;
114
115/// The effect switches a file with cylinders has beside the shared ones.
116pub const EFFECTS: [&str; 2] = ["cylinder_friction", "cylinder_cushion"];
117
118/// One ISO 6358 flow element: sonic conductance C, m^3/(s Pa) (ANR), and critical pressure ratio b.
119#[derive(Debug, Clone, Copy, PartialEq)]
120pub struct Flow {
121    pub c: f64,
122    pub b: f64,
123}
124
125/// The ISO 6358 flow function at the pressure ratio r = p_down / p_up (at most 1).
126pub fn psi(r: f64, b: f64) -> f64 {
127    let ellipse = |r: f64| (1.0 - ((r - b) / (1.0 - b)).powi(2)).max(0.0).sqrt();
128    if r <= b {
129        1.0
130    } else if r < 1.0 - LINEAR {
131        ellipse(r)
132    } else {
133        ellipse(1.0 - LINEAR) * (1.0 - r).max(0.0) / LINEAR
134    }
135}
136
137impl Flow {
138    pub fn new(c_dm3_s_bar: f64, b: f64) -> Self {
139        Self { c: c_dm3_s_bar * DM3_S_BAR, b }
140    }
141
142    /// Elements one after the other (see the module's text).
143    pub fn series(parts: &[Flow]) -> Flow {
144        let c = parts.iter().map(|f| f.c.powi(-3)).sum::<f64>().powf(-1.0 / 3.0);
145        let b = 1.0 - c * c * parts.iter().map(|f| (1.0 - f.b) / (f.c * f.c)).sum::<f64>();
146        Flow { c, b: b.max(0.0) }
147    }
148
149    /// Mass flow from `p_up` at `t_up` down to `p_down`, kg/s; zero where `p_down` is not lower.
150    pub fn mass_flow(&self, p_up: f64, t_up: f64, p_down: f64) -> f64 {
151        if p_up <= p_down {
152            return 0.0;
153        }
154        self.c * p_up * RHO0 * (T0 / t_up).sqrt() * psi(p_down / p_up, self.b)
155    }
156
157    /// The slope of the flow law's straight end, d psi / d r, for the stability estimate.
158    fn end_slope(&self) -> f64 {
159        psi(1.0 - LINEAR, self.b) / LINEAR
160    }
161}
162
163/// The seal's friction: a Stribeck curve, smoothed through zero speed, whose levels rise with the pressure.
164#[derive(Debug, Clone, Copy)]
165struct Seal {
166    coulomb: f64,
167    per_pa: f64,
168    stiction_ratio: f64,
169    stribeck: f64,
170    viscous: f64,
171    smoothing: f64,
172}
173
174impl Seal {
175    /// The force against the speed `v` with the chambers' mean gauge pressure `gauge`, N.
176    fn force(&self, v: f64, gauge: f64) -> f64 {
177        let level = self.coulomb + self.per_pa * gauge.max(0.0);
178        let breakaway = level * (1.0 + (self.stiction_ratio - 1.0) * (-(v / self.stribeck).powi(2)).exp());
179        breakaway * (v / self.smoothing).tanh() + self.viscous * v
180    }
181}
182
183/// What the flows are at a state: into chamber 1 and 2 (kg/s), and the supply's and the exhaust's share.
184#[derive(Debug, Clone, Copy, Default)]
185pub struct Flows {
186    pub into: [f64; 2],
187    pub supply: f64,
188    pub supply_enthalpy: f64,
189    pub exhaust: f64,
190    pub exhaust_enthalpy: f64,
191}
192
193/// What a cylinder keeps from step to step outside the state: the valve, the sensors and what it measured on its
194/// strokes. Numbers only, so that it is the machine's memory as it is (`to_vec`).
195#[derive(Debug, Clone, Copy, Default, PartialEq)]
196struct Track {
197    command: f64,
198    spool: f64,
199    /// The command the valve switches to and the time left until it does; below 0: none pending.
200    pending: f64,
201    pending_left: f64,
202    sensor_time: [f64; 2],
203    /// Since the spool last switched, s.
204    since_switch: f64,
205    arrived: f64,
206    cushioned: f64,
207    contact_time: f64,
208    stroke_time: [f64; 2],
209    impact_speed: f64,
210    impact_energy: f64,
211    end_speed: f64,
212    bounce: f64,
213    settling: f64,
214    air_mark: f64,
215    air_cycle: f64,
216}
217
218const TRACK: usize = 19;
219
220impl Track {
221    fn to_vec(self) -> [f64; TRACK] {
222        let t = self;
223        [
224            t.command,
225            t.spool,
226            t.pending,
227            t.pending_left,
228            t.sensor_time[0],
229            t.sensor_time[1],
230            t.since_switch,
231            t.arrived,
232            t.cushioned,
233            t.contact_time,
234            t.stroke_time[0],
235            t.stroke_time[1],
236            t.impact_speed,
237            t.impact_energy,
238            t.end_speed,
239            t.bounce,
240            t.settling,
241            t.air_mark,
242            t.air_cycle,
243        ]
244    }
245    fn from_slice(m: &[f64]) -> Self {
246        Self {
247            command: m[0],
248            spool: m[1],
249            pending: m[2],
250            pending_left: m[3],
251            sensor_time: [m[4], m[5]],
252            since_switch: m[6],
253            arrived: m[7],
254            cushioned: m[8],
255            contact_time: m[9],
256            stroke_time: [m[10], m[11]],
257            impact_speed: m[12],
258            impact_energy: m[13],
259            end_speed: m[14],
260            bounce: m[15],
261            settling: m[16],
262            air_mark: m[17],
263            air_cycle: m[18],
264        }
265    }
266}
267
268/// A double-acting cylinder with its valve, throttles and cushions (see the module's text).
269#[derive(Debug, Clone)]
270pub struct Cylinder {
271    pub id: String,
272    pub key: String,
273    pub a1: f64,
274    pub a2: f64,
275    pub stroke: f64,
276    pub mass: f64,
277    pub payload: f64,
278    payload_on: bool,
279    /// Gravity's component against +x per kg, m/s^2 (g sin incline, 0 with effects.gravity off).
280    pub gravity: f64,
281    incline: f64,
282    pub dead: [f64; 2],
283    /// Supply and ambient pressure (absolute), Pa; ambient (and supply, and wall) temperature, K.
284    pub supply: f64,
285    pub ambient: f64,
286    pub temperature: f64,
287    pub heat_transfer: f64,
288    pub closed_centre: bool,
289    pub switch_time: f64,
290    /// Into a chamber: valve and tube. Out of chamber 1 and 2: valve, tube and that chamber's throttle; and within
291    /// the cushion: valve, tube and the bleed.
292    pub inflow: Flow,
293    pub outflow: [Flow; 2],
294    pub bleed: [Flow; 2],
295    /// Cushion length, m; 0 with effects.cylinder_cushion off.
296    pub cushion: f64,
297    stops: HardStop,
298    seal: Option<Seal>,
299    pub load: f64,
300    sensor_band: f64,
301    sensor_delay: f64,
302    start_extended: bool,
303    rated_cushion_energy: f64,
304    load_factor_limit: f64,
305    compressor_j_per_kg: f64,
306    track: Track,
307}
308
309/// The cylinder's signals, after `cylinder.<id>.`, with their quantity keys (`quantity-cylinder-<name>`) and units.
310pub const SIGNALS: [(&str, &str); 21] = [
311    ("position", "m"),
312    ("velocity", "m/s"),
313    ("pressure_cap", "Pa"),
314    ("pressure_rod", "Pa"),
315    ("temperature_cap", "K"),
316    ("temperature_rod", "K"),
317    ("spool", ""),
318    ("sensor_retracted", ""),
319    ("sensor_extended", ""),
320    ("supply_flow", "l/min"),
321    ("air", "l"),
322    ("air_cycle", "l"),
323    ("compressor_energy", "J"),
324    ("stroke_time_extend", "s"),
325    ("stroke_time_retract", "s"),
326    ("impact_speed", "m/s"),
327    ("impact_energy", "J"),
328    ("end_speed", "m/s"),
329    ("bounce", "m"),
330    ("settling_time", "s"),
331    ("load_factor", ""),
332];
333
334fn text<'a>(cfg: &'a Config, path: &str) -> Result<&'a str, ConfigError> {
335    cfg.get(path)?.as_str().ok_or_else(|| ConfigError::Type(path.into()))
336}
337
338impl Cylinder {
339    /// The cylinder `id` from its table at `path`, integrated in sub-steps of `h` seconds: refused where that step
340    /// would not be stable (`error-cylinder-unstable`).
341    pub fn from_config(cfg: &Config, id: &str, key: &str, path: &str, h: f64) -> Result<Self, ConfigError> {
342        let at = |k: &str| format!("{path}.{k}");
343        let pos = |k: &str| cfg.positive(&at(k));
344        let nonneg = |k: &str| cfg.non_negative(&at(k));
345        let ratio = |k: &str| -> Result<f64, ConfigError> {
346            let b = cfg.non_negative(&at(k))?;
347            if b < 0.95 { Ok(b) } else { Err(ConfigError::Invalid(at(k))) }
348        };
349        let flow = |c: &str, b: &str| -> Result<Flow, ConfigError> { Ok(Flow::new(pos(c)?, ratio(b)?)) };
350        let (d, rod) = (pos("piston_diameter_m")?, pos("rod_diameter_m")?);
351        if rod >= d {
352            return Err(ConfigError::Invalid(at("rod_diameter_m")));
353        }
354        let a1 = std::f64::consts::PI * d * d / 4.0;
355        let a2 = a1 - std::f64::consts::PI * rod * rod / 4.0;
356        let stroke = pos("stroke_m")?;
357        let ambient = pos("ambient_pressure_pa")?;
358        let supply = ambient + nonneg("supply_pressure_bar")? * 1e5;
359        let incline = cfg.f64(&at("incline_deg"))?.to_radians();
360        let gravity = if cfg.bool("effects.gravity")? { G * incline.sin() } else { 0.0 };
361        let payload = if cfg.bool("effects.payload")? { nonneg("payload_kg")? } else { 0.0 };
362        let closed_centre = match text(cfg, &at("valve"))? {
363            "5/2" => false,
364            "5/3" => true,
365            _ => return Err(ConfigError::Invalid(at("valve"))),
366        };
367        let start_extended = match text(cfg, &at("start"))? {
368            "retracted" => false,
369            "extended" => true,
370            _ => return Err(ConfigError::Invalid(at("start"))),
371        };
372        let (valve, tube) = (flow("valve_c_dm3_s_bar", "valve_b")?, flow("tube_c_dm3_s_bar", "tube_b")?);
373        let throttle_b = ratio("throttle_b")?;
374        // During the extend stroke the rod chamber exhausts: its throttle is the one that sets the extend speed.
375        let throttles = [
376            Flow::new(pos("throttle_retract_c_dm3_s_bar")?, throttle_b),
377            Flow::new(pos("throttle_extend_c_dm3_s_bar")?, throttle_b),
378        ];
379        let bleed = flow("cushion_bleed_c_dm3_s_bar", "cushion_bleed_b")?;
380        let cushion = if cfg.bool("effects.cylinder_cushion")? { nonneg("cushion_length_m")? } else { 0.0 };
381        if cushion > 0.5 * stroke {
382            return Err(ConfigError::Invalid(at("cushion_length_m")));
383        }
384        let stiction_ratio = cfg.f64(&at("friction_stiction_ratio"))?;
385        if stiction_ratio < 1.0 {
386            return Err(ConfigError::Invalid(at("friction_stiction_ratio")));
387        }
388        let seal = Seal {
389            coulomb: nonneg("friction_coulomb_n")?,
390            per_pa: nonneg("friction_coulomb_n_bar")? / 1e5,
391            stiction_ratio,
392            stribeck: pos("friction_stribeck_m_s")?,
393            viscous: nonneg("friction_viscous_n_s_m")?,
394            smoothing: pos("friction_smoothing_m_s")?,
395        };
396        let seal = cfg.bool("effects.cylinder_friction")?.then_some(seal);
397        let temperature = pos("ambient_temperature_k")?;
398        let cylinder = Self {
399            id: id.to_string(),
400            key: key.to_string(),
401            a1,
402            a2,
403            stroke,
404            mass: pos("moved_mass_kg")?,
405            payload,
406            payload_on: true,
407            gravity,
408            incline,
409            dead: [pos("dead_volume_cap_m3")?, pos("dead_volume_rod_m3")?],
410            supply,
411            ambient,
412            temperature,
413            heat_transfer: nonneg("heat_transfer_w_k")?,
414            closed_centre,
415            switch_time: nonneg("valve_switch_time_s")?,
416            inflow: Flow::series(&[valve, tube]),
417            outflow: throttles.map(|t| Flow::series(&[valve, tube, t])),
418            // The cushion's bleed screw sits behind the port's meter-out throttle, so that is in series too.
419            bleed: throttles.map(|t| Flow::series(&[valve, tube, bleed, t])),
420            cushion,
421            stops: HardStop { stiffness: pos("stop_stiffness_n_m")?, damping: nonneg("stop_damping_n_s_m")? },
422            seal,
423            load: cfg.f64(&at("load_force_n"))?,
424            sensor_band: pos("sensor_band_m")?,
425            sensor_delay: nonneg("sensor_delay_s")?,
426            start_extended,
427            rated_cushion_energy: pos("rated_cushion_energy_j")?,
428            load_factor_limit: pos("load_factor_limit")?,
429            compressor_j_per_kg: nonneg("compressor_energy_kwh_m3")? * 3.6e6 / RHO0,
430            track: Track::default(),
431        };
432        if let Some((what, rate)) = cylinder.stiffest().into_iter().find(|(_, rate)| rate * h > STABLE) {
433            return Err(ConfigError::Part(
434                "error-cylinder-unstable",
435                format!("{path}: {what} {rate:.0} 1/s, sim.dt_s / sim.substeps at most {:.3e} s", STABLE / rate),
436            ));
437        }
438        let mut cylinder = cylinder;
439        let spool = cylinder.start_command();
440        // At rest in the end it starts at: arrived there, nothing to measure until the valve switches.
441        cylinder.track = Track {
442            command: spool,
443            spool,
444            pending: spool,
445            pending_left: -1.0,
446            arrived: 1.0,
447            cushioned: 1.0,
448            ..Track::default()
449        };
450        Ok(cylinder)
451    }
452
453    fn start_command(&self) -> f64 {
454        if self.start_extended { 1.0 } else { -1.0 }
455    }
456
457    fn moved(&self) -> f64 {
458        self.mass + if self.payload_on { self.payload } else { 0.0 }
459    }
460
461    /// The stiffest rates of the model at its worst (smallest chamber, highest pressure), 1/s: the flow into the
462    /// smallest dead volume where the law is a straight line, the air spring of it, the stops, the seal's smoothing
463    /// and the heat transfer. What each is, for the message.
464    fn stiffest(&self) -> Vec<(&'static str, f64)> {
465        let small = self.dead[0].min(self.dead[1]);
466        let widest = self.inflow.c.max(self.outflow[0].c).max(self.outflow[1].c);
467        let slope = [self.inflow, self.outflow[0], self.outflow[1]].iter().map(Flow::end_slope).fold(0.0, f64::max);
468        let m = self.mass;
469        let mut out = vec![
470            ("flow", KAPPA * R * self.temperature * RHO0 * widest * slope / small),
471            (
472                "air spring",
473                (KAPPA * self.supply * (self.a1 * self.a1 / self.dead[0]).max(self.a2 * self.a2 / self.dead[1]) / m)
474                    .sqrt(),
475            ),
476            ("end stop", (self.stops.stiffness / m).sqrt().max(self.stops.damping / m)),
477            ("heat transfer", self.heat_transfer * (KAPPA - 1.0) * self.temperature / (self.ambient * small)),
478        ];
479        if let Some(s) = self.seal {
480            let level = (s.coulomb + s.per_pa * (self.supply - self.ambient)) * s.stiction_ratio;
481            out.push(("seal friction", (level / s.smoothing + s.viscous) / m));
482        }
483        out
484    }
485
486    pub fn volumes(&self, x: f64) -> [f64; 2] {
487        [self.dead[0] + self.a1 * x, self.dead[1] + self.a2 * (self.stroke - x)]
488    }
489
490    /// Pressure and temperature of both chambers at state `s` (this cylinder's).
491    pub fn gas(&self, s: &[f64]) -> [[f64; 2]; 2] {
492        let v = self.volumes(s[X]);
493        let p = [(KAPPA - 1.0) * s[U1] / v[0], (KAPPA - 1.0) * s[U2] / v[1]];
494        [p, [p[0] * v[0] / (s[M1] * R), p[1] * v[1] / (s[M2] * R)]]
495    }
496
497    /// The net force on the piston but the seal's and the stops', N, towards +x (extending).
498    fn pressure_force(&self, p: [f64; 2]) -> f64 {
499        p[0] * self.a1 - p[1] * self.a2 - self.ambient * (self.a1 - self.a2) - self.load - self.moved() * self.gravity
500    }
501
502    fn seal_force(&self, v: f64, p: [f64; 2]) -> f64 {
503        self.seal.map_or(0.0, |s| s.force(v, 0.5 * (p[0] + p[1]) - self.ambient))
504    }
505
506    /// The flows at state `s` with the spool at `spool` (+1, -1, 0).
507    pub fn flows(&self, s: &[f64], spool: f64) -> Flows {
508        let [p, t] = self.gas(s);
509        let x = s[X];
510        let mut f = Flows::default();
511        for i in 0..2 {
512            // Chamber 1 is on the supply while extending, chamber 2 while retracting.
513            let on_supply = if i == 0 { spool > 0.5 } else { spool < -0.5 };
514            if spool.abs() < 0.5 {
515                continue;
516            }
517            let (port, port_t) =
518                if on_supply { (self.supply, self.temperature) } else { (self.ambient, self.temperature) };
519            let mdot = if port > p[i] {
520                self.inflow.mass_flow(port, port_t, p[i])
521            } else {
522                // Within the cushion length of this chamber's end the spear closes the main bore: the bleed alone, blended
523                // in over the first millimetre so that the rates stay continuous.
524                let to_end = if i == 0 { x } else { self.stroke - x };
525                let ramp = (0.001f64).min(self.cushion);
526                let w = if self.cushion > 0.0 { ((self.cushion - to_end) / ramp).clamp(0.0, 1.0) } else { 0.0 };
527                let out = (1.0 - w) * self.outflow[i].mass_flow(p[i], t[i], port)
528                    + w * self.bleed[i].mass_flow(p[i], t[i], port);
529                -out
530            };
531            let enthalpy = CP * mdot * if mdot > 0.0 { port_t } else { t[i] };
532            f.into[i] = mdot;
533            if on_supply {
534                f.supply += mdot;
535                f.supply_enthalpy += enthalpy;
536            } else {
537                f.exhaust -= mdot;
538                f.exhaust_enthalpy -= enthalpy;
539            }
540        }
541        f
542    }
543
544    /// The rates of this cylinder's states at `s` (`STATES` of each).
545    pub fn derivatives(&self, s: &[f64], out: &mut [f64]) {
546        self.derivatives_with(s, self.track.spool, out)
547    }
548
549    pub fn derivatives_with(&self, s: &[f64], spool: f64, out: &mut [f64]) {
550        let [p, t] = self.gas(s);
551        let (x, v) = (s[X], s[V]);
552        let f = self.flows(s, spool);
553        let dv = [self.a1 * v, -self.a2 * v];
554        let heat = [0, 1].map(|i| self.heat_transfer * (self.temperature - t[i]));
555        let enthalpy = [0, 1].map(|i| CP * f.into[i] * if f.into[i] > 0.0 { self.temperature } else { t[i] });
556        let seal = self.seal_force(v, p);
557        let stop = self.stops.force(x, v, self.stroke);
558        out[X] = v;
559        out[V] = (self.pressure_force(p) - seal + stop) / self.moved();
560        out[M1] = f.into[0];
561        out[U1] = enthalpy[0] + heat[0] - p[0] * dv[0];
562        out[M2] = f.into[1];
563        out[U2] = enthalpy[1] + heat[1] - p[1] * dv[1];
564        out[AIR] = f.supply;
565        out[H_IN] = f.supply_enthalpy;
566        out[H_OUT] = f.exhaust_enthalpy;
567        out[HEAT] = heat[0] + heat[1];
568        out[LOSS] = seal * v + self.stops.loss_power(x, v, self.stroke);
569    }
570
571    /// At rest in the end the valve holds it at: the driven chamber at the supply pressure, the other at ambient, the
572    /// piston pressed into its stop as far as the net force deflects it, the gas at ambient temperature. Appended to
573    /// `state`.
574    pub fn rest(&self, spool: f64, state: &mut Vec<f64>) {
575        let extended = spool > 0.0;
576        let p = if extended { [self.supply, self.ambient] } else { [self.ambient, self.supply] };
577        let force = self.pressure_force(p);
578        let x = if extended {
579            self.stroke + force.max(0.0) / self.stops.stiffness
580        } else {
581            force.min(0.0) / self.stops.stiffness
582        };
583        let v = self.volumes(x);
584        let mut s = [0.0; STATES];
585        s[X] = x;
586        s[M1] = p[0] * v[0] / (R * self.temperature);
587        s[U1] = p[0] * v[0] / (KAPPA - 1.0);
588        s[M2] = p[1] * v[1] / (R * self.temperature);
589        s[U2] = p[1] * v[1] / (KAPPA - 1.0);
590        state.extend(s);
591    }
592
593    /// Mechanical energy (kinetic, gravity, the load's and the atmosphere's work on the rod, the stops' springs), J.
594    pub fn mechanical_energy(&self, s: &[f64]) -> f64 {
595        let (x, v) = (s[X], s[V]);
596        0.5 * self.moved() * v * v
597            + (self.moved() * self.gravity + self.load + self.ambient * (self.a1 - self.a2)) * x
598            + self.stops.energy(x, self.stroke)
599    }
600
601    /// The gas's internal energy in both chambers, J.
602    pub fn gas_energy(&self, s: &[f64]) -> f64 {
603        s[U1] + s[U2]
604    }
605
606    /// The load over the theoretical force at the supply's gauge pressure, the worse of the two strokes: what the
607    /// cylinder has to push against gravity and the load, over p_g A1 extending and p_g A2 retracting.
608    pub fn load_factor(&self) -> f64 {
609        let gauge = self.supply - self.ambient;
610        let against = self.load + (self.mass + self.payload) * self.gravity;
611        (against.max(0.0) / (gauge * self.a1)).max((-against).max(0.0) / (gauge * self.a2))
612    }
613
614    /// The command of the valve, from the cycle: switches after `switch_time` where it differs from where the valve
615    /// goes. A 5/2 valve has no centre: 0 keeps it where it is.
616    pub fn command(&mut self, command: f64) {
617        let command = if !self.closed_centre && command.abs() < 0.5 { self.track.command } else { command.signum() };
618        let going = if self.track.pending_left < 0.0 { self.track.spool } else { self.track.pending };
619        self.track.command = command;
620        if command != going {
621            (self.track.pending, self.track.pending_left) = (command, self.switch_time);
622        }
623    }
624
625    /// The step of `dt` done: the valve's delay, the sensors' delay, and what the stroke measured.
626    fn stepped(&mut self, s: &[f64], dt: f64) {
627        let t = &mut self.track;
628        t.since_switch += dt;
629        if t.pending_left >= 0.0 {
630            t.pending_left -= dt;
631            if t.pending_left <= 1e-12 {
632                t.spool = t.pending;
633                t.pending_left = -1.0;
634                (t.since_switch, t.arrived, t.cushioned, t.contact_time) = (0.0, 0.0, 0.0, -1.0);
635                (t.bounce, t.settling) = (0.0, 0.0);
636                if t.spool > 0.5 {
637                    t.air_cycle = s[AIR] / RHO0 * 1e3 - t.air_mark;
638                    t.air_mark = s[AIR] / RHO0 * 1e3;
639                }
640            }
641        }
642        let (x, v) = (s[X], s[V]);
643        for (k, at_end) in [x <= self.sensor_band, x >= self.stroke - self.sensor_band].into_iter().enumerate() {
644            t.sensor_time[k] = if at_end { t.sensor_time[k] + dt } else { 0.0 };
645        }
646        // Measured on the stroke under way: toward the end the spool drives to.
647        let extending = t.spool > 0.5;
648        if t.spool.abs() < 0.5 {
649            return;
650        }
651        let to_end = if extending { self.stroke - x } else { x };
652        let moved = self.mass + if self.payload_on { self.payload } else { 0.0 };
653        if t.cushioned == 0.0 && self.cushion > 0.0 && to_end <= self.cushion {
654            t.cushioned = 1.0;
655            // The kinetic energy alone, the vendor's rule for the cylinder's own cushioning (Festo DSBC data sheet: v = sqrt(2 E /
656            // (m1 + m2))); the weight's work over the cushion length belongs to the rule for external shock absorbers.
657            (t.impact_speed, t.impact_energy) = (v.abs(), 0.5 * moved * v * v);
658        }
659        if t.arrived == 0.0 && to_end <= self.sensor_band {
660            t.arrived = 1.0;
661            t.stroke_time[extending as usize] = t.since_switch;
662        }
663        if t.contact_time < 0.0 && to_end <= 0.0 {
664            t.contact_time = t.since_switch;
665            t.end_speed = v.abs();
666            if self.cushion == 0.0 {
667                (t.impact_speed, t.impact_energy) = (v.abs(), 0.5 * moved * v * v);
668            }
669        }
670        if t.contact_time >= 0.0 {
671            t.bounce = t.bounce.max(to_end);
672            if to_end > self.sensor_band {
673                t.settling = t.since_switch - t.contact_time;
674            }
675        }
676    }
677
678    fn sensors(&self) -> [bool; 2] {
679        self.track.sensor_time.map(|time| time > 0.0 && time >= self.sensor_delay - 1e-12)
680    }
681
682    fn signals(&self, s: &[f64], out: &mut Vec<f64>) {
683        let [p, t] = self.gas(s);
684        let f = self.flows(s, self.track.spool);
685        let tr = &self.track;
686        let sensors = self.sensors();
687        let air = s[AIR] / RHO0 * 1e3;
688        out.extend([
689            s[X],
690            s[V],
691            p[0],
692            p[1],
693            t[0],
694            t[1],
695            tr.spool,
696            sensors[0] as u8 as f64,
697            sensors[1] as u8 as f64,
698            f.supply / RHO0 * 6e4,
699            air,
700            tr.air_cycle,
701            s[AIR] * self.compressor_j_per_kg,
702            tr.stroke_time[1],
703            tr.stroke_time[0],
704            tr.impact_speed,
705            tr.impact_energy,
706            tr.end_speed,
707            tr.bounce,
708            tr.settling,
709            self.load_factor(),
710        ]);
711    }
712}
713
714/// A machine with pneumatic cylinders beside its axes. Its state is the machine's, then `STATES` per cylinder.
715pub struct Pneumatic {
716    inner: Box<dyn Machine>,
717    pub cylinders: Vec<Cylinder>,
718    inner_base_signals: usize,
719}
720
721/// The cylinder nodes of a machine file: id, translation key and the path of its table.
722pub struct CylinderNode {
723    pub id: String,
724    pub key: String,
725    pub values: String,
726}
727
728/// The machine with the cylinders `nodes` attached, as it is without any. `carrying`: the axes that carry the tool,
729/// where the cylinders sit, each with its direction (a unit vector) or None for a rotary axis.
730pub fn attach(
731    cfg: &Config,
732    nodes: &[CylinderNode],
733    carrying: &[(String, Option<[f64; 3]>)],
734    machine: Box<dyn Machine>,
735) -> Result<Box<dyn Machine>, ConfigError> {
736    if nodes.is_empty() {
737        return Ok(machine);
738    }
739    let h = cfg.positive("sim.dt_s")? / cfg.positive("sim.substeps")?;
740    let cylinders =
741        nodes.iter().map(|n| Cylinder::from_config(cfg, &n.id, &n.key, &n.values, h)).collect::<Result<Vec<_>, _>>()?;
742    for (c, n) in cylinders.iter().zip(nodes) {
743        if let Some(axis) = along_carrying_axis(c.incline, carrying) {
744            return Err(ConfigError::Invalid(format!(
745                "{}.incline_deg (the cylinder {} pushes on the machine's axis {axis}, which carries it; the model \
746                 lets the cylinder ride without acting back and holds only at right angles to the linear axes that \
747                 carry it and on none that turns it)",
748                n.values, n.id
749            )));
750        }
751    }
752    let pose = crate::sim::start_pose(cfg, machine.as_ref())?;
753    let (mut state, mut torque, mut signals) = (Vec::new(), vec![0.0; machine.motors().len()], Vec::new());
754    machine.equilibrium(&pose, &mut state, &mut torque);
755    machine.base_signals(&state, &torque, &mut signals);
756    Ok(Box::new(Pneumatic { inner_base_signals: signals.len(), inner: machine, cylinders }))
757}
758
759/// The id of a carrying axis that a cylinder extending at `incline` (rad, above x in the x-z plane) pushes on: a
760/// linear one whose direction has more than rounding (1e-9) of the cylinder's, or a rotary one (it would turn the
761/// cylinder, whose incline is fixed, and the push has a moment about it). None where it pushes on none.
762fn along_carrying_axis(incline: f64, carrying: &[(String, Option<[f64; 3]>)]) -> Option<&str> {
763    let (sin, cos) = incline.sin_cos();
764    carrying.iter().find(|(_, d)| d.is_none_or(|d| (cos * d[0] + sin * d[2]).abs() > 1e-9)).map(|(id, _)| id.as_str())
765}
766
767impl Pneumatic {
768    fn n(&self) -> usize {
769        self.inner.state_len()
770    }
771    fn of<'a>(&self, state: &'a [f64], k: usize) -> &'a [f64] {
772        let at = self.n() + STATES * k;
773        &state[at..at + STATES]
774    }
775}
776
777impl Machine for Pneumatic {
778    fn frame_momentum(&self, state: &[f64]) -> Option<sim_core::FrameMomentum> {
779        self.inner.frame_momentum(&state[..self.n()])
780    }
781    fn base_shift(&self, tool_pose: &[f64], pivot: [f64; 3], shift: &[f64; 6], out: &mut [f64]) {
782        self.inner.base_shift(tool_pose, pivot, shift, out)
783    }
784    fn twist(&self, torque: &[f64], acc: &[f64], out: &mut [f64]) {
785        self.inner.twist(torque, acc, out)
786    }
787    fn twist_at(&self, angle: &[f64], torque: &[f64], acc: &[f64], out: &mut [f64]) {
788        self.inner.twist_at(angle, torque, acc, out)
789    }
790    fn rigid_split_torque(&self, angle: &[f64], speed: &[f64], acc: &[f64], rotor_acc: &[f64], out: &mut [f64]) {
791        self.inner.rigid_split_torque(angle, speed, acc, rotor_acc, out)
792    }
793    fn links(&self) -> Vec<String> {
794        self.inner.links()
795    }
796    fn set_link_change(&mut self, link: usize, factor: f64, moment: [f64; 3]) {
797        self.inner.set_link_change(link, factor, moment)
798    }
799    fn cam(&self) -> Option<sim_core::CamMaster> {
800        self.inner.cam()
801    }
802    fn cam_at(&self, master: f64, out: &mut [[f64; 4]]) {
803        self.inner.cam_at(master, out)
804    }
805    fn cam_curve(&self) -> Option<sim_core::CamCurve> {
806        self.inner.cam_curve()
807    }
808    fn gantry_motors(&self) -> Option<[usize; 2]> {
809        self.inner.gantry_motors()
810    }
811    fn collision_capsules(&self, state: &[f64]) -> Vec<sim_core::Capsule> {
812        self.inner.collision_capsules(&state[..self.n()])
813    }
814    fn self_collision_capsules(&self, state: &[f64]) -> Vec<sim_core::Capsule> {
815        self.inner.self_collision_capsules(&state[..self.n()])
816    }
817    fn connected_bodies(&self, state: &[f64], boxes: usize, capsules: usize) -> Option<Vec<(usize, usize)>> {
818        self.inner.connected_bodies(&state[..self.n()], boxes, capsules)
819    }
820    fn rating_checks(&self) -> Vec<RatingCheck> {
821        let mut checks = self.inner.rating_checks();
822        for c in &self.cylinders {
823            let check = |check, signal: &str, limit| RatingCheck {
824                check,
825                signal: format!("cylinder.{}.{signal}", c.id),
826                motor: None,
827                limit,
828                life: false,
829            };
830            checks.push(check("cushion-energy", "impact_energy", c.rated_cushion_energy));
831            checks.push(check("load-factor", "load_factor", c.load_factor_limit));
832        }
833        checks
834    }
835    fn axes(&self) -> &[AxisInfo] {
836        self.inner.axes()
837    }
838    fn motors(&self) -> &[MotorInfo] {
839        self.inner.motors()
840    }
841    fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
842        self.inner.inverse(tool, motors)
843    }
844    fn forward(&self, motors: &[f64], tool: &mut [f64]) {
845        self.inner.forward(motors, tool)
846    }
847    fn state_len(&self) -> usize {
848        self.n() + STATES * self.cylinders.len()
849    }
850    fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
851        self.inner.equilibrium(tool, state, torque);
852        for c in &self.cylinders {
853            c.rest(c.track.spool, state);
854        }
855    }
856    fn derivatives(&self, state: &[f64], torque: &[f64], out: &mut [f64]) {
857        let n = self.n();
858        self.inner.derivatives(&state[..n], torque, &mut out[..n]);
859        for (k, c) in self.cylinders.iter().enumerate() {
860            let at = n + STATES * k;
861            c.derivatives(&state[at..at + STATES], &mut out[at..at + STATES]);
862        }
863    }
864    fn tool_state(&self, state: &[f64], pos: &mut [f64], vel: &mut [f64]) {
865        self.inner.tool_state(&state[..self.n()], pos, vel)
866    }
867    fn set_tool_velocity(&self, state: &mut [f64], vel: &[f64]) {
868        let n = self.n();
869        self.inner.set_tool_velocity(&mut state[..n], vel)
870    }
871    fn motor_state(&self, state: &[f64], pos: &mut [f64], vel: &mut [f64]) {
872        self.inner.motor_state(&state[..self.n()], pos, vel)
873    }
874    fn feedforward_torque(&self, tool_pos: &[f64], tool_acc: &[f64], out: &mut [f64]) {
875        self.inner.feedforward_torque(tool_pos, tool_acc, out)
876    }
877    fn feedforward_torque_moving(&self, tool_pos: &[f64], tool_vel: &[f64], tool_acc: &[f64], out: &mut [f64]) {
878        self.inner.feedforward_torque_moving(tool_pos, tool_vel, tool_acc, out)
879    }
880    fn rigid_motor_torque(&self, angle: &[f64], speed: &[f64], acc: &[f64], out: &mut [f64]) {
881        self.inner.rigid_motor_torque(angle, speed, acc, out)
882    }
883    fn rigid_tensions(&self, tool_pos: &[f64], tool_acc: &[f64], out: &mut Vec<f64>) {
884        self.inner.rigid_tensions(tool_pos, tool_acc, out)
885    }
886    fn rigid_tensions_moving(&self, tool_pos: &[f64], tool_vel: &[f64], tool_acc: &[f64], out: &mut Vec<f64>) {
887        self.inner.rigid_tensions_moving(tool_pos, tool_vel, tool_acc, out)
888    }
889    fn tension_band(&self) -> Option<[f64; 2]> {
890        self.inner.tension_band()
891    }
892    fn rigid_guide_loads(&self, tool_pos: &[f64], tool_acc: &[f64], out: &mut Vec<[f64; 2]>) {
893        self.inner.rigid_guide_loads(tool_pos, tool_acc, out)
894    }
895    fn rigid_friction(&self, tool_pos: &[f64], tool_dir: &[f64], out: &mut Vec<[f64; 2]>) {
896        self.inner.rigid_friction(tool_pos, tool_dir, out)
897    }
898    fn rigid_friction_rise(&self, tool_pos: &[f64], tool_dir: &[f64], out: &mut Vec<Vec<[f64; 2]>>) {
899        self.inner.rigid_friction_rise(tool_pos, tool_dir, out)
900    }
901    /// The machine's alone: a cylinder is an open system, fed by the supply, and keeps its own balance (the signals
902    /// `cylinder.<id>.*` and `Cylinder::mechanical_energy`, `gas_energy`).
903    fn energy(&self, state: &[f64]) -> f64 {
904        self.inner.energy(&state[..self.n()])
905    }
906    fn set_payload_attached(&mut self, attached: bool) {
907        self.inner.set_payload_attached(attached);
908        self.cylinders.iter_mut().for_each(|c| c.payload_on = attached);
909    }
910    fn set_dwelling(&mut self, dwelling: bool) {
911        self.inner.set_dwelling(dwelling)
912    }
913    fn set_brake_engaged(&mut self, engaged: bool) {
914        self.inner.set_brake_engaged(engaged)
915    }
916    /// The machine's own, and a cylinder meeting its stop within the step (`HardStop::substeps`).
917    fn substeps_wanted(&self, state: &[f64], torque: &[f64], dt: f64, substeps: u32) -> u32 {
918        let n = self.n();
919        let cylinders = self.cylinders.iter().enumerate().map(|(k, c)| {
920            let at = n + STATES * k;
921            c.stops.substeps(state[at + X], state[at + V], c.stroke, dt)
922        });
923        cylinders.fold(self.inner.substeps_wanted(&state[..n], torque, dt, substeps), u32::max)
924    }
925    fn valves(&self) -> Vec<(String, f64)> {
926        self.cylinders.iter().map(|c| (c.id.clone(), c.track.command)).collect()
927    }
928    fn set_valve(&mut self, valve: usize, command: f64) {
929        if let Some(c) = self.cylinders.get_mut(valve) {
930            c.command(command);
931        }
932    }
933    fn end_sensors(&self, valve: usize) -> [bool; 2] {
934        self.cylinders.get(valve).map_or([false; 2], Cylinder::sensors)
935    }
936    fn after_step(&mut self, state: &mut [f64], dt: f64) {
937        let n = self.n();
938        self.inner.after_step(&mut state[..n], dt);
939        for (k, c) in self.cylinders.iter_mut().enumerate() {
940            let at = n + STATES * k;
941            c.stepped(&state[at..at + STATES], dt);
942        }
943    }
944    fn memory(&self) -> Vec<f64> {
945        let mut m = self.inner.memory();
946        self.cylinders.iter().for_each(|c| m.extend(c.track.to_vec()));
947        m
948    }
949    fn set_memory(&mut self, memory: &[f64]) {
950        let own = TRACK * self.cylinders.len();
951        let (inner, own) = memory.split_at(memory.len() - own);
952        self.inner.set_memory(inner);
953        for (c, m) in self.cylinders.iter_mut().zip(own.chunks(TRACK)) {
954            c.track = Track::from_slice(m);
955        }
956    }
957    fn set_part_temperatures(&mut self, rises: &[f64]) {
958        self.inner.set_part_temperatures(rises)
959    }
960    fn resonance_hz(&self, tool_pose: &[f64]) -> Option<f64> {
961        self.inner.resonance_hz(tool_pose)
962    }
963    fn mode_shape(&self, tool_pose: &[f64]) -> Option<(f64, Vec<f64>)> {
964        let len = self.state_len();
965        self.inner.mode_shape(tool_pose).map(|(hz, mut shape)| {
966            shape.resize(len, 0.0);
967            (hz, shape)
968        })
969    }
970    fn modes(&self, tool_pose: &[f64]) -> Vec<sim_core::Mode> {
971        self.inner.modes(tool_pose)
972    }
973    fn sway_modes(&self, tool_pose: &[f64]) -> Vec<sim_core::Mode> {
974        self.inner.sway_modes(tool_pose)
975    }
976    fn trains(&self, tool_pose: &[f64]) -> Vec<Option<sim_core::Train>> {
977        self.inner.trains(tool_pose)
978    }
979    fn belt_wraps(&self, tool_pose: &[f64]) -> Vec<f64> {
980        self.inner.belt_wraps(tool_pose)
981    }
982    fn unreachable(&self, tool_pose: &[f64], slack: f64) -> Option<&'static str> {
983        self.inner.unreachable(tool_pose, slack)
984    }
985    fn refuses_pick(&self, tool_pose: &[f64]) -> Option<&'static str> {
986        self.inner.refuses_pick(tool_pose)
987    }
988    fn condition(&self, tool_pose: &[f64]) -> Option<f64> {
989        self.inner.condition(tool_pose)
990    }
991    fn setpoint_slack(&self) -> f64 {
992        self.inner.setpoint_slack()
993    }
994    fn signal_infos(&self) -> Vec<SignalInfo> {
995        let mut infos = self.inner.signal_infos();
996        let own = self.cylinders.iter().flat_map(|c| {
997            SIGNALS.iter().map(move |(name, unit)| {
998                SignalInfo::new(
999                    format!("cylinder.{}.{name}", c.id),
1000                    &c.key,
1001                    &format!("quantity-cylinder-{}", name.replace('_', "-")),
1002                    unit,
1003                )
1004            })
1005        });
1006        infos.splice(self.inner_base_signals..self.inner_base_signals, own.collect::<Vec<_>>());
1007        infos
1008    }
1009    fn base_signals(&self, state: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1010        self.inner.base_signals(&state[..self.n()], torque, out);
1011        for (k, c) in self.cylinders.iter().enumerate() {
1012            c.signals(self.of(state, k), out);
1013        }
1014    }
1015    fn effect_signals(&self, state: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1016        self.inner.effect_signals(&state[..self.n()], torque, out)
1017    }
1018    fn loss_powers(&self, state: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1019        self.inner.loss_powers(&state[..self.n()], torque, out)
1020    }
1021    /// The machine's scene, and each cylinder at the tool: its body and its rod along its stroke (along x tilted by its
1022    /// incline, in the x-z plane), the rod out by the piston's position.
1023    fn scene(&self, state: &[f64], out: &mut Scene) {
1024        let n = self.n();
1025        self.inner.scene(&state[..n], out);
1026        let axes = self.inner.axes().len();
1027        let (mut pose, mut vel) = (vec![0.0; axes], vec![0.0; axes]);
1028        self.inner.tool_state(&state[..n], &mut pose, &mut vel);
1029        let Some(tool) = self.inner.scene_point(&pose) else { return };
1030        for (k, c) in self.cylinders.iter().enumerate() {
1031            let (dir, x) = ([c.incline.cos(), 0.0, c.incline.sin()], self.of(state, k)[X]);
1032            let at = |along: f64| std::array::from_fn(|i| tool[i] + along * dir[i]);
1033            let size = |length: f64, thick: f64| {
1034                let s: [f64; 3] = std::array::from_fn(|i| (length * dir[i]).abs().max(thick));
1035                sim_core::scene::Shape::Box { size: s }
1036            };
1037            let width = 2.0 * (c.a1 / std::f64::consts::PI).sqrt() + 0.02;
1038            out.parts.push(sim_core::scene::Part::new(
1039                "cylinder-body",
1040                size(c.stroke + 0.05, width),
1041                at(-0.5 * (c.stroke + 0.05)),
1042                [0.6, 0.65, 0.7],
1043            ));
1044            out.parts.push(sim_core::scene::Part::new(
1045                "cylinder-rod",
1046                size(x.max(0.0) + 0.01, 0.4 * width),
1047                at(0.5 * x.max(0.0)),
1048                [0.85, 0.85, 0.85],
1049            ));
1050        }
1051    }
1052    fn scene_point(&self, tool_pose: &[f64]) -> Option<[f64; 3]> {
1053        self.inner.scene_point(tool_pose)
1054    }
1055    fn collision_bodies(&self, state: &[f64]) -> Vec<sim_core::Aabb> {
1056        self.inner.collision_bodies(&state[..self.n()])
1057    }
1058    fn friction_contacts(&self) -> Vec<FrictionContact> {
1059        self.inner.friction_contacts()
1060    }
1061    fn friction_curve(&self, i: usize, speed: f64, load_scale: f64) -> [f64; 3] {
1062        self.inner.friction_curve(i, speed, load_scale)
1063    }
1064    fn friction_rotary(&self, i: usize) -> bool {
1065        self.inner.friction_rotary(i)
1066    }
1067    fn friction_speed_limit(&self, i: usize, motor_speed: &[f64]) -> Option<f64> {
1068        self.inner.friction_speed_limit(i, motor_speed)
1069    }
1070    fn belt_sections(&self) -> Vec<BeltSection> {
1071        self.inner.belt_sections()
1072    }
1073    fn thermal_parts(&self) -> Vec<ThermalPart> {
1074        self.inner.thermal_parts()
1075    }
1076}
1077
1078#[cfg(test)]
1079mod tests {
1080    use super::*;
1081    use sim_core::Rk4;
1082
1083    /// A cylinder hanging down (-90 degrees) from a carriage on a horizontal x pushes at right angles to it (cos =
1084    /// 6e-17), and to a horizontal y: carried. At 0 degrees it pushes along x, at 45 degrees partly along it; -90 pushes
1085    /// along a vertical z, and along an x inclined by 30 degrees (sin 30 of it); any rotary axis is refused.
1086    #[test]
1087    fn a_cylinder_along_a_carrying_axis_is_found() {
1088        let axis = |id: &str, d: Option<[f64; 3]>| (id.to_string(), d);
1089        let (x, y, z) =
1090            (axis("x", Some([1.0, 0.0, 0.0])), axis("y", Some([0.0, 1.0, 0.0])), axis("z", Some([0.0, 0.0, 1.0])));
1091        let down = -std::f64::consts::FRAC_PI_2;
1092        assert_eq!(along_carrying_axis(down, &[x.clone(), y.clone()]), None);
1093        assert_eq!(along_carrying_axis(0.0, &[y.clone(), x.clone()]), Some("x"));
1094        assert_eq!(along_carrying_axis(0.25 * std::f64::consts::PI, std::slice::from_ref(&x)), Some("x"));
1095        assert_eq!(along_carrying_axis(down, &[x, y.clone(), z]), Some("z"));
1096        let tilted = axis("x", Some([30f64.to_radians().cos(), 0.0, 30f64.to_radians().sin()]));
1097        assert_eq!(along_carrying_axis(down, &[tilted]), Some("x"));
1098        assert_eq!(along_carrying_axis(down, &[y, axis("c", None)]), Some("c"));
1099    }
1100
1101    /// A DSBC-32-like cylinder from `TABLE` (32 mm bore, 12 mm rod: A1 = 8.0425e-4 m2, A2 = 6.9115e-4 m2, 100 mm
1102    /// stroke, 0.5 kg, dead volumes 5 cm3, 6 bar gauge), horizontal, without friction and cushions unless `changes` say.
1103    fn cylinder(changes: &[&str], h: f64) -> Cylinder {
1104        Cylinder::from_config(&config(false, changes), "z", "cylinder", "c", h).unwrap()
1105    }
1106
1107    /// The config of `cylinder`, with seal friction and cushions on or off.
1108    fn config(on: bool, changes: &[&str]) -> Config {
1109        let mut cfg = Config::parse(&format!(
1110            "format_version = 1\n[effects]\ngravity = true\npayload = true\ncylinder_friction = {on}\ncylinder_cushion = {on}\n[c]\n{TABLE}"
1111        ))
1112        .unwrap();
1113        for change in changes {
1114            cfg.set_text(change).unwrap();
1115        }
1116        cfg
1117    }
1118
1119    /// Integrates the cylinder alone with the spool at `spool` for `seconds` in steps of `h`, calling `each` after every
1120    /// step with the time and the state.
1121    fn run(c: &Cylinder, s: &mut [f64], spool: f64, h: f64, seconds: f64, mut each: impl FnMut(f64, &[f64])) {
1122        let mut rk = Rk4::new(STATES);
1123        for k in 0..(seconds / h).round() as usize {
1124            rk.step(|y, dy| c.derivatives_with(y, spool, dy), s, h);
1125            each((k + 1) as f64 * h, s);
1126        }
1127    }
1128
1129    fn rest(c: &Cylinder, spool: f64) -> Vec<f64> {
1130        let mut s = Vec::new();
1131        c.rest(spool, &mut s);
1132        s
1133    }
1134
1135    fn near(a: f64, b: f64, tol: f64, what: &str) {
1136        assert!((a - b).abs() <= tol * b.abs(), "{what}: {a} against {b} (tolerance {tol})");
1137    }
1138
1139    /// The theoretical force p A at 6 bar gauge: extending 6e5 Pa * pi 0.016^2 = 482.5 N, retracting 6e5 Pa *
1140    /// (8.0425e-4 - 1.1310e-4) m2 = 414.7 N; Festo prints 483 N and 415 N for the DSBC-32 (catalog/festo/cylinders_dsbc.csv).
1141    #[test]
1142    fn the_theoretical_force_is_p_a_on_both_sides() {
1143        let c = cylinder(&[], 1e-5);
1144        let (ps, pa) = (c.supply, c.ambient);
1145        near(c.pressure_force([ps, pa]), 482.549, 1e-5, "extending");
1146        near(-c.pressure_force([pa, ps]), 414.690, 1e-5, "retracting");
1147        near(c.a1, 8.04248e-4, 1e-5, "A1");
1148        near(c.a2, 6.91150e-4, 1e-5, "A2");
1149    }
1150
1151    /// ISO 6358 by hand: C = 1 dm3/(s bar) = 1e-8 m3/(s Pa) from 7.01325 bar into the atmosphere (ratio 0.144 < b = 0.3,
1152    /// choked): 1e-8 * 7.01325e5 * 1.185 = 8.3107e-3 kg/s at 293.15 K; at a ratio of 0.65, psi = sqrt(1 - (0.35 /
1153    /// 0.7)^2) = 0.86603 of it; at 0.9975 (the straight end) psi(0.995) / 2.
1154    #[test]
1155    fn the_flow_through_a_conductance_is_choked_below_b_and_elliptic_above() {
1156        let f = Flow::new(1.0, 0.3);
1157        near(f.mass_flow(7.01325e5, T0, 1.01325e5), 8.31070e-3, 1e-5, "choked");
1158        near(f.mass_flow(1e6, T0, 6.5e5) / f.mass_flow(1e6, T0, 1e5), 0.866025, 1e-6, "subsonic");
1159        near(psi(0.9975, 0.3), 0.5 * psi(0.995, 0.3), 1e-12, "straight end");
1160        assert_eq!(f.mass_flow(1e5, T0, 2e5), 0.0);
1161        // Series: two equal elements C = (2 C^-3)^(-1/3) = 0.7937 C, b = 1 - 0.63 * (0.7 + 0.7) = 0.1181.
1162        let s = Flow::series(&[f, f]);
1163        near(s.c / f.c, 0.793701, 1e-6, "series C");
1164        near(s.b, 1.0 - 0.793701f64.powi(2) * 1.4, 1e-5, "series b");
1165    }
1166
1167    /// The meter-out throttled steady speed by hand: with the rod side's throttle choked, the mass that leaves it,
1168    /// C p2 rho0 sqrt(T0 / T2), is the mass the shrinking chamber pushes out, p2 A2 v / (R T2), so
1169    /// v = C rho0 R sqrt(T0 T2) / A2, whatever p2: at T2 = T0, 1e-9 * 1.185 * 287.058 * 293.15 / 6.9115e-4 = 0.14428
1170    /// m/s for C = 0.1 dm3/(s bar). Here the throttle is in series with a valve and a tube of 5 (C 0.1 times
1171    /// (1 + 2 0.1^3 / 5^3)^(-1/3), 5e-6 less) and works against 50 N: p2 = (p1 A1 - p_atm (A1 - A2) - 50) / A2 = 7.27 bar, the
1172    /// ratio 0.14 to the atmosphere, choked. The heat transfer (20 W/K) holds the rod side near T0. Measured over the
1173    /// middle of a 300 mm stroke, within 1 %.
1174    #[test]
1175    fn a_meter_out_throttled_cylinder_runs_at_the_choked_flow_s_speed() {
1176        let h = 1e-5;
1177        let c = cylinder(
1178            &[
1179                "c.stroke_m = 0.3",
1180                "c.valve_c_dm3_s_bar = 5.0",
1181                "c.tube_c_dm3_s_bar = 5.0",
1182                "c.throttle_extend_c_dm3_s_bar = 0.1",
1183                "c.load_force_n = 50.0",
1184                "c.heat_transfer_w_k = 20.0",
1185            ],
1186            h,
1187        );
1188        let mut s = rest(&c, -1.0);
1189        let (mut at, mut speeds) = (Vec::new(), Vec::new());
1190        run(&c, &mut s, 1.0, h, 3.0, |_, s| {
1191            if (0.1..0.2).contains(&s[X]) {
1192                at.push(s[X]);
1193                speeds.push(s[V]);
1194            }
1195        });
1196        assert!(!speeds.is_empty(), "the piston never got to the middle");
1197        let mean = speeds.iter().sum::<f64>() / speeds.len() as f64;
1198        let expected = c.outflow[1].c * RHO0 * R * T0 / c.a2;
1199        near(expected, 0.144279, 1e-4, "hand speed");
1200        near(mean, expected, 0.01, "steady speed");
1201    }
1202
1203    /// The piston on its two air springs, both chambers closed (a 5/3 valve's centre) at mid-stroke: the stiffness
1204    /// n (p1 A1^2 / V1 + p2 A2^2 / V2), with p2 = 5 bar and p1 = (p2 A2 + p_atm (A1 - A2)) / A1 = 4.4394 bar balancing it,
1205    /// V1 = 5e-6 + A1 0.05 = 4.5212e-5 m3, V2 = 3.9558e-5 m3: 12389 N/m times n. Adiabatic (no heat transfer) n = 1.4,
1206    /// sqrt(1.4 * 12389 / 0.5) / 2 pi = 29.64 Hz; with a heat transfer quick against the period (500 W/K: a time
1207    /// constant of 0.34 ms) isothermal, n = 1, 25.05 Hz. Measured from the zero crossings of the speed over 1 s.
1208    #[test]
1209    fn the_air_springs_ring_at_the_hand_frequency_adiabatic_and_isothermal() {
1210        let h = 1e-5;
1211        for (heat, n, hz) in [(0.0, KAPPA, 29.64), (500.0, 1.0, 25.05)] {
1212            let c = cylinder(&["c.valve = \"5/3\"", &format!("c.heat_transfer_w_k = {heat}")], h);
1213            let x = 0.5 * c.stroke;
1214            let v = c.volumes(x);
1215            let p2 = 5e5;
1216            let p1 = (p2 * c.a2 + c.ambient * (c.a1 - c.a2)) / c.a1;
1217            let stiffness = n * (p1 * c.a1 * c.a1 / v[0] + p2 * c.a2 * c.a2 / v[1]);
1218            let expected = (stiffness / c.mass).sqrt() / std::f64::consts::TAU;
1219            near(expected, hz, 2e-3, "hand frequency");
1220            let mut s = vec![0.0; STATES];
1221            (s[X], s[V]) = (x, 1e-3);
1222            (s[M1], s[U1]) = (p1 * v[0] / (R * T0), p1 * v[0] / (KAPPA - 1.0));
1223            (s[M2], s[U2]) = (p2 * v[1] / (R * T0), p2 * v[1] / (KAPPA - 1.0));
1224            let (mut crossings, mut last, mut before) = (Vec::new(), s[V], 0.0);
1225            run(&c, &mut s, 0.0, h, 1.0, |t, s| {
1226                if last > 0.0 && s[V] <= 0.0 {
1227                    crossings.push(before + h * last / (last - s[V]));
1228                }
1229                (last, before) = (s[V], t);
1230            });
1231            let measured = (crossings.len() - 1) as f64 / (crossings[crossings.len() - 1] - crossings[0]);
1232            near(measured, expected, 0.02, &format!("frequency with {heat} W/K"));
1233        }
1234    }
1235
1236    /// Air for a double stroke by hand: each chamber goes from the atmosphere at its dead volume to the supply at its
1237    /// full volume, m = (p_s (V0 + A s) - p_atm V0) / (R T): cap side (7.01325e5 * 8.5425e-5 - 1.01325e5 * 5e-6) /
1238    /// (287.058 * 293.15) = 7.0591e-4 kg, rod side (7.01325e5 * 7.4115e-5 - 0.5066) / 84152 = 6.1166e-4 kg; 1.31757e-3 kg,
1239    /// 1.1119 l (ANR, 1.185 kg/m3). The air settles back to the wall's temperature in the dwells; stiff stops keep
1240    /// their give out of the volumes.
1241    #[test]
1242    fn a_double_stroke_draws_the_hand_air_consumption() {
1243        let h = 1e-5;
1244        let c = cylinder(
1245            &["c.heat_transfer_w_k = 2.0", "c.stop_stiffness_n_m = 1.0e8", "c.stop_damping_n_s_m = 2000.0"],
1246            h,
1247        );
1248        let mut s = rest(&c, -1.0);
1249        run(&c, &mut s, 1.0, h, 2.0, |_, _| {});
1250        assert!(s[X] > c.stroke - 1e-4, "not extended: {}", s[X]);
1251        run(&c, &mut s, -1.0, h, 2.0, |_, _| {});
1252        assert!(s[X] < 1e-4, "not retracted: {}", s[X]);
1253        let full = |a: f64, dead: f64| (c.supply * (dead + a * c.stroke) - c.ambient * dead) / (R * T0);
1254        let expected = full(c.a1, c.dead[0]) + full(c.a2, c.dead[1]);
1255        near(expected, 1.31757e-3, 1e-4, "hand mass");
1256        near(s[AIR], expected, 0.005, "air drawn");
1257        near(s[AIR] / RHO0 * 1e3, 1.1119, 0.006, "normal litres");
1258    }
1259
1260    /// A closed volume filled through a conductance, adiabatic: while choked (p <= b p_s) the flow is the constant
1261    /// C p_s rho0 and dp/dt = kappa R T_s mdot / V, so it takes t = (b p_s - p_atm) V / (kappa R T_s mdot). The piston
1262    /// is held in its stop by a load of 1e5 N, far beyond the force: the stop (1e8 N/m) gives 1 mm under it, so the cap
1263    /// side's volume is the dead volume, 50 cm3, less A1 * 1 mm: 4.920e-5 m3 (the pressure moves it by 0.01 % more).
1264    /// The path is valve and tube (C 1 and 2, b 0.3 and 0.4: C = 0.9615 dm3/(s bar), b = 1 - 0.9245 (0.7 + 0.6 / 4) =
1265    /// 0.2142): (0.2142 * 7.01325e5 - 1.01325e5) * 4.920e-5 / (1.4 * 287.058 * 293.15 * 7.9906e-3 kg/s) = 2.555 ms.
1266    #[test]
1267    fn filling_a_closed_volume_takes_the_closed_form_time_while_choked() {
1268        let h = 2e-6;
1269        let c = cylinder(
1270            &[
1271                "c.dead_volume_cap_m3 = 5.0e-5",
1272                "c.load_force_n = 1.0e5",
1273                "c.stop_stiffness_n_m = 1.0e8",
1274                "c.heat_transfer_w_k = 0.0",
1275            ],
1276            h,
1277        );
1278        let mut s = rest(&c, -1.0);
1279        let volume = c.volumes(s[X])[0];
1280        let mdot = c.inflow.mass_flow(c.supply, T0, c.ambient);
1281        let expected = (c.inflow.b * c.supply - c.ambient) * volume / (KAPPA * R * T0 * mdot);
1282        near(expected, 2.555e-3, 2e-3, "hand time");
1283        let (mut found, mut before) = (None, (0.0, c.gas(&s)[0][0]));
1284        run(&c, &mut s, 1.0, h, 0.01, |t, s| {
1285            let p = c.gas(s)[0][0];
1286            let target = c.inflow.b * c.supply;
1287            if found.is_none() && p >= target {
1288                found = Some(before.0 + h * (target - before.1) / (p - before.1));
1289            }
1290            before = (t, p);
1291        });
1292        near(found.unwrap(), expected, 0.005, "time to b p_s");
1293    }
1294
1295    /// Energy conservation with the chambers closed (a 5/3 valve's centre), adiabatic and without friction: the gas's
1296    /// internal energy and the mechanical energy (kinetic, gravity, the atmosphere's work on the rod, the stops)
1297    /// together stay within 1e-9 of the gas's energy over 1 s of the piston bouncing on its air springs, vertical. The
1298    /// stops' dampers are off: they take energy whenever the piston touches a stop.
1299    #[test]
1300    fn a_closed_cylinder_keeps_its_energy() {
1301        let h = 1e-5;
1302        let changes =
1303            ["c.valve = \"5/3\"", "c.heat_transfer_w_k = 0.0", "c.incline_deg = 90.0", "c.stop_damping_n_s_m = 0.0"];
1304        let c = cylinder(&changes, h);
1305        // Mid-stroke at 3 and 4 bar, at 0.5 m/s: it swings on its air springs, into the stops and out.
1306        let mut s = vec![0.0; STATES];
1307        let v = c.volumes(0.5 * c.stroke);
1308        (s[X], s[V]) = (0.5 * c.stroke, 0.5);
1309        (s[M1], s[U1]) = (3e5 * v[0] / (R * T0), 3e5 * v[0] / (KAPPA - 1.0));
1310        (s[M2], s[U2]) = (4e5 * v[1] / (R * T0), 4e5 * v[1] / (KAPPA - 1.0));
1311        let total = |s: &[f64]| c.mechanical_energy(s) + c.gas_energy(s);
1312        let start = total(&s);
1313        let (mut worst, mut lowest) = (0f64, c.stroke);
1314        run(&c, &mut s, 0.0, h, 1.0, |_, s| {
1315            worst = worst.max((total(s) - start).abs());
1316            lowest = lowest.min(s[X]);
1317        });
1318        assert!(worst < 1e-9 * c.gas_energy(&s), "drifted by {worst} J");
1319        assert!(lowest < c.stroke - 1e-3, "the piston never left the stop");
1320    }
1321
1322    /// The open system's balance in place of energy conservation (the suite's check is for a closed one): over an extend
1323    /// and a retract stroke with friction, cushions and heat transfer, the change of the gas's and the mechanical
1324    /// energy equals the enthalpy from the supply less that to the exhaust, plus the heat from the wall, less what the
1325    /// seals and the stops' dampers took, within 1e-6 of the enthalpy drawn.
1326    #[test]
1327    fn the_enthalpy_flows_balance_the_energy_of_an_open_cylinder() {
1328        let h = 1e-5;
1329        let cfg = config(true, &["c.incline_deg = -90.0", "c.load_force_n = 30.0", "c.heat_transfer_w_k = 0.3"]);
1330        let c = Cylinder::from_config(&cfg, "z", "cylinder", "c", h).unwrap();
1331        assert!(c.seal.is_some() && c.cushion > 0.0);
1332        let mut s = rest(&c, -1.0);
1333        let stored = |s: &[f64]| c.mechanical_energy(s) + c.gas_energy(s);
1334        let start = stored(&s);
1335        for spool in [1.0, -1.0] {
1336            run(&c, &mut s, spool, h, 1.5, |_, _| {});
1337        }
1338        let flows = s[H_IN] - s[H_OUT] + s[HEAT] - s[LOSS];
1339        let off = stored(&s) - start - flows;
1340        assert!(s[LOSS] > 0.0 && s[H_IN] > 0.0);
1341        assert!(off.abs() < 1e-6 * s[H_IN], "off by {off} J of {} J drawn", s[H_IN]);
1342    }
1343
1344    /// Halving the step changes the stroke time by less than 1 % (and much less): a full extend stroke with cushions and
1345    /// friction at the simulation's sub-step (62.5 us / 4) and at half of it.
1346    #[test]
1347    fn the_stroke_time_converges_with_the_step() {
1348        let time = |h: f64| {
1349            let c = Cylinder::from_config(&config(true, &["c.incline_deg = -90.0"]), "z", "cylinder", "c", h).unwrap();
1350            let mut s = rest(&c, -1.0);
1351            let mut arrived = None;
1352            run(&c, &mut s, 1.0, h, 2.0, |t, s| {
1353                if arrived.is_none() && s[X] >= c.stroke - c.sensor_band {
1354                    arrived = Some(t);
1355                }
1356            });
1357            arrived.expect("never arrived")
1358        };
1359        let (coarse, fine) = (time(62.5e-6 / 4.0), time(62.5e-6 / 8.0));
1360        assert!((coarse - fine).abs() < 0.01 * fine, "{coarse} s against {fine} s");
1361    }
1362
1363    /// A dead volume so small that the flow law's straight end is stiffer than the step can integrate is refused by
1364    /// name, not run into NaN: 1e-9 m3 with the default flows needs a sub-step below about 0.1 us.
1365    #[test]
1366    fn a_cylinder_too_stiff_for_the_step_is_refused() {
1367        let cfg = config(true, &["c.dead_volume_rod_m3 = 1.0e-9"]);
1368        let error = Cylinder::from_config(&cfg, "z", "cylinder", "c", 62.5e-6 / 4.0).unwrap_err();
1369        assert_eq!(error.key(), "error-cylinder-unstable");
1370        assert!(error.detail().contains("flow"), "{}", error.detail());
1371    }
1372
1373    /// The energy judged against the cushion's rating at 0.2 m/s into the 17 mm cushion with m = moved mass is the
1374    /// kinetic m v^2 / 2 alone (the vendor's rule), whichever way the weight acts: hanging 1 kg gives 0.02 J (m g L =
1375    /// 0.1667 J of weight work is not added), extending upwards and retracting down likewise.
1376    #[test]
1377    fn the_cushion_energy_is_the_kinetic_energy_whichever_way_the_weight_acts() {
1378        let entering = |incline: &str, spool: f64, x: f64| {
1379            let mut c = cylinder(&[incline], 1e-5);
1380            c.cushion = 0.017;
1381            c.track.spool = spool;
1382            c.track.cushioned = 0.0;
1383            let mut s = rest(&c, spool);
1384            (s[X], s[V]) = (x, 0.2 * spool);
1385            c.stepped(&s, 1e-5);
1386            (c.track.impact_energy, c.mass + c.payload)
1387        };
1388        let (down, m) = entering("c.incline_deg = -90.0", 1.0, 0.1 - 0.0169);
1389        near(down, 0.5 * m * 0.04, 1e-9, "extending down");
1390        let (up, m) = entering("c.incline_deg = 90.0", 1.0, 0.1 - 0.0169);
1391        near(up, 0.5 * m * 0.04, 1e-9, "extending up");
1392        let (retract, m) = entering("c.incline_deg = 90.0", -1.0, 0.0169);
1393        near(retract, 0.5 * m * 0.04, 1e-9, "retracting down");
1394    }
1395}