UCUM, the Unified Code for Units of Measure (https://ucum.org/ucum, Regenstrief Institute), for Elixir: unit codes such as kg/m2, mm[Hg] and {request}/s read, checked and converted as the standard defines them (spec/00).

A code is UCUM's case-sensitive form (case_sensitive/1 answers it for a case-insensitive code). parse/1 reads it into its components, or says why it is not a code; a typo is refused, never guessed at. A code has a dimension (dimension/1), an exact factor to its base units (factor/1), and a kind (kind/1). Two codes of one dimension convert exactly (conversion/2, convert/3), and a code is written for a reader by symbol/2 and named by name/1.

The library reads all of UCUM's grammar and all of its table (spec/01): a string that is not a code is refused with a named reason.

Every function answers {:ok, value} or {:error, reason}; format_error/1 writes a reason as a sentence, and each ! twin answers the value alone or raises Ucum.Error.

Examples

iex> Ucum.valid?("kW.h")
true

iex> Ucum.parse("sec")
{:error, {:unknown_atom, "sec"}}

iex> Ucum.symbol!("By/s")
"B/s"

iex> Ucum.convert!(1500, "ms", "s")
1.5

Summary

Types

Why multiply/2 and divide/2 refuse two quantities.

An atom of the table and its definition (atom/1).

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

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

An exact linear or affine conversion (conversion/2): {scale, offset}, so that a value converts as value × scale + offset.

Why conversion/2 refuses a pair of codes.

UCUM's seven base dimensions, each with its exponent; %{} is dimensionless. The base units are m, s, g, rad, K, C and cd. An arbitrary unit is a dimension of its own, under its code: [IU]/mL is %{"[iU]" => 1, length: -3}.

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

How a code's values relate to its base: by a factor, an offset or another function.

A prefix of the table and its definition (prefix/1).

A value with its unit: {1.5, "g"}.

An exact rational factor, {numerator, denominator}.

Why a string is not a code, or not an atom or a prefix of the table; :too_large also why a code has no factor (spec/01 §6).

Functions

An atom of the table and its definition (spec/01 §4): its dimension, its factor to its base (nil for a special unit), whether it is metric (only a metric atom takes a prefix), its kind and its display symbol. A string that is no single atom — a prefixed code such as km among them — is {:error, {:unknown_atom, string}}.

The code of every atom the table holds, sorted (spec/01 §3).

A code in UCUM's base units (spec/02 §8): {:ok, {factor, code}}, the code's exact factor (factor/1's, nil for a code holding a special unit) and the code of its dimension, the base units in the order m, s, g, rad, K, C, cd, then any arbitrary units, each with its exponent; 1 for a dimensionless code. One of the code is factor of its canonical code. canonical!/1 answers the pair or raises.

As canonical/1, the pair alone, raising Ucum.Error in format_error/1's words.

A case-insensitive UCUM code as its case-sensitive code (spec/01 §5): {:ok, code}, for the other functions here, which read the case-sensitive form only. The case-insensitive form is UCUM's second set of codes, not the first in capitals: M is milli and MA mega, HR the hour and H the henry, PAL the pascal. It is read in any case; an annotation is kept as it is written. A string that is no case-insensitive code is parse/1's {:error, reason}. case_sensitive!/1 answers the code or raises.

As case_sensitive/1, the code alone, raising Ucum.Error in format_error/1's words.

The exact conversion from one code to another (spec/02 §4): {: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.

Applies a resolved conversion from conversion/2 to a value (spec/02 §4): value × scale + offset as a float, with convert/3's range-safe exact arithmetic and rounding, without reading the unit codes again.

A value in from written in to (spec/02 §4): value × scale + offset of conversion/2, as a float — the value, the scale and the offset exact, and the arithmetic rounded once, 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/02 §9). convert!/3 answers the float or raises.

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

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

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/02 §1). dimension!/1 answers the dimension or raises.

As dimension/1, the dimension alone, raising Ucum.Error in format_error/1's words.

The quotient of two quantities (spec/02 §8), as multiply/2: {:ok, {value, code}} in base units. Two quantities of one dimension divide to the unity, 1. A divisor of value zero is {:error, :division_by_zero}. divide!/2 answers the quantity or raises.

As divide/2, the quantity alone, raising Ucum.Error in format_error/1's words.

The version of UCUM's essence table (ucum-essence.xml) this library is compiled from.

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 a special unit (Cel, [degF], B, [pH], …), which has no ratio to its base, as {:ok, factor}; parse/1's {:error, reason} for a string that is not a code (spec/02 §2), and {:error, {:too_large, code}} for a code whose factor is past the size the library holds (spec/01 §6): the factor the code has, what cancels in it having cancelled. factor!/1 answers the factor or raises.

As factor/1, the factor alone, raising Ucum.Error in format_error/1's words.

A refusal of any function here as a line a person reads (spec/03). A term that is no reason of this library answers a line that says so; nothing raises.

How a code's values relate to its base (spec/02 §3): :affine for a code holding Cel, [degF] or [degRe], :nonlinear for one holding any other of UCUM's special units (B, B[SPL], [pH], …), 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.

As kind/1, the kind alone, raising Ucum.Error in format_error/1's words.

The product of two quantities (spec/02 §8), each a {value, code}: {:ok, {value, code}} in base units, the code canonical (canonical/1) and the value a float. A code holding a special unit is {:error, {:special_in_term, code}}, an argument that is no {value, code} pair {:error, {:not_a_quantity, term}}, a value that is no number {:error, :not_a_number}, a product past what a float holds {:error, :out_of_range}. multiply!/2 answers the quantity or raises.

As multiply/2, the quantity alone, raising Ucum.Error in format_error/1's words.

The name of a code (spec/02 §7): the code as it is written, each unit by UCUM's name for it and in parentheses, with * for ., / for / and ^ before an exponent — the form of the UCUM functional tests. name!/1 answers the name or raises.

As name/1, the name alone, raising Ucum.Error in format_error/1's words.

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

A prefix of the table and its definition (spec/01 §4): its exact factor and its display symbol; {:error, {:unknown_prefix, string}} for any other string.

The code of every prefix the table holds, sorted (spec/01 §3).

The display symbol of a code (spec/02 §5): 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 "". symbol!/2 answers the symbol or raises.

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

Whether a term is a code parse/1 reads.

Types

arithmetic_reason()

@type arithmetic_reason() ::
  {:special_in_term, code()}
  | {:not_a_quantity, term()}
  | :not_a_number
  | :division_by_zero
  | :out_of_range

Why multiply/2 and divide/2 refuse two quantities.

atom_definition()

@type atom_definition() :: %{
  code: String.t(),
  dimension: dimension(),
  factor: exact() | nil,
  metric: boolean(),
  kind: kind(),
  symbol: String.t()
}

An atom of the table and its definition (atom/1).

code()

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

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

component()

@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()

@type conversion() :: {exact(), {integer(), pos_integer()}}

An exact linear or affine conversion (conversion/2): {scale, offset}, so that a value converts as value × scale + offset.

conversion_reason()

@type conversion_reason() ::
  {:dimension | :not_linear, code(), code()}
  | {:special_in_term, code()}
  | {:out_of_domain | :out_of_range, number(), code(), code()}

Why conversion/2 refuses a pair of codes.

dimension()

@type dimension() :: %{
  optional(
    :length
    | :time
    | :mass
    | :angle
    | :temperature
    | :charge
    | :luminous_intensity
    | String.t()
  ) => integer()
}

UCUM's seven base dimensions, each with its exponent; %{} is dimensionless. The base units are m, s, g, rad, K, C and cd. An arbitrary unit is a dimension of its own, under its code: [IU]/mL is %{"[iU]" => 1, length: -3}.

exact()

@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()

@type kind() :: :linear | :affine | :nonlinear

How a code's values relate to its base: by a factor, an offset or another function.

prefix_definition()

@type prefix_definition() :: %{code: String.t(), factor: ratio(), symbol: String.t()}

A prefix of the table and its definition (prefix/1).

quantity()

@type quantity() :: {number(), code()}

A value with its unit: {1.5, "g"}.

ratio()

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

An exact rational factor, {numerator, denominator}.

reason()

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

Why a string is not a code, or not an atom or a prefix of the table; :too_large also why a code has no factor (spec/01 §6).

Functions

atom(code)

@spec atom(String.t()) :: {:ok, atom_definition()} | {:error, reason()}

An atom of the table and its definition (spec/01 §4): its dimension, its factor to its base (nil for a special unit), whether it is metric (only a metric atom takes a prefix), its kind and its display symbol. A string that is no single atom — a prefixed code such as km among them — is {:error, {:unknown_atom, string}}.

Examples

iex> Ucum.atom("[ft_i]")
{:ok,
 %{code: "[ft_i]", dimension: %{length: 1}, factor: {381, 1250}, metric: false,
   kind: :linear, symbol: "ft"}}

iex> Ucum.atom("km")
{:error, {:unknown_atom, "km"}}

atoms()

@spec atoms() :: [String.t()]

The code of every atom the table holds, sorted (spec/01 §3).

Examples

iex> "[ft_i]" in Ucum.atoms()
true

canonical(code)

@spec canonical(code()) :: {:ok, {exact() | nil, code()}} | {:error, reason()}

A code in UCUM's base units (spec/02 §8): {:ok, {factor, code}}, the code's exact factor (factor/1's, nil for a code holding a special unit) and the code of its dimension, the base units in the order m, s, g, rad, K, C, cd, then any arbitrary units, each with its exponent; 1 for a dimensionless code. One of the code is factor of its canonical code. canonical!/1 answers the pair or raises.

Examples

iex> Ucum.canonical("km/h")
{:ok, {{5, 18}, "m.s-1"}}

iex> Ucum.canonical("N")
{:ok, {{1000, 1}, "m.s-2.g"}}

iex> Ucum.canonical!("%")
{{1, 100}, "1"}

canonical!(code)

@spec canonical!(code()) :: {exact() | nil, code()}

As canonical/1, the pair alone, raising Ucum.Error in format_error/1's words.

case_sensitive(code)

@spec case_sensitive(String.t()) :: {:ok, code()} | {:error, reason()}

A case-insensitive UCUM code as its case-sensitive code (spec/01 §5): {:ok, code}, for the other functions here, which read the case-sensitive form only. The case-insensitive form is UCUM's second set of codes, not the first in capitals: M is milli and MA mega, HR the hour and H the henry, PAL the pascal. It is read in any case; an annotation is kept as it is written. A string that is no case-insensitive code is parse/1's {:error, reason}. case_sensitive!/1 answers the code or raises.

Examples

iex> Ucum.case_sensitive("MM[HG]")
{:ok, "mm[Hg]"}

iex> Ucum.case_sensitive("MAM/HR")
{:ok, "Mm/h"}

iex> Ucum.case_sensitive!("10*3/ul")
"10*3/ul"

iex> Ucum.case_sensitive("SEC")
{:error, {:unknown_atom, "SEC"}}

case_sensitive!(code)

@spec case_sensitive!(String.t()) :: code()

As case_sensitive/1, the code alone, raising Ucum.Error in format_error/1's words.

conversion(from, to)

@spec conversion(code(), code()) ::
  {:ok, conversion()} | {:error, reason() | conversion_reason()}

The exact conversion from one code to another (spec/02 §4): {: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, [degF] and [degRe] convert with their offsets, standing alone. Any other special unit converts to itself under another prefix (dB to B); to any other unit of its dimension it converts through its function, which is no scale and offset: {:not_linear, from, to}, and convert/3 converts a value. A special unit inside a term is {:special_in_term, code}, two dimensions {:dimension, from, to}, and a string that is not a code the reason parse/1 refuses it.

Examples

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

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

iex> Ucum.conversion("dB[SPL]", "Pa")
{:error, {:not_linear, "dB[SPL]", "Pa"}}

convert(value, conversion)

@spec convert(number(), conversion()) ::
  {:ok, float()}
  | {:error, :not_a_number | :out_of_range | {:not_a_conversion, term()}}

Applies a resolved conversion from conversion/2 to a value (spec/02 §4): value × scale + offset as a float, with convert/3's range-safe exact arithmetic and rounding, without reading the unit codes again.

Answers {:ok, float}, {:error, :not_a_number} for a value that is no number, {:error, {:not_a_conversion, term}} for a conversion that is not {scale, offset} as conversion/2 answers them, and {:error, :out_of_range} for an answer past what a float holds (spec/02 §9). convert!/2 answers the float or raises.

Examples

iex> {:ok, conv} = Ucum.conversion("km/h", "m/s")
iex> Ucum.convert(72.5, conv)
{:ok, 20.13888888888889}

iex> {:ok, conv} = Ucum.conversion("Cel", "[degF]")
iex> Ucum.convert!(100, conv)
212.0

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

convert(value, from, to)

@spec convert(number(), code(), code()) ::
  {:ok, float()} | {:error, reason() | conversion_reason() | :not_a_number}

A value in from written in to (spec/02 §4): value × scale + offset of conversion/2, as a float — the value, the scale and the offset exact, and the arithmetic rounded once, 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/02 §9). convert!/3 answers the float or raises.

Examples

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

iex> Ucum.convert!(100, "Cel", "[degF]")
212.0

iex> Ucum.convert!(30, "dB", "B")
3.0

iex> Ucum.convert(30, "dB", "1")
{:ok, 1000.0}

iex> Ucum.convert(7, "[pH]", "mol/l")
{:ok, 1.0e-7}

iex> Ucum.convert(0, "1", "dB")
{:error, {:out_of_domain, 0, "1", "dB"}}

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

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

convert!(value, conversion)

@spec convert!(number(), conversion()) :: float()

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

convert!(value, from, to)

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

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

dimension(code)

@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/02 §1). dimension!/1 answers the dimension or raises.

Examples

iex> Ucum.dimension("[psi]")
{:ok, %{mass: 1, length: -1, time: -2}}
iex> Ucum.dimension!("By/s")
%{time: -1}
iex> Ucum.dimension("furlong")
{:error, {:unknown_atom, "furlong"}}

dimension!(code)

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

As dimension/1, the dimension alone, raising Ucum.Error in format_error/1's words.

divide(left, right)

@spec divide(quantity(), quantity()) ::
  {:ok, {float(), code()}} | {:error, reason() | arithmetic_reason()}

The quotient of two quantities (spec/02 §8), as multiply/2: {:ok, {value, code}} in base units. Two quantities of one dimension divide to the unity, 1. A divisor of value zero is {:error, :division_by_zero}. divide!/2 answers the quantity or raises.

Examples

iex> Ucum.divide({1.5, "g"}, {2, "m"})
{:ok, {0.75, "m-1.g"}}

iex> Ucum.divide({90, "km"}, {2, "h"})
{:ok, {12.5, "m.s-1"}}

iex> Ucum.divide({1, "[mi_i]"}, {1, "km"})
{:ok, {1.609344, "1"}}

divide!(left, right)

@spec divide!(quantity(), quantity()) :: {float(), code()}

As divide/2, the quantity alone, raising Ucum.Error in format_error/1's words.

essence_version()

@spec essence_version() :: String.t()

The version of UCUM's essence table (ucum-essence.xml) this library is compiled from.

Examples

iex> Ucum.essence_version()
"2.2"

factor(code)

@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 a special unit (Cel, [degF], B, [pH], …), which has no ratio to its base, as {:ok, factor}; parse/1's {:error, reason} for a string that is not a code (spec/02 §2), and {:error, {:too_large, code}} for a code whose factor is past the size the library holds (spec/01 §6): the factor the code has, what cancels in it having cancelled. factor!/1 answers the factor or raises.

Examples

iex> Ucum.factor("[ft_i]")
{:ok, {381, 1250}}
iex> Ucum.factor!("deg")
{1, 180, 1}
iex> Ucum.factor("km999999")
{:error, {:too_large, "km999999"}}

iex> Ucum.factor("km999999/km999998")
{:ok, {1000, 1}}

factor!(code)

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

As factor/1, the factor alone, raising Ucum.Error in format_error/1's words.

format_error(reason)

@spec format_error(term()) :: String.t()

A refusal of any function here as a line a person reads (spec/03). A term that is no reason of this library answers a line that says so; nothing raises.

Examples

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

kind(code)

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

How a code's values relate to its base (spec/02 §3): :affine for a code holding Cel, [degF] or [degRe], :nonlinear for one holding any other of UCUM's special units (B, B[SPL], [pH], …), 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> Ucum.kind("dB")
{:ok, :nonlinear}

kind!(code)

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

As kind/1, the kind alone, raising Ucum.Error in format_error/1's words.

multiply(left, right)

@spec multiply(quantity(), quantity()) ::
  {:ok, {float(), code()}} | {:error, reason() | arithmetic_reason()}

The product of two quantities (spec/02 §8), each a {value, code}: {:ok, {value, code}} in base units, the code canonical (canonical/1) and the value a float. A code holding a special unit is {:error, {:special_in_term, code}}, an argument that is no {value, code} pair {:error, {:not_a_quantity, term}}, a value that is no number {:error, :not_a_number}, a product past what a float holds {:error, :out_of_range}. multiply!/2 answers the quantity or raises.

Examples

iex> Ucum.multiply({1.5, "g"}, {2, "m"})
{:ok, {3.0, "m.g"}}

iex> Ucum.multiply({2, "kW"}, {3, "h"})
{:ok, {2.16e10, "m2.s-2.g"}}

multiply!(left, right)

@spec multiply!(quantity(), quantity()) :: {float(), code()}

As multiply/2, the quantity alone, raising Ucum.Error in format_error/1's words.

name(code)

@spec name(code()) :: {:ok, String.t()} | {:error, reason()}

The name of a code (spec/02 §7): the code as it is written, each unit by UCUM's name for it and in parentheses, with * for ., / for / and ^ before an exponent — the form of the UCUM functional tests. name!/1 answers the name or raises.

Examples

iex> Ucum.name("km/h")
{:ok, "(kilometer) / (hour)"}

iex> Ucum.name!("m3.kg-1.s-2")
"(meter ^ 3) * (kilogram ^ -1) * (second ^ -2)"

iex> Ucum.name("g/(m.s2)")
{:ok, "(gram) / ((meter) * (second ^ 2))"}

iex> Ucum.name("sec")
{:error, {:unknown_atom, "sec"}}

name!(code)

@spec name!(code()) :: String.t()

As name/1, the name alone, raising Ucum.Error in format_error/1's words.

parse(code)

@spec parse(term()) :: {:ok, [component(), ...]} | {:error, reason()}

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

Examples

iex> Ucum.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> Ucum.parse("kmin")
{:error, {:not_metric, "k", "min"}}

prefix(code)

@spec prefix(String.t()) :: {:ok, prefix_definition()} | {:error, reason()}

A prefix of the table and its definition (spec/01 §4): its exact factor and its display symbol; {:error, {:unknown_prefix, string}} for any other string.

Examples

iex> Ucum.prefix("u")
{:ok, %{code: "u", factor: {1, 1000000}, symbol: "μ"}}

iex> Ucum.prefix("x")
{:error, {:unknown_prefix, "x"}}

prefixes()

@spec prefixes() :: [String.t()]

The code of every prefix the table holds, sorted (spec/01 §3).

Examples

iex> Ucum.prefixes() |> Enum.take(3)
["E", "G", "Gi"]

symbol(code, opts \\ [])

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

The display symbol of a code (spec/02 §5): 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 "". symbol!/2 answers the symbol or raises.

Options

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

Options that are no keyword list, any other option and an :annotations that is no boolean are {:error, {:bad_options, opts}}.

Examples

iex> Ucum.symbol("us")
{:ok, "μs"}

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

symbol!(code, opts \\ [])

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

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

valid?(code)

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

Whether a term is a code parse/1 reads.