示例#1
0
def test_neighbors_with_torus():

    model = ap.Model()
    agents = ap.AgentList(model, 5)
    grid = ap.Grid(model, (4, 4), torus=True)
    grid.add_agents(agents, [[0, 0], [1, 3], [2, 0], [3, 2], [3, 3]])

    grid.apply(len).tolist()

    assert list(grid.neighbors(agents[0]).id) == [5, 2]

    model = ap.Model()
    agents = ap.AgentList(model, 5)
    grid = ap.Grid(model, (4, 4), torus=True)
    grid.add_agents(agents, [[0, 1], [1, 3], [2, 0], [3, 2], [3, 3]])

    grid.apply(len).tolist()

    assert list(grid.neighbors(agents[0]).id) == [4]
    assert list(grid.neighbors(agents[1]).id) == [3]

    for d in [2, 3, 4]:

        model = ap.Model()
        agents = ap.AgentList(model, 5)
        grid = ap.Grid(model, (4, 4), torus=True)
        grid.add_agents(agents, [[0, 1], [1, 3], [2, 0], [3, 2], [3, 3]])

        grid.apply(len).tolist()

        assert list(grid.neighbors(agents[0], distance=d).id) == [2, 3, 4, 5]
        assert list(grid.neighbors(agents[1], distance=d).id) == [1, 3, 4, 5]
示例#2
0
def test_add_agents():

    # Add agents to existing nodes
    graph = nx.Graph()
    graph.add_node(0)
    graph.add_node(1)
    model = ap.Model()

    env = ap.Network(model, graph=graph)
    agents = ap.AgentList(model, 2)
    env.add_agents(agents, positions=env.nodes)
    for agent in agents:
        agent.pos = env.positions[agent]
    agents.node = env.nodes
    env.graph.add_edge(*agents.pos)

    # Test structure
    assert list(agents.pos) == list(agents.node)
    assert env.nodes == env.graph.nodes()
    assert list(env.graph.edges) == [tuple(agents.pos)]
    assert list(env.neighbors(agents[0]).id) == [3]

    # Add agents as new nodes
    model2 = ap.Model()
    agents2 = ap.AgentList(model2, 2)
    env2 = ap.Network(model2)
    env2.add_agents(agents2)
    for agent in agents2:
        agent.pos = env2.positions[agent]
    env2.graph.add_edge(*agents2.pos)

    # Test if the two graphs are identical
    assert env.graph.nodes.__repr__() == env2.graph.nodes.__repr__()
    assert env.graph.edges.__repr__() == env2.graph.edges.__repr__()
示例#3
0
def test_move_torus():
    model = ap.Model()
    agents = ap.AgentList(model, 1)
    agent, = agents
    grid = ap.Grid(model, (4, 4), torus=True)
    grid.add_agents(agents, [[0, 0]])

    assert grid.positions[agent] == (0, 0)
    grid.move_by(agent, [-1, -1])
    assert grid.positions[agent] == (3, 3)
    grid.move_by(agent, [1, 0])
    assert grid.positions[agent] == (0, 3)
    grid.move_by(agent, [0, 1])
    assert grid.positions[agent] == (0, 0)

    model = ap.Model()
    agents = ap.AgentList(model, 1)
    agent, = agents
    grid = ap.Grid(model, (4, 4), torus=False)
    grid.add_agents(agents, [[0, 0]])

    assert grid.positions[agent] == (0, 0)
    grid.move_by(agent, [-1, -1])
    assert grid.positions[agent] == (0, 0)
    grid.move_by(agent, [6, 6])
    assert grid.positions[agent] == (3, 3)
示例#4
0
def test_add_agents():

    # Add agents to existing nodes
    graph = nx.Graph()
    graph.add_node(0)
    graph.add_node(1)
    model = ap.Model()
    model.add_agents(2)
    model.add_network(graph=graph, agents=model.agents)
    model.env.graph.add_edge(model.agents[0], model.agents[1])
    assert list(model.agents[0].neighbors().id) == [2]

    # Add agents as new nodes
    model2 = ap.Model()
    agents = model2.add_agents(2)
    model2.add_network(agents=agents[0])  # Add at initialization
    model2.env.add_agents(agents[1])  # Add later
    model2.env.graph.add_edge(model2.agents[0], model2.agents[1])

    # Test if the two graphs are identical
    assert model.env.graph.nodes.__repr__() == model2.env.graph.nodes.__repr__(
    )
    assert model.env.graph.edges.__repr__() == model2.env.graph.edges.__repr__(
    )

    # Test errors
    model3 = ap.Model()
    graph = nx.Graph()
    model3.add_agents()
    with pytest.raises(ValueError):
        assert model3.add_network(graph=graph, agents=model3.agents)
    with pytest.raises(TypeError):
        assert model3.add_network(graph=1)
