runmat-runtime 0.4.8

Core runtime for RunMat with builtins, BLAS/LAPACK integration, and execution APIs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//! MATLAB-compatible `tf` transfer-function constructor for RunMat.

use std::collections::HashMap;
use std::sync::OnceLock;

use num_complex::Complex64;
use runmat_builtins::{
    Access, CharArray, ClassDef, ComplexTensor, MethodDef, ObjectInstance, PropertyDef, Tensor,
    Value,
};
use runmat_macros::runtime_builtin;

use crate::builtins::common::spec::{
    BroadcastSemantics, BuiltinFusionSpec, BuiltinGpuSpec, ConstantStrategy, GpuOpKind,
    ReductionNaN, ResidencyPolicy, ShapeRequirements,
};
use crate::builtins::common::tensor;
use crate::builtins::control::type_resolvers::tf_type;
use crate::{build_runtime_error, dispatcher, BuiltinResult, RuntimeError};

const BUILTIN_NAME: &str = "tf";
const TF_CLASS: &str = "tf";
const DEFAULT_VARIABLE: &str = "s";
const EPS: f64 = 1.0e-12;

static TF_CLASS_REGISTERED: OnceLock<()> = OnceLock::new();

#[runmat_macros::register_gpu_spec(builtin_path = "crate::builtins::control::tf")]
pub const GPU_SPEC: BuiltinGpuSpec = BuiltinGpuSpec {
    name: "tf",
    op_kind: GpuOpKind::Custom("transfer-function-constructor"),
    supported_precisions: &[],
    broadcast: BroadcastSemantics::None,
    provider_hooks: &[],
    constant_strategy: ConstantStrategy::InlineLiteral,
    residency: ResidencyPolicy::GatherImmediately,
    nan_mode: ReductionNaN::Include,
    two_pass_threshold: None,
    workgroup_size: None,
    accepts_nan_mode: false,
    notes: "Object construction runs on the host. gpuArray coefficient inputs are gathered before storing the transfer-function metadata.",
};

#[runmat_macros::register_fusion_spec(builtin_path = "crate::builtins::control::tf")]
pub const FUSION_SPEC: BuiltinFusionSpec = BuiltinFusionSpec {
    name: "tf",
    shape: ShapeRequirements::Any,
    constant_strategy: ConstantStrategy::InlineLiteral,
    elementwise: None,
    reduction: None,
    emits_nan: false,
    notes: "Transfer-function construction is metadata-only and terminates numeric fusion chains.",
};

fn tf_error(message: impl Into<String>) -> RuntimeError {
    build_runtime_error(message)
        .with_builtin(BUILTIN_NAME)
        .build()
}

fn ensure_tf_class_registered() {
    TF_CLASS_REGISTERED.get_or_init(|| {
        let mut properties = HashMap::new();
        for name in [
            "Numerator",
            "Denominator",
            "Variable",
            "Ts",
            "InputDelay",
            "OutputDelay",
        ] {
            properties.insert(
                name.to_string(),
                PropertyDef {
                    name: name.to_string(),
                    is_static: false,
                    is_dependent: false,
                    get_access: Access::Public,
                    set_access: Access::Public,
                    default_value: None,
                },
            );
        }

        let methods: HashMap<String, MethodDef> = HashMap::new();
        runmat_builtins::register_class(ClassDef {
            name: TF_CLASS.to_string(),
            parent: None,
            properties,
            methods,
        });
    });
}

#[runtime_builtin(
    name = "tf",
    category = "control",
    summary = "Create a SISO transfer-function object from numerator and denominator coefficient vectors.",
    keywords = "tf,transfer function,control system,filter,polynomial",
    type_resolver(tf_type),
    builtin_path = "crate::builtins::control::tf"
)]
async fn tf_builtin(
    numerator: Value,
    denominator: Value,
    rest: Vec<Value>,
) -> BuiltinResult<Value> {
    let options = TfOptions::parse(&rest)?;
    let numerator = Coefficients::parse("numerator", numerator).await?;
    let denominator = Coefficients::parse("denominator", denominator).await?;

    if denominator.coeffs.is_empty() {
        return Err(tf_error("tf: denominator coefficients cannot be empty"));
    }
    if denominator.is_all_zero() {
        return Err(tf_error(
            "tf: denominator coefficients must not all be zero",
        ));
    }

    ensure_tf_class_registered();
    let mut object = ObjectInstance::new(TF_CLASS.to_string());
    object
        .properties
        .insert("Numerator".to_string(), numerator.into_row_value()?);
    object
        .properties
        .insert("Denominator".to_string(), denominator.into_row_value()?);
    object.properties.insert(
        "Variable".to_string(),
        Value::CharArray(CharArray::new_row(&options.variable)),
    );
    object
        .properties
        .insert("Ts".to_string(), Value::Num(options.sample_time));
    object
        .properties
        .insert("InputDelay".to_string(), Value::Num(0.0));
    object
        .properties
        .insert("OutputDelay".to_string(), Value::Num(0.0));
    Ok(Value::Object(object))
}

