Debian Codegraph @

shelxfile/misc/dsrmath.py

raw symbols SCIP
1 from __future__ import annotations
2
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 random
13 import string
14 from math import sqrt, radians, cos, sin, acos, degrees, floor
15 from operator import sub, add
16 from typing import List, Union, Optional, Iterable, Tuple, Self
17
18 import numpy as np
19
20 from shelxfile.misc.misc import flatten, determinante
21
22
23 class Array(object):
24 """
25 MIT License
26
27 Copyright (c) 2018 Jens Luebben
28
29 Permission is hereby granted, free of charge, to any person obtaining a copy
30 of this software and associated documentation files (the "Software"), to deal
31 in the Software without restriction, including without limitation the rights
32 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
33 copies of the Software, and to permit persons to whom the Software is
34 furnished to do so, subject to the following conditions:
35
36 The above copyright notice and this permission notice shall be included in all
37 copies or substantial portions of the Software.
38 """
39 __slots__ = ['values']
40
41 def __init__(self, values: Union[list, tuple]):
42 self.values = values
43
44 def __iter__(self) -> Iterable[Union[int, float]]:
45 for v in self.values:
46 yield v
47
48 def __len__(self) -> int:
49 return len(self.values)
50
51 def __hash__(self) -> int:
52 return hash(str(self.values))
53
54 def __add__(self, other: Union[list, 'Array']) -> 'Array':
55 """
56 This method is optimized for speed.
57 """
58 if isinstance(other, Array):
59 return Array(tuple(map(add, self.values, other)))
60 elif isinstance(other, (float, int)):
61 # return Array( list(map(lambda x: x - other, self.values)) )
62 return Array([i + other for i in self.values])
63 else:
64 raise TypeError(f'Cannot add type Array to type {str(type(other))}.')
65
66 def __iadd__(self, other):
67 return self.__add__(other)
68
69 def __eq__(self, other):
70 """
71 Test for equality.
72 """
73 return all([a == b for (a, b) in zip(self.values, other.values)])
74
75 def __sub__(self, other: Array) -> Array:
76 """
77 Subtracts eiter an Array or a value from the self Array.
78 This method is optimized for speed.
79 """
80 if isinstance(other, Array):
81 return Array(list(map(sub, self.values, other))) # slightly faster
82 elif isinstance(other, float) or isinstance(other, int):
83 return Array([i - other for i in self.values])
84 else:
85 raise TypeError('Cannot add type Array to type {}.'.format(str(type(other))))
86
87 def __imul__(self, other: Array) -> Self:
88 """
89 Currently supports multiplication by a number.
90 __imul__ means a *= b
91 """
92 if isinstance(other, (int, float)):
93 self.values = [v * other for v in self.values]
94 return self
95 else:
96 raise TypeError('Unsupported operation.')
97
98 def __mul__(self, other: Union['Array', 'Matrix']) -> Union[float, 'Array']:
99 """
100 Calculates: a * b = axbx + ayby + azbz
101 """
102 if isinstance(other, Matrix):
103 # Array() * Matrix()
104 a = other[0]
105 b = other[1]
106 c = other[2]
107 x = self.values[0] * a[0] + self.values[1] * b[0] + self.values[2] * c[0]
108 y = self.values[0] * a[1] + self.values[1] * b[1] + self.values[2] * c[1]
109 z = self.values[0] * a[2] + self.values[1] * b[2] + self.values[2] * c[2]
110 return Array([x, y, z])
111 else:
112 return self.dot(other)
113
114 def __repr__(self):
115 return 'Array({})'.format(str(self.values))
116
117 def __getitem__(self, val):
118 """
119 Get one item from the array.
120 """
121 return self.values[val]
122
123 def __setitem__(self, pos, val):
124 """
125 Get one item from the array.
126 """
127 self.values[pos] = val
128
129 def norm(self):
130 """
131 The squared lenght of an array
132 """
133 return sum([n ** 2 for n in self.values])
134
135 def normalized(self):
136 """
137 Euclidean norm (straight-line distance) of a vector array.
138 """
139 return sqrt(self.norm())
140
141 @staticmethod
142 def zero(m: int) -> 'Array':
143 """
144 Create zero Array of dimension m
145 """
146 return Array([0.0 for _ in range(m)])
147
148 @staticmethod
149 def randarray(m: int) -> 'Array':
150 """
151 Create random Array of dimension m
152 """
153 return Array([random.randint(1, 99) for _ in range(m)])
154
155 @property
156 def floor(self):
157 return Array(list(map(floor, self.values)))
158
159 def dot(self, other: 'Array') -> float:
160 """
161 Dot product of an array in kartesian space.
162 """
163 if len(self) != len(other):
164 raise ValueError('Vector sizes must match')
165 return sum([i * j for i, j in zip(self, other)])
166
167 def cross(self, other: 'Array') -> 'Array':
168 """
169 Cross product of the Array (currently only for 3D vectors).
170 """
171 if len(self) != len(other) != 3:
172 raise ValueError('For 3D vectors only')
173 a1, a2, a3 = self
174 b1, b2, b3 = other
175 return Array([(a2 * b3 - a3 * b2), (a3 * b1 - a1 * b3), (a1 * b2 - a2 * b1)])
176
177 def angle(self, other: 'Array') -> float:
178 """
179 Calculates the angle between two vectors.
180 """
181 return round(degrees(acos(self.dot(other) / (self.normalized() * other.normalized()))), 9)
182
183
184 class Matrix(object):
185 """
186 MIT License
187
188 Copyright (c) 2018 Jens Luebben
189
190 Permission is hereby granted, free of charge, to any person obtaining a copy
191 of this software and associated documentation files (the "Software"), to deal
192 in the Software without restriction, including without limitation the rights
193 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
194 copies of the Software, and to permit persons to whom the Software is
195 furnished to do so, subject to the following conditions:
196
197 The above copyright notice and this permission notice shall be included in all
198 copies or substantial portions of the Software.
199
200 DK: Missing: inverse, eigenvalues
201 """
202 __slots__ = ['values', 'shape', 'rows', 'columns']
203
204 def __init__(self, values):
205 self.shape = (len(values[0]), len(values))
206 self.rows = len(values[0])
207 self.columns = len(values)
208 self.values = values
209
210 def __getitem__(self, val):
211 """
212 """
213 if isinstance(val, (tuple, list)):
214 if len(val) == 1:
215 return self.values[val[0]]
216 return self.values[val[1]][val[0]]
217 else:
218 return self.values[val]
219
220 def __repr__(self):
221 rows = ''
222 for row in self.values:
223 rows += '|' + ' '.join(['{:>7.4f}'.format(float(x)) for x in row]) + '|' + '\n'
224 return rows
225
226 def __add__(self, other: 'Matrix') -> 'Matrix':
227 """
228 Matrix addition
229 """
230 if isinstance(other, Array):
231 if len(self) != len(other):
232 raise ValueError('Matrix and Array are not of equal length.')
233 return Matrix(
234 [[sum(e1, e2) for e1, e2 in zip(row1, row2)] for row1, row2 in zip(self.values, other.values)])
235 elif isinstance(other, (float, int)):
236 return Matrix([[x + other for x in i] for i in self.values])
237 elif isinstance(other, Matrix):
238 return Matrix([[e1 + e2 for e1, e2 in zip(row1, row2)] for row1, row2 in zip(self.values, other.values)])
239 else:
240 raise TypeError('Cannot add type {} Array to Matrix.'.format(str(type(other))))
241
242 def __mul__(self, other: Union['Matrix', 'Array', int, float]) -> Union['Matrix', 'Array']:
243 """
244 a * b operation
245 """
246 if isinstance(other, (int, float)):
247 return Matrix([[v * other for v in row] for row in self.values])
248 elif isinstance(other, (Matrix, OrthogonalMatrix)):
249 return Matrix([[sum(ea * eb for ea, eb in zip(a, b)) for b in other.values] for a in self.values])
250 elif isinstance(other, Array):
251 return Array([sum([b * x for (b, x) in zip(other.values, row)]) for row in self.values])
252 else:
253 raise TypeError('Cannot add type {} to Matrix.'.format(str(type(other))))
254
255 def __len__(self):
256 return self.shape[1]
257
258 def __iter__(self) -> Iterable[List[float]]:
259 for n in self.values:
260 yield n
261
262 def __eq__(self, other):
263 """
264 Test for equality.
265 """
266 return all([b == x for (b, x) in zip(other.values, self.values)])
267
268 def __sub__(self, other):
269 """
270 Substract two matrices.
271 """
272 output = []
273 for idx in range(len(self)):
274 tmp = []
275 for val_a, val_b in zip(self[idx], other[idx]):
276 tmp.append(val_a - val_b)
277 output.append(tmp[:])
278 return output[:]
279
280 def __truediv__(self, other: Union['Matrix', float, int]):
281 """
282 #>>> Matrix([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) / Matrix([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
283 A / B = A * B^-1
284 """
285 if isinstance(other, Matrix):
286 return self * other.inversed
287 elif isinstance(other, (int, float)):
288 return Matrix([[v / other for v in row] for row in self.values])
289 else:
290 raise NotImplementedError
291
292 def __setitem__(self, key, value):
293 # TODO: Implement setitem
294 pass
295
296 @property
297 def T(self):
298 return self.transposed
299
300 @property
301 def transposed(self) -> 'Matrix':
302 """
303 transposes a matrix
304 """
305 return Matrix(list(zip(*self.values)))
306
307 @property
308 def transposed_alt(self) -> 'Matrix':
309 """
310 Transposes the current matrix.
311 """
312 rows = []
313 for i in range(self.shape[0]):
314 rows.append([r[i] for r in self.values])
315 return Matrix(rows)
316
317 @property
318 def trace(self):
319 return self.values[0][0] + self.values[1][1] + self.values[2][2]
320
321 def dot(self, other):
322 """
323 Dot product of two matrices.
324 """
325 return Matrix([[sum(a * b for a, b in zip(x_row, y_col)) for y_col in zip(*other)] for x_row in self])
326
327 @staticmethod
328 def zero(m: int, n: int) -> 'Matrix':
329 """
330 Create zero matrix of dimension m,n
331 """
332 return Matrix([[0.0 for _ in range(n)] for _ in range(m)])
333
334 @staticmethod
335 def randmat(m: int, n: int) -> 'Matrix':
336 """
337 Create random matrix of dimension m, n (rows, columns)
338
339 #>>> Matrix.randmat(5, 3)
340 | 2.000 1.000 2.000|
341 | 8.000 1.000 2.000|
342 | 3.000 5.000 1.000|
343 | 4.000 1.000 9.000|
344 | 2.000 8.000 4.000|
345 <BLANKLINE>
346 """
347 return Matrix([[random.randint(1, 99) for _ in range(n)] for _ in range(m)])
348
349 def cholesky(self) -> 'Matrix':
350 """
351 """
352 L = Matrix.zero(*self.shape)
353 for i, (ai, li) in enumerate(zip(self.values, L.values)):
354 for j, lj in enumerate(L.values[:i + 1]):
355 s = sum(li[k] * lj[k] for k in range(j))
356 li[j] = sqrt(ai[i] - s) if (i == j) else (1.0 / lj[j] * (ai[j] - s))
357 return L
358
359 @property
360 def inversed(self) -> 'Matrix':
361 """
362 Inversion of 3 × 3 matrices
363 """
364 if self.shape != (3, 3):
365 raise ValueError('Inversion is only valid for 3x3 Matrix.')
366 d = self.det
367 m1, m2, m3, m4, m5, m6, m7, m8, m9 = flatten(self.values)
368 inv = Matrix([[(m5 * m9 - m6 * m8) / d, (m3 * m8 - m2 * m9) / d, (m2 * m6 - m3 * m5) / d],
369 [(m6 * m7 - m4 * m9) / d, (m1 * m9 - m3 * m7) / d, (m3 * m4 - m1 * m6) / d],
370 [(m4 * m8 - m5 * m7) / d, (m2 * m7 - m1 * m8) / d, (m1 * m5 - m2 * m4) / d]])
371 return inv
372
373 @property
374 def det(self):
375 """
376 Return determinant of 3x3 matrix.
377 """
378 return determinante(self.values)
379
380 @property
381 def norm(self):
382 return self.frobenius_norm()
383
384 def frobenius_norm(self):
385 # To store the sum of squares of the
386 # elements of the given matrix
387 sumSq = 0
388 for i in range(self.rows):
389 for j in range(self.columns):
390 sumSq += pow(self[i][j], 2)
391 # Return the square root of
392 # the sum of squares
393 return sqrt(sumSq)
394
395 def power_iteration(self, num_simulations=10):
396 """
397 Eigenvalue algorythm from https://en.wikipedia.org/wiki/Power_iteration
398
399 This does not work. DK
400 """
401 # Ideally choose a random vector
402 # To decrease the chance that our vector
403 # Is orthogonal to the eigenvector
404 b_k = Matrix.randmat(self.rows, self.columns)
405 for _ in range(num_simulations):
406 # calculate the matrix-by-vector product Ab
407 b_k1 = self.dot(b_k)
408 # calculate the norm
409 b_k1_norm = b_k1.norm
410 # re normalize the vector
411 b_k = b_k1 / b_k1_norm
412 return b_k
413
414
415 class SymmetryElement(object):
416 """
417 Class representing a symmetry operation.
418
419 Uses numpy arrays for the rotation matrix and translation vector so that
420 downstream code (SDM, U-value transforms) can use efficient numpy algebra
421 instead of the custom Matrix/Array classes.
422 """
423 symm_id = 1
424 __slots__ = ['centric', 'symms', 'ID', 'matrix', 'trans']
425
426 def __init__(self, symms, centric=False):
427 """
428 Constructor.
429 """
430 self.centric = centric
431 self.symms = symms
432 self.ID = SymmetryElement.symm_id
433 SymmetryElement.symm_id += 1
434 lines = []
435 trans = []
436 for symm in self.symms:
437 line, t = self._parse_line(symm)
438 lines.append(line)
439 trans.append(t)
440 # matrix[i, j] = coefficient of input axis j for output axis i (row-major, NOT transposed)
441 self.matrix: np.ndarray = np.array(lines, dtype=float)
442 self.trans: np.ndarray = np.array(trans, dtype=float)
443 if centric:
444 self.matrix *= -1
445 self.trans *= -1
446
447 def __str__(self) -> str:
448 m = self.matrix.astype(int)
449 string = (f"|{m[0, 0]:2} {m[0, 1]:2} {m[0, 2]:2}| |{float(self.trans[0]):>4.2}|\n"
450 f"|{m[1, 0]:2} {m[1, 1]:2} {m[1, 2]:2}| + |{float(self.trans[1]):>4.2}|\n"
451 f"|{m[2, 0]:2} {m[2, 1]:2} {m[2, 2]:2}| |{float(self.trans[2]):>4.2}|\n")
452 return string
453
454 def __repr__(self):
455 return self.to_shelxl()
456
457 def __eq__(self, other: 'SymmetryElement') -> bool:
458 """
459 Check two SymmetryElement instances for equivalence.
460 Note that differences in lattice translation are ignored.
461 :param other: SymmetryElement instance
462 :return: True/False
463 """
464 m = np.array_equal(self.matrix, other.matrix)
465 t = np.array_equal(self.trans % 1, other.trans % 1)
466 return m and t
467
468 def __sub__(self, other: 'SymmetryElement') -> Union[np.ndarray, float]:
469 """
470 Computes and returns the translational difference between two SymmetryElements. Returns 999.0 if the elements
471 cannot be superimposed via an integer shift of the translational parts.
472 :param other: SymmetryElement instance
473 :return: np.ndarray or 999.0
474 """
475 if self != other:
476 return 999.0
477 return self.trans - other.trans
478
479 def apply_latt_symm(self, latt_symm: 'SymmetryElement') -> 'SymmetryElement':
480 """
481 Copies SymmetryElement instance and returns the copy after applying the translational part of 'lattSymm'.
482 :param latt_symm: SymmetryElement.
483 :return: SymmetryElement.
484 """
485 new_symm = SymmetryElement(self.to_shelxl().split(','))
486 new_symm.trans = self.trans + latt_symm.trans
487 new_symm.centric = self.centric
488 return new_symm
489
490 def to_shelxl(self) -> str:
491 """
492 Generate and return string representation of Symmetry Operation in Shelxl syntax.
493 :return: string.
494 """
495 axes = ['X', 'Y', 'Z']
496 lines = []
497 for i in range(3):
498 text = str(float(self.trans[i])) if self.trans[i] else ''
499 for j in range(3):
500 s = '' if not self.matrix[i, j] else axes[j]
501 if self.matrix[i, j] < 0:
502 s = '-' + s
503 elif s:
504 s = '+' + s
505 text += s
506 lines.append(text)
507 return ', '.join(lines)
508
509 def to_cif(self) -> str:
510 return self._replace_float_values(self.to_shelxl()).lower()
511
512 def _replace_float_values(self, val: str) -> str:
513 val = val.replace('1.25', '5/4')
514 val = val.replace('0.75', '3/4')
515 val = val.replace('0.5', '1/2')
516 val = val.replace('0.33', '1/3')
517 val = val.replace('0.25', '1/4')
518 val = val.replace('0.125', '1/6')
519 return val
520
521 def _parse_line(self, symm: str) -> Tuple[List[int], float]:
522 symm = symm.upper().replace(' ', '')
523 chars = ['X', 'Y', 'Z']
524 line = []
525 for char in chars:
526 element, symm = self._partition(symm, char)
527 line.append(element)
528 if symm:
529 trans = self._float(symm)
530 else:
531 trans = 0
532 return line, trans
533
534 def _float(self, string: str) -> float:
535 try:
536 return float(string)
537 except ValueError:
538 if '/' in string:
539 string = string.replace('/', './') + '.'
540 return eval('{}'.format(string))
541
542 def _partition(self, symm: str, char: str) -> Tuple[int, str]:
543 parts = symm.partition(char)
544 if parts[1]:
545 if parts[0]:
546 sign = parts[0][-1]
547 else:
548 sign = '+'
549 if sign == '-':
550 return -1, ''.join((parts[0][:-1], parts[2]))
551 else:
552 return 1, ''.join((parts[0], parts[2])).replace('+', '')
553 else:
554 return 0, symm
555
556
557 # End of work by Jens Lübben #############
558
559
560 def my_isnumeric(value: str):
561 """
562 Determines if a string can be converted to a number.
563 """
564 try:
565 float(value)
566 except ValueError:
567 return False
568 return True
569
570
571 def mean(values):
572 """
573 returns mean value of a list of numbers
574 """
575 return sum(values) / float(len(values))
576
577
578 def median(nums):
579 """
580 calculates the median of a list of numbers
581 """
582 ls = sorted(nums)
583 n = len(ls)
584 if n == 0:
585 raise ValueError("Need a non-empty iterable")
586 # for uneven list length:
587 elif n % 2 == 1:
588 # // is floordiv:
589 return ls[n // 2]
590 else:
591 return sum(ls[int(int(n) / 2 - 1):int(int(n) / 2 + 1)]) / 2.0
592
593
594 def std_dev(data: List) -> float:
595 """
596 returns standard deviation of values rounded to pl decimal places
597 S = sqrt( (sum(x-xm)^2) / n-1 )
598 xm = sum(x)/n
599 :param data: list with integer or float values
600 """
601 if len(data) == 0:
602 return 0
603 K = data[0]
604 n = 0
605 summ = 0
606 sum_sqr = 0
607 for x in data:
608 n += 1
609 summ += x - K
610 sum_sqr += (x - K) * (x - K)
611 variance = (sum_sqr - (summ * summ) / n) / (n - 1)
612 # use n instead of (n-1) if want to compute the exact variance of the given data
613 # use (n-1) if data are samples of a larger population
614 return sqrt(variance)
615
616
617 def nalimov_test(data):
618 """
619 returns a index list of outliers base on the Nalimov test for data.
620 Modified implementation of:
621 "R. Kaiser, G. Gottschalk, Elementare Tests zur Beurteilung von Messdaten
622 Bibliographisches Institut, Mannheim 1972."
623 """
624 # q-values for degrees of freedom:
625 f = {1 : 1.409, 2: 1.645, 3: 1.757, 4: 1.814, 5: 1.848, 6: 1.870, 7: 1.885, 8: 1.895,
626 9 : 1.903, 10: 1.910, 11: 1.916, 12: 1.920, 13: 1.923, 14: 1.926, 15: 1.928,
627 16: 1.931, 17: 1.933, 18: 1.935, 19: 1.936, 20: 1.937, 30: 1.945}
628 fact = sqrt(float(len(data)) / (len(data) - 1))
629 fval = len(data) - 2
630 if fval < 2:
631 return []
632 outliers = []
633 if fval in f:
634 # less strict than the original:
635 q_crit = f[fval]
636 else:
637 q_crit = 1.95
638 for num, i in enumerate(data):
639 q = abs(((i - median(data)) / std_dev(data)) * fact)
640 if q > q_crit:
641 outliers.append(num)
642 return outliers
643
644
645 def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
646 """
647 returns a random ID like 'L5J74W'
648 :param size: length of the string
649 :type size: integer
650 :param chars: characters used for the ID
651 :type chars: string
652 """
653 return ''.join(random.choice(chars) for _ in range(size))
654
655
656 def atomic_distance(p1: List, p2: List, cell=None, shortest_dist=False):
657 """
658 p1 and p2 are x, y , z coordinates as list ['x', 'y', 'z']
659 cell are the cell parameters as list: ['a', 'b', 'c', 'alpha', 'beta', 'gamma']
660
661 Returns the distance between the two points (Atoms). If shortest_dist is True, the
662 shortest distance ignoring translation is computed.
663 """
664 a, b, c, al, be, ga = 1, 1, 1, 1, 1, 1
665 if cell:
666 a, b, c = cell[:3]
667 al = radians(cell[3])
668 be = radians(cell[4])
669 ga = radians(cell[5])
670 if shortest_dist:
671 x1, y1, z1 = [x + 99.5 for x in p1]
672 x2, y2, z2 = [x + 99.5 for x in p2]
673 dx = (x1 - x2) % 1 - 0.5
674 dy = (y1 - y2) % 1 - 0.5
675 dz = (z1 - z2) % 1 - 0.5
676 else:
677 x1, y1, z1 = p1
678 x2, y2, z2 = p2
679 dx = (x1 - x2)
680 dy = (y1 - y2)
681 dz = (z1 - z2)
682 if cell:
683 return sqrt((a * dx) ** 2 + (b * dy) ** 2 + (c * dz) ** 2 + 2 * b * c * cos(al) * dy * dz +
684 2 * dx * dz * a * c * cos(be) + 2 * dx * dy * a * b * cos(ga))
685 else:
686 return sqrt(dx ** 2 + dy ** 2 + dz ** 2)
687
688
689 def dice_coefficient(a, b, case_insens=True):
690 """
691 :type a: str
692 :type b: str
693 :type case_insens: bool
694 dice coefficient 2nt/na + nb.
695 https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Dice%27s_coefficient#Python
696 """
697 if case_insens:
698 a = a.lower()
699 b = b.lower()
700 if not len(a) or not len(b):
701 return 0.0
702 if len(a) == 1:
703 a = a + u'.'
704 if len(b) == 1:
705 b = b + u'.'
706 a_bigram_list = []
707 for i in range(len(a) - 1):
708 a_bigram_list.append(a[i:i + 2])
709 b_bigram_list = []
710 for i in range(len(b) - 1):
711 b_bigram_list.append(b[i:i + 2])
712 a_bigrams = set(a_bigram_list)
713 b_bigrams = set(b_bigram_list)
714 overlap = len(a_bigrams & b_bigrams)
715 dice_coeff = overlap * 2.0 / (len(a_bigrams) + len(b_bigrams))
716 return round(dice_coeff, 6)
717
718
719 def dice_coefficient2(a, b, case_insens=True):
720 """
721 :type a: str
722 :type b: str
723 :type case_insens: bool
724 duplicate bigrams in a word should be counted distinctly
725 (per discussion), otherwise 'AA' and 'AAAA' would have a
726 dice coefficient of 1...
727 https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Dice%27s_coefficient#Python
728
729 This implementation is reverse. 1 means not hit, 0 means best match
730 """
731 if case_insens:
732 a = a.lower()
733 b = b.lower()
734 if not len(a) or not len(b):
735 return 1.0
736 # quick case for true duplicates
737 if a == b:
738 return 0.0
739 # if a != b, and a or b are single chars, then they can't possibly match
740 if len(a) == 1 or len(b) == 1:
741 return 1.0
742 # use python list comprehension, preferred over list.append()
743 a_bigram_list = [a[i:i + 2] for i in range(len(a) - 1)]
744 b_bigram_list = [b[i:i + 2] for i in range(len(b) - 1)]
745 a_bigram_list.sort()
746 b_bigram_list.sort()
747 # assignments to save function calls
748 lena = len(a_bigram_list)
749 lenb = len(b_bigram_list)
750 # initialize match counters
751 matches = i = j = 0
752 while i < lena and j < lenb:
753 if a_bigram_list[i] == b_bigram_list[j]:
754 matches += 2
755 i += 1
756 j += 1
757 elif a_bigram_list[i] < b_bigram_list[j]:
758 i += 1
759 else:
760 j += 1
761 score = float(matches) / float(lena + lenb)
762 score = 1 - score
763 return round(score, 6)
764
765
766 def levenshtein(s1, s2):
767 """
768 The levensteins distance of two strings.
769 """
770 s1 = s1.lower()
771 s2 = s2.lower()
772 if len(s1) < len(s2):
773 return levenshtein(s2, s1)
774 if len(s2) == 0:
775 return len(s1)
776 previous_row = list(range(len(s2) + 1))
777 for i, c1 in enumerate(s1):
778 current_row = [i + 1]
779 for j, c2 in enumerate(s2):
780 # j+1 instead of j since previous_row and current_row are one character longer:
781 insertions = previous_row[j + 1] + 1
782 deletions = current_row[j] + 1 # than s2
783 substitutions = previous_row[j] + (c1 != c2)
784 current_row.append(min(insertions, deletions, substitutions))
785 previous_row = current_row
786 return previous_row[-1]
787
788
789 def distance(x1, y1, z1, x2, y2, z2, round_out=False):
790 """
791 distance between two points in space for orthogonal axes.
792 """
793 import math as m
794 d = m.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2 + (z1 - z2) ** 2)
795 if round_out:
796 return round(d, round_out)
797 else:
798 return d
799
800
801 def vol_unitcell(a, b, c, al, be, ga):
802 """
803 calculates the volume of a unit cell
804 """
805 ca, cb, cg = cos(radians(al)), cos(radians(be)), cos(radians(ga))
806 v = a * b * c * sqrt(1 + 2 * ca * cb * cg - ca ** 2 - cb ** 2 - cg ** 2)
807 return v
808
809
810 class OrthogonalMatrix():
811 """
812 Orthogonalization matrix used to convert fractional coordinates to cartesian.
813 """
814
815 def __init__(self, a, b, c, alpha, beta, gamma):
816 self.a, self.b, self.c = a, b, c
817 self.V = vol_unitcell(a, b, c, alpha, beta, gamma)
818 self.alpha = radians(alpha)
819 self.beta = radians(beta)
820 self.gamma = radians(gamma)
821 self.m = Matrix(((self.a, self.b * cos(self.gamma), self.c * cos(self.beta)),
822 (0, self.b * sin(self.gamma),
823 (self.c * (cos(self.alpha) - cos(self.beta) * cos(self.gamma)) / sin(self.gamma))),
824 (0, 0, self.V / (self.a * self.b * sin(self.gamma)))))
825 self.metric_matrix = self.transposed.dot(self.m)
826 self._inversed: Optional[Matrix] = None
827
828 def __mul__(self, other: Array) -> Array:
829 """
830 To convert from fractional to cartesian.
831 """
832 return self.m * other
833
834 @property
835 def inversed(self):
836 """
837 To convert from cartesian to fractional.
838 """
839 if not self._inversed:
840 self._inversed = self.m.inversed
841 return self._inversed
842 else:
843 return self._inversed
844
845 @property
846 def transposed(self):
847 return self.m.transposed
848
849 # noinspection PyPep8Naming
850 @property
851 def T(self):
852 return self.m.transposed
853
854 @property
855 def values(self):
856 return self.m.values
857
858
859 def almost_equal(a: Union[int, float], b: Union[int, float], places=3) -> float:
860 """
861 Returns True or False if the numbers a and b are equal inside the
862 decimal places "places".
863 """
864 return round(abs(a - b), places) == 0