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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
"""
Progress Monitoring for Enhanced Symplectic LLM Experiment
進捗監視機能

Author: Kazuhiro Kojima
Version: 1.0.0
"""

import time
import psutil
import threading
import logging
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional, Callable
from dataclasses import dataclass, field
import json
from collections import deque
import numpy as np

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

@dataclass
class ProgressSnapshot:
    """進捗スナップショット"""
    timestamp: str
    current: int
    total: int
    stage: str
    details: str
    percentage: float
    elapsed_time: float
    estimated_remaining: float
    
@dataclass
class SystemMetrics:
    """システムメトリクス"""
    timestamp: str
    cpu_percent: float
    memory_percent: float
    memory_used_gb: float
    disk_usage_percent: float
    network_io: Dict[str, int] = field(default_factory=dict)
    gpu_info: Dict[str, Any] = field(default_factory=dict)

class ProgressMonitor:
    """進捗監視メインクラス"""
    
    def __init__(self, 
                 update_interval: float = 1.0,
                 history_size: int = 1000,
                 auto_log: bool = True):
        
        self.update_interval = update_interval
        self.history_size = history_size
        self.auto_log = auto_log
        
        # 状態管理
        self.current_progress = {
            'current': 0,
            'total': 100,
            'stage': '待機中',
            'details': '',
            'start_time': time.time()
        }
        
        # 履歴管理
        self.progress_history: deque = deque(maxlen=history_size)
        self.callbacks: List[Callable] = []
        
        # スレッド制御
        self._monitoring = False
        self._monitor_thread = None
        self._lock = threading.Lock()
        
        logger.info("📊 ProgressMonitor initialized")
    
    def start_monitoring(self):
        """監視開始"""
        if self._monitoring:
            logger.warning("⚠️ Monitoring already started")
            return
        
        self._monitoring = True
        self._monitor_thread = threading.Thread(target=self._monitor_loop, daemon=True)
        self._monitor_thread.start()
        
        logger.info("📊 Progress monitoring started")
    
    def stop_monitoring(self):
        """監視停止"""
        self._monitoring = False
        if self._monitor_thread:
            self._monitor_thread.join(timeout=5.0)
        
        logger.info("⏹️ Progress monitoring stopped")
    
    def update_progress(self, current: int, total: int, stage: str = "", details: str = ""):
        """進捗更新"""
        with self._lock:
            now = time.time()
            elapsed = now - self.current_progress['start_time']
            
            # 進捗計算
            percentage = (current / total * 100) if total > 0 else 0
            
            # 残り時間推定
            if current > 0 and percentage > 0:
                estimated_total_time = elapsed / (percentage / 100)
                estimated_remaining = max(0, estimated_total_time - elapsed)
            else:
                estimated_remaining = 0
            
            # 進捗更新
            self.current_progress.update({
                'current': current,
                'total': total,
                'stage': stage or self.current_progress['stage'],
                'details': details or self.current_progress['details'],
                'percentage': percentage,
                'elapsed_time': elapsed,
                'estimated_remaining': estimated_remaining
            })
            
            # スナップショット作成
            snapshot = ProgressSnapshot(
                timestamp=datetime.now().isoformat(),
                current=current,
                total=total,
                stage=stage or self.current_progress['stage'],
                details=details or self.current_progress['details'],
                percentage=percentage,
                elapsed_time=elapsed,
                estimated_remaining=estimated_remaining
            )
            
            self.progress_history.append(snapshot)
            
            # コールバック実行
            self._execute_callbacks(snapshot)
            
            # 自動ログ
            if self.auto_log:
                self._log_progress(snapshot)
    
    def reset_progress(self, stage: str = "開始"):
        """進捗リセット"""
        with self._lock:
            self.current_progress = {
                'current': 0,
                'total': 100,
                'stage': stage,
                'details': '',
                'start_time': time.time()
            }
        
        logger.info(f"🔄 Progress reset: {stage}")
    
    def add_callback(self, callback: Callable[[ProgressSnapshot], None]):
        """コールバック追加"""
        self.callbacks.append(callback)
        logger.info(f"📞 Callback added: {callback.__name__}")
    
    def get_current_status(self) -> Dict[str, Any]:
        """現在の状態取得"""
        with self._lock:
            return self.current_progress.copy()
    
    def get_progress_history(self, last_n: Optional[int] = None) -> List[ProgressSnapshot]:
        """進捗履歴取得"""
        history = list(self.progress_history)
        if last_n:
            return history[-last_n:]
        return history
    
    def get_progress_summary(self) -> Dict[str, Any]:
        """進捗サマリー取得"""
        with self._lock:
            current = self.current_progress
            
            # 速度計算
            recent_history = list(self.progress_history)[-10:]
            if len(recent_history) >= 2:
                time_diff = recent_history[-1].elapsed_time - recent_history[0].elapsed_time
                progress_diff = recent_history[-1].current - recent_history[0].current
                speed = progress_diff / max(time_diff, 1) if time_diff > 0 else 0
            else:
                speed = 0
            
            return {
                'current_stage': current['stage'],
                'progress_percentage': current.get('percentage', 0),
                'elapsed_time_formatted': self._format_time(current.get('elapsed_time', 0)),
                'estimated_remaining_formatted': self._format_time(current.get('estimated_remaining', 0)),
                'processing_speed': f"{speed:.2f} items/sec",
                'total_snapshots': len(self.progress_history)
            }
    
    def _monitor_loop(self):
        """監視ループ"""
        while self._monitoring:
            try:
                # システムメトリクス収集は省略(必要に応じて実装)
                time.sleep(self.update_interval)
                
            except Exception as e:
                logger.error(f"❌ Monitor loop error: {e}")
                time.sleep(self.update_interval)
    
    def _execute_callbacks(self, snapshot: ProgressSnapshot):
        """コールバック実行"""
        for callback in self.callbacks:
            try:
                callback(snapshot)
            except Exception as e:
                logger.error(f"❌ Callback error: {e}")
    
    def _log_progress(self, snapshot: ProgressSnapshot):
        """進捗ログ出力"""
        if snapshot.current % 10 == 0 or snapshot.percentage in [25, 50, 75, 100]:
            logger.info(
                f"📊 {snapshot.stage}: {snapshot.current}/{snapshot.total} "
                f"({snapshot.percentage:.1f}%) - "
                f"ETA: {self._format_time(snapshot.estimated_remaining)}"
            )
    
    def _format_time(self, seconds: float) -> str:
        """時間フォーマット"""
        if seconds < 60:
            return f"{seconds:.0f}秒"
        elif seconds < 3600:
            return f"{seconds/60:.1f}分"
        else:
            return f"{seconds/3600:.1f}時間"

