From 88e9cbd9cf55594a0ad875db719867a4719008a7 Mon Sep 17 00:00:00 2001 From: Peter Kroon Date: Mon, 6 May 2024 16:41:14 +0200 Subject: [PATCH] Adapt code to make links add interactions per batch, removing overlapping interactions Fixes #584 --- vermouth/molecule.py | 16 +++++++++------- vermouth/processors/do_links.py | 7 +++++++ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/vermouth/molecule.py b/vermouth/molecule.py index 7d4d151a..cbadfd9b 100644 --- a/vermouth/molecule.py +++ b/vermouth/molecule.py @@ -577,7 +577,7 @@ def get_interaction(self, type_): """ return self.interactions[type_] - def remove_interaction(self, type_, atoms, version=0): + def remove_interaction(self, type_, atoms, version=None): """ Removes the specified interaction. @@ -587,25 +587,27 @@ def remove_interaction(self, type_, atoms, version=0): The type of interaction, such as 'bonds' or 'angles'. atoms: collections.abc.Sequence The atoms that are involved in this interaction. - version: int + version: Optional[int] Sometimes there can be multiple distinct interactions between the same group of atoms. This is reflected with their `version` meta attribute. + If None, the version is not taken into account. Raises ------ KeyError If the specified interaction could not be found """ - idx = 0 + to_remove = [] for idx, interaction in enumerate(self.interactions[type_]): - if interaction.atoms == atoms and interaction.meta.get('version', 0) == version: - break - else: # no break + if interaction.atoms == atoms and (version is None or interaction.meta.get('version', 0) == version): + to_remove.append(idx) + if not to_remove: msg = ("Can't find interaction of type {} between atoms {} " "and with version {}") raise KeyError(msg.format(type_, atoms, version)) - del self.interactions[type_][idx] + for idx in reversed(to_remove): + del self.interactions[type_][idx] if not self.interactions[type_]: del self.interactions[type_] diff --git a/vermouth/processors/do_links.py b/vermouth/processors/do_links.py index 4284beab..c8c9d884 100644 --- a/vermouth/processors/do_links.py +++ b/vermouth/processors/do_links.py @@ -313,8 +313,15 @@ def run_molecule(self, molecule): except ValueError: pass for inter_type, interactions in link.interactions.items(): + interactions_to_add = [] for interaction in interactions: interaction = _build_link_interaction_from(molecule, interaction, match) + interactions_to_add.append(interaction) + try: + molecule.remove_interaction(inter_type, interaction.atoms, version=None) + except KeyError: + pass + for interaction in interactions_to_add: molecule.add_or_replace_interaction(inter_type, *interaction, link.citations) for loglevel, entries in link.log_entries.items():