ovito.traits — OVITO Python Reference 3.16.0 documentation

# `ovito.traits`

Added in version 3.8.0.

This module contains various trait types, which can be used in the context of custom modifiers, custom viewport overlays, and other Python-based extensions for OVITO. Traits encapsulate object parameters, which are displayed in the OVITO graphical user interface and can be adjusted by the user.

The specific trait types defined in this module supplement the generic trait types provided by the Traits Python package, which can be used to define parameters with simple data types such as numeric values and strings. The OVITO-specific trait types in this module are tailored to the needs of OVITO’s Python scripting interface and provide additional functionality for interacting with the OVITO data pipeline, the undo system, and the graphical user interface.

The following OVITO-specific trait types are available:

- `OvitoObject`: A trait type that stores an instance of a class from the `ovito` package, e.g. a visual element, modifier, or data object.

- `Color`: A trait type that stores a tuple of three floats representing the RGB components of a color parameter.

- `Vector2`: A trait type that stores a tuple of two floats representing a vector or point in 2d space.

- `Vector3`: A trait type that stores a tuple of three floats representing a vector or point in 3d space.

- `Matrix3`: A trait type that stores a 3-by-3 floating-point matrix.

- `FilePath`: A trait type that stores a filesystem path. In the GUI, a file selection dialog is displayed for the user to pick the trait value.

- `DataObjectReference`: A trait type that holds a reference to a certain `DataObject` in a `DataCollection` object hierarchy.

- `PropertyReference`: A trait type that holds a reference to a `Property`.

class ovito.traits.Color(default=(1.0, 1.0, 1.0), **metadata)

  A trait type that stores a tuple of three floats representing the RGB components of a color parameter. The three components must be in the range 0.0 - 1.0.

  See User parameters for more information.

  Parameters:

    - default – The initial RGB values to be assigned to the parameter trait.

    - metadata – Additional keyword arguments are forwarded to the base trait constructor.

class ovito.traits.DataObjectReference(object_type, filter=None, default_value=None, **metadata)

  This trait type holds a `DataObject.Ref` reference to a data object in a `DataCollection`. The stored reference tells where to find the selected object in the pipeline output but it does not hold the actual object. The user can select the data object from a list of available objects in the OVITO graphical user interface. To retrieve the actual object from a data collection, use the `DataCollection.get` method.

  Parameters:

    - object_type (type[DataObject]) – A `DataObject`-derived class type.

    - filter (Callable[[DataObject], bool] | None) – Optional callback function that can be used to additionally filter the list of data objects shown to the user in the GUI.

    - default_value (Ref | None) – Optional `DataObject.Ref` instance to be used as the initial value of the trait.

    - metadata – Additional keyword arguments are forwarded to the base trait constructor.

  Usage example: a custom modifier that lets the user select a `DataTable` object from the pipeline:

      from ovito.data import DataTable, DataObject
      from ovito.pipeline import ModifierInterface
      from ovito.traits import DataObjectReference

      class PrintTableModifier(ModifierInterface):

          # Define a parameter trait that lets the user select a DataTable:
          input_table = DataObjectReference(DataTable, label="Input table")

          def modify(self, data, **kwargs):
              # Look up the selected DataTable in the input data collection:
              table = data.get(self.input_table)
              print(table)

  This is how you would insert the custom modifier into the pipeline and configure it to print a specific data table:

      pipeline.modifiers.append(PrintTableModifier(input_table=DataObject.Ref(DataTable, 'structures')))

  Added in version 3.11.0.

class ovito.traits.FilePath(default='', **metadata)

  A trait type that stores a filesystem path. In the GUI, a file selection dialog is displayed for the user to pick the trait value.

  See User parameters for more information.

  Parameters:

    - default (str) – Initial parameter trait value.

    - metadata – Additional keyword arguments are forwarded to the base trait constructor.

  Added in version 3.10.0.

class ovito.traits.Matrix3(default=((0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 0.0)), **metadata)

  A trait type that stores a 3x3 matrix represented as a tuple of tuples of floats. Each inner tuple represents a row of the matrix. Thus, the element in the i-th row and the j-th column of the matrix can be accessed as `matrix[i][j]`.

  See User parameters for more information.

  Parameters:

    - default – The initial matrix to be assigned to the parameter trait. Must be convertible to a tuple of tuples of floats.

    - metadata – Additional keyword arguments are forwarded to the base trait constructor.

  Added in version 3.11.2.

class ovito.traits.OvitoObject(klass, factory=None, ovito_hide_object=False, **params)

  A trait type that stores an instance of a class from the `ovito` package, e.g. a visual element, modifier, or data object. The object instance is treated as an sub-object of the class defining the trait, and the sub-object’s parameters are displayed in the OVITO graphical user interface such that the user can adjust its settings. See User parameters for more information.

  Parameters:

    - klass – The object class type to instantiate.

    - params – All other keyword parameters are forwarded to the constructor of the object class.

  Usage example:

      from ovito.data import DataCollection
      from ovito.pipeline import ModifierInterface
      from ovito.traits import OvitoObject
      from ovito.vis import BondsVis

      class MyCreateBondsModifier(ModifierInterface):

          # This trait field stores a pre-configured BondsVis visual element to be used
          # for the bonds newly created by this custom modifier.
          # The BondsVis visual element is not enabled by default, so the bonds will not
          # be displayed in the viewport unless the user explicitly enables it.
          # The width of the bonds is set to 0.1, but this can be adjusted as needed.
          bonds_vis = OvitoObject(BondsVis, enabled=False, width=0.1)

          def modify(self, data: DataCollection, *, frame: int, **kwargs):
              bonds = data.particles_.create_bonds(count=3, vis=self.bonds_vis)
              pairs = [(0, 1), (1, 2), (2, 0)] # Pairs of particle indices to connect by bonds
              bonds.create_property('Topology', data=pairs)

