Debian Codegraph @

tests/test_sdm.py

raw symbols SCIP
1 import unittest
2 import tempfile
3 from pathlib import Path
4 from unittest import TestCase
5 from unittest.mock import patch
6
7 from shelxfile.misc.misc import wrap_line
8 from shelxfile.shelx import sdm as sdm_module
9 from shelxfile.shelx.sdm import SDM, HAS_CPP
10 from shelxfile import Shelxfile
11
12
13 class TestPackUnitCell(TestCase):
14 """Tests for :meth:`SDM.pack_unit_cell` and :meth:`Shelxfile.pack`."""
15
16 RES_FILE = 'tests/resources/p21c.res'
17 RES_FILE_P31C = 'tests/resources/p-31c.res'
18
19 def _fresh_shx(self, path: str = None) -> Shelxfile:
20 shx = Shelxfile()
21 shx.read_file(path or self.RES_FILE)
22 return shx
23
24 # ------------------------------------------------------------------
25 # Basic correctness
26 # ------------------------------------------------------------------
27
28 def test_packed_nonempty(self):
29 """pack_unit_cell must return at least one atom."""
30 shx = self._fresh_shx()
31 sdm = SDM(shx)
32 packed = sdm.pack_unit_cell()
33 self.assertGreater(len(packed), 0)
34
35 def test_packed_larger_than_asymm(self):
36 """Packed unit cell must contain more atoms than the asymmetric unit."""
37 shx = self._fresh_shx()
38 asymm_count = len(shx.atoms.all_atoms)
39 sdm = SDM(shx)
40 packed = sdm.pack_unit_cell()
41 self.assertGreater(len(packed), asymm_count)
42
43 def test_all_coords_in_unit_cell(self):
44 """All fractional coordinates must be in [0, 1)."""
45 shx = self._fresh_shx()
46 sdm = SDM(shx)
47 for at in sdm.pack_unit_cell():
48 self.assertGreaterEqual(at.x, 0.0, f"{at.name}.x = {at.x}")
49 self.assertLess(at.x, 1.0, f"{at.name}.x = {at.x}")
50 self.assertGreaterEqual(at.y, 0.0, f"{at.name}.y = {at.y}")
51 self.assertLess(at.y, 1.0, f"{at.name}.y = {at.y}")
52 self.assertGreaterEqual(at.z, 0.0, f"{at.name}.z = {at.z}")
53 self.assertLess(at.z, 1.0, f"{at.name}.z = {at.z}")
54
55 def test_returns_atom_objects(self):
56 """pack_unit_cell must return Atom objects."""
57 from shelxfile.atoms.atom import Atom
58 shx = self._fresh_shx()
59 sdm = SDM(shx)
60 packed = sdm.pack_unit_cell()
61 for at in packed:
62 self.assertIsInstance(at, Atom)
63
64 def test_no_qpeaks_by_default(self):
65 """Q-peaks must be excluded unless with_qpeaks=True."""
66 shx = self._fresh_shx()
67 sdm = SDM(shx)
68 packed = sdm.pack_unit_cell(with_qpeaks=False)
69 self.assertFalse(any(at.qpeak for at in packed))
70
71 def test_with_qpeaks(self):
72 """with_qpeaks=True must include Q-peaks when the structure has them."""
73 shx = self._fresh_shx()
74 sdm = SDM(shx)
75 packed_no_q = sdm.pack_unit_cell(with_qpeaks=False)
76 packed_with_q = sdm.pack_unit_cell(with_qpeaks=True)
77 # p21c.res may or may not have Q-peaks; the with_q count must be >= without_q
78 self.assertGreaterEqual(len(packed_with_q), len(packed_no_q))
79
80 # ------------------------------------------------------------------
81 # Symmetry-operation selection
82 # ------------------------------------------------------------------
83
84 def test_identity_only_gives_asymm_unit(self):
85 """Selecting only the identity (index 0) must give one atom per asymm-unit atom."""
86 shx = self._fresh_shx()
87 asymm = [at for at in shx.atoms.all_atoms if not at.qpeak]
88 sdm = SDM(shx)
89 packed = sdm.pack_unit_cell(symmop_indices=[0])
90 self.assertEqual(len(packed), len(asymm))
91
92 def test_symmop_indices_none_uses_all_ops(self):
93 """None (default) must apply all symmetry operations."""
94 shx = self._fresh_shx()
95 sdm = SDM(shx)
96 sdm._build_symm_arrays()
97 packed_all = sdm.pack_unit_cell(symmop_indices=None)
98 packed_sel = sdm.pack_unit_cell(symmop_indices=list(range(len(sdm._symm_m))))
99 self.assertEqual(len(packed_all), len(packed_sel))
100
101 # ------------------------------------------------------------------
102 # Before calc_sdm
103 # ------------------------------------------------------------------
104
105 def test_usable_without_calc_sdm(self):
106 """pack_unit_cell must work on a fresh SDM that has not run calc_sdm."""
107 shx = self._fresh_shx()
108 sdm = SDM(shx)
109 # Do NOT call calc_sdm; pack_unit_cell must still work
110 packed = sdm.pack_unit_cell()
111 self.assertGreater(len(packed), 0)
112
113 # ------------------------------------------------------------------
114 # Duplicate elimination
115 # ------------------------------------------------------------------
116
117 def test_no_duplicate_positions(self):
118 """No two atoms must share the same position within the tolerance."""
119 shx = self._fresh_shx()
120 sdm = SDM(shx)
121 packed = sdm.pack_unit_cell(cart_tolerance=0.2)
122 coords = [(round(at.x, 4), round(at.y, 4), round(at.z, 4)) for at in packed]
123 self.assertEqual(len(coords), len(set(coords)),
124 "Duplicate fractional positions found in packed unit cell")
125
126 # ------------------------------------------------------------------
127 # Shelxfile.pack() high-level API
128 # ------------------------------------------------------------------
129
130 def test_shelxfile_pack_matches_sdm_pack(self):
131 """`Shelxfile.pack()` and `SDM.pack_unit_cell()` must give the same count."""
132 shx1 = self._fresh_shx()
133 shx2 = self._fresh_shx()
134 direct = SDM(shx1).pack_unit_cell()
135 via_api = shx2.pack()
136 self.assertEqual(len(direct), len(via_api))
137
138 def test_shelxfile_pack_returns_list(self):
139 """`Shelxfile.pack()` must return a list."""
140 shx = self._fresh_shx()
141 self.assertIsInstance(shx.pack(), list)
142
143 # ------------------------------------------------------------------
144 # P-31c (different space group)
145 # ------------------------------------------------------------------
146
147 def test_p31c_packed_count(self):
148 """P-31c structure must produce a non-trivial packed unit cell."""
149 shx = self._fresh_shx(self.RES_FILE_P31C)
150 sdm = SDM(shx)
151 packed = sdm.pack_unit_cell()
152 self.assertGreater(len(packed), len(shx.atoms.all_atoms))
153
154
155 class MySDMtest(TestCase):
156 def setUp(self) -> None:
157 self.maxDiff = None
158 self.head = """
159 REM Solution 1 R1 0.081, Alpha = 0.0146 in P31c
160 REM Flack x = -0.072 ( 0.041 ) from Parsons' quotients
161 REM C19.667 N2.667 P4
162 TITL p-31c-neu in P-31c
163 CELL 0.71073 12.5067 12.5067 24.5615 90.000 90.000 120.000
164 ZERR 2 0.0043 0.0043 0.0085 0.000 0.000 0.000
165 LATT -1
166 SFAC C H N P Cl
167 UNIT 120 186 14 12 12
168 TEMP -173.000
169 OMIT 0 0 2
170 L.S. 10
171 BOND $H
172 ACTA
173 CONF
174
175 LIST 4
176 FMAP 2
177 PLAN 40
178 WGHT 0.034600 0.643600
179 FVAR 0.22604 0.76052 0.85152\n"""
180
181 self.tail = """\n
182 HKLF 4
183
184 REM p-31c-neu in P-31c
185 REM R1 = 0.0308 for 4999 Fo > 4sig(Fo) and 0.0343 for all 5352 data
186 REM 287 parameters refined using 365 restraints
187
188 END
189
190 WGHT 0.0348 0.6278
191 """
192
193 def test_SDM(self):
194 shx = Shelxfile()
195 shx.read_file('tests/resources/p-31c.res')
196 sdm = SDM(shx)
197 needsymm = sdm.calc_sdm()
198 packed_atoms = sdm.packer(sdm, needsymm)
199 # print(needsymm)
200 # [[8, 5, 5, 5, 1], [16, 5, 5, 5, 1], [7, 4, 5, 5, 3]]
201 # print(len(shx.atoms))
202 # print(len(packed_atoms))
203
204 for at in packed_atoms:
205 if at.qpeak:
206 continue
207 # print(wrap_line(str(at)))
208 self.head += wrap_line(str(at)) + '\n'
209 self.head += self.tail
210 p = Path('tests/resources/test-sdm1.res')
211 print('Zeit für sdm:', round(sdm.sdmtime, 3), 's')
212 self.assertEqual(p.read_text(), self.head)
213 # print(sdm.bondlist)
214 # print(len(sdm.bondlist), '(170) Atome in p-31c.res, (208) in I-43d.res')
215
216 def test_vector_length(self):
217 shx = Shelxfile()
218 shx.read_string(self.head + self.tail)
219 sdm = SDM(shx)
220 self.assertEqual(7.343581289102655, sdm.vector_length(-0.3665069999999999, 0.293439, -0.06597900000000001))
221
222 def test_grown_atom_names_are_legal(self):
223 """Symmetry-generated atoms returned by packer() must have legal SHELXL names."""
224 import re
225 legal = re.compile(r'^[A-Za-z][A-Za-z0-9]{0,3}$')
226 shx = Shelxfile()
227 shx.read_file('tests/resources/p-31c.res')
228 sdm = SDM(shx)
229 needsymm = sdm.calc_sdm()
230 packed_atoms = sdm.packer(sdm, needsymm)
231 for at in packed_atoms:
232 if at.symmgen: # only check atoms created by the packer
233 self.assertRegex(at.name, legal,
234 f"Atom name '{at.name}' is not a legal SHELXL name")
235
236 def test_grown_atom_names_are_unique(self):
237 """Every atom returned by packer() must have a unique name."""
238 shx = Shelxfile()
239 shx.read_file('tests/resources/p-31c.res')
240 sdm = SDM(shx)
241 needsymm = sdm.calc_sdm()
242 packed_atoms = sdm.packer(sdm, needsymm)
243 names = [at.name.upper() for at in packed_atoms]
244 self.assertEqual(len(names), len(set(names)),
245 "Duplicate atom names found in packer() output")
246
247 def test_pack_unit_cell_names_are_legal(self):
248 """Symmetry-generated atoms from pack_unit_cell() must have legal SHELXL names."""
249 import re
250 legal = re.compile(r'^[A-Za-z][A-Za-z0-9]{0,3}$')
251 shx = Shelxfile()
252 shx.read_file('tests/resources/p-31c.res')
253 sdm = SDM(shx)
254 for at in sdm.pack_unit_cell():
255 if at.symmgen: # only check atoms created by the packer
256 self.assertRegex(at.name, legal,
257 f"Atom name '{at.name}' is not a legal SHELXL name")
258
259 def test_pack_unit_cell_names_are_unique(self):
260 """Every atom returned by pack_unit_cell() must have a unique name."""
261 shx = Shelxfile()
262 shx.read_file('tests/resources/p-31c.res')
263 sdm = SDM(shx)
264 names = [at.name.upper() for at in sdm.pack_unit_cell()]
265 self.assertEqual(len(names), len(set(names)),
266 "Duplicate atom names found in pack_unit_cell() output")
267
268 class TestSDMCpp(TestCase):
269 """Tests for the C++ SDM acceleration (sdm_cpp).
270
271 Each test runs both the C++ and the pure-Python paths on the same
272 structure and asserts they produce identical results. Tests are
273 unconditional: when sdm_cpp is not installed the test verifies that the
274 Python fallback still produces correct output.
275 """
276
277 RES_FILE = 'tests/resources/p-31c.res'
278
279 # ------------------------------------------------------------------
280 # helpers
281 # ------------------------------------------------------------------
282
283 def _run_sdm(self, shx: Shelxfile, use_cpp: bool) -> tuple[list, list, int]:
284 """Run calc_sdm() with the requested backend, return (sdm_list, need_symm, maxmol)."""
285 with patch.object(sdm_module, 'HAS_CPP', use_cpp):
286 s = SDM(shx)
287 need_symm = s.calc_sdm()
288 return s.sdm_list, need_symm, s.maxmol
289
290 def _fresh_shx(self) -> Shelxfile:
291 shx = Shelxfile()
292 shx.read_file(self.RES_FILE)
293 return shx
294
295 # ------------------------------------------------------------------
296 # availability
297 # ------------------------------------------------------------------
298
299 def test_has_cpp_flag_is_bool(self):
300 """HAS_CPP must be a plain bool."""
301 self.assertIsInstance(HAS_CPP, bool)
302
303 @unittest.skipUnless(HAS_CPP, 'sdm_cpp extension not available')
304 def test_cpp_module_has_openmp_attr(self):
305 """sdm_cpp must expose a has_openmp attribute."""
306 import sdm_cpp
307 self.assertIsInstance(sdm_cpp.has_openmp, bool)
308
309 # ------------------------------------------------------------------
310 # C++ path functional tests
311 # ------------------------------------------------------------------
312
313 @unittest.skipUnless(HAS_CPP, 'sdm_cpp extension not available')
314 def test_cpp_sdm_list_nonempty(self):
315 """The C++ path should find at least one atom pair."""
316 sdm_list, _, _ = self._run_sdm(self._fresh_shx(), use_cpp=True)
317 self.assertGreater(len(sdm_list), 0)
318
319 @unittest.skipUnless(HAS_CPP, 'sdm_cpp extension not available')
320 def test_cpp_molindex_assigned(self):
321 """calc_sdm via C++ must assign a molindex to every atom."""
322 shx = self._fresh_shx()
323 with patch.object(sdm_module, 'HAS_CPP', True):
324 s = SDM(shx)
325 s.calc_sdm()
326 for at in shx.atoms.all_atoms:
327 self.assertGreater(at.molindex, 0, f"{at.name} has molindex {at.molindex}")
328
329 @unittest.skipUnless(HAS_CPP, 'sdm_cpp extension not available')
330 def test_cpp_maxmol_positive(self):
331 """At least one molecule must be found."""
332 _, _, maxmol = self._run_sdm(self._fresh_shx(), use_cpp=True)
333 self.assertGreater(maxmol, 0)
334
335 # ------------------------------------------------------------------
336 # C++ vs Python equivalence
337 # ------------------------------------------------------------------
338
339 @unittest.skipUnless(HAS_CPP, 'sdm_cpp extension not available')
340 def test_cpp_and_python_same_pair_count(self):
341 """C++ and Python SDM must find the same number of atom pairs."""
342 cpp_list, _, _ = self._run_sdm(self._fresh_shx(), use_cpp=True)
343 py_list, _, _ = self._run_sdm(self._fresh_shx(), use_cpp=False)
344 self.assertEqual(len(cpp_list), len(py_list))
345
346 @unittest.skipUnless(HAS_CPP, 'sdm_cpp extension not available')
347 def test_cpp_and_python_same_maxmol(self):
348 """C++ and Python SDM must identify the same number of molecular fragments."""
349 _, _, cpp_maxmol = self._run_sdm(self._fresh_shx(), use_cpp=True)
350 _, _, py_maxmol = self._run_sdm(self._fresh_shx(), use_cpp=False)
351 self.assertEqual(cpp_maxmol, py_maxmol)
352
353 @unittest.skipUnless(HAS_CPP, 'sdm_cpp extension not available')
354 def test_cpp_and_python_same_need_symm(self):
355 """C++ and Python SDM must return the same symmetry operations needed for packing."""
356 _, cpp_ns, _ = self._run_sdm(self._fresh_shx(), use_cpp=True)
357 _, py_ns, _ = self._run_sdm(self._fresh_shx(), use_cpp=False)
358 self.assertEqual(sorted(cpp_ns), sorted(py_ns))
359
360 @unittest.skipUnless(HAS_CPP, 'sdm_cpp extension not available')
361 def test_cpp_and_python_same_covalent_count(self):
362 """C++ and Python paths must agree on the number of covalent bonds."""
363 cpp_list, _, _ = self._run_sdm(self._fresh_shx(), use_cpp=True)
364 py_list, _, _ = self._run_sdm(self._fresh_shx(), use_cpp=False)
365 cpp_cov = sum(1 for x in cpp_list if x.covalent)
366 py_cov = sum(1 for x in py_list if x.covalent)
367 self.assertEqual(cpp_cov, py_cov)
368
369 @unittest.skipUnless(HAS_CPP, 'sdm_cpp extension not available')
370 def test_cpp_and_python_distances_match(self):
371 """Shortest distances from C++ and Python must agree to 6 decimal places."""
372 cpp_list, _, _ = self._run_sdm(self._fresh_shx(), use_cpp=True)
373 py_list, _, _ = self._run_sdm(self._fresh_shx(), use_cpp=False)
374 for cpp_item, py_item in zip(cpp_list, py_list):
375 self.assertAlmostEqual(cpp_item.dist, py_item.dist, places=6,
376 msg=f"Distance mismatch for pair ({cpp_item.a1}, {cpp_item.a2})")
377
378 @unittest.skipUnless(HAS_CPP, 'sdm_cpp extension not available')
379 def test_cpp_packer_same_atom_count_as_python(self):
380 """Packed structures from C++ and Python backends must have the same atom count."""
381 shx_cpp = self._fresh_shx()
382 shx_py = self._fresh_shx()
383 with patch.object(sdm_module, 'HAS_CPP', True):
384 s_cpp = SDM(shx_cpp)
385 ns_cpp = s_cpp.calc_sdm()
386 packed_cpp = s_cpp.packer(s_cpp, ns_cpp)
387
388 with patch.object(sdm_module, 'HAS_CPP', False):
389 s_py = SDM(shx_py)
390 ns_py = s_py.calc_sdm()
391 packed_py = s_py.packer(s_py, ns_py)
392
393 self.assertEqual(len(packed_cpp), len(packed_py))
394
395 # ------------------------------------------------------------------
396 # Python fallback (always runs, regardless of HAS_CPP)
397 # ------------------------------------------------------------------
398
399 def test_python_fallback_sdm_list_nonempty(self):
400 """The pure-Python fallback must also find atom pairs."""
401 sdm_list, _, _ = self._run_sdm(self._fresh_shx(), use_cpp=False)
402 self.assertGreater(len(sdm_list), 0)
403
404 def test_python_fallback_maxmol_positive(self):
405 """The pure-Python fallback must identify at least one molecule."""
406 _, _, maxmol = self._run_sdm(self._fresh_shx(), use_cpp=False)
407 self.assertGreater(maxmol, 0)
408
409 def test_python_fallback_need_symm(self):
410 """The pure-Python fallback must return a non-empty symmetry list for p-31c."""
411 _, need_symm, _ = self._run_sdm(self._fresh_shx(), use_cpp=False)
412 self.assertGreater(len(need_symm), 0)
413
414
415 class TestWriteGrownFile(TestCase):
416 """Tests for :meth:`Shelxfile.write_grown_file`."""
417
418 RES_FILE = 'tests/resources/p-31c.res'
419
420 def _fresh_shx(self) -> Shelxfile:
421 shx = Shelxfile()
422 shx.read_file(self.RES_FILE)
423 return shx
424
425 def test_write_grown_file_creates_file(self):
426 """write_grown_file must create a non-empty output file."""
427 shx = self._fresh_shx()
428 with tempfile.NamedTemporaryFile(suffix='.res', delete=False) as f:
429 out = Path(f.name)
430 try:
431 shx.write_grown_file(out)
432 self.assertTrue(out.exists())
433 self.assertGreater(out.stat().st_size, 0)
434 finally:
435 out.unlink(missing_ok=True)
436
437 def test_grown_file_has_p1_symmetry(self):
438 """The grown file must have LATT -1 and no SYMM cards."""
439 shx = self._fresh_shx()
440 with tempfile.NamedTemporaryFile(suffix='.res', delete=False) as f:
441 out = Path(f.name)
442 try:
443 shx.write_grown_file(out)
444 text = out.read_text()
445 lines = text.splitlines()
446 latt_lines = [l for l in lines if l.strip().upper().startswith('LATT')]
447 symm_lines = [l for l in lines if l.strip().upper().startswith('SYMM')]
448 self.assertEqual(len(latt_lines), 1, "Expected exactly one LATT line")
449 self.assertIn('-1', latt_lines[0], "LATT must be -1 for P1 symmetry")
450 self.assertEqual(len(symm_lines), 0, "Grown file must have no SYMM cards")
451 finally:
452 out.unlink(missing_ok=True)
453
454 def test_grown_file_has_warning_comment(self):
455 """The grown file must contain a REM warning about refinement."""
456 shx = self._fresh_shx()
457 with tempfile.NamedTemporaryFile(suffix='.res', delete=False) as f:
458 out = Path(f.name)
459 try:
460 shx.write_grown_file(out)
461 text = out.read_text().upper()
462 self.assertIn('NOT SUITED FOR REFINEMENT', text,
463 "Grown file must warn that it is not suited for refinement")
464 finally:
465 out.unlink(missing_ok=True)
466
467 def test_grown_file_has_part_cards(self):
468 """Disorder parts must be preserved via PART cards in the grown file."""
469 shx = self._fresh_shx()
470 with tempfile.NamedTemporaryFile(suffix='.res', delete=False) as f:
471 out = Path(f.name)
472 try:
473 shx.write_grown_file(out)
474 text = out.read_text()
475 lines = text.splitlines()
476 part_lines = [l for l in lines if l.strip().upper().startswith('PART ')]
477 # p-31c.res has PART 1 / PART 2 disorder groups, repeated for each
478 # symmetry copy, so there must be several PART cards
479 self.assertGreater(len(part_lines), 0, "Grown file must contain PART cards")
480 # Check that both non-zero parts and the closing PART 0 are present
481 part_values = {l.strip().split()[1] for l in part_lines}
482 self.assertIn('1', part_values, "PART 1 must appear")
483 self.assertIn('2', part_values, "PART 2 must appear")
484 self.assertIn('0', part_values, "PART 0 (close disorder) must appear")
485 finally:
486 out.unlink(missing_ok=True)
487
488 def test_grown_file_correct_atom_count(self):
489 """The grown file must contain the same number of atoms as grow() returns."""
490 shx = self._fresh_shx()
491 grown = shx.grow()
492 real_grown = [a for a in grown if not a.qpeak]
493 with tempfile.NamedTemporaryFile(suffix='.res', delete=False) as f:
494 out = Path(f.name)
495 try:
496 shx.write_grown_file(out)
497 # Exclude SHELXL comment lines ("!..." at start of first token)
498 atom_lines = [
499 l for l in out.read_text().splitlines()
500 if Shelxfile.is_atom(l) and not l.lstrip().startswith('!')
501 ]
502 self.assertEqual(len(atom_lines), len(real_grown))
503 finally:
504 out.unlink(missing_ok=True)
505
506 def test_grown_file_no_original_symm_cards(self):
507 """The original SYMM cards from p-31c must not appear in the grown file."""
508 shx = self._fresh_shx()
509 with tempfile.NamedTemporaryFile(suffix='.res', delete=False) as f:
510 out = Path(f.name)
511 try:
512 shx.write_grown_file(out)
513 text = out.read_text()
514 # p-31c has "-Y, X-Y, Z" as first SYMM line — it must not appear
515 self.assertNotIn('-Y, X-Y, Z', text,
516 "Original SYMM cards must be absent in grown file")
517 finally:
518 out.unlink(missing_ok=True)
519
520 def test_grown_file_no_include_references(self):
521 """Include-file (+filename) lines must not appear in the grown file."""
522 shx = self._fresh_shx()
523 with tempfile.NamedTemporaryFile(suffix='.res', delete=False) as f:
524 out = Path(f.name)
525 try:
526 shx.write_grown_file(out)
527 text = out.read_text()
528 include_lines = [l for l in text.splitlines() if l.startswith('+')]
529 self.assertEqual(include_lines, [],
530 "Include-file references must be absent in grown file")
531 finally:
532 out.unlink(missing_ok=True)
533
534 def test_grown_file_accepts_string_path(self):
535 """write_grown_file must also accept a plain string as the filename."""
536 shx = self._fresh_shx()
537 with tempfile.NamedTemporaryFile(suffix='.res', delete=False) as f:
538 out = f.name # plain string
539 try:
540 shx.write_grown_file(out) # must not raise
541 self.assertGreater(Path(out).stat().st_size, 0)
542 finally:
543 Path(out).unlink(missing_ok=True)
544