soc-scf-trajectories / read_example.py
project-14's picture
Publish filtered SOC-SCF scientific metadata and reader; raw mirror in progress
db64be0 verified
Raw History Blame Contribute Delete
4.11 kB
"""Read the three-field worked endpoint; pip install numpy zstandard huggingface_hub.
Scientific metadata and example code: CC BY 4.0, Project-14 (2026).
Downloads only the small first raw shard and the metadata needed for this example.
"""
import hashlib
import io
import json
import struct
import tarfile
from pathlib import Path
import numpy as np
import zstandard
from huggingface_hub import hf_hub_download
REPO = "project-14/soc-scf-trajectories"
TRAJECTORY = "proto014-feal2-reference130-002"
BOHR_A = 0.529177210903
RY_EV = 13.605693122994
def decode(payload, reference, context, role):
if len(payload) != reference["bytes"]:
raise ValueError("Field byte count differs")
if hashlib.sha256(payload).hexdigest() != reference["sha256"]:
raise ValueError("Field checksum differs")
encoding = reference["encoding"]
if encoding == "qe-grid1":
if payload[:8] != b"GPOGRID1":
raise ValueError("Unknown raw header")
header = struct.unpack("<7q", payload[8:64])
if header != (*context["dims"], *context["padded"], 4):
raise ValueError("Grid header/context mismatch")
payload = payload[64:]
elif encoding != "canonical-f64le":
raise ValueError("Unknown encoding")
shape = (4, *reversed(context["dims"]))
if len(payload) != int(np.prod(shape)) * 8:
raise ValueError("Unexpected field length")
a = np.frombuffer(payload, dtype="<f8").reshape(shape).copy()
if encoding == "qe-grid1":
a *= RY_EV if role == "potential" else 1.0 / BOHR_A**3
if not np.isfinite(a).all():
raise ValueError("Non-finite field")
return a
def load_example(local_root=None, revision="main"):
def file(name):
if local_root is not None:
return Path(local_root) / name
return Path(hf_hub_download(REPO, name, repo_type="dataset", revision=revision))
manifest = json.loads(file("MANIFEST.json").read_text())
route_name = "metadata/routes/" + TRAJECTORY + ".json"
route_bytes = file(route_name).read_bytes()
if hashlib.sha256(route_bytes).hexdigest() != manifest["files"][route_name]["sha256"]:
raise ValueError("Route checksum differs")
route = json.loads(route_bytes)
record = next(m for m in route["maps"] if m["sequence"] == 96)
wanted = {v["sha256"]: (k, v) for k, v in record["fields"].items()}
arrays = {}
# No tar extraction: read only the three exact regular-file members.
with file("raw/shard-00000.tar.zst").open("rb") as src:
with zstandard.ZstdDecompressor().stream_reader(src) as stream:
with tarfile.open(fileobj=stream, mode="r|") as archive:
for member in archive:
digest = member.name.rsplit("/", 1)[-1]
if digest not in wanted:
continue
role, ref = wanted[digest]
if not member.isfile() or member.name != digest[:2] + "/" + digest or member.size != ref["bytes"]:
raise ValueError("Unexpected archive member")
arrays[role] = decode(archive.extractfile(member).read(), ref, route["context"], role)
if set(arrays) != set(record["fields"]):
raise ValueError("Worked endpoint incomplete")
return arrays, route["context"]
if __name__ == "__main__":
fields, context = load_example()
dv = context["volume_bohr3"] * BOHR_A**3 / np.prod(context["dims"])
delta = fields["output-density"] - fields["input-density"]
charge = float(np.abs(delta[0]).sum() * dv / context["nat"])
spin = float(np.linalg.norm(delta[1:], axis=0).sum() * dv / context["nat"])
electrons = {k: float(fields[k][0].sum() * dv) for k in ("input-density", "output-density")}
assert all(abs(n - 44) < 1e-8 for n in electrons.values())
assert abs(charge - 3.6909171285e-7) < 1e-14
assert abs(spin - 2.6690981464e-6) < 1e-13
print(json.dumps({"shape": list(delta.shape), "electrons": electrons,
"charge_L1_e_per_atom": charge, "spin_vector_L1_e_per_atom": spin}, indent=2))