/
chap06.ipynb
754 lines (754 loc) · 18.3 KB
/
chap06.ipynb
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Game of Life\n",
"\n",
"Code examples from [Think Complexity, 2nd edition](https://thinkcomplex.com).\n",
"\n",
"Copyright 2016 Allen Downey, [MIT License](http://opensource.org/licenses/MIT)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from os.path import basename, exists\n",
"\n",
"def download(url):\n",
" filename = basename(url)\n",
" if not exists(filename):\n",
" from urllib.request import urlretrieve\n",
" local, _ = urlretrieve(url, filename)\n",
" print('Downloaded ' + local)\n",
" \n",
"download('https://github.com/AllenDowney/ThinkComplexity2/raw/master/notebooks/utils.py')"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"from utils import savefig\n",
"# make a directory for figures\n",
"!mkdir -p figs"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Game of Life entities\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"download('https://github.com/AllenDowney/ThinkComplexity2/raw/master/notebooks/Cell2D.py')"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"from scipy.signal import correlate2d\n",
"from Cell2D import Cell2D\n",
"\n",
"class Life(Cell2D):\n",
" \"\"\"Implementation of Conway's Game of Life.\"\"\"\n",
" kernel = np.array([[1, 1, 1],\n",
" [1,10, 1],\n",
" [1, 1, 1]])\n",
"\n",
" table = np.zeros(20, dtype=np.uint8)\n",
" table[[3, 12, 13]] = 1\n",
"\n",
" def step(self):\n",
" \"\"\"Executes one time step.\"\"\"\n",
" c = correlate2d(self.array, self.kernel, mode='same')\n",
" self.array = self.table[c]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following function creates a `Life` object and sets the initial condition using strings of `0` and `1` characters."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"def make_life(n, m, row, col, *strings):\n",
" \"\"\"Makes a Life object.\n",
" \n",
" n, m: rows and columns of the Life array\n",
" row, col: upper left coordinate of the cells to be added\n",
" strings: list of strings of '0' and '1'\n",
" \"\"\"\n",
" life = Life(n, m)\n",
" life.add_cells(row, col, *strings)\n",
" return life"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A beehive is a stable entity, also called a \"still life\""
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"# beehive\n",
"life = make_life(3, 4, 0, 0, '0110', '1001', '0110')\n",
"life.draw()\n",
"savefig('figs/chap06-1')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here's what it looks like after one step:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"life.step()\n",
"life.draw()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A toad is an oscillator with period 2. Here's are its two configurations:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"# toad\n",
"plt.figure(figsize=(10, 5))\n",
"plt.subplot(1, 2, 1)\n",
"life = make_life(4, 4, 1, 0, '0111', '1110')\n",
"life.draw()\n",
"\n",
"plt.subplot(1, 2, 2)\n",
"life.step()\n",
"life.draw()\n",
"\n",
"savefig('figs/chap06-2')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here's what the toad looks like as an animation."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"life = make_life(4, 4, 1, 0, '0111', '1110')\n",
"life.animate(10, 0.5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A glider is a spaceship that translates one unit down and to the right with period 4. "
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"# glider\n",
"plt.figure(figsize=(12, 4))\n",
"\n",
"glider = ['010', '001', '111']\n",
"life = make_life(4, 4, 0, 0, *glider)\n",
"\n",
"for i in range(1, 6):\n",
" plt.subplot(1, 5, i)\n",
" life.draw()\n",
" life.step()\n",
" \n",
"savefig('figs/chap06-3')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here's an animation showing glider movement."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"life = make_life(10, 10, 0, 0, '010', '001', '111')\n",
"life.animate(frames=28, interval=0.2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise:** If you start GoL from a random configuration, it usually runs chaotically for a while and then settles into stable patterns that include blinkers, blocks, and beehives, ships, boats, and loaves.\n",
"\n",
"For a list of common \"natually\" occurring patterns, see Achim Flammenkamp, \"[Most seen natural occurring ash objects in Game of Life](http://wwwhomes.uni-bielefeld.de/achim/freq_top_life.html)\",\n",
"\n",
"Start GoL in a random state and run it until it stabilizes (try 1000 steps).\n",
"What stable patterns can you identify?\n",
"\n",
"Hint: use `np.random.randint`."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Methuselas\n",
"\n",
"Most initial conditions run for a short time and reach a steady state. But some initial conditional run for a surprisingly long time; they are called [Methuselahs](https://en.wikipedia.org/wiki/Methuselah_(cellular_automaton)).\n",
"\n",
"The r-pentomino starts with only five live cells, but it runs for 1103 steps before stabilizing."
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"# r pentomino\n",
"rpent = ['011', '110', '010']\n",
"life = make_life(3, 3, 0, 0, *rpent)\n",
"life.draw()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here are the start and finish configurations."
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"# r pentomino\n",
"plt.figure(figsize=(10, 5))\n",
"plt.subplot(1, 2, 1)\n",
"life = make_life(120, 120, 50, 45, *rpent)\n",
"life.draw()\n",
"\n",
"for i in range(1103):\n",
" life.step()\n",
"\n",
"plt.subplot(1, 2, 2)\n",
"life.draw()\n",
"\n",
"savefig('figs/chap06-4')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And here's the animation that shows the steps."
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"life = make_life(120, 120, 50, 45, *rpent)\n",
"life.animate(frames=1200)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Conway's conjecture\n",
"\n",
"Most initial conditions run for a short time and reach a steady state. Some, like the r-pentomino, run for a long time before they reach steady state. Another example is [rabbits](https://web.archive.org/web/20081221152607/http://www.argentum.freeserve.co.uk/lex_r.htm#rabbits), which starts with only nine cells and runs 17331 steps before reaching steady state."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Patterns that take a long time to reach steady state are called [Methuselahs](https://en.wikipedia.org/wiki/Methuselah_(cellular_automaton))\n",
"\n",
"Patterns like these prompted Conway's conjecture, which asks whether there are any initial conditions where the number of live cells is unbounded."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Gosper's glider gun was the first entity to be discovered that produces an unbounded number of live cells, which refutes Conway's conjecture."
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [],
"source": [
"glider_gun = [\n",
" '000000000000000000000000100000000000',\n",
" '000000000000000000000010100000000000',\n",
" '000000000000110000001100000000000011',\n",
" '000000000001000100001100000000000011',\n",
" '110000000010000010001100000000000000',\n",
" '110000000010001011000010100000000000',\n",
" '000000000010000010000000100000000000',\n",
" '000000000001000100000000000000000000',\n",
" '000000000000110000000000000000000000'\n",
"]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here's the initial configuration:"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [],
"source": [
"life = make_life(11, 38, 1, 1, *glider_gun)\n",
"life.draw()\n",
"\n",
"savefig('figs/chap06-5')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And here's what it looks like running:"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [],
"source": [
"life = make_life(50, 50, 2, 2, *glider_gun)\n",
"life.animate(frames=200)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another way to refute Conway's conjecture is a [puffer train](https://en.wikipedia.org/wiki/Puffer_train)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Implementing Game of Life\n",
"\n",
"As an example, I'll start with an array of random cells:"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"a = np.random.randint(2, size=(10, 10), dtype=np.uint8)\n",
"print(a)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following is a straightforward translation of the GoL rules using `for` loops and array slicing."
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"b = np.zeros_like(a)\n",
"rows, cols = a.shape\n",
"for i in range(1, rows-1):\n",
" for j in range(1, cols-1):\n",
" state = a[i, j]\n",
" neighbors = a[i-1:i+2, j-1:j+2]\n",
" k = np.sum(neighbors) - state\n",
" if state:\n",
" if k==2 or k==3:\n",
" b[i, j] = 1\n",
" else:\n",
" if k == 3:\n",
" b[i, j] = 1\n",
"\n",
"print(b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here's a smaller, faster version using cross correlation."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"from scipy.signal import correlate2d\n",
"\n",
"kernel = np.array([[1, 1, 1],\n",
" [1, 0, 1],\n",
" [1, 1, 1]])\n",
"\n",
"c = correlate2d(a, kernel, mode='same')\n",
"b = (c==3) | (c==2) & a\n",
"b = b.astype(np.uint8)\n",
"print(b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Using a kernel that gives a weight of 10 to the center cell, we can simplify the logic a little."
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"kernel = np.array([[1, 1, 1],\n",
" [1,10, 1],\n",
" [1, 1, 1]])\n",
"\n",
"c = correlate2d(a, kernel, mode='same')\n",
"b = (c==3) | (c==12) | (c==13)\n",
"b = b.astype(np.uint8)\n",
"print(b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"More importantly, the second version of the kernel makes it possible to use a look up table to get the next state, which is faster and even more concise."
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"table = np.zeros(20, dtype=np.uint8)\n",
"table[[3, 12, 13]] = 1\n",
"c = correlate2d(a, kernel, mode='same')\n",
"b = table[c]\n",
"print(b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise:** Many Game of Life patterns are available in portable file formats. For one source, see http://www.conwaylife.com/wiki/Main_Page.\n",
"\n",
"Write a function to parse one of these formats and initialize the array."
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [],
"source": [
"life.draw()"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Highlife\n",
"\n",
"One variation of GoL, called \"Highlife\", has the\n",
"same rules as GoL, plus one additional rule: a dead cell with 6\n",
"neighbors comes to life.\n",
"\n",
"You can try out different rules by inheriting from `Life` and changing the lookup table.\n",
"\n",
"**Exercise:** Modify the table below to add the new rule."
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [],
"source": [
"# Starter code\n",
"\n",
"class MyLife(Life):\n",
" \"\"\"Implementation of Life.\"\"\"\n",
"\n",
" table = np.zeros(20, dtype=np.uint8)\n",
" table[[3, 12, 13]] = 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"One of the more interesting patterns in Highlife is the replicator, which has the following initial configuration.\n"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [],
"source": [
"replicator = [\n",
" '00111',\n",
" '01001',\n",
" '10001',\n",
" '10010',\n",
" '11100'\n",
"]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Make a `MyLife` object with `n=100` and use `add_cells` to put a replicator near the middle.\n",
"\n",
"Make an animation with about 200 frames and see how it behaves."
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise:** \n",
"\n",
"If you generalize the Turing machine to two dimensions, or\n",
"add a read-write head to a 2-D CA, the result is a\n",
"cellular automaton called a Turmite. It is named after a\n",
"termite because of the way the read-write head moves, but\n",
"spelled wrong as an homage to Alan Turing.\n",
"\n",
"The most famous Turmite is Langton's Ant, discovered by Chris Langton\n",
"in 1986. See http://en.wikipedia.org/wiki/Langton_ant.\n",
"\n",
"The ant is a read-write head with\n",
"four states, which you can think of as facing north, south,\n",
"east or west. The cells have two states, black and white.\n",
"\n",
"The rules are simple. During each time step, the ant checks the color\n",
"of the cell it is on. If black, the ant turns to the right,\n",
"changes the cell to white, and moves forward one space. If the cell\n",
"is white, the ant turns left, changes the cell to black, and moves\n",
"forward.\n",
"\n",
"Given a simple world, a simple set of rules, and only one moving part,\n",
"you might expect to see simple behavior---but you should know\n",
"better by now. Starting with all white cells, Langton's ant\n",
"moves in a seemingly random pattern for more than 10 000 steps\n",
"before it enters a cycle with a period of 104 steps. After\n",
"each cycle, the ant is translated diagonally, so it leaves\n",
"a trail called the \"highway\".\n",
"\n",
"Write an implementation of Langton's Ant."
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [],
"source": [
"n = 5\n",
"turmite = Turmite(n)\n",
"turmite.draw()"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [],
"source": [
"turmite.step()\n",
"turmite.draw()"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [],
"source": [
"# And a larger version with 1000 steps\n",
"\n",
"turmite = Turmite(n=30)\n",
"anim = turmite.animate(frames=1000)"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.11"
}
},
"nbformat": 4,
"nbformat_minor": 2
}