-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblockcode_simulator.py
More file actions
528 lines (432 loc) · 17 KB
/
Copy pathblockcode_simulator.py
File metadata and controls
528 lines (432 loc) · 17 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
"""Blockcode NFT Simulator - Interactive tesseract visualization and simulation."""
import time
import random
from typing import Dict, Any, List, Optional, Tuple
from datetime import datetime
from blockcode_nft_client import get_blockcode_nft_client
from network_nft_bridge import create_network_nft_bridge
class BlockcodeSimulator:
"""Interactive simulator for blockcode NFT system."""
def __init__(self):
"""Initialize the simulator."""
self.client = get_blockcode_nft_client(
tesseract_id="simulator",
local_vertex=[0, 0, 0, 0]
)
self.network_bridge = create_network_nft_bridge("simulator-network")
# Simulation state
self.running = False
self.step_count = 0
self.events = []
print("\n" + "="*80)
print("Blockcode NFT Simulator")
print("="*80)
print("✓ Tesseract initialized (16 vertices, 32 edges)")
print("✓ Network bridge ready")
print("="*80 + "\n")
def visualize_tesseract(self, highlight_vertices: List[List[int]] = None):
"""Visualize the tesseract with NFTs."""
highlight_vertices = highlight_vertices or []
print("\n" + "┌" + "─"*78 + "┐")
print("│" + " "*25 + "TESSERACT VISUALIZATION" + " "*30 + "│")
print("└" + "─"*78 + "┘")
# Get all NFTs
all_nfts = self.client.list_all_nfts()
nft_map = {tuple(nft['vertex']): nft for nft in all_nfts}
# Draw tesseract layers
print("\nInner Cube (t=0): Outer Cube (t=1):")
print("-"*80)
for z in [0, 1]:
print(f"\n z={z} layer:\n")
# t=0 cube
for y in [0, 1]:
line_t0 = " "
for x in [0, 1]:
vertex = [x, y, z, 0]
vertex_tuple = tuple(vertex)
if vertex_tuple in nft_map:
symbol = "●" # NFT present
if vertex in highlight_vertices:
symbol = "◉" # Highlighted NFT
else:
symbol = "○" # Empty vertex
coord = f"[{x},{y},{z},0]"
line_t0 += f"{symbol} {coord:12s} "
# t=1 cube
line_t1 = " "
for x in [0, 1]:
vertex = [x, y, z, 1]
vertex_tuple = tuple(vertex)
if vertex_tuple in nft_map:
symbol = "●"
if vertex in highlight_vertices:
symbol = "◉"
else:
symbol = "○"
coord = f"[{x},{y},{z},1]"
line_t1 += f"{symbol} {coord:12s} "
print(line_t0 + " " + line_t1)
# Legend
print("\n" + "-"*80)
print("Legend: ○ Empty ● NFT Present ◉ Highlighted")
# NFT list
if all_nfts:
print("\nNFTs in Tesseract:")
for nft in all_nfts:
print(f" • {nft['pattern_code']:20s} at {nft['vertex']}")
else:
print("\nNo NFTs in tesseract")
print()
def simulate_step(self, event_type: str = "random") -> Dict[str, Any]:
"""Simulate one step of the system.
Args:
event_type: Type of event to simulate (random, wifi, scan, peer, etc.)
Returns:
Step result dictionary
"""
self.step_count += 1
if event_type == "random":
event_type = random.choice([
"wifi_connect", "wifi_disconnect",
"network_scan", "peer_join",
"mint_nft"
])
result = {
"step": self.step_count,
"event": event_type,
"timestamp": datetime.now().isoformat(),
"changes": []
}
print(f"\n{'='*80}")
print(f"STEP {self.step_count}: {event_type.upper().replace('_', ' ')}")
print(f"{'='*80}")
# Execute event
if event_type == "mint_nft":
result.update(self._simulate_mint())
elif event_type == "wifi_connect":
result.update(self._simulate_wifi_event("connect"))
elif event_type == "wifi_disconnect":
result.update(self._simulate_wifi_event("disconnect"))
elif event_type == "network_scan":
result.update(self._simulate_network_scan())
elif event_type == "peer_join":
result.update(self._simulate_peer_join())
self.events.append(result)
# Show changes
if result.get("changes"):
print("\nChanges:")
for change in result["changes"]:
print(f" {change}")
return result
def _simulate_mint(self) -> Dict[str, Any]:
"""Simulate minting an NFT."""
# Random vertex
vertex = [random.randint(0, 1) for _ in range(4)]
# Generate pattern
spatial = random.choice(self.client.SPATIAL_CODES)
rhythm = random.choice(self.client.RHYTHM_CODES)
structure = random.choice(self.client.STRUCTURE_CODES)
transform = random.choice(self.client.TRANSFORM_CODES)
pattern = f"{spatial}.{rhythm}.{structure}.{transform}"
print(f"\nMinting NFT...")
print(f" Pattern: {pattern}")
print(f" Vertex: {vertex}")
try:
nft = self.client.mint_nft(
pattern_code=pattern,
vertex=vertex,
owner_pattern="SIM.USER.F0",
metadata={
"title": f"Simulated Track #{self.step_count}",
"simulated": True,
"step": self.step_count
}
)
return {
"success": True,
"nft": nft,
"changes": [f"✓ Minted {pattern} at {vertex}"]
}
except Exception as e:
return {
"success": False,
"error": str(e),
"changes": [f"✗ Mint failed: {e}"]
}
def _simulate_wifi_event(self, event: str) -> Dict[str, Any]:
"""Simulate WiFi connect/disconnect."""
all_nfts = self.client.list_all_nfts()
if not all_nfts:
return {
"success": False,
"changes": ["No NFTs to evolve"]
}
# Pick random NFT
nft = random.choice(all_nfts)
pattern = nft['pattern_code']
print(f"\nWiFi {event} event")
print(f" Evolving: {pattern}")
try:
evolved = self.network_bridge.evolve_nft_on_wifi_change(pattern, event)
return {
"success": True,
"evolved_nft": evolved,
"changes": [
f"✓ {pattern} evolved via T-edge",
f" {nft['vertex']} → {evolved['vertex']}"
]
}
except Exception as e:
return {
"success": False,
"error": str(e),
"changes": [f"✗ Evolution failed: {e}"]
}
def _simulate_network_scan(self) -> Dict[str, Any]:
"""Simulate network scan completion."""
all_nfts = self.client.list_all_nfts()
if not all_nfts:
return {
"success": False,
"changes": ["No NFTs to move"]
}
# Pick random NFT
nft = random.choice(all_nfts)
pattern = nft['pattern_code']
current_vertex = nft['vertex']
# Toggle X coordinate
new_vertex = current_vertex.copy()
new_vertex[0] = 1 if current_vertex[0] == 0 else 0
print(f"\nNetwork scan completed")
print(f" Moving: {pattern}")
print(f" Path: {current_vertex} → {new_vertex}")
try:
transfer = self.client.transfer_nft(
pattern_code=pattern,
from_vertex=current_vertex,
to_vertex=new_vertex,
new_owner_pattern=nft['owner_pattern']
)
return {
"success": True,
"transfer": transfer,
"changes": [
f"✓ {pattern} moved via X-edge",
f" {current_vertex} → {new_vertex}"
]
}
except Exception as e:
return {
"success": False,
"error": str(e),
"changes": [f"✗ Transfer failed: {e}"]
}
def _simulate_peer_join(self) -> Dict[str, Any]:
"""Simulate peer joining network."""
all_nfts = self.client.list_all_nfts()
if not all_nfts:
return {
"success": False,
"changes": ["No NFTs to move"]
}
# Pick random NFT
nft = random.choice(all_nfts)
pattern = nft['pattern_code']
current_vertex = nft['vertex']
# Toggle Y coordinate
new_vertex = current_vertex.copy()
new_vertex[1] = 1 if current_vertex[1] == 0 else 0
print(f"\nPeer joined network")
print(f" Moving: {pattern}")
print(f" Path: {current_vertex} → {new_vertex}")
try:
transfer = self.client.transfer_nft(
pattern_code=pattern,
from_vertex=current_vertex,
to_vertex=new_vertex,
new_owner_pattern=nft['owner_pattern']
)
return {
"success": True,
"transfer": transfer,
"changes": [
f"✓ {pattern} moved via Y-edge",
f" {current_vertex} → {new_vertex}"
]
}
except Exception as e:
return {
"success": False,
"error": str(e),
"changes": [f"✗ Transfer failed: {e}"]
}
def run_simulation(self, steps: int = 10, delay: float = 1.0):
"""Run simulation for N steps.
Args:
steps: Number of steps to simulate
delay: Delay between steps in seconds
"""
print(f"\nStarting simulation: {steps} steps")
print("Press Ctrl+C to stop\n")
self.running = True
try:
for i in range(steps):
if not self.running:
break
# Simulate step
self.simulate_step("random")
# Visualize after each step
self.visualize_tesseract()
# Delay
if i < steps - 1:
time.sleep(delay)
except KeyboardInterrupt:
print("\n\nSimulation interrupted")
self.running = False
# Final stats
self.show_statistics()
def interactive_mode(self):
"""Run interactive simulation mode."""
print("\nInteractive Mode")
print("-"*80)
print("Commands:")
print(" m - Mint NFT")
print(" c - WiFi Connect")
print(" d - WiFi Disconnect")
print(" s - Network Scan")
print(" p - Peer Join")
print(" r - Random Event")
print(" v - Visualize Tesseract")
print(" t - Show Statistics")
print(" q - Quit")
print("-"*80 + "\n")
while True:
try:
cmd = input("Command: ").strip().lower()
if cmd == 'q':
print("Exiting...")
break
elif cmd == 'm':
self.simulate_step("mint_nft")
elif cmd == 'c':
self.simulate_step("wifi_connect")
elif cmd == 'd':
self.simulate_step("wifi_disconnect")
elif cmd == 's':
self.simulate_step("network_scan")
elif cmd == 'p':
self.simulate_step("peer_join")
elif cmd == 'r':
self.simulate_step("random")
elif cmd == 'v':
self.visualize_tesseract()
elif cmd == 't':
self.show_statistics()
else:
print("Unknown command")
except KeyboardInterrupt:
print("\n\nExiting...")
break
except EOFError:
print("\n\nExiting...")
break
def show_statistics(self):
"""Show simulation statistics."""
print("\n" + "="*80)
print("SIMULATION STATISTICS")
print("="*80)
all_nfts = self.client.list_all_nfts()
stats = self.client.get_tesseract_stats()
print(f"\nSteps Executed: {self.step_count}")
print(f"Total NFTs: {stats['total_nfts']}")
print(f"Occupied Vertices: {stats['occupied_vertices']}/{stats['max_vertices']}")
# Event breakdown
event_counts = {}
for event in self.events:
event_type = event.get('event', 'unknown')
event_counts[event_type] = event_counts.get(event_type, 0) + 1
if event_counts:
print("\nEvent Breakdown:")
for event_type, count in sorted(event_counts.items()):
print(f" {event_type:20s}: {count}")
# NFT distribution
if all_nfts:
print("\nNFT Distribution:")
for vertex_str, count in stats['distribution'].items():
print(f" {vertex_str:15s}: {count} NFT(s)")
# Transfer statistics
total_transfers = sum(len(nft['transfer_history']) for nft in all_nfts)
if total_transfers > 0:
print(f"\nTotal Transfers: {total_transfers}")
avg_transfers = total_transfers / len(all_nfts)
print(f"Average Transfers per NFT: {avg_transfers:.2f}")
print("="*80 + "\n")
def demo_mode(self):
"""Run a pre-scripted demo."""
print("\nDemo Mode - Blockcode NFT System")
print("="*80)
print("This demo will:")
print(" 1. Mint 3 NFTs at different vertices")
print(" 2. Simulate WiFi connect (temporal evolution)")
print(" 3. Simulate network scan (spatial movement)")
print(" 4. Simulate peer join (spatial movement)")
print(" 5. Show final state")
print("="*80 + "\n")
input("Press Enter to start...")
# Step 1: Mint NFTs
print("\n" + "─"*80)
print("Phase 1: Minting NFTs")
print("─"*80)
for i in range(3):
self.simulate_step("mint_nft")
time.sleep(0.5)
self.visualize_tesseract()
input("\nPress Enter to continue...")
# Step 2: WiFi connect
print("\n" + "─"*80)
print("Phase 2: WiFi Connection Event")
print("─"*80)
self.simulate_step("wifi_connect")
self.visualize_tesseract()
input("\nPress Enter to continue...")
# Step 3: Network scan
print("\n" + "─"*80)
print("Phase 3: Network Scan")
print("─"*80)
self.simulate_step("network_scan")
self.visualize_tesseract()
input("\nPress Enter to continue...")
# Step 4: Peer join
print("\n" + "─"*80)
print("Phase 4: Peer Joins Network")
print("─"*80)
self.simulate_step("peer_join")
self.visualize_tesseract()
# Final stats
print("\n" + "─"*80)
print("Demo Complete!")
print("─"*80)
self.show_statistics()
def main():
"""Main entry point for simulator."""
import sys
simulator = BlockcodeSimulator()
# Check command line args
if len(sys.argv) > 1:
mode = sys.argv[1]
if mode == "--demo":
simulator.demo_mode()
elif mode == "--auto":
steps = int(sys.argv[2]) if len(sys.argv) > 2 else 10
delay = float(sys.argv[3]) if len(sys.argv) > 3 else 1.0
simulator.run_simulation(steps, delay)
elif mode == "--interactive":
simulator.interactive_mode()
else:
print(f"Unknown mode: {mode}")
print("Usage: python blockcode_simulator.py [--demo|--auto|--interactive]")
else:
# Default: interactive mode
simulator.interactive_mode()
if __name__ == "__main__":
main()