-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathunit_reformatting.py
More file actions
57 lines (51 loc) · 1.92 KB
/
unit_reformatting.py
File metadata and controls
57 lines (51 loc) · 1.92 KB
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
import pint
SPECIAL_SYMBOLS = {
'NUMBER': r'#',
'PERCENT': r'%',
}
class CustomUnitReformater(pint.UnitRegistry):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.define('FLOPS = 1 = FLOPS')
self.define('wattseconds = watthours * 3600 = Ws')
self.define('number = 1 = NUMBER')
self.define('percent = 1 = PERCENT')
def reformat_value(self, value, unit_from=None, unit_to=None, as_str=True):
if isinstance(unit_to, str):
unit_to = unit_to.replace('[', '').replace(']', '')
symbol = ''
for unit, short_unit in SPECIAL_SYMBOLS.items(): # remap num and percent units
if short_unit == unit_from:
unit_from = unit
if short_unit == unit_to:
unit_to = unit
# run unit conversion, else only format
if unit_from is not None:
try:
val = value * self[unit_from]
if unit_to is not None:
conv = val.to(unit_to)
else:
conv = val.to_compact()
value = conv.magnitude
symbol = self.get_unit_symbol(conv.u)
except pint.errors.UndefinedUnitError as e:
print(e)
# string formatting
if not as_str:
return value
if value < 1000 and value >= 0.0001:
value = f'{value:7.6f}'[:7]
else:
value = f'{value:.2e}'.replace('e+0', 'e+').replace('e-0', 'e-')
return value, symbol
def get_unit_symbol(self, input, with_brackets=True):
if isinstance(input, str): # unit string input
input = 0 * self[input]
input = input.u
symbol = self._get_symbol(str(input))
if symbol in SPECIAL_SYMBOLS:
symbol = SPECIAL_SYMBOLS[symbol]
if with_brackets:
symbol = f'[{symbol}]'
return symbol