Debian Codegraph @

shelxfile/atoms/atoms.py

raw symbols SCIP
1 from fractions import Fraction
2 from math import acos, sqrt, degrees
3 from typing import Union, List, TYPE_CHECKING, Iterator, Dict
4
5 import numpy as np
6
7 if TYPE_CHECKING:
8 from shelxfile import Shelxfile
9 from shelxfile.atoms.atom import Atom
10 from shelxfile.atoms.pairs import Bond, SymBond
11 from shelxfile.misc.dsrmath import atomic_distance, Array
12 from shelxfile.misc.misc import build_conntable
13
14
15 def _build_symm_label(symm_element, h: int, k: int, l: int) -> str:
16 """Build a human-readable symmetry label in SHELXL/CIF style.
17
18 Combines the rotation/translation from *symm_element* with the extra
19 integer lattice shifts *h*, *k*, *l* into a string such as
20 ``'-x+1, y+1/2, -z'``.
21
22 Parameters
23 ----------
24 symm_element : SymmetryElement
25 The symmetry operation from ``Shelxfile.symmcards``.
26 h, k, l : int
27 Extra integer translations (negative values shift in the opposite
28 direction), corresponding to the lattice vector that places the
29 generated atom nearest to the reference atom.
30 """
31 axes = ['x', 'y', 'z']
32 parts = []
33 for i, shift in enumerate([h, k, l]):
34 total_t = float(symm_element.trans[i]) + shift
35 row = symm_element.matrix[i]
36 term = ''
37 for j in range(3):
38 c = float(row[j])
39 if c == 0.0:
40 continue
41 if c == 1.0:
42 term += f'+{axes[j]}'
43 elif c == -1.0:
44 term += f'-{axes[j]}'
45 elif c > 0:
46 term += f'+{c:g}{axes[j]}'
47 else:
48 term += f'{c:g}{axes[j]}'
49 if total_t:
50 frac = Fraction(total_t).limit_denominator(12)
51 if frac.denominator == 1:
52 t_str = f'{int(frac):+d}'
53 else:
54 sign = '+' if frac > 0 else ''
55 t_str = f'{sign}{frac}'
56 else:
57 t_str = ''
58 parts.append((term + t_str).lstrip('+'))
59 return ', '.join(parts)
60
61
62 class Atoms():
63 """
64 All atoms from a SHELXL file with their properties.
65 """
66
67 def __init__(self, shx: 'Shelxfile'):
68 self.shx = shx
69 self.all_atoms: List[Atom] = []
70 self._atomsdict: Dict[str, Atom] = {}
71
72 def append(self, atom: 'Atom') -> None:
73 """
74 Adds a new atom to the list of atoms. Using append is essential.
75 """
76 self.all_atoms.append(atom)
77 self._atomsdict.clear()
78
79 @property
80 def nameslist(self) -> tuple[str, ...]:
81 return tuple([at.fullname.upper() for at in self.all_atoms])
82
83 def __repr__(self) -> str:
84 if self.all_atoms:
85 return '\n'.join([str(x) for x in self.all_atoms])
86 else:
87 return 'No Atoms in file.'
88
89 def __iter__(self) -> Iterator:
90 return iter(x for x in self.all_atoms)
91
92 def __getitem__(self, item: int) -> 'Atom':
93 return self.get_atom_by_id(item)
94
95 def __len__(self) -> int:
96 return len(self.all_atoms)
97
98 def __delitem__(self, key: int) -> None:
99 """
100 Delete an atom by its atomid:
101 del atoms[4]
102 """
103 for n, at in enumerate(self.all_atoms):
104 if key == at.atomid:
105 if self.shx.debug:
106 print("deleting atom", at.fullname)
107 del self.all_atoms[n]
108 del self.shx._reslist[self.shx._reslist.index(at)]
109 self._atomsdict.clear()
110 # if self.shx.debug:
111 # print('Could not delete atom {}'.format(self.get_atom_by_id(key.atomid).fullname))
112
113 @property
114 def atomsdict(self):
115 if not self._atomsdict:
116 self._atomsdict = dict((atom.fullname.upper(), atom) for atom in self.all_atoms)
117 return self._atomsdict
118
119 @property
120 def number(self) -> int:
121 """
122 The number of atoms in the current SHELX file.
123 """
124 return len(self.all_atoms)
125
126 def get_atom_by_id(self, aid: int) -> Union['Atom', None]:
127 """
128 Returns the atom objext with atomId id.
129 """
130 for a in self.all_atoms:
131 if aid == a.atomid:
132 return a
133
134 def has_atom(self, atom_name: str) -> bool:
135 """
136 Returns true if shelx file has atom.
137 """
138 if '_' not in atom_name:
139 atom_name += '_0'
140 if atom_name.upper() in self.nameslist:
141 return True
142 else:
143 return False
144
145 def get_atom_by_name(self, atom_name: str) -> Union['Atom', None]:
146 """
147 Returns an Atom object using an atom name with residue number like C1, C1_0, F2_4, etc.
148 C1 means atom C1 in residue 0.
149 """
150 if '_' not in atom_name:
151 if atom_name == ">" or atom_name == "<":
152 return None
153 atom_name = f'{atom_name}_0'
154 atom = self.atomsdict.get(atom_name.upper(), None)
155 # if not atom and self.shx.debug:
156 # print(f"Atom {atom_name} not found in atom list.")
157 return atom
158
159 def get_multi_atnames(self, atom_name, residue_class):
160 atoms = []
161 if residue_class:
162 for num in self.shx.residues.residue_classes[residue_class]:
163 if '_' not in atom_name:
164 atom_name += '_0'
165 else:
166 atom_name += '_{}'.format(num)
167 try:
168 atoms.append(self.atomsdict[atom_name.upper()])
169 except KeyError:
170 pass
171 else:
172 try:
173 atoms.append(self.atomsdict[atom_name.upper()])
174 except KeyError:
175 return None
176 return atoms
177
178 def get_all_atomcoordinates(self) -> dict:
179 """
180 Returns a dictionary {'C1': ['1.123', '0.7456', '3.245'], 'C2_2': ...}
181 """
182 atdict = {}
183 for at in self.all_atoms:
184 # if at.qpeak:
185 # atdict[at.name] = at.frac_coords
186 # else:
187 atdict[at.name.upper() + '_' + str(at.resinum)] = at.frac_coords
188 return atdict
189
190 def get_frag_fend_atoms(self) -> list:
191 """
192 Returns a list of atoms with cartesian coordinates. Atom names and sfac are ignored. They come from AFIX 17x.
193 [[0.5316439256202359, 7.037351406500001, 10.112963255220803],
194 [-1.7511017452002604, 5.461541059000001, 10.01187984858907]]
195 """
196 atoms = []
197 for at in self.all_atoms:
198 if at.frag_atom:
199 atoms.append([at.xc, at.yc, at.zc])
200 return atoms
201
202 @property
203 def hydrogen_atoms(self) -> List[Atom]:
204 return [x for x in self.shx.atoms.all_atoms if x.is_hydrogen]
205
206 @property
207 def n_hydrogen_atoms(self) -> int:
208 return len(self.hydrogen_atoms)
209
210 @property
211 def n_anisotropic_atoms(self) -> int:
212 return len([x for x in self.all_atoms if sum(x.uvals[1:]) > 0.00001])
213
214 @property
215 def n_isotropic_atoms(self) -> int:
216 return len([x for x in self.all_atoms if sum(x.uvals[1:]) == 0.0])
217
218 @property
219 def n_anisotropic_hydrogen_atoms(self) -> int:
220 return len([x for x in self.hydrogen_atoms if sum(x.uvals[1:]) > 0.0001])
221
222 @property
223 def n_hydrogen_atoms_with_constr_u_val(self) -> int:
224 return len([x for x in self.hydrogen_atoms if x.uvals[0] < -1.0])
225
226 @property
227 def riding_atoms(self) -> List[Atom]:
228 return [x for x in self.hydrogen_atoms if x.afix]
229
230 @property
231 def residues(self) -> list:
232 """
233 Returns a list of the residue numbers in the shelx file.
234 """
235 return list(set([x.resinum for x in self.all_atoms]))
236
237 @property
238 def q_peaks(self) -> list:
239 r"""
240 Returns a list of q-peaks in the file.
241 """
242 return [x for x in self.all_atoms if x.qpeak]
243
244 def distance(self, atom1: str, atom2: str) -> float:
245 """
246 Calculates the (shortest) distance of two atoms given as text names e.g. C1_3.
247 """
248 a1 = self.get_atom_by_name(atom1)
249 a2 = self.get_atom_by_name(atom2)
250 try:
251 return atomic_distance([a1.xc, a1.yc, a1.zc], [a2.xc, a2.yc, a2.zc])
252 except AttributeError:
253 return 0.0
254
255 def angle(self, at1: 'Atom', at2: 'Atom', at3: 'Atom') -> float:
256 """
257 Calculates the angle between three atoms.
258 """
259 ac1 = Array(at1.cart_coords)
260 ac2 = Array(at2.cart_coords)
261 ac3 = Array(at3.cart_coords)
262 vec1 = ac2 - ac1
263 vec2 = ac2 - ac3
264 return vec1.angle(vec2)
265
266 def torsion_angle(self, at1: 'Atom', at2: 'Atom', at3: 'Atom', at4: 'Atom') -> float:
267 """
268 Calculates the torsion angle (dieder angle) between four atoms.
269
270 From the book of Camelo Giacovazzo:
271 For a sequence of four atoms A, B, C, D, the torsion angle w(ABCD) is
272 defined as the angle between the normals to the planes ABC and BCD.
273 By convention w is positive if the sense of rotation from BA to
274 CD, viewed down BC, is clockwise, otherwise it is negative.
275 """
276 ac1 = Array(at1.cart_coords)
277 ac2 = Array(at2.cart_coords)
278 ac3 = Array(at3.cart_coords)
279 ac4 = Array(at4.cart_coords)
280 # Three vectors between four atoms:
281 v1 = ac2 - ac1
282 v2 = ac3 - ac2
283 v3 = ac4 - ac3
284 # cross product:
285 a = v1.cross(v2)
286 b = v2.cross(v3)
287 # If direction > 0, angle is positive, else negative:
288 direction = v1[0] * v2[1] * v3[2] - v1[2] * v1[1] * v3[0] + v1[2] * v2[0] * v3[1] - v1[0] \
289 * v2[2] * v3[1] + v1[1] * v2[2] * v3[0] - v1[1] * v2[0] * v3[2]
290 # angle between plane normals:
291 ang = acos((a[0] * b[0] + a[1] * b[1] + a[2] * b[2]) / (
292 sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]) * sqrt(b[0] * b[0] + b[1] * b[1] + b[2] * b[2])))
293 return degrees(ang) if direction > 0 else degrees(-ang)
294
295 @property
296 def conntable(self) -> tuple:
297 """Connectivity table for all atoms in the asymmetric unit.
298
299 Returns a tuple of ``(i, j)`` index pairs (i < j) where atoms *i* and
300 *j* are considered covalently bonded based on the sum of their covalent
301 radii multiplied by 1.2. Disorder-part rules and H–H bonds are
302 handled automatically.
303
304 The indices correspond to positions in :attr:`all_atoms`.
305
306 Returns
307 -------
308 tuple of (int, int)
309 """
310 atoms = self.all_atoms
311 if not atoms:
312 return ()
313 coords = np.array([[at.xc, at.yc, at.zc] for at in atoms], dtype=np.float64)
314 types = [at.element for at in atoms]
315 parts = [at.part.n for at in atoms]
316 radii = np.array([at.radius for at in atoms], dtype=np.float64)
317 symmgen = [at.symmgen for at in atoms]
318 return build_conntable(coords, types, parts, radii=radii, symmgen=symmgen)
319
320 @property
321 def bonds(self) -> List[Bond]:
322 """All covalent bonds in the asymmetric unit as a human-readable list.
323
324 Each entry is a :class:`~shelxfile.atoms.pairs.Bond` with ``atom1``,
325 ``atom2``, and ``distance`` (Å) attributes. The list is sorted by
326 atom1 name, then atom2 name.
327
328 Bonds are detected via the same covalent-radii heuristic used by
329 :attr:`conntable` (H–H pairs, cross-disorder and symmetry-generated
330 atoms are excluded).
331
332 Example::
333
334 for bond in shx.atoms.bonds:
335 print(bond)
336 # C1 – C2 1.5210 Å
337 # C1 – H1 1.0900 Å
338 # ...
339
340 # Unpack into components:
341 atom1, atom2, dist = shx.atoms.bonds[0]
342
343 Returns
344 -------
345 list of :class:`~shelxfile.atoms.pairs.Bond`
346 """
347 atoms = self.all_atoms
348 result: List[Bond] = []
349 for i, j in self.conntable:
350 a1, a2 = atoms[i], atoms[j]
351 dist = float(np.sqrt(
352 (a1.xc - a2.xc) ** 2 +
353 (a1.yc - a2.yc) ** 2 +
354 (a1.zc - a2.zc) ** 2
355 ))
356 result.append(Bond(a1, a2, dist))
357 result.sort(key=lambda b: (b.atom1.fullname_short, b.atom2.fullname_short))
358 return result
359
360 def full_bond_list(self, with_qpeaks: bool = False) -> List[SymBond]:
361 """Bond list covering every atom in the asymmetric unit and all its
362 crystallographic neighbors, including symmetry-generated ones.
363
364 For each atom *A* in the asymmetric unit the list contains one
365 :class:`~shelxfile.atoms.pairs.SymBond` per bonded neighbor:
366
367 * **Plain bond** — neighbor *B* is also in the asymmetric unit (same
368 unit cell, identity operation). Stored once with an empty
369 ``symm_label``; *A* is chosen as the atom with the lower index so
370 duplicate entries are suppressed.
371 * **Symmetry bond** — the bonded image of *B* is generated by applying
372 a crystallographic symmetry operation (and possibly a lattice
373 translation) to the coordinates of *B* in the asymmetric unit. The
374 label uses SHELXL / CIF notation, e.g. ``'-x, y+1/2, -z+1/2'``.
375 Both (A → image-of-B) and (B → image-of-A) appear, mirroring
376 SHELXL's ``.lst`` bond table where each atom lists all its neighbors.
377
378 The list is sorted by (atom1 name, atom2 name).
379
380 The method runs :meth:`~shelxfile.shelx.sdm.SDM.calc_sdm` internally;
381 it is O(N²·S) where *N* is the number of atoms and *S* is the number
382 of symmetry operations.
383
384 Parameters
385 ----------
386 with_qpeaks : bool
387 Include Q-peaks (difference-map peaks) in the bond detection.
388 Defaults to ``False``.
389
390 Returns
391 -------
392 list of :class:`~shelxfile.atoms.pairs.SymBond`
393
394 Example::
395
396 for bond in shx.atoms.full_bond_list():
397 print(bond)
398 # AL1 – O1 1.7236 Å
399 # AL1 – O2 1.7095 Å #2 [-x, y+1/2, -z+1/2]
400 # ...
401
402 # Unpack all four fields:
403 a1, a2, dist, label = shx.atoms.full_bond_list()[0]
404
405 # Only symmetry bonds:
406 sym_bonds = [b for b in shx.atoms.full_bond_list() if b.is_symmetry_bond]
407 """
408 # Late import avoids circular dependency: SDM imports Atom but not Atoms.
409 from shelxfile.shelx.sdm import SDM
410
411 sdm = SDM(self.shx)
412 sdm.calc_sdm()
413
414 seen_plain: set = set() # deduplicate intra-asym-unit bonds
415 result: List[SymBond] = []
416
417 for item in sdm.sdm_list:
418 if not item.covalent:
419 continue
420 if not with_qpeaks and (item.atom1.qpeak or item.atom2.qpeak):
421 continue
422
423 # --- compute lattice translation ---
424 x1, y1, z1 = item.atom1.x, item.atom1.y, item.atom1.z
425 x2, y2, z2 = item.atom2.x, item.atom2.y, item.atom2.z
426 n = item.symmetry_number
427 symm = self.shx.symmcards[n]
428 m = symm.matrix # 3×3 numpy array
429 t = symm.trans # 3-element array
430
431 # Position of atom1's image under symmetry op n:
432 px = m[0, 0] * x1 + m[0, 1] * y1 + m[0, 2] * z1 + t[0]
433 py = m[1, 0] * x1 + m[1, 1] * y1 + m[1, 2] * z1 + t[1]
434 pz = m[2, 0] * x1 + m[2, 1] * y1 + m[2, 2] * z1 + t[2]
435
436 # Integer lattice shift that places the image nearest to atom2:
437 h = round(px - x2)
438 k = round(py - y2)
439 l = round(pz - z2)
440
441 is_plain = (n == 0 and h == 0 and k == 0 and l == 0)
442
443 if is_plain:
444 # Deduplicate: keep only the (lower-index, higher-index) pair.
445 key = (min(item.a1, item.a2), max(item.a1, item.a2))
446 if key in seen_plain:
447 continue
448 seen_plain.add(key)
449 # Canonical ordering: lower index atom is atom1.
450 if item.a1 < item.a2:
451 a_center, a_neighbor = item.atom1, item.atom2
452 else:
453 a_center, a_neighbor = item.atom2, item.atom1
454 result.append(SymBond(a_center, a_neighbor, item.dist, ''))
455 else:
456 # Symmetry bond: atom2 bonds to image of atom1 via symm n + (h,k,l).
457 symm_label = _build_symm_label(symm, h, k, l)
458 result.append(SymBond(item.atom2, item.atom1, item.dist, symm_label, symm_number=n))
459
460 result.sort(key=lambda b: (b.atom1.fullname_short, b.atom2.fullname_short))
461 return result
462
463 def atoms_in_class(self, name: str) -> list:
464 """
465 Returns a list of atoms in residue class 'name'
466 """
467 atoms = []
468 for x in self.all_atoms:
469 if x.resiclass == name and x.name not in atoms:
470 atoms.append(x.name)
471 return atoms