Debian Codegraph @

nixio/util/units.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # Copyright © 2016, German Neuroinformatics Node (G-Node)
3 #
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted under the terms of the BSD License. See
8 # LICENSE file in the root of the Project.
9
10 import re
11 try:
12 from collections.abc import Sequence
13 except ImportError:
14 from collections import Sequence
15 from ..exceptions import InvalidUnit
16
17
18 # Base32hex alphabet (RFC 4648)
19 ID_ALPHABET = "0123456789abcdefghijklmnopqrstuv"
20 # Unit scaling, SI only, substitutions for micro and ohm...
21 PREFIXES = "(Y|Z|E|P|T|G|M|k|h|da|d|c|m|u|n|p|f|a|z|y)"
22 UNITS = ("(m|g|s|A|K|mol|cd|Hz|N|Pa|J|W|C|V|F|S|Wb|T|H|lm|lx|Bq|Gy|Sv|kat|l|L|"
23 "Ohm|%|dB|rad)")
24 POWER = "(\\^[+-]?[1-9]\\d*)"
25 PREFIX_FACTORS = {"y": 1.0e-24,
26 "z": 1.0e-21,
27 "a": 1.0e-18,
28 "f": 1.0e-15,
29 "p": 1.0e-12,
30 "n": 1.0e-9,
31 "u": 1.0e-6,
32 "m": 1.0e-3,
33 "c": 1.0e-2,
34 "d": 1.0e-1,
35 "da": 1.0e1,
36 "h": 1.0e2,
37 "k": 1.0e3,
38 "M": 1.0e6,
39 "G": 1.0e9,
40 "T": 1.0e12,
41 "P": 1.0e15,
42 "E": 1.0e18,
43 "Z": 1.0e21,
44 "Y": 1.0e24}
45
46
47 def sanitizer(unit):
48 """
49 Sanitizes a unit string. That is, it is de-blanked, and mu and µ symbols
50 are changed to u for micro.
51
52 :param unit: The unit that needs to be sanitized.
53
54 :returns: the sanitized unit.
55 :rtype: str
56 """
57 # micro = "\u03bc"
58 micro = "µ"
59 # mugr = "\u00b5"
60 mugr = "μ"
61 return unit.replace(" ", "").replace("mu", "u").\
62 replace(micro, "u").replace(mugr, "u")
63
64
65 def is_si(unit):
66 """
67 Determines whether a unit is a recognized SI unit.
68
69 :param unit: The unit that needs to be checked.
70
71 :returns: True if the unit is an SI unit, false otherwise.
72 :rtype: bool
73 """
74 return unit and (is_atomic(unit) or is_compound(unit))
75
76
77 def is_atomic(unit):
78 """
79 Checked whether a unit string represents an atomic si unit, i.e. not a
80 combination.
81
82 :param unit: The unit to be checked.
83
84 :returns: True if unit is atomic, False otherwise.
85 :rtype: bool
86 """
87 atomic_unit = re.compile(
88 "^{prefix}?{unit}{power}?$".format(prefix=PREFIXES,
89 unit=UNITS,
90 power=POWER)
91 )
92 return atomic_unit.match(unit)
93
94
95 def is_compound(unit):
96 """
97 Checks whether a unit string represents a combination of SI units.
98
99 :param unit: The unit string.
100
101 :returns: True if the unit string represents a combination of SI units,
102 False otherwise.
103 :rtype: bool
104 """
105 atomic_unit = "{prefix}?{unit}{power}?".format(
106 prefix=PREFIXES, unit=UNITS, power=POWER
107 )
108 compound_unit = re.compile(
109 "({atomic}(\\*|/))+{atomic}".format(atomic=atomic_unit)
110 )
111 return unit and compound_unit.search(unit)
112
113
114 def scalable(units_a, units_b):
115 """
116 Checks whether units are scalable versions of the same SI unit.
117 Method works on two lists and compares the corresponding units in both
118 lists.
119
120 :param unit_a: List of unit strings.
121 :param unit_b: List of unit strings.
122
123 :returns: True if all corresponding units are scalable.
124 :rtype: bool
125 """
126 if (isinstance(units_a, Sequence) and isinstance(units_b, Sequence) and
127 not isinstance(units_a, str) and
128 not isinstance(units_b, str)):
129 if len(units_a) != len(units_b):
130 return False
131 for unit_a, unit_b in zip(units_a, units_b):
132 if not scalable(unit_a, unit_b):
133 return False
134 return True
135
136 if not (is_si(units_a) and is_si(units_b)):
137 return False
138
139 _, a_unit, a_power = split(units_a)
140 _, b_unit, b_power = split(units_b)
141 if a_unit != b_unit or a_power != b_power:
142 return False
143
144 return True
145
146
147 def scaling(origin, destination):
148 """
149 Returns the scaling factor to convert from one unit to another.
150
151 :param origin: The original unit string.
152 :param destination: The destination unit string.
153
154 :returns: The scaling factor.
155 :rtype: double
156 """
157 scale = 1.0
158 if not scalable(origin, destination):
159 raise InvalidUnit(
160 "Origin unit and destination unit are not scalable version of the "
161 "same SI unit!",
162 "nixio.util.scaling"
163 )
164
165 org_prefix, _, org_power = split(origin)
166 dest_prefix, _, dest_power = split(destination)
167
168 if org_prefix == dest_prefix and org_power == dest_power:
169 return scale
170 if not dest_prefix and org_prefix:
171 scale = PREFIX_FACTORS[org_prefix]
172 elif not org_prefix and dest_prefix:
173 scale = 1.0 / PREFIX_FACTORS[dest_prefix]
174 elif not org_prefix and not dest_prefix:
175 scale = PREFIX_FACTORS[org_prefix] / PREFIX_FACTORS[dest_prefix]
176
177 if org_power:
178 power = int(org_power)
179 scale **= power
180
181 return scale
182
183
184 def split(combined_unit):
185 """
186 Splits a unit string into magnitude prefix, the base unit, and the power.
187
188 :param combined_unit: The unit string.
189
190 :returns: A tuple of prefix, base unit, and power.
191 :rtype: tuple
192 """
193 prefix_re = "(?P<prefix>{})".format(PREFIXES)
194 unit_re = "(?P<unit>{})".format(UNITS)
195 power_re = "(?P<power>{})".format(POWER)
196 pup = re.compile(prefix_re + unit_re + power_re)
197 prefix_matcher = re.compile(prefix_re + unit_re)
198 unit_matcher = re.compile(unit_re + power_re)
199 # u = re.compile(unit_re)
200 # p = re.compile(prefix_re)
201
202 match = pup.match(combined_unit)
203 if match:
204 prefix = match.group("prefix")
205 unit = match.group("unit")
206 power = match.group("power")[1:]
207 return prefix, unit, power
208
209 match = unit_matcher.match(combined_unit)
210 if match:
211 prefix = ""
212 unit = match.group("unit")
213 power = match.group("power")[1:]
214 return prefix, unit, power
215
216 match = prefix_matcher.match(combined_unit)
217 if match:
218 prefix = match.group("prefix")
219 unit = match.group("unit")
220 power = ""
221 return prefix, unit, power
222
223 prefix = ""
224 unit = combined_unit
225 power = ""
226 return prefix, unit, power
227
228
229 def invert_power(unit):
230 prefix, unit, power = split(unit)
231 if not power:
232 return prefix + unit + "^-1"
233 if power[0] == "-":
234 power = power[1:]
235 else:
236 power = "^-" + power
237 return prefix + unit + "^" + power
238
239
240 def split_compound(compound_unit):
241 """
242 Splits a compound unit (like mV/Hz) into the atomic units.
243
244 :param compound_unit: The unit string.
245
246 :returns: A tuple containing the atomic units.
247 :rtype: tuple
248 """
249 opt_pup = re.compile(PREFIXES + "?" + UNITS + POWER + "?")
250 match = opt_pup.match(compound_unit)
251 sep = ""
252 atomic_units = []
253 while match and (match.end() < len(match.string)):
254 suffix = match.string[match.end():]
255 suffix = suffix.replace(" ", "")
256 unit = match.group(0)
257 if sep == "/":
258 atomic_units.append(invert_power(unit))
259 else:
260 atomic_units.append(unit)
261 sep = suffix[0]
262 match = opt_pup.match(suffix[1:])
263 unit = match.group(0)
264 if sep == "/":
265 atomic_units.append(invert_power(unit))
266 else:
267 atomic_units.append(unit)
268 return tuple(atomic_units)