inspect.parameter_sweep: check a design across a parameter's range (#2273) (#2276)

* inspect.parameter_sweep: check a design across a parameter's range

Rebuilds a copy of the design at each value of a parameter and reports what
no longer holds compared with the design as it is: features that fail or
warn, joint origins that are lost or turn over on their own part, sketch
planes that turn over, and sketch solves that fail or fold. The design is
not changed; each value's rebuild time is reported too.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* inspect.parameter_sweep: params doc matches what it takes and returns

`steps` takes at most 199 (200 values), as the check says; failed and
warned entries carry the feature's name; a lost origin says which one; a
value the parameter refuses gives {value, ms, ok: false, error}. The
refusal test covers steps 200.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* inspect.parameter_sweep: Japanese and Chinese labels

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Aac7mP9rthK3WsPpPRvCsF

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
NOWN-DEV
2026-10-25 01:19:00 +00:00
committed by GitHub
parent 2ff17c0fcb
commit c0640cb95e
8 changed files with 325 additions and 1 deletions
+1
View File
@@ -756,6 +756,7 @@
"cmd.inspect_interference": "Interference",
"cmd.inspect_isocurve": "Isocurve Analysis",
"cmd.inspect_minimum_radius": "Minimum Radius Analysis",
"cmd.inspect_parameter_sweep": "Parameter Sweep",
"cmd.inspect_silhouette": "Silhouette",
"cmd.inspect_zebra": "Zebra Analysis",
"cmd.joint_as_built": "As-Built Joint",
+1
View File
@@ -756,6 +756,7 @@
"cmd.inspect_interference": "干渉",
"cmd.inspect_isocurve": "アイソカーブ解析",
"cmd.inspect_minimum_radius": "最小半径解析",
"cmd.inspect_parameter_sweep": "パラメータスイープ",
"cmd.inspect_silhouette": "シルエット",
"cmd.inspect_zebra": "ゼブラ解析",
"cmd.joint_as_built": "現位置ジョイント",
+1
View File
@@ -756,6 +756,7 @@
"cmd.inspect_interference": "干涉",
"cmd.inspect_isocurve": "等参线分析",
"cmd.inspect_minimum_radius": "最小半径分析",
"cmd.inspect_parameter_sweep": "参数扫描",
"cmd.inspect_silhouette": "轮廓",
"cmd.inspect_zebra": "斑马纹分析",
"cmd.joint_as_built": "现状接头",
+2
View File
@@ -63,6 +63,7 @@ mod section;
pub(crate) use measure_sel::measure_items;
#[cfg(test)]
mod kernel_heal_tests;
mod parameter_sweep;
mod parameters;
mod plastic;
mod render;
@@ -295,6 +296,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> {
v.extend(sketch_clipboard::COMMANDS.iter());
v.extend(script::COMMANDS.iter());
v.extend(parameters::COMMANDS.iter());
v.extend(parameter_sweep::COMMANDS.iter());
v.extend(file::COMMANDS.iter());
v.extend(metadata::COMMANDS.iter());
v.extend(inspect::COMMANDS.iter());
+212
View File
@@ -0,0 +1,212 @@
//! Sweep a parameter and check that the design holds together at every value: that each feature
//! still builds, that every joint still finds its origins and none turned over, and that no
//! sketch plane flipped or sketch solve folded. A template driven by its parameters (one
//! design, many sizes) can be checked across its whole range before it is trusted, and the
//! report says what moved where, so a lost face or a flipped joint is found before a part is.
use std::collections::BTreeMap;
use serde_json::{Value, json};
use solidcraft_geom::Vec3;
use super::CommandSpec;
use crate::params::{bad, num, str_};
use crate::{Result, Session};
pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("inspect.parameter_sweep", "Parameter Sweep", sweep).icon("params").noundo().params(
"parameter: name; values: [number | expression] (at most 200) | from, to: numbers, steps? (default 10, at most 199: steps + 1 values) → \
for each value, in a copy of the design (the design itself is not changed): {value, ms (the rebuild), ok, failed: [{feature, name, error}], warned: [{feature, name, warning}] \
(features that build at the current value and fail or warn at this one), joints_lost: [{joint, name, origin?: a|b, why}], joints_flipped: [{joint, name, origin: a|b, degrees}] \
(an origin's z turned more than 90° on its own part from where it is now), sketches_flipped: [{sketch, name, degrees}] (the sketch plane's normal turned more than 90°), \
sketches_failed: [{sketch, name, failing, folded}] (a solve that fails, or keeps a triangle's turn or an offset's side only by flipping it)} \
(or {value, ms, ok: false, error} where the parameter takes no such value); \
summary: {values, ok, slowest_ms, failed, joints_lost, joints_flipped, sketches_flipped, sketches_failed} (how many values show each)",
)];
/// Values swept by one command, at most.
const MAX_VALUES: usize = 200;
/// A frame's origin and z axis, in its occurrence's coordinates.
type Frame = (Vec3, Vec3);
/// What the design looks like at one value.
struct Look {
errors: BTreeMap<u64, (String, String)>,
warnings: BTreeMap<u64, (String, String)>,
/// Per joint: its name, its two origins (none: not found, with why).
joints: BTreeMap<u64, (String, std::result::Result<Frame, String>, std::result::Result<Frame, String>)>,
/// Joints the solve could not apply.
unsolved: BTreeMap<u64, String>,
/// Per sketch: its name, its plane's normal and whether its solve is sound (failing and
/// folded constraints).
sketches: BTreeMap<u64, (String, Vec3, Vec<String>, Vec<String>)>,
}
fn look(s: &Session) -> Look {
let st = s.model.state();
let mut errors = BTreeMap::new();
let mut warnings = BTreeMap::new();
for r in &s.model.results {
if let Some(e) = &r.error {
errors.insert(r.id, (r.name.clone(), e.clone()));
}
if let Some(w) = &r.warning {
warnings.insert(r.id, (r.name.clone(), w.clone()));
}
}
// In its own part's frame: an origin that turns over on its part is a lost reference; a part
// the joints place anew is only its consequence.
let frame = |o: &solidcraft_doc::joints::JointOrigin| -> std::result::Result<Frame, String> {
let f = solidcraft_doc::joints::resolve_origin(&s.doc, &st, o).map_err(|e| e.to_string())?;
Ok((Vec3::new(f[3][0], f[3][1], f[3][2]), Vec3::new(f[2][0], f[2][1], f[2][2])))
};
let joints = s.doc.assembly.joints.iter().filter(|j| !j.suppressed).map(|j| (j.id, (j.name.clone(), frame(&j.a), frame(&j.b)))).collect();
let unsolved = if s.doc.assembly.joints.is_empty() {
BTreeMap::new()
} else {
solidcraft_doc::joints::solve(&s.doc, &st).errors.into_iter().map(|(id, _, why)| (id, why)).collect()
};
let sketches = st
.sketches
.iter()
.map(|k| {
let failing = if k.report.status == solidcraft_sketch::SolveStatus::Failed { k.report.failing.clone() } else { Vec::new() };
(k.feature, (k.name.clone(), k.plane.normal(), failing, k.report.folded.clone()))
})
.collect();
Look { errors, warnings, joints, unsolved, sketches }
}
/// The angle between two directions, in degrees (none if either has no length).
fn degrees(a: Vec3, b: Vec3) -> Option<f64> {
let (a, b) = (a.normalized()?, b.normalized()?);
Some(a.dot(b).clamp(-1.0, 1.0).acos().to_degrees())
}
/// What changed from `base` (the design as it is) to `at` (at one value).
fn compare(base: &Look, at: &Look) -> Value {
let failed: Vec<Value> = at
.errors
.iter()
.filter(|(id, _)| !base.errors.contains_key(id))
.map(|(id, (name, e))| json!({"feature": id, "name": name, "error": e}))
.collect();
let warned: Vec<Value> = at
.warnings
.iter()
.filter(|(id, (_, w))| base.warnings.get(id).is_none_or(|(_, b)| b != w) && !at.errors.contains_key(id))
.map(|(id, (name, w))| json!({"feature": id, "name": name, "warning": w}))
.collect();
let mut lost = Vec::new();
let mut flipped = Vec::new();
for (id, (name, a, b)) in &at.joints {
let Some((_, a0, b0)) = base.joints.get(id) else { continue };
for (side, now, was) in [("a", a, a0), ("b", b, b0)] {
match (now, was) {
(Err(why), Ok(_)) => lost.push(json!({"joint": id, "name": name, "origin": side, "why": why})),
(Ok(f), Ok(f0)) => {
if let Some(d) = degrees(f.1, f0.1).filter(|d| *d > 90.0) {
flipped.push(json!({"joint": id, "name": name, "origin": side, "degrees": (d * 10.0).round() / 10.0}));
}
}
_ => {}
}
}
if let (Some(why), None) = (at.unsolved.get(id), base.unsolved.get(id))
&& a.is_ok()
&& b.is_ok()
{
lost.push(json!({"joint": id, "name": name, "why": why}));
}
}
let mut sketches_flipped = Vec::new();
let mut sketches_failed = Vec::new();
for (id, (name, n, failing, folded)) in &at.sketches {
let Some((_, n0, failing0, folded0)) = base.sketches.get(id) else { continue };
if let Some(d) = degrees(*n, *n0).filter(|d| *d > 90.0) {
sketches_flipped.push(json!({"sketch": id, "name": name, "degrees": (d * 10.0).round() / 10.0}));
}
if (!failing.is_empty() && failing0.is_empty()) || (!folded.is_empty() && folded0.is_empty()) {
sketches_failed.push(json!({"sketch": id, "name": name, "failing": failing, "folded": folded}));
}
}
let ok = failed.is_empty() && lost.is_empty() && flipped.is_empty() && sketches_flipped.is_empty() && sketches_failed.is_empty();
json!({"ok": ok, "failed": failed, "warned": warned, "joints_lost": lost, "joints_flipped": flipped,
"sketches_flipped": sketches_flipped, "sketches_failed": sketches_failed})
}
/// The values to sweep.
fn values(p: &Value, cmd: &str) -> Result<Vec<Value>> {
match (p.get("values"), p.get("from"), p.get("to")) {
(Some(Value::Array(list)), None, None) => {
if list.is_empty() || list.len() > MAX_VALUES {
return Err(bad(cmd, format!("`values` must list 1…{MAX_VALUES} values")));
}
list.iter()
.map(|v| match v {
Value::Number(n) if n.as_f64().is_some_and(f64::is_finite) => Ok(v.clone()),
Value::String(x) if !x.trim().is_empty() && x.len() <= 1000 => Ok(v.clone()),
_ => Err(bad(cmd, "each value is a number or an expression")),
})
.collect()
}
(None, Some(_), Some(_)) => {
let finite = |k: &str| num(p, k).filter(|x| x.is_finite() && x.abs() <= 1e9).ok_or_else(|| bad(cmd, format!("`{k}` must be a number")));
let (from, to) = (finite("from")?, finite("to")?);
let steps = match p.get("steps") {
None | Some(Value::Null) => 10,
Some(_) => num(p, "steps")
.filter(|k| k.fract() == 0.0 && *k >= 1.0 && *k < MAX_VALUES as f64)
.ok_or_else(|| bad(cmd, format!("`steps` must be a whole number 1…{}", MAX_VALUES - 1)))? as usize,
};
Ok((0..=steps).map(|i| json!(from + (to - from) * i as f64 / steps as f64)).collect())
}
_ => Err(bad(cmd, "give `values`, or `from` and `to`")),
}
}
fn sweep(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "inspect.parameter_sweep";
let name = str_(p, "parameter").ok_or_else(|| bad(cmd, "`parameter` is required (parameters.list)"))?.to_string();
if !super::parameters::known(s, &name) {
return Err(bad(cmd, format!("no parameter `{name}` (parameters.list)")));
}
let values = values(p, cmd)?;
let base = look(s);
let mut results = Vec::new();
let mut count: BTreeMap<&str, usize> = BTreeMap::new();
let mut slowest: f64 = 0.0;
for v in values {
let mut x = s.scratch();
let t0 = std::time::Instant::now();
let changed = x.execute("parameters.change", &json!({"name": name, "expression": v}));
let ms = (t0.elapsed().as_secs_f64() * 1e4).round() / 10.0;
slowest = slowest.max(ms);
let mut r = match changed {
Ok(_) => compare(&base, &look(&x)),
Err(e) => json!({"ok": false, "error": e.to_string()}),
};
for key in ["failed", "joints_lost", "joints_flipped", "sketches_flipped", "sketches_failed"] {
if r[key].as_array().is_some_and(|a| !a.is_empty()) {
*count.entry(key).or_default() += 1;
}
}
if r["ok"] == json!(true) {
*count.entry("ok").or_default() += 1;
}
r["value"] = v;
r["ms"] = json!(ms);
results.push(r);
}
let get = |k: &str| count.get(k).copied().unwrap_or(0);
Ok(json!({
"parameter": name,
"results": results,
"summary": {"values": results.len(), "ok": get("ok"), "slowest_ms": slowest, "failed": get("failed"), "joints_lost": get("joints_lost"),
"joints_flipped": get("joints_flipped"), "sketches_flipped": get("sketches_flipped"), "sketches_failed": get("sketches_failed")},
}))
}
#[cfg(test)]
#[path = "parameter_sweep_tests.rs"]
mod tests;
@@ -0,0 +1,89 @@
use serde_json::{Value, json};
use crate::Session;
fn run(s: &mut Session, id: &str, p: Value) -> Value {
match s.execute(id, &p) {
Ok(v) => v,
Err(e) => panic!("{id} {p}: {e}"),
}
}
fn len(v: &Value) -> usize {
v.as_array().map_or(0, Vec::len)
}
/// A 40 x 30 x 5 plate (its own component) with a 6 mm hole at x = `hx` (a parameter, 20 mm),
/// and a pin (another component) held on the hole by a rigid joint.
fn pinned(s: &mut Session) {
run(s, "parameters.add", json!({"name": "hx", "expression": "20 mm"}));
run(s, "component.create", json!({"name": "Plate"}));
run(s, "solid.box", json!({"length": 40, "width": 30, "height": 5, "corner": [0, 0, 0]}));
run(s, "solid.hole", json!({"position": ["hx", 15, 5], "diameter": 6}));
run(s, "component.activate", json!({"component": "root"}));
run(s, "component.create", json!({"name": "Pin"}));
run(s, "solid.cylinder", json!({"base": [100, 0, 0], "axis": [0, 0, 1], "radius": 3, "height": 12, "operation": "new"}));
run(s, "component.activate", json!({"component": "root"}));
run(
s,
"joint.create",
json!({"type": "rigid", "a": {"occurrence": "Plate", "circle": [23, 15, 4.5]}, "b": {"occurrence": "Pin", "circle": [103, 0, 1]}, "name": "Seat"}),
);
}
#[test]
fn a_sweep_reports_where_a_hole_and_its_joint_are_lost_and_leaves_the_design_alone() {
let mut s = Session::default();
pinned(&mut s);
let r = run(&mut s, "inspect.parameter_sweep", json!({"parameter": "hx", "values": [10, "30 mm", 80]}));
let results = r["results"].as_array().cloned().unwrap_or_default();
assert_eq!(results.len(), 3, "{r}");
// Inside the plate the hole and the pin's joint hold.
for v in &results[..2] {
assert_eq!(v["ok"], json!(true), "{v}");
assert!(v["ms"].as_f64().is_some_and(|ms| ms >= 0.0), "{v}");
}
// Off the plate the joint has no hole to seat on.
let off = &results[2];
assert_eq!(off["ok"], json!(false), "{off}");
assert!(len(&off["joints_lost"]) + len(&off["failed"]) > 0, "{off}");
assert_eq!((r["summary"]["values"].as_u64(), r["summary"]["ok"].as_u64()), (Some(3), Some(2)), "{r}");
// The design is as it was.
assert_eq!(s.doc.params.iter().find(|p| p.name == "hx").map(|p| p.expr.as_str()), Some("20 mm"));
assert!(s.model.results.iter().all(|x| x.error.is_none()));
}
#[test]
fn a_sweep_reports_a_sketch_plane_that_turns_over() {
let mut s = Session::default();
run(&mut s, "parameters.add", json!({"name": "tilt", "expression": "30 deg"}));
run(&mut s, "construct.plane.at_angle", json!({"base": "XY", "axis": "X", "angle": "tilt", "name": "Tilted"}));
run(&mut s, "sketch.create", json!({"plane": "Tilted", "name": "OnTilted"}));
run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 5}));
run(&mut s, "sketch.finish", json!({}));
let r = run(&mut s, "inspect.parameter_sweep", json!({"parameter": "tilt", "from": 30, "to": 150, "steps": 2}));
let results = r["results"].as_array().cloned().unwrap_or_default();
assert_eq!(results.len(), 3, "{r}");
assert_eq!(results[1]["ok"], json!(true), "60° from where it is: {r}");
let turned = &results[2]["sketches_flipped"];
assert!(len(turned) == 1 && turned[0]["name"] == json!("OnTilted") && turned[0]["degrees"].as_f64().is_some_and(|d| d > 119.0), "{r}");
assert_eq!(r["summary"]["sketches_flipped"].as_u64(), Some(1), "{r}");
}
#[test]
fn a_sweep_refuses_what_it_cannot_sweep() {
let mut s = Session::default();
pinned(&mut s);
for bad in [
json!({"parameter": "nope", "values": [1]}),
json!({"parameter": "hx"}),
json!({"parameter": "hx", "values": []}),
json!({"parameter": "hx", "values": [null]}),
json!({"parameter": "hx", "from": 1, "to": 2, "steps": 0}),
json!({"parameter": "hx", "from": 1, "to": 2, "steps": 200}),
json!({"parameter": "hx", "from": 1, "to": 2, "steps": 500}),
json!({"parameter": "hx", "from": "a", "to": 2}),
] {
assert!(s.execute("inspect.parameter_sweep", &bad).is_err(), "{bad}");
}
}
+1 -1
View File
@@ -76,7 +76,7 @@ fn failing(s: &Session) -> Vec<Value> {
s.model.results.iter().filter_map(|r| r.error.as_ref().map(|e| json!({"feature": r.name, "error": e}))).collect()
}
fn known(s: &Session, name: &str) -> bool {
pub(super) fn known(s: &Session, name: &str) -> bool {
s.doc.param(name).is_some() || s.doc.features.iter().any(|f| f.param_names.iter().any(|n| n == name))
}
+18
View File
@@ -58,3 +58,21 @@ The table's Library picker selects material or appearance values. Choose **Follo
to clear an appearance override. Custom looks retain their colour and opacity across
activation, undo and save/reopen. See
[configuration commands and examples](https://github.com/bherbruck/solidcraft/blob/main/docs/configurations.md).
## Checking a design across a parameter's range
**Parameter Sweep** (`inspect.parameter_sweep`) rebuilds a copy of the design at each of a
parameter's values and reports what no longer holds, so a design meant to be driven by its
parameters (one template, many sizes) can be checked before it is trusted. The design itself is
not changed.
```json
{"command": "inspect.parameter_sweep", "params": {"parameter": "Width", "from": 300, "to": 510, "steps": 21}}
```
`values` lists the values instead (numbers or expressions). For each value it gives the rebuild's
time and what changed from the design as it is now: features that fail (`failed`) or warn
(`warned`), joints whose origin is no longer found (`joints_lost`) or turned over on its own part
(`joints_flipped`, more than 90°), sketch planes that turned over (`sketches_flipped`) and sketch
solves that fail or only hold by flipping a triangle's turn or an offset's side (`sketches_failed`).
`summary` counts the values that show each.