Skip to main content

sim_components/
parameters.rs

1//! The drive parameters of a tuned machine: for each motor, the numbers of the config's drive settings as the drive takes
2//! them, with the parameter's number, name and unit (SINAMICS S120 servo and S210). The mapping is data, the tables
3//! `catalog/siemens/parameters_s120.csv` and `parameters_s210.csv`, each row with the page of the Siemens document it comes
4//! from; this module reads the config as resolved (the parts applied, each motor's own `[drive.<id>]` over the shared one)
5//! and converts. A setting the table has no parameter for is listed as such, never with a guessed number.
6//!
7//! Rotary servo motors only: a linear motor's gains have other units (N s/m), a stepper or an induction motor has no
8//! such cascade.
9
10use crate::catalog::{motor_config, resolve, rows, table};
11use sim_core::{Config, ConfigError, MachineEntry};
12
13/// The drive families a parameter list exists for.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Family {
16    /// SINAMICS S120 servo on a Motor Module (List Manual LH1, 07/2018).
17    S120,
18    /// SINAMICS S210 (6SL3210 converters; Operating Instructions 09/2022).
19    S210,
20}
21
22impl Family {
23    /// `s120` or `s210`, as `--family` says it.
24    pub fn parse(text: &str) -> Option<Self> {
25        match text {
26            "s120" => Some(Self::S120),
27            "s210" => Some(Self::S210),
28            _ => None,
29        }
30    }
31
32    pub fn name(self) -> &'static str {
33        match self {
34            Self::S120 => "s120",
35            Self::S210 => "s210",
36        }
37    }
38
39    fn mapping(self) -> &'static str {
40        table(match self {
41            Self::S120 => "siemens/parameters_s120.csv",
42            Self::S210 => "siemens/parameters_s210.csv",
43        })
44    }
45
46    /// The family a drive's article number belongs to: an S210 converter of `converters_s210.csv` (not the "S210 (New)"
47    /// 6SL5310, which the Operating Instructions do not cover) or an S120 Motor Module of `motor_modules_s120.csv`.
48    pub fn of_article(article: &str) -> Option<Self> {
49        let article_in = |file: &'static str| rows(table(file)).into_iter().find(|r| r["part_number"] == article);
50        if article_in("siemens/converters_s210.csv").is_some_and(|r| r["series"] == "S210") {
51            Some(Self::S210)
52        } else if article_in("siemens/motor_modules_s120.csv").is_some() {
53            Some(Self::S120)
54        } else {
55            None
56        }
57    }
58}
59
60/// How a row's parameter relates to what the manual prints.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum Basis {
63    /// The parameter's quantity and unit as the manual prints them.
64    Printed,
65    /// A relation worked out from what the manual prints (the Kv unit, the notch damping, a reference speed).
66    Derived,
67    /// No parameter: the table has none for this setting.
68    None,
69}
70
71impl Basis {
72    pub fn name(self) -> &'static str {
73        match self {
74            Self::Printed => "printed",
75            Self::Derived => "derived",
76            Self::None => "none",
77        }
78    }
79}
80
81/// One line of the list.
82#[derive(Debug, Clone, PartialEq)]
83pub struct Row {
84    pub motor: String,
85    /// The config key without its table (`velocity_kp_nm_s_rad`), and its value and unit.
86    pub key: &'static str,
87    pub value: f64,
88    pub unit: &'static str,
89    /// The parameter ("p1460"), its name as the manual prints it and its unit; empty with `Basis::None`.
90    pub parameter: String,
91    pub name: String,
92    pub parameter_value: Option<f64>,
93    pub parameter_unit: String,
94    pub basis: Basis,
95}
96
97/// Why a list could not be made.
98#[derive(Debug, Clone, PartialEq)]
99pub enum Error {
100    Config(ConfigError),
101    /// The motor has no drive part and no family was named.
102    NoDrive(String),
103    /// The motor's drive part is none of the two families (its article).
104    UnknownDrive(String),
105    /// The motor is not a rotary servo motor (its id).
106    NotRotaryServo(String),
107}
108
109impl From<ConfigError> for Error {
110    fn from(e: ConfigError) -> Self {
111        Self::Config(e)
112    }
113}
114
115/// The drive settings, with the config's unit and the effect switch the simulator needs on for the value to act (""
116/// always). A setting of a motor whose effect is off is left out: the drive would not have used the number the
117/// simulation tuned. The order is the list's.
118pub const SETTINGS: &[(&str, &str, &str)] = &[
119    ("kv_1_s", "1/s", ""),
120    ("velocity_kp_nm_s_rad", "N m s/rad", ""),
121    ("velocity_tn_s", "s", ""),
122    ("velocity_feedforward_factor", "factor", "velocity_feedforward"),
123    ("torque_feedforward_factor", "factor", "torque_feedforward"),
124    ("precontrol_balance_s", "s", ""),
125    ("current_kp_v_a", "V/A", ""),
126    ("current_tn_s", "s", ""),
127    ("peak_torque_nm", "N m", ""),
128    ("max_speed_rad_s", "rad/s", ""),
129    ("velocity_filter_s", "s", "velocity_filter"),
130    ("torque_filter_s", "s", "torque_filter"),
131    ("notch_frequency_hz", "Hz", "notch_filter"),
132    ("notch_bandwidth_hz", "Hz", "notch_filter"),
133    ("off1_ramp_s", "s", "drive_monitoring"),
134    ("off3_ramp_s", "s", "drive_monitoring"),
135    ("pulse_off_speed_rad_s", "rad/s", "drive_monitoring"),
136    ("following_error_window_rad", "rad", "drive_monitoring"),
137    ("standstill_window_rad", "rad", "drive_monitoring"),
138    ("standstill_time_s", "s", "drive_monitoring"),
139    ("blocked_speed_rad_s", "rad/s", "drive_monitoring"),
140    ("blocked_time_s", "s", "drive_monitoring"),
141    ("ss1_time_s", "s", "drive_monitoring"),
142];
143
144/// The drive part a motor has: its own `[parts.<id>] drive` over the shared `[parts] drive`, "" for none.
145fn drive_article<'a>(cfg: &'a Config, id: &str) -> &'a str {
146    let text = |path: String| cfg.get(&path).ok().and_then(|v| v.as_str());
147    text(format!("parts.{id}.drive")).or_else(|| text("parts.drive".into())).unwrap_or("")
148}
149
150/// The parameter list of every motor of the machine, from `cfg` as the config file states it (the drive part is read
151/// before the parts are applied). `family` names the drive family where the config has no drive part (or to override it).
152pub fn list(entry: &MachineEntry, cfg: &Config, family: Option<Family>) -> Result<Vec<Row>, Error> {
153    list_resolved(entry, cfg, &resolve(entry, cfg)?, family)
154}
155
156/// `list` with the resolved config given: a front end that sets values on top of the resolved parts (`--set`, which
157/// overrides the retuned gain) passes its own. `cfg` is still the config as the file states it, for the drive part.
158pub fn list_resolved(
159    entry: &MachineEntry,
160    cfg: &Config,
161    resolved: &Config,
162    family: Option<Family>,
163) -> Result<Vec<Row>, Error> {
164    let machine = (entry.build)(resolved)?;
165    let mut out = Vec::new();
166    for (index, motor) in machine.motors().iter().enumerate() {
167        let own = motor_config(resolved, motor.id)?;
168        let servo = own.get("motor.kind").ok().and_then(|v| v.as_str()).is_none_or(|k| k == "servo");
169        if machine.motor_linear(index) || !servo {
170            return Err(Error::NotRotaryServo(motor.id.into()));
171        }
172        let article = drive_article(cfg, motor.id);
173        let family = match (family, article) {
174            (Some(family), _) => family,
175            (None, "") => return Err(Error::NoDrive(motor.id.into())),
176            (None, article) => Family::of_article(article).ok_or_else(|| Error::UnknownDrive(article.into()))?,
177        };
178        let mapping = rows(family.mapping());
179        for &(key, unit, effect) in SETTINGS {
180            let Ok(value) = own.f64(&format!("drive.{key}")) else { continue };
181            if !effect.is_empty() && !own.bool(&format!("effects.{effect}")).unwrap_or(false) {
182                continue;
183            }
184            // A motor's notch at 0 Hz is none (`DriveParams::from_config`): the drive's filter stays off.
185            if effect == "notch_filter" && own.f64("drive.notch_frequency_hz") == Ok(0.0) {
186                continue;
187            }
188            let found: Vec<_> = mapping.iter().filter(|r| r["config_key"] == key).collect();
189            let row = |parameter: &str, name: &str, converted, parameter_unit: &str, basis| Row {
190                motor: motor.id.into(),
191                key,
192                value,
193                unit,
194                parameter: parameter.into(),
195                name: name.into(),
196                parameter_value: converted,
197                parameter_unit: parameter_unit.into(),
198                basis,
199            };
200            if found.is_empty() {
201                out.push(row("", "", None, "", Basis::None));
202            }
203            for r in found {
204                let basis = if r["basis"] == "printed" { Basis::Printed } else { Basis::Derived };
205                out.push(row(r["parameter"], r["name"], Some(convert(r, &own, value)?), r["unit"], basis));
206            }
207        }
208    }
209    Ok(out)
210}
211
212/// The parameter's value for the config's `value` by the row's factor and rule (see the tables' notes).
213fn convert(r: &crate::catalog::Row, own: &Config, value: f64) -> Result<f64, ConfigError> {
214    let factor: f64 =
215        r["factor"].parse().map_err(|_| ConfigError::Invalid(format!("parameters: factor {}", r["factor"])))?;
216    Ok(match r["rule"] {
217        "" => factor * value,
218        "constant" => factor,
219        "zero" => 0.0,
220        "notch_damping" => factor * value / (2.0 * own.positive("drive.notch_frequency_hz")?),
221        "ramp_time" => {
222            // The simulator's ramps run from the rated speed, the drive's from its maximum speed (p1082); the motor's
223            // maximum speed is the no-load speed where the config has none (`DriveParams::from_config`).
224            let max = own.positive("drive.max_speed_rad_s").or_else(|_| own.positive("drive.no_load_speed_rad_s"))?;
225            factor * value * max / own.positive("drive.rated_speed_rad_s")?
226        }
227        other => return Err(ConfigError::Invalid(format!("parameters: rule {other}"))),
228    })
229}