class ExperimentTracker:
    """実験追跡専用クラス"""
    
    def __init__(self, experiment_name: str):
        self.experiment_name = experiment_name
        self.progress_monitor = ProgressMonitor()
        
        # 実験固有メトリクス
        self.experiment_metrics = {
            'api_calls_made': 0,
            'api_errors': 0,
            'samples_processed': 0,
            'conditions_completed': 0,
            'trials_completed': 0
        }
        
        self.phase_times = {}
        self.current_phase = None
        
        logger.info(f"🔬 ExperimentTracker initialized: {experiment_name}")
    
    def start_phase(self, phase_name: str):
        """フェーズ開始"""
        if self.current_phase:
            self.end_phase()
        
        self.current_phase = phase_name
        self.phase_times[phase_name] = {'start': time.time(), 'end': None}
        self.progress_monitor.reset_progress(phase_name)
        
        logger.info(f"🚀 Phase started: {phase_name}")
    
    def end_phase(self):
        """フェーズ終了"""
        if self.current_phase and self.current_phase in self.phase_times:
            self.phase_times[self.current_phase]['end'] = time.time()
            duration = self.phase_times[self.current_phase]['end'] - self.phase_times[self.current_phase]['start']
            
            logger.info(f"✅ Phase completed: {self.current_phase} ({duration:.1f}s)")
            self.current_phase = None
    
    def update_experiment_progress(self, **kwargs):
        """実験進捗更新"""
        # メトリクス更新
        for key, value in kwargs.items():
            if key in self.experiment_metrics:
                self.experiment_metrics[key] = value
        
        # 進捗監視更新
        if 'current' in kwargs and 'total' in kwargs:
            self.progress_monitor.update_progress(
                current=kwargs['current'],
                total=kwargs['total'],
                stage=kwargs.get('stage', self.current_phase or '実験中'),
                details=kwargs.get('details', '')
            )
    
    def increment_metric(self, metric_name: str, increment: int = 1):
        """メトリクス増分"""
        if metric_name in self.experiment_metrics:
            self.experiment_metrics[metric_name] += increment
    
    def get_experiment_summary(self) -> Dict[str, Any]:
        """実験サマリー取得"""
        total_time = sum(
            (times.get('end', time.time()) - times['start'])
            for times in self.phase_times.values()
        )
        
        return {
            'experiment_name': self.experiment_name,
            'total_experiment_time': total_time,
            'phase_durations': {
                phase: (times.get('end', time.time()) - times['start'])
                for phase, times in self.phase_times.items()
            },
            'metrics': self.experiment_metrics.copy(),
            'progress_summary': self.progress_monitor.get_progress_summary()
        }

