Fix graph topology back-edge cycles preventing correct parallel resistance calculations #3
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #2. The graph-to-expression builder was producing incorrect topology with back-edge cycles like
5:6and6:5, which collapsed parallel branches and yielded wrong equivalent values (e.g., 500 Ω instead of 333.333… for three 1k resistors in parallel).Problem
The original
buildPathmethod inscripts/graph.jscould create bidirectional edges in the GraphNode structure, leading to cycles that incorrectly merged parallel branches during expression generation. This resulted in:Solution
This change implements BFS distance-guided edge selection and cycle prevention while preserving the existing
mergeNodesand AST logic:Key Changes
Added
_computeDistances(src)method: Performs BFS to compute distances from any node to all reachable nodes in the merged-node undirected graphEnhanced
toString()method: Now computes distance maps (_distEndand_distStart) once at the beginning to guide GraphNode constructionUpdated
buildPath()method: Added distance-guided filtering that keeps edges if they either:reducesEnd), ORmovesAwayStart)Added
_gnReachable()helper: Prevents GraphNode cycles by checking reachability before adding edgesExample Fix in Action
Before: Risk of cycles disrupting parallel analysis
After: Clean unidirectional topology
Validation
Tested with complex circuit containing 11 resistors and multiple parallel branches:
1k + ((1k + 1k) // (1k + 1k)) + ((1k + ((1k + 0) // (1k + 0)) + 0) // (1k + ((1k + 0) // (1k + 0)) + 0)) + 0Implementation Notes
mergeNodeslogic unchanged as specifiedThe fix ensures that parallel branches like three 1k resistors now correctly yield 333.333Ω equivalent resistance instead of incorrect values caused by topology cycles.
This pull request was created as a result of the following prompt from Copilot chat.
✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.