<<

unyt Documentation Release v2.8.0

The yt Project

Oct 05, 2020

Contents:

1 Installation 3 1.1 Stable release...... 3 1.2 From source...... 3 1.3 Running the tests...... 4

2 Working with unyt 5 2.1 Basic Usage...... 5 2.1.1 An Example from High School ...... 5 2.1.2 Arithmetic and units...... 6 2.1.3 Powers, Logarithms, Exponentials, and Trigonometric Functions...... 8 2.1.4 Printing Units...... 9 2.1.5 Simplifying Units...... 9 2.1.6 Checking Units...... 10 2.1.7 Units...... 10 2.2 Unit Conversions and Unit Systems...... 11 2.2.1 Converting Data to Arbitrary Units...... 11 2.2.2 Converting Units In-Place...... 11 2.2.3 Converting to MKS and CGS Base Units...... 12 2.2.4 Other Unit Systems...... 12 2.3 Equivalencies...... 15 2.4 Dealing with code that doesn’t use unyt ...... 16 2.4.1 Stripping units off of data...... 17 2.4.2 Applying units to data...... 17 2.4.3 Working with code that uses astropy.units ...... 18 2.4.4 Working with code that uses Pint ...... 18 2.5 User-Defined Units...... 19 2.6 Dealing with data types...... 19 2.7 Integrating unyt Into a Python Library...... 20 2.7.1 Unit registries...... 20 2.7.2 Custom Unit Systems...... 22 2.7.3 Writing Data with Units to Disk...... 22 2.7.4 Performance Considerations...... 25 2.8 unyt_array.name attribute...... 26 2.9 Plotting with Matplotlib...... 26

3 Listing of Units 31

i 4 Listing of Physical Constants 35

5 unyt package 37 5.1 Submodules...... 38 5.1.1 unyt.array module...... 38 5.1.2 unyt.dimensions module...... 56 5.1.3 unyt.equivalencies module...... 60 5.1.4 unyt.exceptions module...... 64 5.1.5 unyt.mpl_interface module...... 68 5.1.6 unyt.physical_constants module...... 68 5.1.7 unyt.testing module...... 69 5.1.8 unyt.unit_object module...... 70 5.1.9 unyt.unit_registry module...... 74 5.1.10 unyt.unit_symbols module...... 75 5.1.11 unyt.unit_systems module...... 77

6 Contributing 81 6.1 Code of Conduct...... 81 6.2 Types of Contributions...... 81 6.2.1 Report Bugs...... 81 6.2.2 Fix Bugs...... 82 6.2.3 Implement Features...... 82 6.2.4 Write Documentation...... 82 6.2.5 Submit Feedback...... 82 6.3 Get Started!...... 82 6.4 Testing unyt...... 83 6.5 Pull Request Guidelines...... 84 6.6 Deploying...... 84

7 Citing unyt 85

8 Credits 87 8.1 Contributors...... 87

9 History 89 9.1 2.8.0 (2020-10-05)...... 89 9.2 2.7.2 (2020-06-29)...... 89 9.3 2.7.1 (2020-02-17)...... 90 9.4 2.7.0 (2020-02-06)...... 90 9.5 2.6.0 (2020-01-22)...... 90 9.6 2.5.0 (2020-01-20)...... 90 9.7 2.4.1 (2020-01-10)...... 91 9.8 2.4.0 (2019-10-25)...... 91 9.9 2.3.1 (2019-08-21)...... 91 9.10 2.3.0 (2019-08-14)...... 91 9.11 2.2.2 (2019-07-03)...... 91 9.12 2.2.1 (2019-07-02)...... 91 9.13 2.2.0 (2019-04-03)...... 92 9.14 2.1.1 (2019-03-27)...... 92 9.15 2.1.0 (2019-03-26)...... 92 9.16 2.0.0 (2019-03-08)...... 92 9.17 1.0.7 (2018-08-13)...... 94 9.18 1.0.6 (2018-08-13)...... 94 9.19 1.0.5 (2018-08-03)...... 94 9.20 1.0.4 (2018-06-08)...... 95 ii 9.21 1.0.3 (2018-06-06)...... 95 9.22 1.0.2 (2018-06-06)...... 95 9.23 1.0.1 (2018-05-24)...... 95 9.24 1.0.0 (2018-05-24)...... 95

10 Indices and tables 97

Python Module Index 99

Index 101

iii iv unyt Documentation, Release v2.8.0

This is the documentation for unyt (pronounced like “unit”). This package provides a python library for working with data that has physical units. It was originally developed as part of The yt Project but was split out as an independent project so that other Python projects can easily make use of it. The unyt library defines the unyt.array.unyt_array and unyt.array.unyt_quantity classes for han- dling arrays and scalars with units, respectively. In addition, unyt provides a number of predefined units and physical constants that can be directly imported from from the unyt namespace:

>>> from unyt import G, Mearth, Rearth >>> v_esc=(2 *G*Mearth/Rearth)**(1./2) >>> print(v_esc.to('km/s')) 11.254544657958482 km/s

Contents: 1 unyt Documentation, Release v2.8.0

2 Contents: CHAPTER 1

Installation

1.1 Stable release

To install unyt, run this command in your terminal:

$ pip install unyt

If you have a C compiler available, we also suggest installing fastcache, which will improve the performance of SymPy. If you don’t have pip installed, this Python installation guide can guide you through the process. If you use conda, unyt is available via conda-forge:

$ conda install -c conda-forge unyt

It is not necessary to explicitly install fastcache if you use conda because it will be installed automatically as a dependency of SymPy.

1.2 From source

The sources for unyt can be downloaded from the Github repo. You can either clone the public repository:

$ git clone git://github.com/yt-project/unyt

Or download the tarball:

$ curl -OL https://github.com/yt-project/unyt/tarball/master

Once you have a copy of the source, you can install it by navigating to the root of the installation and issuing the following command:

3 unyt Documentation, Release v2.8.0

$ pip install .

If you would like to make an “editable” where you can directly edit the Python source files of the installed version of unyt, then you can do:

$ pip install -e .

1.3 Running the tests

You can check that unyt is working properly by running the unit tests on your intalled copy:

>>> import unyt >>> unyt.test()

4 Chapter 1. Installation CHAPTER 2

Working with unyt

2.1 Basic Usage

To use unyt in a project:

>>> import unyt

The top-level unyt namespace defines both a number of useful functions as well as a number of units and physical constants populated from the unyt.unit_symbols and unyt.physical_constants namespaces you can use to attach units to NumPy arrays and other common python data container types like list and tuple. For an exhaustive listing of units and physical constants defined in unyt, see Listing of Units.

2.1.1 An Example from High School Physics

To see how you might use unyt to solve a problem where units might be a headache, let’s estimate the orbital periods of Jupiter’s Galilean moons, assuming they have circular orbits and their are negligible compared to Jupiter. Under these assumptions, the orbital period is

(︂ 푟3 )︂1/2 푇 = 2휋 . 퐺푀

For this exercise let’s calculate the orbital period in days. While it’s possible to do this using plain old floating point numbers (you probably had to do something similar on a calculator in a high school physics class, looking up and plugging in conversion factors by hand), it’s much easier to do this sort of thing symbolically and let unyt handle the unit conversions. To do this we’ll need to know the of Jupiter (fortunately that is built into unyt) and the semimajor axis of the orbits of Jupiter’s moons, which we can look up from Wikipedia and enter by hand:

>>> from unyt import Mjup, G, AU >>> from math import pi ... (continues on next page)

5 unyt Documentation, Release v2.8.0

(continued from previous page) >>> moons=['Io','Europa','Ganymede','Callisto'] >>> semimajor_axis=[.002819,.0044856,.00715526,.01258513] *AU ... >>> period=2 *pi*(semimajor_axis**3/(G*Mjup))**0.5 >>> period= period.to('d') ... >>> for moon, period in zip(moons, period): ... print('{}: {:04.2f}'.format(moon, period)) Io: 1.77 day Europa: 3.55 day Ganymede: 7.15 day Callisto: 16.69 day

Let’s break up this example into a few components so you can see what’s going on. First, we import the unit symbols we need from the unyt namespace:

>>> from unyt import Mjup, G, km

The unyt namespace has a large number of units and physical constants you can import to apply units to data in your own code. You can see how that works in the example:

>>> semimajor_axis=[.002819,.0044856,.00715526,.01258513] *AU >>> semimajor_axis unyt_array([0.002819 , 0.0044856 , 0.00715526, 0.01258513], 'AU')

By multiplying by km, we converted the python list into a unyt.unyt_array instance. This is a class that’s built into unyt, has units attached to it, and knows how to convert itself into different dimensionally equivalent units:

>>> semimajor_axis.value array([0.002819 , 0.0044856 , 0.00715526, 0.01258513]) >>> semimajor_axis.units AU >>> print(semimajor_axis.to('km')) [ 421716.39764641 671036.20903964 1070411.66066813 1882708.6511216 ] km

Next, we calculated the orbital period by translating the orbital period formula to Python and then converting the answer to the units we want in the end, days:

>>> period=2 *pi*(semimajor_axis**3/(G*Mjup))**0.5 >>> period unyt_array([ 152864.59689789, 306828.08975058, 618162.17963649, 1441952.18891597], 's') >>> period.to('d') unyt_array([ 1.76926617, 3.55125104, 7.15465486, 16.68926145], 'day')

Note that we haven’t added any conversion factors between different units, that’s all handled internally by unyt. Also note how the unyt_array.to method was able to automatically handle the conversion from to days and how the shorthand "d" was automatically interpreted as "day".

2.1.2 Arithmetic and units

The real of working with unyt is its ability to add, subtract, multiply, and divide quantities and arrays with units in mathematical formulas while automatically handling unit conversions and detecting when you have made a mistake in your units in a mathematical formula. To see what I mean by that, let’s take a look at the following examples:

6 Chapter 2. Working with unyt unyt Documentation, Release v2.8.0

>>> from unyt import cm, m, ft, yard >>> print(3.*cm+ 4. *m- 5. *ft+ 6. *yard) 799.24 cm

Despite the fact that the four unit symbols used in the above example correspond to four different units, unyt is able to automatically convert the value of all three units into a common unit and return the result in those units. Note that for expressions where the return units are ambiguous, unyt always returns data in the units of the leftmost object in an expression:

>>> print(4*m+3 *cm-5 *ft+6 *yard) 7.9924 m

One can also form more complex units out of atomic unit symbols. For example, here is how we’d create an array with units of meters per and print out the values in the array in miles per hour:

>>> from unyt import m, s >>> =[20., 22., 25.] *m/s >>> print(velocities.to('mile/hr')) [44.73872584 49.21259843 55.9234073 ] mile/hr

Similarly one can multiply two units together to create new compound units:

>>> from unyt import N, m >>> =3 *N * 4*m >>> print(energy) 12 N*m >>> print(energy.to('erg')) 120000000.0 erg

In general, one can multiply or divide by an arbitrary rational power of a unit symbol. Most commonly this shows up in mathematical formulas in terms of square roots. For example, let’s calculate the gravitational free-fall for a person to fall from the surface of the Earth through to a hole dug all the way to the center of the Earth. It turns out that this time is given by: √︂ 3휋 푡 = ff 32퐺휌 where 휌 is the average of the Earth.

>>> from unyt import G, Mearth, Rearth >>> from math import pi >>> import numpy as np ... >>> rho= Mearth/(4./3 * pi* Rearth**3) >>> print(rho.to('g/cm**3')) 5.581225129861083 g/cm**3 >>> tff= np.sqrt(3 *pi/(32*G*rho)) >>> print(tff.to('min')) 14.820022043294829 min

If you make a mistake by adding two things that have different dimensions, unyt will raise an error to let you know that you have a bug in your code:

>>> from unyt import kg, m >>> 3*kg+5 *m # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... (continues on next page)

2.1. Basic Usage 7 unyt Documentation, Release v2.8.0

(continued from previous page) unyt.exceptions.UnitOperationError: The operator for unyt_arrays with units "kg" (dimensions "(mass)") and "m" (dimensions "()") is not well defined.

while this example is trivial when one writes more complicated formulae it can be easy to accidentally write expres- sions that are not dimensionally sound. Sometimes this can be annoying to deal with, particularly if one is mixing data that has units attached with data from some outside source with no units. To quickly patch over this lack of unit metadata (which could be applied by explicitly attaching units at I/O time), one can use the units attribute of the unyt.unyt_array class to quickly apply units to a scalar, list, or array:

>>> from unyt import cm, s >>> velocities=[10, 20, 30] * cm/s >>> velocities+ 12 # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE +IGNORE_EXCEPTION_

˓→DETAIL Traceback (most recent call last): ... unyt.exceptions.UnitOperationError: The operator for unyt_arrays with units "cm/s" (dimensions "(length)/(time)") and "dimensionless" (dimensions "1") is not well defined. >>> velocities+ 12 *velocities.units unyt_array([22, 32, 42], 'cm/s')

2.1.3 Powers, Logarithms, Exponentials, and Trigonometric Functions

The unyt library represents powers using standard python syntax. This means you must use ** and not ^, even when writing a unit as a string:

>>> from unyt import kg, m >>> print((10.*kg/m**3).to('g/cm**3')) 0.01 g/cm**3

Formally it does not make sense to exponentiate, take the logarithm of, or apply a transcendental function to a quantity with units. However, the unyt library makes the practical affordance to allow this, simply ignoring the units present and returning a result without units. This makes it easy to work with data that has units both in linear space and in log space:

>>> from unyt import g, cm >>> import numpy as np >>> print(np.log10(1e-23*g/cm**3)) -23.0

The one exception to this rule is for trigonometric functions applied to data with angular units:

>>> from unyt import degree, radian >>> import numpy as np >>> np.sin(np.pi/4*radian) array(0.70710678) >>> np.sin(45.*degree) array(0.70710678)

8 Chapter 2. Working with unyt unyt Documentation, Release v2.8.0

Logarithmic Quantities and Units

The logarithmic quantities level-of-power and level-of-field and the units neper and bel are supported. In the next example, we represent the power , p, as a logarithmic quantity at reference level, p_ref, in the units decibel.

>>> import numpy as np >>> from unyt import dB, mW >>> dB.dimensions (logarithmic) >>> p=[1, 100] *mW >>> p_ref=1 *mW >>> level_of_power= 10 *np.log10(p/p_ref)*dB >>> level_of_power unyt_array([ 0., 20.], 'dB')

You can convert the logarithmic quantity back to physical units through exponentiation, just remember to remove the units using the unyt_array.v property.

>>> 10**(level_of_power.v/10)*p_ref unyt_array([ 1., 100.], 'mW')

2.1.4 Printing Units

The print formatting of unyt_array can be controlled identically to numpy arrays, using numpy. setprintoptions:

>>> import numpy as np >>> import unyt asu ... >>> np.set_printoptions(precision=4) >>> print([1.123456789]*u.km) [1.1235] km >>> np.set_printoptions(precision=8)

Print a LATEX representation of a set of units using the unyt.unit_object.Unit. latex_representation() function or unyt.unit_object.Unit.latex_repr attribute:

>>> from unyt import g, cm >>> (g/cm**3).units.latex_representation() '\\frac{\\rm{g}}{\\rm{cm}^{3}}' >>> (g/cm**3).units.latex_repr '\\frac{\\rm{g}}{\\rm{cm}^{3}}'

2.1.5 Simplifying Units

Unit expressions can often be simplified to cancel pairs of factors with compatible dimensions. For example, we can form a unit with dimensions of length by dividing a unit with dimensions of length squared by another unit with dimensions of length:

>>> from unyt import m, cm >>> m**2/cm m**2/cm

2.1. Basic Usage 9 unyt Documentation, Release v2.8.0

The Unit class has a simplify() method that we can call to create a new unit object to that includes the dimen- sionless ratio m/cm as a constant coefficient:

>>> (m**2/cm).simplify() 100*m

This will also work for units that are the reciprocals of each other, for example:

>>> from unyt import s, Hz >>> (s*Hz).simplify() (dimensionless)

Products and quotients of unit objects will not be simplified unless simplify() is called explicitly. However, products and quotients of arrays and quantities will be simplified to make interactive work more intuitive:

>>> from unyt import erg, minute, hour >>> power=[20, 40, 80] * erg/ minute >>> elapsed_time=3 *hour >>> print(power*elapsed_time) [ 3600. 7200. 14400.] erg

2.1.6 Checking Units

If you write a function that accepts data with units as an argument or returns data with units, you can ensure the dimensional correctness of the inputs or outputs using the @accepts and @returns decorators:

>>> from unyt.dimensions import length, time >>> from unyt import accepts, returns >>> import unyt asu >>> @returns(length) ... @accepts(a=time, v=length/time) ... def foo(a, v): ... return a * v ... >>> res= foo(a=2 * u.s, v=3 * u.m/u.s) >>> print(res) 6 m

Note: Using these decorators may incur some performance overhead, especially for small arrays.

2.1.7 Temperature Units

The temperature unit degree Celsius has the symbol °C, but since the degree character is an invalid Python identifier, unyt uses the symbol degC. Printing a degree Celsius quantity will show the correct symbol.

>>> from unyt import degC >>> Ta= 23 *degC >>> print(Ta) 23 °C

The degC symbol has alternative names degree_Celsius, Celsius and °C.

10 Chapter 2. Working with unyt unyt Documentation, Release v2.8.0

>>> from unyt import degree_Celsius, unyt_array >>> Ta= 23 *degree_Celsius >>> print(Ta) 23 °C >>> Ta= unyt_array([-40, 23, 70],'°C') >>> print(Ta) [-40 23 70] °C

These comments also apply to degree Fahrenheit. Performing arithmetic with temperature quantities can be ambiguous. To clarify intent, unyt has the convenience units delta_degC and delta_degF.

>>> from unyt import degC, delta_degC, V >>> t1= 23 *degC >>> t2=1 *delta_degC >>> print(t1+ t2) 24 °C >>> print(t2- t1) -22 °C >>> tempco= 10.0 *V/delta_degC >>> print(tempco*2*delta_degC) 20.0 V

2.2 Unit Conversions and Unit Systems

2.2.1 Converting Data to Arbitrary Units

If you have some data that you want to convert to a different set of units and you know which units you would like to convert it to, you can make use of the unyt_array.to function:

>>> from unyt import mile >>> (1.0*mile).to('ft') unyt_quantity(5280., 'ft')

If you try to convert to a unit with different dimensions, unyt will raise an error:

>>> from unyt import mile >>> (1.0*mile).to('lb') # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE +IGNORE_EXCEPTION_ ˓→DETAIL Traceback (most recent call last): ... unyt.exceptions.UnitConversionError: Cannot convert between 'mile' (dim '(length)') and 'lb' (dim '(mass)').

While we recommend using unyt_array.to in most cases to convert arrays or quantities to different units, if you would like to explicitly emphasize that this operation has to do with units, we also provide the more verbose name unyt_array.in_units which behaves identically to unyt_array.to.

2.2.2 Converting Units In-Place

The unyt_array.to method makes a copy of the array data. For most cases this is fine, but when dealing with big arrays, or when performance is a concern, it sometimes is preferable to convert the data in an array in-place, without copying the data to a new array. This can be accomplished with the unyt_array.convert_to_units function:

2.2. Unit Conversions and Unit Systems 11 unyt Documentation, Release v2.8.0

>>> from unyt import mile >>> data=[1., 2., 3.] *mile >>> data unyt_array([1., 2., 3.], 'mile') >>> data.convert_to_units('km') >>> data unyt_array([1.609344, 3.218688, 4.828032], 'km')

2.2.3 Converting to MKS and CGS Base Units

If you don’t necessarily know the units you want to convert data to ahead of time, it’s often convenient to spec- ify a unit system to convert to. The unyt_array has built-in conversion methods for the two most popular unit systems, MKS (meter kilogram second) and CGS (centimeter gram second). For CGS these are unyt_array. in_cgs and unyt_array.convert_to_cgs. These functions create a new copy of an array in CGS units and convert an array in-place to CGS. respectively. For MKS, there are the unyt_array.in_mks and unyt_array. convert_to_mks methods, which play analogous roles. See below for details on CGS and MKS electromagnetic units.

2.2.4 Other Unit Systems

The unyt library currently has built-in support for a number of unit systems, as detailed in the table below. Note that all unit systems currently use “radian” as the base angle unit. If a unit system in the table below has “Other Units” specified, this is a mapping from dimension to a unit name. These units override the unit system’s default unit for that dimension. If no unit is explicitly specified of a dimension then the for that dimension is calculated at runtime by combining the base units for the unit system into the appropriate dimension.

12 Chapter 2. Working with unyt unyt Documentation, Release v2.8.0

Unit system Base Units Other Units cgs cm, g, s • Energy: erg • Specific Energy: erg/g • : dyne/cm**2 • : dyne • Power: erg/s • Magnetic : G • Charge: esu • Current: statA

mks m, kg, s • Energy: J • Specific Energy: J/kg • Pressure: Pa • Force: N • Power: W • : T • Charge: C

imperial ft, lb, s • Energy: ft*lbf • Temperature: R • Pressure: lbf/ft**2 • Force: lbf • Power: hp

galactic kpc, Msun, kyr • Energy: kev • Magnetic Field: uG

solar AU, Mearth, yr

Note that in MKS units the current unit, Ampere, is a base unit in the unit system. In CGS units the electromagnetic units like Gauss and statA are decomposable in terms of the base mass, length, and time units in the unit system. For this reason quantities defined in E&M units in CGS units are not readily convertible to MKS units and vice verse since the units are not dimensionally equivalent. The unyt library does have limited support for converting electromagnetic units between MKS and CGS, however only simple conversions of data with a single specific unit are supported and no conversions are allowed for complex combinations of units. For example converting between Gauss and Tesla is supported:

