def generate_summary(results_dict, experiment_name, elapsed_seconds,
output_path=None):
"""
標準フォーマットの analysis_summary.json を生成する。
results_dict はドメイン固有の結果を含む辞書。
この関数がメタ情報を自動追加する。
"""
import datetime
summary = {
"experiment": experiment_name,
"timestamp": datetime.datetime.now().isoformat(),
"elapsed_seconds": round(elapsed_seconds, 2),
"environment": {
"python": __import__("sys").version,
"seed": SEED,
},
"data": {
"n_samples": results_dict.get("n_samples"),
"n_features": results_dict.get("n_features"),
"source": results_dict.get("data_source", "simulation"),
},
"results": results_dict,
}
if output_path is None:
output_path = RESULTS_DIR / "analysis_summary.json"
with open(output_path, "w", encoding="utf-8") as f:
json.dump(summary, f, indent=2, ensure_ascii=False, default=str)
print(f" → Summary saved: {output_path}")
return summary
import matplotlib.gridspec as gridspec
def create_summary_panel(panel_data, experiment_name, figsize=(20, 14)):
"""
解析結果の総括ダッシュボードを 1 枚の Figure にまとめる。
panel_data: [
{"type": "table", "title": "...", "data": df_or_dict},
{"type": "plot_func", "title": "...", "func": callable, "kwargs": {}},
{"type": "text", "title": "...", "text": "..."},
{"type": "metrics_bar", "title": "...", "names": [...], "values": [...]},
]
"""
n_panels = len(panel_data)
ncols = min(3, n_panels)
nrows = (n_panels + ncols - 1) // ncols
fig = plt.figure(figsize=figsize)
gs = gridspec.GridSpec(nrows, ncols, figure=fig, hspace=0.4, wspace=0.3)
for i, panel in enumerate(panel_data):
row, col = divmod(i, ncols)
ax = fig.add_subplot(gs[row, col])
ptype = panel["type"]
title = panel.get("title", f"Panel {chr(65 + i)}")
if ptype == "metrics_bar":
ax.barh(panel["names"], panel["values"],
color="steelblue", edgecolor="black")
ax.set_xlabel("Value")
elif ptype == "text":
ax.text(0.05, 0.95, panel["text"], transform=ax.transAxes,
fontsize=9, verticalalignment="top", fontfamily="monospace",
bbox=dict(boxstyle="round", facecolor="wheat", alpha=0.5))
ax.axis("off")
elif ptype == "table":
ax.axis("off")
if isinstance(panel["data"], pd.DataFrame):
tbl = ax.table(cellText=panel["data"].values,
colLabels=panel["data"].columns,
cellLoc="center", loc="center")
tbl.auto_set_font_size(False)
tbl.set_fontsize(8)
elif isinstance(panel["data"], dict):
rows = [[k, str(v)] for k, v in panel["data"].items()]
tbl = ax.table(cellText=rows, colLabels=["Metric", "Value"],
cellLoc="center", loc="center")
tbl.auto_set_font_size(False)
tbl.set_fontsize(9)
elif ptype == "plot_func":
panel["func"](ax=ax, **panel.get("kwargs", {}))
ax.set_title(f"({chr(65 + i)}) {title}", fontsize=11, fontweight="bold")
fig.suptitle(f"Summary: {experiment_name}", fontsize=14, fontweight="bold")
plt.savefig(FIG_DIR / "summary_panel.png", dpi=300, bbox_inches="tight")
plt.close()
def save_fig(fig, filename, dpi=300, formats=("png",)):
"""図を保存してクローズする共通関数。"""
for fmt in formats:
fig.savefig(FIG_DIR / f"{filename}.{fmt}",
dpi=dpi, bbox_inches="tight",
facecolor="white", edgecolor="none")
plt.close(fig)
print(f" → Figure saved: {filename}")
def save_results(df, filename, index=False):
"""DataFrame を results/ に保存する共通関数。"""
path = RESULTS_DIR / filename
df.to_csv(path, index=index)
print(f" → Results saved: {filename}")