### ViewportOverlayInterface Example Source: https://www.ovito.org/manual/python/modules/ovito_vis.html Example demonstrating how to create a custom viewport overlay using ViewportOverlayInterface and draw an image onto the canvas. ```APIDOC ## ViewportOverlayInterface ### Description Provides an interface for creating custom overlays that can be rendered onto the OVITO viewport canvas. ### Usage ```python from ovito.vis import ViewportOverlayInterface from ovito.qt_compat import QtGui class ImageOverlay(ViewportOverlayInterface): def render(self, canvas: ViewportOverlayInterface.Canvas, **kwargs): image = QtGui.QImage(320, 240, canvas.preferred_qimage_format) image.fill(QtGui.QColor.fromRgbF(1.0, 0.0, 0.0, 0.3)) canvas.draw_image(image, pos=(0.5, 0.5), size=(0.5, 0.5), anchor="center") ``` ``` -------------------------------- ### Install OVITO with pip Source: https://www.ovito.org/manual/python/introduction/installation.html Use this command to install or upgrade the OVITO Python module from the PyPI repository for standard Python environments. ```bash pip install -U ovito ``` -------------------------------- ### Install User Extension Locally Source: https://www.ovito.org/manual/python/introduction/advanced_topics.html Installs a local OVITO extension package in editable mode. Use this command to make your extension available in OVITO Pro after preparing the pyproject.toml file. The `--editable` flag allows for code changes without reinstallation. ```bash ovitos -m pip install --user --editable ``` -------------------------------- ### Install OVITO with conda Source: https://www.ovito.org/manual/python/introduction/installation.html Install the OVITO Python module and OVITO Pro application using conda. Ensure to use the specified channels for the correct package. ```bash conda install --strict-channel-priority -c https://conda.ovito.org -c conda-forge ovito=3.15.4 ``` -------------------------------- ### Example Custom File Format Data Source: https://www.ovito.org/manual/python/introduction/examples/file_readers/example_file_format_reader.html This is an example of the custom file format that the reader will process. It includes timestep information, simulation cell dimensions, and particle data with types and reduced coordinates. ```text Timestep 0 7.865954 0.000000 0.000000 0.000000 7.865954 0.000000 0.000000 0.000000 6.973035 Atoms 18 Reduced coordinates Na 0.09306390 0.30261238 0.46908935 Na 0.90693610 0.69738762 0.46908938 Na 0.30261235 0.90693613 0.53091062 Na 0.69738763 0.09306392 0.53091062 Na 0.40693612 0.80261241 0.03091062 Na 0.59306393 0.19738766 0.03091059 Na 0.19738763 0.40693613 0.96908938 Na 0.80261236 0.59306396 0.96908938 S 0.24180739 0.09397526 0.19064404 S 0.75819276 0.90602458 0.19064394 S 0.09397538 0.75819274 0.80935606 S 0.90602453 0.24180732 0.80935606 S 0.25819273 0.59397545 0.30935596 S 0.74180726 0.40602446 0.30935606 S 0.40602443 0.25819271 0.69064391 S 0.59397545 0.74180729 0.69064404 Sn 0.00000000 0.00000000 0.00000000 Sn 0.50000000 0.50000000 0.49999997 Timestep 100 7.870939 0.000000 0.000000 0.000000 7.870939 0.000000 0.000000 0.000000 6.977331 Atoms 18 Reduced coordinates Na 0.09309428 0.30260112 0.46914038 Na 0.90690570 0.69739888 0.46914042 Na 0.30260109 0.90690574 0.46914042 Na 0.69739888 0.09309430 0.53085958 Na 0.40690573 0.80260115 0.03085957 Na 0.59309430 0.19739893 0.03085954 Na 0.19739889 0.40690574 0.96914042 Na 0.80260110 0.59309434 0.96914043 S 0.24179056 0.09398270 0.19066976 S 0.75820959 0.90601718 0.19066973 S 0.09398279 0.75820959 0.80933034 S 0.90601713 0.24179048 0.80933037 S 0.25820958 0.59398272 0.30933030 S 0.74179038 0.40601712 0.30933031 S 0.40601707 0.25820957 0.69066957 S 0.59398288 0.74179044 0.69066971 Sn 0.00000002 0.00000002 -0.00000002 Sn 0.49999998 0.50000000 0.49999997 Timestep 200 7.878383 0.000000 0.000000 0.000000 7.878383 0.000000 0.000000 0.000000 6.982911 Atoms 19 Reduced coordinates Na 0.09309963 0.30259914 0.46914936 Na 0.90690035 0.69740086 0.46914940 Na 0.30259910 0.90690039 0.53085060 Na 0.69740086 0.09309965 0.53085059 Na 0.40690038 0.80259917 0.03085059 Na 0.59309965 0.19740091 0.03085055 Na 0.19740087 0.40690039 0.96914940 Na 0.80259911 0.59309969 0.96914941 S 0.24178760 0.09398401 0.19067428 S 0.75821255 0.90601588 0.19067427 S 0.09398409 0.75821256 0.80932582 S 0.90601583 0.24178752 0.80932585 S 0.25821254 0.59398400 0.30932578 S 0.74178741 0.40601583 0.30932578 S 0.40601578 0.25821253 0.69067409 S 0.59398418 0.74178748 0.69067423 Sn 0.00000002 0.00000002 -0.00000002 Sn 0.49999997 0.50000000 0.49999997 Fe 0.32000002 0.41690039 0.42785059 ``` -------------------------------- ### Optimize Custom File Reader Performance with OVITO Python Source: https://www.ovito.org/manual/python/introduction/examples.html Example demonstrating how to optimize the performance of a custom file reader. ```python from ovito.io import FileReader from ovito.data import Particles, SimulationCell class OptimizedCustomReader(FileReader): def __init__(self, filename): FileReader.__init__(self, filename=filename) # Pre-process or cache data if possible for faster access. self.cached_data = self.load_and_optimize(filename) def load_and_optimize(self, filename): # Implement optimized file loading and data structuring. # Consider using NumPy for efficient array operations. pass def modify_pipeline(self, pipeline, error): particles = Particles() # Populate particles efficiently from self.cached_data. # ... cell = SimulationCell() # Populate cell efficiently from self.cached_data. # ... pipeline.add_object(particles) pipeline.add_object(cell) # Usage is similar to the non-optimized reader, but performance will be improved. # pipeline = import_file('my_custom_file.dat', reader=OptimizedCustomReader) ``` -------------------------------- ### Create Particles and Bonds Programmatically with OVITO Python Source: https://www.ovito.org/manual/python/introduction/examples.html Example demonstrating how to create particles and bonds programmatically using OVITO's Python API. ```python from ovito.data import Particles, Bonds, SimulationCell from ovito.io import export_file # Create a new data object particles = Particles() # Add some particles particles.create_particle(position=(0,0,0), type=1, radius=0.5) particles.create_particle(position=(1,0,0), type=1, radius=0.5) particles.create_particle(position=(0,1,0), type=1, radius=0.5) # Add a bond between the first two particles bonds = Bonds() bonds.add_bond(0, 1) # Create a simulation cell (optional) cell = SimulationCell(size=(10,10,10)) # Export the data to a file export_file(particles, 'programmatic.dump', atom_style='atomic', simulation_cell=cell, bonds=bonds) ``` -------------------------------- ### Creating a Custom Pipeline Source Source: https://www.ovito.org/manual/python/modules/ovito_pipeline.html Example of implementing the PipelineSourceInterface to create a custom data source. This source defines a simulation cell and its periodic boundary conditions. ```python from ovito.data import DataCollection from ovito.pipeline import PipelineSourceInterface class ExampleSource(PipelineSourceInterface): def create(self, data: DataCollection, **kwargs): cell_matrix = [ [10,0,0,0], [0,10,0,0], [0,0,10,0] ] data.create_cell(cell_matrix, pbc=(False, False, False)) ``` -------------------------------- ### Registering a custom file reader Source: https://www.ovito.org/manual/python/modules/ovito_io.html Example of how to implement and register a custom file reader by inheriting from `FileReaderInterface` and implementing `detect()` and `parse()`. ```python from ovito.io import FileReaderInterface class MyReader(FileReaderInterface): def detect(self, filename): # Check if the file is in a format this reader can handle return filename.endswith('.myformat') def parse(self, data, filename, url, frame_index, frame_info, is_new_file, **kwargs): # Load data from the file into the 'data' object pass # OVITO will automatically discover and use custom readers registered this way. ``` -------------------------------- ### Standalone Trajectory Viewer with OVITO Python Source: https://www.ovito.org/manual/python/introduction/examples.html Example of creating a standalone trajectory viewer using OVITO's Python API. ```python from ovito.io import import_file from ovito.vis import Viewport # Load a simulation trajectory pipeline = import_file('trajectory.dump') # Create a viewport viewport = Viewport() viewport.camera_position = (20, 20, 20) viewport.camera_orientation = (-0.5, -0.5, -0.5) # Render the trajectory and save frames for frame in range(pipeline.num_frames): pipeline.current_frame = frame viewport.render_image(filename=f'frame_{frame:04d}.png', size=(800, 600)) print('Rendering complete.') ``` -------------------------------- ### Surface Mesh Creation and Manipulation Source: https://www.ovito.org/manual/python/modules/ovito_data.html Example demonstrating the creation of a SurfaceMesh object, adding vertices, defining faces, assigning properties, and connecting the mesh. ```APIDOC ## Surface Mesh Operations ### Description This section covers the creation and manipulation of surface meshes using the `ovito.data` module. It includes adding vertices, defining faces, assigning per-face properties like color, and ensuring mesh connectivity. ### Methods #### `create_vertices(_coords : Sequence[Sequence[float]] | ArrayLike[float]_) -> int` Adds a set of new vertices to the mesh. `_coords` must be an n×3 array specifying the xyz coordinates of the n vertices to create. The coordinates will be copied into the `Position` vertex property. The `vertex_count` of the mesh’s `topology` will be incremented by n. Initially, new vertices are not associated with any faces. #### `create_faces(indices : Sequence[Sequence[int]])` Creates new faces for the mesh. Each face is defined by a list of vertex indices. This method increments the mesh’s `topology.face_count` and extends the `faces` property container. An error is raised if any specified vertex index does not exist. #### `faces.create_property(name : str, data : Sequence | ArrayLike)` Creates a new per-face property. `name` is the property name (e.g., 'Color', 'Region', 'Selection'), and `data` is a sequence or array-like object containing the property values for each face. #### `connect_opposite_halfedges()` Connects opposite half-edges to form a closed mesh, ensuring surface manifold properties. ### Usage Example: ```python # Add a new SurfaceMesh object to the DataCollection with unique object identifier 'tetrahedron'. # The simulation cell of the particle system is adopted also as domain of the SurfaceMesh. mesh = data.surfaces.create(identifier='tetrahedron', title='Tetrahedron', domain=data.cell) # Create 4 mesh vertices. verts = [[0,0,0], [10,0,0], [0,10,0], [0,0,10]] mesh.create_vertices(verts) # Create 4 triangular faces forming a tetrahedron. mesh.create_faces([[0,1,2], [0,2,3], [0,3,1], [1,3,2]]) # Initialize the 'Color' property of the newly created faces with RGB values. mesh.faces.create_property('Color', data=[(1,0,0), (1,1,0), (0,0,1), (0,1,0)]) # Make it a "closed" mesh, connecting the four faces to form a surface manifold. mesh.connect_opposite_halfedges() ``` ### Properties #### `domain` : SimulationCell | None The `SimulationCell` describing the (possibly periodic) domain which this surface mesh is embedded in. This cell is independent of the `DataCollection`'s cell. #### `faces` : PropertyContainer The `PropertyContainer` storing the per-face properties of the mesh. Standard properties include 'Color', 'Region', and 'Selection'. ### `get_clipping_planes()` #### Description Returns an N×4 array containing the definitions of the N clipping planes attached to this `SurfaceMesh`. #### Method GET #### Endpoint `/surface_mesh/{mesh_id}/clipping_planes` (Conceptual representation) #### Response #### Success Response (200) - **N** (int) - The number of clipping planes. - **planes** (NDArray[float64]) - An N×4 array where each row defines a clipping plane [normal_x, normal_y, normal_z, distance]. #### Response Example ```json { "N": 2, "planes": [ [0.0, 0.0, 1.0, 10.0], [1.0, 0.0, 0.0, 5.0] ] } ``` ``` -------------------------------- ### Iterate Face Edges with SurfaceMesh Source: https://www.ovito.org/manual/python/modules/ovito_data.html This example demonstrates how to iterate over all halfedges bounding a given face using `first_face_edge()` and `next_face_edge()`. It counts the number of edges for a face, ensuring the loop terminates correctly by checking against the starting edge. ```python def count_edges(mesh: SurfaceMesh, face: int) -> int: start_edge = mesh.topology.first_face_edge(face) count = 1 edge = mesh.topology.next_face_edge(start_edge) while edge != start_edge: assert mesh.topology.adjacent_face(edge) == face count += 1 edge = mesh.topology.next_face_edge(edge) return count ``` -------------------------------- ### Building a Pipeline with a Custom Source Source: https://www.ovito.org/manual/python/modules/ovito_pipeline.html Demonstrates how to integrate a custom pipeline source (ExampleSource) into an OVITO pipeline using PythonSource. ```python from ovito.pipeline import Pipeline, PythonSource example_source = ExampleSource() pipeline = Pipeline(source = PythonSource(delegate = example_source)) ``` -------------------------------- ### Create and Initialize VoxelGrid Source: https://www.ovito.org/manual/python/modules/ovito_data.html Demonstrates creating a new VoxelGrid from scratch and initializing it with data from a NumPy array. This involves creating a SimulationCell, generating field data, and then creating the VoxelGrid linked to the cell and data. ```Python from ovito.data import DataCollection, SimulationCell, VoxelGrid import numpy # Starting with an empty DataCollection: data = DataCollection() # Create a new SimulationCell object defining the outer spatial dimensions # of the grid and the boundary conditions, and add it to the DataCollection: cell = data.create_cell( matrix=[[10,0,0,0],[0,10,0,0],[0,0,10,0]], pbc=(True, True, True) ) # Generate a three-dimensional Numpy array containing the grid cell values. x = 10; ny = 6; nz = 8 field_data = numpy.random.random((nx, ny, nz)) # Create the VoxelGrid object and give it a unique identifier by which it can be referred to later on. # Link the voxel grid to the SimulationCell object created above, which defines its spatial extensions. # Specify the shape of the grid, i.e. the number of cells in each spatial direction. # Finally, assign a VoxelGridVis visual element to the data object to make the grid visible in the scene. grid = data.grids.create( identifier="field", domain=cell, shape=(nx,ny,nz), grid_type=VoxelGrid.GridType.CellData, vis_params={ "enabled": True, "transparency": 0.6 } ) ``` -------------------------------- ### Install Third-Party Python Packages Source: https://www.ovito.org/manual/python/introduction/installation.html Install external Python packages into the ovitos interpreter using the 'pip install' command. The --user flag installs the package for the current user. ```bash ovitos -m pip install --user ``` -------------------------------- ### Pipeline Creation and Usage Source: https://www.ovito.org/manual/python/modules/ovito_pipeline.html Demonstrates how to create a pipeline by importing a file, adding a modifier, computing the results, and accessing input data. ```APIDOC ## Pipeline Creation and Usage ### Description This section illustrates the creation of a data pipeline, the insertion of modifiers, and the computation of results. It also shows how to access the raw input data before any modifications are applied. ### Usage Example ```python from ovito.io import import_file from ovito.modifiers import SliceModifier # Import a simulation file. This creates a Pipeline object. pipeline = import_file('input/simulation.dump') # Insert a modifier that operates on the data: pipeline.modifiers.append(SliceModifier(normal=(0,0,1), distance=0)) # Compute the effect of the slice modifier by evaluating the pipeline. output = pipeline.compute() print("Remaining particle count:", output.particles.count) # Access the pipeline's input data provided by the FileSource: input_data = pipeline.source.compute() print("Input particle count:", input_data.particles.count) ``` ### Pipeline Object - **`Pipeline`**: Represents a data processing pipeline with a data source and a chain of modifiers. - **`Pipeline.source`**: Accesses the data source of the pipeline. - **`Pipeline.modifiers`**: Accesses the list of modifiers in the pipeline. - **`Pipeline.compute()`**: Computes and returns the pipeline's output data as a `DataCollection`. - **`Pipeline.add_to_scene()`**: Adds the pipeline's output to the current 3D scene for visualization. ### Data Source - **`Pipeline.source`**: Can be replaced with different source objects like `FileSource` or `StaticSource`. ### Modifiers - **`Pipeline.modifiers`**: A list where `Modifier` instances can be appended. ### Data Export - **`ovito.io.export_file(pipeline, filename)`**: Exports the generated data of the pipeline to a file. ``` -------------------------------- ### Example: SkipFramesModifier Source: https://www.ovito.org/manual/python/modules/ovito_pipeline.html An example implementation of a custom modifier that filters out every other frame of the input trajectory. ```APIDOC ## Example: SkipFramesModifier This modifier filters out every other frame of the input trajectory: ```python from ovito.data import DataCollection from ovito.pipeline import ModifierInterface class SkipFramesModifier(ModifierInterface): def compute_trajectory_length(self, *, input_slots: dict[str, ModifierInterface.InputSlot], **kwargs): # Let the output trajectory length be half of the input trajectory length. return input_slots['upstream'].num_frames // 2 def modify(self, data: DataCollection, *, frame: int, input_slots: dict[str, ModifierInterface.InputSlot], **kwargs): # Pass only every other frame of the input trajectory down the pipeline. data.objects = input_slots['upstream'].compute(frame * 2).objects ``` ``` -------------------------------- ### Execute OVITO Python Script from Terminal Source: https://www.ovito.org/manual/python/introduction/installation.html Example of how to run the 'hello.py' script from a system terminal using the ovitos executable. This demonstrates the basic execution flow. ```bash user@linux:~/ovito-pro-3.15.4-x86_64/bin$ ./ovitos hello.py Hello, this is OVITO 3.15.4 ``` -------------------------------- ### Integer Trait Example Source: https://www.ovito.org/manual/python/introduction/custom_modifiers.html Example of defining an integer parameter using Traits Int, including a label for the UI. ```python value = Int(100, label="My value") ``` -------------------------------- ### Enable OpenGL Rendering with Qt Application Source: https://www.ovito.org/manual/python/modules/ovito_vis.html Create a QApplication object with GUI support before importing OVITO to establish an environment where OpenGL rendering is available. This is an alternative to setting environment variables. ```python import PySide6.QtWidgets app = PySide6.QtWidgets.QApplication() # This sets up an environment with GUI support from ovito.vis import * vp = Viewport() vp.render_image(renderer=OpenGLRenderer()) ``` -------------------------------- ### Boolean Trait Example Source: https://www.ovito.org/manual/python/introduction/custom_modifiers.html Example of defining a boolean parameter using Traits Bool, including a label for the UI. ```python option = Bool(True, label="My option") ``` -------------------------------- ### Loading and Replacing Data with FileSource Source: https://www.ovito.org/manual/python/modules/ovito_pipeline.html Demonstrates how to create a pipeline with a FileSource, compute data, and then replace the input file using the FileSource.load() method. ```python from ovito.io import import_file # Create a new pipeline with a FileSource: pipeline = import_file('input/first_file.dump') # Get the data from the first file: data1 = pipeline.compute() # Use FileSource.load() method to replace the pipeline's input with a different file pipeline.source.load('input/second_file.dump') # Now the pipeline gets its input data from the new file: data2 = pipeline.compute() ``` -------------------------------- ### Load Trajectory Modifier Example Source: https://www.ovito.org/manual/python/modules/ovito_modifiers.html This example demonstrates how to use the LoadTrajectoryModifier to load particle trajectories from a separate file, typically after loading a topology file. ```python from ovito.io import import_file from ovito.modifiers import LoadTrajectoryModifier ``` -------------------------------- ### Correctly Setting Up Pipeline Before Loop Source: https://www.ovito.org/manual/python/introduction/pipelines.html Set up the pipeline with all necessary modifiers once before entering the loop that iterates through the frames. ```python # CORRECT: # Step I: Populate the pipeline with modifiers: pipeline.modifiers.append(AtomicStrainModifier(cutoff = 3.2)) # Step II: Evaluate the pipeline in a loop over all frames: for data in pipeline.frames: ... ``` -------------------------------- ### Implementing a Custom Viewport Overlay Source: https://www.ovito.org/manual/python/modules/ovito_vis.html Example of creating a custom viewport overlay by inheriting from `ViewportOverlayInterface` and implementing the `render` method. This overlay draws 'Hello world' text at the center of the canvas. ```Python from ovito.vis import ViewportOverlayInterface class MyOverlay(ViewportOverlayInterface): def render(self, canvas: ViewportOverlayInterface.Canvas, **kwargs): canvas.draw_text("Hello world", pos=(0.5, 0.5)) ``` -------------------------------- ### Example Exported Text File Content Source: https://www.ovito.org/manual/python/introduction/file_io.html This is an example of the text file generated when exporting global attributes for multiple frames. The first column is the frame number, and subsequent columns are the exported attribute values. ```text # "Frame" "ExpressionSelection.count" 0 531 1 540 2 522 3 502 ... ``` -------------------------------- ### Create Bonds and Assign Topology Source: https://www.ovito.org/manual/python/modules/ovito_data.html Example of creating bonds and then assigning their topology using particle index pairs. Ensure the `count` matches the number of pairs provided. ```python pairs = [(0, 1), (1, 2), (2, 0)] # Pairs of particle indices to connect by bonds bonds = data.particles_.create_bonds(count=len(pairs), vis_params={'width': 0.6}) bonds.create_property('Topology', data=pairs) ``` -------------------------------- ### Matrix3 Trait Example Source: https://www.ovito.org/manual/python/introduction/custom_modifiers.html Defines a 3x3 matrix parameter for transformations. ```python tm = Matrix3(((1.0, 0.5, 0.0), (0.0, 1.0, -2.0), (0.0, 0.0, 1.0)), label="Transformation") ``` -------------------------------- ### Color Trait Example Source: https://www.ovito.org/manual/python/introduction/custom_modifiers.html Defines a color picker for RGB values. ```python rgb = Color((1.0, 0.5, 0.5), label="Color") ``` -------------------------------- ### Button Trait Example Source: https://www.ovito.org/manual/python/introduction/custom_modifiers.html Defines a button that triggers an action when clicked. ```python action_btn = Button(ovito_label="Run Action") ``` -------------------------------- ### Importing Simulation Data with OVITO Source: https://www.ovito.org/manual/python/modules/ovito_modifiers.html This snippet demonstrates how to import simulation data files using OVITO's import_file function. It sets up the data pipeline for further processing. ```python from ovito.io import * from ovito.data import * from ovito.modifiers import * from ovito.pipeline import * import numpy as np pipeline = import_file("input/simulation.*.dump") ``` -------------------------------- ### Importing and Initializing Dislocation Analysis Source: https://www.ovito.org/manual/python/modules/ovito_modifiers.html This snippet demonstrates how to import necessary OVITO modules and initialize the DislocationAnalysisModifier. It sets up a data pipeline by importing a simulation file. ```python from ovito.io import import_file, export_file from ovito.modifiers import DislocationAnalysisModifier from ovito.data import DislocationNetwork import ovito ovito.enable_logging() pipeline = import_file("input/simulation.dump") ``` -------------------------------- ### Float Trait Example Source: https://www.ovito.org/manual/python/introduction/custom_modifiers.html Defines a floating-point parameter for a custom modifier. ```python value = Float(123.4, label="My value") ``` -------------------------------- ### Vector3 Trait Examples Source: https://www.ovito.org/manual/python/introduction/custom_modifiers.html Defines 3D vector parameters with optional units and labels. ```python vec = Vector3((1.0, 0.5, 0.0), label="Direction") scaling = Vector3((1.0, 1.0, 1.0), label="Scaling", ovito_unit="percent") ``` -------------------------------- ### Set up Data Pipeline and Find Rings Source: https://www.ovito.org/manual/python/modules/ovito_modifiers.html Configures a data pipeline to import a file, append modifiers to create bonds and find rings, and export ring topology data. It also computes the data and prints a ring size histogram. ```python pipeline = import_file("input/Voronoi1.POSCAR.gz") pipeline.modifiers.append(CreateBondsModifier(mode=CreateBondsModifier.Mode.VdWRadius)) pipeline.modifiers.append(FindRingsModifier(maximum_ring_size=10)) # Export the topology of all rings of size 5 to a text file. export_file(pipeline, "output/5_rings_topology.txt", "txt/table", key="5-rings") # Convert ring size histogram to a NumPy array and print it to the terminal. data = pipeline.compute() print(data.tables["ring-size-histogram"].xy()) ``` -------------------------------- ### Enum Trait Example Source: https://www.ovito.org/manual/python/introduction/custom_modifiers.html Defines a dropdown selection for a parameter with a predefined list of options. ```python mode = Enum("Simple", ["Simple", "Advanced"], label="Mode") ``` -------------------------------- ### Access Particle Positions Source: https://www.ovito.org/manual/python/introduction/overview.html Get the positions of all particles from the `DataCollection` via the `particles.positions` field. ```python >>> print(data.particles.positions[...]) [[ 73.24230194 -5.77583981 -0.87618297] [-49.00170135 -35.47610092 -27.92519951] [-50.36349869 -39.02569962 -25.61310005] ..., [ 42.71210098 59.44919968 38.6432991 ] [ 42.9917984 63.53770065 36.33330154] [ 44.17670059 61.49860001 37.5401001 ]] ``` -------------------------------- ### Running OVITO in a Headless Environment with xvfb-run Source: https://www.ovito.org/manual/python/modules/ovito_vis.html This command wrapper allows OVITO to run in headless environments (like remote servers or HPC clusters) by providing a virtual X server. Ensure OVITO_GUI_MODE is set to 1 for GUI-related operations. ```bash OVITO_GUI_MODE=1 xvfb-run python3 ``` -------------------------------- ### Create and Use QPainter for Custom Drawing Source: https://www.ovito.org/manual/python/modules/ovito_vis.html Demonstrates how to create a QPainter object for advanced drawing on the viewport canvas using a context manager. This is useful for drawing complex graphics as part of a custom viewport overlay. ```python from ovito.vis import ViewportOverlayInterface from ovito.qt_compat import QtGui class PainterOverlay(ViewportOverlayInterface): def render(self, canvas: ViewportOverlayInterface.Canvas, **kwargs): with canvas.qt_painter() as painter: pen = QtGui.QPen(QtGui.QColor(255,0,0)) brush = QtGui.QBrush(QtGui.QGradient(QtGui.QGradient.OrangeJuice)) painter.setPen(pen) painter.setBrush(brush) painter.drawEllipse(painter.window()) ``` -------------------------------- ### PropertyReference Trait Example Source: https://www.ovito.org/manual/python/introduction/custom_modifiers.html References a property of a data object, enabling dynamic access to data. ```python input_property = PropertyReference(container="input_table", label="Input property") ``` -------------------------------- ### OvitoObject Trait Example Source: https://www.ovito.org/manual/python/introduction/custom_modifiers.html Manages an OVITO object, such as a visualization element, within a custom modifier. ```python vector_vis = OvitoObject(ovito.vis.VectorVis, flat_shading=False, width=0.3, title='Displacements') ``` -------------------------------- ### Branching Pipelines and Independent Visual Elements Source: https://www.ovito.org/manual/python/modules/ovito_pipeline.html Demonstrates how to branch a pipeline, add multiple pipelines to the scene, and create independent visual elements for different branches to allow distinct visualization configurations. ```python pipeline_A = import_file('input/nylon.data') pipeline_B = Pipeline(head=pipeline_A.head) # Branch pipeline B off of pipeline A # Insert both pipelines into the visualization scene pipeline_A.add_to_scene() pipeline_B.add_to_scene() # Obtain output data collection of pipelines A and B. Both pipelines share the same pipeline nodes, # which means they yield an identitical output, which also means they implicitly share the same # visual elements attached to the data objects. data = pipeline_B.compute() assert pipeline_A.compute().particles.vis is data.particles.vis # A change to a visual element thus affects the rendering of both pipelines A and B. data.particles.vis.scaling = 0.8 # In order to configure the visualization of particles differently in pipelines A and B, # we need to create an independent visual element in pipeline B, for example. vis_B = pipeline_B.make_vis_element_independent(data.particles.vis) # Configure replacement visual element for pipeline B (leaving the original one in pipeline A unchanged) vis_B.shape = ParticlesVis.Shape.Circle ``` -------------------------------- ### Vector2 Trait Examples Source: https://www.ovito.org/manual/python/introduction/custom_modifiers.html Defines 2D vector parameters with optional units and range constraints. ```python xy = Vector2((1.0, -0.5), label="Position") size = Vector2((1.0, 1.0), ovito_unit="percent", low=0.0, high=1.0) ``` -------------------------------- ### Complete Custom File Reader Example Source: https://www.ovito.org/manual/python/introduction/custom_file_readers.html A full implementation of a custom file reader for a hypothetical 'MyFileFormat'. It includes `detect`, `scan`, and `parse` methods to load particle data from a file. ```python from ovito.data import DataCollection from ovito.io import FileReaderInterface, import_file from typing import Callable, Any import re class MyFileReader(FileReaderInterface): @staticmethod def detect(filename: str): try: with open(filename, "r") as f: line = f.readline() return line.strip() == "Header of MyFileFormat" except OSError: return False def scan(self, filename: str, register_frame: Callable[..., None]): expr = r"(Timestep \d+): (\d+) particles" with open(filename, "r") as f: for line_number, line in enumerate(f): match = re.match(expr, line.strip()) if match: num_particles = int(match.group(2)) label = match.group(1) register_frame(frame_info=(line_number, num_particles), label=label) def parse(self, data: DataCollection, filename: str, frame_info: tuple[int, int], **kwargs: Any): starting_line_number, num_particles = frame_info with open(filename, "r") as f: for _ in range(starting_line_number + 1): f.readline() particles = data.create_particles(count=num_particles) positions = particles.create_property("Position") for i in range(num_particles): positions[i] = [float(coord) for coord in f.readline().strip().split()] ``` -------------------------------- ### Code Trait Example Source: https://www.ovito.org/manual/python/introduction/custom_modifiers.html Defines a multi-line text input field for longer text content. ```python long_text = Code("A multi-line\ntext field", label="Text") ``` -------------------------------- ### Creating a Pipeline with StaticSource Source: https://www.ovito.org/manual/python/modules/ovito_pipeline.html Initialize a `Pipeline` using a `StaticSource` that manages a `DataCollection`. This is useful for providing custom or pre-processed data to the pipeline. Ensure all necessary data objects like `SimulationCell` and `Particles` are added to the `DataCollection`. ```python from ovito.pipeline import StaticSource, Pipeline from ovito.data import DataCollection, SimulationCell, Particles from ovito.modifiers import CreateBondsModifier from ovito.io import export_file # Insert a new SimulationCell object into a data collection: data = DataCollection() cell = SimulationCell(pbc = (False, False, False)) cell[:,0] = (4,0,0) cell[:,1] = (0,2,0) cell[:,2] = (0,0,2) data.objects.append(cell) # Create a Particles object containing two particles: particles = Particles() particles.create_property('Position', data=[[0,0,0],[2,0,0]]) data.objects.append(particles) # Create a new Pipeline with a StaticSource as data source: pipeline = Pipeline(source = StaticSource(data = data)) # Apply a modifier: pipeline.modifiers.append(CreateBondsModifier(cutoff = 3.0)) # Write pipeline results to an output file: export_file(pipeline, 'output/structure.data', 'lammps/data', atom_style='bond') ``` -------------------------------- ### Range Trait Examples Source: https://www.ovito.org/manual/python/introduction/custom_modifiers.html Defines integer and float range parameters with optional units and placeholders. ```python c = Range(low=1, high=16, value=1, label="N") f = Range(low=0.0, high=1.0, value=0.5, label="Fract") q = Range(low=0.0, high=1.0, value=0.5, label="Quality", ovito_unit="percent") r = Range(low=0.0, value=0.0, label="Radius", ovito_placeholder="‹default›") ``` -------------------------------- ### vertex_count Source: https://www.ovito.org/manual/python/modules/ovito_data.html Gets the total number of Delaunay vertices in the tessellation, including any generated ghost vertices. ```APIDOC ## vertex_count ### Description Returns the number of Delaunay vertices in the tessellation, including ghost vertices. ### Returns * int ``` -------------------------------- ### Setting TimeAveragingModifier Interval Source: https://www.ovito.org/manual/python/modules/ovito_modifiers.html Example of how to restrict the time averaging to a specific interval of the trajectory, such as the second half. ```python modifier.interval = (pipeline.num_frames//2, pipeline.num_frames-1) ``` -------------------------------- ### create_qwidget Source: https://www.ovito.org/manual/python/modules/ovito_gui.html Creates an interactive Qt widget that displays a 3D scene from a Pipeline or Viewport. This allows for custom UI development integrating OVITO's visualization. ```APIDOC ## ovito.gui.create_qwidget ### Description Creates an interactive visual widget that displays the three-dimensional scene as seen through a virtual `Viewport`. The method creates an interactive window accepting mouse inputs from the user similar to the viewport windows of the OVITO desktop application. You can use this method to develop custom user interfaces based on the Qt cross-platform framework that integrate OVITO’s functionality and display the output of a data pipeline. ### Method Signature `create_qwidget(_contents =None_, _parent =None_, _*_ , _show_orientation_indicator =True_, _show_title =False_) ### Parameters #### Positional Arguments * **contents** (`Union[Pipeline, Viewport, None]`) – The `Pipeline` or `Viewport` object to be displayed by the widget. * **parent** (`PySide6.QtWidgets.QWidget | None`) – An optional Qt widget to be set as parent for the new viewport widget. #### Keyword Arguments * **show_orientation_indicator** (`bool`) – Controls the visibility of the coordinate axes in the lower left corner of the viewport widget. * **show_title** (`bool`) – Controls the visibility of viewport title in the upper left corner of the viewport widget. ### Returns `PySide6.QtWidgets.QWidget` - The Qt widget returned by this method is linked to the `Viewport` instance if provided. Any changes your Python script subsequently makes to the non-visual `Viewport` object, for example setting its `camera_pos` or `camera_dir`, will automatically be reflected by the visual widget. Vice versa will user interactions with the viewport widget automatically lead to changes of the associated `Viewport` object. ### Notes If you provide a `Pipeline` object as the `contents` argument, the method will create an ad-hoc viewport showing the output of just the given pipeline. If you provide no `contents` argument, the method will create an ad-hoc viewport showing the contents of the global `ovito.scene`, including all pipelines that have been added. OVITO automatically creates a global QApplication object if necessary, which can be accessed via the `QApplication.instance()` static method. ### Example ```python from ovito.io import import_file from ovito.vis import Viewport from ovito.gui import create_qwidget from PySide6.QtWidgets import QApplication import sys # Import a particle model and add it to the global visualization scene. pipeline = import_file('input/simulation.dump') pipeline.add_to_scene() # Create a virtual viewport. vp = Viewport(type=Viewport.Type.Perspective, camera_dir=(2, 1, -1)) # Create a GUI widget associated with the viewport. widget = create_qwidget(vp) widget.resize(500, 400) widget.setWindowTitle('OVITO Viewport Demo') widget.show() widget.raise_() vp.zoom_all((widget.width(), widget.height())) # Start the Qt event loop by invoking the QApplication.exec() method. sys.exit(QApplication.instance().exec()) ``` ``` -------------------------------- ### Populating the Scene with Data Source: https://www.ovito.org/manual/python/modules/ovito_vis.html This snippet demonstrates how to load simulation data and add it to the visualization scene. Ensure you have a simulation file (e.g., 'simulation.dump') to use this code. ```python pipeline = import_file('simulation.dump') pipeline.add_to_scene() ``` -------------------------------- ### DataObjectReference Trait Example Source: https://www.ovito.org/manual/python/introduction/custom_modifiers.html References an OVITO data object, like a DataTable, within a custom modifier. ```python input_table = DataObjectReference(DataTable, label="Input table") ``` -------------------------------- ### Import Simulation Data with ovito.io.import_file Source: https://www.ovito.org/manual/python/introduction/overview.html Use `import_file` to create a new pipeline and load simulation data from disk. The loaded data is accessible via the pipeline's `source` field. ```python from ovito.io import import_file pipeline = import_file("simulation.dump") ``` ```python >>> print(pipeline.source) ``` -------------------------------- ### String Trait Examples Source: https://www.ovito.org/manual/python/introduction/custom_modifiers.html Defines text input fields for string parameters, with and without default values. ```python text = Str("Hello world", label="Text") query = Str(label="Query", ovito_placeholder="‹none›") ``` -------------------------------- ### Rendering an Image with Tachyon Renderer Source: https://www.ovito.org/manual/python/modules/ovito_vis.html This example shows how to render an image using the Tachyon renderer with specific settings for ambient occlusion and shadows. The output is saved to a PNG file. ```python vp.render_image(filename='output/simulation.png', size=(320,240), background=(0,0,0), renderer=TachyonRenderer(ambient_occlusion=False, shadows=False)) ``` -------------------------------- ### get Source: https://www.ovito.org/manual/python/modules/ovito_data.html Retrieves a property array from a data container by its name. Optionally raises an error if the property is not found. ```APIDOC ## get(_name : str, _require : bool = False_) → Property | None ### Description Retrieves a property array from this container. If `require` is True, a KeyError is raised if the property does not exist. Otherwise, None is returned. ### Parameters * **name** (str) - The name of the property to retrieve. * **require** (bool, optional) - If True, raise KeyError if the property is not found. Defaults to False. ### Returns * **Property | None** - The requested `Property` object, or `None` if `require=False` and the property is not present. ### Example ```python position_property = data.particles_.get('Position') if position_property is None: print("Position property not found.") try: velocity_property = data.particles_.get('Velocity', require=True) except KeyError: print("Velocity property is mandatory and not found.") ``` ``` -------------------------------- ### Compute Pipeline with Caching Source: https://www.ovito.org/manual/python/introduction/custom_modifiers.html Demonstrates how pipeline computation triggers loading of input frames, highlighting the efficiency gains from input slot caching. ```python pipeline.compute(0) # loads trajectory frames 0 and 1 pipeline.compute(1) # loads trajectory frames 1 and 2 pipeline.compute(2) # loads trajectory frames 2 and 3 ... ``` -------------------------------- ### StructureFactorModifier Example Source: https://www.ovito.org/manual/python/modules/ovito_modifiers.html Demonstrates loading particle data, computing the structure factor using StructureFactorModifier, and exporting the results. ```python from ovito.io import import_file from ovito.modifiers import StructureFactorModifier ``` -------------------------------- ### Loading Custom Particle Shape and Highlighting Edges Source: https://www.ovito.org/manual/python/modules/ovito_data.html This example demonstrates loading a custom 3D shape for a specific particle type using its ID and enabling edge highlighting for that shape. It assumes a pipeline has already been set up and data imported. ```python pipeline = import_file("input/simulation.dump") pipeline.add_to_scene() types = pipeline.source.data.particles_.particle_types_ types.type_by_id_(1).load_shape("input/tetrahedron.vtk") types.type_by_id_(1).highlight_edges = True ``` -------------------------------- ### PythonSource (Function-based Interface) Source: https://www.ovito.org/manual/python/modules/ovito_pipeline.html Example demonstrating the function-based interface for PythonSource, where a single function generates pipeline data. ```APIDOC ## PythonSource (Function-based Interface) ### Description This example shows how to use the function-based interface of `PythonSource` to dynamically generate simulation data. A single Python function is defined and passed to `PythonSource` to create particle data for each frame. ### Usage ```python from ovito.pipeline import Pipeline, PythonSource from ovito.io import export_file from ovito.data import DataCollection import numpy # User-defined data source function, which populates an empty DataCollection with # some data objects: def create_model(frame: int, data: DataCollection): particles = data.create_particles(count=20) coordinates = particles.create_property('Position') coordinates[:,0] = numpy.linspace(0.0, 50.0, particles.count) coordinates[:,1] = numpy.cos(coordinates[:,0]/4.0 + frame/5.0) coordinates[:,2] = numpy.sin(coordinates[:,0]/4.0 + frame/5.0) # Create a data pipeline with a PythonSource, which executes our # script function defined above. pipeline = Pipeline(source = PythonSource(function = create_model)) # Export the results of the data pipeline to an output file. # The system will invoke the Python function defined above once per animation frame. export_file(pipeline, 'output/trajectory.xyz', format='xyz', columns=['Position.X', 'Position.Y', 'Position.Z'], multiple_frames=True, start_frame=0, end_frame=10) ``` ### Parameters - `function` (callable): The Python function to execute for data generation. It must accept `frame` (int) and `data` (DataCollection) as arguments. ``` -------------------------------- ### FilePath Trait Example Source: https://www.ovito.org/manual/python/introduction/custom_modifiers.html Defines a file path parameter with options to check file existence and filter by type. ```python input_file = FilePath(label="Input file", ovito_file_exists = True, ovito_file_filter = ["JSON (*.json)", "All files (*)"]) ``` -------------------------------- ### Create and Attach TextLabelOverlay in OVITO Source: https://www.ovito.org/manual/python/modules/ovito_vis.html Demonstrates how to create a TextLabelOverlay instance and attach it to a viewport. This is useful for displaying static text or custom labels within the OVITO visualization. ```python from ovito.vis import TextLabelOverlay, Viewport from ovito.qt_compat import QtCore # Create the overlay: overlay = TextLabelOverlay( text = 'Some text', alignment = QtCore.Qt.AlignmentFlag.AlignHCenter | QtCore.Qt.AlignmentFlag.AlignBottom, offset_y = 0.1, font_size = 0.03, text_color = (0,0,0)) # Attach the overlay to a newly created viewport: viewport = Viewport(type = Viewport.Type.Top) viewport.overlays.append(overlay) ```