unit.py 25.6 KB
Newer Older
1
2
3
4
5
#!/bin/env python
"""
Module simtk.unit

Contains classes Unit and ScaledUnit.
6
7
8
9
10
11
12
13
14
15

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
16
Permission is hereby granted, free of charge, to any person obtaining a
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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.
33
"""
34
from __future__ import division, print_function, absolute_import
Peter Eastman's avatar
Peter Eastman committed
35

36
37
38
39
40
41
__author__ = "Christopher M. Bruns"
__version__ = "0.5"


import math
import sys
42
43
44
45
from .mymatrix import MyMatrix, zeros
from .basedimension import BaseDimension
from .baseunit import BaseUnit
from .standard_dimensions import *
46
47
48
49
50

class Unit(object):
    """
    Physical unit such as meter or ampere.
    """
51
52
53

    __array_priority__ = 100

54
55
    def __init__(self, base_or_scaled_units):
        """Create a new Unit.
Justin MacCallum's avatar
Justin MacCallum committed
56

Robert McGibbon's avatar
Robert McGibbon committed
57
58
59
60
61
62
        Parameters
        ----------
        self : Unit
            The newly created Unit.
        base_or_scaled_units : dict
            Keys are BaseUnits or ScaledUnits.  Values are exponents (numbers).
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
107
        """
        # Unit contents are of two types: BaseUnits and ScaledUnits
        self._top_base_units = {}
        self._all_base_units = {}
        self._scaled_units = []
        for (base_or_scaled_unit, power) in base_or_scaled_units.items():
            if power == 0:
                continue
            if isinstance(base_or_scaled_unit, BaseUnit):
                bu = base_or_scaled_unit
                dim = bu.dimension
                if dim not in self._top_base_units:
                    self._top_base_units[dim] = {}
                if bu not in self._top_base_units[dim]:
                    self._top_base_units[dim][bu] = 0
                self._top_base_units[dim][bu] += power
            else:
                self._scaled_units.append((base_or_scaled_unit, power))
        # Populate self._all_base_units
        # first, deep copy of self._top_base_units
        self._all_base_units = {}
        for d in self._top_base_units:
            self._all_base_units[d] = {}
            for u in self._top_base_units[d]:
                self._all_base_units[d][u] = self._top_base_units[d][u]
        # second, BaseUnits from self._scaled_units
        for scaled_unit, exponent1 in self._scaled_units:
            for base_unit, exponent2 in scaled_unit.iter_base_units():
                dim = base_unit.dimension
                if dim not in self._all_base_units:
                    self._all_base_units[dim] = {}
                if base_unit not in self._all_base_units[dim]:
                    self._all_base_units[dim][base_unit] = 0
                self._all_base_units[dim][base_unit] += exponent1 * exponent2
        # What about heterogenous units that cancel? --> leave them
        self._scaled_units.sort()

    def create_unit(self, scale, name, symbol):
        """
        Convenience method for creating a new simple unit from another simple unit.
        Both units must consist of a single BaseUnit.
        """
        # TODO - also handle non-simple units, i.e. units with multiple BaseUnits/ScaledUnits
        assert len(self._top_base_units) == 1
        assert len(self._scaled_units) == 0
108
        dimension = next(iter(self._top_base_units))
109
110
        base_unit_dict = self._top_base_units[dimension]
        assert len(base_unit_dict) == 1
111
        parent_base_unit = next(iter(base_unit_dict))
112
113
114
115
116
117
118
119
120
        parent_exponent = base_unit_dict[parent_base_unit]
        new_base_unit = BaseUnit(parent_base_unit.dimension, name, symbol)
        # BaseUnit scale might be different depending on exponent
        true_scale = scale
        if parent_exponent != 1.0:
            true_scale = math.pow(scale, 1.0/parent_exponent)
        new_base_unit.define_conversion_factor_to(parent_base_unit, true_scale)
        new_unit = Unit({new_base_unit: 1.0})
        return new_unit
Justin MacCallum's avatar
Justin MacCallum committed
121

122
123
124
125
126
    def iter_base_dimensions(self):
        """
        Yields (BaseDimension, exponent) tuples comprising this unit.
        """
        # There might be two units with the same dimension? No.
127
128
        for dimension in sorted(self._all_base_units.keys()):
            exponent = sum(self._all_base_units[dimension].values())
