### Run OpenFF Toolkit Examples Script Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/releasehistory.md Command to execute the `openff-toolkit-examples` script after installation to copy the example suite to a convenient location for execution. ```Shell openff-toolkit-examples ``` -------------------------------- ### Install OpenFF Toolkit Examples via Conda Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/releasehistory.md Instructions for installing the `openff-toolkit-examples` package using Conda, which provides easy access to the toolkit's example suite and their dependencies. ```Shell conda install -c conda-forge openff-toolkit-examples ``` -------------------------------- ### Example: QCArchive Interface for Molecule Instantiation and Energy Calculation Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/releasehistory.md An example notebook, `QCarchive_interface.ipynb`, has been added. It illustrates how users can instance a `Molecule` from a QCArchive entry-level record and subsequently calculate its energy using RDKit through QCEngine. ```APIDOC Example notebook: examples/QCArchive_interface/QCarchive_interface.ipynb Key methods: Molecule.from_qcarchive_record(), QCEngine for energy calculation. ``` -------------------------------- ### Example: Compute Conformer Energies Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/releasehistory.md An example notebook and utility have been added to demonstrate how to compute conformer energies. This example is designed to be reverse-compatible with the 0.6.0 OpenFF Toolkit release. ```APIDOC Example notebook: examples/conformer_energies ``` -------------------------------- ### Install OpenFF Toolkit from Source using Pip Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/installation.md This command installs the OpenFF Toolkit from its local source directory using pip. It assumes the user has already navigated into the 'openff-toolkit' directory and has manually installed all necessary dependencies. ```shell-session $ cd openff-toolkit $ python -m pip install . ``` -------------------------------- ### Importing `get_data_file_path` Utility Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/SMIRNOFF_simulation/run_simulation.ipynb Imports the `get_data_file_path` utility function from `openff.toolkit.utils` to easily access example data files distributed with the Open Force Field Toolkit. ```Python from openff.toolkit.utils import get_data_file_path ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/users/developing.md After installing `pre-commit`, this command installs the configured Git hooks into the local repository. These hooks run linters and other checks in an isolated virtual environment before each commit, ensuring that changes adhere to the project's style guidelines. ```shell pre-commit install ``` -------------------------------- ### Define Protein and Ligand File Paths Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/toolkit_showcase/toolkit_showcase.ipynb This snippet defines the file paths for the prepared protein (5tbm_prepared.pdb) and ligand (PT2385.sdf) structures. These paths are used in subsequent steps to load and process the molecular data for the simulation setup. ```python receptor_path = "5tbm_prepared.pdb" ligand_path = "PT2385.sdf" ``` -------------------------------- ### Run Short Molecular Dynamics Simulation with OpenMM and OpenFF Toolkit Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/toolkit_showcase/toolkit_showcase.ipynb This example shows how to run a brief molecular dynamics simulation. It initializes velocities to a specified temperature and runs the simulation for a set clock time. Note: This is a basic demonstration and a real simulation would require additional equilibration steps. ```python simulation.context.setVelocitiesToTemperature(300 * openmm_unit.kelvin) simulation.runForClockTime(1.0 * openmm_unit.minute) ``` -------------------------------- ### Activate OpenFF Toolkit Environment with Mamba Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/installation.md After creating the environment, this command activates it, making the OpenFF Toolkit and its dependencies available in the current shell session. ```shell-session $ mamba activate openff-toolkit ``` -------------------------------- ### Install Pre-commit Tool Locally Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/users/developing.md This command installs the `pre-commit` tool using `mamba` from the `conda-forge` channel, which can also be installed via `pip`. It sets up the framework for running automated hooks before Git commits, helping to enforce style and quality checks automatically. ```shell mamba install pre-commit -c conda-forge # also available via pip ``` -------------------------------- ### Install and Run Code Linters Locally Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/users/developing.md This snippet demonstrates how to install `black`, `isort`, and `flake8` using `mamba` (or `conda-forge`) and then run them against the `openff` directory to ensure code style consistency. These tools help maintain the project's high standards for code cleanliness and readability. ```shell mamba install black isort flake8 -c conda-forge black openff isort openff flake8 openff ``` -------------------------------- ### Install nglview JupyterLab Extensions Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/visualization/README.md These commands install the necessary `nglview` extensions for JupyterLab. The first command installs the `nglview-js-widgets` extension, and the second installs the core `@jupyter-widgets/jupyterlab-manager` for general widget support, both required for `nglview` visualizations to function properly in JupyterLab. ```Shell jupyter labextension install nglview-js-widgets jupyter-labextension install @jupyter-widgets/jupyterlab-manager ``` -------------------------------- ### Specifying PDB File Path for System Loading Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/SMIRNOFF_simulation/run_simulation.ipynb Sets the `pdb_file_path` variable to point to an example PDB file containing a mixture of ethanol and cyclohexane. It demonstrates how to use `get_data_file_path` to load different system complexities, from single molecules to larger mixtures. ```Python # 1 molecule of ethanol and 1 of cyclohexane. pdb_file_path = get_data_file_path("systems/test_systems/1_cyclohexane_1_ethanol.pdb") # 40%-60% cyclohexane-ethanol mixture. # pdb_file_path = get_data_file_path('systems/packmol_boxes/cyclohexane_ethanol_0.4_0.6.pdb') ``` -------------------------------- ### Visualize Molecule with OpenEye Backend Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/visualization/visualization.ipynb Illustrates how to use the 'openeye' backend for visualization. This requires the OpenEye Toolkits to be installed and licensed, handling potential import or licensing errors gracefully. ```python try: from openeye import oechem assert oechem.OEChemIsLicensed() m.visualize(backend="openeye") except (ImportError, AssertionError): print('Visualizing with `backend="openeye"` requires the OpenEye Toolkits') ``` -------------------------------- ### Create OpenFF Toolkit Environment with Mamba Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/installation.md This command creates a new Conda environment named 'openff-toolkit' and installs the Open Force Field Toolkit package from the 'conda-forge' channel using Mamba. It is the recommended way to install the toolkit and its dependencies. ```shell-session $ mamba create -n openff-toolkit -c conda-forge openff-toolkit ``` -------------------------------- ### Install OpenEye Toolkits with Mamba Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/installation.md This command installs the OpenEye toolkits from the 'openeye' Conda channel using Mamba. This is an optional dependency for the OpenFF Toolkit, requiring a separate license key for full functionality. ```shell-session $ mamba install -c openeye openeye-toolkits ``` -------------------------------- ### Set up OpenFF Toolkit development environment Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/users/developing.md Commands to clone the OpenFF Toolkit repository, create a dedicated conda environment using mamba with specified dependencies, activate it, and perform an editable installation of the toolkit for development. ```shell git clone https://github.com/openforcefield/openff-toolkit cd openff-toolkit/ mamba env create -n openff-dev -f devtools/conda-envs/test_env.yaml mamba activate openff-dev pip install -e . ``` -------------------------------- ### Compute Molecular Energy with QCEngine and RDKit Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/QCArchive_interface/QCarchive_interface.ipynb Demonstrates setting up and executing an energy computation task using `qcengine` with RDKit, taking a QCArchive molecule as input. This functionality requires QCEngine to be installed. ```python import qcengine # set up the RDKit task rdkit_task = { "schema_name": "qcschema_input", "schema_version": 2, "molecule": qc_molecule, "driver": "energy", "model": {"method": "uff", "basis": None}, "keywords": {"scf_type": "df"}, } # now lets compute the energy using qcengine and RDKit and print the result result = qcengine.compute(rdkit_task, "rdkit") ``` -------------------------------- ### Create an example molecule and label the force terms applied to it Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/inspect_assigned_parameters/inspect_assigned_parameters.ipynb This example shows the parameters applied to a single molecule that is created from a SMILES string. The first output section consists of `Bond` parameters that would be assigned to the molecule. Each bond is described by the indices of the two atoms it connects, its "parameter ID", and the SMIRKS that caused it to match the target bond. The other `ParameterHandler`s print in order after that. Note that the `ToolkitAM1BCC` and `Electrostatics` handlers do not assign SMIRKS-based parameters, therefore they do not print any match information. ```python from openff.toolkit import ForceField, Molecule, Topology # Create a simple molecule from SMILES and turn it into a topology. molecule = Molecule.from_smiles("C=C(N)(C)") topology = Topology.from_molecules([molecule]) # Let's label using the Sage force field forcefield = ForceField("openff-2.2.0.offxml") # Run the molecule labeling molecule_force_list = forcefield.label_molecules(topology) # Print out a formatted description of the parameters applied to this molecule for mol_idx, mol_forces in enumerate(molecule_force_list): print(f"Forces for molecule {mol_idx}") for force_tag, force_dict in mol_forces.items(): print(f"\n{force_tag}:") for atom_indices, parameter in force_dict.items(): atomstr = "" for idx in atom_indices: atomstr += f"{idx:>3}" print( f"atoms: {atomstr} parameter_id: {parameter.id} smirks {parameter.smirks}" ) ``` -------------------------------- ### Install jupyterlab-myst for MyST Markdown Support Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/users/developing.md This command installs the `jupyterlab-myst` Jupyter extension using `mamba` from the `conda-forge` channel. This extension enables Jupyter Notebooks to correctly render MyST Markdown syntax, aligning the viewing experience in Jupyter with the Sphinx-rendered documentation. ```shell mamba install -c conda-forge jupyterlab-myst ``` -------------------------------- ### Install nglview with Mamba Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/visualization/README.md This command installs the `nglview` package using the `mamba` package manager from the `conda-forge` channel. `nglview` is a dependency for enabling the `nglview` backend for molecule visualizations within `openff-toolkit` in Jupyter environments. ```Shell mamba install -c conda-forge nglview ``` -------------------------------- ### Simplified SMIRNOFF XML for TIP3P Water Model Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/users/smirnoff.md This XML snippet illustrates a simplified SMIRNOFF force field file for TIP3P water. It demonstrates how parameters like constraints, van der Waals, and electrostatics are defined using SMIRKS codes, explicit functional forms, and units, ensuring reproducibility and clear implementation definitions. The example shows how specific atoms are indexed for parameter application. ```xml The Open Force Field Initiative 2021-08-16 ``` -------------------------------- ### Enhanced OpenEye Toolkit Availability Check Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/releasehistory.md The `OpenEyeToolkitWrapper.is_available` method now returns `True` if any OpenEye tools are licensed and installed, rather than requiring all specific tools. This allows for more flexible use of OpenEye functionality, such as `OEChem` without an `OEOmega` license. ```APIDOC OpenEyeToolkitWrapper.is_available() -> bool // Behavior change: Returns True if any OpenEye tools are licensed and installed. ``` -------------------------------- ### Check Registered Toolkits and Versions in OpenFF Toolkit Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/installation.md This Python snippet demonstrates how to access the `GLOBAL_TOOLKIT_REGISTRY` to inspect which external chemistry toolkits (like RDKit, AmberTools, OpenEye) are currently registered and their respective versions within the OpenFF Toolkit environment. ```python from openff.toolkit import GLOBAL_TOOLKIT_REGISTRY print(GLOBAL_TOOLKIT_REGISTRY.registered_toolkit_versions) # {'The RDKit': '2022.03.5', 'AmberTools': '22.0', 'Built-in Toolkit': None} ``` -------------------------------- ### Lazy Loading openff.toolkit Submodules Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/releasehistory.md This snippet illustrates how submodules like `topology`, `typing`, and `utils` can now be lazy-loaded after importing only the top-level `openff.toolkit` module. This change allows for partial loading of the toolkit, which can improve performance by only loading necessary components when they are first accessed. The example shows accessing `Atom` from the `topology` submodule. ```Python - import openff.toolkit.topology + import openff.toolkit atom = openff.toolkit.topology.Atom() ``` -------------------------------- ### Initialize QCArchive Client and List Datasets Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/QCArchive_interface/QCarchive_interface.ipynb Demonstrates how to connect to the public QCArchive instance using `qcportal.PortalClient` and list available datasets to begin interacting with the archive. ```python import qcportal from openff.toolkit import Molecule client = qcportal.PortalClient("https://api.qcarchive.molssi.org:443") print(client.list_datasets_table()) ``` -------------------------------- ### Clone FEP Benchmark Repository and Extract Structures Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/toolkit_showcase/toolkit_showcase.ipynb These shell commands demonstrate how to clone the Merck FEP benchmark repository from GitHub. It then extracts the specific PT2385 ligand from the `ligands.sdf` file and copies the prepared protein structure `5tbm_prepared.pdb` into the current directory, preparing the necessary input files for the simulation. ```shell # Clone the repository git clone https://github.com/MCompChem/fep-benchmark.git # Take the last ligand from the hif2a benchmark tail -n90 fep-benchmark/hif2a/ligands.sdf > PT2385.sdf # Take the prepared protein structure cp fep-benchmark/hif2a/5tbm_prepared.pdb . ``` -------------------------------- ### Import necessary libraries for OpenFF Toolkit and OpenMM simulations Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/virtual_sites/vsite_showcase.ipynb This snippet imports the required Python libraries for setting up and running molecular simulations. It includes `openmm` for the simulation engine, `openff.toolkit` for force field and molecule handling, `openff.interchange` for converting between OpenFF and OpenMM, and `openff.units` for unit handling. ```python import time import numpy import openmm import openmm.app import openmm.unit from openff.interchange import Interchange from openff.units import Quantity, unit from openff.toolkit import ForceField, Molecule, Topology ``` -------------------------------- ### Install GROMACS and LAMMPS via Conda Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/using_smirnoff_in_amber_or_gromacs/export_with_interchange.ipynb Installs GROMACS and LAMMPS simulation engines using Mamba from the conda-forge channel. These engines are required for performing and validating file conversions. ```shell mamba install "gromacs >=2021=nompi*" lammps -c conda-forge ``` -------------------------------- ### Define functions to prepare and run OpenMM simulations Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/virtual_sites/vsite_showcase.ipynb This snippet defines two Python functions: `prepare_simulation` and `run_simulation`. `prepare_simulation` sets up an OpenMM simulation from an `Interchange` object, configuring Langevin dynamics, performing energy minimization, computing virtual site positions, and setting up reporters. `run_simulation` executes the prepared simulation for a specified number of steps and reports the elapsed time. ```python def prepare_simulation(interchange: Interchange) -> openmm.app.Simulation: """Propagate an OpenMM System with Langevin dynamics.""" time_step = 2 * openmm.unit.femtoseconds temperature = 300 * openmm.unit.kelvin friction = 1 / openmm.unit.picosecond integrator = openmm.LangevinIntegrator(temperature, friction, time_step) trj_freq, data_freq = 100, 100 simulation = interchange.to_openmm_simulation(integrator=integrator) # It's important to run energy minimization before computing velocities; otherwise the initial # velocities of virtual sites may be too high as a result of high initial forces, causing a crash # See https://github.com/openmm/openmm/issues/3736#issuecomment-1217250635 simulation.minimizeEnergy() # Since we placed all virtual sites at [0.0, 0.0, 0.0], compute virtual site positions to avoid a crash simulation.context.computeVirtualSites() simulation.context.setVelocitiesToTemperature(temperature) pdb_reporter = openmm.app.PDBReporter("trajectory.pdb", trj_freq) state_data_reporter = openmm.app.StateDataReporter( "data.csv", data_freq, step=True, potentialEnergy=True, temperature=True, density=True, ) simulation.reporters.append(pdb_reporter) simulation.reporters.append(state_data_reporter) return simulation def run_simulation(simulation: openmm.app.Simulation, num_steps: int = 1000): print("Starting simulation") start = time.process_time() simulation.step(num_steps) end = time.process_time() print("Elapsed time %.2f seconds" % (end - start)) print("Done!") ``` -------------------------------- ### Execute Molecular Dynamics Simulation with OpenMM Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/virtual_sites/vsite_showcase.ipynb This snippet prepares an OpenMM Simulation object using a previously defined prepare_simulation function and then runs the simulation for 10,000 steps using a run_simulation function. This demonstrates the final execution phase of the simulation workflow. ```python simulation = prepare_simulation(interchange) run_simulation(simulation, 10000) ``` -------------------------------- ### Initialize Python Environment and Import Libraries Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/toolkit_showcase/toolkit_showcase.ipynb This snippet imports essential libraries from the computational chemistry ecosystem, including MDTraj, NGLview, NumPy, OpenMM, and OpenFF Toolkit components like ForceField, Molecule, and Topology. It also sets the OMP_NUM_THREADS environment variable to optimize performance for OpenMP-enabled operations. ```python # Imports from the comp chem ecosystem import mdtraj import nglview import numpy as np import openmm from openff.units import Quantity, unit from openmm import unit as openmm_unit from pdbfixer import PDBFixer # Imports from the toolkit from openff.toolkit import ForceField, Molecule, Topology %env OMP_NUM_THREADS=2 ``` -------------------------------- ### API Reference: openff.toolkit.topology.Topology.from_json Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/toolkit_showcase/toolkit_showcase.ipynb Documentation for the static method `Topology.from_json()`, which allows loading a `Topology` object from a JSON file. This method is crucial for persisting and restoring molecular system definitions. ```APIDOC openff.toolkit.topology.Topology.from_json( file_path: Union[str, PathLike], _cls: Optional[Type[Topology]] = None ) -> Topology Parameters: file_path (Union[str, PathLike]): The path to the JSON file containing the topology data. _cls (Optional[Type[Topology]]): Internal parameter, typically not used by end-users. Returns: Topology: A new Topology object loaded from the specified JSON file. Description: Loads a Topology object from a JSON file. This method is the counterpart to `Topology.to_json()`. It reconstructs the full molecular system, including molecular identities, conformers, and box vectors, from the serialized JSON data. ``` -------------------------------- ### Solvate Receptor with PDBFixer Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/toolkit_showcase/toolkit_showcase.ipynb This code snippet demonstrates how to solvate a receptor PDB file using `PDBFixer`. It adds water and salt with specified padding and ionic strength, then saves the solvated receptor to a new PDB file and loads it into an OpenFF `Topology` object. ```python fixer = PDBFixer(receptor_path) fixer.addSolvent( padding=1.0 * openmm_unit.nanometer, ionicStrength=0.15 * openmm_unit.molar ) with open("receptor_solvated.pdb", "w") as f: openmm.app.PDBFile.writeFile(fixer.topology, fixer.positions, f) top = Topology.from_pdb("receptor_solvated.pdb") ``` -------------------------------- ### Python: Initialize TIP5P Force Fields Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/virtual_sites/vsite_showcase.ipynb This snippet demonstrates how to load the TIP5P force field definition using both the OpenFF Toolkit (SMIRNOFF format) and OpenMM (XML format), preparing them for subsequent simulations. ```python # The TIP5P force field in SMIRNOFF format, provided by the OpenFF Toolkit openff_force_field = ForceField("tip5p.offxml") # The OpenMM definition of TIP5P openmm_force_field = openmm.app.ForceField("tip5p.xml") ``` -------------------------------- ### Build OpenFF Toolkit documentation from scratch Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/users/developing.md Instructions to activate the 'openff-dev' conda environment, navigate to the 'docs' directory, and execute 'make html' to compile the Sphinx documentation, which will be located in 'docs/_build/html/index.html'. ```shell mamba activate openff-dev cd docs make html ``` -------------------------------- ### Loading Molecules from Files with OpenEye Toolkit Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/SMIRNOFF_simulation/run_simulation.ipynb Demonstrates an alternative approach to creating `Molecule` objects by loading them from `.mol2` files, contingent on the availability of the OpenEye Toolkit. This method allows for importing detailed molecular information directly from file-based formats. ```Python from openff.toolkit.utils.toolkits import OpenEyeToolkitWrapper if OpenEyeToolkitWrapper.is_available(): ethanol = Molecule.from_file(get_data_file_path("molecules/ethanol.mol2")) cyclohexane = Molecule.from_file(get_data_file_path("molecules/cyclohexane.mol2")) ``` -------------------------------- ### Analyze the parameters assigned to groups of molecules Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/inspect_assigned_parameters/inspect_assigned_parameters.ipynb Here we analyze which parameters are applied to a group of molecules. This example uses `get_molecule_parameterIDs`, a simple utility function similar to `label_molecules`, but intended for use on large datasets. `get_molecule_parameterIDs` processes a list of molecules using a specified `ForceField` and returns the parameters that would be assigned to each molecule, grouping the results both by molecule and by parameter. This example may be useful when adding new parameters, to ensure that they are applied to molecules in a given data set. This example also highlights the difference between "specific" and "generic" parameters. In the SMIRNOFF format, more than one SMIRKS-based parameter may match a motif in a molecule. Therefore, some parameters have precedence over others. Parameters which are "generic" are listed near the top of a parameter section, while more "specific" parameters occur near the end of the section. During parameter assignment, the furthest-down parameter that matches a motif in the molecule is assigned. During actual parameter assignment, if the toolkit is unable to assign SMIRKS-based parameters to any part of a molecule, an `UnassignedValenceParameterException` will be raised. ```python from openff.toolkit import ForceField, Molecule from openff.toolkit.utils import get_molecule_parameterIDs # The set of molecules that we want to parametrize in SMILES format. molecule_smiles = [ "[H][C@@]1([C@](OC1([H])[H])([H])O[H])O[H]", "[H]C1(C(C(C1([H])O[H])([H])[H])([H])O[H])[H]", "[H]C1(C(C(O1)([H])[H])([H])O[H])[H]", "[H][C@@]1(C([C@@](OC1([H])[H])([H])O[H])([H])[H])O[H]", "[H][C@@]1(C(O[C@](O1)([H])O[H])([H])[H])O[H]", "[H][C@]1(C([C@](O1)([H])O[H])([H])[H])O[H]", "[H][C@]1(C(OC(O1)([H])[H])([H])[H])O[H]", "[H][C@@]1([C@](C(C(C1([H])[H])([H])[H])([H])[H])([H])O[H])O[H]", "[H][C@]1([C@@](C(OC(C(C1([H])[H])([H])[H])([H])[H])([H])[H])([H])O[H])O[H]", "[H][C@@]1([C@](OC(C(C1([H])[H])([H])[H])([H])[H])([H])O[H])O[H]" ] # Create the Molecule objects to parametrize. mols = [Molecule.from_smiles(smiles) for smiles in molecule_smiles] # Let's label using the original "Sage" force field forcefield = ForceField("openff-2.1.0.offxml") # This utility function creates dictionaries describing parameter assignment, # grouped both by molecule and by parameter parameters_by_molecule, parameters_by_ID = get_molecule_parameterIDs(mols, forcefield) print("Molecules with parameter IDs:") # parameters_by_ID is a dictionary where keys are parameter IDs and values # are molecules in which each parameter ID occurs. pids_ordered = sorted(list(parameters_by_ID.keys())) for pid in pids_ordered: print(pid) for ids in parameters_by_ID[pid]: print("\t", ids) ``` -------------------------------- ### Visualize a Molecule Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/toolkit_showcase/toolkit_showcase.ipynb This snippet demonstrates how to visualize a `ligand` molecule using the `visualize` method, optionally hiding all hydrogens. ```python ligand.visualize(show_all_hydrogens=False) ``` -------------------------------- ### Serve and auto-rebuild OpenFF Toolkit documentation locally Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/users/developing.md Command to activate the 'openff-dev' environment and use 'sphinx-autobuild' to host the documentation on a local HTTP server (http://localhost:8000), automatically rebuilding and refreshing the browser upon source file changes. ```shell mamba activate openff-dev sphinx-autobuild docs docs/_build/html --watch openff ``` -------------------------------- ### Add documentation dependencies to OpenFF Toolkit environment Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/users/developing.md Commands to update an existing 'openff-dev' conda environment by adding the necessary documentation requirements from 'docs/environment.yml' and installing 'sphinx-autobuild' for documentation generation. ```shell mamba env update --name openff-dev --file docs/environment.yml mamba install --name openff-dev -c conda-forge sphinx-autobuild ``` -------------------------------- ### Initialize NGLview Visualization Widget Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/toolkit_showcase/toolkit_showcase.ipynb This Python snippet demonstrates how to initialize an NGLview visualization widget from a `Topology` object using `top.visualize()`. The resulting `view` object can be further modified to customize representations or interact with the visualization, such as clearing default representations with `view.clear()` or saving images with `view.download_image()`. ```python view = top.visualize() # can make further modifications to this representation object, or just look at it view ``` -------------------------------- ### Configure NGLView for Jupyter Lab Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/visualization/visualization.ipynb Commands to install necessary Jupyter Lab extensions (`nglview-js-widgets` and `@jupyter-widgets/jupyterlab-manager`) for `nglview` compatibility with Jupyter Lab. These extensions are crucial for NGLView visualizations to render properly in Jupyter Lab environments. ```bash jupyter labextension install nglview-js-widgets jupyter-labextension install @jupyter-widgets/jupyterlab-manager ``` -------------------------------- ### Load OpenFF Force Field with Virtual Sites Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/virtual_sites/vsite_showcase.ipynb This snippet initializes a ForceField object, loading a standard OpenFF force field along with an additional OFFXML file that defines virtual sites. This is the first step in preparing a system for parametrization. ```python force_field = ForceField("openff-2.2.0.offxml", vsite_offxml) ``` -------------------------------- ### APIDOC: IndexedParameterAttribute Class Definition Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/users/developing.md A `ParameterAttribute` with a sequence of values, indexed by an integer. Its name appears with a numerical suffix in OFFXML files (e.g., `k1`, `k2`). Indexing starts at 1 and must be contiguous. ```APIDOC IndexedParameterAttribute: Inherits: ParameterAttribute Description: A ParameterAttribute with a sequence of values, indexed by an integer. OFFXML Naming: Appears with a numerical integer suffix (e.g., k1, k2, k3). Indexing Rules: Requires indexing to start at 1 and subsequent values to be contiguous (no skipping numbers). No enforced upper limit. Example Usage: Used for dihedral torsion parameters like k, periodicity, and phase, which are implemented as IndexedParameterAttribute. ``` -------------------------------- ### OpenFF Interchange: Parametrized Topology for simulation Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/users/concepts.md Defines the OpenFF Interchange class, a Topology that has been parametrized by a ForceField. It contains all information needed to calculate energy or start a simulation, and provides methods for export to MD simulation engines. ```APIDOC OpenFF Interchange: Description: A Topology that has been parametrized by a ForceField. Purpose: Contains all the information needed to calculate an energy or start a simulation. Capabilities: Provides methods to export information to MD simulation engines. ``` -------------------------------- ### Python: Build Water Molecule Conformation and Lattice Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/virtual_sites/vsite_showcase.ipynb This snippet demonstrates how to programmatically add a conformer to a water molecule reference and then build a lattice of water molecules by duplicating the reference and adding spatial offsets. It uses `Quantity` for unit handling and `Molecule` objects. ```python water_reference.add_conformer( bond_length * Quantity( [ [0.0, 0.0, 0.0], [-sin(theta / 2), cos(theta / 2), 0.0], [sin(theta / 2), cos(theta / 2), 0.0], ] ) ) for i, xyz in enumerate(XYZ): water_box[i] = Molecule(water_reference) water_box[i].conformers[0] = water_box[i].conformers[0] + xyz * unit.angstrom return water_box ``` -------------------------------- ### Get PDB Residue Information with RDKit Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/users/molecule_conversion.md Demonstrates how to retrieve specific PDB residue information (insertion code, chain ID) from an RDKit atom's residue data. The 'rda' object is assumed to be an RDKit atom. ```Python rda.GetPDBResidueInfo().GetInsertionCode() ``` ```Python rda.GetPDBResidueInfo().GetChainId() ``` -------------------------------- ### Parametrize System with OpenFF Toolkit create_interchange Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/toolkit_showcase/toolkit_showcase.ipynb This snippet demonstrates how to create an `Interchange` object using the OpenFF Toolkit. It combines a `ForceField` (e.g., `sage_ff14sb`) with a `Topology` (`top`) to produce a fully parametrized molecular mechanics system. The `Interchange` handles partial charge computation and introduces virtual sites as required by the force field. ```python interchange = sage_ff14sb.create_interchange(top) ``` -------------------------------- ### OpenMM Object Creation from Interchange Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/virtual_sites/vsite_showcase.ipynb This section lists the methods available on an Interchange object for generating standard OpenMM objects. It specifies how to obtain an openmm.System, openmm.app.Topology, and openmm.app.Simulation from an Interchange instance. ```APIDOC openmm.System: Interchange.to_openmm() openmm.app.Topology: Interchange.to_openmm_topology() openmm.app.Simulation: Interchange.to_openmm_simulation() ``` -------------------------------- ### Calculate OpenFF-OpenMM Coordinate and Energy Differences Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/virtual_sites/vsite_showcase.ipynb This snippet calculates the normalized coordinate and energy differences between OpenFF and OpenMM simulation outputs. It uses `numpy.linalg.norm` for coordinate differences and absolute difference for energies, scaling both by the number of duplicates to get a per-molecule mean. ```python coordinate_difference = Quantity( numpy.linalg.norm(off_crds - omm_crds[reorder(numpy.prod(num_duplicates)), :]), unit.angstrom, ) coordinate_difference /= numpy.prod(num_duplicates) # Compute the mean energy difference per molecule energy_difference = abs(off_ene - omm_ene) / numpy.prod(num_duplicates) ``` -------------------------------- ### Visualize Ligand Structure with NGLview Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/toolkit_showcase/toolkit_showcase.ipynb This snippet uses the NGLview widget to display the 3D structure of the ligand from the specified path. The visualization is interactive, allowing users to rotate, pan, zoom, and inspect atom details, facilitating quick visual inspection of the molecular structure. ```python view = nglview.show_structure_file(ligand_path) view ``` -------------------------------- ### Execute CLI Utility for Conformer Energies Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/conformer_energies/README.md This command demonstrates how to run the `conformer_energies.py` script from the command line, providing an SDF file as input to compute conformer energies using the 'Sage' (openff-2.1.0) SMIRNOFF force field. ```Shell python conformer_energies.py -f ruxolitinib_conformers.sdf ``` -------------------------------- ### Get tagged SMARTS connectivity using RDKit or OpenEye toolkits Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/releasehistory.md Introduces `get_tagged_smarts_connectivity` methods to both `RDKitToolkitWrapper` and `OpenEyeToolkitWrapper`. These methods enable the use of either toolkit for validating SMIRKS or tagged SMARTS patterns, providing flexibility in toolkit choice for connectivity checks. ```APIDOC RDKitToolkitWrapper.get_tagged_smarts_connectivity( smarts_pattern: str ) -> list[tuple[int, int]] OpenEyeToolkitWrapper.get_tagged_smarts_connectivity( smarts_pattern: str ) -> list[tuple[int, int]] ``` -------------------------------- ### Get OpenEye Residue Information (Defined Fields) Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/users/molecule_conversion.md Demonstrates how to retrieve specific residue properties (name, number, insertion code, chain ID) from an OpenEye atom's residue data. 'atom' is an OpenEye atom object, and 'oechem' is the OpenEye chemistry toolkit module. ```Python oechem.OEAtomGetResidue(atom).GetName() ``` ```Python oechem.OEAtomGetResidue(atom).GetResidueNumber() ``` ```Python oechem.OEAtomGetResidue(atom).GetInsertCode() ``` ```Python oechem.OEAtomGetResidue(atom).GetChainID() ``` -------------------------------- ### Minimize System Energy with OpenMM and OpenFF Toolkit Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/toolkit_showcase/toolkit_showcase.ipynb This snippet demonstrates how to minimize the potential energy of a molecular system using the OpenFF Toolkit and OpenMM. It includes a helper function to describe the system's state (energy and maximum force) before and after minimization, addressing issues like clashes or force field disagreements. ```python def describe_state(state: openmm.State, name: str = "State"): max_force = max(np.sqrt(v.x**2 + v.y**2 + v.z**2) for v in state.getForces()) print( f"{name} has energy {round(state.getPotentialEnergy()._value, 2)} kJ/mol " f"with maximum force {round(max_force, 2)} kJ/(mol nm)" ) describe_state( simulation.context.getState( getEnergy=True, getForces=True, ), "Original state", ) simulation.minimizeEnergy() describe_state( simulation.context.getState(getEnergy=True, getForces=True), "Minimized state", ) ``` -------------------------------- ### OpenFF Toolkit Conda and Pip Package Dependencies Source: https://github.com/openforcefield/openff-toolkit/blob/main/openff/toolkit/data/reference_energies/reference_after_1007.json.txt This snippet provides a complete list of Python packages and their exact versions required to set up the OpenFF Toolkit development environment. It includes packages managed by conda and those installed via pip, ensuring all necessary libraries are present for development and testing. ```YAML - uncertainties=3.1.5=pyhd8ed1ab_0 - urllib3=1.26.3=pyhd8ed1ab_0 - wcwidth=0.2.5=pyh9f0ad1d_2 - webencodings=0.5.1=py_1 - wheel=0.36.2=pyhd3deb0d_0 - widgetsnbextension=3.5.1=py38h50d1736_4 - xmltodict=0.12.0=py_0 - xorg-kbproto=1.0.7=h35c211d_1002 - xorg-libice=1.0.10=h01d97ff_0 - xorg-libsm=1.2.3=h01d97ff_1000 - xorg-libx11=1.6.12=haf1e3a3_0 - xorg-libxau=1.0.9=h35c211d_0 - xorg-libxdmcp=1.1.3=h35c211d_0 - xorg-libxext=1.3.4=h01d97ff_0 - xorg-libxt=1.2.1=h35c211d_0 - xorg-xextproto=7.3.0=h35c211d_1002 - xorg-xproto=7.0.31=h35c211d_1007 - xz=5.2.5=haf1e3a3_1 - yaml=0.2.5=haf1e3a3_0 - yank=0.25.2=pyhd8ed1ab_0 - zeromq=4.3.4=h1c7c35f_0 - zict=2.0.0=py_0 - zipp=3.4.0=py_0 - zlib=1.2.11=h7795811_1010 - zstd=1.4.8=hf387650_1 - pip: - amberlite==16.0 - ambertools==20.15 - m2r2==0.2.7 - mmpbsa-py==16.0 - packmol-memgen==1.1.0rc0 - pdb4amber==1.7.dev0 - pytraj==2.0.5 - sander==16.0 - z3-solver==4.8.10.0 ``` -------------------------------- ### Molecule Virtual Site Addition Methods with New Kwargs Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/releasehistory.md Documentation for `Molecule` methods that add virtual sites, now supporting `replace` and `all_permutations` keyword arguments for more flexible virtual site creation and manipulation. ```APIDOC Molecule: add_bond_charge_virtual_site(replace: bool = False, all_permutations: bool = False) add_monovalent_lone_pair_virtual_site(replace: bool = False, all_permutations: bool = False) add_divalent_lone_pair_virtual_site(replace: bool = False, all_permutations: bool = False) add_trivalent_lone_pair_virtual_site(replace: bool = False, all_permutations: bool = False) ``` -------------------------------- ### Retrieve BRD4 Protein and Ligand Files from GitHub Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/using_smirnoff_with_amber_protein_forcefield/BRD4_inhibitor_benchmark.ipynb This Python snippet uses the `requests` library to download protein (PDB) and ligand (PDB, SDF) files for the BRD4 system from the MobleyLab benchmarksets GitHub repository. It iterates through a dictionary of filenames and URLs, saving each file locally. ```python # Retrieve protein and ligand files for BRD4 and a docked inhibitor from the benchmark systems GitHub repository # https://github.com/MobleyLab/benchmarksets import requests repo_url = ( "https://raw.githubusercontent.com/MobleyLab/benchmarksets/master/input_files/" ) sources = { "receptor.pdb": repo_url + "BRD4/pdb/BRD4.pdb", "ligand.pdb": repo_url + "BRD4/pdb/ligand-1.pdb", "ligand.sdf": repo_url + "BRD4/sdf/ligand-1.sdf", } for filename, url in sources.items(): r = requests.get(url) open(filename, "w").write(r.text) ``` -------------------------------- ### Configure OpenMM Simulation and Reporters in Python Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/SMIRNOFF_simulation/run_simulation.ipynb This snippet demonstrates how to initialize an OpenMM simulation from an `interchange` object, set initial velocities to a given temperature, and configure `PDBReporter` and `StateDataReporter` to save trajectory and thermodynamic data respectively. It appends these reporters to the simulation object for output generation. ```python # Set up an OpenMM simulation. simulation = interchange.to_openmm_simulation(integrator) # Randomize the velocities from a Boltzmann distribution at a given temperature. simulation.context.setVelocitiesToTemperature(temperature) # Configure the information in the output files. pdb_reporter = openmm.app.PDBReporter("trajectory.pdb", trj_freq) state_data_reporter = openmm.app.StateDataReporter( "data.csv", data_freq, step=True, potentialEnergy=True, temperature=True, density=True, ) simulation.reporters.append(pdb_reporter) simulation.reporters.append(state_data_reporter) ``` -------------------------------- ### Import necessary OpenFF Toolkit and OpenMM modules Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/conformer_energies/conformer_energies.ipynb Imports `openmm`, `openff.interchange`, `openff.units.openmm`, `rdkit.Chem`, `openff.toolkit`, and `openff.toolkit.utils` for molecular manipulation, force field application, and energy calculations. ```python import openmm from openff.interchange import Interchange from openff.units.openmm import from_openmm from rdkit.Chem import rdMolAlign from openff.toolkit import ForceField, Molecule from openff.toolkit.utils import get_data_file_path ``` -------------------------------- ### Import OpenFF Toolkit Modules Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/visualization/visualization.ipynb Imports necessary classes `Molecule` and `Topology` from `openff.toolkit` and `get_data_file_path` from `openff.toolkit.utils` for general use within the OpenFF Toolkit. ```python from openff.toolkit import Molecule, Topology from openff.toolkit.utils import get_data_file_path ``` -------------------------------- ### Retrieve Optimization Dataset from QCArchive Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/QCArchive_interface/QCarchive_interface.ipynb Shows how to fetch a specific optimization dataset, 'Kinase Inhibitors: WBO Distributions', from the connected QCArchive client for further analysis. ```python dataset = client.get_dataset( dataset_type="optimization", dataset_name="Kinase Inhibitors: WBO Distributions", ) ``` -------------------------------- ### Initialize ToolkitRegistry with specific wrappers Source: https://github.com/openforcefield/openff-toolkit/blob/main/docs/api/toolkits.md Demonstrates how to create a ToolkitRegistry instance by providing a list of ToolkitWrapper classes, such as OpenEyeToolkitWrapper, RDKitToolkitWrapper, and AmberToolsToolkitWrapper, ordered by precedence. ```python from openff.toolkit import ( ToolkitRegistry, OpenEyeToolkitWrapper, RDKitToolkitWrapper, AmberToolsToolkitWrapper, ) toolkit_registry = ToolkitRegistry( [ OpenEyeToolkitWrapper, RDKitToolkitWrapper, AmberToolsToolkitWrapper, ] ) ``` -------------------------------- ### Import Core Classes from OpenFF Toolkit Source: https://github.com/openforcefield/openff-toolkit/blob/main/examples/using_smirnoff_with_amber_protein_forcefield/BRD4_inhibitor_benchmark.ipynb This snippet imports essential classes from the `openff.toolkit` library, including `ForceField`, `Molecule`, `Quantity`, and `Topology`. These classes are fundamental for defining molecular structures, applying force fields, and managing system properties within the OpenFF ecosystem. ```python from openff.toolkit import ForceField, Molecule, Quantity, Topology ```