diff --git a/src/rxn/chemutils/miscellaneous.py b/src/rxn/chemutils/miscellaneous.py index b398f7f..ad4d764 100644 --- a/src/rxn/chemutils/miscellaneous.py +++ b/src/rxn/chemutils/miscellaneous.py @@ -15,6 +15,7 @@ sort_multicomponent_smiles, ) from .reaction_equation import ( + ReactionEquation, apply_to_compound_groups, apply_to_compounds, sort_compounds, @@ -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) diff --git a/tests/test_miscellaneous.py b/tests/test_miscellaneous.py index 32aaf15..e7cefd0 100644 --- a/tests/test_miscellaneous.py +++ b/tests/test_miscellaneous.py @@ -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: @@ -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"] + )