-
Notifications
You must be signed in to change notification settings - Fork 1
/
Code_Hamming.py
310 lines (279 loc) · 8.99 KB
/
Code_Hamming.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
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
# -*- coding: utf-8 -*-
"""
Created on Tue May 15 22:55:34 2018
@author: liuzx
"""
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 6 16:13:27 2018
@author: liuzx
"""
import matplotlib.pyplot as plt
import numpy as np
import random
import copy
import math
import time
import pickle
import Functions as fc
'''Function for hamming distance'''
def minHamming(x,y):#x,y are lists
hamming = []
for a in x:
for b in y:
a = np.array(a)
b= np.array(b)
#print(a)
#print(b)
vec = (a ^ b)
#print (vec)
hamming.append(sum (vec))
return min(hamming)/len(a)#, hamming
def create_world(propsition_number):
single_agent =set()# [set()]*an # use SET as for any agents
# agents_temp = []
agent_tuple = [] # belief as tuple(tuple is unchangeable)
states = [0]*propsition_number #proposition as list
world = [] #A list of sets of tuple
# initialise the agents
agents_number = int(math.pow(2,propsition_number))
for i in range(agents_number):
basic = i+1
for j in range (propsition_number):
states[j] = basic%2
basic = basic//2
states_set = tuple(states)
agent_tuple.append(states_set)
single_agent = set (agent_tuple)
#print (states_set)
#print (single_agent)
agent_tuple.clear()
#print (single_agent)
world.append(single_agent)
# world_set = world[0]
# for k in range(agents_number):
# world_set = world_set|world[k]
return world
def random_initialise(agents_number, propsition_number,world):
'''
initialise the agents randomly (with a random number of beliefs)
'''
single_agent =set()# [set()]*an # use SET as for any agents
# agents_temp = []
agent_tuple = [] # belief as tuple(tuple is unchangeable)
states = [0]*propsition_number #proposition as list
agents = [] #A list of sets of tuple
indexlist = list(range(2**propsition_number))
# print(indexlist)
# initialise the agents
for i in range(agents_number):
for j in range (propsition_number):
states[j] = (random.randint(0,1))
states_set = tuple(states)
agent_tuple.append(states_set)
single_agent = set (agent_tuple)
#print (states_set)
#print (single_agent)
agent_tuple.clear()
#print (single_agent)
agents.append(single_agent)
for num in range(len(agents)):
num_blf = random.randint(1,int(math.pow(2,propsition_number)))
agt = [agents[num]]
random.shuffle(indexlist)
k = 0
while cal_card(agt) < num_blf :
# print (agt)
# print(cal_card(agt))
# print (num_blf)
# print(agents)
agents[num] = agents[num]|world[indexlist[k]]
k=k+1
agt = [agents[num]]
return agents
def initialise_agents(agents_number, propsition_number):
'''
initialise the agents randomly (with a single belief)
'''
single_agent =set()# [set()]*an # use SET as for any agents
# agents_temp = []
agent_tuple = [] # belief as tuple(tuple is unchangeable)
states = [0]*propsition_number #proposition as list
agents = [] #A list of sets of tuple
# initialise the agents
for i in range(agents_number):
for j in range (propsition_number):
states[j] = (random.randint(0,1))
states_set = tuple(states)
agent_tuple.append(states_set)
single_agent = set (agent_tuple)
#print (states_set)
#print (single_agent)
agent_tuple.clear()
#print (single_agent)
agents.append(single_agent)
return agents
'''compute the average cardinality of all agents'''
def cal_card(agents):
sumcard = 0;
N =len(agents)
for i in range(N):
sumcard = sumcard + len (agents[i])
mean_card = sumcard/N
return mean_card
def deleteDuplicatedElementFromList(listx):
resultList = []
for item in listx:
if not item in resultList:
resultList.append(item)
return resultList
''' transfer binary string to DEC number'''
def trans2dec(list_set_of_tuple):
dec= []
for index in range(1):# range(len(list_set_of_tuple)):
# print(set_of_tuple)
for x in list_set_of_tuple[index]:
a=0
for i in range(len(x)):
a = a+x[i]*math.pow(2,len(x)-i-1)
# print(a)
dec.append(a)
return dec
'''compute the average simlarity of all agents'''
def cal_similarity(agents):
#calculate similarity
similarity = []
simtotal = []
an = len(agents)
for i in range(an):
for j in range (i+1,an):
Num_inter =len(agents[i]&agents[j])
Num_uni = len(agents[i]|agents[j])
similarity.append((Num_inter/Num_uni))
simtotal.append(similarity)
return similarity
''' one time for combine beliefs'''
def iterationHamm(agents,agent_number, iteration_times,threshold):
an = agent_number
#sn = proposition_number
N = iteration_times
averagesim = [];
iteration=0 # iteration time count
cardinality = [];
while iteration < N:
iteration =iteration +1
# print (iteration)
index1 = random.randint(0,an-1)
index2 = random.randint(0,an-1)
#t = agents [index1]
#s = agents [index2]
Intersection = agents[index1]&agents[index2]
Union = agents[index1]|agents[index2]
#distance = hammingdis(s,t) # check if overlap exists
if minHamming(agents[index1],agents[index2])<=threshold:
if (Intersection == set()) :
agents [index1] =Union
agents [index2] =Union
else:
agents [index1]=Intersection#intersect if not
agents [index2]=Intersection
mean_card = cal_card(agents)
cardinality.append(mean_card)
similarity = cal_similarity(agents)
averagesim.append(sum(similarity)/len(similarity))
'''
print (averagesim)
plt.figure(1)
plt.plot(averagesim)#, sta)
#plt.xlabel('Time (ms)')
#plt.ylabel('Stimulus')
#plt.title('Spike-Triggered Average')
#plt.savefig('C:\\Users\\liuzx\\Spyderpro\\CW2\\Computational-Neuroscience-coursework2\\Spike_Triggered_Average(Q3)')
plt.show()
plt.figure(2)
plt.plot(cardinality)
plt.show()
#print (similarity)
#print (simtotal)
'''
return averagesim, cardinality , agents
def text_save(content,filename,mode='a'):
# Try to save a list variable in txt file.
file = open(filename,mode)
for i in range(len(content)):
file.write(str(content[i])+'\n')
file.close()
start1 = time.time()
#long running
#do something other
start = time.clock()
an = 100 #Number of agents
sn = 5 #Number of propsitions
N = 1800 # Times of iterations
T = 1
threshold = 0.3
sim = []
card = []
AVEsim=[]
AVEcard = []
convergePos = []
belief_num =[]
#averagesim = [0]*T
#cardinality = [0]*T
#agents = initialise_agents(an, sn);
for i in range (T):
'''when change the initialise method,
Remember to change the FILENAME and FIGURENAME'''
#agents = initialise_agents(an, sn)
agents = random_initialise(an, sn,create_world(sn))
trans = copy.deepcopy(agents)
#print (agents)
(averagesim, cardinality, store) = iterationHamm(trans,an,N,threshold)
print(store)
store2 = deleteDuplicatedElementFromList(store)
dec = trans2dec(store2)
pos = copy.deepcopy(dec)
#print (agents)
#print (pos)
convergePos.append(pos)
belief_num.append(len(store2))
sim.append(averagesim)
card.append(cardinality)
#print (averagesim)
sumsim = [0]*len(averagesim)
sumcard = [0]*len(cardinality)
countagt = [0]*int(math.pow(2,sn))
for i in range (T):
sumsim = (np.sum([sumsim,sim[i]],axis = 0))
sumcard =(np.sum([sumcard,card[i]],axis = 0))
countagt[int(convergePos[i][0])]=countagt[int(convergePos[i][0])]+1
xaxis = np.arange(1, len(countagt)+1)
AVEsim=sumsim/T
AVEcard=sumcard/T
stdsim = np.std(sim,axis=0)
stdcard = np.std(card,axis=0)
stdsim_f = []
stdcard_f= []
AVEcard_f = []
AVEsim_f = []
index = []
j=0
while j < len(stdsim):
index.append(j)
stdsim_f.append(stdsim[j])
stdcard_f.append(stdcard[j])
AVEcard_f.append(AVEcard[j])
AVEsim_f.append(AVEsim[j])
j = j+50
end1 = time.time()
print("Time1 used:",end1-start1)
elapsed = (time.clock() - start)
print("Time used:",elapsed)
filename ='data'+str(an)+'_'+str(sn)+'_'+str(N)+'_'+str(T)+'_'+str(int(threshold*10))#+'single'
figurename = str(an)+'_'+str(sn)+'_'+str(N)+'_'+str(T)+'_'+str(int(threshold*10))#+'single'
path = 'figsHamm/'
fc.seriesplot(path,figurename,AVEsim, AVEsim_f,stdsim_f,AVEcard,index,AVEcard_f,stdcard_f,xaxis,countagt,belief_num)
text_save([AVEsim, AVEcard, stdsim_f,stdcard_f,countagt,elapsed],filename,mode='a')
f= open(path+filename, 'wb')
pickle.dump([AVEsim, AVEcard, stdsim_f,stdcard_f,countagt,elapsed], f)
f.close()