def birth(self, payload, agent_index):

        node_parent = self.get(agent_index, get_node=True)
        node = Node('child', None, SimpleEnv())
        self.agents_graph.add_node(node)
        self.agents_graph.add_edge(node, node_parent)
        self.situate(payload, node)
Exemple #2
0
def create_new_world():

    #
    # Define the spatial arrangement
    #
    if NETWORK_TYPE == '2d grid lattice':
        network = nx.generators.lattice.grid_2d_graph(SQRT_N_AGENTS,
                      SQRT_N_AGENTS, periodic=True)

    elif NETWORK_TYPE == 'cube lattice':
        network = nx.generators.lattice.grid_graph([CUBE_N_AGENTS,
                                                    CUBE_N_AGENTS,
                                                    CUBE_N_AGENTS],
                                                    periodic=True)

    elif NETWORK_TYPE == 'small world':
        network = nx.generators.random_graphs.connected_watts_strogatz_graph(TOTAL_AGENTS,
                      4, 0.25)

    else:
        raise RuntimeError('Unknown network type: {0}'.format(NETWORK_TYPE))

    #
    # Define agent intentions
    #
    agent_policy = UnitPolicy('One Heartbeat Step', THRS_INFO_TO_SPLIT,
                              THRS_BAD_INFO_DEATH)

    #
    # Place agents in spatial arrangement and assing them intentions
    #
    agents = []
    mapping = {}
    for k_agent, coord in enumerate(network.nodes()):
        init_essence = INIT_ESSENCE_POOL[np.random.randint(len(INIT_ESSENCE_POOL))]
        agent_x = Unit('Agent', *init_essence)
        agent_x.set_policies(*agent_policy.all)
        agents.append(agent_x)

        env_x = AgentAuxEnv(0.0, 0.0, 0.0, 0.0, ENV_DECAY_INVERSE)
        node = Node('{0}'.format(k_agent), agent_x, env_x)

        mapping[coord] = node

    network = nx.relabel_nodes(network, mapping)

    #
    # Define the world
    #
    ww = World('Agent World', agents, network,
               MID_MAX_MOVE, MAX_MAX_MOVE, MUT_PROB,
               RESOURCE_JUMP_MAG, RESOURCE_JUMP_PROB,
               MUT_ESSENCE)

    return ww
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)
def test_main():

    a1 = Bacteria('bacteria 1', 1.0, 1.0, 10.0, 10.0, 0.5, 0.5)
    a2 = Bacteria('bacteria 2', 1.0, 0.5, 5.0, 6.0, 0.5, 0.5)
    a3 = Bacteria('bacteria 3', 1.1, 0.3, 10.0, 2.0, 0.9, 0.1)
    e1 = Env('environment 1', 0.1, 0.1)
    e2 = Env('environment 2', 0.2, 0.2)
    e3 = Env('environment 3', 0.3, 0.3)
    n1 = Node('first', a1, e1)
    n2 = Node('second', a2, e2)
    n3 = Node('third', a3, e3)

    a_graph = nx.Graph()
    a_graph.add_edge(n1, n2)
    a_graph.add_edge(n2, n3)

    env_sampler = EnvSampler('feel_the_env', _get_data)
    g_sampler = GraphSampler('connections')

    mess = AgentManagementSystem('3 bacteria', [a1, a2, a3], a_graph)
    mess.set_sampler(a1.sampler['full_state'])
    mess.set_sampler(env_sampler)
    mess.set_sampler(g_sampler)

    x1 = a1.sample('full_state')
    x2 = a2.sample('full_state')
    x3 = a3.sample('full_state')

    y1 = mess.sample('full_state')
    y2 = mess.sample('feel_the_env')
    y3 = mess.sample('connections')

    assert (x1.shape == (6, 1))
    assert (x2.shape == (6, 1))
    assert (x3.shape == (6, 1))
    assert (x1.index.nlevels == 4)
    assert (x2.index.nlevels == 4)
    assert (x3.index.nlevels == 4)
    v1 = x1.loc[(slice(None), slice(None), slice(None),
                 'belief:Bacteria Belief:B1'), 'value'].values[0]
    v2 = x1.loc[(slice(None), slice(None), slice(None),
                 'belief:Bacteria Belief:B2'), 'value'].values[0]
    v3 = x1.loc[(slice(None), slice(None), slice(None),
                 'essence:Bacteria Essence:E1'), 'value'].values[0]
    v4 = x1.loc[(slice(None), slice(None), slice(None),
                 'essence:Bacteria Essence:E2'), 'value'].values[0]
    v5 = x1.loc[(slice(None), slice(None), slice(None),
                 'resource:Bacteria Resource:R1'), 'value'].values[0]
    v6 = x1.loc[(slice(None), slice(None), slice(None),
                 'resource:Bacteria Resource:R2'), 'value'].values[0]
    assert (v1 == 0.5)
    assert (v2 == 0.5)
    assert (v3 == 1.0)
    assert (v4 == 1.0)
    assert (v5 == 10.0)
    assert (v6 == 10.0)
    v1 = x2.loc[(slice(None), slice(None), slice(None),
                 'belief:Bacteria Belief:B1'), 'value'].values[0]
    v2 = x2.loc[(slice(None), slice(None), slice(None),
                 'belief:Bacteria Belief:B2'), 'value'].values[0]
    v3 = x2.loc[(slice(None), slice(None), slice(None),
                 'essence:Bacteria Essence:E1'), 'value'].values[0]
    v4 = x2.loc[(slice(None), slice(None), slice(None),
                 'essence:Bacteria Essence:E2'), 'value'].values[0]
    v5 = x2.loc[(slice(None), slice(None), slice(None),
                 'resource:Bacteria Resource:R1'), 'value'].values[0]
    v6 = x2.loc[(slice(None), slice(None), slice(None),
                 'resource:Bacteria Resource:R2'), 'value'].values[0]
    assert (v1 == 0.5)
    assert (v2 == 0.5)
    assert (v3 == 1.0)
    assert (v4 == 0.5)
    assert (v5 == 5.0)
    assert (v6 == 6.0)
    v1 = x3.loc[(slice(None), slice(None), slice(None),
                 'belief:Bacteria Belief:B1'), 'value'].values[0]
    v2 = x3.loc[(slice(None), slice(None), slice(None),
                 'belief:Bacteria Belief:B2'), 'value'].values[0]
    v3 = x3.loc[(slice(None), slice(None), slice(None),
                 'essence:Bacteria Essence:E1'), 'value'].values[0]
    v4 = x3.loc[(slice(None), slice(None), slice(None),
                 'essence:Bacteria Essence:E2'), 'value'].values[0]
    v5 = x3.loc[(slice(None), slice(None), slice(None),
                 'resource:Bacteria Resource:R1'), 'value'].values[0]
    v6 = x3.loc[(slice(None), slice(None), slice(None),
                 'resource:Bacteria Resource:R2'), 'value'].values[0]
    assert (v1 == 0.9)
    assert (v2 == 0.1)
    assert (v3 == 1.1)
    assert (v4 == 0.3)
    assert (v5 == 10.0)
    assert (v6 == 2.0)

    assert (y1.shape == (18, 1))
    assert (y1.index.nlevels == 4)
    assert (y1.index.levshape == (1, 3, 3, 6))
    ident = y1 == pd.concat([x1, x2, x3])
    assert (all(ident.values))

    assert (y2.shape == (6, 1))
    assert (y2.index.levshape == (1, 3, 3, 2))
    v1 = y2.loc[(slice(None), 'bacteria 1', slice(None), 'env_data_1'),
                'value'].values[0]
    v2 = y2.loc[(slice(None), 'bacteria 1', slice(None), 'env_data_2'),
                'value'].values[0]
    v3 = y2.loc[(slice(None), 'bacteria 2', slice(None), 'env_data_1'),
                'value'].values[0]
    v4 = y2.loc[(slice(None), 'bacteria 2', slice(None), 'env_data_2'),
                'value'].values[0]
    v5 = y2.loc[(slice(None), 'bacteria 3', slice(None), 'env_data_1'),
                'value'].values[0]
    v6 = y2.loc[(slice(None), 'bacteria 3', slice(None), 'env_data_2'),
                'value'].values[0]
    assert (v1 == 0.1)
    assert (v2 == 0.1)
    assert (v3 == 0.2)
    assert (v4 == 0.2)
    assert (v5 == 0.3)
    assert (v6 == 0.3)

    REF = [
        sorted((a1.agent_id_system, a2.agent_id_system)),
        sorted((a2.agent_id_system, a3.agent_id_system))
    ]
    for ee in y3.edges:
        canonical = sorted(ee)
        assert (canonical in REF)
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)
node_x = ams.get(agent_1.agent_id_system, get_node=True)
node_y = ams.get(agent_2.agent_id_system, get_node=True)
Exemple #6
0
df_e = pd.read_csv(env_file)
gg_e = df_e.groupby('agent_index')
envs = {}
for a_id, e_data in gg_e:
    r_container = {}
    for _, row in e_data.iterrows():
        dd = row.to_dict()
        r_container[dd['variable']] = dd['value']
    env = AgentAuxEnv(**r_container)

    envs[a_id] = env