#[derive(Clone)]
struct TfOptions {
    variable: String,
    sample_time: f64,
    variable_explicit: bool,
}

impl TfOptions {
    fn parse(rest: &[Value]) -> BuiltinResult<Self> {
        let mut options = Self {
            variable: DEFAULT_VARIABLE.to_string(),
            sample_time: 0.0,
            variable_explicit: false,
        };

        match rest {
            [] => {}
            [sample_time] => {
                options.sample_time = parse_sample_time(sample_time)?;
                if options.sample_time > 0.0 {
                    options.variable = "z".to_string();
                }
            }
            _ => {
                if !rest.len().is_multiple_of(2) {
                    return Err(tf_error(
                        "tf: optional arguments must be name-value pairs or a scalar sample time",
                    ));
                }
                let mut idx = 0;
                while idx < rest.len() {
                    let name = scalar_text(&rest[idx], "option name")?;
                    let lowered = name.trim().to_ascii_lowercase();
                    let value = &rest[idx + 1];
                    match lowered.as_str() {
                        "variable" => {
                            options.variable = parse_variable(value)?;
                            options.variable_explicit = true;
                        }
                        "ts" | "sampletime" => options.sample_time = parse_sample_time(value)?,
                        _ => {
                            return Err(tf_error(format!("tf: unsupported option '{name}'")));
                        }
                    }
                    idx += 2;
                }
                if options.sample_time > 0.0 && !options.variable_explicit {
                    options.variable = "z".to_string();
                }
            }
        }

        Ok(options)
    }
}

fn parse_sample_time(value: &Value) -> BuiltinResult<f64> {
    let sample_time = match value {
        Value::Num(n) => *n,
        Value::Int(i) => i.to_f64(),
        other => {
            return Err(tf_error(format!(
                "tf: sample time must be a non-negative scalar, got {other:?}"
            )))
        }
    };
    if !sample_time.is_finite() || sample_time < 0.0 {
        return Err(tf_error(
            "tf: sample time must be a finite non-negative scalar",
        ));
    }
    Ok(sample_time)
}

fn parse_variable(value: &Value) -> BuiltinResult<String> {
    let variable = scalar_text(value, "Variable")?;
    let variable = variable.trim();
    match variable {
        "s" | "p" | "z" | "q" | "z^-1" | "q^-1" => Ok(variable.to_string()),
        _ => Err(tf_error(
            "tf: Variable must be one of 's', 'p', 'z', 'q', 'z^-1', or 'q^-1'",
        )),
    }
}

fn scalar_text(value: &Value, context: &str) -> BuiltinResult<String> {
    match value {
        Value::String(text) => Ok(text.clone()),
        Value::StringArray(array) if array.data.len() == 1 => Ok(array.data[0].clone()),
        Value::CharArray(array) if array.rows == 1 => Ok(array.data.iter().collect()),
        other => Err(tf_error(format!(
            "tf: {context} must be a string scalar or character vector, got {other:?}"
        ))),
    }
}

#[derive(Clone)]
struct Coefficients {
    coeffs: Vec<Complex64>,
}

impl Coefficients {
    async fn parse(label: &str, value: Value) -> BuiltinResult<Self> {
        let gathered = dispatcher::gather_if_needed_async(&value).await?;
        let coeffs = match gathered {
            Value::Tensor(tensor) => {
                ensure_vector_shape(label, &tensor.shape)?;
                tensor
                    .data
                    .into_iter()
                    .map(|re| Complex64::new(re, 0.0))
                    .collect()
            }
            Value::ComplexTensor(tensor) => {
                ensure_vector_shape(label, &tensor.shape)?;
                tensor
                    .data
                    .into_iter()
                    .map(|(re, im)| Complex64::new(re, im))
                    .collect()
            }
            Value::LogicalArray(logical) => {
                let tensor = tensor::logical_to_tensor(&logical).map_err(tf_error)?;
                ensure_vector_shape(label, &tensor.shape)?;
                tensor
                    .data
                    .into_iter()
                    .map(|re| Complex64::new(re, 0.0))
                    .collect()
            }
            Value::Num(n) => vec![Complex64::new(n, 0.0)],
            Value::Int(i) => vec![Complex64::new(i.to_f64(), 0.0)],
            Value::Bool(b) => vec![Complex64::new(if b { 1.0 } else { 0.0 }, 0.0)],
            Value::Complex(re, im) => vec![Complex64::new(re, im)],
            other => {
                return Err(tf_error(format!(
                    "tf: {label} must be a numeric coefficient vector, got {other:?}"
                )));
            }
        };

        if coeffs.is_empty() {
            return Err(tf_error(format!(
                "tf: {label} coefficients cannot be empty"
            )));
        }
        for coeff in &coeffs {
            if !coeff.re.is_finite() || !coeff.im.is_finite() {
                return Err(tf_error(format!("tf: {label} coefficients must be finite")));
            }
        }

        Ok(Self { coeffs })
    }

    fn is_all_zero(&self) -> bool {
        self.coeffs.iter().all(|coeff| coeff.norm() <= EPS)
    }

    fn into_row_value(self) -> BuiltinResult<Value> {
        let len = self.coeffs.len();
        if self.coeffs.iter().all(|coeff| coeff.im.abs() <= EPS) {
            let data = self.coeffs.into_iter().map(|coeff| coeff.re).collect();
            let tensor =
                Tensor::new(data, vec![1, len]).map_err(|err| tf_error(format!("tf: {err}")))?;
            Ok(Value::Tensor(tensor))
        } else {
            let data = self
                .coeffs
                .into_iter()
                .map(|coeff| (coeff.re, coeff.im))
                .collect();
            let tensor = ComplexTensor::new(data, vec![1, len])
                .map_err(|err| tf_error(format!("tf: {err}")))?;
            Ok(Value::ComplexTensor(tensor))
        }
    }
}