示例#5
0
def test_basics():
    model = ap.Model()
    l1 = ap.AgentList(model, 0)
    l2 = ap.AgentList(model, 1)
    l3 = ap.AgentList(model, 2)
    assert l1.__repr__() == "AgentList (0 objects)"
    assert l2.__repr__() == "AgentList (1 object)"
    assert l3.__repr__() == "AgentList (2 objects)"

    agentlist = ap.AgentList(model, 2)
    AgentDList = ap.AgentDList(model, 2)
    agentiter = ap.AgentIter(model, agentlist)
    AgentDListiter = ap.AgentDListIter(agentlist)
    attriter = agentiter.id

    assert np.array(agentlist).tolist() == list(agentlist)
    assert np.array(AgentDList).tolist() == list(AgentDList)
    assert np.array(agentiter).tolist() == list(agentiter)
    assert np.array(AgentDListiter).tolist() == list(AgentDListiter)
    assert np.array(attriter).tolist() == list(attriter)

    with pytest.raises(AgentpyError):
        _ = agentiter[2]  # No item lookup allowed

    # Seta and get attribute
    for agents in [agentlist, AgentDList, agentiter]:
        agents.x = 1
        agents.y = 1
        assert list(agents.x) == [1, 1]
        agents.x += agents.x
        assert list(agents.x) == [2, 2]
示例#6
0
def test_remove():
    model = ap.Model()
    agents = ap.AgentList(model, 2)
    grid = ap.Grid(model, (2, 2))
    grid.add_agents(agents)
    grid.remove_agents(agents[0])
    assert grid.apply(len).tolist() == [[0, 1], [0, 0]]

    # With track_empty
    model = ap.Model()
    agents = ap.AgentList(model, 2)
    grid = ap.Grid(model, (2, 2), track_empty=True)
    grid.add_agents(agents)
    assert list(grid.empty) == [(1, 1), (1, 0)]
    grid.remove_agents(agents[0])
    assert list(grid.empty) == [(1, 1), (1, 0), (0, 0)]
示例#7
0
def test_grid_iter():
    model = ap.Model()
    agents = ap.AgentList(model, 4)
    grid = ap.Grid(model, (2, 2))
    grid.add_agents(agents)
    assert len(grid.agents) == 4
    assert len(grid.agents[0:1, 0:1]) == 1
示例#8
0
def test_positions():
    model = ap.Model()
    grid = model.add_grid((2, 2))
    grid.add_agents(5)

    # Position reference
    a = model.agents[0]
    assert a.position() == (0, 0)
    assert a.position() is grid.position(a)  # By instance
    assert a.position() is grid.position(a.id)  # By id

    # Positions
    assert list(grid.positions()) == [(0, 0), (0, 1), (1, 0), (1, 1)]
    assert list(grid.positions([(0, 0), (0, 1)])) == [(0, 0), (0, 1)]

    # Get agents
    assert len(grid.get_agents()) == 5
    assert len(grid.get_agents([0, 0])) == 2  # Single pos
    assert len(grid.get_agents([(0, 0), (0, 1)])) == 3  # Area

    # Get items
    assert [x for x in grid.items()][0][0] == (0, 0)
    assert len([x for x in grid.items()][0][1]) == 2

    # Wrong area
    with pytest.raises(ValueError):
        assert grid.get_agents(1)
示例#9
0
def test_run_seed():
    """ Test random seed setting. """
    rd = random.Random(1)
    npseed = rd.getrandbits(128)
    nprd = np.random.default_rng(seed=npseed)
    n1 = rd.randint(0, 100)
    n2 = nprd.integers(100)

    model = ap.Model({'seed': 1})
    model.run(steps=0, display=False)
    assert model.random.randint(0, 100) == n1
    assert model.nprandom.integers(100) == n2
    model = ap.Model()
    model.run(seed=1, steps=0, display=False)
    assert model.random.randint(0, 100) == n1
    assert model.nprandom.integers(100) == n2
示例#10
0
def test_update_parameters():
    parameters = {'x': 1, 'y': 2}
    model = ap.Model(parameters)
    assert model.p == {'x': 1, 'y': 2}
    parameters2 = {'z': 4, 'y': 3}
    model.set_parameters(parameters2)
    assert model.p == {'x': 1, 'y': 3, 'z': 4}
