Add some additional logging to util/rdflib.py to help debugging
[htsworkflow.git] / htsworkflow / util / rdfhelp.py
1 """Helper features for working with librdf
2 """
3 import logging
4 import os
5 import types
6
7 import RDF
8
9 logger = logging.getLogger(__name__)
10
11 # standard ontology namespaces
12 owlNS = RDF.NS('http://www.w3.org/2002/07/owl#')
13 dublinCoreNS = RDF.NS("http://purl.org/dc/elements/1.1/")
14 rdfNS = RDF.NS("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
15 rdfsNS= RDF.NS("http://www.w3.org/2000/01/rdf-schema#")
16 xsdNS = RDF.NS("http://www.w3.org/2001/XMLSchema#")
17
18 # internal ontologies
19 submissionOntology = RDF.NS("http://jumpgate.caltech.edu/wiki/UcscSubmissionOntology#")
20 dafTermOntology = RDF.NS("http://jumpgate.caltech.edu/wiki/UcscDaf#")
21 libraryOntology = RDF.NS("http://jumpgate.caltech.edu/wiki/LibraryOntology#")
22 submissionLog = RDF.NS("http://jumpgate.caltech.edu/wiki/SubmissionsLog/")
23
24 def sparql_query(model, query_filename):
25     """Execute sparql query from file
26     """
27     logger.info("Opening: %s" % (query_filename,))
28     query_body = open(query_filename,'r').read()
29     query = RDF.SPARQLQuery(query_body)
30     results = query.execute(model)
31     for row in results:
32         output = []
33         for k,v in row.items()[::-1]:
34             print "{0}: {1}".format(k,v)
35         print 
36
37
38 def blankOrUri(value=None):
39     node = None
40     if value is None:
41         node = RDF.Node()
42     elif type(value) in types.StringTypes:
43         node = RDF.Node(uri_string=value)
44     elif isinstance(value, RDF.Node):
45         node = value
46
47     return node
48
49
50 def toTypedNode(value):
51     if type(value) == types.BooleanType:
52         value_type = xsdNS['boolean'].uri
53         if value:
54             value = u'1'
55         else:
56             value = u'0'
57     elif type(value) in (types.IntType, types.LongType):
58         value_type = xsdNS['decimal'].uri
59         value = unicode(value)
60     elif type(value) == types.FloatType:
61         value_type = xsdNS['float'].uri
62         value = unicode(value)
63     elif type(value) in types.StringTypes:
64         value_type = xsdNS['string'].uri
65     else:
66         value_type = None
67         value = unicode(value)
68
69     return RDF.Node(literal=value, datatype=value_type)
70
71 def fromTypedNode(node):
72     if node is None:
73         return None
74
75     value_type = str(node.literal_value['datatype'])
76     # chop off xml schema declaration
77     value_type = value_type.replace(str(xsdNS[''].uri),'')
78     literal = node.literal_value['string']
79     literal_lower = literal.lower()
80
81     if value_type == 'boolean':
82         if literal_lower in ('1', 'yes', 'true'):
83             return True
84         elif literal_lower in ('0', 'no', 'false'):
85             return False
86         else:
87             raise ValueError("Unrecognized boolean %s" % (literal,))
88     elif value_type == 'decimal' and literal.find('.') == -1:
89         return int(literal)
90     elif value_type in ('decimal', 'float', 'double'):
91         return float(literal)
92     elif value_type in ('string'):
93         return literal
94     elif value_type in ('dateTime'):
95         raise NotImplemented('need to parse isoformat date-time')
96
97     return literal
98
99     
100 def get_model(model_name=None, directory=None):
101     if directory is None:
102         directory = os.getcwd()
103         
104     if model_name is None:
105         storage = RDF.MemoryStorage()
106         logger.info("Using RDF Memory model")
107     else:
108         options = "hash-type='bdb',dir='{0}'".format(directory)
109         storage = RDF.HashStorage(model_name,
110                       options=options)
111         logger.info("Using {0} with options {1}".format(model_name, options))
112     model = RDF.Model(storage)
113     return model
114         
115
116 def load_into_model(model, parser_name, filename, ns=None):
117     if not os.path.exists(filename):
118         raise IOError("Can't find {0}".format(filename))
119     
120     data = open(filename, 'r').read()
121     rdf_parser = RDF.Parser(name=parser_name)
122     rdf_parser.parse_string_into_model(model, data, ns)
123
124
125 def get_serializer(name='turtle'):
126     """Return a serializer with our standard prefixes loaded
127     """
128     writer = RDF.Serializer(name=name)
129     # really standard stuff
130     writer.set_namespace('owl', owlNS._prefix)
131     writer.set_namespace('rdf', rdfNS._prefix)
132     writer.set_namespace('rdfs', rdfsNS._prefix)
133     writer.set_namespace('xsd', xsdNS._prefix)
134
135     # should these be here, kind of specific to an application
136     writer.set_namespace('libraryOntology', libraryOntology._prefix)
137     writer.set_namespace('ucscSubmission', submissionOntology._prefix)
138     writer.set_namespace('ucscDaf', dafTermOntology._prefix)
139     return writer
140