Integrate attr libraries

This commit is contained in:
Marcell Vazquez-Chanlatte 2018-09-17 22:43:21 -07:00
parent fb2e79b807
commit 472fd45ce2
9 changed files with 200 additions and 265 deletions

View file

@ -1,7 +1,9 @@
# -*- coding: utf-8 -*-
from collections import deque, namedtuple
from functools import lru_cache
from typing import Union, NamedTuple
import attr
import funcy as fn
from lenses import lens, bind
@ -24,131 +26,161 @@ def flatten_binary(phi, op, dropT, shortT):
return op(tuple(fn.mapcat(f, phi.args)))
class AST(object):
__slots__ = ()
def __or__(self, other):
return flatten_binary(Or((self, other)), Or, BOT, TOP)
def __and__(self, other):
return flatten_binary(And((self, other)), And, TOP, BOT)
def __invert__(self):
if isinstance(self, Neg):
return self.arg
return Neg(self)
def __rshift__(self, t):
if self in (BOT, TOP):
return self
phi = self
for _ in range(t):
phi = Next(phi)
return phi
def __call__(self, trace, time=0):
return mtl.pointwise_sat(self)(trace, time)
@property
def children(self):
return tuple()
def walk(self):
"""Walk of the AST."""
pop = deque.pop
children = deque([self])
while len(children) > 0:
node = pop(children)
yield node
children.extend(node.children)
@property
def params(self):
def get_params(leaf):
if isinstance(leaf, ModalOp):
if isinstance(leaf.interval[0], Param):
yield leaf.interval[0]
if isinstance(leaf.interval[1], Param):
yield leaf.interval[1]
return set(fn.mapcat(get_params, self.walk()))
def set_params(self, val):
phi = param_lens(self)
return phi.modify(lambda x: float(val.get(x, val.get(str(x), x))))
@property
def atomic_predicates(self):
return set(AP_lens.collect()(self))
def inline_context(self, context):
phi, phi2 = self, None
def update(ap):
return context.get(ap, ap)
while phi2 != phi:
phi2, phi = phi, AP_lens.modify(update)(phi)
return phi
def __hash__(self):
# TODO: compute hash based on contents
return hash(repr(self))
def _or(exp1, exp2):
return flatten_binary(Or((exp1, exp2)), Or, BOT, TOP)
class _Top(AST):
__slots__ = ()
def _and(exp1, exp2):
return flatten_binary(And((exp1, exp2)), And, TOP, BOT)
def _neg(exp):
if isinstance(exp, _Bot):
return _Top()
elif isinstance(exp, _Top):
return _Bot()
elif isinstance(exp, Neg):
return exp.arg
return Neg(exp)
def _eval(exp, trace, time=0):
return mtl.pointwise_sat(exp)(trace, time)
def _timeshift(exp, t):
if exp in (BOT, TOP):
return exp
for _ in range(t):
exp = Next(exp)
return exp
def _walk(exp):
"""Walk of the AST."""
pop = deque.pop
children = deque([exp])
while len(children) > 0:
node = pop(children)
yield node
children.extend(node.children)
def _params(exp):
def get_params(leaf):
if isinstance(leaf, ModalOp):
if isinstance(leaf.interval[0], Param):
yield leaf.interval[0]
if isinstance(leaf.interval[1], Param):
yield leaf.interval[1]
return set(fn.mapcat(get_params, exp.walk()))
def _set_symbols(node, val):
children = tuple(_set_symbols(c, val) for c in node.children)
if hasattr(node, 'interval'):
return node.evolve(
arg=children[0],
interval=_update_itvl(node.interval, val),
)
elif isinstance(node, AtomicPred):
return val.get(node.id, node)
elif hasattr(node, 'args'):
return node.evolve(args=children)
elif hasattr(node, 'arg'):
return node.evolve(arg=children[0])
return node
def _inline_context(exp, context):
phi, phi2 = exp, None
while phi2 != phi:
phi2, phi = phi, _set_symbols(phi, context)
return phi
def _atomic_predicates(exp):
return set(bind(exp).Recur(AtomicPred).collect())
class Param(NamedTuple):
name: str
def __repr__(self):
return self.name
def ast_class(cls):
cls.__or__ = _or
cls.__and__ = _and
cls.__invert__ = _neg
cls.__call__ = _eval
cls.__rshift__ = _timeshift
cls.__getitem__ = _inline_context
cls.walk = _walk
cls.params = property(_params)
cls.atomic_predicates = property(_atomic_predicates)
cls.evolve = attr.evolve
if not hasattr(cls, "children"):
cls.children = property(lambda _: ())
return attr.s(frozen=True, auto_attribs=True, repr=False, slots=True)(cls)
def _update_itvl(itvl, lookup):
def _update_param(p):
if not isinstance(p, Param) or p.name not in lookup:
return p
val = lookup[p.name]
return val if isinstance(lookup, Param) else float(val)
return Interval(*map(_update_param, itvl))
@ast_class
class _Top:
def __repr__(self):
return "TRUE"
def __invert__(self):
return BOT
class _Bot(AST):
__slots__ = ()
@ast_class
class _Bot:
def __repr__(self):
return "FALSE"
def __invert__(self):
return TOP
TOP = _Top()
BOT = _Bot()
class AtomicPred(namedtuple("AP", ["id"]), AST):
__slots__ = ()
@ast_class
class AtomicPred:
id: str
def __repr__(self):
return f"{self.id}"
def __hash__(self):
# TODO: compute hash based on contents
return hash(repr(self))
@property
def children(self):
return tuple()
class Interval(namedtuple('I', ['lower', 'upper'])):
__slots__ = ()
class Interval(NamedTuple):
lower: Union[float, Param]
upper: Union[float, Param]
def __repr__(self):
return f"[{self.lower},{self.upper}]"
class NaryOpMTL(namedtuple('NaryOp', ['args']), AST):
__slots__ = ()
@ast_class
class NaryOpMTL:
OP = "?"
args: "Node" # TODO: when 3.7 is more common replace with type union.
def __repr__(self):
return "(" + f" {self.OP} ".join(f"{x}" for x in self.args) + ")"
@ -159,28 +191,18 @@ class NaryOpMTL(namedtuple('NaryOp', ['args']), AST):
class Or(NaryOpMTL):
__slots__ = ()
OP = "|"
def __hash__(self):
# TODO: compute hash based on contents
return hash(repr(self))
class And(NaryOpMTL):
__slots__ = ()
OP = "&"
def __hash__(self):
# TODO: compute hash based on contents
return hash(repr(self))
class ModalOp(namedtuple('ModalOp', ['interval', 'arg']), AST):
__slots__ = ()
@ast_class
class ModalOp:
OP = '?'
interval: Interval
arg: "Node"
def __repr__(self):
if self.interval.lower == 0 and self.interval.upper == float('inf'):
@ -193,25 +215,17 @@ class ModalOp(namedtuple('ModalOp', ['interval', 'arg']), AST):
class F(ModalOp):
__slots__ = ()
OP = "< >"
def __hash__(self):
# TODO: compute hash based on contents
return hash(repr(self))
class G(ModalOp):
__slots__ = ()
OP = "[ ]"
def __hash__(self):
# TODO: compute hash based on contents
return hash(repr(self))
class Until(namedtuple('ModalOp', ['arg1', 'arg2']), AST):
__slots__ = ()
@ast_class
class Until:
arg1: "Node"
arg2: "Node"
def __repr__(self):
return f"({self.arg1} U {self.arg2})"
@ -220,13 +234,10 @@ class Until(namedtuple('ModalOp', ['arg1', 'arg2']), AST):
def children(self):
return (self.arg1, self.arg2)
def __hash__(self):
# TODO: compute hash based on contents
return hash(repr(self))
class Neg(namedtuple('Neg', ['arg']), AST):
__slots__ = ()
@ast_class
class Neg:
arg: "Node"
def __repr__(self):
return f"~{self.arg}"
@ -235,13 +246,10 @@ class Neg(namedtuple('Neg', ['arg']), AST):
def children(self):
return (self.arg,)
def __hash__(self):
# TODO: compute hash based on contents
return hash(repr(self))
class Next(namedtuple('Next', ['arg']), AST):
__slots__ = ()
@ast_class
class Next:
arg: "Node"
def __repr__(self):
return f"@{self.arg}"
@ -250,30 +258,7 @@ class Next(namedtuple('Next', ['arg']), AST):
def children(self):
return (self.arg,)
def __hash__(self):
# TODO: compute hash based on contents
return hash(repr(self))
class Param(namedtuple('Param', ['name']), AST):
__slots__ = ()
def __repr__(self):
return self.name
def __hash__(self):
# TODO: compute hash based on contents
return hash(repr(self))
@lru_cache()
def param_lens(phi, *, getter=False):
return bind(phi).Recur(Param)
def type_pred(*args):
ast_types = set(args)
return lambda x: type(x) in ast_types
AP_lens = lens.Recur(AtomicPred)