rumoca 0.7.28

Modelica compiler written in RUST
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
//! Equation Causalization
//!
//! This module implements causalization of equations - rewriting equations so that
//! a specific variable is isolated on the left-hand side.
//!
//! Causalization is essential for BLT transformation because once we know which
//! variable each equation should solve for (via matching), we need to algebraically
//! rearrange the equation to compute that variable.

use crate::ir::ast::{
    ComponentRefPart, ComponentReference, Equation, Expression, OpBinary, OpUnary, TerminalType,
    Token,
};
use crate::ir::visitor::{Visitable, Visitor};

/// Visitor to find der() calls in an expression
struct DerivativeFinder {
    derivatives: Vec<String>,
}

impl DerivativeFinder {
    fn new() -> Self {
        Self {
            derivatives: Vec::new(),
        }
    }
}

impl Visitor for DerivativeFinder {
    fn enter_expression(&mut self, node: &Expression) {
        if let Expression::FunctionCall { comp, args } = node
            && comp.to_string() == "der"
            && !args.is_empty()
            && let Expression::ComponentReference(cref) = &args[0]
        {
            self.derivatives.push(cref.to_string());
        }
    }
}

/// Check if expression contains a der() call
pub fn has_der_call(expr: &Expression) -> bool {
    let mut finder = DerivativeFinder::new();
    expr.accept(&mut finder);
    !finder.derivatives.is_empty()
}

/// Check if equation needs LHS/RHS swap (der() on RHS but not on LHS)
pub(super) fn check_if_needs_swap(lhs: &Expression, rhs: &Expression) -> bool {
    let lhs_has_der = has_der_call(lhs);
    let rhs_has_der = has_der_call(rhs);

    // Swap if RHS has der() but LHS doesn't
    !lhs_has_der && rhs_has_der
}

/// Normalize derivative equations of the form `coeff * der(x) = expr` to `der(x) = expr / coeff`
///
/// This handles cases from component models like:
/// - `C * der(v) = i` (capacitor) -> `der(v) = i / C`
/// - `L * der(i) = v` (inductor) -> `der(i) = v / L`
///
/// Returns None if the equation is not of this form.
pub(super) fn normalize_derivative_equation(
    lhs: &Expression,
    rhs: &Expression,
) -> Option<Equation> {
    // Check if LHS is coeff * der(x) or der(x) * coeff
    if let Expression::Binary {
        op: OpBinary::Mul(_),
        lhs: mult_lhs,
        rhs: mult_rhs,
    } = lhs
    {
        // Case 1: coeff * der(x)
        if let Expression::FunctionCall { comp, args } = mult_rhs.as_ref()
            && comp.to_string() == "der"
            && args.len() == 1
        {
            // Extract der(x) and coefficient
            let der_expr = mult_rhs.as_ref().clone();
            let coeff = mult_lhs.as_ref().clone();
            return Some(Equation::Simple {
                lhs: der_expr,
                rhs: Expression::Binary {
                    op: OpBinary::Div(Token::default()),
                    lhs: Box::new(rhs.clone()),
                    rhs: Box::new(coeff),
                },
            });
        }

        // Case 2: der(x) * coeff
        if let Expression::FunctionCall { comp, args } = mult_lhs.as_ref()
            && comp.to_string() == "der"
            && args.len() == 1
        {
            // Extract der(x) and coefficient
            let der_expr = mult_lhs.as_ref().clone();
            let coeff = mult_rhs.as_ref().clone();
            return Some(Equation::Simple {
                lhs: der_expr,
                rhs: Expression::Binary {
                    op: OpBinary::Div(Token::default()),
                    lhs: Box::new(rhs.clone()),
                    rhs: Box::new(coeff),
                },
            });
        }
    }

    None
}

