forked from J535D165/FEBRL-fork-v0.4.2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataset.py
2430 lines (1830 loc) · 84 KB
/
dataset.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: "dataset.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 several classes of data set implementations.
This module provides classes for access to different types of data sets,
including text files (coma separated values and column wise), databases
(using the Python database API), binary files (using Python shelves), and
memory based data (using Python dictionaries).
A data set is generally defined as a set of fields (or attributes), with the
possibility that one of these fields contains unique record identifiers. If
such a field is not available unique record identifiers will be generated on
the fly.
Records read from or written into a data set are basically a dictionary
entry made of a record identifier (dictionary key) and a list of the
attribute values of the record, like:
{'rec-id-42':['peter','miller','42','main','st','sydney','2000','nsw']}
See the doc strings of individual classes and methods for detailed
documentation.
TODO:
- Implement SQL data set
- Implement handling of .ZIP and .BZ2 files for CSV and COL data sets
- Allow multiple files or tables in one data set
"""
# =============================================================================
# Import necessary modules (Python standard modules first, then Febrl modules)
import csv
import gzip
import logging
import math
import os
import random
import shelve
import string
import sys
import time
import auxiliary
import mymath
# =============================================================================
# Some constants used by the analyse() method
QUANT_LIST = [0.0,0.05,0.25,0.5,0.75,0.95,1.0] # List of quantiles for analyse
NUM_VALUES = 15 # Maximum number of values to be shown for a column in analyse
MISS_PERC_THRES = 5.0 # Threshold in percentage above which a column will not
# be classified suitable for blocking in analyse
# =============================================================================
class DataSet:
"""Base class for data set access.
This class and all its derived classes provide methods for reading from
and writing to various data set implementations.
Currently a data set can consists of one underlying file or table only.
Each record in a data set is made of fields (or attributes). A list of
tuples with the field names needs to be given when a data set is
initialised. The first element in each tuple is a field name while the
second element depends upon the data set type (e.g. column numbers for CSV
files, or the names of the attributes in an SQL table).
Records are returned as dictionary entries containing a unique record
identifier (dictionary key) and a list of the record field (attribute)
values from the data set.
All data sets have the following instance variables, which can be set when
a data set is initialised:
description A string describing the data set.
access_mode The data set's access mode, which can be either 'read',
'write', 'append' or 'readwrite'. Not all access modes
are possible for all data set implementations.
field_list Field names and data set specific information about the
fields (or attributes) in the data set.
rec_ident Either the name of a field in the data set containing
unique record identifiers, or a string (different from
any field name in the data set) that will be used to
generate record identifiers (by adding unique numbers
to that string) on the fly.
strip_fields A flag (True/False) stating if whitespaces should be
stripped off fields before they are returned. Default is
True.
miss_val If not None (the default), this can be either a string or
a list of strings. This (or these) string(s), if found in
an attribute, will be removed and the attribute set to an
empty string. Note that leading and trailing whitespaces
will be removed from all strings in this missing values
list.
"""
# ---------------------------------------------------------------------------
def __init__(self, base_kwargs):
"""Constructor, set general attributes.
"""
# General attributes for all data sets
#
self.type = ''
self.description = ''
self.access_mode = None
self.field_list = None
self.rec_ident = None
self.strip_fields = True
self.miss_val = None
self.num_records = None # To be set when a data set is initialised
# 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('access')):
auxiliary.check_is_string('access_mode', value)
if (value not in ['read','write','append','readwrite']):
logging.exception('Illegal "access_mode" value: %s' % (str(value)))
raise Exception
self.access_mode = value
elif (keyword.startswith('field_l')):
auxiliary.check_is_list('field_list',value)
self.field_list = value
elif (keyword.startswith('rec_id')):
auxiliary.check_is_string('rec_ident',value)
self.rec_ident = value
elif (keyword.startswith('strip_f')):
auxiliary.check_is_flag('strip_fields', value)
self.strip_fields = value
elif (keyword.startswith('miss_v')):
if (value != None):
if (isinstance(value, str)):
value = [value] # Make it a list
auxiliary.check_is_list('miss_val',value)
self.miss_val = value
else:
logging.exception('Illegal constructor argument keyword: "%s"' % \
(str(keyword)))
raise Exception
# Check if access mode and record identifier are defined - - - - - - - - -
#
auxiliary.check_is_string('access_mode', self.access_mode)
auxiliary.check_is_string('rec_ident', self.rec_ident)
# Remove all leading and trailing whitespaces from missing values - - - - -
#
if (self.miss_val != None):
clean_miss_val = []
for miss_val in self.miss_val:
auxiliary.check_is_string('miss_val entry', miss_val)
stripped_miss_val = miss_val.strip()
if (stripped_miss_val != ''): # Not empty string
clean_miss_val.append(stripped_miss_val)
if (clean_miss_val != []): # Check if there are non-empty missing values
self.miss_val = clean_miss_val
else:
self.miss_val = None
# ---------------------------------------------------------------------------
def finalise(self):
"""Finalise a data set.
See implementations in derived classes for details.
"""
logging.exception('Override abstract method in derived class')
raise Exception
# ---------------------------------------------------------------------------
def read(self, *recs):
"""Read and return one or more records.
Calling arguments are not the same for all derived data set classes, see
implementations in derived classes for details.
"""
logging.exception('Override abstract method in derived class')
raise Exception
# ---------------------------------------------------------------------------
def readall(self):
"""An iterator which will return one record per call as a tuple (record
identifier, record field list).
Use like: for rec in dataset.readall():
See implementations in derived classes for details.
"""
logging.exception('Override abstract method in derived class')
raise Exception
# ---------------------------------------------------------------------------
def write(self, rec_dict):
"""Write one or more records into the data set.
See implementations in derived classes for details.
"""
logging.exception('Override abstract method in derived class')
raise Exception
# ---------------------------------------------------------------------------
def analyse(self, sample, word_analysis, log_funct=None, log_num_recs=None):
"""Read the data and analyse a sample (or all) of the records in it.
The following arguments have to be set:
sample A number between 0 and 100 that gives the percentage of
records that will be randomly selected and analysed. If
set to 100 then all records in the data set will be
analysed.
word_analysis This flag determines if the values in fields should
be analysed as separate words or as complete values.
If set to True, then a value that contains more than
one word (i.e. contains at least one whitespace) will
be split into its words and they will be used in the
analysis for frequencies, rather than the original
value.
log_funct This can be a Python function or method which will log
(print or save to a file) a progress report message. It
is assumed that this function or method has one input
argument of type string (the message to be printed).
log_num_recs If 'log_funct' is defined, this must be a positive
integer number which interval in number of records read
from the data set between calls to the 'log_funct'
function.
For each field (column / attribute) in the data set this method collects
and generates the following basic statistics for the sampled records:
- The number of unique values
- The smallest and largest values (as strings)
- The average frequency and standard deviation of the values
- A list of quantiles of the values
- The most and least frequent values and their frequencies
- The minimum and maximum value length
- If the field only contains digits, only contains letters, or only
contains digits and letters
- The maximum number of spaces in values
- The number of records with missing value
It then generates a table summarising the field statistics and a table
summarising the quantiles statistics.
Finally, it generates a table containing details on the suitability of
fields for blocking (according to their number of values and proportion
of missing values).
It returns a list containing strings (each assumed to be a line of text)
that can be printed or save into a file.
"""
# Check input parameters
#
auxiliary.check_is_percentage('Sample percentage', sample)
auxiliary.check_is_flag('Word analysis', word_analysis)
if (log_funct != None):
auxiliary.check_is_function_or_method('Log function', log_funct)
auxiliary.check_is_integer('Log number of records', log_num_recs)
auxiliary.check_is_positive('Log number of records', log_num_recs)
test_rec_dict = self.read() # Read one record to get the number of fields
num_fields = len(test_rec_dict.values()[0])
# Define list of data structures for information to be collected
#
num_missing_list = []
values_dict_list = []
min_length_list = []
max_length_list = []
isdigit_list = []
isalpha_list = []
isalnum_list = []
max_num_spaces_list = []
warn_message_dict = {} # Keys will be warning messages, values their counts
for i in range(num_fields):
num_missing_list.append(0)
values_dict_list.append({})
min_length_list.append(999)
max_length_list.append(0)
isdigit_list.append(True)
isalpha_list.append(True)
isalnum_list.append(True)
max_num_spaces_list.append(0)
num_warnings = 0 # Count all warnings
num_records = 0 # Nunmber of records in data set
num_recs_analysed = 0 # Number of records analysed (sampled)
# Read and process data lines - - - - - - - - - - - - - - - - - - - - - - -
#
start_time = time.time()
for (rec_id, rec_list) in self.readall():
if (len(rec_list) != num_fields):
warn_msg = 'Line does have %d fields (not %d as expected)' % \
(len(rec_list), num_fields)
warn_msg_count = warn_message_dict.get(warn_msg, 0) + 1
warn_message_dict[warn_msg] = warn_msg_count
num_warnings += 1
if (len(rec_list) < num_fields): # Correct by adding empty fields
rec_list += ['']*(num_fields-len(rec_list))
if (random.random()*100 < sample): # Randomly select a record
c = 0
# Loop over the field values in this record
#
for col_val in rec_list[:num_fields]:
# Value has been stripped and/or missing values removed in .readall()
if (col_val == ''):
num_missing_list[c] += 1
else: # Value is not empty
if (word_analysis == True): # Split into words and analyse separate
col_val_list = col_val.split() # Split at whitespaces
else:
col_val_list = [col_val]
for col_val in col_val_list:
col_dict = values_dict_list[c]
col_val_freq = col_dict.get(col_val, 0) + 1 # Increase count
col_dict[col_val] = col_val_freq
values_dict_list[c] = col_dict
col_val_len = len(col_val)
min_length_list[c] = min(min_length_list[c], col_val_len)
max_length_list[c] = max(max_length_list[c], col_val_len)
isdigit_list[c] = isdigit_list[c] and col_val.isdigit()
isalpha_list[c] = isalpha_list[c] and col_val.isalpha()
isalnum_list[c] = isalnum_list[c] and col_val.isalnum()
if (' ' in col_val): # Count number of whitespaces in value
max_num_spaces_list[c] = max(max_num_spaces_list[c],
(len(col_val.split(' '))-1))
c += 1
num_recs_analysed += 1
num_records += 1
if ((log_funct != None) and (log_num_recs != None) and \
((num_records % log_num_recs) == 0)):
used_time = (time.time() - start_time)
processed_perc = 100.0 * float(num_records) / self.num_records
log_funct('Read %.2f%% of %d records in %.2f sec ' % \
(processed_perc, self.num_records, used_time))
#log_funct('Processed a %.1f%% sample of %d records in %.2f sec' % \
# (sample, num_records, used_time))
if ((log_funct != None) and (log_num_recs != None)):
used_time = (time.time() - start_time)
log_funct('Finished reading a %.1f%% sample of %d records in %.2f' % \
(sample, num_records, used_time)+' sec')
# Log warnings if there were some - - - - - - - - - - - - - - - - - - - - -
#
if (warn_message_dict != {}):
warn_msg_tuples = warn_message_dict.items()
warn_msg_tuples.sort()
logging.warn('Warnings from "analyse" read records:')
for (warn_msg, warn_count) in warn_msg_tuples:
logging.warn(' %s occured %d times' % (warn_msg, warn_count))
# Calculate and report final statistics - - - - - - - - - - - - - - - - - -
#
final_stats = [] # Build a list of lines to be returned
stddev_list = []
avrg_list = []
num_val_list = []
num_miss_list = []
type_list = [] # If field is digits only, letters only, etc.
final_stats.append('')
final_stats.append('Detailed statistics for data set: %s' % \
(self.file_name))
final_stats.append('='*(34+len(self.file_name)))
final_stats.append('')
final_stats.append('Analysis conducted on '+time.asctime())
final_stats.append('')
final_stats.append('Analysed %d of %d records (%.2f%% sample)' % \
(num_recs_analysed, num_records, sample))
final_stats.append('')
if (word_analysis == True):
final_stats.append('Frequency analysis based on separate words ' + \
'in fields')
else:
final_stats.append('Frequency analysis based on field values')
final_stats.append('')
for c in range(num_fields):
header_line_str = 'Field %d: "%s"' % (c, self.field_list[c][0])
final_stats.append(header_line_str)
value_list = values_dict_list[c].keys()
freq_list = values_dict_list[c].values()
freq_list_len = len(freq_list)
final_stats.append(' Number of unique values: %d' % (freq_list_len))
num_val_list.append(freq_list_len)
if (freq_list_len > 0):
list_tuples = map(None, freq_list, value_list)
list_tuples.sort()
value_list.sort()
final_stats.append(' Smallest and largest values (as strings): ' + \
'"%s" / "%s"' % (str(value_list[0]),
str(value_list[-1])))
avrg = float(sum(freq_list)) / float(freq_list_len)
final_stats.append(' Average frequency: %.2f' % (avrg))
avrg_list.append(avrg)
stddev = 0.0
for v in freq_list:
stddev += (v - avrg)*(v - avrg)
stddev = math.sqrt(stddev / float(freq_list_len))
final_stats.append(' Frequency stddev: %.2f' % (stddev))
stddev_list.append(stddev)
quantiles_str = auxiliary.str_vector(mymath.quantiles(freq_list,
QUANT_LIST), num_digits=2)
final_stats.append(' Quantiles: %s' % (quantiles_str))
if (freq_list_len < NUM_VALUES):
final_stats.append(' All field values:')
for lt in list_tuples:
final_stats.append(' '+str(lt))
else:
final_stats.append(' Most frequent field values:')
for j in [-1, -2, -3, -4, -5, -6]:
final_stats.append(' '+str(list_tuples[j]))
final_stats.append(' Least frequent field values:')
for j in [5, 4, 3, 2, 1, 0]:
final_stats.append(' '+str(list_tuples[j]))
final_stats.append(' Minimum and maximum value lengths: %d / %d' % \
(min_length_list[c], max_length_list[c]))
final_stats.append(' Is-digit: %s, is-alpha: %s, is-alnum: %s' % \
(str(isdigit_list[c]),str(isalpha_list[c]),
str(isalnum_list[c])))
final_stats.append(' Maximum number of spaces in values: %d' % \
(max_num_spaces_list[c]))
final_stats.append(' Number of records with missing value: %d' % \
(num_missing_list[c]))
num_miss_list.append(num_missing_list[c])
# Determine if field contents are digits only, letters only, etc.
#
if (isdigit_list[c] == True):
type_list.append('Only digits')
elif (isalpha_list[c] == True):
type_list.append('Only letters')
elif (isalnum_list[c] == True):
type_list.append('Digits and letters')
else:
type_list.append('Various')
else: # freq_list_len = 0 (no values in a field at all)
avrg_list.append(-1)
stddev_list.append(-1)
type_list.append('Empty')
num_miss_list.append(num_records)
num_val_list.append(0)
final_stats.append(' Empty field!')
final_stats.append('')
# Give a summary of fields - - - - - - - - - - - - - - - - - - - - - - - - -
#
final_stats.append('Summary of field statistics')
final_stats.append('===========================')
final_stats.append('')
final_stats.append(' Unique Missing ' + \
' Frequencies')
final_stats.append('Field names values values ' + \
' Avrg StdDev Field type')
final_stats.append('-'*86)
for c in range(num_fields):
hv = self.field_list[c][0]
av = '%.2f' % (avrg_list[c])
if (av != '-1.00'):
av = av.rjust(10)
else:
av = ' --'
sv = '%.2f' % (stddev_list[c])
if (sv != '-1.00'):
sv = sv.rjust(9)
else:
sv = ' --'
tv = type_list[c]
final_stats.append('%22s %10d %10d %s %s %s' % \
(hv.ljust(22), num_val_list[c], num_miss_list[c], av, sv, tv))
final_stats.append('')
# Give a summary of quantiles - - - - - - - - - - - - - - - - - - - - - - -
#
final_stats.append('Field quantiles')
final_stats.append('===============')
final_stats.append('')
quant_list_str = '['
for v in QUANT_LIST:
quant_list_str += '%d%%, ' % (int(v*100))
quant_list_str = quant_list_str[:-2]+']'
final_stats.append('Field names Quantiles %s' % \
(quant_list_str))
final_stats.append('-'*86)
for c in range(num_fields):
hv = self.field_list[c][0]
freq_list = values_dict_list[c].values()
if (len(freq_list) > 0):
qv = auxiliary.str_vector(mymath.quantiles(freq_list, QUANT_LIST),
num_digits=2)
final_stats.append('%22s %s' % (hv.ljust(22), qv))
else: # An empty field
final_stats.append('%22s [Empty]' % (hv.ljust(22)))
final_stats.append('')
# Calculate number of blocks as well as percentage of missing values - - -
#
final_stats.append('Suitability of fields for blocking')
final_stats.append('==================================')
final_stats.append('(number of record pair comparisons is calculated ' + \
'for a deduplication)')
final_stats.append('')
final_stats.append('Field names Suitability')
final_stats.append('-'*86)
for c in range(num_fields):
hv = self.field_list[c][0]
num_miss_rec = num_missing_list[c]
if (num_miss_rec > 0):
miss_perc = 100.0 * float(num_miss_rec) / float(num_records)
if (miss_perc > MISS_PERC_THRES): # Field not suitable for blocking
final_stats.append('%22s %.2f%% (%d) records with missing ' % \
(hv.ljust(22), miss_perc, num_miss_rec) + \
'values (not suitable)')
else:
miss_perc = 0.0
if (miss_perc <= MISS_PERC_THRES): # Field suitable for blocking
freq_list = values_dict_list[c].values()
num_val = len(freq_list)
# Start with missing value records
#
num_comp = num_miss_rec*(num_miss_rec-1)
for j in freq_list:
num_comp += j*(j-1) # Add number of record pair comparisons
final_stats.append('%22s %d unique values, resulting in %d ' % \
(hv.ljust(22), num_val, num_comp) + \
'record pair comparisons')
if (miss_perc > 0.0):
final_stats.append(' '*24+'Note field contains %.2f%% (%d) ' % \
(miss_perc, num_miss_rec) + 'records with missing' + \
' values')
final_stats.append('')
final_stats.append('')
return final_stats
# ---------------------------------------------------------------------------
def log(self, instance_var_list = None):
"""Write a log message with the basic data set 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('Data set: "%s"' % (self.description))
logging.info(' Data set type: %s' % (self.dataset_type))
logging.info(' Access mode: %s' % (self.access_mode))
logging.info(' Strip fields: %s' % (str(self.strip_fields)))
logging.info(' Number of records: %d' % (self.num_records))
logging.info(' Record identifier: %s' % (self.rec_ident))
if (self.miss_val != None):
logging.info(' Missing values: %s' % (str(self.miss_val)))
else:
logging.info(' Missing values: None')
logging.info(' Fields list:')
for (field_name,val) in self.field_list:
if (field_name == self.rec_ident):
logging.info(' %s: %s (record identifier)' % \
(str(field_name), str(val)))
else:
logging.info(' %s: %s' % (str(field_name), str(val)))
if (instance_var_list != None):
logging.info(' Data set 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)))
# =============================================================================
class DataSetCSV(DataSet):
"""Implementation of a CSV (comma separated values) data set class.
The 'field_list' attribute can either be given when a CSV data set is
initialised (in which case it must contain pairs of field names and column
numbers, starting from zero), or it can be generated from the header line
in the CSV data file (if the 'header_line' attribute is set to True and
the 'access_mode' is 'read').
Possible values for the 'access_mode' argument are: 'read', 'write', or
'append' (but not 'readwrite').
If the file name ends with '.gz' it is assumed the file is GZIP compressed
and it will be opened using the gzip library. This will only be checked
when opening a CSV data set for reading, writing and appending will always
be into uncompressed files.
The additional arguments (besides the base class arguments) which have to
be set when this data set is initialised are:
file_name A string containing the name of the underlying CSV
file.
delimiter A one character string which designates the delimter
used to split a line into columns/attributes. Default
value is a comma (','), aother commen alternative is
a tabulator ('\t').
header_line A flag, if set to True (and access mode is "read") the
first line in the CSV data file is assumed to contain
the field (attribute) names and these will be used to
generate the 'field_list' attribute. If set to False
(default) then the 'field_list' attribute needs to be
provided.
write_header A flag, if set to "True" a header line with the field
names is written into the file when it is opened in
'write' or 'append' (only if file empty) mode.
write_quote_char A quote character, used when writing to file. Default
is no quote character (empty string '').
Note that all values returned from a CSV data set (from it's read methods)
are strings, while non-string values written to the data set will be
stored as strings in the CSV data file.
"""
# ---------------------------------------------------------------------------
def __init__(self, **kwargs):
"""Constructor. Process the derived attributes first, then call the base
class constructor.
"""
self.dataset_type = 'CSV'
self.file_name = None # The name of the CSV file
self.header_line = False # Flag, default set to no header line
self.write_header = False # Flag, set to not write header line
self.file = None # File pointer to current file
self.write_quote_char = '' # The quote character for writing fields
self.delimiter = ',' # The delimiter character
self.next_rec_num = None
self.rec_ident_col = -1 # Column of the record identifier field
# Process all keyword arguments
#
base_kwargs = {} # Dictionary, will contain unprocessed arguments
for (keyword, value) in kwargs.items():
if (keyword.startswith('file')):
auxiliary.check_is_string('file_name', value)
self.file_name = value
elif (keyword.startswith('header')):
auxiliary.check_is_flag('header_line', value)
self.header_line = value
elif (keyword.startswith('write_he')):
auxiliary.check_is_flag('write_header', value)
self.write_header = value
elif (keyword.startswith('write_qu')):
auxiliary.check_is_string('write_quote_char', value)
self.write_quote_char = value
elif (keyword.startswith('delimi')):
auxiliary.check_is_string('delimiter', value)
if (len(value) != 1):
logging.exception('Value of "delimiter" argument must be a one-' + \
'character string, but it is: "%s"' % (delimiter))
raise Exception
self.delimiter = value
else:
base_kwargs[keyword] = value
DataSet.__init__(self, base_kwargs) # Process base arguments
if ((self.header_line == False) and (self.field_list == None)):
logging.exception('Argument "field_list" must be given if field ' + \
'names are not taken from header line')
raise Exception
if ((self.header_line == True) and (self.access_mode == 'read')):
self.field_list = [] # Will be generated from file header line
# Make sure the 'file_name' attribute is set - - - - - - - - - - - - - - -
#
auxiliary.check_is_string('file_name', self.file_name)
# Now perform various checks for each access mode and open file - - - - - -
#
if (self.access_mode == 'read'):
if (self.file_name.endswith('.gz')) or (self.file_name.endswith('.GZ')):
file_gzipped = True
try:
self.file = gzip.open(self.file_name) # Open gzipped file
except:
logging.exception('Cannot open gzipped CSV file "%s" for reading' % \
(self.file_name))
raise IOError
else: # Open normal file for reading
file_gzipped = False
try: # Try to open the file in read mode
self.file = open(self.file_name,'r')
except:
logging.exception('Cannot open CSV file "%s" for reading' % \
(self.file_name))
raise IOError
# Initialise the CSV parser - - - - - - - - - - - - - - - - - - - - - - -
#
self.csv_parser = csv.reader(self.file, delimiter = self.delimiter)
# If header line is set to True get field names
#
if (self.header_line == True):
header_line = self.csv_parser.next()
self.field_list = [] # Make sure field list is empty
col_num = 0 # Create a list with field names and column numbers
for field_name in header_line:
if (self.strip_fields == True):
field_name = field_name.strip()
self.field_list.append((field_name,col_num))
col_num += 1
# Count number of records in the file
#
if ((sys.platform[0:5] in ['linux','sunos']) and \
(file_gzipped == False)): # Fast line counting
if (' ' not in self.file_name):
wc = os.popen('wc -l ' + self.file_name)
else:
wc = os.popen('wc -l "%s"' % (self.file_name))
num_rows = int(string.split(wc.readline())[0])
wc.close()
else: # Slow line counting method
num_rows = 0
if (file_gzipped == True):
fp = gzip.open(self.file_name)
else:
fp = open(self.file_name,'r')
for l in fp:
num_rows += 1
fp.close()
self.num_records = num_rows
if (self.header_line == True):
self.num_records -= 1
# Check that there are records in the data set
#
if (self.num_records == 0):
logging.exception('No records in CSV data set opened for reading')
raise Exception
self.next_rec_num = 0
elif (self.access_mode == 'write'): # - - - - - - - - - - - - - - - - - -
# Try to open the file in write mode
#
try:
self.file = open(self.file_name,'w')
except:
logging.exception('Cannot open CSV file "%s" for writing' % \
(self.file_name))
raise IOError
# Initialise the CSV parser as writer - - - - - - - - - - - - - - - - - -
#
self.csv_parser = csv.writer(self.file, delimiter = self.delimiter)
# Write the header line with field names if desired
#
if (self.write_header == True):
header_list = []
for (field_name,col) in self.field_list:
if (self.strip_fields == True):
field_name = field_name.strip()
if (self.write_quote_char != ''):
field_name = self.write_quote_char + field_name + \
self.write_quote_char
header_list.append(field_name)
self.csv_parser.writerow(header_list)
self.file.flush()
self.num_records = 0
self.next_rec_num = 0
elif (self.access_mode == 'append'): # - - - - - - - - - - - - - - - - - -
# Try to open the file in append mode
#
try:
self.file = open(self.file_name,'a')
except:
logging.exception('Cannot open CSV file "%s" for appending' % \
(self.file_name))
raise IOError
# Count number of records in the file
#
if (sys.platform[0:5] in ['linux','sunos']): # Fast line counting
wc = os.popen('wc -l ' + self.file_name)
num_rows = int(string.split(wc.readline())[0])
wc.close()
else: # Slow line counting method
num_rows = 0
fp = open(self.file_name,'r')
for l in fp:
num_rows += 1
fp.close()
# Initialise the CSV parser as writer - - - - - - - - - - - - - - - - - -
#
self.csv_parser = csv.writer(self.file, delimiter = self.delimiter)
# If no records are stored write header if desired
#
if (num_rows == 0) and (self.write_header == True):
header_list = []
for (field_name,col) in self.field_list:
if (self.strip_fields == True):
field_name = field_name.strip()
if (self.write_quote_char != ''):
field_name = self.write_quote_char + field_name + \
self.write_quote_char
header_list.append(field_name)
self.csv_parser.writerow(header_list)
self.file.flush()
self.num_records = 0
self.next_rec_num = 0
else: # There are records in the data set already
self.num_records = num_rows
if (self.header_line == True):
self.num_records -= 1
self.next_rec_num = self.num_records
else: # Illegal data set access mode - - - - - - - - - - - - - - - - - - -
logging.exception('Illegal data set access mode: "%s" (not allowed ' % \
(str(self.access_mode)) + 'with CSV data set implementation).')
raise Exception
# Check if the values in the 'field_list' argument are all positive integer
# numbers (column numbers), and also check if one is the record identifier
#
this_col_num = 0 # Check if column numbers are consecutive
for (field_name, field_col) in self.field_list:
auxiliary.check_is_string('Field name for column %d is not a string' % \
(field_col), field_name)
auxiliary.check_is_integer('Value of field column "%s" is not an ' % \
(field_name) + ' integer number', field_col)
auxiliary.check_is_not_negative('Value of field column "%s" is a ' % \
(field_name) + 'negative number', field_col)
if (this_col_num != field_col):
logging.exception('Column numbers are not consecutive: %s' % \