| from typing import List, Dict, Optional, Any, Union, Tuple | |
| import matplotlib.pyplot as plt | |
| import seaborn as sns | |
| import networkx as nx | |
| import numpy as np | |
| import pandas as pd | |
| from collections import defaultdict | |
| import json | |
| import pickle | |
| from datetime import datetime | |
| import os | |
| from ..core.reasoning_structures import ReasoningStep, ReasoningChain | |
| class CoTVisualizer: | |
| def __init__(self, style: str = "seaborn-v0_8"): | |
| plt.style.use(style) | |
| sns.set_palette("husl") | |
| self.colors = { | |
| "analysis": "#3498db", | |
| "computation": "#2ecc71", | |
| "verification": "#f39c12", | |
| "conclusion": "#e74c3c", | |
| "reflection": "#9b59b6", | |
| "premise": "#1abc9c", | |
| } | |
| def visualize_reasoning_chain( | |
| self, | |
| chain: ReasoningChain, | |
| title: str = "Reasoning Chain", | |
| save_path: Optional[str] = None, | |
| ) -> None: | |
| plt.figure(figsize=(12, 8)) | |
| G = nx.DiGraph() | |
| positions = {} | |
| for i, step in enumerate(chain.steps): | |
| G.add_node( | |
| step.step_id, | |
| content=( | |
| step.content[:50] + "..." | |
| if len(step.content) > 50 | |
| else step.content | |
| ), | |
| type=step.step_type, | |
| confidence=step.confidence, | |
| ) | |
| positions[step.step_id] = (i, 0) | |
| for step in chain.steps: | |
| for dep in step.dependencies: | |
| if dep in [s.step_id for s in chain.steps]: | |
| G.add_edge(dep, step.step_id) | |
| node_colors = [ | |
| self.colors.get(G.nodes[node]["type"], "#95a5a6") for node in G.nodes() | |
| ] | |
| node_sizes = [1000 * G.nodes[node]["confidence"] for node in G.nodes()] | |
| nx.draw( | |
| G, | |
| positions, | |
| node_color=node_colors, | |
| node_size=node_sizes, | |
| with_labels=True, | |
| font_size=8, | |
| font_weight="bold", | |
| edge_color="gray", | |
| arrows=True, | |
| arrowsize=20, | |
| ) | |
| plt.title(title) | |
| plt.tight_layout() | |
| if save_path: | |
| plt.savefig(save_path, dpi=300, bbox_inches="tight") | |
| print(f"Reasoning chain visualization saved to {save_path}") | |
| plt.show() | |
| def visualize_confidence_progression( | |
| self, chain: ReasoningChain, save_path: Optional[str] = None | |
| ) -> None: | |
| plt.figure(figsize=(12, 6)) | |
| steps = chain.get_step_order() | |
| step_numbers = list(range(1, len(steps) + 1)) | |
| confidences = [step.confidence for step in steps] | |
| step_types = [step.step_type for step in steps] | |
| plt.plot(step_numbers, confidences, "o-", linewidth=2, markersize=8) | |
| for i, (step_num, conf, step_type) in enumerate( | |
| zip(step_numbers, confidences, step_types) | |
| ): | |
| plt.scatter( | |
| step_num, conf, c=self.colors.get(step_type, "#95a5a6"), s=100, zorder=5 | |
| ) | |
| plt.xlabel("Step Number") | |
| plt.ylabel("Confidence Score") | |
| plt.title("Confidence Progression Through Reasoning Steps") | |
| plt.grid(True, alpha=0.3) | |
| plt.ylim(0, 1) | |
| legend_elements = [ | |
| plt.Line2D( | |
| [0], | |
| [0], | |
| marker="o", | |
| color="w", | |
| markerfacecolor=color, | |
| markersize=8, | |
| label=step_type, | |
| ) | |
| for step_type, color in self.colors.items() | |
| ] | |
| plt.legend(handles=legend_elements, loc="best") | |
| if save_path: | |
| plt.savefig(save_path, dpi=300, bbox_inches="tight") | |
| print(f"Confidence progression plot saved to {save_path}") | |
| plt.show() | |
| def visualize_step_type_distribution( | |
| self, chains: List[ReasoningChain], save_path: Optional[str] = None | |
| ) -> None: | |
| plt.figure(figsize=(10, 6)) | |
| step_type_counts = defaultdict(int) | |
| for chain in chains: | |
| for step in chain.steps: | |
| step_type_counts[step.step_type] += 1 | |
| labels = list(step_type_counts.keys()) | |
| sizes = list(step_type_counts.values()) | |
| colors = [self.colors.get(label, "#95a5a6") for label in labels] | |
| plt.pie(sizes, labels=labels, colors=colors, autopct="%1.1f%%", startangle=90) | |
| plt.title("Distribution of Reasoning Step Types") | |
| if save_path: | |
| plt.savefig(save_path, dpi=300, bbox_inches="tight") | |
| print(f"Step type distribution plot saved to {save_path}") | |
| plt.show() | |
| def visualize_chain_comparison( | |
| self, | |
| chains: List[ReasoningChain], | |
| chain_names: Optional[List[str]] = None, | |
| save_path: Optional[str] = None, | |
| ) -> None: | |
| if chain_names is None: | |
| chain_names = [f"Chain {i+1}" for i in range(len(chains))] | |
| fig, axes = plt.subplots(2, 2, figsize=(15, 10)) | |
| lengths = [len(chain.steps) for chain in chains] | |
| axes[0, 0].bar(chain_names, lengths, color="skyblue") | |
| axes[0, 0].set_title("Number of Reasoning Steps") | |
| axes[0, 0].set_ylabel("Steps") | |
| confidences = [chain.total_confidence for chain in chains] | |
| axes[0, 1].bar(chain_names, confidences, color="lightgreen") | |
| axes[0, 1].set_title("Total Confidence") | |
| axes[0, 1].set_ylabel("Confidence") | |
| avg_confidences = [ | |
| np.mean([step.confidence for step in chain.steps]) for chain in chains | |
| ] | |
| axes[1, 0].bar(chain_names, avg_confidences, color="lightcoral") | |
| axes[1, 0].set_title("Average Step Confidence") | |
| axes[1, 0].set_ylabel("Confidence") | |
| diversities = [ | |
| len(set(step.step_type for step in chain.steps)) for chain in chains | |
| ] | |
| axes[1, 1].bar(chain_names, diversities, color="gold") | |
| axes[1, 1].set_title("Step Type Diversity") | |
| axes[1, 1].set_ylabel("Number of Types") | |
| plt.tight_layout() | |
| if save_path: | |
| plt.savefig(save_path, dpi=300, bbox_inches="tight") | |
| print(f"Chain comparison plot saved to {save_path}") | |
| plt.show() | |
| class CoTDataset: | |
| def __init__(self, chains: Optional[List[ReasoningChain]] = None): | |
| self.chains = chains or [] | |
| self.metadata = {} | |
| def add_chain(self, chain: ReasoningChain) -> None: | |
| self.chains.append(chain) | |
| def filter_by_confidence(self, min_confidence: float) -> List[ReasoningChain]: | |
| return [ | |
| chain for chain in self.chains if chain.total_confidence >= min_confidence | |
| ] | |
| def filter_by_length( | |
| self, min_length: int, max_length: Optional[int] = None | |
| ) -> List[ReasoningChain]: | |
| filtered = [chain for chain in self.chains if len(chain.steps) >= min_length] | |
| if max_length is not None: | |
| filtered = [chain for chain in filtered if len(chain.steps) <= max_length] | |
| return filtered | |
| def filter_by_step_type(self, step_type: str) -> List[ReasoningChain]: | |
| return [ | |
| chain | |
| for chain in self.chains | |
| if any(step.step_type == step_type for step in chain.steps) | |
| ] | |
| def get_statistics(self) -> Dict[str, Any]: | |
| if not self.chains: | |
| return {} | |
| confidences = [chain.total_confidence for chain in self.chains] | |
| step_counts = [len(chain.steps) for chain in self.chains] | |
| step_type_counts = defaultdict(int) | |
| for chain in self.chains: | |
| for step in chain.steps: | |
| step_type_counts[step.step_type] += 1 | |
| problem_categories = defaultdict(int) | |
| for chain in self.chains: | |
| if "category" in chain.metadata: | |
| problem_categories[chain.metadata["category"]] += 1 | |
| return { | |
| "total_chains": len(self.chains), | |
| "avg_confidence": np.mean(confidences), | |
| "min_confidence": np.min(confidences), | |
| "max_confidence": np.max(confidences), | |
| "std_confidence": np.std(confidences), | |
| "avg_steps": np.mean(step_counts), | |
| "min_steps": np.min(step_counts), | |
| "max_steps": np.max(step_counts), | |
| "std_steps": np.std(step_counts), | |
| "step_type_distribution": dict(step_type_counts), | |
| "problem_categories": dict(problem_categories), | |
| } | |
| def export_to_json(self, filepath: str) -> None: | |
| data = { | |
| "chains": [chain.to_dict() for chain in self.chains], | |
| "metadata": self.metadata, | |
| "statistics": self.get_statistics(), | |
| "export_timestamp": datetime.now().isoformat(), | |
| } | |
| with open(filepath, "w", encoding="utf-8") as f: | |
| json.dump(data, f, indent=2, ensure_ascii=False) | |
| print(f"Dataset exported to {filepath}") | |
| def export_to_pickle(self, filepath: str) -> None: | |
| with open(filepath, "wb") as f: | |
| pickle.dump(self, f) | |
| print(f"Dataset exported to {filepath}") | |
| def load_from_json(cls, filepath: str) -> "CoTDataset": | |
| with open(filepath, "r", encoding="utf-8") as f: | |
| data = json.load(f) | |
| chains = [ | |
| ReasoningChain.from_dict(chain_data) | |
| for chain_data in data.get("chains", []) | |
| ] | |
| dataset = cls(chains) | |
| dataset.metadata = data.get("metadata", {}) | |
| return dataset | |
| def load_from_pickle(cls, filepath: str) -> "CoTDataset": | |
| with open(filepath, "rb") as f: | |
| return pickle.load(f) | |
| class CoTDataProcessor: | |
| def create_synthetic_chains( | |
| num_chains: int = 100, problem_types: List[str] = None | |
| ) -> List[ReasoningChain]: | |
| if problem_types is None: | |
| problem_types = ["arithmetic", "word_problem", "decision_making"] | |
| chains = [] | |
| for i in range(num_chains): | |
| problem_type = np.random.choice(problem_types) | |
| if problem_type == "arithmetic": | |
| chain = CoTDataProcessor._create_arithmetic_chain(i) | |
| elif problem_type == "word_problem": | |
| chain = CoTDataProcessor._create_word_problem_chain(i) | |
| elif problem_type == "decision_making": | |
| chain = CoTDataProcessor._create_decision_chain(i) | |
| else: | |
| chain = CoTDataProcessor._create_generic_chain(i) | |
| chains.append(chain) | |
| return chains | |
| def _create_arithmetic_chain(chain_id: int) -> ReasoningChain: | |
| a, b = np.random.randint(1, 100, 2) | |
| operation = np.random.choice(["+", "-", "*", "/"]) | |
| if operation == "+": | |
| problem = f"What is {a} + {b}?" | |
| answer = a + b | |
| elif operation == "-": | |
| problem = f"What is {a} - {b}?" | |
| answer = a - b | |
| elif operation == "*": | |
| problem = f"What is {a} × {b}?" | |
| answer = a * b | |
| else: | |
| problem = f"What is {a} ÷ {b}?" | |
| answer = a / b | |
| steps = [ | |
| ReasoningStep( | |
| step_id=f"step_1_{chain_id}", | |
| content=f"I need to perform {operation} with {a} and {b}", | |
| step_type="analysis", | |
| confidence=0.9, | |
| dependencies=[], | |
| ), | |
| ReasoningStep( | |
| step_id=f"step_2_{chain_id}", | |
| content=f"Applying the {operation} operation: {a} {operation} {b}", | |
| step_type="computation", | |
| confidence=0.95, | |
| dependencies=[f"step_1_{chain_id}"], | |
| ), | |
| ReasoningStep( | |
| step_id=f"step_3_{chain_id}", | |
| content=f"The result is {answer}", | |
| step_type="conclusion", | |
| confidence=0.98, | |
| dependencies=[f"step_1_{chain_id}", f"step_2_{chain_id}"], | |
| ), | |
| ] | |
| return ReasoningChain( | |
| problem=problem, | |
| steps=steps, | |
| solution=f"The answer is {answer}", | |
| total_confidence=0.0, | |
| metadata={"category": "arithmetic", "chain_id": chain_id}, | |
| ) | |
| def _create_word_problem_chain(chain_id: int) -> ReasoningChain: | |
| problems = [ | |
| "If a train travels 60 mph for 2.5 hours, how far does it go?", | |
| "Sarah has 15 apples and gives 7 to her friend. How many does she have left?", | |
| "A rectangle has length 12 and width 8. What is its area?", | |
| ] | |
| problem = np.random.choice(problems) | |
| steps = [ | |
| ReasoningStep( | |
| step_id=f"step_1_{chain_id}", | |
| content="I need to identify the key information in this word problem", | |
| step_type="analysis", | |
| confidence=0.85, | |
| dependencies=[], | |
| ), | |
| ReasoningStep( | |
| step_id=f"step_2_{chain_id}", | |
| content="I'll set up the mathematical relationship", | |
| step_type="computation", | |
| confidence=0.90, | |
| dependencies=[f"step_1_{chain_id}"], | |
| ), | |
| ReasoningStep( | |
| step_id=f"step_3_{chain_id}", | |
| content="Now I'll solve the equation", | |
| step_type="computation", | |
| confidence=0.92, | |
| dependencies=[f"step_2_{chain_id}"], | |
| ), | |
| ReasoningStep( | |
| step_id=f"step_4_{chain_id}", | |
| content="The solution makes sense in the context", | |
| step_type="conclusion", | |
| confidence=0.88, | |
| dependencies=[ | |
| f"step_1_{chain_id}", | |
| f"step_2_{chain_id}", | |
| f"step_3_{chain_id}", | |
| ], | |
| ), | |
| ] | |
| return ReasoningChain( | |
| problem=problem, | |
| steps=steps, | |
| solution="Word problem solution derived", | |
| total_confidence=0.0, | |
| metadata={"category": "word_problem", "chain_id": chain_id}, | |
| ) | |
| def _create_decision_chain(chain_id: int) -> ReasoningChain: | |
| decisions = [ | |
| "Should we invest in renewable energy?", | |
| "Which candidate should we hire?", | |
| "Should we expand to international markets?", | |
| ] | |
| problem = np.random.choice(decisions) | |
| steps = [ | |
| ReasoningStep( | |
| step_id=f"step_1_{chain_id}", | |
| content="I need to identify the key factors to consider", | |
| step_type="analysis", | |
| confidence=0.80, | |
| dependencies=[], | |
| ), | |
| ReasoningStep( | |
| step_id=f"step_2_{chain_id}", | |
| content="I'll evaluate the pros and cons of each option", | |
| step_type="computation", | |
| confidence=0.85, | |
| dependencies=[f"step_1_{chain_id}"], | |
| ), | |
| ReasoningStep( | |
| step_id=f"step_3_{chain_id}", | |
| content="I need to consider the risks and benefits", | |
| step_type="verification", | |
| confidence=0.82, | |
| dependencies=[f"step_2_{chain_id}"], | |
| ), | |
| ReasoningStep( | |
| step_id=f"step_4_{chain_id}", | |
| content="Based on my analysis, I recommend the best option", | |
| step_type="conclusion", | |
| confidence=0.75, | |
| dependencies=[ | |
| f"step_1_{chain_id}", | |
| f"step_2_{chain_id}", | |
| f"step_3_{chain_id}", | |
| ], | |
| ), | |
| ] | |
| return ReasoningChain( | |
| problem=problem, | |
| steps=steps, | |
| solution="Decision recommendation provided", | |
| total_confidence=0.0, | |
| metadata={"category": "decision_making", "chain_id": chain_id}, | |
| ) | |
| def _create_generic_chain(chain_id: int) -> ReasoningChain: | |
| problem = f"Generic problem {chain_id}" | |
| steps = [ | |
| ReasoningStep( | |
| step_id=f"step_1_{chain_id}", | |
| content="I need to understand this problem", | |
| step_type="analysis", | |
| confidence=0.8, | |
| dependencies=[], | |
| ), | |
| ReasoningStep( | |
| step_id=f"step_2_{chain_id}", | |
| content="I'll work through the solution", | |
| step_type="computation", | |
| confidence=0.85, | |
| dependencies=[f"step_1_{chain_id}"], | |
| ), | |
| ReasoningStep( | |
| step_id=f"step_3_{chain_id}", | |
| content="The solution is complete", | |
| step_type="conclusion", | |
| confidence=0.9, | |
| dependencies=[f"step_1_{chain_id}", f"step_2_{chain_id}"], | |
| ), | |
| ] | |
| return ReasoningChain( | |
| problem=problem, | |
| steps=steps, | |
| solution="Generic solution", | |
| total_confidence=0.0, | |
| metadata={"category": "generic", "chain_id": chain_id}, | |
| ) | |
| def create_visualizations_folder(base_path: str) -> str: | |
| viz_path = os.path.join(base_path, "visualizations") | |
| os.makedirs(viz_path, exist_ok=True) | |
| subdirs = ["reasoning_chains", "comparisons", "performance", "trees", "graphs"] | |
| for subdir in subdirs: | |
| os.makedirs(os.path.join(viz_path, subdir), exist_ok=True) | |
| return viz_path | |
Xet Storage Details
- Size:
- 17.6 kB
- Xet hash:
- cd185c9c3b752fc46e1099e4054a0cdfe4d41995cf6b048b06fbff59cbaabeb5
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.