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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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
"""
Visualization Utilities for Enhanced Symplectic LLM Experiment
可視化ユーティリティ

Author: Kazuhiro Kojima
Version: 1.0.0
"""

import matplotlib.pyplot as plt
import seaborn as sns
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.express as px
import numpy as np
import pandas as pd
from typing import Dict, List, Any, Optional, Tuple
import logging
from datetime import datetime

# 設定
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# プロット設定
plt.style.use('seaborn-v0_8')
sns.set_palette("husl")

class ResultsVisualizer:
    """実験結果可視化メインクラス"""
    
    def __init__(self, theme: str = 'plotly_white'):
        self.theme = theme
        self.color_palette = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b']
        self.figure_config = {
            'width': 1200,
            'height': 800,
            'font_size': 12,
            'title_font_size': 16
        }
        
        logger.info("📊 ResultsVisualizer initialized")
    
    def create_comprehensive_plots(self, results: Dict[str, Any]) -> go.Figure:
        """包括的可視化作成"""
        try:
            # データ抽出
            raw_results = results.get('raw_results', {})
            statistical_analysis = results.get('statistical_analysis', {})
            
            if not raw_results:
                return self._create_error_plot("データが見つかりません")
            
            # サブプロット作成
            fig = make_subplots(
                rows=2, cols=2,
                subplot_titles=[
                    "セマンティックドリフト分布比較",
                    "効果量と信頼区間", 
                    "統計的有意性 (-log10 p値)",
                    "条件別要約統計"
                ],
                specs=[
                    [{"secondary_y": False}, {"secondary_y": False}],
                    [{"secondary_y": False}, {"secondary_y": False}]
                ],
                #【修正】間隔を広げる
                horizontal_spacing=0.15,  # 水平間隔
                vertical_spacing=0.15     # 垂直間隔
            )
            
            # 1. ドリフト分布のボックスプロット
            self._add_distribution_plot(fig, raw_results, row=1, col=1)
            
            # 2. 効果量プロット
            self._add_effect_size_plot(fig, statistical_analysis, row=1, col=2)
            
            # 3. p値プロット
            self._add_pvalue_plot(fig, statistical_analysis, row=2, col=1)
            
            # 4. 要約統計プロット
            self._add_summary_stats_plot(fig, raw_results, row=2, col=2)
            
            # レイアウト調整
            fig.update_layout(
                height=1000,  # 高さを拡大 800 → 1000
                width=1400,   # 幅を拡大 1200 → 1400
                #height=self.figure_config['height'],
                #width=self.figure_config['width'],
                title_text="🔬 Enhanced Symplectic LLM Experiment Results",
                title_x=0.5,
                title_font_size=self.figure_config['title_font_size'],
                showlegend=True,
                template=self.theme
            )
            
            return fig
            
        except Exception as e:
            logger.error(f"Visualization creation failed: {e}")
            return self._create_error_plot(f"可視化エラー: {str(e)}")
    
    def _add_distribution_plot(self, fig: go.Figure, raw_results: Dict[str, List[float]], 
                             row: int, col: int):
        """ドリフト分布プロット追加"""
        conditions = list(raw_results.keys())
        
        for i, condition in enumerate(conditions):
            if raw_results[condition]:  # データが存在する場合
                fig.add_trace(
                    go.Box(
                        y=raw_results[condition],
                        name=condition.replace('_', ' ').title(),
                        boxpoints='outliers',
                        marker_color=self.color_palette[i % len(self.color_palette)],
                        showlegend=False
                    ),
                    row=row, col=col
                )
        
        fig.update_xaxes(title_text="実験条件", row=row, col=col)
        fig.update_yaxes(title_text="セマンティックドリフト", row=row, col=col)
    
    def _add_effect_size_plot(self, fig: go.Figure, statistical_analysis: Dict[str, Any],
                            row: int, col: int):
        """効果量プロット追加"""
        individual_comparisons = statistical_analysis.get('individual_comparisons', {})
        
        if not individual_comparisons:
            # データなしの場合のプレースホルダー
            fig.add_trace(
                go.Scatter(
                    x=[0], y=[0],
                    mode='text',
                    text=['データなし'],
                    showlegend=False
                ),
                row=row, col=col
            )
            return
        
        comparisons = list(individual_comparisons.keys())
        effect_sizes = []
        ci_lowers = []
        ci_uppers = []
        
        for comp in comparisons:
            result = individual_comparisons[comp]
            effect_sizes.append(result.get('cohens_d', 0))
            ci_lowers.append(result.get('ci_lower', 0))
            ci_uppers.append(result.get('ci_upper', 0))
        
        # 効果量バープロット
        fig.add_trace(
            go.Bar(
                x=[c.replace('_', ' ').title() for c in comparisons],
                y=effect_sizes,
                error_y=dict(
                    type='data',
                    symmetric=False,
                    array=[u - e for e, u in zip(effect_sizes, ci_uppers)],
                    arrayminus=[e - l for e, l in zip(effect_sizes, ci_lowers)]
                ),
                name="Cohen's d",
                marker_color=self.color_palette[1],
                showlegend=False
            ),
            row=row, col=col
        )
        
        # 効果量解釈線
        for threshold, label, color in [(0.2, "Small", "green"), (0.5, "Medium", "orange"), (0.8, "Large", "red")]:
            fig.add_hline(y=threshold, line_dash="dash", line_color=color, 
                         annotation_text=label, row=row, col=col)
            fig.add_hline(y=-threshold, line_dash="dash", line_color=color, row=row, col=col)
        
        fig.update_xaxes(title_text="比較", row=row, col=col)
        fig.update_yaxes(title_text="効果量 (Cohen's d)", row=row, col=col)
    
    def _add_pvalue_plot(self, fig: go.Figure, statistical_analysis: Dict[str, Any],
                        row: int, col: int):
        """p値プロット追加"""
        individual_comparisons = statistical_analysis.get('individual_comparisons', {})
        
        if not individual_comparisons:
            fig.add_trace(
                go.Scatter(x=[0], y=[0], mode='text', text=['データなし'], showlegend=False),
                row=row, col=col
            )
            return
        
        comparisons = list(individual_comparisons.keys())
        p_values = []
        
        for comp in comparisons:
            result = individual_comparisons[comp]
            p_val = result.get('p_value', 1.0)
            p_values.append(max(-np.log10(p_val), 0))  # log10変換
        
        # p値散布図
        colors = ['red' if individual_comparisons[comp].get('significant', False) else 'gray' 
                 for comp in comparisons]
        
        fig.add_trace(
            go.Scatter(
                x=[c.replace('_', ' ').title() for c in comparisons],
                y=p_values,
                mode='markers+lines',
                marker=dict(size=12, color=colors),
                name="-log10(p-value)",
                showlegend=False
            ),
            row=row, col=col
        )
        
        # 有意水準線
        fig.add_hline(y=-np.log10(0.05), line_dash="dash", line_color="red",
                     annotation_text="p=0.05", row=row, col=col)
        fig.add_hline(y=-np.log10(0.01), line_dash="dash", line_color="orange", 
                     annotation_text="p=0.01", row=row, col=col)
        
        fig.update_xaxes(title_text="比較", row=row, col=col)
        fig.update_yaxes(title_text="-log10(p-value)", row=row, col=col)
    
    def _add_summary_stats_plot(self, fig: go.Figure, raw_results: Dict[str, List[float]],
                               row: int, col: int):
        """要約統計プロット追加"""
        conditions = list(raw_results.keys())
        means = []
        stds = []
        
        for condition in conditions:
            if raw_results[condition]:
                means.append(np.mean(raw_results[condition]))
                stds.append(np.std(raw_results[condition]))
            else:
                means.append(0)
                stds.append(0)
        
        # 平均値エラーバープロット
        fig.add_trace(
            go.Scatter(
                x=[c.replace('_', ' ').title() for c in conditions],
                y=means,
                error_y=dict(type='data', array=stds),
                mode='markers+lines',
                marker=dict(size=10, color=self.color_palette[2]),
                name="平均±標準偏差",
                showlegend=False
            ),
            row=row, col=col
        )
        
        fig.update_xaxes(title_text="実験条件", row=row, col=col)
        fig.update_yaxes(title_text="平均セマンティックドリフト", row=row, col=col)
    
    def _create_error_plot(self, error_message: str) -> go.Figure:
        """エラー表示プロット作成"""
        fig = go.Figure()
        fig.add_trace(
            go.Scatter(
                x=[0.5], y=[0.5],
                mode='text',
                text=[f"❌ {error_message}"],
                textfont=dict(size=16, color='red'),
                showlegend=False
            )
        )
        
        fig.update_layout(
            title="可視化エラー",
            xaxis=dict(range=[0, 1], showticklabels=False),
            yaxis=dict(range=[0, 1], showticklabels=False),
            width=600, height=400
        )
        
        return fig

