Skip to content

Optimize node_swap#735

Merged
maximelucas merged 2 commits into
devfrom
fix_642
Jun 1, 2026
Merged

Optimize node_swap#735
maximelucas merged 2 commits into
devfrom
fix_642

Conversation

@maximelucas

Copy link
Copy Markdown
Collaborator

Optimize node_swap by replacing the three-loop temp-ID swap with a single-pass dictionary mapping. Closes #642

Old approach: used a temporary node ID to swap in three sequential passes — replace nid1 → temp, then nid2 → nid1, then temp → nid2 — plus a deepcopy of the full edge dict.

New approach: builds a {nid1: nid2, nid2: nid1} mapping and remaps each edge's members in a single dict comprehension. Handles the edge case where both nodes appear in the same edge correctly (the swap is applied
atomically per member, leaving the set unchanged). Removes the id_temp parameter and the deepcopy import entirely.

Timing

Single swap on an xgi.random_hypergraph averaged over runs.

nodes edges before (ms) after (ms) speedup
50 324 3.13 2.08 1.51x
200 7 533 70.69 46.71 1.51x
500 24 396 248.70 160.23 1.55x
1 000 93 195 958.04 643.82 1.49x

The ~1.5x speedup is consistent across sizes.

Tests

Added some tests for uncovered cases.

@review-notebook-app

Copy link
Copy Markdown

Check out this pull request on  ReviewNB

See visual diffs & provide feedback on Jupyter Notebooks.


Powered by ReviewNB

@maximelucas maximelucas changed the base branch from main to dev May 31, 2026 15:09

@leotrs leotrs left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice cleanup Max. The dict-mapping comprehension is much easier to read than the three-pass temp-ID swap, the deepcopy goes away, and the new tests cover the previously implicit edge cases (self-inverse on both-in-one-edge, original-not-mutated, attribute preservation).

One thing worth flagging: removing the id_temp parameter is a backward-incompatible change. Anyone passing node_swap(H, a, b, id_temp=...) will get a TypeError. The arg was always implementation-detail leakage so dropping it is the right call, but worth mentioning in the changelog so it's an intentional v1.0 break rather than a silent one.

@maximelucas maximelucas merged commit 10d3bd7 into dev Jun 1, 2026
2 checks passed
@maximelucas maximelucas deleted the fix_642 branch June 1, 2026 19:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

make node_swap faster

2 participants