Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

to_compact: support uncertainties' Magnitudes , keeping warning #1911

Merged
merged 3 commits into from
Jan 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions pint/facets/numpy/quantity.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from ..plain import PlainQuantity, MagnitudeT

from ..._typing import Shape
from ...compat import _to_magnitude, np
from ...compat import _to_magnitude, np, HAS_NUMPY
from ...errors import DimensionalityError, PintTypeError, UnitStrippedWarning
from .numpy_func import (
HANDLED_UFUNCS,
Expand Down Expand Up @@ -115,11 +115,12 @@ def _numpy_method_wrap(self, func, *args, **kwargs):
return value

def __array__(self, t=None) -> np.ndarray:
warnings.warn(
"The unit of the quantity is stripped when downcasting to ndarray.",
UnitStrippedWarning,
stacklevel=2,
)
if HAS_NUMPY and isinstance(self._magnitude, np.ndarray):
warnings.warn(
"The unit of the quantity is stripped when downcasting to ndarray.",
UnitStrippedWarning,
stacklevel=2,
)
return _to_magnitude(self._magnitude, force_ndarray=True)

def clip(self, min=None, max=None, out=None, **kwargs):
Expand Down
7 changes: 6 additions & 1 deletion pint/facets/plain/qto.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,9 @@ def to_compact(
<Quantity(10.0, 'millinewton')>
"""

if not isinstance(quantity.magnitude, numbers.Number):
if not isinstance(quantity.magnitude, numbers.Number) and not hasattr(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nicer indeed!

quantity.magnitude, "nominal_value"
):
msg = "to_compact applied to non numerical types " "has an undefined behavior."
w = RuntimeWarning(msg)
warnings.warn(w, stacklevel=2)
Expand Down Expand Up @@ -137,6 +139,9 @@ def to_compact(
q_base = quantity.to(unit)

magnitude = q_base.magnitude
# Support uncertainties
if hasattr(magnitude, "nominal_value"):
magnitude = magnitude.nominal_value

units = list(q_base._units.items())
units_numerator = [a for a in units if a[1] > 0]
Expand Down
Loading