Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
from minimal_self_full import MinimalSelf, MovingObstacle, SocialEntity, run_simulation, compute_phi
|
| 6 |
+
|
| 7 |
+
plt.switch_backend("Agg") # Ensure headless plotting
|
| 8 |
+
|
| 9 |
+
def run_agent(
|
| 10 |
+
steps=500,
|
| 11 |
+
epsilon=0.2,
|
| 12 |
+
learning_rate=0.1,
|
| 13 |
+
reward_type="original",
|
| 14 |
+
obstacle=False,
|
| 15 |
+
social=False,
|
| 16 |
+
seed=123
|
| 17 |
+
):
|
| 18 |
+
# Configure agent
|
| 19 |
+
agent = MinimalSelf(
|
| 20 |
+
seed=seed,
|
| 21 |
+
epsilon=epsilon,
|
| 22 |
+
learning_rate=learning_rate,
|
| 23 |
+
body_bit_reinforce_factor=0.1,
|
| 24 |
+
body_bit_decay_rate=0.01,
|
| 25 |
+
reward_type=reward_type
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# Optional entities
|
| 29 |
+
entity_actions = [
|
| 30 |
+
np.array([0, 1]), np.array([1, 0]), np.array([0, -1]), np.array([-1, 0])
|
| 31 |
+
]
|
| 32 |
+
obs = None
|
| 33 |
+
soc = None
|
| 34 |
+
if obstacle:
|
| 35 |
+
obs = MovingObstacle(start_pos=np.array([0, 0]), actions=entity_actions, seed=43)
|
| 36 |
+
if social:
|
| 37 |
+
soc = SocialEntity(start_pos=np.array([2, 2]), actions=entity_actions, seed=44)
|
| 38 |
+
|
| 39 |
+
# Run simulation
|
| 40 |
+
history = run_simulation(agent, steps, obstacle_instance=obs, social_entity_instance=soc)
|
| 41 |
+
df = pd.DataFrame(history)
|
| 42 |
+
|
| 43 |
+
# Compute final phi
|
| 44 |
+
final_phi = compute_phi(history)
|
| 45 |
+
|
| 46 |
+
# Plot metrics
|
| 47 |
+
fig1, axes = plt.subplots(4, 1, figsize=(10, 9), sharex=True)
|
| 48 |
+
metrics = ["predictive_rate", "C_min", "body_bit_strength", "reward"]
|
| 49 |
+
for i, m in enumerate(metrics):
|
| 50 |
+
if m in df.columns:
|
| 51 |
+
axes[i].plot(df["t"], df[m], label=m, color=["#2b8","#06c","#a5a","#e67"][i])
|
| 52 |
+
axes[i].set_ylabel(m)
|
| 53 |
+
axes[i].grid(True)
|
| 54 |
+
axes[i].legend()
|
| 55 |
+
else:
|
| 56 |
+
axes[i].text(0.5, 0.5, f"{m} not available", transform=axes[i].transAxes, ha="center")
|
| 57 |
+
axes[-1].set_xlabel("Time step")
|
| 58 |
+
fig1.suptitle("Metrics over time")
|
| 59 |
+
fig1.tight_layout()
|
| 60 |
+
|
| 61 |
+
# Plot path (agent + optional obstacle/social)
|
| 62 |
+
fig2, ax = plt.subplots(figsize=(6, 6))
|
| 63 |
+
ax.set_title("Agent and environment paths")
|
| 64 |
+
ax.set_xlabel("X")
|
| 65 |
+
ax.set_ylabel("Y")
|
| 66 |
+
ax.set_aspect("equal", adjustable="box")
|
| 67 |
+
ax.grid(True)
|
| 68 |
+
ax.set_xticks(np.arange(0, 3))
|
| 69 |
+
ax.set_yticks(np.arange(0, 3))
|
| 70 |
+
ax.set_xlim(-0.5, 2.5)
|
| 71 |
+
ax.set_ylim(-0.5, 2.5)
|
| 72 |
+
|
| 73 |
+
# Agent path
|
| 74 |
+
ax.plot([p[0] for p in df["position"]], [p[1] for p in df["position"]],
|
| 75 |
+
marker="o", linestyle="-", color="blue", alpha=0.7, label="Agent")
|
| 76 |
+
ax.scatter(df["position"].iloc[0][0], df["position"].iloc[0][1], color="cyan", s=80, label="Start")
|
| 77 |
+
ax.scatter(df["position"].iloc[-1][0], df["position"].iloc[-1][1], color="navy", s=80, label="End")
|
| 78 |
+
|
| 79 |
+
# Obstacle path
|
| 80 |
+
if obstacle and "obstacle_position" in df.columns:
|
| 81 |
+
ax.plot([p[0] for p in df["obstacle_position"]], [p[1] for p in df["obstacle_position"]],
|
| 82 |
+
marker="x", linestyle="--", color="red", alpha=0.6, label="Obstacle")
|
| 83 |
+
|
| 84 |
+
# Social entity path
|
| 85 |
+
if social and "social_entity_position" in df.columns:
|
| 86 |
+
ax.plot([p[0] for p in df["social_entity_position"]], [p[1] for p in df["social_entity_position"]],
|
| 87 |
+
marker="^", linestyle=":", color="green", alpha=0.6, label="Social entity")
|
| 88 |
+
|
| 89 |
+
ax.legend()
|
| 90 |
+
|
| 91 |
+
# Prepare CSV
|
| 92 |
+
csv_bytes = df.to_csv(index=False).encode("utf-8")
|
| 93 |
+
|
| 94 |
+
return (
|
| 95 |
+
gr.Plot(fig1),
|
| 96 |
+
gr.Plot(fig2),
|
| 97 |
+
f"{final_phi:.2f}",
|
| 98 |
+
csv_bytes
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
with gr.Blocks(title="RFT Minimal Self: 3×3 Agent") as demo:
|
| 102 |
+
gr.Markdown("# RFT Minimal Self: 3×3 Agent")
|
| 103 |
+
gr.Markdown("Run the 3×3 embodied agent with Q-learning, obstacles, and social mimicry. Visualize metrics, paths, and export results.")
|
| 104 |
+
|
| 105 |
+
with gr.Row():
|
| 106 |
+
steps = gr.Slider(100, 5000, value=500, step=50, label="Steps")
|
| 107 |
+
epsilon = gr.Slider(0.0, 1.0, value=0.2, step=0.05, label="Epsilon (exploration)")
|
| 108 |
+
learning_rate = gr.Slider(0.0, 1.0, value=0.1, step=0.05, label="Learning rate")
|
| 109 |
+
seed = gr.Number(value=123, label="Seed")
|
| 110 |
+
|
| 111 |
+
reward_type = gr.Radio(choices=["original", "explore_grow", "social"], value="original", label="Reward type")
|
| 112 |
+
obstacle = gr.Checkbox(value=False, label="Enable moving obstacle")
|
| 113 |
+
social = gr.Checkbox(value=False, label="Enable social entity")
|
| 114 |
+
|
| 115 |
+
run_btn = gr.Button("Run simulation")
|
| 116 |
+
|
| 117 |
+
metrics_plot = gr.Plot(label="Metrics over time")
|
| 118 |
+
path_plot = gr.Plot(label="Paths in 3×3 world")
|
| 119 |
+
final_phi = gr.Textbox(label="Final Φ_min (toy measure)", interactive=False)
|
| 120 |
+
csv_out = gr.File(label="Download results.csv", file_count="single")
|
| 121 |
+
|
| 122 |
+
run_btn.click(
|
| 123 |
+
fn=run_agent,
|
| 124 |
+
inputs=[steps, epsilon, learning_rate, reward_type, obstacle, social, seed],
|
| 125 |
+
outputs=[metrics_plot, path_plot, final_phi, csv_out]
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
if __name__ == "__main__":
|
| 129 |
+
demo.launch()
|