From 655d7405c4014248fb26354f5f46b42238409abf Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 22 Nov 2025 20:52:00 +0000 Subject: [PATCH] style: Fix Black formatting issues in 7 files --- check_harmony.py | 19 +- harmonizer/ljpw_baselines.py | 113 +++--- harmonizer/relationship_analyzer.py | 376 ++++++++++---------- scripts/anchor_analysis_V2.py | 4 +- scripts/run_validation.py | 8 +- scripts/validate_relationship_hypothesis.py | 248 +++++++------ scripts/verify_tech_debt.py | 8 +- 7 files changed, 396 insertions(+), 380 deletions(-) diff --git a/check_harmony.py b/check_harmony.py index 6249473..ee9aed2 100644 --- a/check_harmony.py +++ b/check_harmony.py @@ -10,24 +10,23 @@ from harmonizer.legacy_mapper import LegacyCodeMapper -def check_harmony( - target_dir: str = ".", config_path: str = None, verbose: bool = False -): +def check_harmony(target_dir: str = ".", config_path: str = None, verbose: bool = False): print(f"Running LJPW Harmony Check on: {os.path.abspath(target_dir)}") print("=" * 60) # If analyzing a subdirectory, find project root for config # Otherwise use target_dir project_root = os.getcwd() if target_dir != "." else target_dir - + # Create mapper - it will load config from project_root mapper = LegacyCodeMapper(target_dir, quiet=not verbose) - + # If we're in project root, use config from there if os.path.exists(os.path.join(project_root, "pyproject.toml")): from harmonizer.config import ConfigLoader + mapper.config = ConfigLoader.load(project_root) - + mapper.analyze_codebase(show_progress=True) failures = [] @@ -81,13 +80,9 @@ def check_harmony( def main(): parser = argparse.ArgumentParser(description="LJPW Harmony Check") - parser.add_argument( - "target", nargs="?", default=".", help="Target directory to analyze" - ) + parser.add_argument("target", nargs="?", default=".", help="Target directory to analyze") parser.add_argument("--config", help="Path to configuration file (optional)") - parser.add_argument( - "-v", "--verbose", action="store_true", help="Enable verbose output" - ) + parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output") args = parser.parse_args() diff --git a/harmonizer/ljpw_baselines.py b/harmonizer/ljpw_baselines.py index c1c23fe..0309126 100644 --- a/harmonizer/ljpw_baselines.py +++ b/harmonizer/ljpw_baselines.py @@ -271,118 +271,109 @@ def interpret_composite_score(score: float) -> str: return "Excellent - high-performing, growth active" else: return "Elite - exceptional, Love multiplier engaged" - + @staticmethod def validate_coupling_structure() -> Dict[str, bool]: """ Validate that the coupling matrix exhibits expected relationship patterns. - + This validates the "grammar of semantic interaction": - Love amplifies (κ_L→* > 1) - Power constrains (κ_P→* < 1) - Justice supports Wisdom (κ_JW > κ_JP) - Asymmetry is present (κ_ij ≠ κ_ji) - + Returns: Dict with validation results for each pattern """ cm = LJPWBaselines.COUPLING_MATRIX - + # Check Love amplifies - love_amplifies = ( - cm['LJ'] > 1.0 and - cm['LP'] > 1.0 and - cm['LW'] > 1.0 - ) - + love_amplifies = cm["LJ"] > 1.0 and cm["LP"] > 1.0 and cm["LW"] > 1.0 + # Check Power constrains - power_constrains = ( - cm['PL'] < 1.0 and - cm['PJ'] < 1.0 and - cm['PW'] < 1.0 - ) - + power_constrains = cm["PL"] < 1.0 and cm["PJ"] < 1.0 and cm["PW"] < 1.0 + # Check Justice supports Wisdom more than Power - justice_wisdom = cm['JW'] > cm['JP'] - + justice_wisdom = cm["JW"] > cm["JP"] + # Check asymmetry (giving ≠ receiving) asymmetry = ( - abs(cm['LJ'] - cm['JL']) > 0.1 and - abs(cm['LP'] - cm['PL']) > 0.1 and - abs(cm['PJ'] - cm['JP']) > 0.1 + abs(cm["LJ"] - cm["JL"]) > 0.1 + and abs(cm["LP"] - cm["PL"]) > 0.1 + and abs(cm["PJ"] - cm["JP"]) > 0.1 ) - + return { - 'love_amplifies': love_amplifies, - 'power_constrains': power_constrains, - 'justice_supports_wisdom': justice_wisdom, - 'asymmetry_present': asymmetry, - 'all_patterns_valid': all([ - love_amplifies, - power_constrains, - justice_wisdom, - asymmetry - ]) + "love_amplifies": love_amplifies, + "power_constrains": power_constrains, + "justice_supports_wisdom": justice_wisdom, + "asymmetry_present": asymmetry, + "all_patterns_valid": all( + [love_amplifies, power_constrains, justice_wisdom, asymmetry] + ), } - + @staticmethod - def check_proportions(L: float, J: float, P: float, W: float, tolerance: float = 0.3) -> Dict[str, any]: + def check_proportions( + L: float, J: float, P: float, W: float, tolerance: float = 0.3 + ) -> Dict[str, any]: """ Check if L:J:P:W proportions match Natural Equilibrium (scale-invariant check). - + This validates the core insight: "relationships between constants matter more than the constants themselves." The same proportions define harmony at any scale. - + Args: L, J, P, W: Current dimension values (any scale) tolerance: Allowed deviation from ideal ratios (default 0.3 = 30%) - + Returns: Dict with proportion analysis """ NE = ReferencePoints.NATURAL_EQUILIBRIUM - + # Calculate current ratios (scale-invariant) if J <= 0: - return { - 'proportions_healthy': False, - 'error': 'Justice dimension cannot be zero' - } - + return {"proportions_healthy": False, "error": "Justice dimension cannot be zero"} + current_ratios = { - 'L/J': L / J, - 'P/J': P / J, - 'W/J': W / J, + "L/J": L / J, + "P/J": P / J, + "W/J": W / J, } - + # Expected ratios from Natural Equilibrium expected_ratios = { - 'L/J': NE[0] / NE[1], # 1.492 - 'P/J': NE[2] / NE[1], # 1.734 - 'W/J': NE[3] / NE[1], # 1.673 + "L/J": NE[0] / NE[1], # 1.492 + "P/J": NE[2] / NE[1], # 1.734 + "W/J": NE[3] / NE[1], # 1.673 } - + # Check deviations deviations = {} checks = {} - + for key in expected_ratios: expected = expected_ratios[key] actual = current_ratios[key] deviation = abs(actual - expected) / expected deviations[key] = deviation checks[key] = deviation < tolerance - + all_pass = all(checks.values()) - + return { - 'proportions_healthy': all_pass, - 'current_ratios': current_ratios, - 'expected_ratios': expected_ratios, - 'deviations': deviations, - 'checks': checks, - 'summary': 'Proportions match Natural Equilibrium (scale-invariant)' if all_pass - else f'Proportions deviate from Natural Equilibrium' + "proportions_healthy": all_pass, + "current_ratios": current_ratios, + "expected_ratios": expected_ratios, + "deviations": deviations, + "checks": checks, + "summary": ( + "Proportions match Natural Equilibrium (scale-invariant)" + if all_pass + else f"Proportions deviate from Natural Equilibrium" + ), } diff --git a/harmonizer/relationship_analyzer.py b/harmonizer/relationship_analyzer.py index 9d23519..4cd3861 100644 --- a/harmonizer/relationship_analyzer.py +++ b/harmonizer/relationship_analyzer.py @@ -16,274 +16,279 @@ class RelationshipPatterns: """Expected patterns in LJPW coupling structure""" - + # Qualitative expectations for coupling LOVE_AMPLIFIES = { - 'LJ': (1.2, 1.6), # Should be > 1.0 (amplification) - 'LP': (1.1, 1.5), - 'LW': (1.3, 1.7), + "LJ": (1.2, 1.6), # Should be > 1.0 (amplification) + "LP": (1.1, 1.5), + "LW": (1.3, 1.7), } - + POWER_CONSTRAINS = { - 'PL': (0.4, 0.8), # Should be < 1.0 (constraint) - 'PJ': (0.6, 1.0), - 'PW': (0.3, 0.7), + "PL": (0.4, 0.8), # Should be < 1.0 (constraint) + "PJ": (0.6, 1.0), + "PW": (0.3, 0.7), } - + JUSTICE_SUPPORTS_WISDOM = { - 'JW': (1.0, 1.4), # J→W should be strong - 'JP': (0.5, 0.9), # J→P should be weaker than J→W + "JW": (1.0, 1.4), # J→W should be strong + "JP": (0.5, 0.9), # J→P should be weaker than J→W } - + ASYMMETRY_PATTERNS = [ - ('LJ', 'JL', 'Love gives more to Justice than receives'), - ('LP', 'PL', 'Love gives more to Power than receives'), - ('LW', 'WL', 'Love and Wisdom are nearly symmetric'), - ('PJ', 'JP', 'Power receives more from Justice than gives'), + ("LJ", "JL", "Love gives more to Justice than receives"), + ("LP", "PL", "Love gives more to Power than receives"), + ("LW", "WL", "Love and Wisdom are nearly symmetric"), + ("PJ", "JP", "Power receives more from Justice than gives"), ] class RelationshipAnalyzer: """ Analyzes whether a system exhibits healthy LJPW relationship patterns. - + This focuses on structural properties (coupling patterns) rather than exact numerical values of constants. """ - + def __init__(self): self.NE = ReferencePoints.NATURAL_EQUILIBRIUM self.constants = { - 'L': NumericalEquivalents.L, - 'J': NumericalEquivalents.J, - 'P': NumericalEquivalents.P, - 'W': NumericalEquivalents.W, + "L": NumericalEquivalents.L, + "J": NumericalEquivalents.J, + "P": NumericalEquivalents.P, + "W": NumericalEquivalents.W, } - + def check_proportions( - self, - L: float, - J: float, - P: float, - W: float, - tolerance: float = 0.3 + self, L: float, J: float, P: float, W: float, tolerance: float = 0.3 ) -> Dict[str, any]: """ Check if L:J:P:W proportions match Natural Equilibrium (scale-invariant). - + Args: L, J, P, W: Current values tolerance: Allowed deviation from ideal ratios (default 0.3 = 30%) - + Returns: Dict with proportions analysis """ # Calculate current ratios current_ratios = { - 'L/J': L / J if J > 0 else float('inf'), - 'P/J': P / J if J > 0 else float('inf'), - 'W/J': W / J if J > 0 else float('inf'), - 'L/P': L / P if P > 0 else float('inf'), - 'L/W': L / W if W > 0 else float('inf'), - 'W/P': W / P if P > 0 else float('inf'), + "L/J": L / J if J > 0 else float("inf"), + "P/J": P / J if J > 0 else float("inf"), + "W/J": W / J if J > 0 else float("inf"), + "L/P": L / P if P > 0 else float("inf"), + "L/W": L / W if W > 0 else float("inf"), + "W/P": W / P if P > 0 else float("inf"), } - + # Expected ratios from Natural Equilibrium expected_ratios = { - 'L/J': self.NE[0] / self.NE[1], # 1.492 - 'P/J': self.NE[2] / self.NE[1], # 1.734 - 'W/J': self.NE[3] / self.NE[1], # 1.673 - 'L/P': self.NE[0] / self.NE[2], # 0.860 - 'L/W': self.NE[0] / self.NE[3], # 0.892 - 'W/P': self.NE[3] / self.NE[2], # 0.965 + "L/J": self.NE[0] / self.NE[1], # 1.492 + "P/J": self.NE[2] / self.NE[1], # 1.734 + "W/J": self.NE[3] / self.NE[1], # 1.673 + "L/P": self.NE[0] / self.NE[2], # 0.860 + "L/W": self.NE[0] / self.NE[3], # 0.892 + "W/P": self.NE[3] / self.NE[2], # 0.965 } - + # Check deviations deviations = {} checks = {} - + for key in expected_ratios: expected = expected_ratios[key] actual = current_ratios[key] - + if math.isfinite(actual): deviation = abs(actual - expected) / expected deviations[key] = deviation checks[key] = deviation < tolerance else: - deviations[key] = float('inf') + deviations[key] = float("inf") checks[key] = False - + all_pass = all(checks.values()) - + return { - 'proportions_healthy': all_pass, - 'current_ratios': current_ratios, - 'expected_ratios': expected_ratios, - 'deviations': deviations, - 'checks': checks, - 'summary': 'Healthy proportions (scale-invariant)' if all_pass else 'Proportions deviate from Natural Equilibrium' + "proportions_healthy": all_pass, + "current_ratios": current_ratios, + "expected_ratios": expected_ratios, + "deviations": deviations, + "checks": checks, + "summary": ( + "Healthy proportions (scale-invariant)" + if all_pass + else "Proportions deviate from Natural Equilibrium" + ), } - - def check_coupling_character( - self, - coupling_matrix: Dict[str, float] - ) -> Dict[str, any]: + + def check_coupling_character(self, coupling_matrix: Dict[str, float]) -> Dict[str, any]: """ Check if coupling matrix exhibits expected qualitative patterns. - + Args: coupling_matrix: Dict mapping 'XY' to coupling coefficient κ_XY - + Returns: Dict with pattern analysis """ checks = {} - + # Check 1: Love amplifies love_amplifies = {} for key, (min_val, max_val) in RelationshipPatterns.LOVE_AMPLIFIES.items(): if key in coupling_matrix: κ = coupling_matrix[key] love_amplifies[key] = { - 'value': κ, - 'expected_range': (min_val, max_val), - 'healthy': min_val <= κ <= max_val, - 'character': 'amplifies' if κ > 1.0 else 'diminishes' + "value": κ, + "expected_range": (min_val, max_val), + "healthy": min_val <= κ <= max_val, + "character": "amplifies" if κ > 1.0 else "diminishes", } - - checks['love_amplifies'] = { - 'pattern': 'Love should amplify other dimensions (κ > 1)', - 'results': love_amplifies, - 'pass': all(v['healthy'] for v in love_amplifies.values()) + + checks["love_amplifies"] = { + "pattern": "Love should amplify other dimensions (κ > 1)", + "results": love_amplifies, + "pass": all(v["healthy"] for v in love_amplifies.values()), } - + # Check 2: Power constrains power_constrains = {} for key, (min_val, max_val) in RelationshipPatterns.POWER_CONSTRAINS.items(): if key in coupling_matrix: κ = coupling_matrix[key] power_constrains[key] = { - 'value': κ, - 'expected_range': (min_val, max_val), - 'healthy': min_val <= κ <= max_val, - 'character': 'constrained' if κ < 1.0 else 'amplifies' + "value": κ, + "expected_range": (min_val, max_val), + "healthy": min_val <= κ <= max_val, + "character": "constrained" if κ < 1.0 else "amplifies", } - - checks['power_constrains'] = { - 'pattern': 'Power should be constrained (κ < 1)', - 'results': power_constrains, - 'pass': all(v['healthy'] for v in power_constrains.values()) + + checks["power_constrains"] = { + "pattern": "Power should be constrained (κ < 1)", + "results": power_constrains, + "pass": all(v["healthy"] for v in power_constrains.values()), } - + # Check 3: Justice supports Wisdom more than Power justice_pattern = {} - if 'JW' in coupling_matrix and 'JP' in coupling_matrix: - κ_JW = coupling_matrix['JW'] - κ_JP = coupling_matrix['JP'] + if "JW" in coupling_matrix and "JP" in coupling_matrix: + κ_JW = coupling_matrix["JW"] + κ_JP = coupling_matrix["JP"] justice_pattern = { - 'JW': κ_JW, - 'JP': κ_JP, - 'healthy': κ_JW > κ_JP, - 'interpretation': 'Justice flows more to Wisdom than Power' if κ_JW > κ_JP else 'Justice favors Power over Wisdom (unusual)' + "JW": κ_JW, + "JP": κ_JP, + "healthy": κ_JW > κ_JP, + "interpretation": ( + "Justice flows more to Wisdom than Power" + if κ_JW > κ_JP + else "Justice favors Power over Wisdom (unusual)" + ), } - - checks['justice_supports_wisdom'] = { - 'pattern': 'Justice should support Wisdom more than Power (κ_JW > κ_JP)', - 'results': justice_pattern, - 'pass': justice_pattern.get('healthy', False) + + checks["justice_supports_wisdom"] = { + "pattern": "Justice should support Wisdom more than Power (κ_JW > κ_JP)", + "results": justice_pattern, + "pass": justice_pattern.get("healthy", False), } - + return checks - - def check_asymmetry( - self, - coupling_matrix: Dict[str, float] - ) -> Dict[str, any]: + + def check_asymmetry(self, coupling_matrix: Dict[str, float]) -> Dict[str, any]: """ Check if coupling matrix exhibits proper asymmetry. - + Args: coupling_matrix: Dict mapping 'XY' to coupling coefficient κ_XY - + Returns: Dict with asymmetry analysis """ asymmetries = [] - + for forward, reverse, description in RelationshipPatterns.ASYMMETRY_PATTERNS: if forward in coupling_matrix and reverse in coupling_matrix: κ_forward = coupling_matrix[forward] κ_reverse = coupling_matrix[reverse] - - asymmetries.append({ - 'forward': forward, - 'reverse': reverse, - 'κ_forward': κ_forward, - 'κ_reverse': κ_reverse, - 'asymmetry_ratio': κ_forward / κ_reverse if κ_reverse > 0 else float('inf'), - 'is_asymmetric': abs(κ_forward - κ_reverse) > 0.1, - 'description': description - }) - + + asymmetries.append( + { + "forward": forward, + "reverse": reverse, + "κ_forward": κ_forward, + "κ_reverse": κ_reverse, + "asymmetry_ratio": κ_forward / κ_reverse if κ_reverse > 0 else float("inf"), + "is_asymmetric": abs(κ_forward - κ_reverse) > 0.1, + "description": description, + } + ) + # Asymmetry is healthy - symmetric coupling would be unusual - healthy_asymmetry = sum(1 for a in asymmetries if a['is_asymmetric']) >= len(asymmetries) * 0.75 - + healthy_asymmetry = ( + sum(1 for a in asymmetries if a["is_asymmetric"]) >= len(asymmetries) * 0.75 + ) + return { - 'asymmetry_healthy': healthy_asymmetry, - 'patterns': asymmetries, - 'summary': 'Healthy asymmetric coupling' if healthy_asymmetry else 'Warning: Coupling too symmetric' + "asymmetry_healthy": healthy_asymmetry, + "patterns": asymmetries, + "summary": ( + "Healthy asymmetric coupling" + if healthy_asymmetry + else "Warning: Coupling too symmetric" + ), } - + def full_relationship_diagnostic( - self, - L: float, - J: float, - P: float, - W: float, - coupling_matrix: Dict[str, float] = None + self, L: float, J: float, P: float, W: float, coupling_matrix: Dict[str, float] = None ) -> Dict[str, any]: """ Complete relationship structure analysis. - + Args: L, J, P, W: Current dimension values coupling_matrix: Optional coupling matrix (uses default if None) - + Returns: Comprehensive diagnostic report """ # Use default coupling if not provided if coupling_matrix is None: from harmonizer.ljpw_baselines import LJPWBaselines + coupling_matrix = LJPWBaselines.COUPLING_MATRIX - + # Run all checks proportions = self.check_proportions(L, J, P, W) coupling_character = self.check_coupling_character(coupling_matrix) asymmetry = self.check_asymmetry(coupling_matrix) - + # Overall health assessment health_scores = { - 'proportions': 1.0 if proportions['proportions_healthy'] else 0.0, - 'love_amplifies': 1.0 if coupling_character['love_amplifies']['pass'] else 0.0, - 'power_constrains': 1.0 if coupling_character['power_constrains']['pass'] else 0.0, - 'justice_supports_wisdom': 1.0 if coupling_character['justice_supports_wisdom']['pass'] else 0.0, - 'asymmetry': 1.0 if asymmetry['asymmetry_healthy'] else 0.0, + "proportions": 1.0 if proportions["proportions_healthy"] else 0.0, + "love_amplifies": 1.0 if coupling_character["love_amplifies"]["pass"] else 0.0, + "power_constrains": 1.0 if coupling_character["power_constrains"]["pass"] else 0.0, + "justice_supports_wisdom": ( + 1.0 if coupling_character["justice_supports_wisdom"]["pass"] else 0.0 + ), + "asymmetry": 1.0 if asymmetry["asymmetry_healthy"] else 0.0, } - + overall_health = sum(health_scores.values()) / len(health_scores) - + return { - 'overall_health': overall_health, - 'health_scores': health_scores, - 'proportions_analysis': proportions, - 'coupling_character_analysis': coupling_character, - 'asymmetry_analysis': asymmetry, - 'interpretation': self._interpret_health(overall_health), - 'recommendations': self._generate_recommendations(proportions, coupling_character, asymmetry) + "overall_health": overall_health, + "health_scores": health_scores, + "proportions_analysis": proportions, + "coupling_character_analysis": coupling_character, + "asymmetry_analysis": asymmetry, + "interpretation": self._interpret_health(overall_health), + "recommendations": self._generate_recommendations( + proportions, coupling_character, asymmetry + ), } - + def _interpret_health(self, health: float) -> str: """Interpret overall relationship health score""" if health >= 0.9: @@ -294,66 +299,61 @@ def _interpret_health(self, health: float) -> str: return "Moderate: Some relationship patterns need attention" else: return "Critical: Major deviations from expected LJPW coupling structure" - + def _generate_recommendations( - self, - proportions: Dict, - coupling: Dict, - asymmetry: Dict + self, proportions: Dict, coupling: Dict, asymmetry: Dict ) -> List[str]: """Generate actionable recommendations based on analysis""" recommendations = [] - + # Proportion recommendations - if not proportions['proportions_healthy']: - worst_ratio = max(proportions['deviations'].items(), key=lambda x: x[1]) + if not proportions["proportions_healthy"]: + worst_ratio = max(proportions["deviations"].items(), key=lambda x: x[1]) recommendations.append( f"⚠️ Adjust proportions: {worst_ratio[0]} deviates by {worst_ratio[1]:.1%} from Natural Equilibrium" ) - + # Coupling character recommendations - if not coupling['love_amplifies']['pass']: + if not coupling["love_amplifies"]["pass"]: recommendations.append( "⚠️ Love is not amplifying properly - increase Love's influence on other dimensions" ) - - if not coupling['power_constrains']['pass']: + + if not coupling["power_constrains"]["pass"]: recommendations.append( "⚠️ Power is not constrained - reduce Power's direct influence, channel through Love/Wisdom" ) - - if not coupling['justice_supports_wisdom']['pass']: + + if not coupling["justice_supports_wisdom"]["pass"]: recommendations.append( "⚠️ Justice should support Wisdom more than Power - strengthen J→W coupling" ) - + # Asymmetry recommendations - if not asymmetry['asymmetry_healthy']: + if not asymmetry["asymmetry_healthy"]: recommendations.append( "⚠️ Coupling is too symmetric - verify that giving ≠ receiving for each dimension pair" ) - + if not recommendations: - recommendations.append("✓ All relationship patterns are healthy - maintain current structure") - + recommendations.append( + "✓ All relationship patterns are healthy - maintain current structure" + ) + return recommendations # Convenience function def analyze_system_relationships( - L: float, - J: float, - P: float, - W: float, - coupling_matrix: Dict[str, float] = None + L: float, J: float, P: float, W: float, coupling_matrix: Dict[str, float] = None ) -> Dict: """ Analyze if a system has healthy LJPW relationship patterns. - + Args: L, J, P, W: Dimension values coupling_matrix: Optional custom coupling matrix - + Returns: Comprehensive diagnostic report """ @@ -367,49 +367,49 @@ def analyze_system_relationships( print("LJPW Relationship Structure Analyzer") print("=" * 80) print() - + # Test with Natural Equilibrium (should be perfect) NE = ReferencePoints.NATURAL_EQUILIBRIUM - + print("Testing Natural Equilibrium:") print(f" L={NE[0]:.3f}, J={NE[1]:.3f}, P={NE[2]:.3f}, W={NE[3]:.3f}") print() - + result = analyze_system_relationships(NE[0], NE[1], NE[2], NE[3]) - + print(f"Overall Health: {result['overall_health']:.2%}") print(f"Interpretation: {result['interpretation']}") print() - + print("Health Breakdown:") - for aspect, score in result['health_scores'].items(): + for aspect, score in result["health_scores"].items(): status = "✓" if score >= 0.9 else "⚠️" if score >= 0.7 else "✗" print(f" {status} {aspect}: {score:.0%}") print() - + print("Recommendations:") - for rec in result['recommendations']: + for rec in result["recommendations"]: print(f" {rec}") print() - + # Test with imbalanced system print("=" * 80) print("Testing Imbalanced System (High Power, Low Love):") print(" L=0.2, J=0.3, P=0.9, W=0.4") print() - + result2 = analyze_system_relationships(0.2, 0.3, 0.9, 0.4) - + print(f"Overall Health: {result2['overall_health']:.2%}") print(f"Interpretation: {result2['interpretation']}") print() - + print("Health Breakdown:") - for aspect, score in result2['health_scores'].items(): + for aspect, score in result2["health_scores"].items(): status = "✓" if score >= 0.9 else "⚠️" if score >= 0.7 else "✗" print(f" {status} {aspect}: {score:.0%}") print() - + print("Recommendations:") - for rec in result2['recommendations']: + for rec in result2["recommendations"]: print(f" {rec}") diff --git a/scripts/anchor_analysis_V2.py b/scripts/anchor_analysis_V2.py index f137acf..e2b3941 100644 --- a/scripts/anchor_analysis_V2.py +++ b/scripts/anchor_analysis_V2.py @@ -96,9 +96,7 @@ def analyze_anchor_point_v2(): print(f"Distance from origin: {engine.get_distance(anchor, origin):.6f}") print(f"Distance from pure Love: {engine.get_distance(anchor, pure_love):.6f}") - print( - f"Distance from pure Justice: {engine.get_distance(anchor, pure_justice):.6f}" - ) + print(f"Distance from pure Justice: {engine.get_distance(anchor, pure_justice):.6f}") print(f"Distance from pure Power: {engine.get_distance(anchor, pure_power):.6f}") print(f"Distance from pure Wisdom: {engine.get_distance(anchor, pure_wisdom):.6f}") print() diff --git a/scripts/run_validation.py b/scripts/run_validation.py index 33d4c07..71eeebf 100644 --- a/scripts/run_validation.py +++ b/scripts/run_validation.py @@ -45,9 +45,7 @@ def analyze_and_simulate(file_path, harmonizer): execution = ice_components.get("execution") if execution: coords = execution.coordinates - all_coords.append( - (coords.love, coords.justice, coords.power, coords.wisdom) - ) + all_coords.append((coords.love, coords.justice, coords.power, coords.wisdom)) avg_p_sum += coords.power if not all_coords: @@ -81,9 +79,7 @@ def analyze_and_simulate(file_path, harmonizer): final_w = history["W"][-1] print(f" Final State:") - print( - f" L: {final_l:.2f} | J: {final_j:.2f} | P: {final_p:.2f} | W: {final_w:.2f}" - ) + print(f" L: {final_l:.2f} | J: {final_j:.2f} | P: {final_p:.2f} | W: {final_w:.2f}") # Assessment if final_j < 0.3: diff --git a/scripts/validate_relationship_hypothesis.py b/scripts/validate_relationship_hypothesis.py index c16d971..1b04817 100644 --- a/scripts/validate_relationship_hypothesis.py +++ b/scripts/validate_relationship_hypothesis.py @@ -22,52 +22,64 @@ # LJPW Constants (Natural Equilibrium) class Constants: L = (math.sqrt(5) - 1) / 2 # 0.618034 - J = math.sqrt(2) - 1 # 0.414214 - P = math.e - 2 # 0.718282 - W = math.log(2) # 0.693147 + J = math.sqrt(2) - 1 # 0.414214 + P = math.e - 2 # 0.718282 + W = math.log(2) # 0.693147 # Current Coupling Matrix (from ljpw_baselines.py) COUPLING_MATRIX = { - 'LL': 1.0, 'LJ': 1.4, 'LP': 1.3, 'LW': 1.5, - 'JL': 0.9, 'JJ': 1.0, 'JP': 0.7, 'JW': 1.2, - 'PL': 0.6, 'PJ': 0.8, 'PP': 1.0, 'PW': 0.5, - 'WL': 1.3, 'WJ': 1.1, 'WP': 1.0, 'WW': 1.0, + "LL": 1.0, + "LJ": 1.4, + "LP": 1.3, + "LW": 1.5, + "JL": 0.9, + "JJ": 1.0, + "JP": 0.7, + "JW": 1.2, + "PL": 0.6, + "PJ": 0.8, + "PP": 1.0, + "PW": 0.5, + "WL": 1.3, + "WJ": 1.1, + "WP": 1.0, + "WW": 1.0, } def calculate_all_ratios() -> Dict[str, float]: """Calculate ratios between all pairs of constants""" - dims = {'L': Constants.L, 'J': Constants.J, 'P': Constants.P, 'W': Constants.W} + dims = {"L": Constants.L, "J": Constants.J, "P": Constants.P, "W": Constants.W} ratios = {} - + for i in dims: for j in dims: - ratios[f'{i}{j}'] = dims[i] / dims[j] - + ratios[f"{i}{j}"] = dims[i] / dims[j] + return ratios def extract_coupling_data() -> Tuple[np.ndarray, np.ndarray, List[str]]: """ Extract (ratio, coupling) pairs for analysis - + Returns: ratios: Array of constant ratios couplings: Array of coupling coefficients labels: List of dimension pair labels """ const_ratios = calculate_all_ratios() - + ratios = [] couplings = [] labels = [] - + for key in COUPLING_MATRIX: ratios.append(const_ratios[key]) couplings.append(COUPLING_MATRIX[key]) labels.append(key) - + return np.array(ratios), np.array(couplings), labels @@ -75,6 +87,7 @@ def extract_coupling_data() -> Tuple[np.ndarray, np.ndarray, List[str]]: # Relationship Function Models # ============================================================================ + def identity_model(r, a, b): """κ = a*r + b (Linear relationship)""" return a * r + b @@ -82,7 +95,7 @@ def identity_model(r, a, b): def power_model(r, a, n): """κ = a * r^n (Power law)""" - return a * (r ** n) + return a * (r**n) def reciprocal_model(r, a, b): @@ -109,10 +122,11 @@ def log_model(r, a, b): # Model Fitting and Evaluation # ============================================================================ + def fit_model(model, ratios, couplings, p0=None): """ Fit a relationship model to the data - + Returns: params: Fitted parameters rmse: Root mean square error @@ -121,83 +135,83 @@ def fit_model(model, ratios, couplings, p0=None): try: params, _ = curve_fit(model, ratios, couplings, p0=p0, maxfev=10000) predictions = model(ratios, *params) - + # Calculate metrics residuals = couplings - predictions - rmse = np.sqrt(np.mean(residuals ** 2)) - ss_res = np.sum(residuals ** 2) + rmse = np.sqrt(np.mean(residuals**2)) + ss_res = np.sum(residuals**2) ss_tot = np.sum((couplings - np.mean(couplings)) ** 2) r2 = 1 - (ss_res / ss_tot) if ss_tot > 0 else 0 - + return params, rmse, r2, predictions except Exception as e: print(f"Failed to fit model: {e}") - return None, float('inf'), 0, None + return None, float("inf"), 0, None def evaluate_all_models(ratios, couplings): """Fit and evaluate all candidate models""" - + models = { - 'Linear (κ = a*r + b)': (identity_model, None), - 'Power Law (κ = a*r^n)': (power_model, [1.0, 1.0]), - 'Reciprocal (κ = a/r + b)': (reciprocal_model, None), - 'Sigmoid (κ = a/(1+e^(-k*(r-r0))))': (sigmoid_model, [1.0, 1.0, 1.0]), - 'Hybrid (κ = a1*r + a2/r + b)': (hybrid_model, [0.5, 0.5, 0.0]), - 'Logarithmic (κ = a*log(r) + b)': (log_model, None), + "Linear (κ = a*r + b)": (identity_model, None), + "Power Law (κ = a*r^n)": (power_model, [1.0, 1.0]), + "Reciprocal (κ = a/r + b)": (reciprocal_model, None), + "Sigmoid (κ = a/(1+e^(-k*(r-r0))))": (sigmoid_model, [1.0, 1.0, 1.0]), + "Hybrid (κ = a1*r + a2/r + b)": (hybrid_model, [0.5, 0.5, 0.0]), + "Logarithmic (κ = a*log(r) + b)": (log_model, None), } - + results = {} - + print("=" * 80) print("MODEL EVALUATION: Coupling = f(Ratio)") print("=" * 80) print() - + for name, (model, p0) in models.items(): params, rmse, r2, predictions = fit_model(model, ratios, couplings, p0) - + if params is not None: results[name] = { - 'model': model, - 'params': params, - 'rmse': rmse, - 'r2': r2, - 'predictions': predictions + "model": model, + "params": params, + "rmse": rmse, + "r2": r2, + "predictions": predictions, } - + print(f"{name}") print(f" Parameters: {params}") print(f" RMSE: {rmse:.4f}") print(f" R²: {r2:.4f}") print() - + return results def analyze_diagonal_vs_offdiagonal(ratios, couplings, labels): """Analyze if diagonal elements (LL, JJ, PP, WW) follow different pattern""" - + diagonal_mask = [label[0] == label[1] for label in labels] offdiagonal_mask = [not d for d in diagonal_mask] - + diag_ratios = ratios[diagonal_mask] diag_couplings = couplings[diagonal_mask] - + offdiag_ratios = ratios[offdiagonal_mask] offdiag_couplings = couplings[offdiagonal_mask] - + print("=" * 80) print("DIAGONAL vs OFF-DIAGONAL ANALYSIS") print("=" * 80) print() - + print("DIAGONAL ELEMENTS (self-coupling):") for i, label in enumerate([l for l, d in zip(labels, diagonal_mask) if d]): print(f" {label}: ratio={diag_ratios[i]:.4f}, κ={diag_couplings[i]:.4f}") print(f" All diagonal couplings = 1.0 (by definition)") print() - + print("OFF-DIAGONAL ELEMENTS (cross-coupling):") # Fit linear model to off-diagonal only if len(offdiag_ratios) > 0: @@ -210,82 +224,107 @@ def analyze_diagonal_vs_offdiagonal(ratios, couplings, labels): def find_special_patterns(ratios, couplings, labels): """Look for special patterns in the coupling-ratio relationship""" - + print("=" * 80) print("SPECIAL PATTERNS ANALYSIS") print("=" * 80) print() - + # Group by source dimension - for source in ['L', 'J', 'P', 'W']: + for source in ["L", "J", "P", "W"]: 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] - + print(f"Source: {source} (outgoing influence)") for i, label in enumerate(source_labels): - print(f" {label}: r={source_ratios[i]:.3f} → κ={source_couplings[i]:.3f} " - f"(diff: {source_couplings[i] - source_ratios[i]:+.3f})") + print( + f" {label}: r={source_ratios[i]:.3f} → κ={source_couplings[i]:.3f} " + f"(diff: {source_couplings[i] - source_ratios[i]:+.3f})" + ) print() def visualize_results(ratios, couplings, labels, results): """Create visualization of relationship between ratios and coupling""" - + fig, axes = plt.subplots(2, 3, figsize=(18, 12)) - fig.suptitle('Coupling Coefficient vs. Constant Ratio Analysis', fontsize=16, fontweight='bold') - + fig.suptitle("Coupling Coefficient vs. Constant Ratio Analysis", fontsize=16, fontweight="bold") + # Plot 1: Scatter with diagonal highlighted ax = axes[0, 0] diagonal = [label[0] == label[1] for label in labels] - ax.scatter(ratios[~np.array(diagonal)], couplings[~np.array(diagonal)], - alpha=0.6, s=100, label='Off-diagonal', color='blue') - ax.scatter(ratios[diagonal], couplings[diagonal], - alpha=0.8, s=100, label='Diagonal (self)', color='red', marker='s') - + ax.scatter( + ratios[~np.array(diagonal)], + couplings[~np.array(diagonal)], + alpha=0.6, + s=100, + label="Off-diagonal", + color="blue", + ) + ax.scatter( + ratios[diagonal], + couplings[diagonal], + alpha=0.8, + s=100, + label="Diagonal (self)", + color="red", + marker="s", + ) + # Add labels for each point for i, label in enumerate(labels): - ax.annotate(label, (ratios[i], couplings[i]), - xytext=(5, 5), textcoords='offset points', fontsize=8) - - ax.plot([0, 2], [0, 2], 'k--', alpha=0.3, label='κ = r (identity)') - ax.set_xlabel('Constant Ratio (Ci/Cj)', fontsize=12) - ax.set_ylabel('Coupling Coefficient κij', fontsize=12) - ax.set_title('Raw Data: Coupling vs. Ratio', fontweight='bold') + ax.annotate( + label, (ratios[i], couplings[i]), xytext=(5, 5), textcoords="offset points", fontsize=8 + ) + + ax.plot([0, 2], [0, 2], "k--", alpha=0.3, label="κ = r (identity)") + ax.set_xlabel("Constant Ratio (Ci/Cj)", fontsize=12) + ax.set_ylabel("Coupling Coefficient κij", fontsize=12) + ax.set_title("Raw Data: Coupling vs. Ratio", fontweight="bold") ax.legend() ax.grid(True, alpha=0.3) - + # Plot best models model_names = list(results.keys())[:5] for idx, name in enumerate(model_names): row = (idx + 1) // 3 col = (idx + 1) % 3 ax = axes[row, col] - + result = results[name] - predictions = result['predictions'] - + predictions = result["predictions"] + # Scatter actual vs predicted ax.scatter(couplings, predictions, alpha=0.6, s=100) - ax.plot([0, 2], [0, 2], 'r--', alpha=0.5, label='Perfect prediction') - + ax.plot([0, 2], [0, 2], "r--", alpha=0.5, label="Perfect prediction") + # Add labels for i, label in enumerate(labels): if abs(couplings[i] - predictions[i]) > 0.2: # Highlight large errors - ax.annotate(label, (couplings[i], predictions[i]), - xytext=(5, 5), textcoords='offset points', fontsize=8, - color='red', fontweight='bold') - - ax.set_xlabel('Actual Coupling κ', fontsize=10) - ax.set_ylabel('Predicted κ', fontsize=10) - ax.set_title(f"{name}\nRMSE={result['rmse']:.3f}, R²={result['r2']:.3f}", - fontsize=10, fontweight='bold') + ax.annotate( + label, + (couplings[i], predictions[i]), + xytext=(5, 5), + textcoords="offset points", + fontsize=8, + color="red", + fontweight="bold", + ) + + ax.set_xlabel("Actual Coupling κ", fontsize=10) + ax.set_ylabel("Predicted κ", fontsize=10) + ax.set_title( + f"{name}\nRMSE={result['rmse']:.3f}, R²={result['r2']:.3f}", + fontsize=10, + fontweight="bold", + ) ax.legend(fontsize=8) ax.grid(True, alpha=0.3) - + plt.tight_layout() - plt.savefig('/workspace/coupling_ratio_analysis.png', dpi=150, bbox_inches='tight') + plt.savefig("/workspace/coupling_ratio_analysis.png", dpi=150, bbox_inches="tight") print(f"\n✓ Visualization saved to: /workspace/coupling_ratio_analysis.png") plt.close() @@ -294,24 +333,25 @@ def visualize_results(ratios, couplings, labels, results): # Main Analysis # ============================================================================ + def main(): """Run complete relationship analysis""" - - print("\n" + "="*80) + + print("\n" + "=" * 80) print("LJPW RELATIONSHIP HYPOTHESIS VALIDATION") print("Insight: 'Relationships between constants matter more than constants themselves'") - print("="*80 + "\n") - + print("=" * 80 + "\n") + # Calculate ratios all_ratios = calculate_all_ratios() print("CONSTANT RATIOS:") print("-" * 40) - dims = ['L', 'J', 'P', 'W'] - const_vals = {'L': Constants.L, 'J': Constants.J, 'P': Constants.P, 'W': Constants.W} + dims = ["L", "J", "P", "W"] + const_vals = {"L": Constants.L, "J": Constants.J, "P": Constants.P, "W": Constants.W} for d in dims: print(f"{d} = {const_vals[d]:.6f}") print() - + print("Key Ratios:") print(f" L/J = {all_ratios['LJ']:.4f}") print(f" L/P = {all_ratios['LP']:.4f}") @@ -320,19 +360,19 @@ def main(): print(f" W/J = {all_ratios['WJ']:.4f}") print(f" W/P = {all_ratios['WP']:.4f}") print() - + # Extract data ratios, couplings, labels = extract_coupling_data() - + # Run analyses analyze_diagonal_vs_offdiagonal(ratios, couplings, labels) find_special_patterns(ratios, couplings, labels) results = evaluate_all_models(ratios, couplings) - + # Find best model - best_model_name = min(results.keys(), key=lambda k: results[k]['rmse']) + best_model_name = min(results.keys(), key=lambda k: results[k]["rmse"]) best_result = results[best_model_name] - + print("=" * 80) print("CONCLUSION") print("=" * 80) @@ -342,12 +382,12 @@ def main(): print(f" R²: {best_result['r2']:.4f}") print(f" Parameters: {best_result['params']}") print() - - if best_result['r2'] > 0.5: + + if best_result["r2"] > 0.5: print("✓ STRONG RELATIONSHIP DETECTED") print(" The coupling coefficients CAN be partially derived from constant ratios.") print(" This supports the insight: relationships are more fundamental than absolutes.") - elif best_result['r2'] > 0.3: + elif best_result["r2"] > 0.3: print("~ MODERATE RELATIONSHIP DETECTED") print(" There is some connection between ratios and coupling,") print(" but additional factors influence the coupling structure.") @@ -355,10 +395,10 @@ def main(): print("✗ WEAK RELATIONSHIP") print(" Coupling coefficients appear to be independent of constant ratios.") print(" Additional theoretical work needed to understand coupling origins.") - + print() print("IMPLICATIONS:") - if best_result['r2'] > 0.3: + if best_result["r2"] > 0.3: print(" • Parameter reduction possible: coupling ≈ f(ratio)") print(" • System exhibits scale invariance") print(" • Proportions more fundamental than magnitudes") @@ -367,13 +407,13 @@ def main(): print(" • Current coupling coefficients are independently calibrated") print(" • May represent emergent properties beyond simple ratios") print(" • Further research needed to find deeper unifying principle") - + # Visualize visualize_results(ratios, couplings, labels, results) - - print("\n" + "="*80) + + print("\n" + "=" * 80) print("Analysis complete. See RELATIONSHIP_ANALYSIS.md for detailed interpretation.") - print("="*80 + "\n") + print("=" * 80 + "\n") if __name__ == "__main__": diff --git a/scripts/verify_tech_debt.py b/scripts/verify_tech_debt.py index ffb9a44..b80c54c 100644 --- a/scripts/verify_tech_debt.py +++ b/scripts/verify_tech_debt.py @@ -38,16 +38,12 @@ def verify_tech_debt(): # Run smell detection for this file mapper._detect_architectural_smells() - smells = [ - s for s in mapper.architectural_smells if s.file_path.endswith(filename) - ] + smells = [s for s in mapper.architectural_smells if s.file_path.endswith(filename)] if smells: print(f" Detected {len(smells)} Architectural Smells:") for smell in smells: - print( - f" - [{smell.severity}] {smell.smell_type}: {smell.description}" - ) + print(f" - [{smell.severity}] {smell.smell_type}: {smell.description}") else: print(" No Architectural Smells detected.")