Skip to content

Use astropy.units subpackage to represent quantities with units? #26

@namurphy

Description

@namurphy

It's exciting to find an open source Python software analysis package for big plasma physics experiments! We as a community need to do more of this.

It looks like many of the physical values in this package are stored as floats or arrays. There exist a few Python packages to represent quantities with units. For PlasmaPy, we use astropy.units for compatibility with Astropy, SunPy, and other packages in the Python ecosystems for astronomy and heliophysics. The use of a units package has helped immensely and makes it a lot easier for people to be able to choose between SI or cgs units. Here's an example:

>>> from astropy import units as u
>>> distance = 5 * u.m
>>> distance = 88 * u.imperial.mi
>>> distance = 88 * u.imperial.mile
>>> time = 1 * u.hour
>>> velocity = distance / time
>>> print(velocity)
88.0 mi / h
>>> velocity.to('m/s')
<Quantity 39.33952 m / s>
>>> distance + time  # using astropy.units acts as an additional error check
astropy.units.core.UnitConversionError: Can only apply 'add' function to quantities with compatible dimensions

The astropy.constants subpackage has most of the fundamental physical constants that we need for plasma physics too.

There's also a really useful decorator, astropy.units.quantity_input, that uses annotations in functions to check that the units are physically compatible. One caveat is that last I checked (sometime in 2018), it didn't work well if you have some arguments that are supposed to be astropy.units.Quantity instances and some that aren't.

from astropy import units as u

@u.quantity_input
def get_velocity(distance: u.m, time: u.s) -> u.m / u.s:
    return distance / time

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions