-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDTMCSN.py
243 lines (181 loc) · 8.78 KB
/
DTMCSN.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
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
# -*- coding: utf-8 -*-
# author: Yu Fu, Louise A. Dennis
# Update version used for large network(>99/use Networkx)
import tkinter as tk
from tkinter import ttk
import operator
from random import choice
import random
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
import statistics
def generate_FCN_graph(nodes, edges, seed):
G = nx.complete_graph(nodes)
# pos = nx.spring_layout(G) # layout style of the graph
# nx.draw(G, pos, with_labels=False, node_size=30, node_color='blue')
# Show the graph of the network(structure)
# plt.show()
return G
def generate_graph(nodes, edges, seed):
G = nx.random_graphs.barabasi_albert_graph(nodes, edges, seed)
# pos = nx.spring_layout(G) # layout style of the graph
# nx.draw(G, pos, with_labels=False, node_size=30, node_color='blue')
# Show the graph of the network(structure)
# plt.show()
return G
# sim_diff is 0 to seed at nodes with different degrees, 1 to see at nodes with similar degrees
def Infection_Model(nodes, graph, probability_indifferent, prob_idea, messages, runs, sim_diff):
# G = generate_graph(nodes, edges, graph_seed)
edges = list(graph.edges())
# print("Edges: ", edges)
connections = {}
for node in range(nodes):
connections[node] = len(list(graph.neighbors(node)))
sortedConnections = sorted(connections.items(), key=operator.itemgetter(1))
if (sim_diff == 0): # unbalanced
# print("A")
# seed connections: many is top 0.25, few is the last 0.25
ManyNumber = FewNumber = int(float(nodes) * 0.25)
FewList = sortedConnections[:FewNumber]
ManyList = sortedConnections[-ManyNumber:]
# First we generate some stats for `gets there first'
idea_init = choice(ManyList)[0]
antiidea_init = choice(FewList)[0]
elif (sim_diff==1): # similar
# print("B")
idea_index = random.randrange(nodes)
less_greater = random.randint(0, 1)
if (less_greater == 0):
anti_idea_index = random.randint(idea_index - int(float(nodes) * 0.1), idea_index - 1)
if (anti_idea_index < 0 or anti_idea_index > len(sortedConnections) - 1):
anti_idea_index = random.randint(idea_index + 1, idea_index + int(float(nodes) * 0.1))
else:
anti_idea_index = random.randint(idea_index + 1, idea_index + int(float(nodes) * 0.1))
if (anti_idea_index < 0 or anti_idea_index > len(sortedConnections) - 1):
anti_idea_index = random.randint(idea_index - int(float(nodes) * 0.1), idea_index - 1)
idea_init = sortedConnections[idea_index][0]
antiidea_init = sortedConnections[anti_idea_index][0]
else: # few and few
ManyNumber = FewNumber = int(float(nodes) * 0.25)
FewList = sortedConnections[:FewNumber]
# First we generate some stats for `gets there first'
perm = np.random.permutation(FewList)
idea_init = perm[0,0]
antiidea_init = perm[1,0]
# print ("idea: " + str(len(list(graph.neighbors(idea_init)))) + " anti idea: " + str(len(list(graph.neighbors(antiidea_init)))))
total = 0
for i in range(runs):
agree = model_results(nodes,probability_indifferent, prob_idea,idea_init,antiidea_init,messages,graph)
total = agree + total
AgreePercent = float( (total * 100) / (runs * nodes))
# print ("Expected Agreement: ", AgreePercent)
return AgreePercent
def model_results(nodes, prob1, prob2, idea, anti, messages, G):
state = ["agree", "disagree", "indifferent"]
dict = DTMC_Transition(nodes, prob1, prob2, idea, anti, messages, G)
agree = 0
disagree = 0
for key, value in dict.items():
if dict[key] == state[0]:
agree += 1
if dict[key] == state[1]:
disagree +=1
return agree
# print("Agree: ", agree)
# print("Disagree: ", disagree)
def DTMC_Transition(nodes,prob1, prob2,idea,antiIdea,messages, G):
edges = G.edges
# probability of infection
probability1=float(prob1)
probability2=float(prob2)
# state: agree, disagree, indifferent
state = ["agree", "disagree", "indifferent"]
######################################################################################
# construct a dictionary to store the state of each node (key: node name; value: state)
dict={}
# initially set all nodes' state indifferent
for n in range(int(nodes)):
dict[n]=state[2]
InfectedNodes = [] # store all infected nodes and update in time
# set two seeds' state: agree or disagree
if idea!=None:
dict[idea]=state[0]
InfectedNodes.append(idea)
if antiIdea!=None:
dict[antiIdea]=state[1]
InfectedNodes.append(antiIdea)
m = 0 # messages
# the number of loops equals to the simulation time? equal to message number?
# print ("starting run")
while(m < messages):
# select one infected node at random(PRISM work model)
Random_Infected_Node = choice(InfectedNodes)
# Find the connection of the node and transform the idea based on the probability
#print("Random_Infected_node: ",Random_Infected_Node)
# connectednodes=find_connected_nodes(Random_Infected_Node,edges)
#print("Connected nodes: ",connectednodes)
# The state of the random selected infected node: agree or anti
x_state = dict[Random_Infected_Node]
# The state of each connected nodes: initialized is indifferent
for n in G.neighbors(Random_Infected_Node):
n_state = dict[n]
# for the connected node n, update the opinions of it according to the relevant probabilities
if (x_state != n_state):
x = random.uniform(0,1)
if (n_state == "indifferent" and x < probability1):
dict[n]=x_state
InfectedNodes.append(n)
elif (x < probability2):
# print(probability2)
dict[n]=x_state
# print(dict)
m += 1
return dict
def output_graph(FewList, AverageList, ManyList, numberOfNodes, probability_value, edges, number_Of_SimulationTimes):
FewideaConnection = FewList # few connection
FewantiIdeaConnection = FewList # few connection
AverageideaConnection=AverageList # average connection
AverageantiIdeaConnection=AverageList # average connection
ManyideaConnection=ManyList # many connection
#antiIdeaConnection=[('1', 2), ('3', 2)] # few connection
print('FewideaConnection: ',FewideaConnection)
print("FewantiIdeaConnection: ", FewantiIdeaConnection)
print("AverageideaConnection: ", AverageideaConnection)
print("AverageantiIdeaConnection", AverageantiIdeaConnection)
print("ManyideaConnection", ManyideaConnection)
messages = []
ExpectedInfection_few = []
ExpectedInfection_average = []
ExpectedInfection_manyAndfew = []
i = 0
message = int(numberOfNodes) *4
# when there are 10 nodes the number of messages is 40, so quadruple here
while i <= message:
messages.append(i)
y1 = statistics(i, FewideaConnection, FewantiIdeaConnection, numberOfNodes, probability_value, edges, number_Of_SimulationTimes)
ExpectedInfection_few.append(y1)
y2 = statistics(i, AverageideaConnection, AverageantiIdeaConnection, numberOfNodes, probability_value, edges, number_Of_SimulationTimes)
ExpectedInfection_average.append(y2)
y3 = statistics(i, ManyideaConnection, FewantiIdeaConnection, numberOfNodes, probability_value, edges, number_Of_SimulationTimes)
ExpectedInfection_manyAndfew.append(y3)
i = i + int(message/10) # this is the interval between data points on the curve (10 nodes -> 2 interval)
print(messages)
print(ExpectedInfection_few)
print(ExpectedInfection_average)
print(ExpectedInfection_manyAndfew)
plt.plot(messages, ExpectedInfection_few, color='blue', label='initial agent have few connections', marker='o',
markersize='3', linestyle='-')
plt.plot(messages, ExpectedInfection_average, color='green', label='initial agent have average connections', marker='s',
markersize='3', linestyle='-')
plt.plot(messages, ExpectedInfection_manyAndfew, color='red', label='initial agent have many and few connections', marker='v',
markersize='3', linestyle='-')
x_ticks = np.arange(0, message + 2, int(message/10))
y_ticks = np.arange(0.0, max(ExpectedInfection_manyAndfew) + 0.5, int(max(ExpectedInfection_manyAndfew) + 0.5)/10)
plt.xticks(x_ticks)
plt.yticks(y_ticks)
plt.legend()
plt.grid()
plt.xlabel('messages')
plt.ylabel('Expected Infection')
plt.show()