CUQIpy 1.0.0.post0.dev229__py3-none-any.whl → 1.0.0.post0.dev337__py3-none-any.whl
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.
Potentially problematic release.
This version of CUQIpy might be problematic. Click here for more details.
- {CUQIpy-1.0.0.post0.dev229.dist-info → CUQIpy-1.0.0.post0.dev337.dist-info}/METADATA +1 -1
- {CUQIpy-1.0.0.post0.dev229.dist-info → CUQIpy-1.0.0.post0.dev337.dist-info}/RECORD +19 -15
- cuqi/_version.py +3 -3
- cuqi/experimental/mcmc/__init__.py +4 -0
- cuqi/experimental/mcmc/_conjugate.py +77 -0
- cuqi/experimental/mcmc/_conjugate_approx.py +75 -0
- cuqi/experimental/mcmc/_cwmh.py +29 -42
- cuqi/experimental/mcmc/_direct.py +28 -0
- cuqi/experimental/mcmc/_gibbs.py +267 -0
- cuqi/experimental/mcmc/_hmc.py +34 -34
- cuqi/experimental/mcmc/_langevin_algorithm.py +5 -4
- cuqi/experimental/mcmc/_laplace_approximation.py +11 -13
- cuqi/experimental/mcmc/_mh.py +9 -16
- cuqi/experimental/mcmc/_pcn.py +14 -34
- cuqi/experimental/mcmc/_rto.py +25 -52
- cuqi/experimental/mcmc/_sampler.py +186 -59
- {CUQIpy-1.0.0.post0.dev229.dist-info → CUQIpy-1.0.0.post0.dev337.dist-info}/LICENSE +0 -0
- {CUQIpy-1.0.0.post0.dev229.dist-info → CUQIpy-1.0.0.post0.dev337.dist-info}/WHEEL +0 -0
- {CUQIpy-1.0.0.post0.dev229.dist-info → CUQIpy-1.0.0.post0.dev337.dist-info}/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: CUQIpy
|
|
3
|
-
Version: 1.0.0.post0.
|
|
3
|
+
Version: 1.0.0.post0.dev337
|
|
4
4
|
Summary: Computational Uncertainty Quantification for Inverse problems in Python
|
|
5
5
|
Maintainer-email: "Nicolai A. B. Riis" <nabr@dtu.dk>, "Jakob S. Jørgensen" <jakj@dtu.dk>, "Amal M. Alghamdi" <amaal@dtu.dk>, Chao Zhang <chaz@dtu.dk>
|
|
6
6
|
License: Apache License
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
cuqi/__init__.py,sha256=LsGilhl-hBLEn6Glt8S_l0OJzAA1sKit_rui8h-D-p0,488
|
|
2
2
|
cuqi/_messages.py,sha256=fzEBrZT2kbmfecBBPm7spVu7yHdxGARQB4QzXhJbCJ0,415
|
|
3
|
-
cuqi/_version.py,sha256=
|
|
3
|
+
cuqi/_version.py,sha256=bop6laBkqMl8sVGPBD_LKMsjPG6Dv1XBkb3SMN2t8KY,510
|
|
4
4
|
cuqi/config.py,sha256=wcYvz19wkeKW2EKCGIKJiTpWt5kdaxyt4imyRkvtTRA,526
|
|
5
5
|
cuqi/diagnostics.py,sha256=5OrbJeqpynqRXOe5MtOKKhe7EAVdOEpHIqHnlMW9G_c,3029
|
|
6
6
|
cuqi/array/__init__.py,sha256=-EeiaiWGNsE3twRS4dD814BIlfxEsNkTCZUc5gjOXb0,30
|
|
@@ -32,15 +32,19 @@ cuqi/distribution/_normal.py,sha256=UeoTtGDT7YSf4ZNo2amlVF9K-YQpYbf8q76jcRJTVFw,
|
|
|
32
32
|
cuqi/distribution/_posterior.py,sha256=zAfL0GECxekZ2lBt1W6_LN0U_xskMwK4VNce5xAF7ig,5018
|
|
33
33
|
cuqi/distribution/_uniform.py,sha256=7xJmCZH_LPhuGkwEDGh-_CTtzcWKrXMOxtTJUFb7Ydo,1607
|
|
34
34
|
cuqi/experimental/__init__.py,sha256=vhZvyMX6rl8Y0haqCzGLPz6PSUKyu75XMQbeDHqTTrw,83
|
|
35
|
-
cuqi/experimental/mcmc/__init__.py,sha256=
|
|
36
|
-
cuqi/experimental/mcmc/
|
|
37
|
-
cuqi/experimental/mcmc/
|
|
38
|
-
cuqi/experimental/mcmc/
|
|
39
|
-
cuqi/experimental/mcmc/
|
|
40
|
-
cuqi/experimental/mcmc/
|
|
41
|
-
cuqi/experimental/mcmc/
|
|
42
|
-
cuqi/experimental/mcmc/
|
|
43
|
-
cuqi/experimental/mcmc/
|
|
35
|
+
cuqi/experimental/mcmc/__init__.py,sha256=TyN_CASRnTcUBQYxoYUeSUBhorLzVwgPQaY72-6hXm8,537
|
|
36
|
+
cuqi/experimental/mcmc/_conjugate.py,sha256=qYrBvZ9wNK4oBz0c0RRUtQkbpPIHI3BvBYSLRw8ok5k,3757
|
|
37
|
+
cuqi/experimental/mcmc/_conjugate_approx.py,sha256=JQe9gmnNespCxSP6vaZWfizFvUWUh8Jn-jRqsJYyNeM,2839
|
|
38
|
+
cuqi/experimental/mcmc/_cwmh.py,sha256=dbvmy6Fyr_xszbO3YmYcRsDaRRtQfPimLo6rbp0II6M,6898
|
|
39
|
+
cuqi/experimental/mcmc/_direct.py,sha256=E3UevdJ_DLk2wL0lid1TTKkdmgnIMJ5Ihr7iM1jU8KI,738
|
|
40
|
+
cuqi/experimental/mcmc/_gibbs.py,sha256=z6YOCiBM1YuZbQHfdmsArR-pT61dsS14F_O4kUxsNYM,10638
|
|
41
|
+
cuqi/experimental/mcmc/_hmc.py,sha256=0sZMHtnNFGGtQdzpx-cgqA0xyfvGy7r4K62RH3AQNa4,19285
|
|
42
|
+
cuqi/experimental/mcmc/_langevin_algorithm.py,sha256=n6WRQooKuUDjmqF-CtpcSNFDvaHCgLKhWxX-hi7h_ZA,8224
|
|
43
|
+
cuqi/experimental/mcmc/_laplace_approximation.py,sha256=VVLOKQWZViT1CZg5RDiycG6trpKdQg94aQCKrAdSl2g,5707
|
|
44
|
+
cuqi/experimental/mcmc/_mh.py,sha256=6yQjdpx3fMKvescRFL94Ik-ALTKi0BwBRXbTsIsck-I,2630
|
|
45
|
+
cuqi/experimental/mcmc/_pcn.py,sha256=T4T32mfoii3k6Jfz0qxPQbwdh6wdVOxttiEP7NWaZzg,3386
|
|
46
|
+
cuqi/experimental/mcmc/_rto.py,sha256=wzlqm8waT6mB-3RFtMz-PlSUa1Yy3dfUoyKKahTaey4,10086
|
|
47
|
+
cuqi/experimental/mcmc/_sampler.py,sha256=4dh9XVALkD3Ro9vkLZkNoFNge7Xv8QRbjh4LB7NY0HI,20073
|
|
44
48
|
cuqi/geometry/__init__.py,sha256=Tz1WGzZBY-QGH3c0GiyKm9XHN8MGGcnU6TUHLZkzB3o,842
|
|
45
49
|
cuqi/geometry/_geometry.py,sha256=WYFC-4_VBTW73b2ldsnfGYKvdSiCE8plr89xTSmkadg,46804
|
|
46
50
|
cuqi/implicitprior/__init__.py,sha256=ZRZ9fgxgEl5n0A9F7WCl1_jid-GUiC8ZLkyTmGQmFlY,100
|
|
@@ -77,8 +81,8 @@ cuqi/testproblem/_testproblem.py,sha256=x769LwwRdJdzIiZkcQUGb_5-vynNTNALXWKato7s
|
|
|
77
81
|
cuqi/utilities/__init__.py,sha256=T4tLsC215MknBCsw_C0Qeeg_ox26aDUrCA5hbWvNQkU,387
|
|
78
82
|
cuqi/utilities/_get_python_variable_name.py,sha256=QwlBVj2koJRA8s8pWd554p7-ElcI7HUwY32HknaR92E,1827
|
|
79
83
|
cuqi/utilities/_utilities.py,sha256=MWAqV6L5btMpWwlUzrZYuV2VeSpfTbOaLRMRkuw2WIA,8509
|
|
80
|
-
CUQIpy-1.0.0.post0.
|
|
81
|
-
CUQIpy-1.0.0.post0.
|
|
82
|
-
CUQIpy-1.0.0.post0.
|
|
83
|
-
CUQIpy-1.0.0.post0.
|
|
84
|
-
CUQIpy-1.0.0.post0.
|
|
84
|
+
CUQIpy-1.0.0.post0.dev337.dist-info/LICENSE,sha256=kJWRPrtRoQoZGXyyvu50Uc91X6_0XRaVfT0YZssicys,10799
|
|
85
|
+
CUQIpy-1.0.0.post0.dev337.dist-info/METADATA,sha256=d44JgxdIjhKP_Z33mhZ3vll3JbJrLsxAIIIpFh6N6WU,18393
|
|
86
|
+
CUQIpy-1.0.0.post0.dev337.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
|
|
87
|
+
CUQIpy-1.0.0.post0.dev337.dist-info/top_level.txt,sha256=AgmgMc6TKfPPqbjV0kvAoCBN334i_Lwwojc7HE3ZwD0,5
|
|
88
|
+
CUQIpy-1.0.0.post0.dev337.dist-info/RECORD,,
|
cuqi/_version.py
CHANGED
|
@@ -8,11 +8,11 @@ import json
|
|
|
8
8
|
|
|
9
9
|
version_json = '''
|
|
10
10
|
{
|
|
11
|
-
"date": "2024-
|
|
11
|
+
"date": "2024-06-11T10:55:36+0200",
|
|
12
12
|
"dirty": false,
|
|
13
13
|
"error": null,
|
|
14
|
-
"full-revisionid": "
|
|
15
|
-
"version": "1.0.0.post0.
|
|
14
|
+
"full-revisionid": "b3c53f2ac21c807186dc35053421615c1cb3f205",
|
|
15
|
+
"version": "1.0.0.post0.dev337"
|
|
16
16
|
}
|
|
17
17
|
''' # END VERSION_JSON
|
|
18
18
|
|
|
@@ -8,3 +8,7 @@ from ._rto import LinearRTONew, RegularizedLinearRTONew
|
|
|
8
8
|
from ._cwmh import CWMHNew
|
|
9
9
|
from ._laplace_approximation import UGLANew
|
|
10
10
|
from ._hmc import NUTSNew
|
|
11
|
+
from ._gibbs import HybridGibbsNew
|
|
12
|
+
from ._conjugate import ConjugateNew
|
|
13
|
+
from ._conjugate_approx import ConjugateApproxNew
|
|
14
|
+
from ._direct import DirectNew
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from cuqi.experimental.mcmc import SamplerNew
|
|
3
|
+
from cuqi.distribution import Posterior, Gaussian, Gamma, GMRF
|
|
4
|
+
from cuqi.implicitprior import RegularizedGaussian, RegularizedGMRF
|
|
5
|
+
|
|
6
|
+
class ConjugateNew(SamplerNew):
|
|
7
|
+
""" Conjugate sampler
|
|
8
|
+
|
|
9
|
+
Sampler for sampling a posterior distribution where the likelihood and prior are conjugate.
|
|
10
|
+
|
|
11
|
+
Currently supported conjugate pairs are:
|
|
12
|
+
- (Gaussian, Gamma) where Gamma is defined on the precision parameter of the Gaussian
|
|
13
|
+
- (GMRF, Gamma) where Gamma is defined on the precision parameter of the GMRF
|
|
14
|
+
- (RegularizedGaussian, Gamma) with nonnegativity constraints only and Gamma is defined on the precision parameter of the RegularizedGaussian
|
|
15
|
+
- (RegularizedGMRF, Gamma) with nonnegativity constraints only and Gamma is defined on the precision parameter of the RegularizedGMRF
|
|
16
|
+
|
|
17
|
+
Gamma distribution must be univariate.
|
|
18
|
+
|
|
19
|
+
Currently, the sampler does NOT automatically check that the conjugate distributions are defined on the correct parameters.
|
|
20
|
+
|
|
21
|
+
For more information on conjugate pairs, see https://en.wikipedia.org/wiki/Conjugate_prior.
|
|
22
|
+
|
|
23
|
+
For implicit regularized Gaussians see:
|
|
24
|
+
|
|
25
|
+
[1] Everink, Jasper M., Yiqiu Dong, and Martin S. Andersen. "Bayesian inference with projected densities." SIAM/ASA Journal on Uncertainty Quantification 11.3 (2023): 1025-1043.
|
|
26
|
+
|
|
27
|
+
"""
|
|
28
|
+
def _initialize(self):
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
def validate_target(self):
|
|
32
|
+
|
|
33
|
+
if not isinstance(self.target, Posterior):
|
|
34
|
+
raise TypeError("Conjugate sampler requires a target of type Posterior")
|
|
35
|
+
|
|
36
|
+
if not isinstance(self.target.likelihood.distribution, (Gaussian, GMRF, RegularizedGaussian, RegularizedGMRF)):
|
|
37
|
+
raise ValueError("Conjugate sampler only works with a Gaussian-type likelihood function")
|
|
38
|
+
|
|
39
|
+
if not isinstance(self.target.prior, Gamma):
|
|
40
|
+
raise ValueError("Conjugate sampler only works with Gamma prior")
|
|
41
|
+
|
|
42
|
+
if not self.target.prior.dim == 1:
|
|
43
|
+
raise ValueError("Conjugate sampler only works with univariate Gamma prior")
|
|
44
|
+
|
|
45
|
+
if isinstance(self.target.likelihood.distribution, (RegularizedGaussian, RegularizedGMRF)) and self.target.likelihood.distribution.preset not in ["nonnegativity"]:
|
|
46
|
+
raise ValueError("Conjugate sampler only works with implicit regularized Gaussian likelihood with nonnegativity constraints")
|
|
47
|
+
|
|
48
|
+
def step(self):
|
|
49
|
+
# Extract variables
|
|
50
|
+
b = self.target.likelihood.data #mu
|
|
51
|
+
m = self._calc_m_for_Gaussians(b) #n
|
|
52
|
+
Ax = self.target.likelihood.distribution.mean #x_i
|
|
53
|
+
L = self.target.likelihood.distribution(np.array([1])).sqrtprec #L
|
|
54
|
+
alpha = self.target.prior.shape #alpha
|
|
55
|
+
beta = self.target.prior.rate #beta
|
|
56
|
+
|
|
57
|
+
# Create Gamma distribution and sample
|
|
58
|
+
dist = Gamma(shape=m/2+alpha,rate=.5*np.linalg.norm(L@(Ax-b))**2+beta)
|
|
59
|
+
|
|
60
|
+
self.current_point = dist.sample()
|
|
61
|
+
|
|
62
|
+
def tune(self, skip_len, update_count):
|
|
63
|
+
pass
|
|
64
|
+
|
|
65
|
+
def _calc_m_for_Gaussians(self, b):
|
|
66
|
+
""" Helper method to calculate m parameter for Gaussian-Gamma conjugate pair.
|
|
67
|
+
|
|
68
|
+
Classically m defines the number of observations in the Gaussian likelihood function.
|
|
69
|
+
|
|
70
|
+
However, for implicit regularized Gaussians, m is the number of non-zero elements in the data vector b see [1].
|
|
71
|
+
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
if isinstance(self.target.likelihood.distribution, (Gaussian, GMRF)):
|
|
75
|
+
return len(b)
|
|
76
|
+
elif isinstance(self.target.likelihood.distribution, (RegularizedGaussian, RegularizedGMRF)):
|
|
77
|
+
return np.count_nonzero(b)
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from cuqi.experimental.mcmc import SamplerNew
|
|
3
|
+
from cuqi.distribution import Posterior, LMRF, Gamma
|
|
4
|
+
import scipy as sp
|
|
5
|
+
|
|
6
|
+
class ConjugateApproxNew(SamplerNew):
|
|
7
|
+
""" Approximate Conjugate sampler
|
|
8
|
+
|
|
9
|
+
Sampler for sampling a posterior distribution where the likelihood and prior can be approximated
|
|
10
|
+
by a conjugate pair.
|
|
11
|
+
|
|
12
|
+
Currently supported pairs are:
|
|
13
|
+
- (LMRF, Gamma): Approximated by (Gaussian, Gamma) where Gamma is defined on the inverse of the scale parameter of the LMRF distribution.
|
|
14
|
+
|
|
15
|
+
Gamma distribution must be univariate.
|
|
16
|
+
|
|
17
|
+
LMRF likelihood must have zero mean.
|
|
18
|
+
|
|
19
|
+
Currently, the sampler does NOT automatically check that the conjugate distributions are defined on the correct parameters.
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
For more information on conjugate pairs, see https://en.wikipedia.org/wiki/Conjugate_prior.
|
|
23
|
+
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def _initialize(self):
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
def validate_target(self):
|
|
30
|
+
|
|
31
|
+
if not isinstance(self.target, Posterior):
|
|
32
|
+
raise TypeError("Approximate conjugate sampler requires a target of type Posterior")
|
|
33
|
+
|
|
34
|
+
if not isinstance(self.target.likelihood.distribution, LMRF):
|
|
35
|
+
raise ValueError("Approximate conjugate sampler only works with LMRF likelihood function")
|
|
36
|
+
|
|
37
|
+
if not isinstance(self.target.prior, Gamma):
|
|
38
|
+
raise ValueError("Approximate conjugate sampler only works with Gamma prior")
|
|
39
|
+
|
|
40
|
+
if not self.target.prior.dim == 1:
|
|
41
|
+
raise ValueError("Approximate conjugate sampler only works with univariate Gamma prior")
|
|
42
|
+
|
|
43
|
+
if np.sum(self.target.likelihood.distribution.location) != 0:
|
|
44
|
+
raise ValueError("Approximate conjugate sampler only works with zero mean LMRF likelihood")
|
|
45
|
+
|
|
46
|
+
def step(self):
|
|
47
|
+
# Extract variables
|
|
48
|
+
# Here we approximate the LMRF with a Gaussian
|
|
49
|
+
|
|
50
|
+
# Extract diff_op from target likelihood
|
|
51
|
+
D = self.target.likelihood.distribution._diff_op
|
|
52
|
+
n = D.shape[0]
|
|
53
|
+
|
|
54
|
+
# Gaussian approximation of LMRF prior as function of x_k
|
|
55
|
+
# See Uribe et al. (2022) for details
|
|
56
|
+
# Current has a zero mean assumption on likelihood! TODO
|
|
57
|
+
beta=1e-5
|
|
58
|
+
def Lk_fun(x_k):
|
|
59
|
+
dd = 1/np.sqrt((D @ x_k)**2 + beta*np.ones(n))
|
|
60
|
+
W = sp.sparse.diags(dd)
|
|
61
|
+
return W.sqrt() @ D
|
|
62
|
+
|
|
63
|
+
x = self.target.likelihood.data #x
|
|
64
|
+
d = len(x) #d
|
|
65
|
+
Lx = Lk_fun(x)@x #Lx
|
|
66
|
+
alpha = self.target.prior.shape #alpha
|
|
67
|
+
beta = self.target.prior.rate #beta
|
|
68
|
+
|
|
69
|
+
# Create Gamma distribution and sample
|
|
70
|
+
dist = Gamma(shape=d+alpha, rate=np.linalg.norm(Lx)**2+beta)
|
|
71
|
+
|
|
72
|
+
self.current_point = dist.sample()
|
|
73
|
+
|
|
74
|
+
def tune(self, skip_len, update_count):
|
|
75
|
+
pass
|
cuqi/experimental/mcmc/_cwmh.py
CHANGED
|
@@ -67,16 +67,21 @@ class CWMHNew(ProposalBasedSamplerNew):
|
|
|
67
67
|
samples = sampler.sample(2000).get_samples()
|
|
68
68
|
|
|
69
69
|
"""
|
|
70
|
-
|
|
70
|
+
|
|
71
|
+
_STATE_KEYS = ProposalBasedSamplerNew._STATE_KEYS.union(['_scale_temp'])
|
|
72
|
+
|
|
73
|
+
def __init__(self, target:cuqi.density.Density=None, proposal=None, scale=1,
|
|
71
74
|
initial_point=None, **kwargs):
|
|
72
75
|
super().__init__(target, proposal=proposal, scale=scale,
|
|
73
76
|
initial_point=initial_point, **kwargs)
|
|
77
|
+
|
|
78
|
+
def _initialize(self):
|
|
79
|
+
if isinstance(self.scale, Number):
|
|
80
|
+
self.scale = np.ones(self.dim)*self.scale
|
|
81
|
+
self._acc = [np.ones((self.dim))] # Overwrite acc from ProposalBasedSamplerNew with list of arrays
|
|
74
82
|
|
|
75
|
-
#
|
|
76
|
-
self.
|
|
77
|
-
|
|
78
|
-
# set initial acceptance rate
|
|
79
|
-
self._acc = [np.ones((self.dim))]
|
|
83
|
+
# Handling of temporary scale parameter due to possible bug in old CWMH
|
|
84
|
+
self._scale_temp = self.scale.copy()
|
|
80
85
|
|
|
81
86
|
@property
|
|
82
87
|
def scale(self):
|
|
@@ -86,53 +91,35 @@ class CWMHNew(ProposalBasedSamplerNew):
|
|
|
86
91
|
@scale.setter
|
|
87
92
|
def scale(self, value):
|
|
88
93
|
""" Set the scale parameter. """
|
|
89
|
-
if isinstance(value, Number):
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
self._scale = value
|
|
93
|
-
self._scale_temp = self._scale.copy()
|
|
94
|
+
if self._is_initialized and isinstance(value, Number):
|
|
95
|
+
value = np.ones(self.dim)*value
|
|
96
|
+
self._scale = value
|
|
94
97
|
|
|
95
98
|
def validate_target(self):
|
|
96
99
|
if not isinstance(self.target, cuqi.density.Density):
|
|
97
100
|
raise ValueError(
|
|
98
101
|
"Target should be an instance of "+\
|
|
99
102
|
f"{cuqi.density.Density.__class__.__name__}")
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
if value is None:
|
|
103
|
+
|
|
104
|
+
def validate_proposal(self):
|
|
105
|
+
if not isinstance(self.proposal, cuqi.distribution.Distribution):
|
|
106
|
+
raise ValueError("Proposal must be a cuqi.distribution.Distribution object")
|
|
107
|
+
if not self.proposal.is_symmetric:
|
|
108
|
+
raise ValueError("Proposal must be symmetric")
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def proposal(self):
|
|
112
|
+
if self._proposal is None:
|
|
112
113
|
self._proposal = cuqi.distribution.Normal(
|
|
113
114
|
mean=lambda location: location,
|
|
114
115
|
std=lambda scale: scale,
|
|
115
116
|
geometry=self.dim,
|
|
116
117
|
)
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
elif isinstance(value, cuqi.distribution.Normal) and sorted(
|
|
124
|
-
value.get_conditioning_variables()
|
|
125
|
-
) == ["mean", "std"]:
|
|
126
|
-
self._proposal = value(
|
|
127
|
-
mean=lambda location: location, std=lambda scale: scale
|
|
128
|
-
)
|
|
129
|
-
|
|
130
|
-
elif not isinstance(value, cuqi.distribution.Distribution) and callable(
|
|
131
|
-
value):
|
|
132
|
-
self._proposal = value
|
|
133
|
-
|
|
134
|
-
else:
|
|
135
|
-
raise ValueError(fail_msg)
|
|
118
|
+
return self._proposal
|
|
119
|
+
|
|
120
|
+
@proposal.setter
|
|
121
|
+
def proposal(self, value):
|
|
122
|
+
self._proposal = value
|
|
136
123
|
|
|
137
124
|
def step(self):
|
|
138
125
|
# Initialize x_t which is used to store the current CWMH sample
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from cuqi.experimental.mcmc import SamplerNew
|
|
2
|
+
|
|
3
|
+
class DirectNew(SamplerNew):
|
|
4
|
+
""" Direct sampler
|
|
5
|
+
|
|
6
|
+
This sampler is used to sample from a target distribution directly. It simply calls the sample method of the target object to generate a sample.
|
|
7
|
+
|
|
8
|
+
Parameters
|
|
9
|
+
----------
|
|
10
|
+
target : Distribution
|
|
11
|
+
The target distribution to sample from.
|
|
12
|
+
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def _initialize(self):
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
def validate_target(self):
|
|
19
|
+
try:
|
|
20
|
+
self.target.sample()
|
|
21
|
+
except:
|
|
22
|
+
raise TypeError("Direct sampler requires a target with a sample method.")
|
|
23
|
+
|
|
24
|
+
def step(self):
|
|
25
|
+
self.current_point = self.target.sample()
|
|
26
|
+
|
|
27
|
+
def tune(self, skip_len, update_count):
|
|
28
|
+
pass
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
from cuqi.distribution import JointDistribution
|
|
2
|
+
from cuqi.experimental.mcmc import SamplerNew
|
|
3
|
+
from cuqi.samples import Samples
|
|
4
|
+
from typing import Dict
|
|
5
|
+
import numpy as np
|
|
6
|
+
import warnings
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
from progressbar import progressbar
|
|
10
|
+
except ImportError:
|
|
11
|
+
def progressbar(iterable, **kwargs):
|
|
12
|
+
warnings.warn("Module mcmc: Progressbar not found. Install progressbar2 to get sampling progress.")
|
|
13
|
+
return iterable
|
|
14
|
+
|
|
15
|
+
# Not subclassed from SamplerNew as Gibbs handles multiple samplers and samples multiple parameters
|
|
16
|
+
# Similar approach as for JointDistribution
|
|
17
|
+
class HybridGibbsNew:
|
|
18
|
+
"""
|
|
19
|
+
Hybrid Gibbs sampler for sampling a joint distribution.
|
|
20
|
+
|
|
21
|
+
Gibbs sampling samples the variables of the distribution sequentially,
|
|
22
|
+
one variable at a time. When a variable represents a random vector, the
|
|
23
|
+
whole vector is sampled simultaneously.
|
|
24
|
+
|
|
25
|
+
The sampling of each variable is done by sampling from the conditional
|
|
26
|
+
distribution of that variable given the values of the other variables.
|
|
27
|
+
This is often a very efficient way of sampling from a joint distribution
|
|
28
|
+
if the conditional distributions are easy to sample from.
|
|
29
|
+
|
|
30
|
+
Hybrid Gibbs sampler is a generalization of the Gibbs sampler where the
|
|
31
|
+
conditional distributions are sampled using different MCMC samplers.
|
|
32
|
+
|
|
33
|
+
When the conditionals are sampled exactly, the samples from the Gibbs
|
|
34
|
+
sampler converge to the joint distribution. See e.g.
|
|
35
|
+
Gelman et al. "Bayesian Data Analysis" (2014), Third Edition
|
|
36
|
+
for more details.
|
|
37
|
+
|
|
38
|
+
In each Gibbs step, the corresponding sampler has the initial_point
|
|
39
|
+
and initial_scale (if applicable) set to the value of the previous step
|
|
40
|
+
and the sampler is reinitialized. This means that the sampling is not
|
|
41
|
+
fully stateful at this point. This means samplers like NUTS will lose
|
|
42
|
+
their internal state between Gibbs steps.
|
|
43
|
+
|
|
44
|
+
Parameters
|
|
45
|
+
----------
|
|
46
|
+
target : cuqi.distribution.JointDistribution
|
|
47
|
+
Target distribution to sample from.
|
|
48
|
+
|
|
49
|
+
sampling_strategy : dict
|
|
50
|
+
Dictionary of sampling strategies for each variable.
|
|
51
|
+
Keys are variable names.
|
|
52
|
+
Values are sampler objects.
|
|
53
|
+
|
|
54
|
+
num_sampling_steps : dict, *optional*
|
|
55
|
+
Dictionary of number of sampling steps for each variable.
|
|
56
|
+
The sampling steps are defined as the number of times the sampler
|
|
57
|
+
will call its step method in each Gibbs step.
|
|
58
|
+
Default is 1 for all variables.
|
|
59
|
+
|
|
60
|
+
Example
|
|
61
|
+
-------
|
|
62
|
+
.. code-block:: python
|
|
63
|
+
|
|
64
|
+
import cuqi
|
|
65
|
+
import numpy as np
|
|
66
|
+
|
|
67
|
+
# Model and data
|
|
68
|
+
A, y_obs, probinfo = cuqi.testproblem.Deconvolution1D(phantom='square').get_components()
|
|
69
|
+
n = A.domain_dim
|
|
70
|
+
|
|
71
|
+
# Define distributions
|
|
72
|
+
d = cuqi.distribution.Gamma(1, 1e-4)
|
|
73
|
+
l = cuqi.distribution.Gamma(1, 1e-4)
|
|
74
|
+
x = cuqi.distribution.GMRF(np.zeros(n), lambda d: d)
|
|
75
|
+
y = cuqi.distribution.Gaussian(A, lambda l: 1/l)
|
|
76
|
+
|
|
77
|
+
# Combine into a joint distribution and create posterior
|
|
78
|
+
joint = cuqi.distribution.JointDistribution(d, l, x, y)
|
|
79
|
+
posterior = joint(y=y_obs)
|
|
80
|
+
|
|
81
|
+
# Define sampling strategy
|
|
82
|
+
sampling_strategy = {
|
|
83
|
+
'x': cuqi.experimental.mcmc.LinearRTONew(maxit=15),
|
|
84
|
+
'd': cuqi.experimental.mcmc.ConjugateNew(),
|
|
85
|
+
'l': cuqi.experimental.mcmc.ConjugateNew(),
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
# Define Gibbs sampler
|
|
89
|
+
sampler = cuqi.experimental.mcmc.HybridGibbsNew(posterior, sampling_strategy)
|
|
90
|
+
|
|
91
|
+
# Run sampler
|
|
92
|
+
samples = sampler.sample(Ns=1000, Nb=200)
|
|
93
|
+
|
|
94
|
+
# Plot results
|
|
95
|
+
samples['x'].plot_ci(exact=probinfo.exactSolution)
|
|
96
|
+
samples['d'].plot_trace(figsize=(8,2))
|
|
97
|
+
samples['l'].plot_trace(figsize=(8,2))
|
|
98
|
+
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
def __init__(self, target: JointDistribution, sampling_strategy: Dict[str, SamplerNew], num_sampling_steps: Dict[str, int] = None):
|
|
102
|
+
|
|
103
|
+
# Store target and allow conditioning to reduce to a single density
|
|
104
|
+
self.target = target() # Create a copy of target distribution (to avoid modifying the original)
|
|
105
|
+
|
|
106
|
+
# Store sampler instances (again as a copy to avoid modifying the original)
|
|
107
|
+
self.samplers = sampling_strategy.copy()
|
|
108
|
+
|
|
109
|
+
# Store number of sampling steps for each parameter
|
|
110
|
+
self.num_sampling_steps = num_sampling_steps
|
|
111
|
+
|
|
112
|
+
# Store parameter names
|
|
113
|
+
self.par_names = self.target.get_parameter_names()
|
|
114
|
+
|
|
115
|
+
# Initialize sampler (after target is set)
|
|
116
|
+
self._initialize()
|
|
117
|
+
|
|
118
|
+
def _initialize(self):
|
|
119
|
+
""" Initialize sampler """
|
|
120
|
+
|
|
121
|
+
# Initial points
|
|
122
|
+
self.current_samples = self._get_initial_points()
|
|
123
|
+
|
|
124
|
+
# Initialize sampling steps
|
|
125
|
+
self._initialize_num_sampling_steps()
|
|
126
|
+
|
|
127
|
+
# Allocate samples
|
|
128
|
+
self._allocate_samples()
|
|
129
|
+
|
|
130
|
+
# Set targets
|
|
131
|
+
self._set_targets()
|
|
132
|
+
|
|
133
|
+
# Initialize the samplers
|
|
134
|
+
self._initialize_samplers()
|
|
135
|
+
|
|
136
|
+
# Run over pre-sample methods for samplers that have it
|
|
137
|
+
# TODO. Some samplers (NUTS) seem to require to run _pre_warmup before _pre_sample
|
|
138
|
+
# This is not ideal and should be fixed in the future
|
|
139
|
+
for sampler in self.samplers.values():
|
|
140
|
+
self._pre_warmup_and_pre_sample_sampler(sampler)
|
|
141
|
+
|
|
142
|
+
# Validate all targets for samplers.
|
|
143
|
+
self.validate_targets()
|
|
144
|
+
|
|
145
|
+
# ------------ Public methods ------------
|
|
146
|
+
def validate_targets(self):
|
|
147
|
+
""" Validate each of the conditional targets used in the Gibbs steps """
|
|
148
|
+
if not isinstance(self.target, JointDistribution):
|
|
149
|
+
raise ValueError('Target distribution must be a JointDistribution.')
|
|
150
|
+
for sampler in self.samplers.values():
|
|
151
|
+
sampler.validate_target()
|
|
152
|
+
|
|
153
|
+
def sample(self, Ns) -> 'HybridGibbsNew':
|
|
154
|
+
""" Sample from the joint distribution using Gibbs sampling """
|
|
155
|
+
for _ in progressbar(range(Ns)):
|
|
156
|
+
self.step()
|
|
157
|
+
self._store_samples()
|
|
158
|
+
|
|
159
|
+
def warmup(self, Nb) -> 'HybridGibbsNew':
|
|
160
|
+
""" Warmup (tune) the Gibbs sampler """
|
|
161
|
+
for idx in progressbar(range(Nb)):
|
|
162
|
+
self.step()
|
|
163
|
+
self.tune(idx)
|
|
164
|
+
self._store_samples()
|
|
165
|
+
|
|
166
|
+
def get_samples(self) -> Dict[str, Samples]:
|
|
167
|
+
samples_object = {}
|
|
168
|
+
for par_name in self.par_names:
|
|
169
|
+
samples_array = np.array(self.samples[par_name]).T
|
|
170
|
+
samples_object[par_name] = Samples(samples_array, self.target.get_density(par_name).geometry)
|
|
171
|
+
return samples_object
|
|
172
|
+
|
|
173
|
+
def step(self):
|
|
174
|
+
""" Sequentially go through all parameters and sample them conditionally on each other """
|
|
175
|
+
|
|
176
|
+
# Sample from each conditional distribution
|
|
177
|
+
for par_name in self.par_names:
|
|
178
|
+
|
|
179
|
+
# Set target for current parameter
|
|
180
|
+
self._set_target(par_name)
|
|
181
|
+
|
|
182
|
+
# Get sampler
|
|
183
|
+
sampler = self.samplers[par_name]
|
|
184
|
+
|
|
185
|
+
# Set initial parameters using current point and scale (subset of state)
|
|
186
|
+
# This does not store the full state from e.g. NUTS sampler
|
|
187
|
+
# But works on samplers like MH, PCN, ULA, MALA, LinearRTO, UGLA, CWMH
|
|
188
|
+
# that only use initial_point and initial_scale
|
|
189
|
+
sampler.initial_point = self.current_samples[par_name]
|
|
190
|
+
if hasattr(sampler, 'initial_scale'): sampler.initial_scale = sampler.scale
|
|
191
|
+
|
|
192
|
+
# Reinitialize sampler
|
|
193
|
+
# This makes the sampler lose all of its state.
|
|
194
|
+
# This is only OK because we set the initial values above from the previous state
|
|
195
|
+
sampler.reinitialize()
|
|
196
|
+
|
|
197
|
+
# Run pre_warmup and pre_sample methods for sampler
|
|
198
|
+
# TODO. Some samplers (NUTS) seem to require to run _pre_warmup before _pre_sample
|
|
199
|
+
self._pre_warmup_and_pre_sample_sampler(sampler)
|
|
200
|
+
|
|
201
|
+
# Take MCMC steps
|
|
202
|
+
for _ in range(self.num_sampling_steps[par_name]):
|
|
203
|
+
sampler.step()
|
|
204
|
+
|
|
205
|
+
# Extract samples (Ensure even 1-dimensional samples are 1D arrays)
|
|
206
|
+
self.current_samples[par_name] = sampler.current_point.reshape(-1)
|
|
207
|
+
|
|
208
|
+
def tune(self, idx):
|
|
209
|
+
""" Tune each of the samplers """
|
|
210
|
+
for par_name in self.par_names:
|
|
211
|
+
self.samplers[par_name].tune(skip_len=1, update_count=idx)
|
|
212
|
+
|
|
213
|
+
# ------------ Private methods ------------
|
|
214
|
+
def _initialize_samplers(self):
|
|
215
|
+
""" Initialize samplers """
|
|
216
|
+
for sampler in self.samplers.values():
|
|
217
|
+
sampler.initialize()
|
|
218
|
+
|
|
219
|
+
def _initialize_num_sampling_steps(self):
|
|
220
|
+
""" Initialize the number of sampling steps for each sampler. Defaults to 1 if not set by user """
|
|
221
|
+
|
|
222
|
+
if self.num_sampling_steps is None:
|
|
223
|
+
self.num_sampling_steps = {par_name: 1 for par_name in self.par_names}
|
|
224
|
+
|
|
225
|
+
for par_name in self.par_names:
|
|
226
|
+
if par_name not in self.num_sampling_steps:
|
|
227
|
+
self.num_sampling_steps[par_name] = 1
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _pre_warmup_and_pre_sample_sampler(self, sampler):
|
|
231
|
+
if hasattr(sampler, '_pre_warmup'): sampler._pre_warmup()
|
|
232
|
+
if hasattr(sampler, '_pre_sample'): sampler._pre_sample()
|
|
233
|
+
|
|
234
|
+
def _set_targets(self):
|
|
235
|
+
""" Set targets for all samplers using the current samples """
|
|
236
|
+
par_names = self.par_names
|
|
237
|
+
for par_name in par_names:
|
|
238
|
+
self._set_target(par_name)
|
|
239
|
+
|
|
240
|
+
def _set_target(self, par_name):
|
|
241
|
+
""" Set target conditional distribution for a single parameter using the current samples """
|
|
242
|
+
# Get all other conditional parameters other than the current parameter and update the target
|
|
243
|
+
# This defines - from a joint p(x,y,z) - the conditional distribution p(x|y,z) or p(y|x,z) or p(z|x,y)
|
|
244
|
+
conditional_params = {par_name_: self.current_samples[par_name_] for par_name_ in self.par_names if par_name_ != par_name}
|
|
245
|
+
self.samplers[par_name].target = self.target(**conditional_params)
|
|
246
|
+
|
|
247
|
+
def _allocate_samples(self):
|
|
248
|
+
""" Allocate memory for samples """
|
|
249
|
+
samples = {}
|
|
250
|
+
for par_name in self.par_names:
|
|
251
|
+
samples[par_name] = []
|
|
252
|
+
self.samples = samples
|
|
253
|
+
|
|
254
|
+
def _get_initial_points(self):
|
|
255
|
+
""" Get initial points for each parameter """
|
|
256
|
+
initial_points = {}
|
|
257
|
+
for par_name in self.par_names:
|
|
258
|
+
if hasattr(self.target.get_density(par_name), 'init_point'):
|
|
259
|
+
initial_points[par_name] = self.target.get_density(par_name).init_point
|
|
260
|
+
else:
|
|
261
|
+
initial_points[par_name] = np.ones(self.target.get_density(par_name).dim)
|
|
262
|
+
return initial_points
|
|
263
|
+
|
|
264
|
+
def _store_samples(self):
|
|
265
|
+
""" Store current samples at index i of samples dict """
|
|
266
|
+
for par_name in self.par_names:
|
|
267
|
+
self.samples[par_name].append(self.current_samples[par_name])
|