analitics

Pages

Saturday, September 14, 2024

Python 3.13.0rc1 : AgentPy python module ...

AgentPy is an open-source library for the development and analysis of agent-based models in Python.
The project can be found on the GitHub repo.
This can be install with the pip tool:
pip install agentpy
Collecting agentpy
...
Successfully installed SALib-1.5.1 agentpy-0.1.5 contourpy-1.3.0 cycler-0.12.1 dill-0.3.8 fonttools-4.53.1 
joblib-1.4.2 kiwisolver-1.4.7 matplotlib-3.9.2 multiprocess-0.70.16 networkx-3.3 packaging-24.1 
pillow-10.4.0 pyparsing-3.1.4 scipy-1.14.1
This is the source code:
import agentpy as ap
import matplotlib.pyplot as plt

# define Agent class
class RandomWalker(ap.Agent):
    def setup(self):
        self.position = [0, 0]

    def step(self):
        self.position += self.model.random.choice([[1, 0], [-1, 0], [0, 1], [0, -1]])

# define Model class
class RandomWalkModel(ap.Model):
    def setup(self):
        self.agents = ap.AgentList(self, self.p.agents, RandomWalker)
        self.agents.setup()

    def step(self):
        self.agents.step()

    def update(self):
        self.record('Positions', [agent.position for agent in self.agents])

    def end(self):
        positions = self.log['Positions']
        plt.figure()
        for pos in positions:
            plt.plot(*zip(*pos))
        plt.show()

# configuration and running 
parameters = {'agents': 5, 'steps': 20}
model = RandomWalkModel(parameters)
results = model.run()
The result is a simple graph with these output:
python test001.py
Matplotlib is building the font cache; this may take a moment.
Completed: 20 steps
Run time: 0:00:50.823483
Simulation finished