### Install Poetry and Project Dependencies Source: https://github.com/orbital-materials/orb-models/blob/main/CONTRIBUTING.md Installs Poetry if not already present, then installs the orb_models package and its dependencies using Poetry. ```bash pip install poetry # Install Poetry if you don't have it poetry install ``` -------------------------------- ### Install orb-models Source: https://github.com/orbital-materials/orb-models/blob/main/README.md Installs the orb-models package using pip. This is the primary method for users to get started with the library. ```bash pip install orb-models ``` -------------------------------- ### Download Example Files Source: https://github.com/orbital-materials/orb-models/blob/main/examples/OrbMDTut.ipynb Downloads the example input XYZ file (NaClWater.xyz) and the Python script (NaClWaterMD.py) for running the molecular dynamics simulation from the Orb-Models GitHub repository. ```bash !wget https://raw.githubusercontent.com/orbital-materials/orb-models/main/examples/NaClWater.xyz !wget https://raw.githubusercontent.com/orbital-materials/orb-models/main/examples/NaClWaterMD.py ``` -------------------------------- ### List Files Source: https://github.com/orbital-materials/orb-models/blob/main/examples/OrbMDTut.ipynb Lists the files in the current directory after downloading the example files. This helps verify that the files were downloaded correctly. ```bash !ls ``` -------------------------------- ### Install Orb-Models Source: https://github.com/orbital-materials/orb-models/blob/main/examples/OrbMDTut.ipynb Installs the orb-models Python library using pip. This is a prerequisite for using the Orb-Models package. ```python !pip install -q orb-models ``` -------------------------------- ### Install py3Dmol Source: https://github.com/orbital-materials/orb-models/blob/main/examples/OrbMDTut.ipynb Installs the py3Dmol Python package, which is used for visualizing molecular structures and trajectories. ```bash pip install py3Dmol ``` -------------------------------- ### Install cuML for CUDA Source: https://github.com/orbital-materials/orb-models/blob/main/CONTRIBUTING.md Installs the cuML library, which requires a CUDA-enabled GPU. It provides different versions based on CUDA compatibility. ```bash pip install --extra-index-url=https://pypi.nvidia.com "cuml-cu11==25.2.*" # For cuda versions >=11.4, <11.8 ``` ```bash pip install --extra-index-url=https://pypi.nvidia.com "cuml-cu12==25.2.*" # For cuda versions >=12.0, <13.0 ``` -------------------------------- ### Conda Environment Setup for Orbital Materials Source: https://github.com/orbital-materials/orb-models/blob/main/examples/OrbMDTut.ipynb Instructions for creating and activating a conda environment named 'orb_env' with Python 3.11, essential for running the orbital materials simulations. ```bash conda create --name orb_env python=3.11 conda activate orb_env ``` -------------------------------- ### Run Project Tests with Pytest Source: https://github.com/orbital-materials/orb-models/blob/main/CONTRIBUTING.md Executes all tests for the orb_models package using the pytest framework. Assumes the user is in the root directory of the package. ```bash pytest ``` -------------------------------- ### Install cuML for GPU Acceleration Source: https://github.com/orbital-materials/orb-models/blob/main/README.md Installs the cuML library with specific CUDA versions for enhanced performance on large atomic systems, requiring CUDA-enabled GPUs. ```bash pip install --extra-index-url=https://pypi.nvidia.com "cuml-cu11==25.2.*" # For cuda versions >=11.4, <11.8 ``` ```bash pip install --extra-index-url=https://pypi.nvidia.com "cuml-cu12==25.2.*" # For cuda versions >=12.0, <13.0 ``` -------------------------------- ### Run Orb-models Docker Container Source: https://github.com/orbital-materials/orb-models/blob/main/README.md Command to run the orb-models Docker container. It enables GPU access, removes the container on exit, names it 'orb_models', and starts an interactive bash session inside the container. ```bash docker run --gpus all --rm --name orb_models -it orb_models /bin/bash ``` -------------------------------- ### Configure SageMaker Session and Role Source: https://github.com/orbital-materials/orb-models/blob/main/aws/Orb-Model.ipynb Sets up the SageMaker session for a specific AWS region and attempts to retrieve the execution role. If the execution role cannot be automatically found (e.g., not running in a SageMaker environment), it falls back to creating or getting a predefined role. It also initializes the SageMaker runtime client. ```python region = 'us-east-1' # Specify your desired region here boto3.setup_default_session(region_name=region) # Pass the boto3 session into the SageMaker Session. sagemaker_session = sage.Session() # Use this if running in Amazon SageMaker Notebook Instance or on an EC2 instance # Otherwise, create a role with the necessary permissions and pass it into the SageMaker Session manually. try: role = get_execution_role(sagemaker_session) print(f"Execution role found: {role}") except Exception as e: print(f"Could not retrieve execution role from SageMaker session. Reason: {e}") # Fallback: either use a known role or create one with boto3 role = create_or_get_sagemaker_role("orb-model-sagemaker-role") runtime = boto3.client("runtime.sagemaker") ``` -------------------------------- ### Orb-v2 Model Selection for Dispersion Interactions Source: https://github.com/orbital-materials/orb-models/blob/main/MODELS.md This example highlights the recommended `orb-d3-v2` model for systems where dispersion interactions are significant. It integrates D3 corrections directly into the model for faster processing compared to analytical methods. The model is trained on MPTraj and Alexandria datasets. ```python from orb_models.forcefield.pretrained import load_model # Recommended for systems with important dispersion interactions model = load_model("orb-d3-v2") # Use the loaded model for calculations... ``` -------------------------------- ### Create or Get SageMaker Execution Role Source: https://github.com/orbital-materials/orb-models/blob/main/aws/Orb-Model.ipynb Defines a function to create an IAM role for SageMaker if it doesn't exist, or retrieve its ARN if it does. The role is configured with a trust policy allowing SageMaker to assume it and is granted the `AmazonSageMakerFullAccess` policy. This role is crucial for SageMaker to manage AWS resources. ```python def create_or_get_sagemaker_role(role_name: str): iam_client = boto3.client('iam') # This is the trust policy allowing SageMaker to assume the role assume_role_policy_document = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "sagemaker.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } try: # Check if the role already exists response = iam_client.get_role(RoleName=role_name) print(f"Role '{role_name}' already exists. No action needed.") return response['Role']['Arn'] except iam_client.exceptions.NoSuchEntityException: # The role does not exist, so create it print(f"Role '{role_name}' not found. Creating...") response = iam_client.create_role( RoleName=role_name, AssumeRolePolicyDocument=json.dumps(assume_role_policy_document), Description="Role for SageMaker to create/modify resources", ) # Attach the AmazonSageMakerFullAccess policy iam_client.attach_role_policy( RoleName=role_name, PolicyArn="arn:aws:iam::aws:policy/AmazonSageMakerFullAccess" ) print(f"Role '{role_name}' has been created and policy attached.") return response['Role']['Arn'] except ClientError as e: print(f"Unexpected error: {e}") raise ``` -------------------------------- ### View Simulation Log Header Source: https://github.com/orbital-materials/orb-models/blob/main/examples/OrbMDTut.ipynb Displays the first few lines of the simulation log file 'md_nvt.log'. This is useful for checking the simulation's progress and initial parameters. ```bash !head md_nvt.log ``` -------------------------------- ### Run MD Simulation with Custom Parameters Source: https://github.com/orbital-materials/orb-models/blob/main/examples/OrbMDTut.ipynb This function initiates a molecular dynamics simulation with specified input file, cell size, temperature, and simulation intervals. It requires the 'orb_models' library. ```python run_md_simulation( input_file="NaClWater.xyz", cell_size= 25.25, temperature_K=400, total_steps=10000, traj_interval = 20, log_interval=20 ) ``` -------------------------------- ### Run Molecular Dynamics Simulation Source: https://github.com/orbital-materials/orb-models/blob/main/examples/OrbMDTut.ipynb Executes the molecular dynamics simulation using the downloaded Python script 'NaClWaterMD.py'. This script utilizes the Orb-Models library to perform the simulation. ```bash !python NaClWaterMD.py ``` -------------------------------- ### Import SageMaker Libraries Source: https://github.com/orbital-materials/orb-models/blob/main/aws/Orb-Model.ipynb Imports essential libraries for interacting with Amazon SageMaker, including Boto3 for AWS services, SageMaker SDK components, and utilities for authentication and requests. These are foundational for SageMaker operations. ```python from sagemaker import ModelPackage import sagemaker as sage from sagemaker import ModelPackage, get_execution_role import boto3 import json import requests from botocore.auth import SigV4Auth from botocore.awsrequest import AWSRequest from botocore.exceptions import ClientError ``` -------------------------------- ### Specify Input and Output Files Source: https://github.com/orbital-materials/orb-models/blob/main/aws/Orb-Model.ipynb Defines the filenames for the input data payload and the expected output file. These variables are used in subsequent steps to read the input data and save the inference results. ```python file_name = "examples/4A.cif" output_file_name = "output.json" ``` -------------------------------- ### Import MD Simulation Function Source: https://github.com/orbital-materials/orb-models/blob/main/examples/OrbMDTut.ipynb Imports the 'run_md_simulation' function from the 'NaClWaterMD' script. This allows calling the simulation function directly in the current environment. ```python from NaClWaterMD import run_md_simulation ``` -------------------------------- ### Build Orb-models Docker Image Source: https://github.com/orbital-materials/orb-models/blob/main/README.md Command to build the Docker image for orb-models locally. This command creates a Docker image tagged as 'orb_models'. ```bash docker build -t orb_models . ``` -------------------------------- ### Finetune Orb Models with Custom Dataset Source: https://github.com/orbital-materials/orb-models/blob/main/README.md Command to finetune Orb models using a custom ASE sqlite database. Requires specifying dataset name, data path, and base model. The base model must be one of the pretrained Orb models. ```python python finetune.py --dataset= --data_path= --base_model= ``` -------------------------------- ### Define Inference Parameters Source: https://github.com/orbital-materials/orb-models/blob/main/aws/Orb-Model.ipynb Specifies key parameters for real-time inference, including the model name for the endpoint, the content type of the input data, and the instance type for hosting the model. These settings are essential for deploying and invoking the SageMaker endpoint. ```python model_name = "Orb" content_type = "application/octet-stream" real_time_inference_instance_type = "ml.p3.2xlarge" ``` -------------------------------- ### Load Finetuned Orb Model Checkpoint Source: https://github.com/orbital-materials/orb-models/blob/main/README.md Python code to load a finetuned Orb model from a saved checkpoint. It uses `getattr` to dynamically load the model based on the base model name and requires the path to the checkpoint file and the desired device. ```python from orb_models.forcefield import pretrained model = getattr(pretrained, )( weights_path=, device="cpu", # or device="cuda" precision="float32-high", # or precision="float32-highest" ) ``` -------------------------------- ### Orb-v3 Confidence Head and Heatmap Visualization Source: https://github.com/orbital-materials/orb-models/blob/main/README.md Shows how to utilize the confidence head in Orb-v3 models to obtain per-atom confidence measures. It includes calculating forces and confidence scores, predicting confidence bins, and visualizing these confidences using a heatmap. ```python import ase from ase.build import molecule from seaborn import heatmap # optional, for visualization only import matplotlib.pyplot as plt # optional, for visualization only import numpy from orb_models.forcefield import pretrained from orb_models.forcefield.calculator import ORBCalculator device="cpu" # or device="cuda" # or choose another model using ORB_PRETRAINED_MODELS[model_name]() orbff = pretrained.orb_v3_conservative_inf_omat( device=device, ) calc = ORBCalculator(orbff, device=device) # Use a molecule (OOD for Orb, so confidence plot is # more interesting than a bulk crystal) atoms = molecule("CH3CH2Cl") atoms.calc = calc forces = atoms.get_forces() confidences = calc.results["confidence"] predicted_bin_per_atom = numpy.argmax(confidences, axis=-1) print(forces.shape, confidences.shape) # (num_atoms, 3), (num_atoms, 50) print(predicted_bin_per_atom) # List of length num_atoms heatmap(confidences) plt.xlabel('Confidence Bin') plt.ylabel('Atom Index') plt.title('Confidence Heatmap') plt.show() ``` -------------------------------- ### Orb Models as ASE Calculator Source: https://github.com/orbital-materials/orb-models/blob/main/README.md Shows how to integrate orb-models with ASE's calculator interface. This allows using orb-models within ASE's optimization and simulation workflows. Requires ASE and orb-models. ```python import ase from ase.build import bulk from orb_models.forcefield import pretrained from orb_models.forcefield.calculator import ORBCalculator device="cpu" # or device="cuda" # or choose another model using ORB_PRETRAINED_MODELS[model_name]() orbff = pretrained.orb_v3_conservative_inf_omat( device=device, precision="float32-high", # or "float32-highest" / "float64" ) calc = ORBCalculator(orbff, device=device) atoms = bulk('Cu', 'fcc', a=3.58, cubic=True) atoms.calc = calc atoms.get_potential_energy() ``` -------------------------------- ### Invoke SageMaker Endpoint with File Data Source: https://github.com/orbital-materials/orb-models/blob/main/aws/Orb-Model.ipynb This Python code snippet demonstrates how to invoke a SageMaker endpoint for real-time inference. It reads data from a specified file in binary mode, constructs the request URL for the SageMaker runtime, and sends the file content as the request body using the `sigv4_request` function. The response is then saved to an output file. ```python url=f"https://runtime.sagemaker.{region}.amazonaws.com/endpoints/{model_name}/invocations" with open(file_name, 'rb') as file: # Read the file as binary body = file.read() # Create the signed request with the file body response = sigv4_request( url, method='POST', body=body, headers={'Content-Type': content_type}, ) with open(output_file_name, 'w') as file: json.dump(response.json(), file) ``` -------------------------------- ### Direct Usage of Orb-v3 Potential with ASE Source: https://github.com/orbital-materials/orb-models/blob/main/README.md Demonstrates direct usage of the orb_v3_conservative_inf_omat model. It converts ASE atoms to graphs, predicts energy and forces, and converts results back to ASE atoms. Requires ASE and orb-models. ```python import ase from ase.build import bulk from orb_models.forcefield import atomic_system, pretrained from orb_models.forcefield.base import batch_graphs device = "cpu" # or device="cuda" orbff = pretrained.orb_v3_conservative_inf_omat( device=device, precision="float32-high", # or "float32-highest" / "float64" ) atoms = bulk('Cu', 'fcc', a=3.58, cubic=True) graph = atomic_system.ase_atoms_to_atom_graphs(atoms, orbff.system_config, device=device) # If you have several graphs, batch them like so: # graph = batch_graphs([graph1, graph2, ...]) result = orbff.predict(graph, split=False) # Convert to ASE atoms (unbatches the results and transfers to cpu if necessary) atoms = atomic_system.atom_graphs_to_ase_atoms( graph, energy=result["energy"], forces=result["grad_forces"], stress=result["grad_stress"] ) ``` -------------------------------- ### Deploy SageMaker Model Source: https://github.com/orbital-materials/orb-models/blob/main/aws/Orb-Model.ipynb Deploys the specified model package to create a SageMaker endpoint. It uses the previously defined role, model package ARN, and SageMaker session to instantiate a `ModelPackage` object and then calls the `deploy` method with the instance count, instance type, and endpoint name. ```python # create a deployable model from the model package. model = ModelPackage( role=role, model_package_arn=model_package_arn, sagemaker_session=sagemaker_session, ) # Deploy the model predictor = model.deploy(1, real_time_inference_instance_type, endpoint_name=model_name) ``` -------------------------------- ### Specify Charge and Spin for OrbMol Models Source: https://github.com/orbital-materials/orb-models/blob/main/README.md Demonstrates how to set the total charge and spin multiplicity for OrbMol models by modifying the `atoms.info` dictionary. This is a prerequisite for using OrbMol models. ```python import ase from ase.build import molecule from orb_models.forcefield import atomic_system, pretrained from orb_models.forcefield.base import batch_graphs device = "cpu" # or device="cuda" orbff = pretrained.orb_v3_conservative_omol( device=device, precision="float32-high", # or "float32-highest" / "float64 ) atoms = molecule("C6H6") atoms.info["charge"] = 0 # total charge atoms.info["spin"] = 1 # spin multiplicity graph = atomic_system.ase_atoms_to_atom_graphs(atoms, orbff.system_config, device=device) result = orbff.predict(graph, split=False) ``` -------------------------------- ### Visualize Molecular Frame with py3Dmol Source: https://github.com/orbital-materials/orb-models/blob/main/examples/OrbMDTut.ipynb This Python script visualizes a specific frame from a .xyz trajectory file using the py3Dmol library. It includes a function to parse the .xyz file and extract a desired frame, then displays it with ball-and-stick representation. ```python import py3Dmol # Function to extract a specific frame from the .xyz file def extract_frame(xyz_file, frame_number): with open(xyz_file, "r") as f: lines = f.readlines() # Parse the file num_atoms = int(lines[0].strip()) # Number of atoms from the first line frame_start = frame_number * (num_atoms + 2) # Start of the desired frame frame_lines = lines[frame_start : frame_start + num_atoms + 2] # Extract frame return "".join(frame_lines) # Specify the file and the frame number frame_number = 3 # Pick the frame (0-based indexing) xyz_file = "NaClWaterMD.xyz" frame_data = extract_frame(xyz_file, frame_number) # Visualize the extracted frame with balls and sticks viewer = py3Dmol.view(width=800, height=400) viewer.addModel(frame_data, "xyz") # Add the trajectory frame viewer.setStyle({ "stick": {}, "sphere": {"radius": 0.5} }) viewer.zoomTo() viewer.show() ``` -------------------------------- ### Loading Orb-v3 Conservative Model (Float32-Highest Precision) Source: https://github.com/orbital-materials/orb-models/blob/main/MODELS.md This snippet demonstrates how to load the `orb-v3-conservative-120-omat` model with the highest float32 precision. This model is recommended for initial testing due to its computational expense and accuracy. It utilizes PyTorch and requires careful precision specification for optimal performance. ```python from orb_models.forcefield.pretrained import load_model model = load_model("orb-v3-conservative-120-omat", precision='float32-highest') # Use the loaded model for calculations... ``` -------------------------------- ### Perform Real-time Inference with SigV4 Signed Request Source: https://github.com/orbital-materials/orb-models/blob/main/aws/Orb-Model.ipynb This Python function `sigv4_request` generates a SigV4 signed HTTP request for AWS services. It handles authentication using provided AWS credentials and can send requests with custom methods, bodies, parameters, and headers. It's commonly used to interact with SageMaker endpoints for real-time inference. ```python def sigv4_request( url, method='GET', body=None, params=None, headers=None, service='sagemaker', region=sagemaker_session.boto_region_name, credentials=boto3.Session().get_credentials().get_frozen_credentials() ): """Sends an HTTP request signed with SigV4 Args: url: The request URL (e.g. 'https://www.example.com'). method: The request method (e.g. 'GET', 'POST', 'PUT', 'DELETE'). Defaults to 'GET'. body: The request body (e.g. json.dumps({ 'foo': 'bar' })). Defaults to None. params: The request query params (e.g. { 'foo': 'bar' }). Defaults to None. headers: The request headers (e.g. { 'content-type': 'application/json' }). Defaults to None. service: The AWS service name. Defaults to 'execute-api'. region: The AWS region id. Defaults to the env var 'AWS_REGION'. credentials: The AWS credentials. Defaults to the current boto3 session's credentials. Returns: The HTTP response """ # sign request req = AWSRequest( method=method, url=url, data=body, params=params, headers=headers ) SigV4Auth(credentials, service, region).add_auth(req) req = req.prepare() # send request return requests.request( method=req.method, url=req.url, headers=req.headers, data=req.body ) ``` -------------------------------- ### Geometry Optimization with Orb Calculator Source: https://github.com/orbital-materials/orb-models/blob/main/README.md Demonstrates performing a geometry optimization using an ORBCalculator with ASE's BFGS optimizer. This requires the atoms object to have the ORBCalculator set as its calculator. ```python from ase.optimize import BFGS # Rattle the atoms to get them out of the minimum energy configuration atoms.rattle(0.5) print("Rattled Energy:", atoms.get_potential_energy()) calc = ORBCalculator(orbff, device="cpu") # or device="cuda" dyn = BFGS(atoms) dyn.run(fmax=0.01) print("Optimized Energy:", atoms.get_potential_energy()) ``` -------------------------------- ### Define Model Package ARN Source: https://github.com/orbital-materials/orb-models/blob/main/aws/Orb-Model.ipynb Stores the Amazon Resource Name (ARN) of the Orb model package. This ARN is required to create a deployable model in SageMaker. ```python model_package_arn = "arn:aws:sagemaker:us-east-1:865070037744:model-package/orbmodelpackage-3fcf0a9dd0d838a69043e94193f8bff2" ``` -------------------------------- ### Delete SageMaker Endpoint and Configuration Source: https://github.com/orbital-materials/orb-models/blob/main/aws/Orb-Model.ipynb This Python code snippet shows how to clean up AWS SageMaker resources by deleting a previously created endpoint and its corresponding endpoint configuration. It utilizes the `delete_endpoint` and `delete_endpoint_config` methods provided by the SageMaker session object. ```python model.sagemaker_session.delete_endpoint("Orb") model.sagemaker_session.delete_endpoint_config("Orb") ``` -------------------------------- ### Delete SageMaker Model Source: https://github.com/orbital-materials/orb-models/blob/main/aws/Orb-Model.ipynb This Python code snippet demonstrates how to delete a SageMaker model artifact. It calls the `delete_model` method on the SageMaker model object, which removes the model from SageMaker's managed environment. ```python model.delete_model() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.