>>> from unyt import T >>> (1.0*T).to('G') unyt_quantity(10000., 'G')

But converting a more complicated compound unit will raise an error:

>>> from unyt import C, T, V >>> (1.0*C*T*V).in_cgs() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE +IGNORE_ ˓→EXCEPTION_DETAIL Traceback (most recent call last): ... unyt.exceptions.UnitsNotReducible: The unit "C*T*V" (dimensions "(length)**2*(mass)**2/((current_mks)*(time)**4)") cannot be reduced to an expression within the cgs system of units.

2.2. Unit Conversions and Unit Systems 13 unyt Documentation, Release v2.8.0

If you need to work with complex expressions involving electromagnetic units, we suggest sticking to either CGS or SI units for the full calculation. There is no general way to convert an arbitrary quantity between CGS and SI units if the quantity involves electromagnetic units. Instead, it is necessary to do the conversion on the equations under consideration, and then recompute the necessary quantity in the transformed set of equations. This requires understanding the context for a calculation, which unfortunately is beyond the scope of a library like unyt. You can convert data to a unit system unyt knows about using the unyt_array.in_base and unyt_array. convert_to_base methods:

>>> from unyt import g, cm, horsepower >>> (1e-9*g/cm**2).in_base('galactic') unyt_quantity(4.78843804, 'Msun/kpc**2') >>> data=[100., 500., 700.] *horsepower >>> data unyt_array([100., 500., 700.], 'hp') >>> data.convert_to_base('mks') >>> data unyt_array([ 74569.98715823, 372849.93579114, 521989.91010759], 'W')

Defining and Using New Unit Systems

To define a new custom unit system, one need only create a new instance of the unyt.UnitSystem class. The class initializer accepts a set of base units to define the unit system. If you would like to additionally customize any derived units in the unit system, you can do this using item setting. As an example, let’s define an atomic unit system based on typical scales for atoms and molecules:

>>> from unyt import UnitSystem >>> atomic_unit_system= UnitSystem('atomic','nm','mp','fs','nK','') >>> atomic_unit_system['energy']='eV' >>> atomic_unit_system atomic Unit System Base Units: length: nm mass: mp time: fs temperature: nK angle: rad current_mks: A luminous_intensity: cd logarithmic: Np Other Units: energy: eV >>> print(atomic_unit_system) atomic >>> atomic_unit_system['number_density'] nm**(-3) >>> atomic_unit_system['angular_momentum'] mp*nm**2/fs

It is also legal to define a unit system using unyt.Unit instances:

>>> from unyt.unit_symbols import Msun, second, megaparsec >>> UnitSystem('cosmological', megaparsec, Msun, second) cosmological Unit System Base Units: length: Mpc (continues on next page)

14 Chapter 2. Working with unyt unyt Documentation, Release v2.8.0

(continued from previous page) mass: Msun time: s temperature: K angle: rad current_mks: A luminous_intensity: cd logarithmic: Np Other Units:

Or with a quantity:

>>> UnitSystem('quasmological',3 *megaparsec,.8 *Msun, 42*second) quasmological Unit System Base Units: length: 3*Mpc mass: 0.8*Msun time: 42*s temperature: K angle: rad current_mks: A luminous_intensity: cd logarithmic: Np Other Units:

Once you have defined a new unit system that will register the new system with a global registry of unit systems known to the unyt library. That means you will immediately be able to use it just like the built-in unit systems:

>>> from unyt import W >>> (1.0*W).in_base('atomic') unyt_quantity(0.59746607, 'mp*nm**2/fs**3')

If you would like your unit system to include an MKS current unit (e.g. something that is directly convertible to the MKS Ampere unit), then specify a current_mks_unit in the UnitSystem initializer.

2.3 Equivalencies

An equivalency is a way to define a mapping to convert from one unit to another even if the two units are not di- mensionally equivalent. This usually involves some sort of shorthand or heuristic understanding of the problem under consideration. Only use one of these equivalencies if it makes sense to use it for the problem you are working on. The unyt library implements the following equivalencies:

• "thermal": conversions between temperature and energy (퐸 = 푘퐵푇 ) • "spectral": conversions between wavelength, spatial , frequency, and energy for photons (퐸 = ℎ휈 = ℎ푐/휆, 푐 = 휆휈) • "mass_energy": conversions between mass and energy (퐸 = 푚푐2) • "lorentz": conversions between and Lorentz factor (훾 = 1/√︀1 − (푣/푐)2) 2 • "schwarzschild": conversions between mass and (푅푆 = 2퐺푀/푐 ) • "compton": conversions between mass and (휆 = ℎ/푚푐) You can convert data to a specific set of units via an equivalency appropriate for the units of the data. To see the equivalencies that are available for an array, use the unit_array.list_equivalencies method:

2.3. Equivalencies 15 unyt Documentation, Release v2.8.0

>>> from unyt import gram, km >>> gram.list_equivalencies() mass_energy: mass <-> energy schwarzschild: mass <-> length compton: mass <-> length >>> km.list_equivalencies() spectral: length <-> spatial_frequency <-> frequency <-> energy schwarzschild: mass <-> length compton: mass <-> length

All of the unit conversion methods described above have an equivalence keyword argument that allows one to op- tionally specify an equivalence to use for the unit conversion operation. For example, let’s use the schwarzschild equivalence to calculate the mass of a with a radius of one AU:

>>> from unyt import AU >>> (1.0*AU).to('Msun', equivalence='schwarzschild') unyt_quantity(50656851.7815179, 'Msun')

Both the methods that convert data in-place and the ones that return a copy support optionally specifying equiva- lence. In addition to the methods described above, unyt also supplies two more conversion methods that require an equivalence to be specified: unyt_array.to_equivalent and unyt_array.convert_to_equivalent. These are identical to their counterparts described above, except they equivalence is a required positional argument to the function rather than an optional keyword argument. Use these functions when you want to emphasize that an equivalence is being used. If the equivalence has optional keyword arguments, these can be passed to the unit conversion function. For example, here’s an example where we specify a custom mean molecular weight (mu) for the number_density equivalence:

>>> from unyt import g, cm >>> rho= 1e-23 * g/cm**3 >>> rho.to('cm**-3', equivalence='number_density', mu=1.4) unyt_quantity(4.26761476, 'cm**(-3)')

For full API documentation and an autogenerated listing of the built-in equivalencies in unyt as well as a short usage example for each, see the unyt.equivalencies API listing.

2.4 Dealing with code that doesn’t use unyt

Optimally, a function will work the same irrespective of whether the data passed in has units attached or not:

>>> from unyt import cm >>> def square(x): ... return x**2 >>> print(square(3.)) 9.0 >>> print(square(3.*cm)) 9.0 cm**2

However in the real world that is not always the case. In this section we describe strategies for dealing with that situation.

16 Chapter 2. Working with unyt unyt Documentation, Release v2.8.0

2.4.1 Stripping units off of data

The unyt library provides a number of ways to convert unyt_quantity instances into floats and unyt_array instances into numpy arrays. These methods either return a copy of the data as a numpy array or return a view onto the underlying array data owned by a unyt_array instance. To obtain a new array containing a copy of the original data, use either the unyt_array.to_value function or the unyt_array.value or unyt_array.v properties. All of these are equivalent to passing a unyt_array to the numpy.array() function:

>>> from unyt import g >>> import numpy as np >>> data=[1., 2., 3.] *g >>> data unyt_array([1., 2., 3.], 'g') >>> np.array(data) array([1., 2., 3.]) >>> data.to_value('kg') array([0.001, 0.002, 0.003]) >>> data.value array([1., 2., 3.]) >>> data.v array([1., 2., 3.])

Similarly, to obtain a ndarray containing a view of the data in the original array, use either the unyt_array.ndview or the unyt_array.d properties:

>>> data.view(np.ndarray) array([1., 2., 3.]) >>> data.ndview array([1., 2., 3.]) >>> data.d array([1., 2., 3.])

2.4.2 Applying units to data

Note: A numpy array that shares memory with another numpy array points to the array that owns the data with the base attribute. If arr1.base is arr2 is True then arr1 is a view onto arr2 and arr2.base will be None.

When you create a unyt_array instance from a numpy array, unyt will create a copy of the original array:

>>> from unyt import g >>> data= np.random.random((100, 100)) >>> data_with_units= data *g >>> data_with_units.base is data False

If you would like to create a view rather than a copy, you can apply units like this:

>>> from unyt import unyt_array >>> data_with_units= unyt_array(data, g) >>> data_with_units.base is data True

2.4. Dealing with code that doesn’t use unyt 17 unyt Documentation, Release v2.8.0

Any set of units can be used for either of these operations. For example, if you already have an existing array, you could do this to create a new array with the same units:

>>> more_data=[4,5,6] *data_with_units.units >>> more_data unyt_array([4, 5, 6], 'g')

2.4.3 Working with code that uses astropy.units

The unyt library can convert data contained inside of an Astropy Quantity instance. It can also produce a Quantity from an existing unyt_array instance. To convert data from astropy.units to unyt use the unyt_array.from_astropy function:

>>> from astropy.units import km >>> from unyt import unyt_quantity >>> unyt_quantity.from_astropy(km) unyt_quantity(1., 'km') >>> a=[1,2,3] *km >>> a >>> unyt_array.from_astropy(a) unyt_array([1., 2., 3.], 'km')

To convert data to astropy.units use the unyt_array.to_astropy method:

>>> from unyt import g, cm >>> data=[3,4,5] *g/cm**3 >>> data.to_astropy() >>> (4*cm).to_astropy()

2.4.4 Working with code that uses Pint

The unyt library can also convert data contained in Pint Quantity instances. To convert data from Pint to unyt, use the unyt_array.from_pint function:

>>> from pint import UnitRegistry >>> import numpy as np >>> ureg= UnitRegistry() >>> a= np.arange(4) >>> b= ureg.Quantity(a,"erg/cm **3") >>> b >>> c= unyt_array.from_pint(b) >>> c unyt_array([0, 1, 2, 3], 'erg/cm**3')

And to convert data contained in a unyt_array instance, use the unyt_array.to_pint method:

>>> from unyt import cm, s >>> a=4 *cm**2/s >>> print(a) 4 cm**2/s (continues on next page)

18 Chapter 2. Working with unyt unyt Documentation, Release v2.8.0

(continued from previous page) >>> a.to_pint() >>> b=[1,2,3] *cm >>> b.to_pint()

2.5 User-Defined Units

Often it is convenient to define new custom units. This can happen when you need to make use of a unit that the unyt library does not have a definition for already. It can also happen when dealing with data that uses a custom unit system or when writing software that needs to deal with such data in a flexible way, particularly when the units might change from dataset to dataset. This comes up often when modeling a physical system since it is often convenient to rescale data from a physical unit system to an internal “code” unit system in which the values of the variables under consideration are close to unity. This approach can help minimize floating point round-off error but is often done for convenience or to non-dimensionalize the problem under consideration. The unyt library provides two approaches for dealing with this problem. For more toy one-off use-cases, we suggest using unyt.define_unit which allows defining a new unit name in the global, default unit system that unyt ships with by default. This function makes it possible to easily define a new unit that is unknown to the unyt library:

>>> import unyt asu >>> two_weeks= 14.0 *u.day >>> one_day= 1.0 *u.day >>> u.define_unit("fortnight", two_weeks) >>> print((3*u.fortnight)/one_day) 42.0 dimensionless

This is primarily useful for one-off definitions of units that the unyt library does not already have predefined. For more complex uses cases that need more flexibility, it is possible to use a custom unit system by ensuring that the data you are working with makes use of a UnitRegistry customized for your use case, as described below.

2.6 Dealing with data types

The unyt library supports creating unyt.unyt_array and unyt.unyt_quantity instances with arbitrary integer or floating point data types:

>>> import numpy as np >>> from unyt import km ... >>> int_data=[1,2,3] *km >>> int_data unyt_array([1, 2, 3], 'km') >>> float32_data= np.array([1,2,3], dtype='float32') *km >>> float32_data unyt_array([1., 2., 3.], dtype=float32, units='km')

The dtype of a unyt_array instance created by multiplying an iterable by a unit will be the same as passing the iterable to np.array(). You can also manually specify the dtype by calling np.array() yourself or by using the unyt_array initializer directly:

2.5. User-Defined Units 19 unyt Documentation, Release v2.8.0

>>> np.array([1,2,3], dtype='float64') *km unyt_array([1., 2., 3.], 'km')

Operations that convert an integer array to a new unit will convert the array to the floating point type with an equivalent . For example, Calling in_units on a 32 bit integer array with units of kilometers will return a 32 bit floating point array.

>>> data= np.array([1,2,3], dtype='int32') *km >>> data.in_units('mile') unyt_array([0.62137121, 1.24274242, 1.86411357], dtype=float32, units='mile')

In-place operations will also mutate the dtype from float to integer in these cases, again in away that will preserve the byte size of the data.

>>> data.convert_to_units('mile') >>> data unyt_array([0.62137121, 1.24274242, 1.86411357], dtype=float32, units='mile')

It is possible that arrays containing large integers (16777217 for 32 bit and 9007199254740993 for 64 bit) will lose precision when converting data to a different unit. In these cases a warning message will be printed.

2.7 Integrating unyt Into a Python Library

The unyt library began life as the unit system for the yt data analysis and visualization package, in the form of yt. units. In this role, unyt was deeply integrated into a larger python library. Due to these origins, it is straightforward to build applications that ensure unit consistency by making use of unyt. Below we discuss a few topics that most often come up when integrating unyt into a new or existing Python library.

2.7.1 Unit registries

It is also possible to define a custom database of units completely independent of the global default unit database exposed by the unyt namespace or to create namespaces in your own package that expose listings of units. In these cases it becomes important to understand how unyt stores unit metadata in an internal database, how to add custom entries to the database, how to modify them, and how to persist custom units. In practice, the unit metadata for a unit object is contained in an instance of the UnitRegistry class. Every Unit instance contains a reference to a UnitRegistry instance:

>>> from unyt import g >>> g.registry # doctest: +ELLIPSIS

All the unit objects in the unyt namespace make use of the default unit registry, importable as unyt. unit_registry.default_unit_registry. This registry object contains all of the real-world physical units that the unyt library ships with out of the box. The unit registry itself contains a look-up table that maps from unit names to the metadata necessary to construct a unit. Note that the unit registry only contains metadata for “base” units, and not, for example, SI-prefixed units like centimeter of kilogram, it will instead only contain entries for meter and gram. Sometimes it is convenient to create a unit registry containing new units that are not available in the default unit registry. A common example would be adding a code_length unit that corresponds to the scaling to from physical to an internal unit system. In practice, this value is arbitrary, but will be fixed for a given problem. Let’s create

20 Chapter 2. Working with unyt unyt Documentation, Release v2.8.0

a unit registry and a custom "code_length" unit to it, and then create a "code_length" unit and a quantity with units of "code_length". For the sake of example, let’s set the value of "code_length" equal to 10 meters.

>>> from unyt import UnitRegistry, Unit >>> from unyt.dimensions import length >>> reg= UnitRegistry() >>> reg.add("code_length", base_value=10.0, dimensions=length, ... tex_repr=r"\rm{Code Length}") >>> 'code_length' in reg True >>> u= Unit('code_length', registry=reg) >>> data=3 *u >>> print(data) 3 code_length

As you can see, you can test whether a unit name is in a registry using the Python in operator. In an application that depends on unyt, it is often convenient to define methods or functions to automatically attach the correct unit registry to unit objects associated with an object. For example, consider a Simulation class. Let’s give this class two methods named array and quantity to create new unyt_array and unyt_quantity instances, respectively:

>>> class Simulation(object): ... def __init__(self, registry): ... self.registry= registry ...... def array(self, value, units): ... return unyt_array(value, units, registry=self.registry) ...... def quantity(self, value, units): ... return unyt_quantity(value, units, registry=self.registry) ... >>> registry= UnitRegistry() >>> registry.add("code_length", base_value=3.2, dimensions=length) >>> s= Simulation(registry) >>> s.array([1,2,3],'code_length') unyt_array([1, 2, 3], 'code_length')

We can create an array with "code_length" here because s.registry, the UnitRegistry instance associ- ated with our Simulation instance has a "code_length" unit defined. As for arrays with different units, for operations between arrays created with different unit registries, the result of the operation will use the same unit registry as the leftmost unit. This can sometimes lead to surprising behaviors where data will seem to “forget” about custom units. In this situation it is important to make sure ahead of time that all data are created with units using the same unit registry. If for some reason that is not possible (for example, when comparing data from two different simulations with different internal units), then care must be taken when working with custom units. To avoid these sorts of ambiguities it is best to do work in physical units as much as possible. When writing tests, it is convenient to use unyt.testing. In particular, assert_allclose_units can be used to check for floating-point equality.

>>> from unyt import assert_allclose_units, m >>> import numpy as np >>> actual=[1e-5, 1e-3, 1e-1] * m >>> desired= actual.to("cm") >>> assert_allclose_units(actual, desired)

2.7. Integrating unyt Into a Python Library 21 unyt Documentation, Release v2.8.0

2.7.2 Custom Unit Systems

By default unyt uses the SI MKS unit system. However, libraries can create a unit registry using another unit system to expose that unit system to their users by creating a unit registry with a custom unit system. For example, to make CGS units the default unit for all operations, one might modify the Simulation class defined above like so:

>>> class Simulation(object): ... def __init__(self, registry): ... self.registry= registry ...... def array(self, value, units): ... return unyt_array(value, units, registry=self.registry) ...... def quantity(self, value, units): ... return unyt_quantity(value, units, registry=self.registry) ... >>> registry= UnitRegistry(unit_system='cgs') >>> registry.add("code_length", base_value=3.2, dimensions=length) >>> s_cgs= Simulation(registry) >>> data= s_cgs.array([1,2,3],'code_length') >>> data unyt_array([1, 2, 3], 'code_length') >>> data.in_base() unyt_array([320., 640., 960.], 'cm')

Note that the base_value parameter of UnitRegistry.add must be specified in MKS units. All unit data are stored internally in unyt in MKS units. You can also use two helper functions provided by unyt, unyt.unit_systems.add_constants() and unyt.unit_systems.add_symbols(), to populate a namespace with a set of predefined unit symbols or phys- ical consants. This namespace could correspond to the names importable from a module or the names of attributes of an object, or any other generic dictionary. One example of doing this would be to make a UnitContainer class that contains units that are compatible with the Simulation instance we named s_cgs in the example above:

>>> from unyt.unit_systems import add_symbols >>> class UnitContainer(object): ... def __init__(self, registry): ... add_symbols(vars(self), registry) >>> units= UnitContainer(s_cgs.registry) >>> units.kilometer km >>> units.code_length code_length >>> (10.0 * units.kilometer).in_base() unyt_quantity(1000000., 'cm') >>> (10.0 * units.kilometer).in_units('code_length') unyt_quantity(3125., 'code_length')

Note how the result of the call to in_base() comes out in centimeters because of the the CGS unit system used by the UnitRegistry instance associated with the Simulation.

2.7.3 Writing Data with Units to Disk

The unyt library has support for serializing data stored in a unyt.unyt_array instance to HDF5 files, text files, and via the Python pickle protocol. We give brief examples below, but first describe how to handle saving units

22 Chapter 2. Working with unyt unyt Documentation, Release v2.8.0

manually as string metadata.

Dealing with units as strings

If all you want to do is save data to disk in a physical unit or you are working in a physical unit system, then you only need to save the unit name as a string and treat the array data you are trying to save as a regular numpy array, as in this example:

>>> import numpy as np >>> import os >>> from unyt import cm ... >>> data=[1,2,3] *cm >>> np.save('my_data_cm.npy', data) >>> new_data= np.load('my_data_cm.npy') >>> new_data array([1, 2, 3]) >>> new_data_with_units= new_data * cm >>> os.remove('my_data_cm.npy')

Of course in this example using numpy.save we need to hard-code the units because the .npy format doesn’t have a way to store metadata along with the array data. We could have stored metadata in a sidecar file, but this is much more natural with hdf5 via h5py:

>>> import h5py >>> import os >>> from unyt import cm, Unit ... >>> data=[1,2,3] *cm ... >>> with h5py.File('my_data.h5','a') as f: ... d=f.create_dataset('my_data', data=data) ... f['my_data'].attrs['units']= str(data.units) ... >>> with h5py.File('my_data.h5','r') as f: ... new_data= f['my_data'][:] ... unit_str= f['my_data'].attrs['units'] ... >>> unit= Unit(unit_str) >>> new_data= new_data *unit >>> new_data unyt_array([1, 2, 3], 'cm') >>> os.remove('my_data.h5')

HDF5 Files

The unyt library provides a hook for writing data both to a new HDF5 file and an existing file and then subsequently reading that data back in to restore the array. This works via the unyt_array.write_hdf5 and unyt_array. from_hdf5 methods. The simplest way to use these functions is to write data to a file that does not exist yet:

>>> from unyt import cm >>> import os >>> data=[1,2,3] *cm >>> data.write_hdf5('my_data.h5') ... (continues on next page)

2.7. Integrating unyt Into a Python Library 23 unyt Documentation, Release v2.8.0

(continued from previous page) >>> unyt_array.from_hdf5('my_data.h5') unyt_array([1, 2, 3], 'cm') >>> os.remove('my_data.h5')

By default the data will be written to the root group of the HDF5 file in a dataset named 'array_data'. You can also specify that you would like the data to be saved in a particular group or dataset in the file:

>>> data.write_hdf5('my_data.h5', dataset_name='my_special_data', ... group_name='my_special_group') >>> unyt_array.from_hdf5('my_data.h5', dataset_name='my_special_data', ... group_name='my_special_group') unyt_array([1, 2, 3], 'cm') >>> os.remove('my_data.h5')

