Skip to content

Commit

Permalink
attempt
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewgsavage committed May 24, 2024
1 parent 11b3ee8 commit 4b931fa
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 11 deletions.
4 changes: 3 additions & 1 deletion pint/delegates/formatter/_compound_unit_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
)

from ...compat import babel_parse
from ...util import UnitsContainer
from ...util import NonReducingUnitsContainer, UnitsContainer

T = TypeVar("T")
U = TypeVar("U")
Expand Down Expand Up @@ -250,6 +250,8 @@ def prepare_compount_unit(

if isinstance(unit, UnitsContainer):
out = unit.items()
elif hasattr(unit, "_units") and isinstance(unit._units, NonReducingUnitsContainer):
out = unit._units.non_reduced_d_items
elif hasattr(unit, "_units"):
out = unit._units.items()
else:
Expand Down
9 changes: 8 additions & 1 deletion pint/delegates/formatter/full.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

from ..._typing import Magnitude
from ...compat import Unpack, babel_parse
from ...util import iterable
from ...util import NonReducingUnitsContainer, iterable
from ._compound_unit_helpers import BabelKwds, SortFunc, sort_by_unit_name
from ._to_register import REGISTERED_FORMATTERS
from .html import HTMLFormatter
Expand All @@ -40,6 +40,11 @@
from ...registry import UnitRegistry


def _sort_func(items, registry):
# print([i for i in items])
return items


class FullFormatter(BaseFormatter):
"""A formatter that dispatch to other formatters.
Expand Down Expand Up @@ -126,6 +131,8 @@ def format_unit(
) -> str:
uspec = uspec or self.default_format
sort_func = sort_func or self.default_sort_func
if isinstance(unit._units, NonReducingUnitsContainer):
sort_func = _sort_func
return self.get_formatter(uspec).format_unit(
unit, uspec, sort_func=sort_func, **babel_kwds
)
Expand Down
2 changes: 2 additions & 0 deletions pint/delegates/formatter/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,9 @@ def format_unit(
division_fmt = localize_per(length, babel_kwds.get("locale"), "{}/{}")
else:
division_fmt = "{}/{}"
import pdb

pdb.set_trace()
return formatter(
numerator,
denominator,
Expand Down
6 changes: 3 additions & 3 deletions pint/facets/plain/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
from ...errors import DimensionalityError, RedefinitionError, UndefinedUnitError
from ...pint_eval import build_eval_tree
from ...util import (
NonReducingUnitContainer,
NonReducingUnitsContainer,
ParserHelper,
UnitsContainer,
_is_dim,
Expand Down Expand Up @@ -1407,8 +1407,8 @@ def UnitsContainer(self, *args: Any, **kwargs: Any) -> UnitsContainer:

__call__ = parse_expression

def NonReducingUnitContainer(self, units) -> UnitsContainer:
return NonReducingUnitContainer(units)
def NonReducingUnitsContainer(self, units) -> UnitsContainer:
return NonReducingUnitsContainer(units)


class PlainRegistry(GenericPlainRegistry[PlainQuantity[Any], PlainUnit]):
Expand Down
13 changes: 13 additions & 0 deletions pint/testsuite/test_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -832,6 +832,19 @@ def test_case_sensitivity(self):
assert ureg.parse_units("j", case_sensitive=False) == UnitsContainer(joule=1)


class TestNonReducing(QuantityTestCase):
def test_init(self):
ureg = self.ureg
NRUC_ = ureg.NonReducingUnitsContainer

mm_per_mm_unit = NRUC_([(ureg.mm, 1), (ureg.mm, -1)])
assert mm_per_mm_unit.non_reduced_units == [
ureg.UnitsContainer({"millimeter": 1}),
ureg.UnitsContainer({"millimeter": -1}),
]
assert mm_per_mm_unit == ureg.dimensionless


class TestCaseInsensitiveRegistry(QuantityTestCase):
kwargs = dict(case_sensitive=False)

Expand Down
32 changes: 26 additions & 6 deletions pint/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -676,26 +676,46 @@ def _normalize_nonfloat_value(self, value: Scalar) -> Scalar:
return value


class NonReducingUnitContainer(UnitsContainer):
"""The NonReducingUnitContainer stores UnitsContainers without simplifying common units.
class NonReducingUnitsContainer(UnitsContainer):
"""The NonReducingUnitsContainer stores UnitsContainers without simplifying common units.
This is useful when it is desired to show a unit in the numerator and denominator, eg mm/mm.
"""

def __init__(
self, units: list[UnitsContainer] | list[tuple[QuantityOrUnitLike, Scalar]]
) -> None:
if all(isinstance(u, tuple) for u in units):
units = [u[0]._units ** u[1] for u in units]
self.non_reduced_units = []

self.non_reduced_units = units
for u in units:
if isinstance(u, tuple):
u = u[0]._units ** u[1]
if hasattr(u, "_units"):
u = u._units
self.non_reduced_units.append(u)

self.reduced_units = UnitsContainer()
for unit in units:
for unit in self.non_reduced_units:
self.reduced_units *= unit

self._d = self.reduced_units._d
self._hash = self.reduced_units._hash

self.non_reduced_d_items = [
(key, value)
for uc in self.non_reduced_units
for key, value in uc._d.items()
]
self.i = 0

def __repr__(self) -> str:
tmp = "[%s]" % ", ".join(
[f"'{key}': {value}" for key, value in self.non_reduced_d_items]
)
return f"<NonReducingUnitsContainer({tmp})>"

def unit_items(self) -> Iterable[tuple[str, Scalar]]:
return [items for _d in self.non_reduced_units for items in _d.items()]


class ParserHelper(UnitsContainer):
"""The ParserHelper stores in place the product of variables and
Expand Down

0 comments on commit 4b931fa

Please sign in to comment.