|
| 1 | +from itertools import chain |
| 2 | + |
| 3 | +import pytensor.scalar as ps |
| 4 | +import pytensor.xtensor as px |
| 5 | +from pytensor.graph import Apply, Op |
| 6 | +from pytensor.tensor import TensorType |
| 7 | + |
| 8 | + |
| 9 | +class TensorFromXTensor(Op): |
| 10 | + # TODO: May need mapping of named dims to positional dims? |
| 11 | + |
| 12 | + def make_node(self, x) -> Apply: |
| 13 | + if not isinstance(x.type, px.XTensorType): |
| 14 | + raise TypeError(f"x must be have an XTensorType, got {type(x.type)}") |
| 15 | + output = TensorType(x.type.dtype, shape=x.type.shape)() |
| 16 | + return Apply(self, [x], [output]) |
| 17 | + |
| 18 | + def perform(self, node, inputs, output_storage) -> None: |
| 19 | + [x] = inputs |
| 20 | + output_storage[0][0] = x.copy() |
| 21 | + |
| 22 | + |
| 23 | +tensor_from_xtensor = TensorFromXTensor() |
| 24 | + |
| 25 | + |
| 26 | +class XTensorFromTensor(Op): |
| 27 | + __props__ = ("dims",) |
| 28 | + |
| 29 | + def __init__(self, dims): |
| 30 | + super().__init__() |
| 31 | + self.dims = dims |
| 32 | + |
| 33 | + def make_node(self, x) -> Apply: |
| 34 | + if not isinstance(x.type, TensorType): |
| 35 | + raise TypeError(f"x must be an TensorType type, got {type(x.type)}") |
| 36 | + output = px.XTensorType(x.type.dtype, dims=self.dims, shape=x.type.shape)() |
| 37 | + return Apply(self, [x], [output]) |
| 38 | + |
| 39 | + def perform(self, node, inputs, output_storage) -> None: |
| 40 | + [x] = inputs |
| 41 | + output_storage[0][0] = x.copy() |
| 42 | + |
| 43 | + |
| 44 | +def xtensor_from_tensor(x, dims): |
| 45 | + return XTensorFromTensor(dims=dims)(x) |
| 46 | + |
| 47 | + |
| 48 | +class XElemwise(Op): |
| 49 | + __props__ = ("scalar_op",) |
| 50 | + |
| 51 | + def __init__(self, scalar_op): |
| 52 | + super().__init__() |
| 53 | + self.scalar_op = scalar_op |
| 54 | + |
| 55 | + def make_node(self, *inputs): |
| 56 | + # TODO: Check dim lengths match |
| 57 | + inputs = [px.as_xtensor(inp) for inp in inputs] |
| 58 | + # TODO: This ordering is different than what xarray does |
| 59 | + unique_dims = sorted(set(chain.from_iterable(inp.type.dims for inp in inputs))) |
| 60 | + # TODO: Fix dtype |
| 61 | + output_type = px.XTensorType( |
| 62 | + "float64", dims=unique_dims, shape=(None,) * len(unique_dims) |
| 63 | + ) |
| 64 | + outputs = [output_type() for _ in range(self.scalar_op.nout)] |
| 65 | + return Apply(self, inputs, outputs) |
| 66 | + |
| 67 | + def perform(self, *args, **kwargs) -> None: |
| 68 | + raise NotImplementedError( |
| 69 | + "xtensor operations must be rewritten as tensor operations" |
| 70 | + ) |
| 71 | + |
| 72 | + |
| 73 | +add = XElemwise(ps.add) |
0 commit comments