AdsorbML tutorial#

from fairchem.core.common.relaxation.ase_utils import OCPCalculator
import ase.io
from ase.optimize import BFGS

from fairchem.data.oc.core import Adsorbate, AdsorbateSlabConfig, Bulk, Slab
import os
from glob import glob
import pandas as pd
from fairchem.data.oc.utils import DetectTrajAnomaly
from fairchem.data.oc.utils.vasp import write_vasp_input_files

# Optional - see below
import numpy as np
from dscribe.descriptors import SOAP
from scipy.spatial.distance import pdist, squareform
from x3dase.visualize import view_x3d_n

Enumerate the adsorbate-slab configurations to run relaxations on#

AdsorbML incorporates random placement, which is especially useful for more complicated adsorbates which may have many degrees of freedom. I have opted sample a few random placements and a few heuristic. Here I am using *CO on copper (1,1,1) as an example.

bulk_src_id = "mp-30"
adsorbate_smiles = "*CO"

bulk = Bulk(bulk_src_id_from_db = bulk_src_id)
adsorbate = Adsorbate(adsorbate_smiles_from_db=adsorbate_smiles)
slabs = Slab.from_bulk_get_specific_millers(bulk = bulk, specific_millers=(1,1,1))

# There may be multiple slabs with this miller index.
# For demonstrative purposes we will take the first entry.
slab = slabs[0]
Downloading src/fairchem/data/oc/databases/pkls/bulks.pkl...
# Perform heuristic placements
heuristic_adslabs = AdsorbateSlabConfig(slabs[0], adsorbate, mode="heuristic")

# Perform random placements
# (for AdsorbML we use `num_sites = 100` but we will use 4 for brevity here)
random_adslabs = AdsorbateSlabConfig(slabs[0], adsorbate, mode="random_site_heuristic_placement", num_sites = 4)

Run ML relaxations:#

There are 2 options for how to do this.

  1. Using OCPCalculator as the calculator within the ASE framework

  2. By writing objects to lmdb and relaxing them using main.py in the ocp repo

(1) is really only adequate for small stuff and it is what I will show here, but if you plan to run many relaxations, you should definitely use (2). More details about writing lmdbs has been provided here - follow the IS2RS/IS2RE instructions. And more information about running relaxations once the lmdb has been written is here.

You need to provide the calculator with a path to a model checkpoint file. That can be downloaded here

from fairchem.core.common.relaxation.ase_utils import OCPCalculator
from fairchem.core.models.model_registry import model_name_to_local_file
import os

checkpoint_path = model_name_to_local_file('EquiformerV2-31M-S2EF-OC20-All+MD', local_cache='/tmp/fairchem_checkpoints/')

os.makedirs(f"data/{bulk}_{adsorbate}", exist_ok=True)

# Define the calculator
calc = OCPCalculator(checkpoint_path=checkpoint_path) # if you have a gpu, add `cpu=False` to speed up calculations

adslabs = [*heuristic_adslabs.atoms_list, *random_adslabs.atoms_list]
# Set up the calculator
for idx, adslab in enumerate(adslabs):
    adslab.calc = calc
    opt = BFGS(adslab, trajectory=f"data/{bulk}_{adsorbate}/{idx}.traj")
    opt.run(fmax=0.05, steps=100) # For the AdsorbML results we used fmax = 0.02 and steps = 300, but we will use less strict values for brevity.
/home/runner/work/fairchem/fairchem/src/fairchem/core/models/scn/spherical_harmonics.py:23: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.
  _Jd = torch.load(os.path.join(os.path.dirname(__file__), "Jd.pt"))
/home/runner/work/fairchem/fairchem/src/fairchem/core/models/equiformer_v2/wigner.py:10: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.
  _Jd = torch.load(os.path.join(os.path.dirname(__file__), "Jd.pt"))