fn ensure_vector_shape(label: &str, shape: &[usize]) -> BuiltinResult<()> {
    let non_unit = shape.iter().copied().filter(|&dim| dim > 1).count();
    if non_unit <= 1 {
        Ok(())
    } else {
        Err(tf_error(format!(
            "tf: {label} coefficients must be a vector"
        )))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures::executor::block_on;
    use runmat_builtins::IntValue;

    fn run_tf(numerator: Value, denominator: Value, rest: Vec<Value>) -> BuiltinResult<Value> {
        block_on(tf_builtin(numerator, denominator, rest))
    }

    fn property<'a>(value: &'a Value, name: &str) -> &'a Value {
        let Value::Object(object) = value else {
            panic!("expected object, got {value:?}");
        };
        object
            .properties
            .get(name)
            .unwrap_or_else(|| panic!("missing property {name}"))
    }

    #[test]
    fn tf_constructs_continuous_siso_object() {
        let sys = run_tf(
            Value::Num(20.0),
            Value::Tensor(Tensor::new(vec![1.0, 5.0], vec![1, 2]).unwrap()),
            Vec::new(),
        )
        .expect("tf");

        let Value::Object(object) = &sys else {
            panic!("expected object");
        };
        assert_eq!(object.class_name, "tf");
        assert_eq!(
            property(&sys, "Variable"),
            &Value::CharArray(CharArray::new_row("s"))
        );
        assert_eq!(property(&sys, "Ts"), &Value::Num(0.0));
        match property(&sys, "Numerator") {
            Value::Tensor(tensor) => {
                assert_eq!(tensor.shape, vec![1, 1]);
                assert_eq!(tensor.data, vec![20.0]);
            }
            other => panic!("expected numerator tensor, got {other:?}"),
        }
        match property(&sys, "Denominator") {
            Value::Tensor(tensor) => {
                assert_eq!(tensor.shape, vec![1, 2]);
                assert_eq!(tensor.data, vec![1.0, 5.0]);
            }
            other => panic!("expected denominator tensor, got {other:?}"),
        }
    }

    #[test]
    fn tf_normalizes_column_coefficients_to_rows() {
        let sys = run_tf(
            Value::Tensor(Tensor::new(vec![1.0, 2.0], vec![2, 1]).unwrap()),
            Value::Tensor(Tensor::new(vec![1.0, 3.0, 2.0], vec![3, 1]).unwrap()),
            Vec::new(),
        )
        .expect("tf");

        match property(&sys, "Numerator") {
            Value::Tensor(tensor) => {
                assert_eq!(tensor.shape, vec![1, 2]);
                assert_eq!(tensor.data, vec![1.0, 2.0]);
            }
            other => panic!("expected numerator tensor, got {other:?}"),
        }
        match property(&sys, "Denominator") {
            Value::Tensor(tensor) => {
                assert_eq!(tensor.shape, vec![1, 3]);
                assert_eq!(tensor.data, vec![1.0, 3.0, 2.0]);
            }
            other => panic!("expected denominator tensor, got {other:?}"),
        }
    }

    #[test]
    fn tf_accepts_discrete_sample_time() {
        let sys = run_tf(
            Value::Int(IntValue::I32(1)),
            Value::Tensor(Tensor::new(vec![1.0, -0.5], vec![1, 2]).unwrap()),
            vec![Value::Num(0.1)],
        )
        .expect("tf");

        assert_eq!(
            property(&sys, "Variable"),
            &Value::CharArray(CharArray::new_row("z"))
        );
        assert_eq!(property(&sys, "Ts"), &Value::Num(0.1));
    }

    #[test]
    fn tf_positional_zero_sample_time_remains_continuous() {
        let sys = run_tf(
            Value::Int(IntValue::I32(1)),
            Value::Tensor(Tensor::new(vec![1.0, 5.0], vec![1, 2]).unwrap()),
            vec![Value::Num(0.0)],
        )
        .expect("tf");

        assert_eq!(
            property(&sys, "Variable"),
            &Value::CharArray(CharArray::new_row("s"))
        );
        assert_eq!(property(&sys, "Ts"), &Value::Num(0.0));
    }

    #[test]
    fn tf_accepts_variable_name_value_option() {
        let sys = run_tf(
            Value::Num(1.0),
            Value::Tensor(Tensor::new(vec![1.0, 1.0], vec![1, 2]).unwrap()),
            vec![Value::from("Variable"), Value::from("p")],
        )
        .expect("tf");

        assert_eq!(
            property(&sys, "Variable"),
            &Value::CharArray(CharArray::new_row("p"))
        );
    }

    #[test]
    fn tf_explicit_continuous_variable_survives_positive_sample_time() {
        let sys = run_tf(
            Value::Num(1.0),
            Value::Tensor(Tensor::new(vec![1.0, 1.0], vec![1, 2]).unwrap()),
            vec![
                Value::from("Variable"),
                Value::from("s"),
                Value::from("Ts"),
                Value::Num(0.5),
            ],
        )
        .expect("tf");

        assert_eq!(
            property(&sys, "Variable"),
            &Value::CharArray(CharArray::new_row("s"))
        );
        assert_eq!(property(&sys, "Ts"), &Value::Num(0.5));
    }

    #[test]
    fn tf_rejects_zero_denominator() {
        let err = run_tf(
            Value::Num(1.0),
            Value::Tensor(Tensor::new(vec![0.0, 0.0], vec![1, 2]).unwrap()),
            Vec::new(),
        )
        .expect_err("zero denominator should fail");
        assert!(err.message().contains("must not all be zero"));
    }

    #[test]
    fn tf_rejects_matrix_coefficients() {
        let err = run_tf(
            Value::Tensor(Tensor::new(vec![1.0, 2.0, 3.0, 4.0], vec![2, 2]).unwrap()),
            Value::Tensor(Tensor::new(vec![1.0, 5.0], vec![1, 2]).unwrap()),
            Vec::new(),
        )
        .expect_err("matrix numerator should fail");
        assert!(err
            .message()
            .contains("numerator coefficients must be a vector"));
    }
}