everydaytok commited on
Commit
03fa79b
·
verified ·
1 Parent(s): 098afc3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -83
app.py CHANGED
@@ -1,6 +1,6 @@
1
  #!/usr/bin/env python3
2
  """
3
- PRACTICALITY SYSTEM 3.9
4
 
5
  ===================================================================
6
  ARCHITECTURE & TENSOR TRANSITION MANIFESTO (V4.0 PREP)
@@ -21,20 +21,18 @@ without regressions, we must adhere to the following mapping:
21
  - Future Tensor: Constraints pre-compiled into vectorized Numpy universal
22
  functions (ufuncs). E.g., `np.add(bounds[:, v1, :], bounds[:, v2, :])`.
23
  Invalid regions generate boolean bitmasks `valid_mask = np.ones(N_boxes)`.
24
-
25
- 3. THE DEBATE ENGINE:
26
- - Current: Sequential execution of Seed, Struct, Perturb, Merge.
27
- - Future Tensor: En masse generation. `Perturb` generates 1,000 offsets
28
- via `np.random.normal`, evaluated in parallel against the CE tensor matrix.
29
  ===================================================================
30
 
31
- Changes from 3.8:
32
- NEW 1 — Topology-Ordered Snap (The Causal Sniper): The `_algebraic_snap`
33
- function now queries the `L7 Topology Oracle` to determine the causal
34
- solve order of the variables (e.g., x1 -> x2 -> x3 in chain10).
35
- Instead of greedily picking the "minimum distance" projection, it
36
- enforces projections in structural order. This prevents artificial
37
- downstream energy spikes and honors the physical propagation of the constraints.
 
 
 
38
  """
39
 
40
  import asyncio, time, random, math, threading, warnings
@@ -332,7 +330,7 @@ def expand_psl(prog:PSLProgram) -> ExpandedProblem:
332
  return ExpandedProblem(variables,bounds,constraints, dict(scope_groups),dict(scope_vars),scope_order)
333
 
334
  # ══════════════════════════════════════════════════════════════════════════
335
- # SECTION 4: PROBLEM DEFINITION (WITH ALGEBRAIC CACHING)
336
  # ══════════════════════════════════════════════════════════════════════════
337
 
338
  PROJECTION_CACHE: Dict[str, Dict[str, List[Dict]]] = {}
@@ -351,7 +349,7 @@ class MathConstraint:
351
  parsed:Optional[sp.Expr]=field(default=None,repr=False)
352
  degree:int=1; scope:str="root"
353
  branches:List['MathConstraint']=field(default_factory=list)
354
- projections:Dict[str,List[Dict]]=field(default_factory=dict)
355
 
356
  def compile_mc(kind,expr_str,direction,variables,weight=1.0,scope="root",branches=None):
357
  mc=MathConstraint(kind=kind,expr_str=expr_str,direction=direction,weight=weight,scope=scope)
@@ -537,8 +535,7 @@ class ResidualOracle:
537
 
538
  class BridgeOracle:
539
  def generate_witness(self, problem: Problem, binding: Dict[str, float], ce: float, l7: L7Certificate, l9: L9Certificate) -> str:
540
- lines = []
541
-
542
  lines.append(f"====== UNIVERSAL WITNESS: {problem.pid} ======")
543
  lines.append(f"STATUS: {'SOLVED' if ce < SOLVE_THRESHOLD else 'STUCK'} (CE: {ce:.6f})")
544
  lines.append(f"TOPOLOGY: {l7.topology_sig.upper() if l7 else 'NONE'} | Hubs: {', '.join(l7.hub_vars) if l7 and l7.hub_vars else 'None'}")
@@ -620,81 +617,103 @@ def _global_hc4_tighten(problem:Problem) -> Dict[str,Tuple[float,float]]:
620
  if orig_vol > 0 and new_vol < orig_vol * HC4_VOLUME_FLOOR: return dict(problem.bounds)
621
  return {v:(max(problem.bounds[v][0], contracted[v].lo), min(problem.bounds[v][1], contracted[v].hi)) for v in problem.bounds if v in contracted}
622
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623
  def _algebraic_snap(problem: Problem, binding: Dict[str, float]) -> Tuple[Dict[str, float], float]:
624
  """
625
- NEW 1: Topology-Ordered Snap (The Causal Sniper).
626
- Walks in scope order so downstream variables resolve upstream dependencies correctly.
627
  """
628
- proj_binding = dict(binding)
629
- best_ce = problem.constraint_energy(proj_binding)
630
- best_binding = dict(proj_binding)
631
 
632
  active_scopes = [s for s in problem.scope_order if s != "root" and problem.scope_vars.get(s)]
633
  l7 = TOPOLOGY_ORACLE.evaluate(problem, active_scopes)
634
 
 
635
  ordered_vars =[]
