Debian Codegraph @

tests/test_shelx.py

raw symbols SCIP
1 import tempfile
2 from pathlib import Path
3 from unittest import TestCase
4
5 from shelxfile import Shelxfile
6 from shelxfile.atoms.atom import Atom
7 from shelxfile.shelx.cards import HKLF
8
9
10 class TestShelxFileIsAtom(TestCase):
11
12 def test_is_atom_long_line_true(self):
13 """
14 """
15 is_an_atom = Shelxfile.is_atom(atomline='O1 3 0.120080 0.336659 0.494426 11.00000 0.01445 ...')
16 self.assertEqual(True, is_an_atom)
17
18 def test_is_no_atoms_because_type_is_missing(self):
19 is_an_atom = Shelxfile.is_atom(atomline='O1 0.120080 0.336659 0.494426 11.00000 0.01445 ...')
20 self.assertEqual(False, is_an_atom)
21
22 def test_is_no_atom_because_coordinate_is_missing(self):
23 is_an_atom = Shelxfile.is_atom(atomline='O1 4 0.120080 0.494426 11.00000 0.01445 ...')
24 self.assertEqual(False, is_an_atom)
25
26 def test_is_no_atom_because_its_a_command(self):
27 is_atom = Shelxfile.is_atom("AFIX 123")
28 self.assertEqual(False, is_atom)
29
30 def test_is_no_atom_because_its_a_command2(self):
31 is_atom = Shelxfile.is_atom("AFIX")
32 self.assertEqual(False, is_atom)
33
34 def test_is_an_atom_short(self):
35 is_atom = Shelxfile.is_atom('O1 3 0.120080 0.336659 0.494426')
36 self.assertEqual(True, is_atom)
37
38
39 class TestShelxfileElementToSfac(TestCase):
40 """
41 SFAC C H O F Al Ga
42 """
43
44 def setUp(self) -> None:
45 self.shx = Shelxfile(debug=True)
46 self.shx.read_file('tests/resources/p21c.res')
47
48 def test_elem2sfac_oxygen(self):
49 self.assertEqual(3, self.shx.elem2sfac('O'))
50
51 def test_elem2sfac_carbon(self):
52 self.assertEqual(1, self.shx.elem2sfac('c'))
53
54 def test_elem2sfac_Argon(self):
55 self.assertEqual(0, self.shx.elem2sfac('Ar'))
56
57
58 class TestShelxfile(TestCase):
59
60 def setUp(self) -> None:
61 self.shx = Shelxfile(debug=True)
62 self.shx.read_file('tests/resources/p21c.res')
63
64 def test_sfac2elem_C(self):
65 self.assertEqual('C', self.shx.sfac2elem(1))
66
67 def test_sfac2elem_H(self):
68 self.assertEqual('H', self.shx.sfac2elem(2))
69
70 def test_sfac2elem_O(self):
71 self.assertEqual('O', self.shx.sfac2elem(3))
72
73 def test_sfac2elem_Al(self):
74 self.assertEqual('Al', self.shx.sfac2elem(5))
75
76 def test_sfac2elem_not_existent(self):
77 self.assertEqual('', self.shx.sfac2elem(8))
78
79 def test_sfac2elem_zero(self):
80 self.assertEqual('', self.shx.sfac2elem(0))
81
82 def test_sum_formula(self):
83 self.assertEqual('C0.25 H0.5 O0.75 F1 AL1.25 GA1.5', self.shx.sum_formula)
84
85 def test_read_file_to_list(self):
86 shx = Shelxfile()
87 shx._reslist = ['Foo']
88 shx.read_file('tests/resources/p21c.res')
89 # Make sure read_file() re-initializes the constructor:
90 self.assertEqual(['TITL p21c in P2(1)/c',
91 ' created by SHELXL-2018/3 at 16:18:25 on 03-May-2018',
92 'CELL 0.71073 10.5086 20.9035 20.5072 90 94.13 90',
93 'ZERR 4 0.0003 0.0005 0.0005 0 0.001 0',
94 'LATT 1'],
95 [str(x) for x in shx._reslist[:5]])
96
97 def test_read_string(self):
98 self.shx.atoms = 'Foo'
99 # Make sure read_string re-initializes the constructor:
100 self.shx.read_string(Path('tests/resources/p21c.res').read_text(encoding='latin1'))
101 assert self.shx.atoms.number == 148
102
103 def test_read_file(self):
104 shx = Shelxfile()
105 with self.assertRaises(FileNotFoundError):
106 shx.read_file('tests/resources/foobar.res')
107
108
109 class TestShelxfileGoodModel(TestCase):
110
111 def setUp(self) -> None:
112 self.shx = Shelxfile()
113 self.shx.read_file('tests/resources/model_finished/p21c.res')
114
115 def test_atom_representation(self):
116 a = self.shx._reslist[39]
117 self.assertEqual(
118 'C1 1 -0.187504 0.282782 0.527531 11.00000 0.01807 0.02353 0.01797 0.00008 -0.00179 0.00036',
119 str(a))
120
121 def test_atom_object(self):
122 a = self.shx._reslist[39]
123 self.assertEqual(
124 'C1 1 -0.187504 0.282782 0.527531 11.00000 0.01807 0.02353 0.01797 0.00008 -0.00179 0.00036',
125 a)
126
127 def test_qpeak(self):
128 a = self.shx._reslist[-20]
129 self.assertEqual('Q1 1 0.0784 0.1310 0.6428 11.00000 0.04 0.10 ', str(a))
130
131 def test_r1(self):
132 assert self.shx.R1 == 0.194
133
134 def test_wr2(self):
135 assert self.shx.wr2 == 0.51
136
137 def test_data(self):
138 assert self.shx.data == 10786
139
140 def test_param(self):
141 assert self.shx.parameters == 551
142
143 def test_data_to_param(self):
144 assert round(self.shx.dat_to_param, 4) == 19.5753
145
146 def test_num_restraints(self):
147 assert self.shx.num_restraints == 0
148
149 def test_peak_hole(self):
150 assert self.shx.highest_peak == 6.395
151 assert self.shx.deepest_hole == -5.556
152
153 def test_peak_goof(self):
154 assert self.shx.goof == 5.982
155 assert self.shx.rgoof == 5.982
156
157
158 class TestWriteFile(TestCase):
159 def setUp(self) -> None:
160 self.shx = Shelxfile()
161 self.shx.read_file('tests/resources/2240189.res')
162 self.written = Path('tests/resources/2240189-written.res')
163 self.testwritepath = Path('tests/resources/testwrite.res')
164
165 def tearDown(self) -> None:
166 self.testwritepath.unlink(missing_ok=True)
167
168 def test_write_shelx_file(self):
169 self.shx.write_shelx_file(str(self.testwritepath))
170 self.assertEqual(self.written.read_bytes(), self.testwritepath.read_bytes())
171
172
173 # ---------------------------------------------------------------------------
174 # Tests for the improved add_atom / unused_atom_name interface
175 # ---------------------------------------------------------------------------
176
177 class TestAddAtom(TestCase):
178 """Tests for Shelxfile.add_atom() and Shelxfile.unused_atom_name()."""
179
180 def setUp(self) -> None:
181 self.shx = Shelxfile()
182 self.shx.read_file('tests/resources/p21c.res')
183
184 # ------------------------------------------------------------------
185 # Basic insertion
186 # ------------------------------------------------------------------
187
188 def test_add_atom_returns_atom_object(self):
189 a = self.shx.add_atom(name='C99', coordinates=[0.1, 0.2, 0.3])
190 self.assertIsInstance(a, Atom)
191
192 def test_add_atom_appears_in_atoms_list(self):
193 count_before = len(self.shx.atoms)
194 self.shx.add_atom(name='C99', coordinates=[0.1, 0.2, 0.3])
195 self.assertEqual(count_before + 1, len(self.shx.atoms))
196
197 def test_add_atom_lookup_by_name(self):
198 self.shx.add_atom(name='C99', coordinates=[0.1, 0.2, 0.3])
199 found = self.shx.atoms.get_atom_by_name('C99')
200 self.assertIsNotNone(found)
201 self.assertEqual('C99', found.name)
202
203 # ------------------------------------------------------------------
204 # _reslist position: must NOT overwrite TITL (index 0)
205 # ------------------------------------------------------------------
206
207 def test_add_atom_does_not_corrupt_reslist_index_0(self):
208 self.shx.add_atom(name='C99', coordinates=[0.1, 0.2, 0.3])
209 first = str(self.shx._reslist[0])
210 self.assertIn('TITL', first.upper())
211
212 def test_add_atom_placed_before_hklf(self):
213 self.shx.add_atom(name='C99', coordinates=[0.1, 0.2, 0.3])
214 atom_idx = self.shx._reslist.index(self.shx.atoms.get_atom_by_name('C99'))
215 hklf_idx = next(i for i, x in enumerate(self.shx._reslist) if isinstance(x, HKLF))
216 self.assertLess(atom_idx, hklf_idx)
217
218 def test_add_atom_placed_after_last_real_atom(self):
219 # The last non-Q-peak atom before adding:
220 existing_atoms = [x for x in self.shx._reslist if isinstance(x, Atom) and not x.qpeak]
221 last_existing_pos = self.shx._reslist.index(existing_atoms[-1])
222 self.shx.add_atom(name='C99', coordinates=[0.1, 0.2, 0.3])
223 new_atom_pos = self.shx._reslist.index(self.shx.atoms.get_atom_by_name('C99'))
224 self.assertGreater(new_atom_pos, last_existing_pos)
225
226 # ------------------------------------------------------------------
227 # after= parameter
228 # ------------------------------------------------------------------
229
230 def test_add_atom_after_specific_atom(self):
231 anchor = self.shx.atoms.get_atom_by_name('C1')
232 anchor_pos = self.shx._reslist.index(anchor)
233 self.shx.add_atom(name='C99', coordinates=[0.1, 0.2, 0.3], after=anchor)
234 new_pos = self.shx._reslist.index(self.shx.atoms.get_atom_by_name('C99'))
235 self.assertEqual(anchor_pos + 1, new_pos)
236
237 # ------------------------------------------------------------------
238 # uvals handling
239 # ------------------------------------------------------------------
240
241 def test_add_atom_uvals_default_isotropic(self):
242 a = self.shx.add_atom(name='C99', coordinates=[0.1, 0.2, 0.3])
243 self.assertEqual([0.04, 0.0, 0.0, 0.0, 0.0, 0.0], a.uvals)
244
245 def test_add_atom_uvals_single_value_expanded(self):
246 a = self.shx.add_atom(name='C99', coordinates=[0.1, 0.2, 0.3], uvals=[0.05])
247 self.assertEqual([0.05, 0.0, 0.0, 0.0, 0.0, 0.0], a.uvals)
248
249 def test_add_atom_uvals_anisotropic(self):
250 uvals = [0.03, 0.04, 0.05, 0.001, 0.002, 0.003]
251 a = self.shx.add_atom(name='C99', coordinates=[0.1, 0.2, 0.3], uvals=uvals)
252 self.assertEqual(uvals, a.uvals)
253
254 # ------------------------------------------------------------------
255 # symmgen flag
256 # ------------------------------------------------------------------
257
258 def test_add_atom_not_symmgen(self):
259 a = self.shx.add_atom(name='C99', coordinates=[0.1, 0.2, 0.3])
260 self.assertFalse(a.symmgen)
261
262 # ------------------------------------------------------------------
263 # Element auto-registration
264 # ------------------------------------------------------------------
265
266 def test_add_atom_known_element_carbon(self):
267 a = self.shx.add_atom(name='C99', coordinates=[0.1, 0.2, 0.3], element='C')
268 self.assertEqual('C', a.element)
269
270 def test_add_atom_new_element_auto_added_to_sfac(self):
271 # 'Xe' is not in p21c.res SFAC table
272 self.assertFalse(self.shx.sfac_table.has_element('Xe'))
273 self.shx.add_atom(name='XE1', coordinates=[0.1, 0.2, 0.3], element='Xe')
274 self.assertTrue(self.shx.sfac_table.has_element('Xe'))
275
276 def test_add_atom_new_element_sfac_num_nonzero(self):
277 a = self.shx.add_atom(name='XE1', coordinates=[0.1, 0.2, 0.3], element='Xe')
278 self.assertGreater(a.sfac_num, 0)
279 self.assertEqual('Xe', a.element)
280
281 # ------------------------------------------------------------------
282 # Duplicate name validation
283 # ------------------------------------------------------------------
284
285 def test_add_atom_duplicate_name_raises(self):
286 self.shx.add_atom(name='C99', coordinates=[0.1, 0.2, 0.3])
287 with self.assertRaises(ValueError):
288 self.shx.add_atom(name='C99', coordinates=[0.2, 0.3, 0.4])
289
290 # ------------------------------------------------------------------
291 # Cartesian coordinates
292 # ------------------------------------------------------------------
293
294 def test_add_atom_cartesian_coords(self):
295 # Provide a clearly non-fractional Cartesian point; the atom should land in _reslist
296 a = self.shx.add_atom(name='C99', coordinates=[1.0, 2.0, 3.0], coords_are_cartesian=True)
297 # Fractional coords must all be in a sane range (not equal to 1.0/2.0/3.0 directly)
298 self.assertFalse(a.x == 1.0 and a.y == 2.0 and a.z == 3.0)
299
300 # ------------------------------------------------------------------
301 # PART and SOF
302 # ------------------------------------------------------------------
303
304 def test_add_atom_with_part(self):
305 a = self.shx.add_atom(name='C99', coordinates=[0.5, 0.5, 0.5], part=1, sof=21.0)
306 self.assertEqual(1, a.part.n)
307 self.assertEqual(21.0, a.sof)
308
309 def test_add_atom_occupancy_parameter(self):
310 """occupancy=0.5 with default fvar=1 → sof=10.5"""
311 a = self.shx.add_atom(name='C99', coordinates=[0.1, 0.2, 0.3], occupancy=0.5)
312 self.assertAlmostEqual(10.5, a.sof)
313
314 def test_add_atom_occupancy_with_fvar(self):
315 """occupancy=1.0, fvar=2 → sof=21.0"""
316 a = self.shx.add_atom(name='C99', coordinates=[0.1, 0.2, 0.3],
317 occupancy=1.0, fvar=2)
318 self.assertAlmostEqual(21.0, a.sof)
319
320 def test_add_atom_occupancy_takes_priority_over_sof(self):
321 """Mixing occupancy and sof raises ValueError."""
322 with self.assertRaises(ValueError):
323 self.shx.add_atom(name='C99', coordinates=[0.1, 0.2, 0.3],
324 occupancy=0.5, sof=10.5)
325
326 def test_add_atom_fvar_with_sof_raises(self):
327 """Mixing fvar (non-default) and sof raises ValueError."""
328 with self.assertRaises(ValueError):
329 self.shx.add_atom(name='C99', coordinates=[0.1, 0.2, 0.3],
330 fvar=2, sof=21.0)
331
332 def test_add_atom_occupancy_half_disorder(self):
333 """Typical 50:50 disorder: occupancy=0.5 for both parts."""
334 a1 = self.shx.add_atom(name='C97', coordinates=[0.1, 0.2, 0.3],
335 occupancy=0.5, fvar=1, part=1)
336 a2 = self.shx.add_atom(name='C98', coordinates=[0.1, 0.2, 0.31],
337 occupancy=0.5, fvar=1, part=2)
338 self.assertAlmostEqual(10.5, a1.sof)
339 self.assertAlmostEqual(10.5, a2.sof)
340 self.assertEqual(1, a1.part.n)
341 self.assertEqual(2, a2.part.n)
342
343 # ------------------------------------------------------------------
344 # Written output is valid
345 # ------------------------------------------------------------------
346
347 def test_add_atom_written_to_file(self):
348 self.shx.add_atom(name='C99', coordinates=[0.1, 0.2, 0.3])
349 with tempfile.NamedTemporaryFile(suffix='.res', delete=False) as tmp:
350 tmppath = Path(tmp.name)
351 try:
352 self.shx.write_shelx_file(tmppath)
353 content = tmppath.read_text()
354 self.assertIn('C99', content)
355 self.assertIn('TITL', content)
356 self.assertIn('HKLF', content)
357 finally:
358 tmppath.unlink(missing_ok=True)
359
360 # ------------------------------------------------------------------
361 # unused_atom_name
362 # ------------------------------------------------------------------
363
364 def test_unused_atom_name_carbon(self):
365 name = self.shx.unused_atom_name('C')
366 # It must be a valid, non-existing name
367 self.assertFalse(self.shx.atoms.has_atom(name))
368 self.assertTrue(name.startswith('C'))
369
370 def test_unused_atom_name_new_element(self):
371 name = self.shx.unused_atom_name('Xe')
372 self.assertEqual('Xe1', name)
373
374 def test_unused_atom_name_max_4_chars(self):
375 """Every generated name must fit within SHELX's 4-character limit."""
376 for element in ('C', 'Fe', 'Al'):
377 name = self.shx.unused_atom_name(element)
378 self.assertLessEqual(len(name), 4, f"Name {name!r} exceeds 4 chars")
379
380 def test_unused_atom_name_two_char_element_limit(self):
381 """For a 2-char element like 'Fe', max suffix is 99 (Fe99 = 4 chars)."""
382 # Fill Fe1..Fe99 artificially by patching nameslist lookup
383 shx = Shelxfile()
384 shx.read_file('tests/resources/p21c.res')
385 # Add Fe1..Fe99 to the atoms dict cache to simulate exhaustion
386 fake_names = {f'FE{n}_0' for n in range(1, 100)} # FE1_0 … FE99_0
387 original_nameslist = shx.atoms.nameslist
388 # Monkey-patch nameslist for this one test
389 from unittest.mock import patch
390 with patch.object(type(shx.atoms), 'nameslist',
391 new_callable=lambda: property(lambda self: original_nameslist + tuple(fake_names))):
392 with self.assertRaises(ValueError):
393 shx.unused_atom_name('Fe')
394
395 def test_unused_atom_name_returns_unique_name(self):
396 name1 = self.shx.unused_atom_name('C')
397 self.shx.add_atom(name=name1, coordinates=[0.1, 0.2, 0.3])
398 name2 = self.shx.unused_atom_name('C')
399 self.assertNotEqual(name1, name2)
400 self.assertFalse(self.shx.atoms.has_atom(name2))
401
402 def test_unused_atom_name_combines_with_add_atom(self):
403 """Round-trip: get a name then add an atom with it."""
404 name = self.shx.unused_atom_name('N')
405 a = self.shx.add_atom(name=name, coordinates=[0.3, 0.3, 0.3], element='N')
406 self.assertEqual(name, a.name)
407 self.assertIsNotNone(self.shx.atoms.get_atom_by_name(name))
408
409