def test_main():
    resource = Resource('poison in body', ['amount', 'kind'])
    resource.set_values([10.0, 'mercury'])

    agent = Agent('thin agent', strict_engine=True)
    agent.set_scaffold(resource)

    ams = AgentManagementSystem('exterior laws', [agent])

    mapper = ResourceMap('scale down', 'scale', 'amount', ('factor', ))
    kwargs = {
        'poison_amount_getter': lambda: agent.resource['amount'],
        'doodle': 2.0
    }
    compulsion = Compulsion('natural decay',
                            simple_decline,
                            mapper,
                            compel_func_kwargs=kwargs)
    ams.set_law(compulsion)

    count = 0
    for agent in ams.shuffle_nodes(True, 5, False):
        before = agent.resource['amount']
        ams.compel(agent, 'natural decay')
        after = agent.resource['amount']
        assert (before == REF[count][0])
        assert (after == REF[count][1])
        count += 1
def test_main(set_random):

    essence = Essence('inclinations', ['t_1', 't_2', 't_3', 't_4', 't_5'])
    essence.set_values([0.0, 0.0, 0.0, 0.0, 0.0])

    agent = Agent('thin agent', strict_engine=True)
    agent.set_scaffold(essence)

    ams = AgentManagementSystem('exterior laws', [agent])

    mapper_1 = EssenceMap('tweak', 'wiener', 't_1', ('range_step', ))
    mapper_2 = EssenceMap('tweak', 'wiener', 't_2', ('range_step', ))
    mapper_3 = EssenceMap('tweak', 'wiener', 't_3', ('range_step', ))
    mapper_4 = EssenceMap('tweak', 'wiener', 't_4', ('range_step', ))
    mapper_5 = EssenceMap('tweak', 'wiener', 't_5', ('range_step', ))
    mapper = MapCollection([mapper_1, mapper_2, mapper_3, mapper_4, mapper_5])
    mutate = MultiMutation('jumps', lambda: 1.0, mapper, mutation_prob=0.5)
    ams.set_law(mutate)

    vals = agent.essence.values()
    assert (all([x == pytest.approx(y) for x, y in zip(vals, REF[0])]))
    ams.mutate(agent, 'jumps')
    vals = agent.essence.values()
    assert (all([x == pytest.approx(y) for x, y in zip(vals, REF[1])]))
    ams.mutate(agent, 'jumps')
    vals = agent.essence.values()
    assert (all([x == pytest.approx(y) for x, y in zip(vals, REF[2])]))
    ams.mutate(agent, 'jumps')
    vals = agent.essence.values()
    assert (all([x == pytest.approx(y) for x, y in zip(vals, REF[3])]))
    ams.mutate(agent, 'jumps')
    vals = agent.essence.values()
    assert (all([x == pytest.approx(y) for x, y in zip(vals, REF[4])]))
def test_main():
    #
    # Define Messages
    #
    buzz = Buzz('view_of_dice', ['dice_1', 'dice_2', 'dice_3', 
                                 'dice_4', 'dice_5'])
    belief = Belief('world_is_good', ['joy_index'])
    
    #
    # Define Organs and their associated messages
    #
    sensor = Sensor('check_roll', dice_sensor, buzz)
    interpreter = Interpreter('was_it_good_roll', roll_interpreter, buzz, belief,
                              belief_updater=True)
    
    #
    # Initialize Agent
    #
    agent = Agent('test_agent', strict_engine=True)
    agent.set_organ(sensor)
    agent.set_organ(interpreter)
    
    beliefs = []
    for k in range(0, 5):
        agent.sense('check_roll')
        agent.interpret('was_it_good_roll')
        beliefs.append(agent.belief['world_is_good'].values()[0])
    
    assert (beliefs == REF_OUTCOME)
def test_main(set_random):

    essence = Essence('inclinations', ['t_1', 't_2', 'volatility'])
    essence.set_values([0.7, 1.5, 0.5])

    agent = Agent('thin agent', strict_engine=True)
    agent.set_scaffold(essence)

    ams = AgentManagementSystem('exterior laws', [agent])

    mapper_1 = EssenceMap('tweak_1', 'wiener', 't_1', ('range_step', ))
    mapper_2 = EssenceMap('tweak_2', 'wiener', 't_2', ('range_step', ))
    mutate_1 = Mutation('jumps_1',
                        essence.__getitem__,
                        mapper_1,
                        mutation_prob=0.5,
                        mutate_func_kwargs={'key': 'volatility'})
    mutate_2 = Mutation('jumps_2',
                        essence.__getitem__,
                        mapper_2,
                        mutation_prob=0.5,
                        mutate_func_kwargs={'key': 'volatility'})
    ams.set_laws(mutate_1, mutate_2)

    assert (all([
        a == pytest.approx(b) for a, b in zip(agent.essence.values(), REF[0])
    ]))
    ams.mutate(agent, 'jumps_1')
    assert (all([
        a == pytest.approx(b) for a, b in zip(agent.essence.values(), REF[1])
    ]))
    ams.mutate(agent, 'jumps_1')
    assert (all([
        a == pytest.approx(b) for a, b in zip(agent.essence.values(), REF[2])
    ]))
    ams.mutate(agent, 'jumps_1')
    assert (all([
        a == pytest.approx(b) for a, b in zip(agent.essence.values(), REF[3])
    ]))
    ams.mutate(agent, 'jumps_1')
    assert (all([
        a == pytest.approx(b) for a, b in zip(agent.essence.values(), REF[4])
    ]))
    ams.mutate(agent, 'jumps_2')
    assert (all([
        a == pytest.approx(b) for a, b in zip(agent.essence.values(), REF[5])
    ]))
    ams.mutate(agent, 'jumps_2')
    assert (all([
        a == pytest.approx(b) for a, b in zip(agent.essence.values(), REF[6])
    ]))
    ams.mutate(agent, 'jumps_2')
    assert (all([
        a == pytest.approx(b) for a, b in zip(agent.essence.values(), REF[7])
    ]))
    ams.mutate(agent, 'jumps_2')
    assert (all([
        a == pytest.approx(b) for a, b in zip(agent.essence.values(), REF[8])
    ]))
