Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,235 +1,150 @@
|
|
| 1 |
-
import numpy as np
|
| 2 |
-
import matplotlib.pyplot as plt
|
| 3 |
-
import io, base64
|
| 4 |
-
from fastapi import FastAPI
|
| 5 |
-
from fastapi.responses import HTMLResponse
|
| 6 |
-
from sklearn.decomposition import PCA
|
| 7 |
-
from sklearn.cluster import AgglomerativeClustering
|
| 8 |
-
from sklearn.metrics.pairwise import euclidean_distances
|
| 9 |
import time
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
# Mean distance (how far usually)
|
| 25 |
-
mean_dist = np.mean(dists)
|
| 26 |
-
# Standard Deviation (how chaotic/scattered)
|
| 27 |
-
std_dev = np.std(dists)
|
| 28 |
-
|
| 29 |
-
# Heuristic: We want a high score for Low Mean and Low Std Dev.
|
| 30 |
-
# We normalize based on the mean_dist itself to make it scale-invariant.
|
| 31 |
-
# If std_dev is high relative to mean_dist, score drops.
|
| 32 |
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
# "Find the strongest gravity well."
|
| 55 |
-
elif mode == 'cluster':
|
| 56 |
-
# 1. Compute Pairwise Distances to understand the "Scale" of the data
|
| 57 |
-
dist_matrix = euclidean_distances(data, data)
|
| 58 |
-
# Flatten matrix and remove zeros (self-distance) to get average spacing
|
| 59 |
-
all_dists = dist_matrix[np.triu_indices(len(data), k=1)]
|
| 60 |
-
avg_global_dist = np.mean(all_dists)
|
| 61 |
-
|
| 62 |
-
# 2. DYNAMIC THRESHOLDING
|
| 63 |
-
# We say: To belong to a group, points must be significantly closer
|
| 64 |
-
# than the global average. (e.g., 0.6 * average)
|
| 65 |
-
dynamic_thresh = avg_global_dist * 0.65
|
| 66 |
-
|
| 67 |
-
# 3. Cluster with this dynamic threshold
|
| 68 |
-
clusterer = AgglomerativeClustering(
|
| 69 |
-
n_clusters=None,
|
| 70 |
-
metric='euclidean',
|
| 71 |
-
linkage='ward',
|
| 72 |
-
distance_threshold=dynamic_thresh
|
| 73 |
-
)
|
| 74 |
-
labels = clusterer.fit_predict(data)
|
| 75 |
-
|
| 76 |
-
# 4. Find the "Best" Cluster
|
| 77 |
-
# We look for the Largest cluster, but we ignore "Noise" (clusters of size 1 or 2)
|
| 78 |
-
unique_labels, counts = np.unique(labels, return_counts=True)
|
| 79 |
|
| 80 |
-
#
|
| 81 |
-
|
|
|
|
| 82 |
|
| 83 |
-
|
| 84 |
-
# Fallback if everything is noise: treat everything as one group
|
| 85 |
-
return self.predict_point(data, mode='global')
|
| 86 |
-
|
| 87 |
-
# Pick largest of the valid clusters
|
| 88 |
-
# (You could also pick the 'densest' here, but largest is usually safest)
|
| 89 |
-
best_label = max(valid_clusters, key=lambda l: counts[np.where(unique_labels == l)][0])
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
return center, score, cluster_vectors
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
#
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
# Brute force match for visualization accuracy
|
| 146 |
-
for uv in used_vectors:
|
| 147 |
-
for i, dv in enumerate(data):
|
| 148 |
-
if np.array_equal(uv, dv):
|
| 149 |
-
is_used[i] = True
|
| 150 |
-
break
|
| 151 |
-
|
| 152 |
-
# 1. Plot IGNORED points (Grey, transparent)
|
| 153 |
-
if not np.all(is_used):
|
| 154 |
-
plt.scatter(pts_2d[~is_used, 0], pts_2d[~is_used, 1],
|
| 155 |
-
c='#555555', alpha=0.3, s=30, label='Ignored (Noise/Other)')
|
| 156 |
-
|
| 157 |
-
# 2. Plot USED points (Bright Cyan)
|
| 158 |
-
plt.scatter(pts_2d[is_used, 0], pts_2d[is_used, 1],
|
| 159 |
-
c='#00e5ff', alpha=0.8, s=40, edgecolors='none', label='Constituent Inputs')
|
| 160 |
-
|
| 161 |
-
# 3. Draw "Gravity Lines" (faint lines from used points to center)
|
| 162 |
-
# Only draw lines if there aren't too many points, to keep it clean
|
| 163 |
-
if np.sum(is_used) < 100:
|
| 164 |
-
for pt in pts_2d[is_used]:
|
| 165 |
-
plt.plot([pt[0], center_2d[0]], [pt[1], center_2d[1]],
|
| 166 |
-
c='#00e5ff', alpha=0.15, linewidth=1)
|
| 167 |
-
|
| 168 |
-
# 4. Plot The PREDICTED POINT (Red X)
|
| 169 |
-
plt.scatter(center_2d[0], center_2d[1],
|
| 170 |
-
c='#ff3366', s=200, marker='X', edgecolors='white', linewidth=1.5,
|
| 171 |
-
label='Generated Vector', zorder=10)
|
| 172 |
-
|
| 173 |
-
# Styling
|
| 174 |
-
plt.title(f"Mode: {mode.upper()} | Score: {score:.2f}/10", color='white', fontsize=12, pad=10)
|
| 175 |
-
plt.grid(True, color='#444444', linestyle='--', alpha=0.5)
|
| 176 |
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
for text in leg.get_texts():
|
| 180 |
-
text.set_color("white")
|
| 181 |
-
|
| 182 |
-
# Axis colors
|
| 183 |
-
ax.tick_params(axis='x', colors='white')
|
| 184 |
-
ax.tick_params(axis='y', colors='white')
|
| 185 |
-
for spine in ax.spines.values():
|
| 186 |
-
spine.set_edgecolor('#555555')
|
| 187 |
-
|
| 188 |
-
buf = io.BytesIO()
|
| 189 |
-
plt.savefig(buf, format='png', bbox_inches='tight')
|
| 190 |
-
plt.close()
|
| 191 |
-
return base64.b64encode(buf.getvalue()).decode('utf-8')
|
| 192 |
-
|
| 193 |
-
@app.get("/", response_class=HTMLResponse)
|
| 194 |
-
async def root():
|
| 195 |
-
img_global = generate_plot('global', 'split')
|
| 196 |
-
img_cluster = generate_plot('cluster', 'split')
|
| 197 |
-
img_tight = generate_plot('global', 'tight')
|
| 198 |
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
<div style="display:flex; flex-wrap:wrap; justify-content:center; gap:20px;">
|
| 206 |
-
<!-- SCENARIO A -->
|
| 207 |
-
<div style="background:#1e1e1e; padding:20px; border-radius:12px; border:1px solid #333;">
|
| 208 |
-
<h2 style="color:#aaa; border-bottom:1px solid #333; padding-bottom:10px;">Scenario: Split Data</h2>
|
| 209 |
-
<div style="display:flex; gap:20px;">
|
| 210 |
-
<div>
|
| 211 |
-
<h3 style="color:#00e5ff;">Global Mode</h3>
|
| 212 |
-
<div style="font-size:0.8em; color:#888; margin-bottom:5px;">Averages everything (Score -1 to 2)</div>
|
| 213 |
-
<img src="data:image/png;base64,{img_global}" width="400" style="border-radius:8px;"/>
|
| 214 |
-
</div>
|
| 215 |
-
<div>
|
| 216 |
-
<h3 style="color:#ff3366;">Cluster Mode (Revised)</h3>
|
| 217 |
-
<div style="font-size:0.8em; color:#888; margin-bottom:5px;">Identifies largest mass (Score 8 to 10)</div>
|
| 218 |
-
<img src="data:image/png;base64,{img_cluster}" width="400" style="border-radius:8px;"/>
|
| 219 |
-
</div>
|
| 220 |
-
</div>
|
| 221 |
-
</div>
|
| 222 |
-
|
| 223 |
-
<!-- SCENARIO B -->
|
| 224 |
-
<div style="background:#1e1e1e; padding:20px; border-radius:12px; border:1px solid #333;">
|
| 225 |
-
<h2 style="color:#aaa; border-bottom:1px solid #333; padding-bottom:10px;">Scenario: Converged Data</h2>
|
| 226 |
-
<div>
|
| 227 |
-
<h3 style="color:#00e5ff;">Global Mode</h3>
|
| 228 |
-
<div style="font-size:0.8em; color:#888; margin-bottom:5px;">Efficient calculation (Score ~10)</div>
|
| 229 |
-
<img src="data:image/png;base64,{img_tight}" width="400" style="border-radius:8px;"/>
|
| 230 |
-
</div>
|
| 231 |
-
</div>
|
| 232 |
-
</div>
|
| 233 |
-
</body>
|
| 234 |
-
</html>
|
| 235 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import time
|
| 2 |
+
import collections
|
| 3 |
+
import threading
|
| 4 |
+
from flask import Flask, jsonify, request
|
| 5 |
+
from flask_cors import CORS
|
| 6 |
+
|
| 7 |
+
app = Flask(__name__)
|
| 8 |
+
CORS(app)
|
| 9 |
+
|
| 10 |
+
class SimEngine:
|
| 11 |
+
def __init__(self):
|
| 12 |
+
self.nodes = {}
|
| 13 |
+
self.cells =[]
|
| 14 |
+
self.buffer = collections.deque()
|
| 15 |
+
self.running = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
# Dial Dashboard State
|
| 18 |
+
self.mode = 'inference' # 'inference' (free A&B) or 'training' (clamped A&B)
|
| 19 |
+
self.distribution = 'uniform' # 'uniform' (50/50 split) or 'individual' (vertex k-values)
|
| 20 |
+
self.problem_type = 'add' # 'add' or 'mult'
|
| 21 |
+
self.asymmetric = False # dampen retroactive pushes to prevent exploding values
|
| 22 |
|
| 23 |
+
self.reset()
|
| 24 |
+
|
| 25 |
+
def reset(self):
|
| 26 |
+
# Initialize semantic 'embeddings' in 3D latent space. X is the logic value for this simple PoC.
|
| 27 |
+
self.nodes = {
|
| 28 |
+
'A': {'x': 2.0, 'y': 1.0, 'z': 0.0, 'anchored': False, 'k': 1.0},
|
| 29 |
+
'B': {'x': 3.0, 'y': -1.0, 'z': 0.0, 'anchored': False, 'k': 0.8},
|
| 30 |
+
'C': {'x': 10.0, 'y': 0.0, 'z': 1.0, 'anchored': True, 'k': 1.0}
|
| 31 |
+
}
|
| 32 |
+
# One mesh cell connects all 3 constraints
|
| 33 |
+
self.cells =[{'id': 'Cell_1', 'a': 'A', 'b': 'B', 'c': 'C'}]
|
| 34 |
+
self.buffer.clear()
|
| 35 |
+
self.logs =[]
|
| 36 |
+
self.iteration = 0
|
| 37 |
+
|
| 38 |
+
def add_log(self, msg):
|
| 39 |
+
self.logs.insert(0, f"Iter {self.iteration}: {msg}")
|
| 40 |
+
if len(self.logs) > 50: self.logs.pop() # Keep log buffer clean
|
| 41 |
+
|
| 42 |
+
def set_problem(self, target_value):
|
| 43 |
+
# Target objective is permanently clamped
|
| 44 |
+
self.nodes['C']['x'] = float(target_value)
|
| 45 |
+
self.nodes['C']['anchored'] = True
|
| 46 |
|
| 47 |
+
if self.mode == 'training':
|
| 48 |
+
self.nodes['A']['anchored'] = True
|
| 49 |
+
self.nodes['B']['anchored'] = True
|
| 50 |
+
self.add_log(f"Training initiated. C clamped to: {target_value}")
|
| 51 |
+
else:
|
| 52 |
+
self.nodes['A']['anchored'] = False
|
| 53 |
+
self.nodes['B']['anchored'] = False
|
| 54 |
+
self.add_log(f"Inference initiated. Free mesh calculating towards: {target_value}")
|
| 55 |
+
|
| 56 |
+
self.trigger_cells() # Jumpstart event cascade
|
| 57 |
+
|
| 58 |
+
def trigger_cells(self):
|
| 59 |
+
"""Cell mathematical constraint check. Pushes structural 'error' to buffer if not solved."""
|
| 60 |
+
for cell in self.cells:
|
| 61 |
+
na, nb, nc = self.nodes[cell['a']], self.nodes[cell['b']], self.nodes[cell['c']]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
+
# Using basic arithmetic logic in Dim X for visibility
|
| 64 |
+
valA, valB, valC = na['x'], nb['x'], nc['x']
|
| 65 |
+
predictedC = (valA + valB) if self.problem_type == 'add' else (valA * valB)
|
| 66 |
|
| 67 |
+
error = predictedC - valC
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
+
if abs(error) > 0.05: # Yield Limit threshold
|
| 70 |
+
# Add retroactive tension to A and B
|
| 71 |
+
self.buffer.append({'target': cell['a'], 'error_vector': error, 'cell': cell})
|
| 72 |
+
self.buffer.append({'target': cell['b'], 'error_vector': error, 'cell': cell})
|
|
|
|
|
|
|
| 73 |
|
| 74 |
+
def physics_step(self):
|
| 75 |
+
if not self.buffer: return False # Queue is empty, logic equilibrium reached.
|
| 76 |
+
|
| 77 |
+
event = self.buffer.popleft()
|
| 78 |
+
t_id, err = event['target'], event['error_vector']
|
| 79 |
+
t_node = self.nodes[t_id]
|
| 80 |
+
|
| 81 |
+
# Ignore locked objects
|
| 82 |
+
if t_node['anchored'] and self.mode != 'training':
|
| 83 |
+
return True
|
| 84 |
+
|
| 85 |
+
# Implement Asymmetry Rule (Stop resonance explosions)
|
| 86 |
+
direction_damper = 0.3 if self.asymmetric else 1.0
|
| 87 |
+
|
| 88 |
+
if self.mode == 'inference':
|
| 89 |
+
# --- Adapt Topology Geometry ---
|
| 90 |
+
# Moves to minimize structural stress based on dials
|
| 91 |
+
base_force = (-err * 0.02 * direction_damper)
|
| 92 |
+
if self.distribution == 'uniform':
|
| 93 |
+
t_node['x'] += base_force
|
| 94 |
+
t_node['y'] -= base_force * 0.1 # visual spatial twisting
|
| 95 |
+
elif self.distribution == 'individual':
|
| 96 |
+
t_node['x'] += base_force * t_node['k']
|
| 97 |
+
|
| 98 |
+
elif self.mode == 'training':
|
| 99 |
+
# --- Learn Structural Stiffness 'K' ---
|
| 100 |
+
# Node geometry is locked. System adjusts how elastic the point is.
|
| 101 |
+
base_grad = abs(err) * 0.005 * direction_damper
|
| 102 |
+
if self.distribution == 'individual':
|
| 103 |
+
t_node['k'] -= base_grad
|
| 104 |
+
|
| 105 |
+
# Move cascaded, so tell network to re-measure stress.
|
| 106 |
+
self.trigger_cells()
|
| 107 |
+
self.iteration += 1
|
| 108 |
+
return True
|
| 109 |
+
|
| 110 |
+
engine = SimEngine()
|
| 111 |
+
|
| 112 |
+
def run_loop():
|
| 113 |
+
while True:
|
| 114 |
+
if engine.running: engine.physics_step()
|
| 115 |
+
time.sleep(0.015) # Simulated latency/Buffer cycle speed
|
| 116 |
+
|
| 117 |
+
threading.Thread(target=run_loop, daemon=True).start()
|
| 118 |
+
|
| 119 |
+
# --------- INTERFACE API ---------
|
| 120 |
+
|
| 121 |
+
@app.route('/state', methods=['GET'])
|
| 122 |
+
def get_state():
|
| 123 |
+
return jsonify({
|
| 124 |
+
'nodes': engine.nodes,
|
| 125 |
+
'buffer_size': len(engine.buffer),
|
| 126 |
+
'iteration': engine.iteration,
|
| 127 |
+
'logs': engine.logs,
|
| 128 |
+
'mode': engine.mode
|
| 129 |
+
})
|
| 130 |
+
|
| 131 |
+
@app.route('/apply_config', methods=['POST'])
|
| 132 |
+
def config():
|
| 133 |
+
data = request.json
|
| 134 |
+
engine.running = False # Pause briefly for logic change
|
| 135 |
|
| 136 |
+
engine.mode = data.get('mode', engine.mode)
|
| 137 |
+
engine.distribution = data.get('distribution', engine.distribution)
|
| 138 |
+
engine.problem_type = data.get('problem_type', engine.problem_type)
|
| 139 |
+
engine.asymmetric = data.get('asymmetric', engine.asymmetric)
|
| 140 |
+
target = data.get('target', 10.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
+
engine.set_problem(target)
|
| 143 |
+
engine.add_log(f"[DIALS CHANGED]: phase={engine.mode}, split={engine.distribution}, type={engine.problem_type}, async={engine.asymmetric}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
+
engine.running = data.get('is_running', False)
|
| 146 |
+
return jsonify(success=True)
|
| 147 |
+
|
| 148 |
+
if __name__ == '__main__':
|
| 149 |
+
print("Semantic Latent Topography Core started on :5000.")
|
| 150 |
+
app.run(port=7860, debug=True, use_reloader=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|