| 1 | import numpy as np |
| 2 | from numpy.testing import assert_allclose |
| 3 | |
| 4 | from hmmlearn.utils import normalize, fill_covars |
| 5 | |
| 6 | |
| 7 | def test_normalize(): |
| 8 | A = np.random.normal(42., size=128) |
| 9 | A[np.random.choice(len(A), size=16)] = 0.0 |
| 10 | assert (A == 0.0).any() |
| 11 | normalize(A) |
| 12 | assert_allclose(A.sum(), 1.) |
| 13 | |
| 14 | |
| 15 | def test_normalize_along_axis(): |
| 16 | A = np.random.normal(42., size=(128, 4)) |
| 17 | for axis in range(A.ndim): |
| 18 | A[np.random.choice(len(A), size=16), axis] = 0.0 |
| 19 | assert (A[:, axis] == 0.0).any() |
| 20 | normalize(A, axis=axis) |
| 21 | assert_allclose(A.sum(axis=axis), 1.) |
| 22 | |
| 23 | |
| 24 | def test_fill_covars(): |
| 25 | full = np.arange(12).reshape(3, 2, 2) + 1 |
| 26 | np.testing.assert_equal(fill_covars(full, 'full', 3, 2), full) |
| 27 | |
| 28 | diag = np.arange(6).reshape(3, 2) + 1 |
| 29 | expected = np.array([[[1, 0], [0, 2]], |
| 30 | [[3, 0], [0, 4]], |
| 31 | [[5, 0], [0, 6]]]) |
| 32 | np.testing.assert_equal(fill_covars(diag, 'diag', 3, 2), expected) |
| 33 | |
| 34 | tied = np.arange(4).reshape(2, 2) + 1 |
| 35 | expected = np.array([[[1, 2], [3, 4]], |
| 36 | [[1, 2], [3, 4]], |
| 37 | [[1, 2], [3, 4]]]) |
| 38 | np.testing.assert_equal(fill_covars(tied, 'tied', 3, 2), expected) |
| 39 | |
| 40 | spherical = np.array([1, 2, 3]) |
| 41 | expected = np.array([[[1, 0], [0, 1]], |
| 42 | [[2, 0], [0, 2]], |
| 43 | [[3, 0], [0, 3]]]) |
| 44 | np.testing.assert_equal( |
| 45 | fill_covars(spherical, 'spherical', 3, 2), expected) |