1#![cfg_attr(not(feature = "std"), no_std)]
2
3extern crate alloc;
10#[cfg(test)]
11extern crate std;
12
13#[cfg(test)]
14use std::prelude::v1::*;
15
16pub mod i18n;
17
18pub use i18n::Error;
19pub use i18n::ReservedReason;
20mod math;
21pub mod runtime;
22pub mod wgsl;
23
24pub fn math_fract(value: f64) -> f64 {
26 math::fract(value)
27}
28
29use alloc::boxed::Box;
30use alloc::collections::{BTreeMap, BTreeSet};
31use alloc::format;
32use alloc::string::{String, ToString};
33use alloc::vec;
34use alloc::vec::Vec;
35use core::fmt::Write as _;
36#[cfg(feature = "std")]
37pub use std::collections::HashMap;
38
39#[cfg(not(feature = "std"))]
40pub type HashMap<K, V> = BTreeMap<K, V>;
41
42#[derive(Clone, Debug, PartialEq)]
52pub struct FrontError {
53 pub line: usize,
54 pub col: usize,
55 pub msg: String,
57 pub code: Box<i18n::Error>,
58 args: Vec<String>,
60}
61
62impl FrontError {
63 pub fn new(line: usize, col: usize, msg: impl Into<Error>) -> Self {
64 let error: Error = msg.into();
68 let rendered = error.render(i18n::Locale::En);
69 Self {
70 line,
71 col,
72 msg: rendered,
73 code: Box::new(error),
74 args: Vec::new(),
75 }
76 }
77
78 pub fn plain(msg: impl Into<Error>) -> Self {
79 let error: Error = msg.into();
82 let msg = error.render(i18n::Locale::En);
83 Self {
84 line: 0,
85 col: 0,
86 msg,
87 code: Box::new(error),
88 args: Vec::new(),
89 }
90 }
91
92 pub fn coded(code: i18n::Error, args: &[&str], line: usize, col: usize) -> Self {
97 Self {
98 line,
99 col,
100 msg: i18n::render(&code, args, i18n::Locale::En),
101 code: Box::new(code),
102 args: args.iter().map(|a| a.to_string()).collect(),
103 }
104 }
105
106 pub fn render_in(&self, language: i18n::Locale) -> String {
108 let borrowed: Vec<&str> = self.args.iter().map(|a| a.as_str()).collect();
112 i18n::render(&self.code, &borrowed, language)
113 }
114
115 pub fn in_locale(&self, language: i18n::Locale) -> Self {
117 let mut out = self.clone();
118 out.msg = self.render_in(language);
119 out
120 }
121
122 pub fn localized(&self) -> Self {
124 #[cfg(feature = "std")]
125 {
126 self.in_locale(i18n::Locale::from_env())
127 }
128 #[cfg(not(feature = "std"))]
129 {
130 self.clone()
131 }
132 }
133
134 pub fn render_with_source(&self, origin: &str, src: &str) -> String {
140 let head = self.render(origin);
141 if self.line == 0 {
142 return head;
143 }
144 let Some(text) = src.lines().nth(self.line - 1) else {
145 return head;
146 };
147 let gutter = format!("{}", self.line);
148 let pad = " ".repeat(gutter.len());
149 let mut caret = String::new();
152 for ch in text.chars().take(self.col.saturating_sub(1)) {
153 caret.push(if ch == '\t' { '\t' } else { ' ' });
154 }
155 format!("{head}\n{pad} |\n{gutter} | {text}\n{pad} | {caret}^")
156 }
157
158 pub fn render(&self, origin: &str) -> String {
159 if self.line == 0 {
160 format!("{origin}: {}", self.msg)
161 } else {
162 format!("{origin}:{}:{}: {}", self.line, self.col, self.msg)
163 }
164 }
165}
166
167impl From<Error> for FrontError {
168 fn from(code: Error) -> Self {
175 let msg = code.render(i18n::Locale::En);
176 Self {
177 line: 0,
178 col: 0,
179 msg,
180 code: Box::new(code),
181 args: Vec::new(),
182 }
183 }
184}
185
186#[derive(Clone, Debug, PartialEq, Eq)]
191pub struct Decl {
192 pub name: String,
193 pub quantity: String,
194 pub unit: Option<String>,
195}
196
197#[derive(Clone, Copy, Debug, PartialEq, Eq)]
206pub struct Dim(pub [i16; 7]);
207
208impl Dim {
209 pub const ZERO: Dim = Dim([0; 7]);
210
211 pub fn from_exponents(exps: [i16; 7]) -> Dim {
213 Dim(exps.map(|e| e * 2))
214 }
215
216 pub fn exponents(&self) -> [i16; 7] {
219 self.0.map(|e| e / 2)
220 }
221
222 pub fn is_zero(&self) -> bool {
223 self.0.iter().all(|v| *v == 0)
224 }
225
226 fn mul_dim(self, o: Dim) -> Dim {
227 let mut r = self.0;
228 for (a, b) in r.iter_mut().zip(o.0) {
229 *a += b;
230 }
231 Dim(r)
232 }
233
234 fn div_dim(self, o: Dim) -> Dim {
235 let mut r = self.0;
236 for (a, b) in r.iter_mut().zip(o.0) {
237 *a -= b;
238 }
239 Dim(r)
240 }
241
242 pub fn scale_ratio(self, p: i32, q: i32) -> Result<Dim, Error> {
248 if q == 0 {
249 return Err(Error::ExponentZeroDenominator {
250 exponent: format!("{p}/{q}"),
251 });
252 }
253 let mut r = [0i16; 7];
254 for (out, v) in r.iter_mut().zip(self.0) {
255 let prod = v as i64 * p as i64;
258 if prod % q as i64 != 0 {
259 return Err(Error::ExponentNotHalfInteger(format!("{p}/{q}")));
260 }
261 let scaled = prod / q as i64;
262 *out = i16::try_from(scaled).map_err(|_| Error::ExponentOutOfRange {
263 exponent: format!("{p}/{q}"),
264 })?;
265 }
266 Ok(Dim(r))
267 }
268
269 pub fn display(&self) -> String {
270 const NAMES: [&str; 7] = ["kg", "m", "s", "A", "K", "mol", "cd"];
271 if self.is_zero() {
272 return "1".to_string();
273 }
274 let mut parts = Vec::new();
275 for (i, n) in NAMES.iter().enumerate() {
276 let half = self.0[i];
277 if half == 0 {
278 continue;
279 }
280 if half % 2 == 0 {
281 let e = half / 2;
282 if e == 1 {
283 parts.push((*n).to_string());
284 } else {
285 parts.push(format!("{n}^{e}"));
286 }
287 } else {
288 parts.push(format!("{n}^({half}/2)"));
291 }
292 }
293 parts.join("·")
294 }
295}
296
297#[derive(Clone, Copy, Debug, PartialEq)]
303pub struct UnitSpec {
304 pub dim: Dim,
305 pub scale: f64,
307}
308
309const SI_PREFIXES: &[(&str, f64)] = &[
312 ("da", 1e1),
313 ("Q", 1e30),
314 ("R", 1e27),
315 ("r", 1e-27),
316 ("q", 1e-30),
317 ("Y", 1e24),
318 ("Z", 1e21),
319 ("E", 1e18),
320 ("P", 1e15),
321 ("T", 1e12),
322 ("G", 1e9),
323 ("M", 1e6),
324 ("k", 1e3),
325 ("h", 1e2),
326 ("d", 1e-1),
327 ("c", 1e-2),
328 ("m", 1e-3),
329 ("\u{00b5}", 1e-6),
330 ("\u{03bc}", 1e-6),
331 ("n", 1e-9),
332 ("p", 1e-12),
333 ("f", 1e-15),
334 ("a", 1e-18),
335 ("z", 1e-21),
336 ("y", 1e-24),
337];
338
339fn rejected_unit(name: &str) -> Option<Error> {
350 match name {
351 "degC" | "Celsius" | "degF" | "Fahrenheit" | "degR" => {
352 Some(Error::OffsetUnit(name.to_string()))
353 }
354 "dB" | "dBm" | "dBW" | "dBV" | "neper" => Some(Error::LogUnit(name.to_string())),
355 "cal" | "Cal" => Some(Error::AmbiguousUnit {
359 name: name.to_string(),
360 why: "cal_th = 4.184 J and cal_IT = 4.1868 J differ".to_string(),
361 remedy: "write the J value explicitly".to_string(),
362 }),
363 "rpm" => Some(Error::AmbiguousUnit {
364 name: name.to_string(),
365 why: "1 rpm = 2*pi/60 rad/s, and rad is dimensionless here".to_string(),
366 remedy: "write `2 * pi * f` with f declared in Hz".to_string(),
367 }),
368 _ => None,
369 }
370}
371
372fn prefixed_unit(name: &str) -> Result<(Dim, f64), Error> {
373 if let Some(error) = rejected_unit(name) {
374 return Err(error);
375 }
376 if let Ok(hit) = unit_base(name) {
377 return Ok(hit);
378 }
379 for (pfx, k) in SI_PREFIXES {
380 if let Some(rest) = name.strip_prefix(pfx) {
381 if rest.is_empty() {
382 continue;
383 }
384 if let Ok((d, base_scale)) = unit_base(rest) {
385 return Ok((d, *k * base_scale));
386 }
387 }
388 }
389 Err(Error::UnknownUnit(name.to_string()))
390}
391
392fn unit_base(name: &str) -> Result<(Dim, f64), Error> {
393 let d = |a: [i16; 7]| Dim::from_exponents(a);
395 let one = |a: [i16; 7]| (d(a), 1.0f64);
396 Ok(match name {
397 "kg" => one([1, 0, 0, 0, 0, 0, 0]),
400 "g" => (d([1, 0, 0, 0, 0, 0, 0]), 1e-3),
401 "m" => one([0, 1, 0, 0, 0, 0, 0]),
402 "s" => one([0, 0, 1, 0, 0, 0, 0]),
403 "A" => one([0, 0, 0, 1, 0, 0, 0]),
404 "K" => one([0, 0, 0, 0, 1, 0, 0]),
405 "mol" => one([0, 0, 0, 0, 0, 1, 0]),
406 "cd" => one([0, 0, 0, 0, 0, 0, 1]),
407 "V" => one([1, 2, -3, -1, 0, 0, 0]),
408 "N" => one([1, 1, -2, 0, 0, 0, 0]),
409 "J" => one([1, 2, -2, 0, 0, 0, 0]),
410 "W" => one([1, 2, -3, 0, 0, 0, 0]),
411 "C" => one([0, 0, 1, 1, 0, 0, 0]),
412 "Pa" => one([1, -1, -2, 0, 0, 0, 0]),
413 "Hz" => one([0, 0, -1, 0, 0, 0, 0]),
414 "F" => one([-1, -2, 4, 2, 0, 0, 0]),
416 "\u{03a9}" | "ohm" => one([1, 2, -3, -2, 0, 0, 0]),
417 "S" => one([-1, -2, 3, 2, 0, 0, 0]),
418 "H" => one([1, 2, -2, -2, 0, 0, 0]),
419 "Wb" => one([1, 2, -2, -1, 0, 0, 0]),
420 "T" => one([1, 0, -2, -1, 0, 0, 0]),
421 "rad" | "1" | "sr" => (Dim::ZERO, 1.0),
422 "min" => (d([0, 0, 1, 0, 0, 0, 0]), 60.0),
425 "h" => (d([0, 0, 1, 0, 0, 0, 0]), 3600.0),
426 "d" => (d([0, 0, 1, 0, 0, 0, 0]), 86400.0),
427 "L" | "l" => (d([0, 3, 0, 0, 0, 0, 0]), 1e-3),
428 "deg" => (Dim::ZERO, core::f64::consts::PI / 180.0),
429 "arcmin" => (Dim::ZERO, core::f64::consts::PI / 10_800.0),
430 "arcsec" => (Dim::ZERO, core::f64::consts::PI / 648_000.0),
431 "bar" => (d([1, -1, -2, 0, 0, 0, 0]), 1e5),
432 "atm" => (d([1, -1, -2, 0, 0, 0, 0]), 101_325.0),
433 "eV" => (d([1, 2, -2, 0, 0, 0, 0]), 1.602_176_634e-19),
434 "Wh" => (d([1, 2, -2, 0, 0, 0, 0]), 3600.0),
435 "tonne" => (d([1, 0, 0, 0, 0, 0, 0]), 1000.0),
436 "Da" | "u" => (d([1, 0, 0, 0, 0, 0, 0]), 1.660_539_068_92e-27),
437 "nmi" => (d([0, 1, 0, 0, 0, 0, 0]), 1852.0),
438 "knot" => (d([0, 1, -1, 0, 0, 0, 0]), 1852.0 / 3600.0),
439 "ha" => (d([0, 2, 0, 0, 0, 0, 0]), 1e4),
440 "acre" => (d([0, 2, 0, 0, 0, 0, 0]), 4_046.856_422_4),
441 other => return Err(Error::UnknownUnit(other.to_string())),
442 })
443}
444
445fn parse_ratio(s: &str) -> Result<(i32, i32), Error> {
447 let (n, d) = match s.trim().split_once('/') {
448 Some((n, d)) => (n, d),
449 None => (s.trim(), "1"),
450 };
451 let n: i32 = n.trim().parse().map_err(|_| {
452 Error::MalformedUnit(
453 s.trim().to_string(),
454 "exponent numerator is not an integer".into(),
455 )
456 })?;
457 let d: i32 = d.trim().parse().map_err(|_| {
458 Error::MalformedUnit(
459 s.trim().to_string(),
460 "exponent denominator is not an integer".into(),
461 )
462 })?;
463 if d == 0 {
464 return Err(Error::ExponentZeroDenominator {
465 exponent: s.trim().to_string(),
466 });
467 }
468 Ok((n, d))
469}
470
471pub fn parse_unit(src: &str) -> Result<Dim, Error> {
473 Ok(parse_unit_spec(src)?.dim)
474}
475
476pub fn parse_unit_spec(src: &str) -> Result<UnitSpec, Error> {
479 let src = src.trim();
480 if src.is_empty() {
481 return Err(Error::MalformedUnit(
482 String::new(),
483 "empty unit string".into(),
484 ));
485 }
486 if let Some(c) = src
488 .chars()
489 .find(|c| !c.is_ascii() && !matches!(*c, '\u{00b5}' | '\u{03bc}' | '\u{03a9}' | '\u{00b7}'))
490 {
491 return Err(Error::MalformedUnit(
492 src.to_string(),
493 format!("invalid character `{c}`"),
494 ));
495 }
496 let mut acc = Dim::ZERO;
497 let mut scale = 1.0f64;
498 let mut op = '*';
499 let mut atom = String::new();
500 let flush = |acc: &mut Dim, scale: &mut f64, op: char, atom: &mut String| {
501 if atom.is_empty() {
502 return Err(Error::MalformedUnit(
503 src.to_string(),
504 "empty component".into(),
505 ));
506 }
507 let atom_trimmed = atom.trim().to_string();
513 let (name, p, q) = match atom_trimmed.split_once('^') {
514 Some((n, e)) => {
515 let e = e.trim();
519 let e = e
520 .strip_prefix('(')
521 .and_then(|x| x.strip_suffix(')'))
522 .unwrap_or(e);
523 let (p, q) = parse_ratio(e)?;
524 (n.trim(), p, q)
525 }
526 None => (atom_trimmed.as_str(), 1, 1),
527 };
528 let (d, k) = prefixed_unit(name)?;
529 let d = d.scale_ratio(p, q)?;
530 let k = math::powf(k, p as f64 / q as f64);
532 *acc = if op == '/' {
533 acc.div_dim(d)
534 } else {
535 acc.mul_dim(d)
536 };
537 *scale = if op == '/' { *scale / k } else { *scale * k };
538 atom.clear();
539 Ok(())
540 };
541 let mut depth = 0i32;
542 for c in src.chars() {
543 match c {
544 '(' => {
545 depth += 1;
546 atom.push(c);
547 }
548 ')' => {
549 depth -= 1;
550 if depth < 0 {
551 return Err(Error::MalformedUnit(
552 src.to_string(),
553 "unbalanced `(`".to_string(),
554 ));
555 }
556 atom.push(c);
557 }
558 '/' | '*' | '\u{00b7}' if depth == 0 => {
562 flush(&mut acc, &mut scale, op, &mut atom)?;
563 op = if c == '/' { '/' } else { '*' };
564 }
565 _ => atom.push(c),
566 }
567 }
568 if depth != 0 {
569 return Err(Error::MalformedUnit(
570 src.to_string(),
571 "unbalanced `(`".to_string(),
572 ));
573 }
574 flush(&mut acc, &mut scale, op, &mut atom)?;
575 Ok(UnitSpec { dim: acc, scale })
576}
577
578pub fn convert(value: f64, from: &str, to: &str) -> Result<f64, Error> {
585 let a = parse_unit_spec(from)?;
586 let b = parse_unit_spec(to)?;
587 if a.dim != b.dim {
588 return Err(Error::IncompatibleUnits {
589 from: from.to_string(),
590 to: to.to_string(),
591 from_dim: a.dim.display().to_string(),
592 to_dim: b.dim.display().to_string(),
593 });
594 }
595 Ok(value * a.scale / b.scale)
596}
597
598#[derive(Clone, Copy, Debug, PartialEq)]
608struct Rat(i128, i128);
609
610impl Rat {
611 fn new(n: i128, d: i128) -> Rat {
612 assert!(d != 0, "有理数分母为零");
613 let g = gcd(n, d);
614 let (n, d) = (n / g, d / g);
615 if d < 0 {
616 Rat(-n, -d)
617 } else {
618 Rat(n, d)
619 }
620 }
621 fn zero() -> Rat {
622 Rat(0, 1)
623 }
624 fn is_zero(self) -> bool {
625 self.0 == 0
626 }
627 fn sub(self, o: Rat) -> Rat {
628 Rat::new(self.0 * o.1 - o.0 * self.1, self.1 * o.1)
629 }
630 fn mul(self, o: Rat) -> Rat {
631 Rat::new(self.0 * o.0, self.1 * o.1)
632 }
633 fn div(self, o: Rat) -> Rat {
634 Rat::new(self.0 * o.1, self.1 * o.0)
635 }
636 fn to_f64(self) -> f64 {
637 self.0 as f64 / self.1 as f64
638 }
639}
640
641#[cfg(test)]
642fn contains_pow_of(e: &Expr, name: &str, k: f64) -> bool {
643 match e {
644 Expr::Pow(a, b) => {
645 (matches!(a.as_ref(), Expr::Var(n) if n == name)
646 && matches!(b.as_ref(), Expr::Num(v) if *v == k))
647 || contains_pow_of(a, name, k)
648 || contains_pow_of(b, name, k)
649 }
650 Expr::Add(a, b) | Expr::Sub(a, b) | Expr::Mul(a, b) | Expr::Div(a, b) => {
651 contains_pow_of(a, name, k) || contains_pow_of(b, name, k)
652 }
653 Expr::Neg(a)
654 | Expr::Transpose(a)
655 | Expr::Grad(a)
656 | Expr::Laplacian(a)
657 | Expr::Deriv(a, _) => contains_pow_of(a, name, k),
658 Expr::Call(_, args) => args.iter().any(|a| contains_pow_of(a, name, k)),
659 Expr::Mat(rows) => rows.iter().flatten().any(|c| contains_pow_of(c, name, k)),
660 Expr::MatPattern(p) => p
661 .elements()
662 .into_iter()
663 .any(|c| contains_pow_of(c, name, k)),
664 Expr::Sum {
665 lower, upper, body, ..
666 }
667 | Expr::Integral {
668 lower, upper, body, ..
669 } => {
670 contains_pow_of(lower, name, k)
671 || contains_pow_of(upper, name, k)
672 || contains_pow_of(body, name, k)
673 }
674 _ => false,
675 }
676}
677
678fn gcd(a: i128, b: i128) -> i128 {
679 let (mut a, mut b) = (a.abs(), b.abs());
680 while b != 0 {
681 let t = a % b;
682 a = b;
683 b = t;
684 }
685 if a == 0 {
686 1
687 } else {
688 a
689 }
690}
691
692fn dim_rat(d: Dim) -> Vec<Rat> {
694 d.0.iter().map(|h| Rat::new(*h as i128, 2)).collect()
695}
696
697#[allow(clippy::needless_range_loop)]
702fn rref_aug(mut a: Vec<Vec<Rat>>) -> (Vec<Vec<Rat>>, Vec<usize>, bool) {
703 let rows = a.len();
704 let cols = a.first().map(|r| r.len()).unwrap_or(0);
705 let mut pivots: Vec<usize> = Vec::new();
706 let mut r = 0usize;
707 for c in 0..cols.saturating_sub(1) {
708 if r == rows {
709 break;
710 }
711 let Some(p) = (r..rows).find(|&i| !a[i][c].is_zero()) else {
712 continue;
713 };
714 a.swap(r, p);
715 let inv = a[r][c];
716 for j in c..cols {
717 a[r][j] = a[r][j].div(inv);
718 }
719 for i in 0..rows {
720 if i != r && !a[i][c].is_zero() {
721 let f = a[i][c];
722 for j in c..cols {
723 let sub = f.mul(a[r][j]);
724 a[i][j] = a[i][j].sub(sub);
725 }
726 }
727 }
728 pivots.push(c);
729 r += 1;
730 }
731 let consistent = !(0..rows).any(|i| {
732 (0..cols.saturating_sub(1)).all(|j| a[i][j].is_zero()) && !a[i][cols - 1].is_zero()
733 });
734 (a, pivots, consistent)
735}
736
737pub fn dimensionless_groups(vars: &[(String, Dim)]) -> Result<Vec<Vec<f64>>, Error> {
746 if vars.is_empty() {
747 return Err(Error::InvalidInput(
748 "dimensionless groups need at least one variable".into(),
749 ));
750 }
751 let n = vars.len();
752 let mut a: Vec<Vec<Rat>> = (0..7)
754 .map(|row| {
755 let mut r: Vec<Rat> = vars.iter().map(|(_, d)| dim_rat(*d)[row]).collect();
756 r.push(Rat::zero());
757 r
758 })
759 .collect();
760 let (red, pivots, _) = rref_aug(core::mem::take(&mut a));
761 let mut basis: Vec<Vec<f64>> = Vec::new();
762 for f in 0..n {
763 if pivots.contains(&f) {
764 continue;
765 }
766 let mut x = vec![0.0f64; n];
768 x[f] = 1.0;
769 for (i, &pc) in pivots.iter().enumerate() {
770 x[pc] = -red[i][f].to_f64();
771 }
772 if x.iter().find(|e| **e != 0.0).is_some_and(|e| *e < 0.0) {
777 for e in x.iter_mut() {
778 *e = -*e;
779 }
780 }
781 basis.push(x);
782 }
783 Ok(basis)
784}
785
786pub fn dim_solve(vars: &[(String, Dim)], target: Dim) -> Result<Vec<f64>, Error> {
794 if vars.is_empty() {
795 return if target.is_zero() {
796 Ok(vec![])
797 } else {
798 Err(Error::InvalidInput(format!(
799 "no variables to form the dimension {}",
800 target.display()
801 )))
802 };
803 }
804 let n = vars.len();
805 let t = dim_rat(target);
806 let a: Vec<Vec<Rat>> = (0..7)
807 .map(|row| {
808 let mut r: Vec<Rat> = vars.iter().map(|(_, d)| dim_rat(*d)[row]).collect();
809 r.push(t[row]);
810 r
811 })
812 .collect();
813 let (red, pivots, consistent) = rref_aug(a);
814 if !consistent {
815 return Err(Error::TargetDimensionUnreachable {
816 target: target.display().to_string(),
817 needed: t.iter().filter(|r| !r.is_zero()).count(),
818 spanned: pivots.len(),
819 });
820 }
821 let mut x = vec![0.0f64; n];
822 for (i, &pc) in pivots.iter().enumerate() {
823 x[pc] = red[i][n].to_f64();
824 }
825 Ok(x)
826}
827
828pub fn pi_text(names: &[String], exps: &[f64]) -> String {
830 let mut parts: Vec<String> = Vec::new();
831 for (n, e) in names.iter().zip(exps) {
832 if *e == 0.0 {
833 continue;
834 }
835 if *e == 1.0 {
836 parts.push(n.clone());
837 } else {
838 parts.push(format!("{n}^{}", fmt_num(*e)));
839 }
840 }
841 if parts.is_empty() {
842 "1".to_string()
843 } else {
844 parts.join("·")
845 }
846}
847pub const MAX_DEPTH: usize = 2048;
862
863pub const MAX_PARSE_NESTING: i32 = 256;
871
872pub const MAX_STEPS: u64 = 10_000_000;
875
876pub fn scan_source(src: &str) -> Result<(), FrontError> {
884 let mut depth = 0i32;
888 for (i, c) in src.char_indices() {
889 match c {
890 '(' | '[' | '{' => {
891 depth += 1;
892 if depth > MAX_PARSE_NESTING {
893 let (line, col) = line_col_at(src, i);
894 return Err(FrontError::coded(
895 i18n::Error::NestingTooDeep {
896 got: depth.to_string(),
897 limit: MAX_PARSE_NESTING.to_string(),
898 },
899 &[],
900 line,
901 col,
902 ));
903 }
904 }
905 ')' | ']' | '}' => depth -= 1,
906 _ => {}
907 }
908 }
909 for (i, c) in src.char_indices() {
910 let forbidden = match c {
911 '\u{0000}' => Some("NUL"),
912 '\u{0009}' | '\u{000a}' | '\u{000d}' => None, c if (c as u32) < 0x20 => Some("control character"),
914 '\u{200b}'..='\u{200f}' => Some("zero-width character"),
915 '\u{2028}' | '\u{2029}' => Some("line/paragraph separator"),
916 '\u{202a}'..='\u{202e}' => Some("bidirectional override"),
917 '\u{2060}'..='\u{2064}' => Some("invisible joiner"),
918 '\u{feff}' => Some("byte order mark"),
919 _ => None,
920 };
921 if let Some(kind) = forbidden {
922 let (line, col) = line_col_at(src, i);
923 let hex = format!("{:04X}", c as u32);
924 return Err(FrontError::coded(
925 i18n::Error::InvisibleCharacter(format!("{hex} ({kind})")),
926 &[],
927 line,
928 col,
929 ));
930 }
931 }
932 Ok(())
933}
934
935fn line_col_at(src: &str, byte: usize) -> (usize, usize) {
936 let mut line = 1usize;
937 let mut col = 1usize;
938 for (i, c) in src.char_indices() {
939 if i >= byte {
940 break;
941 }
942 if c == '\n' {
943 line += 1;
944 col = 1;
945 } else {
946 col += 1;
947 }
948 }
949 (line, col)
950}
951
952pub fn depth_of(e: &Expr) -> usize {
954 let kids: Vec<&Expr> = match e {
955 Expr::Num(_) | Expr::Var(_) | Expr::Indexed { .. } => Vec::new(),
956 Expr::Add(a, b) | Expr::Sub(a, b) | Expr::Mul(a, b) | Expr::Div(a, b) | Expr::Pow(a, b) => {
957 vec![a, b]
958 }
959 Expr::Neg(a)
960 | Expr::Transpose(a)
961 | Expr::Grad(a)
962 | Expr::Laplacian(a)
963 | Expr::Deriv(a, _) => {
964 vec![a]
965 }
966 Expr::Call(_, args) => args.iter().collect(),
967 Expr::Mat(rows) => rows.iter().flatten().collect(),
968 Expr::MatPattern(p) => p.elements(),
969 Expr::Sum {
970 lower, upper, body, ..
971 }
972 | Expr::Integral {
973 lower, upper, body, ..
974 } => vec![lower, upper, body],
975 };
976 1 + kids.into_iter().map(depth_of).max().unwrap_or(0)
977}
978
979pub fn check_set_depth(set: &FormulaSet) -> Result<(), FrontError> {
982 if set.items.is_empty() {
986 return Err(FrontError::plain(Error::EmptyFormula));
987 }
988 let runtime_shapes = runtime::shapes_of_set(set).map_err(FrontError::from)?;
989 for item in &set.items {
990 check_depth(&item.expr).map_err(FrontError::from)?;
991 check_calls_with_shapes(&item.expr, &runtime_shapes).map_err(FrontError::from)?;
992 }
993 Ok(())
994}
995
996pub fn check_decl_names(set: &FormulaSet) -> Result<(), FrontError> {
999 const RESERVED: &[&str] = &["j"];
1000 for d in &set.decls {
1001 if func_arity(&d.name).is_some() {
1002 return Err(FrontError::plain(Error::ReservedName {
1005 name: d.name.clone(),
1006 reason: i18n::ReservedReason::BuiltinFunction,
1007 }));
1008 }
1009 if RESERVED.contains(&d.name.as_str()) {
1010 return Err(FrontError::plain(Error::ReservedName {
1011 name: d.name.clone(),
1012 reason: i18n::ReservedReason::ImaginaryUnit,
1013 }));
1014 }
1015 }
1016 Ok(())
1017}
1018
1019pub fn check_depth(e: &Expr) -> Result<(), Error> {
1022 let d = depth_of(e);
1023 if d > MAX_DEPTH {
1024 return Err(Error::NestingTooDeep {
1025 got: d.to_string(),
1026 limit: MAX_DEPTH.to_string(),
1027 });
1028 }
1029 Ok(())
1030}
1031
1032#[derive(Clone, Debug, PartialEq)]
1035pub enum Expr {
1036 Num(f64),
1037 Var(String),
1038 Add(Box<Expr>, Box<Expr>),
1039 Sub(Box<Expr>, Box<Expr>),
1040 Mul(Box<Expr>, Box<Expr>),
1041 Div(Box<Expr>, Box<Expr>),
1042 Pow(Box<Expr>, Box<Expr>),
1043 Neg(Box<Expr>),
1044 Call(String, Vec<Expr>),
1045 Mat(Vec<Vec<Expr>>),
1046 MatPattern(MatPattern),
1051 Transpose(Box<Expr>),
1053 Deriv(Box<Expr>, String),
1055 Grad(Box<Expr>),
1057 Laplacian(Box<Expr>),
1059 Sum {
1061 var: String,
1062 lower: Box<Expr>,
1063 upper: Box<Expr>,
1064 body: Box<Expr>,
1065 },
1066 Integral {
1069 var: String,
1070 lower: Box<Expr>,
1071 upper: Box<Expr>,
1072 body: Box<Expr>,
1073 },
1074 Indexed {
1076 name: String,
1077 indices: Vec<String>,
1078 },
1079}
1080
1081#[derive(Clone, Debug, PartialEq)]
1084pub enum PatternCell {
1085 El(Expr),
1086 Dots,
1087}
1088
1089#[derive(Clone, Debug, PartialEq)]
1090pub struct MatPattern {
1091 pub rows: Vec<Vec<PatternCell>>,
1092}
1093
1094impl MatPattern {
1095 pub fn elements(&self) -> Vec<&Expr> {
1097 self.rows
1098 .iter()
1099 .flatten()
1100 .filter_map(|c| match c {
1101 PatternCell::El(e) => Some(e),
1102 PatternCell::Dots => None,
1103 })
1104 .collect()
1105 }
1106
1107 pub fn grid(&self) -> Option<(usize, usize)> {
1108 let cols = self.rows.first()?.len();
1109 if self.rows.iter().all(|r| r.len() == cols) {
1110 Some((self.rows.len(), cols))
1111 } else {
1112 None
1113 }
1114 }
1115}
1116
1117#[derive(Clone, Debug, PartialEq)]
1122pub enum MatrixKind {
1123 Identity,
1125 Diag(Expr),
1127 DiagVec(String),
1129 Tridiag { a: Expr, b: Expr, c: Expr },
1131 TridiagVec { a: Expr, name: String, c: Expr },
1133 BidiagUpper { b: Expr, c: Expr },
1135 BidiagLower { a: Expr, b: Expr },
1137 BlockDiag2 { p: Expr, q: Expr },
1140 Banded { v: Expr, half_band: usize },
1144}
1145
1146fn as_indexed(e: &Expr) -> Option<(&str, &str)> {
1148 match e {
1149 Expr::Indexed { name, indices } if indices.len() == 1 => {
1150 Some((name.as_str(), indices[0].as_str()))
1151 }
1152 _ => None,
1153 }
1154}
1155
1156fn indexed_diag(cells: &[&Expr]) -> Option<String> {
1159 let mut name: Option<&str> = None;
1160 let mut letters: Option<&str> = None;
1161 let mut nums: Vec<&str> = Vec::new();
1162 for c in cells {
1163 let (n, idx) = as_indexed(c)?;
1164 match name {
1165 None => name = Some(n),
1166 Some(prev) if prev == n => {}
1167 _ => return None,
1168 }
1169 if idx.chars().all(|ch| ch.is_ascii_digit()) {
1170 if nums.contains(&idx) {
1171 return None;
1172 }
1173 nums.push(idx);
1174 } else if idx.chars().all(|ch| ch.is_ascii_alphabetic()) {
1175 match letters {
1176 None => letters = Some(idx),
1177 Some(prev) if prev == idx => {}
1178 _ => return None,
1179 }
1180 } else {
1181 return None;
1182 }
1183 }
1184 if letters.is_some() && !nums.is_empty() {
1185 return None;
1186 }
1187 name.map(|n| n.to_string())
1188}
1189
1190pub fn num(v: f64) -> Expr {
1191 Expr::Num(v)
1192}
1193pub fn var(s: impl Into<String>) -> Expr {
1194 Expr::Var(s.into())
1195}
1196pub fn add(a: Expr, b: Expr) -> Expr {
1197 Expr::Add(Box::new(a), Box::new(b))
1198}
1199pub fn sub(a: Expr, b: Expr) -> Expr {
1200 Expr::Sub(Box::new(a), Box::new(b))
1201}
1202pub fn mul(a: Expr, b: Expr) -> Expr {
1203 Expr::Mul(Box::new(a), Box::new(b))
1204}
1205pub fn div(a: Expr, b: Expr) -> Expr {
1206 Expr::Div(Box::new(a), Box::new(b))
1207}
1208pub fn pow(a: Expr, b: Expr) -> Expr {
1209 Expr::Pow(Box::new(a), Box::new(b))
1210}
1211pub fn neg(a: Expr) -> Expr {
1212 Expr::Neg(Box::new(a))
1213}
1214pub fn transpose(a: Expr) -> Expr {
1215 match a {
1220 Expr::Num(_) => a,
1221 other => Expr::Transpose(Box::new(other)),
1222 }
1223}
1224pub fn deriv(u: Expr, by: impl Into<String>) -> Expr {
1225 Expr::Deriv(Box::new(u), by.into())
1226}
1227pub fn grad(u: Expr) -> Expr {
1228 Expr::Grad(Box::new(u))
1229}
1230pub fn laplacian(u: Expr) -> Expr {
1231 Expr::Laplacian(Box::new(u))
1232}
1233pub fn sum(var: impl Into<String>, lower: Expr, upper: Expr, body: Expr) -> Expr {
1234 Expr::Sum {
1235 var: var.into(),
1236 lower: Box::new(lower),
1237 upper: Box::new(upper),
1238 body: Box::new(body),
1239 }
1240}
1241pub fn integral(var: impl Into<String>, lower: Expr, upper: Expr, body: Expr) -> Expr {
1242 Expr::Integral {
1243 var: var.into(),
1244 lower: Box::new(lower),
1245 upper: Box::new(upper),
1246 body: Box::new(body),
1247 }
1248}
1249pub fn indexed(name: impl Into<String>, indices: Vec<String>) -> Expr {
1250 Expr::Indexed {
1251 name: name.into(),
1252 indices,
1253 }
1254}
1255
1256#[derive(Clone, Debug, Default, PartialEq)]
1261pub struct FormulaSet {
1262 pub decls: Vec<Decl>,
1263 pub items: Vec<FormulaItem>,
1264 pub uses: Vec<String>,
1268}
1269
1270#[derive(Clone, Debug, PartialEq)]
1271pub struct FormulaItem {
1272 pub name: Option<String>,
1273 pub expr: Expr,
1274 pub line: usize,
1277}
1278
1279impl FormulaSet {
1280 pub fn single(&self) -> Result<&Expr, Error> {
1283 match self.items.as_slice() {
1284 [one] => Ok(&one.expr),
1285 _ => Err(Error::ExpectedSingleFormula {
1286 got: self.items.len(),
1287 }),
1288 }
1289 }
1290
1291 pub fn into_single(self) -> (Vec<Decl>, Expr) {
1295 let expr = self
1296 .items
1297 .last()
1298 .map(|i| i.expr.clone())
1299 .expect("FormulaSet 至少一条(parse 保证)");
1300 (self.decls, expr)
1301 }
1302}
1303
1304pub fn subst(e: &Expr, name: &str, by: &Expr) -> Expr {
1307 match e {
1308 Expr::Num(_) => e.clone(),
1309 Expr::Var(n) => {
1310 if n == name {
1311 by.clone()
1312 } else {
1313 e.clone()
1314 }
1315 }
1316 Expr::Add(a, b) => add(subst(a, name, by), subst(b, name, by)),
1317 Expr::Sub(a, b) => sub(subst(a, name, by), subst(b, name, by)),
1318 Expr::Mul(a, b) => mul(subst(a, name, by), subst(b, name, by)),
1319 Expr::Div(a, b) => div(subst(a, name, by), subst(b, name, by)),
1320 Expr::Pow(a, b) => pow(subst(a, name, by), subst(b, name, by)),
1321 Expr::Neg(a) => neg(subst(a, name, by)),
1322 Expr::Call(n, args) => {
1323 Expr::Call(n.clone(), args.iter().map(|a| subst(a, name, by)).collect())
1324 }
1325 Expr::Mat(rows) => Expr::Mat(
1326 rows.iter()
1327 .map(|r| r.iter().map(|c| subst(c, name, by)).collect())
1328 .collect(),
1329 ),
1330 Expr::MatPattern(p) => Expr::MatPattern(MatPattern {
1331 rows: p
1332 .rows
1333 .iter()
1334 .map(|r| {
1335 r.iter()
1336 .map(|c| match c {
1337 PatternCell::El(e) => PatternCell::El(subst(e, name, by)),
1338 PatternCell::Dots => PatternCell::Dots,
1339 })
1340 .collect()
1341 })
1342 .collect(),
1343 }),
1344 Expr::Transpose(a) => transpose(subst(a, name, by)),
1345 Expr::Deriv(u, by_var) => deriv(subst(u, name, by), by_var.clone()),
1346 Expr::Grad(u) => grad(subst(u, name, by)),
1347 Expr::Laplacian(u) => laplacian(subst(u, name, by)),
1348 Expr::Sum {
1349 var,
1350 lower,
1351 upper,
1352 body,
1353 } => sum(
1354 var.clone(),
1355 subst(lower, name, by),
1356 subst(upper, name, by),
1357 subst(body, name, by),
1358 ),
1359 Expr::Integral {
1360 var,
1361 lower,
1362 upper,
1363 body,
1364 } => integral(
1365 var.clone(),
1366 subst(lower, name, by),
1367 subst(upper, name, by),
1368 subst(body, name, by),
1369 ),
1370 Expr::Indexed { name: n, indices } => indexed(
1371 if n == name {
1372 by_var_name(by)
1373 } else {
1374 n.clone()
1375 },
1376 indices.clone(),
1377 ),
1378 }
1379}
1380
1381fn by_var_name(by: &Expr) -> String {
1384 match by {
1385 Expr::Var(n) => n.clone(),
1386 other => format!("__sub_{:x}", other as *const _ as usize),
1387 }
1388}
1389
1390pub fn dims_of_set(set: &FormulaSet) -> Result<HashMap<String, Dim>, Error> {
1394 let declared_dims = dims_of(&set.decls)?;
1395 let runtime_shapes = runtime::shapes_of_set(set)?;
1396 let mut dims = declared_dims.clone();
1397 let mut item_names = BTreeSet::new();
1403 for item in &set.items {
1404 let Some(name) = &item.name else { continue };
1405 if !item_names.insert(name) {
1406 return Err(Error::DuplicateDeclaration {
1407 name: name.clone(),
1408 line: Some(item.line),
1409 });
1410 }
1411 }
1412 let items = federate_inline(set)?;
1417 for item in &items {
1418 if let Some(name) = &item.name {
1419 let d = runtime::dim_check_runtime(&simplify(&item.expr), &dims, &runtime_shapes)?;
1421 if let Some(declared) = declared_dims.get(name) {
1422 if declared != &d {
1423 return Err(Error::ResultDimensionMismatch {
1424 name: name.clone(),
1425 got: d.display(),
1426 declared: declared.display(),
1427 line: item.line,
1428 });
1429 }
1430 }
1431 dims.insert(name.clone(), d);
1432 }
1433 }
1434 Ok(dims)
1435}
1436
1437pub fn federate_inline(set: &FormulaSet) -> Result<Vec<FormulaItem>, Error> {
1442 let mut acc: Vec<(String, Expr)> = Vec::new();
1443 let mut out = Vec::new();
1444 for item in &set.items {
1445 let mut e = item.expr.clone();
1446 for (n, v) in &acc {
1447 e = subst(&e, n, v);
1448 }
1449 e = simplify(&e);
1450 if let Some(n) = &item.name {
1451 acc.push((n.clone(), e.clone()));
1452 }
1453 out.push(FormulaItem {
1454 name: item.name.clone(),
1455 expr: e,
1456 line: item.line,
1457 });
1458 }
1459 Ok(out)
1460}
1461
1462pub fn eval(e: &Expr, env: &HashMap<String, f64>) -> Result<f64, Error> {
1465 let v = eval_value(e, env)?;
1466 let c = v.as_scalar().ok_or_else(|| {
1467 Error::MatrixScalarMix("scalar evaluation met a matrix; use eval_value".into())
1468 })?;
1469 if !c.is_real() {
1470 return Err(Error::ComplexEvalResult { re: c.re, im: c.im });
1471 }
1472 Ok(c.re)
1473}
1474
1475pub fn params_in_decl_order(decls: &[Decl], e: &Expr) -> Vec<String> {
1483 let j_reserved = !decls.iter().any(|d| d.name == "j");
1488 let used: Vec<String> = vars_of(e)
1489 .into_iter()
1490 .filter(|n| !(j_reserved && n == "j"))
1491 .collect();
1492 let mut out: Vec<String> = decls
1493 .iter()
1494 .map(|d| d.name.clone())
1495 .filter(|n| used.contains(n))
1496 .collect();
1497 for u in used {
1498 if !out.contains(&u) {
1499 out.push(u);
1500 }
1501 }
1502 out
1503}
1504
1505pub fn vars_of(e: &Expr) -> Vec<String> {
1506 fn go(e: &Expr, out: &mut Vec<String>) {
1507 match e {
1508 Expr::Num(_) => {}
1509 Expr::Var(n) => {
1510 if !out.contains(n) {
1511 out.push(n.clone());
1512 }
1513 }
1514 Expr::Add(a, b)
1515 | Expr::Sub(a, b)
1516 | Expr::Mul(a, b)
1517 | Expr::Div(a, b)
1518 | Expr::Pow(a, b) => {
1519 go(a, out);
1520 go(b, out);
1521 }
1522 Expr::Neg(a) => go(a, out),
1523 Expr::Call(_, args) => {
1524 for a in args {
1525 go(a, out);
1526 }
1527 }
1528 Expr::Mat(rows) => {
1529 for r in rows {
1530 for c in r {
1531 go(c, out);
1532 }
1533 }
1534 }
1535 Expr::MatPattern(p) => {
1536 for e in p.elements() {
1537 go(e, out);
1538 }
1539 }
1540 Expr::Transpose(a) => go(a, out),
1541 Expr::Deriv(u, by) => {
1542 go(u, out);
1543 let _ = by; }
1545 Expr::Grad(u) | Expr::Laplacian(u) => go(u, out),
1546 Expr::Sum {
1547 var,
1548 lower,
1549 upper,
1550 body,
1551 } => {
1552 go(lower, out);
1553 go(upper, out);
1554 go(body, out);
1555 out.retain(|n| n != var); }
1557 Expr::Integral {
1558 var,
1559 lower,
1560 upper,
1561 body,
1562 } => {
1563 go(lower, out);
1564 go(upper, out);
1565 go(body, out);
1566 out.retain(|n| n != var); }
1568 Expr::Indexed { name, indices } => {
1569 let mut item = name.clone();
1572 item.push_str("__idx");
1573 let _ = item;
1574 if !out.contains(name) {
1575 out.push(name.clone());
1576 }
1577 for i in indices {
1578 if i.parse::<usize>().is_err() && !out.contains(i) {
1581 out.push(i.clone());
1582 }
1583 }
1584 }
1585 }
1586 }
1587 let mut out = Vec::new();
1588 go(e, &mut out);
1589 out.sort();
1590 out
1591}
1592
1593pub fn simplify(e: &Expr) -> Expr {
1596 let e = match e {
1597 Expr::Num(_) | Expr::Var(_) => e.clone(),
1598 Expr::Add(a, b) => add(simplify(a), simplify(b)),
1599 Expr::Sub(a, b) => sub(simplify(a), simplify(b)),
1600 Expr::Mul(a, b) => mul(simplify(a), simplify(b)),
1601 Expr::Div(a, b) => div(simplify(a), simplify(b)),
1602 Expr::Pow(a, b) => pow(simplify(a), simplify(b)),
1603 Expr::Neg(a) => neg(simplify(a)),
1604 Expr::Call(n, args) => Expr::Call(n.clone(), args.iter().map(simplify).collect()),
1605 Expr::Mat(rows) => Expr::Mat(
1606 rows.iter()
1607 .map(|r| r.iter().map(simplify).collect())
1608 .collect(),
1609 ),
1610 Expr::MatPattern(p) => Expr::MatPattern(MatPattern {
1611 rows: p
1612 .rows
1613 .iter()
1614 .map(|r| {
1615 r.iter()
1616 .map(|c| match c {
1617 PatternCell::El(e) => PatternCell::El(simplify(e)),
1618 PatternCell::Dots => PatternCell::Dots,
1619 })
1620 .collect()
1621 })
1622 .collect(),
1623 }),
1624 Expr::Transpose(a) => transpose(simplify(a)),
1625 Expr::Deriv(u, by) => deriv(simplify(u), by.clone()),
1626 Expr::Grad(u) => grad(simplify(u)),
1627 Expr::Laplacian(u) => laplacian(simplify(u)),
1628 Expr::Sum {
1629 var,
1630 lower,
1631 upper,
1632 body,
1633 } => sum(
1634 var.clone(),
1635 simplify(lower),
1636 simplify(upper),
1637 simplify(body),
1638 ),
1639 Expr::Integral {
1640 var,
1641 lower,
1642 upper,
1643 body,
1644 } => integral(
1645 var.clone(),
1646 simplify(lower),
1647 simplify(upper),
1648 simplify(body),
1649 ),
1650 Expr::Indexed { name, indices } => indexed(name.clone(), indices.clone()),
1651 };
1652 fold_const(&e)
1653}
1654
1655fn fold_const(e: &Expr) -> Expr {
1656 let z = |x: &Expr| matches!(x, Expr::Num(v) if *v == 0.0);
1657 let one = |x: &Expr| matches!(x, Expr::Num(v) if *v == 1.0);
1658 match e {
1659 Expr::Neg(a) => match a.as_ref() {
1660 Expr::Num(v) => num(-*v),
1661 Expr::Neg(b) => (**b).clone(),
1662 _ => neg((**a).clone()),
1663 },
1664 Expr::Add(a, b) => {
1665 if let (Expr::Num(x), Expr::Num(y)) = (a.as_ref(), b.as_ref()) {
1666 return num(x + y);
1667 }
1668 if z(a) {
1669 return (**b).clone();
1670 }
1671 if z(b) {
1672 return (**a).clone();
1673 }
1674 add((**a).clone(), (**b).clone())
1675 }
1676 Expr::Sub(a, b) => {
1677 if let (Expr::Num(x), Expr::Num(y)) = (a.as_ref(), b.as_ref()) {
1678 return num(x - y);
1679 }
1680 if z(b) {
1681 return (**a).clone();
1682 }
1683 if z(a) {
1684 return neg((**b).clone());
1685 }
1686 sub((**a).clone(), (**b).clone())
1687 }
1688 Expr::Mul(a, b) => {
1689 if let (Expr::Num(x), Expr::Num(y)) = (a.as_ref(), b.as_ref()) {
1690 return num(x * y);
1691 }
1692 if z(a) || z(b) {
1693 return num(0.0);
1694 }
1695 if one(a) {
1696 return (**b).clone();
1697 }
1698 if one(b) {
1699 return (**a).clone();
1700 }
1701 if let Expr::Num(v) = a.as_ref() {
1702 if *v == -1.0 {
1703 return neg((**b).clone());
1704 }
1705 }
1706 mul((**a).clone(), (**b).clone())
1707 }
1708 Expr::Div(a, b) => {
1709 if let (Expr::Num(x), Expr::Num(y)) = (a.as_ref(), b.as_ref()) {
1710 return num(x / y);
1711 }
1712 if z(a) {
1713 return num(0.0);
1714 }
1715 if one(b) {
1716 return (**a).clone();
1717 }
1718 div((**a).clone(), (**b).clone())
1719 }
1720 Expr::Pow(a, b) => {
1721 if let (Expr::Num(x), Expr::Num(y)) = (a.as_ref(), b.as_ref()) {
1722 if *x < 0.0 && math::fract(*y) != 0.0 {
1729 return e.clone();
1730 }
1731 return num(math::powf(*x, *y));
1732 }
1733 if let Expr::Num(y) = b.as_ref() {
1734 if *y == 1.0 {
1735 return (**a).clone();
1736 }
1737 if *y == 0.0 && !matrix_ish(a) {
1738 return num(1.0);
1739 }
1740 }
1741 pow((**a).clone(), (**b).clone())
1742 }
1743 _ => e.clone(),
1744 }
1745}
1746
1747#[derive(Clone, Copy, Debug, Default, PartialEq)]
1759pub struct C {
1760 pub re: f64,
1761 pub im: f64,
1762}
1763
1764#[allow(clippy::should_implement_trait)]
1771impl C {
1772 pub const ZERO: C = C { re: 0.0, im: 0.0 };
1773 pub const ONE: C = C { re: 1.0, im: 0.0 };
1774 pub const I: C = C { re: 0.0, im: 1.0 };
1776
1777 pub const fn new(re: f64, im: f64) -> Self {
1778 C { re, im }
1779 }
1780
1781 pub const fn real(re: f64) -> Self {
1783 C { re, im: 0.0 }
1784 }
1785
1786 pub fn is_real(self) -> bool {
1788 self.im == 0.0
1789 }
1790
1791 pub fn add(self, o: C) -> C {
1792 C::new(self.re + o.re, self.im + o.im)
1793 }
1794 pub fn sub(self, o: C) -> C {
1795 C::new(self.re - o.re, self.im - o.im)
1796 }
1797 pub fn neg(self) -> C {
1798 C::new(-self.re, -self.im)
1799 }
1800 pub fn mul(self, o: C) -> C {
1801 C::new(
1802 self.re * o.re - self.im * o.im,
1803 self.re * o.im + self.im * o.re,
1804 )
1805 }
1806 pub fn div(self, o: C) -> Result<C, Error> {
1821 if o.is_real() {
1822 if o.re == 0.0 {
1823 return Err(Error::DivisionByZero);
1824 }
1825 return Ok(C::new(self.re / o.re, self.im / o.re));
1826 }
1827 if o.re.abs() >= o.im.abs() {
1828 let r = o.im / o.re;
1829 let den = o.re + o.im * r;
1830 if den == 0.0 {
1831 return Err(Error::DivisionByZero);
1832 }
1833 Ok(C::new(
1834 (self.re + self.im * r) / den,
1835 (self.im - self.re * r) / den,
1836 ))
1837 } else {
1838 let r = o.re / o.im;
1839 let den = o.re * r + o.im;
1840 if den == 0.0 {
1841 return Err(Error::DivisionByZero);
1842 }
1843 Ok(C::new(
1844 (self.re * r + self.im) / den,
1845 (self.im * r - self.re) / den,
1846 ))
1847 }
1848 }
1849
1850 pub fn abs(self) -> f64 {
1852 math::hypot(self.re, self.im)
1853 }
1854 pub fn arg(self) -> f64 {
1856 math::atan2(self.im, self.re)
1857 }
1858 pub fn conj(self) -> C {
1859 C::new(self.re, -self.im)
1860 }
1861 pub fn exp(self) -> C {
1865 if self.is_real() {
1866 return C::real(math::exp(self.re));
1867 }
1868 let m = math::exp(self.re);
1869 C::new(m * math::cos(self.im), m * math::sin(self.im))
1870 }
1871 pub fn ln(self) -> Result<C, Error> {
1873 if self.re == 0.0 && self.im == 0.0 {
1874 return Err(Error::LogOfZero);
1875 }
1876 Ok(C::new(math::ln(self.abs()), self.arg()))
1877 }
1878
1879 pub fn pow_real(self, p: f64) -> C {
1885 if !p.is_finite() {
1889 return C::real(f64::NAN);
1890 }
1891 if self.is_real() {
1892 if p == math::trunc(p) && p.abs() <= i32::MAX as f64 {
1896 return C::real(math::powi(self.re, p as i32));
1897 }
1898 if self.re >= 0.0 {
1899 return C::real(math::powf(self.re, p));
1900 }
1901 }
1902 let (r, t) = (self.abs(), self.arg());
1903 let m = math::powf(r, p);
1904 let a = t * p;
1905 C::new(m * math::cos(a), m * math::sin(a))
1906 }
1907
1908 pub fn pow(self, o: C) -> Result<C, Error> {
1910 if o.is_real() {
1911 return Ok(self.pow_real(o.re));
1912 }
1913 Ok(o.mul(self.ln()?).exp())
1914 }
1915
1916 pub fn sqrt(self) -> C {
1924 if self.is_real() {
1925 return if self.re >= 0.0 {
1927 C::real(math::sqrt(self.re))
1928 } else {
1929 C::new(0.0, math::sqrt(-self.re))
1930 };
1931 }
1932 let r = self.abs();
1933 let re = math::sqrt(((r + self.re) * 0.5).max(0.0));
1934 let im = math::sqrt(((r - self.re) * 0.5).max(0.0)).copysign(self.im);
1935 C::new(re, im)
1936 }
1937
1938 pub fn sin(self) -> C {
1939 C::new(
1940 math::sin(self.re) * math::cosh(self.im),
1941 math::cos(self.re) * math::sinh(self.im),
1942 )
1943 }
1944 pub fn cos(self) -> C {
1945 C::new(
1946 math::cos(self.re) * math::cosh(self.im),
1947 -math::sin(self.re) * math::sinh(self.im),
1948 )
1949 }
1950 pub fn sinh(self) -> C {
1951 C::new(
1952 math::sinh(self.re) * math::cos(self.im),
1953 math::cosh(self.re) * math::sin(self.im),
1954 )
1955 }
1956 pub fn cosh(self) -> C {
1957 C::new(
1958 math::cosh(self.re) * math::cos(self.im),
1959 math::sinh(self.re) * math::sin(self.im),
1960 )
1961 }
1962 pub fn tan(self) -> Result<C, Error> {
1963 self.sin().div(self.cos())
1964 }
1965 pub fn tanh(self) -> Result<C, Error> {
1966 self.sinh().div(self.cosh())
1967 }
1968}
1969
1970#[derive(Clone, Debug, PartialEq)]
1974pub enum Value {
1975 Scalar(C),
1976 Matrix(Vec<Vec<C>>),
1977}
1978
1979impl Value {
1980 pub fn as_scalar(&self) -> Option<C> {
1982 match self {
1983 Value::Scalar(c) => Some(*c),
1984 Value::Matrix(_) => None,
1985 }
1986 }
1987
1988 pub fn is_complex(&self) -> bool {
1990 match self {
1991 Value::Scalar(c) => !c.is_real(),
1992 Value::Matrix(m) => m.iter().flatten().any(|c| !c.is_real()),
1993 }
1994 }
1995}
1996
1997pub fn shape_of(e: &Expr) -> Result<Option<(usize, usize)>, Error> {
2004 Ok(match e {
2005 Expr::Mat(rows) => {
2006 let cols = rows.first().map(|r| r.len());
2007 if let Some(n) = cols {
2008 if rows.iter().any(|r| r.len() != n) {
2009 return Err(Error::ShapeMismatch("matrix literal rows have different lengths (jagged matrices are not supported)".into()));
2010 }
2011 }
2012 Some((rows.len(), cols.unwrap_or(0)))
2013 }
2014 Expr::MatPattern(_) => None, Expr::Transpose(a) => shape_of(a)?.map(|(m, n)| (n, m)),
2016 _ => None, })
2018}
2019
2020fn matrix_shape(e: &Expr) -> Result<Option<(usize, usize)>, Error> {
2028 if let Some(s) = shape_of(e)? {
2029 return Ok(Some(s));
2030 }
2031 Ok(flatten_matrix_value(e).and_then(|m| {
2032 let rows = m.len();
2033 let cols = m.first().map(|r| r.len())?;
2034 if m.iter().all(|r| r.len() == cols) {
2035 Some((rows, cols))
2036 } else {
2037 None
2038 }
2039 }))
2040}
2041
2042pub fn shape_check(e: &Expr) -> Result<(), Error> {
2043 match e {
2044 Expr::Add(a, b) | Expr::Sub(a, b) => {
2045 shape_check(a)?;
2046 shape_check(b)?;
2047 let (ma, mb) = (is_matrix_value(a), is_matrix_value(b));
2052 let is_zero = |x: &Expr| matches!(simplify(x), Expr::Num(v) if v == 0.0);
2057 if ma != mb {
2058 let scalar_side = if ma { b } else { a };
2059 if !is_zero(scalar_side) {
2060 return Err(Error::MatrixScalarMix(
2061 "matrix vs scalar add/sub: operate element-wise or reshape".to_string(),
2062 ));
2063 }
2064 } else if ma && mb {
2065 let (sa, sb) = (matrix_shape(a)?, matrix_shape(b)?);
2068 if let (Some(sa), Some(sb)) = (sa, sb) {
2069 if sa != sb {
2070 return Err(Error::ShapeMismatch(format!(
2071 "matrix add/sub shapes differ: {sa:?} vs {sb:?}"
2072 )));
2073 }
2074 }
2075 }
2076 Ok(())
2077 }
2078 Expr::Mul(a, b) => {
2079 shape_check(a)?;
2080 shape_check(b)?;
2081 let sa = matrix_shape(a)?;
2088 let sb = matrix_shape(b)?;
2089 match (sa, sb) {
2090 (Some(sa), Some(sb)) => {
2091 if sa.1 != sb.0 {
2092 return Err(Error::ShapeMismatch(format!(
2093 "cannot multiply {sa:?} by {sb:?}: columns of the left operand ≠ rows of the right"
2094 )));
2095 }
2096 }
2097 (Some(_), None) if is_matrix_value(b) => {
2100 return Err(Error::ShapeMismatch(
2101 "one side of the product has a shape unknown at compile time, so it cannot be checked".into(),
2102 ))
2103 }
2104 (None, Some(_)) if is_matrix_value(a) => {
2105 return Err(Error::ShapeMismatch(
2106 "one side of the product has a shape unknown at compile time, so it cannot be checked".into(),
2107 ))
2108 }
2109 _ => {}
2110 }
2111 Ok(())
2112 }
2113 Expr::Div(a, b) => {
2114 shape_check(a)?;
2115 if shape_of(b)?.is_some() {
2118 return Err(Error::MatrixDivisionUnsupported(
2119 "write an explicit inverse (`inv(A) * b`) or use the solver".to_string(),
2120 ));
2121 }
2122 Ok(())
2123 }
2124 Expr::Neg(a) | Expr::Transpose(a) => shape_check(a),
2125 Expr::Deriv(u, _) | Expr::Grad(u) | Expr::Laplacian(u) => shape_check(u),
2126 Expr::Sum {
2127 lower, upper, body, ..
2128 }
2129 | Expr::Integral {
2130 lower, upper, body, ..
2131 } => {
2132 shape_check(lower)?;
2133 shape_check(upper)?;
2134 shape_check(body)
2135 }
2136 Expr::Indexed { .. } => Ok(()), Expr::Pow(a, b) => {
2138 shape_check(a)?;
2139 shape_check(b)
2140 }
2141 Expr::Call(_, args) => {
2142 for a in args {
2143 shape_check(a)?;
2144 }
2145 Ok(())
2146 }
2147 Expr::Mat(rows) => {
2148 shape_of(e)?;
2149 for r in rows {
2150 for c in r {
2151 shape_check(c)?;
2152 }
2153 }
2154 Ok(())
2155 }
2156 Expr::MatPattern(p) => {
2157 p.grid().ok_or_else(|| {
2158 Error::ShapeMismatch("pattern matrix rows have inconsistent lengths".into())
2159 })?;
2160 Ok(())
2161 }
2162 _ => Ok(()),
2163 }
2164}
2165
2166pub fn eval_value(e: &Expr, env: &HashMap<String, f64>) -> Result<Value, Error> {
2169 use Expr as E;
2170 Ok(match e {
2171 E::Num(v) => Value::Scalar(C::real(*v)),
2172 E::Var(n) if n == "j" && !env.contains_key("j") => Value::Scalar(C::I),
2175 E::Var(n) => Value::Scalar(C::real(
2176 *env.get(n).ok_or_else(|| Error::UndeclaredSymbol(n.clone()))?,
2177 )),
2178 E::Neg(a) => match eval_value(a, env)? {
2179 Value::Scalar(c) => Value::Scalar(c.neg()),
2180 Value::Matrix(m) => Value::Matrix(map_mat(&m, |c| c.neg())),
2181 },
2182 E::Add(a, b) => c_bin(a, b, env, |x, y| Ok(x.add(y)))?,
2183 E::Sub(a, b) => c_bin(a, b, env, |x, y| Ok(x.sub(y)))?,
2184 E::Div(a, b) => {
2185 let (va, vb) = (eval_value(a, env)?, eval_value(b, env)?);
2192 match (va, vb) {
2193 (Value::Matrix(m), Value::Scalar(k)) => {
2194 let mut rows = Vec::with_capacity(m.len());
2195 for r in m {
2196 let mut out = Vec::with_capacity(r.len());
2197 for c in r {
2198 out.push(c.div(k)?);
2199 }
2200 rows.push(out);
2201 }
2202 Value::Matrix(rows)
2203 }
2204 (Value::Matrix(_), Value::Matrix(_)) => {
2205 return Err(Error::MatrixDivisionUnsupported("write the explicit inverse (`inv(A) * b`) or use a solver".into()))
2206 }
2207 (Value::Scalar(_), Value::Matrix(_)) => {
2208 return Err(Error::MatrixScalarMix("a scalar divided by a matrix is undefined; write matrix equations as `inv(A) * b`".into()))
2209 }
2210 (x, y) => {
2211 let (Value::Scalar(x), Value::Scalar(y)) = (x, y) else {
2212 unreachable!("上面已排除所有含矩阵的情形")
2213 };
2214 Value::Scalar(x.div(y)?)
2215 }
2216 }
2217 }
2218 E::Pow(a, b) => {
2219 let base_is_matrix =
2222 matches!(a.as_ref(), Expr::Mat(_) | Expr::MatPattern(_)) || is_matrix_value(a);
2223 if base_is_matrix {
2224 let Expr::Num(k) = b.as_ref() else {
2225 return Err(Error::InvalidInput(
2226 "the exponent of a matrix power must be an integer constant".into(),
2227 ));
2228 };
2229 if !(*k >= 0.0 && math::fract(*k) == 0.0 && *k <= 8.0) {
2230 return Err(Error::InvalidInput(format!(
2231 "matrix powers support non-negative integers 0–8, got {k}; write the explicit product or use a numeric library"
2232 )));
2233 }
2234 let mut acc = eval_value(a, env)?;
2235 if *k == 0.0 {
2236 let Value::Matrix(m) = acc else {
2237 return Err(Error::ShapeMismatch(
2238 "the base of a zero matrix power must be a square matrix".into(),
2239 ));
2240 };
2241 if m.iter().any(|r| r.len() != m.len()) {
2242 return Err(Error::ShapeMismatch(
2243 "the base of a zero matrix power must be a square matrix".into(),
2244 ));
2245 }
2246 return Ok(Value::Matrix(
2247 (0..m.len())
2248 .map(|i| {
2249 (0..m.len())
2250 .map(|j| C::real(if i == j { 1.0 } else { 0.0 }))
2251 .collect()
2252 })
2253 .collect(),
2254 ));
2255 }
2256 for _ in 1..(*k as usize) {
2257 acc = mat_mul_value_of(acc, eval_value(a, env)?)?;
2258 }
2259 return Ok(acc);
2260 }
2261 let expo_is_matrix =
2267 matches!(b.as_ref(), Expr::Mat(_) | Expr::MatPattern(_)) || is_matrix_value(b);
2268 if expo_is_matrix {
2269 return Err(Error::MatrixScalarMix(
2270 "a matrix cannot be an exponent".into(),
2271 ));
2272 }
2273 c_bin(a, b, env, |x, y| x.pow(y))?
2274 }
2275 E::Mul(a, b) => {
2276 let (va, vb) = (eval_value(a, env)?, eval_value(b, env)?);
2277 mat_mul_value_of(va, vb)?
2278 }
2279 E::Call(name, args) => {
2280 let Some(arg) = args.first() else {
2281 return Err(Error::InvalidInput(format!("`{name}` needs an argument")));
2285 };
2286 if matches!(name.as_str(), "__quad_root_1" | "__quad_root_2") {
2287 if args.len() != 3 {
2288 return Err(Error::FunctionArity {
2289 name: name.clone(),
2290 expected: 3,
2291 got: args.len(),
2292 });
2293 }
2294 let a = as_c(&eval_value(&args[0], env)?, "the quadratic coefficient")?;
2295 let b = as_c(&eval_value(&args[1], env)?, "the linear coefficient")?;
2296 let c = as_c(&eval_value(&args[2], env)?, "the constant term")?;
2297 return Ok(Value::Scalar(stable_quadratic_root(
2298 name == "__quad_root_1",
2299 a,
2300 b,
2301 c,
2302 )?));
2303 }
2304 if name == "dot" || name == "norm" {
2307 let expanded = expand_call(e).ok_or_else(|| {
2308 Error::InvalidInput(format!(
2309 "`{name}` needs a concrete matrix literal (its shape is unknown at compile time)"
2310 ))
2311 })?;
2312 return eval_value(&expanded, env);
2313 }
2314 if name == "solve" || name == "roots" || name == "poly_coeffs" {
2317 let expanded = expand_call(e).ok_or_else(|| {
2318 Error::InvalidInput(
2319 "`solve` is not applicable here: the second argument must be a variable name and the equations must be linear in it".into(),
2320 )
2321 })?;
2322 let value = eval_value(&expanded, env)?;
2323 if name == "roots" && !uses_complex(e) && value.is_complex() {
2324 return Err(Error::UnsupportedOperation(
2325 "the quadratic has no real roots; write the complex lane explicitly with `j`"
2326 .into(),
2327 ));
2328 }
2329 return Ok(value);
2330 }
2331 if matches!(name.as_str(), "det" | "trace" | "adjoint" | "inv") {
2333 let v = eval_value(arg, env)?;
2334 let m = match v {
2335 Value::Matrix(m) => m,
2336 Value::Scalar(_) => {
2337 return Err(Error::MatrixScalarMix(format!(
2338 "`{name}` needs a matrix argument, got a scalar"
2339 )))
2340 }
2341 };
2342 return match name.as_str() {
2343 "trace" => {
2344 if m.len() != m.first().map(|r| r.len()).unwrap_or(0) {
2345 return Err(Error::ShapeMismatch(
2346 "`trace` needs a square matrix".into(),
2347 ));
2348 }
2349 let mut acc = C::ZERO;
2350 for (i, row) in m.iter().enumerate() {
2351 acc = acc.add(row[i]);
2352 }
2353 Ok(Value::Scalar(acc))
2354 }
2355 "det" => Ok(Value::Scalar(mat_det(&m)?)),
2356 "inv" => {
2362 let expanded = expand_matrix_call(e).ok_or_else(|| {
2363 Error::InvalidInput(
2364 "`inv` supports only square matrices of order 1 to 3 (use a numeric library for larger orders)".into(),
2365 )
2366 })?;
2367 eval_value(&expanded, env)
2368 }
2369 _ => {
2370 let cols = m.first().map(|r| r.len()).unwrap_or(0);
2372 let mut t = vec![vec![C::ZERO; m.len()]; cols];
2373 for (i, row) in m.iter().enumerate() {
2374 for (j, c) in row.iter().enumerate() {
2375 t[j][i] = c.conj();
2376 }
2377 }
2378 Ok(Value::Matrix(t))
2379 }
2380 };
2381 }
2382 if args.len() > 1 {
2383 let mut vals = Vec::with_capacity(args.len());
2384 for a in args {
2385 vals.push(as_c(
2386 &eval_value(a, env)?,
2387 &format!("the argument of `{name}`"),
2388 )?);
2389 }
2390 return Ok(Value::Scalar(c_call_n(name, &vals)?));
2391 }
2392 let c = as_c(&eval_value(arg, env)?, &format!("the argument of `{name}`"))?;
2393 Value::Scalar(c_call(name, c)?)
2394 }
2395 E::Mat(rows) => {
2396 let mut out = Vec::with_capacity(rows.len());
2397 for r in rows {
2398 let mut row = Vec::with_capacity(r.len());
2399 for cell in r {
2400 row.push(as_c(&eval_value(cell, env)?, "a matrix element")?);
2401 }
2402 out.push(row);
2403 }
2404 Value::Matrix(out)
2405 }
2406 E::Transpose(a) => match eval_value(a, env)? {
2407 Value::Matrix(m) => {
2408 if m.is_empty() {
2409 return Ok(Value::Matrix(vec![]));
2410 }
2411 let (r, c) = (m.len(), m[0].len());
2412 let mut t = vec![vec![C::ZERO; r]; c];
2413 for i in 0..r {
2414 for j in 0..c {
2415 t[j][i] = m[i][j];
2416 }
2417 }
2418 Value::Matrix(t)
2419 }
2420 Value::Scalar(_) => {
2421 return Err(Error::MatrixScalarMix(
2422 "a scalar cannot be transposed".into(),
2423 ))
2424 }
2425 },
2426 E::Sum {
2427 var,
2428 lower,
2429 upper,
2430 body,
2431 } => {
2432 let lo = eval_i(lower, env)?;
2433 let hi = eval_i(upper, env)?;
2434 if hi >= lo && (hi - lo) as u64 > MAX_STEPS {
2435 return Err(Error::InvalidInput(format!(
2436 "the sum would take {} steps (limit {MAX_STEPS}); sums are explicit teaching loops, not a numeric library",
2437 hi - lo + 1
2438 )));
2439 }
2440 let mut acc = C::ZERO;
2441 for k in lo..=hi {
2442 let mut inner = env.clone();
2443 inner.insert(var.clone(), k as f64);
2444 acc = acc.add(as_c(&eval_value(body, &inner)?, "the summand")?);
2445 }
2446 Value::Scalar(acc)
2447 }
2448 E::Integral {
2449 var,
2450 lower,
2451 upper,
2452 body,
2453 } => {
2454 let lo = eval(lower, env)?;
2455 let hi = eval(upper, env)?;
2456 let n = 128usize;
2459 let h = (hi - lo) / n as f64;
2460 let f = |x: f64| -> Result<C, Error> {
2461 let mut inner = env.clone();
2462 inner.insert(var.clone(), x);
2463 as_c(&eval_value(body, &inner)?, "the integrand")
2464 };
2465 let mut acc = f(lo)?.add(f(hi)?);
2466 for k in 1..n {
2467 let x = lo + h * k as f64;
2468 let w = if k % 2 == 1 { 4.0 } else { 2.0 };
2469 acc = acc.add(f(x)?.mul(C::real(w)));
2470 }
2471 Value::Scalar(acc.mul(C::real(h / 3.0)))
2472 }
2473 E::Deriv(..) => return Err(Error::UnsupportedOperation(
2474 "`∂` is a symbolic operator: differentiate symbolically first, or use a finite difference".into(),
2475 )),
2476 E::Grad(_) | E::Laplacian(_) => {
2477 return Err(Error::UnsupportedOperation(
2478 "`∇`/`∇²` are symbolic operators: numeric evaluation needs a discretisation (use the code-generation lane)".into(),
2479 ))
2480 }
2481 E::Indexed { .. } => {
2482 return Err(Error::UnsupportedOperation(
2483 "evaluating an indexed symbol needs an index environment, which this version does not provide".into(),
2484 ))
2485 }
2486 E::MatPattern(_) => {
2487 return Err(Error::UnsupportedOperation(
2488 "evaluation does not take pattern matrices (call `recognize_pattern` first, then use the code-generation lane)".into(),
2489 ))
2490 }
2491 })
2492}
2493
2494fn map_mat(m: &[Vec<C>], f: impl Fn(C) -> C) -> Vec<Vec<C>> {
2495 m.iter()
2496 .map(|r| r.iter().map(|c| f(*c)).collect())
2497 .collect()
2498}
2499
2500fn as_c(v: &Value, what: &str) -> Result<C, Error> {
2503 v.as_scalar().ok_or_else(|| {
2504 Error::MatrixScalarMix(format!(
2505 "{what} must be a scalar (write matrices element by element; there is no implicit broadcast)"
2506 ))
2507 })
2508}
2509
2510pub fn func_arity(name: &str) -> Option<usize> {
2518 match name {
2519 "exp" | "ln" | "log" | "sqrt" | "sin" | "cos" | "tan" | "sinh" | "cosh" | "tanh"
2521 | "abs" | "arg" | "conj" | "re" | "im" => Some(1),
2522 "min" | "max" => Some(2),
2524 "clamp" => Some(3),
2525 "solve" => Some(2),
2527 "roots" => Some(2),
2528 "poly_coeffs" => Some(2),
2529 "det" | "trace" | "adjoint" | "inv" | "norm" => Some(1),
2531 "dot" => Some(2),
2533 _ => None,
2534 }
2535}
2536
2537fn edit_distance(a: &str, b: &str) -> usize {
2539 let (a, b) = (a.as_bytes(), b.as_bytes());
2540 let mut prev: Vec<usize> = (0..=b.len()).collect();
2541 let mut cur = vec![0usize; b.len() + 1];
2542 for i in 1..=a.len() {
2543 cur[0] = i;
2544 for j in 1..=b.len() {
2545 let cost = if a[i - 1] == b[j - 1] { 0 } else { 1 };
2546 cur[j] = (prev[j] + 1).min(cur[j - 1] + 1).min(prev[j - 1] + cost);
2547 }
2548 core::mem::swap(&mut prev, &mut cur);
2549 }
2550 prev[b.len()]
2551}
2552
2553pub const FUNC_NAMES: &[&str] = &[
2559 "exp",
2560 "ln",
2561 "log",
2562 "sqrt",
2563 "sin",
2564 "cos",
2565 "tan",
2566 "sinh",
2567 "cosh",
2568 "tanh",
2569 "abs",
2570 "arg",
2571 "conj",
2572 "re",
2573 "im",
2574 "min",
2575 "max",
2576 "clamp",
2577 "det",
2578 "trace",
2579 "adjoint",
2580 "inv",
2581 "solve",
2582 "roots",
2583 "poly_coeffs",
2584 "dot",
2585 "norm",
2586];
2587
2588pub fn closest_func(name: &str) -> Option<&'static str> {
2589 const NAMES: &[&str] = &[
2590 "exp",
2591 "ln",
2592 "log",
2593 "sqrt",
2594 "sin",
2595 "cos",
2596 "tan",
2597 "sinh",
2598 "cosh",
2599 "tanh",
2600 "abs",
2601 "arg",
2602 "conj",
2603 "re",
2604 "im",
2605 "min",
2606 "max",
2607 "clamp",
2608 "det",
2609 "trace",
2610 "adjoint",
2611 "inv",
2612 "solve",
2613 "roots",
2614 "poly_coeffs",
2615 "dot",
2616 "norm",
2617 ];
2618 let max_distance = if name.len() <= 4 { 1 } else { 2 };
2621 NAMES
2622 .iter()
2623 .map(|n| (*n, edit_distance(name, n)))
2624 .filter(|(_, d)| *d <= max_distance)
2625 .min_by_key(|(_, d)| *d)
2626 .map(|(n, _)| n)
2627}
2628
2629pub fn check_calls(e: &Expr) -> Result<(), Error> {
2632 check_calls_with_shapes(e, &runtime::RuntimeShapes::new())
2633}
2634
2635pub fn check_calls_with_shapes(
2638 e: &Expr,
2639 runtime_shapes: &runtime::RuntimeShapes,
2640) -> Result<(), Error> {
2641 match e {
2642 Expr::Call(name, args) => {
2643 let Some(want) = func_arity(name) else {
2644 let suggestion = closest_func(name).unwrap_or_default().to_string();
2649 return Err(Error::UnknownFunction {
2650 name: name.clone(),
2651 suggestion,
2652 });
2653 };
2654 if args.len() != want {
2655 return Err(Error::FunctionArity {
2656 name: name.clone(),
2657 expected: want,
2658 got: args.len(),
2659 });
2660 }
2661 if name == "poly_coeffs" {
2663 let Expr::Var(v) = &args[1] else {
2664 return Err(Error::InvalidInput(
2665 "`poly_coeffs(poly, x)`: the second argument must be a variable name"
2666 .into(),
2667 ));
2668 };
2669 poly_coeffs_vec(&args[0], v)?;
2670 }
2671 if name == "roots" {
2674 let Expr::Var(v) = &args[1] else {
2675 return Err(Error::InvalidInput(
2676 "`roots(poly, x)`: the second argument must be a variable name".into(),
2677 ));
2678 };
2679 solve_poly(&args[0], v)?;
2680 }
2681 if name == "solve" {
2687 match &args[1] {
2688 Expr::Var(v) => {
2689 let is_runtime_solve = runtime::runtime_kind_of(&args[0], runtime_shapes)
2690 .map(|kind| kind == runtime::RuntimeKind::Matrix)
2691 .unwrap_or(false)
2692 && runtime::runtime_kind_of(&args[1], runtime_shapes)
2693 .map(|kind| kind == runtime::RuntimeKind::Vector)
2694 .unwrap_or(false);
2695 if !is_runtime_solve {
2696 solve_linear(&args[0], v)?;
2697 }
2698 }
2699 Expr::Mat(_) => {
2700 let vars = mat_var_names(&args[1]).ok_or_else(|| {
2701 Error::InvalidInput(
2702 "`solve` expects its second argument to be a list of variable names"
2703 .into(),
2704 )
2705 })?;
2706 let eqs = flat_mat_items(&args[0]).ok_or_else(|| {
2707 Error::InvalidInput(
2708 "`solve` expects its first argument to be a list of equations, each of the form `expr = 0`".into(),
2709 )
2710 })?;
2711 solve_system(&eqs, &vars)?;
2712 }
2713 _ => {
2714 return Err(Error::InvalidInput(
2715 "`solve(expr, x)`: the second argument must be a variable name or a list of names".into(),
2716 ))
2717 }
2718 }
2719 }
2720 for a in args {
2721 check_calls_with_shapes(a, runtime_shapes)?;
2722 }
2723 Ok(())
2724 }
2725 Expr::Num(_) | Expr::Var(_) | Expr::Indexed { .. } => Ok(()),
2726 Expr::Add(a, b) | Expr::Sub(a, b) | Expr::Mul(a, b) | Expr::Div(a, b) | Expr::Pow(a, b) => {
2727 check_calls_with_shapes(a, runtime_shapes)?;
2728 check_calls(b)
2729 }
2730 Expr::Neg(a)
2731 | Expr::Transpose(a)
2732 | Expr::Grad(a)
2733 | Expr::Laplacian(a)
2734 | Expr::Deriv(a, _) => check_calls_with_shapes(a, runtime_shapes),
2735 Expr::Mat(rows) => {
2736 for r in rows {
2737 for c in r {
2738 check_calls_with_shapes(c, runtime_shapes)?;
2739 }
2740 }
2741 Ok(())
2742 }
2743 Expr::MatPattern(p) => {
2744 for e in p.elements() {
2745 check_calls_with_shapes(e, runtime_shapes)?;
2746 }
2747 Ok(())
2748 }
2749 Expr::Sum {
2750 lower, upper, body, ..
2751 }
2752 | Expr::Integral {
2753 lower, upper, body, ..
2754 } => {
2755 check_calls_with_shapes(lower, runtime_shapes)?;
2756 check_calls_with_shapes(upper, runtime_shapes)?;
2757 check_calls_with_shapes(body, runtime_shapes)
2758 }
2759 }
2760}
2761
2762fn c_call_n(name: &str, args: &[C]) -> Result<C, Error> {
2769 let real = |v: C| -> Result<f64, Error> {
2770 if v.is_real() {
2771 Ok(v.re)
2772 } else {
2773 Err(Error::InvalidInput(format!(
2774 "`{name}` is defined for real numbers only (got {v:?})"
2775 )))
2776 }
2777 };
2778 Ok(match name {
2779 "min" => C::real(real(args[0])?.min(real(args[1])?)),
2780 "max" => C::real(real(args[0])?.max(real(args[1])?)),
2781 "clamp" => C::real(real(args[0])?.max(real(args[1])?).min(real(args[2])?)),
2787 other => {
2788 return Err(Error::InvalidInput(format!(
2789 "`{other}` is not a scalar multi-argument function"
2790 )))
2791 }
2792 })
2793}
2794
2795fn c_call(name: &str, x: C) -> Result<C, Error> {
2796 Ok(match name {
2797 "exp" => x.exp(),
2798 "ln" | "log" => x.ln()?,
2799 "sqrt" => x.sqrt(),
2800 "sin" => x.sin(),
2801 "cos" => x.cos(),
2802 "tan" => x.tan()?,
2803 "sinh" => x.sinh(),
2804 "cosh" => x.cosh(),
2805 "tanh" => x.tanh()?,
2806 "abs" => C::real(x.abs()),
2808 "arg" => C::real(x.arg()),
2809 "conj" => x.conj(),
2810 "re" => C::real(x.re),
2811 "im" => C::real(x.im),
2812 other => {
2813 return Err(Error::UnsupportedOperation(format!(
2814 "the function `{other}` is not supported during evaluation"
2815 )))
2816 }
2817 })
2818}
2819
2820fn mat_det(m: &[Vec<C>]) -> Result<C, Error> {
2827 let n = m.len();
2828 if n == 0 || m.iter().any(|r| r.len() != n) {
2829 return Err(Error::ShapeMismatch(
2830 "`det` needs a non-empty square matrix".into(),
2831 ));
2832 }
2833 if n > 4 {
2834 return Err(Error::InvalidInput(format!(
2835 "`det` supports orders 1–4 only (got {n}); use a numeric library for higher orders"
2836 )));
2837 }
2838 if n == 1 {
2839 return Ok(m[0][0]);
2840 }
2841 let mut acc = C::ZERO;
2842 for (j, cell) in m[0].iter().enumerate() {
2843 let sub: Vec<Vec<C>> = m
2844 .iter()
2845 .skip(1)
2846 .map(|row| {
2847 row.iter()
2848 .enumerate()
2849 .filter(|(c, _)| *c != j)
2850 .map(|(_, x)| *x)
2851 .collect()
2852 })
2853 .collect();
2854 let term = cell.mul(mat_det(&sub)?);
2855 acc = if j % 2 == 0 {
2856 acc.add(term)
2857 } else {
2858 acc.sub(term)
2859 };
2860 }
2861 Ok(acc)
2862}
2863
2864fn c_bin(
2867 a: &Expr,
2868 b: &Expr,
2869 env: &HashMap<String, f64>,
2870 f: impl Fn(C, C) -> Result<C, Error>,
2871) -> Result<Value, Error> {
2872 let (va, vb) = (eval_value(a, env)?, eval_value(b, env)?);
2873 match (va, vb) {
2874 (Value::Scalar(x), Value::Scalar(y)) => Ok(Value::Scalar(f(x, y)?)),
2875 (Value::Matrix(ma), Value::Matrix(mb)) => {
2876 if ma.len() != mb.len() {
2877 return Err(Error::ShapeMismatch(format!(
2878 "element-wise rows disagree: {} vs {}",
2879 ma.len(),
2880 mb.len()
2881 )));
2882 }
2883 let mut out = Vec::with_capacity(ma.len());
2884 for (ra, rb) in ma.iter().zip(mb.iter()) {
2885 if ra.len() != rb.len() {
2886 return Err(Error::ShapeMismatch(format!(
2887 "element-wise operation on matrices with different column counts: {} vs {}",
2888 ra.len(),
2889 rb.len()
2890 )));
2891 }
2892 let mut row = Vec::with_capacity(ra.len());
2893 for (x, y) in ra.iter().zip(rb.iter()) {
2894 row.push(f(*x, *y)?);
2895 }
2896 out.push(row);
2897 }
2898 Ok(Value::Matrix(out))
2899 }
2900 _ => Err(Error::MatrixScalarMix("write element-wise matrix/scalar operations explicitly (there is no implicit broadcast)".into())),
2901 }
2902}
2903
2904fn mat_mul_value_of(a: Value, b: Value) -> Result<Value, Error> {
2906 match (a, b) {
2907 (Value::Scalar(x), Value::Scalar(y)) => Ok(Value::Scalar(x.mul(y))),
2908 (Value::Matrix(ma), Value::Matrix(mb)) => {
2909 let n_inner = ma.first().map(|r| r.len()).unwrap_or(0);
2910 if mb.len() != n_inner {
2911 return Err(Error::ShapeMismatch(format!(
2912 "cannot multiply: inner dimension {n_inner} ≠ rows {}",
2913 mb.len()
2914 )));
2915 }
2916 let cols = mb.first().map(|r| r.len()).unwrap_or(0);
2917 let mut out = vec![vec![C::ZERO; cols]; ma.len()];
2918 for (i, row) in ma.iter().enumerate() {
2919 for (j, cell) in out[i].iter_mut().enumerate() {
2920 let mut acc = C::ZERO;
2921 for (k, v) in row.iter().enumerate() {
2922 acc = acc.add(v.mul(mb[k][j]));
2923 }
2924 *cell = acc;
2925 }
2926 }
2927 Ok(Value::Matrix(out))
2928 }
2929 (Value::Matrix(m), Value::Scalar(k)) => Ok(Value::Matrix(map_mat(&m, |v| v.mul(k)))),
2930 (Value::Scalar(k), Value::Matrix(m)) => Ok(Value::Matrix(map_mat(&m, |v| v.mul(k)))),
2931 }
2932}
2933
2934fn eval_i(e: &Expr, env: &HashMap<String, f64>) -> Result<i64, Error> {
2936 let v = eval(e, env)?;
2937 if math::fract(v) != 0.0 {
2938 return Err(Error::InvalidInput(format!(
2939 "the sum bounds must be integers, got {v}"
2940 )));
2941 }
2942 Ok(v as i64)
2943}
2944
2945pub fn contains_nan_expr(e: &Expr) -> bool {
2953 match e {
2954 Expr::Num(v) => v.is_nan(),
2955 Expr::Var(_) | Expr::Indexed { .. } => false,
2956 Expr::Add(a, b) | Expr::Sub(a, b) | Expr::Mul(a, b) | Expr::Div(a, b) | Expr::Pow(a, b) => {
2957 contains_nan_expr(a) || contains_nan_expr(b)
2958 }
2959 Expr::Neg(a)
2960 | Expr::Transpose(a)
2961 | Expr::Grad(a)
2962 | Expr::Laplacian(a)
2963 | Expr::Deriv(a, _) => contains_nan_expr(a),
2964 Expr::Call(_, args) => args.iter().any(contains_nan_expr),
2965 Expr::Mat(rows) => rows.iter().flatten().any(contains_nan_expr),
2966 Expr::MatPattern(p) => p.elements().into_iter().any(contains_nan_expr),
2967 Expr::Sum {
2968 lower, upper, body, ..
2969 }
2970 | Expr::Integral {
2971 lower, upper, body, ..
2972 } => contains_nan_expr(lower) || contains_nan_expr(upper) || contains_nan_expr(body),
2973 }
2974}
2975
2976pub fn contains_nonfinite_expr(e: &Expr) -> bool {
2982 match e {
2983 Expr::Num(v) => !v.is_finite(),
2984 Expr::Var(_) | Expr::Indexed { .. } => false,
2985 Expr::Add(a, b) | Expr::Sub(a, b) | Expr::Mul(a, b) | Expr::Div(a, b) | Expr::Pow(a, b) => {
2986 contains_nonfinite_expr(a) || contains_nonfinite_expr(b)
2987 }
2988 Expr::Neg(a)
2989 | Expr::Transpose(a)
2990 | Expr::Grad(a)
2991 | Expr::Laplacian(a)
2992 | Expr::Deriv(a, _) => contains_nonfinite_expr(a),
2993 Expr::Call(_, args) => args.iter().any(contains_nonfinite_expr),
2994 Expr::Mat(rows) => rows.iter().flatten().any(contains_nonfinite_expr),
2995 Expr::MatPattern(p) => p.elements().into_iter().any(contains_nonfinite_expr),
2996 Expr::Sum {
2997 lower, upper, body, ..
2998 }
2999 | Expr::Integral {
3000 lower, upper, body, ..
3001 } => {
3002 contains_nonfinite_expr(lower)
3003 || contains_nonfinite_expr(upper)
3004 || contains_nonfinite_expr(body)
3005 }
3006 }
3007}
3008
3009pub fn nondiffable(e: &Expr) -> Vec<String> {
3012 fn go(e: &Expr, out: &mut Vec<String>) {
3013 match e {
3014 Expr::Call(n, args) => {
3015 let named = matches!(n.as_str(), "arg" | "min" | "max" | "clamp");
3024 if named && !out.contains(n) {
3025 out.push(n.clone());
3026 }
3027 for a in args {
3028 go(a, out);
3029 }
3030 }
3031 Expr::Deriv(..) | Expr::Sum { .. } | Expr::Integral { .. } | Expr::Indexed { .. } => {
3032 if !out.contains(&"operators/sums/integrals".to_string()) {
3033 out.push("operators/sums/integrals".to_string());
3034 }
3035 }
3036 Expr::Mat(rows) => {
3037 for r in rows {
3038 for c in r {
3039 go(c, out);
3040 }
3041 }
3042 }
3043 Expr::MatPattern(p) => {
3044 for e in p.elements() {
3045 go(e, out);
3046 }
3047 }
3048 Expr::Add(a, b)
3049 | Expr::Sub(a, b)
3050 | Expr::Mul(a, b)
3051 | Expr::Div(a, b)
3052 | Expr::Pow(a, b) => {
3053 go(a, out);
3054 go(b, out);
3055 }
3056 Expr::Neg(a) | Expr::Transpose(a) | Expr::Grad(a) | Expr::Laplacian(a) => go(a, out),
3057 _ => {}
3058 }
3059 }
3060 let mut out = Vec::new();
3061 go(e, &mut out);
3062 out
3063}
3064
3065pub fn diff(e: &Expr, x: &str) -> Expr {
3066 match e {
3067 Expr::Num(_) => num(0.0),
3068 Expr::Var(n) => num(if n == x { 1.0 } else { 0.0 }),
3069 Expr::Add(a, b) => add(diff(a, x), diff(b, x)),
3070 Expr::Sub(a, b) => sub(diff(a, x), diff(b, x)),
3071 Expr::Mul(a, b) => add(
3072 mul(diff(a, x), (**b).clone()),
3073 mul((**a).clone(), diff(b, x)),
3074 ),
3075 Expr::Div(a, b) => div(
3076 sub(
3077 mul(diff(a, x), (**b).clone()),
3078 mul((**a).clone(), diff(b, x)),
3079 ),
3080 pow((**b).clone(), num(2.0)),
3081 ),
3082 Expr::Neg(a) => neg(diff(a, x)),
3083 Expr::Pow(a, b) => match b.as_ref() {
3084 Expr::Num(n) => mul(mul(num(*n), pow((**a).clone(), num(n - 1.0))), diff(a, x)),
3085 _ => mul(
3086 pow((**a).clone(), (**b).clone()),
3087 add(
3088 mul(diff(b, x), Expr::Call("ln".into(), vec![(**a).clone()])),
3089 div(mul((**b).clone(), diff(a, x)), (**a).clone()),
3090 ),
3091 ),
3092 },
3093 Expr::Call(name, args) => {
3094 let Some(u) = args.first().cloned() else {
3095 return num(f64::NAN);
3096 };
3097 let du = diff(&u, x);
3098 let one = |v: Expr| Expr::Call(name.clone(), vec![v]);
3099 match name.as_str() {
3100 "exp" => mul(one(u), du),
3101 "ln" | "log" => div(du, u),
3102 "sin" => mul(Expr::Call("cos".into(), vec![u]), du),
3103 "cos" => neg(mul(Expr::Call("sin".into(), vec![u]), du)),
3104 "tan" => mul(add(num(1.0), pow(one(u), num(2.0))), du),
3105 "sinh" => mul(Expr::Call("cosh".into(), vec![u]), du),
3106 "cosh" => mul(Expr::Call("sinh".into(), vec![u]), du),
3107 "tanh" => mul(sub(num(1.0), pow(one(u), num(2.0))), du),
3108 "sqrt" => div(du, mul(num(2.0), one(u))),
3109 "abs" => mul(div(u.clone(), Expr::Call("abs".into(), vec![u])), du),
3112 "det" | "trace" | "solve" | "roots" | "dot" | "norm" => match expand_call(e) {
3115 Some(expanded) => diff(&expanded, x),
3116 None => num(f64::NAN),
3117 },
3118 "min" | "max" | "clamp" | "inv" => num(f64::NAN),
3123 "conj" | "re" | "im" => du,
3126 "arg" => num(f64::NAN),
3128 _ => num(f64::NAN),
3129 }
3130 }
3131 Expr::Mat(_) | Expr::MatPattern(_) => num(f64::NAN),
3132 Expr::Transpose(a) => transpose(diff(a, x)),
3133 Expr::Deriv(..)
3136 | Expr::Grad(_)
3137 | Expr::Laplacian(_)
3138 | Expr::Sum { .. }
3139 | Expr::Integral { .. }
3140 | Expr::Indexed { .. } => num(f64::NAN),
3141 }
3142}
3143
3144pub fn dims_of(decls: &[Decl]) -> Result<HashMap<String, Dim>, Error> {
3147 let mut m = HashMap::new();
3148 for d in decls {
3149 let dim = match &d.unit {
3150 Some(u) => parse_unit(u).map_err(|unit| Error::DeclarationUnit {
3151 name: d.name.clone(),
3152 unit: Box::new(unit),
3153 })?,
3154 None => Dim::ZERO,
3155 };
3156 if m.insert(d.name.clone(), dim).is_some() {
3157 return Err(Error::DuplicateDeclaration {
3159 name: d.name.clone(),
3160 line: None, });
3162 }
3163 }
3164 Ok(m)
3165}
3166
3167fn is_zero_lit(e: &Expr) -> bool {
3168 matches!(e, Expr::Num(v) if *v == 0.0)
3169}
3170
3171fn dim_addsub(a: &Expr, b: &Expr, op: &str, dims: &HashMap<String, Dim>) -> Result<Dim, Error> {
3175 if is_zero_lit(a) {
3178 return dim_check(b, dims);
3179 }
3180 if is_zero_lit(b) {
3181 return dim_check(a, dims);
3182 }
3183 let da = dim_check(a, dims)?;
3184 let db = dim_check(b, dims)?;
3185 if da != db {
3186 return Err(Error::OperatorDimensionMismatch {
3187 operator: op.into(),
3188 left: da.display(),
3189 right: db.display(),
3190 });
3191 }
3192 Ok(da)
3193}
3194
3195pub fn dim_check(e: &Expr, dims: &HashMap<String, Dim>) -> Result<Dim, Error> {
3196 use Expr::*;
3197 Ok(match e {
3198 Num(_) => Dim::ZERO,
3199 Var(n) if n == "j" => Dim::ZERO,
3202 Var(n) => *dims
3203 .get(n)
3204 .ok_or_else(|| Error::UndeclaredSymbol(n.clone()))?,
3205 Neg(a) => dim_check(a, dims)?,
3206 Add(a, b) => dim_addsub(a, b, "+", dims)?,
3207 Sub(a, b) => dim_addsub(a, b, "-", dims)?,
3208 Mul(a, b) => dim_check(a, dims)?.mul_dim(dim_check(b, dims)?),
3209 Div(a, b) => dim_check(a, dims)?.div_dim(dim_check(b, dims)?),
3210 Pow(a, b) => {
3211 let db = dim_check(b, dims)?;
3212 if !db.is_zero() {
3213 return Err(Error::ExponentNotDimensionless(db.display()));
3214 }
3215 let da = dim_check(a, dims)?;
3216 let folded;
3225 let expo = match b.as_ref() {
3226 Num(n) => Some(*n),
3227 other => {
3228 folded = simplify(other);
3232 match &folded {
3233 Num(n) => Some(*n),
3234 _ => None,
3235 }
3236 }
3237 };
3238 if da.is_zero() {
3243 return Ok(Dim::ZERO);
3244 }
3245 match expo {
3246 Some(n) => {
3247 let two_n = n * 2.0;
3248 if math::fract(two_n) != 0.0 || two_n.abs() > 1.0e6 {
3249 return Err(Error::ExponentNotHalfInteger(format!("{n} is not p/2")));
3250 }
3251 let p = two_n as i32;
3252 let mut r = [0i16; 7];
3253 for (a, b) in r.iter_mut().zip(da.0) {
3254 let prod = b as i32 * p;
3255 if prod % 2 != 0 {
3256 return Err(Error::InvalidInput(format!(
3257 "`^{n}` needs every exponent of {} to stay even after scaling by {p}, otherwise the dimension is undefined",
3258 da.display()
3259 )));
3260 }
3261 *a = (prod / 2) as i16;
3262 }
3263 Dim(r)
3264 }
3265 None => {
3266 return Err(Error::InvalidInput(
3267 "the exponent must be a numeric constant".into(),
3268 ))
3269 }
3270 }
3271 }
3272 Call(name, args) => {
3273 let Some(arg0) = args.first() else {
3274 return Err(Error::InvalidInput(format!("`{name}` needs an argument")));
3277 };
3278 if name == "solve" && matches!(arg0, Expr::Mat(_)) {
3286 if let Some(eqs) = flat_mat_items(arg0) {
3287 for eq in &eqs {
3288 dim_check(eq, dims)?;
3291 }
3292 }
3293 return match expand_call(e) {
3294 Some(x) => dim_check(&x, dims),
3295 None => Err(Error::InvalidInput(
3296 "`solve` needs its second argument to be a variable name or a list of names, and the equations to be linear in the unknowns".into(),
3297 )),
3298 };
3299 }
3300 if matches!(name.as_str(), "__quad_root_1" | "__quad_root_2") {
3301 if args.len() != 3 {
3302 return Err(Error::FunctionArity {
3303 name: name.clone(),
3304 expected: 3,
3305 got: args.len(),
3306 });
3307 }
3308 let da = dim_check(&args[0], dims)?;
3310 let db = dim_check(&args[1], dims)?;
3311 return Ok(db.div_dim(da));
3312 }
3313 let d = dim_check(arg0, dims)?;
3314 match name.as_str() {
3315 "exp" | "ln" | "log" | "sin" | "cos" | "tan" | "sinh" | "cosh" | "tanh" => {
3316 if !d.is_zero() {
3317 return Err(Error::InvalidInput(format!(
3318 "`{name}` arguments must be dimensionless, got {}",
3319 d.display()
3320 )));
3321 }
3322 Dim::ZERO
3323 }
3324 "sqrt" => {
3325 let mut r = [0i16; 7];
3326 for (a, b) in r.iter_mut().zip(d.0) {
3327 if b % 2 != 0 {
3328 return Err(Error::InvalidInput(format!(
3329 "`sqrt` needs a dimension whose exponents are all even, got {}",
3330 d.display()
3331 )));
3332 }
3333 *a = b / 2;
3334 }
3335 Dim(r)
3336 }
3337 "arg" => Dim::ZERO,
3341 "abs" | "conj" | "re" | "im" => d,
3342 "min" | "max" | "clamp" => {
3345 for a in &args[1..] {
3346 let other = dim_check(a, dims)?;
3347 if other != d {
3348 return Err(Error::InvalidInput(format!(
3349 "`{name}` requires all its arguments to have the same dimension: {} vs {}",
3350 d.display(),
3351 other.display()
3352 )));
3353 }
3354 }
3355 d
3356 }
3357 "det" => {
3363 let n = match flatten_matrix_value(&args[0]) {
3364 Some(m) if !m.is_empty() && m.iter().all(|r| r.len() == m.len()) => m.len(),
3365 _ => match shape_of(&args[0])? {
3366 Some((r, c)) if r == c && r > 0 => r,
3367 _ => {
3368 return Err(Error::InvalidInput("`det` needs a concrete square matrix literal (its shape is unknown, so the dimension cannot be computed)".into()))
3369 }
3370 },
3371 };
3372 d.scale_ratio(n as i32, 1)?
3373 }
3374 "trace" | "adjoint" => d,
3375 "inv" => d.scale_ratio(-1, 1)?,
3377 "dot" => {
3380 let d2 = dim_check(&args[1], dims)?;
3381 if d2 != d {
3382 return Err(Error::InvalidInput(format!(
3383 "`dot` requires both arguments to have the same dimension: {} vs {}",
3384 d.display(),
3385 d2.display()
3386 )));
3387 }
3388 d.mul_dim(d)
3389 }
3390 "norm" => d,
3392 "roots" | "solve" | "poly_coeffs" => {
3395 if name == "poly_coeffs" {
3404 if let Some(Expr::Var(v)) = args.get(1) {
3405 let dv = dims.get(v).copied().unwrap_or(Dim::ZERO);
3406 if !dv.is_zero() {
3407 return Err(Error::InvalidInput(format!(
3408 "`poly_coeffs`: the coefficients of `{v}` have dimension {}, but matrix elements must share one dimension; take coefficients of a dimensionless variable (for example divide by a scale first) or use `roots`",
3409 dv.display()
3410 )));
3411 }
3412 }
3413 }
3414 match expand_call(e) {
3415 Some(x) => return dim_check(&x, dims),
3416 None if name == "poly_coeffs" => {
3421 return Err(Error::InvalidInput(
3422 "`poly_coeffs(poly, x)` needs its second argument to be a variable name and its first to be a univariate polynomial in it".into(),
3423 ))
3424 }
3425 None if name == "roots" => {
3426 return Err(Error::InvalidInput(
3427 "`roots(poly, x)` needs its second argument to be a variable name and its first to be a univariate polynomial in it".into(),
3428 ))
3429 }
3430 None => return Err(Error::InvalidInput(
3431 "`solve` needs its second argument to be a variable name and the equation to be linear in it".into(),
3432 )),
3433 }
3434 }
3435 other => {
3436 return Err(Error::UnknownFunction {
3437 name: other.to_string(),
3438 suggestion: String::new(),
3439 })
3440 }
3441 }
3442 }
3443 Mat(rows) => {
3444 let mut acc: Option<Dim> = None;
3445 for r in rows {
3446 for c in r {
3447 if is_zero_lit(c) {
3448 continue; }
3450 let d = dim_check(c, dims)?;
3451 match acc {
3452 None => acc = Some(d),
3453 Some(prev) if prev == d => {}
3454 Some(prev) => {
3455 return Err(Error::InvalidInput(format!(
3456 "matrix elements must all share one dimension: {} vs {}",
3457 prev.display(),
3458 d.display()
3459 )))
3460 }
3461 }
3462 }
3463 }
3464 acc.unwrap_or(Dim::ZERO)
3465 }
3466 MatPattern(p) => {
3467 let grid = p.grid().ok_or_else(|| {
3470 Error::ShapeMismatch("pattern matrix rows have inconsistent lengths".into())
3471 })?;
3472 if grid.0 < 2 || grid.1 < 2 {
3473 return Err(Error::InvalidInput(
3474 "a pattern matrix must be at least 2×2, otherwise the ellipsis means nothing"
3475 .into(),
3476 ));
3477 }
3478 let mut acc: Option<Dim> = None;
3479 for e in p.elements() {
3480 if is_zero_lit(e) {
3481 continue; }
3483 let d = dim_check(e, dims)?;
3484 match acc {
3485 None => acc = Some(d),
3486 Some(prev) if prev == d => {}
3487 Some(prev) => {
3488 return Err(Error::InvalidInput(format!(
3489 "pattern-matrix elements must all share one dimension: {} vs {}",
3490 prev.display(),
3491 d.display()
3492 )))
3493 }
3494 }
3495 }
3496 acc.unwrap_or(Dim::ZERO)
3497 }
3498 Transpose(a) => dim_check(a, dims)?,
3499 Deriv(u, by) => {
3500 let du = dim_check(u, dims)?;
3501 let dx = *dims
3504 .get(by)
3505 .ok_or_else(|| Error::UndeclaredSymbol(by.clone()))?;
3506 du.div_dim(dx)
3507 }
3508 Grad(u) => dim_check(u, dims)?.div_dim(parse_unit("m")?), Laplacian(u) => {
3510 let d = dim_check(u, dims)?;
3511 let m2 = parse_unit("m")?.scale_ratio(2, 1)?;
3512 d.div_dim(m2)
3513 }
3514 Sum {
3515 var,
3516 lower,
3517 upper,
3518 body,
3519 } => {
3520 let dl = dim_check(lower, dims)?;
3521 let du = dim_check(upper, dims)?;
3522 if !dl.is_zero() || !du.is_zero() {
3523 return Err(Error::InvalidInput(
3524 "the sum bounds must be dimensionless (the index is a counter)".into(),
3525 ));
3526 }
3527 let mut inner = dims.clone();
3528 inner.insert(var.clone(), Dim::ZERO); dim_check(body, &inner)?
3530 }
3531 Integral {
3532 var,
3533 lower,
3534 upper,
3535 body,
3536 } => {
3537 let dl = dim_check(lower, dims)?;
3538 let du = dim_check(upper, dims)?;
3539 let dv = *dims
3540 .get(var)
3541 .ok_or_else(|| Error::UndeclaredSymbol(var.clone()))?;
3542 if dl != du {
3543 return Err(Error::DimensionMismatch {
3544 left: dl.display().to_string(),
3545 right: du.display().to_string(),
3546 });
3547 }
3548 let db = dim_check(body, dims)?;
3549 db.mul_dim(dv)
3550 }
3551 Indexed { name, indices } => {
3552 let d = *dims
3553 .get(name)
3554 .ok_or_else(|| Error::UndeclaredSymbol(name.clone()))?;
3555 for i in indices {
3556 if !dims.get(i).map(|x| x.is_zero()).unwrap_or(false) {
3557 return Err(Error::InvalidInput(format!(
3558 "the index `{i}` must be a dimensionless symbol (it is undeclared or carries a dimension)"
3559 )));
3560 }
3561 }
3562 d
3563 }
3564 })
3565}
3566
3567pub fn key(e: &Expr) -> String {
3570 let mut s = String::new();
3571 key_into(e, &mut s);
3572 s
3573}
3574
3575fn key_into(e: &Expr, s: &mut String) {
3576 match e {
3577 Expr::Num(v) => {
3578 let _ = write!(s, "#{:016x}", v.to_bits());
3579 }
3580 Expr::Var(n) => {
3581 s.push('$');
3582 s.push_str(n);
3583 }
3584 Expr::Add(a, b) => bin(s, 'A', a, b),
3585 Expr::Sub(a, b) => bin(s, 'S', a, b),
3586 Expr::Mul(a, b) => bin(s, 'M', a, b),
3587 Expr::Div(a, b) => bin(s, 'D', a, b),
3588 Expr::Pow(a, b) => bin(s, 'P', a, b),
3589 Expr::Neg(a) => {
3590 s.push_str("(N");
3591 key_into(a, s);
3592 s.push(')');
3593 }
3594 Expr::Call(n, args) => {
3595 s.push_str("(C");
3596 s.push_str(n);
3597 for a in args {
3598 key_into(a, s);
3599 }
3600 s.push(')');
3601 }
3602 Expr::Mat(rows) => {
3603 s.push_str("(T");
3604 for r in rows {
3605 for c in r {
3606 key_into(c, s);
3607 }
3608 s.push('|');
3609 }
3610 s.push(')');
3611 }
3612 Expr::MatPattern(p) => {
3613 s.push_str("(TP");
3614 for r in &p.rows {
3615 for c in r {
3616 match c {
3617 PatternCell::El(e) => key_into(e, s),
3618 PatternCell::Dots => s.push('\u{b7}'),
3619 }
3620 }
3621 s.push('|');
3622 }
3623 s.push(')');
3624 }
3625 Expr::Transpose(a) => {
3626 s.push_str("(TR");
3627 key_into(a, s);
3628 s.push(')');
3629 }
3630 Expr::Deriv(u, by) => {
3631 s.push_str("(DV");
3632 key_into(u, s);
3633 s.push('$');
3634 s.push_str(by);
3635 s.push(')');
3636 }
3637 Expr::Grad(u) => {
3638 s.push_str("(GR");
3639 key_into(u, s);
3640 s.push(')');
3641 }
3642 Expr::Laplacian(u) => {
3643 s.push_str("(LP");
3644 key_into(u, s);
3645 s.push(')');
3646 }
3647 Expr::Sum {
3648 var,
3649 lower,
3650 upper,
3651 body,
3652 } => {
3653 s.push_str("(SM$");
3654 s.push_str(var);
3655 key_into(lower, s);
3656 key_into(upper, s);
3657 key_into(body, s);
3658 s.push(')');
3659 }
3660 Expr::Integral {
3661 var,
3662 lower,
3663 upper,
3664 body,
3665 } => {
3666 s.push_str("(IN$");
3667 s.push_str(var);
3668 key_into(lower, s);
3669 key_into(upper, s);
3670 key_into(body, s);
3671 s.push(')');
3672 }
3673 Expr::Indexed { name, indices } => {
3674 s.push_str("(IX$");
3675 s.push_str(name);
3676 for i in indices {
3677 s.push('$');
3678 s.push_str(i);
3679 }
3680 s.push(')');
3681 }
3682 }
3683}
3684
3685fn bin(s: &mut String, tag: char, a: &Expr, b: &Expr) {
3686 s.push('(');
3687 s.push(tag);
3688 key_into(a, s);
3689 key_into(b, s);
3690 s.push(')');
3691}
3692
3693fn vs(n: &str) -> Expr {
3696 Expr::Var(n.to_string())
3697}
3698
3699pub fn to_latex(e: &Expr) -> String {
3700 to_latex_prec(e, 0)
3701}
3702
3703fn to_latex_prec(e: &Expr, min: u8) -> String {
3707 let (text, p) = to_latex_raw(e);
3708 wrap(text, p, min)
3709}
3710
3711fn to_latex_raw(e: &Expr) -> (String, u8) {
3712 match e {
3713 Expr::Num(v) => (fmt_num(*v), 9),
3714 Expr::Var(n) => (latex_var(n), 9),
3715 Expr::Neg(a) => (format!("-{}", to_latex_prec(a, 5)), 4),
3716 Expr::Add(a, b) => (
3717 format!("{} + {}", to_latex_prec(a, 2), to_latex_prec(b, 3)),
3718 2,
3719 ),
3720 Expr::Sub(a, b) => (
3721 format!("{} - {}", to_latex_prec(a, 2), to_latex_prec(b, 3)),
3722 2,
3723 ),
3724 Expr::Mul(a, b) => (
3725 format!("{} \\cdot {}", to_latex_prec(a, 3), to_latex_prec(b, 4)),
3726 3,
3727 ),
3728 Expr::Div(a, b) => (
3730 format!(
3731 "\\frac{{{}}}{{{}}}",
3732 to_latex_prec(a, 0),
3733 to_latex_prec(b, 0)
3734 ),
3735 3,
3736 ),
3737 Expr::Pow(a, b) => (
3744 format!("{}^{{{}}}", to_latex_prec(a, 7), to_latex_prec(b, 0)),
3745 6,
3746 ),
3747 Expr::Call(n, args) => {
3748 let inner: Vec<String> = args.iter().map(|x| to_latex_prec(x, 0)).collect();
3749 let text = match n.as_str() {
3750 "sqrt" => format!("\\sqrt{{{}}}", inner.join(", ")),
3752 "abs" | "arg" | "conj" | "re" | "im" | "clamp" | "trace" | "adjoint" | "inv"
3757 | "solve" | "roots" | "poly_coeffs" | "norm" | "dot" => {
3758 format!("\\operatorname{{{}}}({})", n, inner.join(", "))
3759 }
3760 _ => format!("\\{}({})", n.as_str(), inner.join(", ")),
3761 };
3762 (text, 9)
3763 }
3764 Expr::Mat(rows) => {
3765 let body: Vec<String> = rows
3766 .iter()
3767 .map(|r| {
3768 r.iter()
3769 .map(|x| to_latex_prec(x, 0))
3770 .collect::<Vec<_>>()
3771 .join(" & ")
3772 })
3773 .collect();
3774 (
3775 format!("\\begin{{bmatrix}}{}\\end{{bmatrix}}", body.join(" \\\\ ")),
3776 9,
3777 )
3778 }
3779 Expr::MatPattern(p) => {
3780 let (m, n) = p.grid().unwrap_or((p.rows.len(), 0));
3781 let has_el_row: Vec<bool> = p
3782 .rows
3783 .iter()
3784 .map(|r| r.iter().any(|c| matches!(c, PatternCell::El(_))))
3785 .collect();
3786 let has_el_col: Vec<bool> = (0..n.max(p.rows.first().map(|r| r.len()).unwrap_or(0)))
3787 .map(|j| {
3788 p.rows
3789 .iter()
3790 .any(|r| matches!(r.get(j), Some(PatternCell::El(_))))
3791 })
3792 .collect();
3793 let _ = m;
3794 let body: Vec<String> = p
3795 .rows
3796 .iter()
3797 .enumerate()
3798 .map(|(i, r)| {
3799 r.iter()
3800 .enumerate()
3801 .map(|(j, c)| match c {
3802 PatternCell::El(e) => to_latex_prec(e, 0),
3803 PatternCell::Dots => {
3804 if has_el_row[i] {
3807 "\\cdots".to_string()
3808 } else if has_el_col[j] {
3809 "\\vdots".to_string()
3810 } else {
3811 "\\ddots".to_string()
3812 }
3813 }
3814 })
3815 .collect::<Vec<_>>()
3816 .join(" & ")
3817 })
3818 .collect();
3819 (
3820 format!("\\begin{{bmatrix}}{}\\end{{bmatrix}}", body.join(" \\\\ ")),
3821 9,
3822 )
3823 }
3824 Expr::Transpose(a) => (
3825 format!("{}^{{T}}", to_latex_prec(a, 7)),
3828 6,
3829 ),
3830 Expr::Deriv(u, by) => (
3831 format!(
3832 "\\frac{{\\partial {}}}{{\\partial {}}}",
3833 to_latex_prec(u, 0),
3834 to_latex_prec(&vs(by), 0)
3835 ),
3836 3,
3837 ),
3838 Expr::Grad(u) => (format!("\\nabla {}", to_latex_prec(u, 5)), 5),
3843 Expr::Laplacian(u) => (format!("\\nabla^2 {}", to_latex_prec(u, 5)), 5),
3844 Expr::Sum {
3845 var,
3846 lower,
3847 upper,
3848 body,
3849 } => (
3850 format!(
3851 "\\sum_{{{}={}}}^{{{}}} {}",
3852 to_latex_prec(&vs(var), 0),
3853 to_latex_prec(lower, 0),
3854 to_latex_prec(upper, 0),
3855 to_latex_prec(body, 5)
3856 ),
3857 5,
3860 ),
3861 Expr::Integral {
3862 var,
3863 lower,
3864 upper,
3865 body,
3866 } => (
3867 format!(
3868 "\\int_{{{}}}^{{{}}} {} \\, d{}",
3869 to_latex_prec(lower, 0),
3870 to_latex_prec(upper, 0),
3871 to_latex_prec(body, 5),
3872 to_latex_prec(&vs(var), 0)
3873 ),
3874 5,
3875 ),
3876 Expr::Indexed { name, indices } => {
3877 let idx: Vec<String> = indices.iter().map(|i| to_latex_prec(&vs(i), 0)).collect();
3878 (
3879 format!("{}_{{{}}}", to_latex_prec(&vs(name), 0), idx.join(", ")),
3880 9,
3881 )
3882 }
3883 }
3884}
3885
3886pub fn latex_var(n: &str) -> String {
3900 const GREEK: &[&str] = &[
3901 "alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota", "kappa",
3902 "lambda", "mu", "nu", "xi", "pi", "rho", "sigma", "tau", "upsilon", "phi", "chi", "psi",
3903 "omega", "Gamma", "Delta", "Theta", "Lambda", "Xi", "Sigma", "Upsilon", "Phi", "Psi",
3904 "Omega",
3905 ];
3906 if n.len() == 1 && n.chars().all(|c| c.is_ascii_alphabetic()) {
3907 return n.to_string();
3908 }
3909 let (head, tail) = match n.split_once('_') {
3910 Some((h, t)) => (h, format!("_{t}")),
3911 None => (n, String::new()),
3912 };
3913 if GREEK.contains(&head) {
3914 return format!("\\{head}{tail}");
3915 }
3916 format!("\\mathrm{{{n}}}")
3917}
3918
3919pub fn fmt_num(v: f64) -> String {
3920 if v == math::trunc(v) && v.abs() < 1e15 {
3921 format!("{v:.0}")
3922 } else {
3923 format!("{v:?}")
3924 }
3925}
3926
3927fn wrap(s: String, p: u8, min: u8) -> String {
3930 if p < min {
3931 format!("({s})")
3932 } else {
3933 s
3934 }
3935}
3936
3937fn rust_ident(n: &str) -> String {
3938 let mut s: String = n
3939 .chars()
3940 .map(|c| {
3941 if c.is_ascii_alphanumeric() || c == '_' {
3942 c
3943 } else {
3944 '_'
3945 }
3946 })
3947 .collect();
3948 if s.chars().next().map(|c| c.is_ascii_digit()).unwrap_or(true) {
3949 s.insert(0, '_');
3950 }
3951 s
3952}
3953
3954#[derive(Clone, Copy, PartialEq)]
3962pub enum Fx {
3963 F64,
3964 F32,
3965 F64Libm,
3969}
3970
3971impl Fx {
3972 fn lit(self, v: f64) -> String {
3974 match self {
3975 Fx::F64 | Fx::F64Libm => format!("{v:?}"),
3976 Fx::F32 => format!("{:?}f32", v as f32),
3977 }
3978 }
3979
3980 fn is_libm(self) -> bool {
3981 matches!(self, Fx::F64Libm)
3982 }
3983}
3984
3985fn libm_name(name: &str) -> Option<&'static str> {
3987 Some(match name {
3988 "exp" => "exp",
3989 "ln" | "log" => "log",
3990 "sqrt" => "sqrt",
3991 "sin" => "sin",
3992 "cos" => "cos",
3993 "tan" => "tan",
3994 "sinh" => "sinh",
3995 "cosh" => "cosh",
3996 "tanh" => "tanh",
3997 "abs" => "fabs",
3998 _ => return None,
3999 })
4000}
4001
4002pub fn emit_block_libm(root: &Expr) -> String {
4009 emit_block_fx(root, Fx::F64Libm)
4010}
4011
4012pub fn emit_block(root: &Expr) -> String {
4013 emit_block_fx(root, Fx::F64)
4014}
4015
4016pub fn emit_block_f32(root: &Expr) -> String {
4018 emit_block_fx(root, Fx::F32)
4019}
4020
4021fn emit_block_fx(root: &Expr, fx: Fx) -> String {
4022 if fx.is_libm() && is_matrix_value(root) {
4025 return "{\n compile_error!(\"the no_std lane does not do matrix-valued formulas (vec! needs alloc): assemble them on the CPU side, or use the std lane\")\n }"
4026 .to_string();
4027 }
4028 let mut counts: HashMap<String, usize> = HashMap::new();
4029 count_nodes(root, &mut counts);
4030 let mut out: Vec<String> = Vec::new();
4031 let mut names: HashMap<String, String> = HashMap::new();
4032 let mut counter = 0usize;
4033 let (body, _) = emit_node(root, true, &counts, &mut names, &mut out, &mut counter, fx);
4034 let mut s = String::from("{\n");
4035 for line in &out {
4036 let _ = writeln!(s, " {line}");
4037 }
4038 let _ = writeln!(s, " {body}");
4039 s.push_str(" }");
4040 s
4041}
4042
4043pub fn uses_complex(e: &Expr) -> bool {
4061 match e {
4062 Expr::Var(n) => n == "j",
4063 Expr::Num(_) | Expr::Indexed { .. } => false,
4064 Expr::Add(a, b) | Expr::Sub(a, b) | Expr::Mul(a, b) | Expr::Div(a, b) | Expr::Pow(a, b) => {
4065 uses_complex(a) || uses_complex(b)
4066 }
4067 Expr::Neg(a)
4068 | Expr::Transpose(a)
4069 | Expr::Deriv(a, _)
4070 | Expr::Grad(a)
4071 | Expr::Laplacian(a) => uses_complex(a),
4072 Expr::Call(_, args) => args.iter().any(uses_complex),
4073 Expr::Mat(rows) => rows.iter().flatten().any(uses_complex),
4074 Expr::MatPattern(p) => p.elements().into_iter().any(uses_complex),
4075 Expr::Sum {
4076 lower, upper, body, ..
4077 }
4078 | Expr::Integral {
4079 lower, upper, body, ..
4080 } => uses_complex(lower) || uses_complex(upper) || uses_complex(body),
4081 }
4082}
4083
4084fn complex_helper(name: &str) -> &'static str {
4087 match name {
4093 "__c_add" => "#[inline(always)]\nfn __c_add(a: (f64, f64), b: (f64, f64)) -> (f64, f64) {\n (a.0 + b.0, a.1 + b.1)\n}",
4094 "__c_sub" => "#[inline(always)]\nfn __c_sub(a: (f64, f64), b: (f64, f64)) -> (f64, f64) {\n (a.0 - b.0, a.1 - b.1)\n}",
4095 "__c_neg" => "#[inline(always)]\nfn __c_neg(a: (f64, f64)) -> (f64, f64) {\n (-a.0, -a.1)\n}",
4096 "__c_mul" => "#[inline(always)]\nfn __c_mul(a: (f64, f64), b: (f64, f64)) -> (f64, f64) {\n (a.0 * b.0 - a.1 * b.1, a.0 * b.1 + a.1 * b.0)\n}",
4097 "__c_div" => "#[inline(always)]\nfn __c_div(a: (f64, f64), b: (f64, f64)) -> (f64, f64) {\n let m = b.0.abs().max(b.1.abs());\n if m > 1e-150 && m < 1e150 {\n let d = b.0 * b.0 + b.1 * b.1;\n ((a.0 * b.0 + a.1 * b.1) / d, (a.1 * b.0 - a.0 * b.1) / d)\n } else {\n let (br, bi) = (b.0 / m, b.1 / m);\n let s = m * (br * br + bi * bi);\n ((a.0 * br + a.1 * bi) / s, (a.1 * br - a.0 * bi) / s)\n }\n}",
4104 "__c_abs" => "#[inline(always)]\nfn __c_abs(a: (f64, f64)) -> (f64, f64) {\n (a.0.hypot(a.1), 0.0)\n}",
4105 "__c_arg" => "#[inline(always)]\nfn __c_arg(a: (f64, f64)) -> (f64, f64) {\n (a.1.atan2(a.0), 0.0)\n}",
4106 "__c_conj" => "#[inline(always)]\nfn __c_conj(a: (f64, f64)) -> (f64, f64) {\n (a.0, -a.1)\n}",
4107 "__c_re" => "#[inline(always)]\nfn __c_re(a: (f64, f64)) -> (f64, f64) {\n (a.0, 0.0)\n}",
4108 "__c_im" => "#[inline(always)]\nfn __c_im(a: (f64, f64)) -> (f64, f64) {\n (a.1, 0.0)\n}",
4109 "__c_exp" => "#[inline(always)]\nfn __c_exp(a: (f64, f64)) -> (f64, f64) {\n if a.1 == 0.0 {\n return (a.0.exp(), 0.0);\n }\n let m = a.0.exp();\n (m * a.1.cos(), m * a.1.sin())\n}",
4110 "__c_ln" => "#[inline(always)]\nfn __c_ln(a: (f64, f64)) -> (f64, f64) {\n (a.0.hypot(a.1).ln(), a.1.atan2(a.0))\n}",
4111 "__c_sqrt" => "#[inline(always)]\nfn __c_sqrt(a: (f64, f64)) -> (f64, f64) {\n if a.1 == 0.0 {\n return if a.0 >= 0.0 { (a.0.sqrt(), 0.0) } else { (0.0, (-a.0).sqrt()) };\n }\n if a.0 == 0.0 {\n let m = (a.1.abs() * 0.5).sqrt();\n return (m, m.copysign(a.1));\n }\n let r = a.0.hypot(a.1);\n let re = (((r + a.0) * 0.5).max(0.0)).sqrt();\n let im = (((r - a.0) * 0.5).max(0.0)).sqrt().copysign(a.1);\n (re, im)\n}",
4116 "__c_quad_root" => "#[inline(always)]\nfn __c_quad_root(a: (f64, f64), b: (f64, f64), c: (f64, f64), first: bool) -> (f64, f64) {\n let d = __c_sub(__c_mul(b, b), __c_mul((4.0, 0.0), __c_mul(a, c)));\n let s = __c_sqrt(d);\n let q_first = __c_mul(__c_conj(b), s).0 >= 0.0;\n let signed_s = if q_first { s } else { __c_neg(s) };\n let q = __c_mul((-0.5, 0.0), __c_add(b, signed_s));\n if q.0 == 0.0 && q.1 == 0.0 {\n return __c_div(__c_neg(b), __c_mul((2.0, 0.0), a));\n }\n let large = __c_div(q, a);\n let small = __c_div(c, q);\n if first == q_first { large } else { small }\n}",
4120 "__c_powf" => "#[inline(always)]\nfn __c_powf(a: (f64, f64), p: f64) -> (f64, f64) {\n if !p.is_finite() {\n return (f64::NAN, 0.0);\n }\n if a.1 == 0.0 {\n if p == p.trunc() && p.abs() <= i32::MAX as f64 {\n return (a.0.powi(p as i32), 0.0);\n }\n if a.0 >= 0.0 {\n return (a.0.powf(p), 0.0);\n }\n }\n let (r, t) = (a.0.hypot(a.1), a.1.atan2(a.0));\n let m = r.powf(p);\n let g = t * p;\n (m * g.cos(), m * g.sin())\n}",
4123 "__c_pow" => "#[inline(always)]\nfn __c_pow(a: (f64, f64), b: (f64, f64)) -> (f64, f64) {\n let lr = a.0.hypot(a.1).ln();\n let li = a.1.atan2(a.0);\n let (er, ei) = (b.0 * lr - b.1 * li, b.0 * li + b.1 * lr);\n let m = er.exp();\n (m * ei.cos(), m * ei.sin())\n}",
4124 "__c_sin" => "#[inline(always)]\nfn __c_sin(a: (f64, f64)) -> (f64, f64) {\n (a.0.sin() * a.1.cosh(), a.0.cos() * a.1.sinh())\n}",
4125 "__c_cos" => "#[inline(always)]\nfn __c_cos(a: (f64, f64)) -> (f64, f64) {\n (a.0.cos() * a.1.cosh(), -(a.0.sin() * a.1.sinh()))\n}",
4126 "__c_sinh" => "#[inline(always)]\nfn __c_sinh(a: (f64, f64)) -> (f64, f64) {\n (a.0.sinh() * a.1.cos(), a.0.cosh() * a.1.sin())\n}",
4127 "__c_cosh" => "#[inline(always)]\nfn __c_cosh(a: (f64, f64)) -> (f64, f64) {\n (a.0.cosh() * a.1.cos(), a.0.sinh() * a.1.sin())\n}",
4128 "__c_tan" => "#[inline(always)]\nfn __c_tan(a: (f64, f64)) -> (f64, f64) {\n let s = (a.0.sin() * a.1.cosh(), a.0.cos() * a.1.sinh());\n let c = (a.0.cos() * a.1.cosh(), -(a.0.sin() * a.1.sinh()));\n let d = c.0 * c.0 + c.1 * c.1;\n ((s.0 * c.0 + s.1 * c.1) / d, (s.1 * c.0 - s.0 * c.1) / d)\n}",
4129 "__c_tanh" => "#[inline(always)]\nfn __c_tanh(a: (f64, f64)) -> (f64, f64) {\n let s = (a.0.sinh() * a.1.cos(), a.0.cosh() * a.1.sin());\n let c = (a.0.cosh() * a.1.cos(), a.0.sinh() * a.1.sin());\n let d = c.0 * c.0 + c.1 * c.1;\n ((s.0 * c.0 + s.1 * c.1) / d, (s.1 * c.0 - s.0 * c.1) / d)\n}",
4130 other => panic!("未登记的复数算子 `{other}`"),
4131 }
4132}
4133
4134struct CEmit {
4135 counts: HashMap<String, usize>,
4136 names: HashMap<String, String>,
4137 helpers: BTreeSet<&'static str>,
4138 temps: Vec<String>,
4139 counter: usize,
4140 cx_vars: BTreeSet<String>,
4144}
4145
4146impl CEmit {
4147 fn help(&mut self, name: &'static str) -> &'static str {
4148 self.helpers.insert(name);
4149 name
4150 }
4151
4152 fn node(&mut self, e: &Expr, is_root: bool) -> String {
4155 let k = key(e);
4156 let shareable = !is_root
4157 && self.counts.get(&k).copied().unwrap_or(0) >= 2
4158 && !matches!(e, Expr::Num(_) | Expr::Var(_));
4159 if shareable {
4160 if let Some(n) = self.names.get(&k) {
4161 return n.clone();
4162 }
4163 }
4164 let text = self.value(e);
4165 if shareable {
4166 let name = format!("__t{}", self.counter);
4167 self.counter += 1;
4168 self.temps.push(format!("let {name} = {text};"));
4169 self.names.insert(k, name.clone());
4170 return name;
4171 }
4172 text
4173 }
4174
4175 fn call1(&mut self, helper: &'static str, e: &Expr) -> String {
4176 let a = self.node(e, false);
4177 let h = self.help(helper);
4178 format!("{h}({a})")
4179 }
4180
4181 fn call2(&mut self, helper: &'static str, a: &Expr, b: &Expr) -> String {
4182 let x = self.node(a, false);
4183 let y = self.node(b, false);
4184 let h = self.help(helper);
4185 format!("{h}({x}, {y})")
4186 }
4187
4188 fn value(&mut self, e: &Expr) -> String {
4189 if !matches!(e, Expr::Mat(_)) {
4196 if let Some(m) = flatten_matrix_value(e) {
4197 if !m.is_empty() {
4198 let mut parts: Vec<String> = Vec::with_capacity(m.len());
4199 for r in &m {
4200 let mut cols: Vec<String> = Vec::with_capacity(r.len());
4201 for cell in r {
4202 cols.push(self.node(cell, false));
4203 }
4204 parts.push(format!("vec![{}]", cols.join(", ")));
4205 }
4206 return format!("vec![{}]", parts.join(", "));
4207 }
4208 }
4209 }
4210 match e {
4211 Expr::Num(v) => format!("({v:?}, 0.0)"),
4212 Expr::Var(n) if n == "j" => "(0.0, 1.0)".to_string(),
4213 Expr::Var(n) if self.cx_vars.contains(n) => rust_ident(n),
4214 Expr::Var(n) => format!("({}, 0.0)", rust_ident(n)),
4215 Expr::Neg(a) => self.call1("__c_neg", a),
4216 Expr::Add(a, b) => self.call2("__c_add", a, b),
4217 Expr::Sub(a, b) => self.call2("__c_sub", a, b),
4218 Expr::Mul(a, b) => self.call2("__c_mul", a, b),
4219 Expr::Div(a, b) => self.call2("__c_div", a, b),
4220 Expr::Pow(a, b) => match b.as_ref() {
4221 Expr::Num(n) if *n == 2.0 => self.call2("__c_mul", a, a),
4222 Expr::Num(n) if *n == 0.5 => self.call1("__c_sqrt", a),
4223 Expr::Num(n) if *n == -1.0 => {
4226 let x = self.node(a, false);
4227 let h = self.help("__c_div");
4228 format!("{h}((1.0, 0.0), {x})")
4229 }
4230 Expr::Num(n) if *n == -0.5 => {
4231 let x = self.node(a, false);
4232 let s = self.help("__c_sqrt");
4233 let d = self.help("__c_div");
4234 format!("{d}((1.0, 0.0), {s}({x}))")
4235 }
4236 Expr::Num(n) => {
4237 let x = self.node(a, false);
4238 let h = self.help("__c_powf");
4239 format!("{h}({x}, {n:?})")
4240 }
4241 _ => self.call2("__c_pow", a, b),
4242 },
4243 Expr::Call(name, args) => {
4244 if matches!(name.as_str(), "__quad_root_1" | "__quad_root_2") {
4245 if args.len() != 3 {
4246 return "compile_error!(\"the internal quadratic-root operator needs three coefficients\")".to_string();
4247 }
4248 let a = self.node(&args[0], false);
4249 let b = self.node(&args[1], false);
4250 let c = self.node(&args[2], false);
4251 for helper in [
4252 "__c_add", "__c_sub", "__c_mul", "__c_neg", "__c_div", "__c_conj",
4253 "__c_sqrt",
4254 ] {
4255 self.help(helper);
4256 }
4257 let helper = self.help("__c_quad_root");
4258 let first = if name == "__quad_root_1" {
4259 "true"
4260 } else {
4261 "false"
4262 };
4263 return format!("{helper}({a}, {b}, {c}, {first})");
4264 }
4265 let Some(arg0) = args.first() else {
4266 return "compile_error!(\"the function call is missing its argument\")".to_string();
4267 };
4268 if matches!(
4276 name.as_str(),
4277 "det"
4278 | "trace"
4279 | "adjoint"
4280 | "inv"
4281 | "solve"
4282 | "roots"
4283 | "poly_coeffs"
4284 | "dot"
4285 | "norm"
4286 ) {
4287 return match expand_call(e) {
4288 Some(x) => self.node(&x, false),
4289 None => "compile_error!(\"det/trace/adjoint/inv/solve/roots/dot/norm need a concrete matrix literal\")".to_string(),
4290 };
4291 }
4292 let helper = match name.as_str() {
4293 "exp" => "__c_exp",
4294 "ln" | "log" => "__c_ln",
4295 "sqrt" => "__c_sqrt",
4296 "sin" => "__c_sin",
4297 "cos" => "__c_cos",
4298 "tan" => "__c_tan",
4299 "sinh" => "__c_sinh",
4300 "cosh" => "__c_cosh",
4301 "tanh" => "__c_tanh",
4302 "abs" => "__c_abs",
4303 "arg" => "__c_arg",
4304 "conj" => "__c_conj",
4305 "re" => "__c_re",
4306 "im" => "__c_im",
4307 _ => {
4310 return "compile_error!(\"the complex lane does not support this function (exp/ln/sqrt/sin/cos/tan/sinh/cosh/tanh/abs/arg/conj/re/im)\")".to_string()
4311 }
4312 };
4313 self.call1(helper, arg0)
4314 }
4315 Expr::Sum {
4318 var,
4319 lower,
4320 upper,
4321 body,
4322 } => {
4323 if let (Expr::Num(lo), Expr::Num(hi)) = (lower.as_ref(), upper.as_ref()) {
4324 if math::fract(*lo) == 0.0 && math::fract(*hi) == 0.0 && (hi - lo) < 64.0 {
4325 let mut parts = Vec::new();
4326 let mut k = *lo;
4327 while k <= *hi {
4328 let b = subst(body, var, &num(k));
4329 parts.push(self.node(&b, false));
4330 k += 1.0;
4331 }
4332 if parts.is_empty() {
4335 return "(0.0, 0.0)".to_string();
4336 }
4337 let mut acc = parts.remove(0);
4338 for p in parts {
4339 let h = self.help("__c_add");
4340 acc = format!("{h}({acc}, {p})");
4341 }
4342 return acc;
4343 }
4344 }
4345 "compile_error!(\"a non-constant sum bound must go through the .formula file lane\")".to_string()
4346 }
4347 Expr::Integral { .. } => {
4348 "compile_error!(\"definite integrals must go through the .formula file lane (numeric integration is a runtime loop)\")"
4349 .to_string()
4350 }
4351 Expr::Mat(rows) => {
4359 let mut parts: Vec<String> = Vec::with_capacity(rows.len());
4360 for r in rows {
4361 let mut cols: Vec<String> = Vec::with_capacity(r.len());
4362 for cell in r {
4363 cols.push(self.node(cell, false));
4364 }
4365 parts.push(format!("vec![{}]", cols.join(", ")));
4366 }
4367 format!("vec![{}]", parts.join(", "))
4368 }
4369 Expr::Transpose(a) => match flatten_matrix_value(a) {
4374 Some(m) if !m.is_empty() && m.iter().all(|r| r.len() == m[0].len()) => {
4375 let (nr, nc) = (m.len(), m[0].len());
4376 let mut parts: Vec<String> = Vec::with_capacity(nc);
4377 for j in 0..nc {
4378 let mut cols: Vec<String> = Vec::with_capacity(nr);
4379 for row in &m {
4380 cols.push(self.node(&row[j], false));
4381 }
4382 parts.push(format!("vec![{}]", cols.join(", ")));
4383 }
4384 format!("vec![{}]", parts.join(", "))
4385 }
4386 _ => "compile_error!(\"a transpose in the complex lane needs a matrix literal whose shape is known at compile time\")".to_string(),
4387 },
4388 Expr::MatPattern(_) => {
4389 "compile_error!(\"the complex lane does not take pattern matrices (call `recognize_pattern` first to get a concrete shape)\")"
4390 .to_string()
4391 }
4392 Expr::Deriv(..) | Expr::Grad(_) | Expr::Laplacian(_) | Expr::Indexed { .. } => {
4393 "compile_error!(\"symbolic operators and indexed symbols must go through the .formula file lane\")".to_string()
4394 }
4395 }
4396 }
4397}
4398
4399pub fn emit_block_complex(root: &Expr) -> String {
4404 emit_block_complex_with(root, &[])
4405}
4406
4407pub fn emit_block_complex_with(root: &Expr, complex_vars: &[String]) -> String {
4413 let mut counts: HashMap<String, usize> = HashMap::new();
4414 count_nodes(root, &mut counts);
4415 let mut em = CEmit {
4416 counts,
4417 names: HashMap::new(),
4418 helpers: BTreeSet::new(),
4419 temps: Vec::new(),
4420 counter: 0,
4421 cx_vars: complex_vars.iter().cloned().collect(),
4422 };
4423 let body = em.node(root, true);
4424 let mut s = String::from("{\n");
4425 for h in &em.helpers {
4426 let line = complex_helper(h);
4427 for l in line.lines() {
4428 let _ = writeln!(s, " {l}");
4429 }
4430 }
4431 for t in &em.temps {
4432 let _ = writeln!(s, " {t}");
4433 }
4434 let _ = writeln!(s, " {body}");
4435 s.push_str(" }");
4436 s
4437}
4438
4439fn count_nodes(e: &Expr, counts: &mut HashMap<String, usize>) {
4440 *counts.entry(key(e)).or_insert(0) += 1;
4441 match e {
4442 Expr::Num(_) | Expr::Var(_) => {}
4443 Expr::Add(a, b) | Expr::Sub(a, b) | Expr::Mul(a, b) | Expr::Div(a, b) | Expr::Pow(a, b) => {
4444 count_nodes(a, counts);
4445 count_nodes(b, counts);
4446 }
4447 Expr::Neg(a) => count_nodes(a, counts),
4448 Expr::Call(_, args) => {
4449 for a in args {
4450 count_nodes(a, counts);
4451 }
4452 }
4453 Expr::Mat(rows) => {
4454 for r in rows {
4455 for c in r {
4456 count_nodes(c, counts);
4457 }
4458 }
4459 }
4460 Expr::MatPattern(p) => {
4461 for e in p.elements() {
4462 count_nodes(e, counts);
4463 }
4464 }
4465 Expr::Transpose(a) => count_nodes(a, counts),
4466 Expr::Deriv(u, _) | Expr::Grad(u) | Expr::Laplacian(u) => count_nodes(u, counts),
4467 Expr::Sum {
4468 lower, upper, body, ..
4469 }
4470 | Expr::Integral {
4471 lower, upper, body, ..
4472 } => {
4473 count_nodes(lower, counts);
4474 count_nodes(upper, counts);
4475 count_nodes(body, counts);
4476 }
4477 Expr::Indexed { name, indices } => {
4478 *counts.entry(format!("${name}")).or_insert(0) += 1;
4479 let _ = indices;
4480 }
4481 }
4482}
4483
4484fn emit_node(
4485 e: &Expr,
4486 is_root: bool,
4487 counts: &HashMap<String, usize>,
4488 names: &mut HashMap<String, String>,
4489 out: &mut Vec<String>,
4490 counter: &mut usize,
4491 fx: Fx,
4492) -> (String, u8) {
4493 let k = key(e);
4494 let shareable = !is_root
4495 && counts.get(&k).copied().unwrap_or(0) >= 2
4496 && !matches!(e, Expr::Num(_) | Expr::Var(_));
4497 if shareable {
4498 if let Some(n) = names.get(&k) {
4499 return (n.clone(), 9);
4500 }
4501 }
4502 let (text, p) = emit_uncached(e, counts, names, out, counter, fx);
4503 if shareable {
4504 let name = format!("__t{counter}");
4505 *counter += 1;
4506 out.push(format!("let {name} = {text};"));
4507 names.insert(k, name.clone());
4508 return (name, 9);
4509 }
4510 (text, p)
4511}
4512
4513fn matrix_ish(e: &Expr) -> bool {
4517 match e {
4518 Expr::Mat(_) | Expr::MatPattern(_) | Expr::Transpose(_) | Expr::Indexed { .. } => true,
4519 Expr::Add(a, b) | Expr::Sub(a, b) | Expr::Mul(a, b) | Expr::Div(a, b) | Expr::Pow(a, b) => {
4520 matrix_ish(a) || matrix_ish(b)
4521 }
4522 Expr::Neg(a) => matrix_ish(a),
4523 Expr::Call(_, args) => args.iter().any(matrix_ish),
4524 _ => false,
4525 }
4526}
4527
4528fn mat_mul_exprs(ma: &[Vec<Expr>], mb: &[Vec<Expr>]) -> Option<Vec<Vec<Expr>>> {
4530 let inner = ma.first()?.len();
4531 if mb.len() != inner {
4532 return None;
4533 }
4534 let cols = mb.first()?.len();
4535 let mut out: Vec<Vec<Expr>> = Vec::with_capacity(ma.len());
4536 for row in ma {
4537 let mut r2: Vec<Expr> = Vec::with_capacity(cols);
4538 #[allow(clippy::needless_range_loop)]
4541 for j in 0..cols {
4542 let mut acc: Option<Expr> = None;
4543 for (k, x) in row.iter().enumerate() {
4544 let prod = mul(x.clone(), mb[k][j].clone());
4545 acc = Some(match acc {
4546 None => prod,
4547 Some(p) => add(p, prod),
4548 });
4549 }
4550 r2.push(acc?);
4551 }
4552 out.push(r2);
4553 }
4554 Some(out)
4555}
4556
4557pub fn flatten_matrix_value(e: &Expr) -> Option<Vec<Vec<Expr>>> {
4566 fn same_shape(a: &[Vec<Expr>], b: &[Vec<Expr>]) -> bool {
4567 a.len() == b.len()
4568 && a.first().map(|r| r.len()) == b.first().map(|r| r.len())
4569 && a.iter().zip(b.iter()).all(|(x, y)| x.len() == y.len())
4570 }
4571 fn zip(
4572 a: Vec<Vec<Expr>>,
4573 b: Vec<Vec<Expr>>,
4574 f: fn(Expr, Expr) -> Expr,
4575 ) -> Option<Vec<Vec<Expr>>> {
4576 if !same_shape(&a, &b) {
4577 return None;
4578 }
4579 Some(
4580 a.into_iter()
4581 .zip(b)
4582 .map(|(ra, rb)| ra.into_iter().zip(rb).map(|(x, y)| f(x, y)).collect())
4583 .collect(),
4584 )
4585 }
4586 let scale = |m: Vec<Vec<Expr>>, k: Expr| -> Vec<Vec<Expr>> {
4587 m.into_iter()
4588 .map(|r| r.into_iter().map(|x| mul(k.clone(), x)).collect())
4589 .collect()
4590 };
4591 match e {
4592 Expr::Mat(rows) => Some(rows.clone()),
4593 Expr::Transpose(a) => {
4594 let m = flatten_matrix_value(a)?;
4595 let cols = m.first()?.len();
4596 if m.iter().any(|r| r.len() != cols) {
4597 return None;
4598 }
4599 Some(
4600 (0..cols)
4601 .map(|j| m.iter().map(|r| r[j].clone()).collect())
4602 .collect(),
4603 )
4604 }
4605 Expr::Neg(a) => {
4606 let m = flatten_matrix_value(a)?;
4607 Some(
4608 m.into_iter()
4609 .map(|r| r.into_iter().map(neg).collect())
4610 .collect(),
4611 )
4612 }
4613 Expr::Div(a, b) => {
4620 if matrix_ish(b) {
4621 return None;
4622 }
4623 let m = flatten_matrix_value(a)?;
4624 Some(
4625 m.into_iter()
4626 .map(|r| r.into_iter().map(|x| div(x, (**b).clone())).collect())
4627 .collect(),
4628 )
4629 }
4630 Expr::Call(name, _) if name == "adjoint" || name == "inv" => {
4633 flatten_matrix_value(&expand_matrix_call(e)?)
4634 }
4635 Expr::Call(name, _) if name == "solve" || name == "roots" || name == "poly_coeffs" => {
4638 flatten_matrix_value(&expand_call(e)?)
4639 }
4640 Expr::Add(a, b) => zip(flatten_matrix_value(a)?, flatten_matrix_value(b)?, add),
4641 Expr::Sub(a, b) => zip(flatten_matrix_value(a)?, flatten_matrix_value(b)?, sub),
4642 Expr::Mul(a, b) => match (flatten_matrix_value(a), flatten_matrix_value(b)) {
4643 (Some(ma), Some(mb)) => mat_mul_exprs(&ma, &mb),
4644 (Some(ma), None) if !matrix_ish(b) => Some(scale(ma, (**b).clone())),
4646 (None, Some(mb)) if !matrix_ish(a) => Some(scale(mb, (**a).clone())),
4647 _ => None,
4648 },
4649 Expr::Pow(a, b) => match b.as_ref() {
4654 Expr::Num(k) if *k == 0.0 => {
4655 let m = flatten_matrix_value(a)?;
4656 if !m.iter().all(|r| r.len() == m.len()) {
4657 return None;
4658 }
4659 Some(
4662 (0..m.len())
4663 .map(|i| {
4664 (0..m.len())
4665 .map(|j| num(if i == j { 1.0 } else { 0.0 }))
4666 .collect()
4667 })
4668 .collect(),
4669 )
4670 }
4671 Expr::Num(k) if *k >= 1.0 && math::fract(*k) == 0.0 && *k <= 8.0 => {
4672 let m = flatten_matrix_value(a)?;
4673 if !m.iter().all(|r| r.len() == m.len()) {
4674 return None;
4675 }
4676 let mut acc = m.clone();
4677 for _ in 1..(*k as usize) {
4678 acc = mat_mul_exprs(&acc, &m)?;
4679 }
4680 Some(acc)
4681 }
4682 _ => None,
4683 },
4684 _ => None,
4685 }
4686}
4687
4688fn has_var(e: &Expr, var: &str) -> bool {
4690 vars_of(e).iter().any(|v| v == var)
4691}
4692
4693fn lin_coeffs(e: &Expr, var: &str) -> Result<(Expr, Expr), Error> {
4700 use Expr as E;
4701 let zero = || num(0.0);
4702 Ok(match e {
4703 E::Num(_) | E::Indexed { .. } => (zero(), e.clone()),
4704 E::Var(n) => {
4705 if n == var {
4706 (num(1.0), zero())
4707 } else {
4708 (zero(), e.clone())
4709 }
4710 }
4711 E::Add(x, y) => {
4712 let (a1, b1) = lin_coeffs(x, var)?;
4713 let (a2, b2) = lin_coeffs(y, var)?;
4714 (add(a1, a2), add(b1, b2))
4715 }
4716 E::Sub(x, y) => {
4717 let (a1, b1) = lin_coeffs(x, var)?;
4718 let (a2, b2) = lin_coeffs(y, var)?;
4719 (sub(a1, a2), sub(b1, b2))
4720 }
4721 E::Neg(x) => {
4722 let (a, b) = lin_coeffs(x, var)?;
4723 (neg(a), neg(b))
4724 }
4725 E::Mul(x, y) => match (has_var(x, var), has_var(y, var)) {
4726 (false, false) => (zero(), e.clone()),
4727 (true, false) => {
4728 let (a, b) = lin_coeffs(x, var)?;
4729 (mul(a, (**y).clone()), mul(b, (**y).clone()))
4730 }
4731 (false, true) => {
4732 let (a, b) = lin_coeffs(y, var)?;
4733 (mul((**x).clone(), a), mul((**x).clone(), b))
4734 }
4735 (true, true) => {
4736 return Err(Error::NonlinearEquation {
4737 name: var.to_string(),
4738 why: "the unknown appears twice in one product".to_string(),
4739 })
4740 }
4741 },
4742 E::Div(x, y) => {
4743 if has_var(y, var) {
4744 return Err(Error::NonlinearEquation {
4745 name: var.to_string(),
4746 why: "the unknown appears in a denominator".to_string(),
4747 });
4748 }
4749 let (a, b) = lin_coeffs(x, var)?;
4750 (div(a, (**y).clone()), div(b, (**y).clone()))
4751 }
4752 E::Pow(x, y) => {
4753 if has_var(y, var) {
4760 return Err(Error::NonlinearEquation {
4761 name: var.to_string(),
4762 why: "it appears in an exponent".into(),
4763 });
4764 }
4765 if !has_var(x, var) {
4766 (zero(), e.clone())
4767 } else if matches!(y.as_ref(), E::Num(n) if *n == 1.0) {
4768 lin_coeffs(x, var)?
4769 } else {
4770 return Err(Error::NonlinearEquation {
4771 name: var.to_string(),
4772 why: "the unknown appears in a power or exponent".to_string(),
4773 });
4774 }
4775 }
4776 E::Call(name, args) => {
4777 if args.iter().any(|a| has_var(a, var)) {
4782 return Err(Error::NonlinearEquation {
4783 name: var.to_string(),
4784 why: format!("the unknown appears inside `{name}`"),
4785 });
4786 }
4787 (zero(), e.clone())
4788 }
4789 _ => {
4790 if has_var(e, var) {
4791 return Err(Error::NonlinearEquation {
4792 name: var.to_string(),
4793 why: "this construct is not supported by the linear solver".into(),
4794 });
4795 }
4796 (zero(), e.clone())
4797 }
4798 })
4799}
4800
4801pub fn solve_linear(e: &Expr, var: &str) -> Result<Expr, Error> {
4809 let (a, b) = lin_coeffs(e, var)?;
4810 let (a, b) = (simplify(&a), simplify(&b));
4815 fn has_matrix_literal(e: &Expr) -> bool {
4827 match e {
4828 Expr::Mat(_) | Expr::MatPattern(_) => true,
4829 Expr::Add(x, y)
4830 | Expr::Sub(x, y)
4831 | Expr::Mul(x, y)
4832 | Expr::Div(x, y)
4833 | Expr::Pow(x, y) => has_matrix_literal(x) || has_matrix_literal(y),
4834 Expr::Neg(x) | Expr::Transpose(x) => has_matrix_literal(x),
4835 _ => false,
4836 }
4837 }
4838 if is_matrix_value(&a)
4839 || is_matrix_value(&b)
4840 || has_matrix_literal(&a)
4841 || has_matrix_literal(&b)
4842 {
4843 return Err(Error::MatrixCoefficient(
4844 "`solve` solves scalar equations only; write matrix equations as `inv(A) * b`, or pass a list of scalar equations".into(),
4845 ));
4846 }
4847 if let Expr::Num(v) = simplify(&a) {
4851 if v == 0.0 {
4852 return Err(Error::NonlinearEquation {
4853 name: var.to_string(),
4854 why: "the equation has no linear term in it".into(),
4855 });
4856 }
4857 }
4858 Ok(simplify(&neg(div(b, a))))
4859}
4860
4861fn signed_terms(e: &Expr, sign: f64, out: &mut Vec<(f64, Expr)>) {
4864 match e {
4865 Expr::Add(a, b) => {
4866 signed_terms(a, sign, out);
4867 signed_terms(b, sign, out);
4868 }
4869 Expr::Sub(a, b) => {
4870 signed_terms(a, sign, out);
4871 signed_terms(b, -sign, out);
4872 }
4873 Expr::Neg(a) => signed_terms(a, -sign, out),
4874 _ => out.push((sign, e.clone())),
4875 }
4876}
4877
4878fn term_factors(e: &Expr) -> Option<(f64, Vec<String>)> {
4890 fn go(e: &Expr) -> Option<(f64, Vec<String>)> {
4897 match e {
4898 Expr::Num(v) => Some((*v, Vec::new())),
4899 Expr::Neg(a) => go(a).map(|(c, k)| (-c, k)),
4900 Expr::Mul(a, b) => {
4901 let (ca, mut ka) = go(a)?;
4902 let (cb, kb) = go(b)?;
4903 ka.extend(kb);
4904 Some((ca * cb, ka))
4905 }
4906 Expr::Div(a, b) => match b.as_ref() {
4909 Expr::Num(d) if *d != 0.0 => go(a).map(|(c, k)| (c / d, k)),
4910 _ => Some((1.0, vec![key(e)])),
4911 },
4912 Expr::Pow(a, b) => match b.as_ref() {
4913 Expr::Num(n) if *n >= 0.0 && math::fract(*n) == 0.0 && *n <= 8.0 => {
4916 let (cb, kb) = go(a)?;
4917 let mut keys = Vec::with_capacity(kb.len() * (*n as usize));
4918 for _ in 0..(*n as usize) {
4919 keys.extend(kb.iter().cloned());
4920 }
4921 Some((math::powi(cb, *n as i32), keys))
4922 }
4923 _ => Some((1.0, vec![key(e)])),
4928 },
4929 _ => Some((1.0, vec![key(e)])),
4930 }
4931 }
4932 let (coef, mut keys) = go(e)?;
4933 keys.sort();
4934 Some((coef, keys))
4935}
4936
4937pub fn is_structurally_zero(e: &Expr) -> bool {
4954 let s = simplify(e);
4955 if matches!(s, Expr::Num(v) if v == 0.0) {
4956 return true;
4957 }
4958 let mut terms: Vec<(f64, Expr)> = Vec::new();
4959 signed_terms(&s, 1.0, &mut terms);
4960 let mut acc: BTreeMap<String, f64> = BTreeMap::new();
4961 for (sign, t) in terms {
4962 let Some((coef, keys)) = term_factors(&t) else {
4965 return false;
4966 };
4967 let k = keys.join("\u{1}");
4968 *acc.entry(k).or_insert(0.0) += sign * coef;
4969 }
4970 acc.values().all(|v| *v == 0.0)
4971}
4972
4973#[allow(clippy::needless_range_loop)]
4983fn lin_coeffs_multi(e: &Expr, vars: &[String]) -> Result<(Vec<Expr>, Expr), Error> {
4984 use Expr as E;
4985 let n = vars.len();
4986 let zeros = || vec![num(0.0); n];
4987 let hit = |x: &Expr| vars.iter().any(|v| has_var(x, v));
4988 Ok(match e {
4989 E::Num(_) | E::Indexed { .. } => (zeros(), e.clone()),
4990 E::Var(name) => match vars.iter().position(|v| v == name) {
4991 Some(k) => {
4992 let mut a = zeros();
4993 a[k] = num(1.0);
4994 (a, num(0.0))
4995 }
4996 None => (zeros(), e.clone()),
4997 },
4998 E::Add(x, y) => {
4999 let (mut a, b) = lin_coeffs_multi(x, vars)?;
5000 let (a2, b2) = lin_coeffs_multi(y, vars)?;
5001 for k in 0..n {
5002 a[k] = add(a[k].clone(), a2[k].clone());
5003 }
5004 (a, add(b, b2))
5005 }
5006 E::Sub(x, y) => {
5007 let (mut a, b) = lin_coeffs_multi(x, vars)?;
5008 let (a2, b2) = lin_coeffs_multi(y, vars)?;
5009 for k in 0..n {
5010 a[k] = sub(a[k].clone(), a2[k].clone());
5011 }
5012 (a, sub(b, b2))
5013 }
5014 E::Neg(x) => {
5015 let (mut a, b) = lin_coeffs_multi(x, vars)?;
5016 for k in 0..n {
5017 a[k] = neg(a[k].clone());
5018 }
5019 (a, neg(b))
5020 }
5021 E::Mul(x, y) => match (hit(x), hit(y)) {
5022 (false, false) => (zeros(), e.clone()),
5023 (true, true) => {
5024 let involved: Vec<&str> = vars
5028 .iter()
5029 .filter(|v| has_var(e, v))
5030 .map(String::as_str)
5031 .collect();
5032 return Err(Error::NonlinearEquation {
5033 name: involved.join(", "),
5034 why: "both factors contain an unknown".into(),
5035 });
5036 }
5037 (true, false) => {
5040 let (mut a, b) = lin_coeffs_multi(x, vars)?;
5041 for k in 0..n {
5042 a[k] = mul(a[k].clone(), (**y).clone());
5043 }
5044 (a, mul(b, (**y).clone()))
5045 }
5046 (false, true) => {
5047 let (mut a, b) = lin_coeffs_multi(y, vars)?;
5048 for k in 0..n {
5049 a[k] = mul((**x).clone(), a[k].clone());
5050 }
5051 (a, mul((**x).clone(), b))
5052 }
5053 },
5054 E::Div(x, y) => {
5055 if hit(y) {
5056 return Err(Error::NonlinearEquation {
5057 name: "the equation".into(),
5058 why: "the unknown appears in a denominator".into(),
5059 });
5060 }
5061 let (mut a, b) = lin_coeffs_multi(x, vars)?;
5062 for k in 0..n {
5063 a[k] = div(a[k].clone(), (**y).clone());
5064 }
5065 (a, div(b, (**y).clone()))
5066 }
5067 E::Pow(x, y) => {
5068 if hit(y) {
5075 return Err(Error::NonlinearEquation {
5076 name: "the equation".into(),
5077 why: "the unknown appears in an exponent".into(),
5078 });
5079 }
5080 if !hit(x) {
5081 (zeros(), e.clone())
5082 } else if matches!(y.as_ref(), E::Num(m) if *m == 1.0) {
5083 lin_coeffs_multi(x, vars)?
5084 } else {
5085 return Err(Error::NonlinearEquation {
5086 name: "the equation".into(),
5087 why: "the unknown appears in a power".into(),
5088 });
5089 }
5090 }
5091 E::Call(name, args) => {
5092 if args.iter().any(&hit) {
5095 return Err(Error::NonlinearEquation {
5096 name: name.clone(),
5097 why: "the unknown appears inside a function argument".to_string(),
5098 });
5099 }
5100 (zeros(), e.clone())
5101 }
5102 _ => {
5103 if hit(e) {
5104 return Err(Error::NonlinearEquation {
5105 name: "the equation".into(),
5106 why: "this construct is not supported by the linear solver".into(),
5107 });
5108 }
5109 (zeros(), e.clone())
5110 }
5111 })
5112}
5113
5114fn flat_mat_items(e: &Expr) -> Option<Vec<Expr>> {
5119 match e {
5120 Expr::Mat(rows) => {
5121 let items: Vec<Expr> = rows.iter().flatten().cloned().collect();
5122 if items.is_empty() {
5123 None
5124 } else {
5125 Some(items)
5126 }
5127 }
5128 _ => None,
5129 }
5130}
5131
5132fn mat_var_names(e: &Expr) -> Option<Vec<String>> {
5134 let mut out = Vec::new();
5135 for c in flat_mat_items(e)? {
5136 match c {
5137 Expr::Var(n) => out.push(n),
5138 _ => return None,
5139 }
5140 }
5141 Some(out)
5142}
5143
5144#[allow(clippy::needless_range_loop)]
5162pub fn solve_system(eqs: &[Expr], vars: &[String]) -> Result<Expr, Error> {
5163 if vars.is_empty() {
5164 return Err(Error::InvalidInput(
5165 "the list of unknowns is empty; at least one is required".into(),
5166 ));
5167 }
5168 if eqs.is_empty() {
5169 return Err(Error::InvalidInput(
5170 "the list of equations is empty; at least one is required".into(),
5171 ));
5172 }
5173 let mut seen = BTreeSet::new();
5174 for v in vars {
5175 if !seen.insert(v.as_str()) {
5176 return Err(Error::InvalidInput(format!(
5177 "the unknown `{v}` appears twice in the list"
5178 )));
5179 }
5180 }
5181 let (m, n) = (eqs.len(), vars.len());
5182 let mut aug: Vec<Vec<Expr>> = Vec::with_capacity(m);
5184 for (i, eq) in eqs.iter().enumerate() {
5185 let (a, b) = lin_coeffs_multi(eq, vars).map_err(|error| Error::InEquation {
5190 index: i + 1,
5191 error: Box::new(error),
5192 })?;
5193 for (j, aj) in a.iter().enumerate() {
5197 if is_matrix_value(&simplify(aj)) {
5198 return Err(Error::InEquation {
5199 index: i + 1,
5200 error: Box::new(Error::MatrixCoefficient(vars[j].clone())),
5201 });
5202 }
5203 }
5204 if is_matrix_value(&simplify(&b)) {
5205 return Err(Error::InEquation {
5207 index: i + 1,
5208 error: Box::new(Error::MatrixCoefficient("<constant>".into())),
5209 });
5210 }
5211 let mut row = a;
5212 row.push(neg(b));
5213 aug.push(row);
5214 }
5215 let is_zero = |e: &Expr| is_structurally_zero(e);
5220 let mut pivots = 0usize;
5221 for col in 0..n {
5222 let Some(p) = (pivots..m).find(|&r| !is_zero(&aug[r][col])) else {
5223 return Err(Error::Underdetermined(vars[col].clone()));
5224 };
5225 aug.swap(pivots, p);
5226 let piv = aug[pivots][col].clone();
5233 for c in (col + 1)..=n {
5234 aug[pivots][c] = simplify(&div(aug[pivots][c].clone(), piv.clone()));
5235 }
5236 aug[pivots][col] = num(1.0);
5237 for r in 0..m {
5241 if r == pivots || is_zero(&aug[r][col]) {
5242 continue;
5243 }
5244 let f = aug[r][col].clone();
5245 for c in (col + 1)..=n {
5246 aug[r][c] = simplify(&sub(
5247 aug[r][c].clone(),
5248 mul(f.clone(), aug[pivots][c].clone()),
5249 ));
5250 }
5251 aug[r][col] = num(0.0);
5252 }
5253 pivots += 1;
5254 }
5255 for r in pivots..m {
5258 if !is_zero(&aug[r][n]) {
5259 return Err(Error::Inconsistent);
5260 }
5261 }
5262 let sols: Vec<Vec<Expr>> = (0..n).map(|j| vec![simplify(&aug[j][n].clone())]).collect();
5264 Ok(Expr::Mat(sols))
5265}
5266
5267pub fn poly_coeffs_vec(e: &Expr, var: &str) -> Result<Expr, Error> {
5281 let coeffs = poly_coeffs(e, var).ok_or_else(|| Error::NotPolynomial {
5282 var: var.to_string(),
5283 })?;
5284 let n = coeffs.len();
5285 let mut trimmed = coeffs;
5286 while trimmed.len() > 1
5287 && matches!(simplify(&trimmed[trimmed.len() - 1]), Expr::Num(v) if v == 0.0)
5288 {
5289 trimmed.pop();
5290 }
5291 let out: Vec<Expr> = trimmed.into_iter().map(|c| simplify(&c)).collect();
5292 if out.len() == 1 && matches!(out[0], Expr::Num(v) if v == 0.0) {
5293 return Err(Error::InvalidInput(format!(
5294 "`poly_coeffs`: `{var}` is a zero polynomial, so there are no coefficients to report"
5295 )));
5296 }
5297 let _ = n;
5298 Ok(Expr::Mat(vec![out]))
5301}
5302
5303pub fn solve_poly(e: &Expr, var: &str) -> Result<Expr, Error> {
5327 let coeffs = poly_coeffs(e, var).ok_or_else(|| Error::NotPolynomial {
5328 var: var.to_string(),
5329 })?;
5330 let mut c = coeffs;
5332 while c.len() > 1 && matches!(simplify(&c[c.len() - 1]), Expr::Num(v) if v == 0.0) {
5333 c.pop();
5334 }
5335 let mut normalized = Vec::with_capacity(c.len());
5340 for (k, coef) in c.iter().enumerate() {
5341 let cs = simplify(coef);
5342 if is_matrix_value(&cs) {
5343 return Err(Error::MatrixCoefficient(format!(
5344 "`roots`: the degree-{k} coefficient is matrix-valued; root finding handles scalar coefficients only"
5345 )));
5346 }
5347 normalized.push(cs);
5348 }
5349 c = normalized;
5350 match c.len() - 1 {
5351 0 => Err(Error::NonlinearEquation {
5352 name: var.to_string(),
5353 why: "the equation does not contain it, so there is nothing to solve for".into(),
5354 }),
5355 1 => Ok(Expr::Mat(vec![vec![simplify(&neg(div(
5363 c[0].clone(),
5364 c[1].clone(),
5365 )))]])),
5366 2 => {
5367 let (a, b, c0) = (c[2].clone(), c[1].clone(), c[0].clone());
5368 let r1 = Expr::Call(
5374 "__quad_root_1".into(),
5375 vec![a.clone(), b.clone(), c0.clone()],
5376 );
5377 let r2 = Expr::Call("__quad_root_2".into(), vec![a, b, c0]);
5378 Ok(Expr::Mat(vec![vec![r1], vec![r2]]))
5379 }
5380 n => Err(Error::InvalidInput(format!(
5381 "`roots` solves degree 1–2 only (got degree {n}): closed forms above that are unstable in floating point, and this crate does not offer a look-exact approximation — reduce the degree first, or compute the coefficients numerically and use a numeric root finder"
5382 ))),
5383 }
5384}
5385
5386fn stable_quadratic_root(first: bool, a: C, b: C, c: C) -> Result<C, Error> {
5393 let d = b.mul(b).sub(C::real(4.0).mul(a).mul(c));
5394 let s = d.sqrt();
5395 let q_is_first = b.conj().mul(s).re >= 0.0;
5398 let signed_s = if q_is_first { s } else { s.neg() };
5399 let q = b.add(signed_s).mul(C::real(-0.5));
5400 if q.re == 0.0 && q.im == 0.0 {
5401 return b.neg().div(C::real(2.0).mul(a));
5404 }
5405 let large = q.div(a)?;
5406 let small = c.div(q)?;
5407 Ok(if first == q_is_first { large } else { small })
5408}
5409
5410pub fn expand_deep(e: &Expr) -> Expr {
5425 fn go(e: &Expr, depth: usize) -> Expr {
5426 if depth > MAX_DEPTH {
5432 return e.clone();
5433 }
5434 if let Some(x) = expand_call(e) {
5437 return go(&x, depth + 1);
5438 }
5439 match e {
5440 Expr::Num(_) | Expr::Var(_) | Expr::Indexed { .. } => e.clone(),
5441 Expr::MatPattern(p) => Expr::MatPattern(MatPattern {
5444 rows: p
5445 .rows
5446 .iter()
5447 .map(|r| {
5448 r.iter()
5449 .map(|c| match c {
5450 PatternCell::El(x) => PatternCell::El(go(x, depth + 1)),
5451 PatternCell::Dots => PatternCell::Dots,
5452 })
5453 .collect()
5454 })
5455 .collect(),
5456 }),
5457 Expr::Add(a, b) => add(go(a, depth + 1), go(b, depth + 1)),
5458 Expr::Sub(a, b) => sub(go(a, depth + 1), go(b, depth + 1)),
5459 Expr::Mul(a, b) => mul(go(a, depth + 1), go(b, depth + 1)),
5460 Expr::Div(a, b) => div(go(a, depth + 1), go(b, depth + 1)),
5461 Expr::Pow(a, b) => pow(go(a, depth + 1), go(b, depth + 1)),
5462 Expr::Neg(a) => neg(go(a, depth + 1)),
5463 Expr::Call(n, args) => {
5464 Expr::Call(n.clone(), args.iter().map(|a| go(a, depth + 1)).collect())
5465 }
5466 Expr::Mat(rows) => Expr::Mat(
5467 rows.iter()
5468 .map(|r| r.iter().map(|c| go(c, depth + 1)).collect())
5469 .collect(),
5470 ),
5471 Expr::Transpose(a) => transpose(go(a, depth + 1)),
5472 Expr::Deriv(u, by) => deriv(go(u, depth + 1), by.clone()),
5473 Expr::Grad(u) => grad(go(u, depth + 1)),
5474 Expr::Laplacian(u) => laplacian(go(u, depth + 1)),
5475 Expr::Sum {
5476 var,
5477 lower,
5478 upper,
5479 body,
5480 } => sum(
5481 var.clone(),
5482 go(lower, depth + 1),
5483 go(upper, depth + 1),
5484 go(body, depth + 1),
5485 ),
5486 Expr::Integral {
5487 var,
5488 lower,
5489 upper,
5490 body,
5491 } => integral(
5492 var.clone(),
5493 go(lower, depth + 1),
5494 go(upper, depth + 1),
5495 go(body, depth + 1),
5496 ),
5497 }
5498 }
5499 go(e, 0)
5500}
5501
5502#[allow(clippy::needless_range_loop)]
5512pub fn expand_matrix_call(e: &Expr) -> Option<Expr> {
5513 let Expr::Call(name, args) = e else {
5514 return None;
5515 };
5516 if args.len() != 1 {
5517 return None;
5518 }
5519 let m = flatten_matrix_value(&args[0])?;
5520 let n = m.len();
5521 if n == 0 {
5522 return None;
5523 }
5524 let square = |m: &[Vec<Expr>]| m.iter().all(|r| r.len() == m.len());
5527 match name.as_str() {
5528 "trace" => {
5529 if !square(&m) {
5530 return None;
5531 }
5532 Some(trace_of(&m))
5533 }
5534 "det" => {
5535 if !square(&m) {
5536 return None;
5537 }
5538 det_of(&m)
5539 }
5540 "norm" => {
5542 let mut acc: Option<Expr> = None;
5543 for row in &m {
5544 for x in row {
5545 let sq = mul(x.clone(), x.clone());
5546 acc = Some(match acc {
5547 None => sq,
5548 Some(a) => add(a, sq),
5549 });
5550 }
5551 }
5552 Some(Expr::Call("sqrt".into(), vec![acc?]))
5553 }
5554 "adjoint" => {
5558 #[allow(clippy::needless_range_loop)] let cols = m.first().map(|r| r.len()).unwrap_or(0);
5560 let mut t: Vec<Vec<Expr>> = Vec::with_capacity(cols);
5561 for j in 0..cols {
5562 let mut row: Vec<Expr> = Vec::with_capacity(n);
5563 for i in 0..n {
5564 row.push(Expr::Call("conj".into(), vec![m[i][j].clone()]));
5565 }
5566 t.push(row);
5567 }
5568 Some(Expr::Mat(t))
5569 }
5570 "inv" => {
5576 if n > 3 || !square(&m) {
5577 return None;
5578 }
5579 let det = det_of(&m)?;
5580 let mut adj: Vec<Vec<Expr>> = Vec::with_capacity(n);
5581 for i in 0..n {
5582 let mut row: Vec<Expr> = Vec::with_capacity(n);
5583 for j in 0..n {
5584 let cof = det_of(&minor(&m, j, i))?;
5586 let val = if (i + j) % 2 == 0 { cof } else { neg(cof) };
5587 row.push(div(val, det.clone()));
5588 }
5589 adj.push(row);
5590 }
5591 Some(Expr::Mat(adj))
5592 }
5593 _ => None,
5594 }
5595}
5596
5597fn trace_of(m: &[Vec<Expr>]) -> Expr {
5598 let mut acc = m[0][0].clone();
5599 for (i, row) in m.iter().enumerate().skip(1) {
5600 acc = add(acc, row[i].clone());
5601 }
5602 acc
5603}
5604
5605fn minor(m: &[Vec<Expr>], i: usize, j: usize) -> Vec<Vec<Expr>> {
5607 m.iter()
5608 .enumerate()
5609 .filter(|(r, _)| *r != i)
5610 .map(|(_, row)| {
5611 row.iter()
5612 .enumerate()
5613 .filter(|(c, _)| *c != j)
5614 .map(|(_, x)| x.clone())
5615 .collect()
5616 })
5617 .collect()
5618}
5619
5620fn det_of(m: &[Vec<Expr>]) -> Option<Expr> {
5627 let n = m.len();
5628 if m.iter().any(|r| r.len() != n) || n > 4 {
5629 return None;
5630 }
5631 if n == 0 {
5633 return Some(num(1.0));
5634 }
5635 if n == 1 {
5636 return Some(m[0][0].clone());
5637 }
5638 let mut acc: Option<Expr> = None;
5639 for (j, cell) in m[0].iter().enumerate() {
5640 let sub = det_of(&minor(m, 0, j))?;
5641 let term = mul(cell.clone(), sub);
5642 let term = if j % 2 == 0 { term } else { neg(term) };
5643 acc = Some(match acc {
5644 None => term,
5645 Some(a) => add(a, term),
5646 });
5647 }
5648 acc
5649}
5650
5651pub fn numeric_roots(coeffs: &[f64]) -> Result<Vec<C>, Error> {
5675 let mut c = coeffs.to_vec();
5676 while c.len() > 1 && c[c.len() - 1] == 0.0 {
5677 c.pop();
5678 }
5679 if c.iter().all(|v| *v == 0.0) {
5680 return Err(Error::InvalidInput(
5681 "zero polynomial: every number is a root, so the solution set is not determined".into(),
5682 ));
5683 }
5684 if c.iter().any(|v| !v.is_finite()) {
5685 return Err(Error::NonFiniteValue(
5686 "the polynomial coefficients contain inf/NaN, so numeric root finding is impossible"
5687 .into(),
5688 ));
5689 }
5690 let n = c.len() - 1;
5691 match n {
5692 0 => {
5693 return Err(Error::InvalidInput(
5694 "a constant polynomial (degree 0) has no roots".into(),
5695 ))
5696 }
5697 1 => {
5698 let r = -c[0] / c[1];
5704 if !r.is_finite() {
5705 return Err(Error::NonFiniteValue(
5706 "the solution of the linear equation overflows (the coefficient ratio exceeds the f64 range); rescale the variable and retry".into(),
5707 ));
5708 }
5709 return Ok(vec![C::new(r, 0.0)]);
5710 }
5711 _ => {}
5712 }
5713 if n > 64 {
5714 return Err(Error::InvalidInput(format!(
5715 "degree {n} exceeds the numeric root-finding limit of 64"
5716 )));
5717 }
5718 let lead = c[n];
5719 let a: Vec<f64> = c.iter().map(|v| v / lead).collect(); let geo = if a[0] == 0.0 || !a[0].is_finite() {
5733 0.0
5734 } else {
5735 math::powf(a[0].abs(), 1.0 / n as f64)
5736 };
5737 let radius = if geo.is_finite() && geo > 0.0 {
5738 geo
5739 } else {
5740 1.0 + a[..n].iter().fold(0.0f64, |m, v| m.max(v.abs()))
5741 };
5742 let seed = C::new(0.4, 0.9);
5744 let mut z: Vec<C> = Vec::with_capacity(n);
5745 let mut p = C::ONE;
5746 for _ in 0..n {
5747 z.push(C::new(p.re * radius, p.im * radius));
5748 p = p.mul(seed);
5749 }
5750 let scale_ref = radius.abs().max(1e-300);
5753 let mut converged = false;
5754 for _ in 0..1000 {
5755 let old = z.clone();
5756 let mut max_delta = 0.0f64;
5757 for i in 0..n {
5758 let mut val = C::new(a[n], 0.0);
5760 for k in (0..n).rev() {
5761 val = val.mul(old[i]).add(C::new(a[k], 0.0));
5762 }
5763 let mut den = C::ONE;
5766 for (j, zj) in old.iter().enumerate() {
5767 if j != i {
5768 den = den.mul(old[i].sub(*zj));
5769 }
5770 }
5771 if den.abs() < 1e-300 {
5772 z[i] = old[i].add(C::new(1e-6 * (1.0 + i as f64), 1e-6));
5775 max_delta = f64::INFINITY;
5776 continue;
5777 }
5778 let step = val.div(den)?;
5779 z[i] = old[i].sub(step);
5780 if !step.re.is_finite()
5781 || !step.im.is_finite()
5782 || !z[i].re.is_finite()
5783 || !z[i].im.is_finite()
5784 {
5785 return Err(Error::RootFindingFailed {
5790 reason: "the iteration produced inf/NaN (divergence)".into(),
5791 });
5792 }
5793 let rel = step.abs() / scale_ref;
5798 max_delta = if rel.is_finite() {
5799 max_delta.max(rel)
5800 } else {
5801 f64::INFINITY
5802 };
5803 }
5804 if max_delta <= 1e-10 {
5811 converged = true;
5812 break;
5813 }
5814 }
5815 if !converged {
5816 return Err(Error::RootFindingFailed {
5817 reason: "it did not converge within 1000 iterations".into(),
5818 });
5819 }
5820
5821 #[allow(clippy::needless_range_loop)]
5827 for i in 0..n {
5828 for _ in 0..60 {
5829 let mut p = C::new(a[n], 0.0);
5830 let mut dp = C::ZERO;
5831 for k in (0..n).rev() {
5832 dp = dp.mul(z[i]).add(p);
5833 p = p.mul(z[i]).add(C::new(a[k], 0.0));
5834 }
5835 if dp.abs() < 1e-300 {
5836 break;
5837 }
5838 let Ok(step) = p.div(dp) else { break };
5839 let next = z[i].sub(step);
5840 if !next.re.is_finite() || !next.im.is_finite() {
5841 break;
5842 }
5843 z[i] = next;
5844 let scale = z[i].abs().max(scale_ref * 1e-6).max(1e-300);
5848 if step.abs() <= 1e-15 * scale {
5849 break;
5850 }
5851 }
5852 }
5853
5854 for zi in &z {
5861 let mut p = C::new(a[n], 0.0);
5862 for k in (0..n).rev() {
5863 p = p.mul(*zi).add(C::new(a[k], 0.0));
5864 }
5865 let mut scale = 0.0f64;
5872 let mut pw = 1.0f64;
5873 #[allow(clippy::needless_range_loop)]
5876 for k in 0..=n {
5877 scale += a[k].abs() * pw;
5878 pw *= zi.abs();
5879 }
5880 let rel = if scale > 0.0 {
5883 p.abs() / scale
5884 } else {
5885 p.abs()
5886 };
5887 if rel > 1e-8 {
5888 return Err(Error::UnstableResidual {
5889 residual: rel,
5890 limit: 1e-8,
5891 });
5892 }
5893 }
5894
5895 for c in z.iter_mut() {
5909 let mag = c.abs();
5910 if mag > 0.0 && c.im.abs() <= 1e-12 * mag {
5911 c.im = 0.0;
5912 }
5913 }
5914 z.sort_by(|a, b| {
5916 a.re.partial_cmp(&b.re)
5917 .unwrap_or(core::cmp::Ordering::Equal)
5918 .then(
5919 a.im.partial_cmp(&b.im)
5920 .unwrap_or(core::cmp::Ordering::Equal),
5921 )
5922 });
5923 Ok(z)
5924}
5925
5926pub fn poly_coeffs(e: &Expr, var: &str) -> Option<Vec<Expr>> {
5927 use Expr as E;
5928 match e {
5929 E::Num(_) | E::Indexed { .. } => Some(vec![e.clone()]),
5930 E::Var(n) => {
5931 if n == var {
5932 Some(vec![num(0.0), num(1.0)])
5933 } else {
5934 Some(vec![e.clone()])
5935 }
5936 }
5937 E::Neg(a) => Some(poly_coeffs(a, var)?.into_iter().map(neg).collect()),
5938 E::Add(a, b) | E::Sub(a, b) => {
5939 let (ca, cb) = (poly_coeffs(a, var)?, poly_coeffs(b, var)?);
5940 let n = ca.len().max(cb.len());
5941 let mut out = Vec::with_capacity(n);
5942 for k in 0..n {
5943 let x = ca.get(k).cloned().unwrap_or_else(|| num(0.0));
5944 let y = cb.get(k).cloned().unwrap_or_else(|| num(0.0));
5945 out.push(if matches!(e, E::Add(..)) {
5946 add(x, y)
5947 } else {
5948 sub(x, y)
5949 });
5950 }
5951 Some(out)
5952 }
5953 E::Mul(a, b) => {
5954 let (ca, cb) = (poly_coeffs(a, var)?, poly_coeffs(b, var)?);
5955 let mut out = vec![num(0.0); ca.len() + cb.len() - 1];
5957 for (i, x) in ca.iter().enumerate() {
5958 for (j, y) in cb.iter().enumerate() {
5959 let prod = mul(x.clone(), y.clone());
5960 out[i + j] = add(core::mem::replace(&mut out[i + j], num(0.0)), prod);
5961 }
5962 }
5963 Some(out)
5964 }
5965 E::Div(a, b) => {
5966 if has_var(b, var) {
5967 return None;
5968 }
5969 Some(
5970 poly_coeffs(a, var)?
5971 .into_iter()
5972 .map(|c| div(c, (**b).clone()))
5973 .collect(),
5974 )
5975 }
5976 E::Pow(a, b) => match b.as_ref() {
5977 E::Num(n) if *n >= 0.0 && math::fract(*n) == 0.0 && *n <= 16.0 => {
5978 let c = poly_coeffs(a, var)?;
5979 let mut acc = vec![num(1.0)];
5980 for _ in 0..(*n as usize) {
5981 let mut next = vec![num(0.0); acc.len() + c.len() - 1];
5982 for (i, x) in acc.iter().enumerate() {
5983 for (j, y) in c.iter().enumerate() {
5984 let prod = mul(x.clone(), y.clone());
5985 next[i + j] = add(core::mem::replace(&mut next[i + j], num(0.0)), prod);
5986 }
5987 }
5988 acc = next;
5989 }
5990 Some(acc)
5991 }
5992 _ => None,
5993 },
5994 _ => {
5997 if has_var(e, var) {
5998 None
5999 } else {
6000 Some(vec![e.clone()])
6001 }
6002 }
6003 }
6004}
6005
6006fn is_explicit_poly(e: &Expr, var: &str) -> bool {
6009 match e {
6010 Expr::Pow(a, b) => {
6011 let base_is_var = matches!(a.as_ref(), Expr::Var(n) if n == var);
6012 let expo_num =
6013 matches!(b.as_ref(), Expr::Num(n) if *n >= 0.0 && math::fract(*n) == 0.0);
6014 base_is_var && expo_num
6015 }
6016 Expr::Num(_) | Expr::Var(_) | Expr::Indexed { .. } => true,
6017 Expr::Neg(a) => is_explicit_poly(a, var),
6018 Expr::Add(a, b) | Expr::Sub(a, b) | Expr::Mul(a, b) | Expr::Div(a, b) => {
6019 is_explicit_poly(a, var) && is_explicit_poly(b, var)
6020 }
6021 _ => !has_var(e, var),
6022 }
6023}
6024
6025pub fn horner_in(e: &Expr, var: &str) -> Option<Expr> {
6032 if !is_explicit_poly(e, var) {
6036 return None;
6037 }
6038 let coeffs = poly_coeffs(e, var)?;
6039 if coeffs.len() <= 2 {
6041 return None;
6042 }
6043 let mut last = coeffs.len() - 1;
6045 while last > 0 && matches!(&coeffs[last], Expr::Num(v) if *v == 0.0) {
6046 last -= 1;
6047 }
6048 if last < 2 {
6049 return None;
6050 }
6051 let x = var.to_string();
6052 let x = Expr::Var(x);
6053 let mut acc = coeffs[last].clone();
6054 for k in (0..last).rev() {
6055 acc = add(mul(acc, x.clone()), coeffs[k].clone());
6056 }
6057 Some(simplify(&acc))
6058}
6059
6060pub fn expand_dot(e: &Expr) -> Option<Expr> {
6063 let Expr::Call(name, args) = e else {
6064 return None;
6065 };
6066 if name != "dot" || args.len() != 2 {
6067 return None;
6068 }
6069 let (a, b) = (
6070 flatten_matrix_value(&args[0])?,
6071 flatten_matrix_value(&args[1])?,
6072 );
6073 if a.len() != b.len() {
6075 return None;
6076 }
6077 let mut acc: Option<Expr> = None;
6078 for (ra, rb) in a.iter().zip(b.iter()) {
6079 if ra.len() != rb.len() {
6080 return None;
6081 }
6082 for (x, y) in ra.iter().zip(rb.iter()) {
6083 let prod = mul(x.clone(), y.clone());
6084 acc = Some(match acc {
6085 None => prod,
6086 Some(p) => add(p, prod),
6087 });
6088 }
6089 }
6090 acc
6091}
6092
6093pub fn expand_call(e: &Expr) -> Option<Expr> {
6098 let Expr::Call(name, args) = e else {
6099 return None;
6100 };
6101 match name.as_str() {
6102 "det" | "trace" | "adjoint" | "inv" | "norm" => expand_matrix_call(e),
6103 "dot" => expand_dot(e),
6104 "poly_coeffs" => {
6105 if args.len() != 2 {
6106 return None;
6107 }
6108 let Expr::Var(v) = &args[1] else {
6109 return None;
6110 };
6111 poly_coeffs_vec(&args[0], v).ok()
6112 }
6113 "roots" => {
6114 if args.len() != 2 {
6115 return None;
6116 }
6117 let Expr::Var(v) = &args[1] else {
6118 return None;
6119 };
6120 solve_poly(&args[0], v).ok()
6121 }
6122 "solve" => {
6123 if args.len() != 2 {
6124 return None;
6125 }
6126 match &args[1] {
6130 Expr::Var(v) => solve_linear(&args[0], v).ok(),
6131 Expr::Mat(_) => {
6132 let vars = mat_var_names(&args[1])?;
6133 let eqs = flat_mat_items(&args[0])?;
6134 solve_system(&eqs, &vars).ok()
6135 }
6136 _ => None,
6137 }
6138 }
6139 _ => None,
6140 }
6141}
6142
6143pub fn is_matrix_value(e: &Expr) -> bool {
6146 flatten_matrix_value(e).is_some()
6147}
6148
6149fn emit_mat_literal(
6157 rows: &[Vec<Expr>],
6158 counts: &HashMap<String, usize>,
6159 names: &mut HashMap<String, String>,
6160 out: &mut Vec<String>,
6161 counter: &mut usize,
6162 fx: Fx,
6163) -> String {
6164 let mut parts = Vec::new();
6165 for r in rows {
6166 let mut cols = Vec::new();
6167 for c in r {
6168 let (s, _) = emit_node(c, false, counts, names, out, counter, fx);
6169 cols.push(s);
6170 }
6171 parts.push(format!("vec![{}]", cols.join(", ")));
6172 }
6173 format!("vec![{}]", parts.join(", "))
6174}
6175
6176fn emit_uncached(
6177 e: &Expr,
6178 counts: &HashMap<String, usize>,
6179 names: &mut HashMap<String, String>,
6180 out: &mut Vec<String>,
6181 counter: &mut usize,
6182 fx: Fx,
6183) -> (String, u8) {
6184 match e {
6185 Expr::Num(v) => (fx.lit(*v), 9),
6186 Expr::Var(n) => (rust_ident(n), 9),
6187 Expr::Neg(a) => {
6188 if let Some(m) = flatten_matrix_value(e) {
6189 return (emit_mat_literal(&m, counts, names, out, counter, fx), 9);
6190 }
6191 let (s, p) = emit_node(a, false, counts, names, out, counter, fx);
6192 (format!("-{}", wrap(s, p, 5)), 4)
6193 }
6194 Expr::Add(a, b) => {
6195 if let Some(m) = flatten_matrix_value(e) {
6198 return (emit_mat_literal(&m, counts, names, out, counter, fx), 9);
6199 }
6200 if let Expr::Num(v) = b.as_ref() {
6203 if *v < 0.0 {
6204 let (l, lp) = emit_node(a, false, counts, names, out, counter, fx);
6205 return (format!("{} - {}", wrap(l, lp, 2), fx.lit(-*v)), 2);
6206 }
6207 }
6208 let (l, lp) = emit_node(a, false, counts, names, out, counter, fx);
6209 let (r, rp) = emit_node(b, false, counts, names, out, counter, fx);
6210 (format!("{} + {}", wrap(l, lp, 2), wrap(r, rp, 3)), 2)
6211 }
6212 Expr::Sub(a, b) => {
6213 if let Some(m) = flatten_matrix_value(e) {
6216 return (emit_mat_literal(&m, counts, names, out, counter, fx), 9);
6217 }
6218 let (l, lp) = emit_node(a, false, counts, names, out, counter, fx);
6219 let (r, rp) = emit_node(b, false, counts, names, out, counter, fx);
6220 (format!("{} - {}", wrap(l, lp, 2), wrap(r, rp, 3)), 2)
6221 }
6222 Expr::Mul(a, b) => {
6223 if let Some(m) = flatten_matrix_value(e) {
6227 return (emit_mat_literal(&m, counts, names, out, counter, fx), 9);
6228 }
6229 if let Expr::Num(n) = a.as_ref() {
6233 if *n == -1.0 {
6234 let (r, rp) = emit_node(b, false, counts, names, out, counter, fx);
6235 return (format!("-{}", wrap(r, rp, 5)), 4);
6236 }
6237 if *n == 1.0 {
6238 return emit_node(b, false, counts, names, out, counter, fx);
6239 }
6240 }
6241 if let Expr::Num(n) = b.as_ref() {
6242 if *n == -1.0 {
6243 let (l, lp) = emit_node(a, false, counts, names, out, counter, fx);
6244 return (format!("-{}", wrap(l, lp, 5)), 4);
6245 }
6246 if *n == 1.0 {
6247 return emit_node(a, false, counts, names, out, counter, fx);
6248 }
6249 }
6250 let (l, lp) = emit_node(a, false, counts, names, out, counter, fx);
6251 let (r, rp) = emit_node(b, false, counts, names, out, counter, fx);
6252 (format!("{} * {}", wrap(l, lp, 3), wrap(r, rp, 4)), 3)
6253 }
6254 Expr::Div(a, b) => {
6255 let (l, lp) = emit_node(a, false, counts, names, out, counter, fx);
6256 let (r, rp) = emit_node(b, false, counts, names, out, counter, fx);
6257 (format!("{} / {}", wrap(l, lp, 3), wrap(r, rp, 4)), 3)
6258 }
6259 Expr::Pow(a, b) => {
6260 if let Some(m) = flatten_matrix_value(e) {
6265 return (emit_mat_literal(&m, counts, names, out, counter, fx), 9);
6266 }
6267 let base_is_matrix =
6274 matches!(a.as_ref(), Expr::Mat(_) | Expr::MatPattern(_)) || is_matrix_value(a);
6275 if base_is_matrix {
6276 return (
6277 "compile_error!(\"write a matrix power as an explicit matrix product (the generator supports non-negative integer powers up to 8)\")"
6278 .to_string(),
6279 9,
6280 );
6281 }
6282 if let (Expr::Num(bv), Expr::Num(ev)) = (a.as_ref(), b.as_ref()) {
6287 if *bv < 0.0 && math::fract(*ev) != 0.0 {
6288 return (
6289 "compile_error!(\"a non-integer power of a negative number has no real value (the value layer is complex): rewrite the formula or use the complex lane\")"
6290 .to_string(),
6291 9,
6292 );
6293 }
6294 }
6295 let (l, lp) = emit_node(a, false, counts, names, out, counter, fx);
6296 match b.as_ref() {
6297 Expr::Num(n) if *n == 2.0 => {
6298 let lw = wrap(l.clone(), lp, 4);
6299 (format!("{lw} * {lw}"), 3)
6300 }
6301 Expr::Num(n) if *n == 0.5 => {
6302 if fx.is_libm() {
6304 (format!("libm::sqrt({})", wrap(l, lp, 3)), 9)
6305 } else {
6306 (format!("({}).sqrt()", wrap(l, lp, 3)), 9)
6307 }
6308 }
6309 Expr::Num(n) if math::fract(*n) == 0.0 && n.abs() < 1e9 => {
6311 if fx.is_libm() {
6312 (format!("libm::pow({}, {})", wrap(l, lp, 3), fx.lit(*n)), 9)
6313 } else {
6314 (format!("({}).powi({})", wrap(l, lp, 3), *n as i64), 9)
6315 }
6316 }
6317 _ => {
6318 let (r, rp) = emit_node(b, false, counts, names, out, counter, fx);
6319 if fx.is_libm() {
6321 (
6322 format!("libm::pow({}, {})", wrap(l, lp, 3), wrap(r, rp, 3)),
6323 9,
6324 )
6325 } else {
6326 (format!("({}).powf({})", wrap(l, lp, 3), wrap(r, rp, 3)), 9)
6327 }
6328 }
6329 }
6330 }
6331 Expr::Call(n, args) => {
6332 if matches!(n.as_str(), "__quad_root_1" | "__quad_root_2") {
6333 if args.len() != 3 {
6334 return (
6335 "compile_error!(\"the internal quadratic-root operator needs three coefficients\")".to_string(),
6336 9,
6337 );
6338 }
6339 if let [Expr::Num(a), Expr::Num(b), Expr::Num(c)] = args.as_slice() {
6340 if b * b - 4.0 * a * c < 0.0 {
6341 return (
6342 "compile_error!(\"the quadratic discriminant is negative: the real lane has no real roots, use the complex lane\")"
6343 .to_string(),
6344 9,
6345 );
6346 }
6347 }
6348 let (a, _) = emit_node(&args[0], false, counts, names, out, counter, fx);
6349 let (b, _) = emit_node(&args[1], false, counts, names, out, counter, fx);
6350 let (c, _) = emit_node(&args[2], false, counts, names, out, counter, fx);
6351 let (two, four, half) = (fx.lit(2.0), fx.lit(4.0), fx.lit(0.5));
6352 let first = n == "__quad_root_1";
6353 let large = if first {
6354 "__q_q / __q_a"
6355 } else {
6356 "__q_c / __q_q"
6357 };
6358 let small = if first {
6359 "__q_c / __q_q"
6360 } else {
6361 "__q_q / __q_a"
6362 };
6363 let text = format!(
6364 "{{ let __q_a = {a}; let __q_b = {b}; let __q_c = {c}; \
6365 let __q_s = (__q_b * __q_b - {four} * __q_a * __q_c).sqrt(); \
6366 let __q_first = __q_b >= 0.0; \
6367 let __q_q = if __q_first {{ -{half} * (__q_b + __q_s) }} else {{ -{half} * (__q_b - __q_s) }}; \
6368 if __q_q == 0.0 {{ -__q_b / ({two} * __q_a) }} else if __q_first {{ {large} }} else {{ {small} }} }}"
6369 );
6370 return (text, 9);
6371 }
6372 let Some(arg0) = args.first() else {
6373 return (
6374 "compile_error!(\"the function call is missing its argument: every function in this dialect is unary\")".to_string(),
6375 9,
6376 );
6377 };
6378 if n == "sqrt" && matches!(arg0, Expr::Num(v) if *v < 0.0) {
6379 return (
6380 "compile_error!(\"the square root of a negative number has no real value (the value layer is complex): rewrite the formula or use the complex lane\")"
6381 .to_string(),
6382 9,
6383 );
6384 }
6385 let (a, ap) = emit_node(arg0, false, counts, names, out, counter, fx);
6386 let wrapped = wrap(a, ap, 3);
6387 if fx.is_libm() {
6389 if let Some(m) = libm_name(n) {
6390 return (format!("libm::{m}({wrapped})"), 9);
6391 }
6392 }
6393 match n.as_str() {
6394 "log" | "ln" => (format!("({wrapped}).ln()"), 9),
6395 "exp" | "sin" | "cos" | "tan" | "sinh" | "cosh" | "tanh" | "sqrt" | "abs" => {
6396 (format!("({wrapped}).{n}()"), 9)
6397 }
6398 "min" | "max" => {
6401 let (b, bp) = emit_node(&args[1], false, counts, names, out, counter, fx);
6402 (format!("({wrapped}).{n}({})", wrap(b, bp, 3)), 9)
6403 }
6404 "clamp" => {
6405 let (lo, lp) = emit_node(&args[1], false, counts, names, out, counter, fx);
6406 let (hi, hp) = emit_node(&args[2], false, counts, names, out, counter, fx);
6407 (
6408 format!(
6409 "({wrapped}).max({}).min({})",
6410 wrap(lo, lp, 3),
6411 wrap(hi, hp, 3)
6412 ),
6413 9,
6414 )
6415 }
6416 "det" | "trace" | "adjoint" | "inv" | "solve" | "roots" | "poly_coeffs" | "dot"
6420 | "norm" => {
6421 match expand_call(e) {
6422 Some(x) => emit_node(&x, false, counts, names, out, counter, fx),
6427 None => (
6428 "compile_error!(\"det/trace/adjoint/inv/norm/dot need a concrete matrix literal (det only goes up to order 3)\")"
6429 .to_string(),
6430 9,
6431 ),
6432 }
6433 }
6434 "re" | "im" | "conj" => (wrapped, ap),
6439 "arg" => (
6442 "compile_error!(\"arg is only defined for complex values: write the sign test out explicitly in a real formula\")"
6443 .to_string(),
6444 9,
6445 ),
6446 _ => (
6451 "compile_error!(\"unknown function: the real lane supports exp/ln/log/sin/cos/tan/sinh/cosh/tanh/sqrt/abs/re/im/conj\")"
6452 .to_string(),
6453 9,
6454 ),
6455 }
6456 }
6457 Expr::Mat(rows) => (emit_mat_literal(rows, counts, names, out, counter, fx), 9),
6458 Expr::Deriv(..) | Expr::Grad(_) | Expr::Laplacian(_) | Expr::Indexed { .. } => (
6461 "compile_error!(\"symbolic operators and indexed symbols must go through the .formula file lane (the generator needs the context)\")"
6462 .to_string(),
6463 9,
6464 ),
6465 Expr::Sum {
6468 var,
6469 lower,
6470 upper,
6471 body,
6472 } => {
6473 if let (Expr::Num(lo), Expr::Num(hi)) = (lower.as_ref(), upper.as_ref()) {
6474 if math::fract(*lo) == 0.0 && math::fract(*hi) == 0.0 && (hi - lo) < 64.0 {
6475 let mut parts = Vec::new();
6476 let mut k = *lo;
6477 while k <= *hi {
6478 let b = subst(body, var, &num(k));
6479 let (t, _) = emit_node(&b, false, counts, names, out, counter, fx);
6480 parts.push(t);
6481 k += 1.0;
6482 }
6483 if parts.is_empty() {
6486 return ("0.0".to_string(), 9);
6487 }
6488 return (parts.join(" + "), 2);
6489 }
6490 }
6491 (
6492 "compile_error!(\"a non-constant sum bound must go through the .formula file lane\")".to_string(),
6493 9,
6494 )
6495 }
6496 Expr::Integral { .. } => (
6499 "compile_error!(\"definite integrals must go through the .formula file lane (numeric integration is a runtime loop)\")".to_string(),
6500 9,
6501 ),
6502 Expr::MatPattern(_) => (
6506 "compile_error!(\"a pattern matrix must go through the generator lane; it cannot be emitted inline\")".to_string(),
6507 9,
6508 ),
6509 Expr::Transpose(a) => {
6514 if let Some(m) = flatten_matrix_value(e) {
6515 return (emit_mat_literal(&m, counts, names, out, counter, fx), 9);
6516 }
6517 let _ = a;
6518 (
6519 "compile_error!(\"the transpose operand must be a concrete matrix literal (the shape of a symbolic matrix is unknown at compile time)\")"
6520 .to_string(),
6521 9,
6522 )
6523 }
6524 }
6525}
6526
6527fn try_banded(p: &MatPattern, m: usize) -> Option<MatrixKind> {
6540 let cell = |i: usize, j: usize| -> Option<&PatternCell> { p.rows.get(i)?.get(j) };
6541 let blank = |i: usize, j: usize| -> bool {
6542 match cell(i, j) {
6543 Some(PatternCell::Dots) => true,
6544 Some(PatternCell::El(Expr::Num(v))) => *v == 0.0,
6545 _ => false,
6546 }
6547 };
6548 let el = |i: usize, j: usize| -> Option<&Expr> {
6549 match cell(i, j)? {
6550 PatternCell::El(e) => Some(e),
6551 PatternCell::Dots => None,
6552 }
6553 };
6554 for k in (1..=(m / 2)).rev() {
6556 if m < 2 * k + 1 {
6559 continue;
6560 }
6561 let mut val: Option<&Expr> = None;
6562 let mut ok = true;
6563 let mut concrete = 0usize;
6564 for i in 0..m {
6565 for j in 0..m {
6566 let inside = i.abs_diff(j) <= k;
6567 if inside {
6568 match el(i, j) {
6569 Some(e) => {
6570 concrete += 1;
6571 match val {
6572 None => val = Some(e),
6573 Some(v) if key(v) == key(e) => {}
6574 _ => {
6575 ok = false;
6576 }
6577 }
6578 }
6579 None => ok = false,
6580 }
6581 } else if !blank(i, j) {
6582 ok = false;
6583 }
6584 if !ok {
6585 break;
6586 }
6587 }
6588 if !ok {
6589 break;
6590 }
6591 }
6592 let expect: usize = (0..m)
6595 .map(|i| {
6596 let lo = i.saturating_sub(k);
6597 let hi = (i + k).min(m - 1);
6598 hi - lo + 1
6599 })
6600 .sum();
6601 if ok && concrete == expect {
6602 if let Some(v) = val {
6603 return Some(MatrixKind::Banded {
6604 v: v.clone(),
6605 half_band: k,
6606 });
6607 }
6608 }
6609 }
6610 None
6611}
6612
6613fn try_blockdiag(p: &MatPattern) -> Option<MatrixKind> {
6617 let cell = |i: usize, j: usize| -> Option<&PatternCell> { p.rows.get(i)?.get(j) };
6618 let el = |i: usize, j: usize| -> Option<&Expr> {
6619 match cell(i, j)? {
6620 PatternCell::El(e) => Some(e),
6621 PatternCell::Dots => None,
6622 }
6623 };
6624 let blank = |i: usize, j: usize| -> bool {
6627 match cell(i, j) {
6628 Some(PatternCell::Dots) => true,
6629 Some(PatternCell::El(Expr::Num(v))) => *v == 0.0,
6630 _ => false,
6631 }
6632 };
6633 for (i, j) in [
6635 (0, 2),
6636 (0, 3),
6637 (1, 2),
6638 (1, 3),
6639 (2, 0),
6640 (2, 1),
6641 (3, 0),
6642 (3, 1),
6643 ] {
6644 if !blank(i, j) {
6645 return None;
6646 }
6647 }
6648 let block = |a: (usize, usize), b: (usize, usize), o1: (usize, usize), o2: (usize, usize)| {
6651 let da = el(a.0, a.1)?;
6652 let db = el(b.0, b.1)?;
6653 if key(da) != key(db) {
6654 return None;
6655 }
6656 if !blank(o1.0, o1.1) || !blank(o2.0, o2.1) {
6657 return None;
6658 }
6659 Some(da.clone())
6660 };
6661 let pv = block((0, 0), (1, 1), (0, 1), (1, 0))?;
6662 let qv = block((2, 2), (3, 3), (2, 3), (3, 2))?;
6663 Some(MatrixKind::BlockDiag2 { p: pv, q: qv })
6664}
6665
6666fn try_bidiag(p: &MatPattern) -> Option<MatrixKind> {
6669 let el = |i: usize, j: usize| -> Option<&Expr> {
6670 match p.rows.get(i)?.get(j)? {
6671 PatternCell::El(e) => Some(e),
6672 PatternCell::Dots => None,
6673 }
6674 };
6675 let is_dots = |i: usize, j: usize| {
6676 matches!(
6677 p.rows.get(i).and_then(|r| r.get(j)),
6678 Some(PatternCell::Dots)
6679 )
6680 };
6681
6682 let diag: Option<Vec<&Expr>> = (0..4).map(|i| el(i, i)).collect();
6683 let diag = diag?;
6684 if key(diag[0]) != key(diag[1]) || key(diag[1]) != key(diag[2]) || key(diag[2]) != key(diag[3])
6685 {
6686 return None;
6687 }
6688
6689 let upper: Option<Vec<&Expr>> = (0..3).map(|i| el(i, i + 1)).collect();
6692 if let Some(up) = upper {
6693 let lower_dots = is_dots(1, 0)
6694 && is_dots(2, 0)
6695 && is_dots(2, 1)
6696 && is_dots(3, 0)
6697 && is_dots(3, 1)
6698 && is_dots(3, 2);
6699 let upper_same = key(up[0]) == key(up[1]) && key(up[1]) == key(up[2]);
6700 if lower_dots && upper_same {
6701 return Some(MatrixKind::BidiagUpper {
6702 b: diag[0].clone(),
6703 c: up[0].clone(),
6704 });
6705 }
6706 }
6707
6708 let lower: Option<Vec<&Expr>> = (0..3).map(|i| el(i + 1, i)).collect();
6711 if let Some(lo) = lower {
6712 let upper_dots = is_dots(0, 1)
6713 && is_dots(0, 2)
6714 && is_dots(0, 3)
6715 && is_dots(1, 2)
6716 && is_dots(1, 3)
6717 && is_dots(2, 3);
6718 let lower_same = key(lo[0]) == key(lo[1]) && key(lo[1]) == key(lo[2]);
6719 if upper_dots && lower_same {
6720 return Some(MatrixKind::BidiagLower {
6721 a: lo[0].clone(),
6722 b: diag[0].clone(),
6723 });
6724 }
6725 }
6726 None
6727}
6728
6729pub fn recognize_pattern(p: &MatPattern) -> Result<MatrixKind, Error> {
6730 let (m, n) = p.grid().ok_or_else(|| {
6731 Error::ShapeMismatch("pattern matrix rows have inconsistent lengths".into())
6732 })?;
6733
6734 let el = |i: usize, j: usize| -> Option<&Expr> {
6735 match p.rows.get(i)?.get(j)? {
6736 PatternCell::El(e) => Some(e),
6737 PatternCell::Dots => None,
6738 }
6739 };
6740 let is_dots = |i: usize, j: usize| {
6741 matches!(
6742 p.rows.get(i).and_then(|r| r.get(j)),
6743 Some(PatternCell::Dots)
6744 )
6745 };
6746
6747 if m == 3 && n == 3 {
6749 let all_dots_off = [(0, 1), (1, 0), (1, 2), (2, 1)]
6751 .iter()
6752 .all(|&(i, j)| is_dots(i, j));
6753 if all_dots_off {
6754 let get = |i: usize, j: usize| el(i, j).cloned();
6755 let (x, z, y, w, v) = (get(0, 0), get(0, 2), get(1, 1), get(2, 0), get(2, 2));
6756 if let (Some(x), Some(z), Some(y), Some(w), Some(v)) = (x, z, y, w, v) {
6757 let is_zero = |e: &Expr| matches!(e, Expr::Num(v) if *v == 0.0);
6758 let is_one = |e: &Expr| matches!(e, Expr::Num(v) if *v == 1.0);
6759 if is_one(&x) && is_zero(&z) && is_one(&y) && is_zero(&w) && is_one(&v) {
6761 return Ok(MatrixKind::Identity);
6762 }
6763 if let Some(name) = indexed_diag(&[&x, &y, &v]) {
6766 if is_zero(&z) && is_zero(&w) {
6767 return Ok(MatrixKind::DiagVec(name));
6768 }
6769 }
6770 let same_diag = key(&x) == key(&y) && key(&y) == key(&v);
6773 if same_diag && is_zero(&z) && is_zero(&w) {
6774 return Ok(MatrixKind::Diag(x));
6775 }
6776 }
6777 }
6778 }
6779
6780 if m == n && m >= 5 {
6782 if let Some(kind) = try_banded(p, m) {
6783 return Ok(kind);
6784 }
6785 }
6786
6787 if m == 4 && n == 4 {
6789 if let Some(kind) = try_blockdiag(p) {
6797 return Ok(kind);
6798 }
6799 if let Some(kind) = try_bidiag(p) {
6802 return Ok(kind);
6803 }
6804
6805 let concrete = [
6811 (0, 0),
6812 (0, 1),
6813 (0, 3),
6814 (1, 0),
6815 (1, 1),
6816 (1, 2),
6817 (2, 1),
6818 (2, 2),
6819 (2, 3),
6820 (3, 0),
6821 (3, 2),
6822 (3, 3),
6823 ];
6824 let dots_at = [(0, 2), (1, 3), (2, 0), (3, 1)];
6825 let structure_ok = dots_at.iter().all(|&(i, j)| is_dots(i, j))
6826 && concrete.iter().all(|&(i, j)| el(i, j).is_some());
6827 if structure_ok {
6828 let grab = |i: usize, j: usize| el(i, j).cloned().unwrap();
6829 let is_zero = |e: &Expr| matches!(e, Expr::Num(v) if *v == 0.0);
6830 let (b1, c1, z1) = (grab(0, 0), grab(0, 1), grab(0, 3));
6831 let (a1, b2, c2) = (grab(1, 0), grab(1, 1), grab(1, 2));
6832 let (a2, b3, c3) = (grab(2, 1), grab(2, 2), grab(2, 3));
6833 let (z2, a3, b4) = (grab(3, 0), grab(3, 2), grab(3, 3));
6834
6835 if let Some(name) = indexed_diag(&[&b1, &b2, &b3, &b4]) {
6840 if key(&a1) == key(&a2)
6841 && key(&a2) == key(&a3)
6842 && key(&c1) == key(&c2)
6843 && key(&c2) == key(&c3)
6844 && is_zero(&z1)
6845 && is_zero(&z2)
6846 {
6847 return Ok(MatrixKind::TridiagVec { a: a1, name, c: c1 });
6848 }
6849 }
6850 let diag_same = key(&b1) == key(&b2) && key(&b2) == key(&b3) && key(&b3) == key(&b4);
6851 let sub_same = key(&a1) == key(&a2) && key(&a2) == key(&a3);
6852 let sup_same = key(&c1) == key(&c2) && key(&c2) == key(&c3);
6853 if diag_same && sub_same && sup_same && is_zero(&z1) && is_zero(&z2) {
6854 return Ok(MatrixKind::Tridiag {
6855 a: a1,
6856 b: b1,
6857 c: c1,
6858 });
6859 }
6860 return Err(Error::InvalidInput(
6861 "this 4×4 pattern looks tridiagonal, but the main and off-diagonals are not the same expression, or the far corners are not 0".into(),
6862 ));
6863 }
6864 }
6865
6866 Err(Error::InvalidInput(format!(
6867 "the pattern matrix ({m}×{n}) does not match any built-in shape. Supported:\n \
6868 identity(n) [1 ⋯ 0; ⋮ 1 ⋮; 0 ⋯ 1]\n \
6869 diag(d, n) / diag_v(d[i], n) one expression on the diagonal / an index sequence\n \
6870 tridiag(a,b,c,n) / tridiag_v(...) tridiagonal (the corners must be ellipses)\n \
6871 bidiag_u(b,c,n) / bidiag_l(a,b,n) upper/lower bidiagonal\n \
6872 blockdiag2(p,q,n,m) block diagonal diag(p·I₂, q·I₂)\n \
6873 banded(v,k,n) symmetric banded (unambiguous only when m≥2k+1)\n\
6874 Note: a sketch without ellipses IS a **concrete matrix** and is emitted as a literal\n\
6875 (which beats the generator: constants fold, no allocation loop) — write the ellipses if\
6876 you want the generator lane."
6877 )))
6878}
6879
6880pub fn emit_matrix_ctor(fname: &str, kind: &MatrixKind) -> String {
6884 match kind {
6885 MatrixKind::Identity => format!(
6886 "/// Identity matrix I_n (generated from a pattern matrix)\n#[allow(non_snake_case)]\npub fn {fname}(n: usize) -> Vec<Vec<f64>> {{\n vec![vec![0.0; n]; n]\n .into_iter()\n .enumerate()\n .map(|(i, mut row)| {{ row[i] = 1.0; row }})\n .collect()\n}}\n"
6887 ),
6888 MatrixKind::Diag(d) => {
6889 let body = emit_block(d);
6890 let params = sig_of(core::slice::from_ref(d));
6891 format!(
6892 "/// Diagonal matrix diag(d)·I_n (generated from a pattern matrix; d is broadcast as a scalar)\n#[allow(non_snake_case)]\npub fn {fname}({params}, n: usize) -> Vec<Vec<f64>> {{\n let mut m = vec![vec![0.0; n]; n];\n for __row in 0..n {{ m[__row][__row] = {body}; }}\n m\n}}\n"
6893 )
6894 }
6895 MatrixKind::DiagVec(name) => {
6896 let id = rust_ident(name);
6897 format!(
6898 "/// Diagonal matrix (generated from an indexed pattern matrix; d is a **vector** whose length must be ≥ n)\n#[allow(non_snake_case)]\npub fn {fname}({id}: &[f64], n: usize) -> Vec<Vec<f64>> {{\n let mut m = vec![vec![0.0; n]; n];\n for __row in 0..n {{\n m[__row][__row] = {id}[__row];\n }}\n m\n}}\n"
6899 )
6900 }
6901 MatrixKind::TridiagVec { a, c, .. } => {
6902 let ba = emit_block(a);
6903 let bc = emit_block(c);
6904 format!(
6905 "/// Tridiagonal matrix (generated from an indexed pattern matrix; b is a **vector** whose length must be ≥ n)\n#[allow(non_snake_case)]\npub fn {fname}(a: f64, b: &[f64], c: f64, n: usize) -> Vec<Vec<f64>> {{\n let av = {ba};\n let cv = {bc};\n let mut m = vec![vec![0.0; n]; n];\n for __row in 0..n {{\n m[__row][__row] = b[__row];\n let __next = __row + 1;\n if __next < n {{\n m[__row][__next] = cv;\n m[__next][__row] = av;\n }}\n }}\n m\n}}\n"
6906 )
6907 }
6908 MatrixKind::BlockDiag2 { p, q } => {
6909 let bp = emit_block(p);
6910 let bq = emit_block(q);
6911 format!(
6912 "/// Block diagonal matrix diag(P·I₂, Q·I₂) (generated from a pattern matrix)\n#[allow(non_snake_case, clippy::needless_range_loop)]\npub fn {fname}(p: f64, q: f64, n: usize) -> Vec<Vec<f64>> {{\n // n is the **total** dimension; each block takes half (the lower-right block takes the odd one)\n let pv = {bp};\n let qv = {bq};\n let half = n / 2;\n let mut m = vec![vec![0.0; n]; n];\n for __row in 0..half {{\n m[__row][__row] = pv;\n m[n - 1 - __row][n - 1 - __row] = qv;\n }}\n if n % 2 == 1 {{\n m[half][half] = qv;\n }}\n m\n}}\n"
6913 )
6914 }
6915 MatrixKind::Banded { v, half_band } => {
6916 let bv = emit_block(v);
6917 let k = *half_band;
6918 format!(
6919 "/// Symmetric banded matrix (half-bandwidth {k}: the main diagonal and {k} off-diagonals share one value)\n#[allow(non_snake_case, clippy::needless_range_loop)]\npub fn {fname}(v: f64, n: usize) -> Vec<Vec<f64>> {{\n let vv = {bv};\n let mut m = vec![vec![0.0; n]; n];\n for __row in 0..n {{\n let __hi = (__row + {k}).min(n - 1);\n for __col in __row..=__hi {{\n m[__row][__col] = vv;\n m[__col][__row] = vv;\n }}\n }}\n m\n}}\n"
6920 )
6921 }
6922 MatrixKind::BidiagUpper { b, c } => {
6923 let bb = emit_block(b);
6924 let bc = emit_block(c);
6925 format!(
6926 "/// Upper bidiagonal matrix (main diagonal b plus the superdiagonal c)\n#[allow(non_snake_case, clippy::needless_range_loop)]\npub fn {fname}(b: f64, c: f64, n: usize) -> Vec<Vec<f64>> {{\n let bv = {bb};\n let cv = {bc};\n let mut m = vec![vec![0.0; n]; n];\n for __row in 0..n {{\n m[__row][__row] = bv;\n let __next = __row + 1;\n if __next < n {{\n m[__row][__next] = cv;\n }}\n }}\n m\n}}\n"
6927 )
6928 }
6929 MatrixKind::BidiagLower { a, b } => {
6930 let ba = emit_block(a);
6931 let bb = emit_block(b);
6932 format!(
6933 "/// Lower bidiagonal matrix (main diagonal b plus the subdiagonal a)\n#[allow(non_snake_case, clippy::needless_range_loop)]\npub fn {fname}(a: f64, b: f64, n: usize) -> Vec<Vec<f64>> {{\n let av = {ba};\n let bv = {bb};\n let mut m = vec![vec![0.0; n]; n];\n for __row in 0..n {{\n m[__row][__row] = bv;\n let __next = __row + 1;\n if __next < n {{\n m[__next][__row] = av;\n }}\n }}\n m\n}}\n"
6934 )
6935 }
6936 MatrixKind::Tridiag { a, b, c } => {
6937 let ba = emit_block(a);
6938 let bb = emit_block(b);
6939 let bc = emit_block(c);
6940 let params = sig_of(&[a.clone(), b.clone(), c.clone()]);
6941 format!(
6942 "/// Tridiagonal matrix tridiag(a,b,c)_n (generated from a pattern matrix)\n#[allow(non_snake_case, clippy::too_many_arguments)]\npub fn {fname}({params}, n: usize) -> Vec<Vec<f64>> {{\n let av = {ba};\n let bv = {bb};\n let cv = {bc};\n let mut m = vec![vec![0.0; n]; n];\n #[allow(clippy::needless_range_loop)]\n for __row in 0..n {{\n m[__row][__row] = bv;\n let __next = __row + 1;\n if __next < n {{\n m[__row][__next] = cv;\n m[__next][__row] = av;\n }}\n }}\n m\n}}\n"
6943 )
6944 }
6945 }
6946}
6947
6948fn sig_of(exprs: &[Expr]) -> String {
6951 let mut names: Vec<String> = exprs.iter().flat_map(vars_of).collect();
6952 names.sort();
6953 names.dedup();
6954 names
6955 .iter()
6956 .map(|n| format!("{}: f64", rust_ident(n)))
6957 .collect::<Vec<_>>()
6958 .join(", ")
6959}
6960
6961pub fn to_mathml(e: &Expr) -> String {
6967 format!("<math>{}</math>", mm(e))
6968}
6969
6970fn mm(e: &Expr) -> String {
6971 match e {
6972 Expr::Num(v) => format!("<mn>{}</mn>", fmt_num(*v)),
6973 Expr::Var(n) => format!("<mi>{}</mi>", xml_escape(n)),
6974 Expr::Add(a, b) => format!("<mrow>{}<mo>+</mo>{}</mrow>", mm(a), mm(b)),
6975 Expr::Sub(a, b) => format!("<mrow>{}<mo>-</mo>{}</mrow>", mm(a), mm(b)),
6976 Expr::Mul(a, b) => format!("<mrow>{}<mo>\u{2062}</mo>{}</mrow>", mm(a), mm(b)),
6977 Expr::Div(a, b) => format!("<mfrac>{}{}</mfrac>", mm(a), mm(b)),
6978 Expr::Pow(a, b) => format!("<msup>{}{}</msup>", mm(a), mm(b)),
6979 Expr::Neg(a) => format!("<mrow><mo>-</mo>{}</mrow>", mm(a)),
6980 Expr::Call(name, args) => {
6981 let inner: String = args
6984 .iter()
6985 .map(mm)
6986 .collect::<Vec<_>>()
6987 .join("<mo>,</mo>");
6988 format!(
6989 "<mrow><mi>{}</mi><mo>\u{2061}</mo><mo>(</mo>{}<mo>)</mo></mrow>",
6990 xml_escape(name),
6991 inner
6992 )
6993 }
6994 Expr::Transpose(a) => format!("<msup>{}<mi>T</mi></msup>", mm(a)),
6995 Expr::Deriv(u, by) => format!(
6996 "<mfrac><mrow><mo>\u{2202}</mo>{}</mrow><mrow><mo>\u{2202}</mo><mi>{}</mi></mrow></mfrac>",
6997 mm(u),
6998 xml_escape(by)
6999 ),
7000 Expr::Grad(u) => format!("<mrow><mo>\u{2207}</mo>{}</mrow>", mm(u)),
7001 Expr::Laplacian(u) => format!("<mrow><msup><mo>\u{2207}</mo><mn>2</mn></msup>{}</mrow>", mm(u)),
7002 Expr::Sum { var, lower, upper, body } => format!(
7003 "<mrow><munderover><mo>\u{2211}</mo><mrow><mi>{}</mi><mo>=</mo>{}</mrow>{}</munderover>{}</mrow>",
7004 xml_escape(var),
7005 mm(lower),
7006 mm(upper),
7007 mm(body)
7008 ),
7009 Expr::Integral { var, lower, upper, body } => format!(
7010 "<mrow><munderover><mo>\u{222b}</mo>{}{}</munderover>{}<mi>{}d</mi></mrow>",
7011 mm(lower),
7012 mm(upper),
7013 mm(body),
7014 xml_escape(var)
7015 ),
7016 Expr::Indexed { name, indices } => {
7017 let sub: String = indices
7018 .iter()
7019 .map(|i| format!("<mi>{}</mi>", xml_escape(i)))
7020 .collect();
7021 format!("<msub><mi>{}</mi><mrow>{}</mrow></msub>", xml_escape(name), sub)
7022 }
7023 Expr::Mat(rows) => mat_mathml(&rows.iter().map(|r| r.iter().map(mm_cell).collect::<Vec<_>>()).collect::<Vec<_>>()),
7024 Expr::MatPattern(p) => mat_mathml(
7025 &p.rows
7026 .iter()
7027 .map(|r| r.iter().map(mm_pattern_cell).collect::<Vec<_>>())
7028 .collect::<Vec<_>>(),
7029 ),
7030 }
7031}
7032
7033fn mm_cell(e: &Expr) -> String {
7034 format!("<mtd>{}</mtd>", mm(e))
7035}
7036
7037fn mm_pattern_cell(c: &PatternCell) -> String {
7038 match c {
7039 PatternCell::El(e) => format!("<mtd>{}</mtd>", mm(e)),
7040 PatternCell::Dots => "<mtd><mo>\u{22ef}</mo></mtd>".to_string(),
7041 }
7042}
7043
7044fn mat_mathml(rows: &[Vec<String>]) -> String {
7045 let rows_xml: String = rows
7046 .iter()
7047 .map(|r| format!("<mtr>{}</mtr>", r.concat()))
7048 .collect();
7049 format!("<mtable>{rows_xml}</mtable>")
7050}
7051
7052fn xml_escape(s: &str) -> String {
7053 s.replace('&', "&")
7054 .replace('<', "<")
7055 .replace('>', ">")
7056}
7057
7058pub fn to_matex(e: &Expr) -> String {
7065 to_matex_raw_matex(e).0
7066}
7067
7068fn wrap_matex(e: &Expr, min: u8) -> String {
7069 let (s, p) = to_matex_raw_matex(e);
7070 if p < min {
7071 format!("({s})")
7072 } else {
7073 s
7074 }
7075}
7076
7077fn to_matex_raw_matex(e: &Expr) -> (String, u8) {
7082 match e {
7083 Expr::Num(v) => (fmt_num(*v), 9),
7084 Expr::Var(n) => (n.clone(), 9),
7085 Expr::Neg(a) => (format!("-{}", wrap_matex(a, 5)), 4),
7086 Expr::Add(a, b) => (format!("{} + {}", wrap_matex(a, 2), wrap_matex(b, 3)), 2),
7087 Expr::Sub(a, b) => (format!("{} - {}", wrap_matex(a, 2), wrap_matex(b, 3)), 2),
7088 Expr::Mul(a, b) => (format!("{} * {}", wrap_matex(a, 3), wrap_matex(b, 4)), 3),
7089 Expr::Div(a, b) => (format!("{} / {}", wrap_matex(a, 3), wrap_matex(b, 4)), 3),
7090 Expr::Pow(a, b) => (format!("{} ^ {}", wrap_matex(a, 7), wrap_matex(b, 7)), 6),
7094 Expr::Call(name, args) => (
7095 format!(
7096 "{}({})",
7097 name,
7098 args.iter().map(to_matex).collect::<Vec<_>>().join(", ")
7099 ),
7100 9,
7101 ),
7102 Expr::Transpose(a) => (format!("{}'", wrap_matex(a, 7)), 6),
7103 Expr::Deriv(u, by) => (format!("\u{2202}({}, {})", to_matex(u), by), 9),
7104 Expr::Grad(u) => (format!("\u{2207}({})", to_matex(u)), 9),
7105 Expr::Laplacian(u) => (format!("\u{2207}^2({})", to_matex(u)), 9),
7106 Expr::Sum {
7107 var,
7108 lower,
7109 upper,
7110 body,
7111 } => (
7112 format!(
7113 "\u{2211}({}, {}, {}, {})",
7114 var,
7115 to_matex(lower),
7116 to_matex(upper),
7117 to_matex(body)
7118 ),
7119 9,
7120 ),
7121 Expr::Integral {
7122 var,
7123 lower,
7124 upper,
7125 body,
7126 } => (
7127 format!(
7128 "\u{222b}({}, {}, {}, {})",
7129 var,
7130 to_matex(lower),
7131 to_matex(upper),
7132 to_matex(body)
7133 ),
7134 9,
7135 ),
7136 Expr::Indexed { name, indices } => (format!("{}({})", name, indices.join(", ")), 9),
7142 Expr::Mat(rows) => (format_matex_rows(&rows_payload(rows)), 9),
7143 Expr::MatPattern(p) => {
7144 let cells: Vec<Vec<Option<String>>> = p
7145 .rows
7146 .iter()
7147 .map(|r| {
7148 r.iter()
7149 .map(|c| match c {
7150 PatternCell::El(e) => Some(to_matex(e)),
7151 PatternCell::Dots => None,
7152 })
7153 .collect()
7154 })
7155 .collect();
7156 (format_matex_rows(&cells), 9)
7157 }
7158 }
7159}
7160
7161fn rows_payload(rows: &[Vec<Expr>]) -> Vec<Vec<Option<String>>> {
7162 rows.iter()
7163 .map(|r| r.iter().map(|c| Some(to_matex(c))).collect())
7164 .collect()
7165}
7166
7167#[allow(clippy::needless_range_loop)] pub fn format_matex_rows(cells: &[Vec<Option<String>>]) -> String {
7172 let cols = cells.iter().map(|r| r.len()).max().unwrap_or(0);
7173 let dots = "...".to_string();
7174 let mut widths = vec![0usize; cols];
7175 for r in cells {
7176 for (j, c) in r.iter().enumerate() {
7177 let w = c.as_ref().unwrap_or(&dots).chars().count();
7178 widths[j] = widths[j].max(w);
7179 }
7180 }
7181 let mut lines = Vec::new();
7185 for (i, r) in cells.iter().enumerate() {
7186 let mut line = String::new();
7187 for j in 0..cols {
7188 let cell = r
7189 .get(j)
7190 .and_then(|x| x.clone())
7191 .unwrap_or_else(|| dots.clone());
7192 line.push_str(&cell);
7193 if j + 1 < cols {
7194 line.push(',');
7195 }
7196 let pad = widths[j] + 1 - cell.chars().count();
7197 line.push_str(&" ".repeat(pad));
7198 }
7199 let mut line = line.trim_end().to_string();
7200 if i + 1 < cells.len() {
7201 line.push_str(" ;");
7202 }
7203 lines.push(line);
7204 }
7205 format!("[ {} ]", lines.join("\n "))
7206}
7207
7208pub fn format_set(set: &FormulaSet) -> String {
7211 let mut out = String::new();
7212 for u in &set.uses {
7216 out.push_str(&format!("use \"{u}\"\n"));
7217 }
7218 if !set.uses.is_empty() {
7219 out.push('\n');
7220 }
7221 if !set.decls.is_empty() {
7222 out.push_str("decl {\n");
7223 for d in &set.decls {
7224 match &d.unit {
7225 Some(u) => out.push_str(&format!(" {} : {} [{}];\n", d.name, d.quantity, u)),
7226 None => out.push_str(&format!(" {} : {};\n", d.name, d.quantity)),
7227 }
7228 }
7229 out.push_str("}\n");
7230 }
7231 for item in &set.items {
7232 let body = to_matex(&item.expr);
7233 match &item.name {
7234 Some(n) => out.push_str(&format!("{n} = {body}\n")),
7235 None => out.push_str(&format!("{body}\n")),
7236 }
7237 }
7238 out
7239}
7240
7241#[cfg(test)]
7244mod tests {
7245 use super::*;
7246
7247 #[test]
7248 fn units() {
7249 assert_eq!(
7250 parse_unit("A/m^2").unwrap(),
7251 Dim::from_exponents([0, -2, 0, 1, 0, 0, 0])
7252 );
7253 assert_eq!(
7254 parse_unit("V").unwrap(),
7255 Dim::from_exponents([1, 2, -3, -1, 0, 0, 0])
7256 );
7257 assert_eq!(parse_unit("kg*m/s^2").unwrap(), parse_unit("N").unwrap());
7258 assert!(parse_unit("A/m^x").is_err());
7259 }
7260
7261 #[test]
7262 fn units_fractional_exponents() {
7263 let w = parse_unit("V/A*s^(-1/2)").unwrap();
7266 assert_eq!(w.display(), "kg·m^2·s^(-7/2)·A^-2");
7267 assert_eq!(
7268 w,
7269 parse_unit("V/A")
7270 .unwrap()
7271 .mul_dim(parse_unit("s").unwrap().scale_ratio(-1, 2).unwrap())
7272 );
7273 assert_eq!(
7275 parse_unit("s^(1/2)").unwrap().scale_ratio(2, 1).unwrap(),
7276 parse_unit("s").unwrap()
7277 );
7278 assert!(parse_unit("m^(1/3)").is_err());
7281 assert!(parse_unit("s^(-1/2").is_err());
7283 assert!(parse_unit("s^(1/0)").is_err());
7284 assert!(parse_unit("V/A*s^-1/2").is_err());
7287 }
7288
7289 #[test]
7290 fn complex_arithmetic_basics() {
7291 let z = C::new(0.7, -1.3);
7292 let s = z.sqrt();
7294 let back = s.mul(s);
7295 assert!((back.re - z.re).abs() < 1e-15 && (back.im - z.im).abs() < 1e-15);
7296 let e = z.ln().unwrap().exp();
7298 assert!((e.re - z.re).abs() < 1e-15 && (e.im - z.im).abs() < 1e-15);
7299 let sq = C::real(-1.3).pow_real(2.0);
7302 assert!(sq.is_real(), "负底整数幂必须落在实轴上:{sq:?}");
7303 assert!((sq.re - 1.69).abs() < 1e-15, "{}", sq.re);
7304 let i2 = C::real(-4.0).sqrt();
7306 assert!(i2.re.abs() < 1e-15 && (i2.im - 2.0).abs() < 1e-15);
7307 assert!(C::ONE.div(C::ZERO).is_err());
7309 assert!(C::ZERO.ln().is_err());
7310 let i = C::I.pow(C::I).unwrap();
7312 assert!((i.re - (-core::f64::consts::FRAC_PI_2).exp()).abs() < 1e-15);
7313 assert!(i.im.abs() < 1e-15);
7314 }
7315
7316 #[test]
7317 fn si_prefixes_and_conversion() {
7318 assert_eq!(parse_unit("mm").unwrap(), parse_unit("m").unwrap());
7321 assert_eq!(parse_unit("mol").unwrap(), parse_unit("mol").unwrap());
7322 assert_eq!(parse_unit("GHz").unwrap(), parse_unit("Hz").unwrap());
7323 assert!((parse_unit_spec("nF").unwrap().scale - 1e-9).abs() < 1e-20);
7324 assert!((parse_unit_spec("mm").unwrap().scale - 1e-3).abs() < 1e-18);
7325 assert!((parse_unit_spec("km").unwrap().scale - 1e3).abs() < 1e-9);
7326 assert!((parse_unit_spec("mm^2").unwrap().scale - 1e-6).abs() < 1e-20);
7328 assert!((parse_unit_spec("mV/mm").unwrap().scale - 1.0).abs() < 1e-18);
7330 assert!((parse_unit_spec("daN").unwrap().scale - 10.0).abs() < 1e-12);
7332 assert!((convert(1.0, "nF", "F").unwrap() - 1e-9).abs() < 1e-24);
7334 assert!((convert(1500.0, "mV", "V").unwrap() - 1.5).abs() < 1e-12);
7335 assert!((convert(1.0, "kHz", "Hz").unwrap() - 1000.0).abs() < 1e-9);
7336 assert_eq!(convert(1.0, "g", "kg").unwrap(), 1e-3);
7339 assert_eq!(convert(1.0, "kg", "g").unwrap(), 1000.0);
7340 assert_eq!(convert(1.0, "mg", "kg").unwrap(), 1e-6);
7341 assert_eq!(convert(1.0, "Mg", "kg").unwrap(), 1000.0);
7342 assert_eq!(convert(1.0, "mg", "g").unwrap(), 1e-3);
7343 assert!(matches!(
7344 convert(1.0, "nF", "V").unwrap_err(),
7345 Error::IncompatibleUnits {
7346 ref from,
7347 ref to,
7348 ..
7349 } if from == "nF" && to == "V"
7350 ));
7351 assert_eq!(convert(1.0, "Qm", "m").unwrap(), 1e30);
7353 assert_eq!(convert(1.0, "Rm", "m").unwrap(), 1e27);
7354 assert_eq!(convert(1.0, "rm", "m").unwrap(), 1e-27);
7355 assert_eq!(convert(1.0, "qm", "m").unwrap(), 1e-30);
7356 assert_eq!(convert(1.0, "min", "s").unwrap(), 60.0);
7358 assert_eq!(convert(2.0, "h", "min").unwrap(), 120.0);
7359 assert_eq!(convert(1.0, "d", "h").unwrap(), 24.0);
7360 assert_eq!(convert(1.0, "L", "m^3").unwrap(), 1e-3);
7361 assert_eq!(convert(1.0, "mL", "L").unwrap(), 1e-3);
7362 assert_eq!(convert(1.0, "bar", "Pa").unwrap(), 1e5);
7363 assert_eq!(convert(1.0, "atm", "Pa").unwrap(), 101_325.0);
7364 assert_eq!(convert(1.0, "tonne", "kg").unwrap(), 1000.0);
7365 assert_eq!(convert(1.0, "nmi", "m").unwrap(), 1852.0);
7366 assert_eq!(convert(1.0, "ha", "m^2").unwrap(), 1e4);
7367 assert_eq!(convert(1.0, "acre", "m^2").unwrap(), 4_046.856_422_4);
7368 assert!((convert(1.0, "knot", "m/s").unwrap() - 1852.0 / 3600.0).abs() < 1e-15);
7369 assert!(
7370 (convert(1.0, "deg", "rad").unwrap() - core::f64::consts::PI / 180.0).abs() < 1e-15
7371 );
7372 assert!((convert(1.0, "eV", "J").unwrap() - 1.602_176_634e-19).abs() < 1e-34);
7373 assert_eq!(convert(1.0, "Wh", "J").unwrap(), 3600.0);
7374 let Error::AmbiguousUnit { why, remedy, .. } = parse_unit("cal").unwrap_err() else {
7376 panic!("cal must be AmbiguousUnit")
7377 };
7378 assert!(why.contains("4.184") && why.contains("4.1868"), "{why}");
7379 assert!(remedy.contains("J"), "{remedy}");
7380 let Error::AmbiguousUnit { why, remedy, .. } = parse_unit("rpm").unwrap_err() else {
7381 panic!("rpm must be AmbiguousUnit")
7382 };
7383 assert!(why.contains("rad/s"), "{why}");
7384 assert!(remedy.contains("Hz"), "{remedy}");
7385 assert!((parse_unit_spec("\u{00b5}F").unwrap().scale - 1e-6).abs() < 1e-20);
7387 assert!((parse_unit_spec("\u{03bc}F").unwrap().scale - 1e-6).abs() < 1e-20);
7388 assert!(parse_unit("uF").is_err());
7389 assert!(matches!(
7392 parse_unit("degC").unwrap_err(),
7393 Error::OffsetUnit(_)
7394 ));
7395 assert!(matches!(parse_unit("dBm").unwrap_err(), Error::LogUnit(_)));
7396 assert!(parse_unit("sr").unwrap().is_zero());
7398 }
7399
7400 #[test]
7401 fn formula_names_must_respect_declared_dimensions_and_be_unique() {
7402 let set = FormulaSet {
7403 decls: vec![
7404 Decl {
7405 name: "F".into(),
7406 quantity: "force".into(),
7407 unit: Some("N".into()),
7408 },
7409 Decl {
7410 name: "d".into(),
7411 quantity: "distance".into(),
7412 unit: Some("m".into()),
7413 },
7414 Decl {
7415 name: "s".into(),
7416 quantity: "stress".into(),
7417 unit: Some("Pa".into()),
7418 },
7419 ],
7420 items: vec![FormulaItem {
7421 name: Some("s".into()),
7422 expr: div(var("F"), var("d")),
7423 line: 7,
7424 }],
7425 uses: vec![],
7426 };
7427 let err = dims_of_set(&set).unwrap_err();
7428 let Error::ResultDimensionMismatch {
7430 name,
7431 got,
7432 declared,
7433 line,
7434 } = err
7435 else {
7436 panic!("expected ResultDimensionMismatch: {err}")
7437 };
7438 assert_eq!(name, "s");
7439 assert_eq!(got, "kg·s^-2");
7440 assert_eq!(declared, "kg·m^-1·s^-2");
7441 assert_eq!(line, 7);
7442
7443 let mut compatible = set.clone();
7446 compatible.decls[2].unit = Some("N/m".into());
7447 compatible.items.push(FormulaItem {
7450 name: Some("t".into()),
7451 expr: mul(var("s"), var("d")),
7452 line: 8,
7453 });
7454 let dims = dims_of_set(&compatible).unwrap();
7455 assert_eq!(dims["s"], parse_unit("N/m").unwrap());
7456 assert_eq!(dims["t"], parse_unit("N").unwrap());
7457
7458 let duplicate = FormulaSet {
7459 decls: vec![],
7460 items: vec![
7461 FormulaItem {
7462 name: Some("q".into()),
7463 expr: num(1.0),
7464 line: 1,
7465 },
7466 FormulaItem {
7467 name: Some("q".into()),
7468 expr: num(2.0),
7469 line: 2,
7470 },
7471 ],
7472 uses: vec![],
7473 };
7474 let err = dims_of_set(&duplicate).unwrap_err();
7475 assert_eq!(err.code(), "duplicate-declaration", "{err}");
7476 }
7477
7478 #[test]
7479 fn complex_division_survives_extremes() {
7480 assert_eq!(
7484 C::div(C::real(1e300), C::real(1e10)).unwrap().re,
7485 1e300 / 1e10
7486 );
7487 assert!((C::div(C::real(1e200), C::real(1e200)).unwrap().re - 1.0).abs() < 1e-15);
7488 assert!((C::div(C::real(1e-200), C::real(1e-200)).unwrap().re - 1.0).abs() < 1e-15);
7489 assert!(C::div(C::ONE, C::ZERO).is_err());
7490 let big = C::new(1e300, 1e300);
7492 let q = C::div(big, big).unwrap();
7493 assert!((q.re - 1.0).abs() < 1e-12 && q.im.abs() < 1e-12, "{q:?}");
7494 assert_eq!(C::div(C::real(1.0), C::real(4.0)).unwrap().re, 0.25);
7496 }
7497
7498 #[test]
7499 fn unit_exponent_overflow_is_rejected_not_wrapped() {
7500 assert!(parse_unit("m^(20000)").is_err());
7503 assert!(parse_unit("m^(2000000000)").is_err());
7504 assert!(parse_unit("V^(1000000000)").is_err());
7505 assert_eq!(
7507 parse_unit("m^2").unwrap(),
7508 Dim::from_exponents([0, 2, 0, 0, 0, 0, 0])
7509 );
7510 }
7511
7512 #[test]
7513 fn dim_display_round_trips_through_parse() {
7514 for u in ["V/A*s^(-1/2)", "kg/m^3", "Pa*s", "J/mol/K", "m/s^2"] {
7521 let d = parse_unit(u).unwrap();
7522 let printed = d.display();
7523 let back = parse_unit(&printed).unwrap_or_else(|e| panic!("{u} → {printed}: {e}"));
7524 assert_eq!(d, back, "{u} 的回写 {printed} 不一致");
7525 }
7526 }
7527
7528 #[test]
7529 fn nondifferentiable_operators_are_named() {
7530 let e = Expr::Call("arg".into(), vec![var("x")]);
7533 assert!(contains_nan_expr(&diff(&e, "x")));
7534 assert_eq!(nondiffable(&e), vec!["arg".to_string()]);
7535 for f in ["abs", "conj", "re", "im"] {
7537 let e = Expr::Call(f.into(), vec![pow(var("x"), num(2.0))]);
7538 let d = diff(&e, "x");
7539 assert!(!contains_nan_expr(&d), "`{f}` 的导数不该是 NaN:{d:?}");
7540 }
7541 let e = Expr::Call("abs".into(), vec![pow(var("x"), num(2.0))]);
7543 let d = simplify(&diff(&e, "x"));
7544 let mut env = HashMap::new();
7545 env.insert("x".to_string(), 1.0);
7546 assert!((eval(&d, &env).unwrap() - 2.0).abs() < 1e-12);
7547 }
7548
7549 #[test]
7550 fn display_and_precedence_edge_cases() {
7551 let nested = pow(pow(var("x"), num(2.0)), num(3.0));
7554 assert!(
7555 to_latex(&nested).contains("(x^{2})^{3}"),
7556 "{}",
7557 to_latex(&nested)
7558 );
7559 assert!(
7560 to_matex(&nested).contains("(x ^ 2) ^ 3"),
7561 "{}",
7562 to_matex(&nested)
7563 );
7564 let e = pow(var("x"), pow(num(2.0), num(3.0)));
7566 assert!(to_matex(&e).contains("x ^ (2 ^ 3)"), "{}", to_matex(&e));
7567 let g = pow(grad(var("u")), num(2.0));
7570 assert!(to_latex(&g).contains("(\\nabla u)^{2}"), "{}", to_latex(&g));
7571 let t = pow(transpose(var("a")), num(2.0));
7573 assert!(to_latex(&t).contains("(a^{T})^{2}"), "{}", to_latex(&t));
7574 }
7575
7576 #[test]
7577 fn matrix_division_is_rejected() {
7578 let a = Expr::Mat(vec![vec![num(2.0), num(4.0)]]);
7579 let b = Expr::Mat(vec![vec![num(2.0), num(2.0)]]);
7580 let err = eval_value(&div(a.clone(), b), &HashMap::new()).unwrap_err();
7582 assert_eq!(err.code(), "matrix-division-unsupported", "{err}");
7583 assert!(err.render(crate::i18n::Locale::En).contains("inv"), "{err}");
7584 match eval_value(&div(a.clone(), num(2.0)), &HashMap::new()).unwrap() {
7587 Value::Matrix(m) => {
7588 assert_eq!(m.len(), 1);
7589 assert_eq!((m[0][0].re, m[0][1].re), (1.0, 2.0), "逐元素除");
7590 }
7591 other => panic!("矩阵除以标量应得矩阵,得到 {other:?}"),
7592 }
7593 let err = eval_value(&div(num(2.0), a), &HashMap::new()).unwrap_err();
7595 let text = err.to_string();
7596 assert!(text.contains("inv"), "{text}");
7597 }
7598
7599 #[test]
7600 fn empty_sum_is_the_zero_element() {
7601 let s = sum("i", num(5.0), num(3.0), var("i"));
7604 assert_eq!(eval(&s, &HashMap::new()).unwrap(), 0.0);
7605 assert!(emit_block(&s).contains("0.0"));
7606 assert!(emit_block_complex(&s).contains("(0.0, 0.0)"));
7607 }
7608
7609 #[test]
7610 fn declared_j_keeps_its_parameter_slot() {
7611 let decls = vec![Decl {
7614 name: "j".into(),
7615 quantity: "current_density".into(),
7616 unit: Some("A/m^2".into()),
7617 }];
7618 let e = mul(var("j"), num(2.0));
7619 assert_eq!(params_in_decl_order(&decls, &e), vec!["j".to_string()]);
7620 let r = vec![Decl {
7622 name: "r".into(),
7623 quantity: "resistance".into(),
7624 unit: Some("V/A".into()),
7625 }];
7626 assert!(params_in_decl_order(&r, &add(var("r"), var("j"))).contains(&"r".to_string()));
7627 }
7628
7629 #[test]
7630 fn error_render_points_at_the_column() {
7631 let src = "decl { x : d; }\nx + undeclared_symbol";
7632 let e = FrontError::new(2, 5, "未声明的符号 `undeclared_symbol`");
7633 let text = e.render_with_source("demo.formula", src);
7634 let lines: Vec<&str> = text.lines().collect();
7636 assert_eq!(lines.len(), 4, "{text}");
7637 assert!(lines[0].contains("demo.formula:2:5"), "{text}");
7638 assert!(lines[2].contains("x + undeclared_symbol"), "{text}");
7639 assert!(lines[3].ends_with(" ^"), "{text:?}");
7641 let plain = FrontError::plain("语义错误").render_with_source("demo", src);
7643 assert_eq!(plain, "demo: 语义错误");
7644 }
7645
7646 #[test]
7647 fn hostile_sources_are_rejected_not_crashed() {
7648 for (src, payload) in [
7651 (
7652 "decl { x : d; } x\u{200b} + 1",
7653 "200B (zero-width character)",
7654 ),
7655 (
7656 "decl { x : d; } x + 1\u{202e}",
7657 "202E (bidirectional override)",
7658 ),
7659 ("decl { x : d; } x + 1\u{0}", "0000 (NUL)"),
7660 ("decl { x : d; } x + 1\u{feff}", "FEFF (byte order mark)"),
7661 ] {
7662 let err = scan_source(src).unwrap_err();
7665 assert_eq!(err.code.code(), "invisible-character", "{src:?}");
7666 match &*err.code {
7667 i18n::Error::InvisibleCharacter(p) => assert_eq!(p, payload, "{src:?}"),
7668 other => panic!("{src:?} → {other:?}"),
7669 }
7670 }
7671 assert!(scan_source("decl {\n\tx : d;\n}\nx + 1").is_ok());
7673
7674 let mut deep = var("x");
7678 for _ in 0..MAX_DEPTH + 5 {
7679 deep = neg(deep);
7680 }
7681 let err = check_depth(&deep).unwrap_err();
7682 let text = err.to_string();
7683 assert!(text.contains("nesting too deep"), "{text}");
7684 assert!(depth_of(&var("x")) == 1);
7685 let mut ok = var("x");
7686 for _ in 0..50 {
7687 ok = neg(ok);
7688 }
7689 assert!(check_depth(&ok).is_ok(), "50 层应放行");
7690 }
7691
7692 #[test]
7693 fn sum_step_cap_prevents_dos() {
7694 let s = sum("i", num(1.0), num(1.0e9), var("i"));
7696 let err = eval_value(&s, &HashMap::new()).unwrap_err();
7697 assert_eq!(err.code(), "invalid-input", "{err}");
7698 assert!(
7699 err.render(crate::i18n::Locale::En).contains("limit"),
7700 "{err}"
7701 );
7702 let small = sum("i", num(1.0), num(10.0), var("i"));
7704 assert_eq!(eval(&small, &HashMap::new()).unwrap(), 55.0);
7705 }
7706
7707 #[test]
7708 fn scalar_valued_matrix_ops_work_as_exponents_and_det_args() {
7709 let j = Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0), num(4.0)]]);
7714 let env = HashMap::new();
7715 let e = pow(num(2.0), Expr::Call("det".into(), vec![j.clone()]));
7717 let v = eval_value(&e, &env).unwrap().as_scalar().unwrap();
7718 assert!((v.re - 0.25).abs() < 1e-12, "{v:?}");
7719 let vv = Expr::Mat(vec![vec![num(3.0), num(4.0)]]);
7721 let e = pow(num(2.0), Expr::Call("norm".into(), vec![vv]));
7722 let v = eval_value(&e, &env).unwrap().as_scalar().unwrap();
7723 assert!((v.re - 32.0).abs() < 1e-12, "2^5 = 32:{v:?}");
7724 let bad = pow(num(2.0), j.clone());
7726 let err = eval_value(&bad, &env).unwrap_err();
7727 assert_eq!(err.code(), "matrix-scalar-mix", "{err}");
7728 assert!(err
7729 .render(crate::i18n::Locale::En)
7730 .contains("cannot be an exponent"));
7731 let decls = vec![Decl {
7733 name: "c".into(),
7734 quantity: "cell".into(),
7735 unit: Some("m".into()),
7736 }];
7737 let dims = dims_of(&decls).unwrap();
7738 let cells = Expr::Mat(vec![vec![var("c"), var("c")], vec![var("c"), var("c")]]);
7739 let inner = Expr::Call("inv".into(), vec![cells]);
7740 let d = dim_check(&Expr::Call("det".into(), vec![inner]), &dims).unwrap();
7741 assert_eq!(d, parse_unit("m^-2").unwrap(), "det(inv(J)) 量纲 = m^-2");
7742 }
7743
7744 #[test]
7745 fn canonical_form_keeps_use_directives() {
7746 let mut set = FormulaSet::default();
7750 set.uses.push("lib/atmosphere.formula".into());
7751 set.decls.push(Decl {
7752 name: "x".into(),
7753 quantity: "d".into(),
7754 unit: None,
7755 });
7756 set.items.push(FormulaItem {
7757 name: Some("y".into()),
7758 expr: var("x"),
7759 line: 2,
7760 });
7761 let text = format_set(&set);
7762 let use_pos = text
7763 .find("use \"lib/atmosphere.formula\"")
7764 .expect("use 必须保留");
7765 let decl_pos = text.find("decl {").expect("decl 必须在");
7766 assert!(use_pos < decl_pos, "`use` 必须排在声明之前:\n{text}");
7767 }
7768
7769 #[test]
7770 fn linear_solve_works_and_rejects_nonlinearity() {
7771 let mut env = HashMap::new();
7775 env.insert("a".to_string(), 2.0);
7776 env.insert("b".to_string(), -6.0);
7777 env.insert("k1".to_string(), 3.0);
7778 env.insert("k2".to_string(), 4.0);
7779 env.insert("x".to_string(), 0.0);
7780 let e = add(mul(var("a"), var("x")), var("b"));
7781 let x = solve_linear(&e, "x").unwrap();
7782 assert!((eval(&x, &env).unwrap() - 3.0).abs() < 1e-12, "{x:?}");
7784 let e2 = sub(mul(var("k1"), var("a")), mul(var("k2"), var("x")));
7786 let x2 = solve_linear(&e2, "x").unwrap();
7787 assert!((eval(&x2, &env).unwrap() - 1.5).abs() < 1e-12, "{x2:?}");
7788 env.insert("x".to_string(), eval(&x2, &env).unwrap());
7791 assert!(eval(&e2, &env).unwrap().abs() < 1e-12);
7792
7793 for (src, want) in [
7795 (mul(var("x"), var("x")), "twice in one product"),
7796 (div(num(1.0), var("x")), "denominator"),
7797 (pow(var("x"), num(2.0)), "power"),
7798 (Expr::Call("exp".into(), vec![var("x")]), "inside `exp`"),
7799 ] {
7800 let err = solve_linear(&src, "x").unwrap_err();
7803 assert_eq!(err.code(), "nonlinear-equation", "{err}");
7804 assert!(
7805 err.render(i18n::Locale::En).contains(want),
7806 "expected `{want}` in {err}"
7807 );
7808 }
7809 let err = solve_linear(&add(var("a"), var("b")), "x").unwrap_err();
7813 assert!(
7814 err.render(i18n::Locale::En).contains('x'),
7815 "the rejection must name the variable: {err}"
7816 );
7817 }
7818
7819 #[test]
7820 fn solve_system_solves_and_roundtrips_to_zero() {
7821 let k1 = var("k1");
7823 let k2 = var("k2");
7824 let k3 = var("k3");
7825 let f1 = var("F1");
7826 let f2 = var("F2");
7827 let (x, y) = (var("x1"), var("x2"));
7828 let eq1 = sub(
7829 sub(
7830 mul(k1.clone(), x.clone()),
7831 mul(k2.clone(), sub(y.clone(), x.clone())),
7832 ),
7833 f1.clone(),
7834 );
7835 let eq2 = sub(
7836 add(
7837 mul(k2.clone(), sub(y.clone(), x.clone())),
7838 mul(k3.clone(), y.clone()),
7839 ),
7840 f2.clone(),
7841 );
7842 let sol = solve_system(&[eq1.clone(), eq2.clone()], &["x1".into(), "x2".into()]).unwrap();
7843 let Expr::Mat(rows) = &sol else {
7844 panic!("解必须是列向量矩阵,得到 {sol:?}");
7845 };
7846 assert_eq!(rows.len(), 2);
7847 assert!(rows.iter().all(|r| r.len() == 1), "列向量形状 2×1");
7848
7849 for r in rows {
7852 for name in vars_of(&r[0]) {
7853 assert!(
7854 !["x1", "x2"].contains(&name.as_str()),
7855 "解里还含未知数 `{name}`"
7856 );
7857 }
7858 }
7859
7860 let mut env = HashMap::new();
7863 env.insert("k1".to_string(), 1.0);
7864 env.insert("k2".to_string(), 2.0);
7865 env.insert("k3".to_string(), 3.0);
7866 env.insert("F1".to_string(), 10.0);
7867 env.insert("F2".to_string(), 20.0);
7868 env.insert("x1".to_string(), eval(&rows[0][0], &env).unwrap());
7869 env.insert("x2".to_string(), eval(&rows[1][0], &env).unwrap());
7870 assert!(
7871 eval(&eq1, &env).unwrap().abs() < 1e-12,
7872 "eq1 残差 {}",
7873 eval(&eq1, &env).unwrap()
7874 );
7875 assert!(
7876 eval(&eq2, &env).unwrap().abs() < 1e-12,
7877 "eq2 残差 {}",
7878 eval(&eq2, &env).unwrap()
7879 );
7880
7881 let det = 3.0 * 5.0 - 2.0 * 2.0;
7886 assert!((env["x1"] - 90.0 / det).abs() < 1e-12, "x1 = {}", env["x1"]);
7887 assert!((env["x2"] - 80.0 / det).abs() < 1e-12, "x2 = {}", env["x2"]);
7888 }
7889
7890 #[test]
7891 fn roots_solves_linear_and_quadratic_exactly() {
7892 let mut env = HashMap::new();
7893 for (k, v) in [("a", 2.0), ("b", -6.0), ("k", 3.0), ("F", 12.0)] {
7894 env.insert(k.to_string(), v);
7895 }
7896 let lin = solve_poly(&sub(mul(var("a"), var("x")), num(6.0)), "x").unwrap();
7898 let Expr::Mat(r) = &lin else {
7899 panic!("必须是矩阵")
7900 };
7901 assert_eq!((r.len(), r[0].len()), (1, 1));
7902 assert!((eval(&r[0][0], &env).unwrap() - 3.0).abs() < 1e-12);
7903
7904 let quad = solve_poly(
7906 &add(
7907 sub(pow(var("x"), num(2.0)), mul(num(5.0), var("x"))),
7908 num(6.0),
7909 ),
7910 "x",
7911 )
7912 .unwrap();
7913 let Expr::Mat(r) = &quad else {
7914 panic!("必须是矩阵")
7915 };
7916 assert_eq!((r.len(), r[0].len()), (2, 1), "两个根,列向量");
7917 let mut got: Vec<f64> = r.iter().map(|row| eval(&row[0], &env).unwrap()).collect();
7918 got.sort_by(|a, b| a.partial_cmp(b).unwrap());
7919 assert!((got[0] - 2.0).abs() < 1e-12, "{got:?}");
7920 assert!((got[1] - 3.0).abs() < 1e-12, "{got:?}");
7921
7922 for g in &got {
7925 let mut e2 = env.clone();
7926 e2.insert("x".to_string(), *g);
7927 let orig = add(
7928 sub(pow(var("x"), num(2.0)), mul(num(5.0), var("x"))),
7929 num(6.0),
7930 );
7931 assert!(eval(&orig, &e2).unwrap().abs() < 1e-12, "代回残差");
7932 }
7933
7934 let dbl = solve_poly(
7936 &add(
7937 sub(pow(var("x"), num(2.0)), mul(num(2.0), var("x"))),
7938 num(1.0),
7939 ),
7940 "x",
7941 )
7942 .unwrap();
7943 let Expr::Mat(r) = &dbl else { panic!() };
7944 for row in r {
7945 let v = eval(&row[0], &env).unwrap();
7946 assert!((v - 1.0).abs() < 1e-12, "{v}");
7947 }
7948
7949 let cancel = sub(
7951 add(
7952 sub(pow(var("x"), num(3.0)), pow(var("x"), num(3.0))),
7953 var("x"),
7954 ),
7955 num(1.0),
7956 );
7957 let Expr::Mat(r) = &solve_poly(&cancel, "x").unwrap() else {
7958 panic!("必须是矩阵")
7959 };
7960 assert_eq!(r.len(), 1, "高阶项抵消后是 1 次");
7961 assert!((eval(&r[0][0], &env).unwrap() - 1.0).abs() < 1e-12);
7962 }
7963
7964 #[test]
7965 fn quadratic_roots_are_stable_and_preserve_the_documented_order() {
7966 let poly = add(
7967 add(
7968 mul(var("a"), pow(var("x"), num(2.0))),
7969 mul(var("b"), var("x")),
7970 ),
7971 var("c"),
7972 );
7973 let roots = solve_poly(&poly, "x").unwrap();
7974 let Expr::Mat(rows) = roots else {
7975 panic!("roots must be a column vector")
7976 };
7977 let eval_at = |a: f64, b: f64, c: f64, index: usize| {
7978 let env = HashMap::from([
7979 ("a".to_string(), a),
7980 ("b".to_string(), b),
7981 ("c".to_string(), c),
7982 ]);
7983 eval_value(&rows[index][0], &env)
7984 .unwrap()
7985 .as_scalar()
7986 .unwrap()
7987 };
7988 let small = eval_at(1.0, -1.0e8, 1.0, 0);
7991 assert!((small.re - 1.0e-8).abs() / 1.0e-8 < 1.0e-12, "{small:?}");
7992 assert!(small.im == 0.0);
7993 assert_eq!(eval_at(1.0, -1.0e8, 1.0, 1).re, 1.0e8);
7994 assert!((eval_at(1.0, 1.0e8, 1.0, 0).re + 1.0e8).abs() / 1.0e8 < 1.0e-15);
7995 assert!((eval_at(1.0, 1.0e8, 1.0, 1).re + 1.0e-8).abs() / 1.0e-8 < 1.0e-12);
7996 assert_eq!(eval_at(1.0, 0.0, 0.0, 0), C::ZERO);
7998 assert_eq!(eval_at(1.0, 0.0, 0.0, 1), C::ZERO);
7999 assert_eq!(eval_at(1.0, 2.0, 1.0, 0).re, -1.0);
8000 assert_eq!(eval_at(1.0, 2.0, 1.0, 1).re, -1.0);
8001 assert!(eval_at(1.0, 0.0, 1.0, 0).im < 0.0);
8004 assert!(eval_at(1.0, 0.0, 1.0, 1).im > 0.0);
8005 }
8006
8007 #[test]
8008 fn numeric_roots_finds_all_roots_including_complex() {
8009 let r = numeric_roots(&[-6.0, 11.0, -6.0, 1.0]).unwrap();
8011 assert_eq!(r.len(), 3, "三次必须有三个根(含重数)");
8012 let mut re: Vec<f64> = r.iter().map(|c| c.re).collect();
8013 re.sort_by(|a, b| a.partial_cmp(b).unwrap());
8014 for (got, want) in re.iter().zip([1.0, 2.0, 3.0]) {
8015 assert!((got - want).abs() < 1e-10, "实根 {got} ≠ {want}");
8016 }
8017 assert!(r.iter().all(|c| c.im.abs() < 1e-10), "应当全是实根");
8018
8019 let r2 = numeric_roots(&[1.0, 0.0, 1.0]).unwrap();
8021 assert_eq!(r2.len(), 2);
8022 let ims: Vec<f64> = r2.iter().map(|c| c.im).collect();
8023 assert!(ims.iter().any(|v| (*v - 1.0).abs() < 1e-12), "{ims:?}");
8024 assert!(ims.iter().any(|v| (*v + 1.0).abs() < 1e-12), "{ims:?}");
8025 assert!(r2.iter().all(|c| c.re.abs() < 1e-12));
8026
8027 let r3 = numeric_roots(&[1.0, 0.0, 0.0, 1.0]).unwrap();
8029 assert_eq!(r3.len(), 3);
8030 assert!(r3
8031 .iter()
8032 .any(|c| (c.re + 1.0).abs() < 1e-10 && c.im.abs() < 1e-10));
8033 for z in &r3 {
8035 let z2 = z.mul(*z);
8036 let z3 = z2.mul(*z);
8037 let res = z3.add(C::ONE);
8038 assert!(res.abs() < 1e-8, "z³+1 残差 {res:?}");
8039 }
8040
8041 let r4 = numeric_roots(&[4.0, -4.0, 1.0]).unwrap();
8044 assert_eq!(r4.len(), 2);
8045 for z in &r4 {
8046 assert!((z.re - 2.0).abs() < 1e-6, "重根 {z:?}");
8047 }
8048
8049 assert!(numeric_roots(&[0.0, 0.0]).is_err());
8051 assert!(numeric_roots(&[5.0]).is_err());
8052 let lin = numeric_roots(&[3.0, 2.0]).unwrap();
8053 assert!((lin[0].re + 1.5).abs() < 1e-15);
8054 assert_eq!(numeric_roots(&[3.0, 2.0, 0.0, 0.0]).unwrap().len(), 1);
8056 assert!(numeric_roots(&[f64::NAN, 1.0]).is_err());
8058 }
8059
8060 #[test]
8061 fn numeric_roots_never_reports_garbage() {
8062 let mut coeffs = vec![1.0f64];
8073 for k in 1..=20 {
8074 let mut next = vec![0.0; coeffs.len() + 1];
8075 for (i, c) in coeffs.iter().enumerate() {
8076 next[i] += -(k as f64) * c;
8077 next[i + 1] += c;
8078 }
8079 coeffs = next;
8080 }
8081 match numeric_roots(&coeffs) {
8082 Ok(rs) => {
8083 for z in &rs {
8086 assert!(
8087 z.re.is_finite() && z.im.is_finite(),
8088 "根必须是有限数:{z:?}"
8089 );
8090 let mut acc = C::new(coeffs[coeffs.len() - 1], 0.0);
8091 for c in coeffs.iter().rev().skip(1) {
8092 acc = acc.mul(*z).add(C::new(*c, 0.0));
8093 }
8094 assert!(acc.abs() < 1e-4, "根 {z:?} 代回残差 {}", acc.abs());
8095 }
8096 assert_eq!(rs.len(), 20);
8097 }
8098 Err(e) => {
8101 assert!(
8102 matches!(e, Error::RootFindingFailed { .. }),
8103 "a failed run must be catalogued: {e:?}"
8104 );
8105 let text = e.render(i18n::Locale::En);
8106 assert!(text.contains("root finding failed"), "{text}")
8107 }
8108 }
8109
8110 let small = numeric_roots(&[-1e-26, 0.0, 1.0]).unwrap();
8112 assert_eq!(small.len(), 2);
8113 for z in &small {
8114 assert!(
8118 (z.re.abs() - 1e-13).abs() / 1e-13 < 1e-2,
8119 "小根被抹平了:{z:?}(应为 ±1e-13 量级)"
8120 );
8121 }
8122
8123 let mut c8 = vec![1.0f64];
8125 for k in 1..=8 {
8126 let mut next = vec![0.0; c8.len() + 1];
8127 for (i, c) in c8.iter().enumerate() {
8128 next[i] += -(k as f64) * c;
8129 next[i + 1] += c;
8130 }
8131 c8 = next;
8132 }
8133 let r8 = numeric_roots(&c8).expect("∏(x−k), k=1..8 是健康多项式,不该报病态");
8134 let mut re8: Vec<f64> = r8.iter().map(|z| z.re).collect();
8135 re8.sort_by(|a, b| a.partial_cmp(b).unwrap());
8136 for (k, got) in re8.iter().enumerate() {
8137 assert!((got - (k as f64 + 1.0)).abs() < 1e-6, "第 {k} 个根 {got}");
8138 }
8139
8140 let imag = numeric_roots(&[1e-26, 0.0, 1.0]).unwrap();
8143 for z in &imag {
8144 assert!(
8145 (z.im.abs() - 1e-13).abs() / 1e-13 < 1e-2,
8146 "纯虚小根被清掉了:{z:?}"
8147 );
8148 }
8149 }
8150
8151 #[test]
8152 fn numeric_roots_handles_tiny_roots_exactly_or_refuses() {
8153 for (eps, want) in [
8159 (1e-26f64, 1e-13f64),
8160 (1e-45, 3.1622776601683793e-23),
8161 (1e-50, 1e-25),
8162 (1e-60, 1e-30),
8163 (1e-100, 1e-50),
8164 (1e-300, 1e-150),
8165 ] {
8166 let r = match numeric_roots(&[-eps, 0.0, 1.0]) {
8167 Ok(r) => r,
8168 Err(_) => continue, };
8170 for z in &r {
8171 let rel = (z.re.abs() - want).abs() / want;
8172 assert!(rel < 1e-6, "eps={eps:e}:根 {z:?} 与真值 {want:e} 不符");
8173 }
8174 }
8175 let r = numeric_roots(&[-1e-12, 0.0, 1.0]).unwrap();
8177 for z in &r {
8178 assert!((z.re.abs() - 1e-6).abs() / 1e-6 < 1e-9, "{z:?}");
8179 }
8180 let err = numeric_roots(&[1e300, 1e-300]).unwrap_err();
8182 assert_eq!(err.code(), "non-finite-value", "{err}");
8183 let en = err.render(i18n::Locale::En);
8184 assert!(en.contains("overflows") && en.contains("rescale"), "{en}");
8185 }
8186
8187 #[test]
8188 fn poly_coeffs_extracts_low_to_high_and_round_trips_with_roots() {
8189 let mut env = HashMap::new();
8190 env.insert("a".to_string(), 2.0);
8191 env.insert("b".to_string(), 3.0);
8192 env.insert("c".to_string(), 1.0);
8193 let poly = add(
8195 sub(
8196 mul(var("a"), pow(var("x"), num(2.0))),
8197 mul(var("b"), var("x")),
8198 ),
8199 var("c"),
8200 );
8201 let Expr::Mat(rows) = poly_coeffs_vec(&poly, "x").unwrap() else {
8202 panic!("系数应是 1×k 行向量")
8203 };
8204 assert_eq!(rows.len(), 1, "行向量");
8205 let got: Vec<f64> = rows[0].iter().map(|e| eval(e, &env).unwrap()).collect();
8206 assert_eq!(got, vec![1.0, -3.0, 2.0], "低次到高次");
8207
8208 let r = solve_poly(&poly, "x").unwrap();
8210 let Expr::Mat(rr) = &r else { panic!() };
8211 let mut roots: Vec<f64> = rr.iter().map(|row| eval(&row[0], &env).unwrap()).collect();
8212 roots.sort_by(|a, b| a.partial_cmp(b).unwrap());
8213 assert!((roots[0] - 0.5).abs() < 1e-12, "{roots:?}");
8214 assert!((roots[1] - 1.0).abs() < 1e-12, "{roots:?}");
8215
8216 let cancel = add(
8218 sub(
8219 sub(pow(var("x"), num(3.0)), pow(var("x"), num(3.0))),
8220 mul(num(2.0), var("x")),
8221 ),
8222 num(1.0),
8223 );
8224 let Expr::Mat(rows) = poly_coeffs_vec(&cancel, "x").unwrap() else {
8225 panic!()
8226 };
8227 let got: Vec<f64> = rows[0]
8228 .iter()
8229 .map(|e| eval(e, &HashMap::new()).unwrap())
8230 .collect();
8231 assert_eq!(got, vec![1.0, -2.0], "高次抵消后是 1 次");
8232
8233 for bad in [
8235 Expr::Call("sin".into(), vec![var("x")]),
8236 div(num(1.0), var("x")),
8237 ] {
8238 let err = poly_coeffs_vec(&bad, "x").unwrap_err();
8239 assert_eq!(err.code(), "not-polynomial", "{err}");
8240 assert!(
8241 err.render(i18n::Locale::En)
8242 .contains("univariate polynomial"),
8243 "{err}"
8244 );
8245 }
8246 assert!(poly_coeffs_vec(&mul(num(0.0), var("x")), "x").is_err());
8247 }
8248
8249 #[test]
8250 fn numeric_roots_keeps_imaginary_parts_of_small_complex_roots() {
8251 let r = numeric_roots(&[-1e-60, 0.0, 0.0, 1.0]).expect("三次应可解");
8258 assert_eq!(r.len(), 3);
8259 let real_count = r.iter().filter(|c| c.im == 0.0).count();
8260 assert_eq!(real_count, 1, "x³−1e-60 只有一个实根:{r:?}");
8261 for z in &r {
8263 let z3 = z.mul(*z).mul(*z);
8264 let rel = z3.sub(C::new(1e-60, 0.0)).abs() / 1e-60;
8265 assert!(rel < 1e-6, "根 {z:?} 代回相对残差 {rel}");
8266 }
8267 let r5 = numeric_roots(&[-1e-100, 0.0, 0.0, 0.0, 0.0, 1.0]).expect("五次应可解");
8269 let re5 = r5.iter().filter(|c| c.im == 0.0).count();
8270 assert_eq!(re5, 1, "x⁵−1e-100 只有一个实根:{r5:?}");
8271 for z in &r5 {
8272 let mut acc = *z;
8273 for _ in 0..4 {
8274 acc = acc.mul(*z);
8275 }
8276 let rel = acc.sub(C::new(1e-100, 0.0)).abs() / 1e-100;
8277 assert!(rel < 1e-5, "根 {z:?} 代回相对残差 {rel}");
8278 }
8279 let r2 = numeric_roots(&[-6.0, 5.0, 1.0]).unwrap(); assert!(r2.iter().all(|c| c.im == 0.0), "{r2:?}");
8283 }
8284
8285 #[test]
8286 fn roots_rejects_high_degree_and_non_polynomial() {
8287 let cubic = add(pow(var("x"), num(3.0)), num(1.0));
8289 let err = solve_poly(&cubic, "x").unwrap_err();
8290 assert_eq!(err.code(), "invalid-input", "{err}");
8291 let en = err.render(i18n::Locale::En);
8292 assert!(en.contains("degree 3") && en.contains("degree 1–2"), "{en}");
8293 for bad in [
8296 Expr::Call("sin".into(), vec![var("x")]),
8297 div(num(1.0), var("x")),
8298 pow(var("x"), num(-1.0)),
8299 ] {
8300 let err = solve_poly(&bad, "x").unwrap_err();
8301 assert_eq!(err.code(), "not-polynomial", "{err}");
8302 assert!(
8303 err.render(i18n::Locale::En)
8304 .contains("univariate polynomial"),
8305 "{err}"
8306 );
8307 }
8308 let err = solve_poly(&add(var("a"), var("b")), "x").unwrap_err();
8310 assert_eq!(err.code(), "nonlinear-equation", "{err}");
8311 assert!(
8312 err.render(i18n::Locale::En).contains("does not contain"),
8313 "{err}"
8314 );
8315 }
8316
8317 #[test]
8318 fn solve_system_rejects_nonuniq_and_nonlinear() {
8319 let (x, y) = (var("x"), var("y"));
8320 let err =
8322 solve_system(&[sub(x.clone(), y.clone())], &["x".into(), "y".into()]).unwrap_err();
8323 let text = err.to_string();
8324 assert_eq!(err.code(), "underdetermined", "{text}");
8325 let err = solve_system(
8327 &[sub(x.clone(), num(1.0)), sub(x.clone(), num(2.0))],
8328 &["x".into()],
8329 )
8330 .unwrap_err();
8331 assert_eq!(err.code(), "inconsistent", "{err}");
8332 let err = solve_system(
8335 &[sub(mul(x.clone(), y.clone()), num(1.0))],
8336 &["x".into(), "y".into()],
8337 )
8338 .unwrap_err();
8339 assert_eq!(err.code(), "in-equation", "{err}");
8340 assert!(
8341 err.render(i18n::Locale::En).contains("in equation 1:"),
8342 "{err}"
8343 );
8344 let Error::InEquation { error: inner, .. } = &err else {
8345 panic!("{err:?}")
8346 };
8347 assert_eq!(inner.code(), "nonlinear-equation", "{err:?}");
8348 let err = solve_system(&[sub(x.clone(), num(1.0))], &["x".into(), "x".into()]).unwrap_err();
8350 assert_eq!(err.code(), "invalid-input", "{err}");
8351 assert!(err.render(i18n::Locale::En).contains("twice"), "{err}");
8352 let err = solve_system(&[sub(x.clone(), num(1.0))], &[]).unwrap_err();
8354 assert_eq!(err.code(), "invalid-input", "{err}");
8355 assert!(
8356 err.render(i18n::Locale::En).contains("at least one"),
8357 "{err}"
8358 );
8359 let eq1 = sub(add(x.clone(), y.clone()), num(3.0));
8362 let eq2 = sub(x.clone(), y.clone());
8363 let eq3 = sub(mul(num(2.0), add(x.clone(), y.clone())), num(6.0));
8364 let sol = solve_system(&[eq1, eq2, eq3], &["x".into(), "y".into()]).unwrap();
8365 let Expr::Mat(rows) = &sol else {
8366 panic!("解必须是矩阵");
8367 };
8368 let mut env = HashMap::new();
8369 env.insert("x".to_string(), eval(&rows[0][0], &env).unwrap());
8370 env.insert("y".to_string(), eval(&rows[1][0], &env).unwrap());
8371 assert!((env["x"] - 1.5).abs() < 1e-12 && (env["y"] - 1.5).abs() < 1e-12);
8373 }
8374
8375 #[test]
8376 fn solve_rejects_hidden_unknown_in_exponent() {
8377 let (x, y) = (var("x"), var("y"));
8384 let err = solve_system(
8386 &[sub(add(x.clone(), pow(num(2.0), x.clone())), num(3.0))],
8387 &["x".into()],
8388 )
8389 .unwrap_err();
8390 match &err {
8391 Error::InEquation {
8394 index,
8395 error: inner,
8396 } => {
8397 assert_eq!(*index, 1, "{err:?}");
8398 let Error::NonlinearEquation { why, .. } = &**inner else {
8399 panic!("the inner variant must survive the wrap: {err:?}")
8400 };
8401 assert!(why.contains("exponent"), "{why}");
8402 }
8403 other => panic!("{other:?}"),
8404 }
8405 let err = solve_linear(
8408 &sub(add(x.clone(), pow(num(2.0), x.clone())), num(3.0)),
8409 "x",
8410 )
8411 .unwrap_err();
8412 assert!(
8413 matches!(
8414 &err,
8415 Error::NonlinearEquation { why, .. } if why.contains("exponent")
8416 ),
8417 "{err}"
8418 );
8419 let ok = solve_system(&[sub(x.clone(), pow(num(2.0), y.clone()))], &["x".into()])
8421 .expect("2^y 不含 x,应可解");
8422 let Expr::Mat(m) = &ok else {
8423 panic!("应是列向量")
8424 };
8425 let mut env = HashMap::new();
8426 env.insert("y".to_string(), 3.0);
8427 assert!((eval(&m[0][0], &env).unwrap() - 8.0).abs() < 1e-12);
8428 }
8429
8430 #[test]
8431 fn solve_system_detects_structurally_zero_coefficients() {
8432 let (x, y) = (var("x"), var("y"));
8436 let k2 = var("k2");
8437 let err = solve_system(
8440 &[
8441 sub(x.clone(), num(1.0)),
8442 sub(
8443 add(mul(sub(k2.clone(), k2.clone()), y.clone()), x.clone()),
8444 num(1.0),
8445 ),
8446 ],
8447 &["x".into(), "y".into()],
8448 )
8449 .unwrap_err();
8450 let text = err.to_string();
8451 assert_eq!(err.code(), "underdetermined", "{text}");
8452 let k = var("k");
8454 let err = solve_system(
8455 &[
8456 sub(add(x.clone(), y.clone()), num(1.0)),
8457 sub(mul(k.clone(), add(x.clone(), y.clone())), k.clone()),
8458 ],
8459 &["x".into(), "y".into()],
8460 )
8461 .unwrap_err();
8462 let text = err.to_string();
8463 assert_eq!(err.code(), "underdetermined", "{text}");
8464 assert!(is_structurally_zero(&sub(k2.clone(), k2.clone())), "k−k");
8466 assert!(
8467 is_structurally_zero(&sub(mul(k.clone(), x.clone()), mul(x.clone(), k.clone()))),
8468 "k·x − x·k"
8469 );
8470 assert!(
8471 is_structurally_zero(&sub(sub(mul(num(2.0), x.clone()), x.clone()), x.clone())),
8472 "2x − x − x"
8473 );
8474 assert!(
8475 is_structurally_zero(&sub(
8476 mul(x.clone(), pow(x.clone(), num(2.0))),
8477 pow(x.clone(), num(3.0))
8478 )),
8479 "x·x² − x³"
8480 );
8481 for (bad, why) in [
8488 (sub(pow(k2.clone(), num(2.0)), k2.clone()), "a²−a"),
8489 (
8490 sub(
8491 pow(mul(num(2.0), k2.clone()), num(2.0)),
8492 mul(num(2.0), k2.clone()),
8493 ),
8494 "(2a)²−2a",
8495 ),
8496 (
8497 sub(
8498 pow(mul(x.clone(), k2.clone()), num(2.0)),
8499 mul(x.clone(), k2.clone()),
8500 ),
8501 "(xy)²−xy",
8502 ),
8503 (pow(k2.clone(), num(3.0)), "a³(单项非零)"),
8504 ] {
8505 assert!(!is_structurally_zero(&bad), "{why} 被误判为恒零");
8506 }
8507 assert!(
8510 is_structurally_zero(&sub(pow(k2.clone(), num(2.0)), mul(k2.clone(), k2.clone()))),
8511 "a² − a·a"
8512 );
8513 assert!(
8514 is_structurally_zero(&sub(
8515 pow(mul(num(2.0), k2.clone()), num(2.0)),
8516 mul(num(4.0), pow(k2.clone(), num(2.0)))
8517 )),
8518 "(2a)² − 4a²"
8519 );
8520 assert!(!is_structurally_zero(&sub(k2.clone(), var("k3"))));
8522 assert!(!is_structurally_zero(&sub(x.clone(), num(1.0))));
8523 assert!(is_structurally_zero(&sub(
8525 Expr::Call("exp".into(), vec![x.clone()]),
8526 Expr::Call("exp".into(), vec![x.clone()])
8527 )));
8528 let kv = var("k");
8531 assert!(is_structurally_zero(&sub(
8532 div(x.clone(), kv.clone()),
8533 div(x.clone(), kv.clone())
8534 )));
8535 let (a, b) = (var("a"), var("b"));
8538 let expandable = sub(
8539 pow(add(a.clone(), b.clone()), num(2.0)),
8540 add(
8541 add(
8542 pow(a.clone(), num(2.0)),
8543 mul(num(2.0), mul(a.clone(), b.clone())),
8544 ),
8545 pow(b.clone(), num(2.0)),
8546 ),
8547 );
8548 assert!(
8549 !is_structurally_zero(&expandable),
8550 "(a+b)² − (a²+2ab+b²) 需要展开,证不出就该返回 false"
8551 );
8552 }
8553
8554 #[test]
8555 fn solve_system_allows_equations_with_different_dimensions() {
8556 let dims = dims_of(&[
8561 Decl {
8562 name: "k".into(),
8563 quantity: "stiffness".into(),
8564 unit: Some("N/m".into()),
8565 },
8566 Decl {
8567 name: "F".into(),
8568 quantity: "load".into(),
8569 unit: Some("N".into()),
8570 },
8571 Decl {
8572 name: "x".into(),
8573 quantity: "d1".into(),
8574 unit: Some("m".into()),
8575 },
8576 Decl {
8577 name: "L".into(),
8578 quantity: "len".into(),
8579 unit: Some("m".into()),
8580 },
8581 Decl {
8582 name: "y".into(),
8583 quantity: "d2".into(),
8584 unit: Some("m".into()),
8585 },
8586 ])
8587 .unwrap();
8588 let sys = Expr::Call(
8590 "solve".into(),
8591 vec![
8592 Expr::Mat(vec![
8593 vec![sub(mul(var("k"), sub(var("x"), var("y"))), var("F"))],
8594 vec![sub(var("x"), var("L"))],
8595 ]),
8596 Expr::Mat(vec![vec![var("x")], vec![var("y")]]),
8597 ],
8598 );
8599 let d = dim_check(&sys, &dims).expect("量纲不同的方程应被接受");
8600 assert_eq!(d, parse_unit("m").unwrap(), "解的每个分量都是位移");
8601 let bad = Expr::Call(
8603 "solve".into(),
8604 vec![
8605 Expr::Mat(vec![
8606 vec![sub(var("x"), var("F"))], ]),
8608 Expr::Mat(vec![vec![var("x")]]),
8609 ],
8610 );
8611 let err = dim_check(&bad, &dims).unwrap_err();
8612 assert_eq!(err.code(), "operator-dimension-mismatch", "{err}");
8613 assert!(err.render(i18n::Locale::En).contains("`-`"), "{err}");
8614 }
8615
8616 #[test]
8617 fn matrix_and_scalar_cannot_be_added() {
8618 let mat = Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0), num(4.0)]]);
8621 for bad in [
8622 add(num(3.0), mat.clone()),
8623 sub(mat.clone(), num(3.0)),
8624 add(mat.clone(), var("x")),
8625 ] {
8626 let err = shape_check(&bad).unwrap_err();
8627 assert_eq!(err.code(), "matrix-scalar-mix", "{err}");
8629 }
8630 assert!(shape_check(&add(mat.clone(), num(0.0))).is_ok());
8632 assert!(shape_check(&sub(mat.clone(), num(0.0))).is_ok());
8633 assert!(shape_check(&add(mat.clone(), mat.clone())).is_ok());
8635 let other = Expr::Mat(vec![vec![num(1.0), num(2.0), num(3.0)]]);
8637 let err = shape_check(&add(mat, other)).unwrap_err();
8638 assert_eq!(err.code(), "shape-mismatch", "{err}");
8639 let prod = mul(
8642 Expr::Mat(vec![vec![num(1.0), num(0.0)], vec![num(0.0), num(1.0)]]),
8643 Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0), num(4.0)]]),
8644 );
8645 assert!(
8646 shape_check(&add(prod.clone(), num(0.0))).is_ok(),
8647 "矩阵乘积 + 0 应合法"
8648 );
8649 let err = shape_check(&add(prod, num(1.0))).unwrap_err();
8650 assert_eq!(err.code(), "matrix-scalar-mix", "{err}");
8651 }
8652
8653 #[test]
8654 fn matrix_shapes_are_checked_even_when_only_flatten_knows_them() {
8655 let x = var("x");
8662 let r1 = Expr::Call("roots".into(), vec![sub(x.clone(), num(1.0)), x.clone()]);
8664 let r2 = Expr::Call(
8665 "roots".into(),
8666 vec![sub(pow(x.clone(), num(2.0)), num(1.0)), x.clone()],
8667 );
8668 let err = shape_check(&add(r1.clone(), r2.clone())).unwrap_err();
8669 assert_eq!(err.code(), "shape-mismatch", "{err}");
8670 let coeffs = Expr::Call(
8673 "poly_coeffs".into(),
8674 vec![add(pow(x.clone(), num(2.0)), x.clone()), x.clone()],
8675 );
8676 let err = shape_check(&mul(coeffs.clone(), r2.clone())).unwrap_err();
8679 match &err {
8680 Error::ShapeMismatch(why) => assert!(
8681 why.contains("cannot multiply") && why.contains("1, 3"),
8682 "the sentence must name both factors: {why}"
8683 ),
8684 other => panic!("{other:?}"),
8685 }
8686 let m = Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0), num(4.0)]]);
8688 let col = Expr::Mat(vec![vec![num(1.0)], vec![num(2.0)]]);
8689 assert!(shape_check(&mul(m.clone(), col.clone())).is_ok());
8690 assert!(shape_check(&add(m.clone(), m.clone())).is_ok());
8692 let err = shape_check(&add(m, col)).unwrap_err();
8694 assert_eq!(err.code(), "shape-mismatch", "{err}");
8695 }
8696
8697 #[test]
8698 fn solve_system_rejects_matrix_coefficients() {
8699 let mat = Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0), num(4.0)]]);
8702 let x = var("x");
8703 let err =
8704 solve_system(&[sub(mul(mat.clone(), x.clone()), var("b"))], &["x".into()]).unwrap_err();
8705 assert_eq!(err.code(), "in-equation", "{err}");
8706 let Error::InEquation {
8707 index,
8708 error: inner,
8709 } = &err
8710 else {
8711 panic!("{err:?}")
8712 };
8713 assert_eq!(*index, 1, "{err:?}");
8714 assert_eq!(inner.code(), "matrix-coefficient", "{err:?}");
8715 let err = solve_system(&[sub(x.clone(), mat)], &["x".into()]).unwrap_err();
8718 assert_eq!(err.code(), "in-equation", "{err}");
8719 let Error::InEquation { error: inner, .. } = &err else {
8720 panic!("{err:?}")
8721 };
8722 let Error::MatrixCoefficient(name) = &**inner else {
8723 panic!("{err:?}")
8724 };
8725 assert_eq!(name, "<constant>", "{err:?}");
8726 }
8727
8728 #[test]
8729 fn expand_deep_reaches_nested_operators() {
8730 let x = var("x");
8735 let a = var("a");
8736 let c = var("c");
8737 let nested = mul(
8738 num(2.0),
8739 Expr::Call(
8740 "solve".into(),
8741 vec![sub(mul(a.clone(), x.clone()), c.clone()), x.clone()],
8742 ),
8743 );
8744 assert!(expand_call(&nested).is_none(), "顶层展开不该命中嵌套算子");
8747 let deep = expand_deep(&nested);
8748 assert!(
8749 !vars_of(&deep).contains(&"x".to_string()),
8750 "深度展开后不该再有被求解的 x:{deep:?}"
8751 );
8752 let det_nested = add(
8754 Expr::Call(
8755 "det".into(),
8756 vec![Expr::Mat(vec![
8757 vec![num(1.0), num(2.0)],
8758 vec![num(3.0), num(4.0)],
8759 ])],
8760 ),
8761 num(1.0),
8762 );
8763 let d = simplify(&expand_deep(&det_nested));
8764 assert!(matches!(d, Expr::Num(_)), "det(A)+1 应折成常数,得到 {d:?}");
8765 assert!((eval(&d, &HashMap::new()).unwrap() - (-1.0)).abs() < 1e-12);
8766 }
8767
8768 #[test]
8769 fn solve_system_routes_through_expand_and_flatten() {
8770 let (x, y) = (var("x"), var("y"));
8771 let sys = Expr::Call(
8772 "solve".into(),
8773 vec![
8774 Expr::Mat(vec![
8775 vec![sub(x.clone(), num(4.0))],
8776 vec![sub(y.clone(), num(1.0))],
8777 ]),
8778 Expr::Mat(vec![vec![x.clone(), y.clone()]]),
8779 ],
8780 );
8781 let expanded = expand_call(&sys).expect("方程组应可展开");
8783 let Expr::Mat(rows) = &expanded else {
8784 panic!("展开结果应是矩阵,得到 {expanded:?}");
8785 };
8786 assert_eq!(rows.len(), 2);
8787 assert!((eval(&rows[0][0], &HashMap::new()).unwrap() - 4.0).abs() < 1e-12);
8788 assert!(is_matrix_value(&sys), "方程组 solve 应是矩阵值");
8791 let single = Expr::Call(
8792 "solve".into(),
8793 vec![sub(mul(var("a"), var("x")), num(6.0)), var("x")],
8794 );
8795 assert!(!is_matrix_value(&single), "单变量 solve 是标量值");
8796 let mat_coeff = Expr::Call(
8799 "solve".into(),
8800 vec![
8801 sub(
8802 mul(
8803 Expr::Mat(vec![vec![num(1.0), num(0.0)], vec![num(0.0), num(1.0)]]),
8804 x.clone(),
8805 ),
8806 y.clone(),
8807 ),
8808 x,
8809 ],
8810 );
8811 let Expr::Call(_, mat_args) = &mat_coeff else {
8812 panic!("构造的应是 Call");
8813 };
8814 let err = solve_linear(&mat_args[0], "x").unwrap_err();
8815 assert_eq!(err.code(), "matrix-coefficient", "{err}");
8816 }
8817
8818 #[test]
8819 fn typo_suggestions_and_multiarg_mathml() {
8820 assert_eq!(closest_func("sqrtt"), Some("sqrt"));
8822 assert_eq!(closest_func("clampx"), Some("clamp"));
8826 assert_eq!(closest_func("adjiont"), Some("adjoint"));
8827 assert_eq!(closest_func("dett"), Some("det"));
8828 assert_eq!(closest_func("foobar"), None);
8830 let e = Expr::Call("sqrtt".into(), vec![var("x")]);
8831 let err = check_calls(&e).unwrap_err();
8832 let text = err.to_string();
8833 assert!(text.contains("sqrt"), "{text}");
8834
8835 let m = Expr::Call("min".into(), vec![var("a"), var("b")]);
8838 let xml = to_mathml(&m);
8839 assert!(xml.contains("<mo>,</mo>"), "{xml}");
8840 assert!(xml.contains("<mi>min</mi>"), "{xml}");
8841 }
8842
8843 #[test]
8844 fn horner_matches_power_form_and_only_touches_explicit_polynomials() {
8845 let e = add(
8848 mul(var("a"), pow(var("x"), num(3.0))),
8849 mul(var("b"), var("x")),
8850 );
8851 let h = horner_in(&e, "x").expect("显式多项式应可 Horner");
8852 assert!(!matches!(h, Expr::Num(_)));
8853 let case = [
8855 (0.0f64, 2.0f64, 3.0f64),
8856 (-1.5, 0.3, -2.0),
8857 (7.25, 1.0, 0.5),
8858 ];
8859 for (x, a, b) in case {
8860 let mut env = HashMap::new();
8861 env.insert("x".to_string(), x);
8862 env.insert("a".to_string(), a);
8863 env.insert("b".to_string(), b);
8864 let want = eval(&e, &env).unwrap();
8865 let got = eval(&h, &env).unwrap();
8866 assert!(
8867 (got - want).abs() <= 1e-12 * (1.0 + want.abs()),
8868 "x={x} Horner {got} vs 幂次 {want}"
8869 );
8870 }
8871 assert!(!contains_pow_of(&h, "x", 3.0), "Horner 后不该有 x^3:{h:?}");
8873
8874 let compact = pow(sub(var("u"), num(1.0)), num(3.0));
8876 assert!(horner_in(&compact, "u").is_none());
8877
8878 let lin = add(mul(var("a"), var("x")), var("b"));
8880 assert!(horner_in(&lin, "x").is_none());
8881 }
8882
8883 #[test]
8884 fn libm_lane_uses_libm_calls_and_rejects_alloc() {
8885 let e = pow(var("x"), num(0.5));
8887 let w = emit_block_libm(&e);
8888 assert!(w.contains("libm::sqrt"), "{w}");
8889 assert!(!w.contains(".sqrt()"), "{w}");
8890 let e = pow(var("x"), num(2.5));
8892 let w = emit_block_libm(&e);
8893 assert!(w.contains("libm::pow"), "{w}");
8894 let e = pow(var("x"), num(3.0));
8896 let w = emit_block_libm(&e);
8897 assert!(w.contains("libm::pow"), "{w}");
8898 let e = Expr::Call("exp".into(), vec![var("x")]);
8900 let w = emit_block_libm(&e);
8901 assert!(w.contains("libm::exp"), "{w}");
8902 let e = Expr::Call("abs".into(), vec![var("x")]);
8904 let w = emit_block_libm(&e);
8905 assert!(w.contains("libm::fabs"), "{w}");
8906 let m = Expr::Mat(vec![vec![num(1.0), num(2.0)]]);
8908 let w = emit_block_libm(&m);
8909 assert!(w.contains("no_std"), "{w}");
8910 let e = Expr::Call("clamp".into(), vec![var("x"), num(0.0), num(1.0)]);
8912 let w = emit_block_libm(&e);
8913 assert!(w.contains(".max(0.0).min(1.0)"), "{w}");
8914 let e = Expr::Call("arg".into(), vec![var("x")]);
8916 let w = emit_block_libm(&e);
8917 assert!(w.contains("compile_error!"), "{w}");
8918 }
8919
8920 #[test]
8921 fn negative_base_fractional_power_is_not_folded_to_nan() {
8922 let e = pow(num(-8.0), div(num(1.0), num(3.0)));
8926 let folded = simplify(&e);
8927 assert!(
8928 !matches!(folded, Expr::Num(v) if v.is_nan()),
8929 "不该折叠成 NaN:{folded:?}"
8930 );
8931 let v = eval_value(&folded, &HashMap::new())
8933 .unwrap()
8934 .as_scalar()
8935 .unwrap();
8936 assert!((v.re - 1.0).abs() < 1e-12, "{v:?}");
8937 assert!((v.im - 3.0f64.sqrt()).abs() < 1e-12, "{v:?}");
8938 assert!(matches!(simplify(&pow(num(4.0), num(0.5))), Expr::Num(v) if v == 2.0));
8940 assert!(matches!(simplify(&pow(num(-2.0), num(3.0))), Expr::Num(v) if v == -8.0));
8941 }
8942
8943 #[test]
8944 fn negative_literal_sqrt_is_rejected_by_real_emission_not_deferred_to_nan() {
8945 let e = Expr::Call("sqrt".into(), vec![num(-4.0)]);
8946 let real = emit_block(&e);
8947 assert!(real.contains("compile_error!"), "{real}");
8948 let complex = emit_block_complex(&e);
8951 assert!(
8952 complex.contains("__c_sqrt") && !complex.contains("compile_error!"),
8953 "{complex}"
8954 );
8955 let value = eval_value(&e, &HashMap::new())
8956 .unwrap()
8957 .as_scalar()
8958 .unwrap();
8959 assert_eq!(value, C::new(0.0, 2.0));
8960 }
8961
8962 #[test]
8963 fn matrix_power_folds_to_explicit_products_or_rejects() {
8964 let m = Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0), num(4.0)]]);
8966 let sq = Expr::Pow(Box::new(m.clone()), Box::new(num(2.0)));
8967 assert!(is_matrix_value(&sq), "整数幂的矩阵应可折叠");
8968 let want = [[7.0f64, 10.0], [15.0, 22.0]];
8972 match eval_value(&sq, &HashMap::new()).unwrap() {
8973 Value::Matrix(mm) => {
8974 for r in 0..2 {
8975 for c in 0..2 {
8976 assert_eq!(mm[r][c].re, want[r][c], "值层 [{r}][{c}]");
8977 }
8978 }
8979 }
8980 other => panic!("{other:?}"),
8981 }
8982 let flat = flatten_matrix_value(&sq).unwrap();
8983 match eval_value(&Expr::Mat(flat), &HashMap::new()).unwrap() {
8984 Value::Matrix(mm) => {
8985 for r in 0..2 {
8986 for c in 0..2 {
8987 assert_eq!(mm[r][c].re, want[r][c], "折叠 [{r}][{c}]");
8988 }
8989 }
8990 }
8991 other => panic!("{other:?}"),
8992 }
8993 assert!(!is_matrix_value(&Expr::Pow(
8995 Box::new(m.clone()),
8996 Box::new(num(2.5))
8997 )));
8998 let row = Expr::Mat(vec![vec![num(1.0), num(2.0)]]);
8999 assert!(!is_matrix_value(&Expr::Pow(
9000 Box::new(row),
9001 Box::new(num(2.0))
9002 )));
9003 let code = emit_block(&Expr::Pow(Box::new(m.clone()), Box::new(num(2.5))));
9006 assert!(code.contains("compile_error!"), "{code}");
9007 }
9008
9009 #[test]
9010 fn matrix_zero_power_is_identity_not_the_scalar_one() {
9011 let m = Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0), num(4.0)]]);
9012 let e = pow(m, num(0.0));
9013 let folded = simplify(&e);
9014 assert!(is_matrix_value(&folded), "M^0 必须保持矩阵类型:{folded:?}");
9015 let want = Value::Matrix(vec![vec![C::ONE, C::ZERO], vec![C::ZERO, C::ONE]]);
9016 assert_eq!(eval_value(&folded, &HashMap::new()).unwrap(), want);
9017 assert_eq!(
9018 eval_value(
9019 &Expr::Mat(flatten_matrix_value(&folded).unwrap()),
9020 &HashMap::new()
9021 )
9022 .unwrap(),
9023 want
9024 );
9025 let code = emit_block(&folded);
9026 assert!(
9027 code.contains("vec![vec![1.0, 0.0], vec![0.0, 1.0]]"),
9028 "{code}"
9029 );
9030 }
9031
9032 #[test]
9033 fn dot_and_norm_are_expanded_from_literals() {
9034 let a = Expr::Mat(vec![vec![num(1.0), num(2.0)]]);
9036 let b = Expr::Mat(vec![vec![num(3.0), num(4.0)]]);
9037 let d = Expr::Call("dot".into(), vec![a.clone(), b.clone()]);
9038 let v = eval_value(&d, &HashMap::new())
9039 .unwrap()
9040 .as_scalar()
9041 .map(|c| c.re);
9042 assert_eq!(v, Some(11.0));
9043 let n = Expr::Call("norm".into(), vec![a.clone()]);
9045 let v = eval_value(&n, &HashMap::new())
9046 .unwrap()
9047 .as_scalar()
9048 .map(|c| c.re);
9049 assert_eq!(v, Some(5.0f64.sqrt()));
9050 let decls = vec![Decl {
9052 name: "v".into(),
9053 quantity: "velocity".into(),
9054 unit: Some("m/s".into()),
9055 }];
9056 let dims = dims_of(&decls).unwrap();
9057 let ve = Expr::Mat(vec![vec![var("v"), var("v")]]);
9058 let dot = Expr::Call("dot".into(), vec![ve.clone(), ve.clone()]);
9059 assert_eq!(
9060 dim_check(&dot, &dims).unwrap(),
9061 parse_unit("m^2/s^2").unwrap(),
9062 "dot 的量纲是平方"
9063 );
9064 let norm = Expr::Call("norm".into(), vec![ve]);
9065 assert_eq!(
9066 dim_check(&norm, &dims).unwrap(),
9067 parse_unit("m/s").unwrap(),
9068 "norm 与元素同量纲"
9069 );
9070 let c = Expr::Mat(vec![vec![num(1.0), num(2.0), num(3.0)]]);
9072 assert!(expand_dot(&Expr::Call("dot".into(), vec![a, c])).is_none());
9073 let code = emit_block(&Expr::Call(
9075 "dot".into(),
9076 vec![
9077 Expr::Mat(vec![vec![num(1.0), num(2.0)]]),
9078 Expr::Mat(vec![vec![var("x"), var("y")]]),
9079 ],
9080 ));
9081 assert!(code.contains("x") && code.contains("y"), "{code}");
9082 }
9083
9084 #[test]
9085 fn determinant_and_inverse_reach_the_documented_orders() {
9086 let m2 = Expr::Mat(vec![vec![var("a"), var("b")], vec![var("c"), var("d")]]);
9088 let inv2 = Expr::Call("inv".into(), vec![m2.clone()]);
9089 assert_eq!(flatten_matrix_value(&inv2).expect("2 阶逆").len(), 2);
9090 let m3 = Expr::Mat(vec![
9091 vec![var("a"), var("b"), var("c")],
9092 vec![var("d"), var("e"), var("f")],
9093 vec![var("g"), var("h"), var("i")],
9094 ]);
9095 let inv3 = Expr::Call("inv".into(), vec![m3.clone()]);
9096 let flat3 = flatten_matrix_value(&inv3).expect("3 阶逆");
9097 assert_eq!(flat3.len(), 3);
9098 let m4 = Expr::Mat(vec![
9101 vec![num(1.0), num(2.0), num(3.0), num(4.0)],
9102 vec![num(5.0), num(6.0), num(7.0), num(8.0)],
9103 vec![num(9.0), num(10.0), num(11.0), num(12.0)],
9104 vec![num(13.0), num(14.0), num(15.0), num(16.0)],
9105 ]);
9106 assert!(flatten_matrix_value(&Expr::Call("inv".into(), vec![m4.clone()])).is_none());
9107
9108 let tri = Expr::Mat(vec![
9110 vec![num(1.0), num(5.0), num(6.0), num(7.0)],
9111 vec![num(0.0), num(2.0), num(8.0), num(9.0)],
9112 vec![num(0.0), num(0.0), num(3.0), num(10.0)],
9113 vec![num(0.0), num(0.0), num(0.0), num(4.0)],
9114 ]);
9115 let d4 = eval_value(&Expr::Call("det".into(), vec![tri]), &HashMap::new())
9116 .unwrap()
9117 .as_scalar()
9118 .map(|c| c.re);
9119 assert_eq!(d4, Some(24.0));
9120 let five: Vec<Vec<Expr>> = (0..5)
9122 .map(|i| (0..5).map(|j| num((i * 5 + j) as f64)).collect())
9123 .collect();
9124 let err = eval_value(
9125 &Expr::Call("det".into(), vec![Expr::Mat(five)]),
9126 &HashMap::new(),
9127 )
9128 .unwrap_err();
9129 assert_eq!(err.code(), "invalid-input", "{err}");
9130 assert!(err.to_string().contains("1–4"), "{err}");
9131
9132 let mut env = HashMap::new();
9134 for (k, v) in [
9135 ("a", 2.0),
9136 ("b", -1.0),
9137 ("c", 0.0),
9138 ("d", -1.0),
9139 ("e", 2.0),
9140 ("f", -1.0),
9141 ("g", 0.0),
9142 ("h", -1.0),
9143 ("i", 2.0),
9144 ] {
9145 env.insert(k.to_string(), v);
9146 }
9147 let flat = flatten_matrix_value(&inv3).unwrap();
9148 let m_val = match eval_value(&m3, &env).unwrap() {
9149 Value::Matrix(m) => m,
9150 other => panic!("{other:?}"),
9151 };
9152 let inv_val = match eval_value(&Expr::Mat(flat), &env).unwrap() {
9153 Value::Matrix(m) => m,
9154 other => panic!("{other:?}"),
9155 };
9156 #[allow(clippy::needless_range_loop)]
9159 for r in 0..3 {
9160 #[allow(clippy::needless_range_loop)]
9161 for c in 0..3 {
9162 let mut acc = C::ZERO;
9163 for k in 0..3 {
9164 acc = acc.add(m_val[r][k].mul(inv_val[k][c]));
9165 }
9166 let want = if r == c { 1.0 } else { 0.0 };
9167 assert!((acc.re - want).abs() < 1e-12, "M·M⁻¹[{r}][{c}] = {acc:?}");
9168 }
9169 }
9170 let mut sing = HashMap::new();
9172 for (k, v) in [("a", 1.0), ("b", 1.0), ("c", 1.0), ("d", 1.0)] {
9173 sing.insert(k.to_string(), v);
9174 }
9175 let err = eval_value(&inv2, &sing).unwrap_err();
9178 assert_eq!(err.code(), "division-by-zero", "{err}");
9179 assert!(matches!(err, Error::DivisionByZero), "{err}");
9180 }
9181
9182 #[test]
9183 fn buckingham_pi_recovers_reynolds() {
9184 let vars = vec![
9185 ("rho".to_string(), parse_unit("kg/m^3").unwrap()),
9186 ("v".to_string(), parse_unit("m/s").unwrap()),
9187 ("L".to_string(), parse_unit("m").unwrap()),
9188 ("mu".to_string(), parse_unit("Pa*s").unwrap()),
9189 ];
9190 let g = dimensionless_groups(&vars).unwrap();
9191 assert_eq!(g.len(), 1, "4 变量 / 秩 3 → 1 个无量纲群");
9192 let names: Vec<String> = vars.iter().map(|(n, _)| n.clone()).collect();
9193 assert_eq!(pi_text(&names, &g[0]), "rho·v·L·mu^-1");
9194 let mut acc = Dim::ZERO;
9196 for ((_, d), e) in vars.iter().zip(&g[0]) {
9197 acc = acc.mul_dim(d.scale_ratio((e * 2.0) as i32, 2).unwrap());
9198 }
9199 assert!(acc.is_zero(), "Π 必须无量纲:{}", acc.display());
9200 }
9201
9202 #[test]
9203 fn buckingham_pi_group_count_matches_theorem() {
9204 let mut base: Vec<(String, Dim)> = ["kg", "m", "s", "A", "K"]
9206 .iter()
9207 .map(|u| (u.to_string(), parse_unit(u).unwrap()))
9208 .collect();
9209 assert_eq!(dimensionless_groups(&base).unwrap().len(), 0);
9210 base.push(("F".to_string(), parse_unit("N").unwrap()));
9215 let g1 = dimensionless_groups(&base).unwrap();
9216 assert_eq!(g1.len(), 1, "6 变量 / 秩 5 → 1 个群");
9217 assert_eq!(
9218 pi_text(
9219 &base.iter().map(|(n, _)| n.clone()).collect::<Vec<_>>(),
9220 &g1[0]
9221 ),
9222 "kg·m·s^-2·F^-1",
9223 "F/(kg·m/s²) 的那个群"
9224 );
9225 let mut v = base.clone();
9228 v.push(("E".to_string(), parse_unit("J").unwrap()));
9229 assert_eq!(
9230 dimensionless_groups(&v).unwrap().len(),
9231 2,
9232 "7 变量 / 秩 5 → 2 个群"
9233 );
9234 }
9235
9236 #[test]
9237 fn dim_solve_finds_target_dimension() {
9238 let vars = vec![
9239 ("mass".to_string(), parse_unit("kg").unwrap()),
9240 ("acc".to_string(), parse_unit("m/s^2").unwrap()),
9241 ];
9242 assert_eq!(
9244 dim_solve(&vars, parse_unit("N").unwrap()).unwrap(),
9245 vec![1.0, 1.0]
9246 );
9247 let volt = parse_unit("V").unwrap();
9249 let err = dim_solve(&vars, volt).unwrap_err();
9250 assert_eq!(err.code(), "target-dimension-unreachable", "{err}");
9253 match &err {
9254 Error::TargetDimensionUnreachable { target, .. } => {
9255 assert_eq!(*target, volt.display().to_string());
9256 }
9257 other => panic!("{other:?}"),
9258 }
9259 assert!(
9260 err.to_string().contains(&volt.display().to_string()),
9261 "{err}"
9262 );
9263 let zero = dim_solve(&vars, Dim::ZERO).unwrap();
9265 assert_eq!(zero, vec![0.0, 0.0]);
9266 }
9267
9268 #[test]
9269 fn matrix_expression_codegen_matches_value_layer() {
9270 let a = Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0), num(4.0)]]);
9276 let b = Expr::Mat(vec![vec![num(5.0), num(6.0)], vec![num(7.0), num(8.0)]]);
9277 let row = Expr::Mat(vec![vec![num(1.0), num(2.0), num(3.0)]]);
9278 let cases = vec![
9279 transpose(row.clone()),
9280 add(a.clone(), b.clone()),
9281 sub(a.clone(), b.clone()),
9282 mul(a.clone(), b.clone()),
9283 mul(var("k"), a.clone()),
9284 neg(a.clone()),
9285 transpose(mul(a.clone(), b.clone())),
9286 ];
9287 let mut env = HashMap::new();
9288 env.insert("k".to_string(), 2.5);
9289 for e in &cases {
9290 let folded = flatten_matrix_value(e).unwrap_or_else(|| panic!("应可折叠:{e:?}"));
9291 let v1 = eval_value(e, &env).unwrap();
9292 let v2 = eval_value(&Expr::Mat(folded), &env).unwrap();
9293 assert_eq!(v1, v2, "折叠与值层不同值:{e:?}");
9294 assert!(is_matrix_value(e));
9295 assert!(
9296 emit_block(e).contains("vec!["),
9297 "矩阵值必须发射成 vec![...]"
9298 );
9299 }
9300 assert_eq!(
9302 emit_block(&transpose(row)).trim(),
9303 "{\n vec![vec![1.0], vec![2.0], vec![3.0]]\n }"
9304 );
9305 let jag = Expr::Mat(vec![vec![num(1.0)], vec![num(2.0)]]);
9308 let small = Expr::Mat(vec![vec![num(1.0)]]);
9309 assert!(!is_matrix_value(&add(small.clone(), jag)));
9310 assert!(!is_matrix_value(&transpose(var("A"))));
9311 assert!(!is_matrix_value(&add(num(1.0), var("k"))));
9312 assert!(is_matrix_value(&mul(var("A"), small)));
9316 }
9317
9318 #[test]
9319 fn reserved_j_is_not_a_parameter() {
9320 let decls = vec![Decl {
9323 name: "r".into(),
9324 quantity: "resistance".into(),
9325 unit: Some("V/A".into()),
9326 }];
9327 let e = add(var("r"), mul(var("j"), num(2.0)));
9328 assert_eq!(params_in_decl_order(&decls, &e), vec!["r".to_string()]);
9329 assert!(uses_complex(&e));
9330 let code = emit_block_complex(&e);
9331 assert!(
9332 code.contains("__c_add") && code.contains("(0.0, 1.0)"),
9333 "{code}"
9334 );
9335 assert!(!code.contains("__c_sqrt"), "未用到的算子不该被发射:{code}");
9336 assert!(!uses_complex(&add(var("r"), num(2.0))));
9338 }
9339
9340 #[test]
9341 fn diff_matches_finite_difference() {
9342 let f = div(
9344 mul(
9345 Expr::Call("exp".into(), vec![mul(num(2.0), var("x"))]),
9346 Expr::Call("sin".into(), vec![var("x")]),
9347 ),
9348 add(num(1.0), pow(var("x"), num(2.0))),
9349 );
9350 let df = simplify(&diff(&f, "x"));
9351 let mut env = HashMap::new();
9352 for x in [-1.3, -0.2, 0.4, 1.7] {
9353 env.insert("x".to_string(), x);
9354 let h = 1e-6;
9355 env.insert("x".to_string(), x + h);
9356 let fp = eval(&f, &env).unwrap();
9357 env.insert("x".to_string(), x - h);
9358 let fm = eval(&f, &env).unwrap();
9359 env.insert("x".to_string(), x);
9360 let analytic = eval(&df, &env).unwrap();
9361 let numeric = (fp - fm) / (2.0 * h);
9362 assert!(
9363 (analytic - numeric).abs() < 1e-5 * (1.0 + numeric.abs()),
9364 "x={x} analytic={analytic} numeric={numeric}"
9365 );
9366 }
9367 }
9368
9369 #[test]
9370 fn dim_check_catches_mismatch() {
9371 let decls = vec![
9372 Decl {
9373 name: "a".into(),
9374 quantity: "length".into(),
9375 unit: Some("m".into()),
9376 },
9377 Decl {
9378 name: "t".into(),
9379 quantity: "time".into(),
9380 unit: Some("s".into()),
9381 },
9382 ];
9383 let dims = dims_of(&decls).unwrap();
9384 assert!(dim_check(&div(var("a"), var("t")), &dims).is_ok());
9385 assert!(dim_check(&add(var("a"), var("t")), &dims).is_err());
9386 assert!(dim_check(&var("nope"), &dims).is_err());
9387 }
9388
9389 fn pat(rows: Vec<Vec<PatternCell>>) -> MatPattern {
9392 MatPattern { rows }
9393 }
9394 fn el(e: Expr) -> PatternCell {
9395 PatternCell::El(e)
9396 }
9397 const D: PatternCell = PatternCell::Dots;
9398
9399 #[test]
9400 fn recognize_identity() {
9401 let p = pat(vec![
9403 vec![el(num(1.0)), D, el(num(0.0))],
9404 vec![D, el(num(1.0)), D],
9405 vec![el(num(0.0)), D, el(num(1.0))],
9406 ]);
9407 assert_eq!(recognize_pattern(&p).unwrap(), MatrixKind::Identity);
9408 }
9409
9410 #[test]
9411 fn recognize_diag() {
9412 let p = pat(vec![
9413 vec![el(var("d")), D, el(num(0.0))],
9414 vec![D, el(var("d")), D],
9415 vec![el(num(0.0)), D, el(var("d"))],
9416 ]);
9417 assert!(matches!(
9418 recognize_pattern(&p).unwrap(),
9419 MatrixKind::Diag(_)
9420 ));
9421 let bad = pat(vec![
9423 vec![el(var("d")), D, el(num(0.0))],
9424 vec![D, el(var("e")), D],
9425 vec![el(num(0.0)), D, el(var("d"))],
9426 ]);
9427 assert!(recognize_pattern(&bad).is_err());
9428 }
9429
9430 #[test]
9431 fn recognize_tridiag() {
9432 let p = pat(vec![
9433 vec![el(var("b")), el(var("c")), D, el(num(0.0))],
9434 vec![el(var("a")), el(var("b")), el(var("c")), D],
9435 vec![D, el(var("a")), el(var("b")), el(var("c"))],
9436 vec![el(num(0.0)), D, el(var("a")), el(var("b"))],
9437 ]);
9438 match recognize_pattern(&p).unwrap() {
9439 MatrixKind::Tridiag { .. } => {}
9440 other => panic!("期望 Tridiag,得到 {other:?}"),
9441 }
9442 let mut bad = p;
9444 if let PatternCell::El(e) = &mut bad.rows[1][1] {
9445 *e = var("z");
9446 }
9447 assert!(matches!(
9448 recognize_pattern(&bad).unwrap_err(),
9449 Error::InvalidInput(ref why) if why.contains("tridiagonal")
9450 ));
9451 }
9452
9453 #[test]
9454 fn half_integer_dimensions() {
9455 let decls = vec![Decl {
9457 name: "a".into(),
9458 quantity: "area".into(),
9459 unit: Some("m^2".into()),
9460 }];
9461 let dims = dims_of(&decls).unwrap();
9462 let root = Expr::Call("sqrt".into(), vec![var("a")]);
9463 assert_eq!(dim_check(&root, &dims).unwrap(), parse_unit("m").unwrap());
9464
9465 let decls2 = vec![Decl {
9467 name: "t".into(),
9468 quantity: "time".into(),
9469 unit: Some("s".into()),
9470 }];
9471 let dims2 = dims_of(&decls2).unwrap();
9472 let root2 = Expr::Call("sqrt".into(), vec![var("t")]);
9473 let half = dim_check(&root2, &dims2).unwrap();
9474 assert_eq!(half.display(), "s^(1/2)");
9475 let sigma = var("sigma");
9477 let d_sigma = dim_check(
9478 &sigma,
9479 &dims_of(&[Decl {
9480 name: "sigma".into(),
9481 quantity: "warburg_coefficient".into(),
9482 unit: Some("V/A".into()),
9483 }])
9484 .unwrap(),
9485 )
9486 .unwrap();
9487 let inv_sqrt_s = div(num(1.0), root2.clone());
9489 let d_inv = dim_check(&inv_sqrt_s, &dims2).unwrap();
9490 let combined = d_sigma.mul_dim(d_inv);
9491 assert_eq!(
9493 combined.display(),
9494 "kg·m^2·s^(-7/2)·A^-2",
9495 "Ω·s^(-1/2) 量纲"
9496 );
9497 }
9498
9499 #[test]
9500 fn complex_impedance_arithmetic() {
9501 let z = add(var("R"), mul(var("j"), var("X")));
9503 let mut env = HashMap::new();
9504 env.insert("R".to_string(), 3.0);
9505 env.insert("X".to_string(), -4.0);
9506 match eval_value(&z, &env).unwrap() {
9507 Value::Scalar(c) => {
9508 assert_eq!((c.re, c.im), (3.0, -4.0));
9509 }
9510 other => panic!("期望标量,得到 {other:?}"),
9511 }
9512 let mag = Expr::Call(
9514 "sqrt".into(),
9515 vec![add(pow(var("R"), num(2.0)), pow(var("X"), num(2.0)))],
9516 );
9517 assert_eq!(eval(&mag, &env).unwrap(), 5.0);
9518
9519 let decls = vec![
9521 Decl {
9522 name: "R".into(),
9523 quantity: "resistance".into(),
9524 unit: Some("V/A".into()),
9525 },
9526 Decl {
9527 name: "X".into(),
9528 quantity: "reactance".into(),
9529 unit: Some("V/A".into()),
9530 },
9531 ];
9532 let dims = dims_of(&decls).unwrap();
9533 assert_eq!(
9534 dim_check(&z, &dims).unwrap(),
9535 parse_unit("V/A").unwrap(),
9536 "复阻抗量纲应仍是 Ω"
9537 );
9538
9539 let q = div(
9541 add(num(1.0), mul(var("j"), num(1.0))),
9542 add(num(1.0), mul(var("j"), num(-1.0))),
9543 );
9544 match eval_value(&q, &HashMap::new()).unwrap() {
9545 Value::Scalar(c) => {
9546 assert!(c.re.abs() < 1e-15, "re={}", c.re);
9547 assert!((c.im - 1.0).abs() < 1e-15, "im={}", c.im);
9548 }
9549 other => panic!("期望标量,得到 {other:?}"),
9550 }
9551 }
9552
9553 #[test]
9554 fn recognize_banded_k2() {
9555 let mk = |blank_at: &[(usize, usize)]| {
9557 let mut rows = Vec::new();
9558 for i in 0..5usize {
9559 let mut r = Vec::new();
9560 for j in 0..5usize {
9561 r.push(if i.abs_diff(j) <= 2 {
9562 el(var("v"))
9563 } else if blank_at.contains(&(i, j)) {
9564 D
9565 } else {
9566 el(num(0.0))
9567 });
9568 }
9569 rows.push(r);
9570 }
9571 pat(rows)
9572 };
9573 match recognize_pattern(&mk(&[])).unwrap() {
9574 MatrixKind::Banded { half_band, .. } => assert_eq!(half_band, 2),
9575 other => panic!("期望 Banded k=2,得到 {other:?}"),
9576 }
9577 match recognize_pattern(&mk(&[(0, 3), (0, 4), (3, 0), (4, 0)])).unwrap() {
9579 MatrixKind::Banded { half_band, .. } => assert_eq!(half_band, 2),
9580 other => panic!("省略号形态应为 Banded,得到 {other:?}"),
9581 }
9582 let mut bad = mk(&[]);
9584 bad.rows[0][4] = el(var("w"));
9585 assert!(!matches!(
9586 recognize_pattern(&bad),
9587 Ok(MatrixKind::Banded { .. })
9588 ));
9589 }
9592
9593 #[test]
9594 fn recognize_blockdiag2() {
9595 let bd = pat(vec![
9598 vec![el(var("p")), D, el(num(0.0)), el(num(0.0))],
9599 vec![D, el(var("p")), el(num(0.0)), el(num(0.0))],
9600 vec![el(num(0.0)), el(num(0.0)), el(var("q")), D],
9601 vec![el(num(0.0)), el(num(0.0)), D, el(var("q"))],
9602 ]);
9603 match recognize_pattern(&bd).unwrap() {
9604 MatrixKind::BlockDiag2 { .. } => {}
9605 other => panic!("期望 BlockDiag2,得到 {other:?}"),
9606 }
9607 let bd2 = pat(vec![
9609 vec![el(var("p")), D, D, D],
9610 vec![D, el(var("p")), D, D],
9611 vec![D, D, el(var("q")), D],
9612 vec![D, D, D, el(var("q"))],
9613 ]);
9614 match recognize_pattern(&bd2).unwrap() {
9615 MatrixKind::BlockDiag2 { .. } => {}
9616 other => panic!("省略号形态应为 BlockDiag2,得到 {other:?}"),
9617 }
9618 let bad = pat(vec![
9620 vec![el(var("p")), D, el(var("c")), el(num(0.0))],
9621 vec![D, el(var("p")), el(num(0.0)), el(num(0.0))],
9622 vec![el(num(0.0)), el(num(0.0)), el(var("q")), D],
9623 vec![el(num(0.0)), el(num(0.0)), D, el(var("q"))],
9624 ]);
9625 assert!(!matches!(
9626 recognize_pattern(&bad),
9627 Ok(MatrixKind::BlockDiag2 { .. })
9628 ));
9629 }
9630
9631 #[test]
9632 fn recognize_bidiag_both_orientations() {
9633 let up = pat(vec![
9636 vec![el(var("b")), el(var("c")), D, D],
9637 vec![D, el(var("b")), el(var("c")), D],
9638 vec![D, D, el(var("b")), el(var("c"))],
9639 vec![D, D, D, el(var("b"))],
9640 ]);
9641 match recognize_pattern(&up).unwrap() {
9642 MatrixKind::BidiagUpper { .. } => {}
9643 other => panic!("期望 BidiagUpper,得到 {other:?}"),
9644 }
9645 let lo = pat(vec![
9648 vec![el(var("b")), D, D, D],
9649 vec![el(var("a")), el(var("b")), D, D],
9650 vec![D, el(var("a")), el(var("b")), D],
9651 vec![D, D, el(var("a")), el(var("b"))],
9652 ]);
9653 match recognize_pattern(&lo).unwrap() {
9654 MatrixKind::BidiagLower { .. } => {}
9655 other => panic!("期望 BidiagLower,得到 {other:?}"),
9656 }
9657 let su = emit_matrix_ctor(
9659 "BU",
9660 &MatrixKind::BidiagUpper {
9661 b: var("b"),
9662 c: var("c"),
9663 },
9664 );
9665 assert!(
9666 su.contains("m[__row][__next] = cv;") && !su.contains("m[__next]"),
9667 "{su}"
9668 );
9669 let sl = emit_matrix_ctor(
9670 "BL",
9671 &MatrixKind::BidiagLower {
9672 a: var("a"),
9673 b: var("b"),
9674 },
9675 );
9676 assert!(sl.contains("m[__next][__row] = av;"), "{sl}");
9677 }
9678
9679 #[test]
9680 fn recognize_unknown_shape_rejected_with_guidance() {
9681 let p = pat(vec![
9684 vec![el(var("x")), D, el(var("y"))],
9685 vec![D, el(var("q")), D],
9686 vec![el(var("z")), D, el(var("w"))],
9687 ]);
9688 let text = recognize_pattern(&p).unwrap_err().render(i18n::Locale::En);
9689 assert!(
9690 text.contains("identity") && text.contains("diag") && text.contains("tridiag"),
9691 "{text}"
9692 );
9693 }
9694
9695 #[test]
9696 fn to_latex_dots_directions() {
9697 let p = Expr::MatPattern(pat(vec![
9698 vec![el(var("a")), D, el(var("b"))],
9699 vec![D, D, D],
9700 vec![el(var("c")), D, el(var("d"))],
9701 ]));
9702 let tex = to_latex(&p);
9703 assert!(tex.contains("\\cdots"), "{tex}");
9704 assert!(tex.contains("\\vdots"), "{tex}");
9705 assert!(tex.contains("\\ddots"), "{tex}");
9706 assert!(tex.contains("bmatrix"), "{tex}");
9707 }
9708
9709 #[test]
9710 fn solve_system_dimensions_are_checked_on_both_sides() {
9711 let dims = dims_of(&[
9718 Decl {
9719 name: "k".into(),
9720 quantity: "stiffness".into(),
9721 unit: Some("N/m".into()),
9722 },
9723 Decl {
9724 name: "F".into(),
9725 quantity: "load".into(),
9726 unit: Some("N".into()),
9727 },
9728 Decl {
9729 name: "x".into(),
9730 quantity: "displacement".into(),
9731 unit: Some("m".into()),
9732 },
9733 ])
9734 .unwrap();
9735 let good = Expr::Call(
9737 "solve".into(),
9738 vec![
9739 Expr::Mat(vec![vec![sub(mul(var("k"), var("x")), var("F"))]]),
9740 Expr::Mat(vec![vec![var("x")]]),
9741 ],
9742 );
9743 assert_eq!(
9744 dim_check(&good, &dims).unwrap(),
9745 parse_unit("m").unwrap(),
9746 "解的列向量元素量纲应是位移"
9747 );
9748 let bad = Expr::Call(
9751 "solve".into(),
9752 vec![
9753 Expr::Mat(vec![vec![sub(var("x"), var("F"))]]),
9754 Expr::Mat(vec![vec![var("x")]]),
9755 ],
9756 );
9757 let err = dim_check(&bad, &dims).unwrap_err();
9758 assert_eq!(err.code(), "operator-dimension-mismatch", "{err}");
9759 assert!(err.render(i18n::Locale::En).contains("`-`"), "{err}");
9760 }
9761
9762 #[test]
9763 fn roots_dimension_equals_variable_dimension() {
9764 let dims = dims_of(&[
9770 Decl {
9771 name: "a".into(),
9772 quantity: "inv_len".into(),
9773 unit: Some("1/m".into()),
9774 },
9775 Decl {
9776 name: "b".into(),
9777 quantity: "one".into(),
9778 unit: Some("1".into()),
9779 },
9780 Decl {
9781 name: "c".into(),
9782 quantity: "len".into(),
9783 unit: Some("m".into()),
9784 },
9785 Decl {
9786 name: "x".into(),
9787 quantity: "position".into(),
9788 unit: Some("m".into()),
9789 },
9790 ])
9791 .unwrap();
9792 let poly = add(
9794 sub(
9795 mul(var("a"), pow(var("x"), num(2.0))),
9796 mul(var("b"), var("x")),
9797 ),
9798 var("c"),
9799 );
9800 let call = Expr::Call("roots".into(), vec![poly, var("x")]);
9801 assert_eq!(
9802 dim_check(&call, &dims).unwrap(),
9803 parse_unit("m").unwrap(),
9804 "二次方程的根应是长度"
9805 );
9806 let mut bad = dims.clone();
9809 bad.insert("x".to_string(), parse_unit("s").unwrap());
9810 let err = dim_check(&call, &bad).unwrap_err();
9811 assert_eq!(err.code(), "operator-dimension-mismatch", "{err}");
9812 }
9813
9814 #[test]
9815 fn poly_coeffs_requires_a_dimensionless_variable() {
9816 let dims = dims_of(&[
9823 Decl {
9824 name: "k".into(),
9825 quantity: "stiffness_quad".into(),
9826 unit: Some("N/m^2".into()),
9829 },
9830 Decl {
9831 name: "F".into(),
9832 quantity: "load".into(),
9833 unit: Some("N".into()),
9834 },
9835 Decl {
9836 name: "x".into(),
9837 quantity: "len".into(),
9838 unit: Some("m".into()),
9839 },
9840 Decl {
9841 name: "s".into(),
9842 quantity: "norm".into(),
9843 unit: Some("1".into()),
9844 },
9845 ])
9846 .unwrap();
9847 let poly = add(mul(var("k"), pow(var("x"), num(2.0))), var("F"));
9849 let call = Expr::Call("poly_coeffs".into(), vec![poly, var("x")]);
9850 let err = dim_check(&call, &dims).unwrap_err();
9851 assert_eq!(err.code(), "invalid-input", "{err}");
9852 let en = err.render(crate::i18n::Locale::En);
9853 assert!(
9854 en.contains("dimension") && en.contains("dimensionless"),
9855 "{en}"
9856 );
9857 let ok = Expr::Call(
9859 "poly_coeffs".into(),
9860 vec![
9861 add(
9862 mul(num(2.0), pow(var("s"), num(2.0))),
9863 mul(num(3.0), var("s")),
9864 ),
9865 var("s"),
9866 ],
9867 );
9868 assert_eq!(dim_check(&ok, &dims).unwrap(), Dim::ZERO);
9869 }
9870
9871 #[test]
9872 fn dim_check_matrix_family() {
9873 let decls = vec![
9874 Decl {
9875 name: "a".into(),
9876 quantity: "l".into(),
9877 unit: Some("m".into()),
9878 },
9879 Decl {
9880 name: "b".into(),
9881 quantity: "l".into(),
9882 unit: Some("m".into()),
9883 },
9884 Decl {
9885 name: "t".into(),
9886 quantity: "t".into(),
9887 unit: Some("s".into()),
9888 },
9889 ];
9890 let dims = dims_of(&decls).unwrap();
9891 let m = Expr::Mat(vec![vec![var("a"), var("b")], vec![var("b"), var("a")]]);
9893 assert_eq!(dim_check(&m, &dims).unwrap(), parse_unit("m").unwrap());
9894 let bad = Expr::Mat(vec![vec![var("a")], vec![var("t")]]);
9896 assert!(dim_check(&bad, &dims).is_err());
9897 let pm = Expr::MatPattern(pat(vec![
9899 vec![el(var("a")), D, el(num(0.0))],
9900 vec![D, el(var("a")), D],
9901 vec![el(num(0.0)), D, el(var("a"))],
9902 ]));
9903 assert!(dim_check(&pm, &dims).is_ok());
9904 let pbad = Expr::MatPattern(pat(vec![
9905 vec![el(var("a")), D, el(num(0.0))],
9906 vec![D, el(var("t")), D],
9907 vec![el(num(0.0)), D, el(var("a"))],
9908 ]));
9909 assert!(dim_check(&pbad, &dims).is_err());
9910 }
9911
9912 #[test]
9913 fn mathml_shapes() {
9914 let x = to_mathml(&div(var("a"), var("b")));
9916 assert!(x.contains("<mfrac>"), "{x}");
9917 let p = to_mathml(&pow(var("x"), num(2.0)));
9919 assert!(x.contains("<mn>2</mn>") || p.contains("<msup>"), "{p}");
9920 let ix = to_mathml(&indexed("a", vec!["i".into(), "j".into()]));
9922 assert!(ix.contains("<msub>") && ix.contains("<mi>j</mi>"), "{ix}");
9923 let sm = to_mathml(&sum("i", num(1.0), num(3.0), pow(var("i"), num(2.0))));
9925 assert!(sm.contains("<munderover>"), "{sm}");
9926 let esc = to_mathml(&var("a<b"));
9928 assert!(esc.contains("<"), "{esc}");
9929 }
9930
9931 #[test]
9932 fn matrix_mul_eval_and_shapes() {
9933 use Value::Matrix;
9934 let a = Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0), num(4.0)]]);
9936 let b = Expr::Mat(vec![vec![num(5.0), num(6.0)], vec![num(7.0), num(8.0)]]);
9937 let prod = mul(a.clone(), b.clone());
9938 shape_check(&prod).unwrap();
9939 match eval_value(&prod, &HashMap::new()).unwrap() {
9940 Matrix(m) => {
9941 let got: Vec<Vec<f64>> =
9942 m.iter().map(|r| r.iter().map(|c| c.re).collect()).collect();
9943 assert_eq!(got, vec![vec![19.0, 22.0], vec![43.0, 50.0]]);
9944 assert!(
9945 m.iter().flatten().all(|c| c.is_real()),
9946 "实数矩阵不应带虚部"
9947 );
9948 }
9949 _ => panic!("期望矩阵"),
9950 }
9951 assert_eq!(shape_of(&transpose(a.clone())).unwrap(), Some((2, 2)));
9953 let row = Expr::Mat(vec![vec![num(1.0), num(2.0), num(3.0)]]);
9954 assert_eq!(shape_of(&transpose(row)).unwrap(), Some((3, 1)));
9955 }
9956
9957 #[test]
9958 fn matrix_shape_violations_rejected() {
9959 let a = Expr::Mat(vec![
9961 vec![num(1.0), num(2.0), num(3.0)],
9962 vec![num(4.0), num(5.0), num(6.0)],
9963 ]);
9964 let b = a.clone();
9965 let err = shape_check(&mul(a, b)).unwrap_err();
9966 assert_eq!(err.code(), "shape-mismatch", "{err}");
9967 match &err {
9969 Error::ShapeMismatch(why) => {
9970 assert!(
9971 why.contains("cannot multiply") && why.contains("2"),
9972 "{why}"
9973 );
9974 }
9975 other => panic!("{other:?}"),
9976 }
9977 let r2 = Expr::Mat(vec![vec![num(1.0)], vec![num(2.0)]]);
9979 let r3 = Expr::Mat(vec![vec![num(1.0)], vec![num(2.0)], vec![num(3.0)]]);
9980 assert_eq!(
9981 shape_check(&add(r2, r3)).unwrap_err().code(),
9982 "shape-mismatch"
9983 );
9984 let jag = Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0)]]);
9986 assert!(shape_of(&jag).is_err());
9987 let m = Expr::Mat(vec![vec![num(1.0)]]);
9989 let s = Expr::Mat(vec![vec![num(2.0)]]);
9990 assert_eq!(
9991 shape_check(&div(m, s)).unwrap_err().code(),
9992 "matrix-division-unsupported"
9993 );
9994 }
9995
9996 #[test]
9997 fn federate_inline_substitutes_in_order() {
9998 let set = FormulaSet {
10000 decls: vec![Decl {
10001 name: "x".into(),
10002 quantity: "d".into(),
10003 unit: None,
10004 }],
10005 uses: vec![],
10006 items: vec![
10007 FormulaItem {
10008 name: Some("a".into()),
10009 expr: add(var("x"), num(1.0)),
10010 line: 0,
10011 },
10012 FormulaItem {
10013 name: Some("b".into()),
10014 expr: mul(var("a"), num(2.0)),
10015 line: 0,
10016 },
10017 FormulaItem {
10018 name: Some("c".into()),
10019 expr: sub(var("b"), var("a")),
10020 line: 0,
10021 },
10022 ],
10023 };
10024 let fed = federate_inline(&set).unwrap();
10025 let mut env = HashMap::new();
10026 env.insert("x".to_string(), 3.0);
10027 assert_eq!(eval(&fed[2].expr, &env).unwrap(), 4.0);
10029 assert!(!vars_of(&fed[1].expr).contains(&"a".to_string()));
10031 }
10032
10033 #[test]
10034 fn matrix_ctors_compile_shape() {
10035 let src = emit_matrix_ctor(
10036 "M",
10037 &MatrixKind::Tridiag {
10038 a: var("a"),
10039 b: var("b"),
10040 c: var("c"),
10041 },
10042 );
10043 assert!(
10044 src.contains("pub fn M(a: f64, b: f64, c: f64, n: usize)"),
10045 "{src}"
10046 );
10047 assert!(src.contains("m[__row][__next] = cv;"), "{src}");
10048 let src_i = emit_matrix_ctor("I", &MatrixKind::Identity);
10049 assert!(src_i.contains("pub fn I(n: usize)"), "{src_i}");
10050 }
10051
10052 #[test]
10053 fn cse_emits_shared_lets() {
10054 let shared = add(var("a"), var("b"));
10055 let e = add(mul(shared.clone(), shared.clone()), shared.clone());
10056 let code = emit_block(&e);
10057 assert_eq!(code.matches("let __t0 = a + b;").count(), 1, "{code}");
10058 assert_eq!(code.matches("__t0").count(), 4, "{code}");
10060 }
10061
10062 #[test]
10068 fn from_error_for_fronterror_is_field_identical_to_plain() {
10069 let cases = vec![
10073 Error::NotPolynomial { var: "x".into() },
10074 Error::Inconsistent,
10075 Error::MalformedUnit("m^3/2".into(), "detail".into()),
10076 ];
10077 for err in cases {
10078 assert_eq!(
10079 FrontError::from(err.clone()),
10080 FrontError::plain(err.clone()),
10081 "{err:?}"
10082 );
10083 }
10084 }
10085
10086 #[test]
10087 fn a_missing_eval_variable_is_undeclared_symbol() {
10088 let err = eval(&var("x"), &HashMap::new()).unwrap_err();
10089 assert_eq!(err.code(), "undeclared-symbol", "{err}");
10090 assert!(err.render(crate::i18n::Locale::En).contains("`x`"), "{err}");
10091 }
10092
10093 #[test]
10094 fn a_jagged_pattern_matrix_is_a_shape_mismatch_in_every_lane() {
10095 let p = pat(vec![vec![el(num(1.0)), el(num(2.0))], vec![el(num(3.0))]]);
10096 let err = recognize_pattern(&p).unwrap_err();
10097 assert_eq!(err.code(), "shape-mismatch", "{err}");
10098 let err = dim_check(&Expr::MatPattern(p), &HashMap::new()).unwrap_err();
10099 assert_eq!(err.code(), "shape-mismatch", "{err}");
10100 }
10101
10102 #[test]
10103 fn the_unit_exponent_grid_range_and_numerator_are_typed() {
10104 let err = parse_ratio("3/x").unwrap_err();
10106 assert_eq!(err.code(), "malformed-unit", "{err}");
10107 let err = parse_unit("s")
10109 .unwrap()
10110 .scale_ratio(2_000_000_000, 2)
10111 .unwrap_err();
10112 assert_eq!(err.code(), "exponent-out-of-range", "{err}");
10113 assert!(
10114 err.render(crate::i18n::Locale::En)
10115 .contains("dimension grid range"),
10116 "{err}"
10117 );
10118 }
10119
10120 #[test]
10121 fn each_dim_lane_symbol_lookup_is_undeclared_symbol() {
10122 let mut dims = HashMap::new();
10123 dims.insert("u".to_string(), parse_unit("Pa").unwrap());
10124 dims.insert("t".to_string(), Dim::ZERO);
10125 let err = dim_check(&Expr::Deriv(Box::new(var("u")), "nope".into()), &dims).unwrap_err();
10127 assert_eq!(err.code(), "undeclared-symbol", "{err}");
10128 let err = dim_check(
10130 &Expr::Integral {
10131 var: "nope".into(),
10132 lower: Box::new(var("t")),
10133 upper: Box::new(var("t")),
10134 body: Box::new(var("u")),
10135 },
10136 &dims,
10137 )
10138 .unwrap_err();
10139 assert_eq!(err.code(), "undeclared-symbol", "{err}");
10140 let err = dim_check(
10142 &Expr::Indexed {
10143 name: "nope".into(),
10144 indices: vec!["i".into()],
10145 },
10146 &dims,
10147 )
10148 .unwrap_err();
10149 assert_eq!(err.code(), "undeclared-symbol", "{err}");
10150 }
10151
10152 #[test]
10153 fn mismatched_integral_bounds_are_a_dimension_mismatch() {
10154 let mut dims = HashMap::new();
10155 dims.insert("u".to_string(), parse_unit("Pa").unwrap());
10156 dims.insert("t".to_string(), Dim::ZERO);
10157 let err = dim_check(
10158 &Expr::Integral {
10159 var: "u".into(),
10160 lower: Box::new(var("t")),
10161 upper: Box::new(var("u")),
10162 body: Box::new(var("t")),
10163 },
10164 &dims,
10165 )
10166 .unwrap_err();
10167 assert_eq!(err.code(), "dimension-mismatch", "{err}");
10168 }
10169
10170 #[test]
10171 fn a_dimensional_argument_to_a_transcendental_is_rejected() {
10172 let mut dims = HashMap::new();
10173 dims.insert("u".to_string(), parse_unit("Pa").unwrap());
10174 let err = dim_check(&Expr::Call("sin".into(), vec![var("u")]), &dims).unwrap_err();
10175 assert_eq!(err.code(), "invalid-input", "{err}");
10176 assert!(
10177 err.render(crate::i18n::Locale::En)
10178 .contains("must be dimensionless"),
10179 "{err}"
10180 );
10181 }
10182
10183 #[test]
10184 fn elementwise_matrix_rows_must_agree() {
10185 let a = Expr::Mat(vec![vec![num(1.0), num(2.0)]]);
10186 let b = Expr::Mat(vec![vec![num(3.0)], vec![num(4.0)]]);
10187 let err = eval_value(&add(a, b), &HashMap::new()).unwrap_err();
10188 assert_eq!(err.code(), "shape-mismatch", "{err}");
10189 assert!(
10190 err.render(crate::i18n::Locale::En)
10191 .contains("rows disagree"),
10192 "{err}"
10193 );
10194 }
10195
10196 #[test]
10197 fn the_solve_and_inv_guards_are_typed_rejections() {
10198 let eqs = Expr::Mat(vec![vec![add(var("x"), num(-1.0))]]);
10200 let junk = Expr::Mat(vec![vec![num(1.0)]]);
10201 let err = eval_value(
10202 &Expr::Call("solve".into(), vec![eqs.clone(), junk]),
10203 &HashMap::new(),
10204 )
10205 .unwrap_err();
10206 assert_eq!(err.code(), "invalid-input", "{err}");
10207 assert!(
10208 err.render(crate::i18n::Locale::En)
10209 .contains("second argument"),
10210 "{err}"
10211 );
10212 let nonlin = Expr::Mat(vec![vec![Expr::Call("sin".into(), vec![var("x")])]]);
10214 let unknowns = Expr::Mat(vec![vec![var("x")]]);
10215 let err = eval_value(
10216 &Expr::Call("solve".into(), vec![nonlin, unknowns.clone()]),
10217 &HashMap::new(),
10218 )
10219 .unwrap_err();
10220 assert_eq!(err.code(), "invalid-input", "{err}");
10221 assert!(
10222 err.render(crate::i18n::Locale::En).contains("linear"),
10223 "{err}"
10224 );
10225 let err = eval_value(
10227 &Expr::Call("solve".into(), vec![var("x"), unknowns.clone()]),
10228 &HashMap::new(),
10229 )
10230 .unwrap_err();
10231 assert_eq!(err.code(), "invalid-input", "{err}");
10232 let big = Expr::Mat(vec![
10233 vec![num(1.0), num(0.0), num(0.0), num(0.0)],
10234 vec![num(0.0), num(1.0), num(0.0), num(0.0)],
10235 vec![num(0.0), num(0.0), num(1.0), num(0.0)],
10236 vec![num(0.0), num(0.0), num(0.0), num(1.0)],
10237 ]);
10238 let err = eval_value(&Expr::Call("inv".into(), vec![big]), &HashMap::new()).unwrap_err();
10239 assert_eq!(err.code(), "invalid-input", "{err}");
10240 assert!(
10241 err.render(crate::i18n::Locale::En).contains("order 1 to 3"),
10242 "{err}"
10243 );
10244 let _ = eqs;
10245 }
10246 #[test]
10252 fn a_zero_argument_call_names_the_function() {
10253 let err = eval_value(&Expr::Call("max".into(), vec![]), &HashMap::new()).unwrap_err();
10256 assert_eq!(err.code(), "invalid-input", "{err}");
10257 assert!(err.render(i18n::Locale::En).contains("`max`"), "{err}");
10258 let dims = HashMap::new();
10259 let err = dim_check(&Expr::Call("sin".into(), vec![]), &dims).unwrap_err();
10260 assert_eq!(err.code(), "invalid-input", "{err}");
10261 assert!(err.render(i18n::Locale::En).contains("`sin`"), "{err}");
10262 }
10263
10264 #[test]
10265 fn an_empty_unit_string_and_a_zero_scale_denominator_are_typed() {
10266 let err = parse_unit_spec("").unwrap_err();
10268 assert_eq!(err.code(), "malformed-unit", "{err}");
10269 assert!(
10270 err.render(i18n::Locale::En).contains("empty unit string"),
10271 "{err}"
10272 );
10273 let err = convert(1.0, "", "m").unwrap_err();
10274 assert_eq!(err.code(), "malformed-unit", "{err}");
10275 let err = parse_unit("m").unwrap().scale_ratio(1, 0).unwrap_err();
10276 assert_eq!(err.code(), "exponent-zero-denominator", "{err}");
10277 }
10278
10279 #[test]
10280 fn trace_rejects_a_non_square_matrix() {
10281 let m = Expr::Mat(vec![
10283 vec![num(1.0), num(2.0)],
10284 vec![num(3.0), num(4.0)],
10285 vec![num(5.0), num(6.0)],
10286 ]);
10287 let err = eval_value(&Expr::Call("trace".into(), vec![m]), &HashMap::new()).unwrap_err();
10288 assert_eq!(err.code(), "shape-mismatch", "{err}");
10289 assert!(err.render(i18n::Locale::En).contains("square"), "{err}");
10290 }
10291
10292 #[test]
10293 fn incompatible_units_reports_its_code() {
10294 let err = convert(1.0, "nF", "V").unwrap_err();
10296 assert_eq!(err.code(), "incompatible-units", "{err}");
10297 assert!(
10298 err.render(i18n::Locale::En).contains("cannot convert `nF`"),
10299 "{err}"
10300 );
10301 }
10302
10303 #[test]
10304 fn the_shape_lane_rejects_matrix_division_itself() {
10305 let a = Expr::Mat(vec![vec![num(2.0), num(4.0)]]);
10307 let b = Expr::Mat(vec![vec![num(2.0), num(2.0)]]);
10308 let err = shape_check(&div(a, b)).unwrap_err();
10309 assert_eq!(err.code(), "matrix-division-unsupported", "{err}");
10310 assert!(err.render(i18n::Locale::En).contains("inv(A) * b"), "{err}");
10311 }
10312
10313 #[test]
10314 fn quad_root_arity_guards_bite_in_both_lanes() {
10315 let dims = HashMap::new();
10317 let one = eval_value(
10318 &Expr::Call("__quad_root_1".into(), vec![var("x")]),
10319 &HashMap::new(),
10320 )
10321 .unwrap_err();
10322 assert_eq!(one.code(), "function-arity", "{one}");
10323 let four = eval_value(
10324 &Expr::Call(
10325 "__quad_root_2".into(),
10326 vec![var("x"), var("y"), var("z"), var("w")],
10327 ),
10328 &HashMap::new(),
10329 )
10330 .unwrap_err();
10331 assert_eq!(four.code(), "function-arity", "{four}");
10332 let one_d =
10333 dim_check(&Expr::Call("__quad_root_1".into(), vec![var("x")]), &dims).unwrap_err();
10334 assert_eq!(one_d.code(), "function-arity", "{one_d}");
10335 let four_d = dim_check(
10336 &Expr::Call(
10337 "__quad_root_2".into(),
10338 vec![var("x"), var("y"), var("z"), var("w")],
10339 ),
10340 &dims,
10341 )
10342 .unwrap_err();
10343 assert_eq!(four_d.code(), "function-arity", "{four_d}");
10344 }
10345
10346 #[test]
10347 fn sum_bounds_must_be_dimensionless() {
10348 let mut dims = HashMap::new();
10350 dims.insert("u".to_string(), parse_unit("Pa").unwrap());
10351 dims.insert("t".to_string(), Dim::ZERO);
10352 let err = dim_check(
10353 &Expr::Sum {
10354 var: "u".into(),
10355 lower: Box::new(var("t")),
10356 upper: Box::new(var("u")),
10357 body: Box::new(var("t")),
10358 },
10359 &dims,
10360 )
10361 .unwrap_err();
10362 assert_eq!(err.code(), "invalid-input", "{err}");
10363 assert!(
10364 err.render(i18n::Locale::En).contains("dimensionless"),
10365 "{err}"
10366 );
10367 }
10368
10369 #[test]
10370 fn an_unknown_function_in_the_dim_lane_falls_back_without_suggestion() {
10371 let mut dims = HashMap::new();
10374 dims.insert("t".to_string(), Dim::ZERO);
10375 let err = dim_check(&Expr::Call("no_such_fn".into(), vec![var("t")]), &dims).unwrap_err();
10376 assert_eq!(err.code(), "unknown-function", "{err}");
10377 let Error::UnknownFunction { name, suggestion } = &err else {
10378 panic!("{err:?}")
10379 };
10380 assert_eq!(name, "no_such_fn");
10381 assert!(suggestion.is_empty(), "{suggestion:?}");
10382 }
10383
10384 #[test]
10385 fn a_nonlinear_product_names_the_unknowns_it_involves() {
10386 let err =
10388 solve_system(&[sub(mul(var("x"), var("x")), num(1.0))], &["x".into()]).unwrap_err();
10389 let en = err.render(i18n::Locale::En);
10390 assert!(en.contains("not linear in `x`"), "{en}");
10391 assert!(!en.contains("the product"), "{en}");
10392 let err = solve_system(
10394 &[sub(mul(var("x"), var("y")), num(1.0))],
10395 &["x".into(), "y".into()],
10396 )
10397 .unwrap_err();
10398 let en = err.render(i18n::Locale::En);
10399 assert!(en.contains("not linear in `x, y`"), "{en}");
10400 let err = solve_system(
10404 &[sub(mul(var("x"), var("x")), num(1.0))],
10405 &["x".into(), "z".into()],
10406 )
10407 .unwrap_err();
10408 let en = err.render(i18n::Locale::En);
10409 assert!(en.contains("not linear in `x`"), "{en}");
10410 assert!(!en.contains("`x, z`"), "{en}");
10411 }
10412
10413 #[test]
10414 fn solve_system_names_the_failing_equation_in_both_frames() {
10415 let linear = sub(var("x"), num(1.0));
10417 let nonlinear = mul(var("x"), var("y")); let err = solve_system(&[linear, nonlinear], &["x".into(), "y".into()]).unwrap_err();
10419 assert_eq!(err.code(), "in-equation", "{err}");
10420 let en = err.render(i18n::Locale::En);
10421 assert!(en.contains("in equation 2:"), "{en}");
10422 assert!(en.contains("not linear in"), "{en}");
10423 let ja = err.render(i18n::Locale::Ja);
10427 assert!(ja.contains("2 番目の方程式:"), "{ja}");
10428 assert!(ja.contains("線形ではありません"), "{ja}");
10429 let front = FrontError::plain(err);
10431 let ja_front = front.in_locale(i18n::Locale::Ja);
10432 assert!(
10433 ja_front.msg.contains("線形ではありません"),
10434 "{}",
10435 ja_front.msg
10436 );
10437 }
10438
10439 #[test]
10440 fn in_equation_renders_the_inner_in_the_target_locale() {
10441 let composed = Error::InEquation {
10442 index: 3,
10443 error: Box::new(Error::UndeclaredSymbol("k".into())),
10444 };
10445 assert_eq!(composed.code(), "in-equation");
10446 let ja = composed.render(i18n::Locale::Ja);
10447 assert!(ja.contains("3 番目の方程式:"), "{ja}");
10448 assert!(ja.contains("`k`"), "{ja}");
10449 let en = composed.render(i18n::Locale::En);
10450 assert!(en.contains("in equation 3:"), "{en}");
10451 assert!(en.contains("`k`"), "{en}");
10452 }
10453 #[test]
10454 fn the_eval_lane_refuses_operators_and_patterns_with_typed_variants() {
10455 let err = eval_value(&Expr::Grad(Box::new(var("u"))), &HashMap::new()).unwrap_err();
10459 assert_eq!(err.code(), "unsupported-operation", "{err}");
10460 assert!(
10461 err.render(i18n::Locale::En).contains("symbolic operators"),
10462 "{err}"
10463 );
10464 let p = pat(vec![vec![el(num(1.0)), D], vec![D, el(num(1.0))]]);
10465 let err = eval_value(&Expr::MatPattern(p), &HashMap::new()).unwrap_err();
10466 assert_eq!(err.code(), "unsupported-operation", "{err}");
10467 assert!(
10468 err.render(i18n::Locale::En).contains("pattern matrices"),
10469 "{err}"
10470 );
10471 }
10472
10473 #[test]
10474 fn a_diverging_dk_iteration_is_catalogued() {
10475 let err = numeric_roots(&[1e308, 0.0, 1.0]).unwrap_err();
10479 assert_eq!(err.code(), "root-finding-failed", "{err}");
10480 let en = err.render(i18n::Locale::En);
10481 assert!(en.contains("inf/NaN"), "{en}");
10482 }
10483}