class StatisticalPlotter:
    """統計プロット専用クラス"""
    
    def __init__(self):
        self.style_config = {
            'figure.figsize': (12, 8),
            'font.size': 10,
            'axes.titlesize': 14,
            'axes.labelsize': 12,
            'xtick.labelsize': 10,
            'ytick.labelsize': 10,
            'legend.fontsize': 10
        }
        
        plt.rcParams.update(self.style_config)
    
    def create_forest_plot(self, comparisons: Dict[str, Dict[str, float]], 
                          save_path: Optional[str] = None) -> plt.Figure:
        """フォレストプロット作成(効果量と信頼区間)"""
        fig, ax = plt.subplots(figsize=(10, 6))
        
        comp_names = list(comparisons.keys())
        y_positions = range(len(comp_names))
        
        for i, (comp_name, result) in enumerate(comparisons.items()):
            effect_size = result.get('cohens_d', 0)
            ci_lower = result.get('ci_lower', 0)
            ci_upper = result.get('ci_upper', 0)
            significant = result.get('significant', False)
            
            # 効果量点
            color = 'red' if significant else 'blue'
            ax.scatter(effect_size, i, color=color, s=100, zorder=3)
            
            # 信頼区間
            ax.plot([ci_lower, ci_upper], [i, i], color=color, linewidth=2, zorder=2)
            ax.plot([ci_lower, ci_lower], [i-0.1, i+0.1], color=color, linewidth=2, zorder=2)
            ax.plot([ci_upper, ci_upper], [i-0.1, i+0.1], color=color, linewidth=2, zorder=2)
        
        # 効果量境界線
        ax.axvline(x=0, color='black', linestyle='-', alpha=0.3)
        ax.axvline(x=0.2, color='green', linestyle='--', alpha=0.5, label='Small effect')
        ax.axvline(x=0.5, color='orange', linestyle='--', alpha=0.5, label='Medium effect')
        ax.axvline(x=0.8, color='red', linestyle='--', alpha=0.5, label='Large effect')
        
        ax.set_yticks(y_positions)
        ax.set_yticklabels([name.replace('_', ' ').title() for name in comp_names])
        ax.set_xlabel("Effect Size (Cohen's d)")
        ax.set_title("Effect Sizes with 95% Confidence Intervals")
        ax.legend()
        ax.grid(True, alpha=0.3)
        
        plt.tight_layout()
        
        if save_path:
            plt.savefig(save_path, dpi=300, bbox_inches='tight')
            logger.info(f"Forest plot saved to {save_path}")
        
        return fig
    
    def create_power_analysis_plot(self, effect_sizes: np.ndarray, 
                                 sample_sizes: np.ndarray,
                                 save_path: Optional[str] = None) -> plt.Figure:
        """検出力分析プロット作成"""
        from scipy.stats import t
        
        fig, ax = plt.subplots(figsize=(10, 6))
        
        # 検出力計算
        alpha = 0.05
        for effect_size in [0.2, 0.5, 0.8]:
            powers = []
            for n in sample_sizes:
                # 簡易検出力計算
                t_crit = t.ppf(1 - alpha/2, 2*n - 2)
                ncp = effect_size * np.sqrt(n/2)  # 非心パラメータ
                power = 1 - t.cdf(t_crit, 2*n - 2, ncp) + t.cdf(-t_crit, 2*n - 2, ncp)
                powers.append(power)
            
            ax.plot(sample_sizes, powers, label=f'Effect size = {effect_size}', linewidth=2)
        
        ax.axhline(y=0.8, color='red', linestyle='--', alpha=0.7, label='Power = 0.8')
        ax.set_xlabel('Sample Size (per group)')
        ax.set_ylabel('Statistical Power')
        ax.set_title('Power Analysis: Sample Size vs. Statistical Power')
        ax.legend()
        ax.grid(True, alpha=0.3)
        
        plt.tight_layout()
        
        if save_path:
            plt.savefig(save_path, dpi=300, bbox_inches='tight')
            logger.info(f"Power analysis plot saved to {save_path}")
        
        return fig

