| 1 |
|
| 2 |
ß |
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
__doc__ = """ |
| 13 |
This is a full implementation of the SHELXL file syntax. Additionally it is able to edit SHELX properties with Python. |
| 14 |
The implementation is Python3-only and supports SHELXL after 2017 (You should not use old versions anyway). |
| 15 |
|
| 16 |
The parser is quiet about the most errors unless you enable debug or verbose during initialization. |
| 17 |
The parser will try to read the SHELX file even if it has syntax errors, but if for example, the SFAC and UNIT |
| 18 |
instruction is not consistent it will fail. |
| 19 |
""" |
| 20 |
|
| 21 |
import re |
| 22 |
import sys |
| 23 |
from contextlib import suppress |
| 24 |
from pathlib import Path |
| 25 |
from typing import Union, List, Optional |
| 26 |
|
| 27 |
from shelxfile.atoms.atom import Atom |
| 28 |
from shelxfile.atoms.atoms import Atoms |
| 29 |
from shelxfile.cif.cif_write import CifFile |
| 30 |
from shelxfile.misc.dsrmath import Array |
| 31 |
from shelxfile.misc.elements import weight_from_symbol |
| 32 |
|
| 33 |
from shelxfile.misc.misc import ParseOrderError, ParseNumError, ParseUnknownParam, \ |
| 34 |
multiline_test, dsr_regex, wrap_line, ParseSyntaxError, cart_to_frac |
| 35 |
from shelxfile.refine.refine import ShelxlRefine |
| 36 |
from shelxfile.shelx.cards import ACTA, FVAR, FVARs, REM, BOND, Restraints, DEFS, NCSY, ISOR, FLAT, \ |
| 37 |
BUMP, DFIX, DANG, SADI, SAME, RIGU, SIMU, DELU, CHIV, EADP, EXYZ, DAMP, HFIX, HKLF, SUMP, SYMM, LSCycles, \ |
| 38 |
SFACTable, UNIT, BASF, TWIN, WGHT, BLOC, SymmCards, CONN, CONF, BIND, DISP, GRID, HTAB, MERG, FRAG, FREE, FMAP, \ |
| 39 |
MOVE, PLAN, PRIG, RTAB, SHEL, SIZE, SPEC, STIR, TWST, WIGL, WPDB, XNPD, ZERR, CELL, LATT, MORE, MPLA, AFIX, PART, \ |
| 40 |
RESI, ABIN, ANIS, Residues, SWAT, Command, Restraint |
| 41 |
from shelxfile.shelx.sdm import SDM |
| 42 |
from shelxfile.version import VERSION |
| 43 |
|
| 44 |
__version__ = VERSION |
| 45 |
|
| 46 |
""" |
| 47 |
TODO: |
| 48 |
- Handle BEDE & LONE plus their results |
| 49 |
- Rotate ellipsoids with kabsch |
| 50 |
- killall.Q, killall.C |
| 51 |
- Q-peak printing is wrong: Q1 1 0.9828 1.1159 0.3148 11.00000 0.04 0.00 |
| 52 |
- Write out parts and afix in grow mode |
| 53 |
- Delete atoms (H) in AFIX -> delete entire afix group |
| 54 |
- Is backup file and reccovery from failed refinement working? |
| 55 |
------------------------------------------------------------ |
| 56 |
- add remove_hydrogen_atoms(atom) method. |
| 57 |
- shx.remove_all_H([list of atoms], or all) |
| 58 |
- bond list |
| 59 |
- implement an add_afix(afixm, afixn, atoms, frag_fend=False, position=None, afix_options=None) |
| 60 |
default position is directly behind FVAR or FRAG/FEND if enabled |
| 61 |
- will read in lst file after refinement to fill shx.lst_file properties. |
| 62 |
- shx.move_in_part([list of atoms]) |
| 63 |
- shx.move_in_resi([list of atoms]) |
| 64 |
- shx.sort.residue(3) (low priority) |
| 65 |
- shx.lst_file.residuals -> density, r-values, goof, movements, bad reflections |
| 66 |
bad restraints, shelx *** errors |
| 67 |
- shx.unused_atom_name('C') -> get a carbon atom with unused number |
| 68 |
- shx.sort -> sort file (low priority) |
| 69 |
""" |
| 70 |
|
| 71 |
SHX_CARDS = ('TITL', 'CELL', 'ZERR', 'LATT', 'SYMM', 'SFAC', 'UNIT', 'LIST', 'L.S.', 'CGLS', |
| 72 |
'BOND', 'FMAP', 'PLAN', 'TEMP', 'ACTA', 'CONF', 'SIMU', 'RIGU', 'WGHT', 'FVAR', |
| 73 |
'DELU', 'SAME', 'DISP', 'LAUE', 'REM ', 'MORE', 'TIME', 'END ', 'HKLF', 'OMIT', |
| 74 |
'SHEL', 'BASF', 'TWIN', 'EXTI', 'SWAT', 'HOPE', 'MERG', 'SPEC', 'RESI', 'MOVE', |
| 75 |
'ANIS', 'AFIX', 'HFIX', 'FRAG', 'FEND', 'EXYZ', 'EADP', 'EQIV', 'CONN', 'BIND', |
| 76 |
'FREE', 'DFIX', 'BUMP', 'SADI', 'CHIV', 'FLAT', 'DEFS', 'ISOR', 'NCSY', 'SUMP', |
| 77 |
'BLOC', 'DAMP', 'STIR', 'MPLA', 'RTAB', 'HTAB', 'SIZE', 'WPDB', 'GRID', 'MOLE', |
| 78 |
'XNPD', 'REST', 'CHAN', 'FLAP', 'RNUM', 'SOCC', 'PRIG', 'WIGL', 'RANG', 'TANG', |
| 79 |
'ADDA', 'STAG', 'NEUT', 'ABIN', 'ANSC', 'ANSR', 'NOTR', 'TWST', 'PART', 'DANG', |
| 80 |
'BEDE', 'LONE', 'REM', 'END') |
| 81 |
|
| 82 |
|
| 83 |
class Shelxfile(): |
| 84 |
""" |
| 85 |
Class for data from a SHELXL res file. Includes Atoms, cards and unit cell. |
| 86 |
""" |
| 87 |
_r1_regex = re.compile(r'^REM\s+R1\s+=', re.IGNORECASE) |
| 88 |
_wr2_regex = re.compile(r'^REM\s+wR2\s+=', re.IGNORECASE) |
| 89 |
_parameters_regex = re.compile(r'^REM\s+\d+\s+parameters\s+refined', re.IGNORECASE) |
| 90 |
_diff_peak_regex = re.compile(r'^REM\sHighest\sdifference', re.IGNORECASE) |
| 91 |
_goof_regex = re.compile(r'^REM\swR2\s=\s.*,\sGooF', re.IGNORECASE) |
| 92 |
_spgrp_regex = re.compile(r'^REM\s+\S+\s+in\s+\S+', re.IGNORECASE) |
| 93 |
|
| 94 |
def __init__(self, verbose: bool = False, debug: bool = False) -> None: |
| 95 |
if debug and verbose: |
| 96 |
raise ValueError("Either 'verbose' or 'debug' allowed, not both.") |
| 97 |
self.debug = False |
| 98 |
self.verbose = False |
| 99 |
if debug: |
| 100 |
self.debug = True |
| 101 |
if verbose: |
| 102 |
self.verbose = True |
| 103 |
|
| 104 |
self.restraint_errors: List[str] = [] |
| 105 |
self.temp_in_kelvin: float = 0.0 |
| 106 |
self.shelx_max_line_length: int = 79 |
| 107 |
self.cell: Optional[CELL] = None |
| 108 |
self.ansc: List[float] = [] |
| 109 |
self.abin: Optional[ABIN] = None |
| 110 |
self.acta: Optional[ACTA] = None |
| 111 |
self.fmap: Optional[FMAP] = None |
| 112 |
self.xnpd: Optional[XNPD] = None |
| 113 |
self.wpdb: Optional[WPDB] = None |
| 114 |
self.wigl: Optional[WIGL] = None |
| 115 |
self.temp: Union[int, float] = 20 |
| 116 |
self.swat: Optional[SWAT] = None |
| 117 |
self.stir: Optional[STIR] = None |
| 118 |
self.spec: Optional[SPEC] = None |
| 119 |
self.twst: Optional[TWST] = None |
| 120 |
self.plan: Optional[PLAN] = None |
| 121 |
self.prig: Optional[PRIG] = None |
| 122 |
self.merg: Optional[MERG] = None |
| 123 |
self.more: Optional[MORE] = None |
| 124 |
self.move: Optional[MOVE] = None |
| 125 |
self.defs: Optional[DEFS] = None |
| 126 |
self.zerr: Optional[ZERR] = None |
| 127 |
self.wght: Optional[WGHT] = None |
| 128 |
self.frag: Optional[FRAG] = None |
| 129 |
self.twin: Optional[TWIN] = None |
| 130 |
self.basf: Optional[BASF] = None |
| 131 |
self.latt: Optional[LATT] = None |
| 132 |
self.anis: Optional[ANIS] = None |
| 133 |
self.damp: Optional[DAMP] = None |
| 134 |
self.unit: Optional[UNIT] = None |
| 135 |
self.size: Optional[SIZE] = None |
| 136 |
self.htab: Optional[HTAB] = None |
| 137 |
self.shel: Optional[SHEL] = None |
| 138 |
self.mpla: Optional[MPLA] = None |
| 139 |
self.hklf: Optional[HKLF] = None |
| 140 |
self.grid: Optional[GRID] = None |
| 141 |
self.conn: Optional[CONN] = None |
| 142 |
self.conf: Optional[CONF] = None |
| 143 |
self.afix: Optional[AFIX] = None |
| 144 |
self.rtab: List[RTAB] = [] |
| 145 |
self.omit: List[str] = [] |
| 146 |
self.free: List[FREE] = [] |
| 147 |
self.eqiv: List[str] = [] |
| 148 |
self.bonds: List[BOND] = [] |
| 149 |
self.disp: List[BOND] = [] |
| 150 |
self.bind: List[BIND] = [] |
| 151 |
self.bloc: List[BLOC] = [] |
| 152 |
self.part: PART = PART(self, ['PART', '0']) |
| 153 |
self.resi: RESI = RESI(self, ['RESI', '0']) |
| 154 |
self.residues = Residues(self) |
| 155 |
self.dsrlines: List[str] = [] |
| 156 |
self.dsrline_nums: List[int] = [] |
| 157 |
self.symmcards: SymmCards = SymmCards(self) |
| 158 |
self.hfixes: List[HFIX] = [] |
| 159 |
self.sump: List[SUMP] = [] |
| 160 |
self.wght_suggested: Optional[WGHT] = None |
| 161 |
self.Z: int = 1 |
| 162 |
self.titl: str = "" |
| 163 |
self.exti: float = 0.0 |
| 164 |
self.ansr: float = 0.001 |
| 165 |
self.rem: List[REM] = [] |
| 166 |
self.atoms: Atoms = Atoms(self) |
| 167 |
self.fvars: FVARs = FVARs(self) |
| 168 |
self.restraints: Restraints = Restraints() |
| 169 |
self.sfac_table: SFACTable = SFACTable(self) |
| 170 |
self.cycles: Optional[LSCycles] = None |
| 171 |
self.R1: Optional[float] = None |
| 172 |
self.wr2: Optional[float] = None |
| 173 |
self.goof: Optional[float] = None |
| 174 |
self.rgoof: Optional[float] = None |
| 175 |
self.space_group: Optional[str] = None |
| 176 |
self.data: Optional[int] = None |
| 177 |
self.parameters: Optional[int] = None |
| 178 |
self.dat_to_param: Optional[float] = None |
| 179 |
self.num_restraints: Optional[int] = None |
| 180 |
self.highest_peak: Optional[float] = None |
| 181 |
self.deepest_hole: Optional[float] = None |
| 182 |
self.formula_weight: Optional[float] = None |
| 183 |
self.end: bool = False |
| 184 |
self.maxsof: float = 1.0 |
| 185 |
self.delete_on_write: set = set() |
| 186 |
self.wavelength: float = 0.0 |
| 187 |
self.global_sadi: Optional[int] = None |
| 188 |
self.list: int = 0 |
| 189 |
self.theta_full: float = 0.0 |
| 190 |
self.error_line_num: int = -1 |
| 191 |
self.resfile: Optional[Path] = None |
| 192 |
self._reslist: List[Union[str, Command, SFACTable, FVARs, Atom, SYMM]] = [] |
| 193 |
|
| 194 |
def write_shelx_file(self, filename: Union[str, Path, None] = None) -> None: |
| 195 |
if not self._reslist: |
| 196 |
print('*** No file was loaded for writing. ***') |
| 197 |
return None |
| 198 |
if not filename: |
| 199 |
filename = self.resfile |
| 200 |
if isinstance(filename, str): |
| 201 |
filename = Path(filename) |
| 202 |
with open(filename, 'w') as f: |
| 203 |
for num, line in enumerate(self._reslist): |
| 204 |
if num in self.delete_on_write: |
| 205 |
if self.debug: |
| 206 |
|
| 207 |
pass |
| 208 |
continue |
| 209 |
if line == '': |
| 210 |
continue |
| 211 |
|
| 212 |
line = "\n".join([wrap_line(x) for x in str(line).split("\n")]) |
| 213 |
f.write(str(line) + '\n') |
| 214 |
if self.verbose or self.debug: |
| 215 |
print(f'*** File successfully written to {filename.resolve()} ***') |
| 216 |
|
| 217 |
def read_file(self, resfile: Union[Path, str]) -> None: |
| 218 |
""" |
| 219 |
Read input from a file path. |
| 220 |
""" |
| 221 |
self.__init__(debug=self.debug, verbose=self.verbose) |
| 222 |
if isinstance(resfile, str): |
| 223 |
resfile = Path(resfile) |
| 224 |
self.resfile = resfile.resolve() |
| 225 |
if self.debug: |
| 226 |
print(f'Resfile is: {resfile}') |
| 227 |
try: |
| 228 |
self._reslist: List = resfile.read_text().splitlines(keepends=False) |
| 229 |
self._test_if_file_is_valid(resfile) |
| 230 |
except UnicodeDecodeError: |
| 231 |
if self.debug or self.verbose: |
| 232 |
print(f'*** Unable to read file {resfile} ***') |
| 233 |
return |
| 234 |
self._find_included_files() |
| 235 |
self.parse_cards() |
| 236 |
|
| 237 |
def read_string(self, resfile_string: str): |
| 238 |
""" |
| 239 |
Read input as string. |
| 240 |
This will not read files included with "+filename" syntax! |
| 241 |
""" |
| 242 |
self.__init__(debug=self.debug, verbose=self.verbose) |
| 243 |
self._reslist = resfile_string.splitlines(keepends=False) |
| 244 |
self.parse_cards() |
| 245 |
|
| 246 |
def parse_cards(self) -> None: |
| 247 |
try: |
| 248 |
self._parse_cards() |
| 249 |
except Exception as e: |
| 250 |
if self.debug or self.verbose: |
| 251 |
self.show_line_where_error_occured(e) |
| 252 |
if self.debug: |
| 253 |
raise |
| 254 |
else: |
| 255 |
return |
| 256 |
self.restraint_errors = self._assign_atoms_to_restraints() |
| 257 |
|
| 258 |
def _assign_atoms_to_restraints(self) -> List[str]: |
| 259 |
warnings = [] |
| 260 |
|
| 261 |
|
| 262 |
|
| 263 |
populated_resi_nums_by_class: dict = {} |
| 264 |
for atom in self.atoms: |
| 265 |
cls = atom.resiclass |
| 266 |
num = atom.resinum |
| 267 |
if cls not in populated_resi_nums_by_class: |
| 268 |
populated_resi_nums_by_class[cls] = set() |
| 269 |
populated_resi_nums_by_class[cls].add(num) |
| 270 |
|
| 271 |
empty_residues = [] |
| 272 |
for resi in self.residues.all_residues: |
| 273 |
if resi.residue_number not in populated_resi_nums_by_class.get(resi.residue_class, set()): |
| 274 |
empty_residues.append(f'{resi.residue_class} {resi.residue_number}') |
| 275 |
if empty_residues: |
| 276 |
warnings.append(f'*** Empty residue(s) detected (no atoms): {", ".join(empty_residues)} ***') |
| 277 |
for restraint in self.restraints: |
| 278 |
bad_atoms = [] |
| 279 |
for restraint_atom in restraint.atoms: |
| 280 |
if restraint_atom in ('>', '<', '='): |
| 281 |
continue |
| 282 |
if (restraint.residue_class or sum(restraint.residue_number) > 0) and '_' not in restraint_atom: |
| 283 |
populated_nums = populated_resi_nums_by_class.get(restraint.residue_class, set()) |
| 284 |
for num in restraint.residue_number: |
| 285 |
|
| 286 |
|
| 287 |
if restraint.residue_class and num not in populated_nums: |
| 288 |
continue |
| 289 |
self.does_atom_exist(f'{restraint_atom}_{num}', bad_atoms, f'{restraint_atom}_{num}') |
| 290 |
elif '_' in restraint_atom: |
| 291 |
self.does_atom_exist(f'{restraint_atom}', bad_atoms, restraint_atom) |
| 292 |
else: |
| 293 |
self.does_atom_exist(f'{restraint_atom}_{0}', bad_atoms, restraint_atom) |
| 294 |
if bad_atoms: |
| 295 |
sorted_atoms = list(set(bad_atoms)) |
| 296 |
sorted_atoms.sort() |
| 297 |
warnings.append(f'*** Unknown atom{"s" if len(bad_atoms) > 0 else ""} in restraint: {restraint}, ' |
| 298 |
f'line {restraint.index + 1} ***') |
| 299 |
warnings.append(f'*** Atom list has no --> {", ".join(sorted_atoms)} ***') |
| 300 |
bad_atoms.clear() |
| 301 |
if restraint.residue_class and sum(restraint.residue_number) == 0: |
| 302 |
warnings.append(f"*** Restraint '{restraint}', line {restraint.index + 1}, " |
| 303 |
f"has a residue class, but no residues are defined. ***") |
| 304 |
if self.debug or self.verbose: |
| 305 |
print('\n'.join(warnings)) |
| 306 |
return warnings |
| 307 |
|
| 308 |
def does_atom_exist(self, atom_name: str, bad_atoms: List[str], restraint_atom: str): |
| 309 |
residue_number_is_wildcard = '_' in atom_name and atom_name.split('_')[-1] == '*' |
| 310 |
if atom_name.startswith('$'): |
| 311 |
return None |
| 312 |
elif residue_number_is_wildcard: |
| 313 |
for num in self.residues.residue_numbers.keys(): |
| 314 |
residue_atom = f"{atom_name.split('_')[0]}_{num}" |
| 315 |
if not self.atoms.get_atom_by_name(residue_atom): |
| 316 |
bad_atoms.append(residue_atom) |
| 317 |
else: |
| 318 |
if not self.atoms.get_atom_by_name(atom_name): |
| 319 |
bad_atoms.append(restraint_atom) |
| 320 |
|
| 321 |
def _test_if_file_is_valid(self, resfile: Path) -> None: |
| 322 |
if len(self._reslist) < 20 and (self.debug or self.verbose): |
| 323 |
print('*** Not a SHELXL file: {} ***'.format(resfile)) |
| 324 |
if self.debug: |
| 325 |
sys.exit() |
| 326 |
|
| 327 |
def show_line_where_error_occured(self, e): |
| 328 |
try: |
| 329 |
print(f'Error near:\n {self._reslist[self.error_line_num]}') |
| 330 |
except IndexError: |
| 331 |
pass |
| 332 |
print(e) |
| 333 |
print(f"*** Syntax error found in file {self.resfile}, line {self.error_line_num + 1} ***") |
| 334 |
|
| 335 |
def _find_included_files(self) -> None: |
| 336 |
|
| 337 |
includefiles = [] |
| 338 |
for line_num, line in enumerate(self._reslist): |
| 339 |
if line.startswith('+'): |
| 340 |
try: |
| 341 |
file_included_in_includefile = self._read_included_file(includefiles, line) |
| 342 |
if file_included_in_includefile: |
| 343 |
for line_num_includefile, include_line in enumerate(file_included_in_includefile): |
| 344 |
reslist_position = line_num + 1 + line_num_includefile |
| 345 |
|
| 346 |
|
| 347 |
|
| 348 |
|
| 349 |
|
| 350 |
|
| 351 |
self._reslist.insert(reslist_position, include_line) |
| 352 |
continue |
| 353 |
except IndexError: |
| 354 |
if self.debug or self.verbose: |
| 355 |
print(f'*** CANNOT READ INCLUDE FILE {line} ***') |
| 356 |
|
| 357 |
|
| 358 |
def _read_included_file(self, includefiles: List[str], line: str): |
| 359 |
include_filename: Path = self.resfile.resolve().parent.joinpath(line[1:]) |
| 360 |
|
| 361 |
if include_filename.name in includefiles: |
| 362 |
raise ValueError('*** Recoursive include files detected! ***') |
| 363 |
includefiles.append(include_filename.name) |
| 364 |
try: |
| 365 |
newfile = include_filename.read_text().splitlines(keepends=False) |
| 366 |
except IOError as e: |
| 367 |
if self.debug or self.verbose: |
| 368 |
print(e) |
| 369 |
print(f'*** CANNOT OPEN NESTED INPUT FILE {include_filename} ***') |
| 370 |
return [] |
| 371 |
return newfile |
| 372 |
|
| 373 |
def reload(self) -> None: |
| 374 |
""" |
| 375 |
Reloads the shelx file and parses it again. |
| 376 |
""" |
| 377 |
if self.debug or self.verbose: |
| 378 |
print(f'*** reloading file: {self.resfile} ***') |
| 379 |
self.read_file(self.resfile.resolve()) |
| 380 |
|
| 381 |
def _parse_cards(self) -> None: |
| 382 |
last_nonhydrogen_atom: Optional[Atom] = None |
| 383 |
lastcard = '' |
| 384 |
fvarnum = 1 |
| 385 |
for line_num, line in enumerate(self._reslist): |
| 386 |
self.error_line_num = line_num |
| 387 |
list_of_lines = [line_num] |
| 388 |
if line.startswith(' ') or line == '': |
| 389 |
continue |
| 390 |
wrapindex = 0 |
| 391 |
|
| 392 |
|
| 393 |
|
| 394 |
if multiline_test(self._reslist[line_num]): |
| 395 |
multiline = True |
| 396 |
else: |
| 397 |
multiline = False |
| 398 |
while multiline: |
| 399 |
|
| 400 |
wrapindex += 1 |
| 401 |
line = line.rpartition('=')[0] + self._reslist[line_num + wrapindex] |
| 402 |
|
| 403 |
list_of_lines.append(line_num + wrapindex) |
| 404 |
|
| 405 |
if multiline_test(self._reslist[line_num + wrapindex]): |
| 406 |
multiline = True |
| 407 |
else: |
| 408 |
multiline = False |
| 409 |
self._reslist[line_num + wrapindex] = '' |
| 410 |
|
| 411 |
spline: list = line.split('!')[0].split() |
| 412 |
|
| 413 |
line = line.upper().split('!')[0] |
| 414 |
word = line[:4] |
| 415 |
|
| 416 |
if line.startswith(('END', 'HKLF')) and self.resi: |
| 417 |
self.resi.num = 0 |
| 418 |
if self.debug or self.verbose: |
| 419 |
print('RESI in line {} was not closed'.format(line_num + 1)) |
| 420 |
|
| 421 |
|
| 422 |
if word == 'RESI': |
| 423 |
self.resi = self._assign_card(RESI(self, spline), line_num) |
| 424 |
if self.resi.residue_number > 0: |
| 425 |
self.residues.append(self.resi) |
| 426 |
continue |
| 427 |
|
| 428 |
if line.startswith(('END', 'HKLF')) and self.part: |
| 429 |
self.part.n = 0 |
| 430 |
if self.debug or self.verbose: |
| 431 |
print('PART in line {} was not closed'.format(line_num + 1)) |
| 432 |
|
| 433 |
|
| 434 |
if word == 'PART': |
| 435 |
self.part = self._assign_card(PART(self, spline), line_num) |
| 436 |
continue |
| 437 |
|
| 438 |
if line.startswith(('END', 'HKLF')) and self.afix: |
| 439 |
self.afix.mn = 0 |
| 440 |
if self.debug or self.verbose: |
| 441 |
print('AFIX in line {} was not closed'.format(line_num + 1)) |
| 442 |
elif word == 'AFIX': |
| 443 |
self.afix = self._assign_card(AFIX(self, spline), line_num) |
| 444 |
elif self.is_atom_spline(word, spline): |
| 445 |
|
| 446 |
|
| 447 |
|
| 448 |
a = Atom(self) |
| 449 |
if last_nonhydrogen_atom: |
| 450 |
a.pivot = last_nonhydrogen_atom |
| 451 |
a.parse_line(spline, list_of_lines, part=self.part, afix=self.afix, resi=self.resi) |
| 452 |
if not a.is_hydrogen: |
| 453 |
last_nonhydrogen_atom = a |
| 454 |
a.pivot = None |
| 455 |
self._append_card(self.atoms, a, line_num) |
| 456 |
elif word == 'SADI': |
| 457 |
|
| 458 |
|
| 459 |
if len(spline) == 1: |
| 460 |
self.global_sadi = line_num |
| 461 |
self._append_card(self.restraints, SADI(self, spline), line_num) |
| 462 |
elif word == 'DFIX': |
| 463 |
|
| 464 |
self._append_card(self.restraints, DFIX(self, spline), line_num) |
| 465 |
elif word == 'SIMU': |
| 466 |
|
| 467 |
self._append_card(self.restraints, SIMU(self, spline), line_num) |
| 468 |
elif word == 'DELU': |
| 469 |
|
| 470 |
self._append_card(self.restraints, DELU(self, spline), line_num) |
| 471 |
elif word == 'RIGU': |
| 472 |
|
| 473 |
self._append_card(self.restraints, RIGU(self, spline), line_num) |
| 474 |
elif word == 'BASF': |
| 475 |
|
| 476 |
self._assign_card(BASF(self, spline), line_num) |
| 477 |
elif word == 'HFIX': |
| 478 |
|
| 479 |
self._append_card(self.hfixes, HFIX(self, spline), line_num) |
| 480 |
elif word == 'DANG': |
| 481 |
|
| 482 |
self._append_card(self.restraints, DANG(self, spline), line_num) |
| 483 |
elif word == 'EADP': |
| 484 |
self._append_card(self.restraints, EADP(self, spline), line_num) |
| 485 |
elif line.startswith('REM'): |
| 486 |
if dsr_regex.match(line): |
| 487 |
self.dsrlines.append(" ".join(spline)) |
| 488 |
self.dsrline_nums.extend(list_of_lines) |
| 489 |
self._append_card(self.rem, REM(self, spline), line_num) |
| 490 |
self._get_residuals(spline, line) |
| 491 |
elif word == 'CELL': |
| 492 |
β γ |
| 493 |
if lastcard != 'TITL' and (self.debug or self.verbose): |
| 494 |
print('*** TITL is missing. ***') |
| 495 |
self.cell = self._assign_card(CELL(self, spline), line_num) |
| 496 |
self.orthogonal_matrix = self.cell.o |
| 497 |
self.wavelength = self.cell.wavelen |
| 498 |
lastcard = 'CELL' |
| 499 |
elif word == "ZERR": |
| 500 |
γ) |
| 501 |
if lastcard != 'CELL': |
| 502 |
if self.debug or self.verbose: |
| 503 |
print('*** Invalid SHELX file: CELL must occur before ZERR. ***') |
| 504 |
if self.debug: |
| 505 |
raise ParseOrderError(debug=shx.debug, verbose=shx.verbose) |
| 506 |
if not self.cell: |
| 507 |
raise ParseOrderError('*** Cell parameters missing! ***', debug=shx.debug, verbose=shx.verbose) |
| 508 |
if len(spline) >= 8: |
| 509 |
self.zerr: ZERR = self._assign_card(ZERR(self, spline), line_num) |
| 510 |
self.Z = self.zerr.Z |
| 511 |
if self.Z < 1: |
| 512 |
self.Z = 1 |
| 513 |
if self.verbose or self.debug: |
| 514 |
print('*** Warning: Z value is zero. ***') |
| 515 |
lastcard = 'ZERR' |
| 516 |
elif word == "LATT": |
| 517 |
|
| 518 |
|
| 519 |
|
| 520 |
self.latt = self._assign_card(LATT(self, spline), line_num) |
| 521 |
if lastcard != 'ZERR' and (self.verbose or self.debug): |
| 522 |
print('*** ZERR instruction is missing! ***') |
| 523 |
if self.latt.centric: |
| 524 |
self.symmcards.set_centric(True) |
| 525 |
elif word == "SYMM": |
| 526 |
|
| 527 |
|
| 528 |
|
| 529 |
|
| 530 |
|
| 531 |
|
| 532 |
s = SYMM(self, spline) |
| 533 |
if not self.latt and (self.debug or self.verbose): |
| 534 |
print("*** LATT instruction is missing! ***") |
| 535 |
if self.debug: |
| 536 |
raise ParseSyntaxError(debug=self.debug, verbose=self.verbose) |
| 537 |
|
| 538 |
|
| 539 |
|
| 540 |
self.symmcards.append(s.symmcard) |
| 541 |
if s not in self._reslist: |
| 542 |
self._reslist[line_num] = s |
| 543 |
else: |
| 544 |
self.delete_on_write.update([line_num]) |
| 545 |
self._reslist[line_num] = ' ' |
| 546 |
lastcard = 'SYMM' |
| 547 |
elif word == 'SFAC': |
| 548 |
|
| 549 |
|
| 550 |
|
| 551 |
|
| 552 |
|
| 553 |
|
| 554 |
|
| 555 |
if len(spline) <= 1: |
| 556 |
continue |
| 557 |
self.sfac_table.parse_element_line(spline) |
| 558 |
if self.sfac_table not in self._reslist: |
| 559 |
self._reslist[line_num] = self.sfac_table |
| 560 |
else: |
| 561 |
self.delete_on_write.update([line_num]) |
| 562 |
self._reslist[line_num] = ' ' |
| 563 |
lastcard = 'SFAC' |
| 564 |
elif word == 'UNIT': |
| 565 |
|
| 566 |
|
| 567 |
if lastcard != 'SFAC': |
| 568 |
raise ParseOrderError(debug=shx.debug, verbose=shx.verbose) |
| 569 |
if self.sfac_table: |
| 570 |
try: |
| 571 |
self.unit = self._assign_card(UNIT(self, spline), line_num) |
| 572 |
except ValueError: |
| 573 |
if self.debug or self.verbose: |
| 574 |
print('*** Non-numeric value in SFAC instruction! ***') |
| 575 |
if self.debug: |
| 576 |
raise |
| 577 |
else: |
| 578 |
raise ParseOrderError(debug=shx.debug, verbose=shx.verbose) |
| 579 |
if len(self.unit.values) != len(self.sfac_table.elements_list) and (self.debug or self.verbose): |
| 580 |
print('*** Number of UNIT and SFAC values differ! ***') |
| 581 |
if self.debug: |
| 582 |
raise ParseNumError(debug=self.shx.debug, verbose=self.shx.verbose) |
| 583 |
lastcard = 'UNIT' |
| 584 |
elif word in ['L.S.', 'CGLS']: |
| 585 |
|
| 586 |
|
| 587 |
self.cycles = self._assign_card(LSCycles(self, spline), line_num) |
| 588 |
elif word == "LIST": |
| 589 |
|
| 590 |
self.list = int(spline[1]) |
| 591 |
elif word == "FVAR": |
| 592 |
|
| 593 |
for fvvalue in spline[1:]: |
| 594 |
fvarnum += 1 |
| 595 |
self._append_card(self.fvars, FVAR(fvarnum, float(fvvalue)), line_num) |
| 596 |
if self.fvars not in self._reslist: |
| 597 |
self._reslist[line_num] = self.fvars |
| 598 |
else: |
| 599 |
self.delete_on_write.update([line_num]) |
| 600 |
elif word == 'ANIS': |
| 601 |
|
| 602 |
|
| 603 |
self.anis = self._assign_card(ANIS(self, spline), line_num) |
| 604 |
elif word == 'WGHT': |
| 605 |
|
| 606 |
if self.end: |
| 607 |
self.wght_suggested = self._assign_card(WGHT(self, spline), line_num) |
| 608 |
continue |
| 609 |
self.wght = self._assign_card(WGHT(self, spline), line_num) |
| 610 |
elif word == 'ACTA': |
| 611 |
L |
| 612 |
self.acta = self._assign_card(ACTA(self, spline), line_num) |
| 613 |
elif word == 'DAMP': |
| 614 |
|
| 615 |
self.damp = self._assign_card(DAMP(self, spline), line_num) |
| 616 |
elif word == 'ABIN': |
| 617 |
|
| 618 |
self.abin = self._assign_card(ABIN(self, spline), line_num) |
| 619 |
elif word == 'ANSC': |
| 620 |
|
| 621 |
if len(spline) == 7: |
| 622 |
self.ansc = [float(x) for x in spline[:1]] |
| 623 |
elif word == 'ANSR': |
| 624 |
|
| 625 |
if len(spline) == 2: |
| 626 |
self.ansr = float(spline[1]) |
| 627 |
elif word == 'BIND': |
| 628 |
|
| 629 |
if len(spline) == 3: |
| 630 |
self._append_card(self.bind, BIND(self, spline), line_num) |
| 631 |
elif word == 'BLOC': |
| 632 |
|
| 633 |
self._append_card(self.bloc, BLOC(self, spline), line_num) |
| 634 |
elif word == 'BOND': |
| 635 |
|
| 636 |
self._append_card(self.bonds, BOND(self, spline), line_num) |
| 637 |
elif word == 'BUMP': |
| 638 |
|
| 639 |
self._assign_card(BUMP(self, spline), line_num) |
| 640 |
elif word == 'CHIV': |
| 641 |
|
| 642 |
self._append_card(self.restraints, CHIV(self, spline), line_num) |
| 643 |
elif word == 'CONF': |
| 644 |
|
| 645 |
self.conf = self._assign_card(CONF(self, spline), line_num) |
| 646 |
elif word == 'CONN': |
| 647 |
|
| 648 |
Å |
| 649 |
self.conn = self._assign_card(CONN(self, spline), line_num) |
| 650 |
elif word == 'DEFS': |
| 651 |
|
| 652 |
self.defs = self._assign_card(DEFS(self, spline), line_num) |
| 653 |
elif word == 'DISP': |
| 654 |
|
| 655 |
if lastcard != 'SFAC': |
| 656 |
raise ParseOrderError(debug=shx.debug, verbose=shx.verbose) |
| 657 |
self._append_card(self.disp, DISP(self, spline), line_num) |
| 658 |
elif word == 'EQIV': |
| 659 |
|
| 660 |
|
| 661 |
if len(spline) > 1 and spline[1].startswith('$'): |
| 662 |
self.eqiv.append(spline[1:]) |
| 663 |
elif word == 'EXTI': |
| 664 |
|
| 665 |
self.exti = float(spline[1]) |
| 666 |
elif word == 'EXYZ': |
| 667 |
|
| 668 |
self._append_card(self.restraints, EXYZ(self, spline), line_num) |
| 669 |
elif word == 'FRAG': |
| 670 |
90] |
| 671 |
if len(spline) == 8: |
| 672 |
self.frag = self._assign_card(FRAG(self, spline), line_num) |
| 673 |
elif word == 'FEND': |
| 674 |
|
| 675 |
if not self.frag: |
| 676 |
raise ParseOrderError(debug=shx.debug, verbose=shx.verbose) |
| 677 |
self.frag = None |
| 678 |
elif word == 'FLAT': |
| 679 |
|
| 680 |
self._append_card(self.restraints, FLAT(self, spline), line_num) |
| 681 |
elif word == 'FREE': |
| 682 |
|
| 683 |
self._append_card(self.free, FREE(self, spline), line_num) |
| 684 |
elif word == 'GRID': |
| 685 |
|
| 686 |
self.grid = self._assign_card(GRID(self, spline), line_num) |
| 687 |
elif word == 'HKLF': |
| 688 |
|
| 689 |
self.hklf = self._assign_card(HKLF(self, spline), line_num) |
| 690 |
elif line.startswith('END'): |
| 691 |
|
| 692 |
self.end = True |
| 693 |
elif word == 'HTAB': |
| 694 |
|
| 695 |
self.htab = self._assign_card(HTAB(self, spline), line_num) |
| 696 |
elif word == 'ISOR': |
| 697 |
|
| 698 |
self._append_card(self.restraints, ISOR(self, spline), line_num) |
| 699 |
elif word == 'LAUE': |
| 700 |
|
| 701 |
|
| 702 |
continue |
| 703 |
elif word == 'MERG': |
| 704 |
|
| 705 |
self.merg = self._assign_card(MERG(self, spline), line_num) |
| 706 |
elif word == 'MORE': |
| 707 |
|
| 708 |
self.more = self._assign_card(MORE(self, spline), line_num) |
| 709 |
elif word == 'FMAP': |
| 710 |
|
| 711 |
self.fmap = self._assign_card(FMAP(self, spline), line_num) |
| 712 |
elif word == 'MOVE': |
| 713 |
|
| 714 |
self.move = self._assign_card(MOVE(self, spline), line_num) |
| 715 |
elif word == 'MPLA': |
| 716 |
|
| 717 |
self.mpla = self._assign_card(MPLA(self, spline), line_num) |
| 718 |
elif word == 'NCSY': |
| 719 |
|
| 720 |
self._append_card(self.restraints, NCSY(self, spline), line_num) |
| 721 |
elif word == 'NEUT': |
| 722 |
|
| 723 |
|
| 724 |
if lastcard != 'SYMM': |
| 725 |
raise ParseOrderError(debug=shx.debug, verbose=shx.verbose) |
| 726 |
elif word == 'OMIT': |
| 727 |
l |
| 728 |
|
| 729 |
self.omit.append(spline[1:]) |
| 730 |
elif word == 'PLAN': |
| 731 |
|
| 732 |
self.plan = self._assign_card(PLAN(self, spline), line_num) |
| 733 |
elif word == 'PRIG': |
| 734 |
|
| 735 |
self.prig = self._assign_card(PRIG(self, spline), line_num) |
| 736 |
elif word == 'RTAB': |
| 737 |
|
| 738 |
self._append_card(self.rtab, RTAB(self, spline), line_num) |
| 739 |
elif word == 'SAME': |
| 740 |
|
| 741 |
self._append_card(self.restraints, SAME(self, spline), line_num) |
| 742 |
elif word == 'SHEL': |
| 743 |
|
| 744 |
self.shel = self._assign_card(SHEL(self, spline), line_num) |
| 745 |
elif word == 'SIZE': |
| 746 |
|
| 747 |
self.size = self._assign_card(SIZE(self, spline), line_num) |
| 748 |
elif word == 'SPEC': |
| 749 |
|
| 750 |
if len(spline) > 1: |
| 751 |
self.spec = self._assign_card(SPEC(self, spline), line_num) |
| 752 |
elif word == 'STIR': |
| 753 |
|
| 754 |
self.stir = self._assign_card(STIR(self, spline), line_num) |
| 755 |
elif word == 'SUMP': |
| 756 |
|
| 757 |
self._append_card(self.sump, SUMP(self, spline), line_num) |
| 758 |
elif word == 'SWAT': |
| 759 |
|
| 760 |
self.swat = self._assign_card(SWAT(self, spline), line_num) |
| 761 |
elif word == 'TEMP': |
| 762 |
|
| 763 |
self.temp = float(spline[1].split('(')[0]) |
| 764 |
self.temp_in_kelvin = self.temp + 273.15 |
| 765 |
elif word == 'TWIN': |
| 766 |
|
| 767 |
self.twin = self._assign_card(TWIN(self, spline), line_num) |
| 768 |
elif word == 'TWST': |
| 769 |
|
| 770 |
if len(spline) > 1: |
| 771 |
self.twst = self._assign_card(TWST(self, spline), line_num) |
| 772 |
elif word == 'WIGL': |
| 773 |
|
| 774 |
self.wigl = self._assign_card(WIGL(self, spline), line_num) |
| 775 |
elif word == 'WPDB': |
| 776 |
|
| 777 |
self.wpdb = self._assign_card(WPDB(self, spline), line_num) |
| 778 |
elif word == 'XNPD': |
| 779 |
|
| 780 |
self.xnpd = self._assign_card(XNPD(self, spline), line_num) |
| 781 |
elif word == 'BEDE': |
| 782 |
|
| 783 |
continue |
| 784 |
elif word == 'LONE': |
| 785 |
|
| 786 |
continue |
| 787 |
elif word == 'MOLE': |
| 788 |
|
| 789 |
pass |
| 790 |
elif word == 'HOPE': |
| 791 |
|
| 792 |
pass |
| 793 |
elif line.startswith('+'): |
| 794 |
pass |
| 795 |
elif word == 'TITL': |
| 796 |
self.titl = line[5:76] |
| 797 |
lastcard = 'TITL' |
| 798 |
else: |
| 799 |
if not line.strip(): |
| 800 |
continue |
| 801 |
if self.debug or self.verbose: |
| 802 |
print(f"Error in line: {line_num + 1} -> {line}") |
| 803 |
if self.debug: |
| 804 |
raise ParseUnknownParam(debug=self.debug, verbose=self.verbose) |
| 805 |
|
| 806 |
def _find_atom_insert_position(self, after: Optional['Atom'] = None) -> int: |
| 807 |
""" |
| 808 |
Returns the index in ``_reslist`` at which a new atom should be inserted. |
| 809 |
|
| 810 |
Priority order: |
| 811 |
1. Directly after *after* (if given and present in ``_reslist``). |
| 812 |
2. Directly after the last real (non-Q-peak) :class:`~shelxfile.atoms.atom.Atom` |
| 813 |
in ``_reslist``. |
| 814 |
3. Directly before the ``HKLF`` card. |
| 815 |
4. One position before the end of ``_reslist`` as a last resort. |
| 816 |
""" |
| 817 |
if after is not None: |
| 818 |
try: |
| 819 |
return self._reslist.index(after) + 1 |
| 820 |
except ValueError: |
| 821 |
pass |
| 822 |
|
| 823 |
last_atom_pos = None |
| 824 |
for i, item in enumerate(self._reslist): |
| 825 |
if isinstance(item, Atom) and not item.qpeak: |
| 826 |
last_atom_pos = i |
| 827 |
if last_atom_pos is not None: |
| 828 |
return last_atom_pos + 1 |
| 829 |
|
| 830 |
for i, item in enumerate(self._reslist): |
| 831 |
if isinstance(item, HKLF): |
| 832 |
return i |
| 833 |
return max(len(self._reslist) - 1, 0) |
| 834 |
|
| 835 |
def unused_atom_name(self, element: str) -> str: |
| 836 |
""" |
| 837 |
Returns the first atom name of the given element that is not yet used in residue 0. |
| 838 |
|
| 839 |
SHELX limits atom labels to **4 characters**, so the numeric suffix is capped |
| 840 |
accordingly: a 1-character element (e.g. ``'C'``) allows up to ``C999``; a |
| 841 |
2-character element (e.g. ``'Fe'``) allows up to ``Fe99``. |
| 842 |
|
| 843 |
Example:: |
| 844 |
|
| 845 |
shx.unused_atom_name('C') # -> 'C1' if C1_0 is free, else 'C2', … |
| 846 |
shx.unused_atom_name('Fe') # -> 'Fe1' if Fe1_0 is free, … |
| 847 |
|
| 848 |
:param element: Chemical element symbol (case-insensitive), e.g. ``'C'``, ``'Fe'``. |
| 849 |
:returns: An atom name string (without residue suffix) that is not present in the |
| 850 |
file and is at most 4 characters long. |
| 851 |
:raises ValueError: if no unused name can be found within the allowed range. |
| 852 |
""" |
| 853 |
prefix = element.capitalize() |
| 854 |
max_digits = 4 - len(prefix) |
| 855 |
if max_digits < 1: |
| 856 |
raise ValueError( |
| 857 |
f"Element symbol {prefix!r} is {len(prefix)} characters long; " |
| 858 |
f"no room for a numeric suffix within SHELX's 4-character name limit." |
| 859 |
) |
| 860 |
max_num = 10 ** max_digits - 1 |
| 861 |
existing = set(self.atoms.nameslist) |
| 862 |
for n in range(1, max_num + 1): |
| 863 |
candidate = f'{prefix}{n}' |
| 864 |
if f'{candidate}_0'.upper() not in existing: |
| 865 |
return candidate |
| 866 |
raise ValueError( |
| 867 |
f"No unused atom name found for element {element!r} " |
| 868 |
f"(tried {prefix}1 … {prefix}{max_num})" |
| 869 |
) |
| 870 |
|
| 871 |
def add_atom(self, |
| 872 |
name: str, |
| 873 |
coordinates: list, |
| 874 |
element: str = 'C', |
| 875 |
uvals: list = None, |
| 876 |
part: int = 0, |
| 877 |
sof: Optional[float] = None, |
| 878 |
occupancy: Optional[float] = None, |
| 879 |
fvar: int = 1, |
| 880 |
resi: int = 0, |
| 881 |
after: Optional['Atom'] = None, |
| 882 |
coords_are_cartesian: bool = False) -> 'Atom': |
| 883 |
""" |
| 884 |
Add a new atom to the structure and insert it into the ``_reslist`` at the |
| 885 |
correct position so that ``write_shelx_file`` produces a valid file. |
| 886 |
|
| 887 |
**Occupation encoding** — two mutually exclusive styles are supported: |
| 888 |
|
| 889 |
* *High-level*: pass ``occupancy`` (0.0–1.0) and optionally ``fvar`` |
| 890 |
(free-variable number, default 1). The raw SHELX site-occupation factor |
| 891 |
is computed automatically as ``fvar * 10 + occupancy``, e.g. |
| 892 |
``occupancy=0.5, fvar=2`` → ``sof=20.5``. |
| 893 |
* *Raw SHELX*: pass ``sof`` directly, e.g. ``sof=21.0`` (fvar 2, |
| 894 |
occupancy 1.0). |
| 895 |
|
| 896 |
Passing both ``occupancy`` (or ``fvar``) **and** ``sof`` raises a |
| 897 |
:exc:`ValueError` to prevent ambiguous input. If neither is given the |
| 898 |
atom is fully occupied on fvar 1 (``sof=11.0``). |
| 899 |
|
| 900 |
:param name: Atom label, e.g. ``'C1'`` (max 4 characters). Must not |
| 901 |
already exist in residue *resi*; a :exc:`ValueError` is raised |
| 902 |
if it does. |
| 903 |
:param coordinates: Fractional (default) or Cartesian (if |
| 904 |
*coords_are_cartesian* is ``True``) coordinates |
| 905 |
``[x, y, z]``. |
| 906 |
:param element: Chemical element symbol (default ``'C'``). If the element |
| 907 |
is not yet in the SFAC table it is added automatically |
| 908 |
together with a matching UNIT count of 1. |
| 909 |
:param uvals: Displacement parameters. Pass one value ``[Uiso]`` for |
| 910 |
isotropic, or six values ``[U11, U22, U33, U23, U13, U12]`` |
| 911 |
for anisotropic. A single-element list is silently expanded |
| 912 |
to six values. Defaults to ``[0.04, 0, 0, 0, 0, 0]`` |
| 913 |
(isotropic, Uiso = 0.04). |
| 914 |
:param part: PART number (default 0 = no disorder part). |
| 915 |
:param sof: Raw SHELXL site-occupation factor, e.g. ``11.0`` (fvar 1 × |
| 916 |
1.0 = fully occupied). Mutually exclusive with *occupancy* / |
| 917 |
*fvar*; defaults to ``11.0`` when neither *sof* nor *occupancy* |
| 918 |
is given. |
| 919 |
:param occupancy: Fractional occupancy in the range 0.0–1.0. When given, |
| 920 |
the raw ``sof`` is computed as ``fvar * 10 + occupancy``. |
| 921 |
Mutually exclusive with the raw *sof* parameter. |
| 922 |
:param fvar: Free-variable number used together with *occupancy* (default |
| 923 |
1). Mutually exclusive with the raw *sof* parameter. |
| 924 |
:param resi: Residue number (default 0). |
| 925 |
:param after: If given, the new atom is inserted directly after this |
| 926 |
:class:`~shelxfile.atoms.atom.Atom` in the file. Otherwise |
| 927 |
the atom is appended after the last real atom (before |
| 928 |
``HKLF``). |
| 929 |
:param coords_are_cartesian: If ``True``, *coordinates* are treated as |
| 930 |
Cartesian (Å) and converted to fractional |
| 931 |
automatically. |
| 932 |
:returns: The new :class:`~shelxfile.atoms.atom.Atom` object. |
| 933 |
:raises ValueError: if *name* is already used in residue *resi*, or if |
| 934 |
both *sof* and *occupancy*/*fvar* are provided. |
| 935 |
""" |
| 936 |
|
| 937 |
high_level = occupancy is not None or fvar != 1 |
| 938 |
raw_sof = sof is not None |
| 939 |
if high_level and raw_sof: |
| 940 |
raise ValueError( |
| 941 |
"Specify occupation using either 'occupancy'/'fvar' or 'sof', not both." |
| 942 |
) |
| 943 |
|
| 944 |
full_name = f'{name}_{resi}' |
| 945 |
if self.atoms.has_atom(full_name): |
| 946 |
raise ValueError(f"Atom '{full_name}' already exists in the structure.") |
| 947 |
|
| 948 |
if occupancy is not None: |
| 949 |
sof = fvar * 10 + occupancy |
| 950 |
elif sof is None: |
| 951 |
sof = 11.0 |
| 952 |
|
| 953 |
if uvals is None: |
| 954 |
uvals = [0.04, 0.0, 0.0, 0.0, 0.0, 0.0] |
| 955 |
elif len(uvals) == 1: |
| 956 |
uvals = [uvals[0], 0.0, 0.0, 0.0, 0.0, 0.0] |
| 957 |
|
| 958 |
if coords_are_cartesian: |
| 959 |
coordinates = list(cart_to_frac(coordinates, list(self.cell))) |
| 960 |
|
| 961 |
if not self.sfac_table.has_element(element): |
| 962 |
self.sfac_table.add_element(element) |
| 963 |
sfac_num = self.elem2sfac(element) |
| 964 |
|
| 965 |
part_card = PART(self, f'PART {part}'.split()) |
| 966 |
afix_card = AFIX(self, 'AFIX 0'.split()) |
| 967 |
|
| 968 |
resi_card = None |
| 969 |
for r in self.residues.all_residues: |
| 970 |
if r.residue_number == resi: |
| 971 |
resi_card = r |
| 972 |
break |
| 973 |
if resi_card is None: |
| 974 |
resi_card = RESI(self, ['RESI', str(resi)]) |
| 975 |
|
| 976 |
a = Atom(self) |
| 977 |
a.set_atom_parameters( |
| 978 |
name=name, |
| 979 |
sfac_num=sfac_num, |
| 980 |
coords=coordinates, |
| 981 |
part=part_card, |
| 982 |
afix=afix_card, |
| 983 |
resi=resi_card, |
| 984 |
site_occupation=sof, |
| 985 |
uvals=uvals, |
| 986 |
symmgen=False, |
| 987 |
) |
| 988 |
|
| 989 |
insert_pos = self._find_atom_insert_position(after=after) |
| 990 |
self._reslist.insert(insert_pos, a) |
| 991 |
self.atoms.append(a) |
| 992 |
self.atoms._atomsdict.clear() |
| 993 |
return a |
| 994 |
|
| 995 |
def frac_to_cart(self, coordinates: list) -> Array: |
| 996 |
""" |
| 997 |
fractional to cartesian coordinates by applying the orthogonal matrix. |
| 998 |
""" |
| 999 |
return self.orthogonal_matrix * Array(coordinates) |
| 1000 |
|
| 1001 |
def __repr__(self): |
| 1002 |
""" |
| 1003 |
Represents the shelxl object. |
| 1004 |
""" |
| 1005 |
resl = [] |
| 1006 |
for num, line in enumerate(self._reslist): |
| 1007 |
if num in self.delete_on_write: |
| 1008 |
continue |
| 1009 |
try: |
| 1010 |
if line == '' and self._reslist[num + 1] == '': |
| 1011 |
continue |
| 1012 |
except IndexError: |
| 1013 |
pass |
| 1014 |
|
| 1015 |
line = "".join([wrap_line(x) for x in str(line).split("\n")]) |
| 1016 |
resl.append(line) |
| 1017 |
return "\n".join(resl) |
| 1018 |
|
| 1019 |
def grow(self, with_qpeaks: bool = False): |
| 1020 |
""" |
| 1021 |
Returns a list of atoms that represent the complete molecules of the structure. |
| 1022 |
""" |
| 1023 |
sdm = SDM(self) |
| 1024 |
needsymm = sdm.calc_sdm() |
| 1025 |
packed_atoms = sdm.packer(sdm, needsymm, with_qpeaks=with_qpeaks) |
| 1026 |
return packed_atoms |
| 1027 |
|
| 1028 |
def write_grown_file(self, filename: Union[str, Path], with_qpeaks: bool = False) -> None: |
| 1029 |
"""Write a grown (complete molecule) .res file in P1 symmetry. |
| 1030 |
|
| 1031 |
The output file: |
| 1032 |
|
| 1033 |
- Completes all molecular fragments by applying crystal symmetry to the |
| 1034 |
asymmetric unit (calls :meth:`grow` internally). |
| 1035 |
- Sets the space group to P1 (``LATT -1``, no ``SYMM`` cards) so that |
| 1036 |
viewers and SHELXL do **not** re-apply symmetry to the already-grown |
| 1037 |
atoms — this prevents duplicate atoms and wrong bonds. |
| 1038 |
- Preserves disorder parts via ``PART`` cards so the bond graph is |
| 1039 |
correct (atoms in different disorder alternatives are not connected). |
| 1040 |
- Adds a ``REM`` warning that the file is not suited for refinement. |
| 1041 |
|
| 1042 |
Restraints, ``AFIX``, ``HFIX``, ``ACTA``, ``CONF``, ``ANIS`` and other |
| 1043 |
instruction cards that reference atoms of the original asymmetric unit |
| 1044 |
are omitted from the output. |
| 1045 |
|
| 1046 |
:param filename: Output file path (string or :class:`~pathlib.Path`). |
| 1047 |
:param with_qpeaks: Include Q-peaks in the grown structure (default |
| 1048 |
``False``). |
| 1049 |
""" |
| 1050 |
if isinstance(filename, str): |
| 1051 |
filename = Path(filename) |
| 1052 |
|
| 1053 |
grown_atoms = self.grow(with_qpeaks=with_qpeaks) |
| 1054 |
real_grown = [a for a in grown_atoms if not a.qpeak] if not with_qpeaks else grown_atoms |
| 1055 |
|
| 1056 |
lines: List[str] = [] |
| 1057 |
|
| 1058 |
───────────────────────────────── |
| 1059 |
lines.append('REM This file was grown from the asymmetric unit to complete molecules.') |
| 1060 |
lines.append('REM It has P1 symmetry and is NOT suited for refinement unless you know what you are doing.') |
| 1061 |
|
| 1062 |
d ── |
| 1063 |
atoms_inserted = False |
| 1064 |
for num, item in enumerate(self._reslist): |
| 1065 |
if num in self.delete_on_write: |
| 1066 |
continue |
| 1067 |
if item == '': |
| 1068 |
continue |
| 1069 |
|
| 1070 |
st |
| 1071 |
if isinstance(item, Atom): |
| 1072 |
continue |
| 1073 |
|
| 1074 |
ns |
| 1075 |
if isinstance(item, SYMM): |
| 1076 |
continue |
| 1077 |
|
| 1078 |
es |
| 1079 |
if isinstance(item, Restraint): |
| 1080 |
continue |
| 1081 |
|
| 1082 |
|
| 1083 |
|
| 1084 |
if isinstance(item, (AFIX, PART, RESI, HFIX, ANIS)): |
| 1085 |
continue |
| 1086 |
|
| 1087 |
|
| 1088 |
if isinstance(item, (ACTA, CONF)): |
| 1089 |
continue |
| 1090 |
|
| 1091 |
he |
| 1092 |
|
| 1093 |
if isinstance(item, str) and item.startswith('+'): |
| 1094 |
continue |
| 1095 |
|
| 1096 |
|
| 1097 |
if isinstance(item, LATT): |
| 1098 |
lines.append('LATT -1') |
| 1099 |
continue |
| 1100 |
|
| 1101 |
|
| 1102 |
if isinstance(item, HKLF) and not atoms_inserted: |
| 1103 |
atoms_inserted = True |
| 1104 |
current_part = 0 |
| 1105 |
for atom in real_grown: |
| 1106 |
atom_part = atom.part.n |
| 1107 |
if atom_part != current_part: |
| 1108 |
lines.append(f'PART {atom_part}') |
| 1109 |
current_part = atom_part |
| 1110 |
lines.append(wrap_line(str(atom))) |
| 1111 |
if current_part != 0: |
| 1112 |
lines.append('PART 0') |
| 1113 |
lines.append('') |
| 1114 |
|
| 1115 |
line_str = str(item) |
| 1116 |
if not line_str.strip(): |
| 1117 |
continue |
| 1118 |
line_str = '\n'.join([wrap_line(x) for x in line_str.split('\n')]) |
| 1119 |
lines.append(line_str) |
| 1120 |
|
| 1121 |
with open(filename, 'w') as f: |
| 1122 |
f.write('\n'.join(lines) + '\n') |
| 1123 |
|
| 1124 |
if self.verbose or self.debug: |
| 1125 |
print(f'*** Grown file written to {filename.resolve()} ***') |
| 1126 |
|
| 1127 |
def pack(self, with_qpeaks: bool = False) -> list: |
| 1128 |
"""Returns a list of atoms representing the packed unit cell. |
| 1129 |
|
| 1130 |
Applies all symmetry operations to the asymmetric unit and folds every |
| 1131 |
position back into [0, 1) fractional coordinates, removing duplicates. |
| 1132 |
Unlike :meth:`grow`, this does not stitch molecular fragments together — |
| 1133 |
it simply fills one unit cell. |
| 1134 |
|
| 1135 |
:param with_qpeaks: include Q-peaks (difference-map peaks) in the output. |
| 1136 |
:returns: List of :class:`~shelxfile.atoms.atom.Atom` objects. |
| 1137 |
""" |
| 1138 |
sdm = SDM(self) |
| 1139 |
return sdm.pack_unit_cell(with_qpeaks=with_qpeaks) |
| 1140 |
|
| 1141 |
def refine(self, cycles: Union[int, None] = None, backup_before: bool = True) -> bool: |
| 1142 |
if self.resfile: |
| 1143 |
filen = self.resfile.stem |
| 1144 |
if cycles is not None: |
| 1145 |
self.cycles.number = cycles |
| 1146 |
ref = ShelxlRefine(self, self.resfile) |
| 1147 |
ref.remove_acta_card(self.acta) |
| 1148 |
self.write_shelx_file(filen + '.ins') |
| 1149 |
ref.run_shelxl(backup_before=backup_before) |
| 1150 |
self.reload() |
| 1151 |
ref.restore_acta_card() |
| 1152 |
|
| 1153 |
return True |
| 1154 |
return False |
| 1155 |
|
| 1156 |
def refine_weight_convergence(self, stop_after: int = 10): |
| 1157 |
""" |
| 1158 |
Tries to refine weigting sheme from SHELXL until it converged (self.weight_difference() is zero) or |
| 1159 |
stopt_after cycles are reached. |
| 1160 |
""" |
| 1161 |
for _ in range(stop_after): |
| 1162 |
difference = self.wght.difference() |
| 1163 |
print("Weighting difference = {} {}".format(*difference)) |
| 1164 |
if self._weight_converged(difference): |
| 1165 |
return True |
| 1166 |
else: |
| 1167 |
self.update_weight() |
| 1168 |
self.refine(9) |
| 1169 |
print("Maximum number of refinement cycles reached, but no WGHT convergence.") |
| 1170 |
return False |
| 1171 |
|
| 1172 |
def _weight_converged(self, diff: List[float]) -> bool: |
| 1173 |
return diff == [0.0, 0.0] |
| 1174 |
|
| 1175 |
def _append_card(self, obj, card, line_num: int) -> Command: |
| 1176 |
""" |
| 1177 |
Appends SHELX card to an object list, e.g. self.restraints and |
| 1178 |
assigns the line_num in reslist with the card instance. |
| 1179 |
""" |
| 1180 |
obj.append(card) |
| 1181 |
self._reslist[line_num] = card |
| 1182 |
return card |
| 1183 |
|
| 1184 |
def _assign_card(self, card, line_num: int): |
| 1185 |
self._reslist[line_num] = card |
| 1186 |
return card |
| 1187 |
|
| 1188 |
@staticmethod |
| 1189 |
def is_atom(atomline: str) -> bool: |
| 1190 |
""" |
| 1191 |
Returns True is line contains an atom. |
| 1192 |
""" |
| 1193 |
|
| 1194 |
if atomline[:4].upper() not in SHX_CARDS: |
| 1195 |
spline: List[str] = atomline.split() |
| 1196 |
|
| 1197 |
if len(spline) < 5: |
| 1198 |
return False |
| 1199 |
|
| 1200 |
if '.' in spline[1]: |
| 1201 |
return False |
| 1202 |
if Shelxfile._coordinates_are_unrealistic(spline): |
| 1203 |
return False |
| 1204 |
|
| 1205 |
if len(spline) > 5 and spline[5] == '!': |
| 1206 |
return False |
| 1207 |
return True |
| 1208 |
else: |
| 1209 |
return False |
| 1210 |
|
| 1211 |
@staticmethod |
| 1212 |
def is_atom_spline(word4: str, spline: List[str]) -> bool: |
| 1213 |
""" |
| 1214 |
Fast atom check using a pre-split, pre-uppercased spline. |
| 1215 |
|
| 1216 |
Avoids re-splitting the line and uppercasing it again — the caller |
| 1217 |
(``_parse_cards``) has already computed both ``word = line[:4]`` and |
| 1218 |
``spline`` before reaching this check. |
| 1219 |
|
| 1220 |
:param word4: The first four characters of the line, upper-cased. |
| 1221 |
:param spline: The line already split on whitespace (comments stripped). |
| 1222 |
""" |
| 1223 |
if word4 in SHX_CARDS: |
| 1224 |
return False |
| 1225 |
if len(spline) < 5: |
| 1226 |
return False |
| 1227 |
if '.' in spline[1]: |
| 1228 |
return False |
| 1229 |
|
| 1230 |
try: |
| 1231 |
if float(spline[2]) > 4.0 or float(spline[3]) > 4.0 or float(spline[4]) > 4.0: |
| 1232 |
return False |
| 1233 |
except ValueError: |
| 1234 |
return False |
| 1235 |
if len(spline) > 5 and spline[5] == '!': |
| 1236 |
return False |
| 1237 |
return True |
| 1238 |
|
| 1239 |
@staticmethod |
| 1240 |
def _coordinates_are_unrealistic(spline: List[str]) -> bool: |
| 1241 |
return any(float(y) > 4.0 for y in spline[2:5]) |
| 1242 |
|
| 1243 |
def to_cif(self, filename: str = None, template: Optional[str] = None) -> None: |
| 1244 |
""" |
| 1245 |
Writes a CIF file from the ShelxFile object. |
| 1246 |
""" |
| 1247 |
if not filename: |
| 1248 |
filename = self.resfile.stem + '.cif' |
| 1249 |
CifFile(self, template).write_cif(Path(filename)) |
| 1250 |
|
| 1251 |
def elem2sfac(self, atom_type: str) -> int: |
| 1252 |
""" |
| 1253 |
returns an sfac-number for the element given in "atom_type" |
| 1254 |
""" |
| 1255 |
for num, element in enumerate(self.sfac_table, 1): |
| 1256 |
if atom_type.capitalize() == element.capitalize(): |
| 1257 |
return num |
| 1258 |
|
| 1259 |
return 0 |
| 1260 |
|
| 1261 |
def sfac2elem(self, sfacnum: int) -> str: |
| 1262 |
""" |
| 1263 |
returns an element and needs an sfac-number |
| 1264 |
:param sfacnum: string like '2' |
| 1265 |
""" |
| 1266 |
try: |
| 1267 |
elem = self.sfac_table[int(sfacnum)] |
| 1268 |
except IndexError: |
| 1269 |
return '' |
| 1270 |
return elem |
| 1271 |
|
| 1272 |
def add_line(self, linenum: int, line: str) -> None: |
| 1273 |
""" |
| 1274 |
Adds a new SHELX card to the reslist after linenum. |
| 1275 |
e.g. shx.add_line(shx.unit.position, 'ANIS') |
| 1276 |
""" |
| 1277 |
self._reslist.insert(linenum + 1, line) |
| 1278 |
|
| 1279 |
def replace_line(self, obj, new_line: str) -> None: |
| 1280 |
""" |
| 1281 |
Replaces a single line in the res file with new_line. |
| 1282 |
""" |
| 1283 |
self._reslist[self.index_of(obj)] = new_line |
| 1284 |
|
| 1285 |
def index_of(self, obj: Union[Atom, Restraint, Command]) -> int: |
| 1286 |
return self._reslist.index(obj) |
| 1287 |
|
| 1288 |
@property |
| 1289 |
def sum_formula(self) -> str: |
| 1290 |
""" |
| 1291 |
The sum formula of the structure in regard to the UNIT instruction. |
| 1292 |
""" |
| 1293 |
formstring = '' |
| 1294 |
formula_weight = 0.0 |
| 1295 |
try: |
| 1296 |
val = self.unit.values |
| 1297 |
eli = self.sfac_table.elements_list |
| 1298 |
except AttributeError: |
| 1299 |
return '' |
| 1300 |
if len(val) == len(eli): |
| 1301 |
for el, num in zip(self.sfac_table.elements_list, self.unit.values): |
| 1302 |
try: |
| 1303 |
elcount = num / self.Z |
| 1304 |
formula_weight += elcount * float(weight_from_symbol(el.capitalize())) |
| 1305 |
formstring += f"{el}{elcount :,g} " |
| 1306 |
except ZeroDivisionError: |
| 1307 |
return '' |
| 1308 |
self.formula_weight = round(formula_weight, 3) |
| 1309 |
return formstring.strip() |
| 1310 |
|
| 1311 |
def update_weight(self) -> None: |
| 1312 |
try: |
| 1313 |
self.wght.a = self.wght_suggested.a |
| 1314 |
self.wght.b = self.wght_suggested.b |
| 1315 |
self.wght.c = self.wght_suggested.c |
| 1316 |
self.wght.d = self.wght_suggested.d |
| 1317 |
self.wght.e = self.wght_suggested.e |
| 1318 |
self.wght.f = self.wght_suggested.f |
| 1319 |
except AttributeError: |
| 1320 |
return |
| 1321 |
|
| 1322 |
def insert_anis(self, atoms: str = '', residue: str = ''): |
| 1323 |
""" |
| 1324 |
Inserts ANIS into a results file for refinement of anisotropic displacement parameters. |
| 1325 |
|
| 1326 |
TODO: implement ANIS n |
| 1327 |
@param atoms: Specify secific atoms or wildcards of atoms. |
| 1328 |
@param residue: Specify a residue like ANIS_ABC with residue='ABC' or ANIS_* (residue='*') |
| 1329 |
""" |
| 1330 |
if atoms: |
| 1331 |
self.add_line(self.unit.position, f'ANIS{"_" if residue else ""}{residue} {atoms}') |
| 1332 |
else: |
| 1333 |
self.add_line(self.unit.position, 'ANIS') |
| 1334 |
|
| 1335 |
@property |
| 1336 |
def sum_formula_exact(self) -> str: |
| 1337 |
""" |
| 1338 |
The sum formula of the structure with all atom occupancies summed together as string. |
| 1339 |
""" |
| 1340 |
formstring = '' |
| 1341 |
sumdict = self.sum_formula_exact_as_dict() |
| 1342 |
for el in sumdict: |
| 1343 |
formstring += f"{el.capitalize()}{round(sumdict[el], 2):,g} " |
| 1344 |
return formstring.strip() |
| 1345 |
|
| 1346 |
def sum_formula_exact_as_dict(self) -> dict: |
| 1347 |
""" |
| 1348 |
The sum formula of the structure with all atom occupancies summed together as dictionary. |
| 1349 |
""" |
| 1350 |
sumdict = {} |
| 1351 |
for el in self.sfac_table.elements_list: |
| 1352 |
for atom in self.atoms: |
| 1353 |
if atom.element.upper() == el.upper() and not atom.qpeak: |
| 1354 |
if el in sumdict: |
| 1355 |
sumdict[el] += atom.occupancy |
| 1356 |
else: |
| 1357 |
sumdict[el] = atom.occupancy |
| 1358 |
if el not in sumdict: |
| 1359 |
sumdict[el] = 0.0 |
| 1360 |
return sumdict |
| 1361 |
|
| 1362 |
def insert_frag_fend_entry(self, dbatoms: list, cell: list): |
| 1363 |
""" |
| 1364 |
Inserts the FRAG ... FEND entry in the res file. |
| 1365 |
:param dbatoms: list of atoms in the database entry |
| 1366 |
:param cell: string with "FRAG 17 cell" from the database entry |
| 1367 |
""" |
| 1368 |
dblist = [] |
| 1369 |
for line in dbatoms: |
| 1370 |
dblist.append("{:4} {:<4} {:>8} {:>8} {:>8}".format(*line)) |
| 1371 |
dblines = ' The following is from DSR:\n' |
| 1372 |
dblines = dblines + 'FRAG 17 {} {} {} {} {} {}'.format(*cell) + '\n' |
| 1373 |
dblines = dblines + '\n'.join(dblist) |
| 1374 |
dblines = dblines + '\nFEND\n' |
| 1375 |
|
| 1376 |
self.add_line(self.fvars.position, dblines) |
| 1377 |
|
| 1378 |
def _get_residuals(self, spline: List[str], line: str) -> None: |
| 1379 |
if Shelxfile._r1_regex.match(line): |
| 1380 |
self._get_r1(spline) |
| 1381 |
if Shelxfile._wr2_regex.match(line): |
| 1382 |
self._get_wr2(spline) |
| 1383 |
if Shelxfile._parameters_regex.match(line): |
| 1384 |
self._get_params_and_restraints(spline) |
| 1385 |
if Shelxfile._diff_peak_regex.match(line): |
| 1386 |
self._get_peak_hole(spline) |
| 1387 |
if Shelxfile._goof_regex.match(line): |
| 1388 |
self._get_goof(spline) |
| 1389 |
if Shelxfile._spgrp_regex.match(line): |
| 1390 |
self._get_space_group(spline) |
| 1391 |
|
| 1392 |
def _get_space_group(self, spline: List[str]) -> None: |
| 1393 |
try: |
| 1394 |
self.space_group = spline[3] |
| 1395 |
except(IndexError, ValueError): |
| 1396 |
pass |
| 1397 |
|
| 1398 |
def _get_goof(self, spline: List[str]) -> None: |
| 1399 |
with suppress(IndexError, ValueError): |
| 1400 |
self.goof = float(spline[8].split(',')[0]) |
| 1401 |
self.rgoof = float(spline[12].split(',')[0]) |
| 1402 |
|
| 1403 |
def _get_peak_hole(self, spline: List[str]) -> None: |
| 1404 |
|
| 1405 |
with suppress(IndexError, ValueError): |
| 1406 |
self.highest_peak = float(spline[4].split(",")[0]) |
| 1407 |
self.deepest_hole = float(spline[7].split(",")[0]) |
| 1408 |
|
| 1409 |
def _get_params_and_restraints(self, spline: List[str]) -> None: |
| 1410 |
with suppress(IndexError): |
| 1411 |
self.parameters = int(spline[1]) |
| 1412 |
if self.data and self.parameters: |
| 1413 |
self.dat_to_param = float(self.data) / float(self.parameters) |
| 1414 |
with suppress(IndexError, ValueError): |
| 1415 |
self.num_restraints = int(spline[-2]) |
| 1416 |
|
| 1417 |
def _get_wr2(self, spline: List[str]) -> None: |
| 1418 |
with suppress(IndexError, ValueError): |
| 1419 |
self.wr2 = float(spline[3].split(",")[0]) |
| 1420 |
|
| 1421 |
def _get_r1(self, spline: List[str]) -> None: |
| 1422 |
with suppress(IndexError, ValueError): |
| 1423 |
self.R1 = float(spline[3]) |
| 1424 |
with suppress(IndexError, ValueError): |
| 1425 |
self.data = int(spline[-2]) |
| 1426 |
|
| 1427 |
|
| 1428 |
if __name__ == "__main__": |
| 1429 |
print(Path('.').resolve()) |
| 1430 |
|
| 1431 |
|
| 1432 |
file = r'/Users/daniel/Documents/GitHub/FinalCif/tests/examples/Esser_JW367_0m-finalcif.res' |
| 1433 |
shx = Shelxfile(debug=True) |
| 1434 |
shx.read_file(file) |
| 1435 |
|
| 1436 |
|
| 1437 |
|
| 1438 |
|
| 1439 |
|
| 1440 |
|
| 1441 |
print(shx) |
| 1442 |
sys.exit() |
| 1443 |
|
| 1444 |
|
| 1445 |
""" |
| 1446 |
#To get all available SHELX commands: |
| 1447 |
def get_shelx_commands(): |
| 1448 |
url = "http://shelx.uni-goettingen.de/shelxl_html.php" |
| 1449 |
response = urlopen('{}/version.txt'.format(url)) |
| 1450 |
html = response.read().decode('UTF-8') |
| 1451 |
#res = BeautifulSoup(html, "html5lib") |
| 1452 |
tags = res.findAll("p", {"class": 'instr'}) |
| 1453 |
for l in tags: |
| 1454 |
if l: |
| 1455 |
print(str(l).split(">")[1].split("<")[0]) |
| 1456 |
""" |