Debian Codegraph @

shelxfile/shelx/shelx.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 __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 # noinspection PyUnresolvedReferences
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 # print(f'DEBUG: {self.debug}, VERBOSE: {self.verbose}')
104 self.restraint_errors: List[str] = []
105 self.temp_in_kelvin: float = 0.0
106 self.shelx_max_line_length: int = 79 # maximum character lenth per line in SHELXL
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 # Only used to tell the line number during an exception.
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 # print('Deleted line {}'.format(num + 1))
207 pass
208 continue
209 if line == '': # and self._reslist[num + 1] == '':
210 continue
211 # Prevent wrapping long lines with \n breaks by splitting first:
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 # Pre-compute which residue numbers contain atoms for each residue class.
261 # This allows skipping empty residues (defined by RESI but without atoms)
262 # during restraint validation, matching SHELXL's own behaviour.
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 # Warn about residues that are defined (via RESI) but contain no atoms.
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 # Skip residue numbers of this class that have no atoms at all.
286 # SHELXL silently ignores empty residues for restraints too.
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 # Tracks the file names of included files in order to find recursive inclusion:
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 # '+filename' include files are not copied to res file,
346 # so I have to delete these lines on write.
347 # '++filename' copies them to the .res file where appropriate
348 # I leave this out, because I am not SHELXL:
349 # if include_line.startswith('+') and include_line[:2] != '++':
350 # self.delete_on_write.update([lnum])
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 # Not sure if this is a good idea: del reslist[n]
357
358 def _read_included_file(self, includefiles: List[str], line: str):
359 include_filename: Path = self.resfile.resolve().parent.joinpath(line[1:])
360 # Detect recursive file inclusion:
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 # For exception during parsing.
387 list_of_lines = [line_num] # list of lines where a card appears, e.g. for atoms with two lines
388 if line.startswith(' ') or line == '':
389 continue
390 wrapindex = 0
391 # This while loop makes wrapped lines look like they are not wrapped. The following lines are then
392 # beginning with a space character and thus are ignored. The 'lines' list holds the line nnumbers where
393 # 'line' is located ([line_num]) plus the wrapped lines.
394 if multiline_test(self._reslist[line_num]):
395 multiline = True
396 else:
397 multiline = False
398 while multiline:
399 # Glue together the two lines wrapped with "=":
400 wrapindex += 1
401 line = line.rpartition('=')[0] + self._reslist[line_num + wrapindex]
402 # self.delete_on_write.update([line_num + wrapindex])
403 list_of_lines.append(line_num + wrapindex) # list containing the lines of a multiline command
404 # Do not activate this, otherwise, the unwrapping stops after two lines.
405 if multiline_test(self._reslist[line_num + wrapindex]):
406 multiline = True
407 else:
408 multiline = False
409 self._reslist[line_num + wrapindex] = ''
410 # The current line split:
411 spline: list = line.split('!')[0].split() # Ignore comments with "!"
412 # The current line as string:
413 line = line.upper().split('!')[0] # Ignore comments with "!"
414 word = line[:4]
415 # get RESI:
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 # Do not continue here, otherwise HKLF is not parsed
421 # continue
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 # Now collect the PART:
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 # Do not continue here, otherwise HKLF is not parsed
433 # continue
434 if word == 'PART':
435 self.part = self._assign_card(PART(self, spline), line_num)
436 continue
437 # collect AFIX:
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 # A SHELXL atom:
446 # F9 4 0.395366 0.177026 0.601546 21.00000 0.03231 ( 0.03248 =
447 # 0.03649 -0.00522 -0.01212 0.00157 )
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 # SADI s[0.02] pairs of atoms
458 # or SADI
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 # DFIX d s[0.02] atom pairs
464 self._append_card(self.restraints, DFIX(self, spline), line_num)
465 elif word == 'SIMU':
466 # SIMU s[0.04] st[0.08] dmax[2.0] atomnames
467 self._append_card(self.restraints, SIMU(self, spline), line_num)
468 elif word == 'DELU':
469 # DELU s1[0.01] s2[0.01] atomnames
470 self._append_card(self.restraints, DELU(self, spline), line_num)
471 elif word == 'RIGU':
472 # RIGU s1[0.004] s2[0.004] atomnames
473 self._append_card(self.restraints, RIGU(self, spline), line_num)
474 elif word == 'BASF':
475 # BASF scale factors
476 self._assign_card(BASF(self, spline), line_num)
477 elif word == 'HFIX':
478 # HFIX mn U[#] d[#] atomnames
479 self._append_card(self.hfixes, HFIX(self, spline), line_num)
480 elif word == 'DANG':
481 # DANG d s[0.04] atom pairs
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 # CELL λ a b c α β γ
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 # ZERR Z esd(a) esd(b) esd(c) esd(α) esd(β) esd(γ)
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 # LATT N[1]
518 # 1=P, 2=I, 3=rhombohedral obverse on hexagonal axes, 4=F, 5=A, 6=B, 7=C.
519 # negative is non-centrosymmetric
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 # SYMM symmetry operation
527 # Being more greedy, because many files do this wrong:
528 # if not lastcard == 'ZERR':
529 # raise ParseOrderError
530 # if not self.zerr:
531 # raise ParseOrderError
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 # Have to do this after parsing, because P-1 has no SYMM!
538 # if self.latt.centric:
539 # self.symmcards.set_centric(True)
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 # SFAC elements or
549 # SFAC E a1 b1 a2 b2 a3 b3 a4 b4 c f' f" mu r wt
550 # Being less strict to be able to parse files without cell errors:
551 # if not (lastcard == 'LATT' or lastcard == 'ZERR'):
552 # raise ParseOrderError
553 # if not self.symmcards:
554 # raise ParseOrderError
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 # UNIT n1 n2 ...
566 # Number of atoms of each type in the unit-cell, in SFAC order.
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 # CGLS nls[0] nrf[0] nextra[0]
586 # L.S. nls[0] nrf[0] nextra[0]
587 self.cycles = self._assign_card(LSCycles(self, spline), line_num)
588 elif word == "LIST":
589 # LIST m[#] mult[1] (mult is for list 4 only)
590 self.list = int(spline[1])
591 elif word == "FVAR":
592 # FVAR osf[1] free variables
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 # ANIS n or ANIS names
602 # Must be before Atom(), to know which atom is anis.
603 self.anis = self._assign_card(ANIS(self, spline), line_num)
604 elif word == 'WGHT':
605 # WGHT a[0.1] b[0] c[0] d[0] e[0] f[.33333]
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 # ACTA 2θfull[#] -> optional parameter NOHKL
612 self.acta = self._assign_card(ACTA(self, spline), line_num)
613 elif word == 'DAMP':
614 # DAMP damp[0.7] limse[15]
615 self.damp = self._assign_card(DAMP(self, spline), line_num)
616 elif word == 'ABIN':
617 # ABIN n1 n2
618 self.abin = self._assign_card(ABIN(self, spline), line_num)
619 elif word == 'ANSC':
620 # ANSC six coefficients
621 if len(spline) == 7:
622 self.ansc = [float(x) for x in spline[:1]]
623 elif word == 'ANSR':
624 # ANSR anres[0.001]
625 if len(spline) == 2:
626 self.ansr = float(spline[1])
627 elif word == 'BIND':
628 # BIND atom1 atom2
629 if len(spline) == 3:
630 self._append_card(self.bind, BIND(self, spline), line_num)
631 elif word == 'BLOC':
632 # BLOC n1 n2 atomnames
633 self._append_card(self.bloc, BLOC(self, spline), line_num)
634 elif word == 'BOND':
635 # BOND atomnames
636 self._append_card(self.bonds, BOND(self, spline), line_num)
637 elif word == 'BUMP':
638 # BUMP s [0.02]
639 self._assign_card(BUMP(self, spline), line_num)
640 elif word == 'CHIV':
641 # CHIV V[0] s[0.1] atomnames
642 self._append_card(self.restraints, CHIV(self, spline), line_num)
643 elif word == 'CONF':
644 # CONF atomnames max_d[1.9] max_a[170]
645 self.conf = self._assign_card(CONF(self, spline), line_num)
646 elif word == 'CONN':
647 # CONN bmax[12] r[#] atomnames or CONN bmax[12]
648 # bonded are d < (r1 + r2 + 0.5) Å
649 self.conn = self._assign_card(CONN(self, spline), line_num)
650 elif word == 'DEFS':
651 # DEFS sd[0.02] sf[0.1] su[0.01] ss[0.04] maxsof[1]
652 self.defs = self._assign_card(DEFS(self, spline), line_num)
653 elif word == 'DISP':
654 # DISP E f' f"[#] mu[#]
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 # EQIV $n symmetry operation
660 # TODO: implement EQUIV class
661 if len(spline) > 1 and spline[1].startswith('$'):
662 self.eqiv.append(spline[1:])
663 elif word == 'EXTI':
664 # EXTI x[0]
665 self.exti = float(spline[1])
666 elif word == 'EXYZ':
667 # EXYZ atomnames
668 self._append_card(self.restraints, EXYZ(self, spline), line_num)
669 elif word == 'FRAG':
670 # FRAG code[17] a[1] b[1] c[1] α[90] β[90] γ[90]
671 if len(spline) == 8:
672 self.frag = self._assign_card(FRAG(self, spline), line_num)
673 elif word == 'FEND':
674 # FEND (must follow FRAG)
675 if not self.frag:
676 raise ParseOrderError(debug=shx.debug, verbose=shx.verbose)
677 self.frag = None # Turns frag mode off.
678 elif word == 'FLAT':
679 # FLAT s[0.1] four or more atoms
680 self._append_card(self.restraints, FLAT(self, spline), line_num)
681 elif word == 'FREE':
682 # FREE atom1 atom2
683 self._append_card(self.free, FREE(self, spline), line_num)
684 elif word == 'GRID':
685 # GRID sl[#] sa[#] sd[#] dl[#] da[#] dd[#]
686 self.grid = self._assign_card(GRID(self, spline), line_num)
687 elif word == 'HKLF':
688 # HKLF N[0] S[1] r11...r33[1 0 0 0 1 0 0 0 1] sm[1] m[0]
689 self.hklf = self._assign_card(HKLF(self, spline), line_num)
690 elif line.startswith('END'):
691 # END (after HKLF or ends an include file)
692 self.end = True
693 elif word == 'HTAB':
694 # HTAB dh[2.0] or HTAB donor-atom acceptor-atom
695 self.htab = self._assign_card(HTAB(self, spline), line_num)
696 elif word == 'ISOR':
697 # ISOR s[0.1] st[0.2] atomnames
698 self._append_card(self.restraints, ISOR(self, spline), line_num)
699 elif word == 'LAUE':
700 # LAUE E
701 # I completely do not understand the LAUE instruction description in the manual!
702 continue
703 elif word == 'MERG':
704 # MERG n[2]
705 self.merg = self._assign_card(MERG(self, spline), line_num)
706 elif word == 'MORE':
707 # MORE m[1]
708 self.more = self._assign_card(MORE(self, spline), line_num)
709 elif word == 'FMAP':
710 # FMAP code[2] axis[#] nl[53]
711 self.fmap = self._assign_card(FMAP(self, spline), line_num)
712 elif word == 'MOVE':
713 # MOVE dx[0] dy[0] dz[0] sign[1]
714 self.move = self._assign_card(MOVE(self, spline), line_num)
715 elif word == 'MPLA':
716 # MPLA na atomnames
717 self.mpla = self._assign_card(MPLA(self, spline), line_num)
718 elif word == 'NCSY':
719 # NCSY DN sd[0.1] su[0.05] atoms
720 self._append_card(self.restraints, NCSY(self, spline), line_num)
721 elif word == 'NEUT':
722 # NEUT
723 # TODO: Implement NEUT class
724 if lastcard != 'SYMM':
725 raise ParseOrderError(debug=shx.debug, verbose=shx.verbose)
726 elif word == 'OMIT':
727 # OMIT atomnames or OMIT s[-2] 2θ(lim)[180] or OMIT h k l
728 # TODO: Implement OMIT class
729 self.omit.append(spline[1:])
730 elif word == 'PLAN':
731 # PLAN npeaks[20] d1[#] d2[#]
732 self.plan = self._assign_card(PLAN(self, spline), line_num)
733 elif word == 'PRIG':
734 # PRIG p[#]
735 self.prig = self._assign_card(PRIG(self, spline), line_num)
736 elif word == 'RTAB':
737 # RTAB codename atomnames --> codename: e.g. 'omeg' gets tabualted in the lst
738 self._append_card(self.rtab, RTAB(self, spline), line_num)
739 elif word == 'SAME':
740 # SAME s1[0.02] s2[0.04] atomnames
741 self._append_card(self.restraints, SAME(self, spline), line_num)
742 elif word == 'SHEL':
743 # SHEL lowres[infinite] highres[0]
744 self.shel = self._assign_card(SHEL(self, spline), line_num)
745 elif word == 'SIZE':
746 # SIZE dx dy dz
747 self.size = self._assign_card(SIZE(self, spline), line_num)
748 elif word == 'SPEC':
749 # SPEC del[0.2]
750 if len(spline) > 1:
751 self.spec = self._assign_card(SPEC(self, spline), line_num)
752 elif word == 'STIR':
753 # STIR sres step[0.01] -> stepwise improvement in the resolution sres
754 self.stir = self._assign_card(STIR(self, spline), line_num)
755 elif word == 'SUMP':
756 # SUMP c sigma c1 m1 c2 m2 ...
757 self._append_card(self.sump, SUMP(self, spline), line_num)
758 elif word == 'SWAT':
759 # SWAT g[0] U[2]
760 self.swat = self._assign_card(SWAT(self, spline), line_num)
761 elif word == 'TEMP':
762 # TEMP T[20] -> in Celsius
763 self.temp = float(spline[1].split('(')[0])
764 self.temp_in_kelvin = self.temp + 273.15
765 elif word == 'TWIN':
766 # TWIN 3x3 matrix [-1 0 0 0 -1 0 0 0 -1] N[2]
767 self.twin = self._assign_card(TWIN(self, spline), line_num)
768 elif word == 'TWST':
769 # TWST N[0] (N[1] after SHELXL-2018/3)
770 if len(spline) > 1:
771 self.twst = self._assign_card(TWST(self, spline), line_num)
772 elif word == 'WIGL':
773 # WIGL del[0.2] dU[0.2]
774 self.wigl = self._assign_card(WIGL(self, spline), line_num)
775 elif word == 'WPDB':
776 # WPDB n[1]
777 self.wpdb = self._assign_card(WPDB(self, spline), line_num)
778 elif word == 'XNPD':
779 # XNPD Umin[-0.001]
780 self.xnpd = self._assign_card(XNPD(self, spline), line_num)
781 elif word == 'BEDE':
782 # Later...
783 continue
784 elif word == 'LONE':
785 # Later...
786 continue
787 elif word == 'MOLE':
788 # print('*** MOLE is deprecated! Do not use it! ***')
789 pass
790 elif word == 'HOPE':
791 # print('*** HOPE is deprecated! Do not use it! ***')
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 # Find last non-Q-peak atom
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 # Fall back to before HKLF
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 # e.g. 999 for 1-char element, 99 for 2-char
861 existing = set(self.atoms.nameslist) # upper-cased "NAME_RESINUM"
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 # --- guard against mixed occupation styles ---
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 # --- validate name uniqueness ---
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 # --- resolve site-occupation factor ---
948 if occupancy is not None:
949 sof = fvar * 10 + occupancy
950 elif sof is None:
951 sof = 11.0 # default: fvar 1, fully occupied
952 # --- normalise uvals ---
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 # --- convert coordinates if needed ---
958 if coords_are_cartesian:
959 coordinates = list(cart_to_frac(coordinates, list(self.cell)))
960 # --- auto-register element in SFAC/UNIT ---
961 if not self.sfac_table.has_element(element):
962 self.sfac_table.add_element(element)
963 sfac_num = self.elem2sfac(element)
964 # --- build context cards ---
965 part_card = PART(self, f'PART {part}'.split())
966 afix_card = AFIX(self, 'AFIX 0'.split())
967 # Resolve residue: look for an existing RESI card matching *resi*, else create one.
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 # --- construct atom ---
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 # --- insert into _reslist at the correct position ---
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 # Prevent wrapping long lines with \n breaks by splitting first:
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 # ── Warning comment ───────────────────────────────────────────────
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 # ── Iterate the original _reslist, filtering/transforming as needed ──
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 # Skip original atoms — replaced by the grown atom list
1071 if isinstance(item, Atom):
1072 continue
1073
1074 # Skip SYMM cards — P1 has no extra symmetry operations
1075 if isinstance(item, SYMM):
1076 continue
1077
1078 # Skip all restraints — they reference asymmetric-unit atom names
1079 if isinstance(item, Restraint):
1080 continue
1081
1082 # Skip instruction cards that only make sense in the context of
1083 # the original asymmetric unit
1084 if isinstance(item, (AFIX, PART, RESI, HFIX, ANIS)):
1085 continue
1086
1087 # Skip refinement-specific cards not needed in a visualization file
1088 if isinstance(item, (ACTA, CONF)):
1089 continue
1090
1091 # Skip include-file references (+filename) — they are local to the
1092 # original file's directory and would not resolve for the grown output
1093 if isinstance(item, str) and item.startswith('+'):
1094 continue
1095
1096 # Replace LATT with LATT -1 (primitive, non-centrosymmetric = P1)
1097 if isinstance(item, LATT):
1098 lines.append('LATT -1')
1099 continue
1100
1101 # Before the HKLF card: insert grown atoms with PART grouping
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 # self.write_shelx_file(filen + '.res')
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 # no empty line, not in cards and not space at start:
1194 if atomline[:4].upper() not in SHX_CARDS: # exclude all non-atom cards
1195 spline: List[str] = atomline.split()
1196 # Too few parameter for an atom:
1197 if len(spline) < 5:
1198 return False
1199 # means sfac number is missing:
1200 if '.' in spline[1]:
1201 return False
1202 if Shelxfile._coordinates_are_unrealistic(spline):
1203 return False
1204 # Exclude lone pairs:
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 # Inline coordinate-realism check (avoids genexpr + slice + function call):
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 # return sfac number
1258 # Element was not found in sfac table
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 # insert the db entry right after FVAR
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 # REM Highest difference peak 0.407, deepest hole -0.691, 1-sigma level 0.073
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 # file = r'../shelxfile/tests/resources/p21c.res'
1431 # file = r'D:\_DEV\GitHub\ShelXFile\tests\resources\test_bedelone.res'
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 # print(shx.atoms)
1436 # print(shx.sum_formula_exact)
1437 # print(shx.sum_formula)
1438 # print(shx.sum_formula_exact_as_dict())
1439 # print(shx.restraints)
1440 # print(shx.atoms.nameslist)
1441 print(shx)
1442 sys.exit()
1443
1444 # noinspection PyUnreachableCode
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 """