129
130
131
132
133
134
135
            if exponent != 0:
                yield (dimension, exponent)

    def iter_all_base_units(self):
        """
        Yields (BaseUnit, exponent) tuples comprising this unit, including those BaseUnits
        found within ScaledUnits.
Justin MacCallum's avatar
Justin MacCallum committed
136

137
138
        There might be multiple BaseUnits with the same dimension.
        """
139
140
        for dimension in sorted(self._all_base_units.keys()):
            for base_unit in sorted(self._all_base_units[dimension].keys()):
141
142
143
144
145
146
147
                exponent = self._all_base_units[dimension][base_unit]
                yield (base_unit, exponent)

    def iter_top_base_units(self):
        """
        Yields (BaseUnit, exponent) tuples in this Unit, excluding those within BaseUnits.
        """
148
149
        for dimension in sorted(self._top_base_units.keys()):
            for unit in sorted(self._top_base_units[dimension].keys()):
150
151
                exponent = self._top_base_units[dimension][unit]
                yield (unit, exponent)
Justin MacCallum's avatar
Justin MacCallum committed
152

153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
    def iter_scaled_units(self):
        for unit, exponent in self._scaled_units:
            yield (unit, exponent)

    def iter_base_or_scaled_units(self):
        for item in self.iter_top_base_units():
            yield item
        for item in self.iter_scaled_units():
            yield item

    def get_conversion_factor_to_base_units(self):
        """
        There may be ScaleUnit components to this Unit.
        Returns conversion factor to the set of BaseUnits returned by iter_all_base_units().

        Units comprised of only BaseUnits return 1.0
        """
        factor = 1.0
        for scaled_unit, exponent in self._scaled_units:
            # print scaled_unit.factor
            factor *= scaled_unit.factor ** exponent
        return factor
Justin MacCallum's avatar
Justin MacCallum committed
175

176
177
178
    def __eq__(self, other):
        if not is_unit(other):
            return False
179
        return self.get_name() == other.get_name()
180
181

    def __ne__(self, other):
182
        return not self == other
183

Peter Eastman's avatar
Peter Eastman committed
184
    def __lt__(self, other):
185
        """Compare two Units.
Justin MacCallum's avatar
Justin MacCallum committed
186

187
        Raises a TypeError if the units have different dimensions.
Justin MacCallum's avatar
Justin MacCallum committed
188

Peter Eastman's avatar
Peter Eastman committed
189
        Returns True if self < other, False otherwise.
190
191
192
        """
        if not self.is_compatible(other):
            raise TypeError('Unit "%s" is not compatible with Unit "%s".', (self, other))
Peter Eastman's avatar
Peter Eastman committed
193
        return self.conversion_factor_to(other) < 1.0
194

195
196
197
198
199
200
201
202
    def __hash__(self):
        """
        Compute a hash code for this object.
        """
        try:
            return self._hash
        except AttributeError:
            pass
203
        self._hash = hash(self.get_name())
204
205
        return self._hash

206
207
    # def __mul__(self, other):
    # See unit_operators.py for Unit.__mul__ operator
Justin MacCallum's avatar
Justin MacCallum committed
208

Peter Eastman's avatar
Peter Eastman committed
209
    def __truediv__(self, other):
210
        """Divide a Unit by another object.
Justin MacCallum's avatar
Justin MacCallum committed
211

212
        Returns a composite Unit if other is another Unit.
Justin MacCallum's avatar
Justin MacCallum committed
213

214
215
216
217
218
219
        Returns a Quantity otherwise.  UNLESS other is a Quantity AND
        the resulting unit type is dimensionless, in which case the underlying
        value type of the Quantity is returned.
        """
        return self * pow(other, -1)

220
221
    __div__ = __truediv__

Peter Eastman's avatar
Peter Eastman committed
222
223
    # def __rtruediv__(self, other):
    # Because rtruediv returns a Quantity, look in quantity.py for definition of Unit.__rtruediv__
224

225
226
    _pow_cache = {}

227
228
    def __pow__(self, exponent):
        """Raise a Unit to a power.
Justin MacCallum's avatar
Justin MacCallum committed
229

230
231
        Returns a new Unit with different exponents on the BaseUnits.
        """
232
233
234
235
236
        if self in Unit._pow_cache:
            if exponent in Unit._pow_cache[self]:
                return Unit._pow_cache[self][exponent]
        else:
            Unit._pow_cache[self] = {}
237
238
239
        result = {} # dictionary of unit: exponent
        for unit, exponent2 in self.iter_base_or_scaled_units():
            result[unit] = exponent2 * exponent
