Ejemplo n.º 1
0
    def _rebuild_covariance_matrix(self, covariance):
        """Rebuild the covariance matrix from its parameter values.

        This method follows the steps:

            * Rebuild a square matrix out of a triangular one.
            * Add the missing half of the matrix by adding its transposed and
              then removing the duplicated diagonal values.
            * ensure the matrix is positive definite

        Args:
            covariance (list):
                covariance values after unflattening model parameters.

        Result:
            list[list[float]]:
                Symmetric positive semi-definite matrix.
        """
        covariance = np.array(square_matrix(covariance))
        covariance = (covariance + covariance.T -
                      (np.identity(covariance.shape[0]) * covariance))

        if not check_matrix_symmetric_positive_definite(covariance):
            covariance = make_positive_definite(covariance)

        return covariance.tolist()
Ejemplo n.º 2
0
def test_make_positive_definite_iterate(mock_check):
    """Test find the nearest positive-definite matrix iterating."""
    # Setup
    mock_check.side_effect = [False, False, True]

    # Run
    matrix = np.array([[-1, -5], [-3, -7]])
    result = make_positive_definite(matrix)

    # Asserts
    expected = np.array([[0.8, -0.4], [-0.4, 0.2]])
    np.testing.assert_array_almost_equal(result, expected)

    assert mock_check.call_count == 3
Ejemplo n.º 3
0
def test_make_positive_definite(mock_check):
    """Test find the nearest positive-definite matrix."""
    # Setup
    mock_check.return_value = True

    # Run
    matrix = np.array([[0, 1], [1, 0]])
    result = make_positive_definite(matrix)

    # Asserts
    expected = np.array([[0.5, 0.5], [0.5, 0.5]])
    np.testing.assert_equal(result, expected)

    assert mock_check.call_count == 1
Ejemplo n.º 4
0
    def _prepare_sampled_covariance(self, covariance):
        """Prepare a covariance matrix.

        Args:
            covariance (list):
                covariance after unflattening model parameters.

        Result:
            list[list]:
                symmetric Positive semi-definite matrix.
        """
        covariance = np.array(square_matrix(covariance))
        covariance = (covariance + covariance.T -
                      (np.identity(covariance.shape[0]) * covariance))

        if not check_matrix_symmetric_positive_definite(covariance):
            covariance = make_positive_definite(covariance)

        return covariance.tolist()