1
|
# Quantities with units
|
2
|
# This file's encoding must be UTF-8Y with BOM so Python will auto-detect UTF-8
|
3
|
|
4
|
import re
|
5
|
|
6
|
import format
|
7
|
import strings
|
8
|
import util
|
9
|
|
10
|
class MissingUnitsException(Exception):
|
11
|
def __init__(self, quantity):
|
12
|
Exception.__init__(self, 'Quantity has no units: '+quantity)
|
13
|
|
14
|
def std_units(units):
|
15
|
if units == None: return units
|
16
|
else: return strings.remove_suffix('.', units) # for abbr ending in '.'
|
17
|
# TODO: deal with '"° and abbrs
|
18
|
|
19
|
class Quantity:
|
20
|
def __init__(self, value='', units=None):
|
21
|
self.value = value
|
22
|
self.units = std_units(util.none_if(units, u''))
|
23
|
|
24
|
def quantity2str(quantity):
|
25
|
str_ = quantity.value
|
26
|
if quantity.units != None: str_ += ' '+quantity.units
|
27
|
return str_
|
28
|
|
29
|
Quantity.__str__ = quantity2str
|
30
|
Quantity.__repr__ = quantity2str
|
31
|
|
32
|
def str2quantity(str_):
|
33
|
value = str_
|
34
|
units = None
|
35
|
if not str_.isdigit(): # optimization to avoid regexp for simple cases
|
36
|
match = re.match(ur'(?i)^\s*(.*?\d\.?)\s*([a-z%\'"°][\w.*/^-]*?)?\s*$',
|
37
|
str_)
|
38
|
if match: value, units = match.groups() # has units
|
39
|
return Quantity(value, units)
|
40
|
|
41
|
def set_default_units(quantity, units):
|
42
|
if quantity.units == None: quantity.units = units
|
43
|
|
44
|
conversions = {
|
45
|
('%', None): 1./100
|
46
|
}
|
47
|
|
48
|
def convert(quantity, units):
|
49
|
units = std_units(units)
|
50
|
if quantity.units == units: return quantity # units already correct
|
51
|
try: conversion = conversions[(quantity.units, units)]
|
52
|
except KeyError:
|
53
|
if units == None: return Quantity(quantity.value, units) # remove units
|
54
|
elif quantity.units == None: raise MissingUnitsException(quantity)
|
55
|
# can't convert quantity with unknown units
|
56
|
else: raise NotImplementedError('Unit conversion not implemented yet')
|
57
|
else:
|
58
|
return Quantity(str(format.str2float(quantity.value)*conversion), units)
|