unit_operators.py 5.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
#!/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
Justin MacCallum's avatar
Justin MacCallum committed
13
might want to make new dimensions for, say, "currency" or
14
15
16
17
18
"information".

Two possible enhancements that have not been implemented are
  1) Include uncertainties with propagation of errors
  2) Incorporate offsets for celsius <-> kelvin conversion
19
20
21
22
23
24
25
26
27
28
29
30



This is part of the OpenMM molecular simulation toolkit originating from
Simbios, the NIH National Center for Physics-Based Simulation of
Biological Structures at Stanford, funded under the NIH Roadmap for
Medical Research, grant U54 GM072970. See https://simtk.org.

Portions copyright (c) 2012 Stanford University and the Authors.
Authors: Christopher M. Bruns
Contributors: Peter Eastman

Justin MacCallum's avatar
Justin MacCallum committed
31
Permission is hereby granted, free of charge, to any person obtaining a
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
48
"""
49
from __future__ import print_function, absolute_import, division
50
51
52
53

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

54
55
from .unit import Unit, is_unit
from .quantity import Quantity, is_quantity
56
57
58
59
60
61
62
63

# 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.
Justin MacCallum's avatar
Justin MacCallum committed
64

65
66
67
68
    Returns a new Quantity with a value of other and units
    of the inverse of self.
    """
    if is_unit(other):
Peter Eastman's avatar
Peter Eastman committed
69
        raise NotImplementedError('programmer is surprised __rtruediv__ was called instead of __truediv__')
70
71
72
73
74
75
    else:
        # print "R scalar / unit"
        unit = pow(self, -1.0)
        value = other
        return Quantity(value, unit).reduce_unit(self)

Peter Eastman's avatar
Peter Eastman committed
76
Unit.__rtruediv__ = _unit_class_rdiv
77
Unit.__rdiv__ = _unit_class_rdiv
78
79
80
81


def _unit_class_mul(self, other):
    """Multiply a Unit by an object.
Justin MacCallum's avatar
Justin MacCallum committed
82
83
84

    If other is another Unit, returns a new composite Unit.
    Exponents of similar dimensions are added.  If self and
85
86
87
    other share similar BaseDimension, but
    with different BaseUnits, the resulting BaseUnit for that
    BaseDimension will be that used in self.
Justin MacCallum's avatar
Justin MacCallum committed
88
89

    If other is a not another Unit, this method returns a
90
91
92
93
94
    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):
95
96
97
98
99
        if self in Unit._multiplication_cache:
            if other in Unit._multiplication_cache[self]:
                return Unit._multiplication_cache[self][other]
        else:
            Unit._multiplication_cache[self] = {}
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
        # 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
122
123
124
        new_unit = Unit(result2)
        Unit._multiplication_cache[self][other] = new_unit
        return new_unit
125
126
127
128
129
130
131
132
133
    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
134
135
136
        # Is reduce_unit needed here?  I hope not, there is a performance issue...
        # return Quantity(other, self).reduce_unit(self)
        return Quantity(other, self)
Justin MacCallum's avatar
Justin MacCallum committed
137

138
139
Unit.__mul__ = _unit_class_mul
Unit.__rmul__ = Unit.__mul__
140
Unit._multiplication_cache = {}
141
142
143
144
145
146
147


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