training-model-material / code /pimamba /build_dataset.py
eduzrh's picture
sync code
239a1be verified
Raw History Blame Contribute Delete
12.3 kB
"""Build the unified modelling dataset from 论文提取data_final.xlsx.
Implements the data-side requirements of `step 2.docx`:
* yellow-highlighted rows are erroneous -> dropped (sample_id 24..60);
* shape-aware geometry with *applicability flags* (never a fake zero);
* per-variable observed masks (missing != 0);
* physical unit handling (dislocation density stored in 1e19 m^-2);
* train-split-only normalisation statistics.
Outputs (data/processed/):
samples_meta.csv one row per sample, static (conditioning) features, raw units
trajectories.csv long format, 401 strain points per sample, raw units, NaN = unobserved
data_dictionary.json
build_report.json
"""
from __future__ import annotations
import json
import re
from pathlib import Path
import numpy as np
import openpyxl
import pandas as pd
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[1]
RAW_XLSX = ROOT / "raw" / "论文提取data_final.xlsx"
OUT = ROOT / "data" / "processed"
ELEMENTS = ["Al", "Ti", "Zr", "Nb", "Mo", "Ta", "V", "Cr", "Mn", "Fe",
"Co", "Ni", "Cu", "Hf", "W", "Re", "Sc", "Mg", "Si", "Sn"]
# Sheet2 block layout (18 columns per block: id + 16 data + 1 spacer)
TRAJ_COLS = ["strain", "sigma_GPa", "twin_density_nm-1",
"xi_BCC", "xi_FCC", "xi_HCP", "xi_other",
"rho_total", "rho_perfect", "rho_shockley", "rho_frank",
"rho_stairrod", "rho_hirth", "rho_other_disl",
"rho_112_111", "rho_100"]
RHO_COLS = ["rho_total", "rho_perfect", "rho_shockley", "rho_frank",
"rho_stairrod", "rho_hirth", "rho_other_disl", "rho_112_111", "rho_100"]
# Sheet1 column indices (1-based)
COL = dict(sid=1, title=2, doi=3, alloy=4, VEC=5, delta=6, rbar=7, dHmix=8,
dSmix=9, chi=10, Mavg=11, dmu=12, Tm=13, rhomass=14, load=15,
direction=16, rate=17, T0=18, eta=19, ensemble=20, cryst=21,
shape=22, LWH=23, diam=24, aspect=25,
xi_BCC=26, xi_FCC=27, xi_HCP=28, xi_other=29, rho0=30,
d_perfect=31, d_shockley=32, d_frank=33, d_stairrod=34,
d_hirth=35, d_oth=36, d_112_111=37, d_100=38,
phase=39, potential=40, twin_nuc=41, twin_type=42, twin_lambda=43)
ELEM0 = 44
def _f(v):
"""None/str -> float or NaN."""
if v is None:
return np.nan
if isinstance(v, (int, float)):
return float(v)
s = str(v).strip().replace("−", "-").replace("–", "-")
if s == "" or s in {"-", "NA", "N/A"}:
return np.nan
try:
return float(s)
except ValueError:
return np.nan
def _parse_lwh(text):
"""'100 × 50 × 3.4 nm(长×高×宽)' -> (length, height, width, volume_nm3)."""
if not text:
return np.nan, np.nan, np.nan
s = str(text).replace("×", "x").replace("*", "x")
nums = re.findall(r"(\d+(?:\.\d+)?)\s*(?:x|,)\s*(\d+(?:\.\d+)?)\s*(?:x|,)\s*(\d+(?:\.\d+)?)", s)
if nums:
a, b, c = map(float, nums[0])
# convention stated in the sheet: 长(length) × 高(height) × 宽(width)
return a, b, c
one = re.findall(r"(\d+(?:\.\d+)?)", s)
if len(one) >= 3:
return float(one[0]), float(one[1]), float(one[2])
return np.nan, np.nan
def _parse_diameter(text):
"""'10(顶)– 11.3(底)' -> 10.65 ; '13' -> 13."""
if not text:
return np.nan
s = str(text).replace("−", "-").replace("–", "-").replace("—", "-")
nums = [float(x) for x in re.findall(r"(\d+(?:\.\d+)?)", s)]
nums = [x for x in nums if 0 < x < 1e4]
if not nums:
return np.nan
if len(nums) >= 2 and (("-" in s) or ("~" in s)):
return float(np.mean([nums[0], nums[1]]))
return float(nums[0])
def _parse_orientation(text):
"""Return (h,k,l, has_flag) from strings like '[011](X 向拉伸)'."""
if not text:
return np.nan, np.nan, np.nan, 0.0
m = re.search(r"\[\s*(-?\d)\s*(-?\d)\s*(-?\d)\s*\]", str(text))
if m:
return float(m.group(1)), float(m.group(2)), float(m.group(3)), 1.0
return np.nan, np.nan, np.nan, 0.0
def _parse_eta(text):
"""'+1/3' / '−1/3' / '0' -> float."""
if text is None:
return np.nan
s = str(text).strip().replace("−", "-").replace("–", "-").replace("+", "")
if "/" in s:
try:
a, b = s.split("/")
return float(a) / float(b)
except Exception:
return np.nan
try:
return float(s)
except ValueError:
return np.nan
def _parse_ensemble(text):
s = str(text or "").upper()
if "NPT" in s:
return "NPT"
if "NVE" in s:
return "NVE"
if "NVT" in s:
return "NVT"
return "unknown"
def _parse_potential(text):
s = str(text or "").upper()
if "SNAP" in s:
return "SNAP"
if "MEAM" in s:
return "MEAM"
if "EAM" in s:
return "EAM"
return "other"
def read_meta(ws) -> pd.DataFrame:
rows = []
for r in range(2, ws.max_row + 1):
sid = ws.cell(r, 1).value
if sid is None:
continue
g = lambda k: ws.cell(r, COL[k]).value
rec = {
"sample_id": int(sid),
"title": g("title"),
"doi": g("doi"),
"alloy": str(g("alloy")).strip(),
"load_mode": str(g("load") or "").strip(),
"load_direction": g("direction"),
"strain_rate": _f(g("rate")),
"T0": _f(g("T0")),
"eta": _parse_eta(g("eta")),
"ensemble": _parse_ensemble(g("ensemble")),
"crystalline": str(g("cryst") or "").strip(),
"shape_raw": str(g("shape") or "").strip(),
"lwh_raw": g("LWH"),
"diameter_raw": g("diam"),
"aspect_raw": g("aspect"),
"rho0": _f(g("rho0")),
"phase_raw": g("phase"),
"potential": _parse_potential(g("potential")),
"twin_nuc": _f(g("twin_nuc")),
"twin_type": g("twin_type"),
"twin_lambda": _f(g("twin_lambda")),
}
for k in ["VEC", "delta", "rbar", "dHmix", "dSmix", "chi", "Mavg",
"dmu", "Tm", "rhomass"]:
rec[k] = _f(g(k))
for k in ["xi_BCC", "xi_FCC", "xi_HCP", "xi_other"]:
rec["init_" + k] = _f(g(k))
for k in ["d_perfect", "d_shockley", "d_frank", "d_stairrod",
"d_hirth", "d_oth", "d_112_111", "d_100"]:
rec["init_" + k] = _f(g(k))
comp = np.array([_f(ws.cell(r, ELEM0 + i).value) for i in range(len(ELEMENTS))])
comp = np.nan_to_num(comp, nan=0.0)
tot = comp.sum()
rec["comp_sum"] = tot
for i, el in enumerate(ELEMENTS):
rec["at_" + el] = comp[i] / tot if tot > 0 else np.nan
# ---- geometry: shape-aware, with applicability flags -------------
shape = rec["shape_raw"].lower()
is_cyl = shape in {"c", "cylinder", "cyl"} or "cyl" in shape
is_prism = (not is_cyl) and (shape in {"r", "rectangular prism", "prism"} or "rect" in shape)
L = W = H = D = AR = np.nan
if is_prism:
L, H, W = _parse_lwh(rec["lwh_raw"])
elif is_cyl:
D = _parse_diameter(rec["diameter_raw"])
AR = _f(rec["aspect_raw"])
if not np.isfinite(AR) and np.isfinite(_f(rec["aspect_raw"])):
AR = _f(rec["aspect_raw"])
rec["shape_type"] = "prism" if is_prism else ("cylinder" if is_cyl else "unknown")
rec["geom_L"] = L
rec["geom_W"] = W
rec["geom_H"] = H
rec["geom_D"] = D
rec["geom_AR"] = AR
rec["app_L"] = float(np.isfinite(L))
rec["app_W"] = float(np.isfinite(W))
rec["app_H"] = float(np.isfinite(H))
rec["app_D"] = float(np.isfinite(D))
rec["app_AR"] = float(np.isfinite(AR))
if is_prism and np.isfinite(L) and np.isfinite(W) and np.isfinite(H):
rec["geom_volume_nm3"] = L * W * H
elif is_cyl and np.isfinite(D) and np.isfinite(AR):
rec["geom_volume_nm3"] = np.pi * (D / 2) ** 2 * (AR * D)
else:
rec["geom_volume_nm3"] = np.nan
rec["app_V"] = float(np.isfinite(rec["geom_volume_nm3"]))
h, k, l, has = _parse_orientation(rec["load_direction"])
norm = np.sqrt(h * h + k * k + l * l) if has else np.nan
rec.update({"orient_h": h / norm if has else np.nan,
"orient_k": k / norm if has else np.nan,
"orient_l": l / norm if has else np.nan,
"app_orient": has})
rows.append(rec)
return pd.DataFrame(rows)
def read_traj(ws2) -> pd.DataFrame:
starts = list(range(1, ws2.max_column + 1, 18))
frames = []
for s in starts:
sid = ws2.cell(2, s).value
if sid is None:
continue
vals = []
for r in range(2, ws2.max_row + 1):
row = [ws2.cell(r, c).value for c in range(s, s + 17)]
if row[0] is None and row[1] is None:
continue
vals.append([_f(v) for v in row[1:17]])
if not vals:
continue
arr = np.asarray(vals, dtype=float)
df = pd.DataFrame(arr, columns=TRAJ_COLS)
df.insert(0, "sample_id", int(sid))
frames.append(df)
out = pd.concat(frames, ignore_index=True)
# enforce physical plausibility: tiny negative round-off -> 0
for c in ["sigma_GPa"] + RHO_COLS + ["twin_density_nm-1"]:
out.loc[out[c] < 0, c] = np.nan if c != "sigma_GPa" else 0.0
return out
def drop_yellow(wb, meta: pd.DataFrame):
ws = wb["Sheet1"]
bad_rows = []
for r in range(2, ws.max_row + 1):
n = sum(1 for c in ws[r] if c.fill and c.fill.fgColor
and c.fill.fgColor.rgb == "FFFFFF00")
if n >= 50: # a whole highlighted record
bad_rows.append(ws.cell(r, 1).value)
return [int(x) for x in bad_rows if x is not None]
def main():
OUT.mkdir(parents=True, exist_ok=True)
wb = openpyxl.load_workbook(RAW_XLSX, data_only=True)
meta_all = read_meta(wb["Sheet1"])
traj_all = read_traj(wb["Sheet2"])
bad = drop_yellow(wb, meta_all)
meta = meta_all[~meta_all.sample_id.isin(bad)].reset_index(drop=True)
traj = traj_all[~traj_all.sample_id.isin(bad)].reset_index(drop=True)
traj = traj.sort_values(["sample_id", "strain"]).reset_index(drop=True)
meta.to_csv(OUT / "samples_meta.csv", index=False, encoding="utf-8-sig")
traj.to_csv(OUT / "trajectories.csv", index=False, encoding="utf-8-sig")
coverage = {}
for c in TRAJ_COLS[1:]:
coverage[c] = {
"n_samples_with_label": int(traj.groupby("sample_id")[c].apply(lambda s: s.notna().any()).sum()),
"n_points": int(traj[c].notna().sum()),
"min": float(np.nanmin(traj[c])) if traj[c].notna().any() else None,
"max": float(np.nanmax(traj[c])) if traj[c].notna().any() else None,
}
report = {
"n_samples_raw": int(len(meta_all)),
"dropped_yellow_sample_ids": bad,
"n_samples_used": int(len(meta)),
"n_strain_points_per_sample": int(traj.groupby("sample_id").size().mode().iloc[0]),
"alloys": {k: int(v) for k, v in meta.alloy.value_counts().items()},
"coverage": coverage,
"unit_notes": {
"rho_*": "stored value x 1e19 = m^-2",
"sigma_GPa": "GPa (magnitude, positive)",
"twin_density_nm-1": "nm^-1",
"xi_*": "volume fraction 0-1",
},
}
(OUT / "build_report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2))
(OUT / "data_dictionary.json").write_text(json.dumps({
"static_features": list(meta.columns),
"trajectory_targets": TRAJ_COLS[1:],
"rho_columns": RHO_COLS,
"phase_columns": ["xi_BCC", "xi_FCC", "xi_HCP", "xi_other"],
}, ensure_ascii=False, indent=2))
print(json.dumps({k: v for k, v in report.items() if k != "coverage"},
ensure_ascii=False, indent=2))
print("\ncoverage:")
for k, v in coverage.items():
print(f" {k:22s} samples={v['n_samples_with_label']:2d} points={v['n_points']:5d} "
f"range=[{v['min']}, {v['max']}]")
if __name__ == "__main__":
main()