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| 8 |
+
"n_agents": 10,
|
| 9 |
+
"steps": 50,
|
| 10 |
+
"grid_size": 10,
|
| 11 |
+
"target": torch.tensor([5.0, 5.0])
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
# Tracker for entropy and convergence
|
| 15 |
+
class MetricsTracker:
|
| 16 |
+
def __init__(self):
|
| 17 |
+
self.entropies = []
|
| 18 |
+
self.distances = []
|
| 19 |
+
|
| 20 |
+
def record(self, positions, target):
|
| 21 |
+
center = positions.mean(dim=0)
|
| 22 |
+
distances = torch.norm(positions - center, dim=1)
|
| 23 |
+
entropy = distances.std().item()
|
| 24 |
+
self.entropies.append(entropy)
|
| 25 |
+
|
| 26 |
+
dist_to_target = torch.norm(positions - target, dim=1).mean().item()
|
| 27 |
+
self.distances.append(dist_to_target)
|
| 28 |
+
|
| 29 |
+
def plot(self):
|
| 30 |
+
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
|
| 31 |
+
ax1.plot(self.entropies, label="Entropy")
|
| 32 |
+
ax1.set_title("Entropy Over Time")
|
| 33 |
+
ax1.set_xlabel("Steps")
|
| 34 |
+
ax1.set_ylabel("Entropy")
|
| 35 |
+
|
| 36 |
+
ax2.plot(self.distances, label="Convergence")
|
| 37 |
+
ax2.set_title("Convergence to Target")
|
| 38 |
+
ax2.set_xlabel("Steps")
|
| 39 |
+
ax2.set_ylabel("Avg Distance to Target")
|
| 40 |
+
plt.tight_layout()
|
| 41 |
+
plt.show()
|
| 42 |
+
|
| 43 |
+
# Agent class
|
| 44 |
+
class Agent:
|
| 45 |
+
def __init__(self, position):
|
| 46 |
+
self.position = torch.tensor(position, dtype=torch.float32)
|
| 47 |
+
self.dna = ["∑", "Ω", "ε₀"]
|
| 48 |
+
self.entropy_thresholds = [1.5, 1.0] # Dynamic thresholds for evolution
|
| 49 |
+
|
| 50 |
+
def emit_symbol(self):
|
| 51 |
+
return self.dna[int(torch.norm(self.position - CONFIG["target"]).item()) % 3]
|
| 52 |
+
|
| 53 |
+
def evolve_dna(self, entropy):
|
| 54 |
+
if entropy > self.entropy_thresholds[0]:
|
| 55 |
+
self.dna[0] = "∑"
|
| 56 |
+
elif entropy > self.entropy_thresholds[1]:
|
| 57 |
+
self.dna[0] = "Ω"
|
| 58 |
+
else:
|
| 59 |
+
self.dna[0] = "ε₀"
|
| 60 |
+
|
| 61 |
+
def update(self, field, target):
|
| 62 |
+
self.position += 0.3 * (field - self.position) + 0.3 * (target - self.position)
|
| 63 |
+
|
| 64 |
+
# Morphic Memory
|
| 65 |
+
class MorphicMemoryCore:
|
| 66 |
+
def __init__(self, decay_rate=0.1):
|
| 67 |
+
self.memory = []
|
| 68 |
+
self.decay_rate = decay_rate
|
| 69 |
+
|
| 70 |
+
def update(self, state):
|
| 71 |
+
self.memory.append(state.clone())
|
| 72 |
+
if len(self.memory) > 50:
|
| 73 |
+
self.memory.pop(0)
|
| 74 |
+
|
| 75 |
+
def compute_field(self):
|
| 76 |
+
if not self.memory:
|
| 77 |
+
return torch.zeros(2)
|
| 78 |
+
weights = torch.exp(-self.decay_rate * torch.arange(len(self.memory), 0, -1, dtype=torch.float32))
|
| 79 |
+
weights /= weights.sum()
|
| 80 |
+
field = sum(w * s.mean(dim=0) for w, s in zip(weights, self.memory))
|
| 81 |
+
return field
|
| 82 |
+
|
| 83 |
+
# TMFS system
|
| 84 |
+
class TMFS:
|
| 85 |
+
def __init__(self, use_field=True):
|
| 86 |
+
self.use_field = use_field
|
| 87 |
+
self.agents = [Agent([np.random.rand()*CONFIG["grid_size"], np.random.rand()*CONFIG["grid_size"]]) for _ in range(CONFIG["n_agents"])]
|
| 88 |
+
self.memory = MorphicMemoryCore()
|
| 89 |
+
self.target = CONFIG["target"]
|
| 90 |
+
self.tracker = MetricsTracker()
|
| 91 |
+
|
| 92 |
+
def step(self):
|
| 93 |
+
positions = torch.stack([a.position for a in self.agents])
|
| 94 |
+
entropy_val = torch.norm(positions - positions.mean(dim=0), dim=1).std().item()
|
| 95 |
+
|
| 96 |
+
if self.use_field:
|
| 97 |
+
self.memory.update(positions)
|
| 98 |
+
field = self.memory.compute_field()
|
| 99 |
+
else:
|
| 100 |
+
field = torch.zeros(2)
|
| 101 |
+
|
| 102 |
+
for agent in self.agents:
|
| 103 |
+
agent.evolve_dna(entropy_val)
|
| 104 |
+
agent.update(field, self.target)
|
| 105 |
+
|
| 106 |
+
self.tracker.record(torch.stack([a.position for a in self.agents]), self.target)
|
| 107 |
+
|
| 108 |
+
def run(self):
|
| 109 |
+
trajectories = []
|
| 110 |
+
for _ in range(CONFIG["steps"]):
|
| 111 |
+
self.step()
|
| 112 |
+
trajectories.append(torch.stack([a.position for a in self.agents]).clone())
|
| 113 |
+
return torch.stack(trajectories), self.tracker
|
| 114 |
+
|
| 115 |
+
# Run and visualize
|
| 116 |
+
def run_simulation():
|
| 117 |
+
sim = TMFS(use_field=True)
|
| 118 |
+
traj, tracker = sim.run()
|
| 119 |
+
|
| 120 |
+
# Trajectories
|
| 121 |
+
plt.figure(figsize=(12, 6))
|
| 122 |
+
for i in range(CONFIG["n_agents"]):
|
| 123 |
+
plt.plot(traj[:, i, 0], traj[:, i, 1], label=f"Agent {i+1}")
|
| 124 |
+
plt.scatter([CONFIG["target"][0]], [CONFIG["target"][1]], c="red", label="Target")
|
| 125 |
+
plt.title("Agent Trajectories With Morphic Field")
|
| 126 |
+
plt.legend()
|
| 127 |
+
plt.grid(True)
|
| 128 |
+
plt.show()
|
| 129 |
+
|
| 130 |
+
tracker.plot()
|
| 131 |
+
|
| 132 |
+
print("Simulation complete. Final symbolic DNA:")
|
| 133 |
+
print([agent.dna for agent in sim.agents])
|
| 134 |
+
|
| 135 |
+
if __name__ == "__main__":
|
| 136 |
+
run_simulation()
|