Beispiel #5
0
def test_main():
    a1 = Agent('a1')
    a2 = Agent('a2')
    a3 = Agent('a3')
    a4 = Agent('a4')

    ams = AgentManagementSystem('dummy', [a1, a2, a3, a4])

    stuff = []
    for nn in ams.cycle_nodes(True, 12):
        assert (isinstance(nn, Agent))
        stuff.append(nn.name)

    assert (len(stuff) == 12)

    for k in range(3):
        assert (set(stuff[4 * k:4 * (k + 1)]) == set(['a1', 'a2', 'a3', 'a4']))

    count = 0
    for nn in ams.shuffle_edges(False, 20, False):
        assert (len(nn) == 2)
        assert (isinstance(nn[0], Node))
        assert (isinstance(nn[1], Node))
        count += 1

    stuff = []
    for nn in ams.shuffle_nodes(True, 20, True):
        stuff.append(nn.name)

    assert (len(stuff) == 20)
    #
    # Small chance this test fails randomly. This checks that sampling is mostly
    # uneven, but randomly it can become even.
    #
    assert (not numpy.std([
        stuff.count('a1'),
        stuff.count('a2'),
        stuff.count('a3'),
        stuff.count('a4')
    ]) < 0.01)

    assert (isinstance(ams.choice_nodes(False), Node))
    assert (isinstance(ams.choice_nodes(True), Agent))

    assert (isinstance(ams.choice_edges(False)[0], Node))
    assert (isinstance(ams.choice_edges(True)[0], Agent))
    assert (len(ams.choice_edges(False)) == 2)
    assert (len(ams.choice_edges(True)) == 2)
Beispiel #6
0
def test_main():
    resource = Resource('harvest', ('wheat', 'rye', 'barley', 'oats'))
    resource.set_values([35.0, 12.0, 8.0, 6.0])
    agent1 = Agent('farmer Joe', strict_engine=True)
    agent1.set_scaffold(resource)

    resource = Resource('food producer', ('wheat', 'rye', 'barley', 'oats',
                                          'cash_on_hand'))
    resource.set_values([0.0, 0.0, 0.0, 0.0, 100.0])
    agent2 = Agent('yummy Inc', strict_engine=True)
    agent2.set_scaffold(resource)

    ams = AgentManagementSystem('food market', [agent1, agent2])
    uuid_of_yummy = list(ams.agents_in_scope.values())[1].agent_id_system

    mapper = ResourceMap('cash loss', 'scale', 'cash_on_hand', ('factor',))
    amort = Compulsion('amortization', interest_rate, mapper)
    ams.set_law(amort)

    mapper_wheat = ResourceMap('loss of wheat', 'scale', 'wheat', ('factor',))
    mapper_rye = ResourceMap('loss of rye', 'scale', 'rye', ('factor',))
    mapper_barley = ResourceMap('loss of barley', 'scale', 'barley', ('factor',))
    mapper_oats = ResourceMap('loss of oats', 'scale', 'oats', ('factor',))
    mapper_cereal = MapCollection([mapper_wheat, mapper_rye, mapper_barley, mapper_oats])
    sloppy = Compulsion('sloppy', lambda : 4*[0.88], mapper_cereal)
    ams.set_law(sloppy)

    ams.make_lawbook_entry(['sloppy'], agent_name_selector=farm_name_test)
    ams.make_lawbook_entry(['amortization'], agent_ids=[uuid_of_yummy])

    for agent in ams.cycle_nodes(True, 2):
        ams.engage_all_verbs(agent, validate_lawbook=True)

    vals1 = agent1.resource.values()
    vals2 = agent2.resource.values()

    assert (vals1 == REF1)
    assert (vals2 == REF2)

    ams.compel(agent2, 'sloppy')

    try:
        ams.compel(agent2, 'sloppy', validate_lawbook=True)
    except RuntimeError as e:
        if 'Compulsion sloppy is not in law book' in str(e):
            pass
        else:
            raise AssertionError('Exception was not properly raised')

    try:
        ams.compel(agent1, 'amortization')
    except KeyError as e:
        if 'cash_on_hand' in str(e):
            pass
        else:
            raise AssertionError('Exception was not properly raised')
