-
Notifications
You must be signed in to change notification settings - Fork 0
/
BA graphAP.py
416 lines (363 loc) · 10.4 KB
/
BA graphAP.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
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
#-------------------------------------------------------------------------------
# Name: module3
# Purpose:
#
# Author: lenovo
#
# Created: 24-07-2017
# Copyright: (c) lenovo 2017
# Licence: <your licence>
#-------------------------------------------------------------------------------
import re, powerlaw
import numpy, math, pylab
from numpy import *
from scipy.interpolate import spline
from nltk.corpus import stopwords, words
from nltk import pos_tag
import sys
from pylab import *
from itertools import chain, combinations
from collections import defaultdict, OrderedDict
from optparse import OptionParser
import matplotlib.pyplot as plt
import matplotlib, itertools
import preprocessor
import networkx as nx
def encode(text):
"""
For printing unicode characters to the console.
"""
return text.encode('utf-8')
def joinSet(itemSet, length):
"""Join a set with itself and returns the n-element itemsets"""
return set([i.union(j) for i in itemSet for j in itemSet if len(i.union(j)) == length])
def tf(word, blob):
return float(blob.count(word) / float(len(blob)))
def n_containing(word, blob, bloblist):
return sum(1 for blob in bloblist if word in blob)
def idf(word, blob, bloblist):
return math.log(len(bloblist) / float(1 + n_containing(word, blob, bloblist)))
def tfidf(word, blob, bloblist):
return tf(word, blob) * idf(word, blob, bloblist)
def main():
pass
if __name__ == '__main__':
main()
usertweet=dict()
dusertweet=dict()
i=0
with open("CIKM3.txt", "r") as f:
usertweet=eval(f.read())
##print usertweet
#Preprocessing of twitter feeds
j=1
for k,v in usertweet.iteritems():
try:
tempstorage=encode(usertweet[k])
except:
tempstorage=usertweet[k]
preprocessor.set_options(preprocessor.OPT.URL, preprocessor.OPT.EMOJI, preprocessor.OPT.SMILEY, preprocessor.OPT.RESERVED)
tempstorage=preprocessor.clean(tempstorage)
tempstorage = re.sub('[@#]', '', tempstorage)
tempstorage = ' '.join([word for word in tempstorage.split() if word not in stopwords.words("english")])
tempstorage = ' '.join([word for word in tempstorage.split() if len(word)>2])
temp=tempstorage.lower()
if j<1000:
dusertweet[j]=temp
j=j+1
##print dusertweet
countword=0
#Vocabulary of twitter feeds
vocabcorpus=[]
for k,v in dusertweet.iteritems():
tempstore=dusertweet[k]
listtemp=tempstore.split()
for each in listtemp:
countword=countword+1
if each not in vocabcorpus:
vocabcorpus.append(each)
##print vocabcorpus
#Creating dictionary of words
dictofwords=dict()
flag=1
for each in vocabcorpus:
dictofwords[each]=flag
flag=flag+1
##print dictofwords
#Indexing words in twitter feeds
templist=[]
duservaluekeys=dict()
j=1
for item in dusertweet.itervalues():
s=item.split()
for eachvalue in s:
templist.append(dictofwords[eachvalue])
duservaluekeys[j]=templist
templist=[]
j=j+1
##print duservaluekeys
flag=1
indexwisedictofwords=dict()
for k,v in dictofwords.iteritems():
indexwisedictofwords[v]=k
#Listofedges
edgelist=[]
for eachvalue in duservaluekeys.itervalues():
for i in range(1,len(eachvalue)):
for j in range(i+1,len(eachvalue)):
edge=(eachvalue[i],eachvalue[j])
edgelist.append(edge)
##print edgelist
indexwisedictofwords=dict()
for k,v in dictofwords.iteritems():
indexwisedictofwords[v]=k
#Weight of edges
weightdict=dict()
for each in edgelist:
if each not in weightdict.keys():
weightdict[each]=1
else:
weightdict[each]=weightdict[each]+1
##print weightdict
##lstwt=list(numpy.unique(weightdict.values()))
##print lstwt
##
##distdict=dict([(key, 0) for key in lstwt])
##
##for each,value in weightdict.iteritems():
## if distdict[value]==0:
## distdict[weightdict[each]]=1
## else:
## distdict[weightdict[each]]=distdict[weightdict[each]]+1
##
##newdictofvalues=dict()
##
##for x in range(1, lstwt[-1]):
## if x in distdict.keys():
## newdictofvalues[x]=distdict[x]
## else:
## newdictofvalues[x]=0
##
##lists=sorted(newdictofvalues.items())
##x, y = zip(*lists)
##newplot=plt.plot(x,y)
##plt.xlim(0,lstwt[-1])
##plt.ylim(0,max(newdictofvalues.values()))
##plt.xlabel('Edge Weight')
##plt.ylabel('Co-occurrence Frequency')
##
##plt.show(newplot)
##lstwt=list(weightdict.values())
##print lstwt
##
##fit = powerlaw.Fit(numpy.array(lstwt)+1,xmin=1,discrete=True)
##fit.power_law.plot_pdf( color= 'b',linestyle='--',label='fit ccdf')
##fit.plot_pdf( color= 'b')
##
##print('alpha= ',fit.power_law.alpha,' sigma= ',fit.power_law.sigma)
##
##
##
##
weightededgelist=[]
for (first,second) in weightdict.iterkeys():
weightededgelist.append((first,second,weightdict[(first,second)]))
#print weightededgelist
G=nx.DiGraph()
for (u,v,d) in weightededgelist:
G.add_edge(u,v,weight=d)
sumdeg=0
degdict=dict()
for each in G.nodes():
deg=G.degree(each)
degdict[each]=deg
sumdeg=sumdeg+deg
print "Average degree"
Ad=(float)(sum(degdict.values()) / (float)(len(degdict.values())))
print Ad
print "***************************************************************************"
N=len(G.nodes())
m=(int)(Ad)
ERG=nx.barabasi_albert_graph(N,m)
G=ERG
Z=G.to_undirected()
le=nx.adjacency_spectrum(Z)
addle=dict()
for each in list(le):
if each in addle.keys():
addle[each]=addle[each]+1
else:
addle[each]=1
plt.plot(223)
lists=sorted(addle.items(),reverse=True)
x, y = zip(*lists)
newpl=plt.plot(x,y,'ro', markersize=1)
plt.xscale('symlog')
plt.yscale('linear')
plt.xlabel('lambda')
plt.ylabel('Spectral Density')
plt.show(newpl)
sumdeg=0
degdict=dict()
for each in G.nodes():
deg=G.degree(each)
degdict[each]=deg
sumdeg=sumdeg+deg
wtdegdict=dict()
sumdeg=0
for each in G.nodes():
deg=G.degree(each,weight="weight")
wtdegdict[each]=deg
sumdeg=sumdeg+deg
##inout=dict()
##outin=dict()
##for each,value in wtdegdict.iteritems():
## inout[G.in_degree(each,weight='weight')]=G.out_degree(each,weight='weight')
## outin[G.out_degree(each,weight='weight')]=G.in_degree(each,weight='weight')
##
##lists=sorted(inout.items())
##x, y = zip(*lists)
##plt.subplot(221)
##newplot=plt.plot(inout.keys(),inout.values(),'ro', markersize=1)
##plt.xlim(0,max(inout.keys()))
##plt.ylim(0,max(inout.values()))
##plt.xlabel('In-degree')
##plt.ylabel('Out-degree')
##
##plt.show(newplot)
##
##lists=sorted(outin.items())
##x, y = zip(*lists)
##plt.subplot(221)
##newplot=plt.plot(x,y,'ro', markersize=1)
##plt.xlim(0,max(outin.keys()))
##plt.ylim(0,max(outin.values()))
##plt.xlabel('Out-degree')
##plt.ylabel('In-degree')
##
##plt.show(newplot)
le=sorted(le,reverse=True)
addle=dict()
i=1
for each in list(le):
addle[i]=each
i=i+1
plt.subplot(223)
lists=sorted(addle.items(),reverse=False)
x, y = zip(*lists)
newplot=plt.plot(x,y,'ro', markersize=1)
plt.yscale('symlog')
##plt.xlim(0,len(le))
##plt.ylim(0,max(le))
plt.xlabel('Rank i')
plt.ylabel('Eigenvalues')
plt.show(newplot)
print max(le)
lst=[]
weightknn=dict()
for each in Z.nodes():
lstofneigh=Z.neighbors(each)
degofneighnode=0
count=0
for eachnode in lstofneigh:
degofneighnode=degofneighnode+Z.degree(eachnode)
count=count+1
if count>=1:
calknn=(float)((float)(degofneighnode)/(float)(count))
weightknn[each]=calknn
lstofneigh=[]
knndict=dict()
lstofdeg=list(degdict.values())
for each in lstofdeg:
count=0
addnode=0
for k,v in weightknn.iteritems():
if degdict[k]==each:
addnode=addnode+v
count=count+1
calknn=(float)((float)(addnode)/(float)(count))
knndict[each]=calknn
plt.subplot(222)
lists=sorted(knndict.items())
x, y = zip(*lists)
newplot=plt.plot(x,y,'ro',markersize=1)
#plt.xlim(0,max(knndict.keys()))
plt.xscale('log')
plt.yscale('log')
#plt.ylim(0,max(knndict.values()))
plt.xlabel('Degree k')
plt.ylabel('K-Nearest Neighbour')
plt.show(newplot)
degdist=dict()
allval=list(sorted(set(wtdegdict.values()),reverse=True))
degdist=dict([(key, 0) for key in allval])
for each,value in wtdegdict.iteritems():
degdist[value]=degdist[value]+1
#Degree Distribution
plt.subplot(222)
lists=sorted(degdist.items(),reverse=True)
x, y = zip(*lists)
newplot=plt.plot(x,y,'ro', markersize=1)
plt.yscale('log')
plt.xscale('log')
plt.xlabel('Degree k')
plt.ylabel('Degree distribution')
plt.show(newplot)
#Edge Weight Distribution
wtdist=dict()
allval=list(sorted(set(weightdict.values()),reverse=True))
wtdist=dict([(key, 0) for key in allval])
for each,value in weightdict.iteritems():
wtdist[value]=wtdist[value]+1
plt.subplot(222)
lists=sorted(wtdist.items(),reverse=True)
x, y = zip(*lists)
newplot=plt.plot(x,y,'ro', markersize=1)
plt.yscale('log')
plt.xscale('log')
plt.xlabel('Edge weight w')
plt.ylabel('Edge weight distribution')
plt.show(newplot)
#Clustering COefficient
nodesbydeg=dict()
for each in lstofdeg:
templst=[]
for k,v in degdict.iteritems():
if v==each:
templst.append(k)
nodesbydeg[each]=templst
templst=[]
clusteringcoeff=dict()
for k,v in nodesbydeg.iteritems():
clusteringcoeff[k]=nx.average_clustering(Z,v)
plt.subplot(222)
lists=sorted(clusteringcoeff.items(),reverse=True)
x, y = zip(*lists)
newplot=plt.plot(x,y,'ro', markersize=1)
plt.yscale('log')
plt.xscale('log')
plt.xlabel('Degree k')
plt.ylabel('Clustering Coefficient')
plt.show(newplot)
print "******************************************************************************"
nodesbydeg=dict()
for each in lstofdeg:
templst=[]
for k,v in degdict.iteritems():
if v==each:
templst.append(k)
nodesbydeg[each]=templst
templst=[]
clusteringcoeff=dict()
for k,v in nodesbydeg.iteritems():
clusteringcoeff[k]=nx.average_clustering(Z,v, weight='weight')
plt.subplot(222)
lists=sorted(clusteringcoeff.items(),reverse=True)
x, y = zip(*lists)
newplot=plt.plot(x,y,'ro', markersize=1)
plt.yscale('log')
plt.xscale('log')
plt.xlabel('Degree k')
plt.ylabel('Clustering Coefficient')
plt.show(newplot)
print "******************************************************************************"