everydaytok commited on
Commit
3111175
Β·
verified Β·
1 Parent(s): 5fb1c68

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -111
app.py CHANGED
@@ -1,22 +1,24 @@
1
  #!/usr/bin/env python3
2
  """
3
- PRACTICALITY SYSTEM 24.1 β€” STRUCTURAL SKETCH, QUANTUM ENGINE & HOMOTOPY CONTINUATION
4
  ══════════════════════════════════════════════════════════════════════════════════
5
  ARCHITECTURE:
6
  User Text β†’ [GEMINI ENCODER] β†’ AXLProblemDef
7
  β†’ [STRUCTURAL SKETCH] β†’ Axiom affinity map + SymPy Derivation
8
- β†’ [TEMPLATE ENGINE] β†’ Analytically-derived partial hypotheses
9
- β†’ [WISDOM LAYER] β†’ Sketch-weighted rays + Masked Deduction (with Homotopy)
10
  β†’ [GEMINI COLLAPSER] β†’ Domain-language explanation
11
 
12
- CRITICAL STABILITY FIXES:
13
- 1. The Tensor Shield: Built impenetrable wrapper around SymPy lambda calls to
14
- prevent unresolvable SymPy symbolic leakages from crashing PyTorch gradients.
15
- 2. Thread Crash Safety: Entire solver loop wrapped in try/finally to prevent UI lockups.
16
- 3. UI Responsive Layout: Clean flexbox rendering for mobile devices.
 
 
17
  """
18
 
19
- import os, time, random, math, threading, warnings, json, textwrap
20
  from functools import reduce
21
  from typing import Optional, Callable, List, Dict, Tuple, Any, Set
22
  from dataclasses import dataclass, field
@@ -43,13 +45,13 @@ except ImportError:
43
  # ══════════════════════════════════════════════════════════════════════
44
  # AI CONFIGURATION
45
  # ══════════════════════════════════════════════════════════════════════
46
- DEFAULT_GEMINI_API_KEY = os.environ.get("AI_Key", "")
47
- GEMINI_MODEL = "gemini-3-flash-preview" # "gemma-4-26b-a4b-it"Β  #
48
 
49
  warnings.filterwarnings("ignore")
50
  USE_GPU = torch.cuda.is_available()
51
  DEVICE = torch.device("cuda" if USE_GPU else "cpu")
52
- print(f"[SYSTEM 24.1] Compute: {DEVICE.type.upper()} | Homotopy + Tensor Shield Active")
53
 
54
  # ══════════════════════════════════════════════════════════════════════
55
  # SECTION 1: CONSTANTS
