Skip to content

Commit

Permalink
Update 0.0.3 (grids)
Browse files Browse the repository at this point in the history
  • Loading branch information
jofmi committed Oct 27, 2020
1 parent 22baf8c commit a23feb6
Show file tree
Hide file tree
Showing 23 changed files with 61,649 additions and 52,117 deletions.
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
# Agentpy - Agent-based modeling in Python

Agentpy is a package for the development and analysis of agent-based models in Python. The packages is still in a very early stage of development. If you need help using Agentpy or want to contribute, feel free to write me via [email protected].
Agentpy is a package for the development and analysis of agent-based models in Python. The project is still in an early stage of development. If you need help or want to contribute, feel free to write me via [email protected].

**Main features:**

- Design of agent-based models with complex procedures.
- Creation of custom agent types, environments, and networks.
- Design of models with complex procedures and multiple environments.
- Standard operators can be used on whole groups of agents simultaneously.
- Container classes for operations on groups of agents and environments.
- Experiments with repeated iterations, large parameter samples, and distinct scenarios.
- Output data that can be saved, loaded, and re-arranged for further analysis.
- Tools for sensitivity analysis, interactive output, animations, and visualization.
- Output data that can be saved, loaded, and transformed for further analysis.
- Tools for sensitivity analysis, interactive output, animations, and plots.

**Documentation:** https://agentpy.readthedocs.io

**Tutorials:** https://agentpy.readthedocs.io/en/latest/tutorials.html
**Model library:** https://agentpy.readthedocs.io/en/latest/models.html

**Requirements:** Python 3, NumPy, scipy, matplotlib, networkx, pandas, SALib, and ipywidgets.

Expand Down
13 changes: 7 additions & 6 deletions agentpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,16 @@
"""

from .framework import model, environment, network, agent, agent_list, env_dict
from .output import data_dict, load, save
from .framework import model, environment, network, grid, agent, agent_list, env_dict

from .sample import sample, sample_discrete, sample_saltelli
from .experiment import experiment

from .experiment import experiment, sample
from .output import data_dict, load, save

from .interactive import interactive, animate
from .analysis import sensitivity, phaseplot
from .analysis import sensitivity, phaseplot, gridplot, interactive, animate

from .tools import attr_dict, attr_list
from .tools import attr_dict, obj_list

# Aliases
exp = experiment
125 changes: 123 additions & 2 deletions agentpy/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as colors

from scipy.interpolate import griddata
from SALib.analyze import sobol

from .tools import make_list
from .framework import agent_list


def sensitivity( output, param_ranges, measures = None, **kwargs ):
Expand Down Expand Up @@ -59,15 +61,15 @@ def sensitivity( output, param_ranges, measures = None, **kwargs ):
keys = ['S1','ST']
s2 = {k:v for k,v in SI.items() if k in keys}
df = pd.DataFrame(s2)
df['parameter'] = output.ps_keys()
df['parameter'] = output.parameters.varied.keys()
df['measure'] = measure
df = df.set_index(['measure','parameter'])
dfs_SI.append(df)

keys1 = ['S1_conf','ST_conf']
s3 = {k:v for k,v in SI.items() if k in keys1}
df = pd.DataFrame(s3)
df['parameter'] = output.ps_keys()
df['parameter'] = output.parameters.varied.keys()
df['measure'] = measure
df = df.set_index(['measure','parameter'])
df.columns = ['S1','ST']
Expand All @@ -81,6 +83,125 @@ def sensitivity( output, param_ranges, measures = None, **kwargs ):
return output['sensitivity']




import ipywidgets as widgets
import matplotlib.pyplot as plt

from .tools import make_list
from matplotlib import animation

def animate(model, parameters, fig, axs, plot, skip_t0 = False, **kwargs):

""" Returns an animation of the model simulation """

m = model(parameters)
m._stop = False
m.setup()
m.update()

step0 = True
step00 = not skip_t0

def frames():

nonlocal m, step0, step00

while not m.stop_if() and not m._stop:

if step0: step0 = False
elif step00: step00 = False
else:
m.t += 1
m.step()
m.update()
m.create_output()
yield m.t

def update(t, m, axs):

for ax in make_list(axs):
ax.clear()

if m.t == 0 and skip_t0: pass
else: plot( m, axs )

ani = animation.FuncAnimation(fig, update, frames=frames, fargs=(m, axs), **kwargs)
plt.close() # Don't display static plot

return ani


def interactive(model,param_ranges,output_function,*args,**kwargs):

"""
Returns 'output_function' as an interactive ipywidget
More infos at https://ipywidgets.readthedocs.io/
"""

def make_param(param_updates):

parameters = dict(param_ranges) # Copy
i = 0

for key, value in parameters.items():

if isinstance(v,tuple):
parameters[key] = param_updates[i]
i += 1

def var_run(**param_updates):

parameters = dict(param_ranges)
parameters.update(param_updates)#make_param(param_updates)
temp_model = model(parameters)
temp_model.run(display=False)

output_function(temp_model.output,*args,**kwargs)

# Create widget dict
widget_dict = {}
param_ranges_tuples = { k:v for k,v in param_ranges.items() if isinstance(v,tuple) }
for var_key, var_range in param_ranges_tuples.items():

widget_dict[var_key] = widgets.FloatSlider(
description=var_key,
value = (var_range[1] - var_range[0]) / 2 ,
min = var_range[0],
max = var_range[1],
step = (var_range[1] - var_range[0]) / 10 ,
style = dict(description_width='initial') ,
layout = {'width': '300px'} )

out = widgets.interactive_output(var_run, widget_dict)

return widgets.HBox([ widgets.VBox(list(widget_dict.values())), out ])





def gridplot(model,ax,grid_key,attr_key,color_dict):

def apply_colors(grid,color_assignment,final_type,attr_key):
if not isinstance(grid[0],final_type):
return [apply_colors(subgrid,color_assignment,final_type,attr_key) for subgrid in grid]
else:
return [colors.to_rgb(color_assignment(i,attr_key)) for i in grid]

def color_assignment(a_list,attr_key):

if len(a_list) == 0: return color_dict['empty']
else: return color_dict[a_list[0][attr_key]]

grid = model.envs[grid_key].grid
color_grid = apply_colors(grid,color_assignment,agent_list,attr_key)
im = ax.imshow(color_grid)



def phaseplot(data,x,y,z,n,fill=True,**kwargs):

""" Creates a contour plot displaying the interpolated
Expand Down
Loading

0 comments on commit a23feb6

Please sign in to comment.