parameters: import evaluates once; parameters.change takes several names (#2777)
* parameters: import evaluates once; parameters.change takes several names
parameters.import checked every row through change_param, which cloned the
design and evaluated every parameter per row: 2000 rows took 9.5 s, 2823 in
an assembly minutes. Rows are now checked and applied in one pass with the
values carried along, then evaluated once (2000 rows: 0.016 s), still all or
nothing; a row may name a parameter defined by a later row.
parameters.change {changes: {name: expression, ...}} sets several existing
parameters together, rebuilt once and undone in one step.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* parameters.change: the params doc names the `changed` result of `changes`
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: bherbruck <brennen.herbruck@gmail.com>
This commit is contained in:
+14
-15
@@ -897,10 +897,6 @@ pub fn eval_params(params: &[ParamDef], doc_len: f64) -> (BTreeMap<String, Value
|
||||
if cx.stack.len() > 512 {
|
||||
return Err(DocError::Expr("parameters nested too deeply".into()));
|
||||
}
|
||||
let Some((kind, _)) = unit_info(&p.unit).or(Some((Kind::Length, 1.0))) else {
|
||||
return Err(DocError::Expr(format!("unknown unit `{}`", p.unit)));
|
||||
};
|
||||
let defaults = Defaults::for_unit(&p.unit, cx.doc_len);
|
||||
cx.stack.push(name.to_string());
|
||||
let mut vals: BTreeMap<String, Value> = BTreeMap::new();
|
||||
let mut err = None;
|
||||
@@ -918,17 +914,7 @@ pub fn eval_params(params: &[ParamDef], doc_len: f64) -> (BTreeMap<String, Value
|
||||
cx.stack.pop();
|
||||
let r = match err {
|
||||
Some(e) => Err(e),
|
||||
None => {
|
||||
eval_with_defaults(&p.expr, &|n| vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))), defaults)
|
||||
.and_then(|v| {
|
||||
let x = v.to_kind_in(kind, defaults)?;
|
||||
Ok(match kind {
|
||||
Kind::Length => Value::length(x),
|
||||
Kind::Angle => Value::angle(x),
|
||||
Kind::Unitless => Value::num(x),
|
||||
})
|
||||
})
|
||||
}
|
||||
None => eval_def(p, &|n| vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))), cx.doc_len),
|
||||
};
|
||||
match &r {
|
||||
Ok(v) => {
|
||||
@@ -949,6 +935,19 @@ pub fn eval_params(params: &[ParamDef], doc_len: f64) -> (BTreeMap<String, Value
|
||||
(cx.done, cx.errors)
|
||||
}
|
||||
|
||||
/// One parameter's value: its expression in its unit, with the values of the parameters it
|
||||
/// refers to from `lookup`.
|
||||
pub fn eval_def(p: &ParamDef, lookup: &dyn Fn(&str) -> Result<Value, DocError>, doc_len: f64) -> Result<Value, DocError> {
|
||||
let (kind, _) = unit_info(&p.unit).unwrap_or((Kind::Length, 1.0));
|
||||
let defaults = Defaults::for_unit(&p.unit, doc_len);
|
||||
let x = eval_with_defaults(&p.expr, lookup, defaults)?.to_kind_in(kind, defaults)?;
|
||||
Ok(match kind {
|
||||
Kind::Length => Value::length(x),
|
||||
Kind::Angle => Value::angle(x),
|
||||
Kind::Unitless => Value::num(x),
|
||||
})
|
||||
}
|
||||
|
||||
/// Dependency edges between parameters: (parameter, parameter it references).
|
||||
pub fn param_edges(params: &[ParamDef]) -> Vec<(String, String)> {
|
||||
let mut out = Vec::new();
|
||||
|
||||
@@ -463,14 +463,92 @@ impl Document {
|
||||
if rows.len() > 10_000 {
|
||||
return Err(DocError::Invalid("too many parameters".into()));
|
||||
}
|
||||
// Each row is checked and applied as `change_param` would, but the parameters are
|
||||
// evaluated once for all of them, not once per row (thousands of rows took minutes).
|
||||
let mut next = self.clone();
|
||||
let mut names = Vec::new();
|
||||
for (n, e, u, c) in rows {
|
||||
next.change_param(&n, &e, u.as_deref(), c.as_deref())?;
|
||||
names.push(n);
|
||||
let (mut vals, _) = next.param_values();
|
||||
for (n, e, u, c) in &rows {
|
||||
next.import_row(n, e, u.as_deref(), c.as_deref(), &mut vals)?;
|
||||
}
|
||||
let (_, errors) = next.param_values();
|
||||
if let Some(e) = rows.iter().find_map(|(n, ..)| errors.get(n)) {
|
||||
return Err(DocError::Expr(e.clone()));
|
||||
}
|
||||
*self = next;
|
||||
Ok(names)
|
||||
Ok(rows.into_iter().map(|(n, ..)| n).collect())
|
||||
}
|
||||
|
||||
/// One imported row: the checks and change of `change_param` (a feature's parameter) or
|
||||
/// `set_param` (a user parameter, a new one taking the unit of its value) without evaluating
|
||||
/// every parameter. `vals` are the values so far, for the units of the rows after it.
|
||||
fn import_row(&mut self, name: &str, expr_s: &str, unit: Option<&str>, comment: Option<&str>, vals: &mut BTreeMap<String, Value>) -> Result<()> {
|
||||
if expr_s.len() > 4096 {
|
||||
return Err(DocError::Expr("expression too long".into()));
|
||||
}
|
||||
let hit = self.features.iter().enumerate().find_map(|(i, f)| f.param_names.iter().position(|n| n == name).map(|k| (i, k)));
|
||||
if let Some((i, k)) = hit {
|
||||
let kind = self.features.get(i).and_then(|f| f.kind.inputs().get(k).map(|x| x.2)).unwrap_or(Kind::Unitless);
|
||||
let expr_s = self.with_design_unit(expr_s, kind);
|
||||
if let Some(f) = self.features.get_mut(i)
|
||||
&& let Some((_, e, _)) = f.kind.inputs_mut().into_iter().nth(k)
|
||||
{
|
||||
*e = expr_s.into();
|
||||
}
|
||||
if let Some(c) = comment {
|
||||
self.param_comments.insert(name.to_string(), c.to_string());
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(p) = Self::param_name_problem(name) {
|
||||
return Err(DocError::Invalid(p));
|
||||
}
|
||||
if expr_s.trim().is_empty() {
|
||||
return Err(DocError::Expr("empty expression".into()));
|
||||
}
|
||||
if let Some(u) = unit
|
||||
&& expr::unit_info(u).is_none()
|
||||
{
|
||||
return Err(DocError::Expr(format!("unknown unit `{u}` (mm, cm, m, in, ft, deg, rad or none)")));
|
||||
}
|
||||
if comment.is_some_and(|c| c.len() > 4096) {
|
||||
return Err(DocError::Invalid("comment too long".into()));
|
||||
}
|
||||
match self.params.iter_mut().find(|p| p.name == name) {
|
||||
Some(p) => {
|
||||
p.expr = expr_s.trim().to_string();
|
||||
if let Some(u) = unit {
|
||||
p.unit = u.trim().to_string();
|
||||
}
|
||||
if let Some(c) = comment {
|
||||
p.comment = c.to_string();
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if self.params.len() >= MAX_PARAMS {
|
||||
return Err(DocError::Invalid("too many parameters".into()));
|
||||
}
|
||||
let unit = match unit {
|
||||
Some(u) => u.trim().to_string(),
|
||||
None => Self::infer_unit_in(vals, expr_s),
|
||||
};
|
||||
self.params.push(crate::Param {
|
||||
name: name.into(),
|
||||
expr: expr_s.trim().into(),
|
||||
unit,
|
||||
comment: comment.unwrap_or_default().into(),
|
||||
model: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
let def = self.params.iter().find(|p| p.name == name).map(|p| ParamDef { name: p.name.clone(), expr: p.expr.clone(), unit: p.unit.clone() });
|
||||
let value = def.and_then(|d| {
|
||||
expr::eval_def(&d, &|n| vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))), doc_len(&self.units)).ok()
|
||||
});
|
||||
match value {
|
||||
Some(v) => vals.insert(name.to_string(), v),
|
||||
None => vals.remove(name),
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -558,7 +636,11 @@ impl Document {
|
||||
/// The unit for a new parameter with this expression: that of its value; a bare number is
|
||||
/// a length (mm).
|
||||
pub(crate) fn infer_unit(&self, e: &str) -> String {
|
||||
let (vals, _) = self.param_values();
|
||||
Self::infer_unit_in(&self.param_values().0, e)
|
||||
}
|
||||
|
||||
/// [`Document::infer_unit`] against parameter values already worked out.
|
||||
fn infer_unit_in(vals: &BTreeMap<String, Value>, e: &str) -> String {
|
||||
let v = expr::eval_with(e, &|n| vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))));
|
||||
match v.ok().and_then(|v| v.kind()) {
|
||||
Some(Kind::Unitless) if !expr::references(e).is_empty() => String::new(),
|
||||
|
||||
@@ -12,7 +12,8 @@ use crate::{EngineError, Result, Session};
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("parameters.change", "Change Parameters", change_param).at("SOLID", "MODIFY").icon("params").params(
|
||||
"name, expression (number or text), unit?: mm|cm|m|in|ft|deg|rad|\"\" (new parameters default to their value's unit), comment?, \
|
||||
favorite?: bool, new_name?: rename (references follow); or delete: name → recomputed: features rebuilt, \
|
||||
favorite?: bool, new_name?: rename (references follow); or delete: name; or changes: {name: expression, …} (existing \
|
||||
parameters, checked together and rebuilt once, all or nothing) → changed?: {name: value} (with changes), recomputed: features rebuilt, \
|
||||
restored: features whose earlier result for the same inputs was reused (e.g. a value set back)",
|
||||
),
|
||||
CommandSpec::new("parameters.list", "List Parameters", list).icon("list").noundo().doc_only().params(
|
||||
@@ -82,6 +83,9 @@ fn known(s: &Session, name: &str) -> bool {
|
||||
fn change_param(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "parameters.change";
|
||||
let solved = s.solved_sketches();
|
||||
if let Some(changes) = p.get("changes") {
|
||||
return change_many(s, changes, &solved);
|
||||
}
|
||||
if let Some(n) = str_(p, "delete") {
|
||||
s.doc_mut().remove_param(n.trim())?;
|
||||
s.settle_value_edit(&solved)?;
|
||||
@@ -129,6 +133,26 @@ fn change_param(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `parameters.change {changes}`: several existing parameters set at once, so a design is
|
||||
/// rebuilt once for all of them instead of once per parameter.
|
||||
fn change_many(s: &mut Session, changes: &Value, solved: &crate::SketchValues) -> Result<Value> {
|
||||
let cmd = "parameters.change";
|
||||
let Some(map) = changes.as_object() else { return Err(bad(cmd, "`changes` must be an object of name: expression")) };
|
||||
if map.is_empty() {
|
||||
return Err(bad(cmd, "`changes` is empty"));
|
||||
}
|
||||
let mut list = Vec::with_capacity(map.len());
|
||||
for (name, e) in map {
|
||||
let e = expr_arg(&json!({"e": e}), "e").ok_or_else(|| bad(cmd, format!("`changes.{name}` must be a number or text")))?;
|
||||
list.push((name.trim().to_string(), e));
|
||||
}
|
||||
s.doc_mut().change_params_atomic(&list)?;
|
||||
s.settle_value_edit(solved)?;
|
||||
let (vals, _) = s.doc.param_values();
|
||||
let values: serde_json::Map<String, Value> = list.iter().map(|(n, _)| (n.clone(), json!(vals.get(n).map(|v| v.v)))).collect();
|
||||
Ok(json!({"changed": values, "recomputed": s.model.last_recomputed, "restored": s.model.last_restored, "errors": failing(s)}))
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let filter = match (bool_(p, "favorites"), str_(p, "filter")) {
|
||||
(Some(true), _) => "favorites".to_string(),
|
||||
|
||||
@@ -593,3 +593,65 @@ fn moving_a_parameter_refuses_bad_targets() {
|
||||
}
|
||||
assert_eq!(s.doc.to_json(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_large_import_is_checked_once_and_keeps_each_rows_unit() {
|
||||
// 3000 parameters, each the one before plus a millimetre, then an angle, a unit-less
|
||||
// ratio and a row that names a parameter defined further down: all new, in one import.
|
||||
let mut csv = String::from("name,expression\n");
|
||||
csv.push_str("a,later * 2\np0,1 mm\n");
|
||||
for i in 1..3000 {
|
||||
csv.push_str(&format!("p{i},p{} + 1 mm\n", i - 1));
|
||||
}
|
||||
csv.push_str("turn,30 deg\nratio,p10 / p4\nlater,5\n");
|
||||
let mut s = Session::default();
|
||||
let t = std::time::Instant::now();
|
||||
run(&mut s, "parameters.import", json!({"text": csv}));
|
||||
println!("import of {} rows: {:.2} s", 3005, t.elapsed().as_secs_f64());
|
||||
let (vals, errors) = s.doc.param_values();
|
||||
assert!(errors.is_empty(), "{errors:?}");
|
||||
let unit = |n: &str| s.doc.param(n).map(|p| p.unit.clone()).unwrap_or_default();
|
||||
assert_eq!((unit("p2999"), unit("turn"), unit("ratio"), unit("later")), ("mm".into(), "deg".into(), String::new(), "mm".into()));
|
||||
assert!(
|
||||
vals.get("p2999").is_some_and(|v| (v.to_kind(solidcraft_doc::expr::Kind::Length).unwrap_or(f64::NAN) - 3000.0).abs() < 1e-9),
|
||||
"{:?}",
|
||||
vals.get("p2999")
|
||||
);
|
||||
assert!(
|
||||
vals.get("a").is_some_and(|v| (v.to_kind(solidcraft_doc::expr::Kind::Length).unwrap_or(f64::NAN) - 10.0).abs() < 1e-9),
|
||||
"{:?}",
|
||||
vals.get("a")
|
||||
);
|
||||
// Changing the first moves the whole chain; a row that breaks changes nothing.
|
||||
run(&mut s, "parameters.import", json!({"text": "name,expression\np0,101 mm\n"}));
|
||||
assert!(
|
||||
s.doc
|
||||
.param_values()
|
||||
.0
|
||||
.get("p2999")
|
||||
.is_some_and(|v| (v.to_kind(solidcraft_doc::expr::Kind::Length).unwrap_or(f64::NAN) - 3100.0).abs() < 1e-9)
|
||||
);
|
||||
assert!(s.execute("parameters.import", &json!({"text": "name,expression\np0,2 mm\np5,p0 + 1 deg\n"})).is_err());
|
||||
assert_eq!(s.doc.param("p0").map(|p| p.expr.as_str()), Some("101 mm"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_parameters_change_in_one_rebuild_and_one_undo() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "parameters.add", json!({"name": "h", "expression": "10 mm"}));
|
||||
block(&mut s);
|
||||
let d = run(&mut s, "parameters.list", json!({"filter": "feature"}))["parameters"][0]["name"].as_str().unwrap_or_default().to_string();
|
||||
run(&mut s, "parameters.change", json!({"name": d, "expression": "h"}));
|
||||
let r = run(&mut s, "parameters.change", json!({"changes": {"len": "100 mm", "h": 20}}));
|
||||
assert_eq!(r["errors"].as_array().map(Vec::len), Some(0), "{r}");
|
||||
assert_eq!(r["changed"]["len"], 100.0, "{r}");
|
||||
assert!(rel(volume(&mut s), 40.0 * 50.0 * 20.0) < 1e-9);
|
||||
// All or nothing: an unknown name or a broken expression changes nothing.
|
||||
assert!(err(&mut s, "parameters.change", json!({"changes": {"len": "60 mm", "nope": "1 mm"}})).contains("nope"));
|
||||
assert!(s.execute("parameters.change", &json!({"changes": {"len": "60 mm", "h": "1 / 0"}})).is_err());
|
||||
assert!(s.execute("parameters.change", &json!({"changes": {}})).is_err());
|
||||
assert_eq!(expr_of(&mut s, "len"), "100 mm");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!((expr_of(&mut s, "len"), expr_of(&mut s, "h")), ("60 mm".to_string(), "10 mm".to_string()));
|
||||
assert!(rel(volume(&mut s), 40.0 * 30.0 * 10.0) < 1e-9);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user