Debian Codegraph @

periodictable/util.py

raw
1 # This program is in the public domain
2 # Author: Paul Kienzle
3 """
4 Helper functions
5 """
6 from math import sqrt
7
8 def parse_uncertainty(s: str) -> tuple[float, float]|tuple[None, None]:
9 """
10 Given a floating point value plus uncertainty return the pair (val, unc).
11
12 Format is val, val(unc), [nominal] or [low,high].
13
14 The val(unc) form is like 23.0035(12), but also 23(1), 23.0(1.0), or
15 maybe even 23(1.0). This parser does not handle exponential notation
16 such as 1.032(4)E10
17
18 The nominal form has zero uncertainty, as does a bare value.
19
20 The [low,high] form is assumed to be a rectangular distribution of 1-sigma
21 equivalent width (high-low)/sqrt(12).
22
23 An empty string is returned as None,None rather than 0,inf.
24 """
25 if s == "": # missing
26 # TODO: maybe 0 +/- inf ?
27 return None, None
28
29 # Parse [nominal] or [low,high]
30 if s.startswith('['):
31 s = s[1:-1]
32 parts = s.split(',')
33 if len(parts) > 1:
34 low, high = float(parts[0]), float(parts[1])
35 # Use equivalent 1-sigma width for a rectangular distribution
36 return (high+low)/2, (high-low)/sqrt(12)
37 else:
38 return float(parts[0]), 0
39
40 # Parse value(unc) with perhaps '#' at the end
41 parts = s.split('(')
42 if len(parts) > 1:
43 # Split the value and uncertainty.
44 value, unc = parts[0], parts[1].split(')')[0]
45 # Count digits after the decimal for value and produce
46 # 0.00...0{unc} with the right number of zeros.
47 # e.g., 23.0035(12) but not 23(1) or 23.0(1.0) or 23(1.0)
48 if '.' not in unc and '.' in value:
49 zeros = len(value.split('.')[1]) - len(unc)
50 unc = f"0.{'0' * zeros}{unc}"
51 return float(value), float(unc)
52
53 # Plain value with no uncertainty
54 return float(s), 0
55
56 def cell_volume(a=None, b=None, c=None, alpha=None, beta=None, gamma=None) -> float:
57 r"""
58 Compute cell volume from lattice parameters.
59
60 :Parameters:
61 *a*, *b*, *c* : float | |Ang|
62 Lattice spacings. *a* is required.
63 *b* and *c* default to *a*.
64 *alpha*, *beta*, *gamma* : float | |deg|
65 Lattice angles. *alpha* defaults to 90\ |deg|.
66 *beta* and *gamma* default to *alpha*.
67
68 :Returns:
69 *V* : float | |Ang^3|
70 Cell volume
71
72 :Raises:
73 *TypeError* : missing or invalid parameters
74
75 The following formula works for all lattice types:
76
77 .. math::
78
79 V = a b c \sqrt{1 - \cos^2 \alpha - \cos^2 \beta - \cos^2 \gamma
80 + 2 \cos \alpha \cos \beta \cos \gamma}
81 """
82 from math import cos, radians, sqrt
83 if a is None:
84 raise TypeError('missing lattice parameters')
85 if b is None:
86 b = a
87 if c is None:
88 c = a
89 calpha = cos(radians(alpha)) if alpha is not None else 0
90 cbeta = cos(radians(beta)) if beta is not None else calpha
91 cgamma = cos(radians(gamma)) if gamma is not None else calpha
92 V = a*b*c*sqrt(1 - calpha**2 - cbeta**2 - cgamma**2 + 2*calpha*cbeta*cgamma)
93 return V