Debian Codegraph @

shelxfile/misc/misc.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 import os
13 import re
14 import textwrap
15 from math import radians, cos, sin, sqrt
16 from shutil import get_terminal_size
17
18 from time import time, perf_counter
19 from typing import List
20
21 dsr_regex = re.compile(r'^rem\s+DSR\s+(PUT|REPLACE).*', re.IGNORECASE)
22
23
24 class ParseOrderError(Exception):
25 def __init__(self, arg=None, debug=False, verbose=False):
26 if debug or verbose:
27 if arg:
28 print(arg)
29 else:
30 print("*** WRONG ODER of INSTRUCTIONS ***")
31
32
33 class ParseNumError(Exception):
34 def __init__(self, arg=None, debug=False, verbose=False):
35 if debug or verbose:
36 if arg:
37 print(arg)
38 print("*** WRONG NUMBER OF NUMERICAL PARAMETERS ***")
39
40
41 class ParseParamError(Exception):
42 def __init__(self, arg=None, debug=False, verbose=False):
43 if debug or verbose:
44 if arg:
45 print(arg)
46 print("*** WRONG NUMBER OF PARAMETERS ***")
47
48
49 class ParseUnknownParam(Exception):
50 def __init__(self, arg=None, debug=False, verbose=False):
51 if debug or verbose:
52 if arg:
53 print(arg)
54 print("*** UNKNOWN PARAMETER ***")
55
56
57 class ParseSyntaxError(Exception):
58 def __init__(self, arg=None, debug=False, verbose=False):
59 if debug or verbose:
60 print("*** Syntax Error ***")
61
62
63 try:
64 width, height = get_terminal_size() # @UnusedVariable
65 except():
66 width = 80
67 sep_line = (width - 1) * '-'
68
69
70 def remove_file(filename):
71 """
72 removes the file "filename" from disk
73 program exits when exit is true
74 platon gets terminated if terminate is true
75 """
76 if os.path.isfile(filename):
77 try:
78 os.remove(filename)
79 except(IOError, OSError):
80 return False
81 return True
82
83
84 def find_line(inputlist: List[str], regex: str, start: int = None) -> int:
85 """
86 returns the index number of the line where regex is found in the inputlist
87 if stop is true, stop searching with first line found
88
89 :param regex: regular expression to search
90 :param start: line number where to start the search
91 """
92 regc = re.compile(regex, re.IGNORECASE)
93 if start:
94 for i, string in enumerate(inputlist[start:], start):
95 if regc.match(string):
96 return i # returns the index number if regex found
97 else:
98 for i, string in enumerate(inputlist):
99 if regc.match(string):
100 return i # returns the index number if regex found
101 return -1 # returns -1 if no regex found
102
103
104 def which(name: str, flags=os.X_OK, exts=None) -> list:
105 """
106 Search PATH for executable files with the given name.
107
108 On MS-Windows the only flag that has any meaning is os.F_OK. Any other
109 flags will be ignored.
110 """
111 if exts is None:
112 exts = ['.exe', '.EXE', '.bat']
113 result = []
114 # exts = filter(None, os.environ.get('PATHEXT', '').split(os.pathsep))
115 path = os.getenv('PATH', None)
116 if path is None:
117 return []
118 for p in os.getenv('PATH', '').split(os.pathsep):
119 p = os.path.join(p, name)
120 if os.access(p, flags):
121 result.append(p)
122 for e in exts:
123 pext = p + e
124 if os.access(pext, flags):
125 result.append(pext)
126 return result
127
128
129 def split_fvar_and_parameter(parameter: float) -> tuple:
130 """
131 Returns the free variable and value of a given parameter e.g. 30.5 for the occupancy.
132 :return (fvar: int, value: float)
133
134 >>> split_fvar_and_parameter(30.5)
135 (3, 0.5)
136 >>> split_fvar_and_parameter(31.0)
137 (3, 1.0)
138 >>> split_fvar_and_parameter(-30.5)
139 (-3, -0.5)
140 >>> split_fvar_and_parameter(11.0)
141 (1, 1.0)
142 >>> split_fvar_and_parameter(-11.0)
143 (-1, -1.0)
144 >>> split_fvar_and_parameter(-10.33333333)
145 (-1, -0.33333333)
146 """
147 abs_p = abs(parameter)
148 fvar = int(abs_p) // 10 # The free variable number e.g. 2
149 value = abs_p % 10 # The value with which the free variable was multiplied e.g. 0.5
150 if parameter < 0:
151 return -fvar, -round(value, 8)
152 return fvar, round(value, 8)
153
154
155 def flatten(lis):
156 """
157 Given a list, possibly nested to any level, return it flattened.
158 From: http://code.activestate.com/recipes/578948-flattening-an-arbitrarily-nested-list-in-python/
159
160 >>> flatten([['wer', 234, 'brdt5'], ['dfg'], [[21, 34,5], ['fhg', 4]]])
161 ['wer', 234, 'brdt5', 'dfg', 21, 34, 5, 'fhg', 4]
162 """
163 new_lis = []
164 for item in lis:
165 if isinstance(item, (list, tuple)):
166 new_lis.extend(flatten(item))
167 else:
168 new_lis.append(item)
169 return new_lis
170
171
172 def vol_tetrahedron(a, b, c, d, cell=None):
173 """
174 Returns the volume of a terahedron spanned by four points.
175
176 No cell is needed for orthogonal coordinates.
177
178 e.g. A = (3, 2, 1), B = (1, 2, 4), C = (4, 0, 3), D = (1, 1, 7)
179 |u1 u2 u3|
180 v = 1/6*|v1 v2 v3|
181 |w1 w2 w3|
182 AB = (1-3, 2-2, 4-1) = (-2, 0, 3)
183 AC = ...
184 AD = ...
185 V = 1/6[u,v,w]
186 |-2, 0, 3|
187 [u,v,w] = | 1, -2, 2| = 24-3-12 = 5
188 |-2, -1, 6|
189 V = 1/6*5
190 >>> cell = (10.5086, 20.9035, 20.5072, 90, 94.13, 90)
191 >>> a = (0.838817, 0.484526, 0.190081) # a ist um 0.01 ausgelenkt
192 >>> b = (0.875251, 0.478410, 0.256955)
193 >>> c = (0.789290, 0.456520, 0.301616)
194 >>> d = (0.674054, 0.430194, 0.280727)
195 >>> print('volume of Benzene ring atoms:')
196 volume of Benzene ring atoms:
197 >>> print(round(vol_tetrahedron(a, b, c, d, cell), 7))
198 0.0633528
199 """
200 A = [float(i) for i in a]
201 B = [float(i) for i in b]
202 C = [float(i) for i in c]
203 D = [float(i) for i in d]
204 if cell:
205 A = frac_to_cart(a, cell)
206 B = frac_to_cart(b, cell)
207 C = frac_to_cart(c, cell)
208 D = frac_to_cart(d, cell)
209 AB = subtract_vect(A, B)
210 AC = subtract_vect(A, C)
211 AD = subtract_vect(A, D)
212 D = determinante([AB, AC, AD])
213 return abs((D / 6))
214
215
216 def time_this_method(f):
217 """
218 Rather promitive way of timing a method. More advanced would be the profilehooks module.
219 """
220 from functools import wraps
221 @wraps(f)
222 def wrapper(*args, **kwargs):
223 t1 = perf_counter()
224 result = f(*args, **kwargs)
225 t2 = perf_counter()
226 print(f'Time for "{f.__name__ + "()"}": {(t2 - t1) * 1000:5.3} ms\n')
227 return result
228
229 return wrapper
230
231
232 def chunks(l: list, n: int) -> list: # noqa: E741
233 """
234 returns successive n-sized chunks from l.
235 """
236 return [l[i:i + n] for i in range(0, len(l), n)]
237
238
239 def multiline_test(line: str) -> bool:
240 """
241 test if the current line is a multiline with "=" at the end
242 :param line: 'O1 3 -0.01453 1.66590 0.10966 11.00 0.05 ='
243 """
244 if line.rfind('=') > -1:
245 # A '=' character in a rem line is not a line break!
246 if line.startswith("REM") and not dsr_regex.match(line):
247 return False
248 return True
249 else:
250 return False
251
252
253 class TextLine:
254 def __init__(self, initdata):
255 """
256 #>>> t = TextLine('foo')
257 #>>> t.id
258 """
259 self.data = initdata
260 self.next = None
261 self.id = time()
262
263 def get_data(self):
264 return self.data
265
266 def get_next(self):
267 return self.next
268
269 def set_data(self, newdata):
270 self.data = newdata
271
272 def set_next(self, newnext):
273 self.next = newnext
274
275
276 class ResList():
277 """
278 Contains the lines of the res file as unordered linked list.
279 """
280
281 def __init__(self):
282 """
283 >>> res = ResList()
284 >>> res
285 <BLANKLINE>
286 >>> res.append('zweiter')
287 >>> res.add('erster')
288 >>> res.add('dritter')
289 >>> res.append('vierter')
290 >>> res.size
291 4
292 >>> res.tail.get_data()
293 'vierter'
294 >>> res
295 dritter
296 erster
297 zweiter
298 vierter
299 """
300 self.head = None
301 self.tail = None
302 self.size = 0
303
304 def __repr__(self):
305 current = self.head
306 datalist = []
307 if not self.head:
308 return ''
309 while current != self.tail:
310 datalist.append(current.get_data())
311 current = current.get_next()
312 datalist.append(self.tail.get_data())
313 return "\n".join(datalist)
314
315 def is_empty(self):
316 return self.head is None
317
318 def add(self, item):
319 temp = TextLine(item)
320 temp.set_next(self.head)
321 self.head = temp
322 self.size += 1
323
324 def search(self, item):
325 current = self.head
326 found = False
327 while current is not None and not found:
328 if current.get_data() == item:
329 found = True
330 else:
331 current = current.get_next()
332 return found
333
334 def remove(self, item):
335 current = self.head
336 previous = None
337 found = False
338 while not found:
339 if current.get_data() == item:
340 found = True
341 else:
342 previous = current
343 current = current.get_next()
344 if previous is None:
345 self.head = current.get_next()
346 else:
347 previous.setNext(current.get_next())
348 self.size -= 1
349
350 def append(self, item):
351 temp = TextLine(item)
352 if not self.head:
353 self.head = temp
354 else:
355 last = self.tail
356 last.set_next(temp)
357 self.tail = temp
358 self.size += 1
359
360
361 def wrap_line(line: str) -> str:
362 """
363 Wraps long lines according to SHELXL syntax with = at end and space characters before the next line.
364 The wrapping will only be at whitespace, not inside words.
365 """
366 maxlen = 79
367 if len(line) < maxlen:
368 line = ''.join(line)
369 return line
370 line = textwrap.wrap(line, maxlen, subsequent_indent=' ', drop_whitespace=False, replace_whitespace=False)
371 if len(line) > 1:
372 newline = []
373 for n, ln in enumerate(line):
374 if n < len(line) - 1:
375 ln += ' =\n'
376 newline.append(ln)
377 line = ' '.join(newline)
378 else:
379 line = ''.join(line)
380 return line
381
382
383 def range_resolver(atoms_range: list, atom_names: list) -> list:
384 """
385 Resolves the atom names of ranges like "C1 > C5"
386 and works for each restraint line separately.
387 :param atoms_range: atoms with a range definition
388 :param atom_names: names of atoms in the fragment
389 """
390 # dict with lists of positions of the > or < sign:
391 rightleft = {'>': [], '<': []}
392 for rl in rightleft:
393 for num, i in enumerate(atoms_range):
394 i = i.upper()
395 if rl == i:
396 # fill the dictionary:
397 rightleft[rl].append(num)
398 for rl in rightleft:
399 # for each sign:
400 for i in rightleft[rl]:
401 # for each position of < or >:
402 if rl == '>':
403 # forward range
404 left = atom_names.index(atoms_range[i - 1]) + 1
405 right = atom_names.index(atoms_range[i + 1])
406 atoms_range[i:i + 1] = atom_names[left:right]
407 else:
408 # backward range
409 left = atom_names.index(atoms_range[i - 1])
410 right = atom_names.index(atoms_range[i + 1]) + 1
411 names = atom_names[right:left]
412 names.reverse() # counting backwards
413 atoms_range[i:i + 1] = names
414 return atoms_range
415
416
417 def walkdir(rootdir, include="", exclude=""):
418 """
419 Returns a list of files in all subdirectories with full path.
420 :param rootdir: base path from which walk should start
421 :param filter: list of file endings to include only e.g. ['.py', '.res']
422 :return: list of files
423
424 #>>> walkdir("../docs") #doctest: +REPORT_NDIFF +NORMALIZE_WHITESPACE +ELLIPSIS
425 #['../docs/test.txt']
426 #>>> walkdir("../setup/modpath.iss")
427 #['../setup/modpath.iss']
428 #>>> walkdir("../setup/modpath.iss", exclude=['.iss'])
429 #[]
430 #>>> walkdir("../docs", exclude=['.txt']) #doctest: +REPORT_NDIFF +NORMALIZE_WHITESPACE +ELLIPSIS
431 #[]
432 """
433 results = []
434 if not os.path.isdir(rootdir):
435 if os.path.splitext(rootdir)[1] in exclude:
436 return []
437 return [rootdir]
438 for root, sub_folders, files in os.walk(rootdir):
439 for file in files:
440 fullfilepath = os.path.join(root, file)
441 if exclude and os.path.splitext(fullfilepath)[1] in exclude:
442 continue
443 if include:
444 if os.path.splitext(fullfilepath)[1] in include:
445 results.append(os.path.normpath(fullfilepath).replace('\\', '/'))
446 else:
447 results.append(os.path.normpath(fullfilepath).replace('\\', '/'))
448 return results
449
450
451 def frac_to_cart(frac_coord: (list, tuple), cell: list) -> list:
452 """
453 Converts fractional coordinates to cartesian coodinates
454 :param frac_coord: [float, float, float]
455 :param cell: [float, float, float, float, float, float]
456 """
457 a, b, c, alpha, beta, gamma = cell
458 x, y, z = frac_coord
459 alpha = radians(alpha)
460 beta = radians(beta)
461 gamma = radians(gamma)
462 cosastar = (cos(beta) * cos(gamma) - cos(alpha)) / (sin(beta) * sin(gamma))
463 sinastar = sqrt(1 - cosastar ** 2)
464 xc = a * x + (b * cos(gamma)) * y + (c * cos(beta)) * z
465 yc = 0 + (b * sin(gamma)) * y + (-c * sin(beta) * cosastar) * z
466 zc = 0 + 0 + (c * sin(beta) * sinastar) * z
467 return [xc, yc, zc]
468
469
470 def frac_to_cart_fast(x: float, y: float, z: float, cell) -> tuple:
471 """
472 Fast fractional→Cartesian conversion using precomputed upper-triangular matrix
473 scalars stored on a CELL object (_M00 … _M22). Avoids all trig calls.
474
475 :param x: fractional x
476 :param y: fractional y
477 :param z: fractional z
478 :param cell: a CELL instance with precomputed ``_M00``…``_M22`` attributes
479 :return: (xc, yc, zc) Cartesian coordinates
480 """
481 return (
482 cell._M00 * x + cell._M01 * y + cell._M02 * z,
483 cell._M11 * y + cell._M12 * z,
484 cell._M22 * z,
485 )
486
487
488 def cart_to_frac(cart_coord: list, cell: list) -> tuple:
489 """
490 converts cartesian coordinates to fractional coordinates
491 :param cart_coord: [float, float, float]
492 :param cell: [float, float, float, float, float, float]
493 """
494 a, b, c, alpha, beta, gamma = cell
495 xc, yc, zc = cart_coord
496 alpha = radians(alpha)
497 beta = radians(beta)
498 gamma = radians(gamma)
499 cosastar = (cos(beta) * cos(gamma) - cos(alpha)) / (sin(beta) * sin(gamma))
500 sinastar = sqrt(1 - cosastar ** 2)
501 z = zc / (c * sin(beta) * sinastar)
502 y = (yc - (-c * sin(beta) * cosastar) * z) / (b * sin(gamma))
503 x = (xc - (b * cos(gamma)) * y - (c * cos(beta)) * z) / a
504 return x, y, z
505
506
507 def determinante(a):
508 """
509 return determinant of 3x3 matrix
510 """
511 return (a[0][0] * (a[1][1] * a[2][2] - a[2][1] * a[1][2])
512 - a[1][0] * (a[0][1] * a[2][2] - a[2][1] * a[0][2])
513 + a[2][0] * (a[0][1] * a[1][2] - a[1][1] * a[0][2]))
514
515
516 def subtract_vect(a, b):
517 """
518 subtract vector b from vector a
519 Deprecated, use mpmath instead!!!
520 :param a: [float, float, float]
521 :param b: [float, float, float]
522 """
523 return (a[0] - b[0],
524 a[1] - b[1],
525 a[2] - b[2])
526
527
528 def matrix_multiply(A, B):
529 result = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]
530 for i in range(len(A)):
531 for j in range(len(B[0])):
532 result[i][j] = sum(A[i][k] * B[k][j] for k in range(len(B)))
533 return result
534
535
536 def transpose_matrix(matrix):
537 return list(zip(*matrix))
538
539
540 def qr_decomposition(matrix):
541 n = len(matrix)
542 Q = [[0.0] * n for _ in range(n)]
543 R = [[0.0] * n for _ in range(n)]
544
545 # Gram-Schmidt
546 for i in range(n):
547 Q[i] = [matrix[j][i] for j in range(n)]
548
549 for j in range(i):
550 R[j][i] = sum(Q[j][k] * Q[i][k] for k in range(n))
551 Q[i] = [Q[i][k] - R[j][i] * Q[j][k] for k in range(n)]
552
553 norm = sqrt(sum(Q[i][k] ** 2 for k in range(n)))
554 R[i][i] = norm
555 Q[i] = [Q[i][k] / norm for k in range(n)]
556
557 Q_transposed = transpose_matrix(Q)
558 return Q_transposed, R
559
560
561 def eigenvals(matrix: list[list[float]], iterations: int = 100) -> tuple[float, float, float]:
562 """
563 Calculates eigenvalues of a 3x3 matrix.
564 """
565 A = matrix
566 for _ in range(iterations):
567 Q, R = qr_decomposition(A)
568 A = matrix_multiply(R, Q)
569 eigenvalues = [A[i][i] for i in range(len(A))]
570 return eigenvalues[2], eigenvalues[1], eigenvalues[0]
571
572
573 def build_conntable(
574 coords: 'np.ndarray',
575 types: list,
576 parts: list,
577 radii: 'np.ndarray | None' = None,
578 extra_param: float = 1.2,
579 symmgen: 'list[bool] | np.ndarray | None' = None,
580 ) -> tuple:
581 """Vectorised connectivity-table builder.
582
583 Parameters
584 ----------
585 coords : ndarray of shape (N, 3)
586 Cartesian atom positions (Å).
587 types : list[str]
588 Element symbols (length N).
589 parts : list[int]
590 SHELX disorder-part numbers (length N).
591 radii : ndarray of shape (N,), optional
592 Pre-computed covalent radii. If *None*, looked up from *types*.
593 extra_param : float
594 Multiplier applied to the sum of covalent radii for bond detection
595 (default 1.2).
596 symmgen : list[bool] or ndarray of shape (N,), optional
597 Per-atom flag indicating whether the atom was symmetry-generated.
598 Required for the negative-PART exclusion rule.
599
600 Returns
601 -------
602 tuple of (i, j) pairs with i < j, where i and j are indices into *coords*.
603 """
604 import numpy as np
605 from shelxfile.misc.elements import get_radius_from_element
606
607 n = len(coords)
608 if n == 0:
609 return ()
610
611 coords = np.asarray(coords, dtype=np.float64)
612
613 # pairwise distance matrix
614 diff = coords[:, None, :] - coords[None, :, :] # (N, N, 3)
615 dists = np.linalg.norm(diff, axis=2) # (N, N)
616
617 # per-pair bond-distance thresholds
618 if radii is None:
619 radii = np.array([get_radius_from_element(t) for t in types], dtype=np.float64)
620 else:
621 radii = np.asarray(radii, dtype=np.float64)
622
623 radii_sum = (radii[:, None] + radii[None, :]) * extra_param # (N, N)
624
625 # upper triangle (i < j), non-trivial distance, within 4 Å pre-filter
626 triu = np.triu(np.ones((n, n), dtype=bool), k=1)
627 bond_mask = triu & (dists > 0.01) & (dists <= 4.0) & (dists < radii_sum)
628
629 if not np.any(bond_mask):
630 return ()
631
632 # Part filter: forbidden when both parts are non-zero and differ
633 parts_arr = np.array(parts, dtype=np.int32)
634 bond_mask &= ~(
635 (parts_arr[:, None] != 0)
636 & (parts_arr[None, :] != 0)
637 & (parts_arr[:, None] != parts_arr[None, :])
638 )
639
640 # Negative-part filter: bonds crossing the asymmetric-unit / symmetry-copy
641 # boundary are excluded for atoms with a negative part number.
642 if symmgen is not None:
643 symmgen_arr = np.asarray(symmgen, dtype=bool)
644 neg_part = parts_arr < 0
645 cross_boundary = symmgen_arr[:, None] != symmgen_arr[None, :]
646 either_neg = neg_part[:, None] | neg_part[None, :]
647 bond_mask &= ~(either_neg & cross_boundary)
648
649 # H–H filter: skip bonds between two hydrogen atoms
650 is_h = np.array([t in ('H', 'D') for t in types], dtype=bool)
651 bond_mask &= ~(is_h[:, None] & is_h[None, :])
652
653 rows, cols = np.where(bond_mask)
654 return tuple(zip(rows.tolist(), cols.tolist()))
655
656
657 if __name__ == '__main__':
658 matrix = [
659 [0.1, 0.02, 0.03],
660 [0.02, 0.2, 0.01],
661 [0.03, 0.01, 0.15]
662 ]
663 import numpy as np
664
665 eigenvalues1 = eigenvals(matrix)
666 eigenvalues2 = np.linalg.eigvals(matrix)
667
668 # Überprüfen, ob die Matrix NPD ist
669 if any(ev <= 0 for ev in eigenvalues1):
670 print("Die ADP-Matrix ist nicht positiv definit (NPD).")
671 else:
672 print("Die ADP-Matrix ist positiv definit.")
673 print(eigenvalues1)
674 print(eigenvalues2)