def test_main():
    #
    # Define Messages
    #
    feature = Feature('colour', ('hue', 'saturation', 'lightness'))

    #
    # Define Scaffold
    #
    agent_essence = Essence('my_parameters',
                            ('hue', 'saturation', 'lightness', 'mood'))
    agent_essence.set_values([0.9, 0.4, 1.0, 'jubilant'])
    slicer_of_essence = MessageOperator(
        agent_essence, slice_labels=['hue', 'saturation', 'lightness'])
    #
    # Define Organs and their associated messages
    #
    cortex = Cortex('colour_revealer',
                    expose_distort,
                    slicer_of_essence,
                    feature,
                    cortex_func_kwargs={'distort_degree': 0.05})

    #
    # Initialize Agent
    #
    agent = Agent('test_agent', strict_engine=True)
    agent.set_organ(cortex)
    agent.set_scaffold(agent_essence)

    #
    # Tickle the cortex
    #
    tickle_me_1 = agent.tickle('colour_revealer')
    for val, ref_val in zip(tickle_me_1.values(), REF1):
        assert (val == pytest.approx(ref_val, abs=1e-3))

    tickle_me_2 = agent.tickle('colour_revealer')
    for val, ref_val in zip(tickle_me_2.values(), REF2):
        assert (val == pytest.approx(ref_val, abs=1e-3))

    agent_essence.set_values([0.0, 0.0, 0.0, 'hey'])
    tickle_me_3 = agent.tickle('colour_revealer')
    for val, ref_val in zip(tickle_me_3.values(), REF3):
        assert (val == pytest.approx(ref_val, abs=1e-3))
Beispiel #8
0
def test_main():
    buzz_1 = Buzz('B1', ('value', ))
    sensor_1 = Sensor('S1', s1, buzz_1)
    buzz_2 = Buzz('B2', ('value', ))
    sensor_2 = Sensor('S2', s2, buzz_2)

    agent = Agent('test', strict_engine=True)
    agent.set_organs(sensor_1, sensor_2)
    agent.set_messages(buzz_1, buzz_2)

    plan = Plan('silly simple')
    plan.add_cargo('sense', 'S1')
    plan.add_cargo('sense', 'S2')
    plan.add_dependency(0, 1)
    plan.stamp_and_approve()
    plan.enacted_by(agent)

    assert (TEST_ORDER == REF_ORDER)
    assert (buzz_1.values() == [1.0])
    assert (buzz_2.values() == [2.0])
def test_main():
    #
    # Define Messages
    #
    belief = Belief('stressed', ('degree', ))
    belief.set_values(10.0)
    direction1 = Direction('collect_amount', ('intake_volume', ))

    #
    # Define Scaffold and Map for it
    #
    agent_resources = Resource('internal_molecules', ('A', 'B', 'C'))
    agent_resources.set_values([2.0, 1.0, 0.5])
    added_a = ResourceMap('get_A', 'delta_scale', 'A', (
        'add',
        'dilute',
    ))
    added_b = ResourceMap('get_B', 'delta_scale', 'B', (
        'add',
        'dilute',
    ))
    added_c = ResourceMap('get_C', 'delta_scale', 'C', (
        'add',
        'dilute',
    ))
    add_internal = MapCollection([added_a, added_b, added_c])

    #
    # Define Organs and their associated messages
    #
    moulder1 = Moulder('discard_or_not', make_decision, belief, direction1)

    env = Env()
    actuator1 = Actuator('collect', env.excretor, direction1, add_internal)

    #
    # Initialize Agent
    #
    agent = Agent('test_agent', strict_engine=True)
    agent.set_organ(moulder1)
    agent.set_organ(actuator1)
    agent.set_scaffold(agent_resources)

    #
    # Decide on direction and execute action
    #
    agent.mould('discard_or_not')
    agent.act('collect')

    for mol in REF:
        assert (isclose(REF[mol], agent.resource[mol], abs_tol=0.0001))

    try:
        agent.act('collect')
        raise AssertionError(
            'Acting twice in sequence did not raise correct exception')
    except EmptyFlashError:
        pass