You can even write to files and groups that already exist:

>>> with h5py.File('my_data.h5') as f: ... g=f.create_group('my_custom_group') ... >>> data.write_hdf5('my_data.h5', group_name='my_custom_group') ... >>> with h5py.File('my_data.h5') as f: ... print(f['my_custom_group/array_data'][:]) [1 2 3] >>> os.remove('my_data.h5')

If the dataset that you would like to write to already exists, unyt will clobber that dataset. Note that with this method of saving data to hdf5 files, the unyt.UnitRegistry instance associated with the units of the data will be saved in the HDF5 file. This means that if you create custom units and save a unit to disk, you will be able to convert data to those custom units even if you are dealing with those units later after restoring the data from disk. Here is a short example illustrating this:

>>> import os >>> from unyt import UnitRegistry >>> reg= UnitRegistry() >>> reg.add("code_length", base_value=10.0, dimensions=length, ... tex_repr=r"\rm{Code Length}") >>> u= Unit('cm', registry=reg) >>> data=[1., 2., 3.] *u >>> data.write_hdf5('my_code_data.h5') >>> read_data= data.from_hdf5('my_code_data.h5') >>> read_data unyt_array([1., 2., 3.], 'cm') >>> read_data.to('code_length') unyt_array([0.001, 0.002, 0.003], 'code_length') >>> os.remove('my_code_data.h5')

Text Files

The unyt library also has wrappers around numpy.savetxt and numpy.loadtxt for saving data as an ASCII table. For example:

>>> import unyt asu >>> import os (continues on next page)

24 Chapter 2. Working with unyt unyt Documentation, Release v2.8.0

(continued from previous page) >>> data=[[1,2,3] *u.cm, [4,5,6] *u.kg] >>> u.savetxt('my_data.txt', data) >>> with open('my_data.txt') as f: ... print("".join(f.readlines())) # doctest: +NORMALIZE_WHITESPACE # Units # cm kg 1.000000000000000000e+00 4.000000000000000000e+00 2.000000000000000000e+00 5.000000000000000000e+00 3.000000000000000000e+00 6.000000000000000000e+00 >>> os.remove('my_data.txt')

Pickles

Note: Pickle files are great for serializing data to disk or over a network for internal usage by a package. They are ill-suited for long-term data storage or for communicating data between different Python installations. If you want to use pickle files for data storage, consider using a format designed for long-term data storage, like HDF5.

Both unyt.unyt_array and unyt.Unit instances can be saved using the pickle protocol:

>>> from unyt import kg >>> import pickle >>> import numpy as np ... >>> assert kg == pickle.loads(pickle.dumps(kg)) >>> data=[1,2,3] *kg >>> reloaded_data= pickle.loads(pickle.dumps(data)) >>> assert np.array_equal(data.value, reloaded_data.value) >>> assert data.units == reloaded_data.units

As for HDF5 data, the unit registry associated with the unit object is saved to the pickle. If you have custom units defined, the reloaded data will know about your custom unit and be able to convert data to and from the custom unit.

2.7.4 Performance Considerations

Tracking units in an application will inevitably add overhead. Judging where overhead is important or not depends on what real-world workflows look like. Ultimately, profiling code is the best way to find out whether handling units is a performance bottleneck. Optimally handling units will be amortized over the cost of an operation. While this is true for large arrays (bigger than about one million elements), this is not true for small arrays that contain only a few elements. In addition, it is sometimes easy to write code that needlessly checks unit consistency when we know ahead of time that data are already in the correct units. Often we can get away with only checking unit consistency once and then stripping units after that. A good rule of thumb is that units should be checked on input, stripped off of data during a calculation, and then re- applied when returning data from a function. In other words, apply or check units at interfaces, but during an internal calculation it is often worth stripping units, especially if the calculation involves many operations on arrays with only a few elements.

2.7. Integrating unyt Into a Python Library 25 unyt Documentation, Release v2.8.0

2.8 unyt_array.name attribute

The unyt_array has a name attribute for use in structured-data applications or similar applications that require labeled data. For example, Numpy has record arrays and when constructed as shown below, it is possible to retain the units while taking advantage of the labeled record fields.

>>> import numpy as np >>> from unyt import unyt_array >>> x= unyt_array([0,1,2],"s", name="time") >>> y= unyt_array([3,4,5],"m", name="distance") >>> data= (x, y) >>> dt= [(a.name,"O") for a in data] >>> data_points= np.array(list(zip( *data)), dtype=dt).view(np.recarray) >>> data_points[0].time unyt_quantity(0, 's') >>> data_points[0].distance unyt_quantity(3, 'm')

Note: The name attribute does not propagate through mathematical operations. Other operations such as indexing, copying, and unit conversion, will preserve the name attribute where the semantic meaning of the quantity remains the same.

2.9 Plotting with Matplotlib

Note: • This is an experimental feature. Please report issues. • This feature works in Matplotlib versions 2.2.4 and above • Matplotlib is not a dependency of Unyt

Matplotlib is Unyt aware. After enabling support in unyt using the unyt.matplotlib_support context man- ager, Matplotlib will label the x and y axes with the units.

>>> import matplotlib.pyplot as plt >>> from unyt import matplotlib_support, s, K >>> x=[0.0, 60.0, 120.0] *s >>> y=[298.15, 308.15, 318.15] *K >>> with matplotlib_support: ... plt.plot(x, y) ... plt.show() []

26 Chapter 2. Working with unyt unyt Documentation, Release v2.8.0

You can change the plotted units without affecting the original data.

>>> with matplotlib_support: ... plt.plot(x, y, xunits="min", yunits=("J","thermal")) ... plt.show() []

It is also possible to set the label style; the choices "()", "[]" and "/" are supported.

2.9. Plotting with Matplotlib 27 unyt Documentation, Release v2.8.0

>>> matplotlib_support.label_style="[]" >>> with matplotlib_support: ... plt.plot(x, y) ... plt.show() []

The axis label will include the unyt_array.name attribute if set.

>>> x.name="Time" >>> y.name="Temperature" >>> with matplotlib_support: ... plt.plot(x, y) ... plt.show() []

28 Chapter 2. Working with unyt unyt Documentation, Release v2.8.0

With label_style set to “/”, the axis label conforms to the SI standard where the axis label is a mathematical expression rather than a caption. In this case, set the unyt_array.name attribute to the latex expression for the symbol.

>>> x.name="$t$" >>> y.name="" >>> matplotlib_support.label_style="/" >>> with matplotlib_support: ... plt.plot(x, y) ... plt.show() []

2.9. Plotting with Matplotlib 29 unyt Documentation, Release v2.8.0

There are three ways to use the context manager: 1. As a conventional context manager in a with statement as shown above 2. As a feature toggle in an interactive session:

>>> import matplotlib.pyplot as plt >>> from unyt import s, K, matplotlib_support >>> matplotlib_support.enable() >>> plt.plot([0,1,2] *s, [3,4,5] *K) [] >>> plt.show() >>> matplotlib_support.disable()

3. As an enable for a complete session:

>>> import unyt >>> unyt.matplotlib_support() >>> import matplotlib.pyplot as plt

30 Chapter 2. Working with unyt CHAPTER 3

Listing of Units

Unit Name Dimensions MKS value CGS Value LaTeX Representation SI Prefixable? Alternate Names m length 1.0 m 100.0 cm \rm{m} True meter, Meter, , Metre g mass 0.001 kg 1.0 g \rm{g} True gram, Gram, gramme, Gramme s time 1.0 s 1.0 s \rm{s} True second, Second K temperature 1.0 K 1.0 K \rm{K} True degree_kelvin, Degree_Kelvin, kelvin, Kelvin rad angle 1.0 rad 1.0 rad \rm{rad} True radian, Radian A current_mks 1 A 2.9979e+09 statA \rm{A} True ampere, Ampere, amp, Amp cd luminous_intensity 1.0 cd 1.0 cd \rm{cd} True candela, Candela mol dimensionless 6.0221e+23 dimensionless 6.0221e+23 dimensionless \rm{mol} True mole, Mole dyn force 1.0000e-05 N 1.0 dyn \rm{dyn} True dyne, Dyne erg energy 1.0000e-07 J 1.0 erg \rm{erg} True ergs, Ergs Ba pressure 0.1 Pa 1.0 dyn/cm**2 \rm{Ba} True barye, Barye G magnetic_field_cgs 0.0001 T 1 G \rm{G} True gauss, Gauss statC magnetic_flux_cgs 3.3356e-10 C 1 statC \rm{statC} True statcoulomb, Statcoulomb, esu, ESU, electrostatic_unit, Electrostatic_Unit statA current_cgs 3.3356e-10 A 1 statA \rm{statA} True statampere, Statampere statV electric_potential_cgs 3.3356e-03 V 3.3356e-03 V \rm{statV} True statvolt, Statvolt statohm v 8.9876e+11 Ω 8.9876e+11 Ω \rm{statohm} True Mx magnetic_flux_cgs 3.1623e-05 sqrt(kg)*m**(3/2)/s 1.0 statC \rm{Mx} True maxwell, Maxwell J energy 1.0 J 1.0000e+07 erg \rm{J} True , Joule W power 1.0 W 1.0000e+07 erg/s \rm{W} True watt, Watt Hz 1/(time) 1.0 Hz 1.0 1/s \rm{Hz} True hertz, Hertz N force 1.0 N 1.0000e+05 dyn \rm{N} True , Newton C charge_mks 1 C 2.9979e+09 statC \rm{C} True coulomb, Coulomb T magnetic_field_mks 1 T 10000.0 G \rm{T} True tesla, Tesla Pa pressure 1.0 Pa 10.0 dyn/cm**2 \rm{Pa} True pascal, Pascal bar pressure 1.0000e+05 Pa 1.0000e+06 dyn/cm**2 \rm{bar} True V electric_potential_mks 1 V 2.9979e+02 statV \rm{V} True volt, Volt F capacitance_mks 1.0 F N/A \rm{F} True farad, Farad H inductance_mks 1.0 H N/A \rm{H} True henry, Henry Continued on next page

31 unyt Documentation, Release v2.8.0

Table 1 – continued from previous page Unit Name Dimensions MKS value CGS Value LaTeX Representation SI Prefixable? Alternate Names Ω k 1 Ω 1.1127e-12 statohm \Omega True ohm, Ohm Wb magnetic_flux_mks 1.0 Wb N/A \rm{Wb} True weber, Weber lm luminous_flux 1.0 lm 1.0 cd*rad**2 \rm{lm} True lumen, Lumen lx (angle)**2*(luminous_intensity)/(length)**2 1.0 cd*rad**2/m**2 0.0001 cd*rad**2/cm**2 \rm{lx} True lux degC temperature 274.15 K 274.15 K ^\circ\rm{C} True degree_celsius, Degree_Celsius, degree_Celsius, celcius, Celcius, celsius, Celsius, °C delta_degC temperature 1.0 K 1.0 K \Delta^\circ\rm{C} True mil length 2.5400e-05 m 0.00254 cm \rm{mil} False thou, Thou, thousandth, Thousandth inch length 0.0254 m 2.54 cm \rm{in} False Inch, in ft length 0.3048 m 30.48 cm \rm{ft} False foot, Foot yd length 0.9144 m 91.44 cm \rm{yd} False yard, Yard mile length 1609.344 m 1.6093e+05 cm \rm{mile} False Mile furlong length 201.168 m 2.0117e+04 cm \rm{fur} False Furlong, fur degF temperature 2.5593e+02 K 2.5593e+02 K ^\circ\rm{F} False Degf, degree_fahrenheit, Degree_Fahrenheit, degree_Fahrenheit, fahrenheit, Fahrenheit, °F delta_degF temperature 5.5556e-01 K 5.5556e-01 K \Delta^\circ\rm{F} False Delta_Degf R temperature 5.5556e-01 K 5.5556e-01 K ^\circ\rm{R} False degree_rankine, Degree_Rankine, rankine, Rankine lbf force 4.4482e+00 N 4.4482e+05 dyn \rm{lbf} False pound_force, Pound_Force kip force 4.4482e+03 N 4.4482e+08 dyn \rm{kip} False kilopound, Kilopound, kipf, Kipf lb mass 4.5359e-01 kg 4.5359e+02 g \rm{lb} False pound, Pound, pound_mass, Pound_Mass, lbm atm pressure 1.0132e+05 Pa 1.0132e+06 dyn/cm**2 \rm{atm} False atmosphere, Atmosphere hp power 7.4570e+02 W 7.4570e+09 erg/s \rm{hp} False horsepower, Horsepower oz mass 2.8350e-02 kg 2.8350e+01 g \rm{oz} False ounce, Ounce ton mass 9.0718e+02 kg 9.0718e+05 g \rm{ton} False slug mass 1.4594e+01 kg 1.4594e+04 g \rm{slug} False Slug cal energy 4.184 J 4.1840e+07 erg \rm{cal} True calorie, Calorie BTU energy 1.0551e+03 J 1.0551e+10 erg \rm{BTU} False british_thermal_unit, British_Thermal_Unit psi pressure 6.8948e+03 Pa 6.8948e+04 dyn/cm**2 \rm{psi} False pounds_per_square_inch, Pounds_Per_Square_Inch ksi pressure 6.8948e+06 Pa 6.8948e+07 dyn/cm**2 \rm{ksi} False kips_per_square_inch, Kips_Per_Square_Inch smoot length 1.7018 m 170.18 cm \rm{smoot} False Smoot dimensionless dimensionless 1.0 dimensionless 1.0 dimensionless False Dimensionless, _, % dimensionless 0.01 dimensionless 0.01 dimensionless \% False percent, Percent min time 60.0 s 60.0 s \rm{min} False minute, Minute hr time 3600.0 s 3600.0 s \rm{hr} False hour, Hour day time 8.6400e+04 s 8.6400e+04 s \rm{d} False d yr time 3.1558e+07 s 3.1558e+07 s \rm{yr} True year, Year c velocity 2.9979e+08 m/s 2.9979e+10 cm/s \rm{c} False Msun mass 1.9884e+30 kg 1.9884e+33 g \rm{M}_\odot False msun, m_sun, M_Sun, M_sun, m_Sun, solar_mass, Solar_Mass, solMass, mass_sun, Mass_Sun Rsun length 6.9550e+08 m 6.9550e+10 cm \rm{R}_\odot False rsun, r_sun, R_Sun, R_sun, r_Sun, solar_radius, Solar_Radius, solRadius Lsun power 3.8270e+26 W 3.8270e+33 erg/s \rm{L}_\odot False lsun, l_sun, L_Sun, L_sun, l_Sun, solar_luminosity, Solar_Luminosity, solLuminosity Tsun temperature 5870.0 K 5870.0 K \rm{T}_\odot False t_sun, T_Sun, tsun, T_sun, t_Sun, solar_temperature, Solar_Temperature, solTemperature Zsun dimensionless 0.01295 dimensionless 0.01295 dimensionless \rm{Z}_\odot False z_sun, Z_Sun, zsun, Z_sun, z_Sun, solar_metallicity, Solar_Metallicity, solMetallicity Mjup mass 1.8985e+27 kg 1.8985e+30 g \rm{M}_{\rm{Jup}} False m_jup, M_Jup, jupiter_mass, Jupiter_Mass Mearth mass 6.0456e+24 kg 6.0456e+27 g \rm{M}_\oplus False m_earth, M_Earth, earth_mass, Earth_Mass Rjup length 6.9911e+07 m 6.9911e+09 cm \rm{R}_\mathrm{Jup} False r_jup, R_Jup, jupiter_radius, Jupiter_Radius Rearth length 6.3710e+06 m 6.3710e+08 cm \rm{R}_\oplus False r_earth, R_Earth, earth_radius, Earth_Radius AU length 1.4960e+11 m 1.4960e+13 cm \rm{AU} False au, astronomical_unit, Astronomical_Unit ly length 9.4605e+15 m 9.4605e+17 cm \rm{ly} False light_year, Light_Year pc length 3.0857e+16 m 3.0857e+18 cm \rm{pc} True , Parsec degree angle 1.7453e-02 rad 1.7453e-02 rad ^\circ False Degree, deg arcmin angle 2.9089e-04 rad 2.9089e-04 rad \rm{arcmin} False Arcmin, arcminute, Arcminute Continued on next page

32 Chapter 3. Listing of Units unyt Documentation, Release v2.8.0

Table 1 – continued from previous page Unit Name Dimensions MKS value CGS Value LaTeX Representation SI Prefixable? Alternate Names arcsec angle 4.8481e-06 rad 4.8481e-06 rad \rm{arcsec} False Arcsec, arcsecond, Arcsecond mas angle 4.8481e-09 rad 4.8481e-09 rad \rm{mas} False milliarcsecond, Milliarcsecond hourangle angle 2.6180e-01 rad 2.6180e-01 rad \rm{HA} False Hourangle, HA sr (angle)**2 1.0 rad**2 1.0 rad**2 \rm{sr} False steradian, Steradian lat angle 1.5533e+00 rad 1.5533e+00 rad \rm{Latitude} False latitude, Latitude, degree_latitude, Degree_Latitude lon angle 3.1590e+00 rad 3.1590e+00 rad \rm{Longitude} False longitude, Longitude, degree_longitude, Degree_Longitude eV energy 1.6022e-19 J 1.6022e-12 erg \rm{eV} True , Electronvolt amu mass 1.6605e-27 kg 1.6605e-24 g \rm{amu} False atomic_mass_unit, Atomic_Mass_Unit Å length 1.0000e-10 m 1.0000e-08 cm \AA False angstrom, Angstrom Jy specific_flux 1.0000e-26 kg/s**2 1.0000e-23 g/s**2 \rm{Jy} True jansky, Jansky counts dimensionless 1.0 dimensionless 1.0 dimensionless \rm{counts} False Counts, count, Count photons dimensionless 1.0 dimensionless 1.0 dimensionless \rm{photons} False Photons, photon, Photon me mass 9.1094e-31 kg 9.1094e-28 g m_e False electron_mass, Electron_Mass mp mass 1.6737e-27 kg 1.6737e-24 g m_p False proton_mass, Proton_Mass Sv specific_energy 1.0 J/kg 10000.0 erg/g \rm{Sv} True sievert, Sievert rayleigh count_intensity 7.9577e+08 1/(m**2*rad**2*s) 7.9577e+04 1/(cm**2*rad**2*s) \rm{R} False Rayleigh lambert luminance 3.1831e+03 cd/m**2 3.1831e-01 cd/cm**2 \rm{L} False Lambert nt luminance 1.0 cd/m**2 0.0001 cd/cm**2 \rm{nt} False nit m_pl mass 2.1765e-08 kg 2.1765e-05 g m_{\rm{P}} False planck_mass, Planck_Mass l_pl length 1.6162e-35 m 1.6162e-33 cm \ell_\rm{P} False planck_length, Planck_Length t_pl time 5.3912e-44 s 5.3912e-44 s t_{\rm{P}} False planck_time, Planck_Time T_pl temperature 1.4168e+32 K 1.4168e+32 K T_{\rm{P}} False planck_temperature, Planck_Temperature q_pl charge_mks 1.8755e-18 C N/A q_{\rm{P}} False planck_charge, Planck_Charge E_pl energy 1.9561e+09 J 1.9561e+16 erg E_{\rm{P}} False planck_energy, Planck_Energy m_geom mass 1.9884e+30 kg 1.9884e+33 g \rm{M}_\odot False l_geom length 1.4766e+03 m 1.4766e+05 cm \rm{M}_\odot False t_geom time 4.9253e-06 s 4.9253e-06 s \rm{M}_\odot False B logarithmic 1.1513e+00 Np 1.1513e+00 Np \rm{B} True bel Np logarithmic 1.0 Np 1.0 Np \rm{Np} True neper, Neper

33 unyt Documentation, Release v2.8.0

34 Chapter 3. Listing of Units CHAPTER 4

Listing of Physical Constants

Constant Name Value Alternate Names me 9.1094e-31 kg mass_electron, electron_mass amu 1.6605e-27 kg atomic_mass_unit Na 0.9999999282021593 dimensionless Avogadros_number, avogadros_number mp 1.6726e-27 kg proton_mass, mass_proton mh 1.6737e-27 kg hydrogen_mass, mass_hydrogen c 2.9979e+08 m/s clight, speed_of_light 휎_T 6.6525e-29 m**2 sigma_thompson, thompson_cross_section, cross_section_thompson qp 1.6022e-19 C proton_charge, elementary_charge, charge_proton qe -1.6022e-19 C electron_charge, charge_electron kb 1.3806e-23 kg*m**2/(K*s**2) kboltz, boltzmann_constant G 6.6741e-11 m**3/(kg*s**2) newtons_constant, gravitational_constant h 6.6261e-34 kg*m**2/s planck_constant hbar 1.0546e-34 kg*m**2/s reduced_planck_constant 휎 5.6704e-08 kg/(K**4*s**3) stefan_boltzmann_constant Tcmb 2.726 K CMB_temperature Msun 1.9884e+30 kg msun, m_sun, m_Sun, M_sun, M_Sun, solar_mass, mass_sun Mjup 1.8985e+27 kg mjup, jupiter_mass, mass_jupiter mercury_mass 3.3010e+23 kg mass_mercury venus_mass 4.8673e+24 kg mass_venus Mearth 6.0456e+24 kg mearth, earth_mass, mass_earth mars_mass 6.4169e+23 kg mass_mars saturn_mass 5.6846e+26 kg mass_saturn uranus_mass 8.6819e+25 kg mass_uranus neptune_mass 1.0243e+26 kg mass_neptune m_pl 2.1765e-08 kg planck_mass l_pl 1.6162e-35 m planck_length t_pl 5.3912e-44 s planck_time E_pl 1.9561e+09 J planck_energy Continued on next page

