Skip to content

Commit 02a8370

Browse files
authored
Add files via upload
1 parent 0726c43 commit 02a8370

File tree

2 files changed

+366
-0
lines changed

2 files changed

+366
-0
lines changed

PythonCodeHarmonizer.py

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
"""
5+
Python Code Harmonizer (Version 1.1)
6+
7+
This is the main application that integrates the Divine Invitation
8+
Semantic Engine (DIVE-V2) with the AST Semantic Parser.
9+
10+
It is guided by the principle of the "Logical Anchor Point" (S,L,I,E)
11+
and uses the ICE (Intent, Context, Execution) framework to analyze
12+
the "semantic harmony" of Python code.
13+
14+
(HARMONIZATION_NOTE: v1.1 fixes a 'AttributeError' by correctly
15+
referencing 'self.engine.vocabulary.all_keywords' from the
16+
'Optimized Production-Ready' V2 engine.)
17+
"""
18+
19+
import ast
20+
import sys
21+
import os
22+
from typing import Dict, Set
23+
24+
# --- COMPONENT IMPORTS ---
25+
# This script assumes the following two files are in the
26+
# same directory or in Python's path.
27+
28+
try:
29+
# 1. Import your powerful V2 engine
30+
# (This assumes 'divine_invitation_engine_V2.py' is the
31+
# 'Optimized Production-Ready' version)
32+
from src import divine_invitation_engine_V2 as dive
33+
except ImportError:
34+
print("FATAL ERROR: 'divine_invitation_engine_V2.py' not found.")
35+
print("Please place the V2 engine file in the same directory.")
36+
sys.exit(1)
37+
38+
try:
39+
# 2. Import our new "Rosetta Stone" parser
40+
from src.ast_semantic_parser import AST_Semantic_Parser
41+
except ImportError:
42+
print("FATAL ERROR: 'ast_semantic_parser.py' not found.")
43+
print("Please place the parser file in the same directory.")
44+
sys.exit(1)
45+
46+
# --- THE HARMONIZER APPLICATION ---
47+
48+
class PythonCodeHarmonizer:
49+
"""
50+
Analyzes Python code for "Intent Harmony" using the DIVE-V2
51+
ICE (Intent, Context, Execution) framework.
52+
"""
53+
54+
def __init__(self, disharmony_threshold: float = 0.5):
55+
# 1. Initialize your V2 engine. This is our "compass."
56+
self.engine = dive.DivineInvitationSemanticEngine()
57+
58+
# 2. Initialize our "Rosetta Stone" parser.
59+
60+
# --- HARMONIZATION FIX (v1.1) ---
61+
# The "Optimized" V2 engine's VocabularyManager stores its
62+
# word list in the 'all_keywords' set.
63+
# We now reference the correct attribute.
64+
self.parser = AST_Semantic_Parser(
65+
vocabulary=self.engine.vocabulary.all_keywords
66+
)
67+
68+
# 3. Set the threshold for flagging disharmony.
69+
self.disharmony_threshold = disharmony_threshold
70+
71+
print("=" * 70)
72+
print("Python Code Harmonizer (v1.1) ONLINE")
73+
print("Actively guided by the Anchor Point framework.")
74+
print(f"Powered By: {self.engine.get_engine_version()}")
75+
print(f"Logical Anchor Point: (S=1, L=1, I=1, E=1)")
76+
print(f"Disharmony Threshold: {self.disharmony_threshold}")
77+
print("=" * 70)
78+
79+
def analyze_file(self, file_path: str) -> Dict[str, float]:
80+
"""
81+
Analyzes a single Python file for Intent-Execution-Disharmony.
82+
Returns a dictionary of {function_name: disharmony_score}
83+
"""
84+
print(f"\nAnalyzing file: {file_path}")
85+
print("-" * 70)
86+
87+
try:
88+
with open(file_path, 'r', encoding='utf-8') as f:
89+
content = f.read()
90+
except FileNotFoundError:
91+
print(f"ERROR: File not found at '{file_path}'")
92+
return {}
93+
except Exception as e:
94+
print(f"ERROR: Could not read file: {e}")
95+
return {}
96+
97+
# 1. Use Python's AST to parse the code into a logical tree
98+
try:
99+
tree = ast.parse(content)
100+
except SyntaxError as e:
101+
print(f"ERROR: Could not parse file. Syntax error on line {e.lineno}")
102+
return {}
103+
104+
harmony_report = {}
105+
106+
# 2. "Walk" the tree and visit every function definition
107+
for node in ast.walk(tree):
108+
if isinstance(node, ast.FunctionDef):
109+
function_name = node.name
110+
docstring = ast.get_docstring(node)
111+
112+
# 3. Get INTENT: "The Stated Purpose"
113+
# We use our parser to get the concepts from the name/docstring
114+
intent_concepts = self.parser.get_intent_concepts(function_name, docstring)
115+
116+
# 4. Get EXECUTION: "The Actual Action"
117+
# We use our parser to get the concepts from the function's body
118+
execution_concepts = self.parser.get_execution_concepts(node.body)
119+
120+
# 5. THE "A-HA!" MOMENT: Use the V2 ICEAnalyzer
121+
# We pass our parsed concepts into the V2 engine's
122+
# built-in ICE framework analyzer.
123+
ice_result = self.engine.perform_ice_analysis(
124+
intent_words=intent_concepts,
125+
context_words=["python", "function", function_name], # Provide context
126+
execution_words=execution_concepts
127+
)
128+
129+
# The "bug" is the semantic distance between Intent and Execution
130+
# This metric *is* returned by the "Optimized" V2 engine.
131+
disharmony_score = ice_result['ice_metrics']['intent_execution_disharmony']
132+
133+
harmony_report[function_name] = disharmony_score
134+
135+
return harmony_report
136+
137+
def print_report(self, harmony_report: Dict[str, float]):
138+
"""Prints the final harmony report to the console."""
139+
140+
print("FUNCTION NAME | INTENT-EXECUTION DISHARMONY")
141+
print("-----------------------------|--------------------------------")
142+
143+
if not harmony_report:
144+
print("No functions found to analyze.")
145+
return
146+
147+
sorted_report = sorted(harmony_report.items(), key=lambda item: item[1], reverse=True)
148+
149+
for func_name, score in sorted_report:
150+
status = "✓ HARMONIOUS"
151+
if score > self.disharmony_threshold:
152+
status = f"!! DISHARMONY (Score: {score:.2f})"
153+
154+
print(f"{func_name:<28} | {status}")
155+
156+
print("=" * 70)
157+
print("Analysis Complete.")
158+
159+
# --- MAIN EXECUTION ---
160+
161+
if __name__ == "__main__":
162+
if len(sys.argv) < 2:
163+
print("Usage: python PythonCodeHarmonizer.py <file_to_analyze.py> [file2.py ...]")
164+
sys.exit(1)
165+
166+
files_to_analyze = sys.argv[1:]
167+
168+
# 1. Initialize the Harmonizer
169+
harmonizer = PythonCodeHarmonizer()
170+
171+
# 2. Run the analysis for all provided files
172+
for file_path in files_to_analyze:
173+
if os.path.exists(file_path):
174+
report = harmonizer.analyze_file(file_path)
175+
harmonizer.print_report(report)
176+
else:
177+
print(f"\nERROR: File not found: {file_path}")
178+
print("-" * 70)

