Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
20 views
Kernel: Python 2

Astropy: Unit Conversion

Documentation

For more information about the features presented below, you can read the astropy.units docs.

Representing units and quantities

Astropy includes a powerful framework for units that allows users to attach units to scalars and arrays, and manipulate/combine these, keeping track of the units.

Since we may want to use a number of units in expressions, it is easiest and most concise to import the units module with:

from astropy import units as u

though note that this will conflict with any variable called u.

Units can then be accessed with:

u.m
u.pc
u.s
u.kg

We can create composite units:

u.m / u.kg / u.s**2
repr(u.m / u.kg / u.s**2)

The most useful feature about the units is the ability to attach them to scalars or arrays, creating Quantity objects:

3. * u.m
import numpy as np
np.array([1.2, 2.2, 1.7]) * u.pc / u.year

Combining and converting units

Quantities can then be combined:

q1 = 3. * u.m
q2 = 5. * u.cm / u.s / u.g**2
q1 * q2

and converted to different units:

(q1 * q2).to(u.m**2 / u.kg**2 / u.s)

The units and value of a quantity can be accessed separately via the value and unit attributes:

q = 5. * u.pc
q.value
q.unit

Advanced features

The units of a quantity can be decomposed into a set of base units using the decompose() method. By default, units will be decomposed to S.I.:

(3. * u.cm * u.pc / u.g / u.year**2).decompose()

To decompose into c.g.s. units, one can do:

(3. * u.cm * u.pc / u.g / u.year**2).decompose(u.cgs.bases)

Using physical constants

The astropy.constants module contains physical constants relevant for Astronomy, and these are defined with units attached to them using the astropy.units framework.

If we want to compute the Gravitational force felt by a 100. * u.kg space probe by the Sun, at a distance of 3.2au, we can do:

from astropy.constants import G
F = (G * 1. * u.M_sun * 100. * u.kg) / (3.2 * u.au)**2
F
F.to(u.N)

The full list of available physical constants is shown here (and additions are welcome!).

Equivalencies

Equivalencies can be used to convert quantities that are not strictly the same physical type:

(450. * u.nm).to(u.GHz)
(450. * u.nm).to(u.GHz, equivalencies=u.spectral())
(450. * u.eV).to(u.nm, equivalencies=u.spectral())
q = (1e-18 * u.erg / u.cm**2 / u.s / u.AA) q.to(u.Jy, equivalencies=u.spectral_density(u.mm, 1))

Integration with Numpy Functions

Some of the Numpy functions understand Quantity objects:

np.sin(30 * u.degree)
np.exp(3 * u.m/ (3 * u.km))

Practical Exercises

Level 1

What is 1 barn megaparsecs in teaspoons? Note that teaspoons are not part of the standard set of units, but it can be found in:

from astropy.units import imperial imperial.tsp
# Your solution here

Level 2

What is 3 nm^2 Mpc / m^3 in dimensionless units?

# Your solution here