Example M4: Finding overlapping particles

This example shows how to write a user-defined modifier function that searches for pairs of particles whose distance of separation is within the specified cutoff distance. Then one of the two particles in the pair is selected by the modifier. Subsequently, the user may apply the DeleteSelectedModifier to remove these selected particles from the system and eliminate any potential overlaps among particles.

The modifier function below makes use of the CutoffNeighborFinder utility class, which allows finding neighboring particles that are within a certain range of a central particles. The modifier produces the standard output particle property Selection.

from ovito.data import CutoffNeighborFinder

# Control parameter:
overlap_distance = 2.5

# The user-defined modifier function:
def modify(frame, data):

    # Show this text in the status bar while the modifier function executes
    yield "Selecting overlapping particles"

    # Create 'Selection' output particle property
    selection = data.particles_.create_property('Selection')

    # Prepare neighbor finder
    finder = CutoffNeighborFinder(overlap_distance, data)

    # Iterate over all particles
    for index in range(data.particles.count):

        # Update progress display in the status bar
        yield (index / data.particles.count)

        # Iterate over all nearby particles around the current center particle
        for neigh in finder.find(index):

            # Once we find a neighbor which hasn't been marked yet,
            # mark the current center particle. This test is to ensure that we
            # always select only one of the particles in a close pair.
            if selection[neigh.index] == 0:
                selection[index] = 1
                break