35 unyt Documentation, Release v2.8.0

Table 1 – continued from previous page Constant Name Value Alternate Names q_pl 1.8755e-18 C planck_charge T_pl 1.4168e+32 K planck_temperature mu_0 1.2566e-06 kg*m/(A**2*s**2) vacuum_permeability, magnetic_constant, 휇_0 eps_0 8.8542e-12 A**2*s**4/(kg*m**3) vacuum_permittivity, electric_constant, 휖_0, epsilon_0 standard_gravity 9.80665 m/s**2

36 Chapter 4. Listing of Physical Constants CHAPTER 5

unyt package

The unyt package. Note that the symbols defined in unyt.physical_constants and unyt.unit_symbols are importable from this module. For example:

>>> from unyt import km, clight >>> print((km/clight).to('ns')) 3335.64095198152 ns

In addition, the following functions and classes are importable from the top-level unyt namespace: • unyt.array.loadtxt() • unyt.array.savetxt() • unyt.test() • unyt.array.uconcatenate() • unyt.array.ucross() • unyt.array.udot() • unyt.array.uhstack() • unyt.array.uintersect1d() • unyt.array.unorm() • unyt.array.ustack() • unyt.array.uunion1d() • unyt.array.uvstack() • unyt.array.unyt_array • unyt.array.unyt_quantity • unyt.unit_object.define_unit()

37 unyt Documentation, Release v2.8.0

• unyt.unit_object.Unit • unyt.unit_registry.UnitRegistry • unyt.unit_systems.UnitSystem • unyt.testing.assert_allclose_units() • unyt.array.allclose_units() • unyt.dimensions.accepts() • unyt.dimensions.returns() unyt.test() Execute the unit tests on an installed copy of unyt. Note that this function requires pytest to run. If pytest is not installed this function will raise ImportError.

5.1 Submodules

5.1.1 unyt.array module unyt_array class. class unyt.array.unyt_array Bases: numpy.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 (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 propa- gate 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 (continues on next page)

38 Chapter 5. unyt package unyt Documentation, Release v2.8.0

(continued from previous page) 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])

