{"id":28089345,"url":"https://github.com/socrats/egttools","last_synced_at":"2025-05-13T12:57:09.309Z","repository":{"id":36987973,"uuid":"242180332","full_name":"Socrats/EGTTools","owner":"Socrats","description":"Toolbox for Evolutionary Game Theory.","archived":false,"fork":false,"pushed_at":"2025-05-02T13:18:57.000Z","size":48095,"stargazers_count":92,"open_issues_count":6,"forks_count":23,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-05-02T14:02:07.404Z","etag":null,"topics":["cpp","evolutionary-dynamics","evolutionary-game-theory","python","simulation","social-dynamics"],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Socrats.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":"CITATION.cff","codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2020-02-21T16:14:28.000Z","updated_at":"2025-05-02T12:55:23.000Z","dependencies_parsed_at":"2023-10-03T19:20:49.067Z","dependency_job_id":"8a8494a5-f36b-4cfe-be96-257975197552","html_url":"https://github.com/Socrats/EGTTools","commit_stats":{"total_commits":864,"total_committers":4,"mean_commits":216.0,"dds":"0.10532407407407407","last_synced_commit":"a6aed875a9bcf702ba1d289394bfb3e0b0142129"},"previous_names":[],"tags_count":31,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Socrats%2FEGTTools","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Socrats%2FEGTTools/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Socrats%2FEGTTools/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Socrats%2FEGTTools/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Socrats","download_url":"https://codeload.github.com/Socrats/EGTTools/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253948346,"owners_count":21988953,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cpp","evolutionary-dynamics","evolutionary-game-theory","python","simulation","social-dynamics"],"created_at":"2025-05-13T12:57:08.499Z","updated_at":"2025-05-13T12:57:09.290Z","avatar_url":"https://github.com/Socrats.png","language":"C++","funding_links":[],"categories":[],"sub_categories":[],"readme":"![EGTtools](docs/images/logo-full.png)\n\n# EGTTools – Evolutionary Game Theory Toolbox\n\n[![PyPI](https://img.shields.io/pypi/v/egttools)](https://pypi.org/project/egttools/)\n[![Docs](https://img.shields.io/badge/docs-ReadTheDocs-green)](https://egttools.readthedocs.io/)\n[![Live Docs](https://img.shields.io/badge/docs-latest-blue)](https://efernandez.eu/EGTTools/)\n[![Build Status](https://github.com/Socrats/EGTTools/actions/workflows/wheels.yml/badge.svg?branch=master)](https://github.com/Socrats/EGTTools/actions/workflows/wheels.yml)\n[![Gitter](https://badges.gitter.im/EGTTools/community.svg)](https://gitter.im/EGTTools/community?utm_source=badge\u0026utm_medium=badge\u0026utm_campaign=pr-badge)\n[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/Socrats/EGTTools/HEAD?labpath=docs%2Fexamples)\n[![DOI](https://zenodo.org/badge/242180332.svg)](https://zenodo.org/badge/latestdoi/242180332)\n\nEGTTools is a modular toolbox for simulating and analyzing **evolutionary dynamics** in strategic environments. It\ncombines **analytical methods** (replicator dynamics, fixation probabilities) and **numerical simulations** (Monte Carlo\nwith parallel C++ backends) under a unified interface.\n\n---\n\n## 📑 Table of Contents\n\nTesting \u0026 Continuous Integration\n\n- [Features](#-features)\n- [Installation](#-installation)\n- [Platform Notes](#-platform-notes)\n- [Advanced Configuration](#-advanced-configuration-blas-openmp-vcpkg)\n- [Build from Source](#-build-from-source-with-vcpkg)\n- [Usage Examples](#-usage-examples)\n- [Documentation](#-documentation)\n- [Testing \u0026 CI](#-testing--continuous-integration)\n- [Citation](#-citation)\n- [License](#-license)\n- [Acknowledgements](#-acknowledgements)\n- [Caveats](#-caveats)\n\n## 🚀 Features\n\n- ✅ Replicator dynamics for 2-strategy and N-player games\n- ✅ Stochastic dynamics using the pairwise comparison rule\n- ✅ Numerical simulation of evolutionary processes in finite populations\n- ✅ Monte Carlo estimation of fixation probabilities and strategy distributions\n- ✅ OpenMP parallelization for large-scale simulations (Linux/macOS)\n- ✅ Modular game and strategy framework, extensible in both Python and C++\n- ✅ Visual tools for plotting gradients, stationary distributions, and simplex diagrams\n- ✅ Support for Boost, Eigen, and BLAS integration (configurable)\n- ✅ Cross-platform wheels (Linux, macOS, Windows; x86_64 and ARM64)\n\n## 📦 Installation\n\nEGTTools is distributed via PyPI and includes prebuilt wheels for major platforms:\n\n| Platform        | Architectures         | Python Versions | OpenMP Supported |\n|-----------------|-----------------------|-----------------|------------------|\n| Linux (x86_64)  | x86_64                | 3.10 – 3.12     | ✅ Yes            |\n| macOS (x86/arm) | x86_64, arm64 (M1/M2) | 3.10 – 3.12     | ✅ Yes            |\n| Windows         | x86_64, arm64         | 3.10 – 3.12     | ❌ Not available  |\n\n### ▶️ Install with pip\n\n```bash\npip install egttools\n```\n\nFor a more reliable installation on macOS with conda-based environments:\n\nconda install numpy scipy matplotlib networkx seaborn\npip install egttools --no-deps\n\n---\n\n## 🖥️ Platform Notes\n\n### 🐧 Linux\n\n- OpenMP is fully supported and enabled by default.\n- Wheels are built with optimized BLAS/LAPACK and Boost.\n- Recommended for high-performance simulation runs.\n\n### 🍎 macOS (Intel or Apple Silicon)\n\n- Supported on both `x86_64` and `arm64`.\n- OpenMP is enabled by default and linked via `libomp`.\n- If using `conda`, prefer `miniforge` or `mambaforge` for ABI compatibility.\n- To skip dependency resolution and control packages manually:\n\n```bash\npip install egttools --no-deps\nconda install numpy scipy matplotlib networkx seaborn\n````\n\n### 🪟 Windows (x86_64 and ARM64)\n\n- Windows wheels are available for both Intel and ARM architectures.\n- OpenMP is currently not available on Windows.\n- Simulations will fall back to single-threaded mode.\n- BLAS/LAPACK can be enabled via conda or system libraries if building from source.\n\n---\n\n## ⚙️ Advanced Configuration (BLAS, OpenMP, vcpkg)\n\nThe C++ backend of EGTTools supports several build-time options that can be toggled when building from source:\n\n| Feature       | CMake Option               | Default          | Description                                     |\n|---------------|----------------------------|------------------|-------------------------------------------------|\n| OpenMP        | `-DEGTTOOLS_USE_OPENMP=ON` | ON (Linux/macOS) | Enables parallel computation for simulations    |\n| BLAS/LAPACK   | `-DEGTTOOLS_USE_BLAS=ON`   | OFF              | Enables matrix acceleration (e.g., OpenBLAS)    |\n| Use vcpkg     | `-DEGTTOOLS_USE_VCPKG=ON`  | ON               | Automatically fetches Boost and Eigen           |\n| Disable vcpkg | `-DEGTTOOLS_USE_VCPKG=OFF` |                  | Allows using system-provided libraries manually |\n\n### 🧰 When to disable vcpkg\n\nYou may want to disable `vcpkg` in CI environments or when using a distribution that provides all necessary dependencies\nsystem-wide. To do this:\n\n```bash\ncmake -DEGTTOOLS_USE_VCPKG=OFF .\n```\n\nIn this case, you are responsible for ensuring that compatible versions of Boost and Eigen are available in your system\npaths.\n\n---\n\n## 🔧 Build from Source (with vcpkg)\n\nTo build EGTTools from source with all dependencies managed via `vcpkg`, run:\n\n```bash\ngit clone --recurse-submodules https://github.com/Socrats/EGTTools.git\ncd EGTTools\npip install .\n```\n\nTo configure optional features manually, such as OpenMP or BLAS support:\n\n```bash\ncmake -DEGTTOOLS_USE_OPENMP=ON -DEGTTOOLS_USE_BLAS=ON -DEGTTOOLS_USE_VCPKG=OFF .\nmake\n```\n\nIf using `conda`, make sure to activate your environment first and ensure that Python, NumPy, and compiler toolchains\nare compatible.\n\n---\n## 🧪 Usage Examples\n\n### Calculate Gradient of Selection\n\n```python\nfrom egttools.analytical import PairwiseComparison\nfrom egttools.games import Matrix2PlayerGameHolder\n\nA = [[-0.5, 2], [0, 0]]\ngame = Matrix2PlayerGameHolder(2, A)\nevolver = PairwiseComparison(100, game)\n\ngradient = evolver.calculate_gradient_of_selection(beta=1.0, state=[10, 90])\n```\n\n---\n\n### Estimate fixation probability numerically\n\n```python\nfrom egttools.numerical import PairwiseComparisonNumerical\nfrom egttools.games import Matrix2PlayerGameHolder\n\nA = [[-0.5, 2], [0, 0]]\ngame = Matrix2PlayerGameHolder(2, A)\nnumerical_evolver = PairwiseComparisonNumerical(game, population_size=100, cache=1_000_000)\nfp = numerical_evolver.estimate_fixation_probability(\n    index_invading_strategy=1,\n    index_resident_strategy=0,\n    nb_runs=500,\n    nb_generations=5000,\n    beta=1.0\n)\n```\n\n\n### More Examples of usage\n\nThe [Analytical example](docs/examples/hawk_dove_dynamics.ipynb) is a jupyter notebook which analyses analytically the\nevolutionary dynamics in a (2-person, 2-actions, one-shot) Hawk-Dove game.\n\nThe [Numerical example](docs/examples/normal_form_game_mc_simulations.ipynb) is a jupyter notebook which analyses\nthrough numerical simulations the evolutionary dynamics in a (2-person, 2-actions, one-shot) Hawk-Dove game.\n\nThe [Invasion example](docs/examples/plot_invasion_diagram.ipynb) is a jupyter notebook calculates the fixation\nprobabilities and stationary distribution of a Normal Form Game with 5 strategies and then plots an invasion diagram.\n\nThe [Plot 2 Simplex](docs/examples/plot_simplex.ipynb) is a jupyter notebook that shows how to use EGTtools to plot the\nevolutionary dynamics in a 2 Simplex (a triangle), both for infinite and finite populations.\n\nYou can also check all these notebooks and a bit more on\nthis [tutorial repository](https://github.com/Socrats/egt-tutorial)\n\nFor example, assuming the following payoff matrix:\n\n![A=\\begin{pmatrix} -0.5 \u0026 2 \\\\ 0 \u0026 0 \\end{pmatrix}](https://latex.codecogs.com/gif.latex?A=\\begin{pmatrix}\u0026space;-0.5\u0026space;\u0026\u0026space;2\u0026space;\\\\\\\\\u0026space;0\u0026space;\u0026\u0026space;0\u0026space;\\end{pmatrix})\n\nYou can plot the gradient of selection in a finite population of \\(Z=100\\) individuals and assuming and intensity of\nselection ![\\beta=1](https://latex.codecogs.com/gif.latex?\\beta=1) in the following way:\n\n```python\nimport numpy as np\nfrom egttools.analytical import PairwiseComparison\nfrom egttools.games import Matrix2PlayerGameHolder\n\nbeta = 1;\nZ = 100;\nnb_strategies = 2;\nA = np.array([[-0.5, 2.], [0., 0.]])\npop_states = np.arange(0, Z + 1, 1)\n\ngame = Matrix2PlayerGameHolder(nb_strategies, payoff_matrix=A)\n\n# Instantiate evolver and calculate gradient\nevolver = PairwiseComparison(population_size=Z, game=game)\ngradients = np.array([evolver.calculate_gradient_of_selection(beta, np.array([x, Z - x])) for x in range(Z + 1)])\n```\n\nAfterward, you can plot the results with:\n\n```python\nfrom egttools.plotting import plot_gradients\n\nplot_gradients(gradients, figsize=(4, 4), fig_title=\"Hawk-Dove game stochastic dynamics\",\n               marker_facecolor='white',\n               xlabel=\"frequency of hawks (k/Z)\", marker=\"o\", marker_size=20, marker_plot_freq=2)\n```\n\n![Gradient of selection](docs/images/hawk_dove_analytical_gradient.png)\n\nAnd you can plot the stationary distribution for a mutation\nrate ![\\mu=1eˆ{-3}](https://latex.codecogs.com/gif.latex?\\mu=1e-3) with:\n\n```python\nimport matplotlib.pyplot as plt\nfrom egttools.utils import calculate_stationary_distribution\n\ntransitions = evolver.calculate_transition_matrix(beta, mu=1e-3)\nstationary_with_mu = calculate_stationary_distribution(transitions.transpose())\nfig, ax = plt.subplots(figsize=(5, 4))\nfig.patch.set_facecolor('white')\nlines = ax.plot(np.arange(0, Z + 1) / Z, stationary_with_mu)\nplt.setp(lines, linewidth=2.0)\nax.set_ylabel('stationary distribution', size=16)\nax.set_xlabel('$k/Z$', size=16)\nax.set_xlim(0, 1)\nplt.show()\n```\n\n![Stationary distribution](docs/images/hawk_dove_analytical_full_sd.png)\n\nWe can get the same results through numerical simulations. The error will depend on how many independent simulations\nyou perform and for how long you let the simulation run. While a future implementation will offer an adaptive method to\nvary these parameters depending on the variations between the estimated distributions, for the moment it is important\nthat you let the simulation run for enough generations after it has achieved a steady state. Here is a comparison\nbetween analytical and numerical results:\n\n```python\nfrom egttools.numerical import PairwiseComparisonNumerical\nfrom egttools.games import NormalFormGame\n\n# Instantiate the game\ngame = NormalFormGame(1, A)\nnumerical_evolver = PairwiseComparisonNumerical(Z, game, 1000000)\n\n# We do this for different betas\nbetas = np.logspace(-4, 1, 50)\nstationary_points = []\n# numerical simulations\nfor i in range(len(betas)):\n    stationary_points.append(numerical_evolver.stationary_distribution(30, int(1e6), int(1e3),\n                                                                       betas[i], 1e-3))\nstationary_points = np.asarray(stationary_points)\n# Now we estimate the probability of Cooperation for each possible state\nstate_frequencies = np.arange(0, Z + 1) / Z\ncoop_level = np.dot(state_frequencies, stationary_points.T)\n```\n\nLastly, we plot the results:\n\n```python\nfrom sklearn.metrics import mean_squared_error\n\nmse = mean_squared_error(1 - coop_level_analytical, coop_level)\n\n# Finally, we plot and compare visually (and check how much error we get)\nfig, ax = plt.subplots(figsize=(7, 5))\n# ax.scatter(betas, coop_level, label=\"simulation\")\nax.scatter(betas, coop_level_analytical, marker='x', label=\"analytical\")\nax.scatter(betas, coop_level, marker='o', label=\"simulation\")\nax.text(0.01, 0.535, 'MSE = {0:.3e}'.format(mse), style='italic',\n        bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10})\nax.legend()\nax.set_xlabel(r'$\\beta$', fontsize=15)\nax.set_ylabel('Cooperation level', fontsize=15)\nax.set_xscale('log')\nplt.show()\n```\n\n![Comparison numerical analytical](docs/images/hawk_dove_comparison.png)\n\nFinally, you may also visualize the result of independent simulations:\n\n```python\ninit_states = np.random.randint(0, Z + 1, size=10, dtype=np.uint64)\noutput = []\nfor i in range(10):\n    output.append(evolver.run(int(1e6), 1, 1e-3,\n                              [init_states[i], Z - init_states[i]]))\n# Plot each year's time series in its own facet\nfig, ax = plt.subplots(figsize=(5, 4))\n\nfor run in output:\n    ax.plot(run[:, 0] / Z, color='gray', linewidth=.1, alpha=0.6)\nax.set_ylabel('k/Z')\nax.set_xlabel('generation')\nax.set_xscale('log')\n```\n\n![Comparison numerical analytical](docs/images/hawk_dove_indep_runs.png)\n\n### Plotting the dynamics in a 2 Simplex\n\nEGTtools can also be used to visualize the evolutionary dynamics in a 2 Simplex. In the example bellow, we use the\n`egttools.plotting.plot_replicator_dynamics_in_simplex` which calculates the gradients on a simplex given an initial\npayoff matrix and returns a `egttools.plotting.Simplex2D` object which can be used to plot the 2 Simplex.\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom egttools.plotting import plot_replicator_dynamics_in_simplex\n\npayoffs = np.array([[1, 0, 0],\n                    [0, 2, 0],\n                    [0, 0, 3]])\ntype_labels = ['A', 'B', 'C']\n\nfig, ax = plt.subplots(figsize=(10, 8))\n\nsimplex, gradient_function, roots, roots_xy, stability = plot_replicator_dynamics_in_simplex(payoffs, ax=ax)\n\nplot = (simplex.add_axis(ax=ax)\n        .draw_triangle()\n        .draw_gradients(zorder=0)\n        .add_colorbar()\n        .add_vertex_labels(type_labels)\n        .draw_stationary_points(roots_xy, stability)\n        .draw_trajectory_from_roots(gradient_function,\n                                    roots,\n                                    stability,\n                                    trajectory_length=15,\n                                    linewidth=1,\n                                    step=0.01,\n                                    color='k', draw_arrow=True,\n                                    arrowdirection='right',\n                                    arrowsize=30, zorder=4, arrowstyle='fancy')\n        .draw_scatter_shadow(gradient_function, 300, color='gray', marker='.', s=0.1, zorder=0)\n        )\n\nax.axis('off')\nax.set_aspect('equal')\n\nplt.xlim((-.05, 1.05))\nplt.ylim((-.02, simplex.top_corner + 0.05))\nplt.show()\n```\n\n![2 Simplex dynamics in infinite populations](docs/images/simplex_example_infinite_pop_1.png)\n\nThe same can be done for finite populations, with the added possibility to plot the stationary distribution inside the\ntriangle (see [simplex plotting](docs/examples/plot_simplex.ipynb)\nand [simplified simplex plotting](docs/examples/plot_simplex_simplified.ipynb)\nfor a more in-depth example).\n\n---\n\n## 📚 Documentation\n\n- 📘 API Reference (ReadTheDocs): [https://egttools.readthedocs.io](https://egttools.readthedocs.io)\n- 🌍 Live Tutorial \u0026 Examples: [https://efernandez.eu/EGTTools/](https://efernandez.eu/EGTTools/)\n\nYou can find a full description of available games, strategies, and simulation methods, along with Jupyter notebooks and\nreal-world use cases.\n\n---\n\n## 🧪 Testing \u0026 Continuous Integration\n\nEGTTools uses GitHub Actions for full CI/CD automation:\n\n- 🧱 **`wheels.yml`** builds wheels for all platforms (Linux, macOS, Windows; x86_64 and arm64)\n- 📘 **`docs.yml`** builds documentation and deploys it to GitHub Pages and ReadTheDocs\n- ✅ Unit tests run with `pytest` and are included in each CI matrix build\n- 🧪 Python stub files are auto-generated from `pybind11` bindings for better typing support\n\nTo run tests locally:\n\n```bash\npytest tests\n```\n\nYou can also build and validate docs locally with:\n\n```bash\ncd docs\nmake html\n```\n\n---\n\n## 📖 Citation\n\nIf you use EGTtools in your publications, please cite it in the following way with bibtex:\n\n```latex\n@article{Fernandez2023,\n  author = {Fernández Domingos, Elias and Santos, Francisco C. and Lenaerts, Tom},\n  title = {EGTtools: Evolutionary game dynamics in Python},\n  journal = {iScience},\n  volume = {26},\n  number = {4},\n  pages = {106419},\n  year = {2023},\n  issn = {2589-0042},\n  doi = {https://doi.org/10.1016/j.isci.2023.106419}\n}\n```\n\nOr in text format:\n\n```\nFernández Domingos, E., Santos, F. C. \u0026 Lenaerts, T. EGTtools: Evolutionary game dynamics in Python. iScience 26, 106419 (2023).\n```\n\nAnd to cite the current version of EGTtools you can use:\n\n```latex\n@misc{Fernandez2020,\n  author = {Fernández Domingos, Elias},\n  title = {EGTTools: Toolbox for Evolutionary Game Theory (0.1.12)},\n  year = {2022},\n  month = {Dec},\n  journal = {Zenodo},\n  doi = {10.5281/zenodo.7458631}\n}\n```\n\nMoreover, you may find our article at [here](https://www.cell.com/iscience/pdf/S2589-0042(23)00496-0.pdf).\n\n---\n\n## 📄 License\n\nEGTTools is released under the [GPLv3 or later](LICENSE).\n\n---\n\n## 🙏 Acknowledgements\n\nDeveloped and maintained by [Elias Fernández](https://efernandez.eu).\n\n* Great parts of this project have been possible thanks to the help of\n  [Yannick Jadoul](https://github.com/YannickJadoul) author of\n  [Parselmouth](https://github.com/YannickJadoul/Parselmouth)\n  and [Eugenio Bargiacchi](https://github.com/Svalorzen) author of [AIToolBox](https://github.com/Svalorzen/AI-Toolbox).\n  They are both great programmers and scientists, so it is always a good idea to check out their work.\n* EGTtools makes use of the amazing [pybind11](https://github.com/pybind/pybind11). library to provide a Python\n  interface for optimized monte-carlo simulations written in C++.\n\n---\n\n## ⚠️ Caveats\n\n- On **Windows**, OpenMP is currently not supported. All simulations will run single-threaded.\n- On **macOS**, OpenMP is supported but performance may depend on the installed `libomp`. If using `conda`, make sure `llvm-openmp` is available.\n- Wheels are only built for **Python 3.10 – 3.12**.\n- Numerical simulations require large RAM allocations when using large population sizes or caching; ensure you configure the `cache` size accordingly.\n- Advanced users building from source should ensure Boost, Eigen, and BLAS/LAPACK libraries are compatible with their compiler toolchain.\n\n---","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsocrats%2Fegttools","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsocrats%2Fegttools","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsocrats%2Fegttools/lists"}