aboutsummaryrefslogtreecommitdiff
path: root/gn3/db/rdf.py
blob: 1d714c185c917cbdc14ed50c2cd343db0f9898df (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
"""RDF utilities

This module is a collection of functions that handle SPARQL queries.

"""
from typing import Tuple
from string import Template
from urllib.parse import unquote
from urllib.parse import urlparse

from SPARQLWrapper import JSON, SPARQLWrapper

from gn3.monads import MonadicDict

PREFIXES = {
    "dcat": "http://www.w3.org/ns/dcat#",
    "dct": "http://purl.org/dc/terms/",
    "ex": "http://example.org/stuff/1.0/",
    "fabio": "http://purl.org/spar/fabio/",
    "foaf": "http://xmlns.com/foaf/0.1/",
    "generif": "http://www.ncbi.nlm.nih.gov/gene?cmd=Retrieve&dopt=Graphics&list_uids=",
    "genotype": "http://genenetwork.org/genotype/",
    "gn": "http://genenetwork.org/id/",
    "gnc": "http://genenetwork.org/category/",
    "gnt": "http://genenetwork.org/term/",
    "owl": "http://www.w3.org/2002/07/owl#",
    "phenotype": "http://genenetwork.org/phenotype/",
    "prism": "http://prismstandard.org/namespaces/basic/2.0/",
    "publication": "http://genenetwork.org/publication/",
    "pubmed": "http://rdf.ncbi.nlm.nih.gov/pubmed/",
    "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
    "rdfs": "http://www.w3.org/2000/01/rdf-schema#",
    "skos": "http://www.w3.org/2004/02/skos/core#",
    "taxon": "https://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Info&id=",
    "up": "http://purl.uniprot.org/core/",
    "xkos": "http://rdf-vocabulary.ddialliance.org/xkos#",
    "xsd": "http://www.w3.org/2001/XMLSchema#",
}


RDF_PREFIXES = "\n".join([f"PREFIX {key}: <{value}>"for key, value in PREFIXES.items()])


def sparql_query(
        sparql_conn: SPARQLWrapper, query: str,
) -> Tuple[MonadicDict, ...]:
    """Run a SPARQL query and return the bound variables."""
    def __add_value_to_dict(key, value, my_dict):
        _values = set()
        if key in my_dict:
            if isinstance(my_dict[key], list):
                _values = set(my_dict[key])
            else:
                _values = set([my_dict[key]])
            _values.add(value)
        if _values:
            return list(_values)
        return value

    sparql_conn.setQuery(query)
    sparql_conn.setReturnFormat(JSON)
    parsed_response: dict = {}
    results = sparql_conn.queryAndConvert()["results"]["bindings"]  # type: ignore
    if results:
        for result in results:
            if "s" in result:  # A CONSTRUCT
                key = result["p"]["value"]  # type: ignore
                value = result["o"]["value"]  # type: ignore
                parsed_response[key] = __add_value_to_dict(
                    key, value, parsed_response
                )
            elif "key" in result:  # A SELECT
                parsed_response[
                    result["key"]  # type: ignore
                ] = __add_value_to_dict(
                    result["key"], result["value"],  # type: ignore
                    parsed_response
                )
    return (MonadicDict(parsed_response),)


def get_url_local_name(string: str) -> str:
    """Get the last item after a '/" from a URL"""
    if string.startswith("http"):
        url = urlparse(string)
        return unquote(url.path).rpartition("/")[-1]
    return string


def get_dataset_metadata(
        sparql_conn: SPARQLWrapper, name: str
) -> MonadicDict:
    """Return info about dataset with a given NAME"""
    response: MonadicDict = MonadicDict()
    for key, value in sparql_query(
            sparql_conn,
            Template("""
$prefix

CONSTRUCT {
	  ?dataset ?predicate ?term .
	  ?dataset gnt:classifiedUnder ?inbredSetName .
          ?dataset gnt:usesNormalization ?normalizationLabel .
          ?typePredicate ex:DatasetType ?typeName .
} WHERE {
	 ?dataset rdf:type dcat:Dataset .
	 ?dataset ?predicate ?term .
	 ?dataset xkos:classifiedUnder ?inbredSet .
	 gnc:Set skos:member ?inbredSet .
	 ?dataset (rdfs:label|dct:identifier) "$name" .
	 ?inbredSet rdfs:label ?inbredSetName .
         OPTIONAL {
            ?dataset xkos:classifiedUnder ?type .
            gnc:DatasetType skos:member ?type .
            ?type ?typePredicate ?typeName .
            ?type (skos:altLabel|skos:prefLabel) ?typeName .
         } .
         OPTIONAL {
            ?dataset gnt:usesNormalization ?normalization .
            ?normalization rdfs:label ?normalizationLabel .
         }
	 FILTER (!regex(str(?predicate), '(classifiedUnder|usesNormalization)','i')) .
}""")
            .substitute(
                prefix=RDF_PREFIXES,
                name=name
            )
    )[0].items():
        response[key] = value
    return response


def get_publication_metadata(
        sparql_conn: SPARQLWrapper, name: str
):
    """Return info about a publication with a given NAME"""
    __metadata_query = """
$prefix

CONSTRUCT {
    gn:publication ?publicationTerm ?publicationValue .
    gn:publication ?predicate ?subject .
} WHERE {
    $name ?publicationTerm ?publicationValue .
    ?publication ?publicationTerm ?publicationValue .
    OPTIONAL {
       ?subject ?predicate ?publication .
    } .
    VALUES ?publicationTerm {
        gn:pubMedId gn:title gn:volume
        gn:abstract gn:pages gn:month gn:year gn:author
    }
    VALUES ?predicate {
        gn:phenotypeOfPublication
    }
}
"""
    response: MonadicDict = MonadicDict()
    for key, value in sparql_query(
            sparql_conn,
            Template(__metadata_query)
            .substitute(
                prefix=RDF_PREFIXES,
                name=name
            )
    )[0].items():
        response[key] = value
        if isinstance(value, str) and not key.endswith("pubMedId"):
            response[key] = value.map(get_url_local_name)  # type: ignore
    return response


def get_phenotype_metadata(
        sparql_conn: SPARQLWrapper, name: str
):
    """Return info about a phenotype with a given NAME"""
    __metadata_query = """
$prefix

CONSTRUCT {
    ?phenotype ?pPredicate ?pValue .
    ?phenotype ?publicationTerm ?publicationValue .
    ?phenotype gn:speciesName ?speciesName .
    ?phenotype gn:inbredSetName ?inbredSetBinomialName .
    ?phenotype gn:datasetName ?datasetFullName .
} WHERE {
    ?phenotype ?pPredicate ?pValue .
    OPTIONAL {
        ?phenotype gn:phenotypeOfPublication ?publication .
        ?publication ?publicationTerm ?publicationValue .
    } .
    OPTIONAL {
        ?phenotype gn:phenotypeOfDataset ?dataset .
        ?dataset gn:name ?datasetFullName .
        ?dataset gn:datasetOfInbredSet ?inbredSet .
        ?inbredSet gn:binomialName ?inbredSetBinomialName .
        ?inbredSet gn:inbredSetOfSpecies ?species .
        ?species gn:displayName ?speciesName .
    } .
    FILTER( ?phenotype = phenotype:$name ) .
    MINUS {
         ?phenotype rdf:type ?pValue .
    }
    MINUS {
         ?publication rdf:type ?publicationValue .
    }
}
"""
    result: MonadicDict = MonadicDict()
    for key, value in sparql_query(
            sparql_conn,
            Template(__metadata_query)
            .substitute(name=name,
                        prefix=RDF_PREFIXES)
    )[0].items():
        result[key] = value
    return result