Debian Codegraph @

weblogo/logomath.py

raw
1 # -------------------------------- WebLogo --------------------------------
2
3 # Copyright (c) 2003-2004 The Regents of the University of California.
4 # Copyright (c) 2005 Gavin E. Crooks
5 # Copyright (c) 2006-2011, The Regents of the University of California, through
6 # Lawrence Berkeley National Laboratory (subject to receipt of any required
7 # approvals from the U.S. Dept. of Energy). All rights reserved.
8
9 # This software is distributed under the new BSD Open Source License.
10 # <http://www.opensource.org/licenses/bsd-license.html>
11 #
12 # Redistribution and use in source and binary forms, with or without
13 # modification, are permitted provided that the following conditions are met:
14 #
15 # (1) Redistributions of source code must retain the above copyright notice,
16 # this list of conditions and the following disclaimer.
17 #
18 # (2) Redistributions in binary form must reproduce the above copyright
19 # notice, this list of conditions and the following disclaimer in the
20 # documentation and or other materials provided with the distribution.
21 #
22 # (3) Neither the name of the University of California, Lawrence Berkeley
23 # National Laboratory, U.S. Dept. of Energy nor the names of its contributors
24 # may be used to endorse or promote products derived from this software
25 # without specific prior written permission.
26 #
27 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
28 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
31 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37 # POSSIBILITY OF SUCH DAMAGE.
38
39 import random
40 from math import exp, log, sqrt
41 from typing import Tuple
42
43 import numpy as np
44 import scipy.optimize
45 from numpy import asarray, float64, shape, zeros
46 from numpy.typing import ArrayLike # pragma: no cover
47 from scipy.special import digamma, gamma, gammaincc, polygamma
48
49
50 class Dirichlet(object):
51 """The Dirichlet probability distribution. The Dirichlet is a continuous
52 multivariate probability distribution across non-negative unit length
53 vectors. In other words, the Dirichlet is a probability distribution of
54 probability distributions. It is conjugate to the multinomial
55 distribution and is widely used in Bayesian statistics.
56
57 The Dirichlet probability distribution of order K-1 is
58
59 p(theta_1,...,theta_K) d theta_1 ... d theta_K =
60 (1/Z) prod_i=1,K theta_i^{alpha_i - 1} delta(1 -sum_i=1,K theta_i)
61
62 The normalization factor Z can be expressed in terms of gamma functions:
63
64 Z = {prod_i=1,K Gamma(alpha_i)} / {Gamma( sum_i=1,K alpha_i)}
65
66 The K constants, alpha_1,...,alpha_K, must be positive. The K parameters,
67 theta_1,...,theta_K are nonnegative and sum to 1.
68
69 Status:
70 Alpha
71 """
72
73 __slots__ = (
74 "alpha",
75 "_total",
76 "_mean",
77 )
78
79 def __init__(self, alpha: "ArrayLike") -> None:
80 """
81 Args:
82 - alpha -- The parameters of the Dirichlet prior distribution.
83 A vector of non-negative real numbers.
84 """
85 # TODO: Check that alphas are positive
86 # TODO: what if alpha's not one dimensional?
87 self.alpha = asarray(alpha, float64)
88
89 self._total = sum(self.alpha)
90 self._mean: np.ndarray = self.alpha / self._total
91
92 def sample(self) -> np.ndarray:
93 """Return a randomly generated probability vector.
94
95 Random samples are generated by sampling K values from gamma
96 distributions with parameters a=\alpha_i, b=1, and renormalizing.
97
98 Ref:
99 A.M. Law, W.D. Kelton, Simulation Modeling and Analysis (1991).
100 Authors:
101 Gavin E. Crooks <[email protected]> (2002)
102 """
103 alpha = self.alpha
104 K = len(alpha)
105 theta = zeros((K,), float64)
106
107 for k in range(K):
108 theta[k] = random.gammavariate(alpha[k], 1.0)
109 theta /= sum(theta)
110
111 return theta
112
113 def mean(self) -> np.ndarray:
114 return self._mean
115
116 def covariance(self) -> np.ndarray:
117 alpha = self.alpha
118 A = sum(alpha)
119 # A2 = A * A
120 K = len(alpha)
121 cv = zeros((K, K), float64)
122
123 for i in range(K):
124 cv[i, i] = alpha[i] * (1.0 - alpha[i] / A) / (A * (A + 1.0))
125
126 for i in range(K):
127 for j in range(i + 1, K):
128 v = -alpha[i] * alpha[j] / (A * A * (A + 1.0))
129 cv[i, j] = v
130 cv[j, i] = v
131 return cv
132
133 def mean_x(self, x: "ArrayLike") -> float:
134 x = asarray(x, float64)
135 if shape(x) != shape(self.alpha):
136 raise ValueError("Argument must be same dimension as Dirichlet")
137 return sum(x * self.mean())
138
139 def variance_x(self, x: "ArrayLike") -> float:
140 x = asarray(x, float64)
141 if shape(x) != shape(self.alpha):
142 raise ValueError("Argument must be same dimension as Dirichlet")
143
144 cv = self.covariance()
145 var = np.dot(np.dot(np.transpose(x), cv), x)
146 return var
147
148 def mean_entropy(self) -> float:
149 """Calculate the average entropy of probabilities sampled
150 from this Dirichlet distribution.
151
152 Returns:
153 The average entropy.
154
155 Ref:
156 Wolpert & Wolf, PRE 53:6841-6854 (1996) Theorem 7
157 (Warning: this paper contains typos.)
158 Status:
159 Alpha
160 Authors:
161 GEC 2005
162
163 """
164 # TODO: Optimize
165 alpha = self.alpha
166 A = float(sum(alpha))
167 ent = 0.0
168 for a in alpha:
169 if a > 0:
170 ent += -1.0 * a * digamma(1.0 + a) # FIXME: Check
171 ent /= A
172 ent += digamma(A + 1.0)
173 return ent
174
175 def variance_entropy(self) -> float:
176 """Calculate the variance of the Dirichlet entropy.
177
178 Ref:
179 Wolpert & Wolf, PRE 53:6841-6854 (1996) Theorem 8
180 (Warning: this paper contains typos.)
181 """
182 alpha = self.alpha
183 A = float(sum(alpha))
184 A2 = A * (A + 1)
185 L = len(alpha)
186
187 dg1 = zeros((L), float64)
188 dg2 = zeros((L), float64)
189 tg2 = zeros((L), float64)
190
191 for i in range(L):
192 dg1[i] = digamma(alpha[i] + 1.0)
193 dg2[i] = digamma(alpha[i] + 2.0)
194 tg2[i] = polygamma(1, alpha[i] + 2.0)
195
196 dg_Ap2 = digamma(A + 2.0)
197 tg_Ap2 = polygamma(1, A + 2.0)
198
199 mean = self.mean_entropy()
200 var = 0.0
201
202 for i in range(L):
203 for j in range(L):
204 if i != j:
205 var += (
206 ((dg1[i] - dg_Ap2) * (dg1[j] - dg_Ap2) - tg_Ap2)
207 * (alpha[i] * alpha[j])
208 / A2
209 )
210 else:
211 var += (
212 ((dg2[i] - dg_Ap2) ** 2 + (tg2[i] - tg_Ap2))
213 * (alpha[i] * (alpha[i] + 1.0))
214 / A2
215 )
216
217 var -= mean**2
218 return var
219
220 def mean_relative_entropy(self, pvec: "ArrayLike") -> float:
221 pvec = asarray(pvec)
222 ln_p = np.log(pvec)
223 return -self.mean_x(ln_p) - self.mean_entropy()
224
225 def variance_relative_entropy(self, pvec: "ArrayLike") -> float:
226 pvec = asarray(pvec)
227 ln_p = np.log(pvec)
228 return self.variance_x(ln_p) + self.variance_entropy()
229
230 def interval_relative_entropy(
231 self, pvec: "ArrayLike", frac: float
232 ) -> Tuple[float, float]:
233 pvec = asarray(pvec)
234 mean = self.mean_relative_entropy(pvec)
235 variance = self.variance_relative_entropy(pvec)
236 sd = sqrt(variance)
237
238 # If the variance is small, use the standard 95%
239 # confidence interval: mean +/- 1.96 * sd
240 if mean / sd > 3.0:
241 return max(0.0, mean - sd * 1.96), mean + sd * 1.96
242
243 g = Gamma.from_mean_variance(mean, variance)
244 low_limit = g.inverse_cdf((1.0 - frac) / 2.0)
245 high_limit = g.inverse_cdf(1.0 - (1.0 - frac) / 2.0)
246
247 return low_limit, high_limit
248
249
250 class Gamma(object):
251 """The gamma probability distribution. (Not to be confused with the
252 gamma function.)
253
254
255 """
256
257 __slots__ = "alpha", "beta"
258
259 def __init__(self, alpha: float, beta: float) -> None:
260 if alpha <= 0.0:
261 raise ValueError("alpha must be positive")
262 if beta <= 0.0:
263 raise ValueError("beta must be positive")
264 self.alpha = alpha
265 self.beta = beta
266
267 @classmethod
268 def from_shape_scale(cls, shape: float, scale: float) -> "Gamma":
269 return cls(shape, 1.0 / scale)
270
271 @classmethod
272 def from_mean_variance(cls, mean: float, variance: float) -> "Gamma":
273 alpha = mean**2 / variance
274 beta = alpha / mean
275 return cls(alpha, beta)
276
277 def mean(self) -> float:
278 return self.alpha / self.beta
279
280 def variance(self) -> float:
281 return self.alpha / (self.beta**2)
282
283 def sample(self) -> float:
284 return random.gammavariate(self.alpha, 1.0 / self.beta)
285
286 def pdf(self, x: float) -> float:
287 if x == 0.0:
288 return 0.0
289 a = self.alpha
290 b = self.beta
291 return (x ** (a - 1.0)) * exp(-b * x) * (b**a) / gamma(a)
292
293 def cdf(self, x: float) -> float:
294 return 1.0 - gammaincc(self.alpha, self.beta * x)
295
296 def inverse_cdf(self, p: float) -> float:
297 def rootof(x: float) -> float:
298 return self.cdf(exp(x)) - p
299
300 root = scipy.optimize.newton(rootof, log(self.mean()))
301 return exp(root)