@@ -57,13 +59,13 @@ print(f"[SYSTEM 24.1] Compute: {DEVICE.type.upper()} | Homotopy + Tensor Shield
57
  SOLVE_THRESHOLD = 0.05
58
  VERIFY_G1_THRESHOLD = 0.08
59
  VERIFY_G2_TOLERANCE = 1e-3
60
- DEDUCE_ADAM_STEPS = 25
61
  N_MPRT_EXPLORE = 1000
62
  PROJECTION_CACHE: Dict = {}
63
 
64
  MAX_RAYS_PER_ATTEMPT = 24576 * 10
65
  RAY_BATCH_SIZE = 24576
66
- TEMPLATE_BATCH_SIZE = 512
67
  CE_EARN_RATIO = 0.90
68
  SCOUT_CE_THRESHOLD = 0.5
69
  BRANCH_WIDTH = 12
@@ -80,28 +82,18 @@ SYMPY_TIMEOUT_SECS = 4.0
80
  STATE_LOCK = threading.Lock()
81
 
82
  GLOBAL_SOLVE_STATE = {
83
- "is_running": False,
84
- "phase": "IDLE",
85
- "best_ce": float('inf'),
86
- "total_fired": 0,
87
- "best_ray": "β€”",
88
- "recent_traces": deque(maxlen=25),
89
- "high_level_logs": [],
90
- "answer": "",
91
- "sketch_summary": "",
92
- "template_count": 0,
93
- "template_best_ce": float('inf'),
94
- "sympy_derivation": [],
95
  }
96
 
97
  def _update_state(**kwargs):
98
  with STATE_LOCK:
99
- for k, v in kwargs.items():
100
- GLOBAL_SOLVE_STATE[k] = v
101
 
102
  def _add_log(line: str):
103
- with STATE_LOCK:
104
- GLOBAL_SOLVE_STATE["high_level_logs"].append(line)
105
 
106
  # ══════════════════════════════════════════════════════════════════════
107
  # SECTION 3: INTERVAL ARITHMETIC (HC4)
@@ -368,10 +360,8 @@ def compile_mc(kind,expr_str,direction,variables,weight=1.0,scope="root",branche
368
  val = t_func_raw(*args)
369
  if not isinstance(val, torch.Tensor):
370
  try:
371
- # Catch Python floats, ints, or fully resolved SymPy numbers
372
  val = torch.tensor(float(val), device=DEVICE, dtype=torch.float32)
373
  except Exception:
374
- # If an unresolvable SymPy Add/Symbol leaked through, penalize heavily instead of crashing
375
  return torch.tensor(9999.0, device=DEVICE, dtype=torch.float32)
376
  return val
377
 
@@ -446,7 +436,7 @@ class Problem:
446
  except: pass
447
 
448
  # ══════════════════════════════════════════════════════════════════════
449
- # HOMOTOPY CONTINUATION FIX: tensor_energy now scales transcendentals
450
  # ══════════════════════════════════════════════════════════════════════
451
  def tensor_energy(self, X: torch.Tensor, step_ratio: float = 1.0) -> torch.Tensor:
452
  is_batched = (X.dim() == 2)
@@ -456,8 +446,6 @@ class Problem:
456
  if getattr(mc, 'weight', 1.0) == 0.0: continue
457
 
458
  eff_weight = float(mc.weight)
459
-
460
- # Soften highly non-linear constraints early in the gradient search
461
  if step_ratio < 1.0 and any(f in mc.expr_str for f in ["sin", "cos", "exp"]):
462
  eff_weight *= (0.1 + 0.9 * step_ratio)
463
 
@@ -480,11 +468,10 @@ class Problem:
480
  else:
481
  total += torch.relu(val) * eff_weight
482
 
483
- # Bounds with exploratory margins for Homotopy Continuation
484
  for i, v in enumerate(self.variables):
485
  lo, hi = self.bounds[v]
486
  col = X[:, i] if is_batched else X[i]
487
- margin = (hi - lo) * 0.1 * (1.0 - step_ratio) # Allow 10% out-of-bounds at step 0
488
  total += torch.relu(lo - margin - col) + torch.relu(col - (hi + margin))
489
 
490
  return total.squeeze()
@@ -521,7 +508,7 @@ def build_base_problem(axl_def:AXLProblemDef) -> Problem:
521
  scope_order=ep.scope_order)
522
 
523
  # ══════════════════════════════════════════════════════════════════════
524
- # SECTION 6: STRUCTURAL SKETCH β€” The World Model Prior
525
  # ══════════════════════════════════════════════════════════════════════
526
  @dataclass
527
  class StructuralSketch:
@@ -558,8 +545,7 @@ def _try_sympy_solve(problem: Problem) -> Tuple[List[Dict[str, float]], bool, Li
558
  syms = [sp.Symbol(v) for v in problem.variables]
559
  equations = [mc.parsed for mc in eq_mcs]
560
 
561
- def _solve():
562
- return sp.solve(equations, syms, dict=True)
563
 
564
  try:
565
  with concurrent.futures.ThreadPoolExecutor(max_workers=1) as ex:
@@ -586,14 +572,6 @@ def _try_sympy_solve(problem: Problem) -> Tuple[List[Dict[str, float]], bool, Li
586
  else:
587
  derivation.append(f" {sym} = {simplified} [eliminates {sym}, depends on {', '.join(str(s) for s in free_s)}]")
588
 
589
- if len(sorted_sol) == 1:
590
- sym, val = sorted_sol[0]
591
- try:
592
- poly = sp.Poly(equations[0], sp.Symbol(str(sym)))
593
- b_lo, b_hi = problem.bounds.get(str(sym), ('?', '?'))
594
- derivation.append(f" Univariate polynomial: degree {poly.degree()}, roots selected by bounds")
595
- except: pass
596
-
597
  valid = []
598
  b_mid = {v: (problem.bounds[v][0] + problem.bounds[v][1]) / 2 for v in problem.variables}
599
  for sol in raw:
@@ -662,22 +640,6 @@ def compute_sketch(problem: Problem) -> StructuralSketch:
662
  affinities["CONTINUOUS"] += 1.5
663
  notes.append("Sum-of-squares β†’ METRIC/QUADRATIC/CONTINUOUS boosted")
664
 
665
- tight = sum(1 for v in problem.variables if abs(problem.bounds[v][1] - problem.bounds[v][0]) < 10)
666
- if tight > n_vars // 2:
667
- affinities["PARSIMONY"] += 2.0
668
- notes.append("Tight bounds β†’ PARSIMONY boosted")
669
-
670
- if n_vars >= 6:
671
- affinities["HOLISM"] += 1.5
672
- affinities["NETWORK"] += 1.5
673
- notes.append(f"High-D ({n_vars} vars) β†’ HOLISM/NETWORK boosted")
674
-
675
- bound_groups = defaultdict(list)
676
- for v in problem.variables: bound_groups[problem.bounds[v]].append(v)
677
- if any(len(g) >= 2 for g in bound_groups.values()):
678
- affinities["SYMMETRIC"] += 1.5
679
- notes.append("Symmetric bounds β†’ SYMMETRIC boosted")
680
-
681
  has_transcendental = any(mc.parsed is not None and (mc.parsed.has(sp.sin) or mc.parsed.has(sp.cos) or mc.parsed.has(sp.exp)) for mc in problem.compiled_constraints)
682
  if has_transcendental:
683
  affinities["CONTINUOUS"] += 2.0
@@ -701,9 +663,7 @@ def compute_sketch(problem: Problem) -> StructuralSketch:
701
  n_obs = sum(1 for v in problem.variables if problem.bounds[v][0] == problem.bounds[v][1])
702
  n_free_dof = max(0, n_vars - n_obs - n_eq)
703
 
704
- exact_solutions = []
705
- solvable = False
706
- sympy_derivation = []
707
  if n_vars <= SYMPY_MAX_VARS and dom_type in ("linear", "quadratic") and not has_transcendental:
708
  exact_solutions, solvable, sympy_derivation = _try_sympy_solve(problem)
709
  if solvable:
@@ -722,12 +682,14 @@ def generate_templates(problem: Problem, sketch: StructuralSketch) -> List[Hypot
722
  templates = []
723
  b_mid = {v: (problem.bounds[v][0] + problem.bounds[v][1]) / 2 for v in problem.variables}
724
 
 
725
  for i, sol in enumerate(sketch.exact_solutions):
726
  templates.append(HypothesisTemplate(
727
  template_id=f"sympy_{i}", pinned_vars=sol,
728
  free_vars=[v for v in problem.variables if v not in sol],
729
  source="sympy_exact", confidence=0.99, derivation=f"SymPy exact solution #{i+1}"))
730
 
 
731
  for mc in problem.compiled_constraints:
732
  if mc.kind != "equality" or mc.weight < 5.0 or not mc.projections: continue
733
  for v, projs in mc.projections.items():
@@ -742,22 +704,55 @@ def generate_templates(problem: Problem, sketch: StructuralSketch) -> List[Hypot
742
  confidence=0.75, derivation=f"Conservation {mc.expr_str} β†’ {v}={val:.4f}"))
743
  except: pass
744
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
745
  tb = _global_hc4_tighten_bounds(problem)
746
  for v_small, v_large, k in problem.monotone_targets:
747
  lo_s, hi_s = problem.bounds.get(v_small, (-1e9, 1e9))
748
  lo_l, hi_l = problem.bounds.get(v_large, (-1e9, 1e9))
749
- for ratio in [0.1, 0.25, 0.5, 0.707, 0.9]:
750
  vs_sq = k * ratio
751
  if vs_sq <= 0: continue
752
  vs = math.sqrt(vs_sq); vl = k / vs
753
  if not (lo_s <= vs <= hi_s and lo_l <= vl <= hi_l and vs <= vl): continue
754
 
755
  nb = dict(b_mid)
756
- nb[v_small] = vs
757
- nb[v_large] = vl
758
  box = {u: IV(*tb.get(u, problem.bounds.get(u, (-10, 10)))) for u in problem.variables}
759
- box[v_small] = IV(vs - 1e-6, vs + 1e-6)
760
- box[v_large] = IV(vl - 1e-6, vl + 1e-6)
761
  cont = _hc4(box, problem.compiled_constraints)
762
 
763
  pinned = {v_small: vs, v_large: vl}
@@ -769,41 +764,13 @@ def generate_templates(problem: Problem, sketch: StructuralSketch) -> List[Hypot
769
  templates.append(HypothesisTemplate(
770
  template_id=f"mpr_{v_small}_{v_large}_r{int(ratio*100)}", pinned_vars=pinned,
771
  free_vars=[u for u in problem.variables if u not in pinned], source="monotone_prod",
772
- confidence=0.88, derivation=f"Monotone {v_small}={vs:.4f}≀{v_large}={vl:.4f}"))
773
-
774
- for mc in problem.compiled_constraints:
775
- if mc.kind != "equality" or not mc.projections: continue
776
- for v, projs in mc.projections.items():
777
- lo, hi = problem.bounds.get(v, (-1e9, 1e9))
778
- for proj in projs:
779
- try:
780
- val = float(proj["func"](*[b_mid.get(s, 0.0) for s in proj["syms"]]))
781
- if math.isfinite(val) and lo <= val <= hi:
782
- templates.append(HypothesisTemplate(
783
- template_id=f"proj_{v}_{hash(mc.expr_str)%9999}", pinned_vars={v: val},
784
- free_vars=[u for u in problem.variables if u != v], source="projection",
785
- confidence=0.72, derivation=f"Root of {mc.expr_str[:30]} β†’ {v}={val:.4f}"))
786
- except: pass
787
-
788
- bound_groups = defaultdict(list)
789
- for v in problem.variables: bound_groups[problem.bounds[v]].append(v)
790
- for bnd, grp in bound_groups.items():
791
- if len(grp) < 2: continue
792
- avg = sum(b_mid[v] for v in grp) / len(grp)
793
- lo, hi = bnd
794
- if lo <= avg <= hi:
795
- pinned = {v: avg for v in grp}
796
- templates.append(HypothesisTemplate(
797
- template_id=f"sym_avg_{'_'.join(grp[:3])}", pinned_vars=pinned,
798
- free_vars=[u for u in problem.variables if u not in pinned], source="symmetry",
799
- confidence=0.55, derivation=f"Symmetry orbit: {grp} averaged to {avg:.4f}"))
800
 
801
  seen = set(); unique = []
802
  for t in sorted(templates, key=lambda t: -t.confidence):
803
  key = str(sorted(t.pinned_vars.items()))
804
  if key not in seen:
805
- seen.add(key)
806
- unique.append(t)
807
 
808
  return unique[:TEMPLATE_BATCH_SIZE]
809
 
@@ -881,7 +848,7 @@ def _batched_deduce_and_evaluate(problem: Problem, hyps: List['Hypothesis']) ->
881
 
882
  for j, v in enumerate(problem.variables):
883
  lo, hi = problem.bounds[v]
884
- margin = (hi - lo) * 0.1 * (1.0 - step_ratio) # Exploratory bounds fade to 0
885
  X.data[:, j] = torch.clamp(X.data[:, j], lo - margin, hi + margin)
886
 
887
  optimizer.zero_grad()
@@ -1934,8 +1901,8 @@ def build_live_html():
1934
  </div>
1935
  """
1936
 
1937
- with gr.Blocks(css=CSS, title="Practicality 24.1") as demo:
1938
- gr.Markdown("## βš— Practicality 24.1 β€” Structural Sketch, World Model Prior & Quantum Engine\n`[Gemini Encoder] β†’ [Structural Sketch / SymPy] β†’ [Morphing Ray Solver] β†’ [Gemini Collapser]`")
1939
 
1940
  with gr.Row(elem_classes=["wrap-row"]):
1941
  with gr.Column(scale=2, min_width=300):
@@ -1955,12 +1922,11 @@ with gr.Blocks(css=CSS, title="Practicality 24.1") as demo:
1955
  with gr.Column(scale=1, min_width=250):
1956
  gr.Textbox(value=(f"Compute: {DEVICE.type.upper()}\n"
1957
  f"Axioms: {len(ALL_AXIOMS)}\n"
1958
- f"New: The Tensor Shield\n"
1959
- f"New: Thread Crash Safety & UI Layout Fix\n"
1960
  f"New: Quantum BBGKY Cumulant Expansion\n"
1961
- f"New: Homotopy Continuation\n"
1962
- f"New: Anchor Fix (Gate 2 Sync)"),
1963
- lines=8, interactive=False, elem_classes=["solver-log"])
1964
 
1965
  with gr.Row(elem_classes=["wrap-row"]):
1966
  with gr.Column(scale=1, min_width=300):
@@ -1982,5 +1948,5 @@ with gr.Blocks(css=CSS, title="Practicality 24.1") as demo:
1982
  demo.load(fetch_ui, inputs=None, outputs=[live_html, answer_box])
1983
 
1984
  if __name__ == "__main__":
1985
- print(f"[SYSTEM 24.1] Compute: {DEVICE.type.upper()} | Feature Flags: Quantum={HAS_QUANTUM}")
1986
  demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
 
1
  #!/usr/bin/env python3
2
  """
3
+ PRACTICALITY SYSTEM 24.2 β€” POSITIVE SPACE SKETCHING & TRANSCENDENTAL GRIDS
4
  ══════════════════════════════════════════════════════════════════════════════════
5
  ARCHITECTURE:
6
  User Text β†’ [GEMINI ENCODER] β†’ AXLProblemDef
7
  β†’ [STRUCTURAL SKETCH] β†’ Axiom affinity map + SymPy Derivation
8
+ β†’ [TEMPLATE ENGINE] β†’ Positive Space Grid Sketching + Algebraic Roots
9
+ β†’ [WISDOM LAYER] β†’ Masked Deduction (with Homotopy)
10
  β†’ [GEMINI COLLAPSER] β†’ Domain-language explanation
11
 
12
+ CRITICAL UPDATE 24.2:
13
+ - Positive Space Sketching: Dynamically detects variables trapped in highly
14
+ non-linear transcendental functions (sin, cos) and sweeps their parameter
15
+ space in the Template Engine. By pinning the non-linear axes, the remaining
16
+ system collapses into a linear manifold, allowing PyTorch to solve complex
17
+ variational circuits (QAOA/VQE) without gradient gridlock.
18
+ - Increased DEDUCE_ADAM_STEPS to 40 for deeper local convergence.
19
  """
20
 
21
+ import os, time, random, math, threading, warnings, json, textwrap, itertools
22
  from functools import reduce
23
  from typing import Optional, Callable, List, Dict, Tuple, Any, Set
24
  from dataclasses import dataclass, field
 
45
  # ══════════════════════════════════════════════════════════════════════
46
  # AI CONFIGURATION
47
  # ══════════════════════════════════════════════════════════════════════
48
+ DEFAULT_GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY", "")
49
+ GEMINI_MODEL = "gemini-2.5-pro-preview-06-05"
50
 
51
  warnings.filterwarnings("ignore")
52
  USE_GPU = torch.cuda.is_available()
53
  DEVICE = torch.device("cuda" if USE_GPU else "cpu")
54
+ print(f"[SYSTEM 24.2] Compute: {DEVICE.type.upper()} | Positive Space Sketching Active")
55
 
56
  # ══════════════════════════════════════════════════════════════════════
57
  # SECTION 1: CONSTANTS
 
59
  SOLVE_THRESHOLD = 0.05
60
  VERIFY_G1_THRESHOLD = 0.08
61
  VERIFY_G2_TOLERANCE = 1e-3
62
+ DEDUCE_ADAM_STEPS = 40 # Increased for deeper gradient convergence
63
  N_MPRT_EXPLORE = 1000
64
  PROJECTION_CACHE: Dict = {}
65
 
66
  MAX_RAYS_PER_ATTEMPT = 24576 * 10
67
  RAY_BATCH_SIZE = 24576
68
+ TEMPLATE_BATCH_SIZE = 1024 # Increased to accommodate Grid Sweeps
69
  CE_EARN_RATIO = 0.90
70
  SCOUT_CE_THRESHOLD = 0.5
71
  BRANCH_WIDTH = 12
 
82
  STATE_LOCK = threading.Lock()
83
 
84
  GLOBAL_SOLVE_STATE = {
85
+ "is_running": False, "phase": "IDLE", "best_ce": float('inf'), "total_fired": 0,
86
+ "best_ray": "β€”", "recent_traces": deque(maxlen=25), "high_level_logs": [],
87
+ "answer": "", "sketch_summary": "", "template_count": 0,
88
+ "template_best_ce": float('inf'), "sympy_derivation": [],
 
 
 
 
 
 
 
 
89
  }
90
 
91
  def _update_state(**kwargs):
92
  with STATE_LOCK:
93
+ for k, v in kwargs.items(): GLOBAL_SOLVE_STATE[k] = v
 
94
 
95
  def _add_log(line: str):
96
+ with STATE_LOCK: GLOBAL_SOLVE_STATE["high_level_logs"].append(line)
 
97
 
98
  # ══════════════════════════════════════════════════════════════════════
99
  # SECTION 3: INTERVAL ARITHMETIC (HC4)
 
360
  val = t_func_raw(*args)
361
  if not isinstance(val, torch.Tensor):
362
  try:
 
363
  val = torch.tensor(float(val), device=DEVICE, dtype=torch.float32)
364
  except Exception:
 
365
  return torch.tensor(9999.0, device=DEVICE, dtype=torch.float32)
366
  return val
367
 
 
436
  except: pass
437
 
438
  # ══════════════════════════════════════════════════════════════════════
439
+ # HOMOTOPY CONTINUATION FIX: tensor_energy scales transcendentals
440
  # ══════════════════════════════════════════════════════════════════════
441
  def tensor_energy(self, X: torch.Tensor, step_ratio: float = 1.0) -> torch.Tensor:
442
  is_batched = (X.dim() == 2)
 
446
  if getattr(mc, 'weight', 1.0) == 0.0: continue
447
 
448
  eff_weight = float(mc.weight)
 
 
449
  if step_ratio < 1.0 and any(f in mc.expr_str for f in ["sin", "cos", "exp"]):
450
  eff_weight *= (0.1 + 0.9 * step_ratio)
451
 
 
468
  else:
469
  total += torch.relu(val) * eff_weight
470
 
 
471
  for i, v in enumerate(self.variables):
472
  lo, hi = self.bounds[v]
473
  col = X[:, i] if is_batched else X[i]
474
+ margin = (hi - lo) * 0.1 * (1.0 - step_ratio)
475
  total += torch.relu(lo - margin - col) + torch.relu(col - (hi + margin))
476
 
477
  return total.squeeze()
 
508
  scope_order=ep.scope_order)
509
 
510
  # ══════════════════════════════════════════════════════════════════════
511
+ # SECTION 6: STRUCTURAL SKETCH & POSITIVE SPACE SWEEP
512
  # ══════════════════════════════════════════════════════════════════════
513
  @dataclass
514
  class StructuralSketch:
 
545
  syms = [sp.Symbol(v) for v in problem.variables]
546
  equations = [mc.parsed for mc in eq_mcs]
547
 
548
+ def _solve(): return sp.solve(equations, syms, dict=True)
 
549
 
550
  try:
551
  with concurrent.futures.ThreadPoolExecutor(max_workers=1) as ex:
 
572
  else:
573
  derivation.append(f" {sym} = {simplified} [eliminates {sym}, depends on {', '.join(str(s) for s in free_s)}]")
574
 
 
 
 
 
 
 
 
 
575
  valid = []
576
  b_mid = {v: (problem.bounds[v][0] + problem.bounds[v][1]) / 2 for v in problem.variables}
577
  for sol in raw:
 
640
  affinities["CONTINUOUS"] += 1.5
641
  notes.append("Sum-of-squares β†’ METRIC/QUADRATIC/CONTINUOUS boosted")
642
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
643
  has_transcendental = any(mc.parsed is not None and (mc.parsed.has(sp.sin) or mc.parsed.has(sp.cos) or mc.parsed.has(sp.exp)) for mc in problem.compiled_constraints)
644
  if has_transcendental:
645
  affinities["CONTINUOUS"] += 2.0
 
663
  n_obs = sum(1 for v in problem.variables if problem.bounds[v][0] == problem.bounds[v][1])
664
  n_free_dof = max(0, n_vars - n_obs - n_eq)
665
 
666
+ exact_solutions = []; solvable = False; sympy_derivation = []
 
 
667
  if n_vars <= SYMPY_MAX_VARS and dom_type in ("linear", "quadratic") and not has_transcendental:
668
  exact_solutions, solvable, sympy_derivation = _try_sympy_solve(problem)
669
  if solvable:
 
682
  templates = []
683
  b_mid = {v: (problem.bounds[v][0] + problem.bounds[v][1]) / 2 for v in problem.variables}
684
 
685
+ # ── 1. SymPy Exact Solutions
686
  for i, sol in enumerate(sketch.exact_solutions):
687
  templates.append(HypothesisTemplate(
688
  template_id=f"sympy_{i}", pinned_vars=sol,
689
  free_vars=[v for v in problem.variables if v not in sol],
690
  source="sympy_exact", confidence=0.99, derivation=f"SymPy exact solution #{i+1}"))
691
 
692
+ # ── 2. Conservation Projections
693
  for mc in problem.compiled_constraints:
694
  if mc.kind != "equality" or mc.weight < 5.0 or not mc.projections: continue
695
  for v, projs in mc.projections.items():
 
704
  confidence=0.75, derivation=f"Conservation {mc.expr_str} β†’ {v}={val:.4f}"))
705
  except: pass
706
 
707
+ # ── 3. POSITIVE SPACE SKETCHING (Transcendental Parameter Grid Sweep)
708
+ # Detects free parameters trapped in non-linear functions (like QAOA angles)
709
+ # and pins them via a grid sweep, reducing the remaining system to linear.
710
+ if sketch.has_transcendental:
711
+ transcendental_vars = set()
712
+ for mc in problem.compiled_constraints:
713
+ if mc.parsed and (mc.parsed.has(sp.sin) or mc.parsed.has(sp.cos) or mc.parsed.has(sp.exp)):
714
+ for func in mc.parsed.atoms(sp.sin, sp.cos, sp.exp):
715
+ for sym in func.free_symbols:
716
+ v_name = str(sym)
717
+ if v_name in problem.bounds:
718
+ transcendental_vars.add(v_name)
719
+
720
+ if transcendental_vars and len(transcendental_vars) <= 3:
721
+ grids = []
722
+ for v in transcendental_vars:
723
+ lo, hi = problem.bounds[v]
724
+ pts = [lo + (hi-lo)*0.15, lo + (hi-lo)*0.5, lo + (hi-lo)*0.85]
725
+ grids.append((v, pts))
726
+
727
+ keys = [g[0] for g in grids]
728
+ val_lists = [g[1] for g in grids]
729
+
730
+ for combo in itertools.product(*val_lists):
731
+ pinned = dict(zip(keys, combo))
732
+ templates.append(HypothesisTemplate(
733
+ template_id=f"grid_{'_'.join(f'{k[:2]}{v:.2f}' for k,v in pinned.items())}",
734
+ pinned_vars=pinned,
735
+ free_vars=[u for u in problem.variables if u not in pinned],
736
+ source="grid_sweep",
737
+ confidence=0.85,
738
+ derivation=f"Positive Space Sketch: Pinned non-linear parameters {pinned}"
739
+ ))
740
+
741
+ # ── 4. Monotone Product Splits
742
  tb = _global_hc4_tighten_bounds(problem)
743
  for v_small, v_large, k in problem.monotone_targets:
744
  lo_s, hi_s = problem.bounds.get(v_small, (-1e9, 1e9))
745
  lo_l, hi_l = problem.bounds.get(v_large, (-1e9, 1e9))
746
+ for ratio in [0.25, 0.5, 0.707]:
747
  vs_sq = k * ratio
748
  if vs_sq <= 0: continue
749
  vs = math.sqrt(vs_sq); vl = k / vs
750
  if not (lo_s <= vs <= hi_s and lo_l <= vl <= hi_l and vs <= vl): continue
751
 
752
  nb = dict(b_mid)
753
+ nb[v_small] = vs; nb[v_large] = vl
 
754
  box = {u: IV(*tb.get(u, problem.bounds.get(u, (-10, 10)))) for u in problem.variables}
755
+ box[v_small] = IV(vs - 1e-6, vs + 1e-6); box[v_large] = IV(vl - 1e-6, vl + 1e-6)
 
756
  cont = _hc4(box, problem.compiled_constraints)
757
 
758
  pinned = {v_small: vs, v_large: vl}
 
764
  templates.append(HypothesisTemplate(
765
  template_id=f"mpr_{v_small}_{v_large}_r{int(ratio*100)}", pinned_vars=pinned,
766
  free_vars=[u for u in problem.variables if u not in pinned], source="monotone_prod",
767
+ confidence=0.82, derivation=f"Monotone {v_small}={vs:.4f}≀{v_large}={vl:.4f}"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
768
 
769
  seen = set(); unique = []
770
  for t in sorted(templates, key=lambda t: -t.confidence):
771
  key = str(sorted(t.pinned_vars.items()))
772
  if key not in seen:
773
+ seen.add(key); unique.append(t)
 
774
 
775
  return unique[:TEMPLATE_BATCH_SIZE]
776
 
 
848
 
849
  for j, v in enumerate(problem.variables):
850
  lo, hi = problem.bounds[v]
851
+ margin = (hi - lo) * 0.1 * (1.0 - step_ratio)
852
  X.data[:, j] = torch.clamp(X.data[:, j], lo - margin, hi + margin)
853
 
854
  optimizer.zero_grad()
 
1901
  </div>
1902
  """
1903
 
1904
+ with gr.Blocks(css=CSS, title="Practicality 24.2") as demo:
1905
+ gr.Markdown("## βš— Practicality 24.2 β€” Structural Sketch, World Model Prior & Quantum Engine\n`[Gemini Encoder] β†’ [Positive Space Sketching] β†’ [Morphing Ray Solver] β†’ [Gemini Collapser]`")
1906
 
1907
  with gr.Row(elem_classes=["wrap-row"]):
1908
  with gr.Column(scale=2, min_width=300):
 
1922
  with gr.Column(scale=1, min_width=250):
1923
  gr.Textbox(value=(f"Compute: {DEVICE.type.upper()}\n"
1924
  f"Axioms: {len(ALL_AXIOMS)}\n"
1925
+ f"New: Positive Space Sketching\n"
1926
+ f"New: Transcendental Grid Sweeping\n"
1927
  f"New: Quantum BBGKY Cumulant Expansion\n"
1928
+ f"New: Homotopy Continuation"),
1929
+ lines=7, interactive=False, elem_classes=["solver-log"])
 
1930
 
1931
  with gr.Row(elem_classes=["wrap-row"]):
1932
  with gr.Column(scale=1, min_width=300):
 
1948
  demo.load(fetch_ui, inputs=None, outputs=[live_html, answer_box])
1949
 
1950
  if __name__ == "__main__":
1951
+ print(f"[SYSTEM 24.2] Compute: {DEVICE.type.upper()} | Feature Flags: Quantum={HAS_QUANTUM}")
1952
  demo.launch(server_name="0.0.0.0", server_port=7860, share=False)