from SPARQLWrapper import SPARQLWrapper, JSON, XML

# Set SPARQL endpoint
endpoint = "http://sparql.wikipathways.org/"

sparql = SPARQLWrapper(endpoint)

# Set prefix
prefix = """
PREFIX wp:      <http://vocabularies.wikipathways.org/wp#>
PREFIX rdfs:    <http://www.w3.org/2000/01/rdf-schema#>
PREFIX dcterms: <http://purl.org/dc/terms/>
"""

# Query
query = """
DESCRIBE <http://identifiers.org/wikipathways/WP43_r84102>
"""

sparql.setQuery(prefix + query)
sparql.setReturnFormat("csv")

results = sparql.query().convert()

# print results
print(str(results))

"""
Explanation: Prise en main SPARQL
Exercice 1 : DESCRIBE
Lister les informations relatives à l'identifiant ENSG00000139618 (Ensembl).
End of explanation
"""


# Query
query = """
SELECT DISTINCT str(?label) as ?geneProduct
WHERE {
    ?geneProduct a wp:GeneProduct . 
    ?geneProduct rdfs:label ?label .

    FILTER regex(str(?label), "CYP"). 
}
"""

sparql.setQuery(prefix + query)
sparql.setReturnFormat(JSON)

results = sparql.query().convert()

# print results
for result in results["results"]["bindings"]:
    print result['geneProduct']['value']

"""
Explanation: Exercice 2 : SELECT AND FILTER 
Lister les gènes "CYP".
End of explanation
"""


# Query
query = """
SELECT DISTINCT ?pathway str(?label) as ?geneProduct
WHERE {
    ?geneProduct a wp:GeneProduct . 
    ?geneProduct rdfs:label ?label .
    ?geneProduct dcterms:isPartOf ?pathway .
    ?pathway a wp:Pathway .
    
    FILTER regex(str(?label), "CYP"). 
}
"""

sparql.setQuery(prefix + query)
sparql.setReturnFormat(JSON)

results = sparql.query().convert()

# print results
for result in results["results"]["bindings"]:
    print result['pathway']['value'] + "\t" + result['geneProduct']['value']

"""
Explanation: Exercice 3 
Lister les pathways qui ont le gène "CYP".
End of explanation
"""


query = """
SELECT DISTINCT ?pathway str(?label) as ?geneProduct ?idEG
WHERE {
    ?geneProduct a wp:GeneProduct . 
    OPTIONAL{?geneProduct wp:bdbEntrezGene ?idEG .}
    ?geneProduct rdfs:label ?label .
    ?geneProduct dcterms:isPartOf ?pathway .
    ?pathway a wp:Pathway .
    
    FILTER regex(str(?label), "CYP"). 
}
"""

sparql.setQuery(prefix + query)
sparql.setReturnFormat(JSON)

results = sparql.query().convert()

# print results
for result in results["results"]["bindings"]:
    if (typeOf(result['idEG']['value'] != undefined)) :
        print result['pathway']['value'] + "\t" + result['geneProduct']['value'] + "\t" + result['idEG']['value']

"""
Explanation: Exercice 4 : OPTIONAL
A partir de la requête précédente, lister les identifiants EntrezGene des gènes "CYP".
End of explanation
"""


