| try: | |
| import matplotlib.pyplot as plt | |
| import seaborn as sns | |
| import networkx as nx | |
| except ImportError: | |
| plt = None | |
| sns = None | |
| nx = None | |
| import numpy as np | |
| from typing import List, Dict, Any, Optional, Tuple, Union | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| import json | |
| try: | |
| from .core.base_classes import VisualizationComponent | |
| from .evaluation import EvaluationResult | |
| except ImportError: | |
| from core.base_classes import VisualizationComponent | |
| from evaluation import EvaluationResult | |
| class PerformanceVisualizer(VisualizationComponent): | |
| def __init__(self, name: str = "PerformanceVisualizer"): | |
| super().__init__(name) | |
| self.output_format = "png" | |
| self.resolution = (1200, 800) | |
| plt.style.use("seaborn-v0_8") | |
| sns.set_palette("husl") | |
| def visualize(self, data: Any, **kwargs) -> str: | |
| if isinstance(data, dict) and "comparison_results" in data: | |
| return self._visualize_system_comparison(data) | |
| elif isinstance(data, list) and all( | |
| isinstance(item, EvaluationResult) for item in data | |
| ): | |
| return self._visualize_evaluation_results(data) | |
| else: | |
| return self._visualize_general_performance(data) | |
| def _visualize_system_comparison(self, comparison_data: Dict) -> str: | |
| fig, axes = plt.subplots(2, 2, figsize=(15, 12)) | |
| systems = [ | |
| result["system_name"] for result in comparison_data["system_results"] | |
| ] | |
| success_rates = [ | |
| result["aggregate_metrics"]["success_rate"] | |
| for result in comparison_data["system_results"] | |
| ] | |
| avg_qualities = [ | |
| result["aggregate_metrics"]["average_quality"] | |
| for result in comparison_data["system_results"] | |
| ] | |
| avg_computes = [ | |
| result["aggregate_metrics"]["average_compute"] | |
| for result in comparison_data["system_results"] | |
| ] | |
| efficiencies = [ | |
| result["aggregate_metrics"]["quality_per_compute"] | |
| for result in comparison_data["system_results"] | |
| ] | |
| axes[0, 0].bar( | |
| systems, | |
| success_rates, | |
| color=["blue", "green", "red", "orange"][: len(systems)], | |
| ) | |
| axes[0, 0].set_title("Success Rate Comparison", fontweight="bold", fontsize=14) | |
| axes[0, 0].set_ylabel("Success Rate") | |
| axes[0, 0].set_ylim(0, 1) | |
| axes[0, 0].tick_params(axis="x", rotation=45) | |
| for i, v in enumerate(success_rates): | |
| axes[0, 0].text(i, v + 0.01, f"{v:.2f}", ha="center", va="bottom") | |
| colors = ["blue", "green", "red", "orange"][: len(systems)] | |
| scatter = axes[0, 1].scatter( | |
| avg_computes, avg_qualities, s=100, c=colors, alpha=0.7 | |
| ) | |
| for i, name in enumerate(systems): | |
| axes[0, 1].annotate( | |
| name, | |
| (avg_computes[i], avg_qualities[i]), | |
| xytext=(5, 5), | |
| textcoords="offset points", | |
| fontsize=10, | |
| ) | |
| axes[0, 1].set_xlabel("Average Computational Cost") | |
| axes[0, 1].set_ylabel("Average Solution Quality") | |
| axes[0, 1].set_title( | |
| "Quality vs Computational Cost", fontweight="bold", fontsize=14 | |
| ) | |
| axes[0, 1].grid(True, alpha=0.3) | |
| axes[1, 0].bar(systems, efficiencies, color=colors, alpha=0.7) | |
| axes[1, 0].set_title("Computational Efficiency", fontweight="bold", fontsize=14) | |
| axes[1, 0].set_ylabel("Quality per Compute") | |
| axes[1, 0].tick_params(axis="x", rotation=45) | |
| for i, v in enumerate(efficiencies): | |
| axes[1, 0].text(i, v + 0.001, f"{v:.3f}", ha="center", va="bottom") | |
| metrics = ["Success Rate", "Quality", "Efficiency", "Speed"] | |
| angles = np.linspace(0, 2 * np.pi, len(metrics), endpoint=False).tolist() | |
| angles += angles[:1] | |
| for i, system in enumerate(systems): | |
| values = [ | |
| success_rates[i], | |
| avg_qualities[i], | |
| efficiencies[i] * 10, | |
| 1.0 | |
| - (avg_computes[i] / max(avg_computes)), | |
| ] | |
| values += values[:1] | |
| axes[1, 1].plot( | |
| angles, values, "o-", linewidth=2, label=system, color=colors[i] | |
| ) | |
| axes[1, 1].fill(angles, values, alpha=0.1, color=colors[i]) | |
| axes[1, 1].set_xticks(angles[:-1]) | |
| axes[1, 1].set_xticklabels(metrics) | |
| axes[1, 1].set_title( | |
| "Overall Performance Comparison", fontweight="bold", fontsize=14 | |
| ) | |
| axes[1, 1].legend(loc="upper right", bbox_to_anchor=(1.3, 1.0)) | |
| axes[1, 1].grid(True) | |
| plt.tight_layout() | |
| output_path = self._save_plot(fig, "system_comparison") | |
| return output_path | |
| def _visualize_evaluation_results(self, results: List[EvaluationResult]) -> str: | |
| fig, axes = plt.subplots(2, 2, figsize=(15, 10)) | |
| problem_names = [result.problem_name for result in results] | |
| qualities = [result.solution_quality for result in results] | |
| compute_costs = [result.computational_cost for result in results] | |
| execution_times = [result.execution_time for result in results] | |
| depths = [ | |
| result.reasoning_metrics.get("reasoning_depth", 0) for result in results | |
| ] | |
| axes[0, 0].bar(range(len(problem_names)), qualities, color="skyblue", alpha=0.7) | |
| axes[0, 0].set_title("Solution Quality by Problem", fontweight="bold") | |
| axes[0, 0].set_ylabel("Quality Score") | |
| axes[0, 0].set_xticks(range(len(problem_names))) | |
| axes[0, 0].set_xticklabels([f"P{i+1}" for i in range(len(problem_names))]) | |
| for i, v in enumerate(qualities): | |
| axes[0, 0].text(i, v + 0.01, f"{v:.2f}", ha="center", va="bottom") | |
| axes[0, 1].scatter(compute_costs, qualities, s=100, c="green", alpha=0.7) | |
| for i, name in enumerate(problem_names): | |
| axes[0, 1].annotate( | |
| f"P{i+1}", | |
| (compute_costs[i], qualities[i]), | |
| xytext=(5, 5), | |
| textcoords="offset points", | |
| ) | |
| axes[0, 1].set_xlabel("Computational Cost") | |
| axes[0, 1].set_ylabel("Solution Quality") | |
| axes[0, 1].set_title("Cost vs Quality Trade-off", fontweight="bold") | |
| axes[0, 1].grid(True, alpha=0.3) | |
| axes[1, 0].hist( | |
| execution_times, bins=5, color="orange", alpha=0.7, edgecolor="black" | |
| ) | |
| axes[1, 0].set_title("Execution Time Distribution", fontweight="bold") | |
| axes[1, 0].set_xlabel("Execution Time (seconds)") | |
| axes[1, 0].set_ylabel("Frequency") | |
| axes[1, 1].scatter(depths, qualities, s=100, c="red", alpha=0.7) | |
| for i, name in enumerate(problem_names): | |
| axes[1, 1].annotate( | |
| f"P{i+1}", | |
| (depths[i], qualities[i]), | |
| xytext=(5, 5), | |
| textcoords="offset points", | |
| ) | |
| axes[1, 1].set_xlabel("Reasoning Depth") | |
| axes[1, 1].set_ylabel("Solution Quality") | |
| axes[1, 1].set_title("Reasoning Depth vs Quality", fontweight="bold") | |
| axes[1, 1].grid(True, alpha=0.3) | |
| plt.tight_layout() | |
| output_path = self._save_plot(fig, "evaluation_results") | |
| return output_path | |
| def _visualize_general_performance(self, data: Any) -> str: | |
| fig, ax = plt.subplots(figsize=(10, 6)) | |
| if isinstance(data, dict): | |
| metrics = list(data.keys()) | |
| values = list(data.values()) | |
| ax.bar(metrics, values, color="lightcoral", alpha=0.7) | |
| ax.set_title("Performance Metrics Summary", fontweight="bold") | |
| ax.set_ylabel("Score") | |
| for i, v in enumerate(values): | |
| ax.text(i, v + 0.01, f"{v:.2f}", ha="center", va="bottom") | |
| plt.tight_layout() | |
| output_path = self._save_plot(fig, "performance_summary") | |
| return output_path | |
| def _save_plot(self, fig, filename_prefix: str) -> str: | |
| output_dir = Path("visualizations") | |
| output_dir.mkdir(exist_ok=True) | |
| timestamp = plt.datetime.datetime.now().strftime("%Y%m%d_%H%M%S") | |
| filename = f"{filename_prefix}_{timestamp}.{self.output_format}" | |
| filepath = output_dir / filename | |
| fig.savefig(filepath, dpi=300, bbox_inches="tight") | |
| plt.close(fig) | |
| return str(filepath) | |
| class ReasoningTreeVisualizer(VisualizationComponent): | |
| def __init__(self, name: str = "ReasoningTreeVisualizer"): | |
| super().__init__(name) | |
| self.output_format = "png" | |
| self.resolution = (1600, 1200) | |
| def visualize(self, data: Any, **kwargs) -> str: | |
| if hasattr(data, "best_solution") and data.best_solution: | |
| return self._visualize_search_tree(data) | |
| elif isinstance(data, dict) and "hierarchical_decomposition" in data: | |
| return self._visualize_hierarchical_tree(data) | |
| else: | |
| return self._visualize_general_tree(data) | |
| def _visualize_search_tree(self, search_result) -> str: | |
| fig, ax = plt.subplots(figsize=(16, 12)) | |
| G = nx.DiGraph() | |
| self._build_tree_graph(G, search_result.all_states) | |
| pos = nx.spring_layout(G, k=3, iterations=50) | |
| node_colors = [] | |
| node_sizes = [] | |
| for node in G.nodes(): | |
| state = G.nodes[node]["state"] | |
| if state == search_result.best_solution: | |
| node_colors.append("gold") | |
| node_sizes.append(800) | |
| elif state.is_terminal: | |
| node_colors.append("lightgreen") | |
| node_sizes.append(400) | |
| else: | |
| node_colors.append("lightblue") | |
| node_sizes.append(200) | |
| nx.draw_networkx_nodes( | |
| G, pos, node_color=node_colors, node_size=node_sizes, alpha=0.8 | |
| ) | |
| nx.draw_networkx_edges( | |
| G, pos, edge_color="gray", arrows=True, arrowsize=20, alpha=0.6 | |
| ) | |
| labels = { | |
| node: f"d{state.depth}\nv{state.value:.2f}" | |
| for node, state in G.nodes(data="state") | |
| } | |
| nx.draw_networkx_labels(G, pos, labels, font_size=8) | |
| ax.set_title("Reasoning Tree Visualization", fontweight="bold", fontsize=16) | |
| ax.axis("off") | |
| legend_elements = [ | |
| plt.scatter([], [], c="gold", s=100, label="Best Solution"), | |
| plt.scatter([], [], c="lightgreen", s=100, label="Terminal States"), | |
| plt.scatter([], [], c="lightblue", s=100, label="Intermediate States"), | |
| ] | |
| ax.legend(handles=legend_elements, loc="upper right") | |
| plt.tight_layout() | |
| output_path = self._save_plot(fig, "reasoning_tree") | |
| return output_path | |
| def _build_tree_graph(self, G, states): | |
| for state in states: | |
| G.add_node(state.state_id, state=state) | |
| for child in state.children: | |
| G.add_edge(state.state_id, child.state_id) | |
| def _visualize_hierarchical_tree(self, hierarchical_data) -> str: | |
| fig, ax = plt.subplots(figsize=(14, 10)) | |
| levels = hierarchical_data["hierarchical_decomposition"] | |
| y_positions = {} | |
| x_positions = {} | |
| for level_id, level_data in levels.items(): | |
| y_positions[level_id] = -level_id * 2 | |
| x_positions[level_id] = 0 | |
| for level_id, level_data in levels.items(): | |
| y = y_positions[level_id] | |
| x = x_positions[level_id] | |
| rect = plt.Rectangle( | |
| (x - 0.8, y - 0.3), | |
| 1.6, | |
| 0.6, | |
| facecolor="lightblue", | |
| edgecolor="black", | |
| alpha=0.7, | |
| ) | |
| ax.add_patch(rect) | |
| ax.text( | |
| x, | |
| y, | |
| f"{level_data.name}\n(Level {level_id})", | |
| ha="center", | |
| va="center", | |
| fontweight="bold", | |
| fontsize=10, | |
| ) | |
| status_color = "green" if level_data.status == "completed" else "red" | |
| circle = plt.Circle((x + 0.6, y + 0.2), 0.1, color=status_color) | |
| ax.add_patch(circle) | |
| for level_id, level_data in levels.items(): | |
| for dep_id in level_data.dependencies: | |
| if dep_id in levels: | |
| ax.annotate( | |
| "", | |
| xy=(x_positions[level_id], y_positions[level_id] - 0.3), | |
| xytext=(x_positions[dep_id], y_positions[dep_id] + 0.3), | |
| arrowprops=dict(arrowstyle="->", lw=2, color="gray"), | |
| ) | |
| ax.set_xlim(-2, 2) | |
| ax.set_ylim(-6, 1) | |
| ax.set_title("Hierarchical Reasoning Structure", fontweight="bold", fontsize=16) | |
| ax.axis("off") | |
| legend_elements = [ | |
| plt.Rectangle( | |
| (0, 0), 1, 1, facecolor="lightblue", alpha=0.7, label="Reasoning Level" | |
| ), | |
| plt.Circle((0, 0), 0.1, color="green", label="Completed"), | |
| plt.Circle((0, 0), 0.1, color="red", label="Failed"), | |
| ] | |
| ax.legend(handles=legend_elements, loc="upper right") | |
| plt.tight_layout() | |
| output_path = self._save_plot(fig, "hierarchical_tree") | |
| return output_path | |
| def _visualize_general_tree(self, data: Any) -> str: | |
| fig, ax = plt.subplots(figsize=(12, 8)) | |
| ax.text( | |
| 0.5, | |
| 0.9, | |
| "Reasoning Tree", | |
| ha="center", | |
| va="center", | |
| fontweight="bold", | |
| fontsize=16, | |
| transform=ax.transAxes, | |
| ) | |
| ax.text( | |
| 0.5, | |
| 0.5, | |
| "Tree visualization not available\nfor this data type", | |
| ha="center", | |
| va="center", | |
| fontsize=12, | |
| transform=ax.transAxes, | |
| ) | |
| ax.set_xlim(0, 1) | |
| ax.set_ylim(0, 1) | |
| ax.axis("off") | |
| plt.tight_layout() | |
| output_path = self._save_plot(fig, "general_tree") | |
| return output_path | |
| def _save_plot(self, fig, filename_prefix: str) -> str: | |
| output_dir = Path("visualizations") | |
| output_dir.mkdir(exist_ok=True) | |
| timestamp = plt.datetime.datetime.now().strftime("%Y%m%d_%H%M%S") | |
| filename = f"{filename_prefix}_{timestamp}.{self.output_format}" | |
| filepath = output_dir / filename | |
| fig.savefig(filepath, dpi=300, bbox_inches="tight") | |
| plt.close(fig) | |
| return str(filepath) | |
| class ScalingAnalysisVisualizer(VisualizationComponent): | |
| def __init__(self, name: str = "ScalingAnalysisVisualizer"): | |
| super().__init__(name) | |
| self.output_format = "png" | |
| self.resolution = (1400, 1000) | |
| def visualize(self, data: Any, **kwargs) -> str: | |
| if isinstance(data, dict) and "scaling_results" in data: | |
| return self._visualize_scaling_comparison(data) | |
| else: | |
| return self._visualize_general_scaling(data) | |
| def _visualize_scaling_comparison(self, scaling_data: Dict) -> str: | |
| fig, axes = plt.subplots(2, 2, figsize=(16, 12)) | |
| strategies = list(scaling_data["scaling_results"].keys()) | |
| colors = ["blue", "green", "red", "orange", "purple"][: len(strategies)] | |
| qualities = [] | |
| compute_costs = [] | |
| execution_times = [] | |
| success_rates = [] | |
| for strategy in strategies: | |
| result = scaling_data["scaling_results"][strategy] | |
| qualities.append(result.get("best_quality", result.get("final_quality", 0))) | |
| compute_costs.append(result.get("compute_used", 0)) | |
| execution_times.append(result.get("execution_time", 0)) | |
| success_rates.append( | |
| 1.0 | |
| if result.get("best_solution") or result.get("final_solution") | |
| else 0.0 | |
| ) | |
| bars1 = axes[0, 0].bar(strategies, qualities, color=colors, alpha=0.7) | |
| axes[0, 0].set_title("Solution Quality by Strategy", fontweight="bold") | |
| axes[0, 0].set_ylabel("Quality Score") | |
| axes[0, 0].tick_params(axis="x", rotation=45) | |
| for bar, value in zip(bars1, qualities): | |
| axes[0, 0].text( | |
| bar.get_x() + bar.get_width() / 2, | |
| bar.get_height() + 0.01, | |
| f"{value:.2f}", | |
| ha="center", | |
| va="bottom", | |
| ) | |
| axes[0, 1].scatter(compute_costs, qualities, s=150, c=colors, alpha=0.7) | |
| for i, strategy in enumerate(strategies): | |
| axes[0, 1].annotate( | |
| strategy, | |
| (compute_costs[i], qualities[i]), | |
| xytext=(5, 5), | |
| textcoords="offset points", | |
| ) | |
| axes[0, 1].set_xlabel("Computational Cost") | |
| axes[0, 1].set_ylabel("Solution Quality") | |
| axes[0, 1].set_title("Cost-Quality Trade-off", fontweight="bold") | |
| axes[0, 1].grid(True, alpha=0.3) | |
| bars3 = axes[1, 0].bar(strategies, execution_times, color=colors, alpha=0.7) | |
| axes[1, 0].set_title("Execution Time by Strategy", fontweight="bold") | |
| axes[1, 0].set_ylabel("Time (seconds)") | |
| axes[1, 0].tick_params(axis="x", rotation=45) | |
| for bar, value in zip(bars3, execution_times): | |
| axes[1, 0].text( | |
| bar.get_x() + bar.get_width() / 2, | |
| bar.get_height() + 0.01, | |
| f"{value:.2f}", | |
| ha="center", | |
| va="bottom", | |
| ) | |
| efficiencies = [q / c if c > 0 else 0 for q, c in zip(qualities, compute_costs)] | |
| bars4 = axes[1, 1].bar(strategies, efficiencies, color=colors, alpha=0.7) | |
| axes[1, 1].set_title("Computational Efficiency", fontweight="bold") | |
| axes[1, 1].set_ylabel("Quality per Compute") | |
| axes[1, 1].tick_params(axis="x", rotation=45) | |
| for bar, value in zip(bars4, efficiencies): | |
| axes[1, 1].text( | |
| bar.get_x() + bar.get_width() / 2, | |
| bar.get_height() + 0.001, | |
| f"{value:.3f}", | |
| ha="center", | |
| va="bottom", | |
| ) | |
| plt.tight_layout() | |
| output_path = self._save_plot(fig, "scaling_analysis") | |
| return output_path | |
| def _visualize_general_scaling(self, data: Any) -> str: | |
| fig, ax = plt.subplots(figsize=(10, 6)) | |
| ax.text( | |
| 0.5, | |
| 0.5, | |
| "Scaling Analysis Visualization", | |
| ha="center", | |
| va="center", | |
| fontweight="bold", | |
| fontsize=16, | |
| transform=ax.transAxes, | |
| ) | |
| ax.set_xlim(0, 1) | |
| ax.set_ylim(0, 1) | |
| ax.axis("off") | |
| plt.tight_layout() | |
| output_path = self._save_plot(fig, "general_scaling") | |
| return output_path | |
| def _save_plot(self, fig, filename_prefix: str) -> str: | |
| output_dir = Path("visualizations") | |
| output_dir.mkdir(exist_ok=True) | |
| timestamp = plt.datetime.datetime.now().strftime("%Y%m%d_%H%M%S") | |
| filename = f"{filename_prefix}_{timestamp}.{self.output_format}" | |
| filepath = output_dir / filename | |
| fig.savefig(filepath, dpi=300, bbox_inches="tight") | |
| plt.close(fig) | |
| return str(filepath) | |
| class ComprehensiveVisualizer: | |
| def __init__(self, output_dir: str = "visualizations"): | |
| self.output_dir = Path(output_dir) | |
| self.output_dir.mkdir(exist_ok=True) | |
| self.performance_visualizer = PerformanceVisualizer() | |
| self.tree_visualizer = ReasoningTreeVisualizer() | |
| self.scaling_visualizer = ScalingAnalysisVisualizer() | |
| def create_comprehensive_report(self, evaluation_data: Dict, **kwargs) -> List[str]: | |
| print("๐ Creating comprehensive visualization report...") | |
| generated_files = [] | |
| if "system_results" in evaluation_data: | |
| performance_file = self.performance_visualizer.visualize(evaluation_data) | |
| generated_files.append(performance_file) | |
| print(f" โ Performance comparison: {performance_file}") | |
| if "individual_results" in evaluation_data: | |
| for system_name, results in evaluation_data["individual_results"].items(): | |
| results_file = self.performance_visualizer.visualize(results) | |
| generated_files.append(results_file) | |
| print(f" โ {system_name} results: {results_file}") | |
| if "search_results" in evaluation_data: | |
| for system_name, search_result in evaluation_data["search_results"].items(): | |
| tree_file = self.tree_visualizer.visualize(search_result) | |
| generated_files.append(tree_file) | |
| print(f" โ {system_name} reasoning tree: {tree_file}") | |
| if "scaling_results" in evaluation_data: | |
| scaling_file = self.scaling_visualizer.visualize(evaluation_data) | |
| generated_files.append(scaling_file) | |
| print(f" โ Scaling analysis: {scaling_file}") | |
| summary_file = self._create_summary_report(evaluation_data, generated_files) | |
| generated_files.append(summary_file) | |
| print(f" โ Summary report: {summary_file}") | |
| return generated_files | |
| def _create_summary_report( | |
| self, evaluation_data: Dict, generated_files: List[str] | |
| ) -> str: | |
| html_content = f | |
| for file_path in generated_files: | |
| filename = Path(file_path).name | |
| html_content += f'<li><a href="{file_path}">{filename}</a></li>\n' | |
| html_content += | |
| if "comparison_results" in evaluation_data: | |
| comparison = evaluation_data["comparison_results"] | |
| if "overall_rankings" in comparison: | |
| html_content += "<h3>Overall System Rankings</h3>" | |
| for i, (system_name, score) in enumerate( | |
| comparison["overall_rankings"] | |
| ): | |
| html_content += ( | |
| f'<div class="metric">{i+1}. {system_name}: {score:.3f}</div>' | |
| ) | |
| html_content += ( | |
| + str(plt.datetime.datetime.now()) | |
| + | |
| + str(len(generated_files)) | |
| + | |
| ) | |
| timestamp = plt.datetime.datetime.now().strftime("%Y%m%d_%H%M%S") | |
| report_file = self.output_dir / f"evaluation_report_{timestamp}.html" | |
| with open(report_file, "w", encoding="utf-8") as f: | |
| f.write(html_content) | |
| return str(report_file) | |
Xet Storage Details
- Size:
- 22.6 kB
- Xet hash:
- 696121350e75e7dbcf3533c32b4270368b01de28d867bca49c67fddf11213272
ยท
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.