mammos_units quickstart#

This tutorial provides a short overview of the most important functionality of mammos_units. For a more in-depth introduction refer to Unit Conversions.

import mammos_units as u

Creating quantities#

mammos_units provides functionality to work with units. It is based on astropy.units. The central object is the Quantity, the combination of a value and a unit. We can create it by multiplying value and unit:

length = 3 * u.m
length
\[3 \; \mathrm{m}\]

We have access to its value and unit:

length.value
np.float64(3.0)
length.unit
\[\mathrm{m}\]

Mathematical operations act on both the value and the unit:

length**2
\[9 \; \mathrm{m^{2}}\]

Magnetic quantities#

The main focus of mammos_units is on magnetic units. In the following we show a few quantities relevant in the context of magnetism.

Magnetization $M$#

1e5 * u.A / u.m
\[100000 \; \mathrm{\frac{A}{m}}\]

Magnetic field strength $H$#

Vector quantities can be set with lists or numpy arrays:

[1e4, 0, 0] * u.A / u.m
\[[10000,~0,~0] \; \mathrm{\frac{A}{m}}\]

Magnetic flux $B$#

1 * u.T
\[1 \; \mathrm{T}\]

Energy $E$#

1e-5 * u.J
\[1 \times 10^{-5} \; \mathrm{J}\]

Converting units#

Quantities can be converted to different units using to(...). We can either pass a unit object or a string.

We can use that functionality to add or remove a prefix such as milli or kilo:

B = 1e-3 * u.T
B.to("mT")
\[1 \; \mathrm{mT}\]
M = 300 * u.kA / u.m  # we can directly use the prefix when creating the quantity
M
\[300 \; \mathrm{\frac{kA}{m}}\]
M.to(u.A / u.m)
\[300000 \; \mathrm{\frac{A}{m}}\]

Similarly, we can convert between SI and cgs:

B.to(u.gauss)
\[10 \; \mathrm{G}\]
M.to("Oe")
\[3769.9112 \; \mathrm{Oe}\]

Equivalencies#

Equivalencies can be used to convert between incompatible units, which are uniquely related in a given context. Equivalencies must be explicitely turned on to allow conversion between otherwise incompatible units.

In the magnetics context magnetic field strength $H$ and magnetic induction $B$ are often used interchangably using the relation $B = μ_0H$. We can activate this equivalency for the rest of the notebook using the following command:

u.set_enabled_equivalencies(u.magnetic_flux_field())
<astropy.units.core._UnitContext at 0x7f96c5f8bc50>

Now we can convert between Tesla and Ampere/meter:

B
\[0.001 \; \mathrm{T}\]
B.to("A/m")
\[795.77472 \; \mathrm{\frac{A}{m}}\]

To disable the equivalency we need to run the following command:

u.set_enabled_equivalencies(None)
<astropy.units.core._UnitContext at 0x7f96c5fe3360>

After disabling the equivalency, the conversion between Tesla and Ampere/meter is no longer possible:

B.to("A/m")
---------------------------------------------------------------------------
UnitConversionError                       Traceback (most recent call last)
Cell In[19], line 1
----> 1 B.to("A/m")

File ~/repos/mammos/mammos-units/.pixi/envs/default/lib/python3.13/site-packages/astropy/units/quantity.py:931, in Quantity.to(self, unit, equivalencies, copy)
    927 unit = Unit(unit)
    928 if copy:
    929     # Avoid using to_value to ensure that we make a copy. We also
    930     # don't want to slow down this method (esp. the scalar case).
--> 931     value = self._to_value(unit, equivalencies)
    932 else:
    933     # to_value only copies if necessary
    934     value = self.to_value(unit, equivalencies)

File ~/repos/mammos/mammos-units/.pixi/envs/default/lib/python3.13/site-packages/astropy/units/quantity.py:884, in Quantity._to_value(self, unit, equivalencies)
    881     equivalencies = self._equivalencies
    882 if not self.dtype.names or isinstance(self.unit, StructuredUnit):
    883     # Standard path, let unit to do work.
--> 884     return self.unit.to(
    885         unit, self.view(np.ndarray), equivalencies=equivalencies
    886     )
    888 else:
    889     # The .to() method of a simple unit cannot convert a structured
    890     # dtype, so we work around it, by recursing.
    891     # TODO: deprecate this?
    892     # Convert simple to Structured on initialization?
    893     result = np.empty_like(self.view(np.ndarray))

File ~/repos/mammos/mammos-units/.pixi/envs/default/lib/python3.13/site-packages/astropy/units/core.py:1208, in UnitBase.to(self, other, value, equivalencies)
   1206     return UNITY
   1207 else:
-> 1208     return self.get_converter(Unit(other), equivalencies)(value)

File ~/repos/mammos/mammos-units/.pixi/envs/default/lib/python3.13/site-packages/astropy/units/core.py:1137, in UnitBase.get_converter(self, other, equivalencies)
   1134             else:
   1135                 return lambda v: b(converter(v))
-> 1137 raise exc

File ~/repos/mammos/mammos-units/.pixi/envs/default/lib/python3.13/site-packages/astropy/units/core.py:1120, in UnitBase.get_converter(self, other, equivalencies)
   1118 # if that doesn't work, maybe we can do it with equivalencies?
   1119 try:
-> 1120     return self._apply_equivalencies(
   1121         self, other, self._normalize_equivalencies(equivalencies)
   1122     )
   1123 except UnitsError as exc:
   1124     # Last hope: maybe other knows how to do it?
   1125     # We assume the equivalencies have the unit itself as first item.
   1126     # TODO: maybe better for other to have a `_back_converter` method?
   1127     if hasattr(other, "equivalencies"):

File ~/repos/mammos/mammos-units/.pixi/envs/default/lib/python3.13/site-packages/astropy/units/core.py:1071, in UnitBase._apply_equivalencies(self, unit, other, equivalencies)
   1068 unit_str = get_err_str(unit)
   1069 other_str = get_err_str(other)
-> 1071 raise UnitConversionError(f"{unit_str} and {other_str} are not convertible")

UnitConversionError: 'T' (magnetic flux density) and 'A / m' (magnetic field strength) are not convertible