Zum Inhalt

Inherited Classes

Mesa Base Model Class

Base class for models in the Mesa ABM library.

This class serves as a foundational structure for creating agent-based models. It includes the basic attributes and methods necessary for initializing and running a simulation model.

Attributes:

Name Type Description
running

A boolean indicating if the model should continue running.

schedule

An object to manage the order and execution of agent steps.

current_id

A counter for assigning unique IDs to agents.

agents_ defaultdict[type, dict]

A defaultdict mapping each agent type to a dict of its instances. This private attribute is used internally to manage agents.

Properties

agents: An AgentSet containing all agents in the model, generated from the _agents attribute. agent_types: A list of different agent types present in the model.

Methods:

Name Description
get_agents_of_type

Returns an AgentSet of agents of the specified type.

run_model

Runs the model's simulation until a defined end condition is reached.

step

Executes a single step of the model's simulation process.

next_id

Generates and returns the next unique identifier for an agent.

reset_randomizer

Resets the model's random number generator with a new or existing seed.

initialize_data_collector

Sets up the data collector for the model, requiring an initialized scheduler and agents.

Source code in mesa/model.py
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
class Model:
    """Base class for models in the Mesa ABM library.

    This class serves as a foundational structure for creating agent-based models.
    It includes the basic attributes and methods necessary for initializing and
    running a simulation model.

    Attributes:
        running: A boolean indicating if the model should continue running.
        schedule: An object to manage the order and execution of agent steps.
        current_id: A counter for assigning unique IDs to agents.
        agents_: A defaultdict mapping each agent type to a dict of its instances.
                 This private attribute is used internally to manage agents.

    Properties:
        agents: An AgentSet containing all agents in the model, generated from the _agents attribute.
        agent_types: A list of different agent types present in the model.

    Methods:
        get_agents_of_type: Returns an AgentSet of agents of the specified type.
        run_model: Runs the model's simulation until a defined end condition is reached.
        step: Executes a single step of the model's simulation process.
        next_id: Generates and returns the next unique identifier for an agent.
        reset_randomizer: Resets the model's random number generator with a new or existing seed.
        initialize_data_collector: Sets up the data collector for the model, requiring an initialized scheduler and agents.
    """

    def __new__(cls, *args: Any, **kwargs: Any) -> Any:
        """Create a new model object and instantiate its RNG automatically."""
        obj = object.__new__(cls)
        obj._seed = kwargs.get("seed")
        if obj._seed is None:
            # We explicitly specify the seed here so that we know its value in
            # advance.
            obj._seed = random.random()
        obj.random = random.Random(obj._seed)
        # TODO: Remove these 2 lines just before Mesa 3.0
        obj._steps = 0
        obj._time = 0
        return obj

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        """Create a new model. Overload this method with the actual code to
        start the model. Always start with super().__init__() to initialize the
        model object properly.
        """

        self.running = True
        self.schedule = None
        self.current_id = 0
        self.agents_: defaultdict[type, dict] = defaultdict(dict)

        self._steps: int = 0
        self._time: TimeT = 0  # the model's clock

    @property
    def agents(self) -> AgentSet:
        """Provides an AgentSet of all agents in the model, combining agents from all types."""

        if hasattr(self, "_agents"):
            return self._agents
        else:
            all_agents = itertools.chain.from_iterable(self.agents_.values())
            return AgentSet(all_agents, self)

    @agents.setter
    def agents(self, agents: Any) -> None:
        warnings.warn(
            "You are trying to set model.agents. In a next release, this attribute is used "
            "by MESA itself so you cannot use it directly anymore."
            "Please adjust your code to use a different attribute name for custom agent storage",
            UserWarning,
            stacklevel=2,
        )

        self._agents = agents

    @property
    def agent_types(self) -> list[type]:
        """Return a list of different agent types."""
        return list(self.agents_.keys())

    def get_agents_of_type(self, agenttype: type[Agent]) -> AgentSet:
        """Retrieves an AgentSet containing all agents of the specified type."""
        return AgentSet(self.agents_[agenttype].keys(), self)

    def run_model(self) -> None:
        """Run the model until the end condition is reached. Overload as
        needed.
        """
        while self.running:
            self.step()

    def step(self) -> None:
        """A single step. Fill in here."""

    def _advance_time(self, deltat: TimeT = 1):
        """Increment the model's steps counter and clock."""
        self._steps += 1
        self._time += deltat

    def next_id(self) -> int:
        """Return the next unique ID for agents, increment current_id"""
        self.current_id += 1
        return self.current_id

    def reset_randomizer(self, seed: int | None = None) -> None:
        """Reset the model random number generator.

        Args:
            seed: A new seed for the RNG; if None, reset using the current seed
        """

        if seed is None:
            seed = self._seed
        self.random.seed(seed)
        self._seed = seed

    def initialize_data_collector(
        self,
        model_reporters=None,
        agent_reporters=None,
        tables=None,
    ) -> None:
        if not hasattr(self, "schedule") or self.schedule is None:
            raise RuntimeError(
                "You must initialize the scheduler (self.schedule) before initializing the data collector."
            )
        if self.schedule.get_agent_count() == 0:
            raise RuntimeError(
                "You must add agents to the scheduler before initializing the data collector."
            )
        self.datacollector = DataCollector(
            model_reporters=model_reporters,
            agent_reporters=agent_reporters,
            tables=tables,
        )
        # Collect data for the first time during initialization.
        self.datacollector.collect(self)

agent_types property

Return a list of different agent types.

agents property writable

Provides an AgentSet of all agents in the model, combining agents from all types.

__init__(*args, **kwargs)