convert_to_units(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 equiva- lence 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

convert_to_base(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).

5.1. Submodules 39 unyt Documentation, Release v2.8.0

• 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 equiva- lence 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')

convert_to_cgs(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 equiva- lence 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')

convert_to_mks(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

40 Chapter 5. unyt package unyt Documentation, Release v2.8.0

• 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 equiva- lence 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')

in_units(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 equiva- lence 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

to(units, equivalence=None, **kwargs) Creates a copy of this array with the data converted to the supplied units, and returns it.

5.1. Submodules 41 unyt Documentation, Release v2.8.0

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 list_equivalencies() method. Default: None • kwargs (optional) – Any additional keywoard arguments are supplied to the equiva- lence 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

to_value(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 list_equivalencies() method. Default: None

42 Chapter 5. unyt package unyt Documentation, Release v2.8.0

Examples

>>> from unyt import km >>> a=[3,4,5] *km >>> print(a.to_value('cm')) [300000. 400000. 500000.]

in_base(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) – The unit system to be used in the con- version. If not specified, the configured default base units of are used (defaults to MKS).

Examples

>>> from unyt import erg, s >>> E= 2.5 *erg/s >>> print(E.in_base("mks")) 2.5e-07 W

in_cgs() Creates a copy of this array with the data in the equivalent cgs units, and returns it. Returns Return type unyt_array object with data in this array converted to cgs units.

Example

>>> from unyt import Newton, km >>> print((10*Newton/km).in_cgs()) 10.0 g/s**2

in_mks() Creates a copy of this array with the data in the equivalent mks units, and returns it. Returns Return type unyt_array object with data in this array converted to mks units.

Example

>>> from unyt import mile >>> print((1.*mile).in_mks()) 1609.344 m

convert_to_equivalent(unit, equivalence, **kwargs) Convert the array in-place to the specified units, assuming the given equivalency. The dimensions of the specified units and the dimensions of the original array need not match so long as there is an appropriate conversion in the specified equivalency. Parameters • unit (string) – The unit that you wish to convert to.

5.1. Submodules 43 unyt Documentation, Release v2.8.0

• equivalence (string) – The equivalence you wish to use. To see which equivalen- cies are supported for this unitful quantity, try the list_equivalencies() method.

Examples

>>> from unyt import K >>> a=[10, 20, 30] *(1e7*K) >>> a.convert_to_equivalent("keV","thermal") >>> a unyt_array([ 8.6173324, 17.2346648, 25.8519972], 'keV')

to_equivalent(unit, equivalence, **kwargs) Return a copy of the unyt_array in the units specified units, assuming the given equivalency. The dimen- sions of the specified units and the dimensions of the original array need not match so long as there is an appropriate conversion in the specified equivalency. Parameters • unit (string) – The unit that you wish to convert to. • equivalence (string) – The equivalence you wish to use. To see which equivalen- cies are supported for this unitful quantity, try the list_equivalencies() method.

Examples

>>> from unyt import K >>> a= 1.0e7 *K >>> print(a.to_equivalent("keV","thermal")) 0.8617332401096504 keV

list_equivalencies() Lists the possible equivalencies associated with this unyt_array or unyt_quantity.

Example

>>> from unyt import km >>> (1.0*km).list_equivalencies() spectral: length <-> spatial_frequency <-> frequency <-> energy schwarzschild: mass <-> length compton: mass <-> length

has_equivalent(equivalence) Check to see if this unyt_array or unyt_quantity has an equivalent unit in equiv.

Example

>>> from unyt import km, keV >>> (1.0*km).has_equivalent('spectral') True >>> print((1*km).to_equivalent('MHz', equivalence='spectral')) 0.299792458 MHz >>> print((1*keV).to_equivalent('angstrom', equivalence='spectral')) 12.39841931521966 Å

44 Chapter 5. unyt package unyt Documentation, Release v2.8.0

ndarray_view() Returns a view into the array as a numpy array Returns Return type View of this array’s data.

Example

>>> from unyt import km >>> a=[3,4,5] *km >>> a unyt_array([3, 4, 5], 'km') >>> a.ndarray_view() array([3, 4, 5])

This function returns a view that shares the same underlying memory as the original array.

>>> b=a.ndarray_view() >>> b.base is a.base True >>> b[2]=4 >>> b array([3, 4, 4]) >>> a unyt_array([3, 4, 4], 'km')

to_ndarray() Creates a copy of this array with the unit information stripped

Example

>>> from unyt import km >>> a=[3,4,5] *km >>> a unyt_array([3, 4, 5], 'km') >>> b=a.to_ndarray() >>> b array([3, 4, 5])

The returned array will contain a copy of the data contained in the original array.

>>> a.base is not b.base True

argsort(axis=-1, kind=’quicksort’, order=None) Returns the indices that would sort the array. See the documentation of ndarray.argsort for details about the keyword arguments.

Example

5.1. Submodules 45 unyt Documentation, Release v2.8.0

>>> from unyt import km >>> data=[3,8,7] *km >>> print(np.argsort(data)) [0 2 1] >>> print(data.argsort()) [0 2 1]

classmethod from_astropy(arr, unit_registry=None) Convert an AstroPy “Quantity” to a unyt_array or unyt_quantity. Parameters • arr (AstroPy Quantity) – The Quantity to convert from. • unit_registry (yt UnitRegistry, optional) – A yt unit registry to use in the conversion. If one is not supplied, the default one will be used.

Example

>>> from astropy.units import km >>> unyt_quantity.from_astropy(km) unyt_quantity(1., 'km') >>> a=[1,2,3] *km >>> a >>> unyt_array.from_astropy(a) unyt_array([1., 2., 3.], 'km')

to_astropy(**kwargs) Creates a new AstroPy quantity with the same unit information.

Example

>>> from unyt import g, cm >>> data=[3,4,5] *g/cm**3 >>> data.to_astropy()

classmethod from_pint(arr, unit_registry=None) Convert a Pint “Quantity” to a unyt_array or unyt_quantity. Parameters • arr (Pint Quantity) – The Quantity to convert from. • unit_registry (yt UnitRegistry, optional) – A yt unit registry to use in the conversion. If one is not supplied, the default one will be used.

Examples

>>> from pint import UnitRegistry >>> import numpy as np >>> ureg= UnitRegistry() >>> a= np.arange(4) (continues on next page)

46 Chapter 5. unyt package unyt Documentation, Release v2.8.0

(continued from previous page) >>> b= ureg.Quantity(a,"erg/cm **3") >>> b >>> c= unyt_array.from_pint(b) >>> c unyt_array([0, 1, 2, 3], 'erg/cm**3')

to_pint(unit_registry=None) Convert a unyt_array or unyt_quantity to a Pint Quantity. Parameters • arr (unyt_array or unyt_quantity) – The unitful quantity to convert from. • unit_registry (Pint UnitRegistry, optional) – The Pint UnitRegistry to use in the conversion. If one is not supplied, the default one will be used. NOTE: This is not the same as a yt UnitRegistry object.

Examples

>>> from unyt import cm, s >>> a=4 *cm**2/s >>> print(a) 4 cm**2/s >>> a.to_pint()

write_hdf5(filename, dataset_name=None, info=None, group_name=None) Writes a unyt_array to hdf5 file. Parameters • filename (string) – The filename to create and write a dataset to • dataset_name (string) – The name of the dataset to create in the file. • info (dictionary) – A dictionary of supplementary info to write to append as at- tributes to the dataset. • group_name (string) – An optional group to write the arrays to. If not specified, the arrays are datasets at the top level by default.

Examples

>>> from unyt import cm >>> a=[1,2,3] *cm >>> myinfo={'field':'dinosaurs','type':'field_data'} >>> a.write_hdf5('test_array_data.h5', dataset_name='dinosaurs', ... info=myinfo) # doctest: +SKIP

classmethod from_hdf5(filename, dataset_name=None, group_name=None) Attempts read in and convert a dataset in an hdf5 file into a unyt_array. Parameters • filename (string)– • filename to of the hdf5 file. (The)–

5.1. Submodules 47 unyt Documentation, Release v2.8.0

• dataset_name (string) – The name of the dataset to read from. If the dataset has a units attribute, attempt to infer units as well. • group_name (string) – An optional group to read the arrays from. If not specified, the arrays are datasets at the top level by default. value Creates a copy of this array with the unit information stripped

Example

>>> from unyt import km >>> a=[3,4,5] *km >>> a unyt_array([3, 4, 5], 'km') >>> b=a.value >>> b array([3, 4, 5])

The returned array will contain a copy of the data contained in the original array.

>>> a.base is not b.base True

v Creates a copy of this array with the unit information stripped

Example

>>> from unyt import km >>> a=[3,4,5] *km >>> a unyt_array([3, 4, 5], 'km') >>> b=a.v >>> b array([3, 4, 5])

The returned array will contain a copy of the data contained in the original array.

>>> a.base is not b.base True

ndview Returns a view into the array as a numpy array Returns Return type View of this array’s data.

Example

>>> from unyt import km >>> a=[3,4,5] *km >>> a (continues on next page)

48 Chapter 5. unyt package unyt Documentation, Release v2.8.0

(continued from previous page) unyt_array([3, 4, 5], 'km') >>> a.ndview array([3, 4, 5])

This function returns a view that shares the same underlying memory as the original array.

>>> b=a.ndview >>> b.base is a.base True >>> b[2]=4 >>> b array([3, 4, 4]) >>> a unyt_array([3, 4, 4], 'km')

d Returns a view into the array as a numpy array Returns Return type View of this array’s data.

Example

>>> from unyt import km >>> a=[3,4,5] *km >>> a unyt_array([3, 4, 5], 'km') >>> a.d array([3, 4, 5])

This function returns a view that shares the same underlying memory as the original array.

>>> b=a.d >>> b.base is a.base True >>> b[2]=4 >>> b array([3, 4, 4]) >>> a unyt_array([3, 4, 4], 'km')

unit_quantity Return a quantity with a value of 1 and the same units as this array

Example

>>> from unyt import km >>> a=[4,5,6] *km >>> a.unit_quantity unyt_quantity(1, 'km') >>> print(a+7 *a.unit_quantity) [11 12 13] km

5.1. Submodules 49 unyt Documentation, Release v2.8.0

uq Return a quantity with a value of 1 and the same units as this array

Example

>>> from unyt import km >>> a=[4,5,6] *km >>> a.uq unyt_quantity(1, 'km') >>> print(a+7 *a.uq) [11 12 13] km

unit_array Return an array filled with ones with the same units as this array

Example

>>> from unyt import km >>> a=[4,5,6] *km >>> a.unit_array unyt_array([1, 1, 1], 'km') >>> print(a+7 *a.unit_array) [11 12 13] km

ua Return an array filled with ones with the same units as this array

Example

>>> from unyt import km >>> a=[4,5,6] *km >>> a.unit_array unyt_array([1, 1, 1], 'km') >>> print(a+7 *a.unit_array) [11 12 13] km

copy(order=’C’) Return a copy of the array. Parameters order ({'C', 'F', 'A', 'K'}, optional) – Controls the memory lay- out of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contigu- ous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible. (Note that this function and numpy.copy() are very similar, but have different default values for their order= arguments.) See also: numpy.copy(), numpy.copyto()

Examples

50 Chapter 5. unyt package unyt Documentation, Release v2.8.0

>>> from unyt import km >>> x=[[1,2,3],[4,5,6]] * km >>> y=x.copy() >>> x.fill(0) >>> print(x) [[0 0 0] [0 0 0]] km

>>> print(y) [[1 2 3] [4 5 6]] km

dot(b, out=None) dot product of two arrays. Refer to numpy.dot for full documentation. See also:

numpy.dot() equivalent function

Examples

>>> from unyt import km, s >>> a= np.eye(2) *km >>> b= (np.ones((2,2)) * 2)*s >>> print(a.dot(b)) [[2. 2.] [2. 2.]] km*s

This array method can be conveniently chained:

>>> print(a.dot(b).dot(b)) [[8. 8.] [8. 8.]] km*s**2 class unyt.array.unyt_quantity Bases: unyt.array.unyt_array A scalar associated with a unit. Parameters • input_scalar (an integer or floating point scalar) – The scalar to at- tach units to • input_units (String unit specification, unit symbol object, or astropy) – units The units of the quantity. Powers must be specified using python syntax (cm**3, not cm^3). • registry (A UnitRegistry object) – The registry to create units from. If in- put_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 (data-type) – The dtype of the array data. • name (string) – The name of the scalar. Defaults to None. This attribute does not propa- gate through mathematical operations, but is preserved under indexing and unit conversions.

5.1. Submodules 51 unyt Documentation, Release v2.8.0

Examples

>>> a= unyt_quantity(3.,'cm') >>> b= unyt_quantity(2.,'m') >>> print(a+ b) 203.0 cm >>> print(b+ a) 2.03 m

NumPy ufuncs will pass through units where appropriate.

>>> import numpy as np >>> from unyt import g, cm >>> a= 12 *g/cm**3 >>> print(np.abs(a)) 12 g/cm**3

and strip them when it would be annoying to deal with them.

>>> print(np.log10(a)) 1.0791812460476249 unyt.array.uconcatenate(arrs, axis=0) Concatenate a sequence of arrays. This wrapper around numpy.concatenate preserves units. All input arrays must have the same units. See the documentation of numpy.concatenate for full details.

Examples

>>> from unyt import cm >>> A=[1,2,3] *cm >>> B=[2,3,4] *cm >>> uconcatenate((A, B)) unyt_array([1, 2, 3, 2, 3, 4], 'cm') unyt.array.ucross(arr1, arr2, registry=None, axisa=-1, axisb=-1, axisc=-1, axis=None) Applies the cross product to two YT arrays. This wrapper around numpy.cross preserves units. See the documentation of numpy.cross for full details. unyt.array.uintersect1d(arr1, arr2, assume_unique=False) Find the sorted unique elements of the two input arrays. A wrapper around numpy.intersect1d that preserves units. All input arrays must have the same units. See the documentation of numpy.intersect1d for full details.

Examples

>>> from unyt import cm >>> A=[1,2,3] *cm >>> B=[2,3,4] *cm >>> uintersect1d(A, B) unyt_array([2, 3], 'cm')

52 Chapter 5. unyt package unyt Documentation, Release v2.8.0 unyt.array.uunion1d(arr1, arr2) Find the union of two arrays. A wrapper around numpy.intersect1d that preserves units. All input arrays must have the same units. See the documentation of numpy.intersect1d for full details.

Examples

>>> from unyt import cm >>> A=[1,2,3] *cm >>> B=[2,3,4] *cm >>> uunion1d(A, B) unyt_array([1, 2, 3, 4], 'cm') unyt.array.unorm(data, ord=None, axis=None, keepdims=False) Matrix or vector norm that preserves units This is a wrapper around np.linalg.norm that preserves units. See the documentation for that function for de- scriptions of the keyword arguments.

Examples

>>> from unyt import km >>> data=[1,2,3] *km >>> print(unorm(data)) 3.7416573867739413 km unyt.array.udot(op1, op2) Matrix or vector dot product that preserves units This is a wrapper around np.dot that preserves units.

Examples

>>> from unyt import km, s >>> a= np.eye(2) *km >>> b= (np.ones((2,2)) * 2)*s >>> print(udot(a, b)) [[2. 2.] [2. 2.]] km*s unyt.array.uvstack(arrs) Stack arrays in sequence vertically (row wise) while preserving units This is a wrapper around np.vstack that preserves units.

Examples

>>> from unyt import km >>> a=[1,2,3] *km >>> b=[2,3,4] *km >>> print(uvstack([a, b])) [[1 2 3] [2 3 4]] km

5.1. Submodules 53 unyt Documentation, Release v2.8.0 unyt.array.uhstack(arrs) Stack arrays in sequence horizontally while preserving units This is a wrapper around np.hstack that preserves units.

Examples

>>> from unyt import km >>> a=[1,2,3] *km >>> b=[2,3,4] *km >>> print(uhstack([a, b])) [1 2 3 2 3 4] km >>> a=[[1],[2],[3]] *km >>> b=[[2],[3],[4]] *km >>> print(uhstack([a, b])) [[1 2] [2 3] [3 4]] km unyt.array.ustack(arrs, axis=0) Join a sequence of arrays along a new axis while preserving units The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension. This is a wrapper around np.stack that preserves units. See the documentation for np.stack for full details.

Examples

>>> from unyt import km >>> a=[1,2,3] *km >>> b=[2,3,4] *km >>> print(ustack([a, b])) [[1 2 3] [2 3 4]] km unyt.array.loadtxt(fname, dtype=’float’, delimiter=’\t’, usecols=None, comments=’#’) Load unyt_arrays with unit information from a text file. Each row in the text file must have the same number of values. Parameters • fname (str) – Filename to read. • dtype (data-type, optional) – Data-type of the resulting array; default: float. • delimiter (str, optional) – The string used to separate values. By default, this is any whitespace. • usecols (sequence, optional) – Which columns to read, with 0 being the first. For example, usecols = (1,4,5) will extract the 2nd, 5th and 6th columns. The default, None, results in all columns being read. • comments (str, optional) – The character used to indicate the start of a comment; default: ‘#’.

54 Chapter 5. unyt package unyt Documentation, Release v2.8.0

Examples

>>> temp, velx= loadtxt( ... "sphere.dat", usecols=(1,2), delimiter="\t") # doctest: +SKIP unyt.array.savetxt(fname, arrays, fmt=’%.18e’, delimiter=’\t’, header=”, footer=”, comments=’#’) Write unyt_arrays with unit information to a text file. Parameters • fname (str) – The file to write the unyt_arrays to. • arrays (list of unyt_arrays or single unyt_array) – The array(s) to write to the file. • fmt (str or sequence of strs, optional) – A single format (%10.5f), or a sequence of formats. • delimiter (str, optional) – String or character separating columns. • header (str, optional) – String that will be written at the beginning of the file, before the unit header. • footer (str, optional) – String that will be written at the end of the file. • comments (str, optional) – String that will be prepended to the header and footer strings, to mark them as comments. Default: ‘# ‘, as expected by e.g. unyt. loadtxt.

Examples

>>> import unyt asu >>> a=[1,2,3] *u.cm >>> b=[8, 10, 12] *u.cm/u.s >>> c=[2, 85,9] *u.g >>> savetxt("sphere.dat", [a,b,c], header='My sphere stuff', ... delimiter="\t") # doctest: +SKIP unyt.array.allclose_units(actual, desired, rtol=1e-07, atol=0, **kwargs) Returns False if two objects are not equal up to desired tolerance This is a wrapper for numpy.allclose() that also verifies unit consistency Parameters • actual (array-like) – Array obtained (possibly with attached units) • desired (array-like) – Array to compare with (possibly with attached units) • rtol (float, optional) – Relative tolerance, defaults to 1e-7 • atol (float or quantity, optional) – Absolute tolerance. If units are attached, they must be consistent with the units of actual and desired. If no units are attached, assumes the same units as desired. Defaults to zero. Raises RuntimeError – If units of rtol are not dimensionless See also: unyt.testing.assert_allclose_units()

5.1. Submodules 55 unyt Documentation, Release v2.8.0

Notes

Also accepts additional keyword arguments accepted by numpy.allclose(), see the documentation of that function for details.

Examples

>>> import unyt asu >>> actual=[1e-5, 1e-3, 1e-1] *u.m >>> desired= actual.to("cm") >>> allclose_units(actual, desired) True

5.1.2 unyt.dimensions module

Dimensions of physical quantities unyt.dimensions.mass = (mass) mass unyt.dimensions.length = (length) length unyt.dimensions.time = (time) time unyt.dimensions.temperature = (temperature) temperature unyt.dimensions.angle = (angle) angle unyt.dimensions.current_mks = (current_mks) current_mks unyt.dimensions.luminous_intensity = (luminous_intensity) luminous_intensity unyt.dimensions.dimensionless = 1 dimensionless unyt.dimensions.logarithmic = (logarithmic) logarithmic unyt.dimensions.base_dimensions = [(mass), (length), (time), (temperature), (angle), (current_mks), 1, (luminous_intensity), (logarithmic)] A list of all of the base dimensions unyt.dimensions.solid_angle = (angle)**2 solid_angle unyt.dimensions.velocity = (length)/(time) velocity unyt.dimensions. = (length)/(time)**2 acceleration unyt.dimensions.jerk = (length)/(time)**3 jerk

56 Chapter 5. unyt package unyt Documentation, Release v2.8.0

unyt.dimensions.snap = (length)/(time)**4 snap unyt.dimensions.crackle = (length)/(time)**5 crackle unyt.dimensions.pop = (length)/(time)**6 pop unyt.dimensions. = (length)**2 area unyt.dimensions. = (length)**3 volume unyt.dimensions. = (length)*(mass)/(time) momentum unyt.dimensions.force = (length)*(mass)/(time)**2 force unyt.dimensions.pressure = (mass)/((length)*(time)**2) pressure unyt.dimensions.energy = (length)**2*(mass)/(time)**2 energy unyt.dimensions.power = (length)**2*(mass)/(time)**3 power unyt.dimensions. = (mass)/(time)**3 flux unyt.dimensions.specific_flux = (mass)/(time)**2 specific_flux unyt.dimensions.number_density = (length)**(-3) number_density unyt.dimensions.density = (mass)/(length)**3 density unyt.dimensions.angular_momentum = (length)**2*(mass)/(time) angular_momentum unyt.dimensions.specific_angular_momentum = (length)**2/(time) specific_angular_momentum unyt.dimensions.specific_energy = (length)**2/(time)**2 specific_energy unyt.dimensions.count_flux = 1/((length)**2*(time)) count_flux unyt.dimensions.count_intensity = 1/((angle)**2*(length)**2*(time)) count_intensity unyt.dimensions.luminous_flux = (angle)**2*(luminous_intensity) luminous_flux unyt.dimensions.luminance = (luminous_intensity)/(length)**2 luminance

5.1. Submodules 57 unyt Documentation, Release v2.8.0

unyt.dimensions.charge_cgs = (length)**(3/2)*sqrt((mass))/(time) charge_cgs unyt.dimensions.current_cgs = (length)**(3/2)*sqrt((mass))/(time)**2 current_cgs unyt.dimensions.electric_field_cgs = sqrt((mass))/(sqrt((length))*(time)) electric_field_cgs unyt.dimensions.magnetic_field_cgs = sqrt((mass))/(sqrt((length))*(time)) magnetic_field_cgs unyt.dimensions.electric_potential_cgs = sqrt((length))*sqrt((mass))/(time) electric_potential_cgs unyt.dimensions.resistance_cgs = (time)/(length) resistance_cgs unyt.dimensions.magnetic_flux_cgs = (length)**(3/2)*sqrt((mass))/(time) magnetic_flux_cgs unyt.dimensions.charge = (current_mks)*(time) charge unyt.dimensions.charge_mks = (current_mks)*(time) charge unyt.dimensions.electric_field = (length)*(mass)/((current_mks)*(time)**3) electric_field unyt.dimensions.electric_field_mks = (length)*(mass)/((current_mks)*(time)**3) electric_field unyt.dimensions.magnetic_field = (mass)/((current_mks)*(time)**2) magnetic_field unyt.dimensions.magnetic_field_mks = (mass)/((current_mks)*(time)**2) magnetic_field unyt.dimensions.electric_potential = (length)**2*(mass)/((current_mks)*(time)**3) electric_potential unyt.dimensions.electric_potential_mks = (length)**2*(mass)/((current_mks)*(time)**3) electric_potential unyt.dimensions.resistance = (length)**2*(mass)/((current_mks)**2*(time)**3) resistance unyt.dimensions.resistance_mks = (length)**2*(mass)/((current_mks)**2*(time)**3) resistance unyt.dimensions.capacitance = (current_mks)**2*(time)**4/((length)**2*(mass)) capacitance unyt.dimensions.capacitance_mks = (current_mks)**2*(time)**4/((length)**2*(mass)) capacitance unyt.dimensions.magnetic_flux = (length)**2*(mass)/((current_mks)*(time)**2) magnetic_flux unyt.dimensions.magnetic_flux_mks = (length)**2*(mass)/((current_mks)*(time)**2) magnetic_flux

58 Chapter 5. unyt package unyt Documentation, Release v2.8.0

unyt.dimensions.inductance = (length)**2*(mass)/((current_mks)**2*(time)**2) inductance unyt.dimensions.inductance_mks = (length)**2*(mass)/((current_mks)**2*(time)**2) inductance unyt.dimensions.derived_dimensions = [1/(time), (length)/(time), (length)/(time)**2, (length)/(time)**3, (length)/(time)**4, (length)/(time)**5, (length)/(time)**6, (length)*(mass)/(time), (length)*(mass)/(time)**2, (length)**2*(mass)/(time)**2, (length)**2*(mass)/(time)**3, (length)**(3/2)*sqrt((mass))/(time), sqrt((mass))/(sqrt((length))*(time)), sqrt((mass))/(sqrt((length))*(time)), (angle)**2, (mass)/(time)**3, (mass)/(time)**2, (length)**3, (angle)**2*(luminous_intensity), (length)**2, (length)**(3/2)*sqrt((mass))/(time)**2, (current_mks)*(time), (length)*(mass)/((current_mks)*(time)**3), (mass)/((current_mks)*(time)**2), sqrt((length))*sqrt((mass))/(time), (length)**2*(mass)/((current_mks)*(time)**3), (time)/(length), (length)**2*(mass)/((current_mks)**2*(time)**3), (length)**2*(mass)/((current_mks)*(time)**2), (length)**(3/2)*sqrt((mass))/(time), (luminous_intensity)/(length)**2, 1/(length)] a list containing all derived_dimensions unyt.dimensions.dimensions = [(mass), (length), (time), (temperature), (angle), (current_mks), 1, (luminous_intensity), (logarithmic), 1/(time), (length)/(time), (length)/(time)**2, (length)/(time)**3, (length)/(time)**4, (length)/(time)**5, (length)/(time)**6, (length)*(mass)/(time), (length)*(mass)/(time)**2, (length)**2*(mass)/(time)**2, (length)**2*(mass)/(time)**3, (length)**(3/2)*sqrt((mass))/(time), sqrt((mass))/(sqrt((length))*(time)), sqrt((mass))/(sqrt((length))*(time)), (angle)**2, (mass)/(time)**3, (mass)/(time)**2, (length)**3, (angle)**2*(luminous_intensity), (length)**2, (length)**(3/2)*sqrt((mass))/(time)**2, (current_mks)*(time), (length)*(mass)/((current_mks)*(time)**3), (mass)/((current_mks)*(time)**2), sqrt((length))*sqrt((mass))/(time), (length)**2*(mass)/((current_mks)*(time)**3), (time)/(length), (length)**2*(mass)/((current_mks)**2*(time)**3), (length)**2*(mass)/((current_mks)*(time)**2), (length)**(3/2)*sqrt((mass))/(time), (luminous_intensity)/(length)**2, 1/(length)] a list containing all dimensions unyt.dimensions.em_dimensions = {(mass)/((current_mks)*(time)**2): sqrt((mass))/(sqrt((length))*(time)), (length)**2*(mass)/((current_mks)*(time)**2): (length)**(3/2)*sqrt((mass))/(time), (current_mks)*(time): (length)**(3/2)*sqrt((mass))/(time), (current_mks): (length)**(3/2)*sqrt((mass))/(time)**2, (length)**2*(mass)/((current_mks)*(time)**3): sqrt((length))*sqrt((mass))/(time), (length)**2*(mass)/((current_mks)**2*(time)**3): (time)/(length), sqrt((mass))/(sqrt((length))*(time)): (mass)/((current_mks)*(time)**2), (length)**(3/2)*sqrt((mass))/(time): (current_mks)*(time), (length)**(3/2)*sqrt((mass))/(time)**2: (current_mks), sqrt((length))*sqrt((mass))/(time): (length)**2*(mass)/((current_mks)*(time)**3), (time)/(length): (length)**2*(mass)/((current_mks)**2*(time)**3)} a dict containing a bidirectional mapping from mks dimension to cgs dimension unyt.dimensions.accepts(**arg_units) Decorator for checking units of function arguments. Parameters arg_units (dict) – Mapping of function arguments to dimensions, of the form ‘arg1’=dimension1 etc where 'arg1' etc are the function arguments and dimension1 etc are SI base units (or combination of units), eg. length/time.

Notes

Keyword args are not dimensionally check, being directly passed to the decorated function. Function arguments that don’t have attached units can be skipped can bypass dimensionality checking by not being passed to the decorator. See baz in the examples, where a has no units.

Examples

>>> import unyt asu >>> from unyt.dimensions import length, time >>> @accepts(a=time, v=length/time) ... def foo(a, v): ... return a * v ... >>> res= foo(a=2 * u.s, v=3 * u.m/u.s) >>> print(res) 6 m >>> @accepts(a=length, v=length/time) ... def bar(a, v): ... return a * v ... >>> bar(a=2 * u.s, v=3 * u.m/u.s) Traceback (most recent call last): ... TypeError: arg 'a=2 s' does not match (length) >>> @accepts(v=length/time) ... def baz(a, v): ... return a * v ... >>> res= baz(a=2, v=3 * u.m/u.s) >>> print(res) 6 m/s

unyt.dimensions.returns(r_unit) Decorator for checking function return units.

5.1. Submodules 59 unyt Documentation, Release v2.8.0

Parameters r_unit (sympy.core.symbol.Symbol) – SI base unit (or combination of units), eg. length/time of the value returned by the original function

Examples

>>> import unyt asu >>> from unyt.dimensions import length, time >>> @returns(length) ... def f(a, v): ... return a * v ... >>> res= f(a=2 * u.s, v=3 * u.m/u.s) >>> print(res) 6 m >>> @returns(length/time) ... def f(a, v): ... return a * v ... >>> f(a=2 * u.s, v=3 * u.m/u.s) Traceback (most recent call last): ... TypeError: result '6 m' does not match (length)/(time)

5.1.3 unyt.equivalencies module

Equivalencies between different kinds of units class unyt.equivalencies.Equivalence(in_place=False) Bases: object convert(x, new_dims, **kwargs) class unyt.equivalencies.NumberDensityEquivalence(in_place=False) Bases: unyt.equivalencies.Equivalence Equivalence between mass and number density, given a mean molecular weight. Given a number density 푛, the mass density 휌 is:

휌 = 휇푚H푛

And similarly

−1 푛 = 휌(휇푚H)

Parameters mu (float) – The mean molecular weight. Defaults to 0.6 whcih is valid for fully ionized gas with primordial composition.

Example

>>> print(NumberDensityEquivalence()) number density: density <-> number density >>> from unyt import Msun, pc >>> rho=3 *Msun/pc**3 >>> rho.to_equivalent('cm**-3','number_density', mu=1.4) unyt_quantity(86.64869896, 'cm**(-3)')

60 Chapter 5. unyt package unyt Documentation, Release v2.8.0

type_name = 'number_density' class unyt.equivalencies.ThermalEquivalence(in_place=False) Bases: unyt.equivalencies.Equivalence Equivalence between temperature and energy via the Given a temperature 푇 in an (e.g. Kelvin or Rankine), the equivalent 퐸 for that temperature is given by:

퐸 = 푘퐵푇 And

푇 = 퐸/푘퐵

Where 푘퐵 is Boltzmann’s constant.

Example

>>> print(ThermalEquivalence()) thermal: temperature <-> energy >>> from unyt import Kelvin >>> temp= 1e6 *Kelvin >>> temp.to_equivalent('keV','thermal') unyt_quantity(0.08617332, 'keV')

type_name = 'thermal' class unyt.equivalencies.MassEnergyEquivalence(in_place=False) Bases: unyt.equivalencies.Equivalence Equivalence between mass and energy in Given a body with mass 푚, the self-energy 퐸 of that mass is given by 퐸 = 푚푐2 where 푐 is the speed of .

Example

>>> print(MassEnergyEquivalence()) mass_energy: mass <-> energy >>> from unyt import g >>> (3.5*g).to_equivalent('J','mass_energy') unyt_quantity(3.14564313e+14, 'J')

type_name = 'mass_energy' class unyt.equivalencies.SpectralEquivalence(in_place=False) Bases: unyt.equivalencies.Equivalence Equivalence between wavelength, frequency, and energy of a photon. Given a photon with wavelength 휆, spatial frequency 휈¯, frequency 휈 and Energy 퐸, these quantities are related by the following forumlae: 퐸 = ℎ휈 = ℎ푐/휆 = ℎ푐휈¯ where ℎ is Planck’s constant and 푐 is the .

5.1. Submodules 61 unyt Documentation, Release v2.8.0

Example

>>> print(SpectralEquivalence()) spectral: length <-> spatial_frequency <-> frequency <-> energy >>> from unyt import angstrom, km >>> (3*angstrom).to_equivalent('keV','spectral') unyt_quantity(4.13280644, 'keV') >>> (1*km).to_equivalent('MHz','spectral') unyt_quantity(0.29979246, 'MHz')

type_name = 'spectral' class unyt.equivalencies.SoundSpeedEquivalence(in_place=False) Bases: unyt.equivalencies.Equivalence Equivalence between the sound speed, temperature, and thermal energy of an ideal gas

For an ideal gas with sound speed 푐푠, temperature 푇 , and thermal energy 퐸, the following equalities will hold: √︃ 훾푘퐵푇 푐푠 = 휇푚H

and

2 퐸 = 푐푠휇푚H/훾 = 푘퐵푇

where 푘퐵 is Boltzmann’s constant, 휇 is the mean molecular weight of the gas, and 훾 is the ratio of specific heats. Parameters • gamma (float) – The ratio of specific heats. Defaults to 5/3, which is correct for monatomic species. • mu (float) – The mean molecular weight. Defaults to 0.6, which is valid for fully ionized gas with primordial composition.

Example

>>> print(SoundSpeedEquivalence()) sound_speed (ideal gas): velocity <-> temperature <-> energy >>> from unyt import Kelvin, km, s >>> hot= 1e6 *Kelvin >>> hot.to_equivalent('km/s','sound_speed') unyt_quantity(151.37249927, 'km/s') >>> hot.to_equivalent('keV','sound_speed') unyt_quantity(0.08617332, 'keV') >>> cs= 100 *km/s >>> cs.to_equivalent('K','sound_speed') unyt_quantity(436421.39881617, 'K') >>> cs.to_equivalent('keV','sound_speed') unyt_quantity(0.03760788, 'keV')

type_name = 'sound_speed' class unyt.equivalencies.LorentzEquivalence(in_place=False) Bases: unyt.equivalencies.Equivalence Equivalence between velocity and the Lorentz gamma factor.

62 Chapter 5. unyt package unyt Documentation, Release v2.8.0

For a body with velocity 푣, the Lorentz gamma factor, 훾 is 1 훾 = √︀1 − 푣2/푐2

ans similarly 푐 푣 = √︀1 − 훾2

where 푐 is the speed of light.

Example

>>> print(LorentzEquivalence()) lorentz: velocity <-> dimensionless >>> from unyt import c, dimensionless >>> v= 0.99 *c >>> print(v.to_equivalent('','lorentz')) 7.088812050083393 dimensionless >>> fast= 99.9 *dimensionless >>> fast.to_equivalent('c','lorentz') unyt_quantity(0.9999499, 'c') >>> fast.to_equivalent('km/s','lorentz') unyt_quantity(299777.43797656, 'km/s')

type_name = 'lorentz' class unyt.equivalencies.SchwarzschildEquivalence(in_place=False) Bases: unyt.equivalencies.Equivalence Equivalence between the mass and radius of a Schwarzschild black hole A Schwarzschild black hole of mass 푀 has radius 푅 2퐺푀 푅 = 푐2 and similarly

푅푐2 푀 = 2퐺 where 퐺 is Newton’s and 푐 is the speed of light.

Example

>>> print(SchwarzschildEquivalence()) schwarzschild: mass <-> length >>> from unyt import Msun, AU >>> (10*Msun).to_equivalent('km','schwarzschild') unyt_quantity(29.53161626, 'km') >>> (1*AU).to_equivalent('Msun','schwarzschild') unyt_quantity(50656851.7815179, 'Msun')

type_name = 'schwarzschild'

5.1. Submodules 63 unyt Documentation, Release v2.8.0 class unyt.equivalencies.ComptonEquivalence(in_place=False) Bases: unyt.equivalencies.Equivalence Equivalence between the Compton wavelength of a particle and its mass.

휆푐 = ℎ/푚푐

Example

>>> print(ComptonEquivalence()) compton: mass <-> length >>> from unyt import me, fm >>> me.to_equivalent('angstrom','compton') unyt_quantity(0.0242631, 'Å') >>> (10*fm).to_equivalent('me','compton') unyt_quantity(242.63102371, 'me')

type_name = 'compton' class unyt.equivalencies.EffectiveTemperatureEquivalence(in_place=False) Bases: unyt.equivalencies.Equivalence Equivalence between the emmitted flux accross all wavelengths and temperature of a blackbody For a blackbody emitter with Temperature 푇 emitting radiation with a flux 퐹 , the following equality holds: F = sigma T^4 where 휎 is the Stefan-Boltzmann constant.

Example

>>> print(EffectiveTemperatureEquivalence()) effective_temperature: flux <-> temperature >>> from unyt import K, W, m >>> (5000.*K).to_equivalent('W/m**2','effective_temperature') unyt_quantity(35439831.25, 'W/m**2') >>> (100.*W/m**2).to_equivalent('K','effective_temperature') unyt_quantity(204.92601414, 'K')

type_name = 'effective_temperature'

5.1.4 unyt.exceptions module

Exception classes defined by unyt exception unyt.exceptions.UnitOperationError(operation, unit1, unit2=None) Bases: ValueError An exception that is raised when unit operations are not allowed

Example

64 Chapter 5. unyt package unyt Documentation, Release v2.8.0

>>> import unyt asu >>> 3*u.g+4 *u.m # doctest: +IGNORE_EXCEPTION_DETAIL +NORMALIZE_WHITESPACE Traceback (most recent call last): ... unyt.exceptions.UnitOperationError: The operator for unyt_arrays with units "g" (dimensions "(mass)") and "m" (dimensions "(length)") is not well defined. exception unyt.exceptions.UnitConversionError(unit1, dimension1, unit2, dimension2) Bases: Exception An error raised when converting to a unit with different dimensions.

Example

>>> import unyt asu >>> data=3 *u.g >>> data.to('m') # doctest: +IGNORE_EXCEPTION_DETAIL +NORMALIZE_WHITESPACE Traceback (most recent call last): ... unyt.exceptions.UnitConversionError: Cannot convert between 'g' (dim '(mass)') and 'm' (dim '(length)'). exception unyt.exceptions.MissingMKSCurrent(unit_system_name) Bases: Exception Raised when querying a unit system for MKS current dimensions Since current is a base dimension for SI or SI-like unit systems but not in CGS or CGS-like unit systems, dimensions that include the MKS current dimension (the dimension of ampere) are not representable in CGS- like unit systems. When a CGS-like unit system is queried for such a dimension, this error is raised.

Example

>>> from unyt.unit_systems import cgs_unit_system as us >>> from unyt import ampere >>> us[ampere.dimensions] # doctest: +IGNORE_EXCEPTION_DETAIL +NORMALIZE_

˓→WHITESPACE Traceback (most recent call last): ... unyt.exceptions.MissingMKSCurrent: The cgs unit system does not have a MKS current base unit exception unyt.exceptions.MKSCGSConversionError Bases: Exception Raised when conversion between MKS and CGS units cannot be performed This error is raised and caught internally and will expose itself to the user as part of a chained exception leading to a UnitConversionError. exception unyt.exceptions.UnitsNotReducible(unit, units_base) Bases: Exception Raised when a unit cannot be safely represented in a unit system

5.1. Submodules 65 unyt Documentation, Release v2.8.0

Example

>>> from unyt import A, cm >>> data= 12 *A/cm >>> data.in_cgs() # doctest: +IGNORE_EXCEPTION_DETAIL +NORMALIZE_WHITESPACE Traceback (most recent call last): ... unyt.exceptions.UnitsNotReducible: The unit "A/cm" (dimensions "(current_mks)/(length)") cannot be reduced to an expression within the cgs system of units. exception unyt.exceptions.IterableUnitCoercionError(quantity_list) Bases: Exception Raised when an iterable cannot be converted to a unyt_array

Example

>>> from unyt import km, cm, unyt_array >>> data=[2 *cm,3 *km] >>> unyt_array(data) # doctest: +IGNORE_EXCEPTION_DETAIL +NORMALIZE_WHITESPACE Traceback (most recent call last): ... unyt.exceptions.IterableUnitCoercionError: Received a list or tuple of quantities with nonuniform units: [unyt_quantity(2., 'cm'), unyt_quantity(3., 'km')] exception unyt.exceptions.InvalidUnitEquivalence(equiv, unit1, unit2) Bases: Exception Raised an equivalence does not apply to a unit conversion

Example

>>> import unyt asu >>> data= 12 *u.g >>> data.to('erg', equivalence='thermal') # doctest: +IGNORE_EXCEPTION_DETAIL

˓→+NORMALIZE_WHITESPACE Traceback (most recent call last): ... unyt.exceptions.InvalidUnitEquivalence: The unit equivalence 'thermal' does not exist for the units 'g' and 'erg'. exception unyt.exceptions.InvalidUnitOperation Bases: Exception Raised when an operation on a unit object is not allowed

Example

>>> from unyt import cm, g >>> cm+g # doctest: +IGNORE_EXCEPTION_DETAIL +NORMALIZE_WHITESPACE Traceback (most recent call last): ... (continues on next page)

66 Chapter 5. unyt package unyt Documentation, Release v2.8.0

(continued from previous page) unyt.exceptions.InvalidUnitOperation: addition with unit objects is not allowed exception unyt.exceptions.SymbolNotFoundError Bases: Exception Raised when a unit name is not available in a unit registry

Example

>>> from unyt.unit_registry import default_unit_registry >>> default_unit_registry['made_up_unit'] # doctest: +IGNORE_EXCEPTION_DETAIL

˓→+NORMALIZE_WHITESPACE Traceback (most recent call last): ... unyt.exceptions.SymbolNotFoundError: The symbol 'made_up_unit' does not exist in this registry. exception unyt.exceptions.UnitParseError Bases: Exception Raised when a string unit name is not parseable as a valid unit

Example

>>> from unyt import Unit >>> Unit('hello') # doctest: +IGNORE_EXCEPTION_DETAIL +NORMALIZE_WHITESPACE Traceback (most recent call last): ... unyt.exceptions.UnitParseError: Could not find unit symbol 'hello' in the provided symbols. exception unyt.exceptions.IllDefinedUnitSystem(units_map) Bases: Exception Raised when the dimensions of the base units of a unit system are inconsistent.

Example

>>> from unyt.unit_systems import UnitSystem >>> UnitSystem('atomic','nm','fs','nK','rad') # doctest: +IGNORE_EXCEPTION_

˓→DETAIL +NORMALIZE_WHITESPACE Traceback (most recent call last): ... unyt.exceptions.IllDefinedUnitSystem: Cannot create unit system with inconsistent mapping from dimensions to units. Received: OrderedDict([((length), nm), ((mass), fs), ((time), nK), ((temperature), rad), ((angle), rad), ((current_mks), A), ((luminous_intensity), cd)])

5.1. Submodules 67 unyt Documentation, Release v2.8.0

5.1.5 unyt.mpl_interface module

Matplotlib offers support for custom classes, such as unyt_array, allowing customization of axis information and unit conversion. In the case of unyt, the axis label is set based on the unyt_array.name and unyt_array.units attributes. It is also possible to convert the plotted units. This feature is optional and has to be enabled using the matplotlib_support context manager. class unyt.mpl_interface.matplotlib_support(label_style=’()’) Bases: object Context manager for enabling the feature When used in a with statement, the feature is enabled during the context and then disabled after it exits. Parameters label_style (str) – One of the following set, {'()', '[]', '/'}. These choices correspond to the following unit labels: • '()' -> '(unit)' • '[]' -> '[unit]' • '/' -> 'q_x / unit' label_style One of the following set, {'()', '[]', '/'}. These choices correspond to the following unit labels: • '()' -> '(unit)' • '[]' -> '[unit]' • '/' -> 'q_x / unit'

Type str

enable() disable()

5.1.6 unyt.physical_constants module

Predefined useful physical constants Note that all of these names can be imported from the top-level unyt namespace. For example:

>>> from unyt.physical_constants import gravitational_constant, solar_mass >>> from unyt import AU >>> from math import pi >>> >>> period=2 * pi * ((1 * AU)**3/ (gravitational_constant * solar_mass))**0.5 >>> period.in_units('day') unyt_quantity(365.26236846, 'day')

Constant Name Value Alternate Names me 9.1094e-31 kg mass_electron, electron_mass amu 1.6605e-27 kg atomic_mass_unit Na 0.9999999282021593 dimensionless Avogadros_number, avogadros_number mp 1.6726e-27 kg proton_mass, mass_proton mh 1.6737e-27 kg hydrogen_mass, mass_hydrogen Continued on next page

68 Chapter 5. unyt package unyt Documentation, Release v2.8.0

Table 1 – continued from previous page Constant Name Value Alternate Names c 2.9979e+08 m/s clight, speed_of_light 휎_T 6.6525e-29 m**2 sigma_thompson, thompson_cross_section, cross_section_thompson qp 1.6022e-19 C proton_charge, elementary_charge, charge_proton qe -1.6022e-19 C electron_charge, charge_electron kb 1.3806e-23 kg*m**2/(K*s**2) kboltz, boltzmann_constant G 6.6741e-11 m**3/(kg*s**2) newtons_constant, gravitational_constant h 6.6261e-34 kg*m**2/s planck_constant hbar 1.0546e-34 kg*m**2/s reduced_planck_constant 휎 5.6704e-08 kg/(K**4*s**3) stefan_boltzmann_constant Tcmb 2.726 K CMB_temperature Msun 1.9884e+30 kg msun, m_sun, m_Sun, M_sun, M_Sun, solar_mass, mass_sun Mjup 1.8985e+27 kg mjup, jupiter_mass, mass_jupiter mercury_mass 3.3010e+23 kg mass_mercury venus_mass 4.8673e+24 kg mass_venus Mearth 6.0456e+24 kg mearth, earth_mass, mass_earth mars_mass 6.4169e+23 kg mass_mars saturn_mass 5.6846e+26 kg mass_saturn uranus_mass 8.6819e+25 kg mass_uranus neptune_mass 1.0243e+26 kg mass_neptune m_pl 2.1765e-08 kg planck_mass l_pl 1.6162e-35 m planck_length t_pl 5.3912e-44 s planck_time E_pl 1.9561e+09 J planck_energy q_pl 1.8755e-18 C planck_charge T_pl 1.4168e+32 K planck_temperature mu_0 1.2566e-06 kg*m/(A**2*s**2) vacuum_permeability, magnetic_constant, 휇_0 eps_0 8.8542e-12 A**2*s**4/(kg*m**3) vacuum_permittivity, electric_constant, 휖_0, epsilon_0 standard_gravity 9.80665 m/s**2

5.1.7 unyt.testing module

Utilities for writing tests unyt.testing.assert_allclose_units(actual, desired, rtol=1e-07, atol=0, **kwargs) Raise an error if two objects are not equal up to desired tolerance This is a wrapper for numpy.testing.assert_allclose() that also verifies unit consistency Parameters • actual (array-like) – Array obtained (possibly with attached units) • desired (array-like) – Array to compare with (possibly with attached units) • rtol (float, optional) – Relative tolerance, defaults to 1e-7 • atol (float or quantity, optional) – Absolute tolerance. If units are attached, they must be consistent with the units of actual and desired. If no units are attached, assumes the same units as desired. Defaults to zero. See also: unyt.array.allclose_units()

5.1. Submodules 69 unyt Documentation, Release v2.8.0

Notes

Also accepts additional keyword arguments accepted by numpy.testing.assert_allclose(), see the documentation of that function for details.

Examples

>>> import unyt asu >>> actual=[1e-5, 1e-3, 1e-1] *u.m >>> desired= actual.to("cm") >>> assert_allclose_units(actual, desired)

5.1.8 unyt.unit_object module

A class that represents a unit symbol. class unyt.unit_object.Unit Bases: object A symbolic unit, using sympy functionality. We only add “dimensions” so that sympy understands relations between different units. is_positive = True is_commutative = True is_number = False latex_repr A LaTeX representation for the unit

Examples

>>> from unyt import g, cm >>> (g/cm**3).units.latex_repr '\\frac{\\rm{g}}{\\rm{cm}^{3}}'

units copy() same_dimensions_as(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

is_dimensionless Is this a dimensionless unit?

70 Chapter 5. unyt package unyt Documentation, Release v2.8.0

Returns Return type True for a dimensionless unit, False otherwise

Examples

>>> from unyt import count, kg >>> count.units.is_dimensionless True >>> kg.units.is_dimensionless False

is_code_unit Is this a “code” unit? Returns • True if the unit consists of atom units that being with “code”. • False otherwise list_equivalencies() 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

has_equivalent(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

get_base_equivalent(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

get_cgs_equivalent() Create and return dimensionally-equivalent cgs units.

5.1. Submodules 71 unyt Documentation, Release v2.8.0

Example

>>> from unyt import kg, m >>> (kg/m**3).get_cgs_equivalent() g/cm**3

get_mks_equivalent() Create and return dimensionally-equivalent mks units.

Example

>>> from unyt import g, cm >>> (g/cm**3).get_mks_equivalent() kg/m**3

get_conversion_factor(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)

latex_representation() A LaTeX representation for the unit

Examples

>>> from unyt import g, cm >>> (g/cm**3).latex_representation() '\\frac{\\rm{g}}{\\rm{cm}^{3}}'

as_coeff_unit() Factor the coefficient multiplying a unit For units that are multiplied by a constant dimensionless coefficient, returns a tuple containing the coeffi- cient and a new unit object for the unmultiplied unit.

72 Chapter 5. unyt package unyt Documentation, Release v2.8.0

Example

>>> import unyt asu >>> unit= (u.m **2/u.cm).simplify() >>> unit 100*m >>> unit.as_coeff_unit() (100.0, m)

simplify() Return a new equivalent unit object with a simplified unit expression

>>> import unyt asu >>> unit= (u.m **2/u.cm).simplify() >>> unit 100*m

base_offset base_value dimensions expr is_Unit is_atomic registry unyt.unit_object.define_unit(symbol, value, tex_repr=None, offset=None, prefixable=False, reg- istry=None) Define a new unit and add it to the specified unit registry. Parameters • symbol (string) – The symbol for the new unit. • value (tuple or unyt.array.unyt_quantity) – The definition of the new unit in terms of some other units. For example, one would define a new “mph” unit with (1.0, "mile/hr") or with 1.0*unyt.mile/unyt.hr • tex_repr (string, optional) – The LaTeX representation of the new unit. If one is not supplied, it will be generated automatically based on the symbol string. • offset (float, optional) – The default offset for the unit. If not set, an offset of 0 is assumed. • prefixable (boolean, optional) – Whether or not the new unit can use SI pre- fixes. Default: False • registry (unyt.unit_registry.UnitRegistry or None) – The unit registry to add the unit to. If None, then defaults to the global default unit registry. If registry is set to None then the unit object will be added as an attribute to the top-level unyt namespace to ease working with the newly defined unit. See the example below.

Examples

5.1. Submodules 73 unyt Documentation, Release v2.8.0

>>> from unyt import day >>> two_weeks= 14.0 *day >>> one_day= 1.0 *day >>> define_unit("two_weeks", two_weeks) >>> from unyt import two_weeks >>> print((3*two_weeks)/one_day) 42.0 dimensionless

5.1.9 unyt.unit_registry module

A registry for units that can be added to and modified. unyt.unit_registry.cached_sympify Successive loads of unit systems produce the same calls to sympify in UnitRegistry.from_json. Even within a single load, this is a net improvement because there will often be a few cache hits class unyt.unit_registry.UnitRegistry(add_default_symbols=True, lut=None, unit_system=None) Bases: object A registry for unit symbols unit_system_id This is a unique identifier for the unit registry created from a FNV hash. It is needed to register a dataset’s code unit system in the unit system registry. prefixable_units add(symbol, base_value, dimensions, tex_repr=None, offset=None, prefixable=False) Add a symbol to this registry. Parameters • symbol (str) – The name of the unit • base_value (float) – The scaling from the units value to the equivalent SI unit with the same dimensions • dimensions (expr) – The dimensions of the unit • tex_repr (str, optional) – The LaTeX representation of the unit. If not provided a LaTeX representation is automatically generated from the name of the unit. • offset (float, optional) – If set, the zero-point offset to apply to the unit to convert to SI. This is mostly used for units like Farhenheit and Celcius that are not defined on an absolute scale. • prefixable (bool) – If True, then SI-prefix versions of the unit will be created along with the unit itself. remove(symbol) Remove the entry for the unit matching symbol. Parameters symbol (str) – The name of the unit symbol to remove from the registry. modify(symbol, base_value) Change the base value of a unit symbol. Useful for adjusting code units after parsing parameters. Parameters • symbol (str) – The name of the symbol to modify

74 Chapter 5. unyt package unyt Documentation, Release v2.8.0

• base_value (float) – The new base_value for the symbol. keys() Print out the units contained in the lookup table. to_json() Returns a json-serialized version of the unit registry classmethod from_json(json_text) Returns a UnitRegistry object from a json-serialized unit registry Parameters json_text (str) – A string containing a json represention of a UnitRegistry list_same_dimensions(unit_object) Return a list of base unit names that this registry knows about that are of equivalent dimensions to unit_object. unyt.unit_registry.default_unit_registry = The default unit registry

5.1.10 unyt.unit_symbols module

Predefined useful aliases to physical units Note that all of these names can be imported from the top-level unyt namespace. For example:

>>> from unyt import cm, g, s >>> data=[3,4,5] *g*cm/s >>> print(data) [3 4 5] cm*g/s

Unit Name Dimensions MKS value CGS Value LaTeX Representation SI Prefixable? Alternate Names m length 1.0 m 100.0 cm \rm{m} True meter, Meter, metre, Metre g mass 0.001 kg 1.0 g \rm{g} True gram, Gram, gramme, Gramme s time 1.0 s 1.0 s \rm{s} True second, Second K temperature 1.0 K 1.0 K \rm{K} True degree_kelvin, Degree_Kelvin, kelvin, Kelvin rad angle 1.0 rad 1.0 rad \rm{rad} True radian, Radian A current_mks 1 A 2.9979e+09 statA \rm{A} True ampere, Ampere, amp, Amp cd luminous_intensity 1.0 cd 1.0 cd \rm{cd} True candela, Candela mol dimensionless 6.0221e+23 dimensionless 6.0221e+23 dimensionless \rm{mol} True mole, Mole dyn force 1.0000e-05 N 1.0 dyn \rm{dyn} True dyne, Dyne erg energy 1.0000e-07 J 1.0 erg \rm{erg} True ergs, Ergs Ba pressure 0.1 Pa 1.0 dyn/cm**2 \rm{Ba} True barye, Barye G magnetic_field_cgs 0.0001 T 1 G \rm{G} True gauss, Gauss statC magnetic_flux_cgs 3.3356e-10 C 1 statC \rm{statC} True statcoulomb, Statcoulomb, esu, ESU, electrostatic_unit, Electrostatic_Unit statA current_cgs 3.3356e-10 A 1 statA \rm{statA} True statampere, Statampere statV electric_potential_cgs 3.3356e-03 V 3.3356e-03 V \rm{statV} True statvolt, Statvolt statohm v 8.9876e+11 Ω 8.9876e+11 Ω \rm{statohm} True Mx magnetic_flux_cgs 3.1623e-05 sqrt(kg)*m**(3/2)/s 1.0 statC \rm{Mx} True maxwell, Maxwell J energy 1.0 J 1.0000e+07 erg \rm{J} True joule, Joule W power 1.0 W 1.0000e+07 erg/s \rm{W} True watt, Watt Hz 1/(time) 1.0 Hz 1.0 1/s \rm{Hz} True hertz, Hertz N force 1.0 N 1.0000e+05 dyn \rm{N} True newton, Newton C charge_mks 1 C 2.9979e+09 statC \rm{C} True coulomb, Coulomb T magnetic_field_mks 1 T 10000.0 G \rm{T} True tesla, Tesla Continued on next page

5.1. Submodules 75 unyt Documentation, Release v2.8.0

Table 2 – continued from previous page Unit Name Dimensions MKS value CGS Value LaTeX Representation SI Prefixable? Alternate Names Pa pressure 1.0 Pa 10.0 dyn/cm**2 \rm{Pa} True pascal, Pascal bar pressure 1.0000e+05 Pa 1.0000e+06 dyn/cm**2 \rm{bar} True V electric_potential_mks 1 V 2.9979e+02 statV \rm{V} True volt, Volt F capacitance_mks 1.0 F N/A \rm{F} True farad, Farad H inductance_mks 1.0 H N/A \rm{H} True henry, Henry Ω k 1 Ω 1.1127e-12 statohm \Omega True ohm, Ohm Wb magnetic_flux_mks 1.0 Wb N/A \rm{Wb} True weber, Weber lm luminous_flux 1.0 lm 1.0 cd*rad**2 \rm{lm} True lumen, Lumen lx (angle)**2*(luminous_intensity)/(length)**2 1.0 cd*rad**2/m**2 0.0001 cd*rad**2/cm**2 \rm{lx} True lux degC temperature 274.15 K 274.15 K ^\circ\rm{C} True degree_celsius, Degree_Celsius, degree_Celsius, celcius, Celcius, celsius, Celsius, °C delta_degC temperature 1.0 K 1.0 K \Delta^\circ\rm{C} True mil length 2.5400e-05 m 0.00254 cm \rm{mil} False thou, Thou, thousandth, Thousandth inch length 0.0254 m 2.54 cm \rm{in} False Inch, in ft length 0.3048 m 30.48 cm \rm{ft} False foot, Foot yd length 0.9144 m 91.44 cm \rm{yd} False yard, Yard mile length 1609.344 m 1.6093e+05 cm \rm{mile} False Mile furlong length 201.168 m 2.0117e+04 cm \rm{fur} False Furlong, fur degF temperature 2.5593e+02 K 2.5593e+02 K ^\circ\rm{F} False Degf, degree_fahrenheit, Degree_Fahrenheit, degree_Fahrenheit, fahrenheit, Fahrenheit, °F delta_degF temperature 5.5556e-01 K 5.5556e-01 K \Delta^\circ\rm{F} False Delta_Degf R temperature 5.5556e-01 K 5.5556e-01 K ^\circ\rm{R} False degree_rankine, Degree_Rankine, rankine, Rankine lbf force 4.4482e+00 N 4.4482e+05 dyn \rm{lbf} False pound_force, Pound_Force kip force 4.4482e+03 N 4.4482e+08 dyn \rm{kip} False kilopound, Kilopound, kipf, Kipf lb mass 4.5359e-01 kg 4.5359e+02 g \rm{lb} False pound, Pound, pound_mass, Pound_Mass, lbm atm pressure 1.0132e+05 Pa 1.0132e+06 dyn/cm**2 \rm{atm} False atmosphere, Atmosphere hp power 7.4570e+02 W 7.4570e+09 erg/s \rm{hp} False horsepower, Horsepower oz mass 2.8350e-02 kg 2.8350e+01 g \rm{oz} False ounce, Ounce ton mass 9.0718e+02 kg 9.0718e+05 g \rm{ton} False slug mass 1.4594e+01 kg 1.4594e+04 g \rm{slug} False Slug cal energy 4.184 J 4.1840e+07 erg \rm{cal} True calorie, Calorie BTU energy 1.0551e+03 J 1.0551e+10 erg \rm{BTU} False british_thermal_unit, British_Thermal_Unit psi pressure 6.8948e+03 Pa 6.8948e+04 dyn/cm**2 \rm{psi} False pounds_per_square_inch, Pounds_Per_Square_Inch ksi pressure 6.8948e+06 Pa 6.8948e+07 dyn/cm**2 \rm{ksi} False kips_per_square_inch, Kips_Per_Square_Inch smoot length 1.7018 m 170.18 cm \rm{smoot} False Smoot dimensionless dimensionless 1.0 dimensionless 1.0 dimensionless False Dimensionless, _, % dimensionless 0.01 dimensionless 0.01 dimensionless \% False percent, Percent min time 60.0 s 60.0 s \rm{min} False minute, Minute hr time 3600.0 s 3600.0 s \rm{hr} False hour, Hour day time 8.6400e+04 s 8.6400e+04 s \rm{d} False d yr time 3.1558e+07 s 3.1558e+07 s \rm{yr} True year, Year c velocity 2.9979e+08 m/s 2.9979e+10 cm/s \rm{c} False Msun mass 1.9884e+30 kg 1.9884e+33 g \rm{M}_\odot False msun, m_sun, M_Sun, M_sun, m_Sun, solar_mass, Solar_Mass, solMass, mass_sun, Mass_Sun Rsun length 6.9550e+08 m 6.9550e+10 cm \rm{R}_\odot False rsun, r_sun, R_Sun, R_sun, r_Sun, solar_radius, Solar_Radius, solRadius Lsun power 3.8270e+26 W 3.8270e+33 erg/s \rm{L}_\odot False lsun, l_sun, L_Sun, L_sun, l_Sun, solar_luminosity, Solar_Luminosity, solLuminosity Tsun temperature 5870.0 K 5870.0 K \rm{T}_\odot False t_sun, T_Sun, tsun, T_sun, t_Sun, solar_temperature, Solar_Temperature, solTemperature Zsun dimensionless 0.01295 dimensionless 0.01295 dimensionless \rm{Z}_\odot False z_sun, Z_Sun, zsun, Z_sun, z_Sun, solar_metallicity, Solar_Metallicity, solMetallicity Mjup mass 1.8985e+27 kg 1.8985e+30 g \rm{M}_{\rm{Jup}} False m_jup, M_Jup, jupiter_mass, Jupiter_Mass Mearth mass 6.0456e+24 kg 6.0456e+27 g \rm{M}_\oplus False m_earth, M_Earth, earth_mass, Earth_Mass Rjup length 6.9911e+07 m 6.9911e+09 cm \rm{R}_\mathrm{Jup} False r_jup, R_Jup, jupiter_radius, Jupiter_Radius Rearth length 6.3710e+06 m 6.3710e+08 cm \rm{R}_\oplus False r_earth, R_Earth, earth_radius, Earth_Radius Continued on next page

76 Chapter 5. unyt package unyt Documentation, Release v2.8.0

Table 2 – continued from previous page Unit Name Dimensions MKS value CGS Value LaTeX Representation SI Prefixable? Alternate Names AU length 1.4960e+11 m 1.4960e+13 cm \rm{AU} False au, astronomical_unit, Astronomical_Unit ly length 9.4605e+15 m 9.4605e+17 cm \rm{ly} False light_year, Light_Year pc length 3.0857e+16 m 3.0857e+18 cm \rm{pc} True parsec, Parsec degree angle 1.7453e-02 rad 1.7453e-02 rad ^\circ False Degree, deg arcmin angle 2.9089e-04 rad 2.9089e-04 rad \rm{arcmin} False Arcmin, arcminute, Arcminute arcsec angle 4.8481e-06 rad 4.8481e-06 rad \rm{arcsec} False Arcsec, arcsecond, Arcsecond mas angle 4.8481e-09 rad 4.8481e-09 rad \rm{mas} False milliarcsecond, Milliarcsecond hourangle angle 2.6180e-01 rad 2.6180e-01 rad \rm{HA} False Hourangle, HA sr (angle)**2 1.0 rad**2 1.0 rad**2 \rm{sr} False steradian, Steradian lat angle 1.5533e+00 rad 1.5533e+00 rad \rm{Latitude} False latitude, Latitude, degree_latitude, Degree_Latitude lon angle 3.1590e+00 rad 3.1590e+00 rad \rm{Longitude} False longitude, Longitude, degree_longitude, Degree_Longitude eV energy 1.6022e-19 J 1.6022e-12 erg \rm{eV} True electronvolt, Electronvolt amu mass 1.6605e-27 kg 1.6605e-24 g \rm{amu} False atomic_mass_unit, Atomic_Mass_Unit Å length 1.0000e-10 m 1.0000e-08 cm \AA False angstrom, Angstrom Jy specific_flux 1.0000e-26 kg/s**2 1.0000e-23 g/s**2 \rm{Jy} True jansky, Jansky counts dimensionless 1.0 dimensionless 1.0 dimensionless \rm{counts} False Counts, count, Count photons dimensionless 1.0 dimensionless 1.0 dimensionless \rm{photons} False Photons, photon, Photon me mass 9.1094e-31 kg 9.1094e-28 g m_e False electron_mass, Electron_Mass mp mass 1.6737e-27 kg 1.6737e-24 g m_p False proton_mass, Proton_Mass Sv specific_energy 1.0 J/kg 10000.0 erg/g \rm{Sv} True sievert, Sievert rayleigh count_intensity 7.9577e+08 1/(m**2*rad**2*s) 7.9577e+04 1/(cm**2*rad**2*s) \rm{R} False Rayleigh lambert luminance 3.1831e+03 cd/m**2 3.1831e-01 cd/cm**2 \rm{L} False Lambert nt luminance 1.0 cd/m**2 0.0001 cd/cm**2 \rm{nt} False nit m_pl mass 2.1765e-08 kg 2.1765e-05 g m_{\rm{P}} False planck_mass, Planck_Mass l_pl length 1.6162e-35 m 1.6162e-33 cm \ell_\rm{P} False planck_length, Planck_Length t_pl time 5.3912e-44 s 5.3912e-44 s t_{\rm{P}} False planck_time, Planck_Time T_pl temperature 1.4168e+32 K 1.4168e+32 K T_{\rm{P}} False planck_temperature, Planck_Temperature q_pl charge_mks 1.8755e-18 C N/A q_{\rm{P}} False planck_charge, Planck_Charge E_pl energy 1.9561e+09 J 1.9561e+16 erg E_{\rm{P}} False planck_energy, Planck_Energy m_geom mass 1.9884e+30 kg 1.9884e+33 g \rm{M}_\odot False l_geom length 1.4766e+03 m 1.4766e+05 cm \rm{M}_\odot False t_geom time 4.9253e-06 s 4.9253e-06 s \rm{M}_\odot False B logarithmic 1.1513e+00 Np 1.1513e+00 Np \rm{B} True bel Np logarithmic 1.0 Np 1.0 Np \rm{Np} True neper, Neper

5.1.11 unyt.unit_systems module

Unit system class. unyt.unit_systems.add_symbols(namespace, registry) Adds the unit symbols from unyt.unit_symbols to a namespace Parameters • namespace (dict) – The dict to insert unit symbols into. The keys will be string unit names and values will be the corresponding unit objects. • registry (unyt.unit_registry.UnitRegistry) – The registry to create units from. Note that if you would like to use a custom unit system, ensure your registry was created using that unit system.

5.1. Submodules 77 unyt Documentation, Release v2.8.0

Example

>>> from unyt.unit_registry import UnitRegistry >>> class MyClass(): ... def __init__(self): ... self.reg= UnitRegistry() ... add_symbols(vars(self), self.reg) >>> foo= MyClass() >>> foo.kilometer km >>> foo.joule J unyt.unit_systems.add_constants(namespace, registry) Adds the quantities from unyt.physical_constants to a namespace Parameters • namespace (dict) – The dict to insert quantities into. The keys will be string names and values will be the corresponding quantities. • registry (unyt.unit_registry.UnitRegistry) – The registry to create units from. Note that if you would like to use a custom unit system, ensure your registry was created using that unit system.

Example

>>> from unyt.unit_registry import UnitRegistry >>> class MyClass(): ... def __init__(self): ... self.reg= UnitRegistry(unit_system='cgs') ... add_constants(vars(self), self.reg) >>> foo= MyClass() >>> foo.gravitational_constant unyt_quantity(6.67408e-08, 'cm**3/(g*s**2)') >>> foo.speed_of_light unyt_quantity(2.99792458e+10, 'cm/s') class unyt.unit_systems.UnitSystem(name, length_unit, mass_unit, time_unit, tempera- ture_unit=’K’, angle_unit=’rad’, current_mks_unit=’A’, luminous_intensity_unit=’cd’, logarithmic_unit=’Np’, registry=None) Bases: object Create a UnitSystem for facilitating conversions to a default set of units. Parameters • name (string) – The name of the unit system. Will be used as the key in the unit_system_registry dict to reference the unit system by. • length_unit (string or unyt.unit_object.Unit) – The base length unit of this unit system. • mass_unit (string or unyt.unit_object.Unit) – The base mass unit of this unit system. • time_unit (string or unyt.unit_object.Unit) – The base time unit of this unit system.

78 Chapter 5. unyt package unyt Documentation, Release v2.8.0

• temperature_unit (string or unyt.unit_object.Unit, optional) – The base temperature unit of this unit system. Defaults to “K”. • angle_unit (string or unyt.unit_object.Unit, optional) – The base angle unit of this unit system. Defaults to “rad”. • mks_system (boolean, optional) – Whether or not this unit system has SI-specific units. Default: False • current_mks_unit (string or unyt.unit_object.Unit, optional) – The base cur- rent unit of this unit system. Defaults to “A”. • luminous_intensity_unit (string or unyt.unit_object.Unit, optional) – The base luminous unit of this unit system. Defaults to “cd”. • registry (unyt.unit_registry.UnitRegistry object) – The unit registry as- sociated with this unit system. Only useful for defining unit systems based on code units. has_current_mks Does this unit system have an MKS current dimension? unyt.unit_systems.cgs_unit_system = cgs Unit System Base Units: length: cm mass: g time: s temperature: K angle: rad luminous_intensity: cd logarithmic: Np Other Units: energy: erg specific_energy: erg/g pressure: dyn/cm**2 force: dyn magnetic_field_cgs: G charge_cgs: statC current_cgs: statA power: erg/s The CGS unit system unyt.unit_systems.mks_unit_system = mks Unit System Base Units: length: m mass: kg time: s temperature: K angle: rad current_mks: A luminous_intensity: cd logarithmic: Np Other Units: energy: J specific_energy: J/kg pressure: Pa force: N magnetic_field: T charge: C frequency: Hz power: W electric_potential: V capacitance: F inductance: H resistance: Ω magnetic_flux: Wb luminous_flux: lm The MKS unit system unyt.unit_systems.imperial_unit_system = imperial Unit System Base Units: length: ft mass: lb time: s temperature: R angle: rad current_mks: A luminous_intensity: cd logarithmic: Np Other Units: force: lbf energy: ft*lbf pressure: lbf/ft**2 power: hp The imperial unit system unyt.unit_systems.galactic_unit_system = galactic Unit System Base Units: length: kpc mass: Msun time: Myr temperature: K angle: rad current_mks: A luminous_intensity: cd logarithmic: Np Other Units: energy: keV magnetic_field_cgs: 휇G The galactic unit system unyt.unit_systems.solar_unit_system = solar Unit System Base Units: length: AU mass: Mearth time: yr temperature: K angle: rad current_mks: A luminous_intensity: cd logarithmic: Np Other Units: The solar unit system unyt.unit_systems.geometrized_unit_system = Base Units: length: l_geom mass: m_geom time: t_geom temperature: K angle: rad current_mks: A luminous_intensity: cd logarithmic: Np Other Units: Geometrized unit system unyt.unit_systems.planck_unit_system = planck Unit System Base Units: length: l_pl mass: m_pl time: t_pl temperature: T_pl angle: rad current_mks: A luminous_intensity: cd logarithmic: Np Other Units: energy: E_pl charge_mks: q_pl Planck unit system

5.1. Submodules 79 unyt Documentation, Release v2.8.0

80 Chapter 5. unyt package CHAPTER 6

Contributing

Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given.

6.1 Code of Conduct

The development of unyt happens in the context of the yt community code of conduct. If for any reason you feel that the code of conduct has been violated in the context of unyt development, please send an e-mail to confidential@yt- project.org with details describing the incident. All emails sent to this address will be treated with the strictest confi- dence by an individual who does not normally participate in yt development.

6.2 Types of Contributions

You can contribute in many ways:

6.2.1 Report Bugs

Report bugs at https://github.com/yt-project/unyt/issues. If you are reporting a bug, please include: • Your operating system name and version. • Any details about your local setup that might be helpful in troubleshooting. This includes things like Python version and versions of any libraries being used, including unyt. • If possible, detailed steps to reproduce the bug.

81 unyt Documentation, Release v2.8.0

6.2.2 Fix Bugs

Look through the GitHub issues for bugs. Anything tagged with “bug” and “help wanted” is open to whoever wants to implement it.

6.2.3 Implement Features

Look through the GitHub issues for features. Anything tagged with “enhancement” and “help wanted” is open to whoever wants to implement it.

6.2.4 Write Documentation

unyt could always use more documentation, whether as part of the official unyt docs, in docstrings, or even on the web in blog posts, articles, and such.

6.2.5 Submit Feedback

The best way to send feedback is to file an issue at https://github.com/yt-project/unyt/issues. If you are proposing a feature: • Explain in detail how it would work. • Keep the scope as narrow as possible, to make it easier to implement. • Remember that this is a volunteer-driven project, and that contributions are welcome :)

6.3 Get Started!

Ready to contribute? Here’s how to set up unyt for local development. The unyt test suite makes use of the tox test runner, which makes it easy to run tests on multiple python versions. However, this means that if all of the python versions needed by tox are not available, many of the tox tests will fail with errors about missing python executables. This guide makes use of pyenv to set up all of the Python versions used in the unyt test suite. You do not have to use pyenv if you have other ways of managing your python evironment using your operating system’s package manager or conda. 1. Fork the unyt repo on GitHub. 2. Clone your fork locally:

$ git clone [email protected]:your_name_here/unyt.git

3. Install pyenv:

$ git clone https://github.com/pyenv/pyenv.git $HOME/.pyenv $ export PYENV_ROOT="$HOME/.pyenv" $ export PATH="$HOME/.pyenv/bin:$PATH $ eval" $(pyenv init -)" $ pyenv install -s 3.5.9 $ pyenv install -s 3.6.10 $ pyenv install -s 3.7.6 (continues on next page)

82 Chapter 6. Contributing unyt Documentation, Release v2.8.0

(continued from previous page) $ pyenv install -s 3.8.1 $ pip install tox tox-pyenv

3. Install your local copy into a virtualenv or conda environment. You can also use one of the python interpreters we installed using pyenv:

$ cd unyt/ $ pyenv local3.8.1 $ python setup.py develop

4. Create a branch for local development:

$ git checkout -b name-of-your-bugfix-or-feature

5. Edit files in the unyt repository, using your local python installation to test your edits. 5. When you’re done making changes, check that your changes pass flake8, format the code with black, and run the tests, including testing several Python versions with tox:

$ flake8 unyt $ black ./ $ pytest --doctest-modules --doctest-rst --doctest-plus $ pyenv local3.5.93.6.103.7.63.8.1 $ tox $ pyenv local3.8.1

To get flake8, black, pytest, pytest-doctestplus, and tox, just pip or conda install them into your python environment, as appropriate. For a pyenv environment you would use pip. 6. Commit your changes and push your branch to GitHub:

$ git add . $ git commit -m "Your detailed description of your changes." $ git push origin name-of-your-bugfix-or-feature

7. Submit a pull request through the GitHub website.

6.4 Testing unyt

We use the pytest test runner as well as the tox test wrapper to manage running tests on various versions of python. To run the tests on your copy of the unyt repository using your current python evironment, run pytest in the root of the repository using the following arguments:

$ cd unyt/ $ pytest --doctest-modules --doctest-rst --doctest-plus

These enable testing the docstrings and doctest examples scattered throughout the unyt and its documentation. You will need to install pytest and pytest-doctestplus to run this command. Some tests depend on h5py, Pint, astropy, matplotlib black, and flake8 being installed. If you would like to run the tests on multiple python versions, first ensure that you have multiple python versions visible on your $PATH, then simply execute tox in the root of the unyt repository. For example, using the pyenv environment we set up above:

6.4. Testing unyt 83 unyt Documentation, Release v2.8.0

$ cd unyt $ pyenv local3.5.93.6.103.7.63.8.1 $ tox

The tox package itself can be installed using the pip associated with one of the python installations. See the tox. ini file in the root of the repository for more details about our tox setup. Note that you do not need to install anything besides tox and the python versions needed by tox for this to work, tox will handle setting up the test environment, including installing any necessary dependencies via pip.

6.5 Pull Request Guidelines

Before you submit a pull request, check that it meets these guidelines: 1. The pull request should include tests for functionality that is not already tested. We strive for 100% test coverage and pull requests should not add any new untested code. Use the codecov.io reports on the pull request to gauge coverage. You can also generate coverage reports locally by running the tox tests. 2. If the pull request adds functionality the docs should be updated. If your new functionality adds new functions or classes to the public API, please add docstrings. If you modified an existing function or class in the public API, please update the existing docstrings. If you modify private implementation details, please use your judgment on documenting it with comments or docstrings. 3. The pull request should work for Python 3.5, 3.6, 3.7, and 3.8. Check in the GitHub interface for your pull request and make sure that the tests pass for all supported Python versions.

6.6 Deploying

A reminder for the maintainers on how to deploy. Make sure all your changes are committed (including an entry in HISTORY.rst and adding any new contributors to AUTHORS.rst). Then run:

$ git tag v1.x.x $ git push upstream master --tags

If the tests pass you can then subsequently manually upload to PyPi:

$ rm -r build dist $ python setup.py sdist bdist_wheel --universal $ twine upload dist/*

84 Chapter 6. Contributing CHAPTER 7

Citing unyt

If you make use of unyt in work that leads to a publication we would appreciate a mention in the text of the paper or in the acknowledgements along with a citation to our paper in the Journal of Open Source Software. You can use the following BibTeX:

@article{Goldbaum2018, doi={10.21105/joss.00809}, url= {https://doi.org/10.21105/joss.00809}, year={2018}, month= {aug}, publisher= {The Open Journal}, volume={3}, number={28}, pages={809}, author= {Nathan J. Goldbaum and John A. ZuHone and Matthew J. Turk and Kacper

˓→Kowalik and Anna L. Rosen}, title= {unyt: Handle, manipulate, and convert data with units in Python}, journal= {Journal of Open Source Software} }

Or the following citation format: Goldbaum et al., (2018). unyt: Handle, manipulate, and convert data with units in Python . Journal of Open Source Software, 3(28), 809, https://doi.org/10.21105/joss.00809

85 unyt Documentation, Release v2.8.0

86 Chapter 7. Citing unyt CHAPTER 8

Credits

8.1 Contributors

• Ricarda Beckmann • Andrei Berceanu • Josh Borrow • Yi-Hao Chen • Bili Dong • Nathan Goldbaum • David Hannasch • Cameron Hummels • Thomas Hisch • Paul Ivanov • Suoqing Ji • Lee Johnston • Ben Kimock • Kacper Kowalik • Nathan Musoke • Andrew Myers • Simon Schopferer • Sam Skillman • Britton Smith • Josh Soref

87 unyt Documentation, Release v2.8.0

• Kyle Sunden • Ben Thompson • Matthew Turk • Miguel de Val-Borro • John ZuHone This library was adapted from dimensionful which was written by Casey Stark .

88 Chapter 8. Credits CHAPTER 9

History

9.1 2.8.0 (2020-10-05)

• Dropped support for Python 3.5. • Add delta_degC and delta_degF units to support temperature difference arithmetic. See PR #152. Thank you to Lee Johnston (@l-johnston on GitHub) for the contribution. • Fix an issue where a subsequent load of the unit registry with units that are equal but not identical leads to a crash. See PR #158. Thank you to Matthew Turk (@matthewturk on GitHub) for the initial bug report and fix. • Add force unit kip and pressure unit psi. Thank you to P. Talley (@otaithleigh on GitHub) for the contribution. See PR #162. • Fix an issue where arithmetic operations on units defined in different registries and having the conversion defined in one direction would lead to a crash. See PR #164. Thank you to Clément Robert (@neutrinoceros on GitHub) for the initial bug report and fix.

9.2 2.7.2 (2020-06-29)

• The unyt.returns and unyt.accepts decorators now work correctly for functions that accept or return data with dimensionless units. See PR #146. Thank you to Simon Schopferer (@simfinite on GitHub) for the initial bug report and fix. • Data used in the tests are packaged with the source distribution and unyt.test() is now itself run as part of unyt’s continuous integration tests. See PR #149 and PR #150. Thank you to Miguel de Val-Borro (@migueldvb on GitHub) for the initial bug report and fix. • The degC and degF units now render as °C and °F by default, °C and °F are now recognized as valid unit names as well. Thank you to Lee Johnston (@l-johnston on GitHub) for the contribution. • Use a more canonical representation of the micro symbol when printing units with the micro prefix, avoid- ing issues with displaying unit names in Matplotlib plot labels. See PR #153. Thank you to Matthew Turk (@matthewturk on GitHub) for the bug report and fix.

89 unyt Documentation, Release v2.8.0

• Add more alternative spellings for solar units. See PR #155. Thank you to Clément Robert (@neutrinoceros on GitHub) for the initial bug report.

9.3 2.7.1 (2020-02-17)

• Fix compatibility with unyt_array subclasses that do not have the new name argument in their initializer. See PR #140. • Fix an issue where custom units added to a unit registry were not restored correctly when reloading a unit registry from a JSON or pickle representation. See PR #140.

9.4 2.7.0 (2020-02-06)

• The unyt_array and unyt_quantity classes now have a new, optional name attribute. The primary purpose of this attribute is to enable automatic generation of matplotlib plot labels. The name attribute is propagated through unit conversions and copies but is not propagated through mathematical operations. SeePR #129 and the documentation for details. • Add support for the Neper and Bel units with logarithmic dimensions. This includes support for the decibel unit. Note that logarithmic units can only be used with other logarithmic units and must be applied and stripped manually. See PR #133 and PR #134. • Add support for the SI unit of inductance, H. See PR #135. • Fix formatting of error message produced when raising a quantity to a power with units. See PR #131. Thank you to Lee Johnston (@l-johnston on GitHub) for all of the above contributions. • Fix incorrect unit metadata when loading a pickled array saved by yt.units. See PR #137.

9.5 2.6.0 (2020-01-22)

• Matplotlib support is no longer enabled by importing unyt. Instead, it is now necessary to use the unyt. matplotlib_support context manager in code where you want unyt to automatically generate plot labels. Enabling Matplotlib support by default in the previous release caused crashes in previously working code for some users so we have decided to make the plotting support optional. See the documentation for more details. We are sorry for introducing a new feature that broke some user’s code. See PR #126. Thank you to Lee Johnston (@l-johnston on GitHub) for the contribution. • Updated the contribution guide to include more details about setting up multiple Python versions for the tox tests.

9.6 2.5.0 (2020-01-20)

• Importing unyt now registers unyt with Matplotlib’s interface for handling units. See the Matplotlib and unyt documentation for more details. See PR #122 and PR #124. Thank you to Lee Johnston (@l-johnston on GitHub) for the contribution. • Updated the LaTeX formatting of solar units so they do not get rendered italicized. See PR #120. Thank you to Josh Borrow (@JBorrow on GitHub) for the contribution. • Reduce floating point round-off error when data are converted from integer to float dtypes. See PR #119.

90 Chapter 9. History unyt Documentation, Release v2.8.0

9.7 2.4.1 (2020-01-10)

• Add support for the latest releases of h5py, sympy, NumPy, and PyTest. See PR #115. • Fix the hash implementation so that identical units cannot have distinct hashes. See PR #114 and PR #117. Thank you to Ben Kimock (@saethlin on GitHub) for the contribution.

9.8 2.4.0 (2019-10-25)

• Improve performance for creating quantities or small arrays via multiplication with a unit object. Creating an array or quantity from data that does not have a numeric dtype will now raise UnitOperationError instead of UnitDtypeError, which has been removed. See PR #111. • Comparing data with units that have different dimensions using the == and != operators will no longer raise an error. Other comparison operators will continue to raise errors. See PR #109. • Fixed a corner case in the implementation of clip. See PR #108. Thank you to Matthew Turk (@matthewturk on GitHub) for the contribution. • Added % as a valid dimensionless unit with a value of 0.01, also available under the name percent. SeePR #106. Thank you to Thomas Hisch for the contribution. • Added bar to the default unit lookup table. See PR #103. Thank you to Thomas Hisch (@thisch on GitHub) for the contribution.

9.9 2.3.1 (2019-08-21)

• Added support for the clip ufunc added in NumPy 1.17. See PR #102.

9.10 2.3.0 (2019-08-14)

• Added unyt.dimensions.accepts and unyt.dimensions.returns, decorators that can be used to ensure that data passed into a decorated function has units that are dimensionally consistent with the function’s expected inputs. See PR #98. Thank you to Andrei Berceanu (@berceanu on GitHub) for the contribution. • Added unyt.allclose_units and improved documentation for writing tests for code that uses unyt. This is a wrapper for numpy.allclose that also checks the units of the input arrays. See PR #94. Thank you to Andrei Berceanu (@berceanu on GitHub) for the contribution.

9.11 2.2.2 (2019-07-03)

• Fix erroneous conversions of E&M units to their “native” unit system, for example, converting Gauss to CGS units would return Tesla and converting Tesla to MKS units would return Gauss. See PR #96.

9.12 2.2.1 (2019-07-02)

• Add support for loading JSON unit registries saved by yt.units. See PR #93.

9.7. 2.4.1 (2020-01-10) 91 unyt Documentation, Release v2.8.0

• Correct the value of the light_year unit. See PR #93. • It is now possible to define a UnitSystem object with a quantity. See PR #86. • Incorrect units for have been fixed. See PR #85. Thank you to Nathan Musoke (@musoke on GitHub) for the contribution. • Updated value of Newton’s constant to latest CODATA value. See PR #84.

9.13 2.2.0 (2019-04-03)

• Several performance optimizations. This includes a slight change to the behavior of MKS/CGS E&M unit conversions that makes the conversion rules slightly more relaxed. See PR #82.

9.14 2.1.1 (2019-03-27)

• Fixed an issue with restoring unit registries from JSON output. See PR #81.

9.15 2.1.0 (2019-03-26)

This release includes a few minor new features and bugfixes for the 2.0.0 release. • Added support for the matmul @ operator. See PR #80. • Allow defining unit systems using Unit instances instead of string unit names. See PR #71. Thank you to Josh Borrow (@JBorrow on GitHub) for the contribution. • Fix incorrect behavior when uhstack is called with the axis argument. See PR #73. • Add "rsun", "lsun", and "au" as alternate spellings for the "Rsun", "Lsun", and "AU" units. SeePR #77. • Improvements for working with code unit systems. See PR #78. • Reduce impact of floating point round-off noise on unit comparisons. See PR #79.

9.16 2.0.0 (2019-03-08) unyt 2.0.0 includes a number of exciting new features as well as some bugfixes. There are some small backwards incompatible changes in this release related to automatic unit simplification and handling of dtypes. Please see the release notes below for more details. If you are upgrading from unyt 1.x we suggest testing to make sure these changes do not siginificantly impact you. If you run into issues please let us know by opening an issue on GitHub. • Dropped support for Python 2.7 and Python 3.4. Added support for Python 3.7. • Added Unit.simplify(), which cancels pairs of terms in a unit expression that have inverse dimensions and made it so the results of unyt_array multiplication and division will automatically simplify units. This means operations that combine distinct dimensionally equivalent units will cancel in many situations. For example

>>> from unyt import kg, g >>> print((12*kg)/(4*g)) 3000.0 dimensionless

92 Chapter 9. History unyt Documentation, Release v2.8.0

older versions of unyt would have returned 4.0 kg/g. See PR #58 for more details. This change may cause the units of operations to have different, equivalent simplified units than they did with older versions of unyt. • Added the ability to resolve non-canonical unit names to the equivalent canonical unit names. This means it is now possible to refer to a unit name using an alternative non-canonical unit name when importing the unit from the unyt namespace as well as when a unit name is passed as a string to unyt. For example:

>>> from unyt import meter, second >>> data= 1000. *meter/second >>> data.to('kilometer/second') unyt_quantity(1., 'km/s') >>> data.to('metre/s') unyt_quantity(1000., 'm/s')

The documentation now has a table of units recognized by unyt along with known alternative spellings for each unit. • Added support for unicode unit names, including 휇m for micrometer and Ω for ohm. See PR #59. • Substantially improved support for data that does not have a float64 dtype. Rather than coercing all data to float64 unyt will now preserve the dtype of data. Data that is not already a numpy array will be coerced to a dtype by calling np.array internally. Converting integer data to a new unit will convert the data to floats, if this causes a loss of precision then a warning message will be printed. See PR #55 for details. This change may cause data to be loaded into unyt with a different dtype. On Windows the default integer dtype is int32, so data may begin to be recognized as int32 or converted to float32 where before it was interpreted as float64 by default. • Unit registries are now associated with a unit system. This means that it’s possible to create a unit registry that is associated with a non-MKS unit system so that conversions to “base” units will end up in that non-MKS system. For example:

>>> from unyt import UnitRegistry, unyt_quantity >>> ureg= UnitRegistry(unit_system='cgs') >>> data= unyt_quantity(12,'N', registry=ureg) >>> data.in_base() unyt_quantity(1200000., 'dyn')

See PR #62 for details. • Added two new utility functions, unyt.unit_systems.add_constants and unyt.unit_systems. add_symbols that can populate a namespace with a set of unit symbols in the same way that the top-level unyt namespace is populated. For example, the author of a library making use of unyt could create an object that users can use to access unit data like this:

>>> from unyt.unit_systems import add_symbols >>> from unyt.unit_registry import UnitRegistry >>> class UnitContainer(object): ... def __init__(self): ... add_symbols(vars(self), registry=UnitRegistry()) >>> units= UnitContainer() >>> units.kilometer km >>> units.microsecond 휇s

See PR #68. • The unyt codebase is now automatically formatted by black. See PR #57. • Add missing “microsecond” name from top-level unyt namespace. See PR #48.

9.16. 2.0.0 (2019-03-08) 93 unyt Documentation, Release v2.8.0

• Add support for numpy.argsort by defining unyt_array.argsort. See PR #52. • Add Farad unit and fix issues with conversions between MKS and CGS electromagnetic units. See PR #54. • Fixed incorrect conversions between inverse velocities and statohm. See PR #61. • Fixed issues with installing unyt from source with newer versions of pip. See PR #63. • Fixed bug when using define_unit that caused crashes when using a custom unit registry. Thank you to Bili Dong (@qobilidob on GitHub) for the pull request. See PR #64. We would also like to thank Daniel Gomez (@dangom), Britton Smith (@brittonsmith), Lee Johnston (@l-johnston), Meagan Lang (@langmm), Eric Chen (@ericchen), Justin Gilmer (@justinGilmer), and Andy Perez (@sharkweek) for reporting issues.

9.17 1.0.7 (2018-08-13)

Trigger zenodo archiving.

9.18 1.0.6 (2018-08-13)

Minor paper updates to finalize JOSS submission.

9.19 1.0.5 (2018-08-03) unyt 1.0.5 includes changes that reflect the peew review process for the JOSS method paper. The peer reviewers were Stuart Mumfork (@cadair), Trevor Bekolay (@tbekolay), and Yan Grange (@ygrange). The editor was Kyle Niemeyer (@kyleniemeyer). The‘ unyt‘ development team thank our reviewers and editor for their help getting the unyt paper out the door as well as for the numerous comments and suggestions that improved the paper and package as a whole. In addition we’d like to thank Mike Zingale, Meagan Lang, Maksin Ratkin, DougAJ4, Ma Jianjun, Paul Ivanov, and Stephan Hoyer for reporting issues. • Added docstrings for the custom exception classes defined by unyt. See PR #44. • Added improved documentation to the contributor guide on how to run the tests and what the PR review guide- lines are. See PR #43. • Updates to the text of the method paper in response to reviewer suggestions. See PR #42. • It is now possible to run the tests on an installed copy of unyt by executing unyt.test(). See PR #41. • Minor edit to LICENSE file so GitHub recognizes it. See PR #40. Thank you to Kyle Sunden (@ksunden) for the contribution. • Add spatial frequency as a dimension and added support in the spectral equivalence for the spatial frequency dimension. See PR #38 Thank you to Kyle Sunden (@ksunden) for the contribution. • Add support for Python 3.7. See PR #37. • Importing unyt will now fail if numpy and sympy are not installed. See PR #35 • Testing whether a unit name is contained in a unit registry using the Python in keyword will now work correctly for all unit names. See PR #31.

94 Chapter 9. History unyt Documentation, Release v2.8.0

• The aliases for megagram in the top-level unyt namespace were incorrectly set to reference kilogram and now have the correct value. See PR #29. • Make it possible to take scalars to dimensionless array powers with a properly broadcasted result without raising an error about units. See PR #23. • Whether or not a unit is allowed to be SI-prefixable (for example, meter is SI-prefixable to form centimeter, kilometer, and many other units) is now stored as metadata in the unit registry rather than as global state inside unyt. See PR #21. • Made adjustments to the rules for converting between CGS and MKS E&M units so that errors are only raised when going between unit systems and not merely when doing a complicated unit conversion invoving E&M units. See PR #20. • round(q) where q is a unyt_quantity instance will no longer raise an error and will now return the nearest rounded float. See PR #19. • Fixed a typo in the readme. Thank you to Paul Ivanov (@ivanov) for the fix. • Added smoot as a unit. See PR #14.

9.20 1.0.4 (2018-06-08)

• Expand installation instructions • Mention paper and arxiv submission in the readme.

9.21 1.0.3 (2018-06-06)

• Fix readme rendering on pypi

9.22 1.0.2 (2018-06-06)

• Added a paper to be submitted to the Journal of Open Source Software. • Tweaks for the readme

9.23 1.0.1 (2018-05-24)

• Don’t use setup_requires in setup.py

9.24 1.0.0 (2018-05-24)

• First release on PyPI. • unyt began life as a submodule of yt named yt.units. • It was separated from yt.units as its own package in 2018.

9.20. 1.0.4 (2018-06-08) 95 unyt Documentation, Release v2.8.0

96 Chapter 9. History CHAPTER 10

Indices and tables

• genindex • modindex • search

97 unyt Documentation, Release v2.8.0

98 Chapter 10. Indices and tables Python Module Index

u unyt, 37 unyt.array, 38 unyt.dimensions, 56 unyt.equivalencies, 60 unyt.exceptions, 64 unyt.mpl_interface, 68 unyt.physical_constants, 68 unyt.testing, 69 unyt.unit_object, 70 unyt.unit_registry, 74 unyt.unit_symbols, 75 unyt.unit_systems, 77

99 unyt Documentation, Release v2.8.0

100 Python Module Index Index

A convert_to_mks() (unyt.array.unyt_array method), acceleration (in module unyt.dimensions), 56 40 accepts() (in module unyt.dimensions), 59 convert_to_units() (unyt.array.unyt_array add() (unyt.unit_registry.UnitRegistry method), 74 method), 39 add_constants() (in module unyt.unit_systems), 78 copy() (unyt.array.unyt_array method), 50 add_symbols() (in module unyt.unit_systems), 77 copy() (unyt.unit_object.Unit method), 70 allclose_units() (in module unyt.array), 55 count_flux (in module unyt.dimensions), 57 angle (in module unyt.dimensions), 56 count_intensity (in module unyt.dimensions), 57 angular_momentum (in module unyt.dimensions), 57 crackle (in module unyt.dimensions), 57 area (in module unyt.dimensions), 57 current_cgs (in module unyt.dimensions), 58 argsort() (unyt.array.unyt_array method), 45 current_mks (in module unyt.dimensions), 56 as_coeff_unit() (unyt.unit_object.Unit method), 72 assert_allclose_units() (in module D unyt.testing), 69 d (unyt.array.unyt_array attribute), 49 default_unit_registry (in module B unyt.unit_registry), 75 base_dimensions (in module unyt.dimensions), 56 define_unit() (in module unyt.unit_object), 73 base_offset (unyt.unit_object.Unit attribute), 73 density (in module unyt.dimensions), 57 base_value (unyt.unit_object.Unit attribute), 73 derived_dimensions (in module unyt.dimensions), 59 C dimensionless (in module unyt.dimensions), 56 dimensions (in module unyt.dimensions), 59 cached_sympify (in module unyt.unit_registry), 74 dimensions (unyt.unit_object.Unit attribute), 73 capacitance (in module unyt.dimensions), 58 disable() (unyt.mpl_interface.matplotlib_support capacitance_mks (in module unyt.dimensions), 58 method), 68 cgs_unit_system (in module unyt.unit_systems), 79 dot() (unyt.array.unyt_array method), 51 charge (in module unyt.dimensions), 58 charge_cgs (in module unyt.dimensions), 57 E charge_mks (in module unyt.dimensions), 58 ComptonEquivalence (class in unyt.equivalencies), EffectiveTemperatureEquivalence (class in 63 unyt.equivalencies), 64 convert() (unyt.equivalencies.Equivalence method), electric_field (in module unyt.dimensions), 58 60 electric_field_cgs (in module unyt.dimensions), convert_to_base() (unyt.array.unyt_array 58 method), 39 electric_field_mks (in module unyt.dimensions), convert_to_cgs() (unyt.array.unyt_array method), 58 40 electric_potential (in module unyt.dimensions), convert_to_equivalent() 58 (unyt.array.unyt_array method), 43 electric_potential_cgs (in module unyt.dimensions), 58

101 unyt Documentation, Release v2.8.0 electric_potential_mks (in module InvalidUnitOperation, 66 unyt.dimensions), 58 is_atomic (unyt.unit_object.Unit attribute), 73 em_dimensions (in module unyt.dimensions), 59 is_code_unit (unyt.unit_object.Unit attribute), 71 enable() (unyt.mpl_interface.matplotlib_support is_commutative (unyt.unit_object.Unit attribute), 70 method), 68 is_dimensionless (unyt.unit_object.Unit attribute), energy (in module unyt.dimensions), 57 70 Equivalence (class in unyt.equivalencies), 60 is_number (unyt.unit_object.Unit attribute), 70 expr (unyt.unit_object.Unit attribute), 73 is_positive (unyt.unit_object.Unit attribute), 70 is_Unit (unyt.unit_object.Unit attribute), 73 F IterableUnitCoercionError, 66 flux (in module unyt.dimensions), 57 force (in module unyt.dimensions), 57 J from_astropy() (unyt.array.unyt_array class jerk (in module unyt.dimensions), 56 method), 46 from_hdf5() (unyt.array.unyt_array class method), K 47 keys() (unyt.unit_registry.UnitRegistry method), 75 from_json() (unyt.unit_registry.UnitRegistry class method), 75 L from_pint() (unyt.array.unyt_array class method), label_style (unyt.mpl_interface.matplotlib_support 46 attribute), 68 latex_repr (unyt.unit_object.Unit attribute), 70 G latex_representation() (unyt.unit_object.Unit galactic_unit_system (in module method), 72 unyt.unit_systems), 79 length (in module unyt.dimensions), 56 geometrized_unit_system (in module list_equivalencies() (unyt.array.unyt_array unyt.unit_systems), 79 method), 44 get_base_equivalent() (unyt.unit_object.Unit list_equivalencies() (unyt.unit_object.Unit method), 71 method), 71 get_cgs_equivalent() (unyt.unit_object.Unit list_same_dimensions() method), 71 (unyt.unit_registry.UnitRegistry method), get_conversion_factor() (unyt.unit_object.Unit 75 method), 72 loadtxt() (in module unyt.array), 54 get_mks_equivalent() (unyt.unit_object.Unit logarithmic (in module unyt.dimensions), 56 method), 72 LorentzEquivalence (class in unyt.equivalencies), 62 H luminance (in module unyt.dimensions), 57 has_current_mks (unyt.unit_systems.UnitSystem at- luminous_flux (in module unyt.dimensions), 57 tribute), 79 luminous_intensity (in module unyt.dimensions), has_equivalent() (unyt.array.unyt_array method), 56 44 has_equivalent() (unyt.unit_object.Unit method), M 71 magnetic_field (in module unyt.dimensions), 58 magnetic_field_cgs (in module unyt.dimensions), I 58 IllDefinedUnitSystem, 67 magnetic_field_mks (in module unyt.dimensions), imperial_unit_system (in module 58 unyt.unit_systems), 79 magnetic_flux (in module unyt.dimensions), 58 in_base() (unyt.array.unyt_array method), 43 magnetic_flux_cgs (in module unyt.dimensions), in_cgs() (unyt.array.unyt_array method), 43 58 in_mks() (unyt.array.unyt_array method), 43 magnetic_flux_mks (in module unyt.dimensions), in_units() (unyt.array.unyt_array method), 41 58 inductance (in module unyt.dimensions), 58 mass (in module unyt.dimensions), 56 inductance_mks (in module unyt.dimensions), 59 MassEnergyEquivalence (class in InvalidUnitEquivalence, 66 unyt.equivalencies), 61

102 Index unyt Documentation, Release v2.8.0 matplotlib_support (class in unyt.mpl_interface), T 68 temperature (in module unyt.dimensions), 56 MissingMKSCurrent, 65 test() (in module unyt), 38 mks_unit_system (in module unyt.unit_systems), 79 ThermalEquivalence (class in unyt.equivalencies), MKSCGSConversionError, 65 61 modify() (unyt.unit_registry.UnitRegistry method), 74 time (in module unyt.dimensions), 56 momentum (in module unyt.dimensions), 57 to() (unyt.array.unyt_array method), 41 to_astropy() (unyt.array.unyt_array method), 46 N to_equivalent() (unyt.array.unyt_array method), ndarray_view() (unyt.array.unyt_array method), 44 44 ndview (unyt.array.unyt_array attribute), 48 to_json() (unyt.unit_registry.UnitRegistry method), number_density (in module unyt.dimensions), 57 75 NumberDensityEquivalence (class in to_ndarray() (unyt.array.unyt_array method), 45 unyt.equivalencies), 60 to_pint() (unyt.array.unyt_array method), 47 to_value() (unyt.array.unyt_array method), 42 P type_name (unyt.equivalencies.ComptonEquivalence planck_unit_system (in module attribute), 64 unyt.unit_systems), 79 type_name (unyt.equivalencies.EffectiveTemperatureEquivalence pop (in module unyt.dimensions), 57 attribute), 64 power (in module unyt.dimensions), 57 type_name (unyt.equivalencies.LorentzEquivalence at- prefixable_units (unyt.unit_registry.UnitRegistry tribute), 63 attribute), 74 type_name (unyt.equivalencies.MassEnergyEquivalence pressure (in module unyt.dimensions), 57 attribute), 61 type_name (unyt.equivalencies.NumberDensityEquivalence R attribute), 60 registry (unyt.unit_object.Unit attribute), 73 type_name (unyt.equivalencies.SchwarzschildEquivalence remove() (unyt.unit_registry.UnitRegistry method), 74 attribute), 63 resistance (in module unyt.dimensions), 58 type_name (unyt.equivalencies.SoundSpeedEquivalence resistance_cgs (in module unyt.dimensions), 58 attribute), 62 resistance_mks (in module unyt.dimensions), 58 type_name (unyt.equivalencies.SpectralEquivalence returns() (in module unyt.dimensions), 59 attribute), 62 type_name (unyt.equivalencies.ThermalEquivalence S attribute), 61 same_dimensions_as() (unyt.unit_object.Unit U method), 70 ua savetxt() (in module unyt.array), 55 (unyt.array.unyt_array attribute), 50 uconcatenate() SchwarzschildEquivalence (class in (in module unyt.array), 52 ucross() unyt.equivalencies), 63 (in module unyt.array), 52 udot() simplify() (unyt.unit_object.Unit method), 73 (in module unyt.array), 53 uhstack() snap (in module unyt.dimensions), 56 (in module unyt.array), 53 uintersect1d() solar_unit_system (in module unyt.unit_systems), (in module unyt.array), 52 Unit 79 (class in unyt.unit_object), 70 unit_array solid_angle (in module unyt.dimensions), 56 (unyt.array.unyt_array attribute), 50 unit_quantity SoundSpeedEquivalence (class in (unyt.array.unyt_array attribute), 49 unit_system_id unyt.equivalencies), 62 (unyt.unit_registry.UnitRegistry at- specific_angular_momentum (in module tribute), 74 UnitConversionError unyt.dimensions), 57 , 65 UnitOperationError specific_energy (in module unyt.dimensions), 57 , 64 UnitParseError specific_flux (in module unyt.dimensions), 57 , 67 UnitRegistry SpectralEquivalence (class in (class in unyt.unit_registry), 74 units unyt.equivalencies), 61 (unyt.unit_object.Unit attribute), 70 UnitsNotReducible SymbolNotFoundError, 67 , 65 UnitSystem (class in unyt.unit_systems), 78 unorm() (in module unyt.array), 53

Index 103 unyt Documentation, Release v2.8.0

unyt (module), 37 unyt.array (module), 38 unyt.dimensions (module), 56 unyt.equivalencies (module), 60 unyt.exceptions (module), 64 unyt.mpl_interface (module), 68 unyt.physical_constants (module), 68 unyt.testing (module), 69 unyt.unit_object (module), 70 unyt.unit_registry (module), 74 unyt.unit_symbols (module), 75 unyt.unit_systems (module), 77 unyt_array (class in unyt.array), 38 unyt_quantity (class in unyt.array), 51 uq (unyt.array.unyt_array attribute), 49 ustack() (in module unyt.array), 54 uunion1d() (in module unyt.array), 52 uvstack() (in module unyt.array), 53 V v (unyt.array.unyt_array attribute), 48 value (unyt.array.unyt_array attribute), 48 velocity (in module unyt.dimensions), 56 volume (in module unyt.dimensions), 57 W write_hdf5() (unyt.array.unyt_array method), 47

104 Index