@@ -1452,7 +1452,7 @@ def make_slice_selection(selection: Any) -> list[slice]:
14521452def decode_morton (z : int , chunk_shape : tuple [int , ...]) -> tuple [int , ...]:
14531453 # Inspired by compressed morton code as implemented in Neuroglancer
14541454 # https://github.com/google/neuroglancer/blob/master/src/neuroglancer/datasource/precomputed/volume.md#compressed-morton-code
1455- bits = tuple (math . ceil ( math . log2 ( c ) ) for c in chunk_shape )
1455+ bits = tuple (( c - 1 ). bit_length ( ) for c in chunk_shape )
14561456 max_coords_bits = max (bits )
14571457 input_bit = 0
14581458 input_value = z
@@ -1467,21 +1467,104 @@ def decode_morton(z: int, chunk_shape: tuple[int, ...]) -> tuple[int, ...]:
14671467 return tuple (out )
14681468
14691469
1470- @lru_cache
1471- def _morton_order (chunk_shape : tuple [int , ...]) -> tuple [tuple [int , ...], ...]:
1470+ def decode_morton_vectorized (
1471+ z : npt .NDArray [np .intp ], chunk_shape : tuple [int , ...]
1472+ ) -> npt .NDArray [np .intp ]:
1473+ """Vectorized Morton code decoding for multiple z values.
1474+
1475+ Parameters
1476+ ----------
1477+ z : ndarray
1478+ 1D array of Morton codes to decode.
1479+ chunk_shape : tuple of int
1480+ Shape defining the coordinate space.
1481+
1482+ Returns
1483+ -------
1484+ ndarray
1485+ 2D array of shape (len(z), len(chunk_shape)) containing decoded coordinates.
1486+ """
1487+ n_dims = len (chunk_shape )
1488+ bits = tuple ((c - 1 ).bit_length () for c in chunk_shape )
1489+
1490+ max_coords_bits = max (bits ) if bits else 0
1491+ out = np .zeros ((len (z ), n_dims ), dtype = np .intp )
1492+
1493+ input_bit = 0
1494+ for coord_bit in range (max_coords_bits ):
1495+ for dim in range (n_dims ):
1496+ if coord_bit < bits [dim ]:
1497+ # Extract bit at position input_bit from all z values
1498+ bit_values = (z >> input_bit ) & 1
1499+ # Place bit at coord_bit position in dimension dim
1500+ out [:, dim ] |= bit_values << coord_bit
1501+ input_bit += 1
1502+
1503+ return out
1504+
1505+
1506+ @lru_cache (maxsize = 16 )
1507+ def _morton_order (chunk_shape : tuple [int , ...]) -> npt .NDArray [np .intp ]:
14721508 n_total = product (chunk_shape )
1473- order : list [tuple [int , ...]] = []
1474- i = 0
1475- while len (order ) < n_total :
1476- m = decode_morton (i , chunk_shape )
1477- if all (x < y for x , y in zip (m , chunk_shape , strict = False )):
1478- order .append (m )
1479- i += 1
1480- return tuple (order )
1509+ n_dims = len (chunk_shape )
1510+ if n_total == 0 :
1511+ out = np .empty ((0 , n_dims ), dtype = np .intp )
1512+ out .flags .writeable = False
1513+ return out
1514+
1515+ # Ceiling hypercube: smallest power-of-2 hypercube whose Morton codes span
1516+ # all valid coordinates in chunk_shape. (c-1).bit_length() gives the number
1517+ # of bits needed to index c values (0 for singleton dims). n_z = 2**total_bits
1518+ # is the size of this hypercube.
1519+ total_bits = sum ((c - 1 ).bit_length () for c in chunk_shape )
1520+ n_z = 1 << total_bits if total_bits > 0 else 1
1521+
1522+ # Decode all Morton codes in the ceiling hypercube, then filter to valid coords.
1523+ # This is fully vectorized. For shapes with n_z >> n_total (e.g. (33,33,33):
1524+ # n_z=262144, n_total=35937), consider the argsort strategy below.
1525+ order : npt .NDArray [np .intp ]
1526+ if n_z <= 4 * n_total :
1527+ # Ceiling strategy: decode all n_z codes vectorized, filter in-bounds.
1528+ # Works well when the overgeneration ratio n_z/n_total is small (≤4).
1529+ z_values = np .arange (n_z , dtype = np .intp )
1530+ all_coords = decode_morton_vectorized (z_values , chunk_shape )
1531+ shape_arr = np .array (chunk_shape , dtype = np .intp )
1532+ valid_mask = np .all (all_coords < shape_arr , axis = 1 )
1533+ order = all_coords [valid_mask ]
1534+ else :
1535+ # Argsort strategy: enumerate all n_total valid coordinates directly,
1536+ # encode each to a Morton code, then sort by code. Avoids the 8x or
1537+ # larger overgeneration penalty for near-miss shapes like (33,33,33).
1538+ # Cost: O(n_total * bits) encode + O(n_total log n_total) sort,
1539+ # vs O(n_z * bits) = O(8 * n_total * bits) for ceiling.
1540+ grids = np .meshgrid (* [np .arange (c , dtype = np .intp ) for c in chunk_shape ], indexing = "ij" )
1541+ all_coords = np .stack ([g .ravel () for g in grids ], axis = 1 )
1542+
1543+ # Encode all coordinates to Morton codes (vectorized).
1544+ bits_per_dim = tuple ((c - 1 ).bit_length () for c in chunk_shape )
1545+ max_coord_bits = max (bits_per_dim )
1546+ z_codes = np .zeros (n_total , dtype = np .intp )
1547+ output_bit = 0
1548+ for coord_bit in range (max_coord_bits ):
1549+ for dim in range (n_dims ):
1550+ if coord_bit < bits_per_dim [dim ]:
1551+ z_codes |= ((all_coords [:, dim ] >> coord_bit ) & 1 ) << output_bit
1552+ output_bit += 1
1553+
1554+ sort_idx : npt .NDArray [np .intp ] = np .argsort (z_codes , kind = "stable" )
1555+ order = np .asarray (all_coords [sort_idx ], dtype = np .intp )
1556+
1557+ order .flags .writeable = False
1558+ return order
1559+
1560+
1561+ @lru_cache (maxsize = 16 )
1562+ def _morton_order_keys (chunk_shape : tuple [int , ...]) -> tuple [tuple [int , ...], ...]:
1563+ return tuple (tuple (int (x ) for x in row ) for row in _morton_order (chunk_shape ))
14811564
14821565
14831566def morton_order_iter (chunk_shape : tuple [int , ...]) -> Iterator [tuple [int , ...]]:
1484- return iter (_morton_order (tuple (chunk_shape )))
1567+ return iter (_morton_order_keys (tuple (chunk_shape )))
14851568
14861569
14871570def c_order_iter (chunks_per_shard : tuple [int , ...]) -> Iterator [tuple [int , ...]]:
0 commit comments