-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgenerate.py
1826 lines (1457 loc) · 66.3 KB
/
generate.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: "generate.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 generate.py - Auxiliary program to create records using various
frequency tables and introduce duplicates with errors.
USAGE:
python generate.py [output_file] [num_originals] [num_duplicates]
[max_duplicate_per_record] [max_modification_per_field]
[max_modification_per_record] [distribution]
ARGUMENTS:
output_file Name of the output file (currently this is a
CSV file).
num_originals Number of original records to be created.
num_duplicates Number of duplicate records to be created
(maximum number is 9).
max_duplicate_per_record The maximal number of duplicates that can be
created for one original record.
max_modification_per_field The maximum number of modifications per field
max_modification_per_record The maximum number of modifications per
record.
distribution The probability distribution used to create
the duplicates (i.e the number of duplicates
for one original).
Possible are: - uniform
- poisson
- zipf
DESCRIPTION:
This program can be used to create a data set with records that contain
randomly created names and addresses (using frequency files), dates,
phone numbers, and identifier numbers. Duplicate records will then be
created following a given probability distribution, with different single
errors being introduced.
Various parameters on how theses duplicates are created can be given
within the program, see below.
New: It is possible to load dictionaries (look-up table) with misspellings
that will be used to replace a correct word with a randomly chosen
misspelling. A user can easily customise this misspelling files.
TODO:
- add substitution matrix with character substitution probabilities
(instead of keyboard based substitutions).
- Improve performance (loading and creating frequency tables)
- for each field have a counter num_modifcations in the field dictionary
- do swap between field first (count as 2 rec. modifications)
- Allow various probability distributions for fields of type 'date' and
'iden' (using a new keyword in field dictionaries).
- Try to find real world error distributions for typographical errors and
integrate them into the random error creation
- Add random word spilling between fields (similar to field swapping)
"""
# =============================================================================
# Imports go here
import math
import os
import random
import sets
import string
import sys
import time
import pandas as pd
import re
# Set this flag to True for verbose output, otherwise to False - - - - - - - -
#
VERBOSE_OUTPUT = True
# =============================================================================
#
# For each field (attribute), a dictionary has to be defined with the following
# keys (probabilities can have values between 0.0 and 1.0, or they can be
# missing - in which case it is assumed they have a value of 0.0):
# - name The field name to be used when a header is written into the
# output file.
# - type The type of the field. Possible are:
# 'freq' (for fields that use a frequency table with field
# values)
# 'date' (for date fields in a certain range)
# 'phone' (for phone numbers)
# 'ident' (for numerical identifier fields in a certain range)
# - char_range The range of random characters that can be introduced. Can
# be one of 'alpha', 'digit', or 'alphanum'.
#
# For fields of type 'freq' the following keys must be given:
# - freq_file The name of a frequency file.
# - misspell_file The name of a misspellings file.
#
# For fields of type 'date' the following keys must be given:
# - start_date A start date, must be a tuple (day,month,year).
# - end_date A end date, must be a tuple (day,month,year).
#
# For fields of type 'phone' the following keys must be given:
# - area_codes A list with possible area codes (as strings).
# - num_digits The number of digits in the phone numbers (without the area
# code).
#
# For fields of type 'ident' the following keys must be given:
# - start_id A start identification number.
# - end_id An end identification number.
#
# For all fields the following keys must be given:
# - select_prob Probability of selecting a field for introducing one or
# more modifications (set this to 0.0 if no modifications
# should be introduced into this field ever). Note: The sum
# of these select probabilities over all defined fields must
# be 100.
# - misspell_prob Probability to swap an original value with a randomly
# chosen misspelling from the corresponding misspelling
# dictionary (can only be set to larger than 0.0 if such a
# misspellings dictionary is defined for the given field).
# - ins_prob Probability to insert a character into a field value.
# - del_prob Probability to delete a character from a field value.
# - sub_prob Probability to substitute a character in a field value with
# another character.
# - trans_prob Probability to transpose two characters in a field value.
# - val_swap_prob Probability to swap the value in a field with another
# (randomly selected) value for this field (taken from this
# field's look-up table).
# - wrd_swap_prob Probability to swap two words in a field (given there are
# at least two words in a field).
# - spc_ins_prob Probability to insert a space into a field value (thus
# splitting a word).
# - spc_del_prob Probability to delete a space (if available) in a field (and
# thus merging two words).
# - miss_prob Probability to set a field value to missing (empty).
# - new_val_prob Probability to insert a new value given the original value
# was empty.
#
# Note: The sum over the probabilities ins_prob, del_prob, sub_prob,
# trans_prob, val_swap_prob, wrd_swap_prob, spc_ins_prob, spc_del_prob,
# and miss_prob for each defined field must be 1.0; or 0.0 if no
# modification should be done at all on a given field.
#
# =============================================================================
# Comments about typographical errors and misspellings found in the literature:
#
# Damerau 1964: - 80% are single errors: insert, delete, substitute or
# transpose
# - Statistic given: 567/964 (59%) substitutions
# 153/964 (16%) deletions
# 23/964 ( 2%) transpositions
# 99/964 (10%) insertions
# 122/964 (13%) multiple errors
#
# Hall 1980: - OCR and other automatic devices introduce similar errors of
# substitutions, deletions and insertions, but not transpositions;
# frequency and type of errors are characteristics of the device.
#
# Pollock/Zamora 1984: - OCR output contains almost exclusively substitution
# errors which ordinarily account for less than 20% of
# key boarded misspellings.
# - 90-95% of misspellings in raw keyboarding typically
# only contain one error.
# - Only 7.8% of the first letter of misspellings were
# incorrect, compared to 11.7% of the second and 19.2%
# of the third.
# - Generally assumed that vowels are less important than
# consonants.
# - The frequency of a misspelling seems to be determined
# more by the frequency of it's parent word than by the
# difficulty of spelling it.
# - Most errors are mechanical (typos), not the result of
# poor spelling.
# - The more frequent a letter, the more likely it is to
# be miskeyed.
# - Deletions are similar frequent than transpositions,
# but more frequent than insertions and again more
# frequent than substitutions.
#
# Pollock/Zamora 1983: - Study of 50,000 nonword errors, 3-4 character
# misspellings constitute only 9.2% of total
# misspellings, but they generate 40% of miscorrections.
#
# Peterson 1986: In two studies:
# - Transpose two letters: 2.6% / 13.1%
# - Insert letter: 18.7% / 20.3%
# - Delete letter: 31.6% / 34.4%
# - Substitute letter: 40.0% / 26.9%
#
# Kukich 1990: - Over 63% of errors in TDD conversations occur in words of
# length 2, 3 or 4.
#
# Kukich 1992: - 13% of non-word spelling errors in a 40,000 corpus of typed
# conversations involved merging of two words, 2% splitting a
# word (often at valid forms, "forgot" -> "for got").
# - Most misspellings seem to be within two characters in length
# of the correct spelling.
#
# =============================================================================
# Other comments:
#
# - Intuitively, one can assume that long and unfrequent words are more likely
# to be misspelt than short and common words.
#
# =============================================================================
company_name_stn_dict = {'name':'company_name_stn',
'type':'freq',
'char_range':'alphanum',
'freq_file':'data'+os.sep+'company_name_stn-freq.csv',
'select_prob':0.25,
# 'misspell_file':'data'+os.sep+'stn_name-misspell.tbl',
'misspell_prob':0.30,
'ins_prob':0.05,
'del_prob':0.15,
'sub_prob':0.35,
'trans_prob':0.05,
'val_swap_prob':0.02,
'wrd_swap_prob':0.02,
'spc_ins_prob':0.01,
'spc_del_prob':0.01,
'miss_prob':0.02,
'new_val_prob':0.02}
streetnumber1_dict = {'name':'street_number1',
'type':'freq',
'char_range':'digit',
'freq_file':'data'+os.sep+'street_number1-freq.csv',
'select_prob':0.25 ,
'ins_prob':0.10,
'del_prob':0.15,
'sub_prob':0.60,
'trans_prob':0.05,
'val_swap_prob':0.05,
'wrd_swap_prob':0.01,
'spc_ins_prob':0.00,
'spc_del_prob':0.00,
'miss_prob':0.02,
'new_val_prob':0.02}
address1_dict = {'name':'address1',
'type':'freq',
'char_range':'alphanum',
'freq_file':'data'+os.sep+'address1-freq.csv',
'select_prob':0.15,
'ins_prob':0.10,
'del_prob':0.15,
'sub_prob':0.55,
'trans_prob':0.05,
'val_swap_prob':0.02,
'wrd_swap_prob':0.03,
'spc_ins_prob':0.02,
'spc_del_prob':0.03,
'miss_prob':0.04,
'new_val_prob':0.01}
city1_dict = {'name':'city1',
'type':'freq',
'char_range':'alpha',
'freq_file':'data'+os.sep+'city1-freq.csv',
'select_prob':0.10,
# 'misspell_file':'data'+os.sep+'city1-misspell.tbl',
'misspell_prob':0.4,
'ins_prob':0.10,
'del_prob':0.15,
'sub_prob':0.22,
'trans_prob':0.04,
'val_swap_prob':0.01,
'wrd_swap_prob':0.02,
'spc_ins_prob':0.02,
'spc_del_prob':0.02,
'miss_prob':0.01,
'new_val_prob':0.01}
state1_dict = {'name':'state1',
'type':'freq',
'char_range':'alpha',
'freq_file':'data'+os.sep+'state1-freq.csv',
'select_prob':0.15,
'ins_prob':0.00,
'del_prob':0.00,
'sub_prob':0.00,
'trans_prob':0.00,
'val_swap_prob':0.00, # to do: make a table of substitution probabilities for states
'wrd_swap_prob':0.00,
'spc_ins_prob':0.00,
'spc_del_prob':0.00,
'miss_prob':1.00,
'new_val_prob':0.00}
zip1_dict = {'name':'zip1',
'type':'freq',
'char_range':'digit',
'freq_file':'data'+os.sep+'zip1-freq.csv',
'select_prob':0.10,
'ins_prob':0.00,
'del_prob':0.00,
'sub_prob':0.35,
'trans_prob':0.35,
'val_swap_prob':0.00,
'wrd_swap_prob':0.00,
'spc_ins_prob':0.00,
'spc_del_prob':0.00,
'miss_prob':0.28,
'new_val_prob':0.02}
# -----------------------------------------------------------------------------
# Probabilities (between 0.0 and 1.0) for swapping values between two fields.
# Use field names as defined in the field directories (keys 'name').
field_swap_prob ={}# {('city1', 'state1'):0.02}
# -----------------------------------------------------------------------------
# Probabilities (between 0.0 and 1.0) for creating a typographical error (a new
# character) in the same row or the same column. This is used in the random
# selection of a new character in the 'sub_prob' (substitution of a character
# in a field).
single_typo_prob = {'same_row':0.40,
'same_col':0.30}
# -----------------------------------------------------------------------------
# Now add all field dictionaries into a list according to how they should be
# saved in the output file.
field_list = [company_name_stn_dict, streetnumber1_dict,
address1_dict, city1_dict, state1_dict, zip1_dict]
# -----------------------------------------------------------------------------
# Flag for writing a header line (keys 'name' of field dictionaries).
save_header = True # Set to 'False' if no header should be written
# -----------------------------------------------------------------------------
# String to be inserted for missing values.
missing_value = ''
# =============================================================================
# Nothing to be changed below here
# =============================================================================
# Initialise random number generator - - - - - - - - - - - - - - - - - - - - -
#
random.seed()
# =============================================================================
# Functions used by the main program come here
def error_position(input_string, len_offset):
"""A function that randomly calculates an error position within the given
input string and returns the position as integer number 0 or larger.
The argument 'len_offset' can be set to an integer (e.g. -1, 0, or 1) and
will give an offset relative to the string length of the maximal error
position that can be returned.
Errors do not likely appear at the beginning of a word, so a gauss random
distribution is used with the mean being one position behind half the
string length (and standard deviation 1.0)
"""
str_len = len(input_string)
max_return_pos = str_len - 1 + len_offset # Maximal position to be returned
if (str_len == 0):
return None # Empty input string
mid_pos = (str_len + len_offset) / 2 + 1
random_pos = random.gauss(float(mid_pos), 1.0)
random_pos = max(0,int(round(random_pos))) # Make it integer and 0 or larger
return min(random_pos, max_return_pos)
# -----------------------------------------------------------------------------
def error_character(input_char, char_range):
"""A function which returns a character created randomly. It uses row and
column keyboard dictionaires.
"""
input_char=input_char.lower()
# Keyboard substitutions gives two dictionaries with the neigbouring keys for
# all letters both for rows and columns (based on ideas implemented by
# Mauricio A. Hernandez in his dbgen).
#
rows = {'a':'s', 'b':'vn', 'c':'xv', 'd':'sf', 'e':'wr', 'f':'dg', 'g':'fh',
'h':'gj', 'i':'uo', 'j':'hk', 'k':'jl', 'l':'k', 'm':'n', 'n':'bm',
'o':'ip', 'p':'o', 'q':'w', 'r':'et', 's':'ad', 't':'ry', 'u':'yi',
'v':'cb', 'w':'qe', 'x':'zc', 'y':'tu', 'z':'x',
'1':'2', '2':'13', '3':'24', '4':'35', '5':'46', '6':'57', '7':'68',
'8':'79', '9':'80', '0':'9'}
colsAlpha = {'a':'qzw','b':'gh', 'c':'df', 'd':'erc','e':'d', 'f':'rvc','g':'tbv',
'h':'ybn','i':'k', 'j':'umn','k':'im', 'l':'o', 'm':'jk', 'n':'hj',
'o':'l', 'p':'p', 'q':'a', 'r':'f', 's':'wxz','t':'gf', 'u':'j',
'v':'fg', 'w':'s', 'x':'sd', 'y':'h', 'z':'as'}
colsAlphaNum = {'a':'qzw','b':'gh', 'c':'df', 'd':'erc','e':'34d', 'f':'rvc','g':'tbv',
'h':'ybn','i':'89k', 'j':'umn','k':'im', 'l':'o', 'm':'jk', 'n':'hj',
'o':'90l', 'p':'0p', 'q':'12a', 'r':'45f', 's':'wxz','t':'56gf', 'u':'78j',
'v':'fg', 'w':'23s', 'x':'sd', 'y':'67h', 'z':'as',
'1':'q', '2':'qw', '3':'we', '4':'er', '5':'rt', '6':'ty', '7':'yu', '8': 'ui',
'9':'io', '0':'op'}
rand_num = random.random() # Create a random number between 0 and 1
if (char_range == 'digit'):
# A randomly chosen neigbouring key in the same keyboard row
#
if (input_char.isdigit()) and (rand_num <= single_typo_prob['same_row']):
output_char = random.choice(rows[input_char])
else:
choice_str = string.replace(string.digits, input_char, '')
output_char = random.choice(choice_str) # A randomly choosen digit
elif (char_range == 'alpha'):
# A randomly chosen neigbouring key in the same keyboard row
#
if (input_char.isalpha()) and (rand_num <= single_typo_prob['same_row']):
output_char = random.choice(rows[input_char])
# A randomly chosen neigbouring key in the same keyboard column
#
elif (input_char.isalpha()) and \
(rand_num <= (single_typo_prob['same_row'] + \
single_typo_prob['same_col'])):
output_char = random.choice(colsAlpha[input_char])
else:
choice_str = string.replace(string.uppercase, input_char, '')
output_char = random.choice(choice_str) # A randomly choosen letter
else: # Both letters and digits possible
# A randomly chosen neigbouring key in the same keyboard row
#
if (rand_num <= single_typo_prob['same_row']):
if (input_char in rows):
output_char = random.choice(rows[input_char])
else:
choice_str = string.replace(string.lowercase+string.digits, \
input_char, '')
output_char = random.choice(choice_str) # A randomly choosen character
# A randomly chosen neigbouring key in the same keyboard column
#
elif (rand_num <= (single_typo_prob['same_row'] + \
single_typo_prob['same_col'])):
if (input_char in colsAlphaNum):
output_char = random.choice(colsAlphaNum[input_char])
else:
choice_str = string.replace(string.lowercase+string.digits, \
input_char, '')
output_char = random.choice(choice_str) # A randomly choosen character
else:
choice_str = string.replace(string.lowercase+string.digits, \
input_char, '')
output_char = random.choice(choice_str) # A randomly choosen character
return output_char
# -----------------------------------------------------------------------------
# Some simple funcions used for date conversions follow
# (based on functions from the 'normalDate.py' module by Jeff Bauer, see:
# http://starship.python.net/crew/jbauer/normalDate/)
days_in_month = [[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], \
[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]]
def first_day_of_year(year):
"""Calculate the day number (relative to 1 january 1900) of the first day in
the given year.
"""
if (year == 0):
print 'Error: A year value of 0 is not possible'
raise Exception
elif (year < 0):
first_day = (year * 365) + int((year - 1) / 4) - 693596
else: # Positive year
leap_adj = int ((year + 3) / 4)
if (year > 1600):
leap_adj = leap_adj - int((year + 99 - 1600) / 100) + \
int((year + 399 - 1600) / 400)
first_day = year * 365 + leap_adj - 693963
if (year > 1582):
first_day -= 10
return first_day
# -----------------------------------------------------------------------------
def is_leap_year(year):
"""Determine if the given year is a leap year. Returns 0 (no) or 1 (yes).
"""
if (year < 1600):
if ((year % 4) != 0):
return 0
else:
return 1
elif ((year % 4) != 0):
return 0
elif ((year % 100) != 0):
return 1
elif ((year % 400) != 0):
return 0
else:
return 1
# -----------------------------------------------------------------------------
def epoch_to_date(daynum):
"""Convert an epoch day number into a date [day, month, year], with
day, month and year being strings of length 2, 2, and 4, respectively.
(based on a function from the 'normalDate.py' module by Jeff Bauer, see:
http://starship.python.net/crew/jbauer/normalDate/)
USAGE:
[year, month, day] = epoch_to_date(daynum)
ARGUMENTS:
daynum A integer giving the epoch day (0 = 1 January 1900)
DESCRIPTION:
Function for converting a number of days (integer value) since epoch time
1 January 1900 (integer value) into a date tuple [day, month, year].
EXAMPLES:
[day, month, year] = epoch_to_date(0) # returns ['01','01','1900']
[day, month, year] = epoch_to_date(37734) # returns ['25','04','2003']
"""
if (not (isinstance(daynum, int) or isinstance(daynum, long))):
print 'Error: Input value for "daynum" is not of integer type: %s' % \
(str(daynum))
raise Exception
if (daynum >= -115860):
year = 1600 + int(math.floor((daynum + 109573) / 365.2425))
elif (daynum >= -693597):
year = 4 + int(math.floor((daynum + 692502) / 365.2425))
else:
year = -4 + int(math.floor((daynum+695058) / 365.2425))
days = daynum - first_day_of_year(year) + 1
if (days <= 0):
year -= 1
days = daynum - first_day_of_year(year) + 1
days_in_year = 365 + is_leap_year(year) # Adjust for a leap year
if (days > days_in_year):
year += 1
days = daynum - first_day_of_year(year) + 1
# Add 10 days for dates between 15 October 1582 and 31 December 1582
#
if (daynum >= -115860) and (daynum <= -115783):
days += 10
day_count = 0
month = 12
leap_year_flag = is_leap_year(year)
for m in range(12):
day_count += days_in_month[leap_year_flag][m]
if (day_count >= days):
month = m + 1
break
# Add up the days in the prior months
#
prior_month_days = 0
for m in range(month-1):
prior_month_days += days_in_month[leap_year_flag][m]
day = days - prior_month_days
day_str = string.zfill(str(day),2) # Add '0' if necessary
month_str = string.zfill(str(month),2) # Add '0' if necessary
year_str = str(year) # Is always four digits long
return [day_str, month_str, year_str]
# -----------------------------------------------------------------------------
def date_to_epoch(day, month, year):
""" Convert a date [day, month, year] into an epoch day number.
(based on a function from the 'normalDate.py' module by Jeff Bauer, see:
http://starship.python.net/crew/jbauer/normalDate/)
USAGE:
daynum = date_to_epoch(year, month, day)
ARGUMENTS:
day Day value (string or integer number)
month Month value (string or integer number)
year Year value (string or integer number)
DESCRIPTION:
Function for converting a date into a epoch day number (integer value)
since 1 january 1900.
EXAMPLES:
day = date_to_epoch('01', '01', '1900') # returns 0
day = date_to_epoch('25', '04', '2003') # returns 37734
"""
# Convert into integer values
#
try:
day_int = int(day)
except:
print 'Error: "day" value is not an integer'
raise Exception
try:
month_int = int(month)
except:
print 'Error: "month" value is not an integer'
raise Exception
try:
year_int = int(year)
except:
print 'Error: "year" value is not an integer'
raise Exception
# Test if values are within range
#
if (year_int <= 1000):
print 'Error: Input value for "year" is not a positive integer ' + \
'number: %i' % (year)
raise Exception
leap_year_flag = is_leap_year(year_int)
if (month_int <= 0) or (month_int > 12):
print 'Error: Input value for "month" is not a possible day number: %i' % \
(month)
raise Exception
if (day_int <= 0) or (day_int > days_in_month[leap_year_flag][month_int-1]):
print 'Error: Input value for "day" is not a possible day number: %i' % \
(day)
raise Exception
days = first_day_of_year(year_int) + day_int - 1
for m in range(month_int-1):
days += days_in_month[leap_year_flag][m]
if (year_int == 1582):
if (month_int > 10) or ((month_int == 10) and (day_int > 4)):
days -= 10
return days
# -----------------------------------------------------------------------------
def load_misspellings_dict(misspellings_file_name):
"""Load a look-up table containing misspellings for common words, which can
be used to introduce realistic errors.
Returns a dictionary where the keys are the correct spellings and the
values are a list of one or more misspellings.
"""
# Open file and read all lines into a list
#
try:
f = open(misspellings_file_name, 'r')
except:
print 'Error: Can not read from misspellings file "%s"' % \
(misspellings_file_name)
raise IOError
file_data = f.readlines() # Read complete file
f.close()
misspell_dict = {}
key = None # Start with a non-existing key word (correct word)
# Now process all lines - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
for line in file_data:
l = line.strip() # Remove line separators
if (len(l) > 0) and (l[0] != '#'): # Not empty line and not comment
ll = l.split(':') # Separate key from values
if (ll[0] == '') and (len(ll) > 1):
ll = ll[1:]
if (len(ll) == 2): # Line contains a key - - - - - - - - - - - - - - - -
key = ll[0].strip().lower() # Get key, make lower and strip spaces
if (key == ''):
print 'This should not happen: "%s"' % (l)
raise Exception
vals = ll[1].strip().lower() # Get values in a string
if (vals == ''):
print 'Error: No misspellings given for "%s" in line: "%s"' % \
(key, l)
raise Exception
val_list = vals.split(',')
val_set = sets.Set()
for val in val_list:
if (val != ''):
val_set.add(val.strip()) # Remove all spaces
# Check that all misspellings are different from the original
#
if (key in val_set):
print 'Error: A misspelling is the same as the original value' + \
' "%s" in line: "%s"' % (key, l)
raise Exception
# Now insert into misspellings dictionary
#
key_val_set = misspell_dict.get(key, sets.Set())
key_val_set = key_val_set.union(val_set)
misspell_dict[key] = key_val_set
elif (len(ll) == 1): # Line contains only values - - - - - - - - - - - -
if (key == None):
print 'Error: No key (correct word) defined in line: "%s"' % (l)
raise Exception
vals = ll[0].lower() # Get values in a string
val_list = vals.split(',')
val_set = sets.Set()
for val in val_list:
if (val != ''):
val_set.add(val.strip()) # Remove all spaces
# Check that all misspellings are different from the original
#
if (key in val_set):
print 'Error: A misspelling is the same as the original value' + \
' "%s" in line: "%s"' % (key, l)
raise Exception
# Now insert into misspellings dictionary
#
key_val_set = misspell_dict.get(key, sets.Set())
key_val_set = key_val_set.union(val_set)
misspell_dict[key] = key_val_set
else:
print 'error:Illegal line format in line: "%s"' % (l)
raise Exception
# Now convert all sets into lists - - - - - - - - - - - - - - - - - - - - -
#
for k in misspell_dict:
misspell_dict[k] = list(misspell_dict[k])
# print ' Length of misspellings dictionary: %d' % (len(misspell_dict))
return misspell_dict
# -----------------------------------------------------------------------------
def random_select(prob_dist_list):
"""Randomly select one of the list entries (tuples of value and probability
values).
"""
rand_num = random.random() # Random number between 0.0 and 1.0
ind = -1
while (prob_dist_list[ind][1] > rand_num):
ind -= 1
return prob_dist_list[ind][0]
# =============================================================================
# Start main program
if (len(sys.argv) != 8):
print 'Seven arguments needed with %s:' % (sys.argv[0])
print ' - Output file name'
print ' - Number of original records'
print ' - Number of duplicate records'
print ' - Maximal number of duplicate records for one original record'
print ' - Maximum number of modifications per field'
print ' - Maximum number of modifications per record'
print ' - Probability distribution for duplicates (uniform, poisson, zipf)'
print 'All other parameters have to be set within the code'
sys.exit()
output_file = sys.argv[1]
num_org_records = int(sys.argv[2])
num_dup_records = int(sys.argv[3])
max_num_dups = int(sys.argv[4])
max_num_field_modifi = int(sys.argv[5])
max_num_record_modifi = int(sys.argv[6])
prob_distribution = sys.argv[7][:3]
if (num_org_records <= 0):
print 'Error: Number of original records must be positive'
sys.exit()
if (num_dup_records < 0):
print 'Error: Number of duplicate records must be zero or positive'
sys.exit()
if (max_num_dups <= 0) or (max_num_dups > 9):
print 'Error: Maximal number of duplicates per record must be positive ' + \
'and less than 10'
sys.exit()
if (max_num_field_modifi <= 0):
print 'Error: Maximal number of modifications per field must be positive'
sys.exit()
if (max_num_record_modifi <= 0):
print 'Error: Maximal number of modifications per record must be positive'
sys.exit()
if (max_num_record_modifi < max_num_field_modifi):
print 'Error: Maximal number of modifications per record must be equal to'
print ' or larger than maximal number of modifications per field'
sys.exit()
if (prob_distribution not in ['uni', 'poi', 'zip']):
print 'Error: Illegal probability distribution: %s' % (sys.argv[7])
print ' Must be one of: "uniform", "poisson", or "zipf"'
sys.exit()
# -----------------------------------------------------------------------------
# Check all user options within generate.py for validity
#
field_names = [] # Make a list of all field names
# A list of all probabilities to check ('select_prob' is checked separately)
#
prob_names = ['ins_prob','del_prob','sub_prob','trans_prob','val_swap_prob',
'wrd_swap_prob','spc_ins_prob','spc_del_prob','miss_prob',
'misspell_prob','new_val_prob']
select_prob_sum = 0.0 # Sum over all select probabilities
# Check if all defined field dictionaries have the necessary keys
#
i = 0 # Loop counter
for field_dict in field_list:
if ('name' not in field_dict):
print 'Error: No field name given for field dictionary'
raise Exception
elif (field_dict['name'] == 'rec_id'):
print 'Error: Illegal field name "rec_id" (used for record identifier)'
raise Exception
else:
field_names.append(field_dict['name'])
if (field_dict.get('type','') not in ['freq','date','phone','ident']):
print 'Error: Illegal or no field type given for field "%s": %s' % \
(field_dict['name'], field_dict.get('type',''))
raise Exception
if (field_dict.get('char_range','') not in ['alpha', 'alphanum','digit']):
print 'Error: Illegal or no random character range given for ' + \
'field "%s": %s' % (field_dict['name'], \
field_dict.get('char_range',''))
raise Exception
if (field_dict['type'] == 'freq'):
if (not field_dict.has_key('freq_file')):
print 'Error: Field of type "freq" has no file name given'
raise Exception
elif (field_dict['type'] == 'date'):
if (not (field_dict.has_key('start_date') and \
field_dict.has_key('end_date'))):
print 'Error: Field of type "date" has no start and/or end date given'
raise Exception
else: # Process start and end date
start_date = field_dict['start_date']
end_date = field_dict['end_date']
start_epoch = date_to_epoch(start_date[0], start_date[1], start_date[2])
end_epoch = date_to_epoch(end_date[0], end_date[1], end_date[2])
field_dict['start_epoch'] = start_epoch
field_dict['end_epoch'] = end_epoch
field_list[i] = field_dict
elif (field_dict['type'] == 'phone'):
if (not (field_dict.has_key('area_codes') and \
field_dict.has_key('num_digits'))):
print 'Error: Field of type "phone" has no area codes and/or number ' + \
'of digits given'
raise Exception
else: # Process area codes and number of digits
if (isinstance(field_dict['area_codes'],str)): # Only one area code
field_dict['area_codes'] = [field_dict['area_codes']] # Make it a list
if (not isinstance(field_dict['area_codes'],list)):
print 'Error: Area codes given are not a string or a list: %s' % \
(str(field_dict['area_codes']))
raise Exception
if (not isinstance(field_dict['num_digits'],int)):
print 'Error: Number of digits given is not an integer: %s (%s)' % \
(str(field_dict['num_digits']), type(field_dict['num_digits']))
raise Exception
field_list[i] = field_dict
elif (field_dict['type'] == 'ident'):
if (not (field_dict.has_key('start_id') and \
field_dict.has_key('end_id'))):
print 'Error: Field of type "iden" has no start and/or end ' + \
'identification number given'
raise Exception
# Check all the probabilities for this field
#
if ('select_prob' not in field_dict):
field_dict['select_dict'] = 0.0
elif (field_dict['select_prob'] < 0.0) or (field_dict['select_prob'] > 1.0):
print 'Error: Illegal value for select probability in dictionary for ' + \
'field "%s": %f' % (field_dict['name'], field_dict['select_prob'])
else:
select_prob_sum += field_dict['select_prob']
field_prob_sum = 0.0
for prob in prob_names:
if (prob not in field_dict):
field_dict[prob] = 0.0