rareeventestimation 0.2.0__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. rareeventestimation-0.2.0/README.md → rareeventestimation-0.4.0/PKG-INFO +58 -3
  2. rareeventestimation-0.2.0/PKG-INFO → rareeventestimation-0.4.0/README.md +21 -37
  3. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/pyproject.toml +3 -3
  4. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/enkf/EnKF_rare_events.py +6 -7
  5. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/era/CEIS_GM.py +1 -1
  6. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/era/CEIS_vMFNM.py +1 -1
  7. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/era/EMvMFNM.py +16 -5
  8. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/era/MCMC.py +47 -55
  9. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/evaluation/convergence_analysis.py +7 -1
  10. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/evaluation/visualization.py +9 -3
  11. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/mls2mc/SIS_VMFNM.py +1 -1
  12. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/problem/diffusion.py +6 -8
  13. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/problem/flowrate_problem.py +1 -0
  14. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/problem/problem.py +53 -4
  15. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/problem/toy_problems.py +10 -1
  16. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/sis/SIS_GM.py +54 -50
  17. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/sis/SIS_aCS.py +35 -25
  18. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/solver.py +69 -47
  19. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/LICENSE +0 -0
  20. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/__init__.py +0 -0
  21. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/era/EMGM.py +0 -0
  22. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/era/ERADist.py +0 -0
  23. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/era/ERANataf.py +0 -0
  24. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/evaluation/constants.py +0 -0
  25. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/mixturemodel.py +0 -0
  26. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/solution.py +0 -0
  27. {rareeventestimation-0.2.0 → rareeventestimation-0.4.0}/src/rareeventestimation/utilities.py +0 -0
@@ -1,8 +1,46 @@
1
+ Metadata-Version: 2.4
2
+ Name: rareeventestimation
3
+ Version: 0.4.0
4
+ Summary: Estimate rare events with consensus based sampling and other methods.
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Author: Konstantin Althaus
8
+ Author-email: althaus.konstantin.95@gmail.com
9
+ Requires-Python: >=3.10
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Programming Language :: Python :: 3.15
18
+ Requires-Dist: Pillow (>=9.1.1)
19
+ Requires-Dist: argparse (>=1.4.0)
20
+ Requires-Dist: ipython (>=8.4.0)
21
+ Requires-Dist: jupyter-core (>=4.11.2)
22
+ Requires-Dist: matplotlib (>=3.5.2)
23
+ Requires-Dist: nbconvert (>=6.5.0)
24
+ Requires-Dist: notebook (>=6.4.12)
25
+ Requires-Dist: numpy (>=1.26)
26
+ Requires-Dist: pandas (>=1.4.2)
27
+ Requires-Dist: plotly (>=5.8.0)
28
+ Requires-Dist: prettytable (>=3.3.0)
29
+ Requires-Dist: pytest (>=7.2.0)
30
+ Requires-Dist: scikit-fem (>=7.0.1)
31
+ Requires-Dist: scipy (>=1.8.1)
32
+ Project-URL: Documentation, https://althauskonstantin.github.io/rareeventestimation/
33
+ Project-URL: Homepage, https://pypi.org/project/rareeventestimation/
34
+ Project-URL: Repository, https://github.com/AlthausKonstantin/rareeventestimation
35
+ Description-Content-Type: text/markdown
36
+
1
37
  # rareeventestimation
2
38
 
