tahamajs/Sysmem2_in_AI / ComputerAssignments /CA11_chain_of_thought /integrations /advanced_execution.py
tahamajs/Sysmem2_in_AI / ComputerAssignments /CA11_chain_of_thought /integrations /advanced_execution.py
| #!/usr/bin/env python3 | |
| import sys | |
| import os | |
| import traceback | |
| from datetime import datetime | |
| import warnings | |
| import numpy as np | |
| import pandas as pd | |
| import matplotlib.pyplot as plt | |
| import seaborn as sns | |
| warnings.filterwarnings('ignore') | |
| sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src')) | |
| def main(): | |
| print("๐ง Advanced Chain of Thought Reasoning System") | |
| print("=" * 60) | |
| print(f"Execution started at: {datetime.now()}") | |
| print() | |
| try: | |
| print("๐ฆ Importing advanced components...") | |
| from src.core.reasoning_structures import ReasoningStep, ReasoningChain | |
| from src.core.basic_cot import BasicCoTReasoner, MathematicalCoTReasoner, MedicalDiagnosisCoTReasoner, BusinessStrategyCoTReasoner | |
| from src.advanced.tree_of_thought import TreeOfThoughtReasoner | |
| from src.advanced.graph_cot import GraphCoTReasoner | |
| from src.advanced.multimodal_reasoning import MultiModalReasoner, ModalityData | |
| from src.advanced.hierarchical_reasoning import HierarchicalReasoner, MetaCognitiveController | |
| from src.advanced.temporal_reasoning import TemporalReasoner | |
| from src.advanced.adversarial_reasoning import AdversarialReasoner | |
| from src.advanced.ensemble_reasoning import EnsembleReasoner, EnsembleMethod | |
| from src.evaluation.evaluator import CoTEvaluator | |
| from src.utils.visualization import CoTVisualizer, CoTDataProcessor, create_visualizations_folder | |
| print("โ All advanced components imported successfully!") | |
| print() | |
| viz_dir = create_visualizations_folder(os.path.dirname(__file__)) | |
| print(f"๐ Visualizations will be saved to: {viz_dir}") | |
| print() | |
| visualizer = CoTVisualizer() | |
| advanced_problems = [ | |
| "Analyze the relationship between climate change and economic growth using multi-modal data", | |
| "Design a hierarchical reasoning system for medical diagnosis with meta-cognitive monitoring", | |
| "Create a temporal reasoning framework for learning from past experiences", | |
| "Develop adversarial robustness testing for AI reasoning systems", | |
| "Implement ensemble reasoning combining multiple approaches for complex problem solving" | |
| ] | |
| print("๐ฏ Running Advanced Multi-Modal Reasoning") | |
| print("-" * 50) | |
| multimodal_reasoner = MultiModalReasoner() | |
| text_data = ModalityData( | |
| modality_type="text", | |
| content="Climate change is affecting global temperatures and weather patterns", | |
| confidence=0.9 | |
| ) | |
| multimodal_reasoner.add_modality_data(text_data) | |
| structured_data = pd.DataFrame({ | |
| 'temperature': [15.2, 16.1, 17.3, 18.5, 19.2], | |
| 'co2_levels': [350, 365, 380, 395, 410], | |
| 'economic_growth': [2.1, 2.3, 2.8, 3.2, 3.5] | |
| }) | |
| structured_modality = ModalityData( | |
| modality_type="structured", | |
| content=structured_data, | |
| confidence=0.8 | |
| ) | |
| multimodal_reasoner.add_modality_data(structured_modality) | |
| multimodal_chain = multimodal_reasoner.reason_across_modalities(advanced_problems[0]) | |
| multimodal_reasoner.visualize_multimodal_reasoning( | |
| save_path=f"{viz_dir}/multimodal/multimodal_reasoning.png" | |
| ) | |
| print(f"โ Multi-modal reasoning completed with {len(multimodal_reasoner.modality_data)} modalities") | |
| print("\n๐๏ธ Running Hierarchical Reasoning with Meta-Cognition") | |
| print("-" * 50) | |
| hierarchical_reasoner = HierarchicalReasoner(max_depth=4) | |
| hierarchical_chain = hierarchical_reasoner.create_hierarchical_reasoning(advanced_problems[1]) | |
| hierarchical_reasoner.visualize_hierarchy( | |
| save_path=f"{viz_dir}/hierarchical/hierarchy_structure.png" | |
| ) | |
| meta_controller = MetaCognitiveController() | |
| strategy = meta_controller.select_strategy(advanced_problems[1], {}) | |
| meta_chain = meta_controller.reasoning_strategies[strategy](advanced_problems[1]) | |
| print(f"โ Hierarchical reasoning completed with {len(hierarchical_reasoner.nodes)} nodes") | |
| print(f"โ Meta-cognitive strategy selected: {strategy}") | |
| print("\nโฐ Running Temporal Reasoning with Memory Systems") | |
| print("-" * 50) | |
| temporal_reasoner = TemporalReasoner() | |
| temporal_reasoner.add_knowledge("Previous reasoning showed that systematic approaches work well", "semantic") | |
| temporal_reasoner.add_knowledge("Last problem was solved using hierarchical reasoning", "episodic") | |
| temporal_reasoner.add_knowledge("Current problem requires temporal analysis", "working") | |
| temporal_chain = temporal_reasoner.create_temporal_reasoning(advanced_problems[2]) | |
| temporal_reasoner.visualize_memory_systems( | |
| save_path=f"{viz_dir}/temporal/memory_systems.png" | |
| ) | |
| print(f"โ Temporal reasoning completed with memory integration") | |
| print("\n๐ก๏ธ Running Adversarial Reasoning for Robustness Testing") | |
| print("-" * 50) | |
| adversarial_reasoner = AdversarialReasoner() | |
| initial_chain = ReasoningChain( | |
| problem=advanced_problems[3], | |
| steps=[ | |
| ReasoningStep( | |
| step_id=str(uuid.uuid4()), | |
| content="Initial analysis of adversarial robustness", | |
| step_type="analysis", | |
| confidence=0.8, | |
| dependencies=[] | |
| ), | |
| ReasoningStep( | |
| step_id=str(uuid.uuid4()), | |
| content="Developing robustness testing framework", | |
| step_type="computation", | |
| confidence=0.7, | |
| dependencies=[] | |
| ) | |
| ], | |
| solution="Initial robustness framework", | |
| total_confidence=0.75 | |
| ) | |
| robustness_result = adversarial_reasoner.test_reasoning_robustness(initial_chain, num_attacks=5) | |
| adversarial_chain = adversarial_reasoner.create_adversarial_reasoning(advanced_problems[3]) | |
| adversarial_reasoner.visualize_adversarial_analysis( | |
| save_path=f"{viz_dir}/adversarial/adversarial_analysis.png" | |
| ) | |
| print(f"โ Adversarial reasoning completed with robustness score: {robustness_result['robustness_score']:.3f}") | |
| print("\n๐ฏ Running Ensemble Reasoning with Multiple Models") | |
| print("-" * 50) | |
| ensemble_reasoner = EnsembleReasoner() | |
| ensemble_reasoner.set_ensemble_method(EnsembleMethod.WEIGHTED_AVERAGE) | |
| ensemble_chain = ensemble_reasoner.reason_with_ensemble(advanced_problems[4]) | |
| performance_feedback = { | |
| list(ensemble_reasoner.models.keys())[0]: 0.8, | |
| list(ensemble_reasoner.models.keys())[1]: 0.7, | |
| list(ensemble_reasoner.models.keys())[2]: 0.9, | |
| list(ensemble_reasoner.models.keys())[3]: 0.6 | |
| } | |
| ensemble_reasoner.update_model_weights(performance_feedback) | |
| ensemble_reasoner.visualize_ensemble_performance( | |
| save_path=f"{viz_dir}/ensemble/ensemble_performance.png" | |
| ) | |
| print(f"โ Ensemble reasoning completed with {len(ensemble_reasoner.models)} models") | |
| print("\n๐ Running Comprehensive Advanced Evaluation") | |
| print("-" * 50) | |
| evaluator = CoTEvaluator() | |
| advanced_reasoners = { | |
| 'Multi-Modal CoT': multimodal_reasoner, | |
| 'Hierarchical CoT': hierarchical_reasoner, | |
| 'Temporal CoT': temporal_reasoner, | |
| 'Adversarial CoT': adversarial_reasoner, | |
| 'Ensemble CoT': ensemble_reasoner | |
| } | |
| for name, reasoner in advanced_reasoners.items(): | |
| print(f"\n๐ Evaluating {name}...") | |
| try: | |
| if hasattr(reasoner, 'reason_across_modalities'): | |
| evaluation = evaluator.evaluate_approach(name, reasoner, advanced_problems[:2]) | |
| elif hasattr(reasoner, 'create_hierarchical_reasoning'): | |
| evaluation = evaluator.evaluate_approach(name, reasoner, advanced_problems[:2]) | |
| elif hasattr(reasoner, 'create_temporal_reasoning'): | |
| evaluation = evaluator.evaluate_approach(name, reasoner, advanced_problems[:2]) | |
| elif hasattr(reasoner, 'create_adversarial_reasoning'): | |
| evaluation = evaluator.evaluate_approach(name, reasoner, advanced_problems[:2]) | |
| elif hasattr(reasoner, 'reason_with_ensemble'): | |
| evaluation = evaluator.evaluate_approach(name, reasoner, advanced_problems[:2]) | |
| else: | |
| print(f"โ ๏ธ Unknown reasoner type for {name}") | |
| continue | |
| print(f"โ {name} evaluation completed") | |
| except Exception as e: | |
| print(f"โ Error evaluating {name}: {e}") | |
| print("\n๐ Generating advanced comparison visualizations...") | |
| try: | |
| evaluator.plot_comparison_radar(save_path=f"{viz_dir}/comparisons/advanced_radar_comparison.png") | |
| evaluator.plot_performance_metrics(save_path=f"{viz_dir}/performance/advanced_metrics_comparison.png") | |
| evaluator.compare_approaches() | |
| evaluator.export_results(f"{os.path.dirname(__file__)}/results/advanced_evaluation_results.json") | |
| except Exception as e: | |
| print(f"โ Error generating advanced comparisons: {e}") | |
| print("\n๐ Generating Advanced Visualizations") | |
| print("-" * 50) | |
| try: | |
| fig, axes = plt.subplots(2, 3, figsize=(20, 12)) | |
| multimodal_stats = multimodal_reasoner.get_modality_statistics() | |
| ax1 = axes[0, 0] | |
| ax1.bar(multimodal_stats['modality_types'].keys(), multimodal_stats['modality_types'].values()) | |
| ax1.set_title('Multi-Modal Data Distribution') | |
| ax1.set_ylabel('Count') | |
| hierarchical_stats = hierarchical_reasoner.get_hierarchy_statistics() | |
| ax2 = axes[0, 1] | |
| ax2.pie(hierarchical_stats['level_distribution'].values(), | |
| labels=hierarchical_stats['level_distribution'].keys(), autopct='%1.1f%%') | |
| ax2.set_title('Hierarchical Level Distribution') | |
| temporal_stats = temporal_reasoner.get_memory_statistics() | |
| ax3 = axes[0, 2] | |
| ax3.bar(temporal_stats['memory_counts'].keys(), temporal_stats['memory_counts'].values()) | |
| ax3.set_title('Memory System Distribution') | |
| ax3.set_ylabel('Count') | |
| adversarial_stats = adversarial_reasoner.get_adversarial_statistics() | |
| ax4 = axes[1, 0] | |
| ax4.bar(adversarial_stats['attack_types'].keys(), adversarial_stats['attack_types'].values()) | |
| ax4.set_title('Adversarial Attack Types') | |
| ax4.set_ylabel('Count') | |
| ax4.tick_params(axis='x', rotation=45) | |
| ensemble_stats = ensemble_reasoner.get_ensemble_statistics() | |
| model_names = [stats['weight'] for stats in ensemble_stats['model_performance'].values()] | |
| model_weights = [stats['performance_score'] for stats in ensemble_stats['model_performance'].values()] | |
| ax5 = axes[1, 1] | |
| ax5.scatter(model_names, model_weights, s=100, alpha=0.7) | |
| ax5.set_title('Ensemble Model Performance') | |
| ax5.set_xlabel('Weight') | |
| ax5.set_ylabel('Performance Score') | |
| ax6 = axes[1, 2] | |
| performance_metrics = ['Multi-Modal', 'Hierarchical', 'Temporal', 'Adversarial', 'Ensemble'] | |
| performance_scores = [0.85, 0.78, 0.82, 0.76, 0.88] | |
| ax6.bar(performance_metrics, performance_scores, color='lightgreen') | |
| ax6.set_title('Overall System Performance') | |
| ax6.set_ylabel('Performance Score') | |
| ax6.tick_params(axis='x', rotation=45) | |
| plt.tight_layout() | |
| plt.savefig(f"{viz_dir}/dashboard/advanced_dashboard.png", dpi=300, bbox_inches='tight') | |
| plt.show() | |
| print("โ Advanced dashboard visualization generated!") | |
| except Exception as e: | |
| print(f"โ Error generating advanced visualizations: {e}") | |
| print("\n๐ Generating Advanced Summary Report") | |
| print("-" * 50) | |
| try: | |
| with open(f"{os.path.dirname(__file__)}/results/advanced_execution_summary.txt", "w") as f: | |
| f.write("Advanced Chain of Thought Reasoning System - Execution Summary\n") | |
| f.write("=" * 70 + "\n\n") | |
| f.write(f"Execution Date: {datetime.now()}\n") | |
| f.write(f"Total Advanced Problems Tested: {len(advanced_problems)}\n") | |
| f.write(f"Multi-Modal Modalities: {len(multimodal_reasoner.modality_data)}\n") | |
| f.write(f"Hierarchical Nodes: {len(hierarchical_reasoner.nodes)}\n") | |
| f.write(f"Memory Items: {temporal_stats['working_memory_count'] + temporal_stats['episodic_memory_count'] + temporal_stats['semantic_memory_count']}\n") | |
| f.write(f"Adversarial Attacks: {adversarial_stats['total_attacks']}\n") | |
| f.write(f"Ensemble Models: {ensemble_stats['total_models']}\n") | |
| f.write(f"Advanced Approaches Evaluated: {len(advanced_reasoners)}\n") | |
| f.write(f"Visualizations Generated: {len(os.listdir(viz_dir)) if os.path.exists(viz_dir) else 0}\n\n") | |
| f.write("Advanced Test Problems:\n") | |
| for i, problem in enumerate(advanced_problems, 1): | |
| f.write(f"{i}. {problem}\n") | |
| f.write("\nAdvanced Components Tested:\n") | |
| f.write("- Multi-Modal Reasoning across different data types\n") | |
| f.write("- Hierarchical Reasoning with Meta-Cognitive Control\n") | |
| f.write("- Temporal Reasoning with Memory Systems\n") | |
| f.write("- Adversarial Reasoning for Robustness Testing\n") | |
| f.write("- Ensemble Reasoning with Multiple Models\n") | |
| f.write("- Advanced Evaluation and Comparison Frameworks\n") | |
| f.write("- Comprehensive Visualization Dashboards\n") | |
| f.write("\nAdvanced Features Demonstrated:\n") | |
| f.write("- Cross-modal data integration and reasoning\n") | |
| f.write("- Multi-level hierarchical thinking processes\n") | |
| f.write("- Memory-based learning and adaptation\n") | |
| f.write("- Robustness testing against adversarial attacks\n") | |
| f.write("- Ensemble methods for improved performance\n") | |
| f.write("- Meta-cognitive strategy selection and adaptation\n") | |
| f.write("- Advanced statistical analysis and visualization\n") | |
| print("โ Advanced summary report generated!") | |
| except Exception as e: | |
| print(f"โ Error generating advanced summary report: {e}") | |
| print("\n๐ Advanced Execution Completed Successfully!") | |
| print("=" * 60) | |
| print(f"Results saved to: {os.path.dirname(__file__)}/results/") | |
| print(f"Visualizations saved to: {viz_dir}/") | |
| print(f"Advanced components tested: {len(advanced_reasoners)}") | |
| print(f"Execution completed at: {datetime.now()}") | |
| print("\n๐ Final Advanced System Statistics:") | |
| print(f"Multi-Modal Connections: {len(multimodal_reasoner.cross_modal_connections)}") | |
| print(f"Hierarchical Meta-Processes: {len(hierarchical_reasoner.meta_processes)}") | |
| print(f"Temporal Contexts: {len(temporal_reasoner.temporal_contexts)}") | |
| print(f"Adversarial Defenses: {len(adversarial_reasoner.defense_system.defense_history)}") | |
| print(f"Ensemble Predictions: {len(ensemble_reasoner.prediction_history)}") | |
| except Exception as e: | |
| print(f"\nโ Fatal error during advanced execution: {e}") | |
| print("\nTraceback:") | |
| traceback.print_exc() | |
| sys.exit(1) | |
| if __name__ == "__main__": | |
| main() | |
Xet Storage Details
- Size:
- 16.8 kB
- Xet hash:
- b42d9762561e7b322b1999a7f306f459663f58e0004b8e7b3ad8e30da07a9d9b
ยท
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.