mirror of
https://github.com/gsi-upm/soil
synced 2025-10-17 08:48:30 +00:00
Compare commits
16 Commits
0.30.0rc2
...
be65592055
Author | SHA1 | Date | |
---|---|---|---|
|
be65592055 | ||
|
1d882dcff6 | ||
|
b3e77cbff5 | ||
|
05748a3250 | ||
|
a3fc6a5efa | ||
|
4e95709188 | ||
|
feab0ba79e | ||
|
73282530fd | ||
|
2869b1e1e6 | ||
|
d3cee18635 | ||
|
9a7b62e88e | ||
|
c09e480d37 | ||
|
b2d48cb4df | ||
|
a1262edd2a | ||
|
cbbaf73538 | ||
|
2f5e5d0a74 |
@@ -20,7 +20,7 @@ docker:
|
||||
test:
|
||||
tags:
|
||||
- docker
|
||||
image: python:3.7
|
||||
image: python:3.8
|
||||
stage: test
|
||||
script:
|
||||
- pip install -r requirements.txt -r test-requirements.txt
|
||||
@@ -31,7 +31,7 @@ push_pypi:
|
||||
- tags
|
||||
tags:
|
||||
- docker
|
||||
image: python:3.7
|
||||
image: python:3.8
|
||||
stage: publish
|
||||
script:
|
||||
- echo $CI_COMMIT_TAG > soil/VERSION
|
||||
@@ -44,7 +44,7 @@ check_pypi:
|
||||
- tags
|
||||
tags:
|
||||
- docker
|
||||
image: python:3.7
|
||||
image: python:3.8
|
||||
stage: check_published
|
||||
script:
|
||||
- pip install soil==$CI_COMMIT_TAG
|
||||
|
@@ -6,15 +6,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
## [0.30 UNRELEASED]
|
||||
### Added
|
||||
* Simple debugging capabilities in `soil.debugging`, with a custom `pdb.Debugger` subclass that exposes commands to list agents and their status and set breakpoints on states (for FSM agents). Try it with `soil --debug <simulation file>`
|
||||
* Ability to run
|
||||
* Ability to
|
||||
* Ability to run mesa simulations
|
||||
* The `soil.exporters` module to export the results of datacollectors (model.datacollector) into files at the end of trials/simulations
|
||||
* A modular set of classes for environments/models. Now the ability to configure the agents through an agent definition and a topology through a network configuration is split into two classes (`soil.agents.BaseEnvironment` for agents, `soil.agents.NetworkEnvironment` to add topology).
|
||||
* FSM agents can now have generators as states. They work similar to normal states, with one caveat. Only `time` values can be yielded, not a state. This is because the state will not change, it will be resumed after the yield, at the appropriate time. The return value *can* be a state, or a `(state, time)` tuple, just like in normal states.
|
||||
### Changed
|
||||
* Configuration schema is very different now. Check `soil.config` for more information. We are also using Pydantic for (de)serialization.
|
||||
* There may be more than one topology/network in the simulation
|
||||
* Ability
|
||||
* Configuration schema is very simplified
|
||||
### Removed
|
||||
* Any `tsih` and `History` integration in the main classes. To record the state of environments/agents, just use a datacollector. In some cases this may be slower or consume more memory than the previous system. However, few cases actually used the full potential of the history, and it came at the cost of unnecessary complexity and worse performance for the majority of cases.
|
||||
|
||||
|
64
README.md
64
README.md
@@ -1,12 +1,53 @@
|
||||
# [SOIL](https://github.com/gsi-upm/soil)
|
||||
|
||||
|
||||
Soil is an extensible and user-friendly Agent-based Social Simulator for Social Networks.
|
||||
Learn how to run your own simulations with our [documentation](http://soilsim.readthedocs.io).
|
||||
|
||||
Follow our [tutorial](examples/tutorial/soil_tutorial.ipynb) to develop your own agent models.
|
||||
|
||||
> **Warning**
|
||||
> Mesa 0.30 introduced many fundamental changes. Check the [documention on how to update your simulations to work with newer versions](docs/notes_v0.30.rst)
|
||||
|
||||
# Changes in version 0.3
|
||||
## Features
|
||||
|
||||
* Integration with (social) networks (through `networkx`)
|
||||
* Convenience functions and methods to easily assign agents to your model (and optionally to its network):
|
||||
* Following a given distribution (e.g., 2 agents of type `Foo`, 10% of the network should be agents of type `Bar`)
|
||||
* Based on the topology of the network
|
||||
* **Several types of abstractions for agents**:
|
||||
* Finite state machine, where methods can be turned into a state
|
||||
* Network agents, which have convenience methods to access the model's topology
|
||||
* Generator-based agents, whose state is paused though a `yield` and resumed on the next step
|
||||
* **Reporting and data collection**:
|
||||
* Soil models include data collection and record some data by default (# of agents, state of each agent, etc.)
|
||||
* All data collected are exported by default to a SQLite database and a description file
|
||||
* Options to export to other formats, such as CSV, or defining your own exporters
|
||||
* A summary of the data collected is shown in the command line, for easy inspection
|
||||
* **An event-based scheduler**
|
||||
* Agents can be explicit about when their next time/step should be, and not all agents run in every step. This avoids unnecessary computation.
|
||||
* Time intervals between each step are flexible.
|
||||
* There are primitives to specify when the next execution of an agent should be (or conditions)
|
||||
* **Actor-inspired** message-passing
|
||||
* A simulation runner (`soil.Simulation`) that can:
|
||||
* Run models in parallel
|
||||
* Save results to different formats
|
||||
* Simulation configuration files
|
||||
* A command line interface (`soil`), to quickly run simulations with different parameters
|
||||
* An integrated debugger (`soil --debug`) with custom functions to print agent states and break at specific states
|
||||
|
||||
|
||||
## Mesa compatibility
|
||||
|
||||
SOIL has been redesigned to integrate well with [Mesa](https://github.com/projectmesa/mesa).
|
||||
For instance, it should be possible to run a `mesa.Model` models using a `soil.Simulation` and the `soil` CLI, or to integrate the `soil.TimedActivation` scheduler on a `mesa.Model`.
|
||||
|
||||
Note that some combinations of `mesa` and `soil` components, while technically possible, are much less useful or might yield surprising results.
|
||||
For instance, you may add any `soil.agent` agent on a regular `mesa.Model` with a vanilla scheduler from `mesa.time`.
|
||||
But in that case the agents will not get any of the advanced event-based scheduling, and most agent behaviors that depend on that may not work.
|
||||
|
||||
|
||||
## Changes in version 0.3
|
||||
|
||||
Version 0.3 came packed with many changes to provide much better integration with MESA.
|
||||
For a long time, we tried to keep soil backwards-compatible, but it turned out to be a big endeavour and the resulting code was less readable.
|
||||
@@ -18,27 +59,6 @@ If you have an older Soil simulation, you have two options:
|
||||
* Update the necessary configuration files and code. You may use the examples in the `examples` folder for reference, as well as the documentation.
|
||||
* Keep using a previous `soil` version.
|
||||
|
||||
## Mesa compatibility
|
||||
|
||||
Soil is in the process of becoming fully compatible with MESA.
|
||||
The idea is to provide a set of modular classes and functions that extend the functionality of mesa, whilst staying compatible.
|
||||
In the end, it should be possible to add regular mesa agents to a soil simulation, or use a soil agent within a mesa simulation/model.
|
||||
|
||||
This is a non-exhaustive list of tasks to achieve compatibility:
|
||||
|
||||
- [ ] Integrate `soil.Simulation` with mesa's runners:
|
||||
- [ ] `soil.Simulation` could mimic/become a `mesa.batchrunner`
|
||||
- [ ] Integrate `soil.Environment` with `mesa.Model`:
|
||||
- [x] `Soil.Environment` inherits from `mesa.Model`
|
||||
- [x] `Soil.Environment` includes a Mesa-like Scheduler (see the `soil.time` module.
|
||||
- [ ] Allow for `mesa.Model` to be used in a simulation.
|
||||
- [ ] Integrate `soil.Agent` with `mesa.Agent`:
|
||||
- [x] Rename agent.id to unique_id?
|
||||
- [x] mesa agents can be used in soil simulations (see `examples/mesa`)
|
||||
- [ ] Provide examples
|
||||
- [ ] Using mesa modules in a soil simulation
|
||||
- [ ] Using soil modules in a mesa simulation
|
||||
- [ ] Document the new APIs and usage
|
||||
|
||||
|
||||
## Citation
|
||||
|
@@ -1,262 +0,0 @@
|
||||
Configuring a simulation
|
||||
------------------------
|
||||
|
||||
There are two ways to configure a simulation: programmatically and with a configuration file.
|
||||
In both cases, the parameters used are the same.
|
||||
The advantage of a configuration file is that it is a clean declarative description, and it makes it easier to reproduce.
|
||||
|
||||
Simulation configuration files can be formatted in ``json`` or ``yaml`` and they define all the parameters of a simulation.
|
||||
Here's an example (``example.yml``).
|
||||
|
||||
.. literalinclude:: example.yml
|
||||
:language: yaml
|
||||
|
||||
|
||||
This example configuration will run three trials (``num_trials``) of a simulation containing a randomly generated network (``network_params``).
|
||||
The 100 nodes in the network will be SISaModel agents (``network_agents.agent_class``), which is an agent behavior that is included in Soil.
|
||||
10% of the agents (``weight=1``) will start in the content state, 10% in the discontent state, and the remaining 80% (``weight=8``) in the neutral state.
|
||||
All agents will have access to the environment (``environment_params``), which only contains one variable, ``prob_infected``.
|
||||
The state of the agents will be updated every 2 seconds (``interval``).
|
||||
|
||||
Now run the simulation with the command line tool:
|
||||
|
||||
.. code:: bash
|
||||
|
||||
soil example.yml
|
||||
|
||||
Once the simulation finishes, its results will be stored in a folder named ``MyExampleSimulation``.
|
||||
Three types of objects are saved by default: a pickle of the simulation; a ``YAML`` representation of the simulation (which can be used to re-launch it); and for every trial, a ``sqlite`` file with the content of the state of every network node and the environment parameters at every step of the simulation.
|
||||
|
||||
|
||||
.. code::
|
||||
|
||||
soil_output
|
||||
└── MyExampleSimulation
|
||||
├── MyExampleSimulation.dumped.yml
|
||||
├── MyExampleSimulation.simulation.pickle
|
||||
├── MyExampleSimulation_trial_0.db.sqlite
|
||||
├── MyExampleSimulation_trial_1.db.sqlite
|
||||
└── MyExampleSimulation_trial_2.db.sqlite
|
||||
|
||||
|
||||
You may also ask soil to export the states in a ``csv`` file, and the network in gephi format (``gexf``).
|
||||
|
||||
Network
|
||||
=======
|
||||
|
||||
The network topology for the simulation can be loaded from an existing network file or generated with one of the random network generation methods from networkx.
|
||||
|
||||
Loading a network
|
||||
#################
|
||||
|
||||
To load an existing network, specify its path in the configuration:
|
||||
|
||||
.. code:: yaml
|
||||
|
||||
---
|
||||
network_params:
|
||||
path: /tmp/mynetwork.gexf
|
||||
|
||||
Soil will try to guess what networkx method to use to read the file based on its extension.
|
||||
However, we only test using ``gexf`` files.
|
||||
|
||||
For simple networks, you may also include them in the configuration itself using , using the ``topology`` parameter like so:
|
||||
|
||||
.. code:: yaml
|
||||
|
||||
---
|
||||
topology:
|
||||
nodes:
|
||||
- id: First
|
||||
- id: Second
|
||||
links:
|
||||
- source: First
|
||||
target: Second
|
||||
|
||||
|
||||
Generating a random network
|
||||
###########################
|
||||
|
||||
To generate a random network using one of networkx's built-in methods, specify the `graph generation algorithm <https://networkx.github.io/documentation/development/reference/generators.html>`_ and other parameters.
|
||||
For example, the following configuration is equivalent to :code:`nx.complete_graph(n=100)`:
|
||||
|
||||
.. code:: yaml
|
||||
|
||||
network_params:
|
||||
generator: complete_graph
|
||||
n: 100
|
||||
|
||||
Environment
|
||||
============
|
||||
|
||||
The environment is the place where the shared state of the simulation is stored.
|
||||
That means both global parameters, such as the probability of disease outbreak.
|
||||
But it also means other data, such as a map, or a network topology that connects multiple agents.
|
||||
As a result, it is also typical to add custom functions in an environment that help agents interact with each other and with the state of the simulation.
|
||||
|
||||
Last but not least, an environment controls when and how its agents will be executed.
|
||||
By default, soil environments incorporate a ``soil.time.TimedActivation`` model for agent execution (more on this on the following section).
|
||||
|
||||
Soil environments are very similar, and often interchangeable with, mesa models (``mesa.Model``).
|
||||
|
||||
A configuration may specify the initial value of the environment parameters:
|
||||
|
||||
.. code:: yaml
|
||||
|
||||
environment_params:
|
||||
daily_probability_of_earthquake: 0.001
|
||||
number_of_earthquakes: 0
|
||||
|
||||
All agents have access to the environment (and its parameters).
|
||||
|
||||
In some scenarios, it is useful to have a custom environment, to provide additional methods or to control the way agents update environment state.
|
||||
For example, if our agents play the lottery, the environment could provide a method to decide whether the agent wins, instead of leaving it to the agent.
|
||||
|
||||
Agents
|
||||
======
|
||||
|
||||
Agents are a way of modelling behavior.
|
||||
Agents can be characterized with two variables: agent type (``agent_class``) and state.
|
||||
The agent type is a ``soil.Agent`` class, which contains the code that encapsulates the behavior of the agent.
|
||||
The state is a set of variables, which may change during the simulation, and that the code may use to control the behavior.
|
||||
All agents provide a ``step`` method either explicitly or implicitly (by inheriting it from a superclass), which controls how the agent will behave in each step of the simulation.
|
||||
|
||||
When and how agent steps are executed in a simulation depends entirely on the ``environment``.
|
||||
Most environments will internally use a scheduler (``mesa.time.BaseScheduler``), which controls the activation of agents.
|
||||
|
||||
In soil, we generally used the ``soil.time.TimedActivation`` scheduler, which allows agents to specify when their next activation will happen, defaulting to a
|
||||
|
||||
When an agent's step is executed (generally, every ``interval`` seconds), the agent has access to its state and the environment.
|
||||
Through the environment, it can access the network topology and the state of other agents.
|
||||
|
||||
There are two types of agents according to how they are added to the simulation: network agents and environment agent.
|
||||
|
||||
Network Agents
|
||||
##############
|
||||
|
||||
Network agents are attached to a node in the topology.
|
||||
The configuration file allows you to specify how agents will be mapped to topology nodes.
|
||||
|
||||
The simplest way is to specify a single type of agent.
|
||||
Hence, every node in the network will be associated to an agent of that type.
|
||||
|
||||
.. code:: yaml
|
||||
|
||||
agent_class: SISaModel
|
||||
|
||||
It is also possible to add more than one type of agent to the simulation.
|
||||
|
||||
To control the ratio of each type (using the ``weight`` property).
|
||||
For instance, with following configuration, it is five times more likely for a node to be assigned a CounterModel type than a SISaModel type.
|
||||
|
||||
.. code:: yaml
|
||||
|
||||
network_agents:
|
||||
- agent_class: SISaModel
|
||||
weight: 1
|
||||
- agent_class: CounterModel
|
||||
weight: 5
|
||||
|
||||
The third option is to specify the type of agent on the node itself, e.g.:
|
||||
|
||||
|
||||
.. code:: yaml
|
||||
|
||||
topology:
|
||||
nodes:
|
||||
- id: first
|
||||
agent_class: BaseAgent
|
||||
states:
|
||||
first:
|
||||
agent_class: SISaModel
|
||||
|
||||
|
||||
This would also work with a randomly generated network:
|
||||
|
||||
|
||||
.. code:: yaml
|
||||
|
||||
network:
|
||||
generator: complete
|
||||
n: 5
|
||||
agent_class: BaseAgent
|
||||
states:
|
||||
- agent_class: SISaModel
|
||||
|
||||
|
||||
|
||||
In addition to agent type, you may add a custom initial state to the distribution.
|
||||
This is very useful to add the same agent type with different states.
|
||||
e.g., to populate the network with SISaModel, roughly 10% of them with a discontent state:
|
||||
|
||||
.. code:: yaml
|
||||
|
||||
network_agents:
|
||||
- agent_class: SISaModel
|
||||
weight: 9
|
||||
state:
|
||||
id: neutral
|
||||
- agent_class: SISaModel
|
||||
weight: 1
|
||||
state:
|
||||
id: discontent
|
||||
|
||||
Lastly, the configuration may include initial state for one or more nodes.
|
||||
For instance, to add a state for the two nodes in this configuration:
|
||||
|
||||
.. code:: yaml
|
||||
|
||||
agent_class: SISaModel
|
||||
network:
|
||||
generator: complete_graph
|
||||
n: 2
|
||||
states:
|
||||
- id: content
|
||||
- id: discontent
|
||||
|
||||
|
||||
Or to add state only to specific nodes (by ``id``).
|
||||
For example, to apply special skills to Linux Torvalds in a simulation:
|
||||
|
||||
.. literalinclude:: ../examples/torvalds.yml
|
||||
:language: yaml
|
||||
|
||||
|
||||
Environment Agents
|
||||
##################
|
||||
In addition to network agents, more agents can be added to the simulation.
|
||||
These agents are programmed in much the same way as network agents, the only difference is that they will not be assigned to network nodes.
|
||||
|
||||
|
||||
.. code::
|
||||
|
||||
environment_agents:
|
||||
- agent_class: MyAgent
|
||||
state:
|
||||
mood: happy
|
||||
- agent_class: DummyAgent
|
||||
|
||||
|
||||
You may use environment agents to model events that a normal agent cannot control, such as natural disasters or chance.
|
||||
They are also useful to add behavior that has little to do with the network and the interactions within that network.
|
||||
|
||||
Templating
|
||||
==========
|
||||
|
||||
Sometimes, it is useful to parameterize a simulation and run it over a range of values in order to compare each run and measure the effect of those parameters in the simulation.
|
||||
For instance, you may want to run a simulation with different agent distributions.
|
||||
|
||||
This can be done in Soil using **templates**.
|
||||
A template is a configuration where some of the values are specified with a variable.
|
||||
e.g., ``weight: "{{ var1 }}"`` instead of ``weight: 1``.
|
||||
There are two types of variables, depending on how their values are decided:
|
||||
|
||||
* Fixed. A list of values is provided, and a new simulation is run for each possible value. If more than a variable is given, a new simulation will be run per combination of values.
|
||||
* Bounded/Sampled. The bounds of the variable are provided, along with a sampler method, which will be used to compute all the configuration combinations.
|
||||
|
||||
When fixed and bounded variables are mixed, Soil generates a new configuration per combination of fixed values and bounded values.
|
||||
|
||||
Here is an example with a single fixed variable and two bounded variable:
|
||||
|
||||
.. literalinclude:: ../examples/template.yml
|
||||
:language: yaml
|
@@ -3,33 +3,38 @@ name: MyExampleSimulation
|
||||
max_time: 50
|
||||
num_trials: 3
|
||||
interval: 2
|
||||
network_params:
|
||||
generator: barabasi_albert_graph
|
||||
n: 100
|
||||
m: 2
|
||||
network_agents:
|
||||
model_params:
|
||||
topology:
|
||||
params:
|
||||
generator: barabasi_albert_graph
|
||||
n: 100
|
||||
m: 2
|
||||
agents:
|
||||
distribution:
|
||||
- agent_class: SISaModel
|
||||
weight: 1
|
||||
topology: True
|
||||
ratio: 0.1
|
||||
state:
|
||||
id: content
|
||||
state_id: content
|
||||
- agent_class: SISaModel
|
||||
weight: 1
|
||||
topology: True
|
||||
ratio: .1
|
||||
state:
|
||||
id: discontent
|
||||
state_id: discontent
|
||||
- agent_class: SISaModel
|
||||
weight: 8
|
||||
topology: True
|
||||
ratio: 0.8
|
||||
state:
|
||||
id: neutral
|
||||
environment_params:
|
||||
prob_infect: 0.075
|
||||
neutral_discontent_spon_prob: 0.1
|
||||
neutral_discontent_infected_prob: 0.3
|
||||
neutral_content_spon_prob: 0.3
|
||||
neutral_content_infected_prob: 0.4
|
||||
discontent_neutral: 0.5
|
||||
discontent_content: 0.5
|
||||
variance_d_c: 0.2
|
||||
content_discontent: 0.2
|
||||
variance_c_d: 0.2
|
||||
content_neutral: 0.2
|
||||
standard_variance: 1
|
||||
state_id: neutral
|
||||
prob_infect: 0.075
|
||||
neutral_discontent_spon_prob: 0.1
|
||||
neutral_discontent_infected_prob: 0.3
|
||||
neutral_content_spon_prob: 0.3
|
||||
neutral_content_infected_prob: 0.4
|
||||
discontent_neutral: 0.5
|
||||
discontent_content: 0.5
|
||||
variance_d_c: 0.2
|
||||
content_discontent: 0.2
|
||||
variance_c_d: 0.2
|
||||
content_neutral: 0.2
|
||||
standard_variance: 1
|
@@ -1,8 +1,3 @@
|
||||
.. Soil documentation master file, created by
|
||||
sphinx-quickstart on Tue Apr 25 12:48:56 2017.
|
||||
You can adapt this file completely to your liking, but it should at least
|
||||
contain the root `toctree` directive.
|
||||
|
||||
Welcome to Soil's documentation!
|
||||
================================
|
||||
|
||||
|
@@ -14,6 +14,10 @@ Now test that it worked by running the command line tool
|
||||
|
||||
soil --help
|
||||
|
||||
#or
|
||||
|
||||
python -m soil --help
|
||||
|
||||
Or, if you're using using soil programmatically:
|
||||
|
||||
.. code:: python
|
||||
@@ -21,4 +25,4 @@ Or, if you're using using soil programmatically:
|
||||
import soil
|
||||
print(soil.__version__)
|
||||
|
||||
The latest version can be installed through `GitLab <https://lab.gsi.upm.es/soil/soil.git>`_ or `GitHub <https://github.com/gsi-upm/soil>`_.
|
||||
The latest version can be installed through `GitHub <https://github.com/gsi-upm/soil>`_ or `GitLab <https://lab.gsi.upm.es/soil/soil.git>`_.
|
||||
|
@@ -12,7 +12,7 @@ set BUILDDIR=_build
|
||||
set SPHINXPROJ=Soil
|
||||
|
||||
if "%1" == "" goto help
|
||||
|
||||
eE
|
||||
%SPHINXBUILD% >NUL 2>NUL
|
||||
if errorlevel 9009 (
|
||||
echo.
|
||||
|
22
docs/mesa.rst
Normal file
22
docs/mesa.rst
Normal file
@@ -0,0 +1,22 @@
|
||||
Mesa compatibility
|
||||
------------------
|
||||
|
||||
Soil is in the process of becoming fully compatible with MESA.
|
||||
The idea is to provide a set of modular classes and functions that extend the functionality of mesa, whilst staying compatible.
|
||||
In the end, it should be possible to add regular mesa agents to a soil simulation, or use a soil agent within a mesa simulation/model.
|
||||
|
||||
This is a non-exhaustive list of tasks to achieve compatibility:
|
||||
|
||||
- [ ] Integrate `soil.Simulation` with mesa's runners:
|
||||
- [ ] `soil.Simulation` could mimic/become a `mesa.batchrunner`
|
||||
- [ ] Integrate `soil.Environment` with `mesa.Model`:
|
||||
- [x] `Soil.Environment` inherits from `mesa.Model`
|
||||
- [x] `Soil.Environment` includes a Mesa-like Scheduler (see the `soil.time` module.
|
||||
- [ ] Allow for `mesa.Model` to be used in a simulation.
|
||||
- [ ] Integrate `soil.Agent` with `mesa.Agent`:
|
||||
- [x] Rename agent.id to unique_id?
|
||||
- [x] mesa agents can be used in soil simulations (see `examples/mesa`)
|
||||
- [ ] Provide examples
|
||||
- [ ] Using mesa modules in a soil simulation
|
||||
- [ ] Using soil modules in a mesa simulation
|
||||
- [ ] Document the new APIs and usage
|
35
docs/notes_v0.30.rst
Normal file
35
docs/notes_v0.30.rst
Normal file
@@ -0,0 +1,35 @@
|
||||
What are the main changes between version 0.3 and 0.2?
|
||||
######################################################
|
||||
|
||||
Version 0.3 is a major rewrite of the Soil system, focused on simplifying the API, aligning it with Mesa, and making it easier to use.
|
||||
Unfortunately, this comes at the cost of backwards compatibility.
|
||||
|
||||
We drew several lessons from the previous version of Soil, and tried to address them in this version.
|
||||
Mainly:
|
||||
|
||||
- The split between simulation configuration and simulation code was overly complicated for most use cases. As a result, most users ended up reusing configuration.
|
||||
- Storing **all** the simulation data in a database is costly and unnecessary for most use cases. For most use cases, only a handful of variables need to be stored. This fits nicely with Mesa's data collection system.
|
||||
- The API was too complex, and it was difficult to understand how to use it.
|
||||
- Most parts of the API were not aligned with Mesa, which made it difficult to use Mesa's features or to integrate Soil modules with Mesa code, especially for newcomers.
|
||||
- Many parts of the API were tightly coupled, which made it difficult to find bugs, test the system and add new features.
|
||||
|
||||
The 0.30 rewrite should provide a middle ground between Soil's opinionated approach and Mesa's flexibility.
|
||||
The new Soil is less configuration-centric.
|
||||
It aims to provide more modular and convenient functions, most of which can be used in vanilla Mesa.
|
||||
|
||||
How are agents assigned to nodes in the network
|
||||
###############################################
|
||||
|
||||
The constructor of the `NetworkAgent` class has two arguments: `node_id` and `topology`.
|
||||
If `topology` is not provided, it will default to `self.model.topology`.
|
||||
This assignment might err if the model does not have a `topology` attribute, but most Soil environments derive from `NetworkEnvironment`, so they include a topology by default.
|
||||
If `node_id` is not provided, a random node will be selected from the topology, until a node with no agent is found.
|
||||
Then, the `node_id` of that node is assigned to the agent.
|
||||
If no node with no agent is found, a new node is automatically added to the topology.
|
||||
|
||||
|
||||
Can Soil environments include more than one network / topology?
|
||||
###############################################################
|
||||
|
||||
Yes, but each network has to be included manually.
|
||||
Somewhere between 0.20 and 0.30 we included the ability to include multiple networks, but it was deemed too complex and was removed.
|
@@ -2,29 +2,32 @@
|
||||
name: quickstart
|
||||
num_trials: 1
|
||||
max_time: 1000
|
||||
network_agents:
|
||||
- agent_class: SISaModel
|
||||
state:
|
||||
id: neutral
|
||||
weight: 1
|
||||
- agent_class: SISaModel
|
||||
state:
|
||||
id: content
|
||||
weight: 2
|
||||
network_params:
|
||||
n: 100
|
||||
k: 5
|
||||
p: 0.2
|
||||
generator: newman_watts_strogatz_graph
|
||||
environment_params:
|
||||
neutral_discontent_spon_prob: 0.05
|
||||
neutral_discontent_infected_prob: 0.1
|
||||
neutral_content_spon_prob: 0.2
|
||||
neutral_content_infected_prob: 0.4
|
||||
discontent_neutral: 0.2
|
||||
discontent_content: 0.05
|
||||
content_discontent: 0.05
|
||||
variance_d_c: 0.05
|
||||
variance_c_d: 0.1
|
||||
content_neutral: 0.1
|
||||
standard_variance: 0.1
|
||||
model_params:
|
||||
agents:
|
||||
- agent_class: SISaModel
|
||||
topology: true
|
||||
state:
|
||||
id: neutral
|
||||
weight: 1
|
||||
- agent_class: SISaModel
|
||||
topology: true
|
||||
state:
|
||||
id: content
|
||||
weight: 2
|
||||
topology:
|
||||
params:
|
||||
n: 100
|
||||
k: 5
|
||||
p: 0.2
|
||||
generator: newman_watts_strogatz_graph
|
||||
neutral_discontent_spon_prob: 0.05
|
||||
neutral_discontent_infected_prob: 0.1
|
||||
neutral_content_spon_prob: 0.2
|
||||
neutral_content_infected_prob: 0.4
|
||||
discontent_neutral: 0.2
|
||||
discontent_content: 0.05
|
||||
content_discontent: 0.05
|
||||
variance_d_c: 0.05
|
||||
variance_c_d: 0.1
|
||||
content_neutral: 0.1
|
||||
standard_variance: 0.1
|
||||
|
@@ -115,13 +115,13 @@ Here's the code:
|
||||
@soil.agents.state
|
||||
def neutral(self):
|
||||
r = random.random()
|
||||
if self['has_tv'] and r < self.env['prob_tv_spread']:
|
||||
if self['has_tv'] and r < self.model['prob_tv_spread']:
|
||||
return self.infected
|
||||
return
|
||||
|
||||
@soil.agents.state
|
||||
def infected(self):
|
||||
prob_infect = self.env['prob_neighbor_spread']
|
||||
prob_infect = self.model['prob_neighbor_spread']
|
||||
for neighbor in self.get_neighboring_agents(state_id=self.neutral.id):
|
||||
r = random.random()
|
||||
if r < prob_infect:
|
||||
@@ -146,11 +146,11 @@ spreading the rumor.
|
||||
class NewsEnvironmentAgent(soil.agents.BaseAgent):
|
||||
def step(self):
|
||||
if self.now == self['event_time']:
|
||||
self.env['prob_tv_spread'] = 1
|
||||
self.env['prob_neighbor_spread'] = 1
|
||||
self.model['prob_tv_spread'] = 1
|
||||
self.model['prob_neighbor_spread'] = 1
|
||||
elif self.now > self['event_time']:
|
||||
self.env['prob_tv_spread'] = self.env['prob_tv_spread'] * TV_FACTOR
|
||||
self.env['prob_neighbor_spread'] = self.env['prob_neighbor_spread'] * NEIGHBOR_FACTOR
|
||||
self.model['prob_tv_spread'] = self.model['prob_tv_spread'] * TV_FACTOR
|
||||
self.model['prob_neighbor_spread'] = self.model['prob_neighbor_spread'] * NEIGHBOR_FACTOR
|
||||
|
||||
Testing the agents
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
File diff suppressed because one or more lines are too long
80808
examples/Untitled.ipynb
80808
examples/Untitled.ipynb
File diff suppressed because it is too large
Load Diff
@@ -1,54 +0,0 @@
|
||||
---
|
||||
version: '2'
|
||||
name: simple
|
||||
group: tests
|
||||
dir_path: "/tmp/"
|
||||
num_trials: 3
|
||||
max_steps: 100
|
||||
interval: 1
|
||||
seed: "CompleteSeed!"
|
||||
model_class: Environment
|
||||
model_params:
|
||||
am_i_complete: true
|
||||
topology:
|
||||
params:
|
||||
generator: complete_graph
|
||||
n: 12
|
||||
environment:
|
||||
agents:
|
||||
agent_class: CounterModel
|
||||
topology: true
|
||||
state:
|
||||
times: 1
|
||||
# In this group we are not specifying any topology
|
||||
fixed:
|
||||
- name: 'Environment Agent 1'
|
||||
agent_class: BaseAgent
|
||||
group: environment
|
||||
topology: false
|
||||
hidden: true
|
||||
state:
|
||||
times: 10
|
||||
- agent_class: CounterModel
|
||||
id: 0
|
||||
group: fixed_counters
|
||||
state:
|
||||
times: 1
|
||||
total: 0
|
||||
- agent_class: CounterModel
|
||||
group: fixed_counters
|
||||
id: 1
|
||||
distribution:
|
||||
- agent_class: CounterModel
|
||||
weight: 1
|
||||
group: distro_counters
|
||||
state:
|
||||
times: 3
|
||||
- agent_class: AggregatedCounter
|
||||
weight: 0.2
|
||||
override:
|
||||
- filter:
|
||||
agent_class: AggregatedCounter
|
||||
n: 2
|
||||
state:
|
||||
times: 5
|
@@ -1,16 +0,0 @@
|
||||
---
|
||||
name: custom-generator
|
||||
description: Using a custom generator for the network
|
||||
num_trials: 3
|
||||
max_steps: 100
|
||||
interval: 1
|
||||
network_params:
|
||||
generator: mymodule.mygenerator
|
||||
# These are custom parameters
|
||||
n: 10
|
||||
n_edges: 5
|
||||
network_agents:
|
||||
- agent_class: CounterModel
|
||||
weight: 1
|
||||
state:
|
||||
state_id: 0
|
@@ -1,6 +1,7 @@
|
||||
from networkx import Graph
|
||||
import random
|
||||
import networkx as nx
|
||||
from soil import Simulation, Environment, CounterModel, parameters
|
||||
|
||||
|
||||
def mygenerator(n=5, n_edges=5):
|
||||
@@ -20,3 +21,19 @@ def mygenerator(n=5, n_edges=5):
|
||||
n_out = random.choice(nodes)
|
||||
G.add_edge(n_in, n_out)
|
||||
return G
|
||||
|
||||
|
||||
class GeneratorEnv(Environment):
|
||||
"""Using a custom generator for the network"""
|
||||
|
||||
generator: parameters.function = staticmethod(mygenerator)
|
||||
|
||||
def init(self):
|
||||
self.create_network(generator=self.generator, n=10, n_edges=5)
|
||||
self.add_agents(CounterModel)
|
||||
|
||||
|
||||
sim = Simulation(model=GeneratorEnv, max_steps=10, interval=1)
|
||||
|
||||
if __name__ == '__main__':
|
||||
sim.run(dump=False)
|
@@ -1,17 +1,17 @@
|
||||
from soil.agents import FSM, state, default_state
|
||||
from soil.time import Delta
|
||||
|
||||
|
||||
class Fibonacci(FSM):
|
||||
"""Agent that only executes in t_steps that are Fibonacci numbers"""
|
||||
|
||||
defaults = {"prev": 1}
|
||||
prev = 1
|
||||
|
||||
@default_state
|
||||
@state
|
||||
def counting(self):
|
||||
self.log("Stopping at {}".format(self.now))
|
||||
prev, self["prev"] = self["prev"], max([self.now, self["prev"]])
|
||||
return None, self.env.timeout(prev)
|
||||
return None, Delta(prev)
|
||||
|
||||
|
||||
class Odds(FSM):
|
||||
@@ -21,18 +21,21 @@ class Odds(FSM):
|
||||
@state
|
||||
def odds(self):
|
||||
self.log("Stopping at {}".format(self.now))
|
||||
return None, self.env.timeout(1 + self.now % 2)
|
||||
return None, Delta(1 + self.now % 2)
|
||||
|
||||
|
||||
from soil import Environment, Simulation
|
||||
from networkx import complete_graph
|
||||
|
||||
|
||||
class TimeoutsEnv(Environment):
|
||||
def init(self):
|
||||
self.create_network(generator=complete_graph, n=2)
|
||||
self.add_agent(agent_class=Fibonacci, node_id=0)
|
||||
self.add_agent(agent_class=Odds, node_id=1)
|
||||
|
||||
|
||||
sim = Simulation(model=TimeoutsEnv, max_steps=10, interval=1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
from soil import Simulation
|
||||
|
||||
s = Simulation(
|
||||
network_agents=[
|
||||
{"ids": [0], "agent_class": Fibonacci},
|
||||
{"ids": [1], "agent_class": Odds},
|
||||
],
|
||||
network_params={"generator": "complete_graph", "n": 2},
|
||||
max_time=100,
|
||||
)
|
||||
s.run(dry_run=True)
|
||||
sim.run(dump=False)
|
@@ -2,6 +2,8 @@ This example can be run like with command-line options, like this:
|
||||
|
||||
```bash
|
||||
python cars.py --level DEBUG -e summary --csv
|
||||
#or
|
||||
soil cars.py -e summary
|
||||
```
|
||||
|
||||
This will set the `CSV` (save the agent and model data to a CSV) and `summary` (print the a summary of the data to stdout) exporters, and set the log level to DEBUG.
|
||||
|
@@ -18,6 +18,7 @@ An example scenario could play like the following:
|
||||
- If there are no more passengers available in the simulation, Drivers die
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from typing import Optional
|
||||
from soil import *
|
||||
from soil import events
|
||||
from mesa.space import MultiGrid
|
||||
@@ -28,17 +29,18 @@ from mesa.space import MultiGrid
|
||||
@dataclass
|
||||
class Journey:
|
||||
"""
|
||||
This represents a request for a journey. Passengers and drivers exchange this object.
|
||||
This represents a request for a journey. Passengers and drivers exchange this object.
|
||||
|
||||
A journey may have a driver assigned or not. If the driver has not been assigned, this
|
||||
object is considered a "request for a journey".
|
||||
"""
|
||||
|
||||
origin: (int, int)
|
||||
destination: (int, int)
|
||||
tip: float
|
||||
|
||||
passenger: Passenger
|
||||
driver: Driver = None
|
||||
driver: Optional[Driver] = None
|
||||
|
||||
|
||||
class City(EventedEnvironment):
|
||||
@@ -54,28 +56,25 @@ class City(EventedEnvironment):
|
||||
:param int height: Height of the internal grid
|
||||
:param int width: Width of the internal grid
|
||||
"""
|
||||
def __init__(self, *args, n_cars=1, n_passengers=10,
|
||||
height=100, width=100, agents=None,
|
||||
model_reporters=None,
|
||||
**kwargs):
|
||||
self.grid = MultiGrid(width=width, height=height, torus=False)
|
||||
if agents is None:
|
||||
agents = []
|
||||
for i in range(n_cars):
|
||||
agents.append({'agent_class': Driver})
|
||||
for i in range(n_passengers):
|
||||
agents.append({'agent_class': Passenger})
|
||||
model_reporters = model_reporters or {'earnings': 'total_earnings', 'n_passengers': 'number_passengers'}
|
||||
print('REPORTERS', model_reporters)
|
||||
super().__init__(*args, agents=agents, model_reporters=model_reporters, **kwargs)
|
||||
n_cars = 1
|
||||
n_passengers = 10
|
||||
height = 100
|
||||
width = 100
|
||||
|
||||
def init(self):
|
||||
self.grid = MultiGrid(width=self.width, height=self.height, torus=False)
|
||||
if not self.agents:
|
||||
self.add_agents(Driver, k=self.n_cars)
|
||||
self.add_agents(Passenger, k=self.n_passengers)
|
||||
|
||||
for agent in self.agents:
|
||||
self.grid.place_agent(agent, (0, 0))
|
||||
self.grid.move_to_empty(agent)
|
||||
|
||||
self.total_earnings = 0
|
||||
self.add_model_reporter("total_earnings")
|
||||
|
||||
@property
|
||||
def total_earnings(self):
|
||||
return sum(d.earnings for d in self.agents(agent_class=Driver))
|
||||
|
||||
@report
|
||||
@property
|
||||
def number_passengers(self):
|
||||
return self.count_agents(agent_class=Passenger)
|
||||
@@ -87,13 +86,13 @@ class Driver(Evented, FSM):
|
||||
earnings = 0
|
||||
|
||||
def on_receive(self, msg, sender):
|
||||
'''This is not a state. It will run (and block) every time check_messages is invoked'''
|
||||
"""This is not a state. It will run (and block) every time check_messages is invoked"""
|
||||
if self.journey is None and isinstance(msg, Journey) and msg.driver is None:
|
||||
msg.driver = self
|
||||
self.journey = msg
|
||||
|
||||
def check_passengers(self):
|
||||
'''If there are no more passengers, stop forever'''
|
||||
"""If there are no more passengers, stop forever"""
|
||||
c = self.count_agents(agent_class=Passenger)
|
||||
self.info(f"Passengers left {c}")
|
||||
if not c:
|
||||
@@ -102,17 +101,20 @@ class Driver(Evented, FSM):
|
||||
@default_state
|
||||
@state
|
||||
def wandering(self):
|
||||
'''Move around the city until a journey is accepted'''
|
||||
"""Move around the city until a journey is accepted"""
|
||||
target = None
|
||||
self.check_passengers()
|
||||
self.journey = None
|
||||
while self.journey is None: # No potential journeys detected (see on_receive)
|
||||
if target is None or not self.move_towards(target):
|
||||
target = self.random.choice(self.model.grid.get_neighborhood(self.pos, moore=False))
|
||||
target = self.random.choice(
|
||||
self.model.grid.get_neighborhood(self.pos, moore=False)
|
||||
)
|
||||
|
||||
self.check_passengers()
|
||||
self.check_messages() # This will call on_receive behind the scenes, and the agent's status will be updated
|
||||
yield Delta(30) # Wait at least 30 seconds before checking again
|
||||
# This will call on_receive behind the scenes, and the agent's status will be updated
|
||||
self.check_messages()
|
||||
yield Delta(30) # Wait at least 30 seconds before checking again
|
||||
|
||||
try:
|
||||
# Re-send the journey to the passenger, to confirm that we have been selected
|
||||
@@ -126,17 +128,18 @@ class Driver(Evented, FSM):
|
||||
|
||||
@state
|
||||
def driving(self):
|
||||
'''The journey has been accepted. Pick them up and take them to their destination'''
|
||||
"""The journey has been accepted. Pick them up and take them to their destination"""
|
||||
while self.move_towards(self.journey.origin):
|
||||
yield
|
||||
while self.move_towards(self.journey.destination, with_passenger=True):
|
||||
yield
|
||||
self.earnings += self.journey.tip
|
||||
self.model.total_earnings += self.journey.tip
|
||||
self.check_passengers()
|
||||
return self.wandering
|
||||
|
||||
def move_towards(self, target, with_passenger=False):
|
||||
'''Move one cell at a time towards a target'''
|
||||
"""Move one cell at a time towards a target"""
|
||||
self.info(f"Moving { self.pos } -> { target }")
|
||||
if target[0] == self.pos[0] and target[1] == self.pos[1]:
|
||||
return False
|
||||
@@ -151,30 +154,36 @@ class Driver(Evented, FSM):
|
||||
break
|
||||
self.model.grid.move_agent(self, tuple(next_pos))
|
||||
if with_passenger:
|
||||
self.journey.passenger.pos = self.pos # This could be communicated through messages
|
||||
self.journey.passenger.pos = (
|
||||
self.pos
|
||||
) # This could be communicated through messages
|
||||
return True
|
||||
|
||||
|
||||
|
||||
class Passenger(Evented, FSM):
|
||||
pos = None
|
||||
|
||||
def on_receive(self, msg, sender):
|
||||
'''This is not a state. It will be run synchronously every time `check_messages` is run'''
|
||||
"""This is not a state. It will be run synchronously every time `check_messages` is run"""
|
||||
|
||||
if isinstance(msg, Journey):
|
||||
self.journey = msg
|
||||
return msg
|
||||
|
||||
|
||||
@default_state
|
||||
@state
|
||||
def asking(self):
|
||||
destination = (self.random.randint(0, self.model.grid.height), self.random.randint(0, self.model.grid.width))
|
||||
destination = (
|
||||
self.random.randint(0, self.model.grid.height),
|
||||
self.random.randint(0, self.model.grid.width),
|
||||
)
|
||||
self.journey = None
|
||||
journey = Journey(origin=self.pos,
|
||||
destination=destination,
|
||||
tip=self.random.randint(10, 100),
|
||||
passenger=self)
|
||||
journey = Journey(
|
||||
origin=self.pos,
|
||||
destination=destination,
|
||||
tip=self.random.randint(10, 100),
|
||||
passenger=self,
|
||||
)
|
||||
|
||||
timeout = 60
|
||||
expiration = self.now + timeout
|
||||
@@ -182,24 +191,36 @@ class Passenger(Evented, FSM):
|
||||
while not self.journey:
|
||||
self.info(f"Passenger at: { self.pos }. Checking for responses.")
|
||||
try:
|
||||
# This will call check_messages behind the scenes, and the agent's status will be updated
|
||||
# If you want to avoid that, you can call it with: check=False
|
||||
yield self.received(expiration=expiration)
|
||||
except events.TimedOut:
|
||||
self.info(f"Passenger at: { self.pos }. Asking for journey.")
|
||||
self.model.broadcast(journey, ttl=timeout, sender=self, agent_class=Driver)
|
||||
self.model.broadcast(
|
||||
journey, ttl=timeout, sender=self, agent_class=Driver
|
||||
)
|
||||
expiration = self.now + timeout
|
||||
self.check_messages()
|
||||
return self.driving_home
|
||||
|
||||
@state
|
||||
def driving_home(self):
|
||||
while self.pos[0] != self.journey.destination[0] or self.pos[1] != self.journey.destination[1]:
|
||||
yield self.received(timeout=60)
|
||||
self.info("Got home safe!")
|
||||
self.die()
|
||||
while (
|
||||
self.pos[0] != self.journey.destination[0]
|
||||
or self.pos[1] != self.journey.destination[1]
|
||||
):
|
||||
try:
|
||||
yield self.received(timeout=60)
|
||||
except events.TimedOut:
|
||||
pass
|
||||
|
||||
self.die("Got home safe!")
|
||||
|
||||
|
||||
simulation = Simulation(name='RideHailing', model_class=City, model_params={'n_passengers': 2})
|
||||
simulation = Simulation(name="RideHailing",
|
||||
model=City,
|
||||
seed="carsSeed",
|
||||
max_time=1000,
|
||||
model_params=dict(n_passengers=2))
|
||||
|
||||
if __name__ == "__main__":
|
||||
with easy(simulation) as s:
|
||||
s.run()
|
||||
easy(simulation)
|
@@ -1,19 +0,0 @@
|
||||
---
|
||||
name: mesa_sim
|
||||
group: tests
|
||||
dir_path: "/tmp"
|
||||
num_trials: 3
|
||||
max_steps: 100
|
||||
interval: 1
|
||||
seed: '1'
|
||||
model_class: social_wealth.MoneyEnv
|
||||
model_params:
|
||||
generator: social_wealth.graph_generator
|
||||
agents:
|
||||
topology: true
|
||||
distribution:
|
||||
- agent_class: social_wealth.SocialMoneyAgent
|
||||
weight: 1
|
||||
N: 10
|
||||
width: 50
|
||||
height: 50
|
7
examples/mesa/mesa_sim.py
Normal file
7
examples/mesa/mesa_sim.py
Normal file
@@ -0,0 +1,7 @@
|
||||
from soil import Simulation
|
||||
from social_wealth import MoneyEnv, graph_generator
|
||||
|
||||
sim = Simulation(name="mesa_sim", dump=False, max_steps=10, interval=2, model=MoneyEnv, model_params=dict(generator=graph_generator, N=10, width=50, height=50))
|
||||
|
||||
if __name__ == "__main__":
|
||||
sim.run()
|
@@ -1,5 +1,5 @@
|
||||
from mesa.visualization.ModularVisualization import ModularServer
|
||||
from soil.visualization import UserSettableParameter
|
||||
from mesa.visualization.UserParam import Slider, Choice
|
||||
from mesa.visualization.modules import ChartModule, NetworkModule, CanvasGrid
|
||||
from social_wealth import MoneyEnv, graph_generator, SocialMoneyAgent
|
||||
import networkx as nx
|
||||
@@ -64,8 +64,7 @@ chart = ChartModule(
|
||||
)
|
||||
|
||||
model_params = {
|
||||
"N": UserSettableParameter(
|
||||
"slider",
|
||||
"N": Slider(
|
||||
"N",
|
||||
5,
|
||||
1,
|
||||
@@ -73,8 +72,7 @@ model_params = {
|
||||
1,
|
||||
description="Choose how many agents to include in the model",
|
||||
),
|
||||
"height": UserSettableParameter(
|
||||
"slider",
|
||||
"height": Slider(
|
||||
"height",
|
||||
5,
|
||||
5,
|
||||
@@ -82,8 +80,7 @@ model_params = {
|
||||
1,
|
||||
description="Grid height",
|
||||
),
|
||||
"width": UserSettableParameter(
|
||||
"slider",
|
||||
"width": Slider(
|
||||
"width",
|
||||
5,
|
||||
5,
|
||||
@@ -91,8 +88,7 @@ model_params = {
|
||||
1,
|
||||
description="Grid width",
|
||||
),
|
||||
"agent_class": UserSettableParameter(
|
||||
"choice",
|
||||
"agent_class": Choice(
|
||||
"Agent class",
|
||||
value="MoneyAgent",
|
||||
choices=["MoneyAgent", "SocialMoneyAgent"],
|
||||
@@ -111,4 +107,5 @@ server = ModularServer(
|
||||
)
|
||||
server.port = 8521
|
||||
|
||||
server.launch(open_browser=False)
|
||||
if __name__ == '__main__':
|
||||
server.launch(open_browser=False)
|
||||
|
@@ -28,7 +28,7 @@ class MoneyAgent(MesaAgent):
|
||||
It will only share wealth with neighbors based on grid proximity
|
||||
"""
|
||||
|
||||
def __init__(self, unique_id, model, wealth=1):
|
||||
def __init__(self, unique_id, model, wealth=1, **kwargs):
|
||||
super().__init__(unique_id=unique_id, model=model)
|
||||
self.wealth = wealth
|
||||
|
||||
@@ -53,7 +53,7 @@ class MoneyAgent(MesaAgent):
|
||||
self.give_money()
|
||||
|
||||
|
||||
class SocialMoneyAgent(NetworkAgent, MoneyAgent):
|
||||
class SocialMoneyAgent(MoneyAgent, NetworkAgent):
|
||||
wealth = 1
|
||||
|
||||
def give_money(self):
|
||||
|
@@ -1,133 +0,0 @@
|
||||
---
|
||||
default_state: {}
|
||||
environment_agents: []
|
||||
environment_params:
|
||||
prob_neighbor_spread: 0.0
|
||||
prob_tv_spread: 0.01
|
||||
interval: 1
|
||||
max_steps: 300
|
||||
name: Sim_all_dumb
|
||||
network_agents:
|
||||
- agent_class: newsspread.DumbViewer
|
||||
state:
|
||||
has_tv: false
|
||||
weight: 1
|
||||
- agent_class: newsspread.DumbViewer
|
||||
state:
|
||||
has_tv: true
|
||||
weight: 1
|
||||
network_params:
|
||||
generator: barabasi_albert_graph
|
||||
n: 500
|
||||
m: 5
|
||||
num_trials: 50
|
||||
---
|
||||
default_state: {}
|
||||
environment_agents: []
|
||||
environment_params:
|
||||
prob_neighbor_spread: 0.0
|
||||
prob_tv_spread: 0.01
|
||||
interval: 1
|
||||
max_steps: 300
|
||||
name: Sim_half_herd
|
||||
network_agents:
|
||||
- agent_class: newsspread.DumbViewer
|
||||
state:
|
||||
has_tv: false
|
||||
weight: 1
|
||||
- agent_class: newsspread.DumbViewer
|
||||
state:
|
||||
has_tv: true
|
||||
weight: 1
|
||||
- agent_class: newsspread.HerdViewer
|
||||
state:
|
||||
has_tv: false
|
||||
weight: 1
|
||||
- agent_class: newsspread.HerdViewer
|
||||
state:
|
||||
has_tv: true
|
||||
weight: 1
|
||||
network_params:
|
||||
generator: barabasi_albert_graph
|
||||
n: 500
|
||||
m: 5
|
||||
num_trials: 50
|
||||
---
|
||||
default_state: {}
|
||||
environment_agents: []
|
||||
environment_params:
|
||||
prob_neighbor_spread: 0.0
|
||||
prob_tv_spread: 0.01
|
||||
interval: 1
|
||||
max_steps: 300
|
||||
name: Sim_all_herd
|
||||
network_agents:
|
||||
- agent_class: newsspread.HerdViewer
|
||||
state:
|
||||
has_tv: true
|
||||
state_id: neutral
|
||||
weight: 1
|
||||
- agent_class: newsspread.HerdViewer
|
||||
state:
|
||||
has_tv: true
|
||||
state_id: neutral
|
||||
weight: 1
|
||||
network_params:
|
||||
generator: barabasi_albert_graph
|
||||
n: 500
|
||||
m: 5
|
||||
num_trials: 50
|
||||
---
|
||||
default_state: {}
|
||||
environment_agents: []
|
||||
environment_params:
|
||||
prob_neighbor_spread: 0.0
|
||||
prob_tv_spread: 0.01
|
||||
prob_neighbor_cure: 0.1
|
||||
interval: 1
|
||||
max_steps: 300
|
||||
name: Sim_wise_herd
|
||||
network_agents:
|
||||
- agent_class: newsspread.HerdViewer
|
||||
state:
|
||||
has_tv: true
|
||||
state_id: neutral
|
||||
weight: 1
|
||||
- agent_class: newsspread.WiseViewer
|
||||
state:
|
||||
has_tv: true
|
||||
weight: 1
|
||||
network_params:
|
||||
generator: barabasi_albert_graph
|
||||
n: 500
|
||||
m: 5
|
||||
num_trials: 50
|
||||
---
|
||||
default_state: {}
|
||||
environment_agents: []
|
||||
environment_params:
|
||||
prob_neighbor_spread: 0.0
|
||||
prob_tv_spread: 0.01
|
||||
prob_neighbor_cure: 0.1
|
||||
interval: 1
|
||||
max_steps: 300
|
||||
name: Sim_all_wise
|
||||
network_agents:
|
||||
- agent_class: newsspread.WiseViewer
|
||||
state:
|
||||
has_tv: true
|
||||
state_id: neutral
|
||||
weight: 1
|
||||
- agent_class: newsspread.WiseViewer
|
||||
state:
|
||||
has_tv: true
|
||||
weight: 1
|
||||
network_params:
|
||||
generator: barabasi_albert_graph
|
||||
n: 500
|
||||
m: 5
|
||||
network_params:
|
||||
generator: barabasi_albert_graph
|
||||
n: 500
|
||||
m: 5
|
||||
num_trials: 50
|
@@ -1,87 +0,0 @@
|
||||
from soil.agents import FSM, NetworkAgent, state, default_state, prob
|
||||
import logging
|
||||
|
||||
|
||||
class DumbViewer(FSM, NetworkAgent):
|
||||
"""
|
||||
A viewer that gets infected via TV (if it has one) and tries to infect
|
||||
its neighbors once it's infected.
|
||||
"""
|
||||
|
||||
prob_neighbor_spread = 0.5
|
||||
prob_tv_spread = 0.1
|
||||
has_been_infected = False
|
||||
|
||||
@default_state
|
||||
@state
|
||||
def neutral(self):
|
||||
if self["has_tv"]:
|
||||
if self.prob(self.model["prob_tv_spread"]):
|
||||
return self.infected
|
||||
if self.has_been_infected:
|
||||
return self.infected
|
||||
|
||||
@state
|
||||
def infected(self):
|
||||
for neighbor in self.get_neighbors(state_id=self.neutral.id):
|
||||
if self.prob(self.model["prob_neighbor_spread"]):
|
||||
neighbor.infect()
|
||||
|
||||
def infect(self):
|
||||
"""
|
||||
This is not a state. It is a function that other agents can use to try to
|
||||
infect this agent. DumbViewer always gets infected, but other agents like
|
||||
HerdViewer might not become infected right away
|
||||
"""
|
||||
|
||||
self.has_been_infected = True
|
||||
|
||||
|
||||
class HerdViewer(DumbViewer):
|
||||
"""
|
||||
A viewer whose probability of infection depends on the state of its neighbors.
|
||||
"""
|
||||
|
||||
def infect(self):
|
||||
"""Notice again that this is NOT a state. See DumbViewer.infect for reference"""
|
||||
infected = self.count_neighbors(state_id=self.infected.id)
|
||||
total = self.count_neighbors()
|
||||
prob_infect = self.model["prob_neighbor_spread"] * infected / total
|
||||
self.debug("prob_infect", prob_infect)
|
||||
if self.prob(prob_infect):
|
||||
self.has_been_infected = True
|
||||
|
||||
|
||||
class WiseViewer(HerdViewer):
|
||||
"""
|
||||
A viewer that can change its mind.
|
||||
"""
|
||||
|
||||
defaults = {
|
||||
"prob_neighbor_spread": 0.5,
|
||||
"prob_neighbor_cure": 0.25,
|
||||
"prob_tv_spread": 0.1,
|
||||
}
|
||||
|
||||
@state
|
||||
def cured(self):
|
||||
prob_cure = self.model["prob_neighbor_cure"]
|
||||
for neighbor in self.get_neighbors(state_id=self.infected.id):
|
||||
if self.prob(prob_cure):
|
||||
try:
|
||||
neighbor.cure()
|
||||
except AttributeError:
|
||||
self.debug("Viewer {} cannot be cured".format(neighbor.id))
|
||||
|
||||
def cure(self):
|
||||
self.has_been_cured = True
|
||||
|
||||
@state
|
||||
def infected(self):
|
||||
if self.has_been_cured:
|
||||
return self.cured
|
||||
cured = max(self.count_neighbors(self.cured.id), 1.0)
|
||||
infected = max(self.count_neighbors(self.infected.id), 1.0)
|
||||
prob_cure = self.model["prob_neighbor_cure"] * (cured / infected)
|
||||
if self.prob(prob_cure):
|
||||
return self.cured
|
134
examples/newsspread/newsspread_sim.py
Normal file
134
examples/newsspread/newsspread_sim.py
Normal file
@@ -0,0 +1,134 @@
|
||||
from soil.agents import FSM, NetworkAgent, state, default_state, prob
|
||||
from soil.parameters import *
|
||||
import logging
|
||||
|
||||
from soil.environment import Environment
|
||||
|
||||
|
||||
class DumbViewer(FSM, NetworkAgent):
|
||||
"""
|
||||
A viewer that gets infected via TV (if it has one) and tries to infect
|
||||
its neighbors once it's infected.
|
||||
"""
|
||||
|
||||
has_been_infected: bool = False
|
||||
has_tv: bool = False
|
||||
|
||||
@default_state
|
||||
@state
|
||||
def neutral(self):
|
||||
if self.has_tv:
|
||||
if self.prob(self.get("prob_tv_spread")):
|
||||
return self.infected
|
||||
if self.has_been_infected:
|
||||
return self.infected
|
||||
|
||||
@state
|
||||
def infected(self):
|
||||
for neighbor in self.get_neighbors(state_id=self.neutral.id):
|
||||
if self.prob(self.get("prob_neighbor_spread")):
|
||||
neighbor.infect()
|
||||
|
||||
def infect(self):
|
||||
"""
|
||||
This is not a state. It is a function that other agents can use to try to
|
||||
infect this agent. DumbViewer always gets infected, but other agents like
|
||||
HerdViewer might not become infected right away
|
||||
"""
|
||||
self.has_been_infected = True
|
||||
|
||||
|
||||
class HerdViewer(DumbViewer):
|
||||
"""
|
||||
A viewer whose probability of infection depends on the state of its neighbors.
|
||||
"""
|
||||
|
||||
def infect(self):
|
||||
"""Notice again that this is NOT a state. See DumbViewer.infect for reference"""
|
||||
infected = self.count_neighbors(state_id=self.infected.id)
|
||||
total = self.count_neighbors()
|
||||
prob_infect = self.get("prob_neighbor_spread") * infected / total
|
||||
self.debug("prob_infect", prob_infect)
|
||||
if self.prob(prob_infect):
|
||||
self.has_been_infected = True
|
||||
|
||||
|
||||
class WiseViewer(HerdViewer):
|
||||
"""
|
||||
A viewer that can change its mind.
|
||||
"""
|
||||
|
||||
@state
|
||||
def cured(self):
|
||||
prob_cure = self.get("prob_neighbor_cure")
|
||||
for neighbor in self.get_neighbors(state_id=self.infected.id):
|
||||
if self.prob(prob_cure):
|
||||
try:
|
||||
neighbor.cure()
|
||||
except AttributeError:
|
||||
self.debug("Viewer {} cannot be cured".format(neighbor.id))
|
||||
|
||||
def cure(self):
|
||||
self.has_been_cured = True
|
||||
|
||||
@state
|
||||
def infected(self):
|
||||
if self.has_been_cured:
|
||||
return self.cured
|
||||
cured = max(self.count_neighbors(self.cured.id), 1.0)
|
||||
infected = max(self.count_neighbors(self.infected.id), 1.0)
|
||||
prob_cure = self.get("prob_neighbor_cure") * (cured / infected)
|
||||
if self.prob(prob_cure):
|
||||
return self.cured
|
||||
|
||||
|
||||
class NewsSpread(Environment):
|
||||
ratio_dumb: probability = 1,
|
||||
ratio_herd: probability = 0,
|
||||
ratio_wise: probability = 0,
|
||||
prob_tv_spread: probability = 0.1,
|
||||
prob_neighbor_spread: probability = 0.1,
|
||||
prob_neighbor_cure: probability = 0.05,
|
||||
|
||||
def init(self):
|
||||
self.populate_network([DumbViewer, HerdViewer, WiseViewer],
|
||||
[self.ratio_dumb, self.ratio_herd, self.ratio_wise])
|
||||
|
||||
|
||||
from itertools import product
|
||||
from soil import Simulation
|
||||
|
||||
|
||||
# We want to investigate the effect of different agent distributions on the spread of news.
|
||||
# To do that, we will run different simulations, with a varying ratio of DumbViewers, HerdViewers, and WiseViewers
|
||||
# Because the effect of these agents might also depend on the network structure, we will run our simulations on two different networks:
|
||||
# one with a small-world structure and one with a connected structure.
|
||||
|
||||
counter = 0
|
||||
for [r1, r2] in product([0, 0.5, 1.0], repeat=2):
|
||||
for (generator, netparams) in {
|
||||
"barabasi_albert_graph": {"m": 5},
|
||||
"erdos_renyi_graph": {"p": 0.1},
|
||||
}.items():
|
||||
print(r1, r2, 1-r1-r2, generator)
|
||||
# Create new simulation
|
||||
netparams["n"] = 500
|
||||
Simulation(
|
||||
name='newspread_sim',
|
||||
model=NewsSpread,
|
||||
model_params=dict(
|
||||
ratio_dumb=r1,
|
||||
ratio_herd=r2,
|
||||
ratio_wise=1-r1-r2,
|
||||
network_generator=generator,
|
||||
network_params=netparams,
|
||||
prob_neighbor_spread=0,
|
||||
),
|
||||
num_trials=5,
|
||||
max_steps=300,
|
||||
dump=False,
|
||||
).run()
|
||||
counter += 1
|
||||
# Run all the necessary instances
|
||||
|
||||
print(f"A total of {counter} simulations were run.")
|
@@ -1,41 +0,0 @@
|
||||
"""
|
||||
Example of a fully programmatic simulation, without definition files.
|
||||
"""
|
||||
from soil import Simulation, agents
|
||||
from networkx import Graph
|
||||
import logging
|
||||
|
||||
|
||||
def mygenerator():
|
||||
# Add only a node
|
||||
G = Graph()
|
||||
G.add_node(1)
|
||||
return G
|
||||
|
||||
|
||||
class MyAgent(agents.FSM):
|
||||
@agents.default_state
|
||||
@agents.state
|
||||
def neutral(self):
|
||||
self.debug("I am running")
|
||||
if agents.prob(0.2):
|
||||
self.info("This runs 2/10 times on average")
|
||||
|
||||
|
||||
s = Simulation(
|
||||
name="Programmatic",
|
||||
network_params={"generator": mygenerator},
|
||||
num_trials=1,
|
||||
max_time=100,
|
||||
agent_class=MyAgent,
|
||||
dry_run=True,
|
||||
)
|
||||
|
||||
|
||||
# By default, logging will only print WARNING logs (and above).
|
||||
# You need to choose a lower logging level to get INFO/DEBUG traces
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
envs = s.run()
|
||||
|
||||
# Uncomment this to output the simulation to a YAML file
|
||||
# s.dump_yaml('simulation.yaml')
|
53
examples/programmatic/programmatic_sim.py
Normal file
53
examples/programmatic/programmatic_sim.py
Normal file
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
Example of a fully programmatic simulation, without definition files.
|
||||
"""
|
||||
from soil import Simulation, Environment, agents
|
||||
from networkx import Graph
|
||||
import logging
|
||||
|
||||
|
||||
def mygenerator():
|
||||
# Add only a node
|
||||
G = Graph()
|
||||
G.add_node(1)
|
||||
G.add_node(2)
|
||||
return G
|
||||
|
||||
|
||||
class MyAgent(agents.NetworkAgent, agents.FSM):
|
||||
times_run = 0
|
||||
@agents.default_state
|
||||
@agents.state
|
||||
def neutral(self):
|
||||
self.debug("I am running")
|
||||
if self.prob(0.2):
|
||||
self.times_run += 1
|
||||
self.info("This runs 2/10 times on average")
|
||||
|
||||
|
||||
class ProgrammaticEnv(Environment):
|
||||
|
||||
def init(self):
|
||||
self.create_network(generator=mygenerator)
|
||||
assert len(self.G)
|
||||
self.populate_network(agent_class=MyAgent)
|
||||
self.add_agent_reporter('times_run')
|
||||
|
||||
|
||||
simulation = Simulation(
|
||||
name="Programmatic",
|
||||
model=ProgrammaticEnv,
|
||||
seed='Program',
|
||||
num_trials=1,
|
||||
max_time=100,
|
||||
dump=False,
|
||||
)
|
||||
|
||||
if __name__ == "__main__":
|
||||
# By default, logging will only print WARNING logs (and above).
|
||||
# You need to choose a lower logging level to get INFO/DEBUG traces
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
envs = simulation.run()
|
||||
|
||||
for agent in envs[0].agents:
|
||||
print(agent.times_run)
|
@@ -1,26 +0,0 @@
|
||||
---
|
||||
name: pubcrawl
|
||||
num_trials: 3
|
||||
max_steps: 10
|
||||
dump: false
|
||||
network_params:
|
||||
# Generate 100 empty nodes. They will be assigned a network agent
|
||||
generator: empty_graph
|
||||
n: 30
|
||||
network_agents:
|
||||
- agent_class: pubcrawl.Patron
|
||||
description: Extroverted patron
|
||||
state:
|
||||
openness: 1.0
|
||||
weight: 9
|
||||
- agent_class: pubcrawl.Patron
|
||||
description: Introverted patron
|
||||
state:
|
||||
openness: 0.1
|
||||
weight: 1
|
||||
environment_agents:
|
||||
- agent_class: pubcrawl.Police
|
||||
environment_class: pubcrawl.CityPubs
|
||||
environment_params:
|
||||
altercations: 0
|
||||
number_of_pubs: 3
|
@@ -1,6 +1,7 @@
|
||||
from soil.agents import FSM, NetworkAgent, state, default_state
|
||||
from soil import Environment
|
||||
from soil import Environment, Simulation, parameters
|
||||
from itertools import islice
|
||||
import networkx as nx
|
||||
import logging
|
||||
|
||||
|
||||
@@ -8,19 +9,24 @@ class CityPubs(Environment):
|
||||
"""Environment with Pubs"""
|
||||
|
||||
level = logging.INFO
|
||||
|
||||
def __init__(self, *args, number_of_pubs=3, pub_capacity=10, **kwargs):
|
||||
super(CityPubs, self).__init__(*args, **kwargs)
|
||||
pubs = {}
|
||||
for i in range(number_of_pubs):
|
||||
number_of_pubs: parameters.Integer = 3
|
||||
ratio_extroverted: parameters.probability = 0.1
|
||||
pub_capacity: parameters.Integer = 10
|
||||
|
||||
def init(self):
|
||||
self.pubs = {}
|
||||
for i in range(self.number_of_pubs):
|
||||
newpub = {
|
||||
"name": "The awesome pub #{}".format(i),
|
||||
"open": True,
|
||||
"capacity": pub_capacity,
|
||||
"capacity": self.pub_capacity,
|
||||
"occupancy": 0,
|
||||
}
|
||||
pubs[newpub["name"]] = newpub
|
||||
self["pubs"] = pubs
|
||||
self.pubs[newpub["name"]] = newpub
|
||||
self.add_agent(agent_class=Police)
|
||||
self.populate_network([Patron.w(openness=0.1), Patron.w(openness=1)],
|
||||
[self.ratio_extroverted, 1-self.ratio_extroverted])
|
||||
assert all(["agent" in node and isinstance(node["agent"], Patron) for (_, node) in self.G.nodes(data=True)])
|
||||
|
||||
def enter(self, pub_id, *nodes):
|
||||
"""Agents will try to enter. The pub checks if it is possible"""
|
||||
@@ -146,10 +152,10 @@ class Patron(FSM, NetworkAgent):
|
||||
continue
|
||||
if friend.befriend(self):
|
||||
self.befriend(friend, force=True)
|
||||
self.debug("Hooray! new friend: {}".format(friend.id))
|
||||
self.debug("Hooray! new friend: {}".format(friend.unique_id))
|
||||
befriended = True
|
||||
else:
|
||||
self.debug("{} does not want to be friends".format(friend.id))
|
||||
self.debug("{} does not want to be friends".format(friend.unique_id))
|
||||
return befriended
|
||||
|
||||
|
||||
@@ -163,13 +169,27 @@ class Police(FSM):
|
||||
def patrol(self):
|
||||
drunksters = list(self.get_agents(drunk=True, state_id=Patron.drunk_in_pub.id))
|
||||
for drunk in drunksters:
|
||||
self.info("Kicking out the trash: {}".format(drunk.id))
|
||||
self.info("Kicking out the trash: {}".format(drunk.unique_id))
|
||||
drunk.kick_out()
|
||||
else:
|
||||
self.info("No trash to take out. Too bad.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from soil import simulation
|
||||
sim = Simulation(
|
||||
model=CityPubs,
|
||||
name="pubcrawl",
|
||||
num_trials=3,
|
||||
max_steps=10,
|
||||
dump=False,
|
||||
model_params=dict(
|
||||
network_generator=nx.empty_graph,
|
||||
network_params={"n": 30},
|
||||
model=CityPubs,
|
||||
altercations=0,
|
||||
number_of_pubs=3,
|
||||
)
|
||||
)
|
||||
|
||||
simulation.run_from_config("pubcrawl.yml", dry_run=True, dump=None, parallel=False)
|
||||
|
||||
if __name__ == "__main__":
|
||||
sim.run(parallel=False)
|
@@ -1,42 +0,0 @@
|
||||
---
|
||||
version: '2'
|
||||
name: rabbits_basic
|
||||
num_trials: 1
|
||||
seed: MySeed
|
||||
description: null
|
||||
group: null
|
||||
interval: 1.0
|
||||
max_time: 100
|
||||
model_class: rabbit_agents.RabbitEnv
|
||||
model_params:
|
||||
agents:
|
||||
topology: true
|
||||
distribution:
|
||||
- agent_class: rabbit_agents.Male
|
||||
weight: 1
|
||||
- agent_class: rabbit_agents.Female
|
||||
weight: 1
|
||||
fixed:
|
||||
- agent_class: rabbit_agents.RandomAccident
|
||||
topology: false
|
||||
hidden: true
|
||||
state:
|
||||
group: environment
|
||||
state:
|
||||
group: network
|
||||
mating_prob: 0.1
|
||||
prob_death: 0.001
|
||||
topology:
|
||||
fixed:
|
||||
directed: true
|
||||
links: []
|
||||
nodes:
|
||||
- id: 1
|
||||
- id: 0
|
||||
model_reporters:
|
||||
num_males: 'num_males'
|
||||
num_females: 'num_females'
|
||||
num_rabbits: |
|
||||
py:lambda env: env.num_males + env.num_females
|
||||
extra:
|
||||
visualization_params: {}
|
@@ -1,42 +0,0 @@
|
||||
---
|
||||
version: '2'
|
||||
name: rabbits_improved
|
||||
num_trials: 1
|
||||
seed: MySeed
|
||||
description: null
|
||||
group: null
|
||||
interval: 1.0
|
||||
max_time: 100
|
||||
model_class: rabbit_agents.RabbitEnv
|
||||
model_params:
|
||||
agents:
|
||||
topology: true
|
||||
distribution:
|
||||
- agent_class: rabbit_agents.Male
|
||||
weight: 1
|
||||
- agent_class: rabbit_agents.Female
|
||||
weight: 1
|
||||
fixed:
|
||||
- agent_class: rabbit_agents.RandomAccident
|
||||
topology: false
|
||||
hidden: true
|
||||
state:
|
||||
group: environment
|
||||
state:
|
||||
group: network
|
||||
mating_prob: 0.1
|
||||
prob_death: 0.001
|
||||
topology:
|
||||
fixed:
|
||||
directed: true
|
||||
links: []
|
||||
nodes:
|
||||
- id: 1
|
||||
- id: 0
|
||||
model_reporters:
|
||||
num_males: 'num_males'
|
||||
num_females: 'num_females'
|
||||
num_rabbits: |
|
||||
py:lambda env: env.num_males + env.num_females
|
||||
extra:
|
||||
visualization_params: {}
|
@@ -1,23 +1,20 @@
|
||||
from soil import FSM, state, default_state, BaseAgent, NetworkAgent, Environment
|
||||
from soil import FSM, state, default_state, BaseAgent, NetworkAgent, Environment, Simulation
|
||||
from soil.time import Delta
|
||||
from enum import Enum
|
||||
from collections import Counter
|
||||
import logging
|
||||
import math
|
||||
|
||||
from rabbits_basic_sim import RabbitEnv
|
||||
|
||||
class RabbitEnv(Environment):
|
||||
@property
|
||||
def num_rabbits(self):
|
||||
return self.count_agents(agent_class=Rabbit)
|
||||
|
||||
@property
|
||||
def num_males(self):
|
||||
return self.count_agents(agent_class=Male)
|
||||
|
||||
@property
|
||||
def num_females(self):
|
||||
return self.count_agents(agent_class=Female)
|
||||
class RabbitsImprovedEnv(RabbitEnv):
|
||||
def init(self):
|
||||
"""Initialize the environment with the new versions of the agents"""
|
||||
a1 = self.add_node(Male)
|
||||
a2 = self.add_node(Female)
|
||||
a1.add_edge(a2)
|
||||
self.add_agent(RandomAccident)
|
||||
|
||||
|
||||
class Rabbit(FSM, NetworkAgent):
|
||||
@@ -150,8 +147,7 @@ class RandomAccident(BaseAgent):
|
||||
self.debug("Rabbits alive: {}".format(rabbits_alive))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from soil import easy
|
||||
sim = Simulation(model=RabbitsImprovedEnv, max_time=100, seed="MySeed", num_trials=1)
|
||||
|
||||
with easy("rabbits.yml") as sim:
|
||||
sim.run()
|
||||
if __name__ == "__main__":
|
||||
sim.run()
|
@@ -1,18 +1,29 @@
|
||||
from soil import FSM, state, default_state, BaseAgent, NetworkAgent, Environment
|
||||
from soil import FSM, state, default_state, BaseAgent, NetworkAgent, Environment, Simulation, report, parameters as params
|
||||
from collections import Counter
|
||||
import logging
|
||||
import math
|
||||
|
||||
|
||||
class RabbitEnv(Environment):
|
||||
prob_death: params.probability = 1e-100
|
||||
|
||||
def init(self):
|
||||
a1 = self.add_node(Male)
|
||||
a2 = self.add_node(Female)
|
||||
a1.add_edge(a2)
|
||||
self.add_agent(RandomAccident)
|
||||
|
||||
@report
|
||||
@property
|
||||
def num_rabbits(self):
|
||||
return self.count_agents(agent_class=Rabbit)
|
||||
|
||||
@report
|
||||
@property
|
||||
def num_males(self):
|
||||
return self.count_agents(agent_class=Male)
|
||||
|
||||
@report
|
||||
@property
|
||||
def num_females(self):
|
||||
return self.count_agents(agent_class=Female)
|
||||
@@ -129,11 +140,11 @@ class RandomAccident(BaseAgent):
|
||||
if not rabbits_alive:
|
||||
return self.die()
|
||||
|
||||
prob_death = self.model.get("prob_death", 1e-100) * math.floor(
|
||||
prob_death = self.model.prob_death * math.floor(
|
||||
math.log10(max(1, rabbits_alive))
|
||||
)
|
||||
self.debug("Killing some rabbits with prob={}!".format(prob_death))
|
||||
for i in self.iter_agents(agent_class=Rabbit):
|
||||
for i in self.get_agents(agent_class=Rabbit):
|
||||
if i.state_id == i.dead.id:
|
||||
continue
|
||||
if self.prob(prob_death):
|
||||
@@ -143,8 +154,8 @@ class RandomAccident(BaseAgent):
|
||||
self.debug("Rabbits alive: {}".format(rabbits_alive))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from soil import easy
|
||||
|
||||
with easy("rabbits.yml") as sim:
|
||||
sim.run()
|
||||
sim = Simulation(model=RabbitEnv, max_time=100, seed="MySeed", num_trials=1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
sim.run()
|
@@ -2,7 +2,7 @@
|
||||
Example of setting a
|
||||
Example of a fully programmatic simulation, without definition files.
|
||||
"""
|
||||
from soil import Simulation, agents
|
||||
from soil import Simulation, agents, Environment
|
||||
from soil.time import Delta
|
||||
|
||||
|
||||
@@ -29,14 +29,18 @@ class MyAgent(agents.FSM):
|
||||
return None, Delta(self.random.expovariate(1 / 16))
|
||||
|
||||
|
||||
class RandomEnv(Environment):
|
||||
|
||||
def init(self):
|
||||
self.add_agent(agent_class=MyAgent)
|
||||
|
||||
|
||||
s = Simulation(
|
||||
name="Programmatic",
|
||||
network_agents=[{"agent_class": MyAgent, "id": 0}],
|
||||
topology={"nodes": [{"id": 0}], "links": []},
|
||||
model=RandomEnv,
|
||||
num_trials=1,
|
||||
max_time=100,
|
||||
agent_class=MyAgent,
|
||||
dry_run=True,
|
||||
dump=False,
|
||||
)
|
||||
|
||||
|
@@ -1,30 +0,0 @@
|
||||
---
|
||||
sampler:
|
||||
method: "SALib.sample.morris.sample"
|
||||
N: 10
|
||||
template:
|
||||
group: simple
|
||||
num_trials: 1
|
||||
interval: 1
|
||||
max_steps: 2
|
||||
seed: "CompleteSeed!"
|
||||
dump: false
|
||||
model_params:
|
||||
network_params:
|
||||
generator: complete_graph
|
||||
n: 10
|
||||
network_agents:
|
||||
- agent_class: CounterModel
|
||||
weight: "{{ x1 }}"
|
||||
state:
|
||||
state_id: 0
|
||||
- agent_class: AggregatedCounter
|
||||
weight: "{{ 1 - x1 }}"
|
||||
name: "{{ x3 }}"
|
||||
skip_test: true
|
||||
vars:
|
||||
bounds:
|
||||
x1: [0, 1]
|
||||
x2: [1, 2]
|
||||
fixed:
|
||||
x3: ["a", "b", "c"]
|
@@ -1,62 +0,0 @@
|
||||
name: TerroristNetworkModel_sim
|
||||
max_steps: 150
|
||||
num_trials: 1
|
||||
model_params:
|
||||
network_params:
|
||||
generator: random_geometric_graph
|
||||
radius: 0.2
|
||||
# generator: geographical_threshold_graph
|
||||
# theta: 20
|
||||
n: 100
|
||||
network_agents:
|
||||
- agent_class: TerroristNetworkModel.TerroristNetworkModel
|
||||
weight: 0.8
|
||||
state:
|
||||
id: civilian # Civilians
|
||||
- agent_class: TerroristNetworkModel.TerroristNetworkModel
|
||||
weight: 0.1
|
||||
state:
|
||||
id: leader # Leaders
|
||||
- agent_class: TerroristNetworkModel.TrainingAreaModel
|
||||
weight: 0.05
|
||||
state:
|
||||
id: terrorist # Terrorism
|
||||
- agent_class: TerroristNetworkModel.HavenModel
|
||||
weight: 0.05
|
||||
state:
|
||||
id: civilian # Civilian
|
||||
|
||||
# TerroristSpreadModel
|
||||
information_spread_intensity: 0.7
|
||||
terrorist_additional_influence: 0.035
|
||||
max_vulnerability: 0.7
|
||||
prob_interaction: 0.5
|
||||
|
||||
# TrainingAreaModel and HavenModel
|
||||
training_influence: 0.20
|
||||
haven_influence: 0.20
|
||||
|
||||
# TerroristNetworkModel
|
||||
vision_range: 0.30
|
||||
sphere_influence: 2
|
||||
weight_social_distance: 0.035
|
||||
weight_link_distance: 0.035
|
||||
|
||||
visualization_params:
|
||||
# Icons downloaded from https://www.iconfinder.com/
|
||||
shape_property: agent
|
||||
shapes:
|
||||
TrainingAreaModel: target
|
||||
HavenModel: home
|
||||
TerroristNetworkModel: person
|
||||
colors:
|
||||
- attr_id: civilian
|
||||
color: '#40de40'
|
||||
- attr_id: terrorist
|
||||
color: red
|
||||
- attr_id: leader
|
||||
color: '#c16a6a'
|
||||
background_image: 'map_4800x2860.jpg'
|
||||
background_opacity: '0.9'
|
||||
background_filter_color: 'blue'
|
||||
skip_test: true # This simulation takes too long for automated tests.
|
@@ -1,8 +1,47 @@
|
||||
import networkx as nx
|
||||
from soil.agents import Geo, NetworkAgent, FSM, state, default_state
|
||||
from soil import Environment
|
||||
from soil.agents import Geo, NetworkAgent, FSM, custom, state, default_state
|
||||
from soil import Environment, Simulation
|
||||
from soil.parameters import *
|
||||
|
||||
|
||||
class TerroristEnvironment(Environment):
|
||||
n: Integer = 100
|
||||
radius: Float = 0.2
|
||||
|
||||
information_spread_intensity: probability = 0.7
|
||||
terrorist_additional_influence: probability = 0.03
|
||||
terrorist_additional_influence: probability = 0.035
|
||||
max_vulnerability: probability = 0.7
|
||||
prob_interaction: probability = 0.5
|
||||
|
||||
# TrainingAreaModel and HavenModel
|
||||
training_influence: probability = 0.20
|
||||
haven_influence: probability = 0.20
|
||||
|
||||
# TerroristNetworkModel
|
||||
vision_range: Float = 0.30
|
||||
sphere_influence: Integer = 2
|
||||
weight_social_distance: Float = 0.035
|
||||
weight_link_distance: Float = 0.035
|
||||
|
||||
ratio_civil: probability = 0.8
|
||||
ratio_leader: probability = 0.1
|
||||
ratio_training: probability = 0.05
|
||||
ratio_haven: probability = 0.05
|
||||
|
||||
def init(self):
|
||||
self.create_network(generator=self.generator, n=self.n, radius=self.radius)
|
||||
self.populate_network([
|
||||
TerroristNetworkModel.w(state_id='civilian'),
|
||||
TerroristNetworkModel.w(state_id='leader'),
|
||||
TrainingAreaModel,
|
||||
HavenModel
|
||||
], [self.ratio_civil, self.ratio_leader, self.ratio_training, self.ratio_haven])
|
||||
|
||||
@staticmethod
|
||||
def generator(*args, **kwargs):
|
||||
return nx.random_geometric_graph(*args, **kwargs)
|
||||
|
||||
class TerroristSpreadModel(FSM, Geo):
|
||||
"""
|
||||
Settings:
|
||||
@@ -13,47 +52,35 @@ class TerroristSpreadModel(FSM, Geo):
|
||||
min_vulnerability (optional else zero)
|
||||
|
||||
max_vulnerability
|
||||
|
||||
prob_interaction
|
||||
"""
|
||||
|
||||
def __init__(self, model=None, unique_id=0, state=()):
|
||||
super().__init__(model=model, unique_id=unique_id, state=state)
|
||||
information_spread_intensity = 0.1
|
||||
terrorist_additional_influence = 0.1
|
||||
min_vulnerability = 0
|
||||
max_vulnerability = 1
|
||||
|
||||
self.information_spread_intensity = model.environment_params[
|
||||
"information_spread_intensity"
|
||||
]
|
||||
self.terrorist_additional_influence = model.environment_params[
|
||||
"terrorist_additional_influence"
|
||||
]
|
||||
self.prob_interaction = model.environment_params["prob_interaction"]
|
||||
|
||||
if self["id"] == self.civilian.id: # Civilian
|
||||
self.mean_belief = self.random.uniform(0.00, 0.5)
|
||||
elif self["id"] == self.terrorist.id: # Terrorist
|
||||
def init(self):
|
||||
if self.state_id == self.civilian.id: # Civilian
|
||||
self.mean_belief = self.model.random.uniform(0.00, 0.5)
|
||||
elif self.state_id == self.terrorist.id: # Terrorist
|
||||
self.mean_belief = self.random.uniform(0.8, 1.00)
|
||||
elif self["id"] == self.leader.id: # Leader
|
||||
elif self.state_id == self.leader.id: # Leader
|
||||
self.mean_belief = 1.00
|
||||
else:
|
||||
raise Exception("Invalid state id: {}".format(self["id"]))
|
||||
|
||||
if "min_vulnerability" in model.environment_params:
|
||||
self.vulnerability = self.random.uniform(
|
||||
model.environment_params["min_vulnerability"],
|
||||
model.environment_params["max_vulnerability"],
|
||||
)
|
||||
else:
|
||||
self.vulnerability = self.random.uniform(
|
||||
0, model.environment_params["max_vulnerability"]
|
||||
)
|
||||
self.vulnerability = self.random.uniform(
|
||||
self.get("min_vulnerability", 0), self.get("max_vulnerability", 1)
|
||||
)
|
||||
|
||||
@default_state
|
||||
@state
|
||||
def civilian(self):
|
||||
neighbours = list(self.get_neighbors(agent_class=TerroristSpreadModel))
|
||||
if len(neighbours) > 0:
|
||||
# Only interact with some of the neighbors
|
||||
interactions = list(
|
||||
n for n in neighbours if self.random.random() <= self.prob_interaction
|
||||
n for n in neighbours if self.random.random() <= self.model.prob_interaction
|
||||
)
|
||||
influence = sum(self.degree(i) for i in interactions)
|
||||
mean_belief = sum(
|
||||
@@ -99,7 +126,7 @@ class TerroristSpreadModel(FSM, Geo):
|
||||
)
|
||||
|
||||
# Check if there are any leaders in the group
|
||||
leaders = list(filter(lambda x: x.state.id == self.leader.id, neighbours))
|
||||
leaders = list(filter(lambda x: x.state_id == self.leader.id, neighbours))
|
||||
if not leaders:
|
||||
# Check if this is the potential leader
|
||||
# Stop once it's found. Otherwise, set self as leader
|
||||
@@ -108,14 +135,13 @@ class TerroristSpreadModel(FSM, Geo):
|
||||
return
|
||||
return self.leader
|
||||
|
||||
def ego_search(self, steps=1, center=False, node=None, **kwargs):
|
||||
def ego_search(self, steps=1, center=False, agent=None, **kwargs):
|
||||
"""Get a list of nodes in the ego network of *node* of radius *steps*"""
|
||||
node = as_node(node if node is not None else self)
|
||||
node = agent.node_id
|
||||
G = self.subgraph(**kwargs)
|
||||
return nx.ego_graph(G, node, center=center, radius=steps).nodes()
|
||||
|
||||
def degree(self, node, force=False):
|
||||
node = as_node(node)
|
||||
def degree(self, agent, force=False):
|
||||
if (
|
||||
force
|
||||
or (not hasattr(self.model, "_degree"))
|
||||
@@ -123,10 +149,9 @@ class TerroristSpreadModel(FSM, Geo):
|
||||
):
|
||||
self.model._degree = nx.degree_centrality(self.G)
|
||||
self.model._last_step = self.now
|
||||
return self.model._degree[node]
|
||||
return self.model._degree[agent.node_id]
|
||||
|
||||
def betweenness(self, node, force=False):
|
||||
node = as_node(node)
|
||||
def betweenness(self, agent, force=False):
|
||||
if (
|
||||
force
|
||||
or (not hasattr(self.model, "_betweenness"))
|
||||
@@ -134,7 +159,7 @@ class TerroristSpreadModel(FSM, Geo):
|
||||
):
|
||||
self.model._betweenness = nx.betweenness_centrality(self.G)
|
||||
self.model._last_step = self.now
|
||||
return self.model._betweenness[node]
|
||||
return self.model._betweenness[agent.node_id]
|
||||
|
||||
|
||||
class TrainingAreaModel(FSM, Geo):
|
||||
@@ -147,13 +172,12 @@ class TrainingAreaModel(FSM, Geo):
|
||||
Requires TerroristSpreadModel.
|
||||
"""
|
||||
|
||||
def __init__(self, model=None, unique_id=0, state=()):
|
||||
super().__init__(model=model, unique_id=unique_id, state=state)
|
||||
self.training_influence = model.environment_params["training_influence"]
|
||||
if "min_vulnerability" in model.environment_params:
|
||||
self.min_vulnerability = model.environment_params["min_vulnerability"]
|
||||
else:
|
||||
self.min_vulnerability = 0
|
||||
training_influence = 0.1
|
||||
min_vulnerability = 0
|
||||
|
||||
def init(self):
|
||||
self.mean_believe = 1
|
||||
self.vulnerability = 0
|
||||
|
||||
@default_state
|
||||
@state
|
||||
@@ -177,18 +201,19 @@ class HavenModel(FSM, Geo):
|
||||
Requires TerroristSpreadModel.
|
||||
"""
|
||||
|
||||
def __init__(self, model=None, unique_id=0, state=()):
|
||||
super().__init__(model=model, unique_id=unique_id, state=state)
|
||||
self.haven_influence = model.environment_params["haven_influence"]
|
||||
if "min_vulnerability" in model.environment_params:
|
||||
self.min_vulnerability = model.environment_params["min_vulnerability"]
|
||||
else:
|
||||
self.min_vulnerability = 0
|
||||
self.max_vulnerability = model.environment_params["max_vulnerability"]
|
||||
min_vulnerability = 0
|
||||
haven_influence = 0.1
|
||||
max_vulnerability = 0.5
|
||||
|
||||
def init(self):
|
||||
self.mean_believe = 0
|
||||
self.vulnerability = 0
|
||||
|
||||
def get_occupants(self, **kwargs):
|
||||
return self.get_neighbors(agent_class=TerroristSpreadModel, **kwargs)
|
||||
return self.get_neighbors(agent_class=TerroristSpreadModel,
|
||||
**kwargs)
|
||||
|
||||
@default_state
|
||||
@state
|
||||
def civilian(self):
|
||||
civilians = self.get_occupants(state_id=self.civilian.id)
|
||||
@@ -224,13 +249,10 @@ class TerroristNetworkModel(TerroristSpreadModel):
|
||||
weight_link_distance
|
||||
"""
|
||||
|
||||
def __init__(self, model=None, unique_id=0, state=()):
|
||||
super().__init__(model=model, unique_id=unique_id, state=state)
|
||||
|
||||
self.vision_range = model.environment_params["vision_range"]
|
||||
self.sphere_influence = model.environment_params["sphere_influence"]
|
||||
self.weight_social_distance = model.environment_params["weight_social_distance"]
|
||||
self.weight_link_distance = model.environment_params["weight_link_distance"]
|
||||
sphere_influence: float = 1
|
||||
vision_range: float = 1
|
||||
weight_social_distance: float = 0.5
|
||||
weight_link_distance: float = 0.2
|
||||
|
||||
@state
|
||||
def terrorist(self):
|
||||
@@ -258,9 +280,7 @@ class TerroristNetworkModel(TerroristSpreadModel):
|
||||
)
|
||||
neighbours = set(
|
||||
agent.id
|
||||
for agent in self.get_neighbors(
|
||||
agent_class=TerroristNetworkModel
|
||||
)
|
||||
for agent in self.get_neighbors(agent_class=TerroristNetworkModel)
|
||||
)
|
||||
search = (close_ups | step_neighbours) - neighbours
|
||||
for agent in self.get_agents(search):
|
||||
@@ -289,3 +309,32 @@ class TerroristNetworkModel(TerroristSpreadModel):
|
||||
return nx.shortest_path_length(self.G, self.id, target)
|
||||
except nx.NetworkXNoPath:
|
||||
return float("inf")
|
||||
|
||||
|
||||
sim = Simulation(
|
||||
model=TerroristEnvironment,
|
||||
num_trials=1,
|
||||
name="TerroristNetworkModel_sim",
|
||||
max_steps=150,
|
||||
skip_test=False,
|
||||
dump=False,
|
||||
)
|
||||
|
||||
# TODO: integrate visualization
|
||||
# visualization_params:
|
||||
# # Icons downloaded from https://www.iconfinder.com/
|
||||
# shape_property: agent
|
||||
# shapes:
|
||||
# TrainingAreaModel: target
|
||||
# HavenModel: home
|
||||
# TerroristNetworkModel: person
|
||||
# colors:
|
||||
# - attr_id: civilian
|
||||
# color: '#40de40'
|
||||
# - attr_id: terrorist
|
||||
# color: red
|
||||
# - attr_id: leader
|
||||
# color: '#c16a6a'
|
||||
# background_image: 'map_4800x2860.jpg'
|
||||
# background_opacity: '0.9'
|
||||
# background_filter_color: 'blue'
|
@@ -1,15 +0,0 @@
|
||||
---
|
||||
name: torvalds_example
|
||||
max_steps: 10
|
||||
interval: 2
|
||||
model_params:
|
||||
agent_class: CounterModel
|
||||
default_state:
|
||||
skill_level: 'beginner'
|
||||
network_params:
|
||||
path: 'torvalds.edgelist'
|
||||
states:
|
||||
Torvalds:
|
||||
skill_level: 'God'
|
||||
balkian:
|
||||
skill_level: 'developer'
|
25
examples/torvalds_sim.py
Normal file
25
examples/torvalds_sim.py
Normal file
@@ -0,0 +1,25 @@
|
||||
from soil import Environment, Simulation, CounterModel, report
|
||||
|
||||
|
||||
# Get directory path for current file
|
||||
import os, sys, inspect
|
||||
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
|
||||
|
||||
class TorvaldsEnv(Environment):
|
||||
|
||||
def init(self):
|
||||
self.create_network(path=os.path.join(currentdir, 'torvalds.edgelist'))
|
||||
self.populate_network(CounterModel, skill_level='beginner')
|
||||
self.agent(node_id="Torvalds").skill_level = 'God'
|
||||
self.agent(node_id="balkian").skill_level = 'developer'
|
||||
self.add_agent_reporter("times")
|
||||
|
||||
@report
|
||||
def god_developers(self):
|
||||
return self.count_agents(skill_level='God')
|
||||
|
||||
|
||||
sim = Simulation(name='torvalds_example',
|
||||
max_steps=10,
|
||||
interval=2,
|
||||
model=TorvaldsEnv)
|
File diff suppressed because one or more lines are too long
@@ -5,6 +5,8 @@ pyyaml>=5.1
|
||||
pandas>=1
|
||||
SALib>=1.3
|
||||
Jinja2
|
||||
Mesa>=1.1
|
||||
Mesa>=1.2
|
||||
pydantic>=1.9
|
||||
sqlalchemy>=1.4
|
||||
typing-extensions>=4.4
|
||||
annotated-types>=0.4
|
7
setup.py
7
setup.py
@@ -44,13 +44,18 @@ setup(
|
||||
'Operating System :: MacOS :: MacOS X',
|
||||
'Operating System :: Microsoft :: Windows',
|
||||
'Operating System :: POSIX',
|
||||
'Programming Language :: Python :: 3'],
|
||||
"Programming Language :: Python :: 3 :: Only",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
],
|
||||
install_requires=install_reqs,
|
||||
extras_require=extras_require,
|
||||
tests_require=test_reqs,
|
||||
setup_requires=['pytest-runner', ],
|
||||
pytest_plugins = ['pytest_profiling'],
|
||||
include_package_data=True,
|
||||
python_requires=">=3.8",
|
||||
entry_points={
|
||||
'console_scripts':
|
||||
['soil = soil.__main__:main',
|
||||
|
@@ -1 +1 @@
|
||||
0.30.0rc2
|
||||
0.30.0rc4
|
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
from importlib.resources import path
|
||||
import sys
|
||||
import os
|
||||
import logging
|
||||
@@ -14,29 +15,33 @@ try:
|
||||
except NameError:
|
||||
basestring = str
|
||||
|
||||
from pathlib import Path
|
||||
from .agents import *
|
||||
from . import agents
|
||||
from .simulation import *
|
||||
from .environment import Environment, EventedEnvironment
|
||||
from .datacollection import SoilCollector
|
||||
from . import serialization
|
||||
from .utils import logger
|
||||
from .time import *
|
||||
from .decorators import *
|
||||
|
||||
|
||||
def main(
|
||||
cfg="simulation.yml",
|
||||
exporters=None,
|
||||
parallel=None,
|
||||
num_processes=1,
|
||||
output="soil_output",
|
||||
*,
|
||||
do_run=False,
|
||||
debug=False,
|
||||
pdb=False,
|
||||
**kwargs,
|
||||
):
|
||||
|
||||
sim = None
|
||||
if isinstance(cfg, Simulation):
|
||||
sim = cfg
|
||||
|
||||
import argparse
|
||||
from . import simulation
|
||||
|
||||
@@ -47,7 +52,7 @@ def main(
|
||||
"file",
|
||||
type=str,
|
||||
nargs="?",
|
||||
default=cfg if sim is None else '',
|
||||
default=cfg if sim is None else "",
|
||||
help="Configuration file for the simulation (e.g., YAML or JSON)",
|
||||
)
|
||||
parser.add_argument(
|
||||
@@ -63,6 +68,11 @@ def main(
|
||||
"--dry-run",
|
||||
"--dry",
|
||||
action="store_true",
|
||||
help="Do not run the simulation",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-dump",
|
||||
action="store_true",
|
||||
help="Do not store the results of the simulation to disk, show in terminal instead.",
|
||||
)
|
||||
parser.add_argument(
|
||||
@@ -92,12 +102,11 @@ def main(
|
||||
default=output or "soil_output",
|
||||
help="folder to write results to. It defaults to the current directory.",
|
||||
)
|
||||
if parallel is None:
|
||||
parser.add_argument(
|
||||
"--synchronous",
|
||||
action="store_true",
|
||||
help="Run trials serially and synchronously instead of in parallel. Defaults to false.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--num-processes",
|
||||
default=num_processes,
|
||||
help="Number of processes to use for parallel execution. Defaults to 1.",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"-e",
|
||||
@@ -106,6 +115,17 @@ def main(
|
||||
default=[],
|
||||
help="Export environment and/or simulations using this exporter",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--until",
|
||||
default="",
|
||||
help="Set maximum time for the simulation to run. ",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--seed",
|
||||
default=None,
|
||||
help="Manually set a seed for the simulation.",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--only-convert",
|
||||
@@ -132,9 +152,6 @@ def main(
|
||||
if args.version:
|
||||
return
|
||||
|
||||
if parallel is None:
|
||||
parallel = not args.synchronous
|
||||
|
||||
exporters = exporters or [
|
||||
"default",
|
||||
]
|
||||
@@ -162,38 +179,46 @@ def main(
|
||||
res = []
|
||||
try:
|
||||
exp_params = {}
|
||||
opts = dict(
|
||||
dry_run=args.dry_run,
|
||||
dump=not args.no_dump,
|
||||
debug=debug,
|
||||
exporters=exporters,
|
||||
num_processes=args.num_processes,
|
||||
outdir=output,
|
||||
exporter_params=exp_params,
|
||||
**kwargs)
|
||||
if args.seed is not None:
|
||||
opts["seed"] = args.seed
|
||||
|
||||
if sim:
|
||||
logger.info("Loading simulation instance")
|
||||
sim.dry_run = args.dry_run
|
||||
sim.exporters = exporters
|
||||
sim.parallel = parallel
|
||||
sim.outdir = output
|
||||
sims = [sim, ]
|
||||
for (k, v) in opts.items():
|
||||
setattr(sim, k, v)
|
||||
sims = [sim]
|
||||
else:
|
||||
logger.info("Loading config file: {}".format(args.file))
|
||||
if not os.path.exists(args.file):
|
||||
logger.error("Please, input a valid file")
|
||||
return
|
||||
|
||||
sims = list(simulation.iter_from_config(
|
||||
args.file,
|
||||
dry_run=args.dry_run,
|
||||
exporters=exporters,
|
||||
parallel=parallel,
|
||||
outdir=output,
|
||||
exporter_params=exp_params,
|
||||
**kwargs,
|
||||
))
|
||||
assert opts["debug"] == debug
|
||||
sims = list(
|
||||
simulation.iter_from_file(
|
||||
args.file,
|
||||
**opts,
|
||||
)
|
||||
)
|
||||
|
||||
for sim in sims:
|
||||
assert sim.debug == debug
|
||||
|
||||
if args.set:
|
||||
for s in args.set:
|
||||
k, v = s.split("=", 1)[:2]
|
||||
v = eval(v)
|
||||
tail, *head = k.rsplit(".", 1)[::-1]
|
||||
target = sim
|
||||
target = sim.model_params
|
||||
if head:
|
||||
for part in head[0].split("."):
|
||||
try:
|
||||
@@ -208,11 +233,7 @@ def main(
|
||||
if args.only_convert:
|
||||
print(sim.to_yaml())
|
||||
continue
|
||||
if do_run:
|
||||
res.append(sim.run())
|
||||
else:
|
||||
print("not running")
|
||||
res.append(sim)
|
||||
res.append(sim.run(until=args.until))
|
||||
|
||||
except Exception as ex:
|
||||
if args.pdb:
|
||||
@@ -233,7 +254,7 @@ def main(
|
||||
@contextmanager
|
||||
def easy(cfg, pdb=False, debug=False, **kwargs):
|
||||
try:
|
||||
yield main(cfg, debug=debug, pdb=pdb, **kwargs)[0]
|
||||
return main(cfg, debug=debug, pdb=pdb, **kwargs)[0]
|
||||
except Exception as e:
|
||||
if os.environ.get("SOIL_POSTMORTEM"):
|
||||
from .debugging import post_mortem
|
||||
@@ -244,4 +265,4 @@ def easy(cfg, pdb=False, debug=False, **kwargs):
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(do_run=True)
|
||||
main()
|
||||
|
@@ -2,8 +2,8 @@ from . import main as init_main
|
||||
|
||||
|
||||
def main():
|
||||
init_main(do_run=True)
|
||||
init_main()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
init_main(do_run=True)
|
||||
init_main()
|
||||
|
@@ -22,10 +22,10 @@ class BassModel(FSM):
|
||||
else:
|
||||
aware_neighbors = self.get_neighbors(state_id=self.aware.id)
|
||||
num_neighbors_aware = len(aware_neighbors)
|
||||
if self.prob((self["imitation_prob"] * num_neighbors_aware)):
|
||||
if self.prob((self.imitation_prob * num_neighbors_aware)):
|
||||
self.sentimentCorrelation = 1
|
||||
return self.aware
|
||||
|
||||
@state
|
||||
def aware(self):
|
||||
self.die()
|
||||
self.die()
|
@@ -1,118 +0,0 @@
|
||||
from . import FSM, state, default_state
|
||||
|
||||
|
||||
class BigMarketModel(FSM):
|
||||
"""
|
||||
Settings:
|
||||
Names:
|
||||
enterprises [Array]
|
||||
|
||||
tweet_probability_enterprises [Array]
|
||||
Users:
|
||||
tweet_probability_users
|
||||
|
||||
tweet_relevant_probability
|
||||
|
||||
tweet_probability_about [Array]
|
||||
|
||||
sentiment_about [Array]
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.enterprises = self.env.environment_params["enterprises"]
|
||||
self.type = ""
|
||||
|
||||
if self.id < len(self.enterprises): # Enterprises
|
||||
self._set_state(self.enterprise.id)
|
||||
self.type = "Enterprise"
|
||||
self.tweet_probability = environment.environment_params[
|
||||
"tweet_probability_enterprises"
|
||||
][self.id]
|
||||
else: # normal users
|
||||
self.type = "User"
|
||||
self._set_state(self.user.id)
|
||||
self.tweet_probability = environment.environment_params[
|
||||
"tweet_probability_users"
|
||||
]
|
||||
self.tweet_relevant_probability = environment.environment_params[
|
||||
"tweet_relevant_probability"
|
||||
]
|
||||
self.tweet_probability_about = environment.environment_params[
|
||||
"tweet_probability_about"
|
||||
] # List
|
||||
self.sentiment_about = environment.environment_params[
|
||||
"sentiment_about"
|
||||
] # List
|
||||
|
||||
@state
|
||||
def enterprise(self):
|
||||
|
||||
if self.random.random() < self.tweet_probability: # Tweets
|
||||
aware_neighbors = self.get_neighbors(
|
||||
state_id=self.number_of_enterprises
|
||||
) # Nodes neighbour users
|
||||
for x in aware_neighbors:
|
||||
if self.random.uniform(0, 10) < 5:
|
||||
x.sentiment_about[self.id] += 0.1 # Increments for enterprise
|
||||
else:
|
||||
x.sentiment_about[self.id] -= 0.1 # Decrements for enterprise
|
||||
|
||||
# Establecemos limites
|
||||
if x.sentiment_about[self.id] > 1:
|
||||
x.sentiment_about[self.id] = 1
|
||||
if x.sentiment_about[self.id] < -1:
|
||||
x.sentiment_about[self.id] = -1
|
||||
|
||||
x.attrs[
|
||||
"sentiment_enterprise_%s" % self.enterprises[self.id]
|
||||
] = x.sentiment_about[self.id]
|
||||
|
||||
@state
|
||||
def user(self):
|
||||
if self.random.random() < self.tweet_probability: # Tweets
|
||||
if (
|
||||
self.random.random() < self.tweet_relevant_probability
|
||||
): # Tweets something relevant
|
||||
# Tweet probability per enterprise
|
||||
for i in range(len(self.enterprises)):
|
||||
random_num = self.random.random()
|
||||
if random_num < self.tweet_probability_about[i]:
|
||||
# The condition is fulfilled, sentiments are evaluated towards that enterprise
|
||||
if self.sentiment_about[i] < 0:
|
||||
# NEGATIVO
|
||||
self.userTweets("negative", i)
|
||||
elif self.sentiment_about[i] == 0:
|
||||
# NEUTRO
|
||||
pass
|
||||
else:
|
||||
# POSITIVO
|
||||
self.userTweets("positive", i)
|
||||
for i in range(
|
||||
len(self.enterprises)
|
||||
): # So that it never is set to 0 if there are not changes (logs)
|
||||
self.attrs[
|
||||
"sentiment_enterprise_%s" % self.enterprises[i]
|
||||
] = self.sentiment_about[i]
|
||||
|
||||
def userTweets(self, sentiment, enterprise):
|
||||
aware_neighbors = self.get_neighbors(
|
||||
state_id=self.number_of_enterprises
|
||||
) # Nodes neighbours users
|
||||
for x in aware_neighbors:
|
||||
if sentiment == "positive":
|
||||
x.sentiment_about[enterprise] += 0.003
|
||||
elif sentiment == "negative":
|
||||
x.sentiment_about[enterprise] -= 0.003
|
||||
else:
|
||||
pass
|
||||
|
||||
# Establecemos limites
|
||||
if x.sentiment_about[enterprise] > 1:
|
||||
x.sentiment_about[enterprise] = 1
|
||||
if x.sentiment_about[enterprise] < -1:
|
||||
x.sentiment_about[enterprise] = -1
|
||||
|
||||
x.attrs[
|
||||
"sentiment_enterprise_%s" % self.enterprises[enterprise]
|
||||
] = x.sentiment_about[enterprise]
|
@@ -1,6 +1,12 @@
|
||||
from . import NetworkAgent
|
||||
from . import BaseAgent, NetworkAgent
|
||||
|
||||
|
||||
class Ticker(BaseAgent):
|
||||
times = 0
|
||||
|
||||
def step(self):
|
||||
self.times += 1
|
||||
|
||||
class CounterModel(NetworkAgent):
|
||||
"""
|
||||
Dummy behaviour. It counts the number of nodes in the network and neighbors
|
||||
|
@@ -1,14 +1,14 @@
|
||||
from scipy.spatial import cKDTree as KDTree
|
||||
import networkx as nx
|
||||
from . import NetworkAgent, as_node
|
||||
from . import NetworkAgent
|
||||
|
||||
|
||||
class Geo(NetworkAgent):
|
||||
"""In this type of network, nodes have a "pos" attribute."""
|
||||
|
||||
def geo_search(self, radius, node=None, center=False, **kwargs):
|
||||
def geo_search(self, radius, agent=None, center=False, **kwargs):
|
||||
"""Get a list of nodes whose coordinates are closer than *radius* to *node*."""
|
||||
node = as_node(node if node is not None else self)
|
||||
node = agent.node
|
||||
|
||||
G = self.subgraph(**kwargs)
|
||||
|
||||
@@ -18,4 +18,4 @@ class Geo(NetworkAgent):
|
||||
nodes, coords = list(zip(*pos.items()))
|
||||
kdtree = KDTree(coords) # Cannot provide generator.
|
||||
indices = kdtree.query_ball_point(pos[node], radius)
|
||||
return [nodes[i] for i in indices if center or (nodes[i] != node)]
|
||||
return [nodes[i] for i in indices if center or (nodes[i] != node)]
|
@@ -1,7 +1,7 @@
|
||||
from . import BaseAgent
|
||||
from . import Agent, state, default_state
|
||||
|
||||
|
||||
class IndependentCascadeModel(BaseAgent):
|
||||
class IndependentCascadeModel(Agent):
|
||||
"""
|
||||
Settings:
|
||||
innovation_prob
|
||||
@@ -9,42 +9,22 @@ class IndependentCascadeModel(BaseAgent):
|
||||
imitation_prob
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.innovation_prob = self.env.environment_params["innovation_prob"]
|
||||
self.imitation_prob = self.env.environment_params["imitation_prob"]
|
||||
self.state["time_awareness"] = 0
|
||||
self.state["sentimentCorrelation"] = 0
|
||||
time_awareness = 0
|
||||
sentimentCorrelation = 0
|
||||
|
||||
def step(self):
|
||||
self.behaviour()
|
||||
# Outside effects
|
||||
@default_state
|
||||
@state
|
||||
def outside(self):
|
||||
if self.prob(self.model.innovation_prob):
|
||||
self.sentimentCorrelation = 1
|
||||
self.time_awareness = self.model.now # To know when they have been infected
|
||||
return self.imitate
|
||||
|
||||
def behaviour(self):
|
||||
aware_neighbors_1_time_step = []
|
||||
# Outside effects
|
||||
if self.prob(self.innovation_prob):
|
||||
if self.state["id"] == 0:
|
||||
self.state["id"] = 1
|
||||
self.state["sentimentCorrelation"] = 1
|
||||
self.state[
|
||||
"time_awareness"
|
||||
] = self.env.now # To know when they have been infected
|
||||
else:
|
||||
pass
|
||||
@state
|
||||
def imitate(self):
|
||||
aware_neighbors = self.get_neighbors(state_id=1, time_awareness=self.now-1)
|
||||
|
||||
return
|
||||
|
||||
# Imitation effects
|
||||
if self.state["id"] == 0:
|
||||
aware_neighbors = self.get_neighbors(state_id=1)
|
||||
for x in aware_neighbors:
|
||||
if x.state["time_awareness"] == (self.env.now - 1):
|
||||
aware_neighbors_1_time_step.append(x)
|
||||
num_neighbors_aware = len(aware_neighbors_1_time_step)
|
||||
if self.prob(self.imitation_prob * num_neighbors_aware):
|
||||
self.state["id"] = 1
|
||||
self.state["sentimentCorrelation"] = 1
|
||||
else:
|
||||
pass
|
||||
|
||||
return
|
||||
if self.prob(self.model.imitation_prob * len(aware_neighbors)):
|
||||
self.sentimentCorrelation = 1
|
||||
return self.outside
|
@@ -1,270 +0,0 @@
|
||||
import numpy as np
|
||||
from . import BaseAgent
|
||||
|
||||
|
||||
class SpreadModelM2(BaseAgent):
|
||||
"""
|
||||
Settings:
|
||||
prob_neutral_making_denier
|
||||
|
||||
prob_infect
|
||||
|
||||
prob_cured_healing_infected
|
||||
|
||||
prob_cured_vaccinate_neutral
|
||||
|
||||
prob_vaccinated_healing_infected
|
||||
|
||||
prob_vaccinated_vaccinate_neutral
|
||||
|
||||
prob_generate_anti_rumor
|
||||
"""
|
||||
|
||||
def __init__(self, model=None, unique_id=0, state=()):
|
||||
super().__init__(model=environment, unique_id=unique_id, state=state)
|
||||
|
||||
# Use a single generator with the same seed as `self.random`
|
||||
random = np.random.default_rng(seed=self._seed)
|
||||
self.prob_neutral_making_denier = random.normal(
|
||||
environment.environment_params["prob_neutral_making_denier"],
|
||||
environment.environment_params["standard_variance"],
|
||||
)
|
||||
|
||||
self.prob_infect = random.normal(
|
||||
environment.environment_params["prob_infect"],
|
||||
environment.environment_params["standard_variance"],
|
||||
)
|
||||
|
||||
self.prob_cured_healing_infected = random.normal(
|
||||
environment.environment_params["prob_cured_healing_infected"],
|
||||
environment.environment_params["standard_variance"],
|
||||
)
|
||||
self.prob_cured_vaccinate_neutral = random.normal(
|
||||
environment.environment_params["prob_cured_vaccinate_neutral"],
|
||||
environment.environment_params["standard_variance"],
|
||||
)
|
||||
|
||||
self.prob_vaccinated_healing_infected = random.normal(
|
||||
environment.environment_params["prob_vaccinated_healing_infected"],
|
||||
environment.environment_params["standard_variance"],
|
||||
)
|
||||
self.prob_vaccinated_vaccinate_neutral = random.normal(
|
||||
environment.environment_params["prob_vaccinated_vaccinate_neutral"],
|
||||
environment.environment_params["standard_variance"],
|
||||
)
|
||||
self.prob_generate_anti_rumor = random.normal(
|
||||
environment.environment_params["prob_generate_anti_rumor"],
|
||||
environment.environment_params["standard_variance"],
|
||||
)
|
||||
|
||||
def step(self):
|
||||
|
||||
if self.state["id"] == 0: # Neutral
|
||||
self.neutral_behaviour()
|
||||
elif self.state["id"] == 1: # Infected
|
||||
self.infected_behaviour()
|
||||
elif self.state["id"] == 2: # Cured
|
||||
self.cured_behaviour()
|
||||
elif self.state["id"] == 3: # Vaccinated
|
||||
self.vaccinated_behaviour()
|
||||
|
||||
def neutral_behaviour(self):
|
||||
|
||||
# Infected
|
||||
infected_neighbors = self.get_neighbors(state_id=1)
|
||||
if len(infected_neighbors) > 0:
|
||||
if self.prob(self.prob_neutral_making_denier):
|
||||
self.state["id"] = 3 # Vaccinated making denier
|
||||
|
||||
def infected_behaviour(self):
|
||||
|
||||
# Neutral
|
||||
neutral_neighbors = self.get_neighbors(state_id=0)
|
||||
for neighbor in neutral_neighbors:
|
||||
if self.prob(self.prob_infect):
|
||||
neighbor.state["id"] = 1 # Infected
|
||||
|
||||
def cured_behaviour(self):
|
||||
|
||||
# Vaccinate
|
||||
neutral_neighbors = self.get_neighbors(state_id=0)
|
||||
for neighbor in neutral_neighbors:
|
||||
if self.prob(self.prob_cured_vaccinate_neutral):
|
||||
neighbor.state["id"] = 3 # Vaccinated
|
||||
|
||||
# Cure
|
||||
infected_neighbors = self.get_neighbors(state_id=1)
|
||||
for neighbor in infected_neighbors:
|
||||
if self.prob(self.prob_cured_healing_infected):
|
||||
neighbor.state["id"] = 2 # Cured
|
||||
|
||||
def vaccinated_behaviour(self):
|
||||
|
||||
# Cure
|
||||
infected_neighbors = self.get_neighbors(state_id=1)
|
||||
for neighbor in infected_neighbors:
|
||||
if self.prob(self.prob_cured_healing_infected):
|
||||
neighbor.state["id"] = 2 # Cured
|
||||
|
||||
# Vaccinate
|
||||
neutral_neighbors = self.get_neighbors(state_id=0)
|
||||
for neighbor in neutral_neighbors:
|
||||
if self.prob(self.prob_cured_vaccinate_neutral):
|
||||
neighbor.state["id"] = 3 # Vaccinated
|
||||
|
||||
# Generate anti-rumor
|
||||
infected_neighbors_2 = self.get_neighbors(state_id=1)
|
||||
for neighbor in infected_neighbors_2:
|
||||
if self.prob(self.prob_generate_anti_rumor):
|
||||
neighbor.state["id"] = 2 # Cured
|
||||
|
||||
|
||||
class ControlModelM2(BaseAgent):
|
||||
"""
|
||||
Settings:
|
||||
prob_neutral_making_denier
|
||||
|
||||
prob_infect
|
||||
|
||||
prob_cured_healing_infected
|
||||
|
||||
prob_cured_vaccinate_neutral
|
||||
|
||||
prob_vaccinated_healing_infected
|
||||
|
||||
prob_vaccinated_vaccinate_neutral
|
||||
|
||||
prob_generate_anti_rumor
|
||||
"""
|
||||
|
||||
def __init__(self, model=None, unique_id=0, state=()):
|
||||
super().__init__(model=environment, unique_id=unique_id, state=state)
|
||||
|
||||
self.prob_neutral_making_denier = np.random.normal(
|
||||
environment.environment_params["prob_neutral_making_denier"],
|
||||
environment.environment_params["standard_variance"],
|
||||
)
|
||||
|
||||
self.prob_infect = np.random.normal(
|
||||
environment.environment_params["prob_infect"],
|
||||
environment.environment_params["standard_variance"],
|
||||
)
|
||||
|
||||
self.prob_cured_healing_infected = np.random.normal(
|
||||
environment.environment_params["prob_cured_healing_infected"],
|
||||
environment.environment_params["standard_variance"],
|
||||
)
|
||||
self.prob_cured_vaccinate_neutral = np.random.normal(
|
||||
environment.environment_params["prob_cured_vaccinate_neutral"],
|
||||
environment.environment_params["standard_variance"],
|
||||
)
|
||||
|
||||
self.prob_vaccinated_healing_infected = np.random.normal(
|
||||
environment.environment_params["prob_vaccinated_healing_infected"],
|
||||
environment.environment_params["standard_variance"],
|
||||
)
|
||||
self.prob_vaccinated_vaccinate_neutral = np.random.normal(
|
||||
environment.environment_params["prob_vaccinated_vaccinate_neutral"],
|
||||
environment.environment_params["standard_variance"],
|
||||
)
|
||||
self.prob_generate_anti_rumor = np.random.normal(
|
||||
environment.environment_params["prob_generate_anti_rumor"],
|
||||
environment.environment_params["standard_variance"],
|
||||
)
|
||||
|
||||
def step(self):
|
||||
|
||||
if self.state["id"] == 0: # Neutral
|
||||
self.neutral_behaviour()
|
||||
elif self.state["id"] == 1: # Infected
|
||||
self.infected_behaviour()
|
||||
elif self.state["id"] == 2: # Cured
|
||||
self.cured_behaviour()
|
||||
elif self.state["id"] == 3: # Vaccinated
|
||||
self.vaccinated_behaviour()
|
||||
elif self.state["id"] == 4: # Beacon-off
|
||||
self.beacon_off_behaviour()
|
||||
elif self.state["id"] == 5: # Beacon-on
|
||||
self.beacon_on_behaviour()
|
||||
|
||||
def neutral_behaviour(self):
|
||||
self.state["visible"] = False
|
||||
|
||||
# Infected
|
||||
infected_neighbors = self.get_neighbors(state_id=1)
|
||||
if len(infected_neighbors) > 0:
|
||||
if self.random(self.prob_neutral_making_denier):
|
||||
self.state["id"] = 3 # Vaccinated making denier
|
||||
|
||||
def infected_behaviour(self):
|
||||
|
||||
# Neutral
|
||||
neutral_neighbors = self.get_neighbors(state_id=0)
|
||||
for neighbor in neutral_neighbors:
|
||||
if self.prob(self.prob_infect):
|
||||
neighbor.state["id"] = 1 # Infected
|
||||
self.state["visible"] = False
|
||||
|
||||
def cured_behaviour(self):
|
||||
|
||||
self.state["visible"] = True
|
||||
# Vaccinate
|
||||
neutral_neighbors = self.get_neighbors(state_id=0)
|
||||
for neighbor in neutral_neighbors:
|
||||
if self.prob(self.prob_cured_vaccinate_neutral):
|
||||
neighbor.state["id"] = 3 # Vaccinated
|
||||
|
||||
# Cure
|
||||
infected_neighbors = self.get_neighbors(state_id=1)
|
||||
for neighbor in infected_neighbors:
|
||||
if self.prob(self.prob_cured_healing_infected):
|
||||
neighbor.state["id"] = 2 # Cured
|
||||
|
||||
def vaccinated_behaviour(self):
|
||||
self.state["visible"] = True
|
||||
|
||||
# Cure
|
||||
infected_neighbors = self.get_neighbors(state_id=1)
|
||||
for neighbor in infected_neighbors:
|
||||
if self.prob(self.prob_cured_healing_infected):
|
||||
neighbor.state["id"] = 2 # Cured
|
||||
|
||||
# Vaccinate
|
||||
neutral_neighbors = self.get_neighbors(state_id=0)
|
||||
for neighbor in neutral_neighbors:
|
||||
if self.prob(self.prob_cured_vaccinate_neutral):
|
||||
neighbor.state["id"] = 3 # Vaccinated
|
||||
|
||||
# Generate anti-rumor
|
||||
infected_neighbors_2 = self.get_neighbors(state_id=1)
|
||||
for neighbor in infected_neighbors_2:
|
||||
if self.prob(self.prob_generate_anti_rumor):
|
||||
neighbor.state["id"] = 2 # Cured
|
||||
|
||||
def beacon_off_behaviour(self):
|
||||
self.state["visible"] = False
|
||||
infected_neighbors = self.get_neighbors(state_id=1)
|
||||
if len(infected_neighbors) > 0:
|
||||
self.state["id"] == 5 # Beacon on
|
||||
|
||||
def beacon_on_behaviour(self):
|
||||
self.state["visible"] = False
|
||||
# Cure (M2 feature added)
|
||||
infected_neighbors = self.get_neighbors(state_id=1)
|
||||
for neighbor in infected_neighbors:
|
||||
if self.prob(self.prob_generate_anti_rumor):
|
||||
neighbor.state["id"] = 2 # Cured
|
||||
neutral_neighbors_infected = neighbor.get_neighbors(state_id=0)
|
||||
for neighbor in neutral_neighbors_infected:
|
||||
if self.prob(self.prob_generate_anti_rumor):
|
||||
neighbor.state["id"] = 3 # Vaccinated
|
||||
infected_neighbors_infected = neighbor.get_neighbors(state_id=1)
|
||||
for neighbor in infected_neighbors_infected:
|
||||
if self.prob(self.prob_generate_anti_rumor):
|
||||
neighbor.state["id"] = 2 # Cured
|
||||
|
||||
# Vaccinate
|
||||
neutral_neighbors = self.get_neighbors(state_id=0)
|
||||
for neighbor in neutral_neighbors:
|
||||
if self.prob(self.prob_cured_vaccinate_neutral):
|
||||
neighbor.state["id"] = 3 # Vaccinated
|
@@ -1,8 +1,9 @@
|
||||
import numpy as np
|
||||
from . import FSM, state
|
||||
from hashlib import sha512
|
||||
from . import Agent, state, default_state
|
||||
|
||||
|
||||
class SISaModel(FSM):
|
||||
class SISaModel(Agent):
|
||||
"""
|
||||
Settings:
|
||||
neutral_discontent_spon_prob
|
||||
@@ -28,38 +29,45 @@ class SISaModel(FSM):
|
||||
standard_variance
|
||||
"""
|
||||
|
||||
def __init__(self, environment, unique_id=0, state=()):
|
||||
super().__init__(model=environment, unique_id=unique_id, state=state)
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
random = np.random.default_rng(seed=self._seed)
|
||||
seed = self.model._seed
|
||||
if isinstance(seed, (str, bytes, bytearray)):
|
||||
if isinstance(seed, str):
|
||||
seed = seed.encode()
|
||||
seed = int.from_bytes(seed + sha512(seed).digest(), 'big')
|
||||
|
||||
random = np.random.default_rng(seed=seed)
|
||||
|
||||
self.neutral_discontent_spon_prob = random.normal(
|
||||
self.env["neutral_discontent_spon_prob"], self.env["standard_variance"]
|
||||
self.model.neutral_discontent_spon_prob, self.model.standard_variance
|
||||
)
|
||||
self.neutral_discontent_infected_prob = random.normal(
|
||||
self.env["neutral_discontent_infected_prob"], self.env["standard_variance"]
|
||||
self.model.neutral_discontent_infected_prob, self.model.standard_variance
|
||||
)
|
||||
self.neutral_content_spon_prob = random.normal(
|
||||
self.env["neutral_content_spon_prob"], self.env["standard_variance"]
|
||||
self.model.neutral_content_spon_prob, self.model.standard_variance
|
||||
)
|
||||
self.neutral_content_infected_prob = random.normal(
|
||||
self.env["neutral_content_infected_prob"], self.env["standard_variance"]
|
||||
self.model.neutral_content_infected_prob, self.model.standard_variance
|
||||
)
|
||||
|
||||
self.discontent_neutral = random.normal(
|
||||
self.env["discontent_neutral"], self.env["standard_variance"]
|
||||
self.model.discontent_neutral, self.model.standard_variance
|
||||
)
|
||||
self.discontent_content = random.normal(
|
||||
self.env["discontent_content"], self.env["variance_d_c"]
|
||||
self.model.discontent_content, self.model.variance_d_c
|
||||
)
|
||||
|
||||
self.content_discontent = random.normal(
|
||||
self.env["content_discontent"], self.env["variance_c_d"]
|
||||
self.model.content_discontent, self.model.variance_c_d
|
||||
)
|
||||
self.content_neutral = random.normal(
|
||||
self.env["content_neutral"], self.env["standard_variance"]
|
||||
self.model.discontent_neutral, self.model.standard_variance
|
||||
)
|
||||
|
||||
@default_state
|
||||
@state
|
||||
def neutral(self):
|
||||
# Spontaneous effects
|
||||
@@ -70,10 +78,10 @@ class SISaModel(FSM):
|
||||
|
||||
# Infected
|
||||
discontent_neighbors = self.count_neighbors(state_id=self.discontent)
|
||||
if self.prob(scontent_neighbors * self.neutral_discontent_infected_prob):
|
||||
if self.prob(discontent_neighbors * self.neutral_discontent_infected_prob):
|
||||
return self.discontent
|
||||
content_neighbors = self.count_neighbors(state_id=self.content.id)
|
||||
if self.prob(s * self.neutral_content_infected_prob):
|
||||
if self.prob(content_neighbors * self.neutral_content_infected_prob):
|
||||
return self.content
|
||||
return self.neutral
|
||||
|
||||
@@ -85,7 +93,7 @@ class SISaModel(FSM):
|
||||
|
||||
# Superinfected
|
||||
content_neighbors = self.count_neighbors(state_id=self.content.id)
|
||||
if self.prob(s * self.discontent_content):
|
||||
if self.prob(content_neighbors * self.discontent_content):
|
||||
return self.content
|
||||
return self.discontent
|
||||
|
||||
@@ -97,6 +105,6 @@ class SISaModel(FSM):
|
||||
|
||||
# Superinfected
|
||||
discontent_neighbors = self.count_neighbors(state_id=self.discontent.id)
|
||||
if self.prob(scontent_neighbors * self.content_discontent):
|
||||
if self.prob(discontent_neighbors * self.content_discontent):
|
||||
self.discontent
|
||||
return self.content
|
||||
|
@@ -1,115 +0,0 @@
|
||||
from . import BaseAgent
|
||||
|
||||
|
||||
class SentimentCorrelationModel(BaseAgent):
|
||||
"""
|
||||
Settings:
|
||||
outside_effects_prob
|
||||
|
||||
anger_prob
|
||||
|
||||
joy_prob
|
||||
|
||||
sadness_prob
|
||||
|
||||
disgust_prob
|
||||
"""
|
||||
|
||||
def __init__(self, environment, unique_id=0, state=()):
|
||||
super().__init__(model=environment, unique_id=unique_id, state=state)
|
||||
self.outside_effects_prob = environment.environment_params[
|
||||
"outside_effects_prob"
|
||||
]
|
||||
self.anger_prob = environment.environment_params["anger_prob"]
|
||||
self.joy_prob = environment.environment_params["joy_prob"]
|
||||
self.sadness_prob = environment.environment_params["sadness_prob"]
|
||||
self.disgust_prob = environment.environment_params["disgust_prob"]
|
||||
self.state["time_awareness"] = []
|
||||
for i in range(4): # In this model we have 4 sentiments
|
||||
self.state["time_awareness"].append(
|
||||
0
|
||||
) # 0-> Anger, 1-> joy, 2->sadness, 3 -> disgust
|
||||
self.state["sentimentCorrelation"] = 0
|
||||
|
||||
def step(self):
|
||||
self.behaviour()
|
||||
|
||||
def behaviour(self):
|
||||
|
||||
angry_neighbors_1_time_step = []
|
||||
joyful_neighbors_1_time_step = []
|
||||
sad_neighbors_1_time_step = []
|
||||
disgusted_neighbors_1_time_step = []
|
||||
|
||||
angry_neighbors = self.get_neighbors(state_id=1)
|
||||
for x in angry_neighbors:
|
||||
if x.state["time_awareness"][0] > (self.env.now - 500):
|
||||
angry_neighbors_1_time_step.append(x)
|
||||
num_neighbors_angry = len(angry_neighbors_1_time_step)
|
||||
|
||||
joyful_neighbors = self.get_neighbors(state_id=2)
|
||||
for x in joyful_neighbors:
|
||||
if x.state["time_awareness"][1] > (self.env.now - 500):
|
||||
joyful_neighbors_1_time_step.append(x)
|
||||
num_neighbors_joyful = len(joyful_neighbors_1_time_step)
|
||||
|
||||
sad_neighbors = self.get_neighbors(state_id=3)
|
||||
for x in sad_neighbors:
|
||||
if x.state["time_awareness"][2] > (self.env.now - 500):
|
||||
sad_neighbors_1_time_step.append(x)
|
||||
num_neighbors_sad = len(sad_neighbors_1_time_step)
|
||||
|
||||
disgusted_neighbors = self.get_neighbors(state_id=4)
|
||||
for x in disgusted_neighbors:
|
||||
if x.state["time_awareness"][3] > (self.env.now - 500):
|
||||
disgusted_neighbors_1_time_step.append(x)
|
||||
num_neighbors_disgusted = len(disgusted_neighbors_1_time_step)
|
||||
|
||||
anger_prob = self.anger_prob + (
|
||||
len(angry_neighbors_1_time_step) * self.anger_prob
|
||||
)
|
||||
joy_prob = self.joy_prob + (len(joyful_neighbors_1_time_step) * self.joy_prob)
|
||||
sadness_prob = self.sadness_prob + (
|
||||
len(sad_neighbors_1_time_step) * self.sadness_prob
|
||||
)
|
||||
disgust_prob = self.disgust_prob + (
|
||||
len(disgusted_neighbors_1_time_step) * self.disgust_prob
|
||||
)
|
||||
outside_effects_prob = self.outside_effects_prob
|
||||
|
||||
num = self.random.random()
|
||||
|
||||
if num < outside_effects_prob:
|
||||
self.state["id"] = self.random.randint(1, 4)
|
||||
|
||||
self.state["sentimentCorrelation"] = self.state[
|
||||
"id"
|
||||
] # It is stored when it has been infected for the dynamic network
|
||||
self.state["time_awareness"][self.state["id"] - 1] = self.env.now
|
||||
self.state["sentiment"] = self.state["id"]
|
||||
|
||||
if num < anger_prob:
|
||||
|
||||
self.state["id"] = 1
|
||||
self.state["sentimentCorrelation"] = 1
|
||||
self.state["time_awareness"][self.state["id"] - 1] = self.env.now
|
||||
elif num < joy_prob + anger_prob and num > anger_prob:
|
||||
|
||||
self.state["id"] = 2
|
||||
self.state["sentimentCorrelation"] = 2
|
||||
self.state["time_awareness"][self.state["id"] - 1] = self.env.now
|
||||
elif num < sadness_prob + anger_prob + joy_prob and num > joy_prob + anger_prob:
|
||||
|
||||
self.state["id"] = 3
|
||||
self.state["sentimentCorrelation"] = 3
|
||||
self.state["time_awareness"][self.state["id"] - 1] = self.env.now
|
||||
elif (
|
||||
num < disgust_prob + sadness_prob + anger_prob + joy_prob
|
||||
and num > sadness_prob + anger_prob + joy_prob
|
||||
):
|
||||
|
||||
self.state["id"] = 4
|
||||
self.state["sentimentCorrelation"] = 4
|
||||
self.state["time_awareness"][self.state["id"] - 1] = self.env.now
|
||||
|
||||
self.state["sentiment"] = self.state["id"]
|
@@ -11,19 +11,15 @@ import inspect
|
||||
import types
|
||||
import textwrap
|
||||
import networkx as nx
|
||||
import warnings
|
||||
import sys
|
||||
|
||||
from typing import Any
|
||||
|
||||
from mesa import Agent as MesaAgent
|
||||
from mesa import Agent as MesaAgent, Model
|
||||
from typing import Dict, List
|
||||
|
||||
from .. import serialization, utils, time, config
|
||||
|
||||
|
||||
def as_node(agent):
|
||||
if isinstance(agent, BaseAgent):
|
||||
return agent.id
|
||||
return agent
|
||||
from .. import serialization, network, utils, time, config
|
||||
|
||||
|
||||
IGNORED_FIELDS = ("model", "logger")
|
||||
@@ -96,11 +92,7 @@ class BaseAgent(MesaAgent, MutableMapping, metaclass=MetaAgent):
|
||||
Any attribute that is not preceded by an underscore (`_`) will also be added to its state.
|
||||
"""
|
||||
|
||||
def __init__(self, unique_id, model, name=None, interval=None, **kwargs):
|
||||
# Check for REQUIRED arguments
|
||||
# Initialize agent parameters
|
||||
if isinstance(unique_id, MesaAgent):
|
||||
raise Exception()
|
||||
def __init__(self, unique_id, model, name=None, init=True, interval=None, **kwargs):
|
||||
assert isinstance(unique_id, int)
|
||||
super().__init__(unique_id=unique_id, model=model)
|
||||
|
||||
@@ -126,6 +118,11 @@ class BaseAgent(MesaAgent, MutableMapping, metaclass=MetaAgent):
|
||||
for (k, v) in kwargs.items():
|
||||
|
||||
setattr(self, k, v)
|
||||
if init:
|
||||
self.init()
|
||||
|
||||
def init(self):
|
||||
pass
|
||||
|
||||
def __hash__(self):
|
||||
return hash(self.unique_id)
|
||||
@@ -133,9 +130,16 @@ class BaseAgent(MesaAgent, MutableMapping, metaclass=MetaAgent):
|
||||
def prob(self, probability):
|
||||
return prob(probability, self.model.random)
|
||||
|
||||
@classmethod
|
||||
def w(cls, **kwargs):
|
||||
return custom(cls, **kwargs)
|
||||
|
||||
# TODO: refactor to clean up mesa compatibility
|
||||
@property
|
||||
def id(self):
|
||||
msg = "This attribute is deprecated. Use `unique_id` instead"
|
||||
warnings.warn(msg, DeprecationWarning)
|
||||
print(msg, file=sys.stderr)
|
||||
return self.unique_id
|
||||
|
||||
@classmethod
|
||||
@@ -185,7 +189,11 @@ class BaseAgent(MesaAgent, MutableMapping, metaclass=MetaAgent):
|
||||
return it
|
||||
|
||||
def get(self, key, default=None):
|
||||
return self[key] if key in self else default
|
||||
if key in self:
|
||||
return self[key]
|
||||
elif key in self.model:
|
||||
return self.model[key]
|
||||
return default
|
||||
|
||||
@property
|
||||
def now(self):
|
||||
@@ -195,8 +203,10 @@ class BaseAgent(MesaAgent, MutableMapping, metaclass=MetaAgent):
|
||||
# No environment
|
||||
return None
|
||||
|
||||
def die(self):
|
||||
self.info(f"agent dying")
|
||||
def die(self, msg=None):
|
||||
if msg:
|
||||
self.info("Agent dying:", msg)
|
||||
self.debug(f"agent dying")
|
||||
self.alive = False
|
||||
try:
|
||||
self.model.schedule.remove(self)
|
||||
@@ -205,14 +215,16 @@ class BaseAgent(MesaAgent, MutableMapping, metaclass=MetaAgent):
|
||||
return time.NEVER
|
||||
|
||||
def step(self):
|
||||
raise NotImplementedError("Agent must implement step method")
|
||||
|
||||
def _check_alive(self):
|
||||
if not self.alive:
|
||||
raise time.DeadAgent(self.unique_id)
|
||||
return super().step() or time.Delta(self.interval)
|
||||
|
||||
def log(self, message, *args, level=logging.INFO, **kwargs):
|
||||
|
||||
def log(self, *message, level=logging.INFO, **kwargs):
|
||||
if not self.logger.isEnabledFor(level):
|
||||
return
|
||||
message = message + " ".join(str(i) for i in args)
|
||||
message = " ".join(str(i) for i in message)
|
||||
message = "[@{:>4}]\t{:>10}: {}".format(self.now, repr(self), message)
|
||||
for k, v in kwargs:
|
||||
message += " {k}={v} ".format(k, v)
|
||||
@@ -385,7 +397,7 @@ class AgentView(Mapping, Set):
|
||||
|
||||
|
||||
def filter_agents(
|
||||
agents,
|
||||
agents: dict,
|
||||
*id_args,
|
||||
unique_id=None,
|
||||
state_id=None,
|
||||
@@ -414,7 +426,7 @@ def filter_agents(
|
||||
if ids:
|
||||
f = (agents[aid] for aid in ids if aid in agents)
|
||||
else:
|
||||
f = (a for a in agents.values())
|
||||
f = agents.values()
|
||||
|
||||
if state_id is not None and not isinstance(state_id, (tuple, list)):
|
||||
state_id = tuple([state_id])
|
||||
@@ -564,9 +576,9 @@ def _from_fixed(
|
||||
def _from_distro(
|
||||
distro: List[config.AgentDistro],
|
||||
n: int,
|
||||
topology: str,
|
||||
default: config.SingleAgentConfig,
|
||||
random,
|
||||
topology: str = None
|
||||
) -> List[Dict[str, Any]]:
|
||||
|
||||
agents = []
|
||||
@@ -630,14 +642,22 @@ def _from_distro(
|
||||
from .network_agents import *
|
||||
from .fsm import *
|
||||
from .evented import *
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class Agent(NetworkAgent, FSM, EventedAgent):
|
||||
"""Default agent class, has both network and event capabilities"""
|
||||
|
||||
|
||||
from ..environment import NetworkEnvironment
|
||||
|
||||
|
||||
from .BassModel import *
|
||||
from .BigMarketModel import *
|
||||
from .IndependentCascadeModel import *
|
||||
from .ModelM2 import *
|
||||
from .SentimentCorrelationModel import *
|
||||
from .SISaModel import *
|
||||
from .CounterModel import *
|
||||
|
||||
|
||||
try:
|
||||
import scipy
|
||||
from .Geo import Geo
|
||||
@@ -645,3 +665,8 @@ except ImportError:
|
||||
import sys
|
||||
|
||||
print("Could not load the Geo Agent, scipy is not installed", file=sys.stderr)
|
||||
|
||||
|
||||
def custom(cls, **kwargs):
|
||||
"""Create a new class from a template class and keyword arguments"""
|
||||
return type(cls.__name__, (cls,), kwargs)
|
@@ -1,57 +1,77 @@
|
||||
from . import BaseAgent
|
||||
from ..events import Message, Tell, Ask, Reply, TimedOut
|
||||
from ..time import Cond
|
||||
from ..events import Message, Tell, Ask, TimedOut
|
||||
from ..time import BaseCond
|
||||
from functools import partial
|
||||
from collections import deque
|
||||
|
||||
|
||||
class Evented(BaseAgent):
|
||||
class ReceivedOrTimeout(BaseCond):
|
||||
def __init__(
|
||||
self, agent, expiration=None, timeout=None, check=True, ignore=False, **kwargs
|
||||
):
|
||||
if expiration is None:
|
||||
if timeout is not None:
|
||||
expiration = agent.now + timeout
|
||||
self.expiration = expiration
|
||||
self.ignore = ignore
|
||||
self.check = check
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def expired(self, time):
|
||||
return self.expiration and self.expiration < time
|
||||
|
||||
def ready(self, agent, time):
|
||||
return len(agent._inbox) or self.expired(time)
|
||||
|
||||
def return_value(self, agent):
|
||||
if not self.ignore and self.expired(agent.now):
|
||||
raise TimedOut("No messages received")
|
||||
if self.check:
|
||||
agent.check_messages()
|
||||
return None
|
||||
|
||||
def schedule_next(self, time, delta, first=False):
|
||||
if self._delta is not None:
|
||||
delta = self._delta
|
||||
return (time + delta, self)
|
||||
|
||||
def __repr__(self):
|
||||
return f"ReceivedOrTimeout(expires={self.expiration})"
|
||||
|
||||
|
||||
class EventedAgent(BaseAgent):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self._inbox = deque()
|
||||
self._received = 0
|
||||
self._processed = 0
|
||||
|
||||
|
||||
def on_receive(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def received(self, expiration=None, timeout=None):
|
||||
current = self._received
|
||||
if expiration is None:
|
||||
expiration = float('inf') if timeout is None else self.now + timeout
|
||||
def received(self, *args, **kwargs):
|
||||
return ReceivedOrTimeout(self, *args, **kwargs)
|
||||
|
||||
if expiration < self.now:
|
||||
raise ValueError("Invalid expiration time")
|
||||
def tell(self, msg, sender=None):
|
||||
self._inbox.append(Tell(timestamp=self.now, payload=msg, sender=sender))
|
||||
|
||||
def ready(agent):
|
||||
return agent._received > current or agent.now >= expiration
|
||||
|
||||
def value(agent):
|
||||
if agent.now > expiration:
|
||||
raise TimedOut("No message received")
|
||||
|
||||
c = Cond(func=ready, return_func=value)
|
||||
c._checked = True
|
||||
return c
|
||||
|
||||
def tell(self, msg, sender):
|
||||
self._received += 1
|
||||
self._inbox.append(Tell(payload=msg, sender=sender))
|
||||
|
||||
def ask(self, msg, timeout=None):
|
||||
self._received += 1
|
||||
ask = Ask(payload=msg)
|
||||
def ask(self, msg, timeout=None, **kwargs):
|
||||
ask = Ask(timestamp=self.now, payload=msg, sender=self)
|
||||
self._inbox.append(ask)
|
||||
expiration = float('inf') if timeout is None else self.now + timeout
|
||||
return ask.replied(expiration=expiration)
|
||||
expiration = float("inf") if timeout is None else self.now + timeout
|
||||
return ask.replied(expiration=expiration, **kwargs)
|
||||
|
||||
def check_messages(self):
|
||||
changed = False
|
||||
while self._inbox:
|
||||
msg = self._inbox.popleft()
|
||||
self._processed += 1
|
||||
if msg.expired(self.now):
|
||||
continue
|
||||
changed = True
|
||||
reply = self.on_receive(msg.payload, sender=msg.sender)
|
||||
if isinstance(msg, Ask):
|
||||
msg.reply = reply
|
||||
return changed
|
||||
|
||||
|
||||
Evented = EventedAgent
|
||||
|
@@ -1,4 +1,5 @@
|
||||
from . import MetaAgent, BaseAgent
|
||||
from ..time import Delta
|
||||
|
||||
from functools import partial, wraps
|
||||
import inspect
|
||||
@@ -38,8 +39,6 @@ def state(name=None):
|
||||
self._last_return = None
|
||||
self._last_except = None
|
||||
|
||||
|
||||
|
||||
func.id = name or func.__name__
|
||||
func.is_default = False
|
||||
return func
|
||||
@@ -87,8 +86,8 @@ class MetaFSM(MetaAgent):
|
||||
|
||||
|
||||
class FSM(BaseAgent, metaclass=MetaFSM):
|
||||
def __init__(self, **kwargs):
|
||||
super(FSM, self).__init__(**kwargs)
|
||||
def __init__(self, init=True, **kwargs):
|
||||
super().__init__(**kwargs, init=False)
|
||||
if not hasattr(self, "state_id"):
|
||||
if not self._default_state:
|
||||
raise ValueError(
|
||||
@@ -97,12 +96,15 @@ class FSM(BaseAgent, metaclass=MetaFSM):
|
||||
self.state_id = self._default_state.id
|
||||
|
||||
self._coroutine = None
|
||||
self.default_interval = Delta(self.model.interval)
|
||||
self._set_state(self.state_id)
|
||||
if init:
|
||||
self.init()
|
||||
|
||||
def step(self):
|
||||
self.debug(f"Agent {self.unique_id} @ state {self.state_id}")
|
||||
default_interval = super().step()
|
||||
|
||||
self._check_alive()
|
||||
next_state = self._states[self.state_id](self)
|
||||
|
||||
when = None
|
||||
@@ -122,7 +124,7 @@ class FSM(BaseAgent, metaclass=MetaFSM):
|
||||
if next_state is not None:
|
||||
self._set_state(next_state)
|
||||
|
||||
return when or default_interval
|
||||
return when or self.default_interval
|
||||
|
||||
def _set_state(self, state, when=None):
|
||||
if hasattr(state, "id"):
|
||||
@@ -134,8 +136,8 @@ class FSM(BaseAgent, metaclass=MetaFSM):
|
||||
self.model.schedule.add(self, when=when)
|
||||
return state
|
||||
|
||||
def die(self):
|
||||
return self.dead, super().die()
|
||||
def die(self, *args, **kwargs):
|
||||
return self.dead, super().die(*args, **kwargs)
|
||||
|
||||
@state
|
||||
def dead(self):
|
||||
|
@@ -2,20 +2,37 @@ from . import BaseAgent
|
||||
|
||||
|
||||
class NetworkAgent(BaseAgent):
|
||||
def __init__(self, *args, topology, node_id, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
def __init__(self, *args, topology=None, init=True, node_id=None, **kwargs):
|
||||
super().__init__(*args, init=False, **kwargs)
|
||||
|
||||
assert topology is not None
|
||||
assert node_id is not None
|
||||
self.G = topology
|
||||
self.G = topology or self.model.G
|
||||
assert self.G
|
||||
if node_id is None:
|
||||
nodes = self.random.choices(list(self.G.nodes), k=len(self.G))
|
||||
for n_id in nodes:
|
||||
if "agent" not in self.G.nodes[n_id] or self.G.nodes[n_id]["agent"] is None:
|
||||
node_id = n_id
|
||||
break
|
||||
else:
|
||||
node_id = len(self.G)
|
||||
self.info(f"All nodes ({len(self.G)}) have an agent assigned, adding a new node to the graph for agent {self.unique_id}")
|
||||
self.G.add_node(node_id)
|
||||
assert node_id is not None
|
||||
self.G.nodes[node_id]["agent"] = self
|
||||
self.node_id = node_id
|
||||
if init:
|
||||
self.init()
|
||||
|
||||
def count_neighbors(self, state_id=None, **kwargs):
|
||||
return len(self.get_neighbors(state_id=state_id, **kwargs))
|
||||
if init:
|
||||
self.init()
|
||||
|
||||
def iter_neighbors(self, **kwargs):
|
||||
return self.iter_agents(limit_neighbors=True, **kwargs)
|
||||
|
||||
def get_neighbors(self, **kwargs):
|
||||
return list(self.iter_agents(limit_neighbors=True, **kwargs))
|
||||
return list(self.iter_neighbors(**kwargs))
|
||||
|
||||
@property
|
||||
def node(self):
|
||||
@@ -35,8 +52,9 @@ class NetworkAgent(BaseAgent):
|
||||
if limit_neighbors:
|
||||
neighbor_ids = set()
|
||||
for node_id in self.G.neighbors(self.node_id):
|
||||
if self.G.nodes[node_id].get("agent") is not None:
|
||||
neighbor_ids.add(node_id)
|
||||
agent = self.G.nodes[node_id].get("agent")
|
||||
if agent is not None:
|
||||
neighbor_ids.add(agent.unique_id)
|
||||
if unique_ids:
|
||||
unique_ids = unique_ids & neighbor_ids
|
||||
else:
|
||||
@@ -54,7 +72,7 @@ class NetworkAgent(BaseAgent):
|
||||
return G
|
||||
|
||||
def remove_node(self):
|
||||
print(f"Removing node for {self.unique_id}: {self.node_id}")
|
||||
self.debug(f"Removing node for {self.unique_id}: {self.node_id}")
|
||||
self.G.remove_node(self.node_id)
|
||||
self.node_id = None
|
||||
|
||||
@@ -80,3 +98,6 @@ class NetworkAgent(BaseAgent):
|
||||
if remove:
|
||||
self.remove_node()
|
||||
return super().die()
|
||||
|
||||
|
||||
NetAgent = NetworkAgent
|
||||
|
272
soil/config.py
272
soil/config.py
@@ -1,270 +1,2 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import Enum
|
||||
from pydantic import BaseModel, ValidationError, validator, root_validator
|
||||
|
||||
import yaml
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
from typing import Any, Callable, Dict, List, Optional, Union, Type
|
||||
from pydantic import BaseModel, Extra
|
||||
|
||||
from . import environment, utils
|
||||
|
||||
import networkx as nx
|
||||
|
||||
|
||||
# Could use TypeAlias in python >= 3.10
|
||||
nodeId = int
|
||||
|
||||
|
||||
class Node(BaseModel):
|
||||
id: nodeId
|
||||
state: Optional[Dict[str, Any]] = {}
|
||||
|
||||
|
||||
class Edge(BaseModel):
|
||||
source: nodeId
|
||||
target: nodeId
|
||||
value: Optional[float] = 1
|
||||
|
||||
|
||||
class Topology(BaseModel):
|
||||
nodes: List[Node]
|
||||
directed: bool
|
||||
links: List[Edge]
|
||||
|
||||
|
||||
class NetParams(BaseModel, extra=Extra.allow):
|
||||
generator: Union[Callable, str]
|
||||
n: int
|
||||
|
||||
|
||||
class NetConfig(BaseModel):
|
||||
params: Optional[NetParams]
|
||||
fixed: Optional[Union[Topology, nx.Graph]]
|
||||
path: Optional[str]
|
||||
|
||||
class Config:
|
||||
arbitrary_types_allowed = True
|
||||
|
||||
@staticmethod
|
||||
def default():
|
||||
return NetConfig(topology=None, params=None)
|
||||
|
||||
@root_validator
|
||||
def validate_all(cls, values):
|
||||
if "params" not in values and "topology" not in values:
|
||||
raise ValueError(
|
||||
"You must specify either a topology or the parameters to generate a graph"
|
||||
)
|
||||
return values
|
||||
|
||||
|
||||
class EnvConfig(BaseModel):
|
||||
@staticmethod
|
||||
def default():
|
||||
return EnvConfig()
|
||||
|
||||
|
||||
class SingleAgentConfig(BaseModel):
|
||||
agent_class: Optional[Union[Type, str]] = None
|
||||
unique_id: Optional[int] = None
|
||||
topology: Optional[bool] = False
|
||||
node_id: Optional[Union[int, str]] = None
|
||||
state: Optional[Dict[str, Any]] = {}
|
||||
|
||||
|
||||
class FixedAgentConfig(SingleAgentConfig):
|
||||
n: Optional[int] = 1
|
||||
hidden: Optional[bool] = False # Do not count this agent towards total agent count
|
||||
|
||||
@root_validator
|
||||
def validate_all(cls, values):
|
||||
if values.get("unique_id", None) is not None and values.get("n", 1) > 1:
|
||||
raise ValueError(
|
||||
f"An unique_id can only be provided when there is only one agent ({values.get('n')} given)"
|
||||
)
|
||||
return values
|
||||
|
||||
|
||||
class OverrideAgentConfig(FixedAgentConfig):
|
||||
filter: Optional[Dict[str, Any]] = None
|
||||
|
||||
|
||||
class Strategy(Enum):
|
||||
topology = "topology"
|
||||
total = "total"
|
||||
|
||||
|
||||
class AgentDistro(SingleAgentConfig):
|
||||
weight: Optional[float] = 1
|
||||
strategy: Strategy = Strategy.topology
|
||||
|
||||
|
||||
class AgentConfig(SingleAgentConfig):
|
||||
n: Optional[int] = None
|
||||
distribution: Optional[List[AgentDistro]] = None
|
||||
fixed: Optional[List[FixedAgentConfig]] = None
|
||||
override: Optional[List[OverrideAgentConfig]] = None
|
||||
|
||||
@staticmethod
|
||||
def default():
|
||||
return AgentConfig()
|
||||
|
||||
@root_validator
|
||||
def validate_all(cls, values):
|
||||
if "distribution" in values and (
|
||||
"n" not in values and "topology" not in values
|
||||
):
|
||||
raise ValueError(
|
||||
"You need to provide the number of agents or a topology to extract the value from."
|
||||
)
|
||||
return values
|
||||
|
||||
|
||||
class Config(BaseModel, extra=Extra.allow):
|
||||
version: Optional[str] = "1"
|
||||
|
||||
name: str = "Unnamed Simulation"
|
||||
description: Optional[str] = None
|
||||
group: str = None
|
||||
dir_path: Optional[str] = None
|
||||
num_trials: int = 1
|
||||
max_time: float = 100
|
||||
max_steps: int = -1
|
||||
interval: float = 1
|
||||
seed: str = ""
|
||||
dry_run: bool = False
|
||||
|
||||
model_class: Union[Type, str] = environment.Environment
|
||||
model_params: Optional[Dict[str, Any]] = {}
|
||||
|
||||
visualization_params: Optional[Dict[str, Any]] = {}
|
||||
|
||||
@classmethod
|
||||
def from_raw(cls, cfg):
|
||||
if isinstance(cfg, Config):
|
||||
return cfg
|
||||
if cfg.get("version", "1") == "1" and any(
|
||||
k in cfg for k in ["agents", "agent_class", "topology", "environment_class"]
|
||||
):
|
||||
return convert_old(cfg)
|
||||
return Config(**cfg)
|
||||
|
||||
|
||||
def convert_old(old, strict=True):
|
||||
"""
|
||||
Try to convert old style configs into the new format.
|
||||
|
||||
This is still a work in progress and might not work in many cases.
|
||||
"""
|
||||
|
||||
utils.logger.warning(
|
||||
"The old configuration format is deprecated. The converted file MAY NOT yield the right results"
|
||||
)
|
||||
|
||||
new = old.copy()
|
||||
|
||||
network = {}
|
||||
|
||||
if "topology" in old:
|
||||
del new["topology"]
|
||||
network["topology"] = old["topology"]
|
||||
|
||||
if "network_params" in old and old["network_params"]:
|
||||
del new["network_params"]
|
||||
for (k, v) in old["network_params"].items():
|
||||
if k == "path":
|
||||
network["path"] = v
|
||||
else:
|
||||
network.setdefault("params", {})[k] = v
|
||||
|
||||
topology = None
|
||||
if network:
|
||||
topology = network
|
||||
|
||||
agents = {"fixed": [], "distribution": []}
|
||||
|
||||
def updated_agent(agent):
|
||||
"""Convert an agent definition"""
|
||||
newagent = dict(agent)
|
||||
return newagent
|
||||
|
||||
by_weight = []
|
||||
fixed = []
|
||||
override = []
|
||||
|
||||
if "environment_agents" in new:
|
||||
|
||||
for agent in new["environment_agents"]:
|
||||
agent.setdefault("state", {})["group"] = "environment"
|
||||
if "agent_id" in agent:
|
||||
agent["state"]["name"] = agent["agent_id"]
|
||||
del agent["agent_id"]
|
||||
agent["hidden"] = True
|
||||
agent["topology"] = False
|
||||
fixed.append(updated_agent(agent))
|
||||
del new["environment_agents"]
|
||||
|
||||
if "agent_class" in old:
|
||||
del new["agent_class"]
|
||||
agents["agent_class"] = old["agent_class"]
|
||||
|
||||
if "default_state" in old:
|
||||
del new["default_state"]
|
||||
agents["state"] = old["default_state"]
|
||||
|
||||
if "network_agents" in old:
|
||||
agents["topology"] = True
|
||||
|
||||
agents.setdefault("state", {})["group"] = "network"
|
||||
|
||||
for agent in new["network_agents"]:
|
||||
agent = updated_agent(agent)
|
||||
if "agent_id" in agent:
|
||||
agent["state"]["name"] = agent["agent_id"]
|
||||
del agent["agent_id"]
|
||||
fixed.append(agent)
|
||||
else:
|
||||
by_weight.append(agent)
|
||||
del new["network_agents"]
|
||||
|
||||
if "agent_class" in old and (not fixed and not by_weight):
|
||||
agents["topology"] = True
|
||||
by_weight = [{"agent_class": old["agent_class"], "weight": 1}]
|
||||
|
||||
# TODO: translate states properly
|
||||
if "states" in old:
|
||||
del new["states"]
|
||||
states = old["states"]
|
||||
if isinstance(states, dict):
|
||||
states = states.items()
|
||||
else:
|
||||
states = enumerate(states)
|
||||
for (k, v) in states:
|
||||
override.append({"filter": {"node_id": k}, "state": v})
|
||||
|
||||
agents["override"] = override
|
||||
agents["fixed"] = fixed
|
||||
agents["distribution"] = by_weight
|
||||
|
||||
model_params = {}
|
||||
if "environment_params" in new:
|
||||
del new["environment_params"]
|
||||
model_params = dict(old["environment_params"])
|
||||
|
||||
if "environment_class" in old:
|
||||
del new["environment_class"]
|
||||
new["model_class"] = old["environment_class"]
|
||||
|
||||
if "dump" in old:
|
||||
del new["dump"]
|
||||
new["dry_run"] = not old["dump"]
|
||||
|
||||
model_params["topology"] = topology
|
||||
model_params["agents"] = agents
|
||||
|
||||
return Config(version="2", model_params=model_params, **new)
|
||||
def load_config(cfg):
|
||||
return cfg
|
@@ -1,6 +1,17 @@
|
||||
from mesa import DataCollector as MDC
|
||||
|
||||
|
||||
class SoilDataCollector(MDC):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
class SoilCollector(MDC):
|
||||
def __init__(self, model_reporters=None, agent_reporters=None, tables=None, **kwargs):
|
||||
model_reporters = model_reporters or {}
|
||||
agent_reporters = agent_reporters or {}
|
||||
tables = tables or {}
|
||||
if 'agent_count' not in model_reporters:
|
||||
model_reporters['agent_count'] = lambda m: m.schedule.get_agent_count()
|
||||
if 'state_id' not in agent_reporters:
|
||||
agent_reporters['agent_id'] = lambda agent: getattr(agent, 'state_id', None)
|
||||
|
||||
super().__init__(model_reporters=model_reporters,
|
||||
agent_reporters=agent_reporters,
|
||||
tables=tables,
|
||||
**kwargs)
|
||||
|
@@ -8,6 +8,7 @@ from textwrap import indent
|
||||
from functools import wraps
|
||||
|
||||
from .agents import FSM, MetaFSM
|
||||
from mesa import Model, Agent
|
||||
|
||||
|
||||
def wrapcmd(func):
|
||||
@@ -15,14 +16,22 @@ def wrapcmd(func):
|
||||
def wrapper(self, arg: str, temporary=False):
|
||||
sys.settrace(self.trace_dispatch)
|
||||
|
||||
lastself = self
|
||||
known = globals()
|
||||
known.update(self.curframe.f_globals)
|
||||
known.update(self.curframe.f_locals)
|
||||
known["agent"] = known.get("self", None)
|
||||
known["model"] = known.get("self", {}).get("model")
|
||||
known["attrs"] = arg.strip().split()
|
||||
|
||||
exec(func.__code__, known, known)
|
||||
this = known.get("self", None)
|
||||
|
||||
if isinstance(this, Model):
|
||||
known["model"] = this
|
||||
elif isinstance(this, Agent):
|
||||
known["agent"] = this
|
||||
known["model"] = this.model
|
||||
|
||||
known["self"] = lastself
|
||||
return exec(func.__code__, known, known)
|
||||
|
||||
return wrapper
|
||||
|
||||
@@ -57,6 +66,7 @@ class Debug(pdb.Pdb):
|
||||
do_sl = do_soil_list
|
||||
|
||||
def do_continue_state(self, arg):
|
||||
"""Continue until next time this state is reached"""
|
||||
self.do_break_state(arg, temporary=True)
|
||||
return self.do_continue("")
|
||||
|
||||
@@ -80,6 +90,49 @@ class Debug(pdb.Pdb):
|
||||
|
||||
do_aa = do_soil_agent
|
||||
|
||||
def do_break_step(self, arg: str):
|
||||
"""
|
||||
Break before the next step.
|
||||
"""
|
||||
try:
|
||||
known = globals()
|
||||
known.update(self.curframe.f_globals)
|
||||
known.update(self.curframe.f_locals)
|
||||
func = getattr(known["model"], "step")
|
||||
except AttributeError as ex:
|
||||
self.error(f"The model does not have a step function: {ex}")
|
||||
return
|
||||
if hasattr(func, "__func__"):
|
||||
func = func.__func__
|
||||
|
||||
code = func.__code__
|
||||
# use co_name to identify the bkpt (function names
|
||||
# could be aliased, but co_name is invariant)
|
||||
funcname = code.co_name
|
||||
lineno = code.co_firstlineno
|
||||
filename = code.co_filename
|
||||
|
||||
# Check for reasonable breakpoint
|
||||
line = self.checkline(filename, lineno)
|
||||
if not line:
|
||||
raise ValueError("no line found")
|
||||
# now set the break point
|
||||
|
||||
existing = self.get_breaks(filename, line)
|
||||
if existing:
|
||||
self.message("Breakpoint already exists at %s:%d" % (filename, line))
|
||||
return
|
||||
cond = f"self.schedule.steps > {model.schedule.steps}"
|
||||
err = self.set_break(filename, line, True, cond, funcname)
|
||||
if err:
|
||||
self.error(err)
|
||||
else:
|
||||
bp = self.get_breaks(filename, line)[-1]
|
||||
self.message("Breakpoint %d at %s:%d" % (bp.number, bp.file, bp.line))
|
||||
return self.do_continue("")
|
||||
|
||||
do_bstep = do_break_step
|
||||
|
||||
def do_break_state(self, arg: str, instances=None, temporary=False):
|
||||
"""
|
||||
Break before a specified state is stepped into.
|
||||
|
6
soil/decorators.py
Normal file
6
soil/decorators.py
Normal file
@@ -0,0 +1,6 @@
|
||||
def report(f: property):
|
||||
if isinstance(f, property):
|
||||
setattr(f.fget, "add_to_report", True)
|
||||
else:
|
||||
setattr(f, "add_to_report", True)
|
||||
return f
|
@@ -6,21 +6,21 @@ import math
|
||||
import logging
|
||||
import inspect
|
||||
|
||||
from typing import Any, Dict, Optional, Union
|
||||
from typing import Any, Callable, Dict, Optional, Union, List, Type
|
||||
from collections import namedtuple
|
||||
from time import time as current_time
|
||||
from copy import deepcopy
|
||||
from networkx.readwrite import json_graph
|
||||
|
||||
|
||||
import networkx as nx
|
||||
|
||||
from mesa import Model
|
||||
from mesa.datacollection import DataCollector
|
||||
from mesa import Model, Agent
|
||||
|
||||
from . import agents as agentmod, config, serialization, utils, time, network, events
|
||||
from . import agents as agentmod, datacollection, serialization, utils, time, network, events
|
||||
|
||||
|
||||
# TODO: maybe add metaclass to read attributes of a model
|
||||
|
||||
class BaseEnvironment(Model):
|
||||
"""
|
||||
The environment is key in a simulation. It controls how agents interact,
|
||||
@@ -34,100 +34,83 @@ class BaseEnvironment(Model):
|
||||
:meth:`soil.environment.Environment.get` method.
|
||||
"""
|
||||
|
||||
def __new__(cls,
|
||||
*args: Any,
|
||||
seed="default",
|
||||
dir_path=None,
|
||||
collector_class: type = datacollection.SoilCollector,
|
||||
agent_reporters: Optional[Any] = None,
|
||||
model_reporters: Optional[Any] = None,
|
||||
tables: Optional[Any] = None,
|
||||
**kwargs: Any) -> Any:
|
||||
"""Create a new model with a default seed value"""
|
||||
self = super().__new__(cls, *args, seed=seed, **kwargs)
|
||||
self.dir_path = dir_path or os.getcwd()
|
||||
collector_class = serialization.deserialize(collector_class)
|
||||
self.datacollector = collector_class(
|
||||
model_reporters=model_reporters,
|
||||
agent_reporters=agent_reporters,
|
||||
tables=tables,
|
||||
)
|
||||
for k in dir(cls):
|
||||
v = getattr(cls, k)
|
||||
if isinstance(v, property):
|
||||
v = v.fget
|
||||
if getattr(v, "add_to_report", False):
|
||||
self.add_model_reporter(k, v)
|
||||
|
||||
return self
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
id="unnamed_env",
|
||||
seed="default",
|
||||
schedule=None,
|
||||
dir_path=None,
|
||||
schedule_class=time.TimedActivation,
|
||||
interval=1,
|
||||
agent_class=None,
|
||||
agents: [tuple[type, Dict[str, Any]]] = {},
|
||||
agents: Optional[Dict] = None,
|
||||
collector_class: type = datacollection.SoilCollector,
|
||||
agent_reporters: Optional[Any] = None,
|
||||
model_reporters: Optional[Any] = None,
|
||||
tables: Optional[Any] = None,
|
||||
init: bool = True,
|
||||
**env_params,
|
||||
):
|
||||
|
||||
super().__init__(seed=seed)
|
||||
self.env_params = env_params or {}
|
||||
super().__init__()
|
||||
|
||||
self.current_id = -1
|
||||
|
||||
self.id = id
|
||||
|
||||
self.dir_path = dir_path or os.getcwd()
|
||||
|
||||
if schedule is None:
|
||||
schedule = time.TimedActivation(self)
|
||||
self.schedule = schedule
|
||||
|
||||
self.agent_class = agent_class or agentmod.BaseAgent
|
||||
if schedule_class is None:
|
||||
schedule_class = time.TimedActivation
|
||||
else:
|
||||
schedule_class = serialization.deserialize(schedule_class)
|
||||
|
||||
self.interval = interval
|
||||
self.init_agents(agents)
|
||||
self.schedule = schedule_class(self)
|
||||
|
||||
self.logger = utils.logger.getChild(self.id)
|
||||
|
||||
self.datacollector = DataCollector(
|
||||
model_reporters=model_reporters,
|
||||
agent_reporters=agent_reporters,
|
||||
tables=tables,
|
||||
)
|
||||
for (k, v) in env_params.items():
|
||||
self[k] = v
|
||||
|
||||
def _agent_from_dict(self, agent):
|
||||
"""
|
||||
Translate an agent dictionary into an agent
|
||||
"""
|
||||
agent = dict(**agent)
|
||||
cls = agent.pop("agent_class", None) or self.agent_class
|
||||
unique_id = agent.pop("unique_id", None)
|
||||
if unique_id is None:
|
||||
unique_id = self.next_id()
|
||||
if agents:
|
||||
self.add_agents(**agents)
|
||||
if init:
|
||||
self.init()
|
||||
|
||||
return serialization.deserialize(cls)(unique_id=unique_id, model=self, **agent)
|
||||
|
||||
def init_agents(self, agents: Union[config.AgentConfig, [Dict[str, Any]]] = {}):
|
||||
"""
|
||||
Initialize the agents in the model from either a `soil.config.AgentConfig` or a list of
|
||||
dictionaries that each describes an agent.
|
||||
|
||||
If given a list of dictionaries, an agent will be created for each dictionary. The agent
|
||||
class can be specified through the `agent_class` key. The rest of the items will be used
|
||||
as parameters to the agent.
|
||||
"""
|
||||
if not agents:
|
||||
return
|
||||
|
||||
lst = agents
|
||||
override = []
|
||||
if not isinstance(lst, list):
|
||||
if not isinstance(agents, config.AgentConfig):
|
||||
lst = config.AgentConfig(**agents)
|
||||
if lst.override:
|
||||
override = lst.override
|
||||
lst = self._agent_dict_from_config(lst)
|
||||
|
||||
# TODO: check override is working again. It cannot (easily) be part of agents.from_config anymore,
|
||||
# because it needs attribute such as unique_id, which are only present after init
|
||||
new_agents = [self._agent_from_dict(agent) for agent in lst]
|
||||
|
||||
for a in new_agents:
|
||||
self.schedule.add(a)
|
||||
|
||||
for rule in override:
|
||||
for agent in agentmod.filter_agents(self.schedule._agents, **rule.filter):
|
||||
for attr, value in rule.state.items():
|
||||
setattr(agent, attr, value)
|
||||
|
||||
def _agent_dict_from_config(self, cfg):
|
||||
return agentmod.from_config(cfg, random=self.random)
|
||||
def init(self):
|
||||
pass
|
||||
|
||||
@property
|
||||
def agents(self):
|
||||
return agentmod.AgentView(self.schedule._agents)
|
||||
|
||||
def find_one(self, *args, **kwargs):
|
||||
def agent(self, *args, **kwargs):
|
||||
return agentmod.AgentView(self.schedule._agents).one(*args, **kwargs)
|
||||
|
||||
def count_agents(self, *args, **kwargs):
|
||||
@@ -140,17 +123,34 @@ class BaseEnvironment(Model):
|
||||
raise Exception(
|
||||
"The environment has not been scheduled, so it has no sense of time"
|
||||
)
|
||||
def init_agents(self):
|
||||
pass
|
||||
|
||||
def add_agent(self, unique_id=None, **kwargs):
|
||||
def add_agent(self, agent_class, unique_id=None, **agent):
|
||||
if unique_id is None:
|
||||
unique_id = self.next_id()
|
||||
|
||||
kwargs["unique_id"] = unique_id
|
||||
a = self._agent_from_dict(kwargs)
|
||||
agent["unique_id"] = unique_id
|
||||
|
||||
agent = dict(**agent)
|
||||
unique_id = agent.pop("unique_id", None)
|
||||
if unique_id is None:
|
||||
unique_id = self.next_id()
|
||||
|
||||
a = serialization.deserialize(agent_class)(unique_id=unique_id, model=self, **agent)
|
||||
|
||||
self.schedule.add(a)
|
||||
return a
|
||||
|
||||
def add_agents(self, agent_classes: List[type], k, weights: Optional[List[float]] = None, **kwargs):
|
||||
if isinstance(agent_classes, type):
|
||||
agent_classes = [agent_classes]
|
||||
if weights is None:
|
||||
weights = [1] * len(agent_classes)
|
||||
|
||||
for cls in self.random.choices(agent_classes, weights=weights, k=k):
|
||||
self.add_agent(agent_class=cls, **kwargs)
|
||||
|
||||
def log(self, message, *args, level=logging.INFO, **kwargs):
|
||||
if not self.logger.isEnabledFor(level):
|
||||
return
|
||||
@@ -168,31 +168,56 @@ class BaseEnvironment(Model):
|
||||
Advance one step in the simulation, and update the data collection and scheduler appropriately
|
||||
"""
|
||||
super().step()
|
||||
self.logger.info(
|
||||
f"--- Step: {self.schedule.steps:^5} - Time: {self.now:^5} ---"
|
||||
)
|
||||
self.schedule.step()
|
||||
self.datacollector.collect(self)
|
||||
|
||||
def __contains__(self, key):
|
||||
return key in self.env_params
|
||||
msg = "Model data:\n"
|
||||
max_width = max(len(k) for k in self.datacollector.model_vars.keys())
|
||||
for (k, v) in self.datacollector.model_vars.items():
|
||||
msg += f"\t{k:<{max_width}}: {v[-1]:>6}\n"
|
||||
self.logger.info(f"--- Steps: {self.schedule.steps:^5} - Time: {self.now:^5} --- " + msg)
|
||||
|
||||
def get(self, key, default=None):
|
||||
"""
|
||||
Get the value of an environment attribute.
|
||||
Return `default` if the value is not set.
|
||||
"""
|
||||
return self.env_params.get(key, default)
|
||||
def add_model_reporter(self, name, func=None):
|
||||
if not func:
|
||||
func = lambda env: getattr(env, name)
|
||||
self.datacollector._new_model_reporter(name, func)
|
||||
|
||||
def add_agent_reporter(self, name, agent_type=None):
|
||||
if agent_type:
|
||||
reporter = lambda a: getattr(a, name) if isinstance(a, agent_type) else None
|
||||
else:
|
||||
reporter = name
|
||||
self.datacollector._new_agent_reporter(name, reporter)
|
||||
|
||||
def __getitem__(self, key):
|
||||
return self.env_params.get(key)
|
||||
try:
|
||||
return getattr(self, key)
|
||||
except AttributeError:
|
||||
raise KeyError(f"key {key} not found in environment")
|
||||
|
||||
def __delitem__(self, key):
|
||||
return delattr(self, key)
|
||||
|
||||
def __contains__(self, key):
|
||||
return hasattr(self, key)
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
return self.env_params.__setitem__(key, value)
|
||||
setattr(self, key, value)
|
||||
|
||||
def __str__(self):
|
||||
return str(self.env_params)
|
||||
return str(dict(self))
|
||||
|
||||
def __len__(self):
|
||||
return sum(1 for n in self.keys())
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.agents())
|
||||
|
||||
def get(self, key, default=None):
|
||||
return self[key] if key in self else default
|
||||
|
||||
def keys(self):
|
||||
return (k for k in self.__dict__ if k[0] != "_")
|
||||
|
||||
class NetworkEnvironment(BaseEnvironment):
|
||||
"""
|
||||
@@ -200,69 +225,71 @@ class NetworkEnvironment(BaseEnvironment):
|
||||
and methods to associate agents to nodes and vice versa.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, *args, topology: Union[config.NetConfig, nx.Graph] = None, **kwargs
|
||||
):
|
||||
agents = kwargs.pop("agents", None)
|
||||
super().__init__(*args, agents=None, **kwargs)
|
||||
def __init__(self,
|
||||
*args,
|
||||
topology: Optional[Union[nx.Graph, str]] = None,
|
||||
agent_class: Optional[Type[agentmod.Agent]] = None,
|
||||
network_generator: Optional[Callable] = None,
|
||||
network_params: Optional[Dict] = {},
|
||||
init=True,
|
||||
**kwargs):
|
||||
self.topology = topology
|
||||
self.network_generator = network_generator
|
||||
self.network_params = network_params
|
||||
if topology or network_params or network_generator:
|
||||
self.create_network(topology, generator=network_generator, **network_params)
|
||||
else:
|
||||
self.G = nx.Graph()
|
||||
super().__init__(*args, **kwargs, init=False)
|
||||
|
||||
self._set_topology(topology)
|
||||
self.agent_class = agent_class
|
||||
if agent_class:
|
||||
self.agent_class = serialization.deserialize(agent_class)
|
||||
if self.agent_class:
|
||||
self.populate_network(self.agent_class)
|
||||
self._check_agent_nodes()
|
||||
if init:
|
||||
self.init()
|
||||
|
||||
self.init_agents(agents)
|
||||
def add_agent(self, agent_class, *args, node_id=None, topology=None, **kwargs):
|
||||
if node_id is None and topology is None:
|
||||
return super().add_agent(agent_class, *args, **kwargs)
|
||||
try:
|
||||
a = super().add_agent(agent_class, *args, node_id=node_id, **kwargs)
|
||||
except TypeError:
|
||||
self.logger.warning(f"Agent constructor for {agent_class} does not have a node_id attribute. Might be a bug.")
|
||||
a = super().add_agent(agent_class, *args, **kwargs)
|
||||
self.G.nodes[node_id]["agent"] = a
|
||||
return a
|
||||
|
||||
def add_agents(self, *args, k=None, **kwargs):
|
||||
if not k and not self.G:
|
||||
raise ValueError("Cannot add agents to an empty network")
|
||||
super().add_agents(*args, k=k or len(self.G), **kwargs)
|
||||
|
||||
def create_network(self, topology=None, generator=None, path=None, **network_params):
|
||||
if topology is not None:
|
||||
topology = network.from_topology(topology, dir_path=self.dir_path)
|
||||
elif path is not None:
|
||||
topology = network.from_topology(path, dir_path=self.dir_path)
|
||||
elif generator is not None:
|
||||
topology = network.from_params(generator=generator, dir_path=self.dir_path, **network_params)
|
||||
else:
|
||||
raise ValueError("topology must be a networkx.Graph or a string, or network_generator must be provided")
|
||||
self.G = topology
|
||||
|
||||
def init_agents(self, *args, **kwargs):
|
||||
"""Initialize the agents from a"""
|
||||
super().init_agents(*args, **kwargs)
|
||||
for agent in self.schedule._agents.values():
|
||||
if hasattr(agent, "node_id"):
|
||||
self._init_node(agent)
|
||||
|
||||
def _init_node(self, agent):
|
||||
"""
|
||||
Make sure the node for a given agent has the proper attributes.
|
||||
"""
|
||||
self.G.nodes[agent.node_id]["agent"] = agent
|
||||
|
||||
def _agent_dict_from_config(self, cfg):
|
||||
return agentmod.from_config(cfg, topology=self.G, random=self.random)
|
||||
|
||||
def _agent_from_dict(self, agent, unique_id=None):
|
||||
agent = dict(agent)
|
||||
|
||||
if not agent.get("topology", False):
|
||||
return super()._agent_from_dict(agent)
|
||||
|
||||
if unique_id is None:
|
||||
unique_id = self.next_id()
|
||||
node_id = agent.get("node_id", None)
|
||||
if node_id is None:
|
||||
node_id = network.find_unassigned(self.G, random=self.random)
|
||||
self.G.nodes[node_id]["agent"] = None
|
||||
agent["node_id"] = node_id
|
||||
agent["unique_id"] = unique_id
|
||||
agent["topology"] = self.G
|
||||
node_attrs = self.G.nodes[node_id]
|
||||
node_attrs.update(agent)
|
||||
agent = node_attrs
|
||||
|
||||
a = super()._agent_from_dict(agent)
|
||||
self._init_node(a)
|
||||
|
||||
return a
|
||||
|
||||
def _set_topology(self, cfg=None, dir_path=None):
|
||||
if cfg is None:
|
||||
cfg = nx.Graph()
|
||||
elif not isinstance(cfg, nx.Graph):
|
||||
cfg = network.from_config(cfg, dir_path=dir_path or self.dir_path)
|
||||
|
||||
self.G = cfg
|
||||
|
||||
@property
|
||||
def network_agents(self):
|
||||
for a in self.schedule._agents:
|
||||
if isinstance(a, agentmod.NetworkAgent):
|
||||
yield a
|
||||
"""Return agents still alive and assigned to a node in the network."""
|
||||
for (id, data) in self.G.nodes(data=True):
|
||||
if "agent" in data:
|
||||
agent = data["agent"]
|
||||
if getattr(agent, "alive", True):
|
||||
yield agent
|
||||
|
||||
def add_node(self, agent_class, unique_id=None, node_id=None, **kwargs):
|
||||
if unique_id is None:
|
||||
@@ -278,7 +305,6 @@ class NetworkEnvironment(BaseEnvironment):
|
||||
self.G.add_node(node_id)
|
||||
|
||||
assert "agent" not in self.G.nodes[node_id]
|
||||
self.G.nodes[node_id]["agent"] = None # Reserve
|
||||
|
||||
a = self.add_agent(
|
||||
unique_id=unique_id,
|
||||
@@ -290,35 +316,80 @@ class NetworkEnvironment(BaseEnvironment):
|
||||
a["visible"] = True
|
||||
return a
|
||||
|
||||
def add_agent(self, *args, **kwargs):
|
||||
a = super().add_agent(*args, **kwargs)
|
||||
if "node_id" in a:
|
||||
assert self.G.nodes[a.node_id]["agent"] == a
|
||||
return a
|
||||
def _check_agent_nodes(self):
|
||||
"""
|
||||
Detect nodes that have agents assigned to them.
|
||||
"""
|
||||
for (id, data) in self.G.nodes(data=True):
|
||||
if "agent_id" in data:
|
||||
agent = self.agents(data["agent_id"])
|
||||
self.G.nodes[id]["agent"] = agent
|
||||
assert not getattr(agent, "node_id", None) or agent.node_id == id
|
||||
agent.node_id = id
|
||||
for agent in self.agents():
|
||||
if hasattr(agent, "node_id"):
|
||||
node_id = agent["node_id"]
|
||||
if node_id not in self.G.nodes:
|
||||
raise ValueError(f"Agent {agent} is assigned to node {agent.node_id} which is not in the network")
|
||||
node = self.G.nodes[node_id]
|
||||
if node.get("agent") is not None and node["agent"] != agent:
|
||||
raise ValueError(f"Node {node_id} already has a different agent assigned to it")
|
||||
self.G.nodes[node_id]["agent"] = agent
|
||||
|
||||
def add_agents(self, agent_classes: List[type], k=None, weights: Optional[List[float]] = None, **kwargs):
|
||||
if k is None:
|
||||
k = len(self.G)
|
||||
if not k:
|
||||
raise ValueError("Cannot add agents to an empty network")
|
||||
super().add_agents(agent_classes, k=k, weights=weights, **kwargs)
|
||||
|
||||
def agent_for_node_id(self, node_id):
|
||||
return self.G.nodes[node_id].get("agent")
|
||||
|
||||
def populate_network(self, agent_class, weights=None, **agent_params):
|
||||
if not hasattr(agent_class, "len"):
|
||||
def populate_network(self, agent_class: List[Model], weights: List[float] = None, **agent_params):
|
||||
if isinstance(agent_class, type):
|
||||
agent_class = [agent_class]
|
||||
weights = None
|
||||
for (node_id, node) in self.G.nodes(data=True):
|
||||
else:
|
||||
agent_class = list(agent_class)
|
||||
if not weights:
|
||||
weights = [1] * len(agent_class)
|
||||
assert len(self.G)
|
||||
classes = self.random.choices(agent_class, weights, k=len(self.G))
|
||||
toadd = []
|
||||
for (cls, (node_id, node)) in zip(classes, self.G.nodes(data=True)):
|
||||
if "agent" in node:
|
||||
continue
|
||||
a_class = self.random.choices(agent_class, weights)[0]
|
||||
self.add_agent(node_id=node_id, agent_class=a_class, **agent_params)
|
||||
node["agent"] = None # Reserve
|
||||
toadd.append(dict(node_id=node_id, topology=self.G, agent_class=cls, **agent_params))
|
||||
for d in toadd:
|
||||
a = self.add_agent(**d)
|
||||
self.G.nodes[d["node_id"]]["agent"] = a
|
||||
assert all("agent" in node for (_, node) in self.G.nodes(data=True))
|
||||
assert len(list(self.network_agents))
|
||||
|
||||
|
||||
Environment = NetworkEnvironment
|
||||
|
||||
|
||||
class EventedEnvironment(Environment):
|
||||
def broadcast(self, msg, sender, expiration=None, ttl=None, **kwargs):
|
||||
class EventedEnvironment(BaseEnvironment):
|
||||
def broadcast(self, msg, sender=None, expiration=None, ttl=None, **kwargs):
|
||||
for agent in self.agents(**kwargs):
|
||||
self.logger.info(f'Telling {repr(agent)}: {msg} ttl={ttl}')
|
||||
if agent == sender:
|
||||
continue
|
||||
self.logger.info(f"Telling {repr(agent)}: {msg} ttl={ttl}")
|
||||
try:
|
||||
agent._inbox.append(events.Tell(payload=msg, sender=sender, expiration=expiration if ttl is None else self.now+ttl))
|
||||
inbox = agent._inbox
|
||||
except AttributeError:
|
||||
self.info(f'Agent {agent.unique_id} cannot receive events')
|
||||
self.logger.info(
|
||||
f"Agent {agent.unique_id} cannot receive events because it does not have an inbox"
|
||||
)
|
||||
continue
|
||||
# Allow for AttributeError exceptions in this part of the code
|
||||
inbox.append(
|
||||
events.Tell(
|
||||
payload=msg,
|
||||
sender=sender,
|
||||
expiration=expiration if ttl is None else self.now + ttl,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class Environment(NetworkEnvironment, EventedEnvironment):
|
||||
"""Default environment class, has both network and event capabilities"""
|
||||
|
@@ -1,38 +1,51 @@
|
||||
from .time import Cond
|
||||
from .time import BaseCond
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
class Event:
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Message:
|
||||
payload: Any
|
||||
sender: Any = None
|
||||
expiration: float = None
|
||||
timestamp: float = None
|
||||
id: int = field(default_factory=uuid4)
|
||||
|
||||
def expired(self, when):
|
||||
return self.expiration is not None and self.expiration < when
|
||||
|
||||
|
||||
class Reply(Message):
|
||||
source: Message
|
||||
|
||||
|
||||
class ReplyCond(BaseCond):
|
||||
def __init__(self, ask, *args, **kwargs):
|
||||
self._ask = ask
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def ready(self, agent, time):
|
||||
return self._ask.reply is not None or self._ask.expired(time)
|
||||
|
||||
def return_value(self, agent):
|
||||
if self._ask.expired(agent.now):
|
||||
raise TimedOut()
|
||||
return self._ask.reply
|
||||
|
||||
def __repr__(self):
|
||||
return f"ReplyCond({self._ask.id})"
|
||||
|
||||
|
||||
class Ask(Message):
|
||||
reply: Message = None
|
||||
|
||||
def replied(self, expiration=None):
|
||||
def ready(agent):
|
||||
return self.reply is not None or agent.now > expiration
|
||||
|
||||
def value(agent):
|
||||
if agent.now > expiration:
|
||||
raise TimedOut(f'No answer received for {self}')
|
||||
return self.reply
|
||||
|
||||
return Cond(func=ready, return_func=value)
|
||||
return ReplyCond(self)
|
||||
|
||||
|
||||
class Tell(Message):
|
||||
|
@@ -38,7 +38,7 @@ class DryRunner(BytesIO):
|
||||
except UnicodeDecodeError:
|
||||
pass
|
||||
logger.info(
|
||||
"**Not** written to {} (dry run mode):\n\n{}\n\n".format(
|
||||
"**Not** written to {} (no_dump mode):\n\n{}\n\n".format(
|
||||
self.__fname, content
|
||||
)
|
||||
)
|
||||
@@ -51,12 +51,12 @@ class Exporter:
|
||||
if you don't plan to implement all the methods.
|
||||
"""
|
||||
|
||||
def __init__(self, simulation, outdir=None, dry_run=None, copy_to=None):
|
||||
def __init__(self, simulation, outdir=None, dump=True, copy_to=None):
|
||||
self.simulation = simulation
|
||||
outdir = outdir or os.path.join(os.getcwd(), "soil_output")
|
||||
self.outdir = os.path.join(outdir, simulation.group or "", simulation.name)
|
||||
self.dry_run = dry_run
|
||||
if copy_to is None and dry_run:
|
||||
self.dump = dump
|
||||
if copy_to is None and not dump:
|
||||
copy_to = sys.stdout
|
||||
self.copy_to = copy_to
|
||||
|
||||
@@ -77,7 +77,7 @@ class Exporter:
|
||||
pass
|
||||
|
||||
def output(self, f, mode="w", **kwargs):
|
||||
if self.dry_run:
|
||||
if not self.dump:
|
||||
f = DryRunner(f, copy_to=self.copy_to)
|
||||
else:
|
||||
try:
|
||||
@@ -104,22 +104,20 @@ def get_dc_dfs(dc, trial_id=None):
|
||||
yield from dfs.items()
|
||||
|
||||
|
||||
class default(Exporter):
|
||||
"""Default exporter. Writes sqlite results, as well as the simulation YAML"""
|
||||
class SQLite(Exporter):
|
||||
"""Writes sqlite results"""
|
||||
|
||||
def sim_start(self):
|
||||
if self.dry_run:
|
||||
logger.info("NOT dumping results")
|
||||
if not self.dump:
|
||||
logger.debug("NOT dumping results")
|
||||
return
|
||||
logger.info("Dumping results to %s", self.outdir)
|
||||
with self.output(self.simulation.name + ".dumped.yml") as f:
|
||||
f.write(self.simulation.to_yaml())
|
||||
self.dbpath = os.path.join(self.outdir, f"{self.simulation.name}.sqlite")
|
||||
logger.info("Dumping results to %s", self.dbpath)
|
||||
try_backup(self.dbpath, remove=True)
|
||||
|
||||
def trial_end(self, env):
|
||||
if self.dry_run:
|
||||
logger.info("Running in DRY_RUN mode, the database will NOT be created")
|
||||
if not self.dump:
|
||||
logger.info("Running in NO DUMP mode, the database will NOT be created")
|
||||
return
|
||||
|
||||
with timer(
|
||||
@@ -131,7 +129,6 @@ class default(Exporter):
|
||||
for (t, df) in self.get_dfs(env):
|
||||
df.to_sql(t, con=engine, if_exists="append")
|
||||
|
||||
|
||||
class csv(Exporter):
|
||||
|
||||
"""Export the state of each environment (and its agents) in a separate CSV file"""
|
||||
@@ -150,8 +147,8 @@ class csv(Exporter):
|
||||
# TODO: reimplement GEXF exporting without history
|
||||
class gexf(Exporter):
|
||||
def trial_end(self, env):
|
||||
if self.dry_run:
|
||||
logger.info("Not dumping GEXF in dry_run mode")
|
||||
if not self.dump:
|
||||
logger.info("Not dumping GEXF (NO_DUMP mode)")
|
||||
return
|
||||
|
||||
with timer(
|
||||
@@ -199,15 +196,61 @@ class summary(Exporter):
|
||||
"""Print a summary of each trial to sys.stdout"""
|
||||
|
||||
def trial_end(self, env):
|
||||
msg = ""
|
||||
for (t, df) in self.get_dfs(env):
|
||||
if not len(df):
|
||||
continue
|
||||
msg = indent(str(df.describe()), " ")
|
||||
logger.info(
|
||||
dedent(
|
||||
f"""
|
||||
tabs = "\t" * 2
|
||||
description = indent(str(df.describe()), tabs)
|
||||
last_line = indent(str(df.iloc[-1:]), tabs)
|
||||
# value_counts = indent(str(df.value_counts()), tabs)
|
||||
value_counts = indent(str(df.apply(lambda x: x.value_counts()).T.stack()), tabs)
|
||||
|
||||
msg += dedent("""
|
||||
Dataframe {t}:
|
||||
"""
|
||||
)
|
||||
+ msg
|
||||
)
|
||||
Last line: :
|
||||
{last_line}
|
||||
|
||||
Description:
|
||||
{description}
|
||||
|
||||
Value counts:
|
||||
{value_counts}
|
||||
|
||||
""").format(**locals())
|
||||
logger.info(msg)
|
||||
|
||||
class YAML(Exporter):
|
||||
"""Writes the configuration of the simulation to a YAML file"""
|
||||
|
||||
def sim_start(self):
|
||||
if not self.dump:
|
||||
logger.debug("NOT dumping results")
|
||||
return
|
||||
with self.output(self.simulation.name + ".dumped.yml") as f:
|
||||
logger.info(f"Dumping simulation configuration to {self.outdir}")
|
||||
f.write(self.simulation.to_yaml())
|
||||
|
||||
class default(Exporter):
|
||||
"""Default exporter. Writes sqlite results, as well as the simulation YAML"""
|
||||
|
||||
def __init__(self, *args, exporter_cls=[], **kwargs):
|
||||
exporter_cls = exporter_cls or [YAML, SQLite]
|
||||
self.inner = [cls(*args, **kwargs) for cls in exporter_cls]
|
||||
|
||||
def sim_start(self):
|
||||
for exporter in self.inner:
|
||||
exporter.sim_start()
|
||||
|
||||
def sim_end(self):
|
||||
for exporter in self.inner:
|
||||
exporter.sim_end()
|
||||
|
||||
def trial_start(self, env):
|
||||
for exporter in self.inner:
|
||||
exporter.trial_start(env)
|
||||
|
||||
|
||||
def trial_end(self, env):
|
||||
for exporter in self.inner:
|
||||
exporter.trial_end(env)
|
@@ -10,47 +10,47 @@ import networkx as nx
|
||||
from . import config, serialization, basestring
|
||||
|
||||
|
||||
def from_config(cfg: config.NetConfig, dir_path: str = None):
|
||||
if not isinstance(cfg, config.NetConfig):
|
||||
cfg = config.NetConfig(**cfg)
|
||||
def from_topology(topology, dir_path: str = None):
|
||||
if topology is None:
|
||||
return nx.Graph()
|
||||
if isinstance(topology, nx.Graph):
|
||||
return topology
|
||||
|
||||
if cfg.path:
|
||||
path = cfg.path
|
||||
if dir_path and not os.path.isabs(path):
|
||||
path = os.path.join(dir_path, path)
|
||||
extension = os.path.splitext(path)[1][1:]
|
||||
kwargs = {}
|
||||
if extension == "gexf":
|
||||
kwargs["version"] = "1.2draft"
|
||||
kwargs["node_type"] = int
|
||||
# If it's a dict, assume it's a node-link graph
|
||||
if isinstance(topology, dict):
|
||||
try:
|
||||
method = getattr(nx.readwrite, "read_" + extension)
|
||||
except AttributeError:
|
||||
raise AttributeError("Unknown format")
|
||||
return method(path, **kwargs)
|
||||
return nx.json_graph.node_link_graph(topology)
|
||||
except Exception as ex:
|
||||
raise ValueError("Unknown topology format")
|
||||
|
||||
# Otherwise, treat like a path
|
||||
path = topology
|
||||
if dir_path and not os.path.isabs(path):
|
||||
path = os.path.join(dir_path, path)
|
||||
extension = os.path.splitext(path)[1][1:]
|
||||
kwargs = {}
|
||||
if extension == "gexf":
|
||||
kwargs["version"] = "1.2draft"
|
||||
kwargs["node_type"] = int
|
||||
try:
|
||||
method = getattr(nx.readwrite, "read_" + extension)
|
||||
except AttributeError:
|
||||
raise AttributeError("Unknown format")
|
||||
return method(path, **kwargs)
|
||||
|
||||
if cfg.params:
|
||||
net_args = cfg.params.dict()
|
||||
net_gen = net_args.pop("generator")
|
||||
|
||||
if dir_path not in sys.path:
|
||||
sys.path.append(dir_path)
|
||||
def from_params(generator, dir_path: str = None, **params):
|
||||
|
||||
method = serialization.deserializer(
|
||||
net_gen,
|
||||
known_modules=[
|
||||
"networkx.generators",
|
||||
],
|
||||
)
|
||||
return method(**net_args)
|
||||
if dir_path not in sys.path:
|
||||
sys.path.append(dir_path)
|
||||
|
||||
if isinstance(cfg.fixed, config.Topology):
|
||||
cfg = cfg.fixed.dict()
|
||||
|
||||
if isinstance(cfg, str) or isinstance(cfg, dict):
|
||||
return nx.json_graph.node_link_graph(cfg)
|
||||
|
||||
return nx.Graph()
|
||||
method = serialization.deserializer(
|
||||
generator,
|
||||
known_modules=[
|
||||
"networkx.generators",
|
||||
],
|
||||
)
|
||||
return method(**params)
|
||||
|
||||
|
||||
def find_unassigned(G, shuffle=False, random=random):
|
||||
@@ -59,7 +59,6 @@ def find_unassigned(G, shuffle=False, random=random):
|
||||
|
||||
If node_id is None, a node without an agent_id will be found.
|
||||
"""
|
||||
# TODO: test
|
||||
candidates = list(G.nodes(data=True))
|
||||
if shuffle:
|
||||
random.shuffle(candidates)
|
||||
|
32
soil/parameters.py
Normal file
32
soil/parameters.py
Normal file
@@ -0,0 +1,32 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing_extensions import Annotated
|
||||
import annotated_types
|
||||
from typing import *
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
class Parameter:
|
||||
pass
|
||||
|
||||
|
||||
def floatrange(
|
||||
*,
|
||||
gt: Optional[float] = None,
|
||||
ge: Optional[float] = None,
|
||||
lt: Optional[float] = None,
|
||||
le: Optional[float] = None,
|
||||
multiple_of: Optional[float] = None,
|
||||
) -> type[float]:
|
||||
return Annotated[
|
||||
float,
|
||||
annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le),
|
||||
annotated_types.MultipleOf(multiple_of) if multiple_of is not None else None,
|
||||
]
|
||||
|
||||
function = Annotated[Callable, Parameter]
|
||||
Integer = Annotated[int, Parameter]
|
||||
Float = Annotated[float, Parameter]
|
||||
|
||||
|
||||
probability = floatrange(ge=0, le=1)
|
@@ -4,14 +4,15 @@ import ast
|
||||
import sys
|
||||
import re
|
||||
import importlib
|
||||
import importlib.machinery, importlib.util
|
||||
from glob import glob
|
||||
from itertools import product, chain
|
||||
|
||||
from .config import Config
|
||||
|
||||
import yaml
|
||||
import networkx as nx
|
||||
|
||||
from . import config
|
||||
|
||||
from jinja2 import Template
|
||||
|
||||
|
||||
@@ -90,24 +91,56 @@ def load_files(*patterns, **kwargs):
|
||||
for i in glob(pattern, **kwargs, recursive=True):
|
||||
for cfg in load_file(i):
|
||||
path = os.path.abspath(i)
|
||||
yield Config.from_raw(cfg), path
|
||||
yield cfg, path
|
||||
|
||||
|
||||
def load_config(cfg):
|
||||
if isinstance(cfg, Config):
|
||||
yield cfg, os.getcwd()
|
||||
elif isinstance(cfg, dict):
|
||||
yield Config.from_raw(cfg), os.getcwd()
|
||||
if isinstance(cfg, dict):
|
||||
yield config.load_config(cfg), os.getcwd()
|
||||
else:
|
||||
yield from load_files(cfg)
|
||||
|
||||
|
||||
builtins = importlib.import_module("builtins")
|
||||
|
||||
KNOWN_MODULES = [
|
||||
"soil",
|
||||
]
|
||||
KNOWN_MODULES = {
|
||||
'soil': None,
|
||||
|
||||
}
|
||||
|
||||
MODULE_FILES = {}
|
||||
|
||||
def add_source_file(file):
|
||||
"""Add a file to the list of known modules"""
|
||||
file = os.path.abspath(file)
|
||||
if file in MODULE_FILES:
|
||||
logger.warning(f"File {file} already added as module {MODULE_FILES[file]}. Reloading")
|
||||
remove_source_file(file)
|
||||
modname = f"imported_module_{len(MODULE_FILES)}"
|
||||
loader = importlib.machinery.SourceFileLoader(modname, file)
|
||||
spec = importlib.util.spec_from_loader(loader.name, loader)
|
||||
my_module = importlib.util.module_from_spec(spec)
|
||||
loader.exec_module(my_module)
|
||||
MODULE_FILES[file] = modname
|
||||
KNOWN_MODULES[modname] = my_module
|
||||
|
||||
def remove_source_file(file):
|
||||
"""Remove a file from the list of known modules"""
|
||||
file = os.path.abspath(file)
|
||||
modname = None
|
||||
try:
|
||||
modname = MODULE_FILES.pop(file)
|
||||
KNOWN_MODULES.pop(modname)
|
||||
except KeyError as ex:
|
||||
raise ValueError(f"File {file} had not been added as a module: {ex}")
|
||||
|
||||
def get_module(modname):
|
||||
"""Get a module from the list of known modules"""
|
||||
if modname not in KNOWN_MODULES or KNOWN_MODULES[modname] is None:
|
||||
module = importlib.import_module(modname)
|
||||
KNOWN_MODULES[modname] = module
|
||||
return KNOWN_MODULES[modname]
|
||||
|
||||
|
||||
def name(value, known_modules=KNOWN_MODULES):
|
||||
"""Return a name that can be imported, to serialize/deserialize an object"""
|
||||
@@ -124,9 +157,7 @@ def name(value, known_modules=KNOWN_MODULES):
|
||||
if known_modules and modname in known_modules:
|
||||
return tname
|
||||
for kmod in known_modules:
|
||||
if not kmod:
|
||||
continue
|
||||
module = importlib.import_module(kmod)
|
||||
module = get_module(kmod)
|
||||
if hasattr(module, tname):
|
||||
return tname
|
||||
return "{}.{}".format(modname, tname)
|
||||
@@ -146,7 +177,10 @@ def serialize(v, known_modules=KNOWN_MODULES):
|
||||
|
||||
|
||||
def serialize_dict(d, known_modules=KNOWN_MODULES):
|
||||
d = dict(d)
|
||||
try:
|
||||
d = dict(d)
|
||||
except (ValueError, TypeError) as ex:
|
||||
return serialize(d)[0]
|
||||
for (k, v) in d.items():
|
||||
if isinstance(v, dict):
|
||||
d[k] = serialize_dict(v, known_modules=known_modules)
|
||||
@@ -174,7 +208,7 @@ def deserializer(type_, known_modules=KNOWN_MODULES):
|
||||
match = IS_CLASS.match(type_)
|
||||
if match:
|
||||
modname, tname = match.group(1).rsplit(".", 1)
|
||||
module = importlib.import_module(modname)
|
||||
module = get_module(modname)
|
||||
cls = getattr(module, tname)
|
||||
return getattr(cls, "deserialize", cls)
|
||||
|
||||
@@ -192,7 +226,7 @@ def deserializer(type_, known_modules=KNOWN_MODULES):
|
||||
errors = []
|
||||
for modname, tname in options:
|
||||
try:
|
||||
module = importlib.import_module(modname)
|
||||
module = get_module(modname)
|
||||
cls = getattr(module, tname)
|
||||
return getattr(cls, "deserialize", cls)
|
||||
except (ImportError, AttributeError) as ex:
|
||||
@@ -221,8 +255,6 @@ def deserialize(type_, value=None, globs=None, **kwargs):
|
||||
|
||||
def deserialize_all(names, *args, known_modules=KNOWN_MODULES, **kwargs):
|
||||
"""Return the list of deserialized objects"""
|
||||
# TODO: remove
|
||||
print("SERIALIZATION", kwargs)
|
||||
objects = []
|
||||
for name in names:
|
||||
mod = deserialize(name, known_modules=known_modules)
|
||||
|
@@ -10,37 +10,74 @@ import networkx as nx
|
||||
|
||||
from textwrap import dedent
|
||||
|
||||
from dataclasses import dataclass, field, asdict
|
||||
from dataclasses import dataclass, field, asdict, replace
|
||||
from typing import Any, Dict, Union, Optional, List
|
||||
|
||||
|
||||
from networkx.readwrite import json_graph
|
||||
from functools import partial
|
||||
from contextlib import contextmanager
|
||||
import pickle
|
||||
|
||||
from . import serialization, exporters, utils, basestring, agents
|
||||
from .environment import Environment
|
||||
from .utils import logger, run_and_return_exceptions
|
||||
from .config import Config, convert_old
|
||||
from .debugging import set_trace
|
||||
|
||||
_AVOID_RUNNING = False
|
||||
_QUEUED = []
|
||||
|
||||
@contextmanager
|
||||
def do_not_run():
|
||||
global _AVOID_RUNNING
|
||||
_AVOID_RUNNING = True
|
||||
try:
|
||||
logger.debug("NOT RUNNING")
|
||||
yield
|
||||
finally:
|
||||
logger.debug("RUNNING AGAIN")
|
||||
_AVOID_RUNNING = False
|
||||
|
||||
|
||||
def _iter_queued():
|
||||
while _QUEUED:
|
||||
(cls, args, kwargs) = _QUEUED.pop(0)
|
||||
yield replace(cls, **kwargs)
|
||||
|
||||
|
||||
# TODO: change documentation for simulation
|
||||
@dataclass
|
||||
class Simulation:
|
||||
"""
|
||||
Parameters
|
||||
---------
|
||||
config (optional): :class:`config.Config`
|
||||
name of the Simulation
|
||||
A simulation is a collection of agents and a model. It is responsible for running the model and agents, and collecting data from them.
|
||||
|
||||
kwargs: parameters to use to initialize a new configuration, if one not been provided.
|
||||
Args:
|
||||
version: The version of the simulation. This is used to determine how to load the simulation.
|
||||
name: The name of the simulation.
|
||||
description: A description of the simulation.
|
||||
group: The group that the simulation belongs to.
|
||||
model: The model to use for the simulation. This can be a string or a class.
|
||||
model_params: The parameters to pass to the model.
|
||||
seed: The seed to use for the simulation.
|
||||
dir_path: The directory path to use for the simulation.
|
||||
max_time: The maximum time to run the simulation.
|
||||
max_steps: The maximum number of steps to run the simulation.
|
||||
interval: The interval to use for the simulation.
|
||||
num_trials: The number of trials (times) to run the simulation.
|
||||
num_processes: The number of processes to use for the simulation. If greater than one, simulations will be performed in parallel. This may make debugging and error handling difficult.
|
||||
tables: The tables to use in the simulation datacollector
|
||||
agent_reporters: The agent reporters to use in the datacollector
|
||||
model_reporters: The model reporters to use in the datacollector
|
||||
dry_run: Whether or not to run the simulation. If True, the simulation will not be run.
|
||||
source_file: Python file to use to find additional classes.
|
||||
"""
|
||||
|
||||
version: str = "2"
|
||||
name: str = "Unnamed simulation"
|
||||
source_file: Optional[str] = None
|
||||
name: Optional[str] = None
|
||||
description: Optional[str] = ""
|
||||
group: str = None
|
||||
model_class: Union[str, type] = "soil.Environment"
|
||||
model: Union[str, type] = "soil.Environment"
|
||||
model_params: dict = field(default_factory=dict)
|
||||
seed: str = field(default_factory=lambda: current_time())
|
||||
dir_path: str = field(default_factory=lambda: os.getcwd())
|
||||
@@ -48,28 +85,25 @@ class Simulation:
|
||||
max_steps: int = -1
|
||||
interval: int = 1
|
||||
num_trials: int = 1
|
||||
parallel: Optional[bool] = None
|
||||
exporters: Optional[List[str]] = field(default_factory=list)
|
||||
num_processes: Optional[int] = 1
|
||||
exporters: Optional[List[str]] = field(default_factory=lambda: [exporters.default])
|
||||
model_reporters: Optional[Dict[str, Any]] = field(default_factory=dict)
|
||||
agent_reporters: Optional[Dict[str, Any]] = field(default_factory=dict)
|
||||
tables: Optional[Dict[str, Any]] = field(default_factory=dict)
|
||||
outdir: Optional[str] = None
|
||||
exporter_params: Optional[Dict[str, Any]] = field(default_factory=dict)
|
||||
dry_run: bool = False
|
||||
dump: bool = False
|
||||
extra: Dict[str, Any] = field(default_factory=dict)
|
||||
skip_test: Optional[bool] = False
|
||||
debug: Optional[bool] = False
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, env, **kwargs):
|
||||
|
||||
ignored = {
|
||||
k: v for k, v in env.items() if k not in inspect.signature(cls).parameters
|
||||
}
|
||||
|
||||
d = {k: v for k, v in env.items() if k not in ignored}
|
||||
if ignored:
|
||||
d.setdefault("extra", {}).update(ignored)
|
||||
if ignored:
|
||||
print(f'Warning: Ignoring these parameters (added to "extra"): { ignored }')
|
||||
d.update(kwargs)
|
||||
|
||||
return cls(**d)
|
||||
def __post_init__(self):
|
||||
if self.name is None:
|
||||
if isinstance(self.model, str):
|
||||
self.name = self.model
|
||||
else:
|
||||
self.name = self.model.__class__.__name__
|
||||
|
||||
def run_simulation(self, *args, **kwargs):
|
||||
return self.run(*args, **kwargs)
|
||||
@@ -85,12 +119,16 @@ class Simulation:
|
||||
)
|
||||
+ self.to_yaml()
|
||||
)
|
||||
return list(self.run_gen(*args, **kwargs))
|
||||
if _AVOID_RUNNING:
|
||||
_QUEUED.append((self, args, kwargs))
|
||||
return []
|
||||
return list(self._run_gen(*args, **kwargs))
|
||||
|
||||
def run_gen(
|
||||
def _run_gen(
|
||||
self,
|
||||
parallel=False,
|
||||
num_processes=1,
|
||||
dry_run=None,
|
||||
dump=None,
|
||||
exporters=None,
|
||||
outdir=None,
|
||||
exporter_params={},
|
||||
@@ -105,6 +143,8 @@ class Simulation:
|
||||
logger.info("Output directory: %s", outdir)
|
||||
if dry_run is None:
|
||||
dry_run = self.dry_run
|
||||
if dump is None:
|
||||
dump = self.dump
|
||||
if exporters is None:
|
||||
exporters = self.exporters
|
||||
if not exporter_params:
|
||||
@@ -116,33 +156,50 @@ class Simulation:
|
||||
known_modules=[
|
||||
"soil.exporters",
|
||||
],
|
||||
dry_run=dry_run,
|
||||
dump=dump and not dry_run,
|
||||
outdir=outdir,
|
||||
**exporter_params,
|
||||
)
|
||||
|
||||
with utils.timer("simulation {}".format(self.name)):
|
||||
for exporter in exporters:
|
||||
exporter.sim_start()
|
||||
if self.source_file:
|
||||
source_file = self.source_file
|
||||
if not os.path.isabs(source_file):
|
||||
source_file = os.path.abspath(os.path.join(self.dir_path, source_file))
|
||||
serialization.add_source_file(source_file)
|
||||
try:
|
||||
|
||||
for env in utils.run_parallel(
|
||||
func=self.run_trial,
|
||||
iterable=range(int(self.num_trials)),
|
||||
parallel=parallel,
|
||||
log_level=log_level,
|
||||
**kwargs,
|
||||
):
|
||||
with utils.timer("simulation {}".format(self.name)):
|
||||
for exporter in exporters:
|
||||
exporter.sim_start()
|
||||
|
||||
if dry_run:
|
||||
def func(*args, **kwargs):
|
||||
return None
|
||||
else:
|
||||
func = self.run_trial
|
||||
|
||||
for env in utils.run_parallel(
|
||||
func=self.run_trial,
|
||||
iterable=range(int(self.num_trials)),
|
||||
num_processes=num_processes,
|
||||
log_level=log_level,
|
||||
**kwargs,
|
||||
):
|
||||
if env is None and dry_run:
|
||||
continue
|
||||
|
||||
for exporter in exporters:
|
||||
exporter.trial_end(env)
|
||||
|
||||
yield env
|
||||
|
||||
for exporter in exporters:
|
||||
exporter.trial_start(env)
|
||||
|
||||
for exporter in exporters:
|
||||
exporter.trial_end(env)
|
||||
|
||||
yield env
|
||||
|
||||
for exporter in exporters:
|
||||
exporter.sim_end()
|
||||
exporter.sim_end()
|
||||
finally:
|
||||
pass
|
||||
# TODO: reintroduce
|
||||
# if self.source_file:
|
||||
# serialization.remove_source_file(self.source_file)
|
||||
|
||||
def get_env(self, trial_id=0, model_params=None, **kwargs):
|
||||
"""Create an environment for a trial of the simulation"""
|
||||
@@ -158,16 +215,22 @@ class Simulation:
|
||||
params.update(model_params)
|
||||
params.update(kwargs)
|
||||
|
||||
agent_reporters = deserialize_reporters(params.pop("agent_reporters", {}))
|
||||
model_reporters = deserialize_reporters(params.pop("model_reporters", {}))
|
||||
agent_reporters = self.agent_reporters.copy()
|
||||
agent_reporters.update(deserialize_reporters(params.pop("agent_reporters", {})))
|
||||
model_reporters = self.model_reporters.copy()
|
||||
model_reporters.update(deserialize_reporters(params.pop("model_reporters", {})))
|
||||
tables = self.tables.copy()
|
||||
tables.update(deserialize_reporters(params.pop("tables", {})))
|
||||
|
||||
env = serialization.deserialize(self.model_class)
|
||||
env = serialization.deserialize(self.model)
|
||||
return env(
|
||||
id=f"{self.name}_trial_{trial_id}",
|
||||
seed=f"{self.seed}_trial_{trial_id}",
|
||||
dir_path=self.dir_path,
|
||||
interval=self.interval,
|
||||
agent_reporters=agent_reporters,
|
||||
model_reporters=model_reporters,
|
||||
tables=tables,
|
||||
**params,
|
||||
)
|
||||
|
||||
@@ -200,6 +263,9 @@ class Simulation:
|
||||
|
||||
def is_done():
|
||||
return prev() or model.schedule.time >= until
|
||||
|
||||
if not model.schedule.agents:
|
||||
raise Exception("No agents in model. This is probably a bug. Make sure that the model has agents scheduled after its initialization.")
|
||||
|
||||
if self.max_steps and self.max_steps > 0 and hasattr(model.schedule, "steps"):
|
||||
prev_steps = is_done
|
||||
@@ -212,47 +278,52 @@ class Simulation:
|
||||
dedent(
|
||||
f"""
|
||||
Model stats:
|
||||
Agents (total: { model.schedule.get_agent_count() }):
|
||||
- { (newline + ' - ').join(str(a) for a in model.schedule.agents) }
|
||||
|
||||
Agent count: { model.schedule.get_agent_count() }):
|
||||
Topology size: { len(model.G) if hasattr(model, "G") else 0 }
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
if self.debug:
|
||||
set_trace()
|
||||
|
||||
while not is_done():
|
||||
utils.logger.debug(
|
||||
f'Simulation time {model.schedule.time}/{until}. Next: {getattr(model.schedule, "next_time", model.schedule.time + self.interval)}'
|
||||
f'Simulation time {model.schedule.time}/{until}.'
|
||||
)
|
||||
model.step()
|
||||
|
||||
if (
|
||||
model.schedule.time < until
|
||||
): # Simulation ended (no more steps) before the expected time
|
||||
model.schedule.time = until
|
||||
return model
|
||||
|
||||
def to_dict(self):
|
||||
d = asdict(self)
|
||||
if not isinstance(d["model_class"], str):
|
||||
d["model_class"] = serialization.name(d["model_class"])
|
||||
d["model_params"] = serialization.serialize_dict(d["model_params"])
|
||||
d["dir_path"] = str(d["dir_path"])
|
||||
d["version"] = "2"
|
||||
return d
|
||||
return serialization.serialize_dict(d)
|
||||
|
||||
def to_yaml(self):
|
||||
return yaml.dump(self.to_dict())
|
||||
|
||||
|
||||
def iter_from_file(*files, **kwargs):
|
||||
for f in files:
|
||||
try:
|
||||
yield from iter_from_py(f, **kwargs)
|
||||
except ValueError as ex:
|
||||
yield from iter_from_config(f, **kwargs)
|
||||
|
||||
|
||||
def from_file(*args, **kwargs):
|
||||
return list(iter_from_file(*args, **kwargs))
|
||||
|
||||
|
||||
def iter_from_config(*cfgs, **kwargs):
|
||||
for config in cfgs:
|
||||
configs = list(serialization.load_config(config))
|
||||
for config, path in configs:
|
||||
d = dict(config)
|
||||
d.update(kwargs)
|
||||
if "dir_path" not in d:
|
||||
d["dir_path"] = os.path.dirname(path)
|
||||
yield Simulation.from_dict(d, **kwargs)
|
||||
yield Simulation(**d)
|
||||
|
||||
|
||||
def from_config(conf_or_path):
|
||||
@@ -262,7 +333,47 @@ def from_config(conf_or_path):
|
||||
return lst[0]
|
||||
|
||||
|
||||
def run_from_config(*configs, **kwargs):
|
||||
for sim in iter_from_config(*configs):
|
||||
def iter_from_py(pyfile, module_name='custom_simulation', **kwargs):
|
||||
"""Try to load every Simulation instance in a given Python file"""
|
||||
import importlib
|
||||
import inspect
|
||||
added = False
|
||||
sims = []
|
||||
assert not _AVOID_RUNNING
|
||||
with do_not_run():
|
||||
assert _AVOID_RUNNING
|
||||
spec = importlib.util.spec_from_file_location(module_name, pyfile)
|
||||
folder = os.path.dirname(pyfile)
|
||||
if folder not in sys.path:
|
||||
added = True
|
||||
sys.path.append(folder)
|
||||
if not spec:
|
||||
raise ValueError(f"{pyfile} does not seem to be a Python module")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules[module_name] = module
|
||||
spec.loader.exec_module(module)
|
||||
for (_name, sim) in inspect.getmembers(module, lambda x: isinstance(x, Simulation)):
|
||||
sims.append(sim)
|
||||
for sim in _iter_queued():
|
||||
sims.append(sim)
|
||||
if not sims:
|
||||
for (_name, sim) in inspect.getmembers(module, lambda x: inspect.isclass(x) and issubclass(x, Simulation)):
|
||||
sims.append(sim(**kwargs))
|
||||
del sys.modules[module_name]
|
||||
assert not _AVOID_RUNNING
|
||||
if not sims:
|
||||
raise AttributeError(f"No valid configurations found in {pyfile}")
|
||||
if added:
|
||||
sys.path.remove(folder)
|
||||
for sim in sims:
|
||||
yield replace(sim, **kwargs)
|
||||
|
||||
|
||||
def from_py(pyfile):
|
||||
return next(iter_from_py(pyfile))
|
||||
|
||||
|
||||
def run_from_file(*files, **kwargs):
|
||||
for sim in iter_from_file(*files):
|
||||
logger.info(f"Using config(s): {sim.name}")
|
||||
sim.run_simulation(**kwargs)
|
||||
|
235
soil/time.py
235
soil/time.py
@@ -1,10 +1,11 @@
|
||||
from mesa.time import BaseScheduler
|
||||
from queue import Empty
|
||||
from heapq import heappush, heappop, heapify
|
||||
from heapq import heappush, heappop
|
||||
import math
|
||||
|
||||
from inspect import getsource
|
||||
from numbers import Number
|
||||
from textwrap import dedent
|
||||
|
||||
from .utils import logger
|
||||
from mesa import Agent as MesaAgent
|
||||
@@ -23,65 +24,11 @@ class When:
|
||||
return time
|
||||
self._time = time
|
||||
|
||||
def next(self, time):
|
||||
def abs(self, time):
|
||||
return self._time
|
||||
|
||||
def abs(self, time):
|
||||
return self
|
||||
|
||||
def __repr__(self):
|
||||
return str(f"When({self._time})")
|
||||
|
||||
def __lt__(self, other):
|
||||
if isinstance(other, Number):
|
||||
return self._time < other
|
||||
return self._time < other.next(self._time)
|
||||
|
||||
def __gt__(self, other):
|
||||
if isinstance(other, Number):
|
||||
return self._time > other
|
||||
return self._time > other.next(self._time)
|
||||
|
||||
def ready(self, agent):
|
||||
return self._time <= agent.model.schedule.time
|
||||
|
||||
def return_value(self, agent):
|
||||
return None
|
||||
|
||||
|
||||
class Cond(When):
|
||||
def __init__(self, func, delta=1, return_func=lambda agent: None):
|
||||
self._func = func
|
||||
self._delta = delta
|
||||
self._checked = False
|
||||
self._return_func = return_func
|
||||
|
||||
def next(self, time):
|
||||
if self._checked:
|
||||
return time + self._delta
|
||||
return time
|
||||
|
||||
def abs(self, time):
|
||||
return self
|
||||
|
||||
def ready(self, agent):
|
||||
self._checked = True
|
||||
return self._func(agent)
|
||||
|
||||
def return_value(self, agent):
|
||||
return self._return_func(agent)
|
||||
|
||||
def __eq__(self, other):
|
||||
return False
|
||||
|
||||
def __lt__(self, other):
|
||||
return True
|
||||
|
||||
def __gt__(self, other):
|
||||
return False
|
||||
|
||||
def __repr__(self):
|
||||
return str(f'Cond("{getsource(self._func)}")')
|
||||
def schedule_next(self, time, delta, first=False):
|
||||
return (self._time, None)
|
||||
|
||||
|
||||
NEVER = When(INFINITY)
|
||||
@@ -91,48 +38,95 @@ class Delta(When):
|
||||
def __init__(self, delta):
|
||||
self._delta = delta
|
||||
|
||||
def abs(self, time):
|
||||
return self._time + self._delta
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, Delta):
|
||||
return self._delta == other._delta
|
||||
return False
|
||||
|
||||
def abs(self, time):
|
||||
return When(self._delta + time)
|
||||
|
||||
def next(self, time):
|
||||
return time + self._delta
|
||||
def schedule_next(self, time, delta, first=False):
|
||||
return (time + self._delta, None)
|
||||
|
||||
def __repr__(self):
|
||||
return str(f"Delta({self._delta})")
|
||||
|
||||
|
||||
class BaseCond:
|
||||
def __init__(self, msg=None, delta=None, eager=False):
|
||||
self._msg = msg
|
||||
self._delta = delta
|
||||
self.eager = eager
|
||||
|
||||
def schedule_next(self, time, delta, first=False):
|
||||
if first and self.eager:
|
||||
return (time, self)
|
||||
if self._delta:
|
||||
delta = self._delta
|
||||
return (time + delta, self)
|
||||
|
||||
def return_value(self, agent):
|
||||
return None
|
||||
|
||||
def __repr__(self):
|
||||
return self._msg or self.__class__.__name__
|
||||
|
||||
|
||||
class Cond(BaseCond):
|
||||
def __init__(self, func, *args, **kwargs):
|
||||
self._func = func
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def ready(self, agent, time):
|
||||
return self._func(agent)
|
||||
|
||||
def __repr__(self):
|
||||
if self._msg:
|
||||
return self._msg
|
||||
return str(f'Cond("{dedent(getsource(self._func)).strip()}")')
|
||||
|
||||
|
||||
class TimedActivation(BaseScheduler):
|
||||
"""A scheduler which activates each agent when the agent requests.
|
||||
In each activation, each agent will update its 'next_time'.
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
def __init__(self, *args, shuffle=True, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self._next = {}
|
||||
self._queue = []
|
||||
self.next_time = 0
|
||||
self._shuffle = shuffle
|
||||
# self.step_interval = getattr(self.model, "interval", 1)
|
||||
self.step_interval = self.model.interval
|
||||
self.logger = logger.getChild(f"time_{ self.model }")
|
||||
|
||||
def add(self, agent: MesaAgent, when=None):
|
||||
if when is None:
|
||||
when = When(self.time)
|
||||
elif not isinstance(when, When):
|
||||
when = When(when)
|
||||
if agent.unique_id in self._agents:
|
||||
del self._agents[agent.unique_id]
|
||||
if agent.unique_id in self._next:
|
||||
self._queue.remove((self._next[agent.unique_id], agent))
|
||||
heapify(self._queue)
|
||||
when = self.time
|
||||
elif isinstance(when, When):
|
||||
when = when.abs()
|
||||
|
||||
self._next[agent.unique_id] = when
|
||||
heappush(self._queue, (when, agent))
|
||||
self._schedule(agent, None, when)
|
||||
super().add(agent)
|
||||
|
||||
def _schedule(self, agent, condition=None, when=None):
|
||||
if condition:
|
||||
if not when:
|
||||
when, condition = condition.schedule_next(
|
||||
when or self.time, self.step_interval
|
||||
)
|
||||
else:
|
||||
if when is None:
|
||||
when = self.time + self.step_interval
|
||||
condition = None
|
||||
if self._shuffle:
|
||||
key = (when, self.model.random.random(), condition)
|
||||
else:
|
||||
key = (when, agent.unique_id, condition)
|
||||
self._next[agent.unique_id] = key
|
||||
heappush(self._queue, (key, agent))
|
||||
|
||||
def step(self) -> None:
|
||||
"""
|
||||
Executes agents in order, one at a time. After each step,
|
||||
@@ -140,76 +134,75 @@ class TimedActivation(BaseScheduler):
|
||||
"""
|
||||
|
||||
self.logger.debug(f"Simulation step {self.time}")
|
||||
if not self.model.running:
|
||||
if not self.model.running or self.time == INFINITY:
|
||||
return
|
||||
|
||||
when = NEVER
|
||||
|
||||
to_process = []
|
||||
skipped = []
|
||||
next_time = INFINITY
|
||||
|
||||
ix = 0
|
||||
|
||||
self.logger.debug(f"Queue length: {len(self._queue)}")
|
||||
self.logger.debug(f"Queue length: %s", len(self._queue))
|
||||
|
||||
while self._queue:
|
||||
(when, agent) = self._queue[0]
|
||||
((when, _id, cond), agent) = self._queue[0]
|
||||
if when > self.time:
|
||||
break
|
||||
|
||||
heappop(self._queue)
|
||||
if when.ready(agent):
|
||||
if cond:
|
||||
if not cond.ready(agent, self.time):
|
||||
self._schedule(agent, cond)
|
||||
continue
|
||||
try:
|
||||
agent._last_return = when.return_value(agent)
|
||||
agent._last_return = cond.return_value(agent)
|
||||
except Exception as ex:
|
||||
agent._last_except = ex
|
||||
else:
|
||||
agent._last_return = None
|
||||
agent._last_except = None
|
||||
|
||||
self._next.pop(agent.unique_id, None)
|
||||
to_process.append(agent)
|
||||
continue
|
||||
|
||||
next_time = min(next_time, when.next(self.time))
|
||||
self._next[agent.unique_id] = next_time
|
||||
skipped.append((when, agent))
|
||||
|
||||
if self._queue:
|
||||
next_time = min(next_time, self._queue[0][0].next(self.time))
|
||||
|
||||
self._queue = [*skipped, *self._queue]
|
||||
|
||||
for agent in to_process:
|
||||
self.logger.debug(f"Stepping agent {agent}")
|
||||
self.logger.debug("Stepping agent %s", agent)
|
||||
self._next.pop(agent.unique_id, None)
|
||||
|
||||
try:
|
||||
returned = ((agent.step() or Delta(1))).abs(self.time)
|
||||
returned = agent.step()
|
||||
except DeadAgent:
|
||||
if agent.unique_id in self._next:
|
||||
del self._next[agent.unique_id]
|
||||
agent.alive = False
|
||||
continue
|
||||
|
||||
# Check status for MESA agents
|
||||
if not getattr(agent, "alive", True):
|
||||
continue
|
||||
|
||||
value = returned.next(self.time)
|
||||
agent._last_return = value
|
||||
|
||||
if value < self.time:
|
||||
raise Exception(
|
||||
f"Cannot schedule an agent for a time in the past ({when} < {self.time})"
|
||||
if returned:
|
||||
next_check = returned.schedule_next(
|
||||
self.time, self.step_interval, first=True
|
||||
)
|
||||
if value < INFINITY:
|
||||
next_time = min(value, next_time)
|
||||
|
||||
self._next[agent.unique_id] = returned
|
||||
heappush(self._queue, (returned, agent))
|
||||
self._schedule(agent, when=next_check[0], condition=next_check[1])
|
||||
else:
|
||||
assert not self._next[agent.unique_id]
|
||||
next_check = (self.time + self.step_interval, None)
|
||||
|
||||
self._schedule(agent)
|
||||
|
||||
self.steps += 1
|
||||
self.logger.debug(f"Updating time step: {self.time} -> {next_time}")
|
||||
self.time = next_time
|
||||
|
||||
if not self._queue or next_time == INFINITY:
|
||||
if not self._queue:
|
||||
self.time = INFINITY
|
||||
self.model.running = False
|
||||
return self.time
|
||||
|
||||
next_time = self._queue[0][0][0]
|
||||
|
||||
if next_time < self.time:
|
||||
raise Exception(
|
||||
f"An agent has been scheduled for a time in the past, there is probably an error ({when} < {self.time})"
|
||||
)
|
||||
self.logger.debug(f"Updating time step: {self.time} -> {next_time}")
|
||||
|
||||
self.time = next_time
|
||||
|
||||
|
||||
class ShuffledTimedActivation(TimedActivation):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, shuffle=True, **kwargs)
|
||||
|
||||
|
||||
class OrderedTimedActivation(TimedActivation):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, shuffle=False, **kwargs)
|
||||
|
@@ -5,7 +5,7 @@ import traceback
|
||||
|
||||
from functools import partial
|
||||
from shutil import copyfile, move
|
||||
from multiprocessing import Pool
|
||||
from multiprocessing import Pool, cpu_count
|
||||
|
||||
from contextlib import contextmanager
|
||||
|
||||
@@ -24,7 +24,7 @@ consoleHandler = logging.StreamHandler()
|
||||
consoleHandler.setFormatter(logFormatter)
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
level=logging.DEBUG,
|
||||
handlers=[
|
||||
consoleHandler,
|
||||
],
|
||||
@@ -140,9 +140,11 @@ def run_and_return_exceptions(func, *args, **kwargs):
|
||||
return ex
|
||||
|
||||
|
||||
def run_parallel(func, iterable, parallel=False, **kwargs):
|
||||
if parallel and not os.environ.get("SOIL_DEBUG", None):
|
||||
p = Pool()
|
||||
def run_parallel(func, iterable, num_processes=1, **kwargs):
|
||||
if num_processes > 1 and not os.environ.get("SOIL_DEBUG", None):
|
||||
if num_processes < 1:
|
||||
num_processes = cpu_count() - num_processes
|
||||
p = Pool(processes=num_processes)
|
||||
wrapped_func = partial(run_and_return_exceptions, func, **kwargs)
|
||||
for i in p.imap_unordered(wrapped_func, iterable):
|
||||
if isinstance(i, Exception):
|
||||
|
@@ -1,6 +0,0 @@
|
||||
from mesa.visualization.UserParam import UserSettableParameter
|
||||
|
||||
|
||||
class UserSettableParameter(UserSettableParameter):
|
||||
def __str__(self):
|
||||
return self.value
|
@@ -1,49 +0,0 @@
|
||||
---
|
||||
version: '2'
|
||||
name: simple
|
||||
group: tests
|
||||
dir_path: "/tmp/"
|
||||
num_trials: 3
|
||||
max_time: 100
|
||||
interval: 1
|
||||
seed: "CompleteSeed!"
|
||||
model_class: Environment
|
||||
model_params:
|
||||
topology:
|
||||
params:
|
||||
generator: complete_graph
|
||||
n: 4
|
||||
agents:
|
||||
agent_class: CounterModel
|
||||
state:
|
||||
group: network
|
||||
times: 1
|
||||
topology: true
|
||||
distribution:
|
||||
- agent_class: CounterModel
|
||||
weight: 0.25
|
||||
state:
|
||||
state_id: 0
|
||||
times: 1
|
||||
- agent_class: AggregatedCounter
|
||||
weight: 0.5
|
||||
state:
|
||||
times: 2
|
||||
override:
|
||||
- filter:
|
||||
node_id: 1
|
||||
state:
|
||||
name: 'Node 1'
|
||||
- filter:
|
||||
node_id: 2
|
||||
state:
|
||||
name: 'Node 2'
|
||||
fixed:
|
||||
- agent_class: BaseAgent
|
||||
hidden: true
|
||||
topology: false
|
||||
state:
|
||||
name: 'Environment Agent 1'
|
||||
times: 10
|
||||
group: environment
|
||||
am_i_complete: true
|
@@ -1,37 +0,0 @@
|
||||
---
|
||||
name: simple
|
||||
group: tests
|
||||
dir_path: "/tmp/"
|
||||
num_trials: 3
|
||||
max_time: 100
|
||||
interval: 1
|
||||
seed: "CompleteSeed!"
|
||||
network_params:
|
||||
generator: complete_graph
|
||||
n: 4
|
||||
network_agents:
|
||||
- agent_class: CounterModel
|
||||
weight: 0.25
|
||||
state:
|
||||
state_id: 0
|
||||
times: 1
|
||||
- agent_class: AggregatedCounter
|
||||
weight: 0.5
|
||||
state:
|
||||
times: 2
|
||||
environment_agents:
|
||||
- agent_id: 'Environment Agent 1'
|
||||
agent_class: BaseAgent
|
||||
state:
|
||||
times: 10
|
||||
environment_class: Environment
|
||||
environment_params:
|
||||
am_i_complete: true
|
||||
agent_class: CounterModel
|
||||
default_state:
|
||||
times: 1
|
||||
states:
|
||||
1:
|
||||
name: 'Node 1'
|
||||
2:
|
||||
name: 'Node 2'
|
@@ -12,34 +12,36 @@ class Dead(agents.FSM):
|
||||
return self.die()
|
||||
|
||||
|
||||
class TestMain(TestCase):
|
||||
class TestAgents(TestCase):
|
||||
def test_die_returns_infinity(self):
|
||||
'''The last step of a dead agent should return time.INFINITY'''
|
||||
"""The last step of a dead agent should return time.INFINITY"""
|
||||
d = Dead(unique_id=0, model=environment.Environment())
|
||||
ret = d.step().abs(0)
|
||||
print(ret, "next")
|
||||
ret = d.step()
|
||||
assert ret == stime.NEVER
|
||||
|
||||
def test_die_raises_exception(self):
|
||||
'''A dead agent should raise an exception if it is stepped after death'''
|
||||
"""A dead agent should raise an exception if it is stepped after death"""
|
||||
d = Dead(unique_id=0, model=environment.Environment())
|
||||
assert d.alive
|
||||
d.step()
|
||||
assert not d.alive
|
||||
with pytest.raises(stime.DeadAgent):
|
||||
d.step()
|
||||
|
||||
|
||||
def test_agent_generator(self):
|
||||
'''
|
||||
"""
|
||||
The step function of an agent could be a generator. In that case, the state of the
|
||||
agent will be resumed after every call to step.
|
||||
'''
|
||||
"""
|
||||
a = 0
|
||||
|
||||
class Gen(agents.BaseAgent):
|
||||
def step(self):
|
||||
nonlocal a
|
||||
for i in range(5):
|
||||
yield
|
||||
a += 1
|
||||
|
||||
e = environment.Environment()
|
||||
g = Gen(model=e, unique_id=e.next_id())
|
||||
e.schedule.add(g)
|
||||
@@ -51,8 +53,9 @@ class TestMain(TestCase):
|
||||
def test_state_decorator(self):
|
||||
class MyAgent(agents.FSM):
|
||||
run = 0
|
||||
|
||||
@agents.default_state
|
||||
@agents.state('original')
|
||||
@agents.state("original")
|
||||
def root(self):
|
||||
self.run += 1
|
||||
return self.other
|
||||
@@ -66,4 +69,109 @@ class TestMain(TestCase):
|
||||
a.step()
|
||||
assert a.run == 1
|
||||
a.step()
|
||||
assert a.run == 2
|
||||
|
||||
def test_broadcast(self):
|
||||
"""
|
||||
An agent should be able to broadcast messages to every other agent, AND each receiver should be able
|
||||
to process it
|
||||
"""
|
||||
|
||||
class BCast(agents.Evented):
|
||||
pings_received = 0
|
||||
|
||||
def step(self):
|
||||
print(self.model.broadcast)
|
||||
try:
|
||||
self.model.broadcast("PING")
|
||||
except Exception as ex:
|
||||
print(ex)
|
||||
while True:
|
||||
self.check_messages()
|
||||
yield
|
||||
|
||||
def on_receive(self, msg, sender=None):
|
||||
self.pings_received += 1
|
||||
|
||||
e = environment.EventedEnvironment()
|
||||
|
||||
for i in range(10):
|
||||
e.add_agent(agent_class=BCast)
|
||||
e.step()
|
||||
pings_received = lambda: [a.pings_received for a in e.agents]
|
||||
assert sorted(pings_received()) == list(range(1, 11))
|
||||
e.step()
|
||||
assert all(x == 10 for x in pings_received())
|
||||
|
||||
def test_ask_messages(self):
|
||||
"""
|
||||
An agent should be able to ask another agent, and wait for a response.
|
||||
"""
|
||||
|
||||
# There are two agents, they try to send pings
|
||||
# This is arguably a very contrived example.
|
||||
# There should be a delay of one step between agent 0 and 1
|
||||
# On the first step:
|
||||
# Agent 0 sends a PING, but blocks before a PONG
|
||||
# Agent 1 detects the PING, responds with a PONG, and blocks after its own PING
|
||||
# After that step, every agent can both receive (there are pending messages) and send.
|
||||
# In each step, for each agent, one message is sent, and another one is received
|
||||
# (although not necessarily in that order).
|
||||
|
||||
# Results depend on ordering (agents are normally shuffled)
|
||||
# so we force the timedactivation not to be shuffled
|
||||
|
||||
pings = []
|
||||
pongs = []
|
||||
responses = []
|
||||
|
||||
class Ping(agents.EventedAgent):
|
||||
def step(self):
|
||||
target_id = (self.unique_id + 1) % self.count_agents()
|
||||
target = self.model.agents[target_id]
|
||||
print("starting")
|
||||
while True:
|
||||
if pongs or not pings: # First agent, or anyone after that
|
||||
pings.append(self.now)
|
||||
response = yield target.ask("PING")
|
||||
responses.append(response)
|
||||
else:
|
||||
print("NOT sending ping")
|
||||
print("Checking msgs")
|
||||
# Do not block if we have already received a PING
|
||||
if not self.check_messages():
|
||||
yield self.received()
|
||||
print("done")
|
||||
|
||||
def on_receive(self, msg, sender=None):
|
||||
if msg == "PING":
|
||||
pongs.append(self.now)
|
||||
return "PONG"
|
||||
raise Exception("This should never happen")
|
||||
|
||||
e = environment.EventedEnvironment(schedule_class=stime.OrderedTimedActivation)
|
||||
for i in range(2):
|
||||
e.add_agent(agent_class=Ping)
|
||||
assert e.now == 0
|
||||
|
||||
for i in range(5):
|
||||
e.step()
|
||||
time = i + 1
|
||||
assert e.now == time
|
||||
assert len(pings) == 2 * time
|
||||
assert len(pongs) == (2 * time) - 1
|
||||
# Every step between 0 and t appears twice
|
||||
assert sum(pings) == sum(range(time)) * 2
|
||||
# It is the same as pings, without the leading 0
|
||||
assert sum(pongs) == sum(range(time)) * 2
|
||||
|
||||
def test_agent_filter(self):
|
||||
e = environment.Environment()
|
||||
e.add_agent(agent_class=agents.BaseAgent)
|
||||
e.add_agent(agent_class=agents.Evented)
|
||||
base = list(e.agents(agent_class=agents.BaseAgent))
|
||||
assert len(base) == 2
|
||||
ev = list(e.agents(agent_class=agents.Evented))
|
||||
assert len(ev) == 1
|
||||
assert ev[0].unique_id == 1
|
||||
null = list(e.agents(unique_ids=[0, 1], agent_class=agents.NetworkAgent))
|
||||
assert not null
|
@@ -1,4 +1,4 @@
|
||||
from unittest import TestCase
|
||||
from unittest import TestCase, skip
|
||||
import os
|
||||
import yaml
|
||||
import copy
|
||||
@@ -23,85 +23,18 @@ def isequal(a, b):
|
||||
assert a == b
|
||||
|
||||
|
||||
# @skip("new versions of soil do not rely on configuration files")
|
||||
class TestConfig(TestCase):
|
||||
def test_conversion(self):
|
||||
expected = serialization.load_file(join(ROOT, "complete_converted.yml"))[0]
|
||||
old = serialization.load_file(join(ROOT, "old_complete.yml"))[0]
|
||||
converted_defaults = config.convert_old(old, strict=False)
|
||||
converted = converted_defaults.dict(exclude_unset=True)
|
||||
|
||||
isequal(converted, expected)
|
||||
|
||||
def test_configuration_changes(self):
|
||||
"""
|
||||
The configuration should not change after running
|
||||
the simulation.
|
||||
"""
|
||||
config = serialization.load_file(join(EXAMPLES, "complete.yml"))[0]
|
||||
s = simulation.from_config(config)
|
||||
init_config = copy.copy(s.to_dict())
|
||||
|
||||
s.run_simulation(dry_run=True)
|
||||
nconfig = s.to_dict()
|
||||
# del nconfig['to
|
||||
isequal(init_config, nconfig)
|
||||
|
||||
def test_topology_config(self):
|
||||
netconfig = config.NetConfig(**{"path": join(ROOT, "test.gexf")})
|
||||
net = network.from_config(netconfig, dir_path=ROOT)
|
||||
assert len(net.nodes) == 2
|
||||
assert len(net.edges) == 1
|
||||
|
||||
def test_env_from_config(self):
|
||||
"""
|
||||
Simple configuration that tests that the graph is loaded, and that
|
||||
network agents are initialized properly.
|
||||
"""
|
||||
cfg = {
|
||||
"name": "CounterAgent",
|
||||
"network_params": {"path": join(ROOT, "test.gexf")},
|
||||
"agent_class": "CounterModel",
|
||||
# 'states': [{'times': 10}, {'times': 20}],
|
||||
"max_time": 2,
|
||||
"dry_run": True,
|
||||
"num_trials": 1,
|
||||
"environment_params": {},
|
||||
}
|
||||
conf = config.convert_old(cfg)
|
||||
s = simulation.from_config(conf)
|
||||
|
||||
env = s.get_env()
|
||||
assert len(env.G.nodes) == 2
|
||||
assert len(env.G.edges) == 1
|
||||
assert len(env.agents) == 2
|
||||
assert env.agents[0].G == env.G
|
||||
|
||||
def test_agents_from_config(self):
|
||||
"""We test that the known complete configuration produces
|
||||
the right agents in the right groups"""
|
||||
cfg = serialization.load_file(join(ROOT, "complete_converted.yml"))[0]
|
||||
s = simulation.from_config(cfg)
|
||||
env = s.get_env()
|
||||
assert len(env.G.nodes) == 4
|
||||
assert len(env.agents(group="network")) == 4
|
||||
assert len(env.agents(group="environment")) == 1
|
||||
|
||||
def test_yaml(self):
|
||||
"""
|
||||
The YAML version of a newly created configuration should be equivalent
|
||||
to the configuration file used.
|
||||
Values not present in the original config file should have reasonable
|
||||
defaults.
|
||||
"""
|
||||
with utils.timer("loading"):
|
||||
config = serialization.load_file(join(EXAMPLES, "complete.yml"))[0]
|
||||
s = simulation.from_config(config)
|
||||
with utils.timer("serializing"):
|
||||
serial = s.to_yaml()
|
||||
with utils.timer("recovering"):
|
||||
recovered = yaml.load(serial, Loader=yaml.SafeLoader)
|
||||
for (k, v) in config.items():
|
||||
assert recovered[k] == v
|
||||
def test_torvalds_config(self):
|
||||
sim = simulation.from_config(os.path.join(ROOT, "test_config.yml"))
|
||||
assert sim.interval == 2
|
||||
envs = sim.run()
|
||||
assert len(envs) == 1
|
||||
env = envs[0]
|
||||
assert env.interval == 2
|
||||
assert env.count_agents() == 3
|
||||
assert env.now == 20
|
||||
|
||||
|
||||
def make_example_test(path, cfg):
|
||||
@@ -109,24 +42,23 @@ def make_example_test(path, cfg):
|
||||
root = os.getcwd()
|
||||
print(path)
|
||||
s = simulation.from_config(cfg)
|
||||
# for s in simulation.all_from_config(path):
|
||||
# iterations = s.config.max_time * s.config.num_trials
|
||||
# if iterations > 1000:
|
||||
# s.config.max_time = 100
|
||||
# s.config.num_trials = 1
|
||||
# if config.get('skip_test', False) and not FORCE_TESTS:
|
||||
# self.skipTest('Example ignored.')
|
||||
# envs = s.run_simulation(dry_run=True)
|
||||
# assert envs
|
||||
# for env in envs:
|
||||
# assert env
|
||||
# try:
|
||||
# n = config['network_params']['n']
|
||||
# assert len(list(env.network_agents)) == n
|
||||
# assert env.now > 0 # It has run
|
||||
# assert env.now <= config['max_time'] # But not further than allowed
|
||||
# except KeyError:
|
||||
# pass
|
||||
iterations = s.max_time * s.num_trials
|
||||
if iterations > 1000:
|
||||
s.max_time = 100
|
||||
s.num_trials = 1
|
||||
if cfg.skip_test and not FORCE_TESTS:
|
||||
self.skipTest('Example ignored.')
|
||||
envs = s.run_simulation(dump=False)
|
||||
assert envs
|
||||
for env in envs:
|
||||
assert env
|
||||
try:
|
||||
n = cfg.model_params['topology']['params']['n']
|
||||
assert len(list(env.network_agents)) == n
|
||||
assert env.now > 0 # It has run
|
||||
assert env.now <= cfg.max_time # But not further than allowed
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
return wrapped
|
||||
|
||||
|
5
tests/test_config.yml
Normal file
5
tests/test_config.yml
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
source_file: "../examples/torvalds_sim.py"
|
||||
model: "TorvaldsEnv"
|
||||
max_steps: 10
|
||||
interval: 2
|
@@ -1,8 +1,12 @@
|
||||
from unittest import TestCase
|
||||
from unittest.case import SkipTest
|
||||
|
||||
import os
|
||||
from os.path import join
|
||||
from glob import glob
|
||||
|
||||
from soil import serialization, simulation, config
|
||||
|
||||
from soil import simulation
|
||||
|
||||
ROOT = os.path.abspath(os.path.dirname(__file__))
|
||||
EXAMPLES = join(ROOT, "..", "examples")
|
||||
@@ -11,45 +15,63 @@ FORCE_TESTS = os.environ.get("FORCE_TESTS", "")
|
||||
|
||||
|
||||
class TestExamples(TestCase):
|
||||
"""Empty class that will be populated with auto-discovery tests for every example"""
|
||||
pass
|
||||
|
||||
|
||||
def make_example_test(path, cfg):
|
||||
def get_test_for_sims(sims, path):
|
||||
root = os.getcwd()
|
||||
|
||||
def wrapped(self):
|
||||
root = os.getcwd()
|
||||
for s in simulation.iter_from_config(cfg):
|
||||
iterations = s.max_steps * s.num_trials
|
||||
run = False
|
||||
for sim in sims:
|
||||
if sim.skip_test and not FORCE_TESTS:
|
||||
continue
|
||||
run = True
|
||||
iterations = sim.max_steps * sim.num_trials
|
||||
if iterations < 0 or iterations > 1000:
|
||||
s.max_steps = 100
|
||||
s.num_trials = 1
|
||||
assert isinstance(cfg, config.Config)
|
||||
if getattr(cfg, "skip_test", False) and not FORCE_TESTS:
|
||||
self.skipTest("Example ignored.")
|
||||
envs = s.run_simulation(dry_run=True)
|
||||
sim.max_steps = 100
|
||||
sim.num_trials = 1
|
||||
envs = sim.run_simulation(dump=False)
|
||||
assert envs
|
||||
for env in envs:
|
||||
assert env
|
||||
assert env.now > 0
|
||||
try:
|
||||
n = cfg.model_params["network_params"]["n"]
|
||||
n = sim.model_params["network_params"]["n"]
|
||||
assert len(list(env.network_agents)) == n
|
||||
except KeyError:
|
||||
pass
|
||||
assert env.schedule.steps > 0 # It has run
|
||||
assert env.schedule.steps <= s.max_steps # But not further than allowed
|
||||
assert env.schedule.steps <= sim.max_steps # But not further than allowed
|
||||
if not run:
|
||||
raise SkipTest("Example ignored because all simulations are set up to be skipped.")
|
||||
|
||||
return wrapped
|
||||
|
||||
|
||||
def add_example_tests():
|
||||
for cfg, path in serialization.load_files(
|
||||
join(EXAMPLES, "**", "*.yml"),
|
||||
):
|
||||
p = make_example_test(path=path, cfg=config.Config.from_raw(cfg))
|
||||
sim_paths = {}
|
||||
for path in glob(join(EXAMPLES, '**', '*.yml')):
|
||||
if "soil_output" in path:
|
||||
continue
|
||||
if path not in sim_paths:
|
||||
sim_paths[path] = []
|
||||
for sim in simulation.iter_from_config(path):
|
||||
sim_paths[path].append(sim)
|
||||
for path in glob(join(EXAMPLES, '**', '*_sim.py')):
|
||||
if path not in sim_paths:
|
||||
sim_paths[path] = []
|
||||
for sim in simulation.iter_from_py(path):
|
||||
sim_paths[path].append(sim)
|
||||
|
||||
for (path, sims) in sim_paths.items():
|
||||
test_case = get_test_for_sims(sims, path)
|
||||
fname = os.path.basename(path)
|
||||
p.__name__ = "test_example_file_%s" % fname
|
||||
p.__doc__ = "%s should be a valid configuration" % fname
|
||||
setattr(TestExamples, p.__name__, p)
|
||||
del p
|
||||
test_case.__name__ = "test_example_file_%s" % fname
|
||||
test_case.__doc__ = "%s should be a valid configuration" % fname
|
||||
setattr(TestExamples, test_case.__name__, test_case)
|
||||
del test_case
|
||||
|
||||
|
||||
add_example_tests()
|
||||
|
@@ -6,9 +6,12 @@ import sqlite3
|
||||
|
||||
from unittest import TestCase
|
||||
from soil import exporters
|
||||
from soil import environment
|
||||
from soil import simulation
|
||||
from soil import agents
|
||||
|
||||
from mesa import Agent as MesaAgent
|
||||
|
||||
|
||||
class Dummy(exporters.Exporter):
|
||||
started = False
|
||||
@@ -38,17 +41,17 @@ class Exporters(TestCase):
|
||||
def test_basic(self):
|
||||
# We need to add at least one agent to make sure the scheduler
|
||||
# ticks every step
|
||||
class SimpleEnv(environment.Environment):
|
||||
def init(self):
|
||||
self.add_agent(agent_class=MesaAgent)
|
||||
|
||||
|
||||
num_trials = 5
|
||||
max_time = 2
|
||||
config = {
|
||||
"name": "exporter_sim",
|
||||
"model_params": {"agents": [{"agent_class": agents.BaseAgent}]},
|
||||
"max_time": max_time,
|
||||
"num_trials": num_trials,
|
||||
}
|
||||
s = simulation.from_config(config)
|
||||
s = simulation.Simulation(num_trials=num_trials, max_time=max_time, name="exporter_sim",
|
||||
dump=False, model=SimpleEnv)
|
||||
|
||||
for env in s.run_simulation(exporters=[Dummy], dry_run=True):
|
||||
for env in s.run_simulation(exporters=[Dummy], dump=False):
|
||||
assert len(env.agents) == 1
|
||||
|
||||
assert Dummy.started
|
||||
@@ -60,16 +63,20 @@ class Exporters(TestCase):
|
||||
assert Dummy.total_time == max_time * num_trials
|
||||
|
||||
def test_writing(self):
|
||||
"""Try to write CSV, sqlite and YAML (without dry_run)"""
|
||||
"""Try to write CSV, sqlite and YAML (without no_dump)"""
|
||||
n_trials = 5
|
||||
n_nodes = 4
|
||||
max_time = 2
|
||||
config = {
|
||||
"name": "exporter_sim",
|
||||
"network_params": {"generator": "complete_graph", "n": 4},
|
||||
"agent_class": "CounterModel",
|
||||
"max_time": 2,
|
||||
"model_params": {
|
||||
"network_generator": "complete_graph",
|
||||
"network_params": {"n": n_nodes},
|
||||
"agent_class": "CounterModel",
|
||||
},
|
||||
"max_time": max_time,
|
||||
"num_trials": n_trials,
|
||||
"dry_run": False,
|
||||
"environment_params": {},
|
||||
"dump": True,
|
||||
}
|
||||
output = io.StringIO()
|
||||
s = simulation.from_config(config)
|
||||
@@ -85,7 +92,7 @@ class Exporters(TestCase):
|
||||
"constant": lambda x: 1,
|
||||
},
|
||||
},
|
||||
dry_run=False,
|
||||
dump=True,
|
||||
outdir=tmpdir,
|
||||
exporter_params={"copy_to": output},
|
||||
)
|
||||
@@ -98,12 +105,13 @@ class Exporters(TestCase):
|
||||
|
||||
try:
|
||||
for e in envs:
|
||||
db = sqlite3.connect(os.path.join(simdir, f"{s.name}.sqlite"))
|
||||
dbpath = os.path.join(simdir, f"{s.name}.sqlite")
|
||||
db = sqlite3.connect(dbpath)
|
||||
cur = db.cursor()
|
||||
agent_entries = cur.execute("SELECT * from agents").fetchall()
|
||||
env_entries = cur.execute("SELECT * from env").fetchall()
|
||||
assert len(agent_entries) > 0
|
||||
assert len(env_entries) > 0
|
||||
agent_entries = cur.execute("SELECT times FROM agents WHERE times > 0").fetchall()
|
||||
env_entries = cur.execute("SELECT constant from env WHERE constant == 1").fetchall()
|
||||
assert len(agent_entries) == n_nodes * n_trials * max_time
|
||||
assert len(env_entries) == n_trials * max_time
|
||||
|
||||
with open(os.path.join(simdir, "{}.env.csv".format(e.id))) as f:
|
||||
result = f.read()
|
||||
|
@@ -6,9 +6,11 @@ import networkx as nx
|
||||
from functools import partial
|
||||
|
||||
from os.path import join
|
||||
from soil import simulation, Environment, agents, network, serialization, utils, config
|
||||
from soil import simulation, Environment, agents, network, serialization, utils, config, from_file
|
||||
from soil.time import Delta
|
||||
|
||||
from mesa import Agent as MesaAgent
|
||||
|
||||
ROOT = os.path.abspath(os.path.dirname(__file__))
|
||||
EXAMPLES = join(ROOT, "..", "examples")
|
||||
|
||||
@@ -29,12 +31,13 @@ class TestMain(TestCase):
|
||||
"""A simulation with a base behaviour should do nothing"""
|
||||
config = {
|
||||
"model_params": {
|
||||
"network_params": {"path": join(ROOT, "test.gexf")},
|
||||
"agent_class": "BaseAgent",
|
||||
}
|
||||
"topology": join(ROOT, "test.gexf"),
|
||||
"agent_class": MesaAgent,
|
||||
},
|
||||
"max_time": 1
|
||||
}
|
||||
s = simulation.from_config(config)
|
||||
s.run_simulation(dry_run=True)
|
||||
s.run_simulation(dump=False)
|
||||
|
||||
def test_network_agent(self):
|
||||
"""
|
||||
@@ -62,46 +65,21 @@ class TestMain(TestCase):
|
||||
"""
|
||||
The initial states should be applied to the agent and the
|
||||
agent should be able to update its state."""
|
||||
config = {
|
||||
"version": "2",
|
||||
"name": "CounterAgent",
|
||||
"dry_run": True,
|
||||
"num_trials": 1,
|
||||
"max_time": 2,
|
||||
"model_params": {
|
||||
"topology": {"path": join(ROOT, "test.gexf")},
|
||||
"agents": {
|
||||
"agent_class": "CounterModel",
|
||||
"topology": True,
|
||||
"fixed": [{"state": {"times": 10}}, {"state": {"times": 20}}],
|
||||
},
|
||||
},
|
||||
}
|
||||
s = simulation.from_config(config)
|
||||
env = s.get_env()
|
||||
assert isinstance(env.agents[0], agents.CounterModel)
|
||||
assert env.agents[0].G == env.G
|
||||
assert env.agents[0]["times"] == 10
|
||||
env = Environment()
|
||||
env.add_agent(agents.Ticker, times=10)
|
||||
env.add_agent(agents.Ticker, times=20)
|
||||
|
||||
assert isinstance(env.agents[0], agents.Ticker)
|
||||
assert env.agents[0]["times"] == 10
|
||||
assert env.agents[1]["times"] == 20
|
||||
env.step()
|
||||
assert env.agents[0]["times"] == 11
|
||||
assert env.agents[1]["times"] == 21
|
||||
|
||||
def test_init_and_count_agents(self):
|
||||
"""Agents should be properly initialized and counting should filter them properly"""
|
||||
# TODO: separate this test into two or more test cases
|
||||
config = {
|
||||
"max_time": 10,
|
||||
"model_params": {
|
||||
"agents": [
|
||||
{"agent_class": CustomAgent, "weight": 1, "topology": True},
|
||||
{"agent_class": CustomAgent, "weight": 3, "topology": True},
|
||||
],
|
||||
"topology": {"path": join(ROOT, "test.gexf")},
|
||||
},
|
||||
}
|
||||
s = simulation.from_config(config)
|
||||
env = s.run_simulation(dry_run=True)[0]
|
||||
env = Environment(topology=join(ROOT, "test.gexf"))
|
||||
env.populate_network([CustomAgent.w(weight=1), CustomAgent.w(weight=3)])
|
||||
assert env.agents[0].weight == 1
|
||||
assert env.count_agents() == 2
|
||||
assert env.count_agents(weight=1) == 1
|
||||
@@ -110,26 +88,28 @@ class TestMain(TestCase):
|
||||
|
||||
def test_torvalds_example(self):
|
||||
"""A complete example from a documentation should work."""
|
||||
config = serialization.load_file(join(EXAMPLES, "torvalds.yml"))[0]
|
||||
config["model_params"]["network_params"]["path"] = join(
|
||||
EXAMPLES, config["model_params"]["network_params"]["path"]
|
||||
)
|
||||
s = simulation.from_config(config)
|
||||
env = s.run_simulation(dry_run=True)[0]
|
||||
for a in env.network_agents:
|
||||
skill_level = a.state["skill_level"]
|
||||
if a.id == "Torvalds":
|
||||
assert skill_level == "God"
|
||||
assert a.state["total"] == 3
|
||||
assert a.state["neighbors"] == 2
|
||||
elif a.id == "balkian":
|
||||
assert skill_level == "developer"
|
||||
assert a.state["total"] == 3
|
||||
assert a.state["neighbors"] == 1
|
||||
else:
|
||||
assert skill_level == "beginner"
|
||||
assert a.state["total"] == 3
|
||||
assert a.state["neighbors"] == 1
|
||||
owd = os.getcwd()
|
||||
pyfile = join(EXAMPLES, "torvalds_sim.py")
|
||||
try:
|
||||
os.chdir(os.path.dirname(pyfile))
|
||||
s = simulation.from_py(pyfile)
|
||||
env = s.run_simulation(dump=False)[0]
|
||||
for a in env.network_agents:
|
||||
skill_level = a["skill_level"]
|
||||
if a.node_id == "Torvalds":
|
||||
assert skill_level == "God"
|
||||
assert a["total"] == 3
|
||||
assert a["neighbors"] == 2
|
||||
elif a.node_id == "balkian":
|
||||
assert skill_level == "developer"
|
||||
assert a["total"] == 3
|
||||
assert a["neighbors"] == 1
|
||||
else:
|
||||
assert skill_level == "beginner"
|
||||
assert a["total"] == 3
|
||||
assert a["neighbors"] == 1
|
||||
finally:
|
||||
os.chdir(owd)
|
||||
|
||||
def test_serialize_class(self):
|
||||
ser, name = serialization.serialize(agents.BaseAgent, known_modules=[])
|
||||
@@ -166,31 +146,24 @@ class TestMain(TestCase):
|
||||
assert ser == "BaseAgent"
|
||||
pickle.dumps(ser)
|
||||
|
||||
def test_templates(self):
|
||||
"""Loading a template should result in several configs"""
|
||||
configs = serialization.load_file(join(EXAMPLES, "template.yml"))
|
||||
assert len(configs) > 0
|
||||
|
||||
def test_until(self):
|
||||
config = {
|
||||
"name": "until_sim",
|
||||
"model_params": {
|
||||
"network_params": {},
|
||||
"agents": {
|
||||
"fixed": [
|
||||
{
|
||||
"agent_class": agents.BaseAgent,
|
||||
}
|
||||
]
|
||||
},
|
||||
},
|
||||
"max_time": 2,
|
||||
"num_trials": 50,
|
||||
}
|
||||
s = simulation.from_config(config)
|
||||
runs = list(s.run_simulation(dry_run=True))
|
||||
n_runs = 0
|
||||
|
||||
class CheckRun(agents.BaseAgent):
|
||||
def step(self):
|
||||
nonlocal n_runs
|
||||
n_runs += 1
|
||||
|
||||
n_trials = 50
|
||||
max_time = 2
|
||||
s = simulation.Simulation(
|
||||
model_params=dict(agents=dict(agent_classes=[CheckRun], k=1)),
|
||||
num_trials=n_trials,
|
||||
max_time=max_time,
|
||||
)
|
||||
runs = list(s.run_simulation(dump=False))
|
||||
over = list(x.now for x in runs if x.now > 2)
|
||||
assert len(runs) == config["num_trials"]
|
||||
assert len(runs) == n_trials
|
||||
assert len(over) == 0
|
||||
|
||||
def test_fsm(self):
|
||||
@@ -231,3 +204,21 @@ class TestMain(TestCase):
|
||||
assert when == 2
|
||||
when = a.step()
|
||||
assert when == Delta(a.interval)
|
||||
|
||||
def test_load_sim(self):
|
||||
"""Make sure at least one of the examples can be loaded"""
|
||||
sims = from_file(os.path.join(EXAMPLES, "newsspread", "newsspread_sim.py"))
|
||||
assert len(sims) == 3*3*2
|
||||
for sim in sims:
|
||||
assert sim
|
||||
assert sim.name == "newspread_sim"
|
||||
assert sim.num_trials == 5
|
||||
assert sim.max_steps == 300
|
||||
assert not sim.dump
|
||||
assert sim.model_params
|
||||
assert "ratio_dumb" in sim.model_params
|
||||
assert "ratio_herd" in sim.model_params
|
||||
assert "ratio_wise" in sim.model_params
|
||||
assert "network_generator" in sim.model_params
|
||||
assert "network_params" in sim.model_params
|
||||
assert "prob_neighbor_spread" in sim.model_params
|
@@ -19,13 +19,11 @@ class TestNetwork(TestCase):
|
||||
Load a graph from file if the extension is known.
|
||||
Raise an exception otherwise.
|
||||
"""
|
||||
config = {"network_params": {"path": join(ROOT, "test.gexf")}}
|
||||
G = network.from_config(config["network_params"])
|
||||
G = network.from_topology(join(ROOT, "test.gexf"))
|
||||
assert G
|
||||
assert len(G) == 2
|
||||
with self.assertRaises(AttributeError):
|
||||
config = {"network_params": {"path": join(ROOT, "unknown.extension")}}
|
||||
G = network.from_config(config["network_params"])
|
||||
G = network.from_topology(join(ROOT, "unknown.extension"))
|
||||
print(G)
|
||||
|
||||
def test_generate_barabasi(self):
|
||||
@@ -33,12 +31,12 @@ class TestNetwork(TestCase):
|
||||
If no path is given, a generator and network parameters
|
||||
should be used to generate a network
|
||||
"""
|
||||
cfg = {"params": {"generator": "barabasi_albert_graph"}}
|
||||
cfg = {"generator": "barabasi_albert_graph"}
|
||||
with self.assertRaises(Exception):
|
||||
G = network.from_config(cfg)
|
||||
cfg["params"]["n"] = 100
|
||||
cfg["params"]["m"] = 10
|
||||
G = network.from_config(cfg)
|
||||
G = network.from_params(**cfg)
|
||||
cfg["n"] = 100
|
||||
cfg["m"] = 10
|
||||
G = network.from_params(**cfg)
|
||||
assert len(G) == 100
|
||||
|
||||
def test_save_geometric(self):
|
||||
@@ -54,56 +52,35 @@ class TestNetwork(TestCase):
|
||||
|
||||
def test_networkenvironment_creation(self):
|
||||
"""Networkenvironment should accept netconfig as parameters"""
|
||||
model_params = {
|
||||
"topology": {"path": join(ROOT, "test.gexf")},
|
||||
"agents": {
|
||||
"topology": True,
|
||||
"distribution": [
|
||||
{
|
||||
"agent_class": CustomAgent,
|
||||
}
|
||||
],
|
||||
},
|
||||
}
|
||||
env = environment.Environment(**model_params)
|
||||
env = environment.Environment(topology=join(ROOT, "test.gexf"))
|
||||
env.populate_network(CustomAgent)
|
||||
assert env.G
|
||||
env.step()
|
||||
assert len(env.G) == 2
|
||||
assert len(env.agents) == 2
|
||||
assert env.agents[1].count_agents(state_id="normal") == 2
|
||||
assert env.agents[1].count_agents(state_id="normal", limit_neighbors=True) == 1
|
||||
assert env.agents[0].neighbors == 1
|
||||
assert env.agents[0].count_neighbors() == 1
|
||||
|
||||
def test_custom_agent_neighbors(self):
|
||||
"""Allow for search of neighbors with a certain state_id"""
|
||||
config = {
|
||||
"model_params": {
|
||||
"topology": {"path": join(ROOT, "test.gexf")},
|
||||
"agents": {
|
||||
"topology": True,
|
||||
"distribution": [{"weight": 1, "agent_class": CustomAgent}],
|
||||
},
|
||||
},
|
||||
"max_time": 10,
|
||||
}
|
||||
s = simulation.from_config(config)
|
||||
env = s.run_simulation(dry_run=True)[0]
|
||||
env = environment.Environment()
|
||||
env.create_network(join(ROOT, "test.gexf"))
|
||||
env.populate_network(CustomAgent)
|
||||
assert env.agents[1].count_agents(state_id="normal") == 2
|
||||
assert env.agents[1].count_agents(state_id="normal", limit_neighbors=True) == 1
|
||||
assert env.agents[0].neighbors == 1
|
||||
assert env.agents[0].count_neighbors() == 1
|
||||
|
||||
def test_subgraph(self):
|
||||
"""An agent should be able to subgraph the global topology"""
|
||||
G = nx.Graph()
|
||||
G.add_node(3)
|
||||
G.add_edge(1, 2)
|
||||
distro = agents.calculate_distribution(agent_class=agents.NetworkAgent)
|
||||
aconfig = config.AgentConfig(distribution=distro, topology=True)
|
||||
env = environment.Environment(name="Test", topology=G, agents=aconfig)
|
||||
lst = list(env.network_agents)
|
||||
env = environment.Environment(name="Test", topology=G)
|
||||
env.populate_network(agents.NetworkAgent)
|
||||
|
||||
a2 = env.find_one(node_id=2)
|
||||
a3 = env.find_one(node_id=3)
|
||||
a2 = env.agent(node_id=2)
|
||||
a3 = env.agent(node_id=3)
|
||||
assert len(a2.subgraph(limit_neighbors=True)) == 2
|
||||
assert len(a3.subgraph(limit_neighbors=True)) == 1
|
||||
assert len(a3.subgraph(limit_neighbors=True, center=False)) == 0
|
||||
|
@@ -2,11 +2,12 @@ from unittest import TestCase
|
||||
|
||||
from soil import time, agents, environment
|
||||
|
||||
|
||||
class TestMain(TestCase):
|
||||
def test_cond(self):
|
||||
'''
|
||||
"""
|
||||
A condition should match a When if the concition is True
|
||||
'''
|
||||
"""
|
||||
|
||||
t = time.Cond(lambda t: True)
|
||||
f = time.Cond(lambda t: False)
|
||||
@@ -16,59 +17,59 @@ class TestMain(TestCase):
|
||||
assert w is not f
|
||||
|
||||
def test_cond(self):
|
||||
'''
|
||||
"""
|
||||
Comparing a Cond to a Delta should always return False
|
||||
'''
|
||||
"""
|
||||
|
||||
c = time.Cond(lambda t: False)
|
||||
d = time.Delta(1)
|
||||
assert c is not d
|
||||
|
||||
def test_cond_env(self):
|
||||
'''
|
||||
'''
|
||||
""" """
|
||||
|
||||
times_started = []
|
||||
times_awakened = []
|
||||
times_asleep = []
|
||||
times = []
|
||||
done = 0
|
||||
done = []
|
||||
|
||||
class CondAgent(agents.BaseAgent):
|
||||
|
||||
def step(self):
|
||||
nonlocal done
|
||||
times_started.append(self.now)
|
||||
while True:
|
||||
yield time.Cond(lambda agent: agent.model.schedule.time >= 10)
|
||||
times_asleep.append(self.now)
|
||||
yield time.Cond(lambda agent: agent.now >= 10, delta=2)
|
||||
times_awakened.append(self.now)
|
||||
if self.now >= 10:
|
||||
break
|
||||
done += 1
|
||||
|
||||
env = environment.Environment(agents=[{'agent_class': CondAgent}])
|
||||
done.append(self.now)
|
||||
|
||||
env = environment.Environment()
|
||||
env.add_agent(CondAgent)
|
||||
|
||||
while env.schedule.time < 11:
|
||||
env.step()
|
||||
times.append(env.now)
|
||||
env.step()
|
||||
|
||||
assert env.schedule.time == 11
|
||||
assert times_started == [0]
|
||||
assert times_awakened == [10]
|
||||
assert done == 1
|
||||
assert done == [10]
|
||||
# The first time will produce the Cond.
|
||||
# Since there are no other agents, time will not advance, but the number
|
||||
# of steps will.
|
||||
assert env.schedule.steps == 12
|
||||
assert len(times) == 12
|
||||
assert env.schedule.steps == 6
|
||||
assert len(times) == 6
|
||||
|
||||
while env.schedule.time < 12:
|
||||
env.step()
|
||||
while env.schedule.time < 13:
|
||||
times.append(env.now)
|
||||
env.step()
|
||||
|
||||
assert env.schedule.time == 12
|
||||
assert times == [0, 2, 4, 6, 8, 10, 11]
|
||||
assert env.schedule.time == 13
|
||||
assert times_started == [0, 11]
|
||||
assert times_awakened == [10, 11]
|
||||
assert done == 2
|
||||
assert times_awakened == [10]
|
||||
assert done == [10]
|
||||
# Once more to yield the cond, another one to continue
|
||||
assert env.schedule.steps == 14
|
||||
assert len(times) == 14
|
||||
assert env.schedule.steps == 7
|
||||
assert len(times) == 7
|
||||
|
Reference in New Issue
Block a user