3
39
  [![coverage](https://raw.githubusercontent.com/AlthausKonstantin/rareeventestimation/gh-pages/_static/images/coverage_badge.svg)](https://github.com/AlthausKonstantin/rareeventestimation/actions/workflows/run_tests.yaml)
4
40
  [![test](https://github.com/AlthausKonstantin/rareeventestimation/actions/workflows/run_tests.yaml/badge.svg)](https://github.com/AlthausKonstantin/rareeventestimation/actions/workflows/run_tests.yaml)
5
41
  [![build documentation](https://github.com/AlthausKonstantin/rareeventestimation/actions/workflows/build_documentation.yaml/badge.svg)](https://github.com/AlthausKonstantin/rareeventestimation/actions/workflows/build_documentation.yaml)
42
+ [![publish package](https://github.com/AlthausKonstantin/rareeventestimation/actions/workflows/publish.yaml/badge.svg)](https://github.com/AlthausKonstantin/rareeventestimation/actions/workflows/publish.yaml)
43
+ [![PyPI version](https://badge.fury.io/py/rareeventestimation.svg)](https://badge.fury.io/py/rareeventestimation)
6
44
 
7
45
  Estimate rare events with consensus-based sampling and other methods.
8
46
  ## Installation
@@ -25,7 +63,7 @@ import rareeventestimation as ree
25
63
  from numpy import ndarray, sum, sqrt
26
64
 
27
65
  # define problem with normal distribution:
28
- # lsf does not need to be vectorized
66
+ # the lsf gets an array of shape (n, d) and returns n values
29
67
  def my_lsf(x: ndarray) -> ndarray:
30
68
  """Affine limit state function
31
69
 
@@ -48,6 +86,19 @@ solution = solver.solve(problem)
48
86
  print(solution.prob_fail_hist[-1]) # print estimate of last (=best) iteration
49
87
  ```
50
88
 
89
+ ### Vectorized limit state functions
90
+ CBREE, EnKF and CMC always call the limit state function with an array of shape `(n, d)` and expect `n` values back.
91
+ SIS calls it one point at a time by default, so it also works with a function that only knows single points.
92
+ If your function evaluates arrays, tell the problem:
93
+ ```python
94
+ problem = ree.NormalProblem(my_lsf, prob_dim, sample_size, vectorized=True)
95
+ ```
96
+ Then SIS passes whole batches to the function: the initial sample in one call, and one call per Markov chain step for all chains.
97
+ With `mixture_model="aCS"` the chains are adapted in groups, so there is one call per step for each group.
98
+ This matters for an expensive function that is much cheaper per point in a batch, for example a simulation of many trajectories at once.
99
+ The estimates do not change.
100
+ The built-in problems, such as `ree.prob_convex` or `ree.make_linear_problem(d)`, are vectorized already.
101
+
51
102
  ## Features
52
103
  - Implementation of the Consensus-Based Rare Event Estimation
53
104
  - Interface and implementation for other rare event estimations methods:
@@ -58,8 +109,11 @@ print(solution.prob_fail_hist[-1]) # print estimate of last (=best) iteration
58
109
 
59
110
  ## About
60
111
  This package was developed during my master's thesis and the publication of a paper about a new method for rare event estimation (the CBREE method).
61
- Therefore this package contains multiple notebooks which produce the figures used in those two publications.
62
- For the exact location have a look at the content section
112
+ Therefore this package contains multiple notebooks which produce the figures used in those two publications.
113
+
114
+ If you want to reproduce the figures of the paper **K. Althaus I. Papaioannou, and E. Ullmann, Consensus-based rare event estimation, (2023), https://doi.org/10.48550/arXiv.2304.09077**,
115
+ use the notebooks in `docs/figures_paper`.
116
+
63
117
 
64
118
  ## Content
65
119
  Here is an incomplete overview of the folder structure of the package.
@@ -122,3 +176,4 @@ F. Wagner, J. Latz, I. Papaioannou, and E. Ullmann, Multilevel Sequential Import
122
176
  <a id="Wagner2022" href="#features">[3]</a>
123
177
  F. Wagner, I. Papaioannou, and E. Ullmann, The ensemble kalman filter for rare event estimation, SIAM/ASA Journal on Uncertainty Quantification, 10 (2022), pp. 317–349, https://doi.org/10.1137/21m1404119.
124
178
 
179
+
@@ -1,41 +1,10 @@
1
- Metadata-Version: 2.1
2
- Name: rareeventestimation
3
- Version: 0.2.0
4
- Summary: Estimate rare events with consensus based sampling and other methods.
5
- Home-page: https://pypi.org/project/rareeventestimation/
6
- License: MIT
7
- Author: Konstantin Althaus
8
- Author-email: althaus.konstantin.95@gmail.com
9
- Requires-Python: >=3.8
10
- Classifier: License :: OSI Approved :: MIT License
11
- Classifier: Programming Language :: Python :: 3
12
- Classifier: Programming Language :: Python :: 3.8
13
- Classifier: Programming Language :: Python :: 3.9
14
- Classifier: Programming Language :: Python :: 3.10
15
- Classifier: Programming Language :: Python :: 3.11
16
- Requires-Dist: Pillow (>=9.1.1)
17
- Requires-Dist: argparse (>=1.4.0)
18
- Requires-Dist: ipython (>=8.4.0)
19
- Requires-Dist: jupyter-core (>=4.11.2)
20
- Requires-Dist: matplotlib (>=3.5.2)
21
- Requires-Dist: nbconvert (>=6.5.0)
22
- Requires-Dist: notebook (>=6.4.12)
23
- Requires-Dist: numpy (>=1.22.3)
24
- Requires-Dist: pandas (>=1.4.2)
25
- Requires-Dist: plotly (>=5.8.0)
26
- Requires-Dist: prettytable (>=3.3.0)
27
- Requires-Dist: pytest (>=7.2.0)
28
- Requires-Dist: scikit-fem (>=7.0.1)
29
- Requires-Dist: scipy (>=1.8.1)
30
- Project-URL: Documentation, https://althauskonstantin.github.io/rareeventestimation/
31
- Project-URL: Repository, https://github.com/AlthausKonstantin/rareeventestimation
32
- Description-Content-Type: text/markdown
33
-
34
1
  # rareeventestimation
35
2
 
36
3
  [![coverage](https://raw.githubusercontent.com/AlthausKonstantin/rareeventestimation/gh-pages/_static/images/coverage_badge.svg)](https://github.com/AlthausKonstantin/rareeventestimation/actions/workflows/run_tests.yaml)
37
4
  [![test](https://github.com/AlthausKonstantin/rareeventestimation/actions/workflows/run_tests.yaml/badge.svg)](https://github.com/AlthausKonstantin/rareeventestimation/actions/workflows/run_tests.yaml)
38
5
  [![build documentation](https://github.com/AlthausKonstantin/rareeventestimation/actions/workflows/build_documentation.yaml/badge.svg)](https://github.com/AlthausKonstantin/rareeventestimation/actions/workflows/build_documentation.yaml)
6
+ [![publish package](https://github.com/AlthausKonstantin/rareeventestimation/actions/workflows/publish.yaml/badge.svg)](https://github.com/AlthausKonstantin/rareeventestimation/actions/workflows/publish.yaml)
7
+ [![PyPI version](https://badge.fury.io/py/rareeventestimation.svg)](https://badge.fury.io/py/rareeventestimation)
39
8
 
40
9
  Estimate rare events with consensus-based sampling and other methods.
41
10
  ## Installation
@@ -58,7 +27,7 @@ import rareeventestimation as ree
58
27
  from numpy import ndarray, sum, sqrt
59
28
 
60
29
  # define problem with normal distribution:
61
- # lsf does not need to be vectorized
30
+ # the lsf gets an array of shape (n, d) and returns n values
62
31
  def my_lsf(x: ndarray) -> ndarray:
63
32
  """Affine limit state function
64
33
 
@@ -81,6 +50,19 @@ solution = solver.solve(problem)
81
50
  print(solution.prob_fail_hist[-1]) # print estimate of last (=best) iteration
82
51
  ```
83
52
 
53
+ ### Vectorized limit state functions
54
+ CBREE, EnKF and CMC always call the limit state function with an array of shape `(n, d)` and expect `n` values back.
55
+ SIS calls it one point at a time by default, so it also works with a function that only knows single points.
56
+ If your function evaluates arrays, tell the problem:
57
+ ```python
58
+ problem = ree.NormalProblem(my_lsf, prob_dim, sample_size, vectorized=True)
59
+ ```
60
+ Then SIS passes whole batches to the function: the initial sample in one call, and one call per Markov chain step for all chains.
61
+ With `mixture_model="aCS"` the chains are adapted in groups, so there is one call per step for each group.
62
+ This matters for an expensive function that is much cheaper per point in a batch, for example a simulation of many trajectories at once.
63
+ The estimates do not change.
64
+ The built-in problems, such as `ree.prob_convex` or `ree.make_linear_problem(d)`, are vectorized already.
65
+
84
66
  ## Features
85
67
  - Implementation of the Consensus-Based Rare Event Estimation
86
68
  - Interface and implementation for other rare event estimations methods:
@@ -91,8 +73,11 @@ print(solution.prob_fail_hist[-1]) # print estimate of last (=best) iteration
91
73
 
92
74
  ## About
93
75
  This package was developed during my master's thesis and the publication of a paper about a new method for rare event estimation (the CBREE method).
94
- Therefore this package contains multiple notebooks which produce the figures used in those two publications.
95
- For the exact location have a look at the content section
76
+ Therefore this package contains multiple notebooks which produce the figures used in those two publications.
77
+
78
+ If you want to reproduce the figures of the paper **K. Althaus I. Papaioannou, and E. Ullmann, Consensus-based rare event estimation, (2023), https://doi.org/10.48550/arXiv.2304.09077**,
79
+ use the notebooks in `docs/figures_paper`.
80
+
96
81
 
97
82
  ## Content
98
83
  Here is an incomplete overview of the folder structure of the package.
@@ -155,4 +140,3 @@ F. Wagner, J. Latz, I. Papaioannou, and E. Ullmann, Multilevel Sequential Import
155
140
  <a id="Wagner2022" href="#features">[3]</a>
156
141
  F. Wagner, I. Papaioannou, and E. Ullmann, The ensemble kalman filter for rare event estimation, SIAM/ASA Journal on Uncertainty Quantification, 10 (2022), pp. 317–349, https://doi.org/10.1137/21m1404119.
157
142
 
158
-
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "rareeventestimation"
3
- version = "0.2.0"
3
+ version = "0.4.0"
4
4
  description = "Estimate rare events with consensus based sampling and other methods."
5
5
  authors = ["Konstantin Althaus <althaus.konstantin.95@gmail.com>"]
6
6
  license = "MIT"
@@ -10,8 +10,8 @@ homepage = "https://pypi.org/project/rareeventestimation/"
10
10
  documentation = "https://althauskonstantin.github.io/rareeventestimation/"
11
11
 
12
12
  [tool.poetry.dependencies]
13
- python = ">=3.8"
14
- numpy = ">=1.22.3"
13
+ python = ">=3.10"
14
+ numpy = ">=1.26"
15
15
  scipy = ">=1.8.1"
16
16
  pandas = ">=1.4.2"
17
17
  plotly = ">=5.8.0"
@@ -60,7 +60,6 @@ class EnKF_rare_events:
60
60
  self.gk = np.zeros((self.ensemble_size, self.data_dim))
61
61
 
62
62
  self.posterior_mean = np.zeros((self.niter_enKF, parameter_dim))
63
- self.posterior_lsf_mean = np.zeros((self.niter_enKF, self.data_dim))
64
63
  self.sigmak_list = np.zeros(self.niter_enKF)
65
64
 
66
65
  """parameters for specific EnkF method"""
@@ -321,7 +320,6 @@ class EnKF_rare_events:
321
320
 
322
321
  def update_posterior_and_error(self):
323
322
  self.posterior_mean = np.mean(self.uk, 0)
324
- self.posterior_lsf_mean = self.lsf(self.posterior_mean)
325
323
 
326
324
  self.rel_error.append(
327
325
  np.linalg.norm(self.y_data - self.gk) / self.ensemble_size
@@ -344,7 +342,8 @@ class EnKF_rare_events:
344
342
 
345
343
  def evaluate_lsf(self):
346
344
  """Calculate the limit state function values with respect to the current particles"""
347
- self.gk = self.lsf(self.uk)[..., None]
345
+ # one value per particle, as a column
346
+ self.gk = np.reshape(self.lsf(self.uk), (self.ensemble_size, 1))
348
347
 
349
348
  "Update the computational costs and number of function evaluations"
350
349
  self.computational_cost = self.computational_cost + self.ensemble_size
@@ -370,8 +369,8 @@ class EnKF_rare_events:
370
369
 
371
370
  self.uk_fitted = GM_sample(mu.T, si, pi, self.ensemble_size)
372
371
 
373
- for j in range(self.ensemble_size):
374
- self.gk_fitted[j] = self.g_original(self.uk_fitted[j])
372
+ # evaluate all samples in one call, like evaluate_lsf does
373
+ self.gk_fitted = np.reshape(self.g_original(self.uk_fitted), self.ensemble_size)
375
374
 
376
375
  "Update the computational costs and number of function evaluations"
377
376
  self.computational_cost = self.computational_cost + self.ensemble_size
@@ -401,8 +400,8 @@ class EnKF_rare_events:
401
400
  [mu, kappa, m, omega, alpha] = EMvMFNM(self.uk.T, W, self.k_init)
402
401
  self.uk_fitted = vMFNM_sample(mu.T, kappa, omega, m, alpha, self.ensemble_size)
403
402
 
404
- for j in range(self.ensemble_size):
405
- self.gk_fitted[j] = self.g_original(self.uk_fitted[j])
403
+ # evaluate all samples in one call, like evaluate_lsf does
404
+ self.gk_fitted = np.reshape(self.g_original(self.uk_fitted), self.ensemble_size)
406
405
 
407
406
  "Update the computational costs and number of function evaluations"
408
407
  self.computational_cost = self.computational_cost + self.ensemble_size
@@ -61,7 +61,7 @@ Based on:
61
61
 
62
62
 
63
63
  def CEIS_GM(N, p, g_fun, distr, k_init):
64
- if (N * p != np.fix(N * p)) or (1 / p != np.fix(1 / p)):
64
+ if (N * p != np.trunc(N * p)) or (1 / p != np.trunc(1 / p)):
65
65
  raise RuntimeError(
66
66
  "N*p and 1/p must be positive integers. Adjust N and p accordingly"
67
67
  )
@@ -59,7 +59,7 @@ Based on:
59
59
 
60
60
 
61
61
  def CEIS_vMFNM(N, p, g_fun, distr, k_init):
62
- if (N * p != np.fix(N * p)) or (1 / p != np.fix(1 / p)):
62
+ if (N * p != np.trunc(N * p)) or (1 / p != np.trunc(1 / p)):
63
63
  raise RuntimeError(
64
64
  "N*p and 1/p must be positive integers. Adjust N and p accordingly"
65
65
  )
@@ -1,6 +1,5 @@
1
1
  import numpy as np
2
2
  import scipy as sp
3
- from numpy.random import default_rng
4
3
 
5
4
  """
6
5
  ---------------------------------------------------------------------------
@@ -294,7 +293,11 @@ def dummyvar(idx):
294
293
  # --------------------------------------------------------------------------
295
294
  # Returns samples from the von Mises-Fisher-Nakagami mixture
296
295
  # --------------------------------------------------------------------------
297
- def vMFNM_sample(mu, kappa, omega, m, alpha, N, rng=default_rng()):
296
+ def vMFNM_sample(mu, kappa, omega, m, alpha, N, rng=None):
297
+ # without an explicit generator, draw from numpy's global random state,
298
+ # which the solvers seed
299
+ if rng is None:
300
+ rng = np.random
298
301
  [k, dim] = np.shape(mu)
299
302
  if k == 1:
300
303
  # sampling the radius
@@ -343,7 +346,11 @@ def vMFNM_sample(mu, kappa, omega, m, alpha, N, rng=default_rng()):
343
346
  # --------------------------------------------------------------------------
344
347
  # Returns samples from the von Mises-Fisher distribution
345
348
  # --------------------------------------------------------------------------
346
- def vsamp(center, kappa, n, rng=default_rng()):
349
+ def vsamp(center, kappa, n, rng=None):
350
+ # without an explicit generator, draw from numpy's global random state,
351
+ # which the solvers seed
352
+ if rng is None:
353
+ rng = np.random
347
354
  d = np.size(center, axis=0) # Dimensionality
348
355
  t1 = np.sqrt(4 * kappa * kappa + (d - 1) * (d - 1))
349
356
  b = (-2 * kappa + t1) / (d - 1)
@@ -369,7 +376,7 @@ def vsamp(center, kappa, n, rng=default_rng()):
369
376
  X[i, : d - 1] = (
370
377
  np.sqrt(1 - w * w) * v
371
378
  ) # X[i,:d-1] = np.matmul(np.sqrt(1-w*w),v.T)
372
- X[i, d - 1] = w
379
+ X[i, d - 1] = np.squeeze(w)
373
380
 
374
381
  [v, b] = house(center)
375
382
  Q = np.eye(d) - b * np.matmul(v, v.T)
@@ -387,7 +394,11 @@ def vsamp(center, kappa, n, rng=default_rng()):
387
394
  # n: # dimensions
388
395
  # R: radius of hypersphere
389
396
  # --------------------------------------------------------------------------
390
- def hs_sample(N, n, R, rng=default_rng()):
397
+ def hs_sample(N, n, R, rng=None):
398
+ # without an explicit generator, draw from numpy's global random state,
399
+ # which the solvers seed
400
+ if rng is None:
401
+ rng = np.random
391
402
  Y = rng.normal(
392
403
  size=(N, n)
393
404
  ) # sp.stats.norm.rvs(size=(n, N), random_state=seed) # randn(n,N)
@@ -127,13 +127,13 @@ class MCMC:
127
127
  ucand = np.random.normal(loc=rhok * u0, scale=self.sigmafk)
128
128
 
129
129
  # Evaluate limit-state function
130
- gcand = self.limit_state_fun_current(ucand)
130
+ gcand = np.squeeze(self.limit_state_fun_current(ucand))
131
131
 
132
132
  # compute acceptance probability
133
133
  acceptance_rate = norm.cdf(-gcand / self.sigma) / norm.cdf(
134
134
  -g0 / self.sigma
135
135
  )
136
- alpha = min(1, acceptance_rate)
136
+ alpha = min(1, np.squeeze(acceptance_rate))
137
137
  self.alphak[k] = self.alphak[k] + alpha / (self.lenchain + self.burn)
138
138
 
139
139
  # check if sample is accepted
@@ -169,8 +169,6 @@ class MCMC:
169
169
  def mcmc_procedure_tempering_vmfnm(self):
170
170
  [gk0, gk0_next, uk0] = MCMC.generate_seeds(self)
171
171
 
172
- count = 0
173
-
174
172
  [mu_vMFNM, kappa, m, omega, alpha_em] = EMvMFNM(
175
173
  self.uk.T, self.wnork, self.k_init
176
174
  )
@@ -183,70 +181,64 @@ class MCMC:
183
181
  [self.nsamlev + self.burn, self.dim]
184
182
  ) # delete previous samples
185
183
 
184
+ nstep = self.lenchain + self.burn
186
185
  ucandidates = vMFNM_sample(
187
186
  mu_vMFNM,
188
187
  kappa,
189
188
  omega,
190
189
  m,
191
190
  alpha_em,
192
- self.nchain * (self.lenchain + self.burn),
191
+ self.nchain * nstep,
193
192
  )
194
- z = 0
195
-
193
+ # candidate of chain k in step i, in the order of the sample above
194
+ ucands = ucandidates.reshape((self.nchain, nstep, self.dim))
195
+ # the uniform numbers for the acceptance, in the order in which
196
+ # running one chain after the other draws them
197
+ uhelps = np.zeros([self.nchain, nstep])
196
198
  for k in range(self.nchain):
197
- # set seed for chain
198
- u0 = uk0[k, :]
199
- g0 = gk0[k]
200
-
201
- for i in range(self.lenchain + self.burn):
202
- if i == self.burn:
203
- count = count - self.burn
204
-
205
- # get candidate sample from conditional normal distribution
206
- ucand = ucandidates[z, :]
207
-
208
- # Evaluate limit-state function
209
- gcand = self.limit_state_fun_current(ucand)
210
-
199
+ for i in range(nstep):
200
+ uhelps[k, i] = sp.stats.uniform.rvs()
201
+
202
+ def log_ratio(u):
203
+ return likelihood_ratio_log(
204
+ u.reshape((1, self.dim)),
205
+ mu_vMFNM,
206
+ kappa,
207
+ omega,
208
+ m,
209
+ alpha_em,
210
+ )[:]
211
+
212
+ # all chains take each step together: one call of the lsf per step
213
+ u0 = uk0.copy() # current state of every chain
214
+ g0 = np.reshape(gk0, self.nchain)
215
+ for i in range(nstep):
216
+ ucand = ucands[:, i, :]
217
+
218
+ # Evaluate limit-state function
219
+ gcand = np.reshape(self.limit_state_fun_current(ucand), self.nchain)
220
+
221
+ for k in range(self.nchain):
211
222
  acceptance_rate = (
212
- sp.stats.norm.cdf(-gcand / self.sigma)
213
- / sp.stats.norm.cdf(-g0 / self.sigma)
214
- * np.exp(
215
- -likelihood_ratio_log(
216
- u0.reshape((1, self.dim)),
217
- mu_vMFNM,
218
- kappa,
219
- omega,
220
- m,
221
- alpha_em,
222
- )[:]
223
- + likelihood_ratio_log(
224
- ucand.reshape((1, self.dim)),
225
- mu_vMFNM,
226
- kappa,
227
- omega,
228
- m,
229
- alpha_em,
230
- )[:]
231
- )
223
+ sp.stats.norm.cdf(-gcand[k] / self.sigma)
224
+ / sp.stats.norm.cdf(-g0[k] / self.sigma)
225
+ * np.exp(-log_ratio(u0[k]) + log_ratio(ucand[k]))
232
226
  )
233
227
 
234
- alpha = min(1, acceptance_rate)
235
- self.alphak[k] = self.alphak[k] + alpha / (self.lenchain + self.burn)
228
+ alpha = min(1, np.squeeze(acceptance_rate))
229
+ self.alphak[k] = self.alphak[k] + alpha / nstep
236
230
 
237
231
  # check if sample is accepted
238
- uhelp = sp.stats.uniform.rvs()
239
- if uhelp <= alpha:
240
- self.uk[count, :] = ucand
241
- self.gk_current[count] = gcand
242
- u0 = ucand
243
- g0 = gcand
244
- else:
245
- self.uk[count, :] = u0
246
- self.gk_current[count] = g0
247
-
248
- count = count + 1
249
- z = z + 1
232
+ if uhelps[k, i] <= alpha:
233
+ u0[k] = ucand[k]
234
+ g0[k] = gcand[k]
235
+
236
+ # chain k keeps its samples after the burn-in in rows
237
+ # k*lenchain to (k+1)*lenchain - 1
238
+ if i >= self.burn:
239
+ rows = np.arange(self.nchain) * self.lenchain + (i - self.burn)
240
+ self.uk[rows, :] = u0
241
+ self.gk_current[rows] = g0
250
242
  self.k_final = len(alpha_em)
251
243
  self.uk = self.uk[: self.nsamlev, :]
252
244
  self.gk_current = self.gk_current[: self.nsamlev]
@@ -101,7 +101,13 @@ def do_multiple_solves(
101
101
  df[c] = [solution.other[c].tolist()]
102
102
  if other_list is not None:
103
103
  for c in other_list:
104
- df[c] = [solution.other.get(c, asarray([pd.NA])).tolist()]
104
+ val = solution.other.get(c, asarray([pd.NA]))
105
+ if hasattr(val, "tolist"):
106
+ df[c] = val.tolist()
107
+ if isinstance(val, list):
108
+ df[c] = val
109
+ else:
110
+ df[c] = [val]
105
111
  try:
106
112
  df[c] = df[c].map(list)
107
113
  except TypeError:
@@ -642,9 +642,10 @@ def make_efficiency_plot(
642
642
  this_df_box = this_df_box.sort_values(x, key=x_axis_sorting_key)
643
643
  xx_box = this_df_box.loc[:, x].values
644
644
  yy_box = this_df_box.loc[:, y_box].values
645
+ msk = yy_box > 0
645
646
  box = Box(
646
- x=xx_box,
647
- y=yy_box,
647
+ x=xx_box[msk],
648
+ y=yy_box[msk],
648
649
  marker_color=CMAP[1],
649
650
  name="Estimates",
650
651
  legendgroup="2",
@@ -670,7 +671,12 @@ def make_efficiency_plot(
670
671
  fig.add_trace(line, row=row_idx + 1, col=col_idx + 1)
671
672
  counter += 1
672
673
  for idx, fun in zip((0, 1), (amin, amax)):
673
- secondary_y_limits[idx] = fun([secondary_y_limits[idx], fun(yy_box)])
674
+ try:
675
+ secondary_y_limits[idx] = fun(
676
+ [secondary_y_limits[idx], fun(yy_box)]
677
+ )
678
+ except Exception:
679
+ Warning(f"bad data")
674
680
  # clean up dfs
675
681
  for df in [df_line, df_box]:
676
682
  df.drop(columns=["fc", "fr"], inplace=True, errors="ignore")
@@ -85,7 +85,7 @@ def sis(
85
85
  accrate = list() # space for acceptance rate
86
86
  sk = list() # space for expected weights
87
87
  sigmak = np.zeros([max_it + 1]) # space for sigmak
88
- sigmak[0] = np.infty # first entry in 'sigmak' is infinity
88
+ sigmak[0] = np.inf # first entry in 'sigmak' is infinity
89
89
 
90
90
  number_fun_eval = 0
91
91
  computational_cost = 0
@@ -1,7 +1,6 @@
1
1
  import numpy as np
2
2
  from scipy import sparse
3
3
  from scipy.sparse.linalg import spsolve
4
- import numpy.matlib
5
4
  from rareeventestimation.problem.problem import NormalProblem, Vectorizer
6
5
 
7
6
  # utilities
@@ -55,9 +54,9 @@ def newtonmethod(f, df, x0, tol, nmax):
55
54
 
56
55
  def eval_quad(nele, L, xGL):
57
56
  ind = np.linspace(1, nele, nele)
58
- XQ = L / nele / 2 * np.matlib.repmat(
59
- xGL.T, 1, len(ind)
60
- ) + L / nele / 2 * np.matlib.repmat((2 * ind - 1), len(xGL), 1)
57
+ XQ = L / nele / 2 * np.tile(xGL.T, (1, len(ind))) + L / nele / 2 * np.tile(
58
+ (2 * ind - 1), (len(xGL), 1)
59
+ )
61
60
  XQ = XQ.T
62
61
  xq = XQ.reshape(len(ind) * np.size(xGL), 1)
63
62
 
@@ -130,7 +129,7 @@ def EigFcnKL(correlationlength, numberroots):
130
129
 
131
130
  def diffusion_equation_solve(h, theta, mu, sigma, function_values):
132
131
  # mesh width and number dof( = number of edges resp.of faces)
133
- n_vertices = np.int(h**-1 + 1)
132
+ n_vertices = int(h**-1 + 1)
134
133
  n_ele = n_vertices - 1
135
134
 
136
135
  # Quadrature weights
@@ -146,9 +145,7 @@ def diffusion_equation_solve(h, theta, mu, sigma, function_values):
146
145
  # Assembling of mass matrix A
147
146
  A = sparse.lil_matrix((n_vertices, n_vertices))
148
147
  Kei = 1 / h / 2 * a_grid
149
- Ke = np.sum(
150
- np.reshape((Kei * np.matlib.repmat(wGL.T, 1, n_ele)).T, (n_ele, 3)).T, 0
151
- )
148
+ Ke = np.sum(np.reshape((Kei * np.tile(wGL.T, (1, n_ele))).T, (n_ele, 3)).T, 0)
152
149
  Ke0 = np.hstack((Ke, [0]))
153
150
  Ke00 = np.hstack(([0], Ke))
154
151
  diagonals = (Ke0, -Ke, -Ke)
@@ -249,4 +246,5 @@ diffusion_problem = NormalProblem(
249
246
  1,
250
247
  name=f"Diffusion Problem (d={parameter_dim})",
251
248
  prob_fail_true=1.682 * 1e-4,
249
+ vectorized=True,
252
250
  )
@@ -42,6 +42,7 @@ def make_flowrate_problem(
42
42
  1,
43
43
  prob_fail_true=3.026 * 1e-4,
44
44
  name=f"Flow-rate Problem (d={d})",
45
+ vectorized=True,
45
46
  )
46
47
 
47
48
 
@@ -1,7 +1,17 @@
1
1
  """Class for problem formulation."""
2
2
  from typing import Callable
3
3
 
4
- from numpy import apply_along_axis, array, ndarray, ndenumerate, zeros, nan, prod, eye
4
+ from numpy import (
5
+ apply_along_axis,
6
+ array,
7
+ asarray,
8
+ ndarray,
9
+ ndenumerate,
10
+ zeros,
11
+ nan,
12
+ prod,
13
+ eye,
14
+ )
5
15
 
6
16
  from rareeventestimation.era.ERANataf import ERANataf
7
17
  from rareeventestimation.era.ERADist import ERADist
@@ -22,6 +32,7 @@ class Problem:
22
32
  eranataf_dist=None,
23
33
  hints=None,
24
34
  name=None,
35
+ vectorized=False,
25
36
  ):
26
37
  """
27
38
  Make an instance of the Problem class.
@@ -35,8 +46,13 @@ class Problem:
35
46
  eranataf_dist ([type], optional): Target distribution as an instance of the ERANataf class. Defaults to None.
36
47
  hints (dict, optional): Dictionary with keyword arguments for solver
37
48
  name (str,optional): Name of problem for stringification
49
+ vectorized (bool, optional): Whether `lsf` accepts a 2-d array of shape `(n, d)`
50
+ and returns the `n` values of its rows. Then SIS passes whole batches of
51
+ points to `lsf` instead of one point at a time, and `lsf` only gets 2-d
52
+ arrays. Defaults to False.
38
53
  """
39
54
  self.lsf = lsf
55
+ self.vectorized = vectorized
40
56
  self.e_fun = e_fun
41
57
  self.sample = sample
42
58
  self.prob_fail_true = prob_fail_true
@@ -89,6 +105,7 @@ class NormalProblem(Problem):
89
105
  mpp=None,
90
106
  hints=None,
91
107
  name=None,
108
+ vectorized=False,
92
109
  ):
93
110
  """
94
111
  Constructor if distribution is standard normal.
@@ -103,6 +120,8 @@ class NormalProblem(Problem):
103
120
  Can be used for performance evaluations in postprocessing.
104
121
  hints (dict, optional): Dictionary with keyword arguments for solver.
105
122
  name (str,optional): Name of problem for stringification.
123
+ vectorized (bool, optional): Whether `lsf` accepts a 2-d array of shape `(n, d)`
124
+ and returns the `n` values of its rows. Defaults to False.
106
125
  """
107
126
 
108
127
  # Define distribution as an ERANataf
@@ -127,9 +146,25 @@ class NormalProblem(Problem):
127
146
  eranataf_dist=eranataf_dist,
128
147
  hints=hints,
129
148
  name=name,
149
+ vectorized=vectorized,
130
150
  )
131
151
 
132
152
 
153
+ def values_per_point(values, n: int) -> ndarray:
154
+ """Return the values of a limit state function for `n` points with shape `(n,)`.
155
+
156
+ Shapes like `(n,)`, `(n, 1)` or `(1,)` for a single point are fine.
157
+ Raise a ValueError if there are not exactly `n` values.
158
+ """
159
+ values = asarray(values)
160
+ if values.size != n:
161
+ raise ValueError(
162
+ f"The limit state function returned {values.size} values "
163
+ f"for {n} points."
164
+ )
165
+ return values.reshape(n)
166
+
167
+
133
168
  class Vectorizer:
134
169
  """
135
170
  A wrapper class for the limit state function.
@@ -141,22 +176,28 @@ class Vectorizer:
141
176
 
142
177
  num_evals = 0
143
178
 
144
- def __init__(self, lsf: Callable, d: int, lsf_2d=None, lsf_msh=None) -> None:
179
+ def __init__(
180
+ self, lsf: Callable, d: int, lsf_2d=None, lsf_msh=None, vectorized=False
181
+ ) -> None:
145
182
  """Write the the callable method for dispatching based on `lsf`.
146
183
  Very slow implementation of the array and mehsgird evaluations!
147
184
  Args:
148
185
  lsf (Callable[[1-d array], float]): The limit state function with a single argument corresponding to a point evaluation
149
186
  d [int]: Dimension of `lsf`'s domain.
150
187
  lsf_2d (Callable[[2-d array], 1-d array]): The limit state function with a single argument corresponding to a 2-d array of shape `(n,d)`, returning a 1-d array of length `n` with the lsf evaluations in the points defined by the rows of the 2-d array.
188
+ vectorized (bool): Whether `lsf` itself evaluates 2-d arrays row by row. If True, `lsf` only gets 2-d arrays: arrays of points go straight to it (unless `lsf_2d` is given) and a single point goes in as an array with one row. Otherwise `lsf` is called once per row.
151
189
  """
152
190
  if isinstance(lsf, Vectorizer):
153
191
  self.d = lsf.d
154
192
  self.lsf_1d = lsf.lsf_1d
155
193
  self.lsf_2d = lsf.lsf_2d
156
194
  self.lsf_msh = lsf.lsf_msh
195
+ self.vectorized = lsf.vectorized
157
196
  self.num_evals = 0
158
197
  else:
159
- if lsf_2d is None:
198
+ if lsf_2d is None and vectorized:
199
+ lsf_2d = lsf
200
+ elif lsf_2d is None:
160
201
 
161
202
  def lsf_2d(xx):
162
203
  return apply_along_axis(lsf, 1, xx)
@@ -174,6 +215,11 @@ class Vectorizer:
174
215
  self.lsf_1d = lsf
175
216
  self.lsf_2d = lsf_2d
176
217
  self.lsf_msh = lsf_msh
218
+ self.vectorized = vectorized
219
+
220
+ def _evaluate_rows(self, xx):
221
+ """Evaluate the rows of `xx` and return one value per row, shape `(n,)`."""
222
+ return values_per_point(self.lsf_2d(xx), xx.shape[0])
177
223
 
178
224
  def __call__(self, *args):
179
225
  """Dispatch to different versions of the limit state function.
@@ -185,11 +231,14 @@ class Vectorizer:
185
231
  if len(args) == 1 and args[0].shape == (self.d,):
186
232
  # Single point evaluation
187
233
  self.num_evals = self.num_evals + 1
234
+ if self.vectorized:
235
+ # a vectorized lsf only gets 2-d arrays, here with one row
236
+ return self._evaluate_rows(args[0][None, :])[0]
188
237
  return self.lsf_1d(args[0])
189
238
  if len(args) == 1 and args[0].ndim == 2 and args[0].shape[1] == self.d:
190
239
  # Evaluation of rows
191
240
  self.num_evals = self.num_evals + args[0].shape[0]
192
- return self.lsf_2d(args[0])
241
+ return self._evaluate_rows(args[0])
193
242
  if len(args) == self.d and all(
194
243
  [x.ndim == self.d and x.shape == args[0].shape for x in args]
195
244
  ):
@@ -21,6 +21,7 @@ prob_convex = NormalProblem(
21
21
  prob_fail_true=prob_fail_convex,
22
22
  name="Convex Problem",
23
23
  mpp=5 / (2 * sqrt(2)) * ones(2),
24
+ vectorized=True,
24
25
  )
25
26
  prob_convex.matlab_str = "@(x) 0.1*(x(:,1)-x(:,2)).^2 - 1/sqrt(2)*(x(:,1)+x(:,2))+2.5"
26
27
 
@@ -43,6 +44,7 @@ def make_linear_problem(d, beta=3.5):
43
44
  prob_fail_true=norm.cdf(-beta),
44
45
  name=f"Linear Problem (d={d})",
45
46
  mpp=beta / sqrt(d) * ones(d),
47
+ vectorized=True,
46
48
  )
47
49
  p.matlab_str = f"@(x) -sum(x)/sqrt(length(x)) + {beta}"
48
50
  return p
@@ -60,7 +62,13 @@ def make_fujita_rackwitz(d, pf=1e-04):
60
62
  pf = gamma.cdf(c, d)
61
63
  mpp = -norm.ppf(exp(-c / d)) * ones(d)
62
64
  prob = NormalProblem(
63
- lsf, d, 1, pf, name=f"Fujita Rackwitz Problem (d={d})", mpp=mpp
65
+ lsf,
66
+ d,
67
+ 1,
68
+ pf,
69
+ name=f"Fujita Rackwitz Problem (d={d})",
70
+ mpp=mpp,
71
+ vectorized=True,
64
72
  )
65
73
  prob.matlab_str = f"@(x) -sum(log(normcdf(-x))) - {c}"
66
74
  return prob
@@ -86,6 +94,7 @@ prob_nonlin_osc = NormalProblem(
86
94
  1,
87
95
  prob_fail_true=6.43 * 1e-6,
88
96
  name="Nonlinear Oscillator Problem",
97
+ vectorized=True,
89
98
  )
90
99
 
91
100
  # problem lists
@@ -75,7 +75,7 @@ def SIS_GM(
75
75
  ):
76
76
  if seed is not None:
77
77
  random.seed(seed=seed)
78
- if (N * p != np.fix(N * p)) or (1 / p != np.fix(1 / p)):
78
+ if (N * p != np.trunc(N * p)) or (1 / p != np.trunc(1 / p)):
79
79
  raise RuntimeError(
80
80
  "N*p and 1/p must be positive integers. Adjust N and p accordingly"
81
81
  )
@@ -195,62 +195,66 @@ def SIS_GM(
195
195
  uk0 = uk[ind, :]
196
196
 
197
197
  # Step 6: perform MH
198
- count = 0
199
- alphak = np.zeros([nchain]) # initialize chain acceptance rate
200
- gk = np.zeros([nsamlev]) # delete previous samples
201
- uk = np.zeros([nsamlev, dim]) # delete previous samples
198
+ # Draw the random numbers of all chains first, in the order in which
199
+ # running one chain after the other draws them. The candidates do not
200
+ # depend on the state of the chain (independence sampler).
201
+ nstep = lenchain + burn
202
+ ucands = np.zeros([nchain, nstep, dim])
203
+ uhelps = np.zeros([nchain, nstep])
202
204
  for k in range(nchain):
203
- # set seed for chain
204
- u0 = uk0[k, :]
205
- g0 = gk0[k]
206
-
207
- for i in range(lenchain + burn):
208
- if i == burn:
209
- count = count - burn
210
-
205
+ for i in range(nstep):
211
206
  # get candidate sample from conditional normal distribution
212
207
  indw = np.random.choice(np.arange(len(ww)), 1, True, ww)[0]
213
- ucand = sp.stats.multivariate_normal.rvs(
208
+ ucands[k, i, :] = sp.stats.multivariate_normal.rvs(
214
209
  mean=mu[:, indw], cov=si[:, :, indw]
215
210
  )
211
+ uhelps[k, i] = sp.stats.uniform.rvs()
216
212
 
217
- # Evaluate limit-state function
218
- gcand = g(ucand)
219
-
220
- # compute acceptance probability
221
- pdfn = 0
222
- pdfd = 0
223
- for ii in range(len(ww)):
224
- pdfn = pdfn + ww[ii] * sp.stats.multivariate_normal.pdf(
225
- u0.T, mu[:, ii], si[:, :, ii]
226
- )
227
- pdfd = pdfd + ww[ii] * sp.stats.multivariate_normal.pdf(
228
- ucand.T, mu[:, ii], si[:, :, ii]
229
- )
230
-
231
- alpha = min(
232
- 1,
233
- sp.stats.norm.cdf(-gcand / sigmak[m + 1])
234
- * np.prod(sp.stats.norm.pdf(ucand))
235
- * pdfn
236
- / sp.stats.norm.cdf(-g0 / sigmak[m + 1])
237
- / np.prod(sp.stats.norm.pdf(u0))
238
- / pdfd,
213
+ # Advance all chains together: one call of g per step for all chains.
214
+ alphak = np.zeros([nchain]) # initialize chain acceptance rate
215
+ gk = np.zeros([nsamlev]) # delete previous samples
216
+ uk = np.zeros([nsamlev, dim]) # delete previous samples
217
+ u0 = uk0.copy() # current state of every chain
218
+ g0 = np.reshape(gk0, nchain)
219
+ for i in range(nstep):
220
+ ucand = ucands[:, i, :]
221
+
222
+ # Evaluate limit-state function
223
+ gcand = np.reshape(g(ucand), nchain)
224
+
225
+ # compute acceptance probability
226
+ pdfn = 0
227
+ pdfd = 0
228
+ for ii in range(len(ww)):
229
+ pdfn = pdfn + ww[ii] * sp.stats.multivariate_normal.pdf(
230
+ u0, mu[:, ii], si[:, :, ii]
239
231
  )
240
- alphak[k] = alphak[k] + alpha / (lenchain + burn)
241
-
242
- # check if sample is accepted
243
- uhelp = sp.stats.uniform.rvs()
244
- if uhelp <= alpha:
245
- uk[count, :] = ucand
246
- gk[count] = gcand
247
- u0 = ucand
248
- g0 = gcand
249
- else:
250
- uk[count, :] = u0
251
- gk[count] = g0
252
-
253
- count = count + 1
232
+ pdfd = pdfd + ww[ii] * sp.stats.multivariate_normal.pdf(
233
+ ucand, mu[:, ii], si[:, :, ii]
234
+ )
235
+
236
+ alpha = np.minimum(
237
+ 1,
238
+ sp.stats.norm.cdf(-gcand / sigmak[m + 1])
239
+ * np.prod(sp.stats.norm.pdf(ucand), axis=1)
240
+ * pdfn
241
+ / sp.stats.norm.cdf(-g0 / sigmak[m + 1])
242
+ / np.prod(sp.stats.norm.pdf(u0), axis=1)
243
+ / pdfd,
244
+ )
245
+ alphak = alphak + alpha / nstep
246
+
247
+ # check if sample is accepted
248
+ accept = uhelps[:, i] <= alpha
249
+ u0 = np.where(accept[:, None], ucand, u0)
250
+ g0 = np.where(accept, gcand, g0)
251
+
252
+ # chain k keeps its samples after the burn-in in rows
253
+ # k*lenchain to (k+1)*lenchain - 1
254
+ if i >= burn:
255
+ rows = np.arange(nchain) * lenchain + (i - burn)
256
+ uk[rows, :] = u0
257
+ gk[rows] = g0
254
258
 
255
259
  uk = uk[:nsamlev, :]
256
260
  gk = gk[:nsamlev]
@@ -75,7 +75,7 @@ def SIS_aCS(
75
75
  ):
76
76
  if seed is not None:
77
77
  random.seed(seed=seed)
78
- if (N * p != np.fix(N * p)) or (1 / p != np.fix(1 / p)):
78
+ if (N * p != np.trunc(N * p)) or (1 / p != np.trunc(1 / p)):
79
79
  raise RuntimeError(
80
80
  "N*p and 1/p must be positive integers. Adjust N and p accordingly"
81
81
  )
@@ -211,49 +211,59 @@ def SIS_aCS(
211
211
  sigmafk = min(lam * sigmaf, 1)
212
212
  rhok = np.sqrt(1 - sigmafk**2)
213
213
  counta = 0
214
- count = 0
214
+
215
+ # Draw the random numbers of all chains first, in the order in which
216
+ # running one chain after the other draws them: for every step the
217
+ # standard normal part of the candidate, then the uniform number.
218
+ nstep = lenchain + burn
219
+ zs = np.zeros([nchain, nstep, dim])
220
+ uhelps = np.zeros([nchain, nstep])
221
+ for k in range(nchain):
222
+ for i in range(nstep):
223
+ zs[k, i, :] = np.random.normal(size=dim)
224
+ uhelps[k, i] = sp.stats.uniform.rvs()
215
225
 
216
226
  # initialize chain acceptance rate
217
227
  alphak = np.zeros([nchain]) # initialize chain acceptance rate
218
228
  gk = np.zeros([nsamlev]) # delete previous samples
219
229
  uk = np.zeros([nsamlev, dim]) # delete previous samples
220
- for k in range(nchain):
221
- # set seed for chain
222
- u0 = uk0[k, :]
223
- g0 = gk0[k]
224
- for i in range(lenchain + burn):
225
- if i == burn:
226
- count = count - burn
227
230
 
231
+ # The chains run in groups of adapchains chains. All chains of a group
232
+ # take each step together, with one call of g. After a full group the
233
+ # chain correlation is adapted, as before after every adapchains chains.
234
+ for start in range(0, nchain, adapchains):
235
+ ks = np.arange(start, min(start + adapchains, nchain))
236
+ u0 = uk0[ks, :] # current state of the chains in the group
237
+ g0 = np.reshape(gk0[ks], len(ks))
238
+ for i in range(nstep):
228
239
  # get candidate sample from conditional normal distribution
229
- ucand = np.random.normal(loc=rhok * u0, scale=sigmafk)
230
- # ucand = np.random.multivariate_normal(u0*lam, np.identity(dim) * (1 - lam ** 2))
240
+ ucand = rhok * u0 + sigmafk * zs[ks, i, :]
231
241
 
232
242
  # Evaluate limit-state function
233
- gcand = g(ucand)
243
+ gcand = np.reshape(g(ucand), len(ks))
234
244
 
235
245
  # compute acceptance probability
236
- alpha = min(
246
+ alpha = np.minimum(
237
247
  1,
238
248
  sp.stats.norm.cdf(-gcand / sigmak[m + 1])
239
249
  / sp.stats.norm.cdf(-g0 / sigmak[m + 1]),
240
250
  )
241
- alphak[k] = alphak[k] + alpha / (lenchain + burn)
251
+ alphak[ks] = alphak[ks] + alpha / nstep
242
252
 
243
253
  # check if sample is accepted
244
- uhelp = sp.stats.uniform.rvs()
245
- if uhelp <= alpha:
246
- uk[count, :] = ucand
247
- gk[count] = gcand
248
- u0 = ucand
249
- g0 = gcand
250
- else:
251
- uk[count, :] = u0
252
- gk[count] = g0
253
-
254
- count += 1
254
+ accept = uhelps[ks, i] <= alpha
255
+ u0 = np.where(accept[:, None], ucand, u0)
256
+ g0 = np.where(accept, gcand, g0)
257
+
258
+ # chain k keeps its samples after the burn-in in rows
259
+ # k*lenchain to (k+1)*lenchain - 1
260
+ if i >= burn:
261
+ rows = ks * lenchain + (i - burn)
262
+ uk[rows, :] = u0
263
+ gk[rows] = g0
255
264
 
256
265
  # adapt the chain correlation
266
+ k = ks[-1]
257
267
  if adapflag == 1:
258
268
  # check whether to adapt now
259
269
  if (k + 1) % adapchains == 0:
@@ -2,8 +2,7 @@
2
2
  import traceback
3
3
  from copy import deepcopy
4
4
  from dataclasses import dataclass
5
- from distutils.log import warn
6
- from logging import info
5
+ from logging import info, warning
7
6
  from numbers import Real
8
7
  from sys import float_info
9
8
  from typing import Optional
@@ -54,7 +53,7 @@ from rareeventestimation.utilities import (
54
53
 
55
54
  from rareeventestimation.enkf.EnKF_rare_events import EnKF_rare_events
56
55
  from rareeventestimation.era.ERANataf import ERANataf
57
- from rareeventestimation.problem.problem import Vectorizer
56
+ from rareeventestimation.problem.problem import Vectorizer, values_per_point
58
57
  from rareeventestimation.sis.SIS_aCS import SIS_aCS
59
58
  from rareeventestimation.sis.SIS_GM import SIS_GM
60
59
  from rareeventestimation.mls2mc.SIS_VMFNM import sis
@@ -175,8 +174,8 @@ class CBREE(Solver):
175
174
 
176
175
  def __init__(
177
176
  self,
178
- stepsize_adaptivity=True,
179
177
  stepsize_tolerance=0.5,
178
+ t_step=-1,
180
179
  num_steps=100,
181
180
  tgt_fun="algebraic",
182
181
  observation_window=5,
@@ -202,12 +201,9 @@ class CBREE(Solver):
202
201
  The constructor can handle the following keyword arguments.
203
202
 
204
203
  Args:
205
- stepsize_adaptivity (bool|Real, optional):: Whether to update `t_step` adaptively. Defaults to `True`.
206
- Can be one of:
207
- * `True`
208
- * positive number: Fix stepsize of exponential Euler method. Corresponds to gridsize `-log(t_step)`.
209
-
210
204
  stepsize_tolerance (float, optional): Tolerance for updating `t_step`. Defaults to 0.5.
205
+ t_step (float, optional): Set to a positive number to set a constant
206
+ stepssize. Otherwise choose stepsize adaptively. Defaults to -1.
211
207
  num_steps (int, optional): Maximal number of steps. Defaults to 100.
212
208
  tgt_fun (str, optional): Which smoothing function should be used.
213
209
  Can be one of:
@@ -262,14 +258,12 @@ class CBREE(Solver):
262
258
  callback (Callable, optional): Apply this function to the current `CBREECache` after each iteration. Defaults to None.
263
259
  """
264
260
  super().__init__()
265
- if stepsize_adaptivity is True:
266
- self.stepsize_adaptivity = stepsize_adaptivity
267
- else:
268
- assert (
269
- stepsize_adaptivity > 0
270
- ), f"sigma_adaptivity must be either a positive number or `True`. I got '{sigma_adaptivity}'"
271
- self.t_step = stepsize_adaptivity # constant stepsize
261
+ if t_step > 0:
272
262
  self.stepsize_adaptivity = False
263
+ self.t_step = t_step
264
+ else:
265
+ self.stepsize_adaptivity = True
266
+ print(f"adaptive: {self.stepsize_adaptivity}")
273
267
 
274
268
  if isinstance(sigma_adaptivity, str):
275
269
  assert sigma_adaptivity in ["cvar", "sfp"]
@@ -432,7 +426,7 @@ class CBREE(Solver):
432
426
  except Exception as e:
433
427
  msg = str(e)
434
428
  if not self.verbose:
435
- warn(str(e))
429
+ warning(str(e))
436
430
  break
437
431
  # maybe prune list
438
432
  if not self.save_history and len(cache_list) > self.observation_window:
@@ -447,7 +441,7 @@ class CBREE(Solver):
447
441
  except Exception as e:
448
442
  msg = str(e)
449
443
  if not self.verbose:
450
- warn(str(e))
444
+ warning(str(e))
451
445
  break
452
446
  # maybe print info about this iteration
453
447
  if self.verbose:
@@ -911,7 +905,7 @@ class CBREE(Solver):
911
905
  except Exception as e:
912
906
  msg = str(e)
913
907
  if not self.verbose:
914
- warn(str(e))
908
+ warning(str(e))
915
909
  break
916
910
 
917
911
  # maybe print info about this iteration
@@ -982,9 +976,18 @@ class ENKF(Solver):
982
976
  Please consult the credits section of the package's readme file.
983
977
  """
984
978
 
985
- def __init__(self, **kwargs) -> None:
979
+ def __init__(
980
+ self,
981
+ *,
982
+ cvar_tgt=1.0,
983
+ mixture_model="GM",
984
+ num_steps=100,
985
+ num_comps=1,
986
+ localize=False,
987
+ seed=None,
988
+ ) -> None:
986
989
  """
987
- The constructor can handle the following keyword arguments.
990
+ The constructor takes the following keyword arguments, and no others.
988
991
 
989
992
  Args:
990
993
  cvar_tgt: Stop if coefficient of variation is smaller than this, Defaults to 1.
@@ -998,16 +1001,16 @@ class ENKF(Solver):
998
1001
  seed: Seed for the random number generator. Defaults to None.
999
1002
  """
1000
1003
  super().__init__()
1001
- self.cvar_tgt = kwargs.get("cvar_tgt", 1.0)
1002
- self.mixture_model = kwargs.get("mixture_model", "GM")
1004
+ self.cvar_tgt = cvar_tgt
1005
+ self.mixture_model = mixture_model
1003
1006
  assert self.mixture_model in [
1004
1007
  "GM",
1005
1008
  "vMFNM",
1006
1009
  ], "Importance sampling distribution must be 'GM' or 'vMFNM'."
1007
- self.num_steps = kwargs.get("num_steps", 100)
1008
- self.num_comps = kwargs.get("num_comps", 1)
1009
- self.localize = kwargs.get("localize", False)
1010
- self.seed = kwargs.get("seed", None)
1010
+ self.num_steps = num_steps
1011
+ self.num_comps = num_comps
1012
+ self.localize = localize
1013
+ self.seed = seed
1011
1014
 
1012
1015
  def __str__(self) -> str:
1013
1016
  """Return abbreviated name of method."""
@@ -1055,9 +1058,9 @@ class ENKF(Solver):
1055
1058
  other={"Final Iteration": array([enkf.uk])},
1056
1059
  )
1057
1060
  except Exception as e:
1058
- warn(str(e))
1059
- Solution(
1060
- zeros(0),
1061
+ warning(str(e))
1062
+ return Solution(
1063
+ zeros((1, 0, 0)),
1061
1064
  array([nan]),
1062
1065
  zeros((1, 0)) * nan,
1063
1066
  array([nan]),
@@ -1072,9 +1075,21 @@ class SIS(Solver):
1072
1075
  Please consult the credits section of the package's readme file.
1073
1076
  """
1074
1077
 
1075
- def __init__(self, **kwargs) -> None:
1078
+ def __init__(
1079
+ self,
1080
+ *,
1081
+ num_chains_wrt_sample=0.1,
1082
+ burn_in=0,
1083
+ cvar_tgt=1.0,
1084
+ mixture_model="GM",
1085
+ num_comps=1,
1086
+ seed=None,
1087
+ fixed_initial_sample=True,
1088
+ verbose=False,
1089
+ return_other=False,
1090
+ ) -> None:
1076
1091
  """
1077
- The constructor can handle the following keyword arguments.
1092
+ The constructor takes the following keyword arguments, and no others.
1078
1093
 
1079
1094
  Args:
1080
1095
  num_chains_wrt_sample: Use `num_chains_wrt_sample`*sample-size number of chains for the MCMC routine.
@@ -1094,20 +1109,20 @@ class SIS(Solver):
1094
1109
  and coefficient of variation of the weights.
1095
1110
  """
1096
1111
  super().__init__()
1097
- self.num_chains_wrt_sample = kwargs.get("num_chains_wrt_sample", 0.1)
1098
- self.burn_in = kwargs.get("burn_in", 0)
1099
- self.cvar_tgt = kwargs.get("cvar_tgt", 1.0)
1100
- self.mixture_model = kwargs.get("mixture_model", "GM")
1112
+ self.num_chains_wrt_sample = num_chains_wrt_sample
1113
+ self.burn_in = burn_in
1114
+ self.cvar_tgt = cvar_tgt
1115
+ self.mixture_model = mixture_model
1101
1116
  assert self.mixture_model in [
1102
1117
  "GM",
1103
1118
  "aCS",
1104
1119
  "vMFNM",
1105
1120
  ], "mixture_model must be either 'GM' or 'aCS'"
1106
- self.num_comps = kwargs.get("num_comps", 1)
1107
- self.seed = kwargs.get("seed", None)
1108
- self.fixed_initial_sample = kwargs.get("fixed_initial_sample", True)
1109
- self.verbose = kwargs.get("verbose", False)
1110
- self.return_other = kwargs.get("return_other", False)
1121
+ self.num_comps = num_comps
1122
+ self.seed = seed
1123
+ self.fixed_initial_sample = fixed_initial_sample
1124
+ self.verbose = verbose
1125
+ self.return_other = return_other
1111
1126
 
1112
1127
  def __str__(self) -> str:
1113
1128
  """Return abbreviated name of method."""
@@ -1129,7 +1144,7 @@ class SIS(Solver):
1129
1144
  N = prob.sample.shape[0]
1130
1145
  d = prob.sample.shape[1]
1131
1146
  p = self.num_chains_wrt_sample
1132
- my_lsf = Vectorizer(prob.lsf, d)
1147
+ my_lsf = Vectorizer(prob.lsf, d, vectorized=getattr(prob, "vectorized", False))
1133
1148
  if self.fixed_initial_sample:
1134
1149
  initial_sample = deepcopy(prob.sample)
1135
1150
  else:
@@ -1178,9 +1193,9 @@ class SIS(Solver):
1178
1193
  verbose=self.verbose,
1179
1194
  )
1180
1195
  except Exception as e:
1181
- warn(str(e))
1182
- Solution(
1183
- zeros(0, 0),
1196
+ warning(str(e))
1197
+ return Solution(
1198
+ zeros((1, N, 0)),
1184
1199
  array([nan]),
1185
1200
  zeros((1, N)) * nan,
1186
1201
  array([nan]),
@@ -1252,7 +1267,9 @@ class CMC(Solver):
1252
1267
  # evaluate this batch
1253
1268
  prob.set_sample(current_batch_size, seed=batch_seed)
1254
1269
  final_sample[cost : cost + current_batch_size, ...] = prob.sample
1255
- lsf_evals[cost : cost + current_batch_size] = prob.lsf(prob.sample)
1270
+ lsf_evals[cost : cost + current_batch_size] = values_per_point(
1271
+ prob.lsf(prob.sample), current_batch_size
1272
+ )
1256
1273
  cost += current_batch_size
1257
1274
  pf = sum(lsf_evals[0:cost] <= 0) / cost
1258
1275
  cvar = variation(lsf_evals[0:cost] <= 0, nan_policy="omit")
@@ -1260,10 +1277,15 @@ class CMC(Solver):
1260
1277
  print(f" Current estimate: {pf}, cvar: {cvar}")
1261
1278
 
1262
1279
  except Exception as e:
1263
- warn(str(e))
1280
+ warning(str(e))
1264
1281
  print(traceback.format_exc())
1265
1282
  msg = str(e)
1283
+ # a broken lsf fails on every batch, no need to try them all
1284
+ break
1266
1285
  prob.sample = final_sample
1286
+ if cost == 0:
1287
+ # no batch was evaluated, so there is no estimate
1288
+ pf = nan
1267
1289
 
1268
1290
  return Solution(
1269
1291
  final_sample[None, ...],