-
Notifications
You must be signed in to change notification settings - Fork 46
/
array.py
2696 lines (2361 loc) · 84 KB
/
array.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
"""
unyt_array class.
"""
import copy
import re
import sys
import warnings
from functools import lru_cache
from numbers import Number as numeric_type
import numpy as np
from numpy import (
absolute,
add,
arccos,
arccosh,
arcsin,
arcsinh,
arctan,
arctan2,
arctanh,
bitwise_and,
bitwise_or,
bitwise_xor,
ceil,
clip,
conj,
copysign,
cos,
cosh,
deg2rad,
divide,
divmod as divmod_,
equal,
exp,
exp2,
expm1,
fabs,
floor,
floor_divide,
fmax,
fmin,
fmod,
frexp,
greater,
greater_equal,
heaviside,
hypot,
invert,
iscomplex,
isfinite,
isinf,
isnan,
isnat,
isreal,
ldexp,
left_shift,
less,
less_equal,
log,
log1p,
log2,
log10,
logaddexp,
logaddexp2,
logical_and,
logical_not,
logical_or,
logical_xor,
matmul,
maximum,
minimum,
mod,
modf,
multiply,
negative,
nextafter,
not_equal,
ones_like,
positive,
power,
rad2deg,
reciprocal,
remainder,
right_shift,
rint,
sign,
signbit,
sin,
sinh,
spacing,
sqrt,
square,
subtract,
tan,
tanh,
true_divide,
trunc,
)
from numpy.core.umath import _ones_like
from sympy import Rational
from unyt._on_demand_imports import _astropy, _dask, _pint
from unyt._pint_conversions import convert_pint_units
from unyt._unit_lookup_table import default_unit_symbol_lut
from unyt.dimensions import angle, temperature
from unyt.equivalencies import equivalence_registry
from unyt.exceptions import (
InvalidUnitEquivalence,
InvalidUnitOperation,
IterableUnitCoercionError,
MKSCGSConversionError,
SymbolNotFoundError,
UnitConversionError,
UnitOperationError,
UnitsNotReducible,
)
from unyt.unit_object import Unit, _check_em_conversion, _em_conversion
from unyt.unit_registry import (
UnitRegistry,
_correct_old_unit_registry,
_sanitize_unit_system,
default_unit_registry,
)
from ._deprecation import warn_deprecated
NULL_UNIT = Unit()
POWER_MAPPING = {multiply: lambda x: x, divide: lambda x: 2 - x}
DISALLOWED_DTYPES = (
"S", # bytestring
"a", # bytestring
"U", # (unicode) bytes
"O", # Python object
"M", # datetime
"m", # timedelta
)
__doctest_requires__ = {
("unyt_array.from_pint", "unyt_array.to_pint"): ["pint"],
("unyt_array.from_astropy", "unyt_array.to_astropy"): ["astropy"],
}
# This is partially adapted from the following SO thread
# https://stackoverflow.com/questions/41668588/regex-to-match-scientific-notation
_NUMB_PATTERN = (
r"[+/-]?(?:((?:\d\.?\d*[Ee][+\-]?\d+)|(?:\d+\.\d*|\d*\.\d+))|\d+|inf\s|nan\s)"
)
# *all* greek letters are considered valid unit string elements.
# This may be an overshoot. We rely on unyt.Unit to do the actual validation
_UNIT_PATTERN = r"((\s*[*/]\s*)?[α-ωΑ-Ωa-zA-Z]+(\*\*([+-]?\d+|\([+-]?\d+\)))?)+"
_QUAN_PATTERN = rf"{_NUMB_PATTERN}\s*{_UNIT_PATTERN}"
_NUMB_REGEXP = re.compile(_NUMB_PATTERN)
_UNIT_REGEXP = re.compile(_UNIT_PATTERN)
_QUAN_REGEXP = re.compile(_QUAN_PATTERN)
def _iterable(obj):
try:
len(obj)
except Exception:
return False
return True
@lru_cache(maxsize=128, typed=False)
def _sqrt_unit(unit):
return 1, unit**0.5
@lru_cache(maxsize=128, typed=False)
def _multiply_units(unit1, unit2):
try:
ret = (unit1 * unit2).simplify()
except SymbolNotFoundError:
# Some operators are not natively commutative when operands are
# defined within different unit registries, and conversion
# is defined one way but not the other.
ret = (unit2 * unit1).simplify()
return ret.as_coeff_unit()
TEMPERATURE_WARNING = """
Ambiguous operation with heterogeneous temperature units.
In the future, such operations will generate UnitOperationError.
Use delta_degC or delta_degF to avoid the ambiguity.
"""
@lru_cache(maxsize=128, typed=False)
def _preserve_units(unit1, unit2=None):
if unit2 is None or unit1.dimensions is not temperature:
return 1, unit1
if unit1.base_offset == 0.0 and unit2.base_offset != 0.0:
if str(unit1.expr) in ["K", "R"]:
warnings.warn(TEMPERATURE_WARNING, FutureWarning, stacklevel=3)
return 1, unit1
return 1, unit2
return 1, unit1
@lru_cache(maxsize=128, typed=False)
def _power_unit(unit, power):
return 1, unit**power
@lru_cache(maxsize=128, typed=False)
def _square_unit(unit):
return 1, unit * unit
@lru_cache(maxsize=128, typed=False)
def _divide_units(unit1, unit2):
try:
ret = (unit1 / unit2).simplify()
except SymbolNotFoundError:
ret = (1 / (unit2 / unit1).simplify()).units
return ret.as_coeff_unit()
@lru_cache(maxsize=128, typed=False)
def _reciprocal_unit(unit):
return 1, unit**-1
def _passthrough_unit(unit, unit2=None):
return 1, unit
def _return_without_unit(unit, unit2=None):
return 1, None
def _arctan2_unit(unit1, unit2):
return 1, NULL_UNIT
def _comparison_unit(unit1, unit2=None):
return 1, None
def _invert_units(unit):
raise TypeError("Bit-twiddling operators are not defined for unyt_array instances")
def _bitop_units(unit1, unit2):
raise TypeError("Bit-twiddling operators are not defined for unyt_array instances")
def _coerce_iterable_units(input_object, registry=None):
if isinstance(input_object, np.ndarray):
ret = input_object
elif _iterable(input_object):
if any(isinstance(o, unyt_array) for o in input_object):
ff = getattr(input_object[0], "units", NULL_UNIT)
if any(ff != getattr(_, "units", NULL_UNIT) for _ in input_object):
ret = []
for datum in input_object:
try:
ret.append(datum.in_units(ff.units))
except UnitConversionError:
raise IterableUnitCoercionError(str(input_object))
ret = unyt_array(np.array(ret), ff, registry=registry)
# This will create a copy of the data in the iterable.
else:
ret = unyt_array(np.array(input_object), ff, registry=registry)
else:
ret = np.asarray(input_object)
else:
ret = np.asarray(input_object)
if ret.dtype.char in DISALLOWED_DTYPES:
raise IterableUnitCoercionError(str(input_object))
return ret
def _sanitize_units_convert(possible_units, registry):
if isinstance(possible_units, Unit):
return possible_units
# let Unit() try to parse this if it's not already a Unit
unit = Unit(possible_units, registry=registry)
return unit
def _apply_power_mapping(ufunc, in_unit, in_size, in_shape, input_kwarg_dict):
# a reduction of a multiply or divide corresponds to
# a repeated product which we implement as an exponent
mul = 1
power_map = POWER_MAPPING[ufunc]
if input_kwarg_dict.get("axis", None) is not None:
unit = in_unit ** (power_map(in_shape[input_kwarg_dict["axis"]]))
else:
unit = in_unit ** (power_map(in_size))
return mul, unit
unary_operators = (
negative,
absolute,
rint,
sign,
conj,
exp,
exp2,
log,
log2,
log10,
expm1,
log1p,
sqrt,
square,
reciprocal,
sin,
cos,
tan,
arcsin,
arccos,
arctan,
sinh,
cosh,
tanh,
arcsinh,
arccosh,
arctanh,
deg2rad,
rad2deg,
invert,
logical_not,
isreal,
iscomplex,
isfinite,
isinf,
isnan,
signbit,
floor,
ceil,
trunc,
modf,
frexp,
fabs,
spacing,
positive,
isnat,
ones_like,
)
binary_operators = (
add,
subtract,
multiply,
divide,
logaddexp,
logaddexp2,
true_divide,
power,
remainder,
mod,
arctan2,
hypot,
bitwise_and,
bitwise_or,
bitwise_xor,
left_shift,
right_shift,
greater,
greater_equal,
less,
less_equal,
not_equal,
equal,
logical_and,
logical_or,
logical_xor,
maximum,
minimum,
fmax,
fmin,
copysign,
nextafter,
ldexp,
fmod,
divmod_,
heaviside,
)
trigonometric_operators = (sin, cos, tan)
multiple_output_operators = {modf: 2, frexp: 2, divmod_: 2}
LARGE_INPUT = {4: 16777217, 8: 9007199254740993}
class unyt_array(np.ndarray):
"""
An ndarray subclass that attaches a symbolic unit object to the array data.
Parameters
----------
input_array : iterable
A tuple, list, or array to attach units to
input_units : String unit name, unit symbol object, or astropy unit
The units of the array. Powers must be specified using python
syntax (cm**3, not cm^3).
registry : :class:`unyt.unit_registry.UnitRegistry`
The registry to create units from. If input_units is already associated
with a unit registry and this is specified, this will be used instead
of the registry associated with the unit object.
dtype : numpy dtype or dtype name
The dtype of the array data. Defaults to the dtype of the input data,
or, if none is found, uses np.float64
bypass_validation : boolean
If True, all input validation is skipped. Using this option may produce
corrupted, invalid units or array data, but can lead to significant
speedups in the input validation logic adds significant overhead. If
set, input_units *must* be a valid unit object. Defaults to False.
name : string
The name of the array. Defaults to None. This attribute does not propagate
through mathematical operations, but is preserved under indexing
and unit conversions.
Examples
--------
>>> from unyt import unyt_array
>>> a = unyt_array([1, 2, 3], 'cm')
>>> b = unyt_array([4, 5, 6], 'm')
>>> a + b
unyt_array([401., 502., 603.], 'cm')
>>> b + a
unyt_array([4.01, 5.02, 6.03], 'm')
NumPy ufuncs will pass through units where appropriate.
>>> from unyt import g, cm
>>> import numpy as np
>>> a = (np.arange(8) - 4)*g/cm**3
>>> np.abs(a)
unyt_array([4, 3, 2, 1, 0, 1, 2, 3], 'g/cm**3')
and strip them when it would be annoying to deal with them.
>>> np.log10(np.arange(8)+1)
array([0. , 0.30103 , 0.47712125, 0.60205999, 0.69897 ,
0.77815125, 0.84509804, 0.90308999])
"""
_ufunc_registry = {
add: _preserve_units,
subtract: _preserve_units,
multiply: _multiply_units,
divide: _divide_units,
logaddexp: _return_without_unit,
logaddexp2: _return_without_unit,
true_divide: _divide_units,
floor_divide: _divide_units,
negative: _passthrough_unit,
power: _power_unit,
remainder: _preserve_units,
mod: _preserve_units,
fmod: _preserve_units,
absolute: _passthrough_unit,
fabs: _passthrough_unit,
rint: _return_without_unit,
sign: _return_without_unit,
conj: _passthrough_unit,
exp: _return_without_unit,
exp2: _return_without_unit,
log: _return_without_unit,
log2: _return_without_unit,
log10: _return_without_unit,
expm1: _return_without_unit,
log1p: _return_without_unit,
sqrt: _sqrt_unit,
square: _square_unit,
reciprocal: _reciprocal_unit,
sin: _return_without_unit,
cos: _return_without_unit,
tan: _return_without_unit,
sinh: _return_without_unit,
cosh: _return_without_unit,
tanh: _return_without_unit,
arcsin: _return_without_unit,
arccos: _return_without_unit,
arctan: _return_without_unit,
arctan2: _arctan2_unit,
arcsinh: _return_without_unit,
arccosh: _return_without_unit,
arctanh: _return_without_unit,
hypot: _preserve_units,
deg2rad: _return_without_unit,
rad2deg: _return_without_unit,
bitwise_and: _bitop_units,
bitwise_or: _bitop_units,
bitwise_xor: _bitop_units,
invert: _invert_units,
left_shift: _bitop_units,
right_shift: _bitop_units,
greater: _comparison_unit,
greater_equal: _comparison_unit,
less: _comparison_unit,
less_equal: _comparison_unit,
not_equal: _comparison_unit,
equal: _comparison_unit,
logical_and: _comparison_unit,
logical_or: _comparison_unit,
logical_xor: _comparison_unit,
logical_not: _return_without_unit,
maximum: _preserve_units,
minimum: _preserve_units,
fmax: _preserve_units,
fmin: _preserve_units,
isreal: _return_without_unit,
iscomplex: _return_without_unit,
isfinite: _return_without_unit,
isinf: _return_without_unit,
isnan: _return_without_unit,
signbit: _return_without_unit,
copysign: _passthrough_unit,
nextafter: _preserve_units,
modf: _passthrough_unit,
ldexp: _bitop_units,
frexp: _return_without_unit,
floor: _passthrough_unit,
ceil: _passthrough_unit,
trunc: _passthrough_unit,
spacing: _passthrough_unit,
positive: _passthrough_unit,
divmod_: _passthrough_unit,
isnat: _return_without_unit,
heaviside: _preserve_units,
_ones_like: _preserve_units,
matmul: _multiply_units,
clip: _passthrough_unit,
}
__array_priority__ = 2.0
def __new__(
cls,
input_array,
units=None,
registry=None,
dtype=None,
bypass_validation=False,
input_units=None,
name=None,
):
# deprecate input_units in favor of units
if input_units is not None:
warnings.warn(
"input_units has been deprecated, please use units instead",
DeprecationWarning,
stacklevel=2,
)
if units is not None:
input_units = units
if bypass_validation is True:
if dtype is None:
dtype = input_array.dtype
obj = input_array.view(type=cls, dtype=dtype)
obj.units = input_units
if registry is not None:
obj.units.registry = registry
obj.name = name
return obj
if isinstance(input_array, unyt_array):
ret = input_array.view(cls)
if input_units is None:
if registry is None:
ret.units = input_array.units
else:
units = Unit(str(input_array.units), registry=registry)
ret.units = units
elif isinstance(input_units, Unit):
ret.units = input_units
else:
ret.units = Unit(input_units, registry=registry)
ret.name = name
return ret
elif isinstance(input_array, np.ndarray):
pass
elif _iterable(input_array) and input_array:
if isinstance(input_array[0], unyt_array):
return _coerce_iterable_units(input_array, registry)
# Input array is an already formed ndarray instance
# We first cast to be our class type
obj = np.asarray(input_array, dtype=dtype).view(cls)
# Check units type
if input_units is None:
# Nothing provided. Make dimensionless...
units = Unit()
elif isinstance(input_units, Unit):
if registry and registry is not input_units.registry:
units = Unit(str(input_units), registry=registry)
else:
units = input_units
else:
# units kwarg set, but it's not a Unit object.
# don't handle all the cases here, let the Unit class handle if
# it's a str.
units = Unit(input_units, registry=registry)
# Attach the units and name
obj.units = units
obj.name = name
return obj
def __repr__(self):
rep = super().__repr__()
units_repr = self.units.__repr__()
if "=" in rep:
return rep[:-1] + ", units='" + units_repr + "')"
else:
return rep[:-1] + ", '" + units_repr + "')"
def __str__(self):
return str(self.view(np.ndarray)) + " " + str(self.units)
def __format__(self, format_spec):
return f"{self.d.__format__(format_spec)} {self.units}"
#
# Start unit conversion methods
#
def convert_to_units(self, units, equivalence=None, **kwargs):
"""
Convert the array to the given units in-place.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions.
Parameters
----------
units : Unit object or string
The units you want to convert to.
equivalence : string, optional
The equivalence you wish to use. To see which equivalencies
are supported for this object, try the ``list_equivalencies``
method. Default: None
kwargs: optional
Any additional keyword arguments are supplied to the equivalence
Raises
------
If the provided unit does not have the same dimensions as the array
this will raise a UnitConversionError
Examples
--------
>>> from unyt import cm, km
>>> length = [3000, 2000, 1000]*cm
>>> length.convert_to_units('m')
>>> print(length)
[30. 20. 10.] m
"""
units = _sanitize_units_convert(units, self.units.registry)
if equivalence is None:
conv_data = _check_em_conversion(
self.units, units, registry=self.units.registry
)
if any(conv_data):
new_units, (conv_factor, offset) = _em_conversion(
self.units, conv_data, units
)
else:
new_units = units
(conv_factor, offset) = self.units.get_conversion_factor(
new_units, self.dtype
)
self.units = new_units
values = self.d
# if our dtype is an integer do the following somewhat awkward
# dance to change the dtype in-place. We can't use astype
# directly because that will create a copy and not update self
if self.dtype.kind in ("u", "i"):
# create a copy of the original data in floating point
# form, it's possible this may lose precision for very
# large integers
dsize = values.dtype.itemsize
if dsize == 1:
raise ValueError(
"Can't convert memory buffer in place. "
f"Input dtype ({self.dtype}) has a smaller itemsize than the "
"smallest floating point representation possible."
)
new_dtype = "f" + str(dsize)
large = LARGE_INPUT.get(dsize, 0)
if large and np.any(np.abs(values) > large):
warnings.warn(
f"Overflow encountered while converting to units '{new_units}'",
RuntimeWarning,
stacklevel=2,
)
float_values = values.astype(new_dtype)
# change the dtypes in-place, this does not change the
# underlying memory buffer
values.dtype = new_dtype
self.dtype = new_dtype
# actually fill in the new float values now that our
# dtype is correct
np.copyto(values, float_values)
values *= conv_factor
if offset:
np.subtract(values, offset, values)
else:
self.convert_to_equivalent(units, equivalence, **kwargs)
def convert_to_base(self, unit_system=None, equivalence=None, **kwargs):
"""
Convert the array in-place to the equivalent base units in
the specified unit system.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions.
Parameters
----------
unit_system : string, optional
The unit system to be used in the conversion. If not specified,
the configured base units are used (defaults to MKS).
equivalence : string, optional
The equivalence you wish to use. To see which equivalencies
are supported for this object, try the ``list_equivalencies``
method. Default: None
kwargs: optional
Any additional keyword arguments are supplied to the equivalence
Raises
------
If the provided unit does not have the same dimensions as the array
this will raise a UnitConversionError
Examples
--------
>>> from unyt import erg, s
>>> E = 2.5*erg/s
>>> E.convert_to_base("mks")
>>> E
unyt_quantity(2.5e-07, 'W')
"""
self.convert_to_units(
self.units.get_base_equivalent(unit_system),
equivalence=equivalence,
**kwargs,
)
def convert_to_cgs(self, equivalence=None, **kwargs):
"""
Convert the array and in-place to the equivalent cgs units.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions.
Parameters
----------
equivalence : string, optional
The equivalence you wish to use. To see which equivalencies
are supported for this object, try the ``list_equivalencies``
method. Default: None
kwargs: optional
Any additional keyword arguments are supplied to the equivalence
Raises
------
If the provided unit does not have the same dimensions as the array
this will raise a UnitConversionError
Examples
--------
>>> from unyt import Newton
>>> data = [1., 2., 3.]*Newton
>>> data.convert_to_cgs()
>>> data
unyt_array([100000., 200000., 300000.], 'dyn')
"""
self.convert_to_units(
self.units.get_cgs_equivalent(), equivalence=equivalence, **kwargs
)
def convert_to_mks(self, equivalence=None, **kwargs):
"""
Convert the array and units to the equivalent mks units.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions.
Parameters
----------
equivalence : string, optional
The equivalence you wish to use. To see which equivalencies
are supported for this object, try the ``list_equivalencies``
method. Default: None
kwargs: optional
Any additional keyword arguments are supplied to the equivalence
Raises
------
If the provided unit does not have the same dimensions as the array
this will raise a UnitConversionError
Examples
--------
>>> from unyt import dyne, erg
>>> data = [1., 2., 3.]*erg
>>> data
unyt_array([1., 2., 3.], 'erg')
>>> data.convert_to_mks()
>>> data
unyt_array([1.e-07, 2.e-07, 3.e-07], 'J')
"""
self.convert_to_units(self.units.get_mks_equivalent(), equivalence, **kwargs)
def in_units(self, units, equivalence=None, **kwargs):
"""
Creates a copy of this array with the data converted to the
supplied units, and returns it.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions.
Parameters
----------
units : Unit object or string
The units you want to get a new quantity in.
equivalence : string, optional
The equivalence you wish to use. To see which equivalencies
are supported for this object, try the ``list_equivalencies``
method. Default: None
kwargs: optional
Any additional keyword arguments are supplied to the
equivalence
Raises
------
If the provided unit does not have the same dimensions as the array
this will raise a UnitConversionError
Examples
--------
>>> from unyt import c, gram
>>> m = 10*gram
>>> E = m*c**2
>>> print(E.in_units('erg'))
8.987551787368176e+21 erg
>>> print(E.in_units('J'))
898755178736817.6 J
"""
units = _sanitize_units_convert(units, self.units.registry)
if equivalence is None:
conv_data = _check_em_conversion(
self.units, units, registry=self.units.registry
)
if any(conv_data):
new_units, (conversion_factor, offset) = _em_conversion(
self.units, conv_data, units
)
offset = 0
else:
new_units = units
(conversion_factor, offset) = self.units.get_conversion_factor(
new_units, self.dtype
)
dsize = max(2, self.dtype.itemsize)
if self.dtype.kind in ("u", "i"):
large = LARGE_INPUT.get(dsize, 0)
if large and np.any(np.abs(self.d) > large):
warnings.warn(
f"Overflow encountered while converting to units '{new_units}'",
RuntimeWarning,
stacklevel=2,
)
new_dtypekind = "c" if self.dtype.kind == "c" else "f"
new_dtype = np.dtype(new_dtypekind + str(dsize))
ret = np.asarray(self.ndview * conversion_factor, dtype=new_dtype)
if offset:
np.subtract(ret, offset, ret)
try:
new_array = type(self)(
ret, new_units, bypass_validation=True, name=self.name
)
except TypeError:
# subclasses might not take name as a kwarg
new_array = type(self)(ret, new_units, bypass_validation=True)
return new_array
else:
return self.to_equivalent(units, equivalence, **kwargs)
def to(self, units, equivalence=None, **kwargs):
"""
Creates a copy of this array with the data converted to the
supplied units, and returns it.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions.
.. note::
All additional keyword arguments are passed to the
equivalency, which should be used if that particular
equivalency requires them.
Parameters
----------
units : Unit object or string
The units you want to get a new quantity in.
equivalence : string, optional
The equivalence you wish to use. To see which
equivalencies are supported for this unitful
quantity, try the :meth:`list_equivalencies`
method. Default: None
kwargs: optional
Any additional keywoard arguments are supplied to the
equivalence
Raises
------
If the provided unit does not have the same dimensions as the array
this will raise a UnitConversionError
Examples
--------
>>> from unyt import c, gram
>>> m = 10*gram
>>> E = m*c**2
>>> print(E.to('erg'))
8.987551787368176e+21 erg
>>> print(E.to('J'))
898755178736817.6 J
"""
return self.in_units(units, equivalence=equivalence, **kwargs)
def to_value(self, units=None, equivalence=None, **kwargs):
"""
Creates a copy of this array with the data in the supplied
units, and returns it without units. Output is therefore a
bare NumPy array.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions.
.. note::
All additional keyword arguments are passed to the
equivalency, which should be used if that particular
equivalency requires them.
Parameters
----------
units : Unit object or string, optional
The units you want to get the bare quantity in. If not
specified, the value will be returned in the current units.
equivalence : string, optional
The equivalence you wish to use. To see which
equivalencies are supported for this unitful
quantity, try the :meth:`list_equivalencies`
method. Default: None
Examples
--------
>>> from unyt import km
>>> a = [3, 4, 5]*km
>>> print(a.to_value('cm'))
[300000. 400000. 500000.]
"""
if units is None:
v = self.value
else:
v = self.in_units(units, equivalence=equivalence, **kwargs).value
if isinstance(self, unyt_quantity):
return float(v)
else:
return v
def in_base(self, unit_system=None):
"""
Creates a copy of this array with the data in the specified unit
system, and returns it in that system's base units.
Parameters
----------
unit_system : string, optional