Newer
Older
SmTIAS-Evaluation / src / export / exporter.py
"""CSV・PNG 出力モジュール."""

import csv
from pathlib import Path

SUMMARY_FIELDNAMES = ["image_name", "mean", "std", "cov", "max_min_ratio", "max", "min"]
SPATIAL_FIELDNAMES = [
    "image_name",
    "center_mean",
    "middle_mean",
    "periphery_mean",
    "center_periphery_ratio",
    "gradient_magnitude",
]


def ensure_output_dirs(base_path: str) -> None:
    """output/figures/, output/results/, output/reports/ ディレクトリを作成する.

    Args:
        base_path: 出力ルートディレクトリのパス.
    """
    base = Path(base_path)
    (base / "figures").mkdir(parents=True, exist_ok=True)
    (base / "results").mkdir(parents=True, exist_ok=True)
    (base / "reports").mkdir(parents=True, exist_ok=True)
    print(f"出力ディレクトリを確認しました: {base}")


def export_results(results: dict, output_path: str) -> None:
    """均一性指標を CSV ファイルに出力する.

    CSV の形式は 1 行目がヘッダー,2 行目が値.

    Args:
        results: 均一性指標の辞書(calc_uniformity の戻り値).
        output_path: 出力先ファイルパス(CSV).
    """
    Path(output_path).parent.mkdir(parents=True, exist_ok=True)

    with Path(output_path).open("w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=list(results.keys()))
        writer.writeheader()
        writer.writerow(results)

    print(f"結果を保存しました: {output_path}")


def export_summary(all_results: list[dict], output_path: str) -> None:
    """バッチ解析の集約結果を CSV ファイルに出力する.

    CSV の形式は 1 行目がヘッダー,2 行目以降が各画像の値.

    Args:
        all_results: 均一性指標の辞書リスト.各要素は
            {"image_name": "xxx", "mean": ..., "std": ..., "cov": ...,
             "max_min_ratio": ..., "max": ..., "min": ...} の形式.
        output_path: 出力先ファイルパス(CSV).
    """
    Path(output_path).parent.mkdir(parents=True, exist_ok=True)

    with Path(output_path).open("w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=SUMMARY_FIELDNAMES, extrasaction="ignore")
        writer.writeheader()
        writer.writerows(all_results)

    print(f"まとめ CSV を保存しました: {output_path}")


def export_spatial_summary(all_results: list[dict], output_path: str) -> None:
    """空間解析の集約結果を CSV ファイルに出力する.

    CSV の形式は 1 行目がヘッダー,2 行目以降が各画像の値.

    Args:
        all_results: 空間解析結果を含む辞書リスト.各要素は
            {"image_name": "xxx", "center_mean": ..., "middle_mean": ...,
             "periphery_mean": ..., "center_periphery_ratio": ...,
             "gradient_magnitude": ...} を含む形式.
        output_path: 出力先ファイルパス(CSV).
    """
    Path(output_path).parent.mkdir(parents=True, exist_ok=True)

    with Path(output_path).open("w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=SPATIAL_FIELDNAMES, extrasaction="ignore")
        writer.writeheader()
        writer.writerows(all_results)

    print(f"空間解析まとめ CSV を保存しました: {output_path}")