File size: 8,687 Bytes
9affda1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import json
import glob
import os
import pandas as pd
import numpy as np

# 1. 基础配置
methods = [
    "vanilla_3dgs", "analyticsplatting", "erankgs", "ges", 
    "lightgaussian", "minisplatting", "opti3dgs", "pgsr", 
    "steepgs", "3dgsmcmc"
]
scene_mapping = {"bonsai": "bonsai", "lego": "Lego"}
seeds = {"seed0": "", "seed1": "_seed1", "seed2": "_seed2"}

raw_records = []

# 2. 扫描数据
print("========================================================")
print("开始扫描 Seed 目录...")
for method in methods:
    for norm_scene, dir_scene in scene_mapping.items():
        for seed_id, seed_suffix in seeds.items():
            dir_name = f"{method}{seed_suffix}_{dir_scene}"
            search_dir = f"outputs/{dir_name}"

            # vanilla_3dgs 特殊 fallback 逻辑
            if method == "vanilla_3dgs" and seed_id == "seed0":
                if not os.path.exists(search_dir) or not glob.glob(f"{search_dir}/metrics_test_iter*.json"):
                    search_dir = f"outputs/{method}_{dir_scene}_bak"

            json_files = sorted(glob.glob(f"{search_dir}/metrics_test_iter*.json"))
            psnr, ssim, lpips = np.nan, np.nan, np.nan
            source_file = "MISSING"
            status = "MISSING"

            if json_files:
                target_file = json_files[-1]  # 默认取排序后的最后一个
                for jf in json_files:
                    if "30000" in jf:
                        target_file = jf
                        break

                source_file = target_file
                try:
                    with open(target_file, 'r') as f:
                        data = json.load(f)
                        # 兼容不同 JSON 层级
                        photo = data.get("photometric", data) 
                        psnr = photo.get("PSNR", photo.get("psnr", np.nan))
                        ssim = photo.get("SSIM", photo.get("ssim", np.nan))
                        lpips = photo.get("LPIPS", photo.get("lpips", np.nan))
                        status = "OK"
                except Exception:
                    pass

            # 基于业务逻辑的 Status 调整
            if method == "erankgs" and norm_scene == "lego" and psnr < 20:  # ~17dB
                status = "METHOD_FAILURE"

            raw_records.append({
                "SceneNormalized": norm_scene,
                "SceneDirName": dir_scene,
                "Method": method,
                "Seed": seed_id,
                "PSNR": psnr,
                "SSIM": ssim,
                "LPIPS": lpips,
                "Status": status,
                "SourceFile": source_file
            })

# 输出 Raw Table
os.makedirs("outputs/phase4", exist_ok=True)
df_raw = pd.DataFrame(raw_records)
raw_path = "outputs/phase4/task_4_1_seed_variance_raw_reconstructed.csv"
df_raw.to_csv(raw_path, index=False)

# 3. 生成 Summary Table
summary_records = []
for (norm_scene, method), group in df_raw.groupby(["SceneNormalized", "Method"]):
    psnrs = group["PSNR"].dropna()
    n_seeds = len(psnrs)
    psnr_mean = psnrs.mean() if n_seeds > 0 else np.nan
    psnr_std = psnrs.std(ddof=1) if n_seeds > 1 else np.nan
    psnr_min = psnrs.min() if n_seeds > 0 else np.nan
    psnr_max = psnrs.max() if n_seeds > 0 else np.nan
    psnr_range = (psnr_max - psnr_min) if n_seeds > 0 else np.nan

    statuses = group["Status"].tolist()
    if "METHOD_FAILURE" in statuses:
        final_status = "METHOD_FAILURE"
    elif method == "analyticsplatting" and norm_scene == "lego" and psnr_std > 1.0:
        final_status = "OUTLIER"
    elif "MISSING" in statuses and n_seeds < 3:
        final_status = "MISSING_SEEDS"
    else:
        final_status = "OK"

    summary_records.append({
        "Scene": norm_scene,
        "Method": method,
        "NSeeds": n_seeds,
        "PSNR_mean": psnr_mean,
        "PSNR_std": psnr_std,
        "PSNR_min": psnr_min,
        "PSNR_max": psnr_max,
        "PSNR_range": psnr_range,
        "Status": final_status
    })

df_summary = pd.DataFrame(summary_records)
sum_path = "outputs/phase4/task_4_1_seed_variance_summary_reconstructed.csv"
df_summary.to_csv(sum_path, index=False)

# 4. 生成 Kendall Tau Checked CSV
tau_file = "outputs/phase4/task_4_2_kendall_tau.json"
tau_path = "outputs/phase4/task_4_2_kendall_tau_checked.csv"
if os.path.exists(tau_file):
    with open(tau_file, 'r') as f:
        tau_data = json.load(f)
    tau_records = []
    for scene in ["bonsai", "Lego"]:
        if scene in tau_data:
            sc_data = tau_data[scene]
            tau_records.append({
                "Scene": "lego" if scene == "Lego" else "bonsai",
                "default_vs_seed1_tau": sc_data.get("default_vs_seed1", {}).get("tau"),
                "default_vs_seed1_pval": sc_data.get("default_vs_seed1", {}).get("pval"),
                "default_vs_seed2_tau": sc_data.get("default_vs_seed2", {}).get("tau"),
                "default_vs_seed2_pval": sc_data.get("default_vs_seed2", {}).get("pval"),
                "seed1_vs_seed2_tau": sc_data.get("seed1_vs_seed2", {}).get("tau"),
                "seed1_vs_seed2_pval": sc_data.get("seed1_vs_seed2", {}).get("pval"),
                "median_tau": sc_data.get("median_tau"),
                "min_tau": sc_data.get("min_tau"),
                "valid_methods_count": len(sc_data.get("valid_methods", []))
            })
    df_tau = pd.DataFrame(tau_records)
    df_tau.to_csv(tau_path, index=False)
else:
    print(f"⚠️ 警告: Kendall Tau 源文件缺失 {tau_file}")


# 5. Sanity Checks 输出
print("\n========================================================")
print("SANITY CHECKS")
print("========================================================")

# 基础计数
print(f"每个 scene 找到的 method 数量: bonsai = {len(df_summary[df_summary['Scene'] == 'bonsai'])}, lego = {len(df_summary[df_summary['Scene'] == 'lego'])}")
print(f"每个 scene 找到的 raw seed rows: bonsai = {len(df_raw[df_raw['SceneNormalized'] == 'bonsai'])}, lego = {len(df_raw[df_raw['SceneNormalized'] == 'lego'])}")

# 特殊 Cell 验证
try:
    ana_lego = df_summary[(df_summary['Method'] == 'analyticsplatting') & (df_summary['Scene'] == 'lego')].iloc[0]
    print(f"\n[验证] analyticsplatting x Lego")
    print(f"  - PSNR_mean:  {ana_lego['PSNR_mean']:.3f}")
    print(f"  - PSNR_std:   {ana_lego['PSNR_std']:.3f} (预期 ~1.33)")
    print(f"  - PSNR_range: {ana_lego['PSNR_range']:.3f} (预期 ~2.34)")
    print(f"  - Status:     {ana_lego['Status']} (预期 OUTLIER)")
except Exception as e:
    print("\n[错误] 未能定位 analyticsplatting x Lego 的聚合数据")

try:
    era_lego = df_summary[(df_summary['Method'] == 'erankgs') & (df_summary['Scene'] == 'lego')].iloc[0]
    print(f"\n[验证] erankgs x Lego")
    print(f"  - PSNR_mean:  {era_lego['PSNR_mean']:.3f} (预期 ~17)")
    print(f"  - PSNR_std:   {era_lego['PSNR_std']:.3f}")
    print(f"  - PSNR_range: {era_lego['PSNR_range']:.3f}")
    print(f"  - Status:     {era_lego['Status']} (预期 METHOD_FAILURE)")
except Exception as e:
    print("\n[错误] 未能定位 erankgs x Lego 的聚合数据")

# 队列级中位数与 P95 (排除 METHOD_FAILURE)
valid_stds_incl = df_summary[df_summary["Status"].isin(["OK", "OUTLIER"])]["PSNR_std"].dropna()
valid_stds_excl = df_summary[df_summary["Status"] == "OK"]["PSNR_std"].dropna()

med_incl = valid_stds_incl.median()
p95_incl = valid_stds_incl.quantile(0.95)
med_excl = valid_stds_excl.median()
p95_excl = valid_stds_excl.quantile(0.95)

print("\n[验证] Cohort PSNR Std 统计")
print(f"  - Median (including outlier): {med_incl:.4f}")
print(f"  - P95    (including outlier): {p95_incl:.4f}")
print(f"  - Median (excluding outlier): {med_excl:.4f}")
print(f"  - P95    (excluding outlier): {p95_excl:.4f}")

if abs(p95_incl - 0.384) > 0.005 and abs(p95_excl - 0.384) > 0.005:
    print(f"\n⚠️ 论文一致性警告:")
    print(f"不一致:论文中声明 P95=0.384 dB,但重算结果为包含Outlier: {p95_incl:.3f}, 排除Outlier: {p95_excl:.3f}")
else:
    print(f"\n✅ P95=0.384 dB 与论文声明一致")

# Kendall Tau
if 'df_tau' in locals():
    print("\n[验证] Kendall Tau 值")
    b_tau = df_tau[df_tau["Scene"] == "bonsai"]["median_tau"].iloc[0]
    l_tau = df_tau[df_tau["Scene"] == "lego"]["median_tau"].iloc[0]
    print(f"  - bonsai median_tau: {b_tau:.4f} (预期: 0.7778)")
    print(f"  - Lego median_tau:   {l_tau:.4f} (预期: 0.8571)")

print("\n========================================================")
print("生成的文件清单:")
print(f"1. {raw_path}")
print(f"2. {sum_path}")
print(f"3. {tau_path}")
print("========================================================")