File size: 10,648 Bytes
c3efd49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Visualization tools for training monitoring."""
import matplotlib.pyplot as plt
import numpy as np
from typing import Dict, List, Optional, Any
from pathlib import Path
import logging

logger = logging.getLogger(__name__)


class Visualizer:
    """
    Creates visualizations for training metrics.
    
    Supports TensorBoard integration and static plots.
    """
    
    def __init__(self, output_dir: str = "visualizations"):
        """
        Initialize visualizer.
        
        Args:
            output_dir: Directory to save visualizations
        """
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        
        # Try to import tensorboard
        self.tensorboard_available = False
        try:
            from torch.utils.tensorboard import SummaryWriter
            self.SummaryWriter = SummaryWriter
            self.tensorboard_available = True
            logger.info("TensorBoard available")
        except ImportError:
            logger.warning("TensorBoard not available")
        
        self.writer = None
        
        logger.info(f"Visualizer initialized: output_dir={output_dir}")
    
    def initialize_tensorboard(self, log_dir: Optional[str] = None) -> None:
        """
        Initialize TensorBoard writer.
        
        Args:
            log_dir: Optional TensorBoard log directory
        """
        if not self.tensorboard_available:
            logger.warning("TensorBoard not available, skipping initialization")
            return
        
        if log_dir is None:
            log_dir = str(self.output_dir / "tensorboard")
        
        self.writer = self.SummaryWriter(log_dir)
        logger.info(f"TensorBoard initialized: {log_dir}")
    
    def log_scalar_to_tensorboard(
        self,
        tag: str,
        value: float,
        step: int
    ) -> None:
        """
        Log scalar value to TensorBoard.
        
        Args:
            tag: Metric name
            value: Metric value
            step: Step number
        """
        if self.writer is not None:
            self.writer.add_scalar(tag, value, step)
    
    def plot_training_curve(
        self,
        metrics: Dict[str, List[Dict[str, Any]]],
        metric_name: str,
        title: Optional[str] = None,
        filename: Optional[str] = None
    ) -> str:
        """
        Plot training curve for a metric.
        
        Args:
            metrics: Dictionary of metrics
            metric_name: Name of metric to plot
            title: Optional plot title
            filename: Optional output filename
        
        Returns:
            Path to saved plot
        """
        if metric_name not in metrics:
            raise ValueError(f"Metric '{metric_name}' not found")
        
        data = metrics[metric_name]
        steps = [entry['step'] for entry in data]
        values = [entry['value'] for entry in data]
        
        plt.figure(figsize=(10, 6))
        plt.plot(steps, values, linewidth=2)
        plt.xlabel('Step')
        plt.ylabel(metric_name.replace('_', ' ').title())
        plt.title(title or f'{metric_name.replace("_", " ").title()} Over Time')
        plt.grid(True, alpha=0.3)
        
        if filename is None:
            filename = f"{metric_name}_curve.png"
        
        output_path = self.output_dir / filename
        plt.savefig(output_path, dpi=150, bbox_inches='tight')
        plt.close()
        
        logger.info(f"Training curve saved: {output_path}")
        return str(output_path)
    
    def plot_multiple_metrics(
        self,
        metrics: Dict[str, List[Dict[str, Any]]],
        metric_names: List[str],
        title: Optional[str] = None,
        filename: Optional[str] = None
    ) -> str:
        """
        Plot multiple metrics on the same figure.
        
        Args:
            metrics: Dictionary of metrics
            metric_names: List of metric names to plot
            title: Optional plot title
            filename: Optional output filename
        
        Returns:
            Path to saved plot
        """
        plt.figure(figsize=(12, 6))
        
        for metric_name in metric_names:
            if metric_name in metrics:
                data = metrics[metric_name]
                steps = [entry['step'] for entry in data]
                values = [entry['value'] for entry in data]
                plt.plot(steps, values, label=metric_name, linewidth=2)
        
        plt.xlabel('Step')
        plt.ylabel('Value')
        plt.title(title or 'Training Metrics')
        plt.legend()
        plt.grid(True, alpha=0.3)
        
        if filename is None:
            filename = "multiple_metrics.png"
        
        output_path = self.output_dir / filename
        plt.savefig(output_path, dpi=150, bbox_inches='tight')
        plt.close()
        
        logger.info(f"Multi-metric plot saved: {output_path}")
        return str(output_path)
    
    def plot_training_curves(
        self,
        metrics: Dict[str, List[Dict[str, Any]]],
        title: str = "Training Progress",
        filename: Optional[str] = None
    ) -> str:
        """
        Plot comprehensive training curves with subplots.

        Args:
            metrics: Dictionary of all metrics
            title: Main title for the figure
            filename: Optional output filename

        Returns:
            Path to saved plot
        """
        if not metrics:
            logger.warning("No metrics to plot")
            return ""

        # Determine which metrics to plot
        metric_names = list(metrics.keys())
        num_metrics = len(metric_names)

        if num_metrics == 0:
            return ""

        # Create subplots
        fig, axes = plt.subplots(2, 2, figsize=(15, 10))
        fig.suptitle(title, fontsize=16, fontweight='bold')
        axes = axes.flatten()

        # Plot up to 4 key metrics
        key_metrics = ['reward', 'loss', 'total_reward', 'episode_time']
        plot_idx = 0

        for metric_name in key_metrics:
            if metric_name in metrics and plot_idx < 4:
                data = metrics[metric_name]
                steps = [entry['step'] for entry in data]
                values = [entry['value'] for entry in data]

                ax = axes[plot_idx]
                ax.plot(steps, values, linewidth=2, marker='o', markersize=4)
                ax.set_xlabel('Episode')
                ax.set_ylabel(metric_name.replace('_', ' ').title())
                ax.set_title(f'{metric_name.replace("_", " ").title()}')
                ax.grid(True, alpha=0.3)

                # Add trend line
                if len(steps) > 1:
                    z = np.polyfit(steps, values, 1)
                    p = np.poly1d(z)
                    ax.plot(steps, p(steps), "--", alpha=0.5, color='red', label='Trend')
                    ax.legend()

                plot_idx += 1

        # Hide unused subplots
        for idx in range(plot_idx, 4):
            axes[idx].axis('off')

        plt.tight_layout()

        if filename is None:
            filename = f"training_curves_{len(steps)}_episodes.png"

        output_path = self.output_dir / filename
        plt.savefig(output_path, dpi=150, bbox_inches='tight')
        plt.close()

        logger.info(f"Training curves saved: {output_path}")
        return str(output_path)

    def plot_reward_distribution(
        self,
        rewards: List[float],
        title: Optional[str] = None,
        filename: Optional[str] = None
    ) -> str:
        """
        Plot reward distribution histogram.
        
        Args:
            rewards: List of reward values
            title: Optional plot title
            filename: Optional output filename
        
        Returns:
            Path to saved plot
        """
        plt.figure(figsize=(10, 6))
        plt.hist(rewards, bins=30, alpha=0.7, edgecolor='black')
        plt.xlabel('Reward')
        plt.ylabel('Frequency')
        plt.title(title or 'Reward Distribution')
        plt.grid(True, alpha=0.3, axis='y')
        
        # Add statistics
        mean_reward = np.mean(rewards)
        std_reward = np.std(rewards)
        plt.axvline(mean_reward, color='red', linestyle='--', 
                   label=f'Mean: {mean_reward:.3f}')
        plt.axvline(mean_reward + std_reward, color='orange', 
                   linestyle=':', alpha=0.7, label=f'±1 Std')
        plt.axvline(mean_reward - std_reward, color='orange', 
                   linestyle=':', alpha=0.7)
        plt.legend()
        
        if filename is None:
            filename = "reward_distribution.png"
        
        output_path = self.output_dir / filename
        plt.savefig(output_path, dpi=150, bbox_inches='tight')
        plt.close()
        
        logger.info(f"Reward distribution saved: {output_path}")
        return str(output_path)
    
    def generate_summary_report(
        self,
        metrics: Dict[str, List[Dict[str, Any]]],
        statistics: Dict[str, Dict[str, float]],
        output_filename: str = "training_summary.txt"
    ) -> str:
        """
        Generate text summary report.
        
        Args:
            metrics: Dictionary of metrics
            statistics: Dictionary of metric statistics
            output_filename: Output filename
        
        Returns:
            Path to saved report
        """
        lines = []
        lines.append("=" * 60)
        lines.append("TRAINING SUMMARY REPORT")
        lines.append("=" * 60)
        lines.append("")
        
        # Overall statistics
        lines.append("METRIC STATISTICS:")
        lines.append("-" * 60)
        
        for metric_name, stats in statistics.items():
            lines.append(f"\n{metric_name}:")
            lines.append(f"  Count:  {stats['count']}")
            lines.append(f"  Mean:   {stats['mean']:.6f}")
            lines.append(f"  Std:    {stats['std']:.6f}")
            lines.append(f"  Min:    {stats['min']:.6f}")
            lines.append(f"  Max:    {stats['max']:.6f}")
        
        lines.append("")
        lines.append("=" * 60)
        
        report_text = "\n".join(lines)
        
        output_path = self.output_dir / output_filename
        with open(output_path, 'w') as f:
            f.write(report_text)
        
        logger.info(f"Summary report saved: {output_path}")
        return str(output_path)
    
    def close(self) -> None:
        """Close TensorBoard writer if open."""
        if self.writer is not None:
            self.writer.close()
            logger.info("TensorBoard writer closed")