-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 6b727e6
Showing
8 changed files
with
393 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
# Auto detect text files and perform LF normalization | ||
* text=auto |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,152 @@ | ||
# Byte-compiled / optimized / DLL files | ||
__pycache__/ | ||
*.py[cod] | ||
*$py.class | ||
|
||
# C extensions | ||
*.so | ||
|
||
# Distribution / packaging | ||
.Python | ||
build/ | ||
develop-eggs/ | ||
dist/ | ||
downloads/ | ||
eggs/ | ||
.eggs/ | ||
lib/ | ||
lib64/ | ||
parts/ | ||
sdist/ | ||
var/ | ||
wheels/ | ||
share/python-wheels/ | ||
*.egg-info/ | ||
.installed.cfg | ||
*.egg | ||
MANIFEST | ||
|
||
# PyInstaller | ||
# Usually these files are written by a python script from a template | ||
# before PyInstaller builds the exe, so as to inject date/other infos into it. | ||
*.manifest | ||
*.spec | ||
|
||
# Installer logs | ||
pip-log.txt | ||
pip-delete-this-directory.txt | ||
|
||
# Unit test / coverage reports | ||
htmlcov/ | ||
.tox/ | ||
.nox/ | ||
.coverage | ||
.coverage.* | ||
.cache | ||
nosetests.xml | ||
coverage.xml | ||
*.cover | ||
*.py,cover | ||
.hypothesis/ | ||
.pytest_cache/ | ||
cover/ | ||
|
||
# Translations | ||
*.mo | ||
*.pot | ||
|
||
# Django stuff: | ||
*.log | ||
local_settings.py | ||
db.sqlite3 | ||
db.sqlite3-journal | ||
|
||
# Flask stuff: | ||
instance/ | ||
.webassets-cache | ||
|
||
# Scrapy stuff: | ||
.scrapy | ||
|
||
# Sphinx documentation | ||
docs/_build/ | ||
|
||
# PyBuilder | ||
.pybuilder/ | ||
target/ | ||
|
||
# Jupyter Notebook | ||
.ipynb_checkpoints | ||
|
||
# IPython | ||
profile_default/ | ||
ipython_config.py | ||
|
||
# pyenv | ||
# For a library or package, you might want to ignore these files since the code is | ||
# intended to run in multiple environments; otherwise, check them in: | ||
# .python-version | ||
|
||
# pipenv | ||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. | ||
# However, in case of collaboration, if having platform-specific dependencies or dependencies | ||
# having no cross-platform support, pipenv may install dependencies that don't work, or not | ||
# install all needed dependencies. | ||
#Pipfile.lock | ||
|
||
# poetry | ||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. | ||
# This is especially recommended for binary packages to ensure reproducibility, and is more | ||
# commonly ignored for libraries. | ||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control | ||
#poetry.lock | ||
|
||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow | ||
__pypackages__/ | ||
|
||
# Celery stuff | ||
celerybeat-schedule | ||
celerybeat.pid | ||
|
||
# SageMath parsed files | ||
*.sage.py | ||
|
||
# Environments | ||
.env | ||
.venv | ||
env/ | ||
venv/ | ||
ENV/ | ||
env.bak/ | ||
venv.bak/ | ||
|
||
# Spyder project settings | ||
.spyderproject | ||
.spyproject | ||
|
||
# Rope project settings | ||
.ropeproject | ||
|
||
# mkdocs documentation | ||
/site | ||
|
||
# mypy | ||
.mypy_cache/ | ||
.dmypy.json | ||
dmypy.json | ||
|
||
# Pyre type checker | ||
.pyre/ | ||
|
||
# pytype static type analyzer | ||
.pytype/ | ||
|
||
# Cython debug symbols | ||
cython_debug/ | ||
|
||
# PyCharm | ||
# JetBrains specific template is maintainted in a separate JetBrains.gitignore that can | ||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore | ||
# and can be added to the global gitignore or merged into this file. For a more nuclear | ||
# option (not recommended) you can uncomment the following to ignore the entire idea folder. | ||
#.idea/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2024 Adam Amer | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
# mesa-frames | ||
|
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
from dataclasses import dataclass | ||
from uuid import uuid4 | ||
import pandas as pd | ||
from numpy.random import randint | ||
|
||
@dataclass | ||
class AgentParams(): | ||
"""The AgentParams class is a dataclass that contains the parameters of an Agent. | ||
It is used to initialize the Agent class. | ||
""" | ||
pass | ||
|
||
class Agent(): | ||
"""The Agent class is a class that defines the basic attributes and methods of an agent. | ||
It is used as a parent class for all the other agents. | ||
Parameters: | ||
---------- | ||
params : AgentParams | ||
The parameters of the Agent. Default: None | ||
dtypes : dict[str, str] | ||
The data types of the attributes of the Agent. Default: {'id' : 'int64', 'type' : 'str'} | ||
values : dict[str, any] | ||
The values of the attributes of the Agent. Default: {'id' : lambda: uuid4().int >> 64, 'status' : 'free'} | ||
model : Model | ||
The model of the simulation where the Agent is used. See streetcrime/model/model.py. Default: None | ||
agents : gpd.GeoDataFrame | ||
The GeoDataFrame containing all Agents. Default: None | ||
""" | ||
|
||
params : AgentParams = None | ||
dtypes : dict[str, str] = { | ||
'id' : 'int64', | ||
'type' : 'str', | ||
} | ||
model : 'Model' = None | ||
mask : pd.Series = None | ||
|
||
@classmethod | ||
def __init__(cls): | ||
cls.model.agents.loc[cls.mask, 'id'] = randint(low=-9223372036854775808, high=9223372036854775807, size = cls.mask.sum(), dtype='int64') | ||
|
||
class GeoAgent(Agent): | ||
dtypes : dict[str, str] = { | ||
'geometry' : 'geometry' | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,160 @@ | ||
from mesa_frames.agent import Agent | ||
from mesa_frames.space import Space, GeoSpace | ||
import pandas as pd | ||
import geopandas as gpd | ||
from uuid import uuid4 | ||
from time import time | ||
from copy import deepcopy | ||
from warnings import warn | ||
|
||
class Model(): | ||
|
||
def __init__(self, | ||
space: Space = None, | ||
n_steps: int = None, | ||
p_agents: dict[type[Agent], float] = None, | ||
n_agents: int = None, | ||
data_collection: str = '2d', #TODO: implement different data collection frequencies (xw, xd, xh, weekly, daily, hourly, per every step) | ||
**kwargs): | ||
|
||
#self._verify_parameters(data_collection) | ||
|
||
# Initialize model attributes | ||
self.id = uuid4().int >> 64 | ||
self.n_agents : int = None | ||
self.agent_types = None | ||
self.agents : pd.DataFrame | gpd.GeoDataFrame = None | ||
self.p_agents = p_agents | ||
self.space = space | ||
self.n_steps = n_steps | ||
self.n_agents = n_agents | ||
|
||
# Initialize data collection | ||
self._initialize_data_collection(data_collection) | ||
|
||
for key, value in kwargs.items(): | ||
setattr(self, key, value) | ||
|
||
def create_agents(self, | ||
p_agents : dict[type[Agent], float] = None, | ||
n_agents : int = None) -> None: | ||
"""Creates the agents of the model and adds them to the schedule and the space | ||
Parameters | ||
---------- | ||
num_agents : int | ||
The number of agents to create | ||
agents : dict[type[agent], float] | ||
The dictionary of agents to create. The keys are the types of agents and the values are the percentages of each agent type to create. | ||
""" | ||
start_time = time() | ||
print("Creating agents: ...") | ||
|
||
mros = [[agent.__mro__[:-1], p] for agent, p in p_agents.items()] | ||
mros_copy = deepcopy(mros) | ||
agent_types = [] | ||
|
||
# Create a "merged MRO" (inspired by C3 linearization algorithm) | ||
while True: | ||
candidate_added = False | ||
#if all mros are empty, the merged mro is done | ||
if not any(mro[0] for mro in mros): | ||
break | ||
for mro in mros: | ||
# If mro is empty, continue | ||
if not mro[0]: | ||
continue | ||
# candidate = head | ||
candidate = mro[0][0] | ||
# If candidate appears in the tail of another MRO, skip it for now (because other agent_types depend on it, will be added later) | ||
if any(candidate in other_mro[0][1:] for other_mro in mros if other_mro is not mro): | ||
continue | ||
else: | ||
p = 0 | ||
for i, other_mro in enumerate(mros): | ||
if other_mro[0][0] == candidate: | ||
p += other_mro[1] | ||
mros[i][0] = other_mro[0][1:] | ||
else: | ||
continue | ||
agent_types.append((candidate, p)) #Safe to add it | ||
candidate_added = True | ||
# If there wasn't any good head, there is an inconsistent hierarchy | ||
if not candidate_added: | ||
raise ValueError("Inconsistent hierarchy") | ||
self.agent_types = list(reversed(agent_types)) | ||
|
||
### Create DataFrame using vars and values for every class | ||
columns = set() | ||
dtypes = {} | ||
for agent_type in self.agent_types: | ||
for key, val in agent_type[0].dtypes.items(): | ||
if key not in columns: | ||
columns.add(key) | ||
dtypes[key] = val | ||
|
||
if isinstance(self.space, GeoSpace): | ||
self.agents = gpd.GeoDataFrame(index=pd.RangeIndex(0, n_agents), columns = list(columns), crs = self.space.crs) | ||
else: | ||
self.agents = pd.DataFrame(index=pd.RangeIndex(0, n_agents), columns = list(columns)) | ||
|
||
#Populate type column | ||
start_index = 0 | ||
for i, (_, p) in enumerate(p_agents.items()): | ||
self.agents.loc[start_index:start_index + int(n_agents * p)-1, 'type'] = str(mros_copy[i][0]) | ||
start_index += int(n_agents * p) | ||
|
||
#Initialize model and mask attributes for agents | ||
Agent.model = self | ||
self.update_agents_masks() | ||
|
||
#Execute init method for every agent | ||
for agent in p_agents: | ||
agent.__init__() | ||
|
||
for col, dtype in dtypes.items(): | ||
if 'int' in dtype and self.agents[col].isna().sum() > 0: | ||
#warn(f'Pandas does not support NaN values for int{dtype[-2:]} dtypes. Changing dtype to float{dtype[-2:]} for {col}', RuntimeWarning) | ||
dtypes[col] = 'float' + dtype[-2:] | ||
self.agents = self.agents.astype(dtypes) | ||
self.agents.set_index('id', inplace=True) | ||
#Have to reassign masks because index changed | ||
self.update_agents_masks() | ||
print("Created agents: " + "--- %s seconds ---" % (time() - start_time)) | ||
|
||
def run_model(self) -> None: | ||
for _ in range(self.n_steps): | ||
self.step() | ||
|
||
def step(self) -> None: | ||
for agent in self.p_agents: | ||
agent.step() | ||
|
||
def _initialize_data_collection(self, how = '2d') -> None: | ||
"""Initializes the data collection of the model. | ||
Parameters | ||
---------- | ||
how : str | ||
The frequency of the data collection. It can be 'xd', 'xd', 'xh', 'weekly', 'daily', 'hourly'. | ||
""" | ||
#TODO: finish implementation of different data collections | ||
if how == '2d': | ||
return | ||
|
||
def update_agents_masks(self) -> None: | ||
for agent_type in self.agent_types: | ||
agent_type[0].mask = self.agents['type'].str.contains(str(agent_type[0])) | ||
|
||
'''def _verify_parameters(self, p_agents, n_agents, data_collection) -> None: | ||
"""Verifies that the parameters of the model are correct. | ||
""" | ||
if sum(p_agents.values()) != 1: | ||
raise ValueError("Sum of proportions of agents should be 1") | ||
if any(p < 0 or p > 1 for p in p_agents.values()): | ||
raise ValueError("Proportions of agents should be between 0 and 1") | ||
if n_agents <= 0 or n_agents % 1 != 0: | ||
raise ValueError("Number of agents should be an integer greater than 0") | ||
#TODO: implement data_collection verification''' |
Oops, something went wrong.