Skip to content

Commit ca2da94

Browse files
Refactor: Improve path handling and print statements in examples
Co-authored-by: taurekaw <taurekaw@gmail.com>
1 parent 7fb2d99 commit ca2da94

13 files changed

+54
-68
lines changed

examples/demo_ljpw_v4.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,16 @@
1111
import os
1212
import matplotlib.pyplot as plt
1313

14-
# Add parent directory to path to import harmonizer
15-
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
1614

17-
from harmonizer.ljpw_baselines import DynamicLJPWv4, ReferencePoints
15+
def run_demo():
16+
# Import lazily after ensuring the repository root is on sys.path to keep
17+
# flake8 happy about module level imports (E402).
18+
repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
19+
if repo_root not in sys.path:
20+
sys.path.insert(0, repo_root)
1821

22+
from harmonizer.ljpw_baselines import DynamicLJPWv4, ReferencePoints
1923

20-
def run_demo():
2124
print("=" * 60)
2225
print("LJPW v4.0 Dynamic Model Demo")
2326
print("=" * 60)
@@ -32,7 +35,7 @@ def run_demo():
3235
# Initial State: High Power (0.9), Low Wisdom (0.2), Low Love (0.2), Moderate Justice (0.5)
3336
initial_state = (0.2, 0.5, 0.9, 0.2)
3437

35-
print(f"Initial State:")
38+
print("Initial State:")
3639
print(f" Love: {initial_state[0]:.2f}")
3740
print(f" Justice: {initial_state[1]:.2f}")
3841
print(f" Power: {initial_state[2]:.2f} (High!)")
@@ -52,7 +55,7 @@ def run_demo():
5255
final_W = history["W"][-1]
5356

5457
print("-" * 60)
55-
print(f"Final State:")
58+
print("Final State:")
5659
print(f" Love: {final_L:.2f}")
5760
print(f" Justice: {final_J:.2f} (Collapsed?)")
5861
print(f" Power: {final_P:.2f}")

examples/demo_v2.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,18 +45,18 @@ def analyze_with_v2(code, function_name):
4545

4646
def print_analysis(result):
4747
"""Pretty print analysis results."""
48-
print(f"\n{'='*70}")
48+
print("\n" + "=" * 70)
4949
print(f"FUNCTION: {result['function']}")
50-
print(f"{'='*70}")
50+
print("=" * 70)
5151

52-
print(f"\nINTENT (what function claims to do):")
52+
print("\nINTENT (what function claims to do):")
5353
print(f" Concepts: {result['intent_concepts']}")
5454
print(
5555
f" Coordinates: L={result['intent_coords'].love:.3f}, J={result['intent_coords'].justice:.3f}, "
5656
f"P={result['intent_coords'].power:.3f}, W={result['intent_coords'].wisdom:.3f}"
5757
)
5858

59-
print(f"\nEXECUTION (what function actually does):")
59+
print("\nEXECUTION (what function actually does):")
6060
print(f" Concepts: {result['execution_concepts']}")
6161
print(
6262
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):
133133
result5 = analyze_with_v2(code5, "fetch_validate_and_save")
134134
print_analysis(result5)
135135

136-
print(f"\n{'='*70}")
136+
print("\n" + "=" * 70)
137137
print("DEMONSTRATION COMPLETE")
138138
print("=" * 70)
139139
print("\n✅ Enhanced Parser V2 Features:")

examples/realistic_code_samples.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
Demonstrates real-world functions with proper LJPW semantic mapping.
44
"""
55

6+
from datetime import datetime
7+
68
# ============================================================================
79
# HARMONIOUS FUNCTIONS (Intent matches Execution)
810
# ============================================================================
@@ -52,7 +54,7 @@ def send_welcome_email(user_email):
5254
EXECUTION: LOVE (email.send = communication operation)
5355
Expected harmony: EXCELLENT (~0.05)
5456
"""
55-
message = f"Welcome to our platform!"
57+
message = "Welcome to our platform!"
5658
email_service.send(to=user_email, body=message)
5759

5860

harmonizer/ljpw_baselines.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -372,7 +372,7 @@ def check_proportions(
372372
"summary": (
373373
"Proportions match Natural Equilibrium (scale-invariant)"
374374
if all_pass
375-
else f"Proportions deviate from Natural Equilibrium"
375+
else "Proportions deviate from Natural Equilibrium"
376376
),
377377
}
378378

harmonizer/relationship_analyzer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
regardless of absolute magnitudes.
1010
"""
1111

12-
from typing import Dict, Tuple, List
12+
from typing import Dict, List
1313
import math
1414
from harmonizer.ljpw_baselines import NumericalEquivalents, ReferencePoints
1515

scripts/run_validation.py

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,18 @@
1010
import sys
1111
import os
1212
import glob
13-
import numpy as np
1413
from statistics import mean
1514

16-
# Add project root to path
17-
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
18-
sys.path.append(project_root)
1915

20-
from harmonizer.main import PythonCodeHarmonizer
21-
from harmonizer.ljpw_baselines import DynamicLJPWv4, LJPWBaselines
22-
from harmonizer.dependency_engine import DependencyEngine
23-
from harmonizer.visualizer import HarmonizerVisualizer
16+
def _ensure_project_root_on_path() -> str:
17+
"""Add the repository root to sys.path when running as a script."""
18+
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
19+
if project_root not in sys.path:
20+
sys.path.insert(0, project_root)
21+
return project_root
2422

2523

26-
def analyze_and_simulate(file_path, harmonizer):
24+
def analyze_and_simulate(file_path, harmonizer, simulator_cls):
2725
print(f"\nAnalyzing: {os.path.basename(file_path)}")
2826
print("-" * 40)
2927

@@ -58,7 +56,7 @@ def analyze_and_simulate(file_path, harmonizer):
5856
avg_p = mean([c[2] for c in all_coords])
5957
avg_w = mean([c[3] for c in all_coords])
6058

61-
print(f" Static Metrics (Avg):")
59+
print(" Static Metrics (Avg):")
6260
print(f" L: {avg_l:.2f} | J: {avg_j:.2f} | P: {avg_p:.2f} | W: {avg_w:.2f}")
6361

6462
# 2. Dynamic Simulation
@@ -67,7 +65,7 @@ def analyze_and_simulate(file_path, harmonizer):
6765
complexity_score = 1.0 + (function_count * 0.2)
6866
print(f" Complexity Score: {complexity_score:.2f}")
6967

70-
simulator = DynamicLJPWv4(complexity_score=complexity_score)
68+
simulator = simulator_cls(complexity_score=complexity_score)
7169

7270
print(" Running Dynamic Simulation (50 steps)...")
7371
initial_state = (avg_l, avg_j, avg_p, avg_w)
@@ -78,7 +76,7 @@ def analyze_and_simulate(file_path, harmonizer):
7876
final_p = history["P"][-1]
7977
final_w = history["W"][-1]
8078

81-
print(f" Final State:")
79+
print(" Final State:")
8280
print(f" L: {final_l:.2f} | J: {final_j:.2f} | P: {final_p:.2f} | W: {final_w:.2f}")
8381

8482
# Assessment
@@ -101,6 +99,13 @@ def analyze_and_simulate(file_path, harmonizer):
10199

102100

103101
def run_validation():
102+
project_root = _ensure_project_root_on_path()
103+
104+
from harmonizer.main import PythonCodeHarmonizer
105+
from harmonizer.ljpw_baselines import DynamicLJPWv4
106+
from harmonizer.dependency_engine import DependencyEngine
107+
from harmonizer.visualizer import HarmonizerVisualizer
108+
104109
harmonizer = PythonCodeHarmonizer(quiet=True)
105110

106111
test_dir = os.path.join(project_root, "tests", "user_validation")
@@ -112,10 +117,6 @@ def run_validation():
112117
print("LJPW v4.0 Validation Run (Visual Analytics)")
113118
print("=" * 60)
114119

115-
# 3. Visual Analytics Integration
116-
from harmonizer.dependency_engine import DependencyEngine
117-
from harmonizer.visualizer import HarmonizerVisualizer
118-
119120
simple_files = glob.glob(os.path.join(test_dir, "simple_*.py"))
120121
complex_files = glob.glob(os.path.join(test_dir, "complex_*.py"))
121122
all_files = simple_files + complex_files
@@ -129,7 +130,7 @@ def run_validation():
129130

130131
print("\n--- ANALYZING FILES ---")
131132
for f in all_files:
132-
analysis_data = analyze_and_simulate(f, harmonizer)
133+
analysis_data = analyze_and_simulate(f, harmonizer, DynamicLJPWv4)
133134
if analysis_data:
134135
results[f] = analysis_data
135136

scripts/validate_relationship_hypothesis.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
import math
1616
import numpy as np
17-
from scipy.optimize import curve_fit, minimize
17+
from scipy.optimize import curve_fit
1818
import matplotlib.pyplot as plt
1919
from typing import Dict, Tuple, List
2020

@@ -207,9 +207,10 @@ def analyze_diagonal_vs_offdiagonal(ratios, couplings, labels):
207207
print()
208208

209209
print("DIAGONAL ELEMENTS (self-coupling):")
210-
for i, label in enumerate([l for l, d in zip(labels, diagonal_mask) if d]):
210+
diagonal_labels = [label for label, is_diagonal in zip(labels, diagonal_mask) if is_diagonal]
211+
for i, label in enumerate(diagonal_labels):
211212
print(f" {label}: ratio={diag_ratios[i]:.4f}, κ={diag_couplings[i]:.4f}")
212-
print(f" All diagonal couplings = 1.0 (by definition)")
213+
print(" All diagonal couplings = 1.0 (by definition)")
213214
print()
214215

215216
print("OFF-DIAGONAL ELEMENTS (cross-coupling):")
@@ -235,7 +236,7 @@ def find_special_patterns(ratios, couplings, labels):
235236
mask = [label[0] == source for label in labels]
236237
source_ratios = ratios[mask]
237238
source_couplings = couplings[mask]
238-
source_labels = [l for l, m in zip(labels, mask) if m]
239+
source_labels = [label for label, include in zip(labels, mask) if include]
239240

240241
print(f"Source: {source} (outgoing influence)")
241242
for i, label in enumerate(source_labels):
@@ -325,7 +326,7 @@ def visualize_results(ratios, couplings, labels, results):
325326

326327
plt.tight_layout()
327328
plt.savefig("/workspace/coupling_ratio_analysis.png", dpi=150, bbox_inches="tight")
328-
print(f"\n✓ Visualization saved to: /workspace/coupling_ratio_analysis.png")
329+
print("\n✓ Visualization saved to: /workspace/coupling_ratio_analysis.png")
329330
plt.close()
330331

331332

scripts/verify_tech_debt.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import os
2-
import sys
32
from harmonizer.legacy_mapper import LegacyCodeMapper
43

54

@@ -50,7 +49,7 @@ def verify_tech_debt():
5049
# Run Debt Projection
5150
projection = mapper.project_debt_trajectory(file_path, months=6)
5251
if "error" not in projection:
53-
print(f" Future Debt Projection (6 months):")
52+
print(" Future Debt Projection (6 months):")
5453
print(f" Status: {projection['status']}")
5554
print(f" Risk Level: {projection['risk_level']}")
5655
print(f" Drift: {projection['drift']:.4f}")

tests/test_enhanced_parser.py

Lines changed: 5 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,6 @@ def test_wisdom_operations():
3232
parser = AST_Semantic_Parser_V2(engine.vocabulary.all_keywords)
3333

3434
for code, func_name in code_samples:
35-
tree = ast.parse(code)
36-
func_node = tree.body[0]
37-
3835
# Get intent from name
3936
intent_concepts = parser.get_intent_concepts(func_name, None)
4037

@@ -43,7 +40,7 @@ def test_wisdom_operations():
4340

4441
# Verify WISDOM is in intent
4542
assert "wisdom" in intent_concepts, f"WISDOM should be in intent for {func_name}"
46-
print(f" ✓ WISDOM detected in intent")
43+
print(" ✓ WISDOM detected in intent")
4744

4845
print("\n✓ All WISDOM operations validated")
4946

@@ -77,9 +74,6 @@ def test_justice_operations():
7774
parser = AST_Semantic_Parser_V2(engine.vocabulary.all_keywords)
7875

7976
for code, func_name in code_samples:
80-
tree = ast.parse(code)
81-
func_node = tree.body[0]
82-
8377
# Get intent from name
8478
intent_concepts = parser.get_intent_concepts(func_name, None)
8579

@@ -88,7 +82,7 @@ def test_justice_operations():
8882

8983
# Verify JUSTICE is in intent
9084
assert "justice" in intent_concepts, f"JUSTICE should be in intent for {func_name}"
91-
print(f" ✓ JUSTICE detected in intent")
85+
print(" ✓ JUSTICE detected in intent")
9286

9387
print("\n✓ All JUSTICE operations validated")
9488

@@ -121,9 +115,6 @@ def test_power_operations():
121115
parser = AST_Semantic_Parser_V2(engine.vocabulary.all_keywords)
122116

123117
for code, func_name in code_samples:
124-
tree = ast.parse(code)
125-
func_node = tree.body[0]
126-
127118
# Get intent from name
128119
intent_concepts = parser.get_intent_concepts(func_name, None)
129120

@@ -132,7 +123,7 @@ def test_power_operations():
132123

133124
# Verify POWER is in intent
134125
assert "power" in intent_concepts, f"POWER should be in intent for {func_name}"
135-
print(f" ✓ POWER detected in intent")
126+
print(" ✓ POWER detected in intent")
136127

137128
print("\n✓ All POWER operations validated")
138129

@@ -164,9 +155,6 @@ def test_love_operations():
164155
parser = AST_Semantic_Parser_V2(engine.vocabulary.all_keywords)
165156

166157
for code, func_name in code_samples:
167-
tree = ast.parse(code)
168-
func_node = tree.body[0]
169-
170158
# Get intent from name
171159
intent_concepts = parser.get_intent_concepts(func_name, None)
172160

@@ -175,7 +163,7 @@ def test_love_operations():
175163

176164
# Verify LOVE is in intent
177165
assert "love" in intent_concepts, f"LOVE should be in intent for {func_name}"
178-
print(f" ✓ LOVE detected in intent")
166+
print(" ✓ LOVE detected in intent")
179167

180168
print("\n✓ All LOVE operations validated")
181169

@@ -229,7 +217,7 @@ def validate_and_save_user(user_data):
229217
assert "power" in exec_concepts, "POWER should be in execution (assignments)"
230218
assert "wisdom" in exec_concepts, "WISDOM should be in execution (return)"
231219

232-
print(f" ✓ Mixed operations correctly detected")
220+
print(" ✓ Mixed operations correctly detected")
233221
print(f" ✓ Intent: {len(intent_concepts)} dimensions")
234222
print(f" ✓ Execution: {len(exec_concepts)} dimensions")
235223

@@ -326,8 +314,6 @@ def test_backward_compatibility():
326314

327315
from harmonizer.ast_semantic_parser import AST_Semantic_Parser
328316

329-
code = "def calculate_total(items):\n return sum(items)"
330-
331317
engine = DivineInvitationSemanticEngine()
332318

333319
# Test with V1 parser

tests/test_harmonizer_enhanced.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,13 @@
99

1010
from harmonizer.ast_semantic_parser_v2 import AST_Semantic_Parser_V2
1111
from harmonizer.divine_invitation_engine_V2 import DivineInvitationSemanticEngine
12-
from harmonizer.semantic_map import SemanticMapGenerator
1312

1413

1514
def analyze_function_with_v2(code: str, function_name: str):
1615
"""Analyze a function using the enhanced V2 parser."""
1716
# Initialize components
1817
engine = DivineInvitationSemanticEngine()
1918
parser = AST_Semantic_Parser_V2(engine.vocabulary.all_keywords)
20-
map_generator = SemanticMapGenerator()
2119

2220
# Parse code
2321
tree = ast.parse(code)
@@ -70,7 +68,7 @@ def print_analysis_report(result):
7068
if result["docstring"]:
7169
print(f"\nDocstring: {result['docstring'][:60]}...")
7270

73-
print(f"\nINTENT (from function name):")
71+
print("\nINTENT (from function name):")
7472
print(f" Concepts: {result['intent_concepts']}")
7573
print(
7674
f" Coordinates: L={result['intent_coords'].love:.3f}, "
@@ -79,7 +77,7 @@ def print_analysis_report(result):
7977
f"W={result['intent_coords'].wisdom:.3f}"
8078
)
8179

82-
print(f"\nEXECUTION (from function body):")
80+
print("\nEXECUTION (from function body):")
8381
print(f" Concepts: {result['exec_concepts']}")
8482
print(
8583
f" Coordinates: L={result['exec_coords'].love:.3f}, "

0 commit comments

Comments
 (0)