Discrete spaces (Grid)
- class Grid(model, shape, torus=False, track_empty=False, check_border=True, **kwargs)[source]
Environment that contains agents with a discrete spatial topology, supporting multiple agents and attribute fields per cell. For a continuous spatial topology, see
Space.This class can be used as a parent class for custom grid types. All agentpy model objects call the method
setup()after creation, and can access class attributes like dictionary items.- Parameters
model (Model) – The model instance.
shape (tuple of int) – Size of the grid. The length of the tuple defines the number of dimensions, and the values in the tuple define the length of each dimension.
torus (bool, optional) – Whether to connect borders (default False). If True, the grid will be toroidal, meaning that agents who move over a border will re-appear on the opposite side. If False, they will remain at the edge of the border.
track_empty (bool, optional) – Whether to keep track of empty cells (default False). If true, empty cells can be accessed via
Grid.empty.check_border (bool, optional) – Ensure that agents stay within border (default True). Can be set to False for faster performance.
**kwargs – Will be forwarded to
Grid.setup().
- Variables
agents (GridIter) – Iterator over all agents in the grid.
positions (dict of Agent) – Dictionary linking each agent instance to its position.
grid (numpy.rec.array) – Structured numpy record array with a field ‘agents’ that holds an
AgentSetin each position.shape (tuple of int) – Length of each dimension.
ndim (int) – Number of dimensions.
all (list) – List of all positions in the grid.
empty (ListDict) – List of unoccupied positions, only available if the Grid was initiated with track_empty=True.
- add_agents(agents, positions=None, random=False, empty=False)[source]
Adds agents to the grid environment.
- Parameters
agents (Sequence of Agent) – Iterable of agents to be added.
positions (Sequence of positions, optional) –
The positions of the agents. Must have the same length as ‘agents’, with each entry being a tuple of integers. If none is passed, positions will be chosen automatically based on the arguments ‘random’ and ‘empty’:
random and empty: Random selection without repetition from Grid.empty.
random and not empty: Random selection with repetition from Grid.all.
not random and empty: Iterative selection from Grid.empty.
not random and not empty: Iterative selection from Grid.all.
random (bool, optional) – Whether to choose random positions (default False).
empty (bool, optional) – Whether to choose only empty cells (default False). Can only be True if Grid was initiated with track_empty=True.
- add_field(key, values=None)[source]
Add an attribute field to the grid.
- Parameters
key (str) – Name of the field.
values (optional) – Single value or
numpy.ndarrayof values (default None).
- apply(func, field='agents')[source]
Applies a function to each grid position, end returns an numpy.ndarray of return values.
- Parameters
func (function) – Function that takes cell content as input.
field (str, optional) – Field to use (default ‘agents’).
- attr_grid(attr_key, otypes='f', field='agents')[source]
Returns a grid with the value of the attribute of the agent in each position, using
numpy.vectorize. Positions with no agent will contain numpy.nan. Should only be used for grids with zero or one agents per cell. Other kinds of attribute grids can be created withGrid.apply().- Parameters
attr_key (str) – Name of the attribute.
otypes (str or list of dtypes, optional) – Data type of returned grid (default float). For more information, see
numpy.vectorize.field (str, optional) – Field to use (default ‘agents’).
- del_field(key)[source]
Delete a attribute field from the grid.
- Parameters
key (str) – Name of the field.
- move_by(agent, path)[source]
Moves agent to new position, relative to current position.
- Parameters
agent (Agent) – Instance of the agent.
path (tuple of int) – Relative change of position.
- move_to(agent, pos)[source]
Moves agent to new position.
- Parameters
agent (Agent) – Instance of the agent.
pos (tuple of int) – New position of the agent.
- record(var_keys, value=None)
Records an object’s variables at the current time-step. Recorded variables can be accessed via the object’s log attribute and will be saved to the model’s output at the end of a simulation.
- Parameters
var_keys (str or list of str) – Names of the variables to be recorded.
value (optional) – Value to be recorded. The same value will be used for all var_keys. If none is given, the values of object attributes with the same name as each var_key will be used.
Notes
Recording mutable objects like lists can lead to wrong results if the object’s content will be changed during the simulation. Make a copy of the list or record each list entry seperately.
Examples
Record the existing attributes x and y of an object a:
a.record(['x', 'y'])
Record a variable z with the value 1 for an object a:
a.record('z', 1)
Record all variables of an object:
a.record(a.vars)
- record_positions(label='p')
Records the positions of each agent.
- Parameters
label (string, optional) – Name under which to record each position (default p). A number will be added for each coordinate (e.g. p1, p2, …).
- setup(**kwargs)
This empty method is called automatically at the objects’ creation. Can be overwritten in custom sub-classes to define initial attributes and actions.
- Parameters
**kwargs – Keyword arguments that have been passed to
AgentorModel.add_agents(). If the original setup method is used, they will be set as attributes of the object.
Examples
The following setup initializes an object with three variables:
def setup(self, y): self.x = 0 # Value defined locally self.y = y # Value defined in kwargs self.z = self.p.z # Value defined in parameters
- class GridIter(model, iter_, items)[source]
Iterator over objects in
Gridthat supports slicing.Examples
Create a model with a 10 by 10 grid with one agent in each position:
model = ap.Model() agents = ap.AgentList(model, 100) grid = ap.Grid(model, (10, 10)) grid.add_agents(agents)
The following returns an iterator over the agents in all position:
>>> grid.agents GridIter (100 objects)
The following returns an iterator over the agents in the top-left quarter of the grid:
>>> grid.agents[0:5, 0:5] GridIter (25 objects)
- to_dlist()
Returns an
AgentDListof the iterator.