class SystemResourceMonitor:
    """システムリソース監視クラス"""
    
    def __init__(self, monitoring_interval: float = 5.0):
        self.monitoring_interval = monitoring_interval
        self.metrics_history: deque = deque(maxlen=100)
        self._monitoring = False
        self._monitor_thread = None
        
        logger.info("🖥️ SystemResourceMonitor initialized")
    
    def start_monitoring(self):
        """リソース監視開始"""
        if self._monitoring:
            return
        
        self._monitoring = True
        self._monitor_thread = threading.Thread(target=self._monitor_resources, daemon=True)
        self._monitor_thread.start()
        
        logger.info("🖥️ Resource monitoring started")
    
    def stop_monitoring(self):
        """リソース監視停止"""
        self._monitoring = False
        if self._monitor_thread:
            self._monitor_thread.join(timeout=10.0)
        
        logger.info("⏹️ Resource monitoring stopped")
    
    def get_current_metrics(self) -> SystemMetrics:
        """現在のシステムメトリクス取得"""
        try:
            # CPU使用率
            cpu_percent = psutil.cpu_percent(interval=1)
            
            # メモリ使用状況
            memory = psutil.virtual_memory()
            memory_percent = memory.percent
            memory_used_gb = memory.used / (1024**3)
            
            # ディスク使用状況
            disk = psutil.disk_usage('/')
            disk_usage_percent = disk.percent
            
            # ネットワークI/O(オプション)
            network_io = {}
            try:
                net_io = psutil.net_io_counters()
                network_io = {
                    'bytes_sent': net_io.bytes_sent,
                    'bytes_recv': net_io.bytes_recv
                }
            except:
                pass
            
            return SystemMetrics(
                timestamp=datetime.now().isoformat(),
                cpu_percent=cpu_percent,
                memory_percent=memory_percent,
                memory_used_gb=memory_used_gb,
                disk_usage_percent=disk_usage_percent,
                network_io=network_io
            )
            
        except Exception as e:
            logger.error(f"❌ Failed to get system metrics: {e}")
            return SystemMetrics(
                timestamp=datetime.now().isoformat(),
                cpu_percent=0,
                memory_percent=0,
                memory_used_gb=0,
                disk_usage_percent=0
            )
    
    def _monitor_resources(self):
        """リソース監視ループ"""
        while self._monitoring:
            try:
                metrics = self.get_current_metrics()
                self.metrics_history.append(metrics)
                
                # 警告チェック
                self._check_resource_warnings(metrics)
                
                time.sleep(self.monitoring_interval)
                
            except Exception as e:
                logger.error(f"❌ Resource monitoring error: {e}")
                time.sleep(self.monitoring_interval)


    def _check_resource_warnings(self, metrics: SystemMetrics):
        """リソース警告チェック"""
        # CPU使用率警告
        if metrics.cpu_percent > 90:
            logger.warning(f"⚠️ High CPU usage: {metrics.cpu_percent:.1f}%")
        
        # メモリ使用率警告
        if metrics.memory_percent > 85:
            logger.warning(f"⚠️ High memory usage: {metrics.memory_percent:.1f}%")
        
        # ディスク使用率警告
        if metrics.disk_usage_percent > 90:
            logger.warning(f"⚠️ High disk usage: {metrics.disk_usage_percent:.1f}%")
    
    def get_resource_summary(self) -> Dict[str, Any]:
        """リソース使用状況サマリー"""
        if not self.metrics_history:
            return {'error': 'No metrics available'}
        
        recent_metrics = list(self.metrics_history)[-10:]  # 最新10件
        
        cpu_values = [m.cpu_percent for m in recent_metrics]
        memory_values = [m.memory_percent for m in recent_metrics]
        
        return {
            'current_cpu': recent_metrics[-1].cpu_percent,
            'average_cpu': np.mean(cpu_values),
            'max_cpu': np.max(cpu_values),
            'current_memory': recent_metrics[-1].memory_percent,
            'average_memory': np.mean(memory_values),
            'max_memory': np.max(memory_values),
            'current_memory_gb': recent_metrics[-1].memory_used_gb,
            'disk_usage': recent_metrics[-1].disk_usage_percent,
            'monitoring_duration': len(self.metrics_history) * self.monitoring_interval
        }