240
241
242
        new_unit = Unit(result)
        Unit._pow_cache[self][exponent] = new_unit
        return new_unit
243
244
245
246

    def sqrt(self):
        """
        Returns square root of a unit.
Justin MacCallum's avatar
Justin MacCallum committed
247

248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
        Raises ArithmeticError if component exponents are not even.
        This behavior can be changed if you present a reasonable real life case to me.
        """
        new_units = {}
        # There might be odd exponents in base and scaled units that
        # boil down to even exponents in base dimensions.
        # But if ScaledUnits and BaseUnits have even exponents, we should use them.
        nice_and_even = True
        for u, exponent in self.iter_base_or_scaled_units():
            if exponent%2 != 0:
                # This isn't going to work, we need to bust apart the ScaledUnits
                nice_and_even = False
                break
            new_units[u] = exponent/2
        if not nice_and_even:
            # Create a new unit formed from inner BaseUnits
            new_units = {}
            base_units_by_dimension = {}
            # Choose the first BaseUnit for each dimension
            for base_unit, exponent in self.iter_all_base_units():
                d = base_unit.dimension
                if d not in base_units_by_dimension:
                    base_units_by_dimension[d] = base_unit
                    new_units[base_unit] = exponent
                else:
                    # Already assigned a BaseUnit to this dimension, just update exponent
                    bu = base_units_by_dimension[d]
                    new_units[bu] += exponent
            # If exponents are not even by now, they never will be even
            for u, exponent in new_units.items():
                if exponent%2 != 0:
                    raise ArithmeticError('Exponents in Unit.sqrt() must be even.')
                new_units[u] = exponent/2
        return Unit(new_units)

    def __str__(self):
        """Returns the human-readable name of this unit"""
        return self.get_name()
Justin MacCallum's avatar
Justin MacCallum committed
286

287
288
289
290
291
292
293
294
295
296
    def __repr__(self):
        """
        Returns a unit name (string) for this Unit, composed of its various
        BaseUnit symbols.  e.g. 'kilogram meter**2 second**-1'
        """
        units = {}
        for unit, power in self.iter_base_or_scaled_units():
            units[unit] = power
        return 'Unit(%s)' % repr(units)

297
298
299
    # Performance
    _is_compatible_cache = {}

300
301
302
303
304
    def is_compatible(self, other):
        """
        Returns True if two Units share the same dimension.
        Returns False otherwise.
        """
305
306
307
        if self in Unit._is_compatible_cache:
            if other in Unit._is_compatible_cache[self]:
                return Unit._is_compatible_cache[self][other]
308
309
310
311
312
313
314
315
316
317
318
319
        if not is_unit(other):
            if self.is_dimensionless():
                return True
            else:
                return False
        self_dims = {}
        for dimension, exponent in self.iter_base_dimensions():
            self_dims[dimension] = exponent
        other_dims = {}
        for dimension, exponent in other.iter_base_dimensions():
            other_dims[dimension] = exponent
        if len(self_dims) != len(other_dims):
320
321
322
323
324
325
326
            result = False
        else:
            result = (self_dims == other_dims)
        if not self in Unit._is_compatible_cache:
            Unit._is_compatible_cache[self] = {}
        Unit._is_compatible_cache[self][other] = result
        return result
Justin MacCallum's avatar
Justin MacCallum committed
327

328
329
    _is_dimensionless_cache = {}

330
331
332
333
    def is_dimensionless(self):
        """Returns True if this Unit has no dimensions.
        Returns False otherwise.
        """
334
335
        if self in Unit._is_dimensionless_cache:
            return Unit._is_dimensionless_cache[self]
336
337
        for dimension, exponent in self.iter_base_dimensions():
            if exponent != 0:
338
                Unit._is_dimensionless_cache[self] = False
339
                return False
340
        Unit._is_dimensionless_cache[self] = True
341
        return True
Justin MacCallum's avatar
Justin MacCallum committed
342

343
344
345
    # Performance
    _conversion_factor_cache = {}

346
347
348
349
    def conversion_factor_to(self, other):
        """
        Returns conversion factor for computing all of the common dimensions
        between self and other from self base units to other base units.
Justin MacCallum's avatar
Justin MacCallum committed
350

351
352
353
354
355
356
357
        The two units need not share all of the same dimensions.  In case they
        do not, the conversion factor applies only to the BaseUnits of self
        that correspond to different BaseUnits in other.

        This method requires strict compatibility between the two units.
        """
        factor = 1.0