nodes = {}
for a_id in agents:
    nn = Node('', agents[a_id], envs[a_id])
    nodes[a_id] = nn

graph = nx.Graph()
graph.add_nodes_from(nodes.values())
fin = open(graph_file)
lines = fin.read().split('\n')
for line in lines[:-1]:
    xx = line.split(' ')
    n1 = nodes[xx[0]]
    n2 = nodes[xx[1]]
    graph.add_edge(n1, n2)

ww = World('dummy', agents.values(), graph, 0.0, 0.0, 0.0, 0.0, 0.0, [])
print(ww)
Exemple #7
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')
Exemple #8
0
    def __init__(self,
                 name,
                 agents,
                 full_agents_graph=None,
                 agent_env=None,
                 common_env=None,
                 strict_engine=False):

        self.name = name
        self.strict_engine = strict_engine

        #
        # The agent to agent network relation is defined, which is a complete
        # graph in case nothing specific is given.
        #
        if full_agents_graph is None:
            if not agent_env is None:
                if (not isinstance(agent_env, Iterable)) or isinstance(
                        agent_env, str):
                    agent_envs = [agent_env] * len(agents)

                else:
                    if len(agent_env) != len(agents):
                        raise ValueError('An iterable of agent environments ' + \
                                         'of wrong length %s' %(str(len(agent_env))))

                    agent_envs = agent_env

            else:
                agent_envs = [None] * len(agents)

            nodes = []
            for k, (agent, agent_env) in enumerate(zip(agents, agent_envs)):
                nodes.append(Node('agent_%s' % (str(k)), agent, agent_env))
            self.agents_graph = nx.complete_graph(nodes)

        #
        # If a network is given it is assumed to contain all objects, and hence
        # swapped directly into the graph attribute
        #
        else:
            if isinstance(full_agents_graph, nx.Graph):
                self.agents_graph = full_agents_graph

            else:
                raise TypeError('Agent Management System given graph not ' + \
                                'of the Graph class')

        self.agents_graph.name = 'Agents Graph of System %s' % (self.name)

        self.common_env = common_env

        #
        # The agents are added to the system book keeping
        #
        self.agents_in_scope = OrderedDict()
        for agent in agents:
            self.bookkeep(agent)

        #
        # Initialize the look-up table for agent index and node. Provides
        # considerable speed up
        #
        self.node_from_agent_id_ = {}
        for node in self.agents_graph:
            if not node.agent_content is None:
                self.node_from_agent_id_[
                    node.agent_content.agent_id_system] = node

        #
        # Initialize verbs for the Agent System
        #
        self.compulsion = {}
        self.mutation = {}
        self.law = {'compulsion': self.compulsion, 'mutation': self.mutation}
        self.lawbook = {}

        #
        # Initialize system samplers
        #
        self.sampler = {}

        #
        # Initialize system dynamics
        #
        self.mover = {}
