diff --git a/src/pyrecest/utils/cost_matrix_adjustments.py b/src/pyrecest/utils/cost_matrix_adjustments.py index f2a56cbae..1e1f6f83e 100644 --- a/src/pyrecest/utils/cost_matrix_adjustments.py +++ b/src/pyrecest/utils/cost_matrix_adjustments.py @@ -39,6 +39,11 @@ class CostMatrixAdjustmentResult: diagnostics: Mapping[str, Any] | None = field(default_factory=dict) def __post_init__(self) -> None: + object.__setattr__( + self, + "adjusted_cost_matrix", + _as_cost_matrix(self.adjusted_cost_matrix).copy(), + ) object.__setattr__( self, "diagnostics", diff --git a/tests/test_cost_matrix_adjustment_result_validation.py b/tests/test_cost_matrix_adjustment_result_validation.py new file mode 100644 index 000000000..679ce365a --- /dev/null +++ b/tests/test_cost_matrix_adjustment_result_validation.py @@ -0,0 +1,34 @@ +import unittest + +import numpy as np +import numpy.testing as npt + +from pyrecest.utils.cost_matrix_adjustments import CostMatrixAdjustmentResult + + +class TestCostMatrixAdjustmentResultValidation(unittest.TestCase): + def test_result_takes_ownership_of_adjusted_matrix(self): + matrix = np.array([[1.0, 2.0]], dtype=float) + + result = CostMatrixAdjustmentResult(matrix) + matrix[:] = -7.0 + + npt.assert_allclose(result.adjusted_cost_matrix, np.array([[1.0, 2.0]])) + + def test_result_rejects_invalid_direct_construction(self): + invalid_matrices = ( + np.array([1.0, 2.0]), + np.array([[np.nan]]), + np.array([[-np.inf]]), + np.array([[True]]), + np.array([[1.0 + 0.0j]]), + ) + + for matrix in invalid_matrices: + with self.subTest(matrix=matrix): + with self.assertRaises(ValueError): + CostMatrixAdjustmentResult(matrix) + + +if __name__ == "__main__": + unittest.main()