* claim: #10977 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Parameter Sweep: input and output schemas (#10977) inspect.parameter_sweep gets a typed contract and reply types in schema/parameter_sweep.rs and leaves unconverted.txt. Each key reads as the handler reads it, with its message; the reply is built from ParameterSweep and its item types, with the same JSON as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Parameter Sweep schema: a missing parameter reaches the handler's message Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * parameter_sweep schema: do not publish a null default on the required parameter Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: bherbruck <brennen.herbruck@gmail.com>
This commit is contained in:
5 files changed
+433
-46
No files matched your search
@@ -12,9 +12,21 @@ use solidcore_record::Vec3;
|
||||
|
||||
use super::CommandSpec;
|
||||
use crate::params::{bad, num, str_};
|
||||
use crate::schema::parameter_sweep::{
|
||||
FeatureFailed, FeatureWarned, JointFlipped, JointLost, JointSide, MAX_VALUES, ParameterSweep, ParameterSweepParams, SketchFailed, SketchFlipped,
|
||||
SweepChanges, SweepResult, SweepSummary,
|
||||
};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{Result, Session};
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("inspect.parameter_sweep", "Parameter Sweep", sweep).icon("params").noundo().params(
|
||||
const CONTRACT: TypedContract<ParameterSweepParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("inspect.parameter_sweep", "Parameter Sweep", crate::checked!("inspect.parameter_sweep", sweep))
|
||||
.icon("params")
|
||||
.noundo()
|
||||
.contract(&CONTRACT)
|
||||
.output(output_schema_for::<ParameterSweep>)
|
||||
.params(
|
||||
"parameter: name; values: [number | expression] (at most 200) | from, to: numbers, steps? (default 10, at most 199: steps + 1 values) → \
|
||||
for each value, in a copy of the design (the design itself is not changed): {value, ms (the rebuild), ok, failed: [{feature, name, error}], warned: [{feature, name, warning}] \
|
||||
(features that build at the current value and fail or warn at this one), joints_lost: [{joint, name, origin?: a|b, why}], joints_flipped: [{joint, name, origin: a|b, degrees}] \
|
||||
@@ -24,9 +36,6 @@ pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("inspect.parameter_swee
|
||||
summary: {values, ok, slowest_ms, failed, joints_lost, joints_flipped, sketches_flipped, sketches_failed} (how many values show each)",
|
||||
)];
|
||||
|
||||
/// Values swept by one command, at most.
|
||||
const MAX_VALUES: usize = 200;
|
||||
|
||||
/// A frame's origin and z axis, in its occurrence's coordinates.
|
||||
type Frame = (Vec3, Vec3);
|
||||
|
||||
@@ -85,29 +94,29 @@ fn degrees(a: Vec3, b: Vec3) -> Option<f64> {
|
||||
}
|
||||
|
||||
/// What changed from `base` (the design as it is) to `at` (at one value).
|
||||
fn compare(base: &Look, at: &Look) -> Value {
|
||||
let failed: Vec<Value> = at
|
||||
fn compare(base: &Look, at: &Look) -> SweepChanges {
|
||||
let failed = at
|
||||
.errors
|
||||
.iter()
|
||||
.filter(|(id, _)| !base.errors.contains_key(id))
|
||||
.map(|(id, (name, e))| json!({"feature": id, "name": name, "error": e}))
|
||||
.map(|(id, (name, e))| FeatureFailed { feature: *id, name: name.clone(), error: e.clone() })
|
||||
.collect();
|
||||
let warned: Vec<Value> = at
|
||||
let warned = at
|
||||
.warnings
|
||||
.iter()
|
||||
.filter(|(id, (_, w))| base.warnings.get(id).is_none_or(|(_, b)| b != w) && !at.errors.contains_key(id))
|
||||
.map(|(id, (name, w))| json!({"feature": id, "name": name, "warning": w}))
|
||||
.map(|(id, (name, w))| FeatureWarned { feature: *id, name: name.clone(), warning: w.clone() })
|
||||
.collect();
|
||||
let mut lost = Vec::new();
|
||||
let mut flipped = Vec::new();
|
||||
let mut joints_lost = Vec::new();
|
||||
let mut joints_flipped = Vec::new();
|
||||
for (id, (name, a, b)) in &at.joints {
|
||||
let Some((_, a0, b0)) = base.joints.get(id) else { continue };
|
||||
for (side, now, was) in [("a", a, a0), ("b", b, b0)] {
|
||||
for (side, now, was) in [(JointSide::A, a, a0), (JointSide::B, b, b0)] {
|
||||
match (now, was) {
|
||||
(Err(why), Ok(_)) => lost.push(json!({"joint": id, "name": name, "origin": side, "why": why})),
|
||||
(Err(why), Ok(_)) => joints_lost.push(JointLost { joint: *id, name: name.clone(), origin: Some(side), why: why.clone() }),
|
||||
(Ok(f), Ok(f0)) => {
|
||||
if let Some(d) = degrees(f.1, f0.1).filter(|d| *d > 90.0) {
|
||||
flipped.push(json!({"joint": id, "name": name, "origin": side, "degrees": (d * 10.0).round() / 10.0}));
|
||||
joints_flipped.push(JointFlipped { joint: *id, name: name.clone(), origin: side, degrees: (d * 10.0).round() / 10.0 });
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -117,7 +126,7 @@ fn compare(base: &Look, at: &Look) -> Value {
|
||||
&& a.is_ok()
|
||||
&& b.is_ok()
|
||||
{
|
||||
lost.push(json!({"joint": id, "name": name, "why": why}));
|
||||
joints_lost.push(JointLost { joint: *id, name: name.clone(), origin: None, why: why.clone() });
|
||||
}
|
||||
}
|
||||
let mut sketches_flipped = Vec::new();
|
||||
@@ -125,15 +134,13 @@ fn compare(base: &Look, at: &Look) -> Value {
|
||||
for (id, (name, n, failing, folded)) in &at.sketches {
|
||||
let Some((_, n0, failing0, folded0)) = base.sketches.get(id) else { continue };
|
||||
if let Some(d) = degrees(*n, *n0).filter(|d| *d > 90.0) {
|
||||
sketches_flipped.push(json!({"sketch": id, "name": name, "degrees": (d * 10.0).round() / 10.0}));
|
||||
sketches_flipped.push(SketchFlipped { sketch: *id, name: name.clone(), degrees: (d * 10.0).round() / 10.0 });
|
||||
}
|
||||
if (!failing.is_empty() && failing0.is_empty()) || (!folded.is_empty() && folded0.is_empty()) {
|
||||
sketches_failed.push(json!({"sketch": id, "name": name, "failing": failing, "folded": folded}));
|
||||
sketches_failed.push(SketchFailed { sketch: *id, name: name.clone(), failing: failing.clone(), folded: folded.clone() });
|
||||
}
|
||||
}
|
||||
let ok = failed.is_empty() && lost.is_empty() && flipped.is_empty() && sketches_flipped.is_empty() && sketches_failed.is_empty();
|
||||
json!({"ok": ok, "failed": failed, "warned": warned, "joints_lost": lost, "joints_flipped": flipped,
|
||||
"sketches_flipped": sketches_flipped, "sketches_failed": sketches_failed})
|
||||
SweepChanges { failed, warned, joints_lost, joints_flipped, sketches_flipped, sketches_failed }
|
||||
}
|
||||
|
||||
/// The values to sweep.
|
||||
@@ -175,37 +182,36 @@ fn sweep(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let values = values(p, cmd)?;
|
||||
let base = look(s);
|
||||
let mut results = Vec::new();
|
||||
let mut count: BTreeMap<&str, usize> = BTreeMap::new();
|
||||
let mut slowest: f64 = 0.0;
|
||||
for v in values {
|
||||
let mut summary =
|
||||
SweepSummary { values: 0, ok: 0, slowest_ms: 0.0, failed: 0, joints_lost: 0, joints_flipped: 0, sketches_flipped: 0, sketches_failed: 0 };
|
||||
for value in values {
|
||||
let mut x = s.scratch();
|
||||
let t0 = std::time::Instant::now();
|
||||
let changed = x.execute("parameters.change", &json!({"name": name, "expression": v}));
|
||||
let changed = x.execute("parameters.change", &json!({"name": name, "expression": value}));
|
||||
let ms = (t0.elapsed().as_secs_f64() * 1e4).round() / 10.0;
|
||||
slowest = slowest.max(ms);
|
||||
let mut r = match changed {
|
||||
Ok(_) => compare(&base, &look(&x)),
|
||||
Err(e) => json!({"ok": false, "error": e.to_string()}),
|
||||
};
|
||||
for key in ["failed", "joints_lost", "joints_flipped", "sketches_flipped", "sketches_failed"] {
|
||||
if r[key].as_array().is_some_and(|a| !a.is_empty()) {
|
||||
*count.entry(key).or_default() += 1;
|
||||
summary.slowest_ms = summary.slowest_ms.max(ms);
|
||||
let r = match changed {
|
||||
Ok(_) => {
|
||||
let c = compare(&base, &look(&x));
|
||||
summary.failed += usize::from(!c.failed.is_empty());
|
||||
summary.joints_lost += usize::from(!c.joints_lost.is_empty());
|
||||
summary.joints_flipped += usize::from(!c.joints_flipped.is_empty());
|
||||
summary.sketches_flipped += usize::from(!c.sketches_flipped.is_empty());
|
||||
summary.sketches_failed += usize::from(!c.sketches_failed.is_empty());
|
||||
let ok = c.failed.is_empty()
|
||||
&& c.joints_lost.is_empty()
|
||||
&& c.joints_flipped.is_empty()
|
||||
&& c.sketches_flipped.is_empty()
|
||||
&& c.sketches_failed.is_empty();
|
||||
SweepResult { value, ms, ok, error: None, changes: Some(c) }
|
||||
}
|
||||
}
|
||||
if r["ok"] == json!(true) {
|
||||
*count.entry("ok").or_default() += 1;
|
||||
}
|
||||
r["value"] = v;
|
||||
r["ms"] = json!(ms);
|
||||
Err(e) => SweepResult { value, ms, ok: false, error: Some(e.to_string()), changes: None },
|
||||
};
|
||||
summary.ok += usize::from(r.ok);
|
||||
results.push(r);
|
||||
}
|
||||
let get = |k: &str| count.get(k).copied().unwrap_or(0);
|
||||
Ok(json!({
|
||||
"parameter": name,
|
||||
"results": results,
|
||||
"summary": {"values": results.len(), "ok": get("ok"), "slowest_ms": slowest, "failed": get("failed"), "joints_lost": get("joints_lost"),
|
||||
"joints_flipped": get("joints_flipped"), "sketches_flipped": get("sketches_flipped"), "sketches_failed": get("sketches_failed")},
|
||||
}))
|
||||
summary.values = results.len();
|
||||
serde_json::to_value(ParameterSweep { parameter: name, results, summary, param_warnings: Vec::new() }).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -74,6 +74,7 @@ pub mod material_properties;
|
||||
pub mod metadata;
|
||||
pub mod motion;
|
||||
pub mod panels;
|
||||
pub mod parameter_sweep;
|
||||
pub mod parts;
|
||||
pub mod print_face;
|
||||
pub mod render;
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
//! Contract and result types for `inspect.parameter_sweep` in `cmd/parameter_sweep.rs` (#10977).
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
|
||||
use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::check::whole;
|
||||
use super::types::{not_blank_pattern, present};
|
||||
|
||||
/// Values swept by one command, at most.
|
||||
pub const MAX_VALUES: usize = 200;
|
||||
|
||||
/// Rebuild the design in a copy at each value of a parameter and report what fails, turns over
|
||||
/// or loses its reference there, against the design as it is. The design itself isn't changed.
|
||||
/// Give `values`, or `from` and `to`.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ParameterSweepParams {
|
||||
/// The parameter, by name, as `parameters.list` lists it.
|
||||
#[serde(default, deserialize_with = "parameter_name")]
|
||||
#[schemars(required, transform = drop_default)]
|
||||
pub parameter: Option<String>,
|
||||
#[serde(default, deserialize_with = "present")]
|
||||
#[schemars(with = "SweepValues")]
|
||||
pub values: Option<SweepValues>,
|
||||
/// The first value of an even sweep (used only with `to`).
|
||||
#[serde(default, deserialize_with = "present")]
|
||||
#[schemars(with = "SweepBound")]
|
||||
pub from: Option<SweepBound>,
|
||||
/// The last value of an even sweep (used only with `from`).
|
||||
#[serde(default, deserialize_with = "present")]
|
||||
#[schemars(with = "SweepBound")]
|
||||
pub to: Option<SweepBound>,
|
||||
/// With `from` and `to`: how many steps between them (default 10), so `steps + 1` values.
|
||||
#[serde(default, deserialize_with = "steps")]
|
||||
#[schemars(schema_with = "steps_schema")]
|
||||
pub steps: Option<f64>,
|
||||
}
|
||||
|
||||
/// `serde(default)` makes schemars publish `"default": null` on a required string; drop it.
|
||||
fn drop_default(schema: &mut Schema) {
|
||||
schema.remove("default");
|
||||
}
|
||||
|
||||
/// The parameter's name, with the handler's message for anything that isn't text.
|
||||
fn parameter_name<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::String(s) => Ok(Some(s)),
|
||||
_ => Err(D::Error::custom(whole("`parameter` is required (parameters.list)"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// `steps`, as the handler reads it: `null` is none, else a whole number 1 to 199.
|
||||
fn steps<'de, D: Deserializer<'de>>(d: D) -> Result<Option<f64>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Null => Ok(None),
|
||||
v => v
|
||||
.as_f64()
|
||||
.filter(|k| k.fract() == 0.0 && *k >= 1.0 && *k < MAX_VALUES as f64)
|
||||
.map(Some)
|
||||
.ok_or_else(|| D::Error::custom(format!("must be a whole number 1…{}", MAX_VALUES - 1))),
|
||||
}
|
||||
}
|
||||
|
||||
fn steps_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"type": ["number", "null"], "minimum": 1, "maximum": MAX_VALUES - 1, "multipleOf": 1})
|
||||
}
|
||||
|
||||
/// The values to sweep: 1 to 200, each a number or an expression (1 to 1000 bytes, not blank),
|
||||
/// with the handler's messages. Each is set as the parameter's expression in turn.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SweepValues(pub Vec<Value>);
|
||||
|
||||
impl<'de> Deserialize<'de> for SweepValues {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let Value::Array(list) = Value::deserialize(d)? else {
|
||||
return Err(D::Error::custom(whole("give `values`, or `from` and `to`")));
|
||||
};
|
||||
if list.is_empty() || list.len() > MAX_VALUES {
|
||||
return Err(D::Error::custom(whole(format!("`values` must list 1…{MAX_VALUES} values"))));
|
||||
}
|
||||
let usable = |v: &Value| match v {
|
||||
Value::Number(n) => n.as_f64().is_some_and(f64::is_finite),
|
||||
Value::String(x) => !x.trim().is_empty() && x.len() <= 1000,
|
||||
_ => false,
|
||||
};
|
||||
if !list.iter().all(usable) {
|
||||
return Err(D::Error::custom(whole("each value is a number or an expression")));
|
||||
}
|
||||
Ok(SweepValues(list))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for SweepValues {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"SweepValues".into()
|
||||
}
|
||||
fn inline_schema() -> bool {
|
||||
true
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "The values to sweep, each a number or an expression (at most 1000 bytes, not blank), set as the parameter's expression in turn.",
|
||||
"type": "array",
|
||||
"items": {"anyOf": [{"type": "number"}, {"type": "string", "minLength": 1, "maxLength": 1000, "pattern": not_blank_pattern()}]},
|
||||
"minItems": 1,
|
||||
"maxItems": MAX_VALUES
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// An end of an even sweep: a number at most 1e9 in size, with the handler's message.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct SweepBound(pub f64);
|
||||
|
||||
impl<'de> Deserialize<'de> for SweepBound {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
Value::deserialize(d)?
|
||||
.as_f64()
|
||||
.filter(|x| x.is_finite() && x.abs() <= 1e9)
|
||||
.map(SweepBound)
|
||||
.ok_or_else(|| D::Error::custom("must be a number"))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for SweepBound {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"SweepBound".into()
|
||||
}
|
||||
fn inline_schema() -> bool {
|
||||
true
|
||||
}
|
||||
fn json_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"type": "number", "minimum": -1e9, "maximum": 1e9})
|
||||
}
|
||||
}
|
||||
|
||||
/// What `inspect.parameter_sweep` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ParameterSweep {
|
||||
/// The parameter swept.
|
||||
pub parameter: String,
|
||||
/// One result per value, in order.
|
||||
pub results: Vec<SweepResult>,
|
||||
/// How many values show each kind of change.
|
||||
pub summary: SweepSummary,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// The design at one value: what changed against the design as it is, or why the parameter
|
||||
/// takes no such value.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct SweepResult {
|
||||
/// The value: the number or expression given, or the number an even sweep reached.
|
||||
#[schemars(schema_with = "value_schema")]
|
||||
pub value: Value,
|
||||
/// How long the rebuild took (ms).
|
||||
pub ms: f64,
|
||||
/// Whether nothing failed, was lost or turned over at this value.
|
||||
pub ok: bool,
|
||||
/// Why the parameter takes no such value; then there are no changes.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub error: Option<String>,
|
||||
/// What changed, when the parameter took the value.
|
||||
#[serde(flatten)]
|
||||
pub changes: Option<SweepChanges>,
|
||||
}
|
||||
|
||||
fn value_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"anyOf": [{"type": "number"}, {"type": "string"}]})
|
||||
}
|
||||
|
||||
/// What changed at one value against the design as it is.
|
||||
#[derive(Debug, Default, Serialize, JsonSchema)]
|
||||
pub struct SweepChanges {
|
||||
/// Features that build now and fail at this value.
|
||||
pub failed: Vec<FeatureFailed>,
|
||||
/// Features that warn at this value, with a warning they don't have now.
|
||||
pub warned: Vec<FeatureWarned>,
|
||||
/// Joints that lose an origin, or that the joint solve can no longer apply.
|
||||
pub joints_lost: Vec<JointLost>,
|
||||
/// Joints with an origin whose z axis turned more than 90° on its own part.
|
||||
pub joints_flipped: Vec<JointFlipped>,
|
||||
/// Sketches whose plane's normal turned more than 90°.
|
||||
pub sketches_flipped: Vec<SketchFlipped>,
|
||||
/// Sketches whose solve fails, or keeps a triangle's turn or an offset's side only by
|
||||
/// flipping it, where it doesn't now.
|
||||
pub sketches_failed: Vec<SketchFailed>,
|
||||
}
|
||||
|
||||
/// A feature that fails at this value.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct FeatureFailed {
|
||||
pub feature: u64,
|
||||
pub name: String,
|
||||
pub error: String,
|
||||
}
|
||||
|
||||
/// A feature that warns at this value.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct FeatureWarned {
|
||||
pub feature: u64,
|
||||
pub name: String,
|
||||
pub warning: String,
|
||||
}
|
||||
|
||||
/// Which origin of a joint.
|
||||
#[derive(Clone, Copy, Debug, Serialize, JsonSchema)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum JointSide {
|
||||
A,
|
||||
B,
|
||||
}
|
||||
|
||||
/// A joint that loses an origin (`origin`), or that the joint solve can no longer apply (no
|
||||
/// `origin`).
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct JointLost {
|
||||
pub joint: u64,
|
||||
pub name: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub origin: Option<JointSide>,
|
||||
pub why: String,
|
||||
}
|
||||
|
||||
/// A joint origin whose z axis turned over.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct JointFlipped {
|
||||
pub joint: u64,
|
||||
pub name: String,
|
||||
pub origin: JointSide,
|
||||
/// How far it turned, to 0.1°.
|
||||
pub degrees: f64,
|
||||
}
|
||||
|
||||
/// A sketch whose plane turned over.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct SketchFlipped {
|
||||
pub sketch: u64,
|
||||
pub name: String,
|
||||
/// How far its normal turned, to 0.1°.
|
||||
pub degrees: f64,
|
||||
}
|
||||
|
||||
/// A sketch whose solve fails or folds at this value.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct SketchFailed {
|
||||
pub sketch: u64,
|
||||
pub name: String,
|
||||
/// The constraints its solve can't meet.
|
||||
pub failing: Vec<String>,
|
||||
/// The constraints it meets only by flipping a triangle's turn or an offset's side.
|
||||
pub folded: Vec<String>,
|
||||
}
|
||||
|
||||
/// How many values show each kind of change.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct SweepSummary {
|
||||
/// How many values were swept.
|
||||
pub values: usize,
|
||||
/// How many were ok.
|
||||
pub ok: usize,
|
||||
/// The slowest rebuild (ms).
|
||||
pub slowest_ms: f64,
|
||||
pub failed: usize,
|
||||
pub joints_lost: usize,
|
||||
pub joints_flipped: usize,
|
||||
pub sketches_flipped: usize,
|
||||
pub sketches_failed: usize,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "parameter_sweep_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,102 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{ParameterSweep, ParameterSweepParams};
|
||||
use crate::Session;
|
||||
use crate::schema::tests::{assert_keys, conforms};
|
||||
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
/// A 40 x 30 x 5 plate (its own component) with a 6 mm hole at x = `hx` (a parameter, 20 mm),
|
||||
/// and a pin (another component) held on the hole by a rigid joint, as in the command's tests.
|
||||
fn pinned(s: &mut Session) {
|
||||
run(s, "parameters.add", json!({"name": "hx", "expression": "20 mm"}));
|
||||
run(s, "component.create", json!({"name": "Plate"}));
|
||||
run(s, "solid.box", json!({"length": 40, "width": 30, "height": 5, "corner": [0, 0, 0]}));
|
||||
run(s, "solid.hole", json!({"position": ["hx", 15, 5], "diameter": 6}));
|
||||
run(s, "component.activate", json!({"component": "root"}));
|
||||
run(s, "component.create", json!({"name": "Pin"}));
|
||||
run(s, "solid.cylinder", json!({"base": [100, 0, 0], "axis": [0, 0, 1], "radius": 3, "height": 12, "operation": "new"}));
|
||||
run(s, "component.activate", json!({"component": "root"}));
|
||||
run(
|
||||
s,
|
||||
"joint.create",
|
||||
json!({"type": "rigid", "a": {"occurrence": "Plate", "circle": [23, 15, 4.5]}, "b": {"occurrence": "Pin", "circle": [103, 0, 1]}, "name": "Seat"}),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<ParameterSweepParams>(), &["from", "parameter", "steps", "to", "values"]);
|
||||
}
|
||||
|
||||
/// A call that fails today gets the same message in strict. The handler looks the parameter up
|
||||
/// before it reads the values, so each call runs on a design that has one
|
||||
/// (`assert_strict_keeps_todays_errors` runs on one that has none).
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors() {
|
||||
let many: Vec<u32> = (0..201).collect();
|
||||
let long = "1".repeat(1001);
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"parameter": 5, "values": [1]}),
|
||||
json!({"parameter": "nope", "values": [1]}),
|
||||
json!({"parameter": "w"}),
|
||||
json!({"parameter": "w", "values": 5}),
|
||||
json!({"parameter": "w", "values": null}),
|
||||
json!({"parameter": "w", "values": []}),
|
||||
json!({"parameter": "w", "values": many}),
|
||||
json!({"parameter": "w", "values": [true]}),
|
||||
json!({"parameter": "w", "values": [" "]}),
|
||||
json!({"parameter": "w", "values": [long]}),
|
||||
json!({"parameter": "w", "values": [1], "from": 0}),
|
||||
json!({"parameter": "w", "from": 0}),
|
||||
json!({"parameter": "w", "from": "x", "to": 1}),
|
||||
json!({"parameter": "w", "from": null, "to": 1}),
|
||||
json!({"parameter": "w", "from": 0, "to": 2e9}),
|
||||
json!({"parameter": "w", "from": 0, "to": 1, "steps": 0}),
|
||||
json!({"parameter": "w", "from": 0, "to": 1, "steps": 1.5}),
|
||||
json!({"parameter": "w", "from": 0, "to": 1, "steps": "x"}),
|
||||
json!({"parameter": "w", "from": 0, "to": 1, "steps": 200}),
|
||||
] {
|
||||
let error = |level: ParamCheck| {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "parameters.add", json!({"name": "w", "expression": "10 mm"}));
|
||||
s.param_check = level;
|
||||
s.execute("inspect.parameter_sweep", &p).err().map(|e| e.to_string())
|
||||
};
|
||||
let off = error(ParamCheck::Off);
|
||||
assert!(off.is_some(), "{p} should fail today");
|
||||
assert_eq!(error(ParamCheck::Strict), off, "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #10977: a sweep replies as its output schema says, in Warn without warnings for good calls
|
||||
/// and with them for a misspelt key: values the last of which loses the joint (each result with
|
||||
/// its changes), an even sweep, and a value the parameter refuses (a result with an error).
|
||||
#[test]
|
||||
fn a_sweep_replies_with_its_schema() {
|
||||
let schema = output_schema_for::<ParameterSweep>();
|
||||
let matches = |r: &Value, warned: bool| {
|
||||
let schema = schema.as_value();
|
||||
assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");
|
||||
assert_eq!(r.get("param_warnings").is_some(), warned, "{r}");
|
||||
};
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
pinned(&mut s);
|
||||
let r = run(&mut s, "inspect.parameter_sweep", json!({"parameter": "hx", "values": [10, "30 mm", 80]}));
|
||||
matches(&r, false);
|
||||
let far = &r["results"][2];
|
||||
assert_eq!(far["ok"], false, "{r}");
|
||||
assert!(far["joints_lost"].as_array().is_some_and(|j| !j.is_empty()), "{r}");
|
||||
assert_eq!(r["summary"]["values"], 3, "{r}");
|
||||
let r = run(&mut s, "inspect.parameter_sweep", json!({"parameter": "hx", "from": 10, "to": 30, "steps": 2}));
|
||||
matches(&r, false);
|
||||
assert_eq!(r["results"].as_array().map(Vec::len), Some(3), "{r}");
|
||||
let r = run(&mut s, "inspect.parameter_sweep", json!({"parameter": "hx", "values": ["1 +"], "steps": null}));
|
||||
matches(&r, false);
|
||||
assert!(r["results"][0]["error"].is_string() && r["results"][0].get("failed").is_none(), "{r}");
|
||||
matches(&run(&mut s, "inspect.parameter_sweep", json!({"parameter": "hx", "values": [20], "step": 2})), true);
|
||||
}
|
||||
@@ -73,7 +73,6 @@ frame.profile.list
|
||||
frame.profile.properties
|
||||
inspect.interference
|
||||
inspect.measure
|
||||
inspect.parameter_sweep
|
||||
inspect.silhouette
|
||||
joint.as_built
|
||||
joint.cam
|
||||
|
||||
Reference in new issue
Block a user