|
| 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, xtensor_from_tensor |
| 13 | +from pytensor.xtensor.type import XTensorType, as_xtensor, xtensor |
| 14 | + |
| 15 | + |
| 16 | +def as_idx_variable(idx, indexed_dim: str): |
| 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 | + elif ( |
| 26 | + isinstance(idx, tuple) |
| 27 | + and len(idx) == 2 |
| 28 | + and ( |
| 29 | + isinstance(idx[0], str) |
| 30 | + or ( |
| 31 | + isinstance(idx[0], tuple | list) |
| 32 | + and all(isinstance(d, str) for d in idx[0]) |
| 33 | + ) |
| 34 | + ) |
| 35 | + ): |
| 36 | + # Special case for ("x", array) that xarray supports |
| 37 | + dim, idx = idx |
| 38 | + if isinstance(idx, Variable) and isinstance(idx.type, XTensorType): |
| 39 | + raise TypeError( |
| 40 | + "Giving a dimension name to an XTensorVariable indexer is not supported" |
| 41 | + ) |
| 42 | + if isinstance(dim, str): |
| 43 | + dims = (dim,) |
| 44 | + else: |
| 45 | + dims = tuple(dim) |
| 46 | + idx = as_xtensor(as_tensor(idx), dims=dims) |
| 47 | + else: |
| 48 | + # Must be integer indices, we already counted for None and slices |
| 49 | + try: |
| 50 | + idx = as_xtensor(idx) |
| 51 | + except TypeError: |
| 52 | + idx = as_tensor(idx) |
| 53 | + if idx.type.ndim > 1: |
| 54 | + # Same error that xarray raises |
| 55 | + raise IndexError( |
| 56 | + "Unlabeled multi-dimensional array cannot be used for indexing" |
| 57 | + ) |
| 58 | + # This is implicitly an XTensorVariable with dim matching the indexed one |
| 59 | + idx = xtensor_from_tensor(idx, dims=(indexed_dim,)[: idx.type.ndim]) |
| 60 | + |
| 61 | + if idx.type.dtype == "bool": |
| 62 | + if idx.type.ndim != 1: |
| 63 | + # xarray allaws `x[True]`, but I think it is a bug: https://github.com/pydata/xarray/issues/10379 |
| 64 | + # Otherwise, it is always restricted to 1d boolean indexing arrays |
| 65 | + raise NotImplementedError( |
| 66 | + "Only 1d boolean indexing arrays are supported" |
| 67 | + ) |
| 68 | + if idx.type.dims != (indexed_dim,): |
| 69 | + raise IndexError( |
| 70 | + "Boolean indexer should be unlabeled or on the same dimension to the indexed array. " |
| 71 | + f"Indexer is on {idx.type.dims} but the target dimension is {indexed_dim}." |
| 72 | + ) |
| 73 | + |
| 74 | + # Convert to nonzero indices |
| 75 | + idx = as_xtensor(idx.values.nonzero()[0], dims=idx.type.dims) |
| 76 | + |
| 77 | + elif idx.type.dtype not in discrete_dtypes: |
| 78 | + raise TypeError("Numerical indices must be integers or boolean") |
| 79 | + return idx |
| 80 | + |
| 81 | + |
| 82 | +def get_static_slice_length(slc: Variable, dim_length: None | int) -> int | None: |
| 83 | + if dim_length is None: |
| 84 | + return None |
| 85 | + if isinstance(slc, Constant): |
| 86 | + d = slc.data |
| 87 | + start, stop, step = d.start, d.stop, d.step |
| 88 | + elif slc.owner is None: |
| 89 | + # It's a root variable no way of knowing what we're getting |
| 90 | + return None |
| 91 | + else: |
| 92 | + # It's a MakeSliceOp |
| 93 | + start, stop, step = slc.owner.inputs |
| 94 | + if isinstance(start, Constant): |
| 95 | + start = start.data |
| 96 | + else: |
| 97 | + return None |
| 98 | + if isinstance(stop, Constant): |
| 99 | + stop = stop.data |
| 100 | + else: |
| 101 | + return None |
| 102 | + if isinstance(step, Constant): |
| 103 | + step = step.data |
| 104 | + else: |
| 105 | + return None |
| 106 | + return len(range(*slice(start, stop, step).indices(dim_length))) |
| 107 | + |
| 108 | + |
| 109 | +class Index(XOp): |
| 110 | + __props__ = () |
| 111 | + |
| 112 | + def make_node(self, x, *idxs): |
| 113 | + x = as_xtensor(x) |
| 114 | + |
| 115 | + if any(idx is Ellipsis for idx in idxs): |
| 116 | + if idxs.count(Ellipsis) > 1: |
| 117 | + raise IndexError("an index can only have a single ellipsis ('...')") |
| 118 | + # Convert intermediate Ellipsis to slice(None) |
| 119 | + ellipsis_loc = idxs.index(Ellipsis) |
| 120 | + n_implied_none_slices = x.type.ndim - (len(idxs) - 1) |
| 121 | + idxs = ( |
| 122 | + *idxs[:ellipsis_loc], |
| 123 | + *((slice(None),) * n_implied_none_slices), |
| 124 | + *idxs[ellipsis_loc + 1 :], |
| 125 | + ) |
| 126 | + |
| 127 | + x_ndim = x.type.ndim |
| 128 | + x_dims = x.type.dims |
| 129 | + x_shape = x.type.shape |
| 130 | + out_dims = [] |
| 131 | + out_shape = [] |
| 132 | + |
| 133 | + def combine_dim_info(idx_dim, idx_dim_shape): |
| 134 | + if idx_dim not in out_dims: |
| 135 | + # First information about the dimension length |
| 136 | + out_dims.append(idx_dim) |
| 137 | + out_shape.append(idx_dim_shape) |
| 138 | + else: |
| 139 | + # Dim already introduced in output by a previous index |
| 140 | + # Update static shape or raise if incompatible |
| 141 | + out_dim_pos = out_dims.index(idx_dim) |
| 142 | + out_dim_shape = out_shape[out_dim_pos] |
| 143 | + if out_dim_shape is None: |
| 144 | + # We don't know the size of the dimension yet |
| 145 | + out_shape[out_dim_pos] = idx_dim_shape |
| 146 | + elif idx_dim_shape is not None and idx_dim_shape != out_dim_shape: |
| 147 | + raise IndexError( |
| 148 | + f"Dimension of indexers mismatch for dim {idx_dim}" |
| 149 | + ) |
| 150 | + |
| 151 | + if len(idxs) > x_ndim: |
| 152 | + raise IndexError("Too many indices") |
| 153 | + |
| 154 | + idxs = [ |
| 155 | + as_idx_variable(idx, dim) for idx, dim in zip(idxs, x_dims, strict=False) |
| 156 | + ] |
| 157 | + |
| 158 | + for i, idx in enumerate(idxs): |
| 159 | + if isinstance(idx.type, SliceType): |
| 160 | + idx_dim = x_dims[i] |
| 161 | + idx_dim_shape = get_static_slice_length(idx, x_shape[i]) |
| 162 | + combine_dim_info(idx_dim, idx_dim_shape) |
| 163 | + else: |
| 164 | + if idx.type.ndim == 0: |
| 165 | + # Scalar index, dimension is dropped |
| 166 | + continue |
| 167 | + |
| 168 | + assert isinstance(idx.type, XTensorType) |
| 169 | + |
| 170 | + idx_dims = idx.type.dims |
| 171 | + for idx_dim in idx_dims: |
| 172 | + idx_dim_shape = idx.type.shape[idx_dims.index(idx_dim)] |
| 173 | + combine_dim_info(idx_dim, idx_dim_shape) |
| 174 | + |
| 175 | + for dim_i, shape_i in zip(x_dims[i + 1 :], x_shape[i + 1 :]): |
| 176 | + # Add back any unindexed dimensions |
| 177 | + if dim_i not in out_dims: |
| 178 | + # If the dimension was not indexed, we keep it as is |
| 179 | + combine_dim_info(dim_i, shape_i) |
| 180 | + |
| 181 | + output = xtensor(dtype=x.type.dtype, shape=out_shape, dims=out_dims) |
| 182 | + return Apply(self, [x, *idxs], [output]) |
| 183 | + |
| 184 | + |
| 185 | +index = Index() |
0 commit comments