π§ Neural Network Visualization | π Synapses Fire with Each Improvement
"""
def create_3d_landscape():
"""Create an animated 3D fitness landscape."""
# Create mesh grid
x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
X, Y = np.meshgrid(x, y)
# Create landscape with multiple peaks
Z = np.sin(np.sqrt(X**2 + Y**2)) / np.sqrt(X**2 + Y**2 + 1)
Z += 0.5 * np.exp(-((X-2)**2 + (Y-2)**2) / 3)
Z += 0.8 * np.exp(-((X+2)**2 + (Y-1)**2) / 2)
fig = go.Figure(data=[go.Surface(
x=X, y=Y, z=Z,
colorscale=[
[0, '#0A0A2A'],
[0.5, '#7B3FF2'],
[1, '#00FF88']
],
opacity=0.9,
lighting=dict(
ambient=0.4,
diffuse=0.5,
specular=0.2,
roughness=0.5,
fresnel=0.2
),
lightposition=dict(x=-100, y=-100, z=50)
)])
# Add moving points representing evolving programs
if state["fitness_history"]:
n_points = min(len(state["fitness_history"]), 10)
for i in range(n_points):
t = i / max(n_points - 1, 1)
fitness = state["fitness_history"][-(n_points-i)]
# Spiral path
angle = t * 4 * np.pi
radius = 3 * (1 - t)
x_pos = radius * np.cos(angle)
y_pos = radius * np.sin(angle)
z_pos = fitness - 0.9
fig.add_trace(go.Scatter3d(
x=[x_pos], y=[y_pos], z=[z_pos],
mode='markers',
marker=dict(
size=10,
color='#FFD700' if i == n_points - 1 else '#00FF88',
symbol='diamond'
),
showlegend=False
))
fig.update_layout(
scene=dict(
xaxis=dict(showgrid=False, showticklabels=False, title=''),
yaxis=dict(showgrid=False, showticklabels=False, title=''),
zaxis=dict(showgrid=True, title='Fitness'),
camera=dict(
eye=dict(x=1.5, y=1.5, z=1.5),
up=dict(x=0, y=0, z=1)
),
aspectmode='cube'
),
paper_bgcolor='#0A0A2A',
plot_bgcolor='#0A0A2A',
height=500,
margin=dict(l=0, r=0, t=0, b=0)
)
return fig
def create_fitness_chart():
"""Create animated fitness progress chart."""
fig = go.Figure()
if state["fitness_history"]:
x = list(range(len(state["fitness_history"])))
y = state["fitness_history"]
# Main line
fig.add_trace(go.Scatter(
x=x, y=y,
mode='lines+markers',
name='Fitness',
line=dict(color='#00FF88', width=4),
marker=dict(size=8, color='#7B3FF2', line=dict(color='#00FF88', width=2))
))
# Add glow effect
fig.add_trace(go.Scatter(
x=x, y=y,
mode='lines',
line=dict(color='#00FF88', width=12),
opacity=0.3,
showlegend=False
))
fig.update_layout(
xaxis=dict(
title='Generation',
gridcolor='#333',
zerolinecolor='#333'
),
yaxis=dict(
title='Fitness Score',
gridcolor='#333',
zerolinecolor='#333',
range=[0.9, 1.0]
),
paper_bgcolor='#0A0A2A',
plot_bgcolor='#0A0A2A',
font=dict(color='#FFF'),
height=400,
showlegend=False
)
return fig
def update_multiplayer():
"""Update multiplayer state with other players' progress."""
if not state["multiplayer_active"]:
return
# Simulate other players making progress
for player in FAKE_PLAYERS:
if random.random() < 0.3: # 30% chance of improvement
improvement = random.uniform(0.001, 0.01)
player["fitness"] = min(player["fitness"] + improvement, 0.9999)
# Check if someone beat us
current_fitness = state["fitness_history"][-1] if state["fitness_history"] else 0.9333
if player["fitness"] > current_fitness and player["fitness"] > state["global_best"]:
state["global_best"] = player["fitness"]
state["events"].append({
"time": datetime.now().strftime("%H:%M:%S"),
"type": "multiplayer",
"message": f"β‘ {player['name']} {player['country']} TOOK THE LEAD! ({player['fitness']:.4f})"
})
def format_multiplayer_leaderboard():
"""Format live multiplayer leaderboard."""
current_fitness = state["fitness_history"][-1] if state["fitness_history"] else 0.9333
# Combine all players
all_players = [{"name": state["player_name"], "country": "π΄", "fitness": current_fitness, "status": "you"}]
all_players.extend(FAKE_PLAYERS)
# Sort by fitness
all_players.sort(key=lambda x: x["fitness"], reverse=True)
html = '''
π LIVE GLOBAL LEADERBOARD
'''
for i, player in enumerate(all_players):
rank = i + 1
medal = "π₯" if rank == 1 else "π₯" if rank == 2 else "π₯" if rank == 3 else f"#{rank}"
is_you = player["status"] == "you"
bg_color = "linear-gradient(45deg, #FFD700, #FFA500)" if is_you else "rgba(123, 63, 242, 0.2)"
border = "2px solid #FFD700" if rank == 1 else "1px solid rgba(255, 255, 255, 0.1)"
html += f'''
{medal} {player['country']} {player['name']}
{' (YOU)' if is_you else ''}
{player['fitness']:.4f}
{'
π₯ YOUR POSITION
' if is_you else ''}
'''
html += '''
'''
return html
def handle_boss_defeat():
"""Handle boss defeat and reach 100% fitness."""
if state["boss_active"] and state["boss_health"] <= 0:
state["boss_defeated"] = True
state["boss_active"] = False
state["fitness_history"].append(1.0) # 100% fitness!
state["events"].append({
"time": datetime.now().strftime("%H:%M:%S"),
"type": "victory",
"message": "π BOSS DEFEATED! You've achieved 100% FITNESS! PERFECTION ATTAINED!"
})
# Unlock special achievement
if "perfection_plus" not in state["achievements"]:
state["achievements"].append("perfection_plus")
state["events"].append({
"time": datetime.now().strftime("%H:%M:%S"),
"type": "achievement",
"message": "π LEGENDARY ACHIEVEMENT: Perfection Plus Ultra!"
})
return True
return False
def simulate_evolution():
"""Simulate one evolution step."""
if not state["running"]:
return
state["iteration"] += 1
# Update multiplayer if active
if state["multiplayer_active"]:
update_multiplayer()
# Simulate evaluating multiple variants (Modal parallel execution)
variants_this_gen = random.randint(4, 8) # Simulating parallel evaluation
state["variants_evaluated"] += variants_this_gen
# Simulate fitness improvement
current_fitness = state["fitness_history"][-1]
improvement = random.uniform(0.001, 0.015) * (1 - current_fitness)
new_fitness = min(current_fitness + improvement, 0.9999)
state["fitness_history"].append(new_fitness)
# Check for new achievements
new_achievements = check_achievements()
# Add event
event = {
"time": datetime.now().strftime("%H:%M:%S"),
"type": "improvement" if improvement > 0.005 else "minor",
"message": f"Generation {state['iteration']}: Fitness {new_fitness:.4f} (+{improvement:.4f}) - {variants_this_gen} variants evaluated"
}
state["events"].append(event)
# Add achievement events
for ach in new_achievements:
state["events"].append({
"time": datetime.now().strftime("%H:%M:%S"),
"type": "achievement",
"message": f"π ACHIEVEMENT UNLOCKED: {ach['name']}"
})
# Trigger quantum effects at high fitness levels
if new_fitness >= 0.95 and current_fitness < 0.95:
state["events"].append({
"time": datetime.now().strftime("%H:%M:%S"),
"type": "quantum",
"message": "βοΈ QUANTUM REALM ENTERED! Reality is bending..."
})
if new_fitness >= 0.99 and current_fitness < 0.99:
state["events"].append({
"time": datetime.now().strftime("%H:%M:%S"),
"type": "boss",
"message": "πΎ FINAL BOSS APPEARED: The Local Optimum! Click on it to attack!"
})
# Trigger boss battle
state["boss_active"] = True
state["boss_health"] = 100
# Boss battle progress
if state["boss_active"] and state["boss_health"] > 0:
# Boss slowly damages our fitness
damage = random.uniform(0.0001, 0.0005)
new_fitness = max(0.98, new_fitness - damage)
state["fitness_history"][-1] = new_fitness
return event
def get_evolved_code():
"""Generate example of evolved code with improvements."""
iteration = state.get("iteration", 0)
fitness = state["fitness_history"][-1] if state["fitness_history"] else 0.9333
# Base code
base_code = '''def create_model(X_train, y_train):
"""Create and train a DecisionTree model."""
model = DecisionTreeClassifier(
max_depth=3,
min_samples_split=2,
random_state=42
)
model.fit(X_train, y_train)
return model'''
# Evolved improvements based on iteration
if iteration == 0:
return base_code, base_code, []
improvements = []
evolved_code = base_code
if iteration >= 1:
evolved_code = evolved_code.replace("max_depth=3", "max_depth=5")
improvements.append("β Increased max_depth: 3 β 5")
if iteration >= 2:
evolved_code = evolved_code.replace("min_samples_split=2", "min_samples_split=5")
improvements.append("β Optimized min_samples_split: 2 β 5")
if iteration >= 3:
evolved_code = evolved_code.replace(
"model = DecisionTreeClassifier(",
"model = DecisionTreeClassifier(\n criterion='entropy',"
)
improvements.append("+ Added entropy criterion")
if iteration >= 4:
evolved_code = evolved_code.replace("random_state=42", "random_state=42,\n min_samples_leaf=2")
improvements.append("+ Added min_samples_leaf constraint")
return base_code, evolved_code, improvements
def format_code_display():
"""Format code evolution display with syntax highlighting."""
original, evolved, improvements = get_evolved_code()
html = f'''
𧬠Code Evolution
Original Code
{original}
Evolved Code (Gen {state.get("iteration", 0)})
{evolved}
β¨ Improvements Applied:
{"".join(f'
β’ {imp}
' for imp in improvements) if improvements else '
β’ Analyzing code patterns...
'}
'''
return html
def check_achievements():
"""Check and award achievements."""
new_achievements = []
# First evolution
if state["iteration"] >= 1 and "first_evolution" not in state["achievements"]:
state["achievements"].append("first_evolution")
new_achievements.append(ACHIEVEMENTS["first_evolution"])
# Fitness achievements
current_fitness = state["fitness_history"][-1] if state["fitness_history"] else 0
if current_fitness >= 0.95 and "fast_learner" not in state["achievements"]:
state["achievements"].append("fast_learner")
new_achievements.append(ACHIEVEMENTS["fast_learner"])
if current_fitness >= 0.99 and "perfectionist" not in state["achievements"]:
state["achievements"].append("perfectionist")
new_achievements.append(ACHIEVEMENTS["perfectionist"])
# Speed achievement
if state["start_time"] and state["variants_evaluated"] > 0:
elapsed = time.time() - state["start_time"]
if elapsed > 0:
speed = state["variants_evaluated"] / elapsed
if speed >= 10 and "speed_demon" not in state["achievements"]:
state["achievements"].append("speed_demon")
new_achievements.append(ACHIEVEMENTS["speed_demon"])
# Marathon achievement
if state["iteration"] >= 10 and "marathon" not in state["achievements"]:
state["achievements"].append("marathon")
new_achievements.append(ACHIEVEMENTS["marathon"])
# Update high score
if current_fitness > state["high_score"]:
state["high_score"] = current_fitness
return new_achievements
def format_achievements():
"""Format achievements display."""
html = '
'
html += '
π Achievements
'
html += '
'
for ach_id in state["achievements"]:
ach = ACHIEVEMENTS.get(ach_id, {})
html += f'''
{ach.get("name", "")}
{ach.get("desc", "")}
'''
if not state["achievements"]:
html += '
Start evolving to unlock achievements!
'
html += '
'
html += f'
High Score: {state["high_score"]:.4f}
'
html += '
'
return html
def get_share_text():
"""Generate share text for social media."""
fitness = state["fitness_history"][-1] if state["fitness_history"] else 0.9333
achievements_count = len(state["achievements"])
text = f"π Evolution Aurora: I evolved AI to {fitness:.2%} fitness with {achievements_count} achievements unlocked! Can you beat my score?\n\n"
text += "Try it yourself: https://huggingface.co/spaces/Agents-MCP-Hackathon/Evolution\n"
text += "#EvolutionAurora #AIEvolution #HuggingFace"
return text
def format_events():
"""Format events for display."""
html = '