/home/runner/work/fairchem/fairchem/src/fairchem/core/models/escn/so3.py:23: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.
  _Jd = torch.load(os.path.join(os.path.dirname(__file__), "Jd.pt"))
/home/runner/work/fairchem/fairchem/src/fairchem/core/common/relaxation/ase_utils.py:191: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.
  checkpoint = torch.load(checkpoint_path, map_location=torch.device("cpu"))
WARNING:root:Detected old config, converting to new format. Consider updating to avoid potential incompatibilities.
INFO:root:amp: true
cmd:
  checkpoint_dir: /home/runner/work/fairchem/fairchem/docs/tutorials/checkpoints/2025-01-21-20-11-44
  commit: c162617
  identifier: ''
  logs_dir: /home/runner/work/fairchem/fairchem/docs/tutorials/logs/wandb/2025-01-21-20-11-44
  print_every: 100
  results_dir: /home/runner/work/fairchem/fairchem/docs/tutorials/results/2025-01-21-20-11-44
  seed: null
  timestamp_id: 2025-01-21-20-11-44
  version: 0.1.dev1+gc162617
dataset:
  format: trajectory_lmdb_v2
  grad_target_mean: 0.0
  grad_target_std: 2.887317180633545
  key_mapping:
    force: forces
    y: energy
  normalize_labels: true
  target_mean: -0.7554450631141663
  target_std: 2.887317180633545
  transforms:
    normalizer:
      energy:
        mean: -0.7554450631141663
        stdev: 2.887317180633545
      forces:
        mean: 0.0
        stdev: 2.887317180633545
evaluation_metrics:
  metrics:
    energy:
    - mae
    forces:
    - forcesx_mae
    - forcesy_mae
    - forcesz_mae
    - mae
    - cosine_similarity
    - magnitude_error
    misc:
    - energy_forces_within_threshold
  primary_metric: forces_mae
gp_gpus: null
gpus: 0
logger: wandb
loss_functions:
- energy:
    coefficient: 4
    fn: mae
- forces:
    coefficient: 100
    fn: l2mae
model:
  alpha_drop: 0.1
  attn_activation: silu
  attn_alpha_channels: 64
  attn_hidden_channels: 64
  attn_value_channels: 16
  distance_function: gaussian
  drop_path_rate: 0.1
  edge_channels: 128
  ffn_activation: silu
  ffn_hidden_channels: 128
  grid_resolution: 18
  lmax_list:
  - 4
  max_neighbors: 20
  max_num_elements: 90
  max_radius: 12.0
  mmax_list:
  - 2
  name: equiformer_v2
  norm_type: layer_norm_sh
  num_distance_basis: 512
  num_heads: 8
  num_layers: 8
  num_sphere_samples: 128
  otf_graph: true
  proj_drop: 0.0
  regress_forces: true
  sphere_channels: 128
  use_atom_edge_embedding: true
  use_gate_act: false
  use_grid_mlp: true
  use_pbc: true
  use_s2_act_attn: false
  weight_init: uniform
optim:
  batch_size: 8
  clip_grad_norm: 100
  ema_decay: 0.999
  energy_coefficient: 4
  eval_batch_size: 8
  eval_every: 10000
  force_coefficient: 100
  grad_accumulation_steps: 1
  load_balancing: atoms
  loss_energy: mae
  loss_force: l2mae
  lr_initial: 0.0004
  max_epochs: 3
  num_workers: 8
  optimizer: AdamW
  optimizer_params:
    weight_decay: 0.001
  scheduler: LambdaLR
  scheduler_params:
    epochs: 1009275
    lambda_type: cosine
    lr: 0.0004
    lr_min_factor: 0.01
    warmup_epochs: 3364.25
    warmup_factor: 0.2
outputs:
  energy:
    level: system
  forces:
    eval_on_free_atoms: true
    level: atom
    train_on_free_atoms: true