# ユーティリティ関数
def create_comparison_plots(results: Dict[str, Any], output_dir: str = ".") -> List[str]:
    """比較プロット一括作成"""
    visualizer = ResultsVisualizer()
    plotter = StatisticalPlotter()
    
    saved_files = []
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    
    try:
        # 1. メインプロット
        main_plot = visualizer.create_comprehensive_plots(results)
        main_path = f"{output_dir}/comprehensive_results_{timestamp}.html"
        main_plot.write_html(main_path)
        saved_files.append(main_path)
        
        # 2. フォレストプロット
        if 'statistical_analysis' in results:
            individual_comparisons = results['statistical_analysis'].get('individual_comparisons', {})
            if individual_comparisons:
                forest_path = f"{output_dir}/forest_plot_{timestamp}.png"
                plotter.create_forest_plot(individual_comparisons, forest_path)
                saved_files.append(forest_path)
        
        # 3. 検出力分析プロット
        sample_sizes = np.arange(10, 200, 10)
        effect_sizes = np.array([0.2, 0.5, 0.8])
        power_path = f"{output_dir}/power_analysis_{timestamp}.png"
        plotter.create_power_analysis_plot(effect_sizes, sample_sizes, power_path)
        saved_files.append(power_path)
        
        logger.info(f"📊 Created {len(saved_files)} visualization files")
        
    except Exception as e:
        logger.error(f"Plot creation failed: {e}")
    
    return saved_files

