|
| 1 | +# HERE LIE DRAGONS |
| 2 | +# Uselful links to make sense of all the numpy/xarray complexity |
| 3 | +# https://numpy.org/devdocs//user/basics.indexing.html |
| 4 | +# https://numpy.org/neps/nep-0021-advanced-indexing.html |
| 5 | +# https://docs.xarray.dev/en/latest/user-guide/indexing.html |
| 6 | +# https://tutorial.xarray.dev/intermediate/indexing/advanced-indexing.html |
| 7 | + |
| 8 | +from pytensor.graph.basic import Apply, Constant, Variable |
| 9 | +from pytensor.scalar.basic import discrete_dtypes |
| 10 | +from pytensor.tensor.basic import as_tensor |
| 11 | +from pytensor.tensor.type_other import NoneTypeT, SliceType, make_slice |
| 12 | +from pytensor.xtensor.basic import XOp |
| 13 | +from pytensor.xtensor.type import XTensorType, as_xtensor, xtensor |
| 14 | + |
| 15 | + |
| 16 | +def as_idx_variable(idx): |
| 17 | + if idx is None or (isinstance(idx, Variable) and isinstance(idx.type, NoneTypeT)): |
| 18 | + raise TypeError( |
| 19 | + "XTensors do not support indexing with None (np.newaxis), use expand_dims instead" |
| 20 | + ) |
| 21 | + if isinstance(idx, slice): |
| 22 | + idx = make_slice(idx) |
| 23 | + elif isinstance(idx, Variable) and isinstance(idx.type, SliceType): |
| 24 | + pass |
| 25 | + else: |
| 26 | + # Must be integer indices, we already counted for None and slices |
| 27 | + try: |
| 28 | + idx = as_tensor(idx) |
| 29 | + except TypeError: |
| 30 | + idx = as_xtensor(idx) |
| 31 | + if idx.type.dtype == "bool": |
| 32 | + raise NotImplementedError("Boolean indexing not yet supported") |
| 33 | + if idx.type.dtype not in discrete_dtypes: |
| 34 | + raise TypeError("Numerical indices must be integers or boolean") |
| 35 | + if idx.type.dtype == "bool" and idx.type.ndim == 0: |
| 36 | + # This can't be triggered right now, but will once we lift the boolean restriction |
| 37 | + raise NotImplementedError("Scalar boolean indices not supported") |
| 38 | + return idx |
| 39 | + |
| 40 | + |
| 41 | +def get_static_slice_length(slc: Variable, dim_length: None | int) -> int | None: |
| 42 | + if dim_length is None: |
| 43 | + return None |
| 44 | + if isinstance(slc, Constant): |
| 45 | + d = slc.data |
| 46 | + start, stop, step = d.start, d.stop, d.step |
| 47 | + elif slc.owner is None: |
| 48 | + # It's a root variable no way of knowing what we're getting |
| 49 | + return None |
| 50 | + else: |
| 51 | + # It's a MakeSliceOp |
| 52 | + start, stop, step = slc.owner.inputs |
| 53 | + if isinstance(start, Constant): |
| 54 | + start = start.data |
| 55 | + else: |
| 56 | + return None |
| 57 | + if isinstance(stop, Constant): |
| 58 | + stop = stop.data |
| 59 | + else: |
| 60 | + return None |
| 61 | + if isinstance(step, Constant): |
| 62 | + step = step.data |
| 63 | + else: |
| 64 | + return None |
| 65 | + return len(range(*slice(start, stop, step).indices(dim_length))) |
| 66 | + |
| 67 | + |
| 68 | +class Index(XOp): |
| 69 | + __props__ = () |
| 70 | + |
| 71 | + def make_node(self, x, *idxs): |
| 72 | + x = as_xtensor(x) |
| 73 | + idxs = [as_idx_variable(idx) for idx in idxs] |
| 74 | + |
| 75 | + x_ndim = x.type.ndim |
| 76 | + x_dims = x.type.dims |
| 77 | + x_shape = x.type.shape |
| 78 | + out_dims = [] |
| 79 | + out_shape = [] |
| 80 | + has_unlabeled_vector_idx = False |
| 81 | + has_labeled_vector_idx = False |
| 82 | + for i, idx in enumerate(idxs): |
| 83 | + if i == x_ndim: |
| 84 | + raise IndexError("Too many indices") |
| 85 | + if isinstance(idx.type, SliceType): |
| 86 | + out_dims.append(x_dims[i]) |
| 87 | + out_shape.append(get_static_slice_length(idx, x_shape[i])) |
| 88 | + elif isinstance(idx.type, XTensorType): |
| 89 | + if has_unlabeled_vector_idx: |
| 90 | + raise NotImplementedError( |
| 91 | + "Mixing of labeled and unlabeled vector indexing not implemented" |
| 92 | + ) |
| 93 | + has_labeled_vector_idx = True |
| 94 | + idx_dims = idx.type.dims |
| 95 | + for dim in idx_dims: |
| 96 | + idx_dim_shape = idx.type.shape[idx_dims.index(dim)] |
| 97 | + if dim in out_dims: |
| 98 | + # Dim already introduced in output by a previous index |
| 99 | + # Update static shape or raise if incompatible |
| 100 | + out_dim_pos = out_dims.index(dim) |
| 101 | + out_dim_shape = out_shape[out_dim_pos] |
| 102 | + if out_dim_shape is None: |
| 103 | + # We don't know the size of the dimension yet |
| 104 | + out_shape[out_dim_pos] = idx_dim_shape |
| 105 | + elif ( |
| 106 | + idx_dim_shape is not None and idx_dim_shape != out_dim_shape |
| 107 | + ): |
| 108 | + raise IndexError( |
| 109 | + f"Dimension of indexers mismatch for dim {dim}" |
| 110 | + ) |
| 111 | + else: |
| 112 | + # New dimension |
| 113 | + out_dims.append(dim) |
| 114 | + out_shape.append(idx_dim_shape) |
| 115 | + |
| 116 | + else: # TensorType |
| 117 | + if idx.type.ndim == 0: |
| 118 | + # Scalar, dimension is dropped |
| 119 | + pass |
| 120 | + elif idx.type.ndim == 1: |
| 121 | + if has_labeled_vector_idx: |
| 122 | + raise NotImplementedError( |
| 123 | + "Mixing of labeled and unlabeled vector indexing not implemented" |
| 124 | + ) |
| 125 | + has_unlabeled_vector_idx = True |
| 126 | + out_dims.append(x_dims[i]) |
| 127 | + out_shape.append(idx.type.shape[0]) |
| 128 | + else: |
| 129 | + # Same error that xarray raises |
| 130 | + raise IndexError( |
| 131 | + "Unlabeled multi-dimensional array cannot be used for indexing" |
| 132 | + ) |
| 133 | + for j in range(i + 1, x_ndim): |
| 134 | + # Add any unindexed dimensions |
| 135 | + out_dims.append(x_dims[j]) |
| 136 | + out_shape.append(x_shape[j]) |
| 137 | + |
| 138 | + output = xtensor(dtype=x.type.dtype, shape=out_shape, dims=out_dims) |
| 139 | + return Apply(self, [x, *idxs], [output]) |
| 140 | + |
| 141 | + |
| 142 | +index = Index() |
0 commit comments