class TestGraphGraphPattern(unittest.TestCase): def setUp(self): self.graph1 = Graph( identifier=URIRef('http://example.org/foaf/aliceFoaf')) self.graph1.parse(StringIO(test_graph_a), format="n3") self.graph2 = Graph( identifier=URIRef('http://example.org/foaf/bobFoaf')) self.graph2.parse(StringIO(test_graph_b), format="n3") self.unionGraph = ReadOnlyGraphAggregate( graphs=[self.graph1, self.graph2]) def test_8_3_1(self): rt = self.unionGraph.query(test_query1, DEBUG=False).serialize("python") self.failUnless(len(rt) == 2, "Expected 2 item solution set") for src, bobNick in rt: self.failUnless( src in [ URIRef('http://example.org/foaf/aliceFoaf'), URIRef('http://example.org/foaf/bobFoaf') ], "Unexpected ?src binding :\n %s" % src) self.failUnless(bobNick in [Literal("Bobby"), Literal("Robert")], "Unexpected ?bobNick binding :\n %s" % bobNick) def test_8_3_2(self): rt = self.unionGraph.query(test_query2, DEBUG=False).serialize("python") self.failUnless(len(rt) == 1, "Expected 1 item solution set") self.failUnless(rt[0] == Literal("Robert"), "Unexpected ?nick binding :\n %s" % rt[0])
def testAggregateRaw(): memStore = plugin.get('IOMemory',Store)() graph1 = Graph(memStore) graph2 = Graph(memStore) graph3 = Graph(memStore) for n3Str,graph in [(testGraph1N3,graph1), (testGraph2N3,graph2), (testGraph3N3,graph3)]: graph.parse(StringIO(n3Str),format='n3') G = ReadOnlyGraphAggregate([graph1,graph2,graph3]) #Test triples assert len(list(G.triples((None,RDF.type,None)))) == 4 assert len(list(G.triples((URIRef("http://test/bar"),None,None)))) == 2 assert len(list(G.triples((None,URIRef("http://test/d"),None)))) == 3 #Test __len__ assert len(G) == 8 #Test __contains__ assert (URIRef("http://test/foo"),RDF.type,RDFS.Resource) in G barPredicates = [URIRef("http://test/d"),RDFS.isDefinedBy] assert len(list(G.triples_choices((URIRef("http://test/bar"),barPredicates,None)))) == 2
def PrepareSipCollection(adornedRuleset): """ Takes adorned ruleset and returns an RDF dataset formed from the sips associated with each adorned rule as named graphs. Also returns a mapping from the head predicates of each rule to the rules that match it - for efficient retrieval later """ headToRule = {} graphs = [] secondOrderRules = set() for rule in adornedRuleset: ruleHead = GetOp(rule.formula.head) if isinstance(ruleHead, Variable): #We store second order rules (i.e., rules whose head is a #predicate occurrence whose predicate symbol is a variable) aside secondOrderRules.add(rule) headToRule.setdefault(ruleHead, set()).add(rule) if hasattr(rule, 'sip'): graphs.append(rule.sip) #Second order rules are mapped from a None key (in order to indicate they are wildcards) headToRule[None] = secondOrderRules if not graphs: return graph = ReadOnlyGraphAggregate(graphs) graph.headToRule = headToRule return graph
def PrepareSipCollection(adornedRuleset): """ Takes adorned ruleset and returns an RDF dataset formed from the sips associated with each adorned rule as named graphs. Also returns a mapping from the head predicates of each rule to the rules that match it - for efficient retrieval later """ headToRule = {} graphs = [] secondOrderRules = set() for rule in adornedRuleset: ruleHead = GetOp(rule.formula.head) if isinstance(ruleHead,Variable): #We store second order rules (i.e., rules whose head is a #predicate occurrence whose predicate symbol is a variable) aside secondOrderRules.add(rule) headToRule.setdefault(ruleHead,set()).add(rule) if hasattr(rule,'sip'): graphs.append(rule.sip) #Second order rules are mapped from a None key (in order to indicate they are wildcards) headToRule[None]=secondOrderRules if not graphs: return graph = ReadOnlyGraphAggregate(graphs) graph.headToRule = headToRule return graph
def setUp(self): self.graph1 = Graph( identifier=URIRef('http://example.org/foaf/aliceFoaf')) self.graph1.parse(StringIO(test_graph_a), format="n3") self.graph2 = Graph( identifier=URIRef('http://example.org/foaf/bobFoaf')) self.graph2.parse(StringIO(test_graph_b), format="n3") self.unionGraph = ReadOnlyGraphAggregate( graphs=[self.graph1, self.graph2])
def closureGraph(self,sourceGraph,readOnly=True,store=None): if readOnly: if store is None and not sourceGraph: store = Graph().store store = store is None and sourceGraph.store or store roGraph=ReadOnlyGraphAggregate([sourceGraph,self.inferredFacts], store=store) roGraph.namespace_manager = NamespaceManager(roGraph) for srcGraph in [sourceGraph,self.inferredFacts]: for prefix,uri in srcGraph.namespaces(): roGraph.namespace_manager.bind(prefix,uri) return roGraph else: cg=ConjunctiveGraph() cg+=sourceGraph cg+=self.inferredFacts return cg
def testAggregateRaw(): memStore = plugin.get('IOMemory', Store)() graph1 = Graph(memStore) #Crea una instancia de un grafo graph2 = Graph(memStore) graph3 = Graph(memStore) for n3Str, graph in [(testGraph1N3, graph1), (testGraph2N3, graph2), (testGraph3N3, graph3)]: graph.parse(StringIO(n3Str), format='n3') #Lee los grafos desde texto en formato N3 for s, p, o in graph2: #Analizando el contenido del grafo print 'tripleta:', s, p, o, '-' # Utility class for treating a set of graphs as a single graph # Only read operations are supported (hence the name). #Essentially a ConjunctiveGraph over an explicit subset of the entire store. G = ReadOnlyGraphAggregate([graph1, graph2, graph3]) # print '----------------------------------------' print G.triples((None, RDF.type, None)) for g in G.triples((URIRef("http://test/bar"), None, None)): print g print '---------------------------------------' #Test triples assert len(list(G.triples((None, RDF.type, None)))) == 4 assert len(list(G.triples((URIRef("http://test/bar"), None, None)))) == 2 assert len(list(G.triples((None, URIRef("http://test/d"), None)))) == 3 #Test __len__ assert len(G) == 8 print '----------Analizando G:------------------------------' for g in G: print g print '----------------------------------------' #Test __contains__ assert (URIRef("http://test/foo"), RDF.type, RDFS.Resource) in G print '----------Comprobando contenido G:------------------------------' print(URIRef("http://test/foo"), RDF.type, RDFS.Resource) in G print '----------------------------------------' barPredicates = [URIRef("http://test/d"), RDFS.isDefinedBy] assert len( list( G.triples_choices( (URIRef("http://test/bar"), barPredicates, None)))) == 2
def testAggregateRaw(): memStore = plugin.get('IOMemory', Store)() graph1 = Graph(memStore) graph2 = Graph(memStore) graph3 = Graph(memStore) for n3Str, graph in [(testGraph1N3, graph1), (testGraph2N3, graph2), (testGraph3N3, graph3)]: graph.parse(StringIO(n3Str), format='n3') G = ReadOnlyGraphAggregate([graph1, graph2, graph3]) #Test triples assert len(list(G.triples((None, RDF.type, None)))) == 4 assert len(list(G.triples((URIRef("http://test/bar"), None, None)))) == 2 assert len(list(G.triples((None, URIRef("http://test/d"), None)))) == 3 #Test __len__ assert len(G) == 8 #Test __contains__ assert (URIRef("http://test/foo"), RDF.type, RDFS.Resource) in G barPredicates = [URIRef("http://test/d"), RDFS.isDefinedBy] assert len( list( G.triples_choices( (URIRef("http://test/bar"), barPredicates, None)))) == 2
class TestGraphGraphPattern(unittest.TestCase): def setUp(self): self.graph1 = Graph(identifier=URIRef('http://example.org/foaf/aliceFoaf')) self.graph1.parse(StringIO(test_graph_a), format="n3") self.graph2 = Graph(identifier=URIRef('http://example.org/foaf/bobFoaf')) self.graph2.parse(StringIO(test_graph_b), format="n3") self.unionGraph = ReadOnlyGraphAggregate(graphs=[self.graph1,self.graph2]) def test_8_3_1(self): rt=self.unionGraph.query(test_query1,DEBUG=False).serialize("python") self.failUnless(len(rt) == 2,"Expected 2 item solution set") for src,bobNick in rt: self.failUnless(src in [URIRef('http://example.org/foaf/aliceFoaf'),URIRef('http://example.org/foaf/bobFoaf')], "Unexpected ?src binding :\n %s" % src) self.failUnless(bobNick in [Literal("Bobby"),Literal("Robert")], "Unexpected ?bobNick binding :\n %s" % bobNick) def test_8_3_2(self): rt=self.unionGraph.query(test_query2,DEBUG=False).serialize("python") self.failUnless(len(rt) == 1,"Expected 1 item solution set") self.failUnless(rt[0] == Literal("Robert"),"Unexpected ?nick binding :\n %s" % rt[0])
def Evaluate(graph, query, passedBindings={}, DEBUG=False): """ Takes: 1. a rdflib.Graph.Graph instance 2. a SPARQL query instance (parsed using the BisonGen parser) 3. A dictionary of initial variable bindings (varName -> .. rdflib Term .. ) 4. DEBUG Flag Returns a list of tuples - each a binding of the selected variables in query order """ if query.prolog: query.prolog.DEBUG = DEBUG if query.query.dataSets: graphs = [] for dtSet in query.query.dataSets: if isinstance(dtSet, NamedGraph): graphs.append(Graph(graph.store, dtSet)) else: memStore = plugin.get('IOMemory', Store)() memGraph = Graph(memStore) try: memGraph.parse(dtSet, format='n3') except: #Parse as RDF/XML instead memGraph.parse(dtSet) graphs.append(memGraph) tripleStore = sparqlGraph.SPARQLGraph(ReadOnlyGraphAggregate(graphs)) else: tripleStore = sparqlGraph.SPARQLGraph(graph) if isinstance(query.query, SelectQuery) and query.query.variables: query.query.variables = [ convertTerm(item, query.prolog) for item in query.query.variables ] else: query.query.variables = [] #Interpret Graph Graph Patterns as Named Graphs graphGraphPatterns = categorizeGroupGraphPattern( query.query.whereClause.parsedGraphPattern)[0] # rt = categorizeGroupGraphPattern(query.query.whereClause.parsedGraphPattern)[0] # print rt[0], rt[1] if graphGraphPatterns: graphGraphP = graphGraphPatterns[0].nonTripleGraphPattern if isinstance(graphGraphP.name, Variable): if graphGraphP.name in passedBindings: tripleStore = sparqlGraph.SPARQLGraph( Graph(graph.store, passedBindings[graphGraphP.name])) else: #print graphGraphP #raise Exception("Graph Graph Patterns can only be used with variables bound at the top level or a URIRef or BNode term") tripleStore = sparqlGraph.SPARQLGraph( graph, graphVariable=graphGraphP.name) else: graphName = isinstance(graphGraphP.name, Variable) and passedBindings[ graphGraphP.name] or graphGraphP.name graphName = convertTerm(graphName, query.prolog) if isinstance(graph, ReadOnlyGraphAggregate) and not graph.store: targetGraph = [ g for g in graph.graphs if g.identifier == graphName ] assert len(targetGraph) == 1 targetGraph = targetGraph[0] else: targetGraph = Graph(graph.store, graphName) tripleStore = sparqlGraph.SPARQLGraph(targetGraph) gp = reorderGroupGraphPattern(query.query.whereClause.parsedGraphPattern) validateGroupGraphPattern(gp) basicPatterns, optionalPatterns = sparqlPSetup(gp, query.prolog) if DEBUG: print "## Select Variables ##\n", query.query.variables print "## Patterns ##\n", basicPatterns print "## OptionalPatterns ##\n", optionalPatterns result = queryObject(tripleStore, basicPatterns, optionalPatterns, passedBindings) if result == None: # generate some proper output for the exception :-) msg = "Errors in the patterns, no valid query object generated; " msg += ("pattern:\n%s\netc..." % basicPatterns[0]) raise SPARQLError(msg) if isinstance(query.query, AskQuery): return result.ask() elif isinstance(query.query, SelectQuery): orderBy = None orderAsc = None if query.query.solutionModifier.orderClause: orderBy = [] orderAsc = [] for orderCond in query.query.solutionModifier.orderClause: # is it a variable? if isinstance(orderCond, Variable): orderBy.append(orderCond) orderAsc.append(ASCENDING_ORDER) # is it another expression, only variables are supported else: expr = orderCond.expression assert isinstance( expr, Variable ), "Support for ORDER BY with anything other than a variable is not supported: %s" % expr orderBy.append(expr) orderAsc.append(orderCond.order == ASCENDING_ORDER) limit = query.query.solutionModifier.limitClause and int( query.query.solutionModifier.limitClause) or None offset = query.query.solutionModifier.offsetClause and int( query.query.solutionModifier.offsetClause) or 0 return result.select(query.query.variables, query.query.distinct, limit, orderBy, orderAsc, offset), _variablesToArray( query.query.variables, "selection"), result._getAllVariables( ), orderBy, query.query.distinct else: raise NotImplemented(CONSTRUCT_NOT_SUPPORTED, repr(query))
def setUp(self): self.graph1 = Graph(identifier=URIRef('http://example.org/foaf/aliceFoaf')) self.graph1.parse(StringIO(test_graph_a), format="n3") self.graph2 = Graph(identifier=URIRef('http://example.org/foaf/bobFoaf')) self.graph2.parse(StringIO(test_graph_b), format="n3") self.unionGraph = ReadOnlyGraphAggregate(graphs=[self.graph1,self.graph2])
def _getDataList(thing): return grrmBasisSetFilter(*grrmCanostFilter(*grrmTypeFilter( *grrmMoleculeInfoFilter(thing, [Data()])))) options = Options(sys.argv) submission_graph = Graph(graphstore.store(), identifier=rdflib.URIRef("urn:uuid:" + options.submission_uuid)) sys_uuid = _get_system_uuid(graphstore.store(), options.submission_uuid) sys_graph = Graph(graphstore.store(), identifier=rdflib.URIRef("urn:uuid:" + sys_uuid)) graph = ReadOnlyGraphAggregate([submission_graph, sys_graph]) try: indexer = indexing.DbIndex() indexer.addIndex("is_grrm__molecule", "BOOLEAN") indexer.addIndex("is_grrm__equilibrium_structure", "BOOLEAN") indexer.addIndex("is_grrm__transition_state", "BOOLEAN") indexer.addIndex("is_grrm__barrierless_dissociated", "BOOLEAN") indexer.addIndex("is_grrm__barrier_dissociated", "BOOLEAN") indexer.addIndex("is_grrm__interconversion_step", "BOOLEAN") indexer.addIndex("is_grrm__interconversion", "BOOLEAN") indexer.addIndex("is_grrm__run", "BOOLEAN") indexer.addIndex("grrm__energy", "FLOAT") indexer.addIndex("grrm__mass", "FLOAT") indexer.addIndex("grrm__basis_set", "VARCHAR(32)") indexer.addIndex("grrm__carbons", "INTEGER")