Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cleanup, move some things around, add functionality #134

Open
wants to merge 150 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
150 commits
Select commit Hold shift + click to select a range
5ced119
Did initial reformatting (with black) and a little cleanup.
crh23 Jul 3, 2019
d86bf04
Removed most abce dependance, except for gui function, and some unnec…
KloskaT Jul 3, 2019
bbe554f
A bit more aesthetic cleanup
crh23 Jul 3, 2019
b4783d2
Cleaned up the init file for InsuranceSimulation and added a function…
KloskaT Jul 3, 2019
77f7972
Removed ABCE. There are probably some simplifications that can be mad…
crh23 Jul 3, 2019
bf53795
More cleanup and minor fixes.
crh23 Jul 4, 2019
8c9b867
Added docstring to every function in the simulation class. Small typo…
KloskaT Jul 4, 2019
2b72fb9
Removed redundant functions from insurancesimulation: reinsurance_cap…
KloskaT Jul 5, 2019
202b1ab
Reimplemented replication using file names instead of replic_id, more…
crh23 Jul 5, 2019
1a01d78
Minor performance improvements
crh23 Jul 5, 2019
83f3cc6
Added docstring to all functions in metainsuranceorg. Also created fu…
KloskaT Jul 5, 2019
829c001
More minor performance improvements
crh23 Jul 8, 2019
facfeba
Made the get_mean_std function take a tuple as an argument to enable …
crh23 Jul 8, 2019
b9ab7e4
Added comments, cleaned up remnants of parent functions.
KloskaT Jul 8, 2019
919537b
Added comments. Removed some redundant lines.
KloskaT Jul 8, 2019
e95bd39
Created file and class that acts as central bank in awarding agents i…
KloskaT Jul 8, 2019
53810ad
Mostly just refactoring/comments
crh23 Jul 9, 2019
c87453f
Added docstring to all methods. Merged create_reinrisk into ask_reins…
KloskaT Jul 9, 2019
882d0bf
Apply black.py to all python files. Just a code formatter, zero chang…
crh23 Jul 9, 2019
9713c53
Small change
crh23 Jul 9, 2019
5c0f021
Added docstring to all methods. General clean up.
KloskaT Jul 9, 2019
697e7f6
Small change
crh23 Jul 9, 2019
a346ab8
Bugfix (I think) and small improvement (bigger for more risk categories)
crh23 Jul 9, 2019
7e52a5c
Added method to allow continually updating network in same figure with
KloskaT Jul 10, 2019
1ea7ae3
Removed last of abce references.
KloskaT Jul 10, 2019
b70f504
Updated to include new arguments, removed abce, altered plotting section
KloskaT Jul 10, 2019
9493a18
Update README.md
KloskaT Jul 10, 2019
c742f3a
Save state now includes events. Removed abce from resume.py and now w…
KloskaT Jul 11, 2019
2ea0bcc
Merge branch 'master' of https://github.com/KloskaT/isle
KloskaT Jul 11, 2019
d3080e7
Fixed resume.py
KloskaT Jul 11, 2019
fbc6944
Cleaned up, added central bank to award interest
KloskaT Jul 11, 2019
3408f8b
Starting to add docstrings and set relevant attributes and methods to…
crh23 Jul 10, 2019
65e944f
Merge branch 'cleanup'
crh23 Jul 11, 2019
64810af
Fix simulation saving
crh23 Jul 12, 2019
1ccb7f1
black.py
crh23 Jul 12, 2019
2edc655
Merge branch 'thomas'
crh23 Jul 12, 2019
c466b9b
Merge branch 'privatise'
crh23 Jul 12, 2019
d8c22ad
Cleanup after merge
crh23 Jul 12, 2019
444bc28
Moved agent creating code into insurancesimulation.py from start.py
crh23 Jul 12, 2019
d8fcce6
Fixed error where reinsurance were initialized using insurance firm IDs
KloskaT Jul 15, 2019
c82025a
Attempting to get resume working, not successfully (pickle?!)
crh23 Jul 12, 2019
8470ae3
Minor tweaks
crh23 Jul 16, 2019
25fb93b
Added animated pie chart for percent contracts on same figure, for bo…
KloskaT Jul 16, 2019
361f02a
Minor tweaks
crh23 Jul 16, 2019
d0c1c45
Merge remote-tracking branch 'thomas/master'
crh23 Jul 16, 2019
bbc1b08
Fixed bug due to slightly improper merge
crh23 Jul 16, 2019
6c7bc05
Implemented scaling of insurance (not reinsurance) premiums and risk …
crh23 Jul 16, 2019
465adf3
Fixed bug due to slightly improper merge
crh23 Jul 16, 2019
3b4fc96
Merge branch 'bigger_is_better'
crh23 Jul 16, 2019
1130cab
Lots of little aesthetic cleanups
crh23 Jul 16, 2019
8d225fa
Lots of little aesthetic cleanups
crh23 Jul 16, 2019
e093301
Slightly updated the readme
crh23 Jul 16, 2019
f7d3bfd
Can now call either pie plots or timeseries from command line when ru…
KloskaT Jul 17, 2019
5cc359f
Necessary network data is now saved. Added class that animates (and s…
KloskaT Jul 17, 2019
681c287
Added condition for saving network data, set true by default.
KloskaT Jul 17, 2019
eccc94b
Updated README for visualisation.
KloskaT Jul 17, 2019
7d56c23
Added some classes and lots of type hints
crh23 Jul 17, 2019
94f5e5f
Added visualisation_paper3.py stuff to file, inluding histogram and C…
KloskaT Jul 17, 2019
c3c6376
Remove replicid argument
crh23 Jul 17, 2019
64d6fe5
Commented. Now saves all to 'figures' folder. Updated visualisation R…
KloskaT Jul 18, 2019
88816ce
Fixed a bug causing contracts to be lost
crh23 Jul 18, 2019
0f08920
Even more type hints
crh23 Jul 18, 2019
e233b27
Merge branch 'dataclasses_and_type_hints'
crh23 Jul 18, 2019
9bccdd2
Merge remote-tracking branch 'chris/master'
crh23 Jul 18, 2019
b08ce8c
Can plot specific data types against each other for all riskmodels, w…
KloskaT Jul 18, 2019
e7f442a
Misc cleanups
crh23 Jul 19, 2019
7f910e8
Allow firms to issue multi-layered requests for reinsurance
crh23 Jul 19, 2019
bb16e69
Properly integrated metaplotter_pl_timescale_additional_measures_alph…
KloskaT Jul 19, 2019
868a7d8
Updated README for visualisation.
KloskaT Jul 19, 2019
695929d
Start creating a way for firms to track reinsurance
crh23 Jul 19, 2019
aee9048
Merge in changes for python 3.6 (and notes from meeting)
crh23 Jul 23, 2019
5da97e5
Made multi-layer reinsurance work. Also fix for python 3.6
crh23 Jul 23, 2019
36900c9
Add provision for what should happen when paying a non-operational firm
crh23 Jul 23, 2019
8cfc49c
Apply black.py
crh23 Jul 23, 2019
771083b
Change excess to limit
crh23 Jul 23, 2019
bdbaf64
Little bit of cleanup
crh23 Jul 24, 2019
c7cff96
Merge branch 'layered_reinsurance'
crh23 Jul 24, 2019
3aca163
Both types of firms going bankrupt can now be bought by others. If no…
KloskaT Jul 24, 2019
8b9aa5d
Changed event damage values so they are just a number not array (allo…
KloskaT Jul 24, 2019
b78513b
Merge remote-tracking branch 'thomas/master'
crh23 Jul 25, 2019
9b17456
Network data now saved (to separate file) using logger for both types…
KloskaT Jul 25, 2019
75ae851
Deleted redundant plotter files. Visualisation prints when each reque…
KloskaT Jul 25, 2019
a3dca48
Added save network to start.py for single run using logger object.
KloskaT Jul 25, 2019
10a8f1e
Creates figures folder if not already existing.
KloskaT Jul 25, 2019
c23aefd
Checks, creates, and writes animation to figures folder
KloskaT Jul 25, 2019
747b188
Added regulator to central bank based on solvency ii, issues warning …
KloskaT Jul 29, 2019
555f54b
Added method to central bank that grants disaster relief aid to firms…
KloskaT Jul 30, 2019
6c389d6
Added file to load different data sets and compare them by plot or test
KloskaT Jul 31, 2019
d1756a2
Removed redundant method
KloskaT Aug 1, 2019
05739aa
Regulator changed such that it includes reinsurance contract values a…
KloskaT Aug 1, 2019
f9e5b0d
Merge branch 'master' into comparison
KloskaT Aug 2, 2019
44050e2
black
crh23 Aug 2, 2019
bb971b3
Merge branch 'thomas'
crh23 Aug 2, 2019
951d8e3
Merge branch 'thomas'
crh23 Aug 2, 2019
72f010b
Now looks at percentage difference between original and new values. A…
KloskaT Aug 2, 2019
4efb20a
Remove existing code for proportional reinsurance, since it is not used.
crh23 Aug 5, 2019
2ef0649
Fixed some bugs causing logged data to be incorrect. Included (or mor…
KloskaT Aug 5, 2019
cba79a8
Added more denominations to aid fractions. Removed comparison.py and …
KloskaT Aug 6, 2019
2a6ddba
Merge branch 'master' of https://github.com/crh23/isle into chris
KloskaT Aug 6, 2019
c83983c
Merged Chris Master Branch. Almost fixed regulator for multi layer re…
KloskaT Aug 6, 2019
0220829
Implement catbonds.
crh23 Aug 6, 2019
ae8e0ea
Fixed bug causing most firms to exit market (firms with warnings dont…
KloskaT Aug 7, 2019
666144b
Fix bugs
crh23 Aug 8, 2019
37392cc
Optimisations - updates risk characterisation instead of re-calculating,
crh23 Aug 8, 2019
bbeaecf
Optimisations - updates risk characterisation instead of re-calculating,
crh23 Aug 9, 2019
a1c106e
Final. Changes due to Chris' changes. Tweaking firm pricing. Removed …
KloskaT Aug 9, 2019
656aebf
Changed aid check in line with change to insurance claims' claim time…
KloskaT Aug 9, 2019
e06666c
Updated readme
KloskaT Aug 9, 2019
2c68d08
Investigating the distribution of cat damage for potential implementa…
crh23 Aug 12, 2019
8fa8166
Merge branch 'thomas'
crh23 Aug 19, 2019
42a3a77
Merge branch 'Optimisation'
crh23 Aug 19, 2019
97e767b
Merge in a couple of changes from branch "sum_distributions"
crh23 Aug 19, 2019
d6ecb94
Squashing some old TODOs
crh23 Aug 19, 2019
3a6cacd
Switch to pickle for storing network data
crh23 Aug 20, 2019
ee0c446
Modified the ensemble running functions to simplify changing parameters
crh23 Aug 21, 2019
16f0b73
Switch to pickle for storing network data
crh23 Aug 21, 2019
cfccfdd
Merge branch 'master' into parameter_sets
crh23 Aug 21, 2019
568f315
Minor tweaks
crh23 Aug 21, 2019
08beb30
Investigating the distribution of cat damage for potential implementa…
crh23 Aug 21, 2019
8c4f029
Merge branch 'sum_distributions'
crh23 Aug 22, 2019
fb1b591
Tweak to make insurers pay out in the same timestep as reinsurers
crh23 Aug 22, 2019
f40afa3
Merge branch 'parameter_sets'
crh23 Aug 22, 2019
e411b1c
Ensembles now run fully asynchronously
crh23 Aug 22, 2019
f012424
Thinking about storage/RAM
crh23 Aug 23, 2019
55220a0
Fix issue with requested logs not being passed to simulation
crh23 Aug 23, 2019
b9392b6
Merge branch 'master' into pickle
crh23 Aug 23, 2019
7b94423
Change log storage to hickle (HDF5), add utility to convert back to old
crh23 Aug 27, 2019
b44c1ca
Document parameters a little more, misc changes
crh23 Aug 30, 2019
9868f53
Adding function for sensitivity analysis
crh23 Sep 3, 2019
a2aad0f
Removed all assert statements (sandman only returns exception, not
crh23 Sep 4, 2019
32f0729
It turns out the central bank wasn't implemented correctly at all
crh23 Sep 4, 2019
2649edd
Add parameter specification for sensitivity analysis
crh23 Sep 4, 2019
a764d49
Merge branch 'SensitivityAnalysis'
crh23 Sep 5, 2019
70a6fb1
bug fix
crh23 Sep 6, 2019
4dc7ecc
bug fix
crh23 Sep 6, 2019
fd4b2c8
bug fix
crh23 Sep 6, 2019
63bff53
Merge branch 'sandman_fix'
crh23 Sep 6, 2019
add4f12
Merge remote-tracking branch 'origin/master'
crh23 Sep 6, 2019
73ca98e
Add option to use multiprocessing instead of sandman
crh23 Sep 9, 2019
2d3029f
Implementing proposed calibration statistic
crh23 Sep 9, 2019
336e4cc
(another) bug fix
crh23 Sep 9, 2019
4df8369
(another) bug fix
crh23 Sep 9, 2019
c4aca23
Merge remote-tracking branch 'origin/master' into github
crh23 Sep 9, 2019
cca308a
Merge branch 'github'
crh23 Sep 10, 2019
3f853be
Multiprocessing changes
crh23 Sep 11, 2019
e7957e9
Setting up for calibration
crh23 Sep 12, 2019
e69086d
Setting up for calibration
crh23 Sep 12, 2019
88ef77f
Merge remote-tracking branch 'chris/master'
crh23 Sep 27, 2019
b312467
Code for running sensitivity analysis
crh23 Sep 27, 2019
a60a877
sensitivity
crh23 Sep 29, 2019
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 37 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@ $ pip install -r requirements.txt

# Usage

Isle requires that `./data` does not exist as a file, and may overwrite
particular file names in `./data/`.

## Simulation

Execute the simulation with this command
Execute a single simulation run with the command:

```
$ python3 start.py
Expand All @@ -25,28 +28,21 @@ $ python3 start.py
The ```start.py``` script accepts a number of options.

```
usage: start.py [-h] [--abce] [--oneriskmodel] [--riskmodels {1,2,3,4}]
[--replicid REPLICID] [--replicating]
[--randomseed RANDOMSEED] [--foreground] [-p] [-v]
usage: start.py [-h] [-f FILE] [-r] [-o] [-p] [-v] [--resume] [--oneriskmodel]
[--riskmodels {1,2,3,4}] [--randomseed RANDOMSEED]
[--foreground] [--shownetwork]
[--save_iterations SAVE_ITERATIONS]
```

See the help for more details

```
python3 start.py --help
```

## Graphical simulation runs

abce can be used to run simulations with a graphical interface:

```
python3 start.py --abce
$ python3 start.py --help
```

## Ensemble simulations

The bash scripts ```starter_*.sh``` can be used to run ensembles of a large number of simulations for settings with 1-4 different riskmodels. ```starter_two.sh``` is set up to generate random seeds and risk event schedules that are - for consistency and comparability - also used by the other scripts (i.e. ```starter_two.sh``` needs to be run first).
The bash scripts ```starter_*.sh``` can be used to run ensembles of a large number of simulations for settings with 1-4 different risk models. ```starter_two.sh``` is set up to generate random seeds and risk event schedules that are - for consistency and comparability - also used by the other scripts (i.e. ```starter_two.sh``` needs to be run first).

```
bash starter_two.sh
Expand All @@ -55,7 +51,32 @@ bash starter_four.sh
bash starter_three.sh
```

## Plotting
## Visualisation

#### Single runs
Use the script ```visualisation.py [--single]``` from the command line to plot data from a single run. It also takes the
arguments ```[--pie] [--timeseries]``` for which data representation is wanted. The argument ```[--config_compare_filex ]```
where ```x``` can be 1,2 or 3 is used for comparing two sets of data (singular or with replications) with different conditions.

If the necessary data has been saved a network animation can also be created by running ```visualization_network.py```
which takes the arguments ```[--save] [--number_iterations]``` if you want the animation to be saved as an mp4, and how
many time iterations you want in the animation.

#### Ensemble runs
Ensemble runs can be plotted if the correct data is available using ``visualisation.py`` which has a number of arguments.

```
visualiation.py [--timeseries_comparison] [--firmdistribution]
[--bankruptcydistribution] [--compare_riskmodels]
```

See help for more information.

# Contributing

Use the scripts ```plotter_pl_timescale.py``` and ```visualize.py``` for plotting/visualizing single simulation runs. Use ```.py```, ```metaplotter_pl_timescale.py```, or ```metaplotter_pl_timescale_additional_measures.py``` to visualize ensemble runs.
## Code style

[PEP 8](https://www.python.org/dev/peps/pep-0008/) styling should be used where possible.
The Python code formatter [black](https://github.com/python/black) is a good way
to automatically fix style problems - install it with `$ pip install black` and
then run it with, say, `black *.py`. Additionally, it is good to run flake8 over your code.
136 changes: 136 additions & 0 deletions calibrate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import sandman2.api as sm
import pyabc
import pyabc.sampler
from typing import Callable, Iterable, TypeVar, List
from functools import partial
import os
import isleconfig
import setup_simulation
import start
import calibration_statistic
import scipy.spatial
import scipy.stats
import numpy as np

T1 = TypeVar("T1")
T2 = TypeVar("T2")


def sm_map(
func: Callable[[T1], T2], iter_: Iterable[T1], hostname: str = None
) -> List[T2]:
"""Implements a map-like interface using sandman. Should be obtained using get_sm_map to set hostname"""
op = sm.operation(func, include_modules=True)
outputs = [op(arg) for arg in iter_]
with sm.Session(host=hostname) as sess:
result = sess.submit(outputs)
return result


def get_sm_map(hostname: str) -> Callable[[Callable[[T1], T2], Iterable[T1]], List[T2]]:
"""Returns sm_map with hostname parameter pre-filled, so it can be used as a drop-in repacement for
map (with a single iterable)"""
return partial(sm_map, hostname=hostname)


def model(parameters: dict) -> dict:
"""Runs the model with random randomness
Args:
parameters (dict): the parameters of this model run. Override those in isleconfig
Returns:
the result as a dictionary
"""
sim_params = isleconfig.simulation_parameters.copy()
sim_params.update(parameters)
setup = setup_simulation.SetupSim()
[event_schedule, event_damage, np_seeds, random_seeds] = setup.obtain_ensemble(
1, overwrite=True
)
result = start.main(
sim_params=sim_params,
rc_event_schedule=event_schedule[0],
rc_event_damage=event_damage[0],
np_seed=np_seeds[0],
random_seed=random_seeds[0],
save_iteration=0,
replic_id=0,
requested_logs=None,
resume=False,
summary=calibration_statistic.calculate_single,
)
return result


def single_prior(lower_bound, upper_bound, shape):
if shape not in ("linear", "logarithmic"):
print(f"Warning: shape {shape} not recognised, assuming linear")
shape = "linear"
lower_bound, upper_bound = float(lower_bound), float(upper_bound)
if shape == "linear":
return scipy.stats.uniform(lower_bound, upper_bound - lower_bound)
elif shape == "logarithmic":
return scipy.stats.reciprocal(lower_bound, upper_bound)


def get_prior():
params = {}
param_file_path = os.path.join(os.getcwd(), "isle_calibration_parameters.txt")
with open(param_file_path, "r") as rfile:
for line in rfile:
if line.startswith("#") or line == "\n":
continue
parts = line.strip("\n").replace(" ", "").split(",")
if len(parts) < 4:
continue
params[parts[0]] = single_prior(parts[1], parts[2], parts[3])
return params


def calibrate(observed: dict, hostname: str = None):
"""Calibrates. observed is a dictionary with keys as in calibration_statistic.statistics containing the real data"""
db_path = "sqlite:///" + os.path.join(os.getcwd(), "data", "calibration.db")
if hostname is not None:
# If we're given a hostname, use the above sandman mapping wrapper
sampler = pyabc.sampler.MappingSampler(
map_=get_sm_map(hostname), mapper_pickles=True
)
else:
# Otherwise, run locally with the normal sampler
sampler = pyabc.sampler.MulticoreEvalParallelSampler()
# Adaptive distance based on Prangle (2017) (also acceptor below)
dist = pyabc.distance.AdaptivePNormDistance(p=2, adaptive=True)
prior = pyabc.Distribution(**get_prior())
pop_size = pyabc.populationstrategy.AdaptivePopulationSize(
start_nr_particles=32, max_population_size=256, min_population_size=4
)

abc = pyabc.ABCSMC(
model,
parameter_priors=prior,
distance_function=dist,
population_size=pop_size,
sampler=sampler,
acceptor=pyabc.accept_use_complete_history,
)

run_id = abc.new(db=db_path, observed_sum_stat=observed)
print(f"Run ID is {run_id}")
history = abc.run(max_nr_populations=10)
df, w = history.get_distribution()
results = {}
for param in df.columns.values:
# Calculate the posterior mean of each parameter
results[param] = np.dot(list(df[param]), list(w))

print("Done! The results are:")
print(results)


if __name__ == "__main__":
import sys

host = None
if len(sys.argv) > 1:
# The server is passed as an argument.
host = sys.argv[1]
calibrate(observed=calibration_statistic.observed, hostname=host)
Loading