From b984aa95597b65c5f5d22fdba7573ecf0b314e90 Mon Sep 17 00:00:00 2001 From: Richard Gowers Date: Fri, 13 Nov 2015 14:38:41 -0800 Subject: [PATCH] Added fix for Issue #532 Prevents addition of AtomGroups from different Universes --- package/MDAnalysis/core/AtomGroup.py | 6 ++++++ testsuite/MDAnalysisTests/test_atomgroup.py | 9 +++++++++ 2 files changed, 15 insertions(+) diff --git a/package/MDAnalysis/core/AtomGroup.py b/package/MDAnalysis/core/AtomGroup.py index c40365b02ce..4043cb23c74 100644 --- a/package/MDAnalysis/core/AtomGroup.py +++ b/package/MDAnalysis/core/AtomGroup.py @@ -533,6 +533,10 @@ def __add__(self, other): if not isinstance(other, (Atom, AtomGroup)): raise TypeError('Can only add Atoms or AtomGroups (not "{0}")' ' to Atom'.format(other.__class__.__name__)) + # Dodge property to avoid NoDataErrors + # Will then allow addition of NoneUniverse to NoneUniverse.. + if not self._universe is other._universe: + raise ValueError("Can only add objects from the same Universe") if isinstance(other, Atom): return AtomGroup([self, other]) else: @@ -1074,6 +1078,8 @@ def __add__(self, other): if not isinstance(other, (Atom, AtomGroup)): raise TypeError('Can only concatenate Atom or AtomGroup (not "{0}") to' ' AtomGroup'.format(other.__class__.__name__)) + if (self and other) and (not self.universe is other.universe): + raise ValueError("Can only add objects from the same Universe") if isinstance(other, AtomGroup): return AtomGroup(self._atoms + other._atoms) else: diff --git a/testsuite/MDAnalysisTests/test_atomgroup.py b/testsuite/MDAnalysisTests/test_atomgroup.py index b7d9d7a434b..69419788dcb 100644 --- a/testsuite/MDAnalysisTests/test_atomgroup.py +++ b/testsuite/MDAnalysisTests/test_atomgroup.py @@ -2191,12 +2191,21 @@ def add(x, y): def test_add_mixed_universes(self): # Issue #532 + # Checks that adding objects from different universes + # doesn't proceed quietly. u1 = MDAnalysis.Universe(two_water_gro) u2 = MDAnalysis.Universe(two_water_gro) A = [u1.atoms[:2], u1.atoms[3]] B = [u2.atoms[:3], u2.atoms[0]] + # Checks Atom to Atom, Atom to AG, AG to Atom and AG to AG for x, y in itertools.product(A, B): yield self._check_badadd, x, y + def test_adding_empty_ags(self): + # Check that empty AtomGroups don't trip up on the Universe check + u = MDAnalysis.Universe(two_water_gro) + + assert_(len(AtomGroup([]) + u.atoms[:3]) == 3) + assert_(len(u.atoms[:3] + AtomGroup([])) == 3)