示例#11
0
def test_attribute():
    model = ap.Model()
    model.add_grid((2, 2))
    model.env.add_agents(5)
    assert model.env.attribute('id') == [[8, 3], [4, 5]]
    assert model.env.attribute('id', sum_values=False) == [[[2, 6], [3]],
                                                           [[4], [5]]]
示例#12
0
def test_setup():
    """ Test setup() for all object types """
    class MySetup:
        def setup(self, a):
            self.a = a + 1

    class MyAgentType(MySetup, ap.Agent):
        pass

    class MySpaceType(MySetup, ap.Space):
        pass

    class MyNwType(MySetup, ap.Network):
        pass

    class MyGridType(MySetup, ap.Grid):
        pass

    model = ap.Model()
    agents = ap.AgentList(model, 1, b=1)
    agents.extend(ap.AgentList(model, 1, MyAgentType, a=1))
    model.S1 = MySpaceType(model, shape=(1, 1), a=2)
    model.G1 = MyGridType(model, shape=(1, 1), a=3)
    model.N1 = MyNwType(model, a=4)

    # Standard setup implements keywords as attributes
    # Custom setup uses only keyword a and adds 1
    assert agents[0].b == 1
    assert agents[1].a == 2
    assert model.S1.a == 3
    assert model.G1.a == 4
    assert model.N1.a == 5
