Giter Site home page Giter Site logo

bancaditalia / black-it Goto Github PK

View Code? Open in Web Editor NEW
40.0 7.0 2.0 23.27 MB

Black-box abm calibration kit by the Bank of Italy

Home Page: https://bancaditalia.github.io/black-it/

License: GNU Affero General Public License v3.0

Makefile 1.84% Python 96.79% Shell 1.17% PowerShell 0.21%
agent-based-modeling calibration-toolbox agent-based agent-based-simulation optimization

black-it's Introduction

*

PyPI - Python Version GitHub DOI badge

Black-box abm calibration kit

Black-it is an easy-to-use toolbox designed to help you calibrate the parameters in your agent-based models and simulations (ABMs), using state-of-the-art techniques to sample the parameter search space, with no need to reinvent the wheel.

Models from economics, epidemiology, biology, logistics, and more can be dealt with. The software can be used as-is - if your main interest is the ABM model itself. However, in case your research thing is to, e.g., devise new sampling strategies for ginormous search spaces and highly non-linear model, then you can deploy and test your new ideas on a solid, reusable, modular foundation, in a matter of days, with no need to reimplement all the plumbings from scratch.

Installation

This project requires Python v3.8 or later.

To install the latest version of the package from PyPI:

pip install black-it

Or, directly from GitHub:

pip install git+https://github.com/bancaditalia/black-it.git#egg=black-it

If you'd like to contribute to the package, please read the CONTRIBUTING.md guide.

Installation on Apple Silicon machines

Due to a dependency on the tables package, installing Black-it on Apple Silicon machines can sometimes require specifying the path to the HDF5 executable as explained here.

Quick Example

The GitHub repo of Black-it contains a series ready-to-run calibration examples.

To experiment with them, simply clone the repo and enter the examples folder

git clone https://github.com/bancaditalia/black-it.git
cd black-it/examples

You'll find several scripts and notebooks. The following is the script named main.py, note that copying and pasting the lines below will not work in general as the script needs to be inside the "examples" folder in order to run correctly.

import models.simple_models as md

from black_it.calibrator import Calibrator
from black_it.loss_functions.msm import MethodOfMomentsLoss
from black_it.samplers.best_batch import BestBatchSampler
from black_it.samplers.halton import HaltonSampler
from black_it.samplers.random_forest import RandomForestSampler

true_params = [0.20, 0.20, 0.75]
bounds = [
    [0.10, 0.10, 0.10],  # LOWER bounds
    [1.00, 1.00, 1.00],  # UPPER bounds
]
bounds_step = [0.01, 0.01, 0.01]  # Step size in range between bounds

batch_size = 8
halton_sampler = HaltonSampler(batch_size=batch_size)
random_forest_sampler = RandomForestSampler(batch_size=batch_size)
best_batch_sampler = BestBatchSampler(batch_size=batch_size)

# define a model to be calibrated
model = md.MarkovC_KP

# generate a synthetic dataset to test the calibrator
N = 2000
seed = 1
real_data = model(true_params, N, seed)

# define a loss
loss = MethodOfMomentsLoss()

# define the calibration seed
calibration_seed = 1

# initialize a Calibrator object
cal = Calibrator(
    samplers=[halton_sampler, random_forest_sampler, best_batch_sampler],
    real_data=real_data,
    model=model,
    parameters_bounds=bounds,
    parameters_precision=bounds_step,
    ensemble_size=3,
    loss_function=loss,
    random_state=calibration_seed,
)

# calibrate the model
params, losses = cal.calibrate(n_batches=15)

print(f"True parameters:       {true_params}")
print(f"Best parameters found: {params[0]}")

When the calibration terminates (~half a minute), towards the end of the output you should see the following messages:

True parameters:       [0.2, 0.2, 0.75]
Best parameters found: [0.19 0.21 0.68]

Docs

Black-it calibration is initiated via the Calibrator which, when called, performs three main steps.

First, a Sampler is summoned to suggest a set of promising parameter configurations to explore.

Second, the model to be calibrated is simulated for all the selected parameters.

Third, a specific loss function, measuring the goodness of fitness of the simulation data with respect to the real data, is evaluated.

These steps are performed in a loop, and this allows the samplers to progress towards better parameter values by exploiting the knowledge of previously computed loss functions.

A more detailed explanation of how Black-it works is available here, while the full documentation -complete with examples and tutorials- is available here.

Citing Black-it

A description of the package is available here.

Please consider citing it if you found this package useful for your research

