### Install IPSuite from GitHub using Poetry Source: https://github.com/zincware/ipsuite/blob/main/docs/source/_get_started/quickstart.rst Clones the latest IPSuite version from GitHub and installs dependencies using Poetry. This method is an alternative to using pip for installation. ```bash git clone https://github.com/zincware/IPSuite.git cd IPSuite poetry install ``` -------------------------------- ### Initialize Git and DVC for an IPS Project Source: https://github.com/zincware/ipsuite/blob/main/docs/source/_get_started/quickstart.rst Initializes a new project directory with Git and DVC, which are necessary for IPSuite to function. This sets up version control and data management for the project. ```bash mkdir project cd project git init dvc init ``` -------------------------------- ### Install xtb-python and packmol using Conda Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/06_Bootstrapping_Datasets.ipynb Installs the necessary libraries 'xtb-python' and 'packmol' from the conda-forge channel. These are prerequisites for setting up initial configurations and performing calculations. ```bash conda install -c conda-forge xtb-python conda install -c conda-forge packmol ``` -------------------------------- ### Node Example: Molecular Dynamics Simulation Source: https://github.com/zincware/ipsuite/blob/main/AGENTS.md An example demonstrating how to use an IPSuite Node to run a molecular dynamics simulation, starting from generating conformers and then executing the simulation. Assumes `project` and `ips` objects are available. ```python with project: methanol_conformers = ips.Smiles2Conformers(smiles="CO", numConfs=5) project.repro() frames = methanol_conformers.frames print(f"Generated {len(frames)} conformers.") ``` -------------------------------- ### Initialize Project and Dependencies (Python) Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/01_Data_Loading_and_Selection.ipynb Imports necessary libraries from pathlib, ase, and zntrack for project management and molecular dynamics simulations. It also initializes a temporary directory for working files. This setup is crucial for subsequent data generation and manipulation within the IPS framework. ```python from pathlib import Path from ase import units from ase.calculators.emt import EMT from ase.io.trajectory import TrajectoryWriter from ase.lattice.cubic import FaceCenteredCubic from ase.md.langevin import Langevin from ase.md.velocitydistribution import MaxwellBoltzmannDistribution from ase.visualize import view from zntrack.utils import cwd_temp_dir import ipsuite as ips temp_dir = cwd_temp_dir() ``` -------------------------------- ### Visualize Structures with ZnDraw Source: https://github.com/zincware/ipsuite/blob/main/docs/source/_get_started/quickstart.rst Launches the ZnDraw application to visualize molecular structures generated by IPSuite nodes. This command specifically visualizes the single water molecule created by the Smiles2Atoms node. ```bash zndraw nodes/Smiles2Atoms/structures.h5 ``` -------------------------------- ### Install Dependencies, Lint, and Test Source: https://github.com/zincware/ipsuite/blob/main/AGENTS.md Essential commands to run in sequence before committing code to ensure dependencies are installed, code is formatted and linted, and the test suite passes. These checks are enforced by CI. ```bash uv sync uvx pre-commit run --all-files uv run pytest ``` -------------------------------- ### Initialize Project Environment with Python Imports Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/06_Bootstrapping_Datasets.ipynb Imports essential Python libraries for plotting, workflow management (znflow), temporary directory handling, and the IPSuite. It also sets up a temporary directory for operations. ```python import matplotlib.pyplot as plt import znflow from zntrack.utils import cwd_temp_dir import ipsuite as ips temp_dir = cwd_temp_dir() ``` -------------------------------- ### Docstring Example for IPSuite Node Source: https://github.com/zincware/ipsuite/blob/main/CLAUDE.md Demonstrates the expected format for Node docstrings in IPSuite, adhering to the numpy style. It includes an example showing how to use provided objects like `project` and `ips` to create and interact with a Node, illustrating expected output. ```python Examples -------- >>> with project: ... methanol_conformers = ips.Smiles2Conformers(smiles="CO", numConfs=5) >>> project.repro() >>> frames = methanol_conformers.frames >>> print(f"Generated {len(frames)} conformers.") Generated 5 conformers. ``` -------------------------------- ### Install IPSuite Package Source: https://github.com/zincware/ipsuite/blob/main/README.md Installs the IPSuite package using pip. This is a barebones installation and may require manual installation of third-party ML packages to avoid import errors. ```shell pip install ipsuite ``` -------------------------------- ### Generate Water Molecules using IPSuite and Packmol Source: https://github.com/zincware/ipsuite/blob/main/docs/source/_get_started/quickstart.rst Generates a specified number of water molecules inside a box at a given density using IPSuite's Project, Smiles2Atoms, and Packmol nodes. The workflow is saved to DVC configuration files. ```python import ipsuite as ips with ips.Project() as project: # Generate a single water molecule mol = ips.Smiles2Atoms(smiles="O") # Duplicate water molecules packmol = ips.Packmol( data=[mol.frames], count=[10], density=876 ) project.build() ``` -------------------------------- ### Bootstrap Dataset Generation with IPSuite Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/06_Bootstrapping_Datasets.ipynb Sets up and runs a data bootstrapping process using IPSuite. This involves creating initial atomic configurations, optimizing them with xTB, and generating diverse datasets through rattling, rotation, and translation of molecules, followed by volume scanning. The final dataset is combined and analyzed using energy and forces histograms. ```python mapping = ips.geometry.BarycenterMapping() with ips.Project() as project: water = ips.Smiles2Atoms(smiles="O") packmol = ips.Packmol(data=[water.atoms], count=[10], density=997) opt_calc = ips.xTBSinglePoint(data=packmol, method="gfn1-xtb", name="opt_calc") geopt = ips.ASEGeoOpt( model=opt_calc, data=packmol.atoms, optimizer="BFGS", run_kwargs={"fmax": 1.0}, ) n_configs = 5 rattle = ips.bootstrap.RattleAtoms( data=geopt.atoms, data_id=-1, n_configurations=n_configs, maximum=0.08, # Ang max atomic displacement include_original=True, ) rotate = ips.bootstrap.RotateMolecules( data=geopt.atoms, data_id=-1, n_configurations=n_configs, maximum=15, # deg max rotation include_original=False, ) translate = ips.bootstrap.TranslateMolecules( data=geopt.atoms, data_id=-1, n_configurations=n_configs, maximum=0.3, # Ang max molecular displacement include_original=False, ) bootstrap_configurations = rattle.atoms + rotate.atoms + translate.atoms labeling_calc = ips.xTBSinglePoint( data=bootstrap_configurations, method="gfn1-xtb", name="label_calc" ) volume_scan = ips.BoxScale( data=rattle.atoms, data_id=0, model=labeling_calc, mapping=mapping, start=0.8, stop=1.5, num=5, ) bootstrap_dataset = znflow.combine([labeling_calc, volume_scan], attribute="atoms") energy_hist = ips.EnergyHistogram(data=bootstrap_dataset, bins=10) forces_hist = ips.ForcesHistogram(data=bootstrap_dataset, bins=10) project.repro() ``` -------------------------------- ### IPS Welcome Message and Progress Log Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/06_Bootstrapping_Datasets.ipynb This snippet shows a welcome message from the Interatomic Potential Suite (IPS) along with progress indicators (e.g., percentage completion bars) and debug messages. It's typical output during the initialization or execution of IPS tasks. ```text 2023-05-30 16:18:23,396 (DEBUG): Welcome to IPS - the Interatomic Potential Suite! ``` ``` Output: 100%|██████████| 1/1 [00:00<00:00, 10.92it/s] ``` ``` Output: 2023-05-30 16:18:24,687 (DEBUG): Welcome to IPS - the Interatomic Potential Suite! Step Time Energy fmax BFGS: 0 16:18:24 -1452.227673 560.1183 BFGS: 1 16:18:25 -1525.179018 73.0175 BFGS: 2 16:18:25 -1541.432084 26.5437 BFGS: 3 16:18:25 -1548.847866 20.9261 BFGS: 4 16:18:25 -1553.041573 21.0507 BFGS: 5 16:18:25 -1557.985665 14.9412 BFGS: 6 16:18:25 -1560.632213 8.3526 BFGS: 7 16:18:25 -1562.409822 5.2405 BFGS: 8 16:18:25 -1563.889836 4.6672 BFGS: 9 16:18:26 -1565.320047 13.2885 BFGS: 10 16:18:26 -1566.448285 3.4639 BFGS: 11 16:18:26 -1567.953756 4.4025 BFGS: 12 16:18:26 -1568.948496 7.1006 BFGS: 13 16:18:26 -1569.550374 4.1206 BFGS: 14 16:18:26 -1570.227879 2.1917 BFGS: 15 16:18:26 -1570.532967 7.2313 BFGS: 16 16:18:26 -1570.847957 2.6559 BFGS: 17 16:18:27 -1571.138681 1.4818 BFGS: 18 16:18:27 -1571.662669 2.2882 BFGS: 19 16:18:27 -1571.800839 1.6854 BFGS: 20 16:18:27 -1571.956670 0.8907 2023-05-30 16:18:28,493 (DEBUG): Welcome to IPS - the Interatomic Potential Suite! 2023-05-30 16:18:29,693 (DEBUG): Welcome to IPS - the Interatomic Potential Suite! 2023-05-30 16:18:30,954 (DEBUG): Welcome to IPS - the Interatomic Potential Suite! 2023-05-30 16:18:31,096 (WARNING): Setting maximum to 2 Pi. 2023-05-30 16:18:32,202 (DEBUG): Welcome to IPS - the Interatomic Potential Suite! 2023-05-30 16:18:33,349 (DEBUG): Welcome to IPS - the Interatomic Potential Suite! ``` ``` Output: 100%|██████████| 16/16 [00:01<00:00, 8.80it/s] ``` ``` Output: 2023-05-30 16:18:36,564 (DEBUG): Welcome to IPS - the Interatomic Potential Suite! ``` ``` Output: Could not load field atoms for node BoxScale_mapping. 100%|███████████████████████████████████| 5/5 [00:00<00:00, 8.29it/s] ``` ``` Output: 2023-05-30 16:18:38,818 (DEBUG): Welcome to IPS - the Interatomic Potential Suite! 2023-05-30 16:18:40,299 (DEBUG): Welcome to IPS - the Interatomic Potential Suite! ``` ``` -------------------------------- ### Visualizing DVC Workflow Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/01_Data_Loading_and_Selection.ipynb Displays the Directed Acyclic Graph (DAG) of the DVC (Data Version Control) workflow. This command helps visualize the dependencies between different stages and data nodes in the project, aiding in understanding the data processing pipeline. ```bash !dvc dag ``` -------------------------------- ### Run Molecular Dynamics Simulation (Python) Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/01_Data_Loading_and_Selection.ipynb Configures and runs a short molecular dynamics simulation using the Langevin thermostat. It sets up the simulation parameters like timestep, steps, temperature, assigns an EMT calculator, and saves the trajectory to a file. This generates the sample atomistic data. ```python timestep = 5 * units.fs steps = 100 temperature = 800 traj_path = Path(temp_dir.name) / "trajectory.traj" atoms.calc = EMT() MaxwellBoltzmannDistribution(atoms, temperature_K=temperature) dyn = Langevin(atoms, timestep, temperature_K=temperature, friction=0.002) writer = TrajectoryWriter(traj_path, "w", atoms=atoms) dyn.attach(writer, interval=1) dyn.run(steps) ``` -------------------------------- ### Packmol Simulation Output and Success Message Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/06_Bootstrapping_Datasets.ipynb This snippet displays the output of a Packmol simulation, indicating the packing process, objective function value, constraint violations, and a success message with final results. It also provides citation information for the Packmol tool. ```text Current structure written to file: mixture.xyz -------------------------------------------------------------------------------- Packing solved for molecules of type 1 Objective function value: 1.5567789525860229E-005 Maximum violation of target distance: 0.0000000000000000 Max. constraint violation: 1.5567789525860229E-005 -------------------------------------------------------------------------------- ################################################################################ Packing all molecules together ################################################################################ Initial approximation is a solution. Nothing to do. Solution written to file: mixture.xyz ################################################################################ Success! Final objective function value: .31847E-01 Maximum violation of target distance: 0.000000 Maximum violation of the constraints: .15568E-04 -------------------------------------------------------------------------------- Please cite this work if Packmol was useful: L. Martinez, R. Andrade, E. G. Birgin, J. M. Martinez, PACKMOL: A package for building initial configurations for molecular dynamics simulations. Journal of Computational Chemistry, 30:2157-2164,2009. ################################################################################ Running time: 5.92000026E-04 seconds. -------------------------------------------------------------------------------- ``` -------------------------------- ### Temporal Data Splitting with IPS Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/01_Data_Loading_and_Selection.ipynb Implements a temporally aware data splitting strategy using IPS to ensure that validation and training splits do not temporally overlap with the test set. It uses `SplitSelection` for initial partitioning and `UniformTemporalSelection` and `UniformEnergeticSelection` for final data selection. ```python with ips.Project() as project: trajectory = ips.AddData(file=traj_path, name="trajectory") test_split = ips.SplitSelection(data=trajectory, split=0.1, name="test_split") val_split = ips.SplitSelection( data=test_split.excluded_atoms, split=0.17, name="val_split" ) # 0.15 / 0.9 * 1.0 \approx 0.17 train_split = val_split.excluded_atoms # 0.8 of the total data test_data = ips.UniformTemporalSelection( data=test_split, n_configurations=10, name="test_data" ) val_data = ips.UniformTemporalSelection( data=val_split, n_configurations=15, name="val_data" ) train_data = ips.UniformEnergeticSelection( data=train_split, n_configurations=80, name="train_data" ) project.repro() ``` -------------------------------- ### Load and Visualize Trajectory Data (Python) Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/01_Data_Loading_and_Selection.ipynb Demonstrates how to load the trajectory data processed by IPS and visualize it using ASE's `view` function. The loaded data is a list of ASE Atoms objects, suitable for further analysis or visualization. ```python trajectory.load() # requires the project to have been run view(trajectory) ``` -------------------------------- ### Load Trajectory Data with IPS (Python) Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/01_Data_Loading_and_Selection.ipynb Loads the previously generated trajectory data into the IPS project using the `AddData` Node. It then calls `project.repro()` to execute the data loading process and track the file with DVC. This makes the trajectory data accessible within the IPS environment. ```python with ips.Project() as project: trajectory = ips.AddData(file=traj_path, name="trajectory") project.repro() ``` -------------------------------- ### Random Data Splitting with IPS Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/01_Data_Loading_and_Selection.ipynb Demonstrates random partitioning of data into training, validation, and test sets using IPS. It utilizes `RandomSelection` nodes to iteratively exclude configurations for each split. This method is simple but may lead to temporal overlap between splits for sequential data. ```python with project: random_test_selection = ips.RandomSelection( data=trajectory, n_configurations=10, name="random_test_selection" ) random_val_selection = ips.RandomSelection( data=random_test_selection.excluded_atoms, n_configurations=15, name="random_val_selection", ) random_train_selection = ips.RandomSelection( data=random_val_selection.excluded_atoms, n_configurations=75, name="random_train_selection", ) project.repro() ``` -------------------------------- ### Cleanup Temporary Directory in Python Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/06_Bootstrapping_Datasets.ipynb This Python snippet demonstrates how to clean up a temporary directory. It's typically used after data generation or processing to free up disk space. Ensure that the `temp_dir` object is properly initialized before calling this method. ```python temp_dir.cleanup() ``` -------------------------------- ### Configure PLUMED Metadynamics Input Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/07_metadyanmics_data_generating.ipynb Defines the PLUMED input file content for metadynamics. It specifies collective variables (torsion angles phi and psi), the metadynamics bias parameters (height, sigma, pace), and output files (HILLS, COLVAR). This setup is crucial for guiding the simulation. ```python thermostat = ips.LangevinThermostat( time_step=0.5, temperature=300, friction=0.01, ) FILE = """ FLUSH STRIDE=10000 phi: TORSION ATOMS=8,7,5,3 psi: TORSION ATOMS=7,5,3,2 restraint: METAD ARG=phi,psi SIGMA=0.35,0.35 HEIGHT=1.2 BIASFACTOR=8 \ PACE=400 FILE=HILLS GRID_MIN=-pi,-pi GRID_MAX=pi,pi PRINT ARG=phi,psi FILE=COLVAR STRIDE=1 """ with Path("plumed.dat").open("w") as f: f.write(FILE) ``` -------------------------------- ### Create and Optimize Alanine Dipeptide System Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/07_metadyanmics_data_generating.ipynb Constructs a system containing an alanine dipeptide molecule using SMILES notation and optimizes its geometry using the specified model and optimizer. The output 'geoopt.frames' serves as the starting point for further simulations. ```python with project.group("System_Creation"): mol = ips.Smiles2Atoms(smiles="CNC(=O)[C@H](C)NC(C)=O") geoopt = ips.ASEGeoOpt( data=mol.frames, model=mace, optimizer="FIRE", run_kwargs={"fmax": 0.05} ) ``` -------------------------------- ### Fix Docker Permission Issues Source: https://github.com/zincware/ipsuite/blob/main/README.md Provides shell commands to resolve file permission issues that may arise when switching between Docker containers and a host system's DVC installation. It includes methods to change file ownership both from the host and within the Docker container. ```shell echo $(id -u):$(id -g) docker run -it -v "$(pwd):/app" pythonf/ipsuite /bin/bash addgroup --gid $GROUP_ID user adduser --disabled-password --gecos '' --uid $USER_ID --gid $GROUP_ID user chown user:user -R . ``` -------------------------------- ### Python: Load and Plot Energy Histogram using IPS Data Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/06_Bootstrapping_Datasets.ipynb This Python snippet demonstrates how to load histogram data from an IPS energy histogram object and then visualize it using matplotlib. It assumes the `energy_hist` object has been previously defined and loaded, and it displays a log-scaled histogram of energy counts. ```python energy_hist.load() forces_hist.load() ``` ```python counts, bin_edges = energy_hist.get_hist() plt.stairs(counts, bin_edges, fill=True) plt.xlabel(energy_hist.xlabel) plt.ylabel(energy_hist.ylabel) plt.yscale("log") plt.show() ``` -------------------------------- ### Python: Load and Plot Forces Histogram using IPS Data Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/06_Bootstrapping_Datasets.ipynb This Python snippet shows how to load histogram data for forces from an IPS object and plot it using matplotlib. Similar to the energy histogram, it assumes a `forces_hist` object is available and displays a log-scaled plot of force counts. ```python counts, bin_edges = forces_hist.get_hist() plt.stairs(counts, bin_edges, fill=True) plt.xlabel(forces_hist.xlabel) plt.ylabel(forces_hist.ylabel) plt.yscale("log") plt.show() ``` -------------------------------- ### Initialize Git and DVC Repositories Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/03_Analysing_Datasets_and_Model_Predictions.ipynb Initializes Git and DVC (Data Version Control) repositories in the current directory. This is a standard practice for versioning code and data in machine learning projects. No specific inputs or outputs are defined, but it sets up the project for version control. ```bash !git init !dvc init ``` -------------------------------- ### Set up IPSuite Project and MACE-MP0 Model Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/07_metadyanmics_data_generating.ipynb Initializes an IPSuite project and configures the MACE-MP0 model for subsequent calculations. This is a foundational step for running simulations within the IPSuite framework. ```python import ipsuite as ips project = ips.Project() mace = ips.MACEMPModel() ``` -------------------------------- ### Initialize Python Environment with IPS Utilities Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/03_Analysing_Datasets_and_Model_Predictions.ipynb Sets up the Python environment for IPS analysis by importing necessary modules from pathlib, ase, and zntrack. It creates a temporary directory for operations. Dependencies include pathlib, ase, and zntrack. ```python from pathlib import Path from ase import units from ase.calculators.emt import EMT from ase.io.trajectory import TrajectoryWriter from ase.lattice.cubic import FaceCenteredCubic from ase.md.langevin import Langevin from ase.md.velocitydistribution import MaxwellBoltzmannDistribution from zntrack.utils import cwd_temp_dir temp_dir = cwd_temp_dir() ``` -------------------------------- ### Run NPT Simulations with Barostats in Python Source: https://context7.com/zincware/ipsuite/llms.txt This snippet demonstrates how to perform NPT (constant Number of particles, Pressure, and Temperature) simulations using Ipsuite's NPTThermostat and SVCRBarostat. It includes setting up the simulation parameters like time step, temperature, pressure, and coupling times, and analyzing the final density. Dependencies include the ipsuite and pandas libraries. ```python import ipsuite as ips project = ips.Project() with project: initial = ips.AddData(file="liquid_box.xyz") model = ips.MACEMPModel(model="large", device="cuda") # Nose-Hoover + Parrinello-Rahman NPT npt_thermostat = ips.NPTThermostat( time_step=0.5, temperature=300, # K pressure=1.01325, # bar (converted internally) ttime=100, # Temperature coupling (fs) pfactor=2000000, # Pressure coupling tetragonal_strain=False # Allow all cell deformations ) # Stochastic cell rescaling barostat svcr_barostat = ips.SVCRBarostat( time_step=1.0, temperature=350, betaT=4.57e-5, # Isothermal compressibility pressure_au=1.01325, taut=100, # Temperature damping (fs) taup=1000 # Pressure damping (fs) ) # NPT equilibration npt_md = ips.ASEMD( model=model, data=initial.frames, thermostat=npt_thermostat, steps=50000, sampling_rate=10, checks=[ ips.DensityCheck(min_density=800, max_density=1200) ] ) project.repro() # Analyze density evolution import pandas as pd metrics = pd.read_csv(npt_md.metrics[0]) print(f"Final density: {metrics['density'].iloc[-1]:.2f} kg/m³") ``` -------------------------------- ### Create and Execute Workflows with Project Context Manager (Python) Source: https://context7.com/zincware/ipsuite/llms.txt Demonstrates defining and executing a complete atomistic simulation workflow using the IPSuite Project context manager. It includes steps for loading structures, creating an ensemble model, running MD simulations with temperature control, and analyzing force predictions. The workflow execution relies on ZnTrack and DVC for reproducibility. ```python import ipsuite as ips # Define workflow project = ips.Project() with project: # Load molecular structures water = ips.Smiles2Conformers(smiles="O", numConfs=50, seed=42) # Create ensemble model for uncertainty quantification model = ips.MACEMPModel(model="medium", device="cuda") # Run MD simulation with temperature control thermostat = ips.LangevinThermostat( time_step=0.5, # fs temperature=300, # K friction=0.02 ) md_simulation = ips.ASEMD( model=model, data=water.frames, thermostat=thermostat, steps=10000, sampling_rate=10, checks=[ips.TemperatureCheck(max_temperature=500)] ) # Analyze force predictions analysis = ips.ForcesHistogram( data=md_simulation.frames, bins=100, logy_scale=True ) # Execute all defined Nodes in dependency order project.repro() # Uses DVC to execute only changed nodes # Access results after execution frames = md_simulation.frames # List[ase.Atoms] print(f"Collected {len(frames)} MD frames") ``` -------------------------------- ### Complete Active Learning Loop with Uncertainty-Driven Selection in Python Source: https://context7.com/zincware/ipsuite/llms.txt This Python script demonstrates a full active learning cycle. It uses IPSuite to generate initial structures, perform reference calculations, run molecular dynamics with ensemble uncertainty, select high-uncertainty configurations, retrain a model, and validate its performance. Dependencies include ipsuite, and potentially external ML training nodes (commented out). ```python import ipsuite as ips project = ips.Project() with project: # 1. Initial structure generation water = ips.Smiles2Conformers(smiles="O", numConfs=100, seed=42) box = ips.Packmol( data=[water.frames], count=[64], density=1000 ) # 2. Initial reference calculations reference_calc = ips.CP2KModel( config="cp2k_pbe.yaml", files=["BASIS_MOLOPT", "GTH_POTENTIALS"], cmd="mpirun -np 16 cp2k_shell.psmp" ) initial_training = ips.ApplyCalculator( data=box.frames, model=reference_calc ) # 3. Train initial models (external ML training nodes) # model_v1 = TrainMACE(data=initial_training.frames, ...) # model_v2 = TrainMACE(data=initial_training.frames, ...) # 4. Run exploratory MD with ensemble uncertainty ensemble = ips.EnsembleModel(models=[model_v1, model_v2]) thermostat = ips.LangevinThermostat( time_step=0.5, temperature=350, friction=0.02 ) md_exploration = ips.ASEMD( model=ensemble, data=box.frames, thermostat=thermostat, steps=50000, sampling_rate=5, checks=[ ips.ThresholdCheck( key="forces_uncertainty", max_value=0.12, window_size=500 ), ips.TemperatureCheck(max_temperature=500), ips.NaNCheck() ] ) # 5. Select high-uncertainty configurations uncertain_configs = ips.ThresholdSelection( data=md_exploration.frames, key="forces_uncertainty", threshold=0.08, n_configurations=50, min_distance=10 ) # 6. Calculate reference for uncertain structures new_references = ips.ApplyCalculator( data=uncertain_configs.frames, model=reference_calc ) # 7. Combine with original training data combined_training = ips.Flatten( data=[initial_training.frames, new_references.frames] ) # 8. Retrain models with expanded dataset # model_v3 = TrainMACE(data=combined_training.frames, ...) # 9. Validate on held-out test set test_set = ips.RandomSelection( data=initial_training.frames, n_configurations=20, seed=999 ) final_predictions = ips.ApplyCalculator( data=test_set.frames, model=model_v3 ) validation_metrics = ips.PredictionMetrics( x=test_set.frames, y=final_predictions.frames ) project.repro() print(f"Active learning cycle complete") print(f"Initial training: {len(initial_training.frames)} configs") print(f"New samples: {len(new_references.frames)} configs") print(f"Total training: {len(combined_training.frames)} configs") print(f"Final MAE: {validation_metrics.forces['mae']:.3f} meV/Å") ``` -------------------------------- ### Implement Active Learning with Threshold Checks in Python Source: https://context7.com/zincware/ipsuite/llms.txt This Python snippet demonstrates how to set up a simulation with active learning using threshold checks. It defines an ensemble model, a molecular dynamics simulation with uncertainty-based stopping criteria, and a mechanism to select uncertain frames for retraining. Dependencies include the 'ipsuite' library. ```python import ipsuite as ips project = ips.Project() with project: initial = ips.Smiles2Conformers(smiles="CCO", numConfs=1) box = ips.Packmol(data=[initial.frames], count=[50], density=800) # Ensemble for uncertainty quantification model1 = ips.MACEMPModel(model_path="model_v1.pth", device="cuda") model2 = ips.MACEMPModel(model_path="model_v2.pth", device="cuda") ensemble = ips.EnsembleModel(models=[model1, model2]) thermostat = ips.LangevinThermostat( time_step=0.5, temperature=350, friction=0.02 ) # MD with uncertainty-based stopping md = ips.ASEMD( model=ensemble, data=box.frames, thermostat=thermostat, steps=100000, sampling_rate=5, checks=[ # Stop if force uncertainty too high ips.ThresholdCheck( key="forces_uncertainty", max_value=0.15, # meV/Å threshold window_size=500, # Average over 500 frames minimum_window_size=100, larger_only=False ), # Stop if energy uncertainty too high ips.ThresholdCheck( key="energy_uncertainty", max_value=10.0, # meV/atom threshold window_size=500 ), # Standard safety checks ips.NaNCheck(), ips.TemperatureCheck(max_temperature=600) ] ) # Select uncertain frames for labeling uncertain = ips.ThresholdSelection( data=md.frames, key="forces_uncertainty", threshold=0.1, n_configurations=20 ) # Label with reference method reference = ips.CP2KModel(config="cp2k.yaml", files=["BASIS", "POT"]) labeled = ips.ApplyCalculator( data=uncertain.frames, model=reference ) project.repro() print(f"MD stopped after {len(md.frames)} frames") print(f"Selected {len(uncertain.frames)} frames for retraining") ``` -------------------------------- ### Listing Available Models in ipsuite Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/02_Training_Models.ipynb This code snippet shows how to access and display a list of all available models within the ipsuite library. This is useful for understanding the scope of models you can use. ```python ips.__all__ ``` -------------------------------- ### Importing ipsuite Library Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/02_Training_Models.ipynb This snippet demonstrates the basic import statement for the ipsuite library in Python. It's the first step to utilizing any functionality within the library. ```python import ipsuite as ips ``` -------------------------------- ### Run IPSuite Docker Commands Source: https://github.com/zincware/ipsuite/blob/main/README.md Demonstrates various commands to run IPSuite within a Docker container on Linux. These commands allow for tasks such as running dvc repro, executing Python code, listing zntrack, and launching Jupyter Lab. ```shell docker run -it -v "$(pwd):/app" --gpus all pythonf/ipsuite dvc repro docker run -it -v "$(pwd):/app" --gpus all pythonf/ipsuite python docker run -it -v "$(pwd):/app" --gpus all pythonf/ipsuite zntrack list docker run -it -v "$(pwd):/app" --gpus all --rm -p 8888:8888 pythonf/ipsuite jupyter lab --ip=0.0.0.0 --port=8888 --allow-root ``` -------------------------------- ### Build IPSuite Project Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/07_metadyanmics_data_generating.ipynb Builds the IPSuite project, which triggers the execution of all defined nodes and saves the project's configuration. This command initiates the actual simulation and data generation process. ```python project.build() ``` -------------------------------- ### Initialize PLUMED Calculator and Run MD Simulation Source: https://github.com/zincware/ipsuite/blob/main/docs/source/examples/07_metadyanmics_data_generating.ipynb Initializes the PLUMED calculator using the previously defined input file and the optimized geometry. It then sets up and runs an Adaptive String Method (ASE) Molecular Dynamics simulation using the PLUMED calculator as the model. ```python with project.group("METAD"): calc = ips.PlumedModel( model=mace, data=geoopt.frames, data_id=-1, config="plumed.dat", timestep=0.5, temperature=300, ) md = ips.ASEMD( model=calc, data=geoopt.frames, thermostat=thermostat, steps=4_000_000, ) ``` -------------------------------- ### Run Geometry Optimization with ipSuite Source: https://context7.com/zincware/ipsuite/llms.txt This snippet demonstrates how to perform geometry optimizations using ipSuite's ASEGeoOpt, which integrates with ASE optimizers. It allows for optimization of multiple structures, setting convergence criteria, step sizes, and applying constraints or checks. ```python import ipsuite as ips project = ips.Project() with project: structures = ips.Smiles2Conformers(smiles="CCO", numConfs=10) model = ips.MACEMPModel(model="medium") # Optimize structures optimization = ips.ASEGeoOpt( data=structures.frames, data_id=-1, # Optimize all structures (-1 means all) model=model, optimizer="FIRE", # FIRE, BFGS, LBFGS, etc. run_kwargs={"fmax": 0.05}, # Force convergence: 0.05 eV/Å maxstep=0.2, # Maximum step size (Å) sampling_rate=10, # Save every 10th step dump_rate=1000 # Checkpoint every 1000 steps ) # Optimize with constraints constrained_opt = ips.ASEGeoOpt( data=structures.frames, data_id=0, # Optimize only first structure model=model, optimizer="BFGS", run_kwargs={"fmax": 0.01}, constraints=[ ips.FixedLayerConstraint(upper_limit=5.0, lower_limit=0.0) ], checks=[ ips.EnergySpikeCheck(max_factor=2.0) ] ) project.repro() # Access optimization trajectory trajectory = optimization.frames # All optimization steps final_structures = [traj[-1] for traj in trajectory] print(f"Optimized {len(final_structures)} structures") ``` -------------------------------- ### Use CP2K and ORCA Quantum Chemistry Codes Source: https://context7.com/zincware/ipsuite/llms.txt Provides interfaces to CP2K (CP2KModel) and ORCA (ORCAModel) for quantum chemistry calculations. Supports configuration files, basis sets, potentials, and command-line execution. TBLiteModel is also available for tight-binding DFTB. ```python import ipsuite as ips project = ips.Project() with project: structures = ips.Smiles2Conformers(smiles="CO", numConfs=5) # CP2K model with configuration file cp2k = ips.CP2KModel( config="cp2k_config.yaml", # Contains CP2K input parameters files=["BASIS_MOLOPT", "GTH_POTENTIALS"], cmd="mpirun -np 4 cp2k_shell.psmp" ) # ORCA model with inline configuration orca = ips.ORCAModel( simpleinput="B3LYP def2-TZVP TightSCF", blocks="%pal nprocs 8 end\n%scf maxiter 200 end", cmd="/opt/orca/orca" ) # Tight-binding DFTB with TBLite tblite = ips.TBLiteModel() # Calculate reference energies and forces cp2k_calc = ips.ApplyCalculator( data=structures.frames, model=cp2k ) orca_calc = ips.ApplyCalculator( data=structures.frames, model=orca ) project.repro() # Compare results for cp2k_atoms, orca_atoms in zip(cp2k_calc.frames, orca_calc.frames): e_cp2k = cp2k_atoms.get_potential_energy() e_orca = orca_atoms.get_potential_energy() print(f"CP2K: {e_cp2k:.3f} eV, ORCA: {e_orca:.3f} eV") ``` -------------------------------- ### Load Atomic Configurations from Files with ipsuite Source: https://context7.com/zincware/ipsuite/llms.txt Imports structures from ASE-compatible formats for use in workflows. Supports various file types including XYZ and H5MD, and allows loading a specific number of configurations. Requires the 'ipsuite' library. ```python import ipsuite as ips project = ips.Project() with project: # Load trajectory file trajectory = ips.AddData( file="md_trajectory.xyz", name="trajectory" ) # Load specific number of configurations partial_data = ips.AddData( file="large_dataset.extxyz", lines_to_read=1000, name="partial" ) # Load H5MD format (faster I/O) h5md_data = ips.AddDataH5MD( file="simulation.h5", name="h5md" ) project.repro() # Access loaded configurations structures = trajectory.frames # List[ase.Atoms] print(f"Loaded {len(structures)} structures") print(f"First structure has {len(structures[0])} atoms") ``` -------------------------------- ### Run Molecular Dynamics with ipSuite Source: https://context7.com/zincware/ipsuite/llms.txt This snippet demonstrates running molecular dynamics (MD) simulations using ipSuite's ASEMD. It allows for various thermostats (e.g., Langevin), safety checks (e.g., NaN, temperature, energy spikes), and configuration of simulation parameters like time step, temperature, and friction. ```python import ipsuite as ips import pandas as pd project = ips.Project() with project: initial = ips.Smiles2Conformers(smiles="O", numConfs=1) box = ips.Packmol( data=[initial.frames], count=[100], density=1000 # Water density ) model = ips.MACEMPModel(model="medium", device="cuda") # Langevin thermostat for NVT thermostat = ips.LangevinThermostat( time_step=0.5, # fs temperature=300, # K friction=0.02 ) # MD simulation with safety checks md = ips.ASEMD( model=model, data=box.frames, data_ids=-1, # Run all configurations thermostat=thermostat, steps=100000, sampling_rate=10, # Save every 10 steps dump_rate=1000, # Checkpoint every 1000 steps repeat=(1, 1, 1), # Cell repetition seed=42, checks=[ ips.NaNCheck(), ips.TemperatureCheck(max_temperature=500), ips.EnergySpikeCheck(min_factor=0.5, max_factor=2.0), ips.ConnectivityCheck(bonded_min_dist=0.6, bonded_max_dist=2.0) ] ) project.repro() # Access trajectory trajectory = md.frames print(f"Collected {len(trajectory)} MD frames") # Access metrics CSV metrics = pd.read_csv(md.metrics[0]) print(metrics[["step", "temperature", "energy"]].head()) ``` -------------------------------- ### Analyze Uncertainty Calibration in Python Source: https://context7.com/zincware/ipsuite/llms.txt This Python snippet demonstrates how to analyze the calibration of uncertainty estimates using the 'ipsuite' library. It involves setting up reference calculations and ensemble predictions, then using the 'CalibrationMetrics' class to evaluate metrics like MACE, Miscalibration Area, and NLL. Plots visualizing the calibration curve are also generated. ```python import ipsuite as ips project = ips.Project() with project: structures = ips.AddData(file="validation.xyz") # Reference reference = ips.ApplyCalculator( data=structures.frames, model=ips.CP2KModel(config="cp2k.yaml", files=["BASIS", "POT"]) ) # Ensemble predictions with uncertainty ensemble = ips.EnsembleModel(models=[ ips.MACEMPModel(model_path="model1.pth"), ips.MACEMPModel(model_path="model2.pth"), ips.MACEMPModel(model_path="model3.pth") ]) predictions = ips.ApplyCalculator( data=structures.frames, model=ensemble ) # Calibration analysis calibration = ips.CalibrationMetrics( x=reference.frames, y=predictions.frames, force_dist_slices=[(0, 50), (50, 100), (100, 200)] # meV/Å bins ) project.repro() # Calibration metrics print(f"MACE (Mean Abs Calibration Error): {calibration.mace:.4f}") print(f"Miscalibration Area: {calibration.miscalibration_area:.4f}") print(f"NLL (Negative Log-Likelihood): {calibration.nll:.4f}") # Plots in calibration.plots_dir: # - calibration_curve.png: Expected vs observed error ``` -------------------------------- ### Compare Model Predictions with Reference Data in Python Source: https://context7.com/zincware/ipsuite/llms.txt This Python snippet outlines the process of comparing machine learning model predictions against reference data using the 'ipsuite' library. It involves loading structures, applying reference and ML models, and computing various error metrics such as MAE, RMSE, and R². The output includes printed metrics and generated plots for energy and forces. ```python import ipsuite as ips project = ips.Project() with project: structures = ips.AddData(file="test_set.xyz") # Reference calculations reference_model = ips.CP2KModel( config="cp2k_ref.yaml", files=["BASIS", "POTENTIALS"] ) reference = ips.ApplyCalculator( data=structures.frames, model=reference_model ) # ML predictions ml_model = ips.MACEMPModel(model_path="trained_model.pth") predictions = ips.ApplyCalculator( data=structures.frames, model=ml_model ) # Compute metrics metrics = ips.PredictionMetrics( x=reference.frames, # Reference y=predictions.frames, # Predictions figure_ymax={ "energy": 50, # meV/atom "forces": 200 # meV/Å } ) project.repro() # Access computed metrics print(f"Energy MAE: {metrics.energy['mae']:.3f} meV/atom") print(f"Energy RMSE: {metrics.energy['rmse']:.3f} meV/atom") print(f"Energy R²: {metrics.energy['r2']:.4f}") print(f"Forces MAE: {metrics.forces['mae']:.3f} meV/Å") print(f"Forces RMSE: {metrics.forces['rmse']:.3f} meV/Å") print(f"Forces R²: {metrics.forces['r2']:.4f}") # Plots automatically saved to metrics.plots_dir # - energy_scatter.png: Energy correlation plot # - forces_scatter.png: Forces correlation plot # - energy_histogram.png: Error distribution ``` -------------------------------- ### Apply Constraints During Simulations in Python Source: https://context7.com/zincware/ipsuite/llms.txt This Python snippet demonstrates how to apply various constraints during molecular dynamics simulations using Ipsuite. It covers fixing layers, spherical regions, bond lengths, and applying spring forces. Dependencies include the ipsuite library. ```python import ipsuite as ips project = ips.Project() with project: surface = ips.AddData(file="surface_system.xyz") model = ips.MACEMPModel(model="medium") thermostat = ips.LangevinThermostat( time_step=1.0, temperature=300, friction=0.02 ) # Constrained MD simulation md = ips.ASEMD( model=model, data=surface.frames, thermostat=thermostat, steps=10000, constraints=[ # Fix bottom layer of surface ips.FixedLayerConstraint( lower_limit=0.0, upper_limit=5.0 ), # Fix atoms in spherical region ips.FixedSphereConstraint( radius=3.0, atom_id=0 # Center on atom 0 ), # Fix specific bond length ips.FixedBondLengthConstraint( atom_id_1=10, atom_id_2=11 ), # Apply spring forces between atom pairs ips.HookeanConstraint( atom_ids=[(5, 6), (7, 8)], k=10.0, # Spring constant (eV/Ų) rt=2.5 # Threshold distance (Å) ) ] ) project.repro() print(f"Constrained MD: {len(md.frames)} frames") ```