Axis permutation to correctly handle cycles using bitmask approach#1505
Merged
akern40 merged 7 commits intorust-ndarray:masterfrom May 21, 2025
Merged
Conversation
nilgoyette
reviewed
Apr 23, 2025
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Overview
What's up! 😃 Currently, there're two functions to deal with permuting and reversing arrays(
permuted_axesandreversed_axes).As mentioned from related issue, they're not
in-place, so I addedpermute_axesandreverse_axes. The new implementation forpermute_axesuses a bitmask-based approach to efficiently track and process cycles in axis permutations!Related issue
Changes
permute_axes (in-place):
reverse_axes (in-place):
&mut selfDetails on permute_axes
How it works
The new implementation uses a bitmask to track visited axes during permutation cycles:
usizeis used as a bitmask to efficiently track which axes have been processed.Example
Consider permuting a 2×2 array from
[[1, 2], [3, 4]]with axes permutation[1, 0](transpose):Here's how the algorithm processes this:
Start with axis 1 (new_axis=0):
Process axis 0 (new_axis=1):
The bitmask approach ensures each axis is processed exactly once, even in complex permutations with multiple cycles. The key operations are:
visited |= 1 << axis: Mark axis as visited(visited & (1 << axis)) != 0: Check if axis is visited@akern40 @nilgoyette added test cases similar to the original functions(
premuted_axesandreversed_axes), but there might be missing cases. please take a look when you guys have some time! 🚀