Fix KeyError when solving after insert_node (non-contiguous element ids) (#308)#443
Conversation
insert_node() removes the split element and appends two new ones, leaving
element_map with non-contiguous keys (e.g. {1, 3, 4}). assemble_system_matrix
iterated 'for i in range(len(element_map)): element_map[i + 1]', which assumed
ids 1..N and raised KeyError during validation/solve. Iterate over
element_map.values() instead; assembly is an order-independent accumulation
into the system matrix indexed by node id, so this is equivalent for the
contiguous case and correct when ids have gaps.
Fixes anastruct#308
|
Thank you so much for contributing to the open-source anaStruct project! Your contribution will help thousands of engineers work more efficiently and accuractely. Now that you've created your first pull request here, please don't go away; take a look at the bottom of this page for the automated checks that should already be running. If they pass, great! If not, please click on 'Details' and see if you can fix the problem they've identified. Keep in mind that this repository uses the |
brookshsmith
left a comment
There was a problem hiding this comment.
Thank you @gaoflow for your PR here as well! Again, a simple but needed fix and you've added a good test too. Merged.
Summary
Fixes #308.
insert_node()splits an element by appending two new elements and then removing the original viaremove_element(). This leavessystem.element_mapwith non-contiguous keys — e.g. after inserting a node into element 2 of a 2-element model, the map holds{1, 3, 4}.assemble_system_matrixiterated positionally:which assumes the ids are exactly
1..N. With a gap,element_map[2]no longer exists and validation/solving raisesKeyError: 2.This positional assumption is isolated to this one loop — everywhere else in the codebase indexes
element_mapby an actual element id, andadd_elementassigns ids from a monotonic counter that is never reused.Fix
Iterate over the elements directly:
Assembly is an order-independent accumulation into the global system matrix indexed by node id, so this is identical to the old behaviour for the contiguous case and correct when ids have gaps.
Reproduction (raises on
master)Verification
context_insert_node_then_solvereproduces the issue and additionally asserts the solved result is numerically identical to the equivalent model built with the extra node defined up front (same displacements at every shared node). It raisesKeyError: 2onmasterand passes with this change.test_plotterfailures —'Plotter' object has no attribute 'plot_structure'— are unrelated to this change and fail identically onmaster).blackandmypyclean on the changed files.Note
This supersedes #309 (from the issue reporter @thisisapple), which proposed the same
element_map.values()idea but contains a syntax error (forkeyword dropped) and no test. Credit to them for the original diagnosis.