-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgraph-attack-pprl.py
More file actions
7911 lines (6093 loc) · 322 KB
/
graph-attack-pprl.py
File metadata and controls
7911 lines (6093 loc) · 322 KB
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
# graph-attack-pprl.py - Implementation of a graph alignment based attack
# on a data set encoded for PPRL. The attack aims to identify similar nodes
# across two similarity graphs, one based on the comparison of plain-text
# values while the other is based on the comparison of encoded values. For
# both graphs nodes represent records while edges represent the similarities
# between these records.
#
# Graphs are saved into binary pickle files, and if available these files will
# be used instead of re-calculated
#
# Graph features are also saved into csv files, and if available these files will
# be used instead of re-calculated
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Description of the main steps of the approach and corresponding functions
# used (also see the code in the main program towards the end of the program):
#
# 1) Load the files to be used as plain-text and encoded data sets - if both
# file names are the same we use this file both as plain-text and encoded
# data set (i.e. known plain-text attack).
# Function: load_data_set()
#
# 2) Convert the data set(s) into q-gram sets (one per record).
# Function: gen_q_gram_sets()
#
# 3) Encode the second data set into a encoding (currently either
# Bloom filters, BFs, Duncan Smith's tabulation min-hash, TMH,
# approach, or Ranbaduge's Two-step hashing approach).
# Any other encoding can be used where approximate similarities
# between encodings can be calculated.
# Function: uses modules hashing.py (for BF), tabminhash.py (for TMH)
# or colminhash.py (for 2SH)
#
# 4) Generate two similarity graphs, one by calculating similarities between
# q-gram sets (plain-text similarity graph), the other by calculating
# similarities between encodings (encoded similarity graph). To prevent
# full pair-wise comparison between all records in a data set we use
# min-hashing LSH on the q-gram sets.
#
# 5) To identify the differences between plain-text and encoded similarities,
# assuming we do know the ground truth (which pairs of encodings correspond
# to which q-gram set pairs), we can calculate similarity differences and
# use these differences in a regression model to adjust the encoded similarities
# to what they should have been if they would correspond to q-gram pairs.
# If this step is done then we can adjust either the encoded or plaintext
# similarities accordingly before they are inserted into the similarity graphs.
#
# 6) We get the summary characteristics of the two graphs for different
# minimum similarities.
# Function: show_graph_characteristics()
#
# 7) We save the two graphs into two pickle (binary) files.
# Function: networkx.write_gpickle()
# Note that step 3) to 6) are only done if the corresponding pickle files are
# not available, if they are we skip steps 3) to 6) and instead load these
# pickle files. Function: networkx.read_gpickle()
#
# The attack phase starts here (in the code several nested loops iterate over
# the different parameter settings provided at the beginning of the program
# (i.e. many different attacks are conducted on the two similarity graphs):
#
# 8) To limit the attack to nodes (records) that have information about their
# graph neighbours, remove all connected components in the graph that
# contain less that a certain minimum number of nodes.
# Function: gen_min_conn_comp_graph()
#
# 9) Generate the features where for each node in a similarity graph a feature
# vector is calculated.
# Function: calc_features()
#
# 10) Normalise all features into the [0,1] interval, because the sim-hash
# approach uses random vectors where each element is in the range [0,1].
# Function: norm_features_01()
#
# 11) Apply a possible feature selection: all, only those with non-zero
# values, or those with the highest variance.
# Functions: get_std_features() and select_features()
#
# 12) Because we aim to have 1-to-1 matching nodes across the two graphs,
# remove all feature vectors that occur more than once.
# Function: remove_freq_feat_vectors()
#
# 13) Generate the sim-hashes for all feature vectors, i.e. one binary vector
# representing each numerical feature vector.
# Function: see class CosineLSH
#
# 14) As blocking on these bit arrays either compare all bit array pairs or
# use Hamming LSH.
# Functions: all_in_one_blocking() and hlsh_blocking()
#
# 15) Compare the encodings across the two graphs and only keep those pairs
# with a high similarity. Either compare all pairs (coming out of the
# previous blocking step) or only those pairs where their edge with the
# highest similarity is comparable, and also their total numbers of edges
# are comparable.
# Functions: calc_cos_sim_all_pairs() and calc_cos_sim_edge_comp()
#
# 16) For the compared bit-array pairs with high similarities finally
# calculate their actual Cosine similarity using their actual feature
# vectors. Then sort the resulting pairs according to their similarities
# with highest first, and report how many in the top 10, 20, 50, 100 and
# all, are correct matches (i.e. a feature vector from the plain-text data
# set was correctly matched with a feature vector from the encoded data
# set).
#
#
# Anushka Vidanage, Peter Christen, Thilina Ranbaduge, Rainer Schnell
# July 2020
#
# Usage: python graph-attack-pprl.py [encode_data_set_name] [encode_ent_id_col]
# [encode_col_sep_char] [encode_header_line_flag]
# [encode_attr_list] [encode_num_rec]
# [plain_data_set_name] [plain_ent_id_col]
# [plain_col_sep_char] [plain_header_line_flag]
# [plain_attr_list] [plain_num_rec]
# [q] [padded_flag]
# [plain_sim_funct_name]
# [sim_diff_adjust_flag]
# [encode_sim_funct_name]
# [encode_method] {encode_method_param}
#
# where:
#
# encode_data_set_name is the name of the CSV file to be encoded into BFs.
# encode_ent_id_col is the column in the CSV file containing entity
# identifiers.
# encode_col_sep_char is the character to be used to separate fields in
# the encode input file.
# encode_header_line_flag is a flag, set to True if the file has a header
# line with attribute (field) names.
# encode_attr_list is the list of attributes to encode and use for
# the linkage.
# encode_num_rec is the number of records to be loaded from the data
# set, if -1 then all records will be loaded,
# otherwise the specified number of records (>= 1).
#
# plain_data_set_name is the name of the CSV file to use plain text
# values from.
# plain_ent_id_col is the column in the CSV file containing entity
# identifiers.
# plain_col_sep_char is the character to be used to separate fields in
# the plain text input file.
# plain_header_line_flag is a flag, set to True if the file has a header
# line with attribute (field) names.
# plain_attr_list is the list of attributes to get values from to
# guess if they can be re-identified.
# plain_num_rec is the number of records to be loaded from the data
# set, if -1 then all records will be loaded,
# otherwise the specified number of records (>= 1).
#
# q is the length of q-grams to use when converting
# values into q-gram set.
# padded_flag if set to True then attribute values will be padded
# at the beginning and end, otherwise not.
#
# plain_sim_funct_name is the function to be used to calculate similarities
# between plain-text q-gram sets. Possible values are
# 'dice' and 'jacc'.
# sim_diff_adjust_flag is a flag, if set to True then the encoded
# similarities will be adjusted based on calculated
# similarity differences of true matching edges
# between plain-text and encoded similarities.
# encode_sim_funct_name is the function to be used to calculate similarities
# between encoded values (such as bit-arrays).
# Possible values are 'dice', 'hamm', and 'jacc'.
#
# encode_method is the method to be used to encode values from the
# encoded data set (assuming these have been converted
# into q-gram sets). Possible are: 'bf' (Bloom filter
# encoding) or 'tmh' (tabulation min hash encoding) or
# '2sh' (two-step hash encoding).
# encode_method_param A set of parameters that depend upon the encoding
# method.
# For Bloom filters, these are:
# - bf_hash_type is either DH (double-hashing)
# or RH (random hashing).
# - bf_num_hash_funct is a positive number or 'opt'
# (to fill BF 50%).
# - bf_len is the length of Bloom filters.
# - bf_encode is the Bloom filter encoding method.
# can be 'clk', 'abf', 'rbf-s', or
# 'rbf-d'
# - bf_harden is either None, 'balance' or
# or 'fold' for different BF
# hardening techniques.
# - bf_enc_param parameters for Bloom filter encoding
# method
# For tabulation min-hashing, these are:
# - tmh_num_hash_bits The number of hash bits to
# generate per encoding.
# - tmh_hash_funct is the actual hash function to
# use. Possible values are:
# 'md5', 'sha1', and 'sha2'.
# - tmh_num_tables is the number of tabulation
# hash tables to be generated.
# - tmh_key_len is the length of the keys into
# these tables.
# - tmh_val_len is the length of the random bit
# strings to be generated for
# each table entry.
# For two-step hash encoding, these are:
# - cmh_num_hash_funct The number of hash functions to
# be considered.
# - cmh_num_hash_col is the length of the generated
# encodings (number of random integers
# per encoding)
# - cmh_max_rand_int maximum integer value to select the
# random integers
#
#
#
# Some example calls:
#
# python graph-attack-pprl.py euro-census.csv 0 , True [1,2,8] -1 euro-census.csv 0 , True [1,2,8] -1 2 False dice True bf rh 15 1000 clk none None dice
#
# python graph-attack-pprl4.py euro-census.csv 0 , True [1,2,8] -1 euro-census.csv 0 , True [1,2,8] -1 2 False dice True bf rh 15 1000 rbf-s none [0.2,0.3,0.5] dice
#
# python graph-attack-pprl4.py euro-census.csv 0 , True [1,2,8] -1 euro-census.csv 0 , True [1,2,8] -1 2 False jacc True tmh 1000 sha2 8 8 64 jacc
#
# python graph-attack-pprl4.py euro-census.csv 0 , True [1,2,8] -1 euro-census.csv 0 , True [1,2,8] -1 2 False jacc True 2sh 15 1000 100000 jacc
#
# -----------------------------------------------------------------------------
# The actual parameters for the graph attack are set below - once the
# plain-text and encoded similarity graphs have been generated (or loaded from
# pickled files) they can be matched using various settings for the following
# parameters:
#
# graph_node_min_degr is the minimum degree (number of neighbours) a node in
# the graph needs to be considered in the graph matching.
# graph_sim_list is the list of similarity values to be used when
# generating the features for the graph. The minimum
# similarity value is also used to decide what edges not
# to include in the graph (those below that minimum
# similarity).
# graph_feat_list is the features to be used to characterise the nodes in
# a graph.
# graph_feat_select is the method to select features based on their
# variance. Possible values are 'all', 'nonzero', k (an
# integer, in which case the top k features will be
# selected), or f (a floating-point number, in which case
# features with at least this standard deviation will be
# selected).
#
# sim_hash_num_bit is the number of bits to be used when generating
# Cosine LSH bit arrays from the feature arrays
# sim_hash_match_sim is the minimum similarity for two records to be
# considered a match across the two graphs.
# sim_hash_block_funct is the method used for blocking the similarity hash
# dictionaries, can be one of 'all_in_one' (one block
# with all records from a data set) or 'hlsh' (apply
# Hamming LSH).
# sim_comp_funct is the way similarity hashes are compared, this can
# 'allpairs' (all pairs - based on blocking) or
# 'simwindow' (only pairs with similar highest edges
# and similar numbers of edges).
#
# Several attacks can be conducted on the two graphs with different parameter
# settings - the full combination of the following settings will be run (so be
# careful of the number of settings per parameter)
#
# For each setting provide a name as key and then its parameter values as a
# list or dictionary
#
# Set the graph generation parameters depending upon data sets used
#
import sys
import sklearn
encode_data_set_name = sys.argv[1]
if ('passenger' in encode_data_set_name): # Titanic names
soundex_attr_list = [2] # 2, 3
graph_sim_list = [('[0.2]',[0.2])] #('[0.9-0.5]',[0.9,0.7,0.5]),
#('[0.5]',[0.5])
# Important: this needs to be smallest first because connected components
# smaller than a (minimum degree+1) are removed from the input graph
#
graph_node_min_degr_list = [('5',5)]
sim_hash_match_sim = 0.9
sim_hash_num_bit_list = [('500',500)] #('1000',1000), ('500',500), ('100',100)
sim_hash_block_funct_list = ['all_in_one'] # 'all_in_one','hlsh'
sim_comp_funct_list = ['allpairs'] # 'allpairs', 'simtol'
graph_feat_list_list = [('all',['node_freq','max_sim','min_sim','degree',
'degree_histo1','degree_histo2','sim_avr',
'sim_std','egonet_degree','egonet_density',
#'pagerank', # very time consuming
'between_central',
#'closeness_central', # very time consuming
'degree_central',
#'eigenvec_central', # very time consuming
]),
('no-histo',['node_freq','max_sim','min_sim','degree',
'sim_avr', 'sim_std','egonet_degree',
'egonet_density','between_central',
'degree_central', 'eigenvec_central',
]),
('one-central',['node_freq','max_sim','min_sim','degree',
'degree_histo1', 'degree_histo2', 'sim_avr',
'sim_std','egonet_degree', 'egonet_density',
'degree_central',
]),
('no-nf-central',['max_sim','min_sim','degree',
'degree_histo1','degree_histo2',
'sim_avr','sim_std',
'egonet_degree','egonet_density']),
('no-central',['node_freq','max_sim','min_sim',
'degree','degree_histo1',
'degree_histo2','sim_avr','sim_std',
'egonet_degree','egonet_density']),
('node2vec', ['node2vec']),
]
elif ('titanic' in encode_data_set_name): # Titanic names
soundex_attr_list = [2] # 2, 1
graph_sim_list = [('[0.2]',[0.2])]
# Important: this needs to be smallest first because connected components
# smaller than a (minimum degree+1) are removed from the input graph
#
graph_node_min_degr_list = [('3',3)]
sim_hash_match_sim = 0.9
sim_hash_num_bit_list = [('500',500)]
sim_hash_block_funct_list = ['hlsh']
sim_comp_funct_list = ['simtol']
graph_feat_list_list = [('all',['node_freq','max_sim','min_sim','degree',
'degree_histo1','degree_histo2','sim_avr',
'sim_std','egonet_degree','egonet_density',
#'pagerank', # very time consuming
'between_central',
#'closeness_central', # very time consuming
'degree_central',
#'eigenvec_central', # very time consuming
]),
('no-histo',['node_freq','max_sim','min_sim','degree',
'sim_avr', 'sim_std','egonet_degree',
'egonet_density','between_central',
'degree_central', 'eigenvec_central',
]),
('one-central',['node_freq','max_sim','min_sim','degree',
'degree_histo1', 'degree_histo2', 'sim_avr',
'sim_std','egonet_degree', 'egonet_density',
'degree_central',
]),
('no-nf-central',['max_sim','min_sim','degree',
'degree_histo1','degree_histo2',
'sim_avr','sim_std',
'egonet_degree','egonet_density']),
('no-central',['node_freq','max_sim','min_sim',
'degree','degree_histo1',
'degree_histo2','sim_avr','sim_std',
'egonet_degree','egonet_density']),
('node2vec', ['node2vec']),
]
elif ('ncvoter' in encode_data_set_name or 'ncvr' in encode_data_set_name): # NCVR
soundex_attr_list = [3] # 3, 5
graph_sim_list = [('[0.2]',[0.2])]
graph_node_min_degr_list = [('5',5)]
sim_hash_num_bit_list = [('1000',1000)]
sim_hash_match_sim = 0.9
sim_hash_block_funct_list = ['hlsh']
sim_comp_funct_list = ['simtol']
graph_feat_list_list = [('all',['node_freq','max_sim','min_sim','degree',
'degree_histo1','degree_histo2','sim_avr',
'sim_std','egonet_degree','egonet_density',
#'pagerank', # very time consuming
'between_central',
#'closeness_central', # very time consuming
'degree_central',
#'eigenvec_central', # very time consuming
]),
('no-histo',['node_freq','max_sim','min_sim','degree',
'sim_avr', 'sim_std','egonet_degree',
'egonet_density','between_central',
'degree_central', 'eigenvec_central',
]),
('one-central',['node_freq','max_sim','min_sim','degree',
'degree_histo1', 'degree_histo2', 'sim_avr',
'sim_std','egonet_degree', 'egonet_density',
'degree_central',
]),
('no-nf-central',['max_sim','min_sim','degree',
'degree_histo1','degree_histo2',
'sim_avr','sim_std',
'egonet_degree','egonet_density']),
('no-central',['node_freq','max_sim','min_sim',
'degree','degree_histo1',
'degree_histo2','sim_avr','sim_std',
'egonet_degree','egonet_density']),
('node2vec', ['node2vec']),
]
elif('euro' in encode_data_set_name):
soundex_attr_list = [1] # 1, 2
graph_sim_list = [('[0.2]',[0.2])]
# Important: this needs to be smallest first because connected components
# smaller than a (minimum degree+1) are removed from the input graph
#
graph_node_min_degr_list = [('20',20)]
sim_hash_num_bit_list = [('500',500)]
sim_hash_match_sim = 0.9
sim_hash_block_funct_list = ['hlsh']
sim_comp_funct_list = ['simtol']
graph_feat_list_list = [('all',['node_freq','max_sim','min_sim','degree',
'degree_histo1','degree_histo2','sim_avr',
'sim_std','egonet_degree','egonet_density',
#'pagerank', # very time consuming
'between_central',
#'closeness_central', # very time consuming
'degree_central',
#'eigenvec_central', # very time consuming
]),
('no-histo',['node_freq','max_sim','min_sim','degree',
'sim_avr', 'sim_std','egonet_degree',
'egonet_density','between_central',
'degree_central', 'eigenvec_central',
]),
('one-central',['node_freq','max_sim','min_sim','degree',
'degree_histo1', 'degree_histo2', 'sim_avr',
'sim_std','egonet_degree', 'egonet_density',
'degree_central',
]),
('no-nf-central',['max_sim','min_sim','degree',
'degree_histo1','degree_histo2',
'sim_avr','sim_std',
'egonet_degree','egonet_density']),
('no-central',['node_freq','max_sim','min_sim',
'degree','degree_histo1',
'degree_histo2','sim_avr','sim_std',
'egonet_degree','egonet_density']),
('node2vec', ['node2vec']),
]
else:
print '*** Error: Unknown input data set *****'
sys.exit()
print 'Use similarity lists for graph generation:', graph_sim_list
graph_feat_select_list = [('all','all'),
#('non-zero','nonzero'),
#'top-10':10,
#('top-10',10)
#('min-std-0.4',0.4),
]
# For the 'simtol' comparison approach set the similarity tolerance values:
# lower: how much lower the encoded similarity can be,
# upper: how much higher the encoded similarity can be
#
bf_hash_sim_low_tol = 0.01 # If the encoding are Bloom filters
bf_hash_sim_up_tol = 0.25
tmh_hash_sim_low_tol = 0.05 # If the encoding are tabulation min hashes
tmh_hash_sim_up_tol = 0.05
cmh_hash_sim_low_tol = 0.05 # If the encoding are tabulation min hashes
cmh_hash_sim_up_tol = 0.01
adj_hash_sim_low_tol = 0.05 # If the encoded similarities have been adjusted
adj_hash_sim_up_tol = 0.05
hash_sim_min_tol = 0.05 # Also for the 'simtol' comparison approach, how much
# tolerance to count the number of edges
# Numpy and Scipy Cosine give the same results and are always best - so only
# use those
#
#final_sim_funct_list = ['lsh_cosine','cosine_scipy','cosine_numpy',
# 'euclidean']
#final_sim_funct_list = ['edge_sim_diff']
# The parameters for the Hamming LSH blocking of the similarity hashes in the
# graph matching step
#
if('ncvoter' in encode_data_set_name or 'ncvr' in encode_data_set_name):
graph_block_hlsh_num_sample = 20
graph_block_hlsh_rel_sample_size = 10 # Divide bit array length by this
else:
graph_block_hlsh_num_sample = 50
graph_block_hlsh_rel_sample_size = 50 # Divide bit array length by this
num_exp = len(graph_sim_list) * len(graph_node_min_degr_list) * \
len(graph_feat_list_list) * len(graph_feat_select_list) * \
len(sim_hash_num_bit_list) * \
len(sim_hash_block_funct_list) * len(sim_comp_funct_list)
# * len(final_sim_funct_list)
print
print '*** Number of graph attack experiments to be conducted: %d ***' % \
(num_exp)
print
# Get the overall minimum similarity for the graphs
#
min_sim = 1.0
# Also get a sorted list of all similarities over all parameter settings
#
all_sim_set = set()
for (sim_list_name, sim_list) in graph_sim_list:
min_sim = min(min_sim, min(sim_list))
all_sim_set = all_sim_set | set(sim_list)
all_sim_list = sorted(all_sim_set)
# -----------------------------------------------------------------------------
import binascii
import csv
import gzip
import hashlib
import math
import os.path
import random
import sys
import time
import bitarray
import itertools
import numpy
import numpy.linalg
import scipy.stats
import scipy.spatial.distance
import sklearn.tree
import pickle
import networkx
import networkx.drawing
import matplotlib
matplotlib.use('Agg') # For running on adamms4 (no display)
import matplotlib.pyplot as plt
from libs import auxiliary
from libs import hashing # Bloom filter based PPRL functions
from libs import encoding
from libs import hardening
from libs import tabminhash # Tabulation min-hash PPRL functions
from libs import colminhash # Two step column hashing for PPRL
from libs import simcalc # Similarity functions for q-grams and bit-arrays
from libs import node2vec # Node2vec module for generating features using random walks
from gensim.models import Word2Vec
from matplotlib import pylab as pl
from sklearn import linear_model
from sklearn.model_selection import train_test_split
from sklearn.isotonic import IsotonicRegression
from sklearn.preprocessing import PolynomialFeatures
from scipy.optimize import linear_sum_assignment
from sklearn import metrics
# -----------------------------------------------------------------------------
# Set the maximum size of a graph for plots to be generated
#
MAX_DRAW_PLOT_NODE_NUM = 200
PAD_CHAR = chr(1) # Used for q-gram padding
BF_HASH_FUNCT1 = hashlib.sha1
BF_HASH_FUNCT2 = hashlib.md5
#BF_HASH_FUNCT1 = hashlib.md5
#BF_HASH_FUNCT2 = hashlib.sha256
random_seed = 17
if (random_seed != None):
random.seed(random_seed)
today_str = time.strftime("%Y%m%d", time.localtime())
now_str = time.strftime("%H%M", time.localtime())
today_time_str = time.strftime("%Y%m%d %H:%M:%S", time.localtime())
numpy.set_printoptions(precision=4, linewidth=120)
PLT_PLOT_RATIO = 1.0
FILE_FORMAT = '.eps' #'.png'
PLT_FONT_SIZE = 20# 28 # used for axis lables and ticks
LEGEND_FONT_SIZE = 20 # 28 # used for legends
TITLE_FONT_SIZE = 19 # 30 # used for plt title
TICK_FONT_SIZE = 18
# =============================================================================
def load_data_set(data_set_name, attr_num_list, ent_id_col, soundex_attr_val_list,
num_rec=-1, col_sep_char=',', header_line_flag=False):
"""Load a data set and extract required attributes.
It is assumed that the file to be loaded is a comma separated values file.
Input arguments:
- data_set_name File name of the data set.
- attr_num_list The list of attributes to use (of the form
[1,3]).
- ent_id_col The column number of the entity identifiers.
- num_rec Number of records to be loaded from the file
If 'num_rec' is -1 all records will be read
from file, otherwise (assumed to be a positive
integer number) only the first 'num_rec'
records will be read.
- col_sep_char The column separate character.
- header_line_flag A flag, set this to to True if the data set
contains a header line describing attributes,
otherwise set it to False.
The default value False.
Output:
- rec_attr_val_dict A dictionary with entity identifiers as keys and
where values are lists of attribute values.
- attr_name_list The list of the attributes to be used.
- num_rec_loaded The actual number of records loaded.
"""
rec_attr_val_dict = {} # The dictionary of attribute value lists to be
# loaded from file
rec_soundex_attr_val_dict = {}
# Check if the file name is a gzip file or a csv file
#
if (data_set_name.endswith('gz')):
in_f = gzip.open(data_set_name)
else:
in_f = open(data_set_name)
# Initialise the csv reader
#
csv_reader = csv.reader(in_f, delimiter=col_sep_char)
# The names (if available from the header line) of the attributes to be used
#
attr_name_list = []
# Read the header line if available
#
if (header_line_flag == True):
header_list = csv_reader.next()
print 'File header line:', header_list
print ' Attributes to be used:',
for attr_num in attr_num_list:
print header_list[attr_num],
attr_name_list.append(header_list[attr_num])
print
max_attr_num = max(attr_num_list)+1
# Read each line in the file and store the required attribute values in a
# list
#
rec_num = 0
for rec_val_list in csv_reader:
if (num_rec > 0) and (rec_num >= num_rec):
break # Read enough records
rec_num += 1
use_rec_val_list = []
soundex_val_list = []
# Read the entity identifier
#
ent_id = rec_val_list[ent_id_col].strip().lower()
for attr_num in xrange(max_attr_num):
if attr_num in attr_num_list:
use_rec_val_list.append(rec_val_list[attr_num].lower().strip())
if(attr_num in soundex_attr_val_list):
soundex_val_list.append(rec_val_list[attr_num].lower().strip())
# else:
# use_rec_val_list.append('') # Not needed
# Don't use completely empty list of values
#
if (len(''.join(use_rec_val_list)) > 0):
rec_attr_val_dict[ent_id] = use_rec_val_list
rec_soundex_attr_val_dict[ent_id] = soundex_val_list
in_f.close()
print ' Loaded %d records from file' % (rec_num)
print ' Stored %d values' % (len(rec_attr_val_dict))
# Get the frequency distribution of values
#
rec_tuple_count_dict = {}
for use_rec_val_list in rec_attr_val_dict.itervalues():
rec_tuple = tuple(use_rec_val_list)
rec_tuple_count_dict[rec_tuple] = \
rec_tuple_count_dict.get(rec_tuple, 0) + 1
count_dist_dict = {}
for rec_tuple_count in rec_tuple_count_dict.itervalues():
count_dist_dict[rec_tuple_count] = \
count_dist_dict.get(rec_tuple_count, 0) + 1
print ' Count distribution of value occurrences:', \
sorted(count_dist_dict.items())
rec_tuple_count_dict.clear() # Not needed anymore
count_dist_dict.clear()
return rec_attr_val_dict, attr_name_list, rec_num, rec_soundex_attr_val_dict
# -----------------------------------------------------------------------------
def gen_q_gram_sets(rec_attr_val_dict, q, padded_flag):
"""Convert the attribute value(s) for each record into one q-gram set. If
there are several attributes they are concatenated by a single space
character.
Only add a record to the q-gram dictionary if its q-gram set is not empty.
Input arguments:
- rec_attr_val_dict A dictionary with entity identifiers as keys and
where values are lists of attribute values.
- q The number of characters per q-gram.
- padded_flag if set to True then values will be padded at the
beginning and end, otherwise not.
Output:
- q_gram_dict A dictionary with entity identifiers as keys and one
q-gram set per record.
"""
q_gram_dict = {}
qm1 = q-1 # Shorthand
for (ent_id, attr_val_list) in rec_attr_val_dict.iteritems():
rec_q_gram_set = set()
for attr_val in attr_val_list:
attr_val_str = attr_val.strip()
if (padded_flag == True): # Add padding start and end characters
attr_val_str = PAD_CHAR*qm1+attr_val_str+PAD_CHAR*qm1
attr_val_len = len(attr_val_str)
# Convert into q-grams and process them
#
attr_q_gram_list = [attr_val_str[i:i+q] for i in range(attr_val_len - qm1)]
attr_q_gram_set = set(attr_q_gram_list)
rec_q_gram_set = rec_q_gram_set.union(attr_q_gram_set)
if (len(rec_q_gram_set) > 0):
q_gram_dict[ent_id] = rec_q_gram_set
return q_gram_dict
# -----------------------------------------------------------------------------
def plot_save_graph(sim_graph, file_name, min_sim):
"""Generate a plot of the given similarity graph and save it into the given
file name. It is assumed that the edge similarities are given in the
range [min_sim, 1.0]. Different grey levels will be assigned to different
edge similarities, with black being the lowest similarity and light grey
the highest.
Input arguments:
- sim_graph An undirected graph where edges have similarities (sim).
- file_name The name into which the plot is to be saved.
- min_sim The lowest similarity assumed to be assigned to edges.
Output:
- This method does not return anything.
"""
# Generate a list with different grey scales for different similarities
# (set to 4 levels)
#
color_str_list = ['#333333', '#666666', '#999999', '#CCCCCC']
sim_interval = (1.0 - min_sim) / len(color_str_list)
edge_color_list = [(min_sim,'#000000')]
for (i, color_str) in enumerate(color_str_list):
edge_color_list.append((min_sim + (1+i)*sim_interval, color_str))
graph_edge_list = sim_graph.edges()
graph_edge_color_list = [] # Based on sim generate grey colors
node_key_val_set = set()
for (node_key_val1, node_key_val2) in graph_edge_list:
node_key_val_set.add(node_key_val1)
node_key_val_set.add(node_key_val2)
edge_sim = sim_graph.edge[node_key_val1][node_key_val2]['sim']
for (color_sim, grey_scale_color_str) in edge_color_list:
if (edge_sim <= color_sim):
graph_edge_color_list.append(grey_scale_color_str)
break
assert len(graph_edge_color_list) == len(graph_edge_list)
networkx.draw(sim_graph, node_size=20, width=2, edgelist=graph_edge_list,
edge_color=graph_edge_color_list, with_labels=False)
print 'Save generated graph figure with %d nodes into file: %s' % \
(len(node_key_val_set), file_name)
plt.savefig(file_name)
# -----------------------------------------------------------------------------
def plot_sim_graph_histograms(sim_graph_list, plot_file_name,
round_num_digits=3, y_scale_log=True):
"""Generate a histogram plot with one histogram for each of the given
similarity graphs.
Input arguments:
- sim_graph_list A list of pairs (similarity graph, label_str) where
for each given similarity graph a histogram will
be generated.
- plot_file_name The name into which the plot is to be saved.
- round_num_digit The number of digits values are to be rounded to.
- y_scale_log A flag, if set to True (default) then the y-axis is
shown in log scale.
Output:
- This method does not return anything.
"""
plot_color_list = ['r','b','g','m','k'] # Colors to be used
plot_list = [] # One list of x and y values, plus label, for each graph
min_count = 99999999999 # Needed for plot maximum y-axis value
max_count = 0
min_sim = 1.0
max_sim = 0.0
for (sim_graph, label_str) in sim_graph_list:
# Generate a dictionary where keys will be similarities and values counts
# of how many edges have that similarity
#
sim_histo_dict = {}
for (node_key_val1, node_key_val2) in sim_graph.edges():
edge_sim = sim_graph.edge[node_key_val1][node_key_val2]['sim']
egde_sim = round(edge_sim, round_num_digits)
sim_histo_dict[egde_sim] = sim_histo_dict.get(egde_sim, 0) + 1
sim_graph_x_val_list = []
sim_graph_y_val_list = []
for (edge_sim, count) in sorted(sim_histo_dict.items()):
sim_graph_x_val_list.append(edge_sim)
sim_graph_y_val_list.append(count)
plot_list.append((sim_graph_x_val_list, sim_graph_y_val_list, label_str))
min_count = min(min_count, min(sim_graph_y_val_list))
max_count = max(max_count, max(sim_graph_y_val_list))
min_sim = min(min_sim, min(sim_graph_x_val_list))
max_sim = max(max_sim, max(sim_graph_x_val_list))
sim_histo_dict.clear() # Not needed anymore
# Plot the generated lists
#
w,h = plt.figaspect(PLT_PLOT_RATIO)
plt.figure(figsize=(w,h))
plt.title('Graph edge similarity histograms')
plt.xlabel('Edge similarities')
if (y_scale_log == True):
plt.ylabel('Counts (log-scale)')
plt.yscale('log')
plt.ylim(min_count*0.667, max_count*1.5)
else:
plt.ylabel('Counts')
plt.ylim(min_count-max_count*0.05, max_count*1.05)
x_tol = (max_sim-min_sim)/20.0
plt.xlim(min_sim-x_tol, max_sim+x_tol)
i = 0
for sim_graph_x_val_list, sim_graph_y_val_list, label_str in plot_list:
c = plot_color_list[i]
i += 1
plt.plot(sim_graph_x_val_list, sim_graph_y_val_list, color = c, #lw=2,
label=label_str)
plt.legend(loc="best") #, prop={'size':14}, bbox_to_anchor=(1, 0.5))
plt.savefig(plot_file_name, bbox_inches='tight')
# -----------------------------------------------------------------------------
def plot_save_sim_diff(plot_list_dict, plot_file_name, round_num_digit=3,
density_plot=True):
"""Generate a frequency plot of the given dictionary with similarity
differences for different minimum similarities.
Input arguments:
- plot_list_dict A dictionary with minimum similarities as keys and
lists of similarity differences between true-matching
encoded and plain-text value pairs.
- plot_file_name The name into which the plot is to be saved.
- round_num_digit The number of digits values are to be rounded to.
- density_plot A flag, if set to True then a density plot is
generated instead of a frequency plot.
Output:
- This method does not return anything.
"""
# PC 20181025: TODO: Density plot should be normalised, buty-axis seems to
# be larger than 1 ??
assert density_plot in [True, False], density_plot
# Generate a list of grey levels to be used, with highest similarity having
# black and lowest similarity a middle grey tone
#
plot_color_list = []
min_level = 0.0
max_level = 0.6
level_diff = max_level - min_level
min_sim_list = sorted(plot_list_dict.keys())
num_sim = len(min_sim_list)
if (num_sim == 1):
plot_color_list.append(0.0) # Only one color needed - make it black
else:
for (i, sim) in enumerate(min_sim_list):
c = max_level - i * level_diff/(num_sim-1.0)
plot_color_list.append(c)
# Get the overall minimum and maximum values for the density plot
#
min_x = 9999
max_x = -999