/// Causalize an equation by solving for a specific variable.
///
/// Given an equation `lhs = rhs` and a variable to solve for, this function
/// attempts to algebraically rewrite the equation so the variable is isolated
/// on the left-hand side.
///
/// # Limitations
///
/// This function only handles **linear equations** where the variable appears
/// with coefficient ±1 or as a simple multiplication factor. It does **not** handle:
/// - Nonlinear occurrences (e.g., `x^2`, `sin(x)`, `x * y` where solving for `x`)
/// - Multiple occurrences of the same variable (e.g., `x + 2*x = 3`)
/// - Variables inside function calls (e.g., `f(x) = y`)
///
/// For unsupported equation forms, returns `None` and the equation remains
/// in its original form (may require numerical solving in algebraic loops).
///
/// # Supported Forms
///
/// - `var = expr` → already causalized, returns None
/// - `expr = var` → `var = expr`
/// - `a + b = 0` → `a = -b`
/// - `a + b + c = 0` → `a = -(b + c)`
/// - `coeff * var = expr` → `var = expr / coeff`
/// - `a + b = c` → `a = c - b`
///
/// # Returns
///
/// - `Some(equation)` if the equation was successfully causalized
/// - `None` if the equation is already in correct form or cannot be causalized
pub(super) fn causalize_equation(
    lhs: &Expression,
    rhs: &Expression,
    solve_for: &str,
) -> Option<Equation> {
    // Check if LHS is already just the variable we're solving for
    if let Expression::ComponentReference(cref) = lhs
        && cref.to_string() == solve_for
    {
        return None; // Already in correct form
    }

    // Check if RHS is just the variable we're solving for - swap if so
    // E.g., expr = var => var = expr
    if let Expression::ComponentReference(cref) = rhs
        && cref.to_string() == solve_for
    {
        return Some(Equation::Simple {
            lhs: rhs.clone(),
            rhs: lhs.clone(),
        });
    }

    // Helper to check if an expression is zero
    let is_zero = |expr: &Expression| -> bool {
        match expr {
            Expression::Terminal { token, .. } => token.text == "0" || token.text == "0.0",
            _ => false,
        }
    };

    // Check if RHS is zero (common case for KCL equations: a + b + c = 0)
    let rhs_is_zero = is_zero(rhs);
    // Also check if LHS is zero (alternate form: 0 = a + b + c)
    let lhs_is_zero = is_zero(lhs);

    if rhs_is_zero {
        // Equation is: lhs = 0, where lhs is a sum
        // We need to solve for `solve_for`: solve_for = -(other terms)
        if let Some((coeff, other_terms)) = extract_linear_term(lhs, solve_for) {
            // If coeff is 1: solve_for = -other_terms
            // If coeff is -1: solve_for = other_terms
            let new_rhs = if coeff > 0.0 {
                // solve_for + other = 0 => solve_for = -other
                negate_expression(&other_terms)
            } else {
                // -solve_for + other = 0 => solve_for = other
                other_terms
            };

            return Some(Equation::Simple {
                lhs: Expression::ComponentReference(ComponentReference {
                    local: false,
                    parts: vec![ComponentRefPart {
                        ident: Token {
                            text: solve_for.to_string(),
                            ..Default::default()
                        },
                        subs: None,
                    }],
                }),
                rhs: new_rhs,
            });
        }
    }

    if lhs_is_zero {
        // Equation is: 0 = rhs, where rhs is a sum (alternate form of KCL equations)
        // We need to solve for `solve_for`: solve_for = -(other terms)
        if let Some((coeff, other_terms)) = extract_linear_term(rhs, solve_for) {
            // If coeff is 1: solve_for = -other_terms
            // If coeff is -1: solve_for = other_terms
            let new_rhs = if coeff > 0.0 {
                // 0 = solve_for + other => solve_for = -other
                negate_expression(&other_terms)
            } else {
                // 0 = -solve_for + other => solve_for = other
                other_terms
            };

            return Some(Equation::Simple {
                lhs: Expression::ComponentReference(ComponentReference {
                    local: false,
                    parts: vec![ComponentRefPart {
                        ident: Token {
                            text: solve_for.to_string(),
                            ..Default::default()
                        },
                        subs: None,
                    }],
                }),
                rhs: new_rhs,
            });
        }
    }

    // Handle case: coeff * var = expr (multiplication on LHS)
    // E.g., R * i = v => solving for i gives i = v / R
    if let Expression::Binary {
        op: OpBinary::Mul(_),
        lhs: mult_lhs,
        rhs: mult_rhs,
    } = lhs
    {
        // Check if solve_for is on the right side of multiplication: coeff * var
        if let Expression::ComponentReference(cref) = mult_rhs.as_ref()
            && cref.to_string() == solve_for
        {
            return Some(Equation::Simple {
                lhs: Expression::ComponentReference(ComponentReference {
                    local: false,
                    parts: vec![ComponentRefPart {
                        ident: Token {
                            text: solve_for.to_string(),
                            ..Default::default()
                        },
                        subs: None,
                    }],
                }),
                rhs: Expression::Binary {
                    op: OpBinary::Div(Token::default()),
                    lhs: Box::new(rhs.clone()),
                    rhs: mult_lhs.clone(),
                },
            });
        }
        // Check if solve_for is on the left side of multiplication: var * coeff
        if let Expression::ComponentReference(cref) = mult_lhs.as_ref()
            && cref.to_string() == solve_for
        {
            return Some(Equation::Simple {
                lhs: Expression::ComponentReference(ComponentReference {
                    local: false,
                    parts: vec![ComponentRefPart {
                        ident: Token {
                            text: solve_for.to_string(),
                            ..Default::default()
                        },
                        subs: None,
                    }],
                }),
                rhs: Expression::Binary {
                    op: OpBinary::Div(Token::default()),
                    lhs: Box::new(rhs.clone()),
                    rhs: mult_rhs.clone(),
                },
            });
        }
    }

    // Handle case: lhs = rhs where lhs contains solve_for
    // E.g., a + b = c => solving for a gives a = c - b
    if let Some((coeff, other_terms)) = extract_linear_term(lhs, solve_for) {
        // lhs contains solve_for: coeff*solve_for + other_terms = rhs
        // => solve_for = (rhs - other_terms) / coeff
        let rhs_minus_other = if is_zero_expression(&other_terms) {
            rhs.clone()
        } else {
            Expression::Binary {
                op: OpBinary::Sub(Token::default()),
                lhs: Box::new(rhs.clone()),
                rhs: Box::new(other_terms),
            }
        };

        let new_rhs = if (coeff - 1.0).abs() < 1e-10 {
            rhs_minus_other
        } else if (coeff + 1.0).abs() < 1e-10 {
            negate_expression(&rhs_minus_other)
        } else {
            // General case: divide by coefficient
            Expression::Binary {
                op: OpBinary::Div(Token::default()),
                lhs: Box::new(rhs_minus_other),
                rhs: Box::new(Expression::Terminal {
                    terminal_type: TerminalType::UnsignedReal,
                    token: Token {
                        text: coeff.to_string(),
                        ..Default::default()
                    },
                }),
            }
        };

        return Some(Equation::Simple {
            lhs: Expression::ComponentReference(ComponentReference {
                local: false,
                parts: vec![ComponentRefPart {
                    ident: Token {
                        text: solve_for.to_string(),
                        ..Default::default()
                    },
                    subs: None,
                }],
            }),
            rhs: new_rhs,
        });
    }

    // Handle case: lhs = rhs where rhs contains solve_for
    // E.g., a = b - c where solving for b gives b = a + c
    if let Some((coeff, other_terms)) = extract_linear_term(rhs, solve_for) {
        // rhs contains solve_for: lhs = coeff*solve_for + other_terms
        // => solve_for = (lhs - other_terms) / coeff
        let lhs_minus_other = if is_zero_expression(&other_terms) {
            lhs.clone()
        } else {
            Expression::Binary {
                op: OpBinary::Sub(Token::default()),
                lhs: Box::new(lhs.clone()),
                rhs: Box::new(other_terms),
            }
        };

        let new_rhs = if (coeff - 1.0).abs() < 1e-10 {
            lhs_minus_other
        } else if (coeff + 1.0).abs() < 1e-10 {
            negate_expression(&lhs_minus_other)
        } else {
            // General case: divide by coefficient
            Expression::Binary {
                op: OpBinary::Div(Token::default()),
                lhs: Box::new(lhs_minus_other),
                rhs: Box::new(Expression::Terminal {
                    terminal_type: TerminalType::UnsignedReal,
                    token: Token {
                        text: coeff.to_string(),
                        ..Default::default()
                    },
                }),
            }
        };

        return Some(Equation::Simple {
            lhs: Expression::ComponentReference(ComponentReference {
                local: false,
                parts: vec![ComponentRefPart {
                    ident: Token {
                        text: solve_for.to_string(),
                        ..Default::default()
                    },
                    subs: None,
                }],
            }),
            rhs: new_rhs,
        });
    }

    None
}