Create a new model. Overload this method with the actual code to start the model. Always start with super().init() to initialize the model object properly.

Source code in mesa/model.py
66
67
68
69
70
71
72
73
74
75
76
77
78
def __init__(self, *args: Any, **kwargs: Any) -> None:
    """Create a new model. Overload this method with the actual code to
    start the model. Always start with super().__init__() to initialize the
    model object properly.
    """

    self.running = True
    self.schedule = None
    self.current_id = 0
    self.agents_: defaultdict[type, dict] = defaultdict(dict)

    self._steps: int = 0
    self._time: TimeT = 0  # the model's clock

__new__(*args, **kwargs)

Create a new model object and instantiate its RNG automatically.

Source code in mesa/model.py
52
53
54
55
56
57
58
59
60
61
62
63
64
def __new__(cls, *args: Any, **kwargs: Any) -> Any:
    """Create a new model object and instantiate its RNG automatically."""
    obj = object.__new__(cls)
    obj._seed = kwargs.get("seed")
    if obj._seed is None:
        # We explicitly specify the seed here so that we know its value in
        # advance.
        obj._seed = random.random()
    obj.random = random.Random(obj._seed)
    # TODO: Remove these 2 lines just before Mesa 3.0
    obj._steps = 0
    obj._time = 0
    return obj

get_agents_of_type(agenttype)

Retrieves an AgentSet containing all agents of the specified type.

Source code in mesa/model.py
107
108
109
def get_agents_of_type(self, agenttype: type[Agent]) -> AgentSet:
    """Retrieves an AgentSet containing all agents of the specified type."""
    return AgentSet(self.agents_[agenttype].keys(), self)

next_id()

Return the next unique ID for agents, increment current_id

Source code in mesa/model.py
126
127
128
129
def next_id(self) -> int:
    """Return the next unique ID for agents, increment current_id"""
    self.current_id += 1
    return self.current_id

reset_randomizer(seed=None)

Reset the model random number generator.

Parameters:

Name Type Description Default
seed int | None

A new seed for the RNG; if None, reset using the current seed

None
Source code in mesa/model.py
131
132
133
134
135
136
137
138
139
140
141
def reset_randomizer(self, seed: int | None = None) -> None:
    """Reset the model random number generator.

    Args:
        seed: A new seed for the RNG; if None, reset using the current seed
    """

    if seed is None:
        seed = self._seed
    self.random.seed(seed)
    self._seed = seed

run_model()

Run the model until the end condition is reached. Overload as needed.

Source code in mesa/model.py
111
112
113
114
115
116
def run_model(self) -> None:
    """Run the model until the end condition is reached. Overload as
    needed.
    """
    while self.running:
        self.step()

step()

A single step. Fill in here.

Source code in mesa/model.py
118
119
def step(self) -> None:
    """A single step. Fill in here."""

---

Mesa Base Agent Class

Base class for a model agent in Mesa.

Attributes:

Name Type Description
unique_id int

A unique identifier for this agent.

model Model

A reference to the model instance.

self.pos Model

Position | None = None

Source code in mesa/agent.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class Agent:
    """
    Base class for a model agent in Mesa.

    Attributes:
        unique_id (int): A unique identifier for this agent.
        model (Model): A reference to the model instance.
        self.pos: Position | None = None
    """

    def __init__(self, unique_id: int, model: Model) -> None:
        """
        Create a new agent.

        Args:
            unique_id (int): A unique identifier for this agent.
            model (Model): The model instance in which the agent exists.
        """
        self.unique_id = unique_id
        self.model = model
        self.pos: Position | None = None

        # register agent
        try:
            self.model.agents_[type(self)][self] = None
        except AttributeError:
            # model super has not been called
            self.model.agents_ = defaultdict(dict)
            self.model.agents_[type(self)][self] = None
            self.model.agentset_experimental_warning_given = False

            warnings.warn(
                "The Mesa Model class was not initialized. In the future, you need to explicitly initialize the Model by calling super().__init__() on initialization.",
                FutureWarning,
                stacklevel=2,
            )

    def remove(self) -> None:
        """Remove and delete the agent from the model."""
        with contextlib.suppress(KeyError):
            self.model.agents_[type(self)].pop(self)

    def step(self) -> None:
        """A single step of the agent."""

    def advance(self) -> None:
        pass

    @property
    def random(self) -> Random:
        return self.model.random

__init__(unique_id, model)

Create a new agent.

Parameters:

Name Type Description Default
unique_id int

A unique identifier for this agent.

required
model Model

The model instance in which the agent exists.

required
Source code in mesa/agent.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def __init__(self, unique_id: int, model: Model) -> None:
    """
    Create a new agent.

    Args:
        unique_id (int): A unique identifier for this agent.
        model (Model): The model instance in which the agent exists.
    """
    self.unique_id = unique_id
    self.model = model
    self.pos: Position | None = None

    # register agent
    try:
        self.model.agents_[type(self)][self] = None
    except AttributeError:
        # model super has not been called
        self.model.agents_ = defaultdict(dict)
        self.model.agents_[type(self)][self] = None
        self.model.agentset_experimental_warning_given = False

        warnings.warn(
            "The Mesa Model class was not initialized. In the future, you need to explicitly initialize the Model by calling super().__init__() on initialization.",
            FutureWarning,
            stacklevel=2,
        )

remove()

Remove and delete the agent from the model.

Source code in mesa/agent.py
67
68
69
70
def remove(self) -> None:
    """Remove and delete the agent from the model."""
    with contextlib.suppress(KeyError):
        self.model.agents_[type(self)].pop(self)

step()

A single step of the agent.

Source code in mesa/agent.py
72
73
def step(self) -> None:
    """A single step of the agent."""