636
  if l7.solve_order:
637
  for sn in l7.solve_order:
638
  for v in problem.scope_vars.get(sn,[]):
639
- if v not in ordered_vars:
640
- ordered_vars.append(v)
641
  for v in problem.variables:
642
- if v not in ordered_vars:
643
- ordered_vars.append(v)
644
-
645
- SNAP_SPIKE_TOLERANCE = 0.15
646
-
647
- for _ in range(20):
648
- l9 = RESIDUAL_ORACLE.evaluate(proj_binding, problem,[])
649
- if not l9.dominant_exprs: break
650
-
651
- improved_in_step = False
652
-
653
- for worst_expr in l9.dominant_exprs[:3]:
654
- target_mc = next((mc for mc in problem.compiled_constraints if mc.expr_str == worst_expr), None)
655
- if not target_mc:
656
- for mc in problem.compiled_constraints:
657
- if mc.kind == "or_eq":
658
- for bmc in mc.branches:
659
- if bmc.expr_str == worst_expr: target_mc = bmc; break
660
- if target_mc: break
661
-
662
- if not (target_mc and hasattr(target_mc, 'projections') and target_mc.projections):
663
- continue
664
-
665
- # Walk in topology order, not minimum-distance order
666
- for v in ordered_vars:
667
- if v not in target_mc.projections:
668
- continue
669
- for proj in target_mc.projections[v]:
670
- try:
671
- args = [proj_binding.get(s, 0.0) for s in proj["syms"]]
672
- val = float(proj["func"](*args))
673
- if not math.isfinite(val) or abs(val) > 1e6:
674
- continue
675
- lo, hi = problem.bounds.get(v, (-1e18, 1e18))
676
- if not (lo <= val <= hi):
677
- continue
678
-
679
- test_binding = dict(proj_binding)
680
- test_binding[v] = val
681
- new_ce = problem.constraint_energy(test_binding)
682
-
683
- if new_ce < best_ce * (1 + SNAP_SPIKE_TOLERANCE):
684
- proj_binding = test_binding
685
- improved_in_step = True
686
- if new_ce < best_ce:
687
- best_ce = new_ce
688
- best_binding = dict(proj_binding)
689
- break
690
- except: pass
691
- if improved_in_step: break
692
- if improved_in_step: break
693
-
694
- if not improved_in_step: break
695
- if best_ce < SOLVE_THRESHOLD: break
696
 
697
- return best_binding, best_ce
698
 
699
  def _normalisation_sweep(problem:Problem, binding:Dict[str,float], budget:int) -> Dict:
700
  snap_binding, snap_ce = _algebraic_snap(problem, binding)
@@ -1278,7 +1297,7 @@ async def lifespan(app: FastAPI):
1278
  yield
1279
  POOL.shutdown(wait=False)
1280
 
1281
- app = FastAPI(title="Practicality System 3.9", lifespan=lifespan)
1282
 
1283
  @app.post("/inject/{pid}")
1284
  async def inject_seed(pid:str, request:Request):
@@ -1353,7 +1372,7 @@ async def dashboard():
1353
  f"font-size:0.85em;margin:2px'>{label}: {val}</span>")
1354
 
1355
  html=f"""<!DOCTYPE html><html>
1356
- <head><title>Practicality System 3.9</title>
1357
  <meta http-equiv="refresh" content="3">
1358
  <style>
1359
  body{{background:#0a0a0a;color:#e0e0e0;font-family:monospace;padding:20px}}
@@ -1364,7 +1383,7 @@ async def dashboard():
1364
  th{{color:#444}}
1365
  .witness-box{{background:#111; border:1px solid #333; padding:15px; color:#aaa; white-space:pre-wrap; font-size:0.9em;}}
1366
  </style></head><body>
1367
- <h1>⚗ Practicality System 3.9</h1>
1368
  <div style='margin-bottom:16px;line-height:2.2em;'>
1369
  {badge("Trials",runs,"#aaa")}
1370
  {badge("Avg rounds",avg_rounds,"#aaa")}
@@ -1409,4 +1428,4 @@ async def dashboard():
1409
  return html
1410
 
1411
  if __name__=="__main__":
1412
- uvicorn.run(app,host="0.0.0.0",port=7860,log_level="warning")
 
1
  #!/usr/bin/env python3
2
  """
3
+ PRACTICALITY SYSTEM 3.10
4
 
5
  ===================================================================
6
  ARCHITECTURE & TENSOR TRANSITION MANIFESTO (V4.0 PREP)
 
21
  - Future Tensor: Constraints pre-compiled into vectorized Numpy universal
22
  functions (ufuncs). E.g., `np.add(bounds[:, v1, :], bounds[:, v2, :])`.
23
  Invalid regions generate boolean bitmasks `valid_mask = np.ones(N_boxes)`.
 
 
 
 
 
