| 1 | """ |
| 2 | Hilbert Order |
| 3 | Modified from https://github.com/PrincetonLIPS/numpy-hilbert-curve |
| 4 | |
| 5 | Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com), Kaixin Xu |
| 6 | Please cite our work if the code is helpful to you. |
| 7 | """ |
| 8 | |
| 9 | import torch |
| 10 | |
| 11 | |
| 12 | def right_shift(binary, k=1, axis=-1): |
| 13 | """Right shift an array of binary values. |
| 14 | |
| 15 | Parameters: |
| 16 | ----------- |
| 17 | binary: An ndarray of binary values. |
| 18 | |
| 19 | k: The number of bits to shift. Default 1. |
| 20 | |
| 21 | axis: The axis along which to shift. Default -1. |
| 22 | |
| 23 | Returns: |
| 24 | -------- |
| 25 | Returns an ndarray with zero prepended and the ends truncated, along |
| 26 | whatever axis was specified.""" |
| 27 | |
| 28 | # If we're shifting the whole thing, just return zeros. |
| 29 | if binary.shape[axis] <= k: |
| 30 | return torch.zeros_like(binary) |
| 31 | |
| 32 | # Determine the padding pattern. |
| 33 | # padding = [(0,0)] * len(binary.shape) |
| 34 | # padding[axis] = (k,0) |
| 35 | |
| 36 | # Determine the slicing pattern to eliminate just the last one. |
| 37 | slicing = [slice(None)] * len(binary.shape) |
| 38 | slicing[axis] = slice(None, -k) |
| 39 | shifted = torch.nn.functional.pad( |
| 40 | binary[tuple(slicing)], (k, 0), mode="constant", value=0 |
| 41 | ) |
| 42 | |
| 43 | return shifted |
| 44 | |
| 45 | |
| 46 | def binary2gray(binary, axis=-1): |
| 47 | """Convert an array of binary values into Gray codes. |
| 48 | |
| 49 | This uses the classic X ^ (X >> 1) trick to compute the Gray code. |
| 50 | |
| 51 | Parameters: |
| 52 | ----------- |
| 53 | binary: An ndarray of binary values. |
| 54 | |
| 55 | axis: The axis along which to compute the gray code. Default=-1. |
| 56 | |
| 57 | Returns: |
| 58 | -------- |
| 59 | Returns an ndarray of Gray codes. |
| 60 | """ |
| 61 | shifted = right_shift(binary, axis=axis) |
| 62 | |
| 63 | # Do the X ^ (X >> 1) trick. |
| 64 | gray = torch.logical_xor(binary, shifted) |
| 65 | |
| 66 | return gray |
| 67 | |
| 68 | |
| 69 | def gray2binary(gray, axis=-1): |
| 70 | """Convert an array of Gray codes back into binary values. |
| 71 | |
| 72 | Parameters: |
| 73 | ----------- |
| 74 | gray: An ndarray of gray codes. |
| 75 | |
| 76 | axis: The axis along which to perform Gray decoding. Default=-1. |
| 77 | |
| 78 | Returns: |
| 79 | -------- |
| 80 | Returns an ndarray of binary values. |
| 81 | """ |
| 82 | |
| 83 | # Loop the log2(bits) number of times necessary, with shift and xor. |
| 84 | shift = 2 ** (torch.Tensor([gray.shape[axis]]).log2().ceil().int() - 1) |
| 85 | while shift > 0: |
| 86 | gray = torch.logical_xor(gray, right_shift(gray, shift)) |
| 87 | shift = torch.div(shift, 2, rounding_mode="floor") |
| 88 | return gray |
| 89 | |
| 90 | |
| 91 | def encode(locs, num_dims, num_bits): |
| 92 | """Decode an array of locations in a hypercube into a Hilbert integer. |
| 93 | |
| 94 | This is a vectorized-ish version of the Hilbert curve implementation by John |
| 95 | Skilling as described in: |
| 96 | |
| 97 | Skilling, J. (2004, April). Programming the Hilbert curve. In AIP Conference |
| 98 | Proceedings (Vol. 707, No. 1, pp. 381-387). American Institute of Physics. |
| 99 | |
| 100 | Params: |
| 101 | ------- |
| 102 | locs - An ndarray of locations in a hypercube of num_dims dimensions, in |
| 103 | which each dimension runs from 0 to 2**num_bits-1. The shape can |
| 104 | be arbitrary, as long as the last dimension of the same has size |
| 105 | num_dims. |
| 106 | |
| 107 | num_dims - The dimensionality of the hypercube. Integer. |
| 108 | |
| 109 | num_bits - The number of bits for each dimension. Integer. |
| 110 | |
| 111 | Returns: |
| 112 | -------- |
| 113 | The output is an ndarray of uint64 integers with the same shape as the |
| 114 | input, excluding the last dimension, which needs to be num_dims. |
| 115 | """ |
| 116 | |
| 117 | # Keep around the original shape for later. |
| 118 | orig_shape = locs.shape |
| 119 | bitpack_mask = 1 << torch.arange(0, 8).to(locs.device) |
| 120 | bitpack_mask_rev = bitpack_mask.flip(-1) |
| 121 | |
| 122 | if orig_shape[-1] != num_dims: |
| 123 | raise ValueError( |
| 124 | """ |
| 125 | The shape of locs was surprising in that the last dimension was of size |
| 126 | %d, but num_dims=%d. These need to be equal. |
| 127 | """ |
| 128 | % (orig_shape[-1], num_dims) |
| 129 | ) |
| 130 | |
| 131 | if num_dims * num_bits > 63: |
| 132 | raise ValueError( |
| 133 | """ |
| 134 | num_dims=%d and num_bits=%d for %d bits total, which can't be encoded |
| 135 | into a int64. Are you sure you need that many points on your Hilbert |
| 136 | curve? |
| 137 | """ |
| 138 | % (num_dims, num_bits, num_dims * num_bits) |
| 139 | ) |
| 140 | |
| 141 | # Treat the location integers as 64-bit unsigned and then split them up into |
| 142 | # a sequence of uint8s. Preserve the association by dimension. |
| 143 | locs_uint8 = locs.long().view(torch.uint8).reshape((-1, num_dims, 8)).flip(-1) |
| 144 | |
| 145 | # Now turn these into bits and truncate to num_bits. |
| 146 | gray = ( |
| 147 | locs_uint8.unsqueeze(-1) |
| 148 | .bitwise_and(bitpack_mask_rev) |
| 149 | .ne(0) |
| 150 | .byte() |
| 151 | .flatten(-2, -1)[..., -num_bits:] |
| 152 | ) |
| 153 | |
| 154 | # Run the decoding process the other way. |
| 155 | # Iterate forwards through the bits. |
| 156 | for bit in range(0, num_bits): |
| 157 | # Iterate forwards through the dimensions. |
| 158 | for dim in range(0, num_dims): |
| 159 | # Identify which ones have this bit active. |
| 160 | mask = gray[:, dim, bit] |
| 161 | |
| 162 | # Where this bit is on, invert the 0 dimension for lower bits. |
| 163 | gray[:, 0, bit + 1 :] = torch.logical_xor( |
| 164 | gray[:, 0, bit + 1 :], mask[:, None] |
| 165 | ) |
| 166 | |
| 167 | # Where the bit is off, exchange the lower bits with the 0 dimension. |
| 168 | to_flip = torch.logical_and( |
| 169 | torch.logical_not(mask[:, None]).repeat(1, gray.shape[2] - bit - 1), |
| 170 | torch.logical_xor(gray[:, 0, bit + 1 :], gray[:, dim, bit + 1 :]), |
| 171 | ) |
| 172 | gray[:, dim, bit + 1 :] = torch.logical_xor( |
| 173 | gray[:, dim, bit + 1 :], to_flip |
| 174 | ) |
| 175 | gray[:, 0, bit + 1 :] = torch.logical_xor(gray[:, 0, bit + 1 :], to_flip) |
| 176 | |
| 177 | # Now flatten out. |
| 178 | gray = gray.swapaxes(1, 2).reshape((-1, num_bits * num_dims)) |
| 179 | |
| 180 | # Convert Gray back to binary. |
| 181 | hh_bin = gray2binary(gray) |
| 182 | |
| 183 | # Pad back out to 64 bits. |
| 184 | extra_dims = 64 - num_bits * num_dims |
| 185 | padded = torch.nn.functional.pad(hh_bin, (extra_dims, 0), "constant", 0) |
| 186 | |
| 187 | # Convert binary values into uint8s. |
| 188 | hh_uint8 = ( |
| 189 | (padded.flip(-1).reshape((-1, 8, 8)) * bitpack_mask) |
| 190 | .sum(2) |
| 191 | .squeeze() |
| 192 | .type(torch.uint8) |
| 193 | ) |
| 194 | |
| 195 | # Convert uint8s into uint64s. |
| 196 | hh_uint64 = hh_uint8.view(torch.int64).squeeze() |
| 197 | |
| 198 | return hh_uint64 |
| 199 | |
| 200 | |
| 201 | def decode(hilberts, num_dims, num_bits): |
| 202 | """Decode an array of Hilbert integers into locations in a hypercube. |
| 203 | |
| 204 | This is a vectorized-ish version of the Hilbert curve implementation by John |
| 205 | Skilling as described in: |
| 206 | |
| 207 | Skilling, J. (2004, April). Programming the Hilbert curve. In AIP Conference |
| 208 | Proceedings (Vol. 707, No. 1, pp. 381-387). American Institute of Physics. |
| 209 | |
| 210 | Params: |
| 211 | ------- |
| 212 | hilberts - An ndarray of Hilbert integers. Must be an integer dtype and |
| 213 | cannot have fewer bits than num_dims * num_bits. |
| 214 | |
| 215 | num_dims - The dimensionality of the hypercube. Integer. |
| 216 | |
| 217 | num_bits - The number of bits for each dimension. Integer. |
| 218 | |
| 219 | Returns: |
| 220 | -------- |
| 221 | The output is an ndarray of unsigned integers with the same shape as hilberts |
| 222 | but with an additional dimension of size num_dims. |
| 223 | """ |
| 224 | |
| 225 | if num_dims * num_bits > 64: |
| 226 | raise ValueError( |
| 227 | """ |
| 228 | num_dims=%d and num_bits=%d for %d bits total, which can't be encoded |
| 229 | into a uint64. Are you sure you need that many points on your Hilbert |
| 230 | curve? |
| 231 | """ |
| 232 | % (num_dims, num_bits) |
| 233 | ) |
| 234 | |
| 235 | # Handle the case where we got handed a naked integer. |
| 236 | hilberts = torch.atleast_1d(hilberts) |
| 237 | |
| 238 | # Keep around the shape for later. |
| 239 | orig_shape = hilberts.shape |
| 240 | bitpack_mask = 2 ** torch.arange(0, 8).to(hilberts.device) |
| 241 | bitpack_mask_rev = bitpack_mask.flip(-1) |
| 242 | |
| 243 | # Treat each of the hilberts as a s equence of eight uint8. |
| 244 | # This treats all of the inputs as uint64 and makes things uniform. |
| 245 | hh_uint8 = ( |
| 246 | hilberts.ravel().type(torch.int64).view(torch.uint8).reshape((-1, 8)).flip(-1) |
| 247 | ) |
| 248 | |
| 249 | # Turn these lists of uints into lists of bits and then truncate to the size |
| 250 | # we actually need for using Skilling's procedure. |
| 251 | hh_bits = ( |
| 252 | hh_uint8.unsqueeze(-1) |
| 253 | .bitwise_and(bitpack_mask_rev) |
| 254 | .ne(0) |
| 255 | .byte() |
| 256 | .flatten(-2, -1)[:, -num_dims * num_bits :] |
| 257 | ) |
| 258 | |
| 259 | # Take the sequence of bits and Gray-code it. |
| 260 | gray = binary2gray(hh_bits) |
| 261 | |
| 262 | # There has got to be a better way to do this. |
| 263 | # I could index them differently, but the eventual packbits likes it this way. |
| 264 | gray = gray.reshape((-1, num_bits, num_dims)).swapaxes(1, 2) |
| 265 | |
| 266 | # Iterate backwards through the bits. |
| 267 | for bit in range(num_bits - 1, -1, -1): |
| 268 | # Iterate backwards through the dimensions. |
| 269 | for dim in range(num_dims - 1, -1, -1): |
| 270 | # Identify which ones have this bit active. |
| 271 | mask = gray[:, dim, bit] |
| 272 | |
| 273 | # Where this bit is on, invert the 0 dimension for lower bits. |
| 274 | gray[:, 0, bit + 1 :] = torch.logical_xor( |
| 275 | gray[:, 0, bit + 1 :], mask[:, None] |
| 276 | ) |
| 277 | |
| 278 | # Where the bit is off, exchange the lower bits with the 0 dimension. |
| 279 | to_flip = torch.logical_and( |
| 280 | torch.logical_not(mask[:, None]), |
| 281 | torch.logical_xor(gray[:, 0, bit + 1 :], gray[:, dim, bit + 1 :]), |
| 282 | ) |
| 283 | gray[:, dim, bit + 1 :] = torch.logical_xor( |
| 284 | gray[:, dim, bit + 1 :], to_flip |
| 285 | ) |
| 286 | gray[:, 0, bit + 1 :] = torch.logical_xor(gray[:, 0, bit + 1 :], to_flip) |
| 287 | |
| 288 | # Pad back out to 64 bits. |
| 289 | extra_dims = 64 - num_bits |
| 290 | padded = torch.nn.functional.pad(gray, (extra_dims, 0), "constant", 0) |
| 291 | |
| 292 | # Now chop these up into blocks of 8. |
| 293 | locs_chopped = padded.flip(-1).reshape((-1, num_dims, 8, 8)) |
| 294 | |
| 295 | # Take those blocks and turn them unto uint8s. |
| 296 | # from IPython import embed; embed() |
| 297 | locs_uint8 = (locs_chopped * bitpack_mask).sum(3).squeeze().type(torch.uint8) |
| 298 | |
| 299 | # Finally, treat these as uint64s. |
| 300 | flat_locs = locs_uint8.view(torch.int64) |
| 301 | |
| 302 | # Return them in the expected shape. |
| 303 | return flat_locs.reshape((*orig_shape, num_dims)) |