Skip to content

Commit

Permalink
feat: adding reaction radd (#596)
Browse files Browse the repository at this point in the history
Python's `sum` starts with a 0, and then adds each element in turn. So previously this would fail with
```python
>>> sum(model.metabolites.etoh_c.reactions)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'Reaction'
```

1) Allow an `__radd__` function and
2) Explicitly allow `reaction + 0`

So now you can 
```python
>>> sum(model.metabolites.etoh_c.reactions).reaction
'etoh_e + h_e + nad_c <=> acald_c + 2.0 h_c + nadh_c'
```
  • Loading branch information
pstjohn authored and hredestig committed Sep 25, 2017
1 parent 4ece229 commit 241267e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
8 changes: 7 additions & 1 deletion cobra/core/reaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -608,9 +608,15 @@ def __add__(self, other):
"""
new_reaction = self.copy()
new_reaction += other
if other == 0:
return new_reaction
else:
new_reaction += other

return new_reaction

__radd__ = __add__

def __iadd__(self, other):
self.add_metabolites(other._metabolites, combine=True)
gpr1 = self.gene_reaction_rule.strip()
Expand Down
5 changes: 5 additions & 0 deletions cobra/test/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,11 @@ def test_add(self, model):
assert gene is not model.genes.get_by_id(gene.id)
assert gene.model is not model

def test_radd(self, model):
new = sum([model.reactions.PGI, model.reactions.EX_h2o_e])
assert new._model is not model
assert len(new.metabolites) == 3

def test_mul(self, model):
new = model.reactions.PGI * 2
assert set(new.metabolites.values()) == {-2, 2}
Expand Down

0 comments on commit 241267e

Please sign in to comment.