Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions src/optimagic/parameters/block_trees.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
14 changes: 14 additions & 0 deletions tests/estimagic/test_estimate_ml.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]}

Expand Down
22 changes: 21 additions & 1 deletion tests/optimagic/parameters/test_block_trees.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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}
Expand Down
Loading