24
  ===================================================================
25
 
26
+ Changes from 3.9:
27
+ FIX 1 — The Dual-Sniper: V3.9 enforced causal ordering, which solved chain10
28
+ but slightly degraded symmetric meshes like quantum5. `_algebraic_snap`
29
+ now evaluates BOTH greedy (shortest distance) and causal (topological)
30
+ paths, picking the lowest CE.
31
+ FIX 2 Topological Shrink (Negative Root Recovery): Resolves the `fully10`
32
+ trap. If a projection yields a math domain error (e.g. sqrt of a negative
33
+ due to overshooting a sphere), it geometrically contracts the inputs 10%
34
+ towards their bound midpoints to bring them back into the real domain
35
+ and retries the projection.
36
  """
37
 
38
  import asyncio, time, random, math, threading, warnings
 
330
  return ExpandedProblem(variables,bounds,constraints, dict(scope_groups),dict(scope_vars),scope_order)
331
 
332
  # ══════════════════════════════════════════════════════════════════════════
333
+ # SECTION 4: PROBLEM DEFINITION
334
  # ══════════════════════════════════════════════════════════════════════════
335
 
336
  PROJECTION_CACHE: Dict[str, Dict[str, List[Dict]]] = {}
 
349
  parsed:Optional[sp.Expr]=field(default=None,repr=False)
350
  degree:int=1; scope:str="root"
351
  branches:List['MathConstraint']=field(default_factory=list)
352
+ projections:Dict[str,List[Dict]]=field(default_factory=dict)
353
 
354
  def compile_mc(kind,expr_str,direction,variables,weight=1.0,scope="root",branches=None):
355
  mc=MathConstraint(kind=kind,expr_str=expr_str,direction=direction,weight=weight,scope=scope)
 
535
 
536
  class BridgeOracle:
537
  def generate_witness(self, problem: Problem, binding: Dict[str, float], ce: float, l7: L7Certificate, l9: L9Certificate) -> str:
538
+ lines =[]
 
539
  lines.append(f"====== UNIVERSAL WITNESS: {problem.pid} ======")
540
  lines.append(f"STATUS: {'SOLVED' if ce < SOLVE_THRESHOLD else 'STUCK'} (CE: {ce:.6f})")
541
  lines.append(f"TOPOLOGY: {l7.topology_sig.upper() if l7 else 'NONE'} | Hubs: {', '.join(l7.hub_vars) if l7 and l7.hub_vars else 'None'}")
 
617
  if orig_vol > 0 and new_vol < orig_vol * HC4_VOLUME_FLOOR: return dict(problem.bounds)
618
  return {v:(max(problem.bounds[v][0], contracted[v].lo), min(problem.bounds[v][1], contracted[v].hi)) for v in problem.bounds if v in contracted}
619
 
620
+ def _single_snap_pass(problem: Problem, proj_binding: Dict[str, float], ordered_vars: List[str], best_ce: float, spike_tolerance: float) -> Tuple[Dict[str, float], float, bool]:
621
+ improved_in_step = False
622
+ best_binding = dict(proj_binding)
623
+
624
+ l9 = RESIDUAL_ORACLE.evaluate(proj_binding, problem,[])
625
+ if not l9.dominant_exprs: return best_binding, best_ce, False
626
+
627
+ for worst_expr in l9.dominant_exprs[:3]:
628
+ target_mc = next((mc for mc in problem.compiled_constraints if mc.expr_str == worst_expr), None)
629
+ if not target_mc:
630
+ for mc in problem.compiled_constraints:
631
+ if mc.kind == "or_eq":
632
+ for bmc in mc.branches:
633
+ if bmc.expr_str == worst_expr: target_mc = bmc; break
634
+ if target_mc: break
635
+
636
+ if not (target_mc and hasattr(target_mc, 'projections') and target_mc.projections):
637
+ continue
638
+
639
+ for v in ordered_vars:
640
+ if v not in target_mc.projections: continue
641
+ for proj in target_mc.projections[v]:
642
+
643
+ # FIX 2: Topological Shrink (Domain Error Recovery)
644
+ # We attempt the projection. If it throws ValueError (e.g. sqrt(-x) due to being
645
+ # outside a sphere), we pull the inputs 10% towards bounds-center and retry.
646
+ val = None
647
+ try:
648
+ args = [proj_binding.get(s, 0.0) for s in proj["syms"]]
649
+ val = float(proj["func"](*args))
650
+ except (ValueError, TypeError):
651
+ shrunk_args =[]
652
+ for s in proj["syms"]:
653
+ lo, hi = problem.bounds.get(s, (-1e18, 1e18))
654
+ mid = (lo + hi) / 2.0 if lo != -1e18 else 0.0
655
+ shrunk_args.append(proj_binding.get(s, mid) * 0.9 + mid * 0.1)
656
+ try: val = float(proj["func"](*shrunk_args))
657
+ except: continue
658
+
659
+ if val is None or not math.isfinite(val) or abs(val) > 1e6:
660
+ continue
661
+
662
+ lo, hi = problem.bounds.get(v, (-1e18, 1e18))
663
+ if not (lo <= val <= hi): continue
664
+
665
+ test_binding = dict(proj_binding)
666
+ test_binding[v] = val
667
+ new_ce = problem.constraint_energy(test_binding)
668
+
669
+ if new_ce < best_ce * (1 + spike_tolerance):
670
+ proj_binding = test_binding
671
+ improved_in_step = True
672
+ if new_ce < best_ce:
673
+ best_ce = new_ce
674
+ best_binding = dict(proj_binding)
675
+ break
676
+ if improved_in_step: break
677
+ if improved_in_step: break
678
+
679
+ return best_binding, best_ce, improved_in_step
680
+
681
  def _algebraic_snap(problem: Problem, binding: Dict[str, float]) -> Tuple[Dict[str, float], float]:
682
  """
