Axis permutation to correctly handle cycles using bitmask approach #1505
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_axes
andreversed_axes
).As mentioned from related issue, they're not
in-place
, so I addedpermute_axes
andreverse_axes
. The new implementation forpermute_axes
uses 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 self
Details on permute_axes
How it works
The new implementation uses a bitmask to track visited axes during permutation cycles:
usize
is 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_axes
andreversed_axes
), but there might be missing cases. please take a look when you guys have some time! 🚀