Skip to content

Commit

Permalink
Function to merge ReactionEquation instances (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
avaucher authored Feb 6, 2023
1 parent 38d725c commit 7f4a9c2
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/rxn/chemutils/miscellaneous.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
sort_multicomponent_smiles,
)
from .reaction_equation import (
ReactionEquation,
apply_to_compound_groups,
apply_to_compounds,
sort_compounds,
Expand Down Expand Up @@ -251,3 +252,17 @@ def get_individual_compounds(any_smiles: str) -> List[str]:
# We interpret it as a multicomponent SMILES.
# We use "~" as a fragment bond even if it is not actually needed.
return multicomponent_smiles_to_list(any_smiles, fragment_bond="~")


def merge_reactions(*reactions: ReactionEquation) -> ReactionEquation:
"""Merge several reactions into one.
Useful when ReactionEquation is used to store partial equations."""
reactants = []
agents = []
products = []
for reaction in reactions:
reactants.extend(reaction.reactants)
agents.extend(reaction.agents)
products.extend(reaction.products)
return ReactionEquation(reactants=reactants, agents=agents, products=products)
24 changes: 24 additions & 0 deletions tests/test_miscellaneous.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@
equivalent_smiles,
get_individual_compounds,
is_valid_smiles,
merge_reactions,
remove_chiral_centers,
remove_double_bond_stereochemistry,
sort_any,
)
from rxn.chemutils.reaction_equation import ReactionEquation


def test_equivalent_smiles() -> None:
Expand Down Expand Up @@ -217,3 +219,25 @@ def test_get_individual_compounds() -> None:
"C",
"B",
]


def test_merge_reactions() -> None:
# No reaction given
assert merge_reactions() == ReactionEquation([], [], [])

# one reaction
r1 = ReactionEquation(["A", "B"], ["C"], ["D"])
assert merge_reactions(r1) == r1

# two reactions
r2 = ReactionEquation(["F"], ["G"], [])
assert merge_reactions(r1, r2) == ReactionEquation(
["A", "B", "F"], ["C", "G"], ["D"]
)

# more than two reactions
r3 = ReactionEquation([], ["H"], [])
r4 = ReactionEquation([], [], ["I"])
assert merge_reactions(r1, r2, r3, r4) == ReactionEquation(
["A", "B", "F"], ["C", "G", "H"], ["D", "I"]
)

0 comments on commit 7f4a9c2

Please sign in to comment.