"serialization/src/QTBIntegratorProxy.cpp" did not exist on "0e879806cdd38e58b04481ecf7fcd93c44c7dc27"
unit_operators.py 3.66 KB
Newer Older
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
#!/bin/env python
"""
Module simtk.unit.unit_operators

Physical quantities with units, intended to produce similar functionality
to Boost.Units package in C++ (but with a runtime cost).
Uses similar API as Scientific.Physics.PhysicalQuantities
but different internals to satisfy our local requirements.
In particular, there is no underlying set of 'canonical' base
units, whereas in Scientific.Physics.PhysicalQuantities all
units are secretly in terms of SI units.  Also, it is easier
to add new fundamental dimensions to simtk.dimensions.  You
might want to make new dimensions for, say, "currency" or 
"information".

Two possible enhancements that have not been implemented are
  1) Include uncertainties with propagation of errors
  2) Incorporate offsets for celsius <-> kelvin conversion
"""

__author__ = "Christopher M. Bruns"
__version__ = "0.5"

from unit import Unit, is_unit
from quantity import Quantity, is_quantity

# Attach methods of Unit class that return a Quantity to Unit class.
# I put them here to avoid circular dependence in imports.
# i.e. Quantity depends on Unit, but not vice versa

def _unit_class_rdiv(self, other):
    """
    Divide another object type by a Unit.
    
    Returns a new Quantity with a value of other and units
    of the inverse of self.
    """
    if is_unit(other):
        raise NotImplementedError('programmer is surprised __rdiv__ was called instead of __div__')
    else:
        # print "R scalar / unit"
        unit = pow(self, -1.0)
        value = other
        return Quantity(value, unit).reduce_unit(self)

Unit.__rdiv__ = _unit_class_rdiv


def _unit_class_mul(self, other):
    """Multiply a Unit by an object.
    
    If other is another Unit, returns a new composite Unit.  
    Exponents of similar dimensions are added.  If self and 
    other share similar BaseDimension, but
    with different BaseUnits, the resulting BaseUnit for that
    BaseDimension will be that used in self.
    
    If other is a not another Unit, this method returns a 
    new Quantity...  UNLESS other is a Quantity and the resulting
    unit is dimensionless, in which case the underlying value type
    of the Quantity is returned.
    """
    if is_unit(other):
        # print "unit * unit"
        result1 = {} # dictionary of dimensionTuple: (BaseOrScaledUnit, exponent)
        for unit, exponent in self.iter_base_or_scaled_units():
            d = unit.get_dimension_tuple()
            if d not in result1:
                result1[d] = {}
            assert unit not in result1[d]
            result1[d][unit] = exponent
        for unit, exponent in other.iter_base_or_scaled_units():
            d = unit.get_dimension_tuple()
            if d not in result1:
                result1[d] = {}
            if unit not in result1[d]:
                result1[d][unit] = 0
            result1[d][unit] += exponent
        result2 = {} # stripped of zero exponents
        for d in result1:
            for unit in result1[d]:
                exponent = result1[d][unit]
                if exponent != 0:
                    assert unit not in result2
                    result2[unit] = exponent
        return Unit(result2)
    elif is_quantity(other):
        # print "unit * quantity"
        value = other._value
        unit = self * other.unit
        return Quantity(value, unit).reduce_unit(self)
    else:
        # print "scalar * unit"
        value = other
        unit = self
        return Quantity(other, self).reduce_unit(self)
        
Unit.__mul__ = _unit_class_mul
Unit.__rmul__ = Unit.__mul__


# run module directly for testing
if __name__=='__main__':
    # Test the examples in the docstrings
    import doctest, sys
    doctest.testmod(sys.modules[__name__])