-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer.py
More file actions
287 lines (242 loc) · 8.28 KB
/
Copy pathrenderer.py
File metadata and controls
287 lines (242 loc) · 8.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
"""
renderer.py — Terminal visualization for The Belief Engine.
Renders a live 2D ideological map of the agent population using ANSI escape
codes. No curses, no external libs. Pure stdout manipulation.
Layout:
+----- Ideological Map (60x28) -----+----- Event Log (38x28) -----+
| | |
| [agent glyphs in belief space] | [scrolling encounter log] |
| | |
+-----------------------------------+------------------------------+
| Stats bar: step / polarization / echo chambers / cascades |
+------------------------------------------------------------------+
The 2D projection uses a manual 2-component projection:
x-axis: "individualism" = (autonomy - loyalty + authority*-1) / 3
y-axis: "traditionalism" = (tradition + purity - progress) / 3
"""
from __future__ import annotations
import sys
import os
import time
import math
from typing import List, Optional, Tuple
from agent import Agent
from dynamics import PopulationMetrics, Event, detect_echo_chambers
from config import (
MAP_WIDTH, MAP_HEIGHT, LOG_WIDTH, LOG_MAX_LINES,
DISPLAY_WIDTH, DISPLAY_HEIGHT, REFRESH_DELAY_MS,
BELIEF_TOPICS,
)
# ANSI color codes
class C:
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
MAGENTA= "\033[95m"
CYAN = "\033[96m"
WHITE = "\033[97m"
GRAY = "\033[90m"
BG_DARK= "\033[40m"
# Personality → color mapping
PERSONALITY_COLORS = {
"open_minded": C.GREEN,
"dogmatic": C.RED,
"contrarian": C.MAGENTA,
"pragmatist": C.YELLOW,
"social_mirror": C.CYAN,
}
PERSONALITY_GLYPHS = {
"open_minded": "o",
"dogmatic": "#",
"contrarian": "!",
"pragmatist": "p",
"social_mirror": "m",
}
OUTCOME_COLORS = {
"persuaded": C.GREEN,
"nudged": C.CYAN,
"entrenched": C.RED,
"rebelled": C.MAGENTA,
}
def _project_agent(agent: Agent) -> Tuple[float, float]:
"""
Project agent's beliefs to 2D coordinates.
x: individualism dimension
y: traditionalism dimension
Returns values in [-1, 1].
"""
b = agent.beliefs
def s(topic: str) -> float:
return b.stance(topic)
# Individualism: high autonomy, low loyalty, against authority
x = (s("autonomy") - s("loyalty") - s("authority")) / 3.0
# Traditionalism: high tradition + purity, low progress
y = (s("tradition") + s("purity") - s("progress")) / 3.0
return x, y
def _to_map_coords(x: float, y: float) -> Tuple[int, int]:
"""Convert [-1,1] to map pixel coordinates."""
px = int((x + 1.0) / 2.0 * (MAP_WIDTH - 2)) + 1
py = int((1.0 - (y + 1.0) / 2.0) * (MAP_HEIGHT - 2)) + 1
px = max(1, min(MAP_WIDTH - 2, px))
py = max(1, min(MAP_HEIGHT - 2, py))
return px, py
def render_frame(
agents: List[Agent],
metrics: PopulationMetrics,
events: List[Event],
step: int,
total_steps: int,
) -> str:
"""
Build the full frame as a string.
Returns the string to be printed.
"""
# --- Build the map grid ---
grid = [[" "] * MAP_WIDTH for _ in range(MAP_HEIGHT)]
# Draw border
for x in range(MAP_WIDTH):
grid[0][x] = "-"
grid[MAP_HEIGHT - 1][x] = "-"
for y in range(MAP_HEIGHT):
grid[y][0] = "|"
grid[y][MAP_WIDTH - 1] = "|"
grid[0][0] = "+"
grid[0][MAP_WIDTH - 1] = "+"
grid[MAP_HEIGHT - 1][0] = "+"
grid[MAP_HEIGHT - 1][MAP_WIDTH - 1] = "+"
# Axis labels (center markers)
mid_x = MAP_WIDTH // 2
mid_y = MAP_HEIGHT // 2
for y in range(1, MAP_HEIGHT - 1):
if grid[y][mid_x] == " ":
grid[y][mid_x] = "·"
for x in range(1, MAP_WIDTH - 1):
if grid[mid_y][x] == " ":
grid[mid_y][x] = "·"
grid[mid_y][mid_x] = "+"
# Detect echo chambers for coloring
chambers = detect_echo_chambers(agents)
agent_chamber: dict = {}
for ci, ch in enumerate(chambers):
for a in ch:
agent_chamber[a.id] = ci
# Place agents on map
agent_colors: dict = {} # grid coords -> (char, color)
for agent in agents:
x, y = _project_agent(agent)
px, py = _to_map_coords(x, y)
glyph = PERSONALITY_GLYPHS[agent.personality]
color = PERSONALITY_COLORS[agent.personality]
# Agents in echo chambers get bold
if agent.id in agent_chamber:
color = C.BOLD + color
key = (py, px)
if key in agent_colors:
# Collision: show density with '*'
agent_colors[key] = ("*", C.WHITE + C.BOLD)
else:
agent_colors[key] = (glyph, color)
# --- Build the event log ---
log_lines = []
recent = events[-(LOG_MAX_LINES):]
for ev in recent:
outcome_color = OUTCOME_COLORS.get(ev.outcome, C.WHITE)
line = (
f"{C.GRAY}[{ev.step:3d}]{C.RESET} "
f"{ev.agent_a[:5]:<5}{C.DIM}↔{C.RESET}{ev.agent_b[:5]:<5} "
f"{C.CYAN}{ev.topic[:6]:<6}{C.RESET} "
f"{outcome_color}{ev.outcome:<10}{C.RESET}"
)
log_lines.append(line)
# Pad log to full height
while len(log_lines) < MAP_HEIGHT - 2:
log_lines.append("")
# --- Assemble frame lines ---
lines = []
# Title bar
progress = step / max(1, total_steps)
bar_filled = int(progress * 30)
progress_bar = "[" + "#" * bar_filled + "-" * (30 - bar_filled) + "]"
title = (
f"{C.BOLD}{C.CYAN}THE BELIEF ENGINE{C.RESET} "
f"step {C.YELLOW}{step:3d}{C.RESET}/{total_steps} "
f"{progress_bar} "
f"pol={C.RED}{metrics.polarization:.3f}{C.RESET} "
f"echo={C.MAGENTA}{metrics.echo_chambers}{C.RESET} "
f"conf={C.GREEN}{metrics.mean_confidence:.2f}{C.RESET}"
)
lines.append(title)
lines.append("")
# Axis labels
map_header = (
f"{C.DIM}{'TRADITIONAL':^{MAP_WIDTH}}{C.RESET}"
)
log_header = (
f"{C.DIM}{'ENCOUNTER LOG':^{LOG_WIDTH}}{C.RESET}"
)
lines.append(map_header + " " + log_header)
# Map rows + log rows side by side
for row_idx in range(MAP_HEIGHT):
# Map row
map_row_chars = []
for col_idx in range(MAP_WIDTH):
key = (row_idx, col_idx)
if key in agent_colors:
ch, color = agent_colors[key]
map_row_chars.append(color + ch + C.RESET)
else:
c = grid[row_idx][col_idx]
if c in ("·", "+"):
map_row_chars.append(C.DIM + c + C.RESET)
elif c in ("|", "-"):
map_row_chars.append(C.GRAY + c + C.RESET)
else:
map_row_chars.append(c)
map_row = "".join(map_row_chars)
# Left/right axis label
if row_idx == 1:
left_label = C.DIM + "PROG" + C.RESET
elif row_idx == MAP_HEIGHT - 2:
left_label = C.DIM + "TRAD" + C.RESET
elif row_idx == MAP_HEIGHT // 2:
left_label = C.DIM + " MID" + C.RESET
else:
left_label = " "
# Log row
log_row_idx = row_idx - 1
if 0 <= log_row_idx < len(log_lines):
log_row = log_lines[log_row_idx]
else:
log_row = ""
lines.append(f"{left_label} {map_row} {log_row}")
# Bottom x-axis labels
lines.append(
f" {C.DIM}{'COLLECTIVE':<{MAP_WIDTH//2}}{'INDIVIDUAL':>{MAP_WIDTH//2}}{C.RESET}"
)
lines.append("")
# Legend
legend_parts = []
for pers, glyph in PERSONALITY_GLYPHS.items():
color = PERSONALITY_COLORS[pers]
legend_parts.append(f"{color}{glyph}{C.RESET}={pers[:4]}")
lines.append(" " + " ".join(legend_parts) + f" {C.WHITE + C.BOLD}*{C.RESET}=crowd")
lines.append(
f" {C.BOLD}Echo chambers{C.RESET}: agents with matching beliefs cluster — watch for herding"
)
return "\n".join(lines)
def clear_screen() -> None:
sys.stdout.write("\033[2J\033[H")
sys.stdout.flush()
def move_to_top() -> None:
sys.stdout.write("\033[H")
sys.stdout.flush()
def hide_cursor() -> None:
sys.stdout.write("\033[?25l")
sys.stdout.flush()
def show_cursor() -> None:
sys.stdout.write("\033[?25h")
sys.stdout.flush()