anonymous commited on
Commit ·
9042866
1
Parent(s): 32fa7e5
matris update
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitignore +20 -0
- models/matris/README.md +5 -0
- models/matris/__pycache__/matris_dataset.cpython-310.pyc +0 -0
- models/matris/bench_matris_speed_single.py +227 -0
- models/matris/eval_matris.py +334 -0
- models/matris/example/cif_file/demo.cif +36 -0
- models/matris/example/test_ralexation.py +36 -0
- models/matris/foundation_models/MatRIS_10M_MP.pth.tar +3 -0
- models/matris/foundation_models/MatRIS_10M_OAM.pth.tar +3 -0
- models/matris/matris/__init__.py +8 -0
- models/matris/matris/__pycache__/__init__.cpython-310.pyc +0 -0
- models/matris/matris/applications/__init__.py +4 -0
- models/matris/matris/applications/base.py +199 -0
- models/matris/matris/applications/md.py +349 -0
- models/matris/matris/applications/relax.py +144 -0
- models/matris/matris/graph/__init__.py +3 -0
- models/matris/matris/graph/__pycache__/__init__.cpython-310.pyc +0 -0
- models/matris/matris/graph/__pycache__/converter.cpython-310.pyc +0 -0
- models/matris/matris/graph/__pycache__/radiusgraph.cpython-310.pyc +0 -0
- models/matris/matris/graph/converter.py +226 -0
- models/matris/matris/graph/cygraph.c +0 -0
- models/matris/matris/graph/cygraph.pyx +174 -0
- models/matris/matris/graph/fast_converter_libraries/create_graph.c +423 -0
- models/matris/matris/graph/fast_converter_libraries/uthash.h +1140 -0
- models/matris/matris/graph/radiusgraph.py +504 -0
- models/matris/matris/graph/setup.py +8 -0
- models/matris/matris/model/__init__.py +1 -0
- models/matris/matris/model/__pycache__/__init__.cpython-310.pyc +0 -0
- models/matris/matris/model/__pycache__/basis_function.cpython-310.pyc +0 -0
- models/matris/matris/model/__pycache__/feature_embed.cpython-310.pyc +0 -0
- models/matris/matris/model/__pycache__/functions.cpython-310.pyc +0 -0
- models/matris/matris/model/__pycache__/interaction_block.cpython-310.pyc +0 -0
- models/matris/matris/model/__pycache__/model.cpython-310.pyc +0 -0
- models/matris/matris/model/__pycache__/processgraph.cpython-310.pyc +0 -0
- models/matris/matris/model/__pycache__/readout.cpython-310.pyc +0 -0
- models/matris/matris/model/__pycache__/reference_energy.cpython-310.pyc +0 -0
- models/matris/matris/model/basis_function.py +367 -0
- models/matris/matris/model/feature_embed.py +268 -0
- models/matris/matris/model/functions.py +466 -0
- models/matris/matris/model/interaction_block.py +507 -0
- models/matris/matris/model/model.py +321 -0
- models/matris/matris/model/op/__init__.py +9 -0
- models/matris/matris/model/op/__pycache__/__init__.cpython-310.pyc +0 -0
- models/matris/matris/model/op/__pycache__/fuse_basis_func.cpython-310.pyc +0 -0
- models/matris/matris/model/op/__pycache__/fuse_sigmoid_op.cpython-310.pyc +0 -0
- models/matris/matris/model/op/__pycache__/fused_silu_op.cpython-310.pyc +0 -0
- models/matris/matris/model/op/fuse_basis_func.py +129 -0
- models/matris/matris/model/op/fuse_sigmoid_op.py +63 -0
- models/matris/matris/model/op/fused_silu_op.py +82 -0
- models/matris/matris/model/op/src/Opdefine.h +13 -0
.gitignore
CHANGED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.wandb
|
| 2 |
+
debug.log
|
| 3 |
+
debug-internal.log
|
| 4 |
+
debug-core.log
|
| 5 |
+
*.log
|
| 6 |
+
|
| 7 |
+
# Weights & Biases
|
| 8 |
+
wandb/
|
| 9 |
+
**/wandb/
|
| 10 |
+
# Build artifacts
|
| 11 |
+
models/matris/build/
|
| 12 |
+
*.so
|
| 13 |
+
*.o
|
| 14 |
+
|
| 15 |
+
# Compiled/build artifacts
|
| 16 |
+
models/matris/build/
|
| 17 |
+
models/matris/**/*.so
|
| 18 |
+
models/matris/**/*.o
|
| 19 |
+
*.so
|
| 20 |
+
*.o
|
models/matris/README.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Introduction
|
| 2 |
+
|
| 3 |
+
To train matris, run the run_matris.py script, there's also a ddp version called run_matris_ddp.py
|
| 4 |
+
|
| 5 |
+
To eval matris, run the eval_matris.py
|
models/matris/__pycache__/matris_dataset.cpython-310.pyc
ADDED
|
Binary file (4.73 kB). View file
|
|
|
models/matris/bench_matris_speed_single.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Benchmark MatRIS speed (energy + forces) on a single structure ~96 atoms.
|
| 4 |
+
|
| 5 |
+
- Selects a structure from an extxyz file (closest natoms to target, default 96)
|
| 6 |
+
- Loads a pretrained MatRIS model (matris_10m_oam or matris_10m_mp)
|
| 7 |
+
- Converts the structure to a MatRIS graph (optional to include conversion time)
|
| 8 |
+
- Times the forward pass that returns energy + forces (forces require autograd)
|
| 9 |
+
|
| 10 |
+
Notes
|
| 11 |
+
- Do NOT wrap the model call in torch.no_grad(): MatRIS computes forces via autograd.
|
| 12 |
+
- For reliable repeated timing, we refresh the coordinate tensor each iteration to be a leaf
|
| 13 |
+
requiring grad (avoids "does not require grad" and avoids graph growth).
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
import argparse
|
| 18 |
+
import time
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Any
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
from ase.io import read
|
| 24 |
+
from ase.atoms import Atoms
|
| 25 |
+
|
| 26 |
+
def pick_index_by_natoms(atoms_list: list[Atoms], target: int) -> int:
|
| 27 |
+
best_i = 0
|
| 28 |
+
best_d = 10**9
|
| 29 |
+
for i, a in enumerate(atoms_list):
|
| 30 |
+
d = abs(len(a) - target)
|
| 31 |
+
if d < best_d:
|
| 32 |
+
best_d = d
|
| 33 |
+
best_i = i
|
| 34 |
+
if best_d == 0:
|
| 35 |
+
break
|
| 36 |
+
return best_i
|
| 37 |
+
|
| 38 |
+
def maybe_cuda_sync(device: str):
|
| 39 |
+
if device.startswith("cuda"):
|
| 40 |
+
try:
|
| 41 |
+
import torch
|
| 42 |
+
torch.cuda.synchronize()
|
| 43 |
+
except Exception:
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
def refresh_grad_coords(graph: Any):
|
| 47 |
+
"""
|
| 48 |
+
Ensure graph has a fresh leaf coordinate tensor requiring grad.
|
| 49 |
+
|
| 50 |
+
MatRIS force computation needs gradients w.r.t. Cartesian coordinates.
|
| 51 |
+
Supports dict-like graphs and RadiusGraph-style objects.
|
| 52 |
+
"""
|
| 53 |
+
import torch
|
| 54 |
+
|
| 55 |
+
candidate_keys = [
|
| 56 |
+
"batch_cart_coords",
|
| 57 |
+
"cart_coords",
|
| 58 |
+
"cartesian_coords",
|
| 59 |
+
"pos",
|
| 60 |
+
"positions",
|
| 61 |
+
"atom_frac_coord",
|
| 62 |
+
]
|
| 63 |
+
|
| 64 |
+
# Case 1: dictionary-like graph
|
| 65 |
+
if isinstance(graph, dict):
|
| 66 |
+
for key in candidate_keys:
|
| 67 |
+
if key in graph:
|
| 68 |
+
coords = graph[key]
|
| 69 |
+
if not torch.is_tensor(coords):
|
| 70 |
+
raise TypeError(f"graph['{key}'] is not a torch.Tensor, got {type(coords)}")
|
| 71 |
+
graph[key] = coords.detach().clone().requires_grad_(True)
|
| 72 |
+
return
|
| 73 |
+
|
| 74 |
+
raise KeyError(f"Could not find coordinate tensor in graph keys: {list(graph.keys())}")
|
| 75 |
+
|
| 76 |
+
# Case 2: object with attributes, e.g. RadiusGraph
|
| 77 |
+
for key in candidate_keys:
|
| 78 |
+
if hasattr(graph, key):
|
| 79 |
+
coords = getattr(graph, key)
|
| 80 |
+
|
| 81 |
+
if torch.is_tensor(coords):
|
| 82 |
+
setattr(graph, key, coords.detach().clone().requires_grad_(True))
|
| 83 |
+
return
|
| 84 |
+
|
| 85 |
+
# Helpful debug print
|
| 86 |
+
attrs = [a for a in dir(graph) if not a.startswith("_")]
|
| 87 |
+
raise TypeError(
|
| 88 |
+
f"Unsupported graph type for coord refresh: {type(graph)}\n"
|
| 89 |
+
f"Available public attributes include:\n{attrs[:80]}"
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
def main():
|
| 93 |
+
ap = argparse.ArgumentParser(description="Benchmark MatRIS speed on a single ~96-atom structure.")
|
| 94 |
+
ap.add_argument("--xyz", required=True, help="Path to extxyz dataset (or single-structure xyz)")
|
| 95 |
+
ap.add_argument("--model-name", default="none", choices=["none", "matris_10m_oam", "matris_10m_mp"])
|
| 96 |
+
ap.add_argument("--device", default=None, help='Device, e.g. "cuda" or "cpu" (default: auto)')
|
| 97 |
+
ap.add_argument("--target-natoms", type=int, default=96, help="Pick structure with natoms closest to this (default 96)")
|
| 98 |
+
ap.add_argument("--index", default=":", help='ASE selector for candidate pool (default ":" for all)')
|
| 99 |
+
ap.add_argument("--pick", choices=["closest", "first", "given"], default="closest",
|
| 100 |
+
help="How to pick the structure: closest to target natoms, first, or given index")
|
| 101 |
+
ap.add_argument("--given-index", type=int, default=0, help="Used when --pick given")
|
| 102 |
+
ap.add_argument("--warmup", type=int, default=50, help="Warmup iterations (default 50)")
|
| 103 |
+
ap.add_argument("--iters", type=int, default=300, help="Timed iterations (default 300)")
|
| 104 |
+
ap.add_argument("--include-graph", action="store_true", help="Include structure->graph conversion time in each iteration")
|
| 105 |
+
ap.add_argument("--disable-ref-energy", action="store_true",
|
| 106 |
+
help="Disable MatRIS composition reference energy (mpa AtomRef) during inference")
|
| 107 |
+
ap.add_argument(
|
| 108 |
+
"--is-conservative",
|
| 109 |
+
action=argparse.BooleanOptionalAction,
|
| 110 |
+
default=True,
|
| 111 |
+
help=(
|
| 112 |
+
"Use conservative forces F = -dE/dx. "
|
| 113 |
+
"Use --no-is-conservative for direct force prediction."
|
| 114 |
+
),
|
| 115 |
+
)
|
| 116 |
+
args = ap.parse_args()
|
| 117 |
+
|
| 118 |
+
# device auto
|
| 119 |
+
if args.device is None:
|
| 120 |
+
try:
|
| 121 |
+
import torch
|
| 122 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 123 |
+
except Exception:
|
| 124 |
+
device = "cpu"
|
| 125 |
+
else:
|
| 126 |
+
device = args.device
|
| 127 |
+
|
| 128 |
+
# Lazy imports for MatRIS + adaptor
|
| 129 |
+
try:
|
| 130 |
+
import torch
|
| 131 |
+
from pymatgen.io.ase import AseAtomsAdaptor
|
| 132 |
+
from matris.model.model import MatRIS
|
| 133 |
+
except Exception as e:
|
| 134 |
+
raise SystemExit(f"Failed imports. Ensure MatRIS + pymatgen + torch installed.\nOriginal error: {e}")
|
| 135 |
+
|
| 136 |
+
atoms_list = read(args.xyz, index=args.index)
|
| 137 |
+
if isinstance(atoms_list, Atoms):
|
| 138 |
+
atoms_list = [atoms_list]
|
| 139 |
+
if len(atoms_list) == 0:
|
| 140 |
+
raise SystemExit("No structures read from --xyz/--index.")
|
| 141 |
+
|
| 142 |
+
if args.pick == "first":
|
| 143 |
+
idx = 0
|
| 144 |
+
elif args.pick == "given":
|
| 145 |
+
idx = int(args.given_index)
|
| 146 |
+
if idx < 0 or idx >= len(atoms_list):
|
| 147 |
+
raise SystemExit(f"--given-index {idx} out of range (0..{len(atoms_list)-1})")
|
| 148 |
+
else:
|
| 149 |
+
idx = pick_index_by_natoms(atoms_list, args.target_natoms)
|
| 150 |
+
|
| 151 |
+
atoms = atoms_list[idx]
|
| 152 |
+
n_atoms = len(atoms)
|
| 153 |
+
|
| 154 |
+
if args.model_name is None or args.model_name == "none":
|
| 155 |
+
print("Training from scratch")
|
| 156 |
+
model = MatRIS(is_conservation=args.is_conservative).to(args.device)
|
| 157 |
+
else:
|
| 158 |
+
print(f"Starting from foundation model: {args.model_name}")
|
| 159 |
+
model = MatRIS.load(args.model_name,
|
| 160 |
+
device=args.device,
|
| 161 |
+
cache_dir="foundation_models",)
|
| 162 |
+
# override loaded setting if needed
|
| 163 |
+
model.force_stress_head.is_conservation = args.is_conservative
|
| 164 |
+
|
| 165 |
+
model.eval()
|
| 166 |
+
|
| 167 |
+
if args.disable_ref_energy:
|
| 168 |
+
# The head uses model.reference_energy if present
|
| 169 |
+
model.reference_energy = None
|
| 170 |
+
|
| 171 |
+
adaptor = AseAtomsAdaptor()
|
| 172 |
+
|
| 173 |
+
def build_graph():
|
| 174 |
+
structure = adaptor.get_structure(atoms)
|
| 175 |
+
g = model.graph_converter(structure).to(device)
|
| 176 |
+
return g
|
| 177 |
+
|
| 178 |
+
# Prebuild graph for forward-only timing
|
| 179 |
+
graph0 = build_graph()
|
| 180 |
+
|
| 181 |
+
def one_call():
|
| 182 |
+
# optionally include graph conversion
|
| 183 |
+
g = build_graph() if args.include_graph else graph0
|
| 184 |
+
|
| 185 |
+
# ensure grad leaf coords each call
|
| 186 |
+
refresh_grad_coords(g)
|
| 187 |
+
|
| 188 |
+
out = model([g], task="ef", is_training=False)
|
| 189 |
+
# touch outputs so work is not optimized away
|
| 190 |
+
e = out["e"][0]
|
| 191 |
+
f = out["f"][0]
|
| 192 |
+
# small reduction
|
| 193 |
+
_ = float(e.detach().cpu()) + float(f.detach().abs().mean().cpu())
|
| 194 |
+
return
|
| 195 |
+
|
| 196 |
+
# Warmup
|
| 197 |
+
for _ in range(args.warmup):
|
| 198 |
+
one_call()
|
| 199 |
+
maybe_cuda_sync(device)
|
| 200 |
+
|
| 201 |
+
# Timed loop
|
| 202 |
+
t0 = time.time()
|
| 203 |
+
for _ in range(args.iters):
|
| 204 |
+
one_call()
|
| 205 |
+
maybe_cuda_sync(device)
|
| 206 |
+
t1 = time.time()
|
| 207 |
+
|
| 208 |
+
dt = (t1 - t0) / float(args.iters)
|
| 209 |
+
ms = dt * 1e3
|
| 210 |
+
us_per_atom = (dt / max(1, n_atoms)) * 1e6
|
| 211 |
+
|
| 212 |
+
print("MatRIS speed benchmark")
|
| 213 |
+
print(f" device: {device}")
|
| 214 |
+
print(f" model: {args.model_name}")
|
| 215 |
+
print(f" conservative: {args.is_conservative}")
|
| 216 |
+
print(f" dataset: {Path(args.xyz)}")
|
| 217 |
+
print(f" selected index: {idx}")
|
| 218 |
+
print(f" natoms: {n_atoms}")
|
| 219 |
+
print(f" include graph build: {args.include_graph}")
|
| 220 |
+
print(f" ref energy enabled: {not args.disable_ref_energy}")
|
| 221 |
+
print(f" warmup iters: {args.warmup}")
|
| 222 |
+
print(f" timed iters: {args.iters}")
|
| 223 |
+
print(f" avg time / call: {ms:.4f} ms")
|
| 224 |
+
print(f" avg time / atom: {us_per_atom:.4f} µs/atom")
|
| 225 |
+
|
| 226 |
+
if __name__ == "__main__":
|
| 227 |
+
main()
|
models/matris/eval_matris.py
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import collections
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch import nn
|
| 9 |
+
from torch.utils.data import DataLoader
|
| 10 |
+
from tqdm import tqdm
|
| 11 |
+
|
| 12 |
+
from matris.model.model import MatRIS
|
| 13 |
+
from matris.model.reference_energy import AtomRef
|
| 14 |
+
from matris_dataset import (
|
| 15 |
+
MatRISDataset,
|
| 16 |
+
matris_collate_fn,
|
| 17 |
+
move_matris_batch_to_device,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
REPO_ROOT = Path(__file__).resolve().parents[2]
|
| 21 |
+
|
| 22 |
+
TEST_PATH = REPO_ROOT / "datasets/xyz/testdata.xyz"
|
| 23 |
+
SAVE_DIR = REPO_ROOT / "models/matris/checkpoints_matris"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
E0S_DEFAULT = {
|
| 28 |
+
1: 2.467478445, # H
|
| 29 |
+
6: 8.0273263225, # C
|
| 30 |
+
8: 3.334308855, # O
|
| 31 |
+
22: 4.879036065, # Ti
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
def build_random_init_model(
|
| 35 |
+
device: str,
|
| 36 |
+
is_conservative: bool,
|
| 37 |
+
use_reference_energy: bool,
|
| 38 |
+
model_name: str | None = None,
|
| 39 |
+
) -> MatRIS:
|
| 40 |
+
print("Building RANDOM INIT model")
|
| 41 |
+
print(f"Requested model_name: {model_name}")
|
| 42 |
+
|
| 43 |
+
if model_name is None or model_name == "none" or model_name == "":
|
| 44 |
+
print("Random scratch MatRIS architecture")
|
| 45 |
+
model = MatRIS(is_conservation=is_conservative)
|
| 46 |
+
else:
|
| 47 |
+
print(f"Random foundation architecture: {model_name}")
|
| 48 |
+
model = MatRIS.load(
|
| 49 |
+
model_name,
|
| 50 |
+
device="cpu",
|
| 51 |
+
cache_dir="foundation_models",
|
| 52 |
+
)
|
| 53 |
+
model.force_stress_head.is_conservation = is_conservative
|
| 54 |
+
|
| 55 |
+
if use_reference_energy:
|
| 56 |
+
model.reference_energy = build_reference_energy_module(model, E0S_DEFAULT)
|
| 57 |
+
else:
|
| 58 |
+
model.reference_energy = None
|
| 59 |
+
|
| 60 |
+
model = model.to(device)
|
| 61 |
+
model.eval()
|
| 62 |
+
return model
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def build_reference_energy_module(model: MatRIS, e0_dict: dict[int, float]) -> AtomRef:
|
| 66 |
+
atom_ref = AtomRef(reference_energy="mptrj", is_intensive=model.is_intensive)
|
| 67 |
+
|
| 68 |
+
weight = torch.zeros(94, dtype=torch.float32)
|
| 69 |
+
for Z, e0 in e0_dict.items():
|
| 70 |
+
weight[Z - 1] = e0
|
| 71 |
+
|
| 72 |
+
state_dict = collections.OrderedDict()
|
| 73 |
+
state_dict["weight"] = weight.view(1, 94)
|
| 74 |
+
atom_ref.fc.load_state_dict(state_dict)
|
| 75 |
+
|
| 76 |
+
atom_ref.fitted = True
|
| 77 |
+
for p in atom_ref.parameters():
|
| 78 |
+
p.requires_grad = False
|
| 79 |
+
|
| 80 |
+
return atom_ref
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class MatRISEvalLoss(nn.Module):
|
| 84 |
+
def __init__(self):
|
| 85 |
+
super().__init__()
|
| 86 |
+
self.l1_sum = nn.L1Loss(reduction="sum")
|
| 87 |
+
self.l2_sum = nn.MSELoss(reduction="sum")
|
| 88 |
+
|
| 89 |
+
def forward(self, pred_forces, ref_forces, pred_energy, ref_energy):
|
| 90 |
+
loss_forces_l1 = self.l1_sum(pred_forces, ref_forces)
|
| 91 |
+
loss_energy_l1 = self.l1_sum(pred_energy, ref_energy)
|
| 92 |
+
|
| 93 |
+
loss_forces_l2 = self.l2_sum(pred_forces, ref_forces)
|
| 94 |
+
loss_energy_l2 = self.l2_sum(pred_energy, ref_energy)
|
| 95 |
+
|
| 96 |
+
return loss_forces_l1, loss_energy_l1, loss_forces_l2, loss_energy_l2
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def load_matris_from_checkpoint(
|
| 100 |
+
checkpoint_path: str | Path,
|
| 101 |
+
device: str,
|
| 102 |
+
is_conservative: bool,
|
| 103 |
+
use_reference_energy: bool,
|
| 104 |
+
model_name: str | None = None,
|
| 105 |
+
) -> MatRIS:
|
| 106 |
+
checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
|
| 107 |
+
|
| 108 |
+
print(f"Requested model_name: {model_name}")
|
| 109 |
+
|
| 110 |
+
if model_name is None or model_name == "none" or model_name == "":
|
| 111 |
+
print("Loading scratch MatRIS architecture")
|
| 112 |
+
model = MatRIS(is_conservation=is_conservative)
|
| 113 |
+
else:
|
| 114 |
+
print(f"Loading foundation model architecture: {model_name}")
|
| 115 |
+
model = MatRIS.load(
|
| 116 |
+
model_name,
|
| 117 |
+
device="cpu",
|
| 118 |
+
cache_dir="foundation_models",
|
| 119 |
+
)
|
| 120 |
+
model.force_stress_head.is_conservation = is_conservative
|
| 121 |
+
|
| 122 |
+
if use_reference_energy:
|
| 123 |
+
model.reference_energy = build_reference_energy_module(model, E0S_DEFAULT)
|
| 124 |
+
else:
|
| 125 |
+
model.reference_energy = None
|
| 126 |
+
|
| 127 |
+
model.load_state_dict(checkpoint["model_state_dict"], strict=True)
|
| 128 |
+
|
| 129 |
+
model = model.to(device)
|
| 130 |
+
model.eval()
|
| 131 |
+
return model
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def evaluate(model, loader, loss_fn, use_grad, device, desc="Eval"):
|
| 135 |
+
model.eval()
|
| 136 |
+
|
| 137 |
+
sum_abs_dF = torch.tensor(0.0, device=device)
|
| 138 |
+
sum_abs_dE = torch.tensor(0.0, device=device)
|
| 139 |
+
|
| 140 |
+
sum_sq_dF = torch.tensor(0.0, device=device)
|
| 141 |
+
sum_sq_dE = torch.tensor(0.0, device=device)
|
| 142 |
+
|
| 143 |
+
sum_abs_dE_per_atom = torch.tensor(0.0, device=device)
|
| 144 |
+
sum_sq_dE_per_atom = torch.tensor(0.0, device=device)
|
| 145 |
+
|
| 146 |
+
total_force_components = torch.tensor(0.0, device=device)
|
| 147 |
+
total_systems = torch.tensor(0.0, device=device)
|
| 148 |
+
total_atoms = torch.tensor(0.0, device=device)
|
| 149 |
+
|
| 150 |
+
# Important: no torch.no_grad(), because conservative forces need autograd.
|
| 151 |
+
for batch in tqdm(loader, desc=desc, dynamic_ncols=True):
|
| 152 |
+
# There's one sample in testset where this happens
|
| 153 |
+
if batch is None:
|
| 154 |
+
continue
|
| 155 |
+
batch = move_matris_batch_to_device(batch, device=device)
|
| 156 |
+
|
| 157 |
+
with torch.set_grad_enabled(use_grad):
|
| 158 |
+
out = model(batch["graphs"], task="ef", is_training=False)
|
| 159 |
+
|
| 160 |
+
n_atoms_per_graph = out["atoms_per_graph"].float()
|
| 161 |
+
natoms_batch = n_atoms_per_graph.sum()
|
| 162 |
+
n_systems = n_atoms_per_graph.numel()
|
| 163 |
+
|
| 164 |
+
pred_energy = out["e"]
|
| 165 |
+
if model.is_intensive:
|
| 166 |
+
pred_energy = pred_energy * n_atoms_per_graph
|
| 167 |
+
|
| 168 |
+
ref_energy = batch["energy"]
|
| 169 |
+
|
| 170 |
+
pred_forces = torch.cat(out["f"], dim=0)
|
| 171 |
+
ref_forces = torch.cat(batch["forces"], dim=0)
|
| 172 |
+
|
| 173 |
+
loss_forces_l1, loss_energy_l1, loss_forces_l2, loss_energy_l2 = loss_fn(
|
| 174 |
+
pred_forces=pred_forces,
|
| 175 |
+
ref_forces=ref_forces,
|
| 176 |
+
pred_energy=pred_energy,
|
| 177 |
+
ref_energy=ref_energy,
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
dE = pred_energy.view(-1) - ref_energy.view(-1)
|
| 181 |
+
abs_dE = dE.abs()
|
| 182 |
+
|
| 183 |
+
total_atoms += natoms_batch.detach()
|
| 184 |
+
total_force_components += (3.0 * natoms_batch).detach()
|
| 185 |
+
total_systems += torch.tensor(float(n_systems), device=device)
|
| 186 |
+
|
| 187 |
+
sum_abs_dF += loss_forces_l1.detach()
|
| 188 |
+
sum_abs_dE += loss_energy_l1.detach()
|
| 189 |
+
|
| 190 |
+
sum_sq_dF += loss_forces_l2.detach()
|
| 191 |
+
sum_sq_dE += loss_energy_l2.detach()
|
| 192 |
+
|
| 193 |
+
sum_abs_dE_per_atom += (abs_dE / n_atoms_per_graph).sum().detach()
|
| 194 |
+
sum_sq_dE_per_atom += ((dE / n_atoms_per_graph) ** 2).sum().detach()
|
| 195 |
+
mae_F = (sum_abs_dF / total_force_components).item()
|
| 196 |
+
mae_E_sys = (sum_abs_dE / total_systems).item()
|
| 197 |
+
mae_E_atom_weighted = (sum_abs_dE / total_atoms).item()
|
| 198 |
+
mae_E_atom_mace = (sum_abs_dE_per_atom / total_systems).item()
|
| 199 |
+
|
| 200 |
+
rmse_F = torch.sqrt(sum_sq_dF / total_force_components).item()
|
| 201 |
+
rmse_E_sys = torch.sqrt(sum_sq_dE / total_systems).item()
|
| 202 |
+
rmse_E_atom_weighted = torch.sqrt(sum_sq_dE / total_atoms).item()
|
| 203 |
+
rmse_E_atom_mace = torch.sqrt(sum_sq_dE_per_atom / total_systems).item()
|
| 204 |
+
|
| 205 |
+
print()
|
| 206 |
+
print("========== MatRIS Evaluation ==========")
|
| 207 |
+
print(f"MAE(F components) [eV/A]: {mae_F:.6f}")
|
| 208 |
+
print(f"MAE(E per system) [eV]: {mae_E_sys:.6f}")
|
| 209 |
+
print(f"MAE(E per atom, weighted) [eV]: {mae_E_atom_weighted:.6f}")
|
| 210 |
+
print(f"MAE(E per atom, MACE) [eV]: {mae_E_atom_mace:.6f}")
|
| 211 |
+
print(f"MAE(E per atom, MACE) [meV]: {1000.0 * mae_E_atom_mace:.3f}")
|
| 212 |
+
print()
|
| 213 |
+
print(f"RMSE(F components) [eV/A]: {rmse_F:.6f}")
|
| 214 |
+
print(f"RMSE(E per system) [eV]: {rmse_E_sys:.6f}")
|
| 215 |
+
print(f"RMSE(E per atom, weighted) [eV]: {rmse_E_atom_weighted:.6f}")
|
| 216 |
+
print(f"RMSE(E per atom, MACE) [eV]: {rmse_E_atom_mace:.6f}")
|
| 217 |
+
print(f"RMSE(E per atom, MACE) [meV]: {1000.0 * rmse_E_atom_mace:.3f}")
|
| 218 |
+
print("=======================================")
|
| 219 |
+
|
| 220 |
+
return {
|
| 221 |
+
"mae_F": mae_F,
|
| 222 |
+
"mae_E_sys": mae_E_sys,
|
| 223 |
+
"mae_E_atom_weighted": mae_E_atom_weighted,
|
| 224 |
+
"mae_E_atom_mace": mae_E_atom_mace,
|
| 225 |
+
"rmse_F": rmse_F,
|
| 226 |
+
"rmse_E_sys": rmse_E_sys,
|
| 227 |
+
"rmse_E_atom_weighted": rmse_E_atom_weighted,
|
| 228 |
+
"rmse_E_atom_mace": rmse_E_atom_mace,
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def parse_args():
|
| 233 |
+
parser = argparse.ArgumentParser(description="Evaluate a MatRIS checkpoint.")
|
| 234 |
+
|
| 235 |
+
parser.add_argument("--test_path", type=str, default=str(TEST_PATH))
|
| 236 |
+
parser.add_argument("--checkpoint", type=str, default=None)
|
| 237 |
+
parser.add_argument(
|
| 238 |
+
"--random_init",
|
| 239 |
+
action="store_true",
|
| 240 |
+
help="Evaluate a randomly initialized model instead of loading checkpoint weights.",
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
parser.add_argument("--batch_size", type=int, default=1)
|
| 244 |
+
parser.add_argument("--num_workers", type=int, default=0)
|
| 245 |
+
parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu")
|
| 246 |
+
|
| 247 |
+
parser.add_argument(
|
| 248 |
+
"--is_conservative",
|
| 249 |
+
action=argparse.BooleanOptionalAction,
|
| 250 |
+
default=True,
|
| 251 |
+
help="Use conservative forces.",
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
parser.add_argument(
|
| 255 |
+
"--use_reference_energy",
|
| 256 |
+
action=argparse.BooleanOptionalAction,
|
| 257 |
+
default=True,
|
| 258 |
+
help="Use the same custom AtomRef reference energies as training.",
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
parser.add_argument("--model_name", type=str, default="")
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
return parser.parse_args()
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def main():
|
| 271 |
+
args = parse_args()
|
| 272 |
+
|
| 273 |
+
print(f"Device: {args.device}")
|
| 274 |
+
print(f"Checkpoint: {args.checkpoint}")
|
| 275 |
+
print(f"Random init: {args.random_init}")
|
| 276 |
+
print(f"Test path: {args.test_path}")
|
| 277 |
+
print(f"Conservative forces: {args.is_conservative}")
|
| 278 |
+
print(f"Use reference energy: {args.use_reference_energy}")
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
if args.random_init:
|
| 282 |
+
print("Evaluing random init model")
|
| 283 |
+
model = build_random_init_model(
|
| 284 |
+
device=args.device,
|
| 285 |
+
is_conservative=args.is_conservative,
|
| 286 |
+
use_reference_energy=args.use_reference_energy,
|
| 287 |
+
model_name=args.model_name,
|
| 288 |
+
)
|
| 289 |
+
else:
|
| 290 |
+
if args.checkpoint is None:
|
| 291 |
+
raise ValueError("--checkpoint is required unless --random_init is used.")
|
| 292 |
+
|
| 293 |
+
model = load_matris_from_checkpoint(
|
| 294 |
+
checkpoint_path=args.checkpoint,
|
| 295 |
+
device=args.device,
|
| 296 |
+
is_conservative=args.is_conservative,
|
| 297 |
+
use_reference_energy=args.use_reference_energy,
|
| 298 |
+
model_name=args.model_name,
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
use_grad = model.force_stress_head.is_conservation
|
| 303 |
+
|
| 304 |
+
print(f'use_grad is: {use_grad}')
|
| 305 |
+
|
| 306 |
+
# NOTE Try a random init model.
|
| 307 |
+
# print("Running random Matrsi model")
|
| 308 |
+
# model = MatRIS(is_conservation=args.is_conservative).to(args.device)
|
| 309 |
+
# model.reference_energy = build_reference_energy_module(model, E0S_DEFAULT).to(args.device)
|
| 310 |
+
|
| 311 |
+
test_dataset = MatRISDataset(args.test_path, model=model)
|
| 312 |
+
|
| 313 |
+
test_loader = DataLoader(
|
| 314 |
+
test_dataset,
|
| 315 |
+
batch_size=args.batch_size,
|
| 316 |
+
shuffle=False,
|
| 317 |
+
num_workers=args.num_workers,
|
| 318 |
+
collate_fn=matris_collate_fn,
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
loss_fn = MatRISEvalLoss()
|
| 322 |
+
|
| 323 |
+
evaluate(
|
| 324 |
+
model=model,
|
| 325 |
+
loader=test_loader,
|
| 326 |
+
loss_fn=loss_fn,
|
| 327 |
+
use_grad = use_grad,
|
| 328 |
+
device=args.device,
|
| 329 |
+
desc="MatRIS Eval",
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
if __name__ == "__main__":
|
| 334 |
+
main()
|
models/matris/example/cif_file/demo.cif
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# generated using pymatgen
|
| 2 |
+
data_Pu2Si3
|
| 3 |
+
_symmetry_space_group_name_H-M 'P 1'
|
| 4 |
+
_cell_length_a 4.26022438
|
| 5 |
+
_cell_length_b 7.16692875
|
| 6 |
+
_cell_length_c 7.16692875
|
| 7 |
+
_cell_angle_alpha 90.00000000
|
| 8 |
+
_cell_angle_beta 90.00000000
|
| 9 |
+
_cell_angle_gamma 90.00000000
|
| 10 |
+
_symmetry_Int_Tables_number 1
|
| 11 |
+
_chemical_formula_structural Pu2Si3
|
| 12 |
+
_chemical_formula_sum 'Pu4 Si6'
|
| 13 |
+
_cell_volume 218.82586168
|
| 14 |
+
_cell_formula_units_Z 2
|
| 15 |
+
loop_
|
| 16 |
+
_symmetry_equiv_pos_site_id
|
| 17 |
+
_symmetry_equiv_pos_as_xyz
|
| 18 |
+
1 'x, y, z'
|
| 19 |
+
loop_
|
| 20 |
+
_atom_site_type_symbol
|
| 21 |
+
_atom_site_label
|
| 22 |
+
_atom_site_symmetry_multiplicity
|
| 23 |
+
_atom_site_fract_x
|
| 24 |
+
_atom_site_fract_y
|
| 25 |
+
_atom_site_fract_z
|
| 26 |
+
_atom_site_occupancy
|
| 27 |
+
Pu Pu0 1 0.50000000 0.67597000 0.82403000 1.0
|
| 28 |
+
Pu Pu1 1 0.50000000 0.32403000 0.17597000 1.0
|
| 29 |
+
Pu Pu2 1 0.50000000 0.17597000 0.67597000 1.0
|
| 30 |
+
Pu Pu3 1 0.50000000 0.82403000 0.32403000 1.0
|
| 31 |
+
Si Si4 1 0.00000000 0.88257100 0.61742900 1.0
|
| 32 |
+
Si Si5 1 0.00000000 0.11742900 0.38257100 1.0
|
| 33 |
+
Si Si6 1 0.00000000 0.38257100 0.88257100 1.0
|
| 34 |
+
Si Si7 1 0.00000000 0.61742900 0.11742900 1.0
|
| 35 |
+
Si Si8 1 0.00000000 0.00000000 0.00000000 1.0
|
| 36 |
+
Si Si9 1 0.00000000 0.50000000 0.50000000 1.0
|
models/matris/example/test_ralexation.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ase
|
| 2 |
+
from ase.build import bulk
|
| 3 |
+
import torch
|
| 4 |
+
from pymatgen.core.structure import Structure
|
| 5 |
+
from matris.applications.relax import StructOptimizer
|
| 6 |
+
|
| 7 |
+
model_name = "matris_10m_oam"
|
| 8 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 9 |
+
|
| 10 |
+
matris_opt = StructOptimizer(
|
| 11 |
+
model=model_name,
|
| 12 |
+
task = "efsm",
|
| 13 |
+
optimizer = "FIRE", # FIRE, BFGS ...
|
| 14 |
+
device=device
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
atom = Structure.from_file(f"example/cif_file/demo.cif")
|
| 18 |
+
|
| 19 |
+
max_steps = 500
|
| 20 |
+
fmax = 0.05
|
| 21 |
+
opt_result = matris_opt.relax(
|
| 22 |
+
atoms=atom, # pymatgen.Structure or ase.Atoms
|
| 23 |
+
verbose=True,
|
| 24 |
+
steps=max_steps,
|
| 25 |
+
fmax=fmax,
|
| 26 |
+
relax_cell=max_steps > 0,
|
| 27 |
+
ase_filter="FrechetCellFilter",
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
trajectory = opt_result['trajectory']
|
| 31 |
+
energy = trajectory.energies[-1]
|
| 32 |
+
force = trajectory.forces[-1]
|
| 33 |
+
stress = trajectory.stresses[-1]
|
| 34 |
+
magmom = trajectory.magmoms[-1]
|
| 35 |
+
|
| 36 |
+
final_structure = opt_result['final_structure']
|
models/matris/foundation_models/MatRIS_10M_MP.pth.tar
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:333b6019ec901a4bce9735ef28136d7da637899272825ff7ef9c84587b22f2d9
|
| 3 |
+
size 42184483
|
models/matris/foundation_models/MatRIS_10M_OAM.pth.tar
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c033abc53601a74f10d9b7fec0f658220c013c3b11d4d405f1d32136d4c2b067
|
| 3 |
+
size 42273174
|
models/matris/matris/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from importlib.metadata import version
|
| 2 |
+
|
| 3 |
+
from importlib.metadata import PackageNotFoundError, version
|
| 4 |
+
|
| 5 |
+
try:
|
| 6 |
+
__version__ = version(__name__) # read from pyproject.toml
|
| 7 |
+
except PackageNotFoundError:
|
| 8 |
+
__version__ = "unknown"
|
models/matris/matris/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (325 Bytes). View file
|
|
|
models/matris/matris/applications/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from .base import MatRISCalculator
|
| 3 |
+
from .md import MolecularDynamics
|
| 4 |
+
from .relax import StructOptimizer
|
models/matris/matris/applications/base.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ase import Atoms, units
|
| 2 |
+
from ase.calculators.calculator import Calculator, all_changes, all_properties
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from ..model.model import MatRIS
|
| 6 |
+
|
| 7 |
+
from pymatgen.io.ase import AseAtomsAdaptor
|
| 8 |
+
from ..graph import RadiusGraph
|
| 9 |
+
|
| 10 |
+
from ase.optimize import (
|
| 11 |
+
BFGS, BFGSLineSearch,
|
| 12 |
+
FIRE, LBFGS,
|
| 13 |
+
LBFGSLineSearch, MDMin
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
names = [
|
| 17 |
+
"BFGS", "BFGSLineSearch",
|
| 18 |
+
"FIRE", "LBFGS",
|
| 19 |
+
"LBFGSLineSearch", "MDMin"
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
OPTIMIZERS = {name: globals()[name] for name in names}
|
| 23 |
+
|
| 24 |
+
class MatRISCalculator(Calculator):
|
| 25 |
+
"""MatRIS Calculator for ASE applications."""
|
| 26 |
+
|
| 27 |
+
implemented_properties = ("energy", "forces", "stress", "magmoms") # type: ignore
|
| 28 |
+
|
| 29 |
+
def __init__(
|
| 30 |
+
self,
|
| 31 |
+
model: str = "matris_10m_oam",
|
| 32 |
+
task: str = "efs",
|
| 33 |
+
device: str = "cpu",
|
| 34 |
+
**kwargs,
|
| 35 |
+
) -> None:
|
| 36 |
+
"""
|
| 37 |
+
Args:
|
| 38 |
+
model (MatRIS): Instance of a MatRIS model. If set to None, the default MatRIS is loaded.
|
| 39 |
+
task (str): The prediction task. Can be 'e', 'em', 'ef', 'efs', 'efsm'.
|
| 40 |
+
device (str): The device to be used for predictions,
|
| 41 |
+
stress_unit (float): the conversion factor to convert GPa(MatRIS default) to eV/A^3.
|
| 42 |
+
**kwargs: Passed to the Calculator parent class.
|
| 43 |
+
"""
|
| 44 |
+
super().__init__(**kwargs)
|
| 45 |
+
self.task=task
|
| 46 |
+
self.device = device
|
| 47 |
+
self.model = MatRIS.load(model_name=model, device=self.device)
|
| 48 |
+
|
| 49 |
+
self.stress_unit = units.GPa
|
| 50 |
+
key = ["atoms_per_graph", "ref_energy"]
|
| 51 |
+
for t in task:
|
| 52 |
+
key.append(t)
|
| 53 |
+
self.key = set(key)
|
| 54 |
+
|
| 55 |
+
def calculate(
|
| 56 |
+
self,
|
| 57 |
+
atoms: Atoms,
|
| 58 |
+
properties: list,
|
| 59 |
+
system_changes: list,
|
| 60 |
+
) -> None:
|
| 61 |
+
|
| 62 |
+
properties = properties or all_properties
|
| 63 |
+
system_changes = system_changes or all_changes
|
| 64 |
+
super().calculate(
|
| 65 |
+
atoms=atoms,
|
| 66 |
+
properties=properties,
|
| 67 |
+
system_changes=system_changes,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
pbc = atoms.get_pbc()
|
| 71 |
+
if (not pbc[0]) or (not pbc[1]) or (not pbc[2]):
|
| 72 |
+
pos = atoms.get_positions()
|
| 73 |
+
cell = np.array(atoms.get_cell())
|
| 74 |
+
|
| 75 |
+
pbc_x = pbc[0]
|
| 76 |
+
pbc_y = pbc[1]
|
| 77 |
+
pbc_z = pbc[2]
|
| 78 |
+
identity = np.identity(3, dtype=float)
|
| 79 |
+
max_positions = np.max(np.absolute(pos)) + 1
|
| 80 |
+
|
| 81 |
+
cutoff = self.model.config["pairwise_cutoff"]
|
| 82 |
+
expand = max(5, self.model.config["num_layers"])
|
| 83 |
+
|
| 84 |
+
# Extend cell in non-periodic directions
|
| 85 |
+
if not pbc_x:
|
| 86 |
+
cell[0, :] = max_positions * expand * cutoff * identity[0, :]
|
| 87 |
+
if not pbc_y:
|
| 88 |
+
cell[1, :] = max_positions * expand * cutoff * identity[1, :]
|
| 89 |
+
if not pbc_z:
|
| 90 |
+
cell[2, :] = max_positions * expand * cutoff * identity[2, :]
|
| 91 |
+
|
| 92 |
+
# update
|
| 93 |
+
atoms.set_cell(cell, scale_atoms=False)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
structure = AseAtomsAdaptor.get_structure(atoms)
|
| 97 |
+
graph = self.model.graph_converter(structure).to(self.device) # convert to List
|
| 98 |
+
|
| 99 |
+
graphs = [graph] if isinstance(graph, RadiusGraph) else graph
|
| 100 |
+
|
| 101 |
+
model_prediction = self.model(
|
| 102 |
+
graphs,
|
| 103 |
+
task = self.task,
|
| 104 |
+
is_training = False,
|
| 105 |
+
)
|
| 106 |
+
model_predictions = {}
|
| 107 |
+
|
| 108 |
+
for key in self.key & set(model_prediction.keys()):
|
| 109 |
+
for idx, tensor in enumerate(model_prediction[key]):
|
| 110 |
+
model_predictions[key] = tensor.cpu().detach().numpy()
|
| 111 |
+
|
| 112 |
+
# Convert Result
|
| 113 |
+
n_atoms = 1 if not self.model.is_intensive else structure.composition.num_atoms
|
| 114 |
+
|
| 115 |
+
self.results.update(
|
| 116 |
+
ref_energy=model_predictions["ref_energy"] * n_atoms,
|
| 117 |
+
energy=model_predictions["e"] * n_atoms, # Total Energy
|
| 118 |
+
forces=model_predictions.get("f", None),
|
| 119 |
+
# Stress: GPa -> eV/A^3
|
| 120 |
+
stress=model_predictions.get("s", None) * self.stress_unit if model_predictions.get("s", None) is not None else None,
|
| 121 |
+
magmoms=model_predictions.get("m", None),
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class TrajectoryObserver:
|
| 126 |
+
# ref: https://github.com/CederGroupHub/chgnet
|
| 127 |
+
|
| 128 |
+
def __init__(self, atoms: Atoms) -> None:
|
| 129 |
+
|
| 130 |
+
self.atoms = atoms
|
| 131 |
+
self.energies: list[float] = []
|
| 132 |
+
self.forces: list[np.ndarray] = []
|
| 133 |
+
self.stresses: list[np.ndarray] = []
|
| 134 |
+
self.magmoms: list[np.ndarray] = []
|
| 135 |
+
self.atom_positions: list[np.ndarray] = []
|
| 136 |
+
self.cells: list[np.ndarray] = []
|
| 137 |
+
|
| 138 |
+
def __call__(self) -> None:
|
| 139 |
+
"""The logic for saving the properties of an Atoms during the relaxation."""
|
| 140 |
+
self.energies.append(self.compute_energy())
|
| 141 |
+
self.forces.append(self.atoms.get_forces())
|
| 142 |
+
self.stresses.append(self.atoms.get_stress())
|
| 143 |
+
self.magmoms.append(self.atoms.get_magnetic_moments())
|
| 144 |
+
self.atom_positions.append(self.atoms.get_positions())
|
| 145 |
+
self.cells.append(self.atoms.get_cell()[:])
|
| 146 |
+
|
| 147 |
+
def __len__(self) -> int:
|
| 148 |
+
"""The number of steps in the trajectory."""
|
| 149 |
+
return len(self.energies)
|
| 150 |
+
|
| 151 |
+
def compute_energy(self) -> float:
|
| 152 |
+
"""Calculate the potential energy.
|
| 153 |
+
|
| 154 |
+
Returns:
|
| 155 |
+
energy (float): the potential energy.
|
| 156 |
+
"""
|
| 157 |
+
return self.atoms.get_potential_energy()
|
| 158 |
+
|
| 159 |
+
def save(self, filename: str) -> None:
|
| 160 |
+
"""Save the trajectory to file.
|
| 161 |
+
|
| 162 |
+
Args:
|
| 163 |
+
filename (str): filename to save the trajectory
|
| 164 |
+
"""
|
| 165 |
+
out_pkl = {
|
| 166 |
+
"energy": self.energies,
|
| 167 |
+
"forces": self.forces,
|
| 168 |
+
"stresses": self.stresses,
|
| 169 |
+
"magmoms": self.magmoms,
|
| 170 |
+
"atom_positions": self.atom_positions,
|
| 171 |
+
"cell": self.cells,
|
| 172 |
+
"atomic_number": self.atoms.get_atomic_numbers(),
|
| 173 |
+
}
|
| 174 |
+
with open(filename, "wb") as file:
|
| 175 |
+
pickle.dump(out_pkl, file)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class CrystalFeasObserver:
|
| 179 |
+
# ref: https://github.com/CederGroupHub/chgnet
|
| 180 |
+
|
| 181 |
+
def __init__(self, atoms: Atoms) -> None:
|
| 182 |
+
"""Create a CrystalFeasObserver from an Atoms object."""
|
| 183 |
+
self.atoms = atoms
|
| 184 |
+
self.crystal_feature_vectors: list[np.ndarray] = []
|
| 185 |
+
|
| 186 |
+
def __call__(self) -> None:
|
| 187 |
+
"""Record Atoms crystal feature vectors after an MD/relaxation step."""
|
| 188 |
+
self.crystal_feature_vectors.append(self.atoms._calc.results["crystal_fea"])
|
| 189 |
+
|
| 190 |
+
def __len__(self) -> int:
|
| 191 |
+
"""Number of recorded steps."""
|
| 192 |
+
return len(self.crystal_feature_vectors)
|
| 193 |
+
|
| 194 |
+
def save(self, filename: str) -> None:
|
| 195 |
+
"""Save the crystal feature vectors to filename in pickle format."""
|
| 196 |
+
out_pkl = {"crystal_feas": self.crystal_feature_vectors}
|
| 197 |
+
with open(filename, "wb") as file:
|
| 198 |
+
pickle.dump(out_pkl, file)
|
| 199 |
+
|
models/matris/matris/applications/md.py
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ase import Atoms, units
|
| 9 |
+
from ase.io import Trajectory
|
| 10 |
+
from ase.optimize.optimize import Optimizer
|
| 11 |
+
import ase.filters as filter_classes
|
| 12 |
+
from ase.filters import Filter
|
| 13 |
+
from pymatgen.io.ase import AseAtomsAdaptor
|
| 14 |
+
from pymatgen.core.structure import Structure, Molecule
|
| 15 |
+
|
| 16 |
+
from ase.md.npt import NPT
|
| 17 |
+
from ase.md.nptberendsen import Inhomogeneous_NPTBerendsen, NPTBerendsen
|
| 18 |
+
from ase.md.nvtberendsen import NVTBerendsen
|
| 19 |
+
from ase.md.velocitydistribution import MaxwellBoltzmannDistribution, Stationary
|
| 20 |
+
from ase.md.verlet import VelocityVerlet
|
| 21 |
+
|
| 22 |
+
from ..model.model import MatRIS
|
| 23 |
+
|
| 24 |
+
from .base import (
|
| 25 |
+
OPTIMIZERS,
|
| 26 |
+
MatRISCalculator,
|
| 27 |
+
TrajectoryObserver,
|
| 28 |
+
CrystalFeasObserver
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
class MolecularDynamics:
|
| 32 |
+
"""This class is used for Molecular Dynamics."""
|
| 33 |
+
|
| 34 |
+
def __init__(
|
| 35 |
+
self,
|
| 36 |
+
atoms: Atoms | Structure,
|
| 37 |
+
model: str = "matris_10m_oam",
|
| 38 |
+
ensemble: str = "nvt",
|
| 39 |
+
thermostat: str = "Berendsen_inhomogeneous",
|
| 40 |
+
temperature: int = 300,
|
| 41 |
+
starting_temperature: int | None = None,
|
| 42 |
+
timestep: float = 2.0,
|
| 43 |
+
pressure: float = 1.01325e-4,
|
| 44 |
+
taut: float | None = None,
|
| 45 |
+
taup: float | None = None,
|
| 46 |
+
bulk_modulus: float | None = None,
|
| 47 |
+
trajectory: str | Trajectory | None = None,
|
| 48 |
+
logfile: str | None = None,
|
| 49 |
+
loginterval: int = 1,
|
| 50 |
+
crystal_feas_logfile: str | None = None,
|
| 51 |
+
append_trajectory: bool = False,
|
| 52 |
+
task: str = "efs",
|
| 53 |
+
device: str | None = None,
|
| 54 |
+
) -> None:
|
| 55 |
+
"""
|
| 56 |
+
Args:
|
| 57 |
+
atoms (Atoms): atoms to run the MD
|
| 58 |
+
model (MatRIS): instance of a MatRIS model or MatRISCalculator.
|
| 59 |
+
If set to None, the pretrained MatRIS is loaded.
|
| 60 |
+
Default = None
|
| 61 |
+
ensemble (str): choose from 'nve', 'nvt', 'npt'
|
| 62 |
+
Default = "nvt"
|
| 63 |
+
thermostat (str): Thermostat to use
|
| 64 |
+
choose from "Nose-Hoover", "Berendsen", "Berendsen_inhomogeneous"
|
| 65 |
+
Default = "Berendsen_inhomogeneous"
|
| 66 |
+
temperature (float): temperature for MD simulation, in K
|
| 67 |
+
Default = 300
|
| 68 |
+
starting_temperature (float): starting temperature of MD simulation, in K
|
| 69 |
+
if set as None, the MD starts with the momentum carried by ase.Atoms
|
| 70 |
+
if input is a pymatgen.core.Structure, the MD starts at 0K
|
| 71 |
+
Default = None
|
| 72 |
+
timestep (float): time step in fs
|
| 73 |
+
Default = 2
|
| 74 |
+
pressure (float): pressure in GPa
|
| 75 |
+
Can be 3x3 or 6 np.array if thermostat is "Nose-Hoover"
|
| 76 |
+
Default = 1.01325e-4 GPa = 1 atm
|
| 77 |
+
taut (float): time constant for temperature coupling in fs.
|
| 78 |
+
The temperature will be raised to target temperature in approximate
|
| 79 |
+
10 * taut time.
|
| 80 |
+
Default = 100 * timestep
|
| 81 |
+
taup (float): time constant for pressure coupling in fs
|
| 82 |
+
Default = 1000 * timestep
|
| 83 |
+
bulk_modulus (float): bulk modulus of the material in GPa.
|
| 84 |
+
trajectory (str or Trajectory): Attach trajectory object
|
| 85 |
+
Default = None
|
| 86 |
+
logfile (str): open this file for recording MD outputs
|
| 87 |
+
Default = None
|
| 88 |
+
loginterval (int): write to log file every interval steps
|
| 89 |
+
Default = 1
|
| 90 |
+
crystal_feas_logfile (str): open this file for recording crystal features
|
| 91 |
+
during MD. Default = None
|
| 92 |
+
append_trajectory (bool): Whether to append to prev trajectory.
|
| 93 |
+
If false, previous trajectory gets overwritten
|
| 94 |
+
Default = False
|
| 95 |
+
task (str): The prediction task. Can be 'e', 'em', 'ef', 'efs', 'efsm'.
|
| 96 |
+
device (str): the device for the MD run
|
| 97 |
+
Default = None
|
| 98 |
+
"""
|
| 99 |
+
self.ensemble = ensemble
|
| 100 |
+
self.thermostat = thermostat
|
| 101 |
+
if isinstance(atoms, (Structure, Molecule)):
|
| 102 |
+
atoms = AseAtomsAdaptor().get_atoms(atoms)
|
| 103 |
+
|
| 104 |
+
if starting_temperature is not None:
|
| 105 |
+
MaxwellBoltzmannDistribution(
|
| 106 |
+
atoms, temperature_K=starting_temperature, force_temp=True
|
| 107 |
+
)
|
| 108 |
+
Stationary(atoms)
|
| 109 |
+
|
| 110 |
+
self.atoms = atoms
|
| 111 |
+
|
| 112 |
+
self.atoms.calc = MatRISCalculator(
|
| 113 |
+
model=model,
|
| 114 |
+
device=device,
|
| 115 |
+
task=task,
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
if taut is None:
|
| 119 |
+
taut = 100 * timestep
|
| 120 |
+
if taup is None:
|
| 121 |
+
taup = 1000 * timestep
|
| 122 |
+
|
| 123 |
+
if ensemble.lower() == "nve":
|
| 124 |
+
"""
|
| 125 |
+
VelocityVerlet (constant N, V, E) molecular dynamics.
|
| 126 |
+
|
| 127 |
+
Note: it's recommended to use smaller timestep for NVE compared to other
|
| 128 |
+
ensembles, since the VelocityVerlet algorithm assumes a strict conservative
|
| 129 |
+
force field.
|
| 130 |
+
"""
|
| 131 |
+
self.dyn = VelocityVerlet(
|
| 132 |
+
atoms=self.atoms,
|
| 133 |
+
timestep=timestep * units.fs,
|
| 134 |
+
trajectory=trajectory,
|
| 135 |
+
logfile=logfile,
|
| 136 |
+
loginterval=loginterval,
|
| 137 |
+
append_trajectory=append_trajectory,
|
| 138 |
+
)
|
| 139 |
+
print("NVE-MD created")
|
| 140 |
+
|
| 141 |
+
elif ensemble.lower() == "nvt":
|
| 142 |
+
"""
|
| 143 |
+
Constant volume/temperature molecular dynamics.
|
| 144 |
+
"""
|
| 145 |
+
if thermostat.lower() == "nose-hoover":
|
| 146 |
+
"""
|
| 147 |
+
Nose-hoover (constant N, V, T) molecular dynamics.
|
| 148 |
+
ASE implementation currently only supports upper triangular lattice
|
| 149 |
+
"""
|
| 150 |
+
self.upper_triangular_cell()
|
| 151 |
+
self.dyn = NPT(
|
| 152 |
+
atoms=self.atoms,
|
| 153 |
+
timestep=timestep * units.fs,
|
| 154 |
+
temperature_K=temperature,
|
| 155 |
+
externalstress=pressure
|
| 156 |
+
* units.GPa, # ase NPT does not like externalstress=None
|
| 157 |
+
ttime=taut * units.fs,
|
| 158 |
+
pfactor=None,
|
| 159 |
+
trajectory=trajectory,
|
| 160 |
+
logfile=logfile,
|
| 161 |
+
loginterval=loginterval,
|
| 162 |
+
append_trajectory=append_trajectory,
|
| 163 |
+
)
|
| 164 |
+
print("NVT-Nose-Hoover MD created")
|
| 165 |
+
elif thermostat.lower().startswith("berendsen"):
|
| 166 |
+
"""
|
| 167 |
+
Berendsen (constant N, V, T) molecular dynamics.
|
| 168 |
+
"""
|
| 169 |
+
self.dyn = NVTBerendsen(
|
| 170 |
+
atoms=self.atoms,
|
| 171 |
+
timestep=timestep * units.fs,
|
| 172 |
+
temperature_K=temperature,
|
| 173 |
+
taut=taut * units.fs,
|
| 174 |
+
trajectory=trajectory,
|
| 175 |
+
logfile=logfile,
|
| 176 |
+
loginterval=loginterval,
|
| 177 |
+
append_trajectory=append_trajectory,
|
| 178 |
+
)
|
| 179 |
+
print("NVT-Berendsen-MD created")
|
| 180 |
+
else:
|
| 181 |
+
raise ValueError(
|
| 182 |
+
"Thermostat not supported, choose in 'Nose-Hoover', 'Berendsen', "
|
| 183 |
+
"'Berendsen_inhomogeneous'"
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
elif ensemble.lower() == "npt":
|
| 187 |
+
"""
|
| 188 |
+
Constant pressure/temperature molecular dynamics.
|
| 189 |
+
"""
|
| 190 |
+
# Bulk modulus is needed for pressure damping time
|
| 191 |
+
if bulk_modulus is not None:
|
| 192 |
+
bulk_modulus_au = bulk_modulus * units.GPa # GPa to eV/A^3
|
| 193 |
+
compressibility_au = 1 / bulk_modulus_au
|
| 194 |
+
else:
|
| 195 |
+
try:
|
| 196 |
+
# Fit bulk modulus by equation of state
|
| 197 |
+
eos = EquationOfState(model=self.atoms.calc)
|
| 198 |
+
eos.fit(atoms=atoms, steps=500, fmax=0.1, verbose=False)
|
| 199 |
+
bulk_modulus = eos.get_bulk_modulus(unit="GPa")
|
| 200 |
+
bulk_modulus_au = eos.get_bulk_modulus(unit="eV/A^3")
|
| 201 |
+
compressibility_au = eos.get_compressibility(unit="A^3/eV")
|
| 202 |
+
print(
|
| 203 |
+
f"Completed bulk modulus calculation: "
|
| 204 |
+
f"k = {bulk_modulus:.3}GPa, {bulk_modulus_au:.3}eV/A^3"
|
| 205 |
+
)
|
| 206 |
+
except Exception:
|
| 207 |
+
bulk_modulus_au = 2 * units.GPa
|
| 208 |
+
compressibility_au = 1 / bulk_modulus_au
|
| 209 |
+
print(
|
| 210 |
+
"Warning!!! Equation of State fitting failed, setting bulk "
|
| 211 |
+
"modulus to 2 GPa. NPT simulation can proceed with incorrect "
|
| 212 |
+
"pressure relaxation time."
|
| 213 |
+
"User input for bulk modulus is recommended."
|
| 214 |
+
)
|
| 215 |
+
self.bulk_modulus = bulk_modulus
|
| 216 |
+
|
| 217 |
+
if thermostat.lower() == "nose-hoover":
|
| 218 |
+
"""
|
| 219 |
+
Combined Nose-Hoover and Parrinello-Rahman dynamics, creating an
|
| 220 |
+
NPT (or N,stress,T) ensemble.
|
| 221 |
+
see: https://gitlab.com/ase/ase/-/blob/master/ase/md/npt.py
|
| 222 |
+
ASE implementation currently only supports upper triangular lattice
|
| 223 |
+
"""
|
| 224 |
+
self.upper_triangular_cell()
|
| 225 |
+
ptime = taup * units.fs
|
| 226 |
+
self.dyn = NPT(
|
| 227 |
+
atoms=self.atoms,
|
| 228 |
+
timestep=timestep * units.fs,
|
| 229 |
+
temperature_K=temperature,
|
| 230 |
+
externalstress=pressure * units.GPa,
|
| 231 |
+
ttime=taut * units.fs,
|
| 232 |
+
pfactor=bulk_modulus * units.GPa * ptime * ptime,
|
| 233 |
+
trajectory=trajectory,
|
| 234 |
+
logfile=logfile,
|
| 235 |
+
loginterval=loginterval,
|
| 236 |
+
append_trajectory=append_trajectory,
|
| 237 |
+
)
|
| 238 |
+
print("NPT-Nose-Hoover MD created")
|
| 239 |
+
|
| 240 |
+
elif thermostat.lower() == "berendsen_inhomogeneous":
|
| 241 |
+
"""
|
| 242 |
+
Inhomogeneous_NPTBerendsen thermo/barostat
|
| 243 |
+
This is a more flexible scheme that fixes three angles of the unit
|
| 244 |
+
cell but allows three lattice parameter to change independently.
|
| 245 |
+
see: https://gitlab.com/ase/ase/-/blob/master/ase/md/nptberendsen.py
|
| 246 |
+
"""
|
| 247 |
+
|
| 248 |
+
self.dyn = Inhomogeneous_NPTBerendsen(
|
| 249 |
+
atoms=self.atoms,
|
| 250 |
+
timestep=timestep * units.fs,
|
| 251 |
+
temperature_K=temperature,
|
| 252 |
+
pressure_au=pressure * units.GPa,
|
| 253 |
+
taut=taut * units.fs,
|
| 254 |
+
taup=taup * units.fs,
|
| 255 |
+
compressibility_au=compressibility_au,
|
| 256 |
+
trajectory=trajectory,
|
| 257 |
+
logfile=logfile,
|
| 258 |
+
loginterval=loginterval,
|
| 259 |
+
)
|
| 260 |
+
print("NPT-Berendsen-inhomogeneous-MD created")
|
| 261 |
+
|
| 262 |
+
elif thermostat.lower() == "npt_berendsen":
|
| 263 |
+
"""
|
| 264 |
+
This is a similar scheme to the Inhomogeneous_NPTBerendsen.
|
| 265 |
+
This is a less flexible scheme that fixes the shape of the
|
| 266 |
+
cell - three angles are fixed and the ratios between the three
|
| 267 |
+
lattice constants.
|
| 268 |
+
see: https://gitlab.com/ase/ase/-/blob/master/ase/md/nptberendsen.py
|
| 269 |
+
"""
|
| 270 |
+
|
| 271 |
+
self.dyn = NPTBerendsen(
|
| 272 |
+
atoms=self.atoms,
|
| 273 |
+
timestep=timestep * units.fs,
|
| 274 |
+
temperature_K=temperature,
|
| 275 |
+
pressure_au=pressure * units.GPa,
|
| 276 |
+
taut=taut * units.fs,
|
| 277 |
+
taup=taup * units.fs,
|
| 278 |
+
compressibility_au=compressibility_au,
|
| 279 |
+
trajectory=trajectory,
|
| 280 |
+
logfile=logfile,
|
| 281 |
+
loginterval=loginterval,
|
| 282 |
+
append_trajectory=append_trajectory,
|
| 283 |
+
)
|
| 284 |
+
print("NPT-Berendsen-MD created")
|
| 285 |
+
else:
|
| 286 |
+
raise ValueError(
|
| 287 |
+
"Thermostat not supported, choose in 'Nose-Hoover', 'Berendsen', "
|
| 288 |
+
"'Berendsen_inhomogeneous'"
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
self.trajectory = trajectory
|
| 292 |
+
self.logfile = logfile
|
| 293 |
+
self.loginterval = loginterval
|
| 294 |
+
self.timestep = timestep
|
| 295 |
+
self.crystal_feas_logfile = crystal_feas_logfile
|
| 296 |
+
|
| 297 |
+
def run(self, steps: int) -> None:
|
| 298 |
+
"""Thin wrapper of ase MD run.
|
| 299 |
+
|
| 300 |
+
Args:
|
| 301 |
+
steps (int): number of MD steps
|
| 302 |
+
"""
|
| 303 |
+
if self.crystal_feas_logfile:
|
| 304 |
+
obs = CrystalFeasObserver(self.atoms)
|
| 305 |
+
self.dyn.attach(obs, interval=self.loginterval)
|
| 306 |
+
|
| 307 |
+
self.dyn.run(steps)
|
| 308 |
+
|
| 309 |
+
if self.crystal_feas_logfile:
|
| 310 |
+
obs.save(self.crystal_feas_logfile)
|
| 311 |
+
|
| 312 |
+
def set_atoms(self, atoms: Atoms) -> None:
|
| 313 |
+
"""Set new atoms to run MD.
|
| 314 |
+
|
| 315 |
+
Args:
|
| 316 |
+
atoms (Atoms): new atoms for running MD
|
| 317 |
+
"""
|
| 318 |
+
calculator = self.atoms.calc
|
| 319 |
+
self.atoms = atoms
|
| 320 |
+
self.dyn.atoms = atoms
|
| 321 |
+
self.dyn.atoms.calc = calculator
|
| 322 |
+
|
| 323 |
+
def upper_triangular_cell(self, verbose: bool | None = False) -> None:
|
| 324 |
+
"""Transform to upper-triangular cell.
|
| 325 |
+
ASE Nose-Hoover implementation only supports upper-triangular cell
|
| 326 |
+
while ASE's canonical description is lower-triangular cell.
|
| 327 |
+
|
| 328 |
+
Args:
|
| 329 |
+
verbose (bool): Whether to notify user about upper-triangular cell
|
| 330 |
+
transformation. Default = False
|
| 331 |
+
"""
|
| 332 |
+
if not NPT._isuppertriangular(self.atoms.get_cell()):
|
| 333 |
+
a, b, c, alpha, beta, gamma = self.atoms.cell.cellpar()
|
| 334 |
+
angles = np.radians((alpha, beta, gamma))
|
| 335 |
+
sin_a, sin_b, _sin_g = np.sin(angles)
|
| 336 |
+
cos_a, cos_b, cos_g = np.cos(angles)
|
| 337 |
+
cos_p = (cos_g - cos_a * cos_b) / (sin_a * sin_b)
|
| 338 |
+
cos_p = np.clip(cos_p, -1, 1)
|
| 339 |
+
sin_p = (1 - cos_p**2) ** 0.5
|
| 340 |
+
|
| 341 |
+
new_basis = [
|
| 342 |
+
(a * sin_b * sin_p, a * sin_b * cos_p, a * cos_b),
|
| 343 |
+
(0, b * sin_a, b * cos_a),
|
| 344 |
+
(0, 0, c),
|
| 345 |
+
]
|
| 346 |
+
|
| 347 |
+
self.atoms.set_cell(new_basis, scale_atoms=True)
|
| 348 |
+
if verbose:
|
| 349 |
+
print("Transformed to upper triangular unit cell.", flush=True)
|
models/matris/matris/applications/relax.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Modified from CHGNet: https://github.com/CederGroupHub/chgnet """
|
| 2 |
+
|
| 3 |
+
import inspect
|
| 4 |
+
import sys
|
| 5 |
+
import io
|
| 6 |
+
import contextlib
|
| 7 |
+
from ase import Atoms, units
|
| 8 |
+
from ase.optimize.optimize import Optimizer
|
| 9 |
+
import ase.filters as filter_classes
|
| 10 |
+
from ase.filters import Filter
|
| 11 |
+
from pymatgen.io.ase import AseAtomsAdaptor
|
| 12 |
+
from pymatgen.core.structure import Structure
|
| 13 |
+
|
| 14 |
+
from ..model.model import MatRIS
|
| 15 |
+
from .base import (
|
| 16 |
+
OPTIMIZERS,
|
| 17 |
+
MatRISCalculator,
|
| 18 |
+
TrajectoryObserver,
|
| 19 |
+
CrystalFeasObserver
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
class StructOptimizer:
|
| 23 |
+
"""This class is used for Sturcture Optimization."""
|
| 24 |
+
|
| 25 |
+
def __init__(
|
| 26 |
+
self,
|
| 27 |
+
model: str = "matris_10m_oam",
|
| 28 |
+
task: str = "efs",
|
| 29 |
+
optimizer: str = "FIRE",
|
| 30 |
+
device: str = "cpu",
|
| 31 |
+
) -> None:
|
| 32 |
+
"""
|
| 33 |
+
Args:
|
| 34 |
+
model (MatRIS): Instance of a MatRIS model. If set to None, the default MatRIS is loaded.
|
| 35 |
+
task (str): The prediction task. Can be 'e', 'em', 'ef', 'efs', 'efsm'.
|
| 36 |
+
optimizer (Optimizer,str): choose optimizer from ASE.
|
| 37 |
+
device (str): The device to be used for predictions,
|
| 38 |
+
stress_unit (float): the conversion factor to convert GPa(MatRIS default) to eV/A^3.
|
| 39 |
+
**kwargs: Passed to the Calculator parent class.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
if optimizer in OPTIMIZERS:
|
| 43 |
+
optimizer = OPTIMIZERS[optimizer]
|
| 44 |
+
else:
|
| 45 |
+
raise ValueError(
|
| 46 |
+
f"Optimizer {optimizer} not found. Select from {list(OPTIMIZERS)}"
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
self.optimizer: Optimizer = optimizer
|
| 50 |
+
|
| 51 |
+
self.calculator = MatRISCalculator(
|
| 52 |
+
model=model,
|
| 53 |
+
task=task,
|
| 54 |
+
device=device,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
def relax(
|
| 58 |
+
self,
|
| 59 |
+
atoms: Structure | Atoms,
|
| 60 |
+
fmax: float = 0.05,
|
| 61 |
+
steps: int = 500,
|
| 62 |
+
relax_cell: bool = True,
|
| 63 |
+
ase_filter: str = "FrechetCellFilter",
|
| 64 |
+
save_path: str = None,
|
| 65 |
+
loginterval: int = 1,
|
| 66 |
+
crystal_feas_save_path: str = None,
|
| 67 |
+
verbose: bool = True,
|
| 68 |
+
assign_magmoms: bool = True,
|
| 69 |
+
**kwargs,
|
| 70 |
+
) -> dict[str, Structure | TrajectoryObserver]:
|
| 71 |
+
"""
|
| 72 |
+
Args:
|
| 73 |
+
atoms (Structure | Atoms): A Structure or Atoms object to relax.
|
| 74 |
+
fmax (float): The maximum force tolerance for relaxation.
|
| 75 |
+
steps (int): The maximum number of steps for relaxation.
|
| 76 |
+
relax_cell (bool): Whether to relax the cell as well.
|
| 77 |
+
ase_filter (str): The filter to apply to the atoms object for relaxation.
|
| 78 |
+
save_path (str): The path to save the trajectory.
|
| 79 |
+
loginterval (int): Interval for logging trajectory and crystal feas.
|
| 80 |
+
crystal_feas_save_path (str): Path to save crystal feature vectors
|
| 81 |
+
which are logged at a loginterval rage
|
| 82 |
+
verbose (bool): Whether to print the output of the ASE optimizer.
|
| 83 |
+
assign_magmoms (bool): Whether to assign magnetic moments to the final
|
| 84 |
+
structure.
|
| 85 |
+
**kwargs: Additional parameters for the optimizer.
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
valid_filter_names = [
|
| 89 |
+
name
|
| 90 |
+
for name, cls in inspect.getmembers(filter_classes, inspect.isclass)
|
| 91 |
+
if issubclass(cls, Filter)
|
| 92 |
+
]
|
| 93 |
+
|
| 94 |
+
if isinstance(ase_filter, str):
|
| 95 |
+
if ase_filter in valid_filter_names:
|
| 96 |
+
ase_filter = getattr(filter_classes, ase_filter)
|
| 97 |
+
else:
|
| 98 |
+
raise ValueError(
|
| 99 |
+
f"Invalid {ase_filter=}, must be one of {valid_filter_names}. "
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
if isinstance(atoms, Structure):
|
| 103 |
+
atoms = AseAtomsAdaptor().get_atoms(atoms)
|
| 104 |
+
|
| 105 |
+
atoms.calc = self.calculator
|
| 106 |
+
|
| 107 |
+
stream = sys.stdout if verbose else io.StringIO()
|
| 108 |
+
with contextlib.redirect_stdout(stream):
|
| 109 |
+
obs = TrajectoryObserver(atoms)
|
| 110 |
+
|
| 111 |
+
if crystal_feas_save_path:
|
| 112 |
+
cry_obs = CrystalFeasObserver(atoms)
|
| 113 |
+
|
| 114 |
+
if relax_cell:
|
| 115 |
+
atoms = ase_filter(atoms)
|
| 116 |
+
optimizer: Optimizer = self.optimizer(atoms, **kwargs)
|
| 117 |
+
optimizer.attach(obs, interval=loginterval)
|
| 118 |
+
|
| 119 |
+
if crystal_feas_save_path:
|
| 120 |
+
optimizer.attach(cry_obs, interval=loginterval)
|
| 121 |
+
|
| 122 |
+
optimizer.run(fmax=fmax, steps=steps)
|
| 123 |
+
obs()
|
| 124 |
+
|
| 125 |
+
if save_path is not None:
|
| 126 |
+
obs.save(save_path)
|
| 127 |
+
|
| 128 |
+
if crystal_feas_save_path:
|
| 129 |
+
cry_obs.save(crystal_feas_save_path)
|
| 130 |
+
|
| 131 |
+
if isinstance(atoms, Filter):
|
| 132 |
+
atoms = atoms.atoms
|
| 133 |
+
struct = AseAtomsAdaptor.get_structure(atoms)
|
| 134 |
+
|
| 135 |
+
if assign_magmoms:
|
| 136 |
+
if atoms.get_magnetic_moments() is not None:
|
| 137 |
+
for key in struct.site_properties:
|
| 138 |
+
struct.remove_site_property(property_name=key)
|
| 139 |
+
struct.add_site_property(
|
| 140 |
+
"magmom", [float(magmom) for magmom in atoms.get_magnetic_moments()]
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
return {"final_structure": struct, "trajectory": obs}
|
| 144 |
+
|
models/matris/matris/graph/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from .converter import GraphConverter
|
| 3 |
+
from .radiusgraph import RadiusGraph, datatype
|
models/matris/matris/graph/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (265 Bytes). View file
|
|
|
models/matris/matris/graph/__pycache__/converter.cpython-310.pyc
ADDED
|
Binary file (7.25 kB). View file
|
|
|
models/matris/matris/graph/__pycache__/radiusgraph.cpython-310.pyc
ADDED
|
Binary file (15.3 kB). View file
|
|
|
models/matris/matris/graph/converter.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This code is referenced from: https://github.com/CederGroupHub/chgnet/blob/main/chgnet/graph/converter.py
|
| 3 |
+
The original implementation can be found at the link above.
|
| 4 |
+
"""
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
from torch import nn
|
| 10 |
+
import gc
|
| 11 |
+
|
| 12 |
+
from .radiusgraph import Graph, Node, RadiusGraph
|
| 13 |
+
from pymatgen.core import Structure
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
from .cygraph import make_graph
|
| 17 |
+
except (ImportError, AttributeError):
|
| 18 |
+
make_graph = None
|
| 19 |
+
print("Failed with make_graph, run some program before")
|
| 20 |
+
|
| 21 |
+
datatype = torch.float32
|
| 22 |
+
|
| 23 |
+
class GraphConverter(nn.Module):
|
| 24 |
+
"""Convert a pymatgen.core.Structure to a RadiusGraph"""
|
| 25 |
+
|
| 26 |
+
def __init__(
|
| 27 |
+
self,
|
| 28 |
+
atom_graph_cutoff: float = 6,
|
| 29 |
+
line_graph_cutoff: float = 4,
|
| 30 |
+
verbose: bool = False,
|
| 31 |
+
) -> None:
|
| 32 |
+
"""Initialize the Graph Converter.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
atom_graph_cutoff (float): cutoff radius in atom graph.
|
| 36 |
+
line_graph_cutoff (float): bond length threshold in line graph.
|
| 37 |
+
verbose (bool): whether to print the GraphConverter.
|
| 38 |
+
"""
|
| 39 |
+
super().__init__()
|
| 40 |
+
self.atom_graph_cutoff = atom_graph_cutoff
|
| 41 |
+
self.line_graph_cutoff = (
|
| 42 |
+
atom_graph_cutoff if line_graph_cutoff is None else line_graph_cutoff
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
if make_graph is not None:
|
| 46 |
+
self.create_graph = self._create_graph_fast
|
| 47 |
+
self.algorithm = 'fast'
|
| 48 |
+
else:
|
| 49 |
+
self.create_graph = self._create_graph_legacy
|
| 50 |
+
self.algorithm = 'legacy'
|
| 51 |
+
print("fast graph converter algorithm import error, using legacy")
|
| 52 |
+
|
| 53 |
+
if verbose:
|
| 54 |
+
print(self)
|
| 55 |
+
|
| 56 |
+
def __repr__(self) -> str:
|
| 57 |
+
"""String representation of the GraphConverter."""
|
| 58 |
+
atom_graph_cutoff = self.atom_graph_cutoff
|
| 59 |
+
line_graph_cutoff = self.line_graph_cutoff
|
| 60 |
+
algorithm = self.algorithm
|
| 61 |
+
cls_name = type(self).__name__
|
| 62 |
+
return f"{cls_name}({algorithm=}, {atom_graph_cutoff=}, {line_graph_cutoff=})"
|
| 63 |
+
|
| 64 |
+
def forward(
|
| 65 |
+
self,
|
| 66 |
+
structure: Structure,
|
| 67 |
+
graph_id=None,
|
| 68 |
+
mp_id=None,
|
| 69 |
+
) -> RadiusGraph:
|
| 70 |
+
"""Convert a structure, return a RadiusGraph.
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
structure (pymatgen.core.Structure): structure to convert
|
| 74 |
+
graph_id (str): an id to keep track of this crystal graph
|
| 75 |
+
Default = None
|
| 76 |
+
mp_id (str): Materials Project id of this structure
|
| 77 |
+
Default = None
|
| 78 |
+
|
| 79 |
+
"""
|
| 80 |
+
n_atoms = len(structure)
|
| 81 |
+
atomic_number = torch.tensor( [site.specie.Z for site in structure], dtype=torch.int32 )
|
| 82 |
+
|
| 83 |
+
atom_frac_coord = torch.tensor( structure.frac_coords, dtype=datatype )
|
| 84 |
+
lattice = torch.tensor( structure.lattice.matrix, dtype=datatype )
|
| 85 |
+
|
| 86 |
+
center_index, neighbor_index, image, distance = structure.get_neighbor_list(
|
| 87 |
+
r=self.atom_graph_cutoff, sites=structure.sites, numerical_tol=1e-8
|
| 88 |
+
)
|
| 89 |
+
# Ceate atom graph
|
| 90 |
+
graph = self.create_graph(
|
| 91 |
+
n_atoms, center_index, neighbor_index, image, distance
|
| 92 |
+
)
|
| 93 |
+
atom_graph, directed2undirected = graph.adjacency_list()
|
| 94 |
+
atom_graph = torch.tensor(atom_graph, dtype=torch.int32)
|
| 95 |
+
directed2undirected = torch.tensor(directed2undirected, dtype=torch.int32)
|
| 96 |
+
undirected2directed = graph.undirected2directed()
|
| 97 |
+
undirected2directed = torch.tensor(undirected2directed, dtype=torch.int32)
|
| 98 |
+
|
| 99 |
+
line_graph = []
|
| 100 |
+
try:
|
| 101 |
+
line_graph = graph.line_graph_adjacency_list(
|
| 102 |
+
cutoff=self.line_graph_cutoff
|
| 103 |
+
)
|
| 104 |
+
except Exception as exc:
|
| 105 |
+
structure.to(filename="error_graph.cif")
|
| 106 |
+
|
| 107 |
+
line_graph = torch.tensor(line_graph, dtype=torch.int32)
|
| 108 |
+
|
| 109 |
+
# For isolated atom, we stop this calculation
|
| 110 |
+
n_isolated_atoms = len({*range(n_atoms)} - {*center_index})
|
| 111 |
+
if n_isolated_atoms:
|
| 112 |
+
atom_graph_cutoff = self.atom_graph_cutoff
|
| 113 |
+
error = f"Error: Detected {n_isolated_atoms} isolated atom. Calculation stopped"
|
| 114 |
+
raise ValueError(error) # or print(error)
|
| 115 |
+
|
| 116 |
+
return RadiusGraph(
|
| 117 |
+
atomic_number=atomic_number,
|
| 118 |
+
atom_frac_coord=atom_frac_coord,
|
| 119 |
+
atom_graph=atom_graph,
|
| 120 |
+
neighbor_image=torch.tensor(image, dtype=datatype),
|
| 121 |
+
directed2undirected=directed2undirected,
|
| 122 |
+
undirected2directed=undirected2directed,
|
| 123 |
+
line_graph=line_graph,
|
| 124 |
+
lattice=lattice,
|
| 125 |
+
graph_id=graph_id,
|
| 126 |
+
mp_id=mp_id,
|
| 127 |
+
composition=structure.composition.formula,
|
| 128 |
+
atom_graph_cutoff=self.atom_graph_cutoff,
|
| 129 |
+
line_graph_cutoff=self.line_graph_cutoff,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
@staticmethod
|
| 133 |
+
def _create_graph_legacy(
|
| 134 |
+
n_atoms: int,
|
| 135 |
+
center_index: np.ndarray,
|
| 136 |
+
neighbor_index: np.ndarray,
|
| 137 |
+
image: np.ndarray,
|
| 138 |
+
distance: np.ndarray,
|
| 139 |
+
) -> Graph:
|
| 140 |
+
"""Given structure information, create a Graph structure to be used to
|
| 141 |
+
create Crystal_Graph using pure python implementation.
|
| 142 |
+
|
| 143 |
+
Args:
|
| 144 |
+
n_atoms (int): the number of atoms in the structure
|
| 145 |
+
center_index (np.ndarray): np array of indices of center atoms.
|
| 146 |
+
[num_undirected_bonds]
|
| 147 |
+
neighbor_index (np.ndarray): np array of indices of neighbor atoms.
|
| 148 |
+
[num_undirected_bonds]
|
| 149 |
+
image (np.ndarray): np array of images for each edge.
|
| 150 |
+
[num_undirected_bonds, 3]
|
| 151 |
+
distance (np.ndarray): np array of distances.
|
| 152 |
+
[num_undirected_bonds]
|
| 153 |
+
|
| 154 |
+
Return:
|
| 155 |
+
Graph data structure used to create Crystal_Graph object
|
| 156 |
+
"""
|
| 157 |
+
|
| 158 |
+
graph = Graph([Node(index=idx) for idx in range(n_atoms)])
|
| 159 |
+
for ii, jj, img, dist in zip(center_index, neighbor_index, image, distance):
|
| 160 |
+
graph.add_edge(center_index=ii, neighbor_index=jj, image=img, distance=dist)
|
| 161 |
+
|
| 162 |
+
return graph
|
| 163 |
+
|
| 164 |
+
@staticmethod
|
| 165 |
+
def _create_graph_fast(
|
| 166 |
+
n_atoms: int,
|
| 167 |
+
center_index: np.ndarray,
|
| 168 |
+
neighbor_index: np.ndarray,
|
| 169 |
+
image: np.ndarray,
|
| 170 |
+
distance: np.ndarray,
|
| 171 |
+
) -> Graph:
|
| 172 |
+
"""Given structure information, create a Graph structure to be used to
|
| 173 |
+
create Crystal_Graph using C implementation.
|
| 174 |
+
|
| 175 |
+
NOTE: this is the fast version of _create_graph_legacy optimized
|
| 176 |
+
in c (~3x speedup).
|
| 177 |
+
|
| 178 |
+
Args:
|
| 179 |
+
n_atoms (int): the number of atoms in the structure
|
| 180 |
+
center_index (np.ndarray): np array of indices of center atoms.
|
| 181 |
+
[num_undirected_bonds]
|
| 182 |
+
neighbor_index (np.ndarray): np array of indices of neighbor atoms.
|
| 183 |
+
[num_undirected_bonds]
|
| 184 |
+
image (np.ndarray): np array of images for each edge.
|
| 185 |
+
[num_undirected_bonds, 3]
|
| 186 |
+
distance (np.ndarray): np array of distances.
|
| 187 |
+
[num_undirected_bonds]
|
| 188 |
+
|
| 189 |
+
Return:
|
| 190 |
+
Graph data structure used to create Crystal_Graph object
|
| 191 |
+
"""
|
| 192 |
+
center_index = np.ascontiguousarray(center_index)
|
| 193 |
+
neighbor_index = np.ascontiguousarray(neighbor_index)
|
| 194 |
+
image = np.ascontiguousarray(image, dtype=np.int_)
|
| 195 |
+
distance = np.ascontiguousarray(distance)
|
| 196 |
+
gc_saved = gc.get_threshold()
|
| 197 |
+
gc.set_threshold(0)
|
| 198 |
+
(
|
| 199 |
+
nodes,
|
| 200 |
+
directed_edges_list,
|
| 201 |
+
undirected_edges_list,
|
| 202 |
+
undirected_edges,
|
| 203 |
+
) = make_graph(
|
| 204 |
+
center_index, len(center_index), neighbor_index, image, distance, n_atoms
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
graph = Graph(nodes=nodes)
|
| 208 |
+
graph.directed_edges_list = directed_edges_list
|
| 209 |
+
graph.undirected_edges_list = undirected_edges_list
|
| 210 |
+
graph.undirected_edges = undirected_edges
|
| 211 |
+
gc.set_threshold(gc_saved[0])
|
| 212 |
+
|
| 213 |
+
return graph
|
| 214 |
+
|
| 215 |
+
def as_dict(self) -> dict[str, float]:
|
| 216 |
+
"""Save the args of the graph converter."""
|
| 217 |
+
return {
|
| 218 |
+
"atom_graph_cutoff": self.atom_graph_cutoff,
|
| 219 |
+
"line_graph_cutoff": self.line_graph_cutoff,
|
| 220 |
+
"algorithm": self.algorithm,
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
@classmethod
|
| 224 |
+
def from_dict(cls, dict) -> GraphConverter:
|
| 225 |
+
"""Create converter from dictionary."""
|
| 226 |
+
return GraphConverter(**dict)
|
models/matris/matris/graph/cygraph.c
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
models/matris/matris/graph/cygraph.pyx
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This code is referenced from: https://github.com/CederGroupHub/chgnet/blob/main/chgnet/graph/converter.py
|
| 3 |
+
The original implementation can be found at the link above.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
# cython: language_level=3
|
| 7 |
+
# cython: initializedcheck=False
|
| 8 |
+
# cython: nonecheck=False
|
| 9 |
+
# cython: boundscheck=False
|
| 10 |
+
# cython: wraparound=False
|
| 11 |
+
# cython: cdivision=True
|
| 12 |
+
# cython: profile=False
|
| 13 |
+
# distutils: language = c
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
from . import radiusgraph
|
| 17 |
+
import numpy as np
|
| 18 |
+
from libc.stdlib cimport free
|
| 19 |
+
|
| 20 |
+
cdef extern from 'fast_converter_libraries/create_graph.c':
|
| 21 |
+
ctypedef struct Node:
|
| 22 |
+
long index
|
| 23 |
+
LongToDirectedEdgeList* neighbors
|
| 24 |
+
long num_neighbors
|
| 25 |
+
|
| 26 |
+
ctypedef struct NodeIndexPair:
|
| 27 |
+
long center
|
| 28 |
+
long neighbor
|
| 29 |
+
|
| 30 |
+
ctypedef struct UndirectedEdge:
|
| 31 |
+
NodeIndexPair nodes
|
| 32 |
+
long index
|
| 33 |
+
long* directed_edge_indices
|
| 34 |
+
long num_directed_edges
|
| 35 |
+
double distance
|
| 36 |
+
|
| 37 |
+
ctypedef struct DirectedEdge:
|
| 38 |
+
NodeIndexPair nodes
|
| 39 |
+
long index
|
| 40 |
+
const long* image
|
| 41 |
+
long undirected_edge_index
|
| 42 |
+
double distance
|
| 43 |
+
|
| 44 |
+
ctypedef struct LongToDirectedEdgeList:
|
| 45 |
+
long key
|
| 46 |
+
DirectedEdge** directed_edges_list
|
| 47 |
+
int num_directed_edges_in_group
|
| 48 |
+
|
| 49 |
+
ctypedef struct ReturnElems2:
|
| 50 |
+
long num_nodes
|
| 51 |
+
long num_directed_edges
|
| 52 |
+
long num_undirected_edges
|
| 53 |
+
Node* nodes
|
| 54 |
+
UndirectedEdge** undirected_edges_list
|
| 55 |
+
DirectedEdge** directed_edges_list
|
| 56 |
+
|
| 57 |
+
ReturnElems2* create_graph(
|
| 58 |
+
long* center_index,
|
| 59 |
+
long n_e,
|
| 60 |
+
long* neighbor_index,
|
| 61 |
+
long* image,
|
| 62 |
+
double* distance,
|
| 63 |
+
long num_atoms)
|
| 64 |
+
|
| 65 |
+
void free_LongToDirectedEdgeList_in_nodes(Node* nodes, long num_nodes)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
LongToDirectedEdgeList** get_neighbors(Node* node)
|
| 69 |
+
|
| 70 |
+
def make_graph(
|
| 71 |
+
const long[::1] center_index,
|
| 72 |
+
const long n_e,
|
| 73 |
+
const long[::1] neighbor_index,
|
| 74 |
+
const long[:, ::1] image,
|
| 75 |
+
const double[::1] distance,
|
| 76 |
+
const long num_atoms
|
| 77 |
+
):
|
| 78 |
+
cdef ReturnElems2* returned
|
| 79 |
+
returned = <ReturnElems2*> create_graph(<long*> ¢er_index[0], n_e, <long*> &neighbor_index[0], <long*> &image[0][0], <double*> &distance[0], num_atoms)
|
| 80 |
+
|
| 81 |
+
chg_DirectedEdge = radiusgraph.DirectedEdge
|
| 82 |
+
chg_Node = radiusgraph.Node
|
| 83 |
+
chg_UndirectedEdge = radiusgraph.UndirectedEdge
|
| 84 |
+
|
| 85 |
+
image_np = np.asarray(image)
|
| 86 |
+
|
| 87 |
+
cdef LongToDirectedEdgeList** node_neighbors
|
| 88 |
+
cdef Node this_node
|
| 89 |
+
cdef LongToDirectedEdgeList this_entry
|
| 90 |
+
py_nodes = []
|
| 91 |
+
cdef DirectedEdge* this_DE
|
| 92 |
+
|
| 93 |
+
# Handling nodes + directed edges
|
| 94 |
+
for idx in range(returned[0].num_nodes):
|
| 95 |
+
this_node = returned[0].nodes[idx]
|
| 96 |
+
this_py_node = chg_Node(index=idx)
|
| 97 |
+
|
| 98 |
+
node_neighbors = get_neighbors(&this_node)
|
| 99 |
+
|
| 100 |
+
# Iterate through all neighbors and populate our py_node.neighbors dict
|
| 101 |
+
for j in range(this_node.num_neighbors):
|
| 102 |
+
this_entry = node_neighbors[j][0]
|
| 103 |
+
directed_edges = []
|
| 104 |
+
|
| 105 |
+
for k in range(this_entry.num_directed_edges_in_group):
|
| 106 |
+
this_DE = this_entry.directed_edges_list[k]
|
| 107 |
+
directed_edges.append(this_DE[0].index)
|
| 108 |
+
|
| 109 |
+
this_py_node.neighbors[this_entry.key] = directed_edges
|
| 110 |
+
|
| 111 |
+
py_nodes.append(this_py_node)
|
| 112 |
+
|
| 113 |
+
free(node_neighbors)
|
| 114 |
+
|
| 115 |
+
# Handling directed edges
|
| 116 |
+
py_directed_edges_list = []
|
| 117 |
+
|
| 118 |
+
for idx in range(returned[0].num_directed_edges):
|
| 119 |
+
this_DE = returned[0].directed_edges_list[idx]
|
| 120 |
+
py_DE = chg_DirectedEdge(nodes = [this_DE[0].nodes.center, this_DE[0].nodes.neighbor], index=this_DE[0].index, info = {"distance": this_DE[0].distance, "image": image_np[this_DE[0].index], "undirected_edge_index": this_DE[0].undirected_edge_index})
|
| 121 |
+
|
| 122 |
+
py_directed_edges_list.append(py_DE)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# Handling undirected edges
|
| 126 |
+
py_undirected_edges_list = []
|
| 127 |
+
cdef UndirectedEdge* UDE
|
| 128 |
+
|
| 129 |
+
for idx in range(returned[0].num_undirected_edges):
|
| 130 |
+
UDE = returned[0].undirected_edges_list[idx]
|
| 131 |
+
py_undirected_edge = chg_UndirectedEdge([UDE[0].nodes.center, UDE[0].nodes.neighbor], index = UDE[0].index, info = {"distance": UDE[0].distance, "directed_edge_index": []})
|
| 132 |
+
|
| 133 |
+
for j in range(UDE[0].num_directed_edges):
|
| 134 |
+
py_undirected_edge.info["directed_edge_index"].append(UDE[0].directed_edge_indices[j])
|
| 135 |
+
|
| 136 |
+
py_undirected_edges_list.append(py_undirected_edge)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
# Create Undirected_Edges hashmap
|
| 140 |
+
py_undirected_edges = {}
|
| 141 |
+
for undirected_edge in py_undirected_edges_list:
|
| 142 |
+
this_set = frozenset(undirected_edge.nodes)
|
| 143 |
+
if this_set not in py_undirected_edges:
|
| 144 |
+
py_undirected_edges[this_set] = [undirected_edge]
|
| 145 |
+
else:
|
| 146 |
+
py_undirected_edges[this_set].append(undirected_edge)
|
| 147 |
+
|
| 148 |
+
# # Update the nodes list to have pointers to DirectedEdges instead of indices
|
| 149 |
+
for node_index in range(returned[0].num_nodes):
|
| 150 |
+
this_neighbors = py_nodes[node_index].neighbors
|
| 151 |
+
for this_neighbor_index in this_neighbors:
|
| 152 |
+
replacement = [py_directed_edges_list[edge_index] for edge_index in this_neighbors[this_neighbor_index]]
|
| 153 |
+
this_neighbors[this_neighbor_index] = replacement
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
# Free everything unneeded
|
| 157 |
+
for idx in range(returned[0].num_directed_edges):
|
| 158 |
+
free(returned[0].directed_edges_list[idx])
|
| 159 |
+
|
| 160 |
+
for idx in range(returned[0].num_undirected_edges):
|
| 161 |
+
free(returned[0].undirected_edges_list[idx].directed_edge_indices)
|
| 162 |
+
free(returned[0].undirected_edges_list[idx])
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
# Free node LongToDirectedEdgeList
|
| 166 |
+
free_LongToDirectedEdgeList_in_nodes(returned[0].nodes, returned[0].num_nodes)
|
| 167 |
+
|
| 168 |
+
free(returned[0].directed_edges_list)
|
| 169 |
+
free(returned[0].undirected_edges_list)
|
| 170 |
+
free(returned[0].nodes)
|
| 171 |
+
|
| 172 |
+
free(returned)
|
| 173 |
+
|
| 174 |
+
return py_nodes, py_directed_edges_list, py_undirected_edges_list, py_undirected_edges
|
models/matris/matris/graph/fast_converter_libraries/create_graph.c
ADDED
|
@@ -0,0 +1,423 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
| 1 |
+
#include "uthash.h"
|
| 2 |
+
#include <stdbool.h>
|
| 3 |
+
|
| 4 |
+
typedef struct _UndirectedEdge UndirectedEdge;
|
| 5 |
+
typedef struct _DirectedEdge DirectedEdge;
|
| 6 |
+
typedef struct _Node Node;
|
| 7 |
+
typedef struct _NodeIndexPair NodeIndexPair;
|
| 8 |
+
typedef struct _LongToDirectedEdgeList LongToDirectedEdgeList;
|
| 9 |
+
typedef struct _ReturnElems2 ReturnElems2;
|
| 10 |
+
|
| 11 |
+
// NOTE: This code was mainly written to replicate the original add_edges method
|
| 12 |
+
// in the graph class in chgnet.graph.graph such that anyone familiar with that code should be able to pick up this
|
| 13 |
+
// code pretty easily.
|
| 14 |
+
|
| 15 |
+
long MEM_ERR = 100;
|
| 16 |
+
|
| 17 |
+
typedef struct _Node {
|
| 18 |
+
long index;
|
| 19 |
+
LongToDirectedEdgeList* neighbors; // Assuming neighbors can only be directed edge. Key is dest_node, value is DirectedEdge struct
|
| 20 |
+
long num_neighbors;
|
| 21 |
+
} Node;
|
| 22 |
+
|
| 23 |
+
typedef struct _NodeIndexPair {
|
| 24 |
+
long center;
|
| 25 |
+
long neighbor;
|
| 26 |
+
} NodeIndexPair;
|
| 27 |
+
|
| 28 |
+
typedef struct _UndirectedEdge {
|
| 29 |
+
NodeIndexPair nodes;
|
| 30 |
+
long index;
|
| 31 |
+
long* directed_edge_indices;
|
| 32 |
+
long num_directed_edges;
|
| 33 |
+
double distance;
|
| 34 |
+
} UndirectedEdge;
|
| 35 |
+
|
| 36 |
+
typedef struct _DirectedEdge {
|
| 37 |
+
NodeIndexPair nodes;
|
| 38 |
+
long index;
|
| 39 |
+
const long* image; // Only access the first 3, never edit
|
| 40 |
+
long undirected_edge_index;
|
| 41 |
+
double distance;
|
| 42 |
+
} DirectedEdge;
|
| 43 |
+
|
| 44 |
+
typedef struct _StructToUndirectedEdgeList {
|
| 45 |
+
NodeIndexPair key;
|
| 46 |
+
UndirectedEdge** undirected_edges_list;
|
| 47 |
+
int num_undirected_edges_in_group;
|
| 48 |
+
UT_hash_handle hh;
|
| 49 |
+
} StructToUndirectedEdgeList;
|
| 50 |
+
|
| 51 |
+
typedef struct _LongToDirectedEdgeList {
|
| 52 |
+
long key;
|
| 53 |
+
DirectedEdge** directed_edges_list;
|
| 54 |
+
int num_directed_edges_in_group;
|
| 55 |
+
UT_hash_handle hh;
|
| 56 |
+
} LongToDirectedEdgeList;
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
typedef struct _ReturnElems2 {
|
| 60 |
+
long num_nodes;
|
| 61 |
+
long num_directed_edges;
|
| 62 |
+
long num_undirected_edges;
|
| 63 |
+
Node* nodes;
|
| 64 |
+
UndirectedEdge** undirected_edges_list;
|
| 65 |
+
DirectedEdge** directed_edges_list;
|
| 66 |
+
} ReturnElems2;
|
| 67 |
+
|
| 68 |
+
bool find_in_undirected(NodeIndexPair* tmp, StructToUndirectedEdgeList** undirected_edges, StructToUndirectedEdgeList** found_entry);
|
| 69 |
+
void directed_to_undirected(DirectedEdge* directed, UndirectedEdge* undirected, long undirected_index);
|
| 70 |
+
void create_new_undirected_edges_entry(StructToUndirectedEdgeList** undirected_edges, NodeIndexPair* tmp, UndirectedEdge* new_undirected_edge);
|
| 71 |
+
void append_to_undirected_edges_tmp(UndirectedEdge* undirected, StructToUndirectedEdgeList** undirected_edges, NodeIndexPair* tmp);
|
| 72 |
+
void append_to_undirected_edges_list(UndirectedEdge** undirected_edges_list, UndirectedEdge* to_add, long* num_undirected_edges);
|
| 73 |
+
void append_to_directed_edges_list(DirectedEdge** directed_edges_list, DirectedEdge* to_add, long* num_directed_edges);
|
| 74 |
+
void add_neighbors_to_node(Node* node, long neighbor_index, DirectedEdge* directed_edge);
|
| 75 |
+
void print_neighbors(Node* node);
|
| 76 |
+
void append_to_directed_edge_indices(UndirectedEdge* undirected_edge, long directed_edge_index);
|
| 77 |
+
bool is_reversed_directed_edge(DirectedEdge* directed_edge1, DirectedEdge* directed_edge2);
|
| 78 |
+
void free_undirected_edges(StructToUndirectedEdgeList** undirected_edges);
|
| 79 |
+
void free_LongToDirectedEdgeList_in_nodes(Node* nodes, long num_nodes);
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
Node* create_nodes(long num_nodes) {
|
| 83 |
+
Node* Nodes = (Node*) malloc(sizeof(Node) * num_nodes);
|
| 84 |
+
|
| 85 |
+
if (Nodes == NULL) {
|
| 86 |
+
return NULL;
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
for (long i = 0; i < num_nodes; i++) {
|
| 90 |
+
Nodes[i].index = i;
|
| 91 |
+
Nodes[i].num_neighbors = 0;
|
| 92 |
+
|
| 93 |
+
// Initialize the uthash
|
| 94 |
+
Nodes[i].neighbors = NULL;
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
return Nodes;
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
ReturnElems2* create_graph(
|
| 101 |
+
long* center_indices,
|
| 102 |
+
long num_edges,
|
| 103 |
+
long* neighbor_indices,
|
| 104 |
+
long* images, // contiguous memory (row-major) of image elements (total of n_e * 3 integers)
|
| 105 |
+
double* distances,
|
| 106 |
+
long num_atoms
|
| 107 |
+
) {
|
| 108 |
+
// Initialize pertinent data structures ---------------------
|
| 109 |
+
Node* nodes = create_nodes(num_atoms);
|
| 110 |
+
|
| 111 |
+
DirectedEdge** directed_edges_list = calloc(num_edges, sizeof(DirectedEdge));
|
| 112 |
+
long num_directed_edges = 0;
|
| 113 |
+
|
| 114 |
+
// There will never be more undirected edges than directed edges
|
| 115 |
+
UndirectedEdge** undirected_edges_list = calloc(num_edges, sizeof(UndirectedEdge));
|
| 116 |
+
long num_undirected_edges = 0;
|
| 117 |
+
StructToUndirectedEdgeList* undirected_edges = NULL;
|
| 118 |
+
|
| 119 |
+
// Pointer to beginning of list of UndirectedEdges corresponding to tmp of current iteration
|
| 120 |
+
StructToUndirectedEdgeList* corr_undirected_edges_item = NULL;
|
| 121 |
+
|
| 122 |
+
// Pointer to NodeIndexPair storing tmp
|
| 123 |
+
NodeIndexPair* tmp = malloc(sizeof(NodeIndexPair));
|
| 124 |
+
|
| 125 |
+
// Flag for whether or not the value was found
|
| 126 |
+
bool found = false;
|
| 127 |
+
|
| 128 |
+
// Flag used to show if we've already processed the current undirected edge
|
| 129 |
+
bool processed_edge = false;
|
| 130 |
+
|
| 131 |
+
// Pointer used to store the previously added directed edge between two nodes
|
| 132 |
+
DirectedEdge* added_DE;
|
| 133 |
+
DirectedEdge* this_directed_edge;
|
| 134 |
+
|
| 135 |
+
// Add all edges to graph information
|
| 136 |
+
for (long i = 0; i < num_edges; i++) {
|
| 137 |
+
// Haven't processed the edge yet
|
| 138 |
+
processed_edge = false;
|
| 139 |
+
// Create the current directed edge -------------------
|
| 140 |
+
this_directed_edge = calloc(1, sizeof(DirectedEdge));
|
| 141 |
+
this_directed_edge->nodes.center = center_indices[i];
|
| 142 |
+
this_directed_edge->nodes.neighbor = neighbor_indices[i];
|
| 143 |
+
this_directed_edge->distance = distances[i];
|
| 144 |
+
this_directed_edge->index = num_directed_edges;
|
| 145 |
+
this_directed_edge->image = images + (3 * i);
|
| 146 |
+
|
| 147 |
+
// Load tmp
|
| 148 |
+
memset(tmp, 0, sizeof(NodeIndexPair));
|
| 149 |
+
tmp->center = center_indices[i];
|
| 150 |
+
tmp->neighbor = neighbor_indices[i];
|
| 151 |
+
|
| 152 |
+
// See if tmp is in undirected
|
| 153 |
+
corr_undirected_edges_item = NULL;
|
| 154 |
+
found = find_in_undirected(tmp, &undirected_edges, &corr_undirected_edges_item);
|
| 155 |
+
|
| 156 |
+
if (!found) {
|
| 157 |
+
// Never seen this edge combination before
|
| 158 |
+
this_directed_edge->undirected_edge_index = num_undirected_edges;
|
| 159 |
+
|
| 160 |
+
// Create new undirected edge
|
| 161 |
+
UndirectedEdge* this_undirected_edge = malloc(sizeof(UndirectedEdge));
|
| 162 |
+
|
| 163 |
+
directed_to_undirected(this_directed_edge, this_undirected_edge, num_undirected_edges);
|
| 164 |
+
|
| 165 |
+
// Add this new edge information to various data structures
|
| 166 |
+
create_new_undirected_edges_entry(&undirected_edges, tmp, this_undirected_edge);
|
| 167 |
+
append_to_undirected_edges_list(undirected_edges_list, this_undirected_edge, &num_undirected_edges);
|
| 168 |
+
add_neighbors_to_node(&nodes[center_indices[i]], neighbor_indices[i], this_directed_edge);
|
| 169 |
+
append_to_directed_edges_list(directed_edges_list, this_directed_edge, &num_directed_edges);
|
| 170 |
+
} else {
|
| 171 |
+
// This pair of nodes has been added before. We have to check if it's the other directed edge (but pointed in
|
| 172 |
+
// the different direction) OR it's another totally different undirected edge that has different image and distance
|
| 173 |
+
|
| 174 |
+
// if found is true, then corr_undirected_edges_item points to self.undirected_edges[tmp]
|
| 175 |
+
// iterate through all previously scanned undirected edges that have the same endpoints as this edge
|
| 176 |
+
// if there exists an undirected edge with the same inverted image as this_undirected_edge, then add this new directed edge
|
| 177 |
+
// and associate it with this undirected edge
|
| 178 |
+
for (int j = 0; j < corr_undirected_edges_item->num_undirected_edges_in_group; j++) {
|
| 179 |
+
// Grab the 0th directed edge associated with this undirected edge
|
| 180 |
+
added_DE = directed_edges_list[((corr_undirected_edges_item->undirected_edges_list)[j]->directed_edge_indices)[0]];
|
| 181 |
+
|
| 182 |
+
if (is_reversed_directed_edge(added_DE, this_directed_edge)) {
|
| 183 |
+
this_directed_edge->undirected_edge_index = added_DE->undirected_edge_index;
|
| 184 |
+
add_neighbors_to_node(&nodes[center_indices[i]], neighbor_indices[i], this_directed_edge);
|
| 185 |
+
append_to_directed_edges_list(directed_edges_list, this_directed_edge, &num_directed_edges);
|
| 186 |
+
append_to_directed_edge_indices((corr_undirected_edges_item->undirected_edges_list)[j], this_directed_edge->index);
|
| 187 |
+
processed_edge = true;
|
| 188 |
+
break;
|
| 189 |
+
}
|
| 190 |
+
}
|
| 191 |
+
// There wasn't a pre-existing undirected edge that corresponds to this directed edge
|
| 192 |
+
// Create a new undirected edge and process
|
| 193 |
+
if (!processed_edge) {
|
| 194 |
+
this_directed_edge->undirected_edge_index = num_undirected_edges;
|
| 195 |
+
// Create a new undirected edge
|
| 196 |
+
UndirectedEdge* this_undirected_edge = malloc(sizeof(UndirectedEdge));
|
| 197 |
+
directed_to_undirected(this_directed_edge, this_undirected_edge, num_undirected_edges);
|
| 198 |
+
append_to_undirected_edges_tmp(this_undirected_edge, &undirected_edges, tmp);
|
| 199 |
+
append_to_undirected_edges_list(undirected_edges_list, this_undirected_edge, &num_undirected_edges);
|
| 200 |
+
add_neighbors_to_node(&nodes[center_indices[i]], neighbor_indices[i], this_directed_edge);
|
| 201 |
+
append_to_directed_edges_list(directed_edges_list, this_directed_edge, &num_directed_edges);
|
| 202 |
+
}
|
| 203 |
+
}
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
ReturnElems2* returned2 = malloc(sizeof(ReturnElems2));
|
| 207 |
+
returned2->num_nodes = num_atoms;
|
| 208 |
+
returned2->num_undirected_edges = num_undirected_edges;
|
| 209 |
+
returned2->num_directed_edges = num_directed_edges;
|
| 210 |
+
|
| 211 |
+
returned2->nodes = nodes;
|
| 212 |
+
returned2->directed_edges_list = directed_edges_list;
|
| 213 |
+
returned2->undirected_edges_list = undirected_edges_list;
|
| 214 |
+
|
| 215 |
+
free(tmp);
|
| 216 |
+
free_undirected_edges(&undirected_edges);
|
| 217 |
+
|
| 218 |
+
return returned2;
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
void print_neighbors(Node* node) {
|
| 222 |
+
LongToDirectedEdgeList *tmp, *neighbor;
|
| 223 |
+
HASH_ITER(hh, node->neighbors, neighbor, tmp) {
|
| 224 |
+
printf("C:neighboring atom: %lu\n", neighbor->key);
|
| 225 |
+
}
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
void free_undirected_edges(StructToUndirectedEdgeList** undirected_edges) {
|
| 229 |
+
StructToUndirectedEdgeList* current;
|
| 230 |
+
StructToUndirectedEdgeList* tmp;
|
| 231 |
+
|
| 232 |
+
HASH_ITER(hh, *undirected_edges, current, tmp) {
|
| 233 |
+
HASH_DEL(*undirected_edges, current);
|
| 234 |
+
free(current->undirected_edges_list);
|
| 235 |
+
free(current);
|
| 236 |
+
}
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
void free_LongToDirectedEdgeList_in_nodes(Node* nodes, long num_nodes) {
|
| 240 |
+
LongToDirectedEdgeList* current;
|
| 241 |
+
LongToDirectedEdgeList* tmp;
|
| 242 |
+
|
| 243 |
+
for (long node_i = 0; node_i < num_nodes; node_i++) {
|
| 244 |
+
HASH_ITER(hh, nodes[node_i].neighbors, current, tmp) {
|
| 245 |
+
HASH_DEL(nodes[node_i].neighbors, current);
|
| 246 |
+
free(current->directed_edges_list);
|
| 247 |
+
free(current);
|
| 248 |
+
}
|
| 249 |
+
}
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
// Returns true if the two directed edges have images that are inverted
|
| 253 |
+
// NOTE: assumes that directed_edge1->center = directed_edge2->neighbor and directed_edge1->neighbor = directed_edge2->center
|
| 254 |
+
bool is_reversed_directed_edge(DirectedEdge* directed_edge1, DirectedEdge* directed_edge2) {
|
| 255 |
+
for (int i = 0; i < 3; i++) {
|
| 256 |
+
if (directed_edge1->image[i] != -1 * directed_edge2->image[i]) {
|
| 257 |
+
return false;
|
| 258 |
+
}
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
// The two directed edges should have opposing center/neighbor nodes (i.e. center-neighbor for DE1 is [0, 1] and for DE2 is [1, 0])
|
| 262 |
+
// We check for that condition here
|
| 263 |
+
if (directed_edge1->nodes.center != directed_edge2->nodes.neighbor) {
|
| 264 |
+
return false;
|
| 265 |
+
}
|
| 266 |
+
if (directed_edge1->nodes.neighbor != directed_edge2->nodes.center) {
|
| 267 |
+
return false;
|
| 268 |
+
}
|
| 269 |
+
return true;
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
// If tmp or the reverse of tmp is found in undirected_edges, True is returned and the corresponding StructToUndirectedEdgeList pointer is placed
|
| 273 |
+
// into found_entry. Otherwise, False is returned.
|
| 274 |
+
// NOTE: does not edit the *tmp
|
| 275 |
+
// Assumes *tmp bits have already been 0'd at padding within a struct
|
| 276 |
+
bool find_in_undirected(NodeIndexPair* tmp, StructToUndirectedEdgeList** undirected_edges, StructToUndirectedEdgeList** found_entry) {
|
| 277 |
+
StructToUndirectedEdgeList* out_list;
|
| 278 |
+
// Check tmp
|
| 279 |
+
HASH_FIND(hh, *undirected_edges, tmp, sizeof(NodeIndexPair), out_list);
|
| 280 |
+
|
| 281 |
+
if (out_list) {
|
| 282 |
+
*found_entry = out_list;
|
| 283 |
+
return true;
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
// Check tmp_rev
|
| 287 |
+
NodeIndexPair tmp_rev;
|
| 288 |
+
tmp_rev.center = tmp->neighbor;
|
| 289 |
+
tmp_rev.neighbor = tmp->center;
|
| 290 |
+
|
| 291 |
+
HASH_FIND(hh, *undirected_edges, &tmp_rev, sizeof(NodeIndexPair), out_list);
|
| 292 |
+
|
| 293 |
+
if (out_list) {
|
| 294 |
+
*found_entry = out_list;
|
| 295 |
+
return true;
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
return false;
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
// Creates new entry in undirected_edges and initializes necessary arrays
|
| 303 |
+
void create_new_undirected_edges_entry(StructToUndirectedEdgeList** undirected_edges, NodeIndexPair* tmp, UndirectedEdge* new_undirected_edge) {
|
| 304 |
+
StructToUndirectedEdgeList* new_entry = malloc(sizeof(StructToUndirectedEdgeList));
|
| 305 |
+
memset(new_entry, 0, sizeof(StructToUndirectedEdgeList));
|
| 306 |
+
|
| 307 |
+
// Set up fields within the new entry in the hashmap
|
| 308 |
+
new_entry->key.center = tmp->center;
|
| 309 |
+
new_entry->key.neighbor = tmp->neighbor;
|
| 310 |
+
|
| 311 |
+
new_entry->num_undirected_edges_in_group = 1;
|
| 312 |
+
new_entry->undirected_edges_list = malloc(sizeof(UndirectedEdge*));
|
| 313 |
+
new_entry->undirected_edges_list[0] = new_undirected_edge;
|
| 314 |
+
|
| 315 |
+
HASH_ADD(hh, *undirected_edges, key, sizeof(NodeIndexPair), new_entry);
|
| 316 |
+
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
// Appends undirected into the StructToUndirectedEdgeList entry that corresponds to tmp
|
| 320 |
+
// This function will first look up tmp
|
| 321 |
+
void append_to_undirected_edges_tmp(UndirectedEdge* undirected, StructToUndirectedEdgeList** undirected_edges, NodeIndexPair* tmp) {
|
| 322 |
+
|
| 323 |
+
StructToUndirectedEdgeList* this_undirected_edges_item;
|
| 324 |
+
find_in_undirected(tmp, undirected_edges, &this_undirected_edges_item);
|
| 325 |
+
|
| 326 |
+
long num_undirected_edges = this_undirected_edges_item->num_undirected_edges_in_group;
|
| 327 |
+
|
| 328 |
+
// No need to worry about originally malloc'ing memory for this_undirected_edges_item->undirected_edges_list
|
| 329 |
+
// this is because, we first call create_new_undirected_edges_entry for all entries. This function already mallocs for us.
|
| 330 |
+
|
| 331 |
+
// Realloc the space to fit a new pointer to an undirected edge
|
| 332 |
+
UndirectedEdge** new_list = realloc(this_undirected_edges_item->undirected_edges_list, sizeof(UndirectedEdge*) * (num_undirected_edges + 1));
|
| 333 |
+
this_undirected_edges_item->undirected_edges_list = new_list;
|
| 334 |
+
|
| 335 |
+
// Insert the undirected pointer into the newly allocated slot
|
| 336 |
+
this_undirected_edges_item->undirected_edges_list[num_undirected_edges] = undirected;
|
| 337 |
+
|
| 338 |
+
// Increase the counter for # of undirected edges
|
| 339 |
+
this_undirected_edges_item->num_undirected_edges_in_group = num_undirected_edges + 1;
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
void directed_to_undirected(DirectedEdge* directed, UndirectedEdge* undirected, long undirected_index) {
|
| 344 |
+
// Copy over image and distance
|
| 345 |
+
undirected->distance = directed->distance;
|
| 346 |
+
undirected->nodes = directed->nodes;
|
| 347 |
+
undirected->index = undirected_index;
|
| 348 |
+
|
| 349 |
+
// Add a new directed_edge_index to the directed_edge_indices pointer. This should be the first
|
| 350 |
+
undirected->num_directed_edges = 1;
|
| 351 |
+
undirected->directed_edge_indices = malloc(sizeof(long));
|
| 352 |
+
undirected->directed_edge_indices[0] = directed->index;
|
| 353 |
+
}
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
void append_to_undirected_edges_list(UndirectedEdge** undirected_edges_list, UndirectedEdge* to_add, long* num_undirected_edges) {
|
| 357 |
+
// No need to realloc for space since our original alloc should cover everything
|
| 358 |
+
|
| 359 |
+
// Assign value to next available position
|
| 360 |
+
undirected_edges_list[*num_undirected_edges] = to_add;
|
| 361 |
+
*num_undirected_edges += 1;
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
void append_to_directed_edges_list(DirectedEdge** directed_edges_list, DirectedEdge* to_add, long* num_directed_edges) {
|
| 365 |
+
// No need to realloc for space since our original alloc should cover everything
|
| 366 |
+
|
| 367 |
+
// Assign value to next available position
|
| 368 |
+
directed_edges_list[*num_directed_edges] = to_add;
|
| 369 |
+
*num_directed_edges += 1;
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
void append_to_directed_edge_indices(UndirectedEdge* undirected_edge, long directed_edge_index) {
|
| 373 |
+
// TODO: don't need to realloc if we always know that there will be 2 directed edges per undirected edge. Update this later for performance boosts.
|
| 374 |
+
// TODO: other random performance boost: don't pass longs into function parameters, pass long* instead
|
| 375 |
+
undirected_edge->directed_edge_indices = realloc(undirected_edge->directed_edge_indices, sizeof(long) * (undirected_edge->num_directed_edges + 1));
|
| 376 |
+
undirected_edge->directed_edge_indices[undirected_edge->num_directed_edges] = directed_edge_index;
|
| 377 |
+
undirected_edge->num_directed_edges += 1;
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
// If there already exists neighbor_index within the Node node, then adds directed_edge to the list of directed edges.
|
| 381 |
+
// If there doesn't already exist neighbor_index within the Node node, then create a new entry into the node's neighbors hashmap and add the entry
|
| 382 |
+
void add_neighbors_to_node(Node* node, long neighbor_index, DirectedEdge* directed_edge) {
|
| 383 |
+
LongToDirectedEdgeList* entry = NULL;
|
| 384 |
+
|
| 385 |
+
// Search for the neighbor_index in our hashmap
|
| 386 |
+
HASH_FIND(hh, node->neighbors, &neighbor_index, sizeof(long), entry);
|
| 387 |
+
|
| 388 |
+
if (entry) {
|
| 389 |
+
// We found something, update the list within this pointer
|
| 390 |
+
entry->directed_edges_list = realloc(entry->directed_edges_list, sizeof(DirectedEdge*) * (entry->num_directed_edges_in_group + 1));
|
| 391 |
+
entry->directed_edges_list[entry->num_directed_edges_in_group] = directed_edge;
|
| 392 |
+
|
| 393 |
+
entry->num_directed_edges_in_group += 1;
|
| 394 |
+
} else {
|
| 395 |
+
// allocate memory for entry
|
| 396 |
+
entry = malloc(sizeof(LongToDirectedEdgeList));
|
| 397 |
+
|
| 398 |
+
// The entry doesn't exist, initialize the entry and enter it into our hashmap
|
| 399 |
+
entry->directed_edges_list = malloc(sizeof(DirectedEdge*));
|
| 400 |
+
entry->directed_edges_list[0] = directed_edge;
|
| 401 |
+
entry->key = neighbor_index;
|
| 402 |
+
|
| 403 |
+
entry->num_directed_edges_in_group = 1;
|
| 404 |
+
HASH_ADD(hh, node->neighbors, key, sizeof(long), entry);
|
| 405 |
+
|
| 406 |
+
node->num_neighbors += 1;
|
| 407 |
+
}
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
// Returns a list of LongToDirectedEdgeList pointers which are entries for the neighbors of the inputted node
|
| 411 |
+
LongToDirectedEdgeList** get_neighbors(Node* node) {
|
| 412 |
+
long num_neighbors = HASH_COUNT(node->neighbors);
|
| 413 |
+
LongToDirectedEdgeList** entries = malloc(sizeof(LongToDirectedEdgeList*) * num_neighbors);
|
| 414 |
+
|
| 415 |
+
LongToDirectedEdgeList* entry;
|
| 416 |
+
long counter = 0;
|
| 417 |
+
for (entry = node->neighbors; entry != NULL; entry = entry->hh.next) {
|
| 418 |
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
Copyright (c) 2003-2022, Troy D. Hanson https://troydhanson.github.io/uthash/
|
| 3 |
+
All rights reserved.
|
| 4 |
+
|
| 5 |
+
Redistribution and use in source and binary forms, with or without
|
| 6 |
+
modification, are permitted provided that the following conditions are met:
|
| 7 |
+
|
| 8 |
+
* Redistributions of source code must retain the above copyright
|
| 9 |
+
notice, this list of conditions and the following disclaimer.
|
| 10 |
+
|
| 11 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
|
| 12 |
+
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
|
| 13 |
+
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
|
| 14 |
+
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
|
| 15 |
+
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
| 16 |
+
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
| 17 |
+
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
| 18 |
+
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
| 19 |
+
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
| 20 |
+
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
| 21 |
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 22 |
+
*/
|
| 23 |
+
|
| 24 |
+
#ifndef UTHASH_H
|
| 25 |
+
#define UTHASH_H
|
| 26 |
+
|
| 27 |
+
#define UTHASH_VERSION 2.3.0
|
| 28 |
+
|
| 29 |
+
#include <string.h> /* memcmp, memset, strlen */
|
| 30 |
+
#include <stddef.h> /* ptrdiff_t */
|
| 31 |
+
#include <stdlib.h> /* exit */
|
| 32 |
+
|
| 33 |
+
#if defined(HASH_DEFINE_OWN_STDINT) && HASH_DEFINE_OWN_STDINT
|
| 34 |
+
/* This codepath is provided for backward compatibility, but I plan to remove it. */
|
| 35 |
+
#warning "HASH_DEFINE_OWN_STDINT is deprecated; please use HASH_NO_STDINT instead"
|
| 36 |
+
typedef unsigned int uint32_t;
|
| 37 |
+
typedef unsigned char uint8_t;
|
| 38 |
+
#elif defined(HASH_NO_STDINT) && HASH_NO_STDINT
|
| 39 |
+
#else
|
| 40 |
+
#include <stdint.h> /* uint8_t, uint32_t */
|
| 41 |
+
#endif
|
| 42 |
+
|
| 43 |
+
/* These macros use decltype or the earlier __typeof GNU extension.
|
| 44 |
+
As decltype is only available in newer compilers (VS2010 or gcc 4.3+
|
| 45 |
+
when compiling c++ source) this code uses whatever method is needed
|
| 46 |
+
or, for VS2008 where neither is available, uses casting workarounds. */
|
| 47 |
+
#if !defined(DECLTYPE) && !defined(NO_DECLTYPE)
|
| 48 |
+
#if defined(_MSC_VER) /* MS compiler */
|
| 49 |
+
#if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */
|
| 50 |
+
#define DECLTYPE(x) (decltype(x))
|
| 51 |
+
#else /* VS2008 or older (or VS2010 in C mode) */
|
| 52 |
+
#define NO_DECLTYPE
|
| 53 |
+
#endif
|
| 54 |
+
#elif defined(__MCST__) /* Elbrus C Compiler */
|
| 55 |
+
#define DECLTYPE(x) (__typeof(x))
|
| 56 |
+
#elif defined(__BORLANDC__) || defined(__ICCARM__) || defined(__LCC__) || defined(__WATCOMC__)
|
| 57 |
+
#define NO_DECLTYPE
|
| 58 |
+
#else /* GNU, Sun and other compilers */
|
| 59 |
+
#define DECLTYPE(x) (__typeof(x))
|
| 60 |
+
#endif
|
| 61 |
+
#endif
|
| 62 |
+
|
| 63 |
+
#ifdef NO_DECLTYPE
|
| 64 |
+
#define DECLTYPE(x)
|
| 65 |
+
#define DECLTYPE_ASSIGN(dst,src) \
|
| 66 |
+
do { \
|
| 67 |
+
char **_da_dst = (char**)(&(dst)); \
|
| 68 |
+
*_da_dst = (char*)(src); \
|
| 69 |
+
} while (0)
|
| 70 |
+
#else
|
| 71 |
+
#define DECLTYPE_ASSIGN(dst,src) \
|
| 72 |
+
do { \
|
| 73 |
+
(dst) = DECLTYPE(dst)(src); \
|
| 74 |
+
} while (0)
|
| 75 |
+
#endif
|
| 76 |
+
|
| 77 |
+
#ifndef uthash_malloc
|
| 78 |
+
#define uthash_malloc(sz) malloc(sz) /* malloc fcn */
|
| 79 |
+
#endif
|
| 80 |
+
#ifndef uthash_free
|
| 81 |
+
#define uthash_free(ptr,sz) free(ptr) /* free fcn */
|
| 82 |
+
#endif
|
| 83 |
+
#ifndef uthash_bzero
|
| 84 |
+
#define uthash_bzero(a,n) memset(a,'\0',n)
|
| 85 |
+
#endif
|
| 86 |
+
#ifndef uthash_strlen
|
| 87 |
+
#define uthash_strlen(s) strlen(s)
|
| 88 |
+
#endif
|
| 89 |
+
|
| 90 |
+
#ifndef HASH_FUNCTION
|
| 91 |
+
#define HASH_FUNCTION(keyptr,keylen,hashv) HASH_JEN(keyptr, keylen, hashv)
|
| 92 |
+
#endif
|
| 93 |
+
|
| 94 |
+
#ifndef HASH_KEYCMP
|
| 95 |
+
#define HASH_KEYCMP(a,b,n) memcmp(a,b,n)
|
| 96 |
+
#endif
|
| 97 |
+
|
| 98 |
+
#ifndef uthash_noexpand_fyi
|
| 99 |
+
#define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */
|
| 100 |
+
#endif
|
| 101 |
+
#ifndef uthash_expand_fyi
|
| 102 |
+
#define uthash_expand_fyi(tbl) /* can be defined to log expands */
|
| 103 |
+
#endif
|
| 104 |
+
|
| 105 |
+
#ifndef HASH_NONFATAL_OOM
|
| 106 |
+
#define HASH_NONFATAL_OOM 0
|
| 107 |
+
#endif
|
| 108 |
+
|
| 109 |
+
#if HASH_NONFATAL_OOM
|
| 110 |
+
/* malloc failures can be recovered from */
|
| 111 |
+
|
| 112 |
+
#ifndef uthash_nonfatal_oom
|
| 113 |
+
#define uthash_nonfatal_oom(obj) do {} while (0) /* non-fatal OOM error */
|
| 114 |
+
#endif
|
| 115 |
+
|
| 116 |
+
#define HASH_RECORD_OOM(oomed) do { (oomed) = 1; } while (0)
|
| 117 |
+
#define IF_HASH_NONFATAL_OOM(x) x
|
| 118 |
+
|
| 119 |
+
#else
|
| 120 |
+
/* malloc failures result in lost memory, hash tables are unusable */
|
| 121 |
+
|
| 122 |
+
#ifndef uthash_fatal
|
| 123 |
+
#define uthash_fatal(msg) exit(-1) /* fatal OOM error */
|
| 124 |
+
#endif
|
| 125 |
+
|
| 126 |
+
#define HASH_RECORD_OOM(oomed) uthash_fatal("out of memory")
|
| 127 |
+
#define IF_HASH_NONFATAL_OOM(x)
|
| 128 |
+
|
| 129 |
+
#endif
|
| 130 |
+
|
| 131 |
+
/* initial number of buckets */
|
| 132 |
+
#define HASH_INITIAL_NUM_BUCKETS 32U /* initial number of buckets */
|
| 133 |
+
#define HASH_INITIAL_NUM_BUCKETS_LOG2 5U /* lg2 of initial number of buckets */
|
| 134 |
+
#define HASH_BKT_CAPACITY_THRESH 10U /* expand when bucket count reaches */
|
| 135 |
+
|
| 136 |
+
/* calculate the element whose hash handle address is hhp */
|
| 137 |
+
#define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho)))
|
| 138 |
+
/* calculate the hash handle from element address elp */
|
| 139 |
+
#define HH_FROM_ELMT(tbl,elp) ((UT_hash_handle*)(void*)(((char*)(elp)) + ((tbl)->hho)))
|
| 140 |
+
|
| 141 |
+
#define HASH_ROLLBACK_BKT(hh, head, itemptrhh) \
|
| 142 |
+
do { \
|
| 143 |
+
struct UT_hash_handle *_hd_hh_item = (itemptrhh); \
|
| 144 |
+
unsigned _hd_bkt; \
|
| 145 |
+
HASH_TO_BKT(_hd_hh_item->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \
|
| 146 |
+
(head)->hh.tbl->buckets[_hd_bkt].count++; \
|
| 147 |
+
_hd_hh_item->hh_next = NULL; \
|
| 148 |
+
_hd_hh_item->hh_prev = NULL; \
|
| 149 |
+
} while (0)
|
| 150 |
+
|
| 151 |
+
#define HASH_VALUE(keyptr,keylen,hashv) \
|
| 152 |
+
do { \
|
| 153 |
+
HASH_FUNCTION(keyptr, keylen, hashv); \
|
| 154 |
+
} while (0)
|
| 155 |
+
|
| 156 |
+
#define HASH_FIND_BYHASHVALUE(hh,head,keyptr,keylen,hashval,out) \
|
| 157 |
+
do { \
|
| 158 |
+
(out) = NULL; \
|
| 159 |
+
if (head) { \
|
| 160 |
+
unsigned _hf_bkt; \
|
| 161 |
+
HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _hf_bkt); \
|
| 162 |
+
if (HASH_BLOOM_TEST((head)->hh.tbl, hashval) != 0) { \
|
| 163 |
+
HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], keyptr, keylen, hashval, out); \
|
| 164 |
+
} \
|
| 165 |
+
} \
|
| 166 |
+
} while (0)
|
| 167 |
+
|
| 168 |
+
#define HASH_FIND(hh,head,keyptr,keylen,out) \
|
| 169 |
+
do { \
|
| 170 |
+
(out) = NULL; \
|
| 171 |
+
if (head) { \
|
| 172 |
+
unsigned _hf_hashv; \
|
| 173 |
+
HASH_VALUE(keyptr, keylen, _hf_hashv); \
|
| 174 |
+
HASH_FIND_BYHASHVALUE(hh, head, keyptr, keylen, _hf_hashv, out); \
|
| 175 |
+
} \
|
| 176 |
+
} while (0)
|
| 177 |
+
|
| 178 |
+
#ifdef HASH_BLOOM
|
| 179 |
+
#define HASH_BLOOM_BITLEN (1UL << HASH_BLOOM)
|
| 180 |
+
#define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8UL) + (((HASH_BLOOM_BITLEN%8UL)!=0UL) ? 1UL : 0UL)
|
| 181 |
+
#define HASH_BLOOM_MAKE(tbl,oomed) \
|
| 182 |
+
do { \
|
| 183 |
+
(tbl)->bloom_nbits = HASH_BLOOM; \
|
| 184 |
+
(tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN); \
|
| 185 |
+
if (!(tbl)->bloom_bv) { \
|
| 186 |
+
HASH_RECORD_OOM(oomed); \
|
| 187 |
+
} else { \
|
| 188 |
+
uthash_bzero((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \
|
| 189 |
+
(tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \
|
| 190 |
+
} \
|
| 191 |
+
} while (0)
|
| 192 |
+
|
| 193 |
+
#define HASH_BLOOM_FREE(tbl) \
|
| 194 |
+
do { \
|
| 195 |
+
uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \
|
| 196 |
+
} while (0)
|
| 197 |
+
|
| 198 |
+
#define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8U] |= (1U << ((idx)%8U)))
|
| 199 |
+
#define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8U] & (1U << ((idx)%8U)))
|
| 200 |
+
|
| 201 |
+
#define HASH_BLOOM_ADD(tbl,hashv) \
|
| 202 |
+
HASH_BLOOM_BITSET((tbl)->bloom_bv, ((hashv) & (uint32_t)((1UL << (tbl)->bloom_nbits) - 1U)))
|
| 203 |
+
|
| 204 |
+
#define HASH_BLOOM_TEST(tbl,hashv) \
|
| 205 |
+
HASH_BLOOM_BITTEST((tbl)->bloom_bv, ((hashv) & (uint32_t)((1UL << (tbl)->bloom_nbits) - 1U)))
|
| 206 |
+
|
| 207 |
+
#else
|
| 208 |
+
#define HASH_BLOOM_MAKE(tbl,oomed)
|
| 209 |
+
#define HASH_BLOOM_FREE(tbl)
|
| 210 |
+
#define HASH_BLOOM_ADD(tbl,hashv)
|
| 211 |
+
#define HASH_BLOOM_TEST(tbl,hashv) (1)
|
| 212 |
+
#define HASH_BLOOM_BYTELEN 0U
|
| 213 |
+
#endif
|
| 214 |
+
|
| 215 |
+
#define HASH_MAKE_TABLE(hh,head,oomed) \
|
| 216 |
+
do { \
|
| 217 |
+
(head)->hh.tbl = (UT_hash_table*)uthash_malloc(sizeof(UT_hash_table)); \
|
| 218 |
+
if (!(head)->hh.tbl) { \
|
| 219 |
+
HASH_RECORD_OOM(oomed); \
|
| 220 |
+
} else { \
|
| 221 |
+
uthash_bzero((head)->hh.tbl, sizeof(UT_hash_table)); \
|
| 222 |
+
(head)->hh.tbl->tail = &((head)->hh); \
|
| 223 |
+
(head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS; \
|
| 224 |
+
(head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2; \
|
| 225 |
+
(head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head); \
|
| 226 |
+
(head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc( \
|
| 227 |
+
HASH_INITIAL_NUM_BUCKETS * sizeof(struct UT_hash_bucket)); \
|
| 228 |
+
(head)->hh.tbl->signature = HASH_SIGNATURE; \
|
| 229 |
+
if (!(head)->hh.tbl->buckets) { \
|
| 230 |
+
HASH_RECORD_OOM(oomed); \
|
| 231 |
+
uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \
|
| 232 |
+
} else { \
|
| 233 |
+
uthash_bzero((head)->hh.tbl->buckets, \
|
| 234 |
+
HASH_INITIAL_NUM_BUCKETS * sizeof(struct UT_hash_bucket)); \
|
| 235 |
+
HASH_BLOOM_MAKE((head)->hh.tbl, oomed); \
|
| 236 |
+
IF_HASH_NONFATAL_OOM( \
|
| 237 |
+
if (oomed) { \
|
| 238 |
+
uthash_free((head)->hh.tbl->buckets, \
|
| 239 |
+
HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \
|
| 240 |
+
uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \
|
| 241 |
+
} \
|
| 242 |
+
) \
|
| 243 |
+
} \
|
| 244 |
+
} \
|
| 245 |
+
} while (0)
|
| 246 |
+
|
| 247 |
+
#define HASH_REPLACE_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,replaced,cmpfcn) \
|
| 248 |
+
do { \
|
| 249 |
+
(replaced) = NULL; \
|
| 250 |
+
HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \
|
| 251 |
+
if (replaced) { \
|
| 252 |
+
HASH_DELETE(hh, head, replaced); \
|
| 253 |
+
} \
|
| 254 |
+
HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn); \
|
| 255 |
+
} while (0)
|
| 256 |
+
|
| 257 |
+
#define HASH_REPLACE_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add,replaced) \
|
| 258 |
+
do { \
|
| 259 |
+
(replaced) = NULL; \
|
| 260 |
+
HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \
|
| 261 |
+
if (replaced) { \
|
| 262 |
+
HASH_DELETE(hh, head, replaced); \
|
| 263 |
+
} \
|
| 264 |
+
HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add); \
|
| 265 |
+
} while (0)
|
| 266 |
+
|
| 267 |
+
#define HASH_REPLACE(hh,head,fieldname,keylen_in,add,replaced) \
|
| 268 |
+
do { \
|
| 269 |
+
unsigned _hr_hashv; \
|
| 270 |
+
HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \
|
| 271 |
+
HASH_REPLACE_BYHASHVALUE(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced); \
|
| 272 |
+
} while (0)
|
| 273 |
+
|
| 274 |
+
#define HASH_REPLACE_INORDER(hh,head,fieldname,keylen_in,add,replaced,cmpfcn) \
|
| 275 |
+
do { \
|
| 276 |
+
unsigned _hr_hashv; \
|
| 277 |
+
HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \
|
| 278 |
+
HASH_REPLACE_BYHASHVALUE_INORDER(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced, cmpfcn); \
|
| 279 |
+
} while (0)
|
| 280 |
+
|
| 281 |
+
#define HASH_APPEND_LIST(hh, head, add) \
|
| 282 |
+
do { \
|
| 283 |
+
(add)->hh.next = NULL; \
|
| 284 |
+
(add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \
|
| 285 |
+
(head)->hh.tbl->tail->next = (add); \
|
| 286 |
+
(head)->hh.tbl->tail = &((add)->hh); \
|
| 287 |
+
} while (0)
|
| 288 |
+
|
| 289 |
+
#define HASH_AKBI_INNER_LOOP(hh,head,add,cmpfcn) \
|
| 290 |
+
do { \
|
| 291 |
+
do { \
|
| 292 |
+
if (cmpfcn(DECLTYPE(head)(_hs_iter), add) > 0) { \
|
| 293 |
+
break; \
|
| 294 |
+
} \
|
| 295 |
+
} while ((_hs_iter = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->next)); \
|
| 296 |
+
} while (0)
|
| 297 |
+
|
| 298 |
+
#ifdef NO_DECLTYPE
|
| 299 |
+
#undef HASH_AKBI_INNER_LOOP
|
| 300 |
+
#define HASH_AKBI_INNER_LOOP(hh,head,add,cmpfcn) \
|
| 301 |
+
do { \
|
| 302 |
+
char *_hs_saved_head = (char*)(head); \
|
| 303 |
+
do { \
|
| 304 |
+
DECLTYPE_ASSIGN(head, _hs_iter); \
|
| 305 |
+
if (cmpfcn(head, add) > 0) { \
|
| 306 |
+
DECLTYPE_ASSIGN(head, _hs_saved_head); \
|
| 307 |
+
break; \
|
| 308 |
+
} \
|
| 309 |
+
DECLTYPE_ASSIGN(head, _hs_saved_head); \
|
| 310 |
+
} while ((_hs_iter = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->next)); \
|
| 311 |
+
} while (0)
|
| 312 |
+
#endif
|
| 313 |
+
|
| 314 |
+
#if HASH_NONFATAL_OOM
|
| 315 |
+
|
| 316 |
+
#define HASH_ADD_TO_TABLE(hh,head,keyptr,keylen_in,hashval,add,oomed) \
|
| 317 |
+
do { \
|
| 318 |
+
if (!(oomed)) { \
|
| 319 |
+
unsigned _ha_bkt; \
|
| 320 |
+
(head)->hh.tbl->num_items++; \
|
| 321 |
+
HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \
|
| 322 |
+
HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], hh, &(add)->hh, oomed); \
|
| 323 |
+
if (oomed) { \
|
| 324 |
+
HASH_ROLLBACK_BKT(hh, head, &(add)->hh); \
|
| 325 |
+
HASH_DELETE_HH(hh, head, &(add)->hh); \
|
| 326 |
+
(add)->hh.tbl = NULL; \
|
| 327 |
+
uthash_nonfatal_oom(add); \
|
| 328 |
+
} else { \
|
| 329 |
+
HASH_BLOOM_ADD((head)->hh.tbl, hashval); \
|
| 330 |
+
HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \
|
| 331 |
+
} \
|
| 332 |
+
} else { \
|
| 333 |
+
(add)->hh.tbl = NULL; \
|
| 334 |
+
uthash_nonfatal_oom(add); \
|
| 335 |
+
} \
|
| 336 |
+
} while (0)
|
| 337 |
+
|
| 338 |
+
#else
|
| 339 |
+
|
| 340 |
+
#define HASH_ADD_TO_TABLE(hh,head,keyptr,keylen_in,hashval,add,oomed) \
|
| 341 |
+
do { \
|
| 342 |
+
unsigned _ha_bkt; \
|
| 343 |
+
(head)->hh.tbl->num_items++; \
|
| 344 |
+
HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \
|
| 345 |
+
HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], hh, &(add)->hh, oomed); \
|
| 346 |
+
HASH_BLOOM_ADD((head)->hh.tbl, hashval); \
|
| 347 |
+
HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \
|
| 348 |
+
} while (0)
|
| 349 |
+
|
| 350 |
+
#endif
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
#define HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh,head,keyptr,keylen_in,hashval,add,cmpfcn) \
|
| 354 |
+
do { \
|
| 355 |
+
IF_HASH_NONFATAL_OOM( int _ha_oomed = 0; ) \
|
| 356 |
+
(add)->hh.hashv = (hashval); \
|
| 357 |
+
(add)->hh.key = (char*) (keyptr); \
|
| 358 |
+
(add)->hh.keylen = (unsigned) (keylen_in); \
|
| 359 |
+
if (!(head)) { \
|
| 360 |
+
(add)->hh.next = NULL; \
|
| 361 |
+
(add)->hh.prev = NULL; \
|
| 362 |
+
HASH_MAKE_TABLE(hh, add, _ha_oomed); \
|
| 363 |
+
IF_HASH_NONFATAL_OOM( if (!_ha_oomed) { ) \
|
| 364 |
+
(head) = (add); \
|
| 365 |
+
IF_HASH_NONFATAL_OOM( } ) \
|
| 366 |
+
} else { \
|
| 367 |
+
void *_hs_iter = (head); \
|
| 368 |
+
(add)->hh.tbl = (head)->hh.tbl; \
|
| 369 |
+
HASH_AKBI_INNER_LOOP(hh, head, add, cmpfcn); \
|
| 370 |
+
if (_hs_iter) { \
|
| 371 |
+
(add)->hh.next = _hs_iter; \
|
| 372 |
+
if (((add)->hh.prev = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->prev)) { \
|
| 373 |
+
HH_FROM_ELMT((head)->hh.tbl, (add)->hh.prev)->next = (add); \
|
| 374 |
+
} else { \
|
| 375 |
+
(head) = (add); \
|
| 376 |
+
} \
|
| 377 |
+
HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->prev = (add); \
|
| 378 |
+
} else { \
|
| 379 |
+
HASH_APPEND_LIST(hh, head, add); \
|
| 380 |
+
} \
|
| 381 |
+
} \
|
| 382 |
+
HASH_ADD_TO_TABLE(hh, head, keyptr, keylen_in, hashval, add, _ha_oomed); \
|
| 383 |
+
HASH_FSCK(hh, head, "HASH_ADD_KEYPTR_BYHASHVALUE_INORDER"); \
|
| 384 |
+
} while (0)
|
| 385 |
+
|
| 386 |
+
#define HASH_ADD_KEYPTR_INORDER(hh,head,keyptr,keylen_in,add,cmpfcn) \
|
| 387 |
+
do { \
|
| 388 |
+
unsigned _hs_hashv; \
|
| 389 |
+
HASH_VALUE(keyptr, keylen_in, _hs_hashv); \
|
| 390 |
+
HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, keyptr, keylen_in, _hs_hashv, add, cmpfcn); \
|
| 391 |
+
} while (0)
|
| 392 |
+
|
| 393 |
+
#define HASH_ADD_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,cmpfcn) \
|
| 394 |
+
HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn)
|
| 395 |
+
|
| 396 |
+
#define HASH_ADD_INORDER(hh,head,fieldname,keylen_in,add,cmpfcn) \
|
| 397 |
+
HASH_ADD_KEYPTR_INORDER(hh, head, &((add)->fieldname), keylen_in, add, cmpfcn)
|
| 398 |
+
|
| 399 |
+
#define HASH_ADD_KEYPTR_BYHASHVALUE(hh,head,keyptr,keylen_in,hashval,add) \
|
| 400 |
+
do { \
|
| 401 |
+
IF_HASH_NONFATAL_OOM( int _ha_oomed = 0; ) \
|
| 402 |
+
(add)->hh.hashv = (hashval); \
|
| 403 |
+
(add)->hh.key = (const void*) (keyptr); \
|
| 404 |
+
(add)->hh.keylen = (unsigned) (keylen_in); \
|
| 405 |
+
if (!(head)) { \
|
| 406 |
+
(add)->hh.next = NULL; \
|
| 407 |
+
(add)->hh.prev = NULL; \
|
| 408 |
+
HASH_MAKE_TABLE(hh, add, _ha_oomed); \
|
| 409 |
+
IF_HASH_NONFATAL_OOM( if (!_ha_oomed) { ) \
|
| 410 |
+
(head) = (add); \
|
| 411 |
+
IF_HASH_NONFATAL_OOM( } ) \
|
| 412 |
+
} else { \
|
| 413 |
+
(add)->hh.tbl = (head)->hh.tbl; \
|
| 414 |
+
HASH_APPEND_LIST(hh, head, add); \
|
| 415 |
+
} \
|
| 416 |
+
HASH_ADD_TO_TABLE(hh, head, keyptr, keylen_in, hashval, add, _ha_oomed); \
|
| 417 |
+
HASH_FSCK(hh, head, "HASH_ADD_KEYPTR_BYHASHVALUE"); \
|
| 418 |
+
} while (0)
|
| 419 |
+
|
| 420 |
+
#define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \
|
| 421 |
+
do { \
|
| 422 |
+
unsigned _ha_hashv; \
|
| 423 |
+
HASH_VALUE(keyptr, keylen_in, _ha_hashv); \
|
| 424 |
+
HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, keyptr, keylen_in, _ha_hashv, add); \
|
| 425 |
+
} while (0)
|
| 426 |
+
|
| 427 |
+
#define HASH_ADD_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add) \
|
| 428 |
+
HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add)
|
| 429 |
+
|
| 430 |
+
#define HASH_ADD(hh,head,fieldname,keylen_in,add) \
|
| 431 |
+
HASH_ADD_KEYPTR(hh, head, &((add)->fieldname), keylen_in, add)
|
| 432 |
+
|
| 433 |
+
#define HASH_TO_BKT(hashv,num_bkts,bkt) \
|
| 434 |
+
do { \
|
| 435 |
+
bkt = ((hashv) & ((num_bkts) - 1U)); \
|
| 436 |
+
} while (0)
|
| 437 |
+
|
| 438 |
+
/* delete "delptr" from the hash table.
|
| 439 |
+
* "the usual" patch-up process for the app-order doubly-linked-list.
|
| 440 |
+
* The use of _hd_hh_del below deserves special explanation.
|
| 441 |
+
* These used to be expressed using (delptr) but that led to a bug
|
| 442 |
+
* if someone used the same symbol for the head and deletee, like
|
| 443 |
+
* HASH_DELETE(hh,users,users);
|
| 444 |
+
* We want that to work, but by changing the head (users) below
|
| 445 |
+
* we were forfeiting our ability to further refer to the deletee (users)
|
| 446 |
+
* in the patch-up process. Solution: use scratch space to
|
| 447 |
+
* copy the deletee pointer, then the latter references are via that
|
| 448 |
+
* scratch pointer rather than through the repointed (users) symbol.
|
| 449 |
+
*/
|
| 450 |
+
#define HASH_DELETE(hh,head,delptr) \
|
| 451 |
+
HASH_DELETE_HH(hh, head, &(delptr)->hh)
|
| 452 |
+
|
| 453 |
+
#define HASH_DELETE_HH(hh,head,delptrhh) \
|
| 454 |
+
do { \
|
| 455 |
+
const struct UT_hash_handle *_hd_hh_del = (delptrhh); \
|
| 456 |
+
if ((_hd_hh_del->prev == NULL) && (_hd_hh_del->next == NULL)) { \
|
| 457 |
+
HASH_BLOOM_FREE((head)->hh.tbl); \
|
| 458 |
+
uthash_free((head)->hh.tbl->buckets, \
|
| 459 |
+
(head)->hh.tbl->num_buckets * sizeof(struct UT_hash_bucket)); \
|
| 460 |
+
uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \
|
| 461 |
+
(head) = NULL; \
|
| 462 |
+
} else { \
|
| 463 |
+
unsigned _hd_bkt; \
|
| 464 |
+
if (_hd_hh_del == (head)->hh.tbl->tail) { \
|
| 465 |
+
(head)->hh.tbl->tail = HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->prev); \
|
| 466 |
+
} \
|
| 467 |
+
if (_hd_hh_del->prev != NULL) { \
|
| 468 |
+
HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->prev)->next = _hd_hh_del->next; \
|
| 469 |
+
} else { \
|
| 470 |
+
DECLTYPE_ASSIGN(head, _hd_hh_del->next); \
|
| 471 |
+
} \
|
| 472 |
+
if (_hd_hh_del->next != NULL) { \
|
| 473 |
+
HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->next)->prev = _hd_hh_del->prev; \
|
| 474 |
+
} \
|
| 475 |
+
HASH_TO_BKT(_hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \
|
| 476 |
+
HASH_DEL_IN_BKT((head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \
|
| 477 |
+
(head)->hh.tbl->num_items--; \
|
| 478 |
+
} \
|
| 479 |
+
HASH_FSCK(hh, head, "HASH_DELETE_HH"); \
|
| 480 |
+
} while (0)
|
| 481 |
+
|
| 482 |
+
/* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */
|
| 483 |
+
#define HASH_FIND_STR(head,findstr,out) \
|
| 484 |
+
do { \
|
| 485 |
+
unsigned _uthash_hfstr_keylen = (unsigned)uthash_strlen(findstr); \
|
| 486 |
+
HASH_FIND(hh, head, findstr, _uthash_hfstr_keylen, out); \
|
| 487 |
+
} while (0)
|
| 488 |
+
#define HASH_ADD_STR(head,strfield,add) \
|
| 489 |
+
do { \
|
| 490 |
+
unsigned _uthash_hastr_keylen = (unsigned)uthash_strlen((add)->strfield); \
|
| 491 |
+
HASH_ADD(hh, head, strfield[0], _uthash_hastr_keylen, add); \
|
| 492 |
+
} while (0)
|
| 493 |
+
#define HASH_REPLACE_STR(head,strfield,add,replaced) \
|
| 494 |
+
do { \
|
| 495 |
+
unsigned _uthash_hrstr_keylen = (unsigned)uthash_strlen((add)->strfield); \
|
| 496 |
+
HASH_REPLACE(hh, head, strfield[0], _uthash_hrstr_keylen, add, replaced); \
|
| 497 |
+
} while (0)
|
| 498 |
+
#define HASH_FIND_INT(head,findint,out) \
|
| 499 |
+
HASH_FIND(hh,head,findint,sizeof(int),out)
|
| 500 |
+
#define HASH_ADD_INT(head,intfield,add) \
|
| 501 |
+
HASH_ADD(hh,head,intfield,sizeof(int),add)
|
| 502 |
+
#define HASH_REPLACE_INT(head,intfield,add,replaced) \
|
| 503 |
+
HASH_REPLACE(hh,head,intfield,sizeof(int),add,replaced)
|
| 504 |
+
#define HASH_FIND_PTR(head,findptr,out) \
|
| 505 |
+
HASH_FIND(hh,head,findptr,sizeof(void *),out)
|
| 506 |
+
#define HASH_ADD_PTR(head,ptrfield,add) \
|
| 507 |
+
HASH_ADD(hh,head,ptrfield,sizeof(void *),add)
|
| 508 |
+
#define HASH_REPLACE_PTR(head,ptrfield,add,replaced) \
|
| 509 |
+
HASH_REPLACE(hh,head,ptrfield,sizeof(void *),add,replaced)
|
| 510 |
+
#define HASH_DEL(head,delptr) \
|
| 511 |
+
HASH_DELETE(hh,head,delptr)
|
| 512 |
+
|
| 513 |
+
/* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined.
|
| 514 |
+
* This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined.
|
| 515 |
+
*/
|
| 516 |
+
#ifdef HASH_DEBUG
|
| 517 |
+
#include <stdio.h> /* fprintf, stderr */
|
| 518 |
+
#define HASH_OOPS(...) do { fprintf(stderr, __VA_ARGS__); exit(-1); } while (0)
|
| 519 |
+
#define HASH_FSCK(hh,head,where) \
|
| 520 |
+
do { \
|
| 521 |
+
struct UT_hash_handle *_thh; \
|
| 522 |
+
if (head) { \
|
| 523 |
+
unsigned _bkt_i; \
|
| 524 |
+
unsigned _count = 0; \
|
| 525 |
+
char *_prev; \
|
| 526 |
+
for (_bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; ++_bkt_i) { \
|
| 527 |
+
unsigned _bkt_count = 0; \
|
| 528 |
+
_thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \
|
| 529 |
+
_prev = NULL; \
|
| 530 |
+
while (_thh) { \
|
| 531 |
+
if (_prev != (char*)(_thh->hh_prev)) { \
|
| 532 |
+
HASH_OOPS("%s: invalid hh_prev %p, actual %p\n", \
|
| 533 |
+
(where), (void*)_thh->hh_prev, (void*)_prev); \
|
| 534 |
+
} \
|
| 535 |
+
_bkt_count++; \
|
| 536 |
+
_prev = (char*)(_thh); \
|
| 537 |
+
_thh = _thh->hh_next; \
|
| 538 |
+
} \
|
| 539 |
+
_count += _bkt_count; \
|
| 540 |
+
if ((head)->hh.tbl->buckets[_bkt_i].count != _bkt_count) { \
|
| 541 |
+
HASH_OOPS("%s: invalid bucket count %u, actual %u\n", \
|
| 542 |
+
(where), (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \
|
| 543 |
+
} \
|
| 544 |
+
} \
|
| 545 |
+
if (_count != (head)->hh.tbl->num_items) { \
|
| 546 |
+
HASH_OOPS("%s: invalid hh item count %u, actual %u\n", \
|
| 547 |
+
(where), (head)->hh.tbl->num_items, _count); \
|
| 548 |
+
} \
|
| 549 |
+
_count = 0; \
|
| 550 |
+
_prev = NULL; \
|
| 551 |
+
_thh = &(head)->hh; \
|
| 552 |
+
while (_thh) { \
|
| 553 |
+
_count++; \
|
| 554 |
+
if (_prev != (char*)_thh->prev) { \
|
| 555 |
+
HASH_OOPS("%s: invalid prev %p, actual %p\n", \
|
| 556 |
+
(where), (void*)_thh->prev, (void*)_prev); \
|
| 557 |
+
} \
|
| 558 |
+
_prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh); \
|
| 559 |
+
_thh = (_thh->next ? HH_FROM_ELMT((head)->hh.tbl, _thh->next) : NULL); \
|
| 560 |
+
} \
|
| 561 |
+
if (_count != (head)->hh.tbl->num_items) { \
|
| 562 |
+
HASH_OOPS("%s: invalid app item count %u, actual %u\n", \
|
| 563 |
+
(where), (head)->hh.tbl->num_items, _count); \
|
| 564 |
+
} \
|
| 565 |
+
} \
|
| 566 |
+
} while (0)
|
| 567 |
+
#else
|
| 568 |
+
#define HASH_FSCK(hh,head,where)
|
| 569 |
+
#endif
|
| 570 |
+
|
| 571 |
+
/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to
|
| 572 |
+
* the descriptor to which this macro is defined for tuning the hash function.
|
| 573 |
+
* The app can #include <unistd.h> to get the prototype for write(2). */
|
| 574 |
+
#ifdef HASH_EMIT_KEYS
|
| 575 |
+
#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) \
|
| 576 |
+
do { \
|
| 577 |
+
unsigned _klen = fieldlen; \
|
| 578 |
+
write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \
|
| 579 |
+
write(HASH_EMIT_KEYS, keyptr, (unsigned long)fieldlen); \
|
| 580 |
+
} while (0)
|
| 581 |
+
#else
|
| 582 |
+
#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen)
|
| 583 |
+
#endif
|
| 584 |
+
|
| 585 |
+
/* The Bernstein hash function, used in Perl prior to v5.6. Note (x<<5+x)=x*33. */
|
| 586 |
+
#define HASH_BER(key,keylen,hashv) \
|
| 587 |
+
do { \
|
| 588 |
+
unsigned _hb_keylen = (unsigned)keylen; \
|
| 589 |
+
const unsigned char *_hb_key = (const unsigned char*)(key); \
|
| 590 |
+
(hashv) = 0; \
|
| 591 |
+
while (_hb_keylen-- != 0U) { \
|
| 592 |
+
(hashv) = (((hashv) << 5) + (hashv)) + *_hb_key++; \
|
| 593 |
+
} \
|
| 594 |
+
} while (0)
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at
|
| 598 |
+
* http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx
|
| 599 |
+
* (archive link: https://archive.is/Ivcan )
|
| 600 |
+
*/
|
| 601 |
+
#define HASH_SAX(key,keylen,hashv) \
|
| 602 |
+
do { \
|
| 603 |
+
unsigned _sx_i; \
|
| 604 |
+
const unsigned char *_hs_key = (const unsigned char*)(key); \
|
| 605 |
+
hashv = 0; \
|
| 606 |
+
for (_sx_i=0; _sx_i < keylen; _sx_i++) { \
|
| 607 |
+
hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \
|
| 608 |
+
} \
|
| 609 |
+
} while (0)
|
| 610 |
+
/* FNV-1a variation */
|
| 611 |
+
#define HASH_FNV(key,keylen,hashv) \
|
| 612 |
+
do { \
|
| 613 |
+
unsigned _fn_i; \
|
| 614 |
+
const unsigned char *_hf_key = (const unsigned char*)(key); \
|
| 615 |
+
(hashv) = 2166136261U; \
|
| 616 |
+
for (_fn_i=0; _fn_i < keylen; _fn_i++) { \
|
| 617 |
+
hashv = hashv ^ _hf_key[_fn_i]; \
|
| 618 |
+
hashv = hashv * 16777619U; \
|
| 619 |
+
} \
|
| 620 |
+
} while (0)
|
| 621 |
+
|
| 622 |
+
#define HASH_OAT(key,keylen,hashv) \
|
| 623 |
+
do { \
|
| 624 |
+
unsigned _ho_i; \
|
| 625 |
+
const unsigned char *_ho_key=(const unsigned char*)(key); \
|
| 626 |
+
hashv = 0; \
|
| 627 |
+
for(_ho_i=0; _ho_i < keylen; _ho_i++) { \
|
| 628 |
+
hashv += _ho_key[_ho_i]; \
|
| 629 |
+
hashv += (hashv << 10); \
|
| 630 |
+
hashv ^= (hashv >> 6); \
|
| 631 |
+
} \
|
| 632 |
+
hashv += (hashv << 3); \
|
| 633 |
+
hashv ^= (hashv >> 11); \
|
| 634 |
+
hashv += (hashv << 15); \
|
| 635 |
+
} while (0)
|
| 636 |
+
|
| 637 |
+
#define HASH_JEN_MIX(a,b,c) \
|
| 638 |
+
do { \
|
| 639 |
+
a -= b; a -= c; a ^= ( c >> 13 ); \
|
| 640 |
+
b -= c; b -= a; b ^= ( a << 8 ); \
|
| 641 |
+
c -= a; c -= b; c ^= ( b >> 13 ); \
|
| 642 |
+
a -= b; a -= c; a ^= ( c >> 12 ); \
|
| 643 |
+
b -= c; b -= a; b ^= ( a << 16 ); \
|
| 644 |
+
c -= a; c -= b; c ^= ( b >> 5 ); \
|
| 645 |
+
a -= b; a -= c; a ^= ( c >> 3 ); \
|
| 646 |
+
b -= c; b -= a; b ^= ( a << 10 ); \
|
| 647 |
+
c -= a; c -= b; c ^= ( b >> 15 ); \
|
| 648 |
+
} while (0)
|
| 649 |
+
|
| 650 |
+
#define HASH_JEN(key,keylen,hashv) \
|
| 651 |
+
do { \
|
| 652 |
+
unsigned _hj_i,_hj_j,_hj_k; \
|
| 653 |
+
unsigned const char *_hj_key=(unsigned const char*)(key); \
|
| 654 |
+
hashv = 0xfeedbeefu; \
|
| 655 |
+
_hj_i = _hj_j = 0x9e3779b9u; \
|
| 656 |
+
_hj_k = (unsigned)(keylen); \
|
| 657 |
+
while (_hj_k >= 12U) { \
|
| 658 |
+
_hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \
|
| 659 |
+
+ ( (unsigned)_hj_key[2] << 16 ) \
|
| 660 |
+
+ ( (unsigned)_hj_key[3] << 24 ) ); \
|
| 661 |
+
_hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \
|
| 662 |
+
+ ( (unsigned)_hj_key[6] << 16 ) \
|
| 663 |
+
+ ( (unsigned)_hj_key[7] << 24 ) ); \
|
| 664 |
+
hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 ) \
|
| 665 |
+
+ ( (unsigned)_hj_key[10] << 16 ) \
|
| 666 |
+
+ ( (unsigned)_hj_key[11] << 24 ) ); \
|
| 667 |
+
\
|
| 668 |
+
HASH_JEN_MIX(_hj_i, _hj_j, hashv); \
|
| 669 |
+
\
|
| 670 |
+
_hj_key += 12; \
|
| 671 |
+
_hj_k -= 12U; \
|
| 672 |
+
} \
|
| 673 |
+
hashv += (unsigned)(keylen); \
|
| 674 |
+
switch ( _hj_k ) { \
|
| 675 |
+
case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); /* FALLTHROUGH */ \
|
| 676 |
+
case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); /* FALLTHROUGH */ \
|
| 677 |
+
case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); /* FALLTHROUGH */ \
|
| 678 |
+
case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); /* FALLTHROUGH */ \
|
| 679 |
+
case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); /* FALLTHROUGH */ \
|
| 680 |
+
case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); /* FALLTHROUGH */ \
|
| 681 |
+
case 5: _hj_j += _hj_key[4]; /* FALLTHROUGH */ \
|
| 682 |
+
case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); /* FALLTHROUGH */ \
|
| 683 |
+
case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); /* FALLTHROUGH */ \
|
| 684 |
+
case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); /* FALLTHROUGH */ \
|
| 685 |
+
case 1: _hj_i += _hj_key[0]; /* FALLTHROUGH */ \
|
| 686 |
+
default: ; \
|
| 687 |
+
} \
|
| 688 |
+
HASH_JEN_MIX(_hj_i, _hj_j, hashv); \
|
| 689 |
+
} while (0)
|
| 690 |
+
|
| 691 |
+
/* The Paul Hsieh hash function */
|
| 692 |
+
#undef get16bits
|
| 693 |
+
#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \
|
| 694 |
+
|| defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__)
|
| 695 |
+
#define get16bits(d) (*((const uint16_t *) (d)))
|
| 696 |
+
#endif
|
| 697 |
+
|
| 698 |
+
#if !defined (get16bits)
|
| 699 |
+
#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \
|
| 700 |
+
+(uint32_t)(((const uint8_t *)(d))[0]) )
|
| 701 |
+
#endif
|
| 702 |
+
#define HASH_SFH(key,keylen,hashv) \
|
| 703 |
+
do { \
|
| 704 |
+
unsigned const char *_sfh_key=(unsigned const char*)(key); \
|
| 705 |
+
uint32_t _sfh_tmp, _sfh_len = (uint32_t)keylen; \
|
| 706 |
+
\
|
| 707 |
+
unsigned _sfh_rem = _sfh_len & 3U; \
|
| 708 |
+
_sfh_len >>= 2; \
|
| 709 |
+
hashv = 0xcafebabeu; \
|
| 710 |
+
\
|
| 711 |
+
/* Main loop */ \
|
| 712 |
+
for (;_sfh_len > 0U; _sfh_len--) { \
|
| 713 |
+
hashv += get16bits (_sfh_key); \
|
| 714 |
+
_sfh_tmp = ((uint32_t)(get16bits (_sfh_key+2)) << 11) ^ hashv; \
|
| 715 |
+
hashv = (hashv << 16) ^ _sfh_tmp; \
|
| 716 |
+
_sfh_key += 2U*sizeof (uint16_t); \
|
| 717 |
+
hashv += hashv >> 11; \
|
| 718 |
+
} \
|
| 719 |
+
\
|
| 720 |
+
/* Handle end cases */ \
|
| 721 |
+
switch (_sfh_rem) { \
|
| 722 |
+
case 3: hashv += get16bits (_sfh_key); \
|
| 723 |
+
hashv ^= hashv << 16; \
|
| 724 |
+
hashv ^= (uint32_t)(_sfh_key[sizeof (uint16_t)]) << 18; \
|
| 725 |
+
hashv += hashv >> 11; \
|
| 726 |
+
break; \
|
| 727 |
+
case 2: hashv += get16bits (_sfh_key); \
|
| 728 |
+
hashv ^= hashv << 11; \
|
| 729 |
+
hashv += hashv >> 17; \
|
| 730 |
+
break; \
|
| 731 |
+
case 1: hashv += *_sfh_key; \
|
| 732 |
+
hashv ^= hashv << 10; \
|
| 733 |
+
hashv += hashv >> 1; \
|
| 734 |
+
break; \
|
| 735 |
+
default: ; \
|
| 736 |
+
} \
|
| 737 |
+
\
|
| 738 |
+
/* Force "avalanching" of final 127 bits */ \
|
| 739 |
+
hashv ^= hashv << 3; \
|
| 740 |
+
hashv += hashv >> 5; \
|
| 741 |
+
hashv ^= hashv << 4; \
|
| 742 |
+
hashv += hashv >> 17; \
|
| 743 |
+
hashv ^= hashv << 25; \
|
| 744 |
+
hashv += hashv >> 6; \
|
| 745 |
+
} while (0)
|
| 746 |
+
|
| 747 |
+
/* iterate over items in a known bucket to find desired item */
|
| 748 |
+
#define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,hashval,out) \
|
| 749 |
+
do { \
|
| 750 |
+
if ((head).hh_head != NULL) { \
|
| 751 |
+
DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (head).hh_head)); \
|
| 752 |
+
} else { \
|
| 753 |
+
(out) = NULL; \
|
| 754 |
+
} \
|
| 755 |
+
while ((out) != NULL) { \
|
| 756 |
+
if ((out)->hh.hashv == (hashval) && (out)->hh.keylen == (keylen_in)) { \
|
| 757 |
+
if (HASH_KEYCMP((out)->hh.key, keyptr, keylen_in) == 0) { \
|
| 758 |
+
break; \
|
| 759 |
+
} \
|
| 760 |
+
} \
|
| 761 |
+
if ((out)->hh.hh_next != NULL) { \
|
| 762 |
+
DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (out)->hh.hh_next)); \
|
| 763 |
+
} else { \
|
| 764 |
+
(out) = NULL; \
|
| 765 |
+
} \
|
| 766 |
+
} \
|
| 767 |
+
} while (0)
|
| 768 |
+
|
| 769 |
+
/* add an item to a bucket */
|
| 770 |
+
#define HASH_ADD_TO_BKT(head,hh,addhh,oomed) \
|
| 771 |
+
do { \
|
| 772 |
+
UT_hash_bucket *_ha_head = &(head); \
|
| 773 |
+
_ha_head->count++; \
|
| 774 |
+
(addhh)->hh_next = _ha_head->hh_head; \
|
| 775 |
+
(addhh)->hh_prev = NULL; \
|
| 776 |
+
if (_ha_head->hh_head != NULL) { \
|
| 777 |
+
_ha_head->hh_head->hh_prev = (addhh); \
|
| 778 |
+
} \
|
| 779 |
+
_ha_head->hh_head = (addhh); \
|
| 780 |
+
if ((_ha_head->count >= ((_ha_head->expand_mult + 1U) * HASH_BKT_CAPACITY_THRESH)) \
|
| 781 |
+
&& !(addhh)->tbl->noexpand) { \
|
| 782 |
+
HASH_EXPAND_BUCKETS(addhh,(addhh)->tbl, oomed); \
|
| 783 |
+
IF_HASH_NONFATAL_OOM( \
|
| 784 |
+
if (oomed) { \
|
| 785 |
+
HASH_DEL_IN_BKT(head,addhh); \
|
| 786 |
+
} \
|
| 787 |
+
) \
|
| 788 |
+
} \
|
| 789 |
+
} while (0)
|
| 790 |
+
|
| 791 |
+
/* remove an item from a given bucket */
|
| 792 |
+
#define HASH_DEL_IN_BKT(head,delhh) \
|
| 793 |
+
do { \
|
| 794 |
+
UT_hash_bucket *_hd_head = &(head); \
|
| 795 |
+
_hd_head->count--; \
|
| 796 |
+
if (_hd_head->hh_head == (delhh)) { \
|
| 797 |
+
_hd_head->hh_head = (delhh)->hh_next; \
|
| 798 |
+
} \
|
| 799 |
+
if ((delhh)->hh_prev) { \
|
| 800 |
+
(delhh)->hh_prev->hh_next = (delhh)->hh_next; \
|
| 801 |
+
} \
|
| 802 |
+
if ((delhh)->hh_next) { \
|
| 803 |
+
(delhh)->hh_next->hh_prev = (delhh)->hh_prev; \
|
| 804 |
+
} \
|
| 805 |
+
} while (0)
|
| 806 |
+
|
| 807 |
+
/* Bucket expansion has the effect of doubling the number of buckets
|
| 808 |
+
* and redistributing the items into the new buckets. Ideally the
|
| 809 |
+
* items will distribute more or less evenly into the new buckets
|
| 810 |
+
* (the extent to which this is true is a measure of the quality of
|
| 811 |
+
* the hash function as it applies to the key domain).
|
| 812 |
+
*
|
| 813 |
+
* With the items distributed into more buckets, the chain length
|
| 814 |
+
* (item count) in each bucket is reduced. Thus by expanding buckets
|
| 815 |
+
* the hash keeps a bound on the chain length. This bounded chain
|
| 816 |
+
* length is the essence of how a hash provides constant time lookup.
|
| 817 |
+
*
|
| 818 |
+
* The calculation of tbl->ideal_chain_maxlen below deserves some
|
| 819 |
+
* explanation. First, keep in mind that we're calculating the ideal
|
| 820 |
+
* maximum chain length based on the *new* (doubled) bucket count.
|
| 821 |
+
* In fractions this is just n/b (n=number of items,b=new num buckets).
|
| 822 |
+
* Since the ideal chain length is an integer, we want to calculate
|
| 823 |
+
* ceil(n/b). We don't depend on floating point arithmetic in this
|
| 824 |
+
* hash, so to calculate ceil(n/b) with integers we could write
|
| 825 |
+
*
|
| 826 |
+
* ceil(n/b) = (n/b) + ((n%b)?1:0)
|
| 827 |
+
*
|
| 828 |
+
* and in fact a previous version of this hash did just that.
|
| 829 |
+
* But now we have improved things a bit by recognizing that b is
|
| 830 |
+
* always a power of two. We keep its base 2 log handy (call it lb),
|
| 831 |
+
* so now we can write this with a bit shift and logical AND:
|
| 832 |
+
*
|
| 833 |
+
* ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0)
|
| 834 |
+
*
|
| 835 |
+
*/
|
| 836 |
+
#define HASH_EXPAND_BUCKETS(hh,tbl,oomed) \
|
| 837 |
+
do { \
|
| 838 |
+
unsigned _he_bkt; \
|
| 839 |
+
unsigned _he_bkt_i; \
|
| 840 |
+
struct UT_hash_handle *_he_thh, *_he_hh_nxt; \
|
| 841 |
+
UT_hash_bucket *_he_new_buckets, *_he_newbkt; \
|
| 842 |
+
_he_new_buckets = (UT_hash_bucket*)uthash_malloc( \
|
| 843 |
+
sizeof(struct UT_hash_bucket) * (tbl)->num_buckets * 2U); \
|
| 844 |
+
if (!_he_new_buckets) { \
|
| 845 |
+
HASH_RECORD_OOM(oomed); \
|
| 846 |
+
} else { \
|
| 847 |
+
uthash_bzero(_he_new_buckets, \
|
| 848 |
+
sizeof(struct UT_hash_bucket) * (tbl)->num_buckets * 2U); \
|
| 849 |
+
(tbl)->ideal_chain_maxlen = \
|
| 850 |
+
((tbl)->num_items >> ((tbl)->log2_num_buckets+1U)) + \
|
| 851 |
+
((((tbl)->num_items & (((tbl)->num_buckets*2U)-1U)) != 0U) ? 1U : 0U); \
|
| 852 |
+
(tbl)->nonideal_items = 0; \
|
| 853 |
+
for (_he_bkt_i = 0; _he_bkt_i < (tbl)->num_buckets; _he_bkt_i++) { \
|
| 854 |
+
_he_thh = (tbl)->buckets[ _he_bkt_i ].hh_head; \
|
| 855 |
+
while (_he_thh != NULL) { \
|
| 856 |
+
_he_hh_nxt = _he_thh->hh_next; \
|
| 857 |
+
HASH_TO_BKT(_he_thh->hashv, (tbl)->num_buckets * 2U, _he_bkt); \
|
| 858 |
+
_he_newbkt = &(_he_new_buckets[_he_bkt]); \
|
| 859 |
+
if (++(_he_newbkt->count) > (tbl)->ideal_chain_maxlen) { \
|
| 860 |
+
(tbl)->nonideal_items++; \
|
| 861 |
+
if (_he_newbkt->count > _he_newbkt->expand_mult * (tbl)->ideal_chain_maxlen) { \
|
| 862 |
+
_he_newbkt->expand_mult++; \
|
| 863 |
+
} \
|
| 864 |
+
} \
|
| 865 |
+
_he_thh->hh_prev = NULL; \
|
| 866 |
+
_he_thh->hh_next = _he_newbkt->hh_head; \
|
| 867 |
+
if (_he_newbkt->hh_head != NULL) { \
|
| 868 |
+
_he_newbkt->hh_head->hh_prev = _he_thh; \
|
| 869 |
+
} \
|
| 870 |
+
_he_newbkt->hh_head = _he_thh; \
|
| 871 |
+
_he_thh = _he_hh_nxt; \
|
| 872 |
+
} \
|
| 873 |
+
} \
|
| 874 |
+
uthash_free((tbl)->buckets, (tbl)->num_buckets * sizeof(struct UT_hash_bucket)); \
|
| 875 |
+
(tbl)->num_buckets *= 2U; \
|
| 876 |
+
(tbl)->log2_num_buckets++; \
|
| 877 |
+
(tbl)->buckets = _he_new_buckets; \
|
| 878 |
+
(tbl)->ineff_expands = ((tbl)->nonideal_items > ((tbl)->num_items >> 1)) ? \
|
| 879 |
+
((tbl)->ineff_expands+1U) : 0U; \
|
| 880 |
+
if ((tbl)->ineff_expands > 1U) { \
|
| 881 |
+
(tbl)->noexpand = 1; \
|
| 882 |
+
uthash_noexpand_fyi(tbl); \
|
| 883 |
+
} \
|
| 884 |
+
uthash_expand_fyi(tbl); \
|
| 885 |
+
} \
|
| 886 |
+
} while (0)
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
/* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */
|
| 890 |
+
/* Note that HASH_SORT assumes the hash handle name to be hh.
|
| 891 |
+
* HASH_SRT was added to allow the hash handle name to be passed in. */
|
| 892 |
+
#define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn)
|
| 893 |
+
#define HASH_SRT(hh,head,cmpfcn) \
|
| 894 |
+
do { \
|
| 895 |
+
unsigned _hs_i; \
|
| 896 |
+
unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize; \
|
| 897 |
+
struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail; \
|
| 898 |
+
if (head != NULL) { \
|
| 899 |
+
_hs_insize = 1; \
|
| 900 |
+
_hs_looping = 1; \
|
| 901 |
+
_hs_list = &((head)->hh); \
|
| 902 |
+
while (_hs_looping != 0U) { \
|
| 903 |
+
_hs_p = _hs_list; \
|
| 904 |
+
_hs_list = NULL; \
|
| 905 |
+
_hs_tail = NULL; \
|
| 906 |
+
_hs_nmerges = 0; \
|
| 907 |
+
while (_hs_p != NULL) { \
|
| 908 |
+
_hs_nmerges++; \
|
| 909 |
+
_hs_q = _hs_p; \
|
| 910 |
+
_hs_psize = 0; \
|
| 911 |
+
for (_hs_i = 0; _hs_i < _hs_insize; ++_hs_i) { \
|
| 912 |
+
_hs_psize++; \
|
| 913 |
+
_hs_q = ((_hs_q->next != NULL) ? \
|
| 914 |
+
HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \
|
| 915 |
+
if (_hs_q == NULL) { \
|
| 916 |
+
break; \
|
| 917 |
+
} \
|
| 918 |
+
} \
|
| 919 |
+
_hs_qsize = _hs_insize; \
|
| 920 |
+
while ((_hs_psize != 0U) || ((_hs_qsize != 0U) && (_hs_q != NULL))) { \
|
| 921 |
+
if (_hs_psize == 0U) { \
|
| 922 |
+
_hs_e = _hs_q; \
|
| 923 |
+
_hs_q = ((_hs_q->next != NULL) ? \
|
| 924 |
+
HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \
|
| 925 |
+
_hs_qsize--; \
|
| 926 |
+
} else if ((_hs_qsize == 0U) || (_hs_q == NULL)) { \
|
| 927 |
+
_hs_e = _hs_p; \
|
| 928 |
+
if (_hs_p != NULL) { \
|
| 929 |
+
_hs_p = ((_hs_p->next != NULL) ? \
|
| 930 |
+
HH_FROM_ELMT((head)->hh.tbl, _hs_p->next) : NULL); \
|
| 931 |
+
} \
|
| 932 |
+
_hs_psize--; \
|
| 933 |
+
} else if ((cmpfcn( \
|
| 934 |
+
DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl, _hs_p)), \
|
| 935 |
+
DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl, _hs_q)) \
|
| 936 |
+
)) <= 0) { \
|
| 937 |
+
_hs_e = _hs_p; \
|
| 938 |
+
if (_hs_p != NULL) { \
|
| 939 |
+
_hs_p = ((_hs_p->next != NULL) ? \
|
| 940 |
+
HH_FROM_ELMT((head)->hh.tbl, _hs_p->next) : NULL); \
|
| 941 |
+
} \
|
| 942 |
+
_hs_psize--; \
|
| 943 |
+
} else { \
|
| 944 |
+
_hs_e = _hs_q; \
|
| 945 |
+
_hs_q = ((_hs_q->next != NULL) ? \
|
| 946 |
+
HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \
|
| 947 |
+
_hs_qsize--; \
|
| 948 |
+
} \
|
| 949 |
+
if ( _hs_tail != NULL ) { \
|
| 950 |
+
_hs_tail->next = ((_hs_e != NULL) ? \
|
| 951 |
+
ELMT_FROM_HH((head)->hh.tbl, _hs_e) : NULL); \
|
| 952 |
+
} else { \
|
| 953 |
+
_hs_list = _hs_e; \
|
| 954 |
+
} \
|
| 955 |
+
if (_hs_e != NULL) { \
|
| 956 |
+
_hs_e->prev = ((_hs_tail != NULL) ? \
|
| 957 |
+
ELMT_FROM_HH((head)->hh.tbl, _hs_tail) : NULL); \
|
| 958 |
+
} \
|
| 959 |
+
_hs_tail = _hs_e; \
|
| 960 |
+
} \
|
| 961 |
+
_hs_p = _hs_q; \
|
| 962 |
+
} \
|
| 963 |
+
if (_hs_tail != NULL) { \
|
| 964 |
+
_hs_tail->next = NULL; \
|
| 965 |
+
} \
|
| 966 |
+
if (_hs_nmerges <= 1U) { \
|
| 967 |
+
_hs_looping = 0; \
|
| 968 |
+
(head)->hh.tbl->tail = _hs_tail; \
|
| 969 |
+
DECLTYPE_ASSIGN(head, ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \
|
| 970 |
+
} \
|
| 971 |
+
_hs_insize *= 2U; \
|
| 972 |
+
} \
|
| 973 |
+
HASH_FSCK(hh, head, "HASH_SRT"); \
|
| 974 |
+
} \
|
| 975 |
+
} while (0)
|
| 976 |
+
|
| 977 |
+
/* This function selects items from one hash into another hash.
|
| 978 |
+
* The end result is that the selected items have dual presence
|
| 979 |
+
* in both hashes. There is no copy of the items made; rather
|
| 980 |
+
* they are added into the new hash through a secondary hash
|
| 981 |
+
* hash handle that must be present in the structure. */
|
| 982 |
+
#define HASH_SELECT(hh_dst, dst, hh_src, src, cond) \
|
| 983 |
+
do { \
|
| 984 |
+
unsigned _src_bkt, _dst_bkt; \
|
| 985 |
+
void *_last_elt = NULL, *_elt; \
|
| 986 |
+
UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL; \
|
| 987 |
+
ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst)); \
|
| 988 |
+
if ((src) != NULL) { \
|
| 989 |
+
for (_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) { \
|
| 990 |
+
for (_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; \
|
| 991 |
+
_src_hh != NULL; \
|
| 992 |
+
_src_hh = _src_hh->hh_next) { \
|
| 993 |
+
_elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \
|
| 994 |
+
if (cond(_elt)) { \
|
| 995 |
+
IF_HASH_NONFATAL_OOM( int _hs_oomed = 0; ) \
|
| 996 |
+
_dst_hh = (UT_hash_handle*)(void*)(((char*)_elt) + _dst_hho); \
|
| 997 |
+
_dst_hh->key = _src_hh->key; \
|
| 998 |
+
_dst_hh->keylen = _src_hh->keylen; \
|
| 999 |
+
_dst_hh->hashv = _src_hh->hashv; \
|
| 1000 |
+
_dst_hh->prev = _last_elt; \
|
| 1001 |
+
_dst_hh->next = NULL; \
|
| 1002 |
+
if (_last_elt_hh != NULL) { \
|
| 1003 |
+
_last_elt_hh->next = _elt; \
|
| 1004 |
+
} \
|
| 1005 |
+
if ((dst) == NULL) { \
|
| 1006 |
+
DECLTYPE_ASSIGN(dst, _elt); \
|
| 1007 |
+
HASH_MAKE_TABLE(hh_dst, dst, _hs_oomed); \
|
| 1008 |
+
IF_HASH_NONFATAL_OOM( \
|
| 1009 |
+
if (_hs_oomed) { \
|
| 1010 |
+
uthash_nonfatal_oom(_elt); \
|
| 1011 |
+
(dst) = NULL; \
|
| 1012 |
+
continue; \
|
| 1013 |
+
} \
|
| 1014 |
+
) \
|
| 1015 |
+
} else { \
|
| 1016 |
+
_dst_hh->tbl = (dst)->hh_dst.tbl; \
|
| 1017 |
+
} \
|
| 1018 |
+
HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt); \
|
| 1019 |
+
HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt], hh_dst, _dst_hh, _hs_oomed); \
|
| 1020 |
+
(dst)->hh_dst.tbl->num_items++; \
|
| 1021 |
+
IF_HASH_NONFATAL_OOM( \
|
| 1022 |
+
if (_hs_oomed) { \
|
| 1023 |
+
HASH_ROLLBACK_BKT(hh_dst, dst, _dst_hh); \
|
| 1024 |
+
HASH_DELETE_HH(hh_dst, dst, _dst_hh); \
|
| 1025 |
+
_dst_hh->tbl = NULL; \
|
| 1026 |
+
uthash_nonfatal_oom(_elt); \
|
| 1027 |
+
continue; \
|
| 1028 |
+
} \
|
| 1029 |
+
) \
|
| 1030 |
+
HASH_BLOOM_ADD(_dst_hh->tbl, _dst_hh->hashv); \
|
| 1031 |
+
_last_elt = _elt; \
|
| 1032 |
+
_last_elt_hh = _dst_hh; \
|
| 1033 |
+
} \
|
| 1034 |
+
} \
|
| 1035 |
+
} \
|
| 1036 |
+
} \
|
| 1037 |
+
HASH_FSCK(hh_dst, dst, "HASH_SELECT"); \
|
| 1038 |
+
} while (0)
|
| 1039 |
+
|
| 1040 |
+
#define HASH_CLEAR(hh,head) \
|
| 1041 |
+
do { \
|
| 1042 |
+
if ((head) != NULL) { \
|
| 1043 |
+
HASH_BLOOM_FREE((head)->hh.tbl); \
|
| 1044 |
+
uthash_free((head)->hh.tbl->buckets, \
|
| 1045 |
+
(head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket)); \
|
| 1046 |
+
uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \
|
| 1047 |
+
(head) = NULL; \
|
| 1048 |
+
} \
|
| 1049 |
+
} while (0)
|
| 1050 |
+
|
| 1051 |
+
#define HASH_OVERHEAD(hh,head) \
|
| 1052 |
+
(((head) != NULL) ? ( \
|
| 1053 |
+
(size_t)(((head)->hh.tbl->num_items * sizeof(UT_hash_handle)) + \
|
| 1054 |
+
((head)->hh.tbl->num_buckets * sizeof(UT_hash_bucket)) + \
|
| 1055 |
+
sizeof(UT_hash_table) + \
|
| 1056 |
+
(HASH_BLOOM_BYTELEN))) : 0U)
|
| 1057 |
+
|
| 1058 |
+
#ifdef NO_DECLTYPE
|
| 1059 |
+
#define HASH_ITER(hh,head,el,tmp) \
|
| 1060 |
+
for(((el)=(head)), ((*(char**)(&(tmp)))=(char*)((head!=NULL)?(head)->hh.next:NULL)); \
|
| 1061 |
+
(el) != NULL; ((el)=(tmp)), ((*(char**)(&(tmp)))=(char*)((tmp!=NULL)?(tmp)->hh.next:NULL)))
|
| 1062 |
+
#else
|
| 1063 |
+
#define HASH_ITER(hh,head,el,tmp) \
|
| 1064 |
+
for(((el)=(head)), ((tmp)=DECLTYPE(el)((head!=NULL)?(head)->hh.next:NULL)); \
|
| 1065 |
+
(el) != NULL; ((el)=(tmp)), ((tmp)=DECLTYPE(el)((tmp!=NULL)?(tmp)->hh.next:NULL)))
|
| 1066 |
+
#endif
|
| 1067 |
+
|
| 1068 |
+
/* obtain a count of items in the hash */
|
| 1069 |
+
#define HASH_COUNT(head) HASH_CNT(hh,head)
|
| 1070 |
+
#define HASH_CNT(hh,head) ((head != NULL)?((head)->hh.tbl->num_items):0U)
|
| 1071 |
+
|
| 1072 |
+
typedef struct UT_hash_bucket {
|
| 1073 |
+
struct UT_hash_handle *hh_head;
|
| 1074 |
+
unsigned count;
|
| 1075 |
+
|
| 1076 |
+
/* expand_mult is normally set to 0. In this situation, the max chain length
|
| 1077 |
+
* threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If
|
| 1078 |
+
* the bucket's chain exceeds this length, bucket expansion is triggered).
|
| 1079 |
+
* However, setting expand_mult to a non-zero value delays bucket expansion
|
| 1080 |
+
* (that would be triggered by additions to this particular bucket)
|
| 1081 |
+
* until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH.
|
| 1082 |
+
* (The multiplier is simply expand_mult+1). The whole idea of this
|
| 1083 |
+
* multiplier is to reduce bucket expansions, since they are expensive, in
|
| 1084 |
+
* situations where we know that a particular bucket tends to be overused.
|
| 1085 |
+
* It is better to let its chain length grow to a longer yet-still-bounded
|
| 1086 |
+
* value, than to do an O(n) bucket expansion too often.
|
| 1087 |
+
*/
|
| 1088 |
+
unsigned expand_mult;
|
| 1089 |
+
|
| 1090 |
+
} UT_hash_bucket;
|
| 1091 |
+
|
| 1092 |
+
/* random signature used only to find hash tables in external analysis */
|
| 1093 |
+
#define HASH_SIGNATURE 0xa0111fe1u
|
| 1094 |
+
#define HASH_BLOOM_SIGNATURE 0xb12220f2u
|
| 1095 |
+
|
| 1096 |
+
typedef struct UT_hash_table {
|
| 1097 |
+
UT_hash_bucket *buckets;
|
| 1098 |
+
unsigned num_buckets, log2_num_buckets;
|
| 1099 |
+
unsigned num_items;
|
| 1100 |
+
struct UT_hash_handle *tail; /* tail hh in app order, for fast append */
|
| 1101 |
+
ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */
|
| 1102 |
+
|
| 1103 |
+
/* in an ideal situation (all buckets used equally), no bucket would have
|
| 1104 |
+
* more than ceil(#items/#buckets) items. that's the ideal chain length. */
|
| 1105 |
+
unsigned ideal_chain_maxlen;
|
| 1106 |
+
|
| 1107 |
+
/* nonideal_items is the number of items in the hash whose chain position
|
| 1108 |
+
* exceeds the ideal chain maxlen. these items pay the penalty for an uneven
|
| 1109 |
+
* hash distribution; reaching them in a chain traversal takes >ideal steps */
|
| 1110 |
+
unsigned nonideal_items;
|
| 1111 |
+
|
| 1112 |
+
/* ineffective expands occur when a bucket doubling was performed, but
|
| 1113 |
+
* afterward, more than half the items in the hash had nonideal chain
|
| 1114 |
+
* positions. If this happens on two consecutive expansions we inhibit any
|
| 1115 |
+
* further expansion, as it's not helping; this happens when the hash
|
| 1116 |
+
* function isn't a good fit for the key domain. When expansion is inhibited
|
| 1117 |
+
* the hash will still work, albeit no longer in constant time. */
|
| 1118 |
+
unsigned ineff_expands, noexpand;
|
| 1119 |
+
|
| 1120 |
+
uint32_t signature; /* used only to find hash tables in external analysis */
|
| 1121 |
+
#ifdef HASH_BLOOM
|
| 1122 |
+
uint32_t bloom_sig; /* used only to test bloom exists in external analysis */
|
| 1123 |
+
uint8_t *bloom_bv;
|
| 1124 |
+
uint8_t bloom_nbits;
|
| 1125 |
+
#endif
|
| 1126 |
+
|
| 1127 |
+
} UT_hash_table;
|
| 1128 |
+
|
| 1129 |
+
typedef struct UT_hash_handle {
|
| 1130 |
+
struct UT_hash_table *tbl;
|
| 1131 |
+
void *prev; /* prev element in app order */
|
| 1132 |
+
void *next; /* next element in app order */
|
| 1133 |
+
struct UT_hash_handle *hh_prev; /* previous hh in bucket order */
|
| 1134 |
+
struct UT_hash_handle *hh_next; /* next hh in bucket order */
|
| 1135 |
+
const void *key; /* ptr to enclosing struct's key */
|
| 1136 |
+
unsigned keylen; /* enclosing struct's key len */
|
| 1137 |
+
unsigned hashv; /* result of hash-fcn(key) */
|
| 1138 |
+
} UT_hash_handle;
|
| 1139 |
+
|
| 1140 |
+
#endif /* UTHASH_H */
|
models/matris/matris/graph/radiusgraph.py
ADDED
|
@@ -0,0 +1,504 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This code is referenced from: https://github.com/CederGroupHub/chgnet/blob/main/chgnet/graph/converter.py
|
| 3 |
+
The original implementation can be found at the link above.
|
| 4 |
+
"""
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from torch import Tensor
|
| 12 |
+
import sys
|
| 13 |
+
from abc import ABC, abstractmethod
|
| 14 |
+
|
| 15 |
+
datatype = torch.float32
|
| 16 |
+
|
| 17 |
+
class RadiusGraph:
|
| 18 |
+
def __init__(
|
| 19 |
+
self,
|
| 20 |
+
graph_id: str | None,
|
| 21 |
+
mp_id: str | None,
|
| 22 |
+
composition: str | None,
|
| 23 |
+
atomic_number: Tensor,
|
| 24 |
+
atom_frac_coord: Tensor,
|
| 25 |
+
lattice: Tensor,
|
| 26 |
+
neighbor_image: Tensor,
|
| 27 |
+
atom_graph: Tensor,
|
| 28 |
+
atom_graph_cutoff: float,
|
| 29 |
+
line_graph: Tensor,
|
| 30 |
+
line_graph_cutoff: float,
|
| 31 |
+
directed2undirected: Tensor,
|
| 32 |
+
undirected2directed: Tensor,
|
| 33 |
+
):
|
| 34 |
+
"""Initialize a RadiusGraph object representing a material graph.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
graph_id (str | None): Unique identifier for this graph instance.
|
| 38 |
+
mp_id (str | None): Materials Project ID associated with this structure.
|
| 39 |
+
composition (str | None): Chemical composition of the compound.
|
| 40 |
+
|
| 41 |
+
atomic_number (Tensor): Atomic numbers of all atoms in the structure.
|
| 42 |
+
Shape: [n_atom]
|
| 43 |
+
|
| 44 |
+
atom_frac_coord (Tensor): Fractional atomic coordinates within the unit cell.
|
| 45 |
+
Shape: [n_atom, 3]
|
| 46 |
+
|
| 47 |
+
lattice (Tensor): Lattice vectors defining the periodic cell.
|
| 48 |
+
Shape: [3, 3]
|
| 49 |
+
|
| 50 |
+
neighbor_image (Tensor): Periodic image offsets for each directed edge,
|
| 51 |
+
indicating how many unit cells away the neighbor lies along each axis.
|
| 52 |
+
Shape: [n_directed_edges, 3]
|
| 53 |
+
|
| 54 |
+
atom_graph (Tensor): Directed atomic graph, where each row stores
|
| 55 |
+
(center_atom_index, neighbor_atom_index).
|
| 56 |
+
Shape: [n_directed_edges, 2]
|
| 57 |
+
|
| 58 |
+
atom_graph_cutoff (float): Cutoff radius (in Å) used to build the atom graph.
|
| 59 |
+
|
| 60 |
+
line_graph (Tensor): Line graph describing angular connections between bonds.
|
| 61 |
+
Each row stores
|
| 62 |
+
(central_atom, undirected_bond_1, directed_bond_1,
|
| 63 |
+
undirected_bond_2, directed_bond_2).
|
| 64 |
+
Shape: [n_angle, 5]
|
| 65 |
+
|
| 66 |
+
line_graph_cutoff (float): Cutoff radius (in Å) used to build the line graph.
|
| 67 |
+
|
| 68 |
+
directed2undirected (Tensor): Mapping from each directed edge index
|
| 69 |
+
to its corresponding undirected edge index.
|
| 70 |
+
Shape: [n_directed_edges]
|
| 71 |
+
|
| 72 |
+
undirected2directed (Tensor): Mapping from each undirected edge index
|
| 73 |
+
to one of its directed edge indices.
|
| 74 |
+
Shape: [n_undirected_edges]
|
| 75 |
+
"""
|
| 76 |
+
super().__init__()
|
| 77 |
+
self.graph_id = graph_id
|
| 78 |
+
self.mp_id = mp_id
|
| 79 |
+
self.composition = composition
|
| 80 |
+
|
| 81 |
+
self.atomic_number = atomic_number
|
| 82 |
+
self.atom_frac_coord = atom_frac_coord
|
| 83 |
+
self.lattice = lattice
|
| 84 |
+
self.neighbor_image = neighbor_image
|
| 85 |
+
self.line_graph = line_graph
|
| 86 |
+
self.line_graph_cutoff = line_graph_cutoff
|
| 87 |
+
self.atom_graph = atom_graph
|
| 88 |
+
self.atom_graph_cutoff = atom_graph_cutoff
|
| 89 |
+
self.directed2undirected = directed2undirected
|
| 90 |
+
self.undirected2directed = undirected2directed
|
| 91 |
+
|
| 92 |
+
assert len(directed2undirected) == 2 * len(undirected2directed), (
|
| 93 |
+
f"Number of directed indices ({len(directed2undirected)}) != "
|
| 94 |
+
f"2 * number of undirected indices ({2 * len(undirected2directed)})!"
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
def to(self, device: str = "cpu") -> RadiusGraph:
|
| 98 |
+
"""Move the graph to a device."""
|
| 99 |
+
return RadiusGraph(
|
| 100 |
+
graph_id=self.graph_id,
|
| 101 |
+
mp_id=self.mp_id,
|
| 102 |
+
composition=self.composition,
|
| 103 |
+
atomic_number=self.atomic_number.to(device),
|
| 104 |
+
atom_frac_coord=self.atom_frac_coord.to(device),
|
| 105 |
+
lattice=self.lattice.to(device),
|
| 106 |
+
neighbor_image=self.neighbor_image.to(device),
|
| 107 |
+
atom_graph=self.atom_graph.to(device),
|
| 108 |
+
atom_graph_cutoff=self.atom_graph_cutoff,
|
| 109 |
+
line_graph=self.line_graph.to(device),
|
| 110 |
+
line_graph_cutoff=self.line_graph_cutoff,
|
| 111 |
+
directed2undirected=self.directed2undirected.to(device),
|
| 112 |
+
undirected2directed=self.undirected2directed.to(device),
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
def to_dict(self) -> dict[str, Any]:
|
| 116 |
+
return {
|
| 117 |
+
"graph_id": self.graph_id,
|
| 118 |
+
"mp_id": self.mp_id,
|
| 119 |
+
"composition": self.composition,
|
| 120 |
+
"atomic_number": self.atomic_number,
|
| 121 |
+
"atom_frac_coord": self.atom_frac_coord,
|
| 122 |
+
"lattice": self.lattice,
|
| 123 |
+
"neighbor_image": self.neighbor_image,
|
| 124 |
+
"atom_graph": self.atom_graph,
|
| 125 |
+
"atom_graph_cutoff": self.atom_graph_cutoff,
|
| 126 |
+
"line_graph": self.line_graph,
|
| 127 |
+
"line_graph_cutoff": self.line_graph_cutoff,
|
| 128 |
+
"directed2undirected": self.directed2undirected,
|
| 129 |
+
"undirected2directed": self.undirected2directed,
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
def save(self, fname: str | None = None, save_dir: str = ".") -> str:
|
| 133 |
+
"""Save the Radiusgraph to a file.
|
| 134 |
+
|
| 135 |
+
Args:
|
| 136 |
+
fname (str, optional): File name. Defaults to None.
|
| 137 |
+
save_dir (str, optional): Directory to save the file. Defaults to ".".
|
| 138 |
+
"""
|
| 139 |
+
if fname is not None:
|
| 140 |
+
save_name = os.path.join(save_dir, fname)
|
| 141 |
+
elif self.graph_id is not None:
|
| 142 |
+
save_name = os.path.join(save_dir, f"{self.graph_id}.pt")
|
| 143 |
+
else:
|
| 144 |
+
save_name = os.path.join(save_dir, f"{self.composition}.pt")
|
| 145 |
+
torch.save(self.to_dict(), f=save_name)
|
| 146 |
+
return save_name
|
| 147 |
+
|
| 148 |
+
@classmethod
|
| 149 |
+
def from_file(cls, file_name: str) -> RadiusGraph:
|
| 150 |
+
"""Load a Radiusgraph from a file.
|
| 151 |
+
|
| 152 |
+
Args:
|
| 153 |
+
file_name (str): The path to the file.
|
| 154 |
+
"""
|
| 155 |
+
return torch.load(file_name)
|
| 156 |
+
|
| 157 |
+
@classmethod
|
| 158 |
+
def from_dict(cls, dic: dict[str, Any]) -> RadiusGraph:
|
| 159 |
+
"""Load a RadiusGraph from a dictionary."""
|
| 160 |
+
return RadiusGraph(**dic)
|
| 161 |
+
|
| 162 |
+
def __repr__(self) -> str:
|
| 163 |
+
"""String representation of the graph."""
|
| 164 |
+
composition = self.composition
|
| 165 |
+
atom_graph_cutoff = self.atom_graph_cutoff
|
| 166 |
+
line_graph_cutoff = self.line_graph_cutoff
|
| 167 |
+
atom_graph_len = self.atom_graph
|
| 168 |
+
n_atoms = len(self.atomic_number)
|
| 169 |
+
atom_graph_len = len(self.atom_graph)
|
| 170 |
+
line_graph_len = len(self.line_graph)
|
| 171 |
+
return (
|
| 172 |
+
f"RadiusGraph({composition=}, {atom_graph_cutoff=}, {line_graph_cutoff=}, "
|
| 173 |
+
f"{n_atoms=}, {atom_graph_len=}, {line_graph_len=})"
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class Node:
|
| 178 |
+
"""A node in graph."""
|
| 179 |
+
|
| 180 |
+
def __init__(self, index: int, info: dict | None = None) -> None:
|
| 181 |
+
"""Initialize a Node.
|
| 182 |
+
|
| 183 |
+
Args:
|
| 184 |
+
index (int): the index of this node
|
| 185 |
+
info (dict, optional): any additional information about this node.
|
| 186 |
+
"""
|
| 187 |
+
self.index = index
|
| 188 |
+
self.info = info
|
| 189 |
+
self.neighbors: dict[int, list[DirectedEdge | UndirectedEdge]] = {}
|
| 190 |
+
|
| 191 |
+
def add_neighbor(self, index, edge):
|
| 192 |
+
"""Draw an directed edge between self and the node specified by index.
|
| 193 |
+
|
| 194 |
+
Args:
|
| 195 |
+
index (int): the index of neighboring node
|
| 196 |
+
edge (DirectedEdge): an DirectedEdge object pointing from self to the node.
|
| 197 |
+
"""
|
| 198 |
+
if index not in self.neighbors:
|
| 199 |
+
self.neighbors[index] = [edge]
|
| 200 |
+
else:
|
| 201 |
+
self.neighbors[index].append(edge)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class Edge(ABC):
|
| 205 |
+
"""Abstract base class for edges in a graph."""
|
| 206 |
+
|
| 207 |
+
def __init__(
|
| 208 |
+
self, nodes: list, index: int | None = None, info: dict | None = None
|
| 209 |
+
) -> None:
|
| 210 |
+
"""Initialize an Edge."""
|
| 211 |
+
self.nodes = nodes
|
| 212 |
+
self.index = index
|
| 213 |
+
self.info = info
|
| 214 |
+
|
| 215 |
+
def __repr__(self):
|
| 216 |
+
"""String representation of this edge."""
|
| 217 |
+
nodes, index, info = self.nodes, self.index, self.info
|
| 218 |
+
return f"{type(self).__name__}({nodes=}, {index=}, {info=})"
|
| 219 |
+
|
| 220 |
+
def __hash__(self) -> int:
|
| 221 |
+
"""Hash this edge."""
|
| 222 |
+
img = (self.info or {}).get("image")
|
| 223 |
+
img_str = "" if img is None else img.tobytes()
|
| 224 |
+
return hash((self.nodes[0], self.nodes[1], img_str))
|
| 225 |
+
|
| 226 |
+
@abstractmethod
|
| 227 |
+
def __eq__(self, other: object) -> bool:
|
| 228 |
+
"""Check if two edges are equal."""
|
| 229 |
+
raise NotImplementedError
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
class UndirectedEdge(Edge):
|
| 233 |
+
"""An undirected/bi-directed edge in a graph."""
|
| 234 |
+
|
| 235 |
+
__hash__ = Edge.__hash__
|
| 236 |
+
|
| 237 |
+
def __eq__(self, other):
|
| 238 |
+
"""Check if two undirected edges are equal."""
|
| 239 |
+
return set(self.nodes) == set(other.nodes) and self.info == other.info
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
class DirectedEdge(Edge):
|
| 243 |
+
"""A directed edge in a graph."""
|
| 244 |
+
|
| 245 |
+
__hash__ = Edge.__hash__
|
| 246 |
+
|
| 247 |
+
def make_undirected(self, index: int, info: dict | None = None) -> UndirectedEdge:
|
| 248 |
+
"""Make a directed edge undirected."""
|
| 249 |
+
info = info or {}
|
| 250 |
+
info["distance"] = self.info["distance"]
|
| 251 |
+
return UndirectedEdge(self.nodes, index, info)
|
| 252 |
+
|
| 253 |
+
def __eq__(self, other: object) -> bool:
|
| 254 |
+
"""Check if the two directed edges are equal.
|
| 255 |
+
|
| 256 |
+
Args:
|
| 257 |
+
other (DirectedEdge): another DirectedEdge to compare to
|
| 258 |
+
|
| 259 |
+
Returns:
|
| 260 |
+
bool: True if other is the same directed edge, or if other is the directed
|
| 261 |
+
edge with reverse direction of self, else False.
|
| 262 |
+
"""
|
| 263 |
+
self_img = (self.info or {}).get("image")
|
| 264 |
+
other_img = (other.info or {}).get("image")
|
| 265 |
+
none_img = self_img is other_img is None
|
| 266 |
+
if self.nodes == other.nodes and (none_img or all(self_img == other_img)):
|
| 267 |
+
# the image key here is provided by Pymatgen, which refers to the periodic
|
| 268 |
+
# cell the neighbor node comes from
|
| 269 |
+
|
| 270 |
+
# In this case the two directed edges are exactly the same, but this is not
|
| 271 |
+
# supposed tp happen unless there's a bug in Pymatgen. (we will never add
|
| 272 |
+
# the same edge twice in creating a crystal graph.)
|
| 273 |
+
print(
|
| 274 |
+
"!!!!!! the two directed edges are equal but this operation is "
|
| 275 |
+
"not supposed to happen",
|
| 276 |
+
file=sys.stderr,
|
| 277 |
+
)
|
| 278 |
+
return True
|
| 279 |
+
|
| 280 |
+
# In this case the first edge is from node i to j and the second edge is
|
| 281 |
+
# from node j to i
|
| 282 |
+
return self.nodes == other.nodes[::-1] and (
|
| 283 |
+
none_img or all(self_img == -1 * other_img)
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
class Graph:
|
| 288 |
+
"""A graph for storing the neighbor information of atoms."""
|
| 289 |
+
|
| 290 |
+
def __init__(self, nodes: list[Node]) -> None:
|
| 291 |
+
"""Initialize a Graph from a list of nodes."""
|
| 292 |
+
self.nodes = nodes
|
| 293 |
+
self.directed_edges: dict[frozenset[int], list[DirectedEdge]] = {}
|
| 294 |
+
self.directed_edges_list: list[DirectedEdge] = []
|
| 295 |
+
self.undirected_edges: dict[frozenset[int], list[UndirectedEdge]] = {}
|
| 296 |
+
self.undirected_edges_list: list[UndirectedEdge] = []
|
| 297 |
+
|
| 298 |
+
def add_edge(self, center_index, neighbor_index, image, distance) -> None:
|
| 299 |
+
"""Add an directed edge to the graph.
|
| 300 |
+
|
| 301 |
+
Args:
|
| 302 |
+
center_index (int): center node index
|
| 303 |
+
neighbor_index (int): neighbor node index
|
| 304 |
+
image (np.array): the periodic cell image the neighbor is from
|
| 305 |
+
distance (float): distance between center and neighbor.
|
| 306 |
+
"""
|
| 307 |
+
# Create directed_edge (DE) index using the length of added DEs
|
| 308 |
+
directed_edge_index = len(self.directed_edges_list)
|
| 309 |
+
|
| 310 |
+
# Create the DE with info
|
| 311 |
+
this_directed_edge = DirectedEdge(
|
| 312 |
+
[center_index, neighbor_index],
|
| 313 |
+
index=directed_edge_index,
|
| 314 |
+
info={"image": image, "distance": distance},
|
| 315 |
+
)
|
| 316 |
+
# Record the two ends of the DE and see if they have been added
|
| 317 |
+
# Here the sequence of the ends doesn't matter since we want to
|
| 318 |
+
# search for associated undirected_edge (UDE)
|
| 319 |
+
tmp = frozenset([center_index, neighbor_index])
|
| 320 |
+
# This combination of two ends hasn't been added
|
| 321 |
+
if tmp not in self.undirected_edges:
|
| 322 |
+
# Create UDE index
|
| 323 |
+
this_directed_edge.info["undirected_edge_index"] = len(
|
| 324 |
+
self.undirected_edges_list
|
| 325 |
+
)
|
| 326 |
+
# Create UDE
|
| 327 |
+
this_undirected_edge = this_directed_edge.make_undirected(
|
| 328 |
+
index=len(self.undirected_edges_list),
|
| 329 |
+
info={"directed_edge_index": [directed_edge_index]},
|
| 330 |
+
)
|
| 331 |
+
self.undirected_edges[tmp] = [this_undirected_edge]
|
| 332 |
+
|
| 333 |
+
self.undirected_edges_list.append(this_undirected_edge)
|
| 334 |
+
self.nodes[center_index].add_neighbor(neighbor_index, this_directed_edge)
|
| 335 |
+
self.directed_edges_list.append(this_directed_edge)
|
| 336 |
+
else:
|
| 337 |
+
# This pair of nodes has been added before, we need to see if this time,
|
| 338 |
+
# 1. it's the other directed edge of the same undirected edge or,
|
| 339 |
+
# 2. it's another totally different undirected edge that has
|
| 340 |
+
# different image and distance (this is possible consider periodicity)
|
| 341 |
+
for undirected_edge in self.undirected_edges[tmp]:
|
| 342 |
+
if (
|
| 343 |
+
abs(undirected_edge.info["distance"] - distance) < 1e-6
|
| 344 |
+
and len(undirected_edge.info["directed_edge_index"]) == 1
|
| 345 |
+
):
|
| 346 |
+
# There is an undirected edge with similar length and only one of
|
| 347 |
+
# the directed edges associated has been added
|
| 348 |
+
added_DE = self.directed_edges_list[
|
| 349 |
+
undirected_edge.info["directed_edge_index"][0]
|
| 350 |
+
]
|
| 351 |
+
|
| 352 |
+
# See if the DE that's associated to this UDE
|
| 353 |
+
# is the reverse of our DE
|
| 354 |
+
if added_DE == this_directed_edge:
|
| 355 |
+
# Add UDE index to this DE
|
| 356 |
+
this_directed_edge.info[
|
| 357 |
+
"undirected_edge_index"
|
| 358 |
+
] = added_DE.info["undirected_edge_index"]
|
| 359 |
+
|
| 360 |
+
# At the center node, draw edge with this DE
|
| 361 |
+
self.nodes[center_index].add_neighbor(
|
| 362 |
+
neighbor_index, this_directed_edge
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
# Add this DE to DE list
|
| 366 |
+
self.directed_edges_list.append(this_directed_edge)
|
| 367 |
+
|
| 368 |
+
# Add this DE to the UDE
|
| 369 |
+
undirected_edge.info["directed_edge_index"].append(
|
| 370 |
+
directed_edge_index
|
| 371 |
+
)
|
| 372 |
+
return
|
| 373 |
+
|
| 374 |
+
# no undirected_edge matches to this directed edge
|
| 375 |
+
this_directed_edge.info["undirected_edge_index"] = len(
|
| 376 |
+
self.undirected_edges_list
|
| 377 |
+
)
|
| 378 |
+
this_undirected_edge = this_directed_edge.make_undirected(
|
| 379 |
+
index=len(self.undirected_edges_list),
|
| 380 |
+
info={"directed_edge_index": [directed_edge_index]},
|
| 381 |
+
)
|
| 382 |
+
self.undirected_edges[tmp].append(this_undirected_edge)
|
| 383 |
+
|
| 384 |
+
self.undirected_edges_list.append(this_undirected_edge)
|
| 385 |
+
self.nodes[center_index].add_neighbor(neighbor_index, this_directed_edge)
|
| 386 |
+
self.directed_edges_list.append(this_directed_edge)
|
| 387 |
+
|
| 388 |
+
def adjacency_list(self):
|
| 389 |
+
"""Get the adjacency list
|
| 390 |
+
Return:
|
| 391 |
+
graph: the adjacency list
|
| 392 |
+
[[0, 1],
|
| 393 |
+
[0, 2],
|
| 394 |
+
...
|
| 395 |
+
[5, 2]
|
| 396 |
+
... ]]
|
| 397 |
+
the fist column specifies center/source node,
|
| 398 |
+
the second column specifies neighbor/destination node
|
| 399 |
+
directed2undirected:
|
| 400 |
+
[0, 1, ...]
|
| 401 |
+
a list of length = num_directed_edge that specifies
|
| 402 |
+
the undirected edge index corresponding to the directed edges
|
| 403 |
+
represented in each row in the graph adjacency list.
|
| 404 |
+
"""
|
| 405 |
+
graph = [edge.nodes for edge in self.directed_edges_list]
|
| 406 |
+
directed2undirected = [
|
| 407 |
+
edge.info["undirected_edge_index"] for edge in self.directed_edges_list
|
| 408 |
+
]
|
| 409 |
+
|
| 410 |
+
return graph, directed2undirected
|
| 411 |
+
|
| 412 |
+
def line_graph_adjacency_list(self, cutoff):
|
| 413 |
+
"""Get the line graph adjacency list.
|
| 414 |
+
|
| 415 |
+
Args:
|
| 416 |
+
cutoff (float): a float to indicate the maximum edge length to be included
|
| 417 |
+
in constructing the line graph, this is used to decrease computation
|
| 418 |
+
complexity
|
| 419 |
+
|
| 420 |
+
Return:
|
| 421 |
+
line_graph:
|
| 422 |
+
[[0, 1, 1, 2, 2],
|
| 423 |
+
[0, 1, 1, 4, 23],
|
| 424 |
+
[1, 4, 23, 5, 66],
|
| 425 |
+
... ... ]
|
| 426 |
+
the fist column specifies node(atom) index at this angle,
|
| 427 |
+
the second column specifies 1st undirected edge(left bond) index,
|
| 428 |
+
the third column specifies 1st directed edge(left bond) index,
|
| 429 |
+
the fourth column specifies 2nd undirected edge(right bond) index,
|
| 430 |
+
the fifth column specifies 2nd directed edge(right bond) index,.
|
| 431 |
+
undirected2directed:
|
| 432 |
+
[32, 45, ...]
|
| 433 |
+
a list of length = num_undirected_edge that
|
| 434 |
+
maps the undirected edge index to one of its directed edges indices
|
| 435 |
+
"""
|
| 436 |
+
assert len(self.directed_edges_list) == 2 * len(self.undirected_edges_list), (
|
| 437 |
+
f"Error: number of directed edges={len(self.directed_edges_list)} != 2 * "
|
| 438 |
+
f"number of undirected edges={len(self.directed_edges_list)}!"
|
| 439 |
+
f"This indicates directed edges are not complete"
|
| 440 |
+
)
|
| 441 |
+
line_graph = []
|
| 442 |
+
#undirected2directed = []
|
| 443 |
+
|
| 444 |
+
# Loop through all the undirected edges(UDE)
|
| 445 |
+
for u_edge in self.undirected_edges_list:
|
| 446 |
+
# Create the mapping from the UDE index to one of its DE index
|
| 447 |
+
#undirected2directed.append(u_edge.info["directed_edge_index"][0])
|
| 448 |
+
|
| 449 |
+
# Ignore the UDE if its length is larger than cutoff (3A for default)
|
| 450 |
+
if u_edge.info["distance"] > cutoff:
|
| 451 |
+
continue
|
| 452 |
+
|
| 453 |
+
# Assert if the UDE is valid
|
| 454 |
+
# if encountered exception,
|
| 455 |
+
# it means after Atom_Graph creation, the UDE has only 1 DE associated
|
| 456 |
+
# This exception is not encountered from the develop team's experience
|
| 457 |
+
assert len(u_edge.info["directed_edge_index"]) == 2, (
|
| 458 |
+
"Did not find 2 Directed_edges !!!"
|
| 459 |
+
f"undirected edge {u_edge} has:"
|
| 460 |
+
f"edge.info['directed_edge_index'] = "
|
| 461 |
+
f"{u_edge.info['directed_edge_index']}"
|
| 462 |
+
f"len directed_edges_list = {len(self.directed_edges_list)}"
|
| 463 |
+
f"len undirected_edges_list = {len(self.undirected_edges_list)}"
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
# This UDE is valid to be considered as a node in Bond_Graph
|
| 467 |
+
|
| 468 |
+
# Get the two ends (centers) and the two DE associated with this UDE
|
| 469 |
+
# DE1 should have center=center1 and DE2 should have center=center2
|
| 470 |
+
# We will need to find directed edges with center = center1
|
| 471 |
+
# and create angles with DE1, then do the same for center2 and DE2
|
| 472 |
+
for center, DE in zip(u_edge.nodes, u_edge.info["directed_edge_index"]):
|
| 473 |
+
for directed_edges in self.nodes[center].neighbors.values():
|
| 474 |
+
for directed_edge in directed_edges:
|
| 475 |
+
if directed_edge.index == DE:
|
| 476 |
+
continue
|
| 477 |
+
if directed_edge.info["distance"] < cutoff:
|
| 478 |
+
line_graph.append(
|
| 479 |
+
[
|
| 480 |
+
center,
|
| 481 |
+
u_edge.index,
|
| 482 |
+
DE,
|
| 483 |
+
directed_edge.info["undirected_edge_index"],
|
| 484 |
+
directed_edge.index,
|
| 485 |
+
]
|
| 486 |
+
)
|
| 487 |
+
return line_graph#, undirected2directed
|
| 488 |
+
|
| 489 |
+
def undirected2directed(self):
|
| 490 |
+
"""The index map from undirected_edge index to one of its directed_edge
|
| 491 |
+
index.
|
| 492 |
+
"""
|
| 493 |
+
return [
|
| 494 |
+
undirected_edge.info["directed_edge_index"][0]
|
| 495 |
+
for undirected_edge in self.undirected_edges_list
|
| 496 |
+
]
|
| 497 |
+
|
| 498 |
+
def __repr__(self) -> str:
|
| 499 |
+
"""Return string representation of the Graph."""
|
| 500 |
+
num_nodes = len(self.nodes)
|
| 501 |
+
num_directed_edges = len(self.directed_edges_list)
|
| 502 |
+
num_undirected_edges = len(self.undirected_edges_list)
|
| 503 |
+
return f"Graph({num_nodes=}, {num_directed_edges=}, {num_undirected_edges=})"
|
| 504 |
+
|
models/matris/matris/graph/setup.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from setuptools import Extension, setup
|
| 3 |
+
|
| 4 |
+
ext_modules = [Extension("matris.graph.cygraph", ["matris/graph/cygraph.pyx"])]
|
| 5 |
+
|
| 6 |
+
setup(ext_modules=ext_modules, setup_requires=["Cython"])
|
| 7 |
+
|
| 8 |
+
# python setup.py build_ext --inplace
|
models/matris/matris/model/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .model import MatRIS
|
models/matris/matris/model/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (187 Bytes). View file
|
|
|
models/matris/matris/model/__pycache__/basis_function.cpython-310.pyc
ADDED
|
Binary file (11 kB). View file
|
|
|
models/matris/matris/model/__pycache__/feature_embed.cpython-310.pyc
ADDED
|
Binary file (8.7 kB). View file
|
|
|
models/matris/matris/model/__pycache__/functions.cpython-310.pyc
ADDED
|
Binary file (14.5 kB). View file
|
|
|
models/matris/matris/model/__pycache__/interaction_block.cpython-310.pyc
ADDED
|
Binary file (10.9 kB). View file
|
|
|
models/matris/matris/model/__pycache__/model.cpython-310.pyc
ADDED
|
Binary file (9.57 kB). View file
|
|
|
models/matris/matris/model/__pycache__/processgraph.cpython-310.pyc
ADDED
|
Binary file (6.62 kB). View file
|
|
|
models/matris/matris/model/__pycache__/readout.cpython-310.pyc
ADDED
|
Binary file (8.82 kB). View file
|
|
|
models/matris/matris/model/__pycache__/reference_energy.cpython-310.pyc
ADDED
|
Binary file (6.84 kB). View file
|
|
|
models/matris/matris/model/basis_function.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
Polynomial cutoff function for distance
|
| 11 |
+
Details are given in: https://doi.org/10.48550/arXiv.2106.08903
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
def __init__(self, cutoff: float = 6, envelope_exponent: float = 8) -> None:
|
| 15 |
+
"""Initialize the polynomial cutoff function.
|
| 16 |
+
|
| 17 |
+
Args:
|
| 18 |
+
cutoff (float): cutoff radius in graph construction
|
| 19 |
+
Default = 6
|
| 20 |
+
envelope_exponent (float): envelope exponent
|
| 21 |
+
Default = 8
|
| 22 |
+
"""
|
| 23 |
+
super().__init__()
|
| 24 |
+
assert envelope_exponent > 0
|
| 25 |
+
self.cutoff = cutoff
|
| 26 |
+
self.p = float(envelope_exponent)
|
| 27 |
+
self.a = -(self.p + 1) * (self.p + 2) / 2
|
| 28 |
+
self.b = self.p * (self.p + 2)
|
| 29 |
+
self.c = -self.p * (self.p + 1) / 2
|
| 30 |
+
|
| 31 |
+
def forward(self, dist: Tensor) -> Tensor:
|
| 32 |
+
"""
|
| 33 |
+
Args:
|
| 34 |
+
dist (Tensor): radius distance tensor
|
| 35 |
+
|
| 36 |
+
Returns:
|
| 37 |
+
polynomial cutoff functions: decaying from 1 to 0
|
| 38 |
+
"""
|
| 39 |
+
if self.p != 0:
|
| 40 |
+
dist_scaled = dist / self.cutoff
|
| 41 |
+
|
| 42 |
+
env_val = (
|
| 43 |
+
1
|
| 44 |
+
+ self.a * dist_scaled ** self.p
|
| 45 |
+
+ self.b * dist_scaled ** (self.p + 1)
|
| 46 |
+
+ self.c * dist_scaled ** (self.p + 2)
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
return torch.where(dist_scaled < 1, env_val, torch.zeros_like(dist_scaled))
|
| 50 |
+
return dist.new_ones(dist.shape)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@torch.jit.script
|
| 54 |
+
def SphericalHarmonics(lmax: int, x: torch.Tensor) -> torch.Tensor:
|
| 55 |
+
|
| 56 |
+
sh_0_0 = torch.ones_like(x) * 0.5 * math.sqrt(1.0 / math.pi)
|
| 57 |
+
if lmax == 0:
|
| 58 |
+
return torch.stack(
|
| 59 |
+
[
|
| 60 |
+
sh_0_0,
|
| 61 |
+
],
|
| 62 |
+
dim=-1,
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
sh_1_1 = math.sqrt(3.0 / (4.0 * math.pi)) * x
|
| 66 |
+
if lmax == 1:
|
| 67 |
+
return torch.stack([sh_0_0, sh_1_1], dim=-1)
|
| 68 |
+
|
| 69 |
+
sh_2_2 = math.sqrt(5.0 / (16.0 * math.pi)) * (3.0 * x**2 - 1.0)
|
| 70 |
+
if lmax == 2:
|
| 71 |
+
return torch.stack([sh_0_0, sh_1_1, sh_2_2], dim=-1)
|
| 72 |
+
|
| 73 |
+
sh_3_3 = math.sqrt(7.0 / (16.0 * math.pi)) * x * (5.0 * x**2 - 3.0)
|
| 74 |
+
if lmax == 3:
|
| 75 |
+
return torch.stack([sh_0_0, sh_1_1, sh_2_2, sh_3_3], dim=-1)
|
| 76 |
+
|
| 77 |
+
raise ValueError("lmax <= 3")
|
| 78 |
+
|
| 79 |
+
class FourierExpansion(nn.Module):
|
| 80 |
+
"""
|
| 81 |
+
Fourier expansion for three-body feature.
|
| 82 |
+
Details are given in: https://doi.org/10.1038/s42256-023-00716-3
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
def __init__(self, max_f: int = 5,
|
| 86 |
+
scale: float = np.pi,
|
| 87 |
+
learnable: bool = False):
|
| 88 |
+
"""
|
| 89 |
+
Args:
|
| 90 |
+
max_f (int): the maximum frequency of the expansion.
|
| 91 |
+
Default = 5
|
| 92 |
+
learnable (bool): whether to set the frequencies as learnable parameters.
|
| 93 |
+
Default = False
|
| 94 |
+
"""
|
| 95 |
+
super().__init__()
|
| 96 |
+
self.max_f = max_f
|
| 97 |
+
self.scale = np.sqrt(scale)
|
| 98 |
+
if learnable:
|
| 99 |
+
self.frequencies = torch.nn.Parameter(
|
| 100 |
+
data=torch.arange(1, max_f + 1, dtype=torch.float),
|
| 101 |
+
requires_grad=True,
|
| 102 |
+
)
|
| 103 |
+
else:
|
| 104 |
+
self.register_buffer("frequencies", torch.arange(1, max_f + 1, dtype=torch.float))
|
| 105 |
+
|
| 106 |
+
def forward(self, feature: Tensor) -> Tensor:
|
| 107 |
+
"""Apply Fourier expansion to feature."""
|
| 108 |
+
result = feature.new_zeros(feature.shape[0], 1 + 2 * self.max_f)
|
| 109 |
+
result[:, 0] = 1 / torch.sqrt(torch.tensor([2]))
|
| 110 |
+
tmp = torch.outer(feature, self.frequencies)
|
| 111 |
+
result[:, 1 : self.max_f + 1] = torch.sin(tmp)
|
| 112 |
+
result[:, self.max_f + 1 :] = torch.cos(tmp)
|
| 113 |
+
return result / self.scale
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class BesselExpansion(torch.nn.Module):
|
| 117 |
+
"""
|
| 118 |
+
Bessel expansion for pairwise feature
|
| 119 |
+
Details are given in: https://arxiv.org/abs/2003.03123
|
| 120 |
+
"""
|
| 121 |
+
def __init__(
|
| 122 |
+
self,
|
| 123 |
+
num_radial: int = 9,
|
| 124 |
+
cutoff: float = 6,
|
| 125 |
+
envelope_exponent: int = 8,
|
| 126 |
+
learnable: bool = False,
|
| 127 |
+
):
|
| 128 |
+
"""
|
| 129 |
+
Args:
|
| 130 |
+
num_radial (int): number of radial basis.
|
| 131 |
+
Default = 9
|
| 132 |
+
cutoff (float): cutoff distance.
|
| 133 |
+
Default = 6
|
| 134 |
+
envelope_exponent (int): envelope exponent of Envelope function.
|
| 135 |
+
Default = 8
|
| 136 |
+
learnable (bool): whether to set the frequencies as learnable parameters.
|
| 137 |
+
Default = False
|
| 138 |
+
"""
|
| 139 |
+
super().__init__()
|
| 140 |
+
self.num_radial = num_radial
|
| 141 |
+
self.inv_cutoff = 1 / cutoff
|
| 142 |
+
self.norm_const = (2 * self.inv_cutoff) ** 0.5
|
| 143 |
+
|
| 144 |
+
if learnable:
|
| 145 |
+
self.frequencies = torch.nn.Parameter(
|
| 146 |
+
data=torch.Tensor(
|
| 147 |
+
np.pi * torch.arange(1, self.num_radial + 1, dtype=torch.float)
|
| 148 |
+
), requires_grad=True,
|
| 149 |
+
)
|
| 150 |
+
else:
|
| 151 |
+
self.register_buffer(
|
| 152 |
+
"frequencies",
|
| 153 |
+
np.pi * torch.arange(1, self.num_radial + 1, dtype=torch.float),
|
| 154 |
+
)
|
| 155 |
+
if envelope_exponent is not None:
|
| 156 |
+
self.envelope_func = PolynomialEnvelope(
|
| 157 |
+
cutoff=cutoff, envelope_exponent=envelope_exponent
|
| 158 |
+
)
|
| 159 |
+
else:
|
| 160 |
+
self.envelope_func = None
|
| 161 |
+
|
| 162 |
+
def forward(
|
| 163 |
+
self, dist: Tensor, return_smooth_factor: bool = False
|
| 164 |
+
) -> Tensor | tuple[Tensor, Tensor]:
|
| 165 |
+
"""Apply Bessel expansion to feature.
|
| 166 |
+
|
| 167 |
+
Args:
|
| 168 |
+
dist (Tensor): tensor of distances. [nEdges]
|
| 169 |
+
return_smooth_factor (bool): whether to return the smooth factor
|
| 170 |
+
Default = False
|
| 171 |
+
|
| 172 |
+
Returns:
|
| 173 |
+
out (Tensor): tensor of Bessel basis [nEdges, num_radial]
|
| 174 |
+
smooth_factor (Tensor): tensor of smooth factors [nEdges, 1]
|
| 175 |
+
|
| 176 |
+
TODO: 'torch.script.jit' boosts performance.
|
| 177 |
+
"""
|
| 178 |
+
dist = dist[:, None] # [nEdges] -> [nEdges, 1]
|
| 179 |
+
d_scaled = dist * self.inv_cutoff
|
| 180 |
+
out = self.norm_const * torch.sin(self.frequencies * d_scaled) / dist
|
| 181 |
+
if self.envelope_func is not None:
|
| 182 |
+
smooth_factor = self.envelope_func(dist)
|
| 183 |
+
out = smooth_factor * out
|
| 184 |
+
if return_smooth_factor:
|
| 185 |
+
return out, smooth_factor
|
| 186 |
+
return out
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class GaussianExpansion(nn.Module):
|
| 190 |
+
"""
|
| 191 |
+
Gaussian expansion for pairwise feature.
|
| 192 |
+
Code adapted from the repo: https://github.com/facebookresearch/fairchem/blob/main/src/fairchem/core/models/uma/nn/radial.py#L42
|
| 193 |
+
"""
|
| 194 |
+
def __init__(
|
| 195 |
+
self,
|
| 196 |
+
start: float = 0.0,
|
| 197 |
+
stop: float = 6.0,
|
| 198 |
+
num_gaussians: int = 7,
|
| 199 |
+
basis_width_scalar: float = 2.0,
|
| 200 |
+
):
|
| 201 |
+
super().__init__()
|
| 202 |
+
self.num_output = num_gaussians
|
| 203 |
+
offset = torch.linspace(start, stop, num_gaussians)
|
| 204 |
+
self.coeff = -0.5 / (basis_width_scalar * (offset[1] - offset[0])).item() ** 2
|
| 205 |
+
self.register_buffer("offset", offset)
|
| 206 |
+
|
| 207 |
+
def forward(self, dist) -> Tensor:
|
| 208 |
+
"""Apply Bessel expansion to feature.
|
| 209 |
+
|
| 210 |
+
Args:
|
| 211 |
+
dist (Tensor): tensor of distances. [nEdges]
|
| 212 |
+
|
| 213 |
+
Returns:
|
| 214 |
+
out (Tensor): tensor of Bessel basis [nEdges, num_gaussians]
|
| 215 |
+
|
| 216 |
+
TODO: 'torch.script.jit' boosts performance.
|
| 217 |
+
"""
|
| 218 |
+
dist = dist.view(-1, 1) - self.offset.view(1, -1)
|
| 219 |
+
return torch.exp(self.coeff * torch.pow(dist, 2))
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
class SphericalExpansion(nn.Module):
|
| 223 |
+
"""
|
| 224 |
+
Spherical expansion for three-body feature.
|
| 225 |
+
Code adapted from the repo: https://github.com/microsoft/mattersim
|
| 226 |
+
"""
|
| 227 |
+
def __init__(self, max_n = 4, max_l = 4, cutoff = 6):
|
| 228 |
+
super().__init__()
|
| 229 |
+
|
| 230 |
+
assert max_l <= 4, "lmax must be less than 5"
|
| 231 |
+
assert max_n <= 4, "max_n must be less than 5"
|
| 232 |
+
|
| 233 |
+
self.max_n = max_n
|
| 234 |
+
self.max_l = max_l
|
| 235 |
+
self.cutoff = cutoff
|
| 236 |
+
|
| 237 |
+
# retrieve formulas
|
| 238 |
+
self.register_buffer(
|
| 239 |
+
"factor", torch.sqrt(torch.tensor(2.0 / (self.cutoff**3)))
|
| 240 |
+
)
|
| 241 |
+
self.coef = torch.zeros(4, 9, 4)
|
| 242 |
+
self.coef[0, 0, :] = torch.tensor(
|
| 243 |
+
[ 3.14159274101257, 6.28318548202515, 9.42477798461914, 12.5663709640503 ]
|
| 244 |
+
)
|
| 245 |
+
self.coef[1, :4, :] = torch.tensor(
|
| 246 |
+
[
|
| 247 |
+
[ -1.02446483277785, -1.00834335996107, -1.00419641763893, -1.00252381898662 ],
|
| 248 |
+
[ 4.49340963363647, 7.7252516746521, 10.9041213989258, 14.0661935806274 ],
|
| 249 |
+
[ 0.22799275301076, 0.130525632358311, 0.092093290316619, 0.0712718627992818 ],
|
| 250 |
+
[ 4.49340963363647, 7.7252516746521, 10.9041213989258, 14.0661935806274 ],
|
| 251 |
+
]
|
| 252 |
+
)
|
| 253 |
+
self.coef[2, :6, :] = torch.tensor(
|
| 254 |
+
[
|
| 255 |
+
[ -1.04807944170731, -1.01861796359391, -1.01002272174988, -1.00628955560036 ],
|
| 256 |
+
[ 5.76345920562744, 9.09501171112061, 12.322940826416, 15.5146026611328 ],
|
| 257 |
+
[ 0.545547077361439, 0.335992298618515, 0.245888396928293, 0.194582402961821 ],
|
| 258 |
+
[ 5.76345920562744, 9.09501171112061, 12.322940826416, 15.5146026611328 ],
|
| 259 |
+
[ 0.0946561878721665, 0.0369424811413594, 0.0199537107571916, 0.0125418876146463 ],
|
| 260 |
+
[ 5.76345920562744, 9.09501171112061, 12.322940826416, 15.5146026611328 ],
|
| 261 |
+
]
|
| 262 |
+
)
|
| 263 |
+
self.coef[3, :8, :] = torch.tensor(
|
| 264 |
+
[
|
| 265 |
+
[ 1.06942831392075, 1.0292173312802, 1.01650804843248, 1.01069656069999 ],
|
| 266 |
+
[ 6.9879322052002, 10.4171180725098, 13.6980228424072, 16.9236221313477 ],
|
| 267 |
+
[ 0.918235852195231, 0.592803493701152, 0.445250264272671, 0.358326327374518 ],
|
| 268 |
+
[ 6.9879322052002, 10.4171180725098, 13.6980228424072, 16.9236221313477 ],
|
| 269 |
+
[ 0.328507713452024, 0.142266673367543, 0.0812617757677838, 0.0529328657590962 ],
|
| 270 |
+
[ 6.9879322052002, 10.4171180725098, 13.6980228424072, 16.9236221313477 ],
|
| 271 |
+
[ 0.0470107184508114, 0.0136570088173405, 0.0059323726279831, 0.00312775039221944 ],
|
| 272 |
+
[ 6.9879322052002, 10.4171180725098, 13.6980228424072, 16.9236221313477 ],
|
| 273 |
+
]
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
def forward(self, dist, three_body):
|
| 277 |
+
dist = dist / self.cutoff
|
| 278 |
+
rbfs = []
|
| 279 |
+
|
| 280 |
+
for j in range(self.max_l):
|
| 281 |
+
rbfs.append(torch.sin(self.coef[0, 0, j] * dist) / dist)
|
| 282 |
+
|
| 283 |
+
if self.max_n > 1:
|
| 284 |
+
for j in range(self.max_l):
|
| 285 |
+
rbfs.append(
|
| 286 |
+
(
|
| 287 |
+
self.coef[1, 0, j]
|
| 288 |
+
* dist
|
| 289 |
+
* torch.cos(self.coef[1, 1, j] * dist)
|
| 290 |
+
+ self.coef[1, 2, j]
|
| 291 |
+
* torch.sin(self.coef[1, 3, j] * dist)
|
| 292 |
+
)
|
| 293 |
+
/ dist**2
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
if self.max_n > 2:
|
| 297 |
+
for j in range(self.max_l):
|
| 298 |
+
rbfs.append(
|
| 299 |
+
(
|
| 300 |
+
self.coef[2, 0, j]
|
| 301 |
+
* (dist**2)
|
| 302 |
+
* torch.sin(self.coef[2, 1, j] * dist)
|
| 303 |
+
- self.coef[2, 2, j]
|
| 304 |
+
* dist
|
| 305 |
+
* torch.cos(self.coef[2, 3, j] * dist)
|
| 306 |
+
+ self.coef[2, 4, j]
|
| 307 |
+
* torch.sin(self.coef[2, 5, j] * dist)
|
| 308 |
+
)
|
| 309 |
+
/ (dist**3)
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
if self.max_n > 3:
|
| 313 |
+
for j in range(self.max_l):
|
| 314 |
+
rbfs.append(
|
| 315 |
+
(
|
| 316 |
+
self.coef[3, 0, j]
|
| 317 |
+
* (dist**3)
|
| 318 |
+
* torch.cos(self.coef[3, 1, j] * dist)
|
| 319 |
+
- self.coef[3, 2, j]
|
| 320 |
+
* (dist**2)
|
| 321 |
+
* torch.sin(self.coef[3, 3, j] * dist)
|
| 322 |
+
- self.coef[3, 4, j]
|
| 323 |
+
* dist
|
| 324 |
+
* torch.cos(self.coef[3, 5, j] * dist)
|
| 325 |
+
+ self.coef[3, 6, j]
|
| 326 |
+
* torch.sin(self.coef[3, 7, j] * dist)
|
| 327 |
+
)
|
| 328 |
+
/ dist**4
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
rbfs = torch.stack(rbfs, dim=-1)
|
| 332 |
+
rbfs = rbfs * self.factor
|
| 333 |
+
|
| 334 |
+
cbfs = SphericalHarmonics(self.max_l - 1, torch.cos(three_body))
|
| 335 |
+
|
| 336 |
+
cbfs = cbfs.repeat_interleave(self.max_n, dim=1)
|
| 337 |
+
|
| 338 |
+
return rbfs * cbfs
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
class SinusoidalTimeExpansion(nn.Module):
|
| 342 |
+
""" Encode time """
|
| 343 |
+
|
| 344 |
+
def __init__(self, dim: int = 128):
|
| 345 |
+
"""
|
| 346 |
+
Args:
|
| 347 |
+
dim (int): the embedding size of Time.
|
| 348 |
+
"""
|
| 349 |
+
super().__init__()
|
| 350 |
+
|
| 351 |
+
self.dim = dim
|
| 352 |
+
half_dim = self.dim // 2
|
| 353 |
+
# Inverse frequencies for sinusoidal embedding
|
| 354 |
+
self.register_buffer(
|
| 355 |
+
"inv_freq",
|
| 356 |
+
torch.exp(torch.arange(half_dim, dtype=torch.float32) * (-math.log(10000) / (half_dim - 1)))
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
def forward(self, feature):
|
| 360 |
+
shape = feature.shape
|
| 361 |
+
feature = feature.view(-1).to(torch.float32)
|
| 362 |
+
sinusoid_in = torch.ger(feature, self.inv_freq)
|
| 363 |
+
time_emb = torch.cat([sinusoid_in.sin(), sinusoid_in.cos()], dim=-1)
|
| 364 |
+
# Restore original shape with embedding dimension
|
| 365 |
+
time_emb = time_emb.view(*shape, self.dim)
|
| 366 |
+
|
| 367 |
+
return time_emb
|
models/matris/matris/model/feature_embed.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
BesselExpansion,
|
| 9 |
+
GaussianExpansion,
|
| 10 |
+
GaussianExpansion,
|
| 11 |
+
SphericalExpansion,
|
| 12 |
+
SinusoidalTimeExpansion
|
| 13 |
+
)
|
| 14 |
+
from .functions import get_normalization, SwishLayer, aggregate
|
| 15 |
+
|
| 16 |
+
class AtomTypeEmbedding(nn.Module):
|
| 17 |
+
"""Encode an atom by its atomic number using 'nn.Embedding'."""
|
| 18 |
+
|
| 19 |
+
def __init__(self, atom_feat_dim: int, max_num_elements: int = 94):
|
| 20 |
+
"""
|
| 21 |
+
Args:
|
| 22 |
+
atom_feature_dim (int): dimension of atomic embedding.
|
| 23 |
+
max_num_elements (int): maximum number of elements in the dataset.
|
| 24 |
+
Default = 94
|
| 25 |
+
"""
|
| 26 |
+
super().__init__()
|
| 27 |
+
self.embedding = nn.Embedding(max_num_elements, atom_feat_dim)
|
| 28 |
+
self.atom_swish_layer = SwishLayer(input_dim = atom_feat_dim,
|
| 29 |
+
output_dim = atom_feat_dim,
|
| 30 |
+
bias=False)
|
| 31 |
+
|
| 32 |
+
def forward(self, atom_type: Tensor) -> Tensor:
|
| 33 |
+
"""
|
| 34 |
+
Args:
|
| 35 |
+
atom_type (Tensor): [nAtoms, 1].
|
| 36 |
+
"""
|
| 37 |
+
node_feat = self.embedding(atom_type)
|
| 38 |
+
node_feat = self.atom_swish_layer(node_feat)
|
| 39 |
+
return node_feat
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class EdgeBasisEmbedding(nn.Module):
|
| 43 |
+
"""Embed edge length using 'Bessel' or 'Gaussian'."""
|
| 44 |
+
|
| 45 |
+
def __init__(
|
| 46 |
+
self,
|
| 47 |
+
pairwise_cutoff: float = 6,
|
| 48 |
+
three_body_cutoff: float = 4,
|
| 49 |
+
num_radial: int = 7,
|
| 50 |
+
edge_feat_dim: int = 128,
|
| 51 |
+
envelope_exponent: int = 8,
|
| 52 |
+
distance_expansion: str = "Bessel",
|
| 53 |
+
learnable: bool = False,
|
| 54 |
+
):
|
| 55 |
+
"""
|
| 56 |
+
Args:
|
| 57 |
+
pairwise_cutoff (float): The cutoff for pairwise interaction.
|
| 58 |
+
Default = 6
|
| 59 |
+
three_body_cutoff (float): The cutoff for three-body interaction.
|
| 60 |
+
Default = 4
|
| 61 |
+
num_radial (int): The number of radial.
|
| 62 |
+
Default = 7
|
| 63 |
+
envelope_exponent (int): envelope exponent of Envelope function.
|
| 64 |
+
Default = 8
|
| 65 |
+
distance_expansion (str): The function of basis, "Bessel" or "Gaussian".
|
| 66 |
+
Default = "Bessel"
|
| 67 |
+
learnable(bool): Whether the frequency in bessel expansion is learnable.
|
| 68 |
+
Default = False
|
| 69 |
+
"""
|
| 70 |
+
super().__init__()
|
| 71 |
+
|
| 72 |
+
self.distance_expansion = distance_expansion
|
| 73 |
+
if self.distance_expansion.lower() == "bessel":
|
| 74 |
+
self.pairwise_rbf_expansion = BesselExpansion(
|
| 75 |
+
num_radial=num_radial,
|
| 76 |
+
cutoff=pairwise_cutoff,
|
| 77 |
+
envelope_exponent=envelope_exponent,
|
| 78 |
+
learnable=learnable,
|
| 79 |
+
)
|
| 80 |
+
self.threebody_rbf_expansion = BesselExpansion(
|
| 81 |
+
num_radial=num_radial,
|
| 82 |
+
cutoff=three_body_cutoff,
|
| 83 |
+
envelope_exponent=envelope_exponent,
|
| 84 |
+
learnable=learnable,
|
| 85 |
+
)
|
| 86 |
+
elif self.distance_expansion.lower() == "gaussian":
|
| 87 |
+
self.pairwise_rbf_expansion = GaussianExpansion(
|
| 88 |
+
start=0.0,
|
| 89 |
+
stop=pairwise_cutoff,
|
| 90 |
+
num_gaussians=num_radial,
|
| 91 |
+
basis_width_scalar=2.0,
|
| 92 |
+
)
|
| 93 |
+
self.threebody_rbf_expansion = GaussianExpansion(
|
| 94 |
+
start=0.0,
|
| 95 |
+
stop=three_body_cutoff,
|
| 96 |
+
num_gaussians=num_radial,
|
| 97 |
+
basis_width_scalar=2.0,
|
| 98 |
+
)
|
| 99 |
+
else:
|
| 100 |
+
raise NotImplementedError
|
| 101 |
+
|
| 102 |
+
self.edge_linear1 = nn.Linear(
|
| 103 |
+
in_features=num_radial, out_features=edge_feat_dim, bias=False
|
| 104 |
+
)
|
| 105 |
+
self.edge_linear2 = nn.Linear(
|
| 106 |
+
in_features=edge_feat_dim, out_features=edge_feat_dim, bias=False
|
| 107 |
+
)
|
| 108 |
+
self.swish_layer = SwishLayer(input_dim = edge_feat_dim,
|
| 109 |
+
output_dim = edge_feat_dim,
|
| 110 |
+
bias=False)
|
| 111 |
+
self.edge_init_norm = get_normalization(name="layer", dim=edge_feat_dim)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def forward(
|
| 115 |
+
self,
|
| 116 |
+
graphs,
|
| 117 |
+
) -> tuple[Tensor, Tensor, Tensor]:
|
| 118 |
+
"""
|
| 119 |
+
Args:
|
| 120 |
+
center_pos (Tensor): coord of center atoms.
|
| 121 |
+
neighbor_pos (Tensor): coordinates of neighbor atoms.
|
| 122 |
+
undirected2directed (Tensor): mapping from undirected vectors to one of its
|
| 123 |
+
directed vectors. Following repo: https://github.com/CederGroupHub/chgnet
|
| 124 |
+
image (Tensor): the periodic image specifying the location of neighbor atoms.
|
| 125 |
+
lattice (Tensor): the lattice matrix of structure.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
# From directed edge to undirected edge, this motivation is inspired by https://github.com/CederGroupHub/chgnet
|
| 129 |
+
unique_edge_lengths = torch.index_select( graphs['edge_lengths'], 0, graphs['undirected2directed'] ) #[nEdges/2]
|
| 130 |
+
|
| 131 |
+
pairwise_rbf = self.pairwise_rbf_expansion(unique_edge_lengths) #[nEdges/2, num_radial]
|
| 132 |
+
threebody_rbf = self.threebody_rbf_expansion(unique_edge_lengths) #[nEdges/2, num_radial]
|
| 133 |
+
|
| 134 |
+
edge_feat_undirect = self.edge_linear1(pairwise_rbf)
|
| 135 |
+
# [edges, dim] -> [2*edges, dim]
|
| 136 |
+
edge_feat_direct = torch.index_select(edge_feat_undirect, 0, graphs['directed2undirected'])
|
| 137 |
+
edge_feat_direct = self.edge_linear2(edge_feat_direct)
|
| 138 |
+
edge_feat_direct = self.edge_init_norm(edge_feat_direct)
|
| 139 |
+
# Aggregate to bond_feas_ude
|
| 140 |
+
edge_feat = aggregate(data=edge_feat_direct,
|
| 141 |
+
segment=graphs['directed2undirected'],
|
| 142 |
+
bin_count=None,
|
| 143 |
+
average=True,
|
| 144 |
+
num_segment=None)
|
| 145 |
+
edge_feat = self.swish_layer(edge_feat)
|
| 146 |
+
smooth_weight={"atom graph": pairwise_rbf, "line graph": threebody_rbf}
|
| 147 |
+
#return edge_feat, pairwise_rbf, threebody_rbf
|
| 148 |
+
return edge_feat, smooth_weight
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class ThreebodyEmbedding(nn.Module):
|
| 152 |
+
"""Embed threebody using 'Fourier' or 'Sphere Harmonic'."""
|
| 153 |
+
|
| 154 |
+
def __init__(self,
|
| 155 |
+
num_angular: int = 7, # Fourier
|
| 156 |
+
max_n: int=4, max_l: int=4, cutoff: int=6, #SH
|
| 157 |
+
three_body_feat_dim: int = 128,
|
| 158 |
+
three_body_expansion: str = "fourier",
|
| 159 |
+
learnable: bool = True):
|
| 160 |
+
super().__init__()
|
| 161 |
+
|
| 162 |
+
self.three_body_expansion = three_body_expansion.lower()
|
| 163 |
+
if self.three_body_expansion == "fourier":
|
| 164 |
+
max_f = (num_angular - 1) // 2
|
| 165 |
+
self.expansion = FourierExpansion(
|
| 166 |
+
max_f=max_f, learnable=learnable
|
| 167 |
+
)
|
| 168 |
+
self.angle_embedding = nn.Linear(
|
| 169 |
+
in_features=num_angular, out_features=three_body_feat_dim, bias=False
|
| 170 |
+
)
|
| 171 |
+
elif self.three_body_expansion == "sh":
|
| 172 |
+
self.expansion = SphericalExpansion(max_n=max_n, max_l=max_l, cutoff=cutoff)
|
| 173 |
+
self.angle_embedding = nn.Linear(
|
| 174 |
+
in_features=max_n * max_l, out_features=three_body_feat_dim, bias=False
|
| 175 |
+
)
|
| 176 |
+
else:
|
| 177 |
+
raise NotImplementedError
|
| 178 |
+
|
| 179 |
+
self.swish_layer = SwishLayer(input_dim = three_body_feat_dim,
|
| 180 |
+
output_dim = three_body_feat_dim,
|
| 181 |
+
bias=False)
|
| 182 |
+
|
| 183 |
+
def forward(self, graphs):
|
| 184 |
+
edge_vecs_ij = torch.index_select(
|
| 185 |
+
graphs['unit_edge_vectors'], 0, graphs['line_graph_dict']['target_DE_index']
|
| 186 |
+
) # normalized edge vector ij [nAngle, 3]
|
| 187 |
+
edge_vecs_jk = torch.index_select(
|
| 188 |
+
graphs['unit_edge_vectors'], 0, graphs['line_graph_dict']['source_DE_index']
|
| 189 |
+
) # normalized edge vector jk [nAngle, 3]
|
| 190 |
+
|
| 191 |
+
theta_ijk = torch.sum(edge_vecs_ij * edge_vecs_jk, dim=1) * (1 - 1e-6)
|
| 192 |
+
angle = torch.acos(theta_ijk)
|
| 193 |
+
|
| 194 |
+
if self.three_body_expansion == "sh":
|
| 195 |
+
edge_vecs_jk_len = torch.norm(edge_vecs_jk, dim=1)
|
| 196 |
+
three_body_basis = self.expansion(edge_vecs_jk_len, angle)
|
| 197 |
+
else:
|
| 198 |
+
three_body_basis = self.expansion(angle)
|
| 199 |
+
|
| 200 |
+
threebody_feat = self.angle_embedding(three_body_basis)
|
| 201 |
+
threebody_feat = self.swish_layer(threebody_feat)
|
| 202 |
+
|
| 203 |
+
return threebody_feat
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
class ThreebodyFourierExpansion(nn.Module):
|
| 207 |
+
"""Encode an three-body terms using Fourier Expansion."""
|
| 208 |
+
|
| 209 |
+
def __init__(self, num_angular: int = 7, learnable: bool = True):
|
| 210 |
+
super().__init__()
|
| 211 |
+
|
| 212 |
+
assert num_angular % 2 == 1, f"{num_angular=} must be an odd integer"
|
| 213 |
+
max_f = (num_angular - 1) // 2
|
| 214 |
+
self.fourier_expansion = FourierExpansion(
|
| 215 |
+
max_f=max_f, learnable=learnable
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
def forward(self, edge_vec_ij: Tensor, edge_vec_jk: Tensor) -> Tensor:
|
| 219 |
+
"""
|
| 220 |
+
Args:
|
| 221 |
+
edge_vec_i (Tensor): normalized edge vector ij [n_angle, 3]
|
| 222 |
+
edge_vec_j (Tensor): normalized edge vector jk [n_angle, 3]
|
| 223 |
+
"""
|
| 224 |
+
theta_ijk = torch.sum(edge_vec_ij * edge_vec_jk, dim=1) * (1 - 1e-6)
|
| 225 |
+
angle = torch.acos(theta_ijk)
|
| 226 |
+
return self.fourier_expansion(angle)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
class three_bodySHExpansion(nn.Module):
|
| 230 |
+
"""Encode an three-body terms using Sphere Harmonic Expansion."""
|
| 231 |
+
|
| 232 |
+
def __init__(self, max_n: int=4, max_l: int=4, cutoff: int=6) -> None:
|
| 233 |
+
super().__init__()
|
| 234 |
+
self.sbf = SphericalExpansion(max_n=max_n, max_l=max_l, cutoff=cutoff)
|
| 235 |
+
|
| 236 |
+
def forward(self, edge_vec_ij: Tensor, edge_vec_jk: Tensor) -> Tensor:
|
| 237 |
+
"""
|
| 238 |
+
Args:
|
| 239 |
+
edge_vec_i (Tensor): normalized edge vector ij [n_angle, 3]
|
| 240 |
+
edge_vec_j (Tensor): normalized edge vector jk [n_angle, 3]
|
| 241 |
+
"""
|
| 242 |
+
theta_ijk = torch.sum(edge_vec_ij * edge_vec_jk, dim=1) * (1 - 1e-6)
|
| 243 |
+
angle = torch.acos(theta_ijk)
|
| 244 |
+
|
| 245 |
+
edge_vec_jk_len = torch.norm(edge_vec_jk, dim=1)
|
| 246 |
+
angle_basis = self.sbf(edge_vec_jk_len, angle)
|
| 247 |
+
return angle_basis
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
class TimeEmbedding(nn.Module):
|
| 251 |
+
"""Encode time using nonlinear"""
|
| 252 |
+
|
| 253 |
+
def __init__(self, time_feat_dim):
|
| 254 |
+
super().__init__()
|
| 255 |
+
self.time_encode = SinusoidalTimeExpansion(dim = time_feat_dim)
|
| 256 |
+
self.linear1 = nn.Linear(
|
| 257 |
+
in_features = time_feat_dim, out_features = 2 * time_feat_dim
|
| 258 |
+
)
|
| 259 |
+
self.act = nn.SiLU()
|
| 260 |
+
self.linear2 = nn.Linear(
|
| 261 |
+
in_features = time_feat_dim * 2, out_features = time_feat_dim
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
def forward(self, time):
|
| 265 |
+
time_enc= self.time_encode(time)
|
| 266 |
+
time_enc = self.act(self.linear1(time_enc))
|
| 267 |
+
time_emb = self.linear2(time_enc)
|
| 268 |
+
return time_emb
|
models/matris/matris/model/functions.py
ADDED
|
@@ -0,0 +1,466 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections.abc import Sequence
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch import Tensor, nn
|
| 7 |
+
import math
|
| 8 |
+
from .op import fused_silu, fused_sigmoid
|
| 9 |
+
|
| 10 |
+
class FusedSiLU(torch.nn.Module):
|
| 11 |
+
"""Fused Sigmoid Linear Unit."""
|
| 12 |
+
|
| 13 |
+
def __init__(self) -> None:
|
| 14 |
+
"""Initialize a fused SiLU."""
|
| 15 |
+
super().__init__()
|
| 16 |
+
|
| 17 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 18 |
+
"""Forward pass."""
|
| 19 |
+
if x.device.type == "cuda":
|
| 20 |
+
return fused_silu(x)
|
| 21 |
+
else:
|
| 22 |
+
return torch.nn.functional.silu(x)
|
| 23 |
+
|
| 24 |
+
class FusedSigmoid(torch.nn.Module):
|
| 25 |
+
"""Fused Sigmoid Linear Unit."""
|
| 26 |
+
|
| 27 |
+
def __init__(self) -> None:
|
| 28 |
+
"""Initialize a fused SiLU."""
|
| 29 |
+
super().__init__()
|
| 30 |
+
|
| 31 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 32 |
+
"""Forward pass."""
|
| 33 |
+
if x.device.type == "cuda":
|
| 34 |
+
return fused_sigmoid(x)
|
| 35 |
+
else:
|
| 36 |
+
return torch.nn.functional.sigmoid(x)
|
| 37 |
+
|
| 38 |
+
def get_activation(name: str) -> nn.Module:
|
| 39 |
+
"""Return an activation function"""
|
| 40 |
+
activation_map = {
|
| 41 |
+
"relu": nn.ReLU,
|
| 42 |
+
"silu": FusedSiLU, # Using fused version for better performance
|
| 43 |
+
"gelu": nn.GELU,
|
| 44 |
+
"softplus": nn.Softplus,
|
| 45 |
+
"sigmoid": FusedSigmoid, # Using fused version for better performance
|
| 46 |
+
"tanh": nn.Tanh,
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
name_lower = name.lower()
|
| 50 |
+
if name_lower not in activation_map:
|
| 51 |
+
raise NotImplementedError(
|
| 52 |
+
f"Activation '{name}' is not implemented. "
|
| 53 |
+
f"Supported activations: {list(activation_map.keys())}"
|
| 54 |
+
)
|
| 55 |
+
return activation_map[name_lower]()
|
| 56 |
+
|
| 57 |
+
def get_normalization(name: str, dim: int | None = None) -> nn.Module | None:
|
| 58 |
+
"""Return an normalization function"""
|
| 59 |
+
if name is None:
|
| 60 |
+
return None
|
| 61 |
+
|
| 62 |
+
normalization_map = {
|
| 63 |
+
"layer": nn.LayerNorm(dim),
|
| 64 |
+
"rms": nn.RMSNorm(dim), # torch >= 2.6.0
|
| 65 |
+
"batch": nn.BatchNorm1d(dim),
|
| 66 |
+
}
|
| 67 |
+
name_lower = name.lower()
|
| 68 |
+
return normalization_map[name_lower]
|
| 69 |
+
|
| 70 |
+
class SwishLayer(nn.Module):
|
| 71 |
+
def __init__(
|
| 72 |
+
self,
|
| 73 |
+
input_dim: int = 128,
|
| 74 |
+
output_dim: int = 128,
|
| 75 |
+
bias: bool = True,
|
| 76 |
+
) -> None:
|
| 77 |
+
"""
|
| 78 |
+
Args:
|
| 79 |
+
input_dim: Input dimension.
|
| 80 |
+
output_dim: Output dimension.
|
| 81 |
+
bias: Whether to use bias in the linear layer. Default: True.
|
| 82 |
+
"""
|
| 83 |
+
super().__init__()
|
| 84 |
+
self.linear = nn.Linear(input_dim, output_dim, bias=bias)
|
| 85 |
+
self.act = get_activation("silu")
|
| 86 |
+
|
| 87 |
+
def forward(self, feas: Tensor) -> Tensor:
|
| 88 |
+
"""
|
| 89 |
+
Args:
|
| 90 |
+
feas: shape (feas_num, in_dim)
|
| 91 |
+
|
| 92 |
+
Returns:
|
| 93 |
+
output: shape (feas_num, out_dim)
|
| 94 |
+
"""
|
| 95 |
+
return self.act(self.linear(feas))
|
| 96 |
+
|
| 97 |
+
def Dimwise_softmax(feas: Tensor, segment: Tensor, num_segment=None) -> Tensor:
|
| 98 |
+
"""Computes a sparsely evaluated softmax.
|
| 99 |
+
|
| 100 |
+
Args:
|
| 101 |
+
feas: The source tensor. shape: [num, dim]
|
| 102 |
+
segment: specify the segment of each row [num, 1]
|
| 103 |
+
"""
|
| 104 |
+
num, dim = feas.shape
|
| 105 |
+
if num_segment is None:
|
| 106 |
+
num_segment = int(segment.max()) + 1
|
| 107 |
+
|
| 108 |
+
segment_expanded = segment.unsqueeze(1).expand(-1, dim) # [num, dim]
|
| 109 |
+
|
| 110 |
+
feas_max = torch.empty( num_segment, dim, dtype=feas.dtype, device=feas.device )
|
| 111 |
+
feas_max.fill_(float("-inf"))
|
| 112 |
+
feas_max = feas_max.scatter_reduce(
|
| 113 |
+
0, segment_expanded, feas, reduce='amax', include_self=False,
|
| 114 |
+
) #[num_segment, dim]
|
| 115 |
+
# Gather: [num_segment, dim] -> [num, dim]
|
| 116 |
+
feas_max = feas_max[segment]
|
| 117 |
+
out = (feas - feas_max).exp()
|
| 118 |
+
|
| 119 |
+
# =========== scatter sum ============
|
| 120 |
+
out_sum = torch.zeros(num_segment, dim, device=feas.device, dtype=feas.dtype)
|
| 121 |
+
out_sum = out_sum.scatter_reduce(
|
| 122 |
+
0, segment_expanded, out, reduce='sum', include_self=False
|
| 123 |
+
)
|
| 124 |
+
# Gather: [num_segment, dim] -> [num, dim]
|
| 125 |
+
out_sum = out_sum[segment]
|
| 126 |
+
score = out / out_sum
|
| 127 |
+
return score
|
| 128 |
+
|
| 129 |
+
def aggregate(data: torch.Tensor,
|
| 130 |
+
segment: torch.Tensor,
|
| 131 |
+
bin_count: torch.Tensor = None,
|
| 132 |
+
average=True,
|
| 133 |
+
num_segment=None) -> torch.Tensor:
|
| 134 |
+
"""Aggregate rows in data by specifying the segment.
|
| 135 |
+
|
| 136 |
+
Args:
|
| 137 |
+
data (Tensor): data tensor to aggregate [n_row, feature_dim]
|
| 138 |
+
segment (Tensor): specify the owner of each row [n_row, 1]
|
| 139 |
+
average (bool): if True, average the rows, if False, sum the rows.
|
| 140 |
+
Default = True
|
| 141 |
+
num_owner (int, optional): the number of owners, this is needed if the
|
| 142 |
+
max idx of owner is not presented in owners tensor
|
| 143 |
+
Default = None
|
| 144 |
+
|
| 145 |
+
Returns:
|
| 146 |
+
output (Tensor): [num_owner, feature_dim]
|
| 147 |
+
"""
|
| 148 |
+
if bin_count is None:
|
| 149 |
+
bin_count = torch.bincount(segment)
|
| 150 |
+
bin_count = bin_count.where(bin_count != 0, bin_count.new_ones(1))
|
| 151 |
+
|
| 152 |
+
if (num_segment is not None) and (bin_count.shape[0] != num_segment):
|
| 153 |
+
difference = num_segment - bin_count.shape[0]
|
| 154 |
+
bin_count = torch.cat([bin_count, bin_count.new_ones(difference)])
|
| 155 |
+
# make sure this operation is done on the same device of data and owners
|
| 156 |
+
output = data.new_zeros([bin_count.shape[0], data.shape[1]])
|
| 157 |
+
output = output.index_add_(0, segment, data)
|
| 158 |
+
if average:
|
| 159 |
+
output = (output.T / bin_count).T
|
| 160 |
+
return output
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class MLP(nn.Module):
|
| 164 |
+
|
| 165 |
+
def __init__(
|
| 166 |
+
self,
|
| 167 |
+
input_dim: int = 128,
|
| 168 |
+
hidden_dim: int | Sequence[int] | None = (128, 128),
|
| 169 |
+
output_dim: int = 128,
|
| 170 |
+
dropout: float = 0.0,
|
| 171 |
+
activation: Literal["silu", "relu", "tanh", "gelu"] = "silu",
|
| 172 |
+
bias: bool = True,
|
| 173 |
+
use_fp16: bool = False,
|
| 174 |
+
):
|
| 175 |
+
"""Initialize the MLP layer.
|
| 176 |
+
Args:
|
| 177 |
+
input_dim: Dimension of input features.
|
| 178 |
+
hidden_dim: Number of hidden units. Can be an integer for a single
|
| 179 |
+
hidden layer, a sequence of integers for multiple hidden layers,
|
| 180 |
+
or None for no hidden layers. Default: (128, 128).
|
| 181 |
+
output_dim: Dimension of output predictions. Default: 128.
|
| 182 |
+
dropout: Dropout rate applied before each linear layer. Default: 0.0.
|
| 183 |
+
activation: Activation function. Supported: "relu", "silu", "tanh", "gelu".
|
| 184 |
+
bias: Whether to use bias in linear layers. Default: True.
|
| 185 |
+
use_fp16: Whether to use mixed precision (FP16). Default: False.
|
| 186 |
+
"""
|
| 187 |
+
super().__init__()
|
| 188 |
+
if not 0.0 <= dropout < 1.0:
|
| 189 |
+
raise ValueError(f"Dropout rate must be in [0.0, 1.0), got {dropout}")
|
| 190 |
+
|
| 191 |
+
self.use_fp16 = use_fp16
|
| 192 |
+
activation_func = get_activation(activation)
|
| 193 |
+
|
| 194 |
+
layers = []
|
| 195 |
+
if hidden_dim in (None, 0):
|
| 196 |
+
layers.append(nn.Dropout(dropout))
|
| 197 |
+
layers.append(nn.Linear(input_dim, output_dim, bias=bias))
|
| 198 |
+
elif isinstance(hidden_dim, int):
|
| 199 |
+
# Single hidden layer
|
| 200 |
+
layers.extend([
|
| 201 |
+
nn.Linear(input_dim, hidden_dim, bias=bias),
|
| 202 |
+
activation_func,
|
| 203 |
+
nn.Dropout(dropout),
|
| 204 |
+
nn.Linear(hidden_dim, output_dim, bias=bias),
|
| 205 |
+
])
|
| 206 |
+
elif isinstance(hidden_dim, Sequence):
|
| 207 |
+
# Multiple hidden layers
|
| 208 |
+
layers.extend([
|
| 209 |
+
nn.Linear(input_dim, hidden_dim[0], bias=bias),
|
| 210 |
+
activation_func,
|
| 211 |
+
])
|
| 212 |
+
# Additional hidden layers
|
| 213 |
+
for i in range(len(hidden_dim) - 1):
|
| 214 |
+
layers.extend([
|
| 215 |
+
nn.Dropout(dropout),
|
| 216 |
+
nn.Linear(hidden_dim[i], hidden_dim[i + 1], bias=bias),
|
| 217 |
+
activation_func,
|
| 218 |
+
])
|
| 219 |
+
# Output layer
|
| 220 |
+
layers.extend([nn.Dropout(dropout), nn.Linear(hidden_dim[-1], output_dim, bias=bias)])
|
| 221 |
+
else:
|
| 222 |
+
raise TypeError(
|
| 223 |
+
f"hidden_dim must be an integer, sequence of integers, or None, "
|
| 224 |
+
f"got {type(hidden_dim).__name__}"
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
self.layers = nn.Sequential(*layers)
|
| 228 |
+
|
| 229 |
+
def forward(self, feas: Tensor) -> Tensor:
|
| 230 |
+
"""
|
| 231 |
+
Args:
|
| 232 |
+
feas: Input tensor of shape (features, input_dim)
|
| 233 |
+
Returns:
|
| 234 |
+
Output tensor of shape (features, output_dim)
|
| 235 |
+
"""
|
| 236 |
+
if self.use_fp16 and feas.is_cuda:
|
| 237 |
+
with torch.amp.autocast(dtype=torch.float16, device_type="cuda"):
|
| 238 |
+
out = self.layers(feas)
|
| 239 |
+
out = out.to(torch.float32)
|
| 240 |
+
else:
|
| 241 |
+
out = self.layers(feas)
|
| 242 |
+
return out
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
class GatedMLP(nn.Module):
|
| 246 |
+
|
| 247 |
+
def __init__(
|
| 248 |
+
self,
|
| 249 |
+
input_dim: int = 128,
|
| 250 |
+
hidden_dim: int | Sequence[int] | None = (128, 128),
|
| 251 |
+
output_dim: int = 128,
|
| 252 |
+
dropout: float = 0.0,
|
| 253 |
+
activation: str = "silu",
|
| 254 |
+
norm_type: str = "layer",
|
| 255 |
+
bias: bool = True,
|
| 256 |
+
use_fp16: bool = False,
|
| 257 |
+
) -> None:
|
| 258 |
+
"""
|
| 259 |
+
Args:
|
| 260 |
+
input_dim: The input dimension.
|
| 261 |
+
hidden_dim: A list of integers or a single integer representing the number
|
| 262 |
+
of hidden units in each layer of the MLP. Default: None.
|
| 263 |
+
output_dim: The output dimension.
|
| 264 |
+
dropout: The dropout rate. Default: 0.0.
|
| 265 |
+
activation: The name of the activation function. Must be one of "relu",
|
| 266 |
+
"silu", "tanh", or "gelu". Default: "silu".
|
| 267 |
+
norm_type: The name of the normalization layer to use. Must be one of
|
| 268 |
+
"layer", "rms", "batch", "group", or None. Default: "layer".
|
| 269 |
+
bias: Whether to use bias in linear layers. Default: True.
|
| 270 |
+
use_fp16: Whether to use mixed precision (FP16). Default: False.
|
| 271 |
+
"""
|
| 272 |
+
super().__init__()
|
| 273 |
+
self.use_fp16 = use_fp16
|
| 274 |
+
self.activation_func = get_activation(activation)
|
| 275 |
+
self.activation_gate = get_activation("sigmoid")
|
| 276 |
+
self.gate_norm = get_normalization(name=norm_type, dim=output_dim)
|
| 277 |
+
self.core_norm = get_normalization(name=norm_type, dim=output_dim)
|
| 278 |
+
self.mlp_core = MLP(
|
| 279 |
+
input_dim=input_dim,
|
| 280 |
+
hidden_dim=hidden_dim,
|
| 281 |
+
output_dim=output_dim,
|
| 282 |
+
dropout=dropout,
|
| 283 |
+
activation=activation,
|
| 284 |
+
bias=bias,
|
| 285 |
+
use_fp16=use_fp16,
|
| 286 |
+
)
|
| 287 |
+
self.mlp_gate = MLP(
|
| 288 |
+
input_dim=input_dim,
|
| 289 |
+
hidden_dim=hidden_dim,
|
| 290 |
+
output_dim=output_dim,
|
| 291 |
+
dropout=dropout,
|
| 292 |
+
activation=activation,
|
| 293 |
+
bias=bias,
|
| 294 |
+
use_fp16=use_fp16,
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
def forward(self, feas: Tensor) -> Tensor:
|
| 298 |
+
"""
|
| 299 |
+
Args:
|
| 300 |
+
feas (Tensor): shape (feas_num, input_dim)
|
| 301 |
+
Returns:
|
| 302 |
+
output: shape (feas_num, output_dim)
|
| 303 |
+
"""
|
| 304 |
+
if self.gate_norm is None:
|
| 305 |
+
core = self.activation_func(self.mlp_core(feas))
|
| 306 |
+
gate = self.activation_gate(self.mlp_gate(feas))
|
| 307 |
+
else:
|
| 308 |
+
core = self.activation_func(self.core_norm(self.mlp_core(feas)))
|
| 309 |
+
gate = self.activation_gate(self.gate_norm(self.mlp_gate(feas)))
|
| 310 |
+
out = core * gate # gate mul
|
| 311 |
+
return out
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
class MOE_Layer(nn.Module):
|
| 315 |
+
|
| 316 |
+
def __init__(
|
| 317 |
+
self,
|
| 318 |
+
num_expert: int = 64,
|
| 319 |
+
input_dim: int = 128,
|
| 320 |
+
hidden_dim: int | Sequence[int] | None = (128, 128),
|
| 321 |
+
output_dim: int = 128,
|
| 322 |
+
dropout: float = 0.0,
|
| 323 |
+
activation: Literal["silu", "relu", "tanh", "gelu"] = "silu",
|
| 324 |
+
bias: bool = True,
|
| 325 |
+
use_fp16: bool = False,
|
| 326 |
+
):
|
| 327 |
+
"""Initialize the MOE layer.
|
| 328 |
+
|
| 329 |
+
Args:
|
| 330 |
+
|
| 331 |
+
"""
|
| 332 |
+
super().__init__()
|
| 333 |
+
|
| 334 |
+
raise NotImplementedError
|
| 335 |
+
|
| 336 |
+
def forward(self, feas: Tensor) -> Tensor:
|
| 337 |
+
return None
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
class GraphPooling(nn.Module):
|
| 341 |
+
def __init__(self, average: bool = False) -> None:
|
| 342 |
+
|
| 343 |
+
super().__init__()
|
| 344 |
+
self.average = average
|
| 345 |
+
|
| 346 |
+
def forward(self, node_feat: Tensor, segment: Tensor) -> Tensor:
|
| 347 |
+
"""
|
| 348 |
+
Args:
|
| 349 |
+
atom_feat (Tensor): batched atom features after convolution layers.
|
| 350 |
+
[num_batch_atoms, node_feat_dim or 1]
|
| 351 |
+
segment (Tensor): graph indices for each atom.
|
| 352 |
+
[num_batch_atoms]
|
| 353 |
+
|
| 354 |
+
Returns:
|
| 355 |
+
crystal_feas (Tensor): crystal feature matrix.
|
| 356 |
+
[n_crystals, node_feat_dim or 1]
|
| 357 |
+
"""
|
| 358 |
+
bin_count = torch.bincount(segment)
|
| 359 |
+
bin_count = bin_count.where(bin_count != 0, bin_count.new_ones(1))
|
| 360 |
+
|
| 361 |
+
output = node_feat.new_zeros([bin_count.shape[0], node_feat.shape[1]])
|
| 362 |
+
output = output.index_add_(0, segment, node_feat)
|
| 363 |
+
if self.average:
|
| 364 |
+
output = (output.T / bin_count).T
|
| 365 |
+
return output
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def cg_change_mat(ang_mom: int, device: str = "cpu") -> torch.tensor:
|
| 369 |
+
if ang_mom not in [2]:
|
| 370 |
+
raise NotImplementedError
|
| 371 |
+
|
| 372 |
+
if ang_mom == 2:
|
| 373 |
+
change_mat = torch.tensor(
|
| 374 |
+
[
|
| 375 |
+
[3 ** (-0.5), 0, 0, 0, 3 ** (-0.5), 0, 0, 0, 3 ** (-0.5)],
|
| 376 |
+
[0, 0, 0, 0, 0, 2 ** (-0.5), 0, -(2 ** (-0.5)), 0],
|
| 377 |
+
[0, 0, -(2 ** (-0.5)), 0, 0, 0, 2 ** (-0.5), 0, 0],
|
| 378 |
+
[0, 2 ** (-0.5), 0, -(2 ** (-0.5)), 0, 0, 0, 0, 0],
|
| 379 |
+
[0, 0, 0.5**0.5, 0, 0, 0, 0.5**0.5, 0, 0],
|
| 380 |
+
[0, 2 ** (-0.5), 0, 2 ** (-0.5), 0, 0, 0, 0, 0],
|
| 381 |
+
[
|
| 382 |
+
-(6 ** (-0.5)),
|
| 383 |
+
0,
|
| 384 |
+
0,
|
| 385 |
+
0,
|
| 386 |
+
2 * 6 ** (-0.5),
|
| 387 |
+
0,
|
| 388 |
+
0,
|
| 389 |
+
0,
|
| 390 |
+
-(6 ** (-0.5)),
|
| 391 |
+
],
|
| 392 |
+
[0, 0, 0, 0, 0, 2 ** (-0.5), 0, 2 ** (-0.5), 0],
|
| 393 |
+
[-(2 ** (-0.5)), 0, 0, 0, 0, 0, 0, 0, 2 ** (-0.5)],
|
| 394 |
+
],
|
| 395 |
+
device=device,
|
| 396 |
+
).detach()
|
| 397 |
+
|
| 398 |
+
return change_mat
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
def irreps_sum(ang_mom: int) -> int:
|
| 402 |
+
"""
|
| 403 |
+
Returns the sum of the dimensions of the irreps up to the specified angular momentum.
|
| 404 |
+
|
| 405 |
+
:param ang_mom: max angular momenttum to sum up dimensions of irreps
|
| 406 |
+
"""
|
| 407 |
+
total = 0
|
| 408 |
+
for i in range(ang_mom + 1):
|
| 409 |
+
total += 2 * i + 1
|
| 410 |
+
|
| 411 |
+
return total
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def reshape_stress(L0out, L2out, batch_size=1):
|
| 415 |
+
_max_rank = 2
|
| 416 |
+
pred_irreps = torch.zeros(
|
| 417 |
+
(batch_size, irreps_sum(_max_rank)),
|
| 418 |
+
device = L0out.device,
|
| 419 |
+
)
|
| 420 |
+
# L=0
|
| 421 |
+
L=0
|
| 422 |
+
pred_irreps[: ,irreps_sum(L-1): irreps_sum(L)] = L0out.view(batch_size, -1)
|
| 423 |
+
|
| 424 |
+
L=2
|
| 425 |
+
pred_irreps[: ,irreps_sum(L-1): irreps_sum(L)] = L2out.view(batch_size, -1)
|
| 426 |
+
|
| 427 |
+
pred = torch.einsum(
|
| 428 |
+
"ba, cb->ca",
|
| 429 |
+
cg_change_mat(_max_rank, device = L0out.device),
|
| 430 |
+
pred_irreps,
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
return pred.view(batch_size, 3,3)
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
class Sphere(nn.Module):
|
| 437 |
+
|
| 438 |
+
def __init__(self, lmax=2):
|
| 439 |
+
super(Sphere, self).__init__()
|
| 440 |
+
self.lmax = lmax
|
| 441 |
+
|
| 442 |
+
def forward(self, edge_vec):
|
| 443 |
+
edge_sh = self._spherical_harmonics(self.lmax, edge_vec[..., 0], edge_vec[..., 1], edge_vec[..., 2])
|
| 444 |
+
return edge_sh
|
| 445 |
+
|
| 446 |
+
@staticmethod
|
| 447 |
+
def _spherical_harmonics(lmax: int, x: Tensor, y: Tensor, z: Tensor) -> Tensor:
|
| 448 |
+
sh_0_0 = torch.ones_like(x)
|
| 449 |
+
if lmax == 0:
|
| 450 |
+
return torch.stack([ sh_0_0, ], dim=-1)
|
| 451 |
+
|
| 452 |
+
sh_1_0, sh_1_1, sh_1_2 = x, y, z
|
| 453 |
+
|
| 454 |
+
if lmax == 1:
|
| 455 |
+
return torch.stack([sh_0_0, sh_1_0, sh_1_1, sh_1_2], dim=-1)
|
| 456 |
+
|
| 457 |
+
sh_2_0 = math.sqrt(3.0) * x * z
|
| 458 |
+
sh_2_1 = math.sqrt(3.0) * x * y
|
| 459 |
+
y2 = y.pow(2)
|
| 460 |
+
x2z2 = x.pow(2) + z.pow(2)
|
| 461 |
+
sh_2_2 = y2 - 0.5 * x2z2
|
| 462 |
+
sh_2_3 = math.sqrt(3.0) * y * z
|
| 463 |
+
sh_2_4 = math.sqrt(3.0) / 2.0 * (z.pow(2) - x.pow(2))
|
| 464 |
+
|
| 465 |
+
if lmax == 2:
|
| 466 |
+
return torch.stack([sh_0_0, sh_1_0, sh_1_1, sh_1_2, sh_2_0, sh_2_1, sh_2_2, sh_2_3, sh_2_4], dim=-1)
|
models/matris/matris/model/interaction_block.py
ADDED
|
@@ -0,0 +1,507 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch import Tensor, nn
|
| 5 |
+
from typing import Any, Dict
|
| 6 |
+
from .functions import (
|
| 7 |
+
MLP,
|
| 8 |
+
GatedMLP,
|
| 9 |
+
aggregate,
|
| 10 |
+
get_normalization,
|
| 11 |
+
Dimwise_softmax,
|
| 12 |
+
)
|
| 13 |
+
from torch.utils.checkpoint import checkpoint
|
| 14 |
+
|
| 15 |
+
THRESHOLD_VALUE = 60000 # Safe value for MatRIS-10M (A100-80GB)
|
| 16 |
+
|
| 17 |
+
class Graph_Attention_Layer(nn.Module):
|
| 18 |
+
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
node_feat_dim: int = 128,
|
| 22 |
+
edge_feat_dim: int = 128,
|
| 23 |
+
hidden_dim: int = 128,
|
| 24 |
+
use_bias: bool = False,
|
| 25 |
+
dropout: float = 0.0,
|
| 26 |
+
mlp_type: str = "GateMLP", # MLP, GateMLP
|
| 27 |
+
activation_type: str = "silu",
|
| 28 |
+
norm_type: str = "layer",
|
| 29 |
+
use_fp16: bool = False,
|
| 30 |
+
):
|
| 31 |
+
super().__init__()
|
| 32 |
+
|
| 33 |
+
self.source_weight_linear = nn.Linear(
|
| 34 |
+
in_features = edge_feat_dim, out_features = edge_feat_dim, bias = False
|
| 35 |
+
)
|
| 36 |
+
self.target_weight_linear = nn.Linear(
|
| 37 |
+
in_features = edge_feat_dim, out_features = edge_feat_dim, bias = False
|
| 38 |
+
)
|
| 39 |
+
if mlp_type.lower() == "mlp":
|
| 40 |
+
self.node_nonlinear_update = nn.Sequential(
|
| 41 |
+
MLP(
|
| 42 |
+
input_dim=edge_feat_dim * 2 + node_feat_dim,
|
| 43 |
+
hidden_dim=hidden_dim,
|
| 44 |
+
output_dim=node_feat_dim,
|
| 45 |
+
dropout=dropout,
|
| 46 |
+
bias=use_bias,
|
| 47 |
+
activation=activation_type,
|
| 48 |
+
),
|
| 49 |
+
get_normalization(name=norm_type, dim=node_feat_dim)
|
| 50 |
+
)
|
| 51 |
+
self.edge_nonlinear_update = nn.Sequential(
|
| 52 |
+
MLP(
|
| 53 |
+
input_dim=node_feat_dim * 2 + edge_feat_dim,
|
| 54 |
+
hidden_dim=hidden_dim,
|
| 55 |
+
output_dim=edge_feat_dim,
|
| 56 |
+
dropout=dropout,
|
| 57 |
+
bias=use_bias,
|
| 58 |
+
activation=activation_type,
|
| 59 |
+
use_fp16=use_fp16,
|
| 60 |
+
),
|
| 61 |
+
get_normalization(name=norm_type, dim=edge_feat_dim)
|
| 62 |
+
)
|
| 63 |
+
elif mlp_type.lower() == "gatemlp":
|
| 64 |
+
self.node_nonlinear_update = GatedMLP(
|
| 65 |
+
input_dim=edge_feat_dim * 2 + node_feat_dim,
|
| 66 |
+
hidden_dim=hidden_dim,
|
| 67 |
+
output_dim=node_feat_dim,
|
| 68 |
+
norm_type=norm_type,
|
| 69 |
+
dropout=dropout,
|
| 70 |
+
activation=activation_type,
|
| 71 |
+
)
|
| 72 |
+
self.edge_nonlinear_update = GatedMLP(
|
| 73 |
+
input_dim=node_feat_dim * 2 + edge_feat_dim,
|
| 74 |
+
hidden_dim=hidden_dim,
|
| 75 |
+
output_dim=edge_feat_dim,
|
| 76 |
+
norm_type=norm_type,
|
| 77 |
+
dropout=dropout,
|
| 78 |
+
activation=activation_type,
|
| 79 |
+
use_fp16=use_fp16,
|
| 80 |
+
)
|
| 81 |
+
else:
|
| 82 |
+
raise NotImplementedError
|
| 83 |
+
|
| 84 |
+
self.node_res_weight = torch.nn.Parameter(torch.ones(1, node_feat_dim), requires_grad=True)
|
| 85 |
+
self.edge_res_weight = torch.nn.Parameter(torch.ones(1, edge_feat_dim), requires_grad=True)
|
| 86 |
+
|
| 87 |
+
def forward(self,
|
| 88 |
+
node_feat: Tensor,
|
| 89 |
+
edge_feat: Tensor,
|
| 90 |
+
graph: Dict, # atom graph or line graph
|
| 91 |
+
directed2undirected: Tensor = None,
|
| 92 |
+
):
|
| 93 |
+
source_node_index = graph['source_index']
|
| 94 |
+
target_node_index = graph['target_index']
|
| 95 |
+
# gather
|
| 96 |
+
source_node_feat = torch.index_select(node_feat, 0, source_node_index)
|
| 97 |
+
target_node_feat = torch.index_select(node_feat, 0, target_node_index)
|
| 98 |
+
if directed2undirected is not None:
|
| 99 |
+
# Atom Graph Update
|
| 100 |
+
edge_feat_0 = torch.index_select(edge_feat, 0, directed2undirected) # [edge, dim] -> [2*edge, dim]
|
| 101 |
+
else:
|
| 102 |
+
# Line Graph Update
|
| 103 |
+
edge_feat_0 = edge_feat
|
| 104 |
+
|
| 105 |
+
#======= combine feature =======
|
| 106 |
+
attn_edge_feat = torch.cat([edge_feat_0, target_node_feat, source_node_feat], dim=1)
|
| 107 |
+
attn_edge_feat = self.edge_nonlinear_update(attn_edge_feat)
|
| 108 |
+
|
| 109 |
+
# ======= update atom feature =======
|
| 110 |
+
source_alpha_0 = self.source_weight_linear(edge_feat_0)
|
| 111 |
+
target_alpha_0 = self.target_weight_linear(edge_feat_0)
|
| 112 |
+
|
| 113 |
+
# Softmax
|
| 114 |
+
num_segment = None #torch.unique(source_node_index).numel()
|
| 115 |
+
source_alpha = Dimwise_softmax(source_alpha_0, source_node_index, num_segment)
|
| 116 |
+
target_alpha = Dimwise_softmax(target_alpha_0, target_node_index, num_segment)
|
| 117 |
+
|
| 118 |
+
source_weight = source_alpha * attn_edge_feat # refer to sa_{ij} * e'_{ij} in MatRIS paper
|
| 119 |
+
target_weight = target_alpha * attn_edge_feat # refer to ta_{ij} * e'_{ij} in MatRIS paper
|
| 120 |
+
|
| 121 |
+
if directed2undirected is not None:
|
| 122 |
+
attn_edge_feat = aggregate(data=attn_edge_feat, segment=directed2undirected, bin_count=None, average=True, num_segment=None) #[2*edge, dim] -> [edge, dim]
|
| 123 |
+
# Compute Attention output
|
| 124 |
+
attn_source_feat = aggregate(data=source_weight,
|
| 125 |
+
segment=source_node_index,
|
| 126 |
+
bin_count=graph['source_bincount'],#bincount_source,
|
| 127 |
+
average=False,
|
| 128 |
+
num_segment=len(node_feat))
|
| 129 |
+
|
| 130 |
+
attn_target_feat = aggregate(data=target_weight,
|
| 131 |
+
segment=target_node_index,
|
| 132 |
+
bin_count=graph['target_bincount'],#bincount_target,
|
| 133 |
+
average=False,
|
| 134 |
+
num_segment=len(node_feat))
|
| 135 |
+
|
| 136 |
+
fusion_node_feat = torch.cat([node_feat, attn_target_feat, attn_source_feat], dim=1)
|
| 137 |
+
attn_node_feat = self.node_nonlinear_update(fusion_node_feat)
|
| 138 |
+
|
| 139 |
+
# Resdual
|
| 140 |
+
attn_node_feat = attn_node_feat + self.node_res_weight * node_feat
|
| 141 |
+
attn_edge_feat = attn_edge_feat + self.edge_res_weight * edge_feat
|
| 142 |
+
|
| 143 |
+
return attn_node_feat, attn_edge_feat
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class Refinement(nn.Module):
|
| 147 |
+
|
| 148 |
+
def __init__(
|
| 149 |
+
self,
|
| 150 |
+
node_feat_dim: int = 128,
|
| 151 |
+
edge_feat_dim: int = 128,
|
| 152 |
+
hidden_dim: int = 128,
|
| 153 |
+
num_basis: int = 7,
|
| 154 |
+
dropout: float = 0.0,
|
| 155 |
+
mlp_type: str = "GateMLP",
|
| 156 |
+
activation_type: str = "silu",
|
| 157 |
+
norm_type: str = "layer",
|
| 158 |
+
use_bias: bool = False,
|
| 159 |
+
graph_type: Literal["atom graph", "line graph"] = "atom graph",
|
| 160 |
+
atom_feat_dim: int = 128,
|
| 161 |
+
use_smoothed_for_delta_edge: bool = False,
|
| 162 |
+
use_fp16: bool = False,
|
| 163 |
+
):
|
| 164 |
+
super().__init__()
|
| 165 |
+
self.graph_type = graph_type
|
| 166 |
+
self.use_smoothed_for_delta_edge = use_smoothed_for_delta_edge
|
| 167 |
+
|
| 168 |
+
if graph_type == "atom graph":
|
| 169 |
+
input_dim = 2 * node_feat_dim + edge_feat_dim
|
| 170 |
+
else:
|
| 171 |
+
input_dim = atom_feat_dim + 2 * node_feat_dim + edge_feat_dim
|
| 172 |
+
if mlp_type.lower() == "mlp":
|
| 173 |
+
self.edge_nonlinear_update = nn.Sequential(
|
| 174 |
+
MLP(
|
| 175 |
+
input_dim=input_dim,
|
| 176 |
+
hidden_dim=hidden_dim,
|
| 177 |
+
output_dim=edge_feat_dim,
|
| 178 |
+
dropout=dropout,
|
| 179 |
+
bias=use_bias,
|
| 180 |
+
activation=activation_type,
|
| 181 |
+
use_fp16=use_fp16,
|
| 182 |
+
),
|
| 183 |
+
get_normalization(name=norm_type, dim=edge_feat_dim)
|
| 184 |
+
)
|
| 185 |
+
elif mlp_type.lower() == "gatemlp":
|
| 186 |
+
self.edge_nonlinear_update = GatedMLP(
|
| 187 |
+
input_dim=input_dim,
|
| 188 |
+
hidden_dim=hidden_dim,
|
| 189 |
+
output_dim=edge_feat_dim,
|
| 190 |
+
dropout=dropout,
|
| 191 |
+
norm_type=norm_type,
|
| 192 |
+
activation=activation_type,
|
| 193 |
+
use_fp16=use_fp16,
|
| 194 |
+
)
|
| 195 |
+
else:
|
| 196 |
+
raise NotImplementedError
|
| 197 |
+
|
| 198 |
+
self.node_FFN = MLP(
|
| 199 |
+
input_dim=edge_feat_dim,
|
| 200 |
+
hidden_dim=node_feat_dim,
|
| 201 |
+
output_dim=node_feat_dim,
|
| 202 |
+
bias=use_bias,
|
| 203 |
+
)
|
| 204 |
+
self.edge_FFN = MLP(
|
| 205 |
+
input_dim=edge_feat_dim,
|
| 206 |
+
hidden_dim=edge_feat_dim,
|
| 207 |
+
output_dim=edge_feat_dim,
|
| 208 |
+
bias=use_bias,
|
| 209 |
+
use_fp16=use_fp16,
|
| 210 |
+
)
|
| 211 |
+
self.learnable_envelope = nn.Linear(
|
| 212 |
+
in_features = num_basis, out_features = edge_feat_dim, bias = False
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
self.node_res_weight = torch.nn.Parameter(torch.ones(1, node_feat_dim), requires_grad=True)
|
| 216 |
+
self.edge_res_weight = torch.nn.Parameter(torch.ones(1, edge_feat_dim), requires_grad=True)
|
| 217 |
+
|
| 218 |
+
def forward(
|
| 219 |
+
self,
|
| 220 |
+
node_feat: Tensor,
|
| 221 |
+
edge_feat: Tensor,
|
| 222 |
+
smooth_weight: Tensor,
|
| 223 |
+
graph: Dict,
|
| 224 |
+
directed2undirected: Tensor = None,
|
| 225 |
+
atom_feat: Tensor = None, # Line graph
|
| 226 |
+
) -> Tensor:
|
| 227 |
+
# Gather
|
| 228 |
+
# when graph=="line graph", make sure atom_deat is not None.
|
| 229 |
+
is_atom_graph = (self.graph_type == "atom graph")
|
| 230 |
+
|
| 231 |
+
if is_atom_graph:
|
| 232 |
+
edge_feat_0 = torch.index_select(edge_feat, 0, directed2undirected)
|
| 233 |
+
else:
|
| 234 |
+
edge_feat_0 = edge_feat
|
| 235 |
+
|
| 236 |
+
source_node_feat = torch.index_select(node_feat, 0, graph['source_index'])
|
| 237 |
+
target_node_feat = torch.index_select(node_feat, 0, graph['target_index'])
|
| 238 |
+
# Envelope
|
| 239 |
+
if is_atom_graph:
|
| 240 |
+
smooth_weight = torch.index_select(smooth_weight, 0, directed2undirected)
|
| 241 |
+
smooth_weight = self.learnable_envelope(smooth_weight)
|
| 242 |
+
# Fusion feature
|
| 243 |
+
refine_fusion_feat = torch.cat([edge_feat_0, target_node_feat, source_node_feat], dim=1)
|
| 244 |
+
else:
|
| 245 |
+
base_envelope = self.learnable_envelope(smooth_weight)
|
| 246 |
+
base_weights_i = torch.index_select(base_envelope, 0, graph['source_index'])
|
| 247 |
+
base_weights_j = torch.index_select(base_envelope, 0, graph['target_index'])
|
| 248 |
+
smooth_weight = base_weights_i * base_weights_j
|
| 249 |
+
# Fusion feature
|
| 250 |
+
three_body_atom_feat = torch.index_select(atom_feat, 0, graph['atom_list'])
|
| 251 |
+
refine_fusion_feat = torch.cat([edge_feat_0, three_body_atom_feat, target_node_feat, source_node_feat], dim=1)
|
| 252 |
+
|
| 253 |
+
# Nonlinear
|
| 254 |
+
refine_fusion_feat_nonlinear = self.edge_nonlinear_update(refine_fusion_feat)
|
| 255 |
+
refine_fusion_feat_smooth = refine_fusion_feat_nonlinear * smooth_weight
|
| 256 |
+
|
| 257 |
+
refine_node_feas = aggregate(refine_fusion_feat_smooth,
|
| 258 |
+
graph['target_index'],
|
| 259 |
+
graph['target_bincount'],
|
| 260 |
+
average=False,
|
| 261 |
+
num_segment=len(node_feat))
|
| 262 |
+
|
| 263 |
+
input2edgeFFN = (
|
| 264 |
+
refine_fusion_feat_smooth
|
| 265 |
+
if is_atom_graph and self.use_smoothed_for_delta_edge
|
| 266 |
+
else refine_fusion_feat_nonlinear
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
delta_node_feat = self.node_FFN(refine_node_feas)
|
| 270 |
+
delta_edge_feat = self.edge_FFN(input2edgeFFN)
|
| 271 |
+
|
| 272 |
+
if is_atom_graph:
|
| 273 |
+
delta_edge_feat = aggregate(data=delta_edge_feat, segment=directed2undirected, bin_count=None, average=True, num_segment=None) # [2*edge, dim] -> [edge, dim]
|
| 274 |
+
|
| 275 |
+
update_node_feat = delta_node_feat + self.node_res_weight * node_feat
|
| 276 |
+
update_edge_feat = delta_edge_feat + self.edge_res_weight * edge_feat
|
| 277 |
+
|
| 278 |
+
return update_node_feat, update_edge_feat
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
class Interaction_Block(nn.Module):
|
| 282 |
+
"""
|
| 283 |
+
Interaction Block for MatRIS that processes both atom graphs and line graphs.
|
| 284 |
+
|
| 285 |
+
This block performs attention-based message passing and refinement on two hierarchical graph structures:
|
| 286 |
+
1. Atom graph: Nodes represent atoms, edges represent bonds
|
| 287 |
+
2. Line graph: Nodes represent bonds, edges represent three-body interactions (angles)
|
| 288 |
+
|
| 289 |
+
Attributes:
|
| 290 |
+
attn_block_atom_graph (Graph_Attention_Layer): Attention layer for atom graph
|
| 291 |
+
attn_block_line_graph (Graph_Attention_Layer): Attention layer for line graph
|
| 292 |
+
refine_block_atom_graph (Refinement): Refinement layer for atom graph
|
| 293 |
+
refine_block_line_graph (Refinement): Refinement layer for line graph
|
| 294 |
+
"""
|
| 295 |
+
|
| 296 |
+
def __init__(self,
|
| 297 |
+
node_feat_dim: int = 128,
|
| 298 |
+
edge_feat_dim: int = 128,
|
| 299 |
+
three_body_feat_dim: int = 128,
|
| 300 |
+
num_radial: int = 7,
|
| 301 |
+
num_angular: int = 7,
|
| 302 |
+
dropout: float = 0.0,
|
| 303 |
+
use_bias: bool = False,
|
| 304 |
+
use_smoothed_for_delta_edge: bool = False,
|
| 305 |
+
mlp_type: str = "GateMLP",
|
| 306 |
+
norm_type: str = "layer",
|
| 307 |
+
activation_type: str = "silu",
|
| 308 |
+
):
|
| 309 |
+
"""
|
| 310 |
+
Initialize the Interaction Block.
|
| 311 |
+
|
| 312 |
+
Args:
|
| 313 |
+
node_feat_dim (int): Dimension of node features (atom features)
|
| 314 |
+
edge_feat_dim (int): Dimension of edge features (bond features)
|
| 315 |
+
three_body_feat_dim (int): Dimension of three-body features (angle features)
|
| 316 |
+
mlp_type (str): Type of MLP to use in the layers
|
| 317 |
+
norm_type (str): Type of normalization to apply
|
| 318 |
+
activation_type (str): Type of activation function to use
|
| 319 |
+
"""
|
| 320 |
+
super().__init__()
|
| 321 |
+
|
| 322 |
+
self.attn_block_atom_graph = Graph_Attention_Layer(
|
| 323 |
+
node_feat_dim=node_feat_dim,
|
| 324 |
+
edge_feat_dim=edge_feat_dim,
|
| 325 |
+
hidden_dim=node_feat_dim,
|
| 326 |
+
use_bias=use_bias,
|
| 327 |
+
mlp_type=mlp_type,
|
| 328 |
+
norm_type=norm_type,
|
| 329 |
+
activation_type=activation_type,
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
self.attn_block_line_graph = Graph_Attention_Layer(
|
| 333 |
+
node_feat_dim=edge_feat_dim,
|
| 334 |
+
edge_feat_dim=three_body_feat_dim,
|
| 335 |
+
hidden_dim=edge_feat_dim,
|
| 336 |
+
use_bias=use_bias,
|
| 337 |
+
mlp_type=mlp_type,
|
| 338 |
+
norm_type=norm_type,
|
| 339 |
+
activation_type=activation_type,
|
| 340 |
+
use_fp16=False,
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
self.refine_block_atom_graph = Refinement(
|
| 344 |
+
node_feat_dim=node_feat_dim,
|
| 345 |
+
edge_feat_dim=edge_feat_dim,
|
| 346 |
+
hidden_dim=node_feat_dim,
|
| 347 |
+
num_basis=num_radial,
|
| 348 |
+
dropout=dropout,
|
| 349 |
+
activation_type=activation_type,
|
| 350 |
+
norm_type=norm_type,
|
| 351 |
+
use_bias=use_bias,
|
| 352 |
+
mlp_type=mlp_type,
|
| 353 |
+
graph_type="atom graph",
|
| 354 |
+
use_smoothed_for_delta_edge=use_smoothed_for_delta_edge,
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
self.refine_block_line_graph = Refinement(
|
| 358 |
+
node_feat_dim=edge_feat_dim,
|
| 359 |
+
edge_feat_dim=three_body_feat_dim,
|
| 360 |
+
hidden_dim=edge_feat_dim,
|
| 361 |
+
num_basis=num_angular,
|
| 362 |
+
dropout=dropout,
|
| 363 |
+
activation_type=activation_type,
|
| 364 |
+
norm_type=norm_type,
|
| 365 |
+
use_bias=use_bias,
|
| 366 |
+
mlp_type=mlp_type,
|
| 367 |
+
graph_type="line graph",
|
| 368 |
+
atom_feat_dim=node_feat_dim,
|
| 369 |
+
use_fp16=False,
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
def forward(
|
| 373 |
+
self,
|
| 374 |
+
batch_graph: Dict,
|
| 375 |
+
node_feat: Tensor,
|
| 376 |
+
edge_feat: Tensor,
|
| 377 |
+
threebody_feat: Tensor | None,
|
| 378 |
+
smooth_weight: Tensor,
|
| 379 |
+
) -> Tuple[Tensor, Tensor, Tensor]:
|
| 380 |
+
"""Forward pass of the Interaction Block.
|
| 381 |
+
|
| 382 |
+
Args:
|
| 383 |
+
batch_graph: Graph object containing:
|
| 384 |
+
- atom_graph_dict: Atom graph structure
|
| 385 |
+
- line_graph_dict: Bond graph (line graph) structure
|
| 386 |
+
- directed2undirected: Mapping from directed to undirected edges
|
| 387 |
+
- bond_bases_bg: Smooth weights for bond graph
|
| 388 |
+
- bond_bases_ag: Smooth weights for atom graph
|
| 389 |
+
node_feat (Tensor): Node features [num_atoms, node_feat_dim]
|
| 390 |
+
edge_feat (Tensor): Edge features [num_bonds, edge_feat_dim]
|
| 391 |
+
threebody_feat (Tensor): Three-body features [num_angles, three_body_feat_dim] or None
|
| 392 |
+
bincount_atom_graph (Dict): Bincount information for atom graph
|
| 393 |
+
bincount_line_graph (Dict): Bincount information for line graph
|
| 394 |
+
"""
|
| 395 |
+
# Initialize variables to handle both cases (with and without threebody features)
|
| 396 |
+
attn_edge_feat = edge_feat
|
| 397 |
+
attn_threebody_feat = threebody_feat
|
| 398 |
+
update_edge_feat = edge_feat
|
| 399 |
+
update_threebody_feat = threebody_feat
|
| 400 |
+
use_checkpoint = (
|
| 401 |
+
isinstance(threebody_feat, torch.Tensor)
|
| 402 |
+
and threebody_feat.shape[0] > THRESHOLD_VALUE
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
# Process line graph (bond graph) with attention if threebody features exist
|
| 406 |
+
if threebody_feat is not None:
|
| 407 |
+
attn_edge_feat, attn_threebody_feat = self.wrapper_attn_layer(
|
| 408 |
+
attn_layer=self.attn_block_line_graph,
|
| 409 |
+
node_feat=edge_feat,
|
| 410 |
+
edge_feat=threebody_feat,
|
| 411 |
+
graph=batch_graph['line_graph_dict'],
|
| 412 |
+
use_checkpoint=use_checkpoint,
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
# Process atom graph with attention
|
| 416 |
+
attn_node_feat, attn_edge_feat = self.wrapper_attn_layer(
|
| 417 |
+
attn_layer=self.attn_block_atom_graph,
|
| 418 |
+
node_feat=node_feat,
|
| 419 |
+
edge_feat=attn_edge_feat,
|
| 420 |
+
graph=batch_graph['atom_graph_dict'],
|
| 421 |
+
directed2undirected=batch_graph['directed2undirected'],
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
# Refine line graph features if threebody features exist
|
| 425 |
+
if threebody_feat is not None:
|
| 426 |
+
update_edge_feat, update_threebody_feat = self.wrapper_refine_layer(
|
| 427 |
+
refine_layer=self.refine_block_line_graph,
|
| 428 |
+
node_feat=attn_edge_feat,
|
| 429 |
+
edge_feat=attn_threebody_feat,
|
| 430 |
+
smooth_weight=smooth_weight['line graph'],
|
| 431 |
+
graph=batch_graph['line_graph_dict'],
|
| 432 |
+
atom_feat=attn_node_feat,
|
| 433 |
+
use_checkpoint=use_checkpoint,
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
# Refine atom graph features
|
| 437 |
+
update_node_feat, update_edge_feat = self.wrapper_refine_layer(
|
| 438 |
+
refine_layer=self.refine_block_atom_graph,
|
| 439 |
+
node_feat=attn_node_feat,
|
| 440 |
+
edge_feat=update_edge_feat,
|
| 441 |
+
smooth_weight=smooth_weight['atom graph'],
|
| 442 |
+
graph=batch_graph['atom_graph_dict'],
|
| 443 |
+
directed2undirected=batch_graph['directed2undirected'],
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
return update_node_feat, update_edge_feat, update_threebody_feat
|
| 447 |
+
|
| 448 |
+
def wrapper_attn_layer(self,
|
| 449 |
+
attn_layer: nn.Module,
|
| 450 |
+
node_feat: Tensor,
|
| 451 |
+
edge_feat: Tensor,
|
| 452 |
+
graph: Dict,
|
| 453 |
+
directed2undirected: Tensor = None,
|
| 454 |
+
use_checkpoint: bool = False,
|
| 455 |
+
):
|
| 456 |
+
if use_checkpoint:
|
| 457 |
+
attn_node_feat, attn_edge_feat = checkpoint(
|
| 458 |
+
attn_layer,
|
| 459 |
+
node_feat,
|
| 460 |
+
edge_feat,
|
| 461 |
+
graph,
|
| 462 |
+
directed2undirected,
|
| 463 |
+
use_reentrant=False,
|
| 464 |
+
)
|
| 465 |
+
else:
|
| 466 |
+
attn_node_feat, attn_edge_feat = attn_layer(
|
| 467 |
+
node_feat=node_feat,
|
| 468 |
+
edge_feat=edge_feat,
|
| 469 |
+
graph=graph,
|
| 470 |
+
directed2undirected=directed2undirected,
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
return attn_node_feat, attn_edge_feat
|
| 474 |
+
|
| 475 |
+
def wrapper_refine_layer(self,
|
| 476 |
+
refine_layer: nn.Module,
|
| 477 |
+
node_feat: Tensor,
|
| 478 |
+
edge_feat: Tensor,
|
| 479 |
+
smooth_weight: Tensor,
|
| 480 |
+
graph: Dict,
|
| 481 |
+
directed2undirected: Tensor = None,
|
| 482 |
+
atom_feat: Tensor = None,
|
| 483 |
+
use_checkpoint: bool = False,
|
| 484 |
+
):
|
| 485 |
+
if use_checkpoint:
|
| 486 |
+
update_node_feat, update_edge_feat = checkpoint(
|
| 487 |
+
refine_layer,
|
| 488 |
+
node_feat,
|
| 489 |
+
edge_feat,
|
| 490 |
+
smooth_weight,
|
| 491 |
+
graph,
|
| 492 |
+
directed2undirected,
|
| 493 |
+
atom_feat,
|
| 494 |
+
use_reentrant=False,
|
| 495 |
+
)
|
| 496 |
+
else:
|
| 497 |
+
update_node_feat, update_edge_feat = refine_layer(
|
| 498 |
+
node_feat=node_feat,
|
| 499 |
+
edge_feat=edge_feat,
|
| 500 |
+
smooth_weight=smooth_weight,
|
| 501 |
+
graph=graph,
|
| 502 |
+
directed2undirected=directed2undirected,
|
| 503 |
+
atom_feat=atom_feat,
|
| 504 |
+
)
|
| 505 |
+
return update_node_feat, update_edge_feat
|
| 506 |
+
|
| 507 |
+
|
models/matris/matris/model/model.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Literal, Union, Sequence
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch import Tensor, nn
|
| 5 |
+
import os
|
| 6 |
+
from collections.abc import Sequence
|
| 7 |
+
|
| 8 |
+
from ..graph import RadiusGraph, GraphConverter, datatype
|
| 9 |
+
from .reference_energy import AtomRef
|
| 10 |
+
from .processgraph import process_graphs
|
| 11 |
+
from .feature_embed import (
|
| 12 |
+
ThreebodyFourierExpansion,
|
| 13 |
+
AtomTypeEmbedding,
|
| 14 |
+
EdgeBasisEmbedding,
|
| 15 |
+
ThreebodyEmbedding
|
| 16 |
+
)
|
| 17 |
+
from .functions import (
|
| 18 |
+
MLP,
|
| 19 |
+
GatedMLP,
|
| 20 |
+
get_normalization
|
| 21 |
+
)
|
| 22 |
+
from .interaction_block import Interaction_Block
|
| 23 |
+
from .readout import (
|
| 24 |
+
EnergyHead,
|
| 25 |
+
MagmomHead,
|
| 26 |
+
ForceStressHead,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class MatRIS(nn.Module):
|
| 31 |
+
""" Init MatRIS Potential """
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
num_layers: int = 6, # NOTE orig,debug = 6,2
|
| 36 |
+
node_feat_dim: int = 128, # NOTE orig,debug = 128,32
|
| 37 |
+
edge_feat_dim: int = 128, # NOTE orig,debug = 128,3
|
| 38 |
+
three_body_feat_dim: int = 128, # NOTE orig,debug = 128,32
|
| 39 |
+
mlp_hidden_dims: Union[int, Sequence[int]] = (128, 128),
|
| 40 |
+
dropout: float = 0.0,
|
| 41 |
+
use_bias: bool = False,
|
| 42 |
+
distance_expansion: str = "Bessel",
|
| 43 |
+
three_body_expansion: str = "SH",
|
| 44 |
+
num_radial: int = 7,
|
| 45 |
+
num_angular: int = 7,
|
| 46 |
+
max_l: int = 4,
|
| 47 |
+
max_n: int = 4,
|
| 48 |
+
envelope_exponent: int = 8,
|
| 49 |
+
graph_conv_mlp: str = "GateMLP",
|
| 50 |
+
activation_type: str = "silu",
|
| 51 |
+
norm_type: str = "rms",
|
| 52 |
+
pairwise_cutoff: float = 6,
|
| 53 |
+
three_body_cutoff: float = 4,
|
| 54 |
+
use_smoothed_for_delta_edge: bool = False,
|
| 55 |
+
learnable_basis: bool = True,
|
| 56 |
+
is_intensive: bool = True,
|
| 57 |
+
is_conservation: bool = True,
|
| 58 |
+
reference_energy: str | None = None,
|
| 59 |
+
):
|
| 60 |
+
"""
|
| 61 |
+
Args:
|
| 62 |
+
num_layers (int): message passing layers.
|
| 63 |
+
node_feat_dim (int): atom feature embedding dim.
|
| 64 |
+
edge_feat_dim (int): edge(pairwise) feature embedding dim.
|
| 65 |
+
three_body_feat_dim (int): angle(three body) feature embedding dim.
|
| 66 |
+
mlp_hidden_dims (List or int): hidden dims of MLP.
|
| 67 |
+
Can be 'int' or 'list'.
|
| 68 |
+
dropout (float): dropout rate in MLP.
|
| 69 |
+
use_bias (bool): whether use bias in Interaction block.
|
| 70 |
+
distance_expansion (str): The function of pairwise basis.
|
| 71 |
+
Can be "Bessel" or "Gaussian".
|
| 72 |
+
three_body_expansion (str): The function of three body basis.
|
| 73 |
+
Can be "Fourier(fourier)" or "Spherical Harmonics(sh)".
|
| 74 |
+
num_radial (int): number of radial basis used in Bessel and Gaussian basis.
|
| 75 |
+
num_angular (int): number of three_body basis used in Fourier basis.
|
| 76 |
+
max_l (int): Maximum l value for Spherical Harmonics basis (SH).
|
| 77 |
+
max_n (int): Maximum n value for Spherical Harmonics basis (SH).
|
| 78 |
+
envelope_exponent (int): exponent of 'PolynomialEnvelope'.
|
| 79 |
+
graph_conv_mlp (str): The type of MLP in mp layers.
|
| 80 |
+
Can be "MLP", "GatedMLP" and "MoE".
|
| 81 |
+
See fucntion.py for more informations.
|
| 82 |
+
activation_type (str): activation function.
|
| 83 |
+
Can be "SiLU(silu)", "Sigmoid(sigmoid)", "ReLU(relu)"...
|
| 84 |
+
See fucntion.py for more informations.
|
| 85 |
+
norm_type (str): normalization function used in MLP.
|
| 86 |
+
Can be "LayerNorm(layer)", "BatchNorm(batch)", "RMSNorm(rms)"...
|
| 87 |
+
See fucntion.py for more informations.
|
| 88 |
+
pairwise_cutoff (float): The cutoff of Atom graph.
|
| 89 |
+
three_body_cutoff (float): The cutoff of Line graph.
|
| 90 |
+
use_smoothed_for_delta_edge (bool): Whether to use the smoothed features for edge feature update.
|
| 91 |
+
learnable_basis (bool): Whether the basis functions are learnable.
|
| 92 |
+
is_intensive (bool): whether the model outputs energy per atom (True) or total energy (False).
|
| 93 |
+
is_conservation (bool): whether use conservate force and stress.
|
| 94 |
+
reference_energy (str): refernece energy of 'str'(eg. MPtrj, OMat..) dataset(Caculated by linear regression).
|
| 95 |
+
more details can be found at reference_energy.py.
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
super().__init__()
|
| 99 |
+
# model configs
|
| 100 |
+
self.config = { k: v for k, v in locals().items() if k not in ["self", "__class__"] }
|
| 101 |
+
|
| 102 |
+
self.is_intensive = is_intensive
|
| 103 |
+
|
| 104 |
+
self.reference_energy = None
|
| 105 |
+
if reference_energy is not None:
|
| 106 |
+
self.reference_energy = AtomRef(
|
| 107 |
+
reference_energy=reference_energy,
|
| 108 |
+
is_intensive=is_intensive
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
# Define Graph Converter
|
| 112 |
+
self.graph_converter = GraphConverter(
|
| 113 |
+
atom_graph_cutoff=pairwise_cutoff,
|
| 114 |
+
line_graph_cutoff=three_body_cutoff,
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
# ====== embedding layers ========
|
| 118 |
+
self.atom_embedding = AtomTypeEmbedding(atom_feat_dim=node_feat_dim)
|
| 119 |
+
self.edge_embedding = EdgeBasisEmbedding(
|
| 120 |
+
pairwise_cutoff=pairwise_cutoff,
|
| 121 |
+
three_body_cutoff=three_body_cutoff,
|
| 122 |
+
num_radial=num_radial,
|
| 123 |
+
edge_feat_dim=edge_feat_dim,
|
| 124 |
+
envelope_exponent=envelope_exponent,
|
| 125 |
+
learnable=learnable_basis,
|
| 126 |
+
distance_expansion=distance_expansion,
|
| 127 |
+
)
|
| 128 |
+
self.three_body_embedding = ThreebodyEmbedding(
|
| 129 |
+
num_angular = num_angular, # Fourier
|
| 130 |
+
max_n=max_n, max_l=max_l, cutoff=pairwise_cutoff, # Spherical Harmonics
|
| 131 |
+
three_body_feat_dim = three_body_feat_dim,
|
| 132 |
+
three_body_expansion = three_body_expansion,
|
| 133 |
+
learnable = learnable_basis
|
| 134 |
+
)
|
| 135 |
+
# ====== Interaction layers ========
|
| 136 |
+
interaction_block = [
|
| 137 |
+
Interaction_Block(
|
| 138 |
+
node_feat_dim=node_feat_dim,
|
| 139 |
+
edge_feat_dim=edge_feat_dim,
|
| 140 |
+
three_body_feat_dim=three_body_feat_dim,
|
| 141 |
+
num_radial=num_radial,
|
| 142 |
+
num_angular=num_angular,
|
| 143 |
+
dropout=dropout,
|
| 144 |
+
use_bias=use_bias,
|
| 145 |
+
use_smoothed_for_delta_edge=use_smoothed_for_delta_edge,
|
| 146 |
+
mlp_type=graph_conv_mlp,
|
| 147 |
+
norm_type=norm_type,
|
| 148 |
+
activation_type=activation_type,
|
| 149 |
+
)
|
| 150 |
+
for _ in range(num_layers)
|
| 151 |
+
]
|
| 152 |
+
self.interaction_block = nn.ModuleList(interaction_block)
|
| 153 |
+
|
| 154 |
+
# ====== Readout layers ========
|
| 155 |
+
self.readout_norm = get_normalization(norm_type, dim=node_feat_dim)
|
| 156 |
+
|
| 157 |
+
self.energy_head = EnergyHead(
|
| 158 |
+
feat_dim = node_feat_dim,
|
| 159 |
+
hidden_dim = mlp_hidden_dims,
|
| 160 |
+
output_dim = 1,
|
| 161 |
+
mlp_type = "mlp",
|
| 162 |
+
activation_type = activation_type,
|
| 163 |
+
)
|
| 164 |
+
self.magmom_head = MagmomHead(
|
| 165 |
+
feat_dim = node_feat_dim,
|
| 166 |
+
hidden_dim = 2 * node_feat_dim,
|
| 167 |
+
output_dim = 1,
|
| 168 |
+
mlp_type = "mlp",
|
| 169 |
+
activation_type = activation_type,
|
| 170 |
+
)
|
| 171 |
+
self.force_stress_head = ForceStressHead(
|
| 172 |
+
is_conservation = is_conservation,
|
| 173 |
+
feat_dim = edge_feat_dim, # is_conservation == False
|
| 174 |
+
hidden_dim = mlp_hidden_dims, # is_conservation == False
|
| 175 |
+
output_dim = 3, # is_conservation == False
|
| 176 |
+
mlp_type = "mlp", # is_conservation == False
|
| 177 |
+
activation_type = activation_type, # is_conservation == False
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
if not torch.distributed.is_initialized() or torch.distributed.get_rank() == 0:
|
| 181 |
+
print(f"MatRIS initialized with {self.get_params()} parameters")
|
| 182 |
+
|
| 183 |
+
def forward(
|
| 184 |
+
self,
|
| 185 |
+
graphs: Sequence[RadiusGraph],
|
| 186 |
+
task: str = "ef",
|
| 187 |
+
is_training: bool = False,
|
| 188 |
+
) -> dict[str, Tensor]:
|
| 189 |
+
"""
|
| 190 |
+
Args:
|
| 191 |
+
graphs (List): a list of RadiusGraph.
|
| 192 |
+
task (str): the prediction task. Can be 'e', 'em', 'ef', 'efs', 'efsm'.
|
| 193 |
+
"""
|
| 194 |
+
prediction = {}
|
| 195 |
+
# ======== Graph processing ========
|
| 196 |
+
batch_graph = process_graphs(graphs, compute_stress="s" in task)
|
| 197 |
+
|
| 198 |
+
# ======== Feature embedding ========
|
| 199 |
+
node_feat = self.atom_embedding( batch_graph['atomic_numbers'] - 1 ) # atom type feature init (use 0 for 'H')
|
| 200 |
+
edge_feat, smooth_weight = self.edge_embedding(graphs=batch_graph) # pairwise feature init
|
| 201 |
+
threebody_feat = None
|
| 202 |
+
if len(batch_graph['line_graph_dict']['line_graph']) != 0:
|
| 203 |
+
threebody_feat = self.three_body_embedding(graphs=batch_graph) # three body feature init
|
| 204 |
+
|
| 205 |
+
# ======== Interaction Block =======
|
| 206 |
+
for mp_layer in self.interaction_block:
|
| 207 |
+
node_feat, edge_feat, threebody_feat = mp_layer(
|
| 208 |
+
batch_graph=batch_graph,
|
| 209 |
+
node_feat=node_feat,
|
| 210 |
+
edge_feat=edge_feat,
|
| 211 |
+
threebody_feat=threebody_feat,
|
| 212 |
+
smooth_weight=smooth_weight,
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
# ======== Readout Block =======
|
| 216 |
+
node_feat = self.readout_norm(node_feat)
|
| 217 |
+
|
| 218 |
+
total_energy = self.energy_head(batch_graph = batch_graph, node_feat = node_feat)
|
| 219 |
+
|
| 220 |
+
force_stress_dict = self.force_stress_head(
|
| 221 |
+
batch_graph = batch_graph,
|
| 222 |
+
compute_force="f" in task,
|
| 223 |
+
compute_stress="s" in task,
|
| 224 |
+
total_energy = total_energy,
|
| 225 |
+
node_feat = node_feat,
|
| 226 |
+
edge_feat = edge_feat,
|
| 227 |
+
is_training = is_training)
|
| 228 |
+
prediction.update(force_stress_dict)
|
| 229 |
+
|
| 230 |
+
if "m" in task:
|
| 231 |
+
magmom = self.magmom_head(batch_graph = batch_graph, node_feat = node_feat)
|
| 232 |
+
prediction["m"] = magmom
|
| 233 |
+
|
| 234 |
+
atoms_per_graph_tensor = torch.tensor(batch_graph['atoms_per_graph'],
|
| 235 |
+
dtype=torch.int32,
|
| 236 |
+
device=total_energy.device)
|
| 237 |
+
if self.is_intensive:
|
| 238 |
+
energy_per_atom = total_energy / atoms_per_graph_tensor
|
| 239 |
+
prediction["e"] = energy_per_atom
|
| 240 |
+
else:
|
| 241 |
+
prediction["e"] = total_energy
|
| 242 |
+
|
| 243 |
+
prediction["atoms_per_graph"] = atoms_per_graph_tensor
|
| 244 |
+
|
| 245 |
+
ref_energy = (
|
| 246 |
+
0 if self.reference_energy is None else self.reference_energy(graphs)
|
| 247 |
+
)
|
| 248 |
+
prediction["e"] += ref_energy
|
| 249 |
+
prediction["ref_energy"] = ref_energy
|
| 250 |
+
return prediction
|
| 251 |
+
|
| 252 |
+
def get_params(self) -> int:
|
| 253 |
+
"""Return the number of parameters in the model."""
|
| 254 |
+
return sum(p.numel() for p in self.parameters())
|
| 255 |
+
|
| 256 |
+
@classmethod
|
| 257 |
+
def from_dict(cls, dct: dict):
|
| 258 |
+
matris = MatRIS(**dct["config"])
|
| 259 |
+
matris.load_state_dict(dct["state_dict"])
|
| 260 |
+
return matris
|
| 261 |
+
|
| 262 |
+
@classmethod
|
| 263 |
+
def load(
|
| 264 |
+
cls,
|
| 265 |
+
model_name: str = "matris_10m_oam",
|
| 266 |
+
device: str | None = None,
|
| 267 |
+
cache_dir: str | None = None,
|
| 268 |
+
):
|
| 269 |
+
"""Load pretrained model."""
|
| 270 |
+
model_name = model_name.lower()
|
| 271 |
+
supported_models = ["matris_10m_oam", "matris_10m_mp"]
|
| 272 |
+
if model_name not in supported_models:
|
| 273 |
+
raise ValueError(f"Unsupported model_name: {model_name}. Supported models are: {supported_models}")
|
| 274 |
+
|
| 275 |
+
if device is None:
|
| 276 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
if cache_dir is None:
|
| 280 |
+
cache_dir = os.environ.get("MATRIS_CACHE_DIR", "~/.cache/matris")
|
| 281 |
+
|
| 282 |
+
cache_dir = os.path.expanduser(cache_dir)
|
| 283 |
+
os.makedirs(cache_dir, exist_ok=True)
|
| 284 |
+
|
| 285 |
+
checkpoint_files = {
|
| 286 |
+
"matris_10m_omat": "MatRIS_10M_OMAT.pth.tar",
|
| 287 |
+
"matris_10m_oam": "MatRIS_10M_OAM.pth.tar",
|
| 288 |
+
"matris_10m_mp": "MatRIS_10M_MP.pth.tar",
|
| 289 |
+
"matris_6m_mp": "MatRIS_6M_MP.pth.tar",
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
DOWNLOAD_URLS = {
|
| 293 |
+
"matris_10m_omat": "", # TODO
|
| 294 |
+
"matris_10m_oam": "https://figshare.com/ndownloader/files/59142728",
|
| 295 |
+
"matris_10m_mp": "https://figshare.com/ndownloader/files/59143058",
|
| 296 |
+
"matris_6m_mp": "", # TODO
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
ckpt_filename = checkpoint_files[model_name]
|
| 300 |
+
ckpt_path = os.path.join(cache_dir, ckpt_filename)
|
| 301 |
+
|
| 302 |
+
if not os.path.exists(ckpt_path):
|
| 303 |
+
url = DOWNLOAD_URLS.get(model_name)
|
| 304 |
+
if not url:
|
| 305 |
+
raise ValueError(f"No download URL provided for model: {model_name}")
|
| 306 |
+
|
| 307 |
+
print(f"Checkpoint not found, downloading to {ckpt_path} ...")
|
| 308 |
+
torch.hub.download_url_to_file(url, ckpt_path)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
ckpt_state = torch.load(
|
| 312 |
+
ckpt_path,
|
| 313 |
+
map_location=torch.device("cpu"),
|
| 314 |
+
weights_only=False
|
| 315 |
+
)
|
| 316 |
+
model = MatRIS.from_dict(ckpt_state)
|
| 317 |
+
|
| 318 |
+
model = model.to(device)
|
| 319 |
+
print(f"Loading {model_name} successfully, running on {device}.")
|
| 320 |
+
|
| 321 |
+
return model
|
models/matris/matris/model/op/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .fused_silu_op import fused_silu
|
| 2 |
+
from .fuse_sigmoid_op import fused_sigmoid
|
| 3 |
+
from .fuse_basis_func import fusion_env_val
|
| 4 |
+
|
| 5 |
+
__all__ = [
|
| 6 |
+
"fused_silu",
|
| 7 |
+
"fused_sigmoid",
|
| 8 |
+
"fusion_env_val",
|
| 9 |
+
]
|
models/matris/matris/model/op/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (345 Bytes). View file
|
|
|
models/matris/matris/model/op/__pycache__/fuse_basis_func.cpython-310.pyc
ADDED
|
Binary file (3.95 kB). View file
|
|
|
models/matris/matris/model/op/__pycache__/fuse_sigmoid_op.cpython-310.pyc
ADDED
|
Binary file (2.32 kB). View file
|
|
|
models/matris/matris/model/op/__pycache__/fused_silu_op.cpython-310.pyc
ADDED
|
Binary file (3 kB). View file
|
|
|
models/matris/matris/model/op/fuse_basis_func.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.autograd import Function
|
| 3 |
+
from torch.profiler import profile, ProfilerActivity,record_function
|
| 4 |
+
|
| 5 |
+
fusion_envelop_string = """
|
| 6 |
+
template <typename T> T envelop_fwd_kernel(T r_scaled, T a, T b, T c, T p)
|
| 7 |
+
{
|
| 8 |
+
return ( 1 + a * pow(r_scaled, p) + b * pow(r_scaled, (p + 1)) + c * pow(r_scaled, (p + 2)) );
|
| 9 |
+
}
|
| 10 |
+
"""
|
| 11 |
+
#return ( 1 + a * r_scaled ** p + b * r_scaled ** (p + 1) + c * r_scaled ** (p + 2) );
|
| 12 |
+
envelop_fwd_func = torch.cuda.jiterator._create_jit_fn(fusion_envelop_string)
|
| 13 |
+
|
| 14 |
+
fusion_envelop_bwd_string = """
|
| 15 |
+
template <typename T> T envelop_bwd_kernel(T grad_output, T r_scaled, T a, T b, T c, T p)
|
| 16 |
+
{
|
| 17 |
+
T grad_r_scaled = (
|
| 18 |
+
a * p * pow(r_scaled, (p - 1))
|
| 19 |
+
+ b * (p + 1) * pow(r_scaled, p)
|
| 20 |
+
+ c * (p + 2) * pow(r_scaled, (p + 1))
|
| 21 |
+
);
|
| 22 |
+
return grad_output * grad_r_scaled;
|
| 23 |
+
}
|
| 24 |
+
"""
|
| 25 |
+
envelop_bwd_func = torch.cuda.jiterator._create_jit_fn(fusion_envelop_bwd_string)
|
| 26 |
+
|
| 27 |
+
fusion_envelop_gradbwd_string = """
|
| 28 |
+
template <typename T> T envelop_bwd_kernel(T d_grad_r_scaled, T grad_output, T r_scaled, T a, T b, T c, T p, T &grad_grad_output, T &grad_r_scaled)
|
| 29 |
+
{
|
| 30 |
+
grad_grad_output = (
|
| 31 |
+
a * p * pow(r_scaled, (p - 1))
|
| 32 |
+
+ b * (p + 1) * pow(r_scaled, p)
|
| 33 |
+
+ c * (p + 2) * pow(r_scaled, (p + 1))
|
| 34 |
+
);
|
| 35 |
+
grad_grad_output = d_grad_r_scaled * grad_grad_output;
|
| 36 |
+
|
| 37 |
+
T grad_r_scaled_term = (
|
| 38 |
+
a * p * (p - 1) * pow(r_scaled, (p - 2))
|
| 39 |
+
+ b * (p + 1) * p * pow(r_scaled, (p - 1))
|
| 40 |
+
+ c * (p + 2) * (p + 1) * pow(r_scaled, p)
|
| 41 |
+
);
|
| 42 |
+
grad_r_scaled = d_grad_r_scaled * grad_output * grad_r_scaled_term;
|
| 43 |
+
}
|
| 44 |
+
"""
|
| 45 |
+
envelop_gradbwd_func = torch.cuda.jiterator._create_multi_output_jit_fn(fusion_envelop_gradbwd_string, num_outputs=2)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class envelop_bwd(Function):
|
| 49 |
+
@staticmethod
|
| 50 |
+
def forward(ctx, grad_output: torch.Tensor, r_scaled: torch.Tensor, a: torch.Tensor, b: torch.Tensor, c: torch.Tensor, p: torch.Tensor):
|
| 51 |
+
"""
|
| 52 |
+
# Compute grad_r_scaled
|
| 53 |
+
grad_r_scaled_part = (
|
| 54 |
+
a * p * r_scaled ** (p - 1)
|
| 55 |
+
+ b * (p + 1) * r_scaled ** p
|
| 56 |
+
+ c * (p + 2) * r_scaled ** (p + 1)
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
grad_r_scaled = grad_output * grad_r_scaled_part
|
| 60 |
+
"""
|
| 61 |
+
grad_r_scaled = envelop_bwd_func(grad_output, r_scaled, a, b, c, p)
|
| 62 |
+
# Save for backward
|
| 63 |
+
ctx.save_for_backward(grad_output, r_scaled)
|
| 64 |
+
ctx.a = a
|
| 65 |
+
ctx.b = b
|
| 66 |
+
ctx.c = c
|
| 67 |
+
ctx.p = p
|
| 68 |
+
|
| 69 |
+
return grad_r_scaled
|
| 70 |
+
|
| 71 |
+
@staticmethod
|
| 72 |
+
def backward(ctx, d_grad_r_scaled):
|
| 73 |
+
grad_output, r_scaled = ctx.saved_tensors
|
| 74 |
+
a = ctx.a
|
| 75 |
+
b = ctx.b
|
| 76 |
+
c = ctx.c
|
| 77 |
+
p = ctx.p
|
| 78 |
+
"""
|
| 79 |
+
# Compute gradient w.r.t grad_output
|
| 80 |
+
grad_grad_output = (
|
| 81 |
+
a * p * r_scaled ** (p - 1)
|
| 82 |
+
+ b * (p + 1) * r_scaled ** p
|
| 83 |
+
+ c * (p + 2) * r_scaled ** (p + 1)
|
| 84 |
+
)
|
| 85 |
+
grad_grad_output = d_grad_r_scaled * grad_grad_output # chain rule
|
| 86 |
+
|
| 87 |
+
# Compute gradient w.r.t r_scaled
|
| 88 |
+
grad_r_scaled_term = (
|
| 89 |
+
a * p * (p - 1) * r_scaled ** (p - 2)
|
| 90 |
+
+ b * (p + 1) * p * r_scaled ** (p - 1)
|
| 91 |
+
+ c * (p + 2) * (p + 1) * r_scaled ** p
|
| 92 |
+
)
|
| 93 |
+
grad_r_scaled = d_grad_r_scaled * grad_output * grad_r_scaled_term # chain rule
|
| 94 |
+
"""
|
| 95 |
+
grad_grad_output, grad_r_scaled = envelop_gradbwd_func(d_grad_r_scaled, grad_output, r_scaled, a, b, c, p)
|
| 96 |
+
# Return gradients in the order of forward's inputs
|
| 97 |
+
return grad_grad_output, grad_r_scaled, None, None, None, None
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class envelop_fwd(Function):
|
| 101 |
+
@staticmethod
|
| 102 |
+
def forward(ctx, r_scaled: torch.Tensor, a: torch.Tensor, b:torch.Tensor, c: torch.Tensor, p:torch.Tensor):
|
| 103 |
+
output = envelop_fwd_func(r_scaled, a, b, c, p)
|
| 104 |
+
ctx.save_for_backward(r_scaled)
|
| 105 |
+
ctx.a = a
|
| 106 |
+
ctx.b = b
|
| 107 |
+
ctx.c = c
|
| 108 |
+
ctx.p = p
|
| 109 |
+
return output
|
| 110 |
+
|
| 111 |
+
@staticmethod
|
| 112 |
+
def backward(ctx, grad_output):
|
| 113 |
+
(r_scaled,) = ctx.saved_tensors
|
| 114 |
+
a = ctx.a
|
| 115 |
+
b = ctx.b
|
| 116 |
+
c = ctx.c
|
| 117 |
+
p = ctx.p
|
| 118 |
+
|
| 119 |
+
grad_r_scaled = envelop_bwd.apply(grad_output, r_scaled, a, b, c, p)
|
| 120 |
+
|
| 121 |
+
return grad_r_scaled, None, None, None, None
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def fusion_env_val(r_scaled:torch.Tensor, a:torch.Tensor, b:torch.Tensor, c:torch.Tensor, p:torch.Tensor):
|
| 125 |
+
if r_scaled.device.type == "cuda":
|
| 126 |
+
return envelop_fwd.apply(r_scaled, a, b, c, p)
|
| 127 |
+
else:
|
| 128 |
+
return ( 1 + a * r_scaled ** p + b * r_scaled ** (p + 1) + c * r_scaled ** (p + 2) )
|
| 129 |
+
|
models/matris/matris/model/op/fuse_sigmoid_op.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.autograd import Function
|
| 3 |
+
from torch.profiler import profile, ProfilerActivity,record_function
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
sigmoid_bwd_string = """
|
| 7 |
+
template <typename T> T sigmoid_bwd_kernel(T dgrad, T output)
|
| 8 |
+
{
|
| 9 |
+
return dgrad * output * (1 - output);
|
| 10 |
+
}
|
| 11 |
+
"""
|
| 12 |
+
sigmoid_bwd_func = torch.cuda.jiterator._create_jit_fn(sigmoid_bwd_string)
|
| 13 |
+
|
| 14 |
+
sigmoid_gradbwd_string = """
|
| 15 |
+
template <typename T> T sigmoid_grad_bwd_kernel(T grad_output, T dgrad, T output, T &grad_dgrad, T &grad_output_val)
|
| 16 |
+
{
|
| 17 |
+
grad_dgrad = grad_output * output * (1 - output);
|
| 18 |
+
grad_output_val = grad_output * dgrad * (1 - 2 * output);
|
| 19 |
+
}
|
| 20 |
+
"""
|
| 21 |
+
sigmoid_gradbwd_func = torch.cuda.jiterator._create_multi_output_jit_fn(sigmoid_gradbwd_string, num_outputs=2)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class sigmoid_bwd(Function):
|
| 25 |
+
@staticmethod
|
| 26 |
+
def forward(ctx, dgrad, output):
|
| 27 |
+
#grad_feas = dgrad * output * (1 - output)
|
| 28 |
+
with record_function("sigmoid bwd"):
|
| 29 |
+
grad_feas = sigmoid_bwd_func(dgrad, output)
|
| 30 |
+
ctx.save_for_backward(dgrad, output)
|
| 31 |
+
#ctx.save_for_backward()
|
| 32 |
+
return grad_feas
|
| 33 |
+
|
| 34 |
+
@staticmethod
|
| 35 |
+
def backward(ctx, grad_output):
|
| 36 |
+
dgrad, output = ctx.saved_tensors
|
| 37 |
+
"""
|
| 38 |
+
grad_dgrad = grad_output * output * (1 - output)
|
| 39 |
+
grad_output_val = grad_output * dgrad * (1 - 2 * output)
|
| 40 |
+
"""
|
| 41 |
+
with record_function("sigmoid grad bwd"):
|
| 42 |
+
grad_dgrad, grad_output_val = sigmoid_gradbwd_func(grad_output, dgrad, output)
|
| 43 |
+
return grad_dgrad, grad_output_val
|
| 44 |
+
|
| 45 |
+
class sigmoid_fwd(Function):
|
| 46 |
+
@staticmethod
|
| 47 |
+
def forward(ctx, feas):
|
| 48 |
+
output = torch.nn.functional.sigmoid(feas)
|
| 49 |
+
ctx.save_for_backward(output)
|
| 50 |
+
return output
|
| 51 |
+
|
| 52 |
+
@staticmethod
|
| 53 |
+
def backward(ctx, dgrad):
|
| 54 |
+
output, = ctx.saved_tensors
|
| 55 |
+
grad_feas = sigmoid_bwd.apply(dgrad, output)
|
| 56 |
+
return grad_feas
|
| 57 |
+
|
| 58 |
+
def fused_sigmoid(input_feas):
|
| 59 |
+
if input_feas.device.type == "cuda":
|
| 60 |
+
return sigmoid_fwd.apply(input_feas)
|
| 61 |
+
else:
|
| 62 |
+
return torch.nn.functional.sigmoid(input_feas)
|
| 63 |
+
|
models/matris/matris/model/op/fused_silu_op.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.autograd import Function
|
| 3 |
+
from torch.profiler import profile, ProfilerActivity,record_function
|
| 4 |
+
|
| 5 |
+
silu_bwd_string = """
|
| 6 |
+
template <typename T> T silu_bwd_kernel(T dgrad, T x)
|
| 7 |
+
{
|
| 8 |
+
T sigmoid_x = 1/(1 + exp(-x));
|
| 9 |
+
|
| 10 |
+
T grad_input = dgrad * (1 + x*(1-sigmoid_x)) * sigmoid_x;
|
| 11 |
+
|
| 12 |
+
return grad_input;
|
| 13 |
+
}
|
| 14 |
+
"""
|
| 15 |
+
silu_bwd_func = torch.cuda.jiterator._create_jit_fn(silu_bwd_string)
|
| 16 |
+
|
| 17 |
+
silu_gradbwd_string = """
|
| 18 |
+
template <typename T> T silu_grad_bwd_kernel(T grad_grad_input, T grad_output, T x, T &grad_grad_output, T &grad_x)
|
| 19 |
+
{
|
| 20 |
+
T sigmoid_x = 1/(1 + exp(-x));
|
| 21 |
+
T term = sigmoid_x * (1 + x * (1 - sigmoid_x));
|
| 22 |
+
grad_grad_output = grad_grad_input * term;
|
| 23 |
+
|
| 24 |
+
T sigmoid_derivative = sigmoid_x * (1 - sigmoid_x);
|
| 25 |
+
T d_term_dx = sigmoid_derivative * (2 + x * (1 - 2 * sigmoid_x));
|
| 26 |
+
grad_x = grad_grad_input * grad_output * d_term_dx;
|
| 27 |
+
|
| 28 |
+
}
|
| 29 |
+
"""
|
| 30 |
+
silu_gradbwd_func = torch.cuda.jiterator._create_multi_output_jit_fn(silu_gradbwd_string, num_outputs=2)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class fusion_silu_bwd(Function):
|
| 34 |
+
@staticmethod
|
| 35 |
+
def forward(ctx, grad_output, x):
|
| 36 |
+
ctx.save_for_backward(x, grad_output)
|
| 37 |
+
"""
|
| 38 |
+
sigmoid_x = torch.sigmoid(x)
|
| 39 |
+
grad_input = grad_output * (1 + x * (1 - sigmoid_x)) * sigmoid_x
|
| 40 |
+
"""
|
| 41 |
+
with record_function("silu bwd"):
|
| 42 |
+
grad_input = silu_bwd_func(grad_output, x)
|
| 43 |
+
return grad_input
|
| 44 |
+
|
| 45 |
+
@staticmethod
|
| 46 |
+
def backward(ctx, grad_grad_input):
|
| 47 |
+
"""
|
| 48 |
+
sigmoid_x = torch.sigmoid(x)
|
| 49 |
+
term = sigmoid_x * (1 + x * (1 - sigmoid_x))
|
| 50 |
+
grad_grad_output = grad_grad_input * term
|
| 51 |
+
sigmoid_derivative = sigmoid_x * (1 - sigmoid_x)
|
| 52 |
+
d_term_dx = sigmoid_derivative * (2 + x * (1 - 2 * sigmoid_x))
|
| 53 |
+
|
| 54 |
+
grad_x = grad_grad_input * grad_output * d_term_dx
|
| 55 |
+
"""
|
| 56 |
+
x, grad_output = ctx.saved_tensors
|
| 57 |
+
|
| 58 |
+
with record_function("silu grad bwd"):
|
| 59 |
+
grad_grad_output, grad_x = silu_gradbwd_func(grad_grad_input, grad_output, x)
|
| 60 |
+
return grad_grad_output, grad_x
|
| 61 |
+
|
| 62 |
+
class fusion_silu_fwd(Function):
|
| 63 |
+
@staticmethod
|
| 64 |
+
def forward(ctx, x):
|
| 65 |
+
|
| 66 |
+
out = torch.nn.functional.silu(x)
|
| 67 |
+
ctx.save_for_backward(x)
|
| 68 |
+
return out
|
| 69 |
+
|
| 70 |
+
@staticmethod
|
| 71 |
+
def backward(ctx, grad_output):
|
| 72 |
+
x, = ctx.saved_tensors
|
| 73 |
+
grad_input = fusion_silu_bwd.apply(grad_output, x)
|
| 74 |
+
return grad_input
|
| 75 |
+
|
| 76 |
+
def fused_silu(input_feas):
|
| 77 |
+
if input_feas.device.type == "cuda":
|
| 78 |
+
return fusion_silu_fwd.apply(input_feas)
|
| 79 |
+
else:
|
| 80 |
+
return torch.nn.functional.silu(input_feas)
|
| 81 |
+
|
| 82 |
+
# out = fused_silu(input)
|
models/matris/matris/model/op/src/Opdefine.h
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#ifndef OP_SRC_OPDECLARE_H_
|
| 2 |
+
#define OP_SRC_OPDECLARE_H_
|
| 3 |
+
|
| 4 |
+
#include <torch/extension.h>
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
torch::Tensor fused_SiLU_Bwd(const torch::Tensor &dgrad, const torch::Tensor &input);
|
| 8 |
+
|
| 9 |
+
std::vector<torch::Tensor> fused_SiLU_Grad_Bwd(const torch::Tensor &grad_grad_input, const torch::Tensor &grad_output,
|
| 10 |
+
const torch::Tensor &input);
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
#endif // OP_SRC_OPDECLARE_H_
|