| 1 |
from contextlib import suppress |
| 2 |
from typing import Union, List, Tuple, Optional |
| 3 |
|
| 4 |
import numpy as np |
| 5 |
|
| 6 |
with suppress(Exception): |
| 7 |
from shelxfile import Shelxfile |
| 8 |
from shelxfile.misc.dsrmath import atomic_distance |
| 9 |
from shelxfile.misc.elements import get_atomic_number, get_radius_from_element |
| 10 |
from shelxfile.misc.misc import split_fvar_and_parameter, ParseSyntaxError, frac_to_cart_fast, ParseUnknownParam |
| 11 |
from shelxfile.shelx.cards import PART, AFIX, RESI, CELL, Restraints |
| 12 |
|
| 13 |
|
| 14 |
class Atom(): |
| 15 |
""" |
| 16 |
An object holding all Properties of a shelxl atom plus some extra information like |
| 17 |
kartesian coordinates and element type. |
| 18 |
|
| 19 |
atomname sfac x y z sof[11] U[0.05] or U11 U22 U33 U23 U13 U12 |
| 20 |
""" |
| 21 |
|
| 22 |
_anisatomstr = '{:<5s}{:>2}{:>12.6f}{:>12.6f}{:>12.6f}{:>12.5f}{:>11.5f}{:>11.5f}' \ |
| 23 |
' {:>12.5f}{:>11.5f}{:>11.5f}{:>11.5f}' |
| 24 |
|
| 25 |
_isoatomstr = '{:<5s}{:<2}{:>10.6f} {:>10.6f} {:>9.6f} {:>9.5f} {:>9.5f}' |
| 26 |
_qpeakstr = '{:<5s}{:<2}{:>8.4f} {:>8.4f} {:>8.4f} {:>9.5f} {:<9.2f} {:<9.2f}' |
| 27 |
_fragatomstr = '{:<5s}{:>10.6f} {:>10.6f} {:>9.6f}' |
| 28 |
|
| 29 |
def __init__(self, shx: 'Shelxfile') -> None: |
| 30 |
self.shx = shx |
| 31 |
self._cell: CELL = shx.cell |
| 32 |
self.sfac_num: int = 1 |
| 33 |
self.resi: Union[RESI, None] = None |
| 34 |
self.part: PART = PART(shx, ['PART', '0']) |
| 35 |
self.afix: Union[AFIX, None] = None |
| 36 |
self._name: str = 'name' |
| 37 |
|
| 38 |
self.sof: float = 11.0 |
| 39 |
|
| 40 |
self.x: float = 0.0 |
| 41 |
self.y: float = 0.0 |
| 42 |
self.z: float = 0.0 |
| 43 |
|
| 44 |
self.xc: float = 0.0 |
| 45 |
self.yc: float = 0.0 |
| 46 |
self.zc: float = 0.0 |
| 47 |
self.qpeak: bool = False |
| 48 |
self.peak_height: float = 0.0 |
| 49 |
self.uvals: List[float] = [0.04, 0.0, 0.0, 0.0, 0.0, 0.0] |
| 50 |
self.U11, self.U22, self.U33, self.U23, self.U13, self.U12 = self.uvals |
| 51 |
self.uvals_orig: List[float] = [0.04, 0.0, 0.0, 0.0, 0.0, 0.0] |
| 52 |
self.frag_atom: bool = False |
| 53 |
self.restraints: List[Restraints] = [] |
| 54 |
self._line_numbers = None |
| 55 |
self._occupancy: float = 1.0 |
| 56 |
self.molindex: int = 0 |
| 57 |
|
| 58 |
self.symmgen: bool = False |
| 59 |
self.pivot: Optional[Atom] = None |
| 60 |
|
| 61 |
def __eq__(self, other): |
| 62 |
return self.__str__() == other.__str__() |
| 63 |
|
| 64 |
@property |
| 65 |
def atomid(self) -> int: |
| 66 |
if self.symmgen: |
| 67 |
return 0 |
| 68 |
try: |
| 69 |
return self.shx._reslist.index(self) |
| 70 |
except ValueError: |
| 71 |
return 0 |
| 72 |
|
| 73 |
@property |
| 74 |
def fullname(self) -> str: |
| 75 |
|
| 76 |
return f'{self.name}_{self.resinum}' |
| 77 |
|
| 78 |
@property |
| 79 |
def fullname_short(self) -> str: |
| 80 |
if self.resinum == 0: |
| 81 |
return self.name |
| 82 |
else: |
| 83 |
return f'{self.name}_{self.resinum}' |
| 84 |
|
| 85 |
@property |
| 86 |
def resiclass(self) -> str: |
| 87 |
return self.resi.residue_class |
| 88 |
|
| 89 |
@property |
| 90 |
def resinum(self) -> int: |
| 91 |
return self.resi.residue_number |
| 92 |
|
| 93 |
@property |
| 94 |
def chain_id(self) -> int: |
| 95 |
return self.resi.chain_id |
| 96 |
|
| 97 |
@property |
| 98 |
def fvar(self) -> int: |
| 99 |
|
| 100 |
fvar, _ = split_fvar_and_parameter(self.sof) |
| 101 |
return fvar |
| 102 |
|
| 103 |
@property |
| 104 |
def occupancy(self) -> float: |
| 105 |
|
| 106 |
_, occ = split_fvar_and_parameter(self.sof) |
| 107 |
|
| 108 |
if abs(self.fvar) == 1: |
| 109 |
return occ |
| 110 |
else: |
| 111 |
if occ > 0: |
| 112 |
occ = self._get_positive_occupancy(occ) |
| 113 |
else: |
| 114 |
occ = self._get_negative_occupancy(occ) |
| 115 |
return occ |
| 116 |
|
| 117 |
def _get_negative_occupancy(self, occ): |
| 118 |
try: |
| 119 |
occ = 1 + (self.shx.fvars[self.fvar] * occ) |
| 120 |
except IndexError: |
| 121 |
occ = 1.0 |
| 122 |
if self.shx.debug: |
| 123 |
raise ParseSyntaxError(debug=self.shx.debug, verbose=self.shx.verbose) |
| 124 |
if self.shx.verbose: |
| 125 |
print(f'*** Could not get occupancy of free variable {self.fvar} ***') |
| 126 |
return occ |
| 127 |
|
| 128 |
def _get_positive_occupancy(self, occ): |
| 129 |
try: |
| 130 |
occ = self.shx.fvars[self.fvar] * occ |
| 131 |
except IndexError: |
| 132 |
occ = 1.0 |
| 133 |
if self.shx.debug: |
| 134 |
raise ParseSyntaxError(debug=self.shx.debug, verbose=self.shx.verbose) |
| 135 |
if self.shx.verbose: |
| 136 |
print(f'*** Could not get occupancy of free variable {self.fvar} ***') |
| 137 |
return occ |
| 138 |
|
| 139 |
@occupancy.setter |
| 140 |
def occupancy(self, occ: float): |
| 141 |
self._occupancy = occ |
| 142 |
|
| 143 |
@property |
| 144 |
def is_hydrogen(self) -> bool: |
| 145 |
""" |
| 146 |
Returns True if the current atom is a hydrogen isotope. |
| 147 |
""" |
| 148 |
if self.element in {'H', 'D', 'T'}: |
| 149 |
return True |
| 150 |
else: |
| 151 |
return False |
| 152 |
|
| 153 |
@property |
| 154 |
def ishydrogen(self) -> bool: |
| 155 |
return self.is_hydrogen |
| 156 |
|
| 157 |
def set_atom_parameters(self, name: str = 'C', sfac_num: int = 1, coords: List[float] = None, part: PART = None, |
| 158 |
afix: AFIX = None, resi: RESI = None, site_occupation: float = 11.0, |
| 159 |
uvals: (list, tuple) = None, |
| 160 |
symmgen: bool = False): |
| 161 |
""" |
| 162 |
Sets atom properties manually if not parsed from a SHELXL file. |
| 163 |
""" |
| 164 |
self.name = name |
| 165 |
self.sfac_num = sfac_num |
| 166 |
self.frac_coords = coords |
| 167 |
self.x, self.y, self.z = coords[0], coords[1], coords[2] |
| 168 |
self.xc, self.yc, self.zc = frac_to_cart_fast(self.x, self.y, self.z, self._cell) |
| 169 |
self.part = part |
| 170 |
self.afix = afix |
| 171 |
self.resi = resi |
| 172 |
self.sof = site_occupation |
| 173 |
self.uvals = uvals |
| 174 |
self.U11, self.U22, self.U33, self.U23, self.U13, self.U12 = uvals |
| 175 |
self.symmgen = symmgen |
| 176 |
|
| 177 |
def set_uvals(self, uvals: List[float]) -> None: |
| 178 |
""" |
| 179 |
Sets u values and checks if a free variable was used. |
| 180 |
""" |
| 181 |
self.uvals = uvals |
| 182 |
|
| 183 |
|
| 184 |
if uvals[2] != 0.0: |
| 185 |
|
| 186 |
for n, u in enumerate(uvals): |
| 187 |
if abs(u) > 4.0: |
| 188 |
fvar, uval = split_fvar_and_parameter(u) |
| 189 |
|
| 190 |
self.shx.fvars.set_fvar_usage(fvar) |
| 191 |
else: |
| 192 |
|
| 193 |
if abs(uvals[0]) > 4.0: |
| 194 |
fvar, uval = split_fvar_and_parameter(uvals[0]) |
| 195 |
self.shx.fvars.set_fvar_usage(fvar) |
| 196 |
self.U11, self.U22, self.U33, self.U23, self.U13, self.U12 = self.uvals |
| 197 |
|
| 198 |
def parse_line(self, atline: List, list_of_lines: List, part: PART, afix: AFIX, resi: RESI) -> None: |
| 199 |
""" |
| 200 |
Parses the text line of an atom from SHELXL to initialize the atom parameters. |
| 201 |
""" |
| 202 |
uvals = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] |
| 203 |
self.name = atline[0][:4] |
| 204 |
for n, u in enumerate(atline[6:12]): |
| 205 |
uvals[n] = float(u) |
| 206 |
self.uvals_orig = uvals[:] |
| 207 |
self.set_uvals(uvals) |
| 208 |
self._line_numbers = list_of_lines |
| 209 |
self.part = part |
| 210 |
self.afix = afix |
| 211 |
self.resi = resi |
| 212 |
self._get_part_and_occupation(atline) |
| 213 |
self.x, self.y, self.z = self._get_atom_coordinates(atline) |
| 214 |
self.xc, self.yc, self.zc = frac_to_cart_fast(self.x, self.y, self.z, self._cell) |
| 215 |
if abs(self.uvals[1]) > 0.0 and abs( |
| 216 |
self.uvals[2]) < 0.000001 and self.shx.hklf: |
| 217 |
self.peak_height = uvals[1] |
| 218 |
self.qpeak = True |
| 219 |
if self.shx.end: |
| 220 |
self.qpeak = True |
| 221 |
self.sfac_num = int(atline[1]) |
| 222 |
self.shx.fvars.set_fvar_usage(self.fvar) |
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
@property |
| 229 |
def ucif(self) -> np.ndarray: |
| 230 |
""" |
| 231 |
Returns U(cif) as a symmetric 3×3 numpy array. |
| 232 |
SHELXL stores U11 U22 U33 U23 U13 U12. |
| 233 |
""" |
| 234 |
return self.set_ucif(self.uvals) |
| 235 |
|
| 236 |
@property |
| 237 |
def ustar(self) -> np.ndarray: |
| 238 |
""" |
| 239 |
Returns U(star) = N @ U(cif) @ N.T using numpy. |
| 240 |
N = diag(a*, b*, c*) |
| 241 |
""" |
| 242 |
N = np.diag([self._cell.astar, self._cell.bstar, self._cell.cstar]) |
| 243 |
return N @ self.ucif @ N.T |
| 244 |
|
| 245 |
@property |
| 246 |
def u_cart(self) -> np.ndarray: |
| 247 |
""" |
| 248 |
Returns U(cart) = A @ U(star) @ A.T using numpy. |
| 249 |
A is the orthogonalisation matrix. |
| 250 |
""" |
| 251 |
A = np.array(self._cell.o.values, dtype=float) |
| 252 |
return A @ self.ustar @ A.T |
| 253 |
|
| 254 |
@property |
| 255 |
def ueq(self) -> float: |
| 256 |
return self.set_ueq(self.uvals) |
| 257 |
|
| 258 |
@property |
| 259 |
def Uiso(self) -> float: |
| 260 |
"""Isotropic displacement parameter. |
| 261 |
|
| 262 |
For riding hydrogen atoms whose ``uvals[0]`` is negative (SHELXL |
| 263 |
encoding ``-factor``), returns ``abs(factor) × pivot.ueq``. |
| 264 |
For all other atoms, returns :attr:`ueq` (trace of U_cart / 3). |
| 265 |
""" |
| 266 |
if self.uvals[0] < 0 and self.pivot is not None: |
| 267 |
return abs(self.uvals[0]) * self.pivot.ueq |
| 268 |
return self.ueq |
| 269 |
|
| 270 |
def set_ueq(self, uvals: List[float]) -> float: |
| 271 |
|
| 272 |
if uvals[0] > 0 and not sum(uvals[2:]): |
| 273 |
ueq = uvals[0] |
| 274 |
else: |
| 275 |
ty |
| 276 |
ueq = float(np.trace(self.u_cart)) / 3 |
| 277 |
return ueq |
| 278 |
|
| 279 |
def set_ucif(self, uvals: List[float]) -> np.ndarray: |
| 280 |
""" |
| 281 |
Returns U(cif) as a symmetric 3×3 numpy array. |
| 282 |
|
| 283 |
SHELXL convention: U11 U22 U33 U23 U13 U12 |
| 284 |
U(star) = N @ U(cif) @ N.T |
| 285 |
U(cart) = A @ U(star) @ A.T |
| 286 |
U(star) = R @ U(star) @ R.T (symmetry transformation) |
| 287 |
U(cif) = N⁻¹ @ U(star) @ (N⁻¹).T |
| 288 |
""" |
| 289 |
U11, U22, U33, U23, U13, U12 = uvals |
| 290 |
return np.array([[U11, U12, U13], |
| 291 |
[U12, U22, U23], |
| 292 |
[U13, U23, U33]], dtype=float) |
| 293 |
|
| 294 |
def transform_u_by_symmetry(self, symmetry_number: int) -> tuple: |
| 295 |
""" |
| 296 |
Transforms U(cif) values by the given symmetry operation. |
| 297 |
Implements: U*(new) = R @ U*(old) @ R.T |
| 298 |
followed by back-conversion to U(cif). |
| 299 |
""" |
| 300 |
R = self.shx.symmcards[symmetry_number].matrix |
| 301 |
N = np.diag([self._cell.astar, self._cell.bstar, self._cell.cstar]) |
| 302 |
N_inv = np.linalg.inv(N) |
| 303 |
Ustar = N @ self.ucif @ N.T |
| 304 |
Ustar_n = R @ Ustar @ R.T |
| 305 |
Ucif_n = N_inv @ Ustar_n @ N_inv.T |
| 306 |
return (Ucif_n[0, 0], Ucif_n[1, 1], Ucif_n[2, 2], |
| 307 |
Ucif_n[1, 2], Ucif_n[0, 2], Ucif_n[0, 1]) |
| 308 |
|
| 309 |
def _get_part_and_occupation(self, atline: List[str]) -> None: |
| 310 |
|
| 311 |
if self.part.sof != 11.0: |
| 312 |
if self.afix and self.afix.sof: |
| 313 |
if self.afix.index > self.part.index: |
| 314 |
self.sof = self.afix.sof |
| 315 |
else: |
| 316 |
self.sof = self.part.sof |
| 317 |
elif self.afix and self.afix.sof: |
| 318 |
if self.part.sof != 11.0: |
| 319 |
if self.part.index > self.afix.index: |
| 320 |
self.sof = self.part.sof |
| 321 |
else: |
| 322 |
self.sof = self.afix.sof |
| 323 |
elif len(atline) > 5: |
| 324 |
self.sof = float(atline[5]) |
| 325 |
|
| 326 |
def _get_atom_coordinates(self, atline: List[str]) -> Tuple[float, float, float]: |
| 327 |
try: |
| 328 |
x, y, z = [float(x) for x in atline[2:5]] |
| 329 |
except ValueError as e: |
| 330 |
if self.shx.debug or self.shx.verbose: |
| 331 |
print(e, 'Line:', self._line_numbers[-1]) |
| 332 |
raise ParseUnknownParam(debug=self.shx.debug, verbose=self.shx.verbose) |
| 333 |
else: |
| 334 |
x, y, z = 0.1, 0.1, 0.1 |
| 335 |
if abs(x) > 4: |
| 336 |
fvar, x = split_fvar_and_parameter(x) |
| 337 |
self.shx.fvars.set_fvar_usage(fvar) |
| 338 |
if abs(y) > 4: |
| 339 |
fvar, y = split_fvar_and_parameter(y) |
| 340 |
self.shx.fvars.set_fvar_usage(fvar) |
| 341 |
if abs(z) > 4: |
| 342 |
fvar, z = split_fvar_and_parameter(z) |
| 343 |
self.shx.fvars.set_fvar_usage(fvar) |
| 344 |
return x, y, z |
| 345 |
|
| 346 |
@property |
| 347 |
def is_anisotropic(self) -> bool: |
| 348 |
""" |
| 349 |
Returns True if the atom has anisotropic displacement parameters. |
| 350 |
|
| 351 |
In SHELXL encoding ``uvals = [U11, U22, U33, U23, U13, U12]``. For an |
| 352 |
isotropic atom ``uvals[1:]`` are all zero; for a Q-peak ``uvals[2]`` is |
| 353 |
also zero (only ``uvals[1]`` carries the peak height). Therefore |
| 354 |
``uvals[2] != 0.0`` (i.e. U33 is non-zero) is the exact discriminator |
| 355 |
for a genuine anisotropic atom — no sum, no abs, no list needed. |
| 356 |
""" |
| 357 |
return self.uvals[2] != 0.0 |
| 358 |
|
| 359 |
@property |
| 360 |
def is_isotropic(self) -> bool: |
| 361 |
return not self.is_anisotropic |
| 362 |
|
| 363 |
@property |
| 364 |
def uvals_as_list(self) -> List[list[float]]: |
| 365 |
U11, U22, U33, U23, U13, U12 = self.uvals |
| 366 |
U21 = U12 |
| 367 |
U32 = U23 |
| 368 |
U31 = U13 |
| 369 |
return [[U11, U12, U13], [U21, U22, U23], [U31, U32, U33]] |
| 370 |
|
| 371 |
def is_npd(self) -> bool: |
| 372 |
"""Returns True if the ADP matrix is not positive definite.""" |
| 373 |
eigenvalues = np.linalg.eigvalsh(self.u_cart) |
| 374 |
return bool(np.any(eigenvalues <= 0)) |
| 375 |
|
| 376 |
@property |
| 377 |
def element(self) -> str: |
| 378 |
""" |
| 379 |
Chemical element character |
| 380 |
""" |
| 381 |
return self.shx.sfac2elem(self.sfac_num).capitalize() |
| 382 |
|
| 383 |
@element.setter |
| 384 |
def element(self, new_element: str) -> None: |
| 385 |
""" |
| 386 |
Sets the element type of atom. |
| 387 |
""" |
| 388 |
sfac = self.shx.elem2sfac(new_element) |
| 389 |
if sfac == 0: |
| 390 |
self.shx.sfac_table.add_element(new_element) |
| 391 |
sfac = self.shx.elem2sfac(new_element) |
| 392 |
self.sfac_num = sfac |
| 393 |
|
| 394 |
@property |
| 395 |
def name(self) -> str: |
| 396 |
return self._name |
| 397 |
|
| 398 |
@name.setter |
| 399 |
def name(self, new_name: str) -> None: |
| 400 |
name_has_residue_number = new_name.split('_')[-1].isdigit() |
| 401 |
if '_' in new_name and name_has_residue_number: |
| 402 |
print('*** Illegal atom name. Use a name without a residue number. ***') |
| 403 |
return |
| 404 |
self._name = new_name |
| 405 |
|
| 406 |
@property |
| 407 |
def an(self) -> int: |
| 408 |
return get_atomic_number(self.element) |
| 409 |
|
| 410 |
@property |
| 411 |
def radius(self) -> float: |
| 412 |
""" |
| 413 |
Returns the atomic covalence radius in angstrom. |
| 414 |
""" |
| 415 |
return get_radius_from_element(self.element) |
| 416 |
|
| 417 |
def __iter__(self): |
| 418 |
for x in self.__repr__().split(): |
| 419 |
yield x |
| 420 |
|
| 421 |
def __repr__(self) -> str: |
| 422 |
return 'Atom ID: {}'.format(self.atomid) |
| 423 |
|
| 424 |
def __str__(self) -> str: |
| 425 |
""" |
| 426 |
Returns a text line of the Atom with SHELXL syntax. |
| 427 |
:return: SHELX-formated atom string |
| 428 |
""" |
| 429 |
if self.afix and self.shx.frag: |
| 430 |
|
| 431 |
return Atom._fragatomstr.format(self.name, self.x, self.y, self.z) |
| 432 |
else: |
| 433 |
if self.is_anisotropic: |
| 434 |
|
| 435 |
try: |
| 436 |
return Atom._anisatomstr.format(self.name, self.sfac_num, self.x, self.y, self.z, self.sof, |
| 437 |
*self.uvals) |
| 438 |
except IndexError: |
| 439 |
return 'REM Error in U values.' |
| 440 |
else: |
| 441 |
|
| 442 |
if self.qpeak: |
| 443 |
return Atom._qpeakstr.format(self.name, self.sfac_num, self.x, self.y, self.z, self.sof, 0.04, |
| 444 |
self.peak_height) |
| 445 |
try: |
| 446 |
return Atom._isoatomstr.format(self.name, self.sfac_num, self.x, self.y, self.z, self.sof, |
| 447 |
*self.uvals) |
| 448 |
except IndexError: |
| 449 |
return Atom._isoatomstr.format(self.name, self.sfac_num, self.x, self.y, self.z, self.sof, 0.04) |
| 450 |
|
| 451 |
@property |
| 452 |
def index(self) -> int: |
| 453 |
|
| 454 |
return self.shx.index_of(self) |
| 455 |
|
| 456 |
@property |
| 457 |
def frac_coords(self) -> tuple: |
| 458 |
return self.x, self.y, self.z |
| 459 |
|
| 460 |
@frac_coords.setter |
| 461 |
def frac_coords(self, coords: List[float]): |
| 462 |
self.x, self.y, self.z = coords |
| 463 |
|
| 464 |
@property |
| 465 |
def cart_coords(self) -> Tuple[float, float, float]: |
| 466 |
return self.xc, self.yc, self.zc |
| 467 |
|
| 468 |
def delete(self): |
| 469 |
""" |
| 470 |
Delete atom(s) in the file. |
| 471 |
""" |
| 472 |
del self.shx.atoms[self.index] |
| 473 |
self.shx.atoms._atomsdict.clear() |
| 474 |
|
| 475 |
def to_isotropic(self) -> None: |
| 476 |
""" |
| 477 |
Makes the current atom isotropic. |
| 478 |
""" |
| 479 |
self.uvals = [0.04, 0.0, 0.0, 0.0, 0.0, 0.0] |
| 480 |
|
| 481 |
def find_atoms_around(self, dist=1.2, only_part=0) -> List['Atom']: |
| 482 |
""" |
| 483 |
Finds atoms around the current atom. |
| 484 |
""" |
| 485 |
found = [] |
| 486 |
for at in self.shx.atoms: |
| 487 |
if atomic_distance([self.x, self.y, self.z], [at.x, at.y, at.z], self._cell) < dist \ |
| 488 |
and self != at and at.part.n == only_part and not at.qpeak: |
| 489 |
|
| 490 |
found.append(at) |
| 491 |
return found |
| 492 |
|
| 493 |
r''' |
| 494 |
def get_pivot_atom(self) -> Union['Atom', None]: |
| 495 |
""" |
| 496 |
Returns the pivot atom (C1) of a riding hydrogen atom e.g. (H1, H2, or H3). |
| 497 |
/H1 |
| 498 |
-C1--H2 |
| 499 |
\H3 |
| 500 |
""" |
| 501 |
pivots = self.find_atoms_around(dist=1.2) |
| 502 |
return pivots[0] if pivots and self.afix.mn else None''' |