Exemple #9
0
def load_old_world(load_dir):

    #
    # Saved files
    #
    agent_file = load_dir + '/save_agent_state0.csv'
    env_file = load_dir + '/save_env_state0.csv'
    graph_file = load_dir + '/save_graph_state0.edgelist'

    #
    # Define agent intentions
    #
    agent_policy = UnitPolicy('One Heartbeat Step', THRS_INFO_TO_SPLIT,
                              THRS_BAD_INFO_DEATH)

    #
    # Create populated Agents
    #
    df_a = pd.read_csv(agent_file)
    gg_a = df_a.groupby('agent_index')
    agents = {} 
    for a_id, a_data in gg_a:
        belief_d = {}
        essence_d = {}
        resource_d = {}

        agent = Unit('Agent', agent_id=a_id)
        for _, row in a_data.iterrows():
            dd = row.to_dict()
            xx = dd['variable'].split(':')

            if xx[0] == 'belief':
                belief_d[(xx[1], xx[2])] = dd['value']
            if xx[0] == 'essence':
                essence_d[xx[2]] = dd['value']
            if xx[0] == 'resource':
                resource_d[xx[2]] = dd['value']

        essence_val = []
        for e_key in agent.essence.keys():
            essence_val.append(essence_d[e_key])

        resource_val = []
        for r_key in agent.resource.keys():
            resource_val.append(resource_d[r_key])

        belief_val = []
        for b_key_1 in agent.belief:
            for b_key_2 in agent.belief[b_key_1].keys():
                belief_val.append(belief_d[(b_key_1, b_key_2)])

        agent.essence.set_values(essence_val)
        agent.resource.set_values(resource_val)
        agent.belief[b_key_1].set_values(belief_val)
        agent.set_policies(*agent_policy.all)

        agents[a_id] = agent

    #
    # Create populated environments
    #
    df_e = pd.read_csv(env_file)
    gg_e = df_e.groupby('agent_index')
    envs = {}
    for a_id, e_data in gg_e:
        r_container = {}
        for _, row in e_data.iterrows():
            dd = row.to_dict()
            r_container[dd['variable']] = dd['value']
        env = AgentAuxEnv(**r_container)

        envs[a_id] = env

    #
    # Make Nodes
    #
    nodes = {}
    for a_id in agents:
        nn = Node('', agents[a_id], envs[a_id])
        nodes[a_id] = nn

    #
    # Make the Graph
    #
    graph = nx.Graph()
    graph.add_nodes_from(nodes.values())
    fin = open(graph_file)
    lines = fin.read().split('\n')
    for line in lines[:-1]:
        xx = line.split(' ')
        if 'unocc' in xx[0]:
            n1 = Node('', None, AgentAuxEnv(0.0, 0.0, 0.0, 0.0, ENV_DECAY_INVERSE)) 
        else:
            n1 = nodes[xx[0]]
        if 'unocc' in xx[1]:
            n2 = Node('', None, AgentAuxEnv(0.0, 0.0, 0.0, 0.0, ENV_DECAY_INVERSE)) 
        else:
            n2 = nodes[xx[1]]
        graph.add_edge(n1, n2)

    ww = World('Agent World', agents.values(), graph,
               MID_MAX_MOVE, MAX_MAX_MOVE, MUT_PROB,
               RESOURCE_JUMP_MAG, RESOURCE_JUMP_PROB,
               MUT_ESSENCE)

    return ww