Source code for pyop3.expr.tensor.scalar
from __future__ import annotations
import numbers
from collections.abc import Hashable
from typing import TYPE_CHECKING, ClassVar, Literal
import numpy as np
from immutabledict import immutabledict as idict
from mpi4py import MPI
import pyop3.record
from pyop3 import dtypes, utils
from pyop3 import exceptions as exc
from pyop3.axis_tree.tree import UNIT_AXIS_TREE
from pyop3.buffer import AbstractBuffer, ArrayBuffer
from pyop3.sf import single_star_sf
from .base import Tensor
if TYPE_CHECKING:
from pyop3.types import *
[docs]
@pyop3.record.record()
class Scalar(Tensor):
"""A scalar value."""
# {{{ instance attrs
name: str
buffer: AbstractBuffer
[docs]
def get_instruction_executor_cache_key(self, visitor) -> Hashable:
return (type(self), visitor(self.buffer))
# TODO: It would be nice to accept dtype here to alloc an empty thing
def __init__(
self,
value: numbers.Number | None = None,
comm: MPI.Comm | None = None,
*,
buffer: AbstractBuffer | None = None,
constant: bool | None = None,
name: str | None = None,
prefix: str | None = None,
) -> None:
name = utils.maybe_generate_name(name, prefix, self.DEFAULT_PREFIX)
if buffer is not None:
# clean me up
assert constant is None
if value is not None or comm is not None:
raise ValueError("Since 'buffer' is given, 'value' and 'comm' should not be passed")
else:
if comm is None:
comm = MPI.COMM_SELF
sf = single_star_sf(comm)
buffer_kwargs = {"sf": sf}
if constant is not None:
buffer_kwargs["constant"] = constant
if value is not None:
data = np.asarray([value])
buffer = ArrayBuffer(data, **buffer_kwargs)
else:
buffer = ArrayBuffer.empty(1, dtype=self.DEFAULT_DTYPE, **buffer_kwargs)
if buffer.size != 1:
raise exc.SizeMismatchException("Expected a buffer with unit size")
object.__setattr__(self, "name", name)
object.__setattr__(self, "buffer", buffer)
# }}}
# {{{ interface impls
dim: ClassVar[int] = 0
size = 1
transform: ClassVar[None] = None
[docs]
def copy(self) -> Scalar:
name = f"{self.name}_copy"
buffer = self._buffer.copy()
return self.record_new(_name=name, _buffer=buffer)
shape = (UNIT_AXIS_TREE,)
loop_axes = idict()
axis_trees = ()
@property
def _full_str(self) -> str:
return f"*{self.name}"
@property
def comm(self) -> MPI.Comm:
return self.buffer.comm
[docs]
def concretize(self, *, linear=True):
from pyop3.expr import as_linear_buffer_expression
assert linear
return as_linear_buffer_expression(self)
@property
def local_max(self) -> numbers.Number:
return self.value
@property
def local_min(self) -> numbers.Number:
return self.local_max
[docs]
def as_array(self, mode: Literal["ro", "wo", "rw"]) -> np.ndarray:
"""Return a view of the scalar's buffer.
Parameters
----------
mode
The access mode: read-only, write-only, or read-write.
Returns
-------
numpy.ndarray
A view of the buffer with the requested access mode.
"""
match mode:
case "ro":
return self.buffer.data_ro
case "wo":
return self.buffer.data_wo
case "rw":
return self.buffer.data_rw
case _:
raise ValueError(f"Unknown array access mode '{mode}'")
# }}}
# {{{ class attrs
DEFAULT_PREFIX: ClassVar[str] = "scalar"
DEFAULT_DTYPE: ClassVar[np.dtype] = dtypes.ScalarType
# }}}
@property
def constant(self) -> bool:
return self.buffer.constant
[docs]
def getitem(self, *, strict=False):
return self
[docs]
def with_axis_trees(self, axis_trees):
assert len(axis_trees) == 0, "scalars don't have axis trees"
return self
@property
def value(self):
return utils.just_one(self.buffer.data_ro)
# {{{ arithmetic
# TODO: also think about comm sizes? is this valid for size>1?
# NOTE: Same impl needed for ScalarExpressions...
def __add__(self, other: ExpressionT, /) -> ExpressionT:
if self.constant:
if isinstance(other, numbers.Number):
return Scalar(self.value+other, constant=True)
elif isinstance(other, Scalar) and other.constant:
return Scalar(self.value+other.value, constant=True)
return super().__add__(other)
# }}}