<jupyter_start><jupyter_text>Astropy Units and Quantities Astropy includes a powerful framework for units that allows users to attach units to scalars and arrays.  These quantities can be manipulated or combined, keeping track of the units.For more information about the features presented below, please see the[astropy.units](http://docs.astropy.org/en/stable/units/index.html) docs.  Representing units and quantities Because we may want to use units in many expressions, it is easiest andmost concise to import the units module with:<jupyter_code>import astropy.units as u<jupyter_output><empty_output><jupyter_text>However, note that this will conflict with any variable called ``u``.Units can then be accessed as u."unit", e.g.:<jupyter_code>u.m<jupyter_output><empty_output><jupyter_text>Units have docstrings defining them:<jupyter_code>u.m.__doc__<jupyter_output><empty_output><jupyter_text>and a physical type:<jupyter_code>u.m.physical_type
u.pc.__doc__
u.s.physical_type<jupyter_output><empty_output><jupyter_text>Please see the complete list of [available units](https://astropy.readthedocs.org/en/stable/units/index.htmlmodule-astropy.units.si).  Composite units Composite units are created using Python numeric operators, e.g. "`*`" (multiplication), "`/`" (division), and "`**`" (power).<jupyter_code>u.km / u.s
u.imperial.mile / u.h
(u.eV * u.Mpc) / u.Gyr
u.cm**3
u.m / u.kg / u.s**2<jupyter_output><empty_output><jupyter_text>``Quantity`` objectsThe most useful feature of units is the ability to attach them to scalars or arrays, creating ``Quantity`` objects. The easiest way to create a `Quantity` object is simply by multiplying the value with its unit.<jupyter_code>3. * u.au<jupyter_output><empty_output><jupyter_text>A completely equivalent (but more verbose) way of doing the same thing is to use the `Quantity` object's initializer, demonstrated below.  In general, the simpler form (above) is preferred, as it is closer to how such a quantity would actually be written in text.  The initalizer form has more options, though, which you can learn about from the [astropy reference documentation on Quantity](http://docs.astropy.org/en/stable/api/astropy.units.quantity.Quantity.html).<jupyter_code>u.Quantity(3, unit=u.au)<jupyter_output><empty_output><jupyter_text>We can also generate a ``Quantity`` array:<jupyter_code>import numpy as np
x = np.array([1.2, 2.2, 1.7]) * u.pc / u.year
x
x * 3<jupyter_output><empty_output><jupyter_text>`Quantity` attributes The units and value of a `Quantity` can be accessed separately via the ``value`` and ``unit`` attributes:<jupyter_code>q = 5. * u.Mpc
q.value
q.unit
x = np.array([1.2, 2.2, 1.7]) * u.pc / u.year
x.value
x.unit<jupyter_output><empty_output><jupyter_text>Combining Quantities Quantities can also be combined using Python numeric operators:<jupyter_code>q1 = 3. * u.m / u.s
q1
q2 = 5. * u.cm / u.s / u.g**2
q2
q1 * q2
q1 / q2
q1 ** 2<jupyter_output><empty_output><jupyter_text>Addition and subtraction require compatible unit types:<jupyter_code>q1 = 3 * u.m
q1 + (5 * u.m)
q1 + (5. * u.kpc)
# this will fail because the units are not compatible
q1 + (10. * u.km / u.s)<jupyter_output><empty_output><jupyter_text>Coverting units<jupyter_code>(2.5 * u.year).to(u.s)
(7. * u.deg**2).to(u.sr)
q1.to(u.au)
(55. * u.imperial.mile / u.h).to(u.km / u.h)
q1 * q2
(q1 * q2).to(u.m**2 / u.kg**2 / u.s)
# note that converting units instead of Quantities
# gives only the scale factor
(u.Msun).to(u.kg)
# to keep the units, use a Quantity (value and unit)
(1. * u.Msun).to(u.kg)<jupyter_output><empty_output><jupyter_text>Decomposing units 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.:<jupyter_code>q = 3. * u.cm * u.pc / u.g / u.year**2
q
q.decompose()<jupyter_output><empty_output><jupyter_text>To decompose into c.g.s. bases:<jupyter_code>q.decompose(u.cgs.bases)
u.cgs.bases
u.si.bases<jupyter_output><empty_output><jupyter_text>Using physical constants The [astropy.constants](http://docs.astropy.org/en/v0.2.1/constants/index.html) module contains physical constants relevant for astronomy.  They are defined as ``Quantity`` objects using the ``astropy.units`` framework.<jupyter_code>from astropy.constants import G, c, R_earth
G
c
R_earth<jupyter_output><empty_output><jupyter_text>Constants are Quantities, thus they can be coverted to other units:<jupyter_code>R_earth.to(u.km)<jupyter_output><empty_output><jupyter_text>Please see the complete list of [available physical constants](http://docs.astropy.org/en/stable/constants/index.htmlmodule-astropy.constants).  Additions are welcome!  An exampleKepler's law can be used to estimate the (circular) orbital speed of the Earth around the sun using:$$v = \sqrt{\frac{G M_{\odot}}{r}}$$<jupyter_code>v = np.sqrt(G * 1 * u.M_sun / (1 * u.au))
v
v.decompose()
v.to(u.km / u.s)<jupyter_output><empty_output><jupyter_text>Exercise 1The *James Webb Space Telescope (JWST)* will be located at the second Sun-Earth Lagrange (L2) point.  L2 is located opposite the Sun at a distance from the Earth of approximately:$$ r \approx R \left(\frac{M_{earth}}{3 M_{sun}}\right) ^{(1/3)} $$where $R$ is the Sun-Earth distance.Calculate the Earth-L2 distance in kilometers and miles:* *Hint*:  the mile unit is defined as ``u.imperial.mile`` (see [imperial units](http://docs.astropy.org/en/v0.2.1/units/index.htmlmodule-astropy.units.imperial))<jupyter_code># answer here (km)
# answer here (mile)<jupyter_output><empty_output><jupyter_text>Exercise 2The L2 point is about 1.5 million kilometers away from the Earth opposite the Sun.The total mass of the *James Webb Space Telescope (JWST)* is about 6500 kg.Using the value you obtained above for the Earth-L2 distance, calculate the gravitational force in Newtons between * *JWST* (at L2) and the Earth* *JWST* (at L2) and the Sun*Hint*: the gravitational force between two masses separated by a distance *r* is:$$ F_g = \frac{G m_1 m_2}{r^2} $$<jupyter_code># answer here (Earth)
# answer here (Sun)<jupyter_output><empty_output><jupyter_text>EquivalenciesEquivalencies can be used to convert quantities that are not strictly the same physical type.<jupyter_code># this raises an error
(7. * u.cm).to(u.GHz)
# we need to use an equivalency (here spectral)
(7. * u.cm).to(u.GHz, equivalencies=u.spectral())
(13.6 * u.eV).to(u.Angstrom, equivalencies=u.spectral())
u.eV.find_equivalent_units()
u.eV.find_equivalent_units(equivalencies=u.spectral())<jupyter_output><empty_output><jupyter_text>For spectral density equivalencies, it is necessary to supply the location in the spectrum where the conversion is done:<jupyter_code>q = (1e-18 * u.erg / u.s / u.cm**2 / u.AA)
q
q.to(u.uJy, equivalencies=u.spectral_density(1. * u.um))<jupyter_output><empty_output><jupyter_text>Integration with Numpy ufuncs Most of the [Numpy](http://www.numpy.org) functions understand `Quantity` objects:<jupyter_code>np.sin(30 * u.degree)
q = 100 * u.km * u.km
q
np.sqrt(q)
np.exp(3 * u.m / (3 * u.km))<jupyter_output><empty_output><jupyter_text>Care needs to be taken with dimensionless units.  Passing dimensionless values to an inverse trigonometric function gives a result without units:<jupyter_code>np.arcsin(1.0)<jupyter_output><empty_output><jupyter_text>`u.dimensionless_unscaled` creates a ``Quantity`` with a "dimensionless unit" and therefore gives a result *with* units:<jupyter_code>np.arcsin(1.0 * u.dimensionless_unscaled)
np.arcsin(1.0 * u.dimensionless_unscaled).to(u.degree)<jupyter_output><empty_output><jupyter_text>Known issues Quantities lose their units with some Numpy operations, e.g.:* np.dot* np.hstack* np.vstack* np.where* np.choose* np.vectorizeSee [Quantity Known Issues](http://docs.astropy.org/en/stable/known_issues.htmlquantities-lose-their-units-with-some-operations) for more details.  Defining new units You can also define custom units for something that isn't built-in to astropy.<jupyter_code># fundamental unit
chuckle = u.def_unit('chuckle')
# compound unit
laugh = u.def_unit('laugh', 4 * chuckle)
(3 * laugh).to(chuckle)
bakers_fortnight = u.def_unit('bakers_fortnight', 13 * u.day)
(3 * bakers_fortnight).to(u.s)<jupyter_output><empty_output><jupyter_text>Advanced Example: little *h* For this example, we'll consider how to support the practice of defining units in terms of the dimensionless Hubble constant $h=h_{100}=\frac{H_0}{100 \, {\rm km/s/Mpc}} $. We use the name 'h100' to differentiate from "h" as in "hours".<jupyter_code># define the h100 and h70 units
h100 = u.def_unit(['h100', 'littleh'])
h70 = u.def_unit('h70', h100 * 100./70)
# add as equivalent units
u.add_enabled_units([h100, h70])
h100.find_equivalent_units()<jupyter_output><empty_output><jupyter_text>Define the Hubble constant ($H_0$) in terms of ``h100``:<jupyter_code>H = 100 * h100 * u.km / u.s / u.Mpc
H<jupyter_output><empty_output><jupyter_text>Now compute the Hubble time ($1 / H_0$) for h = h100 = 1:<jupyter_code>t_H = (1/H).to(u.Gyr / h100)
t_H<jupyter_output><empty_output><jupyter_text>and for h = 0.7:<jupyter_code>t_H.to(u.Gyr / h70)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12782941498086386, 'fraction_numerical': 0.019464188080918536, 'mean_word_length': 5.575125808770669, 'pattern_counts': {'":': 0, '<': 117, '<?xml version=': 0, '>': 117, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '29', 'dir': 'jupyter-structured-clean-dedup', 'id': '162799', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 3411, 'n_tokens_neox': 3230, 'n_words': 902, 'path': 'AAS2016/notebooks/aas2016_Units.ipynb', 'repo_name': 'astropy/astropy-workshops', 'size': '9145'}