Debian Codegraph @

shelxfile/shelx/sdm.py

raw symbols SCIP
1 # -*- encoding: utf-8 -*-
2 # möp
3 #
4 # ----------------------------------------------------------------------------
5 # "THE BEER-WARE LICENSE" (Revision 42):
6 # <[email protected]> wrote this file. As long as you retain
7 # this notice you can do whatever you want with this stuff. If we meet some day,
8 # and you think this stuff is worth it, you can buy me a beer in return.
9 # Daniel Kratzert
10 # ----------------------------------------------------------------------------
11 #
12 import time
13 from math import sqrt, radians, sin, floor
14 from pathlib import Path
15
16 import numpy as np
17
18 try:
19 import sdm_cpp
20
21 HAS_CPP = True
22 except ImportError:
23 HAS_CPP = False
24
25 from shelxfile.atoms.atom import Atom
26 from shelxfile.misc.dsrmath import vol_unitcell
27 from shelxfile.misc.misc import wrap_line
28 from shelxfile.shelx.cards import AFIX, RESI
29
30
31 def _unique_legal_atom_name(element: str, used_names: set) -> str:
32 """Return a unique, legal SHELXL atom name (≤4 alphanumeric chars).
33
34 The name follows the pattern ``El1``, ``El2``, … up to the digit limit
35 imposed by the 4-character maximum:
36 - 1-char element symbol → up to ``E999``
37 - 2-char element symbol → up to ``EE99``
38
39 The generated name is added to *used_names* (upper-case) before returning
40 so subsequent calls automatically avoid it.
41
42 :raises ValueError: when the numbering range for the element is exhausted.
43 """
44 prefix = element.capitalize()
45 max_digits = 4 - len(prefix)
46 if max_digits < 1:
47 raise ValueError(
48 f"Element symbol '{element}' is too long to form a legal SHELXL atom name."
49 )
50 max_num = 10 ** max_digits - 1
51 for n in range(1, max_num + 1):
52 candidate = f'{prefix}{n}'
53 if candidate.upper() not in used_names:
54 used_names.add(candidate.upper())
55 return candidate
56 raise ValueError(
57 f"Cannot generate a unique legal SHELXL atom name for element '{element}': "
58 f"all {max_num} slots are taken."
59 )
60
61
62 class SDMItem(object):
63 __slots__ = ['dist', 'atom1', 'atom2', 'a1', 'a2', 'symmetry_number', 'covalent', 'dddd']
64
65 def __init__(self):
66 self.dist = 0.0
67 self.atom1 = None
68 self.a1 = 0
69 self.atom2 = None
70 self.a2 = 0
71 self.symmetry_number = 0
72 self.covalent = True
73 self.dddd = 0
74
75 def __lt__(self, a2):
76 return True if self.dist < a2.dist else False
77
78 def __eq__(self, other: 'SDMItem'):
79 if other.a1 == self.a2 and other.a2 == self.a1:
80 return True
81 return False
82
83 def __repr__(self):
84 return '{} {} dist: {:.6} coval: {} sn: {} {}\n'.format(
85 self.a1, self.a2, self.dist, self.covalent, self.symmetry_number, self.dddd)
86
87
88 class SDM():
89 """
90 Calculates the shortest distance matrix and creates a completed (grown) structure
91 by crystal symmetry.
92
93 Algorithm improvements (matching Fastmolwidget):
94 - Pre-computed symmetry matrices (column-major tuples) avoid per-iteration numpy calls.
95 - Squared distance cutoff (dk2 > 16.0 Ų) eliminates the sqrt for far pairs.
96 - Union-Find (path-halving + union-by-rank) replaces the O(K·|sdm_list|) molindex loop.
97 - numpy is used for U-value transformations.
98 """
99
100 def __init__(self, shx: 'Shelxfile'):
101 self.shx = shx
102 self.cell = (
103 shx.cell.a, shx.cell.b, shx.cell.c,
104 shx.cell.alpha, shx.cell.beta, shx.cell.gamma)
105 self.aga = shx.cell.a * shx.cell.b * shx.cell.cosga
106 self.bbe = shx.cell.a * shx.cell.c * shx.cell.cosbe
107 self.cal = shx.cell.b * shx.cell.c * shx.cell.cosal
108 self.asq = shx.cell[0] ** 2
109 self.bsq = shx.cell[1] ** 2
110 self.csq = shx.cell[2] ** 2
111 # reciprocal lattice vectors (used for U-value transforms and vector_length)
112 self.astar = (shx.cell.b * shx.cell.c * sin(radians(shx.cell.alpha))) / shx.cell.V
113 self.bstar = (shx.cell.c * shx.cell.a * sin(radians(shx.cell.beta))) / shx.cell.V
114 self.cstar = (shx.cell.a * shx.cell.b * sin(radians(shx.cell.gamma))) / shx.cell.V
115 self.sdm_list: list[SDMItem] = []
116 self.maxmol = 1
117 self.sdmtime = 0
118 self.bondlist = []
119 # Pre-computed symmetry matrices (set in _build_symm_arrays, reused everywhere)
120 self._symm_m: list[tuple] = []
121 self._symm_t: list[tuple] = []
122
123 def _build_symm_arrays(self) -> None:
124 """Pre-compute column-major symmetry matrices as nested tuples for fast inner loops.
125
126 Each symmcard.matrix is a (3,3) numpy array stored row-major (matrix[i,j] is the
127 coefficient of input axis j for output axis i). Taking .T converts to column-major
128 so the inner-loop formula
129 px = x*m[0][0] + y*m[1][0] + z*m[2][0]
130 correctly evaluates matrix[0,:] · [x,y,z].
131 """
132 self._symm_m = []
133 self._symm_t = []
134 for s in self.shx.symmcards:
135 self._symm_m.append(tuple(map(tuple, s.matrix.T)))
136 self._symm_t.append(tuple(s.trans))
137
138 def calc_sdm(self) -> list:
139 t1 = time.perf_counter()
140 self._build_symm_arrays()
141 symm_m = self._symm_m
142 symm_t = self._symm_t
143 nlen = len(symm_m)
144
145 all_atoms = self.shx.atoms.all_atoms
146 self.sdm_list.clear()
147 self.bondlist.clear()
148
149 # Pre-extract primitive data to avoid per-iteration attribute lookups
150 coords = [(at.x, at.y, at.z) for at in all_atoms]
151 radii = [at.radius for at in all_atoms]
152 is_h = [at.ishydrogen for at in all_atoms]
153 parts = [at.part.n for at in all_atoms]
154
155 aga, bbe, cal = self.aga, self.bbe, self.cal
156 asq, bsq, csq = self.asq, self.bsq, self.csq
157
158 # ── C++ fast path ──────────────────────────────────────────────────
159 if HAS_CPP:
160 cpp_results = sdm_cpp.calc_sdm_cpp(
161 coords, symm_m, symm_t,
162 aga, bbe, cal,
163 asq, bsq, csq,
164 radii, is_h, parts,
165 )
166 for (i, j, best_n, mind, dddd, covalent) in cpp_results:
167 sdm_item = SDMItem()
168 sdm_item.dist = mind
169 sdm_item.atom1 = all_atoms[i]
170 sdm_item.atom2 = all_atoms[j]
171 sdm_item.a1 = i
172 sdm_item.a2 = j
173 sdm_item.symmetry_number = best_n
174 sdm_item.dddd = dddd
175 sdm_item.covalent = covalent
176 self.sdm_list.append(sdm_item)
177
178 # ── Pure-Python fallback ────────────────────────────────────────────
179 else:
180 at2_plushalf = [(x + 0.5, y + 0.5, z + 0.5) for (x, y, z) in coords]
181
182 for i, at1 in enumerate(all_atoms):
183 x1, y1, z1 = coords[i]
184
185 # Apply all symmetry operations to at1 once (outer loop)
186 prime_array = []
187 for m, t in zip(symm_m, symm_t):
188 px = x1 * m[0][0] + y1 * m[1][0] + z1 * m[2][0] + t[0]
189 py = x1 * m[0][1] + y1 * m[1][1] + z1 * m[2][1] + t[1]
190 pz = x1 * m[0][2] + y1 * m[1][2] + z1 * m[2][2] + t[2]
191 prime_array.append((px, py, pz))
192
193 for j, at2 in enumerate(all_atoms):
194 mind = 1_000_000.0
195 hma = False
196 atp_x, atp_y, atp_z = at2_plushalf[j]
197 sdm_item = SDMItem()
198
199 for n in range(nlen):
200 px, py, pz = prime_array[n]
201
202 dx = px - atp_x
203 dy = py - atp_y
204 dz = pz - atp_z
205
206 dpx = dx - floor(dx) - 0.5
207 dpy = dy - floor(dy) - 0.5
208 dpz = dz - floor(dz) - 0.5
209
210 A = 2.0 * (dpx * dpy * aga + dpx * dpz * bbe + dpy * dpz * cal)
211 dk2 = dpx * dpx * asq + dpy * dpy * bsq + dpz * dpz * csq + A
212
213 if dk2 > 16.0: # 4 Å hard cutoff (squared) – skip sqrt
214 continue
215
216 dk = sqrt(dk2)
217 if n:
218 dk += 0.0001 # slight penalty for symmetry-generated images
219
220 if (dk > 0.01) and (mind >= dk):
221 mind = dk
222 sdm_item.dist = mind
223 sdm_item.atom1 = at1
224 sdm_item.atom2 = at2
225 sdm_item.a1 = i
226 sdm_item.a2 = j
227 sdm_item.symmetry_number = n
228 hma = True
229
230 if not sdm_item.atom1:
231 continue
232
233 if ((not is_h[i] and not is_h[j]) and parts[i] * parts[j] == 0) \
234 or parts[i] == parts[j]:
235 dddd = (radii[i] + radii[j]) * 1.2
236 sdm_item.dddd = dddd
237 else:
238 dddd = 0.0
239
240 if sdm_item.dist < dddd:
241 if hma:
242 sdm_item.covalent = True
243 else:
244 sdm_item.covalent = False
245
246 if hma:
247 self.sdm_list.append(sdm_item)
248
249 t2 = time.perf_counter()
250 self.sdmtime = t2 - t1
251 if self.shx.debug:
252 print(f'SDM {"(C++)" if HAS_CPP else "(Python fallback)"}: {self.sdmtime:.4f} s')
253
254 self.sdm_list.sort()
255 self.calc_molindex(all_atoms)
256 need_symm = self.collect_needed_symmetry()
257 if self.shx.debug:
258 print(f"The asymmetric unit contains {self.maxmol} fragments.")
259 return need_symm
260
261 def collect_needed_symmetry(self) -> list:
262 need_symm = []
263 symm_m = self._symm_m
264 symm_t = self._symm_t
265
266 aga, bbe, cal = self.aga, self.bbe, self.cal
267 asq, bsq, csq = self.asq, self.bsq, self.csq
268
269 for sdm_item in self.sdm_list:
270 if not sdm_item.covalent:
271 continue
272 if sdm_item.atom1.molindex < 1 or sdm_item.atom1.molindex > 6:
273 continue
274
275 x1, y1, z1 = sdm_item.atom1.x, sdm_item.atom1.y, sdm_item.atom1.z
276 x2, y2, z2 = sdm_item.atom2.x, sdm_item.atom2.y, sdm_item.atom2.z
277 part1 = sdm_item.atom1.part.n
278 part2 = sdm_item.atom2.part.n
279 is_h1 = sdm_item.atom1.ishydrogen
280 is_h2 = sdm_item.atom2.ishydrogen
281
282 for n, (m, t) in enumerate(zip(symm_m, symm_t)):
283 if part1 != 0 and part2 != 0 and part1 != part2:
284 continue
285 # Skip H–H pairs of the same atomic number
286 if is_h1 and is_h2 and sdm_item.atom1.an == sdm_item.atom2.an:
287 continue
288
289 px = x1 * m[0][0] + y1 * m[1][0] + z1 * m[2][0] + t[0]
290 py = x1 * m[0][1] + y1 * m[1][1] + z1 * m[2][1] + t[1]
291 pz = x1 * m[0][2] + y1 * m[1][2] + z1 * m[2][2] + t[2]
292
293 Dx = px - x2 + 0.5
294 Dy = py - y2 + 0.5
295 Dz = pz - z2 + 0.5
296
297 fDx = floor(Dx)
298 fDy = floor(Dy)
299 fDz = floor(Dz)
300
301 if n == 0 and fDx == 0 and fDy == 0 and fDz == 0:
302 continue
303
304 dpx = Dx - fDx - 0.5
305 dpy = Dy - fDy - 0.5
306 dpz = Dz - fDz - 0.5
307
308 A = 2.0 * (dpx * dpy * aga + dpx * dpz * bbe + dpy * dpz * cal)
309 dk2 = dpx * dpx * asq + dpy * dpy * bsq + dpz * dpz * csq + A
310
311 if dk2 <= 1e-6:
312 continue
313
314 dk = sqrt(dk2)
315 dddd = sdm_item.dist + 0.2
316 if is_h1 and is_h2:
317 dddd = 1.8
318
319 if dk <= dddd:
320 bs = [n + 1, int(5 - fDx), int(5 - fDy), int(5 - fDz), sdm_item.atom1.molindex]
321 if bs not in need_symm:
322 need_symm.append(bs)
323
324 return need_symm
325
326 def calc_molindex(self, all_atoms: list) -> None:
327 """Assign a molecule index to every atom using Union-Find (path-halving +
328 union-by-rank). Replaces the original O(K|sdm_list|) repeated-scan loop
329 with an essentially linear O(N + M·α(N)) algorithm.
330 """
331 n = len(all_atoms)
332 for at in all_atoms:
333 at.molindex = -1
334
335 parent = list(range(n))
336 rank = [0] * n
337
338 def find(x: int) -> int:
339 while parent[x] != x:
340 parent[x] = parent[parent[x]] # path halving
341 x = parent[x]
342 return x
343
344 def union(x: int, y: int) -> None:
345 rx, ry = find(x), find(y)
346 if rx == ry:
347 return
348 if rank[rx] < rank[ry]:
349 rx, ry = ry, rx
350 parent[ry] = rx
351 if rank[rx] == rank[ry]:
352 rank[rx] += 1
353
354 for sdm_item in self.sdm_list:
355 if sdm_item.covalent:
356 union(sdm_item.a1, sdm_item.a2)
357
358 root_to_mol: dict[int, int] = {}
359 mol_counter = 0
360 for i in range(n):
361 root = find(i)
362 if root not in root_to_mol:
363 mol_counter += 1
364 root_to_mol[root] = mol_counter
365 all_atoms[i].molindex = root_to_mol[root]
366
367 self.maxmol = mol_counter
368
369 def vector_length(self, x: float, y: float, z: float) -> float:
370 """
371 Calculates the vector length given in fractional coordinates.
372 """
373 A = 2.0 * (x * y * self.aga + x * z * self.bbe + y * z * self.cal)
374 return sqrt(x ** 2 * self.asq + y ** 2 * self.bsq + z ** 2 * self.csq + A)
375
376 def packer(self, sdm: 'SDM', need_symm: list, with_qpeaks=False) -> list:
377 """
378 Packs atoms of the asymmetric unit to real molecules.
379 """
380 if not self._symm_m:
381 self._build_symm_arrays()
382 symm_m = self._symm_m
383 symm_t = self._symm_t
384
385 asymm = self.shx.atoms.all_atoms
386 if with_qpeaks:
387 showatoms = asymm[:]
388 else:
389 showatoms = [at for at in asymm if not at.qpeak]
390
391 # Seed used_names with all names already present so generated names
392 # never clash with the asymmetric-unit atoms or with each other.
393 used_names: set = {at.name.upper() for at in showatoms}
394
395 for symm in need_symm:
396 symm_num, h, k, l, symmgroup = symm # noqa: E741
397 h -= 5
398 k -= 5
399 l -= 5 # noqa: E741
400 symm_num -= 1
401
402 m = symm_m[symm_num]
403 t = symm_t[symm_num]
404
405 for atom in asymm:
406 if not with_qpeaks and atom.qpeak:
407 continue
408 if atom.molindex != symmgroup:
409 continue
410
411 new_atom = Atom(self.shx)
412 if atom.qpeak:
413 continue
414
415 uvals = list(atom.uvals)
416 # Transform anisotropic U-values so ADPs are oriented correctly
417 # after the symmetry rotation.
418 if sum(abs(u) for u in uvals[2:]) > 1e-5:
419 uvals = list(self.transform_uvalues(uvals, symm_num))
420
421 # Apply symmetry operation and lattice shift
422 x1, y1, z1 = atom.x, atom.y, atom.z
423 px = x1 * m[0][0] + y1 * m[1][0] + z1 * m[2][0] + t[0] + h
424 py = x1 * m[0][1] + y1 * m[1][1] + z1 * m[2][1] + t[1] + k
425 pz = x1 * m[0][2] + y1 * m[1][2] + z1 * m[2][2] + t[2] + l
426
427 # Assign a unique, legal SHELXL atom name (≤4 alphanumeric chars).
428 element = self.shx.sfac2elem(atom.sfac_num)
429 new_name = _unique_legal_atom_name(element, used_names)
430
431 new_atom.set_atom_parameters(
432 name=new_name,
433 sfac_num=atom.sfac_num,
434 coords=[px, py, pz],
435 part=atom.part,
436 afix=AFIX(self.shx, (atom.afix).split()) if atom.afix else None,
437 resi=RESI(self.shx, (f'RESI {atom.resinum} {atom.resiclass}').split()) if atom.resi else None,
438 site_occupation=atom.sof,
439 uvals=uvals,
440 symmgen=True,
441 )
442
443 isthere = False
444 if new_atom.part.n >= 0:
445 for existing in showatoms:
446 if existing.part.n != new_atom.part.n:
447 continue
448 length = sdm.vector_length(
449 new_atom.x - existing.x,
450 new_atom.y - existing.y,
451 new_atom.z - existing.z)
452 if length < 0.2:
453 isthere = True
454 break
455 if not isthere:
456 showatoms.append(new_atom)
457 else:
458 # Atom was a duplicate — release the name we just reserved
459 used_names.discard(new_name.upper())
460
461 return showatoms
462
463 def pack_unit_cell(
464 self,
465 symmop_indices: list[int] | None = None,
466 *,
467 cart_tolerance: float = 0.2,
468 with_qpeaks: bool = False,
469 ) -> list:
470 """Pack all symmetry-equivalent positions into one unit cell.
471
472 For every atom in the asymmetric unit every selected symmetry operation
473 is applied and the result is folded back into [0, 1) fractional
474 coordinates. Positions already occupied within *cart_tolerance* Å
475 (with periodic boundary conditions) are discarded as duplicates.
476
477 This can be called on a fresh :class:`SDM` object before
478 :meth:`calc_sdm` — it does **not** require the SDM to have been run.
479
480 :param symmop_indices: 0-based indices into the symmetry-card list
481 (identity is index 0). ``None`` applies all operations.
482 :param cart_tolerance: Cartesian duplicate threshold in Å (default 0.2).
483 :param with_qpeaks: include Q-peaks in the output (default False).
484 :returns: List of :class:`~shelxfile.atoms.atom.Atom` objects with
485 updated fractional coordinates.
486 """
487 if not self._symm_m:
488 self._build_symm_arrays()
489 symm_m = self._symm_m
490 symm_t = self._symm_t
491
492 selected: list[int] = (
493 list(range(len(symm_m)))
494 if symmop_indices is None
495 else list(symmop_indices)
496 )
497
498 a, b, c, alpha, beta, gamma = self.cell
499 aga, bbe, cal = self.aga, self.bbe, self.cal
500 asq, bsq, csq = self.asq, self.bsq, self.csq
501 tol_sq = cart_tolerance * cart_tolerance
502
503 # Spatial grid for O(1) average-case duplicate detection.
504 # Each bin spans ~cart_tolerance; at least 3 bins per axis so the
505 # 3×3×3 neighbour check covers exactly one cell-image distance.
506 grid_nx = max(3, int(a / cart_tolerance))
507 grid_ny = max(3, int(b / cart_tolerance))
508 grid_nz = max(3, int(c / cart_tolerance))
509
510 # grid maps (ix, iy, iz) → [(fx, fy, fz, part, packed_idx), ...]
511 grid: dict[tuple[int, int, int], list[tuple]] = {}
512 # packed entries: (orig_atom, px, py, pz, symm_idx)
513 packed: list[tuple] = []
514
515 asymm = self.shx.atoms.all_atoms
516 for at in asymm:
517 if not with_qpeaks and at.qpeak:
518 continue
519 x1, y1, z1 = at.x, at.y, at.z
520 part = at.part.n
521
522 for idx in selected:
523 m = symm_m[idx]
524 t = symm_t[idx]
525
526 # Apply symmetry operation (column-major) and fold to [0, 1)
527 px = (x1 * m[0][0] + y1 * m[1][0] + z1 * m[2][0] + t[0]) % 1.0
528 py = (x1 * m[0][1] + y1 * m[1][1] + z1 * m[2][1] + t[1]) % 1.0
529 pz = (x1 * m[0][2] + y1 * m[1][2] + z1 * m[2][2] + t[2]) % 1.0
530
531 # Determine grid bin for this candidate position
532 ix = int(px * grid_nx) % grid_nx
533 iy = int(py * grid_ny) % grid_ny
534 iz = int(pz * grid_nz) % grid_nz
535
536 # Check 3×3×3 neighbouring bins for a duplicate
537 is_dup = False
538 for dix in (-1, 0, 1):
539 if is_dup:
540 break
541 nix = (ix + dix) % grid_nx
542 for diy in (-1, 0, 1):
543 if is_dup:
544 break
545 niy = (iy + diy) % grid_ny
546 for diz in (-1, 0, 1):
547 if is_dup:
548 break
549 niz = (iz + diz) % grid_nz
550 bucket = grid.get((nix, niy, niz))
551 if bucket is None:
552 continue
553 for (efx, efy, efz, epart, _) in bucket:
554 # Different non-zero disorder parts are never duplicates
555 if epart != 0 and part != 0 and epart != part:
556 continue
557 # Fractional difference folded to [-0.5, 0.5]
558 ddx = px - efx
559 ddx -= int(ddx + (0.5 if ddx >= 0.0 else -0.5))
560 ddy = py - efy
561 ddy -= int(ddy + (0.5 if ddy >= 0.0 else -0.5))
562 ddz = pz - efz
563 ddz -= int(ddz + (0.5 if ddz >= 0.0 else -0.5))
564 d2 = (ddx * ddx * asq + ddy * ddy * bsq
565 + ddz * ddz * csq
566 + 2.0 * (ddx * ddy * aga
567 + ddx * ddz * bbe
568 + ddy * ddz * cal))
569 if d2 < tol_sq:
570 is_dup = True
571 break
572
573 if not is_dup:
574 idx_packed = len(packed)
575 packed.append((at, px, py, pz, idx))
576 key = (ix, iy, iz)
577 bucket = grid.get(key)
578 if bucket is None:
579 grid[key] = [(px, py, pz, part, idx_packed)]
580 else:
581 bucket.append((px, py, pz, part, idx_packed))
582
583 # Build Atom objects with the packed fractional coordinates.
584 # Assign unique, legal SHELXL names: identity-operation atoms keep
585 # their original names; symmetry-generated copies get new sequential
586 # names so no two atoms in the result share the same label.
587 result: list[Atom] = []
588 used_names: set = set()
589 for (orig_at, px, py, pz, symm_num) in packed:
590 new_atom = Atom(self.shx)
591 uvals = list(orig_at.uvals)
592 if sum(abs(u) for u in uvals[2:]) > 1e-5:
593 uvals = list(self.transform_uvalues(uvals, symm_num))
594 # For the identity operation the original name is available unless
595 # already taken (shouldn't happen, but guard anyway).
596 orig_name_up = orig_at.name.upper()
597 if orig_name_up not in used_names:
598 atom_name = orig_at.name
599 used_names.add(orig_name_up)
600 else:
601 element = self.shx.sfac2elem(orig_at.sfac_num)
602 atom_name = _unique_legal_atom_name(element, used_names)
603 new_atom.set_atom_parameters(
604 name=atom_name,
605 sfac_num=orig_at.sfac_num,
606 coords=[px, py, pz],
607 part=orig_at.part,
608 afix=AFIX(self.shx, orig_at.afix.split()) if orig_at.afix else None,
609 resi=RESI(self.shx, f'RESI {orig_at.resinum} {orig_at.resiclass}'.split())
610 if orig_at.resi else None,
611 site_occupation=orig_at.sof,
612 uvals=uvals,
613 symmgen=(symm_num != 0),
614 )
615 result.append(new_atom)
616
617 return result
618
619 def transform_uvalues(self, uvals: list | tuple, symm_num: int) -> tuple:
620 """
621 Transforms the Uij values according to the given symmetry rotation.
622
623 Reference: R. W. Grosse-Kunstleve, P. D. Adams (2002). J. Appl. Cryst. 35, 477–480.
624 http://dx.doi.org/10.1107/S0021889802008580
625
626 Steps:
627 U(star) = N @ U(cif) @ N.T (CIF → star parameterisation)
628 U(star) = R @ U(star) @ R.T (symmetry rotation)
629 U(cif) = N⁻¹ @ U(star) @ N⁻¹.T (star → CIF)
630
631 where N = diag(a*, b*, c*) and R = symmcards[symm_num].matrix (numpy, row-major).
632 """
633 U11, U22, U33, U23, U13, U12 = uvals
634 Ucif = np.array([[U11, U12, U13],
635 [U12, U22, U23],
636 [U13, U23, U33]], dtype=float)
637 N = np.diag([self.astar, self.bstar, self.cstar])
638 N_inv = np.linalg.inv(N)
639 R = self.shx.symmcards[symm_num].matrix # numpy (3,3), not transposed
640
641 Ustar = N @ Ucif @ N.T
642 Ustar = R @ Ustar @ R.T
643 Ucif_new = N_inv @ Ustar @ N_inv.T
644
645 return (float(Ucif_new[0, 0]), float(Ucif_new[1, 1]), float(Ucif_new[2, 2]),
646 float(Ucif_new[1, 2]), float(Ucif_new[0, 2]), float(Ucif_new[0, 1]))
647
648
649 def ufrac_to_ucart(A, cell: tuple, uvals: list) -> np.ndarray:
650 """
651 Converts anisotropic displacement parameters from fractional (CIF) to
652 Cartesian coordinates.
653
654 :param A: OrthogonalMatrix (or any object with a .values attribute)
655 :param cell: (a, b, c, alpha, beta, gamma)
656 :param uvals: [U11, U22, U33, U23, U13, U12] in fractional parameterisation
657 :returns: 3×3 numpy array of U(cart)
658 """
659 U11, U22, U33, U23, U13, U12 = uvals
660 Uij = np.array([[U11, U12, U13],
661 [U12, U22, U23],
662 [U13, U23, U33]], dtype=float)
663 a, b, c, alpha, beta, gamma = cell
664 V = vol_unitcell(*cell)
665 astar = (b * c * sin(radians(alpha))) / V
666 bstar = (c * a * sin(radians(beta))) / V
667 cstar = (a * b * sin(radians(gamma))) / V
668 N = np.diag([astar, bstar, cstar])
669 A_np = np.array(A.values, dtype=float)
670 return A_np @ N @ Uij @ N.T @ A_np.T
671
672
673 if __name__ == "__main__":
674 from shelxfile.shelx.shelx import Shelxfile
675
676 shx = Shelxfile()
677 shx.read_file('tests/resources/p-31c.res')
678 t1 = time.perf_counter()
679 sdm = SDM(shx)
680 needsymm = sdm.calc_sdm()
681 print('sdmlist:', len(sdm.sdm_list))
682 print(needsymm)
683 packed_atoms = sdm.packer(sdm, needsymm)
684 print('Zeit für sdm:', round(time.perf_counter() - t1, 3), 's')
685
686 head = """
687 REM Solution 1 R1 0.081, Alpha = 0.0146 in P31c
688 REM Flack x = -0.072 ( 0.041 ) from Parsons' quotients
689 REM C19.667 N2.667 P4
690 TITL p-31c-neu in P-31c
691 CELL 0.71073 12.5067 12.5067 24.5615 90.000 90.000 120.000
692 ZERR 2 0.0043 0.0043 0.0085 0.000 0.000 0.000
693 LATT -1
694 SFAC C H N P Cl
695 UNIT 120 186 14 12 12
696 TEMP -173.000
697 OMIT 0 0 2
698 L.S. 10
699 BOND $H
700 ACTA
701 CONF
702
703 LIST 4
704 FMAP 2
705 PLAN 40
706 WGHT 0.034600 0.643600
707 FVAR 0.22604 0.76052 0.85152\n"""
708
709 tail = """\n
710 HKLF 4
711
712 REM p-31c-neu in P-31c
713 REM R1 = 0.0308 for 4999 Fo > 4sig(Fo) and 0.0343 for all 5352 data
714 REM 287 parameters refined using 365 restraints
715
716 END
717
718 WGHT 0.0348 0.6278
719 """
720 for at in packed_atoms:
721 if at.qpeak:
722 continue
723 head += wrap_line(str(at)) + '\n'
724 head += tail
725 p = Path('./test.res')
726 p.write_text(head)
727 print(len(shx.atoms))
728 print(len(packed_atoms))
729 print('Zeit für sdm:', round(sdm.sdmtime, 3), 's')