forked from mconlon17/vivo-pump
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vivopump.py
2036 lines (1846 loc) · 70.6 KB
/
vivopump.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
vivopump -- module of helper functions for the pump
"""
import sys
import csv
import string
import random
import logging
__author__ = "Michael Conlon"
__copyright__ = "Copyright (c) 2015 Michael Conlon"
__license__ = "New BSD license"
__version__ = "0.8.4"
# Establish logging
logging.captureWarnings(True)
logger = logging.getLogger(__name__)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler = logging.StreamHandler(sys.stderr)
# handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
logger.addHandler(handler)
# logger.setLevel(logging.DEBUG)
logger.setLevel(logging.INFO)
class InvalidDefException(Exception):
"""
Raise this exception when update definition contains values that can not be processed
"""
def __init__(self, value):
Exception.__init__(self)
self.value = value
def __str__(self):
return repr(self.value)
class InvalidDataException(Exception):
"""
Raise this exception when update data contains values that can not be processed
"""
def __init__(self, value):
Exception.__init__(self)
self.value = value
def __str__(self):
return repr(self.value)
class PathLengthException(Exception):
"""
Raise this exception when update def has a path length greater than support
"""
def __init__(self, value):
Exception.__init__(self)
self.value = value
def __str__(self):
return repr(self.value)
class UnicodeCsvReader(object):
"""
From http://stackoverflow.com/questions/1846135/python-csv-
library-with-unicode-utf-8-support-that-just-works. Added errors='ignore'
to handle cases when the input file misrepresents itself as utf-8.
"""
def __init__(self, f, encoding="utf-8", **kwargs):
self.csv_reader = csv.reader(f, **kwargs)
self.encoding = encoding
def __iter__(self):
return self
def next(self):
"""
Read and split the csv row into fields
"""
row = self.csv_reader.next()
# now decode
return [unicode(cell, self.encoding, errors='ignore') for cell in row]
@property
def line_num(self):
"""
Return line number
"""
return self.csv_reader.line_num
class UnicodeDictReader(csv.DictReader):
"""
A Unicode CSV Reader
"""
def __init__(self, f, encoding="utf-8", fieldnames=None, **kwds):
csv.DictReader.__init__(self, f, fieldnames=fieldnames, **kwds)
self.reader = UnicodeCsvReader(f, encoding=encoding, **kwds)
def read_csv(filename, skip=True, delimiter='|'):
"""
Read a CSV file, return dictionary object
:param filename: name of file to read
:param skip: should lines with invalid number of columns be skipped? False=Throw Exception
:param delimiter: The delimiter for CSV files
:return: Dictionary object
"""
fp = open(filename, 'rU')
data = read_csv_fp(fp, skip, delimiter)
fp.close()
return data
def read_csv_fp(fp, skip=True, delimiter="|"):
"""
Given a filename, read the CSV file with that name. We use "|" as a
separator in CSV files to allow commas to appear in values.
CSV files read by this function follow these conventions:
-- use delimiter as a separator. Defaults to vertical bar.
-- have a first row that contains column headings.
-- all elements must have values. To specify a missing value, use
the string "None" or "NULL" between separators, that is |None| or |NULL|
-- leading and trailing whitespace in values is ignored. | The | will be
read as "The"
-- if skip=True, rows with too many or too few data elements are skipped.
if skip=False, a RowError is thrown
CSV files processed by read_csv will be returned as a dictionary of
dictionaries, one dictionary per row keyed by an integer row number. This supports
maintaining the order of the data input, which is important for some applications
"""
class RowError(Exception):
"""
Thrown when the number of data elements on a row in a CSV is not equal to the number of header elements
"""
pass
heading = []
row_number = 0
data = {}
for row in UnicodeCsvReader(fp, delimiter=delimiter):
i = 0
for r in row:
# remove white space fore and aft
row[i] = r.strip(string.whitespace)
i += 1
if len(heading) == 0:
heading = row # the first row is the heading
continue
row_number += 1
if len(row) == len(heading):
data[row_number] = {}
i = 0
for r in row:
data[row_number][heading[i]] = r
i += 1
elif not skip:
raise RowError("On row " + str(row_number) + ", expecting " +
str(len(heading)) + " data values. Found " +
str(len(row)) + " data values. Row contents = " +
str(row))
else:
pass # row has wrong number of columns and skip is True
return data
def write_csv_fp(fp, data, delimiter='|'):
"""
Write a CSV to a file pointer. Used to support stdout.
:param fp: File pointer. Could be stdout.
:param data: data to be written
:param delimiter: field delimiter for output
:return:
"""
var_names = data[data.keys()[0]].keys() # create a list of var_names from the first row
fp.write(delimiter.join(var_names) + '\n')
for key in sorted(data.keys()):
fp.write(delimiter.join([data[key][x] for x in var_names]) + '\n')
def write_csv(filename, data, delimiter='|'):
"""
Given a filename, a data structure as produced by read_csv and an optional delimiter, write a file
that can be read by read_csv
The data structure is a dictionary keyed by an integer of "row numbers" preserving the natural
order of the data. Each element is in turn a dictionary of name value pairs. All values are
strings
:param filename: name of file to write
:param data: data structure to be written to the file
:param delimiter: field delimiter. Popular choices are '|', '\t' and ','
:return:
"""
with open(filename, 'w') as f:
f.write(delimiter.join(data[data.keys()[0]].keys()) + '\n')
for key in sorted(data.keys()):
f.write(delimiter.join(data[key].values()) + '\n')
def replace_initials(s):
"""
For a string s, find all occurrences of A. B. etc and replace them with A B etc
:param s:
:return: string with replacements made
"""
import re
def repl_function(m):
"""
Helper function for re.sub
"""
return m.group(0)[0]
t = re.sub('[A-Z]\.', repl_function, s)
return t
def key_string(s):
"""
Given a string s, return a string with a bunch of punctuation and special
characters removed and then everything lower cased. Useful for matching
strings in which case, punctuation and special characters should not be
considered in the match
"""
k = s.encode("utf-8", "ignore").translate(None,
""" \t\n\r\f!@#$%^&*()_+:"<>?-=[]\\;'`~,./""")
k = k.lower()
return k
def get_vivo_types(selector, parms, separator=';'):
"""
Query VIVO using the selector and return a dictionary with keys of all uri satisfying the selector and
data of all the types for each uri, separated by the separator
:param: selector: query fragment for selecting the entities whose types will be returned
:param: parms: vivo_query parms
:return: dictionary of types keyed by uri
"""
query = """
select ?uri (GROUP_CONCAT(?type; separator="{{separator}}") AS ?types)
where {
{{selector}}
?uri rdf:type ?type .}
GROUP BY ?uri
"""
q = query.replace("{{separator}}", separator)
q = q.replace("{{selector}}", selector)
a = vivo_query(q, parms)
types = [x['types']['value'] for x in a['results']['bindings']]
uri = [x['uri']['value'] for x in a['results']['bindings']]
return dict(zip(uri, types))
def get_vivo_ufid(parms):
"""
Query VIVO and return a list of all the ufid found in VIVO
:param: parms: vivo_query parameters
:return: dictionary of uri keyed by ufid
"""
query = "select ?uri ?ufid where {?uri uf:ufid ?ufid .}"
a = vivo_query(query, parms)
ufid = [x['ufid']['value'] for x in a['results']['bindings']]
uri = [x['uri']['value'] for x in a['results']['bindings']]
return dict(zip(ufid, uri))
def get_vivo_publishers(parms):
"""
Query VIVO and return a list of all the publishers found in VIVO
:param: parms: vivo_query parameters
:return: dictionary of uri keyed by simplified publisher name
"""
query = "select ?uri ?label where {?uri a vivo:Publisher . ?uri rdfs:label ?label .}"
a = vivo_query(query, parms)
label = [key_string(x['label']['value']) for x in a['results']['bindings']]
uri = [x['uri']['value'] for x in a['results']['bindings']]
return dict(zip(label, uri))
def get_vivo_journals(parms):
"""
Query VIVO and return a list of all the journals found in VIVO
:param: parms: vivo_query params
:return: dictionary of uri keyed by ISSN
"""
query = "select ?uri ?issn where {?uri bibo:issn ?issn .}"
a = vivo_query(query, parms)
issn = [x['issn']['value'] for x in a['results']['bindings']]
uri = [x['uri']['value'] for x in a['results']['bindings']]
return dict(zip(issn, uri))
def get_vivo_ccn(parms):
"""
Query VIVO and return a list of all the ccn found in VIVO
:param: parms: vivo_query parms
:return: dictionary of uri keyed by ccn
"""
query = "select ?uri ?ccn where {?uri uf:ccn ?ccn .}"
a = vivo_query(query, parms)
ccn = [x['ccn']['value'] for x in a['results']['bindings']]
uri = [x['uri']['value'] for x in a['results']['bindings']]
return dict(zip(ccn, uri))
def get_vivo_sponsorid(parms):
"""
Query VIVO and return a list of all the sponsorid found in VIVO
:param: parms: vivo_query parms
:return: dictionary of uri keyed by sponsorid
"""
query = "select ?uri ?sponsorid where {?uri a vivo:FundingOrganization . ?uri ufVivo:sponsorID ?sponsorid .}"
a = vivo_query(query, parms)
sponsorid = [x['sponsorid']['value'] for x in a['results']['bindings']]
uri = [x['uri']['value'] for x in a['results']['bindings']]
return dict(zip(sponsorid, uri))
def get_vivo_authors(parms):
"""
Query VIVO and return a list of all the authors found in VIVO. Authors are people connected to
publications through authorships
:param: parms: vivo_query parms
:return: dictionary of author uri keyed by display_name (that won't work!)
"""
query = """
SELECT ?uri ?display_name
WHERE
{
?art a bibo:AcademicArticle .
?art bibo:doi ?doi .
?art vivo:relatedBy ?a .
?a a vivo:Authorship .
?a vivo:relates ?author .
?uri a foaf:Person .
?uri rdfs:label ?display_name .
}
"""
a = vivo_query(query, parms)
display_name = [x['display_name']['value'] for x in a['results']['bindings']]
uri = [x['uri']['value'] for x in a['results']['bindings']]
return dict(zip(display_name, uri))
def get_vivo_positions(parms):
"""
Query VIVO and return a list of all the UF positions found in VIVO. UF positions will
have an hrTitle. Non UF positions will not have this property
:param: parms: vivo_query parameters
:return: dictionary of position uri keyed by ufid, deptid, hr_title, start_date
"""
query = """
select ?uri ?ufid ?deptid ?hr_title ?start_date
where {
?uri a vivo:Position .
?uri vivo:relates ?x . ?x uf:ufid ?ufid .
?uri vivo:relates ?y . ?y uf:deptid ?deptid .
?uri uf:hrTitle ?hr_title .
?uri vivo:dateTimeInterval ?dti . ?dti vivo:start ?start . ?start vivo:dateTimeValue ?start_date .
}
"""
a = vivo_query(query, parms)
ufids = [x['ufid']['value'] for x in a['results']['bindings']]
deptids = [x['deptid']['value'] for x in a['results']['bindings']]
hr_titles = [x['hr_title']['value'] for x in a['results']['bindings']]
start_dates = [x['start_date']['value'] for x in a['results']['bindings']]
keys = [';'.join(x) for x in zip(ufids, deptids, hr_titles, start_dates)]
uri = [x['uri']['value'] for x in a['results']['bindings']]
return dict(zip(keys, uri))
def read_update_def(filename, prefix):
"""
Read an update_def in JSON format, from a file
:param filename: name of file to read
:param prefix: text prefix for sparql queries
:rtype: dict
:return: JSON-like object from file, replacing all URI strings with URIRef objects
"""
def make_prefix_dict(prefix):
"""
Given prefix text, return a prefix dictionary with tags as keys and url strings as values
:param prefix:
:return: dictionary
:rtype: dict
"""
prefix_dict = {}
prefix_list = prefix.split()
for i in range(len(prefix_list) - 2):
if prefix_list[i].upper() == "PREFIX":
prefix_dict[prefix_list[i + 1]] = prefix_list[i + 2].replace('<', '').replace('>', '')
return prefix_dict
def cast_to_rdflib(t):
"""
Given a string t containing the name of an rdflib object, return the rdflib object. For now
this is returns xsd data types
Will throw a KeyValue error if t is not a known data type
:param t:
:return: an xsd data type
"""
from rdflib import XSD
cast_table = {
'xsd:integer': XSD.integer,
'xsd:string': XSD.string,
'xsd:datetime': XSD.datetime,
'xsd:boolean': XSD.boolean,
'xsd:decimal': XSD.decimal,
'xsd:anyURI': XSD.anyURI
}
r = cast_table[t]
return r
def fixit(current_object, prefix_dict):
"""
Read the def data structure and replace all string URIs with URIRef entities
:param current_object: the piece of the data structure to be fixed
:return current_object: the piece repaired in place
"""
from rdflib import URIRef
if isinstance(current_object, dict):
for k in current_object.keys():
current_object[k] = fixit(current_object[k], prefix_dict)
elif isinstance(current_object, list):
for i in range(0, len(current_object)):
current_object[i] = fixit(current_object[i], prefix_dict)
elif isinstance(current_object, basestring):
if current_object.startswith("http://"):
current_object = URIRef(current_object)
elif current_object.startswith("xsd:"):
current_object = cast_to_rdflib(current_object)
elif ':' in current_object:
k = current_object.find(':')
tag = str(current_object[0:k + 1])
if tag in prefix_dict:
current_object = URIRef(str(current_object).replace(tag, prefix_dict[tag]))
return current_object
def add_order(a, b):
"""
Given an update_def (a) and the string of the input file containing the update_def (b),
add an "order" parameter to the entity_def, specifying the column_def ordering. This
is used in subsequent processing to insure that the order in the input file is preserved
when output is created.
:param a: update_def
:param b: string of update_def from file
:return a new update_def dictionary with an order list in the entity def
"""
defn = a
loc = []
var_list = []
k = b.find("column_defs")
b = b[k:]
for var in defn['column_defs'].keys():
var_list.append(var)
loc.append(b.find(var + '": ['))
seq = sorted(loc)
order = [var_list[loc.index(v)] for v in seq]
defn['entity_def']['order'] = order
return defn
def validate_update_def(a):
"""
Validate the update_def. Throw InvalidDef if errors
:param a: update_def
:return None
"""
names = [y[x].get('object', None).get('name', '') for y in a['column_defs'].values() for x in range(len(y))]
col_names = a['column_defs'].keys()
for name in col_names:
if name in names:
raise InvalidDefException(name + " in object and column_defs")
# Test for multiple multiple predicates (can only have one multiple per path)
for name in col_names:
multiple = 0
for step in a['column_defs'][name]:
if step['predicate']['single'] == False:
multiple += 1
if multiple > 1:
raise InvalidDefException(name + ' has more than one multiple predicate')
# Test for reserved column names
reserved_words = {'uri', 'action'}
if set(col_names) & reserved_words != set():
raise InvalidDefException(str(set(col_names) & reserved_words) + " reserved words used as column names")
# Test for boolean value
for name in col_names:
for step in a['column_defs'][name]:
if step['predicate']['single'] == 'boolean' and 'value' not in step['object']:
raise InvalidDefException(name + 'is boolean with no value')
return None
import json
with open(filename, "r") as my_file:
data = my_file.read()
prefix_dict = make_prefix_dict(prefix)
update_def = fixit(json.loads(data), prefix_dict)
update_def = add_order(update_def, data)
validate_update_def(update_def)
return update_def
def add_qualifiers(input_path):
"""
Given an update_def input_path, generate the SPARQL fragment to express the qualifiers in the path, if any
:param input_path:
:return:
"""
return ' '.join([x['object'].get('qualifier', '') for x in input_path])
def make_update_query(column_name, entity_sparql, path):
"""
Given a path from an update_def data structure, generate the query needed to pull the triples from VIVO that might
be updated. Here's what the queries look like by path length
:param column_name:
Path length 1 example:
select ?uri (vivo:subOrganizationWithin as ?p) ?o
where {
... entity sparql goes here ...
?uri vivo:subOrganizationWithin ?o
}
Path Length 2 example:
select ?uri (vivo:webpage as ?p) (?webpage as ?o) (vivo:linkURI as ?p2) ?o2
where {
... entity sparql goes here ...
?uri vivo:webpage ?webpage . ?webpage vivo:linkURI ?o2 .
}
Path length 3 example:
select ?uri (vivo:dateTimeInterval as ?p) (?award_period as ?o) (vivo:end as ?p2)
(?end as ?o2) (vivo:dateTime as ?p3) ?o3
where {
... entity sparql goes here ...
?uri vivo:dateTimeInterval ?award_period . ?award_period vivo:end ?end . ?end vivo:dateTime ?o3 .
}
:return: a sparql query string
"""
query = ""
if len(path) == 1:
query = 'select ?uri (<' + str(path[0]['predicate']['ref']) + '> as ?p) (?' + column_name + ' as ?o)\n' + \
' where { ' + entity_sparql + '\n ?uri <' + str(path[0]['predicate']['ref']) + '> ?' + \
column_name + \
' . ' + add_qualifiers(path) + ' \n}'
elif len(path) == 2:
query = 'select ?uri (<' + str(path[0]['predicate']['ref']) + '> as ?p) ' + \
'(?' + path[0]['object']['name'] + ' as ?o) (<' + \
str(path[1]['predicate']['ref']) + '> as ?p2) ?o2\n' + \
' where { ' + entity_sparql + '\n ?uri <' + str(path[0]['predicate']['ref']) + '> ?' + \
path[0]['object']['name'] + ' . ?' + \
path[0]['object']['name'] + ' <' + str(path[1]['predicate']['ref']) + '> ?o2' + \
' . ' + add_qualifiers(path) + ' \n}'
elif len(path) == 3:
query = 'select ?uri (<' + str(path[0]['predicate']['ref']) + '> as ?p) ' + \
'(?' + path[0]['object']['name'] + ' as ?o) (<' + str(path[1]['predicate']['ref']) + '> as ?p2) (?' + \
path[1]['object']['name'] + ' as ?o2) (<' + str(path[2]['predicate']['ref']) + '> as ?p3) ?o3\n' + \
'where { ' + entity_sparql + '\n ?uri <' + str(path[0]['predicate']['ref']) + '> ?' + \
path[0]['object']['name'] + ' . ?' + \
path[0]['object']['name'] + ' <' + str(path[1]['predicate']['ref']) + '> ?' + \
path[1]['object']['name'] + \
' . ?' + path[1]['object']['name'] + ' <' + str(path[2]['predicate']['ref']) + '> ?o3' + \
' . ' + add_qualifiers(path) + ' \n}'
return query
def make_rdf_term(row_term):
"""
Given a row term from a JSON object returned by a SPARQL query (whew!) return a corresponding
rdflib term -- either a Literal or a URIRef
:param row_term:
:return: an rdf_term, either Literal or URIRef
"""
from rdflib import Literal, URIRef
if row_term['type'] == 'literal' or row_term['type'] == 'typed-literal':
rdf_term = Literal(row_term['value'], datatype=row_term.get('datatype', None),
lang=row_term.get('xml:lang', None))
else:
rdf_term = URIRef(row_term['value'])
return rdf_term
def get_graph(update_def, query_parms, debug=False):
"""
Given the update def, get a graph from VIVO of the triples eligible for updating
:return: graph of triples
"""
from rdflib import Graph, URIRef
a = Graph()
entity_query = 'select ?uri (<http://www.w3.org/1999/02/22-rdf-syntax-ns#type> as ?p) (<' + \
str(update_def['entity_def']['type']) + '> as ?o)\nwhere {\n ' + \
update_def['entity_def']['entity_sparql'] + '\n}'
result = vivo_query(entity_query, query_parms, debug=debug)
for row in result['results']['bindings']:
s = URIRef(row['uri']['value'])
p = URIRef(row['p']['value'])
o = make_rdf_term(row['o'])
a.add((s, p, o))
for column_name, path in update_def['column_defs'].items():
update_query = make_update_query(column_name, update_def['entity_def']['entity_sparql'], path)
if len(update_query) == 0:
continue
result = vivo_query(update_query, query_parms, debug=debug)
for row in result['results']['bindings']:
s = URIRef(row['uri']['value'])
p = URIRef(row['p']['value'])
o = make_rdf_term(row['o'])
a.add((s, p, o))
if 'p2' in row and 'o2' in row:
p2 = URIRef(row['p2']['value'])
o2 = make_rdf_term(row['o2'])
a.add((o, p2, o2))
if 'p3' in row and 'o3' in row:
p3 = URIRef(row['p3']['value'])
o3 = make_rdf_term(row['o3'])
a.add((o2, p3, o3))
if debug:
print "Triples in original graph", len(a)
return a
def new_uri(parms):
"""
Find an unused VIVO URI in the VIVO defined by the parms
:param parms: dictionary with queryuri, username, password and uriprefix
:return: a URI not in VIVO
"""
test_uri = ""
while True:
test_uri = parms['uriprefix'] + str(random.randint(1, 9999999999))
query = """
SELECT (COUNT(?z) AS ?count) WHERE {
<""" + test_uri + """> ?y ?z
}"""
response = vivo_query(query, parms)
if int(response["results"]["bindings"][0]['count']['value']) == 0:
break
return test_uri
def vivo_query(query, parms, debug=False):
"""
A new VIVO query function using SPARQLWrapper. Tested with Stardog, UF VIVO and Dbpedia
:param query: SPARQL query. VIVO PREFIX will be added
:param parms: dictionary with query parms: queryuri, username and password
:param debug: boolean. If true, query will be printed to stdout
:return: result object, typically JSON
:rtype: dict
"""
from SPARQLWrapper import SPARQLWrapper, JSON
if debug:
print >>sys.stderr, "in vivo_query"
print >>sys.stderr, parms
sparql = SPARQLWrapper(parms['queryuri'])
new_query = parms['prefix'] + '\n' + query
sparql.setQuery(new_query)
if debug:
print >>sys.stderr, new_query
sparql.setReturnFormat(JSON)
sparql.addParameter("email", parms['username'])
sparql.addParameter("password", parms['password'])
# sparql.setCredentials(parms['username'], parms['password'])
results = sparql.query()
results = results.convert()
return results
def write_update_def(update_def, filename):
"""
Write update_def to a json_file
:param filename: name of file to write
:return: None. A file is written
"""
import json
out_file = open(filename, "w")
json.dump(update_def, out_file, indent=4)
out_file.close()
return
def improve_email(email):
"""
Given an email string, fix it
"""
import re
exp = re.compile(r'\w+\.*\w+@\w+\.(\w+\.*)*\w+')
s = exp.search(email)
if s is None:
return ""
elif s.group() is not None:
return s.group()
else:
return ""
def improve_phone_number(phone, debug=False):
"""
Given an arbitrary string that attempts to represent a phone number,
return a best attempt to format the phone number according to ITU standards
If the phone number can not be repaired, the function returns an empty string
"""
phone_text = phone.encode('ascii', 'ignore') # encode to ascii
phone_text = phone_text.lower()
phone_text = phone_text.strip()
extension_digits = None
#
# strip off US international country code
#
if phone_text.find('+1 ') == 0:
phone_text = phone_text[3:]
if phone_text.find('+1-') == 0:
phone_text = phone_text[3:]
if phone_text.find('(1)') == 0:
phone_text = phone_text[3:]
digits = []
for c in list(phone_text):
if c in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
digits.append(c)
if len(digits) > 10 or phone_text.rfind('x') > -1:
# pull off the extension
i = phone_text.rfind(' ') # last blank
if i > 0:
extension = phone_text[i + 1:]
extension_digits = []
for c in list(extension):
if c in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
extension_digits.append(c)
digits = [] # reset the digits
for c in list(phone_text[:i + 1]):
if c in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
digits.append(c)
elif phone_text.rfind('x') > 0:
i = phone_text.rfind('x')
extension = phone_text[i + 1:]
extension_digits = []
for c in list(extension):
if c in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
extension_digits.append(c)
digits = [] # recalculate the digits
for c in list(phone_text[:i + 1]):
if c in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
digits.append(c)
else:
extension_digits = digits[10:]
digits = digits[:10]
if len(digits) == 7:
if phone[0:5] == '352392':
updated_phone = '' # Damaged UF phone number, nothing to repair
extension_digits = None
elif phone[0:5] == '352273':
updated_phone = '' # Another damaged phone number, not to repair
extension_digits = None
else:
updated_phone = '(352) ' + "".join(digits[0:3]) + '-' + "".join(digits[3:7])
elif len(digits) == 10:
updated_phone = '(' + "".join(digits[0:3]) + ') ' + "".join(digits[3:6]) + \
'-' + "".join(digits[6:10])
elif len(digits) == 5 and digits[0] == '2': # UF special
updated_phone = '(352) 392-' + "".join(digits[1:5])
elif len(digits) == 5 and digits[0] == '3': # another UF special
updated_phone = '(352) 273-' + "".join(digits[1:5])
else:
updated_phone = '' # no repair
extension_digits = None
if extension_digits is not None and len(extension_digits) > 0:
updated_phone = updated_phone + ' ext. ' + "".join(extension_digits)
if debug:
print phone.ljust(25), updated_phone.ljust(25)
return updated_phone
def comma_space(s):
"""
insert a space after every comma in s unless s ends in a comma
:param s: string to be checked for spaces after commas
:return s: improved string with commas always followed by spaces
:rtype: basestring
"""
k = s.find(',')
if -1 < k < len(s) - 1 and s[k + 1] != " ":
s = s[0:k] + ', ' + comma_space(s[k + 1:])
return s
def improve_course_title(s):
"""
The Office of the University Registrar at UF uses a series of abbreviations to fit course titles into limited text
strings.
Here we attempt to reverse the process -- a short title is turned into a
longer one for use in labels
"""
abbrev_table = {
"Intro ": "Introduction ",
"To ": "to ",
"Of ": "of ",
"In ": "in ",
"Stat ": "Statistics ",
"Spec ": "Special ",
"Top ": "Topics ",
"Hist ": "History ",
"Hlthcare ": "Healthcare ",
"Prac ": "Practice "
}
s = s.lower() # convert to lower
s = s.title() # uppercase each word
s += ' ' # add a trailing space so we can find these abbreviated words throughout the string
t = s.replace(", ,", ",")
t = t.replace(" ", " ")
t = t.replace("/", " @")
t = t.replace("/", " @") # might be two slashes in the input
t = t.replace(",", " !")
t = t.replace("-", " #")
for abbrev in abbrev_table:
t = t.replace(abbrev, abbrev_table[abbrev])
t = t.replace(" @", "/") # restore /
t = t.replace(" @", "/") # restore /
t = t.replace(" !", ",") # restore ,
t = t.replace(" !", ",") # restore ,
t = t.replace(" #", "-") # restore -
t = comma_space(t.strip())
return t[0].upper() + t[1:]
def improve_jobcode_description(s):
"""
HR uses a series of abbreviations to fit job titles into limited text
strings.
Here we attempt to reverse the process -- a short title is turned into a
longer one for use in position labels
"""
abbrev_table = {
"Aca ": "Academic ",
"Act ": "Acting ",
"Adj ": "Adjunct ",
"Adm ": "Administrator ",
"Admin ": "Administrative ",
"Adv ": "Advisory ",
"Advanc ": "Advanced ",
"Aff ": "Affiliate ",
"Affl ": "Affiliate ",
"Agric ": "Agricultural ",
"Alumn Aff ": "Alumni Affairs ",
"Anal ": "Analyst ",
"Anlst ": "Analyst ",
"Aso ": "Associate ",
"Asoc ": "Associate ",
"Assoc ": "Associate ",
"Asst ": "Assistant ",
"Asst. ": "Assistant ",
"Ast ": "Assistant ",
"Ast #G ": "Grading Assistant ",
"Ast #R ": "Research Assistant ",
"Ast #T ": "Teaching Assistant ",
"Bio ": "Biological ",
"Cfo ": "Chief Financial Officer ",
"Chem ": "Chemist ",
"Chr ": "Chair ",
"Cio ": "Chief Information Officer ",
"Clin ": "Clinical ",
"Clrk ": "Clerk ",
"Co ": "Courtesy ",
"Comm ": "Communications ",
"Communic ": "Communications ",
"Coo ": "Chief Operating Officer ",
"Coord ": "Coordinator ",
"Couns ": "Counselor ",
"Crd ": "Coordinator ",
"Ctr ": "Center ",
"Ctsy ": "Courtesy ",
"Cty ": "County ",
"Dev ": "Development ",
"Devel ": "Development ",
"Dir ": "Director ",
"Dis ": "Distinguished ",
"Dist ": "Distinguished ",
"Div ": "Division ",
"Dn ": "Dean ",
"Educ ": "Education ",
"Emer ": "Emeritus ",
"Emin ": "Eminent ",
"Enforce ": "Enforcement ",
"Eng ": "Engineer ",
"Environ ": "Environmental ",
"Ext ": "Extension ",
"Facil ": "Facility ",
"Fin ": "Financial",
"Finan ": "Financial ",
"Gen ": "General ",
"Grd ": "Graduate ",
"Hlt ": "Health ",
"Hlth ": "Health ",
"Ii ": "II ",
"Iii ": "III ",
"Info ": "Information ",
"Int ": "Interim ",
"It ": "Information Technology ",
"Iv ": "IV ",
"Jnt ": "Joint ",
"Jr": "Junior",
"Lect ": "Lecturer ",
"Mgr ": "Manager ",
"Mgt ": "Management ",
"Mstr ": "Master ",
"Opr ": "Operator ",
"Phas ": "Phased ",
"Pky ": "PK Yonge ",
"Postdoc ": "Postdoctoral ",
"Pract ": "Practitioner ",
"Pres ": "President ",
"Pres5 ": "President 5 ",
"Pres6 ": "President 6 ",
"Prg ": "Program ",
"Prof ": "Professor ",
"Prof. ": "Professor ",
"Prog ": "Programmer ",
"Progs ": "Programs ",
"Prov ": "Provisional ",
"Radiol ": "Radiology ",
"Rcv ": "Receiving ",
"Registr ": "Registration ",
"Rep ": "Representative ",
"Res ": "Research ",
"Ret ": "Retirement ",
"Rsch ": "Research ",
"Rsrh ": "Research ",
"Sch ": "School ",
"Sci ": "Scientist ",
"Sctst ": "Scientist ",
"Ser ": "Service ",
"Serv ": "Service ",
"Spc ": "Specialist ",
"Spec ": "Specialist ",
"Spv ": "Supervisor ",
"Sr ": "Senior ",
"Stu ": "Student ",
"Stud ": "Student",
"Supp ": "Support ",
"Supt ": "Superintendent ",
"Supv ": "Supervisor ",
"Svcs ": "Services ",
"Tch ": "Teaching ",
"Tech ": "Technician ",
"Technol ": "Technologist ",
"Tele ": "Telecommunications ",
"Tv ": "TV ",
"Univ ": "University ",
"Vis ": "Visiting ",
"Vp ": "Vice President "
}
s = s.lower() # convert to lower
s = s.title() # uppercase each word
s += ' ' # add a trailing space so we can find these abbreviated words throughout the string
t = s.replace(", ,", ",")
t = t.replace(" ", " ")
t = t.replace("/", " @")
t = t.replace("/", " @") # might be two slashes in the input
t = t.replace(",", " !")
t = t.replace("&", " and ")
for abbrev in abbrev_table:
t = t.replace(abbrev, abbrev_table[abbrev])
t = t.replace(" @", "/") # restore /
t = t.replace(" @", "/")
t = t.replace(" !", ",") # restore ,
t = t.replace(" #", "-") # restore -
return t[:-1] # Take off the trailing space
def improve_org_name(s):
"""
Organization names are often abbreviated and sometime misspelled. Build a translation table here of
corrections/improvements to org names