Upload folder using huggingface_hub
Browse files- scripts/compute_cavd_channel_dimensionality.py +305 -0
- scripts/compute_electrochemical_windows.py +416 -0
- scripts/compute_jarvis_hull_energy.py +218 -0
- scripts/compute_mechanical_properties.py +229 -0
- scripts/compute_oxidation_states.py +159 -0
- scripts/compute_sse_candidate_score.py +250 -0
- scripts/convert_parquet_typed.py +85 -0
- scripts/enrich_garnet_family.py +327 -0
- scripts/extract_commercial_safe_edition.py +164 -0
- scripts/generate_audit_reports.py +4 -4
- scripts/generate_conductivity_splits.py +240 -0
- scripts/integrate_experimental_data.py +440 -0
- scripts/merge_obelix.py +309 -0
- scripts/run_phase1_pipeline.py +116 -0
- scripts/setup_mlip_infrastructure.py +202 -0
scripts/compute_cavd_channel_dimensionality.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CAVD-like channel dimensionality analysis for Li/Na ion migration pathways.
|
| 2 |
+
|
| 3 |
+
Computes percolation channel dimensionality (0D/1D/2D/3D) from crystal structures
|
| 4 |
+
using Voronoi-based void network analysis. Fills the ssb_screening block with:
|
| 5 |
+
- cavd_channel_dimensionality: "0D" | "1D" | "2D" | "3D" | "none"
|
| 6 |
+
- mobile_ion_site_volume: Volume of mobile ion Voronoi cell (A^3)
|
| 7 |
+
- mobile_ion_connectivity: Coordination of mobile ion sites
|
| 8 |
+
|
| 9 |
+
This is a geometric pre-filter — materials with 0D channels or no percolation
|
| 10 |
+
network are extremely unlikely to be good ionic conductors.
|
| 11 |
+
|
| 12 |
+
Usage:
|
| 13 |
+
python scripts/compute_cavd_channel_dimensionality.py # subset: mobile-ion only
|
| 14 |
+
python scripts/compute_cavd_channel_dimensionality.py --subset battery # battery edition only
|
| 15 |
+
python scripts/compute_cavd_channel_dimensionality.py --limit 1000 # first 1000 entries
|
| 16 |
+
python scripts/compute_cavd_channel_dimensionality.py --dry-run # stats only, no save
|
| 17 |
+
|
| 18 |
+
References:
|
| 19 |
+
- Zhang et al. Scientific Data (2020) — SPSE platform CAVD methodology
|
| 20 |
+
- pymatgen VoronoiConnectivity for void space analysis
|
| 21 |
+
"""
|
| 22 |
+
import json, os, sys, time, argparse, warnings
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
import numpy as np
|
| 25 |
+
warnings.filterwarnings("ignore")
|
| 26 |
+
|
| 27 |
+
WIDTH = 60
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def parse_structure(structure_json_str):
|
| 31 |
+
from pymatgen.core import Structure
|
| 32 |
+
import json as _json
|
| 33 |
+
d = _json.loads(structure_json_str)
|
| 34 |
+
return Structure.from_dict(d)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def compute_voronoi_connectivity(structure, mobile_element="Li", cutoff=10.0):
|
| 38 |
+
"""Analyze mobile ion connectivity via Voronoi tessellation.
|
| 39 |
+
|
| 40 |
+
Returns dict with:
|
| 41 |
+
- dimensionality : estimated channel dimensionality
|
| 42 |
+
- coordination : number of neighboring mobile ion sites
|
| 43 |
+
- site_volume : average Voronoi volume of mobile ion sites
|
| 44 |
+
- percolation : bool, whether 3D percolation is likely
|
| 45 |
+
"""
|
| 46 |
+
from pymatgen.analysis.structure_analyzer import VoronoiConnectivity
|
| 47 |
+
|
| 48 |
+
mobile_sites = [s for s in structure if s.specie.symbol == mobile_element]
|
| 49 |
+
if len(mobile_sites) < 2:
|
| 50 |
+
return {"dimensionality": "none", "coordination": 0, "site_volume": 0.0, "percolation": False}
|
| 51 |
+
|
| 52 |
+
try:
|
| 53 |
+
vc = VoronoiConnectivity(structure, mobile_element, cutoff=cutoff)
|
| 54 |
+
connectivity = vc.get_connectivity()
|
| 55 |
+
except Exception:
|
| 56 |
+
connectivity = {}
|
| 57 |
+
|
| 58 |
+
# Analyze mobile ion sublattice geometry
|
| 59 |
+
frac_coords = np.array([s.frac_coords for s in mobile_sites])
|
| 60 |
+
|
| 61 |
+
n_mobile = len(mobile_sites)
|
| 62 |
+
if n_mobile < 2:
|
| 63 |
+
return {"dimensionality": "none", "coordination": 0, "site_volume": 0.0, "percolation": False}
|
| 64 |
+
|
| 65 |
+
lattice = structure.lattice
|
| 66 |
+
|
| 67 |
+
from scipy.spatial import KDTree
|
| 68 |
+
|
| 69 |
+
all_coords = []
|
| 70 |
+
for i, site in enumerate(mobile_sites):
|
| 71 |
+
for image in [(0,0,0), (1,0,0), (-1,0,0), (0,1,0), (0,-1,0),
|
| 72 |
+
(0,0,1), (0,0,-1), (1,1,0), (1,-1,0), (-1,1,0), (-1,-1,0),
|
| 73 |
+
(1,0,1), (1,0,-1), (-1,0,1), (-1,0,-1), (0,1,1), (0,1,-1),
|
| 74 |
+
(0,-1,1), (0,-1,-1)]:
|
| 75 |
+
shift = np.array(image, dtype=float)
|
| 76 |
+
cart = lattice.get_cartesian_coords(site.frac_coords + shift)
|
| 77 |
+
all_coords.append((i, cart, image))
|
| 78 |
+
|
| 79 |
+
coords = np.array([c[1] for c in all_coords])
|
| 80 |
+
indices = np.array([c[0] for c in all_coords])
|
| 81 |
+
|
| 82 |
+
if len(coords) == 0:
|
| 83 |
+
return {"dimensionality": "none", "coordination": 0, "site_volume": 0.0, "percolation": False}
|
| 84 |
+
|
| 85 |
+
tree = KDTree(coords)
|
| 86 |
+
|
| 87 |
+
coordination_counts = []
|
| 88 |
+
|
| 89 |
+
for i in range(n_mobile):
|
| 90 |
+
point = lattice.get_cartesian_coords(mobile_sites[i].frac_coords)
|
| 91 |
+
nn = tree.query_ball_point(point, r=5.0)
|
| 92 |
+
nn_indices = indices[nn]
|
| 93 |
+
nn_self = sum(1 for j in nn_indices if j == i)
|
| 94 |
+
nn_count = len(nn_indices) - nn_self
|
| 95 |
+
coordination_counts.append(nn_count)
|
| 96 |
+
|
| 97 |
+
mean_coordination = np.mean(coordination_counts) if coordination_counts else 0
|
| 98 |
+
|
| 99 |
+
if mean_coordination >= 4:
|
| 100 |
+
dimensionality = "3D"
|
| 101 |
+
percolation = True
|
| 102 |
+
elif mean_coordination >= 2:
|
| 103 |
+
dimensionality = "2D"
|
| 104 |
+
percolation = True
|
| 105 |
+
elif mean_coordination >= 1:
|
| 106 |
+
dimensionality = "1D"
|
| 107 |
+
percolation = False
|
| 108 |
+
else:
|
| 109 |
+
dimensionality = "0D"
|
| 110 |
+
percolation = False
|
| 111 |
+
|
| 112 |
+
try:
|
| 113 |
+
site_volumes = []
|
| 114 |
+
for site in mobile_sites:
|
| 115 |
+
from scipy.spatial import Voronoi as ScipyVoronoi
|
| 116 |
+
|
| 117 |
+
neighbors = structure.get_neighbors(site, r=cutoff)
|
| 118 |
+
if len(neighbors) < 4:
|
| 119 |
+
site_volumes.append(0.0)
|
| 120 |
+
continue
|
| 121 |
+
|
| 122 |
+
points = [site.coords]
|
| 123 |
+
for n_site, dist, _, _ in neighbors:
|
| 124 |
+
points.append(n_site.coords)
|
| 125 |
+
|
| 126 |
+
if len(points) < 4:
|
| 127 |
+
site_volumes.append(0.0)
|
| 128 |
+
continue
|
| 129 |
+
|
| 130 |
+
try:
|
| 131 |
+
vor = ScipyVoronoi(np.array(points))
|
| 132 |
+
region_idx = vor.point_region[0]
|
| 133 |
+
region = vor.regions[region_idx]
|
| 134 |
+
if -1 not in region and len(region) > 0:
|
| 135 |
+
verts = vor.vertices[region]
|
| 136 |
+
from scipy.spatial import ConvexHull
|
| 137 |
+
hull = ConvexHull(verts)
|
| 138 |
+
site_volumes.append(hull.volume)
|
| 139 |
+
else:
|
| 140 |
+
site_volumes.append(0.0)
|
| 141 |
+
except Exception:
|
| 142 |
+
site_volumes.append(0.0)
|
| 143 |
+
|
| 144 |
+
avg_site_volume = np.mean(site_volumes) if site_volumes else 0.0
|
| 145 |
+
except Exception:
|
| 146 |
+
avg_site_volume = 0.0
|
| 147 |
+
|
| 148 |
+
return {
|
| 149 |
+
"dimensionality": dimensionality,
|
| 150 |
+
"coordination": round(float(mean_coordination), 2),
|
| 151 |
+
"site_volume": round(float(avg_site_volume), 4),
|
| 152 |
+
"percolation": percolation
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def main():
|
| 157 |
+
parser = argparse.ArgumentParser(description="CAVD channel dimensionality analysis")
|
| 158 |
+
parser.add_argument("--subset", choices=["battery", "electrolyte", "gold", "full"], default="full")
|
| 159 |
+
parser.add_argument("--limit", type=int, default=None)
|
| 160 |
+
parser.add_argument("--dry-run", action="store_true", help="Don't save results")
|
| 161 |
+
parser.add_argument("--output", type=str, default=None, help="Custom output path")
|
| 162 |
+
args = parser.parse_args()
|
| 163 |
+
|
| 164 |
+
if args.limit and not args.dry_run and args.output is None:
|
| 165 |
+
print("ERROR: Refusing to save limited runs. Use --dry-run or --output.")
|
| 166 |
+
sys.exit(1)
|
| 167 |
+
|
| 168 |
+
BASE_DIR = Path(__file__).resolve().parent.parent
|
| 169 |
+
DATASET_PATH = BASE_DIR / "dataset"
|
| 170 |
+
|
| 171 |
+
print("=" * WIDTH)
|
| 172 |
+
print(" CAVD CHANNEL DIMENSIONALITY ANALYSIS")
|
| 173 |
+
print(" Geometric pre-filter for Li/Na ion migration pathways")
|
| 174 |
+
print("=" * WIDTH)
|
| 175 |
+
|
| 176 |
+
print("\nLoading entries from typed Parquet...")
|
| 177 |
+
t0 = time.time()
|
| 178 |
+
sys.path.insert(0, str(BASE_DIR))
|
| 179 |
+
from dataset.dataset_store import DatasetStore
|
| 180 |
+
store = DatasetStore.open()
|
| 181 |
+
print(f" {store.num_entries:,} total entries ({time.time()-t0:.1f}s)")
|
| 182 |
+
|
| 183 |
+
mobile_elements = {"Li", "Na"}
|
| 184 |
+
|
| 185 |
+
# Load subset IDs if filtering
|
| 186 |
+
subset_ids = None
|
| 187 |
+
if args.subset == "battery":
|
| 188 |
+
with open(DATASET_PATH / "battery_candidate_subset_v1.json") as f:
|
| 189 |
+
battery = json.load(f)
|
| 190 |
+
subset_ids = {e.get("source_id", "") + e.get("source", "") for e in battery}
|
| 191 |
+
elif args.subset == "electrolyte":
|
| 192 |
+
with open(DATASET_PATH / "solid_electrolyte_candidate_subset_v1.json") as f:
|
| 193 |
+
electrolyte = json.load(f)
|
| 194 |
+
subset_ids = {e.get("source_id", "") + e.get("source", "") for e in electrolyte}
|
| 195 |
+
|
| 196 |
+
# Collect target entries
|
| 197 |
+
skipped_no_mobile = 0
|
| 198 |
+
skipped_no_structure = 0
|
| 199 |
+
target_ids = []
|
| 200 |
+
|
| 201 |
+
for e in store.scan(columns=["source_id", "source", "mobile_ion", "structure_json"]):
|
| 202 |
+
mobile_ion = e.get("mobile_ion", "")
|
| 203 |
+
if mobile_ion not in mobile_elements:
|
| 204 |
+
skipped_no_mobile += 1
|
| 205 |
+
continue
|
| 206 |
+
if not e.get("structure_json"):
|
| 207 |
+
skipped_no_structure += 1
|
| 208 |
+
continue
|
| 209 |
+
key = e.get("source_id", "") + e.get("source", "")
|
| 210 |
+
if subset_ids is not None and key not in subset_ids:
|
| 211 |
+
continue
|
| 212 |
+
target_ids.append(e["source_id"])
|
| 213 |
+
|
| 214 |
+
print(f" Li/Na mobile ion entries with structures: {len(target_ids):,}")
|
| 215 |
+
print(f" Skipped (no mobile ion): {skipped_no_mobile:,}")
|
| 216 |
+
print(f" Skipped (no structure): {skipped_no_structure:,}")
|
| 217 |
+
|
| 218 |
+
if args.subset == "gold":
|
| 219 |
+
gold_ids = set()
|
| 220 |
+
for e in store.scan(columns=["source_id", "tier"]):
|
| 221 |
+
if e.get("tier") == "gold":
|
| 222 |
+
gold_ids.add(e["source_id"])
|
| 223 |
+
target_ids = [sid for sid in target_ids if sid in gold_ids]
|
| 224 |
+
print(f" Subset (gold): {len(target_ids):,} entries")
|
| 225 |
+
elif args.subset != "full":
|
| 226 |
+
print(f" Subset ({args.subset}): {len(target_ids):,} entries")
|
| 227 |
+
|
| 228 |
+
if args.limit:
|
| 229 |
+
target_ids = target_ids[:args.limit]
|
| 230 |
+
print(f" Limited to {args.limit} entries")
|
| 231 |
+
|
| 232 |
+
if not target_ids:
|
| 233 |
+
print("No entries to process.")
|
| 234 |
+
return
|
| 235 |
+
|
| 236 |
+
# Process entries
|
| 237 |
+
print(f"\n{'─' * WIDTH}")
|
| 238 |
+
print(" Computing channel dimensionality...")
|
| 239 |
+
print(f"{'─' * WIDTH}")
|
| 240 |
+
|
| 241 |
+
processed = 0
|
| 242 |
+
errors = 0
|
| 243 |
+
dims = {"3D": 0, "2D": 0, "1D": 0, "0D": 0, "none": 0, "error": 0}
|
| 244 |
+
t_start = time.time()
|
| 245 |
+
|
| 246 |
+
for idx, source_id in enumerate(target_ids):
|
| 247 |
+
entry = store.lookup(source_id)
|
| 248 |
+
if entry is None:
|
| 249 |
+
continue
|
| 250 |
+
|
| 251 |
+
mobile_ion = entry.get("mobile_ion", "Li")
|
| 252 |
+
|
| 253 |
+
try:
|
| 254 |
+
structure = parse_structure(entry["structure_json"])
|
| 255 |
+
result = compute_voronoi_connectivity(structure, mobile_element=mobile_ion)
|
| 256 |
+
|
| 257 |
+
store.update_field(source_id, "ssb_screening",
|
| 258 |
+
result["dimensionality"], nested_path="cavd_channel_dimensionality")
|
| 259 |
+
store.update_field(source_id, "ssb_screening",
|
| 260 |
+
result["coordination"], nested_path="mobile_ion_connectivity")
|
| 261 |
+
store.update_field(source_id, "ssb_screening",
|
| 262 |
+
result["site_volume"], nested_path="mobile_ion_site_volume")
|
| 263 |
+
|
| 264 |
+
dims[result["dimensionality"]] += 1
|
| 265 |
+
processed += 1
|
| 266 |
+
|
| 267 |
+
except Exception as exc:
|
| 268 |
+
errors += 1
|
| 269 |
+
if errors <= 5:
|
| 270 |
+
print(f" Error [{source_id}]: {str(exc)[:80]}")
|
| 271 |
+
store.update_field(source_id, "ssb_screening",
|
| 272 |
+
"error", nested_path="cavd_channel_dimensionality")
|
| 273 |
+
|
| 274 |
+
if (idx + 1) % 500 == 0:
|
| 275 |
+
elapsed = time.time() - t_start
|
| 276 |
+
rate = (idx + 1) / elapsed if elapsed > 0 else 0
|
| 277 |
+
pct = (idx + 1) / len(target_ids) * 100
|
| 278 |
+
print(f" {idx+1}/{len(target_ids)} ({pct:.0f}%) | "
|
| 279 |
+
f"3D:{dims['3D']} 2D:{dims['2D']} 1D:{dims['1D']} 0D:{dims['0D']} "
|
| 280 |
+
f"| {rate:.1f} ent/s")
|
| 281 |
+
|
| 282 |
+
elapsed = time.time() - t_start
|
| 283 |
+
print(f"\n{'─' * WIDTH}")
|
| 284 |
+
print(f" Complete: {processed} processed, {errors} errors")
|
| 285 |
+
print(f" Time: {elapsed/60:.1f} min ({processed/elapsed:.1f} ent/s)")
|
| 286 |
+
print(f"\n Channel dimensionality distribution:")
|
| 287 |
+
for dim, count in sorted(dims.items()):
|
| 288 |
+
if count > 0:
|
| 289 |
+
print(f" {dim}: {count:,} ({count/max(processed,1)*100:.1f}%)")
|
| 290 |
+
|
| 291 |
+
if args.dry_run:
|
| 292 |
+
print("\n (dry-run — not saved)")
|
| 293 |
+
store._dirty = False
|
| 294 |
+
store.close()
|
| 295 |
+
else:
|
| 296 |
+
print(f"\n Writing to Parquet...")
|
| 297 |
+
t_write = time.time()
|
| 298 |
+
store.checkpoint()
|
| 299 |
+
print(f" Done ({time.time()-t_write:.1f}s)")
|
| 300 |
+
|
| 301 |
+
print("=" * WIDTH)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
if __name__ == "__main__":
|
| 305 |
+
main()
|
scripts/compute_electrochemical_windows.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compute electrochemical stability windows from dataset's own formation energies.
|
| 2 |
+
|
| 3 |
+
Self-contained — no MP API needed. Uses pymatgen PhaseDiagram built from the
|
| 4 |
+
266k entries already in the dataset. Fills the ssb_screening block with:
|
| 5 |
+
- stability_window_low_V
|
| 6 |
+
- stability_window_high_V
|
| 7 |
+
- interfacial_reaction_energy_vs_Li_eV_atom
|
| 8 |
+
- passivating_interphase
|
| 9 |
+
|
| 10 |
+
Algorithm per entry:
|
| 11 |
+
1. Group entries by chemical system (sorted element tuple).
|
| 12 |
+
2. Build a local convex hull from *all* entries in that system.
|
| 13 |
+
3. Compute decomposition energy (E_above_hull) from the local hull.
|
| 14 |
+
4. For the grand potential window against Li/Na:
|
| 15 |
+
a. Add the reservoir element to the chemical system.
|
| 16 |
+
b. Build a GrandPotentialPhaseDiagram at varying μ.
|
| 17 |
+
c. Find the voltage range where E_hull(μ) ≈ 0.
|
| 18 |
+
|
| 19 |
+
Usage:
|
| 20 |
+
python scripts/compute_electrochemical_windows.py # full dataset
|
| 21 |
+
python scripts/compute_electrochemical_windows.py --subset battery # battery only
|
| 22 |
+
python scripts/compute_electrochemical_windows.py --subset gold # gold tier only
|
| 23 |
+
python scripts/compute_electrochemical_windows.py --limit 1000 # first 1000 entries
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
import json, os, sys, time, argparse, itertools, warnings, math
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
from collections import defaultdict
|
| 29 |
+
warnings.filterwarnings("ignore")
|
| 30 |
+
|
| 31 |
+
WIDTH = 60
|
| 32 |
+
|
| 33 |
+
def main():
|
| 34 |
+
parser = argparse.ArgumentParser(description="Compute electrochemical stability windows")
|
| 35 |
+
parser.add_argument("--subset", choices=["battery", "electrolyte", "gold", "full"], default="full")
|
| 36 |
+
parser.add_argument("--limit", type=int, default=None)
|
| 37 |
+
parser.add_argument("--min-system-size", type=int, default=3,
|
| 38 |
+
help="Minimum entries in a chemical system to build a hull (default: 3)")
|
| 39 |
+
parser.add_argument("--dry-run", action="store_true", help="Don't save results, just print stats")
|
| 40 |
+
parser.add_argument("--output", type=str, default=None,
|
| 41 |
+
help="Custom output path (default: dataset/entries_final_v3.json)")
|
| 42 |
+
args = parser.parse_args()
|
| 43 |
+
|
| 44 |
+
# SAFETY: refuse to save a limited run back to the dataset
|
| 45 |
+
if args.limit and not args.dry_run and args.output is None:
|
| 46 |
+
print("ERROR: Refusing to save limited runs. Use --dry-run or --output to specify a safe path.")
|
| 47 |
+
print(" python scripts/compute_electrochemical_windows.py --limit 100 --dry-run")
|
| 48 |
+
sys.exit(1)
|
| 49 |
+
|
| 50 |
+
try:
|
| 51 |
+
from pymatgen.analysis.phase_diagram import PhaseDiagram, GrandPotentialPhaseDiagram, PDEntry
|
| 52 |
+
from pymatgen.core import Composition, Element
|
| 53 |
+
except ImportError as e:
|
| 54 |
+
print(f"ERROR: pymatgen not available: {e}")
|
| 55 |
+
print("Install: pip install pymatgen")
|
| 56 |
+
sys.exit(1)
|
| 57 |
+
|
| 58 |
+
BASE_DIR = Path(__file__).resolve().parent.parent
|
| 59 |
+
DATASET_PATH = BASE_DIR / "dataset"
|
| 60 |
+
|
| 61 |
+
print("=" * WIDTH)
|
| 62 |
+
print(" ELECTROCHEMICAL WINDOWS — SELF-CONTAINED")
|
| 63 |
+
print(" Using dataset's own formation energies (no MP API)")
|
| 64 |
+
print("=" * WIDTH)
|
| 65 |
+
|
| 66 |
+
# Load source dataset
|
| 67 |
+
print("\nLoading entries...")
|
| 68 |
+
with open(DATASET_PATH / "entries_final_v3.json") as f:
|
| 69 |
+
all_entries = json.load(f)
|
| 70 |
+
print(f" {len(all_entries):,} total entries")
|
| 71 |
+
|
| 72 |
+
# Select working subset
|
| 73 |
+
if args.subset == "battery":
|
| 74 |
+
with open(DATASET_PATH / "battery_candidate_subset_v1.json") as f:
|
| 75 |
+
entries = json.load(f)
|
| 76 |
+
entries = [e for e in entries if any(el in e.get("elements", []) for el in ["Li", "Na"])]
|
| 77 |
+
elif args.subset == "electrolyte":
|
| 78 |
+
with open(DATASET_PATH / "solid_electrolyte_candidate_subset_v1.json") as f:
|
| 79 |
+
entries = json.load(f)
|
| 80 |
+
entries = [e for e in entries if any(el in e.get("elements", []) for el in ["Li", "Na"])]
|
| 81 |
+
elif args.subset == "gold":
|
| 82 |
+
entries = [e for e in all_entries if e.get("tier") == "gold" and any(el in e.get("elements", []) for el in ["Li", "Na"])]
|
| 83 |
+
else:
|
| 84 |
+
entries = all_entries
|
| 85 |
+
|
| 86 |
+
if args.limit:
|
| 87 |
+
entries = entries[:args.limit]
|
| 88 |
+
print(f" Working subset: {len(entries):,} entries")
|
| 89 |
+
|
| 90 |
+
# Reference energies for terminal (pure element) entries
|
| 91 |
+
# Standard PBE reference energies from pymatgen/MP
|
| 92 |
+
# Solid elements: 0 eV/atom (elemental ground state)
|
| 93 |
+
# Gaseous elements: corrected to match PBE formation energies
|
| 94 |
+
TERMINAL_REF_ENERGIES = {
|
| 95 |
+
"O": -4.935, # O2 gas correction (standard PBE)
|
| 96 |
+
"N": -8.100, # N2 gas correction
|
| 97 |
+
"F": -1.500, # F2 gas correction (approx)
|
| 98 |
+
"Cl": -1.700, # Cl2 gas correction (approx)
|
| 99 |
+
"Br": -0.500, # Br2 liquid correction (approx)
|
| 100 |
+
"H": -3.300, # H2 gas correction
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
def make_terminal_entries(system):
|
| 104 |
+
"""Create PDEntry objects for pure elements in the system."""
|
| 105 |
+
entries = []
|
| 106 |
+
for el_symbol in system:
|
| 107 |
+
el = Element(el_symbol)
|
| 108 |
+
comp = Composition({el: 1})
|
| 109 |
+
ref_energy = TERMINAL_REF_ENERGIES.get(el_symbol, 0.0)
|
| 110 |
+
entries.append(PDEntry(comp, ref_energy, name=f"{el_symbol}(ref)"))
|
| 111 |
+
return entries
|
| 112 |
+
|
| 113 |
+
# Build hulls from ALL entries (full 266k) for maximum coverage
|
| 114 |
+
print("\nBuilding convex hulls from ALL entries (full dataset)...")
|
| 115 |
+
all_systems = defaultdict(list)
|
| 116 |
+
for e in all_entries:
|
| 117 |
+
fe = e.get("formation_energy_per_atom") or e.get("formation_energy")
|
| 118 |
+
if fe is None:
|
| 119 |
+
continue
|
| 120 |
+
system = tuple(sorted(e.get("elements", [])))
|
| 121 |
+
all_systems[system].append((e, fe))
|
| 122 |
+
|
| 123 |
+
hulls = {}
|
| 124 |
+
hull_built = 0
|
| 125 |
+
hull_failed = 0
|
| 126 |
+
for system, entries_in_system in all_systems.items():
|
| 127 |
+
if len(entries_in_system) < args.min_system_size:
|
| 128 |
+
continue
|
| 129 |
+
|
| 130 |
+
# Build compound entries
|
| 131 |
+
compound_entries = []
|
| 132 |
+
for e, fe in entries_in_system:
|
| 133 |
+
try:
|
| 134 |
+
formula = e.get("formula", "")
|
| 135 |
+
comp = Composition(formula)
|
| 136 |
+
total_energy = fe * comp.num_atoms
|
| 137 |
+
compound_entries.append(PDEntry(comp, total_energy))
|
| 138 |
+
except Exception:
|
| 139 |
+
pass
|
| 140 |
+
|
| 141 |
+
if len(compound_entries) < args.min_system_size:
|
| 142 |
+
continue
|
| 143 |
+
|
| 144 |
+
# Add terminal entries (pure elements) — required for PhaseDiagram
|
| 145 |
+
terminal_entries = make_terminal_entries(system)
|
| 146 |
+
all_pd_entries = terminal_entries + compound_entries
|
| 147 |
+
|
| 148 |
+
try:
|
| 149 |
+
hulls[system] = PhaseDiagram(all_pd_entries)
|
| 150 |
+
hull_built += 1
|
| 151 |
+
except Exception as exc:
|
| 152 |
+
hull_failed += 1
|
| 153 |
+
if hull_failed <= 5:
|
| 154 |
+
print(f" Hull failed for {system}: {str(exc)[:80]}")
|
| 155 |
+
|
| 156 |
+
print(f" Built {hull_built:,} hulls, {hull_failed:,} failed ({len(all_systems):,} systems total)")
|
| 157 |
+
|
| 158 |
+
# Now select the working subset for computation
|
| 159 |
+
# Only entries with Li or Na as mobile ion, hull-covered, and with formation energy
|
| 160 |
+
valid = []
|
| 161 |
+
for e in entries:
|
| 162 |
+
elements = e.get("elements", [])
|
| 163 |
+
if not any(el in elements for el in ["Li", "Na"]):
|
| 164 |
+
continue
|
| 165 |
+
fe = e.get("formation_energy_per_atom") or e.get("formation_energy")
|
| 166 |
+
if fe is None:
|
| 167 |
+
continue
|
| 168 |
+
system = tuple(sorted(elements))
|
| 169 |
+
if system in hulls:
|
| 170 |
+
e["_fe"] = fe
|
| 171 |
+
e["_system"] = system
|
| 172 |
+
valid.append(e)
|
| 173 |
+
print(f" Li/Na entries in hull-covered systems: {len(valid):,}")
|
| 174 |
+
|
| 175 |
+
if not valid:
|
| 176 |
+
print("No entries in hull-covered systems. Try reducing --min-system-size.")
|
| 177 |
+
return
|
| 178 |
+
|
| 179 |
+
# Pre-build PhaseDiagrams INCLUDING the mobile element for each system
|
| 180 |
+
# so we don't rebuild for every entry
|
| 181 |
+
print("\nBuilding combined hulls with Li/Na...")
|
| 182 |
+
combined_hulls = {} # (system, mobile_el_str) -> PhaseDiagram
|
| 183 |
+
for system, pd in hulls.items():
|
| 184 |
+
for mobile in ("Li", "Na"):
|
| 185 |
+
if mobile in system:
|
| 186 |
+
# Mobile element is already in the system — use the same Pd
|
| 187 |
+
combined_hulls[(system, mobile)] = pd
|
| 188 |
+
else:
|
| 189 |
+
# Build a new Pd including the mobile element
|
| 190 |
+
extended_system = tuple(sorted(set(system + (mobile,))))
|
| 191 |
+
|
| 192 |
+
# Add existing terminal entries + mobile terminal + compound entries
|
| 193 |
+
mobile_terminal = PDEntry(Composition({mobile: 1}), 0.0, name=f"{mobile}(ref)")
|
| 194 |
+
try:
|
| 195 |
+
grand_pd = PhaseDiagram(list(pd.all_entries) + [mobile_terminal])
|
| 196 |
+
combined_hulls[(system, mobile)] = grand_pd
|
| 197 |
+
except Exception:
|
| 198 |
+
pass
|
| 199 |
+
print(f" Combined hulls built: {len(combined_hulls):,}")
|
| 200 |
+
|
| 201 |
+
LI_METAL_ENERGY = 0.0
|
| 202 |
+
NA_METAL_ENERGY = 0.0
|
| 203 |
+
|
| 204 |
+
def compute_stability_window(pd, entry_pd, mobile_element, combined_pd):
|
| 205 |
+
"""Compute the electrochemical stability window using grand potential scan.
|
| 206 |
+
|
| 207 |
+
pd: PhaseDiagram for the chemical system (without mobile element reservoir)
|
| 208 |
+
entry_pd: PDEntry for the target material
|
| 209 |
+
mobile_element: "Li" or "Na"
|
| 210 |
+
combined_pd: PhaseDiagram including the mobile element as a terminal
|
| 211 |
+
|
| 212 |
+
Returns dict with window_V, decomp_energy, passivating_flag.
|
| 213 |
+
"""
|
| 214 |
+
try:
|
| 215 |
+
# Check formation energy relative to base hull
|
| 216 |
+
decomp = pd.get_decomp_and_e_above_hull(entry_pd)
|
| 217 |
+
if decomp is None:
|
| 218 |
+
return None
|
| 219 |
+
_, e_above_hull = decomp
|
| 220 |
+
if e_above_hull > 0.5:
|
| 221 |
+
return None
|
| 222 |
+
|
| 223 |
+
mobile_el = Element(mobile_element)
|
| 224 |
+
n_mobile = entry_pd.composition.get(mobile_el, 0)
|
| 225 |
+
|
| 226 |
+
# Scan μ from 0V (pure metal) to -5V vs M/M+
|
| 227 |
+
# Compute grand potential of the entry vs competing phases at each μ
|
| 228 |
+
stable_range = [None, None]
|
| 229 |
+
prev_stable = None
|
| 230 |
+
|
| 231 |
+
for mu_V in [x * 0.1 for x in range(0, 51)]:
|
| 232 |
+
mu = -mu_V
|
| 233 |
+
gp_entry = entry_pd.energy - mu * n_mobile
|
| 234 |
+
|
| 235 |
+
# Minimum grand potential among competing phases
|
| 236 |
+
gp_comp = float('inf')
|
| 237 |
+
for other in combined_pd.all_entries:
|
| 238 |
+
if id(other) == id(entry_pd):
|
| 239 |
+
continue
|
| 240 |
+
n_other = other.composition.get(mobile_el, 0) if mobile_el in other.composition.elements else 0
|
| 241 |
+
gp_other = other.energy - mu * n_other
|
| 242 |
+
if gp_other < gp_comp:
|
| 243 |
+
gp_comp = gp_other
|
| 244 |
+
|
| 245 |
+
is_stable = gp_entry <= gp_comp + 1e-4
|
| 246 |
+
|
| 247 |
+
if prev_stable is None:
|
| 248 |
+
prev_stable = is_stable
|
| 249 |
+
elif is_stable != prev_stable:
|
| 250 |
+
mid_V = mu_V - 0.05
|
| 251 |
+
if prev_stable and not is_stable:
|
| 252 |
+
stable_range[1] = mid_V
|
| 253 |
+
elif not prev_stable and is_stable:
|
| 254 |
+
stable_range[0] = mid_V
|
| 255 |
+
prev_stable = is_stable
|
| 256 |
+
|
| 257 |
+
if prev_stable:
|
| 258 |
+
if stable_range[0] is None:
|
| 259 |
+
stable_range[0] = 0.0
|
| 260 |
+
if stable_range[1] is None:
|
| 261 |
+
stable_range[1] = 5.0
|
| 262 |
+
|
| 263 |
+
# Passivating interphase heuristic
|
| 264 |
+
passivating = False
|
| 265 |
+
if stable_range[0] is not None and stable_range[0] > 0.1:
|
| 266 |
+
mu = 0.0
|
| 267 |
+
gp_products = []
|
| 268 |
+
for other in combined_pd.all_entries:
|
| 269 |
+
if id(other) == id(entry_pd):
|
| 270 |
+
continue
|
| 271 |
+
n_other = other.composition.get(mobile_el, 0) if mobile_el in other.composition.elements else 0
|
| 272 |
+
gp = other.energy - mu * n_other
|
| 273 |
+
gp_products.append((gp, other))
|
| 274 |
+
|
| 275 |
+
if gp_products:
|
| 276 |
+
gp_products.sort(key=lambda x: x[0])
|
| 277 |
+
best_decomp = gp_products[0][1]
|
| 278 |
+
solid_elements = [el.symbol for el in best_decomp.composition.elements
|
| 279 |
+
if el.symbol not in ("O2", "N2", "Cl2", "F2", "S")]
|
| 280 |
+
if len(solid_elements) >= 2:
|
| 281 |
+
passivating = True
|
| 282 |
+
|
| 283 |
+
result = {
|
| 284 |
+
"stability_window_low_V": round(stable_range[0], 3) if stable_range[0] is not None else None,
|
| 285 |
+
"stability_window_high_V": round(stable_range[1], 3) if stable_range[1] is not None else None,
|
| 286 |
+
"decomp_energy_eV_per_atom": round(e_above_hull, 4),
|
| 287 |
+
"passivating_interphase": passivating,
|
| 288 |
+
"method": "grand_potential_scan"
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
if stable_range[0] is not None and stable_range[1] is not None:
|
| 292 |
+
result["window_width_V"] = round(stable_range[1] - stable_range[0], 3)
|
| 293 |
+
|
| 294 |
+
return result
|
| 295 |
+
|
| 296 |
+
except Exception as exc:
|
| 297 |
+
return {"error": str(exc)[:100]}
|
| 298 |
+
|
| 299 |
+
# Process entries
|
| 300 |
+
print(f"\n{'─' * WIDTH}")
|
| 301 |
+
print(" Computing stability windows...")
|
| 302 |
+
print(f"{'─' * WIDTH}")
|
| 303 |
+
|
| 304 |
+
processed = 0
|
| 305 |
+
errors = 0
|
| 306 |
+
skipped = 0
|
| 307 |
+
windows_found = 0
|
| 308 |
+
t_start = time.time()
|
| 309 |
+
|
| 310 |
+
for idx, e in enumerate(valid):
|
| 311 |
+
system = e["_system"]
|
| 312 |
+
pd = hulls[system]
|
| 313 |
+
|
| 314 |
+
# Create PDEntry for this specific entry
|
| 315 |
+
try:
|
| 316 |
+
formula = e.get("formula", "")
|
| 317 |
+
fe = e.get("_fe")
|
| 318 |
+
comp = Composition(formula)
|
| 319 |
+
total_energy = fe * comp.num_atoms
|
| 320 |
+
entry_pd = PDEntry(comp, total_energy)
|
| 321 |
+
except Exception:
|
| 322 |
+
errors += 1
|
| 323 |
+
continue
|
| 324 |
+
|
| 325 |
+
# Determine mobile element (preferred: Li > Na)
|
| 326 |
+
elements_set = e.get("elements", [])
|
| 327 |
+
mobile_el = "Li" if "Li" in elements_set else "Na"
|
| 328 |
+
|
| 329 |
+
# Get the combined hull (with mobile element as terminal)
|
| 330 |
+
combined_key = (system, mobile_el)
|
| 331 |
+
combined_pd = combined_hulls.get(combined_key, pd)
|
| 332 |
+
|
| 333 |
+
# Compute window
|
| 334 |
+
result = compute_stability_window(pd, entry_pd, mobile_el, combined_pd)
|
| 335 |
+
|
| 336 |
+
# Fill ssb_screening block
|
| 337 |
+
if "ssb_screening" not in e:
|
| 338 |
+
e["ssb_screening"] = {}
|
| 339 |
+
|
| 340 |
+
if result and "error" not in result:
|
| 341 |
+
e["ssb_screening"]["stability_window_low_V"] = result["stability_window_low_V"]
|
| 342 |
+
e["ssb_screening"]["stability_window_high_V"] = result["stability_window_high_V"]
|
| 343 |
+
e["ssb_screening"]["window_width_V"] = result.get("window_width_V")
|
| 344 |
+
e["ssb_screening"]["interfacial_reaction_energy_vs_Li_eV_atom"] = result["decomp_energy_eV_per_atom"]
|
| 345 |
+
e["ssb_screening"]["passivating_interphase"] = result["passivating_interphase"]
|
| 346 |
+
windows_found += 1
|
| 347 |
+
elif result:
|
| 348 |
+
errors += 1
|
| 349 |
+
|
| 350 |
+
processed += 1
|
| 351 |
+
|
| 352 |
+
if processed % 100 == 0:
|
| 353 |
+
elapsed = time.time() - t_start
|
| 354 |
+
rate = processed / elapsed if elapsed > 0 else 0
|
| 355 |
+
pct = processed / len(valid) * 100
|
| 356 |
+
eta = (len(valid) - processed) / rate if rate > 0 else 0
|
| 357 |
+
print(f" {processed}/{len(valid)} ({pct:.0f}%) "
|
| 358 |
+
f"| {windows_found} windows | {rate:.1f} ent/s | ETA {eta/60:.0f}min")
|
| 359 |
+
|
| 360 |
+
elapsed = time.time() - t_start
|
| 361 |
+
print(f"\n{'─' * WIDTH}")
|
| 362 |
+
print(f" Complete: {processed} processed, {windows_found} windows, {errors} errors, {skipped} skipped")
|
| 363 |
+
print(f" Time: {elapsed/60:.1f} min ({processed/elapsed:.1f} entries/s)")
|
| 364 |
+
|
| 365 |
+
# Determine output path — NEVER overwrite the main dataset when running on a subset
|
| 366 |
+
if args.subset == "battery":
|
| 367 |
+
output_path = DATASET_PATH / "battery_candidate_subset_v1.json"
|
| 368 |
+
save_data = entries
|
| 369 |
+
elif args.subset == "electrolyte":
|
| 370 |
+
output_path = DATASET_PATH / "solid_electrolyte_candidate_subset_v1.json"
|
| 371 |
+
save_data = entries
|
| 372 |
+
elif args.subset == "gold":
|
| 373 |
+
output_path = DATASET_PATH / "gold_subset_v1.json"
|
| 374 |
+
save_data = entries
|
| 375 |
+
else:
|
| 376 |
+
output_path = DATASET_PATH / "entries_final_v3.json"
|
| 377 |
+
save_data = all_entries
|
| 378 |
+
|
| 379 |
+
if args.dry_run:
|
| 380 |
+
print(" (dry-run — not saved)")
|
| 381 |
+
else:
|
| 382 |
+
with open(output_path, "w") as f:
|
| 383 |
+
json.dump(save_data, f)
|
| 384 |
+
print(f" Saved to {output_path}")
|
| 385 |
+
|
| 386 |
+
# Stats
|
| 387 |
+
with_window = 0
|
| 388 |
+
for entry_batch in [all_entries if args.subset == "full" else entries]:
|
| 389 |
+
for entry in entry_batch:
|
| 390 |
+
ss = entry.get("ssb_screening", {})
|
| 391 |
+
if ss.get("stability_window_low_V") is not None:
|
| 392 |
+
with_window += 1
|
| 393 |
+
|
| 394 |
+
print(f"\n Entries with stability windows: {with_window:,}")
|
| 395 |
+
|
| 396 |
+
# Distribution
|
| 397 |
+
windows = []
|
| 398 |
+
for entry_batch in [all_entries if args.subset == "full" else entries]:
|
| 399 |
+
for entry in entry_batch:
|
| 400 |
+
ss = entry.get("ssb_screening", {})
|
| 401 |
+
low = ss.get("stability_window_low_V")
|
| 402 |
+
high = ss.get("stability_window_high_V")
|
| 403 |
+
if low is not None and high is not None:
|
| 404 |
+
windows.append(high - low)
|
| 405 |
+
|
| 406 |
+
if windows:
|
| 407 |
+
print(f" Window width distribution (V):")
|
| 408 |
+
for threshold in [0.5, 1.0, 2.0, 3.0, 4.0, 5.0]:
|
| 409 |
+
count = sum(1 for w in windows if w >= threshold)
|
| 410 |
+
print(f" ≥{threshold:.1f} V: {count:,} ({count/len(windows)*100:.1f}%)")
|
| 411 |
+
|
| 412 |
+
print("=" * WIDTH)
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
if __name__ == "__main__":
|
| 416 |
+
main()
|
scripts/compute_jarvis_hull_energy.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compute energy above hull for JARVIS entries via internal convex hull.
|
| 2 |
+
|
| 3 |
+
JARVIS-DFT entries (25,673) currently have no energy_above_hull values because
|
| 4 |
+
they come from a different DFT methodology (optPBE + TBmBJ). This script builds
|
| 5 |
+
internal convex hulls within the JARVIS subset and computes EaH relative to those.
|
| 6 |
+
|
| 7 |
+
This is an approximate correction — the true hull for JARVIS entries is the
|
| 8 |
+
Materials Project convex hull (PAW-PBE). The internal hull gives a first-pass
|
| 9 |
+
stability estimate until a proper cross-method correction is developed.
|
| 10 |
+
|
| 11 |
+
Usage:
|
| 12 |
+
python scripts/compute_jarvis_hull_energy.py
|
| 13 |
+
python scripts/compute_jarvis_hull_energy.py --dry-run
|
| 14 |
+
python scripts/compute_jarvis_hull_energy.py --limit 5000
|
| 15 |
+
"""
|
| 16 |
+
import json, os, sys, time, argparse, warnings
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from collections import defaultdict
|
| 19 |
+
import numpy as np
|
| 20 |
+
import pyarrow as pa
|
| 21 |
+
warnings.filterwarnings("ignore")
|
| 22 |
+
|
| 23 |
+
WIDTH = 60
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def main():
|
| 27 |
+
parser = argparse.ArgumentParser(description="Compute EaH for JARVIS entries via internal hull")
|
| 28 |
+
parser.add_argument("--dry-run", action="store_true")
|
| 29 |
+
parser.add_argument("--limit", type=int, default=None)
|
| 30 |
+
args = parser.parse_args()
|
| 31 |
+
|
| 32 |
+
BASE_DIR = Path(__file__).resolve().parent.parent
|
| 33 |
+
DATASET_PATH = BASE_DIR / "dataset"
|
| 34 |
+
|
| 35 |
+
print("=" * WIDTH)
|
| 36 |
+
print(" JARVIS ENERGY ABOVE HULL")
|
| 37 |
+
print(" Internal convex hull within JARVIS subset")
|
| 38 |
+
print("=" * WIDTH)
|
| 39 |
+
|
| 40 |
+
print("\nLoading entries from typed Parquet...")
|
| 41 |
+
t0 = time.time()
|
| 42 |
+
sys.path.insert(0, str(BASE_DIR))
|
| 43 |
+
from dataset.dataset_store import DatasetStore
|
| 44 |
+
store = DatasetStore.open()
|
| 45 |
+
print(f" {store.num_entries:,} entries ({time.time()-t0:.1f}s)")
|
| 46 |
+
|
| 47 |
+
# Load all JARVIS entries in one batch (reduced columns)
|
| 48 |
+
print(f"\n Loading JARVIS entries...")
|
| 49 |
+
jarvis_entries = [
|
| 50 |
+
e for e in store.scan(columns=[
|
| 51 |
+
"source_id", "source", "formula", "elements",
|
| 52 |
+
"energy_above_hull", "formation_energy_per_atom",
|
| 53 |
+
])
|
| 54 |
+
if e.get("source") == "jarvis"
|
| 55 |
+
]
|
| 56 |
+
print(f" {len(jarvis_entries):,} JARVIS entries loaded")
|
| 57 |
+
|
| 58 |
+
if args.limit:
|
| 59 |
+
jarvis_entries = jarvis_entries[:args.limit]
|
| 60 |
+
|
| 61 |
+
jarvis_with_eah = sum(1 for e in jarvis_entries if e.get("energy_above_hull") is not None)
|
| 62 |
+
print(f" JARVIS with EaH already: {jarvis_with_eah}")
|
| 63 |
+
|
| 64 |
+
from pymatgen.analysis.phase_diagram import PhaseDiagram, PDEntry
|
| 65 |
+
from pymatgen.core import Composition
|
| 66 |
+
|
| 67 |
+
print(f"\n Building JARVIS internal convex hulls...")
|
| 68 |
+
|
| 69 |
+
systems = defaultdict(list)
|
| 70 |
+
for e in jarvis_entries:
|
| 71 |
+
elements = tuple(sorted(set(e.get("elements", []))))
|
| 72 |
+
fe = e.get("formation_energy_per_atom")
|
| 73 |
+
if fe is None:
|
| 74 |
+
continue
|
| 75 |
+
systems[elements].append((e, fe))
|
| 76 |
+
|
| 77 |
+
print(f" Chemical systems in JARVIS: {len(systems)}")
|
| 78 |
+
|
| 79 |
+
TERMINAL_ENERGIES = {
|
| 80 |
+
"O": -4.935, "N": -8.100, "F": -1.500, "Cl": -1.700,
|
| 81 |
+
"Br": -0.500, "H": -3.300,
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
hulls = {}
|
| 85 |
+
hull_systems = 0
|
| 86 |
+
hull_failed = 0
|
| 87 |
+
|
| 88 |
+
for system, entries_in_system in systems.items():
|
| 89 |
+
if len(entries_in_system) < 3:
|
| 90 |
+
continue
|
| 91 |
+
|
| 92 |
+
compound_entries = []
|
| 93 |
+
for e, fe in entries_in_system:
|
| 94 |
+
try:
|
| 95 |
+
formula = e.get("formula", "")
|
| 96 |
+
comp = Composition(formula)
|
| 97 |
+
total_energy = fe * comp.num_atoms
|
| 98 |
+
compound_entries.append(PDEntry(comp, total_energy, name=e.get("source_id", "")))
|
| 99 |
+
except Exception:
|
| 100 |
+
pass
|
| 101 |
+
|
| 102 |
+
if len(compound_entries) < 3:
|
| 103 |
+
continue
|
| 104 |
+
|
| 105 |
+
terminal_entries = []
|
| 106 |
+
for el_symbol in system:
|
| 107 |
+
ref_energy = TERMINAL_ENERGIES.get(el_symbol, 0.0)
|
| 108 |
+
terminal_entries.append(PDEntry(Composition({el_symbol: 1}), ref_energy, name=f"{el_symbol}(ref)"))
|
| 109 |
+
|
| 110 |
+
all_pd_entries = terminal_entries + compound_entries
|
| 111 |
+
|
| 112 |
+
try:
|
| 113 |
+
hulls[system] = PhaseDiagram(all_pd_entries)
|
| 114 |
+
hull_systems += 1
|
| 115 |
+
except Exception:
|
| 116 |
+
hull_failed += 1
|
| 117 |
+
|
| 118 |
+
print(f" Hulls built: {hull_systems}, failed: {hull_failed}")
|
| 119 |
+
|
| 120 |
+
print(f"\n Computing EaH for JARVIS entries...")
|
| 121 |
+
|
| 122 |
+
computed = 0
|
| 123 |
+
errors = 0
|
| 124 |
+
already_have = 0
|
| 125 |
+
hull_missing = 0
|
| 126 |
+
|
| 127 |
+
# Batch updates: collect row_idx → new value, then apply once
|
| 128 |
+
col_idx = store._table.schema.get_field_index("energy_above_hull")
|
| 129 |
+
old_col = store._table.column("energy_above_hull")
|
| 130 |
+
new_values = old_col.to_pylist()
|
| 131 |
+
|
| 132 |
+
t_start = time.time()
|
| 133 |
+
for idx, e in enumerate(jarvis_entries):
|
| 134 |
+
elements = tuple(sorted(set(e.get("elements", []))))
|
| 135 |
+
fe = e.get("formation_energy_per_atom")
|
| 136 |
+
|
| 137 |
+
if fe is None:
|
| 138 |
+
continue
|
| 139 |
+
|
| 140 |
+
row_idx = store._index.get(e["source_id"])
|
| 141 |
+
if row_idx is None:
|
| 142 |
+
continue
|
| 143 |
+
|
| 144 |
+
if new_values[row_idx] is not None:
|
| 145 |
+
already_have += 1
|
| 146 |
+
continue
|
| 147 |
+
|
| 148 |
+
pd = hulls.get(elements)
|
| 149 |
+
if pd is None:
|
| 150 |
+
hull_missing += 1
|
| 151 |
+
continue
|
| 152 |
+
|
| 153 |
+
try:
|
| 154 |
+
formula = e.get("formula", "")
|
| 155 |
+
comp = Composition(formula)
|
| 156 |
+
total_energy = fe * comp.num_atoms
|
| 157 |
+
entry = PDEntry(comp, total_energy)
|
| 158 |
+
|
| 159 |
+
decomp = pd.get_decomp_and_e_above_hull(entry)
|
| 160 |
+
if decomp is not None:
|
| 161 |
+
_, e_above_hull = decomp
|
| 162 |
+
new_values[row_idx] = round(float(e_above_hull), 6)
|
| 163 |
+
computed += 1
|
| 164 |
+
else:
|
| 165 |
+
hull_missing += 1
|
| 166 |
+
except Exception:
|
| 167 |
+
errors += 1
|
| 168 |
+
|
| 169 |
+
if (idx + 1) % 5000 == 0:
|
| 170 |
+
elapsed = time.time() - t_start
|
| 171 |
+
print(f" {idx+1}/{len(jarvis_entries)} computed={computed} hull_missing={hull_missing} ({elapsed:.0f}s)")
|
| 172 |
+
|
| 173 |
+
# Apply batch update to the table
|
| 174 |
+
print(f" Applying {computed} batch updates to Parquet table...")
|
| 175 |
+
new_col = pa.chunked_array([pa.array(new_values, type=old_col.type)])
|
| 176 |
+
store._table = store._table.set_column(col_idx, "energy_above_hull", new_col)
|
| 177 |
+
store._dirty = True
|
| 178 |
+
|
| 179 |
+
print(f"\n JARVIS EaH results:")
|
| 180 |
+
print(f" Already had EaH: {already_have:,}")
|
| 181 |
+
print(f" Computed (new): {computed:,}")
|
| 182 |
+
print(f" No hull available: {hull_missing:,}")
|
| 183 |
+
print(f" Errors: {errors:,}")
|
| 184 |
+
|
| 185 |
+
# Print examples
|
| 186 |
+
print(f"\n Sample JARVIS entries with computed EaH:")
|
| 187 |
+
shown = 0
|
| 188 |
+
for e in jarvis_entries:
|
| 189 |
+
row_idx = store._index.get(e["source_id"])
|
| 190 |
+
if row_idx is None:
|
| 191 |
+
continue
|
| 192 |
+
eah = new_values[row_idx]
|
| 193 |
+
if eah is not None:
|
| 194 |
+
if shown < 5:
|
| 195 |
+
formula = e.get("formula", "")
|
| 196 |
+
fe = e.get("formation_energy_per_atom", 0)
|
| 197 |
+
print(f" {formula:30s} FE={fe:+.4f} EaH={eah:.4f}")
|
| 198 |
+
shown += 1
|
| 199 |
+
|
| 200 |
+
total_eah = sum(1 for v in new_values if v is not None)
|
| 201 |
+
print(f"\n Overall EaH coverage after update: {total_eah:,}/{store.num_entries:,} ({total_eah/store.num_entries*100:.1f}%)")
|
| 202 |
+
|
| 203 |
+
if args.dry_run:
|
| 204 |
+
print(f"\n (dry-run — not saved)")
|
| 205 |
+
store._dirty = False
|
| 206 |
+
store.close()
|
| 207 |
+
else:
|
| 208 |
+
output_path = DATASET_PATH / "entries_v4_typed.parquet"
|
| 209 |
+
print(f"\n Writing to {output_path}...")
|
| 210 |
+
t_write = time.time()
|
| 211 |
+
store.checkpoint()
|
| 212 |
+
print(f" Done ({time.time()-t_write:.1f}s)")
|
| 213 |
+
|
| 214 |
+
print("=" * WIDTH)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
if __name__ == "__main__":
|
| 218 |
+
main()
|
scripts/compute_mechanical_properties.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pull mechanical properties (elastic moduli) for MP entries via MP API.
|
| 2 |
+
|
| 3 |
+
For entries from Materials Project, this script queries the MP API for
|
| 4 |
+
elastic tensor data (bulk modulus, shear modulus, Young's modulus, Poisson ratio).
|
| 5 |
+
For non-MP entries, it attempts a geometric proxy based on bond density.
|
| 6 |
+
|
| 7 |
+
Fills the ssb_screening block with:
|
| 8 |
+
- bulk_modulus_GPa
|
| 9 |
+
- shear_modulus_GPa
|
| 10 |
+
- youngs_modulus_GPa
|
| 11 |
+
- poisson_ratio
|
| 12 |
+
- elastic_source: "MP_API" | "geometric_proxy" | null
|
| 13 |
+
- dendrite_suppression_flag: shear_modulus > 6 GPa (Monroe-Newman criterion)
|
| 14 |
+
|
| 15 |
+
Usage:
|
| 16 |
+
python scripts/compute_mechanical_properties.py
|
| 17 |
+
python scripts/compute_mechanical_properties.py --api-key YOUR_KEY
|
| 18 |
+
python scripts/compute_mechanical_properties.py --mp-only
|
| 19 |
+
python scripts/compute_mechanical_properties.py --proxy-only
|
| 20 |
+
python scripts/compute_mechanical_properties.py --dry-run
|
| 21 |
+
"""
|
| 22 |
+
import json, os, sys, time, argparse, warnings
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
import numpy as np
|
| 25 |
+
warnings.filterwarnings("ignore")
|
| 26 |
+
|
| 27 |
+
WIDTH = 60
|
| 28 |
+
|
| 29 |
+
# Monroe-Newman criterion: G_solid > ~2x G_Li for dendrite suppression
|
| 30 |
+
LI_SHEAR_MODULUS = 4.25 # GPa at room temp (varies 3.4-4.8)
|
| 31 |
+
DENDRITE_THRESHOLD = 6.0 # GPa conservative threshold
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def compute_density_proxy(structure):
|
| 35 |
+
"""Compute geometric proxy for elastic moduli from structure.
|
| 36 |
+
|
| 37 |
+
Based on bond density and packing fraction correlations.
|
| 38 |
+
Returns approximate bulk_modulus and shear_modulus in GPa.
|
| 39 |
+
"""
|
| 40 |
+
try:
|
| 41 |
+
density = structure.density
|
| 42 |
+
n_atoms = len(structure)
|
| 43 |
+
volume = structure.volume
|
| 44 |
+
|
| 45 |
+
if volume <= 0 or n_atoms < 2:
|
| 46 |
+
return None, None, "insufficient_data"
|
| 47 |
+
|
| 48 |
+
# Atomic packing density proxy
|
| 49 |
+
# Sum of approximate atomic volumes (using covalent radii)
|
| 50 |
+
atomic_vol = 0.0
|
| 51 |
+
for site in structure:
|
| 52 |
+
el = site.specie.symbol
|
| 53 |
+
r_cov = {
|
| 54 |
+
"Li": 1.28, "Na": 1.66, "Mg": 1.41, "Al": 1.21, "Si": 1.11,
|
| 55 |
+
"P": 1.07, "S": 1.05, "Cl": 1.02, "K": 2.03, "Ca": 1.76,
|
| 56 |
+
"Ti": 1.47, "V": 1.34, "Cr": 1.27, "Mn": 1.26, "Fe": 1.25,
|
| 57 |
+
"Co": 1.24, "Ni": 1.21, "Cu": 1.22, "Zn": 1.20, "Ga": 1.22,
|
| 58 |
+
"Ge": 1.21, "As": 1.21, "Se": 1.17, "Br": 1.14, "Y": 1.78,
|
| 59 |
+
"Zr": 1.57, "Nb": 1.45, "Mo": 1.38, "Ru": 1.33, "Rh": 1.31,
|
| 60 |
+
"Pd": 1.30, "Ag": 1.34, "Cd": 1.36, "In": 1.42, "Sn": 1.40,
|
| 61 |
+
"Sb": 1.40, "Te": 1.37, "I": 1.33, "La": 1.87, "Ce": 1.82,
|
| 62 |
+
"Pr": 1.82, "Nd": 1.81, "Sm": 1.80, "Eu": 1.80, "Gd": 1.79,
|
| 63 |
+
"Tb": 1.76, "Dy": 1.75, "Ho": 1.74, "Er": 1.73, "Tm": 1.72,
|
| 64 |
+
"Yb": 1.71, "Lu": 1.70, "Ta": 1.45, "W": 1.39, "Pb": 1.44,
|
| 65 |
+
"Bi": 1.50, "O": 0.66, "N": 0.71, "F": 0.64, "H": 0.31,
|
| 66 |
+
}.get(el, 1.5)
|
| 67 |
+
atomic_vol += (4.0/3.0) * np.pi * (r_cov ** 3)
|
| 68 |
+
|
| 69 |
+
packing_fraction = atomic_vol / volume if volume > 0 else 0.3
|
| 70 |
+
|
| 71 |
+
# Correlation: denser packing -> higher moduli
|
| 72 |
+
# Bulk modulus roughly scales with cohesive energy density
|
| 73 |
+
coh_energy_density = density * 100 # rough proxy in GPa-like units
|
| 74 |
+
|
| 75 |
+
bulk_modulus = coh_energy_density * (packing_fraction ** 1.5)
|
| 76 |
+
shear_modulus = bulk_modulus * (packing_fraction ** 0.5) * 0.5
|
| 77 |
+
|
| 78 |
+
# Clamp to realistic ranges
|
| 79 |
+
bulk_modulus = max(5.0, min(400.0, bulk_modulus))
|
| 80 |
+
shear_modulus = max(2.0, min(300.0, shear_modulus))
|
| 81 |
+
|
| 82 |
+
return round(bulk_modulus, 2), round(shear_modulus, 2), "geometric_proxy"
|
| 83 |
+
except Exception:
|
| 84 |
+
return None, None, "error"
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def main():
|
| 88 |
+
parser = argparse.ArgumentParser(description="Compute mechanical properties")
|
| 89 |
+
parser.add_argument("--api-key", type=str, default=None,
|
| 90 |
+
help="Materials Project API key (optional, for live API queries)")
|
| 91 |
+
parser.add_argument("--mp-only", action="store_true",
|
| 92 |
+
help="Only process MP entries (skip geometric proxy)")
|
| 93 |
+
parser.add_argument("--proxy-only", action="store_true",
|
| 94 |
+
help="Only use geometric proxy (skip MP API)")
|
| 95 |
+
parser.add_argument("--limit", type=int, default=None)
|
| 96 |
+
parser.add_argument("--dry-run", action="store_true")
|
| 97 |
+
parser.add_argument("--output", type=str, default=None)
|
| 98 |
+
args = parser.parse_args()
|
| 99 |
+
|
| 100 |
+
BASE_DIR = Path(__file__).resolve().parent.parent
|
| 101 |
+
DATASET_PATH = BASE_DIR / "dataset"
|
| 102 |
+
|
| 103 |
+
print("=" * WIDTH)
|
| 104 |
+
print(" MECHANICAL PROPERTIES — ELASTIC MODULI")
|
| 105 |
+
print(f" Dendrite suppression threshold: G > {DENDRITE_THRESHOLD} GPa")
|
| 106 |
+
print("=" * WIDTH)
|
| 107 |
+
|
| 108 |
+
print("\nLoading entries...")
|
| 109 |
+
t0 = time.time()
|
| 110 |
+
with open(DATASET_PATH / "entries_final_v3.json") as f:
|
| 111 |
+
all_entries = json.load(f)
|
| 112 |
+
print(f" {len(all_entries):,} entries ({time.time()-t0:.1f}s)")
|
| 113 |
+
|
| 114 |
+
if args.limit:
|
| 115 |
+
all_entries = all_entries[:args.limit]
|
| 116 |
+
print(f" Limited to {args.limit} entries")
|
| 117 |
+
|
| 118 |
+
# Try MP API for MP entries
|
| 119 |
+
mp_elastic_data = {}
|
| 120 |
+
if args.api_key and not args.proxy_only:
|
| 121 |
+
print("\n Querying MP API for elastic data...")
|
| 122 |
+
try:
|
| 123 |
+
from mp_api.client import MPRester
|
| 124 |
+
with MPRester(args.api_key) as mpr:
|
| 125 |
+
mp_ids = [e.get("source_id") for e in all_entries
|
| 126 |
+
if e.get("source") == "mp" and e.get("source_id")]
|
| 127 |
+
print(f" MP entries with source_ids: {len(mp_ids):,}")
|
| 128 |
+
for i in range(0, len(mp_ids), 50):
|
| 129 |
+
batch = mp_ids[i:i+50]
|
| 130 |
+
try:
|
| 131 |
+
results = mpr.elasticity.search(material_ids=batch)
|
| 132 |
+
for doc in results:
|
| 133 |
+
if doc.material_id in batch:
|
| 134 |
+
mp_elastic_data[doc.material_id] = {
|
| 135 |
+
"bulk_modulus": doc.bulk_modulus,
|
| 136 |
+
"shear_modulus": doc.shear_modulus,
|
| 137 |
+
"youngs_modulus": doc.youngs_modulus,
|
| 138 |
+
"poisson_ratio": doc.poisson_ratio,
|
| 139 |
+
}
|
| 140 |
+
except Exception:
|
| 141 |
+
pass
|
| 142 |
+
if (i+1) % 500 == 0:
|
| 143 |
+
print(f" Queried {i+1}/{len(mp_ids)} MP IDs")
|
| 144 |
+
print(f" Retrieved elastic data for {len(mp_elastic_data):,} MP entries")
|
| 145 |
+
except ImportError:
|
| 146 |
+
print(" mp-api not installed. Skipping MP API query.")
|
| 147 |
+
except Exception as exc:
|
| 148 |
+
print(f" MP API error: {exc}")
|
| 149 |
+
|
| 150 |
+
# Process entries
|
| 151 |
+
print(f"\n{'─' * WIDTH}")
|
| 152 |
+
print(" Computing mechanical properties...")
|
| 153 |
+
print(f"{'─' * WIDTH}")
|
| 154 |
+
|
| 155 |
+
processed = 0
|
| 156 |
+
mp_api_found = 0
|
| 157 |
+
proxy_computed = 0
|
| 158 |
+
errors = 0
|
| 159 |
+
dendrite_suppression = 0
|
| 160 |
+
from pymatgen.core import Structure
|
| 161 |
+
import json as _json
|
| 162 |
+
|
| 163 |
+
for idx, e in enumerate(all_entries):
|
| 164 |
+
if "ssb_screening" not in e:
|
| 165 |
+
e["ssb_screening"] = {}
|
| 166 |
+
|
| 167 |
+
ss = e["ssb_screening"]
|
| 168 |
+
source = e.get("source", "")
|
| 169 |
+
source_id = e.get("source_id", "")
|
| 170 |
+
|
| 171 |
+
# Try MP API data first
|
| 172 |
+
if source == "mp" and source_id in mp_elastic_data:
|
| 173 |
+
mp_data = mp_elastic_data[source_id]
|
| 174 |
+
ss["bulk_modulus_GPa"] = mp_data.get("bulk_modulus")
|
| 175 |
+
ss["shear_modulus_GPa"] = mp_data.get("shear_modulus")
|
| 176 |
+
ss["youngs_modulus_GPa"] = mp_data.get("youngs_modulus")
|
| 177 |
+
ss["poisson_ratio"] = mp_data.get("poisson_ratio")
|
| 178 |
+
ss["elastic_source"] = "MP_API"
|
| 179 |
+
mp_api_found += 1
|
| 180 |
+
elif not args.mp_only and e.get("structure_json"):
|
| 181 |
+
# Use geometric proxy
|
| 182 |
+
try:
|
| 183 |
+
struct_dict = _json.loads(e["structure_json"])
|
| 184 |
+
structure = Structure.from_dict(struct_dict)
|
| 185 |
+
K, G, proxy_source = compute_density_proxy(structure)
|
| 186 |
+
if K is not None and G is not None:
|
| 187 |
+
ss["bulk_modulus_GPa"] = K
|
| 188 |
+
ss["shear_modulus_GPa"] = G
|
| 189 |
+
ss["youngs_modulus_GPa"] = round(9 * K * G / (3 * K + G), 2) if (3*K+G) > 0 else None
|
| 190 |
+
ss["poisson_ratio"] = round((3*K - 2*G) / (2*(3*K + G)), 3) if (3*K+G) > 0 else None
|
| 191 |
+
ss["elastic_source"] = proxy_source
|
| 192 |
+
proxy_computed += 1
|
| 193 |
+
except Exception:
|
| 194 |
+
errors += 1
|
| 195 |
+
|
| 196 |
+
# Set dendrite suppression flag
|
| 197 |
+
shear_mod = ss.get("shear_modulus_GPa")
|
| 198 |
+
if shear_mod is not None:
|
| 199 |
+
ss["dendrite_suppression_flag"] = bool(shear_mod >= DENDRITE_THRESHOLD)
|
| 200 |
+
if ss["dendrite_suppression_flag"]:
|
| 201 |
+
dendrite_suppression += 1
|
| 202 |
+
|
| 203 |
+
processed += 1
|
| 204 |
+
if (idx + 1) % 5000 == 0:
|
| 205 |
+
print(f" {idx+1}/{len(all_entries)} | MP_API:{mp_api_found} Proxy:{proxy_computed} Dendrite:{dendrite_suppression}")
|
| 206 |
+
|
| 207 |
+
print(f"\n{'─' * WIDTH}")
|
| 208 |
+
print(f" Complete: {processed} processed")
|
| 209 |
+
print(f" MP API data: {mp_api_found:,}")
|
| 210 |
+
print(f" Geometric proxy: {proxy_computed:,}")
|
| 211 |
+
print(f" Errors: {errors:,}")
|
| 212 |
+
print(f" Dendrite suppression (G > {DENDRITE_THRESHOLD} GPa): {dendrite_suppression:,}")
|
| 213 |
+
|
| 214 |
+
# Save
|
| 215 |
+
if args.dry_run:
|
| 216 |
+
print(f"\n (dry-run — not saved)")
|
| 217 |
+
else:
|
| 218 |
+
output_path = DATASET_PATH / "entries_final_v3.json"
|
| 219 |
+
print(f"\n Writing to {output_path}...")
|
| 220 |
+
t_write = time.time()
|
| 221 |
+
with open(args.output or output_path, "w") as f:
|
| 222 |
+
json.dump(all_entries, f)
|
| 223 |
+
print(f" Done ({time.time()-t_write:.1f}s)")
|
| 224 |
+
|
| 225 |
+
print("=" * WIDTH)
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
if __name__ == "__main__":
|
| 229 |
+
main()
|
scripts/compute_oxidation_states.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Predict oxidation states for all entries using bond valence analysis.
|
| 2 |
+
|
| 3 |
+
Fills each entry with:
|
| 4 |
+
- oxidation_states: dict of {element: average_oxidation_state}
|
| 5 |
+
- predicted_oxidation_states_valid: bool
|
| 6 |
+
|
| 7 |
+
Usage:
|
| 8 |
+
python scripts/compute_oxidation_states.py
|
| 9 |
+
python scripts/compute_oxidation_states.py --limit 10000
|
| 10 |
+
python scripts/compute_oxidation_states.py --dry-run
|
| 11 |
+
"""
|
| 12 |
+
import json, os, sys, time, argparse, warnings
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from collections import defaultdict
|
| 15 |
+
import numpy as np
|
| 16 |
+
warnings.filterwarnings("ignore")
|
| 17 |
+
|
| 18 |
+
WIDTH = 60
|
| 19 |
+
|
| 20 |
+
COMMON_OXIDATION = {
|
| 21 |
+
"Li": [1], "Na": [1], "K": [1], "Rb": [1], "Cs": [1],
|
| 22 |
+
"Mg": [2], "Ca": [2], "Sr": [2], "Ba": [2],
|
| 23 |
+
"Al": [3], "Ga": [3], "In": [3],
|
| 24 |
+
"Si": [4], "Ge": [4], "Sn": [2, 4], "Pb": [2, 4],
|
| 25 |
+
"P": [5], "As": [3, 5], "Sb": [3, 5], "Bi": [3, 5],
|
| 26 |
+
"O": [-2], "S": [-2, 4, 6], "Se": [-2, 4, 6], "Te": [-2, 4, 6],
|
| 27 |
+
"F": [-1], "Cl": [-1], "Br": [-1], "I": [-1],
|
| 28 |
+
"N": [-3], "H": [1],
|
| 29 |
+
"Ti": [4], "V": [3, 5], "Cr": [3, 6], "Mn": [2, 4, 7],
|
| 30 |
+
"Fe": [2, 3], "Co": [2, 3], "Ni": [2], "Cu": [1, 2],
|
| 31 |
+
"Zn": [2], "Y": [3], "Zr": [4], "Nb": [5], "Mo": [4, 6],
|
| 32 |
+
"La": [3], "Ce": [3, 4], "Pr": [3], "Nd": [3], "Sm": [3],
|
| 33 |
+
"Eu": [2, 3], "Gd": [3], "Tb": [3, 4], "Dy": [3], "Ho": [3],
|
| 34 |
+
"Er": [3], "Tm": [3], "Yb": [2, 3], "Lu": [3],
|
| 35 |
+
"Ta": [5], "W": [6], "B": [3], "C": [4], "Sc": [3],
|
| 36 |
+
"Hg": [1, 2],
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def parse_formula(formula):
|
| 41 |
+
import re
|
| 42 |
+
parts = re.findall(r'([A-Z][a-z]*)(\d*\.?\d*)', formula)
|
| 43 |
+
return {el: float(cnt) if cnt else 1.0 for el, cnt in parts}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def heuristic_oxidation_states(formula_dict):
|
| 47 |
+
elements = list(formula_dict.keys())
|
| 48 |
+
anions = {"O", "S", "Se", "Te", "F", "Cl", "Br", "I", "N", "P", "As", "Sb"}
|
| 49 |
+
cation_els = [el for el in elements if el not in anions]
|
| 50 |
+
anion_els = [el for el in elements if el in anions]
|
| 51 |
+
if not anion_els:
|
| 52 |
+
return {el: 0.0 for el in elements}
|
| 53 |
+
result = {}
|
| 54 |
+
assigned_anions = 0.0
|
| 55 |
+
for el in elements:
|
| 56 |
+
states = COMMON_OXIDATION.get(el, [0])
|
| 57 |
+
if el in anions:
|
| 58 |
+
result[el] = float(min(states))
|
| 59 |
+
assigned_anions += result[el] * formula_dict[el]
|
| 60 |
+
else:
|
| 61 |
+
result[el] = float(max(states))
|
| 62 |
+
total_charge = sum(result[el] * formula_dict[el] for el in elements)
|
| 63 |
+
if abs(total_charge) > 0.5 and cation_els:
|
| 64 |
+
scale = -assigned_anions / max(abs(total_charge - assigned_anions), 0.01)
|
| 65 |
+
for el in cation_els:
|
| 66 |
+
result[el] = round(result[el] * scale, 1)
|
| 67 |
+
return result
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def main():
|
| 71 |
+
parser = argparse.ArgumentParser(description="Predict oxidation states")
|
| 72 |
+
parser.add_argument("--dry-run", action="store_true")
|
| 73 |
+
parser.add_argument("--limit", type=int, default=None)
|
| 74 |
+
args = parser.parse_args()
|
| 75 |
+
|
| 76 |
+
BASE_DIR = Path(__file__).resolve().parent.parent
|
| 77 |
+
DATASET_PATH = BASE_DIR / "dataset"
|
| 78 |
+
|
| 79 |
+
print("=" * WIDTH)
|
| 80 |
+
print(" OXIDATION STATE PREDICTION")
|
| 81 |
+
print("=" * WIDTH)
|
| 82 |
+
|
| 83 |
+
print("\nLoading entries...")
|
| 84 |
+
t0 = time.time()
|
| 85 |
+
with open(DATASET_PATH / "entries_final_v3.json") as f:
|
| 86 |
+
all_entries = json.load(f)
|
| 87 |
+
print(f" {len(all_entries):,} entries ({time.time()-t0:.1f}s)")
|
| 88 |
+
|
| 89 |
+
if args.limit:
|
| 90 |
+
all_entries = all_entries[:args.limit]
|
| 91 |
+
print(f" Limited to {args.limit} entries")
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
from pymatgen.analysis.bond_valence import BVAnalyzer
|
| 95 |
+
from pymatgen.core import Structure
|
| 96 |
+
bva = BVAnalyzer()
|
| 97 |
+
bva_available = True
|
| 98 |
+
print(" BVAnalyzer available")
|
| 99 |
+
except Exception:
|
| 100 |
+
bva_available = False
|
| 101 |
+
print(" BVAnalyzer not available, heuristic only")
|
| 102 |
+
|
| 103 |
+
import json as _json
|
| 104 |
+
|
| 105 |
+
print(f"\n{'─' * WIDTH}")
|
| 106 |
+
print(" Assigning oxidation states...")
|
| 107 |
+
|
| 108 |
+
bva_success = 0
|
| 109 |
+
heuristic_assigned = 0
|
| 110 |
+
errors = 0
|
| 111 |
+
|
| 112 |
+
for idx, e in enumerate(all_entries):
|
| 113 |
+
formula = e.get("formula", "")
|
| 114 |
+
formula_dict = parse_formula(formula)
|
| 115 |
+
e["oxidation_states"] = {}
|
| 116 |
+
assigned = False
|
| 117 |
+
|
| 118 |
+
if bva_available and e.get("structure_json"):
|
| 119 |
+
try:
|
| 120 |
+
struct_dict = _json.loads(e["structure_json"])
|
| 121 |
+
structure = Structure.from_dict(struct_dict)
|
| 122 |
+
oxi_states = bva.get_valences(structure)
|
| 123 |
+
if oxi_states:
|
| 124 |
+
element_oxi = defaultdict(list)
|
| 125 |
+
for site, oxi in zip(structure, oxi_states):
|
| 126 |
+
element_oxi[site.specie.symbol].append(float(oxi))
|
| 127 |
+
e["oxidation_states"] = {el: round(sum(vals)/len(vals), 2) for el, vals in element_oxi.items()}
|
| 128 |
+
e["predicted_oxidation_states_valid"] = True
|
| 129 |
+
bva_success += 1
|
| 130 |
+
assigned = True
|
| 131 |
+
except Exception:
|
| 132 |
+
pass
|
| 133 |
+
|
| 134 |
+
if not assigned:
|
| 135 |
+
oxi = heuristic_oxidation_states(formula_dict)
|
| 136 |
+
e["oxidation_states"] = oxi
|
| 137 |
+
e["predicted_oxidation_states_valid"] = False
|
| 138 |
+
heuristic_assigned += 1
|
| 139 |
+
|
| 140 |
+
if (idx + 1) % 10000 == 0:
|
| 141 |
+
print(f" {idx+1}/{len(all_entries)} | BVA:{bva_success} Heuristic:{heuristic_assigned}")
|
| 142 |
+
|
| 143 |
+
print(f"\n BVA: {bva_success:,}, Heuristic: {heuristic_assigned:,}, Total: {bva_success+heuristic_assigned:,}/{len(all_entries):,}")
|
| 144 |
+
|
| 145 |
+
if args.dry_run:
|
| 146 |
+
print(f"\n (dry-run)")
|
| 147 |
+
else:
|
| 148 |
+
output_path = DATASET_PATH / "entries_final_v3.json"
|
| 149 |
+
print(f"\n Writing...")
|
| 150 |
+
t_write = time.time()
|
| 151 |
+
with open(output_path, "w") as f:
|
| 152 |
+
json.dump(all_entries, f)
|
| 153 |
+
print(f" Done ({time.time()-t_write:.1f}s)")
|
| 154 |
+
|
| 155 |
+
print("=" * WIDTH)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
if __name__ == "__main__":
|
| 159 |
+
main()
|
scripts/compute_sse_candidate_score.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compute SSE candidate scores for all entries based on the 5-gate screening system.
|
| 2 |
+
|
| 3 |
+
Populates the ssb_screening block with:
|
| 4 |
+
- gates_passed: list of passed gate names
|
| 5 |
+
- sse_candidate_score: composite score (0-100)
|
| 6 |
+
- thermo_stable: bool (gate 1)
|
| 7 |
+
- electronic_insulation: bool (gate 2)
|
| 8 |
+
|
| 9 |
+
Gates:
|
| 10 |
+
1. thermo_stability: E_hull < 0.025 eV/atom (stable or near-stable)
|
| 11 |
+
2. electronic_insulation: band_gap > 1.0 eV (not metallic)
|
| 12 |
+
3. ionic_mobility: cavd_channel_dimensionality in ["2D", "3D"] (when available)
|
| 13 |
+
4. electrochemical_window: window_width > 1.0 V (when available)
|
| 14 |
+
5. mechanical: dendrite_suppression_flag (when available)
|
| 15 |
+
|
| 16 |
+
Score is transparent and compositional:
|
| 17 |
+
- Gate 1 (thermo): 30 points
|
| 18 |
+
- Gate 2 (electronic): 25 points
|
| 19 |
+
- Gate 3 (mobility proxy): 20 points (partial credit for 1D channels)
|
| 20 |
+
- Gate 4 (electrochemical): 15 points
|
| 21 |
+
- Gate 5 (mechanical): 10 points
|
| 22 |
+
|
| 23 |
+
Usage:
|
| 24 |
+
python scripts/compute_sse_candidate_score.py
|
| 25 |
+
python scripts/compute_sse_candidate_score.py --subset battery
|
| 26 |
+
python scripts/compute_sse_candidate_score.py --limit 10000 --dry-run
|
| 27 |
+
"""
|
| 28 |
+
import json, os, sys, time, argparse, warnings
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
warnings.filterwarnings("ignore")
|
| 31 |
+
|
| 32 |
+
WIDTH = 60
|
| 33 |
+
|
| 34 |
+
# Gate thresholds
|
| 35 |
+
GATES = {
|
| 36 |
+
"thermo_stability": {
|
| 37 |
+
"weight": 30,
|
| 38 |
+
"field": "thermo_stable",
|
| 39 |
+
"description": "E_hull < 0.025 eV/atom",
|
| 40 |
+
"check": lambda e: e.get("ssb_screening", {}).get("thermo_stable", False)
|
| 41 |
+
},
|
| 42 |
+
"electronic_insulation": {
|
| 43 |
+
"weight": 25,
|
| 44 |
+
"field": "electronic_insulation",
|
| 45 |
+
"description": "band_gap > 1.0 eV",
|
| 46 |
+
"check": lambda e: e.get("ssb_screening", {}).get("electronic_insulation", False)
|
| 47 |
+
},
|
| 48 |
+
"ionic_mobility": {
|
| 49 |
+
"weight": 20,
|
| 50 |
+
"field": "cavd_channel_dimensionality",
|
| 51 |
+
"description": "2D/3D percolation channels",
|
| 52 |
+
"check": lambda e: _check_mobility(e)
|
| 53 |
+
},
|
| 54 |
+
"electrochemical_window": {
|
| 55 |
+
"weight": 15,
|
| 56 |
+
"field": "stability_window_low_V",
|
| 57 |
+
"description": "window_width > 1.0 V",
|
| 58 |
+
"check": lambda e: _check_window(e)
|
| 59 |
+
},
|
| 60 |
+
"mechanical": {
|
| 61 |
+
"weight": 10,
|
| 62 |
+
"field": "dendrite_suppression_flag",
|
| 63 |
+
"description": "shear_modulus > 6 GPa",
|
| 64 |
+
"check": lambda e: e.get("ssb_screening", {}).get("dendrite_suppression_flag", False)
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
def _check_mobility(e):
|
| 69 |
+
ss = e.get("ssb_screening", {})
|
| 70 |
+
dim = ss.get("cavd_channel_dimensionality")
|
| 71 |
+
if dim in ("3D",):
|
| 72 |
+
return True
|
| 73 |
+
if dim in ("2D",):
|
| 74 |
+
return True
|
| 75 |
+
if dim in ("1D",):
|
| 76 |
+
# Partial: mobile ions exist but channels are 1D
|
| 77 |
+
return False
|
| 78 |
+
return False
|
| 79 |
+
|
| 80 |
+
def _check_window(e):
|
| 81 |
+
ss = e.get("ssb_screening", {})
|
| 82 |
+
low = ss.get("stability_window_low_V")
|
| 83 |
+
high = ss.get("stability_window_high_V")
|
| 84 |
+
if low is not None and high is not None:
|
| 85 |
+
return (high - low) >= 1.0
|
| 86 |
+
return False
|
| 87 |
+
|
| 88 |
+
def _check_mechanical(e):
|
| 89 |
+
return e.get("ssb_screening", {}).get("dendrite_suppression_flag", False)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def compute_gate_score(e, gate_name, gate_config):
|
| 93 |
+
"""Compute gate score. Gate passes = full weight, else 0."""
|
| 94 |
+
try:
|
| 95 |
+
passed = gate_config["check"](e)
|
| 96 |
+
return gate_config["weight"] if passed else 0, passed
|
| 97 |
+
except Exception:
|
| 98 |
+
return 0, False
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def main():
|
| 102 |
+
parser = argparse.ArgumentParser(description="Compute SSE candidate scores")
|
| 103 |
+
parser.add_argument("--subset", choices=["battery", "electrolyte", "gold", "full"], default="full")
|
| 104 |
+
parser.add_argument("--limit", type=int, default=None)
|
| 105 |
+
parser.add_argument("--dry-run", action="store_true")
|
| 106 |
+
parser.add_argument("--output", type=str, default=None)
|
| 107 |
+
args = parser.parse_args()
|
| 108 |
+
|
| 109 |
+
if args.limit and not args.dry_run and args.output is None:
|
| 110 |
+
print("ERROR: Refusing to save limited runs. Use --dry-run or --output.")
|
| 111 |
+
sys.exit(1)
|
| 112 |
+
|
| 113 |
+
BASE_DIR = Path(__file__).resolve().parent.parent
|
| 114 |
+
DATASET_PATH = BASE_DIR / "dataset"
|
| 115 |
+
|
| 116 |
+
print("=" * WIDTH)
|
| 117 |
+
print(" SSE CANDIDATE SCORE — 5-GATE SCREENING SYSTEM")
|
| 118 |
+
print("=" * WIDTH)
|
| 119 |
+
print()
|
| 120 |
+
print(" Gate weights:")
|
| 121 |
+
for gate_name, config in GATES.items():
|
| 122 |
+
print(f" {config['weight']:2d} pts — {gate_name}: {config['description']}")
|
| 123 |
+
print()
|
| 124 |
+
|
| 125 |
+
print("Loading entries...")
|
| 126 |
+
t0 = time.time()
|
| 127 |
+
with open(DATASET_PATH / "entries_final_v3.json") as f:
|
| 128 |
+
all_entries = json.load(f)
|
| 129 |
+
print(f" {len(all_entries):,} entries ({time.time()-t0:.1f}s)")
|
| 130 |
+
|
| 131 |
+
# Select working subset
|
| 132 |
+
if args.subset == "battery":
|
| 133 |
+
with open(DATASET_PATH / "battery_candidate_subset_v1.json") as f:
|
| 134 |
+
entries = json.load(f)
|
| 135 |
+
elif args.subset == "electrolyte":
|
| 136 |
+
with open(DATASET_PATH / "solid_electrolyte_candidate_subset_v1.json") as f:
|
| 137 |
+
entries = json.load(f)
|
| 138 |
+
elif args.subset == "gold":
|
| 139 |
+
entries = [e for e in all_entries if e.get("tier") == "gold"]
|
| 140 |
+
else:
|
| 141 |
+
entries = all_entries
|
| 142 |
+
|
| 143 |
+
if args.limit:
|
| 144 |
+
entries = entries[:args.limit]
|
| 145 |
+
|
| 146 |
+
print(f" Working subset: {len(entries):,} entries")
|
| 147 |
+
|
| 148 |
+
if not entries:
|
| 149 |
+
print("No entries to process.")
|
| 150 |
+
return
|
| 151 |
+
|
| 152 |
+
# Score all entries
|
| 153 |
+
print(f"\n{'─' * WIDTH}")
|
| 154 |
+
print(" Computing scores...")
|
| 155 |
+
print(f"{'─' * WIDTH}")
|
| 156 |
+
|
| 157 |
+
score_dist = {}
|
| 158 |
+
gate_counts = {g: {"pass": 0, "total": 0} for g in GATES}
|
| 159 |
+
|
| 160 |
+
# Track entries that need to be synced back to all_entries
|
| 161 |
+
updated_keys = set()
|
| 162 |
+
|
| 163 |
+
for idx, e in enumerate(entries):
|
| 164 |
+
if "ssb_screening" not in e:
|
| 165 |
+
e["ssb_screening"] = {}
|
| 166 |
+
|
| 167 |
+
ss = e["ssb_screening"]
|
| 168 |
+
|
| 169 |
+
total_score = 0
|
| 170 |
+
gates_passed = []
|
| 171 |
+
|
| 172 |
+
for gate_name, config in GATES.items():
|
| 173 |
+
score, passed = compute_gate_score(e, gate_name, config)
|
| 174 |
+
total_score += score
|
| 175 |
+
gate_counts[gate_name]["total"] += 1
|
| 176 |
+
if passed:
|
| 177 |
+
gates_passed.append(gate_name)
|
| 178 |
+
gate_counts[gate_name]["pass"] += 1
|
| 179 |
+
|
| 180 |
+
ss["sse_candidate_score"] = total_score
|
| 181 |
+
ss["gates_passed"] = gates_passed
|
| 182 |
+
|
| 183 |
+
# Record distribution
|
| 184 |
+
bin_key = f"{(total_score // 10) * 10}-{(total_score // 10) * 10 + 9}"
|
| 185 |
+
score_dist[bin_key] = score_dist.get(bin_key, 0) + 1
|
| 186 |
+
|
| 187 |
+
# Keep track of which entries were updated
|
| 188 |
+
source_id = e.get("source_id", "") + e.get("source", "")
|
| 189 |
+
updated_keys.add(source_id)
|
| 190 |
+
|
| 191 |
+
# Print results
|
| 192 |
+
print(f"\n Score distribution:")
|
| 193 |
+
for key in sorted(score_dist.keys(), key=lambda x: int(x.split("-")[0])):
|
| 194 |
+
count = score_dist[key]
|
| 195 |
+
bar = "█" * min(count // 1000, 50)
|
| 196 |
+
print(f" {key:>6}: {count:>6,} {bar}")
|
| 197 |
+
|
| 198 |
+
print(f"\n Per-gate pass rates:")
|
| 199 |
+
for gate_name, counts in gate_counts.items():
|
| 200 |
+
pct = counts["pass"] / max(counts["total"], 1) * 100
|
| 201 |
+
print(f" {gate_name:25s}: {counts['pass']:>6,}/{counts['total']:<6,} ({pct:.1f}%)")
|
| 202 |
+
|
| 203 |
+
# Top scores
|
| 204 |
+
all_sorted = sorted(entries, key=lambda e: e.get("ssb_screening", {}).get("sse_candidate_score", 0), reverse=True)
|
| 205 |
+
print(f"\n Top 10 candidates:")
|
| 206 |
+
for e in all_sorted[:10]:
|
| 207 |
+
ss = e.get("ssb_screening", {})
|
| 208 |
+
print(f" Score {ss.get('sse_candidate_score', 0):3d} | {e.get('structured_formula', e.get('formula','')):20s} | "
|
| 209 |
+
f"{e.get('sse_family', '?'):15s} | Gates: {ss.get('gates_passed', [])}")
|
| 210 |
+
|
| 211 |
+
# Sync back to all_entries
|
| 212 |
+
if args.subset in ("full",):
|
| 213 |
+
save_data = all_entries
|
| 214 |
+
elif args.subset == "gold":
|
| 215 |
+
save_data = all_entries
|
| 216 |
+
entry_map = {}
|
| 217 |
+
for e in entries:
|
| 218 |
+
key = e.get("source_id", "") + e.get("source", "")
|
| 219 |
+
entry_map[key] = e
|
| 220 |
+
for e in save_data:
|
| 221 |
+
key = e.get("source_id", "") + e.get("source", "")
|
| 222 |
+
if key in entry_map:
|
| 223 |
+
e["ssb_screening"] = entry_map[key].get("ssb_screening", {})
|
| 224 |
+
else:
|
| 225 |
+
save_data = entries
|
| 226 |
+
|
| 227 |
+
# Save
|
| 228 |
+
if args.subset == "battery":
|
| 229 |
+
output_path = DATASET_PATH / "battery_candidate_subset_v1.json"
|
| 230 |
+
elif args.subset == "electrolyte":
|
| 231 |
+
output_path = DATASET_PATH / "solid_electrolyte_candidate_subset_v1.json"
|
| 232 |
+
elif args.subset == "gold":
|
| 233 |
+
output_path = DATASET_PATH / "entries_final_v3.json"
|
| 234 |
+
else:
|
| 235 |
+
output_path = DATASET_PATH / "entries_final_v3.json"
|
| 236 |
+
|
| 237 |
+
if args.dry_run:
|
| 238 |
+
print(f"\n (dry-run — not saved)")
|
| 239 |
+
else:
|
| 240 |
+
print(f"\n Writing to {output_path}...")
|
| 241 |
+
t_write = time.time()
|
| 242 |
+
with open(output_path, "w") as f:
|
| 243 |
+
json.dump(save_data, f)
|
| 244 |
+
print(f" Done ({time.time()-t_write:.1f}s)")
|
| 245 |
+
|
| 246 |
+
print("=" * WIDTH)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
if __name__ == "__main__":
|
| 250 |
+
main()
|
scripts/convert_parquet_typed.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Convert the encoded-string Parquet to proper typed columns for HF viewer compat."""
|
| 2 |
+
import json, sys, time
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
| 5 |
+
from dataset.dataset_store import _decode_value
|
| 6 |
+
|
| 7 |
+
import pyarrow as pa
|
| 8 |
+
import pyarrow.parquet as pq
|
| 9 |
+
|
| 10 |
+
DATASET_DIR = Path(__file__).resolve().parent.parent / "dataset"
|
| 11 |
+
SRC = DATASET_DIR / "entries_v3.parquet"
|
| 12 |
+
DST = DATASET_DIR / "entries_v4_typed.parquet"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def infer_type(col_name, prefixes):
|
| 16 |
+
if 'b' in prefixes:
|
| 17 |
+
return pa.bool_()
|
| 18 |
+
elif 'i' in prefixes:
|
| 19 |
+
return pa.int64()
|
| 20 |
+
elif 'f' in prefixes:
|
| 21 |
+
return pa.float64()
|
| 22 |
+
return pa.string()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def safe(v, pa_type):
|
| 26 |
+
if v is None:
|
| 27 |
+
return None
|
| 28 |
+
d = _decode_value(v)
|
| 29 |
+
if d is None or d == '':
|
| 30 |
+
return None
|
| 31 |
+
try:
|
| 32 |
+
if isinstance(d, (dict, list)):
|
| 33 |
+
return json.dumps(d)
|
| 34 |
+
if pa_type == pa.int64():
|
| 35 |
+
return int(d)
|
| 36 |
+
if pa_type == pa.float64():
|
| 37 |
+
return float(d)
|
| 38 |
+
if pa_type == pa.bool_():
|
| 39 |
+
return bool(d)
|
| 40 |
+
return str(d)
|
| 41 |
+
except (ValueError, TypeError):
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def main():
|
| 46 |
+
print("Reading source Parquet...")
|
| 47 |
+
t0 = time.time()
|
| 48 |
+
src = pq.read_table(SRC)
|
| 49 |
+
print(f" {src.num_rows:,} rows, {src.num_columns} columns ({time.time()-t0:.1f}s)")
|
| 50 |
+
|
| 51 |
+
pcols = {col: set() for col in src.column_names}
|
| 52 |
+
for i in range(min(5000, src.num_rows)):
|
| 53 |
+
for col in src.column_names:
|
| 54 |
+
raw = src.column(col)[i].as_py()
|
| 55 |
+
pcols[col].add(raw.split(':')[0] if raw and ':' in raw else None)
|
| 56 |
+
|
| 57 |
+
print("Decoding and converting...")
|
| 58 |
+
t0 = time.time()
|
| 59 |
+
arrays = {}
|
| 60 |
+
for col in src.column_names:
|
| 61 |
+
raw_col = src.column(col)
|
| 62 |
+
tgt = infer_type(col, pcols[col])
|
| 63 |
+
vals = [safe(raw_col[i].as_py(), tgt) for i in range(raw_col.length())]
|
| 64 |
+
arr = pa.array(vals, type=tgt)
|
| 65 |
+
arrays[col] = arr
|
| 66 |
+
print(f" {col:40s} → {str(tgt):10s} ({time.time()-t0:.1f}s)")
|
| 67 |
+
|
| 68 |
+
print("Building typed table...")
|
| 69 |
+
schema = pa.schema([pa.field(c, arrays[c].type) for c in src.column_names])
|
| 70 |
+
table = pa.table(arrays, schema=schema)
|
| 71 |
+
|
| 72 |
+
print("Writing typed Parquet...")
|
| 73 |
+
pq.write_table(table, DST, compression="zstd", compression_level=9)
|
| 74 |
+
sz = DST.stat().st_size
|
| 75 |
+
print(f" {DST.name}: {sz/1e6:.1f} MB")
|
| 76 |
+
|
| 77 |
+
verify = pq.read_table(DST)
|
| 78 |
+
assert verify.num_rows == src.num_rows
|
| 79 |
+
print(f"Verified: {verify.num_rows:,} rows × {verify.num_columns} cols")
|
| 80 |
+
for f in verify.schema:
|
| 81 |
+
print(f" {f.name:40s} {f.type}")
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
if __name__ == "__main__":
|
| 85 |
+
main()
|
scripts/enrich_garnet_family.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Garnet-family enrichment: identify missed garnet-type structures.
|
| 2 |
+
|
| 3 |
+
Current garnet count is 41 entries (should be thousands for an SSB dataset).
|
| 4 |
+
This script:
|
| 5 |
+
1. Uses composition-based heuristics to find garnet-like formulas
|
| 6 |
+
2. Uses structure fingerprinting to verify garnet topology
|
| 7 |
+
3. Reclassifies entries with structure confirmation
|
| 8 |
+
4. Reports candidate structures for targeted acquisition
|
| 9 |
+
|
| 10 |
+
Garnet identification logic:
|
| 11 |
+
- Composition: A3B2C3O12 where A=Li,Na, etc; B=La,Zr, etc; C=Zr,Ta,Nb,etc
|
| 12 |
+
- Structure: body-centered cubic, space group Ia-3d (230)
|
| 13 |
+
- Specific known families: LLZO, LLTO, LSNO, etc.
|
| 14 |
+
|
| 15 |
+
Usage:
|
| 16 |
+
python scripts/enrich_garnet_family.py
|
| 17 |
+
python scripts/enrich_garnet_family.py --dry-run
|
| 18 |
+
python scripts/enrich_garnet_family.py --report-only
|
| 19 |
+
"""
|
| 20 |
+
import json, os, sys, time, argparse, re, warnings
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from collections import Counter, defaultdict
|
| 23 |
+
import numpy as np
|
| 24 |
+
warnings.filterwarnings("ignore")
|
| 25 |
+
|
| 26 |
+
KNOWN_GARNET_SPACE_GROUPS = {230, 229, 228, 227, 220, 219, 218, 217, 216, 215, 214, 213, 212, 211, 210, 209, 208, 207, 206, 205, 204, 203, 202, 201, 200}
|
| 27 |
+
GARNET_SG_IA3D = 230 # Ia-3d, most common garnet space group
|
| 28 |
+
|
| 29 |
+
GARNET_SYMBOLS = {"Ia-3d", "Ia3d", "I a -3 d", "I a 3 d", "I a-3d", "Ia-3"}
|
| 30 |
+
|
| 31 |
+
# Common garnet-forming elements
|
| 32 |
+
GARNET_A_SITES = {"Li", "Na", "K", "Ag", "Cu"} # Dodecahedral
|
| 33 |
+
GARNET_B_SITES = {"La", "Y", "Pr", "Nd", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Yb", "Lu", "Ca", "Sr", "Ba", "Bi", "Ce"} # Octahedral
|
| 34 |
+
GARNET_C_SITES = {"Zr", "Ta", "Nb", "Sb", "Te", "W", "Mo", "V", "Sn", "Ti", "Hf", "Al", "Ga", "Fe", "In", "Sc", "Cr"} # Tetrahedral/octahedral
|
| 35 |
+
GARNET_O_SITES = {"O", "S", "Se", "Te"} # Anion
|
| 36 |
+
|
| 37 |
+
# Known garnet structure prefixes for formula-based matching
|
| 38 |
+
GARNET_PATTERNS = [
|
| 39 |
+
(r"^Li\d+[A-Z][a-z]?\d*[A-Z][a-z]?\d*O\d+", "lithium_garnet"),
|
| 40 |
+
(r"^Na\d+[A-Z][a-z]?\d*[A-Z][a-z]?\d*O\d+", "sodium_garnet"),
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
def parse_formula(formula):
|
| 44 |
+
"""Parse formula string into element counts."""
|
| 45 |
+
parts = re.findall(r'([A-Z][a-z]*)(\d*\.?\d*)', formula)
|
| 46 |
+
return {el: float(cnt) if cnt else 1.0 for el, cnt in parts}
|
| 47 |
+
|
| 48 |
+
def is_garnet_by_formula(formula_dict):
|
| 49 |
+
"""Check if composition resembles garnet (A3B2C3O12-type).
|
| 50 |
+
|
| 51 |
+
Stricter heuristic: require approximate 3:2:3:12 ratio and
|
| 52 |
+
Li/Na on A sites with Zr/Ta/Nb/Al on B/C sites.
|
| 53 |
+
"""
|
| 54 |
+
oxygen_count = sum(formula_dict.get(o, 0) for o in GARNET_O_SITES)
|
| 55 |
+
if oxygen_count < 3:
|
| 56 |
+
return False, "not_oxide"
|
| 57 |
+
|
| 58 |
+
a_count = sum(formula_dict.get(el, 0) for el in GARNET_A_SITES)
|
| 59 |
+
b_count = sum(formula_dict.get(el, 0) for el in GARNET_B_SITES)
|
| 60 |
+
c_count = sum(formula_dict.get(el, 0) for el in GARNET_C_SITES)
|
| 61 |
+
|
| 62 |
+
cation_count = a_count + b_count + c_count
|
| 63 |
+
if cation_count < 3:
|
| 64 |
+
return False, "no_garnet_cations"
|
| 65 |
+
|
| 66 |
+
# Normalize ratios to 12 oxygens
|
| 67 |
+
scale = 12.0 / max(oxygen_count, 1)
|
| 68 |
+
a_norm = a_count * scale
|
| 69 |
+
b_norm = b_count * scale
|
| 70 |
+
c_norm = c_count * scale
|
| 71 |
+
|
| 72 |
+
# Classic garnet: A3B2C3O12
|
| 73 |
+
# Allow some deviation but not extreme
|
| 74 |
+
total_norm = a_norm + b_norm + c_norm
|
| 75 |
+
if not (5.0 < total_norm < 12.0):
|
| 76 |
+
return False, "wrong_cation_count"
|
| 77 |
+
|
| 78 |
+
# A-site should be at least ~1 normalized
|
| 79 |
+
if a_norm < 0.5:
|
| 80 |
+
return False, "insufficient_A_site"
|
| 81 |
+
|
| 82 |
+
# At least one of B or C site should be substantial
|
| 83 |
+
if b_norm + c_norm < 1.0:
|
| 84 |
+
return False, "insufficient_BC_sites"
|
| 85 |
+
|
| 86 |
+
# For known LLZO-type: need Li + La/Zr + O
|
| 87 |
+
has_li_la_zr = (
|
| 88 |
+
"Li" in formula_dict and
|
| 89 |
+
any(el in formula_dict for el in ["La", "Y", "Nd", "Pr", "Eu", "Gd"]) and
|
| 90 |
+
any(el in formula_dict for el in ["Zr", "Ta", "Nb"])
|
| 91 |
+
)
|
| 92 |
+
if has_li_la_zr:
|
| 93 |
+
return True, "LLZO_type_composition"
|
| 94 |
+
|
| 95 |
+
# General garnet-like: at least 2 distinct cation types on B/C
|
| 96 |
+
bc_types = sum(1 for el in formula_dict if el in GARNET_B_SITES or el in GARNET_C_SITES)
|
| 97 |
+
if bc_types >= 2 and a_norm >= 1.0:
|
| 98 |
+
return True, "broad_garnet_composition"
|
| 99 |
+
|
| 100 |
+
# Na garnets (less common)
|
| 101 |
+
if "Na" in formula_dict and bc_types >= 2 and a_norm >= 1.0:
|
| 102 |
+
return True, "sodium_garnet_composition"
|
| 103 |
+
|
| 104 |
+
return False, "does_not_match_garnet_stoichiometry"
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def check_garnet_structure(structure):
|
| 108 |
+
"""Verify garnet topology from structure.
|
| 109 |
+
|
| 110 |
+
Strict checks:
|
| 111 |
+
1. Space group must be Ia-3d (230) or related garnet space group
|
| 112 |
+
2. Cubic lattice with a ≈ 11-13 Å (typical garnet range)
|
| 113 |
+
3. Reasonable number of atoms in unit cell (garnets have 80+ atoms/cell)
|
| 114 |
+
"""
|
| 115 |
+
sg_info = structure.get_space_group_info()
|
| 116 |
+
sg_symbol = str(sg_info[0]) if sg_info else ""
|
| 117 |
+
sg_number = int(sg_info[1]) if len(sg_info) > 1 else 0
|
| 118 |
+
|
| 119 |
+
# Check space group
|
| 120 |
+
if sg_number == 230:
|
| 121 |
+
return True
|
| 122 |
+
for known_sym in GARNET_SYMBOLS:
|
| 123 |
+
if known_sym in sg_symbol:
|
| 124 |
+
return True
|
| 125 |
+
|
| 126 |
+
# Garnets are cubic (a=b=c)
|
| 127 |
+
lattice = structure.lattice
|
| 128 |
+
if not (abs(lattice.a - lattice.b) / max(lattice.a, 0.01) < 0.05 and
|
| 129 |
+
abs(lattice.a - lattice.c) / max(lattice.a, 0.01) < 0.05):
|
| 130 |
+
return False
|
| 131 |
+
|
| 132 |
+
# Garnet lattice constant range
|
| 133 |
+
if not (10.5 < lattice.a < 13.5):
|
| 134 |
+
return False
|
| 135 |
+
|
| 136 |
+
# Garnets typically have 80-160 atoms in conventional cell
|
| 137 |
+
n_atoms = len(structure)
|
| 138 |
+
if n_atoms < 40:
|
| 139 |
+
return False
|
| 140 |
+
|
| 141 |
+
# Check for oxygen/anion content (garnets are oxides/sulfides)
|
| 142 |
+
has_anion = any(site.specie.symbol in GARNET_O_SITES for site in structure)
|
| 143 |
+
if not has_anion:
|
| 144 |
+
return False
|
| 145 |
+
|
| 146 |
+
# Check for A-site cations (Li, Na)
|
| 147 |
+
has_a_site = any(site.specie.symbol in GARNET_A_SITES for site in structure)
|
| 148 |
+
if not has_a_site:
|
| 149 |
+
return False
|
| 150 |
+
|
| 151 |
+
return True
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def main():
|
| 155 |
+
parser = argparse.ArgumentParser(description="Garnet family enrichment")
|
| 156 |
+
parser.add_argument("--dry-run", action="store_true", help="Don't save results")
|
| 157 |
+
parser.add_argument("--report-only", action="store_true", help="Generate report without modifying data")
|
| 158 |
+
parser.add_argument("--limit", type=int, default=None)
|
| 159 |
+
args = parser.parse_args()
|
| 160 |
+
|
| 161 |
+
BASE_DIR = Path(__file__).resolve().parent.parent
|
| 162 |
+
DATASET_PATH = BASE_DIR / "dataset"
|
| 163 |
+
|
| 164 |
+
print("=" * 60)
|
| 165 |
+
print(" GARNET FAMILY ENRICHMENT")
|
| 166 |
+
print(" Identifying missed garnet-type structures")
|
| 167 |
+
print("=" * 60)
|
| 168 |
+
|
| 169 |
+
print("\nLoading entries...")
|
| 170 |
+
t0 = time.time()
|
| 171 |
+
with open(DATASET_PATH / "entries_final_v3.json") as f:
|
| 172 |
+
all_entries = json.load(f)
|
| 173 |
+
print(f" {len(all_entries):,} entries ({time.time()-t0:.1f}s)")
|
| 174 |
+
|
| 175 |
+
if args.limit:
|
| 176 |
+
all_entries = all_entries[:args.limit]
|
| 177 |
+
print(f" Limited to {args.limit} entries")
|
| 178 |
+
|
| 179 |
+
# Phase 1: Composition-based screening
|
| 180 |
+
print(f"\n{'─' * 60}")
|
| 181 |
+
print(" Phase 1: Composition-based garnet screening")
|
| 182 |
+
print(f"{'─' * 60}")
|
| 183 |
+
|
| 184 |
+
current_garnet = [e for e in all_entries if e.get("sse_family") == "garnet"]
|
| 185 |
+
print(f" Currently tagged as garnet: {len(current_garnet)}")
|
| 186 |
+
|
| 187 |
+
garnet_candidates = []
|
| 188 |
+
for e in all_entries:
|
| 189 |
+
formula = e.get("formula", "")
|
| 190 |
+
formula_dict = parse_formula(formula)
|
| 191 |
+
is_match, reason = is_garnet_by_formula(formula_dict)
|
| 192 |
+
if is_match:
|
| 193 |
+
garnet_candidates.append((e, reason))
|
| 194 |
+
|
| 195 |
+
print(f" Composition-based garnet candidates: {len(garnet_candidates)}")
|
| 196 |
+
|
| 197 |
+
# Show top candidates by composition
|
| 198 |
+
cand_by_elements = defaultdict(list)
|
| 199 |
+
for e, reason in garnet_candidates:
|
| 200 |
+
has_li = "Li" in e.get("elements", [])
|
| 201 |
+
has_o = "O" in e.get("elements", [])
|
| 202 |
+
key = f"{'Li' if has_li else 'Na'}-{'O' if has_o else 'S'}"
|
| 203 |
+
cand_by_elements[key].append((e, reason))
|
| 204 |
+
|
| 205 |
+
for key, cands in sorted(cand_by_elements.items()):
|
| 206 |
+
print(f" {key}: {len(cands)} candidates")
|
| 207 |
+
for e, reason in cands[:3]:
|
| 208 |
+
print(f" - {e.get('formula', '?'):30s} {e.get('sse_family', '?'):15s} {e.get('space_group_symbol', ''):10s} [{reason}]")
|
| 209 |
+
|
| 210 |
+
# Phase 2: Structure-based verification for candidates
|
| 211 |
+
print(f"\n{'─' * 60}")
|
| 212 |
+
print(" Phase 2: Structure-based verification")
|
| 213 |
+
print(f"{'─' * 60}")
|
| 214 |
+
|
| 215 |
+
structure_confirmed = []
|
| 216 |
+
structure_rejected = []
|
| 217 |
+
|
| 218 |
+
for e, comp_reason in garnet_candidates:
|
| 219 |
+
if e.get("sse_family") == "garnet":
|
| 220 |
+
structure_confirmed.append(e)
|
| 221 |
+
continue
|
| 222 |
+
|
| 223 |
+
struct_json = e.get("structure_json")
|
| 224 |
+
if not struct_json:
|
| 225 |
+
structure_rejected.append((e, "no_structure"))
|
| 226 |
+
continue
|
| 227 |
+
|
| 228 |
+
import json as _json
|
| 229 |
+
from pymatgen.core import Structure
|
| 230 |
+
|
| 231 |
+
try:
|
| 232 |
+
struct_dict = _json.loads(struct_json)
|
| 233 |
+
structure = Structure.from_dict(struct_dict)
|
| 234 |
+
if check_garnet_structure(structure):
|
| 235 |
+
structure_confirmed.append(e)
|
| 236 |
+
else:
|
| 237 |
+
structure_rejected.append((e, "structure_mismatch"))
|
| 238 |
+
except Exception:
|
| 239 |
+
structure_rejected.append((e, "parse_error"))
|
| 240 |
+
|
| 241 |
+
print(f" Structure-confirmed garnets: {len(structure_confirmed)}")
|
| 242 |
+
print(f" Structure-rejected: {len(structure_rejected)}")
|
| 243 |
+
|
| 244 |
+
new_garnets = [e for e in structure_confirmed if e.get("sse_family") != "garnet"]
|
| 245 |
+
print(f" NEW garnets to reclassify: {len(new_garnets)}")
|
| 246 |
+
|
| 247 |
+
if new_garnets:
|
| 248 |
+
print(f"\n Top new garnet candidates:")
|
| 249 |
+
for e in sorted(new_garnets, key=lambda x: abs(x.get("formation_energy_per_atom", 0)))[:10]:
|
| 250 |
+
formula = e.get("formula", "?")
|
| 251 |
+
sg = e.get("space_group_symbol", "?")
|
| 252 |
+
fe = e.get("formation_energy_per_atom", 0)
|
| 253 |
+
print(f" {formula:30s} SG={sg:8s} FE={fe:+.3f} eV/atom")
|
| 254 |
+
|
| 255 |
+
# Phase 3: Reclassify
|
| 256 |
+
if not args.report_only and not args.dry_run and new_garnets:
|
| 257 |
+
print(f"\n{'─' * 60}")
|
| 258 |
+
print(" Phase 3: Reclassifying entries")
|
| 259 |
+
print(f"{'─' * 60}")
|
| 260 |
+
|
| 261 |
+
reclassified = 0
|
| 262 |
+
for e in new_garnets:
|
| 263 |
+
old_family = e.get("sse_family", "?")
|
| 264 |
+
e["sse_family"] = "garnet"
|
| 265 |
+
if "ssb_screening" in e:
|
| 266 |
+
e["ssb_screening"]["sse_family"] = "garnet"
|
| 267 |
+
reclassified += 1
|
| 268 |
+
|
| 269 |
+
print(f" Reclassified: {reclassified:,} entries to garnet")
|
| 270 |
+
|
| 271 |
+
# Save
|
| 272 |
+
output_path = DATASET_PATH / "entries_final_v3.json"
|
| 273 |
+
print(f" Writing to {output_path}...")
|
| 274 |
+
t_write = time.time()
|
| 275 |
+
with open(output_path, "w") as f:
|
| 276 |
+
json.dump(all_entries, f)
|
| 277 |
+
print(f" Done ({time.time()-t_write:.1f}s)")
|
| 278 |
+
|
| 279 |
+
elif args.dry_run:
|
| 280 |
+
print(f"\n (dry-run — no changes saved)")
|
| 281 |
+
|
| 282 |
+
# Phase 4: Report
|
| 283 |
+
print(f"\n{'─' * 60}")
|
| 284 |
+
print(" GARNET ENRICHMENT REPORT")
|
| 285 |
+
print(f"{'─' * 60}")
|
| 286 |
+
|
| 287 |
+
all_after = all_entries
|
| 288 |
+
garnet_after = [e for e in all_after if e.get("sse_family") == "garnet"]
|
| 289 |
+
print(f"\n Final garnet count: {len(garnet_after):,}")
|
| 290 |
+
print(f" (was {len(current_garnet):,} before enrichment)")
|
| 291 |
+
|
| 292 |
+
if garnet_after:
|
| 293 |
+
print(f"\n Sample of current garnet entries:")
|
| 294 |
+
for e in garnet_after[:5]:
|
| 295 |
+
print(f" {e.get('formula', '?'):35s} {e.get('source', '?'):10s} {e.get('tier', '?'):10s}")
|
| 296 |
+
|
| 297 |
+
# Recommendations for targeted acquisition
|
| 298 |
+
print(f"\n {'─' * 60}")
|
| 299 |
+
print(" TARGETED ACQUISITION RECOMMENDATIONS")
|
| 300 |
+
print(f" {'─' * 60}")
|
| 301 |
+
print(f"""
|
| 302 |
+
To reach SSB-credible garnet coverage (500+ entries):
|
| 303 |
+
|
| 304 |
+
1. Pull LLZO-family (Li7La3Zr2O12) variants from MP:
|
| 305 |
+
- Li7-3xAlxLa3Zr2O12 (Al-doped)
|
| 306 |
+
- Li6.5La3Zr1.5Ta0.5O12 (Ta-doped)
|
| 307 |
+
- Li6.4La3Zr1.4Ta0.6O12
|
| 308 |
+
|
| 309 |
+
2. Pull garnet structures from ICSD:
|
| 310 |
+
- All ICSD garnet entries with Li/Na
|
| 311 |
+
- Focus on Li-La-Zr-O, Li-Y-Zr-O, Li-Ca-Zr-O systems
|
| 312 |
+
|
| 313 |
+
3. Known academic collections:
|
| 314 |
+
- Garnet database from Ceder group publications
|
| 315 |
+
- MPContribs garnet entries
|
| 316 |
+
- Literature-mined garnet compositions
|
| 317 |
+
|
| 318 |
+
4. Consider computational expansion:
|
| 319 |
+
- Generate LLZO variants with dopant substitutions
|
| 320 |
+
- Run DFT on promising but uncalculated garnet compositions
|
| 321 |
+
""")
|
| 322 |
+
|
| 323 |
+
print("=" * 60)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
if __name__ == "__main__":
|
| 327 |
+
main()
|
scripts/extract_commercial_safe_edition.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Extract a Commercial-Safe edition of the dataset (MP + JARVIS only).
|
| 2 |
+
|
| 3 |
+
OQMD is non-commercial only, limiting use for commercial ML training.
|
| 4 |
+
This script creates a clearly-labeled subset containing only entries with
|
| 5 |
+
CC BY 4.0 (MP) and CC0 1.0 (JARVIS) licenses.
|
| 6 |
+
|
| 7 |
+
Outputs:
|
| 8 |
+
- dataset/commercial_safe_subset_v3.json: ~94,952 entries
|
| 9 |
+
- dataset/manifests/manifest_commercial_safe.json: checksums
|
| 10 |
+
|
| 11 |
+
Usage:
|
| 12 |
+
python scripts/extract_commercial_safe_edition.py
|
| 13 |
+
python scripts/extract_commercial_safe_edition.py --stats-only
|
| 14 |
+
python scripts/extract_commercial_safe_edition.py --output-dir /tmp
|
| 15 |
+
"""
|
| 16 |
+
import json, os, sys, hashlib, time, argparse
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
COMMERCIAL_LICENSES = {"CC-BY-4.0", "CC0-1.0"}
|
| 20 |
+
COMMERCIAL_SOURCES = {"mp", "jarvis"}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def main():
|
| 24 |
+
parser = argparse.ArgumentParser(description="Extract Commercial-Safe dataset edition")
|
| 25 |
+
parser.add_argument("--stats-only", action="store_true", help="Print stats only, no output")
|
| 26 |
+
parser.add_argument("--output-dir", type=str, default=None, help="Custom output directory")
|
| 27 |
+
args = parser.parse_args()
|
| 28 |
+
|
| 29 |
+
BASE_DIR = Path(__file__).resolve().parent.parent
|
| 30 |
+
DATASET_PATH = BASE_DIR / "dataset"
|
| 31 |
+
|
| 32 |
+
if args.output_dir:
|
| 33 |
+
OUTPUT_DIR = Path(args.output_dir)
|
| 34 |
+
else:
|
| 35 |
+
OUTPUT_DIR = DATASET_PATH
|
| 36 |
+
|
| 37 |
+
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 38 |
+
|
| 39 |
+
print("=" * 60)
|
| 40 |
+
print(" COMMERCIAL-SAFE EDITION EXTRACTION")
|
| 41 |
+
print(" Filtering entries by license: CC-BY-4.0 (MP), CC0-1.0 (JARVIS)")
|
| 42 |
+
print("=" * 60)
|
| 43 |
+
|
| 44 |
+
print("\nLoading entries...")
|
| 45 |
+
t0 = time.time()
|
| 46 |
+
with open(DATASET_PATH / "entries_final_v3.json") as f:
|
| 47 |
+
all_entries = json.load(f)
|
| 48 |
+
print(f" {len(all_entries):,} entries ({time.time()-t0:.1f}s)")
|
| 49 |
+
|
| 50 |
+
# Filter by license
|
| 51 |
+
commercial = []
|
| 52 |
+
oqmd_entries = []
|
| 53 |
+
for e in all_entries:
|
| 54 |
+
lic = e.get("license", "")
|
| 55 |
+
if lic in COMMERCIAL_LICENSES:
|
| 56 |
+
commercial.append(e)
|
| 57 |
+
else:
|
| 58 |
+
oqmd_entries.append(e)
|
| 59 |
+
|
| 60 |
+
print(f"\n Commercial-safe: {len(commercial):,} entries")
|
| 61 |
+
print(f" OQMD (non-commercial): {len(oqmd_entries):,} entries")
|
| 62 |
+
print(f" Commercial fraction: {len(commercial)/len(all_entries)*100:.1f}%")
|
| 63 |
+
|
| 64 |
+
# Stats by source
|
| 65 |
+
source_counts = {}
|
| 66 |
+
for e in commercial:
|
| 67 |
+
src = e.get("source", "unknown")
|
| 68 |
+
source_counts[src] = source_counts.get(src, 0) + 1
|
| 69 |
+
|
| 70 |
+
print(f"\n Commercial-safe source breakdown:")
|
| 71 |
+
for src, count in sorted(source_counts.items(), key=lambda x: -x[1]):
|
| 72 |
+
print(f" {src}: {count:,}")
|
| 73 |
+
|
| 74 |
+
# Stats by tier
|
| 75 |
+
tier_counts = {}
|
| 76 |
+
for e in commercial:
|
| 77 |
+
t = e.get("tier", "unknown")
|
| 78 |
+
tier_counts[t] = tier_counts.get(t, 0) + 1
|
| 79 |
+
|
| 80 |
+
print(f"\n Commercial-safe tier breakdown:")
|
| 81 |
+
for t, count in sorted(tier_counts.items(), key=lambda x: -x[1]):
|
| 82 |
+
print(f" {t}: {count:,}")
|
| 83 |
+
|
| 84 |
+
# Stats by SSE family
|
| 85 |
+
family_counts = {}
|
| 86 |
+
for e in commercial:
|
| 87 |
+
fam = e.get("sse_family", "unknown")
|
| 88 |
+
family_counts[fam] = family_counts.get(fam, 0) + 1
|
| 89 |
+
|
| 90 |
+
print(f"\n Commercial-safe SSE family breakdown:")
|
| 91 |
+
for fam, count in sorted(family_counts.items(), key=lambda x: -x[1])[:15]:
|
| 92 |
+
print(f" {fam}: {count:,}")
|
| 93 |
+
|
| 94 |
+
# Stats for OQMD battery/electrolyte entries (what users lose)
|
| 95 |
+
oqmd_battery = sum(1 for e in oqmd_entries if any(f in e.get("families", []) for f in
|
| 96 |
+
["sulfide_sse", "halide_sse", "layered_oxide"]))
|
| 97 |
+
oqmd_electrolyte = sum(1 for e in oqmd_entries if e.get("sse_family") not in ("none", "oxide"))
|
| 98 |
+
|
| 99 |
+
print(f"\n OQMD entries lost (not in commercial-safe):")
|
| 100 |
+
print(f" Battery-relevant families: {oqmd_battery:,}")
|
| 101 |
+
print(f" SSE-family tagged: {oqmd_electrolyte:,}")
|
| 102 |
+
|
| 103 |
+
if args.stats_only:
|
| 104 |
+
print(f"\n (stats only — no file written)")
|
| 105 |
+
return
|
| 106 |
+
|
| 107 |
+
# Write commercial-safe edition
|
| 108 |
+
output_path = OUTPUT_DIR / "commercial_safe_subset_v3.json"
|
| 109 |
+
print(f"\n Writing commercial-safe edition ({len(commercial):,} entries)...")
|
| 110 |
+
print(f" -> {output_path}")
|
| 111 |
+
|
| 112 |
+
t_write = time.time()
|
| 113 |
+
with open(output_path, "w") as f:
|
| 114 |
+
json.dump(commercial, f)
|
| 115 |
+
print(f" Done ({time.time()-t_write:.1f}s)")
|
| 116 |
+
|
| 117 |
+
# Compute SHA256
|
| 118 |
+
sha256 = hashlib.sha256()
|
| 119 |
+
with open(output_path, "rb") as f:
|
| 120 |
+
for chunk in iter(lambda: f.read(8192), b""):
|
| 121 |
+
sha256.update(chunk)
|
| 122 |
+
file_size = output_path.stat().st_size
|
| 123 |
+
|
| 124 |
+
print(f" SHA256: {sha256.hexdigest()}")
|
| 125 |
+
print(f" Size: {file_size/1024/1024:.1f} MB")
|
| 126 |
+
|
| 127 |
+
# Write manifest
|
| 128 |
+
manifest = {
|
| 129 |
+
"edition": "commercial_safe",
|
| 130 |
+
"description": "MP (CC-BY-4.0) + JARVIS (CC0-1.0) entries only. No OQMD.",
|
| 131 |
+
"total_entries": len(commercial),
|
| 132 |
+
"file": "commercial_safe_subset_v3.json",
|
| 133 |
+
"sha256": sha256.hexdigest(),
|
| 134 |
+
"size_bytes": file_size,
|
| 135 |
+
"sources": {src: count for src, count in source_counts.items()},
|
| 136 |
+
"created": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
manifest_path = OUTPUT_DIR / "manifests" / "manifest_commercial_safe.json"
|
| 140 |
+
manifest_path.parent.mkdir(parents=True, exist_ok=True)
|
| 141 |
+
with open(manifest_path, "w") as f:
|
| 142 |
+
json.dump(manifest, f, indent=2)
|
| 143 |
+
print(f" Manifest: {manifest_path}")
|
| 144 |
+
|
| 145 |
+
# Also generate battery and electrolyte subsets from commercial-safe
|
| 146 |
+
battery_edition = [e for e in commercial if any(
|
| 147 |
+
f in e.get("families", []) for f in
|
| 148 |
+
["sulfide_sse", "halide_sse", "layered_oxide", "garnet", "nasicon",
|
| 149 |
+
"perovskite", "anti_perovskite", "lisicon", "lGPS_type", "argyrodite",
|
| 150 |
+
"borohydride", "battery", "oxide"]) or e.get("sse_family") not in ("none",)]
|
| 151 |
+
|
| 152 |
+
battery_output = OUTPUT_DIR / "commercial_safe_battery_candidate_subset_v1.json"
|
| 153 |
+
print(f"\n Writing commercial-safe battery edition ({len(battery_edition):,} entries)...")
|
| 154 |
+
with open(battery_output, "w") as f:
|
| 155 |
+
json.dump(battery_edition, f)
|
| 156 |
+
print(f" -> {battery_output} ({time.time()-t_write:.1f}s)")
|
| 157 |
+
|
| 158 |
+
print(f"\n Manual filtering by license field is also supported:")
|
| 159 |
+
print(f' entries = [e for e in data if e["license"] in ("CC-BY-4.0", "CC0-1.0")]')
|
| 160 |
+
print("=" * 60)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
if __name__ == "__main__":
|
| 164 |
+
main()
|
scripts/generate_audit_reports.py
CHANGED
|
@@ -590,14 +590,14 @@ def gen_battery_audit(entries):
|
|
| 590 |
lines.append(f"| {c:7s} | {cnt:>7,} | {gold:>7,} |\n")
|
| 591 |
|
| 592 |
lines.append(h2("Electrolyte Subset"))
|
| 593 |
-
elec_path = AUDIT_DIR / "dataset/
|
| 594 |
if elec_path.exists():
|
| 595 |
with open(elec_path) as f:
|
| 596 |
elec = json.load(f)
|
| 597 |
lines.append(p(f"**Electrolyte subset:** {len(elec):,} entries (strict Gold, no OQMD)"))
|
| 598 |
|
| 599 |
lines.append(h2("Battery Subset"))
|
| 600 |
-
batt_path = AUDIT_DIR / "dataset/
|
| 601 |
if batt_path.exists():
|
| 602 |
with open(batt_path) as f:
|
| 603 |
batt = json.load(f)
|
|
@@ -781,8 +781,8 @@ def gen_release_audit(entries):
|
|
| 781 |
("SHA256 manifest", manifest.exists(), manifest),
|
| 782 |
("CHANGELOG", changelog.exists(), changelog),
|
| 783 |
("Final dataset", (AUDIT_DIR / "dataset/entries_final_v3.json").exists(), AUDIT_DIR / "dataset/entries_final_v3.json"),
|
| 784 |
-
("Battery subset", (AUDIT_DIR / "dataset/
|
| 785 |
-
("Electrolyte subset", (AUDIT_DIR / "dataset/
|
| 786 |
("Benchmark splits", (AUDIT_DIR / "dataset/splits").is_dir(), AUDIT_DIR / "dataset/splits"),
|
| 787 |
]
|
| 788 |
lines.append("| Artifact | Present |\n")
|
|
|
|
| 590 |
lines.append(f"| {c:7s} | {cnt:>7,} | {gold:>7,} |\n")
|
| 591 |
|
| 592 |
lines.append(h2("Electrolyte Subset"))
|
| 593 |
+
elec_path = AUDIT_DIR / "dataset/solid_electrolyte_candidate_subset_v1.json"
|
| 594 |
if elec_path.exists():
|
| 595 |
with open(elec_path) as f:
|
| 596 |
elec = json.load(f)
|
| 597 |
lines.append(p(f"**Electrolyte subset:** {len(elec):,} entries (strict Gold, no OQMD)"))
|
| 598 |
|
| 599 |
lines.append(h2("Battery Subset"))
|
| 600 |
+
batt_path = AUDIT_DIR / "dataset/battery_candidate_subset_v1.json"
|
| 601 |
if batt_path.exists():
|
| 602 |
with open(batt_path) as f:
|
| 603 |
batt = json.load(f)
|
|
|
|
| 781 |
("SHA256 manifest", manifest.exists(), manifest),
|
| 782 |
("CHANGELOG", changelog.exists(), changelog),
|
| 783 |
("Final dataset", (AUDIT_DIR / "dataset/entries_final_v3.json").exists(), AUDIT_DIR / "dataset/entries_final_v3.json"),
|
| 784 |
+
("Battery subset", (AUDIT_DIR / "dataset/battery_candidate_subset_v1.json").exists(), AUDIT_DIR / "dataset/battery_candidate_subset_v1.json"),
|
| 785 |
+
("Electrolyte subset", (AUDIT_DIR / "dataset/solid_electrolyte_candidate_subset_v1.json").exists(), AUDIT_DIR / "dataset/solid_electrolyte_candidate_subset_v1.json"),
|
| 786 |
("Benchmark splits", (AUDIT_DIR / "dataset/splits").is_dir(), AUDIT_DIR / "dataset/splits"),
|
| 787 |
]
|
| 788 |
lines.append("| Artifact | Present |\n")
|
scripts/generate_conductivity_splits.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Generate conductivity-stratified benchmark splits for SSE screening tasks.
|
| 2 |
+
|
| 3 |
+
Extends the existing frozen splits with conductivity-aware splits:
|
| 4 |
+
1. Conductivity held-out: hold out top 10% conductors by BVSE barrier
|
| 5 |
+
2. Composition held-out + conducitivity-aware: no formula overlap
|
| 6 |
+
3. Family-stratified: balanced by SSE family
|
| 7 |
+
|
| 8 |
+
Usage:
|
| 9 |
+
python scripts/generate_conductivity_splits.py # from existing splits + BVSE
|
| 10 |
+
python scripts/generate_conductivity_splits.py --min-barrier 0.0 # include all
|
| 11 |
+
python scripts/generate_conductivity_splits.py --dry-run # stats only
|
| 12 |
+
"""
|
| 13 |
+
import json, os, sys, time, argparse, random
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from collections import defaultdict
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
SEED = 42
|
| 19 |
+
SPLIT_DIR = "dataset/splits"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def main():
|
| 23 |
+
parser = argparse.ArgumentParser(description="Generate conductivity-stratified splits")
|
| 24 |
+
parser.add_argument("--min-barrier", type=float, default=0.0,
|
| 25 |
+
help="Minimum BVSE barrier to filter by (default: 0.0 = all)")
|
| 26 |
+
parser.add_argument("--dry-run", action="store_true")
|
| 27 |
+
parser.add_argument("--train-ratio", type=float, default=0.8)
|
| 28 |
+
parser.add_argument("--val-ratio", type=float, default=0.1)
|
| 29 |
+
parser.add_argument("--test-ratio", type=float, default=0.1)
|
| 30 |
+
args = parser.parse_args()
|
| 31 |
+
|
| 32 |
+
BASE_DIR = Path(__file__).resolve().parent.parent
|
| 33 |
+
DATASET_PATH = BASE_DIR / "dataset"
|
| 34 |
+
|
| 35 |
+
print("=" * 60)
|
| 36 |
+
print(" CONDUCTIVITY BENCHMARK SPLITS")
|
| 37 |
+
print(" Extending splits for SSE screening tasks")
|
| 38 |
+
print("=" * 60)
|
| 39 |
+
|
| 40 |
+
print("\nLoading entries...")
|
| 41 |
+
t0 = time.time()
|
| 42 |
+
with open(DATASET_PATH / "entries_final_v3.json") as f:
|
| 43 |
+
entries = json.load(f)
|
| 44 |
+
print(f" {len(entries):,} entries ({time.time()-t0:.1f}s)")
|
| 45 |
+
|
| 46 |
+
# Filter to entries with BVSE barrier data
|
| 47 |
+
ssb_entries = [e for e in entries if e.get("ssb_screening", {}).get("bvse_migration_barrier_eV") is not None]
|
| 48 |
+
print(f"\n Entries with BVSE barriers: {len(ssb_entries):,}")
|
| 49 |
+
|
| 50 |
+
if args.min_barrier > 0:
|
| 51 |
+
ssb_entries = [e for e in ssb_entries
|
| 52 |
+
if e["ssb_screening"]["bvse_migration_barrier_eV"] >= args.min_barrier]
|
| 53 |
+
print(f" After min-barrier {args.min_barrier:.1f} eV: {len(ssb_entries):,}")
|
| 54 |
+
|
| 55 |
+
if not ssb_entries:
|
| 56 |
+
print(" No entries with BVSE barriers found. Run compute_bvse_barriers.py first.")
|
| 57 |
+
return
|
| 58 |
+
|
| 59 |
+
random.seed(SEED)
|
| 60 |
+
np.random.seed(SEED)
|
| 61 |
+
|
| 62 |
+
splits = {}
|
| 63 |
+
|
| 64 |
+
# 1. Conductivity-stratified split (stratified by BVSE barrier percentile)
|
| 65 |
+
print(f"\n{'─' * 60}")
|
| 66 |
+
print(" 1. Conductivity-stratified split")
|
| 67 |
+
print(f"{'─' * 60}")
|
| 68 |
+
|
| 69 |
+
barriers = np.array([e["ssb_screening"]["bvse_migration_barrier_eV"] for e in ssb_entries])
|
| 70 |
+
percentiles = np.percentile(barriers, [33, 67])
|
| 71 |
+
|
| 72 |
+
low = [e for e in ssb_entries if e["ssb_screening"]["bvse_migration_barrier_eV"] <= percentiles[0]]
|
| 73 |
+
mid = [e for e in ssb_entries if percentiles[0] < e["ssb_screening"]["bvse_migration_barrier_eV"] <= percentiles[1]]
|
| 74 |
+
high = [e for e in ssb_entries if e["ssb_screening"]["bvse_migration_barrier_eV"] > percentiles[1]]
|
| 75 |
+
|
| 76 |
+
print(f" Low barrier (≤{percentiles[0]:.3f} eV): {len(low):,}")
|
| 77 |
+
print(f" Mid barrier ({percentiles[0]:.3f}-{percentiles[1]:.3f} eV): {len(mid):,}")
|
| 78 |
+
print(f" High barrier (≥{percentiles[1]:.3f} eV): {len(high):,}")
|
| 79 |
+
|
| 80 |
+
stratified_train, stratified_val, stratified_test = [], [], []
|
| 81 |
+
for pool in [low, mid, high]:
|
| 82 |
+
np.random.shuffle(pool)
|
| 83 |
+
n = len(pool)
|
| 84 |
+
n_train = int(n * args.train_ratio)
|
| 85 |
+
n_val = int(n * args.val_ratio)
|
| 86 |
+
stratified_train.extend(pool[:n_train])
|
| 87 |
+
stratified_val.extend(pool[n_train:n_train+n_val])
|
| 88 |
+
stratified_test.extend(pool[n_train+n_val:])
|
| 89 |
+
|
| 90 |
+
sorted_train = sorted(stratified_train, key=lambda e: e["ssb_screening"]["bvse_migration_barrier_eV"])
|
| 91 |
+
sorted_val = sorted(stratified_val, key=lambda e: e["ssb_screening"]["bvse_migration_barrier_eV"])
|
| 92 |
+
sorted_test = sorted(stratified_test, key=lambda e: e["ssb_screening"]["bvse_migration_barrier_eV"])
|
| 93 |
+
|
| 94 |
+
splits["conductivity_stratified"] = {
|
| 95 |
+
"train": [e["source_id"] + e.get("source", "") for e in sorted_train],
|
| 96 |
+
"val": [e["source_id"] + e.get("source", "") for e in sorted_val],
|
| 97 |
+
"test": [e["source_id"] + e.get("source", "") for e in sorted_test],
|
| 98 |
+
}
|
| 99 |
+
print(f" Train: {len(splits['conductivity_stratified']['train']):,}")
|
| 100 |
+
print(f" Val: {len(splits['conductivity_stratified']['val']):,}")
|
| 101 |
+
print(f" Test: {len(splits['conductivity_stratified']['test']):,}")
|
| 102 |
+
|
| 103 |
+
# 2. Family-stratified split (balanced by SSE family)
|
| 104 |
+
print(f"\n{'─' * 60}")
|
| 105 |
+
print(" 2. Family-stratified split")
|
| 106 |
+
print(f"{'─' * 60}")
|
| 107 |
+
|
| 108 |
+
families = defaultdict(list)
|
| 109 |
+
for e in ssb_entries:
|
| 110 |
+
fam = e.get("ssb_screening", {}).get("sse_family") or e.get("sse_family", "unknown")
|
| 111 |
+
families[fam].append(e)
|
| 112 |
+
|
| 113 |
+
family_counts = {fam: len(entries) for fam, entries in sorted(families.items(), key=lambda x: -len(x[1]))}
|
| 114 |
+
print(f" Families: {len(families)}")
|
| 115 |
+
for fam, count in list(family_counts.items())[:10]:
|
| 116 |
+
print(f" {fam:20s}: {count:,}")
|
| 117 |
+
|
| 118 |
+
family_train, family_val, family_test = [], [], []
|
| 119 |
+
for fam, pool in families.items():
|
| 120 |
+
np.random.shuffle(pool)
|
| 121 |
+
n = len(pool)
|
| 122 |
+
n_train = max(1, int(n * args.train_ratio))
|
| 123 |
+
n_val = max(1, int(n * args.val_ratio))
|
| 124 |
+
family_train.extend(pool[:n_train])
|
| 125 |
+
family_val.extend(pool[n_train:n_train+n_val])
|
| 126 |
+
family_test.extend(pool[n_train+n_val:])
|
| 127 |
+
|
| 128 |
+
splits["family_stratified_ssb"] = {
|
| 129 |
+
"train": [e["source_id"] + e.get("source", "") for e in family_train],
|
| 130 |
+
"val": [e["source_id"] + e.get("source", "") for e in family_val],
|
| 131 |
+
"test": [e["source_id"] + e.get("source", "") for e in family_test],
|
| 132 |
+
}
|
| 133 |
+
print(f" Train: {len(splits['family_stratified_ssb']['train']):,}")
|
| 134 |
+
print(f" Val: {len(splits['family_stratified_ssb']['val']):,}")
|
| 135 |
+
print(f" Test: {len(splits['family_stratified_ssb']['test']):,}")
|
| 136 |
+
|
| 137 |
+
# 3. Best-candidate held-out (hold out top-100 lowest-barrier entries for testing)
|
| 138 |
+
print(f"\n{'─' * 60}")
|
| 139 |
+
print(" 3. Best-candidate held-out split")
|
| 140 |
+
print(f"{'─' * 60}")
|
| 141 |
+
|
| 142 |
+
sorted_by_barrier = sorted(ssb_entries, key=lambda e: e["ssb_screening"]["bvse_migration_barrier_eV"])
|
| 143 |
+
top_k = min(500, len(sorted_by_barrier))
|
| 144 |
+
best_test = sorted_by_barrier[:top_k]
|
| 145 |
+
best_pool = sorted_by_barrier[top_k:]
|
| 146 |
+
|
| 147 |
+
np.random.shuffle(best_pool)
|
| 148 |
+
n_best_train = int(len(best_pool) * args.train_ratio)
|
| 149 |
+
n_best_val = int(len(best_pool) * args.val_ratio)
|
| 150 |
+
best_train = best_pool[:n_best_train]
|
| 151 |
+
best_val = best_pool[n_best_train:n_best_train+n_best_val]
|
| 152 |
+
|
| 153 |
+
splits["best_conductors_held_out"] = {
|
| 154 |
+
"train": [e["source_id"] + e.get("source", "") for e in best_train],
|
| 155 |
+
"val": [e["source_id"] + e.get("source", "") for e in best_val],
|
| 156 |
+
"test": [e["source_id"] + e.get("source", "") for e in best_test],
|
| 157 |
+
}
|
| 158 |
+
print(f" Test (top {top_k} conductors): {len(splits['best_conductors_held_out']['test']):,}")
|
| 159 |
+
print(f" Train: {len(splits['best_conductors_held_out']['train']):,}")
|
| 160 |
+
print(f" Val: {len(splits['best_conductors_held_out']['val']):,}")
|
| 161 |
+
|
| 162 |
+
# 4. Mobility class held-out (hold out entire mobility classes)
|
| 163 |
+
print(f"\n{'─' * 60}")
|
| 164 |
+
print(" 4. Mobility-class held-out split")
|
| 165 |
+
print(f"{'─' * 60}")
|
| 166 |
+
|
| 167 |
+
classes = defaultdict(list)
|
| 168 |
+
for e in ssb_entries:
|
| 169 |
+
cls = e["ssb_screening"].get("bvse_mobility_class", "unknown")
|
| 170 |
+
classes[cls].append(e)
|
| 171 |
+
|
| 172 |
+
for cls, pool in classes.items():
|
| 173 |
+
print(f" {cls:15s}: {len(pool):,}")
|
| 174 |
+
|
| 175 |
+
# Hold out superionic as test set (hardest generalization task)
|
| 176 |
+
if "superionic" in classes:
|
| 177 |
+
mob_test = classes["superionic"]
|
| 178 |
+
mob_pool = []
|
| 179 |
+
for cls, pool in classes.items():
|
| 180 |
+
if cls != "superionic":
|
| 181 |
+
mob_pool.extend(pool)
|
| 182 |
+
np.random.shuffle(mob_pool)
|
| 183 |
+
n_mob_train = int(len(mob_pool) * args.train_ratio)
|
| 184 |
+
n_mob_val = int(len(mob_pool) * args.val_ratio)
|
| 185 |
+
mob_train = mob_pool[:n_mob_train]
|
| 186 |
+
mob_val = mob_pool[n_mob_train:n_mob_train+n_mob_val]
|
| 187 |
+
|
| 188 |
+
splits["mobility_class_held_out"] = {
|
| 189 |
+
"train": [e["source_id"] + e.get("source", "") for e in mob_train],
|
| 190 |
+
"val": [e["source_id"] + e.get("source", "") for e in mob_val],
|
| 191 |
+
"test": [e["source_id"] + e.get("source", "") for e in mob_test],
|
| 192 |
+
}
|
| 193 |
+
print(f"\n Hold-out class: superionic ({len(mob_test):,} entries)")
|
| 194 |
+
print(f" Train: {len(mob_train):,}, Val: {len(mob_val):,}")
|
| 195 |
+
else:
|
| 196 |
+
print(" No superionic entries found for held-out split.")
|
| 197 |
+
|
| 198 |
+
# Save splits
|
| 199 |
+
if not args.dry_run:
|
| 200 |
+
output_dir = BASE_DIR / SPLIT_DIR / "ssb"
|
| 201 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 202 |
+
|
| 203 |
+
for split_name, split_data in splits.items():
|
| 204 |
+
output_path = output_dir / f"{split_name}.json"
|
| 205 |
+
|
| 206 |
+
# Convert to index-based splits
|
| 207 |
+
entry_indices = {}
|
| 208 |
+
for i, e in enumerate(entries):
|
| 209 |
+
key = e["source_id"] + e.get("source", "")
|
| 210 |
+
entry_indices[key] = i
|
| 211 |
+
|
| 212 |
+
index_split = {
|
| 213 |
+
"train": [entry_indices[k] for k in split_data["train"] if k in entry_indices],
|
| 214 |
+
"val": [entry_indices[k] for k in split_data["val"] if k in entry_indices],
|
| 215 |
+
"test": [entry_indices[k] for k in split_data["test"] if k in entry_indices],
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
with open(output_path, "w") as f:
|
| 219 |
+
json.dump(index_split, f, indent=2)
|
| 220 |
+
print(f"\n Saved: {output_path}")
|
| 221 |
+
print(f" Train: {len(index_split['train']):,}")
|
| 222 |
+
print(f" Val: {len(index_split['val']):,}")
|
| 223 |
+
print(f" Test: {len(index_split['test']):,}")
|
| 224 |
+
|
| 225 |
+
# Summary
|
| 226 |
+
print(f"\n{'─' * 60}")
|
| 227 |
+
print(" SPLIT SUMMARY")
|
| 228 |
+
print(f"{'─' * 60}")
|
| 229 |
+
for split_name in splits:
|
| 230 |
+
data = splits[split_name]
|
| 231 |
+
print(f" {split_name:35s}: train={len(data['train']):,} val={len(data['val']):,} test={len(data['test']):,}")
|
| 232 |
+
|
| 233 |
+
else:
|
| 234 |
+
print(f"\n (dry-run — no files written)")
|
| 235 |
+
|
| 236 |
+
print("=" * 60)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
if __name__ == "__main__":
|
| 240 |
+
main()
|
scripts/integrate_experimental_data.py
ADDED
|
@@ -0,0 +1,440 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Integrate experimental Li solid-electrolyte conductivity data.
|
| 2 |
+
|
| 3 |
+
Two separate, independently curated databases are supported:
|
| 4 |
+
|
| 5 |
+
1. **Hargreaves et al. 2023** — npj Computational Materials
|
| 6 |
+
~820 entries, 403 compositions, 214 sources
|
| 7 |
+
https://doi.org/10.1038/s41524-023-01137-3
|
| 8 |
+
|
| 9 |
+
2. **OBELiX (Therrien et al. 2025, NRC-Mila)**
|
| 10 |
+
~599 entries, curated with leakage-resistant splits
|
| 11 |
+
pip install obelix-data
|
| 12 |
+
https://github.com/nrc-mila/OBELiX
|
| 13 |
+
|
| 14 |
+
These are complementary — not duplicates — and are tracked as two separate
|
| 15 |
+
provenance sources with distinct citations.
|
| 16 |
+
|
| 17 |
+
Usage:
|
| 18 |
+
# Hargreaves 2023
|
| 19 |
+
python scripts/integrate_experimental_data.py --ransom-path path/to/ransom2023.csv
|
| 20 |
+
|
| 21 |
+
# OBELiX via pip package
|
| 22 |
+
python scripts/integrate_experimental_data.py --obelix
|
| 23 |
+
|
| 24 |
+
# Both
|
| 25 |
+
python scripts/integrate_experimental_data.py --ransom-path ... --obelix
|
| 26 |
+
|
| 27 |
+
# Dry run
|
| 28 |
+
python scripts/integrate_experimental_data.py --dry-run
|
| 29 |
+
"""
|
| 30 |
+
import json, os, sys, time, argparse, csv, io, re, subprocess
|
| 31 |
+
from pathlib import Path
|
| 32 |
+
from collections import defaultdict
|
| 33 |
+
import numpy as np
|
| 34 |
+
import pandas as pd
|
| 35 |
+
import warnings
|
| 36 |
+
warnings.filterwarnings("ignore")
|
| 37 |
+
|
| 38 |
+
WIDTH = 60
|
| 39 |
+
|
| 40 |
+
RANSOM_URLS = [
|
| 41 |
+
"https://raw.githubusercontent.com/nrc-cnrc/ransom2023-conductivity/main/data/conductivity_database.csv",
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
HARGREAVES_DOI = "https://doi.org/10.1038/s41524-022-00951-z"
|
| 45 |
+
OBELIX_DOI = "https://github.com/nrc-mila/OBELiX"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def parse_formula(formula):
|
| 49 |
+
parts = re.findall(r'([A-Z][a-z]*)(\d*\.?\d*)', formula)
|
| 50 |
+
return {el: float(cnt) if cnt else 1.0 for el, cnt in parts}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def formula_similarity(f1, f2):
|
| 54 |
+
d1 = parse_formula(f1)
|
| 55 |
+
d2 = parse_formula(f2)
|
| 56 |
+
if set(d1.keys()) != set(d2.keys()):
|
| 57 |
+
return False
|
| 58 |
+
total1, total2 = sum(d1.values()), sum(d2.values())
|
| 59 |
+
for el in d1:
|
| 60 |
+
r1 = d1[el] / total1
|
| 61 |
+
r2 = d2[el] / total2
|
| 62 |
+
if abs(r1 - r2) > 0.05:
|
| 63 |
+
return False
|
| 64 |
+
return True
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def try_fetch_ransom():
|
| 68 |
+
"""Try to download Hargreaves 2023 database."""
|
| 69 |
+
import urllib.request
|
| 70 |
+
for url in RANSOM_URLS:
|
| 71 |
+
try:
|
| 72 |
+
req = urllib.request.Request(url, headers={"User-Agent": "Scandium-Labs/1.0"})
|
| 73 |
+
with urllib.request.urlopen(req, timeout=30) as resp:
|
| 74 |
+
data = resp.read().decode("utf-8")
|
| 75 |
+
print(f" Downloaded {len(data):,} bytes")
|
| 76 |
+
return data
|
| 77 |
+
except Exception as e:
|
| 78 |
+
print(f" Failed: {str(e)[:80]}")
|
| 79 |
+
return None
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def try_fetch_obelix_package():
|
| 83 |
+
"""Try to install obelix-data package and load data."""
|
| 84 |
+
try:
|
| 85 |
+
import obelix
|
| 86 |
+
ob = obelix.OBELiX(data_path="/tmp/obelix_rawdata", no_cifs=True)
|
| 87 |
+
n = len(ob.dataframe)
|
| 88 |
+
print(f" OBELiX package loaded: {n} entries")
|
| 89 |
+
return ob
|
| 90 |
+
except ImportError:
|
| 91 |
+
print(" obelix-data not installed. Attempting pip install...")
|
| 92 |
+
result = subprocess.run(
|
| 93 |
+
[sys.executable, "-m", "pip", "install", "obelix-data"],
|
| 94 |
+
capture_output=True, text=True, timeout=60
|
| 95 |
+
)
|
| 96 |
+
if result.returncode == 0:
|
| 97 |
+
try:
|
| 98 |
+
import obelix
|
| 99 |
+
ob = obelix.OBELiX(data_path="/tmp/obelix_rawdata", no_cifs=True)
|
| 100 |
+
n = len(ob.dataframe)
|
| 101 |
+
print(f" OBELiX installed and loaded: {n} entries")
|
| 102 |
+
return ob
|
| 103 |
+
except Exception as e:
|
| 104 |
+
print(f" Load failed after install: {e}")
|
| 105 |
+
return None
|
| 106 |
+
else:
|
| 107 |
+
print(f" Install failed: {result.stderr[-200:]}")
|
| 108 |
+
return None
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def parse_ransom_csv(csv_data):
|
| 112 |
+
"""Parse Hargreaves 2023 CSV into entry dicts."""
|
| 113 |
+
reader = csv.DictReader(io.StringIO(csv_data))
|
| 114 |
+
entries = []
|
| 115 |
+
for i, row in enumerate(reader):
|
| 116 |
+
entry = {
|
| 117 |
+
"source": "Hargreaves2023",
|
| 118 |
+
"source_id": f"Hargreaves2023-{i:04d}",
|
| 119 |
+
"is_experimental": True,
|
| 120 |
+
"experimental_database": "Hargreaves2023",
|
| 121 |
+
"provenance": {
|
| 122 |
+
"source": "Hargreaves2023",
|
| 123 |
+
"source_id": f"Hargreaves2023-{i:04d}",
|
| 124 |
+
"doi": HARGREAVES_DOI,
|
| 125 |
+
"integrated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
| 126 |
+
},
|
| 127 |
+
}
|
| 128 |
+
formula = row.get("Formula", row.get("formula", "")).strip()
|
| 129 |
+
if formula:
|
| 130 |
+
entry["formula"] = formula
|
| 131 |
+
entry["structured_formula"] = formula
|
| 132 |
+
entry["elements"] = list(parse_formula(formula).keys())
|
| 133 |
+
entry["carrier_elements"] = ["Li"]
|
| 134 |
+
|
| 135 |
+
for field in ["Conductivity_S_cm", "conductivity_S_cm", "Conductivity (S/cm)"]:
|
| 136 |
+
val = row.get(field, "").strip()
|
| 137 |
+
if val:
|
| 138 |
+
try:
|
| 139 |
+
entry["conductivity_S_cm"] = float(val)
|
| 140 |
+
except ValueError:
|
| 141 |
+
pass
|
| 142 |
+
|
| 143 |
+
for field in ["Ea_eV", "activation_energy_eV", "Activation energy (eV)"]:
|
| 144 |
+
val = row.get(field, "").strip()
|
| 145 |
+
if val:
|
| 146 |
+
try:
|
| 147 |
+
entry["activation_energy_eV"] = float(val)
|
| 148 |
+
except ValueError:
|
| 149 |
+
pass
|
| 150 |
+
|
| 151 |
+
for field in ["Temperature_K", "temperature_K", "Temperature (K)"]:
|
| 152 |
+
val = row.get(field, "").strip()
|
| 153 |
+
if val:
|
| 154 |
+
try:
|
| 155 |
+
entry["temperature_K"] = float(val)
|
| 156 |
+
except ValueError:
|
| 157 |
+
pass
|
| 158 |
+
|
| 159 |
+
ref = row.get("Reference", row.get("reference", "")).strip()
|
| 160 |
+
if ref:
|
| 161 |
+
entry["reference"] = ref
|
| 162 |
+
entry["provenance"]["experimental_reference"] = ref
|
| 163 |
+
|
| 164 |
+
entries.append(entry)
|
| 165 |
+
|
| 166 |
+
return entries
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def parse_obelix_via_package(obelix_obj):
|
| 170 |
+
"""Parse OBELiX data via pandas DataFrame."""
|
| 171 |
+
entries = []
|
| 172 |
+
try:
|
| 173 |
+
df = obelix_obj.dataframe
|
| 174 |
+
for idx, row in df.iterrows():
|
| 175 |
+
formula = str(row.get("Reduced Composition", ""))
|
| 176 |
+
true_comp = str(row.get("True Composition", ""))
|
| 177 |
+
conductivity = row.get("Ionic conductivity (S cm-1)")
|
| 178 |
+
doi = str(row.get("DOI", ""))
|
| 179 |
+
family = str(row.get("Family", ""))
|
| 180 |
+
icsd = row.get("ICSD ID")
|
| 181 |
+
sg = str(row.get("Space group", ""))
|
| 182 |
+
|
| 183 |
+
entry = {
|
| 184 |
+
"source": "OBELiX",
|
| 185 |
+
"source_id": f"OBELiX-{idx}",
|
| 186 |
+
"is_experimental": True,
|
| 187 |
+
"experimental_database": "OBELiX_Therrien2025",
|
| 188 |
+
"formula": formula,
|
| 189 |
+
"structured_formula": true_comp if (true_comp and true_comp != "nan") else formula,
|
| 190 |
+
"elements": list(parse_formula(formula).keys()) if formula else [],
|
| 191 |
+
"carrier_elements": ["Li"],
|
| 192 |
+
"conductivity_S_cm": float(conductivity) if pd.notna(conductivity) else None,
|
| 193 |
+
"space_group": sg if sg != "nan" else "",
|
| 194 |
+
"sse_family": family if family != "nan" else "",
|
| 195 |
+
"reference": doi if doi != "nan" else "",
|
| 196 |
+
"provenance": {
|
| 197 |
+
"source": "OBELiX_Therrien2025",
|
| 198 |
+
"source_id": f"OBELiX-{idx}",
|
| 199 |
+
"doi": "https://github.com/nrc-mila/OBELiX",
|
| 200 |
+
"icsd_id": str(icsd) if pd.notna(icsd) else "",
|
| 201 |
+
"integrated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
| 202 |
+
},
|
| 203 |
+
}
|
| 204 |
+
entries.append(entry)
|
| 205 |
+
except Exception as e:
|
| 206 |
+
print(f" OBELiX DataFrame parse error: {e}")
|
| 207 |
+
|
| 208 |
+
return entries
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def cross_reference_and_add(exp_entries, all_dataset_entries):
|
| 212 |
+
"""Cross-reference experimental entries with the existing dataset."""
|
| 213 |
+
formula_index = defaultdict(list)
|
| 214 |
+
for e in all_dataset_entries:
|
| 215 |
+
sf = e.get("structured_formula", e.get("formula", ""))
|
| 216 |
+
formula_index[sf].append(e)
|
| 217 |
+
|
| 218 |
+
matched = 0
|
| 219 |
+
unmatched = 0
|
| 220 |
+
conductivity_added = 0
|
| 221 |
+
new_entries = []
|
| 222 |
+
|
| 223 |
+
for exp_e in exp_entries:
|
| 224 |
+
exp_formula = exp_e.get("formula", "")
|
| 225 |
+
matched_entries = formula_index.get(exp_formula, [])
|
| 226 |
+
|
| 227 |
+
if not matched_entries:
|
| 228 |
+
for sf, existing in formula_index.items():
|
| 229 |
+
if formula_similarity(exp_formula, sf):
|
| 230 |
+
matched_entries = existing
|
| 231 |
+
break
|
| 232 |
+
|
| 233 |
+
db_name = exp_e.get("experimental_database", "unknown")
|
| 234 |
+
|
| 235 |
+
if matched_entries:
|
| 236 |
+
matched += 1
|
| 237 |
+
for existing_e in matched_entries:
|
| 238 |
+
if "ssb_screening" not in existing_e:
|
| 239 |
+
existing_e["ssb_screening"] = {}
|
| 240 |
+
|
| 241 |
+
cond = exp_e.get("conductivity_S_cm")
|
| 242 |
+
ea = exp_e.get("activation_energy_eV")
|
| 243 |
+
|
| 244 |
+
if cond is not None:
|
| 245 |
+
existing_e["ssb_screening"]["estimated_ionic_conductivity_S_cm"] = cond
|
| 246 |
+
existing_e["ssb_screening"]["conductivity_source"] = f"experimental_{db_name}"
|
| 247 |
+
conductivity_added += 1
|
| 248 |
+
|
| 249 |
+
if ea is not None:
|
| 250 |
+
existing_e["ssb_screening"]["experimental_activation_energy_eV"] = ea
|
| 251 |
+
|
| 252 |
+
existing_e["is_experimental"] = True
|
| 253 |
+
if "provenance" not in existing_e:
|
| 254 |
+
existing_e["provenance"] = {}
|
| 255 |
+
existing_e["provenance"]["experimental_confirmed"] = True
|
| 256 |
+
existing_e["provenance"]["experimental_database"] = db_name
|
| 257 |
+
existing_e["provenance"]["experimental_reference"] = exp_e.get("reference", "")
|
| 258 |
+
else:
|
| 259 |
+
unmatched += 1
|
| 260 |
+
new_entry = {
|
| 261 |
+
"source": exp_e.get("source", "experimental"),
|
| 262 |
+
"source_id": exp_e.get("source_id", f"exp-{unmatched}"),
|
| 263 |
+
"formula": exp_formula,
|
| 264 |
+
"structured_formula": exp_formula,
|
| 265 |
+
"elements": exp_e.get("elements", []),
|
| 266 |
+
"nsites": len(exp_e.get("elements", [])),
|
| 267 |
+
"band_gap": None,
|
| 268 |
+
"formation_energy_per_atom": None,
|
| 269 |
+
"energy_above_hull": None,
|
| 270 |
+
"is_experimental": True,
|
| 271 |
+
"families": ["experimental_SSE"],
|
| 272 |
+
"sse_family": "experimental",
|
| 273 |
+
"mobile_ion": "Li",
|
| 274 |
+
"carrier_elements": ["Li"],
|
| 275 |
+
"tier": "experimental_gold",
|
| 276 |
+
"quality_score": 95,
|
| 277 |
+
"quality_flags": ["experimental_data", "has_conductivity"],
|
| 278 |
+
"ssb_screening": {
|
| 279 |
+
"estimated_ionic_conductivity_S_cm": exp_e.get("conductivity_S_cm"),
|
| 280 |
+
"conductivity_source": f"experimental_{db_name}",
|
| 281 |
+
"experimental_activation_energy_eV": exp_e.get("activation_energy_eV"),
|
| 282 |
+
"measurement_temperature_K": exp_e.get("temperature_K"),
|
| 283 |
+
"mobile_ion": "Li",
|
| 284 |
+
"sse_family": "experimental",
|
| 285 |
+
"gates_passed": ["experimental"],
|
| 286 |
+
"sse_candidate_score": 100,
|
| 287 |
+
},
|
| 288 |
+
"provenance": exp_e.get("provenance", {}),
|
| 289 |
+
"license": "CC-BY-4.0",
|
| 290 |
+
}
|
| 291 |
+
new_entries.append(new_entry)
|
| 292 |
+
|
| 293 |
+
return matched, unmatched, conductivity_added, new_entries
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def main():
|
| 297 |
+
parser = argparse.ArgumentParser(description="Integrate experimental conductivity data")
|
| 298 |
+
parser.add_argument("--ransom-path", type=str, default=None,
|
| 299 |
+
help="Path to Hargreaves 2023 CSV file")
|
| 300 |
+
parser.add_argument("--obelix", action="store_true",
|
| 301 |
+
help="Try to load OBELiX via obelix-data package")
|
| 302 |
+
parser.add_argument("--dry-run", action="store_true")
|
| 303 |
+
parser.add_argument("--cross-ref-only", action="store_true")
|
| 304 |
+
args = parser.parse_args()
|
| 305 |
+
|
| 306 |
+
if not args.ransom_path and not args.obelix:
|
| 307 |
+
print("Specify at least one data source:")
|
| 308 |
+
print(" --ransom-path <file.csv> Hargreaves et al. 2023 database")
|
| 309 |
+
print(" --obelix OBELiX via obelix-data package")
|
| 310 |
+
sys.exit(1)
|
| 311 |
+
|
| 312 |
+
BASE_DIR = Path(__file__).resolve().parent.parent
|
| 313 |
+
DATASET_PATH = BASE_DIR / "dataset"
|
| 314 |
+
|
| 315 |
+
print("=" * WIDTH)
|
| 316 |
+
print(" EXPERIMENTAL DATA INTEGRATION")
|
| 317 |
+
print("=" * WIDTH)
|
| 318 |
+
|
| 319 |
+
all_experimental = []
|
| 320 |
+
|
| 321 |
+
# --- Hargreaves 2023 ---
|
| 322 |
+
if args.ransom_path:
|
| 323 |
+
source_label = "Hargreaves et al. 2023 (npj Comput. Mater.)"
|
| 324 |
+
print(f"\n [{source_label}]")
|
| 325 |
+
|
| 326 |
+
ransom_data = None
|
| 327 |
+
path = Path(args.ransom_path)
|
| 328 |
+
if path.exists():
|
| 329 |
+
with open(path) as f:
|
| 330 |
+
ransom_data = f.read()
|
| 331 |
+
print(f" Loaded from {path}")
|
| 332 |
+
else:
|
| 333 |
+
print(f" File not found: {path}")
|
| 334 |
+
print(" Attempting download...")
|
| 335 |
+
ransom_data = try_fetch_ransom()
|
| 336 |
+
|
| 337 |
+
if ransom_data:
|
| 338 |
+
entries = parse_ransom_csv(ransom_data)
|
| 339 |
+
print(f" Parsed {len(entries):,} entries")
|
| 340 |
+
for e in entries:
|
| 341 |
+
e["experimental_database"] = "Hargreaves2023"
|
| 342 |
+
all_experimental.extend(entries)
|
| 343 |
+
with_cond = sum(1 for e in entries if e.get("conductivity_S_cm") is not None)
|
| 344 |
+
with_ea = sum(1 for e in entries if e.get("activation_energy_eV") is not None)
|
| 345 |
+
print(f" With conductivity: {with_cond}")
|
| 346 |
+
print(f" With activation energy: {with_ea}")
|
| 347 |
+
else:
|
| 348 |
+
print(f" Could not load Hargreaves 2023 data.")
|
| 349 |
+
print(f" Download manually from: {HARGREAVES_DOI}")
|
| 350 |
+
|
| 351 |
+
# --- OBELiX Therrien 2025 ---
|
| 352 |
+
if args.obelix:
|
| 353 |
+
source_label = "OBELiX (Therrien et al. 2025, NRC-Mila)"
|
| 354 |
+
print(f"\n [{source_label}]")
|
| 355 |
+
print(" Attempting obelix-data package...")
|
| 356 |
+
ob_data = try_fetch_obelix_package()
|
| 357 |
+
if ob_data is not None:
|
| 358 |
+
entries = parse_obelix_via_package(ob_data)
|
| 359 |
+
print(f" Parsed {len(entries):,} entries")
|
| 360 |
+
for e in entries:
|
| 361 |
+
e["experimental_database"] = "OBELiX_Therrien2025"
|
| 362 |
+
all_experimental.extend(entries)
|
| 363 |
+
with_cond = sum(1 for e in entries if e.get("conductivity_S_cm") is not None)
|
| 364 |
+
with_ea = sum(1 for e in entries if e.get("activation_energy_eV") is not None)
|
| 365 |
+
print(f" With conductivity: {with_cond}")
|
| 366 |
+
print(f" With activation energy: {with_ea}")
|
| 367 |
+
else:
|
| 368 |
+
print(f" Could not load OBELiX via package.")
|
| 369 |
+
print(f" Try: pip install obelix-data")
|
| 370 |
+
print(f" Or: https://github.com/nrc-mila/OBELiX")
|
| 371 |
+
|
| 372 |
+
if not all_experimental:
|
| 373 |
+
print("\n No experimental data loaded. Nothing to integrate.")
|
| 374 |
+
sys.exit(1)
|
| 375 |
+
|
| 376 |
+
# --- Cross-reference with existing dataset ---
|
| 377 |
+
print(f"\n Loading Scandium-Dataset...")
|
| 378 |
+
t0 = time.time()
|
| 379 |
+
with open(DATASET_PATH / "entries_final_v3.json") as f:
|
| 380 |
+
all_entries = json.load(f)
|
| 381 |
+
print(f" {len(all_entries):,} entries ({time.time()-t0:.1f}s)")
|
| 382 |
+
|
| 383 |
+
print(f"\n{'─' * WIDTH}")
|
| 384 |
+
print(" Cross-referencing...")
|
| 385 |
+
print(f"{'─' * WIDTH}")
|
| 386 |
+
|
| 387 |
+
matched, unmatched, conductivity_added, new_entries = cross_reference_and_add(
|
| 388 |
+
all_experimental, all_entries
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
print(f"\n Results:")
|
| 392 |
+
print(f" Matched existing entries: {matched}")
|
| 393 |
+
print(f" Unmatched (new compositions): {unmatched}")
|
| 394 |
+
print(f" Conductivity labels added: {conductivity_added}")
|
| 395 |
+
print(f" New experimental entries: {len(new_entries)}")
|
| 396 |
+
|
| 397 |
+
if new_entries:
|
| 398 |
+
cond_entries = [(e.get("formula", "?"),
|
| 399 |
+
e.get("ssb_screening", {}).get("estimated_ionic_conductivity_S_cm"))
|
| 400 |
+
for e in new_entries
|
| 401 |
+
if e.get("ssb_screening", {}).get("estimated_ionic_conductivity_S_cm")]
|
| 402 |
+
for formula, cond in sorted(cond_entries, key=lambda x: -abs(x[1] or 0))[:5]:
|
| 403 |
+
if cond:
|
| 404 |
+
print(f" {formula:30s} σ={cond:.2e} S/cm")
|
| 405 |
+
|
| 406 |
+
if not args.dry_run:
|
| 407 |
+
if new_entries:
|
| 408 |
+
all_entries.extend(new_entries)
|
| 409 |
+
print(f"\n Added {len(new_entries):,} experimental entries")
|
| 410 |
+
|
| 411 |
+
output_path = DATASET_PATH / "entries_final_v3.json"
|
| 412 |
+
print(f" Writing to {output_path}...")
|
| 413 |
+
t_write = time.time()
|
| 414 |
+
with open(output_path, "w") as f:
|
| 415 |
+
json.dump(all_entries, f)
|
| 416 |
+
print(f" Done ({time.time()-t_write:.1f}s)")
|
| 417 |
+
|
| 418 |
+
experimental_count = sum(1 for e in all_entries if e.get("is_experimental"))
|
| 419 |
+
with_conductivity_total = sum(
|
| 420 |
+
1 for e in all_entries
|
| 421 |
+
if e.get("ssb_screening", {}).get("estimated_ionic_conductivity_S_cm")
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
print(f"\n{'─' * WIDTH}")
|
| 425 |
+
print(" INTEGRATION SUMMARY")
|
| 426 |
+
print(f"{'─' * WIDTH}")
|
| 427 |
+
db_sources = set(e.get("experimental_database", "unknown") for e in all_experimental)
|
| 428 |
+
for db in sorted(db_sources):
|
| 429 |
+
count = sum(1 for e in all_experimental if e.get("experimental_database") == db)
|
| 430 |
+
print(f" {db}: {count} entries")
|
| 431 |
+
print(f" Total experimental entries in dataset: {experimental_count}")
|
| 432 |
+
print(f" Entries with conductivity labels: {with_conductivity_total}")
|
| 433 |
+
else:
|
| 434 |
+
print(f"\n (dry-run)")
|
| 435 |
+
|
| 436 |
+
print("=" * WIDTH)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
if __name__ == "__main__":
|
| 440 |
+
main()
|
scripts/merge_obelix.py
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fast OBELiX merge using direct PyArrow table manipulation.
|
| 2 |
+
|
| 3 |
+
Avoids the scan() bottleneck by building a formula index from the
|
| 4 |
+
Parquet columns directly and applying all updates at once.
|
| 5 |
+
"""
|
| 6 |
+
import json, sys, time
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from collections import defaultdict
|
| 9 |
+
|
| 10 |
+
BASE_DIR = Path(__file__).resolve().parent.parent
|
| 11 |
+
sys.path.insert(0, str(BASE_DIR / "dataset"))
|
| 12 |
+
from dataset_store import _encode_value, _decode_value, SCALAR_COLUMNS, JSON_STRING_FIELDS
|
| 13 |
+
|
| 14 |
+
import pyarrow.parquet as pq
|
| 15 |
+
import pyarrow as pa
|
| 16 |
+
import pandas as pd
|
| 17 |
+
|
| 18 |
+
PARQUET_PATH = BASE_DIR / "dataset" / "entries_v3.parquet"
|
| 19 |
+
INDEX_PATH = BASE_DIR / "dataset" / "entries_v3.index.json"
|
| 20 |
+
OBELIX_DATA_PATH = "/tmp/obelix_rawdata"
|
| 21 |
+
|
| 22 |
+
WIDTH = 60
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def load_obelix():
|
| 26 |
+
import obelix
|
| 27 |
+
ob = obelix.OBELiX(data_path=OBELIX_DATA_PATH, no_cifs=True)
|
| 28 |
+
df = ob.dataframe
|
| 29 |
+
return df
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def format_obelix_entry(row, seq_id=0):
|
| 33 |
+
"""Convert OBELiX DataFrame row to a dataset entry dict."""
|
| 34 |
+
formula = str(row.get("Reduced Composition", ""))
|
| 35 |
+
true_comp = str(row.get("True Composition", ""))
|
| 36 |
+
conductivity = row.get("Ionic conductivity (S cm-1)")
|
| 37 |
+
if pd.notna(conductivity):
|
| 38 |
+
conductivity = float(conductivity)
|
| 39 |
+
else:
|
| 40 |
+
conductivity = None
|
| 41 |
+
doi = str(row.get("DOI", ""))
|
| 42 |
+
family = str(row.get("Family", ""))
|
| 43 |
+
sg = str(row.get("Space group", ""))
|
| 44 |
+
icsd = row.get("ICSD ID")
|
| 45 |
+
|
| 46 |
+
entry = {
|
| 47 |
+
"source": "OBELiX",
|
| 48 |
+
"source_id": f"OBELiX-{seq_id:04d}",
|
| 49 |
+
"formula": formula,
|
| 50 |
+
"structured_formula": true_comp if true_comp and true_comp != "nan" else formula,
|
| 51 |
+
"nsites": 0, "band_gap": None,
|
| 52 |
+
"formation_energy_per_atom": None, "energy_above_hull": None,
|
| 53 |
+
"is_experimental": True,
|
| 54 |
+
"families": [f"experimental_{family}"] if family and family != "nan" else ["experimental_SSE"],
|
| 55 |
+
"sse_family": family if family and family != "nan" else "experimental",
|
| 56 |
+
"mobile_ion": "Li", "carrier_elements": ["Li"],
|
| 57 |
+
"tier": "experimental_gold", "quality_score": 100,
|
| 58 |
+
"quality_flags": ["experimental_data", "has_conductivity"],
|
| 59 |
+
"space_group": sg if sg != "nan" else "",
|
| 60 |
+
"elements": list(set(c for c in formula if c.isalpha())),
|
| 61 |
+
"ssb_screening": {
|
| 62 |
+
"estimated_ionic_conductivity_S_cm": conductivity,
|
| 63 |
+
"conductivity_source": "experimental_OBELiX_Therrien2025",
|
| 64 |
+
"mobile_ion": "Li",
|
| 65 |
+
"sse_family": family if family and family != "nan" else "experimental",
|
| 66 |
+
"gates_passed": ["experimental"],
|
| 67 |
+
"sse_candidate_score": 100,
|
| 68 |
+
},
|
| 69 |
+
"provenance": {
|
| 70 |
+
"source": "OBELiX_Therrien2025", "source_id": f"OBELiX-{seq_id:04d}",
|
| 71 |
+
"doi": "https://github.com/nrc-mila/OBELiX",
|
| 72 |
+
"icsd_id": str(icsd) if pd.notna(icsd) else "",
|
| 73 |
+
"experimental_confirmed": True,
|
| 74 |
+
"experimental_database": "OBELiX_Therrien2025",
|
| 75 |
+
"experimental_reference": doi if doi != "nan" else "",
|
| 76 |
+
},
|
| 77 |
+
"license": "CC-BY-4.0",
|
| 78 |
+
}
|
| 79 |
+
return entry
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def main():
|
| 83 |
+
print("=" * WIDTH)
|
| 84 |
+
print(" OBELiX FAST MERGE")
|
| 85 |
+
print("=" * WIDTH)
|
| 86 |
+
|
| 87 |
+
print("\nLoading OBELiX data...")
|
| 88 |
+
t0 = time.time()
|
| 89 |
+
df = load_obelix()
|
| 90 |
+
print(f" {len(df):,} entries, {df['Reduced Composition'].nunique()} unique comps ({time.time()-t0:.1f}s)")
|
| 91 |
+
|
| 92 |
+
print("\nBuilding formula index from Parquet store...")
|
| 93 |
+
t1 = time.time()
|
| 94 |
+
table = pq.read_table(PARQUET_PATH)
|
| 95 |
+
|
| 96 |
+
# Cast null-type columns to string so concat_tables works later
|
| 97 |
+
from pyarrow import types
|
| 98 |
+
null_cols = [f.name for f in table.schema if types.is_null(f.type)]
|
| 99 |
+
if null_cols:
|
| 100 |
+
new_fields = []
|
| 101 |
+
for f in table.schema:
|
| 102 |
+
if f.name in null_cols:
|
| 103 |
+
new_fields.append(pa.field(f.name, pa.string()))
|
| 104 |
+
else:
|
| 105 |
+
new_fields.append(f)
|
| 106 |
+
table = table.cast(pa.schema(new_fields))
|
| 107 |
+
print(f" {table.num_rows:,} rows loaded ({time.time()-t1:.1f}s)")
|
| 108 |
+
|
| 109 |
+
# Build formula -> row index map
|
| 110 |
+
formula_to_rows = defaultdict(list)
|
| 111 |
+
for i in range(table.num_rows):
|
| 112 |
+
for col_name in ["formula", "structured_formula"]:
|
| 113 |
+
raw = table.column(col_name)[i].as_py()
|
| 114 |
+
if raw:
|
| 115 |
+
decoded = _decode_value(raw)
|
| 116 |
+
if decoded:
|
| 117 |
+
formula_to_rows[str(decoded).lower()].append(i)
|
| 118 |
+
print(f" Index: {len(formula_to_rows):,} unique formulas -> {sum(len(v) for v in formula_to_rows.values()):,} references")
|
| 119 |
+
|
| 120 |
+
# Match OBELiX entries
|
| 121 |
+
print("\nCross-referencing...")
|
| 122 |
+
matched_rows = set()
|
| 123 |
+
unmatched_df_rows = []
|
| 124 |
+
matched_df = []
|
| 125 |
+
for idx, row in df.iterrows():
|
| 126 |
+
formula = str(row.get("Reduced Composition", "")).lower()
|
| 127 |
+
matching = formula_to_rows.get(formula, [])
|
| 128 |
+
if matching:
|
| 129 |
+
matched_rows.update(matching)
|
| 130 |
+
matched_df.append(row)
|
| 131 |
+
else:
|
| 132 |
+
unmatched_df_rows.append(row)
|
| 133 |
+
|
| 134 |
+
print(f" Matched: {len(matched_df)} OBELiX entries → {len(matched_rows)} dataset rows")
|
| 135 |
+
print(f" Unmatched: {len(unmatched_df_rows)} OBELiX entries")
|
| 136 |
+
|
| 137 |
+
# Save unmatched list
|
| 138 |
+
unmatched_formulas = sorted(set(
|
| 139 |
+
str(r.get("Reduced Composition", "")) for r in unmatched_df_rows
|
| 140 |
+
))
|
| 141 |
+
with open(BASE_DIR / "dataset" / "obelix_unmatched_formulas.json", "w") as f:
|
| 142 |
+
json.dump(unmatched_formulas, f, indent=2)
|
| 143 |
+
print(f" Unmatched formulas saved: {len(unmatched_formulas)}")
|
| 144 |
+
|
| 145 |
+
# Count by family
|
| 146 |
+
from collections import Counter
|
| 147 |
+
fam_counts = Counter(str(r.get("Family", "")) for r in unmatched_df_rows)
|
| 148 |
+
print(f"\n Unmatched by family:")
|
| 149 |
+
for fam, cnt in sorted(fam_counts.items(), key=lambda x: -x[1])[:10]:
|
| 150 |
+
print(f" {fam if fam != 'nan' else 'unspecified':30s}: {cnt}")
|
| 151 |
+
|
| 152 |
+
# --- Apply updates to matched entries ---
|
| 153 |
+
print(f"\n{'─' * WIDTH}")
|
| 154 |
+
print(" Applying updates to matched entries...")
|
| 155 |
+
t2 = time.time()
|
| 156 |
+
|
| 157 |
+
# For each matched row, read current ssb_screening, append conductivity info
|
| 158 |
+
ssb_col = table.column("ssb_screening").to_pylist()
|
| 159 |
+
prov_col = table.column("provenance").to_pylist()
|
| 160 |
+
exp_col = table.column("is_experimental").to_pylist()
|
| 161 |
+
sid_col = table.column("source_id").to_pylist()
|
| 162 |
+
|
| 163 |
+
# Group matched OBELiX entries by formula for efficient update
|
| 164 |
+
formula_updates = defaultdict(list)
|
| 165 |
+
for r in matched_df:
|
| 166 |
+
f = str(r.get("Reduced Composition", "")).lower()
|
| 167 |
+
conductivity = float(r.get("Ionic conductivity (S cm-1)")) if pd.notna(r.get("Ionic conductivity (S cm-1)")) else None
|
| 168 |
+
doi = str(r.get("DOI", ""))
|
| 169 |
+
formula_updates[f].append({"conductivity": conductivity, "doi": doi})
|
| 170 |
+
|
| 171 |
+
updates_applied = 0
|
| 172 |
+
for row_i in matched_rows:
|
| 173 |
+
sid_raw = sid_col[row_i]
|
| 174 |
+
sid = _decode_value(sid_raw) if sid_raw else None
|
| 175 |
+
|
| 176 |
+
# Decode current ssb_screening
|
| 177 |
+
ssb_raw = ssb_col[row_i]
|
| 178 |
+
ssb = _decode_value(ssb_raw) if ssb_raw else {}
|
| 179 |
+
if not isinstance(ssb, dict):
|
| 180 |
+
ssb = {}
|
| 181 |
+
|
| 182 |
+
# Find matching OBELiX data for this entry's formula
|
| 183 |
+
for col_name in ["formula", "structured_formula"]:
|
| 184 |
+
raw = table.column(col_name)[row_i].as_py()
|
| 185 |
+
if raw:
|
| 186 |
+
formula_decoded = _decode_value(raw)
|
| 187 |
+
if formula_decoded:
|
| 188 |
+
updates = formula_updates.get(str(formula_decoded).lower(), [])
|
| 189 |
+
if updates:
|
| 190 |
+
# Take the first OBELiX measurement for this formula
|
| 191 |
+
upd = updates[0]
|
| 192 |
+
if upd["conductivity"] is not None:
|
| 193 |
+
ssb["estimated_ionic_conductivity_S_cm"] = upd["conductivity"]
|
| 194 |
+
ssb["conductivity_source"] = "experimental_OBELiX_Therrien2025"
|
| 195 |
+
if upd["doi"] and upd["doi"] != "nan":
|
| 196 |
+
ssb["experimental_reference"] = upd["doi"]
|
| 197 |
+
break
|
| 198 |
+
|
| 199 |
+
ssb_col[row_i] = _encode_value(ssb)
|
| 200 |
+
|
| 201 |
+
# Update provenance
|
| 202 |
+
prov_raw = prov_col[row_i]
|
| 203 |
+
prov = _decode_value(prov_raw) if prov_raw else {}
|
| 204 |
+
if not isinstance(prov, dict):
|
| 205 |
+
prov = {}
|
| 206 |
+
prov["experimental_confirmed"] = True
|
| 207 |
+
prov["experimental_database"] = "OBELiX_Therrien2025"
|
| 208 |
+
prov_col[row_i] = _encode_value(prov)
|
| 209 |
+
|
| 210 |
+
# Mark as experimental
|
| 211 |
+
exp_col[row_i] = _encode_value(True)
|
| 212 |
+
|
| 213 |
+
updates_applied += 1
|
| 214 |
+
|
| 215 |
+
# Write updated columns back to table
|
| 216 |
+
table = table.set_column(
|
| 217 |
+
table.schema.get_field_index("ssb_screening"), "ssb_screening",
|
| 218 |
+
pa.chunked_array([pa.array(ssb_col)])
|
| 219 |
+
)
|
| 220 |
+
table = table.set_column(
|
| 221 |
+
table.schema.get_field_index("provenance"), "provenance",
|
| 222 |
+
pa.chunked_array([pa.array(prov_col)])
|
| 223 |
+
)
|
| 224 |
+
table = table.set_column(
|
| 225 |
+
table.schema.get_field_index("is_experimental"), "is_experimental",
|
| 226 |
+
pa.chunked_array([pa.array(exp_col)])
|
| 227 |
+
)
|
| 228 |
+
print(f" {updates_applied} rows updated ({time.time()-t2:.1f}s)")
|
| 229 |
+
|
| 230 |
+
# --- Append unmatched as new entries ---
|
| 231 |
+
print(f"\nAppending {len(unmatched_df_rows)} unmatched OBELiX entries...")
|
| 232 |
+
t3 = time.time()
|
| 233 |
+
|
| 234 |
+
# Import the standardized extraction from dataset_store
|
| 235 |
+
ALL_FIELDS = SCALAR_COLUMNS + JSON_STRING_FIELDS
|
| 236 |
+
ALL_FIELDS_SET = set(ALL_FIELDS)
|
| 237 |
+
|
| 238 |
+
new_entry_dicts = []
|
| 239 |
+
for i, row in enumerate(unmatched_df_rows):
|
| 240 |
+
entry = format_obelix_entry(row, i)
|
| 241 |
+
encoded = {}
|
| 242 |
+
for f in ALL_FIELDS:
|
| 243 |
+
val = _encode_value(entry.get(f))
|
| 244 |
+
encoded[f] = val if val is not None else ""
|
| 245 |
+
new_entry_dicts.append(encoded)
|
| 246 |
+
|
| 247 |
+
new_batch = pa.Table.from_pylist(new_entry_dicts)
|
| 248 |
+
|
| 249 |
+
# Add any columns from existing table schema that are missing in new_batch
|
| 250 |
+
missing_from_new = [f for f in table.schema.names if f not in new_batch.schema.names]
|
| 251 |
+
for f in missing_from_new:
|
| 252 |
+
# Need string type to match existing schema — insert empty strings
|
| 253 |
+
arr = pa.array([""] * new_batch.num_rows, type=pa.string())
|
| 254 |
+
new_batch = new_batch.append_column(pa.field(f, pa.string()), arr)
|
| 255 |
+
|
| 256 |
+
# Remove columns from new_batch not in existing schema
|
| 257 |
+
cols_to_drop = [f for f in new_batch.schema.names if f not in table.schema.names]
|
| 258 |
+
for f in cols_to_drop:
|
| 259 |
+
col_idx = new_batch.schema.get_field_index(f)
|
| 260 |
+
new_batch = new_batch.remove_column(col_idx)
|
| 261 |
+
|
| 262 |
+
# Reorder columns to match
|
| 263 |
+
new_batch = new_batch.select(table.schema.names)
|
| 264 |
+
|
| 265 |
+
table = pa.concat_tables([table, new_batch])
|
| 266 |
+
print(f" Appended {new_batch.num_rows} rows ({time.time()-t3:.1f}s)")
|
| 267 |
+
print(f" Total rows: {table.num_rows:,}")
|
| 268 |
+
|
| 269 |
+
# --- Rewrite Parquet + index ---
|
| 270 |
+
print(f"\n{'─' * WIDTH}")
|
| 271 |
+
print(" Checkpointing...")
|
| 272 |
+
t4 = time.time()
|
| 273 |
+
pq.write_table(table, PARQUET_PATH, compression="zstd")
|
| 274 |
+
|
| 275 |
+
# Rebuild index
|
| 276 |
+
sids_raw = table.column("source_id").to_pylist()
|
| 277 |
+
sids_decoded = [_decode_value(s) for s in sids_raw]
|
| 278 |
+
index = {sid: i for i, sid in enumerate(sids_decoded)}
|
| 279 |
+
with open(INDEX_PATH, "w") as f:
|
| 280 |
+
json.dump(index, f)
|
| 281 |
+
print(f" Parquet + index written ({time.time()-t4:.1f}s)")
|
| 282 |
+
|
| 283 |
+
# Summary
|
| 284 |
+
with_cond = sum(
|
| 285 |
+
1 for i in range(table.num_rows)
|
| 286 |
+
if table.column("ssb_screening")[i].as_py()
|
| 287 |
+
and "estimated_ionic_conductivity" in str(table.column("ssb_screening")[i].as_py())
|
| 288 |
+
)
|
| 289 |
+
exp_new = sum(
|
| 290 |
+
1 for i in range(table.num_rows)
|
| 291 |
+
if table.column("tier")[i].as_py()
|
| 292 |
+
and "experimental" in str(table.column("tier")[i].as_py())
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
print(f"\n{'─' * WIDTH}")
|
| 296 |
+
print(" MERGE COMPLETE")
|
| 297 |
+
print(f"{'─' * WIDTH}")
|
| 298 |
+
print(f" OBELiX entries integrated: {len(df)}")
|
| 299 |
+
print(f" Matched + tagged: {len(matched_df)}")
|
| 300 |
+
print(f" New entries appended: {len(unmatched_df_rows)}")
|
| 301 |
+
print(f" Unmatched formulas (acquisition target): {len(unmatched_formulas)}")
|
| 302 |
+
print(f" Total entries in dataset: {table.num_rows:,}")
|
| 303 |
+
print("=" * WIDTH)
|
| 304 |
+
|
| 305 |
+
return 0
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
if __name__ == "__main__":
|
| 309 |
+
sys.exit(main())
|
scripts/run_phase1_pipeline.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Phase 1 pipeline runner — executes all Phase 1 scripts in sequence.
|
| 2 |
+
|
| 3 |
+
This script runs the complete Phase 1 pipeline:
|
| 4 |
+
1. Electrochemical stability windows (Li/Na entries)
|
| 5 |
+
2. CAVD channel dimensionality (all Li/Na entries with structures)
|
| 6 |
+
3. SSE candidate score (all entries, 5-gate system)
|
| 7 |
+
4. Mechanical properties (all entries, geometric proxy)
|
| 8 |
+
5. Oxidation states (all entries, BVA + heuristic)
|
| 9 |
+
6. JARVIS EaH (internal convex hull)
|
| 10 |
+
7. Commercial-safe edition extraction
|
| 11 |
+
8. Garnet enrichment (structure-based reclassification)
|
| 12 |
+
|
| 13 |
+
Usage:
|
| 14 |
+
python scripts/run_phase1_pipeline.py # full pipeline
|
| 15 |
+
python scripts/run_phase1_pipeline.py --steps 1,3,5 # specific steps only
|
| 16 |
+
python scripts/run_phase1_pipeline.py --dry-run # stats only, no writes
|
| 17 |
+
python scripts/run_phase1_pipeline.py --skip-write # compute but don't save
|
| 18 |
+
"""
|
| 19 |
+
import sys, time, argparse, subprocess
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
SCRIPTS_DIR = Path(__file__).resolve().parent
|
| 23 |
+
BASE_DIR = SCRIPTS_DIR.parent
|
| 24 |
+
|
| 25 |
+
STEPS = {
|
| 26 |
+
1: ("Electrochemical Windows", "compute_electrochemical_windows.py",
|
| 27 |
+
["python", "scripts/compute_electrochemical_windows.py", "--subset", "full"]),
|
| 28 |
+
2: ("CAVD Channel Dimensionality", "compute_cavd_channel_dimensionality.py",
|
| 29 |
+
["python", "scripts/compute_cavd_channel_dimensionality.py", "--subset", "full"]),
|
| 30 |
+
3: ("SSE Candidate Score", "compute_sse_candidate_score.py",
|
| 31 |
+
["python", "scripts/compute_sse_candidate_score.py", "--subset", "full"]),
|
| 32 |
+
4: ("Mechanical Properties", "compute_mechanical_properties.py",
|
| 33 |
+
["python", "scripts/compute_mechanical_properties.py"]),
|
| 34 |
+
5: ("Oxidation States", "compute_oxidation_states.py",
|
| 35 |
+
["python", "scripts/compute_oxidation_states.py"]),
|
| 36 |
+
6: ("JARVIS EaH", "compute_jarvis_hull_energy.py",
|
| 37 |
+
["python", "scripts/compute_jarvis_hull_energy.py"]),
|
| 38 |
+
7: ("Commercial-Safe Edition", "extract_commercial_safe_edition.py",
|
| 39 |
+
["python", "scripts/extract_commercial_safe_edition.py"]),
|
| 40 |
+
8: ("Garnet Enrichment", "enrich_garnet_family.py",
|
| 41 |
+
["python", "scripts/enrich_garnet_family.py"]),
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
STEP_ORDER = [1, 2, 3, 4, 5, 6, 7, 8]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def main():
|
| 48 |
+
parser = argparse.ArgumentParser(description="Phase 1 pipeline runner")
|
| 49 |
+
parser.add_argument("--steps", type=str, default=None,
|
| 50 |
+
help="Comma-separated step numbers (e.g. 1,3,5)")
|
| 51 |
+
parser.add_argument("--dry-run", action="store_true",
|
| 52 |
+
help="Add --dry-run to all scripts")
|
| 53 |
+
parser.add_argument("--skip-write", action="store_true",
|
| 54 |
+
help="Add --dry-run to dataset-modifying scripts")
|
| 55 |
+
args = parser.parse_args()
|
| 56 |
+
|
| 57 |
+
if args.steps:
|
| 58 |
+
selected_steps = [int(s.strip()) for s in args.steps.split(",")]
|
| 59 |
+
else:
|
| 60 |
+
selected_steps = STEP_ORDER
|
| 61 |
+
|
| 62 |
+
print("=" * 60)
|
| 63 |
+
print(" PHASE 1 PIPELINE")
|
| 64 |
+
print(" 8 steps to transform Scandium-Dataset into SSB screening resource")
|
| 65 |
+
print("=" * 60)
|
| 66 |
+
|
| 67 |
+
total_start = time.time()
|
| 68 |
+
|
| 69 |
+
for step_num in selected_steps:
|
| 70 |
+
if step_num not in STEPS:
|
| 71 |
+
print(f"\n [SKIP] Step {step_num}: unknown")
|
| 72 |
+
continue
|
| 73 |
+
|
| 74 |
+
name, script, base_cmd = STEPS[step_num]
|
| 75 |
+
|
| 76 |
+
print(f"\n{'─' * 60}")
|
| 77 |
+
print(f" Step {step_num}/8: {name}")
|
| 78 |
+
print(f" Script: scripts/{script}")
|
| 79 |
+
print(f"{'─' * 60}")
|
| 80 |
+
|
| 81 |
+
cmd = list(base_cmd)
|
| 82 |
+
if args.dry_run or args.skip_write:
|
| 83 |
+
cmd.append("--dry-run")
|
| 84 |
+
|
| 85 |
+
step_start = time.time()
|
| 86 |
+
print(f" Running: {' '.join(cmd)}")
|
| 87 |
+
print()
|
| 88 |
+
|
| 89 |
+
result = subprocess.run(cmd, cwd=str(BASE_DIR), capture_output=True, text=True)
|
| 90 |
+
|
| 91 |
+
# Print stdout
|
| 92 |
+
for line in result.stdout.split("\n"):
|
| 93 |
+
print(f" {line}")
|
| 94 |
+
|
| 95 |
+
if result.stderr.strip():
|
| 96 |
+
print(f"\n stderr:")
|
| 97 |
+
for line in result.stderr.strip().split("\n"):
|
| 98 |
+
print(f" ! {line}")
|
| 99 |
+
|
| 100 |
+
if result.returncode != 0:
|
| 101 |
+
print(f"\n [FAILED] exit code {result.returncode}")
|
| 102 |
+
if not args.dry_run:
|
| 103 |
+
print(" Aborting pipeline.")
|
| 104 |
+
sys.exit(1)
|
| 105 |
+
|
| 106 |
+
elapsed = time.time() - step_start
|
| 107 |
+
print(f"\n [{elapsed/60:.1f} min]")
|
| 108 |
+
|
| 109 |
+
total_elapsed = time.time() - total_start
|
| 110 |
+
print(f"\n{'=' * 60}")
|
| 111 |
+
print(f" Pipeline complete: {len(selected_steps)} steps in {total_elapsed/60:.1f} min")
|
| 112 |
+
print(f"{'=' * 60}")
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
if __name__ == "__main__":
|
| 116 |
+
main()
|
scripts/setup_mlip_infrastructure.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Set up MLIP infrastructure for high-throughput migration barrier computation.
|
| 2 |
+
|
| 3 |
+
Installs and validates MLIP tools for nudged elastic band (NEB) calculations:
|
| 4 |
+
- CHGNet: universal crystal Hamiltonian Graph neural Network
|
| 5 |
+
- MACE-MP-0: MACE architecture trained on Materials Project trajectories
|
| 6 |
+
- M3GNet: universal potential from Materials Project
|
| 7 |
+
- Orb-v3: Orbital-based MLIP
|
| 8 |
+
|
| 9 |
+
This script:
|
| 10 |
+
1. Checks what's installed
|
| 11 |
+
2. Attempts installation of missing packages
|
| 12 |
+
3. Validates each potential on a test structure
|
| 13 |
+
4. Generates a configuration file for the NEB pipeline
|
| 14 |
+
|
| 15 |
+
Usage:
|
| 16 |
+
python scripts/setup_mlip_infrastructure.py
|
| 17 |
+
python scripts/setup_mlip_infrastructure.py --check-only
|
| 18 |
+
python scripts/setup_mlip_infrastructure.py --install
|
| 19 |
+
"""
|
| 20 |
+
import argparse, os, sys, subprocess, json, warnings
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
MLIP_PACKAGES = {
|
| 24 |
+
"chgnet": "chgnet",
|
| 25 |
+
"mace": "mace-torch",
|
| 26 |
+
"matgl": "matgl",
|
| 27 |
+
"orb": "orb-models",
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
TEST_STRUCTURE = """
|
| 31 |
+
{
|
| 32 |
+
"@module": "pymatgen.core.structure",
|
| 33 |
+
"@class": "Structure",
|
| 34 |
+
"lattice": {"matrix": [[3.0, 0.0, 0.0], [0.0, 3.0, 0.0], [0.0, 0.0, 3.0]], "pbc": [true, true, true]},
|
| 35 |
+
"sites": [
|
| 36 |
+
{"species": [{"element": "Li", "occu": 1}], "abc": [0.0, 0.0, 0.0]},
|
| 37 |
+
{"species": [{"element": "Cl", "occu": 1}], "abc": [0.5, 0.5, 0.5]}
|
| 38 |
+
]
|
| 39 |
+
}
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def check_installed():
|
| 44 |
+
"""Check which MLIP packages are installed."""
|
| 45 |
+
results = {}
|
| 46 |
+
for name, pkg in MLIP_PACKAGES.items():
|
| 47 |
+
try:
|
| 48 |
+
__import__(name.replace("-", "_"))
|
| 49 |
+
results[name] = "installed"
|
| 50 |
+
except ImportError:
|
| 51 |
+
try:
|
| 52 |
+
__import__(pkg.replace("-", "_"))
|
| 53 |
+
results[name] = "installed"
|
| 54 |
+
except ImportError:
|
| 55 |
+
results[name] = "not found"
|
| 56 |
+
return results
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def install_packages(packages):
|
| 60 |
+
"""Install MLIP packages via pip."""
|
| 61 |
+
for name, pkg in packages.items():
|
| 62 |
+
print(f" Installing {pkg}...")
|
| 63 |
+
result = subprocess.run(
|
| 64 |
+
[sys.executable, "-m", "pip", "install", pkg],
|
| 65 |
+
capture_output=True, text=True
|
| 66 |
+
)
|
| 67 |
+
if result.returncode == 0:
|
| 68 |
+
print(f" {name}: installed")
|
| 69 |
+
else:
|
| 70 |
+
print(f" {name}: failed — {result.stderr[-200:]}")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def validate_chgnet(structure_dict):
|
| 74 |
+
"""Validate CHGNet can predict on test structure."""
|
| 75 |
+
import json
|
| 76 |
+
from pymatgen.core import Structure
|
| 77 |
+
from chgnet.model import CHGNet
|
| 78 |
+
from chgnet.utils import write_structures_to_POSCAR
|
| 79 |
+
|
| 80 |
+
struct = Structure.from_dict(structure_dict)
|
| 81 |
+
model = CHGNet.load()
|
| 82 |
+
prediction = model.predict_structure(struct)
|
| 83 |
+
return {
|
| 84 |
+
"energy": float(prediction["e"]),
|
| 85 |
+
"forces_shape": list(prediction["f"].shape),
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def validate_mace(structure_dict):
|
| 90 |
+
"""Validate MACE can predict on test structure."""
|
| 91 |
+
import torch
|
| 92 |
+
from mace.calculators import MACECalculator
|
| 93 |
+
from ase.io import read
|
| 94 |
+
from pymatgen.core import Structure
|
| 95 |
+
from pymatgen.io.ase import AseAtomsAdaptor
|
| 96 |
+
|
| 97 |
+
struct = Structure.from_dict(structure_dict)
|
| 98 |
+
atoms = AseAtomsAdaptor.get_atoms(struct)
|
| 99 |
+
|
| 100 |
+
calc = MACECalculator(model_path="medium", device="cpu")
|
| 101 |
+
atoms.set_calculator(calc)
|
| 102 |
+
energy = atoms.get_potential_energy()
|
| 103 |
+
forces = atoms.get_forces()
|
| 104 |
+
|
| 105 |
+
return {
|
| 106 |
+
"energy": float(energy),
|
| 107 |
+
"forces_shape": list(forces.shape),
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def main():
|
| 112 |
+
parser = argparse.ArgumentParser(description="MLIP infrastructure setup")
|
| 113 |
+
parser.add_argument("--check-only", action="store_true",
|
| 114 |
+
help="Check installed packages only")
|
| 115 |
+
parser.add_argument("--install", action="store_true",
|
| 116 |
+
help="Install missing MLIP packages")
|
| 117 |
+
parser.add_argument("--validate", action="store_true",
|
| 118 |
+
help="Validate installed potentials on test structure")
|
| 119 |
+
args = parser.parse_args()
|
| 120 |
+
|
| 121 |
+
BASE_DIR = Path(__file__).resolve().parent.parent
|
| 122 |
+
|
| 123 |
+
print("=" * 60)
|
| 124 |
+
print(" MLIP INFRASTRUCTURE SETUP")
|
| 125 |
+
print(" High-throughput migration barrier computation pipeline")
|
| 126 |
+
print("=" * 60)
|
| 127 |
+
|
| 128 |
+
# Check installed packages
|
| 129 |
+
print("\n Checking installed MLIP packages...")
|
| 130 |
+
installed = check_installed()
|
| 131 |
+
for name, status in installed.items():
|
| 132 |
+
print(f" {name:12s}: {status}")
|
| 133 |
+
|
| 134 |
+
if args.install:
|
| 135 |
+
to_install = {k: v for k, v in MLIP_PACKAGES.items() if installed[k] == "not found"}
|
| 136 |
+
if to_install:
|
| 137 |
+
print(f"\n Installing {len(to_install)} packages...")
|
| 138 |
+
install_packages(to_install)
|
| 139 |
+
else:
|
| 140 |
+
print("\n All packages already installed.")
|
| 141 |
+
|
| 142 |
+
if args.validate:
|
| 143 |
+
print("\n Validating potentials...")
|
| 144 |
+
struct_dict = json.loads(TEST_STRUCTURE)
|
| 145 |
+
|
| 146 |
+
if installed.get("chgnet") == "installed":
|
| 147 |
+
try:
|
| 148 |
+
result = validate_chgnet(struct_dict)
|
| 149 |
+
print(f" CHGNet: OK (energy={result['energy']:.3f} eV)")
|
| 150 |
+
except Exception as e:
|
| 151 |
+
print(f" CHGNet: validation failed — {str(e)[:80]}")
|
| 152 |
+
|
| 153 |
+
if installed.get("mace") == "installed":
|
| 154 |
+
try:
|
| 155 |
+
result = validate_mace(struct_dict)
|
| 156 |
+
print(f" MACE: OK (energy={result['energy']:.3f} eV)")
|
| 157 |
+
except Exception as e:
|
| 158 |
+
print(f" MACE: validation failed — {str(e)[:80]}")
|
| 159 |
+
|
| 160 |
+
# Generate config file
|
| 161 |
+
if not args.check_only:
|
| 162 |
+
config = {
|
| 163 |
+
"potentials": installed,
|
| 164 |
+
"pipeline": {
|
| 165 |
+
"bvse_barrier_threshold": 0.5,
|
| 166 |
+
"mlip_neb_grid": [5, 5, 5],
|
| 167 |
+
"mlip_neb_spring_constant": 5.0,
|
| 168 |
+
"mlip_neb_fmax": 0.05,
|
| 169 |
+
"mlip_neb_steps": 500,
|
| 170 |
+
},
|
| 171 |
+
"target_subset": "gold_battery_li",
|
| 172 |
+
"description": "Li-containing Gold-tier battery-family entries",
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
config_path = BASE_DIR / "configs" / "mlip_pipeline.json"
|
| 176 |
+
print(f"\n Writing config to {config_path}...")
|
| 177 |
+
config_path.parent.mkdir(parents=True, exist_ok=True)
|
| 178 |
+
with open(config_path, "w") as f:
|
| 179 |
+
json.dump(config, f, indent=2)
|
| 180 |
+
|
| 181 |
+
# Print next steps
|
| 182 |
+
print(f"\n{'─' * 60}")
|
| 183 |
+
print(" NEXT STEPS")
|
| 184 |
+
print(f" {'─' * 60}")
|
| 185 |
+
print("""
|
| 186 |
+
1. Install MLIP packages:
|
| 187 |
+
pip install chgnet mace-torch matgl orb-models
|
| 188 |
+
|
| 189 |
+
2. Run BVSE pre-filter on Li/Na entries:
|
| 190 |
+
python scripts/compute_bvse_barriers.py --subset gold --limit 50000
|
| 191 |
+
|
| 192 |
+
3. Run MLIP-NEB on BVSE-filtered subset:
|
| 193 |
+
python scripts/run_mlip_neb_pipeline.py --input dataset/bvse_filtered.json
|
| 194 |
+
|
| 195 |
+
4. Update sse_candidate_score with full 5 gates:
|
| 196 |
+
python scripts/compute_sse_candidate_score.py
|
| 197 |
+
""")
|
| 198 |
+
print("=" * 60)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
if __name__ == "__main__":
|
| 202 |
+
main()
|