def test_main():
    #
    # Define Messages
    #
    belief = Belief('Projectile status', ('speed', 'height', 'angle'))
    belief.set_values([100.0, 0.3, 0.2])
    direction = Direction('motion', ('horizontal direction',
                                     'horizontal magnitude',
                                     'vertical direction',
                                     'vertical magnitude'))

    #
    # Define Scaffold and Map for it
    #
    agent_resources = Resource('internal_resource', ('internal_energy',))
    agent_resources.set_values(20.0)
    change_energy = ResourceMap('adjust_energy', 'delta', 'internal_energy', ('expend_energy',))

    #
    # Define Organs and their associated messages
    #
    moulder = Moulder('take evasive action?', make_decision,
                      belief, direction,
                      change_energy)
    splitter_1 = MessageOperator(direction, slice_labels=['horizontal direction',
                                                          'horizontal magnitude'])
    splitter_2 = MessageOperator(direction, slice_labels=['vertical direction',
                                                          'vertical magnitude'])
    actuator1 = Actuator('move left right', move_rule_horizontal, splitter_1)
    actuator2 = Actuator('move up down', move_rule_vertical, splitter_2)

    #
    # Initialize Agent
    #
    agent = Agent('test_agent', strict_engine=True)
    agent.set_organ(moulder)
    agent.set_organ(actuator1)
    agent.set_organ(actuator2)
    agent.set_scaffold(agent_resources)
    agent.set_message(belief)

    #
    # Decide on direction and execute action
    #
    agent.mould('take evasive action?')
    agent.act('move up down')
    agent.act('move left right')
    assert (agent.resource['internal_energy'] == REF_E[0])
    belief.set_values([100.0, 1.3, -0.5])
    agent.mould('take evasive action?')
    agent.act('move up down')
    agent.act('move left right')
    assert (agent.resource['internal_energy'] == REF_E[1])
    for e1, e2 in zip(REPO, REF_REPO):
        assert(e1 == e2)

    try:
        agent.act('move up down')
        raise AssertionError('Action without preceding moulding did not raise exception')
    except EmptyFlashError:
        pass
    else:
        raise AssertionError('Action without preceding moulding did not raise expected exception')
    try:
        agent.act('move left right')
        raise AssertionError('Action without preceding moulding did not raise exception')
    except EmptyFlashError:
        pass
    else:
        raise AssertionError('Action without preceding moulding did not raise expected exception')
def test_main():

    agent_1 = Agent('A1', strict_engine=True)
    agent_2 = Agent('A2', strict_engine=True)
    agent_3 = Agent('A3', strict_engine=True)
    agents = [agent_1, agent_2, agent_3]
    node = [Node('dummy', a) for a in agents]

    graph = nx.Graph()
    graph.add_nodes_from(node)
    graph.add_edge(node[0], node[1])
    graph.add_edge(node[1], node[2])

    ams = AgentManagementSystem('tester', agents, graph)

    n_to_1 = ams.neighbours_to(agent_1.agent_id_system)
    n_to_2 = ams.neighbours_to(agent_2.agent_id_system)
    n_to_3 = ams.neighbours_to(agent_3.agent_id_system)

    assert (list(map(lambda x: x.name, n_to_1)) == ['A2'])
    assert (sorted(list(map(lambda x: x.name, n_to_2))) == ['A1', 'A3'])
    assert (list(map(lambda x: x.name, n_to_3)) == ['A2'])

    assert (ams.edge_property(agent_1.agent_id_system, agent_2.agent_id_system)[0])
    assert (not ams.edge_property(agent_1.agent_id_system, agent_3.agent_id_system)[0])
    assert (ams.edge_property(agent_2.agent_id_system, agent_3.agent_id_system)[0])

    ams.edge_edit(agent_1.agent_id_system, agent_3.agent_id_system, add=True)
    ams.edge_edit(agent_1.agent_id_system, agent_2.agent_id_system, delete=True)

    assert (not ams.edge_property(agent_1.agent_id_system, agent_2.agent_id_system)[0])
    assert (ams.edge_property(agent_1.agent_id_system, agent_3.agent_id_system)[0])
    assert (ams.edge_property(agent_2.agent_id_system, agent_3.agent_id_system)[0])

    graph.add_node(Node('dummy', None))
    assert (not ams.choice_nodes(True) is None)
    assert (not ams.choice_nodes(True) is None)
    assert (not ams.choice_nodes(True) is None)
    assert (not ams.choice_nodes(True) is None)
    assert (not ams.choice_nodes(True) is None)
    assert (not ams.choice_nodes(True) is None)
    assert (not ams.choice_nodes(True) is None)
    assert (not ams.choice_nodes(True) is None)
    assert (not ams.choice_nodes(True) is None)
    assert (not ams.choice_nodes(True) is None)

    n1 = 0
    n2 = 0
    n3 = 0
    n_none = 0
    for node in ams.shuffle_nodes(False, 16, replace=False):
        agent = node.agent_content
        if not agent is None:
            if agent.name == 'A1':
                n1 += 1
            if agent.name == 'A2':
                n2 += 1
            if agent.name == 'A3':
                n3 += 1
        else:
            n_none += 1

    assert (n1 == 4)
    assert (n2 == 4)
    assert (n3 == 4)
    assert (n_none == 4)
