aboutsummaryrefslogtreecommitdiff
path: root/gn3/api/metadata.py
blob: 08a9418865b4b6be20f61561c46258971ca99c8f (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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
"""API for fetching metadata using an API"""
import json

from string import Template
from http.client import RemoteDisconnected
from urllib.error import URLError
from flask import Blueprint
from flask import jsonify
from flask import request
from flask import current_app

from pyld import jsonld
from SPARQLWrapper import JSON, JSONLD, SPARQLWrapper

from gn3.db.rdf import get_dataset_metadata
from gn3.db.rdf import get_phenotype_metadata
from gn3.db.rdf import get_genotype_metadata
from gn3.db.rdf import sparql_query
from gn3.db.rdf import RDF_PREFIXES, PREFIXES


metadata = Blueprint("metadata", __name__)


@metadata.route("/datasets/<name>", methods=["GET"])
def datasets(name):
    """Fetch a dataset's metadata given it's ACCESSION_ID or NAME"""
    try:
        sparql = SPARQLWrapper(current_app.config.get("SPARQL_ENDPOINT"))
        sparql.setQuery(Template("""
$prefix

CONSTRUCT {
	  ?dataset ?predicate ?term ;
                   rdf:type dcat:Dataset ;
	           ex:belongsToInbredSet ?inbredSetName ;
                   gnt:usesNormalization ?normalizationLabel ;
                   dcat:contactPoint ?investigatorName ;
                   xkos:classifiedUnder  ?altName ;
                   ex:platform ?platform ;
                   ex:tissue ?tissue .
          ?platform ?platformPred  ?platformObject ;
                    ex:info ?platformInfo .
          ?tissue rdfs:label ?tissueName ;
                  rdf:type gnc:tissue ;
                  ex:info ?tissueInfo .
} WHERE {
	 ?dataset rdf:type dcat:Dataset ;
	          xkos:classifiedUnder ?inbredSet ;
                  rdfs:label "$name" .
         OPTIONAL {
            ?inbredSet ^skos:member gnc:Set ;
                       rdfs:label ?inbredSetName .
         } .
         OPTIONAL {
            ?type ^xkos:classifiedUnder ?dataset ;
                  ^skos:member gnc:DatasetType ;
                  skos:prefLabel ?altName .
         } .
         OPTIONAL {
            ?normalization ^gnt:usesNormalization ?dataset ;
                           rdfs:label ?normalizationLabel .
         } .
         OPTIONAL {
           ?investigator foaf:name ?investigatorName ;
                         ^dcat:contactPoint ?dataset .
         } .
         OPTIONAL {
           ?platform ^gnt:usesPlatform ?dataset ;
                     ?platformPred  ?platformObject .
         } .
         OPTIONAL {
           ?dataset gnt:hasPlatformInfo ?platformInfo .
         } .
         OPTIONAL {
           ?dataset gnt:hasTissueInfo ?tissueInfo .
         } .
         OPTIONAL {
           ?dataset gnt:hasTissue ?tissue .
           ?tissue rdfs:label ?tissueName .
         } .
	 FILTER (!regex(str(?predicate), '(classifiedUnder|usesNormalization|contactPoint|hasPlatformInfo|tissueInfo)', 'i')) .
         FILTER (!regex(str(?platformPred), '(classifiedUnder|geoSeriesId|hasGoTreeValue)', 'i')) .
}""").substitute(prefix=RDF_PREFIXES, name=name))
        results = sparql.queryAndConvert()
        results = json.loads(
            results.serialize(format="json-ld")
        )
        frame = {
            "@context": PREFIXES | {
                "data": "@graph",
                "type": "@type",
                "id": "@id",
                "inbredSet": "ex:belongsToInbredSet",
                "description": "dct:description",
                "created":  "dct:created",
                "normalization": "gnt:usesNormalization",
                "classifiedUnder": "xkos:classifiedUnder",
                "accessRights": "dct:accessRights",
                "accessionId": "dct:identifier",
                "title": "dct:title",
                "label": "rdfs:label",
                "altLabel": "skos:altLabel",
                "prefLabel": "skos:prefLabel",
                "contactPoint": "dcat:contactPoint",
                "organization": "foaf:Organization",
                "info": "ex:info",
                "caseInfo": "gnt:hasCaseInfo",
                "geoSeriesId": "gnt:hasGeoSeriesId",
                "experimentDesignInfo": "gnt:hasExperimentDesignInfo",
                "notes": "gnt:hasNotes",
                "processingInfo": "gnt:hasDataProcessingInfo",
                "acknowledgement": "gnt:hasAcknowledgement",
                "tissue": "ex:tissue",
                "platform": "ex:platform",
            },
            "type": "dcat:Dataset",
        }
        return jsonld.compact(jsonld.frame(results, frame), frame)
    # The virtuoso server is misconfigured or it isn't running at all
    except (RemoteDisconnected, URLError):
        return jsonify({})


@metadata.route("/datasets/search/<term>", methods=["GET"])
def search_datasets(term):
    """Search datasets"""
    try:
        args = request.args
        page = args.get("page", 0)
        page_size = args.get("limit", 10)
        sparql = SPARQLWrapper(current_app.config.get("SPARQL_ENDPOINT"))
        sparql.setQuery(Template("""
$prefix

CONSTRUCT {
        ex:result rdf:type ex:resultType ;
                  ex:totalCount ?totalCount ;
                  ex:currentPage $offset ;
                  ex:items [
                    rdfs:label ?label ;
                    dct:title ?title ;
                    ex:belongsToInbredSet ?inbredSetName ;
                    xkos:classifiedUnder ?datasetType
          ]
} WHERE {
{
        SELECT ?dataset ?label ?inbredSetName ?datasetType ?title WHERE {
        ?dataset rdf:type dcat:Dataset ;
                 rdfs:label ?label ;
                 xkos:classifiedUnder ?inbredSet .
        ?inbredSet ^skos:member gnc:Set ;
                   rdfs:label ?inbredSetName .
        ?label bif:contains "'$term'" .
        OPTIONAL {
          ?dataset dct:title ?title .
        } .
        OPTIONAL {
          ?classification ^xkos:classifiedUnder ?dataset ;
                          ^skos:member gnc:DatasetType ;
                          ?typePredicate ?typeName ;
			  skos:prefLabel ?datasetType .
        }
    } ORDER BY ?dataset LIMIT $limit OFFSET $offset
}

{
        SELECT (COUNT(*)/$limit+1 AS ?totalCount) WHERE {
        ?dataset rdf:type dcat:Dataset ;
                 rdfs:label ?label .
        ?label bif:contains "'$term'" .
        }
}

}
""").substitute(prefix=RDF_PREFIXES, term=term, limit=page_size, offset=page))
        return jsonld.frame(
            json.loads(
                sparql.queryAndConvert().serialize(format="json-ld")),
            {
                "@context": PREFIXES | {
                    "data": "@graph",
                    "type": "@type",
                    "id": "@id",
                    "inbredSet": "ex:belongsToInbredSet",
                    "classifiedUnder": "xkos:classifiedUnder",
                    "dataset": "rdfs:label",
                    "title": "dct:title",
                    "currentPage": "ex:currentPage",
                    "result": "ex:result",
                    "results": "ex:items",
                    "resultItem": "ex:resultType",
                    "pages": "ex:totalCount"
                },
                "type": "resultItem",
            }
        )
    # The virtuoso server is misconfigured or it isn't running at all
    except (RemoteDisconnected, URLError):
        return jsonify({})


@metadata.route("/publications/<name>", methods=["GET"])
def publications(name):
    """Fetch a publication's metadata given it's ACCESSION_ID"""
    try:
        if "unpublished" in name:
            name = f"gn:unpublished{name}"
        else:
            name = f"pubmed:{name}"
        sparql = SPARQLWrapper(current_app.config.get("SPARQL_ENDPOINT"))
        sparql.setQuery(Template("""
$prefix

CONSTRUCT {
    $name ?predicate ?object .
} WHERE {
    $name rdf:type fabio:ResearchPaper ;
          ?predicate ?object .
    FILTER (!regex(str(?predicate), '(hasPubMedId)', 'i')) .
}
""").substitute(name=name, prefix=RDF_PREFIXES))
        return jsonld.compact(
            json.loads(sparql.queryAndConvert().serialize(format="json-ld")),
            {
                "@context": PREFIXES | {
                    "type": "@type",
                    "id": "@id",
                    "title": "dct:title",
                    "journal": "fabio:Journal",
                    "volume": "prism:volume",
                    "page": "fabio:page",
                    "creator": "dct:creator",
                    "abstract": "dct:abstract",
                    "year": {
                        "@id": "fabio:hasPublicationYear",
                        "@type": "xsd:gYear",
                    },
                    "month": {
                        "@id": "prism:publicationDate",
                        "@type": "xsd:gMonth"
                    },
                },
            })
    # The virtuoso server is misconfigured or it isn't running at all
    except (RemoteDisconnected, URLError):
        return jsonify({})


@metadata.route("/publications/search/<term>", methods=["GET"])
def search_publications(term):
    """Search publications"""
    try:
        args = request.args
        page = args.get("page", 0)
        page_size = args.get("limit", 10)
        sparql = SPARQLWrapper(current_app.config.get("SPARQL_ENDPOINT"))
        sparql.setQuery(Template("""
$prefix

CONSTRUCT {
        ex:result rdf:type ex:resultType ;
                  ex:totalCount ?totalCount ;
                  ex:currentPage $offset ;
                  ex:items [
                     rdfs:label ?publication ;
                     dct:title ?title ;
        ]
} WHERE {
{
        SELECT ?publication ?title ?pmid WHERE {
        ?pub rdf:type fabio:ResearchPaper ;
             ?predicate ?object ;
             dct:title ?title .
        ?object bif:contains "'$term'" .
        BIND( STR(?pub) AS ?publication ) .
        }  ORDER BY ?title LIMIT $limit OFFSET $offset
    }
{
        SELECT (COUNT(*)/$limit+1 AS ?totalCount) WHERE {
        ?publication rdf:type fabio:ResearchPaper ;
                     ?predicate ?object .
        ?object bif:contains "'$term'" .
        }
}
}
""").substitute(prefix=RDF_PREFIXES, term=term, limit=page_size, offset=page))
        results = sparql.queryAndConvert()
        results = json.loads(results.serialize(format="json-ld"))
        frame = {
            "@context": PREFIXES | {
                "data": "@graph",
                "type": "@type",
                "id": "@id",
                "title": "dct:title",
                "pubmed": "fabio:hasPubMedId",
                "currentPage": "ex:currentPage",
                "result": "ex:result",
                "results": "ex:items",
                "resultItem": "ex:resultType",
                "pages": "ex:totalCount",
                "url": "rdfs:label",
            },
            "type": "resultItem",
            "paper": {
                "@type": "fabio:ResearchPaper",
                "@container": "@index"
            }
        }
        return jsonld.frame(results, frame)
    except (RemoteDisconnected, URLError):
        return jsonify({})

@metadata.route("/phenotype/<name>", methods=["GET"])
def phenotype(name):
    """Fetch a phenotype's metadata given it's name"""
    try:
        return jsonify(
            get_phenotype_metadata(
                SPARQLWrapper(current_app.config.get("SPARQL_ENDPOINT")),
                name,
            ).data
        )
    # The virtuoso server is misconfigured or it isn't running at all
    except (RemoteDisconnected, URLError):
        return jsonify({})


@metadata.route("/genotype/<name>", methods=["GET"])
def genotype(name):
    """Fetch a genotype's metadata given it's name"""
    try:
        return jsonify(
            get_genotype_metadata(
                SPARQLWrapper(current_app.config.get("SPARQL_ENDPOINT")),
                name,
            ).data
        )
    # The virtuoso server is misconfigured or it isn't running at all
    except (RemoteDisconnected, URLError):
        return jsonify({})


@metadata.route("/genewiki/<symbol>", methods=["GET"])
def get_genewiki_entries(symbol):
    """Fetch the GN and NCBI GeneRIF entries"""
    try:
        gn_entries = sparql_query(
            sparql_conn=SPARQLWrapper(current_app.config.get("SPARQL_ENDPOINT")),
            query=Template("""
$rdf_prefixes

SELECT ?author ?geneCategory (STR(?gnEntry) AS ?entry)
       (STR(?createdOn) AS ?created)
       (GROUP_CONCAT(DISTINCT ?pmid; SEPARATOR=',') AS ?PubMedId)
       ?weburl
WHERE {
  ?generif gn:symbol ?symbol .
  ?generif gn:geneWikiEntryOfGn _:gnEntry .
  _:gnEntry gn:geneWikiEntry ?gnEntry;
            dct:creator ?author;
            dct:created ?createdOn .
  OPTIONAL { _:gnEntry gn:geneCategory ?geneCategory } .
  OPTIONAL { _:gnEntry foaf:homepage ?weburl } .
  OPTIONAL { _:gnEntry dct:source ?pmid} .
  OPTIONAL {
    ?generif gn:wikiEntryOfSpecies ?speciesName .
    ?species gn:name ?speciesName ;
             gn:binomialName ?speciesBinomialName .
  } .
  FILTER( lcase(?symbol) = '$symbol' )
} GROUP BY ?author ?createdOn ?gnEntry
           ?generif ?symbol ?weburl
	   ?geneCategory
ORDER BY ASC(?createdOn)""").substitute(rdf_prefixes=RDF_PREFIXES,
                                        symbol=str(symbol).lower()))
        ncbi_entries = sparql_query(
            sparql_conn=SPARQLWrapper(current_app.config.get("SPARQL_ENDPOINT")),
            query=Template("""
$rdf_prefixes

SELECT ?speciesBinomialName (STR(?gnEntry) AS ?entry)
       (STR(?createdOn) AS ?createdOn)
       (GROUP_CONCAT(DISTINCT REPLACE(STR(?pmid), pubmed:, ''); SEPARATOR=',') AS ?PubMedId)
       ?generif
WHERE {
  ?generif gn:symbol ?symbol .
  ?generif gn:geneWikiEntryOfNCBI [
    gn:geneWikiEntry ?gnEntry ;
    dct:created ?createdOn ;
    dct:source ?pmid
  ] .
  OPTIONAL {
    ?generif gn:wikiEntryOfSpecies ?speciesName .
    ?species gn:name ?speciesName ;
             gn:binomialName ?speciesBinomialName .
  } .
  FILTER( lcase(?symbol) = '$symbol' )
} GROUP BY ?createdOn ?gnEntry
           ?generif ?symbol
	   ?speciesBinomialName
ORDER BY ASC(?createdOn)""").substitute(rdf_prefixes=RDF_PREFIXES,
                                        symbol=str(symbol).lower()))
        return jsonify({
            "gn_entries": list(map(lambda x: x.data, gn_entries)),
            "ncbi_entries": list(map(lambda x: x.data, ncbi_entries)),
        })
    except (RemoteDisconnected, URLError):
        return jsonify({
            "gn_entries": {},
            "ncbi_entries": {},
        })