relax_dataset: {}
slurm:
  additional_parameters:
    constraint: volta32gb
  cpus_per_task: 9
  folder: /checkpoint/abhshkdz/open-catalyst-project/logs/equiformer_v2/8307793
  gpus_per_node: 8
  job_id: '8307793'
  job_name: eq2s_051701_allmd
  mem: 480GB
  nodes: 8
  ntasks_per_node: 8
  partition: learnaccel
  time: 4320
task:
  dataset: trajectory_lmdb_v2
  eval_on_free_atoms: true
  grad_input: atomic forces
  labels:
  - potential energy
  primary_metric: forces_mae
  train_on_free_atoms: true
test_dataset: {}
trainer: ocp
val_dataset: {}
INFO:root:Loading model: equiformer_v2
WARNING:root:equiformer_v2 (EquiformerV2) class is deprecated in favor of equiformer_v2_backbone_and_heads  (EquiformerV2BackboneAndHeads)
INFO:root:Loaded EquiformerV2 with 31058690 parameters.
INFO:root:Loading checkpoint in inference-only mode, not loading keys associated with trainer state!
/home/runner/work/fairchem/fairchem/src/fairchem/core/modules/normalization/normalizer.py:69: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).
  "mean": torch.tensor(state_dict["mean"]),
WARNING:root:No seed has been set in modelcheckpoint or OCPCalculator! Results may not be reproducible on re-run
      Step     Time          Energy          fmax
BFGS:    0 20:10:55       -0.241180        1.130923
BFGS:    1 20:10:58       -0.272537        1.482948
BFGS:    2 20:11:01       -0.372797        1.860831
BFGS:    3 20:11:04       -0.442337        1.453495
BFGS:    4 20:11:07       -0.481420        0.592483
BFGS:    5 20:11:09       -0.499219        0.268369
BFGS:    6 20:11:12       -0.504701        0.135804
BFGS:    7 20:11:15       -0.505236        0.120518
BFGS:    8 20:11:18       -0.517501        0.095443
BFGS:    9 20:11:21       -0.525372        0.084905
BFGS:   10 20:11:24       -0.527035        0.062402
BFGS:   11 20:11:27       -0.530098        0.097390
BFGS:   12 20:11:30       -0.532788        0.113824
BFGS:   13 20:11:32       -0.534178        0.059988
BFGS:   14 20:11:35       -0.533391        0.028915
      Step     Time          Energy          fmax
BFGS:    0 20:11:38       -0.332906        1.355625
BFGS:    1 20:11:41       -0.343280        1.642403
BFGS:    2 20:11:44       -0.377296        1.103477
BFGS:    3 20:11:47       -0.500364        0.287171
BFGS:    4 20:11:49       -0.501163        0.184932
BFGS:    5 20:11:52       -0.502899        0.189326
BFGS:    6 20:11:55       -0.508482        0.330626
BFGS:    7 20:11:58       -0.512987        0.262669
BFGS:    8 20:12:01       -0.516844        0.113653
BFGS:    9 20:12:04       -0.517867        0.084262
BFGS:   10 20:12:07       -0.519306        0.164518
BFGS:   11 20:12:09       -0.520836        0.174346
BFGS:   12 20:12:12       -0.523219        0.133427
BFGS:   13 20:12:15       -0.524452        0.088238
BFGS:   14 20:12:18       -0.525360        0.030477
      Step     Time          Energy          fmax
BFGS:    0 20:12:21       -0.407534        1.886756
BFGS:    1 20:12:24       -0.407428        2.300059
BFGS:    2 20:12:27       -0.441233        0.785991
BFGS:    3 20:12:29       -0.465193        0.758457
BFGS:    4 20:12:32       -0.513729        1.208795
BFGS:    5 20:12:35       -0.545979        0.387202
BFGS:    6 20:12:38       -0.547757        0.181122
BFGS:    7 20:12:40       -0.550220        0.308677
BFGS:    8 20:12:43       -0.551160        0.354835
BFGS:    9 20:12:46       -0.556192        0.285570
BFGS:   10 20:12:49       -0.559155        0.139903
BFGS:   11 20:12:52       -0.560498        0.095282
BFGS:   12 20:12:54       -0.561827        0.182859
BFGS:   13 20:12:57       -0.562545        0.223289
BFGS:   14 20:13:00       -0.563661        0.180727
BFGS:   15 20:13:03       -0.563597        0.180218
BFGS:   16 20:13:06       -0.565270        0.057310
BFGS:   17 20:13:08       -0.565759        0.045912
      Step     Time          Energy          fmax