示例#13
0
def test_apply():

    model = ap.Model()
    model.add_grid((3, 3))
    model.env.add_agents(1, positions=[(1, 1)])
    # Apply function len to each position, must be 1 where agent is
    assert model.env.apply(len) == [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
示例#14
0
def test_random():

    model = ap.Model()
    model.add_agents(2)

    assert len(model.agents) == len(model.agents.shuffle())
    assert len(model.agents.random()) == 1
示例#15
0
def test_sort():
    """ Test sorting method. """
    model = ap.Model()
    model.agents = ap.AgentList(model, 2)
    model.agents[0].x = 1
    model.agents[1].x = 0
    model.agents.sort('x')
    assert list(model.agents.x) == [0, 1]
    assert list(model.agents.id) == [2, 1]

    model = ap.Model()
    model.agents = ap.AgentDList(model, 2)
    model.agents[0].x = 1
    model.agents[1].x = 0
    model.agents = model.agents.sort('x')  # Not in-place
    assert list(model.agents.x) == [0, 1]
    assert list(model.agents.id) == [2, 1]
示例#16
0
def test_agent_errors():

    model = ap.Model()
    env = model.add_env()
    agent = model.add_agents()[0]
    with pytest.raises(AgentpyError):
        agent.neighbors()
    with pytest.raises(AgentpyError):
        agent.neighbors(env)
示例#17
0
def make_space(s, n=0, torus=False):

    model = ap.Model()
    agents = ap.AgentList(model, n)
    space = ap.Space(model, (s, s), torus=torus)
    space.add_agents(agents)
    for agent in agents:
        agent.pos = space.positions[agent]
    return model, space, agents
示例#18
0
def test_objects_property():

    model = ap.Model()
    model.add_agents(3)
    model.add_env()

    assert len(model.objects) == 4
    assert model.agents[0] in model.objects
    assert model.envs[0] in model.objects
示例#19
0
def test_remove():
    model = ap.Model()
    grid = model.add_grid((2, 2))
    grid.add_agents(2)
    agent = model.agents[0]
    grid.remove_agents(agent)
    assert grid.attribute('id') == [[np.nan, 3], [np.nan, np.nan]]
    assert len(grid._agent_dict) == 1
    assert len(grid.agents) == 1
示例#20
0
def test_agent_group():
    class MyAgent(ap.Agent):
        def method(self, x):
            if self.id == 2:
                self.model.agents.pop(x)
            self.model.called.append(self.id)

    # Delete later element in list
    model = ap.Model()
    model.called = []
    model.agents = ap.AgentDList(model, 4, MyAgent)
    model.agents.buffer().method(2)
    assert model.called == [1, 2, 4]

    # Delete earlier element in list
    model = ap.Model()
    model.called = []
    model.agents = ap.AgentDList(model, 4, MyAgent)
    model.agents.buffer().method(0)
    assert model.called == [1, 2, 3, 4]

    # Incorrect result without buffer
    model = ap.Model()
    model.called = []
    model.agents = ap.AgentList(model, 4, MyAgent)
    model.agents.method(0)
    assert model.called == [1, 2, 4]

    # Combine with buffer - still number 3 that gets deleted
    model = ap.Model()
    model.run(seed=2, steps=0, display=False)
    model.called = []
    model.agents = ap.AgentDList(model, 4, MyAgent)
    model.agents.shuffle().buffer().method(2)
    assert model.called == [2, 4, 1]

    # Combination order doesn't matter
    model = ap.Model()
    model.run(seed=2, steps=0, display=False)
    model.called = []
    model.agents = ap.AgentDList(model, 4, MyAgent)
    model.agents.buffer().shuffle().method(2)
    assert model.called == [2, 4, 1]
示例#21
0
def make_forest():
    """ IDs are
    1 -> Environment
    2-4 -> Agents
    """
    model = ap.Model()
    model.add_env(color='green')
    model.env.add_agents(3)

    return model
示例#22
0
def test_create_output():
    """ Should put variables directly into output if there are only model
    variables, or make a subdict if there are also other variables. """

    model = ap.Model()
    model.record('x', 0)
    model.run(1)
    assert list(model.output.variables.Model.keys()) == ['x']

    model = ap.Model(_run_id=(1, 2))
    model.agents = ap.AgentList(model, 1)
    model.agents.record('x', 0)
    model.record('x', 0)
    model.run(1)
    assert list(model.output.variables.keys()) == ['Agent', 'Model']

    # Run id and scenario should be added to output
    assert model.output.variables.Model.reset_index()['sample_id'][0] == 1
    assert model.output.variables.Model.reset_index()['iteration'][0] == 2
示例#23
0
def test_remove_agents():

    model = ap.Model()
    model.add_agents(2)
    nw = model.add_network()
    nw.add_agents(model.agents)
    agent = model.agents[0]
    nw.remove_agents(agent)
    len(nw.agents) == 1
    len(nw.graph.nodes) == 1
示例#24
0
def test_create_output():
    """ Should put variables directly into output if there are only model
    variables, or make a subdict if there are also other variables. """

    model = ap.Model()
    model.record('x', 0)
    model.run(1)
    assert list(model.output.variables.keys()) == ['x']

    model = ap.Model(run_id=1, scenario='test')
    model.add_agents()
    model.agents.record('x', 0)
    model.record('x', 0)
    model.run(1)
    assert list(model.output.variables.keys()) == ['Agent', 'Model']

    # Run id and scenario should be added to output
    assert model.output.variables.Model.reset_index()['run_id'][0] == 1
    assert model.output.variables.Model.reset_index()['scenario'][0] == 'test'
示例#25
0
def test_sort():

    model = ap.Model()
    model.add_agents(2)
    model.agents[0].x = 1
    model.agents[1].x = 0
    model.agents.sort('x')

    assert list(model.agents.x) == [0, 1]
    assert list(model.agents.id) == [2, 1]
示例#26
0
def test_add_agents():
    """ Add new agents to model """

    model = ap.Model()
    model.add_agents(3)

    assert len(model.agents) == 3  # New agents
    assert list(model.agents.id) == [1, 2, 3]

    model.add_agents(model.agents)  # Existing agents
    assert list(model.agents.id) == [1, 2, 3] * 2
示例#27
0
def test_delete():
    """ Remove agent from model """

    model = ap.Model()
    model.add_agents(3)
    model.add_env().add_agents(model.agents)
    model.agents[1].delete()

    assert len(model.agents) == 2
    assert list(model.agents.id) == [1, 3]
    assert list(model.env.agents.id) == [1, 3]
示例#28
0
def test_record_all():
    """ Record all dynamic variables automatically """

    model = ap.Model()
    model.var1 = 1
    model.var2 = 2
    model.record(model.var_keys)

    assert len(list(model._log.keys())) == 3
    assert model._log['var1'] == [1]
    assert model._log['var2'] == [2]
示例#29
0
def test_attr_calls():
    model = ap.Model()
    model.add_agents(2)
    model.agents.x = 1
    model.agents.f = lambda: 2
    assert list(model.agents.x) == [1, 1]
    assert list(model.agents.f()) == [2, 2]
    with pytest.raises(AttributeError):
        assert model.agents.y
    with pytest.raises(TypeError):
        assert model.agents.x()  # noqa
示例#30
0
def test_repr():
    model = ap.Model()
    model.add_agents()
    model.add_env()
    assert model.agents.__repr__() == "AgentList [1 agent]"
    assert model.envs.__repr__() == "EnvList [1 environment]"
    assert model.objects.__repr__() == "ObjList [2 objects]"
    l1 = model.agents.id
    l2 = l1 + 1
    assert l1.__repr__() == "AttrList of attribute 'id': [1]"
    assert l2.__repr__() == "AttrList: [2]"