You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
soil/soil/time.py

187 lines
4.8 KiB
Python

from mesa.time import BaseScheduler
from queue import Empty
from heapq import heappush, heappop, heapreplace
1 year ago
from collections import deque
import math
1 year ago
import logging
from inspect import getsource
from numbers import Number
from textwrap import dedent
from .utils import logger
2 years ago
from mesa import Agent as MesaAgent
INFINITY = float("inf")
1 year ago
class Delay:
"""A delay object which can be used both as a return value and as an awaitable (in async code)."""
__slots__ = ("delta", )
def __init__(self, delta):
1 year ago
self.delta = float(delta)
1 year ago
def __float__(self):
return self.delta
def __await__(self):
return (yield self.delta)
1 year ago
class DeadAgent(Exception):
pass
1 year ago
class PQueueActivation(BaseScheduler):
"""
A scheduler which activates each agent with a delay returned by the agent's step method.
If no delay is returned, a default of 1 is used.
In each activation, each agent will update its 'next_time'.
"""
def __init__(self, *args, shuffle=True, **kwargs):
2 years ago
super().__init__(*args, **kwargs)
self._queue = []
self._shuffle = shuffle
self.logger = getattr(self.model, "logger", logger).getChild(f"time_{ self.model }")
self.next_time = self.time
def add(self, agent: MesaAgent, when=None):
if when is None:
when = self.time
1 year ago
else:
when = float(when)
2 years ago
self._schedule(agent, None, when)
super().add(agent)
1 year ago
def _schedule(self, agent, when=None, replace=False):
if when is None:
when = self.time
if self._shuffle:
1 year ago
key = (when, self.model.random.random())
else:
1 year ago
key = (when, agent.unique_id)
if replace:
heapreplace(self._queue, (key, agent))
else:
heappush(self._queue, (key, agent))
def step(self) -> None:
"""
Executes agents in order, one at a time. After each step,
an agent will signal when it wants to be scheduled next.
"""
1 year ago
if self.time == INFINITY:
return
1 year ago
next_time = INFINITY
now = self.time
2 years ago
while self._queue:
1 year ago
((when, _id), agent) = self._queue[0]
if when > now:
next_time = when
break
2 years ago
try:
1 year ago
when = agent.step() or 1
when += now
2 years ago
except DeadAgent:
heappop(self._queue)
2 years ago
continue
1 year ago
if when == INFINITY:
heappop(self._queue)
continue
1 year ago
self._schedule(agent, when, replace=True)
self.steps += 1
1 year ago
self.time = next_time
if next_time == INFINITY:
2 years ago
self.model.running = False
self.time = INFINITY
return
1 year ago
class TimedActivation(BaseScheduler):
def __init__(self, *args, shuffle=True, **kwargs):
super().__init__(*args, **kwargs)
self._queue = deque()
self._shuffle = shuffle
self.logger = getattr(self.model, "logger", logger).getChild(f"time_{ self.model }")
self.next_time = self.time
1 year ago
def add(self, agent: MesaAgent, when=None):
if when is None:
when = self.time
else:
when = float(when)
self._schedule(agent, None, when)
super().add(agent)
def _schedule(self, agent, when=None, replace=False):
when = when or self.time
pos = len(self._queue)
for (ix, l) in enumerate(self._queue):
if l[0] == when:
l[1].append(agent)
return
if l[0] > when:
pos = ix
break
self._queue.insert(pos, (when, [agent]))
def step(self) -> None:
"""
Executes agents in order, one at a time. After each step,
an agent will signal when it wants to be scheduled next.
"""
if not self._queue:
return
now = self.time
next_time = self._queue[0][0]
if next_time > now:
self.time = next_time
return
bucket = self._queue.popleft()[1]
if self._shuffle:
self.model.random.shuffle(bucket)
for agent in bucket:
try:
when = agent.step() or 1
when += now
except DeadAgent:
continue
if when != INFINITY:
self._schedule(agent, when, replace=True)
self.steps += 1
if self._queue:
self.time = self._queue[0][0]
else:
self.time = INFINITY
class ShuffledTimedActivation(TimedActivation):
def __init__(self, *args, **kwargs):
super().__init__(*args, shuffle=True, **kwargs)
class OrderedTimedActivation(TimedActivation):
def __init__(self, *args, **kwargs):
super().__init__(*args, shuffle=False, **kwargs)
1 year ago