Skip to content

filter check_mass_balance zeros with a floating point comparison #1436

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions release-notes/next-release.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ Fixes failures of GPR.copy() in Python 3.13.
Fix compartment not being stored for metabolites created during
reaction.build_reaction_from_string

Fix `reaction.check_mass_balance` giving incorrect results for reactions with floating point coefficients.

## Other

## Deprecated features
Expand Down
8 changes: 6 additions & 2 deletions src/cobra/core/reaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from collections import defaultdict
from copy import copy, deepcopy
from functools import partial
from math import isinf
from math import isclose, isinf
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Expand Down Expand Up @@ -1451,7 +1451,11 @@ def check_mass_balance(self) -> Dict[str, float]:
for element, amount in metabolite.elements.items():
reaction_element_dict[element] += coefficient * amount
# filter out 0 values
return {k: v for k, v in reaction_element_dict.items() if v != 0}
return {
k: v
for k, v in reaction_element_dict.items()
if not isclose(v, 0.0, abs_tol=config.tolerance)
}

@property
def compartments(self) -> Set:
Expand Down
3 changes: 3 additions & 0 deletions tests/test_core/test_core_reaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,9 @@ def test_mass_balance(model: Model) -> None:
imbalance = reaction.check_mass_balance()
assert "H" in imbalance
assert imbalance["H"] == 1
# Should be balanced even when coefficients are non-integer
reaction_scaled = model.reactions.get_by_id("ATPS4r") * 1.3
assert len(reaction_scaled.check_mass_balance()) == 0


def test_build_from_string(model: Model) -> None:
Expand Down
Loading