Spaces:
Paused
Paused
File size: 109,537 Bytes
f6686e1 | 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 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 | <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<meta name="generator" content="pdoc 0.10.0" />
<title>tinytroupe.control API documentation</title>
<meta name="description" content="Simulation controlling mechanisms." />
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/sanitize.min.css" integrity="sha256-PK9q560IAAa6WVRRh76LtCaI8pjTJ2z11v0miyNNjrs=" crossorigin>
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/typography.min.css" integrity="sha256-7l/o7C8jubJiy74VsKTidCy1yBkRtiUGbVkYBylBqUg=" crossorigin>
<link rel="stylesheet preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/styles/github.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/highlight.min.js" integrity="sha256-Uv3H6lx7dJmRfRvH8TH6kJD1TSK1aFcwgx+mdg3epi8=" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => hljs.initHighlighting())</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>tinytroupe.control</code></h1>
</header>
<section id="section-intro">
<p>Simulation controlling mechanisms.</p>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">"""
Simulation controlling mechanisms.
"""
import json
import os
import tempfile
import threading
import traceback
import tinytroupe
import tinytroupe.utils as utils
import uuid
import logging
logger = logging.getLogger("tinytroupe")
# to protect from race conditions when running in parallel
concurrent_execution_lock = threading.Lock()
class Simulation:
STATUS_STOPPED = "stopped"
STATUS_STARTED = "started"
def __init__(self, id="default", cached_trace:list=None):
self.id = id
self.agents = []
self.name_to_agent = {} # {agent_name: agent, ...}
self.environments = []
self.factories = [] # e.g., TinyPersonFactory instances
self.name_to_factory = {} # {factory_name: factory, ...}
self.name_to_environment = {} # {environment_name: environment, ...}
self.status = Simulation.STATUS_STOPPED
self.cache_path = f"./tinytroupe-{id}.cache.json" # default cache path
# should we always automatically checkpoint at the every transaction?
self.auto_checkpoint = False
# whether there are changes not yet saved to the cache file
self.has_unsaved_cache_changes = False
# whether the agent is under a transaction or not, used for managing
# simulation caching later
self._under_transaction = {None: False}
# whether the agent is under a parallel transactions segment or not, used for managing
# simulation caching later
self._under_parallel_transactions = False
# Cache chain mechanism.
#
# stores a list of simulation states.
# Each state is a tuple (prev_node_hash, event_hash, event_output, state), where prev_node_hash is a hash of the previous node in this chain,
# if any, event_hash is a hash of the event that triggered the transition to this state, if any, event_output is the output of the event,
# if any, and state is the actual complete state that resulted.
if cached_trace is None:
self.cached_trace = []
else:
self.cached_trace = cached_trace
self.cache_misses = 0
self.cache_hits = 0
# Execution chain mechanism.
#
# The actual, current, execution trace. Each state is a tuple (prev_node_hash, event_hash, state), where prev_node_hash is a hash
# of the previous node in this chain, if any, event_hash is a hash of the event that triggered the transition to this state, if any,
# event_output is the output of the event, if any, and state is the actual complete state that resulted.
self.execution_trace = []
def begin(self, cache_path:str=None, auto_checkpoint:bool=False):
"""
Marks the start of the simulation being controlled.
Args:
cache_path (str): The path to the cache file. If not specified,
defaults to the default cache path defined in the class.
auto_checkpoint (bool, optional): Whether to automatically checkpoint at the end of each transaction. Defaults to False.
"""
logger.debug(f"Starting simulation, cache_path={cache_path}, auto_checkpoint={auto_checkpoint}.")
# local import to avoid circular dependencies
from tinytroupe.agent import TinyPerson
from tinytroupe.environment import TinyWorld
from tinytroupe.factory.tiny_factory import TinyFactory
from tinytroupe.factory.tiny_person_factory import TinyPersonFactory
if self.status == Simulation.STATUS_STOPPED:
self.status = Simulation.STATUS_STARTED
else:
raise ValueError("Simulation is already started.")
if cache_path is not None:
self.cache_path = cache_path
# should we automatically checkpoint?
self.auto_checkpoint = auto_checkpoint
# clear the agents, environments and other simulated entities, we'll track them from now on
TinyPerson.clear_agents()
TinyWorld.clear_environments()
TinyFactory.clear_factories()
TinyPersonFactory.clear_factories()
# All automated fresh ids will start from 0 again for this simulation
utils.reset_fresh_id()
# load the cache file, if any
if self.cache_path is not None:
self._load_cache_file(self.cache_path)
def end(self):
"""
Marks the end of the simulation being controlled.
"""
logger.debug("Ending simulation.")
if self.status == Simulation.STATUS_STARTED:
self.status = Simulation.STATUS_STOPPED
self.checkpoint()
else:
raise ValueError("Simulation is already stopped.")
def checkpoint(self):
"""
Saves current simulation trace to a file.
"""
logger.debug("Checkpointing simulation state...")
# save the cache file
if self.has_unsaved_cache_changes:
self._save_cache_file(self.cache_path)
else:
logger.debug("No unsaved cache changes to save to file.")
def add_agent(self, agent):
"""
Adds an agent to the simulation.
"""
if agent.name in self.name_to_agent:
raise ValueError(f"Agent names must be unique, but '{agent.name}' is already defined.")
agent.simulation_id = self.id
self.agents.append(agent)
self.name_to_agent[agent.name] = agent
def add_environment(self, environment):
"""
Adds an environment to the simulation.
"""
if environment.name in self.name_to_environment:
raise ValueError(f"Environment names must be unique, but '{environment.name}' is already defined.")
environment.simulation_id = self.id
self.environments.append(environment)
self.name_to_environment[environment.name] = environment
def add_factory(self, factory):
"""
Adds a factory to the simulation.
"""
if factory.name in self.name_to_factory:
raise ValueError(f"Factory names must be unique, but '{factory.name}' is already defined.")
factory.simulation_id = self.id
self.factories.append(factory)
self.name_to_factory[factory.name] = factory
###################################################################################################
# Cache and execution chain mechanisms
###################################################################################################
def _execution_trace_position(self) -> int:
"""
Returns the current position in the execution trace, or -1 if the execution trace is empty.
"""
return len(self.execution_trace) - 1
def _function_call_hash(self, function_name, *args, **kwargs) -> int:
"""
Computes the hash of the given function call.
"""
# if functions are passed as arguments to the function, there's the problem that their
# string representation always changes due to memory position (e.g., <function my_function at 0x7f8d1a7b7d30>).
# so we need to remove the changing suffix in those cases, while preserving the function name if it exists.
# positional arguments
# covnerts to a list of string representations first
args_str = list(map(str, args))
for i, arg in enumerate(args):
if callable(arg):
args_str[i] = arg.__name__
# keyword arguments
# converts to a list of string representations first
kwargs_str = {k: str(v) for k, v in kwargs.items()}
for k, v in kwargs.items():
if callable(v):
kwargs_str[k] = v.__name__
# then, convert to a single string, to obtain a unique hash
event = str((function_name, args_str, kwargs_str))
# TODO actually compute a short hash of the event string, e.g., using SHA256 ?
# event_hash = utils.custom_hash(event)
return event
def _skip_execution_with_cache(self):
"""
Skips the current execution, assuming there's a cached state at the same position.
"""
assert len(self.cached_trace) > self._execution_trace_position() + 1, "There's no cached state at the current execution position."
self.execution_trace.append(self.cached_trace[self._execution_trace_position() + 1])
def _is_transaction_event_cached(self, event_hash, parallel=False) -> bool:
"""
Checks whether the given event hash matches the corresponding cached one, if any.
If there's no corresponding cached state, returns True.
"""
if not parallel:
# there's cache that could be used
if len(self.cached_trace) > self._execution_trace_position() + 1:
if self._execution_trace_position() >= -1:
# here's a graphical depiction of the logic:
#
# Cache: c0:(c_prev_node_hash_0, c_event_hash_0, _, c_state_0) ------------------> c1:(c_prev_node_hash_1, c_event_hash_1, _, c_state_1) -> ...
# Execution: e0:(e_prev_node_hash_0, e_event_hash_0, _, e_state_0) -<being computed>-> e1:(e_prev_node_hash_1, <being computed>, <being computed>, <being computed>)
# position = 0 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# Must satisfy:
# - event_hash == c_event_hash_1
# - hash(e0) == c_prev_node_hash_1
try:
event_hash_match = event_hash == self.cached_trace[self._execution_trace_position() + 1][1]
except Exception as e:
logger.error(f"Error while checking event hash match: {e}")
event_hash_match = False
prev_node_match = True # TODO implement real check
return event_hash_match and prev_node_match
else:
raise ValueError("Execution trace position is invalid, must be >= -1, but is ", self._execution_trace_position())
else: # no cache to use
return False
else: # parallel
if len(self.cached_trace) >= self._execution_trace_position():
if self._execution_trace_position() >= 0:
# parallel stores ignore order, so we need to check instead whether the event hash is a key in the parallel store,
# regardless of the order of the events generated the data therein.
if isinstance(self.cached_trace[self._execution_trace_position()], dict):
event_hash_match = event_hash in self.cached_trace[self._execution_trace_position()].keys()
else:
event_hash_match = False
prev_node_match = True # TODO implement real check
return event_hash_match and prev_node_match
else:
raise ValueError("Execution trace position is invalid, must be >= 0, but is ", self._execution_trace_position())
def _get_cached_parallel_value(self, event_hash, key):
parallel_store = self.cached_trace[self._execution_trace_position()]
value = parallel_store[event_hash][key]
return value
def _drop_cached_trace_suffix(self):
"""
Drops the cached trace suffix starting at the current execution trace position. This effectively
refreshes the cache to the current execution state and starts building a new cache from there.
"""
self.cached_trace = self.cached_trace[:self._execution_trace_position()+1]
def _add_to_execution_trace(self, state: dict, event_hash: int, event_output, parallel=False):
"""
Adds a state to the execution_trace list and computes the appropriate hash.
The computed hash is compared to the hash of the cached trace at the same position,
and if they don't match, the execution is aborted. Similarly, the event_hash is compared
to the hash of the event in the cached trace at the same position, and if they don't match, the execution
is aborted.
"""
# Compute the hash of the previous execution pair, if any
previous_hash = None
if not parallel:
# Create a tuple of (hash, state) and append it to the execution_trace list
self.execution_trace.append((previous_hash, event_hash, event_output, state))
else:
with concurrent_execution_lock:
# state is not stored in parallel segments, only outputs
self.execution_trace[-1][event_hash] = {"prev_node_hash": previous_hash,
"encoded_output": event_output}
def _add_to_cache_trace(self, state: dict, event_hash: int, event_output, parallel=False):
"""
Adds a state to the cached_trace list and computes the appropriate hash.
"""
# Compute the hash of the previous cached pair, if any
previous_hash = None
if self.cached_trace:
previous_hash = utils.custom_hash(self.cached_trace[-1])
if not parallel:
# Create a tuple of (hash, state) and append it to the cached_trace list
self.cached_trace.append((previous_hash, event_hash, event_output, state))
else:
with concurrent_execution_lock:
# state is not stored in parallel segments, only outputs
self.cached_trace[-1][event_hash] = {"prev_node_hash": previous_hash,
"encoded_output": event_output}
self.has_unsaved_cache_changes = True
def _load_cache_file(self, cache_path:str):
"""
Loads the cache file from the given path.
"""
try:
self.cached_trace = json.load(open(cache_path, "r"))
except FileNotFoundError:
logger.info(f"Cache file not found on path: {cache_path}.")
self.cached_trace = []
def _save_cache_file(self, cache_path:str):
"""
Saves the cache file to the given path. Always overwrites.
"""
logger.debug(f"Now saving cache file to {cache_path}.")
try:
# Create a temporary file
with tempfile.NamedTemporaryFile('w', delete=False) as temp:
json.dump(self.cached_trace, temp, indent=4)
# Replace the original file with the temporary file
os.replace(temp.name, cache_path)
except Exception as e:
traceback_string = ''.join(traceback.format_tb(e.__traceback__))
logger.error(f"An error occurred while saving the cache file: {e}\nTraceback:\n{traceback_string}")
self.has_unsaved_cache_changes = False
###################################################################################################
# Transactional control
###################################################################################################
#
# Regular sequential transactions
#
def begin_transaction(self, id=None):
"""
Starts a transaction.
"""
with concurrent_execution_lock:
self._under_transaction[id] = True
self._clear_communications_buffers() # TODO <----------------------------------------------------------------
def end_transaction(self, id=None):
"""
Ends a transaction.
"""
with concurrent_execution_lock:
self._under_transaction[id] = False
def is_under_transaction(self, id=None):
"""
Checks if the agent is under a transaction.
"""
with concurrent_execution_lock:
return self._under_transaction.get(id, False)
def _clear_communications_buffers(self):
"""
Cleans the communications buffers of all agents and environments.
"""
for agent in self.agents:
agent.clear_communications_buffer()
for environment in self.environments:
environment.clear_communications_buffer()
#
# Parallel transactions
#
def begin_parallel_transactions(self):
"""
Starts parallel transactions.
"""
with concurrent_execution_lock:
self._under_parallel_transactions = True
# add a new parallel segment to the execution and cache traces
self.execution_trace.append({})
self.cached_trace.append({})
def end_parallel_transactions(self):
"""
Ends parallel transactions.
"""
self._under_parallel_transactions = False
def is_under_parallel_transactions(self):
"""
Checks if the agent is under parallel transactions.
"""
return self._under_parallel_transactions
###################################################################################################
# Simulation state handling
###################################################################################################
def _encode_simulation_state(self) -> dict:
"""
Encodes the current simulation state, including agents, environments, and other
relevant information.
"""
state = {}
# Encode agents
state["agents"] = []
for agent in self.agents:
state["agents"].append(agent.encode_complete_state())
# Encode environments
state["environments"] = []
for environment in self.environments:
state["environments"].append(environment.encode_complete_state())
# Encode factories
state["factories"] = []
for factory in self.factories:
state["factories"].append(factory.encode_complete_state())
return state
def _decode_simulation_state(self, state: dict):
"""
Decodes the given simulation state, including agents, environments, and other
relevant information.
Args:
state (dict): The state to decode.
"""
# local import to avoid circular dependencies
from tinytroupe.agent import TinyPerson
from tinytroupe.environment import TinyWorld
logger.debug(f"Decoding simulation state: {state['factories']}")
logger.debug(f"Registered factories: {self.name_to_factory}")
logger.debug(f"Registered agents: {self.name_to_agent}")
logger.debug(f"Registered environments: {self.name_to_environment}")
# Decode factories
for factory_state in state["factories"]:
factory = self.name_to_factory[factory_state["name"]]
factory.decode_complete_state(factory_state)
# Decode environments
###self.environments = []
for environment_state in state["environments"]:
try:
environment = self.name_to_environment[environment_state["name"]]
environment.decode_complete_state(environment_state)
if TinyWorld.communication_display:
environment.pop_and_display_latest_communications()
except Exception as e:
raise ValueError(f"Environment {environment_state['name']} is not in the simulation, thus cannot be decoded there.") from e
# Decode agents (if they were not already decoded by the environment)
####self.agents = []
for agent_state in state["agents"]:
try:
agent = self.name_to_agent[agent_state["name"]]
agent.decode_complete_state(agent_state)
# The agent has not yet been decoded because it is not in any environment. So, decode it.
if agent.environment is None:
if TinyPerson.communication_display:
agent.pop_and_display_latest_communications()
except Exception as e:
raise ValueError(f"Agent {agent_state['name']} is not in the simulation, thus cannot be decoded there.") from e
class Transaction:
def __init__(self, obj_under_transaction, simulation, function, *args, **kwargs):
# local import to avoid circular dependencies
from tinytroupe.agent import TinyPerson
from tinytroupe.environment import TinyWorld
from tinytroupe.factory.tiny_factory import TinyFactory
self.obj_under_transaction = obj_under_transaction
self.simulation = simulation
self.function_name = function.__name__
self.function = function
self.args = args
self.kwargs = kwargs
#
# If we have an ongoing simulation, set the simulation id of the object under transaction if it is not already set.
#
if simulation is not None:
if hasattr(obj_under_transaction, 'simulation_id') and obj_under_transaction.simulation_id is not None:
if obj_under_transaction.simulation_id != simulation.id:
raise ValueError(f"Object {obj_under_transaction} is already captured by a different simulation (id={obj_under_transaction.simulation_id}), \
and cannot be captured by simulation id={simulation.id}.")
logger.debug(f">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Object {obj_under_transaction} is already captured by simulation {simulation.id}.")
else:
# if is a TinyPerson, add the agent to the simulation
if isinstance(obj_under_transaction, TinyPerson):
simulation.add_agent(obj_under_transaction)
logger.debug(f">>>>>>>>>>>>>>>>>>>>>>> Added agent {obj_under_transaction} to simulation {simulation.id}.")
# if is a TinyWorld, add the environment to the simulation
elif isinstance(obj_under_transaction, TinyWorld):
simulation.add_environment(obj_under_transaction)
# if is a TinyFactory, add the factory to the simulation
elif isinstance(obj_under_transaction, TinyFactory):
simulation.add_factory(obj_under_transaction)
logger.debug(f">>>>>>>>>>>>>>>>>>>>>>> Added factory {obj_under_transaction} to simulation {simulation.id}.")
else:
raise ValueError(f"Object {obj_under_transaction} (type = {type(obj_under_transaction)}) is not a TinyPerson or TinyWorld instance, and cannot be captured by the simulation.")
def execute(self, begin_parallel=False, parallel_id=None):
output = None
# Transaction caching will only operate if there is a simulation and it is started
if self.simulation is None or self.simulation.status == Simulation.STATUS_STOPPED:
# Compute the function and return it, no caching, since the simulation is not started
output = self.function(*self.args, **self.kwargs)
elif self.simulation.status == Simulation.STATUS_STARTED:
# Compute the event hash
event_hash = self.simulation._function_call_hash(self.function_name, *self.args, **self.kwargs)
# Sequential and parallel transactions are handled in different ways
if begin_parallel:
self.simulation.begin_parallel_transactions()
# CACHED? Check if the event hash is in the cache
if self.simulation._is_transaction_event_cached(event_hash,
parallel=self.simulation.is_under_parallel_transactions()):
self.simulation.cache_hits += 1
# Restore the full state and return the cached output
logger.info(f"Skipping execution of {self.function_name} with args {self.args} and kwargs {self.kwargs} because it is already cached.")
# SEQUENTIAL
if not self.simulation.is_under_parallel_transactions():
self.simulation._skip_execution_with_cache()
state = self.simulation.cached_trace[self.simulation._execution_trace_position()][3] # state
self.simulation._decode_simulation_state(state)
# Output encoding/decoding is used to preserve references to TinyPerson and TinyWorld instances
# mainly. Scalar values (int, float, str, bool) and composite values (list, dict) are
# encoded/decoded as is.
encoded_output = self.simulation.cached_trace[self.simulation._execution_trace_position()][2] # output
output = self._decode_function_output(encoded_output)
# PARALLEL
else: # is under parallel transactions
# in parallel segments, state is not restored, only outputs
encoded_output = self.simulation._get_cached_parallel_value(event_hash, "encoded_output")
output = self._decode_function_output(encoded_output)
else: # not cached
if not begin_parallel:
# in case of beginning a parallel segment, we don't want to count it as a cache miss,
# since the segment itself will not be cached, but rather the events within it.
self.simulation.cache_misses += 1
if not self.simulation.is_under_transaction(id=parallel_id) and not begin_parallel:
# BEGIN SEQUENTIAL TRANSACTION ###############################################################
#
# if this is the beginning of a parallel segment, we don't need to begin a transaction, since
# we want to allow additional transactions within the parallel segment (i.e., one-level reentrancy).
if not begin_parallel:
self.simulation.begin_transaction(id=parallel_id)
# Compute the function and encode the relevant output and simulation state
output = self.function(*self.args, **self.kwargs)
self._save_output_with_simulation_state(event_hash, output)
# END TRANSACTION #################################################################
if not begin_parallel:
self.simulation.end_transaction(id=parallel_id)
else: # already under transaction (thus, now a reentrant transaction) OR beginning a parallel segment
# NOTES:
#
# - Reentrant sequential transactions are not cached, since what matters is the final result of
# the top-level transaction.
#
# - The event that starts the parallel transactions segment WILL NOT itself be cached, since
# it is not part of the parallel segment, but rather the beginning of it. This event will be
# reconstructed during runtime from the parallel events within the segment.
output = self.function(*self.args, **self.kwargs)
if begin_parallel:
self.simulation.end_parallel_transactions()
# execute an ad-hoc Transaction to save the simulation state AFTER the parallel segment is done.
Transaction(self.obj_under_transaction, self.simulation, lambda: True).execute(begin_parallel=False, parallel_id=parallel_id)
else:
raise ValueError(f"Simulation status is invalid at this point: {self.simulation.status}")
# Checkpoint if needed
logger.debug(f"Will attempt to checkpoint simulation state after transaction execution.")
if self.simulation is not None and self.simulation.auto_checkpoint:
logger.debug("Auto-checkpointing simulation state after transaction execution.")
self.simulation.checkpoint()
# after all the transaction is done, return the output - the client will never know about all the complexity we've
# gone through to get here.
return output
def _save_output_with_simulation_state(self, event_hash, output):
encoded_output = self._encode_function_output(output)
state = self.simulation._encode_simulation_state()
# immediately drop the cached trace suffix, since we are starting a new execution from this point on.
# in the case of parallel transactions, this will drop everything _after_ the current parallel segment
# (which itself occupies one position only, with a dictionary of event hashes and their outputs).
self.simulation._drop_cached_trace_suffix()
# Cache the result and update the current execution trace. If this is a parallel transaction, the
# cache and execution traces will be updated in a different way.
self.simulation._add_to_cache_trace(state, event_hash, encoded_output,
parallel=self.simulation.is_under_parallel_transactions())
self.simulation._add_to_execution_trace(state, event_hash, encoded_output,
parallel=self.simulation.is_under_parallel_transactions())
def _encode_function_output(self, output) -> dict:
"""
Encodes the given function output.
"""
# local import to avoid circular dependencies
from tinytroupe.agent import TinyPerson
from tinytroupe.environment import TinyWorld
from tinytroupe.factory.tiny_factory import TinyFactory
# if the output is a supported object, encode it
if output is None:
return None
elif isinstance(output, TinyPerson):
return {"type": "TinyPersonRef", "name": output.name}
elif isinstance(output, TinyWorld):
return {"type": "TinyWorldRef", "name": output.name}
elif isinstance(output, TinyFactory):
return {"type": "TinyFactoryRef", "name": output.name}
elif isinstance(output, list):
encoded_list = []
for item in output:
if isinstance(item, TinyPerson):
encoded_list.append({"type": "TinyPersonRef", "name": item.name})
elif isinstance(item, TinyWorld):
encoded_list.append({"type": "TinyWorldRef", "name": item.name})
elif isinstance(item, TinyFactory):
encoded_list.append({"type": "TinyFactoryRef", "name": item.name})
else:
encoded_list.append({"type": "JSON", "value": item})
return {"type": "List", "value": encoded_list}
elif isinstance(output, (int, float, str, bool, dict, tuple)):
return {"type": "JSON", "value": output}
else:
raise ValueError(f"Unsupported output type: {type(output)}")
def _decode_function_output(self, encoded_output: dict):
"""
Decodes the given encoded function output.
"""
# local import to avoid circular dependencies
from tinytroupe.agent import TinyPerson
from tinytroupe.environment import TinyWorld
from tinytroupe.factory.tiny_factory import TinyFactory
if encoded_output is None:
return None
elif encoded_output["type"] == "TinyPersonRef":
return TinyPerson.get_agent_by_name(encoded_output["name"])
elif encoded_output["type"] == "TinyWorldRef":
return TinyWorld.get_environment_by_name(encoded_output["name"])
elif encoded_output["type"] == "TinyFactoryRef":
return TinyFactory.get_factory_by_name(encoded_output["name"])
elif encoded_output["type"] == "List":
decoded_list = []
for item in encoded_output["value"]:
if item["type"] == "TinyPersonRef":
decoded_list.append(TinyPerson.get_agent_by_name(item["name"]))
elif item["type"] == "TinyWorldRef":
decoded_list.append(TinyWorld.get_environment_by_name(item["name"]))
elif item["type"] == "TinyFactoryRef":
decoded_list.append(TinyFactory.get_factory_by_name(item["name"]))
else:
decoded_list.append(item["value"])
return decoded_list
elif encoded_output["type"] == "JSON":
return encoded_output["value"]
else:
raise ValueError(f"Unsupported output type: {encoded_output['type']}")
def transactional(parallel=False):
"""
A helper decorator that makes a function simulation-transactional.
"""
def decorator(func):
def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result
return wrapper
return decorator
class SkipTransaction(Exception):
pass
class CacheOutOfSync(Exception):
"""
Raised when a cached and the corresponding freshly executed elements are out of sync.
"""
pass
class ExecutionCached(Exception):
"""
Raised when a proposed execution is already cached.
"""
pass
###################################################################################################
# Convenience functions
###################################################################################################
def reset():
"""
Resets the entire simulation control state.
"""
global _current_simulations, _current_simulation_id
_current_simulations = {"default": None}
# TODO Currently, only one simulation can be started at a time. In future versions, this should be
# changed to allow multiple simulations to be started at the same time, e.g., for fast
# analyses through parallelization.
_current_simulation_id = None
def _simulation(id="default"):
global _current_simulations
if _current_simulations[id] is None:
_current_simulations[id] = Simulation()
return _current_simulations[id]
def begin(cache_path=None, id="default", auto_checkpoint=False):
"""
Marks the start of the simulation being controlled.
"""
global _current_simulation_id
if _current_simulation_id is None:
_simulation(id).begin(cache_path, auto_checkpoint)
_current_simulation_id = id
else:
raise ValueError(f"Simulation is already started under id {_current_simulation_id}. Currently only one simulation can be started at a time.")
def end(id="default"):
"""
Marks the end of the simulation being controlled.
"""
global _current_simulation_id
_simulation(id).end()
_current_simulation_id = None
def checkpoint(id="default"):
"""
Saves current simulation state.
"""
_simulation(id).checkpoint()
def current_simulation():
"""
Returns the current simulation.
"""
global _current_simulation_id
if _current_simulation_id is not None:
return _simulation(_current_simulation_id)
else:
return None
def cache_hits(id="default"):
"""
Returns the number of cache hits.
"""
return _simulation(id).cache_hits
def cache_misses(id="default"):
"""
Returns the number of cache misses.
"""
return _simulation(id).cache_misses
reset() # initialize the control state</code></pre>
</details>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="tinytroupe.control.begin"><code class="name flex">
<span>def <span class="ident">begin</span></span>(<span>cache_path=None, id='default', auto_checkpoint=False)</span>
</code></dt>
<dd>
<div class="desc"><p>Marks the start of the simulation being controlled.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def begin(cache_path=None, id="default", auto_checkpoint=False):
"""
Marks the start of the simulation being controlled.
"""
global _current_simulation_id
if _current_simulation_id is None:
_simulation(id).begin(cache_path, auto_checkpoint)
_current_simulation_id = id
else:
raise ValueError(f"Simulation is already started under id {_current_simulation_id}. Currently only one simulation can be started at a time.") </code></pre>
</details>
</dd>
<dt id="tinytroupe.control.cache_hits"><code class="name flex">
<span>def <span class="ident">cache_hits</span></span>(<span>id='default')</span>
</code></dt>
<dd>
<div class="desc"><p>Returns the number of cache hits.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def cache_hits(id="default"):
"""
Returns the number of cache hits.
"""
return _simulation(id).cache_hits</code></pre>
</details>
</dd>
<dt id="tinytroupe.control.cache_misses"><code class="name flex">
<span>def <span class="ident">cache_misses</span></span>(<span>id='default')</span>
</code></dt>
<dd>
<div class="desc"><p>Returns the number of cache misses.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def cache_misses(id="default"):
"""
Returns the number of cache misses.
"""
return _simulation(id).cache_misses</code></pre>
</details>
</dd>
<dt id="tinytroupe.control.checkpoint"><code class="name flex">
<span>def <span class="ident">checkpoint</span></span>(<span>id='default')</span>
</code></dt>
<dd>
<div class="desc"><p>Saves current simulation state.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def checkpoint(id="default"):
"""
Saves current simulation state.
"""
_simulation(id).checkpoint()</code></pre>
</details>
</dd>
<dt id="tinytroupe.control.current_simulation"><code class="name flex">
<span>def <span class="ident">current_simulation</span></span>(<span>)</span>
</code></dt>
<dd>
<div class="desc"><p>Returns the current simulation.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def current_simulation():
"""
Returns the current simulation.
"""
global _current_simulation_id
if _current_simulation_id is not None:
return _simulation(_current_simulation_id)
else:
return None</code></pre>
</details>
</dd>
<dt id="tinytroupe.control.end"><code class="name flex">
<span>def <span class="ident">end</span></span>(<span>id='default')</span>
</code></dt>
<dd>
<div class="desc"><p>Marks the end of the simulation being controlled.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def end(id="default"):
"""
Marks the end of the simulation being controlled.
"""
global _current_simulation_id
_simulation(id).end()
_current_simulation_id = None</code></pre>
</details>
</dd>
<dt id="tinytroupe.control.reset"><code class="name flex">
<span>def <span class="ident">reset</span></span>(<span>)</span>
</code></dt>
<dd>
<div class="desc"><p>Resets the entire simulation control state.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def reset():
"""
Resets the entire simulation control state.
"""
global _current_simulations, _current_simulation_id
_current_simulations = {"default": None}
# TODO Currently, only one simulation can be started at a time. In future versions, this should be
# changed to allow multiple simulations to be started at the same time, e.g., for fast
# analyses through parallelization.
_current_simulation_id = None</code></pre>
</details>
</dd>
<dt id="tinytroupe.control.transactional"><code class="name flex">
<span>def <span class="ident">transactional</span></span>(<span>parallel=False)</span>
</code></dt>
<dd>
<div class="desc"><p>A helper decorator that makes a function simulation-transactional.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def transactional(parallel=False):
"""
A helper decorator that makes a function simulation-transactional.
"""
def decorator(func):
def wrapper(*args, **kwargs):
obj_under_transaction = args[0]
simulation = current_simulation()
obj_sim_id = obj_under_transaction.simulation_id if hasattr(obj_under_transaction, 'simulation_id') else None
logger.debug(f"-----------------------------------------> Transaction: {func.__name__} with args {args[1:]} and kwargs {kwargs} under simulation {obj_sim_id}, parallel={parallel}.")
parallel_id = str(threading.current_thread())
transaction = Transaction(obj_under_transaction, simulation, func, *args, **kwargs)
result = transaction.execute(begin_parallel=parallel, parallel_id=parallel_id)
return result
return wrapper
return decorator</code></pre>
</details>
</dd>
</dl>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="tinytroupe.control.CacheOutOfSync"><code class="flex name class">
<span>class <span class="ident">CacheOutOfSync</span></span>
<span>(</span><span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"><p>Raised when a cached and the corresponding freshly executed elements are out of sync.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class CacheOutOfSync(Exception):
"""
Raised when a cached and the corresponding freshly executed elements are out of sync.
"""
pass</code></pre>
</details>
<h3>Ancestors</h3>
<ul class="hlist">
<li>builtins.Exception</li>
<li>builtins.BaseException</li>
</ul>
</dd>
<dt id="tinytroupe.control.ExecutionCached"><code class="flex name class">
<span>class <span class="ident">ExecutionCached</span></span>
<span>(</span><span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"><p>Raised when a proposed execution is already cached.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class ExecutionCached(Exception):
"""
Raised when a proposed execution is already cached.
"""
pass</code></pre>
</details>
<h3>Ancestors</h3>
<ul class="hlist">
<li>builtins.Exception</li>
<li>builtins.BaseException</li>
</ul>
</dd>
<dt id="tinytroupe.control.Simulation"><code class="flex name class">
<span>class <span class="ident">Simulation</span></span>
<span>(</span><span>id='default', cached_trace: list = None)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class Simulation:
STATUS_STOPPED = "stopped"
STATUS_STARTED = "started"
def __init__(self, id="default", cached_trace:list=None):
self.id = id
self.agents = []
self.name_to_agent = {} # {agent_name: agent, ...}
self.environments = []
self.factories = [] # e.g., TinyPersonFactory instances
self.name_to_factory = {} # {factory_name: factory, ...}
self.name_to_environment = {} # {environment_name: environment, ...}
self.status = Simulation.STATUS_STOPPED
self.cache_path = f"./tinytroupe-{id}.cache.json" # default cache path
# should we always automatically checkpoint at the every transaction?
self.auto_checkpoint = False
# whether there are changes not yet saved to the cache file
self.has_unsaved_cache_changes = False
# whether the agent is under a transaction or not, used for managing
# simulation caching later
self._under_transaction = {None: False}
# whether the agent is under a parallel transactions segment or not, used for managing
# simulation caching later
self._under_parallel_transactions = False
# Cache chain mechanism.
#
# stores a list of simulation states.
# Each state is a tuple (prev_node_hash, event_hash, event_output, state), where prev_node_hash is a hash of the previous node in this chain,
# if any, event_hash is a hash of the event that triggered the transition to this state, if any, event_output is the output of the event,
# if any, and state is the actual complete state that resulted.
if cached_trace is None:
self.cached_trace = []
else:
self.cached_trace = cached_trace
self.cache_misses = 0
self.cache_hits = 0
# Execution chain mechanism.
#
# The actual, current, execution trace. Each state is a tuple (prev_node_hash, event_hash, state), where prev_node_hash is a hash
# of the previous node in this chain, if any, event_hash is a hash of the event that triggered the transition to this state, if any,
# event_output is the output of the event, if any, and state is the actual complete state that resulted.
self.execution_trace = []
def begin(self, cache_path:str=None, auto_checkpoint:bool=False):
"""
Marks the start of the simulation being controlled.
Args:
cache_path (str): The path to the cache file. If not specified,
defaults to the default cache path defined in the class.
auto_checkpoint (bool, optional): Whether to automatically checkpoint at the end of each transaction. Defaults to False.
"""
logger.debug(f"Starting simulation, cache_path={cache_path}, auto_checkpoint={auto_checkpoint}.")
# local import to avoid circular dependencies
from tinytroupe.agent import TinyPerson
from tinytroupe.environment import TinyWorld
from tinytroupe.factory.tiny_factory import TinyFactory
from tinytroupe.factory.tiny_person_factory import TinyPersonFactory
if self.status == Simulation.STATUS_STOPPED:
self.status = Simulation.STATUS_STARTED
else:
raise ValueError("Simulation is already started.")
if cache_path is not None:
self.cache_path = cache_path
# should we automatically checkpoint?
self.auto_checkpoint = auto_checkpoint
# clear the agents, environments and other simulated entities, we'll track them from now on
TinyPerson.clear_agents()
TinyWorld.clear_environments()
TinyFactory.clear_factories()
TinyPersonFactory.clear_factories()
# All automated fresh ids will start from 0 again for this simulation
utils.reset_fresh_id()
# load the cache file, if any
if self.cache_path is not None:
self._load_cache_file(self.cache_path)
def end(self):
"""
Marks the end of the simulation being controlled.
"""
logger.debug("Ending simulation.")
if self.status == Simulation.STATUS_STARTED:
self.status = Simulation.STATUS_STOPPED
self.checkpoint()
else:
raise ValueError("Simulation is already stopped.")
def checkpoint(self):
"""
Saves current simulation trace to a file.
"""
logger.debug("Checkpointing simulation state...")
# save the cache file
if self.has_unsaved_cache_changes:
self._save_cache_file(self.cache_path)
else:
logger.debug("No unsaved cache changes to save to file.")
def add_agent(self, agent):
"""
Adds an agent to the simulation.
"""
if agent.name in self.name_to_agent:
raise ValueError(f"Agent names must be unique, but '{agent.name}' is already defined.")
agent.simulation_id = self.id
self.agents.append(agent)
self.name_to_agent[agent.name] = agent
def add_environment(self, environment):
"""
Adds an environment to the simulation.
"""
if environment.name in self.name_to_environment:
raise ValueError(f"Environment names must be unique, but '{environment.name}' is already defined.")
environment.simulation_id = self.id
self.environments.append(environment)
self.name_to_environment[environment.name] = environment
def add_factory(self, factory):
"""
Adds a factory to the simulation.
"""
if factory.name in self.name_to_factory:
raise ValueError(f"Factory names must be unique, but '{factory.name}' is already defined.")
factory.simulation_id = self.id
self.factories.append(factory)
self.name_to_factory[factory.name] = factory
###################################################################################################
# Cache and execution chain mechanisms
###################################################################################################
def _execution_trace_position(self) -> int:
"""
Returns the current position in the execution trace, or -1 if the execution trace is empty.
"""
return len(self.execution_trace) - 1
def _function_call_hash(self, function_name, *args, **kwargs) -> int:
"""
Computes the hash of the given function call.
"""
# if functions are passed as arguments to the function, there's the problem that their
# string representation always changes due to memory position (e.g., <function my_function at 0x7f8d1a7b7d30>).
# so we need to remove the changing suffix in those cases, while preserving the function name if it exists.
# positional arguments
# covnerts to a list of string representations first
args_str = list(map(str, args))
for i, arg in enumerate(args):
if callable(arg):
args_str[i] = arg.__name__
# keyword arguments
# converts to a list of string representations first
kwargs_str = {k: str(v) for k, v in kwargs.items()}
for k, v in kwargs.items():
if callable(v):
kwargs_str[k] = v.__name__
# then, convert to a single string, to obtain a unique hash
event = str((function_name, args_str, kwargs_str))
# TODO actually compute a short hash of the event string, e.g., using SHA256 ?
# event_hash = utils.custom_hash(event)
return event
def _skip_execution_with_cache(self):
"""
Skips the current execution, assuming there's a cached state at the same position.
"""
assert len(self.cached_trace) > self._execution_trace_position() + 1, "There's no cached state at the current execution position."
self.execution_trace.append(self.cached_trace[self._execution_trace_position() + 1])
def _is_transaction_event_cached(self, event_hash, parallel=False) -> bool:
"""
Checks whether the given event hash matches the corresponding cached one, if any.
If there's no corresponding cached state, returns True.
"""
if not parallel:
# there's cache that could be used
if len(self.cached_trace) > self._execution_trace_position() + 1:
if self._execution_trace_position() >= -1:
# here's a graphical depiction of the logic:
#
# Cache: c0:(c_prev_node_hash_0, c_event_hash_0, _, c_state_0) ------------------> c1:(c_prev_node_hash_1, c_event_hash_1, _, c_state_1) -> ...
# Execution: e0:(e_prev_node_hash_0, e_event_hash_0, _, e_state_0) -<being computed>-> e1:(e_prev_node_hash_1, <being computed>, <being computed>, <being computed>)
# position = 0 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# Must satisfy:
# - event_hash == c_event_hash_1
# - hash(e0) == c_prev_node_hash_1
try:
event_hash_match = event_hash == self.cached_trace[self._execution_trace_position() + 1][1]
except Exception as e:
logger.error(f"Error while checking event hash match: {e}")
event_hash_match = False
prev_node_match = True # TODO implement real check
return event_hash_match and prev_node_match
else:
raise ValueError("Execution trace position is invalid, must be >= -1, but is ", self._execution_trace_position())
else: # no cache to use
return False
else: # parallel
if len(self.cached_trace) >= self._execution_trace_position():
if self._execution_trace_position() >= 0:
# parallel stores ignore order, so we need to check instead whether the event hash is a key in the parallel store,
# regardless of the order of the events generated the data therein.
if isinstance(self.cached_trace[self._execution_trace_position()], dict):
event_hash_match = event_hash in self.cached_trace[self._execution_trace_position()].keys()
else:
event_hash_match = False
prev_node_match = True # TODO implement real check
return event_hash_match and prev_node_match
else:
raise ValueError("Execution trace position is invalid, must be >= 0, but is ", self._execution_trace_position())
def _get_cached_parallel_value(self, event_hash, key):
parallel_store = self.cached_trace[self._execution_trace_position()]
value = parallel_store[event_hash][key]
return value
def _drop_cached_trace_suffix(self):
"""
Drops the cached trace suffix starting at the current execution trace position. This effectively
refreshes the cache to the current execution state and starts building a new cache from there.
"""
self.cached_trace = self.cached_trace[:self._execution_trace_position()+1]
def _add_to_execution_trace(self, state: dict, event_hash: int, event_output, parallel=False):
"""
Adds a state to the execution_trace list and computes the appropriate hash.
The computed hash is compared to the hash of the cached trace at the same position,
and if they don't match, the execution is aborted. Similarly, the event_hash is compared
to the hash of the event in the cached trace at the same position, and if they don't match, the execution
is aborted.
"""
# Compute the hash of the previous execution pair, if any
previous_hash = None
if not parallel:
# Create a tuple of (hash, state) and append it to the execution_trace list
self.execution_trace.append((previous_hash, event_hash, event_output, state))
else:
with concurrent_execution_lock:
# state is not stored in parallel segments, only outputs
self.execution_trace[-1][event_hash] = {"prev_node_hash": previous_hash,
"encoded_output": event_output}
def _add_to_cache_trace(self, state: dict, event_hash: int, event_output, parallel=False):
"""
Adds a state to the cached_trace list and computes the appropriate hash.
"""
# Compute the hash of the previous cached pair, if any
previous_hash = None
if self.cached_trace:
previous_hash = utils.custom_hash(self.cached_trace[-1])
if not parallel:
# Create a tuple of (hash, state) and append it to the cached_trace list
self.cached_trace.append((previous_hash, event_hash, event_output, state))
else:
with concurrent_execution_lock:
# state is not stored in parallel segments, only outputs
self.cached_trace[-1][event_hash] = {"prev_node_hash": previous_hash,
"encoded_output": event_output}
self.has_unsaved_cache_changes = True
def _load_cache_file(self, cache_path:str):
"""
Loads the cache file from the given path.
"""
try:
self.cached_trace = json.load(open(cache_path, "r"))
except FileNotFoundError:
logger.info(f"Cache file not found on path: {cache_path}.")
self.cached_trace = []
def _save_cache_file(self, cache_path:str):
"""
Saves the cache file to the given path. Always overwrites.
"""
logger.debug(f"Now saving cache file to {cache_path}.")
try:
# Create a temporary file
with tempfile.NamedTemporaryFile('w', delete=False) as temp:
json.dump(self.cached_trace, temp, indent=4)
# Replace the original file with the temporary file
os.replace(temp.name, cache_path)
except Exception as e:
traceback_string = ''.join(traceback.format_tb(e.__traceback__))
logger.error(f"An error occurred while saving the cache file: {e}\nTraceback:\n{traceback_string}")
self.has_unsaved_cache_changes = False
###################################################################################################
# Transactional control
###################################################################################################
#
# Regular sequential transactions
#
def begin_transaction(self, id=None):
"""
Starts a transaction.
"""
with concurrent_execution_lock:
self._under_transaction[id] = True
self._clear_communications_buffers() # TODO <----------------------------------------------------------------
def end_transaction(self, id=None):
"""
Ends a transaction.
"""
with concurrent_execution_lock:
self._under_transaction[id] = False
def is_under_transaction(self, id=None):
"""
Checks if the agent is under a transaction.
"""
with concurrent_execution_lock:
return self._under_transaction.get(id, False)
def _clear_communications_buffers(self):
"""
Cleans the communications buffers of all agents and environments.
"""
for agent in self.agents:
agent.clear_communications_buffer()
for environment in self.environments:
environment.clear_communications_buffer()
#
# Parallel transactions
#
def begin_parallel_transactions(self):
"""
Starts parallel transactions.
"""
with concurrent_execution_lock:
self._under_parallel_transactions = True
# add a new parallel segment to the execution and cache traces
self.execution_trace.append({})
self.cached_trace.append({})
def end_parallel_transactions(self):
"""
Ends parallel transactions.
"""
self._under_parallel_transactions = False
def is_under_parallel_transactions(self):
"""
Checks if the agent is under parallel transactions.
"""
return self._under_parallel_transactions
###################################################################################################
# Simulation state handling
###################################################################################################
def _encode_simulation_state(self) -> dict:
"""
Encodes the current simulation state, including agents, environments, and other
relevant information.
"""
state = {}
# Encode agents
state["agents"] = []
for agent in self.agents:
state["agents"].append(agent.encode_complete_state())
# Encode environments
state["environments"] = []
for environment in self.environments:
state["environments"].append(environment.encode_complete_state())
# Encode factories
state["factories"] = []
for factory in self.factories:
state["factories"].append(factory.encode_complete_state())
return state
def _decode_simulation_state(self, state: dict):
"""
Decodes the given simulation state, including agents, environments, and other
relevant information.
Args:
state (dict): The state to decode.
"""
# local import to avoid circular dependencies
from tinytroupe.agent import TinyPerson
from tinytroupe.environment import TinyWorld
logger.debug(f"Decoding simulation state: {state['factories']}")
logger.debug(f"Registered factories: {self.name_to_factory}")
logger.debug(f"Registered agents: {self.name_to_agent}")
logger.debug(f"Registered environments: {self.name_to_environment}")
# Decode factories
for factory_state in state["factories"]:
factory = self.name_to_factory[factory_state["name"]]
factory.decode_complete_state(factory_state)
# Decode environments
###self.environments = []
for environment_state in state["environments"]:
try:
environment = self.name_to_environment[environment_state["name"]]
environment.decode_complete_state(environment_state)
if TinyWorld.communication_display:
environment.pop_and_display_latest_communications()
except Exception as e:
raise ValueError(f"Environment {environment_state['name']} is not in the simulation, thus cannot be decoded there.") from e
# Decode agents (if they were not already decoded by the environment)
####self.agents = []
for agent_state in state["agents"]:
try:
agent = self.name_to_agent[agent_state["name"]]
agent.decode_complete_state(agent_state)
# The agent has not yet been decoded because it is not in any environment. So, decode it.
if agent.environment is None:
if TinyPerson.communication_display:
agent.pop_and_display_latest_communications()
except Exception as e:
raise ValueError(f"Agent {agent_state['name']} is not in the simulation, thus cannot be decoded there.") from e </code></pre>
</details>
<h3>Class variables</h3>
<dl>
<dt id="tinytroupe.control.Simulation.STATUS_STARTED"><code class="name">var <span class="ident">STATUS_STARTED</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="tinytroupe.control.Simulation.STATUS_STOPPED"><code class="name">var <span class="ident">STATUS_STOPPED</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="tinytroupe.control.Simulation.add_agent"><code class="name flex">
<span>def <span class="ident">add_agent</span></span>(<span>self, agent)</span>
</code></dt>
<dd>
<div class="desc"><p>Adds an agent to the simulation.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def add_agent(self, agent):
"""
Adds an agent to the simulation.
"""
if agent.name in self.name_to_agent:
raise ValueError(f"Agent names must be unique, but '{agent.name}' is already defined.")
agent.simulation_id = self.id
self.agents.append(agent)
self.name_to_agent[agent.name] = agent</code></pre>
</details>
</dd>
<dt id="tinytroupe.control.Simulation.add_environment"><code class="name flex">
<span>def <span class="ident">add_environment</span></span>(<span>self, environment)</span>
</code></dt>
<dd>
<div class="desc"><p>Adds an environment to the simulation.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def add_environment(self, environment):
"""
Adds an environment to the simulation.
"""
if environment.name in self.name_to_environment:
raise ValueError(f"Environment names must be unique, but '{environment.name}' is already defined.")
environment.simulation_id = self.id
self.environments.append(environment)
self.name_to_environment[environment.name] = environment</code></pre>
</details>
</dd>
<dt id="tinytroupe.control.Simulation.add_factory"><code class="name flex">
<span>def <span class="ident">add_factory</span></span>(<span>self, factory)</span>
</code></dt>
<dd>
<div class="desc"><p>Adds a factory to the simulation.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def add_factory(self, factory):
"""
Adds a factory to the simulation.
"""
if factory.name in self.name_to_factory:
raise ValueError(f"Factory names must be unique, but '{factory.name}' is already defined.")
factory.simulation_id = self.id
self.factories.append(factory)
self.name_to_factory[factory.name] = factory</code></pre>
</details>
</dd>
<dt id="tinytroupe.control.Simulation.begin"><code class="name flex">
<span>def <span class="ident">begin</span></span>(<span>self, cache_path: str = None, auto_checkpoint: bool = False)</span>
</code></dt>
<dd>
<div class="desc"><p>Marks the start of the simulation being controlled.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>cache_path</code></strong> : <code>str</code></dt>
<dd>The path to the cache file. If not specified,
defaults to the default cache path defined in the class.</dd>
<dt><strong><code>auto_checkpoint</code></strong> : <code>bool</code>, optional</dt>
<dd>Whether to automatically checkpoint at the end of each transaction. Defaults to False.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def begin(self, cache_path:str=None, auto_checkpoint:bool=False):
"""
Marks the start of the simulation being controlled.
Args:
cache_path (str): The path to the cache file. If not specified,
defaults to the default cache path defined in the class.
auto_checkpoint (bool, optional): Whether to automatically checkpoint at the end of each transaction. Defaults to False.
"""
logger.debug(f"Starting simulation, cache_path={cache_path}, auto_checkpoint={auto_checkpoint}.")
# local import to avoid circular dependencies
from tinytroupe.agent import TinyPerson
from tinytroupe.environment import TinyWorld
from tinytroupe.factory.tiny_factory import TinyFactory
from tinytroupe.factory.tiny_person_factory import TinyPersonFactory
if self.status == Simulation.STATUS_STOPPED:
self.status = Simulation.STATUS_STARTED
else:
raise ValueError("Simulation is already started.")
if cache_path is not None:
self.cache_path = cache_path
# should we automatically checkpoint?
self.auto_checkpoint = auto_checkpoint
# clear the agents, environments and other simulated entities, we'll track them from now on
TinyPerson.clear_agents()
TinyWorld.clear_environments()
TinyFactory.clear_factories()
TinyPersonFactory.clear_factories()
# All automated fresh ids will start from 0 again for this simulation
utils.reset_fresh_id()
# load the cache file, if any
if self.cache_path is not None:
self._load_cache_file(self.cache_path)</code></pre>
</details>
</dd>
<dt id="tinytroupe.control.Simulation.begin_parallel_transactions"><code class="name flex">
<span>def <span class="ident">begin_parallel_transactions</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Starts parallel transactions.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def begin_parallel_transactions(self):
"""
Starts parallel transactions.
"""
with concurrent_execution_lock:
self._under_parallel_transactions = True
# add a new parallel segment to the execution and cache traces
self.execution_trace.append({})
self.cached_trace.append({})</code></pre>
</details>
</dd>
<dt id="tinytroupe.control.Simulation.begin_transaction"><code class="name flex">
<span>def <span class="ident">begin_transaction</span></span>(<span>self, id=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Starts a transaction.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def begin_transaction(self, id=None):
"""
Starts a transaction.
"""
with concurrent_execution_lock:
self._under_transaction[id] = True
self._clear_communications_buffers() # TODO <----------------------------------------------------------------</code></pre>
</details>
</dd>
<dt id="tinytroupe.control.Simulation.checkpoint"><code class="name flex">
<span>def <span class="ident">checkpoint</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Saves current simulation trace to a file.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def checkpoint(self):
"""
Saves current simulation trace to a file.
"""
logger.debug("Checkpointing simulation state...")
# save the cache file
if self.has_unsaved_cache_changes:
self._save_cache_file(self.cache_path)
else:
logger.debug("No unsaved cache changes to save to file.")</code></pre>
</details>
</dd>
<dt id="tinytroupe.control.Simulation.end"><code class="name flex">
<span>def <span class="ident">end</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Marks the end of the simulation being controlled.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def end(self):
"""
Marks the end of the simulation being controlled.
"""
logger.debug("Ending simulation.")
if self.status == Simulation.STATUS_STARTED:
self.status = Simulation.STATUS_STOPPED
self.checkpoint()
else:
raise ValueError("Simulation is already stopped.")</code></pre>
</details>
</dd>
<dt id="tinytroupe.control.Simulation.end_parallel_transactions"><code class="name flex">
<span>def <span class="ident">end_parallel_transactions</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Ends parallel transactions.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def end_parallel_transactions(self):
"""
Ends parallel transactions.
"""
self._under_parallel_transactions = False</code></pre>
</details>
</dd>
<dt id="tinytroupe.control.Simulation.end_transaction"><code class="name flex">
<span>def <span class="ident">end_transaction</span></span>(<span>self, id=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Ends a transaction.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def end_transaction(self, id=None):
"""
Ends a transaction.
"""
with concurrent_execution_lock:
self._under_transaction[id] = False</code></pre>
</details>
</dd>
<dt id="tinytroupe.control.Simulation.is_under_parallel_transactions"><code class="name flex">
<span>def <span class="ident">is_under_parallel_transactions</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Checks if the agent is under parallel transactions.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def is_under_parallel_transactions(self):
"""
Checks if the agent is under parallel transactions.
"""
return self._under_parallel_transactions</code></pre>
</details>
</dd>
<dt id="tinytroupe.control.Simulation.is_under_transaction"><code class="name flex">
<span>def <span class="ident">is_under_transaction</span></span>(<span>self, id=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Checks if the agent is under a transaction.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def is_under_transaction(self, id=None):
"""
Checks if the agent is under a transaction.
"""
with concurrent_execution_lock:
return self._under_transaction.get(id, False)</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="tinytroupe.control.SkipTransaction"><code class="flex name class">
<span>class <span class="ident">SkipTransaction</span></span>
<span>(</span><span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"><p>Common base class for all non-exit exceptions.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class SkipTransaction(Exception):
pass</code></pre>
</details>
<h3>Ancestors</h3>
<ul class="hlist">
<li>builtins.Exception</li>
<li>builtins.BaseException</li>
</ul>
</dd>
<dt id="tinytroupe.control.Transaction"><code class="flex name class">
<span>class <span class="ident">Transaction</span></span>
<span>(</span><span>obj_under_transaction, simulation, function, *args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class Transaction:
def __init__(self, obj_under_transaction, simulation, function, *args, **kwargs):
# local import to avoid circular dependencies
from tinytroupe.agent import TinyPerson
from tinytroupe.environment import TinyWorld
from tinytroupe.factory.tiny_factory import TinyFactory
self.obj_under_transaction = obj_under_transaction
self.simulation = simulation
self.function_name = function.__name__
self.function = function
self.args = args
self.kwargs = kwargs
#
# If we have an ongoing simulation, set the simulation id of the object under transaction if it is not already set.
#
if simulation is not None:
if hasattr(obj_under_transaction, 'simulation_id') and obj_under_transaction.simulation_id is not None:
if obj_under_transaction.simulation_id != simulation.id:
raise ValueError(f"Object {obj_under_transaction} is already captured by a different simulation (id={obj_under_transaction.simulation_id}), \
and cannot be captured by simulation id={simulation.id}.")
logger.debug(f">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Object {obj_under_transaction} is already captured by simulation {simulation.id}.")
else:
# if is a TinyPerson, add the agent to the simulation
if isinstance(obj_under_transaction, TinyPerson):
simulation.add_agent(obj_under_transaction)
logger.debug(f">>>>>>>>>>>>>>>>>>>>>>> Added agent {obj_under_transaction} to simulation {simulation.id}.")
# if is a TinyWorld, add the environment to the simulation
elif isinstance(obj_under_transaction, TinyWorld):
simulation.add_environment(obj_under_transaction)
# if is a TinyFactory, add the factory to the simulation
elif isinstance(obj_under_transaction, TinyFactory):
simulation.add_factory(obj_under_transaction)
logger.debug(f">>>>>>>>>>>>>>>>>>>>>>> Added factory {obj_under_transaction} to simulation {simulation.id}.")
else:
raise ValueError(f"Object {obj_under_transaction} (type = {type(obj_under_transaction)}) is not a TinyPerson or TinyWorld instance, and cannot be captured by the simulation.")
def execute(self, begin_parallel=False, parallel_id=None):
output = None
# Transaction caching will only operate if there is a simulation and it is started
if self.simulation is None or self.simulation.status == Simulation.STATUS_STOPPED:
# Compute the function and return it, no caching, since the simulation is not started
output = self.function(*self.args, **self.kwargs)
elif self.simulation.status == Simulation.STATUS_STARTED:
# Compute the event hash
event_hash = self.simulation._function_call_hash(self.function_name, *self.args, **self.kwargs)
# Sequential and parallel transactions are handled in different ways
if begin_parallel:
self.simulation.begin_parallel_transactions()
# CACHED? Check if the event hash is in the cache
if self.simulation._is_transaction_event_cached(event_hash,
parallel=self.simulation.is_under_parallel_transactions()):
self.simulation.cache_hits += 1
# Restore the full state and return the cached output
logger.info(f"Skipping execution of {self.function_name} with args {self.args} and kwargs {self.kwargs} because it is already cached.")
# SEQUENTIAL
if not self.simulation.is_under_parallel_transactions():
self.simulation._skip_execution_with_cache()
state = self.simulation.cached_trace[self.simulation._execution_trace_position()][3] # state
self.simulation._decode_simulation_state(state)
# Output encoding/decoding is used to preserve references to TinyPerson and TinyWorld instances
# mainly. Scalar values (int, float, str, bool) and composite values (list, dict) are
# encoded/decoded as is.
encoded_output = self.simulation.cached_trace[self.simulation._execution_trace_position()][2] # output
output = self._decode_function_output(encoded_output)
# PARALLEL
else: # is under parallel transactions
# in parallel segments, state is not restored, only outputs
encoded_output = self.simulation._get_cached_parallel_value(event_hash, "encoded_output")
output = self._decode_function_output(encoded_output)
else: # not cached
if not begin_parallel:
# in case of beginning a parallel segment, we don't want to count it as a cache miss,
# since the segment itself will not be cached, but rather the events within it.
self.simulation.cache_misses += 1
if not self.simulation.is_under_transaction(id=parallel_id) and not begin_parallel:
# BEGIN SEQUENTIAL TRANSACTION ###############################################################
#
# if this is the beginning of a parallel segment, we don't need to begin a transaction, since
# we want to allow additional transactions within the parallel segment (i.e., one-level reentrancy).
if not begin_parallel:
self.simulation.begin_transaction(id=parallel_id)
# Compute the function and encode the relevant output and simulation state
output = self.function(*self.args, **self.kwargs)
self._save_output_with_simulation_state(event_hash, output)
# END TRANSACTION #################################################################
if not begin_parallel:
self.simulation.end_transaction(id=parallel_id)
else: # already under transaction (thus, now a reentrant transaction) OR beginning a parallel segment
# NOTES:
#
# - Reentrant sequential transactions are not cached, since what matters is the final result of
# the top-level transaction.
#
# - The event that starts the parallel transactions segment WILL NOT itself be cached, since
# it is not part of the parallel segment, but rather the beginning of it. This event will be
# reconstructed during runtime from the parallel events within the segment.
output = self.function(*self.args, **self.kwargs)
if begin_parallel:
self.simulation.end_parallel_transactions()
# execute an ad-hoc Transaction to save the simulation state AFTER the parallel segment is done.
Transaction(self.obj_under_transaction, self.simulation, lambda: True).execute(begin_parallel=False, parallel_id=parallel_id)
else:
raise ValueError(f"Simulation status is invalid at this point: {self.simulation.status}")
# Checkpoint if needed
logger.debug(f"Will attempt to checkpoint simulation state after transaction execution.")
if self.simulation is not None and self.simulation.auto_checkpoint:
logger.debug("Auto-checkpointing simulation state after transaction execution.")
self.simulation.checkpoint()
# after all the transaction is done, return the output - the client will never know about all the complexity we've
# gone through to get here.
return output
def _save_output_with_simulation_state(self, event_hash, output):
encoded_output = self._encode_function_output(output)
state = self.simulation._encode_simulation_state()
# immediately drop the cached trace suffix, since we are starting a new execution from this point on.
# in the case of parallel transactions, this will drop everything _after_ the current parallel segment
# (which itself occupies one position only, with a dictionary of event hashes and their outputs).
self.simulation._drop_cached_trace_suffix()
# Cache the result and update the current execution trace. If this is a parallel transaction, the
# cache and execution traces will be updated in a different way.
self.simulation._add_to_cache_trace(state, event_hash, encoded_output,
parallel=self.simulation.is_under_parallel_transactions())
self.simulation._add_to_execution_trace(state, event_hash, encoded_output,
parallel=self.simulation.is_under_parallel_transactions())
def _encode_function_output(self, output) -> dict:
"""
Encodes the given function output.
"""
# local import to avoid circular dependencies
from tinytroupe.agent import TinyPerson
from tinytroupe.environment import TinyWorld
from tinytroupe.factory.tiny_factory import TinyFactory
# if the output is a supported object, encode it
if output is None:
return None
elif isinstance(output, TinyPerson):
return {"type": "TinyPersonRef", "name": output.name}
elif isinstance(output, TinyWorld):
return {"type": "TinyWorldRef", "name": output.name}
elif isinstance(output, TinyFactory):
return {"type": "TinyFactoryRef", "name": output.name}
elif isinstance(output, list):
encoded_list = []
for item in output:
if isinstance(item, TinyPerson):
encoded_list.append({"type": "TinyPersonRef", "name": item.name})
elif isinstance(item, TinyWorld):
encoded_list.append({"type": "TinyWorldRef", "name": item.name})
elif isinstance(item, TinyFactory):
encoded_list.append({"type": "TinyFactoryRef", "name": item.name})
else:
encoded_list.append({"type": "JSON", "value": item})
return {"type": "List", "value": encoded_list}
elif isinstance(output, (int, float, str, bool, dict, tuple)):
return {"type": "JSON", "value": output}
else:
raise ValueError(f"Unsupported output type: {type(output)}")
def _decode_function_output(self, encoded_output: dict):
"""
Decodes the given encoded function output.
"""
# local import to avoid circular dependencies
from tinytroupe.agent import TinyPerson
from tinytroupe.environment import TinyWorld
from tinytroupe.factory.tiny_factory import TinyFactory
if encoded_output is None:
return None
elif encoded_output["type"] == "TinyPersonRef":
return TinyPerson.get_agent_by_name(encoded_output["name"])
elif encoded_output["type"] == "TinyWorldRef":
return TinyWorld.get_environment_by_name(encoded_output["name"])
elif encoded_output["type"] == "TinyFactoryRef":
return TinyFactory.get_factory_by_name(encoded_output["name"])
elif encoded_output["type"] == "List":
decoded_list = []
for item in encoded_output["value"]:
if item["type"] == "TinyPersonRef":
decoded_list.append(TinyPerson.get_agent_by_name(item["name"]))
elif item["type"] == "TinyWorldRef":
decoded_list.append(TinyWorld.get_environment_by_name(item["name"]))
elif item["type"] == "TinyFactoryRef":
decoded_list.append(TinyFactory.get_factory_by_name(item["name"]))
else:
decoded_list.append(item["value"])
return decoded_list
elif encoded_output["type"] == "JSON":
return encoded_output["value"]
else:
raise ValueError(f"Unsupported output type: {encoded_output['type']}")</code></pre>
</details>
<h3>Methods</h3>
<dl>
<dt id="tinytroupe.control.Transaction.execute"><code class="name flex">
<span>def <span class="ident">execute</span></span>(<span>self, begin_parallel=False, parallel_id=None)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def execute(self, begin_parallel=False, parallel_id=None):
output = None
# Transaction caching will only operate if there is a simulation and it is started
if self.simulation is None or self.simulation.status == Simulation.STATUS_STOPPED:
# Compute the function and return it, no caching, since the simulation is not started
output = self.function(*self.args, **self.kwargs)
elif self.simulation.status == Simulation.STATUS_STARTED:
# Compute the event hash
event_hash = self.simulation._function_call_hash(self.function_name, *self.args, **self.kwargs)
# Sequential and parallel transactions are handled in different ways
if begin_parallel:
self.simulation.begin_parallel_transactions()
# CACHED? Check if the event hash is in the cache
if self.simulation._is_transaction_event_cached(event_hash,
parallel=self.simulation.is_under_parallel_transactions()):
self.simulation.cache_hits += 1
# Restore the full state and return the cached output
logger.info(f"Skipping execution of {self.function_name} with args {self.args} and kwargs {self.kwargs} because it is already cached.")
# SEQUENTIAL
if not self.simulation.is_under_parallel_transactions():
self.simulation._skip_execution_with_cache()
state = self.simulation.cached_trace[self.simulation._execution_trace_position()][3] # state
self.simulation._decode_simulation_state(state)
# Output encoding/decoding is used to preserve references to TinyPerson and TinyWorld instances
# mainly. Scalar values (int, float, str, bool) and composite values (list, dict) are
# encoded/decoded as is.
encoded_output = self.simulation.cached_trace[self.simulation._execution_trace_position()][2] # output
output = self._decode_function_output(encoded_output)
# PARALLEL
else: # is under parallel transactions
# in parallel segments, state is not restored, only outputs
encoded_output = self.simulation._get_cached_parallel_value(event_hash, "encoded_output")
output = self._decode_function_output(encoded_output)
else: # not cached
if not begin_parallel:
# in case of beginning a parallel segment, we don't want to count it as a cache miss,
# since the segment itself will not be cached, but rather the events within it.
self.simulation.cache_misses += 1
if not self.simulation.is_under_transaction(id=parallel_id) and not begin_parallel:
# BEGIN SEQUENTIAL TRANSACTION ###############################################################
#
# if this is the beginning of a parallel segment, we don't need to begin a transaction, since
# we want to allow additional transactions within the parallel segment (i.e., one-level reentrancy).
if not begin_parallel:
self.simulation.begin_transaction(id=parallel_id)
# Compute the function and encode the relevant output and simulation state
output = self.function(*self.args, **self.kwargs)
self._save_output_with_simulation_state(event_hash, output)
# END TRANSACTION #################################################################
if not begin_parallel:
self.simulation.end_transaction(id=parallel_id)
else: # already under transaction (thus, now a reentrant transaction) OR beginning a parallel segment
# NOTES:
#
# - Reentrant sequential transactions are not cached, since what matters is the final result of
# the top-level transaction.
#
# - The event that starts the parallel transactions segment WILL NOT itself be cached, since
# it is not part of the parallel segment, but rather the beginning of it. This event will be
# reconstructed during runtime from the parallel events within the segment.
output = self.function(*self.args, **self.kwargs)
if begin_parallel:
self.simulation.end_parallel_transactions()
# execute an ad-hoc Transaction to save the simulation state AFTER the parallel segment is done.
Transaction(self.obj_under_transaction, self.simulation, lambda: True).execute(begin_parallel=False, parallel_id=parallel_id)
else:
raise ValueError(f"Simulation status is invalid at this point: {self.simulation.status}")
# Checkpoint if needed
logger.debug(f"Will attempt to checkpoint simulation state after transaction execution.")
if self.simulation is not None and self.simulation.auto_checkpoint:
logger.debug("Auto-checkpointing simulation state after transaction execution.")
self.simulation.checkpoint()
# after all the transaction is done, return the output - the client will never know about all the complexity we've
# gone through to get here.
return output</code></pre>
</details>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<h1>Index</h1>
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="tinytroupe" href="index.html">tinytroupe</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="two-column">
<li><code><a title="tinytroupe.control.begin" href="#tinytroupe.control.begin">begin</a></code></li>
<li><code><a title="tinytroupe.control.cache_hits" href="#tinytroupe.control.cache_hits">cache_hits</a></code></li>
<li><code><a title="tinytroupe.control.cache_misses" href="#tinytroupe.control.cache_misses">cache_misses</a></code></li>
<li><code><a title="tinytroupe.control.checkpoint" href="#tinytroupe.control.checkpoint">checkpoint</a></code></li>
<li><code><a title="tinytroupe.control.current_simulation" href="#tinytroupe.control.current_simulation">current_simulation</a></code></li>
<li><code><a title="tinytroupe.control.end" href="#tinytroupe.control.end">end</a></code></li>
<li><code><a title="tinytroupe.control.reset" href="#tinytroupe.control.reset">reset</a></code></li>
<li><code><a title="tinytroupe.control.transactional" href="#tinytroupe.control.transactional">transactional</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="tinytroupe.control.CacheOutOfSync" href="#tinytroupe.control.CacheOutOfSync">CacheOutOfSync</a></code></h4>
</li>
<li>
<h4><code><a title="tinytroupe.control.ExecutionCached" href="#tinytroupe.control.ExecutionCached">ExecutionCached</a></code></h4>
</li>
<li>
<h4><code><a title="tinytroupe.control.Simulation" href="#tinytroupe.control.Simulation">Simulation</a></code></h4>
<ul class="">
<li><code><a title="tinytroupe.control.Simulation.STATUS_STARTED" href="#tinytroupe.control.Simulation.STATUS_STARTED">STATUS_STARTED</a></code></li>
<li><code><a title="tinytroupe.control.Simulation.STATUS_STOPPED" href="#tinytroupe.control.Simulation.STATUS_STOPPED">STATUS_STOPPED</a></code></li>
<li><code><a title="tinytroupe.control.Simulation.add_agent" href="#tinytroupe.control.Simulation.add_agent">add_agent</a></code></li>
<li><code><a title="tinytroupe.control.Simulation.add_environment" href="#tinytroupe.control.Simulation.add_environment">add_environment</a></code></li>
<li><code><a title="tinytroupe.control.Simulation.add_factory" href="#tinytroupe.control.Simulation.add_factory">add_factory</a></code></li>
<li><code><a title="tinytroupe.control.Simulation.begin" href="#tinytroupe.control.Simulation.begin">begin</a></code></li>
<li><code><a title="tinytroupe.control.Simulation.begin_parallel_transactions" href="#tinytroupe.control.Simulation.begin_parallel_transactions">begin_parallel_transactions</a></code></li>
<li><code><a title="tinytroupe.control.Simulation.begin_transaction" href="#tinytroupe.control.Simulation.begin_transaction">begin_transaction</a></code></li>
<li><code><a title="tinytroupe.control.Simulation.checkpoint" href="#tinytroupe.control.Simulation.checkpoint">checkpoint</a></code></li>
<li><code><a title="tinytroupe.control.Simulation.end" href="#tinytroupe.control.Simulation.end">end</a></code></li>
<li><code><a title="tinytroupe.control.Simulation.end_parallel_transactions" href="#tinytroupe.control.Simulation.end_parallel_transactions">end_parallel_transactions</a></code></li>
<li><code><a title="tinytroupe.control.Simulation.end_transaction" href="#tinytroupe.control.Simulation.end_transaction">end_transaction</a></code></li>
<li><code><a title="tinytroupe.control.Simulation.is_under_parallel_transactions" href="#tinytroupe.control.Simulation.is_under_parallel_transactions">is_under_parallel_transactions</a></code></li>
<li><code><a title="tinytroupe.control.Simulation.is_under_transaction" href="#tinytroupe.control.Simulation.is_under_transaction">is_under_transaction</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="tinytroupe.control.SkipTransaction" href="#tinytroupe.control.SkipTransaction">SkipTransaction</a></code></h4>
</li>
<li>
<h4><code><a title="tinytroupe.control.Transaction" href="#tinytroupe.control.Transaction">Transaction</a></code></h4>
<ul class="">
<li><code><a title="tinytroupe.control.Transaction.execute" href="#tinytroupe.control.Transaction.execute">execute</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.10.0</a>.</p>
</footer>
</body>
</html> |