Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_gets_local_agent(self):
addr = self.agents[0].addr
agent_proxy = aiomas.run(self.node.connect(addr))
self.assertTrue(isinstance(agent_proxy, LocalProxy))
def test_agent_update(self, mock_method):
aiomas.run(self.node.update_agents())
self.assertEquals(mock_method.call_count, 2)
def test_multiple_behaviors_called(self):
class NewAgent(syd.Agent):
state_vars = ['cash']
behaviors = [behavior,
partial(behavior_with_params, param=2)]
agent = NewAgent(self.node, {'cash': 100})
self.assertEquals(agent.state.cash, 100)
aiomas.run(agent.decide())
agent.apply_updates()
self.assertEquals(agent.state.cash, 20)
import aiomas
import asyncio
import logging
import operator
import itertools
from .proxy import LocalProxy
logger = logging.getLogger(__name__)
class Node(aiomas.Container):
"""a node manages a population of agents"""
def __init__(self, addr, *args, **kwargs):
super().__init__(addr, *args, **kwargs)
self._local_agent_proxies = {}
# prepare logging for each node
_, port = addr[:-1].rsplit(':', 1)
handler = logging.FileHandler('/tmp/sydspawn_{}.log'.format(port))
handler.setLevel(logging.DEBUG)
self.logger = logging.getLogger(__name__)
self.logger.addHandler(handler)
self.logger.debug('node up at {}'.format(addr))
@classmethod
async def start(cls, addr, **container_kwargs):
# extract vars required by behaviors
# can handle partials as well
all_required_vars = set(sum((
b.required_vars if not isinstance(b, partial)
else b.func.required_vars
for b in behaviors
), []))
missing = [var for var in all_required_vars
if var not in state_vars]
if missing:
raise MissingVarError('required vars {} are missing in agent `state_vars`'.format(missing))
return type.__new__(cls, name, parents, dct)
class Agent(aiomas.Agent, metaclass=AgentMeta):
state_vars = []
behaviors = []
def __init__(self, container, state, *args, world_addr=None, **kwargs):
super().__init__(container)
self.state = self.State(**state)
self.world_addr = world_addr
self._updates = []
self.init(state, *args, **kwargs)
def init(self, state, *args, **kwargs):
"""initialization for an agent. you should
override this method instead of `__init__`."""
pass
async def emit(self, name, *args, **kwargs):
def irun(self, steps, reports=None):
"""run the simulation lazily (as an iterator)"""
# reports = {name: (fn, mod step)}
aggs = defaultdict(dict)
reports = reports or {}
for name, (fn, mod_step) in reports.items():
aggs[mod_step][name] = fn
aiomas.run(self.container.setup_agents())
for i in range(steps):
aiomas.run(self._step())
# TODO any way to make this more efficient?
report = {}
states = None
for mod_step, agg_fns in aggs.items():
if i % mod_step == 0:
for name, fn in agg_fns.items():
if states is None:
states = self.container.states()
report[name] = fn(states)
yield report
def states(self):
"""iterate over all agent states across the cluster"""
tasks = [asyncio.ensure_future(manager.states())
for manager in self._managers]
for states in aiomas.run(asyncio.gather(*tasks)):
yield from states
def irun(self, steps, reports=None):
"""run the simulation lazily (as an iterator)"""
# reports = {name: (fn, mod step)}
aggs = defaultdict(dict)
reports = reports or {}
for name, (fn, mod_step) in reports.items():
aggs[mod_step][name] = fn
aiomas.run(self.container.setup_agents())
for i in range(steps):
aiomas.run(self._step())
# TODO any way to make this more efficient?
report = {}
states = None
for mod_step, agg_fns in aggs.items():
if i % mod_step == 0:
for name, fn in agg_fns.items():
if states is None:
states = self.container.states()
report[name] = fn(states)
yield report
def start_node(port):
"""start a node"""
task = Node.start(('0.0.0.0', port),
codec=aiomas.codecs.MsgPackBlosc,
extra_serializers=[serializers.get_np_serializer])
# terminates when the node's manager is given the 'stop' command
aiomas.run(until=task)
def shutdown(self):
"""shutdown the cluster"""
tasks = [asyncio.ensure_future(manager.stop())
for manager in self._managers]
aiomas.run(asyncio.gather(*tasks))
self._container.shutdown()