From e1a8870c55b7e86b216b025d69d2c1166139497d Mon Sep 17 00:00:00 2001 From: Felix Claessen <30658763+Flix6x@users.noreply.github.com> Date: Tue, 8 Feb 2022 22:46:04 +0100 Subject: [PATCH] Register percent and permille units (#359) * Register percent and permille units Signed-off-by: F.N. Claessen * Changelog entry Signed-off-by: F.N. Claessen * Add test case Signed-off-by: F.N. Claessen --- documentation/changelog.rst | 1 + flexmeasures/utils/tests/test_unit_utils.py | 1 + flexmeasures/utils/unit_utils.py | 10 +++++++++- 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/documentation/changelog.rst b/documentation/changelog.rst index 0bf37f6ba..f68ac3c12 100644 --- a/documentation/changelog.rst +++ b/documentation/changelog.rst @@ -15,6 +15,7 @@ New features * Add CLI commands ``flexmeasures add sensor``, ``flexmeasures add asset-type``, ``flexmeasures add beliefs`` (which were experimental features before). [see `PR #337 `_] * Add CLI commands for showing data [see `PR #339 `_] * Add CLI command for attaching annotations to assets: ``flexmeasures add holidays`` adds public holidays [see `PR #343 `_] +* Support for percent (%) and permille (‰) sensor units [see `PR #359 `_] Bugfixes ----------- diff --git a/flexmeasures/utils/tests/test_unit_utils.py b/flexmeasures/utils/tests/test_unit_utils.py index 642255eab..eaa6c97ed 100644 --- a/flexmeasures/utils/tests/test_unit_utils.py +++ b/flexmeasures/utils/tests/test_unit_utils.py @@ -20,6 +20,7 @@ @pytest.mark.parametrize( "from_unit, to_unit, expected_multiplier, expected_values", [ + ("%", "‰", 10, None), ("m/s", "km/h", 3.6, None), ("m³/h", "l/h", 1000, None), ("m³", "m³/h", 4, None), diff --git a/flexmeasures/utils/unit_utils.py b/flexmeasures/utils/unit_utils.py index 8f70bfbec..d634bc53a 100644 --- a/flexmeasures/utils/unit_utils.py +++ b/flexmeasures/utils/unit_utils.py @@ -31,8 +31,16 @@ ) # Set up UnitRegistry with abbreviated scientific format -ur = pint.UnitRegistry(full_template) +ur = pint.UnitRegistry( + full_template, + preprocessors=[ + lambda s: s.replace("%", " percent "), + lambda s: s.replace("‰", " permille "), + ], +) ur.default_format = "~P" # short pretty +ur.define("percent = 1 / 100 = %") +ur.define("permille = 1 / 1000 = ‰") PREFERRED_UNITS = [