Sketch: a distance dimension of 0 keeps the sketch fully constrained (#4368) (#4397)

This commit is contained in:
raykholo
2026-10-25 18:19:55 +00:00
committed by GitHub
parent ef1a400bb3
commit d876f475a6
3 changed files with 168 additions and 6 deletions
+10 -3
View File
@@ -321,13 +321,17 @@ mod tests {
#[test]
fn measurements_preserve_geometry_and_explain_a_stalled_solve() {
for x in [0.0, 1e-5] {
for (x, stalled) in [(0.0, true), (0.0, false), (1e-5, false)] {
let mut plain = distance(x);
if stalled {
// Horizontal distances retain the magnitude residual and its zero slope.
plain.constraints[0].kind = ConstraintKind::DistanceX { p: 0, q: 1, value: 10.0 };
}
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!(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);
@@ -337,13 +341,16 @@ mod tests {
);
assert!(profile.counters.residual_block_evaluations > profile.counters.residual_system_evaluations);
let first = profile.trials.first().unwrap();
if x == 0.0 {
if stalled {
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!(b.ok());
assert_eq!(profile.runs[0].stop_reason, Some(StopReason::ResidualTolerance));
assert!(first.gradient_inf.unwrap() > 0.0);
assert!(first.step_norm.unwrap() > 0.0);
assert!(profile.counters.accepted_trials > 0);
assert!((first.rho.unwrap() - 1.0).abs() < 1e-6, "the positive radial step is a linear residual");
}
+52 -3
View File
@@ -572,12 +572,20 @@ fn residuals(s: &State, k: &ConstraintKind, out: &mut Vec<f64>) {
out.push((qq - pp).dot(dir) / len);
}
Fix { .. } => {}
// A distance within convergence tolerance of zero means coincidence: two
// component rows keep both directions constrained even when the points meet.
Distance { p, q, value } if value.abs() <= TOL => {
let d = s.p(p) - s.p(q);
out.extend([d.x, d.y]);
}
Distance { p, q, value } => out.push(s.p(p).dist(s.p(q)) - value),
DistanceX { p, q, value } => out.push((s.p(q).x - s.p(p).x).abs() - value),
DistanceY { p, q, value } => out.push((s.p(q).y - s.p(p).y).abs() - value),
PointLineDistance { p, l, value } => {
let (a, b) = s.line(l);
out.push(line_dist(s.p(p), a, b).abs() - value);
let d = line_dist(s.p(p), a, b);
// At zero this is point-on-line; the signed distance retains its slope.
out.push(if value.abs() <= TOL { d } else { d.abs() - value });
}
LineCircleDistance { l, c, value, inside } => out.push(s.line_circle_gap(l, c, inside) - value),
PointCircleDistance { p, c, value, inside } => out.push(s.point_circle_gap(p, c, inside) - value),
@@ -876,6 +884,45 @@ fn block_refs(sk: &Sketch, b: &Block) -> Vec<Ref> {
}
}
/// A positive distance edited from zero needs an opening direction: central differences
/// of its magnitude cancel at coincidence. Use a unit radial subgradient there, or the
/// signed line normal. Once separated, ordinary central differences apply again.
fn distance_opening_slope(s: &State, b: &Block, v: usize) -> Option<f64> {
let point = |p: usize, gradient: Vec2| match s.lay.pvar.get(p).copied().flatten() {
Some(first) if v == first => gradient.x,
Some(first) if v == first + 1 => gradient.y,
_ => 0.0,
};
match b {
Block::User(_, ConstraintKind::Distance { p, q, value }) if *value > TOL => {
let d = s.p(*q) - s.p(*p);
if d.len() > TOL {
return None;
}
// Unequal nonzero components avoid symmetry with axes and 45-degree guides.
let direction = d.normalized().unwrap_or(Vec2::new(0.6, 0.8));
Some(point(*q, direction) - point(*p, direction))
}
Block::User(_, ConstraintKind::PointLineDistance { p, l, value }) if *value > TOL => {
let (a, b) = s.line(*l);
let signed = line_dist(s.p(*p), a, b);
if signed.abs() > TOL {
return None;
}
let Some(CurveKind::Line { a: ai, b: bi }) = s.sk.curves.get(*l).map(|c| &c.kind) else { return None };
let d = b - a;
let length = d.len();
if length <= 1e-12 {
return None;
}
let normal = d.perp() * (if signed < 0.0 { -1.0 } else { 1.0 } / length);
let along = (s.p(*p) - a).dot(d) / (length * length);
Some(point(*p, normal) + point(*ai, normal * (along - 1.0)) - point(*bi, normal * along))
}
_ => None,
}
}
/// 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")]
@@ -909,6 +956,7 @@ fn system(sk: &Sketch, lay: &Layout, blocks: &[(Block, Vec<usize>)], x: &mut [f6
let rows = plus.len();
for &v in vars {
let Some(x0) = x.get(v).copied() else { continue };
let opening = distance_opening_slope(&State { sk, lay, x }, b, v);
let h = 1e-7 * x0.abs().max(1.0);
if let Some(xv) = x.get_mut(v) {
*xv = x0 + h;
@@ -925,7 +973,7 @@ fn system(sk: &Sketch, lay: &Layout, blocks: &[(Block, Vec<usize>)], x: &mut [f6
}
for k in 0..rows {
let d = (plus.get(k).copied().unwrap_or(0.0) - minus.get(k).copied().unwrap_or(0.0)) / (2.0 * h);
j.set(row + k, v, d);
j.set(row + k, v, if k == 0 { opening.unwrap_or(d) } else { d });
}
}
row += rows;
@@ -960,6 +1008,7 @@ fn local_system(
for &v in vars {
let Some(c) = col.get(v).copied().filter(|c| *c < ncols) else { continue };
let Some(x0) = x.get(v).copied() else { continue };
let opening = distance_opening_slope(&State { sk, lay, x }, b, v);
let h = 1e-7 * x0.abs().max(1.0);
if let Some(xv) = x.get_mut(v) {
*xv = x0 + h;
@@ -976,7 +1025,7 @@ fn local_system(
}
for k in 0..rows {
let d = (plus.get(k).copied().unwrap_or(0.0) - minus.get(k).copied().unwrap_or(0.0)) / (2.0 * h);
j.set(row + k, c, d);
j.set(row + k, c, if k == 0 { opening.unwrap_or(d) } else { d });
}
}
row += rows;
+106
View File
@@ -95,6 +95,112 @@ fn fully_constrained_rectangle() {
assert!(p1.dist(v(55.0, 0.0)) < 1e-7);
}
#[test]
fn zero_distance_matches_coincident() {
for seed in [false, true] {
seeded(seed, || {
for fixed in [false, true] {
for value in [0.0, 1e-12] {
let mut sk = Sketch::new();
let p = if fixed { 0 } else { sk.add_point(v(2.0, 3.0), None).unwrap() };
let q = sk.add_point(sk.point(p).unwrap(), None).unwrap();
let mut equivalent = sk.clone();
let id = sk.add_constraint(ConstraintKind::Distance { p, q, value }, None).unwrap();
equivalent.add_constraint(ConstraintKind::Coincident { p, q }, None).unwrap();
let report = solve(&mut sk);
let expected = solve(&mut equivalent);
assert!(report.ok() && expected.ok(), "{report:?}, {expected:?}");
assert_eq!(report.dof, if fixed { 0 } else { 2 }, "{report:?}");
assert_eq!(report.dof, expected.dof);
assert_eq!(report.point_determined, expected.point_determined);
assert!(!report.redundant.contains(&id), "{report:?}");
assert!(determined_by(&sk, 0).is_empty());
assert!(sk.point(q).unwrap().dist(equivalent.point(q).unwrap()) < 1e-8);
sk.add_constraint(ConstraintKind::Coincident { p, q }, None).unwrap();
assert_eq!(solve(&mut sk).redundant.len(), 1);
assert_eq!(determined_by(&sk, 1), vec![0]);
}
}
});
}
}
#[test]
fn zero_distance_to_line_matches_point_on_line() {
for seed in [false, true] {
seeded(seed, || {
for value in [0.0, 1e-12] {
for start in [v(2.0, 2.0), v(3.0, 1.0)] {
let mut sk = Sketch::new();
let l = sk.add_line(v(1.0, 1.0), v(4.0, 4.0), None, None, None).unwrap();
sk.curves[l].fixed = true;
let p = sk.add_point(start, None).unwrap();
let mut equivalent = sk.clone();
let id = sk.add_constraint(ConstraintKind::PointLineDistance { p, l, value }, None).unwrap();
equivalent.add_constraint(ConstraintKind::PointOnCurve { p, c: l }, None).unwrap();
let report = solve(&mut sk);
let expected = solve(&mut equivalent);
assert!(report.ok() && expected.ok(), "{report:?}, {expected:?}");
assert_eq!(report.dof, 1, "{report:?}");
assert_eq!(report.dof, expected.dof);
assert_eq!(report.point_determined, expected.point_determined);
assert!(!report.redundant.contains(&id), "{report:?}");
assert!(determined_by(&sk, 0).is_empty());
assert!(sk.point(p).unwrap().dist(equivalent.point(p).unwrap()) < 1e-8);
sk.add_constraint(ConstraintKind::PointOnCurve { p, c: l }, None).unwrap();
assert_eq!(solve(&mut sk).redundant.len(), 1);
assert_eq!(determined_by(&sk, 1), vec![0]);
}
}
});
}
}
#[test]
fn zero_distance_edits_preserve_dimension_rank() {
for seed in [false, true] {
seeded(seed, || {
for point_line in [false, true] {
for direction in [Vec2::X, Vec2::Y, v(1.0, -1.0) / 2.0_f64.sqrt()] {
let mut sk = Sketch::new();
let p = sk.add_point(direction * 5.0, None).unwrap();
let kind = if point_line {
let along = direction.perp() * 10.0;
let l = sk.add_line(along * -1.0, along, None, None, None).unwrap();
sk.curves[l].fixed = true;
ConstraintKind::PointLineDistance { p, l, value: 5.0 }
} else {
ConstraintKind::Distance { p: 0, q: p, value: 5.0 }
};
let id = sk.add_constraint(kind, None).unwrap();
let alignment = if direction == Vec2::X {
ConstraintKind::HorizontalPoints { p: 0, q: p }
} else if direction == Vec2::Y {
ConstraintKind::VerticalPoints { p: 0, q: p }
} else {
let l = sk.add_line(direction * -10.0, direction * 10.0, None, None, None).unwrap();
sk.curves[l].fixed = true;
ConstraintKind::PointOnCurve { p, c: l }
};
sk.add_constraint(alignment, None).unwrap();
for value in [5.0, 0.0, 5.0] {
let old = sk.driving_values();
sk.constraints[0].kind.set_value(value);
let report = solve_after_value_edit(&mut sk, &old);
assert!(report.ok(), "{point_line}, {direction:?}, {value}: {report:?}");
assert_eq!(report.dof, 0, "{point_line}, {direction:?}, {value}: {report:?}");
assert!(report.point_determined[p]);
assert!(!report.redundant.contains(&id), "{report:?}");
assert!(determined_by(&sk, 0).is_empty());
assert!(constraint_residual(&sk, 0).unwrap() < 1e-6);
assert!((sk.point(p).unwrap().len() - value).abs() < 1e-6);
}
}
}
});
}
}
#[test]
fn under_constrained_reports_dof() {
let mut sk = Sketch::new();