diff --git a/src/optimagic/parameters/block_trees.py b/src/optimagic/parameters/block_trees.py index fb7012ba3..058275f36 100644 --- a/src/optimagic/parameters/block_trees.py +++ b/src/optimagic/parameters/block_trees.py @@ -118,8 +118,7 @@ def hessian_to_block_tree(hessian, f_tree, params_tree): for leaf_inner, s2, block_values in zip( flat_p, shapes_p, np.split(submat, block_bounds_p, axis=2), strict=False ): - _shape = [k for k in (*s0, *s1, *s2) if k != 1] - raw_block = block_values.reshape(_shape) + raw_block = block_values.reshape((*s0, *s1, *s2)) block = _convert_raw_block_to_pandas(raw_block, leaf_outer, leaf_inner) row.append(block) blocks.append(row) diff --git a/tests/estimagic/test_estimate_ml.py b/tests/estimagic/test_estimate_ml.py index 64a8688c6..5385ae100 100644 --- a/tests/estimagic/test_estimate_ml.py +++ b/tests/estimagic/test_estimate_ml.py @@ -431,6 +431,20 @@ def test_estimate_ml_general_pytree(normal_inputs): assert np.abs(true["sd"] - got.summary(method="jacobian")["sd"]["value"][0]) < 1e-1 +def test_estimate_ml_single_parameter(normal_inputs): + y = normal_inputs["y"] + + def loglike(mean): + return -0.5 * (y - mean) ** 2 + + got = estimate_ml(loglike=loglike, params=5.0, optimize_options="scipy_lbfgsb") + + assert np.abs(got.params - normal_inputs["true"]["mean"]) < 1e-1 + cov = got.cov(method="hessian", return_type="array") + assert cov.shape == (1, 1) + assert np.allclose(cov, 1 / len(y)) + + def test_to_pickle(normal_inputs, tmp_path): kwargs = {"y": normal_inputs["y"]} diff --git a/tests/optimagic/parameters/test_block_trees.py b/tests/optimagic/parameters/test_block_trees.py index e4e170810..60d8c2df7 100644 --- a/tests/optimagic/parameters/test_block_trees.py +++ b/tests/optimagic/parameters/test_block_trees.py @@ -10,7 +10,7 @@ hessian_to_block_tree, matrix_to_block_tree, ) -from optimagic.pytree import tree_equal, tree_leaves +from optimagic.pytree import tree_equal, tree_leaves, tree_map from optimagic.typing import PyTreeNamespace @@ -149,6 +149,26 @@ def func(params): assert _tree_equal_up_to_dtype(expected, got) +@pytest.mark.parametrize( + "func, params, expected_shapes", + [ + (lambda x: x @ x, np.array([1.0]), (1, 1)), + (lambda x: x**2, np.array([1.0]), (1, 1, 1)), + ( + lambda p: float(np.sum(p["a"] ** 2) + p["b"] ** 2), + {"a": np.array([1.0]), "b": 2.0}, + {"a": {"a": (1, 1), "b": (1,)}, "b": {"a": (1,), "b": ()}}, + ), + ], +) +def test_second_derivative_keeps_dimensions_of_length_one( + func, params, expected_shapes +): + got = second_derivative(func, params).derivative + got_shapes = tree_map(np.shape, got) + assert got_shapes == expected_shapes + + def test_block_tree_to_matrix_valueerror(): # test that value error is raised when dimensions don't match inner = {"a": 1, "b": 1}