Skip to content

Commit

Permalink
Added __iter__ and __contains__ method to pybamm.ParameterValues (#4465)
Browse files Browse the repository at this point in the history
* Added __contains__ and __iter__ in pybamm.ParameterValues

* After running pre_commit

* added tests to verify __iter__ and __contains__ method work-2

* Update tests/unit/test_parameters/test_parameter_values.py

Deleted print statement which was intended for debugging

Co-authored-by: Agriya Khetarpal <[email protected]>

* Update tests/unit/test_parameters/test_parameter_values.py

---------

Co-authored-by: Agriya Khetarpal <[email protected]>
Co-authored-by: Arjun Verma <[email protected]>
  • Loading branch information
3 people authored Sep 25, 2024
1 parent 1b6ef03 commit e148006
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/pybamm/parameters/parameter_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -930,3 +930,9 @@ def print_evaluated_parameters(self, evaluated_parameters, output_file):
file.write((s + " : {:10.4g}\n").format(name, value))
else:
file.write((s + " : {:10.3E}\n").format(name, value))

def __contains__(self, key):
return key in self._dict_items

def __iter__(self):
return iter(self._dict_items)
21 changes: 21 additions & 0 deletions tests/unit/test_parameters/test_parameter_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
)
from pybamm.expression_tree.exceptions import OptionError
import casadi
from pybamm.parameters.parameter_values import ParameterValues


class TestParameterValues:
Expand Down Expand Up @@ -1029,3 +1030,23 @@ def test_exchange_current_density_plating(self):
match="referring to the reaction at the surface of a lithium metal electrode",
):
parameter_values.evaluate(param)

def test_contains_method(self):
"""Test for __contains__ method to check the functionality of 'in' keyword"""
parameter_values = ParameterValues(
{"Negative particle radius [m]": 1e-6, "Positive particle radius [m]": 2e-6}
)
assert (
"Negative particle radius [m]" in parameter_values
), "Key should be found in parameter_values"
assert (
"Invalid key" not in parameter_values
), "Non-existent key should not be found"

def test_iter_method(self):
"""Test for __iter__ method to check if we can iterate over keys"""
parameter_values = ParameterValues(
values={"Negative particle radius [m]": 1e-6}
)
pv = [i for i in parameter_values]
assert len(pv) == 5, "Should have 5 keys"

0 comments on commit e148006

Please sign in to comment.