683
+ FIX 1: Dual-Sniper logic. Runs both Greedy (minimum-distance) and Causal (topological)
684
+ paths, returning the best. Cures the quantum5 jitter while preserving chain10 solves.
685
  """
686
+ best_ce_overall = problem.constraint_energy(binding)
687
+ best_binding_overall = dict(binding)
 
688
 
689
  active_scopes = [s for s in problem.scope_order if s != "root" and problem.scope_vars.get(s)]
690
  l7 = TOPOLOGY_ORACLE.evaluate(problem, active_scopes)
691
 
692
+ # 1. Evaluate Causal (Topological) Order
693
  ordered_vars =[]
694
  if l7.solve_order:
695
  for sn in l7.solve_order:
696
  for v in problem.scope_vars.get(sn,[]):
697
+ if v not in ordered_vars: ordered_vars.append(v)
 
698
  for v in problem.variables:
699
+ if v not in ordered_vars: ordered_vars.append(v)
700
+
701
+ causal_b = dict(binding); causal_ce = best_ce_overall
702
+ for _ in range(20):
703
+ causal_b, causal_ce, improved = _single_snap_pass(problem, causal_b, ordered_vars, causal_ce, 0.15)
704
+ if not improved or causal_ce < SOLVE_THRESHOLD: break
705
+
706
+ # 2. Evaluate Greedy Order (Prioritizing global variables regardless of scope topology)
707
+ greedy_vars = problem.variables
708
+ greedy_b = dict(binding); greedy_ce = best_ce_overall
709
+ for _ in range(20):
710
+ greedy_b, greedy_ce, improved = _single_snap_pass(problem, greedy_b, greedy_vars, greedy_ce, 0.15)
711
+ if not improved or greedy_ce < SOLVE_THRESHOLD: break
712
+
713
+ if causal_ce < best_ce_overall: best_ce_overall = causal_ce; best_binding_overall = causal_b
714
+ if greedy_ce < best_ce_overall: best_ce_overall = greedy_ce; best_binding_overall = greedy_b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
715
 
716
+ return best_binding_overall, best_ce_overall
717
 
718
  def _normalisation_sweep(problem:Problem, binding:Dict[str,float], budget:int) -> Dict:
719
  snap_binding, snap_ce = _algebraic_snap(problem, binding)
 
1297
  yield
1298
  POOL.shutdown(wait=False)
1299
 
1300
+ app = FastAPI(title="Practicality System 3.10", lifespan=lifespan)
1301
 
1302
  @app.post("/inject/{pid}")
1303
  async def inject_seed(pid:str, request:Request):
 
1372
  f"font-size:0.85em;margin:2px'>{label}: {val}</span>")
1373
 
1374
  html=f"""<!DOCTYPE html><html>
1375
+ <head><title>Practicality System 3.10</title>
1376
  <meta http-equiv="refresh" content="3">
1377
  <style>
1378
  body{{background:#0a0a0a;color:#e0e0e0;font-family:monospace;padding:20px}}
 
1383
  th{{color:#444}}
1384
  .witness-box{{background:#111; border:1px solid #333; padding:15px; color:#aaa; white-space:pre-wrap; font-size:0.9em;}}
1385
  </style></head><body>
1386
+ <h1>⚗ Practicality System 3.10</h1>
1387
  <div style='margin-bottom:16px;line-height:2.2em;'>
1388
  {badge("Trials",runs,"#aaa")}
1389
  {badge("Avg rounds",avg_rounds,"#aaa")}
 
1428
  return html
1429
 
1430
  if __name__=="__main__":
1431
+ uvicorn.run(app,host="0.0.0.0",port=7860,log_level="warning")