Newer
Older
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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"*Note: This is not yet ready, but shows the direction I'm leaning in for Fourth Edition Search.*\n",
"\n",
"# State-Space Search\n",
"\n",
"This notebook describes several state-space search algorithms, and how they can be used to solve a variety of problems. We start with a simple algorithm and a simple domain: finding a route from city to city. Later we will explore other algorithms and domains.\n",
"\n",
"## The Route-Finding Domain\n",
"\n",
"Like all state-space search problems, in a route-finding problem you will be given:\n",
"- A start state (for example, `'A'` for the city Arad).\n",
"- A goal state (for example, `'B'` for the city Bucharest).\n",
"- Actions that can change state (for example, driving from `'A'` to `'S'`).\n",
"\n",
"You will be asked to find:\n",
"- A path from the start state, through intermediate states, to the goal state.\n",
"\n",
"We'll use this map:\n",
"\n",
"<img src=\"http://robotics.cs.tamu.edu/dshell/cs625/images/map.jpg\" height=\"366\" width=\"603\">\n",
"\n",
"A state-space search problem can be represented by a *graph*, where the vertexes of the graph are the states of the problem (in this case, cities) and the edges of the graph are the actions (in this case, driving along a road).\n",
"\n",
"We'll represent a city by its single initial letter. \n",
"We'll represent the graph of connections as a `dict` that maps each city to a list of the neighboring cities (connected by a road). For now we don't explicitly represent the actions, nor the distances\n",
"between cities."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"romania = {\n",
" 'A': ['Z', 'T', 'S'],\n",
" 'B': ['F', 'P', 'G', 'U'],\n",
" 'C': ['D', 'R', 'P'],\n",
" 'D': ['M', 'C'],\n",
" 'E': ['H'],\n",
" 'F': ['S', 'B'],\n",
" 'G': ['B'],\n",
" 'H': ['U', 'E'],\n",
" 'I': ['N', 'V'],\n",
" 'L': ['T', 'M'],\n",
" 'M': ['L', 'D'],\n",
" 'N': ['I'],\n",
" 'O': ['Z', 'S'],\n",
" 'P': ['R', 'C', 'B'],\n",
" 'R': ['S', 'C', 'P'],\n",
" 'S': ['A', 'O', 'F', 'R'],\n",
" 'T': ['A', 'L'],\n",
" 'U': ['B', 'V', 'H'],\n",
" 'V': ['U', 'I'],\n",
" 'Z': ['O', 'A']}"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"Suppose we want to get from `A` to `B`. Where can we go from the start state, `A`?"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"['Z', 'T', 'S']"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"romania['A']"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"We see that from `A` we can get to any of the three cities `['Z', 'T', 'S']`. Which should we choose? *We don't know.* That's the whole point of *search*: we don't know which immediate action is best, so we'll have to explore, until we find a *path* that leads to the goal. \n",
"\n",
"How do we explore? We'll start with a simple algorithm that will get us from `A` to `B`. We'll keep a *frontier*—a collection of not-yet-explored states—and expand the frontier outward until it reaches the goal. To be more precise:\n",
"\n",
"- Initially, the only state in the frontier is the start state, `'A'`.\n",
"- Until we reach the goal, or run out of states in the frontier to explore, do the following:\n",
" - Remove the first state from the frontier. Call it `s`.\n",
" - If `s` is the goal, we're done. Return the path to `s`.\n",
" - Otherwise, consider all the neighboring states of `s`. For each one:\n",
" - If we have not previously explored the state, add it to the end of the frontier.\n",
" - Also keep track of the previous state that led to this new neighboring state; we'll need this to reconstruct the path to the goal, and to keep us from re-visiting previously explored states.\n",
" \n",
"# A Simple Search Algorithm: `breadth_first`\n",
" \n",
"The function `breadth_first` implements this strategy:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"from collections import deque # Doubly-ended queue: pop from left, append to right.\n",
"\n",
"def breadth_first(start, goal, neighbors):\n",
" \"Find a shortest sequence of states from start to the goal.\"\n",
" frontier = deque([start]) # A queue of states\n",
" previous = {start: None} # start has no previous state; other states will\n",
" while frontier:\n",
" s = frontier.popleft()\n",
" if s == goal:\n",
" return path(previous, s)\n",
" for s2 in neighbors[s]:\n",
" if s2 not in previous:\n",
" frontier.append(s2)\n",
" previous[s2] = s\n",
" \n",
"def path(previous, s): \n",
" \"Return a list of states that lead to state s, according to the previous dict.\"\n",
" return [] if (s is None) else path(previous, previous[s]) + [s]"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"A couple of things to note: \n",
"\n",
"1. We always add new states to the end of the frontier queue. That means that all the states that are adjacent to the start state will come first in the queue, then all the states that are two steps away, then three steps, etc.\n",
"That's what we mean by *breadth-first* search.\n",
"2. We recover the path to an `end` state by following the trail of `previous[end]` pointers, all the way back to `start`.\n",
"The dict `previous` is a map of `{state: previous_state}`. \n",
"3. When we finally get an `s` that is the goal state, we know we have found a shortest path, because any other state in the queue must correspond to a path that is as long or longer.\n",
"3. Note that `previous` contains all the states that are currently in `frontier` as well as all the states that were in `frontier` in the past.\n",
"4. If no path to the goal is found, then `breadth_first` returns `None`. If a path is found, it returns the sequence of states on the path.\n",
"\n",
"Some examples:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"['A', 'S', 'F', 'B']"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"breadth_first('A', 'B', romania)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"['L', 'T', 'A', 'S', 'F', 'B', 'U', 'V', 'I', 'N']"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"breadth_first('L', 'N', romania)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"['N', 'I', 'V', 'U', 'B', 'F', 'S', 'A', 'T', 'L']"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"breadth_first('N', 'L', romania)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"['E']"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"breadth_first('E', 'E', romania)"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"Now let's try a different kind of problem that can be solved with the same search function.\n",
"\n",
"## Word Ladders Problem\n",
"\n",
"A *word ladder* problem is this: given a start word and a goal word, find the shortest way to transform the start word into the goal word by changing one letter at a time, such that each change results in a word. For example starting with `green` we can reach `grass` in 7 steps:\n",
"\n",
"`green` → `greed` → `treed` → `trees` → `tress` → `cress` → `crass` → `grass`\n",
"\n",
"We will need a dictionary of words. I'll make a local copy of the list of 5-letter words from the [Stanford GraphBase](http://www-cs-faculty.stanford.edu/~uno/sgb.html) project (the `!` indicates that these are shell commands, not Python):"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"! [ -e sgb-words.txt ] || curl -O http://www-cs-faculty.stanford.edu/~uno/sgb-words.txt"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"which\r\n",
"there\r\n",
"their\r\n",
"about\r\n",
"would\r\n",
"these\r\n",
"other\r\n",
"words\r\n",
"could\r\n",
"write\r\n"
]
}
],
"source": [
"! head sgb-words.txt"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"We can assign `WORDS` to be the set of all the words in this file:"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"5757"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"WORDS = set(open('sgb-words.txt').read().split())\n",
"len(WORDS)"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"And define `neighboring_words` to return the set of all words that are a one-letter change away from a given `word`:"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"def neighboring_words(word):\n",
" \"All words that are one letter away from this word.\"\n",
" neighbors = {word[:i] + c + word[i+1:]\n",
" for i in range(len(word))\n",
" for c in 'abcdefghijklmnopqrstuvwxyz'\n",
" if c != word[i]}\n",
" return neighbors & WORDS"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For example:"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"{'cello', 'hallo', 'hells', 'hullo', 'jello'}"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"neighboring_words('hello')"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{'would'}"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"neighboring_words('world')"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"Now we can create `word_neighbors` as a dict of `{word: {neighboring_word, ...}}`: "
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"word_neighbors = {word: neighboring_words(word)\n",
" for word in WORDS}"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"Now the `breadth_first` function can be used to solve a word ladder problem:"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"['green', 'greed', 'treed', 'trees', 'treys', 'greys', 'grays', 'grass']"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"breadth_first('green', 'grass', word_neighbors)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"['smart',\n",
" 'start',\n",
" 'stars',\n",
" 'sears',\n",
" 'bears',\n",
" 'beans',\n",
" 'brans',\n",
" 'brand',\n",
" 'braid',\n",
" 'brain']"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"breadth_first('smart', 'brain', word_neighbors)"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"['frown',\n",
" 'flown',\n",
" 'flows',\n",
" 'slows',\n",
" 'stows',\n",
" 'stoas',\n",
" 'stoae',\n",
" 'stole',\n",
" 'stile',\n",
" 'smile']"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"breadth_first('frown', 'smile', word_neighbors)"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"# More General Search Algorithms\n",
"\n",
"Now we'll embelish the `breadth_first` algorithm to make a family of search algorithms with more capabilities:\n",
"\n",
"1. We distinguish between an *action* and the *result* of an action.\n",
"3. We allow different measures of the cost of a solution (not just the number of steps in the sequence).\n",
"4. We search through the state space in an order that is more likely to lead to an optimal solution quickly.\n",
"\n",
"Here's how we do these things:\n",
"\n",
"1. Instead of having a graph of neighboring states, we instead have an object of type *Problem*. A Problem\n",
"has one method, `Problem.actions(state)` to return a collection of the actions that are allowed in a state,\n",
"and another method, `Problem.result(state, action)` that says what happens when you take an action.\n",
"2. We keep a set, `explored` of states that have already been explored. We also have a class, `Frontier`, that makes it efficient to ask if a state is on the frontier.\n",
"3. Each action has a cost associated with it (in fact, the cost can vary with both the state and the action).\n",
"4. The `Frontier` class acts as a priority queue, allowing the \"best\" state to be explored next.\n",
"We represent a sequence of actions and resulting states as a linked list of `Node` objects.\n",
"\n",
"The algorithm `breadth_first_search` is basically the same as `breadth_first`, but using our new conventions:"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"def breadth_first_search(problem):\n",
" \"Search for goal; paths with least number of steps first.\"\n",
" if problem.is_goal(problem.initial): \n",
" return Node(problem.initial)\n",
" frontier = FrontierQ(Node(problem.initial), LIFO=False)\n",
" explored = set()\n",
" while frontier:\n",
" node = frontier.pop()\n",
" explored.add(node.state)\n",
" for action in problem.actions(node.state):\n",
" child = node.child(problem, action)\n",
" if child.state not in explored and child.state not in frontier:\n",
" if problem.is_goal(child.state):\n",
" return child\n",
" frontier.add(child)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next is `uniform_cost_search`, in which each step can have a different cost, and we still consider first one os the states with minimum cost so far."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"def uniform_cost_search(problem, costfn=lambda node: node.path_cost):\n",
" frontier = FrontierPQ(Node(problem.initial), costfn)\n",
" explored = set()\n",
" while frontier:\n",
" node = frontier.pop()\n",
" if problem.is_goal(node.state):\n",
" return node\n",
" explored.add(node.state)\n",
" for action in problem.actions(node.state):\n",
" child = node.child(problem, action)\n",
" if child.state not in explored and child not in frontier:\n",
" frontier.add(child)\n",
" elif child in frontier and frontier.cost[child] < child.path_cost:\n",
" frontier.replace(child)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Finally, `astar_search` in which the cost includes an estimate of the distance to the goal as well as the distance travelled so far."
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"def astar_search(problem, heuristic):\n",
" costfn = lambda node: node.path_cost + heuristic(node.state)\n",
" return uniform_cost_search(problem, costfn)"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"# Search Tree Nodes\n",
"\n",
"The solution to a search problem is now a linked list of `Node`s, where each `Node`\n",
"includes a `state` and the `path_cost` of getting to the state. In addition, for every `Node` except for the first (root) `Node`, there is a previous `Node` (indicating the state that lead to this `Node`) and an `action` (indicating the action taken to get here)."
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"class Node(object):\n",
" \"\"\"A node in a search tree. A search tree is spanning tree over states.\n",
" A Node contains a state, the previous node in the tree, the action that\n",
" takes us from the previous state to this state, and the path cost to get to \n",
" this state. If a state is arrived at by two paths, then there are two nodes \n",
" with the same state.\"\"\"\n",
"\n",
" def __init__(self, state, previous=None, action=None, step_cost=1):\n",
" \"Create a search tree Node, derived from a previous Node by an action.\"\n",
" self.state = state\n",
" self.previous = previous\n",
" self.action = action\n",
" self.path_cost = 0 if previous is None else (previous.path_cost + step_cost)\n",
"\n",
" def __repr__(self): return \"<Node {}: {}>\".format(self.state, self.path_cost)\n",
" \n",
" def __lt__(self, other): return self.path_cost < other.path_cost\n",
" \n",
" def child(self, problem, action):\n",
" \"The Node you get by taking an action from this Node.\"\n",
" result = problem.result(self.state, action)\n",
" return Node(result, self, action, \n",
" problem.step_cost(self.state, action, result)) "
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"# Frontiers\n",
"\n",
"A frontier is a collection of Nodes that acts like both a Queue and a Set. A frontier, `f`, supports these operations:\n",
"\n",
"* `f.add(node)`: Add a node to the Frontier.\n",
"\n",
"* `f.pop()`: Remove and return the \"best\" node from the frontier.\n",
"\n",
"* `f.replace(node)`: add this node and remove a previous node with the same state.\n",
"\n",
"* `state in f`: Test if some node in the frontier has arrived at state.\n",
"\n",
"* `f[state]`: returns the node corresponding to this state in frontier.\n",
"\n",
"* `len(f)`: The number of Nodes in the frontier. When the frontier is empty, `f` is *false*.\n",
"\n",
"We provide two kinds of frontiers: One for \"regular\" queues, either first-in-first-out (for breadth-first search) or last-in-first-out (for depth-first search), and one for priority queues, where you can specify what cost function on nodes you are trying to minimize."
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"from collections import OrderedDict\n",
"import heapq\n",
"\n",
"class FrontierQ(OrderedDict):\n",
" \"A Frontier that supports FIFO or LIFO Queue ordering.\"\n",
" \n",
" def __init__(self, initial, LIFO=False):\n",
" \"\"\"Initialize Frontier with an initial Node.\n",
" If LIFO is True, pop from the end first; otherwise from front first.\"\"\"\n",
" self.LIFO = LIFO\n",
" self.add(initial)\n",
" \n",
" def add(self, node):\n",
" \"Add a node to the frontier.\"\n",
" self[node.state] = node\n",
" \n",
" def pop(self):\n",
" \"Remove and return the next Node in the frontier.\"\n",
" (state, node) = self.popitem(self.LIFO)\n",
" return node\n",
" \n",
" def replace(self, node):\n",
" \"Make this node replace the nold node with the same state.\"\n",
" del self[node.state]\n",
" self.add(node)"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"class FrontierPQ:\n",
" \"A Frontier ordered by a cost function; a Priority Queue.\"\n",
" \n",
" def __init__(self, initial, costfn=lambda node: node.path_cost):\n",
" \"Initialize Frontier with an initial Node, and specify a cost function.\"\n",
" self.heap = []\n",
" self.states = {}\n",
" self.costfn = costfn\n",
" self.add(initial)\n",
" \n",
" def add(self, node):\n",
" \"Add node to the frontier.\"\n",
" cost = self.costfn(node)\n",
" heapq.heappush(self.heap, (cost, node))\n",
" self.states[node.state] = node\n",
" \n",
" def pop(self):\n",
" \"Remove and return the Node with minimum cost.\"\n",
" (cost, node) = heapq.heappop(self.heap)\n",
" self.states.pop(node.state, None) # remove state\n",
" return node\n",
" \n",
" def replace(self, node):\n",
" \"Make this node replace a previous node with the same state.\"\n",
" if node.state not in self:\n",
" raise ValueError('{} not there to replace'.format(node.state))\n",
" for (i, (cost, old_node)) in enumerate(self.heap):\n",
" if old_node.state == node.state:\n",
" self.heap[i] = (self.costfn(node), node)\n",
" heapq._siftdown(self.heap, 0, i)\n",
" return\n",
"\n",
" def __contains__(self, state): return state in self.states\n",
" \n",
" def __len__(self): return len(self.heap)"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"# Search Problems\n",
"\n",
"`Problem` is the abstract class for all search problems. You can define your own class of problems as a subclass of `Problem`. You will need to override the `actions` and `result` method to describe how your problem works. You will also have to either override `is_goal` or pass a collection of goal states to the initialization method. If actions have different costs, you should override the `step_cost` method. "
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"class Problem(object):\n",
" \"\"\"The abstract class for a search problem.\"\"\"\n",
"\n",
" def __init__(self, initial=None, goals=(), **additional_keywords):\n",
" \"\"\"Provide an initial state and optional goal states.\n",
" A subclass can have additional keyword arguments.\"\"\"\n",
" self.initial = initial # The initial state of the problem.\n",
" self.goals = goals # A collection of possibe goal states.\n",
" self.__dict__.update(**additional_keywords)\n",
"\n",
" def actions(self, state):\n",
" \"Return a list of actions executable in this state.\"\n",
" raise NotImplementedError # Override this!\n",
"\n",
" def result(self, state, action):\n",
" \"The state that results from executing this action in this state.\"\n",
" raise NotImplementedError # Override this!\n",
"\n",
" def is_goal(self, state):\n",
" \"True if the state is a goal.\" \n",
" return state in self.goals # Optionally override this!\n",
"\n",
" def step_cost(self, state, action, result=None):\n",
" \"The cost of taking this action from this state.\"\n",
" return 1 # Override this if actions have different costs "
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def action_sequence(node):\n",
" \"The sequence of actions to get to this node.\"\n",
" actions = []\n",
" while node.previous:\n",
" actions.append(node.action)\n",
" node = node.previous\n",
" return actions[::-1]\n",
"\n",
"def state_sequence(node):\n",
" \"The sequence of states to get to this node.\"\n",
" states = [node.state]\n",
" while node.previous:\n",
" node = node.previous\n",
" states.append(node.state)\n",
" return states[::-1]"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"# Two Location Vacuum World"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"dirt = '*'\n",
"clean = ' '\n",
"\n",
"class TwoLocationVacuumProblem(Problem):\n",
" \"\"\"A Vacuum in a world with two locations, and dirt.\n",
" Each state is a tuple of (location, dirt_in_W, dirt_in_E).\"\"\"\n",
"\n",
" def actions(self, state): return ('W', 'E', 'Suck')\n",
" \n",
" def is_goal(self, state): return dirt not in state\n",
" \n",
" def result(self, state, action):\n",
" \"The state that results from executing this action in this state.\" \n",
" (loc, dirtW, dirtE) = state\n",
" if action == 'W': return ('W', dirtW, dirtE)\n",
" elif action == 'E': return ('E', dirtW, dirtE)\n",
" elif action == 'Suck' and loc == 'W': return (loc, clean, dirtE)\n",
" elif action == 'Suck' and loc == 'E': return (loc, dirtW, clean) \n",
" else: raise ValueError('unknown action: ' + action)"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"<Node ('E', ' ', ' '): 3>"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"problem = TwoLocationVacuumProblem(initial=('W', dirt, dirt))\n",
"result = uniform_cost_search(problem)\n",
"result"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"['Suck', 'E', 'Suck']"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"action_sequence(result)"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[('W', '*', '*'), ('W', ' ', '*'), ('E', ' ', '*'), ('E', ' ', ' ')]"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"state_sequence(result)"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"['Suck']"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"problem = TwoLocationVacuumProblem(initial=('E', clean, dirt))\n",
"result = uniform_cost_search(problem)\n",
"action_sequence(result)"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"# Water Pouring Problem\n",
"\n",
"Here is another problem domain, to show you how to define one. The idea is that we have a number of water jugs and a water tap and the goal is to measure out a specific amount of water (in, say, ounces or liters). You can completely fill or empty a jug, but because the jugs don't have markings on them, you can't partially fill them with a specific amount. You can, however, pour one jug into another, stopping when the seconfd is full or the first is empty."
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"class PourProblem(Problem):\n",
" \"\"\"Problem about pouring water between jugs to achieve some water level.\n",
" Each state is a tuples of levels. In the initialization, provide a tuple of \n",
" capacities, e.g. PourProblem(capacities=(8, 16, 32), initial=(2, 4, 3), goals={7}), \n",
" which means three jugs of capacity 8, 16, 32, currently filled with 2, 4, 3 units of \n",
" water, respectively, and the goal is to get a level of 7 in any one of the jugs.\"\"\"\n",
" \n",
" def actions(self, state):\n",
" \"\"\"The actions executable in this state.\"\"\"\n",
" jugs = range(len(state))\n",
" return ([('Fill', i) for i in jugs if state[i] != self.capacities[i]] +\n",
" [('Dump', i) for i in jugs if state[i] != 0] +\n",
" [('Pour', i, j) for i in jugs for j in jugs if i != j])\n",
"\n",
" def result(self, state, action):\n",
" \"\"\"The state that results from executing this action in this state.\"\"\"\n",
" result = list(state)\n",
" act, i, j = action[0], action[1], action[-1]\n",
" if act == 'Fill': # Fill i to capacity\n",
" result[i] = self.capacities[i]\n",
" elif act == 'Dump': # Empty i\n",
" result[i] = 0\n",
" elif act == 'Pour':\n",
" a, b = state[i], state[j]\n",
" result[i], result[j] = ((0, a + b) \n",
" if (a + b <= self.capacities[j]) else\n",
" (a + b - self.capacities[j], self.capacities[j]))\n",
" else:\n",
" raise ValueError('unknown action', action)\n",
" return tuple(result)\n",
"\n",
" def is_goal(self, state):\n",
" \"\"\"True if any of the jugs has a level equal to one of the goal levels.\"\"\"\n",
" return any(level in self.goals for level in state)"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"(2, 13)"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"p7 = PourProblem(initial=(2, 0), capacities=(5, 13), goals={7})\n",
"p7.result((2, 0), ('Fill', 1))"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"[('Pour', 0, 1), ('Fill', 0), ('Pour', 0, 1)]"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"result = uniform_cost_search(p7)\n",
"action_sequence(result)"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"# Visualization Output"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"def showpath(searcher, problem):\n",
" \"Show what happens when searcvher solves problem.\"\n",
" problem = Instrumented(problem)\n",
" print('\\n{}:'.format(searcher.__name__))\n",
" result = searcher(problem)\n",
" if result:\n",
" actions = action_sequence(result)\n",
" state = problem.initial\n",
" path_cost = 0\n",
" for steps, action in enumerate(actions, 1):\n",
" path_cost += problem.step_cost(state, action, 0)\n",
" result = problem.result(state, action)\n",
" print(' {} =={}==> {}; cost {} after {} steps'\n",
" .format(state, action, result, path_cost, steps,\n",
" '; GOAL!' if problem.is_goal(result) else ''))\n",
" state = result\n",
" msg = 'GOAL FOUND' if result else 'no solution'\n",
" print('{} after {} results and {} goal checks'\n",
" .format(msg, problem._counter['result'], problem._counter['is_goal']))\n",
" \n",
"from collections import Counter\n",
"\n",
"class Instrumented:\n",
" \"Instrument an object to count all the attribute accesses in _counter.\"\n",
" def __init__(self, obj):\n",
" self._object = obj\n",
" self._counter = Counter()\n",
" def __getattr__(self, attr):\n",
" self._counter[attr] += 1\n",
" return getattr(self._object, attr) "
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"uniform_cost_search:\n",
" (2, 0) ==('Pour', 0, 1)==> (0, 2); cost 1 after 1 steps\n",
" (0, 2) ==('Fill', 0)==> (5, 2); cost 2 after 2 steps\n",
" (5, 2) ==('Pour', 0, 1)==> (0, 7); cost 3 after 3 steps\n",
"GOAL FOUND after 83 results and 22 goal checks\n"
]
}
],
"source": [
"showpath(uniform_cost_search, p7)"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"uniform_cost_search:\n",
" (0, 0) ==('Fill', 0)==> (7, 0); cost 1 after 1 steps\n",
" (7, 0) ==('Pour', 0, 1)==> (0, 7); cost 2 after 2 steps\n",
" (0, 7) ==('Fill', 0)==> (7, 7); cost 3 after 3 steps\n",
" (7, 7) ==('Pour', 0, 1)==> (1, 13); cost 4 after 4 steps\n",
" (1, 13) ==('Dump', 1)==> (1, 0); cost 5 after 5 steps\n",
" (1, 0) ==('Pour', 0, 1)==> (0, 1); cost 6 after 6 steps\n",
" (0, 1) ==('Fill', 0)==> (7, 1); cost 7 after 7 steps\n",
" (7, 1) ==('Pour', 0, 1)==> (0, 8); cost 8 after 8 steps\n",
" (0, 8) ==('Fill', 0)==> (7, 8); cost 9 after 9 steps\n",
" (7, 8) ==('Pour', 0, 1)==> (2, 13); cost 10 after 10 steps\n",
"GOAL FOUND after 110 results and 32 goal checks\n"
]
}
],
"source": [
"p = PourProblem(initial=(0, 0), capacities=(7, 13), goals={2})\n",
"showpath(uniform_cost_search, p)"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"class GreenPourProblem(PourProblem): \n",
" def step_cost(self, state, action, result=None):\n",
" \"The cost is the amount of water used in a fill.\"\n",
" if action[0] == 'Fill':\n",
" i = action[1]\n",
" return self.capacities[i] - state[i]\n",
" return 0"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"uniform_cost_search:\n",
" (0, 0) ==('Fill', 0)==> (7, 0); cost 7 after 1 steps\n",
" (7, 0) ==('Pour', 0, 1)==> (0, 7); cost 7 after 2 steps\n",
" (0, 7) ==('Fill', 0)==> (7, 7); cost 14 after 3 steps\n",
" (7, 7) ==('Pour', 0, 1)==> (1, 13); cost 14 after 4 steps\n",
" (1, 13) ==('Dump', 1)==> (1, 0); cost 14 after 5 steps\n",
" (1, 0) ==('Pour', 0, 1)==> (0, 1); cost 14 after 6 steps\n",
" (0, 1) ==('Fill', 0)==> (7, 1); cost 21 after 7 steps\n",
" (7, 1) ==('Pour', 0, 1)==> (0, 8); cost 21 after 8 steps\n",
" (0, 8) ==('Fill', 0)==> (7, 8); cost 28 after 9 steps\n",
" (7, 8) ==('Pour', 0, 1)==> (2, 13); cost 28 after 10 steps\n",
"GOAL FOUND after 184 results and 48 goal checks\n"
]
}
],
"source": [
"p = GreenPourProblem(initial=(0, 0), capacities=(7, 13), goals={2})\n",
"showpath(uniform_cost_search, p)"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"def compare_searchers(problem, searchers=None):\n",
" \"Apply each of the search algorithms to the problem, and show results\"\n",
" if searchers is None: \n",
" searchers = (breadth_first_search, uniform_cost_search)\n",
" for searcher in searchers:\n",
" showpath(searcher, problem)"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"breadth_first_search:\n",
" (0, 0) ==('Fill', 0)==> (7, 0); cost 7 after 1 steps\n",
" (7, 0) ==('Pour', 0, 1)==> (0, 7); cost 7 after 2 steps\n",
" (0, 7) ==('Fill', 0)==> (7, 7); cost 14 after 3 steps\n",
" (7, 7) ==('Pour', 0, 1)==> (1, 13); cost 14 after 4 steps\n",
" (1, 13) ==('Dump', 1)==> (1, 0); cost 14 after 5 steps\n",
" (1, 0) ==('Pour', 0, 1)==> (0, 1); cost 14 after 6 steps\n",
" (0, 1) ==('Fill', 0)==> (7, 1); cost 21 after 7 steps\n",
" (7, 1) ==('Pour', 0, 1)==> (0, 8); cost 21 after 8 steps\n",
" (0, 8) ==('Fill', 0)==> (7, 8); cost 28 after 9 steps\n",
" (7, 8) ==('Pour', 0, 1)==> (2, 13); cost 28 after 10 steps\n",
"GOAL FOUND after 100 results and 31 goal checks\n",
"\n",
"uniform_cost_search:\n",
" (0, 0) ==('Fill', 0)==> (7, 0); cost 7 after 1 steps\n",
" (7, 0) ==('Pour', 0, 1)==> (0, 7); cost 7 after 2 steps\n",
" (0, 7) ==('Fill', 0)==> (7, 7); cost 14 after 3 steps\n",
" (7, 7) ==('Pour', 0, 1)==> (1, 13); cost 14 after 4 steps\n",
" (1, 13) ==('Dump', 1)==> (1, 0); cost 14 after 5 steps\n",
" (1, 0) ==('Pour', 0, 1)==> (0, 1); cost 14 after 6 steps\n",
" (0, 1) ==('Fill', 0)==> (7, 1); cost 21 after 7 steps\n",
" (7, 1) ==('Pour', 0, 1)==> (0, 8); cost 21 after 8 steps\n",
" (0, 8) ==('Fill', 0)==> (7, 8); cost 28 after 9 steps\n",
" (7, 8) ==('Pour', 0, 1)==> (2, 13); cost 28 after 10 steps\n",
"GOAL FOUND after 184 results and 48 goal checks\n"
]
}
],
"source": [
"compare_searchers(p)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Random Grid\n",
"\n",
"An environment where you can move in any of 4 directions, unless there is an obstacle there.\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{(0, 0): [(0, 1), (1, 0)],\n",
" (0, 1): [(0, 2), (0, 0), (1, 1)],\n",
" (0, 2): [(0, 3), (0, 1), (1, 2)],\n",
" (0, 3): [(0, 2), (1, 3)],\n",
" (0, 4): [(0, 3), (1, 4)],\n",
" (1, 0): [(1, 1), (2, 0), (0, 0)],\n",
" (1, 1): [(1, 2), (1, 0), (0, 1)],\n",
" (1, 2): [(1, 3), (1, 1), (2, 2), (0, 2)],\n",
" (1, 3): [(1, 4), (1, 2), (2, 3), (0, 3)],\n",
" (1, 4): [(1, 3), (2, 4)],\n",
" (2, 0): [(3, 0), (1, 0)],\n",
" (2, 1): [(2, 2), (2, 0), (3, 1), (1, 1)],\n",
" (2, 2): [(2, 3), (3, 2), (1, 2)],\n",
" (2, 3): [(2, 4), (2, 2), (3, 3), (1, 3)],\n",
" (2, 4): [(2, 3), (3, 4), (1, 4)],\n",
" (3, 0): [(3, 1), (4, 0), (2, 0)],\n",
" (3, 1): [(3, 2), (3, 0), (4, 1)],\n",
" (3, 2): [(3, 3), (3, 1), (4, 2), (2, 2)],\n",
" (3, 3): [(3, 4), (3, 2), (4, 3), (2, 3)],\n",
" (3, 4): [(3, 3), (4, 4), (2, 4)],\n",
" (4, 0): [(4, 1), (3, 0)],\n",
" (4, 1): [(4, 2), (4, 0), (3, 1)],\n",
" (4, 2): [(4, 3), (4, 1), (3, 2)],\n",
" (4, 3): [(4, 4), (4, 2), (3, 3)],\n",
" (4, 4): [(4, 3), (3, 4)]}"
]
},
"execution_count": 41,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import random\n",
"\n",
"N, S, E, W = DIRECTIONS = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n",
"\n",
"def Grid(width, height, obstacles=0.1):\n",
" \"\"\"A 2-D grid, width x height, with obstacles that are either a collection of points,\n",
" or a fraction between 0 and 1 indicating the density of obstacles, chosen at random.\"\"\"\n",
" grid = {(x, y) for x in range(width) for y in range(height)}\n",
" if isinstance(obstacles, (float, int)):\n",
" obstacles = random.sample(grid, int(width * height * obstacles))\n",
" def neighbors(x, y):\n",
" for (dx, dy) in DIRECTIONS:\n",
" (nx, ny) = (x + dx, y + dy)\n",
" if (nx, ny) not in obstacles and 0 <= nx < width and 0 <= ny < height:\n",
" yield (nx, ny)\n",
" return {(x, y): list(neighbors(x, y))\n",
" for x in range(width) for y in range(height)}\n",
"\n",
"Grid(5, 5)"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"class GridProblem(Problem):\n",
" \"Create with a call like GridProblem(grid=Grid(10, 10), initial=(0, 0), goal=(9, 9))\"\n",
" def actions(self, state): return DIRECTIONS\n",
" def result(self, state, action):\n",
" #print('ask for result of', state, action)\n",
" (x, y) = state\n",
" (dx, dy) = action\n",
" r = (x + dx, y + dy)\n",
" return r if r in self.grid[state] else state"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"uniform_cost_search:\n",
"no solution after 8 results and 2 goal checks\n"
]
}
],
"source": [
"gp = GridProblem(grid=Grid(5, 5, 0.3), initial=(0, 0), goals={(4, 4)})\n",
"showpath(uniform_cost_search, gp)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"button": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"source": [
"# Finding a hard PourProblem\n",
"\n",
"What solvable two-jug PourProblem requires the most steps? We can define the hardness as the number of steps, and then iterate over all PourProblems with capacities up to size M, keeping the hardest one."
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"def hardness(problem):\n",
" L = breadth_first_search(problem)\n",
" #print('hardness', problem.initial, problem.capacities, problem.goals, L)\n",
" return len(action_sequence(L)) if (L is not None) else 0"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"hardness(p7)"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[('Pour', 0, 1), ('Fill', 0), ('Pour', 0, 1)]"
]
},
"execution_count": 46,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"action_sequence(breadth_first_search(p7))"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"((0, 0), (7, 9), {8})"
]
},
"execution_count": 47,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"C = 9 # Maximum capacity to consider\n",
"\n",
"phard = max((PourProblem(initial=(a, b), capacities=(A, B), goals={goal})\n",
" for A in range(C+1) for B in range(C+1)\n",
" for a in range(A) for b in range(B)\n",
" for goal in range(max(A, B))),\n",
" key=hardness)\n",
"\n",
"phard.initial, phard.capacities, phard.goals"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"breadth_first_search:\n",
" (0, 0) ==('Fill', 1)==> (0, 9); cost 1 after 1 steps\n",
" (0, 9) ==('Pour', 1, 0)==> (7, 2); cost 2 after 2 steps\n",
" (7, 2) ==('Dump', 0)==> (0, 2); cost 3 after 3 steps\n",
" (0, 2) ==('Pour', 1, 0)==> (2, 0); cost 4 after 4 steps\n",
" (2, 0) ==('Fill', 1)==> (2, 9); cost 5 after 5 steps\n",
" (2, 9) ==('Pour', 1, 0)==> (7, 4); cost 6 after 6 steps\n",
" (7, 4) ==('Dump', 0)==> (0, 4); cost 7 after 7 steps\n",
" (0, 4) ==('Pour', 1, 0)==> (4, 0); cost 8 after 8 steps\n",
" (4, 0) ==('Fill', 1)==> (4, 9); cost 9 after 9 steps\n",
" (4, 9) ==('Pour', 1, 0)==> (7, 6); cost 10 after 10 steps\n",
" (7, 6) ==('Dump', 0)==> (0, 6); cost 11 after 11 steps\n",
" (0, 6) ==('Pour', 1, 0)==> (6, 0); cost 12 after 12 steps\n",
" (6, 0) ==('Fill', 1)==> (6, 9); cost 13 after 13 steps\n",
" (6, 9) ==('Pour', 1, 0)==> (7, 8); cost 14 after 14 steps\n",
"GOAL FOUND after 150 results and 44 goal checks\n"
]
}
],
"source": [
"showpath(breadth_first_search, PourProblem(initial=(0, 0), capacities=(7, 9), goals={8}))"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"uniform_cost_search:\n",
" (0, 0) ==('Fill', 1)==> (0, 9); cost 1 after 1 steps\n",
" (0, 9) ==('Pour', 1, 0)==> (7, 2); cost 2 after 2 steps\n",
" (7, 2) ==('Dump', 0)==> (0, 2); cost 3 after 3 steps\n",
" (0, 2) ==('Pour', 1, 0)==> (2, 0); cost 4 after 4 steps\n",
" (2, 0) ==('Fill', 1)==> (2, 9); cost 5 after 5 steps\n",
" (2, 9) ==('Pour', 1, 0)==> (7, 4); cost 6 after 6 steps\n",
" (7, 4) ==('Dump', 0)==> (0, 4); cost 7 after 7 steps\n",
" (0, 4) ==('Pour', 1, 0)==> (4, 0); cost 8 after 8 steps\n",
" (4, 0) ==('Fill', 1)==> (4, 9); cost 9 after 9 steps\n",
" (4, 9) ==('Pour', 1, 0)==> (7, 6); cost 10 after 10 steps\n",
" (7, 6) ==('Dump', 0)==> (0, 6); cost 11 after 11 steps\n",
" (0, 6) ==('Pour', 1, 0)==> (6, 0); cost 12 after 12 steps\n",
" (6, 0) ==('Fill', 1)==> (6, 9); cost 13 after 13 steps\n",
" (6, 9) ==('Pour', 1, 0)==> (7, 8); cost 14 after 14 steps\n",
"GOAL FOUND after 159 results and 45 goal checks\n"
]
}
],
"source": [
"showpath(uniform_cost_search, phard)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {
"button": false,
"collapsed": true,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [],
"source": [
"class GridProblem(Problem):\n",
" \"\"\"A Grid.\"\"\"\n",
"\n",
" def actions(self, state): return ['N', 'S', 'E', 'W'] \n",
" \n",
" def result(self, state, action):\n",
" \"\"\"The state that results from executing this action in this state.\"\"\" \n",
" (W, H) = self.size\n",
" if action == 'N' and state > W: return state - W\n",
" if action == 'S' and state + W < W * W: return state + W\n",
" if action == 'E' and (state + 1) % W !=0: return state + 1\n",
" if action == 'W' and state % W != 0: return state - 1\n",
" return state"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"breadth_first_search:\n",
" 0 ==S==> 10; cost 1 after 1 steps\n",
" 10 ==S==> 20; cost 2 after 2 steps\n",
" 20 ==S==> 30; cost 3 after 3 steps\n",
" 30 ==S==> 40; cost 4 after 4 steps\n",
" 40 ==E==> 41; cost 5 after 5 steps\n",
" 41 ==E==> 42; cost 6 after 6 steps\n",
" 42 ==E==> 43; cost 7 after 7 steps\n",
" 43 ==E==> 44; cost 8 after 8 steps\n",
"GOAL FOUND after 135 results and 49 goal checks\n",
"\n",
"uniform_cost_search:\n",
" 0 ==S==> 10; cost 1 after 1 steps\n",
" 10 ==S==> 20; cost 2 after 2 steps\n",
" 20 ==E==> 21; cost 3 after 3 steps\n",
" 21 ==E==> 22; cost 4 after 4 steps\n",
" 22 ==E==> 23; cost 5 after 5 steps\n",
" 23 ==S==> 33; cost 6 after 6 steps\n",
" 33 ==S==> 43; cost 7 after 7 steps\n",
" 43 ==E==> 44; cost 8 after 8 steps\n",
"GOAL FOUND after 1036 results and 266 goal checks\n"
]
}
],
"source": [
"compare_searchers(GridProblem(initial=0, goals={44}, size=(10, 10)))"
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"data": {
"text/plain": [
"'test_frontier ok'"
]
},
"execution_count": 52,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def test_frontier():\n",
" \n",
" #### Breadth-first search with FIFO Q\n",
" f = FrontierQ(Node(1), LIFO=False)\n",
" assert 1 in f and len(f) == 1\n",
" f.add(Node(2))\n",
" f.add(Node(3))\n",
" assert 1 in f and 2 in f and 3 in f and len(f) == 3\n",
" assert f.pop().state == 1\n",
" assert 1 not in f and 2 in f and 3 in f and len(f) == 2\n",
" assert f\n",
" assert f.pop().state == 2\n",
" assert f.pop().state == 3\n",
" assert not f\n",
" \n",
" #### Depth-first search with LIFO Q\n",
" f = FrontierQ(Node('a'), LIFO=True)\n",
" for s in 'bcdef': f.add(Node(s))\n",
" assert len(f) == 6 and 'a' in f and 'c' in f and 'f' in f\n",
" for s in 'fedcba': assert f.pop().state == s\n",
" assert not f\n",
"\n",
" #### Best-first search with Priority Q\n",
" f = FrontierPQ(Node(''), lambda node: len(node.state))\n",
" assert '' in f and len(f) == 1 and f\n",
" for s in ['book', 'boo', 'bookie', 'bookies', 'cook', 'look', 'b']:\n",
" assert s not in f\n",
" f.add(Node(s))\n",
" assert s in f\n",
" assert f.pop().state == ''\n",
" assert f.pop().state == 'b'\n",
" assert f.pop().state == 'boo'\n",
" assert {f.pop().state for _ in '123'} == {'book', 'cook', 'look'}\n",
" assert f.pop().state == 'bookie'\n",
" \n",
" #### Romania: Two paths to Bucharest; cheapest one found first\n",
" S = Node('S')\n",
" SF = Node('F', S, 'S->F', 99)\n",
" SFB = Node('B', SF, 'F->B', 211)\n",
" SR = Node('R', S, 'S->R', 80)\n",
" SRP = Node('P', SR, 'R->P', 97)\n",
" SRPB = Node('B', SRP, 'P->B', 101)\n",
" f = FrontierPQ(S)\n",
" f.add(SF); f.add(SR), f.add(SRP), f.add(SRPB); f.add(SFB)\n",
" def cs(n): return (n.path_cost, n.state) # cs: cost and state\n",
" assert cs(f.pop()) == (0, 'S')\n",
" assert cs(f.pop()) == (80, 'R')\n",
" assert cs(f.pop()) == (99, 'F')\n",
" assert cs(f.pop()) == (177, 'P')\n",
" assert cs(f.pop()) == (278, 'B')\n",
" return 'test_frontier ok'\n",
"\n",
"test_frontier()"
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAXEAAAEACAYAAABF+UbAAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAGf5JREFUeJzt3XuQVPWd9/H3h4vGy8JiVjAqIRFXJG4lEl0vQWMb77gB\nk31C5ImumsdNJRo1bio6ums5qYpVasol5GbiRhHjJYouQlx9QBZboiZeAG8RWSMrXhmzXFzRCqvw\n3T/OGRzHhjk93T2nT/fnVdU1p5tzur814odf/87voojAzMyKaVDeBZiZWf85xM3MCswhbmZWYA5x\nM7MCc4ibmRWYQ9zMrMAyhbik8yQ9lT7OTV8bIWmBpBWS5ksa3thSzcystz5DXNJ+wP8DDgT2B/5G\n0ligA1gYEeOARcBFjSzUzMw+KEtLfDzwcERsjIhNwGLgi8BkYFZ6zizgpMaUaGZmW5MlxJ8GDk+7\nT3YEJgGjgVER0QUQEauBkY0r08zMKhnS1wkR8aykK4B7gQ3AMmBTpVPrXJuZmfWhzxAHiIiZwEwA\nSZcBL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f2DQzKzCHuJlZgTnEzcwKzCFuZlZgDnEzswJziJuZFZhD3MyswBziZmYF\n9r8varwUoYrZVQAAAABJRU5ErkJggg==\n",
"text/plain": [
"<matplotlib.figure.Figure at 0x10be59cf8>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"%matplotlib inline\n",
"import matplotlib.pyplot as plt\n",
"\n",
"p = plt.plot([i**2 for i in range(10)])\n",
"plt.savefig('destination_path.eps', format='eps', dpi=1200)"
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {
"button": false,
"collapsed": false,
"deletable": true,
"new_sheet": false,
"run_control": {
"read_only": false
}
},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'itertools' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-54-72de964d0631>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 23\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mfig\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 24\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 25\u001b[0;31m \u001b[0mmain\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;32m<ipython-input-54-72de964d0631>\u001b[0m in \u001b[0;36mmain\u001b[0;34m()\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mmain\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 8\u001b[0;31m \u001b[0mgrid_table\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m8\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m8\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 9\u001b[0m \u001b[0mplt\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0maxis\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'scaled'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0mplt\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mshow\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m<ipython-input-54-72de964d0631>\u001b[0m in \u001b[0;36mgrid_table\u001b[0;34m(nrows, ncols)\u001b[0m\n\u001b[1;32m 15\u001b[0m \u001b[0mcolors\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m'white'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'lightgrey'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'dimgrey'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 16\u001b[0m \u001b[0mtb\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mTable\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0max\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mbbox\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 17\u001b[0;31m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mj\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mitertools\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mproduct\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mncols\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mnrows\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 18\u001b[0m tb.add_cell(i, j, 2./ncols, 2./nrows, text='{:0.2f}'.format(0.1234), \n\u001b[1;32m 19\u001b[0m loc='center', facecolor=random.choice(colors), edgecolor='grey') # facecolors=\n",
"\u001b[0;31mNameError\u001b[0m: name 'itertools' is not defined"
]
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAXkAAAEACAYAAABWLgY0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAA55JREFUeJzt1EENACAQwDDAv+dDBSFZWgV7bc/MAqDp/A4A4B2TBwgz\neYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5\ngDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mA\nMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAw\nkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCT\nBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMH\nCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcI\nM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgz\neYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5\ngDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mA\nMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAw\nkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCT\nBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMH\nCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcI\nM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgz\neYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYAwkwcIM3mAMJMHCDN5\ngDCTBwgzeYAwkwcIM3mAMJMHCDN5gDCTBwgzeYCwC5ENBP3D1A5rAAAAAElFTkSuQmCC\n",
"text/plain": [
"<matplotlib.figure.Figure at 0x10efa89e8>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"#### import itertools\n",
"import random\n",
"# http://stackoverflow.com/questions/10194482/custom-matplotlib-plot-chess-board-like-table-with-colored-cells\n",
"\n",
"from matplotlib.table import Table\n",
"\n",
"def main():\n",
" grid_table(8, 8)\n",
" plt.axis('scaled')\n",
" plt.show()\n",
"\n",
"def grid_table(nrows, ncols):\n",
" fig, ax = plt.subplots()\n",
" ax.set_axis_off()\n",
" colors = ['white', 'lightgrey', 'dimgrey']\n",
" tb = Table(ax, bbox=[0,0,2,2])\n",
" for i,j in itertools.product(range(ncols), range(nrows)):\n",
" tb.add_cell(i, j, 2./ncols, 2./nrows, text='{:0.2f}'.format(0.1234), \n",
" loc='center', facecolor=random.choice(colors), edgecolor='grey') # facecolors=\n",
" ax.add_table(tb)\n",
" #ax.plot([0, .3], [.2, .2])\n",
" #ax.add_line(plt.Line2D([0.3, 0.5], [0.7, 0.7], linewidth=2, color='blue'))\n",
" return fig\n",
"\n",
"main()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"class defaultkeydict(collections.defaultdict):\n",
" \"\"\"Like defaultdict, but the default_factory is a function of the key.\n",
" >>> d = defaultkeydict(abs); d[-42]\n",
" 42\n",
" \"\"\"\n",
" def __missing__(self, key):\n",
" self[key] = self.default_factory(key)\n",
" return self[key]"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"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.5.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}