-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstats_tools.py
413 lines (341 loc) · 14.1 KB
/
stats_tools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
'''
Statistics tools for tracking.
MIT License
Copyright (c) 2018 Standard Cognition
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
# Standard
from sys import float_info # for float_info.epsilon
from typing import Union, Tuple, List
# Scientific
import numpy as np
from scipy.stats import chi2
from matplotlib import pyplot as plt
from matplotlib import patches
# ----- Misc. -----
def det(A: np.ndarray) -> float:
'''
Evaluate determinant of a matrix A. Use direct formula for speedup in 2x2
special case. For speed, input validity is not checked.
'''
if A.shape[0] == 2:
determinant = A[0, 0]*A[1, 1] - A[0, 1]*A[1, 0]
else:
determinant = np.linalg.det(A)
return determinant
# ----- Multivariate Normal Distributions -----
def assert_cov_validity(
cov: Union[float, np.ndarray],
eigenvalue_lbnd: float = 1000.0*float_info.epsilon,
condition_number_ubnd: float = 1.0e6):
'''
Assert that covariance `cov` is
symmetric,
real,
positive-definite,
has eigenvalues not too close to zero, and
is well-conditioned.
::WARNING:: Applying `enforce_cov_validity` with the same parameters
does not guarantee that these assertions will pass. Consider either (1)
using the functions mutally exclusively, or (2) making the parameters of
`enforce_cov_validity` slightly stricter in order to compensate for
possible small numerical errors in eigenreconstruction.
Args:
cov: an alleged variance (as `float`) or covariance matrix (as
`np.ndarray`).
eigenvalue_lbnd: eigenvalues should be at least this much greater than
zero. Must be strictly positive.
condition_number_ubnd: inclusive upper bound on matrix condition
number. Must be greater or equal to 1.0.
Returns:
Whether cov is positive definite and has all real elements.
'''
assert eigenvalue_lbnd > 0.0, \
'Covariance eigenvalue lower bound must be > 0.0!'
assert condition_number_ubnd >= 1.0, \
'Covariance condition number bound must be >= 1.0!'
# Symmetry
if not np.isscalar(cov):
assert (cov.T == cov).all(), 'Covariance must be symmetric!'
# Realness
assert np.isrealobj(cov), 'Covariance must be a real object!'
# Eigenvalue properties
if np.isscalar(cov):
assert cov > 0.0, \
'Variance must be strictly positive!'
assert cov >= eigenvalue_lbnd, \
'Variance must be >= lower bound!'
else:
# Precompute eigenvalues for subsequent tests.
ws = np.linalg.eigvalsh(cov) # The eigenvalues of cov
w_min = min(ws)
w_max = max(ws)
# Strict positivity
assert w_min > 0.0, 'Covariance must be strictly positive!'
# Eigenvalue lower bound
assert w_min >= eigenvalue_lbnd, \
'Covariance eigenvalues must be >= lower bound!'
# Condition number upper bound
assert w_max/w_min <= condition_number_ubnd, \
'Condition number must be <= upper bound!'
def enforce_cov_validity(
cov: Union[float, np.ndarray],
eigenvalue_lbnd: float = 1000.0*float_info.epsilon,
condition_number_ubnd: float = 1.0e6) -> Union[float, np.ndarray]:
'''
Create and return a version of covariance `cov` which is modified to
ensure it is
symmetric,
real,
positive-definite,
has eigenvalues not too close to zero, and
is well-conditioned.
::WARNING:: Applying this function to a numpy array does not guarantee that
calling `assert_cov_validity` with the same parameters will pass.
Consider either (1) using the functions mutally exclusively, or (2) making
the parameters of `assert_cov_validity` slightly more lenient in
order to compensate for possible small numerical errors in
eigenreconstruction.
Args:
cov: an alleged variance (as `float`) or covariance matrix (as
`np.ndarray`).
eigenvalue_lbnd: eigenvalues should be at least this much greater than
zero.
condition_number_ubnd: upper bound on matrix condition number. Should
be greater or equal to 1.0. If it is necessary to modify `cov` to
enforce this, the largest eigenvalue is held fixed and the smaller
are increased.
Returns:
A version of cov modified to be valid.
'''
assert eigenvalue_lbnd > 0.0, \
'Covariance eigenvalue lower bound must be > 0.0!'
assert condition_number_ubnd >= 1.0, \
'Covariance condition number bound must be >= 1.0!'
if np.isscalar(cov):
# Realness
cov = float(cov.real)
# Eigenvalue lower bound
if cov < eigenvalue_lbnd:
cov = eigenvalue_lbnd
else:
# Symmetry
cov = 0.5*(cov + cov.T)
# Realness
if not np.isrealobj(cov):
cov = cov.real
# Precompute eigendecomposition for subsequent enforcements.
ws, vr = np.linalg.eigh(cov) # Eigenvalues and right eigenvectors
# Eigenvalue lower bound
for i, w in enumerate(ws):
if w < eigenvalue_lbnd:
ws[i] = eigenvalue_lbnd
# Condition number upper bound
# condition number := max_eigval/min_eigval <= condition_number_ubnd
# <=> max_eigval/condition_number_ubnd <= min_eigval
eigenvalue_lbnd_for_conditioning = max(ws)/condition_number_ubnd
for i, w in enumerate(ws):
if w < eigenvalue_lbnd_for_conditioning:
ws[i] = eigenvalue_lbnd_for_conditioning
# Eigenreconstruction
cov = vr.dot(np.diag(ws).dot(vr.T))
return cov
def evaluate_normal_pdf(
x: Union[float, np.ndarray],
cov: Union[float, np.ndarray],
mean: Union[float, np.ndarray] = None) -> float:
'''
Compute and return the value of a multivariate normal PDF (Probability
Density Function) at a point x.
Args:
x: where to evaluate PDF.
cov: covariance of distribution.
mean: mean of distribution. None => assumed zeros.
Returns:
PDF value at x.
'''
# Get dimension of distribution
if np.isscalar(x):
dimension = 1
else:
dimension = len(x)
if mean is None:
delta = x # assume zero mean
else:
delta = x - mean
if dimension > 1:
k = (2.0*np.pi)**(-0.5*dimension)*det(cov)**(-0.5)
quadratic = delta.dot(np.linalg.solve(cov, delta))
p = k*np.exp(-0.5*quadratic)
else:
k = (2.0*np.pi*cov)**(-0.5)
quadratic = delta*(1.0/cov)*delta
p = k*np.exp(-0.5*quadratic)
return float(p)
def sample_from_normal_distribution(
cov: Union[float, np.ndarray],
cov_cholesky: np.ndarray = None,
mean: Union[float, np.ndarray] = None,
num_samples: int = 1) -> np.ndarray:
'''
Generate random sample(s) from a normal distribution having mean `mean`
and covariance `cov`.
This function is used instead of `np.random.multivariate_normal` because
the latter issues incorrect warnings (as of 2018:05:24) and is less
flexible in input. It may also be less efficient if you already have a
Cholesky factorization.
Args:
cov: covariance of the distribution.
cov_cholesky: optionally precomputed cholesky factorization, as output
from `np.linalg.cholesky(cov)`. If `cov_cholesky` is None, then the
covariance is allowed to be rank deficient.
mean: mean of the distribution. None => assume zeros.
num_samples: number of desired samples.
Returns:
Array of samples. Each column is a sample and the rows run over
components of the vectors.
'''
if np.isscalar(cov):
sigma = np.sqrt(cov)
samples = sigma*np.random.normal(size=(1, num_samples)) + mean
else:
d = cov.shape[0]
if mean is None:
mean = np.zeros(d)
try:
if cov_cholesky is None:
cov_cholesky = np.linalg.cholesky(cov)
samples = np.dot(
cov_cholesky, np.random.normal(size=(d, num_samples)))
for i in range(d):
samples[i, :] += mean[i]
except np.linalg.linalg.LinAlgError:
# Fall back on `np.random.multivariate_normal` only for rank-
# deficient covariances.
samples = np.random.multivariate_normal(
mean=mean, cov=cov, size=num_samples)
samples = samples.T
return samples
# ----- Error Ellipse Visualization -----
def generate_error_ellipse_points(
mean: np.ndarray,
cov: np.ndarray,
cov_cholesky: np.ndarray = None,
acceptance: float = 0.99,
num_points: int = 30,
format: str = 'matplotlib') -> np.ndarray:
'''
Generate points on a level set of a bivariate Gaussian PDF, usu. for
plotting error ellipses.
Args:
mean: the distribution's mean.
cov: 2x2 array, the distribution's covariance.
cov_cholesky: optionally precomputed cholesky factorization, as output
from `np.linalg.cholesky(cov)`.
acceptance: probability mass that ellipse should contain around mean.
num_points: number of points to sample on ellipse. This is a measure of
plotting resolution.
format: use 'matplotlib' for points output as a `float64` numpy array
with rows running over x and y physical dimensions, columns over
points. Use 'opencv' for points output as a `uint32` numpy array with
rows running over points and columns running over x and y pixel
dimensions.
Returns:
Shape (2, num_points) array of points for plotting.
'''
assert mean.shape == (2,), 'Incorrect mean shape!'
assert cov.shape == (2, 2), 'Incorrect cov shape!'
assert acceptance >= 0.0 and acceptance < 1.0, \
'acceptance rate must be in [0.0, 1.0)!'
# Sample points on unit circle.
dtheta = 2.0*np.pi/num_points
thetas = np.linspace(0, 2.0*np.pi - dtheta, num_points)
if cov_cholesky is None:
cov_cholesky = np.linalg.cholesky(cov)
acceptance_factor = np.sqrt(chi2.ppf(acceptance, df=2))
cov_cholesky = acceptance_factor*cov_cholesky
points = np.zeros((2, num_points))
points[0, :] = np.cos(thetas)
points[1, :] = np.sin(thetas)
# Warp circle points into ellipse.
for i in range(num_points):
points[:, i] = cov_cholesky.dot(points[:, i]) + mean
if format == 'matplotlib':
return points
elif format == 'opencv':
return points.T.astype(np.int32)
else:
assert False, 'Format not recognized!'
def plot_polygon(
boundary_points: np.ndarray,
edgecolor: str = 'k', facecolor: str = 'm', alpha: float = 0.5,
linewidth: float = 3.0, linestyle: str = 'solid', zorder: int = 0):
'''
Wrapper for `plt.fill` that has reasonable default arguments for
plotting acceptance regions, esp. error ellipses.
Args:
boundary_points: shape 2 x many, no repeat at wraparound. First row is
x values, second is y values.
edgecolor: edge color.
facecolor: face color, 'none' => transparent interior.
alpha: close to 0.0 => transparent, close to 1.0 => opaque.
linewidth: usu. 3.0 or greater for good visibility.
linestyle: e.g. '-', '--', or ':'.
zorder: higher => closer to foreground.
'''
plt.fill(
boundary_points[0, :], boundary_points[1, :],
edgecolor=edgecolor, facecolor=facecolor, alpha=alpha,
linewidth=linewidth, linestyle=linestyle, zorder=zorder)
def plot_error_ellipse(
mean: np.ndarray,
cov: np.ndarray,
cov_cholesky: np.ndarray = None,
acceptance: float = 0.99,
num_points: int = 30,
edgecolor: str = 'k', facecolor: str = 'm', alpha: float = 0.5,
linewidth: float = 3.0, linestyle: str = 'solid', zorder: int = 0) \
-> List[patches.Polygon]:
'''
Plot 2D error ellipse from mean and covariance.
Args:
mean: distribution's mean (length 2).
cov: distribution's covariance (2x2).
cov_cholesky: optionally precomputed cholesky factorization, as output
from `np.linalg.cholesky(cov)`.
acceptance: amount of probability mass ellipse should contain.
num_points: number of points to sample on ellipse. This is a measure of
plotting resolution.
edgecolor: edge color.
facecolor: face color, 'none' => transparent interior.
alpha: close to 0.0 => transparent, close to 1.0 => opaque.
linewidth: usu. 3.0 or greater for good visibility.
linestyle: e.g. '-', '--', or ':'.
zorder: higher => closer to foreground.
Returns:
list of polygons.
'''
if cov_cholesky is None:
cov_cholesky = np.linalg.cholesky(cov)
boundary_points = generate_error_ellipse_points(
mean=mean, cov=cov, cov_cholesky=cov_cholesky,
acceptance=acceptance, num_points=num_points)
polygons = plt.fill(
boundary_points[0, :], boundary_points[1, :],
edgecolor=edgecolor, facecolor=facecolor, alpha=alpha,
linewidth=linewidth, linestyle=linestyle, zorder=zorder)[0]
return polygons