Project

General

Profile

1 1468 aaronmk
# 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 1476 aaronmk
    def __init__(self, quantity):
12
        Exception.__init__(self, 'Quantity has no units: '+quantity)
13 1468 aaronmk
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 1471 aaronmk
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 1566 aaronmk
Quantity.__repr__ = quantity2str
31 1471 aaronmk
32
def str2quantity(str_):
33
    value = str_
34 1468 aaronmk
    units = None
35 1471 aaronmk
    if not str_.isdigit(): # optimization to avoid regexp for simple cases
36 1566 aaronmk
        match = re.match(ur'(?i)^\s*(.*?\d\.?)\s*([a-z%\'"°][\w.*/^-]*?)?\s*$',
37 1471 aaronmk
            str_)
38
        if match: value, units = match.groups() # has units
39
    return Quantity(value, units)
40 1468 aaronmk
41 1471 aaronmk
def set_default_units(quantity, units):
42
    if quantity.units == None: quantity.units = units
43
44 1566 aaronmk
conversions = {
45
    ('%', None): 1./100
46
}
47
48 1471 aaronmk
def convert(quantity, units):
49
    units = std_units(units)
50 1565 aaronmk
    if quantity.units == units: return quantity # units already correct
51 1566 aaronmk
    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)