/
unit_utils.py
297 lines (261 loc) · 10.4 KB
/
unit_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
"""Utility module for unit conversion
FlexMeasures stores units as strings in short scientific notation (such as 'kWh' to denote kilowatt-hour).
We use the pint library to convert data between compatible units (such as 'm/s' to 'km/h').
Three-letter currency codes (such as 'KRW' to denote South Korean Won) are valid units.
Note that converting between currencies requires setting up a sensor that registers conversion rates over time.
The preferred compact form for combinations of units can be derived automatically (such as 'kW*EUR/MWh' to 'EUR/h').
Time series with fixed resolution can be converted from units of flow to units of stock (such as 'kW' to 'kWh'), and vice versa.
Percentages can be converted to units of some physical capacity if a capacity is known (such as '%' to 'kWh').
"""
from __future__ import annotations
from datetime import timedelta
from typing import List, Optional, Union
from moneyed import list_all_currencies
import numpy as np
import pandas as pd
import pint
import timely_beliefs as tb
# Create custom template
custom_template = [f"{c} = [currency_{c}]" for c in list_all_currencies()]
# Set up UnitRegistry with abbreviated scientific format
ur = pint.UnitRegistry(
# non_int_type=decimal.Decimal, # todo: switch to decimal unit registry, after https://github.com/hgrecco/pint/issues/1505
preprocessors=[
lambda s: s.replace("%", " percent "),
lambda s: s.replace("‰", " permille "),
],
)
ur.load_definitions(custom_template)
ur.default_format = "~P" # short pretty
ur.define("percent = 1 / 100 = %")
ur.define("permille = 1 / 1000 = ‰")
PREFERRED_UNITS = [
"m",
"h",
"kg",
"m/h",
"W",
"N",
"Wh",
"m**2",
"m**3",
"V",
"A",
"dimensionless",
] + [
str(c) for c in list_all_currencies()
] # todo: move to config setting, with these as a default (NB prefixes do not matter here, this is about SI base units, so km/h is equivalent to m/h)
PREFERRED_UNITS_DICT = dict(
[(ur.parse_expression(x).dimensionality, x) for x in PREFERRED_UNITS]
)
def to_preferred(x: pint.Quantity) -> pint.Quantity:
"""From https://github.com/hgrecco/pint/issues/676#issuecomment-689157693"""
dim = x.dimensionality
if dim in PREFERRED_UNITS_DICT:
compact_unit = x.to(PREFERRED_UNITS_DICT[dim]).to_compact()
# todo: switch to decimal unit registry and then swap out the if statements below
# if len(f"{compact_unit.magnitude}" + "{:~P}".format(compact_unit.units)) < len(
# f"{x.magnitude}" + "{:~P}".format(x.units)
# ):
# return compact_unit
if len("{:~P}".format(compact_unit.units)) < len("{:~P}".format(x.units)):
return compact_unit
return x
def is_valid_unit(unit: str) -> bool:
"""Return True if the pint library can work with this unit identifier."""
try:
ur.Quantity(unit)
except Exception: # noqa B902
# in practice, we encountered pint.errors.UndefinedUnitError, ValueError and AttributeError,
# but since there may be more, here we simply catch them all
return False
return True
def determine_unit_conversion_multiplier(
from_unit: str, to_unit: str, duration: Optional[timedelta] = None
):
"""Determine the value multiplier for a given unit conversion.
If needed, requires a duration to convert from units of stock change to units of flow, or vice versa.
"""
scalar = ur.Quantity(from_unit) / ur.Quantity(to_unit)
if scalar.dimensionality == ur.Quantity("h").dimensionality:
# Convert a stock change to a flow
if duration is None:
raise ValueError(
f"Cannot convert units from {from_unit} to {to_unit} without known duration."
)
return scalar.to_timedelta() / duration
elif scalar.dimensionality == ur.Quantity("1/h").dimensionality:
# Convert a flow to a stock change
if duration is None:
raise ValueError(
f"Cannot convert units from {from_unit} to {to_unit} without known duration."
)
return duration / (1 / scalar).to_timedelta()
elif scalar.dimensionality != ur.Quantity("dimensionless").dimensionality:
raise ValueError(
f"Unit conversion from {from_unit} to {to_unit} doesn't seem possible."
)
return scalar.to_reduced_units().magnitude
def determine_flow_unit(stock_unit: str, time_unit: str = "h"):
"""For example:
>>> determine_flow_unit("m³") # m³/h
>>> determine_flow_unit("kWh") # kW
"""
flow = to_preferred(ur.Quantity(stock_unit) / ur.Quantity(time_unit))
return "{:~P}".format(flow.units)
def determine_stock_unit(flow_unit: str, time_unit: str = "h"):
"""Determine the shortest unit of stock, given a unit of flow.
For example:
>>> determine_stock_unit("m³/h") # m³
>>> determine_stock_unit("kW") # kWh
"""
stock = to_preferred(ur.Quantity(flow_unit) * ur.Quantity(time_unit))
return "{:~P}".format(stock.units)
def units_are_convertible(
from_unit: str, to_unit: str, duration_known: bool = True
) -> bool:
"""For example, a sensor with W units allows data to be posted with units:
>>> units_are_convertible("kW", "W") # True (units just have different prefixes)
>>> units_are_convertible("J/s", "W") # True (units can be converted using some multiplier)
>>> units_are_convertible("Wh", "W") # True (units that represent a stock delta can, knowing the duration, be converted to a flow)
>>> units_are_convertible("°C", "W") # False
"""
if not is_valid_unit(from_unit) or not is_valid_unit(to_unit):
return False
scalar = (
ur.Quantity(from_unit).to_base_units() / ur.Quantity(to_unit).to_base_units()
)
if duration_known:
return scalar.dimensionality in (
ur.Quantity("h").dimensionality,
ur.Quantity("dimensionless").dimensionality,
)
return scalar.dimensionality == ur.Quantity("dimensionless").dimensionality
def is_power_unit(unit: str) -> bool:
"""For example:
>>> is_power_unit("kW")
True
>>> is_power_unit("°C")
False
>>> is_power_unit("kWh")
False
>>> is_power_unit("EUR/MWh")
False
"""
if not is_valid_unit(unit):
return False
return ur.Quantity(unit).dimensionality == ur.Quantity("W").dimensionality
def is_energy_unit(unit: str) -> bool:
"""For example:
>>> is_energy_unit("kW")
False
>>> is_energy_unit("°C")
False
>>> is_energy_unit("kWh")
True
>>> is_energy_unit("EUR/MWh")
False
"""
if not is_valid_unit(unit):
return False
return ur.Quantity(unit).dimensionality == ur.Quantity("Wh").dimensionality
def is_energy_price_unit(unit: str) -> bool:
"""For example:
>>> is_energy_price_unit("EUR/MWh")
True
>>> is_energy_price_unit("KRW/MWh")
True
>>> is_energy_price_unit("KRW/MW")
False
>>> is_energy_price_unit("beans/MW")
False
"""
if (
unit[:3] in [str(c) for c in list_all_currencies()]
and unit[3] == "/"
and is_energy_unit(unit[4:])
):
return True
return False
def _convert_time_units(
data: Union[tb.BeliefsSeries, pd.Series, List[Union[int, float]], int, float],
from_unit: str,
to_unit: str,
):
"""Convert data with datetime or timedelta dtypes to float values.
Use Unix epoch or the requested time unit, respectively.
"""
if not to_unit[0].isdigit():
# unit abbreviations passed to pd.Timedelta need a number (so, for example, h becomes 1h)
to_unit = f"1{to_unit}"
if from_unit == "datetime":
return (
pd.to_datetime(data, utc=True) - pd.Timestamp("1970-01-01", tz="utc")
) // pd.Timedelta(to_unit)
else:
return data / pd.Timedelta(to_unit)
def convert_units(
data: Union[tb.BeliefsSeries, pd.Series, List[Union[int, float]], int, float],
from_unit: str,
to_unit: str,
event_resolution: Optional[timedelta] = None,
capacity: Optional[str] = None,
) -> Union[pd.Series, List[Union[int, float]], int, float]:
"""Updates data values to reflect the given unit conversion."""
if from_unit in ("datetime", "timedelta"):
return _convert_time_units(data, from_unit, to_unit)
if from_unit != to_unit:
from_magnitudes = (
data.to_numpy()
if isinstance(data, pd.Series)
else np.asarray(data)
if isinstance(data, list)
else np.array([data])
)
try:
from_quantities = ur.Quantity(from_magnitudes, from_unit)
except ValueError as e:
# Catch units like "-W" and "100km"
if str(e) == "Unit expression cannot have a scaling factor.":
from_quantities = ur.Quantity(from_unit) * from_magnitudes
else:
raise e # reraise
try:
to_magnitudes = from_quantities.to(ur.Quantity(to_unit)).magnitude
except pint.errors.DimensionalityError as e:
# Catch multiplicative conversions that rely on a capacity, like "%" to "kWh" and vice versa
if "from 'percent'" in str(e):
to_magnitudes = (
(from_quantities * ur.Quantity(capacity))
.to(ur.Quantity(to_unit))
.magnitude
)
elif "to 'percent'" in str(e):
to_magnitudes = (
(from_quantities / ur.Quantity(capacity))
.to(ur.Quantity(to_unit))
.magnitude
)
else:
# Catch multiplicative conversions that use the resolution, like "kWh/15min" to "kW"
if event_resolution is None and isinstance(data, tb.BeliefsSeries):
event_resolution = data.event_resolution
multiplier = determine_unit_conversion_multiplier(
from_unit, to_unit, event_resolution
)
to_magnitudes = from_magnitudes * multiplier
# Output type should match input type
if isinstance(data, pd.Series):
# Pandas Series
data = pd.Series(
to_magnitudes,
index=data.index,
name=data.name,
)
elif isinstance(data, list):
# list
data = list(to_magnitudes)
else:
# int or float
data = to_magnitudes[0]
return data