forked from scipy/scipy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_multivariate.py
3787 lines (3196 loc) · 147 KB
/
test_multivariate.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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Test functions for multivariate normal distributions.
"""
import pickle
from numpy.testing import (assert_allclose, assert_almost_equal,
assert_array_almost_equal, assert_equal,
assert_array_less, assert_)
import pytest
from pytest import raises as assert_raises
from .test_continuous_basic import check_distribution_rvs
import numpy
import numpy as np
import scipy.linalg
from scipy.stats._multivariate import (_PSD,
_lnB,
_cho_inv_batch,
multivariate_normal_frozen)
from scipy.stats import (multivariate_normal, multivariate_hypergeom,
matrix_normal, special_ortho_group, ortho_group,
random_correlation, unitary_group, dirichlet,
beta, wishart, multinomial, invwishart, chi2,
invgamma, norm, uniform, ks_2samp, kstest, binom,
hypergeom, multivariate_t, cauchy, normaltest,
random_table, uniform_direction, vonmises_fisher,
dirichlet_multinomial, vonmises)
from scipy.stats import _covariance, Covariance
from scipy import stats
from scipy.integrate import romb, qmc_quad, tplquad
from scipy.special import multigammaln
from scipy._lib._pep440 import Version
from .common_tests import check_random_state_property
from .data._mvt import _qsimvtv
from unittest.mock import patch
def assert_close(res, ref, *args, **kwargs):
res, ref = np.asarray(res), np.asarray(ref)
assert_allclose(res, ref, *args, **kwargs)
assert_equal(res.shape, ref.shape)
class TestCovariance:
def test_input_validation(self):
message = "The input `precision` must be a square, two-dimensional..."
with pytest.raises(ValueError, match=message):
_covariance.CovViaPrecision(np.ones(2))
message = "`precision.shape` must equal `covariance.shape`."
with pytest.raises(ValueError, match=message):
_covariance.CovViaPrecision(np.eye(3), covariance=np.eye(2))
message = "The input `diagonal` must be a one-dimensional array..."
with pytest.raises(ValueError, match=message):
_covariance.CovViaDiagonal("alpaca")
message = "The input `cholesky` must be a square, two-dimensional..."
with pytest.raises(ValueError, match=message):
_covariance.CovViaCholesky(np.ones(2))
message = "The input `eigenvalues` must be a one-dimensional..."
with pytest.raises(ValueError, match=message):
_covariance.CovViaEigendecomposition(("alpaca", np.eye(2)))
message = "The input `eigenvectors` must be a square..."
with pytest.raises(ValueError, match=message):
_covariance.CovViaEigendecomposition((np.ones(2), "alpaca"))
message = "The shapes of `eigenvalues` and `eigenvectors` must be..."
with pytest.raises(ValueError, match=message):
_covariance.CovViaEigendecomposition(([1, 2, 3], np.eye(2)))
_covariance_preprocessing = {"Diagonal": np.diag,
"Precision": np.linalg.inv,
"Cholesky": np.linalg.cholesky,
"Eigendecomposition": np.linalg.eigh,
"PSD": lambda x:
_PSD(x, allow_singular=True)}
_all_covariance_types = np.array(list(_covariance_preprocessing))
_matrices = {"diagonal full rank": np.diag([1, 2, 3]),
"general full rank": [[5, 1, 3], [1, 6, 4], [3, 4, 7]],
"diagonal singular": np.diag([1, 0, 3]),
"general singular": [[5, -1, 0], [-1, 5, 0], [0, 0, 0]]}
_cov_types = {"diagonal full rank": _all_covariance_types,
"general full rank": _all_covariance_types[1:],
"diagonal singular": _all_covariance_types[[0, -2, -1]],
"general singular": _all_covariance_types[-2:]}
@pytest.mark.parametrize("cov_type_name", _all_covariance_types[:-1])
def test_factories(self, cov_type_name):
A = np.diag([1, 2, 3])
x = [-4, 2, 5]
cov_type = getattr(_covariance, f"CovVia{cov_type_name}")
preprocessing = self._covariance_preprocessing[cov_type_name]
factory = getattr(Covariance, f"from_{cov_type_name.lower()}")
res = factory(preprocessing(A))
ref = cov_type(preprocessing(A))
assert type(res) == type(ref)
assert_allclose(res.whiten(x), ref.whiten(x))
@pytest.mark.parametrize("matrix_type", list(_matrices))
@pytest.mark.parametrize("cov_type_name", _all_covariance_types)
def test_covariance(self, matrix_type, cov_type_name):
message = (f"CovVia{cov_type_name} does not support {matrix_type} "
"matrices")
if cov_type_name not in self._cov_types[matrix_type]:
pytest.skip(message)
A = self._matrices[matrix_type]
cov_type = getattr(_covariance, f"CovVia{cov_type_name}")
preprocessing = self._covariance_preprocessing[cov_type_name]
psd = _PSD(A, allow_singular=True)
# test properties
cov_object = cov_type(preprocessing(A))
assert_close(cov_object.log_pdet, psd.log_pdet)
assert_equal(cov_object.rank, psd.rank)
assert_equal(cov_object.shape, np.asarray(A).shape)
assert_close(cov_object.covariance, np.asarray(A))
# test whitening/coloring 1D x
rng = np.random.default_rng(5292808890472453840)
x = rng.random(size=3)
res = cov_object.whiten(x)
ref = x @ psd.U
# res != ref in general; but res @ res == ref @ ref
assert_close(res @ res, ref @ ref)
if hasattr(cov_object, "_colorize") and "singular" not in matrix_type:
# CovViaPSD does not have _colorize
assert_close(cov_object.colorize(res), x)
# test whitening/coloring 3D x
x = rng.random(size=(2, 4, 3))
res = cov_object.whiten(x)
ref = x @ psd.U
assert_close((res**2).sum(axis=-1), (ref**2).sum(axis=-1))
if hasattr(cov_object, "_colorize") and "singular" not in matrix_type:
assert_close(cov_object.colorize(res), x)
@pytest.mark.parametrize("size", [None, tuple(), 1, (2, 4, 3)])
@pytest.mark.parametrize("matrix_type", list(_matrices))
@pytest.mark.parametrize("cov_type_name", _all_covariance_types)
def test_mvn_with_covariance(self, size, matrix_type, cov_type_name):
message = (f"CovVia{cov_type_name} does not support {matrix_type} "
"matrices")
if cov_type_name not in self._cov_types[matrix_type]:
pytest.skip(message)
A = self._matrices[matrix_type]
cov_type = getattr(_covariance, f"CovVia{cov_type_name}")
preprocessing = self._covariance_preprocessing[cov_type_name]
mean = [0.1, 0.2, 0.3]
cov_object = cov_type(preprocessing(A))
mvn = multivariate_normal
dist0 = multivariate_normal(mean, A, allow_singular=True)
dist1 = multivariate_normal(mean, cov_object, allow_singular=True)
rng = np.random.default_rng(5292808890472453840)
x = rng.multivariate_normal(mean, A, size=size)
rng = np.random.default_rng(5292808890472453840)
x1 = mvn.rvs(mean, cov_object, size=size, random_state=rng)
rng = np.random.default_rng(5292808890472453840)
x2 = mvn(mean, cov_object, seed=rng).rvs(size=size)
if isinstance(cov_object, _covariance.CovViaPSD):
assert_close(x1, np.squeeze(x)) # for backward compatibility
assert_close(x2, np.squeeze(x))
else:
assert_equal(x1.shape, x.shape)
assert_equal(x2.shape, x.shape)
assert_close(x2, x1)
assert_close(mvn.pdf(x, mean, cov_object), dist0.pdf(x))
assert_close(dist1.pdf(x), dist0.pdf(x))
assert_close(mvn.logpdf(x, mean, cov_object), dist0.logpdf(x))
assert_close(dist1.logpdf(x), dist0.logpdf(x))
assert_close(mvn.entropy(mean, cov_object), dist0.entropy())
assert_close(dist1.entropy(), dist0.entropy())
@pytest.mark.parametrize("size", [tuple(), (2, 4, 3)])
@pytest.mark.parametrize("cov_type_name", _all_covariance_types)
def test_mvn_with_covariance_cdf(self, size, cov_type_name):
# This is split from the test above because it's slow to be running
# with all matrix types, and there's no need because _mvn.mvnun
# does the calculation. All Covariance needs to do is pass is
# provide the `covariance` attribute.
matrix_type = "diagonal full rank"
A = self._matrices[matrix_type]
cov_type = getattr(_covariance, f"CovVia{cov_type_name}")
preprocessing = self._covariance_preprocessing[cov_type_name]
mean = [0.1, 0.2, 0.3]
cov_object = cov_type(preprocessing(A))
mvn = multivariate_normal
dist0 = multivariate_normal(mean, A, allow_singular=True)
dist1 = multivariate_normal(mean, cov_object, allow_singular=True)
rng = np.random.default_rng(5292808890472453840)
x = rng.multivariate_normal(mean, A, size=size)
assert_close(mvn.cdf(x, mean, cov_object), dist0.cdf(x))
assert_close(dist1.cdf(x), dist0.cdf(x))
assert_close(mvn.logcdf(x, mean, cov_object), dist0.logcdf(x))
assert_close(dist1.logcdf(x), dist0.logcdf(x))
def test_covariance_instantiation(self):
message = "The `Covariance` class cannot be instantiated directly."
with pytest.raises(NotImplementedError, match=message):
Covariance()
@pytest.mark.filterwarnings("ignore::RuntimeWarning") # matrix not PSD
def test_gh9942(self):
# Originally there was a mistake in the `multivariate_normal_frozen`
# `rvs` method that caused all covariance objects to be processed as
# a `_CovViaPSD`. Ensure that this is resolved.
A = np.diag([1, 2, -1e-8])
n = A.shape[0]
mean = np.zeros(n)
# Error if the matrix is processed as a `_CovViaPSD`
with pytest.raises(ValueError, match="The input matrix must be..."):
multivariate_normal(mean, A).rvs()
# No error if it is provided as a `CovViaEigendecomposition`
seed = 3562050283508273023
rng1 = np.random.default_rng(seed)
rng2 = np.random.default_rng(seed)
cov = Covariance.from_eigendecomposition(np.linalg.eigh(A))
rv = multivariate_normal(mean, cov)
res = rv.rvs(random_state=rng1)
ref = multivariate_normal.rvs(mean, cov, random_state=rng2)
assert_equal(res, ref)
def _random_covariance(dim, evals, rng, singular=False):
# Generates random covariance matrix with dimensionality `dim` and
# eigenvalues `evals` using provided Generator `rng`. Randomly sets
# some evals to zero if `singular` is True.
A = rng.random((dim, dim))
A = A @ A.T
_, v = np.linalg.eigh(A)
if singular:
zero_eigs = rng.normal(size=dim) > 0
evals[zero_eigs] = 0
cov = v @ np.diag(evals) @ v.T
return cov
def _sample_orthonormal_matrix(n):
M = np.random.randn(n, n)
u, s, v = scipy.linalg.svd(M)
return u
class TestMultivariateNormal:
def test_input_shape(self):
mu = np.arange(3)
cov = np.identity(2)
assert_raises(ValueError, multivariate_normal.pdf, (0, 1), mu, cov)
assert_raises(ValueError, multivariate_normal.pdf, (0, 1, 2), mu, cov)
assert_raises(ValueError, multivariate_normal.cdf, (0, 1), mu, cov)
assert_raises(ValueError, multivariate_normal.cdf, (0, 1, 2), mu, cov)
def test_scalar_values(self):
np.random.seed(1234)
# When evaluated on scalar data, the pdf should return a scalar
x, mean, cov = 1.5, 1.7, 2.5
pdf = multivariate_normal.pdf(x, mean, cov)
assert_equal(pdf.ndim, 0)
# When evaluated on a single vector, the pdf should return a scalar
x = np.random.randn(5)
mean = np.random.randn(5)
cov = np.abs(np.random.randn(5)) # Diagonal values for cov. matrix
pdf = multivariate_normal.pdf(x, mean, cov)
assert_equal(pdf.ndim, 0)
# When evaluated on scalar data, the cdf should return a scalar
x, mean, cov = 1.5, 1.7, 2.5
cdf = multivariate_normal.cdf(x, mean, cov)
assert_equal(cdf.ndim, 0)
# When evaluated on a single vector, the cdf should return a scalar
x = np.random.randn(5)
mean = np.random.randn(5)
cov = np.abs(np.random.randn(5)) # Diagonal values for cov. matrix
cdf = multivariate_normal.cdf(x, mean, cov)
assert_equal(cdf.ndim, 0)
def test_logpdf(self):
# Check that the log of the pdf is in fact the logpdf
np.random.seed(1234)
x = np.random.randn(5)
mean = np.random.randn(5)
cov = np.abs(np.random.randn(5))
d1 = multivariate_normal.logpdf(x, mean, cov)
d2 = multivariate_normal.pdf(x, mean, cov)
assert_allclose(d1, np.log(d2))
def test_logpdf_default_values(self):
# Check that the log of the pdf is in fact the logpdf
# with default parameters Mean=None and cov = 1
np.random.seed(1234)
x = np.random.randn(5)
d1 = multivariate_normal.logpdf(x)
d2 = multivariate_normal.pdf(x)
# check whether default values are being used
d3 = multivariate_normal.logpdf(x, None, 1)
d4 = multivariate_normal.pdf(x, None, 1)
assert_allclose(d1, np.log(d2))
assert_allclose(d3, np.log(d4))
def test_logcdf(self):
# Check that the log of the cdf is in fact the logcdf
np.random.seed(1234)
x = np.random.randn(5)
mean = np.random.randn(5)
cov = np.abs(np.random.randn(5))
d1 = multivariate_normal.logcdf(x, mean, cov)
d2 = multivariate_normal.cdf(x, mean, cov)
assert_allclose(d1, np.log(d2))
def test_logcdf_default_values(self):
# Check that the log of the cdf is in fact the logcdf
# with default parameters Mean=None and cov = 1
np.random.seed(1234)
x = np.random.randn(5)
d1 = multivariate_normal.logcdf(x)
d2 = multivariate_normal.cdf(x)
# check whether default values are being used
d3 = multivariate_normal.logcdf(x, None, 1)
d4 = multivariate_normal.cdf(x, None, 1)
assert_allclose(d1, np.log(d2))
assert_allclose(d3, np.log(d4))
def test_rank(self):
# Check that the rank is detected correctly.
np.random.seed(1234)
n = 4
mean = np.random.randn(n)
for expected_rank in range(1, n + 1):
s = np.random.randn(n, expected_rank)
cov = np.dot(s, s.T)
distn = multivariate_normal(mean, cov, allow_singular=True)
assert_equal(distn.cov_object.rank, expected_rank)
def test_degenerate_distributions(self):
for n in range(1, 5):
z = np.random.randn(n)
for k in range(1, n):
# Sample a small covariance matrix.
s = np.random.randn(k, k)
cov_kk = np.dot(s, s.T)
# Embed the small covariance matrix into a larger singular one.
cov_nn = np.zeros((n, n))
cov_nn[:k, :k] = cov_kk
# Embed part of the vector in the same way
x = np.zeros(n)
x[:k] = z[:k]
# Define a rotation of the larger low rank matrix.
u = _sample_orthonormal_matrix(n)
cov_rr = np.dot(u, np.dot(cov_nn, u.T))
y = np.dot(u, x)
# Check some identities.
distn_kk = multivariate_normal(np.zeros(k), cov_kk,
allow_singular=True)
distn_nn = multivariate_normal(np.zeros(n), cov_nn,
allow_singular=True)
distn_rr = multivariate_normal(np.zeros(n), cov_rr,
allow_singular=True)
assert_equal(distn_kk.cov_object.rank, k)
assert_equal(distn_nn.cov_object.rank, k)
assert_equal(distn_rr.cov_object.rank, k)
pdf_kk = distn_kk.pdf(x[:k])
pdf_nn = distn_nn.pdf(x)
pdf_rr = distn_rr.pdf(y)
assert_allclose(pdf_kk, pdf_nn)
assert_allclose(pdf_kk, pdf_rr)
logpdf_kk = distn_kk.logpdf(x[:k])
logpdf_nn = distn_nn.logpdf(x)
logpdf_rr = distn_rr.logpdf(y)
assert_allclose(logpdf_kk, logpdf_nn)
assert_allclose(logpdf_kk, logpdf_rr)
# Add an orthogonal component and find the density
y_orth = y + u[:, -1]
pdf_rr_orth = distn_rr.pdf(y_orth)
logpdf_rr_orth = distn_rr.logpdf(y_orth)
# Ensure that this has zero probability
assert_equal(pdf_rr_orth, 0.0)
assert_equal(logpdf_rr_orth, -np.inf)
def test_degenerate_array(self):
# Test that we can generate arrays of random variate from a degenerate
# multivariate normal, and that the pdf for these samples is non-zero
# (i.e. samples from the distribution lie on the subspace)
k = 10
for n in range(2, 6):
for r in range(1, n):
mn = np.zeros(n)
u = _sample_orthonormal_matrix(n)[:, :r]
vr = np.dot(u, u.T)
X = multivariate_normal.rvs(mean=mn, cov=vr, size=k)
pdf = multivariate_normal.pdf(X, mean=mn, cov=vr,
allow_singular=True)
assert_equal(pdf.size, k)
assert np.all(pdf > 0.0)
logpdf = multivariate_normal.logpdf(X, mean=mn, cov=vr,
allow_singular=True)
assert_equal(logpdf.size, k)
assert np.all(logpdf > -np.inf)
def test_large_pseudo_determinant(self):
# Check that large pseudo-determinants are handled appropriately.
# Construct a singular diagonal covariance matrix
# whose pseudo determinant overflows double precision.
large_total_log = 1000.0
npos = 100
nzero = 2
large_entry = np.exp(large_total_log / npos)
n = npos + nzero
cov = np.zeros((n, n), dtype=float)
np.fill_diagonal(cov, large_entry)
cov[-nzero:, -nzero:] = 0
# Check some determinants.
assert_equal(scipy.linalg.det(cov), 0)
assert_equal(scipy.linalg.det(cov[:npos, :npos]), np.inf)
assert_allclose(np.linalg.slogdet(cov[:npos, :npos]),
(1, large_total_log))
# Check the pseudo-determinant.
psd = _PSD(cov)
assert_allclose(psd.log_pdet, large_total_log)
def test_broadcasting(self):
np.random.seed(1234)
n = 4
# Construct a random covariance matrix.
data = np.random.randn(n, n)
cov = np.dot(data, data.T)
mean = np.random.randn(n)
# Construct an ndarray which can be interpreted as
# a 2x3 array whose elements are random data vectors.
X = np.random.randn(2, 3, n)
# Check that multiple data points can be evaluated at once.
desired_pdf = multivariate_normal.pdf(X, mean, cov)
desired_cdf = multivariate_normal.cdf(X, mean, cov)
for i in range(2):
for j in range(3):
actual = multivariate_normal.pdf(X[i, j], mean, cov)
assert_allclose(actual, desired_pdf[i,j])
# Repeat for cdf
actual = multivariate_normal.cdf(X[i, j], mean, cov)
assert_allclose(actual, desired_cdf[i,j], rtol=1e-3)
def test_normal_1D(self):
# The probability density function for a 1D normal variable should
# agree with the standard normal distribution in scipy.stats.distributions
x = np.linspace(0, 2, 10)
mean, cov = 1.2, 0.9
scale = cov**0.5
d1 = norm.pdf(x, mean, scale)
d2 = multivariate_normal.pdf(x, mean, cov)
assert_allclose(d1, d2)
# The same should hold for the cumulative distribution function
d1 = norm.cdf(x, mean, scale)
d2 = multivariate_normal.cdf(x, mean, cov)
assert_allclose(d1, d2)
def test_marginalization(self):
# Integrating out one of the variables of a 2D Gaussian should
# yield a 1D Gaussian
mean = np.array([2.5, 3.5])
cov = np.array([[.5, 0.2], [0.2, .6]])
n = 2 ** 8 + 1 # Number of samples
delta = 6 / (n - 1) # Grid spacing
v = np.linspace(0, 6, n)
xv, yv = np.meshgrid(v, v)
pos = np.empty((n, n, 2))
pos[:, :, 0] = xv
pos[:, :, 1] = yv
pdf = multivariate_normal.pdf(pos, mean, cov)
# Marginalize over x and y axis
margin_x = romb(pdf, delta, axis=0)
margin_y = romb(pdf, delta, axis=1)
# Compare with standard normal distribution
gauss_x = norm.pdf(v, loc=mean[0], scale=cov[0, 0] ** 0.5)
gauss_y = norm.pdf(v, loc=mean[1], scale=cov[1, 1] ** 0.5)
assert_allclose(margin_x, gauss_x, rtol=1e-2, atol=1e-2)
assert_allclose(margin_y, gauss_y, rtol=1e-2, atol=1e-2)
def test_frozen(self):
# The frozen distribution should agree with the regular one
np.random.seed(1234)
x = np.random.randn(5)
mean = np.random.randn(5)
cov = np.abs(np.random.randn(5))
norm_frozen = multivariate_normal(mean, cov)
assert_allclose(norm_frozen.pdf(x), multivariate_normal.pdf(x, mean, cov))
assert_allclose(norm_frozen.logpdf(x),
multivariate_normal.logpdf(x, mean, cov))
assert_allclose(norm_frozen.cdf(x), multivariate_normal.cdf(x, mean, cov))
assert_allclose(norm_frozen.logcdf(x),
multivariate_normal.logcdf(x, mean, cov))
@pytest.mark.parametrize(
'covariance',
[
np.eye(2),
Covariance.from_diagonal([1, 1]),
]
)
def test_frozen_multivariate_normal_exposes_attributes(self, covariance):
mean = np.ones((2,))
cov_should_be = np.eye(2)
norm_frozen = multivariate_normal(mean, covariance)
assert np.allclose(norm_frozen.mean, mean)
assert np.allclose(norm_frozen.cov, cov_should_be)
def test_pseudodet_pinv(self):
# Make sure that pseudo-inverse and pseudo-det agree on cutoff
# Assemble random covariance matrix with large and small eigenvalues
np.random.seed(1234)
n = 7
x = np.random.randn(n, n)
cov = np.dot(x, x.T)
s, u = scipy.linalg.eigh(cov)
s = np.full(n, 0.5)
s[0] = 1.0
s[-1] = 1e-7
cov = np.dot(u, np.dot(np.diag(s), u.T))
# Set cond so that the lowest eigenvalue is below the cutoff
cond = 1e-5
psd = _PSD(cov, cond=cond)
psd_pinv = _PSD(psd.pinv, cond=cond)
# Check that the log pseudo-determinant agrees with the sum
# of the logs of all but the smallest eigenvalue
assert_allclose(psd.log_pdet, np.sum(np.log(s[:-1])))
# Check that the pseudo-determinant of the pseudo-inverse
# agrees with 1 / pseudo-determinant
assert_allclose(-psd.log_pdet, psd_pinv.log_pdet)
def test_exception_nonsquare_cov(self):
cov = [[1, 2, 3], [4, 5, 6]]
assert_raises(ValueError, _PSD, cov)
def test_exception_nonfinite_cov(self):
cov_nan = [[1, 0], [0, np.nan]]
assert_raises(ValueError, _PSD, cov_nan)
cov_inf = [[1, 0], [0, np.inf]]
assert_raises(ValueError, _PSD, cov_inf)
def test_exception_non_psd_cov(self):
cov = [[1, 0], [0, -1]]
assert_raises(ValueError, _PSD, cov)
def test_exception_singular_cov(self):
np.random.seed(1234)
x = np.random.randn(5)
mean = np.random.randn(5)
cov = np.ones((5, 5))
e = np.linalg.LinAlgError
assert_raises(e, multivariate_normal, mean, cov)
assert_raises(e, multivariate_normal.pdf, x, mean, cov)
assert_raises(e, multivariate_normal.logpdf, x, mean, cov)
assert_raises(e, multivariate_normal.cdf, x, mean, cov)
assert_raises(e, multivariate_normal.logcdf, x, mean, cov)
# Message used to be "singular matrix", but this is more accurate.
# See gh-15508
cov = [[1., 0.], [1., 1.]]
msg = "When `allow_singular is False`, the input matrix"
with pytest.raises(np.linalg.LinAlgError, match=msg):
multivariate_normal(cov=cov)
def test_R_values(self):
# Compare the multivariate pdf with some values precomputed
# in R version 3.0.1 (2013-05-16) on Mac OS X 10.6.
# The values below were generated by the following R-script:
# > library(mnormt)
# > x <- seq(0, 2, length=5)
# > y <- 3*x - 2
# > z <- x + cos(y)
# > mu <- c(1, 3, 2)
# > Sigma <- matrix(c(1,2,0,2,5,0.5,0,0.5,3), 3, 3)
# > r_pdf <- dmnorm(cbind(x,y,z), mu, Sigma)
r_pdf = np.array([0.0002214706, 0.0013819953, 0.0049138692,
0.0103803050, 0.0140250800])
x = np.linspace(0, 2, 5)
y = 3 * x - 2
z = x + np.cos(y)
r = np.array([x, y, z]).T
mean = np.array([1, 3, 2], 'd')
cov = np.array([[1, 2, 0], [2, 5, .5], [0, .5, 3]], 'd')
pdf = multivariate_normal.pdf(r, mean, cov)
assert_allclose(pdf, r_pdf, atol=1e-10)
# Compare the multivariate cdf with some values precomputed
# in R version 3.3.2 (2016-10-31) on Debian GNU/Linux.
# The values below were generated by the following R-script:
# > library(mnormt)
# > x <- seq(0, 2, length=5)
# > y <- 3*x - 2
# > z <- x + cos(y)
# > mu <- c(1, 3, 2)
# > Sigma <- matrix(c(1,2,0,2,5,0.5,0,0.5,3), 3, 3)
# > r_cdf <- pmnorm(cbind(x,y,z), mu, Sigma)
r_cdf = np.array([0.0017866215, 0.0267142892, 0.0857098761,
0.1063242573, 0.2501068509])
cdf = multivariate_normal.cdf(r, mean, cov)
assert_allclose(cdf, r_cdf, atol=2e-5)
# Also test bivariate cdf with some values precomputed
# in R version 3.3.2 (2016-10-31) on Debian GNU/Linux.
# The values below were generated by the following R-script:
# > library(mnormt)
# > x <- seq(0, 2, length=5)
# > y <- 3*x - 2
# > mu <- c(1, 3)
# > Sigma <- matrix(c(1,2,2,5), 2, 2)
# > r_cdf2 <- pmnorm(cbind(x,y), mu, Sigma)
r_cdf2 = np.array([0.01262147, 0.05838989, 0.18389571,
0.40696599, 0.66470577])
r2 = np.array([x, y]).T
mean2 = np.array([1, 3], 'd')
cov2 = np.array([[1, 2], [2, 5]], 'd')
cdf2 = multivariate_normal.cdf(r2, mean2, cov2)
assert_allclose(cdf2, r_cdf2, atol=1e-5)
def test_multivariate_normal_rvs_zero_covariance(self):
mean = np.zeros(2)
covariance = np.zeros((2, 2))
model = multivariate_normal(mean, covariance, allow_singular=True)
sample = model.rvs()
assert_equal(sample, [0, 0])
def test_rvs_shape(self):
# Check that rvs parses the mean and covariance correctly, and returns
# an array of the right shape
N = 300
d = 4
sample = multivariate_normal.rvs(mean=np.zeros(d), cov=1, size=N)
assert_equal(sample.shape, (N, d))
sample = multivariate_normal.rvs(mean=None,
cov=np.array([[2, .1], [.1, 1]]),
size=N)
assert_equal(sample.shape, (N, 2))
u = multivariate_normal(mean=0, cov=1)
sample = u.rvs(N)
assert_equal(sample.shape, (N, ))
def test_large_sample(self):
# Generate large sample and compare sample mean and sample covariance
# with mean and covariance matrix.
np.random.seed(2846)
n = 3
mean = np.random.randn(n)
M = np.random.randn(n, n)
cov = np.dot(M, M.T)
size = 5000
sample = multivariate_normal.rvs(mean, cov, size)
assert_allclose(numpy.cov(sample.T), cov, rtol=1e-1)
assert_allclose(sample.mean(0), mean, rtol=1e-1)
def test_entropy(self):
np.random.seed(2846)
n = 3
mean = np.random.randn(n)
M = np.random.randn(n, n)
cov = np.dot(M, M.T)
rv = multivariate_normal(mean, cov)
# Check that frozen distribution agrees with entropy function
assert_almost_equal(rv.entropy(), multivariate_normal.entropy(mean, cov))
# Compare entropy with manually computed expression involving
# the sum of the logs of the eigenvalues of the covariance matrix
eigs = np.linalg.eig(cov)[0]
desired = 1 / 2 * (n * (np.log(2 * np.pi) + 1) + np.sum(np.log(eigs)))
assert_almost_equal(desired, rv.entropy())
def test_lnB(self):
alpha = np.array([1, 1, 1])
desired = .5 # e^lnB = 1/2 for [1, 1, 1]
assert_almost_equal(np.exp(_lnB(alpha)), desired)
def test_cdf_with_lower_limit_arrays(self):
# test CDF with lower limit in several dimensions
rng = np.random.default_rng(2408071309372769818)
mean = [0, 0]
cov = np.eye(2)
a = rng.random((4, 3, 2))*6 - 3
b = rng.random((4, 3, 2))*6 - 3
cdf1 = multivariate_normal.cdf(b, mean, cov, lower_limit=a)
cdf2a = multivariate_normal.cdf(b, mean, cov)
cdf2b = multivariate_normal.cdf(a, mean, cov)
ab1 = np.concatenate((a[..., 0:1], b[..., 1:2]), axis=-1)
ab2 = np.concatenate((a[..., 1:2], b[..., 0:1]), axis=-1)
cdf2ab1 = multivariate_normal.cdf(ab1, mean, cov)
cdf2ab2 = multivariate_normal.cdf(ab2, mean, cov)
cdf2 = cdf2a + cdf2b - cdf2ab1 - cdf2ab2
assert_allclose(cdf1, cdf2)
def test_cdf_with_lower_limit_consistency(self):
# check that multivariate normal CDF functions are consistent
rng = np.random.default_rng(2408071309372769818)
mean = rng.random(3)
cov = rng.random((3, 3))
cov = cov @ cov.T
a = rng.random((2, 3))*6 - 3
b = rng.random((2, 3))*6 - 3
cdf1 = multivariate_normal.cdf(b, mean, cov, lower_limit=a)
cdf2 = multivariate_normal(mean, cov).cdf(b, lower_limit=a)
cdf3 = np.exp(multivariate_normal.logcdf(b, mean, cov, lower_limit=a))
cdf4 = np.exp(multivariate_normal(mean, cov).logcdf(b, lower_limit=a))
assert_allclose(cdf2, cdf1, rtol=1e-4)
assert_allclose(cdf3, cdf1, rtol=1e-4)
assert_allclose(cdf4, cdf1, rtol=1e-4)
def test_cdf_signs(self):
# check that sign of output is correct when np.any(lower > x)
mean = np.zeros(3)
cov = np.eye(3)
b = [[1, 1, 1], [0, 0, 0], [1, 0, 1], [0, 1, 0]]
a = [[0, 0, 0], [1, 1, 1], [0, 1, 0], [1, 0, 1]]
# when odd number of elements of b < a, output is negative
expected_signs = np.array([1, -1, -1, 1])
cdf = multivariate_normal.cdf(b, mean, cov, lower_limit=a)
assert_allclose(cdf, cdf[0]*expected_signs)
def test_mean_cov(self):
# test the interaction between a Covariance object and mean
P = np.diag(1 / np.array([1, 2, 3]))
cov_object = _covariance.CovViaPrecision(P)
message = "`cov` represents a covariance matrix in 3 dimensions..."
with pytest.raises(ValueError, match=message):
multivariate_normal.entropy([0, 0], cov_object)
with pytest.raises(ValueError, match=message):
multivariate_normal([0, 0], cov_object)
x = [0.5, 0.5, 0.5]
ref = multivariate_normal.pdf(x, [0, 0, 0], cov_object)
assert_equal(multivariate_normal.pdf(x, cov=cov_object), ref)
ref = multivariate_normal.pdf(x, [1, 1, 1], cov_object)
assert_equal(multivariate_normal.pdf(x, 1, cov=cov_object), ref)
def test_fit_wrong_fit_data_shape(self):
data = [1, 3]
error_msg = "`x` must be two-dimensional."
with pytest.raises(ValueError, match=error_msg):
multivariate_normal.fit(data)
@pytest.mark.parametrize('dim', (3, 5))
def test_fit_correctness(self, dim):
rng = np.random.default_rng(4385269356937404)
x = rng.random((100, dim))
mean_est, cov_est = multivariate_normal.fit(x)
mean_ref, cov_ref = np.mean(x, axis=0), np.cov(x.T, ddof=0)
assert_allclose(mean_est, mean_ref, atol=1e-15)
assert_allclose(cov_est, cov_ref, rtol=1e-15)
def test_fit_both_parameters_fixed(self):
data = np.full((2, 1), 3)
mean_fixed = 1.
cov_fixed = np.atleast_2d(1.)
mean, cov = multivariate_normal.fit(data, fix_mean=mean_fixed,
fix_cov=cov_fixed)
assert_equal(mean, mean_fixed)
assert_equal(cov, cov_fixed)
@pytest.mark.parametrize('fix_mean', [np.zeros((2, 2)),
np.zeros((3, ))])
def test_fit_fix_mean_input_validation(self, fix_mean):
msg = ("`fix_mean` must be a one-dimensional array the same "
"length as the dimensionality of the vectors `x`.")
with pytest.raises(ValueError, match=msg):
multivariate_normal.fit(np.eye(2), fix_mean=fix_mean)
@pytest.mark.parametrize('fix_cov', [np.zeros((2, )),
np.zeros((3, 2)),
np.zeros((4, 4))])
def test_fit_fix_cov_input_validation_dimension(self, fix_cov):
msg = ("`fix_cov` must be a two-dimensional square array "
"of same side length as the dimensionality of the "
"vectors `x`.")
with pytest.raises(ValueError, match=msg):
multivariate_normal.fit(np.eye(3), fix_cov=fix_cov)
def test_fit_fix_cov_not_positive_semidefinite(self):
error_msg = "`fix_cov` must be symmetric positive semidefinite."
with pytest.raises(ValueError, match=error_msg):
fix_cov = np.array([[1., 0.], [0., -1.]])
multivariate_normal.fit(np.eye(2), fix_cov=fix_cov)
def test_fit_fix_mean(self):
rng = np.random.default_rng(4385269356937404)
loc = rng.random(3)
A = rng.random((3, 3))
cov = np.dot(A, A.T)
samples = multivariate_normal.rvs(mean=loc, cov=cov, size=100,
random_state=rng)
mean_free, cov_free = multivariate_normal.fit(samples)
logp_free = multivariate_normal.logpdf(samples, mean=mean_free,
cov=cov_free).sum()
mean_fix, cov_fix = multivariate_normal.fit(samples, fix_mean=loc)
assert_equal(mean_fix, loc)
logp_fix = multivariate_normal.logpdf(samples, mean=mean_fix,
cov=cov_fix).sum()
# test that fixed parameters result in lower likelihood than free
# parameters
assert logp_fix < logp_free
# test that a small perturbation of the resulting parameters
# has lower likelihood than the estimated parameters
A = rng.random((3, 3))
m = 1e-8 * np.dot(A, A.T)
cov_perturbed = cov_fix + m
logp_perturbed = (multivariate_normal.logpdf(samples,
mean=mean_fix,
cov=cov_perturbed)
).sum()
assert logp_perturbed < logp_fix
def test_fit_fix_cov(self):
rng = np.random.default_rng(4385269356937404)
loc = rng.random(3)
A = rng.random((3, 3))
cov = np.dot(A, A.T)
samples = multivariate_normal.rvs(mean=loc, cov=cov,
size=100, random_state=rng)
mean_free, cov_free = multivariate_normal.fit(samples)
logp_free = multivariate_normal.logpdf(samples, mean=mean_free,
cov=cov_free).sum()
mean_fix, cov_fix = multivariate_normal.fit(samples, fix_cov=cov)
assert_equal(mean_fix, np.mean(samples, axis=0))
assert_equal(cov_fix, cov)
logp_fix = multivariate_normal.logpdf(samples, mean=mean_fix,
cov=cov_fix).sum()
# test that fixed parameters result in lower likelihood than free
# parameters
assert logp_fix < logp_free
# test that a small perturbation of the resulting parameters
# has lower likelihood than the estimated parameters
mean_perturbed = mean_fix + 1e-8 * rng.random(3)
logp_perturbed = (multivariate_normal.logpdf(samples,
mean=mean_perturbed,
cov=cov_fix)
).sum()
assert logp_perturbed < logp_fix
class TestMatrixNormal:
def test_bad_input(self):
# Check that bad inputs raise errors
num_rows = 4
num_cols = 3
M = np.full((num_rows,num_cols), 0.3)
U = 0.5 * np.identity(num_rows) + np.full((num_rows, num_rows), 0.5)
V = 0.7 * np.identity(num_cols) + np.full((num_cols, num_cols), 0.3)
# Incorrect dimensions
assert_raises(ValueError, matrix_normal, np.zeros((5,4,3)))
assert_raises(ValueError, matrix_normal, M, np.zeros(10), V)
assert_raises(ValueError, matrix_normal, M, U, np.zeros(10))
assert_raises(ValueError, matrix_normal, M, U, U)
assert_raises(ValueError, matrix_normal, M, V, V)
assert_raises(ValueError, matrix_normal, M.T, U, V)
e = np.linalg.LinAlgError
# Singular covariance for the rvs method of a non-frozen instance
assert_raises(e, matrix_normal.rvs,
M, U, np.ones((num_cols, num_cols)))
assert_raises(e, matrix_normal.rvs,
M, np.ones((num_rows, num_rows)), V)
# Singular covariance for a frozen instance
assert_raises(e, matrix_normal, M, U, np.ones((num_cols, num_cols)))
assert_raises(e, matrix_normal, M, np.ones((num_rows, num_rows)), V)
def test_default_inputs(self):
# Check that default argument handling works
num_rows = 4
num_cols = 3
M = np.full((num_rows,num_cols), 0.3)
U = 0.5 * np.identity(num_rows) + np.full((num_rows, num_rows), 0.5)
V = 0.7 * np.identity(num_cols) + np.full((num_cols, num_cols), 0.3)
Z = np.zeros((num_rows, num_cols))
Zr = np.zeros((num_rows, 1))
Zc = np.zeros((1, num_cols))
Ir = np.identity(num_rows)
Ic = np.identity(num_cols)
I1 = np.identity(1)
assert_equal(matrix_normal.rvs(mean=M, rowcov=U, colcov=V).shape,
(num_rows, num_cols))
assert_equal(matrix_normal.rvs(mean=M).shape,
(num_rows, num_cols))
assert_equal(matrix_normal.rvs(rowcov=U).shape,
(num_rows, 1))
assert_equal(matrix_normal.rvs(colcov=V).shape,
(1, num_cols))
assert_equal(matrix_normal.rvs(mean=M, colcov=V).shape,
(num_rows, num_cols))
assert_equal(matrix_normal.rvs(mean=M, rowcov=U).shape,
(num_rows, num_cols))
assert_equal(matrix_normal.rvs(rowcov=U, colcov=V).shape,
(num_rows, num_cols))
assert_equal(matrix_normal(mean=M).rowcov, Ir)
assert_equal(matrix_normal(mean=M).colcov, Ic)
assert_equal(matrix_normal(rowcov=U).mean, Zr)
assert_equal(matrix_normal(rowcov=U).colcov, I1)
assert_equal(matrix_normal(colcov=V).mean, Zc)
assert_equal(matrix_normal(colcov=V).rowcov, I1)
assert_equal(matrix_normal(mean=M, rowcov=U).colcov, Ic)
assert_equal(matrix_normal(mean=M, colcov=V).rowcov, Ir)
assert_equal(matrix_normal(rowcov=U, colcov=V).mean, Z)
def test_covariance_expansion(self):
# Check that covariance can be specified with scalar or vector
num_rows = 4
num_cols = 3
M = np.full((num_rows, num_cols), 0.3)
Uv = np.full(num_rows, 0.2)
Us = 0.2
Vv = np.full(num_cols, 0.1)
Vs = 0.1
Ir = np.identity(num_rows)
Ic = np.identity(num_cols)
assert_equal(matrix_normal(mean=M, rowcov=Uv, colcov=Vv).rowcov,
0.2*Ir)
assert_equal(matrix_normal(mean=M, rowcov=Uv, colcov=Vv).colcov,
0.1*Ic)
assert_equal(matrix_normal(mean=M, rowcov=Us, colcov=Vs).rowcov,
0.2*Ir)
assert_equal(matrix_normal(mean=M, rowcov=Us, colcov=Vs).colcov,
0.1*Ic)
def test_frozen_matrix_normal(self):