|
| 1 | +"""Behaviors and monitors.""" |
| 2 | + |
| 3 | +import functools |
| 4 | +import inspect |
| 5 | +import itertools |
| 6 | +import sys |
| 7 | +import warnings |
| 8 | + |
| 9 | +from scenic.core.distributions import Samplable, toDistribution |
| 10 | +import scenic.core.dynamics as dynamics |
| 11 | +from scenic.core.errors import InvalidScenarioError |
| 12 | +from scenic.core.type_support import CoercionFailure |
| 13 | +from scenic.core.utils import alarm |
| 14 | + |
| 15 | +from .invocables import Invocable |
| 16 | +from .utils import StuckBehaviorWarning |
| 17 | + |
| 18 | + |
| 19 | +class Behavior(Invocable, Samplable): |
| 20 | + """Dynamic behaviors of agents. |
| 21 | +
|
| 22 | + Behavior statements are translated into definitions of subclasses of this class. |
| 23 | + """ |
| 24 | + |
| 25 | + _noActionsMsg = ( |
| 26 | + 'does not take any actions (perhaps you forgot to use "take" or "do"?)' |
| 27 | + ) |
| 28 | + |
| 29 | + def __init_subclass__(cls): |
| 30 | + if "__signature__" in cls.__dict__: |
| 31 | + # We're unpickling a behavior; skip this step. |
| 32 | + return |
| 33 | + |
| 34 | + if cls.__module__ is not __name__: |
| 35 | + import scenic.syntax.veneer as veneer |
| 36 | + |
| 37 | + if veneer.currentScenario: |
| 38 | + veneer.currentScenario._behaviors.append(cls) |
| 39 | + |
| 40 | + target = cls.makeGenerator |
| 41 | + target = functools.partial(target, 0, 0) # account for Scenic-inserted args |
| 42 | + cls.__signature__ = inspect.signature(target) |
| 43 | + |
| 44 | + def __init__(self, *args, **kwargs): |
| 45 | + args = tuple(toDistribution(arg) for arg in args) |
| 46 | + kwargs = {name: toDistribution(arg) for name, arg in kwargs.items()} |
| 47 | + |
| 48 | + # Validate arguments to the behavior |
| 49 | + sig = inspect.signature(self.makeGenerator) |
| 50 | + sig.bind(None, *args, **kwargs) # raises TypeError on incompatible arguments |
| 51 | + Samplable.__init__(self, itertools.chain(args, kwargs.values())) |
| 52 | + Invocable.__init__(self, *args, **kwargs) |
| 53 | + |
| 54 | + if not inspect.isgeneratorfunction(self.makeGenerator): |
| 55 | + raise InvalidScenarioError(f"{self} {self._noActionsMsg}") |
| 56 | + |
| 57 | + @classmethod |
| 58 | + def _canCoerceType(cls, ty): |
| 59 | + return issubclass(ty, cls) or ty in (type, type(None)) |
| 60 | + |
| 61 | + @classmethod |
| 62 | + def _coerce(cls, thing): |
| 63 | + if thing is None or isinstance(thing, cls): |
| 64 | + return thing |
| 65 | + elif issubclass(thing, cls): |
| 66 | + return thing() |
| 67 | + else: |
| 68 | + raise CoercionFailure(f"expected type of behavior, got {thing}") |
| 69 | + |
| 70 | + def sampleGiven(self, value): |
| 71 | + args = (value[arg] for arg in self._args) |
| 72 | + kwargs = {name: value[val] for name, val in self._kwargs.items()} |
| 73 | + return type(self)(*args, **kwargs) |
| 74 | + |
| 75 | + def _assignTo(self, agent): |
| 76 | + if self._agent and agent is self._agent._dynamicProxy: |
| 77 | + # Assigned again (e.g. by override) to same agent; do nothing. |
| 78 | + return |
| 79 | + if self._isRunning: |
| 80 | + raise InvalidScenarioError( |
| 81 | + f"tried to reuse behavior object {self} already assigned to {self._agent}" |
| 82 | + ) |
| 83 | + self._start(agent) |
| 84 | + |
| 85 | + def _start(self, agent): |
| 86 | + super()._start() |
| 87 | + self._agent = agent |
| 88 | + self._runningIterator = self.makeGenerator(agent, *self._args, **self._kwargs) |
| 89 | + self._checkAllPreconditions() |
| 90 | + |
| 91 | + def _step(self): |
| 92 | + import scenic.syntax.veneer as veneer |
| 93 | + |
| 94 | + super()._step() |
| 95 | + assert self._runningIterator |
| 96 | + |
| 97 | + def alarmHandler(signum, frame): |
| 98 | + if sys.gettrace(): |
| 99 | + return # skip the warning if we're in the debugger |
| 100 | + warnings.warn( |
| 101 | + f"the behavior {self} is taking a long time to take an action; " |
| 102 | + "maybe you have an infinite loop with no take/wait statements?", |
| 103 | + StuckBehaviorWarning, |
| 104 | + ) |
| 105 | + |
| 106 | + timeout = dynamics.stuckBehaviorWarningTimeout |
| 107 | + with veneer.executeInBehavior(self), alarm(timeout, alarmHandler): |
| 108 | + try: |
| 109 | + actions = self._runningIterator.send(None) |
| 110 | + except StopIteration: |
| 111 | + actions = () # behavior ended early |
| 112 | + return actions |
| 113 | + |
| 114 | + def _stop(self, reason=None): |
| 115 | + super()._stop(reason) |
| 116 | + self._agent = None |
| 117 | + self._runningIterator = None |
| 118 | + |
| 119 | + @property |
| 120 | + def _isFinished(self): |
| 121 | + return self._runningIterator is None |
| 122 | + |
| 123 | + def _invokeInner(self, agent, subs): |
| 124 | + import scenic.syntax.veneer as veneer |
| 125 | + |
| 126 | + assert len(subs) == 1 |
| 127 | + sub = subs[0] |
| 128 | + if not isinstance(sub, Behavior): |
| 129 | + raise TypeError(f"expected a behavior, got {sub}") |
| 130 | + sub._start(agent) |
| 131 | + with veneer.executeInBehavior(sub): |
| 132 | + try: |
| 133 | + yield from sub._runningIterator |
| 134 | + finally: |
| 135 | + if sub._isRunning: |
| 136 | + sub._stop() |
| 137 | + |
| 138 | + def __repr__(self): |
| 139 | + items = itertools.chain( |
| 140 | + (repr(arg) for arg in self._args), |
| 141 | + (f"{key}={repr(val)}" for key, val in self._kwargs.items()), |
| 142 | + ) |
| 143 | + allArgs = ", ".join(items) |
| 144 | + return f"{self.__class__.__name__}({allArgs})" |
| 145 | + |
| 146 | + |
| 147 | +class Monitor(Behavior): |
| 148 | + """Monitors for dynamic simulations. |
| 149 | +
|
| 150 | + Monitor statements are translated into definitions of subclasses of this class. |
| 151 | + """ |
| 152 | + |
| 153 | + _noActionsMsg = 'does not take any actions (perhaps you forgot to use "wait"?)' |
| 154 | + |
| 155 | + def _start(self): |
| 156 | + return super()._start(None) |
0 commit comments