# `Macaw.Units.Unit`
[🔗](https://github.com/dcoai/macaw_units/blob/v0.1.0/lib/macaw/units/unit.ex#L1)

Units named by their UCUM codes (spec/01 §1–§5, D-138, D-155).

A unit is named by its code in the Unified Code for Units of Measure — UCUM,
<https://ucum.org/ucum>, Regenstrief Institute — the case-sensitive, unambiguous codes
OpenTelemetry's semantic conventions use: `s`, `ms`, `By`, `kBy`, `MiBy`, `%`, `Cel`,
`kW.h`, `{request}/s`, `[lb_av]`, `mm[Hg]`. One code per unit is the point: a source that
says `"s"` and one that says `"sec"` must not draw two labels, so a code is checked,
never guessed at. Every atom and prefix here is UCUM's, with UCUM's definition, checked
against the UCUM essence table (`ucum-essence.xml`, version 2.2, 2024-06-17).

Codes are read by the `ucum` library, which gives UCUM's own answers (spec/01 §1): all of
UCUM's grammar (§2.1 of the specification, *Syntax rules*) over its whole essence table
(`Ucum.prefixes/0`, `Ucum.atoms/0`). A symbol is matched whole before it is split into a
prefix and an atom (§2.1.4), so `min` is the minute, and a prefix is refused on an atom
UCUM does not call metric (`kmin`, `k[in_i]`). This module is macaw's layer over it,
keeping macaw's stricter rules on top: data has a dimension of its own, a level never
meets a linear unit, a currency annotation is a currency, and the symbols macaw shows
are its own where it has fixed them (spec/01 §2–§4).

A code has a dimension and an exact factor to its base (the second, the byte, the
meter, the gram, the kelvin, the radian, the coulomb, the candela): a rational, times a
power of π for a code holding the degree. So values scale between two codes of one
dimension — 1,500 `ms` is 1.5 `s` — and convert exactly, `value × scale + offset`
(`conversion/2`). `Cel`, `[degF]` and `[degRe]` are UCUM's affine special units, scales
with an offset: they have no factor and convert by their offsets. UCUM's other special
units (`B`, `B[SPL]`, `Np`, `[pH]`, …) are levels here, each with a dimension of its
own, so a decibel scales to a bel and never to a linear unit. A currency never
converts: an exchange rate is data.

A person types symbols, not codes: reading them is presentation, macaw_format's, never
this module's.

## Examples

    iex> Macaw.Units.Unit.valid?("kW.h")
    true

    iex> Macaw.Units.Unit.parse("sec")
    {:error, {:unknown_atom, "sec"}}

    iex> Macaw.Units.Unit.symbol!("By/s")
    "B/s"

    iex> Macaw.Units.Unit.convert!(1500, "ms", "s")
    1.5

# `code`

```elixir
@type code() :: String.t()
```

A UCUM code, such as `ms` or `{request}/s`.

# `component`

```elixir
@type component() :: %{
  prefix: String.t() | nil,
  atom: String.t() | nil,
  factor: pos_integer() | nil,
  annotation: String.t() | nil,
  exponent: integer()
}
```

One component of a code: a prefixed atom, an integer factor or an annotation standing
alone, with its exponent — negated when the component divides.

# `conversion_reason`

```elixir
@type conversion_reason() ::
  {:dimension | :logarithmic | :currency, code(), code()}
  | {:affine_in_term, code()}
  | {:too_large, code()}
```

Why `conversion/2` refuses a pair of codes.

# `dimension`

```elixir
@type dimension() :: %{
  optional(
    :time
    | :information
    | :length
    | :mass
    | :temperature
    | :angle
    | :charge
    | :luminous_intensity
    | :level
    | :sound_pressure_level
    | {:currency, String.t()}
    | String.t()
  ) =&gt; integer()
}
```

A base dimension and its exponent; `%{}` is dimensionless. An arbitrary unit of UCUM's
(`[IU]`) and a level other than the bel's two (`Np`, `[pH]`) are each a dimension of
their own under a code, as `ucum` keeps an arbitrary unit: `[IU]/ml` is
`%{"[iU]" => 1, length: -3}`.

# `exact`

```elixir
@type exact() :: ratio() | {pos_integer(), pos_integer(), integer()}
```

An exact factor: a rational, or `{numerator, denominator, k}` — the rational times
π to the non-zero power `k`, for a code holding the degree.

# `kind`

```elixir
@type kind() :: :linear | :affine | :logarithmic
```

How a code's values relate to its base: by a factor, an offset, or a logarithm — or one
of UCUM's few other functions (`[p'diop]`, `%[slope]`), which are levels here as the
logarithms are.

# `ratio`

```elixir
@type ratio() :: {pos_integer(), pos_integer()}
```

An exact rational factor, `{numerator, denominator}`.

# `reason`

```elixir
@type reason() ::
  :empty
  | {:syntax, String.t()}
  | {:unknown_atom, String.t()}
  | {:not_metric, String.t(), String.t()}
  | {:unknown_currency, String.t()}
  | {:too_large, String.t()}
```

Why a string is not a code.

# `conversion`

```elixir
@spec conversion(code(), code()) ::
  {:ok, {exact(), {integer(), pos_integer()}}}
  | {:error, reason() | conversion_reason()}
```

The exact conversion from one code to another (spec/01 §5, D-155):
`{:ok, {scale, offset}}`, so that a value in `from` is `value × scale + offset` in `to`
— `scale` an exact factor (`{n, d}`, or `{n, d, k}` for n/d·πᵏ), `offset` an exact
signed rational `{n, d}` — or why the two do not convert.

Two codes of one dimension convert by their factors. The affine units `Cel` and
`[degF]` convert with their offsets, standing alone. A logarithmic unit converts only
to its own level. A currency never converts. A refusal is `{:dimension, from, to}`,
`{:logarithmic, from, to}`, `{:currency, from, to}`, `{:affine_in_term, code}`,
`{:too_large, code}` for a scale past `ucum`'s bound, or the reason `parse/1` refuses a
code; a term that is no string is `{:syntax, text}`, never a raise.

## Examples

    iex> Macaw.Units.Unit.conversion("Cel", "[degF]")
    {:ok, {{9, 5}, {32, 1}}}

    iex> Macaw.Units.Unit.conversion("[lb_av]", "kg")
    {:ok, {{45359237, 100000000}, {0, 1}}}

    iex> Macaw.Units.Unit.conversion("dB[SPL]", "Pa")
    {:error, {:logarithmic, "dB[SPL]", "Pa"}}

# `convert`

```elixir
@spec convert(number(), {exact(), {integer(), pos_integer()}}) ::
  {:ok, float()}
  | {:error, :not_a_number | :out_of_range | {:not_a_conversion, term()}}
```

A value written by a conversion `conversion/2` resolved (spec/01 §5), without reading
the codes again: `value × scale + offset` as a float, the value, the scale and the
offset exact and the answer rounded once, by `Ucum.convert/2`. Answers `{:ok, float}`,
`{:error, :not_a_number}` for a value that is no number, `{:error, :out_of_range}` for
an answer past what a float holds, and `{:error, {:not_a_conversion, term}}` for a
conversion that is not `{scale, offset}` as `conversion/2` answers it. Nothing raises,
whatever the value's size. `convert!/2` answers the float or raises.

## Examples

    iex> {:ok, conversion} = Macaw.Units.Unit.conversion("km/h", "m/s")
    iex> Macaw.Units.Unit.convert(72, conversion)
    {:ok, 20.0}

    iex> {:ok, conversion} = Macaw.Units.Unit.conversion("Gm", "nm")
    iex> Macaw.Units.Unit.convert(1.0e300, conversion)
    {:error, :out_of_range}

# `convert`

```elixir
@spec convert(number(), code(), code()) :: {:ok, float()} | {:error, term()}
```

A value in `from` written in `to` (spec/01 §5): `value × scale + offset` of
`conversion/2`, as a float — the value, the scale and the offset exact, and the
arithmetic rounded once (`convert/2`), as `{:ok, float}`; `{:error, reason}` for a pair
`conversion/2` refuses, `{:error, :not_a_number}` for a value that is no number, and
`{:error, {:out_of_range, value, from, to}}` for an answer past what a float holds
(spec/00 §3). `convert!/3` answers the float or raises.

To convert many values between one pair of codes, resolve the conversion once with
`conversion/2` and apply it to each with `convert/2`.

## Examples

    iex> Macaw.Units.Unit.convert(2_500_000, "By", "MBy")
    {:ok, 2.5}

    iex> Macaw.Units.Unit.convert!(100, "Cel", "[degF]")
    212.0

    iex> Macaw.Units.Unit.convert!(30, "dB", "B")
    3.0

    iex> Macaw.Units.Unit.convert(1, "By", "s")
    {:error, {:dimension, "By", "s"}}

    iex> Macaw.Units.Unit.convert(1.0e300, "Gm", "nm")
    {:error, {:out_of_range, 1.0e300, "Gm", "nm"}}

# `convert!`

```elixir
@spec convert!(number(), {exact(), {integer(), pos_integer()}}) :: float()
```

As `convert/2`, the float alone, raising `Macaw.Units.Error` in `format_error/1`'s words.

# `convert!`

```elixir
@spec convert!(number(), code(), code()) :: float()
```

As `convert/3`, the float alone, raising `Macaw.Units.Error` in `format_error/1`'s words.

# `currency`

```elixir
@spec currency(term()) :: String.t() | nil
```

The ISO 4217 code a code is in when it is a currency alone — `{iso4217:USD}` is
`"USD"` — else `nil`: a rate (`{iso4217:USD}/h`), any other unit, or a string that is not
a code (spec/01 §3).

## Examples

    iex> Macaw.Units.Unit.currency("{iso4217:EUR}")
    "EUR"

    iex> Macaw.Units.Unit.currency("{iso4217:EUR}/kW/h")
    nil

# `dimension`

```elixir
@spec dimension(code()) :: {:ok, dimension()} | {:error, reason()}
```

The dimension of a code: `{:ok, dimension}`, each base dimension's exponent, `%{}` when
dimensionless; `parse/1`'s `{:error, reason}` for a string that is not a code
(spec/00 §3). `dimension!/1` answers the dimension or raises.

## Examples

    iex> Macaw.Units.Unit.dimension("[psi]")
    {:ok, %{mass: 1, length: -1, time: -2}}
    iex> Macaw.Units.Unit.dimension!("dB[SPL]")
    %{sound_pressure_level: 1}
    iex> Macaw.Units.Unit.dimension("furlong")
    {:error, {:unknown_atom, "furlong"}}

# `dimension!`

```elixir
@spec dimension!(code()) :: dimension()
```

As `dimension/1`, the dimension alone, raising `Macaw.Units.Error` in `format_error/1`'s words.

# `factor`

```elixir
@spec factor(code()) :: {:ok, exact() | nil} | {:error, reason()}
```

The exact factor of a code to its base: `{numerator, denominator}`, or
`{numerator, denominator, k}` — that rational times πᵏ — for a code holding the degree,
or `nil` for a code holding an affine unit (`Cel`, `[degF]`, `[degRe]`), as
`{:ok, factor}`; `parse/1`'s `{:error, reason}` for a string that is not a code, and
`{:error, {:too_large, code}}` for a factor past `ucum`'s bound, 2⁶⁵⁵³⁶ (spec/01 §2).
`factor!/1` answers the factor or raises.

## Examples

    iex> Macaw.Units.Unit.factor("[ft_i]")
    {:ok, {381, 1250}}
    iex> Macaw.Units.Unit.factor!("deg")
    {1, 180, 1}

# `factor!`

```elixir
@spec factor!(code()) :: exact() | nil
```

As `factor/1`, the factor alone, raising `Macaw.Units.Error` in `format_error/1`'s words.

# `format_error`

```elixir
@spec format_error(reason() | conversion_reason() | term()) :: String.t()
```

A refusal of `parse/1`, `conversion/2` or `convert/3` as a line a person reads; a
reason of `ucum`'s that macaw passes through (`:too_large`) in `Ucum.format_error/1`'s
words. Every term is worded, so it never fails: `Macaw.Units.Error` words its reasons
with it.

## Examples

    iex> Macaw.Units.Unit.format_error({:dimension, "s", "By"})
    ~s|"s" and "By" measure different dimensions|

# `kind`

```elixir
@spec kind(code()) :: {:ok, kind()} | {:error, reason()}
```

How a code's values relate to its base (spec/01 §2): `:affine` for a code holding
`Cel`, `[degF]` or `[degRe]`, `:logarithmic` for one holding a level (`B`, `B[SPL]`,
`Np`, any of UCUM's special units that is not affine), else `:linear`, as
`{:ok, kind}`; `parse/1`'s `{:error, reason}` for a string that is not a code.
`kind!/1` answers the kind or raises.

## Examples

    iex> Macaw.Units.Unit.kind("dB")
    {:ok, :logarithmic}

# `kind!`

```elixir
@spec kind!(code()) :: kind()
```

As `kind/1`, the kind alone, raising `Macaw.Units.Error` in `format_error/1`'s words.

# `minor_units`

```elixir
@spec minor_units(String.t()) :: {:ok, non_neg_integer() | nil} | {:error, reason()}
```

An ISO 4217 code's minor units — the decimals an amount in it is written to — or `nil`
for a code with none (`XAU`), as `{:ok, units}`; `{:error, {:unknown_currency, code}}`
for a code not in the table. `minor_units!/1` answers the units or raises.

## Examples

    iex> Enum.map(~w(USD JPY BHD XAU), &Macaw.Units.Unit.minor_units!/1)
    [2, 0, 3, nil]
    iex> Macaw.Units.Unit.minor_units("ZZZ")
    {:error, {:unknown_currency, "ZZZ"}}

# `minor_units!`

```elixir
@spec minor_units!(String.t()) :: non_neg_integer() | nil
```

As `minor_units/1`, the units alone, raising `Macaw.Units.Error` in `format_error/1`'s words.

# `parse`

```elixir
@spec parse(String.t()) :: {:ok, [component(), ...]} | {:error, reason()}
```

The components of a code, or why it is not one (spec/01 §1).

## Examples

    iex> Macaw.Units.Unit.parse("km/h")
    {:ok,
     [
       %{prefix: "k", atom: "m", factor: nil, annotation: nil, exponent: 1},
       %{prefix: nil, atom: "h", factor: nil, annotation: nil, exponent: -1}
     ]}

    iex> Macaw.Units.Unit.parse("kmin")
    {:error, {:not_metric, "k", "min"}}

# `symbol`

```elixir
@spec symbol(code(), keyword()) :: {:ok, String.t()} | {:error, reason()}
```

The display symbol of a code (spec/01 §4): `B` for `By`, `µs` for `us`, `°C` for
`Cel`, `kW·h` for `kW.h`, `m²` for `m2`; the factor `1` and annotations are dropped, so
`1` and `{request}` are `""`.

## Options

- `:annotations` - write an annotation standing alone as its text (`{request}/s` →
  `request/s`), default `false`

## Examples

    iex> Macaw.Units.Unit.symbol("us")
    {:ok, "µs"}

    iex> Macaw.Units.Unit.symbol!("{request}/s", annotations: true)
    "request/s"

# `symbol!`

```elixir
@spec symbol!(code(), keyword()) :: String.t()
```

As `symbol/2`, the symbol alone, raising `Macaw.Units.Error` in `format_error/1`'s words.

# `valid?`

```elixir
@spec valid?(term()) :: boolean()
```

Whether a string is a code `parse/1` reads.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