Beispiel #12
0
def test_main():
    belief = Belief('dummy', ('a1', ))
    resource = Resource('internal energy', ('level', ))
    mapper = ResourceMap('eat energy', 'delta', 'level', ('shift', ))
    interpreter1 = Interpreter('thinker',
                               lambda x: (x + 1, -1),
                               belief,
                               belief,
                               resource_map_output=mapper)
    interpreter2 = Interpreter('thinker X',
                               lambda x: (x + 1, -3),
                               belief,
                               belief,
                               resource_map_output=mapper)
    battery = AutoResourceCondition('battery left', lambda x: x > 0)
    heart_1 = Heartbeat('big heart',
                        battery,
                        ticker_arithmetic=lambda: 2,
                        max_ticker=4)
    heart_2 = Heartbeat('small heart',
                        battery,
                        ticker_arithmetic=lambda: 1,
                        max_ticker=4)

    agent_1 = Agent('A1')
    agent_1.set_organs(interpreter1, interpreter2)
    belief.set_values([1])
    resource.set_values([10])
    agent_1.set_message(belief)
    agent_1.set_scaffold(resource)
    agent_1.set_policies(heart_1, heart_2)

    assert (agent_1.belief['dummy'].values()[0] == REF_B1[0])
    assert (agent_1.inert == REF_I1[0])
    agent_1.pump('big heart')
    agent_1.interpret('thinker')
    assert (agent_1.belief['dummy'].values()[0] == REF_B1[1])
    assert (agent_1.inert == REF_I1[1])
    agent_1.pump('big heart')
    agent_1.interpret('thinker')
    assert (agent_1.belief['dummy'].values()[0] == REF_B1[2])
    assert (agent_1.inert == REF_I1[2])
    agent_1.pump('big heart')
    agent_1.interpret('thinker')
    assert (agent_1.belief['dummy'].values()[0] == REF_B1[3])
    assert (agent_1.inert == REF_I1[3])

    agent_1.revive()
    assert (agent_1.inert == False)

    agent_1.pump('small heart')
    agent_1.interpret('thinker X')
    assert (agent_1.belief['dummy'].values()[0] == REF_B2[0])
    assert (agent_1.inert == REF_I2[0])
    agent_1.pump('small heart')
    agent_1.interpret('thinker X')
    assert (agent_1.belief['dummy'].values()[0] == REF_B2[1])
    assert (agent_1.inert == REF_I2[1])
    agent_1.pump('small heart')
    agent_1.interpret('thinker X')
    assert (agent_1.belief['dummy'].values()[0] == REF_B2[2])
    assert (agent_1.inert == REF_I2[2])
    agent_1.pump('small heart')
    agent_1.interpret('thinker X')
    assert (agent_1.belief['dummy'].values()[0] == REF_B2[3])
    assert (agent_1.inert == REF_I2[3])
    agent_1.pump('small heart')
    agent_1.interpret('thinker X')
    assert (agent_1.belief['dummy'].values()[0] == REF_B2[4])
    assert (agent_1.inert == REF_I2[4])
Beispiel #13
0
def test_main():
    #
    # Define Messages
    #
    buzz = Buzz('nerve_endings', ('first', 'second'))
    belief_1 = Belief('chance_of_rain', ('probability', ))
    belief_2 = Belief('ambiguity_kills_me', ('mood', ))
    direction = Direction('get_which_umbrella', ('any', 'colour'))

    #
    # Define Scaffold and Map for it
    #
    agent_resources = Resource('internal_resource', ('energy', ))
    agent_resources.set_values([100.0])
    change_energy = ResourceMap('adjust_energy', 'delta', 'energy',
                                ('how_much', ))

    #
    # Define Organs and their associated messages
    #
    interpreter_1 = Interpreter('will_it_rain',
                                rain_predictor,
                                buzz,
                                belief_1,
                                resource_map_output=change_energy)
    interpreter_2 = Interpreter('am_i_unlucky',
                                mood_maker,
                                belief_1,
                                belief_2,
                                resource_map_output=change_energy)
    total_belief = MessageOperator([belief_1, belief_2], extend=True)
    moulder = Moulder('fetch_umbrella_type', make_decision, total_belief,
                      direction, change_energy)

    #
    # Initialize Agent
    #
    agent = Agent('test_agent', strict_engine=True)
    agent._set('buzz', 'nerve_endings', buzz)
    agent.set_organ(moulder)
    agent.set_organ(interpreter_1)
    agent.set_organ(interpreter_2)
    agent.set_scaffold(agent_resources)

    #
    # Decide on direction and execute action
    #
    agent.buzz['nerve_endings'].set_values([0.2, 0.2])
    agent.interpret('will_it_rain')
    agent.interpret('am_i_unlucky')
    agent.mould('fetch_umbrella_type')
    assert (agent.direction['get_which_umbrella'].values() == REF[0])
    assert (agent.resource.values()[0] == pytest.approx(REF_RESOURCE[0]))

    agent.buzz['nerve_endings'].set_values([1.0, 0.6])
    agent.interpret('will_it_rain')
    agent.interpret('am_i_unlucky')
    agent.mould('fetch_umbrella_type')
    assert (agent.direction['get_which_umbrella'].values() == REF[1])
    assert (agent.resource.values()[0] == pytest.approx(REF_RESOURCE[1]))

    agent.buzz['nerve_endings'].set_values([1.0, 2.6])
    agent.interpret('will_it_rain')
    agent.interpret('am_i_unlucky')
    agent.mould('fetch_umbrella_type')
    assert (agent.direction['get_which_umbrella'].values() == REF[2])
    assert (agent.resource.values()[0] == pytest.approx(REF_RESOURCE[2]))