BFGS:    0 20:13:11       -0.429834        1.859959
BFGS:    1 20:13:14       -0.429124        2.274018
BFGS:    2 20:13:17       -0.461901        0.737163
BFGS:    3 20:13:19       -0.481655        0.701149
BFGS:    4 20:13:22       -0.522270        1.217906
BFGS:    5 20:13:25       -0.549986        0.589065
BFGS:    6 20:13:28       -0.553413        0.194035
BFGS:    7 20:13:30       -0.553898        0.164227
BFGS:    8 20:13:33       -0.554012        0.261752
BFGS:    9 20:13:36       -0.556494        0.279332
BFGS:   10 20:13:39       -0.560708        0.195511
BFGS:   11 20:13:42       -0.562534        0.081900
BFGS:   12 20:13:44       -0.564272        0.096628
BFGS:   13 20:13:47       -0.564480        0.204616
BFGS:   14 20:13:50       -0.565193        0.215479
BFGS:   15 20:13:53       -0.565398        0.135823
BFGS:   16 20:13:56       -0.565587        0.091274
BFGS:   17 20:13:59       -0.565868        0.028526
      Step     Time          Energy          fmax
BFGS:    0 20:14:01       -0.321837        1.350572
BFGS:    1 20:14:04       -0.330835        1.634702
BFGS:    2 20:14:07       -0.365177        1.117475
BFGS:    3 20:14:10       -0.496782        0.343211
BFGS:    4 20:14:13       -0.498397        0.199415
BFGS:    5 20:14:15       -0.500122        0.150964
BFGS:    6 20:14:18       -0.511925        0.349329
BFGS:    7 20:14:21       -0.514473        0.231902
BFGS:    8 20:14:24       -0.517065        0.101355
BFGS:    9 20:14:27       -0.517892        0.158719
BFGS:   10 20:14:29       -0.518056        0.202228
BFGS:   11 20:14:32       -0.518466        0.175738
BFGS:   12 20:14:35       -0.518870        0.129973
BFGS:   13 20:14:38       -0.520166        0.049319
      Step     Time          Energy          fmax
BFGS:    0 20:14:41       -0.280165        1.282519
BFGS:    1 20:14:44       -0.292580        1.552939
BFGS:    2 20:14:46       -0.330638        1.266175
BFGS:    3 20:14:49       -0.380433        2.211922
BFGS:    4 20:14:52       -0.452960        0.653796
BFGS:    5 20:14:55       -0.470122        0.312489
BFGS:    6 20:14:57       -0.479203        0.374080
BFGS:    7 20:15:00       -0.484409        0.385848
BFGS:    8 20:15:03       -0.505498        0.452714
BFGS:    9 20:15:06       -0.512344        0.177174
BFGS:   10 20:15:09       -0.516361        0.175127
BFGS:   11 20:15:11       -0.519411        0.184759
BFGS:   12 20:15:14       -0.522584        0.189043
BFGS:   13 20:15:17       -0.525943        0.131039
BFGS:   14 20:15:20       -0.525381        0.084601
BFGS:   15 20:15:23       -0.525212        0.093308
BFGS:   16 20:15:25       -0.524604        0.077128
BFGS:   17 20:15:28       -0.524426        0.073258
BFGS:   18 20:15:31       -0.524917        0.055894
BFGS:   19 20:15:34       -0.525659        0.051123
BFGS:   20 20:15:36       -0.525735        0.042771
      Step     Time          Energy          fmax
