-
Notifications
You must be signed in to change notification settings - Fork 4
/
wikigraph.py
1336 lines (987 loc) · 61.3 KB
/
wikigraph.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
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
#!/bin/env python2
import WikiwhoRelationships
from copy import deepcopy
from sys import argv,exit
import getopt
import numpy as np
import math
import random
import cgi
from structures.Word import Word
import operator
#from django.utils import simplejson
context = {}
context_obj = {}
random.seed(3)
def getGraph(filename):
# Compute distribution information
(revisions, order, relations) = WikiwhoRelationships.analyseArticle(filename)
# Graph structures.
edges_rev = {}
nodes = {}
# Metrics structures.
ordered_editors = []
ordered_not_vandalism = []
all_antagonized_editors = []
all_supported_editors = []
statsData = []
contributors_rev = {}
window = 50
rev_counter = -1
#C = {}
for (revision, vandalism) in order:
rev_counter = rev_counter + 1
if (vandalism):
#print "vandalism", revision
statsData.append({'revision': revision,
'distinct_editors': 0,
'deletion_edges_contributors_w': 0,
'deletion_outgoing_ratio': 0,
'deletion_incoming_ratio': 0,
'deletion_reciprocity': 0,
'deletion_weight_avg': 0,
'bipolarity' : 0,
'deletion_weight' : 0,
'adjacency_matrix' : ([], [], {}, 0),
'reciprocity_matrix' : {},
'weight_matrix' : {},
'context' : {},
'antagonistic_focus_avg' : {},
'negative_actions_weighted': 0,
'wikigini': 0,
})
continue
relation = relations[revision]
# Authorship distribution.
authorship = getAuthorshipDataFromRevision(revisions[revision], order, rev_counter)
totalWordCount = len(authorship)
authDistSum = sumAuthDist(authorship)
#print "authDistSum", authDistSum
# List of editors in each order.
ordered_editors.append(relation.author)
ordered_not_vandalism.append(revision)
if (relation.author in contributors_rev.keys()):
contributors_rev[relation.author].append(revision)
else:
contributors_rev.update({relation.author : [revision]})
# Update the nodes.
if relation.author in nodes.keys():
nodes[relation.author].append(revisions[revision].id)
else:
nodes.update({relation.author : [revisions[revision].id]})
# Update the edges.
# Edges: (edge_type, editor_source, rev_source, editor_target, rev_target, weight)
edges_rev.update({revision : []})
for elem in relation.deleted.keys():
edges_rev[revision].append(("deletion", relation.author, revision, revisions[elem].contributor_name, elem, relation.deleted[elem]))
for elem in relation.reintroduced.keys():
edges_rev[revision].append(("reintroduction", relation.author, revision, revisions[elem].contributor_name, elem, relation.reintroduced[elem]))
for elem in relation.redeleted.keys():
edges_rev[revision].append(("redeletion", relation.author, revision, revisions[elem].contributor_name, elem, relation.redeleted[elem]))
for elem in relation.revert.keys():
edges_rev[revision].append(("revert", relation.author, revision, revisions[elem].contributor_name, elem, relation.revert[elem]))
# Calculate metrics.
distinct_editors = 0
deletion_edges_contributors_w = 0
deletion_sender_ratio = 0
deletion_receivers_ratio = 0
deletion_reciprocal_edges = []
deletion_reciprocity = 0
deletion_edges_total = 0
deletion_weight_avg = 0
deletion_weight = 0
bipolarity = 0
#negative_actions_weighted = 0
# Compute wikigini: V1
i = 1
res = 0
sortedAuthDistSum = sorted(authDistSum.iteritems(), key=operator.itemgetter(1))
for tup in sortedAuthDistSum:
res = res + (i * tup[1])
i = i + 1
wikiGini = ((2.0 * res)/ (len(sortedAuthDistSum) * totalWordCount)) - ((len(sortedAuthDistSum) + 1.0 ) / len(sortedAuthDistSum))
A = []
editors_window = []
R = {}
C = {}
C2 = {}
C3 = {}
W = {}
X = {}
antagonistic_focus_avg = {}
#CC = {}
window1 = len(ordered_editors)
if (len(ordered_editors) >= window):
window1 = window
if True:
deletion_sender_ratio = set([])
deletion_receivers_ratio = set([])
editors_window = list(set(ordered_editors[len(ordered_editors)-window1:]))
A = np.zeros((len(editors_window), len(editors_window)))
R = {}
C = {}
C2 = {}
C3 = {}
W = np.zeros((len(editors_window), len(editors_window)))
X = {}
target_revs = {}
for past_rev in ordered_not_vandalism[len(ordered_not_vandalism)-window1:]:
#n =
for edge_pos in range(len(edges_rev[past_rev])-1, 0-1, -1):
edge = edges_rev[past_rev][edge_pos]
(edge_type, source, _, target, rev_target, weight) = edge
if edge_type == "deletion" or edge_type == "revert":
#print "edge", past_rev, rev_target, edge_type, source, target, weight
# Checking if the target editor belongs to the window.
if (target in editors_window):
# Counts the total number of edges in the window.
deletion_edges_total = deletion_edges_total + 1
# For metric 2: ratio of number of edges e only between editors in w.
deletion_edges_contributors_w = deletion_edges_contributors_w + 1
# For metric 3: ratio of n that sent nodes at least once in w.
deletion_sender_ratio.add(source)
# For metric 6: avg. weight of the edges e in w
deletion_weight_avg = deletion_weight_avg + weight
# For metric: total negative actions (weight).
deletion_weight = deletion_weight + weight
# Update adjacency matrix
s = editors_window.index(source)
t = editors_window.index(target)
A[s][t] = A[s][t] + math.log10(1 + weight) + 1
A[t][s] = A[t][s] + math.log10(1 + weight) + 1
W[s][t] = W[s][t] + weight
#W[t][s] = W[t][s] + weight
if (s,t) in R.keys():
R[(s,t)] = R[(s,t)] + weight # + 1
else:
R.update({(s,t) : weight})#1})
if (past_rev in X.keys()):
if (target in X[past_rev].keys()):
X[past_rev][target] = X[past_rev][target] + weight
else:
X[past_rev].update({target : weight})
else:
X.update({past_rev : {target : weight}})
# For metric 4: ratio of n that received edges at least once in w.
# Checking if the target revision belongs to the window.
if (rev_target in ordered_not_vandalism[len(ordered_not_vandalism)-window1:]):
deletion_receivers_ratio.add(target)
# for metric 5: ratio of e that was reciprocal
# Don't discriminate edges that target revisions outside the window.
if ((target, source) in deletion_reciprocal_edges):
deletion_reciprocal_edges.remove((target, source))
deletion_reciprocity = deletion_reciprocity + 1
else:
deletion_reciprocal_edges.append((source, target))
# Construction of context in window.
# Iterate over each revision in the window.
for past_rev in ordered_not_vandalism[len(ordered_not_vandalism)-window1:]:
pos = ordered_not_vandalism.index(past_rev)
prev_revision = ordered_not_vandalism[pos-1]
# DETECT: UNDO of delete
# Iterate over all the words of the current processed revision.
for w in range(0, len(context[past_rev])):
word = context[past_rev][w]
for elem in word.deleted:
# If it is not "self-action".
#and prev_revision not in word.used
#if (past_rev == 15):
# print word.value, revisions[past_rev].contributor_name, revisions[elem].contributor_name
# print "elem < past_rev", elem < past_rev
# print "revisions[past_rev].contributor_name != revisions[elem].contributor_name", revisions[past_rev].contributor_name != revisions[elem].contributor_name
# print "revisions[elem].contributor_name in editors_window", revisions[elem].contributor_name in editors_window
# print "....."
if (elem < past_rev and elem in revisions.keys() and revisions[past_rev].contributor_name != revisions[elem].contributor_name) and (revisions[elem].contributor_name in editors_window) and (prev_revision not in word.used):
s = editors_window.index(revisions[past_rev].contributor_name)
t = editors_window.index(revisions[elem].contributor_name)
# Add the context for the edge (s,t).
if (s,t) not in C2.keys():
C2.update({(s,t) : {'target': elem}})
target_revs.update({(s,t) : []})
# Add the information about the context.
if (past_rev,elem) not in C2[(s,t)]:
comment = "Comment: (Empty)"
if revisions[(past_rev)].comment != None:
comment = "Comment: <i>" + revisions[past_rev].comment.encode("utf-8") + "</i>"
#C2[(s,t)].update({(past_rev,elem) : ["<a target=_blank href=http://en.wikipedia.org/w/index.php?&diff=" + str(past_rev) + "> [Undo of Deletion] " + revisions[past_rev].contributor_name + "->" + revisions[elem].contributor_name + ". Revision: " + str(past_rev) +". " + comment + "</a>" ]})
C2[(s,t)].update({(past_rev,elem) : ["<a target=_blank href=http://en.wikipedia.org/w/index.php?&diff=" + str(past_rev) + "> [Undo of Deletion] " + revisions[past_rev].contributor_name + "(" + str(past_rev) + ")->" + revisions[elem].contributor_name + "(" + str(elem) +"). " + comment + "</a>" ]})
if (True):
# If the word is not in the context: add it.
if word not in C2[(s,t)][(past_rev,elem)]:
#target_revs[(s,t)].append(word.revision)
# Add new line if this sentence is a new one in the context.
try:
if context[(past_rev)][w-1] not in C2[(s,t)][(past_rev,elem)]:
C2[(s,t)][(past_rev,elem)].append("<br />")
except:
pass
# Add 4 tokens of pre-context.
for i in range(4,0,-1):
try:
if w-i >= 0 and context[(past_rev)][w-i] not in C2[(s,t)][(past_rev,elem)]:
C2[(s,t)][(past_rev,elem)].append(context[(past_rev)][w-i])
#C[(t,s)][past_rev].append(context[prev_revision][w-i])
#if past_rev == 82285999:
# print "w-i", context[prev_revision][w-i], context[prev_revision][w-i].value
except:
pass
# Append the word.
C2[(s,t)][(past_rev,elem)].append(word)
# Add 4 tokens of post-context.
for i in range(1,5):
try:
if context[(past_rev)][w+i] not in C2[(s,t)][(past_rev,elem)]:
C2[(s,t)][(past_rev,elem)].append(context[(past_rev)][w+i])
except:
pass
# If the word is already in context: add post-context.
else:
# Add 4 tokens of post-context.
for i in range(1,5):
try:
if context[(past_rev)][w+i] not in C2[(s,t)][(past_rev)]:
C2[(s,t)][(past_rev,elem)].append(context[(past_rev)][w+i])
except:
pass
# DETECT: UNDO of re-introduction.
# Iterate over all the words of the immediate previous revision.
for w in range(0, len(context[prev_revision])):
word = context[prev_revision][w]
if past_rev not in word.deleted:
continue
for elem in word.freq:
# If it is not "self-delete".
if elem < past_rev and revisions[past_rev].contributor_name != revisions[elem].contributor_name and revisions[elem].contributor_name in editors_window:
s = editors_window.index(revisions[past_rev].contributor_name)
t = editors_window.index(revisions[elem].contributor_name)
# Add the context for the edge (s,t).
if (s,t) not in C3.keys():
C3.update({(s,t) : {'target': elem}})
#target_revs.update({(s,t) : []})
# Add the information about the context.
if (past_rev,elem) not in C3[(s,t)]:
comment = "Comment: (Empty)"
if revisions[past_rev].comment != None:
comment = "Comment: <i>" + revisions[past_rev].comment.encode("utf-8") + "</i>"
#C3[(s,t)].update({(past_rev,elem) : ["<a target=_blank href=http://en.wikipedia.org/w/index.php?&diff=" + str(past_rev) + "> [Undo of Re-introduction] " + revisions[past_rev].contributor_name + "->" + revisions[elem].contributor_name + ". Revision: " + str(past_rev) +". " + comment + "</a>" ]})
C3[(s,t)].update({(past_rev,elem) : ["<a target=_blank href=http://en.wikipedia.org/w/index.php?&diff=" + str(past_rev) + "> [Undo of Re-introduction] " + revisions[past_rev].contributor_name + "(" + str(past_rev) + ")"+ "->" + revisions[elem].contributor_name + "(" + str(elem) + ")" +". " + comment + "</a>" ]})
if (True):
# If the word is not in the context: add it.
if word not in C3[(s,t)][(past_rev,elem)]:
#target_revs[(s,t)].append(word.revision)
# Add new line if this sentence is a new one in the context.
try:
if context[(prev_revision)][w-1] not in C3[(s,t)][(past_rev,elem)]:
C3[(s,t)][(past_rev,elem)].append("<br />")
except:
pass
# Add 4 tokens of pre-context.
for i in range(4,0,-1):
try:
if w-i >= 0 and context[(prev_revision)][w-i] not in C3[(s,t)][(past_rev,elem)]:
C3[(s,t)][(past_rev,elem)].append(context[prev_revision][w-i])
#C[(t,s)][past_rev].append(context[prev_revision][w-i])
#if past_rev == 82285999:
# print "w-i", context[prev_revision][w-i], context[prev_revision][w-i].value
except:
pass
# Append the word.
C3[(s,t)][(past_rev,elem)].append(word)
# Add 4 tokens of post-context.
for i in range(1,5):
try:
if context[prev_revision][w+i] not in C3[(s,t)][(past_rev,elem)]:
C3[(s,t)][(past_rev,elem)].append(context[prev_revision][w+i])
except:
pass
# If the word is already in context: add post-context.
else:
# Add 4 tokens of post-context.
for i in range(1,5):
try:
if context[prev_revision][w+i] not in C3[(s,t)][(past_rev,elem)]:
C3[(s,t)][(past_rev,elem)].append(context[prev_revision][w+i])
except:
pass
# DETECT: DELETION
# Iterate over all the words of the immediate previous revision.
for w in range(0, len(context[prev_revision])):
word = context[prev_revision][w]
# If the word will be deleted in the window: detect deletion edge (s,t)
if (past_rev in word.deleted and word.author_name in editors_window):
s = editors_window.index(revisions[past_rev].contributor_name)
t = editors_window.index(word.author_name)
# If it is not "self-delete".
if revisions[past_rev].contributor_name != word.author_name:
# Add the context for the edge (s,t).
if (s,t) not in C.keys():
C.update({(s,t) : {'target': word.author_name}})
#target_revs.update({(s,t) : []})
# Add the information about the context.
if past_rev not in C[(s,t)]:
comment = "Comment: (Empty)"
if revisions[past_rev].comment != None:
comment = "Comment: <i>" + revisions[past_rev].comment.encode("utf-8") + "</i>"
#C[(s,t)].update({past_rev : ["<a target=_blank href=http://en.wikipedia.org/w/index.php?&diff=" + str(past_rev) + "> [Deletion] " + revisions[past_rev].contributor_name + "->" + word.author_name + ". Revision: " + str(past_rev) +". " + comment + "</a>" ]})
C[(s,t)].update({past_rev : ["<a target=_blank href=http://en.wikipedia.org/w/index.php?&diff=" + str(past_rev) + "> [Deletion] " + revisions[past_rev].contributor_name + "(" + str(past_rev) + ")->" + word.author_name +"(" + str(prev_revision) + "). " + comment + "</a>" ]})
if (True):
# If the word is not in the context: add it.
if word not in C[(s,t)][past_rev]:
#target_revs[(s,t)].append(word.revision)
# Add new line if this sentence is a new one in the context.
try:
if context[prev_revision][w-1] not in C[(s,t)][past_rev]:
C[(s,t)][past_rev].append("<br />")
except:
pass
# Add 4 tokens of pre-context.
for i in range(4,0,-1):
try:
if w-i >= 0 and context[prev_revision][w-i] not in C[(s,t)][past_rev]:
C[(s,t)][past_rev].append(context[prev_revision][w-i])
#C[(t,s)][past_rev].append(context[prev_revision][w-i])
#if past_rev == 82285999:
# print "w-i", context[prev_revision][w-i], context[prev_revision][w-i].value
except:
pass
# Append the word.
C[(s,t)][past_rev].append(word)
# Add 4 tokens of post-context.
for i in range(1,5):
try:
if context[prev_revision][w+i] not in C[(s,t)][past_rev]:
C[(s,t)][past_rev].append(context[prev_revision][w+i])
except:
pass
# If the word is already in context: add post-context.
else:
# Add 4 tokens of post-context.
for i in range(1,5):
try:
if context[prev_revision][w+i] not in C[(s,t)][past_rev]:
C[(s,t)][past_rev].append(context[prev_revision][w+i])
except:
pass
# Print the context for DELETE.
for (s,t) in C.keys():
target = C[(s,t)]['target']
del C[(s,t)]['target']
for r in C[(s,t)].keys():
info = ""
if (r in X.keys() and target in X[r].keys()):
info = "<b>Disagreement focus:</b> " + str(X[r][target] / float(sum(X[r].values()))) + "<br /><br />"
if ((s,t) in antagonistic_focus_avg.keys()):
antagonistic_focus_avg[(s,t)].append(X[r][target] / float(sum(X[r].values())))
else:
antagonistic_focus_avg.update({(s,t): [X[r][target] / float(sum(X[r].values()))]})
C[(s,t)].update({r : [info + printDeleteContext(C[(s,t)][r], r, target)]})
# Print the context for UNDO of delete.
for (s,t) in C2.keys():
#target = C2[(s,t)]['target']
del C2[(s,t)]['target']
for (r,r2) in C2[(s,t)].keys():
target = r2
info = ""
if (r in X.keys() and revisions[target].contributor_name in X[r].keys()):
# #print "X keys", X.keys(), "X[r] keys", r, target, X[r].keys(), X[r].values()
info = "<b>Disagreement focus:</b> " + str(X[r][revisions[target].contributor_name] / float(sum(X[r].values()))) + "<br /><br />"
if ((s,t) in antagonistic_focus_avg.keys()):
antagonistic_focus_avg[(s,t)].append(X[r][revisions[target].contributor_name] / float(sum(X[r].values())))
else:
antagonistic_focus_avg.update({(s,t): [X[r][revisions[target].contributor_name] / float(sum(X[r].values()))]})
#if past_rev == 9:
# print "X", X, "info", info, "r", r, "target", target
if (s,t) in C.keys():
if (r in C[(s,t)].keys()):
C[(s,t)][r].append(printUndoOfDeletionContext(C2[(s,t)][(r,r2)], r, target))
else:
C[(s,t)].update({r : [info + printUndoOfDeletionContext(C2[(s,t)][(r,r2)], r, target)]})
else:
C.update({(s,t) : {r : [info + printUndoOfDeletionContext(C2[(s,t)][(r,r2)], r, target)]}})
# Print the context for UNDO of re-introduction.
for (s,t) in C3.keys():
#target = C3[(s,t)]['target']
del C3[(s,t)]['target']
for (r,r2) in C3[(s,t)].keys():
target = r2
info = ""
if (r in X.keys() and revisions[target].contributor_name in X[r].keys()):
# #print "X keys", X.keys(), "X[r] keys", r, target, X[r].keys(), X[r].values()
info = "<b>Disagreement focus:</b> " + str(X[r][revisions[target].contributor_name] / float(sum(X[r].values()))) + "<br /><br />"
if ((s,t) in antagonistic_focus_avg.keys()):
antagonistic_focus_avg[(s,t)].append(X[r][revisions[target].contributor_name] / float(sum(X[r].values())))
else:
antagonistic_focus_avg.update({(s,t): [X[r][revisions[target].contributor_name] / float(sum(X[r].values()))]})
#if past_rev == 9:
# print "X", X, "info", info, "r", r, "target", target
if (s,t) in C.keys():
if (r in C[(s,t)].keys()):
C[(s,t)][r].append(printUndoOfReintroductionContext(C3[(s,t)][(r,r2)], r, target))
else:
C[(s,t)].update({r : [info + printUndoOfReintroductionContext(C3[(s,t)][(r,r2)], r, target)]})
else:
C.update({(s,t) : {r : [info + printUndoOfReintroductionContext(C3[(s,t)][(r,r2)], r, target)]}})
# 1: Number of distinct editors n that edited in window1.
distinct_editors = len(set(ordered_editors[len(ordered_editors)-window1:]))
# 2: Ratio of # of edges e only between editors in w
deletion_edges_contributors_w = deletion_edges_contributors_w / float(distinct_editors)
# 3: Ratio of n that sent edges at least once in w
deletion_sender_ratio = len(deletion_sender_ratio) / float(distinct_editors)
# 4: Ratio of n that received edges at least once in w
deletion_receivers_ratio = len(deletion_receivers_ratio) / float(distinct_editors)
if (deletion_edges_total != 0):
# 5: Ratio of e that was reciprocal
deletion_reciprocity = deletion_reciprocity / float((deletion_edges_total / 2.0))
# 6: Average weight of the edges e in w
deletion_weight_avg = deletion_weight_avg / float(deletion_edges_total)
else:
deletion_reciprocity = 0
deletion_weight_avg = 0
#print "A before", A
# Update the reciprocity on the weights of the adjacency matrix.
for (s_index, t_index) in R.keys():
#print "s_index", s_index, "t_index", t_index, R
#if ((t_index, s_index) in R.keys()):
# reciprocity = min(R[(s_index, t_index)], R[(t_index, s_index)])
#else:
# reciprocity = 0
A[s_index][t_index] = A[s_index][t_index] #+ (2*reciprocity)
A[t_index][s_index] = A[t_index][s_index] #+ (2*reciprocity)
eigenvalues, _ = np.linalg.eig(A)
lambda_max = max(eigenvalues)
lambda_min = min(eigenvalues)
bipolarity = 0
if (lambda_max != 0):
bipolarity = -lambda_min / lambda_max
bipolarity = bipolarity.real
#print "bipolarity", bipolarity, "lambda_min", lambda_min, "lambda_max", lambda_max
#print "bipolarity", bipolarity
#print "A after", A
# antagonized_editors: Revert actions + delete actions in revision (distinct editors)
antagonized_editors = set([])
for elem in relation.revert.keys():
antagonized_editors.add(revisions[elem].contributor_id)
for elem in relation.deleted.keys():
antagonized_editors.add(revisions[elem].contributor_id)
all_antagonized_editors.append(len(antagonized_editors))
antagonized_editors_avg_w1 = 0
if (len(all_antagonized_editors) >= window1):
antagonized_editors_avg_w1 = sum(all_antagonized_editors[len(all_antagonized_editors)-window1:]) / float(window1)
# supported_editors: reintroductions + redeletes (distinct editors)
supported_editors = set([])
for elem in relation.reintroduced.keys():
supported_editors.add(revisions[elem].contributor_id)
for elem in relation.redeleted.keys():
supported_editors.add(revisions[elem].contributor_id)
all_supported_editors.append(len(supported_editors))
supported_editors_avg_w1 = 0
if (len(all_supported_editors) >= window1):
supported_editors_avg_w1 = sum(all_supported_editors[len(all_supported_editors)-window1:]) / float(window1)
statsData.append({'revision': revision,
'author': revisions[revision].contributor_name,
'distinct_editors': distinct_editors,
'deletion_edges_contributors_w': deletion_edges_contributors_w,
'deletion_sender_ratio': deletion_sender_ratio,
'deletion_receiver_ratio': deletion_receivers_ratio,
'deletion_reciprocity': deletion_reciprocity,
'deletion_weight_avg': deletion_weight_avg,
'deletion_weight': deletion_weight,
'antagonized_editors_avg_w1': antagonized_editors_avg_w1,
'supported_editors_avg_w1': supported_editors_avg_w1,
'bipolarity' : bipolarity,
'adjacency_matrix' : (A, editors_window, authDistSum, totalWordCount),
'reciprocity_matrix' : R,
'weight_matrix' : W,
'context' : C,
'antagonistic_focus_avg' : antagonistic_focus_avg,
'wikigini' : wikiGini})
#for r in context.keys():
# print "-----"
# print r
# for w in context[r]:
# print w.value
return statsData
def sumAuthDist(authors):
wordCount = {}
for author in authors:
if(author in wordCount.keys()):
wordCount[author] = wordCount[author]+1
else:
wordCount[author] = 1
return wordCount
def getAuthorshipDataFromRevision(revision, order, rev):
#print "Printing authorship for revision: ", revision.wikipedia_id, rev
#text = []
authors = []
(rev_id, _) = order[rev]
#global context_obj
global context
context.update({rev_id: []})
for hash_paragraph in revision.ordered_paragraphs:
p_copy = deepcopy(revision.paragraphs[hash_paragraph])
paragraph = p_copy.pop(0)
for hash_sentence in paragraph.ordered_sentences:
sentence = paragraph.sentences[hash_sentence].pop(0)
for i in range(0, len(sentence.words)):
word = sentence.words[i]
#word in sentence.words:
#text.append(word.value)
authors.append(word.author_name)
context[rev_id].append(word)
#context[rev_id].append(word)
return authors
def printDeleteContext(cc, rev, target_revs):#, source):
mystr = ""
for w in cc:
if isinstance(w, Word):
#if rev == 82784338:
# print w.value, "w.author_name", w.author_name, "target_revs", target_revs, "rev", rev, "w.deleted", w.deleted
if (w.author_name == target_revs and rev in w.deleted):
mystr = mystr + " <b><span class='text-danger'>" + cgi.escape(w.value) + "</span></b> " # + "@"+ w.author_name + "</b> "
else:
mystr = mystr + " " + cgi.escape(w.value) # + "@"+ w.author_name
#if ((w.revision in cc['revs']) and (source in w.deleted)):
# mystr = mystr + " <b>" + w.value + "</b> "# + "$"+ str(id(w)) + "</b> "
#else:
# mystr = mystr + " " + w.value #+ "$"+ str(id(w))
else:
mystr = mystr + " " + w
mystr = mystr.replace('"', '"')
return mystr
def printUndoOfDeletionContext(cc, rev, target_revs):#, source):
mystr = ""
for w in cc:
if isinstance(w, Word):
#if (rev == 143602582):
# print "w.value", w.value, "target_revs", target_revs, "w.deleted", w.deleted
if (target_revs in w.deleted):
mystr = mystr + " <b><span class='text-success'>" + cgi.escape(w.value) + "</span></b> " # + "@"+ w.author_name #+ "</b> "
else:
mystr = mystr + " " + cgi.escape(w.value) # + "@"+ w.author_name
else:
mystr = mystr + " " + w
mystr = mystr.replace('"', '"')
return mystr
def printUndoOfReintroductionContext(cc, rev, target_revs):#, source):
mystr = ""
for w in cc:
if isinstance(w, Word):
if (target_revs in w.freq and rev in w.deleted):
mystr = mystr + " <b><span class='text-danger'>" + cgi.escape(w.value) + "</span></b> " # + "@"+ w.author_name + "</b> "
else:
mystr = mystr + " " + cgi.escape(w.value) # + "@"+ w.author_name
else:
mystr = mystr + " " + w
mystr = mystr.replace('"', '"')
return mystr
def printContext(source, target):
global context
#print context
full_str = ""
#for (source, target) in context.keys():
if True:
#print
sentences = context[(source, target)]
mystr = ""
for s in sentences:
for w in s:
if (w.revision == target and source in w.deleted):
mystr = mystr + " <b>" + w.value + "$"+ str(id(w)) + "</b> "
else:
mystr = mystr + " " + w.value + "$"+ str(id(w))
#print mystr
full_str = full_str + "<br />" + mystr
mystr= ""
full_str = full_str.replace('"', '"')
return full_str
def printForD3(v, e, etype):
v_dict = {}
v_str = []
e_str = []
max_weight = 0
for edge in e:
((source, target), edge_type, weight) = edge
if (weight > max_weight):
max_weight = weight
for edge in e:
((source, target), edge_type, weight) = edge
if (edge_type == etype):
if (source not in v_dict.keys()):
v_dict.update({source : len(v_str)})
v_str.append("{\"name\": \"" + source + "\", \"group\":1}")
if (target not in v_dict.keys()):
v_dict.update({target : len(v_str)})
v_str.append("{\"name\": \"" + target + "\", \"group\":1}")
force = weight
e_str.append("{\"source\":" + str(v_dict[source]) + ", \"target\":" + str(v_dict[target]) + ", \"value\":"+ str(force) + "}")
print "graph={" + "\"nodes\": [" + ','.join(v_str) + "], \"links\": [" + ','.join(e_str) + "]}"
def printTimeForD3(v, e, etype, graph):
v_dict = {}
print "graph={"
count = 0
for rev in graph.keys():
v_str = []
e_str = []
for edge in graph[rev]['links']:
(edge_type, source, target, weight) = edge
if (edge_type == etype):
if (source not in v_dict.keys()):
v_dict.update({source : len(v_str)})
v_str.append("{\"name\": \"" + source + "\", \"group\":1}")
if (target not in v_dict.keys()):
v_dict.update({target : len(v_str)})
v_str.append("{\"name\": \"" + target + "\", \"group\":1}")
force = weight
e_str.append("{\"source\":" + str(v_dict[source]) + ", \"target\":" + str(v_dict[target]) + ", \"value\":"+ str(force) + "}")
print str(count) + ": {" + "\"nodes\": [" + ','.join(v_str) + "], \"links\": [" + ','.join(e_str) + "]},"
count = count + 1
print "}"
def printSnapshotsForD3(v, e, etype, graph):
v_dict = {}
v_str = []
e_str = []
print "graph={"
count = 0
for rev in graph.keys():
for edge in graph[rev]['links']:
(edge_type, source, target, weight) = edge
if (edge_type == etype):
if (source not in v_dict.keys()):
v_dict.update({source : len(v_str)})
v_str.append("{\"name\": \"" + source + "\", \"group\":1}")
if (target not in v_dict.keys()):
v_dict.update({target : len(v_str)})
v_str.append("{\"name\": \"" + target + "\", \"group\":1}")
force = weight
e_str.append("{\"source\":" + str(v_dict[source]) + ", \"target\":" + str(v_dict[target]) + ", \"value\":"+ str(force) + "}")
print str(count) + ": {" + "\"nodes\": [" + ','.join(v_str) + "], \"links\": [" + ','.join(e_str) + "]},"
count = count + 1
print "}"
def printForNeo4J(g, v, e):
code = []
article_tpl = "(%article_id%:ARTICLE {title: '%article%'})"
vertex_tpl = "(%editor%:EDITOR {name: '%editor%'})"
edge_tpl = "(%source%)-[:%edge_type% {weight: %weight%}]->(%target%)"
edge_article_tpl = "(%source%)-[:EDITED_BY {revisions:%revisions%}]->(%target%)"
# Create edges to article.
instance = article_tpl
instance = instance.replace("%article%", g.encode("utf-8"))
instance = instance.replace("%article_id%", g.encode("utf-8").replace(" ", "_"))
code.append(instance)
# Create nodes.
for vertex in v.keys():
instance = vertex_tpl
instance = instance.replace("%editor%", vertex.encode("utf-8"))
code.append(instance)
instance = edge_article_tpl
instance = instance.replace("%source%", g.encode("utf-8").replace(" ", "_"))
instance = instance.replace("%target%", vertex.encode("utf-8"))
instance = instance.replace("%revisions%", str(v[vertex]))
code.append(instance)
# Create edges.
for edge in e:
((source, target), edge_type, weight) = edge
instance = edge_tpl
instance = instance.replace("%source%", source.encode("utf-8"))
instance = instance.replace("%edge_type%", edge_type.upper())
instance = instance.replace("%weight%", str(weight))
instance = instance.replace("%target%", target.encode("utf-8"))
code.append(instance)
print "CREATE " + ",\n".join(code)
def printStats(stats, reciprocity):
# Stats to print
finalStats = []
# Stats per revisions
#distinct_editors = []
#deletion_edges_contributors_w = []
#deletion_outgoing_ratio = []
#deletion_incoming_ratio = []
deletion_reciprocity = []
#deletion_weight_avg = []
deletion_weight = []
#antagonized_editors_avg_w1 = []
#supported_editors_avg_w1 = []
bipolarity = []
weighted_reciprocity = []
wikigini = []
count = 0
total_negative_actions = []
#print "CHECK", len(stats), len(reciprocity)
#for elem in reciprocity
for elem in stats:
total_negative_actions.append(elem['deletion_weight'])
#print "total", total_negative_actions
max_total_negative_actions = max(total_negative_actions)
max_reciprocity = max(reciprocity)
#print "max", max_total_negative_actions
for i in range (0, len(stats)):
elem = stats[i]
elem2 = reciprocity[i]
#distinct_editors.append({"x": count, "y": elem['distinct_editors'], "z": elem["revision"]})
#deletion_edges_contributors_w.append({"x": count, "y": elem['deletion_edges_contributors_w'], "z": elem["revision"]})
#deletion_outgoing_ratio.append({"x": count, "y": elem['deletion_sender_ratio'], "z": elem["revision"]})
#deletion_incoming_ratio.append({"x": count, "y": elem['deletion_receiver_ratio'], "z": elem["revision"]})
#deletion_reciprocity.append({"Revision": count, "Value": elem['deletion_reciprocity'], "Wikipedia Revision": elem["revision"], "Metric": "Disagreement Reciprocity"})
#deletion_weight_avg.append({"x": count, "y": elem['deletion_weight_avg'], "z": elem["revision"]})
#antagonized_editors_avg_w1.append({"x": count, "y": elem['antagonized_editors_avg_w1'], "z": elem["revision"]})
#supported_editors_avg_w1.append({"x": count, "y": elem['supported_editors_avg_w1'], "z": elem["revision"]})
weighted_reciprocity.append({"Revision": count, "Value": elem2/float(max_reciprocity), "Wikipedia Revision": elem["revision"], "Metric": "Reciprocity"})
bipolarity.append({"Revision": count, "Value": elem['bipolarity'], "Wikipedia Revision": elem["revision"], "Metric": "Bipolarity"})
wikigini.append({"Revision": count, "Value": elem['wikigini'], "Wikipedia Revision": elem["revision"], "Metric": "Authorship Gini"})
deletion_weight.append({"Revision": count, "Value": elem['deletion_weight']/float(max_total_negative_actions), "Wikipedia Revision": elem["revision"], "Metric": "Number of Disagreement Actions (Normalized)"})
count = count + 1
#serie1 = {"key" : "No. Distinct Editors in w (w=20)", "values": distinct_editors}