-
Notifications
You must be signed in to change notification settings - Fork 0
/
comparison.py
5263 lines (3967 loc) · 189 KB
/
comparison.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
# =============================================================================
# AUSTRALIAN NATIONAL UNIVERSITY OPEN SOURCE LICENSE (ANUOS LICENSE)
# VERSION 1.3
#
# The contents of this file are subject to the ANUOS License Version 1.3
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at:
#
# https://sourceforge.net/projects/febrl/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
# the License for the specific language governing rights and limitations
# under the License.
#
# The Original Software is: "comparison.py"
#
# The Initial Developer of the Original Software is:
# Dr Peter Christen (Research School of Computer Science, The Australian
# National University)
#
# Copyright (C) 2002 - 2011 the Australian National University and
# others. All Rights Reserved.
#
# Contributors:
#
# Alternatively, the contents of this file may be used under the terms
# of the GNU General Public License Version 2 or later (the "GPL"), in
# which case the provisions of the GPL are applicable instead of those
# above. The GPL is available at the following URL: http://www.gnu.org/
# If you wish to allow use of your version of this file only under the
# terms of the GPL, and not to allow others to use your version of this
# file under the terms of the ANUOS License, indicate your decision by
# deleting the provisions above and replace them with the notice and
# other provisions required by the GPL. If you do not delete the
# provisions above, a recipient may use your version of this file under
# the terms of any one of the ANUOS License or the GPL.
# =============================================================================
#
# Freely extensible biomedical record linkage (Febrl) - Version 0.4.2
#
# See: http://datamining.anu.edu.au/linkage.html
#
# =============================================================================
"""Module with classes for field (attribute) and record comparisons.
This module provides classes for record and field comparisons that can be
used for the linkage process.
TODO:
- improve cache: how to remove oldest count-1 pair efficiently?
- do caching timing test -> comparisonTiming.py module
- improve value frequency based weight calculations
TODO (old version):
- What do we do if we want to link two data sets, and we know that we have
different distributions for e.g. surnames, but only a lookup table for the
surnames from one data set?
- Add frequency table capabilities for numeric, data and age field
comparators.
- Do a proper date/time comparison function (maybe using mxDateTime module)
that takes both date and time into consideration.
"""
# =============================================================================
# Import necessary modules (Python standard modules first, then Febrl modules)
import bz2
import datetime
import difflib
import logging
import math
import time
import zlib
import auxiliary
import encode
import mymath
# =============================================================================
class RecordComparator:
"""Class that implements a record comparator to compare two records and
compute (and return) a weight vector.
"""
# ---------------------------------------------------------------------------
def __init__(self, dataset1, dataset2, field_comparator_list, descr = ''):
"""Constructor.
Has as arguments two data set objects and a list of field comparators,
that each are made of a tuple:
(field comparator, field name in dataset1, field name in dataset2)
The constructor checks if the field names are available in the two data
sets and then generates an efficient list of comparison methods and
field columns (into the data sets).
"""
auxiliary.check_is_string('description', descr)
self.description = descr
# Check if the input objects needed are lists
#
auxiliary.check_is_list('dataset1.field_list', dataset1.field_list)
auxiliary.check_is_list('dataset2.field_list', dataset2.field_list)
auxiliary.check_is_list('field_comparator_list', field_comparator_list)
self.dataset1 = dataset1
self.dataset2 = dataset2
self.field_comparator_list = field_comparator_list
self.field_comparison_list = [] # Only compare methods and field columns
# Extract field names from the two data set field name lists
#
dataset1_field_names = []
dataset2_field_names = []
for (field_name, field_data) in dataset1.field_list:
dataset1_field_names.append(field_name)
for (field_name, field_data) in dataset2.field_list:
dataset2_field_names.append(field_name)
# Go through field list and check if available
#
for (field_comp, field_name1, field_name2) in self.field_comparator_list:
if (field_name1 not in dataset1_field_names):
logging.exception('Field "%s" is not in data set 1 field name list: ' \
% (field_name1) + '%s' % (str(dataset1.field_list)))
raise Exception
field_index1 = dataset1_field_names.index(field_name1)
if (field_name2 not in dataset2_field_names):
logging.exception('Field "%s" is not in data set 2 field name list: ' \
% (field_name2) + '%s' % (str(dataset2.field_list)))
raise Exception
field_index2 = dataset2_field_names.index(field_name2)
field_tuple = (field_comp.compare, field_index1, field_index2)
self.field_comparison_list.append(field_tuple)
assert len(self.field_comparison_list) == len(self.field_comparator_list)
# A log message - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
logging.info('')
logging.info('Initialised record comparator')
logging.info(' Data set 1: %s' % (dataset1.description))
logging.info(' Field names: %s' % (str(dataset1_field_names)))
logging.info(' Data set 2: %s' % (dataset2.description))
logging.info(' Field names: %s' % (str(dataset2_field_names)))
logging.info(' Field comparators:')
for i in range(len(self.field_comparison_list)):
(field_comp, field_name1, field_name2) = self.field_comparator_list[i]
(comp_method, field_index1, field_index2) = self.field_comparison_list[i]
logging.info(' Description: %s' % (field_comp.description))
logging.info(' Field name 1: %s (at column %d)' % \
(field_name1, field_index1))
logging.info(' Field name 2: %s (at column %d)' % \
(field_name2, field_index2))
# ---------------------------------------------------------------------------
def compare(self, rec1, rec2):
"""Compare two records (list of fields) and return a vector with weight
values (floating-point numbers)
"""
weight_vector = []
# Compute a weight for each field comparator
#
for (comp_method,field_index1,field_index2) in self.field_comparison_list:
if (field_index1 >= len(rec1)):
val1 = ''
else:
val1 = rec1[field_index1]
if (field_index2 >= len(rec2)):
val2 = ''
else:
val2 = rec2[field_index2]
val1 = val1.lower()
val2 = val2.lower()
w = comp_method(val1,val2)
weight_vector.append(w)
return weight_vector
# ---------------------------------------------------------------------------
def get_cache_stats(self):
"""Extract information about the cache size, maximum and average counts for
all the field comparators that have an activated cache.
"""
logging.info('Caching statistics for record comparator "%s"' % \
(self.description))
# Go through field list and check if available
#
for (field_comp, field_name1, field_name2) in self.field_comparator_list:
logging.info(' Field comparator: "%s"' % (field_comp.description))
if (field_comp.do_caching == False):
logging.info(' Caching is not activated')
elif (field_comp.cache == {}):
logging.info(' Caching is activated but cache is empty')
else:
cache_size = len(field_comp.cache)
cache_max_count = -1
cache_count_sum = 0.0
for cache_key in field_comp.cache: # Get all cache entries and counts
(cache_weight, access_count) = field_comp.cache[cache_key]
cache_max_count = max(cache_max_count, access_count)
cache_count_sum += access_count
cache_avrg_count = cache_count_sum / cache_size
cache_size_str = ' Number of cache entries: %s' % (cache_size)
if (field_comp.max_cache_size == None):
cache_size_str += ' (Cache size is unlimited)'
else:
cache_size_str += ' (Cache size is limited to %d entries)' % \
(field_comp.max_cache_size)
logging.info(cache_size_str)
logging.info(' Maximum and average cache entry count: %d / %.2f' % \
(cache_max_count, cache_avrg_count))
# =============================================================================
class FieldComparator:
"""Base class for field comparators.
All field comparators have the following instance variables, which can be
set when a field comparator is initialised:
description A string describing the field comparator.
do_caching A flag, True or False, to enable or disable caching.
max_cache_size The maximum number of comparisons to be cached.
cache A dictionary with cached comparisons.
missing_values A list of one or more strings that correspond to
missing values.
missing_weight Numerical weight when values are missing.
agree_weight Numerical weight when two values agree.
disagree_weight Numerical weight when two values totally disagree.
val_freq_table A dictionary with values (as keys) and their counts
(as values). If provided, the comparison weight will be
frequency adjusted. Default is None (not provided).
"""
# ---------------------------------------------------------------------------
def __init__(self, base_kwargs):
"""Constructor.
"""
# General attributes for all field comparators
#
self.description = ''
self.do_caching = False # Caching disabled by default
self.max_cache_size = None # None - no maximum cache size
self.cache = {} # Dictionary with cached values
self.cache_num_not_cached = 0 # Number of comparisons not cached
self.cache_warn_counts = [2,5,10,50] # List of when warnings should be
# given (minimum counts)
self.missing_values = ['']
self.missing_weight = 0.0
self.agree_weight = 1.0
self.disagree_weight = 0.0
self.val_freq_table = None
self.val_freq_sum = None # If a frequency table is provided, the sum of
# all counts will be calculated and stored
self.freq_max_weight = None # A maximum weight value for frequency based
# agreement values. If not provided it will be
# set to the general agreement value
# Process base keyword arguments (all data set specific keywords were
# processed in the derived class constructor)
#
for (keyword, value) in base_kwargs.items():
if (keyword.startswith('desc')):
auxiliary.check_is_string('description', value)
self.description = value
elif (keyword.startswith('do_c')):
auxiliary.check_is_flag('do_caching', value)
self.do_caching = value
elif (keyword.startswith('max_cach')):
if (value == None): # No maximum cache size (use with care!)
self.max_cache_size = value
else:
auxiliary.check_is_integer('max_cache_size', value)
auxiliary.check_is_not_negative('max_cache_size', value)
self.max_cache_size = value
elif (keyword.startswith('missing_v')):
auxiliary.check_is_list('missing_values', value)
self.missing_values = value
elif (keyword.startswith('missing_w')):
auxiliary.check_is_number('missing_weight', value)
self.missing_weight = value
elif (keyword.startswith('agr')):
auxiliary.check_is_number('agree_weight', value)
self.agree_weight = value
elif (keyword.startswith('disa')):
auxiliary.check_is_number('disagree_weight', value)
self.disagree_weight = value
elif (keyword.startswith('val_fr')):
auxiliary.check_is_dictionary('val_freq_table', value)
self.val_freq_table = value
elif (keyword.startswith('freq_m')):
auxiliary.check_is_number('freq_max_weight', value)
self.freq_max_weight = value
else:
logging.exception('Illegal constructor argument keyword: %s' % \
(str(keyword)))
raise Exception
# Create a dictionary with the warning counts - - - - - - - - - - - - - - -
#
self.cache_warn_dict_counts = {}
for i in self.cache_warn_counts:
self.cache_warn_dict_counts[i] = 0 # No value pairs with count i so far
# If a frequency table is given calculate the sum of all counts
#
if (self.val_freq_table != None):
self.val_freq_sum = 0
for (k,v) in self.val_freq_table.items():
auxiliary.check_is_integer('frequency table entry "%s"' % (k), v)
auxiliary.check_is_positive('frequency table entry "%s"' % (k), v)
self.val_freq_sum += v
# Make sure a maximum frequency agreement weight is set
#
if (self.freq_max_weight == None): # Has not be given as argument
self.freq_max_weight = self.agree_weight
logging.warning('Setting maximum frequency agreement weight to ' + \
'general agreement weight')
self.__check_weights__()
# ---------------------------------------------------------------------------
def __check_weights__(self):
"""Check the values of weights. Should not be used from outside the module.
Make sure the agreement weight is larger than the disagreement weight,
and that the missing weight is somewhere in between.
"""
if (self.agree_weight < self.disagree_weight):
logging.exception('Agreement weight set to a value smaller than the ' + \
'disagreement weight')
raise Exception
if (self.agree_weight < self.missing_weight):
logging.exception('Agreement weight set to a value smaller than the ' + \
'missing weight')
raise Exception
if (self.disagree_weight > self.missing_weight):
logging.exception('Disagreement weight set to a value larger than ' + \
'the missing weight')
raise Exception
if (self.val_freq_table != None):
auxiliary.check_is_number('freq_max_weight', self.freq_max_weight)
if (self.freq_max_weight < self.disagree_weight):
logging.exception('Maximum frequency agreement weight set to a ' + \
'value smaller than the disagreement weight')
raise Exception
if (self.freq_max_weight < self.missing_weight):
logging.exception('Maximum frequency agreement weight set to a ' + \
'value smaller than the missing weight')
raise Exception
# ---------------------------------------------------------------------------
def __get_from_cache__(self, val1, val2):
"""Check if the given pair of values is in the cache, if so return cached
similarity weight. Otherwise return None.
If found in the cache, the pair's count is increased by one.
warning messages are logged if the cache size is limited and all entries
have certain counts (see numbers: self.cache_warn_counts).
If caching is disabled, returned None.
"""
if (self.do_caching == False):
return None
# Comparisons have to be symmetric: Only one of the pairs (val1,val2) and
# (val2,val1) should be stored in the cache, so sort them
#
if (val1 < val2):
cache_key = (val1, val2)
else:
cache_key = (val2, val1)
if cache_key not in self.cache: # The values pair is not in the cache
return None
# Get weight and access count from cache, increase count, and put it back
#
(cache_weight, access_count) = self.cache[cache_key]
access_count += 1
self.cache[cache_key] = (cache_weight, access_count)
if (self.max_cache_size == None):
return cache_weight # Unlimited cache size, simply return
if (access_count in self.cache_warn_counts): # Check if warning needed
num_count_pairs = self.cache_warn_dict_counts[access_count]
self.cache_warn_dict_counts[access_count] = num_count_pairs+1
if (num_count_pairs == self.max_cache_size): # All pairs have this count
logging.warning('All cache entries have a count of %d' % \
(access_count))
return cache_weight
# ---------------------------------------------------------------------------
def __put_into_cache__(self, val1, val2, weight):
"""If caching is enabled and there is room in the cache put the given pair
of values into the cache with the given similarity weight.
If the cache is full don't insert values pair but increase the number of
non-cached comparisons.
If caching is disabled do nothing.
"""
if (self.do_caching == False):
return
# Check if the cache is full
#
if ((self.max_cache_size != None) and \
(len(self.cache) == self.max_cache_size)):
self.cache_num_not_cached += 1 # One more pair not cached
if (self.cache_num_not_cached in [100, 1000, 10000, 100000]):
logging.warning('Cache is full, %d comparisons cannot be cached' % \
(self.cache_num_not_cached))
return
# Comparisons have to be symmetric: Only one of the pairs (val1,val2) and
# (val2,val1) should be stored in the cache, so sort them
#
if (val1 < val2):
cache_key = (val1, val2)
else:
cache_key = (val2, val1)
# Insert new pair into cache and list of pairs with count 1
#
self.cache[cache_key] = (weight, 1)
# ---------------------------------------------------------------------------
def __calc_freq_agree_weight__(self, val):
"""Check if a frequency table is given and if so if the given value is in
there - in which case a frequency based agreement weight is calculated
and returned. Otherwise the general agreement weight is returned.
"""
if ((self.val_freq_table != None) and (val in self.val_freq_table)):
val_count = self.val_freq_table[val]
val_freq = float(val_count) / float(self.val_freq_sum)
# Agreement weight, computed according to L. Gill (2001), page 66
#
freq_weight = math.log(1.0 / val_freq, 2) # log_2
# Make sure frequency weight is not larger than maximum frequency
# agreement weight
#
return min(freq_weight, self.freq_max_weight)
else:
return self.agree_weight
# ---------------------------------------------------------------------------
def __calc_freq_weights__(self, val1, val2):
"""Check if a frequency table is given and if so if the given values are in
there - in which case frequency based agreement weights are calculated.
The minimum frequency based weight is then returned. Otherwise the
general agreement weight is returned.
"""
if (self.val_freq_table == None): # No frequency table given
return self.agree_weight
if (val1 in self.val_freq_table):
val1_count = self.val_freq_table[val1]
val1_freq = float(val1_count) / float(self.val_freq_sum)
# Agreement weight, computed according to L. Gill (2001), page 66
#
freq1_weight = math.log(1.0 / val1_freq, 2) # log_2
# Make sure frequency weight is not larger than maximum frequency
# agreement weight
#
freq1_weight = min(freq1_weight, self.freq_max_weight)
else:
freq1_weight = self.agree_weight
if (val2 in self.val_freq_table):
val2_count = self.val_freq_table[val2]
val2_freq = float(val2_count) / float(self.val_freq_sum)
freq2_weight = math.log(1.0 / val2_freq, 2) # log_2
freq2_weight = min(freq2_weight, self.freq_max_weight)
else:
freq2_weight = self.agree_weight
return min(freq1_weight, freq2_weight)
# ---------------------------------------------------------------------------
def set_weights(self, **kwargs):
"""Provide new values for the four possible weights.
"""
# Process base keyword arguments
#
for (keyword, value) in kwargs.items():
if (keyword.startswith('missing_w')):
auxiliary.check_is_number('missing_weight', value)
self.missing_weight = value
elif (keyword.startswith('agr')):
auxiliary.check_is_number('agree_weight', value)
self.agree_weight = value
elif (keyword.startswith('disa')):
auxiliary.check_is_number('disagree_weight', value)
self.disagree_weight = value
elif (keyword.startswith('freq_m')):
if (self.val_freq_table == None):
logging.warning('No frequency table given, so maximum frequency ' + \
'agreement weight will not be used.')
else:
auxiliary.check_is_number('freq_max_weight', value)
self.freq_max_weight = value
else:
logging.exception('Illegal constructor argument keyword: %s' % \
(str(keyword)))
raise Exception
self.__check_weights__()
# ---------------------------------------------------------------------------
def train(self):
"""Method which allows training of a field comparator before using it.
Most field comparators do not need to be trained, see implementations in
derived classes for details.
"""
logging.info('No training needed for this comparator')
# ---------------------------------------------------------------------------
def compare(self, val1, val2):
"""Compare two fields values, compute and return a numerical weight. See
implementations in derived classes for details.
"""
logging.exception('Override abstract method in derived class')
raise Exception
# ---------------------------------------------------------------------------
def log(self, instance_var_list = None):
"""Write a log message with the basic field comparator instance variables
plus the instance variable provided in the given input list (assumed to
contain pairs of names (strings) and values).
"""
logging.info('')
logging.info('Field comparator: "%s"' % (self.description))
logging.info(' Do caching: %s' % (str(self.do_caching)))
if (self.max_cache_size != None):
logging.info(' Maximum cache size: %s' % (str(self.max_cache_size)))
else:
logging.info(' Unlimited cache size')
logging.info(' Warnings will be given once all cache entries have ' + \
'counts: %s' % (str(self.cache_warn_counts)))
logging.info(' Missing values: %s' % (str(self.missing_weight)))
logging.info(' Missing weight: %f' % (self.missing_weight))
logging.info(' Agreement weight: %f' % (self.agree_weight))
logging.info(' Disagreement weight: %f' % (self.disagree_weight))
if (self.val_freq_table != None):
logging.info(' Number of entires in frequency table: %d' % \
(len(self.val_freq_table)))
logging.info(' Frequency table sum: %f' % \
(self.val_freq_sum))
logging.info(' Maximum frequency agreement weight: %f' % \
(self.freq_max_weight))
if (instance_var_list != None):
logging.info(' Comparator specific variables:')
max_name_len = 0
for (name, value) in instance_var_list:
max_name_len = max(max_name_len, len(name))
for (name, value) in instance_var_list:
pad_spaces = (max_name_len-len(name))*' '
logging.info(' %s %s' % (name+':'+pad_spaces, str(value)))
# ---------------------------------------------------------------------------
def get_cache_stats(self):
"""Extract information about the cache size, maximum and average counts.
"""
logging.info('Field comparator: "%s"' % (self.description))
if (self.do_caching == False):
logging.info(' Caching is not activated')
elif (self.cache == {}):
logging.info(' Caching is activated but cache is empty')
else:
cache_size = len(self.cache)
cache_max_count = -1
cache_count_sum = 0.0
for cache_key in self.cache: # Get all cache entries and extract counts
(cache_weight, access_count) = self.cache[cache_key]
cache_max_count = max(cache_max_count, access_count)
cache_count_sum += access_count
cache_avrg_count = cache_count_sum / cache_size
cache_size_str = ' Number of cache entries: %s' % (cache_size)
if (self.max_cache_size == None):
cache_size_str += ' (Cache size is unlimited)'
else:
cache_size_str += ' (Cache size is limited to %d entries)' % \
(self.max_cache_size)
logging.info(cache_size_str)
logging.info(' Maximum and average cache entry count: %d / %.2f' % \
(cache_max_count, cache_avrg_count))
# =============================================================================
class FieldComparatorExactString(FieldComparator):
"""A field comparator based on exact string comparison.
"""
# ---------------------------------------------------------------------------
def __init__(self, **kwargs):
"""No additional attributes needed, just call base class constructor.
"""
FieldComparator.__init__(self, kwargs)
self.log() # Log a message
# ---------------------------------------------------------------------------
def compare(self, val1, val2):
"""Compare two field values using exact string comparator.
"""
# Check if one of the values is a missing value
#
if (val1 in self.missing_values) or (val2 in self.missing_values):
return self.missing_weight
elif (val1 == val2):
return self.__calc_freq_agree_weight__(val1)
else:
return self.disagree_weight
# =============================================================================
class FieldComparatorContainsString(FieldComparator):
"""A field comparator that checks if the shorter of two strings is contained
in the longer string.
Returns the agreement weight if the shorter string is contained in the
longer string and the dis-agreement weight otherwise.
"""
# ---------------------------------------------------------------------------
def __init__(self, **kwargs):
"""No additional attributes needed, just call base class constructor.
"""
FieldComparator.__init__(self, kwargs)
self.log() # Log a message
# ---------------------------------------------------------------------------
def compare(self, val1, val2):
"""Compare two field values checking if the shorter value is contained in
the longer value (both assumed to be strings).
"""
# Check if one of the values is a missing value
#
if (val1 in self.missing_values) or (val2 in self.missing_values):
return self.missing_weight
len1 = len(val1)
len2 = len(val2)
if (len1 < len2):
is_contained = (val1 in val2)
else:
is_contained = (val2 in val1)
if (is_contained == True):
return self.__calc_freq_agree_weight__(val1)
else:
return self.disagree_weight
# =============================================================================
class FieldComparatorTruncateString(FieldComparator):
"""A field comparator based on exact string comparison with the limitation in
number of characters that are compared (strings are truncated).
The additional argument (besides the base class arguments) which has to be
set when this field comparator is initialised is:
num_char_compared Positive integer that gives the number of characters
that are compared.
"""
# ---------------------------------------------------------------------------
def __init__(self, **kwargs):
"""Constructor. Process the 'num_char_compared' argument first, then call
the base class constructor.
"""
self.num_char_compared = None
# Process all keyword arguments
#
base_kwargs = {} # Dictionary, will contain unprocessed arguments for base
# class constructor
for (keyword, value) in kwargs.items():
if (keyword.startswith('num_char')):
auxiliary.check_is_integer('num_char_compared', value)
auxiliary.check_is_not_negative('num_char_compared', value)
self.num_char_compared = value
else:
base_kwargs[keyword] = value
FieldComparator.__init__(self, base_kwargs) # Process base arguments
# Make sure 'num_char_compared' attribute is set - - - - - - - - - - - - -
#
auxiliary.check_is_integer('num_char_compared', self.num_char_compared)
auxiliary.check_is_not_negative('num_char_compared', \
self.num_char_compared)
self.log([('Maximum number of characters compared',
self.num_char_compared)]) # Log a message
# ---------------------------------------------------------------------------
def compare(self, val1, val2):
"""Compare two field values using exact string comparator with truncated
strings.
"""
# Check if one of the values is a missing value
#
if (val1 in self.missing_values) or (val2 in self.missing_values):
return self.missing_weight
elif (val1 == val2):
return self.__calc_freq_agree_weight__(val1)
str1 = str(val1) # Make sure values are strings
str2 = str(val2)
if (str1[:self.num_char_compared] == str2[:self.num_char_compared]):
return self.__calc_freq_weights__(val1, val2)
else:
return self.disagree_weight
# =============================================================================
class FieldComparatorKeyDiff(FieldComparator):
"""A field comparator that compares the fields character-wise with a maximum
number of errors (different characters) being tolerated. This comparator
can be used to compare numerical fields, such as date of birth, telephone
numbers, etc.
The additional argument (besides the base class arguments) which has to be
set when this field comparator is initialised is:
max_key_diff Positive integer that gives the maximum number of
different characters tolerated.
For example, if 'max_key_diff' is set to X and the number of different
characters counted between two strings is Y (with 0 < Y <= X), then the
resulting partial agreement weight will be computed as:
weight = agree_weight - (Y/(X+1))*(agree_weight+abs(disagree_weight))
If the number of different characters counted is larger than X, the
disagreement weight will be returned.
"""
# ---------------------------------------------------------------------------
def __init__(self, **kwargs):
"""Constructor. Process the 'max_key_diff' argument first, then call the
base class constructor.
"""
self.max_key_diff = None
# Process all keyword arguments
#
base_kwargs = {} # Dictionary, will contain unprocessed arguments for base
# class constructor
for (keyword, value) in kwargs.items():
if (keyword.startswith('max_k')):
auxiliary.check_is_integer('max_key_diff', value)
auxiliary.check_is_not_negative('max_key_diff', value)
self.max_key_diff = value
else:
base_kwargs[keyword] = value
FieldComparator.__init__(self, base_kwargs) # Process base arguments
# Make sure 'max_key_diff' attribute is set - - - - - - - - - - - - - - - -
#
auxiliary.check_is_integer('max_key_diff', self.max_key_diff)
auxiliary.check_is_not_negative('max_key_diff', self.max_key_diff)
self.log([('Maximum key difference', self.max_key_diff)]) # Log a message
# ---------------------------------------------------------------------------
def compare(self, val1, val2):
"""Compare two field values using the key difference field comparator.
"""
# Check if one of the values is a missing value
#
if (val1 in self.missing_values) or (val2 in self.missing_values):
return self.missing_weight
elif (val1 == val2):
return self.__calc_freq_agree_weight__(val1)
# Calculate the key difference - - - - - - - - - - - - - - - - - - - - - -
#
str1 = str(val1) # Make sure values are strings
str2 = str(val2)
len1 = len(str1)
len2 = len(str2)
# The initial number of errors is the difference in the string lengths
#
num_err = abs(len1 - len2)
if (num_err > self.max_key_diff):
return self.disagree_weight # Too many different characters
check_len = min(len1, len2)
for i in range(check_len): # Loop over positions in strings
if (str1[i] != str2[i]):
num_err += 1
if (num_err > self.max_key_diff):
return self.disagree_weight # Too many different characters
# Get general or frequency based agreement weight
#
agree_weight = self.__calc_freq_weights__(val1, val2)
# Calculate partial agreement weight
#
return agree_weight - (float(num_err)/(self.max_key_diff+1.0)) * \
(agree_weight + abs(self.disagree_weight))
# =============================================================================
class FieldComparatorNumericPerc(FieldComparator):
"""A field comparator for numeric fields, where a given percentage difference
can be tolerated. The agreement weight is returned if the numbers are the
same, and the disagreement weight if the percentage difference is larger
than a maximum tolerated percentage value.
The additional argument (besides the base class arguments) which has to be
set when this field comparator is initialised is:
max_perc_diff A floating-point number between 0.0 and 100.0 giving the
maximum percentage difference tolerated.
If the percentage difference is smaller than 'max_perc_diff' the resulting
partial agreement weight is calculated according to the following formula:
weight = agree_weight - (perc_diff / (max_perc_diff + 1.0)) *
(agree_weight+abs(disagree_weight))
where the percentage difference is calculated as:
perc_diff = 100.0 *
abs(value_1 - value_2) / max(abs(value_1), abs(value_2))
"""
# ---------------------------------------------------------------------------
def __init__(self, **kwargs):
"""Constructor. Process the 'max_perc_diff' argument first, then call the
base class constructor.
"""
self.max_perc_diff = None
# Process all keyword arguments - - - - - - - - - - - - - - - - - - - - - -
#
base_kwargs = {} # Dictionary, will contain unprocessed arguments for base
# class constructor
for (keyword, value) in kwargs.items():