BFGS:    0 20:15:39       -0.266408        0.972634
BFGS:    1 20:15:42       -0.281242        1.186286
BFGS:    2 20:15:45       -0.352077        1.683339
BFGS:    3 20:15:48       -0.313434        2.648749
BFGS:    4 20:15:50       -0.426905        0.510171
BFGS:    5 20:15:53       -0.441919        0.266383
BFGS:    6 20:15:56       -0.449064        0.295928
BFGS:    7 20:15:59       -0.450767        0.291326
BFGS:    8 20:16:02       -0.471376        0.189149
BFGS:    9 20:16:04       -0.473285        0.166141
BFGS:   10 20:16:07       -0.477067        0.186498
BFGS:   11 20:16:10       -0.482095        0.266889
BFGS:   12 20:16:13       -0.488635        0.304360
BFGS:   13 20:16:16       -0.494040        0.264302
BFGS:   14 20:16:18       -0.497935        0.234159
BFGS:   15 20:16:21       -0.502942        0.259190
BFGS:   16 20:16:24       -0.510730        0.278492
BFGS:   17 20:16:27       -0.518200        0.255536
BFGS:   18 20:16:29       -0.523632        0.227053
BFGS:   19 20:16:32       -0.525690        0.151702
BFGS:   20 20:16:35       -0.529720        0.093103
BFGS:   21 20:16:38       -0.532771        0.206989
BFGS:   22 20:16:41       -0.532317        0.261835
BFGS:   23 20:16:43       -0.534242        0.251697
BFGS:   24 20:16:46       -0.535644        0.145228
BFGS:   25 20:16:49       -0.535123        0.103497
BFGS:   26 20:16:52       -0.535188        0.179422
BFGS:   27 20:16:55       -0.535832        0.243919
BFGS:   28 20:16:57       -0.536999        0.291297
BFGS:   29 20:17:00       -0.543273        0.395216
BFGS:   30 20:17:03       -0.548278        0.181827
BFGS:   31 20:17:06       -0.554657        0.289406
BFGS:   32 20:17:09       -0.556486        0.227632
BFGS:   33 20:17:11       -0.557246        0.113774
BFGS:   34 20:17:14       -0.558432        0.078203
BFGS:   35 20:17:17       -0.559820        0.125901
BFGS:   36 20:17:20       -0.561079        0.101297
BFGS:   37 20:17:23       -0.561208        0.065820
BFGS:   38 20:17:26       -0.561160        0.058017
BFGS:   39 20:17:28       -0.562047        0.076575
BFGS:   40 20:17:31       -0.562796        0.115987
BFGS:   41 20:17:34       -0.564479        0.126160
BFGS:   42 20:17:37       -0.562957        0.067744
BFGS:   43 20:17:40       -0.562929        0.033049
      Step     Time          Energy          fmax
BFGS:    0 20:17:43       -0.218473        1.061664
BFGS:    1 20:17:46       -0.250826        1.324728
BFGS:    2 20:17:48       -0.382507        1.989416
BFGS:    3 20:17:51       -0.360311        2.263717
BFGS:    4 20:17:54       -0.462403        0.801435
BFGS:    5 20:17:57       -0.480871        0.403257
BFGS:    6 20:18:00       -0.490225        0.238986
BFGS:    7 20:18:03       -0.491336        0.200486
BFGS:    8 20:18:06       -0.502408        0.144422
BFGS:    9 20:18:08       -0.506932        0.182685
BFGS:   10 20:18:11       -0.508340        0.171177
BFGS:   11 20:18:14       -0.509576        0.086269
BFGS:   12 20:18:17       -0.513178        0.256044
BFGS:   13 20:18:20       -0.514771        0.309703
BFGS:   14 20:18:23       -0.517227        0.273613
BFGS:   15 20:18:25       -0.517842        0.152048
BFGS:   16 20:18:28       -0.517909        0.073034
BFGS:   17 20:18:31       -0.519713        0.191725
BFGS:   18 20:18:34       -0.521532        0.206186
BFGS:   19 20:18:37       -0.525438        0.124365
BFGS:   20 20:18:40       -0.527839        0.031758