'''
import pytest

from fjarrsyn.core.agent import Agent
from fjarrsyn.core.agent_ms import AgentManagementSystem
from fjarrsyn.core.graph import Node

import networkx as nx


class LocalEnv(object):
    def __init__(self, value):
        self.value = value


agent_1 = Agent('The first')
agent_2 = Agent('The second')
agent_3 = Agent('The third')
node_1 = Node('N1', agent_1, LocalEnv(1))
node_2 = Node('N2', agent_2, LocalEnv(2))
node_3 = Node('N3', agent_3, LocalEnv(3))
node_4 = Node('N4', None, LocalEnv(4))
node_5 = Node('N5', None, LocalEnv(5))
node_6 = Node('N6', None, LocalEnv(6))
nodes = [node_1, node_2, node_3, node_4, node_5, node_6]
agraph = nx.generators.classic.cycle_graph(nodes)

ams = AgentManagementSystem('cycle', [agent_1, agent_2, agent_3],
                            full_agents_graph=agraph)

ams.switch_node_content(node_1, node_2, switch_agent=True, switch_aux=True)
def test_main():

    buzz = Buzz('nose_tingle', ['nerve_1', 'nerve_2'])
    sensor = Sensor('smell_the_roses', smeller, buzz)
    belief = Belief('world_blossoms', ['certainty'])
    interpreter = Interpreter('does_the_world_blossom', nerve_analyzer, buzz,
                              belief)
    direction = Direction('words_to_say', ['first_word', 'second_word'])
    moulder = Moulder('what_to_say', word_smith, belief, direction)
    actuator = Actuator('say_it',
                        speak,
                        direction,
                        actuator_func_kwargs={'well': True})

    agent = Agent('simple human', strict_engine=True)
    agent.set_organs(sensor, interpreter, moulder, actuator)

    agent.sense('smell_the_roses')
    agent.interpret('does_the_world_blossom')
    agent.mould('what_to_say')
    agent.act('say_it')

    agent.sense('smell_the_roses')
    agent.interpret('does_the_world_blossom')
    agent.mould('what_to_say')
    agent.act('say_it')

    agent.sense('smell_the_roses')
    agent.interpret('does_the_world_blossom')
    agent.mould('what_to_say')
    agent.act('say_it')

    agent.sense('smell_the_roses')
    agent.interpret('does_the_world_blossom')
    agent.mould('what_to_say')
    agent.act('say_it')

    agent.sense('smell_the_roses')
    agent.interpret('does_the_world_blossom')
    agent.mould('what_to_say')
    agent.act('say_it')

    assert (read_env() == REF)
Beispiel #16
0
def test_main():
    #
    # Define Messages
    #
    belief_input_1 = Belief('hostile_neighbourhood', ['hostility_index'])
    belief_input_2 = Belief('i_am_followed', ['probability'])

    belief_output = Belief('i_am_about_to_be_mugged', ['best_guess'])

    belief_merge_input = MessageOperator([belief_input_1, belief_input_2],
                                         extend=True)
    #
    # Define Organs and their associated messages
    #
    interpreter = Interpreter('about_to_be_mugged', evaluate,
                              belief_merge_input, belief_output)

    #
    # Initialize Agent
    #
    agent = Agent('test_agent', strict_engine=True)
    agent.set_organ(interpreter)
    agent._set('belief', 'hostile_neighbourhood', belief_input_1)
    agent._set('belief', 'i_am_followed', belief_input_2)

    belief_input_1.set_values(0.8)
    belief_input_2.set_values(0.95)
    agent.interpret('about_to_be_mugged')
    outcome_1 = agent.belief['i_am_about_to_be_mugged'].values()

    belief_input_1.set_values(0.0)
    belief_input_2.set_values(0.0)
    agent.interpret('about_to_be_mugged')
    outcome_2 = agent.belief['i_am_about_to_be_mugged'].values()

    belief_input_1.set_values(0.9)
    belief_input_2.set_values(1.0)
    agent.interpret('about_to_be_mugged')
    outcome_3 = agent.belief['i_am_about_to_be_mugged'].values()

    assert (outcome_1[0] == REFVALUES[0])
    assert (outcome_2[0] == REFVALUES[1])
    assert (outcome_3[0] == REFVALUES[2])
def test_main():
    #
    # Define Messages
    #
    belief = Belief('rich_environment',
                    ('stuff_1', 'stuff_2', 'stuff_3', 'stuff_4'))
    belief.set_values([0.7, 0.3, 0.6, 0.1])
    direction1 = Direction('grab_this_much', ('grab_volume', ))
    direction2 = Direction('shout_loud', ('volume', ))

    #
    # Define Scaffold and Map for it
    #
    agent_resources = Resource('internal_resource',
                               ('internal_energy', 'carrot', 'leek'))
    agent_resources.set_values([100.0, 4, 5])
    change_energy = ResourceMap('adjust_energy', 'delta', 'internal_energy',
                                ('expend_energy', ))
    change_carrot = ResourceMap('adjust_carrot', 'delta', 'carrot',
                                ('tweak_carrot', ))
    change_leek = ResourceMap('adjust_leek', 'delta', 'leek', ('tweak_leek', ))
    hoarding_food = MapCollection([change_carrot, change_leek])

    #
    # Define Organs and their associated messages
    #
    moulder1 = Moulder('reach_and_grab', make_decision, belief, direction1,
                       change_energy)
    moulder2 = Moulder('shout_how_much', shouter, belief, direction2)

    env = Env()
    actuator1 = Actuator('grab_it', env.grabber, direction1, hoarding_food)
    actuator2 = Actuator('shout', env.shout_into_void, direction2)

    #
    # Initialize Agent
    #
    agent = Agent('test_agent', strict_engine=True)
    agent.set_organ(moulder1)
    agent.set_organ(moulder2)
    agent.set_organ(actuator1)
    agent.set_organ(actuator2)
    agent.set_scaffold(agent_resources)

    #
    # Decide on direction and execute action
    #
    agent.mould('reach_and_grab')
    agent.act('grab_it')

    assert (agent.resource.values() == REF_RESOURCE_OUTCOME)

    agent.mould('shout_how_much')
    agent.act('shout')
    agent.mould('shout_how_much')
    agent.act('shout')

    assert (isclose(env.loud_cumsum, 3.4))

    try:
        agent.act('shout')
        raise AssertionError(
            'Action without preceding moulding did not raise exception')
    except EmptyFlashError:
        pass
    else:
        raise AssertionError(
            'Action without preceding moulding did not raise expected exception'
        )
Beispiel #18
0
def test_main():

    # Not fully implemented
    assert 1==2

    battery = Resource('battery power', ('potential',))
    battery.set_values(0.401)
    suck_power = ResourceMap('suck power', 'delta', 'potential', ('reduction',))
    b1 = Buzz('sound stimulation', ('band_1', 'band_2', 'band_3'))
    s1 = Sensor('sound in surrounding', listen, b1, suck_power)
    belief_1 = Belief('The word was spoken', ('probability',))
    int1 = Interpreter('Was the word spoken?', word_estimator, b1, belief_1)
    dir_1 = Direction('follow up request', ('word_section_1', 'word_section_2',
                                            'word_section_3', 'word_section_4'))
    moul1 = Moulder('What response to give', responder, belief_1, dir_1)
    a1 = Actuator('loudspeaker vibrations', loudspeaker_api, dir_1, suck_power)
    moul2 = Moulder('Select warn statement', warn_statement, None, dir_1,
                    resource_op_input=battery)

    bc = AutoBeliefCondition('Sufficiently confident of word spoken',
                             lambda p: p > 0.75, 'The word was spoken')
    rc = AutoResourceCondition('Sufficient power left',
                               lambda pot: pot > 0.2, 'potential')
    clausul_1 = Clause('listen for the word',
                       [('sense', 'sound in surrounding'),
                        ('interpret', 'Was the word spoken?')],
                       condition=bc)

    clausul_2 = Clause('say something to the user',
                       [('mould', 'What response to give'),
                        ('act', 'loudspeaker vibrations')])
    clausul_3 = Clause('power check', condition=rc)
    clausul_4 = Clause('power warn',
                       [('mould', 'Select warn statement'),
                        ('act', 'loudspeaker vibrations')])

    plan = Plan('Clever stuff')
    plan.add_cargo('pronounce', 'listen for the word')
    plan.add_cargo('pronounce', 'say something to the user')
    plan.add_cargo('pronounce', 'power check')
    plan.add_cargo('pronounce', 'power warn')
    plan.add_dependency(2, 0, 3)
    plan.add_dependency(0, 1)
    plan.stamp_and_approve()

    agent = Agent('smart loudspeaker')
    agent.set_organs(s1, int1, moul1, moul2, a1)
    agent.set_messages(b1, belief_1, dir_1)
    agent.set_scaffold(battery)
    agent.set_policies(clausul_1, clausul_2, clausul_3, clausul_4, plan)

    agent.enact('Clever stuff')
    agent.enact('Clever stuff')
    agent.enact('Clever stuff')
    agent.enact('Clever stuff')
Beispiel #19
0
def test_main():

    agent_core = Agent('Coordinator')
    essence = Essence('Coordinator Essence', ('param_1', 'param_2', 'param_3',
                                              'param_4', 'param_5', 'param_6'))
    essence.set_values([1.0,2.0,3.0,4.0,5.0,6.0])
    resource = Resource('Coordinator Resource', ('Energy Status',))
    resource.set_values([75.0])
    agent_core.set_scaffolds(essence, resource)

    agents = [agent_core]
    nodes = [Node('Central', agent_core)]

    for k in range(4):
        agent = Agent('Sensor Leaf %s' %(str(k)), strict_engine=True)
        essence = Essence('Sensor Essence', ('Sensitivity', 'Quality'))
        essence.set_values([78.0 + float(k), 99.0])
        resource = Resource('Sensor Resource', ('Battery Power',))
        resource.set_values([100.0 - 3.0 * k])
        buzz = Buzz('Power Spectrum Sample', ('amplitude_max', 'freq_mode'))
        belief = Belief('Is There Motion', ('size', 'speed'))
        motion_classifier = Interpreter('From Freq to Object', pw2obj, buzz, belief)
        agent.set_scaffolds(essence, resource)
        agent.set_messages(buzz, belief)
        agent.set_organ(motion_classifier)

        agents.append(agent)
        nodes.append(Node('Sensor', agent, LocalEnv(k * k)))

    nodes.append(Node('dummy', None))
    nodes.append(Node('dummy', None))

    star_graph = nx.generators.classic.star_graph(nodes)

    ams = House('A House', agents, star_graph)
    for node in ams:
        agent = node.agent_content
        if not agent is None:
            if 'Is There Motion' in agent.belief:
                agent.sense('Feel microwaves')
                agent.interpret('From Freq to Object')

    central_a_sampler = AgentSampler('central_sampler',
                                     essence_args=[('Coordinator Essence', 'param_2'),
                                                   ('Coordinator Essence', 'param_6')],
                                     resource_args=[('Coordinator Resource', 'Energy Status')],
                                     agent_matcher=_match_c)
    leaf_a_sampler = AgentSampler('leaf_sampler',
                                  resource_args=[('Sensor Resource', 'Battery Power')],
                                  belief_args=[('Is There Motion', 'size'),
                                               ('Is There Motion', 'speed')],
                                  agent_matcher=_match_l)
    env_sampler = EnvSampler('env_sampler', env_stuff, agent_matcher=_match_l)
    graph_sampler = GraphSampler('g_sampler', lambda x: x.name)

    io = SystemIO()
    io.set_write_rule('central', central_a_sampler, 'to_csv')
    io.set_write_rule('leaf', leaf_a_sampler, 'to_csv')
    io.set_write_rule('env', env_sampler, 'to_json')
    io.set_write_rule('graph_props', graph_sampler, 'gexf.write_gexf')

    io.try_stamp(ams, 0)

    exist_1 = os.path.isfile('central0.csv')
    exist_2 = os.path.isfile('leaf0.csv')
    exist_3 = os.path.isfile('env0.json')
    exist_4 = os.path.isfile('graph_props0.gexf')
    assert (exist_1)
    assert (exist_2)
    assert (exist_3)
    assert (exist_4)

    if exist_1:
        data = open('central0.csv').read()
        assert ('essence:Coordinator Essence:param_2,2.0' in data)
        assert ('essence:Coordinator Essence:param_6,6.0' in data)
        assert (not 'essence:Coordinator Essence:param_1' in data)
        assert (not 'essence:Coordinator Essence:param_3' in data)
        assert (not 'essence:Coordinator Essence:param_4' in data)
        assert (not 'essence:Coordinator Essence:param_5' in data)
        assert ('resource:Coordinator Resource:Energy Status,75.0' in data)
        os.remove('central0.csv')

    if exist_2:
        data = open('leaf0.csv').read()
        assert ('0,Sensor Leaf 0,' in data)
        assert ('0,Sensor Leaf 1,' in data)
        assert ('0,Sensor Leaf 2,' in data)
        assert ('0,Sensor Leaf 3,' in data)
        assert ('belief:Is There Motion:size,small' in data)
        assert (not 'belief:Is There Motion:size,large' in data)
        assert ('belief:Is There Motion:speed,fast' in data)
        assert ('belief:Is There Motion:speed,slow' in data)
        assert ('belief:Is There Motion:speed,n/a' in data)
        os.remove('leaf0.csv')

    if exist_3:
        data = open('env0.json').read()
        assert ('"[0,"Sensor Leaf 0"' in data)
        assert ('"[0,"Sensor Leaf 1"' in data)
        assert ('"[0,"Sensor Leaf 2"' in data)
        assert ('"[0,"Sensor Leaf 3"' in data)
        assert ('"env_stuff"]":0' in data)
        assert ('"env_stuff"]":1' in data)
        assert ('"env_stuff"]":4' in data)
        assert ('"env_stuff"]":9' in data)
        os.remove('env0.json')

    if exist_4:
        data = open('graph_props0.gexf').read().split('\n')
        REFS = ['Sensor_0', 'Sensor_1', 'Sensor_2', 'Sensor_3',
                'unoccupied_0', 'unoccupied_1']
        for row in data:
            if '<edge ' in row:
                assert ('"Central"' in row)
                for r in REFS:
                    if r in row:
                        REFS.remove(r)
                        break
                else:
                    raise AssertionError('Missed node %s' %(r))
        assert (len(REFS) == 0)
        os.remove('graph_props0.gexf')
Beispiel #20
0
def test_main():
    a1 = Agent('A1')
    a2 = Agent('A2')
    ams = ABC('dummy', [a1, a2], 1, 2)

    a1.create_socket('tester', 'sense', 'S1', True)
    a1.socket_offered['tester'].whitelist.add(a2.agent_id_system)
    SOCK1 = [('tester', a1.socket_offered['tester'].token)]

    a2.create_socket('tester', 'sense', 'S2', True)
    a2.socket_offered['tester'].whitelist.add(a1.agent_id_system)
    SOCK2 = [('tester', a2.socket_offered['tester'].token)]

    #
    # Agent 1 connects to socket of Agent 2 and executes
    #
    ttt1 = SOCK2[0][1]
    conn = a1.connect_to(a2, 'tester', ttt1)
    conn.execute()
    conn.close()

    assert (a2.buzz['stuff'].values()[0] == 2)

    a2.sense('S2')
    assert (a2.buzz['stuff'].values()[0] == 2)

    try:
        v = a1.buzz['stuff'].values()
        raise AssertionError('Agent 1 Buzz non-empty despite not executed')
    except EmptyFlashError:
        pass

    a1.sense('S1')
    assert (a1.buzz['stuff'].values()[0] == 1)

    try:
        conn = a2.connect_to(a1, 'tester', -1)
        raise AssertionError('Faulty token not caught')
    except SocketConnectionError:
        pass

    try:
        conn.execute()
        raise AssertionError('Did raise exception with unopened connection')
    except RuntimeError:
        pass