From ca2da94dbd8a2cb3f713502bc6e3c5e0f3e9244b Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 27 Nov 2025 09:08:26 +0000 Subject: [PATCH] Refactor: Improve path handling and print statements in examples Co-authored-by: taurekaw --- examples/demo_ljpw_v4.py | 15 +++++---- examples/demo_v2.py | 10 +++--- examples/realistic_code_samples.py | 4 ++- harmonizer/ljpw_baselines.py | 2 +- harmonizer/relationship_analyzer.py | 2 +- scripts/run_validation.py | 35 +++++++++++---------- scripts/validate_relationship_hypothesis.py | 11 ++++--- scripts/verify_tech_debt.py | 3 +- tests/test_enhanced_parser.py | 24 +++----------- tests/test_harmonizer_enhanced.py | 6 ++-- tests/test_language_semantics.py | 4 +-- tests/test_legacy_mapper.py | 4 +-- tests/test_ljpw_baselines.py | 2 -- 13 files changed, 54 insertions(+), 68 deletions(-) diff --git a/examples/demo_ljpw_v4.py b/examples/demo_ljpw_v4.py index 6b9bfda..5b47e00 100644 --- a/examples/demo_ljpw_v4.py +++ b/examples/demo_ljpw_v4.py @@ -11,13 +11,16 @@ import os import matplotlib.pyplot as plt -# Add parent directory to path to import harmonizer -sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -from harmonizer.ljpw_baselines import DynamicLJPWv4, ReferencePoints +def run_demo(): + # Import lazily after ensuring the repository root is on sys.path to keep + # flake8 happy about module level imports (E402). + repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + if repo_root not in sys.path: + sys.path.insert(0, repo_root) + from harmonizer.ljpw_baselines import DynamicLJPWv4, ReferencePoints -def run_demo(): print("=" * 60) print("LJPW v4.0 Dynamic Model Demo") print("=" * 60) @@ -32,7 +35,7 @@ def run_demo(): # Initial State: High Power (0.9), Low Wisdom (0.2), Low Love (0.2), Moderate Justice (0.5) initial_state = (0.2, 0.5, 0.9, 0.2) - print(f"Initial State:") + print("Initial State:") print(f" Love: {initial_state[0]:.2f}") print(f" Justice: {initial_state[1]:.2f}") print(f" Power: {initial_state[2]:.2f} (High!)") @@ -52,7 +55,7 @@ def run_demo(): final_W = history["W"][-1] print("-" * 60) - print(f"Final State:") + print("Final State:") print(f" Love: {final_L:.2f}") print(f" Justice: {final_J:.2f} (Collapsed?)") print(f" Power: {final_P:.2f}") diff --git a/examples/demo_v2.py b/examples/demo_v2.py index 000d589..bf169aa 100644 --- a/examples/demo_v2.py +++ b/examples/demo_v2.py @@ -45,18 +45,18 @@ def analyze_with_v2(code, function_name): def print_analysis(result): """Pretty print analysis results.""" - print(f"\n{'='*70}") + print("\n" + "=" * 70) print(f"FUNCTION: {result['function']}") - print(f"{'='*70}") + print("=" * 70) - print(f"\nINTENT (what function claims to do):") + print("\nINTENT (what function claims to do):") print(f" Concepts: {result['intent_concepts']}") print( f" Coordinates: L={result['intent_coords'].love:.3f}, J={result['intent_coords'].justice:.3f}, " f"P={result['intent_coords'].power:.3f}, W={result['intent_coords'].wisdom:.3f}" ) - print(f"\nEXECUTION (what function actually does):") + print("\nEXECUTION (what function actually does):") print(f" Concepts: {result['execution_concepts']}") print( f" Coordinates: L={result['execution_coords'].love:.3f}, J={result['execution_coords'].justice:.3f}, " @@ -133,7 +133,7 @@ def fetch_validate_and_save(data_id): result5 = analyze_with_v2(code5, "fetch_validate_and_save") print_analysis(result5) -print(f"\n{'='*70}") +print("\n" + "=" * 70) print("DEMONSTRATION COMPLETE") print("=" * 70) print("\n✅ Enhanced Parser V2 Features:") diff --git a/examples/realistic_code_samples.py b/examples/realistic_code_samples.py index 72d5dca..30d140d 100644 --- a/examples/realistic_code_samples.py +++ b/examples/realistic_code_samples.py @@ -3,6 +3,8 @@ Demonstrates real-world functions with proper LJPW semantic mapping. """ +from datetime import datetime + # ============================================================================ # HARMONIOUS FUNCTIONS (Intent matches Execution) # ============================================================================ @@ -52,7 +54,7 @@ def send_welcome_email(user_email): EXECUTION: LOVE (email.send = communication operation) Expected harmony: EXCELLENT (~0.05) """ - message = f"Welcome to our platform!" + message = "Welcome to our platform!" email_service.send(to=user_email, body=message) diff --git a/harmonizer/ljpw_baselines.py b/harmonizer/ljpw_baselines.py index 0309126..814586f 100644 --- a/harmonizer/ljpw_baselines.py +++ b/harmonizer/ljpw_baselines.py @@ -372,7 +372,7 @@ def check_proportions( "summary": ( "Proportions match Natural Equilibrium (scale-invariant)" if all_pass - else f"Proportions deviate from Natural Equilibrium" + else "Proportions deviate from Natural Equilibrium" ), } diff --git a/harmonizer/relationship_analyzer.py b/harmonizer/relationship_analyzer.py index 4cd3861..791f5ab 100644 --- a/harmonizer/relationship_analyzer.py +++ b/harmonizer/relationship_analyzer.py @@ -9,7 +9,7 @@ regardless of absolute magnitudes. """ -from typing import Dict, Tuple, List +from typing import Dict, List import math from harmonizer.ljpw_baselines import NumericalEquivalents, ReferencePoints diff --git a/scripts/run_validation.py b/scripts/run_validation.py index 71eeebf..5cf5209 100644 --- a/scripts/run_validation.py +++ b/scripts/run_validation.py @@ -10,20 +10,18 @@ import sys import os import glob -import numpy as np from statistics import mean -# Add project root to path -project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.append(project_root) -from harmonizer.main import PythonCodeHarmonizer -from harmonizer.ljpw_baselines import DynamicLJPWv4, LJPWBaselines -from harmonizer.dependency_engine import DependencyEngine -from harmonizer.visualizer import HarmonizerVisualizer +def _ensure_project_root_on_path() -> str: + """Add the repository root to sys.path when running as a script.""" + project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + if project_root not in sys.path: + sys.path.insert(0, project_root) + return project_root -def analyze_and_simulate(file_path, harmonizer): +def analyze_and_simulate(file_path, harmonizer, simulator_cls): print(f"\nAnalyzing: {os.path.basename(file_path)}") print("-" * 40) @@ -58,7 +56,7 @@ def analyze_and_simulate(file_path, harmonizer): avg_p = mean([c[2] for c in all_coords]) avg_w = mean([c[3] for c in all_coords]) - print(f" Static Metrics (Avg):") + print(" Static Metrics (Avg):") print(f" L: {avg_l:.2f} | J: {avg_j:.2f} | P: {avg_p:.2f} | W: {avg_w:.2f}") # 2. Dynamic Simulation @@ -67,7 +65,7 @@ def analyze_and_simulate(file_path, harmonizer): complexity_score = 1.0 + (function_count * 0.2) print(f" Complexity Score: {complexity_score:.2f}") - simulator = DynamicLJPWv4(complexity_score=complexity_score) + simulator = simulator_cls(complexity_score=complexity_score) print(" Running Dynamic Simulation (50 steps)...") initial_state = (avg_l, avg_j, avg_p, avg_w) @@ -78,7 +76,7 @@ def analyze_and_simulate(file_path, harmonizer): final_p = history["P"][-1] final_w = history["W"][-1] - print(f" Final State:") + print(" Final State:") print(f" L: {final_l:.2f} | J: {final_j:.2f} | P: {final_p:.2f} | W: {final_w:.2f}") # Assessment @@ -101,6 +99,13 @@ def analyze_and_simulate(file_path, harmonizer): def run_validation(): + project_root = _ensure_project_root_on_path() + + from harmonizer.main import PythonCodeHarmonizer + from harmonizer.ljpw_baselines import DynamicLJPWv4 + from harmonizer.dependency_engine import DependencyEngine + from harmonizer.visualizer import HarmonizerVisualizer + harmonizer = PythonCodeHarmonizer(quiet=True) test_dir = os.path.join(project_root, "tests", "user_validation") @@ -112,10 +117,6 @@ def run_validation(): print("LJPW v4.0 Validation Run (Visual Analytics)") print("=" * 60) - # 3. Visual Analytics Integration - from harmonizer.dependency_engine import DependencyEngine - from harmonizer.visualizer import HarmonizerVisualizer - simple_files = glob.glob(os.path.join(test_dir, "simple_*.py")) complex_files = glob.glob(os.path.join(test_dir, "complex_*.py")) all_files = simple_files + complex_files @@ -129,7 +130,7 @@ def run_validation(): print("\n--- ANALYZING FILES ---") for f in all_files: - analysis_data = analyze_and_simulate(f, harmonizer) + analysis_data = analyze_and_simulate(f, harmonizer, DynamicLJPWv4) if analysis_data: results[f] = analysis_data diff --git a/scripts/validate_relationship_hypothesis.py b/scripts/validate_relationship_hypothesis.py index 1b04817..a1f5a80 100644 --- a/scripts/validate_relationship_hypothesis.py +++ b/scripts/validate_relationship_hypothesis.py @@ -14,7 +14,7 @@ import math import numpy as np -from scipy.optimize import curve_fit, minimize +from scipy.optimize import curve_fit import matplotlib.pyplot as plt from typing import Dict, Tuple, List @@ -207,9 +207,10 @@ def analyze_diagonal_vs_offdiagonal(ratios, couplings, labels): print() print("DIAGONAL ELEMENTS (self-coupling):") - for i, label in enumerate([l for l, d in zip(labels, diagonal_mask) if d]): + diagonal_labels = [label for label, is_diagonal in zip(labels, diagonal_mask) if is_diagonal] + for i, label in enumerate(diagonal_labels): print(f" {label}: ratio={diag_ratios[i]:.4f}, κ={diag_couplings[i]:.4f}") - print(f" All diagonal couplings = 1.0 (by definition)") + print(" All diagonal couplings = 1.0 (by definition)") print() print("OFF-DIAGONAL ELEMENTS (cross-coupling):") @@ -235,7 +236,7 @@ def find_special_patterns(ratios, couplings, labels): mask = [label[0] == source for label in labels] source_ratios = ratios[mask] source_couplings = couplings[mask] - source_labels = [l for l, m in zip(labels, mask) if m] + source_labels = [label for label, include in zip(labels, mask) if include] print(f"Source: {source} (outgoing influence)") for i, label in enumerate(source_labels): @@ -325,7 +326,7 @@ def visualize_results(ratios, couplings, labels, results): plt.tight_layout() plt.savefig("/workspace/coupling_ratio_analysis.png", dpi=150, bbox_inches="tight") - print(f"\n✓ Visualization saved to: /workspace/coupling_ratio_analysis.png") + print("\n✓ Visualization saved to: /workspace/coupling_ratio_analysis.png") plt.close() diff --git a/scripts/verify_tech_debt.py b/scripts/verify_tech_debt.py index b80c54c..44fd2d3 100644 --- a/scripts/verify_tech_debt.py +++ b/scripts/verify_tech_debt.py @@ -1,5 +1,4 @@ import os -import sys from harmonizer.legacy_mapper import LegacyCodeMapper @@ -50,7 +49,7 @@ def verify_tech_debt(): # Run Debt Projection projection = mapper.project_debt_trajectory(file_path, months=6) if "error" not in projection: - print(f" Future Debt Projection (6 months):") + print(" Future Debt Projection (6 months):") print(f" Status: {projection['status']}") print(f" Risk Level: {projection['risk_level']}") print(f" Drift: {projection['drift']:.4f}") diff --git a/tests/test_enhanced_parser.py b/tests/test_enhanced_parser.py index c4da028..1cc7be7 100644 --- a/tests/test_enhanced_parser.py +++ b/tests/test_enhanced_parser.py @@ -32,9 +32,6 @@ def test_wisdom_operations(): parser = AST_Semantic_Parser_V2(engine.vocabulary.all_keywords) for code, func_name in code_samples: - tree = ast.parse(code) - func_node = tree.body[0] - # Get intent from name intent_concepts = parser.get_intent_concepts(func_name, None) @@ -43,7 +40,7 @@ def test_wisdom_operations(): # Verify WISDOM is in intent assert "wisdom" in intent_concepts, f"WISDOM should be in intent for {func_name}" - print(f" ✓ WISDOM detected in intent") + print(" ✓ WISDOM detected in intent") print("\n✓ All WISDOM operations validated") @@ -77,9 +74,6 @@ def test_justice_operations(): parser = AST_Semantic_Parser_V2(engine.vocabulary.all_keywords) for code, func_name in code_samples: - tree = ast.parse(code) - func_node = tree.body[0] - # Get intent from name intent_concepts = parser.get_intent_concepts(func_name, None) @@ -88,7 +82,7 @@ def test_justice_operations(): # Verify JUSTICE is in intent assert "justice" in intent_concepts, f"JUSTICE should be in intent for {func_name}" - print(f" ✓ JUSTICE detected in intent") + print(" ✓ JUSTICE detected in intent") print("\n✓ All JUSTICE operations validated") @@ -121,9 +115,6 @@ def test_power_operations(): parser = AST_Semantic_Parser_V2(engine.vocabulary.all_keywords) for code, func_name in code_samples: - tree = ast.parse(code) - func_node = tree.body[0] - # Get intent from name intent_concepts = parser.get_intent_concepts(func_name, None) @@ -132,7 +123,7 @@ def test_power_operations(): # Verify POWER is in intent assert "power" in intent_concepts, f"POWER should be in intent for {func_name}" - print(f" ✓ POWER detected in intent") + print(" ✓ POWER detected in intent") print("\n✓ All POWER operations validated") @@ -164,9 +155,6 @@ def test_love_operations(): parser = AST_Semantic_Parser_V2(engine.vocabulary.all_keywords) for code, func_name in code_samples: - tree = ast.parse(code) - func_node = tree.body[0] - # Get intent from name intent_concepts = parser.get_intent_concepts(func_name, None) @@ -175,7 +163,7 @@ def test_love_operations(): # Verify LOVE is in intent assert "love" in intent_concepts, f"LOVE should be in intent for {func_name}" - print(f" ✓ LOVE detected in intent") + print(" ✓ LOVE detected in intent") print("\n✓ All LOVE operations validated") @@ -229,7 +217,7 @@ def validate_and_save_user(user_data): assert "power" in exec_concepts, "POWER should be in execution (assignments)" assert "wisdom" in exec_concepts, "WISDOM should be in execution (return)" - print(f" ✓ Mixed operations correctly detected") + print(" ✓ Mixed operations correctly detected") print(f" ✓ Intent: {len(intent_concepts)} dimensions") print(f" ✓ Execution: {len(exec_concepts)} dimensions") @@ -326,8 +314,6 @@ def test_backward_compatibility(): from harmonizer.ast_semantic_parser import AST_Semantic_Parser - code = "def calculate_total(items):\n return sum(items)" - engine = DivineInvitationSemanticEngine() # Test with V1 parser diff --git a/tests/test_harmonizer_enhanced.py b/tests/test_harmonizer_enhanced.py index 74a2597..7f77876 100644 --- a/tests/test_harmonizer_enhanced.py +++ b/tests/test_harmonizer_enhanced.py @@ -9,7 +9,6 @@ from harmonizer.ast_semantic_parser_v2 import AST_Semantic_Parser_V2 from harmonizer.divine_invitation_engine_V2 import DivineInvitationSemanticEngine -from harmonizer.semantic_map import SemanticMapGenerator def analyze_function_with_v2(code: str, function_name: str): @@ -17,7 +16,6 @@ def analyze_function_with_v2(code: str, function_name: str): # Initialize components engine = DivineInvitationSemanticEngine() parser = AST_Semantic_Parser_V2(engine.vocabulary.all_keywords) - map_generator = SemanticMapGenerator() # Parse code tree = ast.parse(code) @@ -70,7 +68,7 @@ def print_analysis_report(result): if result["docstring"]: print(f"\nDocstring: {result['docstring'][:60]}...") - print(f"\nINTENT (from function name):") + print("\nINTENT (from function name):") print(f" Concepts: {result['intent_concepts']}") print( f" Coordinates: L={result['intent_coords'].love:.3f}, " @@ -79,7 +77,7 @@ def print_analysis_report(result): f"W={result['intent_coords'].wisdom:.3f}" ) - print(f"\nEXECUTION (from function body):") + print("\nEXECUTION (from function body):") print(f" Concepts: {result['exec_concepts']}") print( f" Coordinates: L={result['exec_coords'].love:.3f}, " diff --git a/tests/test_language_semantics.py b/tests/test_language_semantics.py index cd29d1c..d4a137e 100644 --- a/tests/test_language_semantics.py +++ b/tests/test_language_semantics.py @@ -301,7 +301,7 @@ def test_code_quality_correlation(): print(f" {intent} → {execution}: distance = {distance:.3f}") assert distance < 0.5, f"Good code should have low distance: {intent}" - print(f" ✓ Low disharmony") + print(" ✓ Low disharmony") # Bad code: Intent contradicts execution (using vocabulary words) bad_examples = [ @@ -322,7 +322,7 @@ def test_code_quality_correlation(): print(f" {intent} → {execution}: distance = {distance:.3f}") assert distance > 0.5, f"Bad code should have high distance: {intent}" - print(f" ✓ High disharmony detected") + print(" ✓ High disharmony detected") print("\n✓ Code quality correlation confirmed") diff --git a/tests/test_legacy_mapper.py b/tests/test_legacy_mapper.py index 0d94564..2bb0079 100644 --- a/tests/test_legacy_mapper.py +++ b/tests/test_legacy_mapper.py @@ -1,8 +1,6 @@ import os -import sys -from harmonizer.legacy_mapper import ArchitecturalSmell, LegacyCodeMapper -from harmonizer.ljpw_baselines import LJPWBaselines +from harmonizer.legacy_mapper import LegacyCodeMapper def test_legacy_mapper(): diff --git a/tests/test_ljpw_baselines.py b/tests/test_ljpw_baselines.py index 00d4a52..1539c74 100644 --- a/tests/test_ljpw_baselines.py +++ b/tests/test_ljpw_baselines.py @@ -6,8 +6,6 @@ Validates the mathematical baseline calculations and interpretations. """ -import math - import pytest from harmonizer.ljpw_baselines import (