Parse the trajectories and post-process#

As a post-processing step we check to see if:

  1. the adsorbate desorbed

  2. the adsorbate disassociated

  3. the adsorbate intercalated

  4. the surface has changed

We check these because they effect our referencing scheme and may result in erroneous energies. For (4), the relaxed surface should really be supplied as well. It will be necessary when correcting the SP / RX energies later. Since we don’t have it here, we will ommit supplying it, and the detector will instead compare the initial and final slab from the adsorbate-slab relaxation trajectory. If a relaxed slab is provided, the detector will compare it and the slab after the adsorbate-slab relaxation. The latter is more correct! Note: for the results in the AdsorbML paper, we did not check if the adsorbate was intercalated (is_adsorbate_intercalated()) because it is a new addition.

# Iterate over trajs to extract results
results = []
for file in glob(f"data/{bulk}_{adsorbate}/*.traj"):
    rx_id = file.split("/")[-1].split(".")[0]
    traj = ase.io.read(file, ":")
    
    # Check to see if the trajectory is anomolous
    initial_atoms = traj[0]
    final_atoms = traj[-1]
    atom_tags = initial_atoms.get_tags()
    detector = DetectTrajAnomaly(initial_atoms, final_atoms, atom_tags)
    anom = (
        detector.is_adsorbate_dissociated()
        or detector.is_adsorbate_desorbed()
        or detector.has_surface_changed()
        or detector.is_adsorbate_intercalated()
    )
    rx_energy = traj[-1].get_potential_energy()
    results.append({"relaxation_idx": rx_id, "relaxed_atoms": traj[-1],
                    "relaxed_energy_ml": rx_energy, "anomolous": anom})
