Source code for pyop3.axis_tree.context_sensitive
import functools
from collections.abc import Hashable, Mapping
from functools import cached_property
from immutabledict import immutabledict as idict
from pyop3 import utils
import pyop3.index_tree.tree
import pyop3.record
from pyop3.index_tree.tree import LoopIndex
from .tree import AbstractAxisTree, AxisForest, LoopContextAwareAxisTreeLike
[docs]
@pyop3.record.frozenrecord()
class LoopContextSensitiveAxisTreeLike(
LoopContextAwareAxisTreeLike,
pyop3.index_tree.tree.LoopContextSensitive,
):
# {{{ instance attrs
trees: idict # context to tree
[docs]
def get_instruction_executor_cache_key(self, visitor) -> Hashable:
trees_key = {}
for path, tree in self.trees.items():
trees_key[visitor.relabel_axis_tree_path(path)] = visitor(tree)
trees_key = idict(trees_key)
return (type(self), trees_key)
def __init__(self, trees: Mapping):
object.__setattr__(self, "trees", idict(trees))
# }}}
@property
def context_map(self): # old alias
return self.trees
def __repr__(self) -> str:
return f"{type(self).__name__}({self.context_map!r})"
def __str__(self) -> str:
return "\n".join(
f"{context}\n{tree}" for context, tree in self.context_map.items()
)
[docs]
def __getitem__(self, indices):
raise NotImplementedError
# TODO think harder about composing context maps
# answer is something like:
# new_context_map = {}
# for context, axes in self.context_map.items():
# for context_, axes_ in index_axes(axes, indices).items():
# new_context_map[context | context_] = axes_
# return ContextSensitiveAxisTree(new_context_map)
[docs]
def index(self) -> LoopIndex:
return LoopIndex(self)
[docs]
@cached_property
def sf(self):
return utils.single_valued([ax.sf for ax in self.context_map.values()])
[docs]
@cached_property
def unindexed(self):
return utils.single_valued([ax.unindexed for ax in self.context_map.values()])
[docs]
@cached_property
def context_free(self):
return utils.just_one(self.context_map.values())
[docs]
@functools.singledispatch
def iter_axis_trees(obj):
utils.raise_missing_dispatch_handler(obj)
@iter_axis_trees.register
def _(tree: AbstractAxisTree):
yield tree
@iter_axis_trees.register
def _(forest: AxisForest):
for t in forest:
yield from iter_axis_trees(t)
@iter_axis_trees.register
def _(cs_trees: LoopContextSensitiveAxisTreeLike):
for t in cs_trees.trees.values():
yield from iter_axis_trees(t)