# ユーティリティ関数
def create_progress_callback(format_string: str = "📊 {stage}: {current}/{total} ({percentage:.1f}%)") -> Callable:
    """進捗コールバック作成"""
    def callback(snapshot: ProgressSnapshot):
        message = format_string.format(
            stage=snapshot.stage,
            current=snapshot.current,
            total=snapshot.total,
            percentage=snapshot.percentage,
            details=snapshot.details,
            elapsed=snapshot.elapsed_time,
            remaining=snapshot.estimated_remaining
        )
        print(message)
    
    return callback

def create_experiment_tracker(experiment_name: str, 
                            enable_resource_monitoring: bool = True) -> ExperimentTracker:
    """実験トラッカー作成"""
    tracker = ExperimentTracker(experiment_name)
    
    if enable_resource_monitoring:
        resource_monitor = SystemResourceMonitor()
        resource_monitor.start_monitoring()
        
        # リソース情報をトラッカーに統合
        tracker.resource_monitor = resource_monitor
    
    return tracker

def save_progress_report(tracker: ExperimentTracker, filepath: str = None) -> str:
    """進捗レポート保存"""
    if not filepath:
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        filepath = f"progress_report_{tracker.experiment_name}_{timestamp}.json"
    
    report = {
        'experiment_summary': tracker.get_experiment_summary(),
        'progress_history': [
            {
                'timestamp': snapshot.timestamp,
                'stage': snapshot.stage,
                'percentage': snapshot.percentage,
                'elapsed_time': snapshot.elapsed_time
            }
            for snapshot in tracker.progress_monitor.get_progress_history()
        ],
        'resource_summary': tracker.resource_monitor.get_resource_summary() if hasattr(tracker, 'resource_monitor') else {},
        'report_generated': datetime.now().isoformat()
    }
    
    with open(filepath, 'w', encoding='utf-8') as f:
        json.dump(report, f, indent=2, ensure_ascii=False)
    
    logger.info(f"📋 Progress report saved: {filepath}")
    return filepath

# エクスポート
__all__ = [
    'ProgressMonitor',
    'ExperimentTracker',
    'SystemResourceMonitor',
    'ProgressSnapshot',
    'SystemMetrics',
    'create_progress_callback',
    'create_experiment_tracker',
    'save_progress_report'
]

if __name__ == "__main__":
    # テスト実行
    print("📊 Progress monitoring test")
    
    # ProgressMonitor テスト
    monitor = ProgressMonitor()
    monitor.start_monitoring()
    
    # 進捗シミュレーション
    for i in range(0, 101, 10):
        monitor.update_progress(i, 100, "テスト実行", f"ステップ {i}")
        time.sleep(0.1)
    
    summary = monitor.get_progress_summary()
    print(f"✅ Progress summary: {summary}")
    
    monitor.stop_monitoring()
    
    # ExperimentTracker テスト
    tracker = ExperimentTracker("test_experiment")
    tracker.start_phase("データ準備")
    
    for i in range(5):
        tracker.update_experiment_progress(current=i, total=5, stage="データ準備")
        tracker.increment_metric('samples_processed')
        time.sleep(0.1)
    
    tracker.end_phase()
    
    exp_summary = tracker.get_experiment_summary()
    print(f"✅ Experiment summary: {exp_summary}")
    
    # SystemResourceMonitor テスト
    resource_monitor = SystemResourceMonitor()
    current_metrics = resource_monitor.get_current_metrics()
    print(f"✅ System metrics: CPU {current_metrics.cpu_percent}%, Memory {current_metrics.memory_percent}%")
    
    print("✅ Progress monitoring test completed")