class ovito.traits.PropertyReference(*, container=DataObject.Ref(Particles), default_value='', mode=Mode.Components, filter=None, **metadata)

  A trait type that manages a reference to a `Property`. The reference is encoded as a string containing the name of the property - optionally followed by a dot and the name of a vector component of the property.

  See User parameters for more information.

  Parameters:

    - container (str | Ref) –

      1. `Ref` specifying a `PropertyContainer` object from which the user can select a property or

      2. name of a `DataObjectReference` trait defined in the same class, which allows the user to select a property container.

    - default_value (str) – Initial property name to be assigned to the parameter trait.

    - mode (Mode) – Controls whether the trait should list entire properties, individual components of properties, or both.

    - filter (Callable[[PropertyContainer, Property], bool] | None) – Optional callback function that can be used to filter the list of properties shown to the user.

    - metadata – Additional keyword arguments are forwarded to the base trait constructor.

  Usage example:

      from ovito.data import DataObject, PropertyContainer, Particles
      from ovito.pipeline import ModifierInterface
      from ovito.traits import DataObjectReference, PropertyReference

      class PrintTypesModifier(ModifierInterface):

          # Define a parameter trait that lets the user select a PropertyContainer.
          # A filter function is provided to show only containers that contain at least one typed property.
          input_container = DataObjectReference(
              PropertyContainer,
              default_value=DataObject.Ref(Particles),
              filter=lambda container: any(prop.types for prop in container.values()),
              label="Container")

          # Define a parameter trait that lets the user select a property from the selected container.
          # A filter function is provided to show only properties that are typed.
          input_property = PropertyReference(
              container="input_container",   # That's the name of the trait defined above
              default_value="Particle Type",
              mode=PropertyReference.Mode.Properties,
              filter=lambda c, p: len(p.types) != 0,
              label="Property")

          # Modifier function implementation:
          def modify(self, data, **kwargs):
              if not self.input_container: return
              if not self.input_property: return
              container = data.get(self.input_container) # Look up the selected PropertyContainer
              prop = container[self.input_property]  # Look up the selected property
              # Print the list of types attached to the selected property:
              for t in prop.types:
                  print(t.id, t.name)

  Added in version 3.11.0.

  class Mode(*values)

    Enumeration of possible component listing modes for vector properties.

    Components

      List individual components of vector properties.

    Properties

      List entire properties (not their vector components).

    PropertiesAndComponents

      List entire properties AND their vector components.

class ovito.traits.Vector2(default=(0.0, 0.0), **metadata)

  A trait type that stores a tuple of two floats, which represent a vector or point in 2d space.

  See User parameters for more information.

  Parameters:

    - default – The initial vector value to be assigned to the parameter trait.

    - metadata – Additional keyword arguments are forwarded to the base trait constructor.

  Added in version 3.10.0.

class ovito.traits.Vector3(default=(0.0, 0.0, 0.0), **metadata)

  A trait type that stores a tuple of three floats, which represent a vector or point in 3d space.

  See User parameters for more information.

  Parameters:

    - default – The initial vector value to be assigned to the parameter trait.

    - metadata – Additional keyword arguments are forwarded to the base trait constructor.

  Added in version 3.10.0.

ovito.traits.action_handler(button_trait_name)

  A decorator for handler methods that handle button events in the GUI. See User parameters for more information on GUI traits.

  Use this decorator to mark a method of your class as an event handler for a `traits.trait_types.Button` trait. The handler method will be called when the user clicks the button in the OVITO graphical user interface.

  Parameters:

    button_trait_name (str) – The name of the button trait that the handler method should respond to.

  Return type:

    Callable

  Usage example:

      from ovito.gui import UtilityInterface
      from ovito.traits import action_handler
      from traits.api import Button

      class MyUtilityApplet(UtilityInterface):
          hello_btn = Button(ovito_label="Click me")

          @action_handler("hello_btn")
          def say_hello(self):
              print("Hello world!")

  Note

  The OVITO GUI does not support the label argument of the `Button` trait constructor. Please use the ovito_label metadata key instead to specify the button’s label in the GUI: `Button(ovito_label="Click me")`.

  If your handler is performing a long-running operation, it should be written as a Python generator function that yields status strings or progress values to the GUI. The GUI will display these messages in a progress dialog window while the handler is running. The `yield` statement also gives the GUI a chance to handle user input events and keep the application responsive. It allows the user to cancel the long-running task.

      @action_handler("process_btn")
      def process_trajectory(self):
          num_frames = 1000
          yield f"Processing trajectory of {num_frames} frames..."
          for frame in range(num_frames):
              yield frame / num_frames # Report progress as a fraction
              do_some_work(frame)

  Any exceptions raised by the handler method will be caught by the GUI and displayed to the user in a message box.

  Added in version 3.12.0.