def _testNegative(uri, manifest):
if verbose:
write(u"TESTING: %s" % uri)
result = 0 # 1=failed, 0=passed
inDoc = first(manifest.objects(uri, TEST["inputDocument"]))
store = Graph()
test = BNode()
results.add((test, RESULT["test"], uri))
results.add((test, RESULT["system"], system))
try:
if inDoc[-3:] == ".nt":
format = "nt"
else:
format = "xml"
store.parse(cached_file(inDoc), publicID=inDoc, format=format)
except ParserError:
results.add((test, RDF.type, RESULT["PassingRun"]))
# pass
else:
write(u"""Failed: '%s'""" % uri)
results.add((test, RDF.type, RESULT["FailingRun"]))
result = 1
return result
python类BNode()的实例源码
def testPositive(self):
manifest = self.manifest
uris = list(manifest.subjects(RDF.type, TEST["PositiveParserTest"]))
uris.sort()
num_failed = total = 0
for uri in uris:
status = first(manifest.objects(uri, TEST["status"]))
# Failing tests, skipped
if uri[44:] in skipped:
status = Literal("Locally DISAPPROVED")
write("Skipping %s" % uri)
if status == Literal("APPROVED"):
result = _testPositive(uri, manifest)
test = BNode()
results.add((test, RESULT["test"], uri))
results.add((test, RESULT["system"], system))
if not result:
results.add((test, RDF.type, RESULT["PassingRun"]))
else:
results.add((test, RDF.type, RESULT["FailingRun"]))
total += 1
num_failed += result
self.assertEquals(
num_failed, 0, "Failed: %s of %s." % (num_failed, total))
def generate_RDF_collection( graph, vals ) :
"""
Generate an RDF List from vals, returns the head of the list
@param graph: RDF graph
@type graph: RDFLib Graph
@param vals: array of RDF Resources
@return: head of the List (an RDF Resource)
"""
# generate an RDF List, returns the head
# list has all the elements in RDF format already
heads = [ BNode() for r in vals ] + [ ns_rdf["nil"] ]
for i in range(0, len(vals)) :
graph.add( (heads[i], ns_rdf["first"], vals[i]) )
graph.add( (heads[i], ns_rdf["rest"], heads[i+1]) )
return heads[0]
#################################################################################
def parseJsonTerm(d):
"""rdflib object (Literal, URIRef, BNode) for the given json-format dict.
input is like:
{ 'type': 'uri', 'value': 'http://famegame.com/2006/01/username' }
{ 'type': 'literal', 'value': 'drewp' }
"""
t = d['type']
if t == 'uri':
return URIRef(d['value'])
elif t == 'literal':
if 'xml:lang' in d:
return Literal(d['value'], lang=d['xml:lang'])
return Literal(d['value'])
elif t == 'typed-literal':
return Literal(d['value'], datatype=URIRef(d['datatype']))
elif t == 'bnode':
return BNode(d['value'])
else:
raise NotImplementedError("json term type %r" % t)
def termToJSON(self, term):
if isinstance(term, URIRef):
return {'type': 'uri', 'value': unicode(term)}
elif isinstance(term, Literal):
if term.datatype is not None:
return {'type': 'typed-literal',
'value': unicode(term),
'datatype': unicode(term.datatype)}
else:
r = {'type': 'literal',
'value': unicode(term)}
if term.language is not None:
r['xml:lang'] = term.language
return r
elif isinstance(term, BNode):
return {'type': 'bnode', 'value': str(term)}
elif term is None:
return None
else:
raise ResultException(
'Unknown term type: %s (%s)' % (term, type(term)))
def __init__(self, graph=None, bindings=None):
self.bindings = bindings or Bindings()
if isinstance(graph, ConjunctiveGraph):
self._dataset = graph
if rdflib.plugins.sparql.SPARQL_DEFAULT_GRAPH_UNION:
self.graph = self.dataset
else:
self.graph = self.dataset.default_context
else:
self._dataset = None
self.graph = graph
self.prologue = None
self.now = datetime.datetime.now()
self.bnodes = collections.defaultdict(BNode)
def _node_from_result(node):
"""
Helper function that casts XML node in SPARQL results
to appropriate rdflib term
"""
if node.tag == '{%s}bnode' % SPARQL_NS:
return BNode(node.text)
elif node.tag == '{%s}uri' % SPARQL_NS:
return URIRef(node.text)
elif node.tag == '{%s}literal' % SPARQL_NS:
value = node.text if node.text is not None else ''
if 'datatype' in node.attrib:
dt = URIRef(node.attrib['datatype'])
return Literal(value, datatype=dt)
elif '{http://www.w3.org/XML/1998/namespace}lang' in node.attrib:
return Literal(value, lang=node.attrib[
"{http://www.w3.org/XML/1998/namespace}lang"])
else:
return Literal(value)
else:
raise Exception('Unknown answer type')
def getgraphuris(self):
"""Method to get all available named graphs.
Returns:
A list containing all graph uris found in store.
"""
graphs = []
for graph in self.store.contexts():
if isinstance(graph, BNode) or str(graph.identifier) == 'default':
pass
else:
graphs.append(graph.identifier)
return graphs
def add_year(self, year):
bnode = rdflib.BNode()
self.graph.add((self.work, BF.subject, bnode))
self.graph.add((bnode, rdflib.RDF.type, BF.Temporal))
self.graph.add((bnode, rdflib.RDF.value, rdflib.Literal(year)))
def agent_relationship_inv_lod(request, agent_assoc_id):
aa = AgentAssociation.objects.filter(id=agent_assoc_id)
if not aa:
return HttpResponse({}, content_type='application/json')
else:
agent_association = aa[0]
from rdflib import Graph, Literal, BNode
from rdflib.namespace import FOAF, RDF, RDFS, OWL, SKOS
from rdflib.serializer import Serializer
from rdflib import Namespace, URIRef
path, instance_abbrv, context, store, vf_ns = get_lod_setup_items()
ref = URIRef(instance_abbrv + ":agent-relationship-inv-lod/" + str(agent_association.id) + "/")
inv_ref = URIRef(instance_abbrv + ":agent-relationship-lod/" + str(agent_association.id) + "/")
ref_object = URIRef(instance_abbrv + ":agent-lod/" + str(agent_association.is_associate.id) + "/")
ref_subject = URIRef(instance_abbrv + ":agent-lod/" + str(agent_association.has_associate.id) + "/")
property_name = camelcase_lower(agent_association.association_type.inverse_label)
ref_relationship = URIRef(instance_abbrv + ":agent-relationship-type-lod/" + property_name)
store.add((ref, RDF.type, vf_ns["Relationship"]))
store.add((ref, vf_ns["subject"], ref_subject))
store.add((ref, vf_ns["object"], ref_object))
store.add((ref, vf_ns["relationship"], ref_relationship))
store.add((ref, OWL.inverseOf, inv_ref))
ser = store.serialize(format='json-ld', context=context, indent=4)
return HttpResponse(ser, content_type='application/json')
#return render_to_response("valueaccounting/agent_association.html", {
# "agent_association": agent_association,
#}, context_instance=RequestContext(request))
def agent_type_lod(request, agent_type_name):
ats = AgentType.objects.all()
agent_type = None
#import pdb; pdb.set_trace()
for at in ats:
if camelcase(at.name) == agent_type_name:
agent_type = at
if not agent_type:
return HttpResponse({}, content_type='application/json')
from rdflib import Graph, Literal, BNode
from rdflib.namespace import FOAF, RDF, RDFS, OWL, SKOS
from rdflib.serializer import Serializer
from rdflib import Namespace, URIRef
path, instance_abbrv, context, store, vf_ns = get_lod_setup_items()
if agent_type.name != "Person" and agent_type.name != "Group" and agent_type.name != "Individual":
class_name = camelcase(agent_type.name)
ref = URIRef(instance_abbrv + ":agent-type-lod/" +class_name)
store.add((ref, RDF.type, OWL.Class))
store.add((ref, SKOS.prefLabel, Literal(class_name, lang="en")))
if agent_type.party_type == "individual":
store.add((ref, RDFS.subClassOf, vf_ns.Person))
else:
store.add((ref, RDFS.subClassOf, vf_ns.Group))
ser = store.serialize(format='json-ld', context=context, indent=4)
return HttpResponse(ser, content_type='application/json')
#return render_to_response("valueaccounting/agent_type.html", {
# "agent_type": agent_type,
#}, context_instance=RequestContext(request))
def agent_relationship_type_lod(request, agent_assoc_type_name):
#import pdb; pdb.set_trace()
aats = AgentAssociationType.objects.all()
agent_assoc_type = None
for aat in aats:
if camelcase_lower(aat.label) == agent_assoc_type_name:
agent_assoc_type = aat
inverse = False
elif camelcase_lower(aat.inverse_label) == agent_assoc_type_name:
agent_assoc_type = aat
inverse = True
if not agent_assoc_type:
return HttpResponse({}, content_type='application/json')
from rdflib import Graph, Literal, BNode
from rdflib.namespace import FOAF, RDF, RDFS, OWL, SKOS
from rdflib.serializer import Serializer
from rdflib import Namespace, URIRef
path, instance_abbrv, context, store, vf_ns = get_lod_setup_items()
if inverse:
property_name = camelcase_lower(agent_assoc_type.inverse_label)
inverse_property_name = camelcase_lower(agent_assoc_type.label)
label = agent_assoc_type.inverse_label
else:
property_name = camelcase_lower(agent_assoc_type.label)
inverse_property_name = camelcase_lower(agent_assoc_type.inverse_label)
label = agent_assoc_type.label
ref = URIRef(instance_abbrv + ":agent-relationship-type-lod/" + property_name)
inv_ref = URIRef(instance_abbrv + ":agent-relationship-type-lod/" + inverse_property_name)
store.add((ref, RDF.type, RDF.Property))
store.add((ref, SKOS.prefLabel, Literal(label, lang="en")))
store.add((ref, OWL.inverseOf, inv_ref))
ser = store.serialize(format='json-ld', context=context, indent=4)
return HttpResponse(ser, content_type='application/json')
#return render_to_response("valueaccounting/agent_assoc_type.html", {
# "agent_assoc_type": agent_assoc_type,
#}, context_instance=RequestContext(request))
def agent_relationship_lod(request, agent_assoc_id):
aa = AgentAssociation.objects.filter(id=agent_assoc_id)
if not aa:
return HttpResponse({}, content_type='application/json')
else:
agent_association = aa[0]
from rdflib import Graph, Literal, BNode
from rdflib.namespace import FOAF, RDF, RDFS, OWL, SKOS
from rdflib.serializer import Serializer
from rdflib import Namespace, URIRef
path, instance_abbrv, context, store, vf_ns = get_lod_setup_items()
ref = URIRef(instance_abbrv + ":agent-relationship-lod/" + str(agent_association.id) + "/")
inv_ref = URIRef(instance_abbrv + ":agent-relationship-inv-lod/" + str(agent_association.id) + "/")
ref_subject = URIRef(instance_abbrv + ":agent-lod/" + str(agent_association.is_associate.id) + "/")
ref_object = URIRef(instance_abbrv + ":agent-lod/" + str(agent_association.has_associate.id) + "/")
property_name = camelcase_lower(agent_association.association_type.label)
ref_relationship = URIRef(instance_abbrv + ":agent-relationship-type/" + property_name)
store.add((ref, RDF.type, vf_ns["Relationship"]))
store.add((ref, vf_ns["subject"], ref_subject))
store.add((ref, vf_ns["object"], ref_object))
store.add((ref, vf_ns["relationship"], ref_relationship))
store.add((ref, OWL.inverseOf, inv_ref))
ser = store.serialize(format='json-ld', context=context, indent=4)
return HttpResponse(ser, content_type='application/json')
#return render_to_response("valueaccounting/agent_association.html", {
# "agent_association": agent_association,
#}, context_instance=RequestContext(request))
def agent_relationship_inv_lod(request, agent_assoc_id):
aa = AgentAssociation.objects.filter(id=agent_assoc_id)
if not aa:
return HttpResponse({}, content_type='application/json')
else:
agent_association = aa[0]
from rdflib import Graph, Literal, BNode
from rdflib.namespace import FOAF, RDF, RDFS, OWL, SKOS
from rdflib.serializer import Serializer
from rdflib import Namespace, URIRef
path, instance_abbrv, context, store, vf_ns = get_lod_setup_items()
ref = URIRef(instance_abbrv + ":agent-relationship-inv-lod/" + str(agent_association.id) + "/")
inv_ref = URIRef(instance_abbrv + ":agent-relationship-lod/" + str(agent_association.id) + "/")
ref_object = URIRef(instance_abbrv + ":agent-lod/" + str(agent_association.is_associate.id) + "/")
ref_subject = URIRef(instance_abbrv + ":agent-lod/" + str(agent_association.has_associate.id) + "/")
property_name = camelcase_lower(agent_association.association_type.inverse_label)
ref_relationship = URIRef(instance_abbrv + ":agent-relationship-type-lod/" + property_name)
store.add((ref, RDF.type, vf_ns["Relationship"]))
store.add((ref, vf_ns["subject"], ref_subject))
store.add((ref, vf_ns["object"], ref_object))
store.add((ref, vf_ns["relationship"], ref_relationship))
store.add((ref, OWL.inverseOf, inv_ref))
ser = store.serialize(format='json-ld', context=context, indent=4)
return HttpResponse(ser, content_type='application/json')
#return render_to_response("valueaccounting/agent_association.html", {
# "agent_association": agent_association,
#}, context_instance=RequestContext(request))
def make_rdf_graph(movies):
mg=ConjunctiveGraph()
mg.bind('fb',FB)
mg.bind('dc',DC)
for movie in movies:
# Make a movie node
movie_node=IVA_MOVIE[movie['id']]
mg.add((movie_node,DC['title'],Literal(movie['title'])))
# Make the director node, give it a name and link it to the movie
dir_node=IVA_PERSON[movie['director']['id']]
mg.add((movie_node,FB['film.film.directed_by'],dir_node))
mg.add((dir_node,DC['title'],Literal(movie['director']['name'])))
for actor in movie['actors']:
# The performance node is a blank node -- it has no URI
performance=BNode()
# The performance is connected to the actor and the movie
actor_node=IVA_PERSON[actor['id']]
mg.add((actor_node,DC['title'],Literal(actor['name'])))
mg.add((performance,FB['film.performance.actor'],actor_node))
# If you had the name of the role, you could also add it to the
# performance node, e.g.
# mg.add((performance,FB['film.performance.role'],Literal('Carrie Bradshaw')))
mg.add((movie_node,FB['film.film.performances'],performance))
return mg
def _object(self, subject, predicate):
'''
Helper for returning the first object for this subject and predicate
Both subject and predicate must be rdflib URIRef or BNode objects
Returns an rdflib reference (URIRef or BNode) or None if not found
'''
for _object in self.g.objects(subject, predicate):
return _object
return None
def _object_value(self, subject, predicate):
'''
Given a subject and a predicate, returns the value of the object
Both subject and predicate must be rdflib URIRef or BNode objects
If found, the unicode representation is returned, else None
'''
for o in self.g.objects(subject, predicate):
return unicode(o)
return None
def _object_value_list(self, subject, predicate):
'''
Given a subject and a predicate, returns a list with all the values of
the objects
Both subject and predicate must be rdflib URIRef or BNode objects
If no values found, returns an empty string
'''
return [unicode(o) for o in self.g.objects(subject, predicate)]
def _time_interval(self, subject, predicate):
'''
Returns the start and end date for a time interval object
Both subject and predicate must be rdflib URIRef or BNode objects
It checks for time intervals defined with both schema.org startDate &
endDate and W3C Time hasBeginning & hasEnd.
Note that partial dates will be expanded to the first month / day
value, eg '1904' -> '1904-01-01'.
Returns a tuple with the start and end date values, both of which
can be None if not found
'''
start_date = end_date = None
for interval in self.g.objects(subject, predicate):
# Fist try the schema.org way
start_date = self._object_value(interval, SCHEMA.startDate)
end_date = self._object_value(interval, SCHEMA.endDate)
if start_date or end_date:
return start_date, end_date
# If no luck, try the w3 time way
start_nodes = [t for t in self.g.objects(interval,
TIME.hasBeginning)]
end_nodes = [t for t in self.g.objects(interval,
TIME.hasEnd)]
if start_nodes:
start_date = self._object_value(start_nodes[0],
TIME.inXSDDateTime)
if end_nodes:
end_date = self._object_value(end_nodes[0],
TIME.inXSDDateTime)
return start_date, end_date