Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Reduce repeated sketch diagnostics and enable normal-CI profiling regressions (#2355) (#2359)

takuto-NA843c0bf97a4d
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs
index a6025acd1a..02afec7552 100644
--- a/crates/doc/src/document.rs
+++ b/crates/doc/src/document.rs
@@ -3372,14 +3372,36 @@ impl Document {
sk: &mut Sketch,
stored: &solidcraft_sketch::DrivingValues,
moved_from: Option<&Sketch>,
+ ) -> Result<solidcraft_sketch::SolveReport> {
+ self.solve_sketch_with_analysis(vals, sk, stored, moved_from, solidcraft_sketch::Analysis::Full)
+ }
+
+ /// [`Self::solve_sketch`] with the diagnostics needed by an internal edit. Parameter
+ /// application, continuation and offset refreshes run regardless of the requested level.
+ /// Model evaluation uses `solve_sketch` so its published report always has full diagnostics.
+ pub fn solve_sketch_with_analysis(
+ &self,
+ vals: &std::collections::BTreeMap<String, expr::Value>,
+ sk: &mut Sketch,
+ stored: &solidcraft_sketch::DrivingValues,
+ moved_from: Option<&Sketch>,
+ analysis: solidcraft_sketch::Analysis,
) -> Result<solidcraft_sketch::SolveReport> {
self.apply_dimension_values(vals, sk)?;
let was = |sk: &Sketch| moved_from.and_then(|from| sk.positions_in(from));
- let mut report = solidcraft_sketch::solve_after_edit(sk, stored, was(sk).as_deref());
- if !sk.offsets.is_empty() || !sk.freeform_offsets.is_empty() {
+ let offsets = !sk.offsets.is_empty() || !sk.freeform_offsets.is_empty();
+ // Offsets always require another solve after refresh. Only that last report is
+ // published; the first report only decides which state the second solve starts from.
+ let first_analysis = if offsets { solidcraft_sketch::Analysis::StatusOnly } else { analysis };
+ let mut report = solidcraft_sketch::solve_after_edit_with_analysis(sk, stored, was(sk).as_deref(), first_analysis);
+ if offsets {
// Source dimensions may have moved curves during the solve.
sk.refresh_offsets()?;
- report = if report.ok() { solidcraft_sketch::solve(sk) } else { solidcraft_sketch::solve_after_edit(sk, stored, was(sk).as_deref()) };
+ report = if report.ok() {
+ solidcraft_sketch::solve_with(sk, &solidcraft_sketch::Hold::default(), None, analysis, None)
+ } else {
+ solidcraft_sketch::solve_after_edit_with_analysis(sk, stored, was(sk).as_deref(), analysis)
+ };
}
Ok(report)
}
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index 3080f1b8ca..1c5ec0fae7 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -8,6 +8,24 @@ license.workspace = true
[lints]
workspace = true
+[features]
+# Turns on the parameter-contract audit recorder (`SOLIDCRAFT_PARAM_AUDIT`, see
+# `src/schema/record.rs`), for checking a new contract against the whole test suite.
+param-audit = []
+solver-profiling = ["solidcraft-sketch/solver-profiling"]
+
+[[example]]
+name = "sketch_analysis_bench"
+required-features = ["solver-profiling"]
+
+[[example]]
+name = "sketch_drag_bench"
+required-features = ["solver-profiling"]
+
+[[example]]
+name = "sketch_target_bench"
+required-features = ["solver-profiling"]
+
[dependencies]
solidcraft-geom = { workspace = true }
solidcraft-sketch = { workspace = true }
@@ -23,7 +41,6 @@ thiserror = { workspace = true }
log = { workspace = true }
web-time = { workspace = true }
-[features]
-# Turns on the parameter-contract audit recorder (`SOLIDCRAFT_PARAM_AUDIT`, see
-# `src/schema/record.rs`), for checking a new contract against the whole test suite.
-param-audit = []
+[dev-dependencies]
+# Normal CI exercises profiling assertions without enabling the production feature.
+solidcraft-sketch = { workspace = true, features = ["solver-profiling"] }
diff --git a/crates/engine/examples/sketch_analysis_bench.rs b/crates/engine/examples/sketch_analysis_bench.rs
new file mode 100644
index 0000000000..e7a10daaac
--- /dev/null
+++ b/crates/engine/examples/sketch_analysis_bench.rs
@@ -0,0 +1,124 @@
+//! Time the actual AutoConstrain command on the solve_profile grid, with no UI or test-only solves.
+
+use std::{error::Error, io::Write, path::PathBuf, sync::Arc, time::Instant};
+
+use serde_json::{Value, json};
+use solidcraft_engine::Session;
+use solidcraft_geom::Vec2;
+use solidcraft_sketch::{ConstraintKind, Sketch, profiling::capture};
+
+type Result<T> = std::result::Result<T, Box<dyn Error>>;
+
+fn grid(size: usize) -> Result<Sketch> {
+ let mut sk = Sketch::new();
+ let mut points = Vec::new();
+ let mut seed = 99u64;
+ let mut jitter = || {
+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ (seed >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0
+ };
+ for y in 0..size {
+ for x in 0..size {
+ let p = sk.add_point(Vec2::new(x as f64 * 10.0 + jitter(), y as f64 * 10.0 + jitter()), None)?;
+ points.push(p);
+ if x == 0 && y == 0 {
+ sk.add_constraint(ConstraintKind::Fix { p }, None)?;
+ }
+ for (other, horizontal) in [((x > 0).then(|| points.len() - 2), true), ((y > 0).then(|| points.len() - 1 - size), false)] {
+ if let Some(q) = other.and_then(|i| points.get(i)).copied() {
+ let l = sk.add_line_pts(q, p, None)?;
+ sk.add_constraint(if horizontal { ConstraintKind::Horizontal { l } } else { ConstraintKind::Vertical { l } }, None)?;
+ sk.add_constraint(ConstraintKind::Distance { p, q, value: 10.0 }, None)?;
+ }
+ }
+ }
+ }
+ Ok(sk)
+}
+
+fn prepare(size: usize) -> Result<Session> {
+ let mut s = Session::default();
+ s.execute("sketch.create", &json!({"plane": "XY"}))?;
+ let id = s.active_sketch.ok_or("missing active sketch")?;
+ *Arc::make_mut(&mut s.doc).sketch_mut(id)? = grid(size)?;
+ Ok(s)
+}
+
+fn run(s: &mut Session) -> Result<Value> {
+ Ok(s.execute("sketch.auto_constrain", &json!({"dimensions": false}))?)
+}
+
+fn percentile(samples: &[u64], percent: usize) -> u64 {
+ let mut sorted = samples.to_vec();
+ sorted.sort_unstable();
+ sorted.get((sorted.len() * percent).div_ceil(100).saturating_sub(1)).copied().unwrap_or(0)
+}
+
+fn main() -> Result<()> {
+ let mut size = 10usize;
+ let mut repeats = 10usize;
+ let mut warmup = 2usize;
+ let mut out: Option<PathBuf> = None;
+ let mut args = std::env::args().skip(1);
+ while let Some(key) = args.next() {
+ if key == "--help" {
+ println!("sketch_analysis_bench [--size 2..20] [--repeats 1..100] [--warmup 0..10] [--out FILE]");
+ return Ok(());
+ }
+ let value = args.next().ok_or_else(|| format!("missing value for {key}"))?;
+ match key.as_str() {
+ "--size" => size = value.parse()?,
+ "--repeats" => repeats = value.parse()?,
+ "--warmup" => warmup = value.parse()?,
+ "--out" => out = Some(value.into()),
+ _ => return Err(format!("unknown option {key}").into()),
+ }
+ }
+ if !(2..=20).contains(&size) || !(1..=100).contains(&repeats) || warmup > 10 {
+ return Err("size, repeats or warmup outside supported range (see --help)".into());
+ }
+ for _ in 0..warmup {
+ run(&mut prepare(size)?)?;
+ }
+ let mut samples = Vec::new();
+ let mut times = Vec::new();
+ let mut reference = None;
+ for _ in 0..repeats {
+ // Session creation, fixture generation and serialization are outside the timer.
+ let mut session = prepare(size)?;
+ let start = Instant::now();
+ let (response, profile) = capture(|| run(&mut session));
+ let elapsed_ns = start.elapsed().as_nanos().min(u64::MAX as u128) as u64;
+ let response = response?;
+ if response["dof"] != 0 || response["added"] != json!([]) || response["sketch"]["solved"] != true {
+ return Err(format!("unexpected AutoConstrain result: {response}").into());
+ }
+ let id = session.active_sketch.ok_or("missing active sketch")?;
+ let final_sketch = session.doc.sketch(id)?;
+ if let Some(expected) = &reference {
+ if final_sketch != expected {
+ return Err("AutoConstrain geometry changed between samples".into());
+ }
+ } else {
+ reference = Some(final_sketch.clone());
+ }
+ times.push(elapsed_ns);
+ let state = session.model.state();
+ let published_report = &state.sketch(id).ok_or("missing published sketch")?.report;
+ samples.push(json!({"elapsed_ns": elapsed_ns, "response": response, "profile": profile, "published_report": published_report}));
+ }
+ let output = json!({
+ "schema": "solidcraft/sketch-analysis-bench/1", "command": "sketch.auto_constrain",
+ "params": {"dimensions": false}, "size": size, "seed": 99, "repeats": repeats, "warmup": warmup,
+ "median_ns": percentile(&times, 50), "p95_ns": percentile(&times, 95),
+ "final_sketch": reference, "samples": samples,
+ });
+ let mut writer: Box<dyn Write> = match out {
+ Some(path) => Box::new(std::io::BufWriter::new(std::fs::File::create(path)?)),
+ None => Box::new(std::io::stdout().lock()),
+ };
+ serde_json::to_writer_pretty(&mut writer, &output)?;
+ writeln!(writer)?;
+ writer.flush()?;
+ Ok(())
+}
diff --git a/crates/engine/examples/sketch_drag_bench.rs b/crates/engine/examples/sketch_drag_bench.rs
new file mode 100644
index 0000000000..df15c69759
--- /dev/null
+++ b/crates/engine/examples/sketch_drag_bench.rs
@@ -0,0 +1,116 @@
+//! Engine time for live frames and release, independent of rendering/input scheduling.
+use std::{error::Error, io::Write, path::PathBuf, sync::Arc, time::Instant};
+
+use serde_json::{Value, json};
+use solidcraft_engine::Session;
+use solidcraft_geom::Vec2;
+use solidcraft_sketch::{Analysis, ConstraintKind, Hold, Sketch, profiling::capture, solve_with};
+
+type Result<T> = std::result::Result<T, Box<dyn Error>>;
+
+fn prepare(size: usize, pinned: bool, cold: bool) -> Result<Session> {
+ let mut s = Session::default();
+ s.execute("sketch.create", &json!({"plane": "XY"}))?;
+ let id = s.active_sketch.ok_or("missing sketch")?;
+ let mut sk = Sketch::new();
+ let mut points = Vec::new();
+ let mut seed = 99u64;
+ let mut jitter = || {
+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ (seed >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0
+ };
+ for y in 0..size {
+ for x in 0..size {
+ let p = sk.add_point(Vec2::new((x + 1) as f64 * 10.0 + jitter(), (y + 1) as f64 * 10.0 + jitter()), None)?;
+ points.push(p);
+ if pinned && x == 0 && y == 0 {
+ sk.add_constraint(ConstraintKind::Fix { p }, None)?;
+ }
+ for (other, horizontal) in [((x > 0).then(|| points.len() - 2), true), ((y > 0).then(|| points.len() - 1 - size), false)] {
+ if let Some(q) = other.and_then(|i| points.get(i)).copied() {
+ let l = sk.add_line_pts(q, p, None)?;
+ sk.add_constraint(if horizontal { ConstraintKind::Horizontal { l } } else { ConstraintKind::Vertical { l } }, None)?;
+ sk.add_constraint(ConstraintKind::Distance { p, q, value: 10.0 }, None)?;
+ }
+ }
+ }
+ }
+ if !solve_with(&mut sk, &Hold::default(), None, Analysis::StatusOnly, None).ok() {
+ return Err("grid preparation failed".into());
+ }
+ *Arc::make_mut(&mut s.doc).sketch_mut(id)? = sk;
+ if cold {
+ s.model = Default::default();
+ } else {
+ s.refresh();
+ }
+ Ok(s)
+}
+
+fn frame(s: &mut Session) -> Result<Value> {
+ let id = s.active_sketch.ok_or("missing sketch")?;
+ let sk = s.doc.sketch(id)?;
+ let p = sk.points.get(1).ok_or("missing point")?;
+ let params = json!({"entity": p.id, "from": [p.pos.x, p.pos.y], "to": [p.pos.x + 0.25, p.pos.y], "live": true});
+ Ok(s.execute("sketch.drag", &params)?)
+}
+
+fn main() -> Result<()> {
+ let mut size = 14usize;
+ let mut repeats = 10usize;
+ let mut out: Option<PathBuf> = None;
+ let mut args = std::env::args().skip(1);
+ while let Some(key) = args.next() {
+ let value = args.next().ok_or("missing option value")?;
+ match key.as_str() {
+ "--size" => size = value.parse()?,
+ "--repeats" => repeats = value.parse()?,
+ "--out" => out = Some(value.into()),
+ _ => return Err(format!("unknown option {key}").into()),
+ }
+ }
+ // The floating variant must stay within the solver's 400-variable redundancy cap so
+ // that this benchmark can require and compare nonempty published diagnostics.
+ if !(2..=14).contains(&size) || !(1..=100).contains(&repeats) {
+ return Err("size must be in 2..14 and repeats in 1..100".into());
+ }
+ let mut cases = Vec::new();
+ for (name, pinned, cold, release) in [
+ ("live-floating", false, false, false),
+ ("live-pinned", true, false, false),
+ ("release-floating", false, false, true),
+ ("first-frame", false, true, false),
+ ] {
+ let mut samples = Vec::new();
+ for i in 0..repeats + 2 {
+ let mut s = prepare(size, pinned, cold)?;
+ if release {
+ frame(&mut s)?;
+ }
+ let start = Instant::now();
+ let (response, profile) = capture(|| if release { s.execute("sketch.drag_end", &json!({})).map_err(Into::into) } else { frame(&mut s) });
+ let elapsed_ns = start.elapsed().as_nanos().min(u64::MAX as u128) as u64;
+ let response: Value = response?;
+ let id = s.active_sketch.ok_or("missing sketch")?;
+ let state = s.world_state();
+ let report = &state.sketch(id).ok_or("missing published sketch")?.report;
+ if !report.ok() || report.redundant.is_empty() {
+ return Err(format!("{name}: missing full diagnostics: {report:?}; response {response}; counters {:?}", profile.counters).into());
+ }
+ if i >= 2 {
+ samples
+ .push(json!({"elapsed_ns": elapsed_ns, "response": response, "profile": profile, "report": report, "sketch": s.doc.sketch(id)?}));
+ }
+ }
+ cases.push(json!({"case": name, "samples": samples}));
+ }
+ let output = json!({"schema": "solidcraft/sketch-drag-bench/1", "size": size, "seed": 99, "repeats": repeats, "warmup": 2, "cases": cases});
+ let mut writer: Box<dyn Write> = match out {
+ Some(path) => Box::new(std::io::BufWriter::new(std::fs::File::create(path)?)),
+ None => Box::new(std::io::stdout().lock()),
+ };
+ serde_json::to_writer_pretty(&mut writer, &output)?;
+ writeln!(writer)?;
+ writer.flush()?;
+ Ok(())
+}
diff --git a/crates/engine/examples/sketch_target_bench.rs b/crates/engine/examples/sketch_target_bench.rs
new file mode 100644
index 0000000000..b07f661262
--- /dev/null
+++ b/crates/engine/examples/sketch_target_bench.rs
@@ -0,0 +1,53 @@
+//! Matched command timings and analytic cursor-distance error for the reported four-bar.
+#[path = "../tests/support/four_bar.rs"]
+mod four_bar;
+use four_bar::Result;
+use serde_json::json;
+use solidcraft_geom::Vec2;
+use solidcraft_sketch::profiling::capture;
+use std::{io::Write, time::Instant};
+
+fn main() -> Result<()> {
+ let mut args = std::env::args().skip(1);
+ let path = args.next().ok_or("usage: sketch_target_bench OUTPUT.json [REPEATS]")?;
+ let repeats: usize = args.next().map(|v| v.parse()).transpose()?.unwrap_or(10);
+ if !(1..=100).contains(&repeats) {
+ return Err("repeats must be in 1..100".into());
+ }
+ let mut cases = Vec::new();
+ for target in [Vec2::new(-10.0, 8.0), Vec2::new(-10.0, -8.0), Vec2::new(20.0, 20.0), Vec2::new(20.0, 0.0), Vec2::new(-8.0, 6.0)] {
+ for events in [1, 16] {
+ let mut samples = Vec::new();
+ for i in 0..repeats + 2 {
+ let mut s = four_bar::session()?;
+ let from = four_bar::point(&s, "crank.end")?;
+ let side = four_bar::branch(&s)?;
+ let start = Instant::now();
+ let (result, profile) = capture(|| -> Result<()> {
+ for k in 1..=events {
+ let q = from + (target - from) * (k as f64 / events as f64);
+ let at = four_bar::point(&s, "crank.end")?;
+ s.execute("sketch.drag", &json!({"entity":"crank.end","from":[at.x,at.y],"to":[q.x,q.y],"live":true}))?;
+ }
+ Ok(())
+ });
+ let elapsed_ns = start.elapsed().as_nanos().min(u64::MAX as u128) as u64;
+ result?;
+ let actual = four_bar::point(&s, "crank.end")?;
+ let error = four_bar::length_error(&s)?;
+ if error > 1e-6 || four_bar::branch(&s)? != side {
+ return Err("length or branch violation".into());
+ }
+ if i >= 2 {
+ samples.push(json!({"elapsed_ns":elapsed_ns,"actual":[actual.x,actual.y],"length_error":error,"cursor_distance":actual.dist(target),"nearest_error":actual.dist(target*(10.0/target.len())),"profile":profile}));
+ }
+ }
+ cases.push(json!({"target":[target.x,target.y],"events":events,"samples":samples}));
+ }
+ }
+ let mut out = std::io::BufWriter::new(std::fs::File::create(path)?);
+ serde_json::to_writer_pretty(&mut out, &json!({"schema":"solidcraft/sketch-target-bench/1","repeats":repeats,"warmup":2,"cases":cases}))?;
+ writeln!(out)?;
+ out.flush()?;
+ Ok(())
+}
diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs
index a906c98075..bbee1a0e56 100644
--- a/crates/engine/src/cmd/sketch.rs
+++ b/crates/engine/src/cmd/sketch.rs
@@ -230,7 +230,7 @@ pub(super) fn edit<T>(
f: impl FnOnce(&mut Sketch, &mut solidcraft_doc::Document) -> Result<T>,
) -> Result<(T, Value)> {
let id = target_sketch(s, p, cmd)?;
- let (out, rep) = edit_solved(s, id, strict, |sk, doc| Ok((f(sk, doc)?, Left::Unsolved)))?;
+ let (out, rep) = edit_solved(s, id, strict, Analysis::Freedom, |sk, doc| Ok((f(sk, doc)?, Left::Unsolved)))?;
Ok((out, rep.map(|rep| report_json(&rep)).unwrap_or(Value::Null)))
}
@@ -263,10 +263,13 @@ impl Left {
/// `edit` of sketch `id` for a step that may solve the sketch itself: when it returns
/// [`Left::Solved`] (and offsets need not be recomputed) the sketch is not solved again and the
/// report is `None`.
+/// `analysis` must be `Full` when the report is published without a model evaluation (a live
+/// drag); command JSON only consumes freedom, and its later model evaluation publishes a full report.
pub(super) fn edit_solved<T>(
s: &mut Session,
id: u64,
strict: bool,
+ analysis: Analysis,
f: impl FnOnce(&mut Sketch, &mut solidcraft_doc::Document) -> Result<(T, Left)>,
) -> Result<(T, Option<SolveReport>)> {
let mut doc = (*s.doc).clone();
@@ -287,10 +290,11 @@ pub(super) fn edit_solved<T>(
doc.apply_dimension_values(&doc.param_values().0, &mut sk)?;
sk.refresh_offsets()?;
let unsolved = sk.clone();
- let mut rep = counted_solve(&mut sk, &Hold::default(), Some(&reference), Analysis::Full, None);
+ let first_analysis = if offsets { Analysis::StatusOnly } else { analysis };
+ let mut rep = counted_solve(&mut sk, &Hold::default(), Some(&reference), first_analysis, None);
if offsets {
sk.refresh_offsets()?;
- rep = counted_solve(&mut sk, &Hold::default(), Some(&reference), Analysis::Full, None);
+ rep = counted_solve(&mut sk, &Hold::default(), Some(&reference), analysis, None);
}
Some(settle(strict, rep, &mut sk, unsolved)?)
}
@@ -300,8 +304,8 @@ pub(super) fn edit_solved<T>(
sk.refresh_offsets()?;
let unsolved = sk.clone();
#[cfg(test)]
- solve_counts::record(Analysis::Full);
- let rep = doc.solve_sketch(&vals, &mut sk, &stored, None)?;
+ solve_counts::record(analysis);
+ let rep = doc.solve_sketch_with_analysis(&vals, &mut sk, &stored, None, analysis)?;
Some(settle(strict, rep, &mut sk, unsolved)?)
}
};
@@ -343,7 +347,7 @@ pub(super) fn counted_solve(
pub(super) fn solve_current(sk: &mut Sketch, doc: &solidcraft_doc::Document) -> Result<SolveReport> {
let stored = sk.driving_values();
let (values, _) = doc.param_values();
- Ok(doc.solve_sketch(&values, sk, &stored, None)?)
+ Ok(doc.solve_sketch_with_analysis(&values, sk, &stored, None, Analysis::Freedom)?)
}
/// Solves run on this thread by [`counted_solve`] and the edit's own solve: (all of them, those
@@ -361,7 +365,7 @@ pub(super) mod solve_counts {
pub fn record(analysis: Analysis) {
COUNTS.with(|c| {
let (n, full) = c.get();
- c.set((n + 1, full + usize::from(analysis == Analysis::Full)));
+ c.set((n + 1, full + usize::from(analysis != Analysis::StatusOnly)));
});
}
@@ -1515,7 +1519,7 @@ pub(super) fn apply_in_order(sk: &mut Sketch, rep: &SolveReport, first: &[Ent],
driven: false,
text: None,
}));
- let ok = solve_with(&mut trial, &h, None, Analysis::Full, None).ok();
+ let ok = solve_with(&mut trial, &h, None, Analysis::StatusOnly, None).ok();
trial.constraints.retain(|c| c.id != TEMP);
if ok && !collapsed(sk, &trial) {
*sk = trial;
@@ -1525,7 +1529,7 @@ pub(super) fn apply_in_order(sk: &mut Sketch, rep: &SolveReport, first: &[Ent],
// Both could move but holding either one leads nowhere: solve as usual.
if !first_locked && !second_locked {
let mut trial = sk.clone();
- if solve(&mut trial).ok() {
+ if solve_with(&mut trial, &Hold::default(), None, Analysis::StatusOnly, None).ok() {
*sk = trial;
return Ok(());
}
@@ -1535,7 +1539,7 @@ pub(super) fn apply_in_order(sk: &mut Sketch, rep: &SolveReport, first: &[Ent],
/// Degrees of freedom of a sketch as it is.
pub(super) fn dof_now(sk: &Sketch) -> usize {
- solve(&mut sk.clone()).dof
+ solve_with(&mut sk.clone(), &Hold::default(), None, Analysis::Freedom, None).dof
}
/// A constraint just added that removes no degree of freedom (`before` → the edit's `info`) is
@@ -2406,7 +2410,7 @@ fn move_point(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.move_point";
let to = req_vec2(cmd, p, "to")?;
let id = target_sketch(s, p, cmd)?;
- let (_, rep) = edit_solved(s, id, false, |sk, _| {
+ let (_, rep) = edit_solved(s, id, false, Analysis::Freedom, |sk, _| {
let q = point_ref(sk, p.get("point"), cmd, "point")?;
Ok(((), drag_entity(sk, Ent::Point(q), &[], to, to, false).1.solve_again()))
})?;
@@ -2432,7 +2436,8 @@ fn drag_frame(s: &mut Session, p: &Value, live: bool) -> Result<(Value, Option<c
let id = target_sketch(s, p, cmd)?;
// The sketch's report as last evaluated: a live frame keeps its degrees of freedom.
let last = s.model.result(id).and_then(|r| r.state.sketch(id)).map(|ss| ss.report.clone());
- let (d, rep) = edit_solved(s, id, false, |sk, doc| {
+ let analysis = if live { Analysis::Full } else { Analysis::Freedom };
+ let (d, rep) = edit_solved(s, id, false, analysis, |sk, doc| {
let r = p.get("entity").and_then(Value::as_str).ok_or_else(|| bad(cmd, "`entity` must be a sketch point or curve"))?;
let e = ent(sk, r).ok_or_else(|| bad(cmd, format!("unknown sketch entity `{r}`")))?;
let with = match p.get("with") {
diff --git a/crates/engine/src/cmd/sketch_constraints.rs b/crates/engine/src/cmd/sketch_constraints.rs
index 59617b7415..8ac590467a 100644
--- a/crates/engine/src/cmd/sketch_constraints.rs
+++ b/crates/engine/src/cmd/sketch_constraints.rs
@@ -138,7 +138,7 @@ fn try_add(sk: &mut Sketch, doc: &mut solidcraft_doc::Document, k: ConstraintKin
return None;
}
let mut trial = sk.clone();
- let rep = solidcraft_sketch::solve(&mut trial);
+ let rep = solidcraft_sketch::solve_with(&mut trial, &solidcraft_sketch::Hold::default(), None, solidcraft_sketch::Analysis::Freedom, None);
if rep.ok() && rep.dof < dof {
*sk = trial;
return Some(rep.dof);
@@ -150,13 +150,12 @@ fn try_add(sk: &mut Sketch, doc: &mut solidcraft_doc::Document, k: ConstraintKin
None
}
-fn run_auto(sk: &mut Sketch, doc: &mut solidcraft_doc::Document, p: &Value, datum: usize) -> (Vec<String>, usize) {
+fn run_auto(sk: &mut Sketch, doc: &mut solidcraft_doc::Document, p: &Value, datum: usize, mut dof: usize) -> (Vec<String>, usize) {
use ConstraintKind::*;
let tol = num(p, "tolerance").filter(|t| *t > 0.0).unwrap_or(0.01);
let atol = num(p, "angle_tolerance").filter(|t| *t > 0.0).unwrap_or(1.0).to_radians();
let dims = crate::params::bool_(p, "dimensions").unwrap_or(true);
let n0 = sk.constraints.len();
- let mut dof = dof_now(sk);
let mut trials = 0;
let mut attempt = |sk: &mut Sketch, doc: &mut solidcraft_doc::Document, k: ConstraintKind, dim: bool, dof: &mut usize| {
if *dof == 0 || trials >= MAX_TRIALS {
@@ -258,7 +257,9 @@ fn auto(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
if !rep.keeps_orientation() {
return Err(bad(cmd, rep.failure(|f| format!("the sketch constraints conflict ({f})"))));
}
- Ok(run_auto(sk, doc, p, datum))
+ // This is the exact state just solved for the current parameter values. Trials update
+ // its freedom whenever they change constraints; no separate initial solve is needed.
+ Ok(run_auto(sk, doc, p, datum, rep.dof))
})?;
Ok(json!({"added": added, "dof": dof, "sketch": info}))
}
diff --git a/crates/engine/src/cmd/sketch_constraints_tests.rs b/crates/engine/src/cmd/sketch_constraints_tests.rs
index c68343ff9e..56063ccdcc 100644
--- a/crates/engine/src/cmd/sketch_constraints_tests.rs
+++ b/crates/engine/src/cmd/sketch_constraints_tests.rs
@@ -155,6 +155,35 @@ fn auto_constrain_fully_constrains_a_rough_sketch() {
assert!(r["added"].as_array().unwrap().len() >= 3, "{r}");
}
+#[test]
+fn internal_freedom_queries_skip_redundancy_and_keep_constraint_acceptance() {
+ use solidcraft_sketch::{ConstraintKind, Sketch, profiling::capture};
+
+ let mut sk = Sketch::new();
+ let q = sk.add_point(Vec2::new(10.0, 2.0), None).unwrap();
+ let k = ConstraintKind::Distance { p: 0, q, value: 10.0 };
+ sk.add_constraint(k.clone(), None).unwrap();
+ let redundant = sk.add_constraint(k.clone(), None).unwrap();
+ let (dof, profile) = capture(|| super::dof_now(&sk));
+ assert_eq!(dof, 1);
+ assert_eq!(profile.counters.redundancy_checks, 0);
+
+ let mut doc = solidcraft_doc::Document::default();
+ let before = sk.clone();
+ let (rejected, profile) = capture(|| super::try_add(&mut sk, &mut doc, k, dof, false));
+ assert_eq!(rejected, None, "a duplicate must not be accepted as a DOF reduction");
+ assert_eq!(sk, before);
+ assert_eq!(profile.counters.redundancy_checks, 0);
+
+ let (accepted, profile) = capture(|| super::try_add(&mut sk, &mut doc, ConstraintKind::DistanceX { p: 0, q, value: 6.0 }, dof, false));
+ assert_eq!(accepted, Some(0));
+ assert_eq!(profile.counters.redundancy_checks, 0);
+ let full = solidcraft_sketch::solve(&mut sk);
+ assert!(full.ok());
+ assert_eq!(full.dof, 0);
+ assert!(full.redundant.contains(&redundant), "the final full report must retain diagnostics");
+}
+
#[test]
fn drawing_infers_tangent_and_perpendicular() {
let mut s = new_sketch();
diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs
index 0a080a7f25..dc54235933 100644
--- a/crates/engine/src/cmd/sketch_create.rs
+++ b/crates/engine/src/cmd/sketch_create.rs
@@ -367,7 +367,9 @@ fn edit_text(s: &mut Session, p: &Value) -> Result<Value> {
fn edit_text_live(s: &mut Session, p: &Value) -> Result<(Value, Option<crate::LiveEdit>)> {
let cmd = "sketch.edit_text";
let id = s.active_sketch.ok_or_else(|| bad(cmd, "no sketch is being edited"))?;
- let (out, report) = super::sketch::edit_solved(s, id, false, |sk, doc| Ok((apply_text_edits(sk, doc, p)?, super::sketch::Left::Unsolved)))?;
+ let (out, report) = super::sketch::edit_solved(s, id, false, solidcraft_sketch::Analysis::Full, |sk, doc| {
+ Ok((apply_text_edits(sk, doc, p)?, super::sketch::Left::Unsolved))
+ })?;
Ok((out, report.map(|report| crate::LiveEdit { sketch: id, report })))
}
diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs
index 2b57abd26f..1561ed31f8 100644
--- a/crates/engine/src/cmd/sketch_modify.rs
+++ b/crates/engine/src/cmd/sketch_modify.rs
@@ -527,7 +527,7 @@ fn extend(s: &mut Session, p: &Value) -> Result<Value> {
pin(sk, end, oi)?;
let before = sk.points.iter().map(|p| p.pos).collect::<Vec<_>>();
let hold = solidcraft_sketch::Hold { points: (0..sk.points.len()).filter(|i| *i != end).collect(), radii: (0..sk.curves.len()).collect() };
- if !solidcraft_sketch::solve_with(sk, &hold, None, solidcraft_sketch::Analysis::Full, None).ok()
+ if !solidcraft_sketch::solve_with(sk, &hold, None, solidcraft_sketch::Analysis::StatusOnly, None).ok()
|| sk.point(end).is_none_or(|point| point.dist(q) > TOL)
|| sk.points.iter().enumerate().any(|(i, point)| i != end && point.pos.dist(before[i]) > TOL)
{
diff --git a/crates/engine/tests/sketch_analysis.rs b/crates/engine/tests/sketch_analysis.rs
new file mode 100644
index 0000000000..337062c64c
--- /dev/null
+++ b/crates/engine/tests/sketch_analysis.rs
@@ -0,0 +1,174 @@
+//! Command-level diagnostic work, including the report ultimately published to the model.
+
+use std::sync::Arc;
+
+use serde_json::json;
+use solidcraft_engine::Session;
+use solidcraft_geom::Vec2;
+use solidcraft_sketch::{Analysis, ConstraintKind, Sketch, profiling::capture};
+
+fn session(horizontal: bool) -> (Session, u64, String) {
+ let mut s = Session::default();
+ s.execute("sketch.create", &json!({"plane": "XY"})).unwrap();
+ let id = s.active_sketch.unwrap();
+ let mut sk = Sketch::new();
+ let q = sk.add_point(Vec2::new(10.0, 0.0), None).unwrap();
+ let l = sk.add_line_pts(0, q, None).unwrap();
+ let k = ConstraintKind::Distance { p: 0, q, value: 10.0 };
+ sk.add_constraint(k.clone(), None).unwrap();
+ let redundant = sk.add_constraint(k, None).unwrap();
+ if horizontal {
+ sk.add_constraint(ConstraintKind::Horizontal { l }, None).unwrap();
+ }
+ *Arc::make_mut(&mut s.doc).sketch_mut(id).unwrap() = sk;
+ (s, id, redundant)
+}
+
+#[test]
+fn auto_constrain_computes_redundancy_once_and_publishes_full_diagnostics() {
+ let (mut s, id, redundant) = session(true);
+ let before = s.doc.sketch(id).unwrap().clone();
+ let (response, profile) = capture(|| s.execute("sketch.auto_constrain", &json!({"dimensions": false})));
+ let response = response.unwrap();
+ assert_eq!(response["added"], json!([]));
+ assert_eq!(response["sketch"], json!({"solved": true, "dof": 0}));
+ assert_eq!(*s.doc.sketch(id).unwrap(), before);
+ let state = s.model.state();
+ let shown = state.sketch(id).unwrap();
+ assert!(shown.report.ok());
+ assert_eq!(shown.report.dof, 0);
+ assert!(shown.report.redundant.contains(&redundant));
+ assert!(shown.report.point_determined.iter().all(|d| *d));
+ assert_eq!(profile.counters.redundancy_checks, 1, "only the published model report needs redundant IDs");
+ assert_eq!(profile.counters.solve_calls, 3, "reuse the preparation solve's DOF");
+}
+
+#[test]
+fn auto_constrain_reuses_real_freedom_and_keeps_accepted_trial_diagnostics() {
+ let (mut s, id, redundant) = session(false);
+ let (response, profile) = capture(|| s.execute("sketch.auto_constrain", &json!({"dimensions": false})));
+ let response = response.unwrap();
+ assert_eq!(response["added"].as_array().unwrap().len(), 1, "one angular degree of freedom must be removed");
+ assert_eq!(response["dof"], 0);
+ assert_eq!(response["sketch"], json!({"solved": true, "dof": 0}));
+ let state = s.model.state();
+ let shown = state.sketch(id).unwrap();
+ assert!(shown.report.redundant.contains(&redundant));
+ assert!(shown.report.ok());
+ assert_eq!(profile.counters.redundancy_checks, 1);
+}
+
+#[test]
+fn a_live_drag_keeps_full_diagnostics_when_it_publishes_without_evaluation() {
+ for horizontal in [false, true] {
+ let (mut s, id, redundant) = session(horizontal);
+ // The fixture edits the document directly. Establish a valid full report before
+ // testing its reuse; a no-op solve is not required to rebuild an unchanged model.
+ s.model.evaluate(&s.doc);
+ s.execute("sketch.solve", &json!({})).unwrap();
+ assert!(
+ s.model.state().sketch(id).unwrap().report.redundant.contains(&redundant),
+ "the pre-drag model must contain the fixture's full diagnostics"
+ );
+ let endpoint = s.doc.sketch(id).unwrap().points[1].id.clone();
+ s.execute("sketch.drag", &json!({"entity": endpoint, "from": [10, 0], "to": [12, 8], "live": true})).unwrap();
+ let state = s.model.state();
+ let shown = state.sketch(id).unwrap();
+ assert!(shown.report.redundant.contains(&redundant));
+ assert_eq!(shown.report.dof, usize::from(!horizontal));
+ if !horizontal {
+ assert!(s.doc.sketch(id).unwrap().points[1].pos.dist(Vec2::new(10.0, 0.0)) > 1.0, "exercise publication of changed geometry");
+ }
+ }
+}
+
+#[test]
+fn a_live_text_edit_keeps_full_diagnostics_when_it_publishes_without_evaluation() {
+ let (mut s, id, redundant) = session(false);
+ let text = s.execute("sketch.text", &json!({"text": "T", "at": [30, 20], "height": 5})).unwrap();
+ assert!(s.model.state().sketch(id).unwrap().report.redundant.contains(&redundant));
+ s.execute("sketch.edit_text", &json!({"link": text["link"], "height": 8, "live": true})).unwrap();
+ let state = s.model.state();
+ let shown = state.sketch(id).unwrap();
+ assert!(shown.report.ok());
+ assert!(shown.report.redundant.contains(&redundant), "live publication must retain redundant IDs for unrelated geometry");
+}
+
+#[test]
+fn a_live_text_batch_keeps_full_diagnostics_when_it_publishes_without_evaluation() {
+ let (mut s, id, redundant) = session(false);
+ let a = s.execute("sketch.text", &json!({"text": "T", "at": [30, 20], "height": 5})).unwrap();
+ let b = s.execute("sketch.text", &json!({"text": "I", "at": [50, 20], "height": 5})).unwrap();
+ let out =
+ s.execute("sketch.edit_text", &json!({"edits": [{"link": a["link"], "height": 8}, {"link": b["link"], "height": 9}], "live": true})).unwrap();
+ assert_eq!(out["edits"][0]["link"], a["link"]);
+ assert_eq!(out["edits"][1]["link"], b["link"]);
+ let state = s.model.state();
+ let shown = state.sketch(id).unwrap();
+ let expected = solidcraft_sketch::solve(&mut s.doc.sketch(id).unwrap().clone());
+ assert!(shown.report.ok());
+ assert!(shown.report.redundant.contains(&redundant));
+ assert_eq!(serde_json::to_value(&shown.report).unwrap(), serde_json::to_value(expected).unwrap());
+}
+
+fn compare_document_levels(doc: &solidcraft_doc::Document, id: u64, expected_ok: bool) {
+ let input = doc.sketch(id).unwrap();
+ let stored = input.driving_values();
+ let values = doc.param_values().0;
+ let mut full_geometry = input.clone();
+ let (full, profile) = capture(|| doc.solve_sketch(&values, &mut full_geometry, &stored, Some(input)).unwrap());
+ assert_eq!(full.ok(), expected_ok);
+ assert!(profile.counters.redundancy_checks > 0, "the default document API retains full diagnostics");
+ if expected_ok {
+ let (_, last_only) = capture(|| solidcraft_sketch::solve(&mut full_geometry.clone()));
+ assert_eq!(profile.counters.redundancy_checks, last_only.counters.redundancy_checks, "only the last offset solve needs redundant IDs");
+ }
+ for analysis in [Analysis::Freedom, Analysis::StatusOnly] {
+ let mut geometry = input.clone();
+ let (report, profile) = capture(|| doc.solve_sketch_with_analysis(&values, &mut geometry, &stored, Some(input), analysis).unwrap());
+ assert_eq!(geometry, full_geometry, "parameter application, offset refresh and rollback must match");
+ assert_eq!(profile.counters.redundancy_checks, 0, "offset retries must retain the requested level");
+ let mut expected = full.clone();
+ expected.redundant.clear();
+ if analysis == Analysis::StatusOnly {
+ expected.dof = 0;
+ expected.point_determined.clear();
+ expected.curve_determined.clear();
+ }
+ assert_eq!(serde_json::to_value(report).unwrap(), serde_json::to_value(expected).unwrap());
+ }
+}
+
+#[test]
+fn document_analysis_levels_survive_parameter_application_and_offset_retries() {
+ for freeform in [false, true] {
+ let (mut s, id, _) = session(false);
+ let curve = if freeform {
+ s.execute("sketch.ellipse", &json!({"center": [30, 30], "major": [40, 30], "minor_radius": 5})).unwrap()["curves"][0]
+ .as_str()
+ .unwrap()
+ .to_owned()
+ } else {
+ s.doc.sketch(id).unwrap().curves[0].id.clone()
+ };
+ s.execute("sketch.offset", &json!({"curves": [curve], "distance": -1, "chain": false})).unwrap();
+ let sk = s.doc.sketch(id).unwrap();
+ assert!(if freeform { !sk.freeform_offsets.is_empty() } else { !sk.offsets.is_empty() });
+ compare_document_levels(&s.doc, id, true);
+
+ // Both original distances must follow the edited parameter before analyzing freedom.
+ let doc = Arc::make_mut(&mut s.doc);
+ let param = doc.new_model_param("20 mm", "mm");
+ for c in &mut doc.sketch_mut(id).unwrap().constraints {
+ if matches!(c.kind, ConstraintKind::Distance { .. }) {
+ c.param = Some(param.clone());
+ }
+ }
+ compare_document_levels(doc, id, true);
+ // One conflicting dimension makes the first solve fail, exercising the offset retry.
+ let conflict = doc.new_model_param("11 mm", "mm");
+ doc.sketch_mut(id).unwrap().constraints.iter_mut().find(|c| matches!(c.kind, ConstraintKind::Distance { .. })).unwrap().param =
+ Some(conflict);
+ compare_document_levels(doc, id, false);
+ }
+}
diff --git a/crates/sketch/Cargo.toml b/crates/sketch/Cargo.toml
index 76fa295c24..eba000b5a4 100644
--- a/crates/sketch/Cargo.toml
+++ b/crates/sketch/Cargo.toml
@@ -8,6 +8,14 @@ license.workspace = true
[lints]
workspace = true
+[features]
+# Opt-in developer instrumentation; normal builds contain no collection or clocks.
+solver-profiling = []
+
+[[example]]
+name = "solve_profile"
+required-features = ["solver-profiling"]
+
[dependencies]
solidcraft-geom = { workspace = true }
serde = { workspace = true }
diff --git a/crates/sketch/examples/solve_profile.rs b/crates/sketch/examples/solve_profile.rs
new file mode 100644
index 0000000000..f41e12af60
--- /dev/null
+++ b/crates/sketch/examples/solve_profile.rs
@@ -0,0 +1,306 @@
+//! Reproducible numerical traces and paired wall-time samples. Use `--help` for cases and bounds.
+
+use std::{error::Error, io::Write, path::PathBuf, time::Instant};
+
+use serde::Serialize;
+use solidcraft_geom::Vec2;
+use solidcraft_sketch::{
+ Analysis, ConstraintKind, DrivingValues, Hold, Sketch, SolveReport,
+ profiling::{Counters, SolveProfile, Timings, capture},
+ solve_after_value_edit, solve_with,
+};
+
+type Result<T> = std::result::Result<T, Box<dyn Error>>;
+const CASES: [&str; 6] = ["distance-zero", "distance-offset", "x-zero", "linkage", "linkage-edit", "grid"];
+
+struct Options {
+ case: String,
+ repeats: usize,
+ warmup: usize,
+ size: usize,
+ seed: u64,
+ scale: f64,
+ offset: f64,
+ analysis: Analysis,
+ cpu_loops: Option<usize>,
+ out: Option<PathBuf>,
+}
+
+impl Options {
+ fn read() -> Result<Option<Self>> {
+ let mut opt = Self {
+ case: "all".into(),
+ repeats: 5,
+ warmup: 1,
+ size: 10,
+ seed: 99,
+ scale: 1.0,
+ offset: 0.0,
+ analysis: Analysis::Full,
+ cpu_loops: None,
+ out: None,
+ };
+ let mut args = std::env::args().skip(1);
+ while let Some(key) = args.next() {
+ if key == "--help" {
+ println!(
+ "solve_profile [--case all|{}] [--repeats 1..100] [--warmup 0..10] [--size 2..30] [--seed U64] [--scale 1e-6..1e6] [--offset MM] [--analysis full|freedom|status] [--cpu-loops 1..1000000] [--out FILE]",
+ CASES.join("|")
+ );
+ return Ok(None);
+ }
+ let value = args.next().ok_or_else(|| format!("missing value for {key}"))?;
+ match key.as_str() {
+ "--case" => opt.case = value,
+ "--repeats" => opt.repeats = value.parse()?,
+ "--warmup" => opt.warmup = value.parse()?,
+ "--size" => opt.size = value.parse()?,
+ "--seed" => opt.seed = value.parse()?,
+ "--cpu-loops" => opt.cpu_loops = Some(value.parse()?),
+ "--scale" => opt.scale = value.parse()?,
+ "--offset" => opt.offset = value.parse()?,
+ "--analysis" => match value.as_str() {
+ "full" => opt.analysis = Analysis::Full,
+ "freedom" => opt.analysis = Analysis::Freedom,
+ "status" => opt.analysis = Analysis::StatusOnly,
+ _ => return Err("analysis must be full, freedom or status".into()),
+ },
+ "--out" => opt.out = Some(value.into()),
+ _ => return Err(format!("unknown option {key}").into()),
+ }
+ }
+ if !(1..=100).contains(&opt.repeats) || opt.warmup > 10 || !(2..=30).contains(&opt.size) {
+ return Err("repeats, warmup or size outside supported range (see --help)".into());
+ }
+ if opt.cpu_loops.is_some_and(|n| !(1..=1_000_000).contains(&n)) {
+ return Err("cpu-loops must be in 1..1000000".into());
+ }
+ if !opt.scale.is_finite() || !(1e-6..=1e6).contains(&opt.scale) || !opt.offset.is_finite() || opt.offset.abs() > 1e8 {
+ return Err("scale must be finite in 1e-6..1e6 and offset finite within +/-1e8 mm".into());
+ }
+ if opt.case != "all" && !CASES.contains(&opt.case.as_str()) {
+ return Err(format!("unknown case {}", opt.case).into());
+ }
+ if opt.analysis != Analysis::Full && (opt.case == "all" || opt.case == "linkage-edit") {
+ return Err("linkage-edit uses full analysis; select another --case for reduced analysis".into());
+ }
+ Ok(Some(opt))
+ }
+
+ fn at(&self, x: f64, y: f64) -> Vec2 {
+ Vec2::new(self.offset + x * self.scale, self.offset + y * self.scale)
+ }
+}
+
+struct Lcg(u64);
+impl Lcg {
+ fn next(&mut self) -> f64 {
+ self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ (self.0 >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0
+ }
+}
+
+struct Case {
+ sketch: Sketch,
+ old: Option<DrivingValues>,
+}
+
+fn make_case(name: &str, opt: &Options) -> Result<Case> {
+ let mut sk = Sketch::new();
+ let mut old = None;
+ let mut rnd = Lcg(opt.seed);
+ if name == "grid" {
+ let mut points = Vec::new();
+ for y in 0..opt.size {
+ for x in 0..opt.size {
+ let p = sk.add_point(opt.at(x as f64 * 10.0 + rnd.next(), y as f64 * 10.0 + rnd.next()), None)?;
+ points.push(p);
+ if x == 0 && y == 0 {
+ sk.add_constraint(ConstraintKind::Fix { p }, None)?;
+ }
+ for (other, horizontal) in [((x > 0).then(|| points.len() - 2), true), ((y > 0).then(|| points.len() - 1 - opt.size), false)] {
+ if let Some(q) = other.and_then(|i| points.get(i)).copied() {
+ let l = sk.add_line_pts(q, p, None)?;
+ sk.add_constraint(if horizontal { ConstraintKind::Horizontal { l } } else { ConstraintKind::Vertical { l } }, None)?;
+ sk.add_constraint(ConstraintKind::Distance { p, q, value: 10.0 * opt.scale }, None)?;
+ }
+ }
+ }
+ }
+ } else if name.starts_with("linkage") {
+ let truth = [(0.0, 0.0), (40.0, 0.0), (18.0, 30.0), (8.0, 55.0), (52.0, 48.0), (30.0, 80.0)];
+ let mut ids = Vec::new();
+ for (i, (x, y)) in truth.iter().copied().enumerate() {
+ let jitter = if i == 0 { (0.0, 0.0) } else { (rnd.next() * 2.0, rnd.next() * 2.0) };
+ ids.push(sk.add_point(opt.at(x + jitter.0, y + jitter.1), None)?);
+ }
+ let p = *ids.first().ok_or("missing base point")?;
+ let q = *ids.get(1).ok_or("missing base endpoint")?;
+ sk.add_constraint(ConstraintKind::Fix { p }, None)?;
+ let l = sk.add_line_pts(p, q, None)?;
+ sk.add_constraint(ConstraintKind::Horizontal { l }, None)?;
+ for (a, b) in [(0, 1), (1, 2), (2, 0), (3, 4), (4, 5), (5, 3), (0, 3), (1, 4), (2, 5)] {
+ let (ax, ay) = *truth.get(a).ok_or("missing endpoint")?;
+ let (bx, by) = *truth.get(b).ok_or("missing endpoint")?;
+ let p = *ids.get(a).ok_or("missing point")?;
+ let q = *ids.get(b).ok_or("missing point")?;
+ sk.add_constraint(ConstraintKind::Distance { p, q, value: (ax - bx).hypot(ay - by) * opt.scale }, None)?;
+ }
+ if name == "linkage-edit" {
+ let report = solve_with(&mut sk, &Hold::default(), None, Analysis::Full, None);
+ if !report.ok() {
+ return Err("could not prepare the solved linkage for the dimension edit".into());
+ }
+ old = Some(sk.driving_values());
+ for c in &mut sk.constraints {
+ if let Some(value) = c.kind.value() {
+ c.kind.set_value(value * (1.0 + rnd.next() * 0.15));
+ }
+ }
+ }
+ } else {
+ let p = sk.add_point(opt.at(0.0, 0.0), None)?;
+ let q = sk.add_point(opt.at(if name == "distance-offset" { 1e-5 } else { 0.0 }, if name == "x-zero" { 5.0 } else { 0.0 }), None)?;
+ sk.add_constraint(ConstraintKind::Fix { p }, None)?;
+ let k = if name == "x-zero" {
+ ConstraintKind::DistanceX { p, q, value: 10.0 * opt.scale }
+ } else {
+ ConstraintKind::Distance { p, q, value: 10.0 * opt.scale }
+ };
+ sk.add_constraint(k, None)?;
+ }
+ Ok(Case { sketch: sk, old })
+}
+
+fn solve(case: &Case, sk: &mut Sketch, opt: &Options) -> SolveReport {
+ match &case.old {
+ Some(old) => solve_after_value_edit(sk, old),
+ None => solve_with(sk, &Hold::default(), None, opt.analysis, None),
+ }
+}
+
+#[derive(Serialize)]
+struct Sample {
+ elapsed_ns: u64,
+ report: SolveReport,
+ counters: Counters,
+ timings_ns: Timings,
+}
+
+#[derive(Serialize)]
+struct CaseResult {
+ case: String,
+ points: usize,
+ constraints: usize,
+ profiled_median_ns: u64,
+ profiled_p95_ns: u64,
+ uncaptured_median_ns: u64,
+ uncaptured_p95_ns: u64,
+ uncaptured_samples_ns: Vec<u64>,
+ samples: Vec<Sample>,
+ last_run_trace: SolveProfile,
+}
+
+fn elapsed(t: Instant) -> u64 {
+ t.elapsed().as_nanos().min(u64::MAX as u128) as u64
+}
+
+fn percentile(samples: &[u64], percent: usize) -> u64 {
+ let mut sorted = samples.to_vec();
+ sorted.sort_unstable();
+ sorted.get((sorted.len() * percent).div_ceil(100).saturating_sub(1)).copied().unwrap_or(0)
+}
+
+fn measure(name: &str, opt: &Options) -> Result<CaseResult> {
+ let case = make_case(name, opt)?;
+ for _ in 0..opt.warmup {
+ solve(&case, &mut case.sketch.clone(), opt);
+ }
+ let mut samples = Vec::new();
+ let mut baseline = Vec::new();
+ let mut last = SolveProfile::default();
+ for i in 0..opt.repeats {
+ // Clones and comparison are outside both timers; alternate ordering to reduce drift.
+ let mut measured = case.sketch.clone();
+ let mut plain = case.sketch.clone();
+ let unprofiled = |sk: &mut Sketch| {
+ let t = Instant::now();
+ let r = solve(&case, sk, opt);
+ (r, elapsed(t))
+ };
+ let profiled = |sk: &mut Sketch| {
+ let t = Instant::now();
+ let (r, p) = capture(|| solve(&case, sk, opt));
+ (r, p, elapsed(t))
+ };
+ let ((a, plain_ns), (b, profile, ns)) = if i % 2 == 0 {
+ let a = unprofiled(&mut plain);
+ (a, profiled(&mut measured))
+ } else {
+ let b = profiled(&mut measured);
+ (unprofiled(&mut plain), b)
+ };
+ if measured != plain || serde_json::to_value(&a)? != serde_json::to_value(&b)? {
+ return Err(format!("instrumentation changed the result for {name}").into());
+ }
+ baseline.push(plain_ns);
+ samples.push(Sample { elapsed_ns: ns, report: b, counters: profile.counters.clone(), timings_ns: profile.timings_ns.clone() });
+ last = profile;
+ }
+ let times: Vec<_> = samples.iter().map(|s| s.elapsed_ns).collect();
+ Ok(CaseResult {
+ case: name.into(),
+ points: case.sketch.points.len(),
+ constraints: case.sketch.constraints.len(),
+ profiled_median_ns: percentile(&times, 50),
+ profiled_p95_ns: percentile(&times, 95),
+ uncaptured_median_ns: percentile(&baseline, 50),
+ uncaptured_p95_ns: percentile(&baseline, 95),
+ uncaptured_samples_ns: baseline,
+ samples,
+ last_run_trace: last,
+ })
+}
+
+fn main() -> Result<()> {
+ let Some(opt) = Options::read()? else { return Ok(()) };
+ let names = if opt.case == "all" { CASES.to_vec() } else { vec![opt.case.as_str()] };
+ let cases: Vec<serde_json::Value> = names
+ .iter()
+ .map(|name| {
+ if let Some(loops) = opt.cpu_loops {
+ // Sampling profilers see a sustained workload without trace allocation, rho
+ // calculation or JSON serialization in the hot loop. Each solve starts fresh.
+ let case = make_case(name, &opt)?;
+ for _ in 0..opt.warmup {
+ solve(&case, &mut case.sketch.clone(), &opt);
+ }
+ let (mut solved, mut failed) = (0usize, 0usize);
+ let t = Instant::now();
+ for _ in 0..loops {
+ let report = std::hint::black_box(solve(&case, &mut case.sketch.clone(), &opt));
+ if report.ok() { solved += 1 } else { failed += 1 }
+ }
+ Ok(serde_json::json!({ "case": name, "loops": loops, "solved": solved, "failed": failed, "elapsed_ns": elapsed(t) }))
+ } else {
+ Ok(serde_json::to_value(measure(name, &opt)?)?)
+ }
+ })
+ .collect::<Result<_>>()?;
+ let output = serde_json::json!({
+ "schema": "solidcraft/sketch-profile/1", "package_version": env!("CARGO_PKG_VERSION"),
+ "os": std::env::consts::OS, "arch": std::env::consts::ARCH, "debug_assertions": cfg!(debug_assertions),
+ "seed": opt.seed, "scale": opt.scale, "offset_mm": opt.offset, "size": opt.size,
+ "repeats": opt.repeats, "warmup": opt.warmup, "analysis": match opt.analysis { Analysis::Full => "full", Analysis::Freedom => "freedom", Analysis::StatusOnly => "status" },
+ "mode": if opt.cpu_loops.is_some() { "cpu" } else { "trace" },
+ "cases": cases,
+ });
+ let mut writer: Box<dyn Write> = match opt.out {
+ Some(path) => Box::new(std::io::BufWriter::new(std::fs::File::create(path)?)),
+ None => Box::new(std::io::stdout().lock()),
+ };
+ serde_json::to_writer_pretty(&mut writer, &output)?;
+ writeln!(writer)?;
+ writer.flush()?;
+ Ok(())
+}
diff --git a/crates/sketch/src/lib.rs b/crates/sketch/src/lib.rs
index 80c32b996d..aada4300c7 100644
--- a/crates/sketch/src/lib.rs
+++ b/crates/sketch/src/lib.rs
@@ -32,6 +32,8 @@ mod offset_topology;
mod pattern;
mod periodic;
mod profiles;
+#[cfg(feature = "solver-profiling")]
+pub mod profiling;
mod shape;
mod solver;
mod text;
@@ -62,6 +64,7 @@ pub use profiles::{
without_text_counters,
};
pub use shape::{Shape, intersections};
+pub use solver::solve_after_edit_with_analysis;
pub use solver::{
Analysis, CONSISTENT, DrivingValues, Hold, SolveReport, SolveStatus, constraint_residual, determined_by, measure_dimension, move_line_towards,
move_point_towards, solve, solve_after_edit, solve_after_value_edit, solve_holding, solve_with,
diff --git a/crates/sketch/src/profiling.rs b/crates/sketch/src/profiling.rs
new file mode 100644
index 0000000000..b8987b8abe
--- /dev/null
+++ b/crates/sketch/src/profiling.rs
@@ -0,0 +1,406 @@
+//! Opt-in, per-thread solver measurements (`solver-profiling` feature).
+//!
+//! Wrap a public solve in [`capture`]. Collection never changes solver decisions. Timings are
+//! inclusive (LM includes Jacobian and linear solve time), not additive. On wasm the counters
+//! and trace work but clocks are disabled: `std::time::Instant` is unavailable there.
+
+use std::cell::Cell;
+
+use serde::Serialize;
+
+/// Bounds retained records, independently of how many solves the closure performs.
+pub const MAX_RUNS: usize = 1024;
+pub const MAX_TRIALS: usize = 10_000;
+
+/// Inclusive phase wall times in nanoseconds. Empty phases stay zero.
+#[derive(Clone, Debug, Default, Serialize)]
+pub struct Timings {
+ pub solve: u64,
+ pub seed: u64,
+ pub lm: u64,
+ pub residual_system: u64,
+ pub jacobian: u64,
+ pub normal_equations: u64,
+ pub linear_solve: u64,
+ pub analysis: u64,
+ /// Dependency classification, including its Jacobian and optional explanation.
+ pub redundancy: u64,
+ /// Jacobian construction within dependency classification (also included in `jacobian`).
+ pub redundancy_jacobian: u64,
+ /// Ordered, twice-reorthogonalized row classification, including row storage.
+ pub redundancy_classification: u64,
+ /// Optional `determined_by` explanation; ordinary solve reports do not request it.
+ pub redundancy_support: u64,
+}
+
+/// Work counts include all actual calls in the captured closure, including retries and
+/// continuation. A residual block evaluation is one constraint/implicit-curve block, not one row.
+#[derive(Clone, Debug, Default, Serialize)]
+pub struct Counters {
+ pub solve_calls: u64,
+ pub components: u64,
+ pub oversized_components: u64,
+ pub constructed_variables: u64,
+ pub residual_system_evaluations: u64,
+ pub residual_block_evaluations: u64,
+ pub jacobian_evaluations: u64,
+ pub lm_runs: u64,
+ pub outer_iterations: u64,
+ pub linear_solves: u64,
+ pub linear_failures: u64,
+ pub accepted_trials: u64,
+ pub rejected_trials: u64,
+ pub plain_start_retries: u64,
+ pub continuation_runs: u64,
+ pub redundancy_checks: u64,
+}
+
+/// Why this invocation of LM returned. This is distinct from the final solve's acceptance
+/// tolerance, and does not certify that inconsistent constraints have no solution.
+#[derive(Clone, Copy, Debug, Serialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum StopReason {
+ ResidualTolerance,
+ NoImprovement,
+ IterationLimit,
+ /// The shared frame-work budget was exhausted after evaluating the initial residual.
+ WorkBudget,
+}
+
+#[derive(Clone, Copy, Debug, Serialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum Decision {
+ Accepted,
+ Rejected,
+ LinearFailure,
+}
+
+/// One LM call, identified even when the caller retries the same component.
+#[derive(Debug, Serialize)]
+pub struct LmRun {
+ pub id: u64,
+ pub variables: usize,
+ pub residual_rows: usize,
+ pub iteration_limit: usize,
+ pub initial_cost: Option<f64>,
+ pub final_max_residual: Option<f64>,
+ pub stop_reason: Option<StopReason>,
+}
+
+/// One damping trial. `None` means unavailable or non-finite. Cost is sum(r²), without 1/2.
+/// Predicted reduction uses the undamped residual model; rho is observational only.
+#[derive(Debug, Serialize)]
+pub struct Trial {
+ pub run: u64,
+ pub iteration: usize,
+ pub attempt: usize,
+ pub lambda: f64,
+ pub cost_before: Option<f64>,
+ pub cost_after: Option<f64>,
+ pub gradient_inf: Option<f64>,
+ pub step_norm: Option<f64>,
+ pub predicted_reduction: Option<f64>,
+ pub actual_reduction: Option<f64>,
+ pub rho: Option<f64>,
+ pub decision: Decision,
+}
+
+#[derive(Debug, Default, Serialize)]
+pub struct SolveProfile {
+ pub timings_available: bool,
+ pub timings_ns: Timings,
+ pub counters: Counters,
+ pub runs: Vec<LmRun>,
+ pub trials: Vec<Trial>,
+ pub dropped_runs: u64,
+ pub dropped_trials: u64,
+}
+
+thread_local! {
+ static ACTIVE: Cell<Option<SolveProfile>> = const { Cell::new(None) };
+}
+
+struct CaptureGuard(Option<SolveProfile>);
+
+impl Drop for CaptureGuard {
+ fn drop(&mut self) {
+ ACTIVE.set(self.0.take());
+ }
+}
+
+/// Measure only the closure on the current thread. Nested captures are isolated and the outer
+/// collector resumes afterwards. Unwinding restores the previous collector as well.
+pub fn capture<T>(f: impl FnOnce() -> T) -> (T, SolveProfile) {
+ let previous = ACTIVE.replace(Some(SolveProfile { timings_available: !cfg!(target_arch = "wasm32"), ..SolveProfile::default() }));
+ let guard = CaptureGuard(previous);
+ let result = f();
+ let profile = ACTIVE.take().unwrap_or_default();
+ drop(guard);
+ (result, profile)
+}
+
+fn update(f: impl FnOnce(&mut SolveProfile)) {
+ if let Some(mut profile) = ACTIVE.take() {
+ f(&mut profile);
+ ACTIVE.set(Some(profile));
+ }
+}
+
+pub(crate) fn count(f: impl FnOnce(&mut Counters)) {
+ update(|p| f(&mut p.counters));
+}
+
+pub(crate) fn finite(x: f64) -> Option<f64> {
+ x.is_finite().then_some(x)
+}
+
+pub(crate) fn record_trial(
+ run: u64,
+ iteration: usize,
+ attempt: usize,
+ lambda: f64,
+ before: f64,
+ after: Option<f64>,
+ gradient: &[f64],
+ j: &crate::linalg::Mat,
+ step: Option<&[f64]>,
+ decision: Decision,
+) {
+ // Keep the extra matrix-vector product out of uncaptured timing baselines.
+ let active = ACTIVE.with(|cell| {
+ let p = cell.take();
+ let active = p.is_some();
+ cell.set(p);
+ active
+ });
+ if !active {
+ return;
+ }
+ let predicted = step.map(|step| {
+ let gp: f64 = gradient.iter().zip(step).map(|(g, s)| g * s).sum();
+ let jp2: f64 = (0..j.rows).map(|row| step.iter().enumerate().map(|(c, s)| j.get(row, c) * s).sum::<f64>().powi(2)).sum();
+ -2.0 * gp - jp2
+ });
+ let actual = after.map(|after| before - after);
+ trial(Trial {
+ run,
+ iteration,
+ attempt,
+ lambda,
+ cost_before: finite(before),
+ cost_after: after.and_then(finite),
+ gradient_inf: finite(gradient.iter().fold(0.0_f64, |m, g| if g.is_finite() { m.max(g.abs()) } else { f64::INFINITY })),
+ step_norm: step.and_then(|s| finite(s.iter().fold(0.0_f64, |n, x| n.hypot(*x)))),
+ predicted_reduction: predicted.and_then(finite),
+ actual_reduction: actual.and_then(finite),
+ rho: predicted.filter(|p| *p > 0.0).zip(actual).and_then(|(p, a)| finite(a / p)),
+ decision,
+ });
+}
+
+pub(crate) enum Phase {
+ Solve,
+ Seed,
+ Lm,
+ ResidualSystem,
+ Jacobian,
+ NormalEquations,
+ LinearSolve,
+ Analysis,
+ Redundancy,
+ RedundancyJacobian,
+ RedundancyClassification,
+ RedundancySupport,
+}
+
+pub(crate) struct Timer {
+ phase: Phase,
+ #[cfg(not(target_arch = "wasm32"))]
+ start: Option<std::time::Instant>,
+}
+
+pub(crate) fn timer(phase: Phase) -> Timer {
+ Timer {
+ phase,
+ #[cfg(not(target_arch = "wasm32"))]
+ start: ACTIVE.with(|cell| {
+ let profile = cell.take();
+ let active = profile.is_some();
+ cell.set(profile);
+ active.then(std::time::Instant::now)
+ }),
+ }
+}
+
+impl Drop for Timer {
+ fn drop(&mut self) {
+ #[cfg(not(target_arch = "wasm32"))]
+ let ns = self.start.map(|s| s.elapsed().as_nanos().min(u64::MAX as u128) as u64).unwrap_or(0);
+ #[cfg(target_arch = "wasm32")]
+ let ns = 0;
+ update(|p| {
+ let slot = match self.phase {
+ Phase::Solve => &mut p.timings_ns.solve,
+ Phase::Seed => &mut p.timings_ns.seed,
+ Phase::Lm => &mut p.timings_ns.lm,
+ Phase::ResidualSystem => &mut p.timings_ns.residual_system,
+ Phase::Jacobian => &mut p.timings_ns.jacobian,
+ Phase::NormalEquations => &mut p.timings_ns.normal_equations,
+ Phase::LinearSolve => &mut p.timings_ns.linear_solve,
+ Phase::Analysis => &mut p.timings_ns.analysis,
+ Phase::Redundancy => &mut p.timings_ns.redundancy,
+ Phase::RedundancyJacobian => &mut p.timings_ns.redundancy_jacobian,
+ Phase::RedundancyClassification => &mut p.timings_ns.redundancy_classification,
+ Phase::RedundancySupport => &mut p.timings_ns.redundancy_support,
+ };
+ *slot = slot.saturating_add(ns);
+ });
+ }
+}
+
+pub(crate) fn start_run(variables: usize, residual_rows: usize, iteration_limit: usize, cost: f64) -> u64 {
+ let mut id = 0;
+ update(|p| {
+ id = p.counters.lm_runs;
+ p.counters.lm_runs = p.counters.lm_runs.saturating_add(1);
+ if p.runs.len() < MAX_RUNS {
+ p.runs.push(LmRun {
+ id,
+ variables,
+ residual_rows,
+ iteration_limit,
+ initial_cost: finite(cost),
+ final_max_residual: None,
+ stop_reason: None,
+ });
+ } else {
+ p.dropped_runs = p.dropped_runs.saturating_add(1);
+ }
+ });
+ id
+}
+
+pub(crate) fn finish_run(id: u64, reason: StopReason, residual: f64) {
+ update(|p| {
+ if let Some(run) = p.runs.iter_mut().find(|r| r.id == id) {
+ run.stop_reason = Some(reason);
+ run.final_max_residual = finite(residual);
+ }
+ });
+}
+
+pub(crate) fn trial(record: Trial) {
+ update(|p| {
+ let c = &mut p.counters;
+ c.linear_solves = c.linear_solves.saturating_add(1);
+ match record.decision {
+ Decision::Accepted => c.accepted_trials = c.accepted_trials.saturating_add(1),
+ Decision::Rejected => c.rejected_trials = c.rejected_trials.saturating_add(1),
+ Decision::LinearFailure => c.linear_failures = c.linear_failures.saturating_add(1),
+ }
+ if p.trials.len() < MAX_TRIALS {
+ p.trials.push(record);
+ } else {
+ p.dropped_trials = p.dropped_trials.saturating_add(1);
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{Analysis, ConstraintKind, Hold, Sketch, solve_with};
+ use solidcraft_geom::Vec2;
+
+ fn distance(x: f64) -> Sketch {
+ let mut sk = Sketch::new();
+ let q = sk.add_point(Vec2::new(x, 0.0), None).unwrap();
+ sk.add_constraint(ConstraintKind::Distance { p: 0, q, value: 10.0 }, None).unwrap();
+ sk
+ }
+
+ #[test]
+ fn measurements_preserve_geometry_and_explain_a_stalled_solve() {
+ for x in [0.0, 1e-5] {
+ let mut plain = distance(x);
+ let mut measured = plain.clone();
+ let run = |sk: &mut Sketch| solve_with(sk, &Hold::default(), None, Analysis::StatusOnly, None);
+ let a = run(&mut plain);
+ let (b, profile) = crate::construct::switch::without_differential(|| capture(|| run(&mut measured)));
+ assert_eq!(serde_json::to_value(a).unwrap(), serde_json::to_value(b).unwrap());
+ assert_eq!(plain, measured);
+ assert_eq!(profile.counters.solve_calls, 1);
+ assert_eq!(profile.counters.lm_runs, 1);
+ assert_eq!(
+ profile.counters.linear_solves,
+ profile.counters.accepted_trials + profile.counters.rejected_trials + profile.counters.linear_failures
+ );
+ assert!(profile.counters.residual_block_evaluations > profile.counters.residual_system_evaluations);
+ let first = profile.trials.first().unwrap();
+ if x == 0.0 {
+ assert_eq!(profile.runs[0].stop_reason, Some(StopReason::NoImprovement));
+ assert_eq!(first.gradient_inf, Some(0.0));
+ assert_eq!(first.step_norm, Some(0.0));
+ assert_eq!(profile.counters.accepted_trials, 0);
+ } else {
+ assert_eq!(profile.runs[0].stop_reason, Some(StopReason::ResidualTolerance));
+ assert!(profile.counters.accepted_trials > 0);
+ assert!((first.rho.unwrap() - 1.0).abs() < 1e-6, "the positive radial step is a linear residual");
+ }
+ serde_json::to_string(&profile).unwrap();
+ }
+ }
+
+ #[test]
+ fn freedom_and_status_queries_do_not_run_dependency_analysis() {
+ let mut sk = distance(10.0);
+ sk.add_constraint(ConstraintKind::Distance { p: 0, q: 1, value: 10.0 }, None).unwrap();
+ for analysis in [Analysis::Full, Analysis::Freedom, Analysis::StatusOnly] {
+ let (report, profile) =
+ crate::construct::switch::without_differential(|| capture(|| solve_with(&mut sk.clone(), &Hold::default(), None, analysis, None)));
+ assert!(report.ok());
+ if analysis == Analysis::Full {
+ assert_eq!(profile.counters.redundancy_checks, 1);
+ assert_eq!(report.redundant.len(), 1);
+ } else {
+ assert_eq!(profile.counters.redundancy_checks, 0);
+ assert_eq!(profile.timings_ns.redundancy, 0);
+ assert!(report.redundant.is_empty());
+ }
+ assert_eq!(report.dof, usize::from(analysis != Analysis::StatusOnly));
+ }
+ }
+
+ #[test]
+ fn nested_captures_and_unwinds_restore_the_outer_collector() {
+ let (_, outer) = capture(|| {
+ count(|c| c.solve_calls += 1);
+ let (_, inner) = capture(|| count(|c| c.solve_calls += 2));
+ assert_eq!(inner.counters.solve_calls, 2);
+ let unwind = std::panic::catch_unwind(|| capture(|| panic!("test unwind")));
+ assert!(unwind.is_err());
+ count(|c| c.solve_calls += 3);
+ });
+ assert_eq!(outer.counters.solve_calls, 4);
+ assert!(ACTIVE.take().is_none());
+ }
+
+ #[test]
+ fn run_storage_is_bounded_but_counts_are_not_truncated() {
+ let (_, p) = capture(|| {
+ for _ in 0..MAX_RUNS + 3 {
+ start_run(2, 1, 500, f64::INFINITY);
+ }
+ for _ in 0..MAX_TRIALS + 2 {
+ record_trial(0, 0, 0, 1.0, f64::INFINITY, None, &[], &crate::linalg::Mat::zeros(0, 0), None, Decision::LinearFailure);
+ }
+ });
+ assert_eq!(p.runs.len(), MAX_RUNS);
+ assert_eq!(p.dropped_runs, 3);
+ assert_eq!(p.counters.lm_runs, (MAX_RUNS + 3) as u64);
+ assert_eq!(p.runs[0].initial_cost, None);
+ assert_eq!(p.trials.len(), MAX_TRIALS);
+ assert_eq!(p.dropped_trials, 2);
+ assert_eq!(p.counters.linear_failures, (MAX_TRIALS + 2) as u64);
+ }
+}
diff --git a/crates/sketch/src/redundancy.rs b/crates/sketch/src/redundancy.rs
index 9af067718f..f070de0d3a 100644
--- a/crates/sketch/src/redundancy.rs
+++ b/crates/sketch/src/redundancy.rs
@@ -13,14 +13,20 @@
use super::{Block, Hold, Layout, State, block_residuals, build_blocks, columns, initial_x, layout, local_system, max_abs, points_on_curves};
use crate::linalg::{Mat, solve as lin_solve};
use crate::model::Sketch;
+#[cfg(feature = "solver-profiling")]
+use crate::profiling::{self, Phase};
use crate::union_find::{find, union};
+#[cfg(test)]
+#[path = "redundancy_tests.rs"]
+mod tests;
+
/// A row is dependent on the rows before it when what is left of it, once their directions are
/// taken out, is below this share of its length (the rank analysis' pivot tolerance is 1e-7 on
/// rows of a comparable scale).
const DEPENDENT: f64 = 1e-6;
/// Variables in one component past which its constraints are not checked for redundancy: the
-/// check is dense, rows × rank × variables.
+/// worst case is still dense, rows × rank × variables.
pub(super) const MAX_REDUNDANCY_VARS: usize = 400;
/// A constraint's residual (mm, or radians for angles) below which it holds.
pub const CONSISTENT: f64 = 1e-6;
@@ -37,6 +43,43 @@ fn dot(a: &[f64], b: &[f64]) -> f64 {
a.iter().zip(b).map(|(x, y)| x * y).sum()
}
+/// Keep exact nonzeros in column order; never drop a small coefficient. Dense directions
+/// retain the contiguous loop when indexing a sparse representation would cost more.
+enum Direction {
+ Dense(Vec<f64>),
+ Sparse(Vec<(usize, f64)>),
+}
+
+impl Direction {
+ fn new(w: &[f64], length: f64) -> Self {
+ let dense: Vec<f64> = w.iter().map(|v| v / length).collect();
+ let nonzero = dense.iter().filter(|v| **v != 0.0).count();
+ if nonzero < dense.len() / 2 { Self::Sparse(dense.into_iter().enumerate().filter(|(_, v)| *v != 0.0).collect()) } else { Self::Dense(dense) }
+ }
+
+ fn remove_from(&self, w: &mut [f64]) {
+ match self {
+ Self::Dense(q) => {
+ let d = dot(q, w);
+ for (wk, qk) in w.iter_mut().zip(q) {
+ *wk -= d * qk;
+ }
+ }
+ Self::Sparse(q) => {
+ // Same reduction order as the dense dot product, omitting only exact zeros.
+ let d: f64 = q.iter().filter_map(|(i, v)| w.get(*i).map(|wk| v * wk)).sum();
+ if d != 0.0 {
+ for &(i, v) in q {
+ if let Some(wk) = w.get_mut(i) {
+ *wk -= d * v;
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
/// Per block of `blocks` (in order, over the variables `vars`): whether every one of its rows
/// is a combination of the rows before it. With `support`, also for the block at that index
/// (when redundant) the earlier blocks its rows combine.
@@ -48,28 +91,44 @@ pub(super) fn dependent_blocks(
x: &mut [f64],
support: Option<usize>,
) -> (Vec<bool>, Vec<usize>) {
+ #[cfg(feature = "solver-profiling")]
+ let _timer = {
+ profiling::count(|c| c.redundancy_checks += 1);
+ profiling::timer(Phase::Redundancy)
+ };
let mut col = vec![usize::MAX; lay.n];
columns(&mut col, vars, vars);
- let (_, j, owner) = local_system(sk, lay, blocks, x, &col, vars.len());
+ let (_, j, owner) = {
+ #[cfg(feature = "solver-profiling")]
+ let _timer = profiling::timer(Phase::RedundancyJacobian);
+ local_system(sk, lay, blocks, x, &col, vars.len())
+ };
+ classify_rows(&j, &owner, blocks.len(), support)
+}
+
+fn classify_rows(j: &Mat, owner: &[usize], block_count: usize, support: Option<usize>) -> (Vec<bool>, Vec<usize>) {
+ #[cfg(feature = "solver-profiling")]
+ let classification_timer = profiling::timer(Phase::RedundancyClassification);
let n = j.cols;
- let row = |k: usize| -> Vec<f64> { j.data.get(k * n..(k + 1) * n).map(<[f64]>::to_vec).unwrap_or_default() };
+ let row = |k: usize| -> &[f64] { j.data.get(k * n..(k + 1) * n).unwrap_or_default() };
// Orthonormal directions of the independent rows so far, and those rows with their block.
- let mut q: Vec<Vec<f64>> = Vec::new();
+ let mut q: Vec<Direction> = Vec::new();
let mut basis: Vec<(Vec<f64>, usize)> = Vec::new();
- let mut has_rows = vec![false; blocks.len()];
- let mut adds_rank = vec![false; blocks.len()];
+ let mut has_rows = vec![false; block_count];
+ let mut adds_rank = vec![false; block_count];
let mut target_rows: Vec<Vec<f64>> = Vec::new();
for k in 0..j.rows {
let Some(&b) = owner.get(k) else { continue };
let v = row(k);
- let norm = dot(&v, &v).sqrt();
- let mut w = v.clone();
- // Twice, for the orthogonality lost to rounding.
- for _ in 0..2 {
- for qi in &q {
- let d = dot(qi, &w);
- for (wk, qk) in w.iter_mut().zip(qi) {
- *wk -= d * qk;
+ let norm = dot(v, v).sqrt();
+ let mut w = v.to_vec();
+ // A non-finite or zero norm cannot add rank, regardless of its projections. Skipping
+ // those rows also keeps non-finite inputs out of the exact-zero sparse fast path.
+ if norm.is_finite() && norm > 0.0 {
+ // Twice, for the orthogonality lost to rounding. Preserve row/direction order.
+ for _ in 0..2 {
+ for qi in &q {
+ qi.remove_from(&mut w);
}
}
}
@@ -78,16 +137,23 @@ pub(super) fn dependent_blocks(
*h = true;
}
if norm.is_finite() && left.is_finite() && norm > 0.0 && left > DEPENDENT * norm {
- q.push(w.iter().map(|wk| wk / left).collect());
- basis.push((v, b));
+ q.push(Direction::new(&w, left));
+ // Original rows are used only by explanation queries, never ordinary reports.
+ if support.is_some() {
+ basis.push((v.to_vec(), b));
+ }
if let Some(a) = adds_rank.get_mut(b) {
*a = true;
}
} else if Some(b) == support {
- target_rows.push(v);
+ target_rows.push(v.to_vec());
}
}
let dependent: Vec<bool> = has_rows.iter().zip(&adds_rank).map(|(h, a)| *h && !*a).collect();
+ #[cfg(feature = "solver-profiling")]
+ drop(classification_timer);
+ #[cfg(feature = "solver-profiling")]
+ let _support_timer = profiling::timer(Phase::RedundancySupport);
let mut by = Vec::new();
if let Some(t) = support
&& dependent.get(t).copied().unwrap_or(false)
diff --git a/crates/sketch/src/redundancy_tests.rs b/crates/sketch/src/redundancy_tests.rs
new file mode 100644
index 0000000000..3b284b52f6
--- /dev/null
+++ b/crates/sketch/src/redundancy_tests.rs
@@ -0,0 +1,184 @@
+//! Frozen ordered dense MGS reference for numerical equivalence tests.
+use super::*;
+
+fn compare(rows: &[Vec<f64>], owners: &[usize], blocks: usize) {
+ let cols = rows.first().map_or(0, Vec::len);
+ let j = Mat { rows: rows.len(), cols, data: rows.iter().flatten().copied().collect() };
+ for support in std::iter::once(None).chain((0..blocks).map(Some)) {
+ assert_eq!(classify_rows(&j, owners, blocks, support), dense_reference(&j, owners, blocks, support), "{rows:?}, support {support:?}");
+ }
+}
+
+#[test]
+fn exact_zero_projection_preserves_every_nonzero_result_bit() {
+ for scale in [f64::from_bits(1), 1e-150, 1.0, 1e150] {
+ for q in [vec![0.0, -0.0, 0.6, 0.0, 0.8, 0.0, 0.0, 0.0], vec![0.125; 8]] {
+ for sign in [-1.0, 0.0, 1.0] {
+ let input: Vec<f64> = (0..8).map(|i| sign * scale * (i as f64 - 3.0)).collect();
+ let mut expected = input.clone();
+ let d = dot(&q, &expected);
+ for (wk, qk) in expected.iter_mut().zip(&q) {
+ *wk -= d * qk;
+ }
+ let mut actual = input;
+ Direction::new(&q, 1.0).remove_from(&mut actual);
+ for (a, b) in actual.iter().zip(&expected) {
+ assert!((*a == 0.0 && *b == 0.0) || a.to_bits() == b.to_bits(), "{a} != {b}");
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn ordered_ids_and_explanations_match_dense_mgs_at_the_threshold() {
+ // The repeated target and the partially dependent two-row block must retain their owners.
+ for scale in [1e-150, 1e-6, 1.0, 1e6, 1e150] {
+ for epsilon in [0.0, DEPENDENT * (1.0 - 1e-10), DEPENDENT, DEPENDENT * (1.0 + 1e-10), 1e-5] {
+ let rows = vec![
+ vec![scale, 0.0, 0.0, -0.0, 0.0, 0.0],
+ vec![scale, scale * epsilon, 0.0, 0.0, 0.0, 0.0],
+ vec![0.0, 0.0, scale, 0.0, 0.0, 0.0],
+ vec![scale, scale * epsilon, 0.0, 0.0, 0.0, 0.0],
+ vec![0.0; 6],
+ ];
+ compare(&rows, &[0, 1, 1, 2, 3], 5);
+ }
+ }
+ for hostile in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX, f64::MIN_POSITIVE, f64::from_bits(1)] {
+ compare(&[vec![1.0, 0.0, 0.0, 0.0], vec![0.0, hostile, 0.0, 0.0], vec![1.0, 1.0, 0.0, 0.0]], &[0, 1, 2], 3);
+ }
+ compare(&[], &[], 2);
+}
+
+#[test]
+fn sparse_and_dense_rows_match_over_seeded_mixed_rank_matrices() {
+ let mut seed = 99u64;
+ let mut next = || {
+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ (seed >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0
+ };
+ for cols in [2, 3, 8, 17, 32] {
+ for density in [0.05, 0.3, 1.0] {
+ for _ in 0..20 {
+ let mut rows: Vec<Vec<f64>> = Vec::new();
+ for k in 0..cols * 2 {
+ let row = if k > 0 && k % 3 == 0 {
+ rows[k / 3].iter().map(|v| v * 2.0).collect()
+ } else {
+ (0..cols).map(|_| if next().abs() < density { next() } else { 0.0 }).collect()
+ };
+ rows.push(row);
+ }
+ let owners: Vec<usize> = (0..rows.len()).map(|k| k / 2).collect();
+ compare(&rows, &owners, cols + 1);
+ }
+ }
+ }
+}
+
+#[test]
+fn real_sketch_jacobians_keep_redundant_blocks_and_support() {
+ use crate::ConstraintKind;
+ use solidcraft_geom::Vec2;
+
+ for seed in 0..8 {
+ let mut sk = Sketch::new();
+ let mut points = vec![0];
+ for i in 1..10 {
+ let p = sk.add_point(Vec2::new(i as f64 * 3.0, (i * seed % 7) as f64), None).unwrap();
+ let q = points[i - 1];
+ points.push(p);
+ let l = sk.add_line_pts(q, p, None).unwrap();
+ for k in [ConstraintKind::Horizontal { l }, ConstraintKind::Distance { p, q, value: 3.0 }, ConstraintKind::Horizontal { l }] {
+ sk.add_constraint(k, None).unwrap();
+ }
+ if i % 3 == 0 {
+ sk.add_constraint(ConstraintKind::Coincident { p, q }, None).unwrap();
+ }
+ }
+ let lay = layout(&sk, &Hold::default());
+ let mut x = initial_x(&sk, &lay);
+ let (blocks, _) = build_blocks(&sk, &lay, &points_on_curves(&sk));
+ let vars: Vec<usize> = (0..lay.n).collect();
+ let mut col = vec![usize::MAX; lay.n];
+ columns(&mut col, &vars, &vars);
+ let (_, j, owner) = local_system(&sk, &lay, &blocks, &mut x, &col, vars.len());
+ for support in std::iter::once(None).chain((0..blocks.len()).map(Some)) {
+ assert_eq!(classify_rows(&j, &owner, blocks.len(), support), dense_reference(&j, &owner, blocks.len(), support));
+ }
+ }
+}
+
+fn dense_reference(j: &Mat, owner: &[usize], block_count: usize, support: Option<usize>) -> (Vec<bool>, Vec<usize>) {
+ #[cfg(feature = "solver-profiling")]
+ let classification_timer = profiling::timer(Phase::RedundancyClassification);
+ let n = j.cols;
+ let row = |k: usize| -> Vec<f64> { j.data.get(k * n..(k + 1) * n).map(<[f64]>::to_vec).unwrap_or_default() };
+ // Orthonormal directions of the independent rows so far, and those rows with their block.
+ let mut q: Vec<Vec<f64>> = Vec::new();
+ let mut basis: Vec<(Vec<f64>, usize)> = Vec::new();
+ let mut has_rows = vec![false; block_count];
+ let mut adds_rank = vec![false; block_count];
+ let mut target_rows: Vec<Vec<f64>> = Vec::new();
+ for k in 0..j.rows {
+ let Some(&b) = owner.get(k) else { continue };
+ let v = row(k);
+ let norm = dot(&v, &v).sqrt();
+ let mut w = v.clone();
+ // Twice, for the orthogonality lost to rounding.
+ for _ in 0..2 {
+ for qi in &q {
+ let d = dot(qi, &w);
+ for (wk, qk) in w.iter_mut().zip(qi) {
+ *wk -= d * qk;
+ }
+ }
+ }
+ let left = dot(&w, &w).sqrt();
+ if let Some(h) = has_rows.get_mut(b) {
+ *h = true;
+ }
+ if norm.is_finite() && left.is_finite() && norm > 0.0 && left > DEPENDENT * norm {
+ q.push(w.iter().map(|wk| wk / left).collect());
+ basis.push((v, b));
+ if let Some(a) = adds_rank.get_mut(b) {
+ *a = true;
+ }
+ } else if Some(b) == support {
+ target_rows.push(v);
+ }
+ }
+ let dependent: Vec<bool> = has_rows.iter().zip(&adds_rank).map(|(h, a)| *h && !*a).collect();
+ #[cfg(feature = "solver-profiling")]
+ drop(classification_timer);
+ #[cfg(feature = "solver-profiling")]
+ let _support_timer = profiling::timer(Phase::RedundancySupport);
+ let mut by = Vec::new();
+ if let Some(t) = support
+ && dependent.get(t).copied().unwrap_or(false)
+ && !basis.is_empty()
+ {
+ // The combination of the independent rows that gives each of the target's rows: the
+ // least-squares solution of Bᵀ a = v, from (B Bᵀ) a = B v (B has full row rank).
+ let m = basis.len();
+ let mut g = Mat::zeros(m, m);
+ for (r, (br, _)) in basis.iter().enumerate() {
+ for (c, (bc, _)) in basis.iter().enumerate() {
+ g.set(r, c, dot(br, bc));
+ }
+ }
+ for v in &target_rows {
+ let rhs: Vec<f64> = basis.iter().map(|(b, _)| dot(b, v)).collect();
+ let Some(a) = lin_solve(g.clone(), rhs) else { continue };
+ let big = a.iter().fold(0.0_f64, |m, x| m.max(x.abs()));
+ for (ak, (_, b)) in a.iter().zip(&basis) {
+ if ak.abs() > 1e-6 * big && !by.contains(b) {
+ by.push(*b);
+ }
+ }
+ }
+ by.sort_unstable();
+ }
+ (dependent, by)
+}
diff --git a/crates/sketch/src/solver.rs b/crates/sketch/src/solver.rs
index d5165ae6df..d9f77d5c3b 100644
--- a/crates/sketch/src/solver.rs
+++ b/crates/sketch/src/solver.rs
@@ -19,6 +19,8 @@ use solidcraft_geom::{Seg2, Vec2};
use crate::decompose::Budget;
use crate::linalg::{Mat, determined_vars, solve as lin_solve};
use crate::model::{ConstraintKind, CurveKind, Sketch};
+#[cfg(feature = "solver-profiling")]
+use crate::profiling::{self, Decision, Phase, StopReason};
use crate::union_find::{find, union};
#[path = "cursor.rs"]
@@ -673,6 +675,8 @@ fn copy_block<'a>(b: &Block<'a>) -> Block<'a> {
}
fn block_residuals(s: &State, b: &Block, out: &mut Vec<f64>) {
+ #[cfg(feature = "solver-profiling")]
+ profiling::count(|c| c.residual_block_evaluations = c.residual_block_evaluations.saturating_add(1));
match b {
Block::Closure { a, b } => {
let d = s.p(*a) - s.p(*b);
@@ -846,6 +850,15 @@ fn block_refs(sk: &Sketch, b: &Block) -> Vec<Ref> {
/// Residual vector and Jacobian (rows × all n vars) for the given blocks.
fn system(sk: &Sketch, lay: &Layout, blocks: &[(Block, Vec<usize>)], x: &mut [f64], with_j: bool) -> (Vec<f64>, Option<Mat>, Vec<usize>) {
+ #[cfg(feature = "solver-profiling")]
+ let _timer = profiling::timer(Phase::ResidualSystem);
+ #[cfg(feature = "solver-profiling")]
+ profiling::count(|c| {
+ c.residual_system_evaluations = c.residual_system_evaluations.saturating_add(1);
+ if with_j {
+ c.jacobian_evaluations = c.jacobian_evaluations.saturating_add(1);
+ }
+ });
let mut r = Vec::new();
let mut owner = Vec::new();
for (bi, (b, _)) in blocks.iter().enumerate() {
@@ -856,6 +869,8 @@ fn system(sk: &Sketch, lay: &Layout, blocks: &[(Block, Vec<usize>)], x: &mut [f6
if !with_j {
return (r, None, owner);
}
+ #[cfg(feature = "solver-profiling")]
+ let _jacobian_timer = profiling::timer(Phase::Jacobian);
let mut j = Mat::zeros(r.len(), lay.n);
let mut row = 0;
let mut plus = Vec::new();
@@ -901,6 +916,10 @@ fn local_system(
col: &[usize],
ncols: usize,
) -> (Vec<f64>, Mat, Vec<usize>) {
+ #[cfg(feature = "solver-profiling")]
+ let _timer = profiling::timer(Phase::Jacobian);
+ #[cfg(feature = "solver-profiling")]
+ profiling::count(|c| c.jacobian_evaluations = c.jacobian_evaluations.saturating_add(1));
let (r, _, owner) = system(sk, lay, blocks, x, false);
let mut j = Mat::zeros(r.len(), ncols);
let mut row = 0;
@@ -976,6 +995,8 @@ fn lm_capped_with_budget(
max_iters: usize,
mut budget: Option<&mut Budget>,
) -> Option<(usize, f64)> {
+ #[cfg(feature = "solver-profiling")]
+ let _timer = profiling::timer(Phase::Lm);
let evaluation_work = if budget.is_some() { residual_work(lay, blocks) } else { 0 };
if !within_budget(&mut budget, evaluation_work) {
return None;
@@ -986,17 +1007,27 @@ fn lm_capped_with_budget(
let mut lambda = 1e-3;
let (mut r, _, _) = system(sk, lay, blocks, x, false);
let mut f = norm2(&r);
+ #[cfg(feature = "solver-profiling")]
+ let run = profiling::start_run(n, r.len(), max_iters, f);
for it in 0..max_iters {
if max_abs(&r) < TOL {
+ #[cfg(feature = "solver-profiling")]
+ profiling::finish_run(run, StopReason::ResidualTolerance, max_abs(&r));
return Some((it, max_abs(&r)));
}
let normal_work =
n.saturating_mul(n).saturating_mul(r.len()).saturating_add(evaluation_work.saturating_mul(n.saturating_mul(2).saturating_add(1)));
if !within_budget(&mut budget, normal_work) {
+ #[cfg(feature = "solver-profiling")]
+ profiling::finish_run(run, StopReason::WorkBudget, max_abs(&r));
return Some((it, max_abs(&r)));
}
+ #[cfg(feature = "solver-profiling")]
+ profiling::count(|c| c.outer_iterations = c.outer_iterations.saturating_add(1));
let (_, j, _) = local_system(sk, lay, blocks, x, col, n);
// Normal equations of this component.
+ #[cfg(feature = "solver-profiling")]
+ let normal_timer = profiling::timer(Phase::NormalEquations);
let mut a = Mat::zeros(n, n);
let mut g = vec![0.0; n];
for row in 0..j.rows {
@@ -1011,6 +1042,8 @@ fn lm_capped_with_budget(
}
}
}
+ #[cfg(feature = "solver-profiling")]
+ drop(normal_timer);
let mut improved = false;
// Damping by distance moved, not by JᵀJ's diagonal (Marquardt): of the steps that fit the
// residuals equally well it takes the shortest, so what the constraints leave free moves
@@ -1022,6 +1055,8 @@ fn lm_capped_with_budget(
for _attempt in 0..30 {
let linear_work = n.saturating_mul(n).saturating_mul(n).saturating_add(evaluation_work);
if !within_budget(&mut budget, linear_work) {
+ #[cfg(feature = "solver-profiling")]
+ profiling::finish_run(run, StopReason::WorkBudget, max_abs(&r));
return Some((it, max_abs(&r)));
}
let mut m = a.clone();
@@ -1029,7 +1064,14 @@ fn lm_capped_with_budget(
m.add(i, i, lambda * w + 1e-12);
}
let rhs: Vec<f64> = g.iter().map(|v| -v).collect();
- let Some(step) = lin_solve(m, rhs) else {
+ #[cfg(feature = "solver-profiling")]
+ let linear_timer = profiling::timer(Phase::LinearSolve);
+ let step = lin_solve(m, rhs);
+ #[cfg(feature = "solver-profiling")]
+ drop(linear_timer);
+ let Some(step) = step else {
+ #[cfg(feature = "solver-profiling")]
+ profiling::record_trial(run, it, _attempt, lambda, f, None, &g, &j, None, Decision::LinearFailure);
lambda *= 10.0;
continue;
};
@@ -1041,6 +1083,19 @@ fn lm_capped_with_budget(
}
let (rt, _, _) = system(sk, lay, blocks, &mut trial, false);
let ft = norm2(&rt);
+ #[cfg(feature = "solver-profiling")]
+ profiling::record_trial(
+ run,
+ it,
+ _attempt,
+ lambda,
+ f,
+ Some(ft),
+ &g,
+ &j,
+ Some(&step),
+ if ft.is_finite() && ft < f { Decision::Accepted } else { Decision::Rejected },
+ );
if ft.is_finite() && ft < f {
*x = trial;
r = rt;
@@ -1055,9 +1110,13 @@ fn lm_capped_with_budget(
}
}
if !improved {
+ #[cfg(feature = "solver-profiling")]
+ profiling::finish_run(run, StopReason::NoImprovement, max_abs(&r));
return Some((it, max_abs(&r)));
}
}
+ #[cfg(feature = "solver-profiling")]
+ profiling::finish_run(run, StopReason::IterationLimit, max_abs(&r));
Some((max_iters, max_abs(&r)))
}
@@ -1343,9 +1402,12 @@ pub fn solve_holding(sk: &mut Sketch, hold: &Hold) -> SolveReport {
/// What a solve works out besides placing the geometry.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Analysis {
- /// Degrees of freedom and which geometry the constraints determine: a rank analysis of the
- /// Jacobian, the costly part of solving an already solved sketch.
+ /// Freedom analysis plus redundant constraint IDs. This is the complete diagnostic report
+ /// used by the public solve helpers and final sketch evaluation.
Full,
+ /// Degrees of freedom and which geometry the constraints determine, with the same rank
+ /// analysis as `Full`, but no redundant constraint search (`redundant` is empty).
+ Freedom,
/// Only whether it solved: the report's `dof` is 0 and its determined flags are empty. For
/// solves whose report is only checked with [`SolveReport::ok`] (the frames of a drag).
StatusOnly,
@@ -1389,8 +1451,14 @@ pub fn solve_after_value_edit(sk: &mut Sketch, old: &DrivingValues) -> SolveRepo
/// before an interactive move. Read where the links are now, a point dimensioned from a
/// projected line is on the far side of it as soon as the source moves the line past the point.
pub fn solve_after_edit(sk: &mut Sketch, old: &DrivingValues, stored: Option<&[Vec2]>) -> SolveReport {
+ solve_after_edit_with_analysis(sk, old, stored, Analysis::Full)
+}
+
+/// [`solve_after_edit`] with only the requested diagnostics. Continuation, branch checks and
+/// geometry restoration are identical at every analysis level.
+pub fn solve_after_edit_with_analysis(sk: &mut Sketch, old: &DrivingValues, stored: Option<&[Vec2]>, analysis: Analysis) -> SolveReport {
let old_values: Vec<Option<f64>> = sk.constraints.iter().map(|c| old.get(&c.id).copied()).collect();
- solve_from(sk, &Hold::default(), stored, Analysis::Full, Some(&old_values), &mut Budget::full())
+ solve_from(sk, &Hold::default(), stored, analysis, Some(&old_values), &mut Budget::full())
}
impl Sketch {
@@ -1836,6 +1904,8 @@ fn continue_values(
x: &mut [f64],
edit: &ValueEdit,
) -> (usize, bool) {
+ #[cfg(feature = "solver-profiling")]
+ profiling::count(|c| c.continuation_runs = c.continuation_runs.saturating_add(1));
// Every sub-step lands on a sixty-fourth: the changed constraints at each, built once.
let arena: Vec<Vec<ConstraintKind>> = (0..=SUBSTEPS).map(|j| edit.kinds_at(j)).collect();
let mut blocks: Vec<(Block, Vec<usize>)> = sub.iter().map(|(b, v)| (copy_block(b), v.clone())).collect();
@@ -1870,6 +1940,10 @@ fn solve_inner(
old_values: Option<&[Option<f64>]>,
budget: &mut Budget,
) -> SolveReport {
+ #[cfg(feature = "solver-profiling")]
+ let _timer = profiling::timer(Phase::Solve);
+ #[cfg(feature = "solver-profiling")]
+ profiling::count(|c| c.solve_calls = c.solve_calls.saturating_add(1));
sk.prune_patterns();
sk.refresh_pattern_shapes();
let mut orientation_before = Vec::new();
@@ -1905,7 +1979,11 @@ fn solve_inner(
// applies edits: also the one after linked geometry moved, whose reference is the
// stored state.
let edits = reference.is_none() || old_values.is_some();
+ #[cfg(feature = "solver-profiling")]
+ let seed_timer = profiling::timer(Phase::Seed);
let seeded = crate::construct::seed(sk, &given, reference, edits, &on_curve, budget);
+ #[cfg(feature = "solver-profiling")]
+ drop(seed_timer);
for (i, (at, how)) in seeded.pos.iter().zip(&seeded.placed_by).enumerate() {
if let (Some(at), Some(how), Some(v)) = (at, how, lay.pvar.get(i).copied().flatten())
&& how.anchors()
@@ -1990,6 +2068,12 @@ fn solve_inner(
let mut folded: Vec<String> = Vec::new();
let all_blocks = blocks;
let oversized = |vars: &[usize]| vars.len() > MAX_COMPONENT_VARS;
+ #[cfg(feature = "solver-profiling")]
+ profiling::count(|c| {
+ c.components = c.components.saturating_add(comps.len() as u64);
+ c.oversized_components = c.oversized_components.saturating_add(comps.iter().filter(|(_, v, b)| !b.is_empty() && oversized(v)).count() as u64);
+ c.constructed_variables = c.constructed_variables.saturating_add(constructed.iter().filter(|v| **v).count() as u64);
+ });
let blocks_of = |bis: &mut dyn Iterator<Item = usize>| -> Vec<(Block, Vec<usize>)> {
bis.filter_map(|bi| all_blocks.get(bi).map(|(b, v)| (copy_block(b), v.clone()))).collect()
};
@@ -2044,6 +2128,8 @@ fn solve_inner(
if !(residual < ACCEPT)
&& let Some(plain) = reseeded
{
+ #[cfg(feature = "solver-profiling")]
+ profiling::count(|c| c.plain_start_retries = c.plain_start_retries.saturating_add(1));
for (&v, s0) in vars.iter().zip(&start) {
if let Some(s) = x.get_mut(v) {
*s = plain.get(v).copied().flatten().unwrap_or(*s0);
@@ -2104,6 +2190,8 @@ fn solve_inner(
// Final residuals and analysis, component by component (the Jacobian is block diagonal:
// its rank is the sum of the components' ranks).
+ #[cfg(feature = "solver-profiling")]
+ let _analysis_timer = profiling::timer(Phase::Analysis);
let mut max_residual = 0.0_f64;
let mut failing: Vec<String> = Vec::new();
let mut det = vec![false; lay.n];
@@ -2152,7 +2240,7 @@ fn solve_inner(
let comp_rank = pin_flags.iter().filter(|p| **p).count() + rest_rank;
rank += comp_rank;
// More rows than rank: some constraint may be implied by the others.
- if r.len() > comp_rank && vars.len() <= redundancy::MAX_REDUNDANCY_VARS {
+ if analysis == Analysis::Full && r.len() > comp_rank && vars.len() <= redundancy::MAX_REDUNDANCY_VARS {
let (dependent, _) = redundancy::dependent_blocks(sk, &lay, &sub, vars, &mut x, None);
for ((b, _), d) in sub.iter().zip(dependent) {
if d && let Some(c) = redundancy::block_constraint(b).and_then(|ci| sk.constraints.get(ci))
@@ -2283,7 +2371,7 @@ fn solve_inner(
};
refresh_driven_dimensions(sk);
let (dof, point_determined, curve_determined) = match analysis {
- Analysis::Full => (
+ Analysis::Full | Analysis::Freedom => (
lay.n.saturating_sub(rank),
(0..sk.points.len()).map(pdet).collect(),
sk.curves.iter().enumerate().map(|(i, c)| c.kind.point_ids().into_iter().all(pdet) && vdet(lay.rvar.get(i).copied().flatten())).collect(),
diff --git a/crates/sketch/tests/analysis_levels.rs b/crates/sketch/tests/analysis_levels.rs
new file mode 100644
index 0000000000..a65f76f2b5
--- /dev/null
+++ b/crates/sketch/tests/analysis_levels.rs
@@ -0,0 +1,68 @@
+//! Reduced diagnostics must preserve placement, rollback, feasibility and exact freedom results.
+
+use solidcraft_geom::Vec2;
+use solidcraft_sketch::{Analysis, ConstraintKind, Hold, Sketch, solve_with};
+
+fn compare(sketch: &Sketch, hold: &Hold) {
+ let mut full_geometry = sketch.clone();
+ let mut freedom_geometry = sketch.clone();
+ let mut status_geometry = sketch.clone();
+ let mut full = solve_with(&mut full_geometry, hold, None, Analysis::Full, None);
+ let freedom = solve_with(&mut freedom_geometry, hold, None, Analysis::Freedom, None);
+ let status = solve_with(&mut status_geometry, hold, None, Analysis::StatusOnly, None);
+ assert_eq!(freedom_geometry, full_geometry);
+ assert_eq!(status_geometry, full_geometry);
+ assert!(freedom.redundant.is_empty(), "freedom queries must not compute redundant IDs");
+ full.redundant.clear();
+ assert_eq!(serde_json::to_value(&freedom).unwrap(), serde_json::to_value(&full).unwrap());
+ full.dof = 0;
+ full.point_determined.clear();
+ full.curve_determined.clear();
+ assert_eq!(serde_json::to_value(&status).unwrap(), serde_json::to_value(&full).unwrap());
+}
+
+#[test]
+fn analysis_levels_preserve_results_on_anchored_floating_failed_and_held_geometry() {
+ let mut anchored = Sketch::new();
+ let q = anchored.add_point(Vec2::new(12.0, 3.0), None).unwrap();
+ let k = ConstraintKind::Distance { p: 0, q, value: 10.0 };
+ anchored.add_constraint(k.clone(), None).unwrap();
+ let redundant = anchored.add_constraint(k, None).unwrap();
+ let full = solve_with(&mut anchored.clone(), &Hold::default(), None, Analysis::Full, None);
+ assert!(full.ok());
+ assert_eq!(full.dof, 1);
+ assert!(full.redundant.contains(&redundant));
+ compare(&anchored, &Hold::default());
+ compare(&anchored, &Hold { points: vec![q], radii: vec![] });
+
+ let mut conflict = anchored.clone();
+ conflict.add_constraint(ConstraintKind::Distance { p: 0, q, value: 11.0 }, None).unwrap();
+ assert!(!solve_with(&mut conflict.clone(), &Hold::default(), None, Analysis::Full, None).ok());
+ compare(&conflict, &Hold::default());
+
+ let mut floating = Sketch::new();
+ let l = floating.add_line(Vec2::new(5.0, 5.0), Vec2::new(14.0, 6.0), None, None, None).unwrap();
+ floating.add_constraint(ConstraintKind::Horizontal { l }, None).unwrap();
+ floating.add_constraint(ConstraintKind::Horizontal { l }, None).unwrap();
+ floating.add_constraint(ConstraintKind::Length { l, value: 10.0 }, None).unwrap();
+ compare(&floating, &Hold::default());
+
+ let mut blocks = Sketch::new();
+ let p = blocks.add_point(Vec2::new(4.0, 1.0), None).unwrap();
+ let q = blocks.add_point(Vec2::new(5.0, 2.0), None).unwrap();
+ blocks.add_constraint(ConstraintKind::Coincident { p, q }, None).unwrap();
+ blocks.add_constraint(ConstraintKind::Coincident { p, q }, None).unwrap();
+ let c = blocks.add_circle(Vec2::new(20.0, 30.0), 5.0, None, None).unwrap();
+ blocks.add_constraint(ConstraintKind::Radius { c, value: 5.0 }, None).unwrap();
+ blocks.add_constraint(ConstraintKind::Radius { c, value: 5.0 }, None).unwrap();
+ blocks.add_constraint(ConstraintKind::Distance { p: 0, q: p, value: 999.0 }, None).unwrap();
+ blocks.constraints.last_mut().unwrap().driven = true;
+ compare(&blocks, &Hold::default());
+ compare(&blocks, &Hold { points: vec![p], radii: vec![c] });
+
+ let mut constants = Sketch::new();
+ let q = constants.add_point(Vec2::new(5.0, 0.0), None).unwrap();
+ constants.points[q].fixed = true;
+ constants.add_constraint(ConstraintKind::Distance { p: 0, q, value: 10.0 }, None).unwrap();
+ compare(&constants, &Hold::default());
+}
diff --git a/crates/sketch/tests/cursor_target.rs b/crates/sketch/tests/cursor_target.rs
index df92720280..1e15ee33a4 100644
--- a/crates/sketch/tests/cursor_target.rs
+++ b/crates/sketch/tests/cursor_target.rs
@@ -149,6 +149,33 @@ fn zero_cursor_budget_does_not_start_optimization() {
assert!(budget.exhausted());
}
+#[cfg(feature = "solver-profiling")]
+#[test]
+fn profiling_preserves_budgeted_cursor_motion_and_records_budget_stops() {
+ use solidcraft_sketch::profiling::{StopReason, capture};
+
+ let target = Vec2::new(-10.0, 16.0);
+ let mut saw_budget_stop = false;
+ for work in [0, 128, 256, 512, 1024, 2048, 4096, 8192, 16384] {
+ let (mut plain, a, _) = linkage();
+ let mut measured = plain.clone();
+ let mut plain_budget = solidcraft_sketch::Budget::new(work);
+ let mut measured_budget = solidcraft_sketch::Budget::new(work);
+ let expected = move_point_towards(&mut plain, a, target, 1.25, Some(&mut plain_budget), |_, _| true);
+ let (actual, profile) = capture(|| move_point_towards(&mut measured, a, target, 1.25, Some(&mut measured_budget), |_, _| true));
+ assert_eq!(actual, expected);
+ assert_eq!(measured, plain);
+ assert_eq!(measured_budget.spent(), plain_budget.spent());
+ assert_eq!(measured_budget.exhausted(), plain_budget.exhausted());
+ assert!(profile.runs.iter().all(|run| run.stop_reason.is_some() && run.final_max_residual.is_some()));
+ saw_budget_stop |= profile.runs.iter().any(|run| run.stop_reason == Some(StopReason::WorkBudget));
+ if work == 0 {
+ assert_eq!(profile.counters.lm_runs, 0);
+ }
+ }
+ assert!(saw_budget_stop, "exercise LM returning at its shared work limit");
+}
+
#[test]
fn a_cursor_budget_stop_keeps_the_best_corrected_pose_and_reference_dimensions() {
let target = Vec2::new(-10.0, 16.0);