/usr/share/pyshared/Epigrass/simobj.py is in epigrass 2.0.4-3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | """
This Module contains the definitions of objects for spatial simulation on geo reference spaces.
"""
import sys, matplotlib
#matplotlib.use("Agg")
#from pylab import *
#import dgraph
from numpy import *
from numpy.random import uniform, binomial, poisson
from types import MethodType
from data_io import *
class siteobj:
"""
Basic site object containing attributes and methods common to all
site objects.
"""
def __init__(self, name, initpop,coords,geocode,values=()):
"""
Set initial values for site attributes.
-name: name of the locality
-coords: site coordinates.
-initpop: total population size.
-geocode: integer id code for site
-values: Tuple containing adicional values from the sites file
"""
self.id = self #reference to site instance
self.stochtransp = 1 #Flag for stochastic transportation
self.pos = coords
self.totpop = float(initpop)
self.ts = []
self.incidence = []
self.infected = False
self.infector = None
self.sitename = name
self.values = values
self.centrality = None
self.betweeness = None
self.thidx = None
self.degree = None
self.parentGraph = None
self.edges = []
self.neighbors = []
self.thetalist = []
self.thetahist = [] #infected arriving per time step
self.passlist = []
self.totalcases = 0
self.vaccination = [[],[]] #time and coverage of vaccination event
self.vaccineNow = 0 #flag to indicate that it is vaccination day
self.vaccov = 0 #current vaccination coverage
self.nVaccinated = 0
self.quarantine = [sys.maxint,0]
self.nQuarantined = 0
self.geocode = geocode
self.painted = 0 # Flag for the graph display
self.modtype = None
self.migInf = [] #infectious individuals able to migrate (time series)
self.inedges = [] #Inbound edges
self.outedges = [] #outbound edges
self.pdest=[]
self.infectedvisiting=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
def createModel(self,init,modtype='',name='model1',v=[],bi=None,bp=None):
"""
Creates a model of type modtype and defines its initial parameters.
init -- initial conditions for the state variables tuple with fractions of the total
population in each category (state variable).
par -- initial values for the parameters.
v -- List of extra variables passed in the sites files
bi, bp -- dictionaries containing all the inits and parms defined in the .epg model
"""
Init = init # deprecated
N = self.totpop
self.modtype = modtype
self.values = v
self.bi = bi
self.bp = bp
self.ts =[[0, 0, 0]]
self.model = popmodels(self.id,type=modtype,v=self.values,bi = self.bi, bp = self.bp)
def runModel(self):
"""
Iterate the model
"""
if self.parentGraph.simstep in self.vaccination[0]:
self.vaccineNow = 1
self.vaccov = float(self.vaccination[1][self.vaccination[0].index(self.parentGraph.simstep)])
if self.thetalist:
theta = sum([i[1] for i in self.thetalist])
self.infector = dict([i for i in self.thetalist if i[1] > 0]) #Only those that contribute at least one infected individual
else:
theta = 0
self.infector = {}
npass = sum(self.passlist)
self.thetahist.append(theta) #keep a record of infected passenger arriving
self.ts.append(self.model.step(self.ts[-1],theta,npass))
self.thetalist = [] # reset self.thetalist (for the new timestep)
## if self.parentGraph.gr: #updatn.box.length =es the visual graph display.
## i = self.parentGraph.site_list.index(self)
## if self.infected:
## self.parentGraph.gr.nodes[i].box.length = self.parentGraph.gr.nodes[i].box.width =self.parentGraph.gr.nodes[i].box.height = (self.ts[-1][1]/float(self.totpop)+0.4)**1/3.
## if not self.painted:
## self.parentGraph.lightGRNode(self,'r')
def vaccinate(self,cov):
"""
At time t the population will be vaccinated with coverage cov.
"""
self.nVaccinated = self.ts[-1][2]*cov
self.ts[-1][2] = self.ts[-1][2]*(1-cov)
def intervention(self,par,cov,efic):
"""
From time t on, parameter par is changed to
par * (1-cov*efic)
"""
self.bp[par] = self.bp[par]*(1-cov*efic)
def getTheta(self,npass, delay):
"""
Returns the number of infected individuals in this
site commuting through the edge that called
this function.
npass -- number of individuals leaving the node.
"""
if delay>=len(self.migInf):
delay = len(self.migInf)-1
lag = -1- delay
if not self.stochtransp:
theta = npass * self.migInf[lag]/float(self.totpop) # infectious migrants
else: #Stochastic migration
#print lag, self.migInf
#print npass
try:
theta = binomial(int(npass),self.migInf[lag]/float(self.totpop))
except ValueError: #if npass is less than one
theta = 0
# Check if site is quarantined
if self.parentGraph.simstep > self.quarantine[0]:
self.nQuarantined = npass*self.quarantine[1]
return theta*(1-self.quarantine[1]),npass*(1-self.quarantine[1])
else:
return theta,npass
def getThetaindex(self):
"""
Returns the Theta index.
Measures the function of a node, that is the average
amount of traffic per intersection. The higher theta is,
the greater the load of the network.
"""
if self.thidx:
return self.thidx
self.thidx = thidx = sum([(i.fmig+i.bmig)/2. for i in self.edges])/len(self.parentGraph.site_list)
return thidx
def receiveTheta(self,thetai, npass, site):
"""
Number of infectious individuals arriving from site i
"""
self.thetalist.append((site,thetai))
self.passlist.append(npass)
def plotItself(self):
"""
plot site timeseries
"""
a = transpose(array(self.ts))
#figure(int(self.totpop))
figure()
for i in xrange(3):
plot(transpose(a[i]))
title(self.sitename)
legend(('E','I','S'))
xlabel('time(days)')
savefig(str(self.geocode)+'.png')
close()
#show()
def isNode(self):
"""
find is given site is a node of a graph
"""
if self.parentGraph:
return 1
else:
return 0
def getOutEdges(self):
'''
return a list of outbound edges
'''
if self.outedges:
return self.outedges
oe = [e for e in self.edges if self==e.source]
self.outedges = oe
return oe
def getInEdges(self):
'''
return a list of outbound edges
'''
if self.inedges:
return self.inedges
ie = [e for e in self.edges if self==e.dest]
self.inedges = ie
return ie
def getNeighbors(self):
"""
Returns a dictionary of neighbooring sites as keys,
and distances as values.
"""
if not self.isNode():
return []
if self.neighbors:
return self.neighbors
neigh = {}
for i in self.edges:
n=[i.source,i.dest,i.length]
idx = n.index(self)
n.pop(idx)
neigh[n[0]] = n[-1]
self.neighbors = neigh
return neigh
def getDistanceFromNeighbor(self, neighbor):
"""
Returns the distance in Km from a given neighbor.
neighbor can be a siteobj object, or a geocode number
"""
if not self.neighbors:
self.neighbors = self.getNeighbors()
if type(neighbor) == type(1):
nei = [n for n in self.neighbors if int(n.geocode) == neighbor]
if nei:
d = [e.length for e in self.edges if nei in e.sites][0]
else:
sys.exit('%s is not a neighbor of %s!'%(nei[0].sitename, self.sitename))
else:
if neighbor in self.neighbors:
d = [e.length for e in self.edges if neighbor in e.sites][0]
#if d == 0:
#print 'problem determining distance from neighboor'
else:
sys.exit('%s is not a neighbor of %s!'%(neighbor.sitename, self.sitename))
return d
def getDegree(self):
"""
Returns the degrees of this site if it is part of a graph.
The order (degree) of a node is the number of nodes attached to it
and is a simple, but effective measure of nodal importance.
The higher its value, the more a node is important in a graph
as many links converge to it. Hub nodes have a high order,
while terminal points have an order that can be as low as 1.
A perfect hub would have its order equal to the summation of
all the orders of the other nodes in the graph and a perfect
spoke would have an order of 1.
Returns an integer.
"""
if not self.isNode():
return 0
else:
return len(self.getNeighbors())
def doStats(self):
"""
Calculate indices describing the node and return them in a list.
"""
self.centrality = self.getCentrality()
self.degree = self.getDegree()
self.thidx = self.getThetaindex()
self.betweeness = self.getBetweeness()
return [self.centrality,self.degree,self.thidx, self.betweeness]
def getCentrality(self):
"""
Also known as closeness. A measure of global centrality, is the
inverse of the sum of the shortest paths to all other nodes
in the graph.
"""
#get position in the distance matrix.
if self.centrality:
return self.centrality
pos = self.parentGraph.site_list.index(self)
if not self.parentGraph.allPairs.any():
self.parentGraph.getAllPairs()
c = 1./sum(self.parentGraph.allPairs[pos])
return c
def getBetweeness(self):
"""
Is the number of times any node figures in the the shortest path
between any other pair of nodes.
"""
if self.betweeness:
return self.betweeness
B = 0
for i in self.parentGraph.shortPathList:
if not self in i:
if self in i[2]:
B +=1
return B
class popmodels:
"""
Defines a library of discrete time population models
"""
def __init__(self,parentsite,type='',v=[],bi=None,bp=None):
"""
defines which models a given site will use
and set variable names accordingly.
"""
self.type = type
self.values = v
self.bi = bi # dictionary of inits
self.bp = bp # dictionary of parms
self.parentSite = parentsite
self.parentSite.vnames = ('E','I','S')
self.selectModel(self.type)#sets self.step
#print self.step
def selectModel(self,type):
"""
sets the model engine
"""
if type=='SIR':
self.step=self.stepSIR
elif type == 'SIR_s':
self.step=self.stepSIR_s
elif type == 'SIS':
self.step=self.stepSIS
elif type == 'SIS_s':
self.step=self.stepSIS_s
elif type == 'SEIS':
self.step=self.stepSEIS
elif type == 'SEIS_s':
self.step=self.stepSEIS_s
elif type=='SEIR':
self.step=self.stepSEIR
elif type == 'SEIR_s':
self.step = self.stepSEIR_s
elif type == 'SIpRpS':
self.step=self.stepSIpRpS
elif type == 'SIpRpS_s':
self.step=self.stepSIpRpS_s
elif type == 'SEIpRpS':
self.step=self.stepSEIpRpS
elif type == 'SEIpRpS_s':
self.step=self.stepSEIpRpS_s
elif type == 'SIpR':
self.parentSite.incidence2 = []
self.step=self.stepSIpR
elif type == 'SIpR_s':
self.parentSite.incidence2 = []
self.step=self.stepSIpR_s
elif type == 'SEIpR':
self.parentSite.incidence2 = []
self.step=self.stepSEIpR
elif type == 'SEIpR_s':
self.parentSite.incidence2 = []
self.step=self.stepSEIpR_s
elif type == 'SIRS':
self.step=self.stepSIRS
elif type == 'SIRS_s':
self.step=self.stepSIRS_s
elif type == 'Influenza':
self.step = self.stepFlu
elif type == 'multiple':
self.step = self.multipleStep
elif type == 'Custom':
#adds the user model as a method of instance self
try:
#TODO: move this import to the graph level
import CustomModel
self.step = MethodType(CustomModel.Model,self)
except ImportError:
print "You have to Create a CustomModel.py file before you can select\nthe Custom model type"
else:
sys.exit('Model type specified in .epg file is invalid')
def multipleStep(self,inits,par,theta=0, npass=0, modelos=[]):
"""
Run multiple models on a single site
- Inits and par are a list of lists.
- modelos is a list of of the modeltypes.
"""
if not modelos:
raise Error, 'You have to define a list of model types when using "multiple"'
if not isinstance(inits[0],list):
raise Error, 'Model type is "multiple" but inits is not a tuple'
if not isinstance(par[0],list):
raise Error, 'Model type is "multiple" but par is not a tuple'
results=[]
for i,m in enumerate(modelos):
results.append(selectModel(m)(inits[i],par[i],theta,npass))
return results
def stepFlu(self,vars,N, theta=0,npass=0):
"""
Flu model with classes S,E,I subclinical, I mild, I medium, I serious, deaths
"""
#Variable long names to be used in the database output.
self.parentSite.vnames = ('Susc_age1','Incub_age1','Subc_age1','Sympt_age1','Comp_age1',
'Susc_age2','Incub_age2','Subc_age2','Sympt_age2','Comp_age2',
'Susc_age3','Incub_age3','Subc_age3','Sympt_age3','Comp_age3',
'Susc_age4','Incub_age4','Subc_age4','Sympt_age4','Comp_age4',)
if self.parentSite.parentGraph.simstep == 1: #get initial values
S1,E1,Is1,Ic1,Ig1 = (self.bi['s1'],self.bi['e1'],self.bi['is1'],self.bi['ic1'],self.bi['ig1'])
S2,E2,Is2,Ic2,Ig2 = (self.bi['s2'],self.bi['e2'],self.bi['is2'],self.bi['ic2'],self.bi['ig2'])
S3,E3,Is3,Ic3,Ig3 = (self.bi['s3'],self.bi['e3'],self.bi['is3'],self.bi['ic3'],self.bi['ig3'])
S4,E4,Is4,Ic4,Ig4 = (self.bi['s4'],self.bi['e4'],self.bi['is4'],self.bi['ic4'],self.bi['ig4'])
else: #get values from last time step
S1,E1,Is1,Ic1,Ig1,S2,E2,Is2,Ic2,Ig2,S3,E3,Is3,Ic3,Ig3,S4,E4,Is4,Ic4,Ig4 = vars
N = self.parentSite.totpop
for k, v in self.bp.items():
exec('%s = %s'%(k, v))
#parameters: alpha,beta,r,e,c,g,d,pc1,pc2,pc3,pc4,pp1,pp2,pp3,pp4,b
#Vacination event
if self.parentSite.vaccineNow:
S1 -= self.parentSite.vaccov*S1
S2 -= self.parentSite.vaccov*S2
S3 -= self.parentSite.vaccov*S3
S4 -= self.parentSite.vaccov*S4
#New cases by age class
#beta=eval(self.values[2])
Infectantes = Ig1+Ig2+Ig3+Ig4+Ic1+Ic2+Ic3+Ic4+0.5*(Is1+Is2+Is3+Is4)+theta
L1pos = float(beta)*S1*(Infectantes/(N+npass))**alpha
L2pos = float(beta)*S2*(Infectantes/(N+npass))**alpha
L3pos = float(beta)*S3*(Infectantes/(N+npass))**alpha
L4pos = float(beta)*S4*(Infectantes/(N+npass))**alpha
######################
Lpos = L1pos+L2pos+L3pos+L4pos
self.parentSite.totalcases+=Lpos
# Model
# 0-2 anos
E1pos = L1pos + (1-e)*E1
Is1pos = (1-(pc1*c+(1-pc1)*r))*Is1 + e*E1
Ic1pos = (1-(pp1*g+(1-pp1)*r))*Ic1 + pc1*c*Is1
Ig1pos = (1-d)*Ig1 + pp1*g*Ic1
S1pos = b+S1 - L1pos
# 3-14 anos
E2pos = L2pos + (1-e)*E2
Is2pos = (1-(pc2*c+(1-pc2)*r))*Is2 + e*E2
Ic2pos = (1-(pp2*g+(1-pp2)*r))*Ic2 + pc2*c*Is2
Ig2pos = (1-d)*Ig2 + pp2*g*Ic2
S2pos = b+S2 - L2pos
# 15-59 anos
E3pos = L3pos + (1-e)*E3
Is3pos = (1-(pc3*c+(1-pc3)*r))*Is3 + e*E3
Ic3pos = (1-(pp3*g+(1-pp3)*r))*Ic3 + pc3*c*Is3
Ig3pos = (1-d)*Ig3 + pp3*g*Ic3
S3pos = b+S3 - L3pos
# >60 anos
E4pos = L4pos + (1-e)*E4
Is4pos = (1-(pc4*c+(1-pc4)*r))*Is4 + e*E4
Ic4pos = (1-(pp4*g+(1-pp4)*r))*Ic4 + pc4*c*Is4
Ig4pos = (1-d)*Ig4 + pp4*g*Ic4
S4pos = b+S4 - L4pos
# Updating stats
self.parentSite.incidence.append(Lpos)
# Raises site infected flag and adds parent site to the epidemic history list.
if not self.parentSite.infected:
if Lpos > 0:
#if not self.parentSite.infected:
self.parentSite.infected = self.parentSite.parentGraph.simstep
self.parentSite.parentGraph.epipath.append((self.parentSite.parentGraph.simstep,self.parentSite,self.parentSite.infector))
#Migrating infecctious
self.parentSite.migInf.append(Ig1pos+Ig2pos+Ig3pos+Ig4pos+Ic1pos+Ic2pos+Ic3pos+Ic4pos+0.5*(Is1pos+Is2pos+Is3pos+Is4pos))
# Return variable values
return [S1pos,E1pos,Is1pos,Ic1pos,Ig1pos,S2pos,E2pos,Is2pos,
Ic2pos,Ig2pos,S3pos,E3pos,Is3pos,Ic3pos,Ig3pos,S4pos,
E4pos,Is4pos,Ic4pos,Ig4pos]
def stepSIS(self,inits,theta=0, npass=0):
"""
calculates the model SIS, and return its values (no demographics)
- inits = (E,I,S)
- theta = infectious individuals from neighbor sites
"""
if self.parentSite.parentGraph.simstep == 1: #get initial values
E,I,S = (self.bi['e'],self.bi['i'],self.bi['s'])
else:
E,I,S = inits
N = self.parentSite.totpop
for k, v in self.bp.items():
exec('%s = %s'%(k, v))
#parameter: beta,alpha,e,r,delta,b,w,p
Lpos = float(beta)*S*((I+theta)/(N+npass))**alpha #Number of new cases
self.parentSite.totalcases += Lpos #update number of cases
# Model
Ipos = (1-r)*I + Lpos
Spos = S + b - Lpos + r*I
# Updating stats
self.parentSite.incidence.append(Lpos)
# Raises site infected flag and adds parent site to the epidemic history list.
if not self.parentSite.infected:
if Lpos > 0:
#if not self.parentSite.infected:
self.parentSite.infected = self.parentSite.parentGraph.simstep
self.parentSite.parentGraph.epipath.append((self.parentSite.parentGraph.simstep,self.parentSite,self.parentSite.infector))
#Migrating infecctious
self.parentSite.migInf.append(Ipos)
return [0,Ipos,Spos]
def stepSIS_s(self,inits=(0,0,0),theta=0, npass=0,dist='poisson'):
"""
Defines an stochastic model SIS:
- inits = (E,I,S)
- theta = infectious individuals from neighbor sites
"""
if self.parentSite.parentGraph.simstep == 1: #get initial values
E,I,S = (self.bi['e'],self.bi['i'],self.bi['s'])
else:
E,I,S = inits
N = self.parentSite.totpop
for k, v in self.bp.items():
exec('%s = %s'%(k, v))
# parameter: beta,alpha,e,r,delta,b,w,p
Lpos_esp = float(beta)*S*((I+theta)/(N+npass))**alpha #Number of new cases
if dist == 'poisson':
Lpos = poisson(Lpos_esp)
elif dist == 'negbin':
prob = I/(I+Lpos_esp) #convertin between parameterizations
Lpos = negative_binomial(I,prob)
self.parentSite.totalcases += Lpos #update number of cases
# Model
Ipos = (1-r)*I + Lpos
Spos = S + b - Lpos + r*I
# Updating stats
self.parentSite.incidence.append(Lpos)
if not self.parentSite.infected:
if Lpos > 0:
self.parentSite.infected = self.parentSite.parentGraph.simstep
self.parentSite.parentGraph.epipath.append((self.parentSite.parentGraph.simstep,self.parentSite,self.parentSite.infector))
#Migrating infecctious
self.parentSite.migInf.append(Ipos)
return [0,Ipos,Spos]
def stepSIR(self,inits,theta=0, npass=0):
"""
calculates the model SIR, and return its values (no demographics)
- inits = (E,I,S)
- theta = infectious individuals from neighbor sites
"""
if self.parentSite.parentGraph.simstep == 1: #get initial values
E,I,S = (self.bi['e'],self.bi['i'],self.bi['s'])
else:
E,I,S = inits
N = self.parentSite.totpop
for k, v in self.bp.items():
exec('%s = %s'%(k, v))
# parameter: beta,alpha,e,r,delta,b,w,p
Lpos = float(beta)*S*((I+theta)/(N+npass))**alpha #Number of new cases
self.parentSite.totalcases += Lpos #update number of cases
# Model
Ipos = (1-r)*I + Lpos
Spos = S + b - Lpos
Rpos = N-(Spos+Ipos)
# Updating stats
self.parentSite.incidence.append(Lpos)
# Raises site infected flag and adds parent site to the epidemic history list.
if not self.parentSite.infected:
if Lpos > 0:
#if not self.parentSite.infected:
self.parentSite.infected = self.parentSite.parentGraph.simstep
self.parentSite.parentGraph.epipath.append((self.parentSite.parentGraph.simstep,self.parentSite,self.parentSite.infector))
#Migrating infecctious
self.parentSite.migInf.append(Ipos)
return [0,Ipos,Spos]
def stepSIR_s(self,inits=(0,0,0),theta=0, npass=0,dist='poisson'):
"""
Defines an stochastic model SIR:
- inits = (E,I,S)
- theta = infectious individuals from neighbor sites
"""
if self.parentSite.parentGraph.simstep == 1: #get initial values
E,I,S = (self.bi['e'],self.bi['i'],self.bi['s'])
else:
E,I,S = inits
N = self.parentSite.totpop
for k, v in self.bp.items():
exec('%s = %s'%(k, v))
#parameter: beta,alpha,e,r,delta,b,w,p
Lpos_esp = float(beta)*S*((I+theta)/(N+npass))**alpha #Number of new cases
if dist == 'poisson':
Lpos = poisson(Lpos_esp)
elif dist == 'negbin':
prob = I/(I+Lpos_esp) #convertin between parameterizations
Lpos = negative_binomial(I,prob)
self.parentSite.totalcases += Lpos #update number of cases
# Model
Ipos = (1-r)*I + Lpos
Spos = S + b - Lpos
Rpos = N-(Spos+Ipos)
# Updating stats
self.parentSite.incidence.append(Lpos)
if not self.parentSite.infected:
if Lpos > 0:
self.parentSite.infected = self.parentSite.parentGraph.simstep
self.parentSite.parentGraph.epipath.append((self.parentSite.parentGraph.simstep,self.parentSite,self.parentSite.infector))
#Migrating infecctious
self.parentSite.migInf.append(Ipos)
return [0,Ipos,Spos]
def stepSEIS(self,inits=(0,0,0),theta=0, npass=0):
"""
Defines the model SEIS:
- inits = (E,I,S)
- theta = infectious individuals from neighbor sites
"""
if self.parentSite.parentGraph.simstep == 1: #get initial values
E,I,S = (self.bi['e'],self.bi['i'],self.bi['s'])
else:
E,I,S = inits
N = self.parentSite.totpop
for k, v in self.bp.items():
exec('%s = %s'%(k, v))
#parameters: beta,alpha,e,r,delta,b,w,p
Lpos = float(beta)*S*((I+theta)/(N+npass))**alpha #Number of new cases
self.parentSite.totalcases += Lpos #update number of cases
#print N,E,I,S,Lpos,theta
Epos = (1-e)*E + Lpos
Ipos = e*E + (1-r)*I
Spos = S + b - Lpos + r*I
self.parentSite.incidence.append(Lpos)
if not self.parentSite.infected:
if Lpos > 0:
self.parentSite.infected = self.parentSite.parentGraph.simstep
self.parentSite.parentGraph.epipath.append((self.parentSite.parentGraph.simstep,self.parentSite,self.parentSite.infector))
#Migrating infecctious
self.parentSite.migInf.append(Ipos)
return [Epos,Ipos,Spos]
def stepSEIS_s(self,inits=(0,0,0),theta=0, npass=0,dist='poisson'):
"""
Defines an stochastic model SEIS:
- inits = (E,I,S)
- par = (Beta, alpha, E,r,delta,B,w,p) see docs.
- theta = infectious individuals from neighbor sites
"""
if self.parentSite.parentGraph.simstep == 1: #get initial values
E,I,S = (self.bi['e'],self.bi['i'],self.bi['s'])
else:
E,I,S = inits
N = self.parentSite.totpop
for k, v in self.bp.items():
exec('%s = %s'%(k, v))
#parameters: beta,alpha,e,r,delta,b,w,p
Lpos_esp = float(beta)*S*((I+theta)/(N+npass))**alpha #Number of new cases
if dist == 'poisson':
Lpos = poisson(Lpos_esp)
elif dist == 'negbin':
prob = I/(I+Lpos_esp) #converting between parameterizations
Lpos = negative_binomial(I,prob)
self.parentSite.totalcases += Lpos #update number of cases
Epos = (1-e)*E + Lpos
Ipos = e*E + (1-r)*I
Spos = S + b - Lpos + r*I
self.parentSite.incidence.append(Lpos)
if not self.parentSite.infected:
if Lpos > 0:
self.parentSite.infected = self.parentSite.parentGraph.simstep
self.parentSite.parentGraph.epipath.append((self.parentSite.parentGraph.simstep,self.parentSite,self.parentSite.infector))
#Migrating infecctious
self.parentSite.migInf.append(Ipos)
return [Epos,Ipos,Spos]
def stepSEIR(self,inits=(0,0,0),theta=0, npass=0):
"""
Defines the model SEIR:
- inits = (E,I,S)
- par = (Beta, alpha, E,r,delta,B,w,p) see docs.
- theta = infectious individuals from neighbor sites
"""
if self.parentSite.parentGraph.simstep == 1: #get initial values
E,I,S = (self.bi['e'],self.bi['i'],self.bi['s'])
else:
E,I,S = inits
N = self.parentSite.totpop
for k, v in self.bp.items():
exec('%s = %s'%(k, v))
#parameters: beta,alpha,e,r,delta,B,w,p
Lpos = float(beta)*S*((I+theta)/(N+npass))**alpha #Number of new cases
self.parentSite.totalcases += Lpos #update number of cases
#print N,E,I,S,Lpos,theta
Epos = (1-e)*E + Lpos
Ipos = e*E + (1-r)*I
Spos = S + b - Lpos
Rpos = N-(Spos+Epos+Ipos)
#self.parentSite.totpop = Spos+Epos+Ipos+Rpos
self.parentSite.incidence.append(Lpos)
if not self.parentSite.infected:
if Lpos > 0:
self.parentSite.infected = self.parentSite.parentGraph.simstep
self.parentSite.parentGraph.epipath.append((self.parentSite.parentGraph.simstep,self.parentSite,self.parentSite.infector))
#Migrating infecctious
self.parentSite.migInf.append(Ipos)
return [Epos,Ipos,Spos]
def stepSEIR_s(self,inits=(0,0,0),theta=0, npass=0,dist='poisson'):
"""
Defines an stochastic model SEIR:
- inits = (E,I,S)
- par = (Beta, alpha, E,r,delta,B,w,p) see docs.
- theta = infectious individuals from neighbor sites
"""
if self.parentSite.parentGraph.simstep == 1: #get initial values
E,I,S = (self.bi['e'],self.bi['i'],self.bi['s'])
else:
E,I,S = inits
N = self.parentSite.totpop
for k, v in self.bp.items():
exec('%s = %s'%(k, v))
#parameters: beta,alpha,e,r,delta,B,w,p
Lpos_esp = float(beta)*S*((I+theta)/(N+npass))**alpha #Number of new cases
if dist == 'poisson':
Lpos = poisson(Lpos_esp) #poisson(Lpos_esp)
## if theta == 0 and Lpos_esp == 0 and Lpos > 0:
## print Lpos,Lpos_esp,S,I,theta,N,self.parentSite.sitename
elif dist == 'negbin':
prob = I/(I+Lpos_esp) #convertin between parameterizations
Lpos = negative_binomial(I,prob)
self.parentSite.totalcases += Lpos #update number of cases
Epos = (1-e)*E + Lpos
Ipos = e*E + (1-r)*I
Spos = S + b - Lpos
Rpos = N-(Spos+Epos+Ipos)
#self.parentSite.totpop = Spos+Epos+Ipos+Rpos
self.parentSite.incidence.append(Lpos)
if not self.parentSite.infected:
if Lpos > 0:
self.parentSite.infected = self.parentSite.parentGraph.simstep
self.parentSite.parentGraph.epipath.append((self.parentSite.parentGraph.simstep,self.parentSite,self.parentSite.infector))
#Migrating infecctious
self.parentSite.migInf.append(Ipos)
return [Epos,Ipos,Spos]
def stepSIpRpS(self,inits,theta=0, npass=0):
"""
calculates the model SIpRpS, and return its values (no demographics)
- inits = (E,I,S)
- theta = infectious individuals from neighbor sites
"""
if self.parentSite.parentGraph.simstep == 1: #get initial values
E,I,S = (self.bi['e'],self.bi['i'],self.bi['s'])
else:
E,I,S = inits
N = self.parentSite.totpop
for k, v in self.bp.items():
exec('%s = %s'%(k, v))
# parameter: beta,alpha,e,r,delta,b,w,p
Lpos = float(beta)*S*((I+theta)/(N+npass))**alpha #Number of new cases
self.parentSite.totalcases += Lpos #update number of cases
# Model
Ipos = (1-r)*I + Lpos
Spos = S + b - Lpos + (1-delta)*r*I
Rpos = N-(Spos+Ipos) + delta*r*I
# Updating stats
self.parentSite.incidence.append(Lpos)
# Raises site infected flag and adds parent site to the epidemic history list.
if not self.parentSite.infected:
if Lpos > 0:
#if not self.parentSite.infected:
self.parentSite.infected = self.parentSite.parentGraph.simstep
self.parentSite.parentGraph.epipath.append((self.parentSite.parentGraph.simstep,self.parentSite,self.parentSite.infector))
#Migrating infecctious
self.parentSite.migInf.append(Ipos)
return [0,Ipos,Spos]
def stepSIpRpS_s(self,inits=(0,0,0),theta=0, npass=0,dist='poisson'):
"""
Defines an stochastic model SIpRpS:
- inits = (E,I,S)
- theta = infectious individuals from neighbor sites
"""
if self.parentSite.parentGraph.simstep == 1: #get initial values
E,I,S = (self.bi['e'],self.bi['i'],self.bi['s'])
else:
E,I,S = inits
N = self.parentSite.totpop
for k, v in self.bp.items():
exec('%s = %s'%(k, v))
# parameter: beta,alpha,e,r,delta,B,w,p
Lpos_esp = float(beta)*S*((I+theta)/(N+npass))**alpha #Number of new cases
if dist == 'poisson':
Lpos = poisson(Lpos_esp)
elif dist == 'negbin':
prob = I/(I+Lpos_esp) #convertin between parameterizations
Lpos = negative_binomial(I,prob)
self.parentSite.totalcases += Lpos #update number of cases
# Model
Ipos = (1-r)*I + Lpos
Spos = S + b - Lpos + (1-delta)*r*I
Rpos = N-(Spos+Ipos) + delta*r*I
# Updating stats
self.parentSite.incidence.append(Lpos)
if not self.parentSite.infected:
if Lpos > 0:
self.parentSite.infected = self.parentSite.parentGraph.simstep
self.parentSite.parentGraph.epipath.append((self.parentSite.parentGraph.simstep,self.parentSite,self.parentSite.infector))
#Migrating infecctious
self.parentSite.migInf.append(Ipos)
return [0,Ipos,Spos]
def stepSEIpRpS(self,inits=(0,0,0),theta=0, npass=0):
"""
Defines the model SEIpRpS:
- inits = (E,I,S)
- theta = infectious individuals from neighbor sites
"""
if self.parentSite.parentGraph.simstep == 1: #get initial values
E,I,S = (self.bi['e'],self.bi['i'],self.bi['s'])
else:
E,I,S = inits
N = self.parentSite.totpop
for k, v in self.bp.items():
exec('%s = %s'%(k, v))
# parameter: beta,alpha,e,r,delta,b,w,p
Lpos = float(beta)*S*((I+theta)/(N+npass))**alpha #Number of new cases
self.parentSite.totalcases += Lpos #update number of cases
#print N,E,I,S,Lpos,theta
Epos = (1-e)*E + Lpos
Ipos = e*E + (1-r)*I
Spos = S + b - Lpos + (1-delta)*r*I
Rpos = N-(Spos+Epos+Ipos) + delta*r*I
#self.parentSite.totpop = Spos+Epos+Ipos+Rpos
self.parentSite.incidence.append(Lpos)
if not self.parentSite.infected:
if Lpos > 0:
self.parentSite.infected = self.parentSite.parentGraph.simstep
self.parentSite.parentGraph.epipath.append((self.parentSite.parentGraph.simstep,self.parentSite,self.parentSite.infector))
#Migrating infecctious
self.parentSite.migInf.append(Ipos)
return [Epos,Ipos,Spos]
def stepSEIpRpS_s(self,inits=(0,0,0),theta=0, npass=0,dist='poisson'):
"""
Defines an stochastic model SEIpRpS:
- inits = (E,I,S)
- theta = infectious individuals from neighbor sites
"""
if self.parentSite.parentGraph.simstep == 1: #get initial values
E,I,S = (self.bi['e'],self.bi['i'],self.bi['s'])
else:
E,I,S = inits
N = self.parentSite.totpop
for k, v in self.bp.items():
exec('%s = %s'%(k, v))
# parameter: beta,alpha,e,r,delta,b,w,p
Lpos_esp = float(beta)*S*((I+theta)/(N+npass))**alpha #Number of new cases
if dist == 'poisson':
Lpos = poisson(Lpos_esp)
elif dist == 'negbin':
prob = I/(I+Lpos_esp) #convertin between parameterizations
Lpos = negative_binomial(I,prob)
self.parentSite.totalcases += Lpos #update number of cases
Epos = (1-e)*E + Lpos
Ipos = e*E + (1-r)*I
Spos = S + b - Lpos + (1-delta)*r*I
Rpos = N-(Spos+Epos+Ipos) + delta*r*I
#self.parentSite.totpop = Spos+Epos+Ipos+Rpos
self.parentSite.incidence.append(Lpos)
if not self.parentSite.infected:
if Lpos > 0:
self.parentSite.infected = self.parentSite.parentGraph.simstep
self.parentSite.parentGraph.epipath.append((self.parentSite.parentGraph.simstep,self.parentSite,self.parentSite.infector))
#Migrating infecctious
self.parentSite.migInf.append(Ipos)
return [Epos,Ipos,Spos]
def stepSIpR(self,inits,theta=0, npass=0):
"""
calculates the model SIpR, and return its values (no demographics)
- inits = (E,I,S)
- theta = infectious individuals from neighbor sites
"""
if self.parentSite.parentGraph.simstep == 1: #get initial values
E,I,S = (self.bi['e'],self.bi['i'],self.bi['s'])
else:
E,I,S = inits
N = self.parentSite.totpop
R = N-E-I-S
for k, v in self.bp.items():
exec('%s = %s'%(k, v))
#parameter: beta,alpha,e,r,delta,b,w,p
Lpos = float(beta)*S*((I+theta)/(N+npass))**alpha #Number of new cases
Lpos2 = p*float(beta)*R*((I+theta)/(N+npass))**alpha
self.parentSite.totalcases += Lpos+Lpos2 #update number of cases
# Model
Ipos = (1-r)*I + Lpos + Lpos2
Spos = S + b - Lpos
Rpos = N-(Spos+Ipos) - Lpos2
# Updating stats
self.parentSite.incidence.append(Lpos+Lpos2) #total cases
self.parentSite.incidence2.append(Lpos2) # secondary infections
# Raises site infected flag and adds parent site to the epidemic history list.
if not self.parentSite.infected:
if Lpos > 0:
#if not self.parentSite.infected:
self.parentSite.infected = self.parentSite.parentGraph.simstep
self.parentSite.parentGraph.epipath.append((self.parentSite.parentGraph.simstep,self.parentSite,self.parentSite.infector))
#Migrating infecctious
self.parentSite.migInf.append(Ipos)
return [0,Ipos,Spos]
def stepSIpR_s(self,inits=(0,0,0),theta=0, npass=0,dist='poisson'):
"""
Defines an stochastic model SIpRs:
- inits = (E,I,S)
- theta = infectious individuals from neighbor sites
"""
if self.parentSite.parentGraph.simstep == 1: #get initial values
E,I,S = (self.bi['e'],self.bi['i'],self.bi['s'])
else:
E,I,S = inits
N = self.parentSite.totpop
for k, v in self.bp.items():
exec('%s = %s'%(k, v))
#parameter: beta,alpha,e,r,delta,b,w,p
R = N-E-I-S
Lpos_esp = float(beta)*S*((I+theta)/(N+npass))**alpha #Number of new cases
Lpos2_esp = p*float(beta)*R*((I+theta)/(N+npass))**alpha
if dist == 'poisson':
Lpos = poisson(Lpos_esp)
Lpos2 = poisson(Lpos2_esp)
elif dist == 'negbin':
prob = I/(I+Lpos_esp) #convertin between parameterizations
Lpos = negative_binomial(I,prob)
prob = I/(I+Lpos2_esp) #convertin between parameterizations
Lpos2 = negative_binomial(I,prob)
self.parentSite.totalcases += Lpos+Lpos2 #update number of cases
# Model
Ipos = (1-r)*I + Lpos + Lpos2
Spos = S + b - Lpos
Rpos = N-(Spos+Ipos) - Lpos2
# Updating stats
self.parentSite.incidence.append(Lpos+Lpos2) #total cases
self.parentSite.incidence2.append(Lpos2) # secondary infections
# Raises site infected flag and adds parent site to the epidemic history list.
if not self.parentSite.infected:
if Lpos > 0:
self.parentSite.infected = self.parentSite.parentGraph.simstep
self.parentSite.parentGraph.epipath.append((self.parentSite.parentGraph.simstep,self.parentSite,self.parentSite.infector))
#Migrating infecctious
self.parentSite.migInf.append(Ipos)
return [0,Ipos,Spos]
def stepSEIpR(self,inits,theta=0, npass=0):
"""
calculates the model SEIpR, and return its values (no demographics)
- inits = (E,I,S)
- theta = infectious individuals from neighbor sites
"""
if self.parentSite.parentGraph.simstep == 1: #get initial values
E,I,S = (self.bi['e'],self.bi['i'],self.bi['s'])
else:
E,I,S = inits
N = self.parentSite.totpop
R = N-E-I-S
for k, v in self.bp.items():
exec('%s = %s'%(k, v))
# parameters: beta,alpha,e,r,delta,b,w,p
Lpos = float(beta)*S*((I+theta)/(N+npass))**alpha #Number of new cases
Lpos2 = p*float(beta)*R*((I+theta)/(N+npass))**alpha
self.parentSite.totalcases += Lpos+Lpos2 #update number of cases
# Model
Epos = (1-e)*E + Lpos + Lpos2
Ipos = e*E+ (1-r)*I
Spos = S + b - Lpos
Rpos = N-(Spos+Ipos) - Lpos2
# Updating stats
self.parentSite.incidence.append(Lpos+Lpos2) #total cases
self.parentSite.incidence2.append(Lpos2) # secondary infections
# Raises site infected flag and adds parent site to the epidemic history list.
if not self.parentSite.infected:
if Lpos > 0:
#if not self.parentSite.infected:
self.parentSite.infected = self.parentSite.parentGraph.simstep
self.parentSite.parentGraph.epipath.append((self.parentSite.parentGraph.simstep,self.parentSite,self.parentSite.infector))
#Migrating infecctious
self.parentSite.migInf.append(Ipos)
return [0,Ipos,Spos]
def stepSEIpR_s(self,inits=(0,0,0),theta=0, npass=0,dist='poisson'):
"""
Defines an stochastic model SEIpRs:
- inits = (E,I,S)
- theta = infectious individuals from neighbor sites
"""
if self.parentSite.parentGraph.simstep == 1: #get initial values
E,I,S = (self.bi['e'],self.bi['i'],self.bi['s'])
else:
E,I,S = inits
N = self.parentSite.totpop
for k, v in self.bp.items():
exec('%s = %s'%(k, v))
# parameter: beta,alpha,e,r,delta,B,w,p
R = N-E-I-S
Lpos_esp = float(beta)*S*((I+theta)/(N+npass))**alpha #Number of new cases
Lpos2_esp = p*float(beta)*R*((I+theta)/(N+npass))**alpha
if dist == 'poisson':
Lpos = poisson(Lpos_esp)
Lpos2 = poisson(Lpos2_esp)
elif dist == 'negbin':
prob = I/(I+Lpos_esp) #convertin between parameterizations
Lpos = negative_binomial(I,prob)
prob = I/(I+Lpos2_esp) #convertin between parameterizations
Lpos2 = negative_binomial(I,prob)
self.parentSite.totalcases += Lpos+Lpos2 #update number of cases
# Model
Epos = (1-e)*E + Lpos + Lpos2
Ipos = e*E+ (1-r)*I
Spos = S + b - Lpos
Rpos = N-(Spos+Ipos) - Lpos2
# Updating stats
self.parentSite.incidence.append(Lpos+Lpos2) #total cases
self.parentSite.incidence2.append(Lpos2) # secondary infections
# Raises site infected flag and adds parent site to the epidemic history list.
if not self.parentSite.infected:
if Lpos > 0:
self.parentSite.infected = self.parentSite.parentGraph.simstep
self.parentSite.parentGraph.epipath.append((self.parentSite.parentGraph.simstep,self.parentSite,self.parentSite.infector))
#Migrating infecctious
self.parentSite.migInf.append(Ipos)
return [0,Ipos,Spos]
def stepSIRS(self,inits,theta=0, npass=0):
"""
calculates the model SIRS, and return its values (no demographics)
- inits = (E,I,S)
- theta = infectious individuals from neighbor sites
"""
if self.parentSite.parentGraph.simstep == 1: #get initial values
E,I,S = (self.bi['e'],self.bi['i'],self.bi['s'])
else:
E,I,S = inits
N = self.parentSite.totpop
for k, v in self.bp.items():
exec('%s = %s'%(k, v))
#parameter: beta,alpha,e,r,delta,b,w,p
Lpos = float(beta)*S*((I+theta)/(N+npass))**alpha #Number of new cases
self.parentSite.totalcases += Lpos #update number of cases
# Model
Ipos = (1-r)*I + Lpos
Spos = S + b - Lpos + w*R
Rpos = N-(Spos+Ipos) - w*R
# Updating stats
self.parentSite.incidence.append(Lpos)
# Raises site infected flag and adds parent site to the epidemic history list.
if not self.parentSite.infected:
if Lpos > 0:
#if not self.parentSite.infected:
self.parentSite.infected = self.parentSite.parentGraph.simstep
self.parentSite.parentGraph.epipath.append((self.parentSite.parentGraph.simstep,self.parentSite,self.parentSite.infector))
#Migrating infecctious
self.parentSite.migInf.append(Ipos)
return [0,Ipos,Spos]
def stepSIRS_s(self,inits=(0,0,0),theta=0, npass=0,dist='poisson'):
"""
Defines an stochastic model SIR:
- inits = (E,I,S)
- theta = infectious individuals from neighbor sites
"""
if self.parentSite.parentGraph.simstep == 1: #get initial values
E,I,S = (self.bi['e'],self.bi['i'],self.bi['s'])
else:
E,I,S = inits
N = self.parentSite.totpop
for k, v in self.bp.items():
exec('%s = %s'%(k, v))
# parameter: beta,alpha,e,r,delta,b,w,p
Lpos_esp = float(beta)*S*((I+theta)/(N+npass))**alpha #Number of new cases
if dist == 'poisson':
Lpos = poisson(Lpos_esp)
elif dist == 'negbin':
prob = I/(I+Lpos_esp) #convertin between parameterizations
Lpos = negative_binomial(I,prob)
self.parentSite.totalcases += Lpos #update number of cases
# Model
Ipos = (1-r)*I + Lpos
Spos = S + b - Lpos + w*R
Rpos = N-(Spos+Ipos) - w*R
# Updating stats
self.parentSite.incidence.append(Lpos)
if not self.parentSite.infected:
if Lpos > 0:
self.parentSite.infected = self.parentSite.parentGraph.simstep
self.parentSite.parentGraph.epipath.append((self.parentSite.parentGraph.simstep,self.parentSite,self.parentSite.infector))
#Migrating infecctious
self.parentSite.migInf.append(Ipos)
return [0,Ipos,Spos]
class edge:
"""
Defines an edge connecting two nodes (node source to node dest).
with attributes given by value.
"""
def __init__(self, source, dest, fmig=0, bmig=0, Leng=0):
"""
Main attributes of *Edge*.
source -- Source site object.
dest -- Destination site object.
fmig -- forward migration rate in number of indiv./day.
bmig -- backward migration rate in number of indiv./day.
Length -- Length in kilometers of this route
"""
if not isinstance(source, siteobj):
raise TypeError, 'source received a non siteobj class object'
if not isinstance(dest, siteobj):
raise TypeError, 'destination received a non siteobj class object'
self.dest = dest
self.source = source
self.sites = [source,dest]
self.fmig = float(fmig) #daily migration from source to destination
self.bmig = float(bmig) #daily migration from destination to source
self.parentGraph = None
self.length = Leng
self.delay = 0
self.ftheta = [] #time series of number of infected individuals travelling forward
self.btheta = [] #time series of number of infected individuals travelling backwards
dest.edges.append(self) #add itself to edge list of dest site
source.edges.append(self) #add itself to edge list of source site
def calcDelay(self):
"""
calculate the Transportation delay given the speed and length.
"""
if self.parentGraph.speed > 0:
self.delay = int(float(self.length)/self.parentGraph.speed)
def transportStoD(self):
"""
Get infectious individuals commuting from source node and inform them to destination
"""
theta,npass = self.source.getTheta(self.fmig,self.delay)
self.ftheta.append(theta)
self.dest.receiveTheta(theta,npass,self.source)
def transportDtoS(self):
"""
Get infectious individuals commuting from destination node and inform them to source
"""
theta,npass = self.dest.getTheta(self.bmig,self.delay)
self.btheta.append(theta)
self.source.receiveTheta(theta,npass,self.dest)
class graph:
"""
Defines a graph with sites and edges
"""
def __init__(self,graph_name,digraph=0):
self.name = graph_name
self.digraph = digraph
self.site_list = []
self.edge_list = []
self.speed = 0 # speed of the transportation system
self.simstep = 1 #current step in the simulation
self.maxstep = 100 #maximum number of steps in the simulation
self.epipath = []
self.graphdict = {}
self.shortPathList = []
self.parentGraph = self
self.allPairs = zeros(1)
self.cycles = None
self.wienerD = None
self.meanD = None
self.diameter = None
self.length = None
self.weight = None
self.iotaidx = None
self.piidx = None
self.betaidx = None
self.alphaidx = None
self.gammaidx = None
self.connmatrix = None
self.shortDistMatrix = None
self.episize = 0 # total number of people infected
self.epispeed = [] # new cities pre unit of time
self.infectedcities = 0 #total number of cities infected.
self.spreadtime = 0
self.mediansurvival = None
self.totVaccinated = 0
self.totQuarantined = 0
self.gr = None #This will be th visual graph representation object (DEPRECATED)
self.dmap = 0 #draw the map in the background?
self.printed = 0 #Printed the custom model docstring?
def addSite(self, sitio):
"""
Adds a site object to the graph.
It takes a siteobj object as its only argument and returns
None.
"""
if not isinstance(sitio, siteobj):
raise Error, 'add_site received a non siteobj class object'
self.site_list.append(sitio)
sitio.parentGraph = self
def dijkstra(self,G,start,end=None):
"""
Find shortest paths from the start vertex to all
vertices nearer than or equal to the end.
The input graph G is assumed to have the following
representation: A vertex can be any object that can
be used as an index into a dictionary. G is a
dictionary, indexed by vertices. For any vertex v,
G[v] is itself a dictionary, indexed by the neighbors
of v. For any edge v->w, G[v][w] is the length of
the edge. This is related to the representation in
<http://www.python.org/doc/essays/graphs.html>
where Guido van Rossum suggests representing graphs
as dictionaries mapping vertices to lists of neighbors,
however dictionaries of edges have many advantages
over lists: they can store extra information (here,
the lengths), they support fast existence tests,
and they allow easy modification of the graph by edge
insertion and removal. Such modifications are not
needed here but are important in other graph algorithms.
Since dictionaries obey iterator protocol, a graph
represented as described here could be handed without
modification to an algorithm using Guido's representation.
Of course, G and G[v] need not be Python dict objects;
they can be any other object that obeys dict protocol,
for instance a wrapper in which vertices are URLs
and a call to G[v] loads the web page and finds its links.
The output is a pair (D,P) where D[v] is the distance
from start to v and P[v] is the predecessor of v along
the shortest path from s to v.
Dijkstra's algorithm is only guaranteed to work correctly
when all edge lengths are positive. This code does not
verify this property for all edges (only the edges seen
before the end vertex is reached), but will correctly
compute shortest paths even for some graphs with negative
edges, and will raise an exception if it discovers that
a negative edge has caused it to make a mistake.
"""
D = {} # dictionary of final distances
P = {} # dictionary of predecessors
Q = priorityDictionary() # est.dist. of non-final vert.
Q[start] = 0
for v in Q:
D[v] = Q[v]
if v == end: break
for w in G[v]:
vwLength = D[v] + G[v][w]
if w in D:
#print vwLength
if vwLength < D[w]:
raise ValueError, \
"Dijkstra: found better path to already-final vertex"
elif w not in Q or vwLength < Q[w]:
Q[w] = vwLength
P[w] = v
return (D,P)
def getSite(self, name):
"""Retrieved a site from the graph.
Given a site's name the corresponding Siteobj
instance will be returned.
If multiple sites exist with that name, a list of
Siteobj instances is returned.
If only one site exists, the instance is returned.
None is returned otherwise.
"""
match = [sitio for sitio in self.site_list if sitio.name() == str(name)]
l = len(match)
if l==1:
return match[0]
elif l>1:
return match
else:
return None
def addEdge(self, graph_edge):
"""Adds an edge object to the graph.
It takes a edge object as its only argument and returns
None.
"""
if not isinstance(graph_edge, edge):
raise Error, 'add_edge received a non edge class object'
if not graph_edge.source in self.site_list:
raise Error, 'Edge source does not belong to the graph'
if not graph_edge.dest in self.site_list:
raise Error, 'Edge destination does not belong to the graph'
self.edge_list.append(graph_edge)
graph_edge.parentGraph = self
graph_edge.calcDelay()
def getGraphdict(self):
"""
Generates a dictionary of the graph for use in the shortest path function.
"""
G = {}
for i in self.site_list:
G[i] = i.getNeighbors()
self.graphdict = G
return G
def getEdge(self, src, dst):
"""
Retrieved an edge from the graph.
Given an edge's source and destination the corresponding
Edge instance will be returned.
If multiple edges exist with that source and destination,
a list of Edge instances is returned.
If only one edge exists, the instance is returned.
None is returned otherwise.
"""
match = [edge for edge in self.edge_list if edge.source == src and edge.dest == dst]
l = len(match)
if l==1:
return match[0]
elif l>1:
return match
else:
return None
def getSiteNames(self):
"""
returns list of site names for a given graph.
"""
sitenames = [s.sitename for s in self.site_list]
return sitenames
def getCycles(self):
"""
The maximum number of independent cycles in a graph.
This number (u) is estimated by knowing the number of nodes (v),
links (e) and of sub-graphs (p); u = e-v+p.
Trees and simple networks will have a value of 0 since they have
no cycles.
The more complex a network is, the higher the value of u,
so it can be used as an indicator of the level of development
of a transport system.
"""
u = len(self.edge_list) - len(self.site_list)+ 1
return u
def shortestPath(self,G,start,end):
"""
Find a single shortest path from the given start node
to the given end node.
The input has the same conventions as self.dijkstra().
'G' is the graph's dictionary self.graphdict.
'start' and 'end' are site objects.
The output is a list of the vertices in order along
the shortest path.
"""
D,P = self.dijkstra(G,start,end)
Path = []
while 1:
Path.append(end)
if end == start: break
end = P[end]
Path.reverse()
return Path
def clearVisual(self):
"""
Clear the visual graph display
"""
## for o in self.gr.display.objects:
## o.visible = 0
self.gr.display.visible = 0
del(self.gr)
self.gr = None
def viewGraph(self, mapa='limites.txt'):
"""
Starts the Vpython display of the graph.
"""
try:
import dgraph
self.gr = dgraph.Graph(0.04)
Nlist = [dgraph.Node(3,(i.pos[1],i.pos[0],0)) for i in self.site_list]
Elist = []
for e in self.edge_list:
s = self.site_list.index(e.source)
d = self.site_list.index(e.dest)
Elist.append(dgraph.RubberEdge(Nlist[s],Nlist[d],1,damping=0.7))
self.gr.insertNodeList(Nlist)
self.gr.insertEdgeList(Elist)
self.gr.centerView()
if self.dmap:
m = dgraph.Map(mapa)
self.gr.insertMap(m)
except ImportError, v:
print v
def lightGRNode(self,node,color = 'r'):
"""
Paints red the sphere corresponding to the node in the visual display
"""
i = self.site_list.index(node)
if color == 'r':
red = (self.maxstep-self.simstep)/float(self.maxstep)
blue = 1-red**6
self.gr.nodes[i].box.color = (red,0.,blue)
node.painted = 1
elif color == 'g':
self.gr.nodes[i].box.color = (0.,1.,0.)
def drawGraph(self):
"""
Draws the network using pylab
"""
from matplotlib.collections import LineCollection
from matplotlib.colors import ColorConverter
colorConverter = ColorConverter()
names = [i.sitename for i in self.site_list]
x = array([i.pos[1] for i in self.site_list])
y = array([i.pos[0] for i in self.site_list])
#edge data
xs = array([e.source.pos[1] for e in self.edge_list])
ys = array([e.source.pos[0] for e in self.edge_list])
xd = array([e.dest.pos[1] for e in self.edge_list])
yd = array([e.dest.pos[0] for e in self.edge_list])
edge_list = [((a,b),(c,d)) for a,b,c,d in zip(xs,ys,xd,yd)]
ax= axes()
ax.set_xticks([])
ax.set_yticks([])
#plotting nodes
node_plot = ax.scatter(x,y)
node_plot.set_zorder(2)
#Plotting edges
kolor = colorConverter.to_rgba('k')
ed_colors = [kolor for i in edge_list]
edge_coll = LineCollection(edge_list,colors=ed_colors,linestyle='solid')
edge_coll.set_zorder(1)
ax.add_collection(edge_coll)
#plotting labels
## for x,y,l in zip(x,y,names):
## ax.text(x,y,l,transform=ax.transData)
minx = amin(x)
maxx = amax(x)
miny = amin(y)
maxy = amax(y)
w = maxx-minx
h = maxy-miny
padx, pady = 0.05*w, 0.05*h
corners = (minx-padx, miny-pady), (maxx+padx, maxy+pady)
ax.update_datalim( corners)
ax.autoscale_view()
#saving
savefig('graph.png')
close()
def drawGraphR(self):
"""
Draws the network using R
"""
d=r.capabilities()
if d['png']:
device = r.png
device('graph.png',width=733,height=550)
elif d['jpeg']:
device = r.jpeg
device('graph.png',width=733,height=550)
else:
device = r.postscript
device('graph.png',width=733,height=550)
# node data
x = [i.pos[1] for i in self.site_list]
y = [i.pos[0] for i in self.site_list]
r.plot(x,y,axes=r.F,pch=16,xlab="",ylab="")
#edge data
xs = [e.source.pos[1] for e in self.edge_list]
ys = [e.source.pos[0] for e in self.edge_list]
xd = [e.dest.pos[1] for e in self.edge_list]
yd = [e.dest.pos[0] for e in self.edge_list]
for i in range(len(xs)):
r.lines(r.c(xs[i],xd[i]),r.c(ys[i],yd[i]),lwd=0.5,col="gray")
r.points(x,y,pch=16)
r.dev_off()
def getAllPairs(self):
"""
Returns a distance matrix for the graph nodes where
the distance is the shortest path. Creates another
distance matrix where the distances are the lengths of the paths.
"""
if self.allPairs.any(): #don't run twice
return self.allPairs
if self.graphdict:
g = self.graphdict
else:
g = self.getGraphdict()
d = len(g)
dm = zeros((d,d),float)
ap = zeros((d,d),float)
i = 0
for sitei in g.iterkeys():
j = 0
for sitej in g.keys()[:i]: #calculates only the lower triangle
sp = self.shortestPath(g,sitei,sitej)
lsp = self.getShortestPathLength(sitei,sp) #length of the shortestpath
self.shortPathList.append((sitei,sitej,sp,lsp))
#fill the entire allpairs matrix
ap[i,j] = ap[j,i] = len(sp)-1
dm[i,j] = dm[j,i] = lsp
j += 1
i += 1
self.shortDistMatrix = dm
#print ap,dm
self.allPairs = ap
return ap
def getShortestPathLength(self,origin,sp):
"""
Returns sp Length
"""
Length = 0
i=0
for s in sp[:-1]:
Length += s.getDistanceFromNeighbor(sp[i+1])
i+=1
return Length
def getConnMatrix(self):
"""
The most basic measure of accessibility involves network connectivity
where a network is represented as a connectivity matrix (C1), which
expresses the connectivity of each node with its adjacent nodes.
The number of columns and rows in this matrix is equal to the number
of nodes in the network and a value of 1 is given for each cell where
this is a connected pair and a value of 0 for each cell where there
is an unconnected pair. The summation of this matrix provides a very
basic measure of accessibility, also known as the degree of a node.
"""
try:
if self.connmatrix.any(): return self.connmatrix #don't run twice
except: pass
if not self.graphdict: #this generates site neighbors lists
self.getGraphdict()
nsites = len(self.site_list)
cm = zeros((nsites,nsites),float)
for i,sitei in enumerate(self.site_list):
for j, sitej in enumerate(self.site_list[:i]):#calculates only lower triangle
if sitei == sitej: pass
else:
cm[i,j] = float(sitej in sitei.neighbors)
#map results to the upper triangle
cm[j,i] = cm[i,j]
#print sum(cm), type(cm)
return cm
def getWienerD(self):
"""
Returns the Wiener distance for a graph.
"""
if self.wienerD: # Check if it has been calculated.
return self.wienerD
if self.allPairs.any():
return sum(self.allPairs.flat)
return sum(self.getAllPairs().flat)
def getMeanD(self):
"""
Returns the mean distance for a graph.
"""
if self.meanD:
return self.meanD
if self.allPairs.any():
return mean(compress(greater(self.allPairs.flat,0),self.allPairs.flat))
return mean(compress(greater(self.getAllPairs().flat,0),self.getAllPairs().flat))
def getDiameter(self):
"""
Returns the diameter of the graph: longest shortest path.
"""
if self.diameter:
return self.diameter
if self.allPairs.any():
return max(self.allPairs.flat)
return max(self.getAllPairs().flat)
def getIotaindex(self):
"""
Returns the Iota index of the graph
Measures the ratio between the network and its weighed vertices.
It considers the structure, the length and the function
of a graph and it is mainly used when data about traffic
is not available.
It divides the length of a graph (L(G)) by its weight (W(G)).
The lower its value, the more efficient the network is.
This measure is based on the fact that an intersection
(represented as a node) of a high order is able to handle
large amounts of traffic.
The weight of all nodes in the graph (W(G)) is the summation
of each node's order (o) multiplied by 2 for all orders above 1.
"""
iota = self.getLength()/self.getWeight()
return iota
def getWeight(self):
"""
The weight of all nodes in the graph (W(G)) is the summation
of each node's order (o) multiplied by 2 for all orders above 1.
"""
degrees = [i.getDegree() for i in self.site_list]
W = sum([i*2 for i in degrees if i > 1]) + sum([i for i in degrees if i < 2])
return float(W)
def getLength(self):
"""
Sum of the length in kilometers of all edges in the graph.
"""
L = sum([i.length for i in self.edge_list])
return float(L)
def getPiIndex(self):
"""
Returns the Pi index of the graph.
The relationship between the total length of the graph L(G)
and the distance along the diameter D(d).
It is labeled as Pi because of its similarity with the
real Pi (3.14), which is expressing the ratio between
the circumference and the diameter of a circle.
A high index shows a developed network. It is a measure
of distance per units of diameter and an indicator of
the shape of a network.
"""
if self.length:
l = self.length
else:
l = self.getLength()
lsp = [len(i[2]) for i in self.shortPathList] #list of lenghts of shortest paths.
lpidx = lsp.index(max(lsp))#position of the longest sp.
lp = self.shortPathList[lpidx][2] #longest shortest path
Dd = 0
for i in range(len(lp)-1): #calculates distance in km along lp
Dd += lp[i].getDistanceFromNeighbor(lp[i+1])
#pi = l/self.getDiameter()
pi = l/Dd
return float(pi)
def getBetaIndex(self):
"""
The Beta index
measures the level of connectivity in a graph and is
expressed by the relationship between the number of
links (e) over the number of nodes (v).
Trees and simple networks have Beta value of less than one.
A connected network with one cycle has a value of 1.
More complex networks have a value greater than 1.
In a network with a fixed number of nodes, the higher the
number of links, the higher the number of paths possible in
the network. Complex networks have a high value of Beta.
"""
B = len(self.edge_list)/float(len(self.site_list))
return B
def getAlphaIndex(self):
"""
The Alpha index is a measure of connectivity which evaluates
the number of cycles in a graph in comparison with the maximum
number of cycles. The higher the alpha index, the more a network
is connected. Trees and simple networks will have a value of 0.
A value of 1 indicates a completely connected network.
Measures the level of connectivity independently of the number of
nodes. It is very rare that a network will have an alpha value of 1,
because this would imply very serious redundancies.
"""
nsites = float(len(self.site_list))
A = self.getCycles()/(2.*nsites - 5)
return A
def getGammaIndex(self):
"""
The Gamma index is a A measure of connectivity that considers
the relationship between the number of observed links and the
number of possible links.
The value of gamma is between 0 and 1 where a value of 1
indicates a completely connected network and would be extremely
unlikely in reality. Gamma is an efficient value to measure
the progression of a network in time.
"""
nedg = float(len(self.edge_list))
nsites = float(len(self.site_list))
G = nedg/3*(nsites - 2)
return G
def doStats(self):
"""
Generate the descriptive stats about the graph.
"""
self.allPairs = self.getAllPairs()
self.cycles = self.getCycles()
self.wienerD = self.getWienerD()
self.meanD = self.getMeanD()
self.diameter = self.getDiameter()
self.length = self.getLength()
self.weight = self.getWeight()
self.iotaidx = self.getIotaindex()
self.piidx = self.getPiIndex()
self.betaidx = self.getBetaIndex()
self.alphaidx = self.getAlphaIndex()
self.gammaidx = self.getGammaIndex()
self.connmatrix = self.getConnMatrix()
return [self.allPairs,self.cycles,self.wienerD,self.meanD,self.diameter,self.length,
self.weight,self.iotaidx,self.piidx,self.betaidx,self.alphaidx,self.gammaidx,
self.connmatrix]
def plotDegreeDist(self,cum = False):
"""
Plots the Degree distribution of the graph
maybe cumulative or not.
"""
nn = len(self.site_list)
ne = len(self.edge_list)
deglist = [i.getDegree() for i in self.site_list]
if not cum:
hist(deglist)
title('Degree Distribution (N=%s, E=%s)'%(nn,ne))
xlabel('Degree')
ylabel('Frequency')
else:
pass
savefig('degdist.png')
close()
def getMedianSurvival(self):
"""
Returns the time taken by the epidemic to reach 50% of the nodes.
"""
n = len(self.site_list)
try:
median = self.epipath[int(n/2)][0]
except: # In the case the epidemic does not reach 50% of nodes
median = 'NA'
return median
def getTotVaccinated(self):
"""
Returns the total number of vaccinated.
"""
tot = sum([i.nVaccinated for i in self.site_list])
return tot
def getTotQuarantined(self):
"""
Returns the total number of quarantined individuals.
"""
tot = sum([i.nQuarantined for i in self.site_list])
return tot
def getEpistats(self):
"""
Returns a list of all epidemiologically related stats.
"""
self.episize =self.getEpisize()
self.epispeed = self.getEpispeed()
self.infectedcities = self.getInfectedCities()
self.spreadtime= 0 #self.getSpreadTime()
self.mediansurvival = self.getMedianSurvival()
self.totVaccinated = self.getTotVaccinated()
self.totQuarantined = self.getTotQuarantined()
return[self.episize,self.epispeed,self.infectedcities,
self.spreadtime,self.mediansurvival,self.totVaccinated,self.totQuarantined]
def getInfectedCities(self):
"""
Returns the number of infected cities.
"""
res = len(self.epipath)
return res
def getEpisize(self):
"""
Returns the size of the epidemic
"""
N = sum([site.totalcases for site in self.site_list])
return N
def getEpispeed(self):
"""
Returns the epidemic spreading speed.
"""
tl = [i[0] for i in self.epipath]
nspt = []
for j in range(self.simstep):
nspt.append(tl.count(j)) #new sites per time step
#Speed = [nspt[i+1]-nspt[i] for i in range(len(nspt))]
return nspt
def getSpreadTime(self):
"""
Returns the duration of the epidemic in units of time.
"""
tl = [i[0] for i in self.epipath]
if not tl:
dur = 'NA'
else:
dur = tl[-1]-tl[0]
return dur
def resetStats(self):
"""
Resets all graph related stats
"""
self.allPairs = None
self.cycles = None
self.wienerD = None
self.meanD = None
self.diameter = None
self.length = None
self.weight = None
self.iotaidx = None
self.piidx = None
self.betaidx = None
self.alphaidx = None
self.gammaidx = None
class priorityDictionary(dict):
def __init__(self):
'''
by David Eppstein.
<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117228>
Initialize priorityDictionary by creating binary heap
of pairs (value,key). Note that changing or removing a dict entry will
not remove the old pair from the heap until it is found by smallest() or
until the heap is rebuilt.
'''
self.__heap = []
dict.__init__(self)
def smallest(self):
'''
Find smallest item after removing deleted items from heap.
'''
if len(self) == 0:
raise IndexError, "smallest of empty priorityDictionary"
heap = self.__heap
while heap[0][1] not in self or self[heap[0][1]] != heap[0][0]:
lastItem = heap.pop()
insertionPoint = 0
while 1:
smallChild = 2*insertionPoint+1
if smallChild+1 < len(heap) and \
heap[smallChild] > heap[smallChild+1]:
smallChild += 1
if smallChild >= len(heap) or lastItem <= heap[smallChild]:
heap[insertionPoint] = lastItem
break
heap[insertionPoint] = heap[smallChild]
insertionPoint = smallChild
return heap[0][1]
def __iter__(self):
'''
Create destructive sorted iterator of priorityDictionary.
'''
def iterfn():
while len(self) > 0:
x = self.smallest()
yield x
del self[x]
return iterfn()
def __setitem__(self,key,val):
'''
Change value stored in dictionary and add corresponding
pair to heap. Rebuilds the heap if the number of deleted
items grows too large, to avoid memory leakage.
'''
dict.__setitem__(self,key,val)
heap = self.__heap
if len(heap) > 2 * len(self):
self.__heap = [(v,k) for k,v in self.iteritems()]
self.__heap.sort() # builtin sort likely faster than O(n) heapify
else:
newPair = (val,key)
insertionPoint = len(heap)
heap.append(None)
while insertionPoint > 0 and \
newPair < heap[(insertionPoint-1)//2]:
heap[insertionPoint] = heap[(insertionPoint-1)//2]
insertionPoint = (insertionPoint-1)//2
heap[insertionPoint] = newPair
def update(self, other):
for key in other.keys():
self[key] = other[key]
def setdefault(self,key,val):
'''Reimplement setdefault to call our customized __setitem__.'''
if key not in self:
self[key] = val
return self[key]
#---main----------------------------------------------------------------------------
#if __name__ == '__main__':
# sitioA = siteobj("Penedo",2000)
# sitioB = siteobj("Itatiaia",3020)
# linhaA = edge(sitioA,sitioB,4)
# sitioA.createModel((.3,.3,.3),(1,1))
# sitioA.runModel()
#lista_de_sitios = (i=siteobj(10) for i = range(10))
|