@article{black_it, 
  title = {Black-it: A Ready-to-Use and Easy-to-Extend Calibration Kit for Agent-based Models}, 
  journal = {Journal of Open Source Software},
  publisher = {The Open Journal}, 
  year = {2022}, 
  volume = {7}, 
  number = {79}, 
  pages = {4622}, 
  doi = {10.21105/joss.04622}, 
  url = {https://doi.org/10.21105/joss.04622}, 
  author = {Marco Benedetti and 
            Gennaro Catapano and 
            Francesco {De Sclavis} and 
            Marco Favorito and 
            Aldo Glielmo and 
            Davide Magnanimi and 
            Antonio Muci} 
}

Disclaimer

This package is an outcome of a research project. All errors are those of the authors. All views expressed are personal views, not those of Bank of Italy.


* Credits to Sara Corbo for the logo.

black-it's People

Contributors

aldogl avatar mabene-bi avatar marcofavorito avatar marcofavoritobi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

mmartinoli87 jldc

black-it's Issues

Reproducibility issue of `XGBoostSampler` results for Windows and Linux

Subject of the issue

There is a reproducibility issue for the XGBoostSampler across platforms. In particular, when I use XGBoostSampler on Linux and on Windows, I get different results even if random_state is set correctly.

Your environment

  • OS: Windows 11, Ubuntu 22.04
  • Python version: Python 3.10.9
  • Package Version 0.2.1, commit cffd29e
  • Anything else you consider helpful.

Steps to reproduce

Run the following script on both Windows and Ubuntu:

import numpy as np

from black_it.calibrator import Calibrator
from black_it.loss_functions.msm import MethodOfMomentsLoss
from black_it.samplers.halton import HaltonSampler
from black_it.samplers.xgboost import XGBoostSampler
from black_it.search_space import SearchSpace

xs = np.linspace(0, 1, 6)
ys = np.linspace(0, 1, 6)
xys_list = []
losses_list = []

for x in xs:
    for y in ys:
        xys_list.append([x, y])
        losses_list.append(x**2 + y**2)

xys = np.array(xys_list)
losses = np.array(losses_list)

sampler = XGBoostSampler(batch_size=4, random_state=0)
param_grid = SearchSpace(
    parameters_bounds=np.array([[0, 1], [0, 1]]).T,
    parameters_precision=np.array([0.01, 0.01]),
    verbose=False,
)
new_params = sampler.sample(param_grid, xys, losses)

On Ubuntu, the value of new_params is:

[[0.24 0.26]
 [0.37 0.21]
 [0.43 0.14]
 [0.11 0.04]]

On Windows, the value of new_params is:

[[0.24 0.26]
 [0.19 0.11]
 [0.13 0.22]
 [0.11 0.05]]

Expected behaviour

I expected to get the same result.

Actual behaviour

Different result, see above.

Furhter comments

I understand that the provided details might not be enough for the exact reproduction of the bug. This issue is more a way to point out the reproducibility issue when using the XGBoostSampler.

On the other hand, I suspect this does not depends on black-it, but rather on the underlying implementation of XGBoost, provided by the package xgboost. The following links already document reproducibility issues for that package:

Code for the new ABM paper

I am wondering where is the code for this paper:
Combining search strategies to improve performance in the calibration of economic ABMs
Thanks!

RuntimeError on CI when running Tox on Windows, even if tests succeed

Sometimes the tox command fails on CI when run on Windows, e.g. see https://github.com/bancaditalia/black-it/actions/runs/6051431578/job/16422861344:

=== 87 passed, 19 skipped, 1 deselected, 218 warnings in 188.28s (0:03:08) ====
Traceback (most recent call last):
.pkg: _exit> python C:\hostedtoolcache\windows\Python\3.10.11\x64\lib\site-packages\pyproject_api\_backend.py True poetry.core.masonry.api
  File "C:\hostedtoolcache\windows\Python\3.10.11\x64\lib\site-packages\tox\session\cmd\run\single.py", line 105, in run_command_set
    current_outcome = tox_env.execute(
RuntimeError: <_overlapped.Overlapped object at 0x00000168A4752F70> still has pending operation at deallocation, the process may crash
  py310: OK (350.94=setup[159.83]+cmd[191.11] seconds)
  congratulations :) (353.58 seconds)
Error: Process completed with exit code 1.

Probably it is an asyncio issue inside tox, as shown here for a similar error: https://stackoverflow.com/questions/69833208/runtimeerror-overlapped-overlapped-object-still-has-pending-operation-at-de.

Either fix the error, or do a workaround (e.g. check whether congratulations or py310: OK appears at the end of the output.

pyproject.toml defines pyhon versions not compatible with python 3.11.4 on termux

The expression in pyproject.toml that defines the supported python versions for the project:

[tool.poetry.dependencies]
python = ">=3.8,<3.11"

shows some compatibility problems, albeit in the peculiar test environment I tried:

~/black-it $ poetry shell
The currently activated Python version 3.11.4 is not supported by the project (>=3.8,<3.11).
Trying to find and use a compatible version.

This is python 3.11.4 on Android/termux. I discovered the problem while testing #60 while on the go.

Issue with PyTables on the GitHub Actions runner for MacOS 12.7.1

This issue describes a problem when running tests over MacOS 12.7.1.

The following text is taken by a commit from #77, 2489f3f:

This change was needed because of a nondeterminism in how the macos-12 (=macos-latest at the time of writing) runner image was instantiated by GitHub Actions.
In particular, for runner version 2.311.0, the operating system was nondeterministically chosen between 12.6.9 and 12.7.1, as it can be seen in these two GH runs:

This is a known issue in the community: see actions/runner-images#8642

Furthermore, at the time of writing, it is suspected that Python code that uses pytables is not stable over macos at version 12.7.1 (but this problem does not occur on v12.6.9!), as witnessed by this issue: PyTables/PyTables#1093

What happened in our CI workflow is that tests resulted in a flaky outcome, but not because of our tests, but due to the nondeterminism in how the macos runner was instantiated by GitHub Actions.

This was not our unique attempt. In fact, we first tried to improve the preliminary configuration steps for the testing environment, as follows:

This attempt consisted in installing HDF5 and C-blosc explicitly in the preliminary steps on CI for MacOS images. By the way, this step was part of the installation instructions of PyTables v3.9.2: https://github.com/PyTables/PyTables/blob/v3.9.2/README.rst#installation , although it seems this step is not actually needed.
Moreover, as explained here: https://stackoverflow.com/questions/73029883/could-not-find-hdf5-installation-for-pytables-on-m1-mac, sometimes must be explicitly set the environment path variables where HDF5 ahd C-blosc are installed
For some reason this is not needed on Ubuntu and Windows runners.

However, despite our efforts in this direction, the issue with pytables persisted. From the logs of the CI: (https://github.com/bancaditalia/black-it/actions/runs/7121188681/job/19389914846?pr=78#step:5:62)

Fatal Python error: Illegal instruction

Current thread 0x000000011783c600 (most recent call first):
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/tables/node.py", line 246 in __init__
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/tables/leaf.py", line 264 in __init__
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/tables/carray.py", line 200 in __init__
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/tables/earray.py", line 143 in __init__
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/tables/file.py", line 1345 in create_earray
  File "/Users/runner/work/black-it/black-it/black_it/utils/json_pandas_checkpointing.py", line 211 in save_calibrator_state
  File "/Users/runner/work/black-it/black-it/tests/test_utils/test_pandas_json_checkpointing.py", line 58 in test_save_and_load_calibrator_state
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/_pytest/python.py", line 194 in pytest_pyfunc_call
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/pluggy/_callers.py", line 77 in _multicall
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/pluggy/_manager.py", line 115 in _hookexec
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/pluggy/_hooks.py", line 493 in __call__
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/_pytest/python.py", line 1792 in runtest
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/_pytest/runner.py", line 169 in pytest_runtest_call
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/pluggy/_callers.py", line 77 in _multicall
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/pluggy/_manager.py", line 115 in _hookexec
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/pluggy/_hooks.py", line 493 in __call__
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/_pytest/runner.py", line 262 in <lambda>
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/_pytest/runner.py", line 341 in from_call
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/_pytest/runner.py", line 261 in call_runtest_hook
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/_pytest/runner.py", line 222 in call_and_report
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/_pytest/runner.py", line 133 in runtestprotocol
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/_pytest/runner.py", line 114 in pytest_runtest_protocol
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/pluggy/_callers.py", line 77 in _multicall
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/pluggy/_manager.py", line 115 in _hookexec
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/pluggy/_hooks.py", line 493 in __call__
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/_pytest/main.py", line 350 in pytest_runtestloop
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/pluggy/_callers.py", line 77 in _multicall
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/pluggy/_manager.py", line 115 in _hookexec
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/pluggy/_hooks.py", line 493 in __call__
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/_pytest/main.py", line 325 in _main
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/_pytest/main.py", line 271 in wrap_session
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/_pytest/main.py", line 318 in pytest_cmdline_main
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/pluggy/_callers.py", line 77 in _multicall
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/pluggy/_manager.py", line 115 in _hookexec
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/pluggy/_hooks.py", line 493 in __call__
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/_pytest/config/__init__.py", line 169 in main
  File "/Users/runner/work/black-it/black-it/.tox/py310/lib/python3.10/site-packages/_pytest/config/__init__.py", line 192 in console_main
  File "/Users/runner/work/black-it/black-it/.tox/py310/bin/pytest", line 8 in <module>

The purpose of this GH issue is to keep track of the workaround, and try to solve it as soon as the problem is solved by GH Actions or PyTables.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.