/// Check if an expression is effectively zero
fn is_zero_expression(expr: &Expression) -> bool {
    match expr {
        Expression::Terminal { token, .. } => token.text == "0" || token.text == "0.0",
        _ => false,
    }
}

/// Negate an expression: expr -> -expr or -(expr)
fn negate_expression(expr: &Expression) -> Expression {
    // Handle simple cases to produce cleaner output
    match expr {
        // -(-x) = x
        Expression::Unary {
            op: OpUnary::Minus(_),
            rhs,
        } => (**rhs).clone(),
        // -(a - b) = b - a
        Expression::Binary {
            op: OpBinary::Sub(_),
            lhs,
            rhs,
        } => Expression::Binary {
            op: OpBinary::Sub(Token::default()),
            lhs: rhs.clone(),
            rhs: lhs.clone(),
        },
        // For other expressions, just negate
        _ => Expression::Unary {
            op: OpUnary::Minus(Token::default()),
            rhs: Box::new(expr.clone()),
        },
    }
}

/// Extract the coefficient and remaining terms for a variable in a linear expression.
///
/// Given an expression like `a + b + c` and variable `a`, returns `(1.0, b + c)`.
/// Given an expression like `-a + b` and variable `a`, returns `(-1.0, b)`.
///
/// Returns None if the variable is not found or appears nonlinearly.
fn extract_linear_term(expr: &Expression, var_name: &str) -> Option<(f64, Expression)> {
    match expr {
        Expression::ComponentReference(cref) => {
            if cref.to_string() == var_name {
                // Just the variable itself: coefficient is 1, no other terms
                Some((
                    1.0,
                    Expression::Terminal {
                        terminal_type: TerminalType::UnsignedReal,
                        token: Token {
                            text: "0".to_string(),
                            ..Default::default()
                        },
                    },
                ))
            } else {
                None // Variable not found in this expression
            }
        }
        Expression::Unary {
            op: OpUnary::Minus(_),
            rhs,
        } => {
            // -expr: check if rhs is the variable
            if let Expression::ComponentReference(cref) = rhs.as_ref()
                && cref.to_string() == var_name
            {
                return Some((
                    -1.0,
                    Expression::Terminal {
                        terminal_type: TerminalType::UnsignedReal,
                        token: Token {
                            text: "0".to_string(),
                            ..Default::default()
                        },
                    },
                ));
            }
            // Recursively check inside the negation
            if let Some((coeff, other)) = extract_linear_term(rhs, var_name) {
                Some((-coeff, negate_expression(&other)))
            } else {
                None
            }
        }
        Expression::Binary {
            op: OpBinary::Add(_),
            lhs,
            rhs,
        } => {
            // a + b: check both sides
            if let Some((coeff, other_from_lhs)) = extract_linear_term(lhs, var_name) {
                // Variable found in lhs
                let combined_other = if is_zero_expression(&other_from_lhs) {
                    (**rhs).clone()
                } else {
                    Expression::Binary {
                        op: OpBinary::Add(Token::default()),
                        lhs: Box::new(other_from_lhs),
                        rhs: rhs.clone(),
                    }
                };
                Some((coeff, combined_other))
            } else if let Some((coeff, other_from_rhs)) = extract_linear_term(rhs, var_name) {
                // Variable found in rhs
                let combined_other = if is_zero_expression(&other_from_rhs) {
                    (**lhs).clone()
                } else {
                    Expression::Binary {
                        op: OpBinary::Add(Token::default()),
                        lhs: lhs.clone(),
                        rhs: Box::new(other_from_rhs),
                    }
                };
                Some((coeff, combined_other))
            } else {
                None
            }
        }
        Expression::Binary {
            op: OpBinary::Sub(_),
            lhs,
            rhs,
        } => {
            // a - b: check both sides
            if let Some((coeff, other_from_lhs)) = extract_linear_term(lhs, var_name) {
                // Variable found in lhs: (coeff*var + other) - rhs
                let combined_other = if is_zero_expression(&other_from_lhs) {
                    negate_expression(rhs)
                } else {
                    Expression::Binary {
                        op: OpBinary::Sub(Token::default()),
                        lhs: Box::new(other_from_lhs),
                        rhs: rhs.clone(),
                    }
                };
                Some((coeff, combined_other))
            } else if let Some((coeff, other_from_rhs)) = extract_linear_term(rhs, var_name) {
                // Variable found in rhs: lhs - (coeff*var + other)
                // = lhs - coeff*var - other
                // = -coeff*var + (lhs - other)
                let combined_other = if is_zero_expression(&other_from_rhs) {
                    (**lhs).clone()
                } else {
                    Expression::Binary {
                        op: OpBinary::Sub(Token::default()),
                        lhs: lhs.clone(),
                        rhs: Box::new(other_from_rhs),
                    }
                };
                Some((-coeff, combined_other))
            } else {
                None
            }
        }
        _ => None, // Other expression types not handled
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_var(name: &str) -> Expression {
        Expression::ComponentReference(ComponentReference {
            local: false,
            parts: vec![ComponentRefPart {
                ident: Token {
                    text: name.to_string(),
                    ..Default::default()
                },
                subs: None,
            }],
        })
    }

    fn make_zero() -> Expression {
        Expression::Terminal {
            terminal_type: TerminalType::UnsignedReal,
            token: Token {
                text: "0".to_string(),
                ..Default::default()
            },
        }
    }

    #[test]
    fn test_causalize_already_causal() {
        // x = y (already in correct form for solving for x)
        let lhs = make_var("x");
        let rhs = make_var("y");

        let result = causalize_equation(&lhs, &rhs, "x");
        assert!(result.is_none(), "Already causal, should return None");
    }

    #[test]
    fn test_causalize_sum_to_zero() {
        // a + b = 0 => solving for a gives a = -b
        let lhs = Expression::Binary {
            op: OpBinary::Add(Token::default()),
            lhs: Box::new(make_var("a")),
            rhs: Box::new(make_var("b")),
        };
        let rhs = make_zero();

        let result = causalize_equation(&lhs, &rhs, "a");
        assert!(result.is_some());

        if let Some(Equation::Simple { lhs, rhs: _ }) = result {
            // LHS should be just "a"
            assert!(
                matches!(lhs, Expression::ComponentReference(_)),
                "LHS should be a simple variable"
            );
        } else {
            panic!("Expected Simple equation");
        }
    }

    #[test]
    fn test_causalize_three_term_sum() {
        // a + b + c = 0 => solving for a gives a = -(b + c)
        let inner_sum = Expression::Binary {
            op: OpBinary::Add(Token::default()),
            lhs: Box::new(make_var("a")),
            rhs: Box::new(make_var("b")),
        };
        let lhs = Expression::Binary {
            op: OpBinary::Add(Token::default()),
            lhs: Box::new(inner_sum),
            rhs: Box::new(make_var("c")),
        };
        let rhs = make_zero();

        let result = causalize_equation(&lhs, &rhs, "a");
        assert!(result.is_some(), "Should be able to solve for 'a'");
    }

    #[test]
    fn test_causalize_zero_on_lhs() {
        // 0 = a + b => solving for a gives a = -b
        let lhs = make_zero();
        let rhs = Expression::Binary {
            op: OpBinary::Add(Token::default()),
            lhs: Box::new(make_var("a")),
            rhs: Box::new(make_var("b")),
        };

        let result = causalize_equation(&lhs, &rhs, "a");
        assert!(result.is_some(), "Should handle zero on LHS");
    }
}