""" 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")