generated from klb2/reproducible-paper-python-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simulation_deterministic.py
173 lines (152 loc) · 6.87 KB
/
simulation_deterministic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import logging
from typing import Iterable
import gc
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
from ide_stopping_time import ide_fft
from mc_stopping_time import mc_stopping_time
from bounds_stopping_time import worst_case_outage_prob_iid
from util import (export_results, find_closest_element_idx, db_to_linear,
capacity)
LOGGER = logging.getLogger(__name__)
def main(save_b: Iterable[float] = [5., 10., 20.],
save_t: Iterable[int] = [1, 4, 10],
snr_bob: float = 20,
snr_eve: float = 10,
num_timesteps: int = 50,
num_budgets: int = 200,
num_samples: int = int(1e6),
skip_mc: bool = False,
plot: bool = False, export: bool = False):
LOGGER.info("Starting simulation...")
LOGGER.debug(f"Number of MC samples: {num_samples:E}")
LOGGER.debug(f"Number of timesteps: {num_timesteps:d}")
LOGGER.debug(f"Number of budgets: {num_budgets:d}")
snr_bob_lin = db_to_linear(snr_bob)
snr_eve_lin = db_to_linear(snr_eve)
rv_bob = stats.expon(scale=snr_bob_lin)
rv_eve = stats.expon(scale=snr_eve_lin)
LOGGER.info(f"Avg. SNR Bob: {snr_bob:.1f}dB")
LOGGER.info(f"Avg. SNR Eve: {snr_eve:.1f}dB")
LOGGER.debug("Determining the density of the claims")
_num_samples_rv = int(2e5)
samples_x = rv_bob.rvs(size=_num_samples_rv)
samples_xt = rv_bob.rvs(size=_num_samples_rv)
samples_y = rv_eve.rvs(size=_num_samples_rv)
rate_sum = capacity(samples_x+samples_y)
rate_eve = capacity(samples_y)
rate_bob = capacity(samples_xt)
samples_claims = -(rate_sum - rate_eve - rate_bob)
_mean_income = np.mean(rate_sum-rate_eve)
_mean_tx = np.mean(rate_bob)
LOGGER.debug(f"Average income: {_mean_income:.3f}")
LOGGER.debug(f"Average claim: {_mean_tx:.3f}")
mean_claim = np.mean(samples_claims)
var_claim = np.var(samples_claims)
LOGGER.debug(f"Average net claim: {mean_claim:.3f}bit")
_hist = np.histogram(samples_claims, bins=300)
rv = stats.rv_histogram(_hist)
LOGGER.info("Performing Gaussian KDE...")
rv_kde = stats.gaussian_kde(samples_claims)
LOGGER.info("KDE finished.")
#plt.hist(samples_claims, bins=200, density=True)
#x = np.linspace(-10, 10, 1000)
#plt.plot(x, rv_kde.pdf(x))
#return
LOGGER.debug("Density estimated.")
del samples_x, samples_xt, samples_y, rate_bob, rate_eve, rate_sum, samples_claims
gc.collect()
max_budget = 1.5*max(save_b)
if not skip_mc:
LOGGER.info("Working on the Monte Carlo simulation...")
budget_mc, cdf_mc = mc_stopping_time(rv, max_budget=max_budget,
num_samples=num_samples,
num_timesteps=num_timesteps)
else:
LOGGER.info("Skipping Monte Carlo simulation...")
budget_mc = np.linspace(0, max_budget, num_budgets)
cdf_mc = np.zeros((num_timesteps, num_budgets))
LOGGER.info("Working on bound...")
timeline = np.arange(num_timesteps)
upper_bound = worst_case_outage_prob_iid(mean_claim, var_claim,
budget=budget_mc,
n=np.reshape(timeline, (-1, 1)))
LOGGER.info("Working on the numerical calculation...")
budget_th, cdf_th = ide_fft(rv_kde.pdf, max_x=max_budget,
num_timesteps=num_timesteps,
num_points=2**13)
#num_points=2**20)
LOGGER.info("Finished all calculations.")
for b in save_b:
idx_b_mc = find_closest_element_idx(budget_mc, b)
idx_b_th = find_closest_element_idx(budget_th, b)
_cdf_mc_b = np.ravel(cdf_mc[:, idx_b_mc])
_cdf_th_b = np.ravel(cdf_th[:, idx_b_th])
_cdf_bound = np.ravel(upper_bound[:, idx_b_mc])
LOGGER.debug(f"b0={b:.1f}, t=1, t=4 and 10: {_cdf_th_b[[1,4,10]]}")
LOGGER.debug(f"Exact outage at t=1: {1-rv.cdf(b)}")
if export:
results = {
"time": timeline,
"mc": np.ravel(_cdf_mc_b),
"ide": np.ravel(_cdf_th_b),
"upper": _cdf_bound,
}
fname = f"ruin-cdf-time-b{b:.1f}.dat"
export_results(results, fname)
if plot:
fig, axs = plt.subplots()
axs.semilogy(timeline, _cdf_mc_b, label="Monte Carlo Simulation")
axs.semilogy(timeline, _cdf_th_b, label="Numerical Solution")
axs.semilogy(timeline, _cdf_bound, label="Upper bound")
axs.legend()
axs.set_xlabel("Time Step $t$")
axs.set_ylabel("Outage Probability $\\varepsilon$")
axs.set_title(f"Start Budget $b_0={b:.1f}$")
axs.set_xlim([0, num_timesteps])
axs.set_ylim([1e-7, 1])
if export:
_components = (("mc", cdf_mc, budget_mc),
("th", cdf_th, budget_th),
("upper", upper_bound, budget_mc),
)
for _name, _cdf, _budget in _components:
results = {f"t{t:d}": _cdf[t] for t in save_t}
results["budget"] = _budget
fname = f"ruin-cdf-budget-{_name}.dat"
export_results(results, fname)
#if plot:
# fig, axs = plt.subplots()
# axs.semilogy(budget_mc, cdf_mc[3], label="Monte Carlo Simulation")
# axs.semilogy(budget_th, cdf_th[3], label="Numerical Solution")
# axs.semilogy(budget_mc, upper_bound[3], label="Upper bound")
# axs.legend()
# axs.set_xlabel("Initial Budget $b_{0}$")
# axs.set_ylabel("Outage Probability $\\varepsilon$")
# #axs.set_title(f"Start Budget $b_0={b:.1f}$")
# #axs.set_xlim([0, num_timesteps])
# #axs.set_ylim([1e-7, 1])
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-b", "--save_b", type=float, nargs="+")
parser.add_argument("-t", "--save_t", type=int, nargs="+")
parser.add_argument("-n", "--num_samples", type=int, default=int(1e6),
help="Number of MC samples used for the simulation")
parser.add_argument("--skip_mc", action="store_true")
parser.add_argument("--plot", action="store_true")
parser.add_argument("--export", action="store_true")
parser.add_argument("-v", "--verbosity", action="count", default=0,
help="Increase output verbosity")
args = vars(parser.parse_args())
verb = args.pop("verbosity")
logging.basicConfig(format="%(asctime)s - [%(levelname)8s]: %(message)s",
handlers=[
logging.FileHandler("main.log", encoding="utf-8"),
logging.StreamHandler()
])
loglevel = logging.WARNING - verb*10
LOGGER.setLevel(loglevel)
main(**args)
plt.show()