df = pd.DataFrame(results)
df
relaxation_idx relaxed_atoms relaxed_energy_ml anomolous
0 2 (Atom('Cu', [-1.3000465215529715, 2.2517466275... -0.565759 False
1 0 (Atom('Cu', [-1.3000465215529715, 2.2517466275... -0.533391 False
2 4 (Atom('Cu', [-1.3000465215529715, 2.2517466275... -0.520166 False
3 7 (Atom('Cu', [-1.3000465215529715, 2.2517466275... -0.527839 False
4 6 (Atom('Cu', [-1.3000465215529715, 2.2517466275... -0.562929 False
5 3 (Atom('Cu', [-1.3000465215529715, 2.2517466275... -0.565868 False
6 1 (Atom('Cu', [-1.3000465215529715, 2.2517466275... -0.525360 False
7 5 (Atom('Cu', [-1.3000465215529715, 2.2517466275... -0.525735 False
#scrap anomalies
df = df[~df.anomolous].copy().reset_index()

(Optional) Deduplicate structures#

We may have enumerated very similar structures or structures may have relaxed to the same configuration. For this reason, it is advantageous to cull systems if they are very similar. This results in marginal improvements in the recall metrics we calculated for AdsorbML, so it wasnt implemented there. It is, however, a good way to prevent wasteful VASP calculations. You can also imagine that if we would have enumerated 1000 configs per slab adsorbate combo rather than 100 for AdsorbML, it is more likely that having redundant systems would reduce performance, so its a good thing to keep in mind. This may be done by eye for a small number of systems, but with many systems it is easier to use an automated approach. Here is an example of one such approach, which uses a SOAP descriptor to find similar systems.

# Extract the configs and their energies
def deduplicate(configs_for_deduplication: list,
                adsorbate_binding_index: int,
                cosine_similarity = 1e-3,
               ):
    """
    A function that may be used to deduplicate similar structures.
    Among duplicate entries, the one with the lowest energy will be kept.
    
    Args:
        configs_for_deduplication: a list of ML relaxed adsorbate-
            surface configurations.
        cosine_similarity: The cosine simularity value above which,
            configurations are considered duplicate.
            
    Returns:
        (list): the indices of configs which should be kept as non-duplicate
    """
    
    energies_for_deduplication = np.array([atoms.get_potential_energy() for atoms in configs_for_deduplication])
    # Instantiate the soap descriptor
    soap = SOAP(
        species=np.unique(configs_for_deduplication[0].get_chemical_symbols()),
        r_cut = 2.0,
        n_max=6,
        l_max=3,
        periodic=True,
    )
    #Figure out which index cooresponds to 
    ads_len = list(configs_for_deduplication[0].get_tags()).count(2)
    position_idx = -1*(ads_len-adsorbate_binding_index)
    # Iterate over the systems to get the SOAP vectors
    soap_desc = []
    for config in configs_for_deduplication:
        soap_ex = soap.create(config, centers=[position_idx])
        soap_desc.extend(soap_ex)

    soap_descs = np.vstack(soap_desc)

    #Use euclidean distance to assess similarity
    distance = squareform(pdist(soap_descs, metric="cosine"))

    bool_matrix = np.where(distance <= cosine_similarity, 1, 0)
    # For configs that are found to be similar, just keep the lowest energy one
    idxs_to_keep = []
    pass_idxs = []
    for idx, row in enumerate(bool_matrix):
        if idx in pass_idxs:
            continue
            
        elif sum(row) == 1:
            idxs_to_keep.append(idx)
        else:
            same_idxs = [row_idx for row_idx, val in enumerate(row) if val == 1]
            pass_idxs.extend(same_idxs)
            # Pick the one with the lowest energy by ML
            min_e = min(energies_for_deduplication[same_idxs])
            idxs_to_keep.append(list(energies_for_deduplication).index(min_e))
    return idxs_to_keep
configs_for_deduplication =  df.relaxed_atoms.tolist()
idxs_to_keep = deduplicate(configs_for_deduplication, adsorbate.binding_indices[0])
# Flip through your configurations to check them out (and make sure deduplication looks good)
print(idxs_to_keep)
view_x3d_n(configs_for_deduplication[2].repeat((2,2,1)))
df = df.iloc[idxs_to_keep]
low_e_values = np.round(df.sort_values(by = "relaxed_energy_ml").relaxed_energy_ml.tolist()[0:5],3)
print(f"The lowest 5 energies are: {low_e_values}")
df
The lowest 5 energies are: [-0.566 -0.533 -0.526]
index relaxation_idx relaxed_atoms relaxed_energy_ml anomolous
5 5 3 (Atom('Cu', [-1.3000465215529715, 2.2517466275... -0.565868 False
1 1 0 (Atom('Cu', [-1.3000465215529715, 2.2517466275... -0.533391 False
7 7 5 (Atom('Cu', [-1.3000465215529715, 2.2517466275... -0.525735 False

Write VASP input files#

This assumes you have access to VASP pseudopotentials and the right environment variables configured for ASE. The default VASP flags (which are equivalent to those used to make OC20) are located in ocdata.utils.vasp. Alternatively, you may pass your own vasp flags to the write_vasp_input_files function as vasp_flags.

# Grab the 5 systems with the lowest energy
configs_for_dft = df.sort_values(by = "relaxed_energy_ml").relaxed_atoms.tolist()[0:5]
config_idxs = df.sort_values(by = "relaxed_energy_ml").relaxation_idx.tolist()[0:5]

# Write the inputs
for idx, config in enumerate(configs_for_dft):
    os.mkdir(f"data/{config_idxs[idx]}")
    write_vasp_input_files(config, outdir = f"data/{config_idxs[idx]}/")