class StatsMachine(Generic[TS]):
"""
Evaluates the stats of a program, binding each alias it defines. cache
holds what the cost models compute from the stats, for as long as the
search which prices with the machine, and the machines of one search may
share it.
"""
def __init__(
self,
stats_factory: StatsFactory[TS],
bindings=None,
cache: dict | None = None,
):
self.stats_factory = stats_factory
if bindings is None:
bindings = OrderedDict()
self.bindings = bindings
self.cache = {} if cache is None else cache
@overload
def __call__(self, node: LogicExpression) -> TS: ...
@overload
def __call__(self, node: Alias) -> TS: ...
@overload
def __call__(self, node: LogicStatement) -> tuple[TS, ...]: ...
@overload
def __call__(self, node: LogicNode) -> TS | tuple[TS, ...]: ...
def __call__(self, node) -> TS | tuple[TS, ...]:
logger.debug("Evaluating: %s", node)
match node:
case Plan():
last_result: TensorStats | tuple[TensorStats, ...] = ()
for body in node.bodies:
last_result = self(body)
return last_result
case Fuse(_, body):
# Fusing loops doesn't change the statistics of their results.
return self(body)
case Query(Table(Alias() as var, idxs), rhs):
if rhs.fields() != idxs:
rhs = Reorder(rhs, idxs)
rhs_stats = self(rhs)
self.bindings[var] = rhs_stats
return rhs_stats
case QueryInto():
return self(node.as_query())
case Alias():
stats = self.bindings.get(node)
if stats is None:
raise ValueError(f"undefined tensor alias {node}")
return stats
case Table(tns, idxs):
if isinstance(tns, Literal):
tensor = self.stats_factory(tns.val, idxs)
elif isinstance(tns, Alias):
base = self.bindings.get(tns)
if base is None:
raise ValueError(f"No TensorStats bound to alias {node.tns}")
new_indices = tuple(f for f in node.idxs)
tensor = self.stats_factory.relabel(base, new_indices)
return tensor
case FillTable(tns):
return fill_statistics(self.stats_factory, self(tns).fill_type)
case DimensionTable():
return fill_statistics(self.stats_factory, node.fill_type({}))
case MapJoin():
if not isinstance(node.op, Literal):
raise TypeError("MapJoin.op must be Literal(...).")
child_stats_list: list[TS] = []
for arg in node.args:
res = self(arg)
child_stats_list.append(res)
return self.stats_factory.mapjoin(node.op.val, *child_stats_list)
case Aggregate():
if not isinstance(node.op, Literal):
raise TypeError("Aggregate.op must be Literal(...).")
op = node.op.val
arg2 = self(node.arg)
reduce_indices = node.idxs
if isinstance(node.init, Literal):
return self.stats_factory.aggregate(
op, node.init.val, reduce_indices, arg2
)
if is_fill_expression(node.init):
# The result starts from the background, as reductions do.
return self.stats_factory.aggregate(op, None, reduce_indices, arg2)
# A tensor init is folded into the reduction of the argument.
reduced = self.stats_factory.aggregate(op, None, reduce_indices, arg2)
return self.stats_factory.reorder(
self.stats_factory.mapjoin(op, self(node.init), reduced),
node.fields(),
)
case Literal(val):
return self.stats_factory(Scalar(val), ())
case Reorder():
return self.stats_factory.reorder(self(node.arg), node.idxs)
case Relabel():
base = self(node.arg)
new_indices = tuple(f for f in node.idxs)
return self.stats_factory.relabel(base, new_indices)
case Produces(args):
ret = tuple(self(arg) for arg in args)
assert all(not isinstance(r, tuple) for r in ret)
return ret
case _:
raise TypeError(f"Unhandled node type {type(node)}")