tahamajs's picture
download
raw
15.9 kB
import time
import json
import random
import numpy as np
from typing import List, Dict, Any, Optional, Tuple, Union, Callable
from pathlib import Path
from dataclasses import dataclass, asdict
import logging
from functools import wraps
try:
from .core.data_structures import ThoughtState, ReasoningProblem
except ImportError:
from core.data_structures import ThoughtState, ReasoningProblem
def setup_logging(
log_level: str = "INFO", log_file: Optional[str] = None
) -> logging.Logger:
logger = logging.getLogger("advanced_reasoning")
logger.setLevel(getattr(logging, log_level.upper()))
logger.handlers.clear()
formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
if log_file:
file_handler = logging.FileHandler(log_file)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
return logger
def timing_decorator(func: Callable) -> Callable:
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
execution_time = end_time - start_time
logger = logging.getLogger("advanced_reasoning")
logger.info(f"{func.__name__} executed in {execution_time:.4f} seconds")
if isinstance(result, dict):
result["execution_time"] = execution_time
return result
return wrapper
def performance_monitor(func: Callable) -> Callable:
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
start_memory = _get_memory_usage()
try:
result = func(*args, **kwargs)
success = True
error = None
except Exception as e:
result = None
success = False
error = str(e)
raise
finally:
end_time = time.time()
end_memory = _get_memory_usage()
performance_metrics = {
"execution_time": end_time - start_time,
"memory_delta": end_memory - start_memory,
"success": success,
"error": error,
}
logger = logging.getLogger("advanced_reasoning")
logger.debug(f"{func.__name__} performance: {performance_metrics}")
if isinstance(result, dict):
result["performance_metrics"] = performance_metrics
return result
return wrapper
def _get_memory_usage() -> float:
try:
import psutil
process = psutil.Process()
return process.memory_info().rss / 1024 / 1024
except ImportError:
return 0.0
def set_random_seed(seed: int = 42):
random.seed(seed)
np.random.seed(seed)
try:
import torch
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
except ImportError:
pass
def create_directory_structure(base_dir: str = "results"):
base_path = Path(base_dir)
directories = [
"results",
"visualizations",
"logs",
"configs",
"data",
"models",
"cache",
]
for directory in directories:
(base_path / directory).mkdir(parents=True, exist_ok=True)
return base_path
def save_results(results: Dict[str, Any], filename: str, directory: str = "results"):
output_dir = Path(directory)
output_dir.mkdir(exist_ok=True)
filepath = output_dir / filename
serializable_results = _make_serializable(results)
with open(filepath, "w") as f:
json.dump(serializable_results, f, indent=2)
return filepath
def load_results(filename: str, directory: str = "results") -> Dict[str, Any]:
filepath = Path(directory) / filename
if not filepath.exists():
raise FileNotFoundError(f"Results file not found: {filepath}")
with open(filepath, "r") as f:
results = json.load(f)
return results
def _make_serializable(obj):
if isinstance(obj, dict):
return {k: _make_serializable(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [_make_serializable(item) for item in obj]
elif hasattr(obj, "to_dict"):
return obj.to_dict()
elif hasattr(obj, "__dict__"):
return {k: _make_serializable(v) for k, v in obj.__dict__.items()}
elif isinstance(obj, (int, float, str, bool)) or obj is None:
return obj
else:
return str(obj)
class ProblemGenerator:
def __init__(self, seed: int = 42):
set_random_seed(seed)
self.problem_types = ["game24", "math_word", "logical", "puzzle"]
def generate_game24_problems(
self, count: int = 5, difficulty: str = "medium"
) -> List[Dict]:
try:
from .tree_of_thought import Game24Problem
except ImportError:
from tree_of_thought import Game24Problem
problems = []
if difficulty == "easy":
number_sets = [
[1, 1, 8, 8],
[2, 2, 4, 4],
[3, 3, 6, 6],
[1, 2, 3, 4],
[2, 3, 4, 6],
]
elif difficulty == "medium":
number_sets = [
[3, 3, 8, 8],
[4, 4, 7, 7],
[1, 5, 5, 5],
[2, 6, 6, 8],
[3, 4, 5, 6],
]
else:
number_sets = [
[1, 5, 5, 5],
[4, 7, 8, 8],
[6, 6, 9, 9],
[1, 3, 7, 9],
[2, 4, 8, 8],
]
for i, numbers in enumerate(number_sets[:count]):
problem = Game24Problem(numbers)
problems.append(
{
"problem": problem,
"difficulty": difficulty,
"problem_type": "game24",
"description": f"Game24 problem {i+1} with numbers {numbers}",
}
)
return problems
def generate_math_word_problems(self, count: int = 5) -> List[Dict]:
try:
from .tree_of_thought import MathWordProblem
except ImportError:
from tree_of_thought import MathWordProblem
problems = []
word_problems = [
("If 5 apples cost $2, how much do 15 apples cost?", 6.0),
("A car travels 60 miles in 1.5 hours. What is its average speed?", 40.0),
("Find the area of a rectangle with length 8 and width 5.", 40.0),
(
"A train travels 240 miles in 4 hours. How long will it take to travel 360 miles?",
6.0,
),
(
"If a recipe serves 4 people and calls for 2 cups of flour, how much flour is needed for 10 people?",
5.0,
),
]
for i, (problem_text, answer) in enumerate(word_problems[:count]):
problem = MathWordProblem(problem_text, answer)
problems.append(
{
"problem": problem,
"difficulty": "medium",
"problem_type": "math_word",
"description": f"Math word problem {i+1}",
}
)
return problems
def generate_benchmark_suite(self, total_problems: int = 10) -> List[Dict]:
benchmark_problems = []
game24_problems = self.generate_game24_problems(
count=min(5, total_problems // 2), difficulty="medium"
)
benchmark_problems.extend(game24_problems)
remaining = total_problems - len(benchmark_problems)
math_problems = self.generate_math_word_problems(count=remaining)
benchmark_problems.extend(math_problems)
return benchmark_problems
class MetricsCalculator:
@staticmethod
def calculate_success_rate(results: List[Dict]) -> float:
if not results:
return 0.0
successful = sum(1 for result in results if result.get("solution_found", False))
return successful / len(results)
@staticmethod
def calculate_average_quality(results: List[Dict]) -> float:
if not results:
return 0.0
qualities = [result.get("solution_quality", 0) for result in results]
return sum(qualities) / len(qualities)
@staticmethod
def calculate_efficiency(results: List[Dict]) -> float:
if not results:
return 0.0
total_quality = sum(result.get("solution_quality", 0) for result in results)
total_compute = sum(result.get("computational_cost", 1) for result in results)
return total_quality / max(total_compute, 1)
@staticmethod
def calculate_consistency(results: List[Dict]) -> float:
if not results:
return 0.0
qualities = [result.get("solution_quality", 0) for result in results]
if not qualities:
return 0.0
mean_quality = sum(qualities) / len(qualities)
variance = sum((q - mean_quality) ** 2 for q in qualities) / len(qualities)
if mean_quality == 0:
return 0.0
coefficient_of_variation = np.sqrt(variance) / mean_quality
return 1.0 / (1.0 + coefficient_of_variation)
class ConfigurationManager:
def __init__(self, config_file: Optional[str] = None):
self.config = {}
if config_file and Path(config_file).exists():
self.load_config(config_file)
def load_config(self, config_file: str):
filepath = Path(config_file)
if filepath.suffix == ".json":
with open(filepath, "r") as f:
self.config = json.load(f)
elif filepath.suffix in [".yaml", ".yml"]:
try:
import yaml
with open(filepath, "r") as f:
self.config = yaml.safe_load(f)
except ImportError:
raise ImportError("PyYAML is required for YAML config files")
else:
raise ValueError(f"Unsupported config format: {filepath.suffix}")
def save_config(self, config_file: str):
filepath = Path(config_file)
filepath.parent.mkdir(parents=True, exist_ok=True)
if filepath.suffix == ".json":
with open(filepath, "w") as f:
json.dump(self.config, f, indent=2)
elif filepath.suffix in [".yaml", ".yml"]:
try:
import yaml
with open(filepath, "w") as f:
yaml.dump(self.config, f, default_flow_style=False)
except ImportError:
raise ImportError("PyYAML is required for YAML config files")
else:
raise ValueError(f"Unsupported config format: {filepath.suffix}")
def get(self, key: str, default: Any = None) -> Any:
return self.config.get(key, default)
def set(self, key: str, value: Any):
self.config[key] = value
def update(self, updates: Dict[str, Any]):
self.config.update(updates)
class ProgressTracker:
def __init__(self, total: int, description: str = "Processing"):
self.total = total
self.current = 0
self.description = description
self.start_time = time.time()
self.last_update = 0
def update(self, increment: int = 1, message: str = None):
self.current += increment
current_time = time.time()
if current_time - self.last_update >= 0.5 or self.current >= self.total:
self._print_progress(message)
self.last_update = current_time
def _print_progress(self, message: str = None):
percentage = (self.current / self.total) * 100
elapsed_time = time.time() - self.start_time
if self.current > 0:
eta = (elapsed_time / self.current) * (self.total - self.current)
eta_str = f"ETA: {eta:.1f}s"
else:
eta_str = "ETA: --"
progress_bar = self._create_progress_bar(percentage)
status = f"\r{self.description}: {progress_bar} {percentage:.1f}% ({self.current}/{self.total}) {eta_str}"
if message:
status += f" - {message}"
print(status, end="", flush=True)
if self.current >= self.total:
print()
def _create_progress_bar(self, percentage: float, width: int = 20) -> str:
filled = int(width * percentage / 100)
bar = "█" * filled + "░" * (width - filled)
return f"[{bar}]"
def validate_problem(problem: ReasoningProblem) -> Tuple[bool, List[str]]:
errors = []
if not problem.problem_statement or not problem.problem_statement.strip():
errors.append("Problem statement is empty")
if not hasattr(problem, "generate_thoughts"):
errors.append("Problem must implement generate_thoughts method")
if not hasattr(problem, "evaluate_state"):
errors.append("Problem must implement evaluate_state method")
if not hasattr(problem, "is_solution"):
errors.append("Problem must implement is_solution method")
return len(errors) == 0, errors
def validate_solution(
solution: ThoughtState, problem: ReasoningProblem
) -> Tuple[bool, str]:
if not solution:
return False, "No solution provided"
if not problem.is_solution(solution):
return False, "Solution does not satisfy problem requirements"
path = solution.get_path_to_root()
if len(path) < 2:
return False, "Solution path is too short"
return True, "Solution is valid"
def create_summary_report(
results: Dict[str, Any], output_file: str = "summary_report.txt"
):
with open(output_file, "w") as f:
f.write("Advanced Reasoning System - Summary Report\n")
f.write("=" * 50 + "\n\n")
if "system_results" in results:
f.write("System Comparison Results:\n")
f.write("-" * 30 + "\n")
for system_name, system_results in results["system_results"].items():
f.write(f"\n{system_name}:\n")
if "aggregate_metrics" in system_results:
metrics = system_results["aggregate_metrics"]
f.write(f" Success Rate: {metrics.get('success_rate', 0):.3f}\n")
f.write(
f" Average Quality: {metrics.get('average_quality', 0):.3f}\n"
)
f.write(
f" Average Compute: {metrics.get('average_compute', 0):.1f}\n"
)
f.write(
f" Efficiency: {metrics.get('quality_per_compute', 0):.3f}\n"
)
if "comparison_results" in results:
f.write("\nOverall Rankings:\n")
f.write("-" * 20 + "\n")
comparison = results["comparison_results"]
if "overall_rankings" in comparison:
for i, (system_name, score) in enumerate(
comparison["overall_rankings"]
):
f.write(f"{i+1}. {system_name}: {score:.3f}\n")
f.write(f"\nReport generated at: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
return output_file
__all__ = [
"setup_logging",
"timing_decorator",
"performance_monitor",
"set_random_seed",
"create_directory_structure",
"save_results",
"load_results",
"ProblemGenerator",
"MetricsCalculator",
"ConfigurationManager",
"ProgressTracker",
"validate_problem",
"validate_solution",
"create_summary_report",
]

Xet Storage Details

Size:
15.9 kB
·
Xet hash:
759a7df5ee122aae04e39bd55a91e3a58c863aceb7da360e0f848d42abd15d9c

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.