""" Enhanced Analysis Engine for Enhanced Symplectic LLM Experiment 強化された実験分析エンジン Author: Kazuhiro Kojima Version: 1.0.0 """ import asyncio import json import time import logging import traceback from datetime import datetime from typing import Dict, List, Any, Optional, Callable, Tuple from dataclasses import dataclass, asdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np # OpenAI API 互換性対応 import openai try: from openai import OpenAI OPENAI_V1_PLUS = True except ImportError: OPENAI_V1_PLUS = False # 内部モジュール from .statistics_utils import StatisticalAnalyzer, batch_statistical_analysis from .data_generator import CorpusExpander from config import ( OPENAI_CONFIG, EXPERIMENT_DEFAULTS, PROMPT_TEMPLATES, HARDWARE_CONFIG, CURRENT_HARDWARE ) # ログ設定 logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # 以下、残りのコードは同じ... @dataclass class ExperimentConfig: """実験設定データクラス""" sample_size: int n_trials: int max_tokens: int temperature_baseline: float temperature_control: float embedding_model: str chat_model: str max_concurrent_requests: int checkpoint_enabled: bool @classmethod def from_defaults(cls, sample_size: int = None, n_trials: int = None): """デフォルト設定から作成""" return cls( sample_size=sample_size or EXPERIMENT_DEFAULTS['sample_size_default'], n_trials=n_trials or EXPERIMENT_DEFAULTS['n_trials_default'], max_tokens=EXPERIMENT_DEFAULTS['max_tokens'], temperature_baseline=EXPERIMENT_DEFAULTS['temperature_baseline'], temperature_control=EXPERIMENT_DEFAULTS['temperature_control'], embedding_model=OPENAI_CONFIG['embedding_model'], chat_model=OPENAI_CONFIG['chat_model'], max_concurrent_requests=HARDWARE_CONFIG[CURRENT_HARDWARE]['max_concurrent_requests'], checkpoint_enabled=True ) class APIOptimizer: """API呼び出し最適化クラス(修正版)""" def __init__(self, max_concurrent: int = 8, rate_limit_delay: float = 1.0): self.max_concurrent = max_concurrent self.rate_limit_delay = rate_limit_delay self.call_count = 0 self.error_count = 0 self.last_call_time = time.time() async def rate_limited_call(self, func, *args, **kwargs): """レート制限対応API呼び出し(修正版)""" # レート制限遵守 elapsed = time.time() - self.last_call_time if elapsed < self.rate_limit_delay: await asyncio.sleep(self.rate_limit_delay - elapsed) max_retries = 3 for attempt in range(max_retries): try: self.last_call_time = time.time() result = await asyncio.get_event_loop().run_in_executor( None, func, *args, **kwargs ) self.call_count += 1 return result except Exception as e: # 新しい例外処理 error_type = type(e).__name__ if "rate" in str(e).lower() or "limit" in str(e).lower(): wait_time = min(2 ** attempt, 60) # 指数バックオフ logger.warning(f"Rate limit hit, waiting {wait_time}s (attempt {attempt+1})") await asyncio.sleep(wait_time) elif "timeout" in str(e).lower() or "connection" in str(e).lower(): self.error_count += 1 if attempt == max_retries - 1: logger.error(f"API call failed after {max_retries} attempts: {e}") raise await asyncio.sleep(2) else: # その他のエラー self.error_count += 1 logger.error(f"API error: {e}") raise raise Exception("Max retries exceeded") class ResultsManager: """結果管理クラス(変更なし)""" def __init__(self): self.raw_data = {} self.processed_results = {} self.metadata = {} def store_raw_data(self, condition: str, trial: int, data: Dict[str, Any]): """生データ保存""" if condition not in self.raw_data: self.raw_data[condition] = {} self.raw_data[condition][trial] = data def get_drift_scores(self, condition: str) -> List[float]: """ドリフトスコア取得""" scores = [] if condition in self.raw_data: for trial_data in self.raw_data[condition].values(): if 'drift_scores' in trial_data: scores.extend(trial_data['drift_scores']) return scores def calculate_summary_statistics(self) -> Dict[str, Any]: """サマリー統計計算""" summary = {} for condition in self.raw_data.keys(): drift_scores = self.get_drift_scores(condition) if drift_scores: summary[condition] = { 'mean': np.mean(drift_scores), 'std': np.std(drift_scores, ddof=1), 'median': np.median(drift_scores), 'min': np.min(drift_scores), 'max': np.max(drift_scores), 'count': len(drift_scores) } return summary class EnhancedExperiment: """強化された実験クラス(修正版)""" def __init__(self, api_key: str, sample_size: int = None, n_trials: int = None, progress_callback: Optional[Callable] = None): # 設定 self.config = ExperimentConfig.from_defaults(sample_size, n_trials) self.progress_callback = progress_callback # API設定(修正版) if OPENAI_V1: self.client = OpenAI(api_key=api_key) else: openai.api_key = api_key self.client = None self.api_optimizer = APIOptimizer( max_concurrent=self.config.max_concurrent_requests ) # 管理オブジェクト self.results_manager = ResultsManager() self.statistical_analyzer = StatisticalAnalyzer() self.corpus_expander = CorpusExpander() # 状態管理 self.total_progress = 0 self.current_progress = 0 logger.info(f"🔬 Enhanced experiment initialized: {self.config.sample_size} samples, {self.config.n_trials} trials") def _update_progress(self, current: int, total: int, stage: str, details: str = ""): """進捗更新""" self.current_progress = current self.total_progress = total if self.progress_callback: self.progress_callback(current, total, stage, details) async def _generate_text_async(self, prompt: str, temperature: float) -> str: """非同期テキスト生成(修正版)""" def api_call(): if OPENAI_V1: # 新しいバージョン response = self.client.chat.completions.create( model=self.config.chat_model, messages=[{"role": "user", "content": prompt}], temperature=temperature, max_tokens=self.config.max_tokens, timeout=OPENAI_CONFIG['timeout_seconds'] ) return response.choices[0].message.content.strip() else: # 古いバージョン response = openai.ChatCompletion.create( model=self.config.chat_model, messages=[{"role": "user", "content": prompt}], temperature=temperature, max_tokens=self.config.max_tokens, timeout=OPENAI_CONFIG['timeout_seconds'] ) return response.choices[0].message.content.strip() return await self.api_optimizer.rate_limited_call(api_call) async def _get_embedding_async(self, text: str) -> List[float]: """非同期埋め込み取得(修正版)""" def api_call(): if OPENAI_V1: # 新しいバージョン response = self.client.embeddings.create( model=self.config.embedding_model, input=text ) return response.data[0].embedding else: # 古いバージョン response = openai.Embedding.create( model=self.config.embedding_model, input=text ) return response['data'][0]['embedding'] return await self.api_optimizer.rate_limited_call(api_call) # 残りのメソッドは変更なし... def _create_prompts(self, sentence: str) -> Dict[str, str]: """プロンプト作成""" return { 'baseline': PROMPT_TEMPLATES['baseline'].format( sentence=sentence, max_tokens=self.config.max_tokens ), 'symp_prompt': PROMPT_TEMPLATES['symp_prompt'].format( sentence=sentence, max_tokens=self.config.max_tokens ) } async def _process_single_sentence(self, sentence: str, condition: str) -> Dict[str, Any]: """単文処理""" prompts = self._create_prompts(sentence) # 温度設定 if condition == 'baseline_T1.0': temperature = self.config.temperature_baseline prompt = prompts['baseline'] elif condition == 'temp_T0.7': temperature = self.config.temperature_control prompt = prompts['baseline'] elif condition == 'symp_prompt_T0.7': temperature = self.config.temperature_control prompt = prompts['symp_prompt'] else: raise ValueError(f"Unknown condition: {condition}") try: # テキスト生成 generated_text = await self._generate_text_async(prompt, temperature) # 埋め込み取得 original_embedding = await self._get_embedding_async(sentence) combined_text = sentence + " " + generated_text generated_embedding = await self._get_embedding_async(combined_text) # ドリフト計算 drift = np.linalg.norm( np.array(original_embedding) - np.array(generated_embedding) ) return { 'sentence': sentence, 'generated_text': generated_text, 'drift_score': drift, 'condition': condition, 'success': True } except Exception as e: logger.error(f"Error processing sentence in {condition}: {e}") return { 'sentence': sentence, 'error': str(e), 'condition': condition, 'success': False } # 以下のメソッドは変更なし(長いので省略) async def _run_trial_async(self, trial_num: int, corpus: List[str]) -> Dict[str, Any]: """非同期試行実行""" trial_results = { 'baseline_T1.0': [], 'temp_T0.7': [], 'symp_prompt_T0.7': [] } conditions = list(trial_results.keys()) total_tasks = len(corpus) * len(conditions) completed_tasks = 0 # 各条件での処理 for condition in conditions: self._update_progress( completed_tasks, total_tasks, f"Trial {trial_num+1}", f"Processing {condition}" ) # バッチ処理でセンテンスを処理 batch_size = self.config.max_concurrent_requests for i in range(0, len(corpus), batch_size): batch_sentences = corpus[i:i+batch_size] # 並列処理 tasks = [ self._process_single_sentence(sentence, condition) for sentence in batch_sentences ] batch_results = await asyncio.gather(*tasks, return_exceptions=True) # 結果処理 for result in batch_results: if isinstance(result, Exception): logger.error(f"Task failed: {result}") elif result.get('success', False): trial_results[condition].append(result['drift_score']) completed_tasks += 1 # 進捗更新 self._update_progress( completed_tasks, total_tasks, f"Trial {trial_num+1}", f"{condition}: {len(trial_results[condition])} completed" ) return trial_results def _run_single_trial(self, trial_num: int, corpus: List[str]) -> Dict[str, Any]: """単一試行実行(同期ラッパー)""" loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: return loop.run_until_complete(self._run_trial_async(trial_num, corpus)) finally: loop.close() def run_full_experiment(self) -> Dict[str, Any]: """完全実験実行""" start_time = time.time() try: # コーパス準備 self._update_progress(0, 100, "初期化", "コーパス準備中") corpus = self.corpus_expander.expand_corpus(self.config.sample_size) logger.info(f"📚 Corpus prepared: {len(corpus)} sentences") # 全試行実行 all_results = { 'baseline_T1.0': [], 'temp_T0.7': [], 'symp_prompt_T0.7': [] } for trial in range(self.config.n_trials): self._update_progress( trial, self.config.n_trials, "実験実行", f"Trial {trial+1}/{self.config.n_trials}" ) trial_results = self._run_single_trial(trial, corpus) # 結果蓄積 for condition, scores in trial_results.items(): all_results[condition].extend(scores) # 中間結果保存 self.results_manager.store_raw_data(condition, trial, { 'drift_scores': scores, 'trial_num': trial, 'timestamp': datetime.now().isoformat() }) logger.info(f"✅ Trial {trial+1} completed") # 統計分析 self._update_progress(90, 100, "分析", "統計分析実行中") statistical_results = self._perform_statistical_analysis(all_results) # 結果統合 self._update_progress(95, 100, "完了", "結果統合中") execution_time = time.time() - start_time final_results = { 'raw_results': all_results, 'statistical_analysis': statistical_results, 'experiment_config': asdict(self.config), 'metadata': { 'execution_time_seconds': execution_time, 'api_calls_made': self.api_optimizer.call_count, 'api_errors': self.api_optimizer.error_count, 'timestamp': datetime.now().isoformat(), 'corpus_size': len(corpus), 'total_samples_processed': sum(len(scores) for scores in all_results.values()) }, 'summary_statistics': self.results_manager.calculate_summary_statistics() } self._update_progress(100, 100, "完了", "実験終了") logger.info(f"🎉 Experiment completed in {execution_time:.1f} seconds") return final_results except Exception as e: logger.error(f"❌ Experiment failed: {e}") logger.error(traceback.format_exc()) raise def _perform_statistical_analysis(self, results: Dict[str, List[float]]) -> Dict[str, Any]: """統計分析実行""" # 個別比較 comparisons = [ ('baseline_T1.0', 'temp_T0.7', 'baseline_vs_temp'), ('baseline_T1.0', 'symp_prompt_T0.7', 'baseline_vs_symp'), ('temp_T0.7', 'symp_prompt_T0.7', 'temp_vs_symp') ] individual_results = [] for baseline_key, treatment_key, comparison_name in comparisons: if baseline_key in results and treatment_key in results: baseline_data = results[baseline_key] treatment_data = results[treatment_key] if len(baseline_data) > 0 and len(treatment_data) > 0: # 個別統計分析 comparison_result = self.statistical_analyzer.comprehensive_analysis( baseline=baseline_data, treatment=treatment_data, baseline_name=baseline_key, treatment_name=treatment_key ) # 比較名を追加 comparison_result['comparison_name'] = comparison_name individual_results.append(comparison_result) logger.info(f"📊 Completed analysis: {comparison_name}") # 多重比較補正 multiple_comparison_result = {} if len(individual_results) > 1: multiple_comparison_result = self.statistical_analyzer.multiple_comparisons_analysis( individual_results, correction_method='fdr_bh' ) logger.info("🔧 Multiple comparison correction applied") # 結果を統合形式に変換 consolidated_results = {} for result in individual_results: comp_name = result['comparison_name'] # 主要統計を抽出 main_test = result.get('statistical_tests', {}).get('main_test', {}) effect_sizes = result.get('effect_sizes', {}).get('cohens_d', {}) confidence_intervals = result.get('confidence_intervals', {}) interpretation = result.get('interpretation', {}) consolidated_results[comp_name] = { 'baseline_name': result['baseline_name'], 'treatment_name': result['treatment_name'], 'baseline_mean': result.get('descriptive_statistics', {}).get('baseline_mean', 0), 'treatment_mean': result.get('descriptive_statistics', {}).get('treatment_mean', 0), 'mean_difference': result.get('descriptive_statistics', {}).get('mean_difference', 0), 'test_used': main_test.get('test_name', 'Unknown'), 'statistic': main_test.get('statistic', 0), 'p_value': main_test.get('p_value', 1.0), 'significant': main_test.get('significant', False), 'cohens_d': effect_sizes.get('cohens_d', 0), 'ci_lower': effect_sizes.get('ci_lower', 0), 'ci_upper': effect_sizes.get('ci_upper', 0), 'interpretation': effect_sizes.get('interpretation', 'unknown'), 'power_analysis': result.get('power_analysis', {}), 'recommendations': result.get('recommendations', []) } return { 'individual_comparisons': consolidated_results, 'multiple_comparison': multiple_comparison_result, 'summary': { 'total_comparisons': len(individual_results), 'significant_comparisons': sum(1 for r in individual_results if r.get('statistical_tests', {}) .get('main_test', {}) .get('significant', False)), 'average_effect_size': np.mean([r.get('effect_sizes', {}) .get('cohens_d', {}) .get('cohens_d', 0) for r in individual_results]) if individual_results else 0, 'analysis_timestamp': datetime.now().isoformat() } } def get_experiment_status(self) -> Dict[str, Any]: """実験状態取得""" return { 'current_progress': self.current_progress, 'total_progress': self.total_progress, 'progress_percentage': (self.current_progress / self.total_progress * 100) if self.total_progress > 0 else 0, 'api_calls_made': self.api_optimizer.call_count, 'api_errors': self.api_optimizer.error_count, 'config': asdict(self.config), 'results_available': len(self.results_manager.raw_data) > 0 } def export_results(self, filepath: str = None) -> str: """結果エクスポート""" if not filepath: timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') filepath = f"symplectic_experiment_results_{timestamp}.json" export_data = { 'experiment_metadata': { 'export_timestamp': datetime.now().isoformat(), 'experiment_config': asdict(self.config), 'api_statistics': { 'total_calls': self.api_optimizer.call_count, 'total_errors': self.api_optimizer.error_count, 'success_rate': (self.api_optimizer.call_count - self.api_optimizer.error_count) / max(self.api_optimizer.call_count, 1) } }, 'raw_data': self.results_manager.raw_data, 'summary_statistics': self.results_manager.calculate_summary_statistics() } with open(filepath, 'w', encoding='utf-8') as f: json.dump(export_data, f, indent=2, ensure_ascii=False) logger.info(f"📁 Results exported to: {filepath}") return filepath # ユーティリティ関数群 def create_quick_experiment(api_key: str, sample_size: int = 100, n_trials: int = 5) -> EnhancedExperiment: """クイック実験作成""" return EnhancedExperiment( api_key=api_key, sample_size=sample_size, n_trials=n_trials ) def load_experiment_results(filepath: str) -> Dict[str, Any]: """実験結果読み込み""" with open(filepath, 'r', encoding='utf-8') as f: return json.load(f) def compare_experiment_results(results1: Dict[str, Any], results2: Dict[str, Any]) -> Dict[str, Any]: """実験結果比較""" comparison = { 'experiment1_config': results1.get('experiment_config', {}), 'experiment2_config': results2.get('experiment_config', {}), 'performance_comparison': {}, 'statistical_comparison': {} } # パフォーマンス比較 meta1 = results1.get('metadata', {}) meta2 = results2.get('metadata', {}) comparison['performance_comparison'] = { 'execution_time_ratio': meta2.get('execution_time_seconds', 0) / max(meta1.get('execution_time_seconds', 1), 1), 'api_calls_ratio': meta2.get('api_calls_made', 0) / max(meta1.get('api_calls_made', 1), 1), 'error_rate_diff': (meta2.get('api_errors', 0) / max(meta2.get('api_calls_made', 1), 1)) - (meta1.get('api_errors', 0) / max(meta1.get('api_calls_made', 1), 1)) } # 統計結果比較 stats1 = results1.get('statistical_analysis', {}).get('individual_comparisons', {}) stats2 = results2.get('statistical_analysis', {}).get('individual_comparisons', {}) for comp_name in set(stats1.keys()).intersection(stats2.keys()): comparison['statistical_comparison'][comp_name] = { 'effect_size_diff': stats2[comp_name].get('cohens_d', 0) - stats1[comp_name].get('cohens_d', 0), 'p_value_ratio': stats2[comp_name].get('p_value', 1) / max(stats1[comp_name].get('p_value', 1), 1e-10), 'both_significant': stats1[comp_name].get('significant', False) and stats2[comp_name].get('significant', False) } return comparison def validate_experiment_setup(config: ExperimentConfig) -> List[str]: """実験設定検証""" warnings = [] # サンプルサイズ検証 if config.sample_size < 100: warnings.append("⚠️ サンプルサイズが100未満です。統計的検出力が不足する可能性があります") if config.sample_size > 2000: warnings.append("⚠️ サンプルサイズが大きすぎます。実行時間とコストが大幅に増加します") # 試行回数検証 if config.n_trials < 10: warnings.append("⚠️ 試行回数が10未満です。結果の信頼性が低下する可能性があります") if config.n_trials > 50: warnings.append("⚠️ 試行回数が多すぎます。実行時間が大幅に増加します") # 温度設定検証 if config.temperature_baseline == config.temperature_control: warnings.append("⚠️ ベースラインと制御条件の温度が同じです。条件間の違いが検出できません") # 並列処理設定検証 if config.max_concurrent_requests > 20: warnings.append("⚠️ 並列処理数が多すぎます。API制限に抵触する可能性があります") return warnings # エクスポート用 __all__ = [ 'EnhancedExperiment', 'ExperimentConfig', 'APIOptimizer', 'ResultsManager', 'create_quick_experiment', 'load_experiment_results', 'compare_experiment_results', 'validate_experiment_setup' ] # テスト用関数 def run_test_experiment(api_key: str = None): """テスト実験実行""" if not api_key: logger.warning("🚫 API key not provided. Cannot run test experiment.") return None logger.info("🧪 Running test experiment...") # 小規模テスト設定 test_experiment = EnhancedExperiment( api_key=api_key, sample_size=50, # 小規模 n_trials=3 # 高速テスト ) # 設定検証 warnings = validate_experiment_setup(test_experiment.config) for warning in warnings: logger.warning(warning) try: # テスト実行 results = test_experiment.run_full_experiment() logger.info("✅ Test experiment completed successfully") logger.info(f"📊 Results summary: {len(results.get('raw_results', {}))} conditions tested") return results except Exception as e: logger.error(f"❌ Test experiment failed: {e}") return None if __name__ == "__main__": # モジュールテスト print("🔬 Enhanced Analysis Engine Test") # 設定テスト config = ExperimentConfig.from_defaults(sample_size=100, n_trials=5) print(f"📋 Test config: {config}") # 検証テスト warnings = validate_experiment_setup(config) print(f"⚠️ Validation warnings: {len(warnings)}") for warning in warnings: print(f" {warning}") print("✅ Module test completed")