diff --git a/news/cif-origin-tests.rst b/news/cif-origin-tests.rst new file mode 100644 index 0000000..b612e58 --- /dev/null +++ b/news/cif-origin-tests.rst @@ -0,0 +1,23 @@ +**Added:** + +* No news needed: tests for the cell origin of CIF files are not user facing; the fix they describe adds its own news + +**Changed:** + +* + +**Deprecated:** + +* + +**Removed:** + +* + +**Fixed:** + +* + +**Security:** + +* diff --git a/tests/test_cif_origin.py b/tests/test_cif_origin.py new file mode 100644 index 0000000..63d654b --- /dev/null +++ b/tests/test_cif_origin.py @@ -0,0 +1,481 @@ +"""Regression tests for the unit cell origin used by a CIF file. + +A CIF file defines its symmetry, including the position of the origin, +by the symmetry operations it lists or, failing that, by a Hall symbol +or a Hermann-Mauguin symbol with an origin choice qualifier. These +tests build small CIF files for one structure described from different +origins and check that each expands to the sites generated by the +symmetry operations which that file defines. + +See +https://github.com/diffpy/diffpy.structure/issues/86. +""" + +import re +import warnings +from fractions import Fraction + +import numpy +import pytest + +from diffpy.structure.parsers import get_parser +from diffpy.structure.spacegroups import get_space_group + +# The 24 space groups that International Tables list with two origin +# choices. Each row is the space group number, the Hermann-Mauguin +# symbol, the position of the origin choice 2 origin (a center of +# inversion) in origin choice 1 coordinates, and the Hall symbol of +# origin choice 2. +TWO_ORIGIN_GROUPS = [ + (48, "P n n n", ("1/4", "1/4", "1/4"), "-P 2ab 2bc"), + (50, "P b a n", ("1/4", "1/4", "0"), "-P 2ab 2b"), + (59, "P m m n", ("1/4", "1/4", "0"), "-P 2ab 2a"), + (68, "C c c a", ("0", "1/4", "1/4"), "-C 2a 2ac"), + (70, "F d d d", ("1/8", "1/8", "1/8"), "-F 2uv 2vw"), + (85, "P 4/n", ("1/4", "3/4", "0"), "-P 4a"), + (86, "P 42/n", ("1/4", "1/4", "1/4"), "-P 4bc"), + (88, "I 41/a", ("0", "1/4", "1/8"), "-I 4ad"), + (125, "P 4/n b m", ("1/4", "1/4", "0"), "-P 4a 2b"), + (126, "P 4/n n c", ("1/4", "1/4", "1/4"), "-P 4a 2bc"), + (129, "P 4/n m m", ("1/4", "3/4", "0"), "-P 4a 2a"), + (130, "P 4/n c c", ("1/4", "3/4", "0"), "-P 4a 2ac"), + (133, "P 42/n b c", ("1/4", "3/4", "1/4"), "-P 4ac 2b"), + (134, "P 42/n n m", ("1/4", "3/4", "1/4"), "-P 4ac 2bc"), + (137, "P 42/n m c", ("1/4", "3/4", "1/4"), "-P 4ac 2a"), + (138, "P 42/n c m", ("1/4", "3/4", "1/4"), "-P 4ac 2ac"), + (141, "I 41/a m d", ("0", "3/4", "1/8"), "-I 4bd 2"), + (142, "I 41/a c d", ("0", "3/4", "1/8"), "-I 4bd 2c"), + (201, "P n -3", ("1/4", "1/4", "1/4"), "-P 2ab 2bc 3"), + (203, "F d -3", ("1/8", "1/8", "1/8"), "-F 2uv 2vw 3"), + (222, "P n -3 n", ("1/4", "1/4", "1/4"), "-P 4a 2bc 3"), + (224, "P n -3 m", ("1/4", "1/4", "1/4"), "-P 4bc 2bc 3"), + (227, "F d -3 m", ("1/8", "1/8", "1/8"), "-F 4vw 2vw 3"), + (228, "F d -3 c", ("3/8", "3/8", "3/8"), "-F 4ud 2vw 3"), +] +TWO_ORIGIN_SHIFTS = {number: shift for number, _, shift, _ in TWO_ORIGIN_GROUPS} + +# The 68 space groups of the ten polar crystal classes 1, 2, m, mm2, 4, +# 4mm, 3, 3m, 6 and 6mm. Their origin is not fixed by symmetry along +# the polar direction(s), so it can sit anywhere along them. +POLAR_GROUPS = [ + 1, + *range(3, 10), + *range(25, 47), + *range(75, 81), + *range(99, 111), + *range(143, 147), + *range(156, 162), + *range(168, 174), + *range(183, 187), +] + +CELL_PARAMETERS = { + "TRICLINIC": (5.1, 6.2, 7.3, 81, 97, 108), + "MONOCLINIC": (5.1, 6.2, 7.3, 90, 97, 90), + "ORTHORHOMBIC": (5.1, 6.2, 7.3, 90, 90, 90), + "TETRAGONAL": (5.1, 5.1, 7.3, 90, 90, 90), + "TRIGONAL": (5.1, 5.1, 7.3, 90, 90, 120), + "HEXAGONAL": (5.1, 5.1, 7.3, 90, 90, 120), + "CUBIC": (5.1, 5.1, 5.1, 90, 90, 90), +} +GENERAL_POSITION = (0.11, 0.23, 0.37) + +# The warning for a CIF that uses a space group with two origin choices +# without saying which origin it uses. +AMBIGUOUS_ORIGIN_WARNING = ( + "The CIF file uses space group number {it_number}, which has two possible origins, " + "but it does not say which origin it uses. Origin choice 1 was assumed. " + "If the structure looks wrong, for example with atoms too close together, " + "append ' :2' to the Hermann-Mauguin space group symbol in the CIF file and load it again." +) +AMBIGUOUS_ORIGIN_PATTERN = "two possible origins" + + +def _tabulated_symops(number): + """Return the tabulated operations of a space group as (R, t) + pairs.""" + return [(op.R, op.t) for op in get_space_group(number).iter_symops()] + + +def _shift_origin(symops, origin): + """Return the operations that describe the same symmetry from a cell + origin moved to the fractional position `origin`.""" + origin = numpy.array([float(Fraction(v)) for v in origin]) + return [(R, (t + (R - numpy.identity(3)) @ origin) % 1) for R, t in symops] + + +def _polar_shift(symops): + """Return an origin shift along the direction(s) that all rotations + of the space group leave unchanged.""" + stacked_rotations = numpy.vstack([R - numpy.identity(3) for R, _ in symops]) + _, singular_values, vh = numpy.linalg.svd(stacked_rotations) + invariant_directions = vh[numpy.abs(singular_values) < 1e-8] + return 0.137 * invariant_directions.sum(axis=0) + + +def _xyz_string(symop): + """Return a symmetry operation in the CIF form, e.g. + '-x+1/2,y,-z'.""" + R, t = symop + rows = [] + for rotation_row, translation in zip(R, t): + row = "" + for coefficient, axis in zip(rotation_row, "xyz"): + if coefficient: + row += ("+" if coefficient > 0 else "-") + axis + shift = Fraction(float(translation)).limit_denominator(48) + if shift: + row += f"+{shift}" + rows.append(row.lstrip("+")) + return ",".join(rows) + + +def _move_sites(sites, origin): + """Return site coordinates referred to a cell origin moved to the + fractional position `origin`.""" + origin = numpy.array([float(Fraction(v)) for v in origin]) + return (numpy.array(sites, dtype=float) - origin) % 1 + + +def _sorted_sites(xyz): + """Return positions wrapped to the unit cell and sorted so that two + sets of sites can be compared.""" + xyz = numpy.round(numpy.reshape(xyz, (-1, 3)), 5) % 1 + # Round again because the modulo leaves noise in the last digits. + xyz = numpy.round(xyz, 5) + return xyz[numpy.lexsort(xyz.T[::-1])] + + +def _orbit(symops, sites): + """Return all unit cell positions that the operations generate from + the sites, with duplicates removed.""" + images = [R @ xyz + t for xyz in sites for R, t in symops] + return numpy.unique(_sorted_sites(images), axis=0) + + +def _make_cif(crystal_system, sites, symops=None, it_number=None, hm_name=None, hall_name=None): + """Return the text of a CIF file that carries only the requested + symmetry items.""" + lines = ["data_origin_test"] + cell_items = ("length_a", "length_b", "length_c", "angle_alpha", "angle_beta", "angle_gamma") + for item, value in zip(cell_items, CELL_PARAMETERS[crystal_system]): + lines.append(f"_cell_{item} {value}") + if it_number is not None: + lines.append(f"_space_group_IT_number {it_number}") + if hm_name is not None: + lines.append(f"_space_group_name_H-M_alt '{hm_name}'") + if hall_name is not None: + lines.append(f"_space_group_name_Hall '{hall_name}'") + if symops is not None: + lines += ["loop_", "_space_group_symop_operation_xyz"] + lines += [f"'{_xyz_string(symop)}'" for symop in symops] + lines += ["loop_", "_atom_site_label", "_atom_site_type_symbol"] + lines += ["_atom_site_fract_x", "_atom_site_fract_y", "_atom_site_fract_z"] + lines += ["C%i C %.6f %.6f %.6f" % (i + 1, *xyz) for i, xyz in enumerate(sites)] + return "\n".join(lines) + "\n" + + +def _parse_sites(cif_text): + """Return the sorted fractional positions of the structure that the + CIF parser builds from the text.""" + return _sorted_sites(get_parser("cif").parse(cif_text).xyz) + + +def _assert_same_sites(actual_sites, expected_sites): + assert len(actual_sites) == len(expected_sites) + numpy.testing.assert_allclose(actual_sites, expected_sites, atol=1e-4) + + +@pytest.mark.parametrize( + "it_number", + [ + # Test that the origin choice 2 shifts tabulated above are consistent + # with the space group tables in diffpy.structure. + # C1: one case per two-origin group, expect an inversion through the + # origin after the shift to origin choice 2 and none before it + pytest.param(row[0], id=row[1].replace(" ", "")) + for row in TWO_ORIGIN_GROUPS + ], +) +def test_two_origin_table(it_number): + inversion = "-x,-y,-z" + origin1_symops = _tabulated_symops(it_number) + origin2_symops = _shift_origin(origin1_symops, TWO_ORIGIN_SHIFTS[it_number]) + assert inversion not in [_xyz_string(symop) for symop in origin1_symops] + assert inversion in [_xyz_string(symop) for symop in origin2_symops] + + +@pytest.mark.parametrize( + "symmetry_items", + [ + # Test a structure in origin choice 2, where the CIF defines the origin + # through different sets of data items. The asymmetric unit holds one + # general site and one site on the origin choice 1 origin. + # C1: all operations listed, with IT number and H-M symbol with a ":2" + # qualifier, expect the sites generated by the listed operations + pytest.param(("symops", "it_number", "hm_name"), id="symops-number-hm"), + # C2: no operations, IT number and H-M symbol with a ":2" qualifier, + # expect the sites generated by the origin choice 2 operations + pytest.param(("it_number", "hm_name"), id="number-hm"), + # C3: no operations, only an H-M symbol with a ":2" qualifier, expect + # the sites generated by the origin choice 2 operations + pytest.param(("hm_name",), id="hm-only"), + # C4: no operations, IT number and the Hall symbol of origin choice 2, + # expect the sites generated by the origin choice 2 operations + pytest.param(("it_number", "hall_name"), id="number-hall"), + ], +) +@pytest.mark.parametrize( + "it_number, hm_symbol, origin2, hall_symbol", + [ + # C1: one case per space group that has two origin choices, expect + # the origin choice 2 expansion + pytest.param(*row, id=row[1].replace(" ", "")) + for row in TWO_ORIGIN_GROUPS + ], +) +def test_origin_choice_2(it_number, hm_symbol, origin2, hall_symbol, symmetry_items): + origin2_symops = _shift_origin(_tabulated_symops(it_number), origin2) + sites = _move_sites([GENERAL_POSITION, (0, 0, 0)], origin2) + available_items = { + "symops": origin2_symops, + "it_number": it_number, + "hm_name": hm_symbol + " :2", + "hall_name": hall_symbol, + } + crystal_system = get_space_group(it_number).crystal_system + cif_text = _make_cif(crystal_system, sites, **{item: available_items[item] for item in symmetry_items}) + expected_sites = _orbit(origin2_symops, sites) + actual_sites = _parse_sites(cif_text) + _assert_same_sites(actual_sites, expected_sites) + + +@pytest.mark.parametrize( + "hm_name, origin", + [ + # Test the spellings of the origin choice in the H-M symbol of a CIF + # that lists no symmetry operations and no IT number. The structure + # is diamond silicon, with 8 atoms per cell in either origin choice. + # C1: ":2" qualifier, expect origin choice 2 + # 1. CIF style after a space + pytest.param("F d -3 m :2", ("1/8", "1/8", "1/8"), id="colon-2"), + # 2. Joined to the symbol + pytest.param("F d -3 m:2", ("1/8", "1/8", "1/8"), id="colon-2-joined"), + # 3. On a symbol without spaces + pytest.param("Fd-3m:2", ("1/8", "1/8", "1/8"), id="colon-2-no-spaces"), + # C2: ICSD style "Z" qualifier, expect origin choice 2 + # 1. After a space + pytest.param("F d -3 m Z", ("1/8", "1/8", "1/8"), id="icsd-z"), + # 2. On a symbol without spaces + pytest.param("Fd-3mZ", ("1/8", "1/8", "1/8"), id="icsd-z-no-spaces"), + # C3: CIF style ":1" qualifier, expect origin choice 1 + pytest.param("F d -3 m :1", ("0", "0", "0"), id="colon-1"), + # C4: ICSD style "S" qualifier, expect origin choice 1 + pytest.param("F d -3 m S", ("0", "0", "0"), id="icsd-s"), + ], +) +def test_origin_choice_spelling(hm_name, origin): + symops = _shift_origin(_tabulated_symops(227), origin) + sites = _move_sites([(0, 0, 0)], origin) + cif_text = _make_cif("CUBIC", sites, hm_name=hm_name) + expected_sites = _orbit(symops, sites) + assert len(expected_sites) == 8 + actual_sites = _parse_sites(cif_text) + _assert_same_sites(actual_sites, expected_sites) + + +@pytest.mark.parametrize( + "symmetry_items", + [ + # Test a CIF that uses a space group with two origin choices but + # gives nothing that tells which origin it uses. + # C1: only a plain H-M symbol, expect the origin choice 1 expansion + # and a warning that tells the user how to ask for origin choice 2 + pytest.param(("hm_name",), id="hm-only"), + # C2: only an IT number, expect the same expansion and warning + pytest.param(("it_number",), id="number-only"), + # C3: IT number and plain H-M symbol, expect the same expansion and + # warning + pytest.param(("it_number", "hm_name"), id="number-hm"), + ], +) +@pytest.mark.parametrize( + "it_number, hm_symbol", + [ + # C1: one case per space group that has two origin choices, expect + # the origin choice 1 expansion and the warning + pytest.param(row[0], row[1], id=row[1].replace(" ", "")) + for row in TWO_ORIGIN_GROUPS + ], +) +def test_ambiguous_origin_warning(it_number, hm_symbol, symmetry_items): + origin1_symops = _tabulated_symops(it_number) + sites = [GENERAL_POSITION, (0, 0, 0)] + available_items = {"it_number": it_number, "hm_name": hm_symbol} + crystal_system = get_space_group(it_number).crystal_system + cif_text = _make_cif(crystal_system, sites, **{item: available_items[item] for item in symmetry_items}) + expected_sites = _orbit(origin1_symops, sites) + expected_warning = AMBIGUOUS_ORIGIN_WARNING.format(it_number=it_number) + with pytest.warns(UserWarning, match=AMBIGUOUS_ORIGIN_PATTERN) as warning_records: + actual_sites = _parse_sites(cif_text) + actual_warnings = [str(w.message) for w in warning_records if AMBIGUOUS_ORIGIN_PATTERN in str(w.message)] + assert actual_warnings == [expected_warning] + _assert_same_sites(actual_sites, expected_sites) + + +@pytest.mark.parametrize( + "it_number, cif_kwargs", + [ + # Test that the ambiguous origin warning is not raised when the CIF + # leaves no doubt about its origin. + # C1: space group with a single origin choice and a plain H-M symbol, + # expect no warning + pytest.param(225, {"it_number": 225, "hm_name": "F m -3 m"}, id="single-origin-group"), + # C2: two-origin group with all symmetry operations listed, expect no + # warning + pytest.param(227, {"symops": True, "it_number": 227, "hm_name": "F d -3 m"}, id="symops-listed"), + # C3: two-origin group with a ":2" qualifier on the H-M symbol, expect + # no warning + pytest.param(227, {"it_number": 227, "hm_name": "F d -3 m :2"}, id="origin-2-qualifier"), + # C4: two-origin group with a ":1" qualifier on the H-M symbol, expect + # no warning + pytest.param(227, {"it_number": 227, "hm_name": "F d -3 m :1"}, id="origin-1-qualifier"), + # C5: two-origin group with a Hall symbol, expect no warning + pytest.param(227, {"it_number": 227, "hall_name": "-F 4vw 2vw 3"}, id="hall-symbol"), + ], +) +def test_unambiguous_origin_no_warning(it_number, cif_kwargs): + cif_kwargs = dict(cif_kwargs) + if cif_kwargs.pop("symops", False): + cif_kwargs["symops"] = _tabulated_symops(it_number) + cif_text = _make_cif("CUBIC", [GENERAL_POSITION], **cif_kwargs) + with warnings.catch_warnings(record=True) as warning_records: + warnings.simplefilter("always") + _parse_sites(cif_text) + actual_warnings = [ + str(w.message) for w in warning_records if re.search(AMBIGUOUS_ORIGIN_PATTERN, str(w.message)) + ] + assert actual_warnings == [] + + +@pytest.mark.parametrize( + "symmetry_items, expected_multiplicities", + [ + # Test the pyrochlore from diffpy.pdfgui issue 291, a CIF in origin + # choice 2 of F d -3 m with Ho on 16d, Ti on 16c, O on 48f and O on 8b. + # C1: all operations listed with IT number 227 and ICSD style symbol, + # expect 88 sites with the Wyckoff multiplicities + pytest.param(("symops", "it_number", "hm_name"), [16, 16, 48, 8], id="symops-number-hm"), + # C2: no operations, IT number 227 and ICSD style symbol, expect the + # same multiplicities + pytest.param(("it_number", "hm_name"), [16, 16, 48, 8], id="number-hm"), + ], +) +def test_pyrochlore_origin_choice_2(symmetry_items, expected_multiplicities): + origin2_symops = _shift_origin(_tabulated_symops(227), TWO_ORIGIN_SHIFTS[227]) + sites = [(0.5, 0.5, 0.5), (0, 0, 0), (0.324, 0.125, 0.125), (0.375, 0.375, 0.375)] + available_items = {"symops": origin2_symops, "it_number": 227, "hm_name": "F d -3 m Z"} + cif_text = _make_cif("CUBIC", sites, **{item: available_items[item] for item in symmetry_items}) + parser = get_parser("cif") + parser.parse(cif_text) + assert parser.eau.multiplicity == expected_multiplicities + + +@pytest.mark.parametrize( + "it_number", + [ + # Test a CIF that lists all symmetry operations for an origin that is + # not a tabulated one, together with the IT number and H-M symbol that + # a CIF writer would add. Every space group except P1 changes its + # operations when the origin moves to (1/8, 1/8, 1/8). The asymmetric + # unit holds one general site and one site on the standard origin. + # C1: one case per space group 2 to 230, expect the sites generated + # by the operations listed in the file + pytest.param(number, id=f"sg-{number}") + for number in range(2, 231) + ], +) +def test_listed_symops_arbitrary_origin(it_number): + origin = ("1/8", "1/8", "1/8") + spacegroup = get_space_group(it_number) + symops = _shift_origin(_tabulated_symops(it_number), origin) + sites = _move_sites([GENERAL_POSITION, (0, 0, 0)], origin) + cif_text = _make_cif( + spacegroup.crystal_system, sites, symops=symops, it_number=it_number, hm_name=spacegroup.short_name + ) + expected_sites = _orbit(symops, sites) + actual_sites = _parse_sites(cif_text) + _assert_same_sites(actual_sites, expected_sites) + + +@pytest.mark.parametrize( + "symops, sites, expected_sites", + [ + # Test hand-written CIF files whose listed symmetry operations do not + # match a tabulated setting although their space group symbol does. + pytest.param( # C1: P 2 with the twofold axis moved to x = 1/4 and a general site, expect two sites + ["x,y,z", "1/2-x,y,-z"], + [(0.1, 0.2, 0.3)], + [(0.1, 0.2, 0.3), (0.4, 0.2, 0.7)], + id="p2-shifted-axis-general-site", + ), + pytest.param( # C2: the same with one site on the moved axis, from pull request 183, expect one site + ["x,y,z", "1/2-x,y,-z"], + [(0.25, 0, 0)], + [(0.25, 0, 0)], + id="p2-shifted-axis-special-site", + ), + pytest.param( # C3: P 2 described in a B-centered cell of twice the volume, expect four sites + ["x,y,z", "-x,y,-z", "x+1/2,y,z+1/2", "-x+1/2,y,-z+1/2"], + [(0.1, 0.2, 0.3)], + [(0.1, 0.2, 0.3), (0.9, 0.2, 0.7), (0.6, 0.2, 0.8), (0.4, 0.2, 0.2)], + id="p2-b-centered-cell", + ), + ], +) +def test_listed_symops_handwritten(symops, sites, expected_sites): + cif_text = _make_cif("MONOCLINIC", sites, it_number=3, hm_name="P 2") + symop_loop = "\n".join(["loop_", "_space_group_symop_operation_xyz", *(f"'{s}'" for s in symops)]) + cif_text = cif_text.replace("loop_", symop_loop + "\nloop_", 1) + actual_sites = _parse_sites(cif_text) + _assert_same_sites(actual_sites, _sorted_sites(expected_sites)) + + +@pytest.mark.parametrize( + "list_symops", + [ + # Test structures in polar space groups whose origin floats along the + # polar direction(s). Sliding the origin along such a direction does + # not change the symmetry operations, only the site coordinates. + # C1: all operations listed with IT number and H-M symbol, expect the + # sites generated by the operations + pytest.param(True, id="symops"), + # C2: the same without listed operations, expect the same sites + pytest.param(False, id="no-symops"), + ], +) +@pytest.mark.parametrize( + "it_number", + [ + # C1: one case per polar space group, expect the expansion not to + # depend on where the origin sits along the polar direction + pytest.param(number, id=f"sg-{number}") + for number in POLAR_GROUPS + ], +) +def test_floating_origin(it_number, list_symops): + spacegroup = get_space_group(it_number) + symops = _tabulated_symops(it_number) + origin = _polar_shift(symops) + assert numpy.any(origin) + sites = _move_sites([GENERAL_POSITION, (0, 0, 0)], origin) + cif_text = _make_cif( + spacegroup.crystal_system, + sites, + symops=symops if list_symops else None, + it_number=it_number, + hm_name=spacegroup.short_name, + ) + expected_sites = _orbit(symops, sites) + actual_sites = _parse_sites(cif_text) + _assert_same_sites(actual_sites, expected_sites)