Justin MacCallum's avatar
Justin MacCallum committed
358
        if (self is other):
359
            return factor
360
361
362
        if self in Unit._conversion_factor_cache:
            if other in Unit._conversion_factor_cache[self]:
                return Unit._conversion_factor_cache[self][other]
363
364
365
        assert self.is_compatible(other)
        factor *= self.get_conversion_factor_to_base_units()
        factor /= other.get_conversion_factor_to_base_units()
366
367
368
369

        # Organize both units' base units by dimension.  Since so many conversion factors
        # are powers of ten, we accumulate them separately as an integer power to reduce
        # numerical error.
370
371

        canonical_units = {} # dimension: BaseUnit
372
        powers_of_ten = 0
373
374
375
376
        for unit, power in self.iter_all_base_units():
            d = unit.dimension
            if d in canonical_units:
                if unit != canonical_units[d]:
377
378
379
380
381
382
                    conversion = unit.conversion_factor_to(canonical_units[d])
                    log_conversion = math.log10(conversion)
                    if log_conversion == int(log_conversion):
                        powers_of_ten += power*int(log_conversion)
                    else:
                        factor *= conversion**power
383
384
385
386
387
388
            else:
                canonical_units[d] = unit
        for unit, power in other.iter_all_base_units():
            d = unit.dimension
            if d in canonical_units:
                if unit != canonical_units[d]:
389
390
391
392
393
394
                    conversion = unit.conversion_factor_to(canonical_units[d])
                    log_conversion = math.log10(conversion)
                    if log_conversion == int(log_conversion):
                        powers_of_ten -= power*int(log_conversion)
                    else:
                        factor /= conversion**power
395
396
            else:
                canonical_units[d] = unit
397
        factor *= 10**powers_of_ten
398
399
400
        if not self in Unit._conversion_factor_cache:
            Unit._conversion_factor_cache[self] = {}
        Unit._conversion_factor_cache[self][other] = factor
401
402
403
404
405
        return factor

    def in_unit_system(self, system):
        """
        Returns a new Unit with the same dimensions as this one, expressed in a particular unit system.
Justin MacCallum's avatar
Justin MacCallum committed
406

407
        Strips off any ScaledUnits in the Unit, leaving only BaseUnits.
Justin MacCallum's avatar
Justin MacCallum committed
408

409
        Parameters
Robert McGibbon's avatar
Robert McGibbon committed
410
411
        ----------
        system : a dictionary of (BaseDimension, BaseUnit) pairs
412
413
414
415
416
417
418
419
420
421
422
423
        """
        return system.express_unit(self)

    def get_symbol(self):
        """
        Returns a unit symbol (string) for this Unit, composed of its various
        BaseUnit symbols.  e.g. 'kg m**2 s**-1'
        """
        symbol = ""
        # emit positive exponents first
        pos = ""
        pos_count = 0
Justin MacCallum's avatar
Justin MacCallum committed
424
        for unit, power in self.iter_base_or_scaled_units():
425
426
427
428
429
430
431
432
433
434
            if power > 0:
                pos_count += 1
                if pos_count > 1: pos += " "
                pos += unit.symbol
                if power != 1.0:
                    pos += "**%g" % power
        # emit negative exponents second
        neg = ""
        neg_count = 0
        simple_denominator = True
Justin MacCallum's avatar
Justin MacCallum committed
435
        for unit, power in self.iter_base_or_scaled_units():
436
437
438
439
440
441
442
            if power < 0:
                neg_count += 1
                if neg_count > 1: neg += " "
                neg += unit.symbol
                if power != -1.0:
                    neg += "**%g" % -power
                    simple_denominator = False
Justin MacCallum's avatar
Justin MacCallum committed
443
        # Format of denominator depends on number of terms
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
        if 0 == neg_count:
            neg_string = ""
        elif 1 == neg_count and simple_denominator:
            neg_string = "/%s" % neg
        else:
            neg_string = "/(%s)" % neg
        if 0 == pos_count:
            pos_string = ""
        else:
            pos_string = pos
        if 0 == pos_count == neg_count:
            symbol = "dimensionless"
        else:
            symbol = "%s%s" % (pos_string, neg_string)
        return symbol

    def get_name(self):
        """
        Returns a unit name (string) for this Unit, composed of its various
        BaseUnit symbols.  e.g. 'kilogram meter**2 secon**-1'.
        """
