Curvature regulators #80

Merged
glen merged 21 commits from Vectornaut/dyna3:curvature-regulators into main 2025-04-21 23:40:43 +00:00
3 changed files with 35 additions and 38 deletions
Showing only changes of commit 00f60b0e90 - Show all commits

View file

@ -188,11 +188,16 @@ pub fn AddRemove() -> View {
}, },
on:click=|_| { on:click=|_| {
let state = use_context::<AppState>(); let state = use_context::<AppState>();
let subjects = state.selection.with( let subjects: [_; 2] = state.selection.with(
|sel| { // the button is only enabled when two elements are
let subject_vec: Vec<_> = sel.into_iter().collect(); // selected, so we know the cast to a two-element array
(subject_vec[0].clone(), subject_vec[1].clone()) // will succeed
} |sel| sel
.clone()
.into_iter()
.collect::<Vec<_>>()
.try_into()
.unwrap()
); );
state.assembly.insert_new_regulator(subjects); state.assembly.insert_new_regulator(subjects);
state.selection.update(|sel| sel.clear()); state.selection.update(|sel| sel.clear());

View file

@ -134,7 +134,7 @@ impl Element {
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub struct ProductRegulator { pub struct ProductRegulator {
pub subjects: (ElementKey, ElementKey), pub subjects: [ElementKey; 2],
glen marked this conversation as resolved Outdated

The check here and the potential panic if it fails (and analogous code in two other ProblemPoser implementations) is evidence of misfactoring: in fact, the ProblemPosers only ever get to execute when every element has just been assigned a column index. So there is no need to have such a check.

I am open to any reasonable way to factor these checks out. One is to insist that all elements in an assembly always have a column index. As far as I can see, the only thing that None column indices are currently used for is a transient period between an Element being added to an Assembly and the next call to that Assembly being realized. That period could be eliminated by simply assigning each Element the next available column index and immediately calling realize. Or there could be a method (likely in engine?) that takes a realized assembly and a new completely unconstrained element and updates the realization to include the unconstrained element -- that should presumably be far less work than a full call to realize. As far as I can tell, the only consistency bit that needs to be kept up is the tangent space bases in the realization. But I suppose it should be possible to calculate the new tangent space basis matriceso directly in the case of a new unconstrained element added to a realized assembly.

Or we can insist that elements always have an index by assigning indices on creation, and dropping the invariant that an element with an index has to have tangent motions in the corresponding column of the tangent space basis matrices. That might not be so terrible -- if an element's column is out of range for the tangent space basis matrices, that must mean it is totally unconstrained, and so we can actually deform it freely, and so just switch to simpler deformation code for that case.

Another possibility is to initially use column index -1 for a new element, and not worry about any -1s in the problem posing because the code is structured such that they never occur when a problem is being posed; we only need to worry about the -1s when deforming, and handle the case there.

Another possibility (if I understand Rust and the Option type properly) is to simply use unwrap in these posers. It nominally could panic, but we know it won't because problems are only posed just after every element has been assigned an index. This route seems the least satisfying because we still have all of the baggage of Option even though the other possibilities make it clear that Option isn't filling a particularly critical need for the column indices of elements. But this route also might be the path of least resistance, so I'm OK if that's the way you want to go here.

Or there might be some other mechanism whereby the data structure passed to a problem poser is something of a slightly different type that definitely has a column for each element. (Perhaps this mild redundant-checking issue is even evidence that elements shouldn't store their column indices; conceptually, a column index is more of a property of an Element as a part of an Assembly, rather than intrinsically of the Element itself. So maybe instead the Assembly has some record of the column index for each Element, where the indices are plain ol' integers, and that record is provided to problem posers. But I am definitely not mandating a refactor of that scope as part of this PR.)

What doesn't seem good is writing out checks and manual panic messages in three places, for panics that can literally never occur because of the structure of the code. That redundant checking is what I mean by "evidence of misfactoring".

The check here and the potential panic if it fails (and analogous code in two other ProblemPoser implementations) is evidence of misfactoring: in fact, the ProblemPosers only ever get to execute when every element has just been assigned a column index. So there is no need to have such a check. I am open to any reasonable way to factor these checks out. One is to insist that all elements in an assembly always have a column index. As far as I can see, the only thing that None column indices are currently used for is a transient period between an Element being added to an Assembly and the next call to that Assembly being realized. That period could be eliminated by simply assigning each Element the next available column index and immediately calling realize. Or there could be a method (likely in engine?) that takes a realized assembly and a new completely unconstrained element and updates the realization to include the unconstrained element -- that should presumably be far less work than a full call to realize. As far as I can tell, the only consistency bit that needs to be kept up is the tangent space bases in the realization. But I suppose it should be possible to calculate the new tangent space basis matriceso directly in the case of a new unconstrained element added to a realized assembly. Or we can insist that elements always have an index by assigning indices on creation, and dropping the invariant that an element with an index has to have tangent motions in the corresponding column of the tangent space basis matrices. That might not be so terrible -- if an element's column is out of range for the tangent space basis matrices, that must mean it is totally unconstrained, and so we can actually deform it freely, and so just switch to simpler deformation code for that case. Another possibility is to initially use column index -1 for a new element, and not worry about any -1s in the problem posing because the code is structured such that they never occur when a problem is being posed; we only need to worry about the -1s when deforming, and handle the case there. Another possibility (if I understand Rust and the Option type properly) is to simply use unwrap in these posers. It nominally could panic, but we know it won't because problems are only posed just after every element has been assigned an index. This route seems the least satisfying because we still have all of the baggage of Option even though the other possibilities make it clear that Option isn't filling a particularly critical need for the column indices of elements. But this route also might be the path of least resistance, so I'm OK if that's the way you want to go here. Or there might be some other mechanism whereby the data structure passed to a problem poser is something of a slightly different type that definitely has a column for each element. (Perhaps this mild redundant-checking issue is even evidence that elements shouldn't store their column indices; conceptually, a column index is more of a property of an Element as a part of an Assembly, rather than intrinsically of the Element itself. So maybe instead the Assembly has some record of the column index for each Element, where the indices are plain ol' integers, and that record is provided to problem posers. But I am definitely not mandating a refactor of that scope as part of this PR.) What doesn't seem good is writing out checks and manual panic messages in three places, for panics that can literally never occur because of the structure of the code. That redundant checking is what I mean by "evidence of misfactoring".

I think there are two problems here—a narrow one that falls within the scope of this pull request, and a broader one that deserves its own pull request.

Narrow: semantics issue

The conditional panic doesn't do a great job of communicating that we expect every element to have a column index when pose is called. Unwrapping the Option, as you point out, has the semantics we want, and that's what we do on the main branch (commit b86f176). However, unwrapping doesn't provide an informative panic message, which would make it harder to debug an invariant violation.

I've switched to the expect method, which has the same semantics, and allows us to provide our own panic message (commit 5eeb093). I've also rewritten the panic messages in the style recommended by the expect documentation.

Broad: factoring issue

I agree that we should eventually rewrite the column index system to avoid these checks entirely. I think that deserves its own pull request, since this pull request didn't create and doesn't modify the column index system.

I think there are two problems here—a narrow one that falls within the scope of this pull request, and a broader one that deserves its own pull request. #### Narrow: semantics issue The conditional panic doesn't do a great job of communicating that we expect every element to have a column index when `pose` is called. Unwrapping the `Option`, as you point out, has the semantics we want, and that's what we do on the main branch (commit b86f176). However, unwrapping doesn't provide an informative panic message, which would make it harder to debug an invariant violation. I've switched to the [`expect`](https://doc.rust-lang.org/std/option/enum.Option.html#method.expect) method, which has the same semantics, and allows us to provide our own panic message (commit 5eeb093). I've also rewritten the panic messages in the [style recommended](https://doc.rust-lang.org/std/option/enum.Option.html#recommended-message-style) by the `expect` documentation. #### Broad: factoring issue I agree that we should eventually rewrite the column index system to avoid these checks entirely. I think that deserves its own pull request, since this pull request didn't create and doesn't modify the column index system.
pub measurement: ReadSignal<f64>, pub measurement: ReadSignal<f64>,
pub set_point: Signal<SpecifiedValue> pub set_point: Signal<SpecifiedValue>
} }
@ -143,12 +143,10 @@ impl ProductRegulator {
fn write_to_problem(&self, problem: &mut ConstraintProblem, elts: &Slab<Element>) { fn write_to_problem(&self, problem: &mut ConstraintProblem, elts: &Slab<Element>) {
self.set_point.with_untracked(|set_pt| { self.set_point.with_untracked(|set_pt| {
if let Some(val) = set_pt.value { if let Some(val) = set_pt.value {
let subjects = self.subjects; let subject_column_indices = self.subjects.map(
let subject_column_indices = ( |subj| elts[subj].column_index
elts[subjects.0].column_index,
elts[subjects.1].column_index
); );
if let (Some(row), Some(col)) = subject_column_indices { if let [Some(row), Some(col)] = subject_column_indices {
problem.gram.push_sym(row, col, val); problem.gram.push_sym(row, col, val);
} else { } else {
panic!("Tried to write problem data from a regulator with an unindexed subject"); panic!("Tried to write problem data from a regulator with an unindexed subject");
@ -246,21 +244,23 @@ impl Assembly {
let subjects = regulator.subjects; let subjects = regulator.subjects;
let key = self.regulators.update(|regs| regs.insert(regulator)); let key = self.regulators.update(|regs| regs.insert(regulator));
let subject_regulators = self.elements.with( let subject_regulators = self.elements.with(
|elts| (elts[subjects.0].regulators, elts[subjects.1].regulators) |elts| subjects.map(|subj| elts[subj].regulators)
); );
subject_regulators.0.update(|regs| regs.insert(key)); for regulators in subject_regulators {
subject_regulators.1.update(|regs| regs.insert(key)); regulators.update(|regs| regs.insert(key));
}
} }
pub fn insert_new_regulator(self, subjects: (ElementKey, ElementKey)) { pub fn insert_new_regulator(self, subjects: [ElementKey; 2]) {
// create and insert a new regulator // create and insert a new regulator
let measurement = self.elements.map( let measurement = self.elements.map(
move |elts| { move |elts| {
let reps = ( let representations = subjects.map(|subj| elts[subj].representation);
elts[subjects.0].representation.get_clone(), representations[0].with(|rep_0|
elts[subjects.1].representation.get_clone() representations[1].with(|rep_1|
); rep_0.dot(&(&*Q * rep_1))
reps.0.dot(&(&*Q * reps.1)) )
)
} }
); );
let set_point = create_signal(SpecifiedValue::from_empty_spec()); let set_point = create_signal(SpecifiedValue::from_empty_spec());
@ -277,8 +277,8 @@ impl Assembly {
for (_, reg) in regs.into_iter() { for (_, reg) in regs.into_iter() {
console::log_5( console::log_5(
&JsValue::from(" "), &JsValue::from(" "),
&JsValue::from(reg.subjects.0), &JsValue::from(reg.subjects[0]),
&JsValue::from(reg.subjects.1), &JsValue::from(reg.subjects[1]),
&JsValue::from(":"), &JsValue::from(":"),
&reg.set_point.with_untracked( &reg.set_point.with_untracked(
|set_pt| JsValue::from(set_pt.spec.as_str()) |set_pt| JsValue::from(set_pt.spec.as_str())
@ -502,25 +502,17 @@ mod tests {
fn unindexed_subject_test() { fn unindexed_subject_test() {
let _ = create_root(|| { let _ = create_root(|| {
let mut elts = Slab::new(); let mut elts = Slab::new();
let subjects = ( let subjects = [0, 1].map(|k| {
elts.insert( elts.insert(
Element::new( Element::new(
"sphere0".to_string(), "sphere{k}".to_string(),
"Sphere 0".to_string(), "Sphere {k}".to_string(),
[1.0_f32, 1.0_f32, 1.0_f32],
engine::sphere(0.0, 0.0, 0.0, 1.0)
)
),
elts.insert(
Element::new(
"sphere1".to_string(),
"Sphere 1".to_string(),
[1.0_f32, 1.0_f32, 1.0_f32], [1.0_f32, 1.0_f32, 1.0_f32],
engine::sphere(0.0, 0.0, 0.0, 1.0) engine::sphere(0.0, 0.0, 0.0, 1.0)
) )
) )
); });
elts[subjects.0].column_index = Some(0); elts[subjects[0]].column_index = Some(0);
ProductRegulator { ProductRegulator {
subjects: subjects, subjects: subjects,
measurement: create_memo(|| 0.0), measurement: create_memo(|| 0.0),

View file

@ -81,10 +81,10 @@ fn RegulatorOutlineItem(regulator_key: RegulatorKey, element_key: ElementKey) ->
let state = use_context::<AppState>(); let state = use_context::<AppState>();
let assembly = &state.assembly; let assembly = &state.assembly;
let regulator = assembly.regulators.with(|regs| regs[regulator_key]); let regulator = assembly.regulators.with(|regs| regs[regulator_key]);
let other_subject = if regulator.subjects.0 == element_key { let other_subject = if regulator.subjects[0] == element_key {
regulator.subjects.1 regulator.subjects[1]
} else { } else {
regulator.subjects.0 regulator.subjects[0]
}; };
let other_subject_label = assembly.elements.with(|elts| elts[other_subject].label.clone()); let other_subject_label = assembly.elements.with(|elts| elts[other_subject].label.clone());
view! { view! {