From 800b4b2d88765f8af65ba9115ebd7554f75fd041 Mon Sep 17 00:00:00 2001 From: Lily Wang <31115101+lilyminium@users.noreply.github.com> Date: Sat, 26 Oct 2024 23:26:29 +1100 Subject: [PATCH] Fix bond deletion (#4763) * Fix issue where duplicate bonds were not being adequately deleted. --------- Co-authored-by: Irfan Alibay --- package/CHANGELOG | 2 ++ package/MDAnalysis/core/topologyattrs.py | 3 ++- testsuite/MDAnalysisTests/core/test_universe.py | 11 +++++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/package/CHANGELOG b/package/CHANGELOG index eaa76f46a96..892e47d3854 100644 --- a/package/CHANGELOG +++ b/package/CHANGELOG @@ -23,6 +23,8 @@ The rules for this file: * 2.8.0 Fixes + * Fixes bug where deleting connections by index would only delete + one of multiple, if multiple are present (Issue #4762, PR #4763) * Changes error to warning on Universe creation if guessing fails due to missing information (Issue #4750, PR #4754) * Adds guessed attributes documentation back to each parser page diff --git a/package/MDAnalysis/core/topologyattrs.py b/package/MDAnalysis/core/topologyattrs.py index 5e2621dc63d..e5cf003b5ba 100644 --- a/package/MDAnalysis/core/topologyattrs.py +++ b/package/MDAnalysis/core/topologyattrs.py @@ -3146,7 +3146,8 @@ def _delete_bonds(self, values): '{attrname} with atom indices:' '{indices}').format(attrname=self.attrname, indices=indices)) - idx = [self.values.index(v) for v in to_check] + # allow multiple matches + idx = [i for i, x in enumerate(self.values) if x in to_check] for i in sorted(idx, reverse=True): del self.values[i] diff --git a/testsuite/MDAnalysisTests/core/test_universe.py b/testsuite/MDAnalysisTests/core/test_universe.py index 3e41a38a967..4f0806728e4 100644 --- a/testsuite/MDAnalysisTests/core/test_universe.py +++ b/testsuite/MDAnalysisTests/core/test_universe.py @@ -48,6 +48,7 @@ two_water_gro, two_water_gro_nonames, TRZ, TRZ_psf, PDB, MMTF, CONECT, + PDB_conect ) import MDAnalysis as mda @@ -1247,6 +1248,16 @@ def test_delete_bonds_refresh_fragments(self, universe): universe.delete_bonds([universe.atoms[[2, 3]]]) assert len(universe.atoms.fragments) == n_fragments + 1 + @pytest.mark.parametrize("filename, n_bonds", [ + (CONECT, 72), + (PDB_conect, 8) + ]) + def test_delete_all_bonds(self, filename, n_bonds): + u = mda.Universe(filename) + assert len(u.bonds) == n_bonds + u.delete_bonds(u.bonds) + assert len(u.bonds) == 0 + @pytest.mark.parametrize( 'attr,values', existing_atom_indices )