perf: a pass over the joints evaluates the design's parameters once (#6418)

Every joint whose offset, angle or values are expressions is worked out again
on each solve, twice per solve (re-expressing the joints, then the check that
leaves out one whose expression no longer works out), and each expression that
names a parameter evaluated every parameter of the design anew
(`Document::eval`). The cost grows with the joints with expressions times the
design's parameters: on 40 parts jointed to a plate, each joint lifted by an
expression and each part carrying 13 parameters (522 in all), a joint solve
took 0.55 s on main and takes 0.41 s now, a change of the lifts' parameter
1.06 s and 0.81 s (CLI, medians of 5 runs).

`joints::Params` keeps the design's parameter values once the first
expression names one, and `joints::expressed` takes it, so one pass evaluates
the parameters once. Values and error messages are those of `Document::eval`.

Test: `kept_parameters_evaluate_as_the_design_does` compares values and
errors with `Document::eval`.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NOWN-DEVandClaude Opus 5.5 authored and GitHub committed 2026-10-25 01:55:20 +00:00
1 parent 0063954286
commit b6a5a9166a
3 files changed
+52 -5

No files matched your search

+48 -3
View File
@@ -351,11 +351,33 @@ impl JointExprs {
/// Largest offset or value an expression may give a joint (mm, or radians for an angle).
const MAX_EXPR_VALUE: f64 = 1e9;
/// A design's parameter values, worked out the first time an expression names one and kept for
/// the next: a pass over the joints works out every joint's expressions again, and each would
/// otherwise evaluate every parameter of the design anew.
pub struct Params<'a> {
doc: &'a Document,
vals: std::cell::OnceCell<BTreeMap<String, crate::expr::Value>>,
}
impl<'a> Params<'a> {
pub fn new(doc: &'a Document) -> Params<'a> {
Params { doc, vals: std::cell::OnceCell::new() }
}
/// What [`Document::eval`] gives for `e`.
pub fn eval(&self, e: &str, kind: crate::expr::Kind) -> Result<f64> {
crate::expr::eval_with(e, &|n| {
self.vals.get_or_init(|| self.doc.param_values().0).get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`")))
})?
.to_kind(kind)
}
}
/// A joint's offset, angle and values worked out from its expressions (those without one keep
/// their numbers), or why one can't be: an unknown name, a wrong unit, or a number too large.
pub fn expressed(doc: &Document, j: &Joint) -> Result<(f64, f64, Vec<f64>)> {
pub fn expressed(params: &Params, j: &Joint) -> Result<(f64, f64, Vec<f64>)> {
let eval = |e: &str, kind: crate::expr::Kind, what: &str| -> Result<f64> {
let v = doc.eval(e, kind).map_err(|err| DocError::Invalid(format!("joint {}: {what} `{e}`: {err}", j.name)))?;
let v = params.eval(e, kind).map_err(|err| DocError::Invalid(format!("joint {}: {what} `{e}`: {err}", j.name)))?;
if v.is_finite() && v.abs() < MAX_EXPR_VALUE { Ok(v) } else { Err(DocError::Invalid(format!("joint {}: {what} `{e}` gives {v}", j.name))) }
};
let x = &j.exprs;
@@ -1878,11 +1900,12 @@ fn build<'a>(doc: &'a Document, st: &ModelState, vals: &Values, sol: &mut Soluti
.clone()
.map_err(DocError::Invalid)
};
let params = Params::new(doc);
for j in &joints {
// A joint whose expressions can't be worked out (a parameter gone) is left out rather
// than placed by numbers that no longer say what it was defined by.
if !j.exprs.is_empty()
&& let Err(e) = expressed(doc, j)
&& let Err(e) = expressed(&params, j)
{
sol.errors.push((j.id, j.name.clone(), e.to_string()));
continue;
@@ -2204,6 +2227,28 @@ mod tests {
}
}
/// The parameter values kept between expressions give what evaluating each expression on
/// its own gives, errors included.
#[test]
fn kept_parameters_evaluate_as_the_design_does() {
let mut doc = Document::new("p");
doc.set_param("W", "300 mm", None, None).unwrap();
doc.set_param("H", "W / 2", None, None).unwrap();
doc.set_param("A", "30 deg", None, None).unwrap();
let params = Params::new(&doc);
for (e, kind) in [
("W / 4", crate::expr::Kind::Length),
("H + 2 mm", crate::expr::Kind::Length),
("A * 2", crate::expr::Kind::Angle),
("12", crate::expr::Kind::Length),
] {
assert_eq!(params.eval(e, kind).unwrap(), doc.eval(e, kind).unwrap(), "{e}");
}
for (e, kind) in [("Q + 1", crate::expr::Kind::Length), ("A", crate::expr::Kind::Length)] {
assert_eq!(params.eval(e, kind).unwrap_err().to_string(), doc.eval(e, kind).unwrap_err().to_string(), "{e}");
}
}
fn close(a: &Mat, b: &Mat) -> bool {
let (t, r) = mismatch(a, b);
t < 1e-9 && r < 1e-9
+2 -1
View File
@@ -118,6 +118,7 @@ pub fn place(s: &mut Session) -> joints::Solution {
/// may have changed). One that can't be worked out (its parameter gone) keeps its numbers; the
/// solve leaves that joint out and says why.
fn reexpress(s: &mut Session) {
let params = joints::Params::new(&s.doc);
let changed: Vec<(usize, (f64, f64, Vec<f64>))> = s
.doc
.assembly
@@ -126,7 +127,7 @@ fn reexpress(s: &mut Session) {
.enumerate()
.filter(|(_, j)| !j.exprs.is_empty())
.filter_map(|(i, j)| {
let (o, a, mut q) = joints::expressed(&s.doc, j).ok()?;
let (o, a, mut q) = joints::expressed(&params, j).ok()?;
joints::clamp(j, &mut q);
((o, a) != (j.offset, j.angle) || q != j.values).then_some((i, (o, a, q)))
})
+2 -1
View File
@@ -169,12 +169,13 @@ fn inputs(s: &Session, t: &MotionTrace) -> Result<Value> {
let (occurrences, ids) = graph(s, t);
let st = s.model.state();
let seeds: BTreeMap<u64, &Vec<f64>> = t.seeds.iter().map(|(id, q)| (*id, q)).collect();
let params = joints::Params::new(&s.doc);
let mut joints = Vec::new();
for j in s.doc.assembly.joints.iter().filter(|j| ids.contains(&j.id)) {
let mut definition = j.clone();
definition.name.clear();
definition.values = seeds.get(&j.id).map(|q| (*q).clone()).unwrap_or_default();
let (offset, angle, q) = joints::expressed(&s.doc, &definition)?;
let (offset, angle, q) = joints::expressed(&params, &definition)?;
definition.offset = offset;
definition.angle = angle;
definition.values = q;