#!/usr/bin/env python3 """Plot MP-20 XRD distribution figures from previously generated statistics.""" from __future__ import annotations import argparse from pathlib import Path import numpy as np import pandas as pd import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt def finite_series(values: pd.Series) -> pd.Series: values = pd.to_numeric(values, errors="coerce") return values[np.isfinite(values)] def describe(values: pd.Series, name: str) -> dict[str, float | int | str]: values = finite_series(values) qs = values.quantile([0.001, 0.01, 0.05, 0.5, 0.95, 0.99, 0.999]) return { "metric": name, "count": int(values.size), "min": float(values.min()), "q001": float(qs.loc[0.001]), "q01": float(qs.loc[0.01]), "q05": float(qs.loc[0.05]), "median": float(qs.loc[0.5]), "mean": float(values.mean()), "q95": float(qs.loc[0.95]), "q99": float(qs.loc[0.99]), "q999": float(qs.loc[0.999]), "max": float(values.max()), } def add_quantile_lines(ax: plt.Axes, values: pd.Series, *, color: str = "#334155") -> None: values = finite_series(values) for q, label, style in [ (0.5, "median", "-"), (0.95, "q95", "--"), (0.99, "q99", ":"), ]: x = float(values.quantile(q)) ax.axvline(x, color=color, linestyle=style, linewidth=1.4, alpha=0.85) ax.text( x, ax.get_ylim()[1] * 0.96, f" {label}={x:.3g}", rotation=90, va="top", ha="left", fontsize=8, color=color, ) def save_hist( values: pd.Series, path: Path, *, title: str, xlabel: str, bins: int | np.ndarray = 80, log_x: bool = False, xlim: tuple[float, float] | None = None, color: str = "#2563eb", ) -> None: values = finite_series(values) fig, ax = plt.subplots(figsize=(8.5, 5.2), dpi=180) ax.hist(values, bins=bins, color=color, alpha=0.82, edgecolor="white", linewidth=0.35) ax.set_title(title) ax.set_xlabel(xlabel) ax.set_ylabel("Number of materials") if log_x: ax.set_xscale("log") if xlim is not None: ax.set_xlim(*xlim) add_quantile_lines(ax, values) ax.grid(True, axis="y", alpha=0.25) fig.tight_layout() fig.savefig(path) plt.close(fig) def save_joint(last_df: pd.DataFrame, path: Path) -> None: x = finite_series(last_df["last_peak_2theta"]) y = finite_series(last_df["last_peak_intensity"]) aligned = pd.concat([x, y], axis=1).dropna() fig, ax = plt.subplots(figsize=(8.2, 5.8), dpi=180) hb = ax.hexbin( aligned["last_peak_2theta"], aligned["last_peak_intensity"], gridsize=70, cmap="viridis", mincnt=1, bins="log", ) ax.set_title("Last XRD Peak Position vs. Relative Intensity") ax.set_xlabel("Last peak 2theta (degree)") ax.set_ylabel("Last peak relative intensity (max peak = 100)") for xv in [150, 160, 170, 178]: ax.axvline(xv, color="#e11d48", linestyle="--", linewidth=0.8, alpha=0.55) ax.text(xv, ax.get_ylim()[1] * 0.98, f" {xv}", rotation=90, va="top", fontsize=8, color="#9f1239") for yv in [1, 5, 10]: ax.axhline(yv, color="#0f766e", linestyle=":", linewidth=0.9, alpha=0.65) ax.text(ax.get_xlim()[0], yv, f" {yv}", va="bottom", fontsize=8, color="#115e59") cbar = fig.colorbar(hb, ax=ax) cbar.set_label("log10(number of materials)") ax.grid(True, alpha=0.18) fig.tight_layout() fig.savefig(path) plt.close(fig) def build_last_peak_intensity(peaks_csv: Path, out_csv: Path, chunksize: int) -> pd.DataFrame: if out_csv.exists(): return pd.read_csv(out_csv) best: dict[tuple[str, int, str], tuple[float, float]] = {} usecols = ["split", "index", "material_id", "two_theta", "intensity"] for chunk in pd.read_csv(peaks_csv, usecols=usecols, chunksize=chunksize): chunk["index"] = pd.to_numeric(chunk["index"], errors="coerce").astype("Int64") chunk["two_theta"] = pd.to_numeric(chunk["two_theta"], errors="coerce") chunk["intensity"] = pd.to_numeric(chunk["intensity"], errors="coerce") chunk = chunk.dropna(subset=["index", "two_theta", "intensity"]) idx = chunk.groupby(["split", "index", "material_id"], sort=False)["two_theta"].idxmax() sub = chunk.loc[idx, usecols] for row in sub.itertuples(index=False): key = (row.split, int(row.index), row.material_id) candidate = (float(row.two_theta), float(row.intensity)) if key not in best or candidate[0] > best[key][0]: best[key] = candidate rows = [ { "split": split, "index": index, "material_id": material_id, "last_peak_2theta_from_peaks": two_theta, "last_peak_intensity": intensity, } for (split, index, material_id), (two_theta, intensity) in best.items() ] df = pd.DataFrame(rows).sort_values(["split", "index", "material_id"]) df.to_csv(out_csv, index=False) return df def write_readme(path: Path) -> None: text = """# MP-20 XRD 分布图说明 本目录中的图用于把之前的表格统计变成更直观的分布图,方便向老师解释 `2theta_max`、最后峰强度以及 bin size 的选择依据。 ## 输入数据 - `../mp20_xrd_material_stats.csv` - 每个材料一行。 - 使用其中的 `last_peak_2theta` 和 `min_peak_gap`。 - `../mp20_xrd_peaks.csv` - 每个峰一行。 - 仅用于派生每个材料最后一个峰的强度。 - 派生结果已保存为 `mp20_xrd_last_peak_intensity.csv`,后续重新画图不需要再次扫描大峰表。 ## 输出图 1. `last_peak_2theta_distribution.png` - 横轴:每个材料最后一个 XRD 峰的位置,单位为 degree 2theta。 - 纵轴:材料数量。 - 图中竖线标出 median、q95、q99。 2. `last_peak_intensity_distribution.png` - 横轴:每个材料最后一个峰的相对强度。 - pymatgen 中最强峰通常归一化为 100,因此这里的强度可以理解为“最后峰相对于最强峰的百分比”。 - 如果大量最后峰强度接近 0,说明高角度最后峰可能很弱。 3. `last_peak_2theta_vs_intensity.png` - 横轴:最后峰位置。 - 纵轴:最后峰相对强度。 - 使用 hexbin 显示二维密度,颜色越亮表示材料越多。 - 红色竖线是常见 2theta 截断参考位置;绿色横线是强度阈值参考。 - 这张图用于判断“大角度最后峰是否主要是弱峰”。 4. `min_peak_gap_distribution.png` - 横轴:每个材料内部相邻峰之间的最小间距,单位为 degree 2theta。 - 纵轴:材料数量。 - 因为最小 gap 有极小异常值,所以主图使用 log x 轴。 - 这张图用于判断离散化 bin size 是否会被极端材料过度约束。 ## 汇总表 `distribution_summary.csv` 保存四个变量的常用统计量: - `count` - `min` - `q001` - `q01` - `q05` - `median` - `mean` - `q95` - `q99` - `q999` - `max` ## 注意 第 4 张图使用的是“每个材料的最小峰间距分布”,不是所有相邻峰 gap 的总体分布。这样更符合当前任务:每个材料贡献一个最小 gap,避免峰数很多的材料在总体分布中占过大权重。 """ path.write_text(text, encoding="utf-8") def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--stats-dir", type=Path, default=Path("/workspace/mp-20/xrd_stats")) parser.add_argument("--output-dir", type=Path, default=Path("/workspace/mp-20/xrd_stats/distributions")) parser.add_argument("--chunksize", type=int, default=500_000) args = parser.parse_args() args.output_dir.mkdir(parents=True, exist_ok=True) material_csv = args.stats_dir / "mp20_xrd_material_stats.csv" peaks_csv = args.stats_dir / "mp20_xrd_peaks.csv" last_intensity_csv = args.output_dir / "mp20_xrd_last_peak_intensity.csv" material = pd.read_csv(material_csv) material = material[material["status"].eq("ok")].copy() last_intensity = build_last_peak_intensity(peaks_csv, last_intensity_csv, args.chunksize) df = material.merge(last_intensity, on=["split", "index", "material_id"], how="left") # Prefer the material-level last peak position generated by the original stats. df["last_peak_intensity"] = pd.to_numeric(df["last_peak_intensity"], errors="coerce") df[["split", "index", "material_id", "last_peak_2theta", "last_peak_intensity", "min_peak_gap"]].to_csv( args.output_dir / "mp20_xrd_distribution_materials.csv", index=False ) summaries = [ describe(df["last_peak_2theta"], "last_peak_2theta"), describe(df["last_peak_intensity"], "last_peak_intensity"), describe(df["min_peak_gap"], "per_material_min_peak_gap"), ] pd.DataFrame(summaries).to_csv(args.output_dir / "distribution_summary.csv", index=False) save_hist( df["last_peak_2theta"], args.output_dir / "last_peak_2theta_distribution.png", title="Distribution of Last XRD Peak Position", xlabel="Last peak 2theta (degree)", bins=np.linspace(120, 180, 121), color="#2563eb", ) save_hist( df["last_peak_intensity"], args.output_dir / "last_peak_intensity_distribution.png", title="Distribution of Last XRD Peak Relative Intensity", xlabel="Last peak relative intensity (max peak = 100)", bins=np.linspace(0, 100, 101), color="#059669", ) save_joint(df, args.output_dir / "last_peak_2theta_vs_intensity.png") positive_gap = df.loc[df["min_peak_gap"] > 0, "min_peak_gap"] gap_min = max(float(positive_gap.min()), 1e-6) gap_max = float(positive_gap.quantile(0.999)) save_hist( positive_gap, args.output_dir / "min_peak_gap_distribution.png", title="Distribution of Per-Material Minimum Adjacent Peak Gap", xlabel="Minimum adjacent peak gap per material (degree 2theta, log scale)", bins=np.logspace(np.log10(gap_min), np.log10(gap_max), 90), log_x=True, xlim=(gap_min, gap_max), color="#7c3aed", ) write_readme(args.output_dir / "README.md") print(f"Wrote figures and summary to {args.output_dir}") if __name__ == "__main__": main()