-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
73 lines (42 loc) · 1.45 KB
/
main.py
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
# imports
import networkx as nx
import numpy as np
import pandas as pd #type: ignore
# creating graph/nodes
G = nx.Graph()
G.add_nodes_from(['A','B','C','D','E'])
G.add_edges_from([('A','D'),('D','E'), ('A','B'), ('A','C'), ('C', 'D'), ('B','E'), ('A','E')])
# creating adjacency matrix
def createAdjacencyMatrix(nodes, edges):
names = G.nodes
size = len(names)
arr = np.zeros(shape=(size,size))
matrix = pd.DataFrame(arr, index=names, columns=names)
for edge in edges:
start, end = edge
matrix.loc[start][end] = 1
matrix.loc[end][start] = 1
return matrix
matrix = createAdjacencyMatrix(G.nodes, G.edges)
print("ADJACENCY MATRIX...")
print(matrix)
# creating probability matrix
def createProbabilityMatrix(adjMatrix):
for index, row in adjMatrix.iterrows():
tempSum = row.sum()
if (tempSum > 0):
adjMatrix.loc[index] = (row / tempSum)
return adjMatrix
def marchovChain(probMatrix, k):
nodes = probMatrix.index.tolist()
probZero = np.zeros(len(nodes))
probZero[nodes.index('A')] = 1
matrixTranspose = probMatrix.T.values
tranpose_power = np.linalg.matrix_power(matrixTranspose, k)
pk = np.dot(probZero, tranpose_power)
return pd.Series(pk, index=nodes)
newMatrix = createProbabilityMatrix(matrix)
for i in range(1,27,4):
print("After " + str(i) + " Steps:")
k_step_matrix = marchovChain(newMatrix, i)
print(k_step_matrix)