| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import numpy as np |
| 4 |
import pytest |
| 5 |
|
| 6 |
from cctbx import sgtbx |
| 7 |
from scitbx.array_family import flex |
| 8 |
|
| 9 |
from dials.algorithms.symmetry.cosym import engine, target |
| 10 |
from dials.algorithms.symmetry.cosym._generate_test_data import generate_test_data |
| 11 |
|
| 12 |
|
| 13 |
@pytest.mark.parametrize("space_group", ["P2", "P3", "P6", "R3:h", "I23"]) |
| 14 |
def test_cosym_target(space_group): |
| 15 |
datasets, expected_reindexing_ops = generate_test_data( |
| 16 |
space_group=sgtbx.space_group_info(symbol=space_group).group(), sample_size=50 |
| 17 |
) |
| 18 |
|
| 19 |
intensities = datasets[0] |
| 20 |
dataset_ids = np.zeros(intensities.size() * len(datasets)) |
| 21 |
for i, d in enumerate(datasets[1:]): |
| 22 |
i += 1 |
| 23 |
intensities = intensities.concatenate(d, assert_is_similar_symmetry=False) |
| 24 |
dataset_ids[i * d.size() : (i + 1) * d.size()] = np.full(d.size(), i, dtype=int) |
| 25 |
|
| 26 |
for weights in [None, "count", "standard_error"]: |
| 27 |
print(weights) |
| 28 |
t = target.Target(intensities, dataset_ids, weights=weights) |
| 29 |
m = len(t.sym_ops) |
| 30 |
n = len(datasets) |
| 31 |
assert t.dim == m |
| 32 |
assert t.rij_matrix.shape == (n * m, n * m) |
| 33 |
# x = np.random.rand(n * m * t.dim) |
| 34 |
x = flex.random_double(n * m * t.dim).as_numpy_array() |
| 35 |
f0 = t.compute_functional(x) |
| 36 |
g = t.compute_gradients(x) |
| 37 |
g_fd = t.compute_gradients_fd(x) |
| 38 |
np.testing.assert_allclose(g, g_fd, rtol=2e-3) |
| 39 |
c = t.curvatures(x) |
| 40 |
c_fd = t.curvatures_fd(x, eps=1e-3) |
| 41 |
assert list(c) == pytest.approx(c_fd, rel=0.8e-1) |
| 42 |
|
| 43 |
if weights == "count": |
| 44 |
# Absolute upper limit on weights |
| 45 |
assert t.wij_matrix.max() <= datasets[0].size() |
| 46 |
|
| 47 |
minimizer = engine.lbfgs_with_curvs(target=t, coords=x) |
| 48 |
# check functional has decreased and gradients are approximately zero |
| 49 |
f = t.compute_functional(minimizer.coords) |
| 50 |
g = t.compute_gradients(minimizer.coords) |
| 51 |
g_fd = t.compute_gradients_fd(minimizer.coords) |
| 52 |
assert f < f0 |
| 53 |
assert pytest.approx(list(g), abs=3e-3) == [0] * len(g) |
| 54 |
assert pytest.approx(g_fd, abs=3e-3) == [0] * len(g) |