forked from yt-project/unyt
/
unit_object.py
1160 lines (1006 loc) · 37.2 KB
/
unit_object.py
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
A class that represents a unit symbol.
"""
# -----------------------------------------------------------------------------
# Copyright (c) 2018, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the LICENSE file, distributed with this software.
# -----------------------------------------------------------------------------
import copy
import itertools
import math
from functools import lru_cache
from keyword import iskeyword as _iskeyword
import numpy as np
from numbers import Number as numeric_type
import token
from sympy import (
Expr,
Mul,
Add,
Number,
Pow,
Symbol,
Integer,
Float,
Basic,
Rational,
sqrt,
Mod,
floor,
)
from sympy.core.numbers import One
from sympy import sympify, latex
from sympy.parsing.sympy_parser import parse_expr, auto_number, rationalize
from unyt.dimensions import (
angle,
base_dimensions,
dimensionless,
temperature,
current_mks,
)
import unyt.dimensions as dims
from unyt.equivalencies import equivalence_registry
from unyt.exceptions import (
InvalidUnitOperation,
MissingMKSCurrent,
MKSCGSConversionError,
UnitConversionError,
UnitDtypeError,
UnitsNotReducible,
)
from unyt._physical_ratios import speed_of_light_cm_per_s
from unyt._unit_lookup_table import inv_name_alternatives
from unyt.unit_registry import (
default_unit_registry,
_lookup_unit_symbol,
UnitRegistry,
UnitParseError,
)
from unyt.unit_systems import _split_prefix
sympy_one = sympify(1)
global_dict = {
"Symbol": Symbol,
"Integer": Integer,
"Float": Float,
"Rational": Rational,
"sqrt": sqrt,
}
def _auto_positive_symbol(tokens, local_dict, global_dict):
"""
Inserts calls to ``Symbol`` for undefined variables.
Passes in positive=True as a keyword argument.
Adapted from sympy.sympy.parsing.sympy_parser.auto_symbol
"""
result = []
prevTok = (None, None)
tokens.append((None, None)) # so zip traverses all tokens
for tok, nextTok in zip(tokens, tokens[1:]):
tokNum, tokVal = tok
nextTokNum, nextTokVal = nextTok
if tokNum == token.NAME:
name = tokVal
if (
name in ["True", "False", "None"]
# special case 'as' for attosecond
or (_iskeyword(name) and name != "as")
or name in local_dict
# Don't convert attribute access
or (prevTok[0] == token.OP and prevTok[1] == ".")
# Don't convert keyword arguments
or (
prevTok[0] == token.OP
and prevTok[1] in ("(", ",")
and nextTokNum == token.OP
and nextTokVal == "="
)
):
result.append((token.NAME, name))
continue
elif name in global_dict:
obj = global_dict[name]
if isinstance(obj, (Basic, type)) or callable(obj):
result.append((token.NAME, name))
continue
# try to resolve known alternative unit name
try:
used_name = inv_name_alternatives[str(name)]
except KeyError:
# if we don't know this name it's a user-defined unit name
# so we should create a new symbol for it
used_name = str(name)
result.extend(
[
(token.NAME, "Symbol"),
(token.OP, "("),
(token.NAME, repr(used_name)),
(token.OP, ","),
(token.NAME, "positive"),
(token.OP, "="),
(token.NAME, "True"),
(token.OP, ")"),
]
)
else:
result.append((tokNum, tokVal))
prevTok = (tokNum, tokVal)
return result
def _get_latex_representation(expr, registry):
symbol_table = {}
for ex in expr.free_symbols:
try:
symbol_table[ex] = registry.lut[str(ex)][3]
except KeyError:
symbol_table[ex] = r"\rm{" + str(ex).replace("_", r"\ ") + "}"
# invert the symbol table dict to look for keys with identical values
invert_symbols = {}
for key, value in symbol_table.items():
if value not in invert_symbols:
invert_symbols[value] = [key]
else:
invert_symbols[value].append(key)
# if there are any units with identical latex representations, substitute
# units to avoid uncanceled terms in the final latex expression.
for val in invert_symbols:
symbols = invert_symbols[val]
for i in range(1, len(symbols)):
expr = expr.subs(symbols[i], symbols[0])
prefix = None
l_expr = expr
if isinstance(expr, Mul):
coeffs = expr.as_coeff_Mul()
if coeffs[0] == 1 or not isinstance(coeffs[0], Float):
l_expr = coeffs[1]
else:
l_expr = coeffs[1]
prefix = Float(coeffs[0], 2)
latex_repr = latex(
l_expr,
symbol_names=symbol_table,
mul_symbol="dot",
fold_frac_powers=True,
fold_short_frac=True,
)
if prefix is not None:
latex_repr = latex(prefix, mul_symbol="times") + "\\ " + latex_repr
if latex_repr == "1":
return ""
else:
return latex_repr
unit_text_transform = (_auto_positive_symbol, rationalize, auto_number)
class Unit(object):
"""
A symbolic unit, using sympy functionality. We only add "dimensions" so
that sympy understands relations between different units.
"""
# Set some assumptions for sympy.
is_positive = True # make sqrt(m**2) --> m
is_commutative = True
is_number = False
# caches for imports
_ua = None
_uq = None
__array_priority__ = 3.0
def __new__(
cls,
unit_expr=sympy_one,
base_value=None,
base_offset=0.0,
dimensions=None,
registry=None,
latex_repr=None,
):
"""
Create a new unit. May be an atomic unit (like a gram) or combinations
of atomic units (like g / cm**3).
Parameters
----------
unit_expr : Unit object, sympy.core.expr.Expr object, or str
The symbolic unit expression.
base_value : float
The unit's value in yt's base units.
base_offset : float
The offset necessary to normalize temperature units to a common
zero point.
dimensions : sympy.core.expr.Expr
A sympy expression representing the dimensionality of this unit.
It must contain only mass, length, time, temperature and angle
symbols.
registry : UnitRegistry object
The unit registry we use to interpret unit symbols.
latex_repr : string
A string to render the unit as LaTeX
"""
unit_cache_key = None
# Parse a text unit representation using sympy's parser
if isinstance(unit_expr, (str, bytes)):
if isinstance(unit_expr, bytes):
unit_expr = unit_expr.decode("utf-8")
# this cache substantially speeds up unit conversions
if registry and unit_expr in registry._unit_object_cache:
return registry._unit_object_cache[unit_expr]
unit_cache_key = unit_expr
if not unit_expr:
# Bug catch...
# if unit_expr is an empty string, parse_expr fails hard...
unit_expr = "1"
try:
unit_expr = parse_expr(
unit_expr,
global_dict=global_dict,
transformations=unit_text_transform,
)
except SyntaxError as e:
msg = "Unit expression '%s' raised an error during parsing:\n%s" % (
unit_expr,
repr(e),
)
raise UnitParseError(msg)
# Simplest case. If user passes a Unit object, just use the expr.
elif isinstance(unit_expr, Unit):
# grab the unit object's sympy expression.
unit_expr = unit_expr.expr
elif hasattr(unit_expr, "units") and hasattr(unit_expr, "value"):
# something that looks like a unyt_array, grab the unit and value
if unit_expr.shape != ():
raise UnitParseError(
"Cannot create a unit from a non-scalar unyt_array, "
"received: %s" % (unit_expr,)
)
value = unit_expr.value
if value == 1:
unit_expr = unit_expr.units.expr
else:
unit_expr = unit_expr.value * unit_expr.units.expr
# Make sure we have an Expr at this point.
if not isinstance(unit_expr, Expr):
raise UnitParseError(
"Unit representation must be a string or "
"sympy Expr. '%s' has type '%s'." % (unit_expr, type(unit_expr))
)
# this is slightly faster if unit_expr is the same object as
# sympy_one than just checking for == equality
is_one = unit_expr is sympy_one or unit_expr == sympy_one
if dimensions is None and is_one:
dimensions = dimensionless
if registry is None:
# Caller did not set the registry, so use the default.
registry = default_unit_registry
# done with argument checking...
# see if the unit is atomic.
is_atomic = False
if isinstance(unit_expr, Symbol):
is_atomic = True
#
# check base_value and dimensions
#
if base_value is not None:
# check that base_value is a float or can be converted to one
try:
base_value = float(base_value)
except ValueError:
raise UnitParseError(
"Could not use base_value as a float. "
"base_value is '%s' (type '%s')." % (base_value, type(base_value))
)
# check that dimensions is valid
if dimensions is not None:
_validate_dimensions(dimensions)
else:
# lookup the unit symbols
unit_data = _get_unit_data_from_expr(unit_expr, registry.lut)
base_value = unit_data[0]
dimensions = unit_data[1]
if len(unit_data) > 2:
base_offset = unit_data[2]
latex_repr = unit_data[3]
else:
base_offset = 0.0
# Create obj with superclass construct.
obj = super(Unit, cls).__new__(cls)
# Attach attributes to obj.
obj.expr = unit_expr
obj.is_atomic = is_atomic
obj.base_value = base_value
obj.base_offset = base_offset
obj.dimensions = dimensions
obj._latex_repr = latex_repr
obj.registry = registry
# if we parsed a string unit expression, cache the result
# for faster lookup later
if unit_cache_key is not None:
registry._unit_object_cache[unit_cache_key] = obj
# Return `obj` so __init__ can handle it.
return obj
@property
def latex_repr(self):
"""A LaTeX representation for the unit
Examples
--------
>>> from unyt import g, cm
>>> (g/cm**3).units.latex_repr
'\\\\frac{\\\\rm{g}}{\\\\rm{cm}^{3}}'
"""
if self._latex_repr is not None:
return self._latex_repr
if self.expr.is_Atom:
expr = self.expr
else:
expr = self.expr.copy()
self._latex_repr = _get_latex_representation(expr, self.registry)
return self._latex_repr
@property
def units(self):
return self
def __hash__(self):
return super(Unit, self).__hash__()
# end sympy conventions
def __repr__(self):
if self.expr == sympy_one:
return "(dimensionless)"
# @todo: don't use dunder method?
return self.expr.__repr__()
def __str__(self):
if self.expr == sympy_one:
return "dimensionless"
# @todo: don't use dunder method?
return self.expr.__str__()
#
# Start unit operations
#
def __add__(self, u):
raise InvalidUnitOperation("addition with unit objects is not allowed")
def __radd__(self, u):
raise InvalidUnitOperation("addition with unit objects is not allowed")
def __sub__(self, u):
raise InvalidUnitOperation("subtraction with unit objects is not allowed")
def __rsub__(self, u):
raise InvalidUnitOperation("subtraction with unit objects is not allowed")
def __iadd__(self, u):
raise InvalidUnitOperation(
"in-place operations with unit objects are not allowed"
)
def __isub__(self, u):
raise InvalidUnitOperation(
"in-place operations with unit objects are not allowed"
)
def __imul__(self, u):
raise InvalidUnitOperation(
"in-place operations with unit objects are not allowed"
)
def __itruediv__(self, u):
raise InvalidUnitOperation(
"in-place operations with unit objects are not allowed"
)
def __rmul__(self, u):
return self.__mul__(u)
def __mul__(self, u):
""" Multiply Unit with u (Unit object). """
if self._ua is None:
# cache the imported object to avoid cost of repeated imports
from unyt.array import unyt_quantity, unyt_array
self._ua = unyt_array
self._uq = unyt_quantity
if not isinstance(u, Unit):
cls = type(u)
if cls in (np.ndarray, np.matrix, np.ma.masked_array) or isinstance(
u, (numeric_type, list, tuple)
):
try:
units = u.units * self
except AttributeError:
units = self
data = np.array(u)
if data.dtype.kind not in ("f", "u", "i", "c"):
raise UnitDtypeError(data, data.dtype)
if data.shape == ():
return self._uq(data, units, bypass_validation=True)
return self._ua(data, units, bypass_validation=True)
elif isinstance(u, self._ua):
return cls(u, u.units * self, bypass_validation=True)
else:
raise InvalidUnitOperation(
"Tried to multiply a Unit object with '%s' (type %s). "
"This behavior is undefined." % (u, type(u))
)
base_offset = 0.0
if self.base_offset or u.base_offset:
if u.dimensions in (temperature, angle) and self.is_dimensionless:
base_offset = u.base_offset
elif self.dimensions in (temperature, angle) and u.is_dimensionless:
base_offset = self.base_offset
else:
raise InvalidUnitOperation(
"Quantities with dimensions of angle or units of "
"Fahrenheit or Celsius cannot be multiplied."
)
return Unit(
self.expr * u.expr,
base_value=(self.base_value * u.base_value),
base_offset=base_offset,
dimensions=(self.dimensions * u.dimensions),
registry=self.registry,
)
def __truediv__(self, u):
""" Divide Unit by u (Unit object). """
if not isinstance(u, Unit):
if isinstance(u, (numeric_type, list, tuple, np.ndarray)):
from unyt.array import unyt_quantity
return unyt_quantity(1.0, self) / u
else:
raise InvalidUnitOperation(
"Tried to divide a Unit object by '%s' (type %s). This "
"behavior is undefined." % (u, type(u))
)
base_offset = 0.0
if self.base_offset or u.base_offset:
if self.dimensions in (temperature, angle) and u.is_dimensionless:
base_offset = self.base_offset
else:
raise InvalidUnitOperation(
"Quantities with units of Farhenheit "
"and Celsius cannot be divided."
)
return Unit(
self.expr / u.expr,
base_value=(self.base_value / u.base_value),
base_offset=base_offset,
dimensions=(self.dimensions / u.dimensions),
registry=self.registry,
)
def __rtruediv__(self, u):
return u * self ** -1
def __pow__(self, p):
""" Take Unit to power p (float). """
try:
p = Rational(str(p)).limit_denominator()
except (ValueError, TypeError):
raise InvalidUnitOperation(
"Tried to take a Unit object to the "
"power '%s' (type %s). Failed to cast "
"it to a float." % (p, type(p))
)
return Unit(
self.expr ** p,
base_value=(self.base_value ** p),
dimensions=(self.dimensions ** p),
registry=self.registry,
)
def __eq__(self, u):
""" Test unit equality. """
if not isinstance(u, Unit):
return False
return (
math.isclose(self.base_value, u.base_value)
and self.dimensions == u.dimensions
)
def __ne__(self, u):
""" Test unit inequality. """
if not isinstance(u, Unit):
return True
if not math.isclose(self.base_value, u.base_value):
return True
# use 'is' comparison dimensions to avoid expensive sympy operation
if self.dimensions is u.dimensions:
return False
# fall back to expensive sympy comparison
return self.dimensions != u.dimensions
def copy(self):
return copy.deepcopy(self)
def __deepcopy__(self, memodict=None):
expr = str(self.expr)
base_value = copy.deepcopy(self.base_value)
base_offset = copy.deepcopy(self.base_offset)
dimensions = copy.deepcopy(self.dimensions)
lut = copy.deepcopy(self.registry.lut)
registry = UnitRegistry(lut=lut)
return Unit(expr, base_value, base_offset, dimensions, registry)
#
# End unit operations
#
def same_dimensions_as(self, other_unit):
"""Test if the dimensions of *other_unit* are the same as this unit
Examples
--------
>>> from unyt import Msun, kg, mile
>>> Msun.units.same_dimensions_as(kg.units)
True
>>> Msun.units.same_dimensions_as(mile.units)
False
"""
# test first for 'is' equality to avoid expensive sympy operation
if self.dimensions is other_unit.dimensions:
return True
return (self.dimensions / other_unit.dimensions) == sympy_one
@property
def is_dimensionless(self):
"""Is this a dimensionless unit?
Returns
-------
True for a dimensionless unit, False otherwise
Examples
--------
>>> from unyt import count, kg
>>> count.units.is_dimensionless
True
>>> kg.units.is_dimensionless
False
"""
return self.dimensions is sympy_one
@property
def is_code_unit(self):
"""Is this a "code" unit?
Returns
-------
True if the unit consists of atom units that being with "code".
False otherwise
"""
for atom in self.expr.atoms():
if not (str(atom).startswith("code") or atom.is_Number):
return False
return True
def list_equivalencies(self):
"""Lists the possible equivalencies associated with this unit object
Examples
--------
>>> from unyt import km
>>> km.units.list_equivalencies()
spectral: length <-> spatial_frequency <-> frequency <-> energy
schwarzschild: mass <-> length
compton: mass <-> length
"""
from unyt.equivalencies import equivalence_registry
for k, v in equivalence_registry.items():
if self.has_equivalent(k):
print(v())
def has_equivalent(self, equiv):
"""
Check to see if this unit object as an equivalent unit in *equiv*.
Example
-------
>>> from unyt import km
>>> km.has_equivalent('spectral')
True
>>> km.has_equivalent('mass_energy')
False
"""
try:
this_equiv = equivalence_registry[equiv]()
except KeyError:
raise KeyError('No such equivalence "%s".' % equiv)
old_dims = self.dimensions
return old_dims in this_equiv._dims
def get_base_equivalent(self, unit_system=None):
"""Create and return dimensionally-equivalent units in a specified base.
>>> from unyt import g, cm
>>> (g/cm**3).get_base_equivalent('mks')
kg/m**3
>>> (g/cm**3).get_base_equivalent('solar')
Mearth/AU**3
"""
from unyt.unit_registry import _sanitize_unit_system
unit_system = _sanitize_unit_system(unit_system, self)
try:
conv_data = _check_em_conversion(
self.units, registry=self.registry, unit_system=unit_system
)
except MKSCGSConversionError:
raise UnitsNotReducible(self.units, unit_system)
if any(conv_data):
new_units, _ = _em_conversion(self, conv_data, unit_system=unit_system)
else:
new_units = unit_system[self.dimensions]
return Unit(new_units, registry=self.registry)
def get_cgs_equivalent(self):
"""Create and return dimensionally-equivalent cgs units.
Example
-------
>>> from unyt import kg, m
>>> (kg/m**3).get_cgs_equivalent()
g/cm**3
"""
return self.get_base_equivalent(unit_system="cgs")
def get_mks_equivalent(self):
"""Create and return dimensionally-equivalent mks units.
Example
-------
>>> from unyt import g, cm
>>> (g/cm**3).get_mks_equivalent()
kg/m**3
"""
return self.get_base_equivalent(unit_system="mks")
def get_conversion_factor(self, other_units, dtype=None):
"""Get the conversion factor and offset (if any) from one unit
to another
Parameters
----------
other_units: unit object
The units we want the conversion factor for
dtype: numpy dtype
The dtype to return the conversion factor as
Returns
-------
conversion_factor : float
old_units / new_units
offset : float or None
Offset between this unit and the other unit. None if there is
no offset.
Examples
--------
>>> from unyt import km, cm, degree_fahrenheit, degree_celsius
>>> km.get_conversion_factor(cm)
(100000.0, None)
>>> degree_celsius.get_conversion_factor(degree_fahrenheit)
(1.7999999999999998, -31.999999999999886)
"""
return _get_conversion_factor(self, other_units, dtype)
def latex_representation(self):
"""A LaTeX representation for the unit
Examples
--------
>>> from unyt import g, cm
>>> (g/cm**3).latex_representation()
'\\\\frac{\\\\rm{g}}{\\\\rm{cm}^{3}}'
"""
return self.latex_repr
def as_coeff_unit(self):
"""Factor the coefficient multiplying a unit
For units that are multiplied by a constant dimensionless
coefficient, returns a tuple containing the coefficient and
a new unit object for the unmultiplied unit.
Example
-------
>>> import unyt as u
>>> unit = (u.m**2/u.cm).simplify()
>>> unit
100*m
>>> unit.as_coeff_unit()
(100.0, m)
"""
coeff, mul = self.expr.as_coeff_Mul()
coeff = float(coeff)
ret = Unit(
mul,
self.base_value / coeff,
self.base_offset,
self.dimensions,
self.registry,
)
return coeff, ret
def simplify(self):
"""Return a new equivalent unit object with a simplified unit expression
>>> import unyt as u
>>> unit = (u.m**2/u.cm).simplify()
>>> unit
100*m
"""
expr = self.expr
self.expr = _cancel_mul(expr, self.registry)
return self
def _factor_pairs(expr):
factors = expr.as_ordered_factors()
expanded_factors = []
for f in factors:
if f.is_Number:
continue
base, exp = f.as_base_exp()
if exp.q != 1:
expanded_factors.append(base ** Mod(exp, 1))
exp = floor(exp)
if exp >= 0:
f = (base,) * exp
else:
f = (1 / base,) * abs(exp)
expanded_factors.extend(f)
return list(itertools.combinations(expanded_factors, 2))
def _create_unit_from_factor(factor, registry):
base, exp = factor.as_base_exp()
f = registry[str(base)]
return Unit(base, f[0], f[2], f[1], registry, f[3]) ** exp
def _cancel_mul(expr, registry):
pairs_to_consider = _factor_pairs(expr)
uncancelable_pairs = set()
while len(pairs_to_consider):
pair = pairs_to_consider.pop()
if pair in uncancelable_pairs:
continue
u1 = _create_unit_from_factor(pair[0], registry)
u2 = _create_unit_from_factor(pair[1], registry)
prod = u1 * u2
if prod.dimensions == 1:
expr = expr / pair[0]
expr = expr / pair[1]
value = prod.base_value
if value != 1:
if value.is_integer():
value = int(value)
expr *= value
else:
uncancelable_pairs.add(pair)
pairs_to_consider = _factor_pairs(expr)
return expr
#
# Unit manipulation functions
#
# map from dimensions in one unit system to dimensions in other system,
# canonical unit to convert to in that system, and floating point
# conversion factor
em_conversions = {
("C", dims.charge_mks): (dims.charge_cgs, "statC", 0.1 * speed_of_light_cm_per_s),
("statC", dims.charge_cgs): (dims.charge_mks, "C", 10.0 / speed_of_light_cm_per_s),
("T", dims.magnetic_field_mks): (dims.magnetic_field_cgs, "G", 1.0e4),
("G", dims.magnetic_field_cgs): (dims.magnetic_field_mks, "T", 1.0e-4),
("A", dims.current_mks): (dims.current_cgs, "statA", 0.1 * speed_of_light_cm_per_s),
("statA", dims.current_cgs): (
dims.current_mks,
"A",
10.0 / speed_of_light_cm_per_s,
),
("V", dims.electric_potential_mks): (
dims.electric_potential_cgs,
"statV",
1.0e-8 * speed_of_light_cm_per_s,
),
("statV", dims.electric_potential_cgs): (
dims.electric_potential_mks,
"V",
1.0e8 / speed_of_light_cm_per_s,
),
("Ω", dims.resistance_mks): (
dims.resistance_cgs,
"statohm",
1.0e9 / (speed_of_light_cm_per_s ** 2),
),
("statohm", dims.resistance_cgs): (
dims.resistance_mks,
"Ω",
1.0e-9 * speed_of_light_cm_per_s ** 2,
),
}
def _em_conversion(orig_units, conv_data, to_units=None, unit_system=None):
"""Convert between E&M & MKS base units.
If orig_units is a CGS (or MKS) E&M unit, conv_data contains the
corresponding MKS (or CGS) unit and scale factor converting between them.
This must be done by replacing the expression of the original unit
with the new one in the unit expression and multiplying by the scale
factor.
"""
conv_unit, canonical_unit, scale = conv_data
if conv_unit is None:
conv_unit = canonical_unit
new_expr = orig_units.copy().expr.replace(
orig_units.expr, scale * canonical_unit.expr
)
if unit_system is not None:
# we don't know the to_units, so we get it directly from the
# conv_data
inter_expr = orig_units.copy().expr.replace(orig_units.expr, conv_unit.expr)
to_units = Unit(inter_expr, registry=orig_units.registry)
new_units = Unit(new_expr, registry=orig_units.registry)
conv = new_units.get_conversion_factor(to_units)
return to_units, conv
@lru_cache(maxsize=128, typed=False)
def _check_em_conversion(unit, to_unit=None, unit_system=None, registry=None):
"""Check to see if the units contain E&M units
This function supports unyt's ability to convert data to and from E&M
electromagnetic units. However, this support is limited and only very
simple unit expressions can be readily converted. This function tries
to see if the unit is an atomic base unit that is present in the
em_conversions dict. If it does not contain E&M units, the function
returns an empty tuple. If it does contain an atomic E&M unit in
the em_conversions dict, it returns a tuple containing the unit to convert
to and scale factor. If it contains a more complicated E&M unit and we are
trying to convert between CGS & MKS E&M units, it raises an error.
"""
em_map = ()
if unit == to_unit:
return em_map
if unit.is_atomic:
prefix, unit_wo_prefix = _split_prefix(str(unit), unit.registry.lut)
else:
prefix, unit_wo_prefix = "", str(unit)
if (unit_wo_prefix, unit.dimensions) in em_conversions:
em_info = em_conversions[unit_wo_prefix, unit.dimensions]
em_unit = Unit(prefix + em_info[1], registry=registry)
if to_unit is None:
cmks_in_unit = current_mks in unit.dimensions.atoms()
cmks_in_unit_system = unit_system.units_map[current_mks]
cmks_in_unit_system = cmks_in_unit_system is not None
if cmks_in_unit and cmks_in_unit_system:
em_map = (unit_system[unit.dimensions], unit, 1.0)
else:
em_map = (None, em_unit, em_info[2])
elif to_unit.dimensions == em_unit.dimensions:
em_map = (to_unit, em_unit, em_info[2])
if em_map:
return em_map
if unit_system is None:
if to_unit.dimensions != unit.dimensions:
raise MKSCGSConversionError(unit)
else:
from unyt.unit_systems import unit_system_registry
unit_system = unit_system_registry["mks"]
for unit_atom in unit.expr.atoms():
if unit_atom.is_Number:
continue
bu = str(unit_atom)
budims = Unit(bu, registry=registry).dimensions
try:
if str(unit_system[budims]) == bu:
continue
except MissingMKSCurrent:
raise MKSCGSConversionError(unit)
if (bu, budims) in em_conversions:
conv_unit = em_conversions[bu, budims][1]
if to_unit is not None:
for to_unit_atom in to_unit.expr.atoms():
bou = str(to_unit_atom)
if bou == conv_unit:
raise MKSCGSConversionError(unit)
else:
raise MKSCGSConversionError(unit)
return em_map
def _get_conversion_factor(old_units, new_units, dtype):
"""
Get the conversion factor between two units of equivalent dimensions. This
is the number you multiply data by to convert from values in `old_units` to
values in `new_units`.
Parameters
----------
old_units: str or Unit object
The current units.
new_units : str or Unit object
The units we want.
dtype: NumPy dtype
The dtype of the conversion factor
Returns
-------
conversion_factor : float
`old_units / new_units`
offset : float or None
Offset between the old unit and new unit.
"""
if old_units.dimensions != new_units.dimensions:
raise UnitConversionError(