Debian Codegraph @

shelxfile/shelx/cards.py

raw symbols SCIP
1 import re
2 from math import cos, radians, sqrt, sin
3 from typing import List, Union, TYPE_CHECKING, Optional, Iterator, Tuple, Dict, Generator
4
5 from shelxfile.atoms.pairs import AtomPair
6 from shelxfile.misc.dsrmath import my_isnumeric, SymmetryElement, OrthogonalMatrix, Matrix
7 from shelxfile.misc.misc import chunks, ParseParamError, ParseNumError, \
8 ParseOrderError, ParseSyntaxError
9
10 if TYPE_CHECKING:
11 from shelxfile import Shelxfile
12 from shelxfile.atoms.atom import Atom
13 """
14 SHELXL cards:
15
16 ABIN n1 n2
17 ACTA 2θfull[#]
18 AFIX mn d[#] sof[11] U[10.08]
19 ANIS n
20 ANIS names
21 ANSC six coefficients
22 ANSR anres[0.001]
23 BASF scale factors
24 BIND atom1 atom2
25 BIND m n
26 BLOC n1 n2 atomnames
27 BOND atomnames
28 BUMP s [0.02]
29 CELL λ a b c α β γ
30 CGLS nls[0] nrf[0] nextra[0]
31 CHIV V[0] s[0.1] atomnames
32 CONF atomnames max_d[1.9] max_a[170]
33 CONN bmax[12] r[#] atomnames or CONN bmax[12]
34 DAMP damp[0.7] limse[15]
35 DANG d s[0.04] atom pairs
36 DEFS sd[0.02] sf[0.1] su[0.01] ss[0.04] maxsof[1]
37 DELU s1[0.01] s2[0.01] atomnames
38 DFIX d s[0.02] atom pairs
39 DISP E f' f"[#] mu[#]
40 EADP atomnames
41 END
42 EQIV $n symmetry operation
43 EXTI x[0]
44 EXYZ atomnames
45 FEND
46 FLAT s[0.1] four or more atoms
47 FMAP code[2] axis[#] nl[53]
48 FRAG code[17] a[1] b[1] c[1] α[90] β[90] γ[90]
49 FREE atom1 atom2
50 FVAR osf[1] free variables
51 GRID sl[#] sa[#] sd[#] dl[#] da[#] dd[#]
52 HFIX mn U[#] d[#] atomnames
53 HKLF N[0] S[1] r11...r33[1 0 0 0 1 0 0 0 1] sm[1] m[0]
54 HTAB dh[2.0]
55 HTAB donor-atom acceptor-atom
56 ISOR s[0.1] st[0.2] atomnames
57 LATT N[1]
58 LAUE E
59 LIST m[#] mult[1]
60 L.S. nls[0] nrf[0] nextra[0]
61 MERG n[2]
62 MORE m[1]
63 MOVE dx[0] dy[0] dz[0] sign[1]
64 MPLA na atomnames
65 NCSY DN sd[0.1] su[0.05] atoms
66 NEUT
67 OMIT atomnames
68 OMIT s[-2] 2θ(lim)[180]
69 OMIT h k l
70 PART n sof
71 PLAN npeaks[20] d1[#] d2[#]
72 PRIG p[#]
73 REM
74 RESI class[ ] number[0] alias
75 RIGU s1[0.004] s2[0.004] atomnames
76 RTAB codename atomnames
77 SADI s[0.02] pairs of atoms
78 SAME s1[0.02] s2[0.04] atomnames
79 SFAC elements
80 SFAC E a1 b1 a2 b2 a3 b3 a4 b4 c f' f" mu r wt
81 SHEL lowres[infinite] highres[0]
82 SIMU s[0.04] st[0.08] dmax[2.0] atomnames
83 SIZE dx dy dz
84 SPEC del[0.2]
85 STIR sres step[0.01]
86 SUMP c sigma c1 m1 c2 m2 ...
87 SWAT g[0] U[2]
88 SYMM symmetry operation
89 TEMP T[20]
90 TITL [ ]
91 TWIN 3x3 matrix [-1 0 0 0 -1 0 0 0 -1] N[2]
92 TWST N[0]
93 UNIT n1 n2 ...
94 WGHT a[0.1] b[0] c[0] d[0] e[0] f[.33333]
95 WIGL del[0.2] dU[0.2]
96 WPDB n[1]
97 XNPD Umin[-0.001]
98 ZERR Z esd(a) esd(b) esd(c) esd(α) esd(β) esd(γ)
99 """
100
101
102 class Residue():
103 def __init__(self):
104 self.shx: Optional['Shelxfile'] = None
105 self._spline: str = ''
106 self.residue_class: str = '' # '' is the default class (with residue number 0)
107
108 @property
109 def residue_number(self) -> List[int]:
110 if '_' in self._spline[0] and '$' not in self._spline[0]:
111 _, suffix = self._spline[0].upper().split('_')
112 if suffix.isdigit():
113 # TODO: implement _+, _- and _*
114 if '*' in suffix:
115 return list(self.shx.residues.residue_numbers.keys()) # type: ignore
116 else:
117 return [int(suffix)]
118 return self.shx.residues.residue_classes.get(self.residue_class, [0]) # type: ignore
119
120
121 class Restraint(Residue):
122
123 def __init__(self, shx: 'Shelxfile', spline: list):
124 """
125 Base class for parsing restraints.
126 TODO: resolve ranges like SADI_CCF3 O1 > F9
127 """
128 super().__init__()
129 self.shx: 'Shelxfile' = shx
130 self.textline: str = ' '.join(spline)
131 self.name: Optional[str] = None
132 self.atoms: List[Atom] = []
133
134 @property
135 def index(self) -> int:
136 return self.shx.index_of(self)
137
138 def _parse_line(self, spline: List[str]):
139 """
140 Residues may be referenced by any instruction that allows atom names; the reference takes
141 the form of the character '_' followed by either the residue class or number without intervening
142 spaces.
143 Individual atom names in an instruction may be followed by '_' and a residue number, but not by '_* ' or '_'
144 and a residue class. If an atom name is not followed by a residue number, the current residue is
145 assumed (unless overridden by a global residue number or class appended to the instruction
146 codeword).
147 """
148 self._spline = spline
149 if '_' in spline[0]:
150 self.name, suffix = spline[0].upper().split('_')
151 # a residue class has to start with a letter, but can contain numbers:
152 if len(suffix) > 0 and re.match(r'[a-zA-Z]', suffix):
153 self.residue_class: str = suffix
154 else:
155 self.name = spline[0].upper()
156 self._set_defs_values()
157 self._check_if_class_name_fits_to_command()
158 params = []
159 atoms = []
160 for x in spline[1:]:
161 if my_isnumeric(x):
162 params.append(float(x))
163 else:
164 atoms.append(x)
165 # if pairs:
166 # return params, self.get_atompairs(atoms)
167 # else:
168 return params, atoms
169
170 def _get_atompairs(self, atoms: List[str]) -> List[AtomPair]:
171 pairs = []
172 for p in chunks(atoms, 2):
173 pairs.append(AtomPair(*p))
174 return pairs
175
176 def _check_if_class_name_fits_to_command(self) -> None:
177 if self.shx.debug and self.__class__.__name__ != self.name:
178 print('*** Trying to parse restraint with wrong class ***')
179 raise ParseSyntaxError(debug=self.shx.debug, verbose=self.shx.verbose)
180
181 def _set_defs_values(self) -> None:
182 # Beware! DEFS changes only the non-defined default values:
183 # DEFS sd[0.02] sf[0.1] su[0.01] ss[0.04] maxsof[1]
184 if self.shx.defs: # and self.shx.defs.active:
185 if self.name == 'DFIX':
186 self.s = self.shx.defs.sd
187 if self.name == 'SAME':
188 self.s1 = self.shx.defs.sd
189 self.s2 = self.shx.defs.sd * 2
190 if self.name == 'SADI':
191 self.s = self.shx.defs.sd
192 if self.name == 'CHIV':
193 self.s = self.shx.defs.sf
194 if self.name == 'FLAT':
195 self.s = self.shx.defs.sf
196 if self.name == 'DELU':
197 self.s1 = self.shx.defs.su
198 self.s2 = self.shx.defs.su
199 if self.name == 'SIMU':
200 self.s = self.shx.defs.ss
201 self.st = self.shx.defs.ss * 2
202
203 def _paircheck(self):
204 if not self.atoms:
205 return
206 if len(self.atoms) % 2 != 0 and (self.shx.debug or self.shx.verbose):
207 print('*** Wrong number of numerical parameters ***')
208 print('Instruction: {}'.format(self.textline))
209 if self.shx.debug:
210 raise ParseNumError(debug=self.shx.debug, verbose=self.shx.verbose)
211
212 def __iter__(self) -> Iterator[str]:
213 for x in self.textline.split():
214 yield x
215
216 def __repr__(self) -> str:
217 return self.textline
218
219 def __str__(self) -> str:
220 return self.textline
221 '''# print(self.atoms, self.residue_number)
222 s = self.s if hasattr(self, 's') else ''
223 s1 = self.s1 if hasattr(self, 's1') else ''
224 s2 = self.s2 if hasattr(self, 's2') else ''
225 st = self.st if hasattr(self, 'st') else ''
226 return f"{self.name}" \
227 f"{' ' if s else ''}{s}" \
228 f"{' ' if s1 else ''}{s1}" \
229 f"{' ' if s2 else ''}{s2}" \
230 f"{' ' if st else ''}{st} " \
231 f"{' '.join(self.atoms)}"'''
232
233 def split(self):
234 return self.textline.split()
235
236
237 class Command():
238 """
239 A class to parse all general commands except restraints.
240 """
241
242 def __init__(self, shx: 'Shelxfile', spline: List[str]):
243 self._shx: 'Shelxfile' = shx
244 self._spline: List[str] = spline
245 self.residue_class: str = ''
246 self._textline: str = ' '.join(spline)
247
248 def _parse_line(self, spline: List[str], intnums: bool = False) -> Tuple[List[Union[int, float]], List[str]]:
249 """
250 :param spline: Split shelxl line
251 :param intnums: if numerical parameters should be integer
252 :return: Tuple of (numerical parameter, words)
253 """
254 if '_' in spline[0]:
255 self._card_name, suffix = spline[0].upper().split('_')
256 else:
257 self._card_name = spline[0].upper()
258 numparams = []
259 words = []
260 for x in spline[1:]: # all values after SHELX card
261 if str.isdigit(x[0]) or x[0] in '+-':
262 if intnums:
263 numparams.append(int(x))
264 else:
265 numparams.append(float(x))
266 else:
267 words.append(x)
268 return numparams, words
269
270 def set(self, value):
271 self.__init__(self._shx, value.split())
272
273 @property
274 def index(self):
275 return self._shx.index_of(self)
276
277 @property
278 def position(self) -> int:
279 return self.index
280
281 def __iter__(self):
282 for x in self.__repr__().split():
283 yield x
284
285 def split(self):
286 return self._textline.split()
287
288 def __str__(self):
289 return self._textline
290
291 def __repr__(self):
292 return self._textline
293
294
295 class ABIN(Command):
296
297 def __init__(self, shx, spline):
298 """
299 ABIN n1 n2
300 """
301 super(ABIN, self).__init__(shx, spline)
302 p, _ = self._parse_line(spline)
303 if len(p) > 0:
304 self.n1 = p[0]
305 if len(p) > 1:
306 self.n2 = p[1]
307
308
309 class ANIS(Command):
310
311 def __init__(self, shx, spline: List):
312 """
313 ANIS
314 ANIS n
315 ANIS names
316
317 Make either all atoms anisotropic (with just ANIS) or specific atoms with ANIS names.
318 Also, wildcards like 'ANIS $CL' would make all chlorine atoms anisotropic.
319 Since ANIS, like other instructions, applies to the current residue unless otherwise specified,
320 ANIS_* $S would be required to make the sulfur atoms in all residues anisotropic.
321 ANIS n makes the next n isotropic non-hydrogen atoms anisotropic.
322 """
323 super(ANIS, self).__init__(shx, spline)
324 p, self.atoms = self._parse_line(spline)
325 self.over_all = True
326 if len(p) > 0:
327 self.over_all = False
328 self.n = p[0]
329 if len(self.atoms) > 0:
330 self.over_all = False
331
332 def __bool__(self):
333 return True
334
335
336 class MPLA(Command):
337
338 def __init__(self, shx, spline: List):
339 """
340 MPLA na atomnames
341 """
342 super(MPLA, self).__init__(shx, spline)
343 p, self.atoms = self._parse_line(spline, intnums=True)
344 if len(p) > 0:
345 self.na = p[0]
346
347
348 class MORE(Command):
349
350 def __init__(self, shx, spline: List):
351 """
352 MORE m[1]
353 """
354 super(MORE, self).__init__(shx, spline)
355 self.m = 1
356 p, _ = self._parse_line(spline, intnums=True)
357 self.m = p[0]
358
359
360 class CELL(Command):
361
362 def __init__(self, shx, spline: List):
363 """
364 CELL λ a b c α β γ
365 """
366 super(CELL, self).__init__(shx, spline)
367 p, _ = self._parse_line(spline)
368 self._cell_list = []
369 if len(p) > 0:
370 self.wavelen = float(p[0])
371 if len(p) > 6:
372 self._cell_list = p[1:]
373 self.a = p[1]
374 self.b = p[2]
375 self.c = p[3]
376 self.alpha = p[4]
377 self.beta = p[5]
378 self.gamma = p[6]
379 self.cosal = cos(radians(self.alpha))
380 self.cosbe = cos(radians(self.beta))
381 self.cosga = cos(radians(self.gamma))
382 self.V = self.volume
383 self.o = OrthogonalMatrix(self.a, self.b, self.c, self.alpha, self.beta, self.gamma)
384 # Precompute flat matrix elements for fast frac→cart (avoids trig per atom).
385 # The orthogonalisation matrix is upper-triangular:
386 # [M00 M01 M02] [a b·cos γ c·cos β ]
387 # [ 0 M11 M12] = [0 b·sin γ c·(cos α-cos β·cos γ)/sin γ]
388 # [ 0 0 M22] [0 0 V/(a·b·sin γ) ]
389 _vals = self.o.m.values
390 self._M00: float = _vals[0][0]
391 self._M01: float = _vals[0][1]
392 self._M02: float = _vals[0][2]
393 self._M11: float = _vals[1][1]
394 self._M12: float = _vals[1][2]
395 self._M22: float = _vals[2][2]
396 # calculate reciprocal lattice vectors:
397 self.astar = (self.b * self.c * sin(radians(self.alpha))) / self.V
398 self.bstar = (self.a * self.c * sin(radians(self.beta))) / self.V
399 self.cstar = (self.a * self.b * sin(radians(self.gamma))) / self.V
400 # matrix with the reciprocal lattice vectors:
401 self.N = Matrix([[self.astar, 0, 0],
402 [0, self.bstar, 0],
403 [0, 0, self.cstar]])
404 else:
405 raise ParseSyntaxError(debug=shx.debug, verbose=shx.verbose)
406
407 @property
408 def volume(self) -> float:
409 """
410 calculates the volume of a unit cell
411 """
412 try:
413 ca, cb, cg = cos(radians(self.alpha)), cos(radians(self.beta)), cos(radians(self.gamma))
414 v = self.a * self.b * self.c * sqrt(1 + 2 * ca * cb * cg - ca ** 2 - cb ** 2 - cg ** 2)
415 except AttributeError:
416 # No valid celll
417 v = 0.0
418 return v
419
420 def __iter__(self):
421 return iter(self._cell_list)
422
423 def __getitem__(self, item: Union[slice, int]) -> Union[List[float], float]:
424 return self._cell_list[item]
425
426
427 class ZERR(Command):
428
429 def __init__(self, shx, spline: List):
430 """
431 ZERR Z esd(a) esd(b) esd(c) esd(α) esd(β) esd(γ)
432 """
433 super(ZERR, self).__init__(shx, spline)
434 p, _ = self._parse_line(spline)
435 self.Z = 1
436 if len(p) > 0:
437 self.Z = p[0]
438 if len(p) > 6:
439 self.esd_list = p[1:]
440 self.esd_a = p[0]
441 self.esd_b = p[1]
442 self.esd_c = p[2]
443 self.esd_al = p[3]
444 self.esd_be = p[4]
445 self.esd_ga = p[5]
446
447
448 class AFIX(Command):
449
450 def __init__(self, shx, spline: list):
451 """
452 AFIX mn d[#] sof[11] U[10.08]
453 """
454 super(AFIX, self).__init__(shx, spline)
455 p, _ = self._parse_line(spline)
456 self.U = 10.08
457 self.sof = 11.0
458 self.mn = None
459 self.d = None
460 if len(p) > 0:
461 self.mn = int(p[0])
462 if len(p) > 1:
463 self.d = p[1]
464 if len(p) > 2:
465 self.sof = p[2]
466 if len(p) > 3:
467 self.U = p[3]
468
469 def __bool__(self):
470 if self.mn and self.mn > 0:
471 return True
472 else:
473 return False
474
475
476 class Residues():
477
478 def __init__(self, shx):
479 self.shx = shx
480 self.all_residues: list = []
481 self.residue_classes: dict = {} # class: numbers
482
483 def append(self, resi: 'RESI') -> None:
484 """
485 Adds a new residues to the list of residues.
486 """
487 self.all_residues.append(resi)
488 # Collect dict with class: numbers
489 if resi.residue_class in self.residue_classes:
490 self.residue_classes[resi.residue_class].append(resi.residue_number)
491 else:
492 self.residue_classes[resi.residue_class] = [resi.residue_number]
493
494 @property
495 def residue_numbers(self):
496 return dict((x.residue_number, x.residue_class) for x in self.shx.residues.all_residues)
497
498
499 class RESI(Command):
500
501 def __init__(self, shx: 'Shelxfile', spline: List[str]):
502 """
503 RESI class[ ] number[0] alias
504 """
505 super().__init__(shx, spline)
506 self.shx = shx
507 self.residue_class = ''
508 self.residue_number: int = 0
509 self.alias: Optional[int] = None
510 self.chain_id: Optional[int] = None
511 self._textline: str = ' '.join(spline)
512 if len(spline) < 2 and (self.shx.debug or self.shx.verbose):
513 print('*** Wrong RESI definition found! Check your RESI instructions ***')
514 raise ParseParamError(debug=self.shx.debug, verbose=self.shx.verbose)
515 self._get_resi_definition(spline)
516 if self.residue_number < -999 or self.residue_number > 9999:
517 if self.shx.debug or self.shx.verbose:
518 print('*** Invalid residue number given. ****')
519 if self.shx.debug:
520 raise ParseSyntaxError(debug=self.shx.debug, verbose=self.shx.verbose)
521
522 def _get_resi_definition(self, resi: List[str]) -> Tuple[str, int, str, int]:
523 """
524 RESI class[ ] number[0] alias
525
526 Returns the residue number and class of a string like 'RESI TOL 1'
527 or 'RESI 1 TOL'
528
529 Residue names may now begin with a digit.
530 They must however contain at least one letter
531
532 Allowed residue numbers is now from -999 to 9999 (2017/1)
533 """
534 alpha = re.compile('[a-zA-Z]')
535 for x in resi:
536 if alpha.search(x):
537 if ':' in x:
538 # contains ":" thus must be a chain-id+number
539 self.chain_id, self.residue_number = x.split(':')[0], int(x.split(':')[1])
540 else:
541 # contains letters, must be a name (class)
542 self.residue_class = x
543 else:
544 # everything else can only be a number
545 if self.residue_number > 0:
546 self.alias = int(x)
547 else:
548 try:
549 self.residue_number = int(x)
550 except ValueError:
551 self.residue_number = 0
552 return self.residue_class, self.residue_number, self.chain_id, self.alias
553
554 def __bool__(self) -> bool:
555 if self.residue_number > 0:
556 return True
557 else:
558 return False
559
560
561 class PART(Command):
562
563 def __init__(self, shx, spline: list):
564 """
565 PART n sof
566 """
567 super(PART, self).__init__(shx, spline)
568 p, _ = self._parse_line(spline)
569 self.sof = 11.0
570 self.n = 0
571 try:
572 self.n = int(p[0])
573 except(ValueError, IndexError):
574 if self.shx.debug or self.shx.verbose:
575 print('*** Wrong PART definition in line {} found! '
576 'Check your PART instructions ***'.format(shx.error_line_num))
577 if self.shx.debug:
578 raise ParseSyntaxError(debug=True)
579 self.n = 0
580 if len(p) > 1:
581 self.sof = float(p[1])
582
583 def __bool__(self):
584 if self.n > 0:
585 return True
586 else:
587 return False
588
589
590 class XNPD(Command):
591
592 def __init__(self, shx, spline: list):
593 """
594 XNPD Umin[-0.001]
595 """
596 super(XNPD, self).__init__(shx, spline)
597 p, _ = self._parse_line(spline)
598 self.Umin = -0.001
599 if len(p) > 0:
600 self.Umin = p[0]
601
602
603 class SIZE(Command):
604
605 def __init__(self, shx, spline: list):
606 """
607 SIZE dx dy dz
608 """
609 super(SIZE, self).__init__(shx, spline)
610 self.dx, self.dy, self.dz = None, None, None
611 p, _ = self._parse_line(spline)
612 if len(p) > 0:
613 self.dx = p[0]
614 if len(p) > 1:
615 self.dy = p[1]
616 if len(p) > 2:
617 self.dz = p[2]
618
619 def _as_text(self):
620 if all([self.dx, self.dy, self.dz]):
621 return "SIZE {:,g} {:,g} {:,g}".format(self.dx, self.dy, self.dz)
622 else:
623 return ""
624
625 @property
626 def max(self):
627 return max(self.dx, self.dy, self.dz)
628
629 @property
630 def mid(self):
631 return sorted([self.dx, self.dy, self.dz])[1]
632
633 @property
634 def min(self):
635 return min(self.dx, self.dy, self.dz)
636
637 def __repr__(self):
638 return self._as_text()
639
640 def __str__(self):
641 return self._as_text()
642
643
644 class SHEL(Command):
645
646 def __init__(self, shx, spline: list):
647 """
648 SHEL lowres[infinite] highres[0]
649 """
650 super(SHEL, self).__init__(shx, spline)
651 params, _ = self._parse_line(spline)
652 self.lowres = None
653 self.highres = None
654 if len(params) > 0:
655 self.lowres = params[0]
656 if len(params) > 1:
657 self.highres = params[1]
658
659
660 class WIGL(Command):
661
662 def __init__(self, shx, spline: list):
663 """
664 WIGL del[0.2] dU[0.2]
665 """
666 super(WIGL, self).__init__(shx, spline)
667 p, _ = self._parse_line(spline)
668 self.d = 0.2
669 self.dU = 0.2
670 if len(p) > 0:
671 self.d = p[0]
672 if len(p) > 1:
673 self.dU = p[1]
674
675
676 class WPDB(Command):
677
678 def __init__(self, shx, spline: list):
679 """
680 WPDB n[1]
681 """
682 super(WPDB, self).__init__(shx, spline)
683 p, _ = self._parse_line(spline)
684 self.n = 1
685 if len(p) > 0:
686 self.n = p[0]
687
688
689 class SPEC(Command):
690
691 def __init__(self, shx, spline: list):
692 """
693 SPEC d[0.2]
694 """
695 super(SPEC, self).__init__(shx, spline)
696 self.d = None
697 p, _ = self._parse_line(spline)
698 if len(p) > 0:
699 self.d = p[0]
700
701
702 class STIR(Command):
703
704 def __init__(self, shx, spline: list):
705 """
706 STIR sres step[0.01]
707 """
708 super(STIR, self).__init__(shx, spline)
709 p, _ = self._parse_line(spline)
710 self.step = 0.01
711 self.sres = None
712 if len(p) > 0:
713 self.sres = p[0]
714 if len(p) > 1:
715 self.step = p[1]
716
717 def __repr__(self):
718 return "STIR {} {}".format(self.sres if self.sres else '', self.step)
719
720 def __str__(self):
721 return "STIR {} {}".format(self.sres if self.sres else '', self.step)
722
723
724 class TWST(Command):
725
726 def __init__(self, shx, spline: list):
727 """
728 TWST N[0] (N[1] after SHELXL-2018/3)
729 Twin component number to be used for the completeness and Friedel completeness statistics.
730 """
731 super(TWST, self).__init__(shx, spline)
732 p, _ = self._parse_line(spline)
733 self.N = 1
734 if len(p) > 0:
735 self.N = p[0]
736
737
738 class RTAB(Command):
739
740 def __init__(self, shx, spline: list):
741 """
742 RTAB codename atomnames
743 """
744 super(RTAB, self).__init__(shx, spline)
745 self.code = spline.pop(1)
746 _, self.atoms = self._parse_line(spline)
747
748
749 class PRIG(Command):
750
751 def __init__(self, shx, spline: list):
752 """
753 PRIG p[#]
754 """
755 super(PRIG, self).__init__(shx, spline)
756 params, _ = self._parse_line(spline)
757 if len(params) > 0:
758 self.p = params[0]
759
760
761 class PLAN(Command):
762
763 def __init__(self, shx, spline: list):
764 """
765 PLAN npeaks[20] d1[#] d2[#]
766 """
767 self.shx = shx
768 super(PLAN, self).__init__(shx, spline)
769 self.npeaks = 20
770 self.d1 = None
771 self.d2 = None
772 params, _ = self._parse_line(spline)
773 if len(params) > 0:
774 self.npeaks = int(params[0])
775 if len(params) > 1:
776 self.d1 = params[1]
777 if len(params) > 2:
778 self.d2 = params[2]
779
780 def __repr__(self):
781 return f'PLAN {self.npeaks:,g}{" " if self.d1 else ""}{self.d1 if self.d1 is not None else ""}' \
782 f'{" " if self.d2 else ""}{self.d2 if self.d2 is not None else ""}'
783
784
785 class FRAG(Command):
786
787 def __init__(self, shx, spline: list):
788 """
789 FRAG code[17] a[1] b[1] c[1] α[90] β[90] γ[90]
790 """
791 super(FRAG, self).__init__(shx, spline)
792 params, _ = self._parse_line(spline)
793 self.code = params[0]
794 self.cell = params[1:7]
795
796
797 class FREE(Command):
798
799 def __init__(self, shx, spline: list):
800 """
801 FREE atom1 atom2
802 """
803 super(FREE, self).__init__(shx, spline)
804 _, atoms = self._parse_line(spline)
805 self.atom1 = None
806 self.atom2 = None
807 try:
808 self.atom1 = atoms[0]
809 self.atom2 = atoms[1]
810 except IndexError:
811 raise ParseParamError(debug=shx.debug, verbose=shx.verbose)
812
813
814 class FMAP(Command):
815 """
816 FMAP code[2] axis[#] nl[53]
817 """
818
819 def __init__(self, shx, spline: list):
820 super(FMAP, self).__init__(shx, spline)
821 params, _ = self._parse_line(spline)
822 self.code = None
823 self.axis = None
824 self.nl = None
825 if len(params) > 0:
826 self.code = params[0]
827 if len(params) > 1:
828 self.axis = params[1]
829 if len(params) > 2:
830 self.nl = params[2]
831
832
833 class MOVE(Command):
834
835 def __init__(self, shx, spline: list):
836 """
837 MOVE dx[0] dy[0] dz[0] sign[1]
838 """
839 super(MOVE, self).__init__(shx, spline)
840 params, _ = self._parse_line(spline)
841 self.dxdydz = None
842 self.sign = None
843 if len(params) > 2:
844 self.dxdydz = params[:3]
845 if len(params) > 3:
846 self.sign = params[3]
847
848
849 class MERG(Command):
850
851 def __init__(self, shx, spline: list):
852 """
853 MERG n[2]
854 """
855 super(MERG, self).__init__(shx, spline)
856 self.n = None
857 _n, _ = self._parse_line(spline)
858 if len(_n) > 0:
859 self.n = _n[0]
860
861
862 class HTAB(Command):
863
864 def __init__(self, shx, spline: list):
865 """
866 HTAB dh[2.0]
867 HTAB donor-atom acceptor-atom
868 """
869 super(HTAB, self).__init__(shx, spline)
870 self.dh = None
871 self.donor = None
872 self.acceptor = None
873 dh, atoms = self._parse_line(spline)
874 if dh:
875 self.dh = dh[0]
876 if len(atoms) == 2:
877 self.donor = atoms[0]
878 self.acceptor = atoms[1]
879
880
881 class GRID(Command):
882
883 def __init__(self, shx, spline: list):
884 """
885 GRID sl[#] sa[#] sd[#] dl[#] da[#] dd[#]
886 """
887 super(GRID, self).__init__(shx, spline)
888 params, _ = self._parse_line(spline)
889 if len(params) > 0:
890 self.sl = params[0]
891 if len(params) > 1:
892 self.sa = params[1]
893 if len(params) > 2:
894 self.sd = params[2]
895 if len(params) > 3:
896 self.dl = params[3]
897 if len(params) > 4:
898 self.da = params[4]
899 if len(params) > 5:
900 self.dd = params[5]
901
902
903 class ACTA(Command):
904
905 def __init__(self, shx, spline: list):
906 """
907 ACTA 2θfull[#] (NOHKL)
908 """
909 super(ACTA, self).__init__(shx, spline)
910 self.twotheta, self.nohkl = self._parse_line(spline)
911 self.shx = shx
912
913 def _as_str(self):
914 if self.twotheta:
915 return f"ACTA {self.twotheta[0]:,g}"
916 else:
917 return "ACTA"
918
919 def __repr__(self):
920 return self._as_str()
921
922 def __str__(self):
923 return self._as_str()
924
925
926 class BLOC(Command):
927
928 def __init__(self, shx, spline: list):
929 """
930 BLOC n1 n2 atomnames
931 """
932 super(BLOC, self).__init__(shx, spline)
933 params, self.atoms = self._parse_line(spline)
934 self.n1 = None
935 self.n2 = None
936 if len(params) > 0:
937 self.n1 = params[0]
938 if len(params) > 1:
939 self.n2 = params[1]
940 self.shx = shx
941
942
943 class FVAR():
944 def __init__(self, number: int = 1, value: float = 0.0):
945 """
946 FVAR osf[1] free variables
947 """
948 self.fvar_value = value # value
949 self.number = number # occurence inside of FVAR instructions
950 self.usage = 1
951
952 def __str__(self):
953 return str(float(self.fvar_value))
954
955 def __repr__(self):
956 return str(float(self.fvar_value))
957
958
959 class FVARs():
960 def __init__(self, shx):
961 super(FVARs, self).__init__()
962 self.fvars = [] # free variables
963 self.shx = shx
964 self._fvarline = 0
965
966 def __iter__(self):
967 """
968 Must be defined for __repr__() to work.
969 """
970 for x in self.fvars:
971 yield x
972
973 def __getitem__(self, item: int) -> str:
974 # SHELXL counts fvars from 1 to x:
975 item = abs(item) - 1
976 return self.fvars[item].fvar_value
977
978 def __setitem__(self, key, fvar_value):
979 self.fvars[key] = fvar_value
980
981 def __len__(self) -> int:
982 return len(self.fvars)
983
984 def __str__(self) -> str:
985 # returnes FVAR as list of FVAR instructions with seven numbers in one line
986 lines = chunks(self.as_stringlist, 7)
987 fvars = [' '.join(i) for i in lines]
988 fvars = ['FVAR ' + i for i in fvars]
989 return "\n".join(fvars)
990
991 def __repr__(self):
992 return str([x for x in self.fvars])
993
994 @property
995 def position(self) -> int:
996 return self.shx.index_of(self)
997
998 def set_free_variables(self, fvar: int, dummy_fvar: float = 0.5):
999 """
1000 Inserts additional free variables according to the fvar number.
1001 """
1002 if fvar > 99:
1003 print('*** SHELXL allows only 99 free variables! ***')
1004 raise ParseParamError(debug=self.shx.debug, verbose=self.shx.verbose)
1005 varlen = len(self.fvars)
1006 difference = (abs(fvar) - varlen)
1007 if difference > 0:
1008 for n in range(int(difference)):
1009 fv = FVAR(varlen + n, dummy_fvar)
1010 self.fvars.append(fv)
1011
1012 def append(self, fvar) -> None:
1013 self.fvars.append(fvar)
1014
1015 def set_fvar_usage(self, fvarnum: int, times: int = 1) -> None:
1016 """
1017 Incerements the usage count of a free variable by times.
1018 """
1019 fvarnum = abs(fvarnum)
1020 if len(self.fvars) >= abs(fvarnum):
1021 self.fvars[fvarnum - 1].usage += times
1022 elif fvarnum > 1 and (self.shx.debug or self.shx.verbose):
1023 print('*** Free variable {} is not defined but used! ***'.format(fvarnum))
1024 if self.shx.debug:
1025 raise ParseParamError(debug=self.shx.debug, verbose=self.shx.verbose)
1026
1027 def get_fvar_usage(self, fvarnum):
1028 """
1029 Returns the usage (count) of a certain free variable.
1030 """
1031 try:
1032 usage = self.fvars[fvarnum - 1].usage
1033 except IndexError:
1034 return 0
1035 return usage
1036
1037 def fvars_used(self):
1038 """
1039 Retruns a dictionary with the usage of all free variables.
1040 """
1041 used = {}
1042 for num, fv in enumerate(self.fvars):
1043 used[num + 1] = fv.usage
1044 return used
1045
1046 @property
1047 def as_stringlist(self):
1048 return [str(x.fvar_value) for x in self.fvars]
1049
1050
1051 class CONF(Command):
1052
1053 def __init__(self, shx, spline: list) -> None:
1054 """
1055 CONF atomnames max_d[1.9] max_a[170]
1056 """
1057 super(CONF, self).__init__(shx, spline)
1058
1059
1060 class CONN(Command):
1061
1062 def __init__(self, shx, spline: list) -> None:
1063 """
1064 CONN bmax[12] r[#] atomnames or CONN bmax[12]
1065 """
1066 super(CONN, self).__init__(shx, spline)
1067
1068
1069 class REM(Command):
1070
1071 def __init__(self, shx, spline: list) -> None:
1072 """
1073 Parses REM lines
1074 """
1075 super(REM, self).__init__(shx, spline)
1076
1077
1078 class BIND(Command):
1079
1080 def __init__(self, shx, spline: list) -> None:
1081 """
1082 BIND atom1 atom2
1083 BIND m n
1084 """
1085 super(BIND, self).__init__(shx, spline)
1086 self.parts, self.atoms = self._parse_line(spline)
1087
1088
1089 class BOND(Command):
1090
1091 def __init__(self, shx, spline: list) -> None:
1092 """
1093 BOND atomnames
1094 """
1095 super(BOND, self).__init__(shx, spline)
1096 _, self.atoms = self._parse_line(spline)
1097
1098
1099 class DISP(Command):
1100 """
1101 DISP E f' f"[#] mu[#]
1102 """
1103
1104 def __init__(self, shx, spline: list) -> None:
1105 super(DISP, self).__init__(shx, spline)
1106 self.element, self.parameter = self._parse_line(spline)
1107
1108
1109 class Restraints():
1110 """
1111 Base class for the list of restraints.
1112 """
1113
1114 def __init__(self) -> None:
1115 """
1116 """
1117 self._restraints: List[Restraint] = []
1118
1119 def append(self, restr: Restraint):
1120 self._restraints.append(restr)
1121
1122 def __iter__(self) -> Generator:
1123 x: Restraint
1124 for x in self._restraints:
1125 yield x
1126
1127 def __getitem__(self, item: int) -> Restraint:
1128 return self._restraints[item]
1129
1130 def __repr__(self) -> str:
1131 if self._restraints:
1132 return "\n".join([str(x) for x in self._restraints])
1133 else:
1134 return 'No Restraints in file.'
1135
1136
1137 class DEFS(Restraint):
1138
1139 def __init__(self, shx, spline: list):
1140 """
1141 DEFS sd[0.02] sf[0.1] su[0.01] ss[0.04] maxsof[1]
1142 Changes the *default* effective standard deviations for the following
1143 DFIX, SAME, SADI, CHIV, FLAT, DELU and SIMU restraints.
1144 """
1145 super(DEFS, self).__init__(shx, spline)
1146 self.sf = 0.1
1147 self.su = 0.01
1148 self.ss = 0.04
1149 self.maxsof = 1
1150 self.sd = 0.02
1151 self.active = True
1152 p, _ = self._parse_line(spline)
1153 if _:
1154 raise ParseParamError(debug=shx.debug, verbose=shx.verbose)
1155 if len(p) > 0:
1156 self.sd = p[0]
1157 if len(p) > 1:
1158 self.sf = p[1]
1159 if len(p) > 2:
1160 self.su = p[2]
1161 if len(p) > 3:
1162 self.ss = p[3]
1163 if len(p) > 4:
1164 self.maxsof = p[4]
1165
1166 @property
1167 def all(self):
1168 return self.sd, self.sf, self.su, self.ss, self.maxsof
1169
1170
1171 class NCSY(Restraint):
1172 """
1173 NCSY DN sd[0.1] su[0.05] atoms
1174 """
1175
1176 def __init__(self, shx, spline: list):
1177 super(NCSY, self).__init__(shx, spline)
1178 self.sd = 0.1
1179 self.su = 0.05
1180 self.DN = None
1181 p, self.atoms = self._parse_line(spline)
1182 if len(p) > 0:
1183 self.DN = p[0]
1184 if len(p) > 1:
1185 self.sd = p[1]
1186 if len(p) > 2:
1187 self.su = p[2]
1188 if not self.DN:
1189 raise ParseNumError(debug=self.shx.debug, verbose=self.shx.verbose)
1190
1191
1192 class ISOR(Restraint):
1193
1194 def __init__(self, shx: 'Shelxfile', spline: List[str]):
1195 """
1196 ISOR s[0.1] st[0.2] atomnames
1197 """
1198 super(ISOR, self).__init__(shx, spline)
1199 self.s = 0.1
1200 self.st = 0.2
1201 p, self.atoms = self._parse_line(spline)
1202 if len(p) > 0:
1203 self.s = p[0]
1204 if len(p) > 1:
1205 self.st = p[1]
1206
1207
1208 class FLAT(Restraint):
1209 """
1210 FLAT s[0.1] four or more atoms
1211 """
1212
1213 def __init__(self, shx, spline: list):
1214 super(FLAT, self).__init__(shx, spline)
1215 self.s = 0.1
1216 p, self.atoms = self._parse_line(spline)
1217 if len(p) > 0:
1218 self.s = p[0]
1219 # TODO: Have to resolve ranges first:
1220 # if len(self.atoms) < 4:
1221 # raise ParseParamError
1222
1223
1224 class BUMP(Restraint):
1225 """
1226 'Anti-bumping' restraints are generated automatically for all distances involving
1227 two non-bonded C, N, O and S atoms (based on the SFAC type) that are shorter than
1228 the expected shortest non-bonded distances, allowing for the possibility of hydrogen bonds.
1229 """
1230
1231 def __init__(self, shx, spline):
1232 """
1233 BUMP s [0.02]
1234 """
1235 super(BUMP, self).__init__(shx, spline)
1236 self.s = 0.02
1237 p, _ = self._parse_line(spline)
1238 if len(p) > 0:
1239 self.s = p[0]
1240 if _:
1241 raise ParseParamError(debug=shx.debug, verbose=shx.verbose)
1242
1243
1244 class DFIX(Restraint):
1245
1246 def __init__(self, shx: 'Shelxfile', spline: List[str]) -> None:
1247 """
1248 DFIX d s[0.02] atom pairs
1249 """
1250 super(DFIX, self).__init__(shx, spline)
1251 self.s = 0.02
1252 p, self.atoms = self._parse_line(spline)
1253 if len(p) > 0:
1254 self.d = p[0]
1255 if len(p) > 1:
1256 self.s = p[1]
1257 self._paircheck()
1258 if not self.d:
1259 raise ParseNumError(debug=self.shx.debug, verbose=self.shx.verbose)
1260 if (self.shx.debug or self.shx.verbose) and 0.0001 < self.d <= self.s:
1261 print('*** WRONG ODER of INSTRUCTIONS. d is smaller than s ***')
1262 print("{}".format(self.textline))
1263
1264
1265 class DANG(Restraint):
1266
1267 def __init__(self, shx: 'Shelxfile', spline: List[str]) -> None:
1268 """
1269 DANG d s[0.04] atom pairs
1270 """
1271 super(DANG, self).__init__(shx, spline)
1272 self.s = 0.04
1273 p, self.atoms = self._parse_line(spline)
1274 if len(p) > 0:
1275 self.d = p[0]
1276 if len(p) > 1:
1277 self.s = p[1]
1278 self._paircheck()
1279 if not self.d:
1280 raise ParseNumError(debug=self.shx.debug, verbose=self.shx.verbose)
1281 if 0.0001 < self.d <= self.s: # Raise exception if d is smaller than s
1282 raise ParseOrderError(debug=shx.debug, verbose=shx.verbose)
1283
1284
1285 class SADI(Restraint):
1286
1287 def __init__(self, shx: 'Shelxfile', spline: List[str]) -> None:
1288 """
1289 SADI s[0.02] pairs of atoms
1290 Instructions with only two atoms are ignored by SHELXL: SADI C3 C4
1291 SADI_3 C3 C4 C3_4 C4_4 creates SADI C3_3 C4_3 C3_4 C4_4
1292 SADI_CCF3 C3 C4 C3_4 C4_4 creates SADI C3_1 C4_1 C3_2 C4_2 C3_4 C4_4 if there are residues 1, 2 and 4
1293 """
1294 super(SADI, self).__init__(shx, spline)
1295 self.s = 0.02
1296 p, self.atoms = self._parse_line(spline)
1297 if len(p) > 0:
1298 self.s = p[0]
1299 self._paircheck()
1300
1301
1302 class SAME(Restraint):
1303
1304 def __init__(self, shx: 'Shelxfile', spline: List[str]) -> None:
1305 """
1306 SAME s1[0.02] s2[0.04] atomnames
1307 """
1308 super(SAME, self).__init__(shx, spline)
1309 self.s1 = 0.02
1310 self.s2 = 0.04
1311 p, self.atoms = self._parse_line(spline)
1312 if len(p) > 0:
1313 self.s1 = p[0]
1314 if len(p) > 1:
1315 self.s2 = p[1]
1316
1317
1318 class RIGU(Restraint):
1319
1320 def __init__(self, shx: 'Shelxfile', spline: List[str]):
1321 """
1322 RIGU s1[0.004] s2[0.004] atomnames
1323 """
1324 super(RIGU, self).__init__(shx, spline)
1325 self.s1 = 0.004
1326 self.s2 = 0.004
1327 p, self.atoms = self._parse_line(spline)
1328 if len(p) > 0:
1329 self.s1 = p[0]
1330 if len(p) > 1:
1331 self.s2 = p[1]
1332
1333
1334 class SIMU(Restraint):
1335
1336 def __init__(self, shx: 'Shelxfile', spline: List[str]):
1337 """
1338 SIMU s[0.04] st[0.08] dmax[2.0] atomnames
1339 """
1340 super(SIMU, self).__init__(shx, spline)
1341 self.s = 0.04
1342 self.st = 0.08
1343 self.dmax = 2.0
1344 p, self.atoms = self._parse_line(spline)
1345 if len(p) > 0:
1346 self.s = p[0]
1347 if len(p) > 1:
1348 self.st = p[1]
1349 if len(p) > 2:
1350 self.dmax = p[2]
1351
1352
1353 class DELU(Restraint):
1354
1355 def __init__(self, shx: 'Shelxfile', spline: List[str]):
1356 """
1357 DELU s1[0.01] s2[0.01] atomnames
1358 """
1359 super(DELU, self).__init__(shx, spline)
1360 self.s1 = 0.01
1361 self.s2 = 0.01
1362 p, self.atoms = self._parse_line(spline)
1363 if len(p) > 0:
1364 self.s1 = p[0]
1365 if len(p) > 1:
1366 self.s2 = p[1]
1367
1368
1369 class CHIV(Restraint):
1370
1371 def __init__(self, shx: 'Shelxfile', spline: List[str]):
1372 """
1373 CHIV V[0] s[0.1] atomnames
1374 """
1375 super(CHIV, self).__init__(shx, spline)
1376 self.s = 0.1
1377 self.V = 0.0
1378 p, self.atoms = self._parse_line(spline)
1379 if len(p) > 0:
1380 self.V = p[0]
1381 if len(p) > 1:
1382 self.s = p[1]
1383
1384
1385 class EADP(Restraint):
1386 """
1387 EADP atomnames
1388 """
1389
1390 def __init__(self, shx: 'Shelxfile', spline: List[str]) -> None:
1391 super(EADP, self).__init__(shx, spline)
1392 _, self.atoms = self._parse_line(spline)
1393
1394
1395 class EXYZ(Restraint):
1396 """
1397 EADP atomnames
1398 """
1399
1400 def __init__(self, shx, spline: list) -> None:
1401 super(EXYZ, self).__init__(shx, spline)
1402 _, self.atoms = self._parse_line(spline)
1403
1404
1405 class DAMP(Command):
1406 """
1407 DAMP damp[0.7] limse[15]
1408 """
1409
1410 def __init__(self, shx, spline: list):
1411 super(DAMP, self).__init__(shx, spline)
1412 values, _ = self._parse_line(spline, intnums=False)
1413 self.damp, self.limse = 0, 0
1414 if len(values) > 0:
1415 self.damp = values[0]
1416 if len(values) > 1:
1417 self.damp, self.limse = values
1418
1419 def __repr__(self) -> str:
1420 if self.limse == 0:
1421 return "DAMP {:,g}".format(self.damp)
1422 else:
1423 return "DAMP {:,g} {:,g}".format(self.damp, self.limse)
1424
1425
1426 class HFIX(Command):
1427
1428 def __init__(self, shx: 'Shelxfile', spline: List[str]) -> None:
1429 """
1430 HFIX mn U[#] d[#] atomnames
1431 """
1432 super(HFIX, self).__init__(shx, spline)
1433 self.params, self.atoms = self._parse_line(spline, intnums=True)
1434
1435 def __repr__(self):
1436 return f"HFIX {' '.join([str(x) for x in self.params]) if self.params else ''} " \
1437 f"{' '.join(self.atoms) if self.atoms else ''}"
1438
1439
1440 class HKLF(Command):
1441
1442 def __init__(self, shx: 'Shelxfile', spline: List[str]) -> None:
1443 """
1444 HKLF N[0] S[1] r11...r33[1 0 0 0 1 0 0 0 1] sm[1] m[0]
1445 """
1446 super(HKLF, self).__init__(shx, spline)
1447 p, _ = self._parse_line(spline)
1448 self.n = 0
1449 self.s = 1
1450 self.matrix = [1, 0, 0, 0, 1, 0, 0, 0, 1]
1451 self.sm = 1
1452 self.m = 0
1453 if len(p) > 0:
1454 self.n = int(p[0])
1455 if len(p) > 1:
1456 self.s = p[1]
1457 if len(p) > 10:
1458 self.matrix = p[3:11]
1459 if len(p) > 11:
1460 self.sm = p[12]
1461 if len(p) > 12:
1462 self.m = p[13]
1463
1464 def __repr__(self) -> str:
1465 return "HKLF {:,g} {:,g} {} {:,g} {:,g}".format(self.n, self.s, ' '.join([str(i) for i in self.matrix]),
1466 self.sm, self.m)
1467
1468
1469 class SUMP(Command):
1470 """
1471 SUMP for linear equation eypressions with free variables.
1472 SUMP c sigma c1 m1 c2 m2 ...
1473 """
1474
1475 def __init__(self, shx, spline: list):
1476 super(SUMP, self).__init__(shx, spline)
1477 p, _ = self._parse_line(spline)
1478 self.c = p.pop(0)
1479 self.sigma = p.pop(0)
1480 # this is to have integer free variables
1481 _fvars: List[int] = [int(x) for x in p[1::2]]
1482 _times: List[Union[int, float]] = [x for x in p[0::2]]
1483 self.fvars: List[list[Union[int, float]]] = [[x, y] for x, y in zip(_times, _fvars)]
1484
1485 def __getitem__(self, item: int) -> Union[List[int], List[float]]:
1486 return self.fvars[item]
1487
1488
1489 class SWAT(Command):
1490 """
1491 SWAT g[0] U[2]
1492 Allows two variables g and U to be refined in order to model diffuse solvent
1493 """
1494
1495 def __init__(self, shx: 'Shelxfile', spline: List[str]):
1496 super().__init__(shx, spline)
1497 p, _ = self._parse_line(spline)
1498 if len(p) > 1:
1499 self.g = p.pop(0)
1500 self.U = p.pop(0)
1501
1502
1503 class LATT(Command):
1504 lattdict = {1: [], # Primitive
1505 2: [SymmetryElement(['0.5', '0.5', '0.5'])], # I-centered
1506 3: [SymmetryElement(['1/3', '2/3', '2/3']), # Rhombohedral
1507 SymmetryElement(['2/3', '1/3', '1/3'])],
1508 4: [SymmetryElement(['0.0', '0.5', '0.5']), # F-centered
1509 SymmetryElement(['0.5', '0.0', '0.5']),
1510 SymmetryElement(['0.5', '0.5', '0.0'])],
1511 5: [SymmetryElement(['0.0', '0.5', '0.5'])], # A-centered
1512 6: [SymmetryElement(['0.5', '0.0', '0.5'])], # B-centered
1513 7: [SymmetryElement(['0.5', '0.5', '0.0'])]} # C-centered
1514
1515 lattint_to_str = {1: 'P', 2: 'I', 3: 'R', 4: 'F', 5: 'A', 6: 'B', 7: 'C'}
1516
1517 def __init__(self, shx: 'Shelxfile', spline: List[str]) -> None:
1518 """
1519 LATT N[1]
1520 """
1521 super(LATT, self).__init__(shx, spline)
1522 p, _ = self._parse_line(spline)
1523 self.centric = False
1524 try:
1525 self.N = int(p[0])
1526 except ValueError:
1527 self.N = -1
1528 self.N_str = self.lattint_to_str[abs(self.N)]
1529 if self.N > 0: # centrosymmetric space group:
1530 self.centric = True
1531 self.latt_ops = LATT.lattdict[abs(self.N)]
1532
1533
1534 class SYMM(Command):
1535
1536 def __init__(self, shx, spline: list):
1537 """
1538 SYMM symmetry operation
1539 """
1540 super(SYMM, self).__init__(shx, spline)
1541 self.symmcard = self._parse_line(spline)
1542
1543 def _parse_line(self, spline: list, intnums: bool = False) -> list:
1544 symmcard = ''.join(spline[1:]).split(',') # removes whitespace
1545 return symmcard
1546
1547 def _as_str(self) -> str:
1548 return "SYMM " + ", ".join(self.symmcard)
1549
1550 def __repr__(self) -> str:
1551 return self._as_str()
1552
1553 def __str__(self) -> str:
1554 return self._as_str()
1555
1556
1557 class SymmCards():
1558 """
1559 Contains the list of SYMM cards
1560 """
1561
1562 def __init__(self, shx: 'Shelxfile') -> None:
1563 self.shx = shx
1564 self._symmcards = [SymmetryElement(['X', 'Y', 'Z'])]
1565 self.latt_ops = []
1566
1567 def _as_str(self) -> str:
1568 return "\n".join([str(x) for x in self._symmcards])
1569
1570 def __repr__(self) -> str:
1571 return self._as_str()
1572
1573 def __str__(self) -> str:
1574 return self._as_str()
1575
1576 def __len__(self) -> int:
1577 return len(self._symmcards)
1578
1579 def __getitem__(self, item: int) -> SymmetryElement:
1580 return self._symmcards[item]
1581
1582 def __iter__(self) -> Generator:
1583 for x in self._symmcards:
1584 yield x
1585
1586 def append(self, symm_data: list) -> None:
1587 """
1588 Add the content of a Shelxl SYMM command to generate the appropriate SymmetryElement instance.
1589 :param symm_data: list of strings. eg.['1/2+X', '1/2+Y', '1/2+Z']
1590 :return: None
1591 """
1592 new_symm = SymmetryElement(symm_data)
1593 self._symmcards.append(new_symm)
1594 for symm in self.shx.latt.latt_ops:
1595 latt_symm = new_symm.apply_latt_symm(symm)
1596 if latt_symm not in self._symmcards:
1597 self._symmcards.append(latt_symm)
1598 if self.shx.latt.centric:
1599 self._symmcards.append(SymmetryElement(symm_data, centric=True))
1600 for symm in self.shx.latt.latt_ops:
1601 latt_symm = new_symm.apply_latt_symm(symm)
1602 latt_symm.centric = True
1603 self._symmcards.append(latt_symm)
1604
1605 def set_centric(self, value: bool) -> None:
1606 """
1607 Defines the instance as representing a centrosymmetric structure. Generates the appropriate SymmetryElement
1608 instances automatically if called before adding further SYMM commands via self.addSymm().
1609 """
1610 self.shx.latt.centric = value
1611 self._symmcards.append(SymmetryElement(['-X', '-Y', '-Z']))
1612 self._symmcards[-1].centric = True
1613
1614 def set_latt_ops(self, lattops: list) -> None:
1615 """
1616 Adds lattice operations. If called before adding SYMM commands, the appropriate lattice operations are used
1617 automatically to generate further SymmetryElements.
1618 :param lattops: list of SymmetryElement instances.
1619 """
1620 self.latt_ops = lattops
1621
1622
1623 class LSCycles(Command):
1624 def __init__(self, shx, spline: list):
1625 """
1626 L.S. nls[0] nrf[0] nextra[0]
1627 #TODO: support nls parameter
1628 If nrf is positive, it is the number of these cycles that should be performed before applying ANIS.
1629 Negative nrf indicates which reflections should be ignored during the refinement but used instead for
1630 the calculation of free R-factors in the final structure factor summation.
1631 nextra is the number of additional parameters that were derived from the data when 'squeezing' the
1632 structure etc.
1633 """
1634 super(LSCycles, self).__init__(shx, spline)
1635 p, _ = self._parse_line(spline)
1636 self._shx = shx
1637 self.cgls = False
1638 self._cycles = 0
1639 self._nrf = ''
1640 self._nextra = ''
1641 try:
1642 self._cycles = int(p[0])
1643 except (IndexError, NameError, ValueError):
1644 raise ParseNumError(debug=self.shx.debug, verbose=self.shx.verbose)
1645 try:
1646 self._nrf = int(p[1])
1647 except IndexError:
1648 pass
1649 try:
1650 self._nextra = int(p[2])
1651 except IndexError:
1652 pass
1653 if spline[0].upper() == 'CGLS':
1654 self.cgls = True
1655
1656 @property
1657 def number(self):
1658 return self._cycles
1659
1660 @number.setter
1661 def number(self, n: int) -> None:
1662 self._cycles = int(n)
1663 self.__init__(self._shx, self._as_str().split())
1664
1665 def set_refine_cycles(self, number: int) -> None:
1666 """
1667 Sets the number of refinement cycles for the current res file.
1668 """
1669 self.number = int(number)
1670
1671 @property
1672 def text(self) -> str:
1673 """
1674 'CGLS 10 2 '
1675 """
1676 return self.__repr__()
1677
1678 def __iter__(self) -> Generator:
1679 for x in self.__repr__().split():
1680 yield x
1681
1682 def _as_str(self) -> str:
1683 return '{} {} {} {}'.format('CGLS' if self.cgls else 'L.S.', self._cycles,
1684 self._nrf if self._nrf else '', self._nextra if self._nextra else '').strip()
1685
1686 def __repr__(self) -> str:
1687 return self._as_str()
1688
1689
1690 class SFACTable():
1691 def __init__(self, shx: 'Shelxfile') -> None:
1692 """
1693 Holds the information of SFAC instructions. Either with default values and only elements
1694 SFAC elements
1695 or as explicit scattering factor in the form of an exponential series, followed by real and
1696 imaginary dispersion terms, linear absorption coefficient, covalent radius and atomic weight.
1697
1698 SFAC elements or SFAC E a1 b1 a2 b2 a3 b3 a4 b4 c f' f" mu r wt
1699 """
1700 self.sfac_table: List[Union[Dict[str, str], Dict[str, int]]] = []
1701 self.shx = shx
1702 self.elements_list = []
1703
1704 def __iter__(self) -> Generator:
1705 for x in self.sfac_table:
1706 yield x['element'].capitalize()
1707
1708 def __repr__(self) -> str:
1709 sftext = ''
1710 elements = []
1711 for sf in self.sfac_table:
1712 if not self.is_exp(sf) and sf['element'].capitalize() not in elements:
1713 elements.append(sf['element'].capitalize())
1714 else:
1715 if elements:
1716 sftext = self._extend_sfac_text(elements, sftext)
1717 elements = []
1718 values = []
1719 for x in ('element', 'a1', 'b1', 'a2', 'b2', 'a3', 'b3', 'a4', 'b4', 'c',
1720 'fprime', 'fdprime', 'mu', 'r', 'wt'):
1721 values.append(sf[x])
1722 sftext = self._extend_sfac_text(elements, sftext)
1723 if elements:
1724 sftext = self._extend_sfac_text(elements, sftext)
1725 return sftext[1:]
1726
1727 def _extend_sfac_text(self, elements: List[str], sftext: str) -> str:
1728 sftext += f"\nSFAC {' '.join(elements)}"
1729 return sftext
1730
1731 def __getitem__(self, index: int) -> str:
1732 """
1733 Returns the n-th element in the sfac table, beginning with 1.
1734 """
1735 if index == 0:
1736 raise IndexError
1737 if index < 0:
1738 index = len(self.sfac_table) + index + 1
1739 return self.sfac_table[index - 1]['element'].capitalize()
1740
1741 def parse_element_line(self, spline: List[str]) -> None:
1742 """
1743 Adds a new SFAC card to the list of cards.
1744 """
1745 if not ''.join(spline[1:]).isalpha(): # joining, because space is not alphabetical
1746 # Excplicit with all values
1747 sfdic = {}
1748 for n, x in enumerate(['element', 'a1', 'b1', 'a2', 'b2', 'a3', 'b3', 'a4', 'b4', 'c',
1749 'fprime', 'fdprime', 'mu', 'r', 'wt']):
1750 if n == 0:
1751 self.elements_list.append(spline[n + 1].upper())
1752 try:
1753 sfdic[x] = spline[n + 1]
1754 except IndexError:
1755 raise ParseNumError(debug=self.shx.debug, verbose=self.shx.verbose)
1756 self.sfac_table.append(sfdic)
1757 else:
1758 # Just the elements
1759 for x in spline[1:]:
1760 self.elements_list.append(x.upper())
1761 self.sfac_table.append({'element': x.upper()})
1762
1763 def has_element(self, element: str) -> bool:
1764 return element.upper() in self.elements_list
1765
1766 @staticmethod
1767 def is_exp(item: Dict[str, str]) -> bool:
1768 return 'a1' in item
1769
1770 def add_element(self, element: str) -> None:
1771 """
1772 Adds an element to the SFAC list.
1773 """
1774 if self.has_element(element):
1775 return
1776 self.elements_list.append(element.upper())
1777 self.sfac_table.append({'element': element.upper(), 'line_number': None})
1778 self.shx.unit.add_number(1.0)
1779
1780 def remove_element(self, element: str):
1781 del self.sfac_table[self.shx.elem2sfac(element.upper()) - 1]
1782 del self.elements_list[self.elements_list.index(element.upper())]
1783
1784
1785 class UNIT(Command):
1786 values: List[Union[int, float]]
1787
1788 def __init__(self, shx, spline: List):
1789 """
1790 UNIT n1 n2 ...
1791 """
1792 super(UNIT, self).__init__(shx, spline)
1793 self.values, _ = self._parse_line(spline)
1794
1795 def add_number(self, number: float):
1796 self.values.append(number)
1797
1798 def __iter__(self):
1799 yield [x for x in self.values]
1800
1801 def __repr__(self) -> str:
1802 return "UNIT " + " ".join(["{:,g}".format(x) for x in self.values])
1803
1804 def __str__(self) -> str:
1805 return self.__repr__()
1806
1807 def __setitem__(self, key: int, value: Union[int, float]) -> None:
1808 self.values[key] = value
1809
1810 def __getitem__(self, item: int) -> Union[int, float]:
1811 return self.values[item]
1812
1813 def __add__(self, other: Union[int, float]) -> None:
1814 self.values.append(other)
1815
1816
1817 class BASF(Command):
1818 """
1819 BASF scale factors
1820 BASF can occour in multiple lines.
1821 """
1822 scale_factors: List[Union[int, float]]
1823
1824 def __init__(self, shx: 'Shelxfile', spline: List[str]) -> None:
1825 super(BASF, self).__init__(shx, spline)
1826 self.scale_factors, _ = self._parse_line(spline)
1827
1828 def __iter__(self):
1829 yield self.scale_factors
1830
1831
1832 class TWIN(Command):
1833
1834 def __init__(self, shx, spline: List):
1835 """
1836 TWIN 3x3 matrix [-1 0 0 0 -1 0 0 0 -1] N[2]
1837 +N -N m = |N|
1838 m-1 to 2m-1
1839 m-1 (2*abs(m)/2)-1
1840 """
1841 super(TWIN, self).__init__(shx, spline)
1842 self.matrix = [-1, 0, 0, 0, -1, 0, 0, 0, -1]
1843 self.allowed_N = 2
1844 self.n_value = 2
1845 if len(spline) > 1:
1846 p, _ = self._parse_line(spline, intnums=False)
1847 if len(p) == 9:
1848 self.matrix = p
1849 elif len(p) == 10:
1850 self.matrix = p[:9]
1851 self.n_value = int(p[9])
1852 else:
1853 raise ParseNumError("*** Check TWIN instruction. ***")
1854 m = abs(self.n_value) / 2
1855 if self.n_value > 0:
1856 self.allowed_N = abs(self.n_value) - 1
1857 else:
1858 self.allowed_N = (2 * m) - 1
1859
1860
1861 class WGHT(Command):
1862
1863 def __init__(self, shx, spline: list):
1864 """
1865 The weighting scheme is defined as follows:
1866 w = q / [ σ²(Fo²) + (a*P)² + b*P + d + e*sin(θ)/$lambda; ]
1867
1868 WGHT a[0.1] b[0] c[0] d[0] e[0] f[.33333]
1869 Usually only 'WGHT a b' is used
1870 """
1871 super(WGHT, self).__init__(shx, spline)
1872 self.shx = shx
1873 self.a = 0.1
1874 self.b = 0.0
1875 self.c = 0.0
1876 self.d = 0.0
1877 self.e = 0.0
1878 self.f = 0.33333
1879 p, _ = self._parse_line(spline)
1880 if len(p) > 0:
1881 self.a = p[0]
1882 if len(p) > 1:
1883 self.b = p[1]
1884 if len(p) > 2:
1885 self.c = p[2]
1886 if len(p) > 3:
1887 self.d = p[3]
1888 if len(p) > 4:
1889 self.e = p[4]
1890 if len(p) > 5:
1891 self.f = p[5]
1892
1893 def _as_string(self):
1894 wght = 'WGHT {} {}'.format(self.a, self.b)
1895 # It is very unlikely that someone changes other parameter than a and b:
1896 if (self.c + self.d + self.e + self.f) != 0.33333:
1897 wght += ' {} {} {} {}'.format(self.c, self.d, self.e, self.f)
1898 return wght
1899
1900 def difference(self) -> List[float]:
1901 """
1902 Returns a list with the weight differences of the parameters a and b.
1903 """
1904 try:
1905 adiff = abs(self.shx.wght.a - self.shx.wght_suggested.a)
1906 bdiff = abs(self.shx.wght.b - self.shx.wght_suggested.b)
1907 except AttributeError:
1908 print("No suggested weighting scheme found. Unable to proceed.")
1909 return [0.0, 0.0]
1910 return [round(adiff, 3), round(bdiff, 3)]
1911
1912 def __repr__(self) -> str:
1913 return self._as_string()
1914
1915 def __str__(self) -> str:
1916 return self._as_string()