Example B3: Creating particles and bonds programmatically — OVITO Python Reference 3.15.3-dev-HEAD-b1e9512d documentation

# Example B3: Creating particles and bonds programmatically

The following script demonstrates the creation of particles, a simulation cell, and bonds on the fly without loading them from an external simulation file. This approach can be used to implement custom data importers or dynamically generate atomic structures within OVITO, which can then be further processed or exported to a file.

The script creates different data objects and adds them to a new `DataCollection`. Finally, a `Pipeline` is created and a `StaticSource` object is used to make the `DataCollection` its data source.

    from ovito.data import *
    from ovito.pipeline import *

    # Create the data collection containing a Particles object:
    data = DataCollection()
    particles = data.create_particles()

    # XYZ coordinates of the three atoms to create:
    pos = [(1.0, 1.5, 0.3),
           (7.0, 4.2, 6.0),
           (5.0, 9.2, 8.0)]

    # Create the particle position property:
    pos_prop = particles.create_property('Position', data=pos)

    # Create the particle type property and insert two atom types:
    type_prop = particles.create_property('Particle Type')
    type_prop.types.append(ParticleType(id = 1, name = 'Cu', color = (0.0,1.0,0.0)))
    type_prop.types.append(ParticleType(id = 2, name = 'Ni', color = (0.0,0.5,1.0)))
    type_prop[0] = 1  # First atom is Cu
    type_prop[1] = 2  # Second atom is Ni
    type_prop[2] = 2  # Third atom is Ni

    # Create a user-defined particle property with some data:
    my_data = [3.141, -1.2, 0.23]
    my_prop = particles.create_property('My property', data=my_data)

    # Create the simulation box:
    cell = SimulationCell(pbc = (False, False, False))
    cell[...] = [[10,0,0,0],
                 [0,10,0,0],
                 [0,0,10,0]]
    cell.vis.line_width = 0.1
    data.objects.append(cell)

    # Create 3 bonds between particles:
    bond_topology = [[0,1], [1,2], [2,0]]
    bonds = particles.create_bonds()
    bonds.create_property('Topology', data=bond_topology)

    # Create a pipeline, set the source and insert it into the scene:
    pipeline = Pipeline(source = StaticSource(data = data))
    pipeline.add_to_scene()