forked from munibanust/febrl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfebrl.py
More file actions
2338 lines (1916 loc) · 91.4 KB
/
febrl.py
File metadata and controls
2338 lines (1916 loc) · 91.4 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
# =============================================================================
# febrl.py - Main module and classes for febrl projects.
#
# Freely extensible biomedical record linkage (Febrl) Version 0.2.2
# See http://datamining.anu.edu.au/projects/linkage.html
#
# =============================================================================
# AUSTRALIAN NATIONAL UNIVERSITY OPEN SOURCE LICENSE (ANUOS LICENSE)
# VERSION 1.1
#
# The contents of this file are subject to the ANUOS License Version 1.1 (the
# "License"); you may not use this file except in compliance with the License.
# 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 "febrl.py".
# The Initial Developers of the Original Software are Dr Peter Christen
# (Department of Computer Science, Australian National University) and Dr Tim
# Churches (Centre for Epidemiology and Research, New South Wales Department
# of Health). Copyright (C) 2002, 2003 the Australian National University and
# others. All Rights Reserved.
# Contributors:
#
# =============================================================================
"""Module febrl.py - Main module and classes for febrl projects.
TODO
- Allow saving and loading not only of pickled project files, but also XML,
text, compressed and uncompressed, etc.
Then, do not restrict project files to have a '.fbl' extension, but list
all files found in a project directory (incl. their tyes)
Changes in Project.save() and Febrl.__init__() needed.
"""
# =============================================================================
# The following flags can be set to True or False
# They are used for testing the parallel functionalities of Febrl and should
# be set to False for normal use.
DO_PARALLEL_TEST = False # Perform several parallel tests of
# intermediate results
SAVE_PARALLEL_TEST_FILES = False # Write intermediate results to file for
# inspection
# =============================================================================
import cPickle
import os
import sys
import time
import traceback
import types
import copy
import parallel
import indexing
import output
import lap
# =============================================================================
class Febrl:
"""Class Febrl - Main class for Febrl projects.
"""
def __init__(self, **kwargs):
"""Constructor - Set attributes and load list of available projects.
"""
self.version_major = '0.2.2'
self.version_minor = ''
self.version = self.version_major+'.'+self.version_minor
self.license = 'ANUOS Version 1.1'
self.copyright = '(C) 2002, 2003 the Australian National ' + \
'University and others'
self.initial_developers = 'Dr Peter Christen (Department of Computer ' + \
'Science, Australian National University) ' + \
'and Dr Tim Churches (Centre for Epidemiology'+ \
' and Research, New South Wales Department ' + \
'of Health)'
self.contributors = ''
self.description = None
self.febrl_path = os.curdir # Default set to current directory
self.project_names = []
# Process all keyword arguments
#
for (keyword, value) in kwargs.items():
if (keyword == 'febrl_path'):
self.febrl_path = value
elif (keyword == 'description'):
self.description = value
else:
print 'error:Illegal constructor argument keyword: "%s"' % \
(str(keyword))
raise Exception
# Check if Febrl projects are available in the 'project_path' directory by
# scanning the directory for files with '.fbr' file extension
#
file_list = os.listdir(self.febrl_path)
for fn in file_list:
file_name = fn.strip().lower()
if (file_name[-4:] == '.fbr'):
self.project_names.append(file_name)
# ---------------------------------------------------------------------------
def __str__(self):
"""Create a string representation of the Febrl object.
"""
linesep = os.linesep
rep = 'Febrl (Freely extensible biomedical record linkage)' + linesep
rep += '---------------------------------------------------' + linesep
rep += linesep
rep += ' Version: ' + self.version + linesep
rep += ' License: ' + self.license + linesep
rep += ' Copyright: ' + self.copyright + linesep + linesep
rep += ' Initial developers: ' + self.initial_developers + linesep
rep += ' Contributors: ' + self.contributors + linesep + linesep
rep += 'Description: ' + str(self.description) + linesep
rep += 'Febrl path: ' + str(self.febrl_path) + linesep
rep += 'Avaliable projects:' + linesep
if (len(self.project_names) == 0):
rep += ' ' + str(None) + linesep
else:
i = 0
for pn in self.project_names:
rep += str(i).rjust(3) + ': ' + pn + linesep
i += 1
rep += linesep
return rep
# ---------------------------------------------------------------------------
def load_project(self, project, project_path=None):
"""Load a project from file.
A project can either be the file name as a string or the project
number (as stored in the list of project names).
"""
# Check project path - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
if (project_path == None): # No project path given, use default
file_name = self.febrl_path
else:
file_name = project_path
if (file_name[-1] != os.sep):
file_name += os.sep # Make sure path ends with a directory separator
# Check input argument type - - - - - - - - - - - - - - - - - - - - - - - -
#
if (type(project) == types.IntType):
try:
file_name += self.project_names[project] # Get project file name
except:
print 'error:Illegal project number: %s' % (str(project))
raise Exception
elif (type(project) == types.StringType):
file_name += project
else:
print 'error:Illegal type for "project" argument, must be either of ' + \
'type string or integer'
raise Exception
# Open project file and load it - - - - - - - - - - - - - - - - - - - - - -
#
f = open(file_name,'r')
loaded_project = cPickle.loads(f.read())
f.close()
loaded_project.febrl = self
return loaded_project
# ---------------------------------------------------------------------------
def new_project(self, **kwargs):
"""Create a new project object and populate it.
"""
new_project = Project(self, **kwargs)
return new_project
# ---------------------------------------------------------------------------
def finalise(self):
"""Finalise a Febrl project.
"""
print '1:'
print '1:Febrl stopped.'
parallel.Barrier() # Make sure all processes are here
parallel.Finalize() # Finalise parallel environment
sys.exit()
# =============================================================================
class Project:
"""Class for record linkage projects.
"""
# ---------------------------------------------------------------------------
def __init__(self, febrl, **kwargs):
"""Constructor - Create a new project object.
"""
self.febrl = febrl
self.name = ''
self.description = ''
self.file_name = None
self.project_path = febrl.febrl_path # Inherit path
self.block_size = 10000 # File blocking size (in number of records)
self.parallel_write = 'host' # Set either to 'host' (default) or 'all'
for (keyword, value) in kwargs.items():
if (keyword == 'name'):
self.name = value
elif (keyword == 'description'):
self.description = value
elif (keyword == 'file_name'):
self.file_name = value
elif (keyword == 'project_path'):
self.project_path = value
elif (keyword == 'block_size'):
if (not isinstance(value, int)) and (value > 0):
print 'error:Argument "block_size" is not a positive integer'
raise Exception
self.block_size = value
elif (keyword == 'parallel_write'):
if (value not in ['host','all']):
print 'error:Argument "parallel_write" must be set to "host"'+ \
' or "all"'
raise Exception
self.parallel_write = value
else:
print 'error:Illegal constructor argument keyword: "%s"' % \
(str(keyword))
raise Exception
# Set the parallel writing/saving mode - - - - - - - - - - - - - - - - - -
#
parallel.writemode = self.parallel_write
# ---------------------------------------------------------------------------
def __str__(self):
"""Create a string representation for this project.
"""
linesep = os.linesep
rep = linesep + 'Febrl project: "'+self.name + '"' + linesep
rep += ' Description: ' + self.description + linesep
rep += ' Filename: ' + self.file_name + linesep
rep += ' Project path: ' + self.project_path + linesep
return rep
# ---------------------------------------------------------------------------
def save(self, path=None):
"""Save the project into a file (currently a pickled file).
"""
if (path is None):
path = self.project_path # Take the project's path
if (path[-1] != os.sep):
path += os.sep # Make sure path ends with a directory separator
# Unset the current febrl object
#
save_febrl = copy.copy(self.febrl) # Make a deep copy first
self.febrl = None
file_name = path + self.file_name
f = open(file_name, 'w+')
f.write(cPickle.dumps(self, 1))
f.close()
# Restore febrl object
#
self.febrl = save_febrl
# ---------------------------------------------------------------------------
def standardise(self, **kwargs):
"""Clean and standardise the given data set using the defined record
standardiser.
Records are loaded block wise from the input data set, then standardised
and written into the output data set.
If the argument 'first_record' is not given, it will automatically be
set to the first record in the data set (i.e. record number 0).
Similarly, if the argument 'number_records' is not given, it will be set
to the total number of records in the input data set.
The output data set can be any data set type except a memory based data
set (as all standardised records would lost once the program finishes).
This output data set has to be initialised in 'write', 'append' or
'readwrite' access mode.
"""
self.input_dataset = None # A reference ot the (raw) input data set
# data set
self.output_dataset = None # A reference to the output data set
self.rec_standardiser = None # Reference to a record standardiser
self.first_record = None # Number of the first record to process
self.number_records = None # Number of records to process
for (keyword, value) in kwargs.items():
if (keyword == 'input_dataset'):
self.input_dataset = value
elif (keyword == 'output_dataset'):
self.output_dataset = value
elif (keyword == 'rec_standardiser'):
self.rec_standardiser = value
elif (keyword == 'first_record'):
if (not isinstance(value, int)) or (value < 0):
print 'error:Argument "first_record" is not a valid integer number'
raise Exception
self.first_record = value
elif (keyword == 'number_records'):
if (not isinstance(value, int)) or (value <= 0):
print 'error:Argument "number_records" is not a positive integer '+ \
'number'
raise Exception
self.number_records = value
else:
print 'error:Illegal constructor argument keyword: "%s"' % \
(str(keyword))
raise Exception
# Do some checks on the input arguments - - - - - - - - - - - - - - - - - -
#
if (self.input_dataset == None):
print 'error:Input data set is not defined'
raise Exception
if (self.output_dataset == None):
print 'error:Output data set is not defined'
raise Exception
elif (self.output_dataset.dataset_type == 'MEMORY'):
print 'error:Output data set can not be a memory based data set'
raise Exception
if (self.output_dataset.access_mode not in ['write','append','readwrite']):
print 'error:Output dataset must be initialised in one of the access' + \
' modes: "write", "append", or "readwrite"'
raise Exception
if (self.rec_standardiser == None):
print 'error:Record standardiser is not defined'
raise Exception
if (self.first_record == None):
self.first_record = 0 # Take default first record in data set
if (self.number_records == None): # Process all records
self.number_records = self.input_dataset.num_records
print '1:'
print '1:***** Standardise data set: "%s" (type "%s")' % \
(self.input_dataset.name, self.input_dataset.dataset_type)
print '1:***** into data set: "%s" (type "%s")' % \
(self.output_dataset.name, self.output_dataset.dataset_type)
print '1:'
# Call the main standardisation routine - - - - - - - - - - - - - - - - - -
# (no indexing will be done)
#
[stand_time, comm_time] = do_load_standard_indexing(self.input_dataset,
self.output_dataset,
self.rec_standardiser,
None,
self.first_record,
self.number_records,
self.block_size)
# ---------------------------------------------------------------------------
def deduplicate(self, **kwargs):
"""Deduplicate the given data set using the defined record standardiser,
record comparators, blocking indexes and classifiers.
Records are loaded block wise from the input data set, then standardised
(if the record standardiser is defined, otherwise the input data set is
directly deduplicated), linked and the results are printed and/or saved
into the result file(s).
If the argument 'first_record' is not given, it will automatically be
set to the first record in the data set (i.e. record number 0).
Similarly, if the argument 'number_records' is not given, it will be set
to the total number of records in the input data set.
The temporary data set must be a random acces data set implementation,
i.e. either a Shelve or a Memory data set. For large data set it is
recommended to use a Shelve data set. This temporary data set has to be
initialised in access mode 'readwrite'.
Currently, the output can be a printed or saved list of record pairs in
both a detailed and condensed form (if the arguments
'output_rec_pair_details' and 'output_rec_pair_weights' are set to
'True' or to a file name (a string). The output can be filtered by
setting the 'output_threshold' (meaning all record pairs with a weight
less then this threshold are not printed or saved).
In future versions, it will be possible to compile an output data set.
A histogram can be saved or printed by setting the argument
'output_histogram' to 'True' or to a file name.
It is also possible to apply a one-to-one assignment procedure by
setting the argument 'output_assignment' to 'one2one'.
"""
self.input_dataset = None # A reference ot the (raw) input data set
self.tmp_dataset = None # A reference to a temporary (random access)
# data set
# self.output_dataset = None # A reference to the output data set
self.rec_standardiser = None # Reference to a record standardiser
self.rec_comparator = None # Reference to a record comparator
self.blocking_index = None # Reference to a blocking index
self.classifier = None # Reference to a weight vector classifier
self.first_record = None # Number of the first record to process
self.number_records = None # Number of records to process
self.output_histogram = False # Set to True, a file name or False
# (default) if a histogram of weights
# should be printed or saved
self.output_rec_pair_details = False # Set to True, a file name or False
# (default) if record pairs should
# be printed or saved in details
self.output_rec_pair_weights = False # Set to True, a file name or False
# (default) if record pairs should
# be printed or saved with weights
self.output_threshold = None # Set to a weight threshold (only
# record pairs with weights equal to
# or above will be saved and or
# printed)
self.output_assignment = None # Set to 'one2one' if one-to-one
# assignment should be forced
# (default: None)
for (keyword, value) in kwargs.items():
if (keyword == 'input_dataset'):
self.input_dataset = value
elif (keyword == 'tmp_dataset'):
self.tmp_dataset = value
# elif (keyword == 'output_dataset'):
# self.output_dataset = value
elif (keyword == 'rec_standardiser'):
self.rec_standardiser = value
elif (keyword == 'rec_comparator'):
self.rec_comparator = value
elif (keyword == 'blocking_index'):
self.blocking_index = value
elif (keyword == 'classifier'):
self.classifier = value
elif (keyword == 'first_record'):
if (not isinstance(value, int)) or (value < 0):
print 'error:Argument "first_record" is not a valid integer number'
raise Exception
self.first_record = value
elif (keyword == 'number_records'):
if (not isinstance(value, int)) or (value <= 0):
print 'error:Argument "number_records" is not a positive integer '+ \
'number'
raise Exception
self.number_records = value
elif (keyword == 'output_rec_pair_details'):
if (not isinstance(value, str)) and (value not in [True, False]):
print 'error:Argument "output_rec_pair_details" must be ' + \
'a file name or "True" or "False"'
raise Exception
self.output_rec_pair_details = value
elif (keyword == 'output_rec_pair_weights'):
if (not isinstance(value, str)) and (value not in [True, False]):
print 'error:Argument "output_rec_pair_weights" must be ' + \
'a file name or "True" or "False"'
raise Exception
self.output_rec_pair_weights = value
elif (keyword == 'output_histogram'):
if (not isinstance(value, str)) and (value not in [True, False]):
print 'error:Argument "output_histogram" must be ' + \
'a file name or "True" or "False"'
raise Exception
self.output_histogram = value
elif (keyword == 'output_threshold'):
if (not (isinstance(value, int) or isinstance(value, float))):
print 'error:Argument "output_threshold" is not a number: %s' % \
(str(value))
self.output_threshold = value
elif (keyword == 'output_assignment'):
if (value not in ['one2one', None]):
print 'error:Illegal value for argument "output_assignment": %s' % \
(str(value))
raise Exception
else:
self.output_assignment = value
else:
print 'error:Illegal constructor argument keyword: "%s"' % \
(str(keyword))
raise Exception
# Do some checks on the input arguments - - - - - - - - - - - - - - - - - -
#
if (self.input_dataset == None):
print 'error:Input data set is not defined'
raise Exception
if (self.tmp_dataset == None):
print 'error:Temporary data set is not defined'
raise Exception
elif (self.tmp_dataset.dataset_type not in ['SHELVE', 'MEMORY']):
print 'error:Temporary data set must be a random access data set' + \
' (either Shelve or Memory)'
raise Exception
if (self.tmp_dataset.access_mode not in ['write','append','readwrite']):
print 'error:Temporary data set must be initialised in one of the ' + \
'access modes: "write", "append", or "readwrite"'
raise Exception
# if (self.output_dataset == None):
# print 'error:Output data set is not defined'
# raise Exception
# Make sure at least one output is defined
#
if (self.output_rec_pair_weights == False) and \
(self.output_rec_pair_details == False) and \
(self.output_histogram == False):
print 'error:No ouput of results is defined.'
raise Exception
#
# Code above to be removed once output data set functionality implemented
if (self.first_record == None):
self.first_record = 0 # Take default first record in data set
if (self.number_records == None): # Process all records
self.number_records = self.input_dataset.num_records
if (self.rec_comparator == None):
print 'error:No record comparator defined'
raise Exception
if (self.rec_comparator.dataset_a != self.tmp_dataset) or \
(self.rec_comparator.dataset_b != self.tmp_dataset):
print 'error:Illegal data set definition in record comparator'
raise Exception
if (self.blocking_index == None):
print 'error:No blocking index defined'
raise Exception
if (self.classifier == None):
print 'error:No classifier defined'
raise Exception
if (self.classifier.dataset_a != self.tmp_dataset) or \
(self.classifier.dataset_b != self.tmp_dataset):
print 'error:Illegal data set definition in classifier'
raise Exception
total_time = time.time() # Get current time
print '1:'
print '1:***** Deduplicate data set: "%s" (type "%s")' % \
(self.input_dataset.name, self.input_dataset.dataset_type)
print '1:***** Temporary data set: "%s" (type "%s")' % \
(self.tmp_dataset.name, self.tmp_dataset.dataset_type)
print '1:'
print '1:Step 1: Loading, standardisation and indexing'
print '1:-------'
print '1:'
step_1_time = time.time() # Get current time
# Call the main standardisation routine - - - - - - - - - - - - - - - - - -
#
[p, step_1_comm_time] = do_load_standard_indexing(self.input_dataset,
self.tmp_dataset,
self.rec_standardiser,
self.blocking_index,
self.first_record,
self.number_records,
self.block_size)
# If Febrl is run in parallel, collect blocking index in process 0 - - - -
#
if (parallel.rank() == 0):
for p in range(1, parallel.size()):
tmp_time = time.time()
tmp_indexes = parallel.receive(p)
step_1_comm_time += (time.time() - tmp_time)
print '1: Received index from process %i' % (p)
self.blocking_index.merge(tmp_indexes)
else: # Send index to process 0
tmp_time = time.time()
parallel.send(self.blocking_index.index, 0) # Send indexes to process 0
step_1_comm_time += (time.time() - tmp_time)
print '1: Sent index to process 0'
# If run in parallel, broadcast the blocking index from process 0 - - - - -
#
if (parallel.size() > 1):
if (parallel.rank() == 0):
for p in range(1, parallel.size()):
tmp_time = time.time()
parallel.send(self.blocking_index.index, p)
step_1_comm_time += (time.time() - tmp_time)
print '1: Sent index to process %i' % (p)
else:
tmp_time = time.time()
tmp_indexes = parallel.receive(0)
step_1_comm_time += (time.time() - tmp_time)
print '1: Received index from process 0'
self.blocking_index.merge(tmp_indexes)
# Compact the blocking index - - - - - - - - - - - - - - - - - - - - - - -
#
self.blocking_index.compact()
step_1_time = time.time() - step_1_time # Calculate time for step 1
step_1_time_string = output.time_string(step_1_time)
print '1:'
print '1:Step 1 finished in %s' % (step_1_time_string)
# End of step 1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
parallel.Barrier() # Make sure all processes are here
# Now re-initialise the temporary data set in read access mode only - - - -
#
self.tmp_dataset.re_initialise('read')
#################### START PARALLEL TEST CODE #############################
# Save temporary data sets and indexes to files (on all processes)
#
if (SAVE_PARALLEL_TEST_FILES == True):
#f = open('tmp_data_set-dedup-'+str(parallel.rank())+'-'+ \
# str(parallel.size()),'w')
#tmp_list = self.tmp_dataset.dict.keys()
#tmp_list.sort()
#for r in tmp_list:
# rec = self.tmp_dataset.dict[r]
# rec_items = rec.items()
# rec_items.sort()
# rec = str(r)+': '+str(rec_items)
# f.write(rec+os.linesep)
#f.close()
f = open('indexes-dedup-'+str(parallel.rank())+'-'+ \
str(parallel.size()),'w')
for i in range (self.blocking_index.num_indexes):
tmp_index = self.blocking_index.index[i].keys()
tmp_index.sort()
for bi in tmp_index:
ind = self.blocking_index.index[i][bi]
ind_list = ind.items()
ind_list.sort()
ii = str(i)+'_'+str(bi)+': '+str(ind_list)
f.write(ii+os.linesep)
f.close()
#################### END PARALLEL TEST CODE ###############################
print '1:'
print '1:Step 2: Perform deduplication within blocks'
print '1:-------'
print '1:'
step_2_time = time.time() # Get current time
step_2_comm_time = 0.0
# Get the record pairs which have to be compared - - - - - - - - - - - - -
#
tmp_time = time.time()
[rec_pair_dict, rec_pair_cnt] = \
indexing.deduplication_rec_pairs(self.blocking_index)
rec_pair_time = time.time() - tmp_time
rec_pair_time_string = output.time_string(rec_pair_time)
print '1:'
print '1: Built record pair dictionary with %i entries in %s' % \
(rec_pair_cnt, rec_pair_time_string)
# And do the comparisons of record pairs into classifer - - - - - - - - - -
#
[p] = do_comparison(self.tmp_dataset, self.tmp_dataset,
self.rec_comparator, self.classifier,
rec_pair_dict, rec_pair_cnt, self.block_size)
# Now gather classifier results on process 0 and merge - - - - - - - - - -
#
if (parallel.size() > 1):
if (parallel.rank() == 0):
for p in range(1, parallel.size()):
tmp_time = time.time()
tmp_classifier_results = parallel.receive(p)
step_2_comm_time += (time.time() - tmp_time)
print '1: Received classifier from process %i and merged it' % (p)
self.classifier.merge(tmp_classifier_results)
else:
tmp_time = time.time()
parallel.send(self.classifier.results, 0) # Send classifier results to
# process 0
step_2_comm_time += (time.time() - tmp_time)
print '1: Sent classifier to process 0'
# If run in parallel, broadcast the classifier results from process 0 - - -
#
if (parallel.size() > 1):
if (parallel.rank() == 0):
for p in range(1, parallel.size()):
tmp_time = time.time()
parallel.send(self.classifier.results, p)
step_2_comm_time += (time.time() - tmp_time)
print '1: Sent classifier to process %i' % (p)
else:
tmp_time = time.time()
self.classifier.results = parallel.receive(0)
step_2_comm_time += (time.time() - tmp_time)
print '1: Received classifier from process 0'
#################### START PARALLEL TEST CODE #############################
# Save classifiers and weight vectors to files (only process 0)
#
if (SAVE_PARALLEL_TEST_FILES == True):
tmp_list = rec_pair_dict.keys()
tmp_list.sort()
f = open('rec-pair-dict-dedup-'+str(parallel.rank())+'-'+ \
str(parallel.size()),'w')
for rp in tmp_list:
rec_list = rec_pair_dict[rp].items()
rec_list.sort()
r = str(rp)+': '+str(rec_list)
f.write(r+os.linesep)
f.close()
tmp_list = self.classifier.results.keys()
tmp_list.sort()
f = open('classifier_results_dict-dedup-'+str(parallel.rank())+'-'+ \
str(parallel.size()),'w')
for c in tmp_list:
res = self.classifier.results[c].items()
res.sort()
ce = str(c)+': '+str(res)
f.write(ce+os.linesep)
f.close()
#################### END PARALLEL TEST CODE ###############################
step_2_time = time.time() - step_2_time # Calculate time for step 2
step_2_time_string = output.time_string(step_2_time)
print '1:'
print '1:Step 2 (deduplication) finished in %s' % (step_2_time_string)
print '1: Totally %i record pair comparisons' % (rec_pair_cnt)
# Output the results - - - - - - - - - - - - - - - - - - - - - - - - - - -
print '1:'
print '1:Step 3: Output and assignment procedures'
print '1:-------'
print '1:'
step_3_time = time.time() # Get current time
# Get the results dictionary with all the record pairs and their weights
#
results_dict = self.classifier.results
if (results_dict == {}):
print 'warning:Results dictionary empty'
else: # There are results
# Do assignment restrictions if they are defined - - - - - - - - - - - -
#
if (self.output_assignment != None): # An output assignment is defined
if (self.output_assignment == 'one2one'):
# Do a one-to-one assignment on the classifier results dict
#
o2o_results_dict = lap.do_lap('auction', results_dict, \
'deduplication', self.output_threshold)
else: # No one-to-one assignment, set one2one result to None
o2o_results_dict = None
#################### START PARALLEL TEST CODE ###########################
if (SAVE_PARALLEL_TEST_FILES == True):
tmp_list = o2o_results_dict.items()
tmp_list.sort()
f = open('one2one-dedup-'+str(parallel.rank())+'-'+ \
str(parallel.size()),'w')
for c in tmp_list:
f.write(str(c)+os.linesep)
f.close()
#################### END PARALLEL TEST CODE #############################
if (parallel.rank() == 0): # Only processor 0 prints results
# Print or save weights histogram - - - - - - - - - - - - - - - - - - -
#
if (self.output_histogram == True):
output.histogram(results_dict)
elif (self.output_histogram != False):
output.histogram(results_dict, self.output_histogram)
# Print or save detailed record pairs - - - - - - - - - - - - - - - - -
#
if (self.output_rec_pair_details == True):
output.rec_pair_details(self.tmp_dataset, self.tmp_dataset,
results_dict, o2o_results_dict,
self.output_threshold)
elif (self.output_rec_pair_details != False):
output.rec_pair_details(self.tmp_dataset, self.tmp_dataset,
results_dict, o2o_results_dict,
self.output_threshold,
self.output_rec_pair_details)
# Print or save record pairs with weights - - - - - - - - - - - - - - -
#
if (self.output_rec_pair_weights == True):
output.rec_pair_weights(self.tmp_dataset.name,
self.tmp_dataset.name,
results_dict, o2o_results_dict,
self.output_threshold)
elif (self.output_rec_pair_weights != False):
output.rec_pair_weights(self.tmp_dataset.name,
self.tmp_dataset.name,
results_dict, o2o_results_dict,
self.output_threshold,
self.output_rec_pair_weights)
step_3_time = time.time() - step_3_time # Calculate time for step 3
step_3_time_string = output.time_string(step_3_time)
print '1:'
print '1:Step 3 (output and assignments) finished in %s' % \
(step_3_time_string)
print '1:'
parallel.Barrier() # Wait here for all processes - - - - - - - - - - - - -
total_time = time.time() - total_time # Calculate total time
total_time_string = output.time_string(total_time)
step_1_comm_time_string = output.time_string(step_1_comm_time)
step_2_comm_time_string = output.time_string(step_2_comm_time)
print '1:Total time needed for deduplication of %i records: %s' % \
(self.number_records, total_time_string)
print '1: Time for step 1 (standardisation): %s' % \
(step_1_time_string)
print '1: Time for step 2 (deduplication): %s' % \
(step_2_time_string)
print '1: Time for step 3 (assignment and output): %s' % \
(step_3_time_string)
print '1: Time for communication in step 1: %s' % \
(step_1_comm_time_string)
print '1: Time for communication in step 2: %s' % \
(step_2_comm_time_string)
# ---------------------------------------------------------------------------
def link(self, **kwargs):
"""Link the given two data set using the defined record standardisers,
record comparators, blocking indexes and classifiers.
Records are loaded block wise from the input data sets, then
standardised (if the record standardisers are defined, otherwise an
input data set is directly taken for the linkage process), linked and
the results are printed and/or saved into the result file(s).
If the arguments 'first_record_a' and/or 'first_record_b' are not given,
they will automatically be set to the first record in the data sets
(i.e. record number 0). Similarly, if the arguments 'number_records_a'
and/or 'number_records_b' are not given, they will be set to the total
number of records in the input data sets.
The temporary data sets must be random acces data set implementations,
i.e. either Shelve or a Memory data sets. For large data set it is
recommended to use Shelve data sets. This temporary data sets have to be
initialised in access mode 'readwrite'.
Currently, the output can be a printed or saved list of record pairs in
both a detailed and condensed form (if the arguments
'output_rec_pair_details' and 'output_rec_pair_weights' are set to
'True' or to a file name (a string). The output can be filtered by
setting the 'output_threshold' (meaning all record pairs with a weight
less then this threshold are not printed or saved).
In future versions, it will be possible to compile an output data set.
A histogram can be saved or printed by setting the argument
'output_histogram' to 'True' or to a file name.
It is also possible to apply a one-to-one assignment procedure by
setting the argument 'output_assignment' to 'one2one'.
"""
self.input_dataset_a = None # A reference to the first input data set
self.tmp_dataset_a = None # A reference to the first temporary
# (random access) data set
self.input_dataset_b = None # A reference ot the second input data set
self.tmp_dataset_b = None # A reference to the second temporary
# (random access) data set
# self.output_dataset = None # A reference to the output data set
self.rec_standardiser_a = None # Reference to a record standardiser for
# the first data set (A)
self.rec_standardiser_b = None # Reference to a record standardiser for
# the second data set (B)
self.blocking_index_a = None # Reference to a blocking index for data
# the first set (A)
self.blocking_index_b = None # Reference to a blocking index for data
# the second set (B)
self.rec_comparator = None # Reference to a record comparator
self.classifier = None # Reference to a weight vector classifier
self.first_record_a = None # Number of the first record to process
# in the first data set (A)
self.number_records_a = None # Number of records to process in the
# first data set (A)
self.first_record_b = None # Number of the first record to process
# in the second data set (B)
self.number_records_b = None # Number of records to process in the
# second data set (B)
self.output_histogram = False # Set to True, a file name or False
# (default) if a histogram of weights
# should be printed or saved
self.output_rec_pair_details = False # Set to True, a file name or False
# (default) if record pairs should
# be printed or saved in details
self.output_rec_pair_weights = False # Set to True, a file name or False
# (default) if record pairs should
# be printed or saved with weights
self.output_threshold = None # Set to a weight threshold (only
# record pairs with weights equal to
# or above will be saved and or
# printed)
self.output_assignment = None # Set to 'one2one' if one-to-one
# assignment should be forced
# (default: None)
for (keyword, value) in kwargs.items():
if (keyword == 'input_dataset_a'):
self.input_dataset_a = value
elif (keyword == 'input_dataset_b'):
self.input_dataset_b = value
elif (keyword == 'tmp_dataset_a'):
self.tmp_dataset_a = value
elif (keyword == 'tmp_dataset_b'):