Skip to content

to_compact() fails with numpy quantities #2274

@sieben-gea

Description

@sieben-gea

to_compact() is a no-op on NumpyQuantitys and results in the warning:

UndefinedBehavior: to_compact applied to non numerical types has an undefined behavior.
qty.to_compact()

The problem appears, because for numpy quantities, the qty.magnitude is of type ndarray, which is non-numeric, an therefore qto.to_compact() returns the quantity without change:

if not isinstance(quantity.magnitude, numbers.Number) and not hasattr(
quantity.magnitude, "nominal_value"
):
warnings.warn(
"to_compact applied to non numerical types has an undefined behavior.",
UndefinedBehavior,
stacklevel=2,
)
return quantity

The method should be modified to accept ndarray by using either the maximum or minimum order of magnitude in the array to select the unit prefix.

Minimal example to reproduce the problem:

from pint import UnitRegistry
ureg = UnitRegistry(force_ndarray=True)
qty = ureg[Any]('1e+3 g')
qty.to_compact() # 1000.0 gram

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions