本文整理汇总了Python中rdflib.compare.isomorphic函数的典型用法代码示例。如果您正苦于以下问题:Python isomorphic函数的具体用法?Python isomorphic怎么用?Python isomorphic使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了isomorphic函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_updatelist_cut_bnodes
def test_updatelist_cut_bnodes(self):
bn = B()
self.g.set((self.g.value(PA, VOCAB.prefLang), RDF.first, bn))
self.g.set((bn, VOCAB.foo, Literal("foo")))
if not isomorphic(self.g, G(INITIAL.replace('''( "fr" "en" "tlh" )''', '''( [v:foo "foo"] "en" "tlh" )'''))):
raise ValueError("Error while setting up test...")
self._my_updatelist(PA, VOCAB.prefLang, Slice(0, 1), [])
exp = G(INITIAL.replace('''( "fr" "en" "tlh" )''', '''( "en" "tlh" )'''))
# NB: no trace for the arc ''' _:nb v:foo "foo" ''' in the graph
got = self.g
assert isomorphic(got, exp), got.serialize(format="turtle")
示例2: testDontReplaceSourceStatements
def testDontReplaceSourceStatements(self):
g = fromN3(''' { :a :b :c } => { :a :b :c } . ''')
escapeOutputStatements(g, [(NS['a'], NS['b'], NS['c'])])
expected = fromN3('''
{ :a :b :c } =>
{ :output :statement [ :subj :a; :pred :b; :obj :c ] } . ''')
self.assert_(isomorphic(impliedGraph(expected), impliedGraph(g)))
示例3: test_query2
def test_query2(self):
with open(join(EXAMPLES, "query2.json")) as query_file:
q = load(query_file)
result = apply(q, self.g)
expected = Graph()
expected.load(join(EXAMPLES, "query2.result.ttl"), format="turtle")
assert isomorphic(result.graph, expected), result.graph.serialize(format="turtle")
示例4: turtle
def turtle(test):
g = Graph()
try:
base = 'http://www.w3.org/2013/TurtleTests/'+split_uri(test.action)[1]
g.parse(test.action, publicID=base, format='turtle')
if not test.syntax:
raise AssertionError("Input shouldn't have parsed!")
if test.result: # eval test
res = Graph()
res.parse(test.result, format='nt')
if verbose:
both, first, second = graph_diff(g,res)
if not first and not second: return
print "Diff:"
#print "%d triples in both"%len(both)
print "Turtle Only:"
for t in first:
print t
print "--------------------"
print "NT Only"
for t in second:
print t
raise Exception('Graphs do not match!')
assert isomorphic(g, res), 'graphs must be the same'
except:
if test.syntax:
raise
示例5: testMatchWildcardPatternOnObject
def testMatchWildcardPatternOnObject(self):
g = fromN3(''' { :a :b :c } => { :d :e :f } . ''')
escapeOutputStatements(g, [(NS['d'], NS['e'], None)])
expected = fromN3('''
{ :a :b :c } =>
{ :output :statement [ :subj :d; :pred :e; :obj :f ] } . ''')
self.assert_(isomorphic(impliedGraph(expected), impliedGraph(g)))
示例6: test_add_two_bnodes
def test_add_two_bnodes(self):
# check that distinct bnodes in the source graph
# generate distinct fresh bnodes in the target graph ;
# as above, try to mess with existing bnode labels to check robustness
jdoe = BNode("ucbl")
jdup = BNode("am")
self.e.add(G([
(PA, FOAF.knows, jdoe),
(jdoe, FOAF.givenName, Literal("John")),
(jdoe, FOAF.familyName, Literal("Doe")),
(PA, FOAF.knows, jdup),
(jdup, FOAF.givenName, Literal("Jeanne")),
(jdup, FOAF.familyName, Literal("Dupont")),
]))
exp = G(INITIAL + """
<http://champin.net/#pa> f:knows
[
f:givenName "John" ;
f:familyName "Doe" ;
],
[
f:givenName "Jeanne" ;
f:familyName "Dupont" ;
];
.
""")
got = self.g
assert isomorphic(got, exp), got.serialize(format="turtle")
示例7: updateSummary
def updateSummary(self):
context = aq_inner(self.context)
# If the Summarizer Source is inactive, we're done
if not context.active:
raise SourceNotActive(context)
# Check if the Summarizer Source has an Summarizer Generator
if not context.generator:
raise NoGeneratorError(context)
generator = context.generator.to_object
generatorPath = '/'.join(generator.getPhysicalPath())
# Adapt the generator to a graph generator, and get the graph in XML form.
serialized = None
mimetype = None
if generator.datatype == 'json':
generator = IJsonGenerator(generator)
serialized = generator.generateJson()
json = jsonlib.read(serialized)
mimetype = SUMMARIZER_JSON_MIMETYPE
# Is there an active file?
if context.approvedFile:
# Is it identical to what we just generated?
print context.approvedFile.to_object.get_data()
current = jsonlib.read(context.approvedFile.to_object.get_data())
if sorted(json.items()) == sorted(current.items()):
raise NoUpdateRequired(context)
elif generator.datatype == 'rdf':
generator = IGraphGenerator(generator)
rdf = generator.generateGraph()
serialized = rdf.serialize()
mimetype = SUMMARIZER_XML_MIMETYPE
# Is there an active file?
if context.approvedFile:
# Is it identical to what we just generated?
current = Graph().parse(data=context.approvedFile.to_object.get_data())
if isomorphic(rdf, current):
raise NoUpdateRequired(context)
else:
raise UnknownGeneratorError(context)
# Create a new file and set it active
# TODO: Add validation steps here
timestamp = datetime.datetime.utcnow().isoformat()
newFile = context[context.invokeFactory(
'File',
context.generateUniqueId('File'),
title=u'Summary %s' % timestamp,
description=u'Generated at %s by %s' % (timestamp, generatorPath),
file=serialized,
)]
newFile.getFile().setContentType(mimetype)
newFile.reindexObject()
intIDs = getUtility(IIntIds)
newFileID = intIDs.getId(newFile)
context.approvedFile = RelationValue(newFileID)
notify(ObjectModifiedEvent(context))
示例8: test_delete_simple
def test_delete_simple(self):
self.e.delete(G([
(PA, FOAF.name, Literal("Pierre-Antoine Champin")),
]))
exp = G(INITIAL.replace("""f:name "Pierre-Antoine Champin" ;""", ""))
got = self.g
assert isomorphic(got, exp), got.serialize(format="turtle")
示例9: _test_parser
def _test_parser(jsonpath, turtlepath):
test_tree, test_graph = _load_test_data(jsonpath, turtlepath)
graph = to_rdf(test_tree, Graph())
assert isomorphic(graph, test_graph), \
"Expected graph:\n%s\nGot:\n %s" % (
test_graph.serialize(format='n3'),
graph.serialize(format='n3'))
示例10: test_graph_prefix
def test_graph_prefix():
"""
This is issue https://github.com/RDFLib/rdflib/issues/313
"""
g1 = Graph()
g1.parse(data="""
@prefix : <urn:ns1:> .
:foo <p> 42.
""", format="n3")
g2 = Graph()
g2.parse(data="""
@prefix : <urn:somethingelse:> .
<urn:ns1:foo> <p> 42.
""", format="n3")
assert isomorphic(g1, g2)
q_str = ("""
PREFIX : <urn:ns1:>
SELECT ?val
WHERE { :foo ?p ?val }
""")
q_prepared = prepareQuery(q_str)
expected = [(Literal(42),)]
eq_(list(g1.query(q_prepared)), expected)
eq_(list(g2.query(q_prepared)), expected)
eq_(list(g1.query(q_str)), expected)
eq_(list(g2.query(q_str)), expected)
示例11: test
def test(self):
metadata = None
if 'metadata' in option:
metadata = option['metadata']
try:
csvw = CSVW(csv_file, metadata_url=metadata)
except Exception as e:
# this should be a negative test
if TYPES[type]:
traceback.print_exc()
self.assertFalse(TYPES[type])
return
# if we get here this should be a positive test
self.assertTrue(TYPES[type])
# if we can parse it we should at least produce some embedded metadata
self.assertNotEqual(csvw.metadata, None)
# and the result should exists
self.assertNotEqual(result_url, None)
gr = Graph()
result = gr.parse(result_url)
converted_result = csvw.to_rdf()
result.serialize('output_rdf/' + name + '.ttl', format='turtle')
converted_result.serialize('output_rdf/generated' + name + '.ttl', format='turtle')
self.assertTrue(compare.isomorphic(result, converted_result))
示例12: test_add_complex
def test_add_complex(self):
g2add = G([(PA, VOCAB.favNumbers, B("l1"))])
Collection(g2add, B("l1"), [ Literal(i) for i in (42, 7, 2, 10) ])
self.e.add(g2add)
exp = G(INITIAL + """<http://champin.net/#pa> v:favNumbers (42 7 2 10) .""")
got = self.g
assert isomorphic(got, exp), got.serialize(format="turtle")
示例13: _test_serializer
def _test_serializer(inputpath, expectedpath, context, serpar):
test_tree, test_graph = _load_test_data(inputpath, expectedpath, context)
if isinstance(test_tree, ConjunctiveGraph):
expected = test_tree.serialize(format="json-ld")
else:
expected = _to_json(_to_ordered(test_tree))
if test_graph is not None:
# toRdf, expected are nquads
result_tree = to_tree(test_graph, context_data=context)
result = _to_json(_to_ordered(result_tree))
elif inputpath.startswith('fromRdf'):
# fromRdf, expected in json-ld
g = ConjunctiveGraph()
data = open(p.join(test_dir, inputpath), 'rb').read()
g.parse(data=data, format="nquads", context=context)
result = g.serialize(format="json-ld", base=context)
else:
# json
f = open(p.join(test_dir, inputpath), 'rb')
result = json.load(f)[0]
f.close()
if isinstance(result, ConjunctiveGraph):
assert isomorphic(result, expected), \
"Expected graph of %s:\n%s\nGot graph of %s:\n %s" % (
expected.serialize(format='n3'),
result.serialize(format='n3'))
else:
assert jsonld_compare(expected, result) == True, \
"Expected JSON:\n%s\nGot:\n%s" % (expected, result)
示例14: testTwoMatchingStatements
def testTwoMatchingStatements(self):
g = fromN3(''' { :a :b :c } => { :d :e :f . :g :e :f } . ''')
escapeOutputStatements(g, [(None, NS['e'], None)])
expected = fromN3('''
{ :a :b :c } =>
{ :output :statement [ :subj :d; :pred :e; :obj :f ],
[ :subj :g; :pred :e; :obj :f ] } . ''')
self.assert_(isomorphic(impliedGraph(expected), impliedGraph(g)))
示例15: testWildcardAndNonMatchingStatements
def testWildcardAndNonMatchingStatements(self):
g = fromN3(''' { :a :b :c } => { :d :e :f . :g :e :f . } . ''')
escapeOutputStatements(g, [(NS['d'], NS['e'], NS['f'])])
expected = fromN3('''
{ :a :b :c } =>
{ :output :statement [ :subj :d; :pred :e; :obj :f ] .
:g :e :f } . ''')
self.assert_(isomorphic(impliedGraph(expected), impliedGraph(g)))