Skip to content

Commit

Permalink
Allow DictList to be selected with boolean arrays
Browse files Browse the repository at this point in the history
Allows numpy-like behavior in ArrayBasedModel. For example:
model.reactions[model.lower_bounds > 0]

This commit also includes a unit test for this behavior.
  • Loading branch information
aebrahim committed Jan 31, 2015
1 parent 38ddc3d commit 04c1b39
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
13 changes: 13 additions & 0 deletions cobra/core/DictList.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
from ..external.six import string_types, iteritems
from itertools import islice

try:
from numpy import bool_
except:
bool_ = bool


class DictList(list):
"""A combined dict and list
Expand Down Expand Up @@ -291,6 +296,14 @@ def __getitem__(self, i):
selection = self.__class__()
selection._extend_nocheck(list.__getitem__(self, i))
return selection
elif hasattr(i, "__len__"):
if len(i) == len(self) and isinstance(i[0], (bool, bool_)):
selection = self.__class__()
result = (o for j, o in enumerate(self) if i[j])
selection._extend_nocheck(result)
return selection
else:
return self.__class__(list.__getitem__(self, i))
else:
return list.__getitem__(self, i)

Expand Down
11 changes: 11 additions & 0 deletions cobra/test/unit_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,17 @@ def test_array_based_model_add(self):
self.assertEqual(model.S[1605, 0], -1)
self.assertEqual(model.lower_bounds[2546], -3.14)

def test_array_based_select(self):
model = self.model
atpm_select = model.reactions[model.lower_bounds > 0]
self.assertEqual(len(atpm_select), 1)
self.assertEqual(atpm_select[0].id, "ATPM")
self.assertEqual(len(model.reactions[model.lower_bounds <= 0]),
len(model.reactions) - 1)
# mismatched dimensions should give an error
with self.assertRaises(TypeError):
model.reactions[[True, False]]


# make a test suite to run all of the tests
loader = TestLoader()
Expand Down

0 comments on commit 04c1b39

Please sign in to comment.