Skip to content

Commit 3bf7403

Browse files
authored
Add function for splitting units and add a test (#4641)
1 parent c471f0d commit 3bf7403

File tree

2 files changed

+26
-8
lines changed

2 files changed

+26
-8
lines changed

src/pybamm/experiment/step/base_step.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
#
2-
# Private classes and functions for experiment steps
3-
#
1+
from __future__ import annotations
42
import pybamm
53
import numpy as np
64
from datetime import datetime
@@ -492,6 +490,10 @@ def set_up(self, new_model, new_parameter_values):
492490
}
493491

494492

493+
def get_unit_from(a_string: str) -> str:
494+
return a_string.lstrip("0123456789.-eE ")
495+
496+
495497
def _convert_time_to_seconds(time_and_units):
496498
"""Convert a time in seconds, minutes or hours to a time in seconds"""
497499
if time_and_units is None:
@@ -501,11 +503,10 @@ def _convert_time_to_seconds(time_and_units):
501503
if isinstance(time_and_units, numbers.Number):
502504
if time_and_units <= 0:
503505
raise ValueError("time must be positive")
504-
else:
505-
return time_and_units
506+
return time_and_units
506507

507508
# Split number and units
508-
units = time_and_units.lstrip("0123456789.- ")
509+
units = get_unit_from(time_and_units)
509510
time = time_and_units[: -len(units)]
510511
if units in ["second", "seconds", "s", "sec"]:
511512
time_in_seconds = float(time)
@@ -528,7 +529,7 @@ def _convert_temperature_to_kelvin(temperature_and_units):
528529
return temperature_and_units
529530

530531
# Split number and units
531-
units = temperature_and_units.lstrip("0123456789.- ")
532+
units = get_unit_from(temperature_and_units)
532533
temperature = temperature_and_units[: -len(units)]
533534
if units in ["K"]:
534535
temperature_in_kelvin = float(temperature)
@@ -547,7 +548,7 @@ def _convert_electric(value_string):
547548
value = 1 / float(value_string[2:])
548549
else:
549550
# All other cases e.g. 4 A, 2.5 V, 1.5 Ohm
550-
unit = value_string.lstrip("0123456789.- ")
551+
unit = get_unit_from(value_string)
551552
value = float(value_string[: -len(unit)])
552553
# Catch milli- prefix
553554
if unit.startswith("m"):
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import pytest
2+
import pybamm
3+
4+
5+
@pytest.mark.parametrize(
6+
"test_string, unit_string",
7+
[
8+
("123e-1 W", "W"),
9+
("123K", "K"),
10+
("1A", "A"),
11+
("2.0 mV", "mV"),
12+
("0.5 Ohm", "Ohm"),
13+
("1e0hours", "hours"),
14+
],
15+
)
16+
def test_read_units(test_string, unit_string):
17+
assert unit_string == pybamm.experiment.step.base_step.get_unit_from(test_string)

0 commit comments

Comments
 (0)