465
466
467
468
        try:
            return self._name
        except AttributeError:
            pass
469
470
471
        # emit positive exponents first
        pos = ""
        pos_count = 0
Justin MacCallum's avatar
Justin MacCallum committed
472
        for unit, power in self.iter_base_or_scaled_units():
473
474
475
476
477
478
479
480
481
482
            if power > 0:
                pos_count += 1
                if pos_count > 1: pos += "*"
                pos += unit.name
                if power != 1.0:
                    pos += "**%g" % power
        # emit negative exponents second
        neg = ""
        neg_count = 0
        simple_denominator = True
Justin MacCallum's avatar
Justin MacCallum committed
483
        for unit, power in self.iter_base_or_scaled_units():
484
485
486
487
488
489
490
            if power < 0:
                neg_count += 1
                if neg_count > 1: neg += "*"
                neg += unit.name
                if power != -1.0:
                    neg += "**%g" % -power
                    simple_denominator = False
Justin MacCallum's avatar
Justin MacCallum committed
491
        # Format of denominator depends on number of terms
492
493
494
495
496
497
498
499
500
501
502
503
504
505
        if 0 == neg_count:
            neg_string = ""
        elif 1 == neg_count and simple_denominator:
            neg_string = "/%s" % neg
        else:
            neg_string = "/(%s)" % neg
        if 0 == pos_count:
            pos_string = ""
        else:
            pos_string = pos
        if 0 == pos_count == neg_count:
            name = "dimensionless"
        else:
            name = "%s%s" % (pos_string, neg_string)
506
        self._name = name
507
508
509
510
511
512
        return name


class ScaledUnit(object):
    """
    ScaledUnit is like a BaseUnit, but it is based on another Unit.
Justin MacCallum's avatar
Justin MacCallum committed
513

514
515
516
    ScaledUnit and BaseUnit are both used in the internals of Unit.  They
    should only be used during the construction of Units.
    """
517
518
    __array_priority__ = 100

519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
    def __init__(self, factor, master, name, symbol):
        self.factor = factor
        # Convert to one base_unit per dimension
        base_units = {}
        for bu, exponent in master.iter_all_base_units():
            dim = bu.dimension
            if dim not in base_units:
                base_units[dim] = [bu, exponent]
            else:
                base_units[dim][1] += exponent
                self.factor *= base_units[dim][0].conversion_factor_to(bu)
        for sbu, exponent in master.iter_scaled_units():
            self.factor *= sbu.factor**exponent
        self.base_units = base_units
        self.master = master
        self.name = name
        self.symbol = symbol

    def __iter__(self):
538
        for dim in sorted(self.base_units.keys()):
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
            yield self.base_units[dim]

    def iter_base_units(self):
        for base_unit, exponent in self:
            yield(base_unit, exponent)

    def iter_base_dimensions(self):
        """
        Returns a sorted tuple of (BaseDimension, exponent) pairs, describing the dimension of this unit.
        """
        for base_unit, exponent in self:
            if exponent != 0:
                yield (base_unit.dimension, exponent)

    def get_dimension_tuple(self):
        """
        Returns a sorted tuple of (BaseDimension, exponent) pairs, that can be used as a dictionary key.
        """
        l = list(self.iter_base_dimensions())
        l.sort()
        return tuple(l)
Justin MacCallum's avatar
Justin MacCallum committed
560

561
562
    def get_conversion_factor_to_base_units(self):
        return self.factor
Justin MacCallum's avatar
Justin MacCallum committed
563

564
565
566
567
568
569
570
571
572
573
574
575
    def conversion_factor_to(self, other):
        # Create fake unit based on base units
        if self is other:
            return 1.0
        u = {}
        for base_unit, exponent in self.iter_base_units():
            u[base_unit] = exponent
        if isinstance(other, Unit):
            other_u = other
        else:
            other_u = Unit({other: 1.0})
        return self.factor * Unit(u).conversion_factor_to(other_u)
Peter Eastman's avatar
Peter Eastman committed
576
577
578
579
580

    def __lt__(self, other):
        """Compare two ScaledUnits.
        """
        return hash(self) < hash(other)
Justin MacCallum's avatar
Justin MacCallum committed
581

582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
    def __str__(self):
        """Returns a string with the name of this ScaledUnit
        """
        return self.name

    def __repr__(self):
        """
        """
        base_units = ""
        for base_unit, power in self.iter_base_units():
            if len(base_units) > 0:
                base_units += ", "
            base_units += "%s: %d" % (base_unit, power)
        return "ScaledUnit(factor=" + repr(self.factor) + \
                ", master="+str(self.master)+", name=" + repr(self.name)\
                + ", symbol=" + repr(self.symbol) + ")"

class UnitSystem(object):
600
601
602
603
604
    """
    A complete system of units defining the *base* unit in each dimension

    Parameters
    ----------
Robert McGibbon's avatar
Robert McGibbon committed
605
    units : list
606
607
        List of base units from which to construct the unit system
    """
608
609
    def __init__(self, units):
        self.units = units
610
        self._unit_conversion_cache = {}
611
612
613
614
615
616
617
618
619
620
621
        # Create a set of base units to be used for dimension conversion
        base_units = {}
        for unit in self.units:
            for base_unit, exponent in unit.iter_base_units():
                d = base_unit.dimension
                if d not in base_units:
                    base_units[d] = base_unit
        self.base_units = base_units
        if not len(self.base_units) == len(self.units):
            raise ArithmeticError("UnitSystem must have same number of units as base dimensions")
        # self.dimensions is a dict of {BaseDimension: index}
622
        dimensions = sorted(base_units.keys())
623
624
625
626
627
628
629
630
631
632
633
634
        self.dimensions = {}
        for d in range(len(dimensions)):
            self.dimensions[dimensions[d]] = d
        # Create units->base units exponent matrix
        to_base_units = zeros(len(self.units))
        for m in range(len(self.units)):
            unit = self.units[m]
            for dim, power in unit.iter_base_dimensions():
                n = self.dimensions[dim]
                to_base_units[m][n] = power
        try:
            self.from_base_units = ~to_base_units
Peter Eastman's avatar
Peter Eastman committed
635
        except ArithmeticError as e:
636
637
638
639
640
        # for compatibility between python 2.5 and python 3.0,
        # try replacing line above with the following two lines:
        # except ArithmeticError:
        #     e=sys.exc_info[1]
            raise ArithmeticError("UnitSystem is not a valid basis set.  " + str(e))
Justin MacCallum's avatar
Justin MacCallum committed
641

642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
    def __iter__(self):
        for unit in self.units:
            yield unit

    def __str__(self):
        """
        """
        result = "UnitSystem(["
        sep = ""
        for unit in self:
            result += sep
            result += str(unit)
            sep = ", "
        result += "])"
        return result

    def express_unit(self, old_unit):
        """
        """
661
662
        if old_unit in self._unit_conversion_cache:
            return self._unit_conversion_cache[old_unit]
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
        # First express unit in terms of base dimensions found in this unit system
        # (plus other dimensions not found)
        m = len(self.dimensions)
        base_dims = [0] * m
        other_dims = {}
        for dim, exponent in old_unit.iter_base_dimensions():
            if dim in self.dimensions:
                base_dims[self.dimensions[dim]] = exponent
            else:
                other_dims[dim] = exponent
        # Multiply by self.from_base_units to convert to unit system units
        u = MyMatrix([base_dims,]) * self.from_base_units
        new_unit = dimensionless
        for i in range(m):
            exponent = u[0][i]
            if exponent != 0:
                new_unit *= Unit({self.units[i]: exponent})
        if len(other_dims) > 0:
            # Find one base unit for each dimension
            found_dims = {}
            for base_unit, useless_exponent in old_unit.iter_all_base_units():
                dim = base_unit.dimension
                if dim not in other_dims:
                    continue # this dimension is in the unit system
                if dim in found_dims:
                    continue # already got a BaseUnit for this dimension
                found_dims[dim] = base_unit
                exponent = other_dims[dim]
                new_unit *= Unit({base_unit: exponent})
692
        self._unit_conversion_cache[old_unit] = new_unit
693
694
695
696
697
        return new_unit

def is_unit(x):
    """
    Returns True if x is a Unit, False otherwise.
Justin MacCallum's avatar
Justin MacCallum committed
698

699
    Examples
Robert McGibbon's avatar
Robert McGibbon committed
700
    --------
701
702
703
704
    >>> is_unit(16)
    False
    """
    return isinstance(x, Unit)
Justin MacCallum's avatar
Justin MacCallum committed
705

706
707
708
709
710
711
712
dimensionless = Unit({})

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