Skip to content

Commit 2725815

Browse files
Change syntax to remove ghost ports (#995)
* Change syntax to remove ghost ports * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * also remove label from when removing port * add unit test Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 41025a2 commit 2725815

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

mbuild/compound.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -833,17 +833,24 @@ def _check_if_empty(child):
833833
removed_part.parent.children.remove(removed_part)
834834
self._remove_references(removed_part)
835835

836-
# Remove ghost ports
837-
all_ports_list = list(self.all_ports())
838-
for port in all_ports_list:
839-
if port.anchor not in [i for i in self.particles()]:
840-
port.parent.children.remove(port)
841-
842836
# Check and reorder rigid id
843837
for _ in particles_to_remove:
844838
if self.contains_rigid:
845839
self.root._reorder_rigid_ids()
846840

841+
# Remove ghsot ports
842+
self._prune_ghost_ports()
843+
844+
def _prune_ghost_ports(self):
845+
"""Worker for remove(). Remove all ports whose anchor has been deleted."""
846+
all_ports_list = list(self.all_ports())
847+
particles = list(self.particles())
848+
for port in all_ports_list:
849+
if port.anchor not in particles:
850+
self._remove(port)
851+
port.parent.children.remove(port)
852+
self._remove_references(port)
853+
847854
def _remove(self, removed_part):
848855
"""Worker for remove(). Fixes rigid IDs and removes bonds."""
849856
if removed_part.rigid_id is not None:

mbuild/tests/test_compound.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1278,6 +1278,20 @@ def test_add_bond_remove_ports(self, hydrogen):
12781278
assert len(hydrogen.all_ports()) == 0
12791279
assert len(h_clone.all_ports()) == 0
12801280

1281+
def test_pruning_ghost_ports(self, ethane):
1282+
eth1 = ethane
1283+
h1 = eth1.particles_by_name("H")
1284+
eth1.remove(h1)
1285+
assert len(eth1.all_ports()) == 6
1286+
for port in eth1.all_ports():
1287+
assert port.anchor in list(eth1.particles())
1288+
1289+
eth2 = mb.load("CC", smiles=True)
1290+
h2 = eth2[-1]
1291+
eth2.remove(h2)
1292+
assert len(eth2.all_ports()) == len(eth2.available_ports()) == 1
1293+
assert eth2.all_ports()[0] is eth2.available_ports()[0]
1294+
12811295
def test_remove_bond_add_ports(self, hydrogen):
12821296
h_clone = mb.clone(hydrogen)
12831297
h2 = Compound(subcompounds=(hydrogen, h_clone))

0 commit comments

Comments
 (0)