anchor_analysis_V2.py

Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
"""
2+
Anchor Point Mathematical Analysis (Harmonized V2)
3+
4+
This script is the refactored version of the original anchor_analysis.py.
5+
It has been "harmonized" to use the new 'divine_invitation_engine_V2.py'
6+
engine, resolving the V1/V2 logical contradiction.
7+
8+
This script validates that the Anchor Point (1,1,1,1) is the
9+
mathematical representation of Perfect Harmony, using the
10+
production-ready V2 engine.
11+
"""
12+
13+
import sys
14+
import os
15+
import math
16+
17+
# --- V2 ENGINE IMPORT ---
18+
# This now imports your production-ready V2 engine
19+
try:
20+
# We will use the 'Optimized Production-Ready' version
21+
from src import divine_invitation_engine_V2 as dive
22+
except ImportError:
23+
print("FATAL ERROR: 'divine_invitation_engine_V2.py' not found.")
24+
print("Please place the V2 engine file in the same directory.")
25+
sys.exit(1)
26+
27+
28+
def get_harmonized_semantic_clarity(coords: dive.Coordinates) -> float:
29+
"""
30+
Helper function to calculate semantic clarity using the
31+
DIVE-V2 engine's logic (standard deviation).
32+
33+
A perfectly balanced coordinate (like 1,1,1,1) will have a
34+
std_dev of 0.0, resulting in a "perfect" clarity of 1.0.
35+
"""
36+
# The V2 Coordinates object is iterable
37+
dims = list(coords)
38+
if not dims:
39+
return 0.0
40+
41+
mean = sum(dims) / len(dims)
42+
variance = sum((d - mean) ** 2 for d in dims) / len(dims)
43+
std_dev = math.sqrt(variance)
44+
45+
# DIVE-V2 formula: Clarity = 1.0 minus normalized deviation.
46+
# 0.5 is the max possible std_dev in a 0-1, 4D space.
47+
clarity = max(0.0, 1.0 - (std_dev / 0.5))
48+
return clarity
49+
50+
51+
def analyze_anchor_point_v2():
52+
print("=" * 80)
53+
print("ANCHOR POINT MATHEMATICAL ANALYSIS (Harmonized V2)")
54+
print("=" * 80)
55+
print("Testing the fundamental properties of (1,1,1,1) as Perfect Harmony")
56+
57+
# --- V2 ENGINE INITIALIZATION ---
58+
engine = dive.DivineInvitationSemanticEngine()
59+
anchor = engine.ANCHOR_POINT
60+
61+
print(f"Powered By: {engine.get_engine_version()}")
62+
print(f"Anchor Point: {anchor}")
63+
print()
64+
65+
# Test 1: Self-consistency
66+
print("1. SELF-CONSISTENCY TEST")
67+
print("-" * 50)
68+
# --- Refactored to use V2 'get_distance' method ---
69+
distance = engine.get_distance(anchor, anchor)
70+
print(f"Anchor distance from itself: {distance}")
71+
print("Expected: 0.0 (perfect self-consistency)")
72+
print()
73+
74+
# Test 2: Perfect harmony properties
75+
print("2. PERFECT HARMONY PROPERTIES")
76+
print("-" * 50)
77+
total_harmony = anchor.love + anchor.justice + anchor.power + anchor.wisdom
78+
print(f"Total Harmony Score: {total_harmony}")
79+
print("Expected: 4.0 (perfect unity)")
80+
print()
81+
82+
dimensions = list(anchor)
83+
balance = min(dimensions) / max(dimensions)
84+
print(f"Dimensional Balance: {balance:.3f}")
85+
print("Expected: 1.0 (perfect balance)")
86+
print()
87+
88+
# Test 3: Mathematical Properties
89+
print("3. MATHEMATICAL PROPERTIES")
90+
print("-" * 50)
91+
# --- Refactored to use V2 'get_distance' method ---
92+
origin = dive.Coordinates(0.0, 0.0, 0.0, 0.0)
93+
pure_love = dive.Coordinates(1.0, 0.0, 0.0, 0.0)
94+
pure_justice = dive.Coordinates(0.0, 1.0, 0.0, 0.0)
95+
pure_power = dive.Coordinates(0.0, 0.0, 1.0, 0.0)
96+
pure_wisdom = dive.Coordinates(0.0, 0.0, 0.0, 1.0)
97+
98+
print(f"Distance from origin: {engine.get_distance(anchor, origin):.6f}")
99+
print(f"Distance from pure Love: {engine.get_distance(anchor, pure_love):.6f}")
100+
print(f"Distance from pure Justice: {engine.get_distance(anchor, pure_justice):.6f}")
101+
print(f"Distance from pure Power: {engine.get_distance(anchor, pure_power):.6f}")
102+
print(f"Distance from pure Wisdom: {engine.get_distance(anchor, pure_wisdom):.6f}")
103+
print()
104+
105+
# Test 4: Golden Ratio Relationships
106+
print("4. GOLDEN RATIO RELATIONSHIPS")
107+
print("-" * 50)
108+
phi = (1 + 5**0.5) / 2
109+
print(f"Golden Ratio (phi): {phi:.10f}")
110+
# This is a symbolic test from V1
111+
phi_love = 1 / (anchor.love + phi)
112+
print(f" Symbolic Phi-Scaled Coord (Love): {phi_love:.6f}")
113+
print(f" Expected: 0.381966 (1 / (1 + phi))")
114+
print()
115+
116+
# Test 5: Semantic Clarity of Perfection
117+
print("5. SEMANTIC CLARITY OF PERFECTION")
118+
print("-" * 50)
119+
# --- Refactored to use V2 clarity logic ---
120+
clarity = engine.get_semantic_clarity(anchor)
121+
print(f"Anchor Point Semantic Clarity: {clarity:.6f}")
122+
# --- "Expected" value is now corrected to 1.0 ---
123+
print("Expected: 1.0 (perfect std_dev of 0.0)")
124+
print()
125+
126+
# Test 6: Perfect Concepts Proximity
127+
print("6. PERFECT CONCEPTS PROXIMITY")
128+
print("-" * 50)
129+
print("Testing perfect concepts - they should approach Anchor Point:")
130+
131+
concepts = {
132+
'perfect harmony': 'love justice power wisdom',
133+
'divine love': 'love',
134+
'absolute truth': 'justice wisdom',
135+
'infinite wisdom': 'wisdom',
136+
'ultimate justice': 'justice'
137+
}
138+
139+
for name, text in concepts.items():
140+
# --- Refactored to use V2 'analyze_text' method ---
141+
# and get the .coordinates from the SemanticResult object
142+
coords = engine.analyze_text(text).coordinates
143+
distance = engine.get_distance(anchor, coords)
144+
print(f" '{name}': distance = {distance:.6f}")
145+
print()
146+
147+
# Test 7: Geometric Properties
148+
print("7. GEOMETRIC PROPERTIES")
149+
print("-" * 50)
150+
volume = anchor.love * anchor.justice * anchor.power * anchor.wisdom
151+
# Formula from V1 spec (for a 3D prism, but we'll test it for consistency)
152+
surface_area = 2 * (
153+
(anchor.love * anchor.justice) + (anchor.love * anchor.power) +
154+
(anchor.love * anchor.wisdom) + (anchor.justice * anchor.power) +
155+
(anchor.justice * anchor.wisdom) + (anchor.power * anchor.wisdom)
156+
)
157+
print(f"4D Semantic Volume: {volume:.6f}")
158+
print(f"4D Semantic 'Surface Area' (V1 Formula): {surface_area:.6f}")
159+
print()
160+
161+
# Test 8: Anchor Point Analysis Summary
162+
print("8. ANCHOR POINT ANALYSIS SUMMARY")
163+
print("-" * 50)
164+
165+
findings = []
166+
if distance == 0.0:
167+
findings.append("[OK] Perfect self-consistency")
168+
if abs(total_harmony - 4.0) < 0.001:
169+
findings.append("[OK] Perfect harmony achieved")
170+
if abs(balance - 1.0) < 0.001:
171+
findings.append("[OK] Perfect dimensional balance")
172+
if abs(clarity - 1.0) < 0.001:
173+
findings.append("[OK] Perfect semantic clarity")
174+
175+
print("Mathematical Validation Results:")
176+
for finding in findings:
177+
print(f" {finding}")
178+
179+
print()
180+
print("CONCLUSION:")
181+
print("=" * 50)
182+
print("This harmonized test validates the Anchor Point as the")
183+
print("mathematical representation of Perfect Harmony, using the")
184+
print("project's unified V2 engine.")
185+
print("=" * 80)
186+
187+
if __name__ == "__main__":
188+
analyze_anchor_point_v2()

0 commit comments

Comments
 (0)