def test_17_query_nase(self): TST = Namespace('http://example.com/ns/') self.graph.add((TST.a, TST.b, TST.c)) self.graph.add((TST.d, TST.e, TST.f)) result = self.graph.query("SELECT * { ?s <b> ?o }", base=TST[""]) assert result.type == "SELECT", result.type assert len(result) == 1
def test_12_ask(self): TST = Namespace('http://example.com/ns/') self.graph.add((TST.a, TST.b, TST.c)) self.graph.add((TST.d, TST.e, TST.f)) result = self.graph.query("ASK { ?s ?p ?o }") assert result.type == "ASK", result.type assert result
def UnderagePassengerCount(graph, namespace): ns = Namespace(namespace) qry = "SELECT (COUNT(?s) as ?pCount) " \ " WHERE {?s pf:UnderagePassenger <http://ws_22208_65138.com/isUnderagePassenger> . } " results = graph.query(qry, initNs={'pf': ns}) return results
def threshold_txt(owl_graph, thresh_type, value, stat_type): # Namespaces and terms describing different thresholding approaches NIDM = Namespace("http://purl.org/nidash/nidm#") P_VALUE_UNC = NIDM["NIDM_0000160"] STATISTIC = OBO["STATO_0000039"] multiple_compa = "" is_p_value = True if thresh_type in [Q_VALUE_FDR, P_VALUE_FWER]: multiple_compa = "with correction for multiple \ comparisons " if thresh_type == Q_VALUE_FDR: thresh = "Q <= " else: thresh = "P <= " elif thresh_type == P_VALUE_UNC: thresh = "P <= " elif thresh_type == STATISTIC: is_p_value = False stat_abv = owl_graph.label(stat_type).replace("-statistic", "") thresh = stat_abv + " >= " thresh += "%0.2f" % float(value) if is_p_value: thresh += " (%s)" % (owl_graph.label(thresh_type).replace( " p-value", "")) return list([thresh, multiple_compa])
def DayTimeCount(graph, namespace): ns = Namespace(namespace) qry = "SELECT (COUNT(*) as ?pCount) " \ " WHERE {?s pf:DayTime ?daytime . } " results = graph.query(qry, initNs={'pf': ns}) return results
def test_11_empty_prefix(self): TST = Namespace('http://example.com/ns/') self.graph.add((TST.a, TST.b, TST.c)) self.graph.add((TST.d, TST.e, TST.f)) result = self.graph.query("""PREFIX : <http://example.com/ns/> SELECT * { ?s :b ?o }""") assert result.type == "SELECT", result.type assert len(result) == 1
def test_16_triple_pattern(self): TST = Namespace('http://example.com/ns/') self.graph.add((TST.a, TST.b, TST.c)) self.graph.add((TST.d, TST.e, TST.f)) for s, p, o in self.graph.triples((None, TST.b, None)): assert s == TST.a, repr(s) assert p == TST.b, repr(p) assert o == TST.c, repr(o)
def test_13_initNs(self): TST = Namespace('http://example.com/ns/') self.graph.add((TST.a, TST.b, TST.c)) self.graph.add((TST.d, TST.e, TST.f)) result = self.graph.query( "SELECT * { ?s tst:b ?o }", initNs={"tst": "http://example.com/ns/"}, )
def test_11_base(self): TST = Namespace('http://example.com/ns/') self.graph.add((TST.a, TST.b, TST.c)) self.graph.add((TST.d, TST.e, TST.f)) result = self.graph.query("""BASE <http://example.com/ns/> SELECT * { ?s <b> ?o }""") assert result.type == "SELECT", result.type assert len(result) == 1
def predicateCount(graph, namespace, predicate): ns = Namespace(namespace) qry = "SELECT (COUNT(pf:" + predicate + ") as ?pCount) " \ " WHERE {" \ "?s pf:" + predicate + " ?o ." \ " } " results = graph.query(qry, initNs={'pf': ns}) return results
def constructDayTime(graph, namespace): ns = Namespace(namespace) queryAfternoon = """ CONSTRUCT { ?roadaccident pf:DayTime <http://ws_22208_65138.com/DayTime/afternoon> } WHERE { ?roadaccident pf:happenedDuring <http://ws_22208_65138.com/AccTime/T13-17> . } """ queryMorning = """ CONSTRUCT { ?roadaccident pf:DayTime <http://ws_22208_65138.com/DayTime/morning> } WHERE { { ?roadaccident pf:happenedDuring <http://ws_22208_65138.com/AccTime/T07-09> . } UNION { ?roadaccident pf:happenedDuring <http://ws_22208_65138.com/AccTime/T09-13> . } UNION { ?roadaccident pf:happenedDuring <http://ws_22208_65138.com/AccTime/T24-07> . } } """ queryEvening = """ CONSTRUCT { ?roadaccident pf:DayTime <http://ws_22208_65138.com/DayTime/evening> } WHERE { { ?roadaccident pf:happenedDuring <http://ws_22208_65138.com/AccTime/T17-21> . } UNION { ?roadaccident pf:happenedDuring <http://ws_22208_65138.com/AccTime/T21-24> . } } """ result = graph.query(queryAfternoon, initNs={'pf': ns}) for triple in result: graph.add(triple) result = graph.query(queryMorning, initNs={'pf': ns}) for triple in result: graph.add(triple) result = graph.query(queryEvening, initNs={'pf': ns}) for triple in result: graph.add(triple)
def accidentsByType(graph, namespace, predicate, value): ns = Namespace(namespace) qry = 'SELECT ?acidente ' \ 'WHERE{ ' \ '?id pf:description "' + value +'". ' \ '?idAcidente pf:' +predicate + ' ?id . ' \ '?idAcidente pf:accidentID ?acidente . ' \ '}' results = graph.query(qry, initNs={'pf': ns}) return results
def listTypes(graph, namespace, type): ns = Namespace(namespace) qry = "SELECT ?Descricao ( Count (*) as ?count) " \ " WHERE {" \ " ?s pf:" + type + " ?Tipo . " \ " ?Tipo pf:description ?Descricao ." \ "}" \ "GROUP BY ?Descricao " \ "ORDER BY DESC (?count)" results = graph.query(qry, initNs={'pf': ns}) return results
def read_owl_file(filename): '''Returns the rdf object from eading an owl file.''' g = Graph() g.parse(filename) count = 0 bp = Namespace("http://www.biopax.org/release/biopax-level2.owl#") relations = list(g.subject_objects(bp["protein"])) for x, y in relations: count += 1 if count > 20: break print x, y
def test_15_prepared_qyery(self): from rdflib.plugins.sparql.processor import prepareQuery pquery = prepareQuery("SELECT * { ?s <b> tst:c }", {"tst": "http://example.com/ns/"}, "http://example.com/ns/") TST = Namespace('http://example.com/ns/') self.graph.add((TST.a, TST.b, TST.c)) self.graph.add((TST.d, TST.e, TST.f)) result = self.graph.query(pquery) assert result.type == "SELECT", result.type assert len(result) == 1
def accidentVictimAge(graph, namespace, accidentID): ns = Namespace(namespace) qry = 'SELECT ?vitima ?descIdade ' \ 'WHERE{ ' \ '?idAcidente pf:accidentID "' + accidentID + '"^^<http://www.w3.org/2001/XMLSchema#int>. ' \ '?idAcidente pf:hasVictim ?idVitima. ' \ '?idVitima pf:victimID ?vitima. ' \ '?idVitima pf:hasVictimAge ?idtipoIdade. ' \ '?idtipoIdade pf:description ?descIdade. ' \ '}' results = graph.query(qry, initNs={'pf': ns}) return results
def underageDriver(graph, namespace): ns = Namespace(namespace) qry = """ SELECT ?victimID WHERE{ ?accidentVictim pf:victimID ?victimID. ?accidentVictim pf:hasVictimAge <http://ws_22208_65138.com/VictimAge/Y0-17> . ?accidentVictim pf:hasVictimType <http://ws_22208_65138.com/VictimType/Driver> . } """ results = graph.query(qry, initNs={'pf': ns}) return results
def test_14_initBindings(self): TST = Namespace('http://example.com/ns/') self.graph.add((TST.a, TST.b, TST.c)) self.graph.add((TST.d, TST.e, TST.f)) result = self.graph.query( "SELECT * { ?s ?p ?o }", initBindings={ "p": TST.b, Variable("o"): TST.c, }, ) assert result.type == "SELECT", result.type assert len(result) == 1
def setUp(cls): cls.store = Virtuoso(rdflib_connection) cls.id1 = URIRef("http://example2.org/g1") cls.g1 = Graph(cls.store, identifier=cls.id1) cls.g1.remove((None, None, None)) cls.id2 = URIRef("http://example2.org/g2") cls.g2 = Graph(cls.store, identifier=cls.id2) cls.g2.remove((None, None, None)) cls.tst = TST = Namespace('http://example.com/ns/') cls.g1.add((TST.g0, RDF.type, TST.Graph)) cls.g1.add((TST.g1, RDF.type, TST.Graph)) cls.g2.add((TST.g0, RDF.type, TST.Graph)) cls.g2.add((TST.g2, RDF.type, TST.Graph))
def test_22_intertwined_queries(self): ex = Namespace('http://example.org/') for i in range(10): self.graph.add((ex.root, ex.p, ex['r%s' % i])) self.graph.add((ex['r%s' % i], ex.value, Literal(i))) bag = set() q1 = 'PREFIX ex: <http://example.org/>\n SELECT * { ex:root ex:p ?x }' q2 = 'PREFIX ex: <http://example.org/>\n SELECT * { ?x ex:value ?y }' for tpl1 in self.store.query(q1): x = tpl1[0] for tpl2 in self.store.query(q2, initBindings={'x': x}): bag.add(int(tpl2[1])) assert len(bag) == 10, len(bag) assert bag == set(range(10)), bag
def victimData(graph, namespace, victimID): ns = Namespace(namespace) qry = 'SELECT ?idVitima ?descIdade ?descVeiculo ?descVitima ?idAcidente ?objAcidente ' \ 'WHERE{ ' \ '?idVitima pf:victimID "' + victimID + '"^^<http://www.w3.org/2001/XMLSchema#int>. ' \ '?idVitima pf:hasVictimAge ?idtipoIdade. ' \ '?idtipoIdade pf:description ?descIdade. ' \ '?idVitima pf:inVehicle ?idtipoveiculo. ' \ '?idtipoveiculo pf:description ?descVeiculo. ' \ '?idVitima pf:hasVictimType ?idtipoVitima. ' \ '?idtipoVitima pf:description ?descVitima. ' \ '?idVitima pf:involvedIn ?idAcidente. ' \ '?idAcidente pf:accidentID ?objAcidente.'\ '}' results = graph.query(qry, initNs={'pf': ns}) return results
def constructUnderagePassenger(graph, namespace): ns = Namespace(namespace) results = graph.query("""CONSTRUCT { ?accidentvictim pf:UnderagePassenger <http://ws_22208_65138.com/isUnderagePassenger> } WHERE{ ?accidentvictim pf:hasVictimType <http://ws_22208_65138.com/VictimType/Passenger> . ?accidentvictim pf:hasVictimAge <http://ws_22208_65138.com/VictimAge/Y0-17> . } """, initNs={'pf': ns}) #.serialize(format="xml") #(rdflib.term.URIRef('http://ws_22208_65138.com/AccidentVictim/459'),) http://xmlns.com/gah/0.1/UnderagePassenger http://ws_22208_65138.com/isUnderagePassenger return results
def test_09_multiple_results(self): # This fails on virtuoso 7. # https://github.com/maparent/virtuoso-python/issues/2 # https://github.com/openlink/virtuoso-opensource/issues/127 TST = Namespace('http://example.com/ns/') self.graph.add((TST.A, RDFS.subClassOf, TST.B)) self.graph.add((TST.B, RDFS.subClassOf, TST.C)) self.graph.add((TST.C, RDFS.subClassOf, TST.D)) self.graph.add((TST.D, RDFS.subClassOf, TST.TOP)) result = self.graph.query("""SELECT DISTINCT ?class WHERE { ?class rdfs:subClassOf+ %s . %s rdfs:subClassOf+ ?class . }""" % (TST.TOP.n3(), TST.A.n3())) result = list(result) print(result) if not len(result): # This should be a xFail, but nosetests does not offer this. raise SkipTest
def accidentData(graph, namespace, accidentID): ns = Namespace(namespace) qry = 'SELECT ?idAcidente ?descVeiculo ?descCausa ?descHora ?descLocal (count (?idVitima) as ?nVitimas) ' \ 'WHERE{ ' \ '?idAcidente pf:accidentID "' + accidentID + '"^^<http://www.w3.org/2001/XMLSchema#int>. ' \ '?idAcidente pf:hasAccVehicle ?idtipoVeiculo. ' \ '?idtipoVeiculo pf:description ?descVeiculo. ' \ '?idAcidente pf:hasAccCause ?idCausa. ' \ '?idCausa pf:description ?descCausa. ' \ '?idAcidente pf:happenedDuring ?idHora. ' \ '?idHora pf:description ?descHora. ' \ '?idAcidente pf:happenedDuring ?idHora. ' \ '?idHora pf:description ?descHora. ' \ '?idAcidente pf:happenedInRoadNet ?idLocal. ' \ '?idLocal pf:description ?descLocal. ' \ '?idAcidente pf:hasVictim ?idVitima. ' \ '}' \ 'GROUP BY ?idAcidente ?descVeiculo ?descCausa ?descHora ?descLocal' results = graph.query(qry, initNs={'pf': ns}) return results
for s, p, o, graph in ConjunctiveGraph(store).quads((None, RDF.predicate, None)) ]) print(uniqueGraphNames) unionGraph = ReadOnlyGraphAggregate([g1, g2]) uniqueGraphNames = set([ graph.identifier for s, p, o, graph in unionGraph.quads((None, RDF.predicate, None)) ]) print(uniqueGraphNames) RDFLib = Namespace('http://rdflib.net/') RDFLib.gswewf #rdflib.term.URIRef('http://rdflib.net/gswewf') RDFLib['中文'] #rdflib.term.URIRef('http://rdflib.net/中文') rr = ResultRow({Variable('a'): URIRef('urn:cake')}, [Variable('a')]) rr[0] #rdflib.term.URIRef(u'urn:cake') rr #(rdflib.term.URIRef(u'urn:cake')) rr.a #rdflib.term.URIRef(u'urn:cake') rr[Variable('a')]
def DayTimeResult(graph, namespace): ns = Namespace(namespace) qry = "SELECT ?s ?daytime " \ " WHERE {?s pf:DayTime ?daytime . } " results = graph.query(qry, initNs={'pf': ns}) return results
def sparql(request): """Renders the about page.""" assert isinstance(request, HttpRequest) lista = {} output = [] form = checkclub() clubsList = m.sparql_listTeams() if 'sparql' in request.POST: team = request.POST['teams'] print(team) FB = Namespace("http://example.com/partida/") FB2 = Namespace("http://example.com/equipa/") FB3 = Namespace("http://example.com/data/") g = ConjunctiveGraph() g.parse("triplos.n3", format="n3") results = g.query(""" SELECT ?HomeTeam ?AwayTeam ?homeGols ?awayGols ?result ?gameDate WHERE{ { ?clubHomeId ns1:team '"""+team+"""'. ?gameId ns2:HomeTeam ?clubHomeId. ?gameId ns2:AwayTeam ?ClubAwayId. ?ClubAwayId ns1:team ?AwayTeam. ?gameId ns2:Date ?dateId. ?dateId ns3:date ?gameDate. ?gameId ns2:FTHG ?homeGols. ?gameId ns2:FTAG ?awayGols. ?gameId ns2:FTR ?result. } UNION { ?clubAwayId ns1:team '"""+team+"""'. ?gameId ns2:AwayTeam ?clubAwayId. ?gameId ns2:HomeTeam ?ClubHomeId. ?ClubHomeId ns1:team ?HomeTeam. ?gameId ns2:Date ?dateId. ?dateId ns3:date ?gameDate. ?gameId ns2:FTHG ?homeGols. ?gameId ns2:FTAG ?awayGols. ?gameId ns2:FTR ?result. } }""", \ initNs={'ns1': FB2,'ns2': FB, 'ns3':FB3}) for i in results: if i[0] is None: if str(i[4]) == 'H': aux = "Win" elif str(i[4]) == 'D': aux = "Draw" elif str(i[4]) == 'A': aux = "Defeat" valores = team + " - " + str(i[2]) + " : " + str( i[3]) + " - " + str(i[1]) + " - " + aux elif i[1] is None: if str(i[4]) == 'H': aux = "Defeat" elif str(i[4]) == 'D': aux = "Draw" elif str(i[4]) == 'A': aux = "Win" valores = str(i[0]) + " - " + str(i[2]) + " : " + str( i[3]) + " - " + team + " - " + aux dataString = str(i[5]).split("/") dataDone = dataString[0] + "-" + dataString[ 1] + "-" + "20" + dataString[2] ter = datetime.strptime(dataDone, '%d-%m-%Y') lista[ter] = valores new_d = OrderedDict(sorted(lista.items())) for u in new_d: key = str(u).split(" ") output.append(key[0] + " - " + lista[u]) return render( request, 'app/sparql.html', { 'title': 'Queries', 'clubsList': clubsList, 'clubeSelecionado': output, 'teamChoose': team, }) elif 'sparqlASK' in request.POST: insert = request.POST['name_field'] insert = insert.title() FB2 = Namespace("http://example.com/equipa/") g = ConjunctiveGraph() g.parse("triplos.n3", format="n3") results = g.query(""" ASK { ?film ns1:team '"""+insert+"""'. }""", \ initNs={'ns1': FB2}) for i in results: result = i return render( request, 'app/sparql.html', { 'title': 'Queries', 'clubsList': clubsList, 'clubeSelecionado': '', 'teamChoose': 'None', 'form': form, 'result': result, 'insert': insert, }) elif 'sparqlBets' in request.POST: list = {} finalList = {} FB = Namespace("http://example.com/partida/") FB2 = Namespace("http://example.com/equipa/") FB3 = Namespace("http://example.com/data/") g = ConjunctiveGraph() g.parse("triplos.n3", format="n3") results = g.query(""" SELECT ?partida ?team_name_a ?team_name_h ?B365H ?B365D ?B365A ?BWH ?BWD ?BWA WHERE{ ?ateam ns1:team ?team_name_a. ?hteam ns1:team ?team_name_h. ?partida ns2:HomeTeam ?hteam. ?partida ns2:AwayTeam ?ateam. ?partida ns2:B365A ?B365A. ?partida ns2:B365D ?B365D. ?partida ns2:B365H ?B365H. ?partida ns2:BWA ?BWA. ?partida ns2:BWD ?BWD. ?partida ns2:BWH ?BWH. }""", \ initNs={'ns1': FB2,'ns2': FB}) for i in results: values = [] partida = str(i[0]).split("/", 4) bet = m.biggest(i[3], i[4], i[5]) bw = m.biggest(i[6], i[7], i[8]) if bet == i[3]: winner = "Home Team" elif bet == i[4]: winner = "Draw" elif bet == i[5]: winner = "Away team" if bw == i[6]: winner2 = "Home Team" elif bw == i[7]: winner2 = "Draw" elif bw == i[8]: winner2 = "Away team" for j in i[1:]: values.append(j) values.append(winner) values.append(winner2) list[partida[4]] = values newList = m.natural_sort(list) for qq in newList: finalList[qq] = list[qq] #for o in finalList: # print(o + " => " + str(finalList[o])) return render( request, 'app/sparql.html', { 'title': 'Queries', 'clubsList': clubsList, 'clubeSelecionado': '', 'result': '', 'teamChoose': 'None', 'form': form, 'bets': finalList, }) else: return render( request, 'app/sparql.html', { 'title': 'Queries', 'clubsList': clubsList, 'clubeSelecionado': '', 'result': '', 'bets': '', 'teamChoose': 'None', 'form': form, })
import logging import zipfile from urllib2 import urlopen, URLError, HTTPError import tempfile from rdflib.graph import Graph, Namespace # Examples of NIDM-Results archives export_urls = [ 'https://docs.google.com/uc?id=0B5rWMFQteK5eMHVtVklCOHV6aGc&export=download' ] # NIDM-Results 1.0.0 owl file owl_file = "https://raw.githubusercontent.com/incf-nidash/nidm/master/nidm/\ nidm-results/terms/releases/nidm-results_110.owl" OBO = Namespace("http://purl.obolibrary.org/obo/") P_VALUE_FWER = OBO["OBI_0001265"] Q_VALUE_FDR = OBO["OBI_0001442"] logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) tmpdir = tempfile.mkdtemp() def threshold_txt(owl_graph, thresh_type, value, stat_type): # Namespaces and terms describing different thresholding approaches NIDM = Namespace("http://purl.org/nidash/nidm#") P_VALUE_UNC = NIDM["NIDM_0000160"] STATISTIC = OBO["STATO_0000039"] multiple_compa = ""
data_dir = os.path.join(SCRIPT_DIR, "data", "data_spm_fsl") pre_dir = os.path.join(SCRIPT_DIR, "pre") if not os.path.exists(pre_dir): os.makedirs(pre_dir) studies = next(os.walk(data_dir))[1] con_maps = dict() varcon_maps = dict() mask_maps = dict() ma_mask_name = os.path.join(pre_dir, "meta_analysis_mask") ma_mask = None NLX = Namespace("http://neurolex.org/wiki/") SPM_SOFTWARE = NLX["nif-0000-00343"] FSL_SOFTWARE = NLX["birnlex_2067"] # studies = studies[0:3] for study in studies: print "\nStudy: " + study nidm_dir = os.path.join(data_dir, study) assert os.path.isdir(nidm_dir) nidm_doc = os.path.join(nidm_dir, "nidm.ttl") nidm_graph = Graph() nidm_graph.parse(nidm_doc, format='turtle')
from codecs import getreader from StringIO import StringIO from pprint import pprint from rdflib.term import URIRef from rdflib.graph import Graph, Namespace #"/Users/jjc/Documents/Dissertation/Notes/1233HostageDeal/modelTesting/hostages8.n3" # rdf = open("/Users/jjc/Documents/Dissertation/Notes/1233HostageDeal/modelTesting/hostages8.n3", mode='r') # rdf_utf8 = rdf.encode('utf-8') # # rdf_reader = getreader('utf-8')(rdf.read()) # rdf_reader.encode('utf-8') xml = Namespace('http://www.w3.org/XML/1998/namespace') foaf = Namespace('http://xmlns.com/foaf/0.1/') snotes = Namespace('http://my.sourcenotes.org/2006/04/sourcenotes#') heml = Namespace('http://www.heml.org/schemas/2003-09-17/heml#') rdf = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#') rdfs = Namespace('http://www.w3.org/2000/01/rdf-schema#') dc = Namespace('http://purl.org/dc/elements/1.1/') dct = Namespace('http://purl.org/dc/terms/') rel = Namespace('http://www.perceive.net/schemas/20021119/relationship#') pome = Namespace('http://prosopOnto.medieval.england/2006/04/pome#') crm = Namespace('http://cidoc.ics.forth.gr/rdfs/cidoc_v4.2.rdfs#') me = Namespace( 'file:///Users/jjc/Documents/Dissertation/Notes/1233HostageDeal/modelTesting/1233Hostages.rdf#' ) g = Graph()