def create_distribution_plots(raw_results: Dict[str, List[float]], 
                            output_dir: str = ".") -> str:
    """分布プロット作成"""
    fig, axes = plt.subplots(2, 2, figsize=(12, 10))
    fig.suptitle('Semantic Drift Distribution Analysis', fontsize=16)
    
    conditions = list(raw_results.keys())
    
    # ヒストグラム
    for i, condition in enumerate(conditions[:4]):  # 最大4条件
        row, col = i // 2, i % 2
        if raw_results[condition]:
            axes[row, col].hist(raw_results[condition], bins=20, alpha=0.7, 
                              label=condition.replace('_', ' ').title())
            axes[row, col].set_title(f'{condition.replace("_", " ").title()} Distribution')
            axes[row, col].set_xlabel('Semantic Drift')
            axes[row, col].set_ylabel('Frequency')
            axes[row, col].grid(True, alpha=0.3)
    
    plt.tight_layout()
    
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    save_path = f"{output_dir}/distribution_analysis_{timestamp}.png"
    plt.savefig(save_path, dpi=300, bbox_inches='tight')
    plt.close()
    
    logger.info(f"📊 Distribution plot saved to {save_path}")
    return save_path

# エクスポート
__all__ = [
    'ResultsVisualizer',
    'StatisticalPlotter',
    'create_comparison_plots',
    'create_distribution_plots'
]

if __name__ == "__main__":
    # テスト実行
    print("📊 Visualization utilities test")
    
    # サンプルデータ
    sample_results = {
        'raw_results': {
            'baseline_T1.0': np.random.normal(0.8, 0.1, 100).tolist(),
            'temp_T0.7': np.random.normal(0.75, 0.1, 100).tolist(),
            'symp_prompt_T0.7': np.random.normal(0.7, 0.1, 100).tolist()
        },
        'statistical_analysis': {
            'individual_comparisons': {
                'baseline_vs_symp': {
                    'cohens_d': 1.5,
                    'ci_lower': 1.2,
                    'ci_upper': 1.8,
                    'p_value': 0.001,
                    'significant': True
                }
            }
        }
    }
    
    # 可視化テスト
    visualizer = ResultsVisualizer()
    fig = visualizer.create_comprehensive_plots(sample_results)
    print("✅ Comprehensive plot created")
    
    print("✅ Visualization test completed")