Debian Codegraph @

pint/facets/plain/qto.py

raw
1 from __future__ import annotations
2
3 import bisect
4 import math
5 import numbers
6 import warnings
7 from typing import TYPE_CHECKING
8
9 from ...compat import np, scipy
10 from ...errors import UndefinedBehavior
11 from ...util import UnitsContainer, infer_base_unit
12
13 if TYPE_CHECKING:
14 from ..._typing import UnitLike
15 from .quantity import PlainQuantity
16
17
18 def _get_reduced_units(
19 quantity: PlainQuantity, units: UnitsContainer
20 ) -> UnitsContainer:
21 # loop through individual units and compare to each other unit
22 # can we do better than a nested loop here?
23 for unit1, exp in units.items():
24 # make sure it wasn't already reduced to zero exponent on prior pass
25 if unit1 not in units:
26 continue
27 for unit2 in units:
28 # get exponent after reduction
29 exp = units[unit1]
30 if unit1 != unit2:
31 power = quantity._REGISTRY._get_dimensionality_ratio(unit1, unit2)
32 if power:
33 units = units.add(unit2, exp / power).remove([unit1])
34 break
35 return units
36
37
38 def ito_reduced_units(quantity: PlainQuantity) -> None:
39 """Return PlainQuantity scaled in place to reduced units, i.e. one unit per
40 dimension. This will not reduce compound units (e.g., 'J/kg' will not
41 be reduced to m**2/s**2), nor can it make use of contexts at this time.
42 """
43
44 # shortcuts in case we're dimensionless or only a single unit
45 if quantity.dimensionless:
46 return quantity.ito({})
47 if len(quantity._units) == 1:
48 return None
49
50 units = quantity._units.copy()
51 new_units = _get_reduced_units(quantity, units)
52
53 return quantity.ito(new_units)
54
55
56 def to_reduced_units(
57 quantity: PlainQuantity,
58 ) -> PlainQuantity:
59 """Return PlainQuantity scaled in place to reduced units, i.e. one unit per
60 dimension. This will not reduce compound units (intentionally), nor
61 can it make use of contexts at this time.
62 """
63
64 # shortcuts in case we're dimensionless or only a single unit
65 if quantity.dimensionless:
66 return quantity.to({})
67 if len(quantity._units) == 1:
68 return quantity
69
70 units = quantity._units.copy()
71 new_units = _get_reduced_units(quantity, units)
72
73 return quantity.to(new_units)
74
75
76 def to_compact(
77 quantity: PlainQuantity, unit: UnitsContainer | None = None
78 ) -> PlainQuantity:
79 """ "Return PlainQuantity rescaled to compact, human-readable units.
80
81 To get output in terms of a different unit, use the unit parameter.
82
83
84 Examples
85 --------
86
87 >>> import pint
88 >>> ureg = pint.UnitRegistry()
89 >>> (200e-9 * ureg.s).to_compact()
90 <Quantity(200.0, 'nanosecond')>
91 >>> (1e-2 * ureg("kg m/s^2")).to_compact("N")
92 <Quantity(10.0, 'millinewton')>
93 """
94
95 if not isinstance(quantity.magnitude, numbers.Number) and not hasattr(
96 quantity.magnitude, "nominal_value"
97 ):
98 warnings.warn(
99 "to_compact applied to non numerical types has an undefined behavior.",
100 UndefinedBehavior,
101 stacklevel=2,
102 )
103 return quantity
104
105 qm = (
106 quantity.magnitude
107 if not hasattr(quantity.magnitude, "nominal_value")
108 else quantity.magnitude.nominal_value
109 )
110 if quantity.unitless or qm == 0 or math.isnan(qm) or math.isinf(qm):
111 return quantity
112
113 SI_prefixes: dict[int, str] = {}
114 for prefix in quantity._REGISTRY._prefixes.values():
115 try:
116 scale = prefix.converter.scale
117 # Kludgy way to check if this is an SI prefix
118 log10_scale = int(math.log10(scale))
119 if log10_scale == math.log10(scale):
120 SI_prefixes[log10_scale] = prefix.name
121 except Exception:
122 SI_prefixes[0] = ""
123
124 SI_prefixes_list = sorted(SI_prefixes.items())
125 SI_powers = [item[0] for item in SI_prefixes_list]
126 SI_bases = [item[1] for item in SI_prefixes_list]
127
128 if unit is None:
129 unit = infer_base_unit(quantity, registry=quantity._REGISTRY)
130 else:
131 unit = infer_base_unit(quantity.__class__(1, unit), registry=quantity._REGISTRY)
132
133 q_base = quantity.to(unit)
134
135 magnitude = q_base.magnitude
136 # Support uncertainties
137 if hasattr(magnitude, "nominal_value"):
138 magnitude = magnitude.nominal_value
139
140 units = list(q_base._units.items())
141 units_numerator = [a for a in units if a[1] > 0]
142
143 if len(units_numerator) > 0:
144 unit_str, unit_power = units_numerator[0]
145 else:
146 unit_str, unit_power = units[0]
147
148 if unit_power > 0:
149 power = math.floor(math.log10(abs(magnitude)) / float(unit_power) / 3) * 3
150 else:
151 power = math.ceil(math.log10(abs(magnitude)) / float(unit_power) / 3) * 3
152
153 index = bisect.bisect_left(SI_powers, power)
154
155 if index >= len(SI_bases):
156 index = -1
157
158 prefix_str = SI_bases[index]
159
160 new_unit_str = prefix_str + unit_str
161 new_unit_container = q_base._units.rename(unit_str, new_unit_str)
162
163 return quantity.to(new_unit_container)
164
165
166 def _get_unprefixed(quantity: PlainQuantity) -> PlainQuantity:
167 units = list(quantity._units.items())
168 new_units = []
169
170 base_unit_map = {}
171
172 for unit in quantity._REGISTRY._base_units:
173 base_unit_map[unit] = str(quantity._REGISTRY.get_base_units(unit)[1]._units)
174
175 # TODO: This code is very similar to util.infer_base_unit.
176 # Look at combining the two functions.
177 for unit in units:
178 candidates = quantity._REGISTRY.parse_unit_name(unit[0])
179 _, unprefix_unit, _ = candidates[0]
180 # the unprefix_unit could be g rather than kg.
181 # check whether the base_unit for the unprefix_unit also maps to g
182 if unprefix_unit in base_unit_map:
183 unprefix_unit = base_unit_map[unprefix_unit]
184 new_units.append((unprefix_unit, unit[1]))
185 new_unit_container = UnitsContainer(new_units)
186 return new_unit_container
187
188
189 def to_unprefixed(quantity: PlainQuantity) -> PlainQuantity:
190 units = _get_unprefixed(quantity)
191 return quantity.to(units)
192
193
194 def ito_unprefixed(quantity: PlainQuantity) -> PlainQuantity:
195 units = _get_unprefixed(quantity)
196 return quantity.ito(units)
197
198
199 def to_preferred(
200 quantity: PlainQuantity, preferred_units: list[UnitLike] | None = None
201 ) -> PlainQuantity:
202 """Return Quantity converted to a unit composed of the preferred units.
203
204 Examples
205 --------
206
207 >>> import pint
208 >>> ureg = pint.UnitRegistry()
209 >>> (1 * ureg.acre).to_preferred([ureg.meters])
210 <Quantity(4046.87261, 'meter ** 2')>
211 >>> (1 * (ureg.force_pound * ureg.m)).to_preferred([ureg.W])
212 <Quantity(4.44822162, 'watt * second')>
213 """
214
215 units = _get_preferred(quantity, preferred_units)
216 return quantity.to(units)
217
218
219 def ito_preferred(
220 quantity: PlainQuantity, preferred_units: list[UnitLike] | None = None
221 ) -> PlainQuantity:
222 """Return Quantity converted to a unit composed of the preferred units.
223
224 Examples
225 --------
226
227 >>> import pint
228 >>> ureg = pint.UnitRegistry()
229 >>> (1 * ureg.acre).to_preferred([ureg.meters])
230 <Quantity(4046.87261, 'meter ** 2')>
231 >>> (1 * (ureg.force_pound * ureg.m)).to_preferred([ureg.W])
232 <Quantity(4.44822162, 'watt * second')>
233 """
234
235 units = _get_preferred(quantity, preferred_units)
236 return quantity.ito(units)
237
238
239 def _get_preferred(
240 quantity: PlainQuantity, preferred_units: list[UnitLike] | None = None
241 ) -> PlainQuantity:
242 if preferred_units is None:
243 preferred_units = quantity._REGISTRY.default_preferred_units
244
245 if not quantity.dimensionality:
246 return quantity._units.copy()
247
248 # The optimizer isn't perfect, and will sometimes miss obvious solutions.
249 # This sub-algorithm is less powerful, but always finds the very simple solutions.
250 def find_simple():
251 best_ratio = None
252 best_unit = None
253 self_dims = sorted(quantity.dimensionality)
254 self_exps = [quantity.dimensionality[d] for d in self_dims]
255 s_exps_head, *s_exps_tail = self_exps
256 n = len(s_exps_tail)
257 for preferred_unit in preferred_units:
258 dims = sorted(preferred_unit.dimensionality)
259 if dims == self_dims:
260 p_exps_head, *p_exps_tail = (
261 preferred_unit.dimensionality[d] for d in dims
262 )
263 if all(
264 s_exps_tail[i] * p_exps_head == p_exps_tail[i] ** s_exps_head
265 for i in range(n)
266 ):
267 ratio = p_exps_head / s_exps_head
268 ratio = max(ratio, 1 / ratio)
269 if best_ratio is None or ratio < best_ratio:
270 best_ratio = ratio
271 best_unit = preferred_unit ** (s_exps_head / p_exps_head)
272 return best_unit
273
274 simple = find_simple()
275 if simple is not None:
276 return simple
277
278 # For each dimension (e.g. T(ime), L(ength), M(ass)), assign a default base unit from
279 # the collection of base units
280
281 unit_selections = {
282 base_unit.dimensionality: base_unit
283 for base_unit in map(quantity._REGISTRY.Unit, quantity._REGISTRY._base_units)
284 }
285
286 # Override the default unit of each dimension with the 1D-units used in this Quantity
287 unit_selections.update(
288 {
289 unit.dimensionality: unit
290 for unit in map(quantity._REGISTRY.Unit, quantity._units.keys())
291 }
292 )
293
294 # Determine the preferred unit for each dimensionality from the preferred_units
295 # (A prefered unit doesn't have to be only one dimensional, e.g. Watts)
296 preferred_dims = {
297 preferred_unit.dimensionality: preferred_unit
298 for preferred_unit in map(quantity._REGISTRY.Unit, preferred_units)
299 }
300
301 # Combine the defaults and preferred, favoring the preferred
302 unit_selections.update(preferred_dims)
303
304 # This algorithm has poor asymptotic time complexity, so first reduce the considered
305 # dimensions and units to only those that are useful to the problem
306
307 # The dimensions (without powers) of this Quantity
308 dimension_set = set(quantity.dimensionality)
309
310 # Getting zero exponents in dimensions not in dimension_set can be facilitated
311 # by units that interact with that dimension and one or more dimension_set members.
312 # For example MT^1 * LT^-1 lets you get MLT^0 when T is not in dimension_set.
313 # For each candidate unit that interacts with a dimension_set member, add the
314 # candidate unit's other dimensions to dimension_set, and repeat until no more
315 # dimensions are selected.
316
317 discovery_done = False
318 while not discovery_done:
319 discovery_done = True
320 for d in unit_selections:
321 unit_dimensions = set(d)
322 intersection = unit_dimensions.intersection(dimension_set)
323 if 0 < len(intersection) < len(unit_dimensions):
324 # there are dimensions in this unit that are in dimension set
325 # and others that are not in dimension set
326 dimension_set = dimension_set.union(unit_dimensions)
327 discovery_done = False
328 break
329
330 # filter out dimensions and their unit selections that don't interact with any
331 # dimension_set members
332 unit_selections = {
333 dimensionality: unit
334 for dimensionality, unit in unit_selections.items()
335 if set(dimensionality).intersection(dimension_set)
336 }
337
338 # update preferred_units with the selected units that were originally preferred
339 preferred_units = list(
340 {u for d, u in unit_selections.items() if d in preferred_dims}
341 )
342 preferred_units.sort(key=str) # for determinism
343
344 # and unpreferred_units are the selected units that weren't originally preferred
345 unpreferred_units = list(
346 {u for d, u in unit_selections.items() if d not in preferred_dims}
347 )
348 unpreferred_units.sort(key=str) # for determinism
349
350 # for indexability
351 dimensions = list(dimension_set)
352 dimensions.sort() # for determinism
353
354 # the powers for each elemet of dimensions (the list) for this Quantity
355 dimensionality = [quantity.dimensionality[dimension] for dimension in dimensions]
356
357 # Now that the input data is minimized, setup the optimization problem
358
359 # use scipy.optimize.milp to select units from preferred units
360
361 # prefer units that interact with fewer dimensions
362 cost = [len(p.dimensionality) for p in preferred_units]
363
364 # set the cost for non preferred units to a higher number
365 bias = (
366 max(map(abs, dimensionality)) * max((1, *cost)) * 10
367 ) # arbitrary, just needs to be larger
368 cost.extend([bias] * len(unpreferred_units))
369
370 all_units = preferred_units + unpreferred_units
371 num_units = len(all_units)
372 num_dims = len(dimensions)
373
374 # where [u_1 ... u_N] are powers of N candidate units (vars)
375 # introduce auxiliary variables [a_1 ... a_N] to handle absolute values
376 # such that |u_i| <= a_i
377 # variables: x = [u_1, ..., u_N, a_1, ..., a_N]
378 # objective: min c @ x
379 # where c = [0, ..., 0, cost_1, ..., cost_i]
380 c = np.concatenate([np.zeros(num_units), np.array(cost)])
381
382 # u: (-inf, inf), a: (0, inf)
383 bounds = scipy.optimize.Bounds(
384 lb=np.concatenate([-np.inf * np.ones(num_units), np.zeros(num_units)]),
385 ub=np.inf * np.ones(2 * num_units),
386 )
387
388 # constraint: 1 means integer
389 integrality = np.ones(2 * num_units, dtype=np.intp)
390
391 # constraint: |u_i| <= a_i
392 E = np.eye(num_units)
393 constraints = [
394 # 1) u_i - a_i <= 0
395 scipy.optimize.LinearConstraint(A=np.hstack([E, -E]), lb=-np.inf, ub=0),
396 # 2) -u_i - a_i <= 0
397 scipy.optimize.LinearConstraint(A=np.hstack([-E, -E]), lb=-np.inf, ub=0),
398 ]
399
400 # constraint: [D, 0] @ [u, a] = dimensionality
401 if num_dims > 0:
402 D = np.array(
403 [[unit.dimensionality[d] for d in dimensions] for unit in all_units]
404 ).transpose()
405
406 A_eq = np.hstack([D, np.zeros((num_dims, num_units))])
407 b_eq = np.array(dimensionality)
408 constraints.append(scipy.optimize.LinearConstraint(A=A_eq, lb=b_eq, ub=b_eq))
409
410 # run the mips minimizer and extract the result if successful
411 res = scipy.optimize.milp(
412 c, constraints=constraints, integrality=integrality, bounds=bounds
413 )
414
415 if res.success and res.x is not None:
416 exponents = np.round(res.x[:num_units]).astype(int)
417
418 result_unit = quantity._REGISTRY.Unit("")
419 for unit, exponent in zip(all_units, exponents, strict=True):
420 if exponent != 0:
421 result_unit *= unit**exponent
422
423 return result_unit
424
425 # for whatever reason, a